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 sage.schemes.generic.divisor import Divisor_generic, Divisor_curve from sage.structure.formal_sum import FormalSums from sage.structure.unique_representation import UniqueRepresentation from sage.rings.integer_ring import ZZ from sage.rings.rational_field import QQ def DivisorGroup(scheme, base_ring=None): r""" Return the group of divisors on the scheme. INPUT: - ``scheme`` -- a scheme. - ``base_ring`` -- usually either `\ZZ` (default) or `\QQ`. The coefficient ring of the divisors. Not to be confused with the base ring of the scheme! OUTPUT: An instance of ``DivisorGroup_generic``. EXAMPLES:: sage: from sage.schemes.generic.divisor_group import DivisorGroup sage: DivisorGroup(Spec(ZZ)) Group of ZZ-Divisors on Spectrum of Integer Ring sage: DivisorGroup(Spec(ZZ), base_ring=QQ) Group of QQ-Divisors on Spectrum of Integer Ring """ if base_ring is None: base_ring = ZZ from sage.schemes.curves.curve import Curve_generic if isinstance(scheme, Curve_generic): DG = DivisorGroup_curve(scheme, base_ring) else: DG = DivisorGroup_generic(scheme, base_ring) return DG def is_DivisorGroup(x): r""" Return whether ``x`` is a :class:`DivisorGroup_generic`. INPUT: - ``x`` -- anything. OUTPUT: ``True`` or ``False``. EXAMPLES:: sage: from sage.schemes.generic.divisor_group import is_DivisorGroup, DivisorGroup sage: Div = DivisorGroup(Spec(ZZ), base_ring=QQ) sage: is_DivisorGroup(Div) True sage: is_DivisorGroup('not a divisor') False """ return isinstance(x, DivisorGroup_generic) class DivisorGroup_generic(FormalSums): r""" The divisor group on a variety. """ @staticmethod def __classcall__(cls, scheme, base_ring=ZZ): """ Set the default value for the base ring. EXAMPLES:: sage: from sage.schemes.generic.divisor_group import DivisorGroup_generic sage: DivisorGroup_generic(Spec(ZZ),ZZ) == DivisorGroup_generic(Spec(ZZ)) # indirect test True """ # Must not call super().__classcall__()! return UniqueRepresentation.__classcall__(cls, scheme, base_ring) def __init__(self, scheme, base_ring): r""" Construct a :class:`DivisorGroup_generic`. INPUT: - ``scheme`` -- a scheme. - ``base_ring`` -- the coefficient ring of the divisor group. Implementation note: :meth:`__classcall__` sets default value for ``base_ring``. EXAMPLES:: sage: from sage.schemes.generic.divisor_group import DivisorGroup_generic sage: DivisorGroup_generic(Spec(ZZ), QQ) Group of QQ-Divisors on Spectrum of Integer Ring TESTS:: sage: from sage.schemes.generic.divisor_group import DivisorGroup sage: D1 = DivisorGroup(Spec(ZZ)) sage: D2 = DivisorGroup(Spec(ZZ), base_ring=QQ) sage: D3 = DivisorGroup(Spec(QQ)) sage: D1 == D1 True sage: D1 == D2 False sage: D1 != D3 True sage: D2 == D2 True sage: D2 == D3 False sage: D3 != D3 False sage: D1 == 'something' False """ super().__init__(base_ring) self._scheme = scheme def _repr_(self): r""" Return a string representation of the divisor group. EXAMPLES:: sage: from sage.schemes.generic.divisor_group import DivisorGroup sage: DivisorGroup(Spec(ZZ), base_ring=QQ) Group of QQ-Divisors on Spectrum of Integer Ring """ ring = self.base_ring() if ring == ZZ: base_ring_str = 'ZZ' elif ring == QQ: base_ring_str = 'QQ' else: base_ring_str = '('+str(ring)+')' return 'Group of '+base_ring_str+'-Divisors on '+str(self._scheme) def _element_constructor_(self, x, check=True, reduce=True): r""" Construct an element of the divisor group. EXAMPLES:: sage: from sage.schemes.generic.divisor_group import DivisorGroup sage: DivZZ=DivisorGroup(Spec(ZZ)) sage: DivZZ([(2,5)]) 2*V(5) """ if isinstance(x, Divisor_generic): P = x.parent() if P is self: return x elif P == self: return Divisor_generic(x._data, check=False, reduce=False, parent=self) else: x = x._data if isinstance(x, list): return Divisor_generic(x, check=check, reduce=reduce, parent=self) if x == 0: return Divisor_generic([], check=False, reduce=False, parent=self) else: return Divisor_generic([(self.base_ring()(1), x)], check=False, reduce=False, parent=self) def scheme(self): r""" Return the scheme supporting the divisors. EXAMPLES:: sage: from sage.schemes.generic.divisor_group import DivisorGroup sage: Div = DivisorGroup(Spec(ZZ)) # indirect test sage: Div.scheme() Spectrum of Integer Ring """ return self._scheme def _an_element_(self): r""" Return an element of the divisor group. EXAMPLES:: sage: A.<x, y> = AffineSpace(2, CC) sage: C = Curve(y^2 - x^9 - x) sage: from sage.schemes.generic.divisor_group import DivisorGroup sage: DivisorGroup(C).an_element() # indirect test 0 """ return self._scheme.divisor([], base_ring=self.base_ring(), check=False, reduce=False) def base_extend(self, R): """ EXAMPLES:: sage: from sage.schemes.generic.divisor_group import DivisorGroup sage: DivisorGroup(Spec(ZZ),ZZ).base_extend(QQ) Group of QQ-Divisors on Spectrum of Integer Ring sage: DivisorGroup(Spec(ZZ),ZZ).base_extend(GF(7)) Group of (Finite Field of size 7)-Divisors on Spectrum of Integer Ring Divisor groups are unique:: sage: A.<x, y> = AffineSpace(2, CC) sage: C = Curve(y^2 - x^9 - x) sage: DivisorGroup(C,ZZ).base_extend(QQ) is DivisorGroup(C,QQ) True """ if self.base_ring().has_coerce_map_from(R): return self elif R.has_coerce_map_from(self.base_ring()): return DivisorGroup(self.scheme(), base_ring=R) class DivisorGroup_curve(DivisorGroup_generic): r""" Special case of the group of divisors on a curve. """ def _element_constructor_(self, x, check=True, reduce=True): r""" Construct an element of the divisor group. EXAMPLES:: sage: A.<x, y> = AffineSpace(2, CC) sage: C = Curve(y^2 - x^9 - x) sage: DivZZ=C.divisor_group(ZZ) sage: DivQQ=C.divisor_group(QQ) sage: DivQQ( DivQQ.an_element() ) # indirect test 0 sage: DivZZ( DivZZ.an_element() ) # indirect test 0 sage: DivQQ( DivZZ.an_element() ) # indirect test 0 """ if isinstance(x, Divisor_curve): P = x.parent() if P is self: return x elif P == self: return Divisor_curve(x._data, check=False, reduce=False, parent=self) else: x = x._data if isinstance(x, list): return Divisor_curve(x, check=check, reduce=reduce, parent=self) if x == 0: return Divisor_curve([], check=False, reduce=False, parent=self) else: return Divisor_curve([(self.base_ring()(1), x)], check=False, reduce=False, parent=self)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/generic/divisor_group.py
0.946032
0.412412
divisor_group.py
pypi
from sage.schemes.projective.projective_space import is_ProjectiveSpace, ProjectiveSpace from sage.rings.polynomial.multi_polynomial_element import is_MPolynomial from .quartic_generic import QuarticCurve_generic def QuarticCurve(F, PP=None, check=False): """ Returns the quartic curve defined by the polynomial F. INPUT: - F -- a polynomial in three variables, homogeneous of degree 4 - PP -- a projective plane (default:None) - check -- whether to check for smoothness or not (default:False) EXAMPLES:: sage: x,y,z=PolynomialRing(QQ,['x','y','z']).gens() sage: QuarticCurve(x**4+y**4+z**4) Quartic Curve over Rational Field defined by x^4 + y^4 + z^4 TESTS:: sage: QuarticCurve(x**3+y**3) Traceback (most recent call last): ... ValueError: Argument F (=x^3 + y^3) must be a homogeneous polynomial of degree 4 sage: QuarticCurve(x**4+y**4+z**3) Traceback (most recent call last): ... ValueError: Argument F (=x^4 + y^4 + z^3) must be a homogeneous polynomial of degree 4 sage: x,y=PolynomialRing(QQ,['x','y']).gens() sage: QuarticCurve(x**4+y**4) Traceback (most recent call last): ... ValueError: Argument F (=x^4 + y^4) must be a polynomial in 3 variables """ if not is_MPolynomial(F): raise ValueError(f"Argument F (={F}) must be a multivariate polynomial") P = F.parent() if not P.ngens() == 3: raise ValueError("Argument F (=%s) must be a polynomial in 3 variables" % F) if not (F.is_homogeneous() and F.degree() == 4): raise ValueError("Argument F (=%s) must be a homogeneous polynomial of degree 4" % F) if PP is not None: if not is_ProjectiveSpace(PP) and PP.dimension == 2: raise ValueError(f"Argument PP (={PP}) must be a projective plane") else: PP = ProjectiveSpace(P) if check: raise NotImplementedError("Argument checking (for nonsingularity) is not implemented.") return QuarticCurve_generic(PP, F)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/plane_quartics/quartic_constructor.py
0.889673
0.500854
quartic_constructor.py
pypi
r""" Symplectic structures The class :class:`SymplecticForm` implements symplectic structures on differentiable manifolds over `\RR`. The derived class :class:`SymplecticFormParal` is devoted to symplectic forms on a parallelizable manifold. AUTHORS: - Tobias Diez (2021) : initial version REFERENCES: - [AM1990]_ - [RS2012]_ """ # ***************************************************************************** # Distributed under the terms of the GNU General Public License (GPL) # 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 __future__ import annotations from typing import Union, Optional from sage.symbolic.expression import Expression from sage.manifolds.differentiable.diff_form import DiffForm, DiffFormParal from sage.manifolds.differentiable.diff_map import DiffMap from sage.manifolds.differentiable.vectorfield_module import VectorFieldModule from sage.manifolds.differentiable.tensorfield import TensorField from sage.manifolds.differentiable.tensorfield_paral import TensorFieldParal from sage.manifolds.differentiable.manifold import DifferentiableManifold from sage.manifolds.differentiable.scalarfield import DiffScalarField from sage.manifolds.differentiable.vectorfield import VectorField from sage.manifolds.differentiable.poisson_tensor import PoissonTensorField class SymplecticForm(DiffForm): r""" A symplectic form on a differentiable manifold. An instance of this class is a closed nondegenerate differential `2`-form `\omega` on a differentiable manifold `M` over `\RR`. In particular, at each point `m \in M`, `\omega_m` is a bilinear map of the type: .. MATH:: \omega_m:\ T_m M \times T_m M \to \RR, where `T_m M` stands for the tangent space to the manifold `M` at the point `m`, such that `\omega_m` is skew-symmetric: `\forall u,v \in T_m M, \ \omega_m(v,u) = - \omega_m(u,v)` and nondegenerate: `(\forall v \in T_m M,\ \ \omega_m(u,v) = 0) \Longrightarrow u=0`. .. NOTE:: If `M` is parallelizable, the class :class:`SymplecticFormParal` should be used instead. INPUT: - ``manifold`` -- module `\mathfrak{X}(M)` of vector fields on the manifold `M`, or the manifold `M` itself - ``name`` -- (default: ``omega``) name given to the symplectic form - ``latex_name`` -- (default: ``None``) LaTeX symbol to denote the symplectic form; if ``None``, it is formed from ``name`` EXAMPLES: A symplectic form on the 2-sphere:: sage: M.<x,y> = manifolds.Sphere(2, coordinates='stereographic') sage: stereoN = M.stereographic_coordinates(pole='north') sage: stereoS = M.stereographic_coordinates(pole='south') sage: omega = M.symplectic_form(name='omega', latex_name=r'\omega') sage: omega Symplectic form omega on the 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3 ``omega`` is initialized by providing its single nonvanishing component w.r.t. the vector frame associated to ``stereoN``, which is the default frame on ``M``:: sage: omega[1, 2] = 1/(1 + x^2 + y^2)^2 The components w.r.t. the vector frame associated to ``stereoS`` are obtained thanks to the method :meth:`~sage.manifolds.differentiable.tensorfield.TensorField.add_comp_by_continuation`:: sage: omega.add_comp_by_continuation(stereoS.frame(), ....: stereoS.domain().intersection(stereoN.domain())) sage: omega.display() omega = (x^2 + y^2 + 1)^(-2) dx∧dy sage: omega.display(stereoS) omega = -1/(xp^4 + yp^4 + 2*(xp^2 + 1)*yp^2 + 2*xp^2 + 1) dxp∧dyp ``omega`` is an exact 2-form (this is trivial here, since ``M`` is 2-dimensional):: sage: diff(omega).display() domega = 0 """ _name: str _latex_name: str _dim_half: int _poisson: Optional[PoissonTensorField] _vol_form: Optional[DiffForm] _restrictions: dict[DifferentiableManifold, SymplecticForm] def __init__( self, manifold: Union[DifferentiableManifold, VectorFieldModule], name: Optional[str] = None, latex_name: Optional[str] = None, ): r""" Construct a symplectic form. TESTS:: sage: from sage.manifolds.differentiable.symplectic_form import SymplecticForm sage: M = manifolds.Sphere(2, coordinates='stereographic') sage: omega = SymplecticForm(M, name='omega', latex_name=r'\omega') sage: omega Symplectic form omega on the 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3 """ try: vector_field_module = manifold.vector_field_module() except AttributeError: vector_field_module = manifold if name is None: name = "omega" if latex_name is None: latex_name = r"\omega" if latex_name is None: latex_name = name DiffForm.__init__( self, vector_field_module, 2, name=name, latex_name=latex_name ) # Check that manifold is even dimensional dim = self._ambient_domain.dimension() if dim % 2 == 1: raise ValueError( f"the dimension of the manifold must be even but it is {dim}" ) self._dim_half = dim // 2 # Initialization of derived quantities SymplecticForm._init_derived(self) def _repr_(self): r""" String representation of the object. TESTS:: sage: M.<q, p> = EuclideanSpace(2) sage: omega = M.symplectic_form('omega', r'\omega'); omega Symplectic form omega on the Euclidean plane E^2 """ return self._final_repr(f"Symplectic form {self._name} ") def _new_instance(self): r""" Create an instance of the same class as ``self``. TESTS:: sage: M.<q, p> = EuclideanSpace(2) sage: omega = M.symplectic_form('omega', r'\omega')._new_instance(); omega Symplectic form unnamed symplectic form on the Euclidean plane E^2 """ return type(self)( self._vmodule, "unnamed symplectic form", latex_name=r"\mbox{unnamed symplectic form}", ) def _init_derived(self): r""" Initialize the derived quantities. TESTS:: sage: M.<q, p> = EuclideanSpace(2) sage: omega = M.symplectic_form('omega', r'\omega')._init_derived() """ # Initialization of quantities pertaining to the mother class DiffForm._init_derived(self) self._poisson = None self._vol_form = None def _del_derived(self): r""" Delete the derived quantities. TESTS:: sage: M.<q, p> = EuclideanSpace(2) sage: omega = M.symplectic_form('omega', r'\omega')._del_derived() """ # Delete the derived quantities from the mother class DiffForm._del_derived(self) # Clear the Poisson tensor if self._poisson is not None: self._poisson._restrictions.clear() self._poisson._del_derived() self._poisson = None # Delete the volume form if self._vol_form is not None: self._vol_form._restrictions.clear() self._vol_form._del_derived() self._vol_form = None def restrict( self, subdomain: DifferentiableManifold, dest_map: Optional[DiffMap] = None ) -> DiffForm: r""" Return the restriction of the symplectic form to some subdomain. If the restriction has not been defined yet, it is constructed here. INPUT: - ``subdomain`` -- open subset `U` of the symplectic form's domain - ``dest_map`` -- (default: ``None``) smooth destination map `\Phi:\ U \to V`, where `V` is a subdomain of the symplectic form's domain If None, the restriction of the initial vector field module is used. OUTPUT: - the restricted symplectic form. EXAMPLES:: sage: M = Manifold(6, 'M') sage: omega = M.symplectic_form() sage: U = M.open_subset('U') sage: omega.restrict(U) 2-form omega on the Open subset U of the 6-dimensional differentiable manifold M """ if subdomain == self._domain: return self if subdomain not in self._restrictions: # Construct the restriction at the tensor field level restriction = DiffForm.restrict(self, subdomain, dest_map=dest_map) # Restrictions of derived quantities if self._poisson is not None: restriction._poisson = self._poisson.restrict(subdomain) if self._vol_form is not None: restriction._vol_form = self._vol_form.restrict(subdomain) # The restriction is ready self._restrictions[subdomain] = restriction return restriction else: return self._restrictions[subdomain] @staticmethod def wrap( form: DiffForm, name: Optional[str] = None, latex_name: Optional[str] = None ) -> SymplecticForm: r""" Define the symplectic form from a differential form. INPUT: - ``form`` -- differential `2`-form EXAMPLES: Volume form on the sphere as a symplectic form:: sage: from sage.manifolds.differentiable.symplectic_form import SymplecticForm sage: M = manifolds.Sphere(2, coordinates='stereographic') sage: vol_form = M.induced_metric().volume_form() sage: omega = SymplecticForm.wrap(vol_form, 'omega', r'\omega') sage: omega.display() omega = -4/(y1^4 + y2^4 + 2*(y1^2 + 1)*y2^2 + 2*y1^2 + 1) dy1∧dy2 """ if form.degree() != 2: raise TypeError("the argument must be a form of degree 2") if name is None: name = form._name if latex_name is None: latex_name = form._latex_name symplectic_form = form.base_module().symplectic_form(name, latex_name) for dom, rst in form._restrictions.items(): symplectic_form._restrictions[dom] = SymplecticForm.wrap( rst, name, latex_name ) if isinstance(form, DiffFormParal): for frame in form._components: symplectic_form._components[frame] = form._components[frame].copy() return symplectic_form def poisson( self, expansion_symbol: Optional[Expression] = None, order: int = 1 ) -> PoissonTensorField: r""" Return the Poisson tensor associated with the symplectic form. INPUT: - ``expansion_symbol`` -- (default: ``None``) symbolic variable; if specified, the inverse will be expanded in power series with respect to this variable (around its zero value) - ``order`` -- integer (default: 1); the order of the expansion if ``expansion_symbol`` is not ``None``; the *order* is defined as the degree of the polynomial representing the truncated power series in ``expansion_symbol``; currently only first order inverse is supported If ``expansion_symbol`` is set, then the zeroth order symplectic form must be invertible. Moreover, subsequent calls to this method will return a cached value, even when called with the default value (to enable computation of derived quantities). To reset, use :meth:`_del_derived`. OUTPUT: - the Poisson tensor, as an instance of :meth:`~sage.manifolds.differentiable.poisson_tensor.PoissonTensorField` EXAMPLES: Poisson tensor of `2`-dimensional symplectic vector space:: sage: M = manifolds.StandardSymplecticSpace(2) sage: omega = M.symplectic_form() sage: poisson = omega.poisson(); poisson 2-vector field poisson_omega on the Standard symplectic space R2 sage: poisson.display() poisson_omega = -e_q∧e_p """ if self._poisson is None: # Initialize the Poisson tensor poisson_name = f"poisson_{self._name}" poisson_latex_name = f"{self._latex_name}^{{-1}}" self._poisson = self._vmodule.poisson_tensor( poisson_name, poisson_latex_name ) # Update the Poisson tensor # TODO: Should this be done instead when a new restriction is added? for domain, restriction in self._restrictions.items(): # Forces the update of the restriction self._poisson._restrictions[domain] = restriction.poisson( expansion_symbol=expansion_symbol, order=order ) return self._poisson def hamiltonian_vector_field(self, function: DiffScalarField) -> VectorField: r""" The Hamiltonian vector field `X_f` generated by a function `f: M \to \RR`. The Hamiltonian vector field is defined by .. MATH:: X_f \lrcorner \omega + df = 0. INPUT: - ``function`` -- the function generating the Hamiltonian vector field EXAMPLES:: sage: M = manifolds.StandardSymplecticSpace(2) sage: omega = M.symplectic_form() sage: f = M.scalar_field({ chart: function('f')(*chart[:]) for chart in M.atlas() }, name='f') sage: f.display() f: R2 → ℝ (q, p) ↦ f(q, p) sage: Xf = omega.hamiltonian_vector_field(f) sage: Xf.display() Xf = d(f)/dp e_q - d(f)/dq e_p """ return self.poisson().hamiltonian_vector_field(function) def flat(self, vector_field: VectorField) -> DiffForm: r""" Return the image of the given differential form under the map `\omega^\flat: T M \to T^*M` defined by .. MATH:: <\omega^\flat(X), Y> = \omega_m (X, Y) for all `X, Y \in T_m M`. In indices, `X_i = \omega_{ji} X^j`. INPUT: - ``vector_field`` -- the vector field to calculate its flat of EXAMPLES:: sage: M = manifolds.StandardSymplecticSpace(2) sage: omega = M.symplectic_form() sage: X = M.vector_field_module().an_element() sage: X.set_name('X') sage: X.display() X = 2 e_q + 2 e_p sage: omega.flat(X).display() X_flat = 2 dq - 2 dp """ form = vector_field.down(self) form.set_name( vector_field._name + "_flat", vector_field._latex_name + "^\\flat" ) return form def sharp(self, form: DiffForm) -> VectorField: r""" Return the image of the given differential form under the map `\omega^\sharp: T^* M \to TM` defined by .. MATH:: \omega (\omega^\sharp(\alpha), X) = \alpha(X) for all `X \in T_m M` and `\alpha \in T^*_m M`. The sharp map is inverse to the flat map. In indices, `\alpha^i = \varpi^{ij} \alpha_j`, where `\varpi` is the Poisson tensor associated with the symplectic form. INPUT: - ``form`` -- the differential form to calculate its sharp of EXAMPLES:: sage: M = manifolds.StandardSymplecticSpace(2) sage: omega = M.symplectic_form() sage: X = M.vector_field_module().an_element() sage: alpha = omega.flat(X) sage: alpha.set_name('alpha') sage: alpha.display() alpha = 2 dq - 2 dp sage: omega.sharp(alpha).display() alpha_sharp = 2 e_q + 2 e_p """ return self.poisson().sharp(form) def poisson_bracket( self, f: DiffScalarField, g: DiffScalarField ) -> DiffScalarField: r""" Return the Poisson bracket .. MATH:: \{f, g\} = \omega(X_f, X_g) of the given functions. INPUT: - ``f`` -- function inserted in the first slot - ``g`` -- function inserted in the second slot EXAMPLES:: sage: M.<q, p> = EuclideanSpace(2) sage: poisson = M.poisson_tensor('varpi') sage: poisson.set_comp()[1,2] = -1 sage: f = M.scalar_field({ chart: function('f')(*chart[:]) for chart in M.atlas() }, name='f') sage: g = M.scalar_field({ chart: function('g')(*chart[:]) for chart in M.atlas() }, name='g') sage: poisson.poisson_bracket(f, g).display() poisson(f, g): E^2 → ℝ (q, p) ↦ d(f)/dp*d(g)/dq - d(f)/dq*d(g)/dp """ return self.poisson().poisson_bracket(f, g) def volume_form(self, contra: int = 0) -> TensorField: r""" Liouville volume form `\frac{1}{n!}\omega^n` associated with the symplectic form `\omega`, where `2n` is the dimension of the manifold. INPUT: - ``contra`` -- (default: 0) number of contravariant indices of the returned tensor OUTPUT: - if ``contra = 0``: volume form associated with the symplectic form - if ``contra = k``, with `1\leq k \leq n`, the tensor field of type (k,n-k) formed from `\epsilon` by raising the first k indices with the symplectic form (see method :meth:`~sage.manifolds.differentiable.tensorfield.TensorField.up`) EXAMPLES: Volume form on `\RR^4`:: sage: M = manifolds.StandardSymplecticSpace(4) sage: omega = M.symplectic_form() sage: vol = omega.volume_form() ; vol 4-form mu_omega on the Standard symplectic space R4 sage: vol.display() mu_omega = dq1∧dp1∧dq2∧dp2 """ if self._vol_form is None: from sage.functions.other import factorial vol_form = self for _ in range(1, self._dim_half): vol_form = vol_form.wedge(self) vol_form = vol_form / factorial(self._dim_half) volume_name = f"mu_{self._name}" volume_latex_name = f"\\mu_{self._latex_name}" vol_form.set_name(volume_name, volume_latex_name) self._vol_form = vol_form result = self._vol_form for k in range(0, contra): result = result.up(self, k) if contra > 1: # restoring the antisymmetry after the up operation: result = result.antisymmetrize(*range(contra)) return result def hodge_star(self, pform: DiffForm) -> DiffForm: r""" Compute the Hodge dual of a differential form with respect to the symplectic form. See :meth:`~sage.manifolds.differentiable.diff_form.DiffForm.hodge_dual` for the definition and more details. INPUT: - ``pform``: a `p`-form `A`; must be an instance of :class:`~sage.manifolds.differentiable.scalarfield.DiffScalarField` for `p=0` and of :class:`~sage.manifolds.differentiable.diff_form.DiffForm` or :class:`~sage.manifolds.differentiable.diff_form.DiffFormParal` for `p\geq 1`. OUTPUT: - the `(n-p)`-form `*A` EXAMPLES: Hodge dual of any form on the symplectic vector space `R^2`:: sage: M = manifolds.StandardSymplecticSpace(2) sage: omega = M.symplectic_form() sage: a = M.one_form(1, 0, name='a') sage: omega.hodge_star(a).display() *a = -dq sage: b = M.one_form(0, 1, name='b') sage: omega.hodge_star(b).display() *b = -dp sage: f = M.scalar_field(1, name='f') sage: omega.hodge_star(f).display() *f = -dq∧dp sage: omega.hodge_star(omega).display() *omega: R2 → ℝ (q, p) ↦ 1 """ return pform.hodge_dual(self) class SymplecticFormParal(SymplecticForm, DiffFormParal): r""" A symplectic form on a parallelizable manifold. .. NOTE:: If `M` is not parallelizable, the class :class:`SymplecticForm` should be used instead. INPUT: - ``manifold`` -- module `\mathfrak{X}(M)` of vector fields on the manifold `M`, or the manifold `M` itself - ``name`` -- (default: ``omega``) name given to the symplectic form - ``latex_name`` -- (default: ``None``) LaTeX symbol to denote the symplectic form; if ``None``, it is formed from ``name`` EXAMPLES: Standard symplectic form on `\RR^2`:: sage: M.<q, p> = EuclideanSpace(name="R2", latex_name=r"\mathbb{R}^2") sage: omega = M.symplectic_form(name='omega', latex_name=r'\omega') sage: omega Symplectic form omega on the Euclidean plane R2 sage: omega.set_comp()[1,2] = -1 sage: omega.display() omega = -dq∧dp """ _poisson: TensorFieldParal def __init__( self, manifold: Union[VectorFieldModule, DifferentiableManifold], name: Optional[str], latex_name: Optional[str] = None, ): r""" Construct a symplectic form. TESTS:: sage: from sage.manifolds.differentiable.symplectic_form import SymplecticFormParal sage: M = EuclideanSpace(2) sage: omega = SymplecticFormParal(M, name='omega', latex_name=r'\omega') sage: omega Symplectic form omega on the Euclidean plane E^2 """ try: vector_field_module = manifold.vector_field_module() except AttributeError: vector_field_module = manifold if name is None: name = "omega" DiffFormParal.__init__( self, vector_field_module, 2, name=name, latex_name=latex_name ) # Check that manifold is even dimensional dim = self._ambient_domain.dimension() if dim % 2 == 1: raise ValueError( f"the dimension of the manifold must be even but it is {dim}" ) self._dim_half = dim // 2 # Initialization of derived quantities SymplecticFormParal._init_derived(self) def _init_derived(self): r""" Initialize the derived quantities. TESTS:: sage: from sage.manifolds.differentiable.symplectic_form import SymplecticFormParal sage: M = EuclideanSpace(2) sage: omega = SymplecticFormParal(M, 'omega', r'\omega') sage: omega._init_derived() """ # Initialization of quantities pertaining to mother classes DiffFormParal._init_derived(self) SymplecticForm._init_derived(self) def _del_derived(self, del_restrictions: bool = True): r""" Delete the derived quantities. INPUT: - ``del_restrictions`` -- (default: True) determines whether the restrictions of ``self`` to subdomains are deleted. TESTS:: sage: from sage.manifolds.differentiable.symplectic_form import SymplecticFormParal sage: M.<q, p> = EuclideanSpace(2, "R2", r"\mathbb{R}^2", symbols=r"q:q p:p") sage: omega = SymplecticFormParal(M, 'omega', r'\omega') sage: omega._del_derived(del_restrictions=False) sage: omega._del_derived() """ # Delete derived quantities from mother classes DiffFormParal._del_derived(self, del_restrictions=del_restrictions) # Clear the Poisson tensor if self._poisson is not None: self._poisson._components.clear() self._poisson._del_derived() SymplecticForm._del_derived(self) def restrict( self, subdomain: DifferentiableManifold, dest_map: Optional[DiffMap] = None ) -> SymplecticFormParal: r""" Return the restriction of the symplectic form to some subdomain. If the restriction has not been defined yet, it is constructed here. INPUT: - ``subdomain`` -- open subset `U` of the symplectic form's domain - ``dest_map`` -- (default: ``None``) smooth destination map `\Phi:\ U \rightarrow V`, where `V` is a subdomain of the symplectic form's domain If None, the restriction of the initial vector field module is used. OUTPUT: - the restricted symplectic form. EXAMPLES: Restriction of the standard symplectic form on `\RR^2` to the upper half plane:: sage: from sage.manifolds.differentiable.symplectic_form import SymplecticFormParal sage: M = EuclideanSpace(2, "R2", r"\mathbb{R}^2", symbols=r"q:q p:p") sage: X.<q, p> = M.chart() sage: omega = SymplecticFormParal(M, 'omega', r'\omega') sage: omega[1,2] = -1 sage: U = M.open_subset('U', coord_def={X: q>0}) sage: omegaU = omega.restrict(U); omegaU Symplectic form omega on the Open subset U of the Euclidean plane R2 sage: omegaU.display() omega = -dq∧dp """ if subdomain == self._domain: return self if subdomain not in self._restrictions: # Construct the restriction at the tensor field level: resu = DiffFormParal.restrict(self, subdomain, dest_map=dest_map) self._restrictions[subdomain] = SymplecticFormParal.wrap(resu) return self._restrictions[subdomain] def poisson( self, expansion_symbol: Optional[Expression] = None, order: int = 1 ) -> TensorFieldParal: r""" Return the Poisson tensor associated with the symplectic form. INPUT: - ``expansion_symbol`` -- (default: ``None``) symbolic variable; if specified, the inverse will be expanded in power series with respect to this variable (around its zero value) - ``order`` -- integer (default: 1); the order of the expansion if ``expansion_symbol`` is not ``None``; the *order* is defined as the degree of the polynomial representing the truncated power series in ``expansion_symbol``; currently only first order inverse is supported If ``expansion_symbol`` is set, then the zeroth order symplectic form must be invertible. Moreover, subsequent calls to this method will return a cached value, even when called with the default value (to enable computation of derived quantities). To reset, use :meth:`_del_derived`. OUTPUT: - the Poisson tensor, , as an instance of :meth:`~sage.manifolds.differentiable.poisson_tensor.PoissonTensorFieldParal` EXAMPLES: Poisson tensor of `2`-dimensional symplectic vector space:: sage: from sage.manifolds.differentiable.symplectic_form import SymplecticFormParal sage: M.<q, p> = EuclideanSpace(2, "R2", r"\mathbb{R}^2", symbols=r"q:q p:p") sage: omega = SymplecticFormParal(M, 'omega', r'\omega') sage: omega[1,2] = -1 sage: poisson = omega.poisson(); poisson 2-vector field poisson_omega on the Euclidean plane R2 sage: poisson.display() poisson_omega = -e_q∧e_p """ super().poisson() if expansion_symbol is not None: if ( self._poisson is not None and bool(self._poisson._components) and list(self._poisson._components.values())[0][0, 0]._expansion_symbol == expansion_symbol and list(self._poisson._components.values())[0][0, 0]._order == order ): return self._poisson if order != 1: raise NotImplementedError("only first order inverse is implemented") decompo = self.series_expansion(expansion_symbol, order) g0 = decompo[0] g1 = decompo[1] g0m = self._new_instance() # needed because only metrics have g0m.set_comp()[:] = g0[:] # an "inverse" method. contraction = g1.contract(0, g0m.inverse(), 0) contraction = contraction.contract(1, g0m.inverse(), 1) self._poisson = -(g0m.inverse() - expansion_symbol * contraction) self._poisson.set_calc_order(expansion_symbol, order) return self._poisson from sage.matrix.constructor import matrix from sage.tensor.modules.comp import CompFullyAntiSym # Is the inverse metric up to date ? for frame in self._components: if frame not in self._poisson._components: # the computation is necessary fmodule = self._fmodule si = fmodule._sindex nsi = fmodule.rank() + si dom = self._domain comp_poisson = CompFullyAntiSym( fmodule._ring, frame, 2, start_index=si, output_formatter=fmodule._output_formatter, ) comp_poisson_scal = ( {} ) # dict. of scalars representing the components of the poisson tensor (keys: comp. indices) for i in fmodule.irange(): for j in range(i, nsi): # symmetry taken into account comp_poisson_scal[(i, j)] = dom.scalar_field() for chart in dom.top_charts(): # TODO: do the computation without the 'SR' enforcement try: self_matrix = matrix( [ [ self.comp(frame)[i, j, chart].expr(method="SR") for j in fmodule.irange() ] for i in fmodule.irange() ] ) self_matrix_inv = self_matrix.inverse() except (KeyError, ValueError): continue for i in fmodule.irange(): for j in range(i, nsi): val = chart.simplify( -self_matrix_inv[i - si, j - si], method="SR" ) comp_poisson_scal[(i, j)].add_expr(val, chart=chart) for i in range(si, nsi): for j in range(i, nsi): comp_poisson[i, j] = comp_poisson_scal[(i, j)] self._poisson._components[frame] = comp_poisson return self._poisson # ****************************************************************************************
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/manifolds/differentiable/symplectic_form.py
0.962953
0.640594
symplectic_form.py
pypi
r""" Spheres smoothly embedded in Euclidean Space Let `E^{n+1}` be a Euclidean space of dimension `n+1` and `c \in E^{n+1}`. An `n`-sphere with radius `r` and centered at `c`, usually denoted by `\mathbb{S}^n_r(c)`, smoothly embedded in the Euclidean space `E^{n+1}` is an `n`-dimensional smooth manifold together with a smooth embedding .. MATH:: \iota \colon \mathbb{S}^n_r \to E^{n+1} whose image consists of all points having the same Euclidean distance to the fixed point `c`. If we choose Cartesian coordinates `(x_1, \ldots, x_{n+1})` on `E^{n+1}` with `x(c)=0` then the above translates to .. MATH:: \iota(\mathbb{S}^n_r(c)) = \left\{ p \in E^{n+1} : \lVert x(p) \rVert = r \right\}. This corresponds to the standard `n`-sphere of radius `r` centered at `c`. AUTHORS: - Michael Jung (2020): initial version REFERENCES: - \M. Berger: *Geometry I&II* [Ber1987]_, [Ber1987a]_ - \J. Lee: *Introduction to Smooth Manifolds* [Lee2013]_ EXAMPLES: We start by defining a 2-sphere of unspecified radius `r`:: sage: r = var('r') sage: S2_r = manifolds.Sphere(2, radius=r); S2_r 2-sphere S^2_r of radius r smoothly embedded in the Euclidean space E^3 The embedding `\iota` is constructed from scratch and can be returned by the following command:: sage: i = S2_r.embedding(); i Differentiable map iota from the 2-sphere S^2_r of radius r smoothly embedded in the Euclidean space E^3 to the Euclidean space E^3 sage: i.display() iota: S^2_r → E^3 on A: (theta, phi) ↦ (x, y, z) = (r*cos(phi)*sin(theta), r*sin(phi)*sin(theta), r*cos(theta)) As a submanifold of a Riemannian manifold, namely the Euclidean space, the 2-sphere admits an induced metric:: sage: g = S2_r.induced_metric() sage: g.display() g = r^2 dtheta⊗dtheta + r^2*sin(theta)^2 dphi⊗dphi The induced metric is also known as the *first fundamental form* (see :meth:`~sage.manifolds.differentiable.pseudo_riemannian_submanifold.PseudoRiemannianSubmanifold.first_fundamental_form`):: sage: g is S2_r.first_fundamental_form() True The *second fundamental form* encodes the extrinsic curvature of the 2-sphere as hypersurface of Euclidean space (see :meth:`~sage.manifolds.differentiable.pseudo_riemannian_submanifold.PseudoRiemannianSubmanifold.second_fundamental_form`):: sage: K = S2_r.second_fundamental_form(); K Field of symmetric bilinear forms K on the 2-sphere S^2_r of radius r smoothly embedded in the Euclidean space E^3 sage: K.display() K = r dtheta⊗dtheta + r*sin(theta)^2 dphi⊗dphi One quantity that can be derived from the second fundamental form is the Gaussian curvature:: sage: K = S2_r.gauss_curvature() sage: K.display() S^2_r → ℝ on A: (theta, phi) ↦ r^(-2) As we have seen, spherical coordinates are initialized by default. To initialize stereographic coordinates retrospectively, we can use the following command:: sage: S2_r.stereographic_coordinates() Chart (S^2_r-{NP}, (y1, y2)) To get all charts corresponding to stereographic coordinates, we can use the :meth:`~sage.manifolds.differentiable.examples.sphere.Sphere.coordinate_charts`:: sage: stereoN, stereoS = S2_r.coordinate_charts('stereographic') sage: stereoN, stereoS (Chart (S^2_r-{NP}, (y1, y2)), Chart (S^2_r-{SP}, (yp1, yp2))) .. SEEALSO:: See :meth:`~sage.manifolds.differentiable.examples.sphere.Sphere.stereographic_coordinates` and :meth:`~sage.manifolds.differentiable.examples.sphere.Sphere.spherical_coordinates` for details. .. NOTE:: Notice that the derived quantities such as the embedding as well as the first and second fundamental forms must be computed from scratch again when new coordinates have been initialized. That makes the usage of previously declared objects obsolete. Consider now a 1-sphere with barycenter `(1,0)` in Cartesian coordinates:: sage: E2 = EuclideanSpace(2) sage: c = E2.point((1,0), name='c') sage: S1c.<chi> = E2.sphere(center=c); S1c 1-sphere S^1(c) of radius 1 smoothly embedded in the Euclidean plane E^2 centered at the Point c sage: S1c.spherical_coordinates() Chart (A, (chi,)) Get stereographic coordinates:: sage: stereoN, stereoS = S1c.coordinate_charts('stereographic') sage: stereoN, stereoS (Chart (S^1(c)-{NP}, (y1,)), Chart (S^1(c)-{SP}, (yp1,))) The embedding takes now the following form in all coordinates:: sage: S1c.embedding().display() iota: S^1(c) → E^2 on A: chi ↦ (x, y) = (cos(chi) + 1, sin(chi)) on S^1(c)-{NP}: y1 ↦ (x, y) = (2*y1/(y1^2 + 1) + 1, (y1^2 - 1)/(y1^2 + 1)) on S^1(c)-{SP}: yp1 ↦ (x, y) = (2*yp1/(yp1^2 + 1) + 1, -(yp1^2 - 1)/(yp1^2 + 1)) Since the sphere is a hypersurface, we can get a normal vector field by using ``normal``:: sage: n = S1c.normal(); n Vector field n along the 1-sphere S^1(c) of radius 1 smoothly embedded in the Euclidean plane E^2 centered at the Point c with values on the Euclidean plane E^2 sage: n.display() n = -cos(chi) e_x - sin(chi) e_y Notice that this is just *one* normal field with arbitrary direction, in this particular case `n` points inwards whereas `-n` points outwards. However, the vector field `n` is indeed non-vanishing and hence the sphere admits an orientation (as all spheres do):: sage: orient = S1c.orientation(); orient [Coordinate frame (S^1(c)-{SP}, (∂/∂yp1)), Vector frame (S^1(c)-{NP}, (f_1))] sage: f = orient[1] sage: f[1].display() f_1 = -∂/∂y1 Notice that the orientation is chosen is such a way that `(\iota_*(f_1), -n)` is oriented in the ambient Euclidean space, i.e. the last entry is the normal vector field pointing outwards. Henceforth, the manifold admits a volume form:: sage: g = S1c.induced_metric() sage: g.display() g = dchi⊗dchi sage: eps = g.volume_form() sage: eps.display() eps_g = -dchi """ from sage.manifolds.differentiable.pseudo_riemannian_submanifold import \ PseudoRiemannianSubmanifold from sage.categories.metric_spaces import MetricSpaces from sage.categories.manifolds import Manifolds from sage.categories.topological_spaces import TopologicalSpaces from sage.rings.real_mpfr import RR from sage.manifolds.differentiable.examples.euclidean import EuclideanSpace class Sphere(PseudoRiemannianSubmanifold): r""" Sphere smoothly embedded in Euclidean Space. An `n`-sphere of radius `r`smoothly embedded in a Euclidean space `E^{n+1}` is a smooth `n`-dimensional manifold smoothly embedded into `E^{n+1}`, such that the embedding constitutes a standard `n`-sphere of radius `r` in that Euclidean space (possibly shifted by a point). - ``n`` -- positive integer representing dimension of the sphere - ``radius`` -- (default: ``1``) positive number that states the radius of the sphere - ``name`` -- (default: ``None``) string; name (symbol) given to the sphere; if ``None``, the name will be set according to the input (see convention above) - ``ambient_space`` -- (default: ``None``) Euclidean space in which the sphere should be embedded; if ``None``, a new instance of Euclidean space is created - ``center`` -- (default: ``None``) the barycenter of the sphere as point of the ambient Euclidean space; if ``None`` the barycenter is set to the origin of the ambient space's standard Cartesian coordinates - ``latex_name`` -- (default: ``None``) string; LaTeX symbol to denote the space; if ``None``, it will be set according to the input (see convention above) - ``coordinates`` -- (default: ``'spherical'``) string describing the type of coordinates to be initialized at the sphere's creation; allowed values are - ``'spherical'`` spherical coordinates (see :meth:`~sage.manifolds.differentiable.examples.sphere.Sphere.spherical_coordinates`)) - ``'stereographic'`` stereographic coordinates given by the stereographic projection (see :meth:`~sage.manifolds.differentiable.examples.sphere.Sphere.stereographic_coordinates`) - ``names`` -- (default: ``None``) must be a tuple containing the coordinate symbols (this guarantees the shortcut operator ``<,>`` to function); if ``None``, the usual conventions are used (see examples below for details) - ``unique_tag`` -- (default: ``None``) tag used to force the construction of a new object when all the other arguments have been used previously (without ``unique_tag``, the :class:`~sage.structure.unique_representation.UniqueRepresentation` behavior inherited from :class:`~sage.manifolds.differentiable.pseudo_riemannian.PseudoRiemannianManifold` would return the previously constructed object corresponding to these arguments) EXAMPLES: A 2-sphere embedded in Euclidean space:: sage: S2 = manifolds.Sphere(2); S2 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3 sage: latex(S2) \mathbb{S}^{2} The ambient Euclidean space is constructed incidentally:: sage: S2.ambient() Euclidean space E^3 Another call creates another sphere and hence another Euclidean space:: sage: S2 is manifolds.Sphere(2) False sage: S2.ambient() is manifolds.Sphere(2).ambient() False By default, the barycenter is set to the coordinate origin of the standard Cartesian coordinates in the ambient Euclidean space:: sage: c = S2.center(); c Point on the Euclidean space E^3 sage: c.coord() (0, 0, 0) Each `n`-sphere is a compact manifold and a complete metric space:: sage: S2.category() Join of Category of compact topological spaces and Category of smooth manifolds over Real Field with 53 bits of precision and Category of connected manifolds over Real Field with 53 bits of precision and Category of complete metric spaces If not stated otherwise, each `n`-sphere is automatically endowed with spherical coordinates:: sage: S2.atlas() [Chart (A, (theta, phi))] sage: S2.default_chart() Chart (A, (theta, phi)) sage: spher = S2.spherical_coordinates() sage: spher is S2.default_chart() True Notice that the spherical coordinates do not cover the whole sphere. To cover the entire sphere with charts, use stereographic coordinates instead:: sage: stereoN, stereoS = S2.coordinate_charts('stereographic') sage: stereoN, stereoS (Chart (S^2-{NP}, (y1, y2)), Chart (S^2-{SP}, (yp1, yp2))) sage: list(S2.open_covers()) [Set {S^2} of open subsets of the 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3, Set {S^2-{NP}, S^2-{SP}} of open subsets of the 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3] .. NOTE:: Keep in mind that the initialization process of stereographic coordinates and their transition maps is computational complex in higher dimensions. Henceforth, high computation times are expected with increasing dimension. """ @staticmethod def __classcall_private__(cls, n=None, radius=1, ambient_space=None, center=None, name=None, latex_name=None, coordinates='spherical', names=None, unique_tag=None): r""" Determine the correct class to return based upon the input. TESTS: Each call gives a new instance:: sage: S2 = manifolds.Sphere(2) sage: S2 is manifolds.Sphere(2) False The dimension can be determined using the ``<...>`` operator:: sage: S.<x,y> = manifolds.Sphere(coordinates='stereographic'); S 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3 sage: S._first_ngens(2) (x, y) """ if n is None: if names is None: raise ValueError("either n or names must be specified") n = len(names) # Technical bit for UniqueRepresentation from sage.misc.prandom import getrandbits from time import time if unique_tag is None: unique_tag = getrandbits(128) * time() return super().__classcall__(cls, n, radius=radius, ambient_space=ambient_space, center=center, name=name, latex_name=latex_name, coordinates=coordinates, names=names, unique_tag=unique_tag) def __init__(self, n, radius=1, ambient_space=None, center=None, name=None, latex_name=None, coordinates='spherical', names=None, category=None, init_coord_methods=None, unique_tag=None): r""" Construct sphere smoothly embedded in Euclidean space. TESTS:: sage: S2 = manifolds.Sphere(2); S2 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3 sage: S2.metric() Riemannian metric g on the 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3 sage: TestSuite(S2).run() """ # radius if radius <= 0: raise ValueError('radius must be greater than zero') # ambient space if ambient_space is None: ambient_space = EuclideanSpace(n+1) elif not isinstance(ambient_space, EuclideanSpace): raise TypeError("the argument 'ambient_space' must be a Euclidean space") elif ambient_space._dim != n+1: raise ValueError("Euclidean space must have dimension {}".format(n+1)) if center is None: cart = ambient_space.cartesian_coordinates() c_coords = [0]*(n+1) center = ambient_space.point(c_coords, chart=cart) elif center not in ambient_space: raise ValueError('{} must be an element of {}'.format(center, ambient_space)) if name is None: name = 'S^{}'.format(n) if radius != 1: name += r'_{}'.format(radius) if center._name: name += r'({})'.format(center._name) if latex_name is None: latex_name = r'\mathbb{S}^{' + str(n) + r'}' if radius != 1: latex_name += r'_{{{}}}'.format(radius) if center._latex_name: latex_name += r'({})'.format(center._latex_name) if category is None: category = Manifolds(RR).Smooth() & MetricSpaces().Complete() & \ TopologicalSpaces().Compact().Connected() # initialize PseudoRiemannianSubmanifold.__init__(self, n, name, ambient=ambient_space, signature=n, latex_name=latex_name, metric_name='g', start_index=1, category=category) # set attributes self._radius = radius self._center = center self._coordinates = {} # established coordinates; values are lists self._init_coordinates = {'spherical': self._init_spherical, 'stereographic': self._init_stereographic} # predefined coordinates if init_coord_methods: self._init_coordinates.update(init_coord_methods) if coordinates not in self._init_coordinates: raise ValueError('{} coordinates not available'.format(coordinates)) # up here, the actual initialization begins: self._init_chart_domains() self._init_embedding() self._init_coordinates[coordinates](names) def _init_embedding(self): r""" Initialize the embedding into Euclidean space. TESTS:: sage: S2 = manifolds.Sphere(2) sage: i = S2.embedding(); i Differentiable map iota from the 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3 to the Euclidean space E^3 sage: i.display() iota: S^2 → E^3 on A: (theta, phi) ↦ (x, y, z) = (cos(phi)*sin(theta), sin(phi)*sin(theta), cos(theta)) """ name = 'iota' latex_name = r'\iota' iota = self.diff_map(self._ambient, name=name, latex_name=latex_name) self.set_embedding(iota) def _repr_(self): r""" Return a string representation of ``self``. TESTS:: sage: S2_3 = manifolds.Sphere(2, radius=3) sage: S2_3._repr_() '2-sphere S^2_3 of radius 3 smoothly embedded in the Euclidean space E^3' sage: S2_3 # indirect doctest 2-sphere S^2_3 of radius 3 smoothly embedded in the Euclidean space E^3 """ s = "{}-sphere {} of radius {} smoothly embedded in " \ "the {}".format(self._dim, self._name, self._radius, self._ambient) if self._center._name: s += ' centered at the Point {}'.format(self._center._name) return s def coordinate_charts(self, coord_name, names=None): r""" Return a list of all charts belonging to the coordinates ``coord_name``. INPUT: - ``coord_name`` -- string describing the type of coordinates - ``names`` -- (default: ``None``) must be a tuple containing the coordinate symbols for the first chart in the list; if ``None``, the standard convention is used EXAMPLES: Spherical coordinates on `S^1`:: sage: S1 = manifolds.Sphere(1) sage: S1.coordinate_charts('spherical') [Chart (A, (phi,))] Stereographic coordinates on `S^1`:: sage: stereo_charts = S1.coordinate_charts('stereographic', names=['a']) sage: stereo_charts [Chart (S^1-{NP}, (a,)), Chart (S^1-{SP}, (ap,))] """ if coord_name not in self._coordinates: if coord_name not in self._init_coordinates: raise ValueError('{} coordinates not available'.format(coord_name)) self._init_coordinates[coord_name](names) return list(self._coordinates[coord_name]) def _first_ngens(self, n): r""" Return the list of coordinates of the default chart. This is useful only for the use of Sage preparser:: sage: preparse("S3.<x,y,z> = manifolds.Sphere(coordinates='stereographic')") "S3 = manifolds.Sphere(coordinates='stereographic', names=('x', 'y', 'z',)); (x, y, z,) = S3._first_ngens(3)" TESTS:: sage: S2 = manifolds.Sphere(2) sage: S2._first_ngens(2) (theta, phi) sage: S2.<u,v> = manifolds.Sphere(2) sage: S2._first_ngens(2) (u, v) """ return self._def_chart[:] def _init_chart_domains(self): r""" Construct the chart domains on ``self``. TESTS:: sage: S2 = manifolds.Sphere(2) sage: list(S2.open_covers()) [Set {S^2} of open subsets of the 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3, Set {S^2-{NP}, S^2-{SP}} of open subsets of the 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3] sage: frozenset(S2.subsets()) # random frozenset({Euclidean 2-sphere S^2 of radius 1, Open subset A of the Euclidean 2-sphere S^2 of radius 1, Open subset S^2-{NP,SP} of the Euclidean 2-sphere S^2 of radius 1, Open subset S^2-{NP} of the Euclidean 2-sphere S^2 of radius 1, Open subset S^2-{SP} of the Euclidean 2-sphere S^2 of radius 1}) """ # without north pole: name = self._name + '-{NP}' latex_name = self._latex_name + r'\setminus\{\mathrm{NP}\}' self._stereoN_dom = self.open_subset(name, latex_name) # without south pole: name = self._name + '-{SP}' latex_name = self._latex_name + r'\setminus\{\mathrm{SP}\}' self._stereoS_dom = self.open_subset(name, latex_name) # intersection: int = self._stereoN_dom.intersection(self._stereoS_dom) int._name = self._name + '-{NP,SP}' int._latex_name = self._latex_name + \ r'\setminus\{\mathrm{NP}, \mathrm{SP}\}' # without half circle: self._spher_dom = int.open_subset('A') # declare union: self.declare_union(self._stereoN_dom, self._stereoS_dom) def _shift_coords(self, coordfunc, s='+'): r""" Shift the coordinates ``coordfunc`` given in Cartesian coordinates to the barycenter. INPUT: - ``coordfunc`` -- coordinate expression given in the standard Cartesian coordinates of the ambient Euclidean space - ``s`` -- either ``'+'`` or ``'-'`` depending on whether ``coordfunc`` should be shifted from the coordinate origin to the center or from the center to the coordinate origin TESTS:: sage: E3 = EuclideanSpace(3) sage: c = E3.point((1,2,3), name='c') sage: S2c = manifolds.Sphere(2, ambient_space=E3, center=c) sage: spher = S2c.spherical_coordinates() sage: cart = E3.cartesian_coordinates() sage: coordfunc = S2c.embedding().expr(spher, cart); coordfunc (cos(phi)*sin(theta) + 1, sin(phi)*sin(theta) + 2, cos(theta) + 3) sage: S2c._shift_coords(coordfunc, s='-') (cos(phi)*sin(theta), sin(phi)*sin(theta), cos(theta)) """ cart = self._ambient.cartesian_coordinates() c_coords = cart(self._center) if s == '+': res = [x + c for x, c in zip(coordfunc, c_coords)] elif s == '-': res = [x - c for x, c in zip(coordfunc, c_coords)] return tuple(res) def _init_spherical(self, names=None): r""" Construct the chart of spherical coordinates. TESTS: Spherical coordinates on a 2-sphere:: sage: S2 = manifolds.Sphere(2) sage: S2.spherical_coordinates() Chart (A, (theta, phi)) Spherical coordinates on a 1-sphere:: sage: S1 = manifolds.Sphere(1, coordinates='stereographic') sage: spher = S1.spherical_coordinates(); spher # create coords Chart (A, (phi,)) sage: S1.atlas() [Chart (S^1-{NP}, (y1,)), Chart (S^1-{SP}, (yp1,)), Chart (S^1-{NP,SP}, (y1,)), Chart (S^1-{NP,SP}, (yp1,)), Chart (A, (phi,)), Chart (A, (y1,)), Chart (A, (yp1,))] """ # speed-up via simplification method... self.set_simplify_function(lambda expr: expr.simplify_trig()) # get domain... A = self._spher_dom # initialize coordinates... n = self._dim if names: # add interval: names = tuple([x + ':(0,pi)' for x in names[:-1]] + [names[-1] + ':(-pi,pi):periodic']) else: if n == 1: names = ('phi:(-pi,pi):periodic',) elif n == 2: names = ('theta:(0,pi)', 'phi:(-pi,pi):periodic') elif n == 3: names = ('chi:(0,pi)', 'theta:(0,pi)', 'phi:(-pi,pi):periodic') else: names = tuple(["phi_{}:(0,pi)".format(i) for i in range(1,n)] + ["phi_{}:(-pi,pi):periodic".format(n)]) spher = A.chart(names=names) coord = spher[:] # make spherical chart and frame the default ones on their domain: A.set_default_chart(spher) A.set_default_frame(spher.frame()) # manage embedding... from sage.misc.misc_c import prod from sage.functions.trig import cos, sin R = self._radius coordfunc = [R*cos(coord[n-1])*prod(sin(coord[i]) for i in range(n-1))] coordfunc += [R*prod(sin(coord[i]) for i in range(n))] for k in reversed(range(n-1)): c = R*cos(coord[k])*prod(sin(coord[i]) for i in range(k)) coordfunc.append(c) cart = self._ambient.cartesian_coordinates() # shift coordinates to barycenter: coordfunc = self._shift_coords(coordfunc, s='+') # add expression to embedding: self._immersion.add_expr(spher, cart, coordfunc) self.clear_cache() # clear cache of extrinsic information # finish process... self._coordinates['spherical'] = [spher] # adapt other coordinates... if 'stereographic' in self._coordinates: self._transition_spher_stereo() # reset simplification method... self.set_simplify_function('default') def stereographic_coordinates(self, pole='north', names=None): r""" Return stereographic coordinates given by the stereographic projection of ``self`` w.r.t. to a given pole. INPUT: - ``pole`` -- (default: ``'north'``) the pole determining the stereographic projection; possible options are ``'north'`` and ``'south'`` - ``names`` -- (default: ``None``) must be a tuple containing the coordinate symbols (this guarantees the usage of the shortcut operator ``<,>``) OUTPUT: - the chart of stereographic coordinates w.r.t. to the given pole, as an instance of :class:`~sage.manifolds.differentiable.chart.RealDiffChart` Let `\mathbb{S}^n_r(c)` be an `n`-sphere of radius `r` smoothly embedded in the Euclidean space `E^{n+1}` centered at `c \in E^{n+1}`. We denote the north pole of `\mathbb{S}^n_r(c)` by `\mathrm{NP}` and the south pole by `\mathrm{SP}`. These poles are uniquely determined by the requirement .. MATH:: x(\iota(\mathrm{NP})) &= (0, \ldots, 0, r) + x(c), \\ x(\iota(\mathrm{SP})) &= (0, \ldots, 0, -r) + x(c). The coordinates `(y_1, \ldots, y_n)` (`(y'_1, \ldots, y'_n)` respectively) define *stereographic coordinates* on `\mathbb{S}^n_r(c)` for the Cartesian coordinates `(x_1, \ldots, x_{n+1})` on `E^{n+1}` if they arise from the stereographic projection from `\iota(\mathrm{NP})` (`\iota(\mathrm{SP})`) to the hypersurface `x_n = x_n(c)`. In concrete formulas, this means: .. MATH:: \left. x \circ \iota \right|_{\mathbb{S}^n_r(c) \setminus \{ \mathrm{NP}\}} &= \left( \frac{2y_1r^2}{r^2+\sum^n_{i=1} y^2_i}, \ldots, \frac{2y_nr^2}{r^2+\sum^n_{i=1} y^2_i}, \frac{r\sum^n_{i=1} y^2_i-r^3}{r^2+\sum^n_{i=1} y^2_i} \right) + x(c), \\ \left. x \circ \iota \right|_{\mathbb{S}^n_r(c) \setminus \{ \mathrm{SP}\}} &= \left( \frac{2y'_1r^2}{r^2+\sum^n_{i=1} y'^2_i}, \ldots, \frac{2y'_nr^2}{r^2+\sum^n_{i=1} y'^2_i}, \frac{r^3 - r\sum^n_{i=1} y'^2_i}{r^2+\sum^n_{i=1} y'^2_i} \right) + x(c). EXAMPLES: Initialize a 1-sphere centered at `(1,0)` in the Euclidean plane using the shortcut operator:: sage: E2 = EuclideanSpace(2) sage: c = E2.point((1,0), name='c') sage: S1.<a> = E2.sphere(center=c, coordinates='stereographic'); S1 1-sphere S^1(c) of radius 1 smoothly embedded in the Euclidean plane E^2 centered at the Point c By default, the shortcut variables belong to the stereographic projection from the north pole:: sage: S1.coordinate_charts('stereographic') [Chart (S^1(c)-{NP}, (a,)), Chart (S^1(c)-{SP}, (ap,))] sage: S1.embedding().display() iota: S^1(c) → E^2 on S^1(c)-{NP}: a ↦ (x, y) = (2*a/(a^2 + 1) + 1, (a^2 - 1)/(a^2 + 1)) on S^1(c)-{SP}: ap ↦ (x, y) = (2*ap/(ap^2 + 1) + 1, -(ap^2 - 1)/(ap^2 + 1)) Initialize a 2-sphere from scratch:: sage: S2 = manifolds.Sphere(2) sage: S2.atlas() [Chart (A, (theta, phi))] In the previous block, the stereographic coordinates have not been initialized. This happens subsequently with the invocation of ``stereographic_coordinates``:: sage: stereoS.<u,v> = S2.stereographic_coordinates(pole='south') sage: S2.coordinate_charts('stereographic') [Chart (S^2-{NP}, (up, vp)), Chart (S^2-{SP}, (u, v))] If not specified by the user, the default coordinate names are given by `(y_1, \ldots, y_n)` and `(y'_1, \ldots, y'_n)` respectively:: sage: S3 = manifolds.Sphere(3, coordinates='stereographic') sage: S3.stereographic_coordinates(pole='north') Chart (S^3-{NP}, (y1, y2, y3)) sage: S3.stereographic_coordinates(pole='south') Chart (S^3-{SP}, (yp1, yp2, yp3)) """ coordinates = 'stereographic' if coordinates not in self._coordinates: self._init_coordinates[coordinates](names, default_pole=pole) if pole == 'north': return self._coordinates[coordinates][0] elif pole == 'south': return self._coordinates[coordinates][1] else: raise ValueError("pole must be 'north' or 'south'") def spherical_coordinates(self, names=None): r""" Return the spherical coordinates of ``self``. INPUT: - ``names`` -- (default: ``None``) must be a tuple containing the coordinate symbols (this guarantees the usage of the shortcut operator ``<,>``) OUTPUT: - the chart of spherical coordinates, as an instance of :class:`~sage.manifolds.differentiable.chart.RealDiffChart` Let `\mathbb{S}^n_r(c)` be an `n`-sphere of radius `r` smoothly embedded in the Euclidean space `E^{n+1}` centered at `c \in E^{n+1}`. We say that `(\varphi_1, \ldots, \varphi_n)` define *spherical coordinates* on the open subset `A \subset \mathbb{S}^n_r(c)` for the Cartesian coordinates `(x_1, \ldots, x_{n+1})` on `E^{n+1}` (not necessarily centered at `c`) if .. MATH:: \begin{aligned} \left. x_1 \circ \iota \right|_{A} &= r \cos(\varphi_n)\sin( \varphi_{n-1}) \cdots \sin(\varphi_1) + x_1(c), \\ \left. x_1 \circ \iota \right|_{A} &= r \sin(\varphi_n)\sin( \varphi_{n-1}) \cdots \sin(\varphi_1) + x_1(c), \\ \left. x_2 \circ \iota \right|_{A} &= r \cos(\varphi_{ n-1})\sin(\varphi_{n-2}) \cdots \sin(\varphi_1) + x_2(c), \\ \left. x_3 \circ \iota \right|_{A} &= r \cos(\varphi_{ n-2})\sin(\varphi_{n-3}) \cdots \sin(\varphi_1) + x_3(c), \\ \vdots & \\ \left. x_{n+1} \circ \iota \right|_{A} &= r \cos(\varphi_1) + x_{n+1}(c), \end{aligned} where `\varphi_i` has range `(0, \pi)` for `i=1, \ldots, n-1` and `\varphi_n` lies in `(-\pi, \pi)`. Notice that the above expressions together with the ranges of the `\varphi_i` fully determine the open set `A`. .. NOTE:: Notice that our convention slightly differs from the one given on the :wikipedia:`N-sphere#Spherical_coordinates`. The definition above ensures that the conventions for the most common cases `n=1` and `n=2` are maintained. EXAMPLES: The spherical coordinates on a 2-sphere follow the common conventions:: sage: S2 = manifolds.Sphere(2) sage: spher = S2.spherical_coordinates(); spher Chart (A, (theta, phi)) The coordinate range of spherical coordinates:: sage: spher.coord_range() theta: (0, pi); phi: [-pi, pi] (periodic) Spherical coordinates do not cover the 2-sphere entirely:: sage: A = spher.domain(); A Open subset A of the 2-sphere S^2 of radius 1 smoothly embedded in the Euclidean space E^3 The embedding of a 2-sphere in Euclidean space via spherical coordinates:: sage: S2.embedding().display() iota: S^2 → E^3 on A: (theta, phi) ↦ (x, y, z) = (cos(phi)*sin(theta), sin(phi)*sin(theta), cos(theta)) Now, consider spherical coordinates on a 3-sphere:: sage: S3 = manifolds.Sphere(3) sage: spher = S3.spherical_coordinates(); spher Chart (A, (chi, theta, phi)) sage: S3.embedding().display() iota: S^3 → E^4 on A: (chi, theta, phi) ↦ (x1, x2, x3, x4) = (cos(phi)*sin(chi)*sin(theta), sin(chi)*sin(phi)*sin(theta), cos(theta)*sin(chi), cos(chi)) By convention, the last coordinate is periodic:: sage: spher.coord_range() chi: (0, pi); theta: (0, pi); phi: [-pi, pi] (periodic) """ coordinates = 'spherical' if coordinates not in self._coordinates: self._init_coordinates[coordinates](names) return self._coordinates[coordinates][0] def _init_stereographic(self, names, default_pole='north'): r""" Construct the charts of stereographic coordinates. TESTS: Stereographic coordinates on the 2-sphere:: sage: S2.<x,y> = manifolds.Sphere(2, coordinates='stereographic') sage: S2.atlas() [Chart (S^2-{NP}, (x, y)), Chart (S^2-{SP}, (xp, yp)), Chart (S^2-{NP,SP}, (x, y)), Chart (S^2-{NP,SP}, (xp, yp))] Stereographic coordinates on the 1-sphere:: sage: S1 = manifolds.Sphere(1) sage: stereoS.<x> = S1.stereographic_coordinates(pole='south') sage: S1.atlas() [Chart (A, (phi,)), Chart (S^1-{NP}, (xp,)), Chart (S^1-{SP}, (x,)), Chart (S^1-{NP,SP}, (xp,)), Chart (S^1-{NP,SP}, (x,)), Chart (A, (xp,)), Chart (A, (x,))] The stereographic chart is the default one on its domain:: sage: V = stereoS.domain() sage: V.default_chart() Chart (S^1-{SP}, (x,)) Accordingly, we have:: sage: S1.metric().restrict(V).display() g = 4/(x^4 + 2*x^2 + 1) dx⊗dx while the spherical chart is still the default one on ``S1``:: sage: S1.metric().display() g = dphi⊗dphi """ # speed-up via simplification method... self.set_simplify_function(lambda expr: expr.simplify_rational()) # TODO: More speed-up? # get domains... U = self._stereoN_dom V = self._stereoS_dom # initialize coordinates... symbols_N = '' symbols_S = '' if names: for x in names: if default_pole == 'north': symbols_N += x + ' ' symbols_S += "{}p".format(x) + ":{}' ".format(x) elif default_pole == 'south': symbols_S += x + ' ' symbols_N += "{}p".format(x) + ":{}' ".format(x) else: for i in self.irange(): symbols_N += "y{}".format(i) + r":y_{" + str(i) + r"} " symbols_S += "yp{}".format(i) + r":y'_{" + str(i) + r"} " symbols_N = symbols_N[:-1] symbols_S = symbols_S[:-1] stereoN = U.chart(coordinates=symbols_N) stereoS = V.chart(coordinates=symbols_S) coordN = stereoN[:] coordS = stereoS[:] # make stereographic charts and frames the default ones on their # respective domains: U.set_default_chart(stereoN) V.set_default_chart(stereoS) U.set_default_frame(stereoN.frame()) V.set_default_frame(stereoS.frame()) # predefine variables... r2_N = sum(y ** 2 for y in coordN) r2_S = sum(yp ** 2 for yp in coordS) R = self._radius R2 = R**2 # define transition map... coordN_to_S = tuple(R*y/r2_N for y in coordN) coordS_to_N = tuple(R*yp/r2_S for yp in coordS) stereoN_to_S = stereoN.transition_map(stereoS, coordN_to_S, restrictions1=r2_N != 0, restrictions2=r2_S != 0) stereoN_to_S.set_inverse(*coordS_to_N, check=False) # manage embedding... coordfuncN = [2*y*R2 / (R2+r2_N) for y in coordN] coordfuncN += [(R*r2_N-R*R2)/(R2+r2_N)] coordfuncS = [2*yp*R2 / (R2+r2_S) for yp in coordS] coordfuncS += [(R*R2-R*r2_S)/(R2+r2_S)] cart = self._ambient.cartesian_coordinates() # shift coordinates to barycenter: coordfuncN = self._shift_coords(coordfuncN, s='+') coordfuncS = self._shift_coords(coordfuncS, s='+') # add expressions to embedding: self._immersion.add_expr(stereoN, cart, coordfuncN) self._immersion.add_expr(stereoS, cart, coordfuncS) self.clear_cache() # clear cache of extrinsic information # define orientation... eN = stereoN.frame() eS = stereoS.frame() # oriented w.r.t. embedding frame_comp = list(eN[:]) frame_comp[0] = -frame_comp[0] # reverse orientation f = U.vector_frame('f', frame_comp) self.set_orientation([eS, f]) # finish process... self._coordinates['stereographic'] = [stereoN, stereoS] # adapt other coordinates... if 'spherical' in self._coordinates: self._transition_spher_stereo() # reset simplification method... self.set_simplify_function('default') def _transition_spher_stereo(self): r""" Initialize the transition map between spherical and stereographic coordinates. TESTS:: sage: S1 = manifolds.Sphere(1) sage: spher = S1.spherical_coordinates(); spher Chart (A, (phi,)) sage: A = spher.domain() sage: stereoN = S1.stereographic_coordinates(pole='north'); stereoN Chart (S^1-{NP}, (y1,)) sage: S1.coord_change(spher, stereoN.restrict(A)) Change of coordinates from Chart (A, (phi,)) to Chart (A, (y1,)) """ # speed-up via simplification method... self.set_simplify_function(lambda expr: expr.simplify()) # configure preexisting charts... W = self._stereoN_dom.intersection(self._stereoS_dom) A = self._spher_dom stereoN, stereoS = self._coordinates['stereographic'][:] coordN = stereoN[:] coordS = stereoS[:] rstN = (coordN[0] != 0,) rstS = (coordS[0] != 0,) if self._dim > 1: rstN += (coordN[0] > 0,) rstS += (coordS[0] > 0,) stereoN_A = stereoN.restrict(A, rstN) stereoS_A = stereoS.restrict(A, rstS) self._coord_changes[(stereoN.restrict(W), stereoS.restrict(W))].restrict(A) self._coord_changes[(stereoS.restrict(W), stereoN.restrict(W))].restrict(A) spher = self._coordinates['spherical'][0] R = self._radius n = self._dim # transition: spher to stereoN... imm = self.embedding() cart = self._ambient.cartesian_coordinates() # get ambient coordinates and shift to coordinate origin: x = self._shift_coords(imm.expr(spher, cart), s='-') coordfunc = [(R*x[i])/(R-x[-1]) for i in range(n)] # define transition map: spher_to_stereoN = spher.transition_map(stereoN_A, coordfunc) # transition: stereoN to spher... from sage.functions.trig import acos, atan2 from sage.misc.functional import sqrt # get ambient coordinates and shift to coordinate origin: x = self._shift_coords(imm.expr(stereoN, cart), s='-') coordfunc = [atan2(x[1],x[0])] for k in range(2, n+1): c = acos(x[k]/sqrt(sum(x[i]**2 for i in range(k+1)))) coordfunc.append(c) coordfunc = reversed(coordfunc) spher_to_stereoN.set_inverse(*coordfunc, check=False) # transition spher <-> stereoS... stereoN_to_S_A = self.coord_change(stereoN_A, stereoS_A) stereoN_to_S_A * spher_to_stereoN # generates spher_to_stereoS stereoS_to_N_A = self.coord_change(stereoS_A, stereoN_A) spher_to_stereoN.inverse() * stereoS_to_N_A # generates stereoS_to_spher def dist(self, p, q): r""" Return the great circle distance between the points ``p`` and ``q`` on ``self``. INPUT: - ``p`` -- an element of ``self`` - ``q`` -- an element of ``self`` OUTPUT: - the great circle distance `d(p, q)` on ``self`` The great circle distance `d(p, q)` of the points `p, q \in \mathbb{S}^n_r(c)` is the length of the shortest great circle segment on `\mathbb{S}^n_r(c)` that joins `p` and `q`. If we choose Cartesian coordinates `(x_1, \ldots, x_{n+1})` of the ambient Euclidean space such that the center lies in the coordinate origin, i.e. `x(c)=0`, the great circle distance can be expressed in terms of the following formula: .. MATH:: d(p,q) = r \, \arccos\left(\frac{x(\iota(p)) \cdot x(\iota(q))}{r^2}\right). EXAMPLES: Define a 2-sphere with unspecified radius:: sage: r = var('r') sage: S2_r = manifolds.Sphere(2, radius=r); S2_r 2-sphere S^2_r of radius r smoothly embedded in the Euclidean space E^3 Given two antipodal points in spherical coordinates:: sage: p = S2_r.point((pi/2, pi/2), name='p'); p Point p on the 2-sphere S^2_r of radius r smoothly embedded in the Euclidean space E^3 sage: q = S2_r.point((pi/2, -pi/2), name='q'); q Point q on the 2-sphere S^2_r of radius r smoothly embedded in the Euclidean space E^3 The distance is determined as the length of the half great circle:: sage: S2_r.dist(p, q) pi*r """ from sage.functions.trig import acos # get Euclidean points: x = self._immersion(p) y = self._immersion(q) cart = self._ambient.cartesian_coordinates() # get ambient coordinates and shift to coordinate origin: x_coord = self._shift_coords(x.coord(chart=cart), s='-') y_coord = self._shift_coords(y.coord(chart=cart), s='-') n = self._dim + 1 r = self._radius inv_angle = sum(x_coord[i]*y_coord[i] for i in range(n)) / r**2 return (r * acos(inv_angle)).simplify() def radius(self): r""" Return the radius of ``self``. EXAMPLES: 3-sphere with radius 3:: sage: S3_2 = manifolds.Sphere(3, radius=2); S3_2 3-sphere S^3_2 of radius 2 smoothly embedded in the 4-dimensional Euclidean space E^4 sage: S3_2.radius() 2 2-sphere with unspecified radius:: sage: r = var('r') sage: S2_r = manifolds.Sphere(3, radius=r); S2_r 3-sphere S^3_r of radius r smoothly embedded in the 4-dimensional Euclidean space E^4 sage: S2_r.radius() r """ return self._radius def minimal_triangulation(self): r""" Return the minimal triangulation of ``self`` as a simplicial complex. EXAMPLES: Minimal triangulation of the 2-sphere:: sage: S2 = manifolds.Sphere(2) sage: S = S2.minimal_triangulation(); S Minimal triangulation of the 2-sphere The Euler characteristic of a 2-sphere:: sage: S.euler_characteristic() 2 """ from sage.topology.simplicial_complex_examples import Sphere as SymplicialSphere return SymplicialSphere(self._dim) def center(self): r""" Return the barycenter of ``self`` in the ambient Euclidean space. EXAMPLES: 2-sphere embedded in Euclidean space centered at `(1,2,3)` in Cartesian coordinates:: sage: E3 = EuclideanSpace(3) sage: c = E3.point((1,2,3), name='c') sage: S2c = manifolds.Sphere(2, ambient_space=E3, center=c); S2c 2-sphere S^2(c) of radius 1 smoothly embedded in the Euclidean space E^3 centered at the Point c sage: S2c.center() Point c on the Euclidean space E^3 We can see that the embedding is shifted accordingly:: sage: S2c.embedding().display() iota: S^2(c) → E^3 on A: (theta, phi) ↦ (x, y, z) = (cos(phi)*sin(theta) + 1, sin(phi)*sin(theta) + 2, cos(theta) + 3) """ return self._center
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/manifolds/differentiable/examples/sphere.py
0.958789
0.965544
sphere.py
pypi
from sage.plot.primitive import GraphicPrimitive from sage.plot.plot import minmax_data, Graphics from sage.misc.decorators import options class Histogram(GraphicPrimitive): """ Graphics primitive that represents a histogram. This takes quite a few options as well. EXAMPLES:: sage: from sage.plot.histogram import Histogram sage: g = Histogram([1,3,2,0], {}); g Histogram defined by a data list of size 4 sage: type(g) <class 'sage.plot.histogram.Histogram'> sage: opts = { 'bins':20, 'label':'mydata'} sage: g = Histogram([random() for _ in range(500)], opts); g Histogram defined by a data list of size 500 We can accept multiple sets of the same length:: sage: g = Histogram([[1,3,2,0], [4,4,3,3]], {}); g Histogram defined by 2 data lists """ def __init__(self, datalist, options): """ Initialize a ``Histogram`` primitive along with its options. EXAMPLES:: sage: from sage.plot.histogram import Histogram sage: Histogram([10,3,5], {'width':0.7}) Histogram defined by a data list of size 3 """ import numpy as np self.datalist = np.asarray(datalist, dtype=float) if 'normed' in options: from sage.misc.superseded import deprecation deprecation(25260, "the 'normed' option is deprecated. Use 'density' instead.") if 'linestyle' in options: from sage.plot.misc import get_matplotlib_linestyle options['linestyle'] = get_matplotlib_linestyle( options['linestyle'], return_type='long') if options.get('range', None): # numpy.histogram performs type checks on "range" so this must be # actual floats options['range'] = [float(x) for x in options['range']] GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Get minimum and maximum horizontal and vertical ranges for the Histogram object. EXAMPLES:: sage: H = histogram([10,3,5], density=True); h = H[0] sage: h.get_minmax_data() # rel tol 1e-15 {'xmax': 10.0, 'xmin': 3.0, 'ymax': 0.4761904761904765, 'ymin': 0} sage: G = histogram([random() for _ in range(500)]); g = G[0] sage: g.get_minmax_data() # random output {'xmax': 0.99729312925213209, 'xmin': 0.00013024562219410285, 'ymax': 61, 'ymin': 0} sage: Y = histogram([random()*10 for _ in range(500)], range=[2,8]); y = Y[0] sage: ymm = y.get_minmax_data(); ymm['xmax'], ymm['xmin'] (8.0, 2.0) sage: Z = histogram([[1,3,2,0], [4,4,3,3]]); z = Z[0] sage: z.get_minmax_data() {'xmax': 4.0, 'xmin': 0, 'ymax': 2, 'ymin': 0} TESTS:: sage: h = histogram([10,3,5], normed=True)[0] doctest:warning...: DeprecationWarning: the 'normed' option is deprecated. Use 'density' instead. See https://trac.sagemath.org/25260 for details. sage: h.get_minmax_data() doctest:warning ... ...VisibleDeprecationWarning: Passing `normed=True` on non-uniform bins has always been broken, and computes neither the probability density function nor the probability mass function. The result is only correct if the bins are uniform, when density=True will produce the same result anyway. The argument will be removed in a future version of numpy. {'xmax': 10.0, 'xmin': 3.0, 'ymax': 0.476190476190..., 'ymin': 0} """ import numpy # Extract these options (if they are not None) and pass them to # histogram() options = self.options() opt = {} for key in ('range', 'bins', 'normed', 'density', 'weights'): try: value = options[key] except KeyError: pass else: if value is not None: opt[key] = value # check to see if a list of datasets if not hasattr(self.datalist[0], '__contains__'): ydata, xdata = numpy.histogram(self.datalist, **opt) return minmax_data(xdata, [0]+list(ydata), dict=True) else: m = {'xmax': 0, 'xmin': 0, 'ymax': 0, 'ymin': 0} if not options.get('stacked'): for d in self.datalist: ydata, xdata = numpy.histogram(d, **opt) m['xmax'] = max([m['xmax']] + list(xdata)) m['xmin'] = min([m['xmin']] + list(xdata)) m['ymax'] = max([m['ymax']] + list(ydata)) return m else: for d in self.datalist: ydata, xdata = numpy.histogram(d, **opt) m['xmax'] = max([m['xmax']] + list(xdata)) m['xmin'] = min([m['xmin']] + list(xdata)) m['ymax'] = m['ymax'] + max(list(ydata)) return m def _allowed_options(self): """ Return the allowed options with descriptions for this graphics primitive. This is used in displaying an error message when the user gives an option that doesn't make sense. EXAMPLES:: sage: from sage.plot.histogram import Histogram sage: g = Histogram( [1,3,2,0], {}) sage: L = list(sorted(g._allowed_options().items())) sage: L[0] ('align', 'How the bars align inside of each bin. Acceptable values are "left", "right" or "mid".') sage: L[-1] ('zorder', 'The layer level to draw the histogram') """ return {'color': 'The color of the face of the bars or list of colors if multiple data sets are given.', 'edgecolor': 'The color of the border of each bar.', 'alpha': 'How transparent the plot is', 'hue': 'The color of the bars given as a hue.', 'fill': '(True or False, default True) Whether to fill the bars', 'hatch': 'What symbol to fill with - one of "/", "\\", "|", "-", "+", "x", "o", "O", ".", "*"', 'linewidth': 'Width of the lines defining the bars', 'linestyle': "One of 'solid' or '-', 'dashed' or '--', 'dotted' or ':', 'dashdot' or '-.'", 'zorder': 'The layer level to draw the histogram', 'bins': 'The number of sections in which to divide the range. Also can be a sequence of points within the range that create the partition.', 'align': 'How the bars align inside of each bin. Acceptable values are "left", "right" or "mid".', 'rwidth': 'The relative width of the bars as a fraction of the bin width', 'cumulative': '(True or False) If True, then a histogram is computed in which each bin gives the counts in that bin plus all bins for smaller values. Negative values give a reversed direction of accumulation.', 'range': 'A list [min, max] which define the range of the histogram. Values outside of this range are treated as outliers and omitted from counts.', 'normed': 'Deprecated. Use density instead.', 'density': '(True or False) If True, the counts are normalized to form a probability density. (n/(len(x)*dbin)', 'weights': 'A sequence of weights the same length as the data list. If supplied, then each value contributes its associated weight to the bin count.', 'stacked': '(True or False) If True, multiple data are stacked on top of each other.', 'label': 'A string label for each data list given.'} def _repr_(self): """ Return text representation of this histogram graphics primitive. EXAMPLES:: sage: from sage.plot.histogram import Histogram sage: g = Histogram( [1,3,2,0], {}) sage: g._repr_() 'Histogram defined by a data list of size 4' sage: g = Histogram( [[1,1,2,3], [1,3,2,0]], {}) sage: g._repr_() 'Histogram defined by 2 data lists' """ L = len(self.datalist) if not hasattr(self.datalist[0], '__contains__'): return "Histogram defined by a data list of size {}".format(L) else: return "Histogram defined by {} data lists".format(L) def _render_on_subplot(self, subplot): """ Render this bar chart graphics primitive on a matplotlib subplot object. EXAMPLES: This rendering happens implicitly when the following command is executed:: sage: histogram([1,2,10]) # indirect doctest Graphics object consisting of 1 graphics primitive """ options = self.options() # check to see if a list of datasets if not hasattr(self.datalist[0], '__contains__'): subplot.hist(self.datalist, **options) else: subplot.hist(self.datalist.transpose(), **options) @options(aspect_ratio='automatic', align='mid', weights=None, range=None, bins=10, edgecolor='black') def histogram(datalist, **options): """ Computes and draws the histogram for list(s) of numerical data. See examples for the many options; even more customization is available using matplotlib directly. INPUT: - ``datalist`` -- A list, or a list of lists, of numerical data - ``align`` -- (default: "mid") How the bars align inside of each bin. Acceptable values are "left", "right" or "mid" - ``alpha`` -- (float in [0,1], default: 1) The transparency of the plot - ``bins`` -- The number of sections in which to divide the range. Also can be a sequence of points within the range that create the partition - ``color`` -- The color of the face of the bars or list of colors if multiple data sets are given - ``cumulative`` -- (boolean - default: False) If True, then a histogram is computed in which each bin gives the counts in that bin plus all bins for smaller values. Negative values give a reversed direction of accumulation - ``edgecolor`` -- The color of the border of each bar - ``fill`` -- (boolean - default: True) Whether to fill the bars - ``hatch`` -- (default: None) symbol to fill the bars with - one of "/", "\\", "|", "-", "+", "x", "o", "O", ".", "*", "" (or None) - ``hue`` -- The color of the bars given as a hue. See :mod:`~sage.plot.colors.hue` for more information on the hue - ``label`` -- A string label for each data list given - ``linewidth`` -- (float) width of the lines defining the bars - ``linestyle`` -- (default: 'solid') Style of the line. One of 'solid' or '-', 'dashed' or '--', 'dotted' or ':', 'dashdot' or '-.' - ``density`` -- (boolean - default: False) If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1. - ``range`` -- A list [min, max] which define the range of the histogram. Values outside of this range are treated as outliers and omitted from counts - ``rwidth`` -- (float in [0,1], default: 1) The relative width of the bars as a fraction of the bin width - ``stacked`` -- (boolean - default: False) If True, multiple data are stacked on top of each other - ``weights`` -- (list) A sequence of weights the same length as the data list. If supplied, then each value contributes its associated weight to the bin count - ``zorder`` -- (integer) the layer level at which to draw the histogram .. NOTE:: The ``weights`` option works only with a single list. List of lists representing multiple data are not supported. EXAMPLES: A very basic histogram for four data points:: sage: histogram([1, 2, 3, 4], bins=2) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(histogram([1, 2, 3, 4], bins=2)) We can see how the histogram compares to various distributions. Note the use of the ``density`` keyword to guarantee the plot looks like the probability density function:: sage: nv = normalvariate sage: H = histogram([nv(0, 1) for _ in range(1000)], bins=20, density=True, range=[-5, 5]) sage: P = plot(1/sqrt(2*pi)*e^(-x^2/2), (x, -5, 5), color='red', linestyle='--') sage: H+P Graphics object consisting of 2 graphics primitives .. PLOT:: nv = normalvariate H = histogram([nv(0, 1) for _ in range(1000)], bins=20, density=True, range=[-5,5 ]) P = plot(1/sqrt(2*pi)*e**(-x**2/2), (x, -5, 5), color='red', linestyle='--') sphinx_plot(H+P) There are many options one can use with histograms. Some of these control the presentation of the data, even if it is boring:: sage: histogram(list(range(100)), color=(1,0,0), label='mydata', rwidth=.5, align="right") Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(histogram(list(range(100)), color=(1,0,0), label='mydata', rwidth=.5, align="right")) This includes many usual matplotlib styling options:: sage: T = RealDistribution('lognormal', [0, 1]) sage: histogram( [T.get_random_element() for _ in range(100)], alpha=0.3, edgecolor='red', fill=False, linestyle='dashed', hatch='O', linewidth=5) Graphics object consisting of 1 graphics primitive .. PLOT:: T = RealDistribution('lognormal', [0, 1]) H = histogram( [T.get_random_element() for _ in range(100)], alpha=0.3, edgecolor='red', fill=False, linestyle='dashed', hatch='O', linewidth=5) sphinx_plot(H) :: sage: histogram( [T.get_random_element() for _ in range(100)],linestyle='-.') Graphics object consisting of 1 graphics primitive .. PLOT:: T = RealDistribution('lognormal', [0, 1]) sphinx_plot(histogram( [T.get_random_element() for _ in range(100)],linestyle='-.')) We can do several data sets at once if desired:: sage: histogram([srange(0, 1, .1)*10, [nv(0, 1) for _ in range(100)]], color=['red', 'green'], bins=5) Graphics object consisting of 1 graphics primitive .. PLOT:: nv = normalvariate sphinx_plot(histogram([srange(0, 1, .1)*10, [nv(0, 1) for _ in range(100)]], color=['red', 'green'], bins=5)) We have the option of stacking the data sets too:: sage: histogram([[1, 1, 1, 1, 2, 2, 2, 3, 3, 3], [4, 4, 4, 4, 3, 3, 3, 2, 2, 2] ], stacked=True, color=['blue', 'red']) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(histogram([[1, 1, 1, 1, 2, 2, 2, 3, 3, 3], [4, 4, 4, 4, 3, 3, 3, 2, 2, 2] ], stacked=True, color=['blue', 'red'])) It is possible to use weights with the histogram as well:: sage: histogram(list(range(10)), bins=3, weights=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(histogram(list(range(10)), bins=3, weights=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1])) """ g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) g.add_primitive(Histogram(datalist, options=options)) return g
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/histogram.py
0.853455
0.649933
histogram.py
pypi
from sage.plot.bezier_path import BezierPath from sage.plot.circle import circle from sage.misc.decorators import options, rename_keyword from sage.rings.cc import CC from sage.plot.hyperbolic_arc import HyperbolicArcCore class HyperbolicPolygon(HyperbolicArcCore): """ Primitive class for hyperbolic polygon type. See ``hyperbolic_polygon?`` for information about plotting a hyperbolic polygon in the complex plane. INPUT: - ``pts`` -- coordinates of the polygon (as complex numbers) - ``options`` -- dict of valid plot options to pass to constructor EXAMPLES: Note that constructions should use :func:`hyperbolic_polygon` or :func:`hyperbolic_triangle`:: sage: from sage.plot.hyperbolic_polygon import HyperbolicPolygon sage: print(HyperbolicPolygon([0, 1/2, I], "UHP", {})) Hyperbolic polygon (0.000000000000000, 0.500000000000000, 1.00000000000000*I) """ def __init__(self, pts, model, options): """ Initialize HyperbolicPolygon. EXAMPLES:: sage: from sage.plot.hyperbolic_polygon import HyperbolicPolygon sage: HP = HyperbolicPolygon([0, 1/2, I], "UHP", {}) sage: TestSuite(HP).run(skip ="_test_pickling") """ if model == "HM": raise ValueError("the hyperboloid model is not supported") if not pts: raise ValueError("cannot plot the empty polygon") from sage.geometry.hyperbolic_space.hyperbolic_interface import HyperbolicPlane HP = HyperbolicPlane() M = getattr(HP, model)() pts = [CC(p) for p in pts] for p in pts: M.point_test(p) self.path = [] if model == "UHP": if pts[0].is_infinity(): # Check for more than one Infinite vertex if any(pts[i].is_infinity() for i in range(1, len(pts))): raise ValueError("no more than one infinite vertex allowed") else: # If any Infinity vertex exist it must be the first for i, p in enumerate(pts): if p.is_infinity(): if any(pt.is_infinity() for pt in pts[i+1:]): raise ValueError("no more than one infinite vertex allowed") pts = pts[i:] + pts[:i] break self._bezier_path(pts[0], pts[1], M, True) for i in range(1, len(pts) - 1): self._bezier_path(pts[i], pts[i + 1], M, False) self._bezier_path(pts[-1], pts[0], M, False) self._pts = pts BezierPath.__init__(self, self.path, options) def _repr_(self): """ String representation of HyperbolicPolygon. TESTS:: sage: from sage.plot.hyperbolic_polygon import HyperbolicPolygon sage: HyperbolicPolygon([0, 1/2, I], "UHP", {}) Hyperbolic polygon (0.000000000000000, 0.500000000000000, 1.00000000000000*I) """ return "Hyperbolic polygon ({})".format(", ".join(map(str, self._pts))) def _winding_number(vertices, point): r""" Compute the winding number of the given point in the plane `z = 0`. TESTS:: sage: from sage.plot.hyperbolic_polygon import _winding_number sage: _winding_number([(0,0,4),(1,0,3),(1,1,2),(0,1,1)],(0.5,0.5,10)) 1 sage: _winding_number([(0,0,4),(1,0,3),(1,1,2),(0,1,1)],(10,10,10)) 0 """ # Helper functions def _intersects(start, end, y0): if end[1] < start[1]: start, end = end, start return start[1] < y0 < end[1] def _is_left(point, edge): start, end = edge[0], edge[1] if end[1] == start[1]: return False x_in = start[0] + (point[1] - start[1]) * (end[0] - start[0]) / (end[1] - start[1]) return x_in > point[0] sides = [] wn = 0 for i in range(0, len(vertices)-1): if _intersects(vertices[i], vertices[i+1], point[1]): sides.append([vertices[i], vertices[i + 1]]) if _intersects(vertices[-1], vertices[0], point[1]): sides.append([vertices[-1], vertices[0]]) for side in sides: if _is_left(point, side): if side[1][1] > side[0][1]: wn = wn + 1 if side[1][1] < side[0][1]: wn = wn - 1 return wn @rename_keyword(color='rgbcolor') @options(alpha=1, fill=False, thickness=1, rgbcolor="blue", zorder=2, linestyle='solid') def hyperbolic_polygon(pts, model="UHP", resolution=200, **options): r""" Return a hyperbolic polygon in the hyperbolic plane with vertices ``pts``. Type ``?hyperbolic_polygon`` to see all options. INPUT: - ``pts`` -- a list or tuple of complex numbers OPTIONS: - ``model`` -- default: ``UHP`` Model used for hyperbolic plane - ``alpha`` -- default: 1 - ``fill`` -- default: ``False`` - ``thickness`` -- default: 1 - ``rgbcolor`` -- default: ``'blue'`` - ``linestyle`` -- (default: ``'solid'``) the style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively EXAMPLES: Show a hyperbolic polygon with coordinates `-1`, `3i`, `2+2i`, `1+i`:: sage: hyperbolic_polygon([-1,3*I,2+2*I,1+I]) Graphics object consisting of 1 graphics primitive .. PLOT:: P = hyperbolic_polygon([-1,3*I,2+2*I,1+I]) sphinx_plot(P) With more options:: sage: hyperbolic_polygon([-1,3*I,2+2*I,1+I], fill=True, color='red') Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(hyperbolic_polygon([-1,3*I,2+2*I,1+I], fill=True, color='red')) With a vertex at `\infty`:: sage: hyperbolic_polygon([-1,0,1,Infinity], color='green') Graphics object consisting of 1 graphics primitive .. PLOT:: from sage.rings.infinity import infinity sphinx_plot(hyperbolic_polygon([-1,0,1,infinity], color='green')) Poincare disc model is supported via the parameter ``model``. Show a hyperbolic polygon in the Poincare disc model with coordinates `1`, `i`, `-1`, `-i`:: sage: hyperbolic_polygon([1,I,-1,-I], model="PD", color='green') Graphics object consisting of 2 graphics primitives .. PLOT:: sphinx_plot(hyperbolic_polygon([1,I,-1,-I], model="PD", color='green')) With more options:: sage: hyperbolic_polygon([1,I,-1,-I], model="PD", color='green', fill=True, linestyle="-") Graphics object consisting of 2 graphics primitives .. PLOT:: P = hyperbolic_polygon([1,I,-1,-I], model="PD", color='green', fill=True, linestyle="-") sphinx_plot(P) Klein model is also supported via the parameter ``model``. Show a hyperbolic polygon in the Klein model with coordinates `1`, `e^{i\pi/3}`, `e^{i2\pi/3}`, `-1`, `e^{i4\pi/3}`, `e^{i5\pi/3}`:: sage: p1 = 1 sage: p2 = (cos(pi/3), sin(pi/3)) sage: p3 = (cos(2*pi/3), sin(2*pi/3)) sage: p4 = -1 sage: p5 = (cos(4*pi/3), sin(4*pi/3)) sage: p6 = (cos(5*pi/3), sin(5*pi/3)) sage: hyperbolic_polygon([p1,p2,p3,p4,p5,p6], model="KM", fill=True, color='purple') Graphics object consisting of 2 graphics primitives .. PLOT:: p1=1 p2=(cos(pi/3),sin(pi/3)) p3=(cos(2*pi/3),sin(2*pi/3)) p4=-1 p5=(cos(4*pi/3),sin(4*pi/3)) p6=(cos(5*pi/3),sin(5*pi/3)) P = hyperbolic_polygon([p1,p2,p3,p4,p5,p6], model="KM", fill=True, color='purple') sphinx_plot(P) Hyperboloid model is supported partially, via the parameter ``model``. Show a hyperbolic polygon in the hyperboloid model with coordinates `(3,3,\sqrt(19))`, `(3,-3,\sqrt(19))`, `(-3,-3,\sqrt(19))`, `(-3,3,\sqrt(19))`:: sage: pts = [(3,3,sqrt(19)),(3,-3,sqrt(19)),(-3,-3,sqrt(19)),(-3,3,sqrt(19))] sage: hyperbolic_polygon(pts, model="HM") Graphics3d Object .. PLOT:: pts = [(3,3,sqrt(19)),(3,-3,sqrt(19)),(-3,-3,sqrt(19)),(-3,3,sqrt(19))] P = hyperbolic_polygon(pts, model="HM") sphinx_plot(P) Filling a hyperbolic_polygon in hyperboloid model is possible although jaggy. We show a filled hyperbolic polygon in the hyperboloid model with coordinates `(1,1,\sqrt(3))`, `(0,2,\sqrt(5))`, `(2,0,\sqrt(5))`. (The doctest is done at lower resolution than the picture below to give a faster result.) :: sage: pts = [(1,1,sqrt(3)), (0,2,sqrt(5)), (2,0,sqrt(5))] sage: hyperbolic_polygon(pts, model="HM", resolution=50, ....: color='yellow', fill=True) Graphics3d Object .. PLOT:: pts = [(1,1,sqrt(3)),(0,2,sqrt(5)),(2,0,sqrt(5))] P = hyperbolic_polygon(pts, model="HM", color='yellow', fill=True) sphinx_plot(P) """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) if model == "HM": from sage.geometry.hyperbolic_space.hyperbolic_interface import HyperbolicPlane from sage.plot.plot3d.implicit_plot3d import implicit_plot3d from sage.symbolic.ring import SR HM = HyperbolicPlane().HM() x, y, z = SR.var('x,y,z') arc_points = [] for i in range(0, len(pts) - 1): line = HM.get_geodesic(pts[i], pts[i + 1]) g = g + line.plot(color=options['rgbcolor'], thickness=options['thickness']) arc_points = arc_points + line._plot_vertices(resolution) line = HM.get_geodesic(pts[-1], pts[0]) g = g + line.plot(color=options['rgbcolor'], thickness=options['thickness']) arc_points = arc_points + line._plot_vertices(resolution) if options['fill']: xlist = [p[0] for p in pts] ylist = [p[1] for p in pts] zlist = [p[2] for p in pts] def region(x, y, z): return _winding_number(arc_points, (x, y, z)) != 0 g = g + implicit_plot3d(x**2 + y**2 - z**2 == -1, (x, min(xlist), max(xlist)), (y, min(ylist), max(ylist)), (z, 0, max(zlist)), region=region, plot_points=resolution, color=options['rgbcolor']) # the less points the more jaggy the picture else: g.add_primitive(HyperbolicPolygon(pts, model, options)) if model == "PD" or model == "KM": g = g + circle((0, 0), 1, rgbcolor='black') g.set_aspect_ratio(1) return g def hyperbolic_triangle(a, b, c, model="UHP", **options): r""" Return a hyperbolic triangle in the hyperbolic plane with vertices ``(a,b,c)``. Type ``?hyperbolic_polygon`` to see all options. INPUT: - ``a, b, c`` -- complex numbers in the upper half complex plane OPTIONS: - ``alpha`` -- default: 1 - ``fill`` -- default: ``False`` - ``thickness`` -- default: 1 - ``rgbcolor`` -- default: ``'blue'`` - ``linestyle`` -- (default: ``'solid'``) the style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively. EXAMPLES: Show a hyperbolic triangle with coordinates `0`, `1/2 + i\sqrt{3}/2` and `-1/2 + i\sqrt{3}/2`:: sage: hyperbolic_triangle(0, -1/2+I*sqrt(3)/2, 1/2+I*sqrt(3)/2) Graphics object consisting of 1 graphics primitive .. PLOT:: P = hyperbolic_triangle(0, 0.5*(-1+I*sqrt(3)), 0.5*(1+I*sqrt(3))) sphinx_plot(P) A hyperbolic triangle with coordinates `0`, `1` and `2+i` and a dashed line:: sage: hyperbolic_triangle(0, 1, 2+i, fill=true, rgbcolor='red', linestyle='--') Graphics object consisting of 1 graphics primitive .. PLOT:: P = hyperbolic_triangle(0, 1, 2+i, fill=true, rgbcolor='red', linestyle='--') sphinx_plot(P) A hyperbolic triangle with a vertex at `\infty`:: sage: hyperbolic_triangle(-5,Infinity,5) Graphics object consisting of 1 graphics primitive .. PLOT:: from sage.rings.infinity import infinity sphinx_plot(hyperbolic_triangle(-5,infinity,5)) It can also plot a hyperbolic triangle in the Poincaré disk model:: sage: z1 = CC((cos(pi/3),sin(pi/3))) sage: z2 = CC((0.6*cos(3*pi/4),0.6*sin(3*pi/4))) sage: z3 = 1 sage: hyperbolic_triangle(z1, z2, z3, model="PD", color="red") Graphics object consisting of 2 graphics primitives .. PLOT:: z1 = CC((cos(pi/3),sin(pi/3))) z2 = CC((0.6*cos(3*pi/4),0.6*sin(3*pi/4))) z3 = 1 P = hyperbolic_triangle(z1, z2, z3, model="PD", color="red") sphinx_plot(P) :: sage: hyperbolic_triangle(0.3+0.3*I, 0.8*I, -0.5-0.5*I, model="PD", color='magenta') Graphics object consisting of 2 graphics primitives .. PLOT:: P = hyperbolic_triangle(0.3+0.3*I, 0.8*I, -0.5-0.5*I, model="PD", color='magenta') sphinx_plot(P) """ return hyperbolic_polygon((a, b, c), model, **options)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/hyperbolic_polygon.py
0.919854
0.600628
hyperbolic_polygon.py
pypi
from sage.plot.primitive import GraphicPrimitive from sage.misc.decorators import options, rename_keyword from sage.plot.colors import to_mpl_color from math import sin, cos, pi class Disk(GraphicPrimitive): """ Primitive class for the ``Disk`` graphics type. See ``disk?`` for information about actually plotting a disk (the Sage term for a sector or wedge of a circle). INPUT: - ``point`` - coordinates of center of disk - ``r`` - radius of disk - ``angle`` - beginning and ending angles of disk (i.e. angle extent of sector/wedge) - ``options`` - dict of valid plot options to pass to constructor EXAMPLES: Note this should normally be used indirectly via ``disk``:: sage: from sage.plot.disk import Disk sage: D = Disk((1,2), 2, (pi/2,pi), {'zorder':3}) sage: D Disk defined by (1.0,2.0) with r=2.0 spanning (1.5707963267..., 3.1415926535...) radians sage: D.options()['zorder'] 3 sage: D.x 1.0 TESTS: We test creating a disk:: sage: disk((2,3), 2, (0,pi/2)) Graphics object consisting of 1 graphics primitive """ def __init__(self, point, r, angle, options): """ Initializes base class ``Disk``. EXAMPLES:: sage: D = disk((2,3), 1, (pi/2, pi), fill=False, color='red', thickness=1, alpha=.5) sage: D[0].x 2.0 sage: D[0].r 1.0 sage: D[0].rad1 1.5707963267948966 sage: D[0].options()['rgbcolor'] 'red' sage: D[0].options()['alpha'] 0.500000000000000 sage: print(loads(dumps(D))) Graphics object consisting of 1 graphics primitive """ self.x = float(point[0]) self.y = float(point[1]) self.r = float(r) self.rad1 = float(angle[0]) self.rad2 = float(angle[1]) GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Returns a dictionary with the bounding box data. EXAMPLES:: sage: D = disk((5,4), 1, (pi/2, pi)) sage: d = D.get_minmax_data() sage: d['xmin'] 4.0 sage: d['ymin'] 3.0 sage: d['xmax'] 6.0 sage: d['ymax'] 5.0 """ from sage.plot.plot import minmax_data return minmax_data([self.x - self.r, self.x + self.r], [self.y - self.r, self.y + self.r], dict=True) def _allowed_options(self): """ Return the allowed options for the ``Disk`` class. EXAMPLES:: sage: p = disk((3, 3), 1, (0, pi/2)) sage: p[0]._allowed_options()['alpha'] 'How transparent the figure is.' sage: p[0]._allowed_options()['zorder'] 'The layer level in which to draw' """ return {'alpha': 'How transparent the figure is.', 'fill': 'Whether or not to fill the disk.', 'legend_label': 'The label for this item in the legend.', 'legend_color': 'The color of the legend text.', 'thickness': 'How thick the border of the disk is.', 'rgbcolor': 'The color as an RGB tuple.', 'hue': 'The color given as a hue.', 'zorder': 'The layer level in which to draw'} def _repr_(self): """ String representation of ``Disk`` primitive. EXAMPLES:: sage: P = disk((3, 3), 1, (0, pi/2)) sage: p = P[0]; p Disk defined by (3.0,3.0) with r=1.0 spanning (0.0, 1.5707963267...) radians """ return "Disk defined by (%s,%s) with r=%s spanning (%s, %s) radians" % (self.x, self.y, self.r, self.rad1, self.rad2) def _render_on_subplot(self, subplot): """ TESTS:: sage: D = disk((2,-1), 2, (0, pi), color='black', thickness=3, fill=False); D Graphics object consisting of 1 graphics primitive Save alpha information in pdf (see :trac:`13732`):: sage: f = tmp_filename(ext='.pdf') sage: p = disk((0,0), 5, (0, pi/4), alpha=0.5) sage: p.save(f) """ import matplotlib.patches as patches options = self.options() deg1 = self.rad1*(180./pi) # convert radians to degrees deg2 = self.rad2*(180./pi) z = int(options.pop('zorder', 0)) p = patches.Wedge((float(self.x), float(self.y)), float(self.r), float(deg1), float(deg2), zorder=z) a = float(options['alpha']) p.set_alpha(a) p.set_linewidth(float(options['thickness'])) p.set_fill(options['fill']) c = to_mpl_color(options['rgbcolor']) p.set_edgecolor(c) p.set_facecolor(c) p.set_label(options['legend_label']) subplot.add_patch(p) def plot3d(self, z=0, **kwds): """ Plots a 2D disk (actually a 52-gon) in 3D, with default height zero. INPUT: - ``z`` - optional 3D height above `xy`-plane. AUTHORS: - Karl-Dieter Crisman (05-09) EXAMPLES:: sage: disk((0,0), 1, (0, pi/2)).plot3d() Graphics3d Object sage: disk((0,0), 1, (0, pi/2)).plot3d(z=2) Graphics3d Object sage: disk((0,0), 1, (pi/2, 0), fill=False).plot3d(3) Graphics3d Object These examples show that the appropriate options are passed:: sage: D = disk((2,3), 1, (pi/4,pi/3), hue=.8, alpha=.3, fill=True) sage: d = D[0] sage: d.plot3d(z=2).texture.opacity 0.3 :: sage: D = disk((2,3), 1, (pi/4,pi/3), hue=.8, alpha=.3, fill=False) sage: d = D[0] sage: dd = d.plot3d(z=2) sage: dd.jmol_repr(dd.testing_render_params())[0][-1] 'color $line_4 translucent 0.7 [204,0,255]' """ options = dict(self.options()) fill = options['fill'] del options['fill'] if 'zorder' in options: del options['zorder'] n = 50 x, y, r, rad1, rad2 = self.x, self.y, self.r, self.rad1, self.rad2 dt = float((rad2-rad1)/n) xdata = [x] ydata = [y] xdata.extend([x+r*cos(t*dt+rad1) for t in range(n+1)]) ydata.extend([y+r*sin(t*dt+rad1) for t in range(n+1)]) xdata.append(x) ydata.append(y) if fill: from .polygon import Polygon return Polygon(xdata, ydata, options).plot3d(z) else: from .line import Line return Line(xdata, ydata, options).plot3d().translate((0, 0, z)) @rename_keyword(color='rgbcolor') @options(alpha=1, fill=True, rgbcolor=(0, 0, 1), thickness=0, legend_label=None, aspect_ratio=1.0) def disk(point, radius, angle, **options): r""" A disk (that is, a sector or wedge of a circle) with center at a point = `(x,y)` (or `(x,y,z)` and parallel to the `xy`-plane) with radius = `r` spanning (in radians) angle=`(rad1, rad2)`. Type ``disk.options`` to see all options. EXAMPLES: Make some dangerous disks:: sage: bl = disk((0.0,0.0), 1, (pi, 3*pi/2), color='yellow') sage: tr = disk((0.0,0.0), 1, (0, pi/2), color='yellow') sage: tl = disk((0.0,0.0), 1, (pi/2, pi), color='black') sage: br = disk((0.0,0.0), 1, (3*pi/2, 2*pi), color='black') sage: P = tl+tr+bl+br sage: P.show(xmin=-2,xmax=2,ymin=-2,ymax=2) .. PLOT:: from sage.plot.disk import Disk bl = disk((0.0,0.0), 1, (pi, 3*pi/2), color='yellow') tr = disk((0.0,0.0), 1, (0, pi/2), color='yellow') tl = disk((0.0,0.0), 1, (pi/2, pi), color='black') br = disk((0.0,0.0), 1, (3*pi/2, 2*pi), color='black') P = tl+tr+bl+br sphinx_plot(P) The default aspect ratio is 1.0:: sage: disk((0.0,0.0), 1, (pi, 3*pi/2)).aspect_ratio() 1.0 Another example of a disk:: sage: bl = disk((0.0,0.0), 1, (pi, 3*pi/2), rgbcolor=(1,1,0)) sage: bl.show(figsize=[5,5]) .. PLOT:: from sage.plot.disk import Disk bl = disk((0.0,0.0), 1, (pi, 3*pi/2), rgbcolor=(1,1,0)) sphinx_plot(bl) Note that since ``thickness`` defaults to zero, it is best to change that option when using ``fill=False``:: sage: disk((2,3), 1, (pi/4,pi/3), hue=.8, alpha=.3, fill=False, thickness=2) Graphics object consisting of 1 graphics primitive .. PLOT:: from sage.plot.disk import Disk D = disk((2,3), 1, (pi/4,pi/3), hue=.8, alpha=.3, fill=False, thickness=2) sphinx_plot(D) The previous two examples also illustrate using ``hue`` and ``rgbcolor`` as ways of specifying the color of the graphic. We can also use this command to plot three-dimensional disks parallel to the `xy`-plane:: sage: d = disk((1,1,3), 1, (pi,3*pi/2), rgbcolor=(1,0,0)) sage: d Graphics3d Object sage: type(d) <... 'sage.plot.plot3d.index_face_set.IndexFaceSet'> .. PLOT:: from sage.plot.disk import Disk d = disk((1,1,3), 1, (pi,3*pi/2), rgbcolor=(1,0,0)) sphinx_plot(d) Extra options will get passed on to ``show()``, as long as they are valid:: sage: disk((0, 0), 5, (0, pi/2), xmin=0, xmax=5, ymin=0, ymax=5, figsize=(2,2), rgbcolor=(1, 0, 1)) Graphics object consisting of 1 graphics primitive sage: disk((0, 0), 5, (0, pi/2), rgbcolor=(1, 0, 1)).show(xmin=0, xmax=5, ymin=0, ymax=5, figsize=(2,2)) # These are equivalent TESTS: Testing that legend labels work right:: sage: disk((2,4), 3, (pi/8, pi/4), hue=1, legend_label='disk', legend_color='blue') Graphics object consisting of 1 graphics primitive We cannot currently plot disks in more than three dimensions:: sage: d = disk((1,1,1,1), 1, (0,pi)) Traceback (most recent call last): ... ValueError: the center point of a plotted disk should have two or three coordinates """ from sage.plot.all import Graphics g = Graphics() # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] if scale == 'semilogy' or scale == 'semilogx': options['aspect_ratio'] = 'automatic' g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) g.add_primitive(Disk(point, radius, angle, options)) if options['legend_label']: g.legend(True) g._legend_colors = [options['legend_color']] if len(point) == 2: return g elif len(point) == 3: return g[0].plot3d(z=point[2]) raise ValueError('the center point of a plotted disk should have ' 'two or three coordinates')
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/disk.py
0.929095
0.552841
disk.py
pypi
from sage.plot.primitive import GraphicPrimitive from sage.misc.decorators import options from sage.plot.colors import get_cmap from sage.arith.srange import xsrange class DensityPlot(GraphicPrimitive): """ Primitive class for the density plot graphics type. See ``density_plot?`` for help actually doing density plots. INPUT: - ``xy_data_array`` - list of lists giving evaluated values of the function on the grid - ``xrange`` - tuple of 2 floats indicating range for horizontal direction - ``yrange`` - tuple of 2 floats indicating range for vertical direction - ``options`` - dict of valid plot options to pass to constructor EXAMPLES: Note this should normally be used indirectly via ``density_plot``:: sage: from sage.plot.density_plot import DensityPlot sage: D = DensityPlot([[1,3],[2,4]], (1,2), (2,3),options={}) sage: D DensityPlot defined by a 2 x 2 data grid sage: D.yrange (2, 3) sage: D.options() {} TESTS: We test creating a density plot:: sage: x,y = var('x,y') sage: density_plot(x^2 - y^3 + 10*sin(x*y), (x,-4,4), (y,-4,4), plot_points=121, cmap='hsv') Graphics object consisting of 1 graphics primitive """ def __init__(self, xy_data_array, xrange, yrange, options): """ Initializes base class DensityPlot. EXAMPLES:: sage: x,y = var('x,y') sage: D = density_plot(x^2 - y^3 + 10*sin(x*y), (x,-4,4), (y,-4,4), plot_points=121, cmap='hsv') sage: D[0].xrange (-4.0, 4.0) sage: D[0].options()['plot_points'] 121 """ self.xrange = xrange self.yrange = yrange self.xy_data_array = xy_data_array self.xy_array_row = len(xy_data_array) self.xy_array_col = len(xy_data_array[0]) GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Returns a dictionary with the bounding box data. EXAMPLES:: sage: x,y = var('x,y') sage: f(x, y) = x^2 + y^2 sage: d = density_plot(f, (3,6), (3,6))[0].get_minmax_data() sage: d['xmin'] 3.0 sage: d['ymin'] 3.0 """ from sage.plot.plot import minmax_data return minmax_data(self.xrange, self.yrange, dict=True) def _allowed_options(self): """ Return the allowed options for the DensityPlot class. TESTS:: sage: isinstance(density_plot(x, (-2,3), (1,10))[0]._allowed_options(), dict) True """ return {'plot_points': 'How many points to use for plotting precision', 'cmap': """the name of a predefined colormap, a list of colors or an instance of a matplotlib Colormap. Type: import matplotlib.cm; matplotlib.cm.datad.keys() for available colormap names.""", 'interpolation': 'What interpolation method to use'} def _repr_(self): """ String representation of DensityrPlot primitive. EXAMPLES:: sage: x,y = var('x,y') sage: D = density_plot(x^2 - y^2, (x,-2,2), (y,-2,2)) sage: d = D[0]; d DensityPlot defined by a 25 x 25 data grid """ return "DensityPlot defined by a %s x %s data grid"%(self.xy_array_row, self.xy_array_col) def _render_on_subplot(self, subplot): """ TESTS: A somewhat random plot, but fun to look at:: sage: x,y = var('x,y') sage: density_plot(x^2 - y^3 + 10*sin(x*y), (x,-4,4), (y,-4,4), plot_points=121, cmap='hsv') Graphics object consisting of 1 graphics primitive """ options = self.options() cmap = get_cmap(options['cmap']) x0, x1 = float(self.xrange[0]), float(self.xrange[1]) y0, y1 = float(self.yrange[0]), float(self.yrange[1]) subplot.imshow(self.xy_data_array, origin='lower', cmap=cmap, extent=(x0,x1,y0,y1), interpolation=options['interpolation']) @options(plot_points=25, cmap='gray', interpolation='catrom') def density_plot(f, xrange, yrange, **options): r""" ``density_plot`` takes a function of two variables, `f(x,y)` and plots the height of the function over the specified ``xrange`` and ``yrange`` as demonstrated below. ``density_plot(f, (xmin,xmax), (ymin,ymax), ...)`` INPUT: - ``f`` -- a function of two variables - ``(xmin,xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin,ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` The following inputs must all be passed in as named parameters: - ``plot_points`` -- integer (default: 25); number of points to plot in each direction of the grid - ``cmap`` -- a colormap (default: ``'gray'``), the name of a predefined colormap, a list of colors or an instance of a matplotlib Colormap. Type: ``import matplotlib.cm; matplotlib.cm.datad.keys()`` for available colormap names. - ``interpolation`` -- string (default: ``'catrom'``), the interpolation method to use: ``'bilinear'``, ``'bicubic'``, ``'spline16'``, ``'spline36'``, ``'quadric'``, ``'gaussian'``, ``'sinc'``, ``'bessel'``, ``'mitchell'``, ``'lanczos'``, ``'catrom'``, ``'hermite'``, ``'hanning'``, ``'hamming'``, ``'kaiser'`` EXAMPLES: Here we plot a simple function of two variables. Note that since the input function is an expression, we need to explicitly declare the variables in 3-tuples for the range:: sage: x,y = var('x,y') sage: density_plot(sin(x) * sin(y), (x,-2,2), (y,-2,2)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = density_plot(sin(x) * sin(y), (x,-2,2), (y,-2,2)) sphinx_plot(g) Here we change the ranges and add some options; note that here ``f`` is callable (has variables declared), so we can use 2-tuple ranges:: sage: x,y = var('x,y') sage: f(x,y) = x^2 * cos(x*y) sage: density_plot(f, (x,-10,5), (y,-5,5), interpolation='sinc', plot_points=100) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 * cos(x*y) g = density_plot(f, (x,-10,5), (y,-5,5), interpolation='sinc', plot_points=100) sphinx_plot(g) An even more complicated plot:: sage: x,y = var('x,y') sage: density_plot(sin(x^2+y^2) * cos(x) * sin(y), (x,-4,4), (y,-4,4), cmap='jet', plot_points=100) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = density_plot(sin(x**2 + y**2)*cos(x)*sin(y), (x,-4,4), (y,-4,4), cmap='jet', plot_points=100) sphinx_plot(g) This should show a "spotlight" right on the origin:: sage: x,y = var('x,y') sage: density_plot(1/(x^10 + y^10), (x,-10,10), (y,-10,10)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = density_plot(1/(x**10 + y**10), (x,-10,10), (y,-10,10)) sphinx_plot(g) Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because we switch the variables `x`, `y`:: sage: density_plot(y^2 + 1 - x^3 - x, (y,-pi,pi), (x,-pi,pi)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = density_plot(y**2 + 1 - x**3 - x, (y,-pi,pi), (x,-pi,pi)) sphinx_plot(g) :: sage: density_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = density_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi)) sphinx_plot(g) Extra options will get passed on to show(), as long as they are valid:: sage: density_plot(log(x) + log(y), (x,1,10), (y,1,10), aspect_ratio=1) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = density_plot(log(x) + log(y), (x,1,10), (y,1,10), aspect_ratio=1) sphinx_plot(g) :: sage: density_plot(log(x) + log(y), (x,1,10), (y,1,10)).show(aspect_ratio=1) # These are equivalent TESTS: Check that :trac:`15315` is fixed, i.e., density_plot respects the ``aspect_ratio`` parameter. Without the fix, it looks like a thin line of width a few mm. With the fix it should look like a nice fat layered image:: sage: density_plot((x*y)^(1/2), (x,0,3), (y,0,500), aspect_ratio=.01) Graphics object consisting of 1 graphics primitive Default ``aspect_ratio`` is ``"automatic"``, and that should work too:: sage: density_plot((x*y)^(1/2), (x,0,3), (y,0,500)) Graphics object consisting of 1 graphics primitive Check that :trac:`17684` is fixed, i.e., symbolic values can be plotted:: sage: def f(x,y): ....: return SR(x) sage: density_plot(f, (0,1), (0,1)) Graphics object consisting of 1 graphics primitive """ from sage.plot.all import Graphics from sage.plot.misc import setup_for_eval_on_grid from sage.rings.real_double import RDF g, ranges = setup_for_eval_on_grid([f], [xrange, yrange], options['plot_points']) g = g[0] xrange, yrange = [r[:2] for r in ranges] xy_data_array = [[RDF(g(x,y)) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin','xmax'])) g.add_primitive(DensityPlot(xy_data_array, xrange, yrange, options)) return g
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/density_plot.py
0.947198
0.716801
density_plot.py
pypi
from .primitive import GraphicPrimitive from sage.misc.decorators import options, rename_keyword from sage.plot.colors import to_mpl_color from math import sin, cos, pi class Circle(GraphicPrimitive): """ Primitive class for the Circle graphics type. See circle? for information about actually plotting circles. INPUT: - x -- `x`-coordinate of center of Circle - y -- `y`-coordinate of center of Circle - r -- radius of Circle object - options -- dict of valid plot options to pass to constructor EXAMPLES: Note this should normally be used indirectly via ``circle``:: sage: from sage.plot.circle import Circle sage: C = Circle(2,3,5,{'zorder':2}) sage: C Circle defined by (2.0,3.0) with r=5.0 sage: C.options()['zorder'] 2 sage: C.r 5.0 TESTS: We test creating a circle:: sage: C = circle((2,3), 5) """ def __init__(self, x, y, r, options): """ Initializes base class Circle. EXAMPLES:: sage: C = circle((2,3), 5, edgecolor='red', alpha=.5, fill=True) sage: C[0].x 2.0 sage: C[0].r 5.0 sage: C[0].options()['edgecolor'] 'red' sage: C[0].options()['alpha'] 0.500000000000000 """ self.x = float(x) self.y = float(y) self.r = float(r) GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Returns a dictionary with the bounding box data. EXAMPLES:: sage: p = circle((3, 3), 1) sage: d = p.get_minmax_data() sage: d['xmin'] 2.0 sage: d['ymin'] 2.0 """ from sage.plot.plot import minmax_data return minmax_data([self.x - self.r, self.x + self.r], [self.y - self.r, self.y + self.r], dict=True) def _allowed_options(self): """ Return the allowed options for the Circle class. EXAMPLES:: sage: p = circle((3, 3), 1) sage: p[0]._allowed_options()['alpha'] 'How transparent the figure is.' sage: p[0]._allowed_options()['facecolor'] '2D only: The color of the face as an RGB tuple.' """ return {'alpha': 'How transparent the figure is.', 'fill': 'Whether or not to fill the circle.', 'legend_label': 'The label for this item in the legend.', 'legend_color': 'The color of the legend text.', 'thickness': 'How thick the border of the circle is.', 'edgecolor': '2D only: The color of the edge as an RGB tuple.', 'facecolor': '2D only: The color of the face as an RGB tuple.', 'rgbcolor': 'The color (edge and face) as an RGB tuple.', 'hue': 'The color given as a hue.', 'zorder': '2D only: The layer level in which to draw', 'linestyle': "2D only: The style of the line, which is one of " "'dashed', 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.', " "respectively.", 'clip': 'Whether or not to clip the circle.'} def _repr_(self): """ String representation of Circle primitive. EXAMPLES:: sage: C = circle((2,3), 5) sage: c = C[0]; c Circle defined by (2.0,3.0) with r=5.0 """ return "Circle defined by (%s,%s) with r=%s"%(self.x, self.y, self.r) def _render_on_subplot(self, subplot): """ TESTS:: sage: C = circle((2,pi), 2, edgecolor='black', facecolor='green', fill=True) """ import matplotlib.patches as patches from sage.plot.misc import get_matplotlib_linestyle options = self.options() p = patches.Circle((float(self.x), float(self.y)), float(self.r), clip_on=options['clip']) if not options['clip']: self._bbox_extra_artists=[p] p.set_linewidth(float(options['thickness'])) p.set_fill(options['fill']) a = float(options['alpha']) p.set_alpha(a) ec = to_mpl_color(options['edgecolor']) fc = to_mpl_color(options['facecolor']) if 'rgbcolor' in options: ec = fc = to_mpl_color(options['rgbcolor']) p.set_edgecolor(ec) p.set_facecolor(fc) p.set_linestyle(get_matplotlib_linestyle(options['linestyle'],return_type='long')) p.set_label(options['legend_label']) z = int(options.pop('zorder', 0)) p.set_zorder(z) subplot.add_patch(p) def plot3d(self, z=0, **kwds): """ Plots a 2D circle (actually a 50-gon) in 3D, with default height zero. INPUT: - ``z`` - optional 3D height above `xy`-plane. EXAMPLES:: sage: circle((0,0), 1).plot3d() Graphics3d Object This example uses this method implicitly, but does not pass the optional parameter z to this method:: sage: sum([circle((random(),random()), random()).plot3d(z=random()) for _ in range(20)]) Graphics3d Object .. PLOT:: P = sum([circle((random(),random()), random()).plot3d(z=random()) for _ in range(20)]) sphinx_plot(P) These examples are explicit, and pass z to this method:: sage: C = circle((2,pi), 2, hue=.8, alpha=.3, fill=True) sage: c = C[0] sage: d = c.plot3d(z=2) sage: d.texture.opacity 0.3 :: sage: C = circle((2,pi), 2, hue=.8, alpha=.3, linestyle='dotted') sage: c = C[0] sage: d = c.plot3d(z=2) sage: d.jmol_repr(d.testing_render_params())[0][-1] 'color $line_1 translucent 0.7 [204,0,255]' """ options = dict(self.options()) fill = options['fill'] for s in ['clip', 'edgecolor', 'facecolor', 'fill', 'linestyle', 'zorder']: if s in options: del options[s] n = 50 dt = float(2*pi/n) x, y, r = self.x, self.y, self.r xdata = [x+r*cos(t*dt) for t in range(n+1)] ydata = [y+r*sin(t*dt) for t in range(n+1)] if fill: from .polygon import Polygon return Polygon(xdata, ydata, options).plot3d(z) else: from .line import Line return Line(xdata, ydata, options).plot3d().translate((0,0,z)) @rename_keyword(color='rgbcolor') @options(alpha=1, fill=False, thickness=1, edgecolor='blue', facecolor='blue', linestyle='solid', zorder=5, legend_label=None, legend_color=None, clip=True, aspect_ratio=1.0) def circle(center, radius, **options): """ Return a circle at a point center = `(x,y)` (or `(x,y,z)` and parallel to the `xy`-plane) with radius = `r`. Type ``circle.options`` to see all options. OPTIONS: - ``alpha`` - default: 1 - ``fill`` - default: False - ``thickness`` - default: 1 - ``linestyle`` - default: ``'solid'`` (2D plotting only) The style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively. - ``edgecolor`` - default: 'blue' (2D plotting only) - ``facecolor`` - default: 'blue' (2D plotting only, useful only if ``fill=True``) - ``rgbcolor`` - 2D or 3D plotting. This option overrides ``edgecolor`` and ``facecolor`` for 2D plotting. - ``legend_label`` - the label for this item in the legend - ``legend_color`` - the color for the legend label EXAMPLES: The default color is blue, the default linestyle is solid, but this is easy to change:: sage: c = circle((1,1), 1) sage: c Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(circle((1,1), 1)) :: sage: c = circle((1,1), 1, rgbcolor=(1,0,0), linestyle='-.') sage: c Graphics object consisting of 1 graphics primitive .. PLOT:: c = circle((1,1), 1, rgbcolor=(1,0,0), linestyle='-.') sphinx_plot(c) We can also use this command to plot three-dimensional circles parallel to the `xy`-plane:: sage: c = circle((1,1,3), 1, rgbcolor=(1,0,0)) sage: c Graphics3d Object sage: type(c) <class 'sage.plot.plot3d.base.TransformGroup'> .. PLOT:: c = circle((1,1,3), 1, rgbcolor=(1,0,0)) sphinx_plot(c) To correct the aspect ratio of certain graphics, it is necessary to show with a ``figsize`` of square dimensions:: sage: c.show(figsize=[5,5],xmin=-1,xmax=3,ymin=-1,ymax=3) Here we make a more complicated plot, with many circles of different colors:: sage: g = Graphics() sage: step=6; ocur=1/5; paths=16 sage: PI = math.pi # numerical for speed -- fine for graphics sage: for r in range(1,paths+1): ....: for x,y in [((r+ocur)*math.cos(n), (r+ocur)*math.sin(n)) for n in srange(0, 2*PI+PI/step, PI/step)]: ....: g += circle((x,y), ocur, rgbcolor=hue(r/paths)) ....: rnext = (r+1)^2 ....: ocur = (rnext-r)-ocur sage: g.show(xmin=-(paths+1)^2, xmax=(paths+1)^2, ymin=-(paths+1)^2, ymax=(paths+1)^2, figsize=[6,6]) .. PLOT:: g = Graphics() step=6; ocur=1/5; paths=16; PI = math.pi # numerical for speed -- fine for graphics for r in range(1,paths+1): for x,y in [((r+ocur)*math.cos(n), (r+ocur)*math.sin(n)) for n in srange(0, 2*PI+PI/step, PI/step)]: g += circle((x,y), ocur, rgbcolor=hue(r*1.0/paths)) rnext = (r+1)**2 ocur = (rnext-r)-ocur g.set_axes_range(-(paths+1)**2,(paths+1)**2,-(paths+1)**2,(paths+1)**2) sphinx_plot(g) Note that the ``rgbcolor`` option overrides the other coloring options. This produces red fill in a blue circle:: sage: circle((2,3), 1, fill=True, edgecolor='blue', facecolor='red') Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(circle((2,3), 1, fill=True, edgecolor='blue', facecolor='red')) This produces an all-green filled circle:: sage: circle((2,3), 1, fill=True, edgecolor='blue', rgbcolor='green') Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(circle((2,3), 1, fill=True, edgecolor='blue', rgbcolor='green')) The option ``hue`` overrides *all* other options, so be careful with its use. This produces a purplish filled circle:: sage: circle((2,3), 1, fill=True, edgecolor='blue', rgbcolor='green', hue=.8) Graphics object consisting of 1 graphics primitive .. PLOT:: C = circle((2,3), 1, fill=True, edgecolor='blue', rgbcolor='green', hue=.8) sphinx_plot(C) And circles with legends:: sage: circle((4,5), 1, rgbcolor='yellow', fill=True, legend_label='the sun').show(xmin=0, ymin=0) .. PLOT:: C = circle((4,5), 1, rgbcolor='yellow', fill=True, legend_label='the sun') C.set_axes_range(xmin=0, ymin=0) sphinx_plot(C) :: sage: circle((4,5), 1, legend_label='the sun', legend_color='yellow').show(xmin=0, ymin=0) .. PLOT:: C = circle((4,5), 1, legend_label='the sun', legend_color='yellow') C.set_axes_range(xmin=0, ymin=0) sphinx_plot(C) Extra options will get passed on to show(), as long as they are valid:: sage: circle((0, 0), 2, figsize=[10,10]) # That circle is huge! Graphics object consisting of 1 graphics primitive :: sage: circle((0, 0), 2).show(figsize=[10,10]) # These are equivalent TESTS: We cannot currently plot circles in more than three dimensions:: sage: circle((1,1,1,1), 1, rgbcolor=(1,0,0)) Traceback (most recent call last): ... ValueError: the center of a plotted circle should have two or three coordinates The default aspect ratio for a circle is 1.0:: sage: P = circle((1,1), 1) sage: P.aspect_ratio() 1.0 """ from sage.plot.all import Graphics # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] if scale == 'semilogy' or scale == 'semilogx': options['aspect_ratio'] = 'automatic' g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) g.add_primitive(Circle(center[0], center[1], radius, options)) if options['legend_label']: g.legend(True) g._legend_colors = [options['legend_color']] if len(center) == 2: return g elif len(center) == 3: return g[0].plot3d(z=center[2]) raise ValueError('the center of a plotted circle should have ' 'two or three coordinates')
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/circle.py
0.928368
0.519156
circle.py
pypi
from sage.plot.line import line def plot_step_function(v, vertical_lines=True, **kwds): r""" Return the line graphics object that gives the plot of the step function `f` defined by the list `v` of pairs `(a,b)`. Here if `(a,b)` is in `v`, then `f(a) = b`. The user does not have to worry about sorting the input list `v`. INPUT: - ``v`` -- list of pairs (a,b) - ``vertical_lines`` -- bool (default: True) if True, draw vertical risers at each step of this step function. Technically these vertical lines are not part of the graph of this function, but they look very nice in the plot so we include them by default EXAMPLES: We plot the prime counting function:: sage: plot_step_function([(i, prime_pi(i)) for i in range(20)]) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(plot_step_function([(i, prime_pi(i)) for i in range(20)])) :: sage: plot_step_function([(i, sin(i)) for i in range(5, 20)]) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(plot_step_function([(i, sin(i)) for i in range(5, 20)])) We pass in many options and get something that looks like "Space Invaders":: sage: v = [(i, sin(i)) for i in range(5, 20)] sage: plot_step_function(v, vertical_lines=False, thickness=30, rgbcolor='purple', axes=False) Graphics object consisting of 14 graphics primitives .. PLOT:: v = [(i, sin(i)) for i in range(5, 20)] sphinx_plot(plot_step_function(v, vertical_lines=False, thickness=30, rgbcolor='purple', axes=False)) """ # make sorted copy of v (don't change in place, since that would be rude). v = sorted(v) if len(v) <= 1: return line([]) # empty line if vertical_lines: w = [] for i in range(len(v)): w.append(v[i]) if i+1 < len(v): w.append((v[i+1][0], v[i][1])) return line(w, **kwds) else: return sum(line([v[i], (v[i+1][0], v[i][1])], **kwds) for i in range(len(v)-1))
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/step.py
0.797044
0.590159
step.py
pypi
from sage.ext.fast_callable import FastCallableFloatWrapper from collections.abc import Iterable def setup_for_eval_on_grid(funcs, ranges, plot_points=None, return_vars=False, imaginary_tolerance=1e-8): r""" Calculate the necessary parameters to construct a list of points, and make the functions fast_callable. INPUT: - ``funcs`` -- a function, or a list, tuple, or vector of functions - ``ranges`` -- a list of ranges. A range can be a 2-tuple of numbers specifying the minimum and maximum, or a 3-tuple giving the variable explicitly. - ``plot_points`` -- a tuple of integers specifying the number of plot points for each range. If a single number is specified, it will be the value for all ranges. This defaults to 2. - ``return_vars`` -- (default ``False``) If ``True``, return the variables, in order. - ``imaginary_tolerance`` -- (default: ``1e-8``); if an imaginary number arises (due, for example, to numerical issues), this tolerance specifies how large it has to be in magnitude before we raise an error. In other words, imaginary parts smaller than this are ignored in your plot points. OUTPUT: - ``fast_funcs`` - if only one function passed, then a fast callable function. If funcs is a list or tuple, then a tuple of fast callable functions is returned. - ``range_specs`` - a list of range_specs: for each range, a tuple is returned of the form (range_min, range_max, range_step) such that ``srange(range_min, range_max, range_step, include_endpoint=True)`` gives the correct points for evaluation. EXAMPLES:: sage: x,y,z=var('x,y,z') sage: f(x,y)=x+y-z sage: g(x,y)=x+y sage: h(y)=-y sage: sage.plot.misc.setup_for_eval_on_grid(f, [(0, 2),(1,3),(-4,1)], plot_points=5) (<sage...>, [(0.0, 2.0, 0.5), (1.0, 3.0, 0.5), (-4.0, 1.0, 1.25)]) sage: sage.plot.misc.setup_for_eval_on_grid([g,h], [(0, 2),(-1,1)], plot_points=5) ((<sage...>, <sage...>), [(0.0, 2.0, 0.5), (-1.0, 1.0, 0.5)]) sage: sage.plot.misc.setup_for_eval_on_grid([sin,cos], [(-1,1)], plot_points=9) ((<sage...>, <sage...>), [(-1.0, 1.0, 0.25)]) sage: sage.plot.misc.setup_for_eval_on_grid([lambda x: x^2,cos], [(-1,1)], plot_points=9) ((<function <lambda> ...>, <sage...>), [(-1.0, 1.0, 0.25)]) sage: sage.plot.misc.setup_for_eval_on_grid([x+y], [(x,-1,1),(y,-2,2)]) ((<sage...>,), [(-1.0, 1.0, 2.0), (-2.0, 2.0, 4.0)]) sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,-1,1),(y,-1,1)], plot_points=[4,9]) (<sage...>, [(-1.0, 1.0, 0.6666666666666666), (-1.0, 1.0, 0.25)]) sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,-1,1),(y,-1,1)], plot_points=[4,9,10]) Traceback (most recent call last): ... ValueError: plot_points must be either an integer or a list of integers, one for each range sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(1,-1),(y,-1,1)], plot_points=[4,9,10]) Traceback (most recent call last): ... ValueError: Some variable ranges specify variables while others do not Beware typos: a comma which should be a period, for instance:: sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x, 1, 2), (y, 0,1, 0.2)], plot_points=[4,9,10]) Traceback (most recent call last): ... ValueError: At least one variable range has more than 3 entries: each should either have 2 or 3 entries, with one of the forms (xmin, xmax) or (x, xmin, xmax) sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(y,1,-1),(x,-1,1)], plot_points=5) (<sage...>, [(1.0, -1.0, 0.5), (-1.0, 1.0, 0.5)]) sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,1,-1),(x,-1,1)], plot_points=5) Traceback (most recent call last): ... ValueError: range variables should be distinct, but there are duplicates sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,1,1),(y,-1,1)]) Traceback (most recent call last): ... ValueError: plot start point and end point must be different sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,1,-1),(y,-1,1)], return_vars=True) (<sage...>, [(1.0, -1.0, 2.0), (-1.0, 1.0, 2.0)], [x, y]) sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(y,1,-1),(x,-1,1)], return_vars=True) (<sage...>, [(1.0, -1.0, 2.0), (-1.0, 1.0, 2.0)], [y, x]) TESTS: Ensure that we can plot expressions with intermediate complex terms as in :trac:`8450`:: sage: x, y = SR.var('x y') sage: contour_plot(abs(x+i*y), (x,-1,1), (y,-1,1)) Graphics object consisting of 1 graphics primitive sage: density_plot(abs(x+i*y), (x,-1,1), (y,-1,1)) Graphics object consisting of 1 graphics primitive sage: plot3d(abs(x+i*y), (x,-1,1),(y,-1,1)) Graphics3d Object sage: streamline_plot(abs(x+i*y), (x,-1,1),(y,-1,1)) Graphics object consisting of 1 graphics primitive """ if max(map(len, ranges)) > 3: raise ValueError("At least one variable range has more than 3 entries: each should either have 2 or 3 entries, with one of the forms (xmin, xmax) or (x, xmin, xmax)") if max(map(len, ranges)) != min(map(len, ranges)): raise ValueError("Some variable ranges specify variables while others do not") if len(ranges[0]) == 3: vars = [r[0] for r in ranges] ranges = [r[1:] for r in ranges] if len(set(vars)) < len(vars): raise ValueError("range variables should be distinct, but there are duplicates") else: vars, free_vars = unify_arguments(funcs) # pad the variables if we don't have enough nargs = len(ranges) if len(vars) < nargs: vars += ('_',)*(nargs-len(vars)) ranges = [[float(z) for z in r] for r in ranges] if plot_points is None: plot_points = 2 if not isinstance(plot_points, (list, tuple)): plot_points = [plot_points]*len(ranges) elif len(plot_points) != nargs: raise ValueError("plot_points must be either an integer or a list of integers, one for each range") plot_points = [int(p) if p >= 2 else 2 for p in plot_points] range_steps = [abs(range[1] - range[0])/(p-1) for range, p in zip(ranges, plot_points)] if min(range_steps) == float(0): raise ValueError("plot start point and end point must be different") eov = False # eov = "expect one value" if nargs == 1: eov = True from sage.ext.fast_callable import fast_callable def try_make_fast(f): # If "f" supports fast_callable(), use it. We can't guarantee # that our arguments will actually support fast_callable() # because, for example, the user may already have done it # himself, and the result of fast_callable() can't be # fast-callabled again. from sage.rings.complex_double import CDF from sage.ext.interpreters.wrapper_cdf import Wrapper_cdf if hasattr(f, '_fast_callable_'): ff = fast_callable(f, vars=vars, expect_one_var=eov, domain=CDF) return FastCallablePlotWrapper(ff, imag_tol=imaginary_tolerance) elif isinstance(f, Wrapper_cdf): # Already a fast-callable, just wrap it. This can happen # if, for example, a symbolic expression is passed to a # higher-level plot() function that converts it to a # fast-callable with expr._plot_fast_callable() before # we ever see it. return FastCallablePlotWrapper(f, imag_tol=imaginary_tolerance) elif callable(f): # This will catch python functions, among other things. We don't # wrap these yet because we don't know what type they'll return. return f else: # Convert things like ZZ(0) into constant functions. from sage.symbolic.ring import SR ff = fast_callable(SR(f), vars=vars, expect_one_var=eov, domain=CDF) return FastCallablePlotWrapper(ff, imag_tol=imaginary_tolerance) # Handle vectors, lists, tuples, etc. if isinstance(funcs, Iterable): funcs = tuple( try_make_fast(f) for f in funcs ) else: funcs = try_make_fast(funcs) #TODO: raise an error if there is a function/method in funcs that takes more values than we have ranges if return_vars: return (funcs, [tuple(_range + [range_step]) for _range, range_step in zip(ranges, range_steps)], vars) else: return (funcs, [tuple(_range + [range_step]) for _range, range_step in zip(ranges, range_steps)]) def unify_arguments(funcs): """ Return a tuple of variables of the functions, as well as the number of "free" variables (i.e., variables that defined in a callable function). INPUT: - ``funcs`` -- a list of functions; these can be symbolic expressions, polynomials, etc OUTPUT: functions, expected arguments - A tuple of variables in the functions - A tuple of variables that were "free" in the functions EXAMPLES:: sage: x,y,z=var('x,y,z') sage: f(x,y)=x+y-z sage: g(x,y)=x+y sage: h(y)=-y sage: sage.plot.misc.unify_arguments((f,g,h)) ((x, y, z), (z,)) sage: sage.plot.misc.unify_arguments((g,h)) ((x, y), ()) sage: sage.plot.misc.unify_arguments((f,z)) ((x, y, z), (z,)) sage: sage.plot.misc.unify_arguments((h,z)) ((y, z), (z,)) sage: sage.plot.misc.unify_arguments((x+y,x-y)) ((x, y), (x, y)) """ vars=set() free_variables=set() if not isinstance(funcs, (list, tuple)): funcs = [funcs] from sage.structure.element import Expression for f in funcs: if isinstance(f, Expression) and f.is_callable(): f_args = set(f.arguments()) vars.update(f_args) else: f_args = set() try: free_vars = set(f.variables()).difference(f_args) vars.update(free_vars) free_variables.update(free_vars) except AttributeError: # we probably have a constant pass return tuple(sorted(vars, key=str)), tuple(sorted(free_variables, key=str)) def _multiple_of_constant(n, pos, const): r""" Function for internal use in formatting ticks on axes with nice-looking multiples of various symbolic constants, such as `\pi` or `e`. Should only be used via keyword argument `tick_formatter` in :meth:`plot.show`. See documentation for the matplotlib.ticker module for more details. EXAMPLES: Here is the intended use:: sage: plot(sin(x), (x,0,2*pi), ticks=pi/3, tick_formatter=pi) Graphics object consisting of 1 graphics primitive Here is an unintended use, which yields unexpected (and probably undesired) results:: sage: plot(x^2, (x, -2, 2), tick_formatter=pi) Graphics object consisting of 1 graphics primitive We can also use more unusual constant choices:: sage: plot(ln(x), (x,0,10), ticks=e, tick_formatter=e) Graphics object consisting of 1 graphics primitive sage: plot(x^2, (x,0,10), ticks=[sqrt(2),8], tick_formatter=sqrt(2)) Graphics object consisting of 1 graphics primitive """ from sage.misc.latex import latex from sage.rings.continued_fraction import continued_fraction from sage.rings.infinity import Infinity cf = continued_fraction(n/const) k = 1 while cf.quotient(k) != Infinity and cf.denominator(k) < 12: k += 1 return '$%s$'%latex(cf.convergent(k-1)*const) def get_matplotlib_linestyle(linestyle, return_type): """ Function which translates between matplotlib linestyle in short notation (i.e. '-', '--', ':', '-.') and long notation (i.e. 'solid', 'dashed', 'dotted', 'dashdot' ). If linestyle is none of these allowed options, the function raises a ValueError. INPUT: - ``linestyle`` - The style of the line, which is one of - ``"-"`` or ``"solid"`` - ``"--"`` or ``"dashed"`` - ``"-."`` or ``"dash dot"`` - ``":"`` or ``"dotted"`` - ``"None"`` or ``" "`` or ``""`` (nothing) The linestyle can also be prefixed with a drawing style (e.g., ``"steps--"``) - ``"default"`` (connect the points with straight lines) - ``"steps"`` or ``"steps-pre"`` (step function; horizontal line is to the left of point) - ``"steps-mid"`` (step function; points are in the middle of horizontal lines) - ``"steps-post"`` (step function; horizontal line is to the right of point) If ``linestyle`` is ``None`` (of type NoneType), then we return it back unmodified. - ``return_type`` - The type of linestyle that should be output. This argument takes only two values - ``"long"`` or ``"short"``. EXAMPLES: Here is an example how to call this function:: sage: from sage.plot.misc import get_matplotlib_linestyle sage: get_matplotlib_linestyle(':', return_type='short') ':' sage: get_matplotlib_linestyle(':', return_type='long') 'dotted' TESTS: Make sure that if the input is already in the desired format, then it is unchanged:: sage: get_matplotlib_linestyle(':', 'short') ':' Empty linestyles should be handled properly:: sage: get_matplotlib_linestyle("", 'short') '' sage: get_matplotlib_linestyle("", 'long') 'None' sage: get_matplotlib_linestyle(None, 'short') is None True Linestyles with ``"default"`` or ``"steps"`` in them should also be properly handled. For instance, matplotlib understands only the short version when ``"steps"`` is used:: sage: get_matplotlib_linestyle("default", "short") '' sage: get_matplotlib_linestyle("steps--", "short") 'steps--' sage: get_matplotlib_linestyle("steps-predashed", "long") 'steps-pre--' Finally, raise error on invalid linestyles:: sage: get_matplotlib_linestyle("isthissage", "long") Traceback (most recent call last): ... ValueError: WARNING: Unrecognized linestyle 'isthissage'. Possible linestyle options are: {'solid', 'dashed', 'dotted', dashdot', 'None'}, respectively {'-', '--', ':', '-.', ''} """ long_to_short_dict={'solid' : '-','dashed' : '--', 'dotted' : ':', 'dashdot':'-.'} short_to_long_dict={'-' : 'solid','--' : 'dashed', ':' : 'dotted', '-.':'dashdot'} # We need this to take care of region plot. Essentially, if None is # passed, then we just return back the same thing. if linestyle is None: return None if linestyle.startswith("default"): return get_matplotlib_linestyle(linestyle.strip("default"), "short") elif linestyle.startswith("steps"): if linestyle.startswith("steps-mid"): return "steps-mid" + get_matplotlib_linestyle( linestyle.strip("steps-mid"), "short") elif linestyle.startswith("steps-post"): return "steps-post" + get_matplotlib_linestyle( linestyle.strip("steps-post"), "short") elif linestyle.startswith("steps-pre"): return "steps-pre" + get_matplotlib_linestyle( linestyle.strip("steps-pre"), "short") else: return "steps" + get_matplotlib_linestyle( linestyle.strip("steps"), "short") if return_type == 'short': if linestyle in short_to_long_dict.keys(): return linestyle elif linestyle == "" or linestyle == " " or linestyle == "None": return '' elif linestyle in long_to_short_dict.keys(): return long_to_short_dict[linestyle] else: raise ValueError("WARNING: Unrecognized linestyle '%s'. " "Possible linestyle options are:\n{'solid', " "'dashed', 'dotted', dashdot', 'None'}, " "respectively {'-', '--', ':', '-.', ''}"% (linestyle)) elif return_type == 'long': if linestyle in long_to_short_dict.keys(): return linestyle elif linestyle == "" or linestyle == " " or linestyle == "None": return "None" elif linestyle in short_to_long_dict.keys(): return short_to_long_dict[linestyle] else: raise ValueError("WARNING: Unrecognized linestyle '%s'. " "Possible linestyle options are:\n{'solid', " "'dashed', 'dotted', dashdot', 'None'}, " "respectively {'-', '--', ':', '-.', ''}"% (linestyle)) class FastCallablePlotWrapper(FastCallableFloatWrapper): r""" A fast-callable wrapper for plotting that returns ``nan`` instead of raising an error whenever the imaginary tolerance is exceeded. A detailed rationale for this can be found in the superclass documentation. EXAMPLES: The ``float`` incarnation of "not a number" is returned instead of an error being thrown if the answer is complex:: sage: from sage.plot.misc import FastCallablePlotWrapper sage: f = sqrt(x) sage: ff = fast_callable(f, vars=[x], domain=CDF) sage: fff = FastCallablePlotWrapper(ff, imag_tol=1e-8) sage: fff(1) 1.0 sage: fff(-1) nan """ def __call__(self, *args): r""" Evaluate the underlying fast-callable and convert the result to ``float``. TESTS: Evaluation never fails and always returns a ``float``:: sage: from sage.plot.misc import FastCallablePlotWrapper sage: f = x sage: ff = fast_callable(f, vars=[x], domain=CDF) sage: fff = FastCallablePlotWrapper(ff, imag_tol=0.1) sage: type(fff(CDF.random_element())) is float True """ try: return super().__call__(*args) except ValueError: return float("nan")
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/misc.py
0.884611
0.536434
misc.py
pypi
from sage.plot.primitive import GraphicPrimitive from sage.misc.decorators import options from sage.arith.srange import xsrange # Below is the base class that is used to make 'field plots'. # Its implementation is motivated by 'PlotField'. # Currently it is used to make the functions 'plot_vector_field' # and 'plot_slope_field'. # TODO: use this to make these functions: # 'plot_gradient_field' and 'plot_hamiltonian_field' class PlotField(GraphicPrimitive): """ Primitive class that initializes the PlotField graphics type """ def __init__(self, xpos_array, ypos_array, xvec_array, yvec_array, options): """ Create the graphics primitive PlotField. This sets options and the array to be plotted as attributes. EXAMPLES:: sage: x,y = var('x,y') sage: R=plot_slope_field(x + y, (x,0,1), (y,0,1), plot_points=2) sage: r=R[0] sage: r.options()['headaxislength'] 0 sage: r.xpos_array [0.0, 0.0, 1.0, 1.0] sage: r.yvec_array masked_array(data=[0.0, 0.70710678118..., 0.70710678118..., 0.89442719...], mask=[False, False, False, False], fill_value=1e+20) TESTS: We test dumping and loading a plot:: sage: x,y = var('x,y') sage: P = plot_vector_field((sin(x),cos(y)), (x,-3,3), (y,-3,3)) sage: Q = loads(dumps(P)) """ self.xpos_array = xpos_array self.ypos_array = ypos_array self.xvec_array = xvec_array self.yvec_array = yvec_array GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Returns a dictionary with the bounding box data. EXAMPLES:: sage: x,y = var('x,y') sage: d = plot_vector_field((.01*x,x+y), (x,10,20), (y,10,20))[0].get_minmax_data() sage: d['xmin'] 10.0 sage: d['ymin'] 10.0 """ from sage.plot.plot import minmax_data return minmax_data(self.xpos_array, self.ypos_array, dict=True) def _allowed_options(self): """ Returns a dictionary with allowed options for PlotField. EXAMPLES:: sage: x,y = var('x,y') sage: P=plot_vector_field((sin(x),cos(y)), (x,-3,3), (y,-3,3)) sage: d=P[0]._allowed_options() sage: d['pivot'] 'Where the arrow should be placed in relation to the point (tail, middle, tip)' """ return {'plot_points': 'How many points to use for plotting precision', 'pivot': 'Where the arrow should be placed in relation to the point (tail, middle, tip)', 'headwidth': 'Head width as multiple of shaft width, default is 3', 'headlength': 'head length as multiple of shaft width, default is 5', 'headaxislength': 'head length at shaft intersection, default is 4.5', 'zorder': 'The layer level in which to draw', 'color': 'The color of the arrows'} def _repr_(self): """ String representation of PlotField graphics primitive. EXAMPLES:: sage: x,y = var('x,y') sage: P=plot_vector_field((sin(x),cos(y)), (x,-3,3), (y,-3,3)) sage: P[0] PlotField defined by a 20 x 20 vector grid TESTS: We check that :trac:`15052` is fixed (note that in general :trac:`15002` should be fixed):: sage: x,y=var('x,y') sage: P=plot_vector_field((sin(x), cos(y)), (x,-3,3), (y,-3,3), wrong_option='nonsense') sage: P[0].options()['plot_points'] verbose 0 (...: primitive.py, options) WARNING: Ignoring option 'wrong_option'=nonsense verbose 0 (...: primitive.py, options) The allowed options for PlotField defined by a 20 x 20 vector grid are: color The color of the arrows headaxislength head length at shaft intersection, default is 4.5 headlength head length as multiple of shaft width, default is 5 headwidth Head width as multiple of shaft width, default is 3 pivot Where the arrow should be placed in relation to the point (tail, middle, tip) plot_points How many points to use for plotting precision zorder The layer level in which to draw <BLANKLINE> 20 """ return "PlotField defined by a %s x %s vector grid"%( self._options['plot_points'], self._options['plot_points']) def _render_on_subplot(self, subplot): """ TESTS:: sage: x,y = var('x,y') sage: P=plot_vector_field((sin(x),cos(y)), (x,-3,3), (y,-3,3)) """ options = self.options() quiver_options = options.copy() quiver_options.pop('plot_points') subplot.quiver(self.xpos_array, self.ypos_array, self.xvec_array, self.yvec_array, angles='xy', **quiver_options) @options(plot_points=20, frame=True) def plot_vector_field(f_g, xrange, yrange, **options): r""" ``plot_vector_field`` takes two functions of two variables xvar and yvar (for instance, if the variables are `x` and `y`, take `(f(x,y), g(x,y))`) and plots vector arrows of the function over the specified ranges, with xrange being of xvar between xmin and xmax, and yrange similarly (see below). ``plot_vector_field((f,g), (xvar,xmin,xmax), (yvar,ymin,ymax))`` EXAMPLES: Plot some vector fields involving sin and cos:: sage: x,y = var('x y') sage: plot_vector_field((sin(x),cos(y)), (x,-3,3), (y,-3,3)) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y = var('x y') g = plot_vector_field((sin(x),cos(y)), (x,-3,3), (y,-3,3)) sphinx_plot(g) :: sage: plot_vector_field((y,(cos(x)-2) * sin(x)), (x,-pi,pi), (y,-pi,pi)) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y = var('x y') g = plot_vector_field((y,(cos(x)-2) * sin(x)), (x,-pi,pi), (y,-pi,pi)) sphinx_plot(g) Plot a gradient field:: sage: u, v = var('u v') sage: f = exp(-(u^2 + v^2)) sage: plot_vector_field(f.gradient(), (u,-2,2), (v,-2,2), color='blue') Graphics object consisting of 1 graphics primitive .. PLOT:: u, v = var('u v') f = exp(-(u**2 + v**2)) g = plot_vector_field(f.gradient(), (u,-2,2), (v,-2,2), color='blue') sphinx_plot(g) Plot two orthogonal vector fields:: sage: x,y = var('x,y') sage: a = plot_vector_field((x,y), (x,-3,3), (y,-3,3), color='blue') sage: b = plot_vector_field((y,-x), (x,-3,3), (y,-3,3), color='red') sage: show(a + b) .. PLOT:: x,y = var('x,y') a = plot_vector_field((x,y), (x,-3,3), (y,-3,3), color='blue') b = plot_vector_field((y,-x), (x,-3,3), (y,-3,3), color='red') sphinx_plot(a + b) We ignore function values that are infinite or NaN:: sage: x,y = var('x,y') sage: plot_vector_field((-x/sqrt(x^2+y^2),-y/sqrt(x^2+y^2)), (x,-10,10), (y,-10,10)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = plot_vector_field((-x/sqrt(x**2+y**2),-y/sqrt(x**2+y**2)), (x,-10,10), (y,-10,10)) sphinx_plot(g) :: sage: x,y = var('x,y') sage: plot_vector_field((-x/sqrt(x+y),-y/sqrt(x+y)), (x,-10, 10), (y,-10,10)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = plot_vector_field((-x/sqrt(x+y),-y/sqrt(x+y)), (x,-10,10), (y,-10,10)) sphinx_plot(g) Extra options will get passed on to show(), as long as they are valid:: sage: plot_vector_field((x,y), (x,-2,2), (y,-2,2), xmax=10) Graphics object consisting of 1 graphics primitive sage: plot_vector_field((x,y), (x,-2,2), (y,-2,2)).show(xmax=10) # These are equivalent .. PLOT:: x,y = var('x,y') g = plot_vector_field((x,y), (x,-2,2), (y,-2,2), xmax=10) sphinx_plot(g) """ (f,g) = f_g from sage.plot.all import Graphics from sage.plot.misc import setup_for_eval_on_grid z, ranges = setup_for_eval_on_grid([f,g], [xrange,yrange], options['plot_points']) f, g = z xpos_array, ypos_array, xvec_array, yvec_array = [], [], [], [] for x in xsrange(*ranges[0], include_endpoint=True): for y in xsrange(*ranges[1], include_endpoint=True): xpos_array.append(x) ypos_array.append(y) xvec_array.append(f(x, y)) yvec_array.append(g(x, y)) import numpy xvec_array = numpy.ma.masked_invalid(numpy.array(xvec_array, dtype=float)) yvec_array = numpy.ma.masked_invalid(numpy.array(yvec_array, dtype=float)) g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) g.add_primitive(PlotField(xpos_array, ypos_array, xvec_array, yvec_array, options)) return g def plot_slope_field(f, xrange, yrange, **kwds): r""" ``plot_slope_field`` takes a function of two variables xvar and yvar (for instance, if the variables are `x` and `y`, take `f(x,y)`), and at representative points `(x_i,y_i)` between xmin, xmax, and ymin, ymax respectively, plots a line with slope `f(x_i,y_i)` (see below). ``plot_slope_field(f, (xvar,xmin,xmax), (yvar,ymin,ymax))`` EXAMPLES: A logistic function modeling population growth:: sage: x,y = var('x y') sage: capacity = 3 # thousand sage: growth_rate = 0.7 # population increases by 70% per unit of time sage: plot_slope_field(growth_rate * (1-y/capacity) * y, (x,0,5), (y,0,capacity*2)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x y') capacity = 3 # thousand growth_rate = 0.7 # population increases by 70% per unit of time g = plot_slope_field(growth_rate * (1-y/capacity) * y, (x,0,5), (y,0,capacity*2)) sphinx_plot(g) Plot a slope field involving sin and cos:: sage: x,y = var('x y') sage: plot_slope_field(sin(x+y) + cos(x+y), (x,-3,3), (y,-3,3)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x y') g = plot_slope_field(sin(x+y)+cos(x+y), (x,-3,3), (y,-3,3)) sphinx_plot(g) Plot a slope field using a lambda function:: sage: plot_slope_field(lambda x,y: x + y, (-2,2), (-2,2)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x y') g = plot_slope_field(lambda x,y: x + y, (-2,2), (-2,2)) sphinx_plot(g) TESTS: Verify that we're not getting warnings due to use of headless quivers (:trac:`11208`):: sage: x,y = var('x y') sage: import numpy # bump warnings up to errors for testing purposes sage: old_err = numpy.seterr('raise') sage: plot_slope_field(sin(x+y) + cos(x+y), (x,-3,3), (y,-3,3)) Graphics object consisting of 1 graphics primitive sage: dummy_err = numpy.seterr(**old_err) """ slope_options = {'headaxislength': 0, 'headlength': 1e-9, 'pivot': 'middle'} slope_options.update(kwds) from sage.misc.functional import sqrt from sage.misc.sageinspect import is_function_or_cython_function if is_function_or_cython_function(f): norm_inverse = lambda x,y: 1/sqrt(f(x, y)**2+1) f_normalized = lambda x,y: f(x, y)*norm_inverse(x, y) else: norm_inverse = 1 / sqrt((f**2+1)) f_normalized = f * norm_inverse return plot_vector_field((norm_inverse, f_normalized), xrange, yrange, **slope_options)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/plot_field.py
0.708616
0.603844
plot_field.py
pypi
from .primitive import GraphicPrimitive from sage.misc.decorators import options, rename_keyword from sage.plot.colors import to_mpl_color from math import sin, cos, sqrt, pi, fmod class Ellipse(GraphicPrimitive): """ Primitive class for the ``Ellipse`` graphics type. See ``ellipse?`` for information about actually plotting ellipses. INPUT: - ``x,y`` - coordinates of the center of the ellipse - ``r1, r2`` - radii of the ellipse - ``angle`` - angle - ``options`` - dictionary of options EXAMPLES: Note that this construction should be done using ``ellipse``:: sage: from sage.plot.ellipse import Ellipse sage: Ellipse(0, 0, 2, 1, pi/4, {}) Ellipse centered at (0.0, 0.0) with radii (2.0, 1.0) and angle 0.78539816339... """ def __init__(self, x, y, r1, r2, angle, options): """ Initializes base class ``Ellipse``. TESTS:: sage: from sage.plot.ellipse import Ellipse sage: e = Ellipse(0, 0, 1, 1, 0, {}) sage: print(loads(dumps(e))) Ellipse centered at (0.0, 0.0) with radii (1.0, 1.0) and angle 0.0 sage: ellipse((0,0),0,1) Traceback (most recent call last): ... ValueError: both radii must be positive """ self.x = float(x) self.y = float(y) self.r1 = float(r1) self.r2 = float(r2) if self.r1 <= 0 or self.r2 <= 0: raise ValueError("both radii must be positive") self.angle = fmod(angle, 2 * pi) if self.angle < 0: self.angle += 2 * pi GraphicPrimitive.__init__(self, options) def get_minmax_data(self): r""" Return a dictionary with the bounding box data. The bounding box is computed to be as minimal as possible. EXAMPLES: An example without an angle:: sage: p = ellipse((-2, 3), 1, 2) sage: d = p.get_minmax_data() sage: d['xmin'] -3.0 sage: d['xmax'] -1.0 sage: d['ymin'] 1.0 sage: d['ymax'] 5.0 The same example with a rotation of angle `\pi/2`:: sage: p = ellipse((-2, 3), 1, 2, pi/2) sage: d = p.get_minmax_data() sage: d['xmin'] -4.0 sage: d['xmax'] 0.0 sage: d['ymin'] 2.0 sage: d['ymax'] 4.0 """ from sage.plot.plot import minmax_data epsilon = 0.000001 cos_angle = cos(self.angle) if abs(cos_angle) > 1-epsilon: xmax = self.r1 ymax = self.r2 elif abs(cos_angle) < epsilon: xmax = self.r2 ymax = self.r1 else: sin_angle = sin(self.angle) tan_angle = sin_angle / cos_angle sxmax = ((self.r2*tan_angle)/self.r1)**2 symax = (self.r2/(self.r1*tan_angle))**2 xmax = ( abs(self.r1 * cos_angle / sqrt(sxmax+1.)) + abs(self.r2 * sin_angle / sqrt(1./sxmax+1.))) ymax = ( abs(self.r1 * sin_angle / sqrt(symax+1.)) + abs(self.r2 * cos_angle / sqrt(1./symax+1.))) return minmax_data([self.x - xmax, self.x + xmax], [self.y - ymax, self.y + ymax], dict=True) def _allowed_options(self): """ Return the allowed options for the ``Ellipse`` class. EXAMPLES:: sage: p = ellipse((3, 3), 2, 1) sage: p[0]._allowed_options()['alpha'] 'How transparent the figure is.' sage: p[0]._allowed_options()['facecolor'] '2D only: The color of the face as an RGB tuple.' """ return {'alpha':'How transparent the figure is.', 'fill': 'Whether or not to fill the ellipse.', 'legend_label':'The label for this item in the legend.', 'legend_color':'The color of the legend text.', 'thickness':'How thick the border of the ellipse is.', 'edgecolor':'2D only: The color of the edge as an RGB tuple.', 'facecolor':'2D only: The color of the face as an RGB tuple.', 'rgbcolor':'The color (edge and face) as an RGB tuple.', 'hue':'The color given as a hue.', 'zorder':'2D only: The layer level in which to draw', 'linestyle':"2D only: The style of the line, which is one of " "'dashed', 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.', " "respectively."} def _repr_(self): """ String representation of ``Ellipse`` primitive. TESTS:: sage: from sage.plot.ellipse import Ellipse sage: Ellipse(0,0,2,1,0,{})._repr_() 'Ellipse centered at (0.0, 0.0) with radii (2.0, 1.0) and angle 0.0' """ return "Ellipse centered at (%s, %s) with radii (%s, %s) and angle %s"%(self.x, self.y, self.r1, self.r2, self.angle) def _render_on_subplot(self, subplot): """ Render this ellipse in a subplot. This is the key function that defines how this ellipse graphics primitive is rendered in matplotlib's library. TESTS:: sage: ellipse((0,0),3,1,pi/6,fill=True,alpha=0.3) Graphics object consisting of 1 graphics primitive :: sage: ellipse((3,2),1,2) Graphics object consisting of 1 graphics primitive """ import matplotlib.patches as patches from sage.plot.misc import get_matplotlib_linestyle options = self.options() p = patches.Ellipse( (self.x,self.y), self.r1*2.,self.r2*2., angle=self.angle/pi*180.) p.set_linewidth(float(options['thickness'])) p.set_fill(options['fill']) a = float(options['alpha']) p.set_alpha(a) ec = to_mpl_color(options['edgecolor']) fc = to_mpl_color(options['facecolor']) if 'rgbcolor' in options: ec = fc = to_mpl_color(options['rgbcolor']) p.set_edgecolor(ec) p.set_facecolor(fc) p.set_linestyle(get_matplotlib_linestyle(options['linestyle'],return_type='long')) p.set_label(options['legend_label']) z = int(options.pop('zorder', 0)) p.set_zorder(z) subplot.add_patch(p) def plot3d(self): r""" Plotting in 3D is not implemented. TESTS:: sage: from sage.plot.ellipse import Ellipse sage: Ellipse(0,0,2,1,pi/4,{}).plot3d() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError @rename_keyword(color='rgbcolor') @options(alpha=1, fill=False, thickness=1, edgecolor='blue', facecolor='blue', linestyle='solid', zorder=5, aspect_ratio=1.0, legend_label=None, legend_color=None) def ellipse(center, r1, r2, angle=0, **options): """ Return an ellipse centered at a point center = ``(x,y)`` with radii = ``r1,r2`` and angle ``angle``. Type ``ellipse.options`` to see all options. INPUT: - ``center`` - 2-tuple of real numbers - coordinates of the center - ``r1``, ``r2`` - positive real numbers - the radii of the ellipse - ``angle`` - real number (default: 0) - the angle between the first axis and the horizontal OPTIONS: - ``alpha`` - default: 1 - transparency - ``fill`` - default: False - whether to fill the ellipse or not - ``thickness`` - default: 1 - thickness of the line - ``linestyle`` - default: ``'solid'`` - The style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively. - ``edgecolor`` - default: 'black' - color of the contour - ``facecolor`` - default: 'red' - color of the filling - ``rgbcolor`` - 2D or 3D plotting. This option overrides ``edgecolor`` and ``facecolor`` for 2D plotting. - ``legend_label`` - the label for this item in the legend - ``legend_color`` - the color for the legend label EXAMPLES: An ellipse centered at (0,0) with major and minor axes of lengths 2 and 1. Note that the default color is blue:: sage: ellipse((0,0),2,1) Graphics object consisting of 1 graphics primitive .. PLOT:: E=ellipse((0,0),2,1) sphinx_plot(E) More complicated examples with tilted axes and drawing options:: sage: ellipse((0,0),3,1,pi/6,fill=True,alpha=0.3,linestyle="dashed") Graphics object consisting of 1 graphics primitive .. PLOT:: E = ellipse((0,0),3,1,pi/6,fill=True,alpha=0.3,linestyle="dashed") sphinx_plot(E) other way to indicate dashed linestyle:: sage: ellipse((0,0),3,1,pi/6,fill=True,alpha=0.3,linestyle="--") Graphics object consisting of 1 graphics primitive .. PLOT:: E =ellipse((0,0),3,1,pi/6,fill=True,alpha=0.3,linestyle='--') sphinx_plot(E) with colors :: sage: ellipse((0,0),3,1,pi/6,fill=True,edgecolor='black',facecolor='red') Graphics object consisting of 1 graphics primitive .. PLOT:: E=ellipse((0,0),3,1,pi/6,fill=True,edgecolor='black',facecolor='red') sphinx_plot(E) We see that ``rgbcolor`` overrides these other options, as this plot is green:: sage: ellipse((0,0),3,1,pi/6,fill=True,edgecolor='black',facecolor='red',rgbcolor='green') Graphics object consisting of 1 graphics primitive .. PLOT:: E=ellipse((0,0),3,1,pi/6,fill=True,edgecolor='black',facecolor='red',rgbcolor='green') sphinx_plot(E) The default aspect ratio for ellipses is 1.0:: sage: ellipse((0,0),2,1).aspect_ratio() 1.0 One cannot yet plot ellipses in 3D:: sage: ellipse((0,0,0),2,1) Traceback (most recent call last): ... NotImplementedError: plotting ellipse in 3D is not implemented We can also give ellipses a legend:: sage: ellipse((0,0),2,1,legend_label="My ellipse", legend_color='green') Graphics object consisting of 1 graphics primitive .. PLOT:: E=ellipse((0,0),2,1,legend_label="My ellipse", legend_color='green') sphinx_plot(E) """ from sage.plot.all import Graphics g = Graphics() # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] if scale == 'semilogy' or scale == 'semilogx': options['aspect_ratio'] = 'automatic' g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) g.add_primitive(Ellipse(center[0],center[1],r1,r2,angle,options)) if options['legend_label']: g.legend(True) g._legend_colors = [options['legend_color']] if len(center)==2: return g elif len(center)==3: raise NotImplementedError("plotting ellipse in 3D is not implemented")
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/ellipse.py
0.958363
0.578359
ellipse.py
pypi
from sage.plot.primitive import GraphicPrimitive from sage.misc.decorators import options, rename_keyword from sage.plot.colors import to_mpl_color class CurveArrow(GraphicPrimitive): def __init__(self, path, options): """ Returns an arrow graphics primitive along the provided path (bezier curve). EXAMPLES:: sage: from sage.plot.arrow import CurveArrow sage: b = CurveArrow(path=[[(0,0),(.5,.5),(1,0)],[(.5,1),(0,0)]], ....: options={}) sage: b CurveArrow from (0, 0) to (0, 0) """ import numpy as np self.path = path codes = [1] + (len(self.path[0])-1)*[len(self.path[0])] vertices = self.path[0] for curve in self.path[1:]: vertices += curve codes += (len(curve))*[len(curve)+1] self.codes = codes self.vertices = np.array(vertices, float) GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Returns a dictionary with the bounding box data. EXAMPLES:: sage: from sage.plot.arrow import CurveArrow sage: b = CurveArrow(path=[[(0,0),(.5,.5),(1,0)],[(.5,1),(0,0)]], ....: options={}) sage: d = b.get_minmax_data() sage: d['xmin'] 0.0 sage: d['xmax'] 1.0 """ return {'xmin': self.vertices[:,0].min(), 'xmax': self.vertices[:,0].max(), 'ymin': self.vertices[:,1].min(), 'ymax': self.vertices[:,1].max()} def _allowed_options(self): """ Return the dictionary of allowed options for the curve arrow graphics primitive. EXAMPLES:: sage: from sage.plot.arrow import CurveArrow sage: list(sorted(CurveArrow(path=[[(0,0),(2,3)]],options={})._allowed_options().items())) [('arrowsize', 'The size of the arrowhead'), ('arrowstyle', 'todo'), ('head', '2-d only: Which end of the path to draw the head (one of 0 (start), 1 (end) or 2 (both)'), ('hue', 'The color given as a hue.'), ('legend_color', 'The color of the legend text.'), ('legend_label', 'The label for this item in the legend.'), ('linestyle', "2d only: The style of the line, which is one of 'dashed', 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.', respectively."), ('rgbcolor', 'The color as an RGB tuple.'), ('thickness', 'The thickness of the arrow.'), ('width', 'The width of the shaft of the arrow, in points.'), ('zorder', '2-d only: The layer level in which to draw')] """ return {'width': 'The width of the shaft of the arrow, in points.', 'rgbcolor': 'The color as an RGB tuple.', 'hue': 'The color given as a hue.', 'legend_label': 'The label for this item in the legend.', 'legend_color': 'The color of the legend text.', 'arrowstyle': 'todo', 'arrowsize': 'The size of the arrowhead', 'thickness': 'The thickness of the arrow.', 'zorder': '2-d only: The layer level in which to draw', 'head': '2-d only: Which end of the path to draw the head (one of 0 (start), 1 (end) or 2 (both)', 'linestyle': "2d only: The style of the line, which is one of " "'dashed', 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.', " "respectively."} def _repr_(self): """ Text representation of an arrow graphics primitive. EXAMPLES:: sage: from sage.plot.arrow import CurveArrow sage: CurveArrow(path=[[(0,0),(1,4),(2,3)]],options={})._repr_() 'CurveArrow from (0, 0) to (2, 3)' """ return "CurveArrow from %s to %s" % (self.path[0][0], self.path[-1][-1]) def _render_on_subplot(self, subplot): """ Render this arrow in a subplot. This is the key function that defines how this arrow graphics primitive is rendered in matplotlib's library. EXAMPLES: This function implicitly ends up rendering this arrow on a matplotlib subplot:: sage: arrow(path=[[(0,1), (2,-1), (4,5)]]) Graphics object consisting of 1 graphics primitive """ from sage.plot.misc import get_matplotlib_linestyle options = self.options() width = float(options['width']) head = options.pop('head') if head == 0: style = '<|-' elif head == 1: style = '-|>' elif head == 2: style = '<|-|>' else: raise KeyError('head parameter must be one of 0 (start), 1 (end) or 2 (both)') arrowsize = float(options.get('arrowsize', 5)) head_width = arrowsize head_length = arrowsize * 2.0 color = to_mpl_color(options['rgbcolor']) from matplotlib.patches import FancyArrowPatch from matplotlib.path import Path bpath = Path(self.vertices, self.codes) p = FancyArrowPatch(path=bpath, lw=width, arrowstyle='%s,head_width=%s,head_length=%s' % (style, head_width, head_length), fc=color, ec=color, linestyle=get_matplotlib_linestyle(options['linestyle'], return_type='long')) p.set_zorder(options['zorder']) p.set_label(options['legend_label']) subplot.add_patch(p) return p class Arrow(GraphicPrimitive): """ Primitive class that initializes the (line) arrow graphics type EXAMPLES: We create an arrow graphics object, then take the 0th entry in it to get the actual Arrow graphics primitive:: sage: P = arrow((0,1), (2,3))[0] sage: type(P) <class 'sage.plot.arrow.Arrow'> sage: P Arrow from (0.0,1.0) to (2.0,3.0) """ def __init__(self, xtail, ytail, xhead, yhead, options): """ Create an arrow graphics primitive. EXAMPLES:: sage: from sage.plot.arrow import Arrow sage: Arrow(0,0,2,3,{}) Arrow from (0.0,0.0) to (2.0,3.0) """ self.xtail = float(xtail) self.xhead = float(xhead) self.ytail = float(ytail) self.yhead = float(yhead) GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Returns a bounding box for this arrow. EXAMPLES:: sage: d = arrow((1,1), (5,5)).get_minmax_data() sage: d['xmin'] 1.0 sage: d['xmax'] 5.0 """ return {'xmin': min(self.xtail, self.xhead), 'xmax': max(self.xtail, self.xhead), 'ymin': min(self.ytail, self.yhead), 'ymax': max(self.ytail, self.yhead)} def _allowed_options(self): """ Return the dictionary of allowed options for the line arrow graphics primitive. EXAMPLES:: sage: from sage.plot.arrow import Arrow sage: list(sorted(Arrow(0,0,2,3,{})._allowed_options().items())) [('arrowshorten', 'The length in points to shorten the arrow.'), ('arrowsize', 'The size of the arrowhead'), ('head', '2-d only: Which end of the path to draw the head (one of 0 (start), 1 (end) or 2 (both)'), ('hue', 'The color given as a hue.'), ('legend_color', 'The color of the legend text.'), ('legend_label', 'The label for this item in the legend.'), ('linestyle', "2d only: The style of the line, which is one of 'dashed', 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.', respectively."), ('rgbcolor', 'The color as an RGB tuple.'), ('thickness', 'The thickness of the arrow.'), ('width', 'The width of the shaft of the arrow, in points.'), ('zorder', '2-d only: The layer level in which to draw')] """ return {'width': 'The width of the shaft of the arrow, in points.', 'rgbcolor': 'The color as an RGB tuple.', 'hue': 'The color given as a hue.', 'arrowshorten': 'The length in points to shorten the arrow.', 'arrowsize': 'The size of the arrowhead', 'thickness': 'The thickness of the arrow.', 'legend_label': 'The label for this item in the legend.', 'legend_color': 'The color of the legend text.', 'zorder': '2-d only: The layer level in which to draw', 'head': '2-d only: Which end of the path to draw the head (one of 0 (start), 1 (end) or 2 (both)', 'linestyle': "2d only: The style of the line, which is one of " "'dashed', 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.', " "respectively."} def _plot3d_options(self, options=None): """ Translate 2D plot options into 3D plot options. EXAMPLES:: sage: P = arrow((0,1), (2,3), width=5) sage: p=P[0]; p Arrow from (0.0,1.0) to (2.0,3.0) sage: q=p.plot3d() sage: q.thickness 5 """ if options is None: options = self.options() options = dict(self.options()) options_3d = {} if 'width' in options: options_3d['thickness'] = options['width'] del options['width'] # ignore zorder and head in 3d plotting if 'zorder' in options: del options['zorder'] if 'head' in options: del options['head'] if 'linestyle' in options: del options['linestyle'] options_3d.update(GraphicPrimitive._plot3d_options(self, options)) return options_3d def plot3d(self, ztail=0, zhead=0, **kwds): """ Takes 2D plot and places it in 3D. EXAMPLES:: sage: A = arrow((0,0),(1,1))[0].plot3d() sage: A.jmol_repr(A.testing_render_params())[0] 'draw line_1 diameter 2 arrow {0.0 0.0 0.0} {1.0 1.0 0.0} ' Note that we had to index the arrow to get the Arrow graphics primitive. We can also change the height via the :meth:`Graphics.plot3d` method, but only as a whole:: sage: A = arrow((0,0),(1,1)).plot3d(3) sage: A.jmol_repr(A.testing_render_params())[0][0] 'draw line_1 diameter 2 arrow {0.0 0.0 3.0} {1.0 1.0 3.0} ' Optional arguments place both the head and tail outside the `xy`-plane, but at different heights. This must be done on the graphics primitive obtained by indexing:: sage: A=arrow((0,0),(1,1))[0].plot3d(3,4) sage: A.jmol_repr(A.testing_render_params())[0] 'draw line_1 diameter 2 arrow {0.0 0.0 3.0} {1.0 1.0 4.0} ' """ from sage.plot.plot3d.shapes2 import line3d options = self._plot3d_options() options.update(kwds) return line3d([(self.xtail, self.ytail, ztail), (self.xhead, self.yhead, zhead)], arrow_head=True, **options) def _repr_(self): """ Text representation of an arrow graphics primitive. EXAMPLES:: sage: from sage.plot.arrow import Arrow sage: Arrow(0,0,2,3,{})._repr_() 'Arrow from (0.0,0.0) to (2.0,3.0)' """ return "Arrow from (%s,%s) to (%s,%s)" % (self.xtail, self.ytail, self.xhead, self.yhead) def _render_on_subplot(self, subplot): r""" Render this arrow in a subplot. This is the key function that defines how this arrow graphics primitive is rendered in matplotlib's library. EXAMPLES: This function implicitly ends up rendering this arrow on a matplotlib subplot:: sage: arrow((0,1), (2,-1)) Graphics object consisting of 1 graphics primitive TESTS: The length of the ends (shrinkA and shrinkB) should not depend on the width of the arrow, because Matplotlib already takes this into account. See :trac:`12836`:: sage: fig = Graphics().matplotlib() sage: sp = fig.add_subplot(1,1,1, label='axis1') sage: a = arrow((0,0), (1,1)) sage: b = arrow((0,0), (1,1), width=20) sage: p1 = a[0]._render_on_subplot(sp) sage: p2 = b[0]._render_on_subplot(sp) sage: p1.shrinkA == p2.shrinkA True sage: p1.shrinkB == p2.shrinkB True Dashed arrows should have solid arrowheads, :trac:`12852`. We tried to make up a test for this, which turned out to be fragile and hence was removed. In general, robust testing of graphics seems basically need a human eye or AI. """ from sage.plot.misc import get_matplotlib_linestyle options = self.options() head = options.pop('head') if head == 0: style = '<|-' elif head == 1: style = '-|>' elif head == 2: style = '<|-|>' else: raise KeyError('head parameter must be one of 0 (start), 1 (end) or 2 (both)') width = float(options['width']) arrowshorten_end = float(options.get('arrowshorten', 0)) / 2.0 arrowsize = float(options.get('arrowsize', 5)) head_width = arrowsize head_length = arrowsize * 2.0 color = to_mpl_color(options['rgbcolor']) from matplotlib.patches import FancyArrowPatch p = FancyArrowPatch((self.xtail, self.ytail), (self.xhead, self.yhead), lw=width, arrowstyle='%s,head_width=%s,head_length=%s' % (style, head_width, head_length), shrinkA=arrowshorten_end, shrinkB=arrowshorten_end, fc=color, ec=color, linestyle=get_matplotlib_linestyle(options['linestyle'], return_type='long')) p.set_zorder(options['zorder']) p.set_label(options['legend_label']) if options['linestyle'] != 'solid': # The next few lines work around a design issue in matplotlib. # Currently, the specified linestyle is used to draw both the path # and the arrowhead. If linestyle is 'dashed', this looks really # odd. This code is from Jae-Joon Lee in response to a post to the # matplotlib mailing list. # See http://sourceforge.net/mailarchive/forum.php?thread_name=CAG%3DuJ%2Bnw2dE05P9TOXTz_zp-mGP3cY801vMH7yt6vgP9_WzU8w%40mail.gmail.com&forum_name=matplotlib-users import matplotlib.patheffects as pe class CheckNthSubPath(): def __init__(self, patch, n): """ creates an callable object that returns True if the provided path is the n-th path from the patch. """ self._patch = patch self._n = n def get_paths(self, renderer): # get_path_in_displaycoord was made private in matplotlib 3.5 try: paths, fillables = self._patch._get_path_in_displaycoord() except AttributeError: paths, fillables = self._patch.get_path_in_displaycoord() return paths def __call__(self, renderer, gc, tpath, affine, rgbFace): path = self.get_paths(renderer)[self._n] vert1, code1 = path.vertices, path.codes import numpy as np return np.array_equal(vert1, tpath.vertices) and np.array_equal(code1, tpath.codes) class ConditionalStroke(pe.RendererBase): def __init__(self, condition_func, pe_list): """ path effect that is only applied when the condition_func returns True. """ super().__init__() self._pe_list = pe_list self._condition_func = condition_func def draw_path(self, renderer, gc, tpath, affine, rgbFace): if self._condition_func(renderer, gc, tpath, affine, rgbFace): for pe1 in self._pe_list: pe1.draw_path(renderer, gc, tpath, affine, rgbFace) pe1 = ConditionalStroke(CheckNthSubPath(p, 0), [pe.Stroke()]) pe2 = ConditionalStroke(CheckNthSubPath(p, 1), [pe.Stroke(dashes={'dash_offset': 0, 'dash_list': None})]) p.set_path_effects([pe1, pe2]) subplot.add_patch(p) return p def arrow(tailpoint=None, headpoint=None, **kwds): """ Returns either a 2-dimensional or 3-dimensional arrow depending on value of points. For information regarding additional arguments, see either arrow2d? or arrow3d?. EXAMPLES:: sage: arrow((0,0), (1,1)) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(arrow((0,0), (1,1))) :: sage: arrow((0,0,1), (1,1,1)) Graphics3d Object .. PLOT:: sphinx_plot(arrow((0,0,1), (1,1,1))) """ try: return arrow2d(tailpoint, headpoint, **kwds) except ValueError: from sage.plot.plot3d.shapes import arrow3d return arrow3d(tailpoint, headpoint, **kwds) @rename_keyword(color='rgbcolor') @options(width=2, rgbcolor=(0,0,1), zorder=2, head=1, linestyle='solid', legend_label=None) def arrow2d(tailpoint=None, headpoint=None, path=None, **options): """ If ``tailpoint`` and ``headpoint`` are provided, returns an arrow from (xtail, ytail) to (xhead, yhead). If ``tailpoint`` or ``headpoint`` is None and ``path`` is not None, returns an arrow along the path. (See further info on paths in :class:`bezier_path`). INPUT: - ``tailpoint`` - the starting point of the arrow - ``headpoint`` - where the arrow is pointing to - ``path`` - the list of points and control points (see bezier_path for detail) that the arrow will follow from source to destination - ``head`` - 0, 1 or 2, whether to draw the head at the start (0), end (1) or both (2) of the path (using 0 will swap headpoint and tailpoint). This is ignored in 3D plotting. - ``linestyle`` - (default: ``'solid'``) The style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively. - ``width`` - (default: 2) the width of the arrow shaft, in points - ``color`` - (default: (0,0,1)) the color of the arrow (as an RGB tuple or a string) - ``hue`` - the color of the arrow (as a number) - ``arrowsize`` - the size of the arrowhead - ``arrowshorten`` - the length in points to shorten the arrow (ignored if using path parameter) - ``legend_label`` - the label for this item in the legend - ``legend_color`` - the color for the legend label - ``zorder`` - the layer level to draw the arrow-- note that this is ignored in 3D plotting. EXAMPLES: A straight, blue arrow:: sage: arrow2d((1,1), (3,3)) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(arrow2d((1,1), (3,3))) Make a red arrow:: sage: arrow2d((-1,-1), (2,3), color=(1,0,0)) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(arrow2d((-1,-1), (2,3), color=(1,0,0))) :: sage: arrow2d((-1,-1), (2,3), color='red') Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(arrow2d((-1,-1), (2,3), color='red')) You can change the width of an arrow:: sage: arrow2d((1,1), (3,3), width=5, arrowsize=15) Graphics object consisting of 1 graphics primitive .. PLOT:: P = arrow2d((1,1), (3,3), width=5, arrowsize=15) sphinx_plot(P) Use a dashed line instead of a solid one for the arrow:: sage: arrow2d((1,1), (3,3), linestyle='dashed') Graphics object consisting of 1 graphics primitive sage: arrow2d((1,1), (3,3), linestyle='--') Graphics object consisting of 1 graphics primitive .. PLOT:: P = arrow2d((1,1), (3,3), linestyle='--') sphinx_plot(P) A pretty circle of arrows:: sage: sum([arrow2d((0,0), (cos(x),sin(x)), hue=x/(2*pi)) for x in [0..2*pi,step=0.1]]) Graphics object consisting of 63 graphics primitives .. PLOT:: P = sum([arrow2d((0,0), (cos(x*0.1),sin(x*0.1)), hue=x/(20*pi)) for x in range(floor(20*pi)+1)]) sphinx_plot(P) If we want to draw the arrow between objects, for example, the boundaries of two lines, we can use the ``arrowshorten`` option to make the arrow shorter by a certain number of points:: sage: L1 = line([(0,0), (1,0)], thickness=10) sage: L2 = line([(0,1), (1,1)], thickness=10) sage: A = arrow2d((0.5,0), (0.5,1), arrowshorten=10, rgbcolor=(1,0,0)) sage: L1 + L2 + A Graphics object consisting of 3 graphics primitives .. PLOT:: L1 = line([(0,0), (1,0)],thickness=10) L2 = line([(0,1), (1,1)], thickness=10) A = arrow2d((0.5,0), (0.5,1), arrowshorten=10, rgbcolor=(1,0,0)) sphinx_plot(L1 + L2 + A) If BOTH ``headpoint`` and ``tailpoint`` are None, then an empty plot is returned:: sage: arrow2d(headpoint=None, tailpoint=None) Graphics object consisting of 0 graphics primitives We can also draw an arrow with a legend:: sage: arrow((0,0), (0,2), legend_label='up', legend_color='purple') Graphics object consisting of 1 graphics primitive .. PLOT:: P = arrow((0,0), (0,2), legend_label='up', legend_color='purple') sphinx_plot(P) Extra options will get passed on to :meth:`Graphics.show()`, as long as they are valid:: sage: arrow2d((-2,2), (7,1), frame=True) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(arrow2d((-2,2), (7,1), frame=True)) :: sage: arrow2d((-2,2), (7,1)).show(frame=True) """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) if headpoint is not None and tailpoint is not None: xtail, ytail = tailpoint xhead, yhead = headpoint g.add_primitive(Arrow(xtail, ytail, xhead, yhead, options=options)) elif path is not None: g.add_primitive(CurveArrow(path, options=options)) elif tailpoint is None and headpoint is None: return g else: raise TypeError('arrow requires either both headpoint and tailpoint or a path parameter') if options['legend_label']: g.legend(True) g._legend_colors = [options['legend_color']] return g
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/arrow.py
0.906439
0.468669
arrow.py
pypi
from sage.plot.primitive import GraphicPrimitive from sage.plot.colors import to_mpl_color from sage.misc.decorators import options, rename_keyword from math import fmod, sin, cos, pi, atan class Arc(GraphicPrimitive): """ Primitive class for the Arc graphics type. See ``arc?`` for information about actually plotting an arc of a circle or an ellipse. INPUT: - ``x,y`` - coordinates of the center of the arc - ``r1``, ``r2`` - lengths of the two radii - ``angle`` - angle of the horizontal with width - ``sector`` - sector of angle - ``options`` - dict of valid plot options to pass to constructor EXAMPLES: Note that the construction should be done using ``arc``:: sage: from sage.plot.arc import Arc sage: print(Arc(0,0,1,1,pi/4,pi/4,pi/2,{})) Arc with center (0.0,0.0) radii (1.0,1.0) angle 0.78539816339... inside the sector (0.78539816339...,1.5707963267...) """ def __init__(self, x, y, r1, r2, angle, s1, s2, options): """ Initializes base class ``Arc``. EXAMPLES:: sage: A = arc((2,3),1,1,pi/4,(0,pi)) sage: A[0].x == 2 True sage: A[0].y == 3 True sage: A[0].r1 == 1 True sage: A[0].r2 == 1 True sage: A[0].angle 0.7853981633974483 sage: bool(A[0].s1 == 0) True sage: A[0].s2 3.141592653589793 TESTS:: sage: from sage.plot.arc import Arc sage: a = Arc(0,0,1,1,0,0,1,{}) sage: print(loads(dumps(a))) Arc with center (0.0,0.0) radii (1.0,1.0) angle 0.0 inside the sector (0.0,1.0) """ self.x = float(x) self.y = float(y) self.r1 = float(r1) self.r2 = float(r2) if self.r1 <= 0 or self.r2 <= 0: raise ValueError("the radii must be positive real numbers") self.angle = float(angle) self.s1 = float(s1) self.s2 = float(s2) if self.s2 < self.s1: self.s1, self.s2 = self.s2, self.s1 GraphicPrimitive.__init__(self, options) def get_minmax_data(self): r""" Return a dictionary with the bounding box data. The bounding box is computed as minimal as possible. EXAMPLES: An example without angle:: sage: p = arc((-2, 3), 1, 2) sage: d = p.get_minmax_data() sage: d['xmin'] -3.0 sage: d['xmax'] -1.0 sage: d['ymin'] 1.0 sage: d['ymax'] 5.0 The same example with a rotation of angle `\pi/2`:: sage: p = arc((-2, 3), 1, 2, pi/2) sage: d = p.get_minmax_data() sage: d['xmin'] -4.0 sage: d['xmax'] 0.0 sage: d['ymin'] 2.0 sage: d['ymax'] 4.0 """ from sage.plot.plot import minmax_data twopi = 2 * pi s1 = self.s1 s2 = self.s2 s = s2 - s1 s1 = fmod(s1, twopi) if s1 < 0: s1 += twopi s2 = fmod(s1 + s, twopi) if s2 < 0: s2 += twopi r1 = self.r1 r2 = self.r2 angle = fmod(self.angle, twopi) if angle < 0: angle += twopi epsilon = float(0.0000001) cos_angle = cos(angle) sin_angle = sin(angle) if cos_angle > 1 - epsilon: xmin = -r1 ymin = -r2 xmax = r1 ymax = r2 axmin = pi axmax = 0 aymin = 3 * pi / 2 aymax = pi / 2 elif cos_angle < -1 + epsilon: xmin = -r1 ymin = -r2 xmax = r1 ymax = r2 axmin = 0 axmax = pi aymin = pi / 2 aymax = 3 * pi / 2 elif sin_angle > 1 - epsilon: xmin = -r2 ymin = -r1 xmax = r2 ymax = r1 axmin = pi / 2 axmax = 3 * pi / 2 aymin = pi aymax = 0 elif sin_angle < -1 + epsilon: xmin = -r2 ymin = -r1 xmax = r2 ymax = r1 axmin = 3 * pi / 2 axmax = pi / 2 aymin = 0 aymax = pi else: tan_angle = sin_angle / cos_angle axmax = atan(-r2 / r1 * tan_angle) if axmax < 0: axmax += twopi xmax = (r1 * cos_angle * cos(axmax) - r2 * sin_angle * sin(axmax)) if xmax < 0: xmax = -xmax axmax = fmod(axmax + pi, twopi) xmin = -xmax axmin = fmod(axmax + pi, twopi) aymax = atan(r2 / (r1 * tan_angle)) if aymax < 0: aymax += twopi ymax = (r1 * sin_angle * cos(aymax) + r2 * cos_angle * sin(aymax)) if ymax < 0: ymax = -ymax aymax = fmod(aymax + pi, twopi) ymin = -ymax aymin = fmod(aymax + pi, twopi) if s < twopi - epsilon: # bb determined by the sector def is_cyclic_ordered(x1, x2, x3): return ((x1 < x2 and x2 < x3) or (x2 < x3 and x3 < x1) or (x3 < x1 and x1 < x2)) x1 = cos_angle * r1 * cos(s1) - sin_angle * r2 * sin(s1) x2 = cos_angle * r1 * cos(s2) - sin_angle * r2 * sin(s2) y1 = sin_angle * r1 * cos(s1) + cos_angle * r2 * sin(s1) y2 = sin_angle * r1 * cos(s2) + cos_angle * r2 * sin(s2) if is_cyclic_ordered(s1, s2, axmin): xmin = min(x1, x2) if is_cyclic_ordered(s1, s2, aymin): ymin = min(y1, y2) if is_cyclic_ordered(s1, s2, axmax): xmax = max(x1, x2) if is_cyclic_ordered(s1, s2, aymax): ymax = max(y1, y2) return minmax_data([self.x + xmin, self.x + xmax], [self.y + ymin, self.y + ymax], dict=True) def _allowed_options(self): """ Return the allowed options for the ``Arc`` class. EXAMPLES:: sage: p = arc((3, 3), 1, 1) sage: p[0]._allowed_options()['alpha'] 'How transparent the figure is.' """ return {'alpha': 'How transparent the figure is.', 'thickness': 'How thick the border of the arc is.', 'hue': 'The color given as a hue.', 'rgbcolor': 'The color', 'zorder': '2D only: The layer level in which to draw', 'linestyle': "2D only: The style of the line, which is one of " "'dashed', 'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.', " "respectively."} def _matplotlib_arc(self): """ Return ``self`` as a matplotlib arc object. EXAMPLES:: sage: from sage.plot.arc import Arc sage: Arc(2,3,2.2,2.2,0,2,3,{})._matplotlib_arc() <matplotlib.patches.Arc object at ...> """ import matplotlib.patches as patches p = patches.Arc((self.x, self.y), 2. * self.r1, 2. * self.r2, angle=fmod(self.angle, 2 * pi) * (180. / pi), theta1=self.s1 * (180. / pi), theta2=self.s2 * (180. / pi)) return p def bezier_path(self): """ Return ``self`` as a Bezier path. This is needed to concatenate arcs, in order to create hyperbolic polygons. EXAMPLES:: sage: from sage.plot.arc import Arc sage: op = {'alpha':1,'thickness':1,'rgbcolor':'blue','zorder':0, ....: 'linestyle':'--'} sage: Arc(2,3,2.2,2.2,0,2,3,op).bezier_path() Graphics object consisting of 1 graphics primitive sage: a = arc((0,0),2,1,0,(pi/5,pi/2+pi/12), linestyle="--", color="red") sage: b = a[0].bezier_path() sage: b[0] Bezier path from (1.133..., 0.8237...) to (-0.2655..., 0.9911...) """ from sage.plot.bezier_path import BezierPath from sage.plot.graphics import Graphics from matplotlib.path import Path import numpy as np ma = self._matplotlib_arc() def theta_stretch(theta, scale): theta = np.deg2rad(theta) x = np.cos(theta) y = np.sin(theta) return np.rad2deg(np.arctan2(scale * y, x)) theta1 = theta_stretch(ma.theta1, ma.width / ma.height) theta2 = theta_stretch(ma.theta2, ma.width / ma.height) pa = ma pa._path = Path.arc(theta1, theta2) transform = pa.get_transform().get_matrix() cA, cC, cE = transform[0] cB, cD, cF = transform[1] points = [] for u in pa._path.vertices: x, y = list(u) points += [(cA * x + cC * y + cE, cB * x + cD * y + cF)] cutlist = [points[0: 4]] N = 4 while N < len(points): cutlist += [points[N: N + 3]] N += 3 g = Graphics() opt = self.options() opt['fill'] = False g.add_primitive(BezierPath(cutlist, opt)) return g def _repr_(self): """ String representation of ``Arc`` primitive. EXAMPLES:: sage: from sage.plot.arc import Arc sage: print(Arc(2,3,2.2,2.2,0,2,3,{})) Arc with center (2.0,3.0) radii (2.2,2.2) angle 0.0 inside the sector (2.0,3.0) """ return "Arc with center (%s,%s) radii (%s,%s) angle %s inside the sector (%s,%s)" % (self.x, self.y, self.r1, self.r2, self.angle, self.s1, self.s2) def _render_on_subplot(self, subplot): """ TESTS:: sage: A = arc((1,1),3,4,pi/4,(pi,4*pi/3)); A Graphics object consisting of 1 graphics primitive """ from sage.plot.misc import get_matplotlib_linestyle options = self.options() p = self._matplotlib_arc() p.set_linewidth(float(options['thickness'])) a = float(options['alpha']) p.set_alpha(a) z = int(options.pop('zorder', 1)) p.set_zorder(z) c = to_mpl_color(options['rgbcolor']) p.set_linestyle(get_matplotlib_linestyle(options['linestyle'], return_type='long')) p.set_edgecolor(c) subplot.add_patch(p) def plot3d(self): r""" TESTS:: sage: from sage.plot.arc import Arc sage: Arc(0,0,1,1,0,0,1,{}).plot3d() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError @rename_keyword(color='rgbcolor') @options(alpha=1, thickness=1, linestyle='solid', zorder=5, rgbcolor='blue', aspect_ratio=1.0) def arc(center, r1, r2=None, angle=0.0, sector=(0.0, 2 * pi), **options): r""" An arc (that is a portion of a circle or an ellipse) Type ``arc.options`` to see all options. INPUT: - ``center`` - 2-tuple of real numbers - position of the center. - ``r1``, ``r2`` - positive real numbers - radii of the ellipse. If only ``r1`` is set, then the two radii are supposed to be equal and this function returns an arc of circle. - ``angle`` - real number - angle between the horizontal and the axis that corresponds to ``r1``. - ``sector`` - 2-tuple (default: (0,2*pi))- angles sector in which the arc will be drawn. OPTIONS: - ``alpha`` - float (default: 1) - transparency - ``thickness`` - float (default: 1) - thickness of the arc - ``color``, ``rgbcolor`` - string or 2-tuple (default: 'blue') - the color of the arc - ``linestyle`` - string (default: ``'solid'``) - The style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively. EXAMPLES: Plot an arc of circle centered at (0,0) with radius 1 in the sector `(\pi/4,3*\pi/4)`:: sage: arc((0,0), 1, sector=(pi/4,3*pi/4)) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(arc((0,0), 1, sector=(pi/4,3*pi/4))) Plot an arc of an ellipse between the angles 0 and `\pi/2`:: sage: arc((2,3), 2, 1, sector=(0,pi/2)) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(arc((2,3), 2, 1, sector=(0,pi/2))) Plot an arc of a rotated ellipse between the angles 0 and `\pi/2`:: sage: arc((2,3), 2, 1, angle=pi/5, sector=(0,pi/2)) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(arc((2,3), 2, 1, angle=pi/5, sector=(0,pi/2))) Plot an arc of an ellipse in red with a dashed linestyle:: sage: arc((0,0), 2, 1, 0, (0,pi/2), linestyle="dashed", color="red") Graphics object consisting of 1 graphics primitive sage: arc((0,0), 2, 1, 0, (0,pi/2), linestyle="--", color="red") Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(arc((0,0), 2, 1, 0, (0,pi/2), linestyle="dashed", color="red")) The default aspect ratio for arcs is 1.0:: sage: arc((0,0), 1, sector=(pi/4,3*pi/4)).aspect_ratio() 1.0 It is not possible to draw arcs in 3D:: sage: A = arc((0,0,0), 1) Traceback (most recent call last): ... NotImplementedError """ from sage.plot.all import Graphics # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] if scale == 'semilogy' or scale == 'semilogx': options['aspect_ratio'] = 'automatic' if len(center) == 2: if r2 is None: r2 = r1 g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) if len(sector) != 2: raise ValueError("the sector must consist of two angles") g.add_primitive(Arc( center[0], center[1], r1, r2, angle, sector[0], sector[1], options)) return g elif len(center) == 3: raise NotImplementedError
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/arc.py
0.949891
0.639173
arc.py
pypi
from sage.plot.primitive import GraphicPrimitive from sage.misc.decorators import options from sage.arith.srange import xsrange class StreamlinePlot(GraphicPrimitive): """ Primitive class that initializes the StreamlinePlot graphics type """ def __init__(self, xpos_array, ypos_array, xvec_array, yvec_array, options): """ Create the graphics primitive StreamlinePlot. This sets options and the array to be plotted as attributes. EXAMPLES:: sage: x, y = var('x y') sage: R = streamline_plot((sin(x), cos(y)), (x,0,1), (y,0,1), plot_points=2) sage: r = R[0] sage: r.options()['plot_points'] 2 sage: r.xpos_array array([0., 1.]) sage: r.yvec_array masked_array( data=[[1.0, 1.0], [0.5403023058681398, 0.5403023058681398]], mask=[[False, False], [False, False]], fill_value=1e+20) TESTS: We test dumping and loading a plot:: sage: x, y = var('x y') sage: P = streamline_plot((sin(x), cos(y)), (x,-3,3), (y,-3,3)) sage: Q = loads(dumps(P)) """ self.xpos_array = xpos_array self.ypos_array = ypos_array self.xvec_array = xvec_array self.yvec_array = yvec_array GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Returns a dictionary with the bounding box data. EXAMPLES:: sage: x, y = var('x y') sage: d = streamline_plot((.01*x, x+y), (x,10,20), (y,10,20))[0].get_minmax_data() sage: d['xmin'] 10.0 sage: d['ymin'] 10.0 """ from sage.plot.plot import minmax_data return minmax_data(self.xpos_array, self.ypos_array, dict=True) def _allowed_options(self): """ Returns a dictionary with allowed options for StreamlinePlot. EXAMPLES:: sage: x, y = var('x y') sage: P = streamline_plot((sin(x), cos(y)), (x,-3,3), (y,-3,3)) sage: d = P[0]._allowed_options() sage: d['density'] 'Controls the closeness of streamlines' """ return {'plot_points': 'How many points to use for plotting precision', 'color': 'The color of the arrows', 'density': 'Controls the closeness of streamlines', 'start_points': 'Coordinates of starting points for the streamlines', 'zorder': 'The layer level in which to draw'} def _repr_(self): """ String representation of StreamlinePlot graphics primitive. EXAMPLES:: sage: x, y = var('x y') sage: P = streamline_plot((sin(x), cos(y)), (x,-3,3), (y,-3,3)) sage: P[0] StreamlinePlot defined by a 20 x 20 vector grid TESTS:: sage: x, y = var('x y') sage: P = streamline_plot((sin(x), cos(y)), (x,-3,3), (y,-3,3), wrong_option='nonsense') sage: P[0].options()['plot_points'] verbose 0 (...: primitive.py, options) WARNING: Ignoring option 'wrong_option'=nonsense verbose 0 (...: primitive.py, options) The allowed options for StreamlinePlot defined by a 20 x 20 vector grid are: color The color of the arrows density Controls the closeness of streamlines plot_points How many points to use for plotting precision start_points Coordinates of starting points for the streamlines zorder The layer level in which to draw <BLANKLINE> 20 """ return "StreamlinePlot defined by a {} x {} vector grid".format( self._options['plot_points'], self._options['plot_points']) def _render_on_subplot(self, subplot): """ TESTS:: sage: x, y = var('x y') sage: P = streamline_plot((sin(x), cos(y)), (x,-3,3), (y,-3,3)) """ options = self.options() streamplot_options = options.copy() streamplot_options.pop('plot_points') subplot.streamplot(self.xpos_array, self.ypos_array, self.xvec_array, self.yvec_array, **streamplot_options) @options(plot_points=20, density=1., frame=True) def streamline_plot(f_g, xrange, yrange, **options): r""" Return a streamline plot in a vector field. ``streamline_plot`` can take either one or two functions. Consider two variables `x` and `y`. If given two functions `(f(x,y), g(x,y))`, then this function plots streamlines in the vector field over the specified ranges with ``xrange`` being of `x`, denoted by ``xvar`` below, between ``xmin`` and ``xmax``, and ``yrange`` similarly (see below). :: streamline_plot((f, g), (xvar, xmin, xmax), (yvar, ymin, ymax)) Similarly, if given one function `f(x, y)`, then this function plots streamlines in the slope field `dy/dx = f(x,y)` over the specified ranges as given above. PLOT OPTIONS: - ``plot_points`` -- (default: 200) the minimal number of plot points - ``density`` -- float (default: 1.); controls the closeness of streamlines - ``start_points`` -- (optional) list of coordinates of starting points for the streamlines; coordinate pairs can be tuples or lists EXAMPLES: Plot some vector fields involving `\sin` and `\cos`:: sage: x, y = var('x y') sage: streamline_plot((sin(x), cos(y)), (x,-3,3), (y,-3,3)) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y = var('x y') g = streamline_plot((sin(x), cos(y)), (x,-3,3), (y,-3,3)) sphinx_plot(g) :: sage: streamline_plot((y, (cos(x)-2) * sin(x)), (x,-pi,pi), (y,-pi,pi)) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y = var('x y') g = streamline_plot((y, (cos(x)-2) * sin(x)), (x,-pi,pi), (y,-pi,pi)) sphinx_plot(g) We increase the density of the plot:: sage: streamline_plot((y, (cos(x)-2) * sin(x)), (x,-pi,pi), (y,-pi,pi), density=2) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y = var('x y') g = streamline_plot((y, (cos(x)-2) * sin(x)), (x,-pi,pi), (y,-pi,pi), density=2) sphinx_plot(g) We ignore function values that are infinite or NaN:: sage: x, y = var('x y') sage: streamline_plot((-x/sqrt(x^2+y^2), -y/sqrt(x^2+y^2)), (x,-10,10), (y,-10,10)) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y = var('x y') g = streamline_plot((-x/sqrt(x**2+y**2), -y/sqrt(x**2+y**2)), (x,-10,10), (y,-10,10)) sphinx_plot(g) Extra options will get passed on to :func:`show()`, as long as they are valid:: sage: streamline_plot((x, y), (x,-2,2), (y,-2,2), xmax=10) Graphics object consisting of 1 graphics primitive sage: streamline_plot((x, y), (x,-2,2), (y,-2,2)).show(xmax=10) # These are equivalent .. PLOT:: x, y = var('x y') g = streamline_plot((x, y), (x,-2,2), (y,-2,2), xmax=10) sphinx_plot(g) We can also construct streamlines in a slope field:: sage: x, y = var('x y') sage: streamline_plot((x + y) / sqrt(x^2 + y^2), (x,-3,3), (y,-3,3)) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y = var('x y') g = streamline_plot((x + y) / sqrt(x**2 + y**2), (x,-3,3), (y,-3,3)) sphinx_plot(g) We choose some particular points the streamlines pass through:: sage: pts = [[1, 1], [-2, 2], [1, -3/2]] sage: g = streamline_plot((x + y) / sqrt(x^2 + y^2), (x,-3,3), (y,-3,3), start_points=pts) sage: g += point(pts, color='red') sage: g Graphics object consisting of 2 graphics primitives .. PLOT:: x, y = var('x y') pts = [[1, 1], [-2, 2], [1, -3/2]] g = streamline_plot((x + y) / sqrt(x**2 + y**2), (x,-3,3), (y,-3,3), start_points=pts) g += point(pts, color='red') sphinx_plot(g) .. NOTE:: Streamlines currently pass close to ``start_points`` but do not necessarily pass directly through them. That is part of the behavior of matplotlib, not an error on your part. """ # Parse the function input if isinstance(f_g, (list, tuple)): (f,g) = f_g else: from sage.misc.functional import sqrt from sage.misc.sageinspect import is_function_or_cython_function if is_function_or_cython_function(f_g): f = lambda x,y: 1 / sqrt(f_g(x, y)**2 + 1) g = lambda x,y: f_g(x, y) * f(x, y) else: f = 1 / sqrt(f_g**2 + 1) g = f_g * f from sage.plot.all import Graphics from sage.plot.misc import setup_for_eval_on_grid z, ranges = setup_for_eval_on_grid([f,g], [xrange,yrange], options['plot_points']) f, g = z # The density values must be floats if isinstance(options['density'], (list, tuple)): options['density'] = [float(x) for x in options['density']] else: options['density'] = float(options['density']) xpos_array, ypos_array, xvec_array, yvec_array = [], [], [], [] for x in xsrange(*ranges[0], include_endpoint=True): xpos_array.append(x) for y in xsrange(*ranges[1], include_endpoint=True): ypos_array.append(y) xvec_row, yvec_row = [], [] for x in xsrange(*ranges[0], include_endpoint=True): xvec_row.append(f(x, y)) yvec_row.append(g(x, y)) xvec_array.append(xvec_row) yvec_array.append(yvec_row) import numpy xpos_array = numpy.array(xpos_array, dtype=float) ypos_array = numpy.array(ypos_array, dtype=float) xvec_array = numpy.ma.masked_invalid(numpy.array(xvec_array, dtype=float)) yvec_array = numpy.ma.masked_invalid(numpy.array(yvec_array, dtype=float)) if 'start_points' in options: xstart_array, ystart_array = [], [] for point in options['start_points']: xstart_array.append(point[0]) ystart_array.append(point[1]) options['start_points'] = numpy.array([xstart_array, ystart_array]).T g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) g.add_primitive(StreamlinePlot(xpos_array, ypos_array, xvec_array, yvec_array, options)) return g
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/streamline_plot.py
0.952695
0.72323
streamline_plot.py
pypi
import operator from sage.plot.primitive import GraphicPrimitive from sage.misc.decorators import options, suboptions from sage.plot.colors import rgbcolor, get_cmap from sage.arith.srange import xsrange class ContourPlot(GraphicPrimitive): """ Primitive class for the contour plot graphics type. See ``contour_plot?`` for help actually doing contour plots. INPUT: - ``xy_data_array`` - list of lists giving evaluated values of the function on the grid - ``xrange`` - tuple of 2 floats indicating range for horizontal direction - ``yrange`` - tuple of 2 floats indicating range for vertical direction - ``options`` - dict of valid plot options to pass to constructor EXAMPLES: Note this should normally be used indirectly via ``contour_plot``:: sage: from sage.plot.contour_plot import ContourPlot sage: C = ContourPlot([[1,3],[2,4]], (1,2), (2,3), options={}) sage: C ContourPlot defined by a 2 x 2 data grid sage: C.xrange (1, 2) TESTS: We test creating a contour plot:: sage: x,y = var('x,y') sage: contour_plot(x^2-y^3+10*sin(x*y), (x,-4,4), (y,-4,4), ....: plot_points=121, cmap='hsv') Graphics object consisting of 1 graphics primitive """ def __init__(self, xy_data_array, xrange, yrange, options): """ Initialize base class ``ContourPlot``. EXAMPLES:: sage: x,y = var('x,y') sage: C = contour_plot(x^2-y^3+10*sin(x*y), (x,-4,4), (y,-4,4), ....: plot_points=121, cmap='hsv') sage: C[0].xrange (-4.0, 4.0) sage: C[0].options()['plot_points'] 121 """ self.xrange = xrange self.yrange = yrange self.xy_data_array = xy_data_array self.xy_array_row = len(xy_data_array) self.xy_array_col = len(xy_data_array[0]) GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Return a dictionary with the bounding box data. EXAMPLES:: sage: x,y = var('x,y') sage: f(x,y) = x^2 + y^2 sage: d = contour_plot(f, (3,6), (3,6))[0].get_minmax_data() sage: d['xmin'] 3.0 sage: d['ymin'] 3.0 """ from sage.plot.plot import minmax_data return minmax_data(self.xrange, self.yrange, dict=True) def _allowed_options(self): """ Return the allowed options for the ContourPlot class. EXAMPLES:: sage: x,y = var('x,y') sage: C = contour_plot(x^2 - y^2, (x,-2,2), (y,-2,2)) sage: isinstance(C[0]._allowed_options(), dict) True """ return {'plot_points': 'How many points to use for plotting precision', 'cmap': """the name of a predefined colormap, a list of colors, or an instance of a matplotlib Colormap. Type: import matplotlib.cm; matplotlib.cm.datad.keys() for available colormap names.""", 'colorbar': "Include a colorbar indicating the levels", 'colorbar_options': "a dictionary of options for colorbars", 'fill': 'Fill contours or not', 'legend_label': 'The label for this item in the legend.', 'contours': """Either an integer specifying the number of contour levels, or a sequence of numbers giving the actual contours to use.""", 'linewidths': 'the width of the lines to be plotted', 'linestyles': 'the style of the lines to be plotted', 'labels': 'show line labels or not', 'label_options': 'a dictionary of options for the labels', 'zorder': 'The layer level in which to draw'} def _repr_(self): """ String representation of ``ContourPlot`` primitive. EXAMPLES:: sage: x,y = var('x,y') sage: C = contour_plot(x^2 - y^2, (x,-2,2), (y,-2,2)) sage: c = C[0]; c ContourPlot defined by a 100 x 100 data grid """ msg = "ContourPlot defined by a %s x %s data grid" return msg % (self.xy_array_row, self.xy_array_col) def _render_on_subplot(self, subplot): """ TESTS: A somewhat random plot, but fun to look at:: sage: x,y = var('x,y') sage: contour_plot(x^2 - y^3 + 10*sin(x*y), (x,-4,4), (y,-4,4), ....: plot_points=121, cmap='hsv') Graphics object consisting of 1 graphics primitive """ from sage.rings.integer import Integer options = self.options() fill = options['fill'] contours = options['contours'] if 'cmap' in options: cmap = get_cmap(options['cmap']) elif fill or contours is None: cmap = get_cmap('gray') else: if isinstance(contours, (int, Integer)): cmap = get_cmap([(i, i, i) for i in xsrange(0, 1, 1 / contours)]) else: step = 1 / Integer(len(contours)) cmap = get_cmap([(i, i, i) for i in xsrange(0, 1, step)]) x0, x1 = float(self.xrange[0]), float(self.xrange[1]) y0, y1 = float(self.yrange[0]), float(self.yrange[1]) if isinstance(contours, (int, Integer)): contours = int(contours) CSF = None if fill: if contours is None: CSF = subplot.contourf(self.xy_data_array, cmap=cmap, extent=(x0, x1, y0, y1)) else: CSF = subplot.contourf(self.xy_data_array, contours, cmap=cmap, extent=(x0, x1, y0, y1), extend='both') linewidths = options.get('linewidths', None) if isinstance(linewidths, (int, Integer)): linewidths = int(linewidths) elif isinstance(linewidths, (list, tuple)): linewidths = tuple(int(x) for x in linewidths) from sage.plot.misc import get_matplotlib_linestyle linestyles = options.get('linestyles', None) if isinstance(linestyles, (list, tuple)): linestyles = [get_matplotlib_linestyle(i, 'long') for i in linestyles] else: linestyles = get_matplotlib_linestyle(linestyles, 'long') if contours is None: CS = subplot.contour(self.xy_data_array, cmap=cmap, extent=(x0, x1, y0, y1), linewidths=linewidths, linestyles=linestyles) else: CS = subplot.contour(self.xy_data_array, contours, cmap=cmap, extent=(x0, x1, y0, y1), linewidths=linewidths, linestyles=linestyles) if options.get('labels', False): label_options = options['label_options'] label_options['fontsize'] = int(label_options['fontsize']) if fill and label_options is None: label_options['inline'] = False subplot.clabel(CS, **label_options) if options.get('colorbar', False): colorbar_options = options['colorbar_options'] from matplotlib import colorbar cax, kwds = colorbar.make_axes_gridspec(subplot, **colorbar_options) if CSF is None: cb = colorbar.Colorbar(cax, CS, **kwds) else: cb = colorbar.Colorbar(cax, CSF, **kwds) cb.add_lines(CS) @suboptions('colorbar', orientation='vertical', format=None, spacing='uniform') @suboptions('label', fontsize=9, colors='blue', inline=None, inline_spacing=3, fmt="%1.2f") @options(plot_points=100, fill=True, contours=None, linewidths=None, linestyles=None, labels=False, frame=True, axes=False, colorbar=False, legend_label=None, aspect_ratio=1, region=None) def contour_plot(f, xrange, yrange, **options): r""" ``contour_plot`` takes a function of two variables, `f(x,y)` and plots contour lines of the function over the specified ``xrange`` and ``yrange`` as demonstrated below. ``contour_plot(f, (xmin,xmax), (ymin,ymax), ...)`` INPUT: - ``f`` -- a function of two variables - ``(xmin,xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin,ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` The following inputs must all be passed in as named parameters: - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid. For old computers, 25 is fine, but should not be used to verify specific intersection points. - ``fill`` -- bool (default: ``True``), whether to color in the area between contour lines - ``cmap`` -- a colormap (default: ``'gray'``), the name of a predefined colormap, a list of colors or an instance of a matplotlib Colormap. Type: ``import matplotlib.cm; matplotlib.cm.datad.keys()`` for available colormap names. - ``contours`` -- integer or list of numbers (default: ``None``): If a list of numbers is given, then this specifies the contour levels to use. If an integer is given, then this many contour lines are used, but the exact levels are determined automatically. If ``None`` is passed (or the option is not given), then the number of contour lines is determined automatically, and is usually about 5. - ``linewidths`` -- integer or list of integer (default: None), if a single integer all levels will be of the width given, otherwise the levels will be plotted with the width in the order given. If the list is shorter than the number of contours, then the widths will be repeated cyclically. - ``linestyles`` -- string or list of strings (default: None), the style of the lines to be plotted, one of: ``"solid"``, ``"dashed"``, ``"dashdot"``, ``"dotted"``, respectively ``"-"``, ``"--"``, ``"-."``, ``":"``. If the list is shorter than the number of contours, then the styles will be repeated cyclically. - ``labels`` -- boolean (default: False) Show level labels or not. The following options are to adjust the style and placement of labels, they have no effect if no labels are shown. - ``label_fontsize`` -- integer (default: 9), the font size of the labels. - ``label_colors`` -- string or sequence of colors (default: None) If a string, gives the name of a single color with which to draw all labels. If a sequence, gives the colors of the labels. A color is a string giving the name of one or a 3-tuple of floats. - ``label_inline`` -- boolean (default: False if fill is True, otherwise True), controls whether the underlying contour is removed or not. - ``label_inline_spacing`` -- integer (default: 3), When inline, this is the amount of contour that is removed from each side, in pixels. - ``label_fmt`` -- a format string (default: "%1.2f"), this is used to get the label text from the level. This can also be a dictionary with the contour levels as keys and corresponding text string labels as values. It can also be any callable which returns a string when called with a numeric contour level. - ``colorbar`` -- boolean (default: False) Show a colorbar or not. The following options are to adjust the style and placement of colorbars. They have no effect if a colorbar is not shown. - ``colorbar_orientation`` -- string (default: 'vertical'), controls placement of the colorbar, can be either 'vertical' or 'horizontal' - ``colorbar_format`` -- a format string, this is used to format the colorbar labels. - ``colorbar_spacing`` -- string (default: 'proportional'). If 'proportional', make the contour divisions proportional to values. If 'uniform', space the colorbar divisions uniformly, without regard for numeric values. - ``legend_label`` -- the label for this item in the legend - ``region`` - (default: None) If region is given, it must be a function of two variables. Only segments of the surface where region(x,y) returns a number >0 will be included in the plot. .. WARNING:: Due to an implementation detail in matplotlib, single-contour plots whose data all lie on one side of the sole contour may not be plotted correctly. We attempt to detect this situation and to produce something better than an empty plot when it happens; a ``UserWarning`` is emitted in that case. EXAMPLES: Here we plot a simple function of two variables. Note that since the input function is an expression, we need to explicitly declare the variables in 3-tuples for the range:: sage: x,y = var('x,y') sage: contour_plot(cos(x^2 + y^2), (x,-4,4), (y,-4,4)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = contour_plot(cos(x**2 + y**2), (x,-4,4), (y,-4,4)) sphinx_plot(g) Here we change the ranges and add some options:: sage: x,y = var('x,y') sage: contour_plot((x^2) * cos(x*y), (x,-10,5), (y,-5,5), fill=False, plot_points=150) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = contour_plot((x**2) * cos(x*y), (x,-10,5), (y,-5,5), fill=False, plot_points=150) sphinx_plot(g) An even more complicated plot:: sage: x,y = var('x,y') sage: contour_plot(sin(x^2+y^2) * cos(x) * sin(y), (x,-4,4), (y,-4,4), plot_points=150) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = contour_plot(sin(x**2+y**2) * cos(x) * sin(y), (x,-4,4), (y,-4,4),plot_points=150) sphinx_plot(g) Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because we switch the variables `x`, `y`:: sage: x,y = var('x,y') sage: contour_plot(y^2 + 1 - x^3 - x, (y,-pi,pi), (x,-pi,pi)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = contour_plot(y**2 + 1 - x**3 - x, (y,-pi,pi), (x,-pi,pi)) sphinx_plot(g) :: sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi)) sphinx_plot(g) We can play with the contour levels:: sage: x,y = var('x,y') sage: f(x,y) = x^2 + y^2 sage: contour_plot(f, (-2,2), (-2,2)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (-2,2), (-2,2)) sphinx_plot(g) :: sage: contour_plot(f, (-2,2), (-2,2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (-2, 2), (-2, 2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) sphinx_plot(g) :: sage: contour_plot(f, (-2,2), (-2,2), ....: contours=(0.1,1.0,1.2,1.4), cmap='hsv') Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (-2,2), (-2,2), contours=(0.1,1.0,1.2,1.4), cmap='hsv') sphinx_plot(g) :: sage: contour_plot(f, (-2,2), (-2,2), contours=(1.0,), fill=False) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (-2,2), (-2,2), contours=(1.0,), fill=False) sphinx_plot(g) :: sage: contour_plot(x - y^2, (x,-5,5), (y,-3,3), contours=[-4,0,1]) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = contour_plot(x - y**2, (x,-5,5), (y,-3,3), contours=[-4,0,1]) sphinx_plot(g) We can change the style of the lines:: sage: contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) sphinx_plot(g) :: sage: contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') sphinx_plot(g) :: sage: P = contour_plot(x^2 - y^2, (x,-3,3), (y,-3,3), ....: contours=[0,1,2,3,4], linewidths=[1,5], ....: linestyles=['solid','dashed'], fill=False) sage: P Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') P = contour_plot(x**2 - y**2, (x,-3,3), (y,-3,3), contours=[0,1,2,3,4], linewidths=[1,5], linestyles=['solid','dashed'], fill=False) sphinx_plot(P) :: sage: P = contour_plot(x^2 - y^2, (x,-3,3), (y,-3,3), ....: contours=[0,1,2,3,4], linewidths=[1,5], ....: linestyles=['solid','dashed']) sage: P Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') P = contour_plot(x**2 - y**2, (x,-3,3), (y,-3,3), contours=[0,1,2,3,4], linewidths=[1,5], linestyles=['solid','dashed']) sphinx_plot(P) :: sage: P = contour_plot(x^2 - y^2, (x,-3,3), (y,-3,3), ....: contours=[0,1,2,3,4], linewidths=[1,5], ....: linestyles=['-',':']) sage: P Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') P = contour_plot(x**2 - y**2, (x,-3,3), (y,-3,3), contours=[0,1,2,3,4], linewidths=[1,5], linestyles=['-',':']) sphinx_plot(P) We can add labels and play with them:: sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), ....: fill=False, cmap='hsv', labels=True) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) sphinx_plot(P) :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), ....: fill=False, cmap='hsv', ....: labels=True, label_fmt="%1.0f", ....: label_colors='black') sage: P Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') P=contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fmt="%1.0f", label_colors='black') sphinx_plot(P) :: sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), ....: fill=False, cmap='hsv', labels=True, ....: contours=[-4,0,4], ....: label_fmt={-4:"low", 0:"medium", 4: "hi"}, ....: label_colors='black') sage: P Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sphinx_plot(P) :: sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), ....: fill=False, cmap='hsv', labels=True, ....: contours=[-4,0,4], label_fmt=lambda x: "$z=%s$"%x, ....: label_colors='black', label_inline=True, ....: label_fontsize=12) sage: P Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, contours=[-4,0,4], label_fmt=lambda x: "$z=%s$"%x, label_colors='black', label_inline=True, label_fontsize=12) sphinx_plot(P) :: sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), ....: fill=False, cmap='hsv', labels=True, ....: label_fontsize=18) sage: P Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fontsize=18) sphinx_plot(P) :: sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), ....: fill=False, cmap='hsv', labels=True, ....: label_inline_spacing=1) sage: P Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sphinx_plot(P) :: sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), ....: fill=False, cmap='hsv', labels=True, ....: label_inline=False) sage: P Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline=False) sphinx_plot(P) We can change the color of the labels if so desired:: sage: contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') sphinx_plot(g) We can add a colorbar as well:: sage: f(x, y) = x^2 + y^2 sage: contour_plot(f, (x,-3,3), (y,-3,3), colorbar=True) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (x,-3,3), (y,-3,3), colorbar=True) sphinx_plot(g) :: sage: contour_plot(f, (x,-3,3), (y,-3,3), colorbar=True, colorbar_orientation='horizontal') Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (x,-3,3), (y,-3,3), colorbar=True, colorbar_orientation='horizontal') sphinx_plot(g) :: sage: contour_plot(f, (x,-3,3), (y,-3,3), contours=[-2,-1,4], colorbar=True) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (x,-3,3), (y,-3,3), contours=[-2,-1,4], colorbar=True) sphinx_plot(g) :: sage: contour_plot(f, (x,-3,3), (y,-3,3), contours=[-2,-1,4], ....: colorbar=True, colorbar_spacing='uniform') Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (x,-3,3), (y,-3,3), contours=[-2,-1,4], colorbar=True, colorbar_spacing='uniform') sphinx_plot(g) :: sage: contour_plot(f, (x,-3,3), (y,-3,3), contours=[0,2,3,6], ....: colorbar=True, colorbar_format='%.3f') Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (x,-3,3), (y,-3,3), contours=[0,2,3,6], colorbar=True, colorbar_format='%.3f') sphinx_plot(g) :: sage: contour_plot(f, (x,-3,3), (y,-3,3), labels=True, ....: label_colors='red', contours=[0,2,3,6], ....: colorbar=True) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (x,-3,3), (y,-3,3), labels=True, label_colors='red', contours=[0,2,3,6], colorbar=True) sphinx_plot(g) :: sage: contour_plot(f, (x,-3,3), (y,-3,3), cmap='winter', ....: contours=20, fill=False, colorbar=True) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return x**2 + y**2 g = contour_plot(f, (x,-3,3), (y,-3,3), cmap='winter', contours=20, fill=False, colorbar=True) sphinx_plot(g) This should plot concentric circles centered at the origin:: sage: x,y = var('x,y') sage: contour_plot(x^2 + y^2-2,(x,-1,1), (y,-1,1)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = contour_plot(x**2 + y**2-2,(x,-1,1), (y,-1,1)) sphinx_plot(g) Extra options will get passed on to show(), as long as they are valid:: sage: f(x,y) = cos(x) + sin(y) sage: contour_plot(f, (0,pi), (0,pi), axes=True) Graphics object consisting of 1 graphics primitive :: sage: contour_plot(f, (0,pi), (0,pi)).show(axes=True) # These are equivalent .. PLOT:: x,y = var('x,y') def f(x,y): return cos(x) + sin(y) g = contour_plot(f, (0,pi), (0,pi), axes=True) sphinx_plot(g) One can also plot over a reduced region:: sage: contour_plot(x**2 - y**2, (x,-2,2), (y,-2,2), region=x - y, plot_points=300) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = contour_plot(x**2 - y**2, (x,-2,2), (y,-2,2), region=x - y, plot_points=300) sphinx_plot(g) Note that with ``fill=False`` and grayscale contours, there is the possibility of confusion between the contours and the axes, so use ``fill=False`` together with ``axes=True`` with caution:: sage: contour_plot(f, (-pi,pi), (-pi,pi), fill=False, axes=True) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') def f(x,y): return cos(x) + sin(y) g = contour_plot(f, (-pi,pi), (-pi,pi), fill=False, axes=True) sphinx_plot(g) If you are plotting a sole contour and if all of your data lie on one side of it, then (as part of :trac:`21042`) a heuristic may be used to improve the result; in that case, a warning is emitted:: sage: contour_plot(lambda x,y: abs(x^2-y^2), (-1,1), (-1,1), ....: contours=[0], fill=False, cmap=['blue']) ... UserWarning: pathological contour plot of a function whose values all lie on one side of the sole contour; we are adding more plot points and perturbing your function values. Graphics object consisting of 1 graphics primitive .. PLOT:: import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") g = contour_plot(lambda x,y: abs(x**2-y**2), (-1,1), (-1,1), contours=[0], fill=False, cmap=['blue']) sphinx_plot(g) Constant functions (with a single contour) can be plotted as well; this was not possible before :trac:`21042`:: sage: contour_plot(lambda x,y: 0, (-1,1), (-1,1), ....: contours=[0], fill=False, cmap=['blue']) ... UserWarning: No contour levels were found within the data range. Graphics object consisting of 1 graphics primitive .. PLOT:: import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") g = contour_plot(lambda x,y: 0, (-1,1), (-1,1), contours=[0], fill=False, cmap=['blue']) sphinx_plot(g) TESTS: To check that :trac:`5221` is fixed, note that this has three curves, not two:: sage: x,y = var('x,y') sage: contour_plot(x - y^2, (x,-5,5), (y,-3,3), ....: contours=[-4,-2,0], fill=False) Graphics object consisting of 1 graphics primitive Check that :trac:`18074` is fixed:: sage: contour_plot(0, (0,1), (0,1)) ... UserWarning: No contour levels were found within the data range. Graphics object consisting of 1 graphics primitive Domain points in :trac:`11648` with complex output are now skipped:: sage: x,y = SR.var('x,y', domain='real') sage: contour_plot(log(x) + log(y), (-1, 5), (-1, 5)) Graphics object consisting of 1 graphics primitive """ from sage.plot.all import Graphics from sage.plot.misc import setup_for_eval_on_grid region = options.pop('region') ev = [f] if region is None else [f, region] F, ranges = setup_for_eval_on_grid(ev, [xrange, yrange], options['plot_points']) h = F[0] xrange, yrange = [r[:2] for r in ranges] xy_data_array = [[h(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] g = Graphics() # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] if scale in ('semilogy', 'semilogx'): options['aspect_ratio'] = 'automatic' g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) # Was a single contour level explicitly given? If "contours" is # the integer 1, then there will be a single level, but we can't # know what it is because it's determined within matplotlib's # "contour" or "contourf" function. So we punt in that case. If # there's a single contour and fill=True, we fall through to let # matplotlib complain that "Filled contours require at least 2 # levels." if (isinstance(options["contours"], (list, tuple)) and len(options["contours"]) == 1 and options.get("fill") is False): # When there's only one level (say, zero), matplotlib doesn't # handle it well. If all of the data lie on one side of that # level -- for example, if f(x,y) >= 0 for all x,y -- then it # will fail to plot the points where f(x,y) == 0. This is # especially catastrophic for implicit_plot(), which tries to # do just that. Here we handle that special case: if there's # only one level, and if all of the data lie on one side of # it, we perturb the data a bit so that they don't. The resulting # plots don't look great, but they're not empty, which is an # improvement. import numpy as np dx = ranges[0][2] dy = ranges[1][2] z0 = options["contours"][0] # This works OK for the examples in the doctests, but basing # it off the plot scale rather than how fast the function # changes can never be truly satisfactory. tol = max(dx, dy) / 4.0 xy_data_array = np.ma.asarray(xy_data_array, dtype=float) # Special case for constant functions. This is needed because # otherwise the forthcoming perturbation trick will take values # like 0,0,0... and perturb them to -tol, -tol, -tol... which # doesn't work for the same reason 0,0,0... doesn't work. if np.all(np.abs(xy_data_array - z0) <= tol): # Up to our tolerance, this is the const_z0 function. # ...make it actually the const_z0 function. xy_data_array.fill(z0) # We're going to set fill=True in a momemt, so we need to # prepend an entry to the cmap so that the user's original # cmap winds up in the right place. if "cmap" in options: if isinstance(options["cmap"], (list, tuple)): oldcmap = options["cmap"][0] else: oldcmap = options["cmap"] else: # The docs promise this as the default. oldcmap = "gray" # Trick matplotlib into plotting all of the points (minus # those masked) by using a single, filled contour that # covers the entire plotting surface. options["cmap"] = ["white", oldcmap] options["contours"] = (z0 - 1, z0) options["fill"] = True else: # The "c" constant is set to plus/minus one to handle both # of the "all values greater than z0" and "all values less # than z0" cases at once. c = 1 if np.all(xy_data_array <= z0): xy_data_array *= -1 c = -1 # Now we check if (a) all of the data lie on one side of # z0, and (b) if perturbing the data will actually help by # moving anything across z0. if (np.all(xy_data_array >= z0) and np.any(xy_data_array - z0 < tol)): from warnings import warn warn("pathological contour plot of a function whose " "values all lie on one side of the sole contour; " "we are adding more plot points and perturbing " "your function values.") # The choice of "4" here is not based on much of anything. # It works well enough for the examples in the doctests. if not isinstance(options["plot_points"], (list, tuple)): options["plot_points"] = (options["plot_points"], options["plot_points"]) options["plot_points"] = (options["plot_points"][0] * 4, options["plot_points"][1] * 4) # Re-plot with more points... F, ranges = setup_for_eval_on_grid(ev, [xrange, yrange], options['plot_points']) h = F[0] xrange, yrange = [r[:2] for r in ranges] # ...and a function whose values are shifted towards # z0 by "tol". xy_data_array = [[h(x, y) - c * tol for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] if region is not None: import numpy xy_data_array = numpy.ma.asarray(xy_data_array, dtype=float) m = F[1] mask = numpy.asarray([[m(x, y) <= 0 for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], dtype=bool) xy_data_array[mask] = numpy.ma.masked g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, options)) return g @options(plot_points=150, contours=(0,), fill=False, cmap=["blue"]) def implicit_plot(f, xrange, yrange, **options): r""" ``implicit_plot`` takes a function of two variables, `f(x, y)` and plots the curve `f(x,y) = 0` over the specified ``xrange`` and ``yrange`` as demonstrated below. ``implicit_plot(f, (xmin,xmax), (ymin,ymax), ...)`` ``implicit_plot(f, (x,xmin,xmax), (y,ymin,ymax), ...)`` INPUT: - ``f`` -- a function of two variables or equation in two variables - ``(xmin,xmax)`` -- 2-tuple, the range of ``x`` values or ``(x,xmin,xmax)`` - ``(ymin,ymax)`` -- 2-tuple, the range of ``y`` values or ``(y,ymin,ymax)`` The following inputs must all be passed in as named parameters: - ``plot_points`` -- integer (default: 150); number of points to plot in each direction of the grid - ``fill`` -- boolean (default: ``False``); if ``True``, fill the region `f(x, y) < 0`. - ``fillcolor`` -- string (default: ``'blue'``), the color of the region where `f(x,y) < 0` if ``fill = True``. Colors are defined in :mod:`sage.plot.colors`; try ``colors?`` to see them all. - ``linewidth`` -- integer (default: None), if a single integer all levels will be of the width given, otherwise the levels will be plotted with the widths in the order given. - ``linestyle`` -- string (default: None), the style of the line to be plotted, one of: ``"solid"``, ``"dashed"``, ``"dashdot"`` or ``"dotted"``, respectively ``"-"``, ``"--"``, ``"-."``, or ``":"``. - ``color`` -- string (default: ``'blue'``), the color of the plot. Colors are defined in :mod:`sage.plot.colors`; try ``colors?`` to see them all. If ``fill = True``, then this sets only the color of the border of the plot. See ``fillcolor`` for setting the color of the fill region. - ``legend_label`` -- the label for this item in the legend - ``base`` -- (default: 10) the base of the logarithm if a logarithmic scale is set. This must be greater than 1. The base can be also given as a list or tuple ``(basex, basey)``. ``basex`` sets the base of the logarithm along the horizontal axis and ``basey`` sets the base along the vertical axis. - ``scale`` -- (default: ``"linear"``) string. The scale of the axes. Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``, ``"semilogy"``. The scale can be also be given as single argument that is a list or tuple ``(scale, base)`` or ``(scale, basex, basey)``. The ``"loglog"`` scale sets both the horizontal and vertical axes to logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis to logarithmic scale. The ``"linear"`` scale is the default value when :class:`~sage.plot.graphics.Graphics` is initialized. .. WARNING:: Due to an implementation detail in matplotlib, implicit plots whose data are all nonpositive or nonnegative may not be plotted correctly. We attempt to detect this situation and to produce something better than an empty plot when it happens; a ``UserWarning`` is emitted in that case. EXAMPLES: A simple circle with a radius of 2. Note that since the input function is an expression, we need to explicitly declare the variables in 3-tuples for the range:: sage: var("x y") (x, y) sage: implicit_plot(x^2 + y^2 - 2, (x,-3,3), (y,-3,3)) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y =var("x y") g = implicit_plot(x**2 + y**2 - 2, (x,-3,3), (y,-3,3)) sphinx_plot(g) We can do the same thing, but using a callable function so we do not need to explicitly define the variables in the ranges. We also fill the inside:: sage: f(x,y) = x^2 + y^2 - 2 sage: implicit_plot(f, (-3,3), (-3,3), fill=True, plot_points=500) # long time Graphics object consisting of 2 graphics primitives .. PLOT:: def f(x,y): return x**2 + y**2 - 2 g = implicit_plot(f, (-3,3), (-3,3), fill=True, plot_points=500) sphinx_plot(g) The same circle but with a different line width:: sage: implicit_plot(f, (-3,3), (-3,3), linewidth=6) Graphics object consisting of 1 graphics primitive .. PLOT:: def f(x,y): return x**2 + y**2 - 2 g = implicit_plot(f, (-3,3), (-3,3), linewidth=6) sphinx_plot(g) Again the same circle but this time with a dashdot border:: sage: implicit_plot(f, (-3,3), (-3,3), linestyle='dashdot') Graphics object consisting of 1 graphics primitive .. PLOT:: x, y =var("x y") def f(x,y): return x**2 + y**2 - 2 g = implicit_plot(f, (-3,3), (-3,3), linestyle='dashdot') sphinx_plot(g) The same circle with different line and fill colors:: sage: implicit_plot(f, (-3,3), (-3,3), color='red', fill=True, fillcolor='green', ....: plot_points=500) # long time Graphics object consisting of 2 graphics primitives .. PLOT:: def f(x,y): return x**2 + y**2 - 2 g = implicit_plot(f, (-3,3), (-3,3), color='red', fill=True, fillcolor='green', plot_points=500) sphinx_plot(g) You can also plot an equation:: sage: var("x y") (x, y) sage: implicit_plot(x^2 + y^2 == 2, (x,-3,3), (y,-3,3)) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y =var("x y") g = implicit_plot(x**2 + y**2 == 2, (x,-3,3), (y,-3,3)) sphinx_plot(g) You can even change the color of the plot:: sage: implicit_plot(x^2 + y^2 == 2, (x,-3,3), (y,-3,3), color="red") Graphics object consisting of 1 graphics primitive .. PLOT:: x, y =var("x y") g = implicit_plot(x**2 + y**2 == 2, (x,-3,3), (y,-3,3), color="red") sphinx_plot(g) The color of the fill region can be changed:: sage: implicit_plot(x**2 + y**2 == 2, (x,-3,3), (y,-3,3), fill=True, fillcolor='red') Graphics object consisting of 2 graphics primitives .. PLOT:: x, y =var("x y") g = implicit_plot(x**2 + y**2 == 2, (x,-3,3), (y,-3,3), fill=True, fillcolor="red") sphinx_plot(g) Here is a beautiful (and long) example which also tests that all colors work with this:: sage: G = Graphics() sage: counter = 0 sage: for col in colors.keys(): # long time ....: G += implicit_plot(x^2 + y^2 == 1 + counter*.1, (x,-4,4),(y,-4,4), color=col) ....: counter += 1 sage: G # long time Graphics object consisting of 148 graphics primitives .. PLOT:: x, y = var("x y") G = Graphics() counter = 0 for col in colors.keys(): G += implicit_plot(x**2 + y**2 == 1 + counter*.1, (x,-4,4), (y,-4,4), color=col) counter += 1 sphinx_plot(G) We can define a level-`n` approximation of the boundary of the Mandelbrot set:: sage: def mandel(n): ....: c = polygen(CDF, 'c') ....: z = 0 ....: for i in range(n): ....: z = z*z + c ....: def f(x,y): ....: val = z(CDF(x, y)) ....: return val.norm() - 4 ....: return f The first-level approximation is just a circle:: sage: implicit_plot(mandel(1), (-3,3), (-3,3)) Graphics object consisting of 1 graphics primitive .. PLOT:: def mandel(n): c = polygen(CDF, 'c') z = 0 for i in range(n): z = z*z + c def f(x,y): val = z(CDF(x, y)) return val.norm() - 4 return f g = implicit_plot(mandel(1), (-3,3), (-3,3)) sphinx_plot(g) A third-level approximation starts to get interesting:: sage: implicit_plot(mandel(3), (-2,1), (-1.5,1.5)) Graphics object consisting of 1 graphics primitive .. PLOT:: def mandel(n): c = polygen(CDF, 'c') z = 0 for i in range(n): z = z*z + c def f(x,y): val = z(CDF(x, y)) return val.norm() - 4 return f g = implicit_plot(mandel(3), (-2,1), (-1.5,1.5)) sphinx_plot(g) The seventh-level approximation is a degree 64 polynomial, and ``implicit_plot`` does a pretty good job on this part of the curve. (``plot_points=200`` looks even better, but it takes over a second.) :: sage: implicit_plot(mandel(7), (-0.3, 0.05), (-1.15, -0.9), plot_points=50) Graphics object consisting of 1 graphics primitive .. PLOT:: def mandel(n): c = polygen(CDF, 'c') z = 0 for i in range(n): z = z*z + c def f(x,y): val = z(CDF(x, y)) return val.norm() - 4 return f g = implicit_plot(mandel(7), (-0.3,0.05), (-1.15,-0.9), plot_points=50) sphinx_plot(g) When making a filled implicit plot using a python function rather than a symbolic expression the user should increase the number of plot points to avoid artifacts:: sage: implicit_plot(lambda x, y: x^2 + y^2 - 2, (x,-3,3), (y,-3,3), ....: fill=True, plot_points=500) # long time Graphics object consisting of 2 graphics primitives .. PLOT:: x, y = var("x y") g = implicit_plot(lambda x, y: x**2 + y**2 - 2, (x,-3,3), (y,-3,3), fill=True, plot_points=500) sphinx_plot(g) An example of an implicit plot on 'loglog' scale:: sage: implicit_plot(x^2 + y^2 == 200, (x,1,200), (y,1,200), scale='loglog') Graphics object consisting of 1 graphics primitive .. PLOT:: x, y = var("x y") g = implicit_plot(x**2 + y**2 == 200, (x,1,200), (y,1,200), scale='loglog') sphinx_plot(g) TESTS:: sage: f(x,y) = x^2 + y^2 - 2 sage: implicit_plot(f, (-3,3), (-3,3), fill=5) Traceback (most recent call last): ... ValueError: fill=5 is not supported To check that :trac:`9654` is fixed:: sage: f(x,y) = x^2 + y^2 - 2 sage: implicit_plot(f, (-3,3), (-3,3), rgbcolor=(1,0,0)) Graphics object consisting of 1 graphics primitive sage: implicit_plot(f, (-3,3), (-3,3), color='green') Graphics object consisting of 1 graphics primitive sage: implicit_plot(f, (-3,3), (-3,3), rgbcolor=(1,0,0), color='green') Traceback (most recent call last): ... ValueError: only one of color or rgbcolor should be specified """ from sage.structure.element import Expression if isinstance(f, Expression) and f.is_relational(): if f.operator() != operator.eq: raise ValueError("input to implicit plot must be function " "or equation") f = f.lhs() - f.rhs() linewidths = options.pop('linewidth', None) linestyles = options.pop('linestyle', None) if 'color' in options and 'rgbcolor' in options: raise ValueError('only one of color or rgbcolor should be specified') if 'color' in options: options['cmap'] = [options.pop('color', None)] elif 'rgbcolor' in options: options['cmap'] = [rgbcolor(options.pop('rgbcolor', None))] if options['fill'] is True: options.pop('fill') options.pop('contours', None) incol = options.pop('fillcolor', 'blue') bordercol = options.pop('cmap', [None])[0] from sage.structure.element import Expression if not isinstance(f, Expression): return region_plot(lambda x, y: f(x, y) < 0, xrange, yrange, borderwidth=linewidths, borderstyle=linestyles, incol=incol, bordercol=bordercol, **options) return region_plot(f < 0, xrange, yrange, borderwidth=linewidths, borderstyle=linestyles, incol=incol, bordercol=bordercol, **options) elif options['fill'] is False: options.pop('fillcolor', None) return contour_plot(f, xrange, yrange, linewidths=linewidths, linestyles=linestyles, **options) else: raise ValueError("fill=%s is not supported" % options['fill']) @options(plot_points=100, incol='blue', outcol=None, bordercol=None, borderstyle=None, borderwidth=None, frame=False, axes=True, legend_label=None, aspect_ratio=1, alpha=1) def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth, alpha, **options): r""" ``region_plot`` takes a boolean function of two variables, `f(x, y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin,xmax), (ymin,ymax), ...)`` INPUT: - ``f`` -- a boolean function or a list of boolean functions of two variables - ``(xmin,xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin,ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``None``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: ``'solid'``), one of ``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``, respectively ``'-'``, ``'--'``, ``':'``, ``'-.'``. - ``borderwidth`` -- integer (default: ``None``), the width of the border in pixels - ``alpha`` -- (default: 1) how transparent the fill is; a number between 0 and 1 - ``legend_label`` -- the label for this item in the legend - ``base`` - (default: 10) the base of the logarithm if a logarithmic scale is set. This must be greater than 1. The base can be also given as a list or tuple ``(basex, basey)``. ``basex`` sets the base of the logarithm along the horizontal axis and ``basey`` sets the base along the vertical axis. - ``scale`` -- (default: ``"linear"``) string. The scale of the axes. Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``, ``"semilogy"``. The scale can be also be given as single argument that is a list or tuple ``(scale, base)`` or ``(scale, basex, basey)``. The ``"loglog"`` scale sets both the horizontal and vertical axes to logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis to logarithmic scale. The ``"linear"`` scale is the default value when :class:`~sage.plot.graphics.Graphics` is initialized. EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2 + y^2) <= 0, (x,-3,3), (y,-3,3)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = region_plot(cos(x**2 + y**2) <= 0, (x,-3,3), (y,-3,3)) sphinx_plot(g) Here we play with the colors:: sage: region_plot(x^2 + y^3 < 2, (x,-2,2), (y,-2,2), incol='lightblue', bordercol='gray') Graphics object consisting of 2 graphics primitives .. PLOT:: x,y = var('x,y') g = region_plot(x**2 + y**3 < 2, (x,-2,2), (y,-2,2), incol='lightblue', bordercol='gray') sphinx_plot(g) An even more complicated plot, with dashed borders:: sage: region_plot(sin(x) * sin(y) >= 1/4, (x,-10,10), (y,-10,10), ....: incol='yellow', bordercol='black', ....: borderstyle='dashed', plot_points=250) Graphics object consisting of 2 graphics primitives .. PLOT:: x,y = var('x,y') g = region_plot(sin(x) * sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) sphinx_plot(g) A disk centered at the origin:: sage: region_plot(x^2 + y^2 < 1, (x,-1,1), (y,-1,1)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = region_plot(x**2 + y**2 < 1, (x,-1,1), (y,-1,1)) sphinx_plot(g) A plot with more than one condition (all conditions must be true for the statement to be true):: sage: region_plot([x^2 + y^2 < 1, x < y], (x,-2,2), (y,-2,2)) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = region_plot([x**2 + y**2 < 1, x < y], (x,-2,2), (y,-2,2)) sphinx_plot(g) Since it does not look very good, let us increase ``plot_points``:: sage: region_plot([x^2 + y^2 < 1, x< y], (x,-2,2), (y,-2,2), plot_points=400) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = region_plot([x**2 + y**2 < 1, x < y], (x,-2,2), (y,-2,2), plot_points=400) sphinx_plot(g) To get plots where only one condition needs to be true, use a function. Using lambda functions, we definitely need the extra ``plot_points``:: sage: region_plot(lambda x, y: x^2 + y^2 < 1 or x < y, (x,-2,2), (y,-2,2), plot_points=400) Graphics object consisting of 1 graphics primitive .. PLOT:: x,y = var('x,y') g = region_plot(lambda x, y: x**2 + y**2 < 1 or x < y, (x,-2,2), (y,-2,2), plot_points=400) sphinx_plot(g) The first quadrant of the unit circle:: sage: region_plot([y > 0, x > 0, x^2 + y^2 < 1], (x,-1.1,1.1), (y,-1.1,1.1), plot_points=400) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y = var("x y") g = region_plot([y > 0, x > 0, x**2 + y**2 < 1], (x,-1.1,1.1), (y,-1.1,1.1), plot_points=400) sphinx_plot(g) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1) + y^2 < 0, (x,-3,2), (y,-3,3), ....: incol='lightblue', bordercol='gray', borderwidth=10, ....: plot_points=50) Graphics object consisting of 2 graphics primitives .. PLOT:: x, y = var("x y") g = region_plot(x*(x-1)*(x+1) + y**2 < 0, (x,-3,2), (y,-3,3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) sphinx_plot(g) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1) + y^2 < 0, x > -1], (x,-3,2), (y,-3,3), ....: incol='lightblue', plot_points=50) Graphics object consisting of 1 graphics primitive .. PLOT:: x, y =var("x y") g = region_plot([x*(x-1)*(x+1) + y**2 < 0, x > -1], (x,-3,2), (y,-3,3), incol='lightblue', plot_points=50) sphinx_plot(g) Here we have a cut circle:: sage: region_plot([x^2 + y^2 < 4, x > -1], (x,-2,2), (y,-2,2), ....: incol='lightblue', bordercol='gray', plot_points=200) Graphics object consisting of 2 graphics primitives .. PLOT:: x, y =var("x y") g = region_plot([x**2 + y**2 < 4, x > -1], (x,-2,2), (y,-2,2), incol='lightblue', bordercol='gray', plot_points=200) sphinx_plot(g) The first variable range corresponds to the horizontal axis and the second variable range corresponds to the vertical axis:: sage: s, t = var('s, t') sage: region_plot(s > 0, (t,-2,2), (s,-2,2)) Graphics object consisting of 1 graphics primitive .. PLOT:: s, t = var('s, t') g = region_plot(s > 0, (t,-2,2), (s,-2,2)) sphinx_plot(g) :: sage: region_plot(s>0,(s,-2,2),(t,-2,2)) Graphics object consisting of 1 graphics primitive .. PLOT:: s, t = var('s, t') g = region_plot(s > 0, (s,-2,2), (t,-2,2)) sphinx_plot(g) An example of a region plot in 'loglog' scale:: sage: region_plot(x^2 + y^2 < 100, (x,1,10), (y,1,10), scale='loglog') Graphics object consisting of 1 graphics primitive .. PLOT:: x, y = var("x y") g = region_plot(x**2 + y**2 < 100, (x,1,10), (y,1,10), scale='loglog') sphinx_plot(g) TESTS: To check that :trac:`16907` is fixed:: sage: x, y = var('x, y') sage: disc1 = region_plot(x^2 + y^2 < 1, (x,-1,1), (y,-1,1), alpha=0.5) sage: disc2 = region_plot((x-0.7)^2 + (y-0.7)^2 < 0.5, (x,-2,2), (y,-2,2), incol='red', alpha=0.5) sage: disc1 + disc2 Graphics object consisting of 2 graphics primitives To check that :trac:`18286` is fixed:: sage: x, y = var('x, y') sage: region_plot([x == 0], (x,-1,1), (y,-1,1)) Graphics object consisting of 1 graphics primitive sage: region_plot([x^2 + y^2 == 1, x < y], (x,-1,1), (y,-1,1)) Graphics object consisting of 1 graphics primitive """ from sage.plot.all import Graphics from sage.plot.misc import setup_for_eval_on_grid from sage.structure.element import Expression from warnings import warn import numpy if not isinstance(f, (list, tuple)): f = [f] feqs = [equify(g) for g in f if isinstance(g, Expression) and g.operator() is operator.eq and not equify(g).is_zero()] f = [equify(g) for g in f if not (isinstance(g, Expression) and g.operator() is operator.eq)] neqs = len(feqs) if neqs > 1: warn("There are at least 2 equations; " "If the region is degenerated to points, " "plotting might show nothing.") feqs = [sum([fn**2 for fn in feqs])] neqs = 1 if neqs and not bordercol: bordercol = incol if not f: return implicit_plot(feqs[0], xrange, yrange, plot_points=plot_points, fill=False, linewidth=borderwidth, linestyle=borderstyle, color=bordercol, **options) f_all, ranges = setup_for_eval_on_grid(feqs + f, [xrange, yrange], plot_points) xrange, yrange = [r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in f_all[neqs::]], dtype=float) xy_data_array = numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays < 0).all(axis=0) xy_data_array[neg_indices] = -xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) if outcol: outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol, alpha=alpha) else: outcol = rgbcolor('white') cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol, alpha=0) cmap.set_under(incol, alpha=alpha) g = Graphics() # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] if scale in ('semilogy', 'semilogx'): options['aspect_ratio'] = 'automatic' g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) if neqs == 0: g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(contours=[-1e-20, 0, 1e-20], cmap=cmap, fill=True, **options))) else: mask = numpy.asarray([[elt > 0 for elt in rows] for rows in xy_data_array], dtype=bool) xy_data_array = numpy.asarray([[f_all[0](x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], dtype=float) xy_data_array[mask] = None if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **options))) return g def equify(f): """ Return the equation rewritten as a symbolic function to give negative values when ``True``, positive when ``False``. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x^2 - 2 sage: equify(x^2 > 2) -x^2 + 2 sage: equify(x*y > 1) -x*y + 1 sage: equify(y > 0) -y sage: f = equify(lambda x, y: x > y) sage: f(1, 2) 1 sage: f(2, 1) -1 """ from sage.calculus.all import symbolic_expression from sage.structure.element import Expression if not isinstance(f, Expression): return lambda x, y: -1 if f(x, y) else 1 op = f.operator() if op is operator.gt or op is operator.ge: return symbolic_expression(f.rhs() - f.lhs()) return symbolic_expression(f.lhs() - f.rhs())
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/contour_plot.py
0.892451
0.550245
contour_plot.py
pypi
from sage.plot.primitive import GraphicPrimitive from sage.misc.decorators import options, rename_keyword from sage.plot.colors import to_mpl_color class Text(GraphicPrimitive): """ Base class for Text graphics primitive. TESTS: We test creating some text:: sage: text("I like Fibonacci",(3,5)) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(text("I like Fibonacci",(3,5))) """ def __init__(self, string, point, options): """ Initialize base class Text. EXAMPLES:: sage: T = text("I like Fibonacci", (3,5)) sage: t = T[0] sage: t.string 'I like Fibonacci' sage: t.x 3.0 sage: t.options()['fontsize'] 10 """ self.string = string self.x = float(point[0]) self.y = float(point[1]) GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Return a dictionary with the bounding box data. Notice that, for text, the box is just the location itself. EXAMPLES:: sage: T = text("Where am I?",(1,1)) sage: t=T[0] sage: t.get_minmax_data()['ymin'] 1.0 sage: t.get_minmax_data()['ymax'] 1.0 """ from sage.plot.plot import minmax_data return minmax_data([self.x], [self.y], dict=True) def _repr_(self): """ String representation of Text primitive. EXAMPLES:: sage: T = text("I like cool constants", (pi,e)) sage: t=T[0];t Text 'I like cool constants' at the point (3.1415926535...,2.7182818284...) """ return "Text '%s' at the point (%s,%s)" % (self.string, self.x, self.y) def _allowed_options(self): """ Return the allowed options for the Text class. EXAMPLES:: sage: T = text("ABC",(1,1),zorder=3) sage: T[0]._allowed_options()['fontsize'] "How big the text is. Either the size in points or a relative size, e.g. 'smaller', 'x-large', etc" sage: T[0]._allowed_options()['zorder'] 'The layer level in which to draw' sage: T[0]._allowed_options()['rotation'] 'How to rotate the text: angle in degrees, vertical, horizontal' """ return {'fontsize': 'How big the text is. Either the size in points or a relative size, e.g. \'smaller\', \'x-large\', etc', 'fontstyle': 'A string either \'normal\', \'italic\' or \'oblique\'', 'fontweight': 'A numeric value in the range 0-1000 or a string' '\'ultralight\', \'light\', \'normal\', \'regular\', \'book\',' '\'medium\', \'roman\', \'semibold\', \'demibold\', \'demi\',' '\'bold,\', \'heavy\', \'extra bold\', \'black\'', 'rgbcolor': 'The color as an RGB tuple', 'background_color': 'The background color', 'bounding_box': 'A dictionary specifying a bounding box', 'hue': 'The color given as a hue', 'alpha': 'A float (0.0 transparent through 1.0 opaque)', 'axis_coords': 'If True use axis coordinates: (0,0) lower left and (1,1) upper right', 'rotation': 'How to rotate the text: angle in degrees, vertical, horizontal', 'vertical_alignment': 'How to align vertically: top, center, bottom', 'horizontal_alignment': 'How to align horizontally: left, center, right', 'zorder': 'The layer level in which to draw', 'clip': 'Whether to clip or not'} def _plot3d_options(self, options=None): """ Translate 2D plot options into 3D plot options. EXAMPLES:: sage: T = text("ABC",(1,1)) sage: t = T[0] sage: t.options()['rgbcolor'] (0.0, 0.0, 1.0) sage: s=t.plot3d() sage: s.jmol_repr(s.testing_render_params())[0][1] 'color atom [0,0,255]' """ if options is None: options = dict(self.options()) options_3d = {} for s in ['fontfamily', 'fontsize', 'fontstyle', 'fontweight']: if s in options: options_3d[s] = options.pop(s) # TODO: figure out how to implement rather than ignore for s in ['axis_coords', 'clip', 'horizontal_alignment', 'rotation', 'vertical_alignment']: if s in options: del options[s] options_3d.update(GraphicPrimitive._plot3d_options(self, options)) return options_3d def plot3d(self, **kwds): """ Plot 2D text in 3D. EXAMPLES:: sage: T = text("ABC", (1, 1)) sage: t = T[0] sage: s = t.plot3d() sage: s.jmol_repr(s.testing_render_params())[0][2] 'label "ABC"' sage: s._trans (1.0, 1.0, 0) """ from sage.plot.plot3d.shapes2 import text3d options = self._plot3d_options() options.update(kwds) return text3d(self.string, (self.x, self.y, 0), **options) def _render_on_subplot(self, subplot): """ TESTS:: sage: t1 = text("Hello",(1,1), vertical_alignment="top", fontsize=30, rgbcolor='black') sage: t2 = text("World", (1,1), horizontal_alignment="left", fontsize=20, zorder=-1) sage: t1 + t2 # render the sum Graphics object consisting of 2 graphics primitives """ options = self.options() opts = {} opts['color'] = options['rgbcolor'] opts['verticalalignment'] = options['vertical_alignment'] opts['horizontalalignment'] = options['horizontal_alignment'] if 'background_color' in options: opts['backgroundcolor'] = options['background_color'] if 'fontweight' in options: opts['fontweight'] = options['fontweight'] if 'alpha' in options: opts['alpha'] = options['alpha'] if 'fontstyle' in options: opts['fontstyle'] = options['fontstyle'] if 'bounding_box' in options: opts['bbox'] = options['bounding_box'] if 'zorder' in options: opts['zorder'] = options['zorder'] if options['axis_coords']: opts['transform'] = subplot.transAxes if 'fontsize' in options: val = options['fontsize'] if isinstance(val, str): opts['fontsize'] = val else: opts['fontsize'] = int(val) if 'rotation' in options: val = options['rotation'] if isinstance(val, str): opts['rotation'] = options['rotation'] else: opts['rotation'] = float(options['rotation']) p = subplot.text(self.x, self.y, self.string, clip_on=options['clip'], **opts) if not options['clip']: self._bbox_extra_artists = [p] @rename_keyword(color='rgbcolor') @options(fontsize=10, rgbcolor=(0,0,1), horizontal_alignment='center', vertical_alignment='center', axis_coords=False, clip=False) def text(string, xy, **options): r""" Return a 2D text graphics object at the point `(x, y)`. Type ``text.options`` for a dictionary of options for 2D text. 2D OPTIONS: - ``fontsize`` - How big the text is. Either an integer that specifies the size in points or a string which specifies a size (one of 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large') - ``fontstyle`` - A string either 'normal', 'italic' or 'oblique' - ``fontweight`` - A numeric value in the range 0-1000 or a string (one of 'ultralight', 'light', 'normal', 'regular', 'book',' 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black') - ``rgbcolor`` - The color as an RGB tuple - ``hue`` - The color given as a hue - ``alpha`` - A float (0.0 transparent through 1.0 opaque) - ``background_color`` - The background color - ``rotation`` - How to rotate the text: angle in degrees, vertical, horizontal - ``vertical_alignment`` - How to align vertically: top, center, bottom - ``horizontal_alignment`` - How to align horizontally: left, center, right - ``zorder`` - The layer level in which to draw - ``clip`` - (default: False) Whether to clip or not - ``axis_coords`` - (default: False) If True, use axis coordinates, so that (0,0) is the lower left and (1,1) upper right, regardless of the x and y range of plotted values. - ``bounding_box`` - A dictionary specifying a bounding box. Currently the text location. EXAMPLES:: sage: text("Sage graphics are really neat because they use matplotlib!", (2,12)) Graphics object consisting of 1 graphics primitive .. PLOT:: t = "Sage graphics are really neat because they use matplotlib!" sphinx_plot(text(t,(2,12))) Larger font, bold, colored red and transparent text:: sage: text("I had a dream!", (2,12), alpha=0.3, fontsize='large', fontweight='bold', color='red') Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(text("I had a dream!", (2,12), alpha=0.3, fontsize='large', fontweight='bold', color='red')) By setting ``horizontal_alignment`` to 'left' the text is guaranteed to be in the lower left no matter what:: sage: text("I got a horse and he lives in a tree", (0,0), axis_coords=True, horizontal_alignment='left') Graphics object consisting of 1 graphics primitive .. PLOT:: t = "I got a horse and he lives in a tree" sphinx_plot(text(t, (0,0), axis_coords=True, horizontal_alignment='left')) Various rotations:: sage: text("noitator", (0,0), rotation=45.0, horizontal_alignment='left', vertical_alignment='bottom') Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(text("noitator", (0,0), rotation=45.0, horizontal_alignment='left', vertical_alignment='bottom')) :: sage: text("Sage is really neat!!",(0,0), rotation="vertical") Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(text("Sage is really neat!!",(0,0), rotation="vertical")) You can also align text differently:: sage: t1 = text("Hello",(1,1), vertical_alignment="top") sage: t2 = text("World", (1,0.5), horizontal_alignment="left") sage: t1 + t2 # render the sum Graphics object consisting of 2 graphics primitives .. PLOT:: t1 = text("Hello",(1,1), vertical_alignment="top") t2 = text("World", (1,0.5), horizontal_alignment="left") sphinx_plot(t1 + t2) You can save text as part of PDF output:: sage: import tempfile sage: with tempfile.NamedTemporaryFile(suffix=".pdf") as f: ....: text("sage", (0,0), rgbcolor=(0,0,0)).save(f.name) Some examples of bounding box:: sage: bbox = {'boxstyle':"rarrow,pad=0.3", 'fc':"cyan", 'ec':"b", 'lw':2} sage: text("I feel good", (1,2), bounding_box=bbox) Graphics object consisting of 1 graphics primitive .. PLOT:: bbox = {'boxstyle':"rarrow,pad=0.3", 'fc':"cyan", 'ec':"b", 'lw':2} sphinx_plot(text("I feel good", (1,2), bounding_box=bbox)) :: sage: text("So good", (0,0), bounding_box={'boxstyle':'round', 'fc':'w'}) Graphics object consisting of 1 graphics primitive .. PLOT:: bbox = {'boxstyle':'round', 'fc':'w'} sphinx_plot(text("So good", (0,0), bounding_box=bbox)) The possible options of the bounding box are 'boxstyle' (one of 'larrow', 'rarrow', 'round', 'round4', 'roundtooth', 'sawtooth', 'square'), 'fc' or 'facecolor', 'ec' or 'edgecolor', 'ha' or 'horizontalalignment', 'va' or 'verticalalignment', 'lw' or 'linewidth'. A text with a background color:: sage: text("So good", (-2,2), background_color='red') Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(text("So good", (-2,2), background_color='red')) Use dollar signs for LaTeX and raw strings to avoid having to escape backslash characters:: sage: A = arc((0, 0), 1, sector=(0.0, RDF.pi())) sage: a = sqrt(1./2.) sage: PQ = point2d([(-a, a), (a, a)]) sage: botleft = dict(horizontal_alignment='left', vertical_alignment='bottom') sage: botright = dict(horizontal_alignment='right', vertical_alignment='bottom') sage: tp = text(r'$z_P = e^{3i\pi/4}$', (-a, a), **botright) sage: tq = text(r'$Q = (\frac{\sqrt{2}}{2}, \frac{\sqrt{2}}{2})$', (a, a), **botleft) sage: A + PQ + tp + tq Graphics object consisting of 4 graphics primitives .. PLOT:: A = arc((0, 0), 1, sector=(0.0, RDF.pi())) a = sqrt(1./2.) PQ = point2d([(-a, a), (a, a)]) botleft = dict(horizontal_alignment='left', vertical_alignment='bottom') botright = dict(horizontal_alignment='right', vertical_alignment='bottom') tp = text(r'$z_P = e^{3i\pi/4}$', (-a, a), **botright) tq = text(r'$Q = (\frac{\sqrt{2}}{2}, \frac{\sqrt{2}}{2})$', (a, a), **botleft) sphinx_plot(A + PQ + tp + tq) Text coordinates must be 2D, an error is raised if 3D coordinates are passed:: sage: t = text("hi", (1, 2, 3)) Traceback (most recent call last): ... ValueError: use text3d instead for text in 3d Use the :func:`text3d <sage.plot.plot3d.shapes2.text3d>` function for 3D text:: sage: t = text3d("hi", (1, 2, 3)) Or produce 2D text with coordinates `(x, y)` and plot it in 3D (at `z = 0`):: sage: t = text("hi", (1, 2)) sage: t.plot3d() # text at position (1, 2, 0) Graphics3d Object Extra options will get passed on to ``show()``, as long as they are valid. Hence this :: sage: text("MATH IS AWESOME", (0, 0), fontsize=40, axes=False) Graphics object consisting of 1 graphics primitive is equivalent to :: sage: text("MATH IS AWESOME", (0, 0), fontsize=40).show(axes=False) """ try: x, y = xy except ValueError: if isinstance(xy, (list, tuple)) and len(xy) == 3: raise ValueError("use text3d instead for text in 3d") raise from sage.plot.all import Graphics options['rgbcolor'] = to_mpl_color(options['rgbcolor']) point = (float(x), float(y)) g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore='fontsize')) g.add_primitive(Text(string, point, options)) return g
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/text.py
0.825167
0.358943
text.py
pypi
from sage.plot.primitive import GraphicPrimitive from sage.misc.decorators import options class ScatterPlot(GraphicPrimitive): """ Scatter plot graphics primitive. Input consists of two lists/arrays of the same length, whose values give the horizontal and vertical coordinates of each point in the scatter plot. Options may be passed in dictionary format. EXAMPLES:: sage: from sage.plot.scatter_plot import ScatterPlot sage: ScatterPlot([0,1,2], [3.5,2,5.1], {'facecolor':'white', 'marker':'s'}) Scatter plot graphics primitive on 3 data points """ def __init__(self, xdata, ydata, options): """ Scatter plot graphics primitive. EXAMPLES:: sage: import numpy sage: from sage.plot.scatter_plot import ScatterPlot sage: ScatterPlot(numpy.array([0,1,2]), numpy.array([3.5,2,5.1]), {'facecolor':'white', 'marker':'s'}) Scatter plot graphics primitive on 3 data points """ self.xdata = xdata self.ydata = ydata GraphicPrimitive.__init__(self, options) def get_minmax_data(self): """ Returns a dictionary with the bounding box data. EXAMPLES:: sage: s = scatter_plot([[0,1],[2,4],[3.2,6]]) sage: d = s.get_minmax_data() sage: d['xmin'] 0.0 sage: d['ymin'] 1.0 """ return {'xmin': self.xdata.min(), 'xmax': self.xdata.max(), 'ymin': self.ydata.min(), 'ymax': self.ydata.max()} def _allowed_options(self): """ Return the dictionary of allowed options for the scatter plot graphics primitive. EXAMPLES:: sage: from sage.plot.scatter_plot import ScatterPlot sage: list(sorted(ScatterPlot([-1,2], [17,4], {})._allowed_options().items())) [('alpha', 'How transparent the marker border is.'), ('clip', 'Whether or not to clip.'), ('edgecolor', 'The color of the marker border.'), ('facecolor', 'The color of the marker face.'), ('hue', 'The color given as a hue.'), ('marker', 'What shape to plot the points. See the documentation of plot() for the full list of markers.'), ('markersize', 'the size of the markers.'), ('rgbcolor', 'The color as an RGB tuple.'), ('zorder', 'The layer level in which to draw.')] """ return {'markersize': 'the size of the markers.', 'marker': 'What shape to plot the points. See the documentation of plot() for the full list of markers.', 'alpha': 'How transparent the marker border is.', 'rgbcolor': 'The color as an RGB tuple.', 'hue': 'The color given as a hue.', 'facecolor': 'The color of the marker face.', 'edgecolor': 'The color of the marker border.', 'zorder': 'The layer level in which to draw.', 'clip': 'Whether or not to clip.'} def _repr_(self): """ Text representation of a scatter plot graphics primitive. EXAMPLES:: sage: import numpy sage: from sage.plot.scatter_plot import ScatterPlot sage: ScatterPlot(numpy.array([0,1,2]), numpy.array([3.5,2,5.1]), {}) Scatter plot graphics primitive on 3 data points """ return 'Scatter plot graphics primitive on %s data points' % len(self.xdata) def _render_on_subplot(self, subplot): """ Render this scatter plot in a subplot. This is the key function that defines how this scatter plot graphics primitive is rendered in matplotlib's library. EXAMPLES:: sage: scatter_plot([[0,1],[2,2],[4.3,1.1]], marker='s') Graphics object consisting of 1 graphics primitive :: sage: scatter_plot([[n,n] for n in range(5)]) Graphics object consisting of 1 graphics primitive """ options = self.options() p = subplot.scatter(self.xdata, self.ydata, alpha=options['alpha'], zorder=options['zorder'], marker=options['marker'], s=options['markersize'], facecolors=options['facecolor'], edgecolors=options['edgecolor'], clip_on=options['clip']) if not options['clip']: self._bbox_extra_artists = [p] @options(alpha=1, markersize=50, marker='o', zorder=5, facecolor='#fec7b8', edgecolor='black', clip=True, aspect_ratio='automatic') def scatter_plot(datalist, **options): """ Returns a Graphics object of a scatter plot containing all points in the datalist. Type ``scatter_plot.options`` to see all available plotting options. INPUT: - ``datalist`` -- a list of tuples ``(x,y)`` - ``alpha`` -- default: 1 - ``markersize`` -- default: 50 - ``marker`` - The style of the markers (default ``"o"``). See the documentation of :func:`plot` for the full list of markers. - ``facecolor`` -- default: ``'#fec7b8'`` - ``edgecolor`` -- default: ``'black'`` - ``zorder`` -- default: 5 EXAMPLES:: sage: scatter_plot([[0,1],[2,2],[4.3,1.1]], marker='s') Graphics object consisting of 1 graphics primitive .. PLOT:: from sage.plot.scatter_plot import ScatterPlot S = scatter_plot([[0,1],[2,2],[4.3,1.1]], marker='s') sphinx_plot(S) Extra options will get passed on to :meth:`~Graphics.show`, as long as they are valid:: sage: scatter_plot([(0, 0), (1, 1)], markersize=100, facecolor='green', ymax=100) Graphics object consisting of 1 graphics primitive sage: scatter_plot([(0, 0), (1, 1)], markersize=100, facecolor='green').show(ymax=100) # These are equivalent .. PLOT:: from sage.plot.scatter_plot import ScatterPlot S = scatter_plot([(0, 0), (1, 1)], markersize=100, facecolor='green', ymax=100) sphinx_plot(S) """ import numpy from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) data = numpy.array(datalist, dtype='float') if len(data) != 0: xdata = data[:, 0] ydata = data[:, 1] g.add_primitive(ScatterPlot(xdata, ydata, options=options)) return g
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/scatter_plot.py
0.944305
0.748697
scatter_plot.py
pypi
from sage.misc.fast_methods import WithEqualityById from sage.structure.sage_object import SageObject from sage.misc.verbose import verbose class GraphicPrimitive(WithEqualityById, SageObject): """ Base class for graphics primitives, e.g., things that knows how to draw themselves in 2D. EXAMPLES: We create an object that derives from GraphicPrimitive:: sage: P = line([(-1,-2), (3,5)]) sage: P[0] Line defined by 2 points sage: type(P[0]) <class 'sage.plot.line.Line'> TESTS:: sage: hash(circle((0,0),1)) # random 42 """ def __init__(self, options): """ Create a base class GraphicsPrimitive. All this does is set the options. EXAMPLES: We indirectly test this function:: sage: from sage.plot.primitive import GraphicPrimitive sage: GraphicPrimitive({}) Graphics primitive """ self._options = options def _allowed_options(self): """ Return the allowed options for a graphics primitive. OUTPUT: - a reference to a dictionary. EXAMPLES:: sage: from sage.plot.primitive import GraphicPrimitive sage: GraphicPrimitive({})._allowed_options() {} """ return {} def plot3d(self, **kwds): """ Plots 3D version of 2D graphics object. Not implemented for base class. EXAMPLES:: sage: from sage.plot.primitive import GraphicPrimitive sage: G=GraphicPrimitive({}) sage: G.plot3d() Traceback (most recent call last): ... NotImplementedError: 3D plotting not implemented for Graphics primitive """ raise NotImplementedError("3D plotting not implemented for %s" % self._repr_()) def _plot3d_options(self, options=None): """ Translate 2D plot options into 3D plot options. EXAMPLES:: sage: P = line([(-1,-2), (3,5)], alpha=.5, thickness=4) sage: p = P[0]; p Line defined by 2 points sage: q=p.plot3d() sage: q.thickness 4 sage: q.texture.opacity 0.5 """ if options is None: options = self.options() options_3d = {} if 'rgbcolor' in options: options_3d['rgbcolor'] = options['rgbcolor'] del options['rgbcolor'] if 'alpha' in options: options_3d['opacity'] = options['alpha'] del options['alpha'] for o in ('legend_color', 'legend_label', 'zorder'): if o in options: del options[o] if len(options) != 0: raise NotImplementedError("Unknown plot3d equivalent for {}".format( ", ".join(options.keys()))) return options_3d def set_zorder(self, zorder): """ Set the layer in which to draw the object. EXAMPLES:: sage: P = line([(-2,-3), (3,4)], thickness=4) sage: p=P[0] sage: p.set_zorder(2) sage: p.options()['zorder'] 2 sage: Q = line([(-2,-4), (3,5)], thickness=4,zorder=1,hue=.5) sage: P+Q # blue line on top Graphics object consisting of 2 graphics primitives sage: q=Q[0] sage: q.set_zorder(3) sage: P+Q # teal line on top Graphics object consisting of 2 graphics primitives sage: q.options()['zorder'] 3 """ self._options['zorder'] = zorder def set_options(self, new_options): """ Change the options to `new_options`. EXAMPLES:: sage: from sage.plot.circle import Circle sage: c = Circle(0,0,1,{}) sage: c.set_options({'thickness': 0.6}) sage: c.options() {'thickness': 0.6...} """ if new_options is not None: self._options = new_options def options(self): """ Return the dictionary of options for this graphics primitive. By default this function verifies that the options are all valid; if any aren't, then a verbose message is printed with level 0. EXAMPLES:: sage: from sage.plot.primitive import GraphicPrimitive sage: GraphicPrimitive({}).options() {} """ from sage.plot.graphics import do_verify from sage.plot.colors import hue O = dict(self._options) if do_verify: A = self._allowed_options() t = False K = list(A) + ['xmin', 'xmax', 'ymin', 'ymax', 'axes'] for k in O.keys(): if k not in K: do_verify = False verbose("WARNING: Ignoring option '%s'=%s" % (k, O[k]), level=0) t = True if t: s = "\nThe allowed options for %s are:\n" % self K.sort() for k in K: if k in A: s += " %-15s%-60s\n" % (k, A[k]) verbose(s, level=0) if 'hue' in O: t = O['hue'] if not isinstance(t, (tuple,list)): t = [t,1,1] O['rgbcolor'] = hue(*t) del O['hue'] return O def _repr_(self): """ String representation of this graphics primitive. EXAMPLES:: sage: from sage.plot.primitive import GraphicPrimitive sage: GraphicPrimitive({})._repr_() 'Graphics primitive' """ return "Graphics primitive" class GraphicPrimitive_xydata(GraphicPrimitive): def get_minmax_data(self): """ Returns a dictionary with the bounding box data. EXAMPLES:: sage: d = polygon([[1,2], [5,6], [5,0]], rgbcolor=(1,0,1))[0].get_minmax_data() sage: d['ymin'] 0.0 sage: d['xmin'] 1.0 :: sage: d = point((3, 3), rgbcolor=hue(0.75))[0].get_minmax_data() sage: d['xmin'] 3.0 sage: d['ymin'] 3.0 :: sage: l = line([(100, 100), (120, 120)])[0] sage: d = l.get_minmax_data() sage: d['xmin'] 100.0 sage: d['xmax'] 120.0 """ from sage.plot.plot import minmax_data return minmax_data(self.xdata, self.ydata, dict=True)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/primitive.py
0.790813
0.378115
primitive.py
pypi
from sage.plot.primitive import GraphicPrimitive_xydata from sage.misc.decorators import options, rename_keyword from sage.plot.colors import to_mpl_color class Line(GraphicPrimitive_xydata): """ Primitive class that initializes the line graphics type. EXAMPLES:: sage: from sage.plot.line import Line sage: Line([1,2,7], [1,5,-1], {}) Line defined by 3 points """ def __init__(self, xdata, ydata, options): """ Initialize a line graphics primitive. EXAMPLES:: sage: from sage.plot.line import Line sage: Line([-1,2], [17,4], {'thickness':2}) Line defined by 2 points """ valid_options = self._allowed_options() for opt in options: if opt not in valid_options: raise RuntimeError("error in line(): option '%s' not valid" % opt) self.xdata = xdata self.ydata = ydata GraphicPrimitive_xydata.__init__(self, options) def _allowed_options(self): """ Displayed the list of allowed line options. EXAMPLES:: sage: from sage.plot.line import Line sage: list(sorted(Line([-1,2], [17,4], {})._allowed_options().items())) [('alpha', 'How transparent the line is.'), ('hue', 'The color given as a hue.'), ('legend_color', 'The color of the legend text.'), ('legend_label', 'The label for this item in the legend.'), ('linestyle', "The style of the line, which is one of '--' (dashed), '-.' (dash dot), '-' (solid), 'steps', ':' (dotted)."), ('marker', 'the marker symbol (see documentation for line2d for details)'), ('markeredgecolor', 'the color of the marker edge'), ('markeredgewidth', 'the size of the marker edge in points'), ('markerfacecolor', 'the color of the marker face'), ('markersize', 'the size of the marker in points'), ('rgbcolor', 'The color as an RGB tuple.'), ('thickness', 'How thick the line is.'), ('zorder', 'The layer level in which to draw')] """ return {'alpha': 'How transparent the line is.', 'legend_color': 'The color of the legend text.', 'legend_label': 'The label for this item in the legend.', 'thickness': 'How thick the line is.', 'rgbcolor': 'The color as an RGB tuple.', 'hue': 'The color given as a hue.', 'linestyle': "The style of the line, which is one of '--' (dashed), '-.' (dash dot), '-' (solid), 'steps', ':' (dotted).", 'marker': "the marker symbol (see documentation for line2d for details)", 'markersize': 'the size of the marker in points', 'markeredgecolor': 'the color of the marker edge', 'markeredgewidth': 'the size of the marker edge in points', 'markerfacecolor': 'the color of the marker face', 'zorder': 'The layer level in which to draw' } def _plot3d_options(self, options=None): """ Translate 2D plot options into 3D plot options. EXAMPLES:: sage: L = line([(1,1), (1,2), (2,2), (2,1)], alpha=.5, thickness=10, zorder=2) sage: l=L[0]; l Line defined by 4 points sage: m=l.plot3d(z=2) sage: m.texture.opacity 0.5 sage: m.thickness 10 sage: L = line([(1,1), (1,2), (2,2), (2,1)], linestyle=":") sage: L.plot3d() Traceback (most recent call last): ... NotImplementedError: invalid 3d line style: ':' """ if options is None: options = dict(self.options()) options_3d = {} if 'thickness' in options: options_3d['thickness'] = options['thickness'] del options['thickness'] if 'zorder' in options: del options['zorder'] if 'linestyle' in options: if options['linestyle'] not in ('-', 'solid'): raise NotImplementedError("invalid 3d line style: '%s'" % (options['linestyle'])) del options['linestyle'] options_3d.update(GraphicPrimitive_xydata._plot3d_options(self, options)) return options_3d def plot3d(self, z=0, **kwds): """ Plots a 2D line in 3D, with default height zero. EXAMPLES:: sage: E = EllipticCurve('37a').plot(thickness=5).plot3d() sage: F = EllipticCurve('37a').plot(thickness=5).plot3d(z=2) sage: E + F # long time (5s on sage.math, 2012) Graphics3d Object .. PLOT:: E = EllipticCurve('37a').plot(thickness=5).plot3d() F = EllipticCurve('37a').plot(thickness=5).plot3d(z=2) sphinx_plot(E+F) """ from sage.plot.plot3d.shapes2 import line3d options = self._plot3d_options() options.update(kwds) return line3d([(x, y, z) for x, y in zip(self.xdata, self.ydata)], **options) def _repr_(self): """ String representation of a line primitive. EXAMPLES:: sage: from sage.plot.line import Line sage: Line([-1,2,3,3], [17,4,0,2], {})._repr_() 'Line defined by 4 points' """ return "Line defined by %s points" % len(self) def __getitem__(self, i): """ Extract the i-th element of the line (which is stored as a list of points). INPUT: - ``i`` -- an integer between 0 and the number of points minus 1 OUTPUT: A 2-tuple of floats. EXAMPLES:: sage: L = line([(1,2), (3,-4), (2, 5), (1,2)]) sage: line_primitive = L[0]; line_primitive Line defined by 4 points sage: line_primitive[0] (1.0, 2.0) sage: line_primitive[2] (2.0, 5.0) sage: list(line_primitive) [(1.0, 2.0), (3.0, -4.0), (2.0, 5.0), (1.0, 2.0)] """ return self.xdata[i], self.ydata[i] def __setitem__(self, i, point): """ Set the i-th element of this line (really a sequence of lines through given points). INPUT: - ``i`` -- an integer between 0 and the number of points on the line minus 1 - ``point`` -- a 2-tuple of floats EXAMPLES: We create a line graphics object ``L`` and get ahold of the corresponding line graphics primitive:: sage: L = line([(1,2), (3,-4), (2, 5), (1,2)]) sage: line_primitive = L[0]; line_primitive Line defined by 4 points We then set the 0th point to `(0,0)` instead of `(1,2)`:: sage: line_primitive[0] = (0,0) sage: line_primitive[0] (0.0, 0.0) Plotting we visibly see the change -- now the line starts at `(0,0)`:: sage: L Graphics object consisting of 1 graphics primitive """ self.xdata[i] = float(point[0]) self.ydata[i] = float(point[1]) def __len__(self): r""" Return the number of points on this line (where a line is really a sequence of line segments through a given list of points). EXAMPLES: We create a line, then grab the line primitive as ``L[0]`` and compute its length:: sage: L = line([(1,2), (3,-4), (2, 5), (1,2)]) sage: len(L[0]) 4 """ return len(self.xdata) def _render_on_subplot(self, subplot): """ Render this line on a matplotlib subplot. INPUT: - ``subplot`` -- a matplotlib subplot EXAMPLES: This implicitly calls this function:: sage: line([(1,2), (3,-4), (2, 5), (1,2)]) Graphics object consisting of 1 graphics primitive """ import matplotlib.lines as lines options = dict(self.options()) for o in ('alpha', 'legend_color', 'legend_label', 'linestyle', 'rgbcolor', 'thickness'): if o in options: del options[o] p = lines.Line2D(self.xdata, self.ydata, **options) options = self.options() a = float(options['alpha']) p.set_alpha(a) p.set_linewidth(float(options['thickness'])) p.set_color(to_mpl_color(options['rgbcolor'])) p.set_label(options['legend_label']) # we don't pass linestyle in directly since the drawstyles aren't # pulled off automatically. This (I think) is a bug in matplotlib 1.0.1 if 'linestyle' in options: from sage.plot.misc import get_matplotlib_linestyle p.set_linestyle(get_matplotlib_linestyle(options['linestyle'], return_type='short')) subplot.add_line(p) def line(points, **kwds): """ Returns either a 2-dimensional or 3-dimensional line depending on value of points. INPUT: - ``points`` - either a single point (as a tuple), a list of points, a single complex number, or a list of complex numbers. For information regarding additional arguments, see either line2d? or line3d?. EXAMPLES:: sage: line([(0,0), (1,1)]) Graphics object consisting of 1 graphics primitive .. PLOT:: E = line([(0,0), (1,1)]) sphinx_plot(E) :: sage: line([(0,0,1), (1,1,1)]) Graphics3d Object .. PLOT:: E = line([(0,0,1), (1,1,1)]) sphinx_plot(E) """ try: return line2d(points, **kwds) except ValueError: from sage.plot.plot3d.shapes2 import line3d return line3d(points, **kwds) @rename_keyword(color='rgbcolor') @options(alpha=1, rgbcolor=(0, 0, 1), thickness=1, legend_label=None, legend_color=None, aspect_ratio='automatic') def line2d(points, **options): r""" Create the line through the given list of points. INPUT: - ``points`` - either a single point (as a tuple), a list of points, a single complex number, or a list of complex numbers. Type ``line2d.options`` for a dictionary of the default options for lines. You can change this to change the defaults for all future lines. Use ``line2d.reset()`` to reset to the default options. INPUT: - ``alpha`` -- How transparent the line is - ``thickness`` -- How thick the line is - ``rgbcolor`` -- The color as an RGB tuple - ``hue`` -- The color given as a hue - ``legend_color`` -- The color of the text in the legend - ``legend_label`` -- the label for this item in the legend Any MATPLOTLIB line option may also be passed in. E.g., - ``linestyle`` - (default: "-") The style of the line, which is one of - ``"-"`` or ``"solid"`` - ``"--"`` or ``"dashed"`` - ``"-."`` or ``"dash dot"`` - ``":"`` or ``"dotted"`` - ``"None"`` or ``" "`` or ``""`` (nothing) The linestyle can also be prefixed with a drawing style (e.g., ``"steps--"``) - ``"default"`` (connect the points with straight lines) - ``"steps"`` or ``"steps-pre"`` (step function; horizontal line is to the left of point) - ``"steps-mid"`` (step function; points are in the middle of horizontal lines) - ``"steps-post"`` (step function; horizontal line is to the right of point) - ``marker`` - The style of the markers, which is one of - ``"None"`` or ``" "`` or ``""`` (nothing) -- default - ``","`` (pixel), ``"."`` (point) - ``"_"`` (horizontal line), ``"|"`` (vertical line) - ``"o"`` (circle), ``"p"`` (pentagon), ``"s"`` (square), ``"x"`` (x), ``"+"`` (plus), ``"*"`` (star) - ``"D"`` (diamond), ``"d"`` (thin diamond) - ``"H"`` (hexagon), ``"h"`` (alternative hexagon) - ``"<"`` (triangle left), ``">"`` (triangle right), ``"^"`` (triangle up), ``"v"`` (triangle down) - ``"1"`` (tri down), ``"2"`` (tri up), ``"3"`` (tri left), ``"4"`` (tri right) - ``0`` (tick left), ``1`` (tick right), ``2`` (tick up), ``3`` (tick down) - ``4`` (caret left), ``5`` (caret right), ``6`` (caret up), ``7`` (caret down) - ``"$...$"`` (math TeX string) - ``markersize`` -- the size of the marker in points - ``markeredgecolor`` -- the color of the marker edge - ``markerfacecolor`` -- the color of the marker face - ``markeredgewidth`` -- the size of the marker edge in points EXAMPLES: A line with no points or one point:: sage: line([]) #returns an empty plot Graphics object consisting of 0 graphics primitives sage: import numpy; line(numpy.array([])) Graphics object consisting of 0 graphics primitives sage: line([(1,1)]) Graphics object consisting of 1 graphics primitive A line with numpy arrays:: sage: line(numpy.array([[1,2], [3,4]])) Graphics object consisting of 1 graphics primitive A line with a legend:: sage: line([(0,0),(1,1)], legend_label='line') Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(line([(0,0),(1,1)], legend_label='line')) Lines with different colors in the legend text:: sage: p1 = line([(0,0),(1,1)], legend_label='line') sage: p2 = line([(1,1),(2,4)], legend_label='squared', legend_color='red') sage: p1 + p2 Graphics object consisting of 2 graphics primitives .. PLOT:: p1 = line([(0,0),(1,1)], legend_label='line') p2 = line([(1,1),(2,4)], legend_label='squared', legend_color='red') sphinx_plot(p1 + p2) Extra options will get passed on to show(), as long as they are valid:: sage: line([(0,1), (3,4)], figsize=[10, 2]) Graphics object consisting of 1 graphics primitive sage: line([(0,1), (3,4)]).show(figsize=[10, 2]) # These are equivalent We can also use a logarithmic scale if the data will support it:: sage: line([(1,2),(2,4),(3,4),(4,8),(4.5,32)],scale='loglog',base=2) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(line([(1,2),(2,4),(3,4),(4,8),(4.5,32)],scale='loglog',base=2)) Many more examples below! A blue conchoid of Nicomedes:: sage: L = [[1+5*cos(pi/2+pi*i/100), tan(pi/2+pi*i/100)*(1+5*cos(pi/2+pi*i/100))] for i in range(1,100)] sage: line(L, rgbcolor=(1/4,1/8,3/4)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[1+5*cos(pi/2+pi*i/100), tan(pi/2+pi*i/100)*(1+5*cos(pi/2+pi*i/100))] for i in range(1,100)] sphinx_plot(line(L, rgbcolor=(1/4,1/8,3/4))) A line with 2 complex points:: sage: i = CC(0,1) sage: line([1+i, 2+3*i]) Graphics object consisting of 1 graphics primitive .. PLOT:: i = CC(0,1) o = line([1+i, 2+3*i]) sphinx_plot(o) A blue hypotrochoid (3 leaves):: sage: n = 4; h = 3; b = 2 sage: L = [[n*cos(pi*i/100)+h*cos((n/b)*pi*i/100),n*sin(pi*i/100)-h*sin((n/b)*pi*i/100)] for i in range(200)] sage: line(L, rgbcolor=(1/4,1/4,3/4)) Graphics object consisting of 1 graphics primitive .. PLOT:: n = 4 h = 3 b = 2 L = [[n*cos(pi*i/100)+h*cos((n/b)*pi*i/100),n*sin(pi*i/100)-h*sin((n/b)*pi*i/100)] for i in range(200)] o = line(L, rgbcolor=(1/4,1/4,3/4)) sphinx_plot(o) A blue hypotrochoid (4 leaves):: sage: n = 6; h = 5; b = 2 sage: L = [[n*cos(pi*i/100)+h*cos((n/b)*pi*i/100),n*sin(pi*i/100)-h*sin((n/b)*pi*i/100)] for i in range(200)] sage: line(L, rgbcolor=(1/4,1/4,3/4)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[sin(pi*i/100)+sin(pi*i/50),-(1+cos(pi*i/100)+cos(pi*i/50))] for i in range(-100,101)] sphinx_plot(line(L, rgbcolor=(1,1/4,1/2))) A red limacon of Pascal:: sage: L = [[sin(pi*i/100)+sin(pi*i/50),-(1+cos(pi*i/100)+cos(pi*i/50))] for i in range(-100,101)] sage: line(L, rgbcolor=(1,1/4,1/2)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[sin(pi*i/100)+sin(pi*i/50),-(1+cos(pi*i/100)+cos(pi*i/50))] for i in range(-100,101)] sphinx_plot(line(L, rgbcolor=(1,1/4,1/2))) A light green trisectrix of Maclaurin:: sage: L = [[2*(1-4*cos(-pi/2+pi*i/100)^2),10*tan(-pi/2+pi*i/100)*(1-4*cos(-pi/2+pi*i/100)^2)] for i in range(1,100)] sage: line(L, rgbcolor=(1/4,1,1/8)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[2*(1-4*cos(-pi/2+pi*i/100)**2),10*tan(-pi/2+pi*i/100)*(1-4*cos(-pi/2+pi*i/100)**2)] for i in range(1,100)] sphinx_plot(line(L, rgbcolor=(1/4,1,1/8))) A green lemniscate of Bernoulli:: sage: cosines = [cos(-pi/2+pi*i/100) for i in range(201)] sage: v = [(1/c, tan(-pi/2+pi*i/100)) for i,c in enumerate(cosines) if c != 0] sage: L = [(a/(a^2+b^2), b/(a^2+b^2)) for a,b in v] sage: line(L, rgbcolor=(1/4,3/4,1/8)) Graphics object consisting of 1 graphics primitive .. PLOT:: cosines = [cos(-pi/2+pi*i/100) for i in range(201)] v = [(1/c, tan(-pi/2+pi*i/100)) for i,c in enumerate(cosines) if c != 0] L = [(a/(a**2+b**2), b/(a**2+b**2)) for a,b in v] sphinx_plot(line(L, rgbcolor=(1/4,3/4,1/8))) A red plot of the Jacobi elliptic function `\text{sn}(x,2)`, `-3 < x < 3`:: sage: L = [(i/100.0, real_part(jacobi('sn', i/100.0, 2.0))) for i in ....: range(-300, 300, 30)] sage: line(L, rgbcolor=(3/4, 1/4, 1/8)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [(i/100.0, real_part(jacobi('sn', i/100.0, 2.0))) for i in range(-300, 300, 30)] sphinx_plot(line(L, rgbcolor=(3/4, 1/4, 1/8))) A red plot of `J`-Bessel function `J_2(x)`, `0 < x < 10`:: sage: L = [(i/10.0, bessel_J(2,i/10.0)) for i in range(100)] sage: line(L, rgbcolor=(3/4,1/4,5/8)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [(i/10.0, bessel_J(2,i/10.0)) for i in range(100)] sphinx_plot(line(L, rgbcolor=(3/4,1/4,5/8))) A purple plot of the Riemann zeta function `\zeta(1/2 + it)`, `0 < t < 30`:: sage: i = CDF.gen() sage: v = [zeta(0.5 + n/10 * i) for n in range(300)] sage: L = [(z.real(), z.imag()) for z in v] sage: line(L, rgbcolor=(3/4,1/2,5/8)) Graphics object consisting of 1 graphics primitive .. PLOT:: i = CDF.gen() v = [zeta(0.5 + n/10 * i) for n in range(300)] L = [(z.real(), z.imag()) for z in v] sphinx_plot(line(L, rgbcolor=(3/4,1/2,5/8))) A purple plot of the Hasse-Weil `L`-function `L(E, 1 + it)`, `-1 < t < 10`:: sage: E = EllipticCurve('37a') sage: vals = E.lseries().values_along_line(1-I, 1+10*I, 100) # critical line sage: L = [(z[1].real(), z[1].imag()) for z in vals] sage: line(L, rgbcolor=(3/4,1/2,5/8)) Graphics object consisting of 1 graphics primitive .. PLOT :: E = EllipticCurve('37a') vals = E.lseries().values_along_line(1-I, 1+10*I, 100) # critical line L = [(z[1].real(), z[1].imag()) for z in vals] sphinx_plot(line(L, rgbcolor=(3/4,1/2,5/8))) A red, blue, and green "cool cat":: sage: G = plot(-cos(x), -2, 2, thickness=5, rgbcolor=(0.5,1,0.5)) sage: P = polygon([[1,2], [5,6], [5,0]], rgbcolor=(1,0,0)) sage: Q = polygon([(-x,y) for x,y in P[0]], rgbcolor=(0,0,1)) sage: G + P + Q # show the plot Graphics object consisting of 3 graphics primitives .. PLOT:: G = plot(-cos(x), -2, 2, thickness=5, rgbcolor=(0.5,1,0.5)) P = polygon([[1,2], [5,6], [5,0]], rgbcolor=(1,0,0)) Q = polygon([(-x,y) for x,y in P[0]], rgbcolor=(0,0,1)) sphinx_plot(G + P + Q) TESTS: Check that :trac:`13690` is fixed. The legend label should have circles as markers.:: sage: line(enumerate(range(2)), marker='o', legend_label='circle') Graphics object consisting of 1 graphics primitive """ from sage.plot.all import Graphics from sage.plot.plot import xydata_from_point_list points = list(points) # make sure points is a python list if not points: return Graphics() xdata, ydata = xydata_from_point_list(points) g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) g.add_primitive(Line(xdata, ydata, options)) if options['legend_label']: g.legend(True) g._legend_colors = [options['legend_color']] return g
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/line.py
0.885693
0.560674
line.py
pypi
from sage.plot.primitive import GraphicPrimitive_xydata from sage.misc.decorators import options, rename_keyword from sage.plot.colors import to_mpl_color class Polygon(GraphicPrimitive_xydata): """ Primitive class for the Polygon graphics type. For information on actual plotting, please see :func:`polygon`, :func:`polygon2d`, or :func:`~sage.plot.plot3d.shapes2.polygon3d`. INPUT: - xdata -- list of `x`-coordinates of points defining Polygon - ydata -- list of `y`-coordinates of points defining Polygon - options -- dict of valid plot options to pass to constructor EXAMPLES: Note this should normally be used indirectly via :func:`polygon`:: sage: from sage.plot.polygon import Polygon sage: P = Polygon([1,2,3],[2,3,2],{'alpha':.5}) sage: P Polygon defined by 3 points sage: P.options()['alpha'] 0.500000000000000 sage: P.ydata [2, 3, 2] TESTS: We test creating polygons:: sage: polygon([(0,0), (1,1), (0,1)]) Graphics object consisting of 1 graphics primitive :: sage: polygon([(0,0,1), (1,1,1), (2,0,1)]) Graphics3d Object :: sage: polygon2d([(1, 1), (0, 1), (1, 0)], fill=False, linestyle="dashed") Graphics object consisting of 1 graphics primitive """ def __init__(self, xdata, ydata, options): """ Initializes base class Polygon. EXAMPLES:: sage: P = polygon([(0,0), (1,1), (-1,3)], thickness=2) sage: P[0].xdata [0.0, 1.0, -1.0] sage: P[0].options()['thickness'] 2 """ self.xdata = xdata self.ydata = ydata GraphicPrimitive_xydata.__init__(self, options) def _repr_(self): """ String representation of Polygon primitive. EXAMPLES:: sage: P = polygon([(0,0), (1,1), (-1,3)]) sage: p=P[0]; p Polygon defined by 3 points """ return "Polygon defined by %s points" % len(self) def __getitem__(self, i): """ Return `i`-th vertex of Polygon primitive It is starting count from 0th vertex. EXAMPLES:: sage: P = polygon([(0,0), (1,1), (-1,3)]) sage: p=P[0] sage: p[0] (0.0, 0.0) """ return self.xdata[i], self.ydata[i] def __setitem__(self, i, point): """ Change `i`-th vertex of Polygon primitive It is starting count from 0th vertex. Note that this only changes a vertex, but does not create new vertices. EXAMPLES:: sage: P = polygon([(0,0), (1,2), (0,1), (-1,2)]) sage: p=P[0] sage: [p[i] for i in range(4)] [(0.0, 0.0), (1.0, 2.0), (0.0, 1.0), (-1.0, 2.0)] sage: p[2]=(0,.5) sage: p[2] (0.0, 0.5) """ i = int(i) self.xdata[i] = float(point[0]) self.ydata[i] = float(point[1]) def __len__(self): """ Return number of vertices of Polygon primitive. EXAMPLES:: sage: P = polygon([(0,0), (1,2), (0,1), (-1,2)]) sage: p=P[0] sage: len(p) 4 """ return len(self.xdata) def _allowed_options(self): """ Return the allowed options for the Polygon class. EXAMPLES:: sage: P = polygon([(1,1), (1,2), (2,2), (2,1)], alpha=.5) sage: P[0]._allowed_options()['alpha'] 'How transparent the figure is.' """ return {'alpha': 'How transparent the figure is.', 'thickness': 'How thick the border line is.', 'edgecolor': 'The color for the border of filled polygons.', 'fill': 'Whether or not to fill the polygon.', 'legend_label': 'The label for this item in the legend.', 'legend_color': 'The color of the legend text.', 'linestyle': 'The style of the enclosing line.', 'rgbcolor': 'The color as an RGB tuple.', 'hue': 'The color given as a hue.', 'zorder': 'The layer level in which to draw'} def _plot3d_options(self, options=None): """ Translate 2d plot options into 3d plot options. EXAMPLES:: sage: P = polygon([(1,1), (1,2), (2,2), (2,1)], alpha=.5) sage: p=P[0]; p Polygon defined by 4 points sage: q=p.plot3d() sage: q.texture.opacity 0.5 """ if options is None: options = dict(self.options()) for o in ['thickness', 'zorder', 'legend_label', 'fill', 'edgecolor']: options.pop(o, None) return GraphicPrimitive_xydata._plot3d_options(self, options) def plot3d(self, z=0, **kwds): """ Plots a 2D polygon in 3D, with default height zero. INPUT: - ``z`` - optional 3D height above `xy`-plane, or a list of heights corresponding to the list of 2D polygon points. EXAMPLES: A pentagon:: sage: polygon([(cos(t), sin(t)) for t in srange(0, 2*pi, 2*pi/5)]).plot3d() Graphics3d Object .. PLOT:: L = polygon([(cos(t), sin(t)) for t in srange(0, 2*pi, 2*pi/5)]).plot3d() sphinx_plot(L) Showing behavior of the optional parameter z:: sage: P = polygon([(0,0), (1,2), (0,1), (-1,2)]) sage: p = P[0]; p Polygon defined by 4 points sage: q = p.plot3d() sage: q.obj_repr(q.testing_render_params())[2] ['v 0 0 0', 'v 1 2 0', 'v 0 1 0', 'v -1 2 0'] sage: r = p.plot3d(z=3) sage: r.obj_repr(r.testing_render_params())[2] ['v 0 0 3', 'v 1 2 3', 'v 0 1 3', 'v -1 2 3'] sage: s = p.plot3d(z=[0,1,2,3]) sage: s.obj_repr(s.testing_render_params())[2] ['v 0 0 0', 'v 1 2 1', 'v 0 1 2', 'v -1 2 3'] TESTS: Heights passed as a list should have same length as number of points:: sage: P = polygon([(0,0), (1,2), (0,1), (-1,2)]) sage: p = P[0] sage: q = p.plot3d(z=[2,-2]) Traceback (most recent call last): ... ValueError: Incorrect number of heights given """ from sage.plot.plot3d.index_face_set import IndexFaceSet options = self._plot3d_options() options.update(kwds) zdata = [] if isinstance(z, list): zdata = z else: zdata = [z] * len(self.xdata) if len(zdata) == len(self.xdata): return IndexFaceSet([list(zip(self.xdata, self.ydata, zdata))], **options) else: raise ValueError('Incorrect number of heights given') def _render_on_subplot(self, subplot): """ TESTS:: sage: P = polygon([(0,0), (1,2), (0,1), (-1,2)]) """ import matplotlib.patches as patches options = self.options() p = patches.Polygon([(self.xdata[i], self.ydata[i]) for i in range(len(self.xdata))]) p.set_linewidth(float(options['thickness'])) if 'linestyle' in options: p.set_linestyle(options['linestyle']) a = float(options['alpha']) z = int(options.pop('zorder', 1)) p.set_alpha(a) f = options.pop('fill') p.set_fill(f) c = to_mpl_color(options['rgbcolor']) if f: ec = options['edgecolor'] if ec is None: p.set_color(c) else: p.set_facecolor(c) p.set_edgecolor(to_mpl_color(ec)) else: p.set_color(c) p.set_label(options['legend_label']) p.set_zorder(z) subplot.add_patch(p) def polygon(points, **options): """ Return either a 2-dimensional or 3-dimensional polygon depending on value of points. For information regarding additional arguments, see either :func:`polygon2d` or :func:`~sage.plot.plot3d.shapes2.polygon3d`. Options may be found and set using the dictionaries ``polygon2d.options`` and ``polygon3d.options``. EXAMPLES:: sage: polygon([(0,0), (1,1), (0,1)]) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(polygon([(0,0), (1,1), (0,1)])) :: sage: polygon([(0,0,1), (1,1,1), (2,0,1)]) Graphics3d Object Extra options will get passed on to show(), as long as they are valid:: sage: polygon([(0,0), (1,1), (0,1)], axes=False) Graphics object consisting of 1 graphics primitive sage: polygon([(0,0), (1,1), (0,1)]).show(axes=False) # These are equivalent """ try: return polygon2d(points, **options) except ValueError: from sage.plot.plot3d.shapes2 import polygon3d return polygon3d(points, **options) @rename_keyword(color='rgbcolor') @options(alpha=1, rgbcolor=(0, 0, 1), edgecolor=None, thickness=None, legend_label=None, legend_color=None, aspect_ratio=1.0, fill=True) def polygon2d(points, **options): r""" Return a 2-dimensional polygon defined by ``points``. Type ``polygon2d.options`` for a dictionary of the default options for polygons. You can change this to change the defaults for all future polygons. Use ``polygon2d.reset()`` to reset to the default options. EXAMPLES: We create a purple-ish polygon:: sage: polygon2d([[1,2], [5,6], [5,0]], rgbcolor=(1,0,1)) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(polygon2d([[1,2], [5,6], [5,0]], rgbcolor=(1,0,1))) By default, polygons are filled in, but we can make them without a fill as well:: sage: polygon2d([[1,2], [5,6], [5,0]], fill=False) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(polygon2d([[1,2], [5,6], [5,0]], fill=False)) In either case, the thickness of the border can be controlled:: sage: polygon2d([[1,2], [5,6], [5,0]], fill=False, thickness=4, color='orange') Graphics object consisting of 1 graphics primitive .. PLOT:: P = polygon2d([[1,2], [5,6], [5,0]], fill=False, thickness=4, color='orange') sphinx_plot(P) For filled polygons, one can use different colors for the border and the interior as follows:: sage: L = [[0,0]]+[[i/100, 1.1+cos(i/20)] for i in range(100)]+[[1,0]] sage: polygon2d(L, color="limegreen", edgecolor="black", axes=False) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[0,0]]+[[i*0.01, 1.1+cos(i*0.05)] for i in range(100)]+[[1,0]] P = polygon2d(L, color="limegreen", edgecolor="black", axes=False) sphinx_plot(P) Some modern art -- a random polygon, with legend:: sage: v = [(randrange(-5,5), randrange(-5,5)) for _ in range(10)] sage: polygon2d(v, legend_label='some form') Graphics object consisting of 1 graphics primitive .. PLOT:: v = [(randrange(-5,5), randrange(-5,5)) for _ in range(10)] P = polygon2d(v, legend_label='some form') sphinx_plot(P) A purple hexagon:: sage: L = [[cos(pi*i/3),sin(pi*i/3)] for i in range(6)] sage: polygon2d(L, rgbcolor=(1,0,1)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[cos(pi*i/3.0),sin(pi*i/3.0)] for i in range(6)] P = polygon2d(L, rgbcolor=(1,0,1)) sphinx_plot(P) A green deltoid:: sage: L = [[-1+cos(pi*i/100)*(1+cos(pi*i/100)),2*sin(pi*i/100)*(1-cos(pi*i/100))] for i in range(200)] sage: polygon2d(L, rgbcolor=(1/8,3/4,1/2)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[-1+cos(pi*i*0.01)*(1+cos(pi*i*0.01)),2*sin(pi*i*0.01)*(1-cos(pi*i*0.01))] for i in range(200)] P = polygon2d(L, rgbcolor=(0.125,0.75,0.5)) sphinx_plot(P) A blue hypotrochoid:: sage: L = [[6*cos(pi*i/100)+5*cos((6/2)*pi*i/100),6*sin(pi*i/100)-5*sin((6/2)*pi*i/100)] for i in range(200)] sage: polygon2d(L, rgbcolor=(1/8,1/4,1/2)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[6*cos(pi*i*0.01)+5*cos(3*pi*i*0.01),6*sin(pi*i*0.01)-5*sin(3*pi*i*0.01)] for i in range(200)] P = polygon2d(L, rgbcolor=(0.125,0.25,0.5)) sphinx_plot(P) Another one:: sage: n = 4; h = 5; b = 2 sage: L = [[n*cos(pi*i/100)+h*cos((n/b)*pi*i/100),n*sin(pi*i/100)-h*sin((n/b)*pi*i/100)] for i in range(200)] sage: polygon2d(L, rgbcolor=(1/8,1/4,3/4)) Graphics object consisting of 1 graphics primitive .. PLOT:: n = 4.0; h = 5.0; b = 2.0 L = [[n*cos(pi*i*0.01)+h*cos((n/b)*pi*i*0.01),n*sin(pi*i*0.01)-h*sin((n/b)*pi*i*0.01)] for i in range(200)] P = polygon2d(L, rgbcolor=(0.125,0.25,0.75)) sphinx_plot(P) A purple epicycloid:: sage: m = 9; b = 1 sage: L = [[m*cos(pi*i/100)+b*cos((m/b)*pi*i/100),m*sin(pi*i/100)-b*sin((m/b)*pi*i/100)] for i in range(200)] sage: polygon2d(L, rgbcolor=(7/8,1/4,3/4)) Graphics object consisting of 1 graphics primitive .. PLOT:: m = 9.0; b = 1 L = [[m*cos(pi*i*0.01)+b*cos((m/b)*pi*i*0.01),m*sin(pi*i*0.01)-b*sin((m/b)*pi*i*0.01)] for i in range(200)] P = polygon2d(L, rgbcolor=(0.875,0.25,0.75)) sphinx_plot(P) A brown astroid:: sage: L = [[cos(pi*i/100)^3,sin(pi*i/100)^3] for i in range(200)] sage: polygon2d(L, rgbcolor=(3/4,1/4,1/4)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[cos(pi*i*0.01)**3,sin(pi*i*0.01)**3] for i in range(200)] P = polygon2d(L, rgbcolor=(0.75,0.25,0.25)) sphinx_plot(P) And, my favorite, a greenish blob:: sage: L = [[cos(pi*i/100)*(1+cos(pi*i/50)), sin(pi*i/100)*(1+sin(pi*i/50))] for i in range(200)] sage: polygon2d(L, rgbcolor=(1/8,3/4,1/2)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[cos(pi*i*0.01)*(1+cos(pi*i*0.02)), sin(pi*i*0.01)*(1+sin(pi*i*0.02))] for i in range(200)] P = polygon2d(L, rgbcolor=(0.125,0.75,0.5)) sphinx_plot(P) This one is for my wife:: sage: L = [[sin(pi*i/100)+sin(pi*i/50),-(1+cos(pi*i/100)+cos(pi*i/50))] for i in range(-100,100)] sage: polygon2d(L, rgbcolor=(1,1/4,1/2)) Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[sin(pi*i*0.01)+sin(pi*i*0.02),-(1+cos(pi*i*0.01)+cos(pi*i*0.02))] for i in range(-100,100)] P = polygon2d(L, rgbcolor=(1,0.25,0.5)) sphinx_plot(P) One can do the same one with a colored legend label:: sage: polygon2d(L, color='red', legend_label='For you!', legend_color='red') Graphics object consisting of 1 graphics primitive .. PLOT:: L = [[sin(pi*i*0.01)+sin(pi*i*0.02),-(1+cos(pi*i*0.01)+cos(pi*i*0.02))] for i in range(-100,100)] P = polygon2d(L, color='red', legend_label='For you!', legend_color='red') sphinx_plot(P) Polygons have a default aspect ratio of 1.0:: sage: polygon2d([[1,2], [5,6], [5,0]]).aspect_ratio() 1.0 AUTHORS: - David Joyner (2006-04-14): the long list of examples above. """ from sage.plot.plot import xydata_from_point_list from sage.plot.all import Graphics if options["thickness"] is None: # If the user did not specify thickness if options["fill"] and options["edgecolor"] is None: # If the user chose fill options["thickness"] = 0 else: options["thickness"] = 1 xdata, ydata = xydata_from_point_list(points) g = Graphics() # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] if scale == 'semilogy' or scale == 'semilogx': options['aspect_ratio'] = 'automatic' g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) g.add_primitive(Polygon(xdata, ydata, options)) if options['legend_label']: g.legend(True) g._legend_colors = [options['legend_color']] return g
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/polygon.py
0.93356
0.647784
polygon.py
pypi
r""" Introduction Sage has a wide support for 3D graphics, from basic shapes to implicit and parametric plots. The following graphics functions are supported: - :func:`~plot3d` - plot a 3d function - :func:`~sage.plot.plot3d.parametric_plot3d.parametric_plot3d` - a parametric three-dimensional space curve or surface - :func:`~sage.plot.plot3d.revolution_plot3d.revolution_plot3d` - a plot of a revolved curve - :func:`~sage.plot.plot3d.plot_field3d.plot_vector_field3d` - a plot of a 3d vector field - :func:`~sage.plot.plot3d.implicit_plot3d.implicit_plot3d` - a plot of an isosurface of a function - :func:`~sage.plot.plot3d.list_plot3d.list_plot3d`- a 3-dimensional plot of a surface defined by a list of points in 3-dimensional space - :func:`~sage.plot.plot3d.list_plot3d.list_plot3d_matrix` - a 3-dimensional plot of a surface defined by a matrix defining points in 3-dimensional space - :func:`~sage.plot.plot3d.list_plot3d.list_plot3d_array_of_arrays`- A 3-dimensional plot of a surface defined by a list of lists defining points in 3-dimensional space - :func:`~sage.plot.plot3d.list_plot3d.list_plot3d_tuples` - a 3-dimensional plot of a surface defined by a list of points in 3-dimensional space The following classes for basic shapes are supported: - :class:`~sage.plot.plot3d.shapes.Box` - a box given its three magnitudes - :class:`~sage.plot.plot3d.shapes.Cone` - a cone, with base in the xy-plane pointing up the z-axis - :class:`~sage.plot.plot3d.shapes.Cylinder` - a cylinder, with base in the xy-plane pointing up the z-axis - :class:`~sage.plot.plot3d.shapes2.Line` - a 3d line joining a sequence of points - :class:`~sage.plot.plot3d.shapes.Sphere` - a sphere centered at the origin - :class:`~sage.plot.plot3d.shapes.Text` - a text label attached to a point in 3d space - :class:`~sage.plot.plot3d.shapes.Torus` - a 3d torus - :class:`~sage.plot.plot3d.shapes2.Point` - a position in 3d, represented by a sphere of fixed size The following plotting functions for basic shapes are supported - :func:`~sage.plot.plot3d.shapes.ColorCube` - a cube with given size and sides with given colors - :func:`~sage.plot.plot3d.shapes.LineSegment` - a line segment, which is drawn as a cylinder from start to end with given radius - :func:`~sage.plot.plot3d.shapes2.line3d` - a 3d line joining a sequence of points - :func:`~sage.plot.plot3d.shapes.arrow3d` - a 3d arrow - :func:`~sage.plot.plot3d.shapes2.point3d` - a point or list of points in 3d space - :func:`~sage.plot.plot3d.shapes2.bezier3d` - a 3d bezier path - :func:`~sage.plot.plot3d.shapes2.frame3d` - a frame in 3d - :func:`~sage.plot.plot3d.shapes2.frame_labels` - labels for a given frame in 3d - :func:`~sage.plot.plot3d.shapes2.polygon3d` - draw a polygon in 3d - :func:`~sage.plot.plot3d.shapes2.polygons3d` - draw the union of several polygons in 3d - :func:`~sage.plot.plot3d.shapes2.ruler` - draw a ruler in 3d, with major and minor ticks - :func:`~sage.plot.plot3d.shapes2.ruler_frame` - draw a frame made of 3d rulers, with major and minor ticks - :func:`~sage.plot.plot3d.shapes2.sphere` - plot of a sphere given center and radius - :func:`~sage.plot.plot3d.shapes2.text3d` - 3d text Sage also supports platonic solids with the following functions: - :func:`~sage.plot.plot3d.platonic.tetrahedron` - :func:`~sage.plot.plot3d.platonic.cube` - :func:`~sage.plot.plot3d.platonic.octahedron` - :func:`~sage.plot.plot3d.platonic.dodecahedron` - :func:`~sage.plot.plot3d.platonic.icosahedron` Different viewers are supported: a web-based interactive viewer using the Three.js JavaScript library (the default), Jmol, and the Tachyon ray tracer. The viewer is invoked by adding the keyword argument ``viewer='threejs'`` (respectively ``'jmol'`` or ``'tachyon'``) to the command ``show()`` on any three-dimensional graphic. - :class:`~sage.plot.plot3d.tachyon.Tachyon` - create a scene the can be rendered using the Tachyon ray tracer - :class:`~sage.plot.plot3d.tachyon.Axis_aligned_box` - box with axis-aligned edges with the given min and max coordinates - :class:`~sage.plot.plot3d.tachyon.Cylinder` - an infinite cylinder - :class:`~sage.plot.plot3d.tachyon.FCylinder` - a finite cylinder - :class:`~sage.plot.plot3d.tachyon.FractalLandscape`- axis-aligned fractal landscape - :class:`~sage.plot.plot3d.tachyon.Light` - represents lighting objects - :class:`~sage.plot.plot3d.tachyon.ParametricPlot` - parametric plot routines - :class:`~sage.plot.plot3d.tachyon.Plane` - an infinite plane - :class:`~sage.plot.plot3d.tachyon.Ring` - an annulus of zero thickness - :class:`~sage.plot.plot3d.tachyon.Sphere`- a sphere - :class:`~sage.plot.plot3d.tachyon.TachyonSmoothTriangle` - a triangle along with a normal vector, which is used for smoothing - :class:`~sage.plot.plot3d.tachyon.TachyonTriangle` - basic triangle class - :class:`~sage.plot.plot3d.tachyon.TachyonTriangleFactory` - class to produce triangles of various rendering types - :class:`~sage.plot.plot3d.tachyon.Texfunc` - creates a texture function - :class:`~sage.plot.plot3d.tachyon.Texture` - stores texture information - :func:`~sage.plot.plot3d.tachyon.tostr` - converts vector information to a space-separated string """
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/plot3d/introduction.py
0.953002
0.930395
introduction.py
pypi
from .parametric_surface import ParametricSurface from .shapes2 import line3d from sage.arith.srange import xsrange, srange from sage.structure.element import is_Vector from sage.misc.decorators import rename_keyword @rename_keyword(alpha='opacity') def parametric_plot3d(f, urange, vrange=None, plot_points="automatic", boundary_style=None, **kwds): r""" Return a parametric three-dimensional space curve or surface. There are four ways to call this function: - ``parametric_plot3d([f_x, f_y, f_z], (u_min, u_max))``: `f_x, f_y, f_z` are three functions and `u_{\min}` and `u_{\max}` are real numbers - ``parametric_plot3d([f_x, f_y, f_z], (u, u_min, u_max))``: `f_x, f_y, f_z` can be viewed as functions of `u` - ``parametric_plot3d([f_x, f_y, f_z], (u_min, u_max), (v_min, v_max))``: `f_x, f_y, f_z` are each functions of two variables - ``parametric_plot3d([f_x, f_y, f_z], (u, u_min, u_max), (v, v_min, v_max))``: `f_x, f_y, f_z` can be viewed as functions of `u` and `v` INPUT: - ``f`` - a 3-tuple of functions or expressions, or vector of size 3 - ``urange`` - a 2-tuple (u_min, u_max) or a 3-tuple (u, u_min, u_max) - ``vrange`` - (optional - only used for surfaces) a 2-tuple (v_min, v_max) or a 3-tuple (v, v_min, v_max) - ``plot_points`` - (default: "automatic", which is 75 for curves and [40,40] for surfaces) initial number of sample points in each parameter; an integer for a curve, and a pair of integers for a surface. - ``boundary_style`` - (default: None, no boundary) a dict that describes how to draw the boundaries of regions by giving options that are passed to the line3d command. - ``mesh`` - bool (default: False) whether to display mesh grid lines - ``dots`` - bool (default: False) whether to display dots at mesh grid points .. note:: #. By default for a curve any points where `f_x`, `f_y`, or `f_z` do not evaluate to a real number are skipped. #. Currently for a surface `f_x`, `f_y`, and `f_z` have to be defined everywhere. This will change. #. mesh and dots are not supported when using the Tachyon ray tracer renderer. EXAMPLES: We demonstrate each of the four ways to call this function. #. A space curve defined by three functions of 1 variable: :: sage: parametric_plot3d((sin, cos, lambda u: u/10), (0,20)) Graphics3d Object .. PLOT:: sphinx_plot(parametric_plot3d((sin, cos, lambda u: u/10), (0,20))) Note above the lambda function, which creates a callable Python function that sends `u` to `u/10`. #. Next we draw the same plot as above, but using symbolic functions: :: sage: u = var('u') sage: parametric_plot3d((sin(u), cos(u), u/10), (u,0,20)) Graphics3d Object .. PLOT:: u = var('u') sphinx_plot(parametric_plot3d((sin(u), cos(u), u/10), (u,0,20))) #. We draw a parametric surface using 3 Python functions (defined using lambda): :: sage: f = (lambda u,v: cos(u), lambda u,v: sin(u)+cos(v), lambda u,v: sin(v)) sage: parametric_plot3d(f, (0,2*pi), (-pi,pi)) Graphics3d Object .. PLOT:: f = (lambda u,v: cos(u), lambda u,v: sin(u)+cos(v), lambda u,v: sin(v)) sphinx_plot(parametric_plot3d(f, (0,2*pi), (-pi,pi))) #. The same surface, but where the defining functions are symbolic: :: sage: u, v = var('u,v') sage: parametric_plot3d((cos(u), sin(u)+cos(v), sin(v)), (u,0,2*pi), (v,-pi,pi)) Graphics3d Object .. PLOT:: u, v = var('u,v') sphinx_plot(parametric_plot3d((cos(u), sin(u)+cos(v) ,sin(v)), (u,0,2*pi), (v,-pi,pi))) The surface, but with a mesh:: sage: u, v = var('u,v') sage: parametric_plot3d((cos(u), sin(u)+cos(v), sin(v)), (u,0,2*pi), (v,-pi,pi), mesh=True) Graphics3d Object .. PLOT:: u, v = var('u,v') sphinx_plot(parametric_plot3d((cos(u), sin(u)+cos(v), sin(v)), (u,0,2*pi), (v,-pi,pi), mesh=True)) We increase the number of plot points, and make the surface green and transparent:: sage: parametric_plot3d((cos(u), sin(u)+cos(v), sin(v)), (u,0,2*pi), (v,-pi,pi), ....: color='green', opacity=0.1, plot_points=[30,30]) Graphics3d Object .. PLOT:: u, v = var('u,v') sphinx_plot(parametric_plot3d((cos(u), sin(u)+cos(v), sin(v)), (u,0,2*pi), (v,-pi,pi), color='green', opacity=0.1, plot_points=[30,30])) One can also color the surface using a coloring function and a colormap as follows. Note that the coloring function must take values in the interval [0,1]. :: sage: u,v = var('u,v') sage: def cf(u,v): return sin(u+v/2)**2 sage: P = parametric_plot3d((cos(u), sin(u)+cos(v), sin(v)), ....: (u,0,2*pi), (v,-pi,pi), color=(cf,colormaps.PiYG), plot_points=[60,60]) sage: P.show(viewer='tachyon') .. PLOT:: u,v = var('u,v') def cf(u,v): return sin(u+v/2)**2 P = parametric_plot3d((cos(u), sin(u)+cos(v), sin(v)), (u,0,2*pi), (v,-pi,pi), color=(cf,colormaps.PiYG), plot_points=[60,60]) sphinx_plot(P) Another example, a colored Möbius band:: sage: cm = colormaps.ocean sage: def c(x,y): return sin(x*y)**2 sage: from sage.plot.plot3d.parametric_surface import MoebiusStrip sage: MoebiusStrip(5, 1, plot_points=200, color=(c,cm)) Graphics3d Object .. PLOT:: cm = colormaps.ocean def c(x,y): return sin(x*y)**2 from sage.plot.plot3d.parametric_surface import MoebiusStrip sphinx_plot(MoebiusStrip(5, 1, plot_points=200, color=(c,cm))) Yet another colored example:: sage: from sage.plot.plot3d.parametric_surface import ParametricSurface sage: cm = colormaps.autumn sage: def c(x,y): return sin(x*y)**2 sage: def g(x,y): return x, y+sin(y), x**2 + y**2 sage: ParametricSurface(g, (srange(-10,10,0.1), srange(-5,5.0,0.1)), color=(c,cm)) Graphics3d Object .. PLOT:: from sage.plot.plot3d.parametric_surface import ParametricSurface cm = colormaps.autumn def c(x,y): return sin(x*y)**2 def g(x,y): return x, y+sin(y), x**2 + y**2 sphinx_plot(ParametricSurface(g, (srange(-10,10,0.1), srange(-5,5.0,0.1)), color=(c,cm))) We call the space curve function but with polynomials instead of symbolic variables. :: sage: R.<t> = RDF[] sage: parametric_plot3d((t, t^2, t^3), (t,0,3)) Graphics3d Object .. PLOT:: t = var('t') R = RDF['t'] sphinx_plot(parametric_plot3d((t, t**2, t**3), (t,0,3))) Next we plot the same curve, but because we use (0, 3) instead of (t, 0, 3), each polynomial is viewed as a callable function of one variable:: sage: parametric_plot3d((t, t^2, t^3), (0,3)) Graphics3d Object .. PLOT:: t = var('t') R = RDF['t'] sphinx_plot(parametric_plot3d((t, t**2, t**3), (0,3))) We do a plot but mix a symbolic input, and an integer:: sage: t = var('t') sage: parametric_plot3d((1, sin(t), cos(t)), (t,0,3)) Graphics3d Object .. PLOT:: t = var('t') sphinx_plot(parametric_plot3d((1, sin(t), cos(t)), (t,0,3))) We specify a boundary style to show us the values of the function at its extrema:: sage: u, v = var('u,v') sage: parametric_plot3d((cos(u), sin(u)+cos(v), sin(v)), (u,0,pi), (v,0,pi), ....: boundary_style={"color": "black", "thickness": 2}) Graphics3d Object .. PLOT:: u, v = var('u,v') P = parametric_plot3d((cos(u), sin(u)+cos(v), sin(v)), (u,0,pi), (v,0,pi), boundary_style={"color":"black", "thickness":2}) sphinx_plot(P) We can plot vectors:: sage: x,y = var('x,y') sage: parametric_plot3d(vector([x-y, x*y, x*cos(y)]), (x,0,2), (y,0,2)) Graphics3d Object .. PLOT:: x,y = var('x,y') sphinx_plot(parametric_plot3d(vector([x-y, x*y, x*cos(y)]), (x,0,2), (y,0,2))) :: sage: t = var('t') sage: p = vector([1,2,3]) sage: q = vector([2,-1,2]) sage: parametric_plot3d(p*t+q, (t,0,2)) Graphics3d Object .. PLOT:: t = var('t') p = vector([1,2,3]) q = vector([2,-1,2]) sphinx_plot(parametric_plot3d(p*t+q, (t,0,2))) Any options you would normally use to specify the appearance of a curve are valid as entries in the ``boundary_style`` dict. MANY MORE EXAMPLES: We plot two interlinked tori:: sage: u, v = var('u,v') sage: f1 = (4+(3+cos(v))*sin(u), 4+(3+cos(v))*cos(u), 4+sin(v)) sage: f2 = (8+(3+cos(v))*cos(u), 3+sin(v), 4+(3+cos(v))*sin(u)) sage: p1 = parametric_plot3d(f1, (u,0,2*pi), (v,0,2*pi), texture="red") sage: p2 = parametric_plot3d(f2, (u,0,2*pi), (v,0,2*pi), texture="blue") sage: p1 + p2 Graphics3d Object .. PLOT:: u, v = var('u,v') f1 = (4+(3+cos(v))*sin(u), 4+(3+cos(v))*cos(u), 4+sin(v)) f2 = (8+(3+cos(v))*cos(u), 3+sin(v), 4+(3+cos(v))*sin(u)) p1 = parametric_plot3d(f1, (u,0,2*pi), (v,0,2*pi), texture="red") p2 = parametric_plot3d(f2, (u,0,2*pi), (v,0,2*pi), texture="blue") sphinx_plot(p1 + p2) A cylindrical Star of David:: sage: u,v = var('u v') sage: K = (abs(cos(u))^200+abs(sin(u))^200)^(-1.0/200) sage: f_x = cos(u) * cos(v) * (abs(cos(3*v/4))^500+abs(sin(3*v/4))^500)^(-1/260) * K sage: f_y = cos(u) * sin(v) * (abs(cos(3*v/4))^500+abs(sin(3*v/4))^500)^(-1/260) * K sage: f_z = sin(u) * K sage: parametric_plot3d([f_x, f_y, f_z], (u, -pi, pi), (v, 0, 2*pi)) Graphics3d Object .. PLOT:: u,v = var('u v') K = (abs(cos(u))**200+abs(sin(u))**200)**(-1.0/200) f_x = cos(u) * cos(v) * (abs(cos(0.75*v))**500+abs(sin(0.75*v))**500)**(-1.0/260) * K f_y = cos(u)*sin(v)*(abs(cos(0.75*v))**500+abs(sin(0.75*v))**500)**(-1.0/260) * K f_z = sin(u) * K P = parametric_plot3d([f_x, f_y, f_z], (u, -pi, pi), (v, 0, 2*pi)) sphinx_plot(P) Double heart:: sage: u, v = var('u,v') sage: G1 = abs(sqrt(2)*tanh((u/sqrt(2)))) sage: G2 = abs(sqrt(2)*tanh((v/sqrt(2)))) sage: f_x = (abs(v) - abs(u) - G1 + G2)*sin(v) sage: f_y = (abs(v) - abs(u) - G1 - G2)*cos(v) sage: f_z = sin(u)*(abs(cos(u)) + abs(sin(u)))^(-1) sage: parametric_plot3d([f_x, f_y, f_z], (u,0,pi), (v,-pi,pi)) Graphics3d Object .. PLOT:: u, v = var('u,v') G1 = abs(sqrt(2)*tanh((u/sqrt(2)))) G2 = abs(sqrt(2)*tanh((v/sqrt(2)))) f_x = (abs(v) - abs(u) - G1 + G2)*sin(v) f_y = (abs(v) - abs(u) - G1 - G2)*cos(v) f_z = sin(u)*(abs(cos(u)) + abs(sin(u)))**(-1) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,pi), (v,-pi,pi))) Heart:: sage: u, v = var('u,v') sage: f_x = cos(u)*(4*sqrt(1-v^2)*sin(abs(u))^abs(u)) sage: f_y = sin(u)*(4*sqrt(1-v^2)*sin(abs(u))^abs(u)) sage: f_z = v sage: parametric_plot3d([f_x, f_y, f_z], (u,-pi,pi), (v,-1,1), frame=False, color="red") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = cos(u)*(4*sqrt(1-v**2)*sin(abs(u))**abs(u)) f_y = sin(u) *(4*sqrt(1-v**2)*sin(abs(u))**abs(u)) f_z = v sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-pi,pi), (v,-1,1), frame=False, color="red")) A Trefoil knot (:wikipedia:`Trefoil_knot`):: sage: u, v = var('u,v') sage: f_x = (4*(1+0.25*sin(3*v))+cos(u))*cos(2*v) sage: f_y = (4*(1+0.25*sin(3*v))+cos(u))*sin(2*v) sage: f_z = sin(u)+2*cos(3*v) sage: parametric_plot3d([f_x, f_y, f_z], (u,-pi,pi), (v,-pi,pi), frame=False, color="blue") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = (4*(1+0.25*sin(3*v))+cos(u))*cos(2*v) f_y = (4*(1+0.25*sin(3*v))+cos(u))*sin(2*v) f_z = sin(u)+2*cos(3*v) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-pi,pi), (v,-pi,pi), frame=False, color="blue")) Green bowtie:: sage: u, v = var('u,v') sage: f_x = sin(u) / (sqrt(2) + sin(v)) sage: f_y = sin(u) / (sqrt(2) + cos(v)) sage: f_z = cos(u) / (1 + sqrt(2)) sage: parametric_plot3d([f_x, f_y, f_z], (u,-pi,pi), (v,-pi,pi), frame=False, color="green") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = sin(u) / (sqrt(2) + sin(v)) f_y = sin(u) / (sqrt(2) + cos(v)) f_z = cos(u) / (1 + sqrt(2)) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-pi,pi), (v,-pi,pi), frame=False, color="green")) Boy's surface (:wikipedia:`Boy%27s_surface` and https://mathcurve.com/surfaces/boy/boy.shtml):: sage: u, v = var('u,v') sage: K = cos(u) / (sqrt(2) - cos(2*u)*sin(3*v)) sage: f_x = K * (cos(u)*cos(2*v)+sqrt(2)*sin(u)*cos(v)) sage: f_y = K * (cos(u)*sin(2*v)-sqrt(2)*sin(u)*sin(v)) sage: f_z = 3 * K * cos(u) sage: parametric_plot3d([f_x, f_y, f_z], (u,-2*pi,2*pi), (v,0,pi), ....: plot_points=[90,90], frame=False, color="orange") # long time -- about 30 seconds Graphics3d Object .. PLOT:: u, v = var('u,v') K = cos(u) / (sqrt(2) - cos(2*u)*sin(3*v)) f_x = K * (cos(u)*cos(2*v)+sqrt(2)*sin(u)*cos(v)) f_y = K * (cos(u)*sin(2*v)-sqrt(2)*sin(u)*sin(v)) f_z = 3 * K * cos(u) P = parametric_plot3d([f_x, f_y, f_z], (u,-2*pi,2*pi), (v,0,pi), plot_points=[90,90], frame=False, color="orange") # long time -- about 30 seconds sphinx_plot(P) Maeder's Owl also known as Bour's minimal surface (:wikipedia:`Bour%27s_minimal_surface`):: sage: u, v = var('u,v') sage: f_x = v*cos(u) - 0.5*v^2*cos(2*u) sage: f_y = -v*sin(u) - 0.5*v^2*sin(2*u) sage: f_z = 4 * v^1.5 * cos(3*u/2) / 3 sage: parametric_plot3d([f_x, f_y, f_z], (u,-2*pi,2*pi), (v,0,1), ....: plot_points=[90,90], frame=False, color="purple") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = v*cos(u) - 0.5*v**2*cos(2*u) f_y = -v*sin(u) - 0.5*v**2*sin(2*u) f_z = 4 * v**1.5 * cos(3*u/2) / 3 P = parametric_plot3d([f_x, f_y, f_z], (u,-2*pi,2*pi), (v,0,1), plot_points=[90,90], frame=False, color="purple") sphinx_plot(P) Bracelet:: sage: u, v = var('u,v') sage: f_x = (2 + 0.2*sin(2*pi*u))*sin(pi*v) sage: f_y = 0.2 * cos(2*pi*u) * 3 * cos(2*pi*v) sage: f_z = (2 + 0.2*sin(2*pi*u))*cos(pi*v) sage: parametric_plot3d([f_x, f_y, f_z], (u,0,pi/2), (v,0,3*pi/4), frame=False, color="gray") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = (2 + 0.2*sin(2*pi*u))*sin(pi*v) f_y = 0.2 * cos(2*pi*u) * 3* cos(2*pi*v) f_z = (2 + 0.2*sin(2*pi*u))*cos(pi*v) P = parametric_plot3d([f_x, f_y, f_z], (u,0,pi/2), (v,0,3*pi/4), frame=False, color="gray") sphinx_plot(P) Green goblet:: sage: u, v = var('u,v') sage: f_x = cos(u) * cos(2*v) sage: f_y = sin(u) * cos(2*v) sage: f_z = sin(v) sage: parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,pi), frame=False, color="green") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = cos(u) * cos(2*v) f_y = sin(u) * cos(2*v) f_z = sin(v) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,pi), frame=False, color="green")) Funny folded surface - with square projection:: sage: u, v = var('u,v') sage: f_x = cos(u) * sin(2*v) sage: f_y = sin(u) * cos(2*v) sage: f_z = sin(v) sage: parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="green") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = cos(u) * sin(2*v) f_y = sin(u) * cos(2*v) f_z = sin(v) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="green")) Surface of revolution of figure 8:: sage: u, v = var('u,v') sage: f_x = cos(u) * sin(2*v) sage: f_y = sin(u) * sin(2*v) sage: f_z = sin(v) sage: parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="green") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = cos(u) * sin(2*v) f_y = sin(u) * sin(2*v) f_z = sin(v) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="green")) Yellow Whitney's umbrella (:wikipedia:`Whitney_umbrella`):: sage: u, v = var('u,v') sage: f_x = u*v sage: f_y = u sage: f_z = v^2 sage: parametric_plot3d([f_x, f_y, f_z], (u,-1,1), (v,-1,1), frame=False, color="yellow") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = u*v f_y = u f_z = v**2 sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-1,1), (v,-1,1), frame=False, color="yellow")) Cross cap (:wikipedia:`Cross-cap`):: sage: u, v = var('u,v') sage: f_x = (1+cos(v)) * cos(u) sage: f_y = (1+cos(v)) * sin(u) sage: f_z = -tanh((2/3)*(u-pi)) * sin(v) sage: parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="red") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = (1+cos(v)) * cos(u) f_y = (1+cos(v)) * sin(u) f_z = -tanh((2.0/3.0)*(u-pi)) * sin(v) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="red")) Twisted torus:: sage: u, v = var('u,v') sage: f_x = (3+sin(v)+cos(u)) * cos(2*v) sage: f_y = (3+sin(v)+cos(u)) * sin(2*v) sage: f_z = sin(u) + 2*cos(v) sage: parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="red") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = (3+sin(v)+cos(u)) * cos(2*v) f_y = (3+sin(v)+cos(u)) * sin(2*v) f_z = sin(u) + 2*cos(v) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="red")) Four intersecting discs:: sage: u, v = var('u,v') sage: f_x = v*cos(u) - 0.5*v^2*cos(2*u) sage: f_y = -v*sin(u) - 0.5*v^2*sin(2*u) sage: f_z = 4 * v^1.5 * cos(3*u/2) / 3 sage: parametric_plot3d([f_x, f_y, f_z], (u,0,4*pi), (v,0,2*pi), frame=False, color="red", opacity=0.7) Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = v*cos(u) - 0.5*v**2*cos(2*u) f_y = -v*sin(u) - 0.5*v**2*sin(2*u) f_z = 4 * v**1.5 * cos(3.0*u/2.0) /3 sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,4*pi), (v,0,2*pi), frame=False, color="red", opacity=0.7)) Steiner surface/Roman's surface (see :wikipedia:`Roman_surface` and :wikipedia:`Steiner_surface`):: sage: u, v = var('u,v') sage: f_x = (sin(2*u) * cos(v) * cos(v)) sage: f_y = (sin(u) * sin(2*v)) sage: f_z = (cos(u) * sin(2*v)) sage: parametric_plot3d([f_x, f_y, f_z], (u,-pi/2,pi/2), (v,-pi/2,pi/2), frame=False, color="red") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = (sin(2*u) * cos(v) * cos(v)) f_y = (sin(u) * sin(2*v)) f_z = (cos(u) * sin(2*v)) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-pi/2,pi/2), (v,-pi/2,pi/2), frame=False, color="red")) Klein bottle? (see :wikipedia:`Klein_bottle`):: sage: u, v = var('u,v') sage: f_x = (3*(1+sin(v)) + 2*(1-cos(v)/2)*cos(u)) * cos(v) sage: f_y = (4+2*(1-cos(v)/2)*cos(u)) * sin(v) sage: f_z = -2 * (1-cos(v)/2) * sin(u) sage: parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="green") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = (3*(1+sin(v)) + 2*(1-cos(v)/2)*cos(u)) * cos(v) f_y = (4+2*(1-cos(v)/2)*cos(u)) * sin(v) f_z = -2 * (1-cos(v)/2) * sin(u) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="green")) A Figure 8 embedding of the Klein bottle (see :wikipedia:`Klein_bottle`):: sage: u, v = var('u,v') sage: f_x = (2+cos(v/2)*sin(u)-sin(v/2)*sin(2*u)) * cos(v) sage: f_y = (2+cos(v/2)*sin(u)-sin(v/2)*sin(2*u)) * sin(v) sage: f_z = sin(v/2)*sin(u) + cos(v/2)*sin(2*u) sage: parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="red") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = (2+cos(0.5*v)*sin(u)-sin(0.5*v)*sin(2*u)) * cos(v) f_y = (2+cos(0.5*v)*sin(u)-sin(0.5*v)*sin(2*u)) * sin(v) f_z = sin(v*0.5)*sin(u) + cos(v*0.5)*sin(2*u) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0,2*pi), frame=False, color="red")) Enneper's surface (see :wikipedia:`Enneper_surface`):: sage: u, v = var('u,v') sage: f_x = u - u^3/3 + u*v^2 sage: f_y = v - v^3/3 + v*u^2 sage: f_z = u^2 - v^2 sage: parametric_plot3d([f_x, f_y, f_z], (u,-2,2), (v,-2,2), frame=False, color="red") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = u - u**3/3 + u*v**2 f_y = v - v**3/3 + v*u**2 f_z = u**2 - v**2 sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-2,2), (v,-2,2), frame=False, color="red")) Henneberg's surface (see http://xahlee.org/surface/gallery_m.html):: sage: u, v = var('u,v') sage: f_x = 2*sinh(u)*cos(v) - (2/3)*sinh(3*u)*cos(3*v) sage: f_y = 2*sinh(u)*sin(v) + (2/3)*sinh(3*u)*sin(3*v) sage: f_z = 2 * cosh(2*u) * cos(2*v) sage: parametric_plot3d([f_x, f_y, f_z], (u,-1,1), (v,-pi/2,pi/2), frame=False, color="red") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = 2.0*sinh(u)*cos(v) - (2.0/3.0)*sinh(3*u)*cos(3*v) f_y = 2.0*sinh(u)*sin(v) + (2.0/3.0)*sinh(3*u)*sin(3*v) f_z = 2.0 * cosh(2*u) * cos(2*v) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-1,1), (v,-pi/2,pi/2), frame=False, color="red")) Dini's spiral:: sage: u, v = var('u,v') sage: f_x = cos(u) * sin(v) sage: f_y = sin(u) * sin(v) sage: f_z = (cos(v)+log(tan(v/2))) + 0.2*u sage: parametric_plot3d([f_x, f_y, f_z], (u,0,12.4), (v,0.1,2), frame=False, color="red") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = cos(u) * sin(v) f_y = sin(u) * sin(v) f_z = (cos(v)+log(tan(v*0.5))) + 0.2*u sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,12.4), (v,0.1,2), frame=False, color="red")) Catalan's surface (see http://xahlee.org/surface/catalan/catalan.html):: sage: u, v = var('u,v') sage: f_x = u - sin(u)*cosh(v) sage: f_y = 1 - cos(u)*cosh(v) sage: f_z = 4 * sin(1/2*u) * sinh(v/2) sage: parametric_plot3d([f_x, f_y, f_z], (u,-pi,3*pi), (v,-2,2), frame=False, color="red") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = u - sin(u)*cosh(v) f_y = 1.0 - cos(u)*cosh(v) f_z = 4.0 * sin(0.5*u) * sinh(0.5*v) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-pi,3*pi), (v,-2,2), frame=False, color="red")) A Conchoid:: sage: u, v = var('u,v') sage: k = 1.2; k_2 = 1.2; a = 1.5 sage: f = (k^u*(1+cos(v))*cos(u), k^u*(1+cos(v))*sin(u), k^u*sin(v)-a*k_2^u) sage: parametric_plot3d(f, (u,0,6*pi), (v,0,2*pi), plot_points=[40,40], texture=(0,0.5,0)) Graphics3d Object .. PLOT:: u, v = var('u,v') k = 1.2; k_2 = 1.2; a = 1.5 f = (k**u*(1+cos(v))*cos(u), k**u*(1+cos(v))*sin(u), k**u*sin(v)-a*k_2**u) sphinx_plot(parametric_plot3d(f, (u,0,6*pi), (v,0,2*pi), plot_points=[40,40], texture=(0,0.5,0))) A Möbius strip:: sage: u,v = var("u,v") sage: parametric_plot3d([cos(u)*(1+v*cos(u/2)), sin(u)*(1+v*cos(u/2)), 0.2*v*sin(u/2)], ....: (u,0, 4*pi+0.5), (v,0, 0.3), plot_points=[50,50]) Graphics3d Object .. PLOT:: u,v = var("u,v") sphinx_plot(parametric_plot3d([cos(u)*(1+v*cos(u*0.5)), sin(u)*(1+v*cos(u*0.5)), 0.2*v*sin(u*0.5)], (u,0,4*pi+0.5), (v,0,0.3), plot_points=[50,50])) A Twisted Ribbon:: sage: u, v = var('u,v') sage: parametric_plot3d([3*sin(u)*cos(v), 3*sin(u)*sin(v), cos(v)], ....: (u,0,2*pi), (v,0,pi), plot_points=[50,50]) Graphics3d Object .. PLOT:: u, v = var('u,v') sphinx_plot(parametric_plot3d([3*sin(u)*cos(v), 3*sin(u)*sin(v), cos(v)], (u,0,2*pi), (v,0,pi), plot_points=[50,50])) An Ellipsoid:: sage: u, v = var('u,v') sage: parametric_plot3d([3*sin(u)*cos(v), 2*sin(u)*sin(v), cos(u)], ....: (u,0, 2*pi), (v, 0, 2*pi), plot_points=[50,50], aspect_ratio=[1,1,1]) Graphics3d Object .. PLOT:: u, v = var('u,v') sphinx_plot(parametric_plot3d([3*sin(u)*cos(v), 2*sin(u)*sin(v), cos(u)], (u,0,2*pi), (v,0,2*pi), plot_points=[50,50], aspect_ratio=[1,1,1])) A Cone:: sage: u, v = var('u,v') sage: parametric_plot3d([u*cos(v), u*sin(v), u], (u,-1,1), (v,0,2*pi+0.5), plot_points=[50,50]) Graphics3d Object .. PLOT:: u, v = var('u,v') sphinx_plot(parametric_plot3d([u*cos(v), u*sin(v), u], (u,-1,1), (v,0,2*pi+0.5), plot_points=[50,50])) A Paraboloid:: sage: u, v = var('u,v') sage: parametric_plot3d([u*cos(v), u*sin(v), u^2], (u,0,1), (v,0,2*pi+0.4), plot_points=[50,50]) Graphics3d Object .. PLOT:: u, v = var('u,v') sphinx_plot(parametric_plot3d([u*cos(v), u*sin(v), u**2], (u,0,1), (v,0,2*pi+0.4), plot_points=[50,50])) A Hyperboloid:: sage: u, v = var('u,v') sage: plot3d(u^2-v^2, (u,-1,1), (v,-1,1), plot_points=[50,50]) Graphics3d Object .. PLOT:: u, v = var('u,v') sphinx_plot(plot3d(u**2-v**2, (u,-1,1), (v,-1,1), plot_points=[50,50])) A weird looking surface - like a Möbius band but also an O:: sage: u, v = var('u,v') sage: parametric_plot3d([sin(u)*cos(u)*log(u^2)*sin(v), (u^2)^(1/6)*(cos(u)^2)^(1/4)*cos(v), sin(v)], ....: (u,0.001,1), (v,-pi,pi+0.2), plot_points=[50,50]) Graphics3d Object .. PLOT:: u, v = var('u,v') sphinx_plot(parametric_plot3d([sin(u)*cos(u)*log(u**2)*sin(v), (u**2)**(1.0/6.0)*(cos(u)**2)**(0.25)*cos(v), sin(v)], (u,0.001,1), (v,-pi,pi+0.2), plot_points=[50,50])) A heart, but not a cardioid (for my wife):: sage: u, v = var('u,v') sage: p1 = parametric_plot3d([sin(u)*cos(u)*log(u^2)*v*(1-v)/2, ((u^6)^(1/20)*(cos(u)^2)^(1/4)-1/2)*v*(1-v), v^(0.5)], ....: (u,0.001,1), (v,0,1), plot_points=[70,70], color='red') sage: p2 = parametric_plot3d([-sin(u)*cos(u)*log(u^2)*v*(1-v)/2, ((u^6)^(1/20)*(cos(u)^2)^(1/4)-1/2)*v*(1-v), v^(0.5)], ....: (u, 0.001,1), (v,0,1), plot_points=[70,70], color='red') sage: show(p1+p2) .. PLOT:: u, v = var('u,v') p1 = parametric_plot3d([sin(u)*cos(u)*log(u**2)*v*(1-v)*0.5, ((u**6)**(1/20.0)*(cos(u)**2)**(0.25)-0.5)*v*(1-v), v**(0.5)], (u,0.001,1), (v,0,1), plot_points=[70,70], color='red') p2 = parametric_plot3d([-sin(u)*cos(u)*log(u**2)*v*(1-v)*0.5, ((u**6)**(1/20.0)*(cos(u)**2)**(0.25)-0.5)*v*(1-v), v**(0.5)], (u,0.001,1), (v,0,1), plot_points=[70,70], color='red') sphinx_plot(p1+p2) A Hyperhelicoidal:: sage: u = var("u") sage: v = var("v") sage: f_x = (sinh(v)*cos(3*u)) / (1+cosh(u)*cosh(v)) sage: f_y = (sinh(v)*sin(3*u)) / (1+cosh(u)*cosh(v)) sage: f_z = (cosh(v)*sinh(u)) / (1+cosh(u)*cosh(v)) sage: parametric_plot3d([f_x, f_y, f_z], (u,-pi,pi), (v,-pi,pi), plot_points=[50,50], frame=False, color="red") Graphics3d Object .. PLOT:: u = var("u") v = var("v") f_x = (sinh(v)*cos(3*u)) / (1+cosh(u)*cosh(v)) f_y = (sinh(v)*sin(3*u)) / (1+cosh(u)*cosh(v)) f_z = (cosh(v)*sinh(u)) / (1+cosh(u)*cosh(v)) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-pi,pi), (v,-pi,pi), plot_points=[50,50], frame=False, color="red")) A Helicoid (lines through a helix, :wikipedia:`Helix`):: sage: u, v = var('u,v') sage: f_x = sinh(v) * sin(u) sage: f_y = -sinh(v) * cos(u) sage: f_z = 3 * u sage: parametric_plot3d([f_x, f_y, f_z], (u,-pi,pi), (v,-pi,pi), plot_points=[50,50], frame=False, color="red") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = sinh(v) * sin(u) f_y = -sinh(v) * cos(u) f_z = 3 * u sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-pi,pi), (v,-pi,pi), plot_points=[50,50], frame=False, color="red")) Kuen's surface (http://virtualmathmuseum.org/Surface/kuen/kuen.html):: sage: f_x = (2*(cos(u) + u*sin(u))*sin(v))/(1+ u^2*sin(v)^2) sage: f_y = (2*(sin(u) - u*cos(u))*sin(v))/(1+ u^2*sin(v)^2) sage: f_z = log(tan(1/2 *v)) + (2*cos(v))/(1+ u^2*sin(v)^2) sage: parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0.01,pi-0.01), plot_points=[50,50], frame=False, color="green") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = (2.0*(cos(u)+u*sin(u))*sin(v)) / (1.0+u**2*sin(v)**2) f_y = (2.0*(sin(u)-u*cos(u))*sin(v)) / (1.0+u**2*sin(v)**2) f_z = log(tan(0.5 *v)) + (2*cos(v))/(1.0+u**2*sin(v)**2) sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,0,2*pi), (v,0.01,pi-0.01), plot_points=[50,50], frame=False, color="green")) A 5-pointed star:: sage: G1 = (abs(cos(u/4))^0.5+abs(sin(u/4))^0.5)^(-1/0.3) sage: G2 = (abs(cos(5*v/4))^1.7+abs(sin(5*v/4))^1.7)^(-1/0.1) sage: f_x = cos(u) * cos(v) * G1 * G2 sage: f_y = cos(u) * sin(v) * G1 * G2 sage: f_z = sin(u) * G1 sage: parametric_plot3d([f_x, f_y, f_z], (u,-pi/2,pi/2), (v,0,2*pi), plot_points=[50,50], frame=False, color="green") Graphics3d Object .. PLOT:: u, v = var('u,v') G1 = (abs(cos(u/4))**0.5+abs(sin(u/4))**0.5)**(-1/0.3) G2 = (abs(cos(5*v/4))**1.7+abs(sin(5*v/4))**1.7)**(-1/0.1) f_x = cos(u) * cos(v) * G1 * G2 f_y = cos(u) * sin(v) * G1 * G2 f_z = sin(u) * G1 sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-pi/2,pi/2), (v,0,2*pi), plot_points=[50,50], frame=False, color="green")) A cool self-intersecting surface (Eppener surface?):: sage: f_x = u - u^3/3 + u*v^2 sage: f_y = v - v^3/3 + v*u^2 sage: f_z = u^2 - v^2 sage: parametric_plot3d([f_x, f_y, f_z], (u,-25,25), (v,-25,25), plot_points=[50,50], frame=False, color="green") Graphics3d Object .. PLOT:: u, v = var('u,v') f_x = u - u**3/3 + u*v**2 f_y = v - v**3/3 + v*u**2 f_z = u**2 - v**2 sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-25,25), (v,-25,25), plot_points=[50,50], frame=False, color="green")) The breather surface (:wikipedia:`Breather_surface`):: sage: K = sqrt(0.84) sage: G = (0.4*((K*cosh(0.4*u))^2 + (0.4*sin(K*v))^2)) sage: f_x = (2*K*cosh(0.4*u)*(-(K*cos(v)*cos(K*v)) - sin(v)*sin(K*v)))/G sage: f_y = (2*K*cosh(0.4*u)*(-(K*sin(v)*cos(K*v)) + cos(v)*sin(K*v)))/G sage: f_z = -u + (2*0.84*cosh(0.4*u)*sinh(0.4*u))/G sage: parametric_plot3d([f_x, f_y, f_z], (u,-13.2,13.2), (v,-37.4,37.4), plot_points=[90,90], frame=False, color="green") Graphics3d Object .. PLOT:: u, v = var('u,v') K = sqrt(0.84) G = (0.4*((K*cosh(0.4*u))**2 + (0.4*sin(K*v))**2)) f_x = (2*K*cosh(0.4*u)*(-(K*cos(v)*cos(K*v)) - sin(v)*sin(K*v)))/G f_y = (2*K*cosh(0.4*u)*(-(K*sin(v)*cos(K*v)) + cos(v)*sin(K*v)))/G f_z = -u + (2*0.84*cosh(0.4*u)*sinh(0.4*u))/G sphinx_plot(parametric_plot3d([f_x, f_y, f_z], (u,-13.2,13.2), (v,-37.4,37.4), plot_points=[90,90], frame=False, color="green")) TESTS:: sage: u, v = var('u,v') sage: plot3d(u^2-v^2, (u,-1,1), (u,-1,1)) Traceback (most recent call last): ... ValueError: range variables should be distinct, but there are duplicates From :trac:`2858`:: sage: parametric_plot3d((u,-u,v), (u,-10,10),(v,-10,10)) Graphics3d Object sage: f(u)=u; g(v)=v^2; parametric_plot3d((g,f,f), (-10,10),(-10,10)) Graphics3d Object From :trac:`5368`:: sage: x, y = var('x,y') sage: plot3d(x*y^2 - sin(x), (x,-1,1), (y,-1,1)) Graphics3d Object """ # TODO: # * Surface -- behavior of functions not defined everywhere -- see note above # * Iterative refinement # color_function -- (default: "automatic") how to determine the color of curves and surfaces # color_function_scaling -- (default: True) whether to scale the input to color_function # exclusions -- (default: "automatic") u points or (u,v) conditions to exclude. # (E.g., exclusions could be a function e = lambda u, v: False if u < v else True # exclusions_style -- (default: None) what to draw at excluded points # max_recursion -- (default: "automatic") maximum number of recursive subdivisions, # when ... # mesh -- (default: "automatic") how many mesh divisions in each direction to draw # mesh_functions -- (default: "automatic") how to determine the placement of mesh divisions # mesh_shading -- (default: None) how to shade regions between mesh divisions # plot_range -- (default: "automatic") range of values to include if is_Vector(f): f = tuple(f) if isinstance(f, (list, tuple)) and len(f) > 0 and isinstance(f[0], (list, tuple)): return sum([parametric_plot3d(v, urange, vrange, plot_points=plot_points, **kwds) for v in f]) if not isinstance(f, (tuple, list)) or len(f) != 3: raise ValueError("f must be a list, tuple, or vector of length 3") if vrange is None: if plot_points == "automatic": plot_points = 75 G = _parametric_plot3d_curve(f, urange, plot_points=plot_points, **kwds) else: if plot_points == "automatic": plot_points = [40, 40] G = _parametric_plot3d_surface(f, urange, vrange, plot_points=plot_points, boundary_style=boundary_style, **kwds) G._set_extra_kwds(kwds) return G def _parametric_plot3d_curve(f, urange, plot_points, **kwds): r""" Return a parametric three-dimensional space curve. This function is used internally by the :func:`parametric_plot3d` command. There are two ways this function is invoked by :func:`parametric_plot3d`. - ``parametric_plot3d([f_x, f_y, f_z], (u_min, u_max))``: `f_x, f_y, f_z` are three functions and `u_{\min}` and `u_{\max}` are real numbers - ``parametric_plot3d([f_x, f_y, f_z], (u, u_min, u_max))``: `f_x, f_y, f_z` can be viewed as functions of `u` INPUT: - ``f`` - a 3-tuple of functions or expressions, or vector of size 3 - ``urange`` - a 2-tuple (u_min, u_max) or a 3-tuple (u, u_min, u_max) - ``plot_points`` - (default: "automatic", which is 75) initial number of sample points in each parameter; an integer. EXAMPLES: We demonstrate each of the two ways of calling this. See :func:`parametric_plot3d` for many more examples. We do the first one with a lambda function, which creates a callable Python function that sends `u` to `u/10`:: sage: parametric_plot3d((sin, cos, lambda u: u/10), (0,20)) # indirect doctest Graphics3d Object Now we do the same thing with symbolic expressions:: sage: u = var('u') sage: parametric_plot3d((sin(u), cos(u), u/10), (u,0,20)) Graphics3d Object """ from sage.plot.misc import setup_for_eval_on_grid g, ranges = setup_for_eval_on_grid(f, [urange], plot_points) f_x, f_y, f_z = g w = [(f_x(u), f_y(u), f_z(u)) for u in xsrange(*ranges[0], include_endpoint=True)] return line3d(w, **kwds) def _parametric_plot3d_surface(f, urange, vrange, plot_points, boundary_style, **kwds): r""" Return a parametric three-dimensional space surface. This function is used internally by the :func:`parametric_plot3d` command. There are two ways this function is invoked by :func:`parametric_plot3d`. - ``parametric_plot3d([f_x, f_y, f_z], (u_min, u_max), (v_min, v_max))``: `f_x, f_y, f_z` are each functions of two variables - ``parametric_plot3d([f_x, f_y, f_z], (u, u_min, u_max), (v, v_min, v_max))``: `f_x, f_y, f_z` can be viewed as functions of `u` and `v` INPUT: - ``f`` - a 3-tuple of functions or expressions, or vector of size 3 - ``urange`` - a 2-tuple (u_min, u_max) or a 3-tuple (u, u_min, u_max) - ``vrange`` - a 2-tuple (v_min, v_max) or a 3-tuple (v, v_min, v_max) - ``plot_points`` - (default: "automatic", which is [40,40] for surfaces) initial number of sample points in each parameter; a pair of integers. - ``boundary_style`` - (default: None, no boundary) a dict that describes how to draw the boundaries of regions by giving options that are passed to the line3d command. EXAMPLES: We demonstrate each of the two ways of calling this. See :func:`parametric_plot3d` for many more examples. We do the first one with lambda functions:: sage: f = (lambda u,v: cos(u), lambda u,v: sin(u)+cos(v), lambda u,v: sin(v)) sage: parametric_plot3d(f, (0, 2*pi), (-pi, pi)) # indirect doctest Graphics3d Object Now we do the same thing with symbolic expressions:: sage: u, v = var('u,v') sage: parametric_plot3d((cos(u), sin(u) + cos(v), sin(v)), (u, 0, 2*pi), (v, -pi, pi), mesh=True) Graphics3d Object """ from sage.plot.misc import setup_for_eval_on_grid g, ranges = setup_for_eval_on_grid(f, [urange, vrange], plot_points) urange = srange(*ranges[0], include_endpoint=True) vrange = srange(*ranges[1], include_endpoint=True) G = ParametricSurface(g, (urange, vrange), **kwds) if boundary_style is not None: for u in (urange[0], urange[-1]): G += line3d([(g[0](u,v), g[1](u,v), g[2](u,v)) for v in vrange], **boundary_style) for v in (vrange[0], vrange[-1]): G += line3d([(g[0](u,v), g[1](u,v), g[2](u,v)) for u in urange], **boundary_style) return G
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/plot3d/parametric_plot3d.py
0.884152
0.564038
parametric_plot3d.py
pypi
from sage.arith.srange import srange from sage.plot.misc import setup_for_eval_on_grid from sage.modules.free_module_element import vector from sage.plot.plot import plot def plot_vector_field3d(functions, xrange, yrange, zrange, plot_points=5, colors='jet', center_arrows=False, **kwds): r""" Plot a 3d vector field INPUT: - ``functions`` - a list of three functions, representing the x-, y-, and z-coordinates of a vector - ``xrange``, ``yrange``, and ``zrange`` - three tuples of the form (var, start, stop), giving the variables and ranges for each axis - ``plot_points`` (default 5) - either a number or list of three numbers, specifying how many points to plot for each axis - ``colors`` (default 'jet') - a color, list of colors (which are interpolated between), or matplotlib colormap name, giving the coloring of the arrows. If a list of colors or a colormap is given, coloring is done as a function of length of the vector - ``center_arrows`` (default False) - If True, draw the arrows centered on the points; otherwise, draw the arrows with the tail at the point - any other keywords are passed on to the plot command for each arrow EXAMPLES: A 3d vector field:: sage: x,y,z=var('x y z') sage: plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi)) Graphics3d Object .. PLOT:: x,y,z=var('x y z') sphinx_plot(plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi))) same example with only a list of colors:: sage: plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),colors=['red','green','blue']) Graphics3d Object .. PLOT:: x,y,z=var('x y z') sphinx_plot(plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),colors=['red','green','blue'])) same example with only one color:: sage: plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),colors='red') Graphics3d Object .. PLOT:: x,y,z=var('x y z') sphinx_plot(plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),colors='red')) same example with the same plot points for the three axes:: sage: plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),plot_points=4) Graphics3d Object .. PLOT:: x,y,z=var('x y z') sphinx_plot(plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),plot_points=4)) same example with different number of plot points for each axis:: sage: plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),plot_points=[3,5,7]) Graphics3d Object .. PLOT:: x,y,z=var('x y z') sphinx_plot(plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),plot_points=[3,5,7])) same example with the arrows centered on the points:: sage: plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),center_arrows=True) Graphics3d Object .. PLOT:: x,y,z=var('x y z') sphinx_plot(plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),center_arrows=True)) TESTS: This tests that :trac:`2100` is fixed in a way compatible with this command:: sage: plot_vector_field3d((x*cos(z),-y*cos(z),sin(z)), (x,0,pi), (y,0,pi), (z,0,pi),center_arrows=True,aspect_ratio=(1,2,1)) Graphics3d Object """ (ff, gg, hh), ranges = setup_for_eval_on_grid(functions, [xrange, yrange, zrange], plot_points) xpoints, ypoints, zpoints = [srange(*r, include_endpoint=True) for r in ranges] points = [vector((i, j, k)) for i in xpoints for j in ypoints for k in zpoints] vectors = [vector((ff(*point), gg(*point), hh(*point))) for point in points] try: from matplotlib.cm import get_cmap cm = get_cmap(colors) except (TypeError, ValueError): cm = None if cm is None: if isinstance(colors, (list, tuple)): from matplotlib.colors import LinearSegmentedColormap cm = LinearSegmentedColormap.from_list('mymap', colors) else: cm = lambda x: colors max_len = max(v.norm() for v in vectors) scaled_vectors = [v/max_len for v in vectors] if center_arrows: G = sum([plot(v, color=cm(v.norm()), **kwds).translate(p-v/2) for v, p in zip(scaled_vectors, points)]) G._set_extra_kwds(kwds) return G else: G = sum([plot(v, color=cm(v.norm()), **kwds).translate(p) for v, p in zip(scaled_vectors, points)]) G._set_extra_kwds(kwds) return G
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/plot3d/plot_field3d.py
0.864067
0.652408
plot_field3d.py
pypi
r""" Texture support This module provides texture/material support for 3D Graphics objects and plotting. This is a very rough common interface for Tachyon, x3d, and obj (mtl). See :class:`Texture <sage.plot.plot3d.texture.Texture>` for full details about options and use. Initially, we have no textures set:: sage: sage.plot.plot3d.base.Graphics3d().texture_set() set() However, one can access these textures in the following manner:: sage: G = tetrahedron(color='red') + tetrahedron(color='yellow') + tetrahedron(color='red', opacity=0.5) sage: [t for t in G.texture_set() if t.color == colors.red] # we should have two red textures [Texture(texture..., red, ff0000), Texture(texture..., red, ff0000)] sage: [t for t in G.texture_set() if t.color == colors.yellow] # ...and one yellow [Texture(texture..., yellow, ffff00)] And the Texture objects keep track of all their data:: sage: T = tetrahedron(color='red', opacity=0.5) sage: t = T.get_texture() sage: t.opacity 0.5 sage: T # should be translucent Graphics3d Object AUTHOR: - Robert Bradshaw (2007-07-07) Initial version. """ from textwrap import dedent from sage.misc.classcall_metaclass import ClasscallMetaclass, typecall from sage.misc.fast_methods import WithEqualityById from sage.structure.sage_object import SageObject from sage.plot.colors import colors, Color uniq_c = 0 def _new_global_texture_id(): """ Generate a new unique id for a texture. EXAMPLES:: sage: sage.plot.plot3d.texture._new_global_texture_id() 'texture...' sage: sage.plot.plot3d.texture._new_global_texture_id() 'texture...' """ global uniq_c uniq_c += 1 return "texture%s" % uniq_c def is_Texture(x): r""" Deprecated. Use ``isinstance(x, Texture)`` instead. EXAMPLES:: sage: from sage.plot.plot3d.texture import is_Texture, Texture sage: t = Texture(0.5) sage: is_Texture(t) doctest:...: DeprecationWarning: Please use isinstance(x, Texture) See https://trac.sagemath.org/27593 for details. True """ from sage.misc.superseded import deprecation deprecation(27593, "Please use isinstance(x, Texture)") return isinstance(x, Texture) def parse_color(info, base=None): r""" Parse the color. It transforms a valid color string into a color object and a color object into an RBG tuple of length 3. Otherwise, it multiplies the info by the base color. INPUT: - ``info`` - color, valid color str or number - ``base`` - tuple of length 3 (optional, default: ``None``) OUTPUT: A tuple or color. EXAMPLES: From a color:: sage: from sage.plot.plot3d.texture import parse_color sage: c = Color('red') sage: parse_color(c) (1.0, 0.0, 0.0) From a valid color str:: sage: parse_color('red') RGB color (1.0, 0.0, 0.0) sage: parse_color('#ff0000') RGB color (1.0, 0.0, 0.0) From a non valid color str:: sage: parse_color('redd') Traceback (most recent call last): ... ValueError: unknown color 'redd' From an info and a base:: sage: opacity = 10 sage: parse_color(opacity, base=(.2,.3,.4)) (2.0, 3.0, 4.0) """ if isinstance(info, Color): return info.rgb() elif isinstance(info, str): try: return Color(info) except KeyError: raise ValueError("unknown color '%s'" % info) else: r, g, b = base # We don't want to lose the data when we split it into its respective components. if not r: r = 1e-5 if not g: g = 1e-5 if not b: b = 1e-5 return (float(info * r), float(info * g), float(info * b)) class Texture(WithEqualityById, SageObject, metaclass=ClasscallMetaclass): r""" Class representing a texture. See documentation of :meth:`Texture.__classcall__ <sage.plot.plot3d.texture.Texture.__classcall__>` for more details and examples. EXAMPLES: We create a translucent texture:: sage: from sage.plot.plot3d.texture import Texture sage: t = Texture(opacity=0.6) sage: t Texture(texture..., 6666ff) sage: t.opacity 0.6 sage: t.jmol_str('obj') 'color obj translucent 0.4 [102,102,255]' sage: t.mtl_str() 'newmtl texture...\nKa 0.2 0.2 0.5\nKd 0.4 0.4 1.0\nKs 0.0 0.0 0.0\nillum 1\nNs 1.0\nd 0.6' sage: t.x3d_str() "<Appearance><Material diffuseColor='0.4 0.4 1.0' shininess='1.0' specularColor='0.0 0.0 0.0'/></Appearance>" TESTS:: sage: Texture(opacity=1/3).opacity 0.3333333333333333 sage: hash(Texture()) # random 42 """ @staticmethod def __classcall__(cls, id=None, **kwds): r""" Construct a new texture by id. INPUT: - ``id`` - a texture (optional, default: None), a dict, a color, a str, a tuple, None or any other type acting as an ID. If ``id`` is None and keyword ``texture`` is empty, then it returns a unique texture object. - ``texture`` - a texture - ``color`` - tuple or str, (optional, default: (.4, .4, 1)) - ``opacity`` - number between 0 and 1 (optional, default: 1) - ``ambient`` - number (optional, default: 0.5) - ``diffuse`` - number (optional, default: 1) - ``specular`` - number (optional, default: 0) - ``shininess`` - number (optional, default: 1) - ``name`` - str (optional, default: None) - ``**kwds`` - other valid keywords OUTPUT: A texture object. EXAMPLES: Texture from integer ``id``:: sage: from sage.plot.plot3d.texture import Texture sage: Texture(17) Texture(17, 6666ff) Texture from rational ``id``:: sage: Texture(3/4) Texture(3/4, 6666ff) Texture from a dict:: sage: Texture({'color':'orange','opacity':0.5}) Texture(texture..., orange, ffa500) Texture from a color:: sage: c = Color('red') sage: Texture(c) Texture(texture..., ff0000) Texture from a valid string color:: sage: Texture('red') Texture(texture..., red, ff0000) Texture from a non valid string color:: sage: Texture('redd') Texture(redd, 6666ff) Texture from a tuple:: sage: Texture((.2,.3,.4)) Texture(texture..., 334c66) Now accepting negative arguments, reduced modulo 1:: sage: Texture((-3/8, 1/2, 3/8)) Texture(texture..., 9f7f5f) Textures using other keywords:: sage: Texture(specular=0.4) Texture(texture..., 6666ff) sage: Texture(diffuse=0.4) Texture(texture..., 6666ff) sage: Texture(shininess=0.3) Texture(texture..., 6666ff) sage: Texture(ambient=0.7) Texture(texture..., 6666ff) """ if isinstance(id, Texture): return id if 'texture' in kwds: t = kwds['texture'] if isinstance(t, Texture): return t else: raise TypeError("texture keyword must be a texture object") if isinstance(id, dict): kwds = id if 'rgbcolor' in kwds: kwds['color'] = kwds['rgbcolor'] id = None elif isinstance(id, Color): kwds['color'] = id.rgb() id = None elif isinstance(id, str) and id in colors: kwds['color'] = id id = None elif isinstance(id, tuple): kwds['color'] = id id = None if id is None: id = _new_global_texture_id() return typecall(cls, id, **kwds) def __init__(self, id, color=(.4, .4, 1), opacity=1, ambient=0.5, diffuse=1, specular=0, shininess=1, name=None, **kwds): r""" Construction of a texture. See documentation of :meth:`Texture.__classcall__ <sage.plot.plot3d.texture.Texture.__classcall__>` for more details and examples. EXAMPLES:: sage: from sage.plot.plot3d.texture import Texture sage: Texture(3, opacity=0.6) Texture(3, 6666ff) """ self.id = id if name is None and isinstance(color, str): name = color self.name = name if not isinstance(color, tuple): color = parse_color(color) else: if len(color) == 4: opacity = color[3] color = tuple(float(1) if c == 1 else float(c) % 1 for c in color[0: 3]) self.color = color self.opacity = float(opacity) self.shininess = float(shininess) if not isinstance(ambient, tuple): ambient = parse_color(ambient, color) self.ambient = ambient if not isinstance(diffuse, tuple): diffuse = parse_color(diffuse, color) self.diffuse = diffuse if not isinstance(specular, tuple): specular = parse_color(specular, color) self.specular = specular def _repr_(self): """ Return a string representation of the Texture object. EXAMPLES:: sage: from sage.plot.plot3d.texture import Texture sage: Texture('yellow') #indirect doctest Texture(texture..., yellow, ffff00) sage: Texture((1,1,0), opacity=.5) Texture(texture..., ffff00) """ if self.name is not None: return "Texture(%s, %s, %s)" % (self.id, self.name, self.hex_rgb()) else: return "Texture(%s, %s)" % (self.id, self.hex_rgb()) def hex_rgb(self): """ EXAMPLES:: sage: from sage.plot.plot3d.texture import Texture sage: Texture('red').hex_rgb() 'ff0000' sage: Texture((1, .5, 0)).hex_rgb() 'ff7f00' """ return "%02x%02x%02x" % tuple(int(255 * s) for s in self.color) def tachyon_str(self): r""" Convert Texture object to string suitable for Tachyon ray tracer. EXAMPLES:: sage: from sage.plot.plot3d.texture import Texture sage: t = Texture(opacity=0.6) sage: t.tachyon_str() 'Texdef texture...\n Ambient 0.3333333333333333 Diffuse 0.6666666666666666 Specular 0.0 Opacity 0.6\n Color 0.4 0.4 1.0\n TexFunc 0' """ total_ambient = sum(self.ambient) total_diffuse = sum(self.diffuse) total_specular = sum(self.specular) total_color = total_ambient + total_diffuse + total_specular if total_color == 0: total_color = 1 ambient = total_ambient / total_color diffuse = total_diffuse / total_color specular = total_specular / total_color return dedent("""\ Texdef {id} Ambient {ambient!r} Diffuse {diffuse!r} Specular {specular!r} Opacity {opacity!r} Color {color[0]!r} {color[1]!r} {color[2]!r} TexFunc 0""").format(id=self.id, ambient=ambient, diffuse=diffuse, specular=specular, opacity=self.opacity, color=self.color) def x3d_str(self): r""" Convert Texture object to string suitable for x3d. EXAMPLES:: sage: from sage.plot.plot3d.texture import Texture sage: t = Texture(opacity=0.6) sage: t.x3d_str() "<Appearance><Material diffuseColor='0.4 0.4 1.0' shininess='1.0' specularColor='0.0 0.0 0.0'/></Appearance>" """ return ( "<Appearance>" "<Material diffuseColor='{color[0]!r} {color[1]!r} {color[2]!r}' " "shininess='{shininess!r}' " "specularColor='{specular!r} {specular!r} {specular!r}'/>" "</Appearance>").format(color=self.color, shininess=self.shininess, specular=self.specular[0]) def mtl_str(self): r""" Convert Texture object to string suitable for mtl output. EXAMPLES:: sage: from sage.plot.plot3d.texture import Texture sage: t = Texture(opacity=0.6) sage: t.mtl_str() 'newmtl texture...\nKa 0.2 0.2 0.5\nKd 0.4 0.4 1.0\nKs 0.0 0.0 0.0\nillum 1\nNs 1.0\nd 0.6' """ return dedent("""\ newmtl {id} Ka {ambient[0]!r} {ambient[1]!r} {ambient[2]!r} Kd {diffuse[0]!r} {diffuse[1]!r} {diffuse[2]!r} Ks {specular[0]!r} {specular[1]!r} {specular[2]!r} illum {illumination} Ns {shininess!r} d {opacity!r}""" ).format(id=self.id, ambient=self.ambient, diffuse=self.diffuse, specular=self.specular, illumination=(2 if sum(self.specular) > 0 else 1), shininess=self.shininess, opacity=self.opacity) def jmol_str(self, obj): r""" Convert Texture object to string suitable for Jmol applet. INPUT: - ``obj`` - str EXAMPLES:: sage: from sage.plot.plot3d.texture import Texture sage: t = Texture(opacity=0.6) sage: t.jmol_str('obj') 'color obj translucent 0.4 [102,102,255]' :: sage: sum([dodecahedron(center=[2.5*x, 0, 0], color=(1, 0, 0, x/10)) for x in range(11)]).show(aspect_ratio=[1,1,1], frame=False, zoom=2) """ translucent = "translucent %s" % float(1 - self.opacity) if self.opacity < 1 else "" return "color %s %s [%s,%s,%s]" % (obj, translucent, int(255 * self.color[0]), int(255 * self.color[1]), int(255 * self.color[2]))
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/plot3d/texture.py
0.893849
0.691413
texture.py
pypi
from .implicit_surface import ImplicitSurface def implicit_plot3d(f, xrange, yrange, zrange, **kwds): r""" Plot an isosurface of a function. INPUT: - ``f`` -- function - ``xrange`` -- a 2-tuple (x_min, x_max) or a 3-tuple (x, x_min, x_max) - ``yrange`` -- a 2-tuple (y_min, y_max) or a 3-tuple (y, y_min, y_max) - ``zrange`` -- a 2-tuple (z_min, z_max) or a 3-tuple (z, z_min, z_max) - ``plot_points`` -- (default: "automatic", which is 40) the number of function evaluations in each direction. (The number of cubes in the marching cubes algorithm will be one less than this). Can be a triple of integers, to specify a different resolution in each of x,y,z. - ``contour`` -- (default: 0) plot the isosurface f(x,y,z)==contour. Can be a list, in which case multiple contours are plotted. - ``region`` -- (default: None) If region is given, it must be a Python callable. Only segments of the surface where region(x,y,z) returns a number >0 will be included in the plot. (Note that returning a Python boolean is acceptable, since True == 1 and False == 0). EXAMPLES:: sage: var('x,y,z') (x, y, z) A simple sphere:: sage: implicit_plot3d(x^2+y^2+z^2==4, (x,-3,3), (y,-3,3), (z,-3,3)) Graphics3d Object .. PLOT:: var('x,y,z') F = x**2 + y**2 + z**2 P = implicit_plot3d(F==4, (x,-3,3), (y,-3,3), (z,-3,3)) sphinx_plot(P) A nested set of spheres with a hole cut out:: sage: implicit_plot3d((x^2 + y^2 + z^2), (x,-2,2), (y,-2,2), (z,-2,2), plot_points=60, contour=[1,3,5], ....: region=lambda x,y,z: x<=0.2 or y>=0.2 or z<=0.2, color='aquamarine').show(viewer='tachyon') .. PLOT:: var('x,y,z') F = x**2 + y**2 + z**2 P = implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), plot_points=60, contour=[1,3,5], region=lambda x,y,z: x<=0.2 or y>=0.2 or z<=0.2, color='aquamarine') sphinx_plot(P) A very pretty example, attributed to Douglas Summers-Stay (`archived page <http://web.archive.org/web/20080529033738/http://iat.ubalt.edu/summers/math/platsol.htm>`_):: sage: T = RDF(golden_ratio) sage: F = 2 - (cos(x+T*y) + cos(x-T*y) + cos(y+T*z) + cos(y-T*z) + cos(z-T*x) + cos(z+T*x)) sage: r = 4.77 sage: implicit_plot3d(F, (x,-r,r), (y,-r,r), (z,-r,r), plot_points=40, color='darkkhaki').show(viewer='tachyon') .. PLOT:: var('x,y,z') T = RDF(golden_ratio) F = 2 - (cos(x+T*y) + cos(x-T*y) + cos(y+T*z) + cos(y-T*z) + cos(z-T*x) + cos(z+T*x)) r = 4.77 V = implicit_plot3d(F, (x,-r,r), (y,-r,r), (z,-r,r), plot_points=40, color='darkkhaki') sphinx_plot(V) As I write this (but probably not as you read it), it's almost Valentine's day, so let's try a heart (from http://mathworld.wolfram.com/HeartSurface.html) :: sage: F = (x^2+9/4*y^2+z^2-1)^3 - x^2*z^3 - 9/(80)*y^2*z^3 sage: r = 1.5 sage: implicit_plot3d(F, (x,-r,r), (y,-r,r), (z,-r,r), plot_points=80, color='red', smooth=False).show(viewer='tachyon') .. PLOT:: var('x,y,z') F = (x**2+9.0/4.0*y**2+z**2-1)**3 - x**2*z**3 - 9.0/(80)*y**2*z**3 r = 1.5 V = implicit_plot3d(F, (x,-r,r), (y,-r,r), (z,-r,r), plot_points=80, color='red', smooth=False) sphinx_plot(V) The same examples also work with the default Jmol viewer; for example:: sage: T = RDF(golden_ratio) sage: F = 2 - (cos(x + T*y) + cos(x - T*y) + cos(y + T*z) + cos(y - T*z) + cos(z - T*x) + cos(z + T*x)) sage: r = 4.77 sage: implicit_plot3d(F, (x,-r,r), (y,-r,r), (z,-r,r), plot_points=40, color='deepskyblue').show() Here we use smooth=True with a Tachyon graph:: sage: implicit_plot3d(x^2 + y^2 + z^2, (x,-2,2), (y,-2,2), (z,-2,2), contour=4, color='deepskyblue', smooth=True) Graphics3d Object .. PLOT:: var('x,y,z') F = x**2 + y**2 + z**2 P = implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), contour=4, color='deepskyblue', smooth=True) sphinx_plot(P) We explicitly specify a gradient function (in conjunction with smooth=True) and invert the normals:: sage: gx = lambda x, y, z: -(2*x + y^2 + z^2) sage: gy = lambda x, y, z: -(x^2 + 2*y + z^2) sage: gz = lambda x, y, z: -(x^2 + y^2 + 2*z) sage: implicit_plot3d(x^2+y^2+z^2, (x,-2,2), (y,-2,2), (z,-2,2), contour=4, ....: plot_points=40, smooth=True, gradient=(gx, gy, gz)).show(viewer='tachyon') .. PLOT:: var('x,y,z') gx = lambda x, y, z: -(2*x + y**2 + z**2) gy = lambda x, y, z: -(x**2 + 2*y + z**2) gz = lambda x, y, z: -(x**2 + y**2 + 2*z) P = implicit_plot3d(x**2+y**2+z**2, (x,-2,2), (y,-2,2), (z,-2,2), contour=4, plot_points=40, smooth=True, gradient=(gx, gy, gz)) sphinx_plot(P) A graph of two metaballs interacting with each other:: sage: def metaball(x0, y0, z0): return 1 / ((x-x0)^2+(y-y0)^2+(z-z0)^2) sage: implicit_plot3d(metaball(-0.6,0,0) + metaball(0.6,0,0), (x,-2,2), (y,-2,2), (z,-2,2), plot_points=60, contour=2, color='seagreen') Graphics3d Object .. PLOT:: var('x,y,z') def metaball(x0, y0, z0): return 1 / ((x-x0)**2+(y-y0)**2+(z-z0)**2) P = implicit_plot3d(metaball(-0.6,0,0) + metaball(0.6,0,0), (x,-2,2), (y,-2,2), (z,-2,2), plot_points=60, contour=2, color='seagreen') sphinx_plot(P) One can also color the surface using a coloring function and a colormap as follows. Note that the coloring function must take values in the interval [0,1]. :: sage: t = (sin(3*z)**2).function(x,y,z) sage: cm = colormaps.gist_rainbow sage: G = implicit_plot3d(x^2 + y^2 + z^2, (x,-2,2), (y,-2,2), (z,-2, 2), ....: contour=4, color=(t,cm), plot_points=100) sage: G.show(viewer='tachyon') .. PLOT:: var('x,y,z') t = (sin(3*z)**2).function(x,y,z) cm = colormaps.gist_rainbow G = implicit_plot3d(x**2 + y**2 + z**2, (x,-2,2), (y,-2,2), (z,-2, 2), contour=4, color=(t,cm), plot_points=60) sphinx_plot(G) Here is another colored example:: sage: x, y, z = var('x,y,z') sage: t = (x).function(x,y,z) sage: cm = colormaps.PiYG sage: G = implicit_plot3d(x^4 + y^2 + z^2, (x,-2,2), ....: (y,-2,2),(z,-2,2), contour=4, color=(t,cm), plot_points=40) sage: G Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') t = (x).function(x,y,z) cm = colormaps.PiYG G = implicit_plot3d(x**4 + y**2 + z**2, (x,-2,2), (y,-2,2),(z,-2,2), contour=4, color=(t,cm), plot_points=40) sphinx_plot(G) MANY MORE EXAMPLES: A kind of saddle:: sage: implicit_plot3d(x^3 + y^2 - z^2, (x,-2,2), (y,-2,2), (z,-2,2), plot_points=60, contour=0, color='lightcoral') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(x**3 + y**2 - z**2, (x,-2,2), (y,-2,2), (z,-2,2), plot_points=60, contour=0, color='lightcoral') sphinx_plot(G) A smooth surface with six radial openings:: sage: implicit_plot3d(-(cos(x) + cos(y) + cos(z)), (x,-4,4), (y,-4,4), (z,-4,4), color='orchid') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(-(cos(x) + cos(y) + cos(z)), (x,-4,4), (y,-4,4), (z,-4,4), color='orchid') sphinx_plot(G) A cube composed of eight conjoined blobs:: sage: F = x^2 + y^2 + z^2 + cos(4*x) + cos(4*y) + cos(4*z) - 0.2 sage: implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), color='mediumspringgreen') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F = x**2 + y**2 + z**2 + cos(4*x) + cos(4*y) + cos(4*z) - 0.2 G = implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), color='mediumspringgreen') sphinx_plot(G) A variation of the blob cube featuring heterogeneously sized blobs:: sage: F = x^2 + y^2 + z^2 + sin(4*x) + sin(4*y) + sin(4*z) - 1 sage: implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), color='lavenderblush') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F = x**2 + y**2 + z**2 + sin(4*x) + sin(4*y) + sin(4*z) - 1 G = implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), color='lavenderblush') sphinx_plot(G) A Klein bottle:: sage: G = x^2 + y^2 + z^2 sage: F = (G+2*y-1)*((G-2*y-1)^2-8*z^2) + 16*x*z*(G-2*y-1) sage: implicit_plot3d(F, (x,-3,3), (y,-3.1,3.1), (z,-4,4), color='moccasin') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = x**2 + y**2 + z**2 F = (G+2*y-1)*((G-2*y-1)**2-8*z**2)+16*x*z*(G-2*y-1) G = implicit_plot3d(F, (x,-3,3), (y,-3.1,3.1), (z,-4,4), color='moccasin') sphinx_plot(G) A lemniscate:: sage: F = 4*x^2*(x^2+y^2+z^2+z) + y^2*(y^2+z^2-1) sage: implicit_plot3d(F, (x,-0.5,0.5), (y,-1,1), (z,-1,1), color='deeppink') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F = 4*x**2*(x**2+y**2+z**2+z) + y**2*(y**2+z**2-1) G = implicit_plot3d(F, (x,-0.5,0.5), (y,-1,1), (z,-1,1), color='deeppink') sphinx_plot(G) Drope:: sage: implicit_plot3d(z - 4*x*exp(-x^2-y^2), (x,-2,2), (y,-2,2), (z,-1.7,1.7), color='darkcyan') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(z - 4*x*exp(-x**2-y**2), (x,-2,2), (y,-2,2), (z,-1.7,1.7), color='darkcyan') sphinx_plot(G) A cube with a circular aperture on each face:: sage: F = ((1/2.3)^2 * (x^2 + y^2 + z^2))^(-6) + ((1/2)^8 * (x^8 + y^8 + z^8))^6 - 1 sage: implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), color='palevioletred') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F = ((1/2.3)**2 * (x**2 + y**2 + z**2))**(-6) + ((1/2)**8 * (x**8 + y**8 + z**8))**6 - 1 G = implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), color='palevioletred') sphinx_plot(G) A simple hyperbolic surface:: sage: implicit_plot3d(x^2 + y - z^2, (x,-1,1), (y,-1,1), (z,-1,1), color='darkslategray') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(x**2 + y - z**2, (x,-1,1), (y,-1,1), (z,-1,1), color='darkslategray') sphinx_plot(G) A hyperboloid:: sage: implicit_plot3d(x^2 + y^2 - z^2 -0.3, (x,-2,2), (y,-2,2), (z,-1.8,1.8), color='honeydew') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(x**2 + y**2 - z**2 -0.3, (x,-2,2), (y,-2,2), (z,-1.8,1.8), color='honeydew') sphinx_plot(G) Dupin cyclide (:wikipedia:`Dupin_cyclide`) :: sage: x, y, z , a, b, c, d = var('x,y,z,a,b,c,d') sage: a = 3.5 sage: b = 3 sage: c = sqrt(a^2 - b^2) sage: d = 2 sage: F = (x^2 + y^2 + z^2 + b^2 - d^2)^2 - 4*(a*x-c*d)^2 - 4*b^2*y^2 sage: implicit_plot3d(F, (x,-6,6), (y,-6,6), (z,-6,6), color='seashell') Graphics3d Object .. PLOT:: x, y, z , a, b, c, d = var('x,y,z,a,b,c,d') a = 3.5 b = 3 c = sqrt(a**2 - b**2) d = 2 F = (x**2 + y**2 + z**2 + b**2 - d**2)**2 - 4*(a*x-c*d)**2 - 4*b**2*y**2 G = implicit_plot3d(F, (x,-6,6), (y,-6,6), (z,-6,6), color='seashell') sphinx_plot(G) Sinus:: sage: implicit_plot3d(sin(pi*((x)^2+(y)^2))/2 + z, (x,-1,1), (y,-1,1), (z,-1,1), color='rosybrown') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(sin(pi*((x)**2+(y)**2))/2 + z, (x,-1,1), (y,-1,1), (z,-1,1), color='rosybrown') sphinx_plot(G) A torus:: sage: implicit_plot3d((sqrt(x*x+y*y)-3)^2 + z*z - 1, (x,-4,4), (y,-4,4), (z,-1,1), color='indigo') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d((sqrt(x*x+y*y)-3)**2 + z*z - 1, (x,-4,4), (y,-4,4), (z,-1,1), color='indigo') sphinx_plot(G) An octahedron:: sage: implicit_plot3d(abs(x) + abs(y) + abs(z) - 1, (x,-1,1), (y,-1,1), (z,-1,1), color='olive') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(abs(x) + abs(y) + abs(z) - 1, (x,-1,1), (y,-1,1), (z,-1,1), color='olive') sphinx_plot(G) A cube:: sage: implicit_plot3d(x^100 + y^100 + z^100 - 1, (x,-2,2), (y,-2,2), (z,-2,2), color='lightseagreen') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(x**100 + y**100 + z**100 - 1, (x,-2,2), (y,-2,2), (z,-2,2), color='lightseagreen') sphinx_plot(G) Toupie:: sage: implicit_plot3d((sqrt(x*x+y*y)-3)^3 + z*z - 1, (x,-4,4), (y,-4,4), (z,-6,6), color='mintcream') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d((sqrt(x*x+y*y)-3)**3 + z*z - 1, (x,-4,4), (y,-4,4), (z,-6,6), color='mintcream') sphinx_plot(G) A cube with rounded edges:: sage: F = x^4 + y^4 + z^4 - (x^2 + y^2 + z^2) sage: implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), color='mediumvioletred') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F = x**4 + y**4 + z**4 - (x**2 + y**2 + z**2) G = implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), color='mediumvioletred') sphinx_plot(G) Chmutov:: sage: F = x^4 + y^4 + z^4 - (x^2 + y^2 + z^2 - 0.3) sage: implicit_plot3d(F, (x,-1.5,1.5), (y,-1.5,1.5), (z,-1.5,1.5), color='lightskyblue') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F = x**4 + y**4 + z**4 - (x**2 + y**2 + z**2 - 0.3) G = implicit_plot3d(F, (x,-1.5,1.5), (y,-1.5,1.5), (z,-1.5,1.5), color='lightskyblue') sphinx_plot(G) Further Chmutov:: sage: F = 2*(x^2*(3-4*x^2)^2+y^2*(3-4*y^2)^2+z^2*(3-4*z^2)^2) - 3 sage: implicit_plot3d(F, (x,-1.3,1.3), (y,-1.3,1.3), (z,-1.3,1.3), color='darksalmon') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F = 2*(x**2*(3-4*x**2)**2+y**2*(3-4*y**2)**2+z**2*(3-4*z**2)**2) - 3 G = implicit_plot3d(F, (x,-1.3,1.3), (y,-1.3,1.3), (z,-1.3,1.3), color='darksalmon') sphinx_plot(G) Clebsch surface:: sage: F_1 = 81 * (x^3+y^3+z^3) sage: F_2 = 189 * (x^2*(y+z)+y^2*(x+z)+z^2*(x+y)) sage: F_3 = 54 * x * y * z sage: F_4 = 126 * (x*y+x*z+y*z) sage: F_5 = 9 * (x^2+y^2+z^2) sage: F_6 = 9 * (x+y+z) sage: F = F_1 - F_2 + F_3 + F_4 - F_5 + F_6 + 1 sage: implicit_plot3d(F, (x,-1,1), (y,-1,1), (z,-1,1), color='yellowgreen') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F_1 = 81 * (x**3+y**3+z**3) F_2 = 189 * (x**2*(y+z)+y**2*(x+z)+z**2*(x+y)) F_3 = 54 * x * y * z F_4 = 126 * (x*y+x*z+y*z) F_5 = 9 * (x**2+y**2+z**2) F_6 = 9 * (x+y+z) F = F_1 - F_2 + F_3 + F_4 - F_5 + F_6 + 1 G = implicit_plot3d(F, (x,-1,1), (y,-1,1), (z,-1,1), color='yellowgreen') sphinx_plot(G) Looks like a water droplet:: sage: implicit_plot3d(x^2 +y^2 -(1-z)*z^2, (x,-1.5,1.5), (y,-1.5,1.5), (z,-1,1), color='bisque') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(x**2 +y**2 -(1-z)*z**2, (x,-1.5,1.5), (y,-1.5,1.5), (z,-1,1), color='bisque') sphinx_plot(G) Sphere in a cage:: sage: F = (x^8+z^30+y^8-(x^4 + z^50 + y^4 -0.3)) * (x^2+y^2+z^2-0.5) sage: implicit_plot3d(F, (x,-1.2,1.2), (y,-1.3,1.3), (z,-1.5,1.5), color='firebrick') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F = (x**8+z**30+y**8-(x**4 + z**50 + y**4 -0.3)) * (x**2+y**2+z**2-0.5) G = implicit_plot3d(F, (x,-1.2,1.2), (y,-1.3,1.3), (z,-1.5,1.5), color='firebrick') sphinx_plot(G) Ortho circle:: sage: F = ((x^2+y^2-1)^2+z^2) * ((y^2+z^2-1)^2+x^2) * ((z^2+x^2-1)^2+y^2)-0.075^2 * (1+3*(x^2+y^2+z^2)) sage: implicit_plot3d(F, (x,-1.5,1.5), (y,-1.5,1.5), (z,-1.5,1.5), color='lemonchiffon') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F = ((x**2+y**2-1)**2+z**2) * ((y**2+z**2-1)**2+x**2) * ((z**2+x**2-1)**2+y**2)-0.075**2 * (1+3*(x**2+y**2+z**2)) G = implicit_plot3d(F, (x,-1.5,1.5), (y,-1.5,1.5), (z,-1.5,1.5), color='lemonchiffon') sphinx_plot(G) Cube sphere:: sage: F = 12 - ((1/2.3)^2 *(x^2 + y^2 + z^2))^-6 - ((1/2)^8 * (x^8 + y^8 + z^8))^6 sage: implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), color='rosybrown') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') F = 12 - ((1/2.3)**2 *(x**2 + y**2 + z**2))**-6 - ( (1/2)**8 * (x**8 + y**8 + z**8) )**6 G = implicit_plot3d(F, (x,-2,2), (y,-2,2), (z,-2,2), color='rosybrown') sphinx_plot(G) Two cylinders intersect to make a cross:: sage: implicit_plot3d((x^2+y^2-1) * (x^2+z^2-1) - 1, (x,-3,3), (y,-3,3), (z,-3,3), color='burlywood') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d((x**2+y**2-1) * (x**2+z**2-1) - 1, (x,-3,3), (y,-3,3), (z,-3,3), color='burlywood') sphinx_plot(G) Three cylinders intersect in a similar fashion:: sage: implicit_plot3d((x^2+y^2-1) * (x^2+z^2-1) * (y^2+z^2-1)-1, (x,-3,3), (y,-3,3), (z,-3,3), color='aqua') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d((x**2+y**2-1) * (x**2+z**2-1) * (y**2+z**2-1)-1, (x,-3,3), (y,-3,3), (z,-3,3), color='aqua') sphinx_plot(G) A sphere-ish object with twelve holes, four on each XYZ plane:: sage: implicit_plot3d(3*(cos(x)+cos(y)+cos(z)) + 4*cos(x)*cos(y)*cos(z), (x,-3,3), (y,-3,3), (z,-3,3), color='orangered') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(3*(cos(x)+cos(y)+cos(z)) + 4*cos(x)*cos(y)*cos(z), (x,-3,3), (y,-3,3), (z,-3,3), color='orangered') sphinx_plot(G) A gyroid:: sage: implicit_plot3d(cos(x)*sin(y) + cos(y)*sin(z) + cos(z)*sin(x), (x,-4,4), (y,-4,4), (z,-4,4), color='sandybrown') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d(cos(x)*sin(y) + cos(y)*sin(z) + cos(z)*sin(x), (x,-4,4), (y,-4,4), (z,-4,4), color='sandybrown') sphinx_plot(G) Tetrahedra:: sage: implicit_plot3d((x^2+y^2+z^2)^2 + 8*x*y*z - 10*(x^2+y^2+z^2) + 25, (x,-4,4), (y,-4,4), (z,-4,4), color='plum') Graphics3d Object .. PLOT:: x, y, z = var('x,y,z') G = implicit_plot3d((x**2+y**2+z**2)**2 + 8*x*y*z - 10*(x**2+y**2+z**2) + 25, (x,-4,4), (y,-4,4), (z,-4,4), color='plum') sphinx_plot(G) TESTS: Test a separate resolution in the X direction; this should look like a regular sphere:: sage: implicit_plot3d(x^2 + y^2 + z^2, (x,-2,2), (y,-2,2), (z,-2,2), plot_points=(10,40,40), contour=4) Graphics3d Object Test using different plot ranges in the different directions; each of these should generate half of a sphere. Note that we need to use the ``aspect_ratio`` keyword to make it look right with the unequal plot ranges:: sage: implicit_plot3d(x^2 + y^2 + z^2, (x,0,2), (y,-2,2), (z,-2,2), contour=4, aspect_ratio=1) Graphics3d Object sage: implicit_plot3d(x^2 + y^2 + z^2, (x,-2,2), (y,0,2), (z,-2,2), contour=4, aspect_ratio=1) Graphics3d Object sage: implicit_plot3d(x^2 + y^2 + z^2, (x,-2,2), (y,-2,2), (z,0,2), contour=4, aspect_ratio=1) Graphics3d Object Extra keyword arguments will be passed to show():: sage: implicit_plot3d(x^2 + y^2 + z^2, (x,-2,2), (y,-2,2), (z,-2,2), contour=4, viewer='tachyon') Graphics3d Object An implicit plot that does not include any surface in the view volume produces an empty plot:: sage: implicit_plot3d(x^2 + y^2 + z^2 - 5000, (x,-2,2), (y,-2,2), (z,-2,2), plot_points=6) Graphics3d Object Make sure that implicit_plot3d does not error if the function cannot be symbolically differentiated:: sage: implicit_plot3d(max_symbolic(x, y^2) - z, (x,-2,2), (y,-2,2), (z,-2,2), plot_points=6) Graphics3d Object TESTS: Check for :trac:`10599`:: sage: var('x,y,z') (x, y, z) sage: M = matrix(3,[1,-1,-1,-1,3,1,-1,1,3]) sage: v = 1/M.eigenvalues()[1] sage: implicit_plot3d(x^2+y^2+z^2==v, [x,-3,3], [y,-3,3],[z,-3,3]) Graphics3d Object """ # These options, related to rendering with smooth shading, are irrelevant # since IndexFaceSet does not support surface normals: # smooth: (default: False) Whether to use vertex normals to produce a # smooth-looking surface. False is slightly faster. # gradient: (default: None) If smooth is True (the default), then # Tachyon rendering needs vertex normals. In that case, if gradient is None # (the default), then we try to differentiate the function to get the # gradient. If that fails, then we use central differencing on the scalar # field. But it's also possible to specify the gradient; this must be either # a single python callable that takes (x,y,z) and returns a tuple (dx,dy,dz) # or a tuple of three callables that each take (x,y,z) and return dx, dy, dz # respectively. G = ImplicitSurface(f, xrange, yrange, zrange, **kwds) G._set_extra_kwds(kwds) return G
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/plot/plot3d/implicit_plot3d.py
0.918274
0.799677
implicit_plot3d.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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/matrix/matrix_misc.py
0.866627
0.711105
matrix_misc.py
pypi
r""" Work with WAV files A WAV file is a header specifying format information, followed by a sequence of bytes, representing the state of some audio signal over a length of time. A WAV file may have any number of channels. Typically, they have 1 (mono) or 2 (for stereo). The data of a WAV file is given as a sequence of frames. A frame consists of samples. There is one sample per channel, per frame. Every wav file has a sample width, or, the number of bytes per sample. Typically this is either 1 or 2 bytes. The wav module supplies more convenient access to this data. In particular, see the docstring for ``Wave.channel_data()``. The header contains information necessary for playing the WAV file, including the number of frames per second, the number of bytes per sample, and the number of channels in the file. AUTHORS: - Bobby Moretti and Gonzalo Tornaria (2007-07-01): First version - William Stein (2007-07-03): add more - Bobby Moretti (2007-07-03): add doctests This module (and all of ``sage.media``) is deprecated. EXAMPLES:: sage: import sage.media doctest:warning... DeprecationWarning: the package sage.media is deprecated See http://trac.sagemath.org/12673 for details. """ import math import os import wave from sage.misc.lazy_import import lazy_import lazy_import("sage.plot.plot", "list_plot") from sage.structure.sage_object import SageObject from sage.arith.srange import srange from sage.misc.html import html from sage.rings.real_double import RDF class Wave(SageObject): """ A class wrapping a wave audio file. INPUT: You must call Wave() with either data = filename, where filename is the name of a wave file, or with each of the following options: - channels -- the number of channels in the wave file (1 for mono, 2 for stereo, etc... - width -- the number of bytes per sample - framerate -- the number of frames per second - nframes -- the number of frames in the data stream - bytes -- a string object containing the bytes of the data stream Slicing: Slicing a Wave object returns a new wave object that has been trimmed to the bytes that you have given it. Indexing: Getting the `n`-th item in a Wave object will give you the value of the `n`-th frame. """ def __init__(self, data=None, **kwds): if data is not None: self._filename = data self._name = os.path.split(data)[1] wv = wave.open(data, "rb") self._nchannels = wv.getnchannels() self._width = wv.getsampwidth() self._framerate = wv.getframerate() self._nframes = wv.getnframes() self._bytes = wv.readframes(self._nframes) from .channels import _separate_channels self._channel_data = _separate_channels(self._bytes, self._width, self._nchannels) wv.close() elif kwds: try: self._name = kwds['name'] self._nchannels = kwds['nchannels'] self._width = kwds['width'] self._framerate = kwds['framerate'] self._nframes = kwds['nframes'] self._bytes = kwds['bytes'] self._channel_data = kwds['channel_data'] except KeyError as msg: raise KeyError(msg + " invalid input to Wave initializer") else: raise ValueError("Must give a filename") def save(self, filename='sage.wav'): r""" Save this wave file to disk, either as a Sage sobj or as a .wav file. INPUT: filename -- the path of the file to save. If filename ends with 'wav', then save as a wave file, otherwise, save a Sage object. If no input is given, save the file as 'sage.wav'. """ if not filename.endswith('.wav'): SageObject.save(self, filename) return wv = wave.open(filename, 'wb') wv.setnchannels(self._nchannels) wv.setsampwidth(self._width) wv.setframerate(self._framerate) wv.setnframes(self._nframes) wv.writeframes(self._bytes) wv.close() def listen(self): """ Listen to (or download) this wave file. Creates a link to this wave file in the notebook. """ i = 0 fname = 'sage%s.wav'%i while os.path.exists(fname): i += 1 fname = 'sage%s.wav'%i self.save(fname) return html('<a href="cell://%s">Click to listen to %s</a>'%(fname, self._name)) def channel_data(self, n): """ Get the data from a given channel. INPUT: n -- the channel number to get OUTPUT: A list of signed ints, each containing the value of a frame. """ return self._channel_data[n] def getnchannels(self): """ Return the number of channels in this wave object. OUTPUT: The number of channels in this wave file. """ return self._nchannels def getsampwidth(self): """ Return the number of bytes per sample in this wave object. OUTPUT: The number of bytes in each sample. """ return self._width def getframerate(self): """ Return the number of frames per second in this wave object. OUTPUT: The frame rate of this sound file. """ return self._framerate def getnframes(self): """ Return the total number of frames in this wave object. OUTPUT: The number of frames in this WAV. """ return self._nframes def readframes(self, n): """ Read out the raw data for the first `n` frames of this wave object. INPUT: n -- the number of frames to return OUTPUT: A list of bytes (in string form) representing the raw wav data. """ return self._bytes[:self._nframes * self._width] def getlength(self): """ Return the length of this file (in seconds). OUTPUT: The running time of the entire WAV object. """ return float(self._nframes) / (self._nchannels * float(self._framerate)) def _repr_(self): nc = self.getnchannels() return "Wave file %s with %s channel%s of length %s seconds%s" % \ (self._name, nc, "" if nc == 1 else "s", self.getlength(), "" if nc == 1 else " each") def _normalize_npoints(self, npoints): """ Used internally while plotting to normalize the number of """ return npoints if npoints else self._nframes def domain(self, npoints=None): """ Used internally for plotting. Get the x-values for the various points to plot. """ npoints = self._normalize_npoints(npoints) # figure out on what intervals to sample the data seconds = float(self._nframes) / float(self._width) frame_duration = seconds / (float(npoints) * float(self._framerate)) domain = [n * frame_duration for n in range(npoints)] return domain def values(self, npoints=None, channel=0): """ Used internally for plotting. Get the y-values for the various points to plot. """ npoints = self._normalize_npoints(npoints) # now, how many of the frames do we sample? frame_skip = int(self._nframes / npoints) # the values of the function at each point in the domain cd = self.channel_data(channel) # now scale the values scale = float(1 << (8*self._width -1)) values = [cd[frame_skip*i]/scale for i in range(npoints)] return values def set_values(self, values, channel=0): """ Used internally for plotting. Get the y-values for the various points to plot. """ c = self.channel_data(channel) npoints = len(c) if len(values) != npoints: raise ValueError("values (of length %s) must have length %s"%(len(values), npoints)) # unscale the values scale = float(1 << (8*self._width -1)) values = [float(abs(s)) * scale for s in values] # the values of the function at each point in the domain c = self.channel_data(channel) for i in range(npoints): c[i] = values[i] def vector(self, npoints=None, channel=0): npoints = self._normalize_npoints(npoints) V = RDF**npoints return V(self.values(npoints=npoints, channel=channel)) def plot(self, npoints=None, channel=0, plotjoined=True, **kwds): """ Plots the audio data. INPUT: - npoints -- number of sample points to take; if not given, draws all known points. - channel -- 0 or 1 (if stereo). default: 0 - plotjoined -- whether to just draw dots or draw lines between sample points OUTPUT: a plot object that can be shown. """ domain = self.domain(npoints=npoints) values = self.values(npoints=npoints, channel=channel) points = zip(domain, values) L = list_plot(points, plotjoined=plotjoined, **kwds) L.xmin(0) L.xmax(domain[-1]) return L def plot_fft(self, npoints=None, channel=0, half=True, **kwds): v = self.vector(npoints=npoints) w = v.fft() if half: w = w[:len(w)//2] z = [abs(x) for x in w] if half: r = math.pi else: r = 2*math.pi data = zip(srange(0, r, r/len(z)), z) L = list_plot(data, plotjoined=True, **kwds) L.xmin(0) L.xmax(r) return L def plot_raw(self, npoints=None, channel=0, plotjoined=True, **kwds): npoints = self._normalize_npoints(npoints) seconds = float(self._nframes) / float(self._width) sample_step = seconds / float(npoints) domain = [float(n*sample_step) / float(self._framerate) for n in range(npoints)] frame_skip = self._nframes / npoints values = [self.channel_data(channel)[frame_skip*i] for i in range(npoints)] points = zip(domain, values) return list_plot(points, plotjoined=plotjoined, **kwds) def __getitem__(self, i): """ Return the `i`-th frame of data in the wave, in the form of a string, if `i` is an integer. Return a slice of self if `i` is a slice. """ if isinstance(i, slice): start, stop, step = i.indices(self._nframes) return self._copy(start, stop) else: n = i*self._width return self._bytes[n:n+self._width] def slice_seconds(self, start, stop): """ Slice the wave from start to stop. INPUT: start -- the time index from which to begin the slice (in seconds) stop -- the time index from which to end the slice (in seconds) OUTPUT: A Wave object whose data is this object's data, sliced between the given time indices """ start = int(start*self.getframerate()) stop = int(stop*self.getframerate()) return self[start:stop] # start and stop are frame numbers def _copy(self, start, stop): start = start * self._width stop = stop * self._width channels_sliced = [self._channel_data[i][start:stop] for i in range(self._nchannels)] print(stop - start) return Wave(nchannels=self._nchannels, width=self._width, framerate=self._framerate, bytes=self._bytes[start:stop], nframes=stop - start, channel_data=channels_sliced, name=self._name) def __copy__(self): return self._copy(0, self._nframes) def convolve(self, right, channel=0): """ NOT DONE! Convolution of self and other, i.e., add their fft's, then inverse fft back. """ if not isinstance(right, Wave): raise TypeError("right must be a wave") npoints = self._nframes v = self.vector(npoints, channel=channel).fft() w = right.vector(npoints, channel=channel).fft() k = v + w i = k.inv_fft() conv = self.__copy__() conv.set_values(list(i)) conv._name = "convolution of %s and %s" % (self._name, right._name) return conv
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/media/wav.py
0.922509
0.573678
wav.py
pypi
from sage.rings.integer_ring import ZZ from .set import Set_generic from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets from sage.arith.misc import nth_prime from sage.structure.unique_representation import UniqueRepresentation class Primes(Set_generic, UniqueRepresentation): """ The set of prime numbers. EXAMPLES:: sage: P = Primes(); P Set of all prime numbers: 2, 3, 5, 7, ... We show various operations on the set of prime numbers:: sage: P.cardinality() +Infinity sage: R = Primes() sage: P == R True sage: 5 in P True sage: 100 in P False sage: len(P) Traceback (most recent call last): ... NotImplementedError: infinite set """ @staticmethod def __classcall__(cls, proof=True): """ TESTS:: sage: Primes(proof=True) is Primes() True sage: Primes(proof=False) is Primes() False """ return super().__classcall__(cls, proof) def __init__(self, proof): """ EXAMPLES:: sage: P = Primes(); P Set of all prime numbers: 2, 3, 5, 7, ... sage: Q = Primes(proof = False); Q Set of all prime numbers: 2, 3, 5, 7, ... TESTS:: sage: P.category() Category of facade infinite enumerated sets sage: TestSuite(P).run() sage: Q.category() Category of facade infinite enumerated sets sage: TestSuite(Q).run() The set of primes can be compared to various things, but is only equal to itself:: sage: P = Primes() sage: R = Primes() sage: P == R True sage: P != R False sage: Q = [1,2,3] sage: Q != P # indirect doctest True sage: R.<x> = ZZ[] sage: P != x^2+x True """ super().__init__(facade=ZZ, category=InfiniteEnumeratedSets()) self.__proof = proof def _repr_(self): """ Representation of the set of primes. EXAMPLES:: sage: P = Primes(); P Set of all prime numbers: 2, 3, 5, 7, ... """ return "Set of all prime numbers: 2, 3, 5, 7, ..." def __contains__(self, x): """ Check whether an object is a prime number. EXAMPLES:: sage: P = Primes() sage: 5 in P True sage: 100 in P False sage: 1.5 in P False sage: e in P False """ try: if x not in ZZ: return False return ZZ(x).is_prime() except TypeError: return False def _an_element_(self): """ Return a typical prime number. EXAMPLES:: sage: P = Primes() sage: P._an_element_() 43 """ return ZZ(43) def first(self): """ Return the first prime number. EXAMPLES:: sage: P = Primes() sage: P.first() 2 """ return ZZ(2) def next(self, pr): """ Return the next prime number. EXAMPLES:: sage: P = Primes() sage: P.next(5) 7 """ pr = pr.next_prime(self.__proof) return pr def unrank(self, n): """ Return the n-th prime number. EXAMPLES:: sage: P = Primes() sage: P.unrank(0) 2 sage: P.unrank(5) 13 sage: P.unrank(42) 191 """ return nth_prime(n+1)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/sets/primes.py
0.873714
0.470919
primes.py
pypi
from sage.structure.element import Element from sage.structure.parent import Parent from sage.structure.richcmp import richcmp, rich_to_bool from sage.sets.finite_enumerated_set import FiniteEnumeratedSet from sage.categories.posets import Posets from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets class TotallyOrderedFiniteSetElement(Element): """ Element of a finite totally ordered set. EXAMPLES:: sage: S = TotallyOrderedFiniteSet([2,7], facade=False) sage: x = S(2) sage: print(x) 2 sage: x.parent() {2, 7} """ def __init__(self, parent, data): r""" TESTS:: sage: T = TotallyOrderedFiniteSet([3,2,1],facade=False) sage: TestSuite(T.an_element()).run() """ Element.__init__(self, parent) self.value = data def __eq__(self, other): r""" Equality. EXAMPLES:: sage: A = TotallyOrderedFiniteSet(['gaga',1], facade=False) sage: A('gaga') == 'gaga' #indirect doctest False sage: 'gaga' == A('gaga') False sage: A('gaga') == A('gaga') True """ try: same_parent = self.parent() is other.parent() except AttributeError: return False if not same_parent: return False return other.value == self.value def __ne__(self, other): r""" Non-equality. EXAMPLES:: sage: A = TotallyOrderedFiniteSet(['gaga',1], facade=False) sage: A('gaga') != 'gaga' #indirect doctest True """ return not (self == other) def _richcmp_(self, other, op): r""" Comparison. For ``self`` and ``other`` that have the same parent the method compares their rank. TESTS:: sage: A = TotallyOrderedFiniteSet([3,2,7], facade=False) sage: A(3) < A(2) and A(3) <= A(2) and A(2) <= A(2) True sage: A(2) > A(3) and A(2) >= A(3) and A(7) >= A(7) True sage: A(3) >= A(7) or A(2) > A(2) False sage: A(7) < A(2) or A(2) <= A(3) or A(2) < A(2) False """ if self.value == other.value: return rich_to_bool(op, 0) return richcmp(self.rank(), other.rank(), op) def _repr_(self): r""" String representation. TESTS:: sage: A = TotallyOrderedFiniteSet(['gaga',1], facade=False) sage: repr(A('gaga')) #indirect doctest "'gaga'" """ return repr(self.value) def __str__(self): r""" String that represents self. EXAMPLES:: sage: A = TotallyOrderedFiniteSet(['gaga',1], facade=False) sage: str(A('gaga')) #indirect doctest 'gaga' """ return str(self.value) class TotallyOrderedFiniteSet(FiniteEnumeratedSet): """ Totally ordered finite set. This is a finite enumerated set assuming that the elements are ordered based upon their rank (i.e. their position in the set). INPUT: - ``elements`` -- A list of elements in the set - ``facade`` -- (default: ``True``) if ``True``, a facade is used; it should be set to ``False`` if the elements do not inherit from :class:`~sage.structure.element.Element` or if you want a funny order. See examples for more details. .. SEEALSO:: :class:`FiniteEnumeratedSet` EXAMPLES:: sage: S = TotallyOrderedFiniteSet([1,2,3]) sage: S {1, 2, 3} sage: S.cardinality() 3 By default, totally ordered finite set behaves as a facade:: sage: S(1).parent() Integer Ring It makes comparison fails when it is not the standard order:: sage: T1 = TotallyOrderedFiniteSet([3,2,5,1]) sage: T1(3) < T1(1) False sage: T2 = TotallyOrderedFiniteSet([3,var('x')]) sage: T2(3) < T2(var('x')) 3 < x To make the above example work, you should set the argument facade to ``False`` in the constructor. In that case, the elements of the set have a dedicated class:: sage: A = TotallyOrderedFiniteSet([3,2,0,'a',7,(0,0),1], facade=False) sage: A {3, 2, 0, 'a', 7, (0, 0), 1} sage: x = A.an_element() sage: x 3 sage: x.parent() {3, 2, 0, 'a', 7, (0, 0), 1} sage: A(3) < A(2) True sage: A('a') < A(7) True sage: A(3) > A(2) False sage: A(1) < A(3) False sage: A(3) == A(3) True But then, the equality comparison is always False with elements outside of the set:: sage: A(1) == 1 False sage: 1 == A(1) False sage: 'a' == A('a') False sage: A('a') == 'a' False Since :trac:`16280`, totally ordered sets support elements that do not inherit from :class:`sage.structure.element.Element`, whether they are facade or not:: sage: S = TotallyOrderedFiniteSet(['a','b']) sage: S('a') 'a' sage: S = TotallyOrderedFiniteSet(['a','b'], facade = False) sage: S('a') 'a' Multiple elements are automatically deleted:: sage: TotallyOrderedFiniteSet([1,1,2,1,2,2,5,4]) {1, 2, 5, 4} """ Element = TotallyOrderedFiniteSetElement @staticmethod def __classcall__(cls, iterable, facade=True): """ Standard trick to expand the iterable upon input, and guarantees unique representation, independently of the type of the iterable. See ``UniqueRepresentation``. TESTS:: sage: S1 = TotallyOrderedFiniteSet([1, 2, 3]) sage: S2 = TotallyOrderedFiniteSet((1, 2, 3)) sage: S3 = TotallyOrderedFiniteSet((x for x in range(1,4))) sage: S1 is S2 True sage: S2 is S3 True """ elements = [] seen = set() for x in iterable: if x not in seen: elements.append(x) seen.add(x) return super(FiniteEnumeratedSet, cls).__classcall__( cls, tuple(elements), facade) def __init__(self, elements, facade=True): """ Initialize ``self``. TESTS:: sage: TestSuite(TotallyOrderedFiniteSet([1,2,3])).run() sage: TestSuite(TotallyOrderedFiniteSet([1,2,3],facade=False)).run() sage: TestSuite(TotallyOrderedFiniteSet([1,3,2],facade=False)).run() sage: TestSuite(TotallyOrderedFiniteSet([])).run() """ Parent.__init__(self, facade = facade, category = (Posets(),FiniteEnumeratedSets())) self._elements = elements if facade: self._facade_elements = None else: self._facade_elements = self._elements self._elements = [self.element_class(self,x) for x in elements] def _element_constructor_(self, data): r""" Build an element of that set from ``data``. EXAMPLES:: sage: S1 = TotallyOrderedFiniteSet([1,2,3]) sage: x = S1(1); x # indirect doctest 1 sage: x.parent() Integer Ring sage: S2 = TotallyOrderedFiniteSet([3,2,1], facade=False) sage: y = S2(1); y # indirect doctest 1 sage: y.parent() {3, 2, 1} sage: y in S2 True sage: S2(y) is y True """ if self._facade_elements is None: return FiniteEnumeratedSet._element_constructor_(self, data) try: i = self._facade_elements.index(data) except ValueError: raise ValueError("%s not in %s"%(data, self)) return self._elements[i] def le(self, x, y): r""" Return ``True`` if `x \le y` for the order of ``self``. EXAMPLES:: sage: T = TotallyOrderedFiniteSet([1,3,2], facade=False) sage: T1, T3, T2 = T.list() sage: T.le(T1,T3) True sage: T.le(T3,T2) True """ try: return self._elements.index(x) <= self._elements.index(y) except Exception: raise ValueError("arguments must be elements of the set")
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/sets/totally_ordered_finite_set.py
0.875528
0.555676
totally_ordered_finite_set.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 from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets 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, category=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) and category is None: return X elif X in Sets().Finite(): return Set_object_enumerated(X, category=category) else: return Set_object(X, category=category) 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, category=category) else: return Set_object_enumerated(X, category=category) 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 infinite 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() if isinstance(X, CategoryObject): if X in Sets().Finite(): category = category.Finite() elif X in Sets().Infinite(): category = category.Infinite() if X in Sets().Enumerated(): category = category.Enumerated() 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 self in Sets().Infinite(): return sage.rings.infinity.infinity 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 return super().cardinality() 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 """ if self in Sets().Finite(): return True if self in Sets().Infinite(): return False 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, category=None): 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 enumerated 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=FiniteEnumeratedSets().or_subcategory(category)) 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, category=None): 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, category=category) 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, category=None): 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: X.category() Category of infinite sets sage: latex(X) \Bold{Q}^{2} \cup \Bold{Z} sage: TestSuite(X).run() """ if category is None: category = Sets() if all(S in Sets().Enumerated() for S in (X, Y)): category = category.Enumerated() if any(S in Sets().Infinite() for S in (X, Y)): category = category.Infinite() elif all(S in Sets().Finite() for S in (X, Y)): category = category.Finite() Set_object_binary.__init__(self, X, Y, "union", "\\cup", category=category) 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, category=None): 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: X.category() Category of enumerated sets sage: latex(X) \Bold{Q}^{2} \cap \Bold{Z} sage: X = Set(IntegerRange(100)).intersection(Primes()) sage: X.is_finite() True sage: X.cardinality() 25 sage: X.category() Category of finite enumerated sets sage: TestSuite(X).run() sage: X = Set(Primes(), category=Sets()).intersection(Set(IntegerRange(200))) sage: X.cardinality() 46 sage: TestSuite(X).run() """ if category is None: category = Sets() if any(S in Sets().Finite() for S in (X, Y)): category = category.Finite() if any(S in Sets().Enumerated() for S in (X, Y)): category = category.Enumerated() Set_object_binary.__init__(self, X, Y, "intersection", "\\cap", category=category) 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, category=None): 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: X.category() Category of sets sage: latex(X) \Bold{Q} - \Bold{Z} sage: TestSuite(X).run() """ if category is None: category = Sets() if X in Sets().Enumerated(): category = category.Enumerated() if X in Sets().Finite(): category = category.Finite() elif X in Sets().Infinite() and Y in Sets().Finite(): category = category.Infinite() Set_object_binary.__init__(self, X, Y, "difference", "-", category=category) 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.category() Category of sets 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.category() Category of enumerated sets 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, category=None): 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: X.category() Category of sets sage: latex(X) \Bold{Q} \bigtriangleup \Bold{Z} sage: TestSuite(X).run() """ if category is None: category = Sets() if all(S in Sets().Finite() for S in (X, Y)): category = category.Finite() if all(S in Sets().Enumerated() for S in (X, Y)): category = category.Enumerated() Set_object_binary.__init__(self, X, Y, "symmetric difference", "\\bigtriangleup", category=category) 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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/sets/set.py
0.850934
0.421492
set.py
pypi
from sage.structure.parent import Parent from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets from sage.structure.unique_representation import UniqueRepresentation from sage.sets.finite_enumerated_set import FiniteEnumeratedSet from sage.rings.integer import Integer from sage.rings.integer_ring import IntegerRing from sage.rings.infinity import Infinity, MinusInfinity, PlusInfinity class IntegerRange(UniqueRepresentation, Parent): r""" The class of :class:`Integer <sage.rings.integer.Integer>` ranges Returns an enumerated set containing an arithmetic progression of integers. INPUT: - ``begin`` -- an integer, Infinity or -Infinity - ``end`` -- an integer, Infinity or -Infinity - ``step`` -- a non zero integer (default to 1) - ``middle_point`` -- an integer inside the set (default to ``None``) OUTPUT: A parent in the category :class:`FiniteEnumeratedSets() <sage.categories.finite_enumerated_sets.FiniteEnumeratedSets>` or :class:`InfiniteEnumeratedSets() <sage.categories.infinite_enumerated_sets.InfiniteEnumeratedSets>` depending on the arguments defining ``self``. ``IntegerRange(i, j)`` returns the set of `\{i, i+1, i+2, \dots , j-1\}`. ``start`` (!) defaults to 0. When ``step`` is given, it specifies the increment. The default increment is `1`. IntegerRange allows ``begin`` and ``end`` to be infinite. ``IntegerRange`` is designed to have similar interface Python range. However, whereas ``range`` accept and returns Python ``int``, ``IntegerRange`` deals with :class:`Integer <sage.rings.integer.Integer>`. If ``middle_point`` is given, then the elements are generated starting from it, in a alternating way: `\{m, m+1, m-2, m+2, m-2 \dots \}`. EXAMPLES:: sage: list(IntegerRange(5)) [0, 1, 2, 3, 4] sage: list(IntegerRange(2,5)) [2, 3, 4] sage: I = IntegerRange(2,100,5); I {2, 7, ..., 97} sage: list(I) [2, 7, 12, 17, 22, 27, 32, 37, 42, 47, 52, 57, 62, 67, 72, 77, 82, 87, 92, 97] sage: I.category() Category of facade finite enumerated sets sage: I[1].parent() Integer Ring When ``begin`` and ``end`` are both finite, ``IntegerRange(begin, end, step)`` is the set whose list of elements is equivalent to the python construction ``range(begin, end, step)``:: sage: list(IntegerRange(4,105,3)) == list(range(4,105,3)) True sage: list(IntegerRange(-54,13,12)) == list(range(-54,13,12)) True Except for the type of the numbers:: sage: type(IntegerRange(-54,13,12)[0]), type(list(range(-54,13,12))[0]) (<... 'sage.rings.integer.Integer'>, <... 'int'>) When ``begin`` is finite and ``end`` is +Infinity, ``self`` is the infinite arithmetic progression starting from the ``begin`` by step ``step``:: sage: I = IntegerRange(54,Infinity,3); I {54, 57, ...} sage: I.category() Category of facade infinite enumerated sets sage: p = iter(I) sage: (next(p), next(p), next(p), next(p), next(p), next(p)) (54, 57, 60, 63, 66, 69) sage: I = IntegerRange(54,-Infinity,-3); I {54, 51, ...} sage: I.category() Category of facade infinite enumerated sets sage: p = iter(I) sage: (next(p), next(p), next(p), next(p), next(p), next(p)) (54, 51, 48, 45, 42, 39) When ``begin`` and ``end`` are both infinite, you will have to specify the extra argument ``middle_point``. ``self`` is then defined by a point and a progression/regression setting by ``step``. The enumeration is done this way: (let us call `m` the ``middle_point``) `\{m, m+step, m-step, m+2step, m-2step, m+3step, \dots \}`:: sage: I = IntegerRange(-Infinity,Infinity,37,-12); I Integer progression containing -12 with increment 37 and bounded with -Infinity and +Infinity sage: I.category() Category of facade infinite enumerated sets sage: -12 in I True sage: -15 in I False sage: p = iter(I) sage: (next(p), next(p), next(p), next(p), next(p), next(p), next(p), next(p)) (-12, 25, -49, 62, -86, 99, -123, 136) It is also possible to use the argument ``middle_point`` for other cases, finite or infinite. The set will be the same as if you didn't give this extra argument but the enumeration will begin with this ``middle_point``:: sage: I = IntegerRange(123,-12,-14); I {123, 109, ..., -3} sage: list(I) [123, 109, 95, 81, 67, 53, 39, 25, 11, -3] sage: J = IntegerRange(123,-12,-14,25); J Integer progression containing 25 with increment -14 and bounded with 123 and -12 sage: list(J) [25, 11, 39, -3, 53, 67, 81, 95, 109, 123] Remember that, like for range, if you define a non empty set, ``begin`` is supposed to be included and ``end`` is supposed to be excluded. In the same way, when you define a set with a ``middle_point``, the ``begin`` bound will be supposed to be included and the ``end`` bound supposed to be excluded:: sage: I = IntegerRange(-100,100,10,0) sage: J = list(range(-100,100,10)) sage: 100 in I False sage: 100 in J False sage: -100 in I True sage: -100 in J True sage: list(I) [0, 10, -10, 20, -20, 30, -30, 40, -40, 50, -50, 60, -60, 70, -70, 80, -80, 90, -90, -100] .. note:: The input is normalized so that:: sage: IntegerRange(1, 6, 2) is IntegerRange(1, 7, 2) True sage: IntegerRange(1, 8, 3) is IntegerRange(1, 10, 3) True TESTS:: sage: # Some category automatic tests sage: TestSuite(IntegerRange(2,100,3)).run() sage: TestSuite(IntegerRange(564,-12,-46)).run() sage: TestSuite(IntegerRange(2,Infinity,3)).run() sage: TestSuite(IntegerRange(732,-Infinity,-13)).run() sage: TestSuite(IntegerRange(-Infinity,Infinity,3,2)).run() sage: TestSuite(IntegerRange(56,Infinity,12,80)).run() sage: TestSuite(IntegerRange(732,-12,-2743,732)).run() sage: # 20 random tests: range and IntegerRange give the same set for finite cases sage: for i in range(20): ....: begin = Integer(randint(-300,300)) ....: end = Integer(randint(-300,300)) ....: step = Integer(randint(-20,20)) ....: if step == 0: ....: step = Integer(1) ....: assert list(IntegerRange(begin, end, step)) == list(range(begin, end, step)) sage: # 20 random tests: range and IntegerRange with middle point for finite cases sage: for i in range(20): ....: begin = Integer(randint(-300,300)) ....: end = Integer(randint(-300,300)) ....: step = Integer(randint(-15,15)) ....: if step == 0: ....: step = Integer(-3) ....: I = IntegerRange(begin, end, step) ....: if I.cardinality() == 0: ....: assert len(range(begin, end, step)) == 0 ....: else: ....: TestSuite(I).run() ....: L1 = list(IntegerRange(begin, end, step, I.an_element())) ....: L2 = list(range(begin, end, step)) ....: L1.sort() ....: L2.sort() ....: assert L1 == L2 Thanks to :trac:`8543` empty integer range are allowed:: sage: TestSuite(IntegerRange(0, 5, -1)).run() """ @staticmethod def __classcall_private__(cls, begin, end=None, step=Integer(1), middle_point=None): """ TESTS:: sage: IntegerRange(2,5,0) Traceback (most recent call last): ... ValueError: IntegerRange() step argument must not be zero sage: IntegerRange(2) is IntegerRange(0, 2) True sage: IntegerRange(1.0) Traceback (most recent call last): ... TypeError: end must be Integer or Infinity, not <... 'sage.rings.real_mpfr.RealLiteral'> """ if isinstance(begin, int): begin = Integer(begin) if isinstance(end, int): end = Integer(end) if isinstance(step, int): step = Integer(step) if end is None: end = begin begin = Integer(0) # check of the arguments if not isinstance(begin, (Integer, MinusInfinity, PlusInfinity)): raise TypeError("begin must be Integer or Infinity, not %r" % type(begin)) if not isinstance(end, (Integer, MinusInfinity, PlusInfinity)): raise TypeError("end must be Integer or Infinity, not %r" % type(end)) if not isinstance(step, Integer): raise TypeError("step must be Integer, not %r" % type(step)) if step.is_zero(): raise ValueError("IntegerRange() step argument must not be zero") # If begin and end are infinite, middle_point and step will defined the set. if begin == -Infinity and end == Infinity: if middle_point is None: raise ValueError("Can't iterate over this set, please provide middle_point") # If we have a middle point, we go on the special enumeration way... if middle_point is not None: return IntegerRangeFromMiddle(begin, end, step, middle_point) if (begin == -Infinity) or (begin == Infinity): raise ValueError("Can't iterate over this set: It is impossible to begin an enumeration with plus/minus Infinity") # Check for empty sets if step > 0 and begin >= end or step < 0 and begin <= end: return IntegerRangeEmpty() if end != Infinity and end != -Infinity: # Normalize the input sgn = 1 if step > 0 else -1 end = begin+((end-begin-sgn)//(step)+1)*step return IntegerRangeFinite(begin, end, step) else: return IntegerRangeInfinite(begin, step) def _element_constructor_(self, el): """ TESTS:: sage: S = IntegerRange(1, 10, 2) sage: S(1) #indirect doctest 1 sage: S(0) #indirect doctest Traceback (most recent call last): ... ValueError: 0 not in {1, 3, 5, 7, 9} """ if el in self: if not isinstance(el,Integer): return Integer(el) return el else: raise ValueError("%s not in %s"%(el, self)) element_class = Integer class IntegerRangeEmpty(IntegerRange, FiniteEnumeratedSet): r""" A singleton class for empty integer ranges See :class:`IntegerRange` for more details. """ # Needed because FiniteEnumeratedSet.__classcall__ takes an argument. @staticmethod def __classcall__(cls, *args): """ TESTS:: sage: from sage.sets.integer_range import IntegerRangeEmpty sage: I = IntegerRangeEmpty(); I {} sage: I.category() Category of facade finite enumerated sets sage: TestSuite(I).run() sage: I(0) Traceback (most recent call last): ... ValueError: 0 not in {} """ return FiniteEnumeratedSet.__classcall__(cls, ()) class IntegerRangeFinite(IntegerRange): r""" The class of finite enumerated sets of integers defined by finite arithmetic progressions See :class:`IntegerRange` for more details. """ def __init__(self, begin, end, step=Integer(1)): r""" TESTS:: sage: I = IntegerRange(123,12,-4) sage: I.category() Category of facade finite enumerated sets sage: TestSuite(I).run() """ self._begin = begin self._end = end self._step = step Parent.__init__(self, facade = IntegerRing(), category = FiniteEnumeratedSets()) def __contains__(self, elt): r""" Returns True if ``elt`` is in ``self``. EXAMPLES:: sage: I = IntegerRange(123,12,-4) sage: 123 in I True sage: 127 in I False sage: 12 in I False sage: 13 in I False sage: 14 in I False sage: 15 in I True sage: 11 in I False """ if not isinstance(elt, Integer): try: x = Integer(elt) if x != elt: return False elt = x except (ValueError, TypeError): return False if abs(self._step).divides(Integer(elt)-self._begin): return (self._begin <= elt < self._end and self._step > 0) or \ (self._begin >= elt > self._end and self._step < 0) return False def cardinality(self): """ Return the cardinality of ``self`` EXAMPLES:: sage: IntegerRange(123,12,-4).cardinality() 28 sage: IntegerRange(-57,12,8).cardinality() 9 sage: IntegerRange(123,12,4).cardinality() 0 """ return (abs((self._end+self._step-self._begin))-1) // abs(self._step) def _repr_(self): """ EXAMPLES:: sage: IntegerRange(1,2) #indirect doctest {1} sage: IntegerRange(1,3) #indirect doctest {1, 2} sage: IntegerRange(1,5) #indirect doctest {1, 2, 3, 4} sage: IntegerRange(1,6) #indirect doctest {1, ..., 5} sage: IntegerRange(123,12,-4) #indirect doctest {123, 119, ..., 15} sage: IntegerRange(-57,1,3) #indirect doctest {-57, -54, ..., 0} """ if self.cardinality() < 6: return "{" + ", ".join(str(x) for x in self) + "}" elif self._step == 1: return "{%s, ..., %s}"%(self._begin, self._end-self._step) else: return "{%s, %s, ..., %s}"%(self._begin, self._begin+self._step, self._end-self._step) def rank(self,x): r""" EXAMPLES:: sage: I = IntegerRange(-57,36,8) sage: I.rank(23) 10 sage: I.unrank(10) 23 sage: I.rank(22) Traceback (most recent call last): ... IndexError: 22 not in self sage: I.rank(87) Traceback (most recent call last): ... IndexError: 87 not in self """ if x not in self: raise IndexError("%s not in self"%x) return Integer((x - self._begin)/self._step) def __getitem__(self, i): r""" Return the i-th element of this integer range. EXAMPLES:: sage: I = IntegerRange(1,13,5) sage: I[0], I[1], I[2] (1, 6, 11) sage: I[3] Traceback (most recent call last): ... IndexError: out of range sage: I[-1] 11 sage: I[-4] Traceback (most recent call last): ... IndexError: out of range sage: I = IntegerRange(13,1,-1) sage: l = I.list() sage: [I[i] for i in range(I.cardinality())] == l True sage: l.reverse() sage: [I[i] for i in range(-1,-I.cardinality()-1,-1)] == l True """ if isinstance(i,slice): raise NotImplementedError("not yet") if isinstance(i, int): i = Integer(i) elif not isinstance(i,Integer): raise ValueError("argument should be an integer") if i < 0: if i < -self.cardinality(): raise IndexError("out of range") n = (self._end - self._begin)//(self._step) return self._begin + (n+i)*self._step else: if i >= self.cardinality(): raise IndexError("out of range") return self._begin + i * self._step unrank = __getitem__ def __iter__(self): r""" Returns an iterator over the elements of ``self`` EXAMPLES:: sage: I = IntegerRange(123,12,-4) sage: p = iter(I) sage: [next(p) for i in range(8)] [123, 119, 115, 111, 107, 103, 99, 95] sage: I = IntegerRange(-57,12,8) sage: p = iter(I) sage: [next(p) for i in range(8)] [-57, -49, -41, -33, -25, -17, -9, -1] """ n = self._begin if self._step > 0: while n < self._end: yield n n += self._step else: while n > self._end: yield n n += self._step def _an_element_(self): r""" Returns an element of ``self``. EXAMPLES:: sage: I = IntegerRange(123,12,-4) sage: I.an_element() #indirect doctest 115 sage: I = IntegerRange(-57,12,8) sage: I.an_element() #indirect doctest -41 """ p = (self._begin + 2*self._step) if p in self: return p else: return self._begin class IntegerRangeInfinite(IntegerRange): r""" The class of infinite enumerated sets of integers defined by infinite arithmetic progressions. See :class:`IntegerRange` for more details. """ def __init__(self, begin, step=Integer(1)): r""" TESTS:: sage: I = IntegerRange(-57,Infinity,8) sage: I.category() Category of facade infinite enumerated sets sage: TestSuite(I).run() """ if not isinstance(begin, Integer): raise TypeError("begin should be Integer, not %r" % type(begin)) self._begin = begin self._step = step Parent.__init__(self, facade = IntegerRing(), category = InfiniteEnumeratedSets()) def _repr_(self): r""" TESTS:: sage: IntegerRange(123,12,-4) #indirect doctest {123, 119, ..., 15} sage: IntegerRange(-57,1,3) #indirect doctest {-57, -54, ..., 0} sage: IntegerRange(-57,Infinity,8) #indirect doctest {-57, -49, ...} sage: IntegerRange(-112,-Infinity,-13) #indirect doctest {-112, -125, ...} """ return "{%s, %s, ...}"%(self._begin, self._begin+self._step) def __contains__(self, elt): r""" Returns True if ``elt`` is in ``self``. EXAMPLES:: sage: I = IntegerRange(-57,Infinity,8) sage: -57 in I True sage: -65 in I False sage: -49 in I True sage: 743 in I True """ if not isinstance(elt, Integer): try: elt = Integer(elt) except (TypeError, ValueError): return False if abs(self._step).divides(Integer(elt)-self._begin): return (self._step > 0 and elt >= self._begin) or \ (self._step < 0 and elt <= self._begin) return False def rank(self, x): r""" EXAMPLES:: sage: I = IntegerRange(-57,Infinity,8) sage: I.rank(23) 10 sage: I.unrank(10) 23 sage: I.rank(22) Traceback (most recent call last): ... IndexError: 22 not in self """ if x not in self: raise IndexError("%s not in self"%x) return Integer((x - self._begin)/self._step) def __getitem__(self, i): r""" Returns the ``i``-th element of self. EXAMPLES:: sage: I = IntegerRange(-8,Infinity,3) sage: I.unrank(1) -5 """ if isinstance(i,slice): raise NotImplementedError("not yet") if isinstance(i, int): i = Integer(i) elif not isinstance(i,Integer): raise ValueError if i < 0: raise IndexError("out of range") else: return self._begin + i * self._step unrank = __getitem__ def __iter__(self): r""" Returns an iterator over the elements of ``self``. EXAMPLES:: sage: I = IntegerRange(-57,Infinity,8) sage: p = iter(I) sage: [next(p) for i in range(8)] [-57, -49, -41, -33, -25, -17, -9, -1] sage: I = IntegerRange(-112,-Infinity,-13) sage: p = iter(I) sage: [next(p) for i in range(8)] [-112, -125, -138, -151, -164, -177, -190, -203] """ n = self._begin while True: yield n n += self._step def _an_element_(self): r""" Returns an element of ``self``. EXAMPLES:: sage: I = IntegerRange(-57,Infinity,8) sage: I.an_element() #indirect doctest 191 sage: I = IntegerRange(-112,-Infinity,-13) sage: I.an_element() #indirect doctest -515 """ return self._begin + 31*self._step class IntegerRangeFromMiddle(IntegerRange): r""" The class of finite or infinite enumerated sets defined with an inside point, a progression and two limits. See :class:`IntegerRange` for more details. """ def __init__(self, begin, end, step=Integer(1), middle_point=Integer(1)): r""" TESTS:: sage: from sage.sets.integer_range import IntegerRangeFromMiddle sage: I = IntegerRangeFromMiddle(-100,100,10,0) sage: I.category() Category of facade finite enumerated sets sage: TestSuite(I).run() sage: I = IntegerRangeFromMiddle(Infinity,-Infinity,-37,0) sage: I.category() Category of facade infinite enumerated sets sage: TestSuite(I).run() sage: IntegerRange(0, 5, 1, -3) Traceback (most recent call last): ... ValueError: middle_point is not in the interval """ self._begin = begin self._end = end self._step = step self._middle_point = middle_point if middle_point not in self: raise ValueError("middle_point is not in the interval") if (begin != Infinity and begin != -Infinity) and \ (end != Infinity and end != -Infinity): Parent.__init__(self, facade = IntegerRing(), category = FiniteEnumeratedSets()) else: Parent.__init__(self, facade = IntegerRing(), category = InfiniteEnumeratedSets()) def _repr_(self): r""" TESTS:: sage: from sage.sets.integer_range import IntegerRangeFromMiddle sage: IntegerRangeFromMiddle(Infinity,-Infinity,-37,0) #indirect doctest Integer progression containing 0 with increment -37 and bounded with +Infinity and -Infinity sage: IntegerRangeFromMiddle(-100,100,10,0) #indirect doctest Integer progression containing 0 with increment 10 and bounded with -100 and 100 """ return "Integer progression containing %s with increment %s and bounded with %s and %s"%(self._middle_point,self._step,self._begin,self._end) def __contains__(self, elt): r""" Returns True if ``elt`` is in ``self``. EXAMPLES:: sage: from sage.sets.integer_range import IntegerRangeFromMiddle sage: I = IntegerRangeFromMiddle(-100,100,10,0) sage: -110 in I False sage: -100 in I True sage: 30 in I True sage: 90 in I True sage: 100 in I False """ if not isinstance(elt, Integer): try: elt = Integer(elt) except (TypeError, ValueError): return False if abs(self._step).divides(Integer(elt)-self._middle_point): return (self._begin <= elt and elt < self._end) or \ (self._begin >= elt and elt > self._end) return False def next(self, elt): r""" Return the next element of ``elt`` in ``self``. EXAMPLES:: sage: from sage.sets.integer_range import IntegerRangeFromMiddle sage: I = IntegerRangeFromMiddle(-100,100,10,0) sage: (I.next(0), I.next(10), I.next(-10), I.next(20), I.next(-100)) (10, -10, 20, -20, None) sage: I = IntegerRangeFromMiddle(-Infinity,Infinity,10,0) sage: (I.next(0), I.next(10), I.next(-10), I.next(20), I.next(-100)) (10, -10, 20, -20, 110) sage: I.next(1) Traceback (most recent call last): ... LookupError: 1 not in Integer progression containing 0 with increment 10 and bounded with -Infinity and +Infinity """ if elt not in self: raise LookupError('%r not in %r' % (elt, self)) n = self._middle_point if (elt <= n and self._step > 0) or (elt >= n and self._step < 0): right = 2*n-elt+self._step if right in self: return right else: left = elt-self._step if left in self: return left else: left = 2*n-elt if left in self: return left else: right = elt+self._step if right in self: return right def __iter__(self): r""" Returns an iterator over the elements of ``self``. EXAMPLES:: sage: from sage.sets.integer_range import IntegerRangeFromMiddle sage: I = IntegerRangeFromMiddle(Infinity,-Infinity,-37,0) sage: p = iter(I) sage: (next(p), next(p), next(p), next(p), next(p), next(p), next(p), next(p)) (0, -37, 37, -74, 74, -111, 111, -148) sage: I = IntegerRangeFromMiddle(-12,214,10,0) sage: p = iter(I) sage: (next(p), next(p), next(p), next(p), next(p), next(p), next(p), next(p)) (0, 10, -10, 20, 30, 40, 50, 60) """ n = self._middle_point while n is not None: yield n n = self.next(n) def _an_element_(self): r""" Returns an element of ``self``. EXAMPLES:: sage: from sage.sets.integer_range import IntegerRangeFromMiddle sage: I = IntegerRangeFromMiddle(Infinity,-Infinity,-37,0) sage: I.an_element() #indirect doctest 0 sage: I = IntegerRangeFromMiddle(-12,214,10,0) sage: I.an_element() #indirect doctest 0 """ return self._middle_point
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/sets/integer_range.py
0.916025
0.649162
integer_range.py
pypi
from sage.sets.integer_range import IntegerRangeInfinite from sage.rings.integer import Integer class PositiveIntegers(IntegerRangeInfinite): r""" The enumerated set of positive integers. To fix the ideas, we mean `\{1, 2, 3, 4, 5, \dots \}`. This class implements the set of positive integers, as an enumerated set (see :class:`InfiniteEnumeratedSets <sage.categories.infinite_enumerated_sets.InfiniteEnumeratedSets>`). This set is an integer range set. The construction is therefore done by IntegerRange (see :class:`IntegerRange <sage.sets.integer_range.IntegerRange>`). EXAMPLES:: sage: PP = PositiveIntegers() sage: PP Positive integers sage: PP.cardinality() +Infinity sage: TestSuite(PP).run() sage: PP.list() Traceback (most recent call last): ... NotImplementedError: cannot list an infinite set sage: it = iter(PP) sage: (next(it), next(it), next(it), next(it), next(it)) (1, 2, 3, 4, 5) sage: PP.first() 1 TESTS:: sage: TestSuite(PositiveIntegers()).run() """ def __init__(self): r""" EXAMPLES:: sage: PP = PositiveIntegers() sage: PP.category() Category of facade infinite enumerated sets """ IntegerRangeInfinite.__init__(self, Integer(1), Integer(1)) def _repr_(self): r""" EXAMPLES:: sage: PositiveIntegers() Positive integers """ return "Positive integers" def an_element(self): r""" Returns an element of ``self``. EXAMPLES:: sage: PositiveIntegers().an_element() 42 """ return Integer(42) def _sympy_(self): r""" Return the SymPy set ``Naturals``. EXAMPLES:: sage: PositiveIntegers()._sympy_() Naturals """ from sympy import Naturals from sage.interfaces.sympy import sympy_init sympy_init() return Naturals
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/sets/positive_integers.py
0.93175
0.673856
positive_integers.py
pypi
from typing import Iterator from sage.categories.map import is_Map from sage.categories.poor_man_map import PoorManMap from sage.categories.sets_cat import Sets from sage.categories.enumerated_sets import EnumeratedSets from sage.misc.cachefunc import cached_method from sage.rings.infinity import Infinity from sage.rings.integer import Integer from sage.modules.free_module import FreeModule from sage.structure.element import Expression from sage.structure.parent import Parent, is_Parent from .set import Set_base, Set_add_sub_operators, Set_boolean_operators class ImageSubobject(Parent): r""" The subset defined as the image of another set under a fixed map. Let `f: X \to Y` be a function. Then the image of `f` is defined as .. MATH:: \{ f(x) | x \in X \} \subseteq Y. INPUT: - ``map`` -- a function - ``domain_subset`` -- the set `X`; optional if `f` has a domain - ``is_injective`` -- whether the ``map`` is injective: - ``None`` (default): infer from ``map`` or default to ``False`` - ``False``: do not assume that ``map`` is injective - ``True``: ``map`` is known to be injective - ``"check"``: raise an error when ``map`` is not injective - ``inverse`` -- a function (optional); a map from `f(X)` to `X` EXAMPLES:: sage: import itertools sage: from sage.sets.image_set import ImageSubobject sage: D = ZZ sage: I = ImageSubobject(abs, ZZ, is_injective='check') sage: list(itertools.islice(I, 10)) Traceback (most recent call last): ... ValueError: The map <built-in function abs> from Integer Ring is not injective: 1 """ def __init__(self, map, domain_subset, *, category=None, is_injective=None, inverse=None): """ Initialize ``self``. EXAMPLES:: sage: M = CombinatorialFreeModule(ZZ, [0,1,2,3]) sage: R.<x,y> = QQ[] sage: H = Hom(M, R, category=Sets()) sage: f = H(lambda v: v[0]*x + v[1]*(x^2-y) + v[2]^2*(y+2) + v[3] - v[0]^2) sage: Im = f.image() sage: TestSuite(Im).run(skip=['_test_an_element', '_test_pickling', ....: '_test_some_elements', '_test_elements']) """ if not is_Parent(domain_subset): from sage.sets.set import Set domain_subset = Set(domain_subset) if not is_Map(map) and not isinstance(map, PoorManMap): map_name = f"The map {map}" if isinstance(map, Expression) and map.is_callable(): domain = map.parent().base() if len(map.arguments()) != 1: domain = FreeModule(domain, len(map.arguments())) function = map def map(arg): return function(*arg) else: domain = domain_subset map = PoorManMap(map, domain, name=map_name) if is_Map(map): map_category = map.category_for() if is_injective is None: try: is_injective = map.is_injective() except NotImplementedError: is_injective = False else: map_category = Sets() if is_injective is None: is_injective = False if category is None: category = map_category._meet_(domain_subset.category()) category = category.Subobjects() if domain_subset in Sets().Finite() or map.codomain() in Sets().Finite(): category = category.Finite() elif is_injective and domain_subset in Sets.Infinite(): category = category.Infinite() if domain_subset in EnumeratedSets(): category = category & EnumeratedSets() Parent.__init__(self, category=category) self._map = map self._inverse = inverse self._domain_subset = domain_subset self._is_injective = is_injective def _element_constructor_(self, x): """ EXAMPLES:: sage: import itertools sage: from sage.sets.image_set import ImageSubobject sage: D = ZZ sage: I = ImageSubobject(lambda x: 2 * x, ZZ, inverse=lambda x: x/2) sage: I(8/2) 4 sage: _.parent() Integer Ring sage: I(10/2) Traceback (most recent call last): ... ValueError: 5 is not in Image of Integer Ring by The map <function <lambda> at ...> from Integer Ring sage: 6 in I True sage: 7 in I False """ # Same as ImageManifoldSubset.__contains__ codomain = self._map.codomain() if codomain is not None and x not in codomain: raise ValueError(f"{x} is not in {self}") if self._inverse is not None: preimage = self._inverse(x) if preimage not in self._domain_subset: raise ValueError(f"{x} is not in {self}") preimage = self._map.domain()(preimage) y = self._map(preimage) if y == x: return y raise ValueError(f"{x} is not in {self}") raise NotImplementedError def ambient(self): """ Return the ambient set of ``self``, which is the codomain of the defining map. EXAMPLES:: sage: M = CombinatorialFreeModule(QQ, [0, 1, 2, 3]) sage: R.<x,y> = ZZ[] sage: H = Hom(M, R, category=Sets()) sage: f = H(lambda v: floor(v[0])*x + ceil(v[3] - v[0]^2)) sage: Im = f.image() sage: Im.ambient() is R True sage: P = Partitions(3).map(attrcall('conjugate')) sage: P.ambient() is None True sage: R = Permutations(10).map(attrcall('reduced_word')) sage: R.ambient() is None True """ return self._map.codomain() def lift(self, x): r""" Return the lift ``x`` to the ambient space, which is ``x``. EXAMPLES:: sage: M = CombinatorialFreeModule(QQ, [0, 1, 2, 3]) sage: R.<x,y> = ZZ[] sage: H = Hom(M, R, category=Sets()) sage: f = H(lambda v: floor(v[0])*x + ceil(v[3] - v[0]^2)) sage: Im = f.image() sage: p = Im.lift(Im.an_element()); p 2*x - 4 sage: p.parent() is R True """ return x def retract(self, x): """ Return the retract of ``x`` from the ambient space, which is ``x``. .. WARNING:: This does not check that ``x`` is actually in the image. EXAMPLES:: sage: M = CombinatorialFreeModule(QQ, [0, 1, 2, 3]) sage: R.<x,y> = ZZ[] sage: H = Hom(M, R, category=Sets()) sage: f = H(lambda v: floor(v[0])*x + ceil(v[3] - v[0]^2)) sage: Im = f.image() sage: p = 2 * x - 4 sage: Im.retract(p).parent() Multivariate Polynomial Ring in x, y over Integer Ring """ return x def _repr_(self) -> str: r""" TESTS:: sage: Partitions(3).map(attrcall('conjugate')) Image of Partitions of the integer 3 by The map *.conjugate() from Partitions of the integer 3 """ return f"Image of {self._domain_subset} by {self._map}" @cached_method def cardinality(self) -> Integer: r""" Return the cardinality of ``self``. EXAMPLES: Injective case (note that :meth:`~sage.categories.enumerated_sets.EnumeratedSets.ParentMethods.map` defaults to ``is_injective=True``): sage: R = Permutations(10).map(attrcall('reduced_word')) sage: R.cardinality() 3628800 sage: Evens = ZZ.map(lambda x: 2 * x) sage: Evens.cardinality() +Infinity Non-injective case:: sage: Z7 = Set(range(7)) sage: from sage.sets.image_set import ImageSet sage: Z4711 = ImageSet(lambda x: x**4 % 11, Z7, is_injective=False) sage: Z4711.cardinality() 6 sage: Squares = ImageSet(lambda x: x^2, ZZ, is_injective=False, ....: category=Sets().Infinite()) sage: Squares.cardinality() +Infinity sage: Mod2 = ZZ.map(lambda x: x % 2, is_injective=False) sage: Mod2.cardinality() Traceback (most recent call last): ... NotImplementedError: cannot determine cardinality of a non-injective image of an infinite set """ domain_cardinality = self._domain_subset.cardinality() if self._is_injective and self._is_injective != 'check': return domain_cardinality if self in Sets().Infinite(): return Infinity if domain_cardinality == Infinity: raise NotImplementedError('cannot determine cardinality of a non-injective image of an infinite set') # Fallback like EnumeratedSets.ParentMethods.__len__ return Integer(len(list(iter(self)))) def __iter__(self) -> Iterator: r""" Return an iterator over the elements of ``self``. EXAMPLES:: sage: P = Partitions() sage: H = Hom(P, ZZ) sage: f = H(ZZ.sum) sage: X = f.image() sage: it = iter(X) sage: [next(it) for _ in range(5)] [0, 1, 2, 3, 4] """ if self._is_injective and self._is_injective != 'check': for x in self._domain_subset: yield self._map(x) else: visited = set() for x in self._domain_subset: y = self._map(x) if y in visited: if self._is_injective == 'check': raise ValueError(f'{self._map} is not injective: {y}') continue visited.add(y) yield y def _an_element_(self): r""" Return an element of this set. EXAMPLES:: sage: R = SymmetricGroup(10).map(attrcall('reduced_word')) sage: R.an_element() [9, 8, 7, 6, 5, 4, 3, 2] """ domain_element = self._domain_subset.an_element() return self._map(domain_element) def _sympy_(self): r""" Return an instance of a subclass of SymPy ``Set`` corresponding to ``self``. EXAMPLES:: sage: from sage.sets.image_set import ImageSet sage: S = ImageSet(sin, RealSet.open(0, pi/4)); S Image of (0, 1/4*pi) by The map sin from (0, 1/4*pi) sage: S._sympy_() ImageSet(Lambda(x, sin(x)), Interval.open(0, pi/4)) """ from sympy import imageset try: sympy_map = self._map._sympy_() except AttributeError: sympy_map = self._map return imageset(sympy_map, self._domain_subset._sympy_()) class ImageSet(ImageSubobject, Set_base, Set_add_sub_operators, Set_boolean_operators): r""" Image of a set by a map. EXAMPLES:: sage: from sage.sets.image_set import ImageSet Symbolics:: sage: ImageSet(sin, RealSet.open(0, pi/4)) Image of (0, 1/4*pi) by The map sin from (0, 1/4*pi) sage: _.an_element() 1/2*sqrt(-sqrt(2) + 2) sage: sos(x,y) = x^2 + y^2; sos (x, y) |--> x^2 + y^2 sage: ImageSet(sos, ZZ^2) Image of Ambient free module of rank 2 over the principal ideal domain Integer Ring by The map (x, y) |--> x^2 + y^2 from Vector space of dimension 2 over Symbolic Ring sage: _.an_element() 1 sage: ImageSet(sos, Set([(3, 4), (3, -4)])) Image of {...(3, -4)...} by The map (x, y) |--> x^2 + y^2 from Vector space of dimension 2 over Symbolic Ring sage: _.an_element() 25 """ pass
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/sets/image_set.py
0.895486
0.414662
image_set.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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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://trac.sagemath.org/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/features/join_feature.py
0.875195
0.580352
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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/features/graph_generators.py
0.829803
0.513425
graph_generators.py
pypi
r""" A catalog of normal form games This allows us to construct common games directly:: sage: g = game_theory.normal_form_games.PrisonersDilemma() sage: g Prisoners dilemma - Normal Form Game with the following utilities: ... We can then immediately obtain the Nash equilibrium for this game:: sage: g.obtain_nash() [[(0, 1), (0, 1)]] When we test whether the game is actually the one in question, sometimes we will build a dictionary to test it, since the printed representation can be platform-dependent, like so:: sage: d = {(0, 0): [-2, -2], (0, 1): [-5, 0], (1, 0): [0, -5], (1, 1): [-4, -4]} sage: g == d True The docstrings give an interpretation of each game. More information is available in the following references: REFERENCES: - [Ba1994]_ - [Cre2003]_ - [McM1992]_ - [Sky2003]_ - [Wat2003]_ - [Web2007]_ AUTHOR: - James Campbell and Vince Knight (06-2014) """ from sage.game_theory.normal_form_game import NormalFormGame def PrisonersDilemma(R=-2, P=-4, S=-5, T=0): r""" Return a Prisoners dilemma game. Assume two thieves have been caught by the police and separated for questioning. If both thieves cooperate and do not divulge any information they will each get a short sentence. If one defects he/she is offered a deal while the other thief will get a long sentence. If they both defect they both get a medium length sentence. This can be modeled as a normal form game using the following two matrices [Web2007]_: .. MATH:: A = \begin{pmatrix} R&S\\ T&P\\ \end{pmatrix} B = \begin{pmatrix} R&T\\ S&P\\ \end{pmatrix} Where `T > R > P > S`. - `R` denotes the reward received for cooperating. - `S` denotes the 'sucker' utility. - `P` denotes the utility for punishing the other player. - `T` denotes the temptation payoff. An often used version [Web2007]_ is the following: .. MATH:: A = \begin{pmatrix} -2&-5\\ 0&-4\\ \end{pmatrix} B = \begin{pmatrix} -2&0\\ -5&-4\\ \end{pmatrix} There is a single Nash equilibrium for this at which both thieves defect. This can be implemented in Sage using the following:: sage: g = game_theory.normal_form_games.PrisonersDilemma() sage: g Prisoners dilemma - Normal Form Game with the following utilities: ... sage: d = {(0, 0): [-2, -2], (0, 1): [-5, 0], (1, 0): [0, -5], ....: (1, 1): [-4, -4]} sage: g == d True sage: g.obtain_nash() [[(0, 1), (0, 1)]] Note that we can pass other values of R, P, S, T:: sage: g = game_theory.normal_form_games.PrisonersDilemma(R=-1, P=-2, S=-3, T=0) sage: g Prisoners dilemma - Normal Form Game with the following utilities:... sage: d = {(0, 1): [-3, 0], (1, 0): [0, -3], ....: (0, 0): [-1, -1], (1, 1): [-2, -2]} sage: g == d True sage: g.obtain_nash() [[(0, 1), (0, 1)]] If we pass values that fail the defining requirement: `T > R > P > S` we get an error message:: sage: g = game_theory.normal_form_games.PrisonersDilemma(R=-1, P=-2, S=0, T=5) Traceback (most recent call last): ... TypeError: the input values for a Prisoners Dilemma must be of the form T > R > P > S """ if not (T > R > P > S): raise TypeError("the input values for a Prisoners Dilemma must be of the form T > R > P > S") from sage.matrix.constructor import matrix A = matrix([[R, S], [T, P]]) g = NormalFormGame([A, A.transpose()]) g.rename('Prisoners dilemma - ' + repr(g)) return g def CoordinationGame(A=10, a=5, B=0, b=0, C=0, c=0, D=5, d=10): r""" Return a 2 by 2 Coordination Game. A coordination game is a particular type of game where the pure Nash equilibrium is for the players to pick the same strategies [Web2007]_. In general these are represented as a normal form game using the following two matrices: .. MATH:: A = \begin{pmatrix} A&C\\ B&D\\ \end{pmatrix} B = \begin{pmatrix} a&c\\ b&d\\ \end{pmatrix} Where `A > B, D > C` and `a > c, d > b`. An often used version is the following: .. MATH:: A = \begin{pmatrix} 10&0\\ 0&5\\ \end{pmatrix} B = \begin{pmatrix} 5&0\\ 0&10\\ \end{pmatrix} This is the default version of the game created by this function:: sage: g = game_theory.normal_form_games.CoordinationGame() sage: g Coordination game - Normal Form Game with the following utilities: ... sage: d = {(0, 1): [0, 0], (1, 0): [0, 0], ....: (0, 0): [10, 5], (1, 1): [5, 10]} sage: g == d True There are two pure Nash equilibria and one mixed:: sage: g.obtain_nash() [[(0, 1), (0, 1)], [(2/3, 1/3), (1/3, 2/3)], [(1, 0), (1, 0)]] We can also pass different values of the input parameters:: sage: g = game_theory.normal_form_games.CoordinationGame(A=9, a=6, ....: B=2, b=1, C=0, c=1, D=4, d=11) sage: g Coordination game - Normal Form Game with the following utilities: ... sage: d ={(0, 1): [0, 1], (1, 0): [2, 1], ....: (0, 0): [9, 6], (1, 1): [4, 11]} sage: g == d True sage: g.obtain_nash() [[(0, 1), (0, 1)], [(2/3, 1/3), (4/11, 7/11)], [(1, 0), (1, 0)]] Note that an error is returned if the defining inequalities are not obeyed `A > B, D > C` and `a > c, d > b`:: sage: g = game_theory.normal_form_games.CoordinationGame(A=9, a=6, ....: B=0, b=1, C=2, c=10, D=4, d=11) Traceback (most recent call last): ... TypeError: the input values for a Coordination game must be of the form A > B, D > C, a > c and d > b """ if not (A > B and D > C and a > c and d > b): raise TypeError("the input values for a Coordination game must be of the form A > B, D > C, a > c and d > b") from sage.matrix.constructor import matrix A = matrix([[A, C], [B, D]]) B = matrix([[a, c], [b, d]]) g = NormalFormGame([A, B]) g.rename('Coordination game - ' + repr(g)) return g def BattleOfTheSexes(): r""" Return a Battle of the Sexes game. Consider two payers: Amy and Bob. Amy prefers to play video games and Bob prefers to watch a movie. They both however want to spend their evening together. This can be modeled as a normal form game using the following two matrices [Web2007]_: .. MATH:: A = \begin{pmatrix} 3&1\\ 0&2\\ \end{pmatrix} B = \begin{pmatrix} 2&1\\ 0&3\\ \end{pmatrix} This is a particular type of Coordination Game. There are three Nash equilibria: 1. Amy and Bob both play video games; 2. Amy and Bob both watch a movie; 3. Amy plays video games 75% of the time and Bob watches a movie 75% of the time. This can be implemented in Sage using the following:: sage: g = game_theory.normal_form_games.BattleOfTheSexes() sage: g Battle of the sexes - Coordination game - Normal Form Game with the following utilities: ... sage: d = {(0, 1): [1, 1], (1, 0): [0, 0], (0, 0): [3, 2], (1, 1): [2, 3]} sage: g == d True sage: g.obtain_nash() [[(0, 1), (0, 1)], [(3/4, 1/4), (1/4, 3/4)], [(1, 0), (1, 0)]] """ g = CoordinationGame(A=3, a=2, B=0, b=0, C=1, c=1, D=2, d=3) g.rename('Battle of the sexes - ' + repr(g)) return g def StagHunt(): r""" Return a Stag Hunt game. Assume two friends go out on a hunt. Each can individually choose to hunt a stag or hunt a hare. Each player must choose an action without knowing the choice of the other. If an individual hunts a stag, he must have the cooperation of his partner in order to succeed. An individual can get a hare by himself, but a hare is worth less than a stag. This can be modeled as a normal form game using the following two matrices [Sky2003]_: .. MATH:: A = \begin{pmatrix} 5&0\\ 4&2\\ \end{pmatrix} B = \begin{pmatrix} 5&4\\ 0&2\\ \end{pmatrix} This is a particular type of Coordination Game. There are three Nash equilibria: 1. Both friends hunting the stag. 2. Both friends hunting the hare. 3. Both friends hunting the stag 2/3rds of the time. This can be implemented in Sage using the following:: sage: g = game_theory.normal_form_games.StagHunt() sage: g Stag hunt - Coordination game - Normal Form Game with the following utilities: ... sage: d = {(0, 1): [0, 4], (1, 0): [4, 0], ....: (0, 0): [5, 5], (1, 1): [2, 2]} sage: g == d True sage: g.obtain_nash() [[(0, 1), (0, 1)], [(2/3, 1/3), (2/3, 1/3)], [(1, 0), (1, 0)]] """ g = CoordinationGame(A=5, a=5, B=4, b=0, C=0, c=4, D=2, d=2) g.rename('Stag hunt - ' + repr(g)) return g def AntiCoordinationGame(A=3, a=3, B=5, b=1, C=1, c=5, D=0, d=0): r""" Return a 2 by 2 AntiCoordination Game. An anti coordination game is a particular type of game where the pure Nash equilibria is for the players to pick different strategies. In general these are represented as a normal form game using the following two matrices: .. MATH:: A = \begin{pmatrix} A&C\\ B&D\\ \end{pmatrix} B = \begin{pmatrix} a&c\\ b&d\\ \end{pmatrix} Where `A < B, D < C` and `a < c, d < b`. An often used version is the following: .. MATH:: A = \begin{pmatrix} 3&1\\ 5&0\\ \end{pmatrix} B = \begin{pmatrix} 3&5\\ 1&0\\ \end{pmatrix} This is the default version of the game created by this function:: sage: g = game_theory.normal_form_games.AntiCoordinationGame() sage: g Anti coordination game - Normal Form Game with the following utilities: ... sage: d ={(0, 1): [1, 5], (1, 0): [5, 1], ....: (0, 0): [3, 3], (1, 1): [0, 0]} sage: g == d True There are two pure Nash equilibria and one mixed:: sage: g.obtain_nash() [[(0, 1), (1, 0)], [(1/3, 2/3), (1/3, 2/3)], [(1, 0), (0, 1)]] We can also pass different values of the input parameters:: sage: g = game_theory.normal_form_games.AntiCoordinationGame(A=2, a=3, ....: B=4, b=2, C=2, c=8, D=1, d=0) sage: g Anti coordination game - Normal Form Game with the following utilities: ... sage: d ={(0, 1): [2, 8], (1, 0): [4, 2], ....: (0, 0): [2, 3], (1, 1): [1, 0]} sage: g == d True sage: g.obtain_nash() [[(0, 1), (1, 0)], [(2/7, 5/7), (1/3, 2/3)], [(1, 0), (0, 1)]] Note that an error is returned if the defining inequality is not obeyed `A > B, D > C` and `a > c, d > b`:: sage: g = game_theory.normal_form_games.AntiCoordinationGame(A=8, a=3, ....: B=4, b=2, C=2, c=8, D=1, d=0) Traceback (most recent call last): ... TypeError: the input values for an Anti coordination game must be of the form A < B, D < C, a < c and d < b """ if not (A < B and D < C and a < c and d < b): raise TypeError("the input values for an Anti coordination game must be of the form A < B, D < C, a < c and d < b") from sage.matrix.constructor import matrix A = matrix([[A, C], [B, D]]) B = matrix([[a, c], [b, d]]) g = NormalFormGame([A, B]) g.rename('Anti coordination game - ' + repr(g)) return g def HawkDove(v=2, c=3): r""" Return a Hawk Dove game. Suppose two birds of prey must share a limited resource `v`. The birds can act like a hawk or a dove. - If a dove meets a hawk, the hawk takes the resources. - If two doves meet they share the resources. - If two hawks meet, one will win (with equal expectation) and take the resources while the other will suffer a cost of `c` where `c>v`. This can be modeled as a normal form game using the following two matrices [Web2007]_: .. MATH:: A = \begin{pmatrix} v/2-c&v\\ 0&v/2\\ \end{pmatrix} B = \begin{pmatrix} v/2-c&0\\ v&v/2\\ \end{pmatrix} Here are the games with the default values of `v=2` and `c=3`. .. MATH:: A = \begin{pmatrix} -2&2\\ 0&1\\ \end{pmatrix} B = \begin{pmatrix} -2&0\\ 2&1\\ \end{pmatrix} This is a particular example of an anti coordination game. There are three Nash equilibria: 1. One bird acts like a Hawk and the other like a Dove. 2. Both birds mix being a Hawk and a Dove This can be implemented in Sage using the following:: sage: g = game_theory.normal_form_games.HawkDove() sage: g Hawk-Dove - Anti coordination game - Normal Form Game with the following utilities: ... sage: d ={(0, 1): [2, 0], (1, 0): [0, 2], ....: (0, 0): [-2, -2], (1, 1): [1, 1]} sage: g == d True sage: g.obtain_nash() [[(0, 1), (1, 0)], [(1/3, 2/3), (1/3, 2/3)], [(1, 0), (0, 1)]] sage: g = game_theory.normal_form_games.HawkDove(v=1, c=3) sage: g Hawk-Dove - Anti coordination game - Normal Form Game with the following utilities: ... sage: d ={(0, 1): [1, 0], (1, 0): [0, 1], ....: (0, 0): [-5/2, -5/2], (1, 1): [1/2, 1/2]} sage: g == d True sage: g.obtain_nash() [[(0, 1), (1, 0)], [(1/6, 5/6), (1/6, 5/6)], [(1, 0), (0, 1)]] Note that an error is returned if the defining inequality is not obeyed `c < v`: sage: g = game_theory.normal_form_games.HawkDove(v=5, c=1) Traceback (most recent call last): ... TypeError: the input values for a Hawk Dove game must be of the form c > v """ if not (c > v): raise TypeError("the input values for a Hawk Dove game must be of the form c > v") g = AntiCoordinationGame(A=v/2-c, a=v/2-c, B=0, b=v, C=v, c=0, D=v/2, d=v/2) g.rename('Hawk-Dove - ' + repr(g)) return g def Pigs(): r""" Return a Pigs game. Consider two pigs. One dominant pig and one subservient pig. These pigs share a pen. There is a lever in the pen that delivers 6 units of food but if either pig pushes the lever it will take them a little while to get to the food as well as cost them 1 unit of food. If the dominant pig pushes the lever, the subservient pig has some time to eat two thirds of the food before being pushed out of the way. If the subservient pig pushes the lever, the dominant pig will eat all the food. Finally if both pigs go to push the lever the subservient pig will be able to eat a third of the food (and they will also both lose 1 unit of food). This can be modeled as a normal form game using the following two matrices [McM1992]_ (we assume that the dominant pig's utilities are given by `A`): .. MATH:: A = \begin{pmatrix} 3&1\\ 6&0\\ \end{pmatrix} B = \begin{pmatrix} 1&4\\ -1&0\\ \end{pmatrix} There is a single Nash equilibrium at which the dominant pig pushes the lever and the subservient pig does not. This can be implemented in Sage using the following:: sage: g = game_theory.normal_form_games.Pigs() sage: g Pigs - Normal Form Game with the following utilities: ... sage: d ={(0, 1): [1, 4], (1, 0): [6, -1], ....: (0, 0): [3, 1], (1, 1): [0, 0]} sage: g == d True sage: g.obtain_nash() [[(1, 0), (0, 1)]] """ from sage.matrix.constructor import matrix A = matrix([[3, 1], [6, 0]]) B = matrix([[1, 4], [-1, 0]]) g = NormalFormGame([A, B]) g.rename('Pigs - ' + repr(g)) return g def MatchingPennies(): r""" Return a Matching Pennies game. Consider two players who can choose to display a coin either Heads facing up or Tails facing up. If both players show the same face then player 1 wins, if not then player 2 wins. This can be modeled as a zero sum normal form game with the following matrix [Web2007]_: .. MATH:: A = \begin{pmatrix} 1&-1\\ -1&1\\ \end{pmatrix} There is a single Nash equilibria at which both players randomly (with equal probability) pick heads or tails. This can be implemented in Sage using the following:: sage: g = game_theory.normal_form_games.MatchingPennies() sage: g Matching pennies - Normal Form Game with the following utilities: ... sage: d ={(0, 1): [-1, 1], (1, 0): [-1, 1], ....: (0, 0): [1, -1], (1, 1): [1, -1]} sage: g == d True sage: g.obtain_nash('enumeration') [[(1/2, 1/2), (1/2, 1/2)]] """ from sage.matrix.constructor import matrix A = matrix([[1, -1], [-1, 1]]) g = NormalFormGame([A]) g.rename('Matching pennies - ' + repr(g)) return g def RPS(): r""" Return a Rock-Paper-Scissors game. Rock-Paper-Scissors is a zero sum game usually played between two players where each player simultaneously forms one of three shapes with an outstretched hand.The game has only three possible outcomes other than a tie: a player who decides to play rock will beat another player who has chosen scissors ("rock crushes scissors") but will lose to one who has played paper ("paper covers rock"); a play of paper will lose to a play of scissors ("scissors cut paper"). If both players throw the same shape, the game is tied and is usually immediately replayed to break the tie. This can be modeled as a zero sum normal form game with the following matrix [Web2007]_: .. MATH:: A = \begin{pmatrix} 0 & -1 & 1\\ 1 & 0 & -1\\ -1 & 1 & 0\\ \end{pmatrix} This can be implemented in Sage using the following:: sage: g = game_theory.normal_form_games.RPS() sage: g Rock-Paper-Scissors - Normal Form Game with the following utilities: ... sage: d = {(0, 1): [-1, 1], (1, 2): [-1, 1], (0, 0): [0, 0], ....: (2, 1): [1, -1], (1, 1): [0, 0], (2, 0): [-1, 1], ....: (2, 2): [0, 0], (1, 0): [1, -1], (0, 2): [1, -1]} sage: g == d True sage: g.obtain_nash('enumeration') [[(1/3, 1/3, 1/3), (1/3, 1/3, 1/3)]] """ from sage.matrix.constructor import matrix A = matrix([[0, -1, 1], [1, 0, -1], [-1, 1, 0]]) g = NormalFormGame([A]) g.rename('Rock-Paper-Scissors - ' + repr(g)) return g def RPSLS(): r""" Return a Rock-Paper-Scissors-Lizard-Spock game. `Rock-Paper-Scissors-Lizard-Spock <http://www.samkass.com/theories/RPSSL.html>`_ is an extension of Rock-Paper-Scissors. It is a zero sum game usually played between two players where each player simultaneously forms one of three shapes with an outstretched hand. This game became popular after appearing on the television show 'Big Bang Theory'. The rules for the game can be summarised as follows: - Scissors cuts Paper - Paper covers Rock - Rock crushes Lizard - Lizard poisons Spock - Spock smashes Scissors - Scissors decapitates Lizard - Lizard eats Paper - Paper disproves Spock - Spock vaporizes Rock - (and as it always has) Rock crushes Scissors This can be modeled as a zero sum normal form game with the following matrix: .. MATH:: A = \begin{pmatrix} 0 & -1 & 1 & 1 & -1\\ 1 & 0 & -1 & -1 & 1\\ -1 & 1 & 0 & 1 & -1\\ -1 & 1 & -1 & 0 & 1\\ 1 & -1 & 1 & -1 & 0\\ \end{pmatrix} This can be implemented in Sage using the following:: sage: g = game_theory.normal_form_games.RPSLS() sage: g Rock-Paper-Scissors-Lizard-Spock - Normal Form Game with the following utilities: ... sage: d = {(1, 3): [-1, 1], (3, 0): [-1, 1], (2, 1): [1, -1], ....: (0, 3): [1, -1], (4, 0): [1, -1], (1, 2): [-1, 1], ....: (3, 3): [0, 0], (4, 4): [0, 0], (2, 2): [0, 0], ....: (4, 1): [-1, 1], (1, 1): [0, 0], (3, 2): [-1, 1], ....: (0, 0): [0, 0], (0, 4): [-1, 1], (1, 4): [1, -1], ....: (2, 3): [1, -1], (4, 2): [1, -1], (1, 0): [1, -1], ....: (0, 1): [-1, 1], (3, 1): [1, -1], (2, 4): [-1, 1], ....: (2, 0): [-1, 1], (4, 3): [-1, 1], (3, 4): [1, -1], ....: (0, 2): [1, -1]} sage: g == d True sage: g.obtain_nash('enumeration') [[(1/5, 1/5, 1/5, 1/5, 1/5), (1/5, 1/5, 1/5, 1/5, 1/5)]] """ from sage.matrix.constructor import matrix A = matrix([[0, -1, 1, 1, -1], [1, 0, -1, -1, 1], [-1, 1, 0, 1, -1], [-1, 1, -1, 0, 1], [1, -1, 1, -1, 0]]) g = NormalFormGame([A]) g.rename('Rock-Paper-Scissors-Lizard-Spock - ' + repr(g)) return g def Chicken(A=0, a=0, B=1, b=-1, C=-1, c=1, D=-10, d=-10): r""" Return a Chicken game. Consider two drivers locked in a fierce battle for pride. They drive towards a cliff and the winner is declared as the last one to swerve. If neither player swerves they will both fall off the cliff. This can be modeled as a particular type of anti coordination game using the following two matrices: .. MATH:: A = \begin{pmatrix} A&C\\ B&D\\ \end{pmatrix} B = \begin{pmatrix} a&c\\ b&d\\ \end{pmatrix} Where `A < B, D < C` and `a < c, d < b` but with the extra condition that `A > C` and `a > b`. Here are the numeric values used by default [Wat2003]_: .. MATH:: A = \begin{pmatrix} 0&-1\\ 1&-10\\ \end{pmatrix} B = \begin{pmatrix} 0&1\\ -1&-10\\ \end{pmatrix} There are three Nash equilibria: 1. The second player swerving. 2. The first player swerving. 3. Both players swerving with 1 out of 10 times. This can be implemented in Sage using the following:: sage: g = game_theory.normal_form_games.Chicken() sage: g Chicken - Anti coordination game - Normal Form Game with the following utilities: ... sage: d = {(0, 1): [-1, 1], (1, 0): [1, -1], ....: (0, 0): [0, 0], (1, 1): [-10, -10]} sage: g == d True sage: g.obtain_nash() [[(0, 1), (1, 0)], [(9/10, 1/10), (9/10, 1/10)], [(1, 0), (0, 1)]] Non default values can be passed:: sage: g = game_theory.normal_form_games.Chicken(A=0, a=0, B=2, ....: b=-1, C=-1, c=2, D=-100, d=-100) sage: g Chicken - Anti coordination game - Normal Form Game with the following utilities: ... sage: d = {(0, 1): [-1, 2], (1, 0): [2, -1], ....: (0, 0): [0, 0], (1, 1): [-100, -100]} sage: g == d True sage: g.obtain_nash() [[(0, 1), (1, 0)], [(99/101, 2/101), (99/101, 2/101)], [(1, 0), (0, 1)]] Note that an error is returned if the defining inequalities are not obeyed `B > A > C > D` and `c > a > b > d`:: sage: g = game_theory.normal_form_games.Chicken(A=8, a=3, B=4, b=2, ....: C=2, c=8, D=1, d=0) Traceback (most recent call last): ... TypeError: the input values for a game of chicken must be of the form B > A > C > D and c > a > b > d """ if not (B > A > C > D and c > a > b > d): raise TypeError("the input values for a game of chicken must be of the form B > A > C > D and c > a > b > d") g = AntiCoordinationGame(A=A, a=a, B=B, b=b, C=C, c=c, D=D, d=d) g.rename('Chicken - ' + repr(g)) return g def TravellersDilemma(max_value=10): r""" Return a Travellers dilemma game. An airline loses two suitcases belonging to two different travelers. Both suitcases happen to be identical and contain identical antiques. An airline manager tasked to settle the claims of both travelers explains that the airline is liable for a maximum of 10 per suitcase, and in order to determine an honest appraised value of the antiques the manager separates both travelers so they can't confer, and asks them to write down the amount of their value at no less than 2 and no larger than 10. He also tells them that if both write down the same number, he will treat that number as the true dollar value of both suitcases and reimburse both travelers that amount. However, if one writes down a smaller number than the other, this smaller number will be taken as the true dollar value, and both travelers will receive that amount along with a bonus/malus: 2 extra will be paid to the traveler who wrote down the lower value and a 2 deduction will be taken from the person who wrote down the higher amount. The challenge is: what strategy should both travelers follow to decide the value they should write down? This can be modeled as a normal form game using the following two matrices [Ba1994]_: .. MATH:: A = \begin{pmatrix} 10 & 7 & 6 & 5 & 4 & 3 & 2 & 1 & 0\\ 11 & 9 & 6 & 5 & 4 & 3 & 2 & 1 & 0\\ 10 & 10 & 8 & 5 & 4 & 3 & 2 & 1 & 0\\ 9 & 9 & 9 & 7 & 4 & 3 & 2 & 1 & 0\\ 8 & 8 & 8 & 8 & 6 & 3 & 2 & 1 & 0\\ 7 & 7 & 7 & 7 & 7 & 5 & 2 & 1 & 0\\ 6 & 6 & 6 & 6 & 6 & 6 & 4 & 1 & 0\\ 5 & 5 & 5 & 5 & 5 & 5 & 5 & 3 & 0\\ 4 & 4 & 4 & 4 & 4 & 4 & 4 & 4 & 2\\ \end{pmatrix} B = \begin{pmatrix} 10 & 11 & 10 & 9 & 8 & 7 & 6 & 5 & 4\\ 7 & 9 & 10 & 9 & 8 & 7 & 6 & 5 & 4\\ 6 & 6 & 8 & 9 & 8 & 7 & 6 & 5 & 4\\ 5 & 5 & 5 & 7 & 8 & 7 & 6 & 5 & 4\\ 4 & 4 & 4 & 4 & 6 & 7 & 6 & 5 & 4\\ 3 & 3 & 3 & 3 & 3 & 5 & 6 & 5 & 4\\ 2 & 2 & 2 & 2 & 2 & 2 & 4 & 5 & 4\\ 1 & 1 & 1 & 1 & 1 & 1 & 1 & 3 & 4\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 2\\ \end{pmatrix} There is a single Nash equilibrium to this game resulting in both players naming the smallest possible value. This can be implemented in Sage using the following:: sage: g = game_theory.normal_form_games.TravellersDilemma() sage: g Travellers dilemma - Normal Form Game with the following utilities: ... sage: d = {(7, 3): [5, 1], (4, 7): [1, 5], (1, 3): [5, 9], ....: (4, 8): [0, 4], (3, 0): [9, 5], (2, 8): [0, 4], ....: (8, 0): [4, 0], (7, 8): [0, 4], (5, 4): [7, 3], ....: (0, 7): [1, 5], (5, 6): [2, 6], (2, 6): [2, 6], ....: (1, 6): [2, 6], (5, 1): [7, 3], (3, 7): [1, 5], ....: (0, 3): [5, 9], (8, 5): [4, 0], (2, 5): [3, 7], ....: (5, 8): [0, 4], (4, 0): [8, 4], (1, 2): [6, 10], ....: (7, 4): [5, 1], (6, 4): [6, 2], (3, 3): [7, 7], ....: (2, 0): [10, 6], (8, 1): [4, 0], (7, 6): [5, 1], ....: (4, 4): [6, 6], (6, 3): [6, 2], (1, 5): [3, 7], ....: (8, 8): [2, 2], (7, 2): [5, 1], (3, 6): [2, 6], ....: (2, 2): [8, 8], (7, 7): [3, 3], (5, 7): [1, 5], ....: (5, 3): [7, 3], (4, 1): [8, 4], (1, 1): [9, 9], ....: (2, 7): [1, 5], (3, 2): [9, 5], (0, 0): [10, 10], ....: (6, 6): [4, 4], (5, 0): [7, 3], (7, 1): [5, 1], ....: (4, 5): [3, 7], (0, 4): [4, 8], (5, 5): [5, 5], ....: (1, 4): [4, 8], (6, 0): [6, 2], (7, 5): [5, 1], ....: (2, 3): [5, 9], (2, 1): [10, 6], (8, 7): [4, 0], ....: (6, 8): [0, 4], (4, 2): [8, 4], (1, 0): [11, 7], ....: (0, 8): [0, 4], (6, 5): [6, 2], (3, 5): [3, 7], ....: (0, 1): [7, 11], (8, 3): [4, 0], (7, 0): [5, 1], ....: (4, 6): [2, 6], (6, 7): [1, 5], (8, 6): [4, 0], ....: (5, 2): [7, 3], (6, 1): [6, 2], (3, 1): [9, 5], ....: (8, 2): [4, 0], (2, 4): [4, 8], (3, 8): [0, 4], ....: (0, 6): [2, 6], (1, 8): [0, 4], (6, 2): [6, 2], ....: (4, 3): [8, 4], (1, 7): [1, 5], (0, 5): [3, 7], ....: (3, 4): [4, 8], (0, 2): [6, 10], (8, 4): [4, 0]} sage: g == d True sage: g.obtain_nash() # optional - lrslib [[(0, 0, 0, 0, 0, 0, 0, 0, 1), (0, 0, 0, 0, 0, 0, 0, 0, 1)]] Note that this command can be used to create travellers dilemma for a different maximum value of the luggage. Below is an implementation with a maximum value of 5:: sage: g = game_theory.normal_form_games.TravellersDilemma(5) sage: g Travellers dilemma - Normal Form Game with the following utilities: ... sage: d = {(0, 1): [2, 6], (1, 2): [1, 5], (3, 2): [4, 0], ....: (0, 0): [5, 5], (3, 3): [2, 2], (3, 0): [4, 0], ....: (3, 1): [4, 0], (2, 1): [5, 1], (0, 2): [1, 5], ....: (2, 0): [5, 1], (1, 3): [0, 4], (2, 3): [0, 4], ....: (2, 2): [3, 3], (1, 0): [6, 2], (0, 3): [0, 4], ....: (1, 1): [4, 4]} sage: g == d True sage: g.obtain_nash() [[(0, 0, 0, 1), (0, 0, 0, 1)]] """ from sage.matrix.constructor import matrix from sage.functions.generalized import sign A = matrix([[min(i, j) + 2 * sign(j - i) for j in range(max_value, 1, -1)] for i in range(max_value, 1, -1)]) g = NormalFormGame([A, A.transpose()]) g.rename('Travellers dilemma - ' + repr(g)) return g
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/game_theory/catalog_normal_form_games.py
0.848722
0.724566
catalog_normal_form_games.py
pypi
from itertools import permutations, combinations from sage.misc.misc import powerset from sage.rings.integer import Integer from sage.structure.sage_object import SageObject class CooperativeGame(SageObject): r""" An object representing a co-operative game. Primarily used to compute the Shapley value, but can also provide other information. INPUT: - ``characteristic_function`` -- a dictionary containing all possible sets of players: * key - each set must be entered as a tuple. * value - a real number representing each set of players contribution EXAMPLES: The type of game that is currently implemented is referred to as a Characteristic function game. This is a game on a set of players `\Omega` that is defined by a value function `v : C \to \RR` where `C = 2^{\Omega}` is the set of all coalitions of players. Let `N := |\Omega|`. An example of such a game is shown below: .. MATH:: v(c) = \begin{cases} 0 &\text{if } c = \emptyset, \\ 6 &\text{if } c = \{1\}, \\ 12 &\text{if } c = \{2\}, \\ 42 &\text{if } c = \{3\}, \\ 12 &\text{if } c = \{1,2\}, \\ 42 &\text{if } c = \{1,3\}, \\ 42 &\text{if } c = \{2,3\}, \\ 42 &\text{if } c = \{1,2,3\}. \\ \end{cases} The function `v` can be thought of as a record of contribution of individuals and coalitions of individuals. Of interest, becomes how to fairly share the value of the grand coalition (`\Omega`)? This class allows for such an answer to be formulated by calculating the Shapley value of the game. Basic examples of how to implement a co-operative game. These functions will be used repeatedly in other examples. :: sage: integer_function = {(): 0, ....: (1,): 6, ....: (2,): 12, ....: (3,): 42, ....: (1, 2,): 12, ....: (1, 3,): 42, ....: (2, 3,): 42, ....: (1, 2, 3,): 42} sage: integer_game = CooperativeGame(integer_function) We can also use strings instead of numbers. :: sage: letter_function = {(): 0, ....: ('A',): 6, ....: ('B',): 12, ....: ('C',): 42, ....: ('A', 'B',): 12, ....: ('A', 'C',): 42, ....: ('B', 'C',): 42, ....: ('A', 'B', 'C',): 42} sage: letter_game = CooperativeGame(letter_function) Please note that keys should be tuples. ``'1, 2, 3'`` is not a valid key, neither is ``123``. The correct input would be ``(1, 2, 3)``. Similarly, for coalitions containing a single element the bracket notation (which tells Sage that it is a tuple) must be used. So ``(1)``, ``(1,)`` are correct however simply inputting `1` is not. Characteristic function games can be of various types. A characteristic function game `G = (N, v)` is monotone if it satisfies `v(C_2) \geq v(C_1)` for all `C_1 \subseteq C_2`. A characteristic function game `G = (N, v)` is superadditive if it satisfies `v(C_1 \cup C_2) \geq v(C_1) + v(C_2)` for all `C_1, C_2 \subseteq 2^{\Omega}` such that `C_1 \cap C_2 = \emptyset`. We can test if a game is monotonic or superadditive. :: sage: letter_game.is_monotone() True sage: letter_game.is_superadditive() False Instances have a basic representation that will display basic information about the game:: sage: letter_game A 3 player co-operative game It can be shown that the "fair" payoff vector, referred to as the Shapley value is given by the following formula: .. MATH:: \phi_i(G) = \frac{1}{N!} \sum_{\pi\in\Pi_n} \Delta_{\pi}^G(i), where the summation is over the permutations of the players and the marginal contributions of a player for a given permutation is given as: .. MATH:: \Delta_{\pi}^G(i) = v\bigl( S_{\pi}(i) \cup \{i\} \bigr) - v\bigl( S_{\pi}(i) \bigr) where `S_{\pi}(i)` is the set of predecessors of `i` in `\pi`, i.e. `S_{\pi}(i) = \{ j \mid \pi(i) > \pi(j) \}` (or the number of inversions of the form `(i, j)`). This payoff vector is "fair" in that it has a collection of properties referred to as: efficiency, symmetry, additivity and Null player. Some of these properties are considered in this documentation (and tests are implemented in the class) but for a good overview see [CEW2011]_. Note ([MSZ2013]_) that an equivalent formula for the Shapley value is given by: .. MATH:: \phi_i(G) = \sum_{S \subseteq \Omega} \sum_{p \in S} \frac{(|S|-1)!(N-|S|)!}{N!} \bigl( v(S) - v(S \setminus \{p\}) \bigr) = \sum_{S \subseteq \Omega} \sum_{p \in S} \frac{1}{|S|\binom{N}{|S|}} \bigl( v(S) - v(S \setminus \{p\}) \bigr). This later formulation is implemented in Sage and requires `2^N-1` calculations instead of `N!`. To compute the Shapley value in Sage is simple:: sage: letter_game.shapley_value() {'A': 2, 'B': 5, 'C': 35} The following example implements a (trivial) 10 player characteristic function game with `v(c) = |c|` for all `c \in 2^{\Omega}`. :: sage: def simple_characteristic_function(N): ....: return {tuple(coalition) : len(coalition) ....: for coalition in subsets(range(N))} sage: g = CooperativeGame(simple_characteristic_function(10)) sage: g.shapley_value() {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1} For very large games it might be worth taking advantage of the particular problem structure to calculate the Shapley value and there are also various approximation approaches to obtaining the Shapley value of a game (see [SWJ2008]_ for one such example). Implementing these would be a worthwhile development For more information about the computational complexity of calculating the Shapley value see [XP1994]_. We can test 3 basic properties of any payoff vector `\lambda`. The Shapley value (described above) is known to be the unique payoff vector that satisfies these and 1 other property not implemented here (additivity). They are: * Efficiency - `\sum_{i=1}^N \lambda_i = v(\Omega)` In other words, no value of the total coalition is lost. * The nullplayer property - If there exists an `i` such that `v(C \cup i) = v(C)` for all `C \in 2^{\Omega}` then, `\lambda_i = 0`. In other words: if a player does not contribute to any coalition then that player should receive no payoff. * Symmetry property - If `v(C \cup i) = v(C \cup j)` for all `C \in 2^{\Omega} \setminus \{i,j\}`, then `x_i = x_j`. If players contribute symmetrically then they should get the same payoff:: sage: payoff_vector = letter_game.shapley_value() sage: letter_game.is_efficient(payoff_vector) True sage: letter_game.nullplayer(payoff_vector) True sage: letter_game.is_symmetric(payoff_vector) True Any payoff vector can be passed to the game and these properties can once again be tested:: sage: payoff_vector = {'A': 0, 'C': 35, 'B': 3} sage: letter_game.is_efficient(payoff_vector) False sage: letter_game.nullplayer(payoff_vector) True sage: letter_game.is_symmetric(payoff_vector) True TESTS: Check that the order within a key does not affect other functions:: sage: letter_function = {(): 0, ....: ('A',): 6, ....: ('B',): 12, ....: ('C',): 42, ....: ('A', 'B',): 12, ....: ('C', 'A',): 42, ....: ('B', 'C',): 42, ....: ('B', 'A', 'C',): 42} sage: letter_game = CooperativeGame(letter_function) sage: letter_game.shapley_value() {'A': 2, 'B': 5, 'C': 35} sage: letter_game.is_monotone() True sage: letter_game.is_superadditive() False sage: letter_game.is_efficient({'A': 2, 'C': 35, 'B': 5}) True sage: letter_game.nullplayer({'A': 2, 'C': 35, 'B': 5}) True sage: letter_game.is_symmetric({'A': 2, 'C': 35, 'B': 5}) True Any payoff vector can be passed to the game and these properties can once again be tested. :: sage: letter_game.is_efficient({'A': 0, 'C': 35, 'B': 3}) False sage: letter_game.nullplayer({'A': 0, 'C': 35, 'B': 3}) True sage: letter_game.is_symmetric({'A': 0, 'C': 35, 'B': 3}) True """ def __init__(self, characteristic_function): r""" Initializes a co-operative game and checks the inputs. TESTS: An attempt to construct a game from an integer:: sage: int_game = CooperativeGame(4) Traceback (most recent call last): ... TypeError: characteristic function must be a dictionary This test checks that an incorrectly entered singularly tuple will be changed into a tuple. In this case ``(1)`` becomes ``(1,)``:: sage: tuple_function = {(): 0, ....: (1): 6, ....: (2,): 12, ....: (3,): 42, ....: (1, 2,): 12, ....: (1, 3,): 42, ....: (2, 3,): 42, ....: (1, 2, 3,): 42} sage: tuple_game = CooperativeGame(tuple_function) This test checks that if a key is not a tuple an error is raised:: sage: error_function = {(): 0, ....: (1,): 6, ....: (2,): 12, ....: (3,): 42, ....: 12: 12, ....: (1, 3,): 42, ....: (2, 3,): 42, ....: (1, 2, 3,): 42} sage: error_game = CooperativeGame(error_function) Traceback (most recent call last): ... TypeError: key must be a tuple A test to ensure that the characteristic function is the power set of the grand coalition (ie all possible sub-coalitions):: sage: incorrect_function = {(): 0, ....: (1,): 6, ....: (2,): 12, ....: (3,): 42, ....: (1, 2, 3,): 42} sage: incorrect_game = CooperativeGame(incorrect_function) Traceback (most recent call last): ... ValueError: characteristic function must be the power set """ if not isinstance(characteristic_function, dict): raise TypeError("characteristic function must be a dictionary") self.ch_f = characteristic_function for key in list(self.ch_f): if len(str(key)) == 1 and not isinstance(key, tuple): self.ch_f[(key,)] = self.ch_f.pop(key) elif not isinstance(key, tuple): raise TypeError("key must be a tuple") for key in list(self.ch_f): sortedkey = tuple(sorted(key)) self.ch_f[sortedkey] = self.ch_f.pop(key) self.player_list = max(characteristic_function, key=len) for coalition in powerset(self.player_list): if tuple(sorted(coalition)) not in self.ch_f: raise ValueError("characteristic function must be the power set") self.number_players = len(self.player_list) def shapley_value(self): r""" Return the Shapley value for ``self``. The Shapley value is the "fair" payoff vector and is computed by the following formula: .. MATH:: \phi_i(G) = \sum_{S \subseteq \Omega} \sum_{p \in S} \frac{1}{|S|\binom{N}{|S|}} \bigl( v(S) - v(S \setminus \{p\}) \bigr). EXAMPLES: A typical example of computing the Shapley value:: sage: integer_function = {(): 0, ....: (1,): 6, ....: (2,): 12, ....: (3,): 42, ....: (1, 2,): 12, ....: (1, 3,): 42, ....: (2, 3,): 42, ....: (1, 2, 3,): 42} sage: integer_game = CooperativeGame(integer_function) sage: integer_game.player_list (1, 2, 3) sage: integer_game.shapley_value() {1: 2, 2: 5, 3: 35} A longer example of the Shapley value:: sage: long_function = {(): 0, ....: (1,): 0, ....: (2,): 0, ....: (3,): 0, ....: (4,): 0, ....: (1, 2): 0, ....: (1, 3): 0, ....: (1, 4): 0, ....: (2, 3): 0, ....: (2, 4): 0, ....: (3, 4): 0, ....: (1, 2, 3): 0, ....: (1, 2, 4): 45, ....: (1, 3, 4): 40, ....: (2, 3, 4): 0, ....: (1, 2, 3, 4): 65} sage: long_game = CooperativeGame(long_function) sage: long_game.shapley_value() {1: 70/3, 2: 10, 3: 25/3, 4: 70/3} """ payoff_vector = {} n = Integer(len(self.player_list)) for player in self.player_list: weighted_contribution = 0 for coalition in powerset(self.player_list): if coalition: # If non-empty k = Integer(len(coalition)) weight = 1 / (n.binomial(k) * k) t = tuple(p for p in coalition if p != player) weighted_contribution += weight * (self.ch_f[tuple(coalition)] - self.ch_f[t]) payoff_vector[player] = weighted_contribution return payoff_vector def is_monotone(self): r""" Return ``True`` if ``self`` is monotonic. A game `G = (N, v)` is monotonic if it satisfies `v(C_2) \geq v(C_1)` for all `C_1 \subseteq C_2`. EXAMPLES: A simple game that is monotone:: sage: integer_function = {(): 0, ....: (1,): 6, ....: (2,): 12, ....: (3,): 42, ....: (1, 2,): 12, ....: (1, 3,): 42, ....: (2, 3,): 42, ....: (1, 2, 3,): 42} sage: integer_game = CooperativeGame(integer_function) sage: integer_game.is_monotone() True An example when the game is not monotone:: sage: integer_function = {(): 0, ....: (1,): 6, ....: (2,): 12, ....: (3,): 42, ....: (1, 2,): 10, ....: (1, 3,): 42, ....: (2, 3,): 42, ....: (1, 2, 3,): 42} sage: integer_game = CooperativeGame(integer_function) sage: integer_game.is_monotone() False An example on a longer game:: sage: long_function = {(): 0, ....: (1,): 0, ....: (2,): 0, ....: (3,): 0, ....: (4,): 0, ....: (1, 2): 0, ....: (1, 3): 0, ....: (1, 4): 0, ....: (2, 3): 0, ....: (2, 4): 0, ....: (3, 4): 0, ....: (1, 2, 3): 0, ....: (1, 2, 4): 45, ....: (1, 3, 4): 40, ....: (2, 3, 4): 0, ....: (1, 2, 3, 4): 65} sage: long_game = CooperativeGame(long_function) sage: long_game.is_monotone() True """ return not any(set(p1) <= set(p2) and self.ch_f[p1] > self.ch_f[p2] for p1, p2 in permutations(self.ch_f.keys(), 2)) def is_superadditive(self): r""" Return ``True`` if ``self`` is superadditive. A characteristic function game `G = (N, v)` is superadditive if it satisfies `v(C_1 \cup C_2) \geq v(C_1) + v(C_2)` for all `C_1, C_2 \subseteq 2^{\Omega}` such that `C_1 \cap C_2 = \emptyset`. EXAMPLES: An example that is not superadditive:: sage: integer_function = {(): 0, ....: (1,): 6, ....: (2,): 12, ....: (3,): 42, ....: (1, 2,): 12, ....: (1, 3,): 42, ....: (2, 3,): 42, ....: (1, 2, 3,): 42} sage: integer_game = CooperativeGame(integer_function) sage: integer_game.is_superadditive() False An example that is superadditive:: sage: A_function = {(): 0, ....: (1,): 6, ....: (2,): 12, ....: (3,): 42, ....: (1, 2,): 18, ....: (1, 3,): 48, ....: (2, 3,): 55, ....: (1, 2, 3,): 80} sage: A_game = CooperativeGame(A_function) sage: A_game.is_superadditive() True An example with a longer game that is superadditive:: sage: long_function = {(): 0, ....: (1,): 0, ....: (2,): 0, ....: (3,): 0, ....: (4,): 0, ....: (1, 2): 0, ....: (1, 3): 0, ....: (1, 4): 0, ....: (2, 3): 0, ....: (2, 4): 0, ....: (3, 4): 0, ....: (1, 2, 3): 0, ....: (1, 2, 4): 45, ....: (1, 3, 4): 40, ....: (2, 3, 4): 0, ....: (1, 2, 3, 4): 65} sage: long_game = CooperativeGame(long_function) sage: long_game.is_superadditive() True An example with a longer game that is not:: sage: long_function = {(): 0, ....: (1,): 0, ....: (2,): 0, ....: (3,): 55, ....: (4,): 0, ....: (1, 2): 0, ....: (1, 3): 0, ....: (1, 4): 0, ....: (2, 3): 0, ....: (2, 4): 0, ....: (3, 4): 0, ....: (1, 2, 3): 0, ....: (1, 2, 4): 45, ....: (1, 3, 4): 40, ....: (2, 3, 4): 0, ....: (1, 2, 3, 4): 85} sage: long_game = CooperativeGame(long_function) sage: long_game.is_superadditive() False """ sets = self.ch_f.keys() for p1, p2 in combinations(sets, 2): if not (set(p1) & set(p2)): union = tuple(sorted(set(p1) | set(p2))) if self.ch_f[union] < self.ch_f[p1] + self.ch_f[p2]: return False return True def _repr_(self): r""" Return a concise description of ``self``. EXAMPLES:: sage: letter_function = {(): 0, ....: ('A',): 6, ....: ('B',): 12, ....: ('C',): 42, ....: ('A', 'B',): 12, ....: ('A', 'C',): 42, ....: ('B', 'C',): 42, ....: ('A', 'B', 'C',): 42} sage: letter_game = CooperativeGame(letter_function) sage: letter_game A 3 player co-operative game """ return "A {} player co-operative game".format(self.number_players) def _latex_(self): r""" Return the LaTeX code representing the characteristic function. EXAMPLES:: sage: letter_function = {(): 0, ....: ('A',): 6, ....: ('B',): 12, ....: ('C',): 42, ....: ('A', 'B',): 12, ....: ('A', 'C',): 42, ....: ('B', 'C',): 42, ....: ('A', 'B', 'C',): 42} sage: letter_game = CooperativeGame(letter_function) sage: latex(letter_game) v(c) = \begin{cases} 0, & \text{if } c = \emptyset \\ 6, & \text{if } c = \{A\} \\ 12, & \text{if } c = \{B\} \\ 42, & \text{if } c = \{C\} \\ 12, & \text{if } c = \{A, B\} \\ 42, & \text{if } c = \{A, C\} \\ 42, & \text{if } c = \{B, C\} \\ 42, & \text{if } c = \{A, B, C\} \\ \end{cases} """ cf = self.ch_f output = "v(c) = \\begin{cases}\n" for key, val in sorted(cf.items(), key=lambda kv: (len(kv[0]), kv[0])): if not key: # == () coalition = "\\emptyset" else: coalition = "\\{" + ", ".join(str(player) for player in key) + "\\}" output += "{}, & \\text{{if }} c = {} \\\\\n".format(val, coalition) output += "\\end{cases}" return output def is_efficient(self, payoff_vector): r""" Return ``True`` if ``payoff_vector`` is efficient. A payoff vector `v` is efficient if `\sum_{i=1}^N \lambda_i = v(\Omega)`; in other words, no value of the total coalition is lost. INPUT: - ``payoff_vector`` -- a dictionary where the key is the player and the value is their payoff EXAMPLES: An efficient payoff vector:: sage: letter_function = {(): 0, ....: ('A',): 6, ....: ('B',): 12, ....: ('C',): 42, ....: ('A', 'B',): 12, ....: ('A', 'C',): 42, ....: ('B', 'C',): 42, ....: ('A', 'B', 'C',): 42} sage: letter_game = CooperativeGame(letter_function) sage: letter_game.is_efficient({'A': 14, 'B': 14, 'C': 14}) True sage: letter_function = {(): 0, ....: ('A',): 6, ....: ('B',): 12, ....: ('C',): 42, ....: ('A', 'B',): 12, ....: ('A', 'C',): 42, ....: ('B', 'C',): 42, ....: ('A', 'B', 'C',): 42} sage: letter_game = CooperativeGame(letter_function) sage: letter_game.is_efficient({'A': 10, 'B': 14, 'C': 14}) False A longer example:: sage: long_function = {(): 0, ....: (1,): 0, ....: (2,): 0, ....: (3,): 0, ....: (4,): 0, ....: (1, 2): 0, ....: (1, 3): 0, ....: (1, 4): 0, ....: (2, 3): 0, ....: (2, 4): 0, ....: (3, 4): 0, ....: (1, 2, 3): 0, ....: (1, 2, 4): 45, ....: (1, 3, 4): 40, ....: (2, 3, 4): 0, ....: (1, 2, 3, 4): 65} sage: long_game = CooperativeGame(long_function) sage: long_game.is_efficient({1: 20, 2: 20, 3: 5, 4: 20}) True """ pl = tuple(sorted(self.player_list)) return sum(payoff_vector.values()) == self.ch_f[pl] def nullplayer(self, payoff_vector): r""" Return ``True`` if ``payoff_vector`` possesses the nullplayer property. A payoff vector `v` has the nullplayer property if there exists an `i` such that `v(C \cup i) = v(C)` for all `C \in 2^{\Omega}` then, `\lambda_i = 0`. In other words: if a player does not contribute to any coalition then that player should receive no payoff. INPUT: - ``payoff_vector`` -- a dictionary where the key is the player and the value is their payoff EXAMPLES: A payoff vector that returns ``True``:: sage: letter_function = {(): 0, ....: ('A',): 0, ....: ('B',): 12, ....: ('C',): 42, ....: ('A', 'B',): 12, ....: ('A', 'C',): 42, ....: ('B', 'C',): 42, ....: ('A', 'B', 'C',): 42} sage: letter_game = CooperativeGame(letter_function) sage: letter_game.nullplayer({'A': 0, 'B': 14, 'C': 14}) True A payoff vector that returns ``False``:: sage: A_function = {(): 0, ....: (1,): 0, ....: (2,): 12, ....: (3,): 42, ....: (1, 2,): 12, ....: (1, 3,): 42, ....: (2, 3,): 55, ....: (1, 2, 3,): 55} sage: A_game = CooperativeGame(A_function) sage: A_game.nullplayer({1: 10, 2: 10, 3: 25}) False A longer example for nullplayer:: sage: long_function = {(): 0, ....: (1,): 0, ....: (2,): 0, ....: (3,): 0, ....: (4,): 0, ....: (1, 2): 0, ....: (1, 3): 0, ....: (1, 4): 0, ....: (2, 3): 0, ....: (2, 4): 0, ....: (3, 4): 0, ....: (1, 2, 3): 0, ....: (1, 2, 4): 45, ....: (1, 3, 4): 40, ....: (2, 3, 4): 0, ....: (1, 2, 3, 4): 65} sage: long_game = CooperativeGame(long_function) sage: long_game.nullplayer({1: 20, 2: 20, 3: 5, 4: 20}) True TESTS: Checks that the function is going through all players:: sage: A_function = {(): 0, ....: (1,): 42, ....: (2,): 12, ....: (3,): 0, ....: (1, 2,): 55, ....: (1, 3,): 42, ....: (2, 3,): 12, ....: (1, 2, 3,): 55} sage: A_game = CooperativeGame(A_function) sage: A_game.nullplayer({1: 10, 2: 10, 3: 25}) False """ for player in self.player_list: results = [] for coalit in self.ch_f: if player in coalit: t = tuple(sorted(set(coalit) - {player})) results.append(self.ch_f[coalit] == self.ch_f[t]) if all(results) and payoff_vector[player] != 0: return False return True def is_symmetric(self, payoff_vector): r""" Return ``True`` if ``payoff_vector`` possesses the symmetry property. A payoff vector possesses the symmetry property if `v(C \cup i) = v(C \cup j)` for all `C \in 2^{\Omega} \setminus \{i,j\}`, then `x_i = x_j`. INPUT: - ``payoff_vector`` -- a dictionary where the key is the player and the value is their payoff EXAMPLES: A payoff vector that has the symmetry property:: sage: letter_function = {(): 0, ....: ('A',): 6, ....: ('B',): 12, ....: ('C',): 42, ....: ('A', 'B',): 12, ....: ('A', 'C',): 42, ....: ('B', 'C',): 42, ....: ('A', 'B', 'C',): 42} sage: letter_game = CooperativeGame(letter_function) sage: letter_game.is_symmetric({'A': 5, 'B': 14, 'C': 20}) True A payoff vector that returns ``False``:: sage: integer_function = {(): 0, ....: (1,): 12, ....: (2,): 12, ....: (3,): 42, ....: (1, 2,): 12, ....: (1, 3,): 42, ....: (2, 3,): 42, ....: (1, 2, 3,): 42} sage: integer_game = CooperativeGame(integer_function) sage: integer_game.is_symmetric({1: 2, 2: 5, 3: 35}) False A longer example for symmetry:: sage: long_function = {(): 0, ....: (1,): 0, ....: (2,): 0, ....: (3,): 0, ....: (4,): 0, ....: (1, 2): 0, ....: (1, 3): 0, ....: (1, 4): 0, ....: (2, 3): 0, ....: (2, 4): 0, ....: (3, 4): 0, ....: (1, 2, 3): 0, ....: (1, 2, 4): 45, ....: (1, 3, 4): 40, ....: (2, 3, 4): 0, ....: (1, 2, 3, 4): 65} sage: long_game = CooperativeGame(long_function) sage: long_game.is_symmetric({1: 20, 2: 20, 3: 5, 4: 20}) True """ sets = self.ch_f.keys() element = [i for i in sets if len(i) == 1] for c1, c2 in combinations(element, 2): results = [] for m in sets: junion = tuple(sorted(set(c1) | set(m))) kunion = tuple(sorted(set(c2) | set(m))) results.append(self.ch_f[junion] == self.ch_f[kunion]) if all(results) and payoff_vector[c1[0]] != payoff_vector[c2[0]]: return False return True
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/game_theory/cooperative_game.py
0.899182
0.676216
cooperative_game.py
pypi
r""" Gabidulin Code This module provides the :class:`~sage.coding.gabidulin.GabidulinCode`, which constructs Gabidulin Codes that are the rank metric equivalent of Reed Solomon codes and are defined as the evaluation codes of degree-restricted skew polynomials. This module also provides :class:`~sage.coding.gabidulin.GabidulinPolynomialEvaluationEncoder`, an encoder with a skew polynomial message space and :class:`~sage.coding.gabidulin.GabidulinVectorEvaluationEncoder`, an encoder based on the generator matrix. It also provides a decoder :class:`~sage.coding.gabidulin.GabidulinGaoDecoder` which corrects errors using the Gao algorithm in the rank metric. AUTHOR: - Arpit Merchant (2016-08-16) - Marketa Slukova (2019-08-19): initial version """ from sage.matrix.constructor import matrix from sage.modules.free_module_element import vector from sage.coding.encoder import Encoder from sage.coding.decoder import Decoder, DecodingError from sage.coding.linear_rank_metric import AbstractLinearRankMetricCode from sage.categories.fields import Fields class GabidulinCode(AbstractLinearRankMetricCode): r""" A Gabidulin Code. DEFINITION: A linear Gabidulin code Gab[n, k] over `F_{q^m}` of length `n` (at most `m`) and dimension `k` (at most `n`) is the set of all codewords, that are the evaluation of a `q`-degree restricted skew polynomial `f(x)` belonging to the skew polynomial constructed over the base ring `F_{q^m}` and the twisting homomorphism `\sigma`. .. math:: \{ \text{Gab[n, k]} = \big\{ (f(g_0) f(g_1) ... f(g_{n-1})) = f(\textbf{g}) : \text{deg}_{q}f(x) < k \big\} \} where the fixed evaluation points `g_0, g_1,..., g_{n-1}` are linearly independent over `F_{q^m}`. EXAMPLES: A Gabidulin Code can be constructed in the following way:: sage: Fqm = GF(16) sage: Fq = GF(4) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: C [2, 2, 1] linear Gabidulin code over GF(16)/GF(4) """ _registered_encoders = {} _registered_decoders = {} def __init__(self, base_field, length, dimension, sub_field=None, twisting_homomorphism=None, evaluation_points=None): r""" Representation of a Gabidulin Code. INPUT: - ``base_field`` -- finite field of order `q^m` where `q` is a prime power and `m` is an integer - ``length`` -- length of the resulting code - ``dimension`` -- dimension of the resulting code - ``sub_field`` -- (default: ``None``) finite field of order `q` which is a subfield of the ``base_field``. If not given, it is the prime subfield of the ``base_field``. - ``twisting_homomorphism`` -- (default: ``None``) homomorphism of the underlying skew polynomial ring. If not given, it is the Frobenius endomorphism on ``base_field``, which sends an element `x` to `x^{q}`. - ``evaluation_points`` -- (default: ``None``) list of elements `g_0, g_1,...,g_{n-1}` of the ``base_field`` that are linearly independent over the ``sub_field``. These elements form the first row of the generator matrix. If not specified, these are the `nth` powers of the generator of the ``base_field``. Both parameters ``sub_field`` and ``twisting_homomorphism`` are optional. Since they are closely related, here is a complete list of behaviours: - both ``sub_field`` and ``twisting_homomorphism`` given -- in this case we only check that given that ``twisting_homomorphism`` has a fixed field method, it returns ``sub_field`` - only ``twisting_homomorphism`` given -- we set ``sub_field`` to be the fixed field of the ``twisting_homomorphism``. If such method does not exist, an error is raised. - only ``sub_field`` given -- we set ``twisting_homomorphism`` to be the Frobenius of the field extension - neither ``sub_field`` or ``twisting_homomorphism`` given -- we take ``sub_field`` to be the prime field of ``base_field`` and the ``twisting_homomorphism`` to be the Frobenius wrt. the prime field TESTS: If ``length`` is bigger than the degree of the extension, an error is raised:: sage: C = codes.GabidulinCode(GF(64), 4, 3, GF(4)) Traceback (most recent call last): ... ValueError: 'length' can be at most the degree of the extension, 3 If the number of evaluation points is not equal to the length of the code, an error is raised:: sage: Fqm = GF(5^20) sage: Fq = GF(5) sage: aa = Fqm.gen() sage: evals = [ aa^i for i in range(21) ] sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq, None, evals) Traceback (most recent call last): ... ValueError: the number of evaluation points should be equal to the length of the code If evaluation points are not linearly independent over the ``base_field``, an error is raised:: sage: evals = [ aa*i for i in range(2) ] sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq, None, evals) Traceback (most recent call last): ... ValueError: the evaluation points provided are not linearly independent If an evaluation point does not belong to the ``base_field``, an error is raised:: sage: a = GF(3).gen() sage: evals = [ a*i for i in range(2) ] sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq, None, evals) Traceback (most recent call last): ... ValueError: evaluation point does not belong to the 'base field' Given that both ``sub_field`` and ``twisting_homomorphism`` are specified and ``twisting_homomorphism`` has a fixed field method. If the fixed field of ``twisting_homomorphism`` is not ``sub_field``, an error is raised:: sage: Fqm = GF(64) sage: Fq = GF(8) sage: twist = GF(64).frobenius_endomorphism(n=2) sage: C = codes.GabidulinCode(Fqm, 3, 2, Fq, twist) Traceback (most recent call last): ... ValueError: the fixed field of the twisting homomorphism has to be the relative field of the extension If ``twisting_homomorphism`` is given, but ``sub_field`` is not. In case ``twisting_homomorphism`` does not have a fixed field method, and error is raised:: sage: Fqm.<z6> = GF(64) sage: sigma = Hom(Fqm, Fqm)[1]; sigma Ring endomorphism of Finite Field in z6 of size 2^6 Defn: z6 |--> z6^2 sage: C = codes.GabidulinCode(Fqm, 3, 2, None, sigma) Traceback (most recent call last): ... ValueError: if 'sub_field' is not given, the twisting homomorphism has to have a 'fixed_field' method """ twist_fix_field = None have_twist = (twisting_homomorphism is not None) have_subfield = (sub_field is not None) if have_twist and have_subfield: try: twist_fix_field = twisting_homomorphism.fixed_field()[0] except AttributeError: pass if twist_fix_field and twist_fix_field.order() != sub_field.order(): raise ValueError("the fixed field of the twisting homomorphism has to be the relative field of the extension") if have_twist and not have_subfield: if not twist_fix_field: raise ValueError("if 'sub_field' is not given, the twisting homomorphism has to have a 'fixed_field' method") else: sub_field = twist_fix_field if (not have_twist) and have_subfield: twisting_homomorphism = base_field.frobenius_endomorphism(n=sub_field.degree()) if (not have_twist) and not have_subfield: sub_field = base_field.base_ring() twisting_homomorphism = base_field.frobenius_endomorphism() self._twisting_homomorphism = twisting_homomorphism super().__init__(base_field, sub_field, length, "VectorEvaluation", "Gao") if length > self.extension_degree(): raise ValueError("'length' can be at most the degree of the extension, {}".format(self.extension_degree())) if evaluation_points is None: evaluation_points = [base_field.gen()**i for i in range(base_field.degree())][:length] else: if not len(evaluation_points) == length: raise ValueError("the number of evaluation points should be equal to the length of the code") for i in range(length): if not evaluation_points[i] in base_field: raise ValueError("evaluation point does not belong to the 'base field'") basis = self.matrix_form_of_vector(vector(evaluation_points)) if basis.rank() != length: raise ValueError("the evaluation points provided are not linearly independent") self._evaluation_points = evaluation_points self._dimension = dimension def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: Fqm = GF(16) sage: Fq = GF(4) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq); C [2, 2, 1] linear Gabidulin code over GF(16)/GF(4) """ R = self.base_field() S = self.sub_field() if R and S in Fields(): return "[%s, %s, %s] linear Gabidulin code over GF(%s)/GF(%s)" % (self.length(), self.dimension(), self.minimum_distance(), R.cardinality(), S.cardinality()) else: return "[%s, %s, %s] linear Gabidulin code over %s/%s" % (self.length(), self.dimension(), self.minimum_distance(), R, S) def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: Fqm = GF(16) sage: Fq = GF(4) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq); sage: latex(C) [2, 2, 1] \textnormal{ linear Gabidulin code over } \Bold{F}_{2^{4}}/\Bold{F}_{2^{2}} """ txt = "[%s, %s, %s] \\textnormal{ linear Gabidulin code over } %s/%s" return txt % (self.length(), self.dimension(), self.minimum_distance(), self.base_field()._latex_(), self.sub_field()._latex_()) def __eq__(self, other): """ Test equality between Gabidulin Code objects. INPUT: - ``other`` -- another Gabidulin Code object OUTPUT: - ``True`` or ``False`` EXAMPLES:: sage: Fqm = GF(16) sage: Fq = GF(4) sage: C1 = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: C2 = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: C1.__eq__(C2) True sage: Fqmm = GF(64) sage: C3 = codes.GabidulinCode(Fqmm, 2, 2, Fq) sage: C3.__eq__(C2) False """ return isinstance(other, GabidulinCode) \ and self.base_field() == other.base_field() \ and self.sub_field() == other.sub_field() \ and self.length() == other.length() \ and self.dimension() == other.dimension() \ and self.evaluation_points() == other.evaluation_points() def twisting_homomorphism(self): r""" Return the twisting homomorphism of ``self``. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5^4) sage: C = codes.GabidulinCode(Fqm, 5, 3, Fq) sage: C.twisting_homomorphism() Frobenius endomorphism z20 |--> z20^(5^4) on Finite Field in z20 of size 5^20 """ return self._twisting_homomorphism def minimum_distance(self): r""" Return the minimum distance of ``self``. Since Gabidulin Codes are Maximum-Distance-Separable (MDS), this returns ``self.length() - self.dimension() + 1``. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5) sage: C = codes.GabidulinCode(Fqm, 20, 15, Fq) sage: C.minimum_distance() 6 """ return self.length() - self.dimension() + 1 def parity_evaluation_points(self): r""" Return the parity evaluation points of ``self``. These form the first row of the parity check matrix of ``self``. EXAMPLES:: sage: C = codes.GabidulinCode(GF(2^10), 5, 2) sage: list(C.parity_check_matrix().row(0)) == C.parity_evaluation_points() #indirect_doctest True """ eval_pts = self.evaluation_points() n = self.length() k = self.dimension() sigma = self.twisting_homomorphism() coefficient_matrix = matrix(self.base_field(), n - 1, n, lambda i, j: (sigma**(-n + k + 1 + i))(eval_pts[j])) solution_space = coefficient_matrix.right_kernel() return list(solution_space.basis()[0]) def dual_code(self): r""" Return the dual code `C^{\perp}` of ``self``, the code `C`, .. MATH:: C^{\perp} = \{ v \in V\ |\ v\cdot c = 0,\ \forall c \in C \}. EXAMPLES:: sage: C = codes.GabidulinCode(GF(2^10), 5, 2) sage: C1 = C.dual_code(); C1 [5, 3, 3] linear Gabidulin code over GF(1024)/GF(2) sage: C == C1.dual_code() True """ return GabidulinCode(self.base_field(), self.length(), self.length() - self.dimension(), self.sub_field(), self.twisting_homomorphism(), self.parity_evaluation_points()) def parity_check_matrix(self): r""" Return the parity check matrix of ``self``. This is the generator matrix of the dual code of ``self``. EXAMPLES:: sage: C = codes.GabidulinCode(GF(2^3), 3, 2) sage: C.parity_check_matrix() [ 1 z3 z3^2 + z3] sage: C.parity_check_matrix() == C.dual_code().generator_matrix() True """ return self.dual_code().generator_matrix() def evaluation_points(self): """ Return the evaluation points of ``self``. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5^4) sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq) sage: C.evaluation_points() [1, z20, z20^2, z20^3] """ return self._evaluation_points # ---------------------- encoders ------------------------------ class GabidulinVectorEvaluationEncoder(Encoder): def __init__(self, code): """ This method constructs the vector evaluation encoder for Gabidulin Codes. INPUT: - ``code`` -- the associated code of this encoder. EXAMPLES:: sage: Fqm = GF(16) sage: Fq = GF(4) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: E = codes.encoders.GabidulinVectorEvaluationEncoder(C) sage: E Vector evaluation style encoder for [2, 2, 1] linear Gabidulin code over GF(16)/GF(4) Alternatively, we can construct the encoder from ``C`` directly:: sage: E = C.encoder("VectorEvaluation") sage: E Vector evaluation style encoder for [2, 2, 1] linear Gabidulin code over GF(16)/GF(4) TESTS: If the code is not a Gabidulin code, an error is raised:: sage: C = codes.HammingCode(GF(4), 2) sage: E = codes.encoders.GabidulinVectorEvaluationEncoder(C) Traceback (most recent call last): ... ValueError: code has to be a Gabidulin code """ if not isinstance(code, GabidulinCode): raise ValueError("code has to be a Gabidulin code") super().__init__(code) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5^4) sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq) sage: E = codes.encoders.GabidulinVectorEvaluationEncoder(C); E Vector evaluation style encoder for [4, 4, 1] linear Gabidulin code over GF(95367431640625)/GF(625) """ return "Vector evaluation style encoder for %s" % self.code() def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5^4) sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq) sage: E = codes.encoders.GabidulinVectorEvaluationEncoder(C) sage: latex(E) \textnormal{Vector evaluation style encoder for } [4, 4, 1] \textnormal{ linear Gabidulin code over } \Bold{F}_{5^{20}}/\Bold{F}_{5^{4}} """ return "\\textnormal{Vector evaluation style encoder for } %s" % self.code()._latex_() def __eq__(self, other): """ Test equality between Gabidulin Generator Matrix Encoder objects. INPUT: - ``other`` -- another Gabidulin Generator Matrix Encoder OUTPUT: - ``True`` or ``False`` EXAMPLES:: sage: Fqm = GF(16) sage: Fq = GF(4) sage: C1 = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: E1 = codes.encoders.GabidulinVectorEvaluationEncoder(C1) sage: C2 = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: E2 = codes.encoders.GabidulinVectorEvaluationEncoder(C2) sage: E1.__eq__(E2) True sage: Fqmm = GF(64) sage: C3 = codes.GabidulinCode(Fqmm, 2, 2, Fq) sage: E3 = codes.encoders.GabidulinVectorEvaluationEncoder(C3) sage: E3.__eq__(E2) False """ return isinstance(other, GabidulinVectorEvaluationEncoder) \ and self.code() == other.code() def generator_matrix(self): """ Return the generator matrix of ``self``. EXAMPLES:: sage: Fqm = GF(2^9) sage: Fq = GF(2^3) sage: C = codes.GabidulinCode(Fqm, 3, 3, Fq) sage: list(C.generator_matrix().row(1)) == [C.evaluation_points()[i]**(2**3) for i in range(3)] True """ from functools import reduce C = self.code() eval_pts = C.evaluation_points() sigma = C.twisting_homomorphism() def create_matrix_elements(A, k, f): return reduce(lambda L, x: [x] + [list(map(f, l)) for l in L], [A] * k, []) return matrix(C.base_field(), C.dimension(), C.length(), create_matrix_elements(eval_pts, C.dimension(), sigma)) class GabidulinPolynomialEvaluationEncoder(Encoder): r""" Encoder for Gabidulin codes which uses evaluation of skew polynomials to obtain codewords. Let `C` be a Gabidulin code of length `n` and dimension `k` over some finite field `F = GF(q^m)`. We denote by `\alpha_i` its evaluations points, where `1 \leq i \leq n`. Let `p`, a skew polynomial of degree at most `k-1` in `F[x]`, be the message. The encoding of `m` will be the following codeword: .. MATH:: (p(\alpha_1), \dots, p(\alpha_n)). TESTS: This module uses the following experimental feature. This test block is here only to trigger the experimental warning so it does not interferes with doctests:: sage: Fqm = GF(2^9) sage: Fq = GF(2^3) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: S.<x> = Fqm['x', C.twisting_homomorphism()] sage: z9 = Fqm.gen() sage: p = (z9^6 + z9^2 + z9 + 1)*x + z9^7 + z9^5 + z9^4 + z9^2 sage: vector(p.multi_point_evaluation(C.evaluation_points())) doctest:...: FutureWarning: This class/method/function is marked as experimental. It, its functionality or its interface might change without a formal deprecation. See http://trac.sagemath.org/13215 for details. (z9^7 + z9^6 + z9^5 + z9^4 + z9 + 1, z9^6 + z9^5 + z9^3 + z9) EXAMPLES:: sage: Fqm = GF(16) sage: Fq = GF(4) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C) sage: E Polynomial evaluation style encoder for [2, 2, 1] linear Gabidulin code over GF(16)/GF(4) Alternatively, we can construct the encoder from ``C`` directly:: sage: E = C.encoder("PolynomialEvaluation") sage: E Polynomial evaluation style encoder for [2, 2, 1] linear Gabidulin code over GF(16)/GF(4) """ def __init__(self, code): r""" INPUT: - ``code`` -- the associated code of this encoder TESTS: If the code is not a Gabidulin code, an error is raised:: sage: C = codes.HammingCode(GF(4), 2) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C) Traceback (most recent call last): ... ValueError: code has to be a Gabidulin code """ if not isinstance(code, GabidulinCode): raise ValueError("code has to be a Gabidulin code") super().__init__(code) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5^4) sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C); E Polynomial evaluation style encoder for [4, 4, 1] linear Gabidulin code over GF(95367431640625)/GF(625) """ return "Polynomial evaluation style encoder for %s" % self.code() def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5^4) sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C) sage: latex(E) \textnormal{Polynomial evaluation style encoder for } [4, 4, 1] \textnormal{ linear Gabidulin code over } \Bold{F}_{5^{20}}/\Bold{F}_{5^{4}} """ return "\\textnormal{Polynomial evaluation style encoder for } %s" % self.code()._latex_() def __eq__(self, other): """ Test equality between Gabidulin Polynomial Evaluation Encoder objects. INPUT: - ``other`` -- another Gabidulin Polynomial Evaluation Encoder OUTPUT: - ``True`` or ``False`` EXAMPLES:: sage: Fqm = GF(16) sage: Fq = GF(4) sage: C1 = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: E1 = codes.encoders.GabidulinPolynomialEvaluationEncoder(C1) sage: C2 = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: E2 = codes.encoders.GabidulinPolynomialEvaluationEncoder(C2) sage: E1.__eq__(E2) True sage: Fqmm = GF(64) sage: C3 = codes.GabidulinCode(Fqmm, 2, 2, Fq) sage: E3 = codes.encoders.GabidulinPolynomialEvaluationEncoder(C3) sage: E3.__eq__(E2) False """ return isinstance(other, GabidulinPolynomialEvaluationEncoder) \ and self.code() == other.code() def message_space(self): r""" Return the message space of the associated code of ``self``. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5^4) sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C) sage: E.message_space() Ore Polynomial Ring in x over Finite Field in z20 of size 5^20 twisted by z20 |--> z20^(5^4) """ C = self.code() return C.base_field()['x', C.twisting_homomorphism()] def encode(self, p, form="vector"): """ Transform the polynomial ``p`` into a codeword of :meth:`code`. The output codeword can be represented as a vector or a matrix, depending on the ``form`` input. INPUT: - ``p`` -- a skew polynomial from the message space of ``self`` of degree less than ``self.code().dimension()`` - ``form`` -- type parameter taking strings "vector" or "matrix" as values and converting the output codeword into the respective form (default: "vector") OUTPUT: - a codeword corresponding to `p` in vector or matrix form EXAMPLES:: sage: Fqm = GF(2^9) sage: Fq = GF(2^3) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C) sage: S.<x> = Fqm['x', C.twisting_homomorphism()] sage: z9 = Fqm.gen() sage: p = (z9^6 + z9^2 + z9 + 1)*x + z9^7 + z9^5 + z9^4 + z9^2 sage: codeword_vector = E.encode(p, "vector"); codeword_vector (z9^7 + z9^6 + z9^5 + z9^4 + z9 + 1, z9^6 + z9^5 + z9^3 + z9) sage: codeword_matrix = E.encode(p, "matrix"); codeword_matrix [ z3 z3^2 + z3] [ z3 1] [ z3^2 z3^2 + z3 + 1] TESTS: If the skew polynomial, `p`, has degree greater than or equal to the dimension of the code, an error is raised:: sage: t = z9^4*x^2 + z9 sage: codeword_vector = E.encode(t, "vector"); codeword_vector Traceback (most recent call last): ... ValueError: the skew polynomial to encode must have degree at most 1 The skew polynomial, `p`, must belong to the message space of the code. Otherwise, an error is raised:: sage: Fqmm = GF(2^12) sage: S.<x> = Fqmm['x', Fqmm.frobenius_endomorphism(n=3)] sage: q = S.random_element(degree=2) sage: codeword_vector = E.encode(q, "vector"); codeword_vector Traceback (most recent call last): ... ValueError: the message to encode must be in Ore Polynomial Ring in x over Finite Field in z9 of size 2^9 twisted by z9 |--> z9^(2^3) """ C = self.code() M = self.message_space() if p not in M: raise ValueError("the message to encode must be in %s" % M) if p.degree() >= C.dimension(): raise ValueError("the skew polynomial to encode must have degree at most %s" % (C.dimension() - 1)) eval_pts = C.evaluation_points() codeword = p.multi_point_evaluation(eval_pts) if form == "vector": return vector(codeword) elif form == "matrix": return C.matrix_form_of_vector(vector(codeword)) else: return ValueError("the argument 'form' takes only either 'vector' or 'matrix' as valid input") def unencode_nocheck(self, c): """ Return the message corresponding to the codeword ``c``. Use this method with caution: it does not check if ``c`` belongs to the code, and if this is not the case, the output is unspecified. INPUT: - ``c`` -- a codeword of :meth:`code` OUTPUT: - a skew polynomial of degree less than ``self.code().dimension()`` EXAMPLES:: sage: Fqm = GF(2^9) sage: Fq = GF(2^3) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C) sage: S.<x> = Fqm['x', C.twisting_homomorphism()] sage: z9 = Fqm.gen() sage: p = (z9^6 + z9^4)*x + z9^2 + z9 sage: codeword_vector = E.encode(p, "vector") sage: E.unencode_nocheck(codeword_vector) (z9^6 + z9^4)*x + z9^2 + z9 """ C = self.code() eval_pts = C.evaluation_points() values = [c[i] for i in range(len(c))] points = [(eval_pts[i], values[i]) for i in range(len(eval_pts))] p = self.message_space().lagrange_polynomial(points) return p # ---------------------- decoders ------------------------------ class GabidulinGaoDecoder(Decoder): def __init__(self, code): r""" Gao style decoder for Gabidulin Codes. INPUT: - ``code`` -- the associated code of this decoder EXAMPLES:: sage: Fqm = GF(16) sage: Fq = GF(4) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: D = codes.decoders.GabidulinGaoDecoder(C) sage: D Gao decoder for [2, 2, 1] linear Gabidulin code over GF(16)/GF(4) Alternatively, we can construct the encoder from ``C`` directly:: sage: D = C.decoder("Gao") sage: D Gao decoder for [2, 2, 1] linear Gabidulin code over GF(16)/GF(4) TESTS: If the code is not a Gabidulin code, an error is raised:: sage: C = codes.HammingCode(GF(4), 2) sage: D = codes.decoders.GabidulinGaoDecoder(C) Traceback (most recent call last): ... ValueError: code has to be a Gabidulin code """ if not isinstance(code, GabidulinCode): raise ValueError("code has to be a Gabidulin code") super().__init__(code, code.ambient_space(), "PolynomialEvaluation") def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5^4) sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq) sage: D = codes.decoders.GabidulinGaoDecoder(C); D Gao decoder for [4, 4, 1] linear Gabidulin code over GF(95367431640625)/GF(625) """ return "Gao decoder for %s" % self.code() def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5^4) sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq) sage: D = codes.decoders.GabidulinGaoDecoder(C) sage: latex(D) \textnormal{Gao decoder for } [4, 4, 1] \textnormal{ linear Gabidulin code over } \Bold{F}_{5^{20}}/\Bold{F}_{5^{4}} """ return "\\textnormal{Gao decoder for } %s" % self.code()._latex_() def __eq__(self, other) -> bool: """ Test equality between Gabidulin Gao Decoder objects. INPUT: - ``other`` -- another Gabidulin Gao Decoder OUTPUT: - ``True`` or ``False`` EXAMPLES:: sage: Fqm = GF(16) sage: Fq = GF(4) sage: C1 = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: D1 = codes.decoders.GabidulinGaoDecoder(C1) sage: C2 = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: D2 = codes.decoders.GabidulinGaoDecoder(C2) sage: D1.__eq__(D2) True sage: Fqmm = GF(64) sage: C3 = codes.GabidulinCode(Fqmm, 2, 2, Fq) sage: D3 = codes.decoders.GabidulinGaoDecoder(C3) sage: D3.__eq__(D2) False """ return isinstance(other, GabidulinGaoDecoder) \ and self.code() == other.code() def _partial_xgcd(self, a, b, d_stop): """ Compute the partial gcd of `a` and `b` using the right linearized extended Euclidean algorithm up to the `d_stop` iterations. This is a private method for internal use only. INPUT: - ``a`` -- a skew polynomial - ``b`` -- another skew polynomial - ``d_stop`` -- the number of iterations for which the algorithm is to be run OUTPUT: - ``r_c`` -- right linearized remainder of `a` and `b` - ``u_c`` -- right linearized quotient of `a` and `b` EXAMPLES:: sage: Fqm = GF(2^9) sage: Fq = GF(2^3) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: D = codes.decoders.GabidulinGaoDecoder(C) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C) sage: S.<x> = Fqm['x', C.twisting_homomorphism()] sage: z9 = Fqm.gen() sage: p = (z9^6 + z9^4)*x + z9^2 + z9 sage: codeword_vector = E.encode(p, "vector") sage: r = D.decode_to_message(codeword_vector) #indirect_doctest sage: r (z9^6 + z9^4)*x + z9^2 + z9 """ S = self.message_space() if (a not in S) or (b not in S): raise ValueError("both the input polynomials must belong to %s" % S) if a.degree() < b.degree(): raise ValueError("degree of first polynomial must be greater than or equal to degree of second polynomial") r_p = a r_c = b u_p = S.zero() u_c = S.one() v_p = u_c v_c = u_p while r_c.degree() >= d_stop: (q, r_c), r_p = r_p.right_quo_rem(r_c), r_c u_c, u_p = u_p - q * u_c, u_c v_c, v_p = v_p - q * v_c, v_c return r_c, u_c def _decode_to_code_and_message(self, r): """ Return the decoded codeword and message (skew polynomial) corresponding to the received codeword `r`. This is a private method for internal use only. INPUT: - ``r`` -- received codeword OUTPUT: - the decoded codeword and decoded message corresponding to the received codeword `r` EXAMPLES:: sage: Fqm = GF(2^9) sage: Fq = GF(2^3) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: D = codes.decoders.GabidulinGaoDecoder(C) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C) sage: S.<x> = Fqm['x', C.twisting_homomorphism()] sage: z9 = Fqm.gen() sage: p = (z9^6 + z9^4)*x + z9^2 + z9 sage: codeword_vector = E.encode(p, "vector") sage: r = D.decode_to_message(codeword_vector) #indirect doctest sage: r (z9^6 + z9^4)*x + z9^2 + z9 """ C = self.code() length = len(r) eval_pts = C.evaluation_points() S = self.message_space() if length == C.dimension() or r in C: return r, self.connected_encoder().unencode_nocheck(r) points = [(eval_pts[i], r[i]) for i in range(len(eval_pts))] # R = S.lagrange_polynomial(eval_pts, list(r)) R = S.lagrange_polynomial(points) r_out, u_out = self._partial_xgcd(S.minimal_vanishing_polynomial(eval_pts), R, (C.length() + C.dimension()) // 2) quo, rem = r_out.left_quo_rem(u_out) if not rem.is_zero(): raise DecodingError("Decoding failed because the number of errors exceeded the decoding radius") if quo not in S: raise DecodingError("Decoding failed because the number of errors exceeded the decoding radius") c = self.connected_encoder().encode(quo) if C.rank_weight_of_vector(c - r) > self.decoding_radius(): raise DecodingError("Decoding failed because the number of errors exceeded the decoding radius") return c, quo def decode_to_code(self, r): """ Return the decoded codeword corresponding to the received word `r`. INPUT: - ``r`` -- received codeword OUTPUT: - the decoded codeword corresponding to the received codeword EXAMPLES:: sage: Fqm = GF(3^20) sage: Fq = GF(3) sage: C = codes.GabidulinCode(Fqm, 5, 3, Fq) sage: D = codes.decoders.GabidulinGaoDecoder(C) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C) sage: S.<x> = Fqm['x', C.twisting_homomorphism()] sage: z20 = Fqm.gen() sage: p = x sage: codeword_vector = E.encode(p, "vector") sage: codeword_vector (1, z20^3, z20^6, z20^9, z20^12) sage: l = list(codeword_vector) sage: l[0] = l[1] #make an error sage: D.decode_to_code(vector(l)) (1, z20^3, z20^6, z20^9, z20^12) """ return self._decode_to_code_and_message(r)[0] def decode_to_message(self, r): """ Return the skew polynomial (message) corresponding to the received word `r`. INPUT: - ``r`` -- received codeword OUTPUT: - the message corresponding to the received codeword EXAMPLES:: sage: Fqm = GF(2^9) sage: Fq = GF(2^3) sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq) sage: D = codes.decoders.GabidulinGaoDecoder(C) sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C) sage: S.<x> = Fqm['x', C.twisting_homomorphism()] sage: z9 = Fqm.gen() sage: p = (z9^6 + z9^4)*x + z9^2 + z9 sage: codeword_vector = E.encode(p, "vector") sage: r = D.decode_to_message(codeword_vector) sage: r (z9^6 + z9^4)*x + z9^2 + z9 """ return self._decode_to_code_and_message(r)[1] def decoding_radius(self): """ Return the decoding radius of the Gabidulin Gao Decoder. EXAMPLES:: sage: Fqm = GF(5^20) sage: Fq = GF(5) sage: C = codes.GabidulinCode(Fqm, 20, 4, Fq) sage: D = codes.decoders.GabidulinGaoDecoder(C) sage: D.decoding_radius() 8 """ return (self.code().minimum_distance() - 1) // 2 # ----------------------------- registration -------------------------------- GabidulinCode._registered_encoders["PolynomialEvaluation"] = GabidulinPolynomialEvaluationEncoder GabidulinCode._registered_encoders["VectorEvaluation"] = GabidulinVectorEvaluationEncoder GabidulinCode._registered_decoders["Gao"] = GabidulinGaoDecoder
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/coding/gabidulin_code.py
0.914121
0.791942
gabidulin_code.py
pypi
r""" Database of two-weight codes This module stores a database of two-weight codes. {DB_INDEX} REFERENCE: - [BS2003]_ - [ChenDB]_ - [Koh2007]_ - [Di2000]_ TESTS: Check the data's consistency:: sage: from sage.coding.two_weight_db import data sage: for code in data: ....: M = code['M'] ....: assert code['n'] == M.ncols() ....: assert code['k'] == M.nrows() ....: w1,w2 = [w for w,f in enumerate(LinearCode(M).weight_distribution()) if w and f] ....: assert (code['w1'], code['w2']) == (w1, w2) """ from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF from sage.matrix.constructor import Matrix # The following is a list of two-weight codes stored as dictionaries. Each entry # sets the base field, the matrix and the source: other parameters are computed # automatically data = [ { 'n' : 68, 'k' : 8, 'w1': 32, 'w2': 40, 'K' : GF(2), 'M' : ("10000000100111100110000001101000100111000011100101011010111111010110", "01000000010011110011000000110100010011100001110010101101011111101011", "00100000001001111101100000011010001001110000111001010110101111110101", "00010000100011011100110001100101100011111011111001100001101000101100", "00001000110110001100011001011010011110111110011001111010001011000000", "00000100111100100000001101000101101000011100101001110111111010110110", "00000010011110010000000110100010111100001110010100101011111101011011", "00000001001111001100000011010001011110000111001010010101111110101101"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 140, 'k' : 6, 'w1': 90, 'w2': 99, 'K' : GF(3), 'M' : ("10111011111111101110101110111100111011111011101111101001001111011011011111100100111101000111101111101100011011001111101110111110101111111001", "01220121111211011101011101112101220022120121011222010110011010120110112112001101021010101111012211011000020110012221212101011101211122020011", "22102021112110111120211021122012100012202220112110101200110101202102122120011110020201211110021210110000101200121222122010211022211210110101", "11010221121101111102210221220221000111011101121102012101101012012022222000211200202012211100111201200001122001211011120102110212212102121001", "20201121211111111012202022201210001220122121211010121011010020110121220201212002010222011001111012100011010212110021202021102112221012110011", "02022222111111110112020112011200022102212222110102210110100101102211201211220020002120110011110221100110002121100222120211021112010112220101"), 'source': "Found by Axel Kohnert [Koh2007]_ and shared by Alfred Wassermann.", }, { 'n' : 98, 'k' : 6, 'w1': 63, 'w2': 72, 'K' : GF(3), 'M' : ("10000021022112121121110122000110112002010011100120022110120200120111220220122120012012100201110210", "01000020121020200200211101202121120002211002210100021021202220112122012212101102010210010221221201", "00100021001211011111111202120022221002201111021101021212210122101020121111002000210000101222202000", "00010022122200222202201212211112001102200112202202121201211212010210202001222120000002110021000110", "00001021201002010011020210221221012112200012020011201200111021021102212120211102012002011201210221", "00000120112212122122202110022202210010200022002120112200101002202221111102110100210212001022201202"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 84, 'k' : 6, 'w1': 54, 'w2': 63, 'K' : GF(3), 'M' : ("100000210221121211211212100002020022102220010202100220112211111022012202220001210020", "010000201210202002002200010022222022012112111222010212120102222221210102112001001022", "001000210012110111111202101021212221000101021021021211021221000111100202101200010122", "000100221222002222022202010121111210202200012001222011212000211200122202100120211002", "000010212010020100110002001011101112122110211102212121200111102212021122100010201120", "000001201122121221222212000110100102011101201012001102201222221110211011100001200102"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 56, 'k' : 6, 'w1': 36, 'w2': 45, 'K' : GF(3), 'M' : ("10000021022112022210202200202122221120200112100200111102", "01000020121020221101202120220001110202220110010222122212", "00100021001211211020022112222122002210122100101222020020", "00010022122200010012221111121001121211212002110020010101", "00001021201002220211121011010222000111021002011201112112", "00000120112212111201011001002111121101002212001022222010"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 65, 'k' : 4, 'w1': 50, 'w2': 55, 'K' : GF(5), 'M' : ("10004323434444234221223441130101034431234004441141003110400203240", "01003023101220331314013121123212111200011403221341101031340421204", "00104120244011212302124203142422240001230144213220111213034240310", "00012321211123213343321143204040211243210011144140014401003023101"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 52, 'k' : 4, 'w1': 40, 'w2': 45, 'K' : GF(5), 'M' : ("1000432343444423422122344123113041011022221414310431", "0100302310122033131401312133032331123141114414001300", "0010412024401121230212420301411224123332332300210011", "0001232121112321334332114324420140440343341412401244"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 39, 'k' : 4, 'w1': 30, 'w2': 35, 'K' : GF(5), 'M' : ("111111111111111111111111111111000000000", "111111222222333333444444000000111111000", "223300133440112240112240133440123400110", "402340414201142301132013234230044330401"), 'source': "From Bouyukliev and Simonis ([BS2003]_, Theorem 4.1)", }, { 'n' : 55, 'k' : 5, 'w1': 36, 'w2': 45, 'K' : GF(3), 'M' : ("1000010122200120121002211022111101011212112022022020002", "0100011101120102100102202121022211112000020211221222002", "0010021021222220122011212220021121100021220002100102201", "0001012221012012100200102211110211121211201002202000222", "0000101222101201210020110221111020112121120120220200022"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 126, 'k' : 6, 'w1': 81, 'w2': 90, 'K' : GF(3), 'M' : ("100000210221121211211101220021210000100011020200201101121021122102020111100122122221120200110001010222000021110110011211110210", "010000201210202002002111012020001001110012222220221211200120201212222102210100001110202220121001110211200120221121012001221201", "001000210012110111111112021220210102211012212122200222212000112220212011021102122002210122122101120210120100102212112112202000", "000100221222002222022012122120201012021112211112111120010221100121011012202201001121211212002211120210012201120021222121000110", "000010212010020100110202102200200102002122111011112210121010202111121212020010222000111021000222122210001011222102100121210221", "000001201122121221222021100221200012000220101001022022100122112010102222002122111121101002200020221110000122202000221222201202"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 154, 'k' : 6, 'w1': 99, 'w2': 108, 'K' : GF(3), 'M' : ("10000021022112121121110122002121000010001102020020110112102112202221021020201"+ "20202212102220222022222110122210022201211222111110211101121002011102101111002", "01000020121020200200211101202000100111001222222022121120012020122110122122221"+ "02222102012112111221111021101101021121002001022221202211100102212212010222102", "00100021001211011111111202122021010221101221212220022221200011221102002202120"+ "20121121000101000111020212200020121210011112210001001022001012222020000100212", "00010022122200222202201212212020101202111221111211112001022110001001221210110"+ "12211020202200222000021101010212001022212020002112011200021100210001100121020", "00001021201002010011020210220020010200212211101111221012101020222021111111212"+ "11120012122110211222201220220201222200102101111020112221020112012102211120101", "00000120112212122122202110022120001200022010100102202210012211211120100101022"+ "01011212011101110111112202111200111021221112222211222020120010222012022220012"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 198, 'k' : 10, 'w1': 96, 'w2': 112, 'K' : GF(2), 'M' : ("1000000000111111101010000100011001111101101010010010011110001101111001101100111000111101010101110011"+ "11110010100111101001001100111101011110111100101101110100111100011111011011100111110010100110110000", "0100000000010110011100100010101010101111011010001001010110011010101011011101000110000001101101010110"+ "10110111110101000000011011001100010111110001001011011100111100100000110001011001110110011101011000", "0010000000011100111110111011000011010100100011110000001100011011101111001010001100110110000001111000"+ "11000000101011010111110101000111110010011011101110000010110100000011100010011111100100111101010010", "0001000000001111100010000000100101010001110111100010010010010111000100101100010001001110111101110100"+ "10010101101100110011010011101100110100100011011101100000110011110011111000000010110101011111101111", "0000100000110010010000010110000111010011010101000010110100101010011011000011001100001110011011110001"+ "11101000010000111101101100111100001011010010111011100101101001111000100011000010110111111111011100", "0000010000110100111001111011010000101110001011100010010010010111100101011001011011100110101110100001"+ "01101010110010100011000101111100100001110111001001001001001100001101110110000110101010011010101101", "0000001000011011110010110100010010001100000011001000011101000110001101001000110110010101011011001111"+ "01111111010011111010100110011001110001001000001110000110111011010000011101001110111001011011001011", "0000000100111001101011110010111100100001010100100110001100100110010101111001100101101001000101011000"+ "10001001111101011101001001010111010011011101010011010000101010011001010110011110010000011011111001", "0000000010101011010101010101011100111101111110100011011001001010111101100111010110100101100110101100"+ "00000001100011110110010101100001000000010100001101111011111000110001100101101010000001110101011100", "0000000001101100111101011000010000000011010100000110101010011010100111100001000011010011011101110111"+ "01110111011110101100100100110110011100001001000001010011010010010111110011101011101001101101011010"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 219, 'k' : 9, 'w1': 96, 'w2': 112, 'K' : GF(2), 'M' : ("10100011001110100010100010010000100100001011110010001010011000000001101011110011001001000010011110111011111"+ "0001001010110110110111001100111100011011101000000110101110001010100011110011111111110111010100101011000101111111", "01100010110101110100001000010110001010010010011000111101111001011101000011101011100111111110001100000111010"+ "1101001000110001111011001100101011110101011110010001101011110000100000101101100010110100001111001100110011001111", "00010010001001011011001110011101111110000000101110101000110110011001110101011011101011011011000010010011111"+ "1110110100111111000000110011101101000000001010000000011000111111100101100001110011110001110011110110100111100001", "00001000100010101110101110011100010101110011010110000001111111100111010000101110001010100100000001011010111"+ "1001001000000011000011001100100100111010000000001010111001001100100101011110001100110001000000111001100100100111", "00000101010100010101101110011101001000101110000000000111101100011000000001110100000001011010101001111110110"+ "0010110111100111000000110011110110101101110000001111100001010001100101100001110011110001101101000000000000100001", "00000000000000000000010000011101011100100010000110110100101011001011001100000001011000101010100111000111101"+ "0011100011011011011111100010011100010111101001011001001101100010011010001011010110001110100001001111110010100100", "00000000000000000000000001011010110110101111010110101001001001000101010000000000001011000011000010100100110"+ "0000110000111101100010000111111111101101001010110000111111101110101011010010010001011101110011111001100100101110", "00000000000000000000000000110111101011110010101110000110010010100010001010000000010100011000101000010011000"+ "0110000111100110100001001011111111111010110000001010111111110011110110001100100010101011101101110110011000110110", "00000000000000000000000000000000000000000000000001111111111111111111111110000001111111111111111111111111111"+ "1111111100000000000011111111111111000000111111111111111111000000000000111111111111000000000000000000111111000110"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 73, 'k' : 9, 'w1': 32, 'w2': 40, 'K' : GF(2), 'M' : ("1010010100000010100000101010001100110101101101000010110010100100111011101", "0110000110000101101111001101000100111111101011011101110010110001100111100", "0001010000000001111111011010100101001111011010101100001010000001110100001", "0000100100000001111111100111000011110011110101000001010110000001011010001", "0000001010000001111110111100011000111100101110010010101100000001101001001", "0000000001000111001010110010011001101001011010110110011001010111100010010", "0000000000100100011000100100111100001100101111010001011011111000110011110", "0000000000010111001100101011111110101010000000000100111110000001111111100", "0000000000001011100001000011011010110001110101101100001100101110101110110"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 70, 'k' : 9, 'w1': 32, 'w2': 40, 'K' : GF(2), 'M' : ("0100011110111000001011010110110111100010001000001000001001010110101101", "1000111101110000000110101111101111000100010000010000000010101111001011", "0001111011100000011101011101011110011000100000100000000101011100010111", "0011110101000000111010111010111100110001000011000000001010111000101101", "0111101000000001110101110111111001100010000100000000010101110011001011", "1111010000000011101011101101110011010100001000000000101011100100010111", "1110100010000111000111011011100110111000010000000001000111001010101101", "1101000110001110001110110101001101110000100010000010001110010101001011", "1010001110011100001101101010011011110001000100000100001100101010010111"), 'source': "Found by Axel Kohnert [Koh2007]_ and shared by Alfred Wassermann.", }, { 'n' : 85, 'k' : 8, 'w1': 40, 'w2': 48, 'K' : GF(2), 'M' : ("1000000010011101010001000011100111000111111010110001101101000110010011001101011100001", "0100000011010011111001100010010100100100000111101001011011100101011010101011110010001", "0010000011110100101101110010101101010101111001000101000000110100111110011000100101001", "0001000011100111000111111010110001101101000110010011001101011100001100000001001110101", "0000100011101110110010111110111111110001011001111000001011101000010101001101111011011", "0000010011101010001000011100111000111111010110001101101000110010011001101011100001100", "0000001001110101000100001110011100011111101011000110110100011001001100110101110000110", "0000000100111010100010000111001110001111110101100011011010001100100110011010111000011"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 15, 'k' : 4, 'w1': 9, 'w2': 12, 'K' : GF(3), 'M' : ("100022021001111", "010011211122000", "001021112100011", "000110120222220"), 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 34, 'k' : 4, 'w1': 24, 'w2': 28, 'K' : GF(4,name='x'), 'M' : [[1,0,0,0, 1,'x', 'x','x^2', 1, 0, 'x','x', 0, 1,'x^2','x','x','x^2','x^2','x^2','x', 'x','x^2','x^2','x^2', 1,'x^2','x',1,0, 1, 'x','x^2', 1], [0,1,0,0,'x','x', 1,'x^2', 1, 1,'x^2', 1,'x', 'x', 0, 0, 1, 0, 'x', 'x', 0, 1,'x^2', 'x', 'x', 1, 0, 0,0,1,'x', 'x','x^2', 1], [0,0,1,0, 1, 0, 0, 'x','x', 1,'x^2', 1, 1,'x^2', 1,'x','x', 'x','x^2', 1, 0, 'x', 'x', 0, 1,'x^2', 'x','x',1,0, 0, 0, 1, 'x'], [0,0,0,1,'x','x','x^2', 1, 0,'x', 'x', 0, 1,'x^2', 'x','x', 1,'x^2','x^2', 'x','x','x^2','x^2','x^2', 1,'x^2', 'x', 1,0,1,'x','x^2', 1,'x^2']], 'source': "Shared by Eric Chen [ChenDB]_.", }, { 'n' : 121, 'k' : 5, 'w1': 88, 'w2': 96, 'K' : GF(4,name='x'), 'M' : [map({'0':0,'1':1,'a':'x','b':'x**2'}.get,x) for x in ["11b1aab0a0101010b1b0a0bab0a0a0b011a0a1b1aab0b1a0b1bab0b0a0b1b011a011a011a011b0b1b0b0b0b0aab1a1b0aab0b010aab1a010b0a1a1aab", "01100110011aa0011aabb0011bb11aabb00bb00aabb11bb11aa0011aabb00aabb00aabb0011bb0011aa00aabb0011aa11aabb00aabb0011aabb00aabb", "000111100000011111111aaaaaabbbbbb0000111111aaaabbbb00000000111111aaaaaabbbbbb000000111111aaaaaa000000111111aaaaaaaabbbbbb", "00000001111111111111111111111111100000000000000000011111111111111111111111111aaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbb", "0000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", ]], 'source' : "From [Di2000]_", }, { 'n' : 132, 'k' : 5, 'w1': 96, 'w2': 104, 'K' : GF(4,name='x'), 'M' : [map({'0':0,'1':1,'a':'x','b':'x**2'}.get,x) for x in ["aab1a1ab0b11b1a10b0b101ab00ab1b01ab01abbabab10a1b0a0101a1a1a01ab1b0101ab01ba00bb1bb111b11b1011b1ab0abb1b01abab00abab0aab01001ab0a11b", "10011b0011abb001aaaab00001ab011aaaabbbb1aabb011aabb001aabb01a00abb001111bbb01aab001ab001bb011aa011aaab001111aab00abb0011aab000011abb", "011111000000011111aaabbbbbbb0000000000011111aaaaaaabbbbbbb00011111aaaaaaaaabbbbb0000011111aaaaabbbbbbb00000000011111aaaaaaabbbbbbbbb", "00000011111111111111111111110000000000000000000000000000001111111111111111111111aaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", ]], 'source' : "From [Di2000]_", }, { 'n' : 143, 'k' : 5, 'w1': 104, 'w2': 112, 'K' : GF(4,name='x'), 'M' : [map({'0':0,'1':1,'a':'x','b':'x**2'}.get,x) for x in ["1a01a01ab0aaab0bab0a1ab0bab0ab0a01a0a011aab00a01a1a011b00101b1a1bb0a0abab00a1a01a1b11a010b01ab1ab0a011a01ab00a10b0a01babab1a1ba011ab0a1ab0a0b01", "0011abbbb001aabb00aabbb0011aaabb00011bb0011abb000aabb001aa00b11aab00111aa0110011abb0aabb001111aaabb0011aaaab001bb00111aa0011aab11aaabb00011aabb", "11111111100000001111111aaaaaaaaabbbbbbb00000001111111aaaaabbb000001111111aaabbbbbbb0000011111111111aaaaaaaaabbbbb00000001111111aaaaaaabbbbbbbbb", "00000000011111111111111111111111111111100000000000000000000001111111111111111111111aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "00000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", ]], 'source' : "From [Di2000]_", }, { 'n' : 168, 'k' : 6, 'w1': 108, 'w2': 117, 'K' : GF(3), 'M' : ["101212212122202012010102120101112012121001201012120220122112001121201201201201010020012201001201201201202120121122012021201221021110200212121011211002012220000122201201", "011100122001200111220011220020011222001200022000220012220122011220011101122012012001222010122200012011120112220112000120120012002012201122001220012122000201212001211211", "000011111000011111112000001112000000111122222000001111112222000001111122222000111222222001111122222000001111112222000001112222000111122222000001111222000011122000011122", "000000000111111111111000000000111111111111111222222222222222000000000000000111111111111222222222222000000000000000111111111111222222222222000000000000111111111222222222", "000000000000000000000111111111111111111111111111111111111111000000000000000000000000000000000000000111111111111111111111111111111111111111222222222222222222222222222222", "000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"], 'source' : "From [Di2000]_", }, ] # Build actual matrices. for code in data: code['M'] = Matrix(code['K'],[list(R) for R in code['M']]) DB_INDEX = (".. csv-table::\n" " :class: contentstable\n" " :widths: 7,7,7,7,7,50\n" " :delim: @\n\n") data.sort(key=lambda x:(x['K'].cardinality(),x['k'],x['n'])) for x in data: s = " `q={}` @ `n={}` @ `k={}` @ `w_1={}` @ `w_2={}` @ {}\n".format(x['K'].cardinality(),x['n'],x['k'],x['w1'],x['w2'],x.get('source','')) DB_INDEX += s __doc__ = __doc__.format(DB_INDEX=DB_INDEX)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/coding/two_weight_db.py
0.753376
0.472197
two_weight_db.py
pypi
r""" Access functions to online databases for coding theory """ from sage.libs.gap.libgap import libgap from sage.features.gap import GapPackage # Do not put any global imports here since this module is accessible as # sage.codes.databases.<tab> def best_linear_code_in_guava(n, k, F): r""" Return the linear code of length ``n``, dimension ``k`` over field ``F`` with the maximal minimum distance which is known to the GAP package GUAVA. The function uses the tables described in :func:`bounds_on_minimum_distance_in_guava` to construct this code. This requires the optional GAP package GUAVA. INPUT: - ``n`` -- the length of the code to look up - ``k`` -- the dimension of the code to look up - ``F`` -- the base field of the code to look up OUTPUT: A :class:`LinearCode` which is a best linear code of the given parameters known to GUAVA. EXAMPLES:: sage: codes.databases.best_linear_code_in_guava(10,5,GF(2)) # long time; optional - gap_packages (Guava package) [10, 5] linear code over GF(2) sage: libgap.LoadPackage('guava') # long time; optional - gap_packages (Guava package) ... sage: libgap.BestKnownLinearCode(10,5,libgap.GF(2)) # long time; optional - gap_packages (Guava package) a linear [10,5,4]2..4 shortened code This means that the best possible binary linear code of length 10 and dimension 5 is a code with minimum distance 4 and covering radius s somewhere between 2 and 4. Use ``bounds_on_minimum_distance_in_guava(10,5,GF(2))`` for further details. """ from .linear_code import LinearCode GapPackage("guava", spkg="gap_packages").require() libgap.load_package("guava") C = libgap.BestKnownLinearCode(n, k, F) return LinearCode(C.GeneratorMat()._matrix_(F)) def bounds_on_minimum_distance_in_guava(n, k, F): r""" Compute a lower and upper bound on the greatest minimum distance of a `[n,k]` linear code over the field ``F``. This function requires the optional GAP package GUAVA. The function returns a GAP record with the two bounds and an explanation for each bound. The method ``Display`` can be used to show the explanations. The values for the lower and upper bound are obtained from a table constructed by Cen Tjhai for GUAVA, derived from the table of Brouwer. See http://www.codetables.de/ for the most recent data. These tables contain lower and upper bounds for `q=2` (when ``n <= 257``), `q=3` (when ``n <= 243``), `q=4` (``n <= 256``). (Current as of 11 May 2006.) For codes over other fields and for larger word lengths, trivial bounds are used. INPUT: - ``n`` -- the length of the code to look up - ``k`` -- the dimension of the code to look up - ``F`` -- the base field of the code to look up OUTPUT: - A GAP record object. See below for an example. EXAMPLES:: sage: gap_rec = codes.databases.bounds_on_minimum_distance_in_guava(10,5,GF(2)) # optional - gap_packages (Guava package) sage: gap_rec.Display() # optional - gap_packages (Guava package) rec( construction := [ <Operation "ShortenedCode">, [ [ <Operation "UUVCode">, [ [ <Operation "DualCode">, [ [ <Operation "RepetitionCode">, [ 8, 2 ] ] ] ], [ <Operation "UUVCode">, [ [ <Operation "DualCode">, [ [ <Operation "RepetitionCode">, [ 4, 2 ] ] ] ], [ <Operation "RepetitionCode">, [ 4, 2 ] ] ] ] ] ], [ 1, 2, 3, 4, 5, 6 ] ] ], k := 5, lowerBound := 4, lowerBoundExplanation := ... n := 10, q := 2, references := rec( ), upperBound := 4, upperBoundExplanation := ... ) """ GapPackage("guava", spkg="gap_packages").require() libgap.load_package("guava") return libgap.BoundsMinimumDistance(n, k, F) def best_linear_code_in_codetables_dot_de(n, k, F, verbose=False): r""" Return the best linear code and its construction as per the web database http://www.codetables.de/ INPUT: - ``n`` - Integer, the length of the code - ``k`` - Integer, the dimension of the code - ``F`` - Finite field, of order 2, 3, 4, 5, 7, 8, or 9 - ``verbose`` - Bool (default: ``False``) OUTPUT: - An unparsed text explaining the construction of the code. EXAMPLES:: sage: L = codes.databases.best_linear_code_in_codetables_dot_de(72, 36, GF(2)) # optional - internet sage: print(L) # optional - internet Construction of a linear code [72,36,15] over GF(2): [1]: [73, 36, 16] Cyclic Linear Code over GF(2) CyclicCode of length 73 with generating polynomial x^37 + x^36 + x^34 + x^33 + x^32 + x^27 + x^25 + x^24 + x^22 + x^21 + x^19 + x^18 + x^15 + x^11 + x^10 + x^8 + x^7 + x^5 + x^3 + 1 [2]: [72, 36, 15] Linear Code over GF(2) Puncturing of [1] at 1 <BLANKLINE> last modified: 2002-03-20 This function raises an ``IOError`` if an error occurs downloading data or parsing it. It raises a ``ValueError`` if the ``q`` input is invalid. AUTHORS: - Steven Sivek (2005-11-14) - David Joyner (2008-03) """ from urllib.request import urlopen from sage.cpython.string import bytes_to_str q = F.order() if q not in [2, 3, 4, 5, 7, 8, 9]: raise ValueError("q (=%s) must be in [2,3,4,5,7,8,9]" % q) n = int(n) k = int(k) param = ("?q=%s&n=%s&k=%s" % (q, n, k)).replace('L', '') url = "http://www.codetables.de/" + "BKLC/BKLC.php" + param if verbose: print("Looking up the bounds at %s" % url) with urlopen(url) as f: s = f.read() s = bytes_to_str(s) i = s.find("<PRE>") j = s.find("</PRE>") if i == -1 or j == -1: raise IOError("Error parsing data (missing pre tags).") return s[i+5:j].strip() def self_orthogonal_binary_codes(n, k, b=2, parent=None, BC=None, equal=False, in_test=None): """ Returns a Python iterator which generates a complete set of representatives of all permutation equivalence classes of self-orthogonal binary linear codes of length in ``[1..n]`` and dimension in ``[1..k]``. INPUT: - ``n`` - Integer, maximal length - ``k`` - Integer, maximal dimension - ``b`` - Integer, requires that the generators all have weight divisible by ``b`` (if ``b=2``, all self-orthogonal codes are generated, and if ``b=4``, all doubly even codes are generated). Must be an even positive integer. - ``parent`` - Used in recursion (default: ``None``) - ``BC`` - Used in recursion (default: ``None``) - ``equal`` - If ``True`` generates only [n, k] codes (default: ``False``) - ``in_test`` - Used in recursion (default: ``None``) EXAMPLES: Generate all self-orthogonal codes of length up to 7 and dimension up to 3:: sage: for B in codes.databases.self_orthogonal_binary_codes(7,3): ....: print(B) [2, 1] linear code over GF(2) [4, 2] linear code over GF(2) [6, 3] linear code over GF(2) [4, 1] linear code over GF(2) [6, 2] linear code over GF(2) [6, 2] linear code over GF(2) [7, 3] linear code over GF(2) [6, 1] linear code over GF(2) Generate all doubly-even codes of length up to 7 and dimension up to 3:: sage: for B in codes.databases.self_orthogonal_binary_codes(7,3,4): ....: print(B); print(B.generator_matrix()) [4, 1] linear code over GF(2) [1 1 1 1] [6, 2] linear code over GF(2) [1 1 1 1 0 0] [0 1 0 1 1 1] [7, 3] linear code over GF(2) [1 0 1 1 0 1 0] [0 1 0 1 1 1 0] [0 0 1 0 1 1 1] Generate all doubly-even codes of length up to 7 and dimension up to 2:: sage: for B in codes.databases.self_orthogonal_binary_codes(7,2,4): ....: print(B); print(B.generator_matrix()) [4, 1] linear code over GF(2) [1 1 1 1] [6, 2] linear code over GF(2) [1 1 1 1 0 0] [0 1 0 1 1 1] Generate all self-orthogonal codes of length equal to 8 and dimension equal to 4:: sage: for B in codes.databases.self_orthogonal_binary_codes(8, 4, equal=True): ....: print(B); print(B.generator_matrix()) [8, 4] linear code over GF(2) [1 0 0 1 0 0 0 0] [0 1 0 0 1 0 0 0] [0 0 1 0 0 1 0 0] [0 0 0 0 0 0 1 1] [8, 4] linear code over GF(2) [1 0 0 1 1 0 1 0] [0 1 0 1 1 1 0 0] [0 0 1 0 1 1 1 0] [0 0 0 1 0 1 1 1] Since all the codes will be self-orthogonal, b must be divisible by 2:: sage: list(codes.databases.self_orthogonal_binary_codes(8, 4, 1, equal=True)) Traceback (most recent call last): ... ValueError: b (1) must be a positive even integer. """ from sage.rings.finite_rings.finite_field_constructor import FiniteField from sage.matrix.constructor import Matrix d=int(b) if d!=b or d%2==1 or d <= 0: raise ValueError("b (%s) must be a positive even integer."%b) from .linear_code import LinearCode from .binary_code import BinaryCode, BinaryCodeClassifier if k < 1 or n < 2: return if equal: in_test = lambda M: (M.ncols() - M.nrows()) <= (n-k) out_test = lambda C: (C.dimension() == k) and (C.length() == n) else: in_test = lambda M: True out_test = lambda C: True if BC is None: BC = BinaryCodeClassifier() if parent is None: for j in range(d, n+1, d): M = Matrix(FiniteField(2), [[1]*j]) if in_test(M): for N in self_orthogonal_binary_codes(n, k, d, M, BC, in_test=in_test): if out_test(N): yield N else: C = LinearCode(parent) if out_test(C): yield C if k == parent.nrows(): return for nn in range(parent.ncols()+1, n+1): if in_test(parent): for child in BC.generate_children(BinaryCode(parent), nn, d): for N in self_orthogonal_binary_codes(n, k, d, child, BC, in_test=in_test): if out_test(N): yield N # Import the following function so that it is available as # sage.codes.databases.self_dual_binary_codes sage.codes.databases functions # somewhat like a catalog in this respect. from sage.coding.self_dual_codes import self_dual_binary_codes
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/coding/databases.py
0.916638
0.744494
databases.py
pypi
from sage.modules.free_module_element import vector from sage.matrix.constructor import matrix from sage.matrix.matrix_space import MatrixSpace from sage.rings.function_field.place import FunctionFieldPlace from .linear_code import (AbstractLinearCode, LinearCodeGeneratorMatrixEncoder, LinearCodeSyndromeDecoder) from .ag_code_decoders import (EvaluationAGCodeUniqueDecoder, EvaluationAGCodeEncoder, DifferentialAGCodeUniqueDecoder, DifferentialAGCodeEncoder) class AGCode(AbstractLinearCode): """ Base class of algebraic geometry codes. A subclass of this class is required to define ``_function_field`` attribute that refers to an abstract functiom field or the function field of the underlying curve used to construct a code of the class. """ def base_function_field(self): """ Return the function field used to construct the code. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: p = C([0,0]) sage: Q, = p.places() sage: pls.remove(Q) sage: G = 5*Q sage: code = codes.EvaluationAGCode(pls, G) sage: code.base_function_field() Function field in y defined by y^2 + y + x^3 """ return self._function_field class EvaluationAGCode(AGCode): """ Evaluation AG code defined by rational places ``pls`` and a divisor ``G``. INPUT: - ``pls`` -- a list of rational places of a function field - ``G`` -- a divisor whose support is disjoint from ``pls`` If ``G`` is a place, then it is regarded as a prime divisor. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: G = 5*Q sage: codes.EvaluationAGCode(pls, G) [8, 5] evaluation AG code over GF(4) sage: G = F.get_place(5) sage: codes.EvaluationAGCode(pls, G) [8, 5] evaluation AG code over GF(4) """ _registered_encoders = {} _registered_decoders = {} def __init__(self, pls, G): """ Initialize. TESTS:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls = [pl for pl in pls if pl != Q] sage: G = 5*Q sage: code = codes.EvaluationAGCode(pls, G) sage: TestSuite(code).run() """ if issubclass(type(G), FunctionFieldPlace): G = G.divisor() # place is converted to a prime divisor F = G.parent().function_field() K = F.constant_base_field() n = len(pls) if any(p.degree() > 1 for p in pls): raise ValueError("there is a nonrational place among the places") if any(p in pls for p in G.support()): raise ValueError("the support of the divisor is not disjoint from the places") self._registered_encoders['evaluation'] = EvaluationAGCodeEncoder self._registered_decoders['K'] = EvaluationAGCodeUniqueDecoder super().__init__(K, n, default_encoder_name='evaluation', default_decoder_name='K') # compute basis functions associated with a generator matrix basis_functions = G.basis_function_space() m = matrix([vector(K, [b.evaluate(p) for p in pls]) for b in basis_functions]) I = MatrixSpace(K, m.nrows()).identity_matrix() mI = m.augment(I) mI.echelonize() M = mI.submatrix(0, 0, m.nrows(), m.ncols()) T = mI.submatrix(0, m.ncols()) r = M.rank() self._generator_matrix = M.submatrix(0, 0, r) self._basis_functions = [sum(c * b for c, b in zip(T[i], basis_functions)) for i in range(r)] self._pls = tuple(pls) self._G = G self._function_field = F def __eq__(self, other): """ Test equality of ``self`` with ``other``. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: codes.EvaluationAGCode(pls, 5*Q) == codes.EvaluationAGCode(pls, 6*Q) False """ if self is other: return True if not isinstance(other, EvaluationAGCode): return False return self._pls == other._pls and self._G == other._G def __hash__(self): """ Return the hash value of ``self``. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.EvaluationAGCode(pls, 5*Q) sage: {code: 1} {[8, 5] evaluation AG code over GF(4): 1} """ return hash((self._pls, self._G)) def _repr_(self): """ Return the string representation of ``self``. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: codes.EvaluationAGCode(pls, 7*Q) [8, 7] evaluation AG code over GF(4) """ return "[{}, {}] evaluation AG code over GF({})".format( self.length(), self.dimension(), self.base_field().cardinality()) def _latex_(self): r""" Return the latex representation of ``self``. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.EvaluationAGCode(pls, 3*Q) sage: latex(code) [8, 3]\text{ evaluation AG code over }\Bold{F}_{2^{2}} """ return r"[{}, {}]\text{{ evaluation AG code over }}{}".format( self.length(), self.dimension(), self.base_field()._latex_()) def basis_functions(self): r""" Return the basis functions associated with the generator matrix. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.EvaluationAGCode(pls, 3*Q) sage: code.basis_functions() (y + a*x + 1, y + x, (a + 1)*x) sage: matrix([[f.evaluate(p) for p in pls] for f in code.basis_functions()]) [ 1 0 0 1 a a + 1 1 0] [ 0 1 0 1 1 0 a + 1 a] [ 0 0 1 1 a a a + 1 a + 1] """ return tuple(self._basis_functions) def generator_matrix(self): r""" Return a generator matrix of the code. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.EvaluationAGCode(pls, 3*Q) sage: code.generator_matrix() [ 1 0 0 1 a a + 1 1 0] [ 0 1 0 1 1 0 a + 1 a] [ 0 0 1 1 a a a + 1 a + 1] """ return self._generator_matrix def designed_distance(self): """ Return the designed distance of the AG code. If the code is of dimension zero, then a ``ValueError`` is raised. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.EvaluationAGCode(pls, 3*Q) sage: code.designed_distance() 5 """ if self.dimension() == 0: raise ValueError("not defined for zero code") d = self.length() - self._G.degree() return d if d > 0 else 1 class DifferentialAGCode(AGCode): """ Differential AG code defined by rational places ``pls`` and a divisor ``G`` INPUT: - ``pls`` -- a list of rational places of a function field - ``G`` -- a divisor whose support is disjoint from ``pls`` If ``G`` is a place, then it is regarded as a prime divisor. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = A.curve(y^3 + y - x^4) sage: Q = C.places_at_infinity()[0] sage: O = C([0,0]).place() sage: pls = [p for p in C.places() if p not in [O, Q]] sage: G = -O + 3*Q sage: codes.DifferentialAGCode(pls, -O + Q) [3, 2] differential AG code over GF(4) sage: F = C.function_field() sage: G = F.get_place(1) sage: codes.DifferentialAGCode(pls, G) [3, 1] differential AG code over GF(4) """ _registered_encoders = {} _registered_decoders = {} def __init__(self, pls, G): """ Initialize. TESTS:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.DifferentialAGCode(pls, 3*Q) sage: TestSuite(code).run() """ if issubclass(type(G), FunctionFieldPlace): G = G.divisor() # place is converted to a prime divisor F = G.parent().function_field() K = F.constant_base_field() n = len(pls) if any(p.degree() > 1 for p in pls): raise ValueError("there is a nonrational place among the places") if any(p in pls for p in G.support()): raise ValueError("the support of the divisor is not disjoint from the places") self._registered_encoders['residue'] = DifferentialAGCodeEncoder self._registered_decoders['K'] = DifferentialAGCodeUniqueDecoder super().__init__(K, n, default_encoder_name='residue', default_decoder_name='K') # compute basis differentials associated with a generator matrix basis_differentials = (-sum(pls) + G).basis_differential_space() m = matrix([vector(K, [w.residue(p) for p in pls]) for w in basis_differentials]) I = MatrixSpace(K, m.nrows()).identity_matrix() mI = m.augment(I) mI.echelonize() M = mI.submatrix(0, 0, m.nrows(), m.ncols()) T = mI.submatrix(0, m.ncols()) r = M.rank() self._generator_matrix = M.submatrix(0, 0, r) self._basis_differentials = [sum(c * w for c, w in zip(T[i], basis_differentials)) for i in range(r)] self._pls = tuple(pls) self._G = G self._function_field = F def __eq__(self, other): """ Test equality of ``self`` with ``other``. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: c1 = codes.DifferentialAGCode(pls, 3*Q) sage: c2 = codes.DifferentialAGCode(pls, 3*Q) sage: c1 is c2 False sage: c1 == c2 True """ if self is other: return True if not isinstance(other, DifferentialAGCode): return False return self._pls == other._pls and self._G == other._G def __hash__(self): """ Return the hash of ``self``. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.DifferentialAGCode(pls, 3*Q) sage: {code: 1} {[8, 5] differential AG code over GF(4): 1} """ return hash((self._pls, self._G)) def _repr_(self): """ Return the string representation of ``self``. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: codes.DifferentialAGCode(pls, 3*Q) [8, 5] differential AG code over GF(4) """ return "[{}, {}] differential AG code over GF({})".format( self.length(), self.dimension(), self.base_field().cardinality()) def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.DifferentialAGCode(pls, 3*Q) sage: latex(code) [8, 5]\text{ differential AG code over }\Bold{F}_{2^{2}} """ return r"[{}, {}]\text{{ differential AG code over }}{}".format( self.length(), self.dimension(), self.base_field()._latex_()) def basis_differentials(self): r""" Return the basis differentials associated with the generator matrix. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.DifferentialAGCode(pls, 3*Q) sage: matrix([[w.residue(p) for p in pls] for w in code.basis_differentials()]) [ 1 0 0 0 0 a + 1 a + 1 1] [ 0 1 0 0 0 a + 1 a 0] [ 0 0 1 0 0 a 1 a] [ 0 0 0 1 0 a 0 a + 1] [ 0 0 0 0 1 1 1 1] """ return tuple(self._basis_differentials) def generator_matrix(self): """ Return a generator matrix of the code. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.DifferentialAGCode(pls, 3*Q) sage: code.generator_matrix() [ 1 0 0 0 0 a + 1 a + 1 1] [ 0 1 0 0 0 a + 1 a 0] [ 0 0 1 0 0 a 1 a] [ 0 0 0 1 0 a 0 a + 1] [ 0 0 0 0 1 1 1 1] """ return self._generator_matrix def designed_distance(self): """ Return the designed distance of the differential AG code. If the code is of dimension zero, then a ``ValueError`` is raised. EXAMPLES:: sage: k.<a> = GF(4) sage: A.<x,y> = AffineSpace(k, 2) sage: C = Curve(y^2 + y - x^3) sage: F = C.function_field() sage: pls = F.places() sage: Q, = C.places_at_infinity() sage: pls.remove(Q) sage: code = codes.DifferentialAGCode(pls, 3*Q) sage: code.designed_distance() 3 """ if self.dimension() == 0: raise ValueError("not defined for zero code") d = self._G.degree() - 2 * self._function_field.genus() + 2 return d if d > 0 else 1 class CartierCode(AGCode): r""" Cartier code defined by rational places ``pls`` and a divisor ``G`` of a function field. INPUT: - ``pls`` -- a list of rational places - ``G`` -- a divisor whose support is disjoint from ``pls`` - ``r`` -- integer (default: 1) - ``name`` -- string; name of the generator of the subfield `\GF{p^r}` OUTPUT: Cartier code over `\GF{p^r}` where `p` is the characteristic of the base constant field of the function field Note that if ``r`` is 1 the default, then ``name`` can be omitted. EXAMPLES:: sage: F.<a> = GF(9) sage: P.<x,y,z> = ProjectiveSpace(F, 2); sage: C = Curve(x^3*y + y^3*z + x*z^3) sage: F = C.function_field() sage: pls = F.places() sage: Z, = C(0,0,1).places() sage: pls.remove(Z) sage: G = 3*Z sage: code = codes.CartierCode(pls, G) # long time sage: code.minimum_distance() # long time 2 """ def __init__(self, pls, G, r=1, name=None): """ Initialize. TESTS:: sage: F.<a> = GF(9) sage: P.<x,y,z> = ProjectiveSpace(F, 2); sage: C = Curve(x^3*y + y^3*z + x*z^3) sage: F = C.function_field() sage: pls = F.places() sage: Z, = C(0,0,1).places() sage: pls.remove(Z) sage: G = 3*Z sage: code = codes.CartierCode(pls, G) # long time sage: TestSuite(code).run() # long time """ F = G.parent().function_field() K = F.constant_base_field() if any(p.degree() > 1 for p in pls): raise ValueError("there is a nonrational place among the places") if any(p in pls for p in G.support()): raise ValueError("the support of the divisor is not disjoint from the places") if K.degree() % r != 0: raise ValueError("{} does not divide the degree of the constant base field".format(r)) n = len(pls) D = sum(pls) p = K.characteristic() subfield = K.subfield(r, name=name) # compute a basis R of the space of differentials in Omega(G - D) # fixed by the Cartier operator E = G - D Grp = E.parent() # group of divisors V, fr_V, to_V = E.differential_space() EE = Grp(0) dic = E.dict() for place in dic: mul = dic[place] if mul > 0: mul = mul // p**r EE += mul * place W, fr_W, to_W = EE.differential_space() a = K.gen() field_basis = [a**i for i in range(K.degree())] # over prime subfield basis = E.basis_differential_space() m = [] for w in basis: for c in field_basis: cw = F(c) * w # c does not coerce... carcw = cw for i in range(r): # apply cartier r times carcw = carcw.cartier() m.append([f for e in to_W(carcw - cw) for f in vector(e)]) ker = matrix(m).kernel() R = [] s = len(field_basis) ncols = s * len(basis) for row in ker.basis(): v = vector([K(row[d:d+s]) for d in range(0,ncols,s)]) R.append(fr_V(v)) # construct a generator matrix m = [] col_index = D.support() for w in R: row = [] for p in col_index: res = w.residue(p).trace() # lies in constant base field c = subfield(res) # as w is Cartier fixed row.append(c) m.append(row) self._generator_matrix = matrix(m).row_space().basis_matrix() self._pls = tuple(pls) self._G = G self._r = r self._function_field = F self._registered_encoders['GeneratorMatrix'] = LinearCodeGeneratorMatrixEncoder self._registered_decoders['Syndrome'] = LinearCodeSyndromeDecoder super().__init__(subfield, n, default_encoder_name='GeneratorMatrix', default_decoder_name='Syndrome') def __eq__(self, other): """ Test equality of ``self`` with ``other``. EXAMPLES:: sage: F.<a> = GF(9) sage: P.<x,y,z> = ProjectiveSpace(F, 2); sage: C = Curve(x^3*y + y^3*z + x*z^3) sage: F = C.function_field() sage: pls = F.places() sage: Z, = C(0,0,1).places() sage: pls.remove(Z) sage: c1 = codes.CartierCode(pls, 3*Z) # long time sage: c2 = codes.CartierCode(pls, 1*Z) # long time sage: c1 == c2 # long time False """ if self is other: return True if not isinstance(other, CartierCode): return False return self._pls == other._pls and self._G == other._G and self._r == other._r def __hash__(self): """ Return the hash of ``self``. EXAMPLES:: sage: F.<a> = GF(9) sage: P.<x,y,z> = ProjectiveSpace(F, 2); sage: C = Curve(x^3*y + y^3*z + x*z^3) sage: F = C.function_field() sage: pls = F.places() sage: Z, = C(0,0,1).places() sage: pls.remove(Z) sage: G = 3*Z sage: code = codes.CartierCode(pls, G) # long time sage: {code: 1} # long time {[9, 4] Cartier code over GF(3): 1} """ return hash((self._pls, self._G, self._r)) def _repr_(self): """ Return the string representation of ``self``. EXAMPLES:: sage: F.<a> = GF(9) sage: P.<x,y,z> = ProjectiveSpace(F, 2); sage: C = Curve(x^3*y + y^3*z + x*z^3) sage: F = C.function_field() sage: pls = F.places() sage: Z, = C(0,0,1).places() sage: pls.remove(Z) sage: G = 3*Z sage: codes.CartierCode(pls, G) # long time [9, 4] Cartier code over GF(3) """ return "[{}, {}] Cartier code over GF({})".format( self.length(), self.dimension(), self.base_field().cardinality()) def _latex_(self): r""" Return the latex representation of ``self``. EXAMPLES:: sage: F.<a> = GF(9) sage: P.<x,y,z> = ProjectiveSpace(F, 2); sage: C = Curve(x^3*y + y^3*z + x*z^3) sage: F = C.function_field() sage: pls = F.places() sage: Z, = C(0,0,1).places() sage: pls.remove(Z) sage: G = 3*Z sage: code = codes.CartierCode(pls, G) # long time sage: latex(code) # long time [9, 4]\text{ Cartier code over }\Bold{F}_{3} """ return r"[{}, {}]\text{{ Cartier code over }}{}".format( self.length(), self.dimension(), self.base_field()._latex_()) def generator_matrix(self): r""" Return a generator matrix of the Cartier code. EXAMPLES:: sage: F.<a> = GF(9) sage: P.<x,y,z> = ProjectiveSpace(F, 2); sage: C = Curve(x^3*y + y^3*z + x*z^3) sage: F = C.function_field() sage: pls = F.places() sage: Z, = C(0,0,1).places() sage: pls.remove(Z) sage: G = 3*Z sage: code = codes.CartierCode(pls, G) # long time sage: code.generator_matrix() # long time [1 0 0 2 2 0 2 2 0] [0 1 0 2 2 0 2 2 0] [0 0 1 0 0 0 0 0 2] [0 0 0 0 0 1 0 0 2] """ return self._generator_matrix def designed_distance(self): """ Return the designed distance of the Cartier code. The designed distance is that of the differential code of which the Cartier code is a subcode. EXAMPLES:: sage: F.<a> = GF(9) sage: P.<x,y,z> = ProjectiveSpace(F, 2); sage: C = Curve(x^3*y + y^3*z + x*z^3) sage: F = C.function_field() sage: pls = F.places() sage: Z, = C(0,0,1).places() sage: pls.remove(Z) sage: G = 3*Z sage: code = codes.CartierCode(pls, G) # long time sage: code.designed_distance() # long time 1 """ if self.dimension() == 0: raise ValueError("not defined for zero code") d = self._G.degree() - 2 * self._function_field.genus() + 2 return d if d > 0 else 1
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/coding/ag_code.py
0.887394
0.55923
ag_code.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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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://trac.sagemath.org/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://trac.sagemath.org/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/structure/support_view.py
0.913792
0.749087
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://trac.sagemath.org/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/structure/graphics_file.py
0.558447
0.249242
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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/structure/proof/proof.py
0.89219
0.614365
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 '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-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/typeset/symbols.py
0.885179
0.489076
symbols.py
pypi
r""" Catalog of matroids A module containing constructors for several common matroids. A list of all matroids in this module is available via tab completion. Let ``<tab>`` indicate pressing the :kbd:`Tab` key. So begin by typing ``matroids.<tab>`` to see the various constructions available. Many special matroids can be accessed from the submenu ``matroids.named_matroids.<tab>``. To create a custom matroid using a variety of inputs, see the function :func:`Matroid() <sage.matroids.constructor.Matroid>`. - Parametrized matroid constructors - :func:`matroids.AG <sage.matroids.catalog.AG>` - :func:`matroids.CompleteGraphic <sage.matroids.catalog.CompleteGraphic>` - :func:`matroids.PG <sage.matroids.catalog.PG>` - :func:`matroids.Uniform <sage.matroids.catalog.Uniform>` - :func:`matroids.Wheel <sage.matroids.catalog.Wheel>` - :func:`matroids.Whirl <sage.matroids.catalog.Whirl>` - Named matroids (``matroids.named_matroids.<tab>``) - :func:`matroids.named_matroids.AG23minus <sage.matroids.catalog.AG23minus>` - :func:`matroids.named_matroids.AG32prime <sage.matroids.catalog.AG32prime>` - :func:`matroids.named_matroids.BetsyRoss <sage.matroids.catalog.BetsyRoss>` - :func:`matroids.named_matroids.Block_9_4 <sage.matroids.catalog.Block_9_4>` - :func:`matroids.named_matroids.Block_10_5 <sage.matroids.catalog.Block_10_5>` - :func:`matroids.named_matroids.D16 <sage.matroids.catalog.D16>` - :func:`matroids.named_matroids.ExtendedBinaryGolayCode <sage.matroids.catalog.ExtendedBinaryGolayCode>` - :func:`matroids.named_matroids.ExtendedTernaryGolayCode <sage.matroids.catalog.ExtendedTernaryGolayCode>` - :func:`matroids.named_matroids.F8 <sage.matroids.catalog.F8>` - :func:`matroids.named_matroids.Fano <sage.matroids.catalog.Fano>` - :func:`matroids.named_matroids.J <sage.matroids.catalog.J>` - :func:`matroids.named_matroids.K33dual <sage.matroids.catalog.K33dual>` - :func:`matroids.named_matroids.L8 <sage.matroids.catalog.L8>` - :func:`matroids.named_matroids.N1 <sage.matroids.catalog.N1>` - :func:`matroids.named_matroids.N2 <sage.matroids.catalog.N2>` - :func:`matroids.named_matroids.NonFano <sage.matroids.catalog.NonFano>` - :func:`matroids.named_matroids.NonPappus <sage.matroids.catalog.NonPappus>` - :func:`matroids.named_matroids.NonVamos <sage.matroids.catalog.NonVamos>` - :func:`matroids.named_matroids.NotP8 <sage.matroids.catalog.NotP8>` - :func:`matroids.named_matroids.O7 <sage.matroids.catalog.O7>` - :func:`matroids.named_matroids.P6 <sage.matroids.catalog.P6>` - :func:`matroids.named_matroids.P7 <sage.matroids.catalog.P7>` - :func:`matroids.named_matroids.P8 <sage.matroids.catalog.P8>` - :func:`matroids.named_matroids.P8pp <sage.matroids.catalog.P8pp>` - :func:`matroids.named_matroids.P9 <sage.matroids.catalog.P9>` - :func:`matroids.named_matroids.Pappus <sage.matroids.catalog.Pappus>` - :func:`matroids.named_matroids.Q6 <sage.matroids.catalog.Q6>` - :func:`matroids.named_matroids.Q8 <sage.matroids.catalog.Q8>` - :func:`matroids.named_matroids.Q10 <sage.matroids.catalog.Q10>` - :func:`matroids.named_matroids.R6 <sage.matroids.catalog.R6>` - :func:`matroids.named_matroids.R8 <sage.matroids.catalog.R8>` - :func:`matroids.named_matroids.R9A <sage.matroids.catalog.R9A>` - :func:`matroids.named_matroids.R9B <sage.matroids.catalog.R9B>` - :func:`matroids.named_matroids.R10 <sage.matroids.catalog.R10>` - :func:`matroids.named_matroids.R12 <sage.matroids.catalog.R12>` - :func:`matroids.named_matroids.S8 <sage.matroids.catalog.S8>` - :func:`matroids.named_matroids.T8 <sage.matroids.catalog.T8>` - :func:`matroids.named_matroids.T12 <sage.matroids.catalog.T12>` - :func:`matroids.named_matroids.TernaryDowling3 <sage.matroids.catalog.TernaryDowling3>` - :func:`matroids.named_matroids.Terrahawk <sage.matroids.catalog.Terrahawk>` - :func:`matroids.named_matroids.TicTacToe <sage.matroids.catalog.TicTacToe>` - :func:`matroids.named_matroids.Vamos <sage.matroids.catalog.Vamos>` """ # Do not add code to this file, only imports. # Workaround for help in the notebook (needs parentheses in this file) # user-accessible: from sage.matroids.catalog import AG, CompleteGraphic, PG, Uniform, Wheel, Whirl from sage.matroids import named_matroids
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/matroids/matroids_catalog.py
0.833968
0.861072
matroids_catalog.py
pypi
r""" Rolfsen database of knots with at most 10 crossings. Each entry is indexed by a pair `(n, k)` where `n` is the crossing number and `k` is the index in the table. Knots are described by words in braids groups, more precisely by pairs `(m, w)` where `m` is the number of strands and `w` is a list of indices of generators (negative for the inverses). This data has been obtained from the [KnotAtlas]_ , with the kind permission of Dror Bar-Natan. All knots in the Rolfsen table are depicted nicely in the following page: http://katlas.math.toronto.edu/wiki/The_Rolfsen_Knot_Table .. NOTE:: Some of the knots are not represented by a diagram with the minimal number of crossings. .. TODO:: - Extend the table to knots with more crossings. - Do something similar for links using http://katlas.org/wiki/The_Thistlethwaite_Link_Table """ small_knots_table = { (0, 1): (1, []), (3, 1): (2, [-1,-1,-1]), (4, 1): (3, [-1,2,-1,2]), (5, 1): (2, [-1,-1,-1,-1,-1]), (5, 2): (3, [-1,-1,-1,-2,1,-2]), (6, 1): (4, [-1,-1,-2,1,3,-2,3]), (6, 2): (3, [-1,-1,-1,2,-1,2]), (6, 3): (3, [-1,-1,2,-1,2,2]), (7, 1): (2, [-1,-1,-1,-1,-1,-1,-1]), (7, 2): (4, [-1,-1,-1,-2,1,-2,-3,2,-3]), (7, 3): (3, [1,1,1,1,1,2,-1,2]), (7, 4): (4, [1,1,2,-1,2,2,3,-2,3]), (7, 5): (3, [-1,-1,-1,-1,-2,1,-2,-2]), (7, 6): (4, [-1,-1,2,-1,-3,2,-3]), (7, 7): (4, [1,-2,1,-2,3,-2,3]), (8, 1): (5, [-1,-1,-2,1,-2,-3,2,4,-3,4]), (8, 2): (3, [-1,-1,-1,-1,-1,2,-1,2]), (8, 3): (5, [-1,-1,-2,1,3,-2,3,4,-3,4]), (8, 4): (4, [-1,-1,-1,2,-1,2,3,-2,3]), (8, 5): (3, [1,1,1,-2,1,1,1,-2]), (8, 6): (4, [-1,-1,-1,-1,-2,1,3,-2,3]), (8, 7): (3, [1,1,1,1,-2,1,-2,-2]), (8, 8): (4, [1,1,1,2,-1,-3,2,-3,-3]), (8, 9): (3, [-1,-1,-1,2,-1,2,2,2]), (8, 10): (3, [1,1,1,-2,1,1,-2,-2]), (8, 11): (4, [-1,-1,-2,1,-2,-2,3,-2,3]), (8, 12): (5, [-1,2,-1,-3,2,4,-3,4]), (8, 13): (4, [-1,-1,2,-1,2,2,3,-2,3]), (8, 14): (4, [-1,-1,-1,-2,1,-2,3,-2,3]), (8, 15): (4, [-1,-1,2,-1,-3,-2,-2,-2,-3]), (8, 16): (3, [-1,-1,2,-1,-1,2,-1,2]), (8, 17): (3, [-1,-1,2,-1,2,-1,2,2]), (8, 18): (3, [-1,2,-1,2,-1,2,-1,2]), (8, 19): (3, [1,1,1,2,1,1,1,2]), (8, 20): (3, [1,1,1,-2,-1,-1,-1,-2]), (8, 21): (3, [-1,-1,-1,-2,1,1,-2,-2]), (9, 1): (2, [-1,-1,-1,-1,-1,-1,-1,-1,-1]), (9, 2): (5, [-1,-1,-1,-2,1,-2,-3,2,-3,-4,3,-4]), (9, 3): (3, [1,1,1,1,1,1,1,2,-1,2]), (9, 4): (4, [-1,-1,-1,-1,-1,-2,1,-2,-3,2,-3]), (9, 5): (5, [1,1,2,-1,2,2,3,-2,3,4,-3,4]), (9, 6): (3, [-1,-1,-1,-1,-1,-1,-2,1,-2,-2]), (9, 7): (4, [-1,-1,-1,-1,-2,1,-2,-3,2,-3,-3]), (9, 8): (5, [-1,-1,2,-1,2,3,-2,-4,3,-4]), (9, 9): (3, [-1,-1,-1,-1,-1,-2,1,-2,-2,-2]), (9, 10): (4, [1,1,2,-1,2,2,2,2,3,-2,3]), (9, 11): (4, [1,1,1,1,-2,1,3,-2,3]), (9, 12): (5, [-1,-1,2,-1,-3,2,-3,-4,3,-4]), (9, 13): (4, [1,1,1,1,2,-1,2,2,3,-2,3]), (9, 14): (5, [1,1,2,-1,-3,2,-3,4,-3,4]), (9, 15): (5, [1,1,1,2,-1,-3,2,4,-3,4]), (9, 16): (3, [1,1,1,1,2,2,-1,2,2,2]), (9, 17): (4, [1,-2,1,-2,-2,-2,3,-2,3]), (9, 18): (4, [-1,-1,-1,-2,1,-2,-2,-2,-3,2,-3]), (9, 19): (5, [1,-2,1,-2,-2,-3,2,4,-3,4]), (9, 20): (4, [-1,-1,-1,2,-1,-3,2,-3,-3]), (9, 21): (5, [1,1,2,-1,2,-3,2,4,-3,4]), (9, 22): (4, [-1,2,-1,2,-3,2,2,2,-3]), (9, 23): (4, [-1,-1,-1,-2,1,-2,-2,-3,2,-3,-3]), (9, 24): (4, [-1,-1,2,-1,-3,2,2,2,-3]), (9, 25): (5, [-1,-1,2,-1,-3,-2,-2,4,-3,4]), (9, 26): (4, [1,1,1,-2,1,-2,3,-2,3]), (9, 27): (4, [-1,-1,2,-1,2,2,-3,2,-3]), (9, 28): (4, [-1,-1,2,-1,-3,2,2,-3,-3]), (9, 29): (4, [1,-2,-2,3,-2,1,-2,3,-2]), (9, 30): (4, [-1,-1,2,2,-1,2,-3,2,-3]), (9, 31): (4, [-1,-1,2,-1,2,-3,2,-3,-3]), (9, 32): (4, [1,1,-2,1,-2,1,3,-2,3]), (9, 33): (4, [-1,2,-1,2,2,-1,-3,2,-3]), (9, 34): (4, [-1,2,-1,2,-3,2,-1,2,-3]), (9, 35): (5, [-1,-1,-2,1,-2,-2,-3,2,2,-4,3,-2,-4,-3]), (9, 36): (4, [1,1,1,-2,1,1,3,-2,3]), (9, 37): (5, [-1,-1,2,-1,-3,2,1,4,-3,2,-3,4]), (9, 38): (4, [-1,-1,-2,-2,3,-2,1,-2,-3,-3,-2]), (9, 39): (5, [1,1,2,-1,-3,-2,1,4,3,-2,3,4]), (9, 40): (4, [-1,2,-1,-3,2,-1,-3,2,-3]), (9, 41): (5, [-1,-1,-2,1,3,2,2,-4,-3,2,-3,-4]), (9, 42): (4, [1,1,1,-2,-1,-1,3,-2,3]), (9, 43): (4, [1,1,1,2,1,1,-3,2,-3]), (9, 44): (4, [-1,-1,-1,-2,1,1,3,-2,3]), (9, 45): (4, [-1,-1,-2,1,-2,-1,-3,2,-3]), (9, 46): (4, [-1,2,-1,2,-3,-2,1,-2,-3]), (9, 47): (4, [-1,2,-1,2,3,2,-1,2,3]), (9, 48): (4, [1,1,2,-1,2,1,-3,2,-1,2,-3]), (9, 49): (4, [1,1,2,1,1,-3,2,-1,2,3,3]), (10, 1): (6, [-1,-1,-2,1,-2,-3,2,-3,-4,3,5,-4,5]), (10, 2): (3, [-1,-1,-1,-1,-1,-1,-1,2,-1,2]), (10, 3): (6, [-1,-1,-2,1,-2,-3,2,4,-3,4,5,-4,5]), (10, 4): (5, [-1,-1,-1,2,-1,2,3,-2,3,4,-3,4]), (10, 5): (3, [1,1,1,1,1,1,-2,1,-2,-2]), (10, 6): (4, [-1,-1,-1,-1,-1,-1,-2,1,3,-2,3]), (10, 7): (5, [-1,-1,-2,1,-2,-3,2,-3,-3,4,-3,4]), (10, 8): (4, [-1,-1,-1,-1,-1,2,-1,2,3,-2,3]), (10, 9): (3, [1,1,1,1,1,-2,1,-2,-2,-2]), (10, 10): (5, [-1,-1,2,-1,2,2,3,-2,3,4,-3,4]), (10, 11): (5, [-1,-1,-1,-1,-2,1,3,-2,3,4,-3,4]), (10, 12): (4, [1,1,1,1,1,2,-1,-3,2,-3,-3]), (10, 13): (6, [-1,-1,-2,1,3,-2,-4,3,5,-4,5]), (10, 14): (4, [-1,-1,-1,-1,-1,-2,1,-2,3,-2,3]), (10, 15): (4, [1,1,1,1,-2,1,-2,-3,2,-3,-3]), (10, 16): (5, [1,1,2,-1,2,2,-3,2,-3,-4,3,-4]), (10, 17): (3, [-1,-1,-1,-1,2,-1,2,2,2,2]), (10, 18): (5, [-1,-1,-1,-2,1,-2,3,-2,3,4,-3,4]), (10, 19): (4, [-1,-1,-1,-1,2,-1,2,2,3,-2,3]), (10, 20): (5, [-1,-1,-1,-1,-2,1,-2,-3,2,4,-3,4]), (10, 21): (4, [-1,-1,-2,1,-2,-2,-2,-2,3,-2,3]), (10, 22): (4, [1,1,1,1,2,-1,-3,2,-3,-3,-3]), (10, 23): (4, [-1,-1,2,-1,2,2,2,2,3,-2,3]), (10, 24): (5, [-1,-1,-2,1,-2,-2,-2,-3,2,4,-3,4]), (10, 25): (4, [-1,-1,-1,-1,-2,1,-2,-2,3,-2,3]), (10, 26): (4, [-1,-1,-1,2,-1,2,2,2,3,-2,3]), (10, 27): (4, [-1,-1,-1,-1,-2,1,-2,3,-2,3,3]), (10, 28): (5, [1,1,2,-1,2,2,3,-2,-4,3,-4,-4]), (10, 29): (5, [-1,-1,-1,2,-1,-3,2,4,-3,4]), (10, 30): (5, [-1,-1,-2,1,-2,-2,-3,2,-3,4,-3,4]), (10, 31): (5, [-1,-1,-1,-2,1,3,-2,3,3,4,-3,4]), (10, 32): (4, [1,1,1,-2,1,-2,-2,-3,2,-3,-3]), (10, 33): (5, [-1,-1,-2,1,-2,3,-2,3,3,4,-3,4]), (10, 34): (5, [1,1,1,2,-1,2,3,-2,-4,3,-4,-4]), (10, 35): (6, [-1,2,-1,2,3,-2,-4,3,5,-4,5]), (10, 36): (5, [-1,-1,-1,-2,1,-2,-3,2,-3,4,-3,4]), (10, 37): (5, [-1,-1,-1,-2,1,3,-2,3,4,-3,4,4]), (10, 38): (5, [-1,-1,-1,-2,1,-2,-2,-3,2,4,-3,4]), (10, 39): (4, [-1,-1,-1,-2,1,-2,-2,-2,3,-2,3]), (10, 40): (4, [1,1,1,2,-1,2,2,-3,2,-3,-3]), (10, 41): (5, [1,-2,1,-2,-2,3,-2,-4,3,-4]), (10, 42): (5, [-1,-1,2,-1,2,-3,2,4,-3,4]), (10, 43): (5, [-1,-1,2,-1,-3,2,4,-3,4,4]), (10, 44): (5, [-1,-1,2,-1,-3,2,-3,4,-3,4]), (10, 45): (5, [-1,2,-1,2,-3,2,-3,4,-3,4]), (10, 46): (3, [1,1,1,1,1,-2,1,1,1,-2]), (10, 47): (3, [1,1,1,1,1,-2,1,1,-2,-2]), (10, 48): (3, [-1,-1,-1,-1,2,2,-1,2,2,2]), (10, 49): (4, [-1,-1,-1,-1,2,-1,-3,-2,-2,-2,-3]), (10, 50): (4, [1,1,2,-1,2,2,-3,2,2,2,-3]), (10, 51): (4, [1,1,2,-1,2,2,-3,2,2,-3,-3]), (10, 52): (4, [1,1,1,-2,1,1,-2,-2,-3,2,-3]), (10, 53): (5, [-1,-1,-2,1,-2,3,-2,-4,-3,-3,-3,-4]), (10, 54): (4, [1,1,1,-2,1,1,-2,-3,2,-3,-3]), (10, 55): (5, [-1,-1,-1,-2,1,3,-2,-4,-3,-3,-3,-4]), (10, 56): (4, [1,1,1,2,-1,2,-3,2,2,2,-3]), (10, 57): (4, [1,1,1,2,-1,2,-3,2,2,-3,-3]), (10, 58): (6, [1,-2,1,3,-2,-4,-3,-3,5,-4,5]), (10, 59): (5, [-1,2,-1,2,-3,2,2,4,-3,4]), (10, 60): (5, [-1,2,-1,2,2,-3,2,-3,-2,-4,3,-4]), (10, 61): (4, [1,1,1,-2,1,1,1,-2,-3,2,-3]), (10, 62): (3, [1,1,1,1,-2,1,1,1,-2,-2]), (10, 63): (5, [-1,-1,2,-1,-3,-2,-2,-2,-3,-4,3,-4]), (10, 64): (3, [1,1,1,-2,1,1,1,-2,-2,-2]), (10, 65): (4, [1,1,2,-1,2,-3,2,2,2,-3,-3]), (10, 66): (4, [-1,-1,-1,2,-1,-3,-2,-2,-2,-3,-3]), (10, 67): (5, [-1,-1,-1,-2,1,-2,-3,2,2,4,-3,-2,4,-3]), (10, 68): (5, [1,1,-2,1,-2,-2,-3,2,2,-4,3,-2,-4,-3]), (10, 69): (5, [1,1,2,-1,-3,2,1,4,-3,2,-3,4]), (10, 70): (5, [-1,2,-1,-3,2,2,2,4,-3,4]), (10, 71): (5, [-1,-1,2,-1,-3,2,2,4,-3,4]), (10, 72): (4, [1,1,1,1,2,2,-1,2,-3,2,-3]), (10, 73): (5, [-1,-1,-2,1,-2,-1,3,-2,3,-4,3,-4]), (10, 74): (5, [-1,-1,-2,1,-2,-2,-3,2,2,4,-3,-2,4,-3]), (10, 75): (5, [1,-2,1,-2,3,-2,-2,4,-3,2,4,3]), (10, 76): (4, [1,1,1,1,2,-1,-3,2,2,2,-3]), (10, 77): (4, [1,1,1,1,2,-1,-3,2,2,-3,-3]), (10, 78): (5, [-1,-1,-2,1,-2,-1,3,-2,-4,3,-4,-4]), (10, 79): (3, [-1,-1,-1,2,2,-1,-1,2,2,2]), (10, 80): (4, [-1,-1,-1,2,-1,-1,-3,-2,-2,-2,-3]), (10, 81): (5, [1,1,-2,1,3,2,2,-4,-3,-3,-3,-4]), (10, 82): (3, [-1,-1,-1,-1,2,-1,2,-1,2,2]), (10, 83): (4, [1,1,2,-1,2,-3,2,2,-3,2,-3]), (10, 84): (4, [1,1,1,2,-1,-3,2,2,-3,2,-3]), (10, 85): (3, [-1,-1,-1,-1,2,-1,-1,2,-1,2]), (10, 86): (4, [-1,-1,2,-1,2,-1,2,2,3,-2,3]), (10, 87): (4, [1,1,1,2,-1,-3,2,-3,2,-3,-3]), (10, 88): (5, [-1,2,-1,-3,2,-3,2,4,-3,4]), (10, 89): (5, [-1,2,-1,2,3,-2,-1,-4,-3,2,-3,-4]), (10, 90): (4, [-1,-1,2,-1,2,3,-2,-1,3,2,2]), (10, 91): (3, [-1,-1,-1,2,-1,2,2,-1,2,2]), (10, 92): (4, [1,1,1,2,2,-3,2,-1,2,-3,2]), (10, 93): (4, [-1,-1,2,-1,-1,2,-1,2,3,-2,3]), (10, 94): (3, [1,1,1,-2,1,1,-2,-2,1,-2]), (10, 95): (4, [-1,-1,2,2,-3,2,-1,2,3,3,2]), (10, 96): (5, [-1,2,1,-3,2,1,-3,4,-3,2,-3,4]), (10, 97): (5, [1,1,2,-1,2,1,-3,2,-1,2,3,-4,3,-4]), (10, 98): (4, [-1,-1,-2,-2,3,-2,1,-2,-2,3,-2]), (10, 99): (3, [-1,-1,2,-1,-1,2,2,-1,2,2]), (10, 100): (3, [-1,-1,-1,2,-1,-1,2,-1,-1,2]), (10, 101): (5, [1,1,1,2,-1,3,-2,1,3,2,2,4,-3,4]), (10, 102): (4, [-1,-1,2,-1,-3,2,-1,2,2,3,3]), (10, 103): (4, [-1,-1,-2,1,3,-2,-2,3,-2,-2,3]), (10, 104): (3, [-1,-1,-1,2,2,-1,2,-1,2,2]), (10, 105): (5, [1,1,-2,1,3,2,2,-4,-3,2,-3,-4]), (10, 106): (3, [1,1,1,-2,1,-2,1,1,-2,-2]), (10, 107): (5, [-1,-1,2,-1,3,2,2,-4,3,-2,3,-4]), (10, 108): (4, [1,1,-2,1,1,3,-2,1,-2,-3,-3]), (10, 109): (3, [-1,-1,2,-1,2,2,-1,-1,2,2]), (10, 110): (5, [-1,2,-1,-3,-2,-2,-2,4,3,-2,3,4]), (10, 111): (4, [1,1,2,2,-3,2,2,-1,2,-3,2]), (10, 112): (3, [-1,-1,-1,2,-1,2,-1,2,-1,2]), (10, 113): (4, [1,1,1,2,-3,2,-1,2,-3,2,-3]), (10, 114): (4, [-1,-1,-2,1,3,-2,3,-2,3,-2,3]), (10, 115): (5, [1,-2,1,3,2,2,-4,-3,2,-3,-3,-4]), (10, 116): (3, [-1,-1,2,-1,-1,2,-1,2,-1,2]), (10, 117): (4, [1,1,2,2,-3,2,-1,2,-3,2,-3]), (10, 118): (3, [1,1,-2,1,-2,1,-2,-2,1,-2]), (10, 119): (4, [-1,-1,2,-1,-3,2,-1,2,3,3,2]), (10, 120): (5, [-1,-1,-2,1,3,2,-1,-4,-3,-2,-2,-3,-3,-4]), (10, 121): (4, [-1,-1,-2,3,-2,1,-2,3,-2,3,-2]), (10, 122): (4, [1,1,2,-3,2,-1,-3,2,-3,2,-3]), (10, 123): (3, [-1,2,-1,2,-1,2,-1,2,-1,2]), (10, 124): (3, [1,1,1,1,1,2,1,1,1,2]), (10, 125): (3, [1,1,1,1,1,-2,-1,-1,-1,-2]), (10, 126): (3, [-1,-1,-1,-1,-1,-2,1,1,1,-2]), (10, 127): (3, [-1,-1,-1,-1,-1,-2,1,1,-2,-2]), (10, 128): (4, [1,1,1,2,1,1,2,2,3,-2,3]), (10, 129): (4, [1,1,1,-2,-1,-1,3,-2,-1,3,-2]), (10, 130): (4, [1,1,1,-2,-1,-1,-2,-2,-3,2,-3]), (10, 131): (4, [-1,-1,-1,-2,1,1,-2,-2,-3,2,-3]), (10, 132): (4, [1,1,1,-2,-1,-1,-2,-3,2,-3,-3]), (10, 133): (4, [-1,-1,-1,-2,1,1,-2,-3,2,-3,-3]), (10, 134): (4, [1,1,1,2,1,1,2,3,-2,3,3]), (10, 135): (4, [1,1,1,2,-1,2,-3,-2,-2,-2,-3]), (10, 136): (5, [1,-2,1,-2,-3,2,2,4,-3,4]), (10, 137): (5, [-1,2,-1,2,-3,-2,-2,4,-3,4]), (10, 138): (5, [-1,2,-1,2,3,2,2,-4,3,-4]), (10, 139): (3, [1,1,1,1,2,1,1,1,2,2]), (10, 140): (4, [1,1,1,-2,-1,-1,-1,-2,-3,2,-3]), (10, 141): (3, [1,1,1,1,-2,-1,-1,-1,-2,-2]), (10, 142): (4, [1,1,1,2,1,1,1,2,3,-2,3]), (10, 143): (3, [-1,-1,-1,-1,-2,1,1,1,-2,-2]), (10, 144): (4, [-1,-1,-2,1,-2,-1,3,-2,-1,3,2]), (10, 145): (4, [-1,-1,-2,1,-2,-1,-3,-2,1,-2,-3]), (10, 146): (4, [-1,-1,2,-1,2,1,-3,2,-1,2,-3]), (10, 147): (4, [1,1,1,-2,1,-2,-3,2,-1,2,-3]), (10, 148): (3, [-1,-1,-1,-1,-2,1,1,-2,1,-2]), (10, 149): (3, [-1,-1,-1,-1,-2,1,-2,1,-2,-2]), (10, 150): (4, [1,1,1,-2,1,1,3,-2,-1,3,2]), (10, 151): (4, [1,1,1,2,-1,-1,3,-2,1,3,-2]), (10, 152): (3, [-1,-1,-1,-2,-2,-1,-1,-2,-2,-2]), (10, 153): (4, [-1,-1,-1,-2,-1,-1,3,2,2,2,3]), (10, 154): (4, [1,1,2,-1,2,1,3,2,2,2,3]), (10, 155): (3, [1,1,1,2,-1,-1,2,-1,-1,2]), (10, 156): (4, [-1,-1,-1,2,1,1,-3,-2,1,-2,-3]), (10, 157): (3, [1,1,1,2,2,-1,2,-1,2,2]), (10, 158): (4, [-1,-1,-1,-2,1,1,3,2,-1,2,3]), (10, 159): (3, [-1,-1,-1,-2,1,-2,1,1,-2,-2]), (10, 160): (4, [1,1,1,2,1,1,-3,2,-1,2,-3]), (10, 161): (3, [-1,-1,-1,-2,1,-2,-1,-1,-2,-2]), (10, 162): (4, [-1,-1,-2,1,1,-2,-2,-1,3,-2,3]), (10, 163): (4, [1,1,-2,-1,-1,3,2,-1,2,2,3]), (10, 164): (4, [1,1,-2,1,-2,-2,-3,2,-1,2,-3]), (10, 165): (4, [1,1,2,-1,-3,2,-1,2,3,3,2]) }
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/knots/knot_table.py
0.705075
0.641387
knot_table.py
pypi
r""" Shard intersection order This file builds a combinatorial version of the shard intersection order of type A (in the classification of finite Coxeter groups). This is a lattice on the set of permutations, closely related to noncrossing partitions and the weak order. For technical reasons, the elements of the posets are not permutations, but can be easily converted from and to permutations:: sage: from sage.combinat.shard_order import ShardPosetElement sage: p0 = Permutation([1,3,4,2]) sage: e0 = ShardPosetElement(p0); e0 (1, 3, 4, 2) sage: Permutation(list(e0)) == p0 True .. SEEALSO:: A general implementation for all finite Coxeter groups is available as :meth:`~sage.categories.finite_coxeter_groups.FiniteCoxeterGroups.ParentMethods.shard_poset` REFERENCES: .. [Banc2011] \E. E. Bancroft, *Shard Intersections and Cambrian Congruence Classes in Type A.*, Ph.D. Thesis, North Carolina State University. 2011. .. [Pete2013] \T. Kyle Petersen, *On the shard intersection order of a Coxeter group*, SIAM J. Discrete Math. 27 (2013), no. 4, 1880-1912. .. [Read2011] \N. Reading, *Noncrossing partitions and the shard intersection order*, J. Algebraic Combin., 33 (2011), 483-530. """ from sage.combinat.posets.posets import Poset from sage.graphs.digraph import DiGraph from sage.combinat.permutation import Permutations class ShardPosetElement(tuple): r""" An element of the shard poset. This is basically a permutation with extra stored arguments: - ``p`` -- the permutation itself as a tuple - ``runs`` -- the decreasing runs as a tuple of tuples - ``run_indices`` -- a list ``integer -> index of the run`` - ``dpg`` -- the transitive closure of the shard preorder graph - ``spg`` -- the transitive reduction of the shard preorder graph These elements can easily be converted from and to permutations:: sage: from sage.combinat.shard_order import ShardPosetElement sage: p0 = Permutation([1,3,4,2]) sage: e0 = ShardPosetElement(p0); e0 (1, 3, 4, 2) sage: Permutation(list(e0)) == p0 True """ def __new__(cls, p): r""" Initialization of the underlying tuple TESTS:: sage: from sage.combinat.shard_order import ShardPosetElement sage: ShardPosetElement(Permutation([1,3,4,2])) (1, 3, 4, 2) """ return tuple.__new__(cls, p) def __init__(self, p): r""" INPUT: - ``p`` - a permutation EXAMPLES:: sage: from sage.combinat.shard_order import ShardPosetElement sage: p0 = Permutation([1,3,4,2]) sage: e0 = ShardPosetElement(p0); e0 (1, 3, 4, 2) sage: e0.dpg Transitive closure of : Digraph on 3 vertices sage: e0.spg Digraph on 3 vertices """ self.runs = p.decreasing_runs(as_tuple=True) self.run_indices = [None] * (len(p) + 1) for i, bloc in enumerate(self.runs): for j in bloc: self.run_indices[j] = i G = shard_preorder_graph(self.runs) self.dpg = G.transitive_closure() self.spg = G.transitive_reduction() def __le__(self, other): """ Comparison between two elements of the poset. This is the core function in the implementation of the shard intersection order. One first compares the number of runs, then the set partitions, then the pre-orders. EXAMPLES:: sage: from sage.combinat.shard_order import ShardPosetElement sage: p0 = Permutation([1,3,4,2]) sage: p1 = Permutation([1,4,3,2]) sage: e0 = ShardPosetElement(p0) sage: e1 = ShardPosetElement(p1) sage: e0 <= e1 True sage: e1 <= e0 False sage: p0 = Permutation([1,2,5,7,3,4,6,8]) sage: p1 = Permutation([2,5,7,3,4,8,6,1]) sage: e0 = ShardPosetElement(p0) sage: e1 = ShardPosetElement(p1) sage: e0 <= e1 True sage: e1 <= e0 False """ if type(self) is not type(other) or len(self) != len(other): raise TypeError("these are not comparable") if self.runs == other.runs: return True # r1 must have less runs than r0 if len(other.runs) > len(self.runs): return False dico1 = other.run_indices # conversion: index of run in r0 -> index of run in r1 dico0 = [None] * len(self.runs) for i, bloc in enumerate(self.runs): j0 = dico1[bloc[0]] for k in bloc: if dico1[k] != j0: return False dico0[i] = j0 # at this point, the set partitions given by tuples are comparable dg0 = self.spg dg1 = other.dpg for i, j in dg0.edge_iterator(labels=False): if dico0[i] != dico0[j] and not dg1.has_edge(dico0[i], dico0[j]): return False return True def shard_preorder_graph(runs): """ Return the preorder attached to a tuple of decreasing runs. This is a directed graph, whose vertices correspond to the runs. There is an edge from a run `R` to a run `S` if `R` is before `S` in the list of runs and the two intervals defined by the initial and final indices of `R` and `S` overlap. This only depends on the initial and final indices of the runs. For this reason, this input can also be given in that shorten way. INPUT: - a tuple of tuples, the runs of a permutation, or - a tuple of pairs `(i,j)`, each one standing for a run from `i` to `j`. OUTPUT: a directed graph, with vertices labelled by integers EXAMPLES:: sage: from sage.combinat.shard_order import shard_preorder_graph sage: s = Permutation([2,8,3,9,6,4,5,1,7]) sage: def cut(lr): ....: return tuple((r[0], r[-1]) for r in lr) sage: shard_preorder_graph(cut(s.decreasing_runs())) Digraph on 5 vertices sage: s = Permutation([9,4,3,2,8,6,5,1,7]) sage: P = shard_preorder_graph(s.decreasing_runs()) sage: P.is_isomorphic(digraphs.TransitiveTournament(3)) True """ N = len(runs) dg = DiGraph(N) dg.add_edges((i, j) for i in range(N - 1) for j in range(i + 1, N) if runs[i][-1] < runs[j][0] and runs[j][-1] < runs[i][0]) return dg def shard_poset(n): """ Return the shard intersection order on permutations of size `n`. This is defined on the set of permutations. To every permutation, one can attach a pre-order, using the descending runs and their relative positions. The shard intersection order is given by the implication (or refinement) order on the set of pre-orders defined from all permutations. This can also be seen in a geometrical way. Every pre-order defines a cone in a vector space of dimension `n`. The shard poset is given by the inclusion of these cones. .. SEEALSO:: :func:`~sage.combinat.shard_order.shard_preorder_graph` EXAMPLES:: sage: P = posets.ShardPoset(4); P # indirect doctest Finite poset containing 24 elements sage: P.chain_polynomial() 34*q^4 + 90*q^3 + 79*q^2 + 24*q + 1 sage: P.characteristic_polynomial() q^3 - 11*q^2 + 23*q - 13 sage: P.zeta_polynomial() 17/3*q^3 - 6*q^2 + 4/3*q sage: P.is_self_dual() False """ import operator Sn = [ShardPosetElement(s) for s in Permutations(n)] return Poset([Sn, operator.le], cover_relations=False, facade=True)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/shard_order.py
0.892891
0.734643
shard_order.py
pypi
r""" Combinatorics Introductory material --------------------- - :ref:`sage.combinat.quickref` - :ref:`sage.combinat.tutorial` Thematic indexes ---------------- - :ref:`sage.combinat.algebraic_combinatorics` - :ref:`sage.combinat.chas.all` - :ref:`sage.combinat.cluster_algebra_quiver.all` - :ref:`sage.combinat.crystals.all` - :ref:`sage.combinat.root_system.all` - :ref:`sage.combinat.sf.all` - :class:`~sage.combinat.fully_commutative_elements.FullyCommutativeElements` - :ref:`sage.combinat.counting` - :ref:`sage.combinat.enumerated_sets` - :ref:`sage.combinat.catalog_partitions` - :ref:`sage.combinat.finite_state_machine` - :ref:`sage.combinat.species.all` - :ref:`sage.combinat.designs.all` - :ref:`sage.combinat.posets.all` - :ref:`sage.combinat.words` Utilities --------- - :ref:`sage.combinat.output` - :ref:`sage.combinat.ranker` - :func:`Combinatorial maps <sage.combinat.combinatorial_map.combinatorial_map>` - :ref:`sage.combinat.misc` Related topics -------------- - :ref:`sage.coding` - :ref:`sage.dynamics` - :ref:`sage.graphs` """ from sage.misc.namespace_package import install_doc, install_dict # install the docstring of this module to the containing package install_doc(__package__, __doc__) # install modules quickref and tutorial to the containing package from . import quickref, tutorial install_dict(__package__, {'quickref': quickref, 'tutorial': tutorial}) del quickref, tutorial from sage.misc.lazy_import import lazy_import from .combinat import (CombinatorialClass, CombinatorialObject, MapCombinatorialClass, bell_number, bell_polynomial, bernoulli_polynomial, catalan_number, euler_number, fibonacci, fibonacci_sequence, fibonacci_xrange, lucas_number1, lucas_number2, number_of_tuples, number_of_unordered_tuples, polygonal_number, stirling_number1, stirling_number2, tuples, unordered_tuples) lazy_import('sage.combinat.combinat', ('InfiniteAbstractCombinatorialClass', 'UnionCombinatorialClass', 'FilteredCombinatorialClass'), deprecation=(31545, 'this class is deprecated, do not use')) from .expnums import expnums from sage.combinat.chas.all import * from sage.combinat.crystals.all import * from .rigged_configurations.all import * from sage.combinat.dlx import DLXMatrix, AllExactCovers, OneExactCover # block designs, etc from sage.combinat.designs.all import * # Free modules and friends from .free_module import CombinatorialFreeModule from .debruijn_sequence import DeBruijnSequences from .schubert_polynomial import SchubertPolynomialRing lazy_import('sage.combinat.key_polynomial', 'KeyPolynomialBasis', as_='KeyPolynomials') from .symmetric_group_algebra import SymmetricGroupAlgebra, HeckeAlgebraSymmetricGroupT from .symmetric_group_representations import SymmetricGroupRepresentation, SymmetricGroupRepresentations from .yang_baxter_graph import YangBaxterGraph # Permutations from .permutation import Permutation, Permutations, Arrangements, CyclicPermutations, CyclicPermutationsOfPartition from .affine_permutation import AffinePermutationGroup lazy_import('sage.combinat.colored_permutations', ['ColoredPermutations', 'SignedPermutation', 'SignedPermutations']) from .derangements import Derangements lazy_import('sage.combinat.baxter_permutations', ['BaxterPermutations']) # RSK from .rsk import RSK, RSK_inverse, robinson_schensted_knuth, robinson_schensted_knuth_inverse, InsertionRules # HillmanGrassl lazy_import("sage.combinat.hillman_grassl", ["WeakReversePlanePartition", "WeakReversePlanePartitions"]) # PerfectMatchings from .perfect_matching import PerfectMatching, PerfectMatchings # Integer lists from .integer_lists import IntegerListsLex # Compositions from .composition import Composition, Compositions from .composition_signed import SignedCompositions # Partitions from .partition import (Partition, Partitions, PartitionsInBox, OrderedPartitions, PartitionsGreatestLE, PartitionsGreatestEQ, number_of_partitions) lazy_import('sage.combinat.partition_tuple', ['PartitionTuple', 'PartitionTuples']) lazy_import('sage.combinat.partition_kleshchev', ['KleshchevPartitions']) lazy_import('sage.combinat.skew_partition', ['SkewPartition', 'SkewPartitions']) # Partition algebra from .partition_algebra import SetPartitionsAk, SetPartitionsPk, SetPartitionsTk, SetPartitionsIk, SetPartitionsBk, SetPartitionsSk, SetPartitionsRk, SetPartitionsPRk # Raising operators lazy_import('sage.combinat.partition_shifting_algebras', 'ShiftingOperatorAlgebra') # Diagram algebra from .diagram_algebras import PartitionAlgebra, BrauerAlgebra, TemperleyLiebAlgebra, PlanarAlgebra, PropagatingIdeal # Descent algebra lazy_import('sage.combinat.descent_algebra', 'DescentAlgebra') # Vector Partitions lazy_import('sage.combinat.vector_partition', ['VectorPartition', 'VectorPartitions']) # Similarity class types from .similarity_class_type import PrimarySimilarityClassType, PrimarySimilarityClassTypes, SimilarityClassType, SimilarityClassTypes # Cores from .core import Core, Cores # Tableaux lazy_import('sage.combinat.tableau', ["Tableau", "SemistandardTableau", "StandardTableau", "RowStandardTableau", "IncreasingTableau", "Tableaux", "SemistandardTableaux", "StandardTableaux", "RowStandardTableaux", "IncreasingTableaux"]) from .skew_tableau import SkewTableau, SkewTableaux, StandardSkewTableaux, SemistandardSkewTableaux from .ribbon_shaped_tableau import RibbonShapedTableau, RibbonShapedTableaux, StandardRibbonShapedTableaux from .ribbon_tableau import RibbonTableaux, RibbonTableau, MultiSkewTableaux, MultiSkewTableau, SemistandardMultiSkewTableaux from .composition_tableau import CompositionTableau, CompositionTableaux lazy_import('sage.combinat.tableau_tuple', ['TableauTuple', 'StandardTableauTuple', 'RowStandardTableauTuple', 'TableauTuples', 'StandardTableauTuples', 'RowStandardTableauTuples']) from .k_tableau import WeakTableau, WeakTableaux, StrongTableau, StrongTableaux lazy_import('sage.combinat.lr_tableau', ['LittlewoodRichardsonTableau', 'LittlewoodRichardsonTableaux']) lazy_import('sage.combinat.shifted_primed_tableau', ['ShiftedPrimedTableaux', 'ShiftedPrimedTableau']) # SuperTableaux lazy_import('sage.combinat.super_tableau', ["StandardSuperTableau", "SemistandardSuperTableau", "StandardSuperTableaux", "SemistandardSuperTableaux"]) # Words from .words.all import * lazy_import('sage.combinat.subword', 'Subwords') from .graph_path import GraphPaths # Tuples from .tuple import Tuples, UnorderedTuples # Alternating sign matrices lazy_import('sage.combinat.alternating_sign_matrix', ('AlternatingSignMatrix', 'AlternatingSignMatrices', 'MonotoneTriangles', 'ContreTableaux', 'TruncatedStaircases')) # Decorated Permutations lazy_import('sage.combinat.decorated_permutation', ('DecoratedPermutation', 'DecoratedPermutations')) # Plane Partitions lazy_import('sage.combinat.plane_partition', ('PlanePartition', 'PlanePartitions')) # Parking Functions lazy_import('sage.combinat.non_decreasing_parking_function', ['NonDecreasingParkingFunctions', 'NonDecreasingParkingFunction']) lazy_import('sage.combinat.parking_functions', ['ParkingFunctions', 'ParkingFunction']) # Trees and Tamari interval posets from .ordered_tree import (OrderedTree, OrderedTrees, LabelledOrderedTree, LabelledOrderedTrees) from .binary_tree import (BinaryTree, BinaryTrees, LabelledBinaryTree, LabelledBinaryTrees) lazy_import('sage.combinat.interval_posets', ['TamariIntervalPoset', 'TamariIntervalPosets']) lazy_import('sage.combinat.rooted_tree', ('RootedTree', 'RootedTrees', 'LabelledRootedTree', 'LabelledRootedTrees')) from .combination import Combinations from .set_partition import SetPartition, SetPartitions from .set_partition_ordered import OrderedSetPartition, OrderedSetPartitions lazy_import('sage.combinat.multiset_partition_into_sets_ordered', ['OrderedMultisetPartitionIntoSets', 'OrderedMultisetPartitionsIntoSets']) from .subset import Subsets from .necklace import Necklaces lazy_import('sage.combinat.dyck_word', ('DyckWords', 'DyckWord')) lazy_import('sage.combinat.nu_dyck_word', ('NuDyckWords', 'NuDyckWord')) from .sloane_functions import sloane lazy_import('sage.combinat.superpartition', ('SuperPartition', 'SuperPartitions')) lazy_import('sage.combinat.parallelogram_polyomino', ['ParallelogramPolyomino', 'ParallelogramPolyominoes']) from .root_system.all import * from .sf.all import * from .ncsf_qsym.all import * from .ncsym.all import * lazy_import('sage.combinat.fqsym', 'FreeQuasisymmetricFunctions') from .matrices.all import * # Posets from .posets.all import * # Cluster Algebras and Quivers from .cluster_algebra_quiver.all import * from . import ranker from .integer_vector import IntegerVectors from .integer_vector_weighted import WeightedIntegerVectors from .integer_vectors_mod_permgroup import IntegerVectorsModPermutationGroup lazy_import('sage.combinat.q_analogues', ['gaussian_binomial', 'q_binomial']) from .species.all import * lazy_import('sage.combinat.kazhdan_lusztig', 'KazhdanLusztigPolynomial') lazy_import('sage.combinat.degree_sequences', 'DegreeSequences') lazy_import('sage.combinat.cyclic_sieving_phenomenon', ['CyclicSievingPolynomial', 'CyclicSievingCheck']) lazy_import('sage.combinat.sidon_sets', 'sidon_sets') # Puzzles lazy_import('sage.combinat.knutson_tao_puzzles', 'KnutsonTaoPuzzleSolver') # Gelfand-Tsetlin patterns lazy_import('sage.combinat.gelfand_tsetlin_patterns', ['GelfandTsetlinPattern', 'GelfandTsetlinPatterns']) # Finite State Machines (Automaton, Transducer) lazy_import('sage.combinat.finite_state_machine', ['Automaton', 'Transducer', 'FiniteStateMachine']) lazy_import('sage.combinat.finite_state_machine_generators', ['automata', 'transducers']) # Sequences lazy_import('sage.combinat.binary_recurrence_sequences', 'BinaryRecurrenceSequence') lazy_import('sage.combinat.recognizable_series', 'RecognizableSeriesSpace') lazy_import('sage.combinat.k_regular_sequence', 'kRegularSequenceSpace') # Six Vertex Model lazy_import('sage.combinat.six_vertex_model', 'SixVertexModel') # sine-Gordon Y-systems lazy_import('sage.combinat.sine_gordon', 'SineGordonYsystem') # Fully Packed Loop lazy_import('sage.combinat.fully_packed_loop', ['FullyPackedLoop', 'FullyPackedLoops']) # Subword complex and cluster complex lazy_import('sage.combinat.subword_complex', 'SubwordComplex') lazy_import("sage.combinat.cluster_complex", "ClusterComplex") # Constellations lazy_import('sage.combinat.constellation', ['Constellation', 'Constellations']) # Growth diagrams lazy_import('sage.combinat.growth', 'GrowthDiagram') # Path Tableaux lazy_import('sage.combinat.path_tableaux', 'catalog', as_='path_tableaux')
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/all.py
0.837487
0.643441
all.py
pypi
from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets from sage.misc.misc_c import prod from sage.misc.prandom import random, randrange from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.integer_ring import ZZ from sage.rings.rational_field import QQ from sage.rings.integer import Integer from sage.combinat.combinat import CombinatorialElement from sage.combinat.permutation import Permutation, Permutations class Derangement(CombinatorialElement): r""" A derangement. A derangement on a set `S` is a permutation `\sigma` such that `\sigma(x) \neq x` for all `x \in S`, i.e. `\sigma` is a permutation of `S` with no fixed points. EXAMPLES:: sage: D = Derangements(4) sage: elt = D([4,3,2,1]) sage: TestSuite(elt).run() """ def to_permutation(self): """ Return the permutation corresponding to ``self``. EXAMPLES:: sage: D = Derangements(4) sage: p = D([4,3,2,1]).to_permutation(); p [4, 3, 2, 1] sage: type(p) <class 'sage.combinat.permutation.StandardPermutations_all_with_category.element_class'> sage: D = Derangements([1, 3, 3, 4]) sage: D[0].to_permutation() Traceback (most recent call last): ... ValueError: Can only convert to a permutation for derangements of [1, 2, ..., n] """ if self.parent()._set != tuple(range(1, len(self) + 1)): raise ValueError("Can only convert to a permutation for derangements of [1, 2, ..., n]") return Permutation(list(self)) class Derangements(UniqueRepresentation, Parent): r""" The class of all derangements of a set or multiset. A derangement on a set `S` is a permutation `\sigma` such that `\sigma(x) \neq x` for all `x \in S`, i.e. `\sigma` is a permutation of `S` with no fixed points. For an integer, or a list or string with all elements distinct, the derangements are obtained by a standard result described in [BV2004]_. For a list or string with repeated elements, the derangements are formed by computing all permutations of the input and discarding all non-derangements. INPUT: - ``x`` -- Can be an integer which corresponds to derangements of `\{1, 2, 3, \ldots, x\}`, a list, or a string REFERENCES: - [BV2004]_ - :wikipedia:`Derangement` EXAMPLES:: sage: D1 = Derangements([2,3,4,5]) sage: D1.list() [[3, 4, 5, 2], [5, 4, 2, 3], [3, 5, 2, 4], [4, 5, 3, 2], [4, 2, 5, 3], [5, 2, 3, 4], [5, 4, 3, 2], [4, 5, 2, 3], [3, 2, 5, 4]] sage: D1.cardinality() 9 sage: D1.random_element() # random [4, 2, 5, 3] sage: D2 = Derangements([1,2,3,1,2,3]) sage: D2.cardinality() 10 sage: D2.list() [[2, 1, 1, 3, 3, 2], [2, 1, 2, 3, 3, 1], [2, 3, 1, 2, 3, 1], [2, 3, 1, 3, 1, 2], [2, 3, 2, 3, 1, 1], [3, 1, 1, 2, 3, 2], [3, 1, 2, 2, 3, 1], [3, 1, 2, 3, 1, 2], [3, 3, 1, 2, 1, 2], [3, 3, 2, 2, 1, 1]] sage: D2.random_element() # random [2, 3, 1, 3, 1, 2] """ @staticmethod def __classcall_private__(cls, x): """ Normalize ``x`` to ensure a unique representation. EXAMPLES:: sage: D = Derangements(4) sage: D2 = Derangements([1, 2, 3, 4]) sage: D3 = Derangements((1, 2, 3, 4)) sage: D is D2 True sage: D is D3 True """ if x in ZZ: x = tuple(range(1, x + 1)) return super().__classcall__(cls, tuple(x)) def __init__(self, x): """ Initialize ``self``. EXAMPLES:: sage: D = Derangements(4) sage: TestSuite(D).run() sage: D = Derangements('abcd') sage: TestSuite(D).run() sage: D = Derangements([2, 2, 1, 1]) sage: TestSuite(D).run() """ Parent.__init__(self, category=FiniteEnumeratedSets()) self._set = x self.__multi = len(set(x)) < len(x) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: Derangements(4) Derangements of the set [1, 2, 3, 4] sage: Derangements('abcd') Derangements of the set ['a', 'b', 'c', 'd'] sage: Derangements([2,2,1,1]) Derangements of the multiset [2, 2, 1, 1] """ if self.__multi: return "Derangements of the multiset %s" % list(self._set) return "Derangements of the set %s" % list(self._set) def _element_constructor_(self, der): """ Construct an element of ``self`` from ``der``. EXAMPLES:: sage: D = Derangements(4) sage: elt = D([3,1,4,2]); elt [3, 1, 4, 2] sage: elt.parent() is D True """ if isinstance(der, Derangement): if der.parent() is self: return der raise ValueError("Cannot convert %s to an element of %s" % (der, self)) return self.element_class(self, der) Element = Derangement def __iter__(self): """ Iterate through ``self``. EXAMPLES:: sage: D = Derangements(4) sage: D.list() # indirect doctest [[2, 3, 4, 1], [4, 3, 1, 2], [2, 4, 1, 3], [3, 4, 2, 1], [3, 1, 4, 2], [4, 1, 2, 3], [4, 3, 2, 1], [3, 4, 1, 2], [2, 1, 4, 3]] sage: D = Derangements([1,44,918,67]) sage: D.list() [[44, 918, 67, 1], [67, 918, 1, 44], [44, 67, 1, 918], [918, 67, 44, 1], [918, 1, 67, 44], [67, 1, 44, 918], [67, 918, 44, 1], [918, 67, 1, 44], [44, 1, 67, 918]] sage: D = Derangements(['A','AT','CAT','CATS']) sage: D.list() [['AT', 'CAT', 'CATS', 'A'], ['CATS', 'CAT', 'A', 'AT'], ['AT', 'CATS', 'A', 'CAT'], ['CAT', 'CATS', 'AT', 'A'], ['CAT', 'A', 'CATS', 'AT'], ['CATS', 'A', 'AT', 'CAT'], ['CATS', 'CAT', 'AT', 'A'], ['CAT', 'CATS', 'A', 'AT'], ['AT', 'A', 'CATS', 'CAT']] sage: D = Derangements('CART') sage: D.list() [['A', 'R', 'T', 'C'], ['T', 'R', 'C', 'A'], ['A', 'T', 'C', 'R'], ['R', 'T', 'A', 'C'], ['R', 'C', 'T', 'A'], ['T', 'C', 'A', 'R'], ['T', 'R', 'A', 'C'], ['R', 'T', 'C', 'A'], ['A', 'C', 'T', 'R']] sage: D = Derangements([1,1,2,2,3,3]) sage: D.list() [[2, 2, 3, 3, 1, 1], [2, 3, 1, 3, 1, 2], [2, 3, 1, 3, 2, 1], [2, 3, 3, 1, 1, 2], [2, 3, 3, 1, 2, 1], [3, 2, 1, 3, 1, 2], [3, 2, 1, 3, 2, 1], [3, 2, 3, 1, 1, 2], [3, 2, 3, 1, 2, 1], [3, 3, 1, 1, 2, 2]] sage: D = Derangements('SATTAS') sage: D.list() [['A', 'S', 'S', 'A', 'T', 'T'], ['A', 'S', 'A', 'S', 'T', 'T'], ['A', 'T', 'S', 'S', 'T', 'A'], ['A', 'T', 'S', 'A', 'S', 'T'], ['A', 'T', 'A', 'S', 'S', 'T'], ['T', 'S', 'S', 'A', 'T', 'A'], ['T', 'S', 'A', 'S', 'T', 'A'], ['T', 'S', 'A', 'A', 'S', 'T'], ['T', 'T', 'S', 'A', 'S', 'A'], ['T', 'T', 'A', 'S', 'S', 'A']] sage: D = Derangements([1,1,2,2,2]) sage: D.list() [] """ if self.__multi: for p in Permutations(self._set): if not self._fixed_point(p): yield self.element_class(self, list(p)) else: for d in self._iter_der(len(self._set)): yield self.element_class(self, [self._set[i - 1] for i in d]) def _iter_der(self, n): r""" Iterate through all derangements of the list `[1, 2, 3, \ldots, n]` using the method given in [BV2004]_. EXAMPLES:: sage: D = Derangements(4) sage: list(D._iter_der(4)) [[2, 3, 4, 1], [4, 3, 1, 2], [2, 4, 1, 3], [3, 4, 2, 1], [3, 1, 4, 2], [4, 1, 2, 3], [4, 3, 2, 1], [3, 4, 1, 2], [2, 1, 4, 3]] """ if n <= 1: return elif n == 2: yield [2, 1] elif n == 3: yield [2, 3, 1] yield [3, 1, 2] elif n >= 4: for d in self._iter_der(n - 1): for i in range(1, n): s = d[:] ii = d.index(i) s[ii] = n yield s + [i] for d in self._iter_der(n - 2): for i in range(1, n): s = d[:] s = [x >= i and x + 1 or x for x in s] s.insert(i - 1, n) yield s + [i] def _fixed_point(self, a): """ Return ``True`` if ``a`` has a point in common with ``self._set``. EXAMPLES:: sage: D = Derangements(5) sage: D._fixed_point([3,1,2,5,4]) False sage: D._fixed_point([5,4,3,2,1]) True """ return any(x == y for (x, y) in zip(a, self._set)) def _count_der(self, n): """ Count the number of derangements of `n` using the recursion `D_2 = 1, D_3 = 2, D_n = (n-1) (D_{n-1} + D_{n-2})`. EXAMPLES:: sage: D = Derangements(5) sage: D._count_der(2) 1 sage: D._count_der(3) 2 sage: D._count_der(5) 44 """ if n <= 1: return Integer(0) if n == 2: return Integer(1) if n == 3: return Integer(2) # n >= 4 last = Integer(2) second_last = Integer(1) for i in range(4, n + 1): current = (i - 1) * (last + second_last) second_last = last last = current return last def cardinality(self): r""" Counts the number of derangements of a positive integer, a list, or a string. The list or string may contain repeated elements. If an integer `n` is given, the value returned is the number of derangements of `[1, 2, 3, \ldots, n]`. For an integer, or a list or string with all elements distinct, the value is obtained by the standard result `D_2 = 1, D_3 = 2, D_n = (n-1) (D_{n-1} + D_{n-2})`. For a list or string with repeated elements, the number of derangements is computed by Macmahon's theorem. If the numbers of repeated elements are `a_1, a_2, \ldots, a_k` then the number of derangements is given by the coefficient of `x_1 x_2 \cdots x_k` in the expansion of `\prod_{i=0}^k (S - s_i)^{a_i}` where `S = x_1 + x_2 + \cdots + x_k`. EXAMPLES:: sage: D = Derangements(5) sage: D.cardinality() 44 sage: D = Derangements([1,44,918,67,254]) sage: D.cardinality() 44 sage: D = Derangements(['A','AT','CAT','CATS','CARTS']) sage: D.cardinality() 44 sage: D = Derangements('UNCOPYRIGHTABLE') sage: D.cardinality() 481066515734 sage: D = Derangements([1,1,2,2,3,3]) sage: D.cardinality() 10 sage: D = Derangements('SATTAS') sage: D.cardinality() 10 sage: D = Derangements([1,1,2,2,2]) sage: D.cardinality() 0 """ if self.__multi: sL = set(self._set) A = [self._set.count(i) for i in sL] R = PolynomialRing(QQ, 'x', len(A)) S = sum(i for i in R.gens()) e = prod((S - x)**y for (x, y) in zip(R.gens(), A)) return Integer(e.coefficient(dict([(x, y) for (x, y) in zip(R.gens(), A)]))) return self._count_der(len(self._set)) def _rand_der(self): r""" Produces a random derangement of `[1, 2, \ldots, n]`. This is an implementation of the algorithm described by Martinez et. al. in [MPP2008]_. EXAMPLES:: sage: D = Derangements(4) sage: d = D._rand_der() sage: d in D True """ n = len(self._set) A = list(range(1, n + 1)) mark = [x < 0 for x in A] i, u = n, n while u >= 2: if not(mark[i - 1]): while True: j = randrange(1, i) if not(mark[j - 1]): A[i - 1], A[j - 1] = A[j - 1], A[i - 1] break p = random() if p < (u - 1) * self._count_der(u - 2) // self._count_der(u): mark[j - 1] = True u -= 1 u -= 1 i -= 1 return A def random_element(self): r""" Produces all derangements of a positive integer, a list, or a string. The list or string may contain repeated elements. If an integer `n` is given, then a random derangements of `[1, 2, 3, \ldots, n]` is returned For an integer, or a list or string with all elements distinct, the value is obtained by an algorithm described in [MPP2008]_. For a list or string with repeated elements the derangement is formed by choosing an element at random from the list of all possible derangements. OUTPUT: A single list or string containing a derangement, or an empty list if there are no derangements. EXAMPLES:: sage: D = Derangements(4) sage: D.random_element() # random [2, 3, 4, 1] sage: D = Derangements(['A','AT','CAT','CATS','CARTS','CARETS']) sage: D.random_element() # random ['AT', 'CARTS', 'A', 'CAT', 'CARETS', 'CATS'] sage: D = Derangements('UNCOPYRIGHTABLE') sage: D.random_element() # random ['C', 'U', 'I', 'H', 'O', 'G', 'N', 'B', 'E', 'L', 'A', 'R', 'P', 'Y', 'T'] sage: D = Derangements([1,1,1,1,2,2,2,2,3,3,3,3]) sage: D.random_element() # random [3, 2, 2, 3, 1, 3, 1, 3, 2, 1, 1, 2] sage: D = Derangements('ESSENCES') sage: D.random_element() # random ['N', 'E', 'E', 'C', 'S', 'S', 'S', 'E'] sage: D = Derangements([1,1,2,2,2]) sage: D.random_element() [] TESTS: Check that index error discovered in :trac:`29974` is fixed:: sage: D = Derangements([1,1,2,2]) sage: _ = [D.random_element() for _ in range(20)] """ if self.__multi: L = list(self) if len(L) == 0: return self.element_class(self, []) i = randrange(len(L)) return L[i] temp = self._rand_der() return self.element_class(self, [self._set[ii - 1] for ii in temp])
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/derangements.py
0.891274
0.620133
derangements.py
pypi
from sage.structure.unique_representation import UniqueRepresentation from sage.structure.parent import Parent from sage.combinat.partition import Partitions, Partition from sage.combinat.combinat import CombinatorialElement from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets from sage.combinat.combinatorial_map import combinatorial_map class Core(CombinatorialElement): r""" A `k`-core is an integer partition from which no rim hook of size `k` can be removed. EXAMPLES:: sage: c = Core([2,1],4); c [2, 1] sage: c = Core([3,1],4); c Traceback (most recent call last): ... ValueError: [3, 1] is not a 4-core """ @staticmethod def __classcall_private__(cls, part, k): r""" Implement the shortcut ``Core(part, k)`` to ``Cores(k,l)(part)`` where `l` is the length of the core. TESTS:: sage: c = Core([2,1],4); c [2, 1] sage: c.parent() 4-Cores of length 3 sage: type(c) <class 'sage.combinat.core.Cores_length_with_category.element_class'> sage: Core([2,1],3) Traceback (most recent call last): ... ValueError: [2, 1] is not a 3-core """ if isinstance(part, cls): return part part = Partition(part) if not part.is_core(k): raise ValueError("%s is not a %s-core" % (part, k)) l = sum(part.k_boundary(k).row_lengths()) return Cores(k, l)(part) def __init__(self, parent, core): """ TESTS:: sage: C = Cores(4,3) sage: c = C([2,1]); c [2, 1] sage: type(c) <class 'sage.combinat.core.Cores_length_with_category.element_class'> sage: c.parent() 4-Cores of length 3 sage: TestSuite(c).run() sage: C = Cores(3,3) sage: C([2,1]) Traceback (most recent call last): ... ValueError: [2, 1] is not a 3-core """ k = parent.k part = Partition(core) if not part.is_core(k): raise ValueError("%s is not a %s-core" % (part, k)) CombinatorialElement.__init__(self, parent, core) def __eq__(self, other): """ Test for equality. EXAMPLES:: sage: c = Core([4,2,1,1],5) sage: d = Core([4,2,1,1],5) sage: e = Core([4,2,1,1],6) sage: c == [4,2,1,1] False sage: c == d True sage: c == e False """ if isinstance(other, Core): return (self._list == other._list and self.parent().k == other.parent().k) return False def __ne__(self, other): """ Test for un-equality. EXAMPLES:: sage: c = Core([4,2,1,1],5) sage: d = Core([4,2,1,1],5) sage: e = Core([4,2,1,1],6) sage: c != [4,2,1,1] True sage: c != d False sage: c != e True """ return not (self == other) def __hash__(self): """ Compute the hash of ``self`` by computing the hash of the underlying list and of the additional parameter. The hash is cached and stored in ``self._hash``. EXAMPLES:: sage: c = Core([4,2,1,1],3) sage: c._hash is None True sage: hash(c) #random 1335416675971793195 sage: c._hash #random 1335416675971793195 TESTS:: sage: c = Core([4,2,1,1],5) sage: d = Core([4,2,1,1],6) sage: hash(c) == hash(d) False """ if self._hash is None: self._hash = hash(tuple(self._list)) + hash(self.parent().k) return self._hash def _latex_(self): r""" Output the LaTeX representation of this core as a partition. See the ``_latex_`` method of :class:`Partition`. EXAMPLES:: sage: c = Core([2,1],4) sage: latex(c) {\def\lr#1{\multicolumn{1}{|@{\hspace{.6ex}}c@{\hspace{.6ex}}|}{\raisebox{-.3ex}{$#1$}}} \raisebox{-.6ex}{$\begin{array}[b]{*{2}c}\cline{1-2} \lr{\phantom{x}}&\lr{\phantom{x}}\\\cline{1-2} \lr{\phantom{x}}\\\cline{1-1} \end{array}$} } """ return self.to_partition()._latex_() def k(self): r""" Return `k` of the `k`-core ``self``. EXAMPLES:: sage: c = Core([2,1],4) sage: c.k() 4 """ return self.parent().k @combinatorial_map(name="to partition") def to_partition(self): r""" Turn the core ``self`` into the partition identical to ``self``. EXAMPLES:: sage: mu = Core([2,1,1],3) sage: mu.to_partition() [2, 1, 1] """ return Partition(self) @combinatorial_map(name="to bounded partition") def to_bounded_partition(self): r""" Bijection between `k`-cores and `(k-1)`-bounded partitions. This maps the `k`-core ``self`` to the corresponding `(k-1)`-bounded partition. This bijection is achieved by deleting all cells in ``self`` of hook length greater than `k`. EXAMPLES:: sage: gamma = Core([9,5,3,2,1,1], 5) sage: gamma.to_bounded_partition() [4, 3, 2, 2, 1, 1] """ k_boundary = self.to_partition().k_boundary(self.k()) return Partition(k_boundary.row_lengths()) def size(self): r""" Return the size of ``self`` as a partition. EXAMPLES:: sage: Core([2,1],4).size() 3 sage: Core([4,2],3).size() 6 """ return self.to_partition().size() def length(self): r""" Return the length of ``self``. The length of a `k`-core is the size of the corresponding `(k-1)`-bounded partition which agrees with the length of the corresponding Grassmannian element, see :meth:`to_grassmannian`. EXAMPLES:: sage: c = Core([4,2],3); c.length() 4 sage: c.to_grassmannian().length() 4 sage: Core([9,5,3,2,1,1], 5).length() 13 """ return self.to_bounded_partition().size() def to_grassmannian(self): r""" Bijection between `k`-cores and Grassmannian elements in the affine Weyl group of type `A_{k-1}^{(1)}`. For further details, see the documentation of the method :meth:`~sage.combinat.partition.Partition.from_kbounded_to_reduced_word` and :meth:`~sage.combinat.partition.Partition.from_kbounded_to_grassmannian`. EXAMPLES:: sage: c = Core([3,1,1],3) sage: w = c.to_grassmannian(); w [-1 1 1] [-2 2 1] [-2 1 2] sage: c.parent() 3-Cores of length 4 sage: w.parent() Weyl Group of type ['A', 2, 1] (as a matrix group acting on the root space) sage: c = Core([],3) sage: c.to_grassmannian() [1 0 0] [0 1 0] [0 0 1] """ bp = self.to_bounded_partition() return bp.from_kbounded_to_grassmannian(self.k() - 1) def affine_symmetric_group_simple_action(self, i): r""" Return the action of the simple transposition `s_i` of the affine symmetric group on ``self``. This gives the action of the affine symmetric group of type `A_k^{(1)}` on the `k`-core ``self``. If ``self`` has outside (resp. inside) corners of content `i` modulo `k`, then these corners are added (resp. removed). Otherwise the action is trivial. EXAMPLES:: sage: c = Core([4,2],3) sage: c.affine_symmetric_group_simple_action(0) [3, 1] sage: c.affine_symmetric_group_simple_action(1) [5, 3, 1] sage: c.affine_symmetric_group_simple_action(2) [4, 2] This action corresponds to the left action by the `i`-th simple reflection in the affine symmetric group:: sage: c = Core([4,2],3) sage: W = c.to_grassmannian().parent() sage: i = 0 sage: c.affine_symmetric_group_simple_action(i).to_grassmannian() == W.simple_reflection(i)*c.to_grassmannian() True sage: i = 1 sage: c.affine_symmetric_group_simple_action(i).to_grassmannian() == W.simple_reflection(i)*c.to_grassmannian() True """ mu = self.to_partition() corners = [p for p in mu.outside_corners() if mu.content(p[0], p[1]) % self.k() == i] if not corners: corners = [p for p in mu.corners() if mu.content(p[0], p[1]) % self.k() == i] if not corners: return self for p in corners: mu = mu.remove_cell(p[0]) else: for p in corners: mu = mu.add_cell(p[0]) return Core(mu, self.k()) def affine_symmetric_group_action(self, w, transposition=False): r""" Return the (left) action of the affine symmetric group on ``self``. INPUT: - ``w`` is a tuple of integers `[w_1,\ldots,w_m]` with `0\le w_j<k`. If transposition is set to be True, then `w = [w_0,w_1]` is interpreted as a transposition `t_{w_0, w_1}` (see :meth:`_transposition_to_reduced_word`). The output is the (left) action of the product of the corresponding simple transpositions on ``self``, that is `s_{w_1} \cdots s_{w_m}(self)`. See :meth:`affine_symmetric_group_simple_action`. EXAMPLES:: sage: c = Core([4,2],3) sage: c.affine_symmetric_group_action([0,1,0,2,1]) [8, 6, 4, 2] sage: c.affine_symmetric_group_action([0,2], transposition=True) [4, 2, 1, 1] sage: c = Core([11,8,5,5,3,3,1,1,1],4) sage: c.affine_symmetric_group_action([2,5],transposition=True) [11, 8, 7, 6, 5, 4, 3, 2, 1] """ c = self if transposition: w = self._transposition_to_reduced_word(w) w.reverse() for i in w: c = c.affine_symmetric_group_simple_action(i) return c def _transposition_to_reduced_word(self, t): r""" Converts the transposition `t = [r,s]` to a reduced word. INPUT: - a tuple `[r,s]` such that `r` and `s` are not equivalent mod `k` OUTPUT: - a list of integers in `\{0,1,\ldots,k-1\}` representing a reduced word for the transposition `t` EXAMPLES:: sage: c = Core([],4) sage: c._transposition_to_reduced_word([2, 5]) [2, 3, 0, 3, 2] sage: c._transposition_to_reduced_word([2, 5]) == c._transposition_to_reduced_word([5,2]) True sage: c._transposition_to_reduced_word([2, 2]) Traceback (most recent call last): ... ValueError: t_0 and t_1 cannot be equal mod k sage: c = Core([],30) sage: c._transposition_to_reduced_word([4, 12]) [4, 5, 6, 7, 8, 9, 10, 11, 10, 9, 8, 7, 6, 5, 4] sage: c = Core([],3) sage: c._transposition_to_reduced_word([4, 12]) [1, 2, 0, 1, 2, 0, 2, 1, 0, 2, 1] """ k = self.k() if (t[0] - t[1]) % k == 0: raise ValueError("t_0 and t_1 cannot be equal mod k") if t[0] > t[1]: return self._transposition_to_reduced_word([t[1], t[0]]) else: resu = [i % k for i in range(t[0], t[1] - (t[1] - t[0]) // k)] resu += [(t[1] - (t[1] - t[0]) // k - 2 - i) % k for i in range(t[1] - (t[1] - t[0]) // k - t[0] - 1)] return resu def weak_le(self, other): r""" Weak order comparison on cores. INPUT: - ``other`` -- another `k`-core OUTPUT: a boolean This returns whether ``self`` <= ``other`` in weak order. EXAMPLES:: sage: c = Core([4,2],3) sage: x = Core([5,3,1],3) sage: c.weak_le(x) True sage: c.weak_le([5,3,1]) True sage: x = Core([4,2,2,1,1],3) sage: c.weak_le(x) False sage: x = Core([5,3,1],6) sage: c.weak_le(x) Traceback (most recent call last): ... ValueError: The two cores do not have the same k """ if type(self) is type(other): if self.k() != other.k(): raise ValueError("The two cores do not have the same k") else: other = Core(other, self.k()) w = self.to_grassmannian() v = other.to_grassmannian() return w.weak_le(v, side='left') def weak_covers(self): r""" Return a list of all elements that cover ``self`` in weak order. EXAMPLES:: sage: c = Core([1],3) sage: c.weak_covers() [[1, 1], [2]] sage: c = Core([4,2],3) sage: c.weak_covers() [[5, 3, 1]] """ w = self.to_grassmannian() S = w.upper_covers(side='left') S = (x for x in S if x.is_affine_grassmannian()) return [x.affine_grassmannian_to_core() for x in set(S)] def strong_le(self, other): r""" Strong order (Bruhat) comparison on cores. INPUT: - ``other`` -- another `k`-core OUTPUT: a boolean This returns whether ``self`` <= ``other`` in Bruhat (or strong) order. EXAMPLES:: sage: c = Core([4,2],3) sage: x = Core([4,2,2,1,1],3) sage: c.strong_le(x) True sage: c.strong_le([4,2,2,1,1]) True sage: x = Core([4,1],4) sage: c.strong_le(x) Traceback (most recent call last): ... ValueError: The two cores do not have the same k """ if type(self) is type(other): if self.k() != other.k(): raise ValueError("The two cores do not have the same k") else: other = Core(other, self.k()) return other.contains(self) def contains(self, other): r""" Checks whether ``self`` contains ``other``. INPUT: - ``other`` -- another `k`-core or a list OUTPUT: a boolean This returns ``True`` if the Ferrers diagram of ``self`` contains the Ferrers diagram of ``other``. EXAMPLES:: sage: c = Core([4,2],3) sage: x = Core([4,2,2,1,1],3) sage: x.contains(c) True sage: c.contains(x) False """ la = self.to_partition() mu = Core(other, self.k()).to_partition() return la.contains(mu) def strong_covers(self): r""" Return a list of all elements that cover ``self`` in strong order. EXAMPLES:: sage: c = Core([1],3) sage: c.strong_covers() [[2], [1, 1]] sage: c = Core([4,2],3) sage: c.strong_covers() [[5, 3, 1], [4, 2, 1, 1]] """ S = Cores(self.k(), length=self.length() + 1) return [ga for ga in S if ga.contains(self)] def strong_down_list(self): r""" Return a list of all elements that are covered by ``self`` in strong order. EXAMPLES:: sage: c = Core([1],3) sage: c.strong_down_list() [[]] sage: c = Core([5,3,1],3) sage: c.strong_down_list() [[4, 2], [3, 1, 1]] """ if not self: return [] return [ga for ga in Cores(self.k(), length=self.length() - 1) if self.contains(ga)] def Cores(k, length=None, **kwargs): r""" A `k`-core is a partition from which no rim hook of size `k` can be removed. Alternatively, a `k`-core is an integer partition such that the Ferrers diagram for the partition contains no cells with a hook of size (a multiple of) `k`. The `k`-cores generally have two notions of size which are useful for different applications. One is the number of cells in the Ferrers diagram with hook less than `k`, the other is the total number of cells of the Ferrers diagram. In the implementation in Sage, the first of notion is referred to as the ``length`` of the `k`-core and the second is the ``size`` of the `k`-core. The class of Cores requires that either the size or the length of the elements in the class is specified. EXAMPLES: We create the set of the `4`-cores of length `6`. Here the length of a `k`-core is the size of the corresponding `(k-1)`-bounded partition, see also :meth:`~sage.combinat.core.Core.length`:: sage: C = Cores(4, 6); C 4-Cores of length 6 sage: C.list() [[6, 3], [5, 2, 1], [4, 1, 1, 1], [4, 2, 2], [3, 3, 1, 1], [3, 2, 1, 1, 1], [2, 2, 2, 1, 1, 1]] sage: C.cardinality() 7 sage: C.an_element() [6, 3] We may also list the set of `4`-cores of size `6`, where the size is the number of boxes in the core, see also :meth:`~sage.combinat.core.Core.size`:: sage: C = Cores(4, size=6); C 4-Cores of size 6 sage: C.list() [[4, 1, 1], [3, 2, 1], [3, 1, 1, 1]] sage: C.cardinality() 3 sage: C.an_element() [4, 1, 1] """ if length is None and 'size' in kwargs: return Cores_size(k, kwargs['size']) elif length is not None: return Cores_length(k, length) else: raise ValueError("You need to either specify the length or size of the cores considered!") class Cores_length(UniqueRepresentation, Parent): r""" The class of `k`-cores of length `n`. """ def __init__(self, k, n): """ TESTS:: sage: C = Cores(3, 4) sage: TestSuite(C).run() """ self.k = k self.n = n Parent.__init__(self, category=FiniteEnumeratedSets()) def _repr_(self): """ TESTS:: sage: repr(Cores(4, 3)) #indirect doctest '4-Cores of length 3' """ return "%s-Cores of length %s" % (self.k, self.n) def list(self): r""" Return the list of all `k`-cores of length `n`. EXAMPLES:: sage: C = Cores(3,4) sage: C.list() [[4, 2], [3, 1, 1], [2, 2, 1, 1]] """ return [la.to_core(self.k - 1) for la in Partitions(self.n, max_part=self.k - 1)] def from_partition(self, part): r""" Converts the partition ``part`` into a core (as the identity map). This is the inverse method to :meth:`~sage.combinat.core.Core.to_partition`. EXAMPLES:: sage: C = Cores(3,4) sage: c = C.from_partition([4,2]); c [4, 2] sage: mu = Partition([2,1,1]) sage: C = Cores(3,3) sage: C.from_partition(mu).to_partition() == mu True sage: mu = Partition([]) sage: C = Cores(3,0) sage: C.from_partition(mu).to_partition() == mu True """ return Core(part, self.k) Element = Core class Cores_size(UniqueRepresentation, Parent): r""" The class of `k`-cores of size `n`. """ def __init__(self, k, n): """ TESTS:: sage: C = Cores(3, size = 4) sage: TestSuite(C).run() """ self.k = k self.n = n Parent.__init__(self, category=FiniteEnumeratedSets()) def _repr_(self): """ TESTS:: sage: repr(Cores(4, size = 3)) #indirect doctest '4-Cores of size 3' """ return "%s-Cores of size %s" % (self.k, self.n) def list(self): r""" Return the list of all `k`-cores of size `n`. EXAMPLES:: sage: C = Cores(3, size = 4) sage: C.list() [[3, 1], [2, 1, 1]] """ return [Core(x, self.k) for x in Partitions(self.n) if x.is_core(self.k)] def from_partition(self, part): r""" Convert the partition ``part`` into a core (as the identity map). This is the inverse method to :meth:`to_partition`. EXAMPLES:: sage: C = Cores(3,size=4) sage: c = C.from_partition([2,1,1]); c [2, 1, 1] sage: mu = Partition([2,1,1]) sage: C = Cores(3,size=4) sage: C.from_partition(mu).to_partition() == mu True sage: mu = Partition([]) sage: C = Cores(3,size=0) sage: C.from_partition(mu).to_partition() == mu True """ return Core(part, self.k) Element = Core
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/core.py
0.907591
0.49585
core.py
pypi
r""" Algebraic combinatorics Thematic tutorials ------------------ - `Algebraic Combinatorics in Sage <../../../../thematic_tutorials/algebraic_combinatorics.html>`_ - `Lie Methods and Related Combinatorics in Sage <../../../../thematic_tutorials/lie.html>`_ - `Linear Programming (Mixed Integer) <../../../../thematic_tutorials/linear_programming.html>`_ Enumerated sets of combinatorial objects ---------------------------------------- - :ref:`sage.combinat.catalog_partitions` - :class:`~sage.combinat.gelfand_tsetlin_patterns.GelfandTsetlinPattern`, :class:`~sage.combinat.gelfand_tsetlin_patterns.GelfandTsetlinPatterns` - :class:`~sage.combinat.knutson_tao_puzzles.KnutsonTaoPuzzleSolver` Groups and Algebras ------------------- - :ref:`Catalog of algebras <sage.algebras.catalog>` - :ref:`Groups <sage.groups.groups_catalog>` - :class:`SymmetricGroup`, :class:`CoxeterGroup`, :class:`WeylGroup` - :class:`~sage.combinat.diagram_algebras.PartitionAlgebra` - :class:`~sage.algebras.iwahori_hecke_algebra.IwahoriHeckeAlgebra` - :class:`~sage.combinat.symmetric_group_algebra.SymmetricGroupAlgebra` - :class:`~sage.algebras.nil_coxeter_algebra.NilCoxeterAlgebra` - :class:`~sage.algebras.affine_nil_temperley_lieb.AffineNilTemperleyLiebTypeA` - :ref:`sage.combinat.descent_algebra` - :ref:`sage.combinat.diagram_algebras` - :ref:`sage.combinat.blob_algebra` Combinatorial Representation Theory ----------------------------------- - :ref:`sage.combinat.root_system.all` - :ref:`sage.combinat.crystals.all` - :ref:`sage.combinat.rigged_configurations.all` - :ref:`sage.combinat.cluster_algebra_quiver.all` - :class:`~sage.combinat.kazhdan_lusztig.KazhdanLusztigPolynomial` - :class:`~sage.combinat.symmetric_group_representations.SymmetricGroupRepresentation` - :ref:`sage.combinat.yang_baxter_graph` - :ref:`sage.combinat.hall_polynomial` - :ref:`sage.combinat.key_polynomial` Operads and their algebras -------------------------- - :ref:`sage.combinat.free_dendriform_algebra` - :ref:`sage.combinat.free_prelie_algebra` - :ref:`sage.algebras.free_zinbiel_algebra` """
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/algebraic_combinatorics.py
0.883701
0.702696
algebraic_combinatorics.py
pypi
from sage.matrix.constructor import matrix from sage.rings.integer_ring import ZZ from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.structure.sage_object import SageObject def _matrix_display(self, variables=None): """ Return the 2-variable polynomial ``self`` as a matrix for display. INPUT: - ``variables`` -- optional choice of 2 variables OUPUT: matrix EXAMPLES:: sage: from sage.combinat.triangles_FHM import _matrix_display sage: x, y = PolynomialRing(QQ,['x', 'y']).gens() sage: _matrix_display(x**2+x*y+y**3) [1 0 0] [0 0 0] [0 1 0] [0 0 1] With a specific choice of variables:: sage: x, y, z = PolynomialRing(QQ,['x','y','z']).gens() sage: _matrix_display(x**2+z*x*y+z*y**3+z*x,[y,z]) [ x x 0 1] [x^2 0 0 0] sage: _matrix_display(x**2+z*x*y+z*y**3+z*x,[x,z]) [ y^3 y + 1 0] [ 0 0 1] """ support = self.exponents() if variables is None: ring = self.parent().base_ring() x, y = self.parent().gens() ix = 0 iy = 1 else: x, y = variables ring = self.parent() all_vars = x.parent().gens() ix = all_vars.index(x) iy = all_vars.index(y) minx = min(u[ix] for u in support) maxy = max(u[iy] for u in support) deltax = max(u[ix] for u in support) - minx + 1 deltay = maxy - min(u[iy] for u in support) + 1 mat = matrix(ring, deltay, deltax) for u in support: ex = u[ix] ey = u[iy] mat[maxy - ey, ex - minx] = self.coefficient({x: ex, y: ey}) return mat class Triangle(SageObject): """ Common class for different kinds of triangles. This serves as a base class for F-triangles, H-triangles, M-triangles and Gamma-triangles. The user should use these subclasses directly. The input is a polynomial in two variables. One can also give a polynomial with more variables and specify two chosen variables. EXAMPLES:: sage: from sage.combinat.triangles_FHM import Triangle sage: x, y = polygens(ZZ, 'x,y') sage: ht = Triangle(1+4*x+2*x*y) sage: unicode_art(ht) ⎛0 2⎞ ⎝1 4⎠ """ def __init__(self, poly, variables=None): """ EXAMPLES:: sage: from sage.combinat.triangles_FHM import Triangle sage: x, y = polygens(ZZ, 'x,y') sage: ht = Triangle(1+2*x*y) sage: unicode_art(ht) ⎛0 2⎞ ⎝1 0⎠ """ if variables is None: self._vars = poly.parent().gens() else: self._vars = variables self._poly = poly self._n = max(self._poly.degree(v) for v in self._vars) def _ascii_art_(self): """ Return the ascii-art representation (as a matrix). EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: ht = H_triangle(1+2*x*y) sage: ascii_art(ht) [0 2] [1 0] """ return self.matrix()._ascii_art_() def _unicode_art_(self): """ Return the unicode representation (as a matrix). EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: ht = H_triangle(1+2*x*y) sage: unicode_art(ht) ⎛0 2⎞ ⎝1 0⎠ """ return self.matrix()._unicode_art_() def _repr_(self) -> str: """ Return the string representation (as a polynomial). EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: ht = H_triangle(1+2*x*y) sage: ht H: 2*x*y + 1 """ return self._prefix + ": " + repr(self._poly) def _latex_(self): r""" Return the LaTeX representation (as a matrix). EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: ht = H_triangle(1+2*x*y) sage: latex(ht) \left(\begin{array}{rr} 0 & 2 \\ 1 & 0 \end{array}\right) """ return self.matrix()._latex_() def __eq__(self, other) -> bool: """ Test for equality. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: h1 = H_triangle(1+2*x*y) sage: h2 = H_triangle(1+3*x*y) sage: h1 == h1 True sage: h1 == h2 False """ if isinstance(other, Triangle): return self._poly == other._poly return self._poly == other def __ne__(self, other) -> bool: """ Test for unequality. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: h1 = H_triangle(1+2*x*y) sage: h2 = H_triangle(1+3*x*y) sage: h1 != h1 False sage: h1 != h2 True """ return not self == other def __call__(self, *args): """ Return the evaluation (as a polynomial). EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: h = H_triangle(1+3*x*y) sage: h(4,5) 61 """ return self._poly(*args) def __getitem__(self, *args): """ Return some coefficient. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: h = H_triangle(1+2*x+3*x*y) sage: h[1,1] 3 """ return self._poly.__getitem__(*args) def __hash__(self): """ Return the hash value. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: h = H_triangle(1+2*x*y) sage: g = H_triangle(1+2*x*y) sage: hash(h) == hash(g) True """ return hash(self._poly) def matrix(self): """ Return the associated matrix for display. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: h = H_triangle(1+2*x*y) sage: h.matrix() [0 2] [1 0] """ return _matrix_display(self._poly, variables=self._vars) def polynomial(self): """ Return the triangle as a bare polynomial. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: h = H_triangle(1+2*x*y) sage: h.polynomial() 2*x*y + 1 """ return self._poly def truncate(self, d): """ Return the truncated triangle. INPUT: - ``d`` -- integer As a polynomial, this means that all monomials with a power of either `x` or `y` greater than or equal to ``d`` are dismissed. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ, 'x,y') sage: h = H_triangle(1+2*x*y) sage: h.truncate(2) H: 2*x*y + 1 """ p = self._poly for v in self._vars: p = p.truncate(v, d) return self.__class__(p, self._vars) class M_triangle(Triangle): """ Class for the M-triangles. This is motivated by generating series of Möbius numbers of graded posets. EXAMPLES:: sage: x, y = polygens(ZZ, 'x,y') sage: P = Poset({2:[1]}) sage: P.M_triangle() M: x*y - y + 1 """ _prefix = 'M' def dual(self): """ Return the dual M-triangle. This is the M-triangle of the dual poset, hence an involution. When seen as a matrix, this performs a symmetry with respect to the northwest-southeast diagonal. EXAMPLES:: sage: from sage.combinat.triangles_FHM import M_triangle sage: x, y = polygens(ZZ, 'x,y') sage: mt = M_triangle(x*y - y + 1) sage: mt.dual() == mt True """ x, y = self._vars n = self._n A = self._poly.parent() dict_dual = {(n - dy, n - dx): coeff for (dx, dy), coeff in self._poly.dict().items()} return M_triangle(A(dict_dual), variables=(x, y)) def transmute(self): """ Return the image of ``self`` by an involution. OUTPUT: another M-triangle The involution is defined by converting to an H-triangle, transposing the matrix, and then converting back to an M-triangle. EXAMPLES:: sage: from sage.combinat.triangles_FHM import M_triangle sage: x, y = polygens(ZZ, 'x,y') sage: nc3 = x^2*y^2 - 3*x*y^2 + 3*x*y + 2*y^2 - 3*y + 1 sage: m = M_triangle(nc3) sage: m2 = m.transmute(); m2 M: 2*x^2*y^2 - 3*x*y^2 + 2*x*y + y^2 - 2*y + 1 sage: m2.transmute() == m True """ return self.h().transpose().m() def h(self): """ Return the associated H-triangle. EXAMPLES:: sage: from sage.combinat.triangles_FHM import M_triangle sage: x, y = polygens(ZZ,'x,y') sage: M_triangle(1-y+x*y).h() H: x*y + 1 TESTS:: sage: h = polygen(ZZ, 'h') sage: x, y = polygens(h.parent(),'x,y') sage: mt = x**2*y**2+(-2*h+2)*x*y**2+(2*h-2)*x*y+(2*h-3)*y**2+(-2*h+2)*y+1 sage: M_triangle(mt, [x,y]).h() H: x^2*y^2 + 2*x*y + (2*h - 4)*x + 1 """ x, y = self._vars n = self._n step = self._poly(x=y / (y - 1), y=(y - 1) * x / (1 + (y - 1) * x)) step *= (1 + (y - 1) * x)**n polyh = step.numerator() return H_triangle(polyh, variables=(x, y)) def f(self): """ Return the associated F-triangle. EXAMPLES:: sage: from sage.combinat.triangles_FHM import M_triangle sage: x, y = polygens(ZZ,'x,y') sage: M_triangle(1-y+x*y).f() F: x + y + 1 TESTS:: sage: h = polygen(ZZ, 'h') sage: x, y = polygens(h.parent(),'x,y') sage: mt = x**2*y**2+(-2*h+2)*x*y**2+(2*h-2)*x*y+(2*h-3)*y**2+(-2*h+2)*y+1 sage: M_triangle(mt, [x,y]).f() F: (2*h - 3)*x^2 + 2*x*y + y^2 + (2*h - 2)*x + 2*y + 1 """ return self.h().f() class H_triangle(Triangle): """ Class for the H-triangles. """ _prefix = 'H' def transpose(self): """ Return the transposed H-triangle. OUTPUT: another H-triangle This operation is an involution. When seen as a matrix, it performs a symmetry with respect to the northwest-southeast diagonal. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ,'x,y') sage: H_triangle(1+x*y).transpose() H: x*y + 1 sage: H_triangle(x^2*y^2 + 2*x*y + x + 1).transpose() H: x^2*y^2 + x^2*y + 2*x*y + 1 """ x, y = self._vars n = self._n A = self._poly.parent() dict_dual = {(n - dy, n - dx): coeff for (dx, dy), coeff in self._poly.dict().items()} return H_triangle(A(dict_dual), variables=(x, y)) def m(self): """ Return the associated M-triangle. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: h = polygen(ZZ, 'h') sage: x, y = polygens(h.parent(),'x,y') sage: ht = H_triangle(x^2*y^2 + 2*x*y + 2*x*h - 4*x + 1, variables=[x,y]) sage: ht.m() M: x^2*y^2 + (-2*h + 2)*x*y^2 + (2*h - 2)*x*y + (2*h - 3)*y^2 + (-2*h + 2)*y + 1 """ x, y = self._vars n = self._n step = self._poly(x=(x - 1) * y / (1 - y), y=x / (x - 1)) * (1 - y)**n polym = step.numerator() return M_triangle(polym, variables=(x, y)) def f(self): """ Return the associated F-triangle. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ,'x,y') sage: H_triangle(1+x*y).f() F: x + y + 1 sage: H_triangle(x^2*y^2 + 2*x*y + x + 1).f() F: 2*x^2 + 2*x*y + y^2 + 3*x + 2*y + 1 sage: flo = H_triangle(1+4*x+2*x**2+x*y*(4+8*x)+ ....: x**2*y**2*(6+4*x)+4*(x*y)**3+(x*y)**4).f(); flo F: 7*x^4 + 12*x^3*y + 10*x^2*y^2 + 4*x*y^3 + y^4 + 20*x^3 + 28*x^2*y + 16*x*y^2 + 4*y^3 + 20*x^2 + 20*x*y + 6*y^2 + 8*x + 4*y + 1 sage: flo(-1-x,-1-y) == flo True TESTS:: sage: x,y,h = polygens(ZZ,'x,y,h') sage: ht = x^2*y^2 + 2*x*y + 2*x*h - 4*x + 1 sage: H_triangle(ht,[x,y]).f() F: 2*x^2*h - 3*x^2 + 2*x*y + y^2 + 2*x*h - 2*x + 2*y + 1 """ x, y = self._vars n = self._n step1 = self._poly(x=x / (1 + x), y=y) * (x + 1)**n step2 = step1(x=x, y=y / x) polyf = step2.numerator() return F_triangle(polyf, variables=(x, y)) def gamma(self): """ Return the associated Gamma-triangle. In some cases, this is a more condensed way to encode the same amount of information. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygen(ZZ,'x,y') sage: ht = x**2*y**2 + 2*x*y + x + 1 sage: H_triangle(ht).gamma() Γ: y^2 + x sage: W = SymmetricGroup(5) sage: P = posets.NoncrossingPartitions(W) sage: P.M_triangle().h().gamma() Γ: y^4 + 3*x*y^2 + 2*x^2 + 2*x*y + x """ x, y = self._vars n = self._n remain = self._poly gamma = x.parent().zero() for k in range(n, -1, -1): step = remain.coefficient({x: k}) gamma += x**(n - k) * step remain -= x**(n - k) * step.homogenize(x)(x=1 + x, y=1 + x * y) return Gamma_triangle(gamma, variables=(x, y)) def vector(self): """ Return the h-vector as a polynomial in one variable. This is obtained by letting `y=1`. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygen(ZZ,'x,y') sage: ht = x**2*y**2 + 2*x*y + x + 1 sage: H_triangle(ht).vector() x^2 + 3*x + 1 """ anneau = PolynomialRing(ZZ, 'x') return anneau(self._poly(y=1)) class F_triangle(Triangle): """ Class for the F-triangles. """ _prefix = 'F' def h(self): """ Return the associated H-triangle. EXAMPLES:: sage: from sage.combinat.triangles_FHM import F_triangle sage: x,y = polygens(ZZ,'x,y') sage: ft = F_triangle(1+x+y) sage: ft.h() H: x*y + 1 TESTS:: sage: h = polygen(ZZ, 'h') sage: x, y = polygens(h.parent(),'x,y') sage: ft = 1+2*y+(2*h-2)*x+y**2+2*x*y+(2*h-3)*x**2 sage: F_triangle(ft, [x,y]).h() H: x^2*y^2 + 2*x*y + (2*h - 4)*x + 1 """ x, y = self._vars n = self._n step = (1 - x)**n * self._poly(x=x / (1 - x), y=x * y / (1 - x)) polyh = step.numerator() return H_triangle(polyh, variables=(x, y)) def m(self): """ Return the associated M-triangle. EXAMPLES:: sage: from sage.combinat.triangles_FHM import H_triangle sage: x, y = polygens(ZZ,'x,y') sage: H_triangle(1+x*y).f() F: x + y + 1 sage: _.m() M: x*y - y + 1 sage: H_triangle(x^2*y^2 + 2*x*y + x + 1).f() F: 2*x^2 + 2*x*y + y^2 + 3*x + 2*y + 1 sage: _.m() M: x^2*y^2 - 3*x*y^2 + 3*x*y + 2*y^2 - 3*y + 1 TESTS:: sage: p = 1+4*x+2*x**2+x*y*(4+8*x) sage: p += x**2*y**2*(6+4*x)+4*(x*y)**3+(x*y)**4 sage: flo = H_triangle(p).f(); flo F: 7*x^4 + 12*x^3*y + 10*x^2*y^2 + 4*x*y^3 + y^4 + 20*x^3 + 28*x^2*y + 16*x*y^2 + 4*y^3 + 20*x^2 + 20*x*y + 6*y^2 + 8*x + 4*y + 1 sage: flo.m() M: x^4*y^4 - 8*x^3*y^4 + 8*x^3*y^3 + 20*x^2*y^4 - 36*x^2*y^3 - 20*x*y^4 + 16*x^2*y^2 + 48*x*y^3 + 7*y^4 - 36*x*y^2 - 20*y^3 + 8*x*y + 20*y^2 - 8*y + 1 sage: from sage.combinat.triangles_FHM import F_triangle sage: h = polygen(ZZ, 'h') sage: x, y = polygens(h.parent(),'x,y') sage: ft = F_triangle(1+2*y+(2*h-2)*x+y**2+2*x*y+(2*h-3)*x**2,(x,y)) sage: ft.m() M: x^2*y^2 + (-2*h + 2)*x*y^2 + (2*h - 2)*x*y + (2*h - 3)*y^2 + (-2*h + 2)*y + 1 """ x, y = self._vars n = self._n step = self._poly(x=y * (x - 1) / (1 - x * y), y=x * y / (1 - x * y)) step *= (1 - x * y)**n polym = step.numerator() return M_triangle(polym, variables=(x, y)) def vector(self): """ Return the f-vector as a polynomial in one variable. This is obtained by letting `y=x`. EXAMPLES:: sage: from sage.combinat.triangles_FHM import F_triangle sage: x, y = polygen(ZZ,'x,y') sage: ft = 2*x^2 + 2*x*y + y^2 + 3*x + 2*y + 1 sage: F_triangle(ft).vector() 5*x^2 + 5*x + 1 """ anneau = PolynomialRing(ZZ, 'x') x = anneau.gen() return anneau(self._poly(y=x)) class Gamma_triangle(Triangle): """ Class for the Gamma-triangles. """ _prefix = 'Γ' def h(self): r""" Return the associated H-triangle. The transition between Gamma-triangles and H-triangles is defined by .. MATH:: H(x,y) = (1+x)^d \sum_{0\leq i; 0\leq j \leq d-2i} \gamma_{i,j} \left(\frac{x}{(1+x)^2}\right)^i \left(\frac{1+xy}{1+x}\right)^j EXAMPLES:: sage: from sage.combinat.triangles_FHM import Gamma_triangle sage: x, y = polygen(ZZ,'x,y') sage: g = y**2 + x sage: Gamma_triangle(g).h() H: x^2*y^2 + 2*x*y + x + 1 sage: a, b = polygen(ZZ, 'a, b') sage: x, y = polygens(a.parent(),'x,y') sage: g = Gamma_triangle(y**3+a*x*y+b*x,(x,y)) sage: hh = g.h() sage: hh.gamma() == g True """ x, y = self._vars n = self._n resu = (1 + x)**n * self._poly(x=x / (1 + x)**2, y=(1 + x * y) / (1 + x)) polyh = resu.numerator() return H_triangle(polyh, variables=(x, y)) def vector(self): """ Return the gamma-vector as a polynomial in one variable. This is obtained by letting `y=1`. EXAMPLES:: sage: from sage.combinat.triangles_FHM import Gamma_triangle sage: x, y = polygen(ZZ,'x,y') sage: gt = y**2 + x sage: Gamma_triangle(gt).vector() x + 1 """ anneau = PolynomialRing(ZZ, 'x') return anneau(self._poly(y=1))
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/triangles_FHM.py
0.920994
0.647074
triangles_FHM.py
pypi
from sage.misc.cachefunc import cached_method from sage.misc.bindable_class import BindableClass from sage.misc.lazy_attribute import lazy_attribute from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.categories.algebras import Algebras from sage.categories.realizations import Realizations, Category_realization_of_parent from sage.categories.all import FiniteDimensionalAlgebrasWithBasis from sage.rings.integer_ring import ZZ from sage.rings.rational_field import QQ from sage.arith.misc import factorial from sage.combinat.free_module import CombinatorialFreeModule from sage.combinat.permutation import Permutations from sage.combinat.composition import Compositions from sage.combinat.integer_matrices import IntegerMatrices from sage.combinat.subset import SubsetsSorted from sage.combinat.symmetric_group_algebra import SymmetricGroupAlgebra from sage.combinat.ncsf_qsym.ncsf import NonCommutativeSymmetricFunctions class DescentAlgebra(UniqueRepresentation, Parent): r""" Solomon's descent algebra. The descent algebra `\Sigma_n` over a ring `R` is a subalgebra of the symmetric group algebra `R S_n`. (The product in the latter algebra is defined by `(pq)(i) = q(p(i))` for any two permutations `p` and `q` in `S_n` and every `i \in \{ 1, 2, \ldots, n \}`. The algebra `\Sigma_n` inherits this product.) There are three bases currently implemented for `\Sigma_n`: - the standard basis `D_S` of (sums of) descent classes, indexed by subsets `S` of `\{1, 2, \ldots, n-1\}`, - the subset basis `B_p`, indexed by compositions `p` of `n`, - the idempotent basis `I_p`, indexed by compositions `p` of `n`, which is used to construct the mutually orthogonal idempotents of the symmetric group algebra. The idempotent basis is only defined when `R` is a `\QQ`-algebra. We follow the notations and conventions in [GR1989]_, apart from the order of multiplication being different from the one used in that article. Schocker's exposition [Sch2004]_, in turn, uses the same order of multiplication as we are, but has different notations for the bases. INPUT: - ``R`` -- the base ring - ``n`` -- a nonnegative integer REFERENCES: - [GR1989]_ - [At1992]_ - [MR1995]_ - [Sch2004]_ EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: D = DA.D(); D Descent algebra of 4 over Rational Field in the standard basis sage: B = DA.B(); B Descent algebra of 4 over Rational Field in the subset basis sage: I = DA.I(); I Descent algebra of 4 over Rational Field in the idempotent basis sage: basis_B = B.basis() sage: elt = basis_B[Composition([1,2,1])] + 4*basis_B[Composition([1,3])]; elt B[1, 2, 1] + 4*B[1, 3] sage: D(elt) 5*D{} + 5*D{1} + D{1, 3} + D{3} sage: I(elt) 7/6*I[1, 1, 1, 1] + 2*I[1, 1, 2] + 3*I[1, 2, 1] + 4*I[1, 3] As syntactic sugar, one can use the notation ``D[i,...,l]`` to construct elements of the basis; note that for the empty set one must use ``D[[]]`` due to Python's syntax:: sage: D[[]] + D[2] + 2*D[1,2] D{} + 2*D{1, 2} + D{2} The same syntax works for the other bases:: sage: I[1,2,1] + 3*I[4] + 2*I[3,1] I[1, 2, 1] + 2*I[3, 1] + 3*I[4] TESTS: We check that we can go back and forth between our bases:: sage: DA = DescentAlgebra(QQ, 4) sage: D = DA.D() sage: B = DA.B() sage: I = DA.I() sage: all(D(B(b)) == b for b in D.basis()) True sage: all(D(I(b)) == b for b in D.basis()) True sage: all(B(D(b)) == b for b in B.basis()) True sage: all(B(I(b)) == b for b in B.basis()) True sage: all(I(D(b)) == b for b in I.basis()) True sage: all(I(B(b)) == b for b in I.basis()) True """ def __init__(self, R, n): r""" EXAMPLES:: sage: TestSuite(DescentAlgebra(QQ, 4)).run() """ self._n = n self._category = FiniteDimensionalAlgebrasWithBasis(R) Parent.__init__(self, base=R, category=self._category.WithRealizations()) def _repr_(self): r""" Return a string representation of ``self``. EXAMPLES:: sage: DescentAlgebra(QQ, 4) Descent algebra of 4 over Rational Field """ return "Descent algebra of {0} over {1}".format(self._n, self.base_ring()) def a_realization(self): r""" Return a particular realization of ``self`` (the `B`-basis). EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: DA.a_realization() Descent algebra of 4 over Rational Field in the subset basis """ return self.B() class D(CombinatorialFreeModule, BindableClass): r""" The standard basis of a descent algebra. This basis is indexed by `S \subseteq \{1, 2, \ldots, n-1\}`, and the basis vector indexed by `S` is the sum of all permutations, taken in the symmetric group algebra `R S_n`, whose descent set is `S`. We denote this basis vector by `D_S`. Occasionally this basis appears in literature but indexed by compositions of `n` rather than subsets of `\{1, 2, \ldots, n-1\}`. The equivalence between these two indexings is owed to the bijection from the power set of `\{1, 2, \ldots, n-1\}` to the set of all compositions of `n` which sends every subset `\{i_1, i_2, \ldots, i_k\}` of `\{1, 2, \ldots, n-1\}` (with `i_1 < i_2 < \cdots < i_k`) to the composition `(i_1, i_2-i_1, \ldots, i_k-i_{k-1}, n-i_k)`. The basis element corresponding to a composition `p` (or to the subset of `\{1, 2, \ldots, n-1\}`) is denoted `\Delta^p` in [Sch2004]_. EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: D = DA.D() sage: list(D.basis()) [D{}, D{1}, D{2}, D{3}, D{1, 2}, D{1, 3}, D{2, 3}, D{1, 2, 3}] sage: DA = DescentAlgebra(QQ, 0) sage: D = DA.D() sage: list(D.basis()) [D{}] """ def __init__(self, alg, prefix="D"): r""" Initialize ``self``. EXAMPLES:: sage: TestSuite(DescentAlgebra(QQ, 4).D()).run() """ self._prefix = prefix self._basis_name = "standard" CombinatorialFreeModule.__init__(self, alg.base_ring(), SubsetsSorted(range(1, alg._n)), category=DescentAlgebraBases(alg), bracket="", prefix=prefix) # Change of basis: B = alg.B() self.module_morphism(self.to_B_basis, codomain=B, category=self.category() ).register_as_coercion() B.module_morphism(B.to_D_basis, codomain=self, category=self.category() ).register_as_coercion() def _element_constructor_(self, x): """ Construct an element of ``self``. EXAMPLES:: sage: D = DescentAlgebra(QQ, 4).D() sage: D([1, 3]) D{1, 3} """ if isinstance(x, (list, set)): x = tuple(x) if isinstance(x, tuple): return self.monomial(x) return CombinatorialFreeModule._element_constructor_(self, x) # We need to overwrite this since our basis elements must be indexed by tuples def _repr_term(self, S): r""" EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: DA.D()._repr_term((1, 3)) 'D{1, 3}' """ return self._prefix + '{' + repr(list(S))[1:-1] + '}' def product_on_basis(self, S, T): r""" Return `D_S D_T`, where `S` and `T` are subsets of `[n-1]`. EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: D = DA.D() sage: D.product_on_basis((1, 3), (2,)) D{} + D{1} + D{1, 2} + 2*D{1, 2, 3} + D{1, 3} + D{2} + D{2, 3} + D{3} """ return self(self.to_B_basis(S) * self.to_B_basis(T)) @cached_method def one_basis(self): r""" Return the identity element, as per ``AlgebrasWithBasis.ParentMethods.one_basis``. EXAMPLES:: sage: DescentAlgebra(QQ, 4).D().one_basis() () sage: DescentAlgebra(QQ, 0).D().one_basis() () sage: all( U * DescentAlgebra(QQ, 3).D().one() == U ....: for U in DescentAlgebra(QQ, 3).D().basis() ) True """ return tuple() @cached_method def to_B_basis(self, S): r""" Return `D_S` as a linear combination of `B_p`-basis elements. EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: D = DA.D() sage: B = DA.B() sage: list(map(B, D.basis())) # indirect doctest [B[4], B[1, 3] - B[4], B[2, 2] - B[4], B[3, 1] - B[4], B[1, 1, 2] - B[1, 3] - B[2, 2] + B[4], B[1, 2, 1] - B[1, 3] - B[3, 1] + B[4], B[2, 1, 1] - B[2, 2] - B[3, 1] + B[4], B[1, 1, 1, 1] - B[1, 1, 2] - B[1, 2, 1] + B[1, 3] - B[2, 1, 1] + B[2, 2] + B[3, 1] - B[4]] """ B = self.realization_of().B() if not S: return B.one() n = self.realization_of()._n C = Compositions(n) return B.sum_of_terms([(C.from_subset(T, n), (-1)**(len(S) - len(T))) for T in SubsetsSorted(S)]) def to_symmetric_group_algebra_on_basis(self, S): """ Return `D_S` as a linear combination of basis elements in the symmetric group algebra. EXAMPLES:: sage: D = DescentAlgebra(QQ, 4).D() sage: [D.to_symmetric_group_algebra_on_basis(tuple(b)) ....: for b in Subsets(3)] [[1, 2, 3, 4], [2, 1, 3, 4] + [3, 1, 2, 4] + [4, 1, 2, 3], [1, 3, 2, 4] + [1, 4, 2, 3] + [2, 3, 1, 4] + [2, 4, 1, 3] + [3, 4, 1, 2], [1, 2, 4, 3] + [1, 3, 4, 2] + [2, 3, 4, 1], [3, 2, 1, 4] + [4, 2, 1, 3] + [4, 3, 1, 2], [2, 1, 4, 3] + [3, 1, 4, 2] + [3, 2, 4, 1] + [4, 1, 3, 2] + [4, 2, 3, 1], [1, 4, 3, 2] + [2, 4, 3, 1] + [3, 4, 2, 1], [4, 3, 2, 1]] """ n = self.realization_of()._n SGA = SymmetricGroupAlgebra(self.base_ring(), n) # Need to convert S to a list of positions by -1 for indexing P = Permutations(descents=([x - 1 for x in S], n)) return SGA.sum_of_terms([(p, 1) for p in P]) def __getitem__(self, S): """ Return the basis element indexed by ``S``. INPUT: - ``S`` -- a subset of `[n-1]` EXAMPLES:: sage: D = DescentAlgebra(QQ, 4).D() sage: D[3] D{3} sage: D[1, 3] D{1, 3} sage: D[[]] D{} TESTS:: sage: D = DescentAlgebra(QQ, 0).D() sage: D[[]] D{} """ n = self.realization_of()._n if S in ZZ: if S >= n or S <= 0: raise ValueError("({0},) is not a subset of {{1, ..., {1}}}".format(S, n - 1)) return self.monomial((S,)) if not S: return self.one() S = sorted(S) if S[-1] >= n or S[0] <= 0: raise ValueError("{0} is not a subset of {{1, ..., {1}}}".format(S, n - 1)) return self.monomial(tuple(S)) standard = D class B(CombinatorialFreeModule, BindableClass): r""" The subset basis of a descent algebra (indexed by compositions). The subset basis `(B_S)_{S \subseteq \{1, 2, \ldots, n-1\}}` of `\Sigma_n` is formed by .. MATH:: B_S = \sum_{T \subseteq S} D_T, where `(D_S)_{S \subseteq \{1, 2, \ldots, n-1\}}` is the :class:`standard basis <DescentAlgebra.D>`. However it is more natural to index the subset basis by compositions of `n` under the bijection `\{i_1, i_2, \ldots, i_k\} \mapsto (i_1, i_2 - i_1, i_3 - i_2, \ldots, i_k - i_{k-1}, n - i_k)` (where `i_1 < i_2 < \cdots < i_k`), which is what Sage uses to index the basis. The basis element `B_p` is denoted `\Xi^p` in [Sch2004]_. By using compositions of `n`, the product `B_p B_q` becomes a sum over the non-negative-integer matrices `M` with row sum `p` and column sum `q`. The summand corresponding to `M` is `B_c`, where `c` is the composition obtained by reading `M` row-by-row from left-to-right and top-to-bottom and removing all zeroes. This multiplication rule is commonly called "Solomon's Mackey formula". EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: B = DA.B() sage: list(B.basis()) [B[1, 1, 1, 1], B[1, 1, 2], B[1, 2, 1], B[1, 3], B[2, 1, 1], B[2, 2], B[3, 1], B[4]] """ def __init__(self, alg, prefix="B"): r""" Initialize ``self``. EXAMPLES:: sage: TestSuite(DescentAlgebra(QQ, 4).B()).run() """ self._prefix = prefix self._basis_name = "subset" CombinatorialFreeModule.__init__(self, alg.base_ring(), Compositions(alg._n), category=DescentAlgebraBases(alg), bracket="", prefix=prefix) S = NonCommutativeSymmetricFunctions(alg.base_ring()).Complete() self.module_morphism(self.to_nsym, codomain=S, category=Algebras(alg.base_ring()) ).register_as_coercion() def product_on_basis(self, p, q): r""" Return `B_p B_q`, where `p` and `q` are compositions of `n`. EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: B = DA.B() sage: p = Composition([1,2,1]) sage: q = Composition([3,1]) sage: B.product_on_basis(p, q) B[1, 1, 1, 1] + 2*B[1, 2, 1] """ IM = IntegerMatrices(list(p), list(q)) P = Compositions(self.realization_of()._n) def to_composition(m): return P([x for x in m.list() if x != 0]) return self.sum_of_monomials([to_composition(mat) for mat in IM]) @cached_method def one_basis(self): r""" Return the identity element which is the composition `[n]`, as per ``AlgebrasWithBasis.ParentMethods.one_basis``. EXAMPLES:: sage: DescentAlgebra(QQ, 4).B().one_basis() [4] sage: DescentAlgebra(QQ, 0).B().one_basis() [] sage: all( U * DescentAlgebra(QQ, 3).B().one() == U ....: for U in DescentAlgebra(QQ, 3).B().basis() ) True """ n = self.realization_of()._n P = Compositions(n) if not n: # n == 0 return P([]) return P([n]) @cached_method def to_I_basis(self, p): r""" Return `B_p` as a linear combination of `I`-basis elements. This is done using the formula .. MATH:: B_p = \sum_{q \leq p} \frac{1}{\mathbf{k}!(q,p)} I_q, where `\leq` is the refinement order and `\mathbf{k}!(q,p)` is defined as follows: When `q \leq p`, we can write `q` as a concatenation `q_{(1)} q_{(2)} \cdots q_{(k)}` with each `q_{(i)}` being a composition of the `i`-th entry of `p`, and then we set `\mathbf{k}!(q,p)` to be `l(q_{(1)})! l(q_{(2)})! \cdots l(q_{(k)})!`, where `l(r)` denotes the number of parts of any composition `r`. EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: B = DA.B() sage: I = DA.I() sage: list(map(I, B.basis())) # indirect doctest [I[1, 1, 1, 1], 1/2*I[1, 1, 1, 1] + I[1, 1, 2], 1/2*I[1, 1, 1, 1] + I[1, 2, 1], 1/6*I[1, 1, 1, 1] + 1/2*I[1, 1, 2] + 1/2*I[1, 2, 1] + I[1, 3], 1/2*I[1, 1, 1, 1] + I[2, 1, 1], 1/4*I[1, 1, 1, 1] + 1/2*I[1, 1, 2] + 1/2*I[2, 1, 1] + I[2, 2], 1/6*I[1, 1, 1, 1] + 1/2*I[1, 2, 1] + 1/2*I[2, 1, 1] + I[3, 1], 1/24*I[1, 1, 1, 1] + 1/6*I[1, 1, 2] + 1/6*I[1, 2, 1] + 1/2*I[1, 3] + 1/6*I[2, 1, 1] + 1/2*I[2, 2] + 1/2*I[3, 1] + I[4]] """ I = self.realization_of().I() def coeff(p, q): ret = QQ.one() last = 0 for val in p: count = 0 s = 0 while s != val: s += q[last + count] count += 1 ret /= factorial(count) last += count return ret return I.sum_of_terms([(q, coeff(p, q)) for q in p.finer()]) @cached_method def to_D_basis(self, p): r""" Return `B_p` as a linear combination of `D`-basis elements. EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: B = DA.B() sage: D = DA.D() sage: list(map(D, B.basis())) # indirect doctest [D{} + D{1} + D{1, 2} + D{1, 2, 3} + D{1, 3} + D{2} + D{2, 3} + D{3}, D{} + D{1} + D{1, 2} + D{2}, D{} + D{1} + D{1, 3} + D{3}, D{} + D{1}, D{} + D{2} + D{2, 3} + D{3}, D{} + D{2}, D{} + D{3}, D{}] TESTS: Check to make sure the empty case is handled correctly:: sage: DA = DescentAlgebra(QQ, 0) sage: B = DA.B() sage: D = DA.D() sage: list(map(D, B.basis())) [D{}] """ D = self.realization_of().D() if not p: return D.one() return D.sum_of_terms([(tuple(sorted(s)), 1) for s in p.to_subset().subsets()]) def to_nsym(self, p): """ Return `B_p` as an element in `NSym`, the non-commutative symmetric functions. This maps `B_p` to `S_p` where `S` denotes the Complete basis of `NSym`. EXAMPLES:: sage: B = DescentAlgebra(QQ, 4).B() sage: S = NonCommutativeSymmetricFunctions(QQ).Complete() sage: list(map(S, B.basis())) # indirect doctest [S[1, 1, 1, 1], S[1, 1, 2], S[1, 2, 1], S[1, 3], S[2, 1, 1], S[2, 2], S[3, 1], S[4]] """ S = NonCommutativeSymmetricFunctions(self.base_ring()).Complete() return S.monomial(p) subset = B class I(CombinatorialFreeModule, BindableClass): r""" The idempotent basis of a descent algebra. The idempotent basis `(I_p)_{p \models n}` is a basis for `\Sigma_n` whenever the ground ring is a `\QQ`-algebra. One way to compute it is using the formula (Theorem 3.3 in [GR1989]_) .. MATH:: I_p = \sum_{q \leq p} \frac{(-1)^{l(q)-l(p)}}{\mathbf{k}(q,p)} B_q, where `\leq` is the refinement order and `l(r)` denotes the number of parts of any composition `r`, and where `\mathbf{k}(q,p)` is defined as follows: When `q \leq p`, we can write `q` as a concatenation `q_{(1)} q_{(2)} \cdots q_{(k)}` with each `q_{(i)}` being a composition of the `i`-th entry of `p`, and then we set `\mathbf{k}(q,p)` to be the product `l(q_{(1)}) l(q_{(2)}) \cdots l(q_{(k)})`. Let `\lambda(p)` denote the partition obtained from a composition `p` by sorting. This basis is called the idempotent basis since for any `q` such that `\lambda(p) = \lambda(q)`, we have: .. MATH:: I_p I_q = s(\lambda) I_p where `\lambda` denotes `\lambda(p) = \lambda(q)`, and where `s(\lambda)` is the stabilizer of `\lambda` in `S_n`. (This is part of Theorem 4.2 in [GR1989]_.) It is also straightforward to compute the idempotents `E_{\lambda}` for the symmetric group algebra by the formula (Theorem 3.2 in [GR1989]_): .. MATH:: E_{\lambda} = \frac{1}{k!} \sum_{\lambda(p) = \lambda} I_p. .. NOTE:: The basis elements are not orthogonal idempotents. EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: I = DA.I() sage: list(I.basis()) [I[1, 1, 1, 1], I[1, 1, 2], I[1, 2, 1], I[1, 3], I[2, 1, 1], I[2, 2], I[3, 1], I[4]] """ def __init__(self, alg, prefix="I"): r""" Initialize ``self``. EXAMPLES:: sage: TestSuite(DescentAlgebra(QQ, 4).B()).run() """ self._prefix = prefix self._basis_name = "idempotent" CombinatorialFreeModule.__init__(self, alg.base_ring(), Compositions(alg._n), category=DescentAlgebraBases(alg), bracket="", prefix=prefix) # Change of basis: B = alg.B() self.module_morphism(self.to_B_basis, codomain=B, category=self.category() ).register_as_coercion() B.module_morphism(B.to_I_basis, codomain=self, category=self.category() ).register_as_coercion() def product_on_basis(self, p, q): r""" Return `I_p I_q`, where `p` and `q` are compositions of `n`. EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: I = DA.I() sage: p = Composition([1,2,1]) sage: q = Composition([3,1]) sage: I.product_on_basis(p, q) 0 sage: I.product_on_basis(p, p) 2*I[1, 2, 1] """ # These do not act as orthogonal idempotents, so we have to lift # to the B basis to do the multiplication # TODO: if the partitions of p and q match, return s*I_p where # s is the size of the stabilizer of the partition of p return self(self.to_B_basis(p) * self.to_B_basis(q)) @cached_method def one(self): r""" Return the identity element, which is `B_{[n]}`, in the `I` basis. EXAMPLES:: sage: DescentAlgebra(QQ, 4).I().one() 1/24*I[1, 1, 1, 1] + 1/6*I[1, 1, 2] + 1/6*I[1, 2, 1] + 1/2*I[1, 3] + 1/6*I[2, 1, 1] + 1/2*I[2, 2] + 1/2*I[3, 1] + I[4] sage: DescentAlgebra(QQ, 0).I().one() I[] TESTS:: sage: all( U * DescentAlgebra(QQ, 3).I().one() == U ....: for U in DescentAlgebra(QQ, 3).I().basis() ) True """ B = self.realization_of().B() return B.to_I_basis(B.one_basis()) def one_basis(self): """ The element `1` is not (generally) a basis vector in the `I` basis, thus this returns a ``TypeError``. EXAMPLES:: sage: DescentAlgebra(QQ, 4).I().one_basis() Traceback (most recent call last): ... TypeError: 1 is not a basis element in the I basis """ raise TypeError("1 is not a basis element in the I basis") @cached_method def to_B_basis(self, p): r""" Return `I_p` as a linear combination of `B`-basis elements. This is computed using the formula (Theorem 3.3 in [GR1989]_) .. MATH:: I_p = \sum_{q \leq p} \frac{(-1)^{l(q)-l(p)}}{\mathbf{k}(q,p)} B_q, where `\leq` is the refinement order and `l(r)` denotes the number of parts of any composition `r`, and where `\mathbf{k}(q,p)` is defined as follows: When `q \leq p`, we can write `q` as a concatenation `q_{(1)} q_{(2)} \cdots q_{(k)}` with each `q_{(i)}` being a composition of the `i`-th entry of `p`, and then we set `\mathbf{k}(q,p)` to be `l(q_{(1)}) l(q_{(2)}) \cdots l(q_{(k)})`. EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: B = DA.B() sage: I = DA.I() sage: list(map(B, I.basis())) # indirect doctest [B[1, 1, 1, 1], -1/2*B[1, 1, 1, 1] + B[1, 1, 2], -1/2*B[1, 1, 1, 1] + B[1, 2, 1], 1/3*B[1, 1, 1, 1] - 1/2*B[1, 1, 2] - 1/2*B[1, 2, 1] + B[1, 3], -1/2*B[1, 1, 1, 1] + B[2, 1, 1], 1/4*B[1, 1, 1, 1] - 1/2*B[1, 1, 2] - 1/2*B[2, 1, 1] + B[2, 2], 1/3*B[1, 1, 1, 1] - 1/2*B[1, 2, 1] - 1/2*B[2, 1, 1] + B[3, 1], -1/4*B[1, 1, 1, 1] + 1/3*B[1, 1, 2] + 1/3*B[1, 2, 1] - 1/2*B[1, 3] + 1/3*B[2, 1, 1] - 1/2*B[2, 2] - 1/2*B[3, 1] + B[4]] """ B = self.realization_of().B() def coeff(p, q): ret = QQ.one() last = 0 for val in p: count = 0 s = 0 while s != val: s += q[last + count] count += 1 ret /= count last += count if (len(q) - len(p)) % 2: ret = -ret return ret return B.sum_of_terms([(q, coeff(p, q)) for q in p.finer()]) def idempotent(self, la): """ Return the idempotent corresponding to the partition ``la`` of `n`. EXAMPLES:: sage: I = DescentAlgebra(QQ, 4).I() sage: E = I.idempotent([3,1]); E 1/2*I[1, 3] + 1/2*I[3, 1] sage: E*E == E True sage: E2 = I.idempotent([2,1,1]); E2 1/6*I[1, 1, 2] + 1/6*I[1, 2, 1] + 1/6*I[2, 1, 1] sage: E2*E2 == E2 True sage: E*E2 == I.zero() True """ from sage.combinat.permutation import Permutations k = len(la) C = Compositions(self.realization_of()._n) return self.sum_of_terms([(C(x), QQ((1, factorial(k)))) for x in Permutations(la)]) idempotent = I class DescentAlgebraBases(Category_realization_of_parent): r""" The category of bases of a descent algebra. """ def __init__(self, base): r""" Initialize the bases of a descent algebra. INPUT: - ``base`` -- a descent algebra TESTS:: sage: from sage.combinat.descent_algebra import DescentAlgebraBases sage: DA = DescentAlgebra(QQ, 4) sage: bases = DescentAlgebraBases(DA) sage: DA.B() in bases True """ Category_realization_of_parent.__init__(self, base) def _repr_(self): r""" Return the representation of ``self``. EXAMPLES:: sage: from sage.combinat.descent_algebra import DescentAlgebraBases sage: DA = DescentAlgebra(QQ, 4) sage: DescentAlgebraBases(DA) Category of bases of Descent algebra of 4 over Rational Field """ return "Category of bases of {}".format(self.base()) def super_categories(self): r""" The super categories of ``self``. EXAMPLES:: sage: from sage.combinat.descent_algebra import DescentAlgebraBases sage: DA = DescentAlgebra(QQ, 4) sage: bases = DescentAlgebraBases(DA) sage: bases.super_categories() [Category of finite dimensional algebras with basis over Rational Field, Category of realizations of Descent algebra of 4 over Rational Field] """ return [self.base()._category, Realizations(self.base())] class ParentMethods: def _repr_(self): """ Text representation of this basis of a descent algebra. EXAMPLES:: sage: DA = DescentAlgebra(QQ, 4) sage: DA.B() Descent algebra of 4 over Rational Field in the subset basis sage: DA.D() Descent algebra of 4 over Rational Field in the standard basis sage: DA.I() Descent algebra of 4 over Rational Field in the idempotent basis """ return "{} in the {} basis".format(self.realization_of(), self._basis_name) def __getitem__(self, p): """ Return the basis element indexed by ``p``. INPUT: - ``p`` -- a composition EXAMPLES:: sage: B = DescentAlgebra(QQ, 4).B() sage: B[Composition([4])] B[4] sage: B[1,2,1] B[1, 2, 1] sage: B[4] B[4] sage: B[[3,1]] B[3, 1] """ C = Compositions(self.realization_of()._n) if p in C: return self.monomial(C(p)) # Make sure it's a composition if not p: return self.one() if not isinstance(p, tuple): p = [p] return self.monomial(C(p)) def is_field(self, proof=True): """ Return whether this descent algebra is a field. EXAMPLES:: sage: B = DescentAlgebra(QQ, 4).B() sage: B.is_field() False sage: B = DescentAlgebra(QQ, 1).B() sage: B.is_field() True """ if self.realization_of()._n <= 1: return self.base_ring().is_field() return False def is_commutative(self): """ Return whether this descent algebra is commutative. EXAMPLES:: sage: B = DescentAlgebra(QQ, 4).B() sage: B.is_commutative() False sage: B = DescentAlgebra(QQ, 1).B() sage: B.is_commutative() True """ return self.base_ring().is_commutative() \ and self.realization_of()._n <= 2 @lazy_attribute def to_symmetric_group_algebra(self): """ Morphism from ``self`` to the symmetric group algebra. EXAMPLES:: sage: D = DescentAlgebra(QQ, 4).D() sage: D.to_symmetric_group_algebra(D[1,3]) [2, 1, 4, 3] + [3, 1, 4, 2] + [3, 2, 4, 1] + [4, 1, 3, 2] + [4, 2, 3, 1] sage: B = DescentAlgebra(QQ, 4).B() sage: B.to_symmetric_group_algebra(B[1,2,1]) [1, 2, 3, 4] + [1, 2, 4, 3] + [1, 3, 4, 2] + [2, 1, 3, 4] + [2, 1, 4, 3] + [2, 3, 4, 1] + [3, 1, 2, 4] + [3, 1, 4, 2] + [3, 2, 4, 1] + [4, 1, 2, 3] + [4, 1, 3, 2] + [4, 2, 3, 1] """ SGA = SymmetricGroupAlgebra(self.base_ring(), self.realization_of()._n) return self.module_morphism(self.to_symmetric_group_algebra_on_basis, codomain=SGA) def to_symmetric_group_algebra_on_basis(self, S): """ Return the basis element index by ``S`` as a linear combination of basis elements in the symmetric group algebra. EXAMPLES:: sage: B = DescentAlgebra(QQ, 3).B() sage: [B.to_symmetric_group_algebra_on_basis(c) ....: for c in Compositions(3)] [[1, 2, 3] + [1, 3, 2] + [2, 1, 3] + [2, 3, 1] + [3, 1, 2] + [3, 2, 1], [1, 2, 3] + [2, 1, 3] + [3, 1, 2], [1, 2, 3] + [1, 3, 2] + [2, 3, 1], [1, 2, 3]] sage: I = DescentAlgebra(QQ, 3).I() sage: [I.to_symmetric_group_algebra_on_basis(c) ....: for c in Compositions(3)] [[1, 2, 3] + [1, 3, 2] + [2, 1, 3] + [2, 3, 1] + [3, 1, 2] + [3, 2, 1], 1/2*[1, 2, 3] - 1/2*[1, 3, 2] + 1/2*[2, 1, 3] - 1/2*[2, 3, 1] + 1/2*[3, 1, 2] - 1/2*[3, 2, 1], 1/2*[1, 2, 3] + 1/2*[1, 3, 2] - 1/2*[2, 1, 3] + 1/2*[2, 3, 1] - 1/2*[3, 1, 2] - 1/2*[3, 2, 1], 1/3*[1, 2, 3] - 1/6*[1, 3, 2] - 1/6*[2, 1, 3] - 1/6*[2, 3, 1] - 1/6*[3, 1, 2] + 1/3*[3, 2, 1]] """ D = self.realization_of().D() return D.to_symmetric_group_algebra(D(self[S])) class ElementMethods: def to_symmetric_group_algebra(self): """ Return ``self`` in the symmetric group algebra. EXAMPLES:: sage: B = DescentAlgebra(QQ, 4).B() sage: B[1,3].to_symmetric_group_algebra() [1, 2, 3, 4] + [2, 1, 3, 4] + [3, 1, 2, 4] + [4, 1, 2, 3] sage: I = DescentAlgebra(QQ, 4).I() sage: elt = I(B[1,3]) sage: elt.to_symmetric_group_algebra() [1, 2, 3, 4] + [2, 1, 3, 4] + [3, 1, 2, 4] + [4, 1, 2, 3] """ return self.parent().to_symmetric_group_algebra(self)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/descent_algebra.py
0.898168
0.604924
descent_algebra.py
pypi
r""" Gray codes Functions --------- """ def product(m): r""" Iterator over the switch for the iteration of the product `[m_0] \times [m_1] \ldots \times [m_k]`. The iterator return at each step a pair ``(p,i)`` which corresponds to the modification to perform to get the next element. More precisely, one has to apply the increment ``i`` at the position ``p``. By construction, the increment is either ``+1`` or ``-1``. This is algorithm H in [Knu2011]_ Section 7.2.1.1, "Generating All `n`-Tuples": loopless reflected mixed-radix Gray generation. INPUT: - ``m`` -- a list or tuple of positive integers that correspond to the size of the sets in the product EXAMPLES:: sage: from sage.combinat.gray_codes import product sage: l = [0,0,0] sage: for p,i in product([3,3,3]): ....: l[p] += i ....: print(l) [1, 0, 0] [2, 0, 0] [2, 1, 0] [1, 1, 0] [0, 1, 0] [0, 2, 0] [1, 2, 0] [2, 2, 0] [2, 2, 1] [1, 2, 1] [0, 2, 1] [0, 1, 1] [1, 1, 1] [2, 1, 1] [2, 0, 1] [1, 0, 1] [0, 0, 1] [0, 0, 2] [1, 0, 2] [2, 0, 2] [2, 1, 2] [1, 1, 2] [0, 1, 2] [0, 2, 2] [1, 2, 2] [2, 2, 2] sage: l = [0,0] sage: for i,j in product([2,1]): ....: l[i] += j ....: print(l) [1, 0] TESTS:: sage: for t in [[2,2,2],[2,1,2],[3,2,1],[2,1,3]]: ....: assert sum(1 for _ in product(t)) == prod(t)-1 """ # n is the length of the element (we ignore sets of size 1) n = k = 0 new_m = [] # will be the set of upper bounds m_i different from 1 mm = [] # index of each set (we skip sets of cardinality 1) for i in m: i = int(i) if i <= 0: raise ValueError("accept only positive integers") if i > 1: new_m.append(i-1) mm.append(k) n += 1 k += 1 m = new_m f = list(range(n + 1)) # focus pointer o = [1] * n # switch +1 or -1 a = [0] * n # current element of the product j = f[0] while j != n: f[0] = 0 oo = o[j] a[j] += oo if a[j] == 0 or a[j] == m[j]: f[j] = f[j+1] f[j+1] = j+1 o[j] = -oo yield (mm[j], oo) j = f[0] def combinations(n,t): r""" Iterator through the switches of the revolving door algorithm. The revolving door algorithm is a way to generate all combinations of a set (i.e. the subset of given cardinality) in such way that two consecutive subsets differ by one element. At each step, the iterator output a pair ``(i,j)`` where the item ``i`` has to be removed and ``j`` has to be added. The ground set is always `\{0, 1, ..., n-1\}`. Note that ``n`` can be infinity in that algorithm. See [Knu2011]_ Section 7.2.1.3, "Generating All Combinations". INPUT: - ``n`` -- (integer or ``Infinity``) -- size of the ground set - ``t`` -- (integer) -- size of the subsets EXAMPLES:: sage: from sage.combinat.gray_codes import combinations sage: b = [1, 1, 1, 0, 0] sage: for i,j in combinations(5,3): ....: b[i] = 0; b[j] = 1 ....: print(b) [1, 0, 1, 1, 0] [0, 1, 1, 1, 0] [1, 1, 0, 1, 0] [1, 0, 0, 1, 1] [0, 1, 0, 1, 1] [0, 0, 1, 1, 1] [1, 0, 1, 0, 1] [0, 1, 1, 0, 1] [1, 1, 0, 0, 1] sage: s = set([0,1]) sage: for i,j in combinations(4,2): ....: s.remove(i) ....: s.add(j) ....: print(sorted(s)) [1, 2] [0, 2] [2, 3] [1, 3] [0, 3] Note that ``n`` can be infinity:: sage: c = combinations(Infinity,4) sage: s = set([0,1,2,3]) sage: for _ in range(10): ....: i,j = next(c) ....: s.remove(i); s.add(j) ....: print(sorted(s)) [0, 1, 3, 4] [1, 2, 3, 4] [0, 2, 3, 4] [0, 1, 2, 4] [0, 1, 4, 5] [1, 2, 4, 5] [0, 2, 4, 5] [2, 3, 4, 5] [1, 3, 4, 5] [0, 3, 4, 5] sage: for _ in range(1000): ....: i,j = next(c) ....: s.remove(i); s.add(j) sage: sorted(s) [0, 4, 13, 14] TESTS:: sage: def check_sets_from_iter(n,k): ....: l = [] ....: s = set(range(k)) ....: l.append(frozenset(s)) ....: for i,j in combinations(n,k): ....: s.remove(i) ....: s.add(j) ....: assert len(s) == k ....: l.append(frozenset(s)) ....: assert len(set(l)) == binomial(n,k) sage: check_sets_from_iter(9,5) sage: check_sets_from_iter(8,5) sage: check_sets_from_iter(5,6) Traceback (most recent call last): ... AssertionError: t(=6) must be >=0 and <=n(=5) """ from sage.rings.infinity import Infinity t = int(t) if n != Infinity: n = int(n) else: n = Infinity assert 0 <= t and t <= n, "t(={}) must be >=0 and <=n(={})".format(t,n) if t == 0 or t == n: return iter([]) if t % 2: return _revolving_door_odd(n,t) else: return _revolving_door_even(n,t) def _revolving_door_odd(n,t): r""" Revolving door switch for odd `t`. TESTS:: sage: from sage.combinat.gray_codes import _revolving_door_odd sage: sum(1 for _ in _revolving_door_odd(13,3)) == binomial(13,3) - 1 True sage: sum(1 for _ in _revolving_door_odd(10,5)) == binomial(10,5) - 1 True """ # note: the numbering of the steps below follows Knuth TAOCP c = list(range(t)) + [n] # the combination (ordered list of numbers of length t+1) while True: # R3 : easy case if c[0] + 1 < c[1]: yield c[0], c[0]+1 c[0] += 1 continue j = 1 while j < t: # R4 : try to decrease c[j] # at this point c[j] = c[j-1] + 1 if c[j] > j: yield c[j], j-1 c[j] = c[j-1] c[j-1] = j-1 break j += 1 # R5 : try to increase c[j] # at this point c[j-1] = j-1 if c[j] + 1 < c[j+1]: yield c[j-1], c[j]+1 c[j-1] = c[j] c[j] += 1 break j += 1 else: # j == t break def _revolving_door_even(n,t): r""" Revolving door algorithm for even `t`. TESTS:: sage: from sage.combinat.gray_codes import _revolving_door_even sage: sum(1 for _ in _revolving_door_even(13,4)) == binomial(13,4) - 1 True sage: sum(1 for _ in _revolving_door_even(12,6)) == binomial(12,6) - 1 True """ # note: the numbering of the steps below follows Knuth TAOCP c = list(range(t)) + [n] # the combination (ordered list of numbers of length t+1) while True: # R3 : easy case if c[0] > 0: yield c[0], c[0]-1 c[0] -= 1 continue j = 1 # R5 : try to increase c[j] # at this point c[j-1] = j-1 if c[j] + 1 < c[j+1]: yield c[j-1], c[j]+1 c[j-1] = c[j] c[j] += 1 continue j += 1 while j < t: # R4 : try to decrease c[j] # at this point c[j] = c[j-1] + 1 if c[j] > j: yield c[j], j-1 c[j] = c[j-1] c[j-1] = j-1 break j += 1 # R5 : try to increase c[j] # at this point c[j-1] = j-1 if c[j] + 1 < c[j+1]: yield c[j-1], c[j] + 1 c[j-1] = c[j] c[j] += 1 break j += 1 else: # j == t break
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/gray_codes.py
0.847369
0.80456
gray_codes.py
pypi
r""" Catalog Of Crystal Models For `B(\infty)` We currently have the following models: * :class:`AlcovePaths <sage.combinat.crystals.alcove_path.InfinityCrystalOfAlcovePaths>` * :class:`GeneralizedYoungWalls <sage.combinat.crystals.generalized_young_walls.InfinityCrystalOfGeneralizedYoungWalls>` * :class:`LSPaths <sage.combinat.crystals.littelmann_path.InfinityCrystalOfLSPaths>` * :class:`Multisegments <sage.combinat.crystals.multisegments.InfinityCrystalOfMultisegments>` * :class:`MVPolytopes <sage.combinat.crystals.mv_polytopes.MVPolytopes>` * :class:`NakajimaMonomials <sage.combinat.crystals.monomial_crystals.InfinityCrystalOfNakajimaMonomials>` * :class:`PBW <sage.combinat.crystals.pbw_crystal.PBWCrystal>` * :class:`PolyhedralRealization <sage.combinat.crystals.polyhedral_realization.InfinityCrystalAsPolyhedralRealization>` * :class:`RiggedConfigurations <sage.combinat.rigged_configurations.rc_infinity.InfinityCrystalOfRiggedConfigurations>` * :class:`Star <sage.combinat.crystals.star_crystal.StarCrystal>` * :class:`Tableaux <sage.combinat.crystals.infinity_crystals.InfinityCrystalOfTableaux>` """ from .generalized_young_walls import InfinityCrystalOfGeneralizedYoungWalls as GeneralizedYoungWalls from .multisegments import InfinityCrystalOfMultisegments as Multisegments from .monomial_crystals import InfinityCrystalOfNakajimaMonomials as NakajimaMonomials from sage.combinat.rigged_configurations.rc_infinity import InfinityCrystalOfRiggedConfigurations as RiggedConfigurations from .infinity_crystals import InfinityCrystalOfTableaux as Tableaux from sage.combinat.crystals.polyhedral_realization import InfinityCrystalAsPolyhedralRealization as PolyhedralRealization from sage.combinat.crystals.pbw_crystal import PBWCrystal as PBW from sage.combinat.crystals.mv_polytopes import MVPolytopes from sage.combinat.crystals.star_crystal import StarCrystal as Star from sage.combinat.crystals.littelmann_path import InfinityCrystalOfLSPaths as LSPaths from sage.combinat.crystals.alcove_path import InfinityCrystalOfAlcovePaths as AlcovePaths
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/crystals/catalog_infinity_crystals.py
0.89735
0.541227
catalog_infinity_crystals.py
pypi
from sage.categories.category import Category from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets from sage.sets.family import Family from sage.structure.element_wrapper import ElementWrapper from sage.structure.element import get_coercion_model class DirectSumOfCrystals(DisjointUnionEnumeratedSets): r""" Direct sum of crystals. Given a list of crystals `B_0, \ldots, B_k` of the same Cartan type, one can form the direct sum `B_0 \oplus \cdots \oplus B_k`. INPUT: - ``crystals`` -- a list of crystals of the same Cartan type - ``keepkey`` -- a boolean The option ``keepkey`` is by default set to ``False``, assuming that the crystals are all distinct. In this case the elements of the direct sum are just represented by the elements in the crystals `B_i`. If the crystals are not all distinct, one should set the ``keepkey`` option to ``True``. In this case, the elements of the direct sum are represented as tuples `(i, b)` where `b \in B_i`. EXAMPLES:: sage: C = crystals.Letters(['A',2]) sage: C1 = crystals.Tableaux(['A',2],shape=[1,1]) sage: B = crystals.DirectSum([C,C1]) sage: B.list() [1, 2, 3, [[1], [2]], [[1], [3]], [[2], [3]]] sage: [b.f(1) for b in B] [2, None, None, None, [[2], [3]], None] sage: B.module_generators (1, [[1], [2]]) :: sage: B = crystals.DirectSum([C,C], keepkey=True) sage: B.list() [(0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3)] sage: B.module_generators ((0, 1), (1, 1)) sage: b = B( tuple([0,C(1)]) ) sage: b (0, 1) sage: b.weight() (1, 0, 0) The following is required, because :class:`~sage.combinat.crystals.direct_sum.DirectSumOfCrystals` takes the same arguments as :class:`DisjointUnionEnumeratedSets` (which see for details). TESTS:: sage: C = crystals.Letters(['A',2]) sage: B = crystals.DirectSum([C,C], keepkey=True) sage: B Direct sum of the crystals Family (The crystal of letters for type ['A', 2], The crystal of letters for type ['A', 2]) sage: TestSuite(C).run() """ @staticmethod def __classcall_private__(cls, crystals, facade=True, keepkey=False, category=None): """ Normalization of arguments; see :class:`UniqueRepresentation`. TESTS: We check that direct sum of crystals have unique representation:: sage: B = crystals.Tableaux(['A',2], shape=[2,1]) sage: C = crystals.Letters(['A',2]) sage: D1 = crystals.DirectSum([B, C]) sage: D2 = crystals.DirectSum((B, C)) sage: D1 is D2 True sage: D3 = crystals.DirectSum([B, C, C]) sage: D4 = crystals.DirectSum([D1, C]) sage: D3 is D4 True """ if not isinstance(facade, bool) or not isinstance(keepkey, bool): raise TypeError # Normalize the facade-keepkey by giving keepkey dominance facade = not keepkey # We expand out direct sums of crystals ret = [] for x in Family(crystals): if isinstance(x, DirectSumOfCrystals): ret += list(x.crystals) else: ret.append(x) category = Category.meet([Category.join(c.categories()) for c in ret]) return super().__classcall__(cls, Family(ret), facade=facade, keepkey=keepkey, category=category) def __init__(self, crystals, facade, keepkey, category, **options): """ TESTS:: sage: C = crystals.Letters(['A',2]) sage: B = crystals.DirectSum([C,C], keepkey=True) sage: B Direct sum of the crystals Family (The crystal of letters for type ['A', 2], The crystal of letters for type ['A', 2]) sage: B.cartan_type() ['A', 2] sage: from sage.combinat.crystals.direct_sum import DirectSumOfCrystals sage: isinstance(B, DirectSumOfCrystals) True """ DisjointUnionEnumeratedSets.__init__(self, crystals, keepkey=keepkey, facade=facade, category=category) self.rename("Direct sum of the crystals {}".format(crystals)) self._keepkey = keepkey self.crystals = crystals if len(crystals) == 0: raise ValueError("the direct sum is empty") else: assert(crystal.cartan_type() == crystals[0].cartan_type() for crystal in crystals) self._cartan_type = crystals[0].cartan_type() if keepkey: self.module_generators = tuple([ self((i,b)) for i,B in enumerate(crystals) for b in B.module_generators ]) else: self.module_generators = sum((tuple(B.module_generators) for B in crystals), ()) def weight_lattice_realization(self): r""" Return the weight lattice realization used to express weights. The weight lattice realization is the common parent which all weight lattice realizations of the crystals of ``self`` coerce into. EXAMPLES:: sage: LaZ = RootSystem(['A',2,1]).weight_lattice(extended=True).fundamental_weights() sage: LaQ = RootSystem(['A',2,1]).weight_space(extended=True).fundamental_weights() sage: B = crystals.LSPaths(LaQ[1]) sage: B.weight_lattice_realization() Extended weight space over the Rational Field of the Root system of type ['A', 2, 1] sage: C = crystals.AlcovePaths(LaZ[1]) sage: C.weight_lattice_realization() Extended weight lattice of the Root system of type ['A', 2, 1] sage: D = crystals.DirectSum([B,C]) sage: D.weight_lattice_realization() Extended weight space over the Rational Field of the Root system of type ['A', 2, 1] """ cm = get_coercion_model() return cm.common_parent(*[crystal.weight_lattice_realization() for crystal in self.crystals]) class Element(ElementWrapper): r""" A class for elements of direct sums of crystals. """ def e(self, i): r""" Return the action of `e_i` on ``self``. EXAMPLES:: sage: C = crystals.Letters(['A',2]) sage: B = crystals.DirectSum([C,C], keepkey=True) sage: [[b, b.e(2)] for b in B] [[(0, 1), None], [(0, 2), None], [(0, 3), (0, 2)], [(1, 1), None], [(1, 2), None], [(1, 3), (1, 2)]] """ v = self.value vn = v[1].e(i) if vn is None: return None else: return self.parent()(tuple([v[0],vn])) def f(self, i): r""" Return the action of `f_i` on ``self``. EXAMPLES:: sage: C = crystals.Letters(['A',2]) sage: B = crystals.DirectSum([C,C], keepkey=True) sage: [[b,b.f(1)] for b in B] [[(0, 1), (0, 2)], [(0, 2), None], [(0, 3), None], [(1, 1), (1, 2)], [(1, 2), None], [(1, 3), None]] """ v = self.value vn = v[1].f(i) if vn is None: return None else: return self.parent()(tuple([v[0],vn])) def weight(self): r""" Return the weight of ``self``. EXAMPLES:: sage: C = crystals.Letters(['A',2]) sage: B = crystals.DirectSum([C,C], keepkey=True) sage: b = B( tuple([0,C(2)]) ) sage: b (0, 2) sage: b.weight() (0, 1, 0) """ return self.value[1].weight() def phi(self, i): r""" EXAMPLES:: sage: C = crystals.Letters(['A',2]) sage: B = crystals.DirectSum([C,C], keepkey=True) sage: b = B( tuple([0,C(2)]) ) sage: b.phi(2) 1 """ return self.value[1].phi(i) def epsilon(self, i): r""" EXAMPLES:: sage: C = crystals.Letters(['A',2]) sage: B = crystals.DirectSum([C,C], keepkey=True) sage: b = B( tuple([0,C(2)]) ) sage: b.epsilon(2) 0 """ return self.value[1].epsilon(i)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/crystals/direct_sum.py
0.894728
0.627637
direct_sum.py
pypi
r""" Catalog Of Crystals Let `I` be an index set and let `(A,\Pi,\Pi^\vee,P,P^\vee)` be a Cartan datum associated with generalized Cartan matrix `A = (a_{ij})_{i,j\in I}`. An *abstract crystal* associated to this Cartan datum is a set `B` together with maps .. MATH:: e_i,f_i \colon B \to B \cup \{0\}, \qquad \varepsilon_i,\varphi_i\colon B \to \ZZ \cup \{-\infty\}, \qquad \mathrm{wt}\colon B \to P, subject to the following conditions: 1. `\varphi_i(b) = \varepsilon_i(b) + \langle h_i, \mathrm{wt}(b) \rangle` for all `b \in B` and `i \in I`; 2. `\mathrm{wt}(e_ib) = \mathrm{wt}(b) + \alpha_i` if `e_ib \in B`; 3. `\mathrm{wt}(f_ib) = \mathrm{wt}(b) - \alpha_i` if `f_ib \in B`; 4. `\varepsilon_i(e_ib) = \varepsilon_i(b) - 1`, `\varphi_i(e_ib) = \varphi_i(b) + 1` if `e_ib \in B`; 5. `\varepsilon_i(f_ib) = \varepsilon_i(b) + 1`, `\varphi_i(f_ib) = \varphi_i(b) - 1` if `f_ib \in B`; 6. `f_ib = b'` if and only if `b = e_ib'` for `b,b' \in B` and `i\in I`; 7. if `\varphi_i(b) = -\infty` for `b\in B`, then `e_ib = f_ib = 0`. .. SEEALSO:: - :mod:`sage.categories.crystals` - :mod:`sage.combinat.crystals.crystals` Catalog ------- This is a catalog of crystals that are currently implemented in Sage: * :class:`~sage.combinat.crystals.affine.AffineCrystalFromClassical` * :class:`~sage.combinat.crystals.affine.AffineCrystalFromClassicalAndPromotion` * :class:`AffineFactorization <sage.combinat.crystals.affine_factorization.AffineFactorizationCrystal>` * :class:`AffinizationOf <sage.combinat.crystals.affinization.AffinizationOfCrystal>` * :class:`AlcovePaths <sage.combinat.crystals.alcove_path.CrystalOfAlcovePaths>` * :class:`FastRankTwo <sage.combinat.crystals.fast_crystals.FastCrystal>` * :class:`FullyCommutativeStableGrothendieck <sage.combinat.crystals.fully_commutative_stable_grothendieck.FullyCommutativeStableGrothendieckCrystal>` * :class:`GeneralizedYoungWalls <sage.combinat.crystals.generalized_young_walls.CrystalOfGeneralizedYoungWalls>` * :func:`HighestWeight <sage.combinat.crystals.highest_weight_crystals.HighestWeightCrystal>` * :class:`Induced <sage.combinat.crystals.induced_structure.InducedCrystal>` * :class:`KacModule <sage.combinat.crystals.kac_modules.CrystalOfKacModule>` * :func:`KirillovReshetikhin <sage.combinat.crystals.kirillov_reshetikhin.KirillovReshetikhinCrystal>` * :class:`KleshchevPartitions <sage.combinat.partition_kleshchev.KleshchevPartitions_all>` * :class:`KyotoPathModel <sage.combinat.crystals.kyoto_path_model.KyotoPathModel>` * :class:`Letters <sage.combinat.crystals.letters.CrystalOfLetters>` * :class:`LSPaths <sage.combinat.crystals.littelmann_path.CrystalOfLSPaths>` * :class:`Minimaj <sage.combinat.multiset_partition_into_sets_ordered.MinimajCrystal>` * :class:`NakajimaMonomials <sage.combinat.crystals.monomial_crystals.CrystalOfNakajimaMonomials>` * :class:`OddNegativeRoots <sage.combinat.crystals.kac_modules.CrystalOfOddNegativeRoots>` * :class:`ProjectedLevelZeroLSPaths <sage.combinat.crystals.littelmann_path.CrystalOfProjectedLevelZeroLSPaths>` * :class:`RiggedConfigurations <sage.combinat.rigged_configurations.rc_crystal.CrystalOfRiggedConfigurations>` * :class:`ShiftedPrimedTableaux <sage.combinat.shifted_primed_tableau.ShiftedPrimedTableaux_shape>` * :class:`Spins <sage.combinat.crystals.spins.CrystalOfSpins>` * :class:`SpinsPlus <sage.combinat.crystals.spins.CrystalOfSpinsPlus>` * :class:`SpinsMinus <sage.combinat.crystals.spins.CrystalOfSpinsMinus>` * :class:`Tableaux <sage.combinat.crystals.tensor_product.CrystalOfTableaux>` Subcatalogs: * :ref:`sage.combinat.crystals.catalog_infinity_crystals` * :ref:`sage.combinat.crystals.catalog_elementary_crystals` * :ref:`sage.combinat.crystals.catalog_kirillov_reshetikhin` Functorial constructions: * :class:`DirectSum <sage.combinat.crystals.direct_sum.DirectSumOfCrystals>` * :class:`TensorProduct <sage.combinat.crystals.tensor_product.TensorProductOfCrystals>` """ from .letters import CrystalOfLetters as Letters from .spins import CrystalOfSpins as Spins from .spins import CrystalOfSpinsPlus as SpinsPlus from .spins import CrystalOfSpinsMinus as SpinsMinus from .tensor_product import CrystalOfTableaux as Tableaux from .fast_crystals import FastCrystal as FastRankTwo from .affine import AffineCrystalFromClassical as AffineFromClassical from .affine import AffineCrystalFromClassicalAndPromotion as AffineFromClassicalAndPromotion from .affine_factorization import AffineFactorizationCrystal as AffineFactorization from .fully_commutative_stable_grothendieck import FullyCommutativeStableGrothendieckCrystal as FullyCommutativeStableGrothendieck from sage.combinat.crystals.affinization import AffinizationOfCrystal as AffinizationOf from .highest_weight_crystals import HighestWeightCrystal as HighestWeight from .alcove_path import CrystalOfAlcovePaths as AlcovePaths from .littelmann_path import CrystalOfLSPaths as LSPaths from .littelmann_path import CrystalOfProjectedLevelZeroLSPaths as ProjectedLevelZeroLSPaths from .kyoto_path_model import KyotoPathModel from .generalized_young_walls import CrystalOfGeneralizedYoungWalls as GeneralizedYoungWalls from .monomial_crystals import CrystalOfNakajimaMonomials as NakajimaMonomials from sage.combinat.rigged_configurations.tensor_product_kr_tableaux import TensorProductOfKirillovReshetikhinTableaux from sage.combinat.crystals.kirillov_reshetikhin import KirillovReshetikhinCrystal as KirillovReshetikhin from sage.combinat.rigged_configurations.rc_crystal import CrystalOfRiggedConfigurations as RiggedConfigurations from sage.combinat.shifted_primed_tableau import ShiftedPrimedTableaux_shape as ShiftedPrimedTableaux from sage.combinat.partition_kleshchev import KleshchevPartitions from sage.combinat.multiset_partition_into_sets_ordered import MinimajCrystal as Minimaj from sage.combinat.crystals.induced_structure import InducedCrystal as Induced from sage.combinat.crystals.kac_modules import CrystalOfKacModule as KacModule from sage.combinat.crystals.kac_modules import CrystalOfOddNegativeRoots as OddNegativeRoots from .tensor_product import TensorProductOfCrystals as TensorProduct from .direct_sum import DirectSumOfCrystals as DirectSum from . import catalog_kirillov_reshetikhin as kirillov_reshetikhin from . import catalog_infinity_crystals as infinity from . import catalog_elementary_crystals as elementary
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/crystals/catalog.py
0.851675
0.771349
catalog.py
pypi
from sage.structure.parent import Parent from sage.categories.regular_supercrystals import RegularSuperCrystals from sage.combinat.partition import _Partitions from sage.combinat.root_system.cartan_type import CartanType from sage.combinat.crystals.letters import CrystalOfBKKLetters from sage.combinat.crystals.tensor_product import CrystalOfWords from sage.combinat.crystals.tensor_product_element import CrystalOfBKKTableauxElement class CrystalOfBKKTableaux(CrystalOfWords): r""" Crystal of tableaux for type `A(m|n)`. This is an implementation of the tableaux model of the Benkart-Kang-Kashiwara crystal [BKK2000]_ for the Lie superalgebra `\mathfrak{gl}(m+1,n+1)`. INPUT: - ``ct`` -- a super Lie Cartan type of type `A(m|n)` - ``shape`` -- shape specifying the highest weight; this should be a partition contained in a hook of height `n+1` and width `m+1` EXAMPLES:: sage: T = crystals.Tableaux(['A', [1,1]], shape = [2,1]) sage: T.cardinality() 20 """ @staticmethod def __classcall_private__(cls, ct, shape): """ Normalize input to ensure a unique representation. TESTS:: sage: crystals.Tableaux(['A', [1, 2]], shape=[2,1]) Crystal of BKK tableaux of shape [2, 1] of gl(2|3) sage: crystals.Tableaux(['A', [1, 1]], shape=[3,3,3]) Traceback (most recent call last): ... ValueError: invalid hook shape """ ct = CartanType(ct) shape = _Partitions(shape) if len(shape) > ct.m + 1 and shape[ct.m+1] > ct.n + 1: raise ValueError("invalid hook shape") return super().__classcall__(cls, ct, shape) def __init__(self, ct, shape): r""" Initialize ``self``. TESTS:: sage: T = crystals.Tableaux(['A', [1,1]], shape = [2,1]); T Crystal of BKK tableaux of shape [2, 1] of gl(2|2) sage: TestSuite(T).run() """ self._shape = shape self._cartan_type = ct m = ct.m + 1 C = CrystalOfBKKLetters(ct) tr = shape.conjugate() mg = [] for i,col_len in enumerate(tr): for j in range(col_len - m): mg.append(C(i+1)) for j in range(max(0, m - col_len), m): mg.append(C(-j-1)) mg = list(reversed(mg)) Parent.__init__(self, category=RegularSuperCrystals()) self.module_generators = (self.element_class(self, mg),) def _repr_(self): """ Return a string representation of ``self``. TESTS:: sage: crystals.Tableaux(['A', [1, 2]], shape=[2,1]) Crystal of BKK tableaux of shape [2, 1] of gl(2|3) """ m = self._cartan_type.m + 1 n = self._cartan_type.n + 1 return "Crystal of BKK tableaux of shape {} of gl({}|{})".format(self.shape(), m, n) def shape(self): r""" Return the shape of ``self``. EXAMPLES:: sage: T = crystals.Tableaux(['A', [1, 2]], shape=[2,1]) sage: T.shape() [2, 1] """ return self._shape def genuine_highest_weight_vectors(self, index_set=None): """ Return a tuple of genuine highest weight elements. A *fake highest weight vector* is one which is annihilated by `e_i` for all `i` in the index set, but whose weight is not bigger in dominance order than all other elements in the crystal. A *genuine highest weight vector* is a highest weight element that is not fake. EXAMPLES:: sage: B = crystals.Tableaux(['A', [1,1]], shape=[3,2,1]) sage: B.genuine_highest_weight_vectors() ([[-2, -2, -2], [-1, -1], [1]],) sage: B.highest_weight_vectors() ([[-2, -2, -2], [-1, -1], [1]], [[-2, -2, -2], [-1, 2], [1]], [[-2, -2, 2], [-1, -1], [1]]) """ if index_set is None or index_set == self.index_set(): return self.module_generators return super().genuine_highest_weight_vectors(index_set) class Element(CrystalOfBKKTableauxElement): pass
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/crystals/bkk_crystals.py
0.893562
0.613497
bkk_crystals.py
pypi
import copy from sage.combinat.combinat import CombinatorialObject from sage.combinat.words.word import Word from sage.combinat.combination import Combinations from sage.combinat.permutation import Permutation from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.rational_field import QQ from sage.misc.misc_c import prod from sage.combinat.backtrack import GenericBacktracker from sage.structure.parent import Parent from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets from sage.structure.unique_representation import UniqueRepresentation class LatticeDiagram(CombinatorialObject): def boxes(self): """ EXAMPLES:: sage: a = LatticeDiagram([3,0,2]) sage: a.boxes() [(1, 1), (1, 2), (1, 3), (3, 1), (3, 2)] sage: a = LatticeDiagram([2, 1, 3, 0, 0, 2]) sage: a.boxes() [(1, 1), (1, 2), (2, 1), (3, 1), (3, 2), (3, 3), (6, 1), (6, 2)] """ res = [] for i in range(1, len(self) + 1): res += [(i, j + 1) for j in range(self[i])] return res def __getitem__(self, i): """ Return the `i^{th}` entry of ``self``. Note that the indexing for lattice diagrams starts at `1`. EXAMPLES:: sage: a = LatticeDiagram([3,0,2]) sage: a[1] 3 sage: a[0] Traceback (most recent call last): ... ValueError: indexing starts at 1 sage: a[-1] 2 """ if i == 0: raise ValueError("indexing starts at 1") elif i < 0: i += 1 return self._list[i - 1] def leg(self, i, j): """ Return the leg of the box ``(i,j)`` in ``self``. EXAMPLES:: sage: a = LatticeDiagram([3,1,2,4,3,0,4,2,3]) sage: a.leg(5,2) [(5, 3)] """ return [(i, k) for k in range(j + 1, self[i] + 1)] def arm_left(self, i, j): """ Return the left arm of the box ``(i,j)`` in ``self``. EXAMPLES:: sage: a = LatticeDiagram([3,1,2,4,3,0,4,2,3]) sage: a.arm_left(5,2) [(1, 2), (3, 2)] """ return [(ip, j) for ip in range(1, i) if j <= self[ip] <= self[i]] def arm_right(self, i, j): """ Return the right arm of the box ``(i,j)`` in ``self``. EXAMPLES:: sage: a = LatticeDiagram([3,1,2,4,3,0,4,2,3]) sage: a.arm_right(5,2) [(8, 1)] """ return [(ip, j - 1) for ip in range(i + 1, len(self) + 1) if j - 1 <= self[ip] < self[i]] def arm(self, i, j): """ Return the arm of the box ``(i,j)`` in ``self``. EXAMPLES:: sage: a = LatticeDiagram([3,1,2,4,3,0,4,2,3]) sage: a.arm(5,2) [(1, 2), (3, 2), (8, 1)] """ return self.arm_left(i, j) + self.arm_right(i, j) def l(self, i, j): """ Return ``self[i] - j``. EXAMPLES:: sage: a = LatticeDiagram([3,1,2,4,3,0,4,2,3]) sage: a.l(5,2) 1 """ return self[i] - j def a(self, i, j): """ Return the length of the arm of the box ``(i,j)`` in ``self``. EXAMPLES:: sage: a = LatticeDiagram([3,1,2,4,3,0,4,2,3]) sage: a.a(5,2) 3 """ return len(self.arm(i, j)) def size(self): """ Return the number of boxes in ``self``. EXAMPLES:: sage: a = LatticeDiagram([3,1,2,4,3,0,4,2,3]) sage: a.size() 22 """ return sum(self._list) def flip(self): """ Return the flip of ``self``, where flip is defined as follows. Let ``r = max(self)``. Then ``self.flip()[i] = r - self[i]``. EXAMPLES:: sage: a = LatticeDiagram([3,0,2]) sage: a.flip() [0, 3, 1] """ r = max(self) return LatticeDiagram([r - i for i in self]) def boxes_same_and_lower_right(self, ii, jj): """ Return a list of the boxes of ``self`` that are in row ``jj`` but not identical with ``(ii, jj)``, or lie in the row ``jj - 1`` (the row directly below ``jj``; this might be the basement) and strictly to the right of ``(ii, jj)``. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a = a.shape() sage: a.boxes_same_and_lower_right(1,1) [(2, 1), (3, 1), (6, 1), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0)] sage: a.boxes_same_and_lower_right(1,2) [(3, 2), (6, 2), (2, 1), (3, 1), (6, 1)] sage: a.boxes_same_and_lower_right(3,3) [(6, 2)] sage: a.boxes_same_and_lower_right(2,3) [(3, 3), (3, 2), (6, 2)] """ res = [] # Add all of the boxes in the same row for i in range(1, len(self) + 1): if self[i] >= jj and i != ii: res.append((i, jj)) for i in range(ii + 1, len(self) + 1): if self[i] >= jj - 1: res.append((i, jj - 1)) return res class AugmentedLatticeDiagramFilling(CombinatorialObject): def __init__(self, l, pi=None): """ EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a == loads(dumps(a)) True sage: pi = Permutation([2,3,1]).to_permutation_group_element() sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]],pi) sage: a == loads(dumps(a)) True """ if pi is None: pi = Permutation([1]).to_permutation_group_element() self._list = [[pi(i + 1)] + li for i, li in enumerate(l)] def __getitem__(self, i): """ EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a[0] Traceback (most recent call last): ... ValueError: indexing starts at 1 sage: a[1,0] 1 sage: a[2,0] 2 sage: a[3,2] 4 sage: a[3][2] 4 """ if isinstance(i, tuple): i, j = i return self._list[i - 1][j] if i < 1: raise ValueError("indexing starts at 1") return self._list[i - 1] def shape(self): """ Return the shape of ``self``. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.shape() [2, 1, 3, 0, 0, 2] """ return LatticeDiagram([max(0, len(self[i]) - 1) for i in range(1, len(self) + 1)]) def __contains__(self, ij): """ Return ``True`` if the box ``(i,j) (= ij)`` is in ``self``. Note that this does not include the basement row. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: (1,1) in a True sage: (1,0) in a False """ i, j = ij return 0 < i <= len(self) and 0 < j <= len(self[i]) def are_attacking(self, i, j, ii, jj): """ Return ``True`` if the boxes ``(i,j)`` and ``(ii,jj)`` in ``self`` are attacking. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: all( a.are_attacking(i,j,ii,jj) for (i,j),(ii,jj) in a.attacking_boxes()) True sage: a.are_attacking(1,1,3,2) False """ # If the two boxes are at the same height, # then they are attacking if j == jj: return True # Make it so that the lower box is in position i,j if jj < j: i, j, ii, jj = ii, jj, i, j # If the lower box is one row below and # strictly to the right, then they are # attacking. return j == jj - 1 and i > ii def boxes(self): """ Return a list of the coordinates of the boxes of ``self``, including the 'basement row'. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.boxes() [(1, 1), (1, 2), (2, 1), (3, 1), (3, 2), (3, 3), (6, 1), (6, 2), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0)] """ return self.shape().boxes() + [(i, 0) for i in range(1, len(self.shape()) + 1)] def attacking_boxes(self): """ Return a list of pairs of boxes in ``self`` that are attacking. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.attacking_boxes()[:5] [((1, 1), (2, 1)), ((1, 1), (3, 1)), ((1, 1), (6, 1)), ((1, 1), (2, 0)), ((1, 1), (3, 0))] """ boxes = self.boxes() res = [] for (i, j), (ii, jj) in Combinations(boxes, 2): if self.are_attacking(i, j, ii, jj): res.append(((i, j), (ii, jj))) return res def is_non_attacking(self): """ Return ``True`` if ``self`` is non-attacking. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.is_non_attacking() True sage: a = AugmentedLatticeDiagramFilling([[1, 1, 1], [2, 3], [3]]) sage: a.is_non_attacking() False sage: a = AugmentedLatticeDiagramFilling([[2,2],[1]]) sage: a.is_non_attacking() False sage: pi = Permutation([2,1]).to_permutation_group_element() sage: a = AugmentedLatticeDiagramFilling([[2,2],[1]],pi) sage: a.is_non_attacking() True """ for a, b in self.attacking_boxes(): if self[a] == self[b]: return False return True def weight(self): """ Return the weight of ``self``. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.weight() [1, 2, 1, 1, 2, 1] """ ed = self.reading_word().evaluation_dict() entries = list(ed) m = max(entries) + 1 if entries else -1 return [ed.get(k, 0) for k in range(1, m)] def descents(self): """ Return a list of the descents of ``self``. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.descents() [(1, 2), (3, 2)] """ res = [] for i, j in self.shape().boxes(): if self[i, j] > self[i, j - 1]: res.append((i, j)) return res def maj(self): """ Return the major index of ``self``. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.maj() 3 """ res = 0 shape = self.shape() for i, j in self.descents(): res += shape.l(i, j) + 1 return res def reading_order(self): """ Return a list of coordinates of the boxes in ``self``, starting from the top right, and reading from right to left. Note that this includes the 'basement row' of ``self``. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.reading_order() [(3, 3), (6, 2), (3, 2), (1, 2), (6, 1), (3, 1), (2, 1), (1, 1), (6, 0), (5, 0), (4, 0), (3, 0), (2, 0), (1, 0)] """ boxes = self.boxes() def fn(ij): return (-ij[1], -ij[0]) boxes.sort(key=fn) return boxes def reading_word(self): """ Return the reading word of ``self``, obtained by reading the boxes entries of self from right to left, starting in the upper right. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.reading_word() word: 25465321 """ w = [self[i, j] for i, j in self.reading_order() if j > 0] return Word(w) def inversions(self): """ Return a list of the inversions of ``self``. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.inversions()[:5] [((6, 2), (3, 2)), ((1, 2), (6, 1)), ((1, 2), (3, 1)), ((1, 2), (2, 1)), ((6, 1), (3, 1))] sage: len(a.inversions()) 25 """ atboxes = [set(x) for x in self.attacking_boxes()] res = [] order = self.reading_order() for a in range(len(order)): i, j = order[a] for b in range(a + 1, len(order)): ii, jj = order[b] if self[i, j] > self[ii, jj] and set(((i, j), (ii, jj))) in atboxes: res.append(((i, j), (ii, jj))) return res def _inv_aux(self): """ EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a._inv_aux() 7 """ res = 0 shape = self.shape() for i in range(1, len(self) + 1): for j in range(i + 1, len(self) + 1): if shape[i] <= shape[j]: res += 1 return res def inv(self): """ Return ``self``'s inversion statistic. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.inv() 15 """ res = len(self.inversions()) res -= sum(self.shape().a(i, j) for i, j in self.descents()) res -= self._inv_aux() return res def coinv(self): """ Return ``self``'s co-inversion statistic. EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: a.coinv() 2 """ shape = self.shape() return sum(shape.a(i, j) for i, j in shape.boxes()) - self.inv() def coeff(self, q, t): """ Return the coefficient in front of ``self`` in the HHL formula for the expansion of the non-symmetric Macdonald polynomial E(self.shape()). EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: q,t = var('q,t') sage: a.coeff(q,t) (t - 1)^4/((q^2*t^3 - 1)^2*(q*t^2 - 1)^2) """ res = 1 shape = self.shape() for i, j in shape.boxes(): if self[i, j] != self[i, j - 1]: res *= (1 - t) / (1 - q**(shape.l(i, j) + 1) * t**(shape.a(i, j) + 1)) return res def coeff_integral(self, q, t): """ Return the coefficient in front of ``self`` in the HHL formula for the expansion of the integral non-symmetric Macdonald polynomial E(self.shape()) EXAMPLES:: sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: q,t = var('q,t') sage: a.coeff_integral(q,t) (q^2*t^3 - 1)^2*(q*t^2 - 1)^2*(t - 1)^4 """ res = 1 shape = self.shape() for i, j in shape.boxes(): if self[i, j] != self[i, j - 1]: res *= (1 - q**(shape.l(i, j) + 1) * t**(shape.a(i, j) + 1)) for i, j in shape.boxes(): if self[i, j] == self[i, j - 1]: res *= (1 - t) return res def permuted_filling(self, sigma): """ EXAMPLES:: sage: pi=Permutation([2,1,4,3]).to_permutation_group_element() sage: fill=[[2],[1,2,3],[],[3,1]] sage: AugmentedLatticeDiagramFilling(fill).permuted_filling(pi) [[2, 1], [1, 2, 1, 4], [4], [3, 4, 2]] """ new_filling = [] for col in self: nc = [sigma(x) for x in col] nc.pop(0) new_filling.append(nc) return AugmentedLatticeDiagramFilling(new_filling, sigma) def NonattackingFillings(shape, pi=None): """ Returning the finite set of nonattacking fillings of a given shape. EXAMPLES:: sage: NonattackingFillings([0,1,2]) Nonattacking fillings of [0, 1, 2] sage: NonattackingFillings([0,1,2]).list() [[[1], [2, 1], [3, 2, 1]], [[1], [2, 1], [3, 2, 2]], [[1], [2, 1], [3, 2, 3]], [[1], [2, 1], [3, 3, 1]], [[1], [2, 1], [3, 3, 2]], [[1], [2, 1], [3, 3, 3]], [[1], [2, 2], [3, 1, 1]], [[1], [2, 2], [3, 1, 2]], [[1], [2, 2], [3, 1, 3]], [[1], [2, 2], [3, 3, 1]], [[1], [2, 2], [3, 3, 2]], [[1], [2, 2], [3, 3, 3]]] """ return NonattackingFillings_shape(tuple(shape), pi) class NonattackingFillings_shape(Parent, UniqueRepresentation): def __init__(self, shape, pi=None): """ EXAMPLES:: sage: n = NonattackingFillings([0,1,2]) sage: n == loads(dumps(n)) True """ self.pi = pi self._shape = LatticeDiagram(shape) self._name = "Nonattacking fillings of %s" % list(shape) Parent.__init__(self, category=FiniteEnumeratedSets()) def __repr__(self): """ EXAMPLES:: sage: NonattackingFillings([0,1,2]) Nonattacking fillings of [0, 1, 2] """ return self._name def flip(self): """ Return the nonattacking fillings of the flipped shape. EXAMPLES:: sage: NonattackingFillings([0,1,2]).flip() Nonattacking fillings of [2, 1, 0] """ return NonattackingFillings(list(self._shape.flip()), self.pi) def __iter__(self): """ EXAMPLES:: sage: NonattackingFillings([0,1,2]).list() #indirect doctest [[[1], [2, 1], [3, 2, 1]], [[1], [2, 1], [3, 2, 2]], [[1], [2, 1], [3, 2, 3]], [[1], [2, 1], [3, 3, 1]], [[1], [2, 1], [3, 3, 2]], [[1], [2, 1], [3, 3, 3]], [[1], [2, 2], [3, 1, 1]], [[1], [2, 2], [3, 1, 2]], [[1], [2, 2], [3, 1, 3]], [[1], [2, 2], [3, 3, 1]], [[1], [2, 2], [3, 3, 2]], [[1], [2, 2], [3, 3, 3]]] sage: len(_) 12 TESTS:: sage: NonattackingFillings([3,2,1,1]).cardinality() 3 sage: NonattackingFillings([3,2,1,2]).cardinality() 4 sage: NonattackingFillings([1,2,3]).cardinality() 12 sage: NonattackingFillings([2,2,2]).cardinality() 1 sage: NonattackingFillings([1,2,3,2]).cardinality() 24 """ if sum(self._shape) == 0: yield AugmentedLatticeDiagramFilling([[] for _ in self._shape], self.pi) return for z in NonattackingBacktracker(self._shape, self.pi): yield AugmentedLatticeDiagramFilling(z, self.pi) class NonattackingBacktracker(GenericBacktracker): def __init__(self, shape, pi=None): """ EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import NonattackingBacktracker sage: n = NonattackingBacktracker(LatticeDiagram([0,1,2])) sage: n._ending_position (3, 2) sage: n._initial_state (2, 1) """ self._shape = shape self._n = sum(shape) self._initial_data = [[None] * s for s in shape] if pi is None: pi = Permutation([1]).to_permutation_group_element() self.pi = pi # The ending position will be at the highest box # which is farthest right ending_row = max(shape) ending_col = len(shape) - list(reversed(list(shape))).index(ending_row) self._ending_position = (ending_col, ending_row) # Get the lowest box that is farthest left starting_row = 1 nonzero = [i for i in shape if i != 0] starting_col = list(shape).index(nonzero[0]) + 1 GenericBacktracker.__init__(self, self._initial_data, (starting_col, starting_row)) def _rec(self, obj, state): """ EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import NonattackingBacktracker sage: n = NonattackingBacktracker(LatticeDiagram([0,1,2])) sage: len(list(n)) 12 sage: obj = [ [], [None], [None, None]] sage: state = 2, 1 sage: list(n._rec(obj, state)) [([[], [1], [None, None]], (3, 1), False), ([[], [2], [None, None]], (3, 1), False)] """ # We need to set the i,j^th entry. i, j = state # Get the next state new_state = self.get_next_pos(i, j) yld = bool(new_state is None) for k in range(1, len(self._shape) + 1): # We check to make sure that k does not # violate any of the attacking conditions if j == 1 and any(self.pi(x + 1) == k for x in range(i, len(self._shape))): continue if any(obj[ii - 1][jj - 1] == k for ii, jj in self._shape.boxes_same_and_lower_right(i, j) if jj != 0): continue # Fill in the in the i,j box with k+1 obj[i - 1][j - 1] = k # Yield the object yield copy.deepcopy(obj), new_state, yld def get_next_pos(self, ii, jj): """ EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import NonattackingBacktracker sage: a = AugmentedLatticeDiagramFilling([[1,6],[2],[3,4,2],[],[],[5,5]]) sage: n = NonattackingBacktracker(a.shape()) sage: n.get_next_pos(1, 1) (2, 1) sage: n.get_next_pos(6, 1) (1, 2) sage: n = NonattackingBacktracker(LatticeDiagram([2,2,2])) sage: n.get_next_pos(3, 1) (1, 2) """ if (ii, jj) == self._ending_position: return None for i in range(ii + 1, len(self._shape) + 1): if self._shape[i] >= jj: return i, jj for i in range(1, ii + 1): if self._shape[i] >= jj + 1: return i, jj + 1 raise ValueError("we should never be here") def _check_muqt(mu, q, t, pi=None): """ EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import _check_muqt sage: P, q, t, n, R, x = _check_muqt([0,0,1],None,None) sage: P Fraction Field of Multivariate Polynomial Ring in q, t over Rational Field sage: q q sage: t t sage: n Nonattacking fillings of [0, 0, 1] sage: R Multivariate Polynomial Ring in x0, x1, x2 over Fraction Field of Multivariate Polynomial Ring in q, t over Rational Field sage: x (x0, x1, x2) :: sage: q,t = var('q,t') sage: P, q, t, n, R, x = _check_muqt([0,0,1],q,None) Traceback (most recent call last): ... ValueError: you must specify either both q and t or neither of them :: sage: P, q, t, n, R, x = _check_muqt([0,0,1],q,2) Traceback (most recent call last): ... ValueError: the parents of q and t must be the same """ if q is None and t is None: P = PolynomialRing(QQ, 'q,t').fraction_field() q, t = P.gens() elif q is not None and t is not None: if q.parent() != t.parent(): raise ValueError("the parents of q and t must be the same") P = q.parent() else: raise ValueError("you must specify either both q and t or neither of them") n = NonattackingFillings(mu, pi) R = PolynomialRing(P, len(n._shape), 'x') x = R.gens() return P, q, t, n, R, x def E(mu, q=None, t=None, pi=None): """ Return the non-symmetric Macdonald polynomial in type A corresponding to a shape ``mu``, with basement permuted according to ``pi``. Note that if both `q` and `t` are specified, then they must have the same parent. REFERENCE: - J. Haglund, M. Haiman, N. Loehr. *A combinatorial formula for non-symmetric Macdonald polynomials*. :arxiv:`math/0601693v3`. .. SEEALSO:: :class:`~sage.combinat.root_system.non_symmetric_macdonald_polynomials.NonSymmetricMacdonaldPolynomials` for a type free implementation where the polynomials are constructed recursively by the application of intertwining operators. EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import E sage: E([0,0,0]) 1 sage: E([1,0,0]) x0 sage: E([0,1,0]) (t - 1)/(q*t^2 - 1)*x0 + x1 sage: E([0,0,1]) (t - 1)/(q*t - 1)*x0 + (t - 1)/(q*t - 1)*x1 + x2 sage: E([1,1,0]) x0*x1 sage: E([1,0,1]) (t - 1)/(q*t^2 - 1)*x0*x1 + x0*x2 sage: E([0,1,1]) (t - 1)/(q*t - 1)*x0*x1 + (t - 1)/(q*t - 1)*x0*x2 + x1*x2 sage: E([2,0,0]) x0^2 + (q*t - q)/(q*t - 1)*x0*x1 + (q*t - q)/(q*t - 1)*x0*x2 sage: E([0,2,0]) (t - 1)/(q^2*t^2 - 1)*x0^2 + (q^2*t^3 - q^2*t^2 + q*t^2 - 2*q*t + q - t + 1)/(q^3*t^3 - q^2*t^2 - q*t + 1)*x0*x1 + x1^2 + (q*t^2 - 2*q*t + q)/(q^3*t^3 - q^2*t^2 - q*t + 1)*x0*x2 + (q*t - q)/(q*t - 1)*x1*x2 """ P, q, t, n, R, x = _check_muqt(mu, q, t, pi) res = 0 for a in n: weight = a.weight() res += q**a.maj() * t**a.coinv() * a.coeff(q, t) * prod(x[i]**weight[i] for i in range(len(weight))) return res def E_integral(mu, q=None, t=None, pi=None): """ Return the integral form for the non-symmetric Macdonald polynomial in type A corresponding to a shape mu. Note that if both q and t are specified, then they must have the same parent. REFERENCE: - J. Haglund, M. Haiman, N. Loehr. *A combinatorial formula for non-symmetric Macdonald polynomials*. :arxiv:`math/0601693v3`. EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import E_integral sage: E_integral([0,0,0]) 1 sage: E_integral([1,0,0]) (-t + 1)*x0 sage: E_integral([0,1,0]) (-q*t^2 + 1)*x0 + (-t + 1)*x1 sage: E_integral([0,0,1]) (-q*t + 1)*x0 + (-q*t + 1)*x1 + (-t + 1)*x2 sage: E_integral([1,1,0]) (t^2 - 2*t + 1)*x0*x1 sage: E_integral([1,0,1]) (q*t^3 - q*t^2 - t + 1)*x0*x1 + (t^2 - 2*t + 1)*x0*x2 sage: E_integral([0,1,1]) (q^2*t^3 + q*t^4 - q*t^3 - q*t^2 - q*t - t^2 + t + 1)*x0*x1 + (q*t^2 - q*t - t + 1)*x0*x2 + (t^2 - 2*t + 1)*x1*x2 sage: E_integral([2,0,0]) (t^2 - 2*t + 1)*x0^2 + (q^2*t^2 - q^2*t - q*t + q)*x0*x1 + (q^2*t^2 - q^2*t - q*t + q)*x0*x2 sage: E_integral([0,2,0]) (q^2*t^3 - q^2*t^2 - t + 1)*x0^2 + (q^4*t^3 - q^3*t^2 - q^2*t + q*t^2 - q*t + q - t + 1)*x0*x1 + (t^2 - 2*t + 1)*x1^2 + (q^4*t^3 - q^3*t^2 - q^2*t + q)*x0*x2 + (q^2*t^2 - q^2*t - q*t + q)*x1*x2 """ P, q, t, n, R, x = _check_muqt(mu, q, t, pi) res = 0 for a in n: weight = a.weight() res += q**a.maj() * t**a.coinv() * a.coeff_integral(q, t) * prod(x[i]**weight[i] for i in range(len(weight))) return res def Ht(mu, q=None, t=None, pi=None): """ Return the symmetric Macdonald polynomial using the Haiman, Haglund, and Loehr formula. Note that if both `q` and `t` are specified, then they must have the same parent. REFERENCE: - J. Haglund, M. Haiman, N. Loehr. *A combinatorial formula for non-symmetric Macdonald polynomials*. :arxiv:`math/0601693v3`. EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import Ht sage: HHt = SymmetricFunctions(QQ['q','t'].fraction_field()).macdonald().Ht() sage: Ht([0,0,1]) x0 + x1 + x2 sage: HHt([1]).expand(3) x0 + x1 + x2 sage: Ht([0,0,2]) x0^2 + (q + 1)*x0*x1 + x1^2 + (q + 1)*x0*x2 + (q + 1)*x1*x2 + x2^2 sage: HHt([2]).expand(3) x0^2 + (q + 1)*x0*x1 + x1^2 + (q + 1)*x0*x2 + (q + 1)*x1*x2 + x2^2 """ P, q, t, n, R, x = _check_muqt(mu, q, t, pi) res = 0 for a in n: weight = a.weight() res += q**a.maj() * t**a.inv() * prod(x[i]**weight[i] for i in range(len(weight))) return res
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/sf/ns_macdonald.py
0.784236
0.62855
ns_macdonald.py
pypi
from . import sfa, multiplicative, classical from sage.combinat.partition import Partition from sage.arith.all import divisors from sage.rings.infinity import infinity from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.misc.misc_c import prod class SymmetricFunctionAlgebra_power(multiplicative.SymmetricFunctionAlgebra_multiplicative): def __init__(self, Sym): """ A class for methods associated to the power sum basis of the symmetric functions INPUT: - ``self`` -- the power sum basis of the symmetric functions - ``Sym`` -- an instance of the ring of symmetric functions TESTS:: sage: p = SymmetricFunctions(QQ).p() sage: p == loads(dumps(p)) True sage: TestSuite(p).run(skip=['_test_associativity', '_test_distributivity', '_test_prod']) sage: TestSuite(p).run(elements = [p[1,1]+p[2], p[1]+2*p[1,1]]) """ classical.SymmetricFunctionAlgebra_classical.__init__(self, Sym, "powersum", 'p') def coproduct_on_generators(self, i): r""" Return coproduct on generators for power sums `p_i` (for `i > 0`). The elements `p_i` are primitive elements. INPUT: - ``self`` -- the power sum basis of the symmetric functions - ``i`` -- a positive integer OUTPUT: - the result of the coproduct on the generator `p(i)` EXAMPLES:: sage: Sym = SymmetricFunctions(QQ) sage: p = Sym.powersum() sage: p.coproduct_on_generators(2) p[] # p[2] + p[2] # p[] """ Pi = Partition([i]) P0 = Partition([]) T = self.tensor_square() return T.sum_of_monomials( [(Pi, P0), (P0, Pi)] ) def antipode_on_basis(self, partition): r""" Return the antipode of ``self[partition]``. The antipode on the generator `p_i` (for `i > 0`) is `-p_i`, and the antipode on `p_\mu` is `(-1)^{length(\mu)} p_\mu`. INPUT: - ``self`` -- the power sum basis of the symmetric functions - ``partition`` -- a partition OUTPUT: - the result of the antipode on ``self(partition)`` EXAMPLES:: sage: Sym = SymmetricFunctions(QQ) sage: p = Sym.p() sage: p.antipode_on_basis([2]) -p[2] sage: p.antipode_on_basis([3]) -p[3] sage: p.antipode_on_basis([2,2]) p[2, 2] sage: p.antipode_on_basis([]) p[] """ if len(partition) % 2 == 0: return self[partition] return -self[partition] #This is slightly faster than: return (-1)**len(partition) * self[partition] def bottom_schur_function(self, partition, degree=None): r""" Return the least-degree component of ``s[partition]``, where ``s`` denotes the Schur basis of the symmetric functions, and the grading is not the usual grading on the symmetric functions but rather the grading which gives every `p_i` degree `1`. This least-degree component has its degree equal to the Frobenius rank of ``partition``, while the degree with respect to the usual grading is still the size of ``partition``. This method requires the base ring to be a (commutative) `\QQ`-algebra. This restriction is unavoidable, since the least-degree component (in general) has noninteger coefficients in all classical bases of the symmetric functions. The optional keyword ``degree`` allows taking any homogeneous component rather than merely the least-degree one. Specifically, if ``degree`` is set, then the ``degree``-th component will be returned. REFERENCES: .. [ClSt03] Peter Clifford, Richard P. Stanley, *Bottom Schur functions*. :arxiv:`math/0311382v2`. EXAMPLES:: sage: Sym = SymmetricFunctions(QQ) sage: p = Sym.p() sage: p.bottom_schur_function([2,2,1]) -1/6*p[3, 2] + 1/4*p[4, 1] sage: p.bottom_schur_function([2,1]) -1/3*p[3] sage: p.bottom_schur_function([3]) 1/3*p[3] sage: p.bottom_schur_function([1,1,1]) 1/3*p[3] sage: p.bottom_schur_function(Partition([1,1,1])) 1/3*p[3] sage: p.bottom_schur_function([2,1], degree=1) -1/3*p[3] sage: p.bottom_schur_function([2,1], degree=2) 0 sage: p.bottom_schur_function([2,1], degree=3) 1/3*p[1, 1, 1] sage: p.bottom_schur_function([2,2,1], degree=3) 1/8*p[2, 2, 1] - 1/6*p[3, 1, 1] """ from sage.combinat.partition import _Partitions s = self.realization_of().schur() partition = _Partitions(partition) if degree is None: degree = partition.frobenius_rank() s_partition = self(s[partition]) return self.sum_of_terms([(p, coeff) for p, coeff in s_partition if len(p) == degree], distinct=True) def eval_at_permutation_roots_on_generators(self, k, rho): r""" Evaluate `p_k` at eigenvalues of permutation matrix. This function evaluates a symmetric function ``p([k])`` at the eigenvalues of a permutation matrix with cycle structure ``\rho``. This function evaluates a `p_k` at the roots of unity .. MATH:: \Xi_{\rho_1},\Xi_{\rho_2},\ldots,\Xi_{\rho_\ell} where .. MATH:: \Xi_{m} = 1,\zeta_m,\zeta_m^2,\ldots,\zeta_m^{m-1} and `\zeta_m` is an `m` root of unity. This is characterized by `p_k[ A , B ] = p_k[A] + p_k[B]` and `p_k[ \Xi_m ] = 0` unless `m` divides `k` and `p_{rm}[\Xi_m]=m`. INPUT: - ``k`` -- a non-negative integer - ``rho`` -- a partition or a list of non-negative integers OUTPUT: - an element of the base ring EXAMPLES:: sage: p = SymmetricFunctions(QQ).p() sage: p.eval_at_permutation_roots_on_generators(3, [6]) 0 sage: p.eval_at_permutation_roots_on_generators(3, [3]) 3 sage: p.eval_at_permutation_roots_on_generators(3, [1]) 1 sage: p.eval_at_permutation_roots_on_generators(3, [3,3]) 6 sage: p.eval_at_permutation_roots_on_generators(3, [1,1,1,1,1]) 5 """ return self.base_ring().sum(d*list(rho).count(d) for d in divisors(k)) class Element(classical.SymmetricFunctionAlgebra_classical.Element): def omega(self): r""" Return the image of ``self`` under the omega automorphism. The *omega automorphism* is defined to be the unique algebra endomorphism `\omega` of the ring of symmetric functions that satisfies `\omega(e_k) = h_k` for all positive integers `k` (where `e_k` stands for the `k`-th elementary symmetric function, and `h_k` stands for the `k`-th complete homogeneous symmetric function). It furthermore is a Hopf algebra endomorphism and an involution, and it is also known as the *omega involution*. It sends the power-sum symmetric function `p_k` to `(-1)^{k-1} p_k` for every positive integer `k`. The images of some bases under the omega automorphism are given by .. MATH:: \omega(e_{\lambda}) = h_{\lambda}, \qquad \omega(h_{\lambda}) = e_{\lambda}, \qquad \omega(p_{\lambda}) = (-1)^{|\lambda| - \ell(\lambda)} p_{\lambda}, \qquad \omega(s_{\lambda}) = s_{\lambda^{\prime}}, where `\lambda` is any partition, where `\ell(\lambda)` denotes the length (:meth:`~sage.combinat.partition.Partition.length`) of the partition `\lambda`, where `\lambda^{\prime}` denotes the conjugate partition (:meth:`~sage.combinat.partition.Partition.conjugate`) of `\lambda`, and where the usual notations for bases are used (`e` = elementary, `h` = complete homogeneous, `p` = powersum, `s` = Schur). :meth:`omega_involution()` is a synonym for the :meth:`omega()` method. OUTPUT: - the image of ``self`` under the omega automorphism EXAMPLES:: sage: p = SymmetricFunctions(QQ).p() sage: a = p([2,1]); a p[2, 1] sage: a.omega() -p[2, 1] sage: p([]).omega() p[] sage: p(0).omega() 0 sage: p = SymmetricFunctions(ZZ).p() sage: (p([3,1,1]) - 2 * p([2,1])).omega() 2*p[2, 1] + p[3, 1, 1] """ f = lambda part, coeff: (part, (-1)**(sum(part)-len(part)) * coeff) return self.map_item(f) omega_involution = omega def scalar(self, x, zee=None): r""" Return the standard scalar product of ``self`` and ``x``. INPUT: - ``x`` -- a power sum symmetric function - ``zee`` -- (default: uses standard ``zee`` function) optional input specifying the scalar product on the power sum basis with normalization `\langle p_{\mu}, p_{\mu} \rangle = \mathrm{zee}(\mu)`. ``zee`` should be a function on partitions. Note that the power-sum symmetric functions are orthogonal under this scalar product. With the default value of ``zee``, the value of `\langle p_{\lambda}, p_{\lambda} \rangle` is given by the size of the centralizer in `S_n` of a permutation of cycle type `\lambda`. OUTPUT: - the standard scalar product between ``self`` and ``x``, or, if the optional parameter ``zee`` is specified, then the scalar product with respect to the normalization `\langle p_{\mu}, p_{\mu} \rangle = \mathrm{zee}(\mu)` with the power sum basis elements being orthogonal EXAMPLES:: sage: p = SymmetricFunctions(QQ).p() sage: p4 = Partitions(4) sage: matrix([ [p(a).scalar(p(b)) for a in p4] for b in p4]) [ 4 0 0 0 0] [ 0 3 0 0 0] [ 0 0 8 0 0] [ 0 0 0 4 0] [ 0 0 0 0 24] sage: p(0).scalar(p(1)) 0 sage: p(1).scalar(p(2)) 2 sage: zee = lambda x : 1 sage: matrix( [[p[la].scalar(p[mu], zee) for la in Partitions(3)] for mu in Partitions(3)]) [1 0 0] [0 1 0] [0 0 1] """ parent = self.parent() x = parent(x) if zee is None: f = lambda part1, part2: sfa.zee(part1) else: f = lambda part1, part2: zee(part1) return parent._apply_multi_module_morphism(self, x, f, orthogonal=True) def _derivative(self, part): """ Return the 'derivative' of ``p([part])`` with respect to ``p([1])`` (where ``p([part])`` is regarded as a polynomial in the indeterminates ``p([i])``). INPUT: - ``part`` -- a partition EXAMPLES:: sage: p = SymmetricFunctions(QQ).p() sage: a = p([2,1]) sage: a._derivative(Partition([2,1])) p[2] sage: a._derivative(Partition([1,1,1])) 3*p[1, 1] """ p = self.parent() if 1 not in part: return p.zero() else: return len([i for i in part if i == 1]) * p(part[:-1]) def _derivative_with_respect_to_p1(self): """ Return the 'derivative' of a symmetric function in the power sum basis with respect to ``p([1])`` (where ``p([part])`` is regarded as a polynomial in the indeterminates ``p([i])``). On the Frobenius image of an `S_n`-module, the resulting character is the Frobenius image of the restriction of this module to `S_{n-1}`. OUTPUT: - a symmetric function (in the power sum basis) of degree one smaller than ``self``, obtained by differentiating ``self`` by `p_1`. EXAMPLES:: sage: p = SymmetricFunctions(QQ).p() sage: a = p([2,1,1,1]) sage: a._derivative_with_respect_to_p1() 3*p[2, 1, 1] sage: a = p([3,2]) sage: a._derivative_with_respect_to_p1() 0 sage: p(0)._derivative_with_respect_to_p1() 0 sage: p(1)._derivative_with_respect_to_p1() 0 sage: p([1])._derivative_with_respect_to_p1() p[] sage: f = p[1] + p[2,1] sage: f._derivative_with_respect_to_p1() p[] + p[2] """ p = self.parent() if self == p.zero(): return self return p._apply_module_morphism(self, self._derivative) def frobenius(self, n): r""" Return the image of the symmetric function ``self`` under the `n`-th Frobenius operator. The `n`-th Frobenius operator `\mathbf{f}_n` is defined to be the map from the ring of symmetric functions to itself that sends every symmetric function `P(x_1, x_2, x_3, \ldots)` to `P(x_1^n, x_2^n, x_3^n, \ldots)`. This operator `\mathbf{f}_n` is a Hopf algebra endomorphism, and satisfies .. MATH:: \mathbf{f}_n m_{(\lambda_1, \lambda_2, \lambda_3, \ldots)} = m_{(n\lambda_1, n\lambda_2, n\lambda_3, \ldots)} for every partition `(\lambda_1, \lambda_2, \lambda_3, \ldots)` (where `m` means the monomial basis). Moreover, `\mathbf{f}_n (p_r) = p_{nr}` for every positive integer `r` (where `p_k` denotes the `k`-th powersum symmetric function). The `n`-th Frobenius operator is also called the `n`-th Frobenius endomorphism. It is not related to the Frobenius map which connects the ring of symmetric functions with the representation theory of the symmetric group. The `n`-th Frobenius operator is also the `n`-th Adams operator of the `\Lambda`-ring of symmetric functions over the integers. The `n`-th Frobenius operator can also be described via plethysm: Every symmetric function `P` satisfies `\mathbf{f}_n(P) = p_n \circ P = P \circ p_n`, where `p_n` is the `n`-th powersum symmetric function, and `\circ` denotes (outer) plethysm. INPUT: - ``n`` -- a positive integer OUTPUT: The result of applying the `n`-th Frobenius operator (on the ring of symmetric functions) to ``self``. EXAMPLES:: sage: Sym = SymmetricFunctions(ZZ) sage: p = Sym.p() sage: p[3].frobenius(2) p[6] sage: p[4,2,1].frobenius(3) p[12, 6, 3] sage: p([]).frobenius(4) p[] sage: p[3].frobenius(1) p[3] sage: (p([3]) - p([2]) + p([])).frobenius(3) p[] - p[6] + p[9] TESTS: Let us check that this method on the powersum basis gives the same result as the implementation in :mod:`sage.combinat.sf.sfa` on the complete homogeneous basis:: sage: Sym = SymmetricFunctions(QQ) sage: p = Sym.p(); h = Sym.h() sage: all( h(p(lam)).frobenius(3) == h(p(lam).frobenius(3)) ....: for lam in Partitions(3) ) True sage: all( p(h(lam)).frobenius(2) == p(h(lam).frobenius(2)) ....: for lam in Partitions(4) ) True .. SEEALSO:: :meth:`~sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.plethysm` """ dct = {lam.stretch(n): coeff for lam, coeff in self.monomial_coefficients().items()} return self.parent()._from_dict(dct) adams_operation = frobenius def verschiebung(self, n): r""" Return the image of the symmetric function ``self`` under the `n`-th Verschiebung operator. The `n`-th Verschiebung operator `\mathbf{V}_n` is defined to be the unique algebra endomorphism `V` of the ring of symmetric functions that satisfies `V(h_r) = h_{r/n}` for every positive integer `r` divisible by `n`, and satisfies `V(h_r) = 0` for every positive integer `r` not divisible by `n`. This operator `\mathbf{V}_n` is a Hopf algebra endomorphism. For every nonnegative integer `r` with `n \mid r`, it satisfies .. MATH:: \mathbf{V}_n(h_r) = h_{r/n}, \quad \mathbf{V}_n(p_r) = n p_{r/n}, \quad \mathbf{V}_n(e_r) = (-1)^{r - r/n} e_{r/n} (where `h` is the complete homogeneous basis, `p` is the powersum basis, and `e` is the elementary basis). For every nonnegative integer `r` with `n \nmid r`, it satisfes .. MATH:: \mathbf{V}_n(h_r) = \mathbf{V}_n(p_r) = \mathbf{V}_n(e_r) = 0. The `n`-th Verschiebung operator is also called the `n`-th Verschiebung endomorphism. Its name derives from the Verschiebung (German for "shift") endomorphism of the Witt vectors. The `n`-th Verschiebung operator is adjoint to the `n`-th Frobenius operator (see :meth:`frobenius` for its definition) with respect to the Hall scalar product (:meth:`scalar`). The action of the `n`-th Verschiebung operator on the Schur basis can also be computed explicitly. The following (probably clumsier than necessary) description can be obtained by solving exercise 7.61 in Stanley's [STA]_. Let `\lambda` be a partition. Let `n` be a positive integer. If the `n`-core of `\lambda` is nonempty, then `\mathbf{V}_n(s_\lambda) = 0`. Otherwise, the following method computes `\mathbf{V}_n(s_\lambda)`: Write the partition `\lambda` in the form `(\lambda_1, \lambda_2, \ldots, \lambda_{ns})` for some nonnegative integer `s`. (If `n` does not divide the length of `\lambda`, then this is achieved by adding trailing zeroes to `\lambda`.) Set `\beta_i = \lambda_i + ns - i` for every `s \in \{ 1, 2, \ldots, ns \}`. Then, `(\beta_1, \beta_2, \ldots, \beta_{ns})` is a strictly decreasing sequence of nonnegative integers. Stably sort the list `(1, 2, \ldots, ns)` in order of (weakly) increasing remainder of `-1 - \beta_i` modulo `n`. Let `\xi` be the sign of the permutation that is used for this sorting. Let `\psi` be the sign of the permutation that is used to stably sort the list `(1, 2, \ldots, ns)` in order of (weakly) increasing remainder of `i - 1` modulo `n`. (Notice that `\psi = (-1)^{n(n-1)s(s-1)/4}`.) Then, `\mathbf{V}_n(s_\lambda) = \xi \psi \prod_{i = 0}^{n - 1} s_{\lambda^{(i)}}`, where `(\lambda^{(0)}, \lambda^{(1)}, \ldots, \lambda^{(n - 1)})` is the `n`-quotient of `\lambda`. INPUT: - ``n`` -- a positive integer OUTPUT: The result of applying the `n`-th Verschiebung operator (on the ring of symmetric functions) to ``self``. EXAMPLES:: sage: Sym = SymmetricFunctions(ZZ) sage: p = Sym.p() sage: p[3].verschiebung(2) 0 sage: p[4].verschiebung(4) 4*p[1] The Verschiebung endomorphisms are multiplicative:: sage: all( all( p(lam).verschiebung(2) * p(mu).verschiebung(2) ....: == (p(lam) * p(mu)).verschiebung(2) ....: for mu in Partitions(4) ) ....: for lam in Partitions(4) ) True Testing the adjointness between the Frobenius operators `\mathbf{f}_n` and the Verschiebung operators `\mathbf{V}_n`:: sage: Sym = SymmetricFunctions(QQ) sage: p = Sym.p() sage: all( all( p(lam).verschiebung(2).scalar(p(mu)) ....: == p(lam).scalar(p(mu).frobenius(2)) ....: for mu in Partitions(2) ) ....: for lam in Partitions(4) ) True TESTS: Let us check that this method on the powersum basis gives the same result as the implementation in :mod:`sage.combinat.sf.sfa` on the monomial basis:: sage: Sym = SymmetricFunctions(QQ) sage: p = Sym.p(); m = Sym.m() sage: all( m(p(lam)).verschiebung(3) == m(p(lam).verschiebung(3)) ....: for lam in Partitions(6) ) True sage: all( p(m(lam)).verschiebung(2) == p(m(lam).verschiebung(2)) ....: for lam in Partitions(4) ) True """ parent = self.parent() p_coords_of_self = self.monomial_coefficients().items() dct = {Partition([i // n for i in lam]): coeff * (n ** len(lam)) for (lam, coeff) in p_coords_of_self if all( i % n == 0 for i in lam )} result_in_p_basis = parent._from_dict(dct) return parent(result_in_p_basis) def expand(self, n, alphabet='x'): """ Expand the symmetric function ``self`` as a symmetric polynomial in ``n`` variables. INPUT: - ``n`` -- a nonnegative integer - ``alphabet`` -- (default: ``'x'``) a variable for the expansion OUTPUT: A monomial expansion of ``self`` in the `n` variables labelled by ``alphabet``. EXAMPLES:: sage: p = SymmetricFunctions(QQ).p() sage: a = p([2]) sage: a.expand(2) x0^2 + x1^2 sage: a.expand(3, alphabet=['a','b','c']) a^2 + b^2 + c^2 sage: p([2,1,1]).expand(2) x0^4 + 2*x0^3*x1 + 2*x0^2*x1^2 + 2*x0*x1^3 + x1^4 sage: p([7]).expand(4) x0^7 + x1^7 + x2^7 + x3^7 sage: p([7]).expand(4,alphabet='t') t0^7 + t1^7 + t2^7 + t3^7 sage: p([7]).expand(4,alphabet='x,y,z,t') x^7 + y^7 + z^7 + t^7 sage: p(1).expand(4) 1 sage: p(0).expand(4) 0 sage: (p([]) + 2*p([1])).expand(3) 2*x0 + 2*x1 + 2*x2 + 1 sage: p([1]).expand(0) 0 sage: (3*p([])).expand(0) 3 """ if n == 0: # Symmetrica crashes otherwise... return self.counit() condition = lambda part: False return self._expand(condition, n, alphabet) def eval_at_permutation_roots(self, rho): r""" Evaluate at eigenvalues of a permutation matrix. Evaluate an element of the power sum basis at the eigenvalues of a permutation matrix with cycle structure `\rho`. This function evaluates an element at the roots of unity .. MATH:: \Xi_{\rho_1},\Xi_{\rho_2},\ldots,\Xi_{\rho_\ell} where .. MATH:: \Xi_{m} = 1,\zeta_m,\zeta_m^2,\ldots,\zeta_m^{m-1} and `\zeta_m` is an `m` root of unity. These roots of unity represent the eigenvalues of permutation matrix with cycle structure `\rho`. INPUT: - ``rho`` -- a partition or a list of non-negative integers OUTPUT: - an element of the base ring EXAMPLES:: sage: p = SymmetricFunctions(QQ).p() sage: p([3,3]).eval_at_permutation_roots([6]) 0 sage: p([3,3]).eval_at_permutation_roots([3]) 9 sage: p([3,3]).eval_at_permutation_roots([1]) 1 sage: p([3,3]).eval_at_permutation_roots([3,3]) 36 sage: p([3,3]).eval_at_permutation_roots([1,1,1,1,1]) 25 sage: (p[1]+p[2]+p[3]).eval_at_permutation_roots([3,2]) 5 """ p = self.parent() R = self.base_ring() on_basis = lambda lam: R.prod( p.eval_at_permutation_roots_on_generators(k, rho) for k in lam) return p._apply_module_morphism(self, on_basis, R) def principal_specialization(self, n=infinity, q=None): r""" Return the principal specialization of a symmetric function. The *principal specialization* of order `n` at `q` is the ring homomorphism `ps_{n,q}` from the ring of symmetric functions to another commutative ring `R` given by `x_i \mapsto q^{i-1}` for `i \in \{1,\dots,n\}` and `x_i \mapsto 0` for `i > n`. Here, `q` is a given element of `R`, and we assume that the variables of our symmetric functions are `x_1, x_2, x_3, \ldots`. (To be more precise, `ps_{n,q}` is a `K`-algebra homomorphism, where `K` is the base ring.) See Section 7.8 of [EnumComb2]_. The *stable principal specialization* at `q` is the ring homomorphism `ps_q` from the ring of symmetric functions to another commutative ring `R` given by `x_i \mapsto q^{i-1}` for all `i`. This is well-defined only if the resulting infinite sums converge; thus, in particular, setting `q = 1` in the stable principal specialization is an invalid operation. INPUT: - ``n`` (default: ``infinity``) -- a nonnegative integer or ``infinity``, specifying whether to compute the principal specialization of order ``n`` or the stable principal specialization. - ``q`` (default: ``None``) -- the value to use for `q`; the default is to create a ring of polynomials in ``q`` (or a field of rational functions in ``q``) over the given coefficient ring. We use the formulas from Proposition 7.8.3 of [EnumComb2]_: .. MATH:: ps_{n,q}(p_\lambda) = \prod_i (1-q^{n\lambda_i}) / (1-q^{\lambda_i}), ps_{n,1}(p_\lambda) = n^{\ell(\lambda)}, ps_q(p_\lambda) = 1 / \prod_i (1-q^{\lambda_i}), where `\ell(\lambda)` denotes the length of `\lambda`, and where the products range from `i=1` to `i=\ell(\lambda)`. EXAMPLES:: sage: p = SymmetricFunctions(QQ).p() sage: x = p[8,7,3,1] sage: x.principal_specialization(3, q=var("q")) (q^24 - 1)*(q^21 - 1)*(q^9 - 1)/((q^8 - 1)*(q^7 - 1)*(q - 1)) sage: x = 5*p[1,1,1] + 3*p[2,1] + 1 sage: x.principal_specialization(3, q=var("q")) 5*(q^3 - 1)^3/(q - 1)^3 + 3*(q^6 - 1)*(q^3 - 1)/((q^2 - 1)*(q - 1)) + 1 By default, we return a rational function in `q`:: sage: x.principal_specialization(3) 8*q^6 + 18*q^5 + 36*q^4 + 38*q^3 + 36*q^2 + 18*q + 9 If ``n`` is not given we return the stable principal specialization:: sage: x.principal_specialization(q=var("q")) 3/((q^2 - 1)*(q - 1)) - 5/(q - 1)^3 + 1 TESTS:: sage: p.zero().principal_specialization(3) 0 """ def get_variable(ring, name): try: ring(name) except TypeError: from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing return PolynomialRing(ring, name).gen() else: raise ValueError("the variable %s is in the base ring, pass it explicitly" % name) if q is None: q = get_variable(self.base_ring(), 'q') if q == 1: if n == infinity: raise ValueError("the stable principal specialization at q=1 is not defined") f = lambda partition: n**len(partition) elif n == infinity: f = lambda partition: prod(1/(1-q**part) for part in partition) else: from sage.rings.integer_ring import ZZ ZZq = PolynomialRing(ZZ, "q") q_lim = ZZq.gen() def f(partition): denom = prod((1 - q**part) for part in partition) try: ~denom rational = prod((1 - q**(n*part)) for part in partition) / denom return q.parent()(rational) except (ZeroDivisionError, NotImplementedError, TypeError): # If denom is not invertible, we need to do the # computation with universal coefficients instead: quotient = ZZq(prod((1-q_lim**(n*part))/(1-q_lim**part) for part in partition)) return quotient.subs({q_lim: q}) return self.parent()._apply_module_morphism(self, f, q.parent()) def exponential_specialization(self, t=None, q=1): r""" Return the exponential specialization of a symmetric function (when `q = 1`), or the `q`-exponential specialization (when `q \neq 1`). The *exponential specialization* `ex` at `t` is a `K`-algebra homomorphism from the `K`-algebra of symmetric functions to another `K`-algebra `R`. It is defined whenever the base ring `K` is a `\QQ`-algebra and `t` is an element of `R`. The easiest way to define it is by specifying its values on the powersum symmetric functions to be `p_1 = t` and `p_n = 0` for `n > 1`. Equivalently, on the homogeneous functions it is given by `ex(h_n) = t^n / n!`; see Proposition 7.8.4 of [EnumComb2]_. By analogy, the `q`-exponential specialization is a `K`-algebra homomorphism from the `K`-algebra of symmetric functions to another `K`-algebra `R` that depends on two elements `t` and `q` of `R` for which the elements `1 - q^i` for all positive integers `i` are invertible. It can be defined by specifying its values on the complete homogeneous symmetric functions to be .. MATH:: ex_q(h_n) = t^n / [n]_q!, where `[n]_q!` is the `q`-factorial. Equivalently, for `q \neq 1` and a homogeneous symmetric function `f` of degree `n`, we have .. MATH:: ex_q(f) = (1-q)^n t^n ps_q(f), where `ps_q(f)` is the stable principal specialization of `f` (see :meth:`principal_specialization`). (See (7.29) in [EnumComb2]_.) The limit of `ex_q` as `q \to 1` is `ex`. INPUT: - ``t`` (default: ``None``) -- the value to use for `t`; the default is to create a ring of polynomials in ``t``. - ``q`` (default: `1`) -- the value to use for `q`. If ``q`` is ``None``, then a ring (or fraction field) of polynomials in ``q`` is created. EXAMPLES:: sage: p = SymmetricFunctions(QQ).p() sage: x = p[8,7,3,1] sage: x.exponential_specialization() 0 sage: x = p[3] + 5*p[1,1] + 2*p[1] + 1 sage: x.exponential_specialization(t=var("t")) 5*t^2 + 2*t + 1 We also support the `q`-exponential_specialization:: sage: factor(p[3].exponential_specialization(q=var("q"), t=var("t"))) (q - 1)^2*t^3/(q^2 + q + 1) TESTS:: sage: p.zero().exponential_specialization() 0 """ def get_variable(ring, name): try: ring(name) except TypeError: from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing return PolynomialRing(ring, name).gen() else: raise ValueError("the variable %s is in the base ring, pass it explicitly" % name) if q == 1: if t is None: t = get_variable(self.base_ring(), 't') def f(partition): n = 0 for part in partition: if part != 1: return 0 n += 1 return t**n return self.parent()._apply_module_morphism(self, f, t.parent()) if q is None and t is None: q = get_variable(self.base_ring(), 'q') t = get_variable(q.parent(), 't') elif q is None: q = get_variable(t.parent(), 'q') elif t is None: t = get_variable(q.parent(), 't') def f(partition): n = 0 m = 1 for part in partition: n += part m *= 1-q**part return (1-q)**n * t**n / m return self.parent()._apply_module_morphism(self, f, t.parent()) # Backward compatibility for unpickling from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.sf.powersum', 'SymmetricFunctionAlgebraElement_power', SymmetricFunctionAlgebra_power.Element)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/sf/powersum.py
0.895157
0.698124
powersum.py
pypi
from sage.categories.morphism import SetMorphism from sage.categories.homset import Hom from sage.matrix.constructor import matrix import sage.combinat.partition import sage.data_structures.blas_dict as blas from . import classical class SymmetricFunctionAlgebra_dual(classical.SymmetricFunctionAlgebra_classical): def __init__(self, dual_basis, scalar, scalar_name="", basis_name=None, prefix=None): r""" Generic dual basis of a basis of symmetric functions. INPUT: - ``dual_basis`` -- a basis of the ring of symmetric functions - ``scalar`` -- A function `z` on partitions which determines the scalar product on the power sum basis by `\langle p_{\mu}, p_{\mu} \rangle = z(\mu)`. (Independently on the function chosen, the power sum basis will always be orthogonal; the function ``scalar`` only determines the norms of the basis elements.) This defaults to the function ``zee`` defined in ``sage.combinat.sf.sfa``, that is, the function is defined by: .. MATH:: \lambda \mapsto \prod_{i = 1}^\infty m_i(\lambda)! i^{m_i(\lambda)}`, where `m_i(\lambda)` means the number of times `i` appears in `\lambda`. This default function gives the standard Hall scalar product on the ring of symmetric functions. - ``scalar_name`` -- (default: the empty string) a string giving a description of the scalar product specified by the parameter ``scalar`` - ``basis_name`` -- (optional) a string to serve as name for the basis to be generated (such as "forgotten" in "the forgotten basis"); don't set it to any of the already existing basis names (such as ``homogeneous``, ``monomial``, ``forgotten``, etc.). - ``prefix`` -- (default: ``'d'`` and the prefix for ``dual_basis``) a string to use as the symbol for the basis OUTPUT: The basis of the ring of symmetric functions dual to the basis ``dual_basis`` with respect to the scalar product determined by ``scalar``. EXAMPLES:: sage: e = SymmetricFunctions(QQ).e() sage: f = e.dual_basis(prefix = "m", basis_name="Forgotten symmetric functions"); f Symmetric Functions over Rational Field in the Forgotten symmetric functions basis sage: TestSuite(f).run(elements = [f[1,1]+2*f[2], f[1]+3*f[1,1]]) sage: TestSuite(f).run() # long time (11s on sage.math, 2011) This class defines canonical coercions between ``self`` and ``self^*``, as follow: Lookup for the canonical isomorphism from ``self`` to `P` (=powersum), and build the adjoint isomorphism from `P^*` to ``self^*``. Since `P` is self-adjoint for this scalar product, derive an isomorphism from `P` to ``self^*``, and by composition with the above get an isomorphism from ``self`` to ``self^*`` (and similarly for the isomorphism ``self^*`` to ``self``). This should be striped down to just (auto?) defining canonical isomorphism by adjunction (as in MuPAD-Combinat), and let the coercion handle the rest. Inversions may not be possible if the base ring is not a field:: sage: m = SymmetricFunctions(ZZ).m() sage: h = m.dual_basis(lambda x: 1) sage: h[2,1] Traceback (most recent call last): ... TypeError: no conversion of this rational to integer By transitivity, this defines indirect coercions to and from all other bases:: sage: s = SymmetricFunctions(QQ['t'].fraction_field()).s() sage: t = QQ['t'].fraction_field().gen() sage: zee_hl = lambda x: x.centralizer_size(t=t) sage: S = s.dual_basis(zee_hl) sage: S(s([2,1])) (-t/(t^5-2*t^4+t^3-t^2+2*t-1))*d_s[1, 1, 1] + ((-t^2-1)/(t^5-2*t^4+t^3-t^2+2*t-1))*d_s[2, 1] + (-t/(t^5-2*t^4+t^3-t^2+2*t-1))*d_s[3] TESTS: Regression test for :trac:`12489`. This ticket improving equality test revealed that the conversion back from the dual basis did not strip cancelled terms from the dictionary:: sage: y = e[1, 1, 1, 1] - 2*e[2, 1, 1] + e[2, 2] sage: sorted(f.element_class(f, dual = y)) [([1, 1, 1, 1], 6), ([2, 1, 1], 2), ([2, 2], 1)] """ self._dual_basis = dual_basis self._scalar = scalar self._scalar_name = scalar_name # Set up the cache # cache for the coordinates of the elements # of ``dual_basis`` with respect to ``self`` self._to_self_cache = {} # cache for the coordinates of the elements # of ``self`` with respect to ``dual_basis`` self._from_self_cache = {} # cache for transition matrices which contain the coordinates of # the elements of ``dual_basis`` with respect to ``self`` self._transition_matrices = {} # cache for transition matrices which contain the coordinates of # the elements of ``self`` with respect to ``dual_basis`` self._inverse_transition_matrices = {} scalar_target = scalar(sage.combinat.partition.Partition([1])).parent() scalar_target = (scalar_target.one()*dual_basis.base_ring().one()).parent() self._sym = sage.combinat.sf.sf.SymmetricFunctions(scalar_target) self._p = self._sym.power() if prefix is None: prefix = 'd_'+dual_basis.prefix() classical.SymmetricFunctionAlgebra_classical.__init__(self, self._sym, basis_name=basis_name, prefix=prefix) # temporary until Hom(GradedHopfAlgebrasWithBasis work better) category = sage.categories.all.ModulesWithBasis(self.base_ring()) self.register_coercion(SetMorphism(Hom(self._dual_basis, self, category), self._dual_to_self)) self._dual_basis.register_coercion(SetMorphism(Hom(self, self._dual_basis, category), self._self_to_dual)) def _dual_to_self(self, x): """ Coerce an element of the dual of ``self`` canonically into ``self``. INPUT: - ``x`` -- an element in the dual basis of ``self`` OUTPUT: - returns ``x`` expressed in the basis ``self`` EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(scalar=zee) sage: h._dual_to_self(m([2,1]) + 3*m[1,1,1]) d_m[1, 1, 1] - d_m[2, 1] sage: hh = m.realization_of().h() sage: h._dual_to_self(m(hh([2,2,2]))) d_m[2, 2, 2] :: Note that the result is not correct if ``x`` is not an element of the dual basis of ``self`` sage: h._dual_to_self(m([2,1])) -2*d_m[1, 1, 1] + 5*d_m[2, 1] - 3*d_m[3] sage: h._dual_to_self(hh([2,1])) -2*d_m[1, 1, 1] + 5*d_m[2, 1] - 3*d_m[3] This is for internal use only. Please use instead:: sage: h(m([2,1]) + 3*m[1,1,1]) d_m[1, 1, 1] - d_m[2, 1] """ return self._element_class(self, dual=x) def _self_to_dual(self, x): """ Coerce an element of ``self`` canonically into the dual. INPUT: - ``x`` -- an element of ``self`` OUTPUT: - returns ``x`` expressed in the dual basis EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(scalar=zee) sage: h._self_to_dual(h([2,1]) + 3*h[1,1,1]) 21*m[1, 1, 1] + 11*m[2, 1] + 4*m[3] This is for internal use only. Please use instead: sage: m(h([2,1]) + 3*h[1,1,1]) 21*m[1, 1, 1] + 11*m[2, 1] + 4*m[3] or:: sage: (h([2,1]) + 3*h[1,1,1]).dual() 21*m[1, 1, 1] + 11*m[2, 1] + 4*m[3] """ return x.dual() def _dual_basis_default(self): """ Returns the default value for ``self.dual_basis()`` This returns the basis ``self`` has been built from by duality. .. WARNING:: This is not necessarily the dual basis for the standard (Hall) scalar product! EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(scalar=zee) sage: h.dual_basis() Symmetric Functions over Rational Field in the monomial basis sage: m2 = h.dual_basis(zee, prefix='m2') sage: m([2])^2 2*m[2, 2] + m[4] sage: m2([2])^2 2*m2[2, 2] + m2[4] TESTS:: sage: h.dual_basis() is h._dual_basis_default() True """ return self._dual_basis def _repr_(self): """ Representation of ``self``. OUTPUT: - a string description of ``self`` EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(scalar=zee); h #indirect doctests Dual basis to Symmetric Functions over Rational Field in the monomial basis sage: h = m.dual_basis(scalar=zee, scalar_name='Hall scalar product'); h #indirect doctest Dual basis to Symmetric Functions over Rational Field in the monomial basis with respect to the Hall scalar product """ if hasattr(self, "_basis"): return super()._repr_() if self._scalar_name: return "Dual basis to %s" % self._dual_basis + " with respect to the " + self._scalar_name else: return "Dual basis to %s" % self._dual_basis def _precompute(self, n): """ Compute the transition matrices between ``self`` and its dual basis for the homogeneous component of size `n`. The result is not returned, but stored in the cache. INPUT: - ``n`` -- nonnegative integer EXAMPLES:: sage: e = SymmetricFunctions(QQ['t']).elementary() sage: f = e.dual_basis() sage: f._precompute(0) sage: f._precompute(1) sage: f._precompute(2) sage: l = lambda c: [ (i[0],[j for j in sorted(i[1].items())]) for i in sorted(c.items())] sage: l(f._to_self_cache) # note: this may depend on possible previous computations! [([], [([], 1)]), ([1], [([1], 1)]), ([1, 1], [([1, 1], 2), ([2], 1)]), ([2], [([1, 1], 1), ([2], 1)])] sage: l(f._from_self_cache) [([], [([], 1)]), ([1], [([1], 1)]), ([1, 1], [([1, 1], 1), ([2], -1)]), ([2], [([1, 1], -1), ([2], 2)])] sage: f._transition_matrices[2] [1 1] [1 2] sage: f._inverse_transition_matrices[2] [ 2 -1] [-1 1] """ base_ring = self.base_ring() zero = base_ring.zero() # Handle the n == 0 and n == 1 cases separately if n == 0 or n == 1: part = sage.combinat.partition.Partition([1]*n) self._to_self_cache[ part ] = { part: base_ring.one() } self._from_self_cache[ part ] = { part: base_ring.one() } self._transition_matrices[n] = matrix(base_ring, [[1]]) self._inverse_transition_matrices[n] = matrix(base_ring, [[1]]) return partitions_n = sage.combinat.partition.Partitions_n(n).list() # We now get separated into two cases, depending on whether we can # use the power-sum basis to compute the matrix, or we have to use # the Schur basis. from sage.rings.rational_field import RationalField if (not base_ring.has_coerce_map_from(RationalField())) and self._scalar == sage.combinat.sf.sfa.zee: # This is the case when (due to the base ring not being a # \QQ-algebra) we cannot use the power-sum basis, # but (due to zee being the standard zee function) we can # use the Schur basis. schur = self._sym.schur() # Get all the basis elements of the n^th homogeneous component # of the dual basis and express them in the Schur basis d = {} for part in partitions_n: d[part] = schur(self._dual_basis(part))._monomial_coefficients # This contains the data for the transition matrix from the # dual basis to self. transition_matrix_n = matrix(base_ring, len(partitions_n), len(partitions_n)) # This first section calculates how the basis elements of the # dual basis are expressed in terms of self's basis. # For every partition p of size n, compute self(p) in # terms of the dual basis using the scalar product. i = 0 for s_part in partitions_n: # s_part corresponds to self(dual_basis(part)) # s_mcs corresponds to self(dual_basis(part))._monomial_coefficients s_mcs = {} # We need to compute the scalar product of d[s_part] and # all of the d[p_part]'s j = 0 for p_part in partitions_n: # Compute the scalar product of d[s_part] and d[p_part] sp = zero for ds_part in d[s_part]: if ds_part in d[p_part]: sp += d[s_part][ds_part]*d[p_part][ds_part] if sp != zero: s_mcs[p_part] = sp transition_matrix_n[i,j] = sp j += 1 self._to_self_cache[ s_part ] = s_mcs i += 1 else: # Now the other case. Note that just being in this case doesn't # guarantee that we can use the power-sum basis, but we can at # least try. # Get all the basis elements of the n^th homogeneous component # of the dual basis and express them in the power-sum basis d = {} for part in partitions_n: d[part] = self._p(self._dual_basis(part))._monomial_coefficients # This contains the data for the transition matrix from the # dual basis to self. transition_matrix_n = matrix(base_ring, len(partitions_n), len(partitions_n)) # This first section calculates how the basis elements of the # dual basis are expressed in terms of self's basis. # For every partition p of size n, compute self(p) in # terms of the dual basis using the scalar product. i = 0 for s_part in partitions_n: # s_part corresponds to self(dual_basis(part)) # s_mcs corresponds to self(dual_basis(part))._monomial_coefficients s_mcs = {} # We need to compute the scalar product of d[s_part] and # all of the d[p_part]'s j = 0 for p_part in partitions_n: # Compute the scalar product of d[s_part] and d[p_part] sp = zero for ds_part in d[s_part]: if ds_part in d[p_part]: sp += d[s_part][ds_part]*d[p_part][ds_part]*self._scalar(ds_part) if sp != zero: s_mcs[p_part] = sp transition_matrix_n[i,j] = sp j += 1 self._to_self_cache[ s_part ] = s_mcs i += 1 # Save the transition matrix self._transition_matrices[n] = transition_matrix_n # This second section calculates how the basis elements of # self expand in terms of the dual basis. We do this by # computing the inverse of the matrix obtained above. inverse_transition = ~transition_matrix_n for i in range(len(partitions_n)): d_mcs = {} for j in range(len(partitions_n)): if inverse_transition[i,j] != zero: d_mcs[ partitions_n[j] ] = inverse_transition[i,j] self._from_self_cache[ partitions_n[i] ] = d_mcs self._inverse_transition_matrices[n] = inverse_transition def transition_matrix(self, basis, n): r""" Returns the transition matrix between the `n^{th}` homogeneous components of ``self`` and ``basis``. INPUT: - ``basis`` -- a target basis of the ring of symmetric functions - ``n`` -- nonnegative integer OUTPUT: - A transition matrix from ``self`` to ``basis`` for the elements of degree ``n``. The indexing order of the rows and columns is the order of ``Partitions(n)``. EXAMPLES:: sage: Sym = SymmetricFunctions(QQ) sage: s = Sym.schur() sage: e = Sym.elementary() sage: f = e.dual_basis() sage: f.transition_matrix(s, 5) [ 1 -1 0 1 0 -1 1] [-2 1 1 -1 -1 1 0] [-2 2 -1 -1 1 0 0] [ 3 -1 -1 1 0 0 0] [ 3 -2 1 0 0 0 0] [-4 1 0 0 0 0 0] [ 1 0 0 0 0 0 0] sage: Partitions(5).list() [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]] sage: s(f[2,2,1]) s[3, 2] - 2*s[4, 1] + 3*s[5] sage: e.transition_matrix(s, 5).inverse().transpose() [ 1 -1 0 1 0 -1 1] [-2 1 1 -1 -1 1 0] [-2 2 -1 -1 1 0 0] [ 3 -1 -1 1 0 0 0] [ 3 -2 1 0 0 0 0] [-4 1 0 0 0 0 0] [ 1 0 0 0 0 0 0] """ if n not in self._transition_matrices: self._precompute(n) if basis is self._dual_basis: return self._inverse_transition_matrices[n] else: return self._inverse_transition_matrices[n]*self._dual_basis.transition_matrix(basis, n) def product(self, left, right): """ Return product of ``left`` and ``right``. Multiplication is done by performing the multiplication in the dual basis of ``self`` and then converting back to ``self``. INPUT: - ``left``, ``right`` -- elements of ``self`` OUTPUT: - the product of ``left`` and ``right`` in the basis ``self`` EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(scalar=zee) sage: a = h([2]) sage: b = a*a; b # indirect doctest d_m[2, 2] sage: b.dual() 6*m[1, 1, 1, 1] + 4*m[2, 1, 1] + 3*m[2, 2] + 2*m[3, 1] + m[4] """ # Do the multiplication in the dual basis # and then convert back to self. eclass = left.__class__ d_product = left.dual() * right.dual() return eclass(self, dual=d_product) class Element(classical.SymmetricFunctionAlgebra_classical.Element): """ An element in the dual basis. INPUT: At least one of the following must be specified. The one (if any) which is not provided will be computed. - ``dictionary`` -- an internal dictionary for the monomials and coefficients of ``self`` - ``dual`` -- self as an element of the dual basis. """ def __init__(self, A, dictionary=None, dual=None): """ Create an element of a dual basis. TESTS:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(scalar=zee, prefix='h') sage: a = h([2]) sage: ec = h._element_class sage: ec(h, dual=m([2])) -h[1, 1] + 2*h[2] sage: h(m([2])) -h[1, 1] + 2*h[2] sage: h([2]) h[2] sage: h([2])._dual m[1, 1] + m[2] sage: m(h([2])) m[1, 1] + m[2] """ if dictionary is None and dual is None: raise ValueError("you must specify either x or dual") parent = A base_ring = parent.base_ring() zero = base_ring.zero() if dual is None: # We need to compute the dual dual_dict = {} from_self_cache = parent._from_self_cache # Get the underlying dictionary for self s_mcs = dictionary # Make sure all the conversions from self to # to the dual basis have been precomputed for part in s_mcs: if part not in from_self_cache: parent._precompute(sum(part)) # Create the monomial coefficient dictionary from the # the monomial coefficient dictionary of dual for s_part in s_mcs: from_dictionary = from_self_cache[s_part] for part in from_dictionary: dual_dict[ part ] = dual_dict.get(part, zero) + base_ring(s_mcs[s_part]*from_dictionary[part]) dual = parent._dual_basis._from_dict(dual_dict) if dictionary is None: # We need to compute the monomial coefficients dictionary dictionary = {} to_self_cache = parent._to_self_cache # Get the underlying dictionary for the dual d_mcs = dual._monomial_coefficients # Make sure all the conversions from the dual basis # to self have been precomputed for part in d_mcs: if part not in to_self_cache: parent._precompute(sum(part)) # Create the monomial coefficient dictionary from the # the monomial coefficient dictionary of dual dictionary = blas.linear_combination( (to_self_cache[d_part], d_mcs[d_part]) for d_part in d_mcs) # Initialize self self._dual = dual classical.SymmetricFunctionAlgebra_classical.Element.__init__(self, A, dictionary) def dual(self): """ Return ``self`` in the dual basis. OUTPUT: - the element ``self`` expanded in the dual basis to ``self.parent()`` EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(scalar=zee) sage: a = h([2,1]) sage: a.parent() Dual basis to Symmetric Functions over Rational Field in the monomial basis sage: a.dual() 3*m[1, 1, 1] + 2*m[2, 1] + m[3] """ return self._dual def omega(self): r""" Return the image of ``self`` under the omega automorphism. The *omega automorphism* is defined to be the unique algebra endomorphism `\omega` of the ring of symmetric functions that satisfies `\omega(e_k) = h_k` for all positive integers `k` (where `e_k` stands for the `k`-th elementary symmetric function, and `h_k` stands for the `k`-th complete homogeneous symmetric function). It furthermore is a Hopf algebra endomorphism and an involution, and it is also known as the *omega involution*. It sends the power-sum symmetric function `p_k` to `(-1)^{k-1} p_k` for every positive integer `k`. The images of some bases under the omega automorphism are given by .. MATH:: \omega(e_{\lambda}) = h_{\lambda}, \qquad \omega(h_{\lambda}) = e_{\lambda}, \qquad \omega(p_{\lambda}) = (-1)^{|\lambda| - \ell(\lambda)} p_{\lambda}, \qquad \omega(s_{\lambda}) = s_{\lambda^{\prime}}, where `\lambda` is any partition, where `\ell(\lambda)` denotes the length (:meth:`~sage.combinat.partition.Partition.length`) of the partition `\lambda`, where `\lambda^{\prime}` denotes the conjugate partition (:meth:`~sage.combinat.partition.Partition.conjugate`) of `\lambda`, and where the usual notations for bases are used (`e` = elementary, `h` = complete homogeneous, `p` = powersum, `s` = Schur). :meth:`omega_involution` is a synonym for the :meth:`omega` method. OUTPUT: - the result of applying omega to ``self`` EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(zee) sage: hh = SymmetricFunctions(QQ).homogeneous() sage: hh([2,1]).omega() h[1, 1, 1] - h[2, 1] sage: h([2,1]).omega() d_m[1, 1, 1] - d_m[2, 1] """ eclass = self.__class__ return eclass(self.parent(), dual=self._dual.omega() ) omega_involution = omega def scalar(self, x): """ Return the standard scalar product of ``self`` and ``x``. INPUT: - ``x`` -- element of the symmetric functions OUTPUT: - the scalar product between ``x`` and ``self`` EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(scalar=zee) sage: a = h([2,1]) sage: a.scalar(a) 2 """ return self._dual.scalar(x) def scalar_hl(self, x): """ Return the Hall-Littlewood scalar product of ``self`` and ``x``. INPUT: - ``x`` -- element of the same dual basis as ``self`` OUTPUT: - the Hall-Littlewood scalar product between ``x`` and ``self`` EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(scalar=zee) sage: a = h([2,1]) sage: a.scalar_hl(a) (-t - 2)/(t^4 - 2*t^3 + 2*t - 1) """ return self._dual.scalar_hl(x) def _add_(self, y): """ Add two elements in the dual basis. INPUT: - ``y`` -- element of the same dual basis as ``self`` OUTPUT: - the sum of ``self`` and ``y`` EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(zee) sage: a = h([2,1])+h([3]); a # indirect doctest d_m[2, 1] + d_m[3] sage: h[2,1]._add_(h[3]) d_m[2, 1] + d_m[3] sage: a.dual() 4*m[1, 1, 1] + 3*m[2, 1] + 2*m[3] """ eclass = self.__class__ return eclass(self.parent(), dual=(self.dual()+y.dual())) def _neg_(self): """ Return the negative of ``self``. EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(zee) sage: -h([2,1]) # indirect doctest -d_m[2, 1] """ eclass = self.__class__ return eclass(self.parent(), dual=self.dual()._neg_()) def _sub_(self, y): """ Subtract two elements in the dual basis. INPUT: - ``y`` -- element of the same dual basis as ``self`` OUTPUT: - the difference of ``self`` and ``y`` EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(zee) sage: h([2,1])-h([3]) # indirect doctest d_m[2, 1] - d_m[3] sage: h[2,1]._sub_(h[3]) d_m[2, 1] - d_m[3] """ eclass = self.__class__ return eclass(self.parent(), dual=(self.dual()-y.dual())) def _div_(self, y): """ Divide an element ``self`` of the dual basis by ``y``. INPUT: - ``y`` -- element of base field OUTPUT: - the element ``self`` divided by ``y`` EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(zee) sage: a = h([2,1])+h([3]) sage: a/2 # indirect doctest 1/2*d_m[2, 1] + 1/2*d_m[3] """ return self*(~y) def __invert__(self): """ Invert ``self`` (only possible if ``self`` is a scalar multiple of `1` and we are working over a field). OUTPUT: - multiplicative inverse of ``self`` if possible EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(zee) sage: a = h(2); a 2*d_m[] sage: ~a 1/2*d_m[] sage: a = 3*h[1] sage: a.__invert__() Traceback (most recent call last): ... ValueError: cannot invert self (= 3*m[1]) """ eclass = self.__class__ return eclass(self.parent(), dual=~self.dual()) def expand(self, n, alphabet='x'): """ Expand the symmetric function ``self`` as a symmetric polynomial in ``n`` variables. INPUT: - ``n`` -- a nonnegative integer - ``alphabet`` -- (default: ``'x'``) a variable for the expansion OUTPUT: A monomial expansion of ``self`` in the `n` variables labelled by ``alphabet``. EXAMPLES:: sage: m = SymmetricFunctions(QQ).monomial() sage: zee = sage.combinat.sf.sfa.zee sage: h = m.dual_basis(zee) sage: a = h([2,1])+h([3]) sage: a.expand(2) 2*x0^3 + 3*x0^2*x1 + 3*x0*x1^2 + 2*x1^3 sage: a.dual().expand(2) 2*x0^3 + 3*x0^2*x1 + 3*x0*x1^2 + 2*x1^3 sage: a.expand(2,alphabet='y') 2*y0^3 + 3*y0^2*y1 + 3*y0*y1^2 + 2*y1^3 sage: a.expand(2,alphabet='x,y') 2*x^3 + 3*x^2*y + 3*x*y^2 + 2*y^3 sage: h([1]).expand(0) 0 sage: (3*h([])).expand(0) 3 """ return self._dual.expand(n, alphabet) # Backward compatibility for unpickling from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.sf.dual', 'SymmetricFunctionAlgebraElement_dual', SymmetricFunctionAlgebra_dual.Element)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/sf/dual.py
0.905446
0.720995
dual.py
pypi
from . import sfa from sage.categories.morphism import SetMorphism from sage.categories.homset import Hom class SymmetricFunctionAlgebra_orthotriang(sfa.SymmetricFunctionAlgebra_generic): class Element(sfa.SymmetricFunctionAlgebra_generic.Element): pass def __init__(self, Sym, base, scalar, prefix, basis_name, leading_coeff=None): r""" Initialization of the symmetric function algebra defined via orthotriangular rules. INPUT: - ``self`` -- a basis determined by an orthotriangular definition - ``Sym`` -- ring of symmetric functions - ``base`` -- an instance of a basis of the ring of symmetric functions (e.g. the Schur functions) - ``scalar`` -- a function ``zee`` on partitions. The function ``zee`` determines the scalar product on the power sum basis with normalization `\langle p_{\mu}, p_{\mu} \rangle = \mathrm{zee}(\mu)`. - ``prefix`` -- the prefix used to display the basis - ``basis_name`` -- the name used for the basis .. NOTE:: The base ring is required to be a `\QQ`-algebra for this method to be usable, since the scalar product is defined by its values on the power sum basis. EXAMPLES:: sage: from sage.combinat.sf.sfa import zee sage: from sage.combinat.sf.orthotriang import SymmetricFunctionAlgebra_orthotriang sage: Sym = SymmetricFunctions(QQ) sage: m = Sym.m() sage: s = SymmetricFunctionAlgebra_orthotriang(Sym, m, zee, 's', 'Schur'); s Symmetric Functions over Rational Field in the Schur basis TESTS:: sage: TestSuite(s).run(elements = [s[1,1]+2*s[2], s[1]+3*s[1,1]]) sage: TestSuite(s).run(skip = ["_test_associativity", "_test_prod"]) # long time (7s on sage.math, 2011) Note: ``s.an_element()`` is of degree 4; so we skip ``_test_associativity`` and ``_test_prod`` which involve (currently?) expensive calculations up to degree 12. """ self._sym = Sym self._sf_base = base self._scalar = scalar self._leading_coeff = leading_coeff sfa.SymmetricFunctionAlgebra_generic.__init__(self, Sym, prefix=prefix, basis_name=basis_name) self._self_to_base_cache = {} self._base_to_self_cache = {} self.register_coercion(SetMorphism(Hom(base, self), self._base_to_self)) base.register_coercion(SetMorphism(Hom(self, base), self._self_to_base)) def _base_to_self(self, x): """ Coerce a symmetric function in base ``x`` into ``self``. INPUT: - ``self`` -- a basis determined by an orthotriangular definition - ``x`` -- an element of the basis `base` to which ``self`` is triangularly related OUTPUT: - an element of ``self`` equivalent to ``x`` EXAMPLES:: sage: from sage.combinat.sf.sfa import zee sage: from sage.combinat.sf.orthotriang import SymmetricFunctionAlgebra_orthotriang sage: Sym = SymmetricFunctions(QQ) sage: m = Sym.m() sage: s = SymmetricFunctionAlgebra_orthotriang(Sym, m, zee, 's', 'Schur functions') sage: s._base_to_self(m([2,1])) -2*s[1, 1, 1] + s[2, 1] """ return self._from_cache(x, self._base_cache, self._base_to_self_cache) def _self_to_base(self, x): """ Coerce a symmetric function in ``self`` into base ``x``. INPUT: - ``self`` -- a basis determined by an orthotriangular definition - ``x`` -- an element of ``self`` as a basis of the ring of symmetric functions. OUTPUT: - the element ``x`` expressed in the basis to which ``self`` is triangularly related EXAMPLES:: sage: from sage.combinat.sf.sfa import zee sage: from sage.combinat.sf.orthotriang import SymmetricFunctionAlgebra_orthotriang sage: Sym = SymmetricFunctions(QQ) sage: m = Sym.m() sage: s = SymmetricFunctionAlgebra_orthotriang(Sym, m, zee, 's', 'Schur functions') sage: s._self_to_base(s([2,1])) 2*m[1, 1, 1] + m[2, 1] """ return self._sf_base._from_cache(x, self._base_cache, self._self_to_base_cache) def _base_cache(self, n): """ Computes the change of basis between ``self`` and base for the homogeneous component of size ``n`` INPUT: - ``self`` -- a basis determined by an orthotriangular definition - ``n`` -- a nonnegative integer EXAMPLES:: sage: from sage.combinat.sf.sfa import zee sage: from sage.combinat.sf.orthotriang import SymmetricFunctionAlgebra_orthotriang sage: Sym = SymmetricFunctions(QQ) sage: m = Sym.m() sage: s = SymmetricFunctionAlgebra_orthotriang(Sym, m, zee, 's', 'Schur functions') sage: s._base_cache(2) sage: l = lambda c: [ (i[0],[j for j in sorted(i[1].items())]) for i in sorted(c.items())] sage: l(s._base_to_self_cache[2]) [([1, 1], [([1, 1], 1)]), ([2], [([1, 1], -1), ([2], 1)])] sage: l(s._self_to_base_cache[2]) [([1, 1], [([1, 1], 1)]), ([2], [([1, 1], 1), ([2], 1)])] """ if n in self._self_to_base_cache: return else: self._self_to_base_cache[n] = {} self._gram_schmidt(n, self._sf_base, self._scalar, self._self_to_base_cache, leading_coeff=self._leading_coeff, upper_triangular=True) self._invert_morphism(n, self.base_ring(), self._self_to_base_cache, self._base_to_self_cache, to_other_function=self._to_base) def _to_base(self, part): r""" Return a function which takes in a partition `\mu` and returns the coefficient of a partition in the expansion of ``self`` `(part)` in base. INPUT: - ``self`` -- a basis determined by an orthotriangular definition - ``part`` -- a partition .. note:: We assume that self._gram_schmidt has been called before self._to_base is called. OUTPUT: - a function which accepts a partition ``mu`` and returns the coefficients in the expansion of ``self(part)`` in the triangularly related basis. EXAMPLES:: sage: from sage.combinat.sf.sfa import zee sage: from sage.combinat.sf.orthotriang import SymmetricFunctionAlgebra_orthotriang sage: Sym = SymmetricFunctions(QQ) sage: m = Sym.m() sage: s = SymmetricFunctionAlgebra_orthotriang(Sym, m, zee, 's', 'Schur functions') sage: m(s([2,1])) 2*m[1, 1, 1] + m[2, 1] sage: f = s._to_base(Partition([2,1])) sage: [f(p) for p in Partitions(3)] [0, 1, 2] """ f = lambda mu: self._self_to_base_cache[part].get(mu, 0) return f def product(self, left, right): """ Return ``left`` * ``right`` by converting both to the base and then converting back to ``self``. INPUT: - ``self`` -- a basis determined by an orthotriangular definition - ``left``, ``right`` -- elements in ``self`` OUTPUT: - the expansion of the product of ``left`` and ``right`` in the basis ``self``. EXAMPLES:: sage: from sage.combinat.sf.sfa import zee sage: from sage.combinat.sf.orthotriang import SymmetricFunctionAlgebra_orthotriang sage: Sym = SymmetricFunctions(QQ) sage: m = Sym.m() sage: s = SymmetricFunctionAlgebra_orthotriang(Sym, m, zee, 's', 'Schur functions') sage: s([1])*s([2,1]) #indirect doctest s[2, 1, 1] + s[2, 2] + s[3, 1] """ return self(self._sf_base(left) * self._sf_base(right)) # Backward compatibility for unpickling from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.sf.orthotriang', 'SymmetricFunctionAlgebraElement_orthotriang', SymmetricFunctionAlgebra_orthotriang.Element)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/sf/orthotriang.py
0.943295
0.583915
orthotriang.py
pypi
from . import sfa import sage.libs.lrcalc.lrcalc as lrcalc from sage.combinat.partition import Partitions from sage.misc.cachefunc import cached_method class SymmetricFunctionAlgebra_orthogonal(sfa.SymmetricFunctionAlgebra_generic): r""" The orthogonal symmetric function basis (or orthogonal basis, to be short). The orthogonal basis `\{ o_{\lambda} \}` where `\lambda` is taken over all partitions is defined by the following change of basis with the Schur functions: .. MATH:: s_{\lambda} = \sum_{\mu} \left( \sum_{\nu \in H} c^{\lambda}_{\mu\nu} \right) o_{\mu} where `H` is the set of all partitions with even-width rows and `c^{\lambda}_{\mu\nu}` is the usual Littlewood-Richardson (LR) coefficients. By the properties of LR coefficients, this can be shown to be a upper unitriangular change of basis. .. NOTE:: This is only a filtered basis, not a `\ZZ`-graded basis. However this does respect the induced `(\ZZ/2\ZZ)`-grading. INPUT: - ``Sym`` -- an instance of the ring of the symmetric functions REFERENCES: - [ChariKleber2000]_ - [KoikeTerada1987]_ - [ShimozonoZabrocki2006]_ EXAMPLES: Here are the first few orthogonal symmetric functions, in various bases:: sage: Sym = SymmetricFunctions(QQ) sage: o = Sym.o() sage: e = Sym.e() sage: h = Sym.h() sage: p = Sym.p() sage: s = Sym.s() sage: m = Sym.m() sage: p(o([1])) p[1] sage: m(o([1])) m[1] sage: e(o([1])) e[1] sage: h(o([1])) h[1] sage: s(o([1])) s[1] sage: p(o([2])) -p[] + 1/2*p[1, 1] + 1/2*p[2] sage: m(o([2])) -m[] + m[1, 1] + m[2] sage: e(o([2])) -e[] + e[1, 1] - e[2] sage: h(o([2])) -h[] + h[2] sage: s(o([2])) -s[] + s[2] sage: p(o([3])) -p[1] + 1/6*p[1, 1, 1] + 1/2*p[2, 1] + 1/3*p[3] sage: m(o([3])) -m[1] + m[1, 1, 1] + m[2, 1] + m[3] sage: e(o([3])) -e[1] + e[1, 1, 1] - 2*e[2, 1] + e[3] sage: h(o([3])) -h[1] + h[3] sage: s(o([3])) -s[1] + s[3] sage: Sym = SymmetricFunctions(ZZ) sage: o = Sym.o() sage: e = Sym.e() sage: h = Sym.h() sage: s = Sym.s() sage: m = Sym.m() sage: p = Sym.p() sage: m(o([4])) -m[1, 1] + m[1, 1, 1, 1] - m[2] + m[2, 1, 1] + m[2, 2] + m[3, 1] + m[4] sage: e(o([4])) -e[1, 1] + e[1, 1, 1, 1] + e[2] - 3*e[2, 1, 1] + e[2, 2] + 2*e[3, 1] - e[4] sage: h(o([4])) -h[2] + h[4] sage: s(o([4])) -s[2] + s[4] Some examples of conversions the other way:: sage: o(h[3]) o[1] + o[3] sage: o(e[3]) o[1, 1, 1] sage: o(m[2,1]) o[1] - 2*o[1, 1, 1] + o[2, 1] sage: o(p[3]) o[1, 1, 1] - o[2, 1] + o[3] Some multiplication:: sage: o([2]) * o([1,1]) o[1, 1] + o[2] + o[2, 1, 1] + o[3, 1] sage: o([2,1,1]) * o([2]) o[1, 1] + o[1, 1, 1, 1] + 2*o[2, 1, 1] + o[2, 2] + o[2, 2, 1, 1] + o[3, 1] + o[3, 1, 1, 1] + o[3, 2, 1] + o[4, 1, 1] sage: o([1,1]) * o([2,1]) o[1] + o[1, 1, 1] + 2*o[2, 1] + o[2, 1, 1, 1] + o[2, 2, 1] + o[3] + o[3, 1, 1] + o[3, 2] Examples of the Hopf algebra structure:: sage: o([1]).antipode() -o[1] sage: o([2]).antipode() -o[] + o[1, 1] sage: o([1]).coproduct() o[] # o[1] + o[1] # o[] sage: o([2]).coproduct() o[] # o[] + o[] # o[2] + o[1] # o[1] + o[2] # o[] sage: o([1]).counit() 0 sage: o.one().counit() 1 """ def __init__(self, Sym): """ Initialize ``self``. TESTS:: sage: o = SymmetricFunctions(QQ).o() sage: TestSuite(o).run() """ sfa.SymmetricFunctionAlgebra_generic.__init__(self, Sym, "orthogonal", 'o', graded=False) # We make a strong reference since we use it for our computations # and so we can define the coercion below (only codomains have # strong references) self._s = Sym.schur() # Setup the coercions M = self._s.module_morphism(self._s_to_o_on_basis, codomain=self, triangular='upper', unitriangular=True) M.register_as_coercion() Mi = self.module_morphism(self._o_to_s_on_basis, codomain=self._s, triangular='upper', unitriangular=True) Mi.register_as_coercion() @cached_method def _o_to_s_on_basis(self, lam): r""" Return the orthogonal symmetric function ``o[lam]`` expanded in the Schur basis, where ``lam`` is a partition. TESTS: Check that this is the inverse:: sage: o = SymmetricFunctions(QQ).o() sage: s = SymmetricFunctions(QQ).s() sage: all(o(s(o[la])) == o[la] for i in range(5) for la in Partitions(i)) True sage: all(s(o(s[la])) == s[la] for i in range(5) for la in Partitions(i)) True """ R = self.base_ring() n = sum(lam) return self._s._from_dict({ mu: R.sum( (-1)**j * lrcalc.lrcoef_unsafe(lam, mu, nu) for nu in Partitions(2*j) if all(nu.arm_length(i,i) == nu.leg_length(i,i)+1 for i in range(nu.frobenius_rank())) ) for j in range(n//2+1) # // 2 for horizontal dominoes for mu in Partitions(n-2*j) }) @cached_method def _s_to_o_on_basis(self, lam): r""" Return the Schur symmetric function ``s[lam]`` expanded in the orthogonal basis, where ``lam`` is a partition. INPUT: - ``lam`` -- a partition OUTPUT: - the expansion of ``s[lam]`` in the orthogonal basis ``self`` EXAMPLES:: sage: Sym = SymmetricFunctions(QQ) sage: s = Sym.schur() sage: o = Sym.orthogonal() sage: o._s_to_o_on_basis(Partition([])) o[] sage: o._s_to_o_on_basis(Partition([4,2,1])) o[1] + 2*o[2, 1] + o[2, 2, 1] + o[3] + o[3, 1, 1] + o[3, 2] + o[4, 1] + o[4, 2, 1] sage: s(o._s_to_o_on_basis(Partition([3,1]))) == s[3,1] True """ R = self.base_ring() n = sum(lam) return self._from_dict({ mu: R.sum( lrcalc.lrcoef_unsafe(lam, mu, [2*x for x in nu]) for nu in Partitions(j) ) for j in range(n//2+1) # // 2 for horizontal dominoes for mu in Partitions(n-2*j) })
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/sf/orthogonal.py
0.879755
0.699747
orthogonal.py
pypi
from . import sfa import sage.libs.lrcalc.lrcalc as lrcalc from sage.combinat.partition import Partitions from sage.misc.cachefunc import cached_method class SymmetricFunctionAlgebra_symplectic(sfa.SymmetricFunctionAlgebra_generic): r""" The symplectic symmetric function basis (or symplectic basis, to be short). The symplectic basis `\{ sp_{\lambda} \}` where `\lambda` is taken over all partitions is defined by the following change of basis with the Schur functions: .. MATH:: s_{\lambda} = \sum_{\mu} \left( \sum_{\nu \in V} c^{\lambda}_{\mu\nu} \right) sp_{\mu} where `V` is the set of all partitions with even-height columns and `c^{\lambda}_{\mu\nu}` is the usual Littlewood-Richardson (LR) coefficients. By the properties of LR coefficients, this can be shown to be a upper unitriangular change of basis. .. NOTE:: This is only a filtered basis, not a `\ZZ`-graded basis. However this does respect the induced `(\ZZ/2\ZZ)`-grading. INPUT: - ``Sym`` -- an instance of the ring of the symmetric functions REFERENCES: .. [ChariKleber2000] Vyjayanthi Chari and Michael Kleber. *Symmetric functions and representations of quantum affine algebras*. :arxiv:`math/0011161v1` .. [KoikeTerada1987] \K. Koike, I. Terada, *Young-diagrammatic methods for the representation theory of the classical groups of type Bn, Cn, Dn*. J. Algebra 107 (1987), no. 2, 466-511. .. [ShimozonoZabrocki2006] Mark Shimozono and Mike Zabrocki. *Deformed universal characters for classical and affine algebras*. Journal of Algebra, **299** (2006). :arxiv:`math/0404288`. EXAMPLES: Here are the first few symplectic symmetric functions, in various bases:: sage: Sym = SymmetricFunctions(QQ) sage: sp = Sym.sp() sage: e = Sym.e() sage: h = Sym.h() sage: p = Sym.p() sage: s = Sym.s() sage: m = Sym.m() sage: p(sp([1])) p[1] sage: m(sp([1])) m[1] sage: e(sp([1])) e[1] sage: h(sp([1])) h[1] sage: s(sp([1])) s[1] sage: p(sp([2])) 1/2*p[1, 1] + 1/2*p[2] sage: m(sp([2])) m[1, 1] + m[2] sage: e(sp([2])) e[1, 1] - e[2] sage: h(sp([2])) h[2] sage: s(sp([2])) s[2] sage: p(sp([3])) 1/6*p[1, 1, 1] + 1/2*p[2, 1] + 1/3*p[3] sage: m(sp([3])) m[1, 1, 1] + m[2, 1] + m[3] sage: e(sp([3])) e[1, 1, 1] - 2*e[2, 1] + e[3] sage: h(sp([3])) h[3] sage: s(sp([3])) s[3] sage: Sym = SymmetricFunctions(ZZ) sage: sp = Sym.sp() sage: e = Sym.e() sage: h = Sym.h() sage: s = Sym.s() sage: m = Sym.m() sage: p = Sym.p() sage: m(sp([4])) m[1, 1, 1, 1] + m[2, 1, 1] + m[2, 2] + m[3, 1] + m[4] sage: e(sp([4])) e[1, 1, 1, 1] - 3*e[2, 1, 1] + e[2, 2] + 2*e[3, 1] - e[4] sage: h(sp([4])) h[4] sage: s(sp([4])) s[4] Some examples of conversions the other way:: sage: sp(h[3]) sp[3] sage: sp(e[3]) sp[1] + sp[1, 1, 1] sage: sp(m[2,1]) -sp[1] - 2*sp[1, 1, 1] + sp[2, 1] sage: sp(p[3]) sp[1, 1, 1] - sp[2, 1] + sp[3] Some multiplication:: sage: sp([2]) * sp([1,1]) sp[1, 1] + sp[2] + sp[2, 1, 1] + sp[3, 1] sage: sp([2,1,1]) * sp([2]) sp[1, 1] + sp[1, 1, 1, 1] + 2*sp[2, 1, 1] + sp[2, 2] + sp[2, 2, 1, 1] + sp[3, 1] + sp[3, 1, 1, 1] + sp[3, 2, 1] + sp[4, 1, 1] sage: sp([1,1]) * sp([2,1]) sp[1] + sp[1, 1, 1] + 2*sp[2, 1] + sp[2, 1, 1, 1] + sp[2, 2, 1] + sp[3] + sp[3, 1, 1] + sp[3, 2] Examples of the Hopf algebra structure:: sage: sp([1]).antipode() -sp[1] sage: sp([2]).antipode() sp[] + sp[1, 1] sage: sp([1]).coproduct() sp[] # sp[1] + sp[1] # sp[] sage: sp([2]).coproduct() sp[] # sp[2] + sp[1] # sp[1] + sp[2] # sp[] sage: sp([1]).counit() 0 sage: sp.one().counit() 1 """ def __init__(self, Sym): """ Initialize ``self``. TESTS:: sage: sp = SymmetricFunctions(QQ).sp() sage: TestSuite(sp).run() """ sfa.SymmetricFunctionAlgebra_generic.__init__(self, Sym, "symplectic", 'sp', graded=False) # We make a strong reference since we use it for our computations # and so we can define the coercion below (only codomains have # strong references) self._s = Sym.schur() # Setup the coercions M = self._s.module_morphism(self._s_to_sp_on_basis, codomain=self, triangular='upper', unitriangular=True) M.register_as_coercion() Mi = self.module_morphism(self._sp_to_s_on_basis, codomain=self._s, triangular='upper', unitriangular=True) Mi.register_as_coercion() @cached_method def _sp_to_s_on_basis(self, lam): r""" Return the symplectic symmetric function ``sp[lam]`` expanded in the Schur basis, where ``lam`` is a partition. TESTS: Check that this is the inverse:: sage: sp = SymmetricFunctions(QQ).sp() sage: s = SymmetricFunctions(QQ).s() sage: all(sp(s(sp[la])) == sp[la] for i in range(5) for la in Partitions(i)) True sage: all(s(sp(s[la])) == s[la] for i in range(5) for la in Partitions(i)) True """ R = self.base_ring() n = sum(lam) return self._s._from_dict({ mu: R.sum( (-1)**j * lrcalc.lrcoef_unsafe(lam, mu, nu) for nu in Partitions(2*j) if all(nu.leg_length(i,i) == nu.arm_length(i,i)+1 for i in range(nu.frobenius_rank())) ) for j in range(n//2+1) # // 2 for horizontal dominoes for mu in Partitions(n-2*j) }) @cached_method def _s_to_sp_on_basis(self, lam): r""" Return the Schur symmetric function ``s[lam]`` expanded in the symplectic basis, where ``lam`` is a partition. INPUT: - ``lam`` -- a partition OUTPUT: - the expansion of ``s[lam]`` in the symplectic basis ``self`` EXAMPLES:: sage: Sym = SymmetricFunctions(QQ) sage: s = Sym.schur() sage: sp = Sym.symplectic() sage: sp._s_to_sp_on_basis(Partition([])) sp[] sage: sp._s_to_sp_on_basis(Partition([4,2,1])) sp[2, 1] + sp[3] + sp[3, 1, 1] + sp[3, 2] + sp[4, 1] + sp[4, 2, 1] sage: s(sp._s_to_sp_on_basis(Partition([3,1]))) == s[3,1] True """ R = self.base_ring() n = sum(lam) return self._from_dict({ mu: R.sum( lrcalc.lrcoef_unsafe(lam, mu, sum([[x,x] for x in nu], [])) for nu in Partitions(j) ) for j in range(n//2+1) # // 2 for vertical dominoes for mu in Partitions(n-2*j) })
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/sf/symplectic.py
0.890247
0.781038
symplectic.py
pypi
from .species import GenericCombinatorialSpecies from sage.arith.misc import factorial from .subset_species import SubsetSpeciesStructure from .set_species import SetSpecies from .structure import GenericSpeciesStructure from sage.combinat.species.misc import accept_size from functools import reduce class PartitionSpeciesStructure(GenericSpeciesStructure): def __init__(self, parent, labels, list): """ EXAMPLES:: sage: from sage.combinat.species.partition_species import PartitionSpeciesStructure sage: P = species.PartitionSpecies() sage: s = PartitionSpeciesStructure(P, ['a','b','c'], [[1,2],[3]]); s {{'a', 'b'}, {'c'}} sage: s == loads(dumps(s)) True """ list = [SubsetSpeciesStructure(parent, labels, block) if not isinstance(block, SubsetSpeciesStructure) else block for block in list] list.sort(key=lambda block:(-len(block), block)) GenericSpeciesStructure.__init__(self, parent, labels, list) def __repr__(self): """ EXAMPLES:: sage: S = species.PartitionSpecies() sage: a = S.structures(["a","b","c"])[0]; a {{'a', 'b', 'c'}} """ s = GenericSpeciesStructure.__repr__(self) return "{"+s[1:-1]+"}" def canonical_label(self): """ EXAMPLES:: sage: P = species.PartitionSpecies() sage: S = P.structures(["a", "b", "c"]) sage: [s.canonical_label() for s in S] [{{'a', 'b', 'c'}}, {{'a', 'b'}, {'c'}}, {{'a', 'b'}, {'c'}}, {{'a', 'b'}, {'c'}}, {{'a'}, {'b'}, {'c'}}] """ P = self.parent() p = [len(block) for block in self._list] return P._canonical_rep_from_partition(self.__class__, self._labels, p) def transport(self, perm): """ Returns the transport of this set partition along the permutation perm. For set partitions, this is the direct product of the automorphism groups for each of the blocks. EXAMPLES:: sage: p = PermutationGroupElement((2,3)) sage: from sage.combinat.species.partition_species import PartitionSpeciesStructure sage: a = PartitionSpeciesStructure(None, [2,3,4], [[1,2],[3]]); a {{2, 3}, {4}} sage: a.transport(p) {{2, 4}, {3}} """ l = [block.transport(perm)._list for block in self._list] l.sort(key=lambda block:(-len(block), block)) return PartitionSpeciesStructure(self.parent(), self._labels, l) def automorphism_group(self): """ Returns the group of permutations whose action on this set partition leave it fixed. EXAMPLES:: sage: p = PermutationGroupElement((2,3)) sage: from sage.combinat.species.partition_species import PartitionSpeciesStructure sage: a = PartitionSpeciesStructure(None, [2,3,4], [[1,2],[3]]); a {{2, 3}, {4}} sage: a.automorphism_group() Permutation Group with generators [(1,2)] """ from sage.groups.all import SymmetricGroup return reduce(lambda a,b: a.direct_product(b, maps=False), [SymmetricGroup(block._list) for block in self._list]) def change_labels(self, labels): """ Return a relabelled structure. INPUT: - ``labels``, a list of labels. OUTPUT: A structure with the i-th label of self replaced with the i-th label of the list. EXAMPLES:: sage: p = PermutationGroupElement((2,3)) sage: from sage.combinat.species.partition_species import PartitionSpeciesStructure sage: a = PartitionSpeciesStructure(None, [2,3,4], [[1,2],[3]]); a {{2, 3}, {4}} sage: a.change_labels([1,2,3]) {{1, 2}, {3}} """ return PartitionSpeciesStructure(self.parent(), labels, [block.change_labels(labels) for block in self._list]) class PartitionSpecies(GenericCombinatorialSpecies): @staticmethod @accept_size def __classcall__(cls, *args, **kwds): """ EXAMPLES:: sage: P = species.PartitionSpecies(); P Partition species """ return super(PartitionSpecies, cls).__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ Returns the species of partitions. EXAMPLES:: sage: P = species.PartitionSpecies() sage: P.generating_series()[0:5] [1, 1, 1, 5/6, 5/8] sage: P.isotype_generating_series()[0:5] [1, 1, 2, 3, 5] sage: P = species.PartitionSpecies() sage: P._check() True sage: P == loads(dumps(P)) True """ GenericCombinatorialSpecies.__init__(self, min=min, max=max, weight=weight) self._name = "Partition species" _default_structure_class = PartitionSpeciesStructure def _structures(self, structure_class, labels): """ EXAMPLES:: sage: P = species.PartitionSpecies() sage: P.structures([1,2,3]).list() [{{1, 2, 3}}, {{1, 3}, {2}}, {{1, 2}, {3}}, {{2, 3}, {1}}, {{1}, {2}, {3}}] """ from sage.combinat.restricted_growth import RestrictedGrowthArrays n = len(labels) if n == 0: yield structure_class(self, labels, []) return u = [i for i in reversed(range(1, n + 1))] s0 = u.pop() # Reconstruct the set partitions from # restricted growth arrays for a in RestrictedGrowthArrays(n): m = a.pop(0) r = [[] for _ in range(m)] i = n for i, z in enumerate(u): r[a[i]].append(z) r[0].append(s0) for sp in r: sp.reverse() r.sort(key=len, reverse=True) yield structure_class(self, labels, r) def _isotypes(self, structure_class, labels): """ EXAMPLES:: sage: P = species.PartitionSpecies() sage: P.isotypes([1,2,3,4]).list() [{{1, 2, 3, 4}}, {{1, 2, 3}, {4}}, {{1, 2}, {3, 4}}, {{1, 2}, {3}, {4}}, {{1}, {2}, {3}, {4}}] """ from sage.combinat.partition import Partitions for p in Partitions(len(labels)): yield self._canonical_rep_from_partition(structure_class, labels, p) def _canonical_rep_from_partition(self, structure_class, labels, p): """ Returns the canonical representative corresponding to the partition p. EXAMPLES:: sage: P = species.PartitionSpecies() sage: P._canonical_rep_from_partition(P._default_structure_class,[1,2,3],[2,1]) {{1, 2}, {3}} """ breaks = [sum(p[:i]) for i in range(len(p) + 1)] return structure_class(self, labels, [list(range(breaks[i]+1, breaks[i+1]+1)) for i in range(len(p))]) def _gs_callable(self, base_ring, n): r""" EXAMPLES:: sage: P = species.PartitionSpecies() sage: g = P.generating_series() sage: [g.coefficient(i) for i in range(5)] [1, 1, 1, 5/6, 5/8] """ from sage.combinat.combinat import bell_number return self._weight * base_ring(bell_number(n) / factorial(n)) def _itgs_callable(self, base_ring, n): r""" The isomorphism type generating series is given by `\frac{1}{1-x}`. EXAMPLES:: sage: P = species.PartitionSpecies() sage: g = P.isotype_generating_series() sage: [g.coefficient(i) for i in range(10)] [1, 1, 2, 3, 5, 7, 11, 15, 22, 30] """ from sage.combinat.partition import number_of_partitions return self._weight*base_ring(number_of_partitions(n)) def _cis(self, series_ring, base_ring): r""" The cycle index series for the species of partitions is given by .. MATH:: exp \sum_{n \ge 1} \frac{1}{n} \left( exp \left( \sum_{k \ge 1} \frac{x_{kn}}{k} \right) -1 \right). EXAMPLES:: sage: P = species.PartitionSpecies() sage: g = P.cycle_index_series() sage: g[0:5] [p[], p[1], p[1, 1] + p[2], 5/6*p[1, 1, 1] + 3/2*p[2, 1] + 2/3*p[3], 5/8*p[1, 1, 1, 1] + 7/4*p[2, 1, 1] + 7/8*p[2, 2] + p[3, 1] + 3/4*p[4]] """ ciset = SetSpecies().cycle_index_series(base_ring) res = ciset(ciset - 1) if self.is_weighted(): res *= self._weight return res #Backward compatibility PartitionSpecies_class = PartitionSpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/partition_species.py
0.794185
0.466663
partition_species.py
pypi
from .species import GenericCombinatorialSpecies from sage.arith.misc import factorial from .structure import GenericSpeciesStructure from .set_species import SetSpecies from sage.structure.unique_representation import UniqueRepresentation class CharacteristicSpeciesStructure(GenericSpeciesStructure): def __repr__(self): """ EXAMPLES:: sage: F = species.CharacteristicSpecies(3) sage: a = F.structures([1, 2, 3]).random_element(); a {1, 2, 3} sage: F = species.SingletonSpecies() sage: F.structures([1]).list() [1] sage: F = species.EmptySetSpecies() sage: F.structures([]).list() [{}] """ s = GenericSpeciesStructure.__repr__(self) if self.parent()._n == 1: return s[1:-1] else: return "{" + s[1:-1] + "}" def canonical_label(self): """ EXAMPLES:: sage: F = species.CharacteristicSpecies(3) sage: a = F.structures(["a", "b", "c"]).random_element(); a {'a', 'b', 'c'} sage: a.canonical_label() {'a', 'b', 'c'} """ P = self.parent() rng = list(range(1, P._n + 1)) return CharacteristicSpeciesStructure(P, self._labels, rng) def transport(self, perm): """ Returns the transport of this structure along the permutation perm. EXAMPLES:: sage: F = species.CharacteristicSpecies(3) sage: a = F.structures(["a", "b", "c"]).random_element(); a {'a', 'b', 'c'} sage: p = PermutationGroupElement((1,2)) sage: a.transport(p) {'a', 'b', 'c'} """ return self def automorphism_group(self): """ Returns the group of permutations whose action on this structure leave it fixed. For the characteristic species, there is only one structure, so every permutation is in its automorphism group. EXAMPLES:: sage: F = species.CharacteristicSpecies(3) sage: a = F.structures(["a", "b", "c"]).random_element(); a {'a', 'b', 'c'} sage: a.automorphism_group() Symmetric group of order 3! as a permutation group """ from sage.groups.all import SymmetricGroup return SymmetricGroup(len(self._labels)) class CharacteristicSpecies(GenericCombinatorialSpecies, UniqueRepresentation): def __init__(self, n, min=None, max=None, weight=None): """ Return the characteristic species of order `n`. This species has exactly one structure on a set of size `n` and no structures on sets of any other size. EXAMPLES:: sage: X = species.CharacteristicSpecies(1) sage: X.structures([1]).list() [1] sage: X.structures([1,2]).list() [] sage: X.generating_series()[0:4] [0, 1, 0, 0] sage: X.isotype_generating_series()[0:4] [0, 1, 0, 0] sage: X.cycle_index_series()[0:4] [0, p[1], 0, 0] sage: F = species.CharacteristicSpecies(3) sage: c = F.generating_series()[0:4] sage: F._check() True sage: F == loads(dumps(F)) True TESTS:: sage: S1 = species.CharacteristicSpecies(1) sage: S2 = species.CharacteristicSpecies(1) sage: S3 = species.CharacteristicSpecies(2) sage: S4 = species.CharacteristicSpecies(2, weight=2) sage: S1 is S2 True sage: S1 == S3 False """ self._n = n self._name = "Characteristic species of order %s"%n self._state_info = [n] GenericCombinatorialSpecies.__init__(self, min=min, max=max, weight=weight) _default_structure_class = CharacteristicSpeciesStructure def _structures(self, structure_class, labels): """ EXAMPLES:: sage: F = species.CharacteristicSpecies(2) sage: l = [1, 2, 3] sage: F.structures(l).list() [] sage: F = species.CharacteristicSpecies(3) sage: F.structures(l).list() [{1, 2, 3}] """ if len(labels) == self._n: yield structure_class(self, labels, range(1,self._n+1)) _isotypes = _structures def _gs_term(self, base_ring): """ EXAMPLES:: sage: F = species.CharacteristicSpecies(2) sage: F.generating_series()[0:5] [0, 0, 1/2, 0, 0] sage: F.generating_series().count(2) 1 """ return base_ring(self._weight) / base_ring(factorial(self._n)) def _order(self): """ Returns the order of the generating series. EXAMPLES:: sage: F = species.CharacteristicSpecies(2) sage: F._order() 2 """ return self._n def _itgs_term(self, base_ring): """ EXAMPLES:: sage: F = species.CharacteristicSpecies(2) sage: F.isotype_generating_series()[0:5] [0, 0, 1, 0, 0] Here we test out weighting each structure by q. :: sage: R.<q> = ZZ[] sage: Fq = species.CharacteristicSpecies(2, weight=q) sage: Fq.isotype_generating_series()[0:5] [0, 0, q, 0, 0] """ return base_ring(self._weight) def _cis_term(self, base_ring): """ EXAMPLES:: sage: F = species.CharacteristicSpecies(2) sage: g = F.cycle_index_series() sage: g[0:5] [0, 0, 1/2*p[1, 1] + 1/2*p[2], 0, 0] """ cis = SetSpecies(weight=self._weight).cycle_index_series(base_ring) return cis.coefficient(self._n) def _equation(self, var_mapping): """ Returns the right hand side of an algebraic equation satisfied by this species. This is a utility function called by the algebraic_equation_system method. EXAMPLES:: sage: C = species.CharacteristicSpecies(2) sage: Qz = QQ['z'] sage: R.<node0> = Qz[] sage: var_mapping = {'z':Qz.gen(), 'node0':R.gen()} sage: C._equation(var_mapping) z^2 """ return var_mapping['z']**(self._n) #Backward compatibility CharacteristicSpecies_class = CharacteristicSpecies class EmptySetSpecies(CharacteristicSpecies): def __init__(self, min=None, max=None, weight=None): """ Returns the empty set species. This species has exactly one structure on the empty set. It is the same (and is implemented) as ``CharacteristicSpecies(0)``. EXAMPLES:: sage: X = species.EmptySetSpecies() sage: X.structures([]).list() [{}] sage: X.structures([1,2]).list() [] sage: X.generating_series()[0:4] [1, 0, 0, 0] sage: X.isotype_generating_series()[0:4] [1, 0, 0, 0] sage: X.cycle_index_series()[0:4] [p[], 0, 0, 0] TESTS:: sage: E1 = species.EmptySetSpecies() sage: E2 = species.EmptySetSpecies() sage: E1 is E2 True sage: E = species.EmptySetSpecies() sage: E._check() True sage: E == loads(dumps(E)) True """ CharacteristicSpecies_class.__init__(self, 0, min=min, max=max, weight=weight) self._name = "Empty set species" self._state_info = [] #Backward compatibility EmptySetSpecies_class = EmptySetSpecies._cached_constructor = EmptySetSpecies class SingletonSpecies(CharacteristicSpecies): def __init__(self, min=None, max=None, weight=None): """ Returns the species of singletons. This species has exactly one structure on a set of size `1`. It is the same (and is implemented) as ``CharacteristicSpecies(1)``. EXAMPLES:: sage: X = species.SingletonSpecies() sage: X.structures([1]).list() [1] sage: X.structures([1,2]).list() [] sage: X.generating_series()[0:4] [0, 1, 0, 0] sage: X.isotype_generating_series()[0:4] [0, 1, 0, 0] sage: X.cycle_index_series()[0:4] [0, p[1], 0, 0] TESTS:: sage: S1 = species.SingletonSpecies() sage: S2 = species.SingletonSpecies() sage: S1 is S2 True sage: S = species.SingletonSpecies() sage: S._check() True sage: S == loads(dumps(S)) True """ CharacteristicSpecies_class.__init__(self, 1, min=min, max=max, weight=weight) self._name = "Singleton species" self._state_info = [] #Backward compatibility SingletonSpecies_class = SingletonSpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/characteristic_species.py
0.87362
0.401219
characteristic_species.py
pypi
from .set_species import SetSpecies from .partition_species import PartitionSpecies from .subset_species import SubsetSpecies from .recursive_species import CombinatorialSpecies from .characteristic_species import CharacteristicSpecies, SingletonSpecies, EmptySetSpecies from .cycle_species import CycleSpecies from .linear_order_species import LinearOrderSpecies from .permutation_species import PermutationSpecies from .empty_species import EmptySpecies from .sum_species import SumSpecies from .product_species import ProductSpecies from .composition_species import CompositionSpecies from .functorial_composition_species import FunctorialCompositionSpecies from sage.misc.cachefunc import cached_function @cached_function def SimpleGraphSpecies(): """ Return the species of simple graphs. EXAMPLES:: sage: S = species.SimpleGraphSpecies() sage: S.generating_series().counts(10) [1, 1, 2, 8, 64, 1024, 32768, 2097152, 268435456, 68719476736] sage: S.cycle_index_series()[:5] [p[], p[1], p[1, 1] + p[2], 4/3*p[1, 1, 1] + 2*p[2, 1] + 2/3*p[3], 8/3*p[1, 1, 1, 1] + 4*p[2, 1, 1] + 2*p[2, 2] + 4/3*p[3, 1] + p[4]] sage: S.isotype_generating_series()[:6] [1, 1, 2, 4, 11, 34] TESTS:: sage: seq = S.isotype_generating_series().counts(6)[1:] sage: oeis(seq)[0] # optional -- internet A000088: Number of graphs on n unlabeled nodes. :: sage: seq = S.generating_series().counts(10)[1:] sage: oeis(seq)[0] # optional -- internet A006125: a(n) = 2^(n*(n-1)/2). """ E = SetSpecies() E2 = SetSpecies(size=2) WP = SubsetSpecies() P2 = E2 * E return WP.functorial_composition(P2) @cached_function def BinaryTreeSpecies(): r""" Return the species of binary trees on `n` leaves. The species of binary trees `B` is defined by `B = X + B \cdot B`, where `X` is the singleton species. EXAMPLES:: sage: B = species.BinaryTreeSpecies() sage: B.generating_series().counts(10) [0, 1, 2, 12, 120, 1680, 30240, 665280, 17297280, 518918400] sage: B.isotype_generating_series().counts(10) [0, 1, 1, 2, 5, 14, 42, 132, 429, 1430] sage: B._check() True :: sage: B = species.BinaryTreeSpecies() sage: a = B.structures([1,2,3,4,5])[187]; a 2*((5*3)*(4*1)) sage: a.automorphism_group() Permutation Group with generators [()] TESTS:: sage: seq = B.isotype_generating_series().counts(10)[1:] sage: oeis(seq)[0] # optional -- internet A000108: Catalan numbers: ... """ B = CombinatorialSpecies(min=1) X = SingletonSpecies() B.define(X + B * B) return B @cached_function def BinaryForestSpecies(): """ Return the species of binary forests. Binary forests are defined as sets of binary trees. EXAMPLES:: sage: F = species.BinaryForestSpecies() sage: F.generating_series().counts(10) [1, 1, 3, 19, 193, 2721, 49171, 1084483, 28245729, 848456353] sage: F.isotype_generating_series().counts(10) [1, 1, 2, 4, 10, 26, 77, 235, 758, 2504] sage: F.cycle_index_series()[:7] [p[], p[1], 3/2*p[1, 1] + 1/2*p[2], 19/6*p[1, 1, 1] + 1/2*p[2, 1] + 1/3*p[3], 193/24*p[1, 1, 1, 1] + 3/4*p[2, 1, 1] + 5/8*p[2, 2] + 1/3*p[3, 1] + 1/4*p[4], 907/40*p[1, 1, 1, 1, 1] + 19/12*p[2, 1, 1, 1] + 5/8*p[2, 2, 1] + 1/2*p[3, 1, 1] + 1/6*p[3, 2] + 1/4*p[4, 1] + 1/5*p[5], 49171/720*p[1, 1, 1, 1, 1, 1] + 193/48*p[2, 1, 1, 1, 1] + 15/16*p[2, 2, 1, 1] + 61/48*p[2, 2, 2] + 19/18*p[3, 1, 1, 1] + 1/6*p[3, 2, 1] + 7/18*p[3, 3] + 3/8*p[4, 1, 1] + 1/8*p[4, 2] + 1/5*p[5, 1] + 1/6*p[6]] TESTS:: sage: seq = F.isotype_generating_series().counts(10)[1:] sage: oeis(seq)[0] # optional -- internet A052854: Number of forests of ordered trees on n total nodes. """ B = BinaryTreeSpecies() S = SetSpecies() F = S(B) return F del cached_function # so it doesn't get picked up by tab completion
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/library.py
0.767254
0.44746
library.py
pypi
from .species import GenericCombinatorialSpecies from .set_species import SetSpecies from .structure import GenericSpeciesStructure from sage.combinat.species.misc import accept_size from sage.structure.unique_representation import UniqueRepresentation from sage.arith.misc import factorial class SubsetSpeciesStructure(GenericSpeciesStructure): def __repr__(self): """ EXAMPLES:: sage: set_random_seed(0) sage: S = species.SubsetSpecies() sage: a = S.structures(["a","b","c"])[0]; a {} """ s = GenericSpeciesStructure.__repr__(self) return "{"+s[1:-1]+"}" def canonical_label(self): """ Return the canonical label of ``self``. EXAMPLES:: sage: P = species.SubsetSpecies() sage: S = P.structures(["a", "b", "c"]) sage: [s.canonical_label() for s in S] [{}, {'a'}, {'a'}, {'a'}, {'a', 'b'}, {'a', 'b'}, {'a', 'b'}, {'a', 'b', 'c'}] """ rng = list(range(1, len(self._list) + 1)) return self.__class__(self.parent(), self._labels, rng) def label_subset(self): r""" Return a subset of the labels that "appear" in this structure. EXAMPLES:: sage: P = species.SubsetSpecies() sage: S = P.structures(["a", "b", "c"]) sage: [s.label_subset() for s in S] [[], ['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']] """ return [self._relabel(i) for i in self._list] def transport(self, perm): r""" Return the transport of this subset along the permutation perm. EXAMPLES:: sage: F = species.SubsetSpecies() sage: a = F.structures(["a", "b", "c"])[5]; a {'a', 'c'} sage: p = PermutationGroupElement((1,2)) sage: a.transport(p) {'b', 'c'} sage: p = PermutationGroupElement((1,3)) sage: a.transport(p) {'a', 'c'} """ l = sorted([perm(i) for i in self._list]) return SubsetSpeciesStructure(self.parent(), self._labels, l) def automorphism_group(self): r""" Return the group of permutations whose action on this subset leave it fixed. EXAMPLES:: sage: F = species.SubsetSpecies() sage: a = F.structures([1,2,3,4])[6]; a {1, 3} sage: a.automorphism_group() Permutation Group with generators [(2,4), (1,3)] :: sage: [a.transport(g) for g in a.automorphism_group()] [{1, 3}, {1, 3}, {1, 3}, {1, 3}] """ from sage.groups.all import SymmetricGroup, PermutationGroup a = SymmetricGroup(self._list) b = SymmetricGroup(self.complement()._list) return PermutationGroup(a.gens() + b.gens()) def complement(self): r""" Return the complement of ``self``. EXAMPLES:: sage: F = species.SubsetSpecies() sage: a = F.structures(["a", "b", "c"])[5]; a {'a', 'c'} sage: a.complement() {'b'} """ new_list = [i for i in range(1, len(self._labels)+1) if i not in self._list] return SubsetSpeciesStructure(self.parent(), self._labels, new_list) class SubsetSpecies(GenericCombinatorialSpecies, UniqueRepresentation): @staticmethod @accept_size def __classcall__(cls, *args, **kwds): """ EXAMPLES:: sage: S = species.SubsetSpecies(); S Subset species """ return super(SubsetSpecies, cls).__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ Return the species of subsets. EXAMPLES:: sage: S = species.SubsetSpecies() sage: S.generating_series()[0:5] [1, 2, 2, 4/3, 2/3] sage: S.isotype_generating_series()[0:5] [1, 2, 3, 4, 5] sage: S = species.SubsetSpecies() sage: c = S.generating_series()[0:3] sage: S._check() True sage: S == loads(dumps(S)) True """ GenericCombinatorialSpecies.__init__(self, min=None, max=None, weight=None) self._name = "Subset species" _default_structure_class = SubsetSpeciesStructure def _structures(self, structure_class, labels): """ EXAMPLES:: sage: S = species.SubsetSpecies() sage: S.structures([1,2]).list() [{}, {1}, {2}, {1, 2}] sage: S.structures(['a','b']).list() [{}, {'a'}, {'b'}, {'a', 'b'}] """ from sage.combinat.combination import Combinations for c in Combinations(range(1, len(labels)+1)): yield structure_class(self, labels, c) def _isotypes(self, structure_class, labels): """ EXAMPLES:: sage: S = species.SubsetSpecies() sage: S.isotypes([1,2]).list() [{}, {1}, {1, 2}] sage: S.isotypes(['a','b']).list() [{}, {'a'}, {'a', 'b'}] """ for i in range(len(labels)+1): yield structure_class(self, labels, range(1, i+1)) def _gs_callable(self, base_ring, n): """ The generating series for the species of subsets is `e^{2x}`. EXAMPLES:: sage: S = species.SubsetSpecies() sage: [S.generating_series().coefficient(i) for i in range(5)] [1, 2, 2, 4/3, 2/3] """ return base_ring(2)**n / base_ring(factorial(n)) def _itgs_callable(self, base_ring, n): r""" The generating series for the species of subsets is `e^{2x}`. EXAMPLES:: sage: S = species.SubsetSpecies() sage: S.isotype_generating_series()[0:5] [1, 2, 3, 4, 5] """ return base_ring(n + 1) def _cis(self, series_ring, base_ring): r""" The cycle index series for the species of subsets satisfies .. MATH:: Z_{\mathfrak{p}} = Z_{\mathcal{E}} \cdot Z_{\mathcal{E}}. EXAMPLES:: sage: S = species.SubsetSpecies() sage: S.cycle_index_series()[0:5] [p[], 2*p[1], 2*p[1, 1] + p[2], 4/3*p[1, 1, 1] + 2*p[2, 1] + 2/3*p[3], 2/3*p[1, 1, 1, 1] + 2*p[2, 1, 1] + 1/2*p[2, 2] + 4/3*p[3, 1] + 1/2*p[4]] """ ciset = SetSpecies().cycle_index_series(base_ring) res = ciset**2 if self.is_weighted(): res *= self._weight return res #Backward compatibility SubsetSpecies_class = SubsetSpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/subset_species.py
0.844024
0.42185
subset_species.py
pypi
from .species import GenericCombinatorialSpecies from sage.combinat.species.structure import GenericSpeciesStructure from sage.combinat.species.misc import accept_size from sage.structure.unique_representation import UniqueRepresentation from sage.arith.misc import factorial class SetSpeciesStructure(GenericSpeciesStructure): def __repr__(self): """ EXAMPLES:: sage: S = species.SetSpecies() sage: a = S.structures(["a","b","c"]).random_element(); a {'a', 'b', 'c'} """ s = GenericSpeciesStructure.__repr__(self) return "{"+s[1:-1]+"}" def canonical_label(self): """ EXAMPLES:: sage: S = species.SetSpecies() sage: a = S.structures(["a","b","c"]).random_element(); a {'a', 'b', 'c'} sage: a.canonical_label() {'a', 'b', 'c'} """ rng = list(range(1, len(self._labels) + 1)) return SetSpeciesStructure(self.parent(), self._labels, rng) def transport(self, perm): """ Returns the transport of this set along the permutation perm. EXAMPLES:: sage: F = species.SetSpecies() sage: a = F.structures(["a", "b", "c"]).random_element(); a {'a', 'b', 'c'} sage: p = PermutationGroupElement((1,2)) sage: a.transport(p) {'a', 'b', 'c'} """ return self def automorphism_group(self): """ Returns the group of permutations whose action on this set leave it fixed. For the species of sets, there is only one isomorphism class, so every permutation is in its automorphism group. EXAMPLES:: sage: F = species.SetSpecies() sage: a = F.structures(["a", "b", "c"]).random_element(); a {'a', 'b', 'c'} sage: a.automorphism_group() Symmetric group of order 3! as a permutation group """ from sage.groups.all import SymmetricGroup return SymmetricGroup(max(1,len(self._labels))) class SetSpecies(GenericCombinatorialSpecies, UniqueRepresentation): @staticmethod @accept_size def __classcall__(cls, *args, **kwds): """ EXAMPLES:: sage: E = species.SetSpecies(); E Set species """ return super(SetSpecies, cls).__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ Returns the species of sets. EXAMPLES:: sage: E = species.SetSpecies() sage: E.structures([1,2,3]).list() [{1, 2, 3}] sage: E.isotype_generating_series()[0:4] [1, 1, 1, 1] sage: S = species.SetSpecies() sage: c = S.generating_series()[0:3] sage: S._check() True sage: S == loads(dumps(S)) True """ GenericCombinatorialSpecies.__init__(self, min=min, max=max, weight=weight) self._name = "Set species" _default_structure_class = SetSpeciesStructure def _structures(self, structure_class, labels): """ EXAMPLES:: sage: S = species.SetSpecies() sage: S.structures([1,2,3]).list() [{1, 2, 3}] """ n = len(labels) yield structure_class(self, labels, range(1,n+1)) _isotypes = _structures def _gs_callable(self, base_ring, n): r""" The generating series for the species of sets is given by `e^x`. EXAMPLES:: sage: S = species.SetSpecies() sage: g = S.generating_series() sage: [g.coefficient(i) for i in range(10)] [1, 1, 1/2, 1/6, 1/24, 1/120, 1/720, 1/5040, 1/40320, 1/362880] sage: [g.count(i) for i in range(10)] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] """ return base_ring(self._weight / factorial(n)) def _itgs_list(self, base_ring, n): r""" The isomorphism type generating series for the species of sets is `\frac{1}{1-x}`. EXAMPLES:: sage: S = species.SetSpecies() sage: g = S.isotype_generating_series() sage: g[0:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] sage: [g.count(i) for i in range(10)] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] """ return base_ring(self._weight) def _cis(self, series_ring, base_ring): r""" The cycle index series for the species of sets is given by `exp\( \sum_{n=1}{\infty} = \frac{x_n}{n} \)`. EXAMPLES:: sage: S = species.SetSpecies() sage: g = S.cycle_index_series() sage: g[0:5] [p[], p[1], 1/2*p[1, 1] + 1/2*p[2], 1/6*p[1, 1, 1] + 1/2*p[2, 1] + 1/3*p[3], 1/24*p[1, 1, 1, 1] + 1/4*p[2, 1, 1] + 1/8*p[2, 2] + 1/3*p[3, 1] + 1/4*p[4]] """ from .generating_series import ExponentialCycleIndexSeries res = ExponentialCycleIndexSeries(base_ring) if self.is_weighted(): res *= self._weight return res #Backward compatibility SetSpecies_class = SetSpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/set_species.py
0.870941
0.424412
set_species.py
pypi
from .species import GenericCombinatorialSpecies from .structure import SpeciesStructureWrapper from sage.structure.unique_representation import UniqueRepresentation class SumSpeciesStructure(SpeciesStructureWrapper): pass class SumSpecies(GenericCombinatorialSpecies, UniqueRepresentation): def __init__(self, F, G, min=None, max=None, weight=None): """ Returns the sum of two species. EXAMPLES:: sage: S = species.PermutationSpecies() sage: A = S+S sage: A.generating_series()[:5] [2, 2, 2, 2, 2] sage: P = species.PermutationSpecies() sage: F = P + P sage: F._check() True sage: F == loads(dumps(F)) True TESTS:: sage: A = species.SingletonSpecies() + species.SingletonSpecies() sage: B = species.SingletonSpecies() + species.SingletonSpecies() sage: C = species.SingletonSpecies() + species.SingletonSpecies(min=2) sage: A is B True sage: (A is C) or (A == C) False """ self._F = F self._G = G self._state_info = [F, G] GenericCombinatorialSpecies.__init__(self, min=None, max=None, weight=None) _default_structure_class = SumSpeciesStructure def left_summand(self): """ Returns the left summand of this species. EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P + P*P sage: F.left_summand() Permutation species """ return self._F def right_summand(self): """ Returns the right summand of this species. EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P + P*P sage: F.right_summand() Product of (Permutation species) and (Permutation species) """ return self._G def _name(self): """ Note that we use a function to return the name of this species because we can't do it in the __init__ method due to it requiring that self.left_summand() and self.right_summand() already be unpickled. EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P + P sage: F._name() 'Sum of (Permutation species) and (Permutation species)' """ return "Sum of (%s) and (%s)" % (self.left_summand(), self.right_summand()) def _structures(self, structure_class, labels): """ EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P + P sage: F.structures([1,2]).list() [[1, 2], [2, 1], [1, 2], [2, 1]] """ for res in self.left_summand().structures(labels): yield structure_class(self, res, tag="left") for res in self.right_summand().structures(labels): yield structure_class(self, res, tag="right") def _isotypes(self, structure_class, labels): """ EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P + P sage: F.isotypes([1,2]).list() [[2, 1], [1, 2], [2, 1], [1, 2]] """ for res in self._F.isotypes(labels): yield structure_class(self, res, tag="left") for res in self._G.isotypes(labels): yield structure_class(self, res, tag="right") def _gs(self, series_ring, base_ring): """ Returns the cycle index series of this species. EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P + P sage: F.generating_series()[:5] [2, 2, 2, 2, 2] """ return (self.left_summand().generating_series(base_ring) + self.right_summand().generating_series(base_ring)) def _itgs(self, series_ring, base_ring): """ Returns the isomorphism type generating series of this species. EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P + P sage: F.isotype_generating_series()[:5] [2, 2, 4, 6, 10] """ return (self.left_summand().isotype_generating_series(base_ring) + self.right_summand().isotype_generating_series(base_ring)) def _cis(self, series_ring, base_ring): """ Returns the generating series of this species. EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P + P sage: F.cycle_index_series()[:5] [2*p[], 2*p[1], 2*p[1, 1] + 2*p[2], 2*p[1, 1, 1] + 2*p[2, 1] + 2*p[3], 2*p[1, 1, 1, 1] + 2*p[2, 1, 1] + 2*p[2, 2] + 2*p[3, 1] + 2*p[4]] """ return (self.left_summand().cycle_index_series(base_ring) + self.right_summand().cycle_index_series(base_ring)) def weight_ring(self): """ Returns the weight ring for this species. This is determined by asking Sage's coercion model what the result is when you add elements of the weight rings for each of the operands. EXAMPLES:: sage: S = species.SetSpecies() sage: C = S+S sage: C.weight_ring() Rational Field :: sage: S = species.SetSpecies(weight=QQ['t'].gen()) sage: C = S + S sage: C.weight_ring() Univariate Polynomial Ring in t over Rational Field """ return self._common_parent([self.left_summand().weight_ring(), self.right_summand().weight_ring()]) def _equation(self, var_mapping): """ Returns the right hand side of an algebraic equation satisfied by this species. This is a utility function called by the algebraic_equation_system method. EXAMPLES:: sage: X = species.SingletonSpecies() sage: S = X + X sage: S.algebraic_equation_system() [node1 + (-2*z)] """ return sum(var_mapping[operand] for operand in self._state_info) #Backward compatibility SumSpecies_class = SumSpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/sum_species.py
0.889867
0.497559
sum_species.py
pypi
from .species import GenericCombinatorialSpecies from .structure import GenericSpeciesStructure from sage.structure.unique_representation import UniqueRepresentation from sage.arith.all import divisors, euler_phi from sage.combinat.species.misc import accept_size class CycleSpeciesStructure(GenericSpeciesStructure): def __repr__(self): """ EXAMPLES:: sage: S = species.CycleSpecies() sage: S.structures(["a","b","c"])[0] ('a', 'b', 'c') """ s = GenericSpeciesStructure.__repr__(self) return "("+s[1:-1]+")" def canonical_label(self): """ EXAMPLES:: sage: P = species.CycleSpecies() sage: P.structures(["a","b","c"]).random_element().canonical_label() ('a', 'b', 'c') """ n = len(self._labels) return CycleSpeciesStructure(self.parent(), self._labels, range(1, n+1)) def permutation_group_element(self): """ Returns this cycle as a permutation group element. EXAMPLES:: sage: F = species.CycleSpecies() sage: a = F.structures(["a", "b", "c"])[0]; a ('a', 'b', 'c') sage: a.permutation_group_element() (1,2,3) """ from sage.groups.all import PermutationGroupElement return PermutationGroupElement(tuple(self._list)) def transport(self, perm): """ Returns the transport of this structure along the permutation perm. EXAMPLES:: sage: F = species.CycleSpecies() sage: a = F.structures(["a", "b", "c"])[0]; a ('a', 'b', 'c') sage: p = PermutationGroupElement((1,2)) sage: a.transport(p) ('a', 'c', 'b') """ p = self.permutation_group_element() p = perm*p*~perm new_list = [1] for i in range(len(self._list)-1): new_list.append( p(new_list[-1]) ) return CycleSpeciesStructure(self.parent(), self._labels, new_list) def automorphism_group(self): """ Returns the group of permutations whose action on this structure leave it fixed. EXAMPLES:: sage: P = species.CycleSpecies() sage: a = P.structures([1, 2, 3, 4])[0]; a (1, 2, 3, 4) sage: a.automorphism_group() Permutation Group with generators [(1,2,3,4)] :: sage: [a.transport(perm) for perm in a.automorphism_group()] [(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4)] """ from sage.groups.all import SymmetricGroup, PermutationGroup S = SymmetricGroup(len(self._labels)) p = self.permutation_group_element() return PermutationGroup(S.centralizer(p).gens()) class CycleSpecies(GenericCombinatorialSpecies, UniqueRepresentation): @staticmethod @accept_size def __classcall__(cls, *args, **kwds): r""" EXAMPLES:: sage: C = species.CycleSpecies(); C Cyclic permutation species """ return super(CycleSpecies, cls).__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ Returns the species of cycles. EXAMPLES:: sage: C = species.CycleSpecies(); C Cyclic permutation species sage: C.structures([1,2,3,4]).list() [(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2)] TESTS: We check to verify that the caching of species is actually working. :: sage: species.CycleSpecies() is species.CycleSpecies() True sage: P = species.CycleSpecies() sage: c = P.generating_series()[:3] sage: P._check() True sage: P == loads(dumps(P)) True """ GenericCombinatorialSpecies.__init__(self, min=min, max=max, weight=weight) self._name = "Cyclic permutation species" _default_structure_class = CycleSpeciesStructure def _structures(self, structure_class, labels): """ EXAMPLES:: sage: P = species.CycleSpecies() sage: P.structures([1,2,3]).list() [(1, 2, 3), (1, 3, 2)] """ from sage.combinat.permutation import CyclicPermutations for c in CyclicPermutations(range(1, len(labels)+1)): yield structure_class(self, labels, c) def _isotypes(self, structure_class, labels): """ EXAMPLES:: sage: P = species.CycleSpecies() sage: P.isotypes([1,2,3]).list() [(1, 2, 3)] """ if len(labels) != 0: yield structure_class(self, labels, range(1, len(labels)+1)) def _gs_callable(self, base_ring, n): r""" The generating series for cyclic permutations is `-\log(1-x) = \sum_{n=1}^\infty x^n/n`. EXAMPLES:: sage: P = species.CycleSpecies() sage: g = P.generating_series() sage: g[0:10] [0, 1, 1/2, 1/3, 1/4, 1/5, 1/6, 1/7, 1/8, 1/9] TESTS:: sage: P = species.CycleSpecies() sage: g = P.generating_series(RR) sage: g[0:3] [0.000000000000000, 1.00000000000000, 0.500000000000000] """ if n: return self._weight * base_ring.one() / n return base_ring.zero() def _order(self): """ Returns the order of the generating series. EXAMPLES:: sage: P = species.CycleSpecies() sage: P._order() 1 """ return 1 def _itgs_list(self, base_ring, n): """ The isomorphism type generating series for cyclic permutations is given by `x/(1-x)`. EXAMPLES:: sage: P = species.CycleSpecies() sage: g = P.isotype_generating_series() sage: g[0:5] [0, 1, 1, 1, 1] TESTS:: sage: P = species.CycleSpecies() sage: g = P.isotype_generating_series(RR) sage: g[0:3] [0.000000000000000, 1.00000000000000, 1.00000000000000] """ if n: return self._weight * base_ring.one() return base_ring.zero() def _cis_callable(self, base_ring, n): r""" The cycle index series of the species of cyclic permutations is given by .. MATH:: -\sum_{k=1}^\infty \phi(k)/k * log(1 - x_k) which is equal to .. MATH:: \sum_{n=1}^\infty \frac{1}{n} * \sum_{k|n} \phi(k) * x_k^{n/k} . EXAMPLES:: sage: P = species.CycleSpecies() sage: cis = P.cycle_index_series() sage: cis[0:7] [0, p[1], 1/2*p[1, 1] + 1/2*p[2], 1/3*p[1, 1, 1] + 2/3*p[3], 1/4*p[1, 1, 1, 1] + 1/4*p[2, 2] + 1/2*p[4], 1/5*p[1, 1, 1, 1, 1] + 4/5*p[5], 1/6*p[1, 1, 1, 1, 1, 1] + 1/6*p[2, 2, 2] + 1/3*p[3, 3] + 1/3*p[6]] """ from sage.combinat.sf.sf import SymmetricFunctions p = SymmetricFunctions(base_ring).power() zero = base_ring.zero() if not n: return zero res = zero for k in divisors(n): res += euler_phi(k)*p([k])**(n//k) res /= n return self._weight * res #Backward compatibility CycleSpecies_class = CycleSpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/cycle_species.py
0.839767
0.36676
cycle_species.py
pypi
from .species import GenericCombinatorialSpecies from .structure import GenericSpeciesStructure from sage.structure.unique_representation import UniqueRepresentation from sage.combinat.permutation import Permutation, Permutations from sage.combinat.species.misc import accept_size class PermutationSpeciesStructure(GenericSpeciesStructure): def canonical_label(self): """ EXAMPLES:: sage: P = species.PermutationSpecies() sage: S = P.structures(["a", "b", "c"]) sage: [s.canonical_label() for s in S] [['a', 'b', 'c'], ['b', 'a', 'c'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['b', 'c', 'a'], ['b', 'a', 'c']] """ P = self.parent() return P._canonical_rep_from_partition(self.__class__, self._labels, Permutation(self._list).cycle_type()) def permutation_group_element(self): """ Returns self as a permutation group element. EXAMPLES:: sage: p = PermutationGroupElement((2,3,4)) sage: P = species.PermutationSpecies() sage: a = P.structures(["a", "b", "c", "d"])[2]; a ['a', 'c', 'b', 'd'] sage: a.permutation_group_element() (2,3) """ return Permutation(self._list).to_permutation_group_element() def transport(self, perm): """ Returns the transport of this structure along the permutation perm. EXAMPLES:: sage: p = PermutationGroupElement((2,3,4)) sage: P = species.PermutationSpecies() sage: a = P.structures(["a", "b", "c", "d"])[2]; a ['a', 'c', 'b', 'd'] sage: a.transport(p) ['a', 'd', 'c', 'b'] """ p = self.permutation_group_element() p = perm*p*~perm return self.__class__(self.parent(), self._labels, p.domain()) def automorphism_group(self): """ Returns the group of permutations whose action on this structure leave it fixed. EXAMPLES:: sage: set_random_seed(0) sage: p = PermutationGroupElement((2,3,4)) sage: P = species.PermutationSpecies() sage: a = P.structures(["a", "b", "c", "d"])[2]; a ['a', 'c', 'b', 'd'] sage: a.automorphism_group() Permutation Group with generators [(2,3), (1,4)] :: sage: [a.transport(perm) for perm in a.automorphism_group()] [['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd']] """ from sage.groups.all import SymmetricGroup, PermutationGroup S = SymmetricGroup(len(self._labels)) p = self.permutation_group_element() return PermutationGroup(S.centralizer(p).gens()) class PermutationSpecies(GenericCombinatorialSpecies, UniqueRepresentation): @staticmethod @accept_size def __classcall__(cls, *args, **kwds): """ EXAMPLES:: sage: P = species.PermutationSpecies(); P Permutation species """ return super(PermutationSpecies, cls).__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ Returns the species of permutations. EXAMPLES:: sage: P = species.PermutationSpecies() sage: P.generating_series()[0:5] [1, 1, 1, 1, 1] sage: P.isotype_generating_series()[0:5] [1, 1, 2, 3, 5] sage: P = species.PermutationSpecies() sage: c = P.generating_series()[0:3] sage: P._check() True sage: P == loads(dumps(P)) True """ GenericCombinatorialSpecies.__init__(self, min=min, max=max, weight=weight) self._name = "Permutation species" _default_structure_class = PermutationSpeciesStructure def _structures(self, structure_class, labels): """ EXAMPLES:: sage: P = species.PermutationSpecies() sage: P.structures([1,2,3]).list() [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] """ if labels == []: yield structure_class(self, labels, []) else: for p in Permutations(len(labels)): yield structure_class(self, labels, list(p)) def _isotypes(self, structure_class, labels): """ EXAMPLES:: sage: P = species.PermutationSpecies() sage: P.isotypes([1,2,3]).list() [[2, 3, 1], [2, 1, 3], [1, 2, 3]] """ from sage.combinat.partition import Partitions if labels == []: yield structure_class(self, labels, []) return for p in Partitions(len(labels)): yield self._canonical_rep_from_partition(structure_class, labels, p) def _canonical_rep_from_partition(self, structure_class, labels, p): """ EXAMPLES:: sage: P = species.PermutationSpecies() sage: P._canonical_rep_from_partition(P._default_structure_class, ["a","b","c"], [2,1]) ['b', 'a', 'c'] """ indices = list(range(1, len(labels) + 1)) breaks = [sum(p[:i]) for i in range(len(p)+1)] cycles = tuple(tuple(indices[breaks[i]:breaks[i+1]]) for i in range(len(p))) perm = list(Permutation(cycles)) return structure_class(self, labels, perm) def _gs_list(self, base_ring, n): r""" The generating series for the species of linear orders is `\frac{1}{1-x}`. EXAMPLES:: sage: P = species.PermutationSpecies() sage: g = P.generating_series() sage: g[0:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] """ return base_ring.one() def _itgs_callable(self, base_ring, n): r""" The isomorphism type generating series is given by `\frac{1}{1-x}`. EXAMPLES:: sage: P = species.PermutationSpecies() sage: g = P.isotype_generating_series() sage: [g.coefficient(i) for i in range(10)] [1, 1, 2, 3, 5, 7, 11, 15, 22, 30] """ from sage.combinat.partition import number_of_partitions return base_ring(number_of_partitions(n)) def _cis(self, series_ring, base_ring): r""" The cycle index series for the species of permutations is given by .. MATH:: \prod{n=1}^\infty \frac{1}{1-x_n}. EXAMPLES:: sage: P = species.PermutationSpecies() sage: g = P.cycle_index_series() sage: g[0:5] [p[], p[1], p[1, 1] + p[2], p[1, 1, 1] + p[2, 1] + p[3], p[1, 1, 1, 1] + p[2, 1, 1] + p[2, 2] + p[3, 1] + p[4]] """ from sage.combinat.sf.sf import SymmetricFunctions from sage.combinat.partition import Partitions p = SymmetricFunctions(base_ring).p() CIS = series_ring return CIS(lambda n: sum(p(la) for la in Partitions(n))) def _cis_gen(self, base_ring, m, n): """ EXAMPLES:: sage: P = species.PermutationSpecies() sage: [P._cis_gen(QQ, 2, i) for i in range(10)] [p[], 0, p[2], 0, p[2, 2], 0, p[2, 2, 2], 0, p[2, 2, 2, 2], 0] """ from sage.combinat.sf.sf import SymmetricFunctions p = SymmetricFunctions(base_ring).power() pn = p([m]) if not n: return p(1) if m == 1: if n % 2: return base_ring.zero() return pn**(n//2) elif n % m: return base_ring.zero() return pn**(n//m) #Backward compatibility PermutationSpecies_class = PermutationSpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/permutation_species.py
0.795221
0.456046
permutation_species.py
pypi
from .species import GenericCombinatorialSpecies from sage.structure.unique_representation import UniqueRepresentation class EmptySpecies(GenericCombinatorialSpecies, UniqueRepresentation): """ Returns the empty species. This species has no structure at all. It is the zero of the semi-ring of species. EXAMPLES:: sage: X = species.EmptySpecies(); X Empty species sage: X.structures([]).list() [] sage: X.structures([1]).list() [] sage: X.structures([1,2]).list() [] sage: X.generating_series()[0:4] [0, 0, 0, 0] sage: X.isotype_generating_series()[0:4] [0, 0, 0, 0] sage: X.cycle_index_series()[0:4] [0, 0, 0, 0] The empty species is the zero of the semi-ring of species. The following tests that it is neutral with respect to addition:: sage: Empt = species.EmptySpecies() sage: S = species.CharacteristicSpecies(2) sage: X = S + Empt sage: X == S # TODO: Not Implemented True sage: (X.generating_series()[0:4] == ....: S.generating_series()[0:4]) True sage: (X.isotype_generating_series()[0:4] == ....: S.isotype_generating_series()[0:4]) True sage: (X.cycle_index_series()[0:4] == ....: S.cycle_index_series()[0:4]) True The following tests that it is the zero element with respect to multiplication:: sage: Y = Empt*S sage: Y == Empt # TODO: Not Implemented True sage: Y.generating_series()[0:4] [0, 0, 0, 0] sage: Y.isotype_generating_series()[0:4] [0, 0, 0, 0] sage: Y.cycle_index_series()[0:4] [0, 0, 0, 0] TESTS:: sage: Empt = species.EmptySpecies() sage: Empt2 = species.EmptySpecies() sage: Empt is Empt2 True """ def __init__(self, min=None, max=None, weight=None): """ Initializer for the empty species. EXAMPLES:: sage: F = species.EmptySpecies() sage: F._check() True sage: F == loads(dumps(F)) True """ # There is no structure at all, so we set min and max accordingly. GenericCombinatorialSpecies.__init__(self, weight=weight) self._name = "Empty species" def _gs(self, series_ring, base_ring): """ Return the generating series for self. EXAMPLES:: sage: F = species.EmptySpecies() sage: F.generating_series()[0:5] # indirect doctest [0, 0, 0, 0, 0] sage: F.generating_series().count(3) 0 sage: F.generating_series().count(4) 0 """ return series_ring.zero() _itgs = _gs _cis = _gs def _structures(self, structure_class, labels): """ Thanks to the counting optimisation, this is never called... Otherwise this should return an empty iterator. EXAMPLES:: sage: F = species.EmptySpecies() sage: F.structures([]).list() # indirect doctest [] sage: F.structures([1,2,3]).list() # indirect doctest [] """ assert False, "This should never be called" _default_structure_class = 0 _isotypes = _structures def _equation(self, var_mapping): """ Returns the right hand side of an algebraic equation satisfied by this species. This is a utility function called by the algebraic_equation_system method. EXAMPLES:: sage: C = species.EmptySpecies() sage: Qz = QQ['z'] sage: R.<node0> = Qz[] sage: var_mapping = {'z':Qz.gen(), 'node0':R.gen()} sage: C._equation(var_mapping) 0 """ return 0 EmptySpecies_class = EmptySpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/empty_species.py
0.61555
0.613237
empty_species.py
pypi
from .species import GenericCombinatorialSpecies from .structure import GenericSpeciesStructure from sage.structure.unique_representation import UniqueRepresentation from sage.combinat.species.misc import accept_size class LinearOrderSpeciesStructure(GenericSpeciesStructure): def canonical_label(self): """ EXAMPLES:: sage: P = species.LinearOrderSpecies() sage: s = P.structures(["a", "b", "c"]).random_element() sage: s.canonical_label() ['a', 'b', 'c'] """ return self.__class__(self.parent(), self._labels, range(1, len(self._labels)+1)) def transport(self, perm): """ Returns the transport of this structure along the permutation perm. EXAMPLES:: sage: F = species.LinearOrderSpecies() sage: a = F.structures(["a", "b", "c"])[0]; a ['a', 'b', 'c'] sage: p = PermutationGroupElement((1,2)) sage: a.transport(p) ['b', 'a', 'c'] """ return LinearOrderSpeciesStructure(self.parent(), self._labels, [perm(i) for i in self._list]) def automorphism_group(self): """ Returns the group of permutations whose action on this structure leave it fixed. For the species of linear orders, there is no non-trivial automorphism. EXAMPLES:: sage: F = species.LinearOrderSpecies() sage: a = F.structures(["a", "b", "c"])[0]; a ['a', 'b', 'c'] sage: a.automorphism_group() Symmetric group of order 1! as a permutation group """ from sage.groups.all import SymmetricGroup return SymmetricGroup(1) class LinearOrderSpecies(GenericCombinatorialSpecies, UniqueRepresentation): @staticmethod @accept_size def __classcall__(cls, *args, **kwds): r""" EXAMPLES:: sage: L = species.LinearOrderSpecies(); L Linear order species """ return super(LinearOrderSpecies, cls).__classcall__(cls, *args, **kwds) def __init__(self, min=None, max=None, weight=None): """ Returns the species of linear orders. EXAMPLES:: sage: L = species.LinearOrderSpecies() sage: L.generating_series()[0:5] [1, 1, 1, 1, 1] sage: L = species.LinearOrderSpecies() sage: L._check() True sage: L == loads(dumps(L)) True """ GenericCombinatorialSpecies.__init__(self, min=min, max=max, weight=None) self._name = "Linear order species" _default_structure_class = LinearOrderSpeciesStructure def _structures(self, structure_class, labels): """ EXAMPLES:: sage: L = species.LinearOrderSpecies() sage: L.structures([1,2,3]).list() [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] """ from sage.combinat.permutation import Permutations for p in Permutations(len(labels)): yield structure_class(self, labels, p._list) def _isotypes(self, structure_class, labels): """ EXAMPLES:: sage: L = species.LinearOrderSpecies() sage: L.isotypes([1,2,3]).list() [[1, 2, 3]] """ yield structure_class(self, labels, range(1, len(labels)+1)) def _gs_list(self, base_ring, n): r""" The generating series for the species of linear orders is `\frac{1}{1-x}`. EXAMPLES:: sage: L = species.LinearOrderSpecies() sage: g = L.generating_series() sage: g[0:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] """ return base_ring.one() def _itgs_list(self, base_ring, n): r""" The isomorphism type generating series is given by `\frac{1}{1-x}`. EXAMPLES:: sage: L = species.LinearOrderSpecies() sage: g = L.isotype_generating_series() sage: g[0:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] """ return base_ring.one() def _cis_callable(self, base_ring, n): """ EXAMPLES:: sage: L = species.LinearOrderSpecies() sage: g = L.cycle_index_series() sage: g[0:5] [p[], p[1], p[1, 1], p[1, 1, 1], p[1, 1, 1, 1]] """ from sage.combinat.sf.sf import SymmetricFunctions p = SymmetricFunctions(base_ring).power() return p([1]*n) #Backward compatibility LinearOrderSpecies_class = LinearOrderSpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/linear_order_species.py
0.891634
0.440048
linear_order_species.py
pypi
from sage.combinat.species.species import GenericCombinatorialSpecies from sage.combinat.species.structure import SpeciesStructureWrapper from sage.rings.rational_field import QQ class CombinatorialSpeciesStructure(SpeciesStructureWrapper): pass class CombinatorialSpecies(GenericCombinatorialSpecies): def __init__(self, min=None): """ EXAMPLES:: sage: F = CombinatorialSpecies() sage: loads(dumps(F)) Combinatorial species :: sage: X = species.SingletonSpecies() sage: E = species.EmptySetSpecies() sage: L = CombinatorialSpecies() sage: L.define(E+X*L) sage: L.generating_series()[0:4] [1, 1, 1, 1] sage: LL = loads(dumps(L)) sage: LL.generating_series()[0:4] [1, 1, 1, 1] """ self._generating_series = {} self._isotype_generating_series = {} self._cycle_index_series = {} GenericCombinatorialSpecies.__init__(self, min=min, max=None, weight=None) _default_structure_class = CombinatorialSpeciesStructure def __hash__(self): """ EXAMPLES:: sage: hash(CombinatorialSpecies) #random 53751280 :: sage: X = species.SingletonSpecies() sage: E = species.EmptySetSpecies() sage: L = CombinatorialSpecies() sage: L.define(E+X*L) sage: hash(L) #random -826511807095108317 """ try: return hash(('CombinatorialSpecies', id(self._reference))) except AttributeError: return hash('CombinatorialSpecies') def __eq__(self, other): """ TESTS:: sage: A = species.CombinatorialSpecies() sage: B = species.CombinatorialSpecies() sage: A == B False sage: X = species.SingletonSpecies() sage: A.define(X+A*A) sage: B.define(X+B*B) sage: A == B True sage: C = species.CombinatorialSpecies() sage: E = species.EmptySetSpecies() sage: C.define(E+X*C*C) sage: A == C False """ if not isinstance(other, CombinatorialSpecies): return False if not hasattr(self, "_reference"): return False if hasattr(self, '_computing_eq'): return True self._computing_eq = True res = self._unique_info() == other._unique_info() del self._computing_eq return res def __ne__(self, other): """ Check whether ``self`` is not equal to ``other``. EXAMPLES:: sage: A = species.CombinatorialSpecies() sage: B = species.CombinatorialSpecies() sage: A != B True sage: X = species.SingletonSpecies() sage: A.define(X+A*A) sage: B.define(X+B*B) sage: A != B False sage: C = species.CombinatorialSpecies() sage: E = species.EmptySetSpecies() sage: C.define(E+X*C*C) sage: A != C True """ return not (self == other) def _unique_info(self): """ Return a tuple which should uniquely identify the species. EXAMPLES:: sage: F = CombinatorialSpecies() sage: F._unique_info() (<class 'sage.combinat.species.recursive_species.CombinatorialSpecies'>,) :: sage: X = species.SingletonSpecies() sage: E = species.EmptySetSpecies() sage: L = CombinatorialSpecies() sage: L.define(E+X*L) sage: L._unique_info() (<class 'sage.combinat.species.recursive_species.CombinatorialSpecies'>, <class 'sage.combinat.species.sum_species.SumSpecies'>, None, None, 1, Empty set species, Product of (Singleton species) and (Combinatorial species)) """ if hasattr(self, "_reference"): return (self.__class__,) + self._reference._unique_info() else: return (self.__class__,) def __getstate__(self): """ EXAMPLES:: sage: X = species.SingletonSpecies() sage: E = species.EmptySetSpecies() sage: L = CombinatorialSpecies() sage: L.define(E+X*L) sage: L.__getstate__() {'reference': Sum of (Empty set species) and (Product of (Singleton species) and (Combinatorial species))} """ state = {} if hasattr(self, '_reference'): state['reference'] = self._reference return state def __setstate__(self, state): """ EXAMPLES:: sage: X = species.SingletonSpecies() sage: E = species.EmptySetSpecies() sage: L = CombinatorialSpecies() sage: L.define(E+X*L) sage: state = L.__getstate__(); state {'reference': Sum of (Empty set species) and (Product of (Singleton species) and (Combinatorial species))} sage: L._reference = None sage: L.__setstate__(state) sage: L._reference Sum of (Empty set species) and (Product of (Singleton species) and (Combinatorial species)) """ CombinatorialSpecies.__init__(self) if 'reference' in state: self.define(state['reference']) def _structures(self, structure_class, labels): """ EXAMPLES:: sage: F = CombinatorialSpecies() sage: list(F._structures(F._default_structure_class, [1,2,3])) Traceback (most recent call last): ... NotImplementedError """ if not hasattr(self, "_reference"): raise NotImplementedError for s in self._reference.structures(labels): yield structure_class(self, s) def _isotypes(self, structure_class, labels): """ EXAMPLES:: sage: F = CombinatorialSpecies() sage: list(F._isotypes(F._default_structure_class, [1,2,3])) Traceback (most recent call last): ... NotImplementedError """ if not hasattr(self, "_reference"): raise NotImplementedError for s in self._reference.isotypes(labels): yield structure_class(self, s) def _gs(self, series_ring, base_ring): """ EXAMPLES:: sage: F = CombinatorialSpecies() sage: F.generating_series() Uninitialized Lazy Laurent Series """ if base_ring not in self._generating_series: self._generating_series[base_ring] = series_ring.undefined(valuation=(0 if self._min is None else self._min)) res = self._generating_series[base_ring] if hasattr(self, "_reference") and not hasattr(res, "_reference"): res._reference = None res.define(self._reference.generating_series(base_ring)) return res def _itgs(self, series_ring, base_ring): """ EXAMPLES:: sage: F = CombinatorialSpecies() sage: F.isotype_generating_series() Uninitialized Lazy Laurent Series """ if base_ring not in self._isotype_generating_series: self._isotype_generating_series[base_ring] = series_ring.undefined(valuation=(0 if self._min is None else self._min)) res = self._isotype_generating_series[base_ring] if hasattr(self, "_reference") and not hasattr(res, "_reference"): res._reference = None res.define(self._reference.isotype_generating_series(base_ring)) return res def _cis(self, series_ring, base_ring): """ EXAMPLES:: sage: F = CombinatorialSpecies() sage: F.cycle_index_series() Uninitialized Lazy Laurent Series """ if base_ring not in self._cycle_index_series: self._cycle_index_series[base_ring] = series_ring.undefined(valuation=(0 if self._min is None else self._min)) res = self._cycle_index_series[base_ring] if hasattr(self, "_reference") and not hasattr(res, "_reference"): res._reference = None res.define(self._reference.cycle_index_series(base_ring)) return res def weight_ring(self): """ EXAMPLES:: sage: F = species.CombinatorialSpecies() sage: F.weight_ring() Rational Field :: sage: X = species.SingletonSpecies() sage: E = species.EmptySetSpecies() sage: L = CombinatorialSpecies() sage: L.define(E+X*L) sage: L.weight_ring() Rational Field """ if not hasattr(self, "_reference"): return QQ if hasattr(self, "_weight_ring_been_called"): return QQ else: self._weight_ring_been_called = True res = self._reference.weight_ring() del self._weight_ring_been_called return res def define(self, x): """ Define ``self`` to be equal to the combinatorial species ``x``. This is used to define combinatorial species recursively. All of the real work is done by calling the .set() method for each of the series associated to self. EXAMPLES: The species of linear orders L can be recursively defined by `L = 1 + X*L` where 1 represents the empty set species and X represents the singleton species. :: sage: X = species.SingletonSpecies() sage: E = species.EmptySetSpecies() sage: L = CombinatorialSpecies() sage: L.define(E+X*L) sage: L.generating_series()[0:4] [1, 1, 1, 1] sage: L.structures([1,2,3]).cardinality() 6 sage: L.structures([1,2,3]).list() [1*(2*(3*{})), 1*(3*(2*{})), 2*(1*(3*{})), 2*(3*(1*{})), 3*(1*(2*{})), 3*(2*(1*{}))] :: sage: L = species.LinearOrderSpecies() sage: L.generating_series()[0:4] [1, 1, 1, 1] sage: L.structures([1,2,3]).cardinality() 6 sage: L.structures([1,2,3]).list() [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] TESTS:: sage: A = CombinatorialSpecies() sage: A.define(E+X*A*A) sage: A.generating_series()[0:6] [1, 1, 2, 5, 14, 42] sage: A.generating_series().counts(6) [1, 1, 4, 30, 336, 5040] sage: len(A.structures([1,2,3,4]).list()) 336 sage: A.isotype_generating_series()[0:6] [1, 1, 2, 5, 14, 42] sage: len(A.isotypes([1,2,3,4]).list()) 14 :: sage: A = CombinatorialSpecies(min=1) sage: A.define(X+A*A) sage: A.generating_series()[0:6] [0, 1, 1, 2, 5, 14] sage: A.generating_series().counts(6) [0, 1, 2, 12, 120, 1680] sage: len(A.structures([1,2,3]).list()) 12 sage: A.isotype_generating_series()[0:6] [0, 1, 1, 2, 5, 14] sage: len(A.isotypes([1,2,3,4]).list()) 5 :: sage: X2 = X*X sage: X5 = X2*X2*X sage: A = CombinatorialSpecies(min=1) sage: B = CombinatorialSpecies(min=1) sage: C = CombinatorialSpecies(min=1) sage: A.define(X5+B*B) sage: B.define(X5+C*C) sage: C.define(X2+C*C+A*A) sage: A.generating_series()[0:15] [0, 0, 0, 0, 0, 1, 0, 0, 1, 2, 5, 4, 14, 10, 48] sage: B.generating_series()[0:15] [0, 0, 0, 0, 1, 1, 2, 0, 5, 0, 14, 0, 44, 0, 138] sage: C.generating_series()[0:15] [0, 0, 1, 0, 1, 0, 2, 0, 5, 0, 15, 0, 44, 2, 142] :: sage: F = CombinatorialSpecies() sage: F.define(E+X+(X*F+X*X*F)) sage: F.generating_series().counts(10) [1, 2, 6, 30, 192, 1560, 15120, 171360, 2217600, 32296320] sage: F.generating_series()[0:10] [1, 2, 3, 5, 8, 13, 21, 34, 55, 89] sage: F.isotype_generating_series()[0:10] [1, 2, 3, 5, 8, 13, 21, 34, 55, 89] """ if not isinstance(x, GenericCombinatorialSpecies): raise TypeError("x must be a combinatorial species") if self.__class__ is not CombinatorialSpecies: raise TypeError("only undefined combinatorial species can be set") self._reference = x def _add_to_digraph(self, d): """ Adds this species as a vertex to the digraph d along with any 'children' of this species. Note that to avoid infinite recursion, we just return if this species already occurs in the digraph d. EXAMPLES:: sage: d = DiGraph(multiedges=True) sage: X = species.SingletonSpecies() sage: B = species.CombinatorialSpecies() sage: B.define(X+B*B) sage: B._add_to_digraph(d); d Multi-digraph on 4 vertices TESTS:: sage: C = species.CombinatorialSpecies() sage: C._add_to_digraph(d) Traceback (most recent call last): ... NotImplementedError """ if self in d: return try: d.add_edge(self, self._reference) self._reference._add_to_digraph(d) except AttributeError: raise NotImplementedError def _equation(self, var_mapping): """ Returns the right hand side of an algebraic equation satisfied by this species. This is a utility function called by the algebraic_equation_system method. EXAMPLES:: sage: C = species.CombinatorialSpecies() sage: C.algebraic_equation_system() Traceback (most recent call last): ... NotImplementedError :: sage: B = species.BinaryTreeSpecies() sage: B.algebraic_equation_system() [-node3^2 + node1, -node1 + node3 + (-z)] """ try: return var_mapping[self._reference] except AttributeError: raise NotImplementedError
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/recursive_species.py
0.755457
0.295481
recursive_species.py
pypi
from .species import GenericCombinatorialSpecies from .structure import GenericSpeciesStructure from .subset_species import SubsetSpecies from sage.structure.unique_representation import UniqueRepresentation class ProductSpeciesStructure(GenericSpeciesStructure): def __init__(self, parent, labels, subset, left, right): """ TESTS:: sage: S = species.SetSpecies() sage: F = S * S sage: a = F.structures(['a','b','c']).random_element() sage: a == loads(dumps(a)) True """ self._subset = subset GenericSpeciesStructure.__init__(self, parent, labels, [left, right]) def __repr__(self): """ Return the string representation of this object. EXAMPLES:: sage: S = species.SetSpecies() sage: (S*S).structures(['a','b','c'])[0] {}*{'a', 'b', 'c'} sage: (S*S*S).structures(['a','b','c'])[13] ({'c'}*{'a'})*{'b'} """ left, right = map(repr, self._list) if "*" in left: left = "(%s)" % left if "*" in right: right = "(%s)" % right return "%s*%s" % (left, right) def transport(self, perm): """ EXAMPLES:: sage: p = PermutationGroupElement((2,3)) sage: S = species.SetSpecies() sage: F = S * S sage: a = F.structures(['a','b','c'])[4]; a {'a', 'b'}*{'c'} sage: a.transport(p) {'a', 'c'}*{'b'} """ left, right = self._list new_subset = self._subset.transport(perm) left_labels = new_subset.label_subset() right_labels = new_subset.complement().label_subset() return self.__class__(self.parent(), self._labels, new_subset, left.change_labels(left_labels), right.change_labels(right_labels)) def canonical_label(self): """ EXAMPLES:: sage: S = species.SetSpecies() sage: F = S * S sage: S = F.structures(['a','b','c']).list(); S [{}*{'a', 'b', 'c'}, {'a'}*{'b', 'c'}, {'b'}*{'a', 'c'}, {'c'}*{'a', 'b'}, {'a', 'b'}*{'c'}, {'a', 'c'}*{'b'}, {'b', 'c'}*{'a'}, {'a', 'b', 'c'}*{}] :: sage: F.isotypes(['a','b','c']).cardinality() 4 sage: [s.canonical_label() for s in S] [{}*{'a', 'b', 'c'}, {'a'}*{'b', 'c'}, {'a'}*{'b', 'c'}, {'a'}*{'b', 'c'}, {'a', 'b'}*{'c'}, {'a', 'b'}*{'c'}, {'a', 'b'}*{'c'}, {'a', 'b', 'c'}*{}] """ left, right = self._list new_subset = self._subset.canonical_label() left_labels = new_subset.label_subset() right_labels = new_subset.complement().label_subset() return self.__class__(self.parent(), self._labels, new_subset, left.canonical_label().change_labels(left_labels), right.canonical_label().change_labels(right_labels)) def change_labels(self, labels): """ Return a relabelled structure. INPUT: - ``labels``, a list of labels. OUTPUT: A structure with the i-th label of self replaced with the i-th label of the list. EXAMPLES:: sage: S = species.SetSpecies() sage: F = S * S sage: a = F.structures(['a','b','c'])[0]; a {}*{'a', 'b', 'c'} sage: a.change_labels([1,2,3]) {}*{1, 2, 3} """ left, right = self._list new_subset = self._subset.change_labels(labels) left_labels = new_subset.label_subset() right_labels = new_subset.complement().label_subset() return self.__class__(self.parent(), labels, new_subset, left.change_labels(left_labels), right.change_labels(right_labels)) def automorphism_group(self): """ EXAMPLES:: sage: p = PermutationGroupElement((2,3)) sage: S = species.SetSpecies() sage: F = S * S sage: a = F.structures([1,2,3,4])[1]; a {1}*{2, 3, 4} sage: a.automorphism_group() Permutation Group with generators [(2,3), (2,3,4)] :: sage: [a.transport(g) for g in a.automorphism_group()] [{1}*{2, 3, 4}, {1}*{2, 3, 4}, {1}*{2, 3, 4}, {1}*{2, 3, 4}, {1}*{2, 3, 4}, {1}*{2, 3, 4}] :: sage: a = F.structures([1,2,3,4])[8]; a {2, 3}*{1, 4} sage: [a.transport(g) for g in a.automorphism_group()] [{2, 3}*{1, 4}, {2, 3}*{1, 4}, {2, 3}*{1, 4}, {2, 3}*{1, 4}] """ from sage.groups.all import PermutationGroupElement, PermutationGroup from sage.combinat.species.misc import change_support left, right = self._list # Get the supports for each of the sides l_support = self._subset._list r_support = self._subset.complement()._list # Get the automorphism group for the left object and # make it have the correct support. Do the same to the # right side. l_aut = change_support(left.automorphism_group(), l_support) r_aut = change_support(right.automorphism_group(), r_support) identity = PermutationGroupElement([]) gens = l_aut.gens() + r_aut.gens() gens = [g for g in gens if g != identity] gens = sorted(set(gens)) if gens else [[]] return PermutationGroup(gens) class ProductSpecies(GenericCombinatorialSpecies, UniqueRepresentation): def __init__(self, F, G, min=None, max=None, weight=None): """ EXAMPLES:: sage: X = species.SingletonSpecies() sage: A = X*X sage: A.generating_series()[0:4] [0, 0, 1, 0] sage: P = species.PermutationSpecies() sage: F = P * P; F Product of (Permutation species) and (Permutation species) sage: F == loads(dumps(F)) True sage: F._check() True TESTS:: sage: X = species.SingletonSpecies() sage: X*X is X*X True """ self._F = F self._G = G self._state_info = [F, G] GenericCombinatorialSpecies.__init__(self, min=None, max=None, weight=weight) _default_structure_class = ProductSpeciesStructure def left_factor(self): """ Returns the left factor of this product. EXAMPLES:: sage: P = species.PermutationSpecies() sage: X = species.SingletonSpecies() sage: F = P*X sage: F.left_factor() Permutation species """ return self._F def right_factor(self): """ Returns the right factor of this product. EXAMPLES:: sage: P = species.PermutationSpecies() sage: X = species.SingletonSpecies() sage: F = P*X sage: F.right_factor() Singleton species """ return self._G def _name(self): """ Note that we use a function to return the name of this species because we can't do it in the __init__ method due to it requiring that self.left_factor() and self.right_factor() already be unpickled. EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P * P sage: F._name() 'Product of (Permutation species) and (Permutation species)' """ return "Product of (%s) and (%s)" % (self.left_factor(), self.right_factor()) def _structures(self, structure_class, labels): """ EXAMPLES:: sage: S = species.SetSpecies() sage: F = S * S sage: F.structures([1,2]).list() [{}*{1, 2}, {1}*{2}, {2}*{1}, {1, 2}*{}] """ return self._times_gen(structure_class, "structures", labels) def _isotypes(self, structure_class, labels): """ EXAMPLES:: sage: S = species.SetSpecies() sage: F = S * S sage: F.isotypes([1,2,3]).list() [{}*{1, 2, 3}, {1}*{2, 3}, {1, 2}*{3}, {1, 2, 3}*{}] """ return self._times_gen(structure_class, "isotypes", labels) def _times_gen(self, structure_class, attr, labels): """ EXAMPLES:: sage: S = species.SetSpecies() sage: F = S * S sage: list(F._times_gen(F._default_structure_class, 'structures',[1,2])) [{}*{1, 2}, {1}*{2}, {2}*{1}, {1, 2}*{}] """ def c(F, n): return F.generating_series().coefficient(n) S = SubsetSpecies() for u in getattr(S, attr)(labels): vl = u.complement().label_subset() ul = u.label_subset() if c(self.left_factor(), len(ul)) == 0 or c(self.right_factor(), len(vl)) == 0: continue for x in getattr(self.left_factor(), attr)(ul): for y in getattr(self.right_factor(), attr)(vl): yield structure_class(self, labels, u, x, y) def _gs(self, series_ring, base_ring): """ EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P * P sage: F.generating_series()[0:5] [1, 2, 3, 4, 5] """ res = (self.left_factor().generating_series(base_ring) * self.right_factor().generating_series(base_ring)) if self.is_weighted(): res = self._weight * res return res def _itgs(self, series_ring, base_ring): """ EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P * P sage: F.isotype_generating_series()[0:5] [1, 2, 5, 10, 20] """ res = (self.left_factor().isotype_generating_series(base_ring) * self.right_factor().isotype_generating_series(base_ring)) if self.is_weighted(): res = self._weight * res return res def _cis(self, series_ring, base_ring): """ EXAMPLES:: sage: P = species.PermutationSpecies() sage: F = P * P sage: F.cycle_index_series()[0:5] [p[], 2*p[1], 3*p[1, 1] + 2*p[2], 4*p[1, 1, 1] + 4*p[2, 1] + 2*p[3], 5*p[1, 1, 1, 1] + 6*p[2, 1, 1] + 3*p[2, 2] + 4*p[3, 1] + 2*p[4]] """ res = (self.left_factor().cycle_index_series(base_ring) * self.right_factor().cycle_index_series(base_ring)) if self.is_weighted(): res = self._weight * res return res def weight_ring(self): """ Returns the weight ring for this species. This is determined by asking Sage's coercion model what the result is when you multiply (and add) elements of the weight rings for each of the operands. EXAMPLES:: sage: S = species.SetSpecies() sage: C = S*S sage: C.weight_ring() Rational Field :: sage: S = species.SetSpecies(weight=QQ['t'].gen()) sage: C = S*S sage: C.weight_ring() Univariate Polynomial Ring in t over Rational Field :: sage: S = species.SetSpecies() sage: C = (S*S).weighted(QQ['t'].gen()) sage: C.weight_ring() Univariate Polynomial Ring in t over Rational Field """ return self._common_parent([self.left_factor().weight_ring(), self.right_factor().weight_ring(), self._weight.parent()]) def _equation(self, var_mapping): """ Returns the right hand side of an algebraic equation satisfied by this species. This is a utility function called by the algebraic_equation_system method. EXAMPLES:: sage: X = species.SingletonSpecies() sage: S = X * X sage: S.algebraic_equation_system() [node0 + (-z^2)] """ from sage.misc.misc_c import prod return prod(var_mapping[operand] for operand in self._state_info) # Backward compatibility ProductSpecies_class = ProductSpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/product_species.py
0.854869
0.386242
product_species.py
pypi
from .species import GenericCombinatorialSpecies from .structure import GenericSpeciesStructure class FunctorialCompositionStructure(GenericSpeciesStructure): pass class FunctorialCompositionSpecies(GenericCombinatorialSpecies): def __init__(self, F, G, min=None, max=None, weight=None): """ Returns the functorial composition of two species. EXAMPLES:: sage: E = species.SetSpecies() sage: E2 = species.SetSpecies(size=2) sage: WP = species.SubsetSpecies() sage: P2 = E2*E sage: G = WP.functorial_composition(P2) sage: G.isotype_generating_series()[0:5] [1, 1, 2, 4, 11] sage: G = species.SimpleGraphSpecies() sage: c = G.generating_series()[0:2] sage: type(G) <class 'sage.combinat.species.functorial_composition_species.FunctorialCompositionSpecies'> sage: G == loads(dumps(G)) True sage: G._check() #False due to isomorphism types not being implemented False """ self._F = F self._G = G self._state_info = [F, G] self._name = f"Functorial composition of ({F}) and ({G})" GenericCombinatorialSpecies.__init__(self, min=None, max=None, weight=None) _default_structure_class = FunctorialCompositionStructure def _structures(self, structure_class, s): """ EXAMPLES:: sage: G = species.SimpleGraphSpecies() sage: G.structures([1,2,3]).list() [{}, {{1, 2}*{3}}, {{1, 3}*{2}}, {{2, 3}*{1}}, {{1, 2}*{3}, {1, 3}*{2}}, {{1, 2}*{3}, {2, 3}*{1}}, {{1, 3}*{2}, {2, 3}*{1}}, {{1, 2}*{3}, {1, 3}*{2}, {2, 3}*{1}}] """ gs = self._G.structures(s).list() for f in self._F.structures(gs): yield f def _isotypes(self, structure_class, s): """ There is no known algorithm for efficiently generating the isomorphism types of the functorial composition of two species. EXAMPLES:: sage: G = species.SimpleGraphSpecies() sage: G.isotypes([1,2,3]).list() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def _gs(self, series_ring, base_ring): """ EXAMPLES:: sage: G = species.SimpleGraphSpecies() sage: G.generating_series()[0:5] [1, 1, 1, 4/3, 8/3] """ return self._F.generating_series(base_ring).functorial_composition(self._G.generating_series(base_ring)) def _itgs(self, series_ring, base_ring): """ EXAMPLES:: sage: G = species.SimpleGraphSpecies() sage: G.isotype_generating_series()[0:5] [1, 1, 2, 4, 11] """ return self.cycle_index_series(base_ring).isotype_generating_series() def _cis(self, series_ring, base_ring): """ EXAMPLES:: sage: G = species.SimpleGraphSpecies() sage: G.cycle_index_series()[0:5] [p[], p[1], p[1, 1] + p[2], 4/3*p[1, 1, 1] + 2*p[2, 1] + 2/3*p[3], 8/3*p[1, 1, 1, 1] + 4*p[2, 1, 1] + 2*p[2, 2] + 4/3*p[3, 1] + p[4]] """ return self._F.cycle_index_series(base_ring).functorial_composition(self._G.cycle_index_series(base_ring)) def weight_ring(self): """ Returns the weight ring for this species. This is determined by asking Sage's coercion model what the result is when you multiply (and add) elements of the weight rings for each of the operands. EXAMPLES:: sage: G = species.SimpleGraphSpecies() sage: G.weight_ring() Rational Field """ from sage.structure.element import get_coercion_model cm = get_coercion_model() f_weights = self._F.weight_ring() g_weights = self._G.weight_ring() return cm.explain(f_weights, g_weights, verbosity=0) # Backward compatibility FunctorialCompositionSpecies_class = FunctorialCompositionSpecies
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/species/functorial_composition_species.py
0.842345
0.441071
functorial_composition_species.py
pypi
r""" Common combinatorial tools REFERENCES: .. [NCSF] Gelfand, Krob, Lascoux, Leclerc, Retakh, Thibon, *Noncommutative Symmetric Functions*, Adv. Math. 112 (1995), no. 2, 218-348. .. [QSCHUR] Haglund, Luoto, Mason, van Willigenburg, *Quasisymmetric Schur functions*, J. Comb. Theory Ser. A 118 (2011), 463-490. http://www.sciencedirect.com/science/article/pii/S0097316509001745 , :arxiv:`0810.2489v2`. .. [Tev2007] Lenny Tevlin, *Noncommutative Analogs of Monomial Symmetric Functions, Cauchy Identity, and Hall Scalar Product*, :arxiv:`0712.2201v1`. """ from sage.misc.misc_c import prod from sage.arith.misc import factorial from sage.misc.cachefunc import cached_function from sage.combinat.composition import Composition, Compositions from sage.combinat.composition_tableau import CompositionTableaux from sage.rings.integer_ring import ZZ # The following might call for defining a morphism from ``structure # coefficients'' / matrix using something like: # Complete.module_morphism( coeff = coeff_pi, codomain=Psi, triangularity="finer" ) # the difficulty is how to best describe the support of the output. def coeff_pi(J, I): r""" Returns the coefficient `\pi_{J,I}` as defined in [NCSF]_. INPUT: - ``J`` -- a composition - ``I`` -- a composition refining ``J`` OUTPUT: - integer EXAMPLES:: sage: from sage.combinat.ncsf_qsym.combinatorics import coeff_pi sage: coeff_pi(Composition([1,1,1]), Composition([2,1])) 2 sage: coeff_pi(Composition([2,1]), Composition([3])) 6 """ return prod(prod(K.partial_sums()) for K in J.refinement_splitting(I)) def coeff_lp(J,I): r""" Returns the coefficient `lp_{J,I}` as defined in [NCSF]_. INPUT: - ``J`` -- a composition - ``I`` -- a composition refining ``J`` OUTPUT: - integer EXAMPLES:: sage: from sage.combinat.ncsf_qsym.combinatorics import coeff_lp sage: coeff_lp(Composition([1,1,1]), Composition([2,1])) 1 sage: coeff_lp(Composition([2,1]), Composition([3])) 1 """ return prod(K[-1] for K in J.refinement_splitting(I)) def coeff_ell(J,I): r""" Returns the coefficient `\ell_{J,I}` as defined in [NCSF]_. INPUT: - ``J`` -- a composition - ``I`` -- a composition refining ``J`` OUTPUT: - integer EXAMPLES:: sage: from sage.combinat.ncsf_qsym.combinatorics import coeff_ell sage: coeff_ell(Composition([1,1,1]), Composition([2,1])) 2 sage: coeff_ell(Composition([2,1]), Composition([3])) 2 """ return prod([len(elt) for elt in J.refinement_splitting(I)]) def coeff_sp(J, I): r""" Returns the coefficient `sp_{J,I}` as defined in [NCSF]_. INPUT: - ``J`` -- a composition - ``I`` -- a composition refining ``J`` OUTPUT: - integer EXAMPLES:: sage: from sage.combinat.ncsf_qsym.combinatorics import coeff_sp sage: coeff_sp(Composition([1,1,1]), Composition([2,1])) 2 sage: coeff_sp(Composition([2,1]), Composition([3])) 4 """ return prod(factorial(len(K))*prod(K) for K in J.refinement_splitting(I)) def coeff_dab(I, J): r""" Return the number of standard composition tableaux of shape `I` with descent composition `J`. INPUT: - ``I, J`` -- compositions OUTPUT: - An integer EXAMPLES:: sage: from sage.combinat.ncsf_qsym.combinatorics import coeff_dab sage: coeff_dab(Composition([2,1]),Composition([2,1])) 1 sage: coeff_dab(Composition([1,1,2]),Composition([1,2,1])) 0 """ d = 0 for T in CompositionTableaux(I): if (T.is_standard()) and (T.descent_composition() == J): d += 1 return d def compositions_order(n): r""" Return the compositions of `n` ordered as defined in [QSCHUR]_. Let `S(\gamma)` return the composition `\gamma` after sorting. For compositions `\alpha` and `\beta`, we order `\alpha \rhd \beta` if 1) `S(\alpha) > S(\beta)` lexicographically, or 2) `S(\alpha) = S(\beta)` and `\alpha > \beta` lexicographically. INPUT: - ``n`` -- a positive integer OUTPUT: - A list of the compositions of ``n`` sorted into decreasing order by `\rhd` EXAMPLES:: sage: from sage.combinat.ncsf_qsym.combinatorics import compositions_order sage: compositions_order(3) [[3], [2, 1], [1, 2], [1, 1, 1]] sage: compositions_order(4) [[4], [3, 1], [1, 3], [2, 2], [2, 1, 1], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]] """ def _keyfunction(I): return sorted(I, reverse=True), list(I) return sorted(Compositions(n), key=_keyfunction, reverse=True) def m_to_s_stat(R, I, K): r""" Return the coefficient of the complete non-commutative symmetric function `S^K` in the expansion of the monomial non-commutative symmetric function `M^I` with respect to the complete basis over the ring `R`. This is the coefficient in formula (36) of Tevlin's paper [Tev2007]_. INPUT: - ``R`` -- A ring, supposed to be a `\QQ`-algebra - ``I``, ``K`` -- compositions OUTPUT: - The coefficient of `S^K` in the expansion of `M^I` in the complete basis of the non-commutative symmetric functions over ``R``. EXAMPLES:: sage: from sage.combinat.ncsf_qsym.combinatorics import m_to_s_stat sage: m_to_s_stat(QQ, Composition([2,1]), Composition([1,1,1])) -1 sage: m_to_s_stat(QQ, Composition([3]), Composition([1,2])) -2 sage: m_to_s_stat(QQ, Composition([2,1,2]), Composition([2,1,2])) 8/3 """ stat = 0 for J in Compositions(I.size()): if I.is_finer(J) and K.is_finer(J): pvec = [0] + Composition(I).refinement_splitting_lengths(J).partial_sums() pp = prod( R( len(I) - pvec[i] ) for i in range( len(pvec)-1 ) ) stat += R((-1)**(len(I)-len(K)) / pp * coeff_lp(K, J)) return stat @cached_function def number_of_fCT(content_comp, shape_comp): r""" Return the number of Immaculate tableaux of shape ``shape_comp`` and content ``content_comp``. See [BBSSZ2012]_, Definition 3.9, for the notion of an immaculate tableau. INPUT: - ``content_comp``, ``shape_comp`` -- compositions OUTPUT: - An integer EXAMPLES:: sage: from sage.combinat.ncsf_qsym.combinatorics import number_of_fCT sage: number_of_fCT(Composition([3,1]), Composition([1,3])) 0 sage: number_of_fCT(Composition([1,2,1]), Composition([1,3])) 1 sage: number_of_fCT(Composition([1,1,3,1]), Composition([2,1,3])) 2 """ if content_comp.to_partition().length() == 1: if shape_comp.to_partition().length() == 1: return 1 else: return 0 C = Compositions(content_comp.size()-content_comp[-1], outer = list(shape_comp)) s = 0 for x in C: if len(x) >= len(shape_comp)-1: s += number_of_fCT(Composition(content_comp[:-1]),x) return s @cached_function def number_of_SSRCT(content_comp, shape_comp): r""" The number of semi-standard reverse composition tableaux. The dual quasisymmetric-Schur functions satisfy a left Pieri rule where `S_n dQS_\gamma` is a sum over dual quasisymmetric-Schur functions indexed by compositions which contain the composition `\gamma`. The definition of an SSRCT comes from this rule. The number of SSRCT of content `\beta` and shape `\alpha` is equal to the number of SSRCT of content `(\beta_2, \ldots, \beta_\ell)` and shape `\gamma` where `dQS_\alpha` appears in the expansion of `S_{\beta_1} dQS_\gamma`. In sage the recording tableau for these objects are called :class:`~sage.combinat.composition_tableau.CompositionTableaux`. INPUT: - ``content_comp``, ``shape_comp`` -- compositions OUTPUT: - An integer EXAMPLES:: sage: from sage.combinat.ncsf_qsym.combinatorics import number_of_SSRCT sage: number_of_SSRCT(Composition([3,1]), Composition([1,3])) 0 sage: number_of_SSRCT(Composition([1,2,1]), Composition([1,3])) 1 sage: number_of_SSRCT(Composition([1,1,2,2]), Composition([3,3])) 2 sage: all(CompositionTableaux(be).cardinality() ....: == sum(number_of_SSRCT(al,be)*binomial(4,len(al)) ....: for al in Compositions(4)) ....: for be in Compositions(4)) True """ if len(content_comp) == 1: if len(shape_comp) == 1: return ZZ.one() else: return ZZ.zero() s = ZZ.zero() cond = lambda al,be: all(al[j] <= be_val and not any(al[i] <= k and k <= be[i] for k in range(al[j], be_val) for i in range(j)) for j, be_val in enumerate(be)) C = Compositions(content_comp.size()-content_comp[0], inner=[1]*len(shape_comp), outer=list(shape_comp)) for x in C: if cond(x, shape_comp): s += number_of_SSRCT(Composition(content_comp[1:]), x) if shape_comp[0] <= content_comp[0]: C = Compositions(content_comp.size()-content_comp[0], inner=[min(val, shape_comp[0]+1) for val in shape_comp[1:]], outer=shape_comp[1:]) Comps = Compositions() for x in C: if cond([shape_comp[0]]+list(x), shape_comp): s += number_of_SSRCT(Comps(content_comp[1:]), x) return s
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/ncsf_qsym/combinatorics.py
0.919482
0.551574
combinatorics.py
pypi
r""" Introduction to Quasisymmetric Functions In this document we briefly explain the quasisymmetric function bases and related functionality in Sage. We assume the reader is familiar with the package :class:`SymmetricFunctions`. Quasisymmetric functions, denoted `QSym`, form a subring of the power series ring in countably many variables. `QSym` contains the symmetric functions. These functions first arose in the theory of `P`-partitions. The initial ideas in this field are attributed to MacMahon, Knuth, Kreweras, Glânffrwd Thomas, Stanley. In 1984, Gessel formalized the study of quasisymmetric functions and introduced the basis of fundamental quasisymmetric functions [Ges]_. In 1995, Gelfand, Krob, Lascoux, Leclerc, Retakh, and Thibon showed that the ring of quasisymmetric functions is Hopf dual to the noncommutative symmetric functions [NCSF]_. Many results have built on these. One advantage of working in `QSym` is that many interesting families of symmetric functions have explicit expansions in fundamental quasisymmetric functions such as Schur functions [Ges]_, Macdonald polynomials [HHL05]_, and plethysm of Schur functions [LW12]_. For more background see :wikipedia:`Quasisymmetric_function`. To begin, initialize the ring. Below we chose to use the rational numbers `\QQ`. Other options include the integers `\ZZ` and `\CC`:: sage: QSym = QuasiSymmetricFunctions(QQ) sage: QSym Quasisymmetric functions over the Rational Field sage: QSym = QuasiSymmetricFunctions(CC); QSym Quasisymmetric functions over the Complex Field with 53 bits of precision sage: QSym = QuasiSymmetricFunctions(ZZ); QSym Quasisymmetric functions over the Integer Ring All bases of `QSym` are indexed by compositions e.g. `[3,1,1,4]`. The convention is to use capital letters for bases of `QSym` and lowercase letters for bases of the symmetric functions `Sym`. Next set up names for the known bases by running ``inject_shorthands()``. As with symmetric functions, you do not need to run this command and you could assign these bases other names. :: sage: QSym = QuasiSymmetricFunctions(QQ) sage: QSym.inject_shorthands() Defining M as shorthand for Quasisymmetric functions over the Rational Field in the Monomial basis Defining F as shorthand for Quasisymmetric functions over the Rational Field in the Fundamental basis Defining E as shorthand for Quasisymmetric functions over the Rational Field in the Essential basis Defining dI as shorthand for Quasisymmetric functions over the Rational Field in the dualImmaculate basis Defining QS as shorthand for Quasisymmetric functions over the Rational Field in the Quasisymmetric Schur basis Defining YQS as shorthand for Quasisymmetric functions over the Rational Field in the Young Quasisymmetric Schur basis Defining phi as shorthand for Quasisymmetric functions over the Rational Field in the phi basis Defining psi as shorthand for Quasisymmetric functions over the Rational Field in the psi basis Now one can start constructing quasisymmetric functions. .. NOTE:: It is best to use variables other than ``M`` and ``F``. :: sage: x = M[2,1] + M[1,2] sage: x M[1, 2] + M[2, 1] sage: y = 3*M[1,2] + M[3]^2; y 3*M[1, 2] + 2*M[3, 3] + M[6] sage: F[3,1,3] + 7*F[2,1] 7*F[2, 1] + F[3, 1, 3] sage: 3*F[2,1,2] + F[3]^2 F[1, 2, 2, 1] + F[1, 2, 3] + 2*F[1, 3, 2] + F[1, 4, 1] + F[1, 5] + 3*F[2, 1, 2] + 2*F[2, 2, 2] + 2*F[2, 3, 1] + 2*F[2, 4] + F[3, 2, 1] + 3*F[3, 3] + 2*F[4, 2] + F[5, 1] + F[6] To convert from one basis to another is easy:: sage: z = M[1,2,1] sage: z M[1, 2, 1] sage: F(z) -F[1, 1, 1, 1] + F[1, 2, 1] sage: M(F(z)) M[1, 2, 1] To expand in variables, one can specify a finite size alphabet `x_1, x_2, \ldots, x_m`:: sage: y = M[1,2,1] sage: y.expand(4) x0*x1^2*x2 + x0*x1^2*x3 + x0*x2^2*x3 + x1*x2^2*x3 The usual methods on free modules are available such as coefficients, degrees, and the support:: sage: z = 3*M[1,2]+M[3]^2; z 3*M[1, 2] + 2*M[3, 3] + M[6] sage: z.coefficient([1,2]) 3 sage: z.degree() 6 sage: sorted(z.coefficients()) [1, 2, 3] sage: sorted(z.monomials(), key=lambda x: tuple(x.support())) [M[1, 2], M[3, 3], M[6]] sage: z.monomial_coefficients() {[1, 2]: 3, [3, 3]: 2, [6]: 1} As with the symmetric functions package, the quasisymmetric function ``1`` has several instantiations. However, the most obvious way to write ``1`` leads to an error (this is due to the semantics of python):: sage: M[[]] M[] sage: M.one() M[] sage: M(1) M[] sage: M[[]] == 1 True sage: M[] Traceback (most recent call last): ... SyntaxError: invalid ... Working with symmetric functions -------------------------------- The quasisymmetric functions are a ring which contains the symmetric functions as a subring. The Monomial quasisymmetric functions are related to the monomial symmetric functions by `m_\lambda = \sum_{\mathrm{sort}(c) = \lambda} M_c`, where `\mathrm{sort}(c)` means the partition obtained by sorting the composition `c`:: sage: SymmetricFunctions(QQ).inject_shorthands() Defining e as shorthand for Symmetric Functions over Rational Field in the elementary basis Defining f as shorthand for Symmetric Functions over Rational Field in the forgotten basis Defining h as shorthand for Symmetric Functions over Rational Field in the homogeneous basis Defining m as shorthand for Symmetric Functions over Rational Field in the monomial basis Defining p as shorthand for Symmetric Functions over Rational Field in the powersum basis Defining s as shorthand for Symmetric Functions over Rational Field in the Schur basis sage: m[2,1] m[2, 1] sage: M(m[2,1]) M[1, 2] + M[2, 1] sage: M(s[2,1]) 2*M[1, 1, 1] + M[1, 2] + M[2, 1] There are methods to test if an expression `f` in the quasisymmetric functions is a symmetric function:: sage: f = M[1,1,2] + M[1,2,1] sage: f.is_symmetric() False sage: f = M[3,1] + M[1,3] sage: f.is_symmetric() True If `f` is symmetric, there are methods to convert `f` to an expression in the symmetric functions:: sage: f.to_symmetric_function() m[3, 1] The expansion of the Schur function in terms of the Fundamental quasisymmetric functions is due to [Ges]_. There is one term in the expansion for each standard tableau of shape equal to the partition indexing the Schur function. :: sage: f = F[3,2] + F[2,2,1] + F[2,3] + F[1,3,1] + F[1,2,2] sage: f.is_symmetric() True sage: f.to_symmetric_function() 5*m[1, 1, 1, 1, 1] + 3*m[2, 1, 1, 1] + 2*m[2, 2, 1] + m[3, 1, 1] + m[3, 2] sage: s(f.to_symmetric_function()) s[3, 2] It is also possible to convert any symmetric function to the quasisymmetric function expansion in any known basis. The converse is not true:: sage: M( m[3,1,1] ) M[1, 1, 3] + M[1, 3, 1] + M[3, 1, 1] sage: F( s[2,2,1] ) F[1, 1, 2, 1] + F[1, 2, 1, 1] + F[1, 2, 2] + F[2, 1, 2] + F[2, 2, 1] sage: s(M[2,1]) Traceback (most recent call last): ... TypeError: do not know how to make x (= M[2, 1]) an element of self It is possible to experiment with the quasisymmetric function expansion of other bases, but it is important that the base ring be the same for both algebras. :: sage: R = QQ['t'] sage: Qp = SymmetricFunctions(R).hall_littlewood().Qp() sage: QSymt = QuasiSymmetricFunctions(R) sage: Ft = QSymt.F() sage: Ft( Qp[2,2] ) F[1, 2, 1] + t*F[1, 3] + (t+1)*F[2, 2] + t*F[3, 1] + t^2*F[4] :: sage: K = QQ['q','t'].fraction_field() sage: Ht = SymmetricFunctions(K).macdonald().Ht() sage: Fqt = QuasiSymmetricFunctions(Ht.base_ring()).F() sage: Fqt(Ht[2,1]) q*t*F[1, 1, 1] + (q+t)*F[1, 2] + (q+t)*F[2, 1] + F[3] The following will raise an error because the base ring of ``F`` is not equal to the base ring of ``Ht``:: sage: F(Ht[2,1]) Traceback (most recent call last): ... TypeError: do not know how to make x (= McdHt[2, 1]) an element of self (=Quasisymmetric functions over the Rational Field in the Fundamental basis) QSym is a Hopf algebra ---------------------- The product on `QSym` is commutative and is inherited from the product by the realization within the polynomial ring:: sage: M[3]*M[1,1] == M[1,1]*M[3] True sage: M[3]*M[1,1] M[1, 1, 3] + M[1, 3, 1] + M[1, 4] + M[3, 1, 1] + M[4, 1] sage: F[3]*F[1,1] F[1, 1, 3] + F[1, 2, 2] + F[1, 3, 1] + F[1, 4] + F[2, 1, 2] + F[2, 2, 1] + F[2, 3] + F[3, 1, 1] + F[3, 2] + F[4, 1] sage: M[3]*F[2] M[1, 1, 3] + M[1, 3, 1] + M[1, 4] + M[2, 3] + M[3, 1, 1] + M[3, 2] + M[4, 1] + M[5] sage: F[2]*M[3] F[1, 1, 1, 2] - F[1, 2, 2] + F[2, 1, 1, 1] - F[2, 1, 2] - F[2, 2, 1] + F[5] There is a coproduct on this ring as well, which in the Monomial basis acts by cutting the composition into a left half and a right half. The co-product is non-co-commutative:: sage: M[1,3,1].coproduct() M[] # M[1, 3, 1] + M[1] # M[3, 1] + M[1, 3] # M[1] + M[1, 3, 1] # M[] sage: F[1,3,1].coproduct() F[] # F[1, 3, 1] + F[1] # F[3, 1] + F[1, 1] # F[2, 1] + F[1, 2] # F[1, 1] + F[1, 3] # F[1] + F[1, 3, 1] # F[] .. rubric:: The Duality Pairing with Non-Commutative Symmetric Functions These two operations endow `QSym` with the structure of a Hopf algebra. It is the dual Hopf algebra of the non-commutative symmetric functions `NCSF`. Under this duality, the Monomial basis of `QSym` is dual to the Complete basis of `NCSF`, and the Fundamental basis of `QSym` is dual to the Ribbon basis of `NCSF` (see [MR]_):: sage: S = M.dual(); S Non-Commutative Symmetric Functions over the Rational Field in the Complete basis sage: M[1,3,1].duality_pairing( S[1,3,1] ) 1 sage: M.duality_pairing_matrix( S, degree=4 ) [1 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0] [0 0 1 0 0 0 0 0] [0 0 0 1 0 0 0 0] [0 0 0 0 1 0 0 0] [0 0 0 0 0 1 0 0] [0 0 0 0 0 0 1 0] [0 0 0 0 0 0 0 1] sage: F.duality_pairing_matrix( S, degree=4 ) [1 0 0 0 0 0 0 0] [1 1 0 0 0 0 0 0] [1 0 1 0 0 0 0 0] [1 1 1 1 0 0 0 0] [1 0 0 0 1 0 0 0] [1 1 0 0 1 1 0 0] [1 0 1 0 1 0 1 0] [1 1 1 1 1 1 1 1] sage: NCSF = M.realization_of().dual() sage: R = NCSF.Ribbon() sage: F.duality_pairing_matrix( R, degree=4 ) [1 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0] [0 0 1 0 0 0 0 0] [0 0 0 1 0 0 0 0] [0 0 0 0 1 0 0 0] [0 0 0 0 0 1 0 0] [0 0 0 0 0 0 1 0] [0 0 0 0 0 0 0 1] sage: M.duality_pairing_matrix( R, degree=4 ) [ 1 0 0 0 0 0 0 0] [-1 1 0 0 0 0 0 0] [-1 0 1 0 0 0 0 0] [ 1 -1 -1 1 0 0 0 0] [-1 0 0 0 1 0 0 0] [ 1 -1 0 0 -1 1 0 0] [ 1 0 -1 0 -1 0 1 0] [-1 1 1 -1 1 -1 -1 1] Let `H` and `G` be elements of `QSym` and `h` an element of `NCSF`. Then if we represent the duality pairing with the mathematical notation `[ \cdot, \cdot ]`, we have: .. MATH:: [H \cdot G, h] = [H \otimes G, \Delta(h)]. For example, the coefficient of ``M[2,1,4,1]`` in ``M[1,3]*M[2,1,1]`` may be computed with the duality pairing:: sage: I, J = Composition([1,3]), Composition([2,1,1]) sage: (M[I]*M[J]).duality_pairing(S[2,1,4,1]) 1 And the coefficient of ``S[1,3] # S[2,1,1]`` in ``S[2,1,4,1].coproduct()`` is equal to this result:: sage: S[2,1,4,1].coproduct() S[] # S[2, 1, 4, 1] + ... + S[1, 3] # S[2, 1, 1] + ... + S[4, 1] # S[2, 1] The duality pairing on the tensor space is another way of getting this coefficient, but currently the method :meth:`~sage.combinat.ncsf_qsym.generic_basis_code.BasesOfQSymOrNCSF.ParentMethods.duality_pairing()` is not defined on the tensor squared space. However, we can extend this functionality by applying a linear morphism to the terms in the coproduct, as follows:: sage: X = S[2,1,4,1].coproduct() sage: def linear_morphism(x, y): ....: return x.duality_pairing(M[1,3]) * y.duality_pairing(M[2,1,1]) sage: X.apply_multilinear_morphism(linear_morphism, codomain=ZZ) 1 Similarly, if `H` is an element of `QSym` and `g` and `h` are elements of `NCSF`, then .. MATH:: [ H, g \cdot h ] = [ \Delta(H), g \otimes h ]. For example, the coefficient of ``R[2,3,1]`` in ``R[2,1]*R[2,1]`` is computed with the duality pairing by the following command:: sage: (R[2,1]*R[2,1]).duality_pairing(F[2,3,1]) 1 sage: R[2,1]*R[2,1] R[2, 1, 2, 1] + R[2, 3, 1] This coefficient should then be equal to the coefficient of ``F[2,1] # F[2,1]`` in ``F[2,3,1].coproduct()``:: sage: F[2,3,1].coproduct() F[] # F[2, 3, 1] + ... + F[2, 1] # F[2, 1] + ... + F[2, 3, 1] # F[] This can also be computed by the duality pairing on the tensor space, as above:: sage: X = F[2,3,1].coproduct() sage: def linear_morphism(x, y): ....: return x.duality_pairing(R[2,1]) * y.duality_pairing(R[2,1]) sage: X.apply_multilinear_morphism(linear_morphism, codomain=ZZ) 1 .. rubric:: The Operation Adjoint to Multiplication by a Non-Commutative Symmetric Function Let `g \in NCSF` and consider the linear endomorphism of `NCSF` defined by left (respectively, right) multiplication by `g`. Since there is a duality between `QSym` and `NCSF`, this linear transformation induces an operator `g^\perp` on `QSym` satisfying .. MATH:: [ g^\perp(H), h ] = [ H, g \cdot h ]. for any non-commutative symmetric function `h`. This is implemented by the method :meth:`~sage.combinat.ncsf_qsym.generic_basis_code.BasesOfQSymOrNCSF.ElementMethods.skew_by()`. Explicitly, if ``H`` is a quasisymmetric function and ``g`` a non-commutative symmetric function, then ``H.skew_by(g)`` and ``H.skew_by(g, side='right')`` are expressions that satisfy, for any non-commutative symmetric function ``h``, the following identities:: H.skew_by(g).duality_pairing(h) == H.duality_pairing(g*h) H.skew_by(g, side='right').duality_pairing(h) == H.duality_pairing(h*g) For example, ``M[J].skew_by(S[I])`` is `0` unless the composition `J` begins with `I` and ``M(J).skew_by(S(I), side='right')`` is `0` unless the composition `J` ends with `I`:: sage: M[3,2,2].skew_by(S[3]) M[2, 2] sage: M[3,2,2].skew_by(S[2]) 0 sage: M[3,2,2].coproduct().apply_multilinear_morphism( lambda x,y: x.duality_pairing(S[3])*y ) M[2, 2] sage: M[3,2,2].skew_by(S[3], side='right') 0 sage: M[3,2,2].skew_by(S[2], side='right') M[3, 2] .. rubric:: The antipode The antipode sends the Fundamental basis element indexed by the composition `I` to `-1` to the size of `I` times the Fundamental basis element indexed by the conjugate composition to `I`:: sage: F[3,2,2].antipode() -F[1, 2, 2, 1, 1] sage: Composition([3,2,2]).conjugate() [1, 2, 2, 1, 1] sage: M[3,2,2].antipode() -M[2, 2, 3] - M[2, 5] - M[4, 3] - M[7] We demonstrate here the defining relation of the antipode:: sage: X = F[3,2,2].coproduct() sage: X.apply_multilinear_morphism(lambda x,y: x*y.antipode()) 0 sage: X.apply_multilinear_morphism(lambda x,y: x.antipode()*y) 0 REFERENCES: .. [HHL05] *A combinatorial formula for Macdonald polynomials*. Haiman, Haglund, and Loehr. J. Amer. Math. Soc. 18 (2005), no. 3, 735-761. .. [LW12] *Quasisymmetric expansions of Schur-function plethysms*. Loehr and Warrington. Proc. Amer. Math. Soc. 140 (2012), no. 4, 1159-1171. .. [KT97] *Noncommutative symmetric functions IV: Quantum linear groups and Hecke algebras at* `q = 0`. Krob and Thibon. Journal of Algebraic Combinatorics 6 (1997), 339-376. """
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/ncsf_qsym/tutorial.py
0.935619
0.975878
tutorial.py
pypi
# OneExactCover and AllExactCovers are almost exact copies of the # functions with the same name in sage/combinat/dlx.py by Tom Boothby. from .dancing_links import dlx_solver def DLXCPP(rows): """ Solves the Exact Cover problem by using the Dancing Links algorithm described by Knuth. Consider a matrix M with entries of 0 and 1, and compute a subset of the rows of this matrix which sum to the vector of all 1's. The dancing links algorithm works particularly well for sparse matrices, so the input is a list of lists of the form:: [ [i_11,i_12,...,i_1r] ... [i_m1,i_m2,...,i_ms] ] where M[j][i_jk] = 1. The first example below corresponds to the matrix:: 1110 1010 0100 0001 which is exactly covered by:: 1110 0001 and :: 1010 0100 0001 If soln is a solution given by DLXCPP(rows) then [ rows[soln[0]], rows[soln[1]], ... rows[soln[len(soln)-1]] ] is an exact cover. Solutions are given as a list. EXAMPLES:: sage: rows = [[0,1,2]] sage: rows+= [[0,2]] sage: rows+= [[1]] sage: rows+= [[3]] sage: [x for x in DLXCPP(rows)] [[3, 0], [3, 1, 2]] """ if not rows: return x = dlx_solver(rows) while x.search(): yield x.get_solution() def AllExactCovers(M): """ Solves the exact cover problem on the matrix M (treated as a dense binary matrix). EXAMPLES: No exact covers:: sage: M = Matrix([[1,1,0],[1,0,1],[0,1,1]]) sage: [cover for cover in AllExactCovers(M)] [] Two exact covers:: sage: M = Matrix([[1,1,0],[1,0,1],[0,0,1],[0,1,0]]) sage: [cover for cover in AllExactCovers(M)] [[(1, 1, 0), (0, 0, 1)], [(1, 0, 1), (0, 1, 0)]] """ rows = [] for R in M.rows(): row = [] for i in range(len(R)): if R[i]: row.append(i) rows.append(row) for s in DLXCPP(rows): yield [M.row(i) for i in s] def OneExactCover(M): """ Solves the exact cover problem on the matrix M (treated as a dense binary matrix). EXAMPLES:: sage: M = Matrix([[1,1,0],[1,0,1],[0,1,1]]) #no exact covers sage: print(OneExactCover(M)) None sage: M = Matrix([[1,1,0],[1,0,1],[0,0,1],[0,1,0]]) #two exact covers sage: OneExactCover(M) [(1, 1, 0), (0, 0, 1)] """ for s in AllExactCovers(M): return s
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/matrices/dlxcpp.py
0.810966
0.837321
dlxcpp.py
pypi
from itertools import repeat from sage.misc.cachefunc import cached_method from sage.misc.misc_c import prod from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.categories.graded_hopf_algebras import GradedHopfAlgebras from sage.categories.rings import Rings from sage.categories.fields import Fields from sage.arith.misc import factorial from sage.combinat.free_module import CombinatorialFreeModule from sage.combinat.ncsym.bases import NCSymBases, MultiplicativeNCSymBases, NCSymBasis_abstract from sage.combinat.set_partition import SetPartitions from sage.combinat.set_partition_ordered import OrderedSetPartitions from sage.combinat.posets.posets import Poset from sage.combinat.sf.sf import SymmetricFunctions from sage.matrix.matrix_space import MatrixSpace from sage.sets.set import Set from sage.rings.integer_ring import ZZ from functools import reduce def matchings(A, B): """ Iterate through all matchings of the sets `A` and `B`. EXAMPLES:: sage: from sage.combinat.ncsym.ncsym import matchings sage: list(matchings([1, 2, 3], [-1, -2])) [[[1], [2], [3], [-1], [-2]], [[1], [2], [3, -1], [-2]], [[1], [2], [3, -2], [-1]], [[1], [2, -1], [3], [-2]], [[1], [2, -1], [3, -2]], [[1], [2, -2], [3], [-1]], [[1], [2, -2], [3, -1]], [[1, -1], [2], [3], [-2]], [[1, -1], [2], [3, -2]], [[1, -1], [2, -2], [3]], [[1, -2], [2], [3], [-1]], [[1, -2], [2], [3, -1]], [[1, -2], [2, -1], [3]]] """ lst_A = list(A) lst_B = list(B) # Handle corner cases if not lst_A: if not lst_B: yield [] else: yield [[b] for b in lst_B] return if not lst_B: yield [[a] for a in lst_A] return rem_A = lst_A[:] a = rem_A.pop(0) for m in matchings(rem_A, lst_B): yield [[a]] + m for i in range(len(lst_B)): rem_B = lst_B[:] b = rem_B.pop(i) for m in matchings(rem_A, rem_B): yield [[a, b]] + m def nesting(la, nu): r""" Return the nesting number of ``la`` inside of ``nu``. If we consider a set partition `A` as a set of arcs `i - j` where `i` and `j` are in the same part of `A`. Define .. MATH:: \operatorname{nst}_{\lambda}^{\nu} = \#\{ i < j < k < l \mid i - l \in \nu, j - k \in \lambda \}, and this corresponds to the number of arcs of `\lambda` strictly contained inside of `\nu`. EXAMPLES:: sage: from sage.combinat.ncsym.ncsym import nesting sage: nu = SetPartition([[1,4], [2], [3]]) sage: mu = SetPartition([[1,4], [2,3]]) sage: nesting(set(mu).difference(nu), nu) 1 :: sage: lst = list(SetPartitions(4)) sage: d = {} sage: for i, nu in enumerate(lst): ....: for mu in nu.coarsenings(): ....: if set(nu.arcs()).issubset(mu.arcs()): ....: d[i, lst.index(mu)] = nesting(set(mu).difference(nu), nu) sage: matrix(d) [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 1 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] """ arcs = [] for p in nu: p = sorted(p) arcs += [(p[i], p[i+1]) for i in range(len(p)-1)] nst = 0 for p in la: p = sorted(p) for i in range(len(p)-1): for a in arcs: if a[0] >= p[i]: break if p[i+1] < a[1]: nst += 1 return nst class SymmetricFunctionsNonCommutingVariables(UniqueRepresentation, Parent): r""" Symmetric functions in non-commutative variables. The ring of symmetric functions in non-commutative variables, which is not to be confused with the :class:`non-commutative symmetric functions<NonCommutativeSymmetricFunctions>`, is the ring of all bounded-degree noncommutative power series in countably many indeterminates (i.e., elements in `R \langle \langle x_1, x_2, x_3, \ldots \rangle \rangle` of bounded degree) which are invariant with respect to the action of the symmetric group `S_{\infty}` on the indices of the indeterminates. It can be regarded as a direct limit over all `n \to \infty` of rings of `S_n`-invariant polynomials in `n` non-commuting variables (that is, `S_n`-invariant elements of `R\langle x_1, x_2, \ldots, x_n \rangle`). This ring is implemented as a Hopf algebra whose basis elements are indexed by set partitions. Let `A = \{A_1, A_2, \ldots, A_r\}` be a set partition of the integers `[k] := \{ 1, 2, \ldots, k \}`. This partition `A` determines an equivalence relation `\sim_A` on `[k]`, which has `c \sim_A d` if and only if `c` and `d` are in the same part `A_j` of `A`. The monomial basis element `\mathbf{m}_A` indexed by `A` is the sum of monomials `x_{i_1} x_{i_2} \cdots x_{i_k}` such that `i_c = i_d` if and only if `c \sim_A d`. The `k`-th graded component of the ring of symmetric functions in non-commutative variables has its dimension equal to the number of set partitions of `[k]`. (If we work, instead, with finitely many -- say, `n` -- variables, then its dimension is equal to the number of set partitions of `[k]` where the number of parts is at most `n`.) .. NOTE:: All set partitions are considered standard (i.e., set partitions of `[n]` for some `n`) unless otherwise stated. REFERENCES: .. [BZ05] \N. Bergeron, M. Zabrocki. *The Hopf algebra of symmetric functions and quasisymmetric functions in non-commutative variables are free and cofree*. (2005). :arxiv:`math/0509265v3`. .. [BHRZ06] \N. Bergeron, C. Hohlweg, M. Rosas, M. Zabrocki. *Grothendieck bialgebras, partition lattices, and symmetric functions in noncommutative variables*. Electronic Journal of Combinatorics. **13** (2006). .. [RS06] \M. Rosas, B. Sagan. *Symmetric functions in noncommuting variables*. Trans. Amer. Math. Soc. **358** (2006). no. 1, 215-232. :arxiv:`math/0208168`. .. [BRRZ08] \N. Bergeron, C. Reutenauer, M. Rosas, M. Zabrocki. *Invariants and coinvariants of the symmetric group in noncommuting variables*. Canad. J. Math. **60** (2008). 266-296. :arxiv:`math/0502082` .. [BT13] \N. Bergeron, N. Thiem. *A supercharacter table decomposition via power-sum symmetric functions*. Int. J. Algebra Comput. **23**, 763 (2013). :doi:`10.1142/S0218196713400171`. :arxiv:`1112.4901`. EXAMPLES: We begin by first creating the ring of `NCSym` and the bases that are analogues of the usual symmetric functions:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: m = NCSym.m() sage: e = NCSym.e() sage: h = NCSym.h() sage: p = NCSym.p() sage: m Symmetric functions in non-commuting variables over the Rational Field in the monomial basis The basis is indexed by set partitions, so we create a few elements and convert them between these bases:: sage: elt = m(SetPartition([[1,3],[2]])) - 2*m(SetPartition([[1],[2]])); elt -2*m{{1}, {2}} + m{{1, 3}, {2}} sage: e(elt) 1/2*e{{1}, {2, 3}} - 2*e{{1, 2}} + 1/2*e{{1, 2}, {3}} - 1/2*e{{1, 2, 3}} - 1/2*e{{1, 3}, {2}} sage: h(elt) -4*h{{1}, {2}} - 2*h{{1}, {2}, {3}} + 1/2*h{{1}, {2, 3}} + 2*h{{1, 2}} + 1/2*h{{1, 2}, {3}} - 1/2*h{{1, 2, 3}} + 3/2*h{{1, 3}, {2}} sage: p(elt) -2*p{{1}, {2}} + 2*p{{1, 2}} - p{{1, 2, 3}} + p{{1, 3}, {2}} sage: m(p(elt)) -2*m{{1}, {2}} + m{{1, 3}, {2}} sage: elt = p(SetPartition([[1,3],[2]])) - 4*p(SetPartition([[1],[2]])) + 2; elt 2*p{} - 4*p{{1}, {2}} + p{{1, 3}, {2}} sage: e(elt) 2*e{} - 4*e{{1}, {2}} + e{{1}, {2}, {3}} - e{{1, 3}, {2}} sage: m(elt) 2*m{} - 4*m{{1}, {2}} - 4*m{{1, 2}} + m{{1, 2, 3}} + m{{1, 3}, {2}} sage: h(elt) 2*h{} - 4*h{{1}, {2}} - h{{1}, {2}, {3}} + h{{1, 3}, {2}} sage: p(m(elt)) 2*p{} - 4*p{{1}, {2}} + p{{1, 3}, {2}} There is also a shorthand for creating elements. We note that we must use ``p[[]]`` to create the empty set partition due to python's syntax. :: sage: eltm = m[[1,3],[2]] - 3*m[[1],[2]]; eltm -3*m{{1}, {2}} + m{{1, 3}, {2}} sage: elte = e[[1,3],[2]]; elte e{{1, 3}, {2}} sage: elth = h[[1,3],[2,4]]; elth h{{1, 3}, {2, 4}} sage: eltp = p[[1,3],[2,4]] + 2*p[[1]] - 4*p[[]]; eltp -4*p{} + 2*p{{1}} + p{{1, 3}, {2, 4}} There is also a natural projection to the usual symmetric functions by letting the variables commute. This projection map preserves the product and coproduct structure. We check that Theorem 2.1 of [RS06]_ holds:: sage: Sym = SymmetricFunctions(QQ) sage: Sm = Sym.m() sage: Se = Sym.e() sage: Sh = Sym.h() sage: Sp = Sym.p() sage: eltm.to_symmetric_function() -6*m[1, 1] + m[2, 1] sage: Sm(p(eltm).to_symmetric_function()) -6*m[1, 1] + m[2, 1] sage: elte.to_symmetric_function() 2*e[2, 1] sage: Se(h(elte).to_symmetric_function()) 2*e[2, 1] sage: elth.to_symmetric_function() 4*h[2, 2] sage: Sh(m(elth).to_symmetric_function()) 4*h[2, 2] sage: eltp.to_symmetric_function() -4*p[] + 2*p[1] + p[2, 2] sage: Sp(e(eltp).to_symmetric_function()) -4*p[] + 2*p[1] + p[2, 2] """ def __init__(self, R): """ Initialize ``self``. EXAMPLES:: sage: NCSym1 = SymmetricFunctionsNonCommutingVariables(FiniteField(23)) sage: NCSym2 = SymmetricFunctionsNonCommutingVariables(Integers(23)) sage: TestSuite(SymmetricFunctionsNonCommutingVariables(QQ)).run() """ # change the line below to assert(R in Rings()) once MRO issues from #15536, #15475 are resolved assert(R in Fields() or R in Rings()) # side effect of this statement assures MRO exists for R self._base = R # Won't be needed once CategoryObject won't override base_ring category = GradedHopfAlgebras(R) # TODO: .Cocommutative() Parent.__init__(self, category = category.WithRealizations()) def _repr_(self): r""" EXAMPLES:: sage: SymmetricFunctionsNonCommutingVariables(ZZ) Symmetric functions in non-commuting variables over the Integer Ring """ return "Symmetric functions in non-commuting variables over the %s" % self.base_ring() def a_realization(self): r""" Return the realization of the powersum basis of ``self``. OUTPUT: - The powersum basis of symmetric functions in non-commuting variables. EXAMPLES:: sage: SymmetricFunctionsNonCommutingVariables(QQ).a_realization() Symmetric functions in non-commuting variables over the Rational Field in the powersum basis """ return self.powersum() _shorthands = tuple(['chi', 'cp', 'm', 'e', 'h', 'p', 'rho', 'x']) def dual(self): r""" Return the dual Hopf algebra of the symmetric functions in non-commuting variables. EXAMPLES:: sage: SymmetricFunctionsNonCommutingVariables(QQ).dual() Dual symmetric functions in non-commuting variables over the Rational Field """ from sage.combinat.ncsym.dual import SymmetricFunctionsNonCommutingVariablesDual return SymmetricFunctionsNonCommutingVariablesDual(self.base_ring()) class monomial(NCSymBasis_abstract): r""" The Hopf algebra of symmetric functions in non-commuting variables in the monomial basis. EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: m = NCSym.m() sage: m[[1,3],[2]]*m[[1,2]] m{{1, 3}, {2}, {4, 5}} + m{{1, 3}, {2, 4, 5}} + m{{1, 3, 4, 5}, {2}} sage: m[[1,3],[2]].coproduct() m{} # m{{1, 3}, {2}} + m{{1}} # m{{1, 2}} + m{{1, 2}} # m{{1}} + m{{1, 3}, {2}} # m{} """ def __init__(self, NCSym): """ EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: TestSuite(NCSym.m()).run() """ CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='m', bracket=False, category=NCSymBases(NCSym)) @cached_method def _m_to_p_on_basis(self, A): r""" Return `\mathbf{m}_A` in terms of the powersum basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the powersum basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: m = NCSym.m() sage: all(m(m._m_to_p_on_basis(A)) == m[A] for i in range(5) ....: for A in SetPartitions(i)) True """ def lt(s, t): if s == t: return False for p in s: if len([z for z in t if z.intersection(p)]) != 1: return False return True p = self.realization_of().p() P = Poset((A.coarsenings(), lt)) R = self.base_ring() return p._from_dict({B: R(P.moebius_function(A, B)) for B in P}) @cached_method def _m_to_cp_on_basis(self, A): r""" Return `\mathbf{m}_A` in terms of the `\mathbf{cp}` basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{cp}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: m = NCSym.m() sage: all(m(m._m_to_cp_on_basis(A)) == m[A] for i in range(5) ....: for A in SetPartitions(i)) True """ cp = self.realization_of().cp() arcs = set(A.arcs()) R = self.base_ring() return cp._from_dict({B: R((-1)**len(set(B.arcs()).difference(A.arcs()))) for B in A.coarsenings() if arcs.issubset(B.arcs())}, remove_zeros=False) def from_symmetric_function(self, f): r""" Return the image of the symmetric function ``f`` in ``self``. This is performed by converting to the monomial basis and extending the method :meth:`sum_of_partitions` linearly. This is a linear map from the symmetric functions to the symmetric functions in non-commuting variables that does not preserve the product or coproduct structure of the Hopf algebra. .. SEEALSO:: :meth:`~Element.to_symmetric_function` INPUT: - ``f`` -- an element of the symmetric functions OUTPUT: - An element of the `\mathbf{m}` basis EXAMPLES:: sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m() sage: mon = SymmetricFunctions(QQ).m() sage: elt = m.from_symmetric_function(mon[2,1,1]); elt 1/12*m{{1}, {2}, {3, 4}} + 1/12*m{{1}, {2, 3}, {4}} + 1/12*m{{1}, {2, 4}, {3}} + 1/12*m{{1, 2}, {3}, {4}} + 1/12*m{{1, 3}, {2}, {4}} + 1/12*m{{1, 4}, {2}, {3}} sage: elt.to_symmetric_function() m[2, 1, 1] sage: e = SymmetricFunctionsNonCommutingVariables(QQ).e() sage: elm = SymmetricFunctions(QQ).e() sage: e(m.from_symmetric_function(elm[4])) 1/24*e{{1, 2, 3, 4}} sage: h = SymmetricFunctionsNonCommutingVariables(QQ).h() sage: hom = SymmetricFunctions(QQ).h() sage: h(m.from_symmetric_function(hom[4])) 1/24*h{{1, 2, 3, 4}} sage: p = SymmetricFunctionsNonCommutingVariables(QQ).p() sage: pow = SymmetricFunctions(QQ).p() sage: p(m.from_symmetric_function(pow[4])) p{{1, 2, 3, 4}} sage: p(m.from_symmetric_function(pow[2,1])) 1/3*p{{1}, {2, 3}} + 1/3*p{{1, 2}, {3}} + 1/3*p{{1, 3}, {2}} sage: p([[1,2]])*p([[1]]) p{{1, 2}, {3}} Check that `\chi \circ \widetilde{\chi}` is the identity on `Sym`:: sage: all(m.from_symmetric_function(pow(la)).to_symmetric_function() == pow(la) ....: for la in Partitions(4)) True """ m = SymmetricFunctions(self.base_ring()).m() return self.sum([c * self.sum_of_partitions(i) for i,c in m(f)]) def dual_basis(self): r""" Return the dual basis to the monomial basis. OUTPUT: - the `\mathbf{w}` basis of the dual Hopf algebra EXAMPLES:: sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m() sage: m.dual_basis() Dual symmetric functions in non-commuting variables over the Rational Field in the w basis """ return self.realization_of().dual().w() def duality_pairing(self, x, y): r""" Compute the pairing between an element of ``self`` and an element of the dual. INPUT: - ``x`` -- an element of symmetric functions in non-commuting variables - ``y`` -- an element of the dual of symmetric functions in non-commuting variables OUTPUT: - an element of the base ring of ``self`` EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: m = NCSym.m() sage: w = m.dual_basis() sage: matrix([[m(A).duality_pairing(w(B)) for A in SetPartitions(3)] for B in SetPartitions(3)]) [1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0 0 1 0] [0 0 0 0 1] sage: (m[[1,2],[3]] + 3*m[[1,3],[2]]).duality_pairing(2*w[[1,3],[2]] + w[[1,2,3]] + 2*w[[1,2],[3]]) 8 """ x = self(x) y = self.dual_basis()(y) return sum(coeff * y[I] for (I, coeff) in x) def product_on_basis(self, A, B): r""" The product on monomial basis elements. The product of the basis elements indexed by two set partitions `A` and `B` is the sum of the basis elements indexed by set partitions `C` such that `C \wedge ([n] | [k]) = A | B` where `n = |A|` and `k = |B|`. Here `A \wedge B` is the infimum of `A` and `B` and `A | B` is the :meth:`SetPartition.pipe` operation. Equivalently we can describe all `C` as matchings between the parts of `A` and `B` where if `a \in A` is matched with `b \in B`, we take `a \cup b` instead of `a` and `b` in `C`. INPUT: - ``A``, ``B`` -- set partitions OUTPUT: - an element of the `\mathbf{m}` basis EXAMPLES:: sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial() sage: A = SetPartition([[1], [2,3]]) sage: B = SetPartition([[1], [3], [2,4]]) sage: m.product_on_basis(A, B) m{{1}, {2, 3}, {4}, {5, 7}, {6}} + m{{1}, {2, 3, 4}, {5, 7}, {6}} + m{{1}, {2, 3, 5, 7}, {4}, {6}} + m{{1}, {2, 3, 6}, {4}, {5, 7}} + m{{1, 4}, {2, 3}, {5, 7}, {6}} + m{{1, 4}, {2, 3, 5, 7}, {6}} + m{{1, 4}, {2, 3, 6}, {5, 7}} + m{{1, 5, 7}, {2, 3}, {4}, {6}} + m{{1, 5, 7}, {2, 3, 4}, {6}} + m{{1, 5, 7}, {2, 3, 6}, {4}} + m{{1, 6}, {2, 3}, {4}, {5, 7}} + m{{1, 6}, {2, 3, 4}, {5, 7}} + m{{1, 6}, {2, 3, 5, 7}, {4}} sage: B = SetPartition([[1], [2]]) sage: m.product_on_basis(A, B) m{{1}, {2, 3}, {4}, {5}} + m{{1}, {2, 3, 4}, {5}} + m{{1}, {2, 3, 5}, {4}} + m{{1, 4}, {2, 3}, {5}} + m{{1, 4}, {2, 3, 5}} + m{{1, 5}, {2, 3}, {4}} + m{{1, 5}, {2, 3, 4}} sage: m.product_on_basis(A, SetPartition([])) m{{1}, {2, 3}} TESTS: We check that we get all of the correct set partitions:: sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial() sage: A = SetPartition([[1], [2,3]]) sage: B = SetPartition([[1], [2]]) sage: S = SetPartition([[1,2,3], [4,5]]) sage: AB = SetPartition([[1], [2,3], [4], [5]]) sage: L = sorted(filter(lambda x: S.inf(x) == AB, SetPartitions(5)), key=str) sage: list(map(list, L)) == list(map(list, sorted(m.product_on_basis(A, B).support(), key=str))) True """ if not A: return self.monomial(B) if not B: return self.monomial(A) P = SetPartitions() n = A.size() B = [Set([y+n for y in b]) for b in B] # Shift B by n unions = lambda m: [reduce(lambda a,b: a.union(b), x) for x in m] one = self.base_ring().one() return self._from_dict({P(unions(m)): one for m in matchings(A, B)}, remove_zeros=False) def coproduct_on_basis(self, A): r""" Return the coproduct of a monomial basis element. INPUT: - ``A`` -- a set partition OUTPUT: - The coproduct applied to the monomial symmetric function in non-commuting variables indexed by ``A`` expressed in the monomial basis. EXAMPLES:: sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial() sage: m[[1, 3], [2]].coproduct() m{} # m{{1, 3}, {2}} + m{{1}} # m{{1, 2}} + m{{1, 2}} # m{{1}} + m{{1, 3}, {2}} # m{} sage: m.coproduct_on_basis(SetPartition([])) m{} # m{} sage: m.coproduct_on_basis(SetPartition([[1,2,3]])) m{} # m{{1, 2, 3}} + m{{1, 2, 3}} # m{} sage: m[[1,5],[2,4],[3,7],[6]].coproduct() m{} # m{{1, 5}, {2, 4}, {3, 7}, {6}} + m{{1}} # m{{1, 5}, {2, 4}, {3, 6}} + 2*m{{1, 2}} # m{{1, 3}, {2, 5}, {4}} + m{{1, 2}} # m{{1, 4}, {2, 3}, {5}} + 2*m{{1, 2}, {3}} # m{{1, 3}, {2, 4}} + m{{1, 3}, {2}} # m{{1, 4}, {2, 3}} + 2*m{{1, 3}, {2, 4}} # m{{1, 2}, {3}} + 2*m{{1, 3}, {2, 5}, {4}} # m{{1, 2}} + m{{1, 4}, {2, 3}} # m{{1, 3}, {2}} + m{{1, 4}, {2, 3}, {5}} # m{{1, 2}} + m{{1, 5}, {2, 4}, {3, 6}} # m{{1}} + m{{1, 5}, {2, 4}, {3, 7}, {6}} # m{} """ P = SetPartitions() # Handle corner cases if not A: return self.tensor_square().monomial(( P([]), P([]) )) if len(A) == 1: return self.tensor_square().sum_of_monomials([(P([]), A), (A, P([]))]) ell_set = list(range(1, len(A) + 1)) # +1 for indexing L = [[[], ell_set]] + list(SetPartitions(ell_set, 2)) def to_basis(S): if not S: return P([]) sub_parts = [list(A[i-1]) for i in S] # -1 for indexing mins = [min(p) for p in sub_parts] over_max = max([max(p) for p in sub_parts]) + 1 ret = [[] for _ in repeat(None, len(S))] cur = 1 while min(mins) != over_max: m = min(mins) i = mins.index(m) ret[i].append(cur) cur += 1 sub_parts[i].pop(sub_parts[i].index(m)) if sub_parts[i]: mins[i] = min(sub_parts[i]) else: mins[i] = over_max return P(ret) L1 = [(to_basis(S), to_basis(C)) for S,C in L] L2 = [(M, N) for N,M in L1] return self.tensor_square().sum_of_monomials(L1 + L2) def internal_coproduct_on_basis(self, A): r""" Return the internal coproduct of a monomial basis element. The internal coproduct is defined by .. MATH:: \Delta^{\odot}(\mathbf{m}_A) = \sum_{B \wedge C = A} \mathbf{m}_B \otimes \mathbf{m}_C where we sum over all pairs of set partitions `B` and `C` whose infimum is `A`. INPUT: - ``A`` -- a set partition OUTPUT: - an element of the tensor square of the `\mathbf{m}` basis EXAMPLES:: sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial() sage: m.internal_coproduct_on_basis(SetPartition([[1,3],[2]])) m{{1, 2, 3}} # m{{1, 3}, {2}} + m{{1, 3}, {2}} # m{{1, 2, 3}} + m{{1, 3}, {2}} # m{{1, 3}, {2}} """ P = SetPartitions() SP = SetPartitions(A.size()) ret = [[A,A]] for i, B in enumerate(SP): for C in SP[i+1:]: if B.inf(C) == A: B_std = P(list(B.standardization())) C_std = P(list(C.standardization())) ret.append([B_std, C_std]) ret.append([C_std, B_std]) return self.tensor_square().sum_of_monomials((B, C) for B,C in ret) def sum_of_partitions(self, la): r""" Return the sum over all set partitions whose shape is ``la`` with a fixed coefficient `C` defined below. Fix a partition `\lambda`, we define `\lambda! := \prod_i \lambda_i!` and `\lambda^! := \prod_i m_i!`. Recall that `|\lambda| = \sum_i \lambda_i` and `m_i` is the number of parts of length `i` of `\lambda`. Thus we defined the coefficient as .. MATH:: C := \frac{\lambda! \lambda^!}{|\lambda|!}. Hence we can define a lift `\widetilde{\chi}` from `Sym` to `NCSym` by .. MATH:: m_{\lambda} \mapsto C \sum_A \mathbf{m}_A where the sum is over all set partitions whose shape is `\lambda`. INPUT: - ``la`` -- an integer partition OUTPUT: - an element of the `\mathbf{m}` basis EXAMPLES:: sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m() sage: m.sum_of_partitions(Partition([2,1,1])) 1/12*m{{1}, {2}, {3, 4}} + 1/12*m{{1}, {2, 3}, {4}} + 1/12*m{{1}, {2, 4}, {3}} + 1/12*m{{1, 2}, {3}, {4}} + 1/12*m{{1, 3}, {2}, {4}} + 1/12*m{{1, 4}, {2}, {3}} TESTS: Check that `\chi \circ \widetilde{\chi}` is the identity on `Sym`:: sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m() sage: mon = SymmetricFunctions(QQ).monomial() sage: all(m.from_symmetric_function(mon[la]).to_symmetric_function() == mon[la] ....: for i in range(6) for la in Partitions(i)) True """ from sage.combinat.partition import Partition la = Partition(la) # Make sure it is a partition R = self.base_ring() P = SetPartitions() c = R( prod(factorial(i) for i in la) / ZZ(factorial(la.size())) ) return self._from_dict({P(m): c for m in SetPartitions(sum(la), la)}, remove_zeros=False) class Element(CombinatorialFreeModule.Element): """ An element in the monomial basis of `NCSym`. """ def expand(self, n, alphabet='x'): r""" Expand ``self`` written in the monomial basis in `n` non-commuting variables. INPUT: - ``n`` -- an integer - ``alphabet`` -- (default: ``'x'``) a string OUTPUT: - The symmetric function of ``self`` expressed in the ``n`` non-commuting variables described by ``alphabet``. EXAMPLES:: sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial() sage: m[[1,3],[2]].expand(4) x0*x1*x0 + x0*x2*x0 + x0*x3*x0 + x1*x0*x1 + x1*x2*x1 + x1*x3*x1 + x2*x0*x2 + x2*x1*x2 + x2*x3*x2 + x3*x0*x3 + x3*x1*x3 + x3*x2*x3 One can use a different set of variables by using the optional argument ``alphabet``:: sage: m[[1],[2,3]].expand(3,alphabet='y') y0*y1^2 + y0*y2^2 + y1*y0^2 + y1*y2^2 + y2*y0^2 + y2*y1^2 """ from sage.algebras.free_algebra import FreeAlgebra from sage.combinat.permutation import Permutations m = self.parent() F = FreeAlgebra(m.base_ring(), n, alphabet) x = F.gens() def on_basis(A): basic_term = [0] * A.size() for index, part in enumerate(A): for i in part: basic_term[i-1] = index # -1 for indexing return sum( prod(x[p[i]-1] for i in basic_term) # -1 for indexing for p in Permutations(n, len(A)) ) return m._apply_module_morphism(self, on_basis, codomain=F) def to_symmetric_function(self): r""" The projection of ``self`` to the symmetric functions. Take a symmetric function in non-commuting variables expressed in the `\mathbf{m}` basis, and return the projection of expressed in the monomial basis of symmetric functions. The map `\chi \colon NCSym \to Sym` is defined by .. MATH:: \mathbf{m}_A \mapsto m_{\lambda(A)} \prod_i n_i(\lambda(A))! where `\lambda(A)` is the partition associated with `A` by taking the sizes of the parts and `n_i(\mu)` is the multiplicity of `i` in `\mu`. OUTPUT: - an element of the symmetric functions in the monomial basis EXAMPLES:: sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial() sage: m[[1,3],[2]].to_symmetric_function() m[2, 1] sage: m[[1],[3],[2]].to_symmetric_function() 6*m[1, 1, 1] """ m = SymmetricFunctions(self.parent().base_ring()).monomial() c = lambda la: prod(factorial(i) for i in la.to_exp()) return m.sum_of_terms((i.shape(), coeff*c(i.shape())) for (i, coeff) in self) m = monomial class elementary(NCSymBasis_abstract): r""" The Hopf algebra of symmetric functions in non-commuting variables in the elementary basis. EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: e = NCSym.e() """ def __init__(self, NCSym): """ EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: TestSuite(NCSym.e()).run() """ CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='e', bracket=False, category=MultiplicativeNCSymBases(NCSym)) ## Register coercions # monomials m = NCSym.m() self.module_morphism(self._e_to_m_on_basis, codomain=m).register_as_coercion() # powersum # NOTE: Keep this ahead of creating the homogeneous basis to # get the coercion path m -> p -> e p = NCSym.p() self.module_morphism(self._e_to_p_on_basis, codomain=p, triangular="upper").register_as_coercion() p.module_morphism(p._p_to_e_on_basis, codomain=self, triangular="upper").register_as_coercion() # homogeneous h = NCSym.h() self.module_morphism(self._e_to_h_on_basis, codomain=h, triangular="upper").register_as_coercion() h.module_morphism(h._h_to_e_on_basis, codomain=self, triangular="upper").register_as_coercion() @cached_method def _e_to_m_on_basis(self, A): r""" Return `\mathbf{e}_A` in terms of the monomial basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{m}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: e = NCSym.e() sage: all(e(e._e_to_m_on_basis(A)) == e[A] for i in range(5) ....: for A in SetPartitions(i)) True """ m = self.realization_of().m() n = A.size() P = SetPartitions(n) min_elt = P([[i] for i in range(1, n+1)]) one = self.base_ring().one() return m._from_dict({B: one for B in P if A.inf(B) == min_elt}, remove_zeros=False) @cached_method def _e_to_h_on_basis(self, A): r""" Return `\mathbf{e}_A` in terms of the homogeneous basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{h}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: e = NCSym.e() sage: all(e(e._e_to_h_on_basis(A)) == e[A] for i in range(5) ....: for A in SetPartitions(i)) True """ h = self.realization_of().h() sign = lambda B: (-1)**(B.size() - len(B)) coeff = lambda B: sign(B) * prod(factorial(sum( 1 for part in B if part.issubset(big) )) for big in A) R = self.base_ring() return h._from_dict({B: R(coeff(B)) for B in A.refinements()}, remove_zeros=False) @cached_method def _e_to_p_on_basis(self, A): r""" Return `\mathbf{e}_A` in terms of the powersum basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{p}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: e = NCSym.e() sage: all(e(e._e_to_p_on_basis(A)) == e[A] for i in range(5) ....: for A in SetPartitions(i)) True """ p = self.realization_of().p() coeff = lambda B: prod([(-1)**(i-1) * factorial(i-1) for i in B.shape()]) R = self.base_ring() return p._from_dict({B: R(coeff(B)) for B in A.refinements()}, remove_zeros=False) class Element(CombinatorialFreeModule.Element): """ An element in the elementary basis of `NCSym`. """ def omega(self): r""" Return the involution `\omega` applied to ``self``. The involution `\omega` on `NCSym` is defined by `\omega(\mathbf{e}_A) = \mathbf{h}_A`. OUTPUT: - an element in the basis ``self`` EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: e = NCSym.e() sage: h = NCSym.h() sage: elt = e[[1,3],[2]].omega(); elt 2*e{{1}, {2}, {3}} - e{{1, 3}, {2}} sage: elt.omega() e{{1, 3}, {2}} sage: h(elt) h{{1, 3}, {2}} """ P = self.parent() h = P.realization_of().h() return P(h.sum_of_terms(self)) def to_symmetric_function(self): r""" The projection of ``self`` to the symmetric functions. Take a symmetric function in non-commuting variables expressed in the `\mathbf{e}` basis, and return the projection of expressed in the elementary basis of symmetric functions. The map `\chi \colon NCSym \to Sym` is given by .. MATH:: \mathbf{e}_A \mapsto e_{\lambda(A)} \prod_i \lambda(A)_i! where `\lambda(A)` is the partition associated with `A` by taking the sizes of the parts. OUTPUT: - An element of the symmetric functions in the elementary basis EXAMPLES:: sage: e = SymmetricFunctionsNonCommutingVariables(QQ).e() sage: e[[1,3],[2]].to_symmetric_function() 2*e[2, 1] sage: e[[1],[3],[2]].to_symmetric_function() e[1, 1, 1] """ e = SymmetricFunctions(self.parent().base_ring()).e() c = lambda la: prod(factorial(i) for i in la) return e.sum_of_terms((i.shape(), coeff*c(i.shape())) for (i, coeff) in self) e = elementary class homogeneous(NCSymBasis_abstract): r""" The Hopf algebra of symmetric functions in non-commuting variables in the homogeneous basis. EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: h = NCSym.h() sage: h[[1,3],[2,4]]*h[[1,2,3]] h{{1, 3}, {2, 4}, {5, 6, 7}} sage: h[[1,2]].coproduct() h{} # h{{1, 2}} + 2*h{{1}} # h{{1}} + h{{1, 2}} # h{} """ def __init__(self, NCSym): """ EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: TestSuite(NCSym.h()).run() """ CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='h', bracket=False, category=MultiplicativeNCSymBases(NCSym)) # Register coercions m = NCSym.m() self.module_morphism(self._h_to_m_on_basis, codomain=m).register_as_coercion() p = NCSym.p() self.module_morphism(self._h_to_p_on_basis, codomain=p).register_as_coercion() p.module_morphism(p._p_to_h_on_basis, codomain=self).register_as_coercion() @cached_method def _h_to_m_on_basis(self, A): r""" Return `\mathbf{h}_A` in terms of the monomial basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{m}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: h = NCSym.h() sage: all(h(h._h_to_m_on_basis(A)) == h[A] for i in range(5) ....: for A in SetPartitions(i)) True """ P = SetPartitions() m = self.realization_of().m() coeff = lambda B: prod(factorial(i) for i in B.shape()) R = self.base_ring() return m._from_dict({P(B): R( coeff(A.inf(B)) ) for B in SetPartitions(A.size())}, remove_zeros=False) @cached_method def _h_to_e_on_basis(self, A): r""" Return `\mathbf{h}_A` in terms of the elementary basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{e}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: h = NCSym.h() sage: all(h(h._h_to_e_on_basis(A)) == h[A] for i in range(5) ....: for A in SetPartitions(i)) True """ e = self.realization_of().e() sign = lambda B: (-1)**(B.size() - len(B)) coeff = lambda B: (sign(B) * prod(factorial(sum( 1 for part in B if part.issubset(big) )) for big in A)) R = self.base_ring() return e._from_dict({B: R(coeff(B)) for B in A.refinements()}, remove_zeros=False) @cached_method def _h_to_p_on_basis(self, A): r""" Return `\mathbf{h}_A` in terms of the powersum basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{p}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: h = NCSym.h() sage: all(h(h._h_to_p_on_basis(A)) == h[A] for i in range(5) ....: for A in SetPartitions(i)) True """ p = self.realization_of().p() coeff = lambda B: abs( prod([(-1)**(i-1) * factorial(i-1) for i in B.shape()]) ) R = self.base_ring() return p._from_dict({B: R(coeff(B)) for B in A.refinements()}, remove_zeros=False) class Element(CombinatorialFreeModule.Element): """ An element in the homogeneous basis of `NCSym`. """ def omega(self): r""" Return the involution `\omega` applied to ``self``. The involution `\omega` on `NCSym` is defined by `\omega(\mathbf{h}_A) = \mathbf{e}_A`. OUTPUT: - an element in the basis ``self`` EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: h = NCSym.h() sage: e = NCSym.e() sage: elt = h[[1,3],[2]].omega(); elt 2*h{{1}, {2}, {3}} - h{{1, 3}, {2}} sage: elt.omega() h{{1, 3}, {2}} sage: e(elt) e{{1, 3}, {2}} """ P = self.parent() e = self.parent().realization_of().e() return P(e.sum_of_terms(self)) def to_symmetric_function(self): r""" The projection of ``self`` to the symmetric functions. Take a symmetric function in non-commuting variables expressed in the `\mathbf{h}` basis, and return the projection of expressed in the complete basis of symmetric functions. The map `\chi \colon NCSym \to Sym` is given by .. MATH:: \mathbf{h}_A \mapsto h_{\lambda(A)} \prod_i \lambda(A)_i! where `\lambda(A)` is the partition associated with `A` by taking the sizes of the parts. OUTPUT: - An element of the symmetric functions in the complete basis EXAMPLES:: sage: h = SymmetricFunctionsNonCommutingVariables(QQ).h() sage: h[[1,3],[2]].to_symmetric_function() 2*h[2, 1] sage: h[[1],[3],[2]].to_symmetric_function() h[1, 1, 1] """ h = SymmetricFunctions(self.parent().base_ring()).h() c = lambda la: prod(factorial(i) for i in la) return h.sum_of_terms((i.shape(), coeff*c(i.shape())) for (i, coeff) in self) h = homogeneous class powersum(NCSymBasis_abstract): r""" The Hopf algebra of symmetric functions in non-commuting variables in the powersum basis. The powersum basis is given by .. MATH:: \mathbf{p}_A = \sum_{A \leq B} \mathbf{m}_B, where we sum over all coarsenings of the set partition `A`. If we allow our variables to commute, then `\mathbf{p}_A` goes to the usual powersum symmetric function `p_{\lambda}` whose (integer) partition `\lambda` is the shape of `A`. EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: p = NCSym.p() sage: x = p.an_element()**2; x 4*p{} + 8*p{{1}} + 4*p{{1}, {2}} + 6*p{{1}, {2, 3}} + 12*p{{1, 2}} + 6*p{{1, 2}, {3}} + 9*p{{1, 2}, {3, 4}} sage: x.to_symmetric_function() 4*p[] + 8*p[1] + 4*p[1, 1] + 12*p[2] + 12*p[2, 1] + 9*p[2, 2] """ def __init__(self, NCSym): """ EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: TestSuite(NCSym.p()).run() """ CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='p', bracket=False, category=MultiplicativeNCSymBases(NCSym)) # Register coercions m = NCSym.m() self.module_morphism(self._p_to_m_on_basis, codomain=m, unitriangular="lower").register_as_coercion() m.module_morphism(m._m_to_p_on_basis, codomain=self, unitriangular="lower").register_as_coercion() x = NCSym.x() self.module_morphism(self._p_to_x_on_basis, codomain=x, unitriangular="upper").register_as_coercion() x.module_morphism(x._x_to_p_on_basis, codomain=self, unitriangular="upper").register_as_coercion() @cached_method def _p_to_m_on_basis(self, A): r""" Return `\mathbf{p}_A` in terms of the monomial basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{m}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: p = NCSym.p() sage: all(p(p._p_to_m_on_basis(A)) == p[A] for i in range(5) ....: for A in SetPartitions(i)) True """ m = self.realization_of().m() one = self.base_ring().one() return m._from_dict({B: one for B in A.coarsenings()}, remove_zeros=False) @cached_method def _p_to_e_on_basis(self, A): r""" Return `\mathbf{p}_A` in terms of the elementary basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{e}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: p = NCSym.p() sage: all(p(p._p_to_e_on_basis(A)) == p[A] for i in range(5) ....: for A in SetPartitions(i)) True """ e = self.realization_of().e() P_refine = Poset((A.refinements(), A.parent().lt)) c = prod((-1)**(i-1) * factorial(i-1) for i in A.shape()) R = self.base_ring() return e._from_dict({B: R(P_refine.moebius_function(B, A) / ZZ(c)) for B in P_refine}, remove_zeros=False) @cached_method def _p_to_h_on_basis(self, A): r""" Return `\mathbf{p}_A` in terms of the homogeneous basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{h}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: p = NCSym.p() sage: all(p(p._p_to_h_on_basis(A)) == p[A] for i in range(5) ....: for A in SetPartitions(i)) True """ h = self.realization_of().h() P_refine = Poset((A.refinements(), A.parent().lt)) c = abs(prod((-1)**(i-1) * factorial(i-1) for i in A.shape())) R = self.base_ring() return h._from_dict({B: R(P_refine.moebius_function(B, A) / ZZ(c)) for B in P_refine}, remove_zeros=False) @cached_method def _p_to_x_on_basis(self, A): r""" Return `\mathbf{p}_A` in terms of the `\mathbf{x}` basis. INPUT: - ``A`` -- a set partition OUTPUT: - An element of the `\mathbf{x}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: p = NCSym.p() sage: all(p(p._p_to_x_on_basis(A)) == p[A] for i in range(5) ....: for A in SetPartitions(i)) True """ x = self.realization_of().x() one = self.base_ring().one() return x._from_dict({B: one for B in A.refinements()}, remove_zeros=False) # Note that this is the same as the monomial coproduct_on_basis def coproduct_on_basis(self, A): r""" Return the coproduct of a monomial basis element. INPUT: - ``A`` -- a set partition OUTPUT: - The coproduct applied to the monomial symmetric function in non-commuting variables indexed by ``A`` expressed in the monomial basis. EXAMPLES:: sage: p = SymmetricFunctionsNonCommutingVariables(QQ).powersum() sage: p[[1, 3], [2]].coproduct() p{} # p{{1, 3}, {2}} + p{{1}} # p{{1, 2}} + p{{1, 2}} # p{{1}} + p{{1, 3}, {2}} # p{} sage: p.coproduct_on_basis(SetPartition([[1]])) p{} # p{{1}} + p{{1}} # p{} sage: p.coproduct_on_basis(SetPartition([])) p{} # p{} """ P = SetPartitions() # Handle corner cases if not A: return self.tensor_square().monomial(( P([]), P([]) )) if len(A) == 1: return self.tensor_square().sum_of_monomials([(P([]), A), (A, P([]))]) ell_set = list(range(1, len(A) + 1)) # +1 for indexing L = [[[], ell_set]] + list(SetPartitions(ell_set, 2)) def to_basis(S): if not S: return P([]) sub_parts = [list(A[i-1]) for i in S] # -1 for indexing mins = [min(p) for p in sub_parts] over_max = max([max(p) for p in sub_parts]) + 1 ret = [[] for _ in repeat(None, len(S))] cur = 1 while min(mins) != over_max: m = min(mins) i = mins.index(m) ret[i].append(cur) cur += 1 sub_parts[i].pop(sub_parts[i].index(m)) if sub_parts[i]: mins[i] = min(sub_parts[i]) else: mins[i] = over_max return P(ret) L1 = [(to_basis(S), to_basis(C)) for S,C in L] L2 = [(M, N) for N,M in L1] return self.tensor_square().sum_of_monomials(L1 + L2) def internal_coproduct_on_basis(self, A): r""" Return the internal coproduct of a powersum basis element. The internal coproduct is defined by .. MATH:: \Delta^{\odot}(\mathbf{p}_A) = \mathbf{p}_A \otimes \mathbf{p}_A INPUT: - ``A`` -- a set partition OUTPUT: - an element of the tensor square of ``self`` EXAMPLES:: sage: p = SymmetricFunctionsNonCommutingVariables(QQ).powersum() sage: p.internal_coproduct_on_basis(SetPartition([[1,3],[2]])) p{{1, 3}, {2}} # p{{1, 3}, {2}} """ return self.tensor_square().monomial((A, A)) def antipode_on_basis(self, A): r""" Return the result of the antipode applied to a powersum basis element. Let `A` be a set partition. The antipode given in [LM2011]_ is .. MATH:: S(\mathbf{p}_A) = \sum_{\gamma} (-1)^{\ell(\gamma)} \mathbf{p}_{\gamma[A]} where we sum over all ordered set partitions (i.e. set compositions) of `[\ell(A)]` and .. MATH:: \gamma[A] = A_{\gamma_1}^{\downarrow} | \cdots | A_{\gamma_{\ell(A)}}^{\downarrow} is the action of `\gamma` on `A` defined in :meth:`SetPartition.ordered_set_partition_action()`. INPUT: - ``A`` -- a set partition OUTPUT: - an element in the basis ``self`` EXAMPLES:: sage: p = SymmetricFunctionsNonCommutingVariables(QQ).powersum() sage: p.antipode_on_basis(SetPartition([[1], [2,3]])) p{{1, 2}, {3}} sage: p.antipode_on_basis(SetPartition([])) p{} sage: F = p[[1,3],[5],[2,4]].coproduct() sage: F.apply_multilinear_morphism(lambda x,y: x.antipode()*y) 0 """ P = SetPartitions() def action(gamma): cur = 1 ret = [] for S in gamma: sub_parts = [list(A[i - 1]) for i in S] # -1 for indexing mins = [min(p) for p in sub_parts] over_max = max([max(p) for p in sub_parts]) + 1 temp = [[] for _ in repeat(None, len(S))] while min(mins) != over_max: m = min(mins) i = mins.index(m) temp[i].append(cur) cur += 1 sub_parts[i].pop(sub_parts[i].index(m)) if sub_parts[i]: mins[i] = min(sub_parts[i]) else: mins[i] = over_max ret += temp return P(ret) return self.sum_of_terms( (A.ordered_set_partition_action(gamma), (-1)**len(gamma)) for gamma in OrderedSetPartitions(len(A)) ) def primitive(self, A, i=1): r""" Return the primitive associated to ``A`` in ``self``. Fix some `i \in S`. Let `A` be an atomic set partition of `S`, then the primitive `p(A)` given in [LM2011]_ is .. MATH:: p(A) = \sum_{\gamma} (-1)^{\ell(\gamma)-1} \mathbf{p}_{\gamma[A]} where we sum over all ordered set partitions of `[\ell(A)]` such that `i \in \gamma_1` and `\gamma[A]` is the action of `\gamma` on `A` defined in :meth:`SetPartition.ordered_set_partition_action()`. If `A` is not atomic, then `p(A) = 0`. .. SEEALSO:: :meth:`SetPartition.is_atomic` INPUT: - ``A`` -- a set partition - ``i`` -- (default: 1) index in the base set for ``A`` specifying which set of primitives this belongs to OUTPUT: - an element in the basis ``self`` EXAMPLES:: sage: p = SymmetricFunctionsNonCommutingVariables(QQ).powersum() sage: elt = p.primitive(SetPartition([[1,3], [2]])); elt -p{{1, 2}, {3}} + p{{1, 3}, {2}} sage: elt.coproduct() -p{} # p{{1, 2}, {3}} + p{} # p{{1, 3}, {2}} - p{{1, 2}, {3}} # p{} + p{{1, 3}, {2}} # p{} sage: p.primitive(SetPartition([[1], [2,3]])) 0 sage: p.primitive(SetPartition([])) p{} """ if not A: return self.one() A = SetPartitions()(A) # Make sure it's a set partition if not A.is_atomic(): return self.zero() return self.sum_of_terms( (A.ordered_set_partition_action(gamma), (-1)**(len(gamma)-1)) for gamma in OrderedSetPartitions(len(A)) if i in gamma[0] ) class Element(CombinatorialFreeModule.Element): """ An element in the powersum basis of `NCSym`. """ def to_symmetric_function(self): r""" The projection of ``self`` to the symmetric functions. Take a symmetric function in non-commuting variables expressed in the `\mathbf{p}` basis, and return the projection of expressed in the powersum basis of symmetric functions. The map `\chi \colon NCSym \to Sym` is given by .. MATH:: \mathbf{p}_A \mapsto p_{\lambda(A)} where `\lambda(A)` is the partition associated with `A` by taking the sizes of the parts. OUTPUT: - an element of symmetric functions in the power sum basis EXAMPLES:: sage: p = SymmetricFunctionsNonCommutingVariables(QQ).p() sage: p[[1,3],[2]].to_symmetric_function() p[2, 1] sage: p[[1],[3],[2]].to_symmetric_function() p[1, 1, 1] """ p = SymmetricFunctions(self.parent().base_ring()).p() return p.sum_of_terms((i.shape(), coeff) for (i, coeff) in self) p = powersum class coarse_powersum(NCSymBasis_abstract): r""" The Hopf algebra of symmetric functions in non-commuting variables in the `\mathbf{cp}` basis. This basis was defined in [BZ05]_ as .. MATH:: \mathbf{cp}_A = \sum_{A \leq_* B} \mathbf{m}_B, where we sum over all strict coarsenings of the set partition `A`. An alternative description of this basis was given in [BT13]_ as .. MATH:: \mathbf{cp}_A = \sum_{A \subseteq B} \mathbf{m}_B, where we sum over all set partitions whose arcs are a subset of the arcs of the set partition `A`. .. NOTE:: In [BZ05]_, this basis was denoted by `\mathbf{q}`. In [BT13]_, this basis was called the powersum basis and denoted by `p`. However it is a coarser basis than the usual powersum basis in the sense that it does not yield the usual powersum basis of the symmetric function under the natural map of letting the variables commute. EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: cp = NCSym.cp() sage: cp[[1,3],[2,4]]*cp[[1,2,3]] cp{{1, 3}, {2, 4}, {5, 6, 7}} sage: cp[[1,2],[3]].internal_coproduct() cp{{1, 2}, {3}} # cp{{1, 2}, {3}} sage: ps = SymmetricFunctions(NCSym.base_ring()).p() sage: ps(cp[[1,3],[2]].to_symmetric_function()) p[2, 1] - p[3] sage: ps(cp[[1,2],[3]].to_symmetric_function()) p[2, 1] """ def __init__(self, NCSym): """ EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: TestSuite(NCSym.cp()).run() """ CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='cp', bracket=False, category=MultiplicativeNCSymBases(NCSym)) # Register coercions m = NCSym.m() self.module_morphism(self._cp_to_m_on_basis, codomain=m, unitriangular="lower").register_as_coercion() m.module_morphism(m._m_to_cp_on_basis, codomain=self, unitriangular="lower").register_as_coercion() @cached_method def _cp_to_m_on_basis(self, A): r""" Return `\mathbf{cp}_A` in terms of the monomial basis. INPUT: - ``A`` -- a set partition OUTPUT: - an element of the `\mathbf{m}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: cp = NCSym.cp() sage: all(cp(cp._cp_to_m_on_basis(A)) == cp[A] for i in range(5) ....: for A in SetPartitions(i)) True """ m = self.realization_of().m() one = self.base_ring().one() return m._from_dict({B: one for B in A.strict_coarsenings()}, remove_zeros=False) cp = coarse_powersum class x_basis(NCSymBasis_abstract): r""" The Hopf algebra of symmetric functions in non-commuting variables in the `\mathbf{x}` basis. This basis is defined in [BHRZ06]_ by the formula: .. MATH:: \mathbf{x}_A = \sum_{B \leq A} \mu(B, A) \mathbf{p}_B and has the following properties: .. MATH:: \mathbf{x}_A \mathbf{x}_B = \mathbf{x}_{A|B}, \quad \quad \Delta^{\odot}(\mathbf{x}_C) = \sum_{A \vee B = C} \mathbf{x}_A \otimes \mathbf{x}_B. EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: x = NCSym.x() sage: x[[1,3],[2,4]]*x[[1,2,3]] x{{1, 3}, {2, 4}, {5, 6, 7}} sage: x[[1,2],[3]].internal_coproduct() x{{1}, {2}, {3}} # x{{1, 2}, {3}} + x{{1, 2}, {3}} # x{{1}, {2}, {3}} + x{{1, 2}, {3}} # x{{1, 2}, {3}} """ def __init__(self, NCSym): """ EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: TestSuite(NCSym.x()).run() """ CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='x', bracket=False, category=MultiplicativeNCSymBases(NCSym)) @cached_method def _x_to_p_on_basis(self, A): r""" Return `\mathbf{x}_A` in terms of the powersum basis. INPUT: - ``A`` -- a set partition OUTPUT: - an element of the `\mathbf{p}` basis TESTS:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: x = NCSym.x() sage: all(x(x._x_to_p_on_basis(A)) == x[A] for i in range(5) ....: for A in SetPartitions(i)) True """ def lt(s, t): if s == t: return False for p in s: if len([z for z in t if z.intersection(p)]) != 1: return False return True p = self.realization_of().p() P_refine = Poset((A.refinements(), lt)) R = self.base_ring() return p._from_dict({B: R(P_refine.moebius_function(B, A)) for B in P_refine}) x = x_basis class deformed_coarse_powersum(NCSymBasis_abstract): r""" The Hopf algebra of symmetric functions in non-commuting variables in the `\rho` basis. This basis was defined in [BT13]_ as a `q`-deformation of the `\mathbf{cp}` basis: .. MATH:: \rho_A = \sum_{A \subseteq B} \frac{1}{q^{\operatorname{nst}_{B-A}^A}} \mathbf{m}_B, where we sum over all set partitions whose arcs are a subset of the arcs of the set partition `A`. INPUT: - ``q`` -- (default: ``2``) the parameter `q` EXAMPLES:: sage: R = QQ['q'].fraction_field() sage: q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: rho = NCSym.rho(q) We construct Example 3.1 in [BT13]_:: sage: rnode = lambda A: sorted([a[1] for a in A.arcs()], reverse=True) sage: dimv = lambda A: sorted([a[1]-a[0] for a in A.arcs()], reverse=True) sage: lst = list(SetPartitions(4)) sage: S = sorted(lst, key=lambda A: (dimv(A), rnode(A))) sage: m = NCSym.m() sage: matrix([[m(rho[A])[B] for B in S] for A in S]) [ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] [ 0 1 0 0 1 1 0 1 0 0 1 0 0 0 0] [ 0 0 1 0 1 0 1 1 0 0 0 0 0 0 1] [ 0 0 0 1 0 1 1 1 0 0 0 1 0 0 0] [ 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0] [ 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0] [ 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0] [ 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1/q] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1] """ def __init__(self, NCSym, q=2): """ EXAMPLES:: sage: R = QQ['q'].fraction_field() sage: q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: TestSuite(NCSym.rho(q)).run() """ R = NCSym.base_ring() self._q = R(q) CombinatorialFreeModule.__init__(self, R, SetPartitions(), prefix='rho', bracket=False, category=MultiplicativeNCSymBases(NCSym)) # Register coercions m = NCSym.m() self.module_morphism(self._rho_to_m_on_basis, codomain=m).register_as_coercion() m.module_morphism(self._m_to_rho_on_basis, codomain=self).register_as_coercion() def q(self): """ Return the deformation parameter `q` of ``self``. EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: rho = NCSym.rho(5) sage: rho.q() 5 sage: R = QQ['q'].fraction_field() sage: q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: rho = NCSym.rho(q) sage: rho.q() == q True """ return self._q @cached_method def _rho_to_m_on_basis(self, A): r""" Return `\rho_A` in terms of the monomial basis. INPUT: - ``A`` -- a set partition OUTPUT: - an element of the `\mathbf{m}` basis TESTS:: sage: R = QQ['q'].fraction_field() sage: q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: rho = NCSym.rho(q) sage: all(rho(rho._rho_to_m_on_basis(A)) == rho[A] for i in range(5) ....: for A in SetPartitions(i)) True """ m = self.realization_of().m() arcs = set(A.arcs()) return m._from_dict({B: self._q**-nesting(set(B).difference(A), A) for B in A.coarsenings() if arcs.issubset(B.arcs())}, remove_zeros=False) @cached_method def _m_to_rho_on_basis(self, A): r""" Return `\mathbf{m}_A` in terms of the `\rho` basis. INPUT: - ``A`` -- a set partition OUTPUT: - an element of the `\rho` basis TESTS:: sage: R = QQ['q'].fraction_field() sage: q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: rho = NCSym.rho(q) sage: m = NCSym.m() sage: all(m(rho._m_to_rho_on_basis(A)) == m[A] for i in range(5) ....: for A in SetPartitions(i)) True """ coeff = lambda A,B: ((-1)**len(set(B.arcs()).difference(A.arcs())) / self._q**nesting(set(B).difference(A), B)) arcs = set(A.arcs()) return self._from_dict({B: coeff(A,B) for B in A.coarsenings() if arcs.issubset(B.arcs())}, remove_zeros=False) rho = deformed_coarse_powersum class supercharacter(NCSymBasis_abstract): r""" The Hopf algebra of symmetric functions in non-commuting variables in the supercharacter `\chi` basis. This basis was defined in [BT13]_ as a `q`-deformation of the supercharacter basis. .. MATH:: \chi_A = \sum_B \chi_A(B) \mathbf{m}_B, where we sum over all set partitions `A` and `\chi_A(B)` is the evaluation of the supercharacter `\chi_A` on the superclass `\mu_B`. .. NOTE:: The supercharacters considered in [BT13]_ are coarser than those considered by Aguiar et. al. INPUT: - ``q`` -- (default: ``2``) the parameter `q` EXAMPLES:: sage: R = QQ['q'].fraction_field() sage: q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: chi = NCSym.chi(q) sage: chi[[1,3],[2]]*chi[[1,2]] chi{{1, 3}, {2}, {4, 5}} sage: chi[[1,3],[2]].coproduct() chi{} # chi{{1, 3}, {2}} + (2*q-2)*chi{{1}} # chi{{1}, {2}} + (3*q-2)*chi{{1}} # chi{{1, 2}} + (2*q-2)*chi{{1}, {2}} # chi{{1}} + (3*q-2)*chi{{1, 2}} # chi{{1}} + chi{{1, 3}, {2}} # chi{} sage: chi2 = NCSym.chi() sage: chi(chi2[[1,2],[3]]) ((-q+2)/q)*chi{{1}, {2}, {3}} + 2/q*chi{{1, 2}, {3}} sage: chi2 Symmetric functions in non-commuting variables over the Fraction Field of Univariate Polynomial Ring in q over Rational Field in the supercharacter basis with parameter q=2 """ def __init__(self, NCSym, q=2): """ EXAMPLES:: sage: R = QQ['q'].fraction_field() sage: q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: TestSuite(NCSym.chi(q)).run() """ R = NCSym.base_ring() self._q = R(q) CombinatorialFreeModule.__init__(self, R, SetPartitions(), prefix='chi', bracket=False, category=MultiplicativeNCSymBases(NCSym)) # Register coercions m = NCSym.m() self.module_morphism(self._chi_to_m_on_basis, codomain=m).register_as_coercion() m.module_morphism(self._m_to_chi_on_basis, codomain=self).register_as_coercion() def q(self): """ Return the deformation parameter `q` of ``self``. EXAMPLES:: sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ) sage: chi = NCSym.chi(5) sage: chi.q() 5 sage: R = QQ['q'].fraction_field() sage: q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: chi = NCSym.chi(q) sage: chi.q() == q True """ return self._q @cached_method def _chi_to_m_on_basis(self, A): r""" Return `\chi_A` in terms of the monomial basis. INPUT: - ``A`` -- a set partition OUTPUT: - an element of the `\mathbf{m}` basis TESTS:: sage: R = QQ['q'].fraction_field() sage: q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: chi = NCSym.chi(q) sage: all(chi(chi._chi_to_m_on_basis(A)) == chi[A] for i in range(5) ....: for A in SetPartitions(i)) True """ m = self.realization_of().m() q = self._q arcs = set(A.arcs()) ret = {} for B in SetPartitions(A.size()): Barcs = B.arcs() if any((a[0] == b[0] and b[1] < a[1]) or (b[0] > a[0] and a[1] == b[1]) for a in arcs for b in Barcs): continue ret[B] = ((-1)**len(arcs.intersection(Barcs)) * (q - 1)**(len(arcs) - len(arcs.intersection(Barcs))) * q**(sum(a[1] - a[0] for a in arcs) - len(arcs)) / q**nesting(B, A)) return m._from_dict(ret, remove_zeros=False) @cached_method def _graded_inverse_matrix(self, n): r""" Return the inverse of the transition matrix of the ``n``-th graded part from the `\chi` basis to the monomial basis. EXAMPLES:: sage: R = QQ['q'].fraction_field(); q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: chi = NCSym.chi(q); m = NCSym.m() sage: lst = list(SetPartitions(2)) sage: m = matrix([[m(chi[A])[B] for A in lst] for B in lst]); m [ -1 1] [q - 1 1] sage: chi._graded_inverse_matrix(2) [ -1/q 1/q] [(q - 1)/q 1/q] sage: chi._graded_inverse_matrix(2) * m [1 0] [0 1] """ lst = SetPartitions(n) MS = MatrixSpace(self.base_ring(), lst.cardinality()) m = self.realization_of().m() m = MS([[m(self[A])[B] for A in lst] for B in lst]) return ~m @cached_method def _m_to_chi_on_basis(self, A): r""" Return `\mathbf{m}_A` in terms of the `\chi` basis. INPUT: - ``A`` -- a set partition OUTPUT: - an element of the `\chi` basis TESTS:: sage: R = QQ['q'].fraction_field() sage: q = R.gen() sage: NCSym = SymmetricFunctionsNonCommutingVariables(R) sage: chi = NCSym.chi(q) sage: m = NCSym.m() sage: all(m(chi._m_to_chi_on_basis(A)) == m[A] for i in range(5) ....: for A in SetPartitions(i)) True """ n = A.size() lst = list(SetPartitions(n)) m = self._graded_inverse_matrix(n) i = lst.index(A) return self._from_dict({B: m[j,i] for j,B in enumerate(lst)}) chi = supercharacter
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/ncsym/ncsym.py
0.708616
0.595581
ncsym.py
pypi
from sage.misc.lazy_attribute import lazy_attribute from sage.misc.misc_c import prod from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.categories.graded_hopf_algebras import GradedHopfAlgebras from sage.categories.rings import Rings from sage.categories.fields import Fields from sage.combinat.ncsym.bases import NCSymDualBases, NCSymBasis_abstract from sage.combinat.partition import Partition from sage.combinat.set_partition import SetPartitions from sage.combinat.free_module import CombinatorialFreeModule from sage.combinat.sf.sf import SymmetricFunctions from sage.combinat.subset import Subsets from sage.arith.misc import factorial from sage.sets.set import Set class SymmetricFunctionsNonCommutingVariablesDual(UniqueRepresentation, Parent): r""" The Hopf dual to the symmetric functions in non-commuting variables. See Section 2.3 of [BZ05]_ for a study. """ def __init__(self, R): """ Initialize ``self``. EXAMPLES:: sage: NCSymD1 = SymmetricFunctionsNonCommutingVariablesDual(FiniteField(23)) sage: NCSymD2 = SymmetricFunctionsNonCommutingVariablesDual(Integers(23)) sage: TestSuite(SymmetricFunctionsNonCommutingVariables(QQ).dual()).run() """ # change the line below to assert(R in Rings()) once MRO issues from #15536, #15475 are resolved assert(R in Fields() or R in Rings()) # side effect of this statement assures MRO exists for R self._base = R # Won't be needed once CategoryObject won't override base_ring category = GradedHopfAlgebras(R) # TODO: .Commutative() Parent.__init__(self, category=category.WithRealizations()) # Bases w = self.w() # Embedding of Sym in the homogeneous bases into DNCSym in the w basis Sym = SymmetricFunctions(self.base_ring()) Sym_h_to_w = Sym.h().module_morphism(w.sum_of_partitions, triangular='lower', inverse_on_support=w._set_par_to_par, codomain=w, category=category) Sym_h_to_w.register_as_coercion() self.to_symmetric_function = Sym_h_to_w.section() def _repr_(self): r""" EXAMPLES:: sage: SymmetricFunctionsNonCommutingVariables(ZZ).dual() Dual symmetric functions in non-commuting variables over the Integer Ring """ return "Dual symmetric functions in non-commuting variables over the %s" % self.base_ring() def a_realization(self): r""" Return the realization of the `\mathbf{w}` basis of ``self``. EXAMPLES:: sage: SymmetricFunctionsNonCommutingVariables(QQ).dual().a_realization() Dual symmetric functions in non-commuting variables over the Rational Field in the w basis """ return self.w() _shorthands = tuple(['w']) def dual(self): r""" Return the dual Hopf algebra of the dual symmetric functions in non-commuting variables. EXAMPLES:: sage: NCSymD = SymmetricFunctionsNonCommutingVariables(QQ).dual() sage: NCSymD.dual() Symmetric functions in non-commuting variables over the Rational Field """ from sage.combinat.ncsym.ncsym import SymmetricFunctionsNonCommutingVariables return SymmetricFunctionsNonCommutingVariables(self.base_ring()) class w(NCSymBasis_abstract): r""" The Hopf algebra of symmetric functions in non-commuting variables in the `\mathbf{w}` basis. EXAMPLES:: sage: NCSymD = SymmetricFunctionsNonCommutingVariables(QQ).dual() sage: w = NCSymD.w() We have the embedding `\chi^*` of `Sym` into `NCSym^*` available as a coercion:: sage: h = SymmetricFunctions(QQ).h() sage: w(h[2,1]) w{{1}, {2, 3}} + w{{1, 2}, {3}} + w{{1, 3}, {2}} Similarly we can pull back when we are in the image of `\chi^*`:: sage: elt = 3*(w[[1],[2,3]] + w[[1,2],[3]] + w[[1,3],[2]]) sage: h(elt) 3*h[2, 1] """ def __init__(self, NCSymD): """ EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: TestSuite(w).run() """ def key_func_set_part(A): return sorted(map(sorted, A)) CombinatorialFreeModule.__init__(self, NCSymD.base_ring(), SetPartitions(), prefix='w', bracket=False, sorting_key=key_func_set_part, category=NCSymDualBases(NCSymD)) @lazy_attribute def to_symmetric_function(self): r""" The preimage of `\chi^*` in the `\mathbf{w}` basis. EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: w.to_symmetric_function Generic morphism: From: Dual symmetric functions in non-commuting variables over the Rational Field in the w basis To: Symmetric Functions over Rational Field in the homogeneous basis """ return self.realization_of().to_symmetric_function def dual_basis(self): r""" Return the dual basis to the `\mathbf{w}` basis. The dual basis to the `\mathbf{w}` basis is the monomial basis of the symmetric functions in non-commuting variables. OUTPUT: - the monomial basis of the symmetric functions in non-commuting variables EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: w.dual_basis() Symmetric functions in non-commuting variables over the Rational Field in the monomial basis """ return self.realization_of().dual().m() def product_on_basis(self, A, B): r""" The product on `\mathbf{w}` basis elements. The product on the `\mathbf{w}` is the dual to the coproduct on the `\mathbf{m}` basis. On the basis `\mathbf{w}` it is defined as .. MATH:: \mathbf{w}_A \mathbf{w}_B = \sum_{S \subseteq [n]} \mathbf{w}_{A\uparrow_S \cup B\uparrow_{S^c}} where the sum is over all possible subsets `S` of `[n]` such that `|S| = |A|` with a term indexed the union of `A \uparrow_S` and `B \uparrow_{S^c}`. The notation `A \uparrow_S` represents the unique set partition of the set `S` such that the standardization is `A`. This product is commutative. INPUT: - ``A``, ``B`` -- set partitions OUTPUT: - an element of the `\mathbf{w}` basis EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: A = SetPartition([[1], [2,3]]) sage: B = SetPartition([[1, 2, 3]]) sage: w.product_on_basis(A, B) w{{1}, {2, 3}, {4, 5, 6}} + w{{1}, {2, 3, 4}, {5, 6}} + w{{1}, {2, 3, 5}, {4, 6}} + w{{1}, {2, 3, 6}, {4, 5}} + w{{1}, {2, 4}, {3, 5, 6}} + w{{1}, {2, 4, 5}, {3, 6}} + w{{1}, {2, 4, 6}, {3, 5}} + w{{1}, {2, 5}, {3, 4, 6}} + w{{1}, {2, 5, 6}, {3, 4}} + w{{1}, {2, 6}, {3, 4, 5}} + w{{1, 2, 3}, {4}, {5, 6}} + w{{1, 2, 4}, {3}, {5, 6}} + w{{1, 2, 5}, {3}, {4, 6}} + w{{1, 2, 6}, {3}, {4, 5}} + w{{1, 3, 4}, {2}, {5, 6}} + w{{1, 3, 5}, {2}, {4, 6}} + w{{1, 3, 6}, {2}, {4, 5}} + w{{1, 4, 5}, {2}, {3, 6}} + w{{1, 4, 6}, {2}, {3, 5}} + w{{1, 5, 6}, {2}, {3, 4}} sage: B = SetPartition([[1], [2]]) sage: w.product_on_basis(A, B) 3*w{{1}, {2}, {3}, {4, 5}} + 2*w{{1}, {2}, {3, 4}, {5}} + 2*w{{1}, {2}, {3, 5}, {4}} + w{{1}, {2, 3}, {4}, {5}} + w{{1}, {2, 4}, {3}, {5}} + w{{1}, {2, 5}, {3}, {4}} sage: w.product_on_basis(A, SetPartition([])) w{{1}, {2, 3}} """ if len(A) == 0: return self.monomial(B) if len(B) == 0: return self.monomial(A) P = SetPartitions() n = A.size() k = B.size() def unions(s): a = sorted(s) b = sorted(Set(range(1, n+k+1)).difference(s)) # -1 for indexing ret = [[a[i-1] for i in sorted(part)] for part in A] ret += [[b[i-1] for i in sorted(part)] for part in B] return P(ret) return self.sum_of_terms([(unions(s), 1) for s in Subsets(n+k, n)]) def coproduct_on_basis(self, A): r""" Return the coproduct of a `\mathbf{w}` basis element. The coproduct on the basis element `\mathbf{w}_A` is the sum over tensor product terms `\mathbf{w}_B \otimes \mathbf{w}_C` where `B` is the restriction of `A` to `\{1,2,\ldots,k\}` and `C` is the restriction of `A` to `\{k+1, k+2, \ldots, n\}`. INPUT: - ``A`` -- a set partition OUTPUT: - The coproduct applied to the `\mathbf{w}` dual symmetric function in non-commuting variables indexed by ``A`` expressed in the `\mathbf{w}` basis. EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: w[[1], [2,3]].coproduct() w{} # w{{1}, {2, 3}} + w{{1}} # w{{1, 2}} + w{{1}, {2}} # w{{1}} + w{{1}, {2, 3}} # w{} sage: w.coproduct_on_basis(SetPartition([])) w{} # w{} """ n = A.size() return self.tensor_square().sum_of_terms([ (( A.restriction(range(1, i+1)).standardization(), A.restriction(range(i+1, n+1)).standardization() ), 1) for i in range(n+1)], distinct=True) def antipode_on_basis(self, A): r""" Return the antipode applied to the basis element indexed by ``A``. INPUT: - ``A`` -- a set partition OUTPUT: - an element in the basis ``self`` EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: w.antipode_on_basis(SetPartition([[1],[2,3]])) -3*w{{1}, {2}, {3}} + w{{1, 2}, {3}} + w{{1, 3}, {2}} sage: F = w[[1,3],[5],[2,4]].coproduct() sage: F.apply_multilinear_morphism(lambda x,y: x.antipode()*y) 0 """ if A.size() == 0: return self.one() if A.size() == 1: return -self(A) cpr = self.coproduct_on_basis(A) return -sum( c*self.monomial(B1)*self.antipode_on_basis(B2) for ((B1,B2),c) in cpr if B2 != A ) def duality_pairing(self, x, y): r""" Compute the pairing between an element of ``self`` and an element of the dual. INPUT: - ``x`` -- an element of the dual of symmetric functions in non-commuting variables - ``y`` -- an element of the symmetric functions in non-commuting variables OUTPUT: - an element of the base ring of ``self`` EXAMPLES:: sage: DNCSym = SymmetricFunctionsNonCommutingVariablesDual(QQ) sage: w = DNCSym.w() sage: m = w.dual_basis() sage: matrix([[w(A).duality_pairing(m(B)) for A in SetPartitions(3)] for B in SetPartitions(3)]) [1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0 0 1 0] [0 0 0 0 1] sage: (w[[1,2],[3]] + 3*w[[1,3],[2]]).duality_pairing(2*m[[1,3],[2]] + m[[1,2,3]] + 2*m[[1,2],[3]]) 8 sage: h = SymmetricFunctionsNonCommutingVariables(QQ).h() sage: matrix([[w(A).duality_pairing(h(B)) for A in SetPartitions(3)] for B in SetPartitions(3)]) [6 2 2 2 1] [2 2 1 1 1] [2 1 2 1 1] [2 1 1 2 1] [1 1 1 1 1] sage: (2*w[[1,3],[2]] + w[[1,2,3]] + 2*w[[1,2],[3]]).duality_pairing(h[[1,2],[3]] + 3*h[[1,3],[2]]) 32 """ x = self(x) y = self.dual_basis()(y) return sum(coeff * y[I] for (I, coeff) in x) def sum_of_partitions(self, la): r""" Return the sum over all sets partitions whose shape is ``la``, scaled by `\prod_i m_i!` where `m_i` is the multiplicity of `i` in ``la``. INPUT: - ``la`` -- an integer partition OUTPUT: - an element of ``self`` EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: w.sum_of_partitions([2,1,1]) 2*w{{1}, {2}, {3, 4}} + 2*w{{1}, {2, 3}, {4}} + 2*w{{1}, {2, 4}, {3}} + 2*w{{1, 2}, {3}, {4}} + 2*w{{1, 3}, {2}, {4}} + 2*w{{1, 4}, {2}, {3}} """ la = Partition(la) c = prod([factorial(i) for i in la.to_exp()]) P = SetPartitions() return self.sum_of_terms([(P(m), c) for m in SetPartitions(sum(la), la)], distinct=True) def _set_par_to_par(self, A): r""" Return the shape of ``A`` if ``A`` is the canonical standard set partition `A_1 | A_2 | \cdots | A_k` where `|` is the pipe operation (see :meth:`~sage.combinat.set_partition.SetPartition.pipe()` ) and `A_i = [\lambda_i]` where `\lambda_1 \leq \lambda_2 \leq \cdots \leq \lambda_k`. Otherwise, return ``None``. This is the trailing term of `h_{\lambda}` mapped by `\chi` to the `\mathbf{w}` basis and is used by the coercion framework to construct the preimage `\chi^{-1}`. INPUT: - ``A`` -- a set partition EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: w._set_par_to_par(SetPartition([[1], [2], [3,4,5]])) [3, 1, 1] sage: w._set_par_to_par(SetPartition([[1,2,3],[4],[5]])) sage: w._set_par_to_par(SetPartition([[1],[2,3,4],[5]])) sage: w._set_par_to_par(SetPartition([[1],[2,3,5],[4]])) TESTS: This is used in the coercion between `\mathbf{w}` and the homogeneous symmetric functions. :: sage: w = SymmetricFunctionsNonCommutingVariablesDual(QQ).w() sage: h = SymmetricFunctions(QQ).h() sage: h(w[[1,3],[2]]) Traceback (most recent call last): ... ValueError: w{{1, 3}, {2}} is not in the image sage: h(w(h[2,1])) == w(h[2,1]).to_symmetric_function() True """ cur = 1 prev_len = 0 for p in A: if prev_len > len(p) or list(p) != list(range(cur, cur+len(p))): return None prev_len = len(p) cur += len(p) return A.shape() class Element(CombinatorialFreeModule.Element): r""" An element in the `\mathbf{w}` basis. """ def expand(self, n, letter='x'): r""" Expand ``self`` written in the `\mathbf{w}` basis in `n^2` commuting variables which satisfy the relation `x_{ij} x_{ik} = 0` for all `i`, `j`, and `k`. The expansion of an element of the `\mathbf{w}` basis is given by equations (26) and (55) in [HNT06]_. INPUT: - ``n`` -- an integer - ``letter`` -- (default: ``'x'``) a string OUTPUT: - The symmetric function of ``self`` expressed in the ``n*n`` non-commuting variables described by ``letter``. REFERENCES: .. [HNT06] \F. Hivert, J.-C. Novelli, J.-Y. Thibon. *Commutative combinatorial Hopf algebras*. (2006). :arxiv:`0605262v1`. EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: w[[1,3],[2]].expand(4) x02*x11*x20 + x03*x11*x30 + x03*x22*x30 + x13*x22*x31 One can use a different set of variable by using the optional argument ``letter``:: sage: w[[1,3],[2]].expand(3, letter='y') y02*y11*y20 """ from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.combinat.permutation import Permutations m = self.parent() names = ['{}{}{}'.format(letter, i, j) for i in range(n) for j in range(n)] R = PolynomialRing(m.base_ring(), n*n, names) x = [[R.gens()[i*n+j] for j in range(n)] for i in range(n)] I = R.ideal([x[i][j]*x[i][k] for j in range(n) for k in range(n) for i in range(n)]) Q = R.quotient(I, names) x = [[Q.gens()[i*n+j] for j in range(n)] for i in range(n)] P = SetPartitions() def on_basis(A): k = A.size() ret = R.zero() if n < k: return ret for p in Permutations(k): if P(p.to_cycles()) == A: # -1 for indexing ret += R.sum(prod(x[I[i]][I[p[i]-1]] for i in range(k)) for I in Subsets(range(n), k)) return ret return m._apply_module_morphism(self, on_basis, codomain=R) def is_symmetric(self): r""" Determine if a `NCSym^*` function, expressed in the `\mathbf{w}` basis, is symmetric. A function `f` in the `\mathbf{w}` basis is a symmetric function if it is in the image of `\chi^*`. That is to say we have .. MATH:: f = \sum_{\lambda} c_{\lambda} \prod_i m_i(\lambda)! \sum_{\lambda(A) = \lambda} \mathbf{w}_A where the second sum is over all set partitions `A` whose shape `\lambda(A)` is equal to `\lambda` and `m_i(\mu)` is the multiplicity of `i` in the partition `\mu`. OUTPUT: - ``True`` if `\lambda(A)=\lambda(B)` implies the coefficients of `\mathbf{w}_A` and `\mathbf{w}_B` are equal, ``False`` otherwise EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: elt = w.sum_of_partitions([2,1,1]) sage: elt.is_symmetric() True sage: elt -= 3*w.sum_of_partitions([1,1]) sage: elt.is_symmetric() True sage: w = SymmetricFunctionsNonCommutingVariables(ZZ).dual().w() sage: elt = w.sum_of_partitions([2,1,1]) / 2 sage: elt.is_symmetric() False sage: elt = w[[1,3],[2]] sage: elt.is_symmetric() False sage: elt = w[[1],[2,3]] + w[[1,2],[3]] + 2*w[[1,3],[2]] sage: elt.is_symmetric() False """ d = {} R = self.base_ring() for A, coeff in self: la = A.shape() exp = prod([factorial(i) for i in la.to_exp()]) if la not in d: if coeff / exp not in R: return False d[la] = [coeff, 1] else: if d[la][0] != coeff: return False d[la][1] += 1 # Make sure we've seen each set partition of the shape return all(d[la][1] == SetPartitions(la.size(), la).cardinality() for la in d) def to_symmetric_function(self): r""" Take a function in the `\mathbf{w}` basis, and return its symmetric realization, when possible, expressed in the homogeneous basis of symmetric functions. OUTPUT: - If ``self`` is a symmetric function, then the expansion in the homogeneous basis of the symmetric functions is returned. Otherwise an error is raised. EXAMPLES:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: elt = w[[1],[2,3]] + w[[1,2],[3]] + w[[1,3],[2]] sage: elt.to_symmetric_function() h[2, 1] sage: elt = w.sum_of_partitions([2,1,1]) / 2 sage: elt.to_symmetric_function() 1/2*h[2, 1, 1] TESTS:: sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w() sage: w(0).to_symmetric_function() 0 sage: w([]).to_symmetric_function() h[] sage: (2*w([])).to_symmetric_function() 2*h[] """ if not self.is_symmetric(): raise ValueError("not a symmetric function") h = SymmetricFunctions(self.parent().base_ring()).homogeneous() d = {A.shape(): c for A, c in self} return h.sum_of_terms([( AA, cc / prod([factorial(i) for i in AA.to_exp()]) ) for AA, cc in d.items()], distinct=True)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/ncsym/dual.py
0.77535
0.600071
dual.py
pypi
from .cartan_type import CartanType_standard_finite from sage.combinat.root_system.root_system import RootSystem class CartanType(CartanType_standard_finite): """ Cartan Type `Q_n` .. SEEALSO:: :func:`~sage.combinat.root_systems.cartan_type.CartanType` """ def __init__(self, m): """ EXAMPLES:: sage: ct = CartanType(['Q',4]) sage: ct ['Q', 4] sage: ct._repr_(compact = True) 'Q4' sage: ct.is_irreducible() True sage: ct.is_finite() True sage: ct.is_affine() False sage: ct.is_simply_laced() True sage: ct.dual() ['Q', 4] TESTS:: sage: TestSuite(ct).run() """ assert m >= 2 CartanType_standard_finite.__init__(self, "Q", m-1) def _repr_(self, compact = False): """ TESTS:: sage: ct = CartanType(['Q',4]) sage: repr(ct) "['Q', 4]" sage: ct._repr_(compact=True) 'Q4' """ format = '%s%s' if compact else "['%s', %s]" return format%(self.letter, self.n+1) def __reduce__(self): """ TESTS:: sage: T = CartanType(['Q', 4]) sage: T.__reduce__() (CartanType, ('Q', 4)) sage: T == loads(dumps(T)) True """ from .cartan_type import CartanType return (CartanType, (self.letter, self.n+1)) def index_set(self): r""" Return the index set for Cartan type Q. The index set for type Q is of the form `\{-n, \ldots, -1, 1, \ldots, n\}`. EXAMPLES:: sage: CartanType(['Q', 3]).index_set() (1, 2, -2, -1) """ return tuple(list(range(1, self.n + 1)) + list(range(-self.n, 0))) def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['Q',4])) Q_{4} """ return "Q_{%s}" % (self.n + 1) def root_system(self): """ Return the root system of ``self``. EXAMPLES:: sage: Q = CartanType(['Q',3]) sage: Q.root_system() Root system of type ['A', 2] """ return RootSystem(['A',self.n]) def is_irreducible(self): """ Return whether this Cartan type is irreducible. EXAMPLES:: sage: Q = CartanType(['Q',3]) sage: Q.is_irreducible() True """ return True def is_simply_laced(self): """ Return whether this Cartan type is simply-laced. EXAMPLES:: sage: Q = CartanType(['Q',3]) sage: Q.is_simply_laced() True """ return True def dual(self): """ Return dual of ``self``. EXAMPLES:: sage: Q = CartanType(['Q',3]) sage: Q.dual() ['Q', 3] """ return self
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_Q.py
0.895111
0.571348
type_Q.py
pypi
from sage.misc.cachefunc import cached_method from sage.sets.family import Family from sage.combinat.free_module import CombinatorialFreeModule from .weight_lattice_realizations import WeightLatticeRealizations import functools class WeightSpace(CombinatorialFreeModule): r""" INPUT: - ``root_system`` -- a root system - ``base_ring`` -- a ring `R` - ``extended`` -- a boolean (default: False) The weight space (or lattice if ``base_ring`` is `\ZZ`) of a root system is the formal free module `\bigoplus_i R \Lambda_i` generated by the fundamental weights `(\Lambda_i)_{i\in I}` of the root system. This class is also used for coweight spaces (or lattices). .. SEEALSO:: - :meth:`RootSystem` - :meth:`RootSystem.weight_lattice` and :meth:`RootSystem.weight_space` - :meth:`~sage.combinat.root_system.weight_lattice_realizations.WeightLatticeRealizations` EXAMPLES:: sage: Q = RootSystem(['A', 3]).weight_lattice(); Q Weight lattice of the Root system of type ['A', 3] sage: Q.simple_roots() Finite family {1: 2*Lambda[1] - Lambda[2], 2: -Lambda[1] + 2*Lambda[2] - Lambda[3], 3: -Lambda[2] + 2*Lambda[3]} sage: Q = RootSystem(['A', 3, 1]).weight_lattice(); Q Weight lattice of the Root system of type ['A', 3, 1] sage: Q.simple_roots() Finite family {0: 2*Lambda[0] - Lambda[1] - Lambda[3], 1: -Lambda[0] + 2*Lambda[1] - Lambda[2], 2: -Lambda[1] + 2*Lambda[2] - Lambda[3], 3: -Lambda[0] - Lambda[2] + 2*Lambda[3]} For infinite types, the Cartan matrix is singular, and therefore the embedding of the root lattice is not faithful:: sage: sum(Q.simple_roots()) 0 In particular, the null root is zero:: sage: Q.null_root() 0 This can be compensated by extending the basis of the weight space and slightly deforming the simple roots to make them linearly independent, without affecting the scalar product with the coroots. This feature is currently only implemented for affine types. In that case, if ``extended`` is set, then the basis of the weight space is extended by an element `\delta`:: sage: Q = RootSystem(['A', 3, 1]).weight_lattice(extended = True); Q Extended weight lattice of the Root system of type ['A', 3, 1] sage: Q.basis().keys() {0, 1, 2, 3, 'delta'} And the simple root `\alpha_0` associated to the special node is deformed as follows:: sage: Q.simple_roots() Finite family {0: 2*Lambda[0] - Lambda[1] - Lambda[3] + delta, 1: -Lambda[0] + 2*Lambda[1] - Lambda[2], 2: -Lambda[1] + 2*Lambda[2] - Lambda[3], 3: -Lambda[0] - Lambda[2] + 2*Lambda[3]} Now, the null root is nonzero:: sage: Q.null_root() delta .. WARNING:: By a slight notational abuse, the extra basis element used to extend the fundamental weights is called ``\delta`` in the current implementation. However, in the literature, ``\delta`` usually denotes instead the null root. Most of the time, those two objects coincide, but not for type `BC` (aka. `A_{2n}^{(2)}`). Therefore we currently have:: sage: Q = RootSystem(["A",4,2]).weight_lattice(extended=True) sage: Q.simple_root(0) 2*Lambda[0] - Lambda[1] + delta sage: Q.null_root() 2*delta whereas, with the standard notations from the literature, one would expect to get respectively `2\Lambda_0 -\Lambda_1 +1/2 \delta` and `\delta`. Other than this notational glitch, the implementation remains correct for type `BC`. The notations may get improved in a subsequent version, which might require changing the index of the extra basis element. To guarantee backward compatibility in code not included in Sage, it is recommended to use the following idiom to get that index:: sage: F = Q.basis_extension(); F Finite family {'delta': delta} sage: index = F.keys()[0]; index 'delta' Then, for example, the coefficient of an element of the extended weight lattice on that basis element can be recovered with:: sage: Q.null_root()[index] 2 TESTS:: sage: for ct in CartanType.samples(crystallographic=True)+[CartanType(["A",2],["C",5,1])]: ....: TestSuite(ct.root_system().weight_lattice()).run() ....: TestSuite(ct.root_system().weight_space()).run() sage: for ct in CartanType.samples(affine=True): ....: if ct.is_implemented(): ....: P = ct.root_system().weight_space(extended=True) ....: TestSuite(P).run() """ @staticmethod def __classcall_private__(cls, root_system, base_ring, extended=False): """ Guarantees Unique representation .. SEEALSO:: :class:`UniqueRepresentation` TESTS:: sage: R = RootSystem(['A',4]) sage: from sage.combinat.root_system.weight_space import WeightSpace sage: WeightSpace(R, QQ) is WeightSpace(R, QQ, False) True """ return super().__classcall__(cls, root_system, base_ring, extended) def __init__(self, root_system, base_ring, extended): """ TESTS:: sage: R = RootSystem(['A',4]) sage: from sage.combinat.root_system.weight_space import WeightSpace sage: Q = WeightSpace(R, QQ); Q Weight space over the Rational Field of the Root system of type ['A', 4] sage: TestSuite(Q).run() sage: WeightSpace(R, QQ, extended = True) Traceback (most recent call last): ... ValueError: extended weight lattices are only implemented for affine root systems """ basis_keys = root_system.index_set() self._extended = extended if extended: if not root_system.cartan_type().is_affine(): raise ValueError("extended weight lattices are only" " implemented for affine root systems") basis_keys = tuple(basis_keys) + ("delta",) def sortkey(x): return (1 if isinstance(x, str) else 0, x) else: def sortkey(x): return x self.root_system = root_system CombinatorialFreeModule.__init__(self, base_ring, basis_keys, prefix = "Lambdacheck" if root_system.dual_side else "Lambda", latex_prefix = "\\Lambda^\\vee" if root_system.dual_side else "\\Lambda", sorting_key=sortkey, category = WeightLatticeRealizations(base_ring)) if root_system.cartan_type().is_affine() and not extended: # For an affine type, register the quotient map from the # extended weight lattice/space to the weight lattice/space domain = root_system.weight_space(base_ring, extended=True) domain.module_morphism(self.fundamental_weight, codomain = self ).register_as_coercion() def is_extended(self): """ Return whether this is an extended weight lattice. .. SEEALSO:: :meth:`~sage.combinat.root_system.weight_lattice_realization.ParentMethods.is_extended` EXAMPLES:: sage: RootSystem(["A",3,1]).weight_lattice().is_extended() False sage: RootSystem(["A",3,1]).weight_lattice(extended=True).is_extended() True """ return self._extended def _repr_(self): """ TESTS:: sage: RootSystem(['A',4]).weight_lattice() # indirect doctest Weight lattice of the Root system of type ['A', 4] sage: RootSystem(['B',4]).weight_space() Weight space over the Rational Field of the Root system of type ['B', 4] sage: RootSystem(['A',4]).coweight_lattice() Coweight lattice of the Root system of type ['A', 4] sage: RootSystem(['B',4]).coweight_space() Coweight space over the Rational Field of the Root system of type ['B', 4] """ return self._name_string() def _name_string(self, capitalize=True, base_ring=True, type=True): """ EXAMPLES:: sage: RootSystem(['A',4]).weight_lattice()._name_string() "Weight lattice of the Root system of type ['A', 4]" """ return self._name_string_helper("weight", capitalize=capitalize, base_ring=base_ring, type=type, prefix="extended " if self.is_extended() else "") @cached_method def fundamental_weight(self, i): r""" Returns the `i`-th fundamental weight INPUT: - ``i`` -- an element of the index set or ``"delta"`` By a slight notational abuse, for an affine type this method also accepts ``"delta"`` as input, and returns the image of `\delta` of the extended weight lattice in this realization. .. SEEALSO:: :meth:`~sage.combinat.root_system.weight_lattice_realization.ParentMethods.fundamental_weight` EXAMPLES:: sage: Q = RootSystem(["A",3]).weight_lattice() sage: Q.fundamental_weight(1) Lambda[1] sage: Q = RootSystem(["A",3,1]).weight_lattice(extended=True) sage: Q.fundamental_weight(1) Lambda[1] sage: Q.fundamental_weight("delta") delta """ if i == "delta": if not self.cartan_type().is_affine(): raise ValueError("delta is only defined for affine weight spaces") if self.is_extended(): return self.monomial(i) else: return self.zero() else: if i not in self.index_set(): raise ValueError("{} is not in the index set".format(i)) return self.monomial(i) @cached_method def basis_extension(self): r""" Return the basis elements used to extend the fundamental weights EXAMPLES:: sage: Q = RootSystem(["A",3,1]).weight_lattice() sage: Q.basis_extension() Family () sage: Q = RootSystem(["A",3,1]).weight_lattice(extended=True) sage: Q.basis_extension() Finite family {'delta': delta} This method is irrelevant for finite types:: sage: Q = RootSystem(["A",3]).weight_lattice() sage: Q.basis_extension() Family () """ if self.is_extended(): return Family(["delta"], self.monomial) else: return Family([]) @cached_method def simple_root(self, j): r""" Returns the `j^{th}` simple root EXAMPLES:: sage: L = RootSystem(["C",4]).weight_lattice() sage: L.simple_root(3) -Lambda[2] + 2*Lambda[3] - Lambda[4] Its coefficients are given by the corresponding column of the Cartan matrix:: sage: L.cartan_type().cartan_matrix()[:,2] [ 0] [-1] [ 2] [-1] Here are all simple roots:: sage: L.simple_roots() Finite family {1: 2*Lambda[1] - Lambda[2], 2: -Lambda[1] + 2*Lambda[2] - Lambda[3], 3: -Lambda[2] + 2*Lambda[3] - Lambda[4], 4: -2*Lambda[3] + 2*Lambda[4]} For the extended weight lattice of an affine type, the simple root associated to the special node is deformed by adding `\delta`, where `\delta` is the null root:: sage: L = RootSystem(["C",4,1]).weight_lattice(extended=True) sage: L.simple_root(0) 2*Lambda[0] - 2*Lambda[1] + delta In fact `\delta` is really `1/a_0` times the null root (see the discussion in :class:`~sage.combinat.root_system.weight_space.WeightSpace`) but this only makes a difference in type `BC`:: sage: L = RootSystem(CartanType(["BC",4,2])).weight_lattice(extended=True) sage: L.simple_root(0) 2*Lambda[0] - Lambda[1] + delta sage: L.null_root() 2*delta .. SEEALSO:: - :meth:`~sage.combinat.root_system.type_affine.AmbientSpace.simple_root` - :meth:`CartanType.col_annihilator` """ if j not in self.index_set(): raise ValueError("{} is not in the index set".format(j)) K = self.base_ring() result = self.sum_of_terms((i,K(c)) for i,c in self.root_system.dynkin_diagram().column(j)) if self._extended and j == self.cartan_type().special_node(): result = result + self.monomial("delta") return result def _repr_term(self, m): r""" Customized monomial printing for extended weight lattices EXAMPLES:: sage: L = RootSystem(["C",4,1]).weight_lattice(extended=True) sage: L.simple_root(0) # indirect doctest 2*Lambda[0] - 2*Lambda[1] + delta sage: L = RootSystem(["C",4,1]).coweight_lattice(extended=True) sage: L.simple_root(0) # indirect doctest 2*Lambdacheck[0] - Lambdacheck[1] + deltacheck """ if m == "delta": return "deltacheck" if self.root_system.dual_side else "delta" return super()._repr_term(m) def _latex_term(self, m): r""" Customized monomial typesetting for extended weight lattices EXAMPLES:: sage: L = RootSystem(["C",4,1]).weight_lattice(extended=True) sage: latex(L.simple_root(0)) # indirect doctest 2 \Lambda_{0} - 2 \Lambda_{1} + \delta sage: L = RootSystem(["C",4,1]).coweight_lattice(extended=True) sage: latex(L.simple_root(0)) # indirect doctest 2 \Lambda^\vee_{0} - \Lambda^\vee_{1} + \delta^\vee """ if m == "delta": return "\\delta^\\vee" if self.root_system.dual_side else "\\delta" return super()._latex_term(m) @cached_method def _to_classical_on_basis(self, i): r""" Implement the projection onto the corresponding classical space or lattice, on the basis. INPUT: - ``i`` -- a vertex of the Dynkin diagram or "delta" EXAMPLES:: sage: L = RootSystem(["A",2,1]).weight_space() sage: L._to_classical_on_basis("delta") 0 sage: L._to_classical_on_basis(0) 0 sage: L._to_classical_on_basis(1) Lambda[1] sage: L._to_classical_on_basis(2) Lambda[2] """ if i == "delta" or i == self.cartan_type().special_node(): return self.classical().zero() else: return self.classical().monomial(i) @cached_method def to_ambient_space_morphism(self): r""" The morphism from ``self`` to its associated ambient space. EXAMPLES:: sage: CartanType(['A',2]).root_system().weight_lattice().to_ambient_space_morphism() Generic morphism: From: Weight lattice of the Root system of type ['A', 2] To: Ambient space of the Root system of type ['A', 2] .. warning:: Implemented only for finite Cartan type. """ if self.root_system.dual_side: raise TypeError("No implemented map from the coweight space to the ambient space") L = self.cartan_type().root_system().ambient_space() basis = L.fundamental_weights() def basis_value(basis, i): return basis[i] return self.module_morphism(on_basis = functools.partial(basis_value, basis), codomain=L) class WeightSpaceElement(CombinatorialFreeModule.Element): def scalar(self, lambdacheck): """ The canonical scalar product between the weight lattice and the coroot lattice. .. TODO:: - merge with_apply_multi_module_morphism - allow for any root space / lattice - define properly the return type (depends on the base rings of the two spaces) - make this robust for extended weight lattices (`i` might be "delta") EXAMPLES:: sage: L = RootSystem(["C",4,1]).weight_lattice() sage: Lambda = L.fundamental_weights() sage: alphacheck = L.simple_coroots() sage: Lambda[1].scalar(alphacheck[1]) 1 sage: Lambda[1].scalar(alphacheck[2]) 0 The fundamental weights and the simple coroots are dual bases:: sage: matrix([ [ Lambda[i].scalar(alphacheck[j]) ....: for i in L.index_set() ] ....: for j in L.index_set() ]) [1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0 0 1 0] [0 0 0 0 1] Note that the scalar product is not yet implemented between the weight space and the coweight space; in any cases, that won't be the job of this method:: sage: R = RootSystem(["A",3]) sage: alpha = R.weight_space().roots() sage: alphacheck = R.coweight_space().roots() sage: alpha[1].scalar(alphacheck[1]) Traceback (most recent call last): ... ValueError: -Lambdacheck[1] + 2*Lambdacheck[2] - Lambdacheck[3] is not in the coroot space """ # TODO: Find some better test if lambdacheck not in self.parent().coroot_lattice() and lambdacheck not in self.parent().coroot_space(): raise ValueError("{} is not in the coroot space".format(lambdacheck)) zero = self.parent().base_ring().zero() if len(self) < len(lambdacheck): return sum( (lambdacheck[i]*c for (i,c) in self), zero) else: return sum( (self[i]*c for (i,c) in lambdacheck), zero) def is_dominant(self): """ Checks whether an element in the weight space lies in the positive cone spanned by the basis elements (fundamental weights). EXAMPLES:: sage: W = RootSystem(['A',3]).weight_space() sage: Lambda = W.basis() sage: w = Lambda[1]+Lambda[3] sage: w.is_dominant() True sage: w = Lambda[1]-Lambda[2] sage: w.is_dominant() False In the extended affine weight lattice, 'delta' is orthogonal to the positive coroots, so adding or subtracting it should not effect dominance :: sage: P = RootSystem(['A',2,1]).weight_lattice(extended=true) sage: Lambda = P.fundamental_weights() sage: delta = P.null_root() sage: w = Lambda[1]-delta sage: w.is_dominant() True """ return all(self.coefficient(i) >= 0 for i in self.parent().index_set()) def to_ambient(self): r""" Maps ``self`` to the ambient space. EXAMPLES:: sage: mu = CartanType(['B',2]).root_system().weight_lattice().an_element(); mu 2*Lambda[1] + 2*Lambda[2] sage: mu.to_ambient() (3, 1) .. WARNING:: Only implemented in finite Cartan type. Does not work for coweight lattices because there is no implemented map from the coweight lattice to the ambient space. """ return self.parent().to_ambient_space_morphism()(self) def to_weight_space(self): r""" Map ``self`` to the weight space. Since `self.parent()` is the weight space, this map just returns ``self``. This overrides the generic method in `WeightSpaceRealizations`. EXAMPLES:: sage: mu = CartanType(['A',2]).root_system().weight_lattice().an_element(); mu 2*Lambda[1] + 2*Lambda[2] sage: mu.to_weight_space() 2*Lambda[1] + 2*Lambda[2] """ return self WeightSpace.Element = WeightSpaceElement
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/weight_space.py
0.924321
0.743971
weight_space.py
pypi
from .cartan_type import CartanType_standard_finite, CartanType_simple class CartanType(CartanType_standard_finite, CartanType_simple): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['I',5]) sage: ct ['I', 5] sage: ct._repr_(compact = True) 'I5' sage: ct.rank() 2 sage: ct.index_set() (1, 2) sage: ct.is_irreducible() True sage: ct.is_finite() True sage: ct.is_affine() False sage: ct.is_crystallographic() False sage: ct.is_simply_laced() False TESTS:: sage: TestSuite(ct).run() """ assert n >= 1 CartanType_standard_finite.__init__(self, "I", n) def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['I',5])) I_2(5) """ return "I_2({})".format(self.n) def rank(self): """ Type `I_2(p)` is of rank 2. EXAMPLES:: sage: CartanType(['I', 5]).rank() 2 """ return 2 def index_set(self): r""" Type `I_2(p)` is indexed by `\{1,2\}`. EXAMPLES:: sage: CartanType(['I', 5]).index_set() (1, 2) """ return (1, 2) def coxeter_diagram(self): """ Returns the Coxeter matrix for this type. EXAMPLES:: sage: ct = CartanType(['I', 4]) sage: ct.coxeter_diagram() Graph on 2 vertices sage: ct.coxeter_diagram().edges(sort=True) [(1, 2, 4)] sage: ct.coxeter_matrix() [1 4] [4 1] """ from sage.graphs.graph import Graph return Graph([[1,2,self.n]], multiedges=False) def coxeter_number(self): """ Return the Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['I',3]).coxeter_number() 3 sage: CartanType(['I',12]).coxeter_number() 12 """ return self.n
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_I.py
0.896837
0.613352
type_I.py
pypi
from sage.rings.integer_ring import ZZ from sage.combinat.root_system.root_lattice_realizations import RootLatticeRealizations from . import ambient_space class AmbientSpace(ambient_space.AmbientSpace): r""" EXAMPLES:: sage: R = RootSystem(["A",3]) sage: e = R.ambient_space(); e Ambient space of the Root system of type ['A', 3] sage: TestSuite(e).run() By default, this ambient space uses the barycentric projection for plotting:: sage: L = RootSystem(["A",2]).ambient_space() sage: e = L.basis() sage: L._plot_projection(e[0]) (1/2, 989/1142) sage: L._plot_projection(e[1]) (-1, 0) sage: L._plot_projection(e[2]) (1/2, -989/1142) sage: L = RootSystem(["A",3]).ambient_space() sage: l = L.an_element(); l (2, 2, 3, 0) sage: L._plot_projection(l) (0, -1121/1189, 7/3) .. SEEALSO:: - :meth:`sage.combinat.root_system.root_lattice_realizations.RootLatticeRealizations.ParentMethods._plot_projection` """ @classmethod def smallest_base_ring(cls, cartan_type=None): """ Returns the smallest base ring the ambient space can be defined upon .. SEEALSO:: :meth:`~sage.combinat.root_system.ambient_space.AmbientSpace.smallest_base_ring` EXAMPLES:: sage: e = RootSystem(["A",3]).ambient_space() sage: e.smallest_base_ring() Integer Ring """ return ZZ def dimension(self): """ EXAMPLES:: sage: e = RootSystem(["A",3]).ambient_space() sage: e.dimension() 4 """ return self.root_system.cartan_type().rank()+1 def root(self, i, j): """ Note that indexing starts at 0. EXAMPLES:: sage: e = RootSystem(['A',3]).ambient_lattice() sage: e.root(0,1) (1, -1, 0, 0) """ return self.monomial(i) - self.monomial(j) def simple_root(self, i): """ EXAMPLES:: sage: e = RootSystem(['A',3]).ambient_lattice() sage: e.simple_roots() Finite family {1: (1, -1, 0, 0), 2: (0, 1, -1, 0), 3: (0, 0, 1, -1)} """ return self.root(i-1, i) def negative_roots(self): """ EXAMPLES:: sage: e = RootSystem(['A',3]).ambient_lattice() sage: e.negative_roots() [(-1, 1, 0, 0), (-1, 0, 1, 0), (-1, 0, 0, 1), (0, -1, 1, 0), (0, -1, 0, 1), (0, 0, -1, 1)] """ res = [] for j in range(self.n-1): for i in range(j+1,self.n): res.append( self.root(i,j) ) return res def positive_roots(self): """ EXAMPLES:: sage: e = RootSystem(['A',3]).ambient_lattice() sage: e.positive_roots() [(1, -1, 0, 0), (1, 0, -1, 0), (0, 1, -1, 0), (1, 0, 0, -1), (0, 1, 0, -1), (0, 0, 1, -1)] """ res = [] for j in range(self.n): for i in range(j): res.append( self.root(i,j) ) return res def highest_root(self): """ EXAMPLES:: sage: e = RootSystem(['A',3]).ambient_lattice() sage: e.highest_root() (1, 0, 0, -1) """ return self.root(0,self.n-1) def fundamental_weight(self, i): """ EXAMPLES:: sage: e = RootSystem(['A',3]).ambient_lattice() sage: e.fundamental_weights() Finite family {1: (1, 0, 0, 0), 2: (1, 1, 0, 0), 3: (1, 1, 1, 0)} """ return self.sum(self.monomial(j) for j in range(i)) def det(self, k=1): """ returns the vector (1, ... ,1) which in the ['A',r] weight lattice, interpreted as a weight of GL(r+1,CC) is the determinant. If the optional parameter k is given, returns (k, ... ,k), the k-th power of the determinant. EXAMPLES:: sage: e = RootSystem(['A',3]).ambient_space() sage: e.det(1/2) (1/2, 1/2, 1/2, 1/2) """ return self.sum(self.monomial(j)*k for j in range(self.n)) _plot_projection = RootLatticeRealizations.ParentMethods.__dict__['_plot_projection_barycentric'] from .cartan_type import CartanType_standard_finite, CartanType_simply_laced, CartanType_simple class CartanType(CartanType_standard_finite, CartanType_simply_laced, CartanType_simple): """ Cartan Type `A_n` .. SEEALSO:: :func:`~sage.combinat.root_systems.cartan_type.CartanType` """ def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['A',4]) sage: ct ['A', 4] sage: ct._repr_(compact = True) 'A4' sage: ct.is_irreducible() True sage: ct.is_finite() True sage: ct.is_affine() False sage: ct.is_crystallographic() True sage: ct.is_simply_laced() True sage: ct.affine() ['A', 4, 1] sage: ct.dual() ['A', 4] TESTS:: sage: TestSuite(ct).run() """ assert n >= 0 CartanType_standard_finite.__init__(self, "A", n) def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['A',4])) A_{4} """ return "A_{%s}" % self.n AmbientSpace = AmbientSpace def coxeter_number(self): """ Return the Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['A',4]).coxeter_number() 5 """ return self.n + 1 def dual_coxeter_number(self): """ Return the dual Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['A',4]).dual_coxeter_number() 5 """ return self.n + 1 def dynkin_diagram(self): """ Returns the Dynkin diagram of type A. EXAMPLES:: sage: a = CartanType(['A',3]).dynkin_diagram() sage: a O---O---O 1 2 3 A3 sage: a.edges(sort=True) [(1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 2, 1)] TESTS:: sage: a = DynkinDiagram(['A',1]) sage: a O 1 A1 sage: a.vertices(sort=False), a.edges(sort=False) ([1], []) """ from .dynkin_diagram import DynkinDiagram_class n = self.n g = DynkinDiagram_class(self) for i in range(1, n): g.add_edge(i, i+1) return g def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['A',4])._latex_dynkin_diagram()) \draw (0 cm,0) -- (6 cm,0); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; <BLANKLINE> sage: print(CartanType(['A',0])._latex_dynkin_diagram()) <BLANKLINE> sage: print(CartanType(['A',1])._latex_dynkin_diagram()) \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; <BLANKLINE> """ if node is None: node = self._latex_draw_node if self.n > 1: ret = "\\draw (0 cm,0) -- ({} cm,0);\n".format((self.n-1)*node_dist) else: ret = "" return ret + "".join(node((i-1)*node_dist, 0, label(i)) for i in self.index_set()) def ascii_art(self, label=lambda i: i, node=None): """ Return an ascii art representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['A',0]).ascii_art()) sage: print(CartanType(['A',1]).ascii_art()) O 1 sage: print(CartanType(['A',3]).ascii_art()) O---O---O 1 2 3 sage: print(CartanType(['A',12]).ascii_art()) O---O---O---O---O---O---O---O---O---O---O---O 1 2 3 4 5 6 7 8 9 10 11 12 sage: print(CartanType(['A',5]).ascii_art(label = lambda x: x+2)) O---O---O---O---O 3 4 5 6 7 sage: print(CartanType(['A',5]).ascii_art(label = lambda x: x-2)) O---O---O---O---O -1 0 1 2 3 """ n = self.n if n == 0: return "" if node is None: node = self._ascii_art_node ret = "---".join(node(label(i)) for i in range(1,n+1)) + "\n" ret += "".join("{!s:4}".format(label(i)) for i in range(1,n+1)) return ret # For unpickling backward compatibility (Sage <= 4.1) from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.root_system.type_A', 'ambient_space', AmbientSpace)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_A.py
0.889
0.54256
type_A.py
pypi