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 |
|---|---|---|---|---|---|
import sage.modules.free_module_element
from sage.misc.repr import repr_lincomb
import sage.structure.formal_sum as formal_sum
import sage.modular.hecke.all as hecke
import sage.misc.latex as latex
_print_mode = "manin"
def is_ModularSymbolsElement(x):
r"""
Return True if x is an element of a modular symbols space.
EXAMPLES::
sage: sage.modular.modsym.element.is_ModularSymbolsElement(ModularSymbols(11, 2).0)
True
sage: sage.modular.modsym.element.is_ModularSymbolsElement(13)
False
"""
return isinstance(x, ModularSymbolsElement)
def set_modsym_print_mode(mode="manin"):
r"""
Set the mode for printing of elements of modular symbols spaces.
INPUT:
- ``mode`` - a string. The possibilities are as
follows:
- ``'manin'`` - (the default) formal sums of Manin
symbols [P(X,Y),(u,v)]
- ``'modular'`` - formal sums of Modular symbols
P(X,Y)\*alpha,beta, where alpha and beta are cusps
- ``'vector'`` - as vectors on the basis for the
ambient space
OUTPUT: none
EXAMPLES::
sage: M = ModularSymbols(13, 8)
sage: x = M.0 + M.1 + M.14
sage: set_modsym_print_mode('manin'); x
[X^5*Y,(1,11)] + [X^5*Y,(1,12)] + [X^6,(1,11)]
sage: set_modsym_print_mode('modular'); x
1610510*X^6*{-1/11, 0} + 893101*X^5*Y*{-1/11, 0} + 206305*X^4*Y^2*{-1/11, 0} + 25410*X^3*Y^3*{-1/11, 0} + 1760*X^2*Y^4*{-1/11, 0} + 65*X*Y^5*{-1/11, 0} - 248832*X^6*{-1/12, 0} - 103680*X^5*Y*{-1/12, 0} - 17280*X^4*Y^2*{-1/12, 0} - 1440*X^3*Y^3*{-1/12, 0} - 60*X^2*Y^4*{-1/12, 0} - X*Y^5*{-1/12, 0} + Y^6*{-1/11, 0}
sage: set_modsym_print_mode('vector'); x
(1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0)
sage: set_modsym_print_mode()
"""
mode = str(mode).lower()
if not (mode in ['manin', 'modular', 'vector']):
raise ValueError("mode must be one of 'manin', 'modular', or 'vector'")
global _print_mode
_print_mode = mode
class ModularSymbolsElement(hecke.HeckeModuleElement):
"""
An element of a space of modular symbols.
TESTS::
sage: x = ModularSymbols(3, 12).cuspidal_submodule().gen(0)
sage: x == loads(dumps(x))
True
"""
def __init__(self, parent, x, check=True):
"""
INPUT:
- ``parent`` -- a space of modular symbols
- ``x`` -- a free module element that represents the modular
symbol in terms of a basis for the ambient space (not in
terms of a basis for parent!)
EXAMPLES::
sage: S = ModularSymbols(11, sign=1).cuspidal_submodule()
sage: S(vector([0,1])) == S.basis()[0]
True
sage: S(vector([1,0]))
Traceback (most recent call last):
...
TypeError: x does not coerce to an element of this Hecke module
"""
if check:
from .space import ModularSymbolsSpace
if not isinstance(parent, ModularSymbolsSpace):
raise TypeError("parent (= %s) must be a space of modular symbols" % parent)
if not isinstance(x, sage.modules.free_module_element.FreeModuleElement):
raise TypeError("x must be a free module element.")
if x.degree() != parent.degree():
raise TypeError("x (of degree %s) must be of degree the same as the degree of the parent (of degree %s)."%(x.degree(), parent.degree()))
hecke.HeckeModuleElement.__init__(self, parent, x)
def _repr_(self):
r"""
String representation of self. The output will depend on the global
modular symbols print mode setting controlled by the function
``set_modsym_print_mode``.
EXAMPLES::
sage: M = ModularSymbols(13, 4)
sage: set_modsym_print_mode('manin'); M.0._repr_()
'[X^2,(0,1)]'
sage: set_modsym_print_mode('modular'); M.0._repr_()
'X^2*{0, Infinity}'
sage: set_modsym_print_mode('vector'); M.0._repr_()
'(1, 0, 0, 0, 0, 0, 0, 0)'
sage: set_modsym_print_mode()
"""
if _print_mode == "vector":
return str(self.element())
elif _print_mode == "manin":
m = self.manin_symbol_rep()
elif _print_mode == "modular":
m = self.modular_symbol_rep()
return repr_lincomb([(t,c) for c,t in m])
def _latex_(self):
r"""
LaTeX representation of self. The output will be determined by the print mode setting set using ``set_modsym_print_mode``.
EXAMPLES::
sage: M = ModularSymbols(11, 2)
sage: x = M.0 + M.2; x
(1,0) + (1,9)
sage: set_modsym_print_mode('manin'); latex(x) # indirect doctest
(1,0) + (1,9)
sage: set_modsym_print_mode('modular'); latex(x) # indirect doctest
\left\{\infty, 0\right\} + \left\{\frac{-1}{9}, 0\right\}
sage: set_modsym_print_mode('vector'); latex(x) # indirect doctest
\left(1,\,0,\,1\right)
sage: set_modsym_print_mode()
"""
if _print_mode == "vector":
return self.element()._latex_()
elif _print_mode == "manin":
m = self.manin_symbol_rep()
elif _print_mode == "modular":
m = self.modular_symbol_rep()
c = [x[0] for x in m]
v = [x[1] for x in m]
# TODO: use repr_lincomb with is_latex=True
return latex.repr_lincomb(v, c)
def _add_(self, right):
r"""
Sum of self and other.
EXAMPLES::
sage: M = ModularSymbols(3, 12)
sage: x = M.0; y = M.1; z = x + y; z # indirect doctest
[X^8*Y^2,(1,2)] + [X^9*Y,(1,0)]
sage: z.parent() is M
True
"""
return ModularSymbolsElement(self.parent(), self.element() + right.element(), check=False)
def _rmul_(self, other):
r"""
Right-multiply self by other.
EXAMPLES::
sage: M = ModularSymbols(3, 12)
sage: x = M.0; z = x*3; z # indirect doctest
3*[X^8*Y^2,(1,2)]
sage: z.parent() is M
True
sage: z*Mod(1, 17)
Traceback (most recent call last):
...
TypeError: unsupported operand parent(s) for *: 'Modular Symbols space of dimension 8 for Gamma_0(3) of weight 12 with sign 0 over Rational Field' and 'Ring of integers modulo 17'
"""
return ModularSymbolsElement(self.parent(), self.element()*other, check=False)
def _lmul_(self, left):
r"""
Left-multiply self by other.
EXAMPLES::
sage: M = ModularSymbols(3, 12)
sage: x = M.0; z = 3*x; z # indirect doctest
3*[X^8*Y^2,(1,2)]
sage: z.parent() is M
True
sage: Mod(1, 17)*z
Traceback (most recent call last):
...
TypeError: unsupported operand parent(s) for *: 'Ring of integers modulo 17' and 'Modular Symbols space of dimension 8 for Gamma_0(3) of weight 12 with sign 0 over Rational Field'
"""
return ModularSymbolsElement(self.parent(), left*self.element(), check=False)
def _neg_(self):
r"""
Multiply by -1.
EXAMPLES::
sage: M = ModularSymbols(3, 12)
sage: x = M.0; z = -x; z # indirect doctest
-[X^8*Y^2,(1,2)]
sage: z.parent() is M
True
"""
return ModularSymbolsElement(self.parent(), -self.element(), check=False)
def _sub_(self, other):
r"""
Subtract other from self.
EXAMPLES::
sage: M = ModularSymbols(3, 12)
sage: x = M.0; y = M.1; z = y-x; z # indirect doctest
-[X^8*Y^2,(1,2)] + [X^9*Y,(1,0)]
sage: z.parent() is M
True
"""
return ModularSymbolsElement(self.parent(), self.element() - other.element(), check=False)
# this clearly hasn't worked for some time -- the method embedded_vector_space doesn't exist -- DL 2009-05-18
# def coordinate_vector(self):
# if self.parent().is_ambient():
# return self.element()
# return self.parent().embedded_vector_space().coordinate_vector(self.element())
def list(self):
r"""
Return a list of the coordinates of self in terms of a basis for the ambient space.
EXAMPLES::
sage: ModularSymbols(37, 2).0.list()
[1, 0, 0, 0, 0]
"""
return self.element().list()
def manin_symbol_rep(self):
"""
Return a representation of self as a formal sum of Manin symbols.
EXAMPLES::
sage: x = ModularSymbols(37, 4).0
sage: x.manin_symbol_rep()
[X^2,(0,1)]
The result is cached::
sage: x.manin_symbol_rep() is x.manin_symbol_rep()
True
"""
try:
return self.__manin_symbols
except AttributeError:
A = self.parent()
v = self.element()
manin_symbols = A.ambient_hecke_module().manin_symbols_basis()
F = formal_sum.FormalSums(A.base_ring())
ms = F([(v[i], manin_symbols[i]) for i in range(v.degree())
if v[i] != 0], check=False, reduce=False)
self.__manin_symbols = ms
return self.__manin_symbols
def modular_symbol_rep(self):
"""
Return a representation of ``self`` as a formal sum of modular symbols.
EXAMPLES::
sage: x = ModularSymbols(37, 4).0
sage: x.modular_symbol_rep()
X^2*{0, Infinity}
The result is cached::
sage: x.modular_symbol_rep() is x.modular_symbol_rep()
True
"""
try:
return self.__modular_symbols
except AttributeError:
v = self.manin_symbol_rep()
if v == 0:
return v
w = [c * x.modular_symbol_rep() for c, x in v]
self.__modular_symbols = sum(w)
return self.__modular_symbols | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/modsym/element.py | 0.655667 | 0.466542 | element.py | pypi |
r"""
Local components of modular forms
If `f` is a (new, cuspidal, normalised) modular eigenform, then one can
associate to `f` an *automorphic representation* `\pi_f` of the group
`\operatorname{GL}_2(\mathbf{A})` (where `\mathbf{A}` is the adele ring of
`\QQ`). This object factors as a restricted tensor product of components
`\pi_{f, v}` for each place of `\QQ`. These are infinite-dimensional
representations, but they are specified by a finite amount of data, and this
module provides functions which determine a description of the local factor
`\pi_{f, p}` at a finite prime `p`.
The functions in this module are based on the algorithms described in
[LW2012]_.
AUTHORS:
- David Loeffler
- Jared Weinstein
"""
from sage.structure.sage_object import SageObject
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.polynomial_ring import polygen
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.qqbar import QQbar
from sage.misc.abstract_method import abstract_method
from sage.misc.cachefunc import cached_method
from sage.misc.verbose import verbose
from sage.misc.flatten import flatten
from sage.modular.modform.element import Newform
from sage.structure.sequence import Sequence
from .type_space import TypeSpace
from .smoothchar import SmoothCharacterGroupQp, SmoothCharacterGroupUnramifiedQuadratic, SmoothCharacterGroupRamifiedQuadratic
def LocalComponent(f, p, twist_factor=None):
r"""
Calculate the local component at the prime `p` of the automorphic
representation attached to the newform `f`.
INPUT:
- ``f`` (:class:`~sage.modular.modform.element.Newform`) a newform of weight `k \ge 2`
- ``p`` (integer) a prime
- ``twist_factor`` (integer) an integer congruent to `k` modulo 2 (default: `k - 2`)
.. note::
The argument ``twist_factor`` determines the choice of normalisation: if it is
set to `j \in \ZZ`, then the central character of `\pi_{f, \ell}` maps `\ell`
to `\ell^j \varepsilon(\ell)` for almost all `\ell`, where `\varepsilon` is the
Nebentypus character of `f`.
In the analytic theory it is conventional to take `j = 0` (the "Langlands
normalisation"), so the representation `\pi_f` is unitary; however, this is
inconvenient for `k` odd, since in this case one needs to choose a square root of `p`
and thus the map `f \to \pi_{f}` is not Galois-equivariant. Hence we use, by default, the
"Hecke normalisation" given by `j = k - 2`. This is also the most natural normalisation
from the perspective of modular symbols.
We also adopt a slightly unusual definition of the principal series: we
define `\pi(\chi_1, \chi_2)` to be the induction from the Borel subgroup of
the character of the maximal torus `\begin{pmatrix} x & \\ & y
\end{pmatrix} \mapsto \chi_1(a) \chi_2(b) |a|`, so its central character is
`z \mapsto \chi_1(z) \chi_2(z) |z|`. Thus `\chi_1 \chi_2` is the
restriction to `\QQ_p^\times` of the unique character of the id\'ele class
group mapping `\ell` to `\ell^{k-1} \varepsilon(\ell)` for almost all `\ell`.
This has the property that the *set* `\{\chi_1, \chi_2\}` also depends
Galois-equivariantly on `f`.
EXAMPLES::
sage: Pi = LocalComponent(Newform('49a'), 7); Pi
Smooth representation of GL_2(Q_7) with conductor 7^2
sage: Pi.central_character()
Character of Q_7*, of level 0, mapping 7 |--> 1
sage: Pi.species()
'Supercuspidal'
sage: Pi.characters()
[
Character of unramified extension Q_7(s)* (s^2 + 6*s + 3 = 0), of level 1, mapping s |--> -d, 7 |--> 1,
Character of unramified extension Q_7(s)* (s^2 + 6*s + 3 = 0), of level 1, mapping s |--> d, 7 |--> 1
]
"""
p = ZZ(p)
if not p.is_prime():
raise ValueError( "p must be prime" )
if not isinstance(f, Newform):
raise TypeError( "f (=%s of type %s) should be a Newform object" % (f, type(f)) )
r = f.level().valuation(p)
if twist_factor is None:
twist_factor = ZZ(f.weight() - 2)
else:
twist_factor = ZZ(twist_factor)
if r == 0:
return UnramifiedPrincipalSeries(f, p, twist_factor)
c = ZZ(f.character().conductor()).valuation(p)
if f[p] != 0:
if c == r:
return PrimitivePrincipalSeries(f, p, twist_factor)
if c == 0 and r == 1:
return PrimitiveSpecial(f, p, twist_factor)
g, chi = f.minimal_twist(p)
if g == f:
return PrimitiveSupercuspidal(f, p, twist_factor)
mintwist = LocalComponent(g, p, twist_factor)
return ImprimitiveLocalComponent(f, p, twist_factor, mintwist, chi)
class LocalComponentBase(SageObject):
r"""
Base class for local components of newforms. Not to be directly instantiated; use the :func:`~LocalComponent` constructor function.
"""
def __init__(self, newform, prime, twist_factor):
r"""
Standard initialisation function.
EXAMPLES::
sage: LocalComponent(Newform('49a'), 7) # indirect doctest
Smooth representation of GL_2(Q_7) with conductor 7^2
"""
self._p = prime
self._f = newform
self._twist_factor = twist_factor
@abstract_method
def species(self):
r"""
The species of this local component, which is either 'Principal
Series', 'Special' or 'Supercuspidal'.
EXAMPLES::
sage: from sage.modular.local_comp.local_comp import LocalComponentBase
sage: LocalComponentBase(Newform('50a'), 3, 0).species()
Traceback (most recent call last):
...
NotImplementedError: <abstract method species at ...>
"""
pass
@abstract_method
def check_tempered(self):
r"""
Check that this representation is quasi-tempered, i.e. `\pi \otimes
|\det|^{j/2}` is tempered. It is well known that local components of
modular forms are *always* tempered, so this serves as a useful check
on our computations.
EXAMPLES::
sage: from sage.modular.local_comp.local_comp import LocalComponentBase
sage: LocalComponentBase(Newform('50a'), 3, 0).check_tempered()
Traceback (most recent call last):
...
NotImplementedError: <abstract method check_tempered at ...>
"""
pass
def _repr_(self):
r"""
String representation of self.
EXAMPLES::
sage: LocalComponent(Newform('50a'), 5)._repr_()
'Smooth representation of GL_2(Q_5) with conductor 5^2'
"""
return "Smooth representation of GL_2(Q_%s) with conductor %s^%s" % (self.prime(), self.prime(), self.conductor())
def newform(self):
r"""
The newform of which this is a local component.
EXAMPLES::
sage: LocalComponent(Newform('50a'), 5).newform()
q - q^2 + q^3 + q^4 + O(q^6)
"""
return self._f
def prime(self):
r"""
The prime at which this is a local component.
EXAMPLES::
sage: LocalComponent(Newform('50a'), 5).prime()
5
"""
return self._p
def conductor(self):
r"""
The smallest `r` such that this representation has a nonzero vector fixed by the subgroup
`\begin{pmatrix} * & * \\ 0 & 1\end{pmatrix} \pmod{p^r}`. This is equal to the power of `p` dividing the level of the corresponding newform.
EXAMPLES::
sage: LocalComponent(Newform('50a'), 5).conductor()
2
"""
return self.newform().level().valuation(self.prime())
def coefficient_field(self):
r"""
The field `K` over which this representation is defined. This is the field generated by the Hecke eigenvalues of the corresponding newform (over whatever base ring the newform is created).
EXAMPLES::
sage: LocalComponent(Newforms(50)[0], 3).coefficient_field()
Rational Field
sage: LocalComponent(Newforms(Gamma1(10), 3, base_ring=QQbar)[0], 5).coefficient_field()
Algebraic Field
sage: LocalComponent(Newforms(DirichletGroup(5).0, 7,names='c')[0], 5).coefficient_field()
Number Field in c0 with defining polynomial x^2 + (5*zeta4 + 5)*x - 88*zeta4 over its base field
"""
return self.newform().hecke_eigenvalue_field()
def twist_factor(self):
r"""
The unique `j` such that `\begin{pmatrix} p & 0 \\ 0 & p\end{pmatrix}`
acts as multiplication by `p^j` times a root of unity.
There are various conventions for this; see the documentation of the
:func:`~LocalComponent` constructor function for more information.
The twist factor should have the same parity as the weight of the form,
since otherwise the map sending `f` to its local component won't be
Galois equivariant.
EXAMPLES::
sage: LocalComponent(Newforms(50)[0], 3).twist_factor()
0
sage: LocalComponent(Newforms(50)[0], 3, twist_factor=173).twist_factor()
173
"""
return self._twist_factor
def central_character(self):
r"""
Return the central character of this representation. This is the
restriction to `\QQ_p^\times` of the unique smooth character `\omega`
of `\mathbf{A}^\times / \QQ^\times` such that `\omega(\varpi_\ell) =
\ell^j \varepsilon(\ell)` for all primes `\ell \nmid Np`, where
`\varpi_\ell` is a uniformiser at `\ell`, `\varepsilon` is the
Nebentypus character of the newform `f`, and `j` is the twist factor
(see the documentation for :func:`~LocalComponent`).
EXAMPLES::
sage: LocalComponent(Newform('27a'), 3).central_character()
Character of Q_3*, of level 0, mapping 3 |--> 1
sage: LocalComponent(Newforms(Gamma1(5), 5, names='c')[0], 5).central_character()
Character of Q_5*, of level 1, mapping 2 |--> c0 + 1, 5 |--> 125
sage: LocalComponent(Newforms(DirichletGroup(24)([1, -1,-1]), 3, names='a')[0], 2).central_character()
Character of Q_2*, of level 3, mapping 7 |--> 1, 5 |--> -1, 2 |--> -2
"""
G = SmoothCharacterGroupQp(self.prime(), self.coefficient_field())
eps = G.from_dirichlet(self.newform().character())
return eps / G.norm_character()**self.twist_factor()
def __eq__(self, other):
r"""
Comparison function.
EXAMPLES::
sage: Pi = LocalComponent(Newform("50a"), 5)
sage: Pi == LocalComponent(Newform("50a"), 3)
False
sage: Pi == LocalComponent(Newform("50b"), 5)
False
sage: Pi == QQ
False
sage: Pi == None
False
sage: Pi == loads(dumps(Pi))
True
"""
return (isinstance(other, LocalComponentBase)
and self.prime() == other.prime()
and self.newform() == other.newform()
and self.twist_factor() == other.twist_factor())
def __ne__(self, other):
"""
Return True if ``self != other``.
EXAMPLES::
sage: Pi = LocalComponent(Newform("50a"), 5)
sage: Pi != LocalComponent(Newform("50a"), 3)
True
sage: Pi != LocalComponent(Newform("50b"), 5)
True
sage: Pi != QQ
True
sage: Pi != None
True
sage: Pi != loads(dumps(Pi))
False
"""
return not (self == other)
class PrimitiveLocalComponent(LocalComponentBase):
r"""
Base class for primitive (twist-minimal) local components.
"""
def is_primitive(self):
r"""
Return True if this local component is primitive (has minimal level
among its character twists).
EXAMPLES::
sage: Newform("50a").local_component(5).is_primitive()
True
"""
return True
def minimal_twist(self):
r"""
Return a twist of this local component which has the minimal possible
conductor.
EXAMPLES::
sage: Pi = Newform("50a").local_component(5)
sage: Pi.minimal_twist() == Pi
True
"""
return self
class PrincipalSeries(PrimitiveLocalComponent):
r"""
A principal series representation. This is an abstract base class, not to
be instantiated directly; see the subclasses
:class:`~UnramifiedPrincipalSeries` and :class:`~PrimitivePrincipalSeries`.
"""
def species(self):
r"""
The species of this local component, which is either 'Principal
Series', 'Special' or 'Supercuspidal'.
EXAMPLES::
sage: LocalComponent(Newform('50a'), 3).species()
'Principal Series'
"""
return "Principal Series"
def check_tempered(self):
r"""
Check that this representation is tempered (after twisting by
`|\det|^{j/2}`), i.e. that `|\chi_1(p)| = |\chi_2(p)| = p^{(j + 1)/2}`.
This follows from the Ramanujan--Petersson conjecture, as proved by
Deligne.
EXAMPLES::
sage: LocalComponent(Newform('49a'), 3).check_tempered()
"""
c1, c2 = self.characters()
K = c1.base_ring()
p = self.prime()
w = QQbar(p)**((1 + self.twist_factor()) / 2)
for sigma in K.embeddings(QQbar):
assert sigma(c1(p)).abs() == sigma(c2(p)).abs() == w
@abstract_method
def characters(self):
r"""
Return the two characters `(\chi_1, \chi_2)` such this representation
`\pi_{f, p}` is equal to the principal series `\pi(\chi_1, \chi_2)`.
EXAMPLES::
sage: from sage.modular.local_comp.local_comp import PrincipalSeries
sage: PrincipalSeries(Newform('50a'), 3, 0).characters()
Traceback (most recent call last):
...
NotImplementedError: <abstract method characters at ...>
"""
pass
class UnramifiedPrincipalSeries(PrincipalSeries):
r"""
An unramified principal series representation of `{\rm GL}_2(\QQ_p)`
(corresponding to a form whose level is not divisible by `p`).
EXAMPLES::
sage: Pi = LocalComponent(Newform('50a'), 3)
sage: Pi.conductor()
0
sage: type(Pi)
<class 'sage.modular.local_comp.local_comp.UnramifiedPrincipalSeries'>
sage: TestSuite(Pi).run()
"""
def satake_polynomial(self):
r"""
Return the Satake polynomial of this representation, i.e.~the polynomial whose roots are `\chi_1(p), \chi_2(p)`
where this representation is `\pi(\chi_1, \chi_2)`. Concretely, this is the polynomial
.. MATH::
X^2 - p^{(j - k + 2)/2} a_p(f) X + p^{j + 1} \varepsilon(p)`.
An error will be raised if `j \ne k \bmod 2`.
EXAMPLES::
sage: LocalComponent(Newform('11a'), 17).satake_polynomial()
X^2 + 2*X + 17
sage: LocalComponent(Newform('11a'), 17, twist_factor = -2).satake_polynomial()
X^2 + 2/17*X + 1/17
"""
p = self.prime()
return PolynomialRing(self.coefficient_field(), 'X')([
self.central_character()(p)*p,
-self.newform()[p] * p**((self.twist_factor() - self.newform().weight() + 2)/2),
1
])
def characters(self):
r"""
Return the two characters `(\chi_1, \chi_2)` such this representation
`\pi_{f, p}` is equal to the principal series `\pi(\chi_1, \chi_2)`.
These are the unramified characters mapping `p` to the roots of the Satake polynomial,
so in most cases (but not always) they will be defined over an
extension of the coefficient field of self.
EXAMPLES::
sage: LocalComponent(Newform('11a'), 17).characters()
[
Character of Q_17*, of level 0, mapping 17 |--> d,
Character of Q_17*, of level 0, mapping 17 |--> -d - 2
]
sage: LocalComponent(Newforms(Gamma1(5), 6, names='a')[1], 3).characters()
[
Character of Q_3*, of level 0, mapping 3 |--> -3/2*a1 + 12,
Character of Q_3*, of level 0, mapping 3 |--> -3/2*a1 - 12
]
"""
f = self.satake_polynomial()
if not f.is_irreducible():
# This can happen; see the second example above
d = f.roots()[0][0]
else:
d = self.coefficient_field().extension(f, 'd').gen()
G = SmoothCharacterGroupQp(self.prime(), d.parent())
return Sequence([G.character(0, [d]), G.character(0, [self.newform()[self.prime()] - d])], cr=True, universe=G)
class PrimitivePrincipalSeries(PrincipalSeries):
r"""
A ramified principal series of the form `\pi(\chi_1, \chi_2)`
where `\chi_1` is unramified but `\chi_2` is not.
EXAMPLES::
sage: Pi = LocalComponent(Newforms(Gamma1(13), 2, names='a')[0], 13)
sage: type(Pi)
<class 'sage.modular.local_comp.local_comp.PrimitivePrincipalSeries'>
sage: TestSuite(Pi).run()
"""
def characters(self):
r"""
Return the two characters `(\chi_1, \chi_2)` such that the local component `\pi_{f, p}` is the induction of the character `\chi_1 \times \chi_2` of the Borel subgroup.
EXAMPLES::
sage: LocalComponent(Newforms(Gamma1(13), 2, names='a')[0], 13).characters()
[
Character of Q_13*, of level 0, mapping 13 |--> 3*a0 + 2,
Character of Q_13*, of level 1, mapping 2 |--> a0 + 2, 13 |--> -3*a0 - 7
]
"""
G = SmoothCharacterGroupQp(self.prime(), self.coefficient_field())
t = ZZ((self.newform().weight() - 2 - self.twist_factor()) / 2)
chi1 = G.character(0, [self.newform()[self.prime()]]) * G.norm_character()**t
chi2 = G.character(0, [self.prime()]) * self.central_character() / chi1
return Sequence([chi1, chi2], cr=True, universe=G)
class PrimitiveSpecial(PrimitiveLocalComponent):
r"""
A primitive special representation: that is, the Steinberg representation
twisted by an unramified character. All such representations have conductor
1.
EXAMPLES::
sage: Pi = LocalComponent(Newform('37a'), 37)
sage: Pi.species()
'Special'
sage: Pi.conductor()
1
sage: type(Pi)
<class 'sage.modular.local_comp.local_comp.PrimitiveSpecial'>
sage: TestSuite(Pi).run()
"""
def species(self):
r"""
The species of this local component, which is either 'Principal
Series', 'Special' or 'Supercuspidal'.
EXAMPLES::
sage: LocalComponent(Newform('37a'), 37).species()
'Special'
"""
return "Special"
def characters(self):
r"""
Return the defining characters of this representation. In this case, it
will return the unique unramified character `\chi` of `\QQ_p^\times`
such that this representation is equal to `\mathrm{St} \otimes \chi`,
where `\mathrm{St}` is the Steinberg representation (defined as the
quotient of the parabolic induction of the trivial character by its
trivial subrepresentation).
EXAMPLES:
Our first example is the newform corresponding to an elliptic curve of
conductor `37`. This is the nontrivial quadratic twist of Steinberg,
corresponding to the fact that the elliptic curve has non-split
multiplicative reduction at 37::
sage: LocalComponent(Newform('37a'), 37).characters()
[Character of Q_37*, of level 0, mapping 37 |--> -1]
We try an example in odd weight, where the central character isn't
trivial::
sage: Pi = LocalComponent(Newforms(DirichletGroup(21)([-1, 1]), 3, names='j')[0], 7); Pi.characters()
[Character of Q_7*, of level 0, mapping 7 |--> -1/2*j0^2 - 7/2]
sage: Pi.characters()[0] ^2 == Pi.central_character()
True
An example using a non-standard twist factor::
sage: Pi = LocalComponent(Newforms(DirichletGroup(21)([-1, 1]), 3, names='j')[0], 7, twist_factor=3); Pi.characters()
[Character of Q_7*, of level 0, mapping 7 |--> -7/2*j0^2 - 49/2]
sage: Pi.characters()[0]^2 == Pi.central_character()
True
"""
return [SmoothCharacterGroupQp(self.prime(), self.coefficient_field()).character(0, [self.newform()[self.prime()] * self.prime() ** ((self.twist_factor() - self.newform().weight() + 2)/2)])]
def check_tempered(self):
r"""
Check that this representation is tempered (after twisting by
`|\det|^{j/2}` where `j` is the twist factor). Since local components
of modular forms are always tempered, this is a useful check on our
calculations.
EXAMPLES::
sage: Pi = LocalComponent(Newforms(DirichletGroup(21)([-1, 1]), 3, names='j')[0], 7)
sage: Pi.check_tempered()
"""
c1 = self.characters()[0]
K = c1.base_ring()
p = self.prime()
w = QQbar(p)**(self.twist_factor() / ZZ(2))
for sigma in K.embeddings(QQbar):
assert sigma(c1(p)).abs() == w
class PrimitiveSupercuspidal(PrimitiveLocalComponent):
r"""
A primitive supercuspidal representation.
Except for some exceptional cases when `p = 2` which we do not implement
here, such representations are parametrized by smooth characters of tamely
ramified quadratic extensions of `\QQ_p`.
EXAMPLES::
sage: f = Newform("50a")
sage: Pi = LocalComponent(f, 5)
sage: type(Pi)
<class 'sage.modular.local_comp.local_comp.PrimitiveSupercuspidal'>
sage: Pi.species()
'Supercuspidal'
sage: TestSuite(Pi).run()
"""
def species(self):
r"""
The species of this local component, which is either 'Principal
Series', 'Special' or 'Supercuspidal'.
EXAMPLES::
sage: LocalComponent(Newform('49a'), 7).species()
'Supercuspidal'
"""
return "Supercuspidal"
@cached_method
def type_space(self):
r"""
Return a :class:`~sage.modular.local_comp.type_space.TypeSpace` object
describing the (homological) type space of this newform, which we know
is dual to the type space of the local component.
EXAMPLES::
sage: LocalComponent(Newform('49a'), 7).type_space()
6-dimensional type space at prime 7 of form q + q^2 - q^4 + O(q^6)
"""
return TypeSpace(self.newform(), self.prime())
def characters(self):
r"""
Return the two conjugate characters of `K^\times`, where `K` is some
quadratic extension of `\QQ_p`, defining this representation. An error
will be raised in some 2-adic cases, since not all 2-adic supercuspidal
representations arise in this way.
EXAMPLES:
The first example from [LW2012]_::
sage: f = Newform('50a')
sage: Pi = LocalComponent(f, 5)
sage: chars = Pi.characters(); chars
[
Character of unramified extension Q_5(s)* (s^2 + 4*s + 2 = 0), of level 1, mapping s |--> -d - 1, 5 |--> 1,
Character of unramified extension Q_5(s)* (s^2 + 4*s + 2 = 0), of level 1, mapping s |--> d, 5 |--> 1
]
sage: chars[0].base_ring()
Number Field in d with defining polynomial x^2 + x + 1
These characters are interchanged by the Frobenius automorphism of `\GF{25}`::
sage: chars[0] == chars[1]**5
True
A more complicated example (higher weight and nontrivial central character)::
sage: f = Newforms(GammaH(25, [6]), 3, names='j')[0]; f
q + j0*q^2 + 1/3*j0^3*q^3 - 1/3*j0^2*q^4 + O(q^6)
sage: Pi = LocalComponent(f, 5)
sage: Pi.characters()
[
Character of unramified extension Q_5(s)* (s^2 + 4*s + 2 = 0), of level 1, mapping s |--> 1/3*j0^2*d - 1/3*j0^3, 5 |--> 5,
Character of unramified extension Q_5(s)* (s^2 + 4*s + 2 = 0), of level 1, mapping s |--> -1/3*j0^2*d, 5 |--> 5
]
sage: Pi.characters()[0].base_ring()
Number Field in d with defining polynomial x^2 - j0*x + 1/3*j0^2 over its base field
.. warning::
The above output isn't actually the same as in Example 2 of
[LW2012]_, due to an error in the published paper (correction
pending) -- the published paper has the inverses of the above
characters.
A higher level example::
sage: f = Newform('81a', names='j'); f
q + j0*q^2 + q^4 - j0*q^5 + O(q^6)
sage: LocalComponent(f, 3).characters() # long time (12s on sage.math, 2012)
[
Character of unramified extension Q_3(s)* (s^2 + 2*s + 2 = 0), of level 2, mapping -2*s |--> -2*d + j0, 4 |--> 1, 3*s + 1 |--> -j0*d + 1, 3 |--> 1,
Character of unramified extension Q_3(s)* (s^2 + 2*s + 2 = 0), of level 2, mapping -2*s |--> 2*d - j0, 4 |--> 1, 3*s + 1 |--> j0*d - 2, 3 |--> 1
]
Some ramified examples::
sage: Newform('27a').local_component(3).characters()
[
Character of ramified extension Q_3(s)* (s^2 - 6 = 0), of level 2, mapping 2 |--> 1, s + 1 |--> -d, s |--> -1,
Character of ramified extension Q_3(s)* (s^2 - 6 = 0), of level 2, mapping 2 |--> 1, s + 1 |--> d - 1, s |--> -1
]
sage: LocalComponent(Newform('54a'), 3, twist_factor=4).characters()
[
Character of ramified extension Q_3(s)* (s^2 - 3 = 0), of level 2, mapping 2 |--> 1, s + 1 |--> -1/9*d, s |--> -9,
Character of ramified extension Q_3(s)* (s^2 - 3 = 0), of level 2, mapping 2 |--> 1, s + 1 |--> 1/9*d - 1, s |--> -9
]
A 2-adic non-example::
sage: Newform('24a').local_component(2).characters()
Traceback (most recent call last):
...
ValueError: Totally ramified 2-adic representations are not classified by characters
Examples where `K^\times / \QQ_p^\times` is not topologically cyclic
(which complicates the computations greatly)::
sage: Newforms(DirichletGroup(64, QQ).1, 2, names='a')[0].local_component(2).characters() # long time, random
[
Character of unramified extension Q_2(s)* (s^2 + s + 1 = 0), of level 3, mapping s |--> 1, 2*s + 1 |--> 1/2*a0, 4*s + 1 |--> 1, -1 |--> 1, 2 |--> 1,
Character of unramified extension Q_2(s)* (s^2 + s + 1 = 0), of level 3, mapping s |--> 1, 2*s + 1 |--> 1/2*a0, 4*s + 1 |--> -1, -1 |--> 1, 2 |--> 1
]
sage: Newform('243a',names='a').local_component(3).characters() # long time
[
Character of ramified extension Q_3(s)* (s^2 - 6 = 0), of level 4, mapping -2*s - 1 |--> -d - 1, 4 |--> 1, 3*s + 1 |--> -d - 1, s |--> 1,
Character of ramified extension Q_3(s)* (s^2 - 6 = 0), of level 4, mapping -2*s - 1 |--> d, 4 |--> 1, 3*s + 1 |--> d, s |--> 1
]
"""
T = self.type_space()
p = self.prime()
if self.conductor() % 2 == 0:
G = SmoothCharacterGroupUnramifiedQuadratic(self.prime(), self.coefficient_field())
n = self.conductor() // 2
gs = G.quotient_gens(n)
g = gs[-1]
assert g.valuation(G.ideal(1)) == 0
m = g.matrix().change_ring(ZZ).list()
tr = (~T.rho(m)).trace()
# The inverse is needed here because T is the *homological* type space,
# which is dual to the cohomological one that defines the local component.
X = polygen(self.coefficient_field())
theta_poly = X**2 - (-1)**n*tr*X + self.central_character()(g.norm())
verbose("theta_poly for %s is %s" % (g, theta_poly), level=1)
if theta_poly.is_irreducible():
F = self.coefficient_field().extension(theta_poly, "d")
G = G.base_extend(F)
# roots with repetitions allowed
gvals = flatten([[y[0]]*y[1] for y in theta_poly.roots(G.base_ring())])
if len(gs) == 1:
# This is always the case if p != 2
chi1, chi2 = [G.extend_character(n, self.central_character(), [x]) for x in gvals]
else:
# 2-adic cases, conductor >= 64. Here life is complicated
# because the quotient (O_K* / p^n)^* / (image of Z_2^*) is not
# cyclic.
g0 = gs[0]
try:
G._reduce_Qp(1, g0)
raise ArithmeticError("Bad generators returned")
except ValueError:
pass
tr = (~T.rho(g0.matrix().list())).trace()
X = polygen(G.base_ring())
theta0_poly = X**2 - (-1)**n*tr*X + self.central_character()(g0.norm())
verbose("theta_poly for %s is %s" % (g0, theta_poly), level=1)
if theta0_poly.is_irreducible():
F = theta0_poly.base_ring().extension(theta_poly, "e")
G = G.base_extend(F)
g0vals = flatten([[y[0]]*y[1] for y in theta0_poly.roots(G.base_ring())])
pairA = [ [g0vals[0], gvals[0]], [g0vals[1], gvals[1]] ]
pairB = [ [g0vals[0], gvals[1]], [g0vals[1], gvals[0]] ]
A_fail = 0
B_fail = 0
try:
chisA = [G.extend_character(n, self.central_character(), [y, x]) for (y, x) in pairA]
except ValueError:
A_fail = 1
try:
chisB = [G.extend_character(n, self.central_character(), [y, x]) for (y, x) in pairB]
except ValueError:
B_fail = 1
if chisA == chisB or chisA == reversed(chisB):
# repeated roots -- break symmetry arbitrarily
B_fail = 1
# check the character relation from LW12
if (not A_fail and not B_fail):
for x in G.ideal(n).invertible_residues():
try:
# test if G mod p is in Fp
flag = G._reduce_Qp(1, x)
except ValueError:
flag = None
if flag is not None:
verbose("skipping x=%s as congruent to %s mod p" % (x, flag))
continue
verbose("testing x = %s" % x, level=1)
ti = (-1)**n * (~T.rho(x.matrix().list())).trace()
verbose(" trace of matrix is %s" % ti, level=1)
if ti != chisA[0](x) + chisA[1](x):
verbose(" chisA FAILED", level=1)
A_fail = 1
break
if ti != chisB[0](x) + chisB[1](x):
verbose(" chisB FAILED", level=1)
B_fail = 1
break
else:
verbose(" Trace identity check works for both", level=1)
if B_fail and not A_fail:
chi1, chi2 = chisA
elif A_fail and not B_fail:
chi1, chi2 = chisB
else:
raise ValueError("Something went wrong: can't identify the characters")
# Consistency checks
assert chi1.restrict_to_Qp() == chi2.restrict_to_Qp() == self.central_character()
assert chi1*chi2 == chi1.parent().compose_with_norm(self.central_character())
return Sequence([chi1, chi2], check=False, cr=True)
else:
# The ramified case.
n = self.conductor() - 1
if p == 2:
# The ramified 2-adic representations aren't classified by admissible pairs. Die.
raise ValueError("Totally ramified 2-adic representations are not classified by characters")
G0 = SmoothCharacterGroupRamifiedQuadratic(p, 0, self.coefficient_field())
G1 = SmoothCharacterGroupRamifiedQuadratic(p, 1, self.coefficient_field())
q0 = G0.quotient_gens(n)
assert all(x.valuation(G0.ideal(1)) == 1 for x in q0)
q1 = G1.quotient_gens(n)
assert all(x.valuation(G1.ideal(1)) == 1 for x in q1)
t0 = [(~T.rho(q.matrix().list())).trace() for q in q0]
t1 = [(~T.rho(q.matrix().list())).trace() for q in q1]
if all(x == 0 for x in t0 + t1):
# Can't happen?
raise NotImplementedError( "Can't identify ramified quadratic extension -- all traces zero" )
elif all(x == 0 for x in t1):
G, qs, ts = G0, q0, t0
elif all(x == 0 for x in t0):
G, qs, ts = G1, q1, t1
else:
# At least one of the traces is *always* 0, since the type
# space has to be isomorphic to its twist by the (ramified
# quadratic) character corresponding to the quadratic
# extension.
raise RuntimeError( "Can't get here!" )
q = qs[0]
t = ts[0]
k = self.newform().weight()
t *= p**ZZ( (k - 2 + self.twist_factor() ) / 2)
X = polygen(self.coefficient_field())
theta_poly = X**2 - X * t + self.central_character()(q.norm())
verbose("theta_poly is %s" % theta_poly, level=1)
if theta_poly.is_irreducible():
F = self.coefficient_field().extension(theta_poly, "d")
G = G.base_extend(F)
c1q, c2q = flatten([[x]*e for x,e in theta_poly.roots(G.base_ring())])
if len(qs) == 1:
chi1, chi2 = [G.extend_character(n, self.central_character(), [x]) for x in [c1q, c2q]]
else:
assert p == 3
q = qs[1]
t = ts[1]
t *= p**ZZ( (k - 2 + self.twist_factor() ) / 2)
X = polygen(G.base_ring())
theta_poly = X**2 - X * t + self.central_character()(q.norm())
verbose("theta_poly is %s" % theta_poly, level=1)
if theta_poly.is_irreducible():
F = G.base_ring().extension(theta_poly, "e")
G = G.base_extend(F)
c1q2, c2q2 = flatten([[x]*e for x,e in theta_poly.roots(G.base_ring())])
pairA = [ [c1q, c1q2], [c2q,c2q2] ]
pairB = [ [c1q, c2q2], [c2q, c1q2] ]
A_fail = 0
B_fail = 0
try:
chisA = [G.extend_character(n, self.central_character(), [x, y]) for (x, y) in pairA]
except ValueError:
verbose('A failed to create', level=1)
A_fail = 1
try:
chisB = [G.extend_character(n, self.central_character(), [x, y]) for (x, y) in pairB]
except ValueError:
verbose('A failed to create', level=1)
B_fail = 1
if c1q == c2q or c1q2 == c2q2:
B_fail = 1
for u in G.ideal(n).invertible_residues():
if A_fail or B_fail:
break
x = q*u
verbose("testing x = %s" % x, level=1)
ti = (~T.rho(x.matrix().list())).trace() * p**ZZ((k-2+self.twist_factor())/2)
verbose("trace of matrix is %s" % ti, level=1)
if chisA[0](x) + chisA[1](x) != ti:
A_fail = 1
if chisB[0](x) + chisB[1](x) != ti:
B_fail = 1
if B_fail and not A_fail:
chi1, chi2 = chisA
elif A_fail and not B_fail:
chi1, chi2 = chisB
else:
raise ValueError("Something went wrong: can't identify the characters")
# Consistency checks
assert chi1.restrict_to_Qp() == chi2.restrict_to_Qp() == self.central_character()
assert chi1*chi2 == chi1.parent().compose_with_norm(self.central_character())
return Sequence([chi1, chi2], check=False, cr=True)
def check_tempered(self):
r"""
Check that this representation is tempered (after twisting by
`|\det|^{j/2}` where `j` is the twist factor). Since local components
of modular forms are always tempered, this is a useful check on our
calculations.
Since the computation of the characters attached to this representation
is not implemented in the odd-conductor case, a NotImplementedError
will be raised for such representations.
EXAMPLES::
sage: LocalComponent(Newform("50a"), 5).check_tempered()
sage: LocalComponent(Newform("27a"), 3).check_tempered()
"""
c1, c2 = self.characters()
K = c1.base_ring()
p = self.prime()
w = QQbar(p)**self.twist_factor()
for sigma in K.embeddings(QQbar):
assert sigma(c1(p)).abs() == sigma(c2(p)).abs() == w
class ImprimitiveLocalComponent(LocalComponentBase):
r"""
A smooth representation which is not of minimal level among its character
twists. Internally, this is stored as a pair consisting of a minimal local
component and a character to twist by.
"""
def __init__(self,newform, prime, twist_factor, min_twist, chi):
r"""
EXAMPLES::
sage: Newform("45a").local_component(3) # indirect doctest
Smooth representation of GL_2(Q_3) with conductor 3^2, twist of representation of conductor 3^1
"""
LocalComponentBase.__init__(self, newform, prime, twist_factor)
self._min_twist = min_twist
self._chi = chi
def is_primitive(self):
r"""
Return True if this local component is primitive (has minimal level
among its character twists).
EXAMPLES::
sage: Newform("45a").local_component(3).is_primitive()
False
"""
return False
def minimal_twist(self):
r"""
Return a twist of this local component which has the minimal possible
conductor.
EXAMPLES::
sage: Pi = Newform("75b").local_component(5)
sage: Pi.minimal_twist()
Smooth representation of GL_2(Q_5) with conductor 5^1
"""
return self._min_twist
def twisting_character(self):
r"""
Return the character giving the minimal twist of this representation.
EXAMPLES::
sage: Pi = Newform("45a").local_component(3)
sage: Pi.twisting_character()
Dirichlet character modulo 3 of conductor 3 mapping 2 |--> -1
"""
return self._chi
def species(self):
r"""
The species of this local component, which is either 'Principal
Series', 'Special' or 'Supercuspidal'.
EXAMPLES::
sage: Pi = Newform("45a").local_component(3)
sage: Pi.species()
'Special'
"""
return self._min_twist.species()
def _repr_(self):
r"""
EXAMPLES::
sage: Pi = Newform("45a").local_component(3)
sage: Pi # indirect doctest
Smooth representation of GL_2(Q_3) with conductor 3^2, twist of representation of conductor 3^1
"""
return LocalComponentBase._repr_(self) + ', twist of representation of conductor %s^%s' % (self.prime(), self._min_twist.conductor())
def characters(self):
r"""
Return the pair of characters (either of `\QQ_p^*` or of some quadratic
extension) corresponding to this representation.
EXAMPLES::
sage: f = [f for f in Newforms(63, 4, names='a') if f[2] == 1][0]
sage: f.local_component(3).characters()
[
Character of Q_3*, of level 1, mapping 2 |--> -1, 3 |--> d,
Character of Q_3*, of level 1, mapping 2 |--> -1, 3 |--> -d - 2
]
"""
minchars = self._min_twist.characters()
G = minchars[0].parent()
chi = self._chi
if self.species() == "Supercuspidal":
H = SmoothCharacterGroupQp(self.prime(), chi.base_ring())
Hchi = H.from_dirichlet(~chi)
Gchi = G.compose_with_norm(Hchi)
else:
Gchi = G.from_dirichlet(~chi)
return Sequence([c*Gchi for c in minchars], cr=True, universe=G)
def check_tempered(self):
r"""
Check that this representation is quasi-tempered, i.e. `\pi \otimes
|\det|^{j/2}` is tempered. It is well known that local components of
modular forms are *always* tempered, so this serves as a useful check
on our computations.
EXAMPLES::
sage: f = [f for f in Newforms(63, 4, names='a') if f[2] == 1][0]
sage: f.local_component(3).check_tempered()
"""
self.minimal_twist().check_tempered() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/local_comp/local_comp.py | 0.92627 | 0.776686 | local_comp.py | pypi |
from sage.modular.arithgroup.congroup_sl2z import is_SL2Z
from sage.modular.modform.constructor import EisensteinForms
from sage.modular.modform.eis_series import eisenstein_series_qexp
from sage.modular.modform.element import GradedModularFormElement
from sage.structure.element import ModuleElement
from sage.structure.richcmp import richcmp, op_NE, op_EQ
from sage.rings.polynomial.polynomial_element import Polynomial
class QuasiModularFormsElement(ModuleElement):
r"""
A quasimodular forms ring element. Such an element is describbed by SageMath
as a polynomial
.. MATH::
f_0 + f_1 E_2 + f_2 E_2^2 + \cdots + f_m E_2^m
where each `f_i` a graded modular form element
(see :class:`~sage.modular.modform.element.GradedModularFormElement`)
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: QM.gens()
[1 - 24*q - 72*q^2 - 96*q^3 - 168*q^4 - 144*q^5 + O(q^6),
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6),
1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 - 1575504*q^5 + O(q^6)]
sage: QM.0 + QM.1
2 + 216*q + 2088*q^2 + 6624*q^3 + 17352*q^4 + 30096*q^5 + O(q^6)
sage: QM.0 * QM.1
1 + 216*q - 3672*q^2 - 62496*q^3 - 322488*q^4 - 1121904*q^5 + O(q^6)
sage: (QM.0)^2
1 - 48*q + 432*q^2 + 3264*q^3 + 9456*q^4 + 21600*q^5 + O(q^6)
sage: QM.0 == QM.1
False
Quasimodular forms ring element can be created via a polynomial in `E2` over the ring of modular forms::
sage: E2 = QM.polygen()
sage: E2.parent()
Univariate Polynomial Ring in E2 over Ring of Modular Forms for Modular Group SL(2,Z) over Rational Field
sage: QM(E2)
1 - 24*q - 72*q^2 - 96*q^3 - 168*q^4 - 144*q^5 + O(q^6)
sage: M = QM.modular_forms_subring()
sage: QM(M.0 * E2 + M.1 * E2^2)
2 - 336*q + 4320*q^2 + 398400*q^3 - 3772992*q^4 - 89283168*q^5 + O(q^6)
One may convert a quasimodular form into a multivariate polynomial in the
generators of the ring by calling
:meth:`~sage.modular.quasimodform.element.QuasiModularFormsElement.polynomial`::
sage: QM = QuasiModularForms(1)
sage: F = QM.0^2 + QM.1^2 + QM.0*QM.1*QM.2
sage: F.polynomial()
E2*E4*E6 + E4^2 + E2^2
If the group is not the full modular group, the default names of the
generators are given by ``Ek_i`` and ``Sk_i`` to denote the `i`-th basis
element of the weight `k` Eisenstein subspace and cuspidal subspace
respectively (for more details, see the documentation of
:meth:`~sage.modular.quasimodform.ring.QuasiModularFormsRing.polynomial_ring`) ::
sage: QM = QuasiModularForms(Gamma1(4))
sage: F = (QM.0^4)*(QM.1^3) + QM.3
sage: F.polynomial()
-512*E2^4*E2_1^3 + E2^4*E3_0^2 + 48*E2^4*E3_1^2 + E3_0
"""
def __init__(self, parent, polynomial):
r"""
INPUT:
- ``parent`` - a quasimodular forms ring
- ``polynomial`` - a polynomial `f_0 + f_1 E_2 + ... + f_n E_2^n` where
each `f_i` are modular forms ring elements and `E_2` correspond to the
weight 2 Eisenstein series
OUTPUT:
``QuasiModularFormsElement``
TESTS::
sage: QM = QuasiModularForms(1)
sage: QM.element_class(QM, 'E2')
Traceback (most recent call last):
...
TypeError: 'polynomial' argument should be of type 'Polynomial'
sage: x = polygen(QQ)
sage: QM.element_class(QM, x^2 + 1)
Traceback (most recent call last):
...
ValueError: at least one coefficient is not a 'GradedModularFormElement'
"""
if not isinstance(polynomial, Polynomial):
raise TypeError("'polynomial' argument should be of type 'Polynomial'")
for f in polynomial.coefficients():
if not isinstance(f, GradedModularFormElement):
raise ValueError("at least one coefficient is not a 'GradedModularFormElement'")
self._polynomial = polynomial
ModuleElement.__init__(self, parent)
def q_expansion(self, prec=6):
r"""
Return the `q`-expansion of the given quasimodular form up to precision
``prec`` (default: 6).
An alias of this method is ``qexp``.
EXAMPLES::
sage: QM = QuasiModularForms()
sage: E2 = QM.0
sage: E2.q_expansion()
1 - 24*q - 72*q^2 - 96*q^3 - 168*q^4 - 144*q^5 + O(q^6)
sage: E2.q_expansion(prec=10)
1 - 24*q - 72*q^2 - 96*q^3 - 168*q^4 - 144*q^5 - 288*q^6 - 192*q^7 - 360*q^8 - 312*q^9 + O(q^10)
"""
E2 = eisenstein_series_qexp(2, prec=prec, K=self.base_ring(), normalization='constant') #normalization -> to force integer coefficients
coefficients = self._polynomial.coefficients(sparse=False)
return sum(f.q_expansion(prec=prec)*E2**idx for idx, f in enumerate(coefficients))
qexp = q_expansion # alias
def _repr_(self):
r"""
String representation of self.
TESTS::
sage: QM = QuasiModularForms()
sage: QM.0
1 - 24*q - 72*q^2 - 96*q^3 - 168*q^4 - 144*q^5 + O(q^6)
sage: QM.1
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6)
sage: QM.2
1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 - 1575504*q^5 + O(q^6)
"""
return str(self.q_expansion())
def _latex_(self):
r"""
Return a latex representation of ``self``.
TESTS::
sage: QM = QuasiModularForms(1)
sage: latex(QM.0)
1 - 24 q - 72 q^{2} - 96 q^{3} - 168 q^{4} - 144 q^{5} + O(q^{6})
"""
return self.q_expansion()._latex_()
def _richcmp_(self, other, op):
r"""
Compare self with other.
TESTS::
sage: QM = QuasiModularForms(1)
sage: QM.0 == QM.1
False
sage: QM.0 == QM.0
True
sage: QM.0 != QM.1
True
sage: QM.0 != QM.0
False
sage: QM.0 < QM.1
Traceback (most recent call last):
...
TypeError: invalid comparison between quasimodular forms ring elements
"""
if op != op_EQ and op != op_NE:
raise TypeError('invalid comparison between quasimodular forms ring elements')
return richcmp(self._polynomial, other._polynomial, op)
def _add_(self, other):
r"""
Addition of two ``QuasiModularFormElement``.
INPUT:
- ``other`` - ``QuasiModularFormElement``
OUTPUT: a ``QuasiModularFormElement``
TESTS::
sage: QM = QuasiModularForms(1)
sage: QM.0 + QM.1
2 + 216*q + 2088*q^2 + 6624*q^3 + 17352*q^4 + 30096*q^5 + O(q^6)
sage: QM.0 + (QM.1 + QM.2) == (QM.0 + QM.1) + QM.2
True
sage: QM = QuasiModularForms(5)
sage: QM.0 + QM.1 + QM.2 + QM.3
3 - 17*q - 54*q^2 - 62*q^3 - 98*q^4 + 137*q^5 + O(q^6)
"""
return self.__class__(self.parent(), self._polynomial + other._polynomial)
def __neg__(self):
r"""
The negation of ``self```
TESTS::
sage: -QuasiModularForms(1).0
-1 + 24*q + 72*q^2 + 96*q^3 + 168*q^4 + 144*q^5 + O(q^6)
sage: QuasiModularForms(1).0 - QuasiModularForms(1).0
0
sage: -QuasiModularForms(Gamma1(2)).2
-1 - 240*q^2 - 2160*q^4 + O(q^6)
"""
return self.__class__(self.parent(), -self._polynomial)
def _mul_(self, other):
r"""
The multiplication of two ``QuasiModularFormElement``
INPUT:
- ``other`` - ``QuasiModularFormElement``
OUTPUT: a ``QuasiModularFormElement``
TESTS::
sage: QM = QuasiModularForms(1)
sage: QM.0 * QM.1
1 + 216*q - 3672*q^2 - 62496*q^3 - 322488*q^4 - 1121904*q^5 + O(q^6)
sage: (QM.0 * QM.1) * QM.2 == QM.0 * (QM.1 * QM.2)
True
sage: QM = QuasiModularForms(Gamma1(5))
sage: QM.0 * QM.1 * QM.2
q - 24*q^2 - 66*q^3 - 189*q^4 - 1917*q^5 + O(q^6)
"""
return self.__class__(self.parent(), self._polynomial * other._polynomial)
def _lmul_(self, c):
r"""
The left action of the base ring on self.
INPUT:
- ``other`` - ``QuasiModularFormElement``
OUTPUT: a ``QuasiModularFormElement``
TESTS::
sage: QM = QuasiModularForms(1)
sage: (1/2) * QM.0
1/2 - 12*q - 36*q^2 - 48*q^3 - 84*q^4 - 72*q^5 + O(q^6)
sage: QM.0 * (3/2)
3/2 - 36*q - 108*q^2 - 144*q^3 - 252*q^4 - 216*q^5 + O(q^6)
sage: (5/2) * QuasiModularForms(Gamma0(7)).0 * (3/2)
15/4 - 90*q - 270*q^2 - 360*q^3 - 630*q^4 - 540*q^5 + O(q^6)
"""
return self.__class__(self.parent(), c * self._polynomial)
def __bool__(self):
r"""
Return whether ``self`` is non-zero.
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: bool(QM(0))
False
sage: bool(QM(1))
True
sage: bool(QM.0)
True
"""
return bool(self._polynomial)
def is_zero(self):
r"""
Return whether the given quasimodular form is zero.
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: QM.zero().is_zero()
True
sage: QM(0).is_zero()
True
sage: QM(1/2).is_zero()
False
sage: (QM.0).is_zero()
False
sage: QM = QuasiModularForms(Gamma0(2))
sage: QM(0).is_zero()
True
"""
return not self
def is_one(self):
r"""
Return whether the given quasimodular form is 1, i.e. the
multiplicative identity.
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: QM.one().is_one()
True
sage: QM(1).is_one()
True
sage: (QM.0).is_one()
False
sage: QM = QuasiModularForms(Gamma0(2))
sage: QM(1).is_one()
True
"""
return self._polynomial.is_one()
def is_graded_modular_form(self):
r"""
Return whether the given quasimodular form is a
graded modular form element
(see :class:`~sage.modular.modform.element.GradedModularFormElement`).
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: (QM.0).is_graded_modular_form()
False
sage: (QM.1).is_graded_modular_form()
True
sage: (QM.1 + QM.0^2).is_graded_modular_form()
False
sage: (QM.1^2 + QM.2).is_graded_modular_form()
True
sage: QM = QuasiModularForms(Gamma0(6))
sage: (QM.0).is_graded_modular_form()
False
sage: (QM.1 + QM.2 + QM.1 * QM.3).is_graded_modular_form()
True
sage: QM.zero().is_graded_modular_form()
True
sage: QM = QuasiModularForms(Gamma0(6))
sage: (QM.0).is_graded_modular_form()
False
sage: (QM.0 + QM.1*QM.2 + QM.3).is_graded_modular_form()
False
sage: (QM.1*QM.2 + QM.3).is_graded_modular_form()
True
.. NOTE::
A graded modular form in SageMath is not necessarily a modular form
as it can have mixed weight components. To check for modular forms
only, see the method :meth:`is_modular_form`.
"""
return self._polynomial.degree() <= 0
def is_modular_form(self):
r"""
Return whether the given quasimodular form is a modular form.
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: (QM.0).is_modular_form()
False
sage: (QM.1).is_modular_form()
True
sage: (QM.1 + QM.2).is_modular_form() # mixed weight components
False
sage: QM.zero().is_modular_form()
True
sage: QM = QuasiModularForms(Gamma0(4))
sage: (QM.0).is_modular_form()
False
sage: (QM.1).is_modular_form()
True
"""
return self._polynomial.degree() <= 0 and self._polynomial[0].is_modular_form()
def polynomial(self, names=None):
r"""
Return a multivariate polynomial such that every variable corresponds to
a generator of the ring, ordered by the method:
:meth:`~sage.modular.quasimodform.ring.QuasiModularForms.gens`.
An alias of this method is ``to_polynomial``.
INPUT:
- ``names`` (str, default: ``None``) -- a list or tuple of names
(strings), or a comma separated string. Defines the names for the
generators of the multivariate polynomial ring. The default names are
of the form ``ABCk`` where ``k`` is a number corresponding to the
weight of the form ``ABC``.
OUTPUT: A multivariate polynomial in the variables ``names``
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: (QM.0 + QM.1).polynomial()
E4 + E2
sage: (1/2 + QM.0 + 2*QM.1^2 + QM.0*QM.2).polynomial()
E2*E6 + 2*E4^2 + E2 + 1/2
Check that :trac:`34569` is fixed::
sage: QM = QuasiModularForms(Gamma1(3))
sage: QM.ngens()
5
sage: (QM.0 + QM.1 + QM.2*QM.1 + QM.3*QM.4).polynomial()
E3_1*E4_0 + E2_0*E3_0 + E2 + E2_0
"""
P = self.parent().polynomial_ring(names)
poly_gens = P.gens()
E2 = poly_gens[0]
poly_gens = poly_gens[1:]
modform_poly_gens = self.parent().modular_forms_subring().polynomial_ring(names='x').gens()
subs_dictionnary = {}
for idx, g in enumerate(modform_poly_gens):
subs_dictionnary[g] = poly_gens[idx]
return sum(f.to_polynomial().subs(subs_dictionnary) * E2 ** exp for exp, f in enumerate(self._polynomial.coefficients(sparse=False)))
to_polynomial = polynomial # alias
def weights_list(self):
r"""
Return the list of the weights of all the graded components of the given
graded quasimodular form.
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: (QM.0).weights_list()
[2]
sage: (QM.0 + QM.1 + QM.2).weights_list()
[2, 4, 6]
sage: (QM.0 * QM.1 + QM.2).weights_list()
[6]
sage: QM(1/2).weights_list()
[0]
sage: QM = QuasiModularForms(Gamma1(3))
sage: (QM.0 + QM.1 + QM.2*QM.1 + QM.3*QM.4).weights_list()
[2, 5, 7]
"""
return sorted(list(self.to_polynomial().homogeneous_components()))
def is_homogeneous(self):
r"""
Return whether the graded quasimodular form is a homogeneous element,
that is, it lives in a unique graded components of the parent of
``self``.
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: (QM.0).is_homogeneous()
True
sage: (QM.0 + QM.1).is_homogeneous()
False
sage: (QM.0 * QM.1 + QM.2).is_homogeneous()
True
sage: QM(1).is_homogeneous()
True
sage: (1 + QM.0).is_homogeneous()
False
sage: QM = QuasiModularForms(Gamma0(4))
sage: (QM.0).is_homogeneous()
True
sage: (QM.0 + QM.1).is_homogeneous()
True
sage: (QM.0 + QM.1 + QM.2).is_homogeneous()
True
sage: (QM.0 + QM.1^3).is_homogeneous()
False
"""
return len(self.weights_list()) == 1
def weight(self):
r"""
Return the weight of the given quasimodular form.
Note that the given form must be homogeneous.
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: (QM.0).weight()
2
sage: (QM.0 * QM.1 + QM.2).weight()
6
sage: QM(1/2).weight()
0
sage: (QM.0 + QM.1).weight()
Traceback (most recent call last):
...
ValueError: the given graded quasiform is not an homogeneous element
"""
if self.is_homogeneous():
return self.to_polynomial().degree()
else:
raise ValueError("the given graded quasiform is not an homogeneous element")
def homogeneous_components(self):
r"""
Return a dictionary where the values are the homogeneous components of
the given graded form and the keys are the weights of those components.
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: (QM.0).homogeneous_components()
{2: 1 - 24*q - 72*q^2 - 96*q^3 - 168*q^4 - 144*q^5 + O(q^6)}
sage: (QM.0 + QM.1 + QM.2).homogeneous_components()
{2: 1 - 24*q - 72*q^2 - 96*q^3 - 168*q^4 - 144*q^5 + O(q^6),
4: 1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6),
6: 1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 - 1575504*q^5 + O(q^6)}
sage: (1 + QM.0).homogeneous_components()
{0: 1, 2: 1 - 24*q - 72*q^2 - 96*q^3 - 168*q^4 - 144*q^5 + O(q^6)}
sage: QM = QuasiModularForms(Gamma0(5))
sage: F = QM.0 + QM.1 * QM.0 + QM.3^2*QM.0
sage: F.homogeneous_components()
{2: 1 - 24*q - 72*q^2 - 96*q^3 - 168*q^4 - 144*q^5 + O(q^6),
4: 1 - 18*q - 198*q^2 - 936*q^3 - 2574*q^4 - 5610*q^5 + O(q^6),
10: q^2 - 24*q^3 - 52*q^4 - 520*q^5 + O(q^6)}
"""
QM = self.parent()
poly_self = self.to_polynomial()
pol_hom_comp = poly_self.homogeneous_components()
return {k: QM.from_polynomial(pol) for k, pol in pol_hom_comp.items()}
def serre_derivative(self):
r"""
Return the Serre derivative of the given quasimodular form.
If the form is not homogeneous, then this method sums the Serre
derivative of each homogeneous component.
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: E2, E4, E6 = QM.gens()
sage: DE2 = E2.serre_derivative(); DE2
-1/6 - 16*q - 216*q^2 - 832*q^3 - 2248*q^4 - 4320*q^5 + O(q^6)
sage: DE2 == (-E2^2 - E4)/12
True
sage: DE4 = E4.serre_derivative(); DE4
-1/3 + 168*q + 5544*q^2 + 40992*q^3 + 177576*q^4 + 525168*q^5 + O(q^6)
sage: DE4 == (-1/3) * E6
True
sage: DE6 = E6.serre_derivative(); DE6
-1/2 - 240*q - 30960*q^2 - 525120*q^3 - 3963120*q^4 - 18750240*q^5 + O(q^6)
sage: DE6 == (-1/2) * E4^2
True
The Serre derivative raises the weight of homogeneous elements by 2::
sage: F = E6 + E4 * E2
sage: F.weight()
6
sage: F.serre_derivative().weight()
8
Check that :trac:`34569` is fixed::
sage: QM = QuasiModularForms(Gamma1(3))
sage: E2 = QM.weight_2_eisenstein_series()
sage: E2.serre_derivative()
-1/6 - 16*q - 216*q^2 - 832*q^3 - 2248*q^4 - 4320*q^5 + O(q^6)
sage: F = QM.0 + QM.1*QM.2
"""
# initial variables:
QM = self.parent()
R = QM.base_ring()
E2 = QM.gen(0)
if is_SL2Z(QM.group()):
E4 = QM.gen(1)
else:
E4 = QM(EisensteinForms(group=1, weight=4, base_ring=R).gen(0))
# compute the derivative of E2: q*dE2/dq
E2deriv = R(12).inverse_of_unit() * (E2 ** 2 - E4)
# sum the Serre derivative of each monomial of the form: f * E2^n
# they are equal to:
# [E2^n * serre_deriv(f)] + [n * f * E2^(n-1) * D(E2)] - [n/6 * f * E2^(n+1)]
# = A + B - C
der = QM.zero()
u6 = R(6).inverse_of_unit()
for n, f in enumerate(self._polynomial.coefficients(sparse=False)):
if n == 0:
der += QM(f.serre_derivative())
else:
A = (E2 ** n) * f.serre_derivative()
B = R(n) * f * E2 ** (n - 1) * E2deriv
C = R(n) * u6 * E2 ** (n + 1) * f
der += QM(A + B - C)
return der
def derivative(self):
r"""
Return the derivative `q \frac{d}{dq}` of the given quasimodular form.
If the form is not homogeneous, then this method sums the derivative of
each homogeneous component.
EXAMPLES::
sage: QM = QuasiModularForms(1)
sage: E2, E4, E6 = QM.gens()
sage: dE2 = E2.derivative(); dE2
-24*q - 144*q^2 - 288*q^3 - 672*q^4 - 720*q^5 + O(q^6)
sage: dE2 == (E2^2 - E4)/12 # Ramanujan identity
True
sage: dE4 = E4.derivative(); dE4
240*q + 4320*q^2 + 20160*q^3 + 70080*q^4 + 151200*q^5 + O(q^6)
sage: dE4 == (E2 * E4 - E6)/3 # Ramanujan identity
True
sage: dE6 = E6.derivative(); dE6
-504*q - 33264*q^2 - 368928*q^3 - 2130912*q^4 - 7877520*q^5 + O(q^6)
sage: dE6 == (E2 * E6 - E4^2)/2 # Ramanujan identity
True
Note that the derivative of a modular form is not necessarily a modular form::
sage: dE4.is_modular_form()
False
sage: dE4.weight()
6
"""
QM = self.parent()
E2 = QM.gen(0)
R = self.base_ring()
u = R(12).inverse_of_unit()
hom_comp = self.homogeneous_components()
return sum(f.serre_derivative() + R(k) * u * f * E2 for k, f in hom_comp.items()) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/quasimodform/element.py | 0.877556 | 0.642713 | element.py | pypi |
from sage.structure.element import AlgebraElement
from sage.structure.richcmp import richcmp, rich_to_bool
from sage.categories.homset import End
import sage.arith.all as arith
from sage.rings.integer import Integer
from . import algebra
from . import morphism
def is_HeckeOperator(x):
r"""
Return True if x is of type HeckeOperator.
EXAMPLES::
sage: from sage.modular.hecke.hecke_operator import is_HeckeOperator
sage: M = ModularSymbols(Gamma0(7), 4)
sage: is_HeckeOperator(M.T(3))
True
sage: is_HeckeOperator(M.T(3) + M.T(5))
False
"""
return isinstance(x, HeckeOperator)
def is_HeckeAlgebraElement(x):
r"""
Return True if x is of type HeckeAlgebraElement.
EXAMPLES::
sage: from sage.modular.hecke.hecke_operator import is_HeckeAlgebraElement
sage: M = ModularSymbols(Gamma0(7), 4)
sage: is_HeckeAlgebraElement(M.T(3))
True
sage: is_HeckeAlgebraElement(M.T(3) + M.T(5))
True
"""
return isinstance(x, HeckeAlgebraElement)
class HeckeAlgebraElement(AlgebraElement):
r"""
Base class for elements of Hecke algebras.
"""
def __init__(self, parent):
r"""
Create an element of a Hecke algebra.
EXAMPLES::
sage: R = ModularForms(Gamma0(7), 4).hecke_algebra()
sage: sage.modular.hecke.hecke_operator.HeckeAlgebraElement(R) # please don't do this!
Generic element of a structure
"""
if not algebra.is_HeckeAlgebra(parent):
raise TypeError("parent (=%s) must be a Hecke algebra"%parent)
AlgebraElement.__init__(self, parent)
def domain(self):
r"""
The domain of this operator. This is the Hecke module associated to the
parent Hecke algebra.
EXAMPLES::
sage: R = ModularForms(Gamma0(7), 4).hecke_algebra()
sage: sage.modular.hecke.hecke_operator.HeckeAlgebraElement(R).domain()
Modular Forms space of dimension 3 for Congruence Subgroup Gamma0(7) of weight 4 over Rational Field
"""
return self.parent().module()
def codomain(self):
r"""
The codomain of this operator. This is the Hecke module associated to the
parent Hecke algebra.
EXAMPLES::
sage: R = ModularForms(Gamma0(7), 4).hecke_algebra()
sage: sage.modular.hecke.hecke_operator.HeckeAlgebraElement(R).codomain()
Modular Forms space of dimension 3 for Congruence Subgroup Gamma0(7) of weight 4 over Rational Field
"""
return self.parent().module()
def hecke_module_morphism(self):
"""
Return the endomorphism of Hecke modules defined by the matrix
attached to this Hecke operator.
EXAMPLES::
sage: M = ModularSymbols(Gamma1(13))
sage: t = M.hecke_operator(2)
sage: t
Hecke operator T_2 on Modular Symbols space of dimension 15 for Gamma_1(13) of weight 2 with sign 0 over Rational Field
sage: t.hecke_module_morphism()
Hecke module morphism T_2 defined by the matrix
[ 2 0 0 0 0 0 0 1 0 0 1 0 0 0 0]
[ 0 2 0 1 0 1 0 0 -1 0 0 0 0 0 1]
[ 0 1 2 0 0 0 0 0 0 0 0 -1 1 0 0]
[ 1 0 0 2 0 -1 1 0 1 0 -1 1 -1 0 0]
[ 0 0 1 0 2 0 -1 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0 0 0 1 -2 2 -1]
[ 0 0 0 0 0 2 -1 0 -1 0 0 0 0 1 0]
[ 0 0 0 0 1 0 0 2 0 0 0 0 0 0 -1]
[ 0 0 0 0 0 1 0 0 -1 0 2 -1 0 2 -1]
[ 0 0 0 0 0 1 1 0 0 -1 0 1 -1 2 0]
[ 0 0 0 0 0 2 0 0 -1 -1 1 -1 0 1 0]
[ 0 0 0 0 0 1 1 0 1 0 0 0 -1 1 0]
[ 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0]
[ 0 0 0 0 0 1 0 0 1 -1 2 0 0 0 -1]
[ 0 0 0 0 0 0 0 0 0 1 0 -1 2 0 -1]
Domain: Modular Symbols space of dimension 15 for Gamma_1(13) of weight ...
Codomain: Modular Symbols space of dimension 15 for Gamma_1(13) of weight ...
"""
try:
return self.__hecke_module_morphism
except AttributeError:
T = self.matrix()
M = self.domain()
H = End(M)
if isinstance(self, HeckeOperator):
name = "T_%s"%self.index()
else:
name = ""
self.__hecke_module_morphism = morphism.HeckeModuleMorphism_matrix(H, T, name)
return self.__hecke_module_morphism
def _add_(self, other):
"""
Add self to other.
EXAMPLES::
sage: M = ModularSymbols(11)
sage: t = M.hecke_operator(2)
sage: t
Hecke operator T_2 on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field
sage: t + t # indirect doctest
Hecke operator on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field defined by:
[ 6 0 -2]
[ 0 -4 0]
[ 0 0 -4]
We can also add Hecke operators with different indexes::
sage: M = ModularSymbols(Gamma1(6),4)
sage: t2 = M.hecke_operator(2); t3 = M.hecke_operator(3)
sage: t2 + t3
Hecke operator on Modular Symbols space of dimension 6 for Gamma_1(6) of weight 4 with sign 0 over Rational Field defined by:
[ 35 0 0 8/5 8/5 -16/5]
[ 4 28 0 -19/5 -19/5 38/5]
[ 18 0 9 -6 8 -2]
[ 0 18 4 -23/5 -13/5 46/5]
[ 0 18 4 2/5 -38/5 46/5]
[ 0 18 4 2/5 -13/5 21/5]
sage: (t2 - t3).charpoly('x')
x^6 + 36*x^5 + 104*x^4 - 3778*x^3 + 7095*x^2 - 3458*x
"""
return self.parent()(self.matrix() + other.matrix(), check=False)
def __call__(self, x):
"""
Apply this Hecke operator to `x`.
EXAMPLES::
sage: M = ModularSymbols(11); t2 = M.hecke_operator(2)
sage: t2(M.gen(0))
3*(1,0) - (1,9)
::
sage: t2 = M.hecke_operator(2); t3 = M.hecke_operator(3)
sage: t3(t2(M.gen(0)))
12*(1,0) - 2*(1,9)
sage: (t3*t2)(M.gen(0))
12*(1,0) - 2*(1,9)
"""
T = self.hecke_module_morphism()
return T(x)
def __rmul__(self, left):
"""
EXAMPLES::
sage: M = ModularSymbols(11); t2 = M.hecke_operator(2)
sage: 2*t2
Hecke operator on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field defined by:
[ 6 0 -2]
[ 0 -4 0]
[ 0 0 -4]
"""
return self.parent()(left * self.matrix())
def _sub_(self, other):
"""
Compute the difference of self and other, where other has already been
coerced into the parent of self.
EXAMPLES::
sage: M = ModularSymbols(Gamma1(6),4)
sage: t2 = M.hecke_operator(2); t3 = M.hecke_operator(3)
sage: t2 - t3 # indirect doctest
Hecke operator on Modular Symbols space of dimension 6 for Gamma_1(6) of weight 4 with sign 0 over Rational Field defined by:
[ -19 0 0 -4/5 -4/5 8/5]
[ 4 -26 0 17/5 17/5 -34/5]
[ -18 0 7 -18/5 12/5 6/5]
[ 0 -18 4 3/5 23/5 -26/5]
[ 0 -18 4 -2/5 28/5 -26/5]
[ 0 -18 4 -2/5 23/5 -21/5]
"""
return self.parent()(self.matrix() - other.matrix(), check=False)
def apply_sparse(self, x):
"""
Apply this Hecke operator to x, where we avoid computing the matrix
of x if possible.
EXAMPLES::
sage: M = ModularSymbols(11)
sage: T = M.hecke_operator(23)
sage: T.apply_sparse(M.gen(0))
24*(1,0) - 5*(1,9)
"""
if x not in self.domain():
raise TypeError("x (=%s) must be in %s"%(x, self.domain()))
# Generic implementation which doesn't actually do anything
# special regarding sparseness. Override this for speed.
T = self.hecke_module_morphism()
return T(x)
def charpoly(self, var='x'):
"""
Return the characteristic polynomial of this Hecke operator.
INPUT:
- ``var`` - string (default: 'x')
OUTPUT: a monic polynomial in the given variable.
EXAMPLES::
sage: M = ModularSymbols(Gamma1(6),4)
sage: M.hecke_operator(2).charpoly('x')
x^6 - 14*x^5 + 29*x^4 + 172*x^3 - 124*x^2 - 320*x + 256
"""
return self.matrix().charpoly(var)
def decomposition(self):
"""
Decompose the Hecke module under the action of this Hecke
operator.
EXAMPLES::
sage: M = ModularSymbols(11)
sage: t2 = M.hecke_operator(2)
sage: t2.decomposition()
[
Modular Symbols subspace of dimension 1 of Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field,
Modular Symbols subspace of dimension 2 of Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field
]
::
sage: M = ModularSymbols(33, sign=1).new_submodule()
sage: T = M.hecke_operator(2)
sage: T.decomposition()
[
Modular Symbols subspace of dimension 1 of Modular Symbols space of dimension 6 for Gamma_0(33) of weight 2 with sign 1 over Rational Field,
Modular Symbols subspace of dimension 1 of Modular Symbols space of dimension 6 for Gamma_0(33) of weight 2 with sign 1 over Rational Field
]
"""
try:
return self.__decomposition
except AttributeError:
pass
if isinstance(self, HeckeOperator) and \
arith.gcd(self.index(), self.domain().level()) == 1:
D = self.hecke_module_morphism().decomposition(is_diagonalizable=True)
else:
# TODO: There are other weaker hypotheses that imply diagonalizability.
D = self.hecke_module_morphism().decomposition()
D.sort()
D.set_immutable()
self.__decomposition = D
return D
def det(self):
"""
Return the determinant of this Hecke operator.
EXAMPLES::
sage: M = ModularSymbols(23)
sage: T = M.hecke_operator(3)
sage: T.det()
100
"""
return self.hecke_module_morphism().det()
def fcp(self, var='x'):
"""
Return the factorization of the characteristic polynomial of this
Hecke operator.
EXAMPLES::
sage: M = ModularSymbols(23)
sage: T = M.hecke_operator(3)
sage: T.fcp('x')
(x - 4) * (x^2 - 5)^2
"""
return self.hecke_module_morphism().fcp(var)
def image(self):
"""
Return the image of this Hecke operator.
EXAMPLES::
sage: M = ModularSymbols(23)
sage: T = M.hecke_operator(3)
sage: T.fcp('x')
(x - 4) * (x^2 - 5)^2
sage: T.image()
Modular Symbols subspace of dimension 5 of Modular Symbols space of dimension 5 for Gamma_0(23) of weight 2 with sign 0 over Rational Field
sage: (T-4).image()
Modular Symbols subspace of dimension 4 of Modular Symbols space of dimension 5 for Gamma_0(23) of weight 2 with sign 0 over Rational Field
sage: (T**2-5).image()
Modular Symbols subspace of dimension 1 of Modular Symbols space of dimension 5 for Gamma_0(23) of weight 2 with sign 0 over Rational Field
"""
return self.hecke_module_morphism().image()
def kernel(self):
"""
Return the kernel of this Hecke operator.
EXAMPLES::
sage: M = ModularSymbols(23)
sage: T = M.hecke_operator(3)
sage: T.fcp('x')
(x - 4) * (x^2 - 5)^2
sage: T.kernel()
Modular Symbols subspace of dimension 0 of Modular Symbols space of dimension 5 for Gamma_0(23) of weight 2 with sign 0 over Rational Field
sage: (T-4).kernel()
Modular Symbols subspace of dimension 1 of Modular Symbols space of dimension 5 for Gamma_0(23) of weight 2 with sign 0 over Rational Field
sage: (T**2-5).kernel()
Modular Symbols subspace of dimension 4 of Modular Symbols space of dimension 5 for Gamma_0(23) of weight 2 with sign 0 over Rational Field
"""
return self.hecke_module_morphism().kernel()
def trace(self):
"""
Return the trace of this Hecke operator.
::
sage: M = ModularSymbols(1,12)
sage: T = M.hecke_operator(2)
sage: T.trace()
2001
"""
return self.hecke_module_morphism().trace()
def __getitem__(self, ij):
"""
EXAMPLES::
sage: M = ModularSymbols(1,12)
sage: T = M.hecke_operator(2).matrix_form()
sage: T[0,0]
-24
"""
return self.matrix()[ij]
class HeckeAlgebraElement_matrix(HeckeAlgebraElement):
r"""
An element of the Hecke algebra represented by a matrix.
"""
def __init__(self, parent, A):
r"""
Initialise an element from a matrix. This *must* be over the base ring
of self and have the right size.
This is a bit overkill as similar checks will be performed by the call
and coerce methods of the parent of self, but it can't hurt to be
paranoid. Any fancy coercion / base_extension / etc happens there, not
here.
TESTS::
sage: T = ModularForms(Gamma0(7), 4).hecke_algebra()
sage: M = sage.modular.hecke.hecke_operator.HeckeAlgebraElement_matrix(T, matrix(QQ,3,[2,3,0,1,2,3,7,8,9])); M
Hecke operator on Modular Forms space of dimension 3 for Congruence Subgroup Gamma0(7) of weight 4 over Rational Field defined by:
[2 3 0]
[1 2 3]
[7 8 9]
sage: loads(dumps(M)) == M
True
sage: sage.modular.hecke.hecke_operator.HeckeAlgebraElement_matrix(T, matrix(Integers(2),3,[2,3,0,1,2,3,7,8,9]))
Traceback (most recent call last):
...
TypeError: base ring of matrix (Ring of integers modulo 2) does not match base ring of space (Rational Field)
sage: sage.modular.hecke.hecke_operator.HeckeAlgebraElement_matrix(T, matrix(QQ,2,[2,3,0,1]))
Traceback (most recent call last):
...
TypeError: A must be a square matrix of rank 3
"""
HeckeAlgebraElement.__init__(self, parent)
from sage.structure.element import is_Matrix
if not is_Matrix(A):
raise TypeError("A must be a matrix")
if not A.base_ring() == self.parent().base_ring():
raise TypeError("base ring of matrix (%s) does not match base ring of space (%s)" % (A.base_ring(), self.parent().base_ring()))
if not A.nrows() == A.ncols() == self.parent().module().rank():
raise TypeError("A must be a square matrix of rank %s" % self.parent().module().rank())
self.__matrix = A
def _richcmp_(self, other, op):
r"""
Compare self to other, where the coercion model has already ensured
that other has the same parent as self.
EXAMPLES::
sage: T = ModularForms(SL2Z, 12).hecke_algebra()
sage: m = T(matrix(QQ, 2, [1,2,0,1]), check=False); n = T.hecke_operator(14)
sage: m == n
False
sage: m == n.matrix_form()
False
sage: n.matrix_form() == T(matrix(QQ, 2, [401856,0,0,4051542498456]), check=False)
True
"""
if not isinstance(other, HeckeAlgebraElement_matrix):
if isinstance(other, HeckeOperator):
return richcmp(self, other.matrix_form(), op)
else:
raise RuntimeError("Bug in coercion code") # can't get here
return richcmp(self.__matrix, other.__matrix, op)
def _repr_(self):
r"""
String representation of self.
EXAMPLES::
sage: M = ModularSymbols(1,12)
sage: M.hecke_operator(2).matrix_form()._repr_()
'Hecke operator on Modular Symbols space of dimension 3 for Gamma_0(1) of weight 12 with sign 0 over Rational Field defined by:\n[ -24 0 0]\n[ 0 -24 0]\n[4860 0 2049]'
sage: ModularForms(Gamma0(100)).hecke_operator(4).matrix_form()._repr_()
'Hecke operator on Modular Forms space of dimension 24 for Congruence Subgroup Gamma0(100) of weight 2 over Rational Field defined by:\n24 x 24 dense matrix over Rational Field'
"""
return "Hecke operator on %s defined by:\n%r" % (self.parent().module(), self.__matrix)
def _latex_(self):
r"""
Latex representation of self (just prints the matrix)
EXAMPLES::
sage: M = ModularSymbols(1,12)
sage: M.hecke_operator(2).matrix_form()._latex_()
'\\left(\\begin{array}{rrr}\n-24 & 0 & 0 \\\\\n0 & -24 & 0 \\\\\n4860 & 0 & 2049\n\\end{array}\\right)'
"""
return self.__matrix._latex_()
def matrix(self):
"""
Return the matrix that defines this Hecke algebra element.
EXAMPLES::
sage: M = ModularSymbols(1,12)
sage: T = M.hecke_operator(2).matrix_form()
sage: T.matrix()
[ -24 0 0]
[ 0 -24 0]
[4860 0 2049]
"""
return self.__matrix
def _mul_(self, other):
r"""
Multiply self by other (which has already been coerced into an element
of the parent of self).
EXAMPLES::
sage: M = ModularSymbols(1,12)
sage: T = M.hecke_operator(2).matrix_form()
sage: T * T # indirect doctest
Hecke operator on Modular Symbols space of dimension 3 for Gamma_0(1) of weight 12 with sign 0 over Rational Field defined by:
[ 576 0 0]
[ 0 576 0]
[9841500 0 4198401]
"""
return self.parent()(other.matrix() * self.matrix(), check=False)
class DiamondBracketOperator(HeckeAlgebraElement_matrix):
r"""
The diamond bracket operator `\langle d \rangle` for some `d \in \ZZ /
N\ZZ` (which need not be a unit, although if it is not, the operator will
be zero).
"""
def __init__(self, parent, d):
r"""
Standard init function.
EXAMPLES::
sage: M = ModularSymbols(Gamma1(5),6)
sage: d = M.diamond_bracket_operator(2); d # indirect doctest
Diamond bracket operator <2> on Modular Symbols space of dimension 10 for Gamma_1(5) of weight 6 with sign 0 over Rational Field
sage: type(d)
<class 'sage.modular.hecke.hecke_operator.DiamondBracketOperator'>
sage: d.matrix()
[ 0 1 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 1]
[ 0 0 0 0 0 0 0 1 0 0]
[ 0 0 17/16 11/16 -3/4 -1 17/16 -3/4 0 11/16]
[ 0 0 1 0 0 0 0 0 0 0]
[ 0 0 0 0 1 0 0 0 0 0]
[ 0 0 -1/2 1/2 1 0 -1/2 1 -1 1/2]
[ 0 0 0 1 0 0 0 0 0 0]
sage: d**4 == 1
True
"""
self.__d = d
A = parent.diamond_bracket_matrix(d)
HeckeAlgebraElement_matrix.__init__(self, parent, A)
def _repr_(self):
r"""
EXAMPLES::
sage: ModularSymbols(Gamma1(5), 6).diamond_bracket_operator(2)._repr_()
'Diamond bracket operator <2> on Modular Symbols space of dimension 10 for Gamma_1(5) of weight 6 with sign 0 over Rational Field'
"""
return "Diamond bracket operator <%s> on %s" % (self.__d, self.domain())
def _latex_(self):
r"""
EXAMPLES::
sage: latex(ModularSymbols(Gamma1(5), 12).diamond_bracket_operator(2)) # indirect doctest
\langle 2 \rangle
"""
return r"\langle %s \rangle" % self.__d
class HeckeOperator(HeckeAlgebraElement):
r"""
The Hecke operator `T_n` for some `n` (which need not be coprime to the
level). The matrix is not computed until it is needed.
"""
def __init__(self, parent, n):
"""
EXAMPLES::
sage: M = ModularSymbols(11)
sage: H = M.hecke_operator(2005); H
Hecke operator T_2005 on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field
sage: H == loads(dumps(H))
True
We create a Hecke operator of large index (greater than 32 bits)::
sage: M1 = ModularSymbols(21,2)
sage: M1.hecke_operator(13^9)
Hecke operator T_10604499373 on Modular Symbols space of dimension 5 for Gamma_0(21) of weight 2 with sign 0 over Rational Field
"""
HeckeAlgebraElement.__init__(self, parent)
if not isinstance(n, (int, Integer)):
raise TypeError("n must be an int")
self.__n = int(n)
def _richcmp_(self, other, op):
r"""
Compare self and other (where the coercion model has already ensured
that self and other have the same parent). Hecke operators on the same
space compare as equal if and only if their matrices are equal, so we
check if the indices are the same and if not we compute the matrices
(which is potentially expensive).
EXAMPLES::
sage: M = ModularSymbols(Gamma0(7), 4)
sage: m = M.hecke_operator(3)
sage: m == m
True
sage: m == 2*m
False
sage: m == M.hecke_operator(5)
False
These last two tests involve a coercion::
sage: m == m.matrix_form()
True
sage: m == m.matrix()
False
"""
if not isinstance(other, HeckeOperator):
if isinstance(other, HeckeAlgebraElement_matrix):
return richcmp(self.matrix_form(), other, op)
else:
raise RuntimeError("Bug in coercion code") # can't get here
if self.__n == other.__n:
return rich_to_bool(op, 0)
return richcmp(self.matrix(), other.matrix(), op)
def _repr_(self):
r"""
String representation of self
EXAMPLES::
sage: ModularSymbols(Gamma0(7), 4).hecke_operator(6)._repr_()
'Hecke operator T_6 on Modular Symbols space of dimension 4 for Gamma_0(7) of weight 4 with sign 0 over Rational Field'
"""
return "Hecke operator T_%s on %s"%(self.__n, self.domain())
def _latex_(self):
r"""
LaTeX representation of self
EXAMPLES::
sage: ModularSymbols(Gamma0(7), 4).hecke_operator(6)._latex_()
'T_{6}'
"""
return "T_{%s}"%self.__n
def _mul_(self, other):
"""
Multiply this Hecke operator by another element of the same algebra. If
the other element is of the form `T_m` for some m, we check whether the
product is equal to `T_{mn}` and return that; if the product is not
(easily seen to be) of the form `T_{mn}`, then we calculate the product
of the two matrices and return a Hecke algebra element defined by that.
EXAMPLES: We create the space of modular symbols of level
`11` and weight `2`, then compute `T_2`
and `T_3` on it, along with their composition.
::
sage: M = ModularSymbols(11)
sage: t2 = M.hecke_operator(2); t3 = M.hecke_operator(3)
sage: t2*t3 # indirect doctest
Hecke operator T_6 on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field
sage: t3.matrix() * t2.matrix()
[12 0 -2]
[ 0 2 0]
[ 0 0 2]
sage: (t2*t3).matrix()
[12 0 -2]
[ 0 2 0]
[ 0 0 2]
When we compute `T_2^5` the result is not (easily seen to
be) a Hecke operator of the form `T_n`, so it is returned
as a Hecke module homomorphism defined as a matrix::
sage: t2**5
Hecke operator on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field defined by:
[243 0 -55]
[ 0 -32 0]
[ 0 0 -32]
"""
if isinstance(other, HeckeOperator) and other.parent() == self.parent():
n = None
if arith.gcd(self.__n, other.__n) == 1:
n = self.__n * other.__n
else:
P = set(arith.prime_divisors(self.domain().level()))
if P.issubset(set(arith.prime_divisors(self.__n))) and \
P.issubset(set(arith.prime_divisors(other.__n))):
n = self.__n * other.__n
if n:
return HeckeOperator(self.parent(), n)
# otherwise
return self.matrix_form() * other
def index(self):
"""
Return the index of this Hecke operator, i.e., if this Hecke
operator is `T_n`, return the int `n`.
EXAMPLES::
sage: T = ModularSymbols(11).hecke_operator(17)
sage: T.index()
17
"""
return self.__n
def matrix(self, *args, **kwds):
"""
Return the matrix underlying this Hecke operator.
EXAMPLES::
sage: T = ModularSymbols(11).hecke_operator(17)
sage: T.matrix()
[18 0 -4]
[ 0 -2 0]
[ 0 0 -2]
"""
try:
return self.__matrix
except AttributeError:
self.__matrix = self.parent().hecke_matrix(self.__n, *args, **kwds)
return self.__matrix
def matrix_form(self):
"""
Return the matrix form of this element of a Hecke algebra.
::
sage: T = ModularSymbols(11).hecke_operator(17)
sage: T.matrix_form()
Hecke operator on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field defined by:
[18 0 -4]
[ 0 -2 0]
[ 0 0 -2]
"""
try:
return self.__matrix_form
except AttributeError:
self.__matrix_form = self.parent()(self.matrix(), check=False)
return self.__matrix_form | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/hecke/hecke_operator.py | 0.785843 | 0.422624 | hecke_operator.py | pypi |
from . import morphism
class DegeneracyMap(morphism.HeckeModuleMorphism_matrix):
"""
A degeneracy map between Hecke modules of different levels.
EXAMPLES:
We construct a number of degeneracy maps::
sage: M = ModularSymbols(33)
sage: d = M.degeneracy_map(11)
sage: d
Hecke module morphism degeneracy map corresponding to f(q) |--> f(q) defined by the matrix
[ 1 0 0]
[ 0 0 1]
[ 0 0 -1]
[ 0 1 -1]
[ 0 0 1]
[ 0 -1 1]
[-1 0 0]
[-1 0 0]
[-1 0 0]
Domain: Modular Symbols space of dimension 9 for Gamma_0(33) of weight ...
Codomain: Modular Symbols space of dimension 3 for Gamma_0(11) of weight ...
sage: d.t()
1
sage: d = M.degeneracy_map(11,3)
sage: d.t()
3
The parameter d must be a divisor of the quotient of the two levels::
sage: d = M.degeneracy_map(11,2)
Traceback (most recent call last):
...
ValueError: the level of self (=33) must be a divisor or multiple of level (=11) and t (=2) must be a divisor of the quotient
Degeneracy maps can also go from lower level to higher level::
sage: M.degeneracy_map(66,2)
Hecke module morphism degeneracy map corresponding to f(q) |--> f(q^2) defined by the matrix
[ 2 0 0 0 0 0 1 0 0 0 1 -1 0 0 0 -1 1 0 0 0 0 0 0 0 -1]
[ 0 0 1 -1 0 -1 1 0 -1 2 0 0 0 -1 0 0 -1 1 2 -2 0 0 0 -1 1]
[ 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 -1 1 0 0 -1 1 0 0 0]
[ 0 0 0 0 0 0 0 0 0 2 -1 0 0 1 0 0 -1 1 0 0 1 0 -1 -1 1]
[ 0 -1 0 0 1 0 0 0 0 0 0 1 0 0 1 1 -1 0 0 -1 0 0 0 0 0]
[ 0 0 0 0 0 0 0 1 -1 0 0 2 -1 0 0 1 0 0 0 -1 0 -1 1 -1 1]
[ 0 0 0 0 1 -1 0 1 -1 0 0 0 0 0 -1 2 0 0 0 0 1 0 1 0 0]
[ 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0]
[ 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 1 1 1 0 0 0]
Domain: Modular Symbols space of dimension 9 for Gamma_0(33) of weight ...
Codomain: Modular Symbols space of dimension 25 for Gamma_0(66) of weight ...
"""
def __init__(self, matrix, domain, codomain, t):
r"""
Initialise a degeneracy map.
EXAMPLES::
sage: D = ModularSymbols(Gamma0(100)).degeneracy_map(2,5); D
Hecke module morphism degeneracy map corresponding to f(q) |--> f(q^5) defined by the matrix
31 x 1 dense matrix over Rational Field
Domain: Modular Symbols space of dimension 31 for Gamma_0(100) of weight ...
Codomain: Modular Symbols space of dimension 1 for Gamma_0(2) of weight ...
sage: D == loads(dumps(D))
True
"""
self.__t = t
H = domain.Hom(codomain)
if t == 1:
pow = ""
else:
pow = "^%s"%t
name = "degeneracy map corresponding to f(q) |--> f(q%s)"%(pow)
morphism.HeckeModuleMorphism_matrix.__init__(self, H, matrix, name)
def t(self):
"""
Return the divisor of the quotient of the two levels
associated to the degeneracy map.
EXAMPLES::
sage: M = ModularSymbols(33)
sage: d = M.degeneracy_map(11,3)
sage: d.t()
3
sage: d = M.degeneracy_map(11,1)
sage: d.t()
1
"""
return self.__t | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/hecke/degenmap.py | 0.756447 | 0.507202 | degenmap.py | pypi |
import sage.rings.infinity
from sage.matrix.constructor import matrix
from sage.arith.functions import lcm
from sage.arith.misc import gcd
from sage.misc.latex import latex
from sage.matrix.matrix_space import MatrixSpace
from sage.rings.ring import CommutativeAlgebra
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.structure.element import Element
from sage.structure.unique_representation import CachedRepresentation
from sage.misc.cachefunc import cached_method
from sage.structure.richcmp import richcmp_method, richcmp
def is_HeckeAlgebra(x):
r"""
Return True if x is of type HeckeAlgebra.
EXAMPLES::
sage: from sage.modular.hecke.algebra import is_HeckeAlgebra
sage: is_HeckeAlgebra(CuspForms(1, 12).anemic_hecke_algebra())
True
sage: is_HeckeAlgebra(ZZ)
False
"""
return isinstance(x, HeckeAlgebra_base)
def _heckebasis(M):
r"""
Return a basis of the Hecke algebra of M as a ZZ-module.
INPUT:
- ``M`` -- a Hecke module
OUTPUT:
a list of Hecke algebra elements represented as matrices
EXAMPLES::
sage: M = ModularSymbols(11,2,1)
sage: sage.modular.hecke.algebra._heckebasis(M)
[Hecke operator on Modular Symbols space of dimension 2 for Gamma_0(11) of weight 2 with sign 1 over Rational Field defined by:
[1 0]
[0 1],
Hecke operator on Modular Symbols space of dimension 2 for Gamma_0(11) of weight 2 with sign 1 over Rational Field defined by:
[0 2]
[0 5]]
"""
d = M.rank()
WW = ZZ**(d**2)
MM = MatrixSpace(QQ, d)
S = []
Denom = []
B = []
B1 = []
for i in range(1, M.hecke_bound() + 1):
v = M.hecke_operator(i).matrix()
den = v.denominator()
Denom.append(den)
S.append(v)
den = lcm(Denom)
for m in S:
B.append(WW((den * m).list()))
UU = WW.submodule(B)
B = UU.basis()
for u in B:
u1 = u.list()
m1 = M.hecke_algebra()(MM(u1), check=False)
B1.append((1 / den) * m1)
return B1
@richcmp_method
class HeckeAlgebra_base(CachedRepresentation, CommutativeAlgebra):
"""
Base class for algebras of Hecke operators on a fixed Hecke module.
INPUT:
- ``M`` - a Hecke module
EXAMPLES::
sage: CuspForms(1, 12).hecke_algebra() # indirect doctest
Full Hecke algebra acting on Cuspidal subspace of dimension 1 of Modular Forms space of dimension 2 for Modular Group SL(2,Z) of weight 12 over Rational Field
"""
@staticmethod
def __classcall__(cls, M):
r"""
We need to work around a problem originally discovered by David
Loeffler on 2009-04-13: The problem is that if one creates two
subspaces of a Hecke module which are equal as subspaces but have
different bases, then the caching machinery needs to distinguish
between them. So we need to add ``basis_matrix`` to the cache key even
though it is not looked at by the constructor.
TESTS:
We test that coercion is OK between the Hecke algebras associated to two submodules which are equal but have different bases::
sage: M = CuspForms(Gamma0(57))
sage: f1,f2,f3 = M.newforms()
sage: N1 = M.submodule(M.free_module().submodule_with_basis([f1.element().element(), f2.element().element()]))
sage: N2 = M.submodule(M.free_module().submodule_with_basis([f1.element().element(), (f1.element() + f2.element()).element()]))
sage: N1.hecke_operator(5).matrix_form()
Hecke operator on Modular Forms subspace of dimension 2 of ... defined by:
[-3 0]
[ 0 1]
sage: N2.hecke_operator(5).matrix_form()
Hecke operator on Modular Forms subspace of dimension 2 of ... defined by:
[-3 0]
[-4 1]
sage: N1.hecke_algebra()(N2.hecke_operator(5)).matrix_form()
Hecke operator on Modular Forms subspace of dimension 2 of ... defined by:
[-3 0]
[ 0 1]
sage: N1.hecke_algebra()(N2.hecke_operator(5).matrix_form())
Hecke operator on Modular Forms subspace of dimension 2 of ... defined by:
[-3 0]
[ 0 1]
"""
if isinstance(M, tuple):
M = M[0]
try:
M = (M, M.basis_matrix())
except AttributeError:
# The AttributeError occurs if M is not a free module; then it might not have a basis_matrix method
pass
return super().__classcall__(cls, M)
def __init__(self, M):
"""
Initialization.
EXAMPLES::
sage: from sage.modular.hecke.algebra import HeckeAlgebra_base
sage: type(HeckeAlgebra_base(CuspForms(1, 12)))
<class 'sage.modular.hecke.algebra.HeckeAlgebra_base_with_category'>
"""
if isinstance(M, tuple):
M = M[0]
from . import module
if not module.is_HeckeModule(M):
raise TypeError("M (=%s) must be a HeckeModule" % M)
self.__M = M
CommutativeAlgebra.__init__(self, M.base_ring())
def _an_element_impl(self):
r"""
Return an element of this algebra. Used by the coercion machinery.
EXAMPLES::
sage: CuspForms(1, 12).hecke_algebra().an_element() # indirect doctest
Hecke operator T_2 on Cuspidal subspace of dimension 1 of Modular Forms space of dimension 2 for Modular Group SL(2,Z) of weight 12 over Rational Field
"""
return self.hecke_operator(self.level() + 1)
def __call__(self, x, check=True):
r"""
Convert x into an element of this Hecke algebra. Here x is either:
- an element of a Hecke algebra equal to this one
- an element of the corresponding anemic Hecke algebra, if x is a full
Hecke algebra
- an element of the corresponding full Hecke algebra of the
form `T_i` where i is coprime to ``self.level()``, if self
is an anemic Hecke algebra
- something that can be converted into an element of the
underlying matrix space.
In the last case, the parameter ``check`` controls whether or
not to check that this element really does lie in the
appropriate algebra. At present, setting ``check=True`` raises
a NotImplementedError unless x is a scalar (or a diagonal
matrix).
EXAMPLES::
sage: T = ModularSymbols(11).hecke_algebra()
sage: T.gen(2) in T
True
sage: 5 in T
True
sage: T.gen(2).matrix() in T
Traceback (most recent call last):
...
NotImplementedError: Membership testing for '...' not implemented
sage: T(T.gen(2).matrix(), check=False)
Hecke operator on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field defined by:
[ 3 0 -1]
[ 0 -2 0]
[ 0 0 -2]
sage: A = ModularSymbols(11).anemic_hecke_algebra()
sage: A(T.gen(3))
Hecke operator T_3 on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field
sage: A(T.gen(11))
Traceback (most recent call last):
...
TypeError: Don't know how to construct an element of Anemic Hecke algebra acting on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field from Hecke operator T_11 on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field
"""
from . import hecke_operator
try:
if not isinstance(x, Element):
x = self.base_ring()(x)
if x.parent() is self:
return x
elif hecke_operator.is_HeckeOperator(x):
if x.parent() == self \
or (not self.is_anemic() and x.parent() == self.anemic_subalgebra()) \
or (self.is_anemic() and x.parent().anemic_subalgebra() == self and gcd(x.index(), self.level()) == 1):
return hecke_operator.HeckeOperator(self, x.index())
else:
raise TypeError
elif hecke_operator.is_HeckeAlgebraElement(x):
if x.parent() == self or (not self.is_anemic() and x.parent() == self.anemic_subalgebra()):
if x.parent().module().basis_matrix() == self.module().basis_matrix():
return hecke_operator.HeckeAlgebraElement_matrix(self, x.matrix())
else:
A = matrix([self.module().coordinate_vector(x.parent().module().gen(i))
for i in range(x.parent().module().rank())])
return hecke_operator.HeckeAlgebraElement_matrix(self, ~A * x.matrix() * A)
elif x.parent() == self.anemic_subalgebra():
pass
else:
raise TypeError
else:
A = self.matrix_space()(x)
if check:
if not A.is_scalar():
raise NotImplementedError("Membership testing for '%s' not implemented" % self)
return hecke_operator.HeckeAlgebraElement_matrix(self, A)
except TypeError:
raise TypeError("Don't know how to construct an element of %s from %s" % (self, x))
def _coerce_impl(self, x):
r"""
Implicit coercion of x into this Hecke algebra. The only things that
coerce implicitly into self are: elements of Hecke algebras which are
equal to self, or to the anemic subalgebra of self if self is not
anemic; and elements that coerce into the base ring of self. Bare
matrices do *not* coerce implicitly into self.
EXAMPLES::
sage: C = CuspForms(3, 12)
sage: A = C.anemic_hecke_algebra()
sage: F = C.hecke_algebra()
sage: F.coerce(A.2) # indirect doctest
Hecke operator T_2 on Cuspidal subspace of dimension 3 of Modular Forms space of dimension 5 for Congruence Subgroup Gamma0(3) of weight 12 over Rational Field
"""
if x.parent() == self or (not self.is_anemic() and x.parent() == self.anemic_subalgebra()):
return self(x)
return self(self.matrix_space()(1) * self.base_ring().coerce(x))
def gen(self, n):
"""
Return the `n`-th Hecke operator.
EXAMPLES::
sage: T = ModularSymbols(11).hecke_algebra()
sage: T.gen(2)
Hecke operator T_2 on Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field
"""
return self.hecke_operator(n)
def ngens(self):
r"""
The size of the set of generators returned by gens(), which is clearly
infinity. (This is not necessarily a minimal set of generators.)
EXAMPLES::
sage: CuspForms(1, 12).anemic_hecke_algebra().ngens()
+Infinity
"""
return sage.rings.infinity.infinity
def is_noetherian(self):
"""
Return True if this Hecke algebra is Noetherian as a ring. This is true
if and only if the base ring is Noetherian.
EXAMPLES::
sage: CuspForms(1, 12).anemic_hecke_algebra().is_noetherian()
True
"""
return self.base_ring().is_noetherian()
@cached_method
def matrix_space(self):
r"""
Return the underlying matrix space of this module.
EXAMPLES::
sage: CuspForms(3, 24, base_ring=Qp(5)).anemic_hecke_algebra().matrix_space()
Full MatrixSpace of 7 by 7 dense matrices over 5-adic Field with capped relative precision 20
"""
return sage.matrix.matrix_space.MatrixSpace(self.base_ring(), self.module().rank())
def _latex_(self):
r"""
LaTeX representation of self.
EXAMPLES::
sage: latex(CuspForms(3, 24).hecke_algebra()) # indirect doctest
\mathbf{T}_{\text{\texttt{Cuspidal...Gamma0(3)...24...}
"""
return "\\mathbf{T}_{%s}" % latex(self.__M)
def level(self):
r"""
Return the level of this Hecke algebra, which is (by definition) the
level of the Hecke module on which it acts.
EXAMPLES::
sage: ModularSymbols(37).hecke_algebra().level()
37
"""
return self.module().level()
def module(self):
"""
The Hecke module on which this algebra is acting.
EXAMPLES::
sage: T = ModularSymbols(1,12).hecke_algebra()
sage: T.module()
Modular Symbols space of dimension 3 for Gamma_0(1) of weight 12 with sign 0 over Rational Field
"""
return self.__M
def rank(self):
r"""
The rank of this Hecke algebra as a module over its base
ring. Not implemented at present.
EXAMPLES::
sage: ModularSymbols(Gamma1(3), 3).hecke_algebra().rank()
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
@cached_method
def basis(self):
r"""
Return a basis for this Hecke algebra as a free module over
its base ring.
EXAMPLES::
sage: ModularSymbols(Gamma1(3), 3).hecke_algebra().basis()
(Hecke operator on Modular Symbols space of dimension 2 for Gamma_1(3) of weight 3 with sign 0 over Rational Field defined by:
[1 0]
[0 1],
Hecke operator on Modular Symbols space of dimension 2 for Gamma_1(3) of weight 3 with sign 0 over Rational Field defined by:
[0 0]
[0 2])
sage: M = ModularSymbols(Gamma0(22), sign=1)
sage: H = M.hecke_algebra()
sage: B = H.basis()
sage: len(B)
5
sage: all(b in H for b in B)
True
sage: [B[0, 0] for B in M.anemic_hecke_algebra().basis()]
Traceback (most recent call last):
...
NotImplementedError: basis not implemented for anemic Hecke algebra
"""
bound = self.__M.hecke_bound()
dim = self.__M.rank()
# current implementation gets stuck in an infinite loop when dimension of Hecke alg != dimension of space
if self.is_anemic():
raise NotImplementedError("basis not implemented for anemic Hecke algebra")
if dim == 0:
basis = []
elif dim == 1:
basis = [self.hecke_operator(1)]
else:
span = [self.hecke_operator(n) for n in range(1, bound + 1)]
rand_max = 5
while True:
# Project the full Hecke module to a random submodule to ease the HNF reduction.
v = (ZZ**dim).random_element(x=rand_max)
proj_span = matrix([T.matrix() * v for T in span])._clear_denom()[0]
proj_basis = proj_span.hermite_form()
if proj_basis[dim - 1] == 0:
# We got unlucky, choose another projection.
rand_max *= 2
continue
# Lift the projected basis to a basis in the Hecke algebra.
trans = proj_span.solve_left(proj_basis)
basis = [sum(c * T for c, T in zip(row, span) if c != 0)
for row in trans[:dim]]
break
return tuple(basis)
@cached_method
def discriminant(self):
r"""
Return the discriminant of this Hecke algebra.
This is the
determinant of the matrix `{\rm Tr}(x_i x_j)` where `x_1,
\dots,x_d` is a basis for self, and `{\rm Tr}(x)` signifies
the trace (in the sense of linear algebra) of left
multiplication by `x` on the algebra (*not* the trace of the
operator `x` acting on the underlying Hecke module!). For
further discussion and conjectures see Calegari + Stein,
*Conjectures about discriminants of Hecke algebras of prime
level*, Springer LNCS 3076.
EXAMPLES::
sage: BrandtModule(3, 4).hecke_algebra().discriminant()
1
sage: ModularSymbols(65, sign=1).cuspidal_submodule().hecke_algebra().discriminant()
6144
sage: ModularSymbols(1,4,sign=1).cuspidal_submodule().hecke_algebra().discriminant()
1
sage: H = CuspForms(1, 24).hecke_algebra()
sage: H.discriminant()
83041344
"""
basis = self.basis()
d = len(basis)
if d <= 1:
return ZZ.one()
trace_matrix = matrix(ZZ, d)
for i in range(d):
for j in range(i + 1):
trace_matrix[i, j] = trace_matrix[j, i] = basis[i].matrix().trace_of_product(basis[j].matrix())
return trace_matrix.det()
def gens(self):
r"""
Return a generator over all Hecke operator `T_n` for
`n = 1, 2, 3, \ldots`. This is infinite.
EXAMPLES::
sage: T = ModularSymbols(1,12).hecke_algebra()
sage: g = T.gens()
sage: next(g)
Hecke operator T_1 on Modular Symbols space of dimension 3 for Gamma_0(1) of weight 12 with sign 0 over Rational Field
sage: next(g)
Hecke operator T_2 on Modular Symbols space of dimension 3 for Gamma_0(1) of weight 12 with sign 0 over Rational Field
"""
n = 1
while True:
yield self.hecke_operator(n)
n += 1
@cached_method(key=lambda self, n: int(n))
def hecke_operator(self, n):
"""
Return the `n`-th Hecke operator `T_n`.
EXAMPLES::
sage: T = ModularSymbols(1,12).hecke_algebra()
sage: T.hecke_operator(2)
Hecke operator T_2 on Modular Symbols space of dimension 3 for Gamma_0(1) of weight 12 with sign 0 over Rational Field
"""
return self.__M._hecke_operator_class()(self, n)
def hecke_matrix(self, n, *args, **kwds):
"""
Return the matrix of the n-th Hecke operator `T_n`.
EXAMPLES::
sage: T = ModularSymbols(1,12).hecke_algebra()
sage: T.hecke_matrix(2)
[ -24 0 0]
[ 0 -24 0]
[4860 0 2049]
"""
return self.__M.hecke_matrix(n, *args, **kwds)
def diamond_bracket_matrix(self, d):
r"""
Return the matrix of the diamond bracket operator `\langle d \rangle`.
EXAMPLES::
sage: T = ModularSymbols(Gamma1(7), 4).hecke_algebra()
sage: d3 = T.diamond_bracket_matrix(3)
sage: x = d3.charpoly().variables()[0]
sage: d3.charpoly() == (x^3-1)^4
True
"""
return self.__M.diamond_bracket_matrix(d)
@cached_method(key=lambda self, d: int(d) % self.__M.level())
def diamond_bracket_operator(self, d):
r"""
Return the diamond bracket operator `\langle d \rangle`.
EXAMPLES::
sage: T = ModularSymbols(Gamma1(7), 4).hecke_algebra()
sage: T.diamond_bracket_operator(3)
Diamond bracket operator <3> on Modular Symbols space of dimension 12 for Gamma_1(7) of weight 4 with sign 0 over Rational Field
"""
return self.__M._diamond_operator_class()(self, d)
class HeckeAlgebra_full(HeckeAlgebra_base):
r"""
A full Hecke algebra (including the operators `T_n` where `n` is not
assumed to be coprime to the level).
"""
def _repr_(self):
r"""
String representation of self.
EXAMPLES::
sage: ModularForms(37).hecke_algebra()._repr_()
'Full Hecke algebra acting on Modular Forms space of dimension 3 for Congruence Subgroup Gamma0(37) of weight 2 over Rational Field'
"""
return "Full Hecke algebra acting on %s" % self.module()
def __richcmp__(self, other, op):
r"""
Compare self to other.
EXAMPLES::
sage: A = ModularForms(37).hecke_algebra()
sage: A == QQ
False
sage: A == ModularForms(37).anemic_hecke_algebra()
False
sage: A == A
True
"""
if not isinstance(other, HeckeAlgebra_full):
return NotImplemented
return richcmp(self.module(), other.module(), op)
def is_anemic(self):
"""
Return False, since this the full Hecke algebra.
EXAMPLES::
sage: H = CuspForms(3, 12).hecke_algebra()
sage: H.is_anemic()
False
"""
return False
def anemic_subalgebra(self):
r"""
The subalgebra of self generated by the Hecke operators of
index coprime to the level.
EXAMPLES::
sage: H = CuspForms(3, 12).hecke_algebra()
sage: H.anemic_subalgebra()
Anemic Hecke algebra acting on Cuspidal subspace of dimension 3 of Modular Forms space of dimension 5 for Congruence Subgroup Gamma0(3) of weight 12 over Rational Field
"""
return self.module().anemic_hecke_algebra()
HeckeAlgebra = HeckeAlgebra_full
class HeckeAlgebra_anemic(HeckeAlgebra_base):
r"""
An anemic Hecke algebra, generated by Hecke operators with index coprime to the level.
"""
def _repr_(self):
r"""
EXAMPLES::
sage: H = CuspForms(3, 12).anemic_hecke_algebra()._repr_()
"""
return "Anemic Hecke algebra acting on %s" % self.module()
def __richcmp__(self, other, op):
r"""
Compare self to other.
EXAMPLES::
sage: A = ModularForms(23).anemic_hecke_algebra()
sage: A == QQ
False
sage: A == ModularForms(23).hecke_algebra()
False
sage: A == A
True
"""
if not isinstance(other, HeckeAlgebra_anemic):
return NotImplemented
return richcmp(self.module(), other.module(), op)
def hecke_operator(self, n):
"""
Return the `n`-th Hecke operator, for `n` any
positive integer coprime to the level.
EXAMPLES::
sage: T = ModularSymbols(Gamma1(5),3).anemic_hecke_algebra()
sage: T.hecke_operator(2)
Hecke operator T_2 on Modular Symbols space of dimension 4 for Gamma_1(5) of weight 3 with sign 0 over Rational Field
sage: T.hecke_operator(5)
Traceback (most recent call last):
...
IndexError: Hecke operator T_5 not defined in the anemic Hecke algebra
"""
n = int(n)
if gcd(self.module().level(), n) != 1:
raise IndexError("Hecke operator T_%s not defined in the anemic Hecke algebra" % n)
return self.module()._hecke_operator_class()(self, n)
def is_anemic(self):
"""
Return True, since this is the anemic Hecke algebra.
EXAMPLES::
sage: H = CuspForms(3, 12).anemic_hecke_algebra()
sage: H.is_anemic()
True
"""
return True
def gens(self):
r"""
Return a generator over all Hecke operator `T_n` for
`n = 1, 2, 3, \ldots`, with `n` coprime to the
level. This is an infinite sequence.
EXAMPLES::
sage: T = ModularSymbols(12,2).anemic_hecke_algebra()
sage: g = T.gens()
sage: next(g)
Hecke operator T_1 on Modular Symbols space of dimension 5 for Gamma_0(12) of weight 2 with sign 0 over Rational Field
sage: next(g)
Hecke operator T_5 on Modular Symbols space of dimension 5 for Gamma_0(12) of weight 2 with sign 0 over Rational Field
"""
level = self.level()
n = 1
while True:
if gcd(n, level) == 1:
yield self.hecke_operator(n)
n += 1
AnemicHeckeAlgebra = HeckeAlgebra_anemic | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/hecke/algebra.py | 0.868813 | 0.521349 | algebra.py | pypi |
import sage.misc.misc as misc
from sage.modules.matrix_morphism import MatrixMorphism
from sage.categories.morphism import Morphism
# We also define other types of Hecke-module morphisms that aren't
# specified by a matrix. E.g., Hecke operators, or maybe morphisms on
# modular abelian varieties (which are specified by matrices, but on
# integral homology). All morphisms derive from HeckeModuleMorphism.
def is_HeckeModuleMorphism(x):
r"""
Return True if x is of type HeckeModuleMorphism.
EXAMPLES::
sage: sage.modular.hecke.morphism.is_HeckeModuleMorphism(ModularSymbols(6).hecke_operator(7).hecke_module_morphism())
True
"""
return isinstance(x, HeckeModuleMorphism)
def is_HeckeModuleMorphism_matrix(x):
"""
EXAMPLES::
sage: sage.modular.hecke.morphism.is_HeckeModuleMorphism_matrix(ModularSymbols(6).hecke_operator(7).matrix_form().hecke_module_morphism())
True
"""
return isinstance(x, HeckeModuleMorphism_matrix)
class HeckeModuleMorphism(Morphism):
r"""
Abstract base class for morphisms of Hecke modules.
"""
pass
class HeckeModuleMorphism_matrix(MatrixMorphism, HeckeModuleMorphism):
"""
Morphisms of Hecke modules when the morphism is given by a matrix.
Note that care is needed when composing morphisms, because morphisms in
Sage act on the left, but their matrices act on the right (!). So if F: A
-> B and G : B -> C are morphisms, the composition A -> C is G*F, but its
matrix is F.matrix() * G.matrix().
EXAMPLES::
sage: A = ModularForms(1, 4)
sage: B = ModularForms(1, 16)
sage: C = ModularForms(1, 28)
sage: F = A.Hom(B)(matrix(QQ,1,2,srange(1, 3)))
sage: G = B.Hom(C)(matrix(QQ,2,3,srange(1, 7)))
sage: G * F
Hecke module morphism defined by the matrix
[ 9 12 15]
Domain: Modular Forms space of dimension 1 for Modular Group SL(2,Z) ...
Codomain: Modular Forms space of dimension 3 for Modular Group SL(2,Z) ...
sage: F * G
Traceback (most recent call last):
...
TypeError: Incompatible composition of morphisms: domain of left morphism must be codomain of right.
"""
def __init__(self, parent, A, name='', side="left"):
"""
INPUT:
- ``parent`` - ModularSymbolsHomspace
- ``A`` - Matrix
- ``name`` - str (defaults to '') name of the morphism
(used for printing)
EXAMPLES::
sage: M = ModularSymbols(6)
sage: t = M.Hom(M)(matrix(QQ,3,3,srange(9)), name="spam"); t
Hecke module morphism spam defined by the matrix
[0 1 2]
[3 4 5]
[6 7 8]
Domain: Modular Symbols space of dimension 3 for Gamma_0(6) of weight ...
Codomain: Modular Symbols space of dimension 3 for Gamma_0(6) of weight ...
sage: t == loads(dumps(t))
True
"""
if not isinstance(name, str):
raise TypeError("name must be a string")
self.__name = name
MatrixMorphism.__init__(self, parent, A, side)
def name(self, new=None):
r"""
Return the name of this operator, or set it to a new name.
EXAMPLES::
sage: M = ModularSymbols(6)
sage: t = M.Hom(M)(matrix(QQ,3,3,srange(9)), name="spam"); t
Hecke module morphism spam defined by ...
sage: t.name()
'spam'
sage: t.name("eggs"); t
Hecke module morphism eggs defined by ...
"""
if new is None:
return self.__name
self.__name = new
def _repr_(self):
r"""
String representation of self.
EXAMPLES::
sage: M = ModularSymbols(6)
sage: t = M.Hom(M)(matrix(QQ,3,3,srange(9))); t._repr_()
'Hecke module morphism defined by the matrix\n[0 1 2]\n[3 4 5]\n[6 7 8]\nDomain: Modular Symbols space of dimension 3 for Gamma_0(6) of weight ...\nCodomain: Modular Symbols space of dimension 3 for Gamma_0(6) of weight ...'
sage: t.name('spam'); t._repr_()
'Hecke module morphism spam defined by the matrix\n[0 1 2]\n[3 4 5]\n[6 7 8]\nDomain: Modular Symbols space of dimension 3 for Gamma_0(6) of weight ...\nCodomain: Modular Symbols space of dimension 3 for Gamma_0(6) of weight ...'
"""
name = self.__name
if name != '':
name += ' '
return "Hecke module morphism %sdefined by the matrix\n%r\nDomain: %s\nCodomain: %s"%(
name, self.matrix(), misc.strunc(self.domain()), misc.strunc(self.codomain()))
# __mul__ method removed by David Loeffler 2009-04-14 as it is an exact duplicate of sage.modules.matrix_morphism.__mul__ | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/hecke/morphism.py | 0.783533 | 0.517144 | morphism.py | pypi |
from . import ambient
from .cuspidal_submodule import CuspidalSubmodule_R
from sage.rings.integer_ring import ZZ
from sage.misc.cachefunc import cached_method
class ModularFormsAmbient_R(ambient.ModularFormsAmbient):
def __init__(self, M, base_ring):
"""
Ambient space of modular forms over a ring other than QQ.
EXAMPLES::
sage: M = ModularForms(23,2,base_ring=GF(7)) # indirect doctest
sage: M
Modular Forms space of dimension 3 for Congruence Subgroup Gamma0(23) of weight 2 over Finite Field of size 7
sage: M == loads(dumps(M))
True
"""
self.__M = M
if M.character() is not None:
self.__R_character = M.character().change_ring(base_ring)
else:
self.__R_character = None
ambient.ModularFormsAmbient.__init__(self, M.group(), M.weight(), base_ring, M.character(), M._eis_only)
@cached_method(key=lambda self,sign: ZZ(sign)) # convert sign to an Integer before looking this up in the cache
def modular_symbols(self,sign=0):
r"""
Return the space of modular symbols attached to this space, with the given sign (default 0).
TESTS::
sage: K.<i> = QuadraticField(-1)
sage: chi = DirichletGroup(5, base_ring = K).0
sage: L.<c> = K.extension(x^2 - 402*i)
sage: M = ModularForms(chi, 7, base_ring = L)
sage: symbs = M.modular_symbols()
sage: symbs.character() == chi
True
sage: symbs.base_ring() == L
True
"""
sign = ZZ(sign)
return self.__M.modular_symbols(sign).change_ring(self.base_ring())
def _repr_(self):
"""
String representation for ``self``.
EXAMPLES::
sage: M = ModularForms(23,2,base_ring=GF(7)) # indirect doctest
sage: M._repr_()
'Modular Forms space of dimension 3 for Congruence Subgroup Gamma0(23) of weight 2 over Finite Field of size 7'
sage: chi = DirichletGroup(109).0 ** 36
sage: ModularForms(chi, 2, base_ring = chi.base_ring())
Modular Forms space of dimension 9, character [zeta3] and weight 2 over Cyclotomic Field of order 108 and degree 36
"""
s = str(self.__M)
i = s.find('over')
if i != -1:
s = s[:i]
return s + 'over %s' % self.base_ring()
def _compute_q_expansion_basis(self, prec=None):
"""
Compute q-expansions for a basis of self to precision prec.
EXAMPLES::
sage: M = ModularForms(23,2,base_ring=GF(7))
sage: M._compute_q_expansion_basis(10)
[q + 6*q^3 + 6*q^4 + 5*q^6 + 2*q^7 + 6*q^8 + 2*q^9 + O(q^10),
q^2 + 5*q^3 + 6*q^4 + 2*q^5 + q^6 + 2*q^7 + 5*q^8 + O(q^10),
1 + 5*q^3 + 5*q^4 + 5*q^6 + 3*q^8 + 5*q^9 + O(q^10)]
TESTS:
This checks that :trac:`13445` is fixed::
sage: M = ModularForms(Gamma1(29), base_ring=GF(29))
sage: S = M.cuspidal_subspace()
sage: 0 in [f.valuation() for f in S.basis()]
False
sage: from sage.modular.dims import dimension_cusp_forms
sage: len(S.basis()) == dimension_cusp_forms(Gamma1(29), 2)
True
"""
if prec is None:
prec = self.prec()
R = self._q_expansion_ring()
c = self.base_ring().characteristic()
if c == 0:
B = self.__M.q_expansion_basis(prec)
return [R(f) for f in B]
elif c.is_prime_power():
K = self.base_ring()
p = K.characteristic().prime_factors()[0]
from sage.rings.finite_rings.finite_field_constructor import GF
Kp = GF(p)
newB = [f.change_ring(K) for f in list(self.__M.cuspidal_subspace().q_integral_basis(prec))]
A = Kp**prec
gens = [f.padded_list(prec) for f in newB]
V = A.span(gens)
B = [f.change_ring(K) for f in self.__M.q_integral_basis(prec)]
for f in B:
fc = f.padded_list(prec)
gens.append(fc)
if not A.span(gens) == V:
newB.append(f)
V = A.span(gens)
if len(newB) != self.dimension():
raise RuntimeError("The dimension of the space is %s but the basis we computed has %s elements"%(self.dimension(), len(newB)))
lst = [R(f) for f in newB]
return [f/f[f.valuation()] for f in lst]
else:
# this returns a basis of q-expansions, without guaranteeing that
# the first vectors form a basis of the cuspidal subspace
# TODO: bring this in line with the other cases
# simply using the above code fails because free modules over
# general rings do not have a .span() method
B = self.__M.q_integral_basis(prec)
return [R(f) for f in B]
def cuspidal_submodule(self):
r"""
Return the cuspidal subspace of this space.
EXAMPLES::
sage: C = CuspForms(7, 4, base_ring=CyclotomicField(5)) # indirect doctest
sage: type(C)
<class 'sage.modular.modform.cuspidal_submodule.CuspidalSubmodule_R_with_category'>
"""
return CuspidalSubmodule_R(self)
def change_ring(self, R):
r"""
Return this modular forms space with the base ring changed to the ring R.
EXAMPLES::
sage: chi = DirichletGroup(109, CyclotomicField(3)).0
sage: M9 = ModularForms(chi, 2, base_ring = CyclotomicField(9))
sage: M9.change_ring(CyclotomicField(15))
Modular Forms space of dimension 10, character [zeta3 + 1] and weight 2 over Cyclotomic Field of order 15 and degree 8
sage: M9.change_ring(QQ)
Traceback (most recent call last):
...
ValueError: Space cannot be defined over Rational Field
"""
if not R.has_coerce_map_from(self.__M.base_ring()):
raise ValueError("Space cannot be defined over %s" % R)
return ModularFormsAmbient_R(self.__M, R) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/modform/ambient_R.py | 0.692122 | 0.354377 | ambient_R.py | pypi |
from sage.rings.fast_arith import prime_range
from sage.matrix.constructor import matrix
from sage.misc.verbose import verbose
from sage.misc.cachefunc import cached_method
from sage.misc.prandom import randint
from sage.modular.arithgroup.all import Gamma0
from sage.modular.modsym.all import ModularSymbols
from sage.modules.all import vector
from sage.rings.complex_double import CDF
from sage.rings.integer import Integer
from sage.rings.rational_field import QQ
from sage.structure.richcmp import richcmp_method, richcmp
from sage.structure.sage_object import SageObject
from sage.structure.sequence import Sequence
# This variable controls importing the SciPy library sparingly
scipy=None
@richcmp_method
class NumericalEigenforms(SageObject):
"""
numerical_eigenforms(group, weight=2, eps=1e-20, delta=1e-2, tp=[2,3,5])
INPUT:
- ``group`` - a congruence subgroup of a Dirichlet character of
order 1 or 2
- ``weight`` - an integer >= 2
- ``eps`` - a small float; abs( ) < eps is what "equal to zero" is
interpreted as for floating point numbers.
- ``delta`` - a small-ish float; eigenvalues are considered distinct
if their difference has absolute value at least delta
- ``tp`` - use the Hecke operators T_p for p in tp when searching
for a random Hecke operator with distinct Hecke eigenvalues.
OUTPUT:
A numerical eigenforms object, with the following useful methods:
- :meth:`ap` - return all eigenvalues of `T_p`
- :meth:`eigenvalues` - list of eigenvalues corresponding
to the given list of primes, e.g.,::
[[eigenvalues of T_2],
[eigenvalues of T_3],
[eigenvalues of T_5], ...]
- :meth:`systems_of_eigenvalues` - a list of the systems of
eigenvalues of eigenforms such that the chosen random linear
combination of Hecke operators has multiplicity 1 eigenvalues.
EXAMPLES::
sage: n = numerical_eigenforms(23)
sage: n == loads(dumps(n))
True
sage: n.ap(2) # abs tol 1e-12
[3.0, -1.6180339887498947, 0.6180339887498968]
sage: n.systems_of_eigenvalues(7) # abs tol 2e-12
[
[-1.6180339887498947, 2.2360679774997894, -3.2360679774997894],
[0.6180339887498968, -2.236067977499788, 1.2360679774997936],
[3.0, 4.0, 6.0]
]
sage: n.systems_of_abs(7) # abs tol 2e-12
[
[0.6180339887498943, 2.2360679774997894, 1.2360679774997887],
[1.6180339887498947, 2.23606797749979, 3.2360679774997894],
[3.0, 4.0, 6.0]
]
sage: n.eigenvalues([2,3,5]) # rel tol 2e-12
[[3.0, -1.6180339887498947, 0.6180339887498968],
[4.0, 2.2360679774997894, -2.236067977499788],
[6.0, -3.2360679774997894, 1.2360679774997936]]
"""
def __init__(self, group, weight=2, eps=1e-20,
delta=1e-2, tp=[2,3,5]):
"""
Create a new space of numerical eigenforms.
EXAMPLES::
sage: numerical_eigenforms(61) # indirect doctest
Numerical Hecke eigenvalues for Congruence Subgroup Gamma0(61) of weight 2
"""
if isinstance(group, (int, Integer)):
group = Gamma0(Integer(group))
self._group = group
self._weight = Integer(weight)
self._tp = tp
if self._weight < 2:
raise ValueError("weight must be at least 2")
self._eps = eps
self._delta = delta
def __richcmp__(self, other, op):
"""
Compare two spaces of numerical eigenforms.
They are considered equal if and only if they come from the
same space of modular symbols.
EXAMPLES::
sage: n = numerical_eigenforms(23)
sage: n == loads(dumps(n))
True
"""
if not isinstance(other, NumericalEigenforms):
return NotImplemented
return richcmp(self.modular_symbols(), other.modular_symbols(), op)
def level(self):
"""
Return the level of this set of modular eigenforms.
EXAMPLES::
sage: n = numerical_eigenforms(61) ; n.level()
61
"""
return self._group.level()
def weight(self):
"""
Return the weight of this set of modular eigenforms.
EXAMPLES::
sage: n = numerical_eigenforms(61) ; n.weight()
2
"""
return self._weight
def _repr_(self):
"""
Print string representation of self.
EXAMPLES::
sage: n = numerical_eigenforms(61) ; n
Numerical Hecke eigenvalues for Congruence Subgroup Gamma0(61) of weight 2
sage: n._repr_()
'Numerical Hecke eigenvalues for Congruence Subgroup Gamma0(61) of weight 2'
"""
return "Numerical Hecke eigenvalues for %s of weight %s"%(
self._group, self._weight)
@cached_method
def modular_symbols(self):
"""
Return the space of modular symbols used for computing this
set of modular eigenforms.
EXAMPLES::
sage: n = numerical_eigenforms(61) ; n.modular_symbols()
Modular Symbols space of dimension 5 for Gamma_0(61) of weight 2 with sign 1 over Rational Field
"""
M = ModularSymbols(self._group,
self._weight, sign=1)
if M.base_ring() != QQ:
raise ValueError("modular forms space must be defined over QQ")
return M
@cached_method
def _eigenvectors(self):
r"""
Find numerical approximations to simultaneous eigenvectors in
self.modular_symbols() for all T_p in self._tp.
EXAMPLES::
sage: n = numerical_eigenforms(61)
sage: n._eigenvectors() # random order
[ 1.0 0.289473640239 0.176788851952 0.336707726757 2.4182243084e-16]
[ 0 -0.0702748344418 0.491416161212 0.155925712173 0.707106781187]
[ 0 0.413171180356 0.141163094698 0.0923242547901 0.707106781187]
[ 0 0.826342360711 0.282326189397 0.18464850958 6.79812569682e-16]
[ 0 0.2402380858 0.792225196393 0.905370774276 4.70805946682e-16]
TESTS:
This tests if this routine selects only eigenvectors with
multiplicity one. Two of the eigenvalues are
(roughly) -92.21 and -90.30 so if we set ``eps = 2.0``
then they should compare as equal, causing both eigenvectors
to be absent from the matrix returned. The remaining eigenvalues
(ostensibly unique) are visible in the test, which should be
independent of which eigenvectors are returned, but it does presume
an ordering of these eigenvectors for the test to succeed.
This exercises a correction in :trac:`8018`. ::
sage: n = numerical_eigenforms(61, eps=2.0)
sage: evectors = n._eigenvectors()
sage: evalues = [(matrix((n._hecke_matrix*evectors).column(i))/matrix(evectors.column(i)))[0, 0]
....: for i in range(evectors.ncols())]
sage: diff = n._hecke_matrix*evectors - evectors*diagonal_matrix(evalues)
sage: sum(abs(a) for a in diff.list()) < 1.0e-9
True
"""
verbose('Finding eigenvector basis')
M = self.modular_symbols()
tp = self._tp
p = tp[0]
t = M.T(p).matrix()
for p in tp[1:]:
t += randint(-50,50)*M.T(p).matrix()
self._hecke_matrix = t
global scipy
if scipy is None:
import scipy
import scipy.linalg
evals,eig = scipy.linalg.eig(self._hecke_matrix.numpy(), right=True, left=False)
B = matrix(eig)
v = [CDF(evals[i]) for i in range(len(evals))]
# Determine the eigenvectors with eigenvalues of multiplicity
# one, with equality controlled by the value of eps
# Keep just these eigenvectors
eps = self._eps
w = []
for i in range(len(v)):
e = v[i]
uniq = True
for j in range(len(v)):
if uniq and i != j and abs(e-v[j]) < eps:
uniq = False
if uniq:
w.append(i)
return B.matrix_from_columns(w)
@cached_method
def _easy_vector(self):
"""
Return a very sparse vector v such that v times the eigenvector matrix
has all entries nonzero.
ALGORITHM:
1. Choose row with the most nonzero entries. (put 1 there)
2. Consider submatrix of columns corresponding to zero entries
in row chosen in 1.
3. Find row of submatrix with most nonzero entries, and add
appropriate multiple. Repeat.
EXAMPLES::
sage: n = numerical_eigenforms(37)
sage: n._easy_vector() # slightly random output
(1.0, 1.0, 0)
sage: n = numerical_eigenforms(43)
sage: n._easy_vector() # slightly random output
(1.0, 0, 1.0, 0)
sage: n = numerical_eigenforms(125)
sage: n._easy_vector() # slightly random output
(0, 0, 0, 1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
"""
E = self._eigenvectors()
delta = self._delta
x = (CDF**E.nrows()).zero_vector()
if E.nrows() == 0:
return x
def best_row(M):
"""
Find the best row among rows of M, i.e. the row
with the most entries supported outside [-delta, delta].
EXAMPLES::
sage: numerical_eigenforms(61)._easy_vector() # indirect doctest
(1.0, 0.0, 0.0, 0.0, 1.0)
"""
R = M.rows()
v = [len(support(r, delta)) for r in R]
m = max(v)
i = v.index(m)
return i, R[i]
i, e = best_row(E)
x[i] = 1
while True:
s = set(support(e, delta))
zp = [j for j in range(e.degree()) if j not in s]
if not zp:
break
C = E.matrix_from_columns(zp)
# best row
i, f = best_row(C)
x[i] += 1 # simplistic
e = x * E
self.__easy_vector = x
return x
@cached_method
def _eigendata(self):
"""
Return all eigendata for self._easy_vector().
EXAMPLES::
sage: numerical_eigenforms(61)._eigendata() # random order
((1.0, 0.668205013164, 0.219198805797, 0.49263343893, 0.707106781187), (1.0, 1.49654668896, 4.5620686498, 2.02990686579, 1.41421356237), [0, 1], (1.0, 1.0))
"""
x = self._easy_vector()
B = self._eigenvectors()
def phi(y):
"""
Take coefficients and a basis, and return that
linear combination of basis vectors.
EXAMPLES::
sage: n = numerical_eigenforms(61) # indirect doctest
sage: n._eigendata() # random order
((1.0, 0.668205013164, 0.219198805797, 0.49263343893, 0.707106781187), (1.0, 1.49654668896, 4.5620686498, 2.02990686579, 1.41421356237), [0, 1], (1.0, 1.0))
"""
return y.element() * B
phi_x = phi(x)
V = phi_x.parent()
phi_x_inv = V([a**(-1) for a in phi_x])
eps = self._eps
nzp = support(x, eps)
x_nzp = vector(CDF, x.list_from_positions(nzp))
self.__eigendata = (phi_x, phi_x_inv, nzp, x_nzp)
return self.__eigendata
@cached_method
def ap(self, p):
"""
Return a list of the eigenvalues of the Hecke operator `T_p`
on all the computed eigenforms. The eigenvalues match up
between one prime and the next.
INPUT:
- ``p`` - integer, a prime number
OUTPUT:
- ``list`` - a list of double precision complex numbers
EXAMPLES::
sage: n = numerical_eigenforms(11,4)
sage: n.ap(2) # random order
[9.0, 9.0, 2.73205080757, -0.732050807569]
sage: n.ap(3) # random order
[28.0, 28.0, -7.92820323028, 5.92820323028]
sage: m = n.modular_symbols()
sage: x = polygen(QQ, 'x')
sage: m.T(2).charpoly('x').factor()
(x - 9)^2 * (x^2 - 2*x - 2)
sage: m.T(3).charpoly('x').factor()
(x - 28)^2 * (x^2 + 2*x - 47)
"""
p = Integer(p)
if not p.is_prime():
raise ValueError("p must be a prime")
return Sequence(self.eigenvalues([p])[0], immutable=True)
def eigenvalues(self, primes):
"""
Return the eigenvalues of the Hecke operators corresponding
to the primes in the input list of primes. The eigenvalues
match up between one prime and the next.
INPUT:
- ``primes`` - a list of primes
OUTPUT:
list of lists of eigenvalues.
EXAMPLES::
sage: n = numerical_eigenforms(1,12)
sage: n.eigenvalues([3,5,13]) # rel tol 2.4e-10
[[177148.0, 252.00000000001896], [48828126.0, 4830.000000001376], [1792160394038.0, -577737.9999898539]]
"""
primes = [Integer(p) for p in primes]
for p in primes:
if not p.is_prime():
raise ValueError('each element of primes must be prime.')
phi_x, phi_x_inv, nzp, x_nzp = self._eigendata()
B = self._eigenvectors()
def phi(y):
"""
Take coefficients and a basis, and return that
linear combination of basis vectors.
EXAMPLES::
sage: n = numerical_eigenforms(1,12) # indirect doctest
sage: n.eigenvalues([3,5,13]) # rel tol 2.4e-10
[[177148.0, 252.00000000001896], [48828126.0, 4830.000000001376], [1792160394038.0, -577737.9999898539]]
"""
return y.element() * B
ans = []
m = self.modular_symbols().ambient_module()
for p in primes:
t = m._compute_hecke_matrix_prime(p, nzp)
w = phi(x_nzp*t)
ans.append([w[i]*phi_x_inv[i] for i in range(w.degree())])
return ans
def systems_of_eigenvalues(self, bound):
"""
Return all systems of eigenvalues for self for primes
up to bound.
EXAMPLES::
sage: numerical_eigenforms(61).systems_of_eigenvalues(10) # rel tol 1e-9
[
[-1.4811943040920152, 0.8060634335253695, 3.1563251746586642, 0.6751308705666477],
[-1.0, -2.0000000000000027, -3.000000000000003, 1.0000000000000044],
[0.3111078174659775, 2.903211925911551, -2.525427560843529, -3.214319743377552],
[2.170086486626034, -1.7092753594369208, -1.63089761381512, -0.46081112718908984],
[3.0, 4.0, 6.0, 8.0]
]
"""
P = prime_range(bound)
e = self.eigenvalues(P)
v = Sequence([], cr=True)
if len(e) == 0:
return v
for i in range(len(e[0])):
v.append([e[j][i] for j in range(len(e))])
v.sort()
v.set_immutable()
return v
def systems_of_abs(self, bound):
"""
Return the absolute values of all systems of eigenvalues for
self for primes up to bound.
EXAMPLES::
sage: numerical_eigenforms(61).systems_of_abs(10) # rel tol 1e-9
[
[0.3111078174659775, 2.903211925911551, 2.525427560843529, 3.214319743377552],
[1.0, 2.0000000000000027, 3.000000000000003, 1.0000000000000044],
[1.4811943040920152, 0.8060634335253695, 3.1563251746586642, 0.6751308705666477],
[2.170086486626034, 1.7092753594369208, 1.63089761381512, 0.46081112718908984],
[3.0, 4.0, 6.0, 8.0]
]
"""
P = prime_range(bound)
e = self.eigenvalues(P)
v = Sequence([], cr=True)
if len(e) == 0:
return v
for i in range(len(e[0])):
v.append([abs(e[j][i]) for j in range(len(e))])
v.sort()
v.set_immutable()
return v
def support(v, eps):
"""
Given a vector `v` and a threshold eps, return all
indices where `|v|` is larger than eps.
EXAMPLES::
sage: sage.modular.modform.numerical.support( numerical_eigenforms(61)._easy_vector(), 1.0 )
[]
sage: sage.modular.modform.numerical.support( numerical_eigenforms(61)._easy_vector(), 0.5 )
[0, 4]
"""
return [i for i in range(v.degree()) if abs(v[i]) > eps] | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/modform/numerical.py | 0.873754 | 0.561876 | numerical.py | pypi |
r"""
This module is now called ``ring.py`` (see :trac:`31559`). Do not import from here as
it will generate a deprecation warning.
TESTS::
sage: from sage.modular.modform.ring import find_generators
sage: find_generators(ModularFormsRing(1))
doctest:warning
...
DeprecationWarning: find_generators is deprecated. Please use sage.modular.modform.ring.generators instead.
See https://trac.sagemath.org/31559 for details.
[(4,
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + 60480*q^6 + 82560*q^7 + 140400*q^8 + 181680*q^9 + O(q^10)),
(6,
1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 - 1575504*q^5 - 4058208*q^6 - 8471232*q^7 - 17047800*q^8 - 29883672*q^9 + O(q^10))]
::
sage: from sage.modular.modform.find_generators import find_generators
sage: find_generators(ModularFormsRing(1))
doctest:warning
...
DeprecationWarning: Importing find_generators from here is deprecated; please use "from sage.modular.modform.ring import find_generators" instead.
See https://trac.sagemath.org/31559 for details.
[(4,
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + 60480*q^6 + 82560*q^7 + 140400*q^8 + 181680*q^9 + O(q^10)),
(6,
1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 - 1575504*q^5 - 4058208*q^6 - 8471232*q^7 - 17047800*q^8 - 29883672*q^9 + O(q^10))]
::
sage: from sage.modular.modform.ring import basis_for_modform_space
sage: basis_for_modform_space(ModularFormsRing(1), 4)
doctest:warning
...
DeprecationWarning: basis_for_modform_space is deprecated. Please use sage.modular.modform.ring.q_expansion_basis instead.
See https://trac.sagemath.org/31559 for details.
[1 + 240*q + O(q^2)]
::
sage: from sage.modular.modform.find_generators import _span_of_forms_in_weight
sage: forms = [(4, 240*eisenstein_series_qexp(4,5)), (6,504*eisenstein_series_qexp(6,5))]
sage: _span_of_forms_in_weight(forms, 12, prec=5)
doctest:warning
...
DeprecationWarning: Importing _span_of_forms_in_weight from here is deprecated; please use "from sage.modular.modform.ring import _span_of_forms_in_weight" instead.
See https://trac.sagemath.org/31559 for details.
Vector space of degree 5 and dimension 2 over Rational Field
Basis matrix:
[ 1 0 196560 16773120 398034000]
[ 0 1 -24 252 -1472]
"""
from sage.misc.lazy_import import lazy_import
lazy_import('sage.modular.modform.ring', ('_span_of_forms_in_weight', 'find_generators', 'basis_for_modform_space', 'ModularFormsRing'), deprecation=31559) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/modform/find_generators.py | 0.673192 | 0.490053 | find_generators.py | pypi |
from sage.rings.integer import Integer
from sage.structure.sage_object import SageObject
from sage.lfunctions.dokchitser import Dokchitser
from .l_series_gross_zagier_coeffs import gross_zagier_L_series
from sage.modular.dirichlet import kronecker_character
class GrossZagierLseries(SageObject):
def __init__(self, E, A, prec=53):
r"""
Class for the Gross-Zagier L-series.
This is attached to a pair `(E,A)` where `E` is an elliptic curve over
`\QQ` and `A` is an ideal class in an imaginary quadratic number field.
For the exact definition, in the more general setting of modular forms
instead of elliptic curves, see section IV of [GZ1986]_.
INPUT:
- ``E`` -- an elliptic curve over `\QQ`
- ``A`` -- an ideal class in an imaginary quadratic number field
- ``prec`` -- an integer (default 53) giving the required precision
EXAMPLES::
sage: e = EllipticCurve('37a')
sage: K.<a> = QuadraticField(-40)
sage: A = K.class_group().gen(0)
sage: from sage.modular.modform.l_series_gross_zagier import GrossZagierLseries
sage: G = GrossZagierLseries(e, A)
TESTS::
sage: K.<b> = QuadraticField(131)
sage: A = K.class_group().one()
sage: G = GrossZagierLseries(e, A)
Traceback (most recent call last):
...
ValueError: A is not an ideal class in an imaginary quadratic field
"""
self._E = E
self._N = N = E.conductor()
self._A = A
ideal = A.ideal()
K = A.gens()[0].parent()
D = K.disc()
if not(K.degree() == 2 and D < 0):
raise ValueError("A is not an ideal class in an"
" imaginary quadratic field")
Q = ideal.quadratic_form().reduced_form()
epsilon = - kronecker_character(D)(N)
self._dokchister = Dokchitser(N ** 2 * D ** 2,
[0, 0, 1, 1],
weight=2, eps=epsilon, prec=prec)
self._nterms = nterms = Integer(self._dokchister.num_coeffs())
if nterms > 1e6:
# just takes way to long
raise ValueError("Too many terms: {}".format(nterms))
zeta_ord = ideal.number_field().zeta_order()
an_list = gross_zagier_L_series(E.anlist(nterms + 1), Q, N, zeta_ord)
self._dokchister.gp().set('a', an_list[1:])
self._dokchister.init_coeffs('a[k]', 1)
def __call__(self, s, der=0):
r"""
Return the value at `s`.
INPUT:
- `s` -- complex number
- ``der`` -- ? (default 0)
EXAMPLES::
sage: e = EllipticCurve('37a')
sage: K.<a> = QuadraticField(-40)
sage: A = K.class_group().gen(0)
sage: from sage.modular.modform.l_series_gross_zagier import GrossZagierLseries
sage: G = GrossZagierLseries(e, A)
sage: G(3)
-0.272946890617590
"""
return self._dokchister(s, der)
def taylor_series(self, s=1, series_prec=6, var='z'):
r"""
Return the Taylor series at `s`.
INPUT:
- `s` -- complex number (default 1)
- ``series_prec`` -- number of terms (default 6) in the Taylor series
- ``var`` -- variable (default 'z')
EXAMPLES::
sage: e = EllipticCurve('37a')
sage: K.<a> = QuadraticField(-40)
sage: A = K.class_group().gen(0)
sage: from sage.modular.modform.l_series_gross_zagier import GrossZagierLseries
sage: G = GrossZagierLseries(e, A)
sage: G.taylor_series(2,3)
-0.613002046122894 + 0.490374999263514*z - 0.122903033710382*z^2 + O(z^3)
"""
return self._dokchister.taylor_series(s, series_prec, var)
def _repr_(self):
"""
Return the string representation.
EXAMPLES::
sage: e = EllipticCurve('37a')
sage: K.<a> = QuadraticField(-40)
sage: A = K.class_group().gen(0)
sage: from sage.modular.modform.l_series_gross_zagier import GrossZagierLseries
sage: GrossZagierLseries(e, A)
Gross Zagier L-series attached to Elliptic Curve defined by y^2 + y = x^3 - x over Rational Field with ideal class Fractional ideal class (2, 1/2*a)
"""
msg = "Gross Zagier L-series attached to {} with ideal class {}"
return msg.format(self._E, self._A) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/modform/l_series_gross_zagier.py | 0.931719 | 0.574096 | l_series_gross_zagier.py | pypi |
from sage.rings.integer import Integer
from sage.rings.integer_ring import ZZ
from sage.rings.power_series_ring import PowerSeriesRing
from math import sqrt
def theta2_qexp(prec=10, var='q', K=ZZ, sparse=False):
r"""
Return the `q`-expansion of the series `\theta_2 = \sum_{n \text{ odd}} q^{n^2}`.
INPUT:
- prec -- integer; the absolute precision of the output
- var -- (default: 'q') variable name
- K -- (default: ZZ) base ring of answer
OUTPUT:
a power series over K
EXAMPLES::
sage: theta2_qexp(18)
q + q^9 + O(q^18)
sage: theta2_qexp(49)
q + q^9 + q^25 + O(q^49)
sage: theta2_qexp(100, 'q', QQ)
q + q^9 + q^25 + q^49 + q^81 + O(q^100)
sage: f = theta2_qexp(100, 't', GF(3)); f
t + t^9 + t^25 + t^49 + t^81 + O(t^100)
sage: parent(f)
Power Series Ring in t over Finite Field of size 3
sage: theta2_qexp(200)
q + q^9 + q^25 + q^49 + q^81 + q^121 + q^169 + O(q^200)
sage: f = theta2_qexp(20,sparse=True); f
q + q^9 + O(q^20)
sage: parent(f)
Sparse Power Series Ring in q over Integer Ring
"""
prec = Integer(prec)
if prec <= 0:
raise ValueError("prec must be positive")
if sparse:
v = {}
else:
v = [Integer(0)] * prec
one = Integer(1)
n = int(sqrt(prec))
if n*n < prec:
n += 1
for m in range(1, n, 2):
v[m*m] = one
R = PowerSeriesRing(K, sparse=sparse, names=var)
return R(v, prec=prec)
def theta_qexp(prec=10, var='q', K=ZZ, sparse=False):
r"""
Return the `q`-expansion of the standard `\theta` series
`\theta = 1 + 2\sum_{n=1}^{\infty} q^{n^2}`.
INPUT:
- prec -- integer; the absolute precision of the output
- var -- (default: 'q') variable name
- K -- (default: ZZ) base ring of answer
OUTPUT:
a power series over K
EXAMPLES::
sage: theta_qexp(25)
1 + 2*q + 2*q^4 + 2*q^9 + 2*q^16 + O(q^25)
sage: theta_qexp(10)
1 + 2*q + 2*q^4 + 2*q^9 + O(q^10)
sage: theta_qexp(100)
1 + 2*q + 2*q^4 + 2*q^9 + 2*q^16 + 2*q^25 + 2*q^36 + 2*q^49 + 2*q^64 + 2*q^81 + O(q^100)
sage: theta_qexp(100, 't')
1 + 2*t + 2*t^4 + 2*t^9 + 2*t^16 + 2*t^25 + 2*t^36 + 2*t^49 + 2*t^64 + 2*t^81 + O(t^100)
sage: theta_qexp(100, 't', GF(2))
1 + O(t^100)
sage: f = theta_qexp(20,sparse=True); f
1 + 2*q + 2*q^4 + 2*q^9 + 2*q^16 + O(q^20)
sage: parent(f)
Sparse Power Series Ring in q over Integer Ring
"""
prec = Integer(prec)
if prec <= 0:
raise ValueError("prec must be positive")
if sparse:
v = {}
else:
v = [Integer(0)] * prec
v[0] = Integer(1)
two = Integer(2)
n = int(sqrt(prec))
if n*n != prec:
n += 1
for m in range(1, n):
v[m*m] = two
R = PowerSeriesRing(K, sparse=sparse, names=var)
return R(v, prec=prec) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/modform/theta.py | 0.908346 | 0.690602 | theta.py | pypi |
r"""
Compute spaces of half-integral weight modular forms
Based on an algorithm in Basmaji's thesis.
AUTHORS:
- William Stein (2007-08)
"""
from sage.matrix.matrix_space import MatrixSpace
from sage.modular.dirichlet import DirichletGroup
from . import constructor
from .theta import theta2_qexp, theta_qexp
from copy import copy
def half_integral_weight_modform_basis(chi, k, prec):
r"""
A basis for the space of weight `k/2` forms with character
`\chi`. The modulus of `\chi` must be divisible by
`16` and `k` must be odd and `>1`.
INPUT:
- ``chi`` -- a Dirichlet character with modulus divisible by 16
- ``k`` -- an odd integer > 1
- ``prec`` -- a positive integer
OUTPUT: a list of power series
.. warning::
1. This code is very slow because it requests computation of a
basis of modular forms for integral weight spaces, and that
computation is still very slow.
2. If you give an input prec that is too small, then the output
list of power series may be larger than the dimension of the
space of half-integral forms.
EXAMPLES:
We compute some half-integral weight forms of level 16\*7
::
sage: half_integral_weight_modform_basis(DirichletGroup(16*7).0^2,3,30)
[q - 2*q^2 - q^9 + 2*q^14 + 6*q^18 - 2*q^21 - 4*q^22 - q^25 + O(q^30),
q^2 - q^14 - 3*q^18 + 2*q^22 + O(q^30),
q^4 - q^8 - q^16 + q^28 + O(q^30),
q^7 - 2*q^15 + O(q^30)]
The following illustrates that choosing too low of a precision can
give an incorrect answer.
::
sage: half_integral_weight_modform_basis(DirichletGroup(16*7).0^2,3,20)
[q - 2*q^2 - q^9 + 2*q^14 + 6*q^18 + O(q^20),
q^2 - q^14 - 3*q^18 + O(q^20),
q^4 - 2*q^8 + 2*q^12 - 4*q^16 + O(q^20),
q^7 - 2*q^8 + 4*q^12 - 2*q^15 - 6*q^16 + O(q^20),
q^8 - 2*q^12 + 3*q^16 + O(q^20)]
We compute some spaces of low level and the first few possible
weights.
::
sage: half_integral_weight_modform_basis(DirichletGroup(16,QQ).1, 3, 10)
[]
sage: half_integral_weight_modform_basis(DirichletGroup(16,QQ).1, 5, 10)
[q - 2*q^3 - 2*q^5 + 4*q^7 - q^9 + O(q^10)]
sage: half_integral_weight_modform_basis(DirichletGroup(16,QQ).1, 7, 10)
[q - 2*q^2 + 4*q^3 + 4*q^4 - 10*q^5 - 16*q^7 + 19*q^9 + O(q^10),
q^2 - 2*q^3 - 2*q^4 + 4*q^5 + 4*q^7 - 8*q^9 + O(q^10),
q^3 - 2*q^5 - 2*q^7 + 4*q^9 + O(q^10)]
sage: half_integral_weight_modform_basis(DirichletGroup(16,QQ).1, 9, 10)
[q - 2*q^2 + 4*q^3 - 8*q^4 + 14*q^5 + 16*q^6 - 40*q^7 + 16*q^8 - 57*q^9 + O(q^10),
q^2 - 2*q^3 + 4*q^4 - 8*q^5 - 8*q^6 + 20*q^7 - 8*q^8 + 32*q^9 + O(q^10),
q^3 - 2*q^4 + 4*q^5 + 4*q^6 - 10*q^7 - 16*q^9 + O(q^10),
q^4 - 2*q^5 - 2*q^6 + 4*q^7 + 4*q^9 + O(q^10),
q^5 - 2*q^7 - 2*q^9 + O(q^10)]
This example once raised an error (see :trac:`5792`).
::
sage: half_integral_weight_modform_basis(trivial_character(16),9,10)
[q - 2*q^2 + 4*q^3 - 8*q^4 + 4*q^6 - 16*q^7 + 48*q^8 - 15*q^9 + O(q^10),
q^2 - 2*q^3 + 4*q^4 - 2*q^6 + 8*q^7 - 24*q^8 + O(q^10),
q^3 - 2*q^4 - 4*q^7 + 12*q^8 + O(q^10),
q^4 - 6*q^8 + O(q^10)]
ALGORITHM: Basmaji (page 55 of his Essen thesis, "Ein Algorithmus
zur Berechnung von Hecke-Operatoren und Anwendungen auf modulare
Kurven", http://wstein.org/scans/papers/basmaji/).
Let `S = S_{k+1}(\epsilon)` be the space of cusp forms of
even integer weight `k+1` and character
`\varepsilon = \chi \psi^{(k+1)/2}`, where `\psi`
is the nontrivial mod-4 Dirichlet character. Let `U` be the
subspace of `S \times S` of elements `(a,b)` such
that `\Theta_2 a = \Theta_3 b`. Then `U` is
isomorphic to `S_{k/2}(\chi)` via the map
`(a,b) \mapsto a/\Theta_3`.
"""
if chi.modulus() % 16:
raise ValueError("the character must have modulus divisible by 16")
if not k % 2:
raise ValueError("k (=%s) must be odd" % k)
if k < 3:
raise ValueError("k (=%s) must be at least 3" % k)
chi = chi.minimize_base_ring()
psi = chi.parent()(DirichletGroup(4, chi.base_ring()).gen())
eps = chi*psi**((k+1) // 2)
eps = eps.minimize_base_ring()
M = constructor.ModularForms(eps, (k+1)//2)
C = M.cuspidal_subspace()
B = C.basis()
# This computation of S below -- of course --dominates the whole function.
S = [f.q_expansion(prec) for f in B]
T2 = theta2_qexp(prec)
T3 = theta_qexp(prec)
n = len(S)
MS = MatrixSpace(M.base_ring(), 2*n, prec)
A = copy(MS.zero_matrix())
for i in range(n):
T2f = T2*S[i]
T3f = T3*S[i]
for j in range(prec):
A[i, j] = T2f[j]
A[n+i, j] = -T3f[j]
B = A.kernel().basis()
a_vec = [sum([b[i]*S[i] for i in range(n)]) for b in B]
if len(a_vec) == 0:
return []
R = a_vec[0].parent()
t3 = R(T3)
return [R(a) / t3 for a in a_vec] | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/modform/half_integral.py | 0.916152 | 0.798187 | half_integral.py | pypi |
from random import shuffle
from sage.categories.graded_algebras import GradedAlgebras
from sage.misc.cachefunc import cached_method
from sage.misc.misc_c import prod
from sage.misc.superseded import deprecated_function_alias
from sage.misc.verbose import verbose
from sage.modular.arithgroup.all import Gamma0, is_CongruenceSubgroup
from sage.rings.integer import Integer
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.multi_polynomial import MPolynomial
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.polynomial.term_order import TermOrder
from sage.rings.power_series_poly import PowerSeries_poly
from sage.rings.rational_field import QQ
from sage.structure.parent import Parent
from sage.structure.richcmp import richcmp_method, richcmp
from .constructor import ModularForms
from .element import is_ModularFormElement, GradedModularFormElement
from .space import is_ModularFormsSpace
def _span_of_forms_in_weight(forms, weight, prec, stop_dim=None, use_random=False):
r"""
Utility function. Given a nonempty list of pairs ``(k,f)``, where `k` is an
integer and `f` is a power series, and a weight l, return all weight l
forms obtained by multiplying together the given forms.
INPUT:
- ``forms`` -- list of pairs `(k, f)` with k an integer and f a power
series (all over the same base ring)
- ``weight`` -- an integer
- ``prec`` -- an integer (less than or equal to the precision of all the
forms in ``forms``) -- precision to use in power series computations.
- ``stop_dim`` -- an integer: stop as soon as we have enough forms to span
a submodule of this rank (a saturated one if the base ring is `\ZZ`).
Ignored if ``use_random`` is False.
- ``use_random`` -- which algorithm to use. If True, tries random products
of the generators of the appropriate weight until a large enough
submodule is found (determined by ``stop_dim``). If False, just tries
everything.
Note that if the given forms do generate the whole space, then
``use_random=True`` will often be quicker (particularly if the weight is
large); but if the forms don't generate, the randomized algorithm is no
help and will actually be substantially slower, because it needs to do
repeated echelon form calls to check if vectors are in a submodule, while
the non-randomized algorithm just echelonizes one enormous matrix at the
end.
EXAMPLES::
sage: import sage.modular.modform.ring as f
sage: forms = [(4, 240*eisenstein_series_qexp(4,5)), (6,504*eisenstein_series_qexp(6,5))]
sage: f._span_of_forms_in_weight(forms, 12, prec=5)
Vector space of degree 5 and dimension 2 over Rational Field
Basis matrix:
[ 1 0 196560 16773120 398034000]
[ 0 1 -24 252 -1472]
sage: f._span_of_forms_in_weight(forms, 24, prec=5)
Vector space of degree 5 and dimension 3 over Rational Field
Basis matrix:
[ 1 0 0 52416000 39007332000]
[ 0 1 0 195660 12080128]
[ 0 0 1 -48 1080]
sage: ModularForms(1, 24).q_echelon_basis(prec=5)
[
1 + 52416000*q^3 + 39007332000*q^4 + O(q^5),
q + 195660*q^3 + 12080128*q^4 + O(q^5),
q^2 - 48*q^3 + 1080*q^4 + O(q^5)
]
Test the alternative randomized algorithm::
sage: f._span_of_forms_in_weight(forms, 24, prec=5, use_random=True, stop_dim=3)
Vector space of degree 5 and dimension 3 over Rational Field
Basis matrix:
[ 1 0 0 52416000 39007332000]
[ 0 1 0 195660 12080128]
[ 0 0 1 -48 1080]
"""
t = verbose('multiplying forms up to weight %s'%weight)
# Algorithm: run through the monomials of the appropriate weight, and build
# up the vector space they span.
n = len(forms)
R = forms[0][1].base_ring()
V = R ** prec
W = V.zero_submodule()
shortforms = [f[1].truncate_powerseries(prec) for f in forms]
# List of weights
from sage.combinat.integer_vector_weighted import WeightedIntegerVectors
wts = list(WeightedIntegerVectors(weight, [f[0] for f in forms]))
t = verbose("calculated weight list", t)
N = len(wts)
if use_random:
if stop_dim is None:
raise ValueError("stop_dim must be provided if use_random is True")
shuffle(wts)
for c in range(N):
w = V(prod(shortforms[i]**wts[c][i] for i in range(n)).padded_list(prec))
if w in W:
continue
W = V.span(list(W.gens()) + [w])
if stop_dim and W.rank() == stop_dim:
if R != ZZ or W.index_in_saturation() == 1:
verbose("Succeeded after %s of %s" % (c, N), t)
return W
verbose("Nothing worked", t)
return W
else:
G = [V(prod(forms[i][1]**c[i] for i in range(n)).padded_list(prec)) for c in wts]
t = verbose('found %s candidates' % N, t)
W = V.span(G)
verbose('span has dimension %s' % W.rank(), t)
return W
@richcmp_method
class ModularFormsRing(Parent):
r"""
The ring of modular forms (of weights 0 or at least 2) for a congruence
subgroup of `\SL_2(\ZZ)`, with coefficients in a specified base ring.
EXAMPLES::
sage: ModularFormsRing(Gamma1(13))
Ring of Modular Forms for Congruence Subgroup Gamma1(13) over Rational Field
sage: m = ModularFormsRing(4); m
Ring of Modular Forms for Congruence Subgroup Gamma0(4) over Rational Field
sage: m.modular_forms_of_weight(2)
Modular Forms space of dimension 2 for Congruence Subgroup Gamma0(4) of weight 2 over Rational Field
sage: m.modular_forms_of_weight(10)
Modular Forms space of dimension 6 for Congruence Subgroup Gamma0(4) of weight 10 over Rational Field
sage: m == loads(dumps(m))
True
sage: m.generators()
[(2, 1 + 24*q^2 + 24*q^4 + 96*q^6 + 24*q^8 + O(q^10)),
(2, q + 4*q^3 + 6*q^5 + 8*q^7 + 13*q^9 + O(q^10))]
sage: m.q_expansion_basis(2,10)
[1 + 24*q^2 + 24*q^4 + 96*q^6 + 24*q^8 + O(q^10),
q + 4*q^3 + 6*q^5 + 8*q^7 + 13*q^9 + O(q^10)]
sage: m.q_expansion_basis(3,10)
[]
sage: m.q_expansion_basis(10,10)
[1 + 10560*q^6 + 3960*q^8 + O(q^10),
q - 8056*q^7 - 30855*q^9 + O(q^10),
q^2 - 796*q^6 - 8192*q^8 + O(q^10),
q^3 + 66*q^7 + 832*q^9 + O(q^10),
q^4 + 40*q^6 + 528*q^8 + O(q^10),
q^5 + 20*q^7 + 190*q^9 + O(q^10)]
Elements of modular forms ring can be initiated via multivariate polynomials (see :meth:`from_polynomial`)::
sage: M = ModularFormsRing(1)
sage: M.ngens()
2
sage: E4, E6 = polygens(QQ, 'E4, E6')
sage: M(E4)
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6)
sage: M(E6)
1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 - 1575504*q^5 + O(q^6)
sage: M((E4^3 - E6^2)/1728)
q - 24*q^2 + 252*q^3 - 1472*q^4 + 4830*q^5 + O(q^6)
"""
Element = GradedModularFormElement
def __init__(self, group, base_ring=QQ):
r"""
INPUT:
- ``group`` -- a congruence subgroup of `\SL_2(\ZZ)`, or a
positive integer `N` (interpreted as `\Gamma_0(N)`)
- ``base_ring`` (ring, default: `\QQ`) -- a base ring, which should be
`\QQ`, `\ZZ`, or the integers mod `p` for some prime `p`
TESTS:
Check that :trac:`15037` is fixed::
sage: ModularFormsRing(3.4)
Traceback (most recent call last):
...
ValueError: group (=3.40000000000000) should be a congruence subgroup
sage: ModularFormsRing(Gamma0(2), base_ring=PolynomialRing(ZZ,x))
Traceback (most recent call last):
...
ValueError: base ring (=Univariate Polynomial Ring in x over Integer Ring) should be QQ, ZZ or a finite prime field
::
sage: TestSuite(ModularFormsRing(1)).run()
sage: TestSuite(ModularFormsRing(Gamma0(6))).run()
sage: TestSuite(ModularFormsRing(Gamma1(4))).run()
.. TODO::
- Add graded modular forms over non-trivial Dirichlet character;
- makes gen_forms returns modular forms over base rings other than `QQ`;
- implement binary operations between two forms with different groups.
"""
if isinstance(group, (int, Integer)):
group = Gamma0(group)
elif not is_CongruenceSubgroup(group):
raise ValueError("group (=%s) should be a congruence subgroup" % group)
if base_ring != ZZ and not base_ring.is_field() and not base_ring.is_finite():
raise ValueError("base ring (=%s) should be QQ, ZZ or a finite prime field" % base_ring)
self.__group = group
self.__cached_maxweight = ZZ(-1)
self.__cached_gens = []
self.__cached_cusp_maxweight = ZZ(-1)
self.__cached_cusp_gens = []
Parent.__init__(self, base=base_ring, category=GradedAlgebras(base_ring))
def change_ring(self, base_ring):
r"""
Return the ring of modular forms over the given base ring and the same
group as ``self``.
INPUT:
- ``base_ring`` -- a base ring, which should be `\QQ`, `\ZZ`, or the
integers mod `p` for some prime `p`.
EXAMPLES::
sage: M = ModularFormsRing(11); M
Ring of Modular Forms for Congruence Subgroup Gamma0(11) over Rational Field
sage: M.change_ring(Zmod(7))
Ring of Modular Forms for Congruence Subgroup Gamma0(11) over Ring of integers modulo 7
sage: M.change_ring(ZZ)
Ring of Modular Forms for Congruence Subgroup Gamma0(11) over Integer Ring
"""
return ModularFormsRing(self.group(), base_ring=base_ring)
def some_elements(self):
r"""
Return a list of generators of ``self``.
EXAMPLES::
sage: ModularFormsRing(1).some_elements()
[1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6),
1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 - 1575504*q^5 + O(q^6)]
"""
return [self(f) for f in self.gen_forms()]
def group(self):
r"""
Return the congruence subgroup for which this is the ring of modular forms.
EXAMPLES::
sage: R = ModularFormsRing(Gamma1(13))
sage: R.group() is Gamma1(13)
True
"""
return self.__group
def gen(self, i):
r"""
Return the `i`-th generator of ``self``.
INPUT:
- ``i`` (Integer) -- correspond to the `i`-th modular form generating
the ring of modular forms.
OUTPUT: A ``GradedModularFormElement``
EXAMPLES::
sage: M = ModularFormsRing(1)
sage: E4 = M.0; E4 # indirect doctest
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6)
sage: E6 = M.1; E6 # indirect doctest
1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 - 1575504*q^5 + O(q^6)
"""
if self.base_ring() is not QQ:
raise NotImplementedError("the base ring of the given ring of modular form should be QQ")
return self(self.gen_forms()[i])
def ngens(self):
r"""
Return the number of generators of ``self``
EXAMPLES::
sage: ModularFormsRing(1).ngens()
2
sage: ModularFormsRing(Gamma0(2)).ngens()
2
sage: ModularFormsRing(Gamma1(13)).ngens() # long time
33
.. WARNING::
Computing the number of generators of a graded ring of modular form for a certain
congruence subgroup can be very long.
"""
return len(self.gen_forms())
def polynomial_ring(self, names, gens=None):
r"""
Return a polynomial ring of which ``self`` is a quotient.
INPUT:
- ``names`` -- a list or tuple of names (strings), or a comma separated string
- ``gens`` (default: None) -- (list) a list of generator of ``self``. If ``gens`` is
``None`` then the generators returned by :meth:`~sage.modular.modform.find_generator.ModularFormsRing.gen_forms`
is used instead.
OUTPUT: A multivariate polynomial ring in the variable ``names``. Each variable of the
polynomial ring correspond to a generator given in gens (following the ordering of the list).
EXAMPLES::
sage: M = ModularFormsRing(1)
sage: gens = M.gen_forms()
sage: M.polynomial_ring('E4, E6', gens)
Multivariate Polynomial Ring in E4, E6 over Rational Field
sage: M = ModularFormsRing(Gamma0(8))
sage: gens = M.gen_forms()
sage: M.polynomial_ring('g', gens)
Multivariate Polynomial Ring in g0, g1, g2 over Rational Field
The degrees of the variables are the weights of the corresponding forms::
sage: M = ModularFormsRing(1)
sage: P.<E4, E6> = M.polynomial_ring()
sage: E4.degree()
4
sage: E6.degree()
6
sage: (E4*E6).degree()
10
"""
if gens is None:
gens = self.gen_forms()
degs = [f.weight() for f in gens]
return PolynomialRing(self.base_ring(), len(gens), names, order=TermOrder('wdeglex', degs)) # Should we remove the deg lexicographic ordering here?
def _generators_variables_dictionnary(self, poly_parent, gens):
r"""
Utility function that returns a dictionary giving an association between
polynomial ring generators and generators of modular forms ring.
INPUT:
- ``poly_parent`` -- A polynomial ring
- ``gen`` -- list of generators of the modular forms ring
TESTS::
sage: M = ModularFormsRing(Gamma0(6))
sage: P = QQ['x, y, z']
sage: M._generators_variables_dictionnary(P, M.gen_forms())
{z: q^2 - 2*q^3 + 3*q^4 + O(q^6),
y: q + 5*q^3 - 2*q^4 + 6*q^5 + O(q^6),
x: 1 + 24*q^3 + O(q^6)}
"""
if poly_parent.base_ring() != self.base_ring():
raise ValueError('the base ring of `poly_parent` must be the same as the base ring of the modular forms ring')
nb_var = poly_parent.ngens()
nb_gens = self.ngens()
if nb_var != nb_gens:
raise ValueError('the number of variables (%s) must be equal to the number of generators of the modular forms ring (%s)'%(nb_var, self.ngens()))
return {poly_parent.gen(i): self(gens[i]) for i in range(0, nb_var)}
def from_polynomial(self, polynomial, gens=None):
r"""
Convert the given polynomial to a graded form living in ``self``. If
``gens`` is ``None`` then the list of generators given by the method
:meth:`gen_forms` will be used. Otherwise, ``gens`` should be a list of
generators.
INPUT:
- ``polynomial`` -- A multivariate polynomial. The variables names of
the polynomial should be different from ``'q'``. The number of
variable of this polynomial should equal the number of generators
- ``gens`` -- list (default: ``None``) of generators of the modular
forms ring
OUTPUT: A ``GradedModularFormElement`` given by the polynomial
relation ``polynomial``.
EXAMPLES::
sage: M = ModularFormsRing(1)
sage: x,y = polygens(QQ, 'x,y')
sage: M.from_polynomial(x^2+y^3)
2 - 1032*q + 774072*q^2 - 77047584*q^3 - 11466304584*q^4 - 498052467504*q^5 + O(q^6)
sage: M = ModularFormsRing(Gamma0(6))
sage: M.ngens()
3
sage: x,y,z = polygens(QQ, 'x,y,z')
sage: M.from_polynomial(x+y+z)
1 + q + q^2 + 27*q^3 + q^4 + 6*q^5 + O(q^6)
sage: M.0 + M.1 + M.2
1 + q + q^2 + 27*q^3 + q^4 + 6*q^5 + O(q^6)
sage: P = x.parent()
sage: M.from_polynomial(P(1/2))
1/2
Note that the number of variables must be equal to the number of generators::
sage: x, y = polygens(QQ, 'x, y')
sage: M(x + y)
Traceback (most recent call last):
...
ValueError: the number of variables (2) must be equal to the number of generators of the modular forms ring (3)
TESTS::
sage: x,y = polygens(GF(7), 'x, y')
sage: ModularFormsRing(1, GF(7))(x)
Traceback (most recent call last):
...
NotImplementedError: conversion from polynomial is not implemented if the base ring is not Q
..TODO::
* add conversion for symbolic expressions?
"""
if not self.base_ring() == QQ: # this comes from the method gens_form
raise NotImplementedError("conversion from polynomial is not implemented if the base ring is not Q")
if not isinstance(polynomial, MPolynomial):
raise TypeError('`polynomial` must be a multivariate polynomial')
if gens is None:
gens = self.gen_forms()
dict = self._generators_variables_dictionnary(polynomial.parent(), gens)
if polynomial.is_constant():
return self(polynomial.constant_coefficient())
return polynomial.substitute(dict)
def _element_constructor_(self, forms_datum):
r"""
The call method of self.
INPUT:
- ``forms_datum`` (dict, list, ModularFormElement,
GradedModularFormElement, RingElement, Multivariate polynomial) -- Try
to coerce ``forms_datum`` into self.
TESTS::
sage: M = ModularFormsRing(1)
sage: E4 = ModularForms(1,4).0; E6 = ModularForms(1,6).0
sage: M([E4, E6])
2 - 264*q - 14472*q^2 - 116256*q^3 - 515208*q^4 - 1545264*q^5 + O(q^6)
sage: M([E4, E4])
2 + 480*q + 4320*q^2 + 13440*q^3 + 35040*q^4 + 60480*q^5 + O(q^6)
sage: M({4:E4, 6:E6})
2 - 264*q - 14472*q^2 - 116256*q^3 - 515208*q^4 - 1545264*q^5 + O(q^6)
sage: M(E4)
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6)
sage: x,y = polygens(QQ, 'x,y')
sage: M(x^2+x^3 + x*y + y^6)
4 - 2088*q + 3816216*q^2 - 2296935072*q^3 + 720715388184*q^4 - 77528994304752*q^5 + O(q^6)
sage: f = ModularForms(3, 10).0
sage: M(f)
Traceback (most recent call last):
...
ValueError: the group (Congruence Subgroup Gamma0(3)) and/or the base ring (Rational Field) of the given modular form is not consistant with the base space: Ring of Modular Forms for Modular Group SL(2,Z) over Rational Field
sage: M = ModularFormsRing(1, base_ring=ZZ)
sage: M(ModularForms(1,4).0)
Traceback (most recent call last):
...
ValueError: the group (Modular Group SL(2,Z)) and/or the base ring (Rational Field) of the given modular form is not consistant with the base space: Ring of Modular Forms for Modular Group SL(2,Z) over Integer Ring
sage: M('x')
Traceback (most recent call last):
...
TypeError: the defining data structure should be a single modular form, a ring element, a list of modular forms, a multivariate polynomial or a dictionary
sage: P.<t> = PowerSeriesRing(QQ)
sage: e = 1 + 240*t + 2160*t^2 + 6720*t^3 + 17520*t^4 + 30240*t^5 + O(t^6)
sage: ModularFormsRing(1)(e)
Traceback (most recent call last):
...
NotImplementedError: conversion from q-expansion not yet implemented
"""
if isinstance(forms_datum, (dict, list)):
forms_dictionary = forms_datum
elif isinstance(forms_datum, self.element_class):
forms_dictionary = forms_datum._forms_dictionary
elif is_ModularFormElement(forms_datum):
if self.group().is_subgroup(forms_datum.group()) and self.base_ring().has_coerce_map_from(forms_datum.base_ring()):
forms_dictionary = {forms_datum.weight(): forms_datum}
else:
raise ValueError('the group (%s) and/or the base ring (%s) of the given modular form is not consistant with the base space: %s'%(forms_datum.group(), forms_datum.base_ring(), self))
elif forms_datum in self.base_ring():
forms_dictionary = {0:forms_datum}
elif isinstance(forms_datum, MPolynomial):
return self.from_polynomial(forms_datum)
elif isinstance(forms_datum, PowerSeries_poly):
raise NotImplementedError("conversion from q-expansion not yet implemented")
else:
raise TypeError('the defining data structure should be a single modular form, a ring element, a list of modular forms, a multivariate polynomial or a dictionary')
return self.element_class(self, forms_dictionary)
def zero(self):
r"""
Return the zero element of this ring.
EXAMPLES::
sage: M = ModularFormsRing(1)
sage: zer = M.zero(); zer
0
sage: zer.is_zero()
True
sage: E4 = ModularForms(1,4).0; E4
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6)
sage: E4 + zer
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6)
sage: zer * E4
0
sage: E4 * zer
0
"""
return self.element_class(self, {})
def one(self):
r"""
Return the one element of this ring.
EXAMPLES::
sage: M = ModularFormsRing(1)
sage: u = M.one(); u
1
sage: u.is_one()
True
sage: u + u
2
sage: E4 = ModularForms(1,4).0; E4
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6)
sage: E4 * u
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + O(q^6)
"""
return self.element_class(self, {0: self.base_ring().one()})
def _coerce_map_from_(self, M):
r"""
Code to make ModularFormRing work well with coercion framework.
TESTS::
sage: M = ModularFormsRing(1)
sage: E6 = ModularForms(1,6).0
sage: D = ModularForms(1,12).1
sage: M(D) + E6
2 - 282744/691*q + 122757768/691*q^2 + 11521760544/691*q^3 + 274576933512/691*q^4 + 3198130142256/691*q^5 + O(q^6)
sage: D + M(E6)
2 - 282744/691*q + 122757768/691*q^2 + 11521760544/691*q^3 + 274576933512/691*q^4 + 3198130142256/691*q^5 + O(q^6)
sage: 14 + M(D)
15 + 65520/691*q + 134250480/691*q^2 + 11606736960/691*q^3 + 274945048560/691*q^4 + 3199218815520/691*q^5 + O(q^6)
sage: M(D) + 53
54 + 65520/691*q + 134250480/691*q^2 + 11606736960/691*q^3 + 274945048560/691*q^4 + 3199218815520/691*q^5 + O(q^6)
"""
if is_ModularFormsSpace(M):
if M.group() == self.group() and self.has_coerce_map_from(M.base_ring()):
return True
if self.base_ring().has_coerce_map_from(M):
return True
return False
def __richcmp__(self, other, op):
r"""
Compare self to other.
Rings are equal if and only if their groups and base rings are.
EXAMPLES::
sage: ModularFormsRing(3) == 3
False
sage: ModularFormsRing(Gamma0(3)) == ModularFormsRing(Gamma0(7))
False
sage: ModularFormsRing(Gamma0(3)) == ModularFormsRing(Gamma0(3))
True
"""
if not isinstance(other, ModularFormsRing):
return NotImplemented
return richcmp((self.group(), self.base_ring()),
(other.group(), other.base_ring()), op)
def _repr_(self):
r"""
String representation of self.
EXAMPLES::
sage: ModularFormsRing(Gamma0(13))._repr_()
'Ring of Modular Forms for Congruence Subgroup Gamma0(13) over Rational Field'
sage: ModularFormsRing(Gamma1(13), base_ring=ZZ)._repr_()
'Ring of Modular Forms for Congruence Subgroup Gamma1(13) over Integer Ring'
"""
return "Ring of Modular Forms for %s over %s" % (self.group(), self.base_ring())
def modular_forms_of_weight(self, weight):
"""
Return the space of modular forms on this group of the given weight.
EXAMPLES::
sage: R = ModularFormsRing(13)
sage: R.modular_forms_of_weight(10)
Modular Forms space of dimension 11 for Congruence Subgroup Gamma0(13) of weight 10 over Rational Field
sage: ModularFormsRing(Gamma1(13)).modular_forms_of_weight(3)
Modular Forms space of dimension 20 for Congruence Subgroup Gamma1(13) of weight 3 over Rational Field
"""
return ModularForms(self.group(), weight)
def generators(self, maxweight=8, prec=10, start_gens=[], start_weight=2):
r"""
If `R` is the base ring of self, then this function calculates a set of
modular forms which generate the `R`-algebra of all modular forms of
weight up to ``maxweight`` with coefficients in `R`.
INPUT:
- ``maxweight`` (integer, default: 8) -- check up to this weight for
generators
- ``prec`` (integer, default: 10) -- return `q`-expansions to this
precision
- ``start_gens`` (list, default: ``[]``) -- list of pairs `(k, f)`, or
triples `(k, f, F)`, where:
- `k` is an integer,
- `f` is the `q`-expansion of a modular form of weight `k`, as a power series over the base ring of self,
- `F` (if provided) is a modular form object corresponding to F.
If this list is nonempty, we find a minimal generating set containing
these forms. If `F` is not supplied, then `f` needs to have
sufficiently large precision (an error will be raised if this is not
the case); otherwise, more terms will be calculated from the modular
form object `F`.
- ``start_weight`` (integer, default: 2) -- calculate the graded
subalgebra of forms of weight at least ``start_weight``.
OUTPUT:
a list of pairs (k, f), where f is the q-expansion to precision
``prec`` of a modular form of weight k.
.. SEEALSO::
:meth:`gen_forms`, which does exactly the same thing, but returns
Sage modular form objects rather than bare power series, and keeps
track of a lifting to characteristic 0 when the base ring is a
finite field.
.. NOTE::
If called with the default values of ``start_gens`` (an empty list)
and ``start_weight`` (2), the values will be cached for re-use on
subsequent calls to this function. (This cache is shared with
:meth:`gen_forms`). If called with non-default values for these
parameters, caching will be disabled.
EXAMPLES::
sage: ModularFormsRing(SL2Z).generators()
[(4, 1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + 30240*q^5 + 60480*q^6 + 82560*q^7 + 140400*q^8 + 181680*q^9 + O(q^10)),
(6, 1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 - 1575504*q^5 - 4058208*q^6 - 8471232*q^7 - 17047800*q^8 - 29883672*q^9 + O(q^10))]
sage: s = ModularFormsRing(SL2Z).generators(maxweight=5, prec=3); s
[(4, 1 + 240*q + 2160*q^2 + O(q^3))]
sage: s[0][1].parent()
Power Series Ring in q over Rational Field
sage: ModularFormsRing(1).generators(prec=4)
[(4, 1 + 240*q + 2160*q^2 + 6720*q^3 + O(q^4)),
(6, 1 - 504*q - 16632*q^2 - 122976*q^3 + O(q^4))]
sage: ModularFormsRing(2).generators(prec=12)
[(2, 1 + 24*q + 24*q^2 + 96*q^3 + 24*q^4 + 144*q^5 + 96*q^6 + 192*q^7 + 24*q^8 + 312*q^9 + 144*q^10 + 288*q^11 + O(q^12)),
(4, 1 + 240*q^2 + 2160*q^4 + 6720*q^6 + 17520*q^8 + 30240*q^10 + O(q^12))]
sage: ModularFormsRing(4).generators(maxweight=2, prec=20)
[(2, 1 + 24*q^2 + 24*q^4 + 96*q^6 + 24*q^8 + 144*q^10 + 96*q^12 + 192*q^14 + 24*q^16 + 312*q^18 + O(q^20)),
(2, q + 4*q^3 + 6*q^5 + 8*q^7 + 13*q^9 + 12*q^11 + 14*q^13 + 24*q^15 + 18*q^17 + 20*q^19 + O(q^20))]
Here we see that for ``\Gamma_0(11)`` taking a basis of forms in weights 2
and 4 is enough to generate everything up to weight 12 (and probably
everything else).::
sage: v = ModularFormsRing(11).generators(maxweight=12)
sage: len(v)
3
sage: [k for k, _ in v]
[2, 2, 4]
sage: from sage.modular.dims import dimension_modular_forms
sage: dimension_modular_forms(11,2)
2
sage: dimension_modular_forms(11,4)
4
For congruence subgroups not containing -1, we miss out some forms since we
can't calculate weight 1 forms at present, but we can still find generators
for the ring of forms of weight `\ge 2`::
sage: ModularFormsRing(Gamma1(4)).generators(prec=10, maxweight=10)
[(2, 1 + 24*q^2 + 24*q^4 + 96*q^6 + 24*q^8 + O(q^10)),
(2, q + 4*q^3 + 6*q^5 + 8*q^7 + 13*q^9 + O(q^10)),
(3, 1 + 12*q^2 + 64*q^3 + 60*q^4 + 160*q^6 + 384*q^7 + 252*q^8 + O(q^10)),
(3, q + 4*q^2 + 8*q^3 + 16*q^4 + 26*q^5 + 32*q^6 + 48*q^7 + 64*q^8 + 73*q^9 + O(q^10))]
Using different base rings will change the generators::
sage: ModularFormsRing(Gamma0(13)).generators(maxweight=12, prec=4)
[(2, 1 + 2*q + 6*q^2 + 8*q^3 + O(q^4)),
(4, 1 + O(q^4)), (4, q + O(q^4)),
(4, q^2 + O(q^4)), (4, q^3 + O(q^4)),
(6, 1 + O(q^4)),
(6, q + O(q^4))]
sage: ModularFormsRing(Gamma0(13),base_ring=ZZ).generators(maxweight=12, prec=4)
[(2, 1 + 2*q + 6*q^2 + 8*q^3 + O(q^4)),
(4, q + 4*q^2 + 10*q^3 + O(q^4)),
(4, 2*q^2 + 5*q^3 + O(q^4)),
(4, q^2 + O(q^4)),
(4, -2*q^3 + O(q^4)),
(6, O(q^4)),
(6, O(q^4)),
(12, O(q^4))]
sage: [k for k,f in ModularFormsRing(1, QQ).generators(maxweight=12)]
[4, 6]
sage: [k for k,f in ModularFormsRing(1, ZZ).generators(maxweight=12)]
[4, 6, 12]
sage: [k for k,f in ModularFormsRing(1, Zmod(5)).generators(maxweight=12)]
[4, 6]
sage: [k for k,f in ModularFormsRing(1, Zmod(2)).generators(maxweight=12)]
[4, 6, 12]
An example where ``start_gens`` are specified::
sage: M = ModularForms(11, 2); f = (M.0 + M.1).qexp(8)
sage: ModularFormsRing(11).generators(start_gens = [(2, f)])
Traceback (most recent call last):
...
ValueError: Requested precision cannot be higher than precision of approximate starting generators!
sage: f = (M.0 + M.1).qexp(10); f
1 + 17/5*q + 26/5*q^2 + 43/5*q^3 + 94/5*q^4 + 77/5*q^5 + 154/5*q^6 + 86/5*q^7 + 36*q^8 + 146/5*q^9 + O(q^10)
sage: ModularFormsRing(11).generators(start_gens = [(2, f)])
[(2, 1 + 17/5*q + 26/5*q^2 + 43/5*q^3 + 94/5*q^4 + 77/5*q^5 + 154/5*q^6 + 86/5*q^7 + 36*q^8 + 146/5*q^9 + O(q^10)),
(2, 1 + 12*q^2 + 12*q^3 + 12*q^4 + 12*q^5 + 24*q^6 + 24*q^7 + 36*q^8 + 36*q^9 + O(q^10)),
(4, 1 + O(q^10))]
"""
sgs = []
for x in start_gens:
if len(x) == 2:
if x[1].prec() < prec:
raise ValueError("Requested precision cannot be higher than precision of approximate starting generators!")
sgs.append((x[0], x[1], None))
else:
sgs.append(x)
G = self._find_generators(maxweight, tuple(sgs), start_weight)
ret = []
# Returned generators may be a funny mixture of precisions if start_gens has been used.
for k, f, F in G:
if f.prec() < prec:
f = F.qexp(prec).change_ring(self.base_ring())
else:
f = f.truncate_powerseries(prec)
ret.append((k, f))
return ret
def gen_forms(self, maxweight=8, start_gens=[], start_weight=2):
r"""
Return a list of modular forms generating this ring (as an algebra over
the appropriate base ring).
This method differs from :meth:`generators` only in that it returns
graded modular form objects, rather than bare `q`-expansions.
INPUT:
- ``maxweight`` (integer, default: 8) -- calculate forms generating all
forms up to this weight
- ``start_gens`` (list, default: ``[]``) -- a list of modular forms. If
this list is nonempty, we find a minimal generating set containing
these forms
- ``start_weight`` (integer, default: 2) -- calculate the graded
subalgebra of forms of weight at least ``start_weight``
.. NOTE::
If called with the default values of ``start_gens`` (an empty list)
and ``start_weight`` (2), the values will be cached for re-use on
subsequent calls to this function. (This cache is shared with
:meth:`generators`). If called with non-default values for these
parameters, caching will be disabled.
EXAMPLES::
sage: A = ModularFormsRing(Gamma0(11), Zmod(5)).gen_forms(); A
[1 + 12*q^2 + 12*q^3 + 12*q^4 + 12*q^5 + O(q^6),
q - 2*q^2 - q^3 + 2*q^4 + q^5 + O(q^6),
q - 9*q^4 - 10*q^5 + O(q^6)]
sage: A[0].parent()
Modular Forms space of dimension 2 for Congruence Subgroup Gamma0(11) of weight 2 over Rational Field
"""
sgs = tuple( (F.weight(), None, F) for F in start_gens )
G = self._find_generators(maxweight, sgs, start_weight)
return [F for k,f,F in G]
gens = gen_forms
def _find_generators(self, maxweight, start_gens, start_weight):
r"""
For internal use. This function is called by :meth:`generators` and
:meth:`gen_forms`: it returns a list of triples `(k, f, F)` where `F`
is a modular form of weight `k` and `f` is its `q`-expansion coerced
into the base ring of self.
INPUT:
- ``maxweight`` -- maximum weight to try
- ``start_weight`` -- minimum weight to try
- ``start_gens`` -- a sequence of tuples of the form `(k, f, F)`, where
`F` is a modular form of weight `k` and `f` is its `q`-expansion
coerced into ``self.base_ring()`. Either (but not both) of `f` and `F`
may be ``None``.
OUTPUT:
a list of tuples, formatted as with ``start_gens``.
EXAMPLES::
sage: R = ModularFormsRing(Gamma1(4))
sage: R._find_generators(8, (), 2)
[(2, 1 + 24*q^2 + 24*q^4 + 96*q^6 + 24*q^8 + O(q^9), 1 + 24*q^2 + 24*q^4 + O(q^6)),
(2, q + 4*q^3 + 6*q^5 + 8*q^7 + O(q^9), q + 4*q^3 + 6*q^5 + O(q^6)),
(3, 1 + 12*q^2 + 64*q^3 + 60*q^4 + 160*q^6 + 384*q^7 + 252*q^8 + O(q^9), 1 + 12*q^2 + 64*q^3 + 60*q^4 + O(q^6)),
(3, q + 4*q^2 + 8*q^3 + 16*q^4 + 26*q^5 + 32*q^6 + 48*q^7 + 64*q^8 + O(q^9), q + 4*q^2 + 8*q^3 + 16*q^4 + 26*q^5 + O(q^6))]
"""
default_params = (start_gens == () and start_weight == 2)
if default_params and self.__cached_maxweight != -1:
verbose("Already know generators up to weight %s -- using those" % self.__cached_maxweight)
if self.__cached_maxweight >= maxweight:
return [(k, f, F) for k, f, F in self.__cached_gens if k <= maxweight]
start_gens = self.__cached_gens
start_weight = self.__cached_maxweight + 1
if self.group().is_even():
increment = 2
else:
increment = 1
working_prec = self.modular_forms_of_weight(maxweight).sturm_bound()
# parse the list of start gens
G = []
for x in start_gens:
k, f, F = x
if F is None and f.prec() < working_prec:
raise ValueError("Need start gens to precision at least %s" % working_prec)
elif f is None or f.prec() < working_prec:
f = F.qexp(working_prec).change_ring(self.base_ring())
G.append((k, f, F))
k = start_weight
if increment == 2 and (k % 2) == 1:
k += 1
while k <= maxweight:
if self.modular_forms_of_weight(k).dimension() == 0:
k += increment
continue
verbose('Looking at k = %s' % k)
M = self.modular_forms_of_weight(k)
# 1. Multiply together all forms in G that give an element
# of M.
if G:
F = _span_of_forms_in_weight(G, k, M.sturm_bound(), None, False)
else:
F = (self.base_ring() ** M.sturm_bound()).zero_submodule()
# 2. If the dimension of the span of the result is equal
# to the dimension of M, increment k.
if F.rank() == M.dimension():
if self.base_ring().is_field() or F.index_in_saturation() == 1:
# TODO: Do something clever if the submodule's of the right
# rank but not saturated -- avoid triggering needless
# modular symbol computations.
verbose('Nothing new in weight %s' % k)
k += increment
continue
# 3. If the dimension is less, compute a basis for G, and
# try adding basis elements of M into G.
verbose("Known generators span a subspace of dimension %s of space of dimension %s" % (F.dimension(), M.dimension()))
if self.base_ring() == ZZ:
verbose("saturation index is %s" % F.index_in_saturation())
t = verbose("Computing more modular forms at weight %s" % k)
kprec = M.sturm_bound()
if self.base_ring() == QQ:
B = M.q_echelon_basis(working_prec)
else:
B = M.q_integral_basis(working_prec)
t = verbose("done computing forms", t)
V = F.ambient_module().submodule_with_basis([f.padded_list(kprec) for f in B])
Q = V / F
for q in Q.gens():
try:
qc = V.coordinates(Q.lift(q))
except AttributeError:
# work around a silly free module bug
qc = V.coordinates(q.lift())
qcZZ = [ZZ(_) for _ in qc] # lift to ZZ so we can define F
f = sum([B[i] * qcZZ[i] for i in range(len(B))])
F = M(f)
G.append((k, f.change_ring(self.base_ring()), F))
verbose('added %s new generators' % Q.ngens(), t)
k += increment
if default_params:
self.__cached_maxweight = maxweight
self.__cached_gens = G
return G
@cached_method
def q_expansion_basis(self, weight, prec=None, use_random=True):
r"""
Calculate a basis of q-expansions for the space of modular forms of the
given weight for this group, calculated using the ring generators given
by ``find_generators``.
INPUT:
- ``weight`` (integer) -- the weight
- ``prec`` (integer or ``None``, default: ``None``) -- power series
precision. If ``None``, the precision defaults to the Sturm bound for
the requested level and weight.
- ``use_random`` (boolean, default: True) -- whether or not to use a
randomized algorithm when building up the space of forms at the given
weight from known generators of small weight.
EXAMPLES::
sage: m = ModularFormsRing(Gamma0(4))
sage: m.q_expansion_basis(2,10)
[1 + 24*q^2 + 24*q^4 + 96*q^6 + 24*q^8 + O(q^10),
q + 4*q^3 + 6*q^5 + 8*q^7 + 13*q^9 + O(q^10)]
sage: m.q_expansion_basis(3,10)
[]
sage: X = ModularFormsRing(SL2Z)
sage: X.q_expansion_basis(12, 10)
[1 + 196560*q^2 + 16773120*q^3 + 398034000*q^4 + 4629381120*q^5 + 34417656000*q^6 + 187489935360*q^7 + 814879774800*q^8 + 2975551488000*q^9 + O(q^10),
q - 24*q^2 + 252*q^3 - 1472*q^4 + 4830*q^5 - 6048*q^6 - 16744*q^7 + 84480*q^8 - 113643*q^9 + O(q^10)]
We calculate a basis of a massive modular forms space, in two ways.
Using this module is about twice as fast as Sage's generic code. ::
sage: A = ModularFormsRing(11).q_expansion_basis(30, prec=40) # long time (5s)
sage: B = ModularForms(Gamma0(11), 30).q_echelon_basis(prec=40) # long time (9s)
sage: A == B # long time
True
Check that absurdly small values of ``prec`` don't mess things up::
sage: ModularFormsRing(11).q_expansion_basis(10, prec=5)
[1 + O(q^5), q + O(q^5), q^2 + O(q^5), q^3 + O(q^5),
q^4 + O(q^5), O(q^5), O(q^5), O(q^5), O(q^5), O(q^5)]
"""
d = self.modular_forms_of_weight(weight).dimension()
if d == 0:
return []
if prec is None:
prec=self.modular_forms_of_weight(weight).sturm_bound()
working_prec = max(prec, self.modular_forms_of_weight(weight).sturm_bound())
gen_weight = min(6, weight)
while True:
verbose("Trying to generate the %s-dimensional space at weight %s using generators of weight up to %s" % (d, weight, gen_weight))
G = self.generators(maxweight=gen_weight, prec=working_prec)
V = _span_of_forms_in_weight(G, weight, prec=working_prec, use_random=use_random, stop_dim=d)
if V.rank() == d and (self.base_ring().is_field() or V.index_in_saturation() == 1):
break
else:
gen_weight += 1
verbose("Need more generators: trying again with generators of weight up to %s" % gen_weight)
R = G[0][1].parent()
return [R(list(x), prec=prec) for x in V.gens()]
def cuspidal_ideal_generators(self, maxweight=8, prec=None):
r"""
Calculate generators for the ideal of cuspidal forms in this ring, as a
module over the whole ring.
EXAMPLES::
sage: ModularFormsRing(Gamma0(3)).cuspidal_ideal_generators(maxweight=12)
[(6, q - 6*q^2 + 9*q^3 + 4*q^4 + O(q^5), q - 6*q^2 + 9*q^3 + 4*q^4 + 6*q^5 + O(q^6))]
sage: [k for k,f,F in ModularFormsRing(13, base_ring=ZZ).cuspidal_ideal_generators(maxweight=14)]
[4, 4, 4, 6, 6, 12]
"""
working_prec = self.modular_forms_of_weight(maxweight).sturm_bound()
if self.__cached_cusp_maxweight > -1:
k = self.__cached_cusp_maxweight + 1
verbose("Already calculated cusp gens up to weight %s -- using those" % (k-1))
# we may need to increase the precision of the cached cusp
# generators
G = []
for j,f,F in self.__cached_cusp_gens:
if f.prec() >= working_prec:
f = F.qexp(working_prec).change_ring(self.base_ring())
G.append( (j,f,F) )
else:
k = 2
G = []
while k <= maxweight:
t = verbose("Looking for cusp generators in weight %s" % k)
kprec = self.modular_forms_of_weight(k).sturm_bound()
flist = []
for (j, f, F) in G:
for g in self.q_expansion_basis(k - j, prec=kprec):
flist.append(g*f)
A = self.base_ring() ** kprec
W = A.span([A(f.padded_list(kprec)) for f in flist])
S = self.modular_forms_of_weight(k).cuspidal_submodule()
if (W.rank() == S.dimension()
and (self.base_ring().is_field() or W.index_in_saturation() == 1)):
verbose("Nothing new in weight %s" % k, t)
k += 1
continue
t = verbose("Known cusp generators span a submodule of dimension %s of space of dimension %s" % (W.rank(), S.dimension()), t)
B = S.q_integral_basis(prec=working_prec)
V = A.span([A(f.change_ring(self.base_ring()).padded_list(kprec)) for f in B])
Q = V/W
for q in Q.gens():
try:
qc = V.coordinates(Q.lift(q))
except AttributeError:
# work around a silly free module bug
qc = V.coordinates(q.lift())
qcZZ = [ZZ(_) for _ in qc] # lift to ZZ so we can define F
f = sum([B[i] * qcZZ[i] for i in range(len(B))])
F = S(f)
G.append((k, f.change_ring(self.base_ring()), F))
verbose('added %s new generators' % Q.ngens(), t)
k += 1
self.__cached_cusp_maxweight = maxweight
self.__cached_cusp_gens = G
if prec is None:
return G
elif prec <= working_prec:
return [ (k, f.truncate_powerseries(prec), F) for k,f,F in G]
else:
# user wants increased precision, so we may as well cache that
Gnew = [ (k, F.qexp(prec).change_ring(self.base_ring()), F) for k,f,F in G]
self.__cached_cusp_gens = Gnew
return Gnew
def cuspidal_submodule_q_expansion_basis(self, weight, prec=None):
r"""
Calculate a basis of `q`-expansions for the space of cusp forms of
weight ``weight`` for this group.
INPUT:
- ``weight`` (integer) -- the weight
- ``prec`` (integer or None) -- precision of `q`-expansions to return
ALGORITHM: Uses the method :meth:`cuspidal_ideal_generators` to
calculate generators of the ideal of cusp forms inside this ring. Then
multiply these up to weight ``weight`` using the generators of the
whole modular form space returned by :meth:`q_expansion_basis`.
EXAMPLES::
sage: R = ModularFormsRing(Gamma0(3))
sage: R.cuspidal_submodule_q_expansion_basis(20)
[q - 8532*q^6 - 88442*q^7 + O(q^8), q^2 + 207*q^6 + 24516*q^7 + O(q^8),
q^3 + 456*q^6 + O(q^8), q^4 - 135*q^6 - 926*q^7 + O(q^8), q^5 + 18*q^6 + 135*q^7 + O(q^8)]
We compute a basis of a space of very large weight, quickly (using this
module) and slowly (using modular symbols), and verify that the answers
are the same. ::
sage: A = R.cuspidal_submodule_q_expansion_basis(80, prec=30) # long time (1s on sage.math, 2013)
sage: B = R.modular_forms_of_weight(80).cuspidal_submodule().q_expansion_basis(prec=30) # long time (19s on sage.math, 2013)
sage: A == B # long time
True
"""
d = self.modular_forms_of_weight(weight).cuspidal_submodule().dimension()
if d == 0:
return []
minprec = self.modular_forms_of_weight(weight).sturm_bound()
if prec is None:
prec = working_prec = minprec
else:
working_prec = max(prec, minprec)
gen_weight = min(6, weight)
while True:
verbose("Trying to generate the %s-dimensional cuspidal submodule at weight %s using generators of weight up to %s" % (d, weight, gen_weight))
G = self.cuspidal_ideal_generators(maxweight=gen_weight, prec=working_prec)
flist = []
for (j, f, F) in G:
for g in self.q_expansion_basis(weight - j, prec=working_prec):
flist.append(g*f)
A = self.base_ring() ** working_prec
W = A.span([A(f.padded_list(working_prec)) for f in flist])
if W.rank() == d and (self.base_ring().is_field() or W.index_in_saturation() == 1):
break
else:
gen_weight += 1
verbose("Need more generators: trying again with generators of weight up to %s" % gen_weight)
R = G[0][1].parent()
return [R(list(x), prec=prec) for x in W.gens()]
# Deprecated functions
find_generators = deprecated_function_alias(31559, ModularFormsRing.generators)
basis_for_modform_space = deprecated_function_alias(31559, ModularFormsRing.q_expansion_basis) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/modform/ring.py | 0.804521 | 0.632077 | ring.py | pypi |
r"""
Weight 1 modular forms
This module contains routines for computing weight 1 modular forms, using
George Schaeffer's "Hecke stability" algorithm (detailed in [Sch2015]_). These
functions are mostly for internal use; a more convenient interface is offered
by the usual ModularForms and CuspForms constructors.
AUTHORS:
- David Loeffler (2017-11): first version
"""
from sage.misc.cachefunc import cached_function
from sage.rings.integer_ring import ZZ
from sage.rings.power_series_ring import PowerSeriesRing
from sage.misc.verbose import verbose
from sage.structure.sequence import Sequence
from sage.modular.arithgroup.all import Gamma0, GammaH
from sage.modular.arithgroup.arithgroup_generic import ArithmeticSubgroup
@cached_function
def modular_ratio_space(chi):
r"""
Compute the space of 'modular ratios', i.e. meromorphic modular forms f
level N and character chi such that f * E is a holomorphic cusp form for
every Eisenstein series E of weight 1 and character 1/chi.
Elements are returned as q-expansions up to precision R, where R is one
greater than the weight 3 Sturm bound.
EXAMPLES::
sage: chi = DirichletGroup(31,QQ).0
sage: sage.modular.modform.weight1.modular_ratio_space(chi)
[q - 8/3*q^3 + 13/9*q^4 + 43/27*q^5 - 620/81*q^6 + 1615/243*q^7 + 3481/729*q^8 + O(q^9),
q^2 - 8/3*q^3 + 13/9*q^4 + 70/27*q^5 - 620/81*q^6 + 1858/243*q^7 + 2752/729*q^8 + O(q^9)]
"""
from sage.modular.modform.constructor import EisensteinForms, CuspForms
if chi(-1) == 1:
return []
N = chi.modulus()
chi = chi.minimize_base_ring()
K = chi.base_ring()
R = Gamma0(N).sturm_bound(3) + 1
verbose("Working precision is %s" % R, level=1)
verbose("Coeff field is %s" % K, level=1)
V = K**R
I = V
d = I.rank()
t = verbose("Calculating Eisenstein forms in weight 1...",level=1)
B0 = EisensteinForms(~chi, 1).q_echelon_basis(prec=R)
B = [b + B0[0] for b in B0]
verbose("Done (dimension %s)" % len(B),level=1,t=t)
t = verbose("Calculating in weight 2...", level=1)
C = CuspForms(Gamma0(N), 2).q_echelon_basis(prec=R)
verbose("Done (dimension %s)" % len(C), t=t, level=1)
t = verbose("Computing candidate space", level=1)
for b in B:
quots = (c/b for c in C)
W = V.span(V(x.padded_list(R)) for x in quots)
I = I.intersection(W)
if I.rank() < d:
verbose(" Cut down to dimension %s" % I.rank(), level=1)
d = I.rank()
if I.rank() == 0:
break
verbose("Done: intersection is %s-dimensional" % I.dimension(), t=t, level=1)
A = PowerSeriesRing(K, 'q')
return [A(x.list()).add_bigoh(R) for x in I.gens()]
def modular_ratio_to_prec(chi, qexp, prec):
r"""
Given a q-expansion of a modular ratio up to sufficient precision to
determine it uniquely, compute it to greater precision.
EXAMPLES::
sage: from sage.modular.modform.weight1 import modular_ratio_to_prec
sage: R.<q> = QQ[[]]
sage: modular_ratio_to_prec(DirichletGroup(31,QQ).0, q-q^2-q^5-q^7+q^8+O(q^9), 20)
q - q^2 - q^5 - q^7 + q^8 + q^9 + q^10 + q^14 - q^16 - q^18 - q^19 + O(q^20)
"""
if prec <= qexp.prec():
return qexp.add_bigoh(prec)
from sage.modular.modform.constructor import EisensteinForms, CuspForms
C = CuspForms(chi.level(), 2, base_ring=qexp.base_ring())
B = EisensteinForms(~chi, 1).gen(0).qexp(prec)
qexp = qexp.add_bigoh(C.sturm_bound())
fB = qexp * B
fB_elt = C(fB, check=False)
return fB_elt.qexp(prec) / B
@cached_function
def hecke_stable_subspace(chi, aux_prime=ZZ(2)):
r"""
Compute a q-expansion basis for S_1(chi).
Results are returned as q-expansions to a certain fixed (and fairly high)
precision. If more precision is required this can be obtained with
:func:`modular_ratio_to_prec`.
EXAMPLES::
sage: from sage.modular.modform.weight1 import hecke_stable_subspace
sage: hecke_stable_subspace(DirichletGroup(59, QQ).0)
[q - q^3 + q^4 - q^5 - q^7 - q^12 + q^15 + q^16 + 2*q^17 - q^19 - q^20 + q^21 + q^27 - q^28 - q^29 + q^35 + O(q^40)]
"""
# Deal quickly with the easy cases.
if chi(-1) == 1:
return []
N = chi.modulus()
H = chi.kernel()
G = GammaH(N, H)
try:
if ArithmeticSubgroup.dimension_cusp_forms(G, 1) == 0:
verbose("no wt 1 cusp forms for N=%s, chi=%s by Riemann-Roch" % (N, chi._repr_short_()), level=1)
return []
except NotImplementedError:
pass
from sage.modular.modform.constructor import EisensteinForms
chi = chi.minimize_base_ring()
K = chi.base_ring()
# Auxiliary prime for Hecke stability method
l = aux_prime
while l.divides(N):
l = l.next_prime()
verbose("Auxiliary prime: %s" % l, level=1)
# Compute working precision
R = l*Gamma0(N).sturm_bound(l + 2)
t = verbose("Computing modular ratio space", level=1)
mrs = modular_ratio_space(chi)
t = verbose("Computing modular ratios to precision %s" % R, level=1)
qexps = [modular_ratio_to_prec(chi, f, R) for f in mrs]
verbose("Done", t=t, level=1)
# We want to compute the largest subspace of I stable under T_l. To do
# this, we compute I intersect T_l(I) modulo q^(R/l), and take its preimage
# under T_l, which is then well-defined modulo q^R.
from sage.modular.modform.hecke_operator_on_qexp import hecke_operator_on_qexp
t = verbose("Computing Hecke-stable subspace", level=1)
A = PowerSeriesRing(K, 'q')
r = R // l
V = K**R
W = K**r
Tl_images = [hecke_operator_on_qexp(f, l, 1, chi) for f in qexps]
qvecs = [V(x.padded_list(R)) for x in qexps]
qvecs_trunc = [W(x.padded_list(r)) for x in qexps]
Tvecs = [W(x.padded_list(r)) for x in Tl_images]
I = V.submodule(qvecs)
Iimage = W.span(qvecs_trunc)
TlI = W.span(Tvecs)
Jimage = Iimage.intersection(TlI)
J = I.Hom(W)(Tvecs).inverse_image(Jimage)
verbose("Hecke-stable subspace is %s-dimensional" % J.dimension(), t=t, level=1)
if J.rank() == 0:
return []
# The theory does not guarantee that J is exactly S_1(chi), just that it is
# intermediate between S_1(chi) and M_1(chi). In every example I know of,
# it is equal to S_1(chi), but just for honesty, we check this anyway.
t=verbose("Checking cuspidality", level=1)
JEis = V.span(V(x.padded_list(R)) for x in EisensteinForms(chi, 1).q_echelon_basis(prec=R))
D = JEis.intersection(J)
if D.dimension() != 0:
raise ArithmeticError("Got non-cuspidal form!")
verbose("Done", t=t, level=1)
qexps = Sequence(A(x.list()).add_bigoh(R) for x in J.gens())
return qexps
@cached_function
def dimension_wt1_cusp_forms(chi):
r"""
Return the dimension of the space of cusp forms of weight 1 and character chi.
EXAMPLES::
sage: chi = DirichletGroup(59, QQ).0
sage: sage.modular.modform.weight1.dimension_wt1_cusp_forms(chi)
1
"""
return len(hecke_stable_subspace(chi))
@cached_function
def dimension_wt1_cusp_forms_gH(group):
r"""
Return the dimension of the space of cusp forms of weight 1 for the given
group (which should be of GammaH type). Computed by summing over Galois
orbits of characters modulo H.
EXAMPLES::
sage: sage.modular.modform.weight1.dimension_wt1_cusp_forms_gH(GammaH(31, [7]))
1
"""
chis = [g.minimize_base_ring() for g in group.characters_mod_H(galois_orbits=True)]
return sum(dimension_wt1_cusp_forms(chi) * chi.base_ring().degree() for chi in chis) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/modform/weight1.py | 0.870762 | 0.604574 | weight1.py | pypi |
from sage.matrix.constructor import matrix
from sage.modular.arithgroup.all import is_Gamma0
from sage.modular.cusps import Cusp
from sage.rings.infinity import infinity
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from .finite_subgroup import FiniteSubgroup
class CuspidalSubgroup_generic(FiniteSubgroup):
def _compute_lattice(self, rational_only=False, rational_subgroup=False):
r"""
Return a list of vectors that define elements of the rational
homology that generate this finite subgroup.
INPUT:
- ``rational_only`` - bool (default: False); if
``True``, only use rational cusps.
OUTPUT:
- ``list`` - list of vectors
EXAMPLES::
sage: J = J0(37)
sage: C = sage.modular.abvar.cuspidal_subgroup.CuspidalSubgroup(J)
sage: C._compute_lattice()
Free module of degree 4 and rank 4 over Integer Ring
Echelon basis matrix:
[ 1 0 0 0]
[ 0 1 0 0]
[ 0 0 1 0]
[ 0 0 0 1/3]
sage: J = J0(43)
sage: C = sage.modular.abvar.cuspidal_subgroup.CuspidalSubgroup(J)
sage: C._compute_lattice()
Free module of degree 6 and rank 6 over Integer Ring
Echelon basis matrix:
[ 1 0 0 0 0 0]
[ 0 1/7 0 6/7 0 5/7]
[ 0 0 1 0 0 0]
[ 0 0 0 1 0 0]
[ 0 0 0 0 1 0]
[ 0 0 0 0 0 1]
sage: J = J0(22)
sage: C = sage.modular.abvar.cuspidal_subgroup.CuspidalSubgroup(J)
sage: C._compute_lattice()
Free module of degree 4 and rank 4 over Integer Ring
Echelon basis matrix:
[1/5 1/5 4/5 0]
[ 0 1 0 0]
[ 0 0 1 0]
[ 0 0 0 1/5]
sage: J = J1(13)
sage: C = sage.modular.abvar.cuspidal_subgroup.CuspidalSubgroup(J)
sage: C._compute_lattice()
Free module of degree 4 and rank 4 over Integer Ring
Echelon basis matrix:
[1/19 0 9/19 9/19]
[ 0 1/19 0 9/19]
[ 0 0 1 0]
[ 0 0 0 1]
We compute with and without the optional
``rational_only`` option.
::
sage: J = J0(27); G = sage.modular.abvar.cuspidal_subgroup.CuspidalSubgroup(J)
sage: G._compute_lattice()
Free module of degree 2 and rank 2 over Integer Ring
Echelon basis matrix:
[1/3 0]
[ 0 1/3]
sage: G._compute_lattice(rational_only=True)
Free module of degree 2 and rank 2 over Integer Ring
Echelon basis matrix:
[1/3 0]
[ 0 1]
"""
A = self.abelian_variety()
Cusp = A.modular_symbols()
Amb = Cusp.ambient_module()
Eis = Amb.eisenstein_submodule()
C = Amb.cusps()
N = Amb.level()
if rational_subgroup:
# QQ-rational subgroup of cuspidal subgroup
assert A.is_ambient()
Q = Cusp.abvarquo_rational_cuspidal_subgroup()
return Q.V()
if rational_only:
# subgroup generated by differences of rational cusps
if not is_Gamma0(A.group()):
raise NotImplementedError('computation of rational cusps only implemented in Gamma0 case.')
if not N.is_squarefree():
data = [n for n in N.coprime_integers(N) if n >= 2]
C = [c for c in C if is_rational_cusp_gamma0(c, N, data)]
v = [Amb([infinity, alpha]).element() for alpha in C]
cusp_matrix = matrix(QQ, len(v), Amb.dimension(), v)
# TODO -- refactor something out here
# Now we project onto the cuspidal part.
B = Cusp.free_module().basis_matrix().stack(Eis.free_module().basis_matrix())
X = B.solve_left(cusp_matrix)
X = X.matrix_from_columns(range(Cusp.dimension()))
lattice = X.row_module(ZZ) + A.lattice()
return lattice
class CuspidalSubgroup(CuspidalSubgroup_generic):
"""
EXAMPLES::
sage: a = J0(65)[2]
sage: t = a.cuspidal_subgroup()
sage: t.order()
6
"""
def _repr_(self):
"""
String representation of the cuspidal subgroup.
EXAMPLES::
sage: G = J0(27).cuspidal_subgroup()
sage: G._repr_()
'Finite subgroup with invariants [3, 3] over QQ of Abelian variety J0(27) of dimension 1'
"""
return "Cuspidal subgroup %sover QQ of %s"%(self._invariants_repr(), self.abelian_variety())
def lattice(self):
"""
Returned cached tuple of vectors that define elements of the
rational homology that generate this finite subgroup.
OUTPUT:
- ``tuple`` - cached
EXAMPLES::
sage: J = J0(27)
sage: G = J.cuspidal_subgroup()
sage: G.lattice()
Free module of degree 2 and rank 2 over Integer Ring
Echelon basis matrix:
[1/3 0]
[ 0 1/3]
Test that the result is cached::
sage: G.lattice() is G.lattice()
True
"""
try:
return self.__lattice
except AttributeError:
lattice = self._compute_lattice(rational_only=False)
self.__lattice = lattice
return lattice
class RationalCuspSubgroup(CuspidalSubgroup_generic):
"""
EXAMPLES::
sage: a = J0(65)[2]
sage: t = a.rational_cusp_subgroup()
sage: t.order()
6
"""
def _repr_(self):
"""
String representation of the cuspidal subgroup.
EXAMPLES::
sage: G = J0(27).rational_cusp_subgroup()
sage: G._repr_()
'Finite subgroup with invariants [3] over QQ of Abelian variety J0(27) of dimension 1'
"""
return "Subgroup generated by differences of rational cusps %sover QQ of %s"%(self._invariants_repr(), self.abelian_variety())
def lattice(self):
"""
Return lattice that defines this group.
OUTPUT: lattice
EXAMPLES::
sage: G = J0(27).rational_cusp_subgroup()
sage: G.lattice()
Free module of degree 2 and rank 2 over Integer Ring
Echelon basis matrix:
[1/3 0]
[ 0 1]
Test that the result is cached.
::
sage: G.lattice() is G.lattice()
True
"""
try:
return self.__lattice
except AttributeError:
lattice = self._compute_lattice(rational_only=True)
self.__lattice = lattice
return lattice
class RationalCuspidalSubgroup(CuspidalSubgroup_generic):
"""
EXAMPLES::
sage: a = J0(65)[2]
sage: t = a.rational_cuspidal_subgroup()
sage: t.order()
6
"""
def _repr_(self):
"""
String representation of the cuspidal subgroup.
EXAMPLES::
sage: G = J0(27).rational_cuspidal_subgroup()
sage: G._repr_()
'Finite subgroup with invariants [3] over QQ of Abelian variety J0(27) of dimension 1'
"""
return "Rational cuspidal subgroup %sover QQ of %s"%(self._invariants_repr(), self.abelian_variety())
def lattice(self):
"""
Return lattice that defines this group.
OUTPUT: lattice
EXAMPLES::
sage: G = J0(27).rational_cuspidal_subgroup()
sage: G.lattice()
Free module of degree 2 and rank 2 over Integer Ring
Echelon basis matrix:
[1/3 0]
[ 0 1]
Test that the result is cached.
::
sage: G.lattice() is G.lattice()
True
"""
try:
return self.__lattice
except AttributeError:
lattice = self._compute_lattice(rational_subgroup=True)
self.__lattice = lattice
return lattice
def is_rational_cusp_gamma0(c, N, data):
"""
Return True if the rational number c is a rational cusp of level N.
This uses remarks in Glenn Steven's Ph.D. thesis.
INPUT:
- ``c`` - a cusp
- ``N`` - a positive integer
- ``data`` - the list [n for n in range(2,N) if
gcd(n,N) == 1], which is passed in as a parameter purely for
efficiency reasons.
EXAMPLES::
sage: from sage.modular.abvar.cuspidal_subgroup import is_rational_cusp_gamma0
sage: N = 27
sage: data = [n for n in range(2,N) if gcd(n,N) == 1]
sage: is_rational_cusp_gamma0(Cusp(1/3), N, data)
False
sage: is_rational_cusp_gamma0(Cusp(1), N, data)
True
sage: is_rational_cusp_gamma0(Cusp(oo), N, data)
True
sage: is_rational_cusp_gamma0(Cusp(2/9), N, data)
False
"""
num = c.numerator()
den = c.denominator()
return all(c.is_gamma0_equiv(Cusp(num, d * den), N) for d in data) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/abvar/cuspidal_subgroup.py | 0.489259 | 0.448245 | cuspidal_subgroup.py | pypi |
from sage.structure.sage_object import SageObject
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.integer import Integer
from sage.rings.infinity import infinity
from sage.rings.cc import CC
from sage.modules.free_module import span
from sage.misc.misc_c import prod
class Lseries(SageObject):
"""
Base class for `L`-series attached to modular abelian varieties.
This is a common base class for complex and `p`-adic `L`-series
of modular abelian varieties.
"""
def __init__(self, abvar):
"""
Called when creating an L-series.
INPUT:
- ``abvar`` -- a modular abelian variety
EXAMPLES::
sage: J0(11).lseries()
Complex L-series attached to Abelian variety J0(11) of dimension 1
sage: J0(11).padic_lseries(7)
7-adic L-series attached to Abelian variety J0(11) of dimension 1
"""
self.__abvar = abvar
def abelian_variety(self):
"""
Return the abelian variety that this `L`-series is attached to.
OUTPUT:
a modular abelian variety
EXAMPLES::
sage: J0(11).padic_lseries(7).abelian_variety()
Abelian variety J0(11) of dimension 1
"""
return self.__abvar
class Lseries_complex(Lseries):
"""
A complex `L`-series attached to a modular abelian variety.
EXAMPLES::
sage: A = J0(37)
sage: A.lseries()
Complex L-series attached to Abelian variety J0(37) of dimension 2
"""
def __call__(self, s, prec=53):
"""
Evaluate this complex `L`-series at `s`.
INPUT:
- ``s`` -- complex number
- ``prec`` -- integer (default: 53) the number of bits of precision
used in computing the lseries of the newforms.
OUTPUT:
a complex number L(A, s).
EXAMPLES::
sage: L = J0(23).lseries()
sage: L(1)
0.248431866590600
sage: L(1, prec=100)
0.24843186659059968120725033931
sage: L = J0(389)[0].lseries()
sage: L(1) # long time (2s) abstol 1e-10
-1.33139759782370e-19
sage: L(1, prec=100) # long time (2s) abstol 1e-20
6.0129758648142797032650287762e-39
sage: L.rational_part()
0
sage: L = J1(23)[0].lseries()
sage: L(1)
0.248431866590600
sage: J = J0(11) * J1(11)
sage: J.lseries()(1)
0.0644356903227915
sage: L = JH(17,[2]).lseries()
sage: L(1)
0.386769938387780
"""
abelian_variety = self.abelian_variety()
# Check for easy dimension zero case
if abelian_variety.dimension() == 0:
return CC(1)
try:
factors = self.__factors[prec]
return prod(L(s) for L in factors)
except AttributeError:
self.__factors = {}
except KeyError:
pass
abelian_variety = self.abelian_variety()
newforms = abelian_variety.newform_decomposition('a')
factors = [newform.lseries(embedding=i, prec=prec)
for newform in newforms
for i in range(newform.base_ring().degree())]
self.__factors[prec] = factors
return prod(L(s) for L in factors)
def __eq__(self, other):
"""
Compare this complex `L`-series to another one.
INPUT:
- ``other`` -- object
OUTPUT:
boolean
EXAMPLES::
sage: L = J0(37)[0].lseries()
sage: M = J0(37)[1].lseries()
sage: L == M
False
sage: L == L
True
"""
if not isinstance(other, Lseries_complex):
return False
return self.abelian_variety() == other.abelian_variety()
def __ne__(self, other):
"""
Check whether ``self`` is not equal to ``other``.
INPUT:
- ``other`` -- object
OUTPUT:
boolean
EXAMPLES::
sage: L = J0(37)[0].lseries()
sage: M = J0(37)[1].lseries()
sage: L != M
True
sage: L != L
False
"""
return not (self == other)
def _repr_(self):
"""
String representation of `L`-series.
OUTPUT:
a string
EXAMPLES::
sage: L = J0(37).lseries()
sage: L._repr_()
'Complex L-series attached to Abelian variety J0(37) of dimension 2'
"""
return "Complex L-series attached to %s" % self.abelian_variety()
def vanishes_at_1(self):
"""
Return True if `L(1)=0` and return False otherwise.
OUTPUT:
a boolean
EXAMPLES:
Numerically, the `L`-series for `J_0(389)` appears to vanish
at 1. This is confirmed by this algebraic computation::
sage: L = J0(389)[0].lseries(); L
Complex L-series attached to Simple abelian subvariety 389a(1,389) of dimension 1 of J0(389)
sage: L(1) # long time (2s) abstol 1e-10
-1.33139759782370e-19
sage: L.vanishes_at_1()
True
Numerically, one might guess that the `L`-series for `J_1(23)`
and `J_1(31)` vanish at 1. This algebraic computation shows
otherwise::
sage: L = J1(23).lseries(); L
Complex L-series attached to Abelian variety J1(23) of dimension 12
sage: L(1) # long time (about 3 s)
0.0001295198...
sage: L.vanishes_at_1()
False
sage: abs(L(1, prec=100)- 0.00012951986142702571478817757148) < 1e-32 # long time (about 3 s)
True
sage: L = J1(31).lseries(); L
Complex L-series attached to Abelian variety J1(31) of dimension 26
sage: abs(L(1) - 3.45014267547611e-7) < 1e-15 # long time (about 8 s)
True
sage: L.vanishes_at_1() # long time (about 6 s)
False
"""
abelian_variety = self.abelian_variety()
# Check for easy dimension zero case
if abelian_variety.dimension() == 0:
return False
if not abelian_variety.is_simple():
from .constructor import AbelianVariety
decomp = (AbelianVariety(f) for f in
abelian_variety.newform_decomposition('a'))
return any(S.lseries().vanishes_at_1() for S in decomp)
modular_symbols = abelian_variety.modular_symbols()
Phi = modular_symbols.rational_period_mapping()
ambient_module = modular_symbols.ambient_module()
e = ambient_module([0, infinity])
return Phi(e).is_zero()
def rational_part(self):
"""
Return the rational part of this `L`-function at the central critical
value 1.
OUTPUT:
a rational number
EXAMPLES::
sage: A, B = J0(43).decomposition()
sage: A.lseries().rational_part()
0
sage: B.lseries().rational_part()
2/7
"""
abelian_variety = self.abelian_variety()
modular_symbols = abelian_variety.modular_symbols()
Phi = modular_symbols.rational_period_mapping()
ambient_module = modular_symbols.ambient_module()
if self.vanishes_at_1():
return QQ(0)
else:
s = ambient_module.sturm_bound()
I = ambient_module.hecke_images(0, range(1, s+1))
PhiTe = span([Phi(ambient_module(I[n]))
for n in range(I.nrows())], ZZ)
ambient_plus = ambient_module.sign_submodule(1)
ambient_plus_cusp = ambient_plus.cuspidal_submodule()
PhiH1plus = span([Phi(x) for
x in ambient_plus_cusp.integral_basis()], ZZ)
return PhiTe.index_in(PhiH1plus)
lratio = rational_part
class Lseries_padic(Lseries):
"""
A `p`-adic `L`-series attached to a modular abelian variety.
"""
def __init__(self, abvar, p):
"""
Create a `p`-adic `L`-series.
EXAMPLES::
sage: J0(37)[0].padic_lseries(389)
389-adic L-series attached to Simple abelian subvariety 37a(1,37) of dimension 1 of J0(37)
"""
Lseries.__init__(self, abvar)
p = Integer(p)
if not p.is_prime():
raise ValueError("p (=%s) must be prime"%p)
self.__p = p
def __eq__(self, other):
"""
Compare this `p`-adic `L`-series to another one.
First the abelian varieties are compared; if they are the same,
then the primes are compared.
INPUT:
other -- object
OUTPUT:
boolean
EXAMPLES::
sage: L = J0(37)[0].padic_lseries(5)
sage: M = J0(37)[1].padic_lseries(5)
sage: K = J0(37)[0].padic_lseries(3)
sage: L == K
False
sage: L == M
False
sage: L == L
True
"""
if not isinstance(other, Lseries_padic):
return False
return (self.abelian_variety() == other.abelian_variety() and
self.__p == other.__p)
def __ne__(self, other):
"""
Check whether ``self`` is not equal to ``other``.
INPUT:
other -- object
OUTPUT:
boolean
EXAMPLES::
sage: L = J0(37)[0].padic_lseries(5)
sage: M = J0(37)[1].padic_lseries(5)
sage: K = J0(37)[0].padic_lseries(3)
sage: L != K
True
sage: L != M
True
sage: L != L
False
"""
return not (self == other)
def prime(self):
"""
Return the prime `p` of this `p`-adic `L`-series.
EXAMPLES::
sage: J0(11).padic_lseries(7).prime()
7
"""
return self.__p
def power_series(self, n=2, prec=5):
"""
Return the `n`-th approximation to this `p`-adic `L`-series as
a power series in `T`.
Each coefficient is a `p`-adic number
whose precision is provably correct.
NOTE: This is not yet implemented.
EXAMPLES::
sage: L = J0(37)[0].padic_lseries(5)
sage: L.power_series()
Traceback (most recent call last):
...
NotImplementedError
sage: L.power_series(3,7)
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
def _repr_(self):
"""
String representation of this `p`-adic `L`-series.
EXAMPLES::
sage: L = J0(37)[0].padic_lseries(5)
sage: L._repr_()
'5-adic L-series attached to Simple abelian subvariety 37a(1,37) of dimension 1 of J0(37)'
"""
return "%s-adic L-series attached to %s" % (self.__p,
self.abelian_variety()) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/abvar/lseries.py | 0.882908 | 0.585279 | lseries.py | pypi |
from sage.misc.lazy_import import lazy_import
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.modular.modform.element import Newform
from sage.modular.arithgroup.all import is_Gamma0, is_Gamma1, is_GammaH
from .abvar import ModularAbelianVariety_modsym_abstract
from . import homspace
lazy_import('sage.databases.cremona', 'cremona_letter_code')
class ModularAbelianVariety_newform(ModularAbelianVariety_modsym_abstract):
"""
A modular abelian variety attached to a specific newform.
"""
def __init__(self, f, internal_name=False):
"""
Create the modular abelian variety `A_f` attached to the
newform `f`.
INPUT:
f -- a newform
EXAMPLES::
sage: f = CuspForms(37).newforms('a')[0]
sage: f.abelian_variety()
Newform abelian subvariety 37a of dimension 1 of J0(37)
sage: AbelianVariety(Newforms(1, 12)[0])
Traceback (most recent call last):
...
TypeError: f must have weight 2
"""
if not isinstance(f, Newform):
raise TypeError("f must be a newform")
if f.weight() != 2:
raise TypeError("f must have weight 2")
self.__f = f
self._is_hecke_stable = True
K = f.qexp().base_ring()
if K == QQ:
variable_name = None
else:
variable_name = K.variable_name()
self.__named_newforms = {variable_name: self.__f}
if not internal_name:
self.__named_newforms[None] = self.__f
ModularAbelianVariety_modsym_abstract.__init__(self, (f.group(),), QQ,
is_simple=True, newform_level=(f.level(), f.group()),
isogeny_number=f.number(), number=0)
def _modular_symbols(self, sign=0):
"""
EXAMPLES::
sage: f = CuspForms(52).newforms('a')[0]
sage: A = f.abelian_variety()
sage: A._modular_symbols()
Modular Symbols subspace of dimension 2 of Modular Symbols space of dimension 15 for Gamma_0(52) of weight 2 with sign 0 over Rational Field
sage: A._modular_symbols(1)
Modular Symbols subspace of dimension 1 of Modular Symbols space of dimension 10 for Gamma_0(52) of weight 2 with sign 1 over Rational Field
sage: A._modular_symbols(-1)
Modular Symbols subspace of dimension 1 of Modular Symbols space of dimension 5 for Gamma_0(52) of weight 2 with sign -1 over Rational Field
"""
return self.__f.modular_symbols(sign=sign)
def newform(self, names=None):
r"""
Return the newform that this modular abelian variety is attached to.
EXAMPLES::
sage: f = Newform('37a')
sage: A = f.abelian_variety()
sage: A.newform()
q - 2*q^2 - 3*q^3 + 2*q^4 - 2*q^5 + O(q^6)
sage: A.newform() is f
True
If the a variable name has not been specified, we must specify one::
sage: A = AbelianVariety('67b')
sage: A.newform()
Traceback (most recent call last):
...
TypeError: You must specify the name of the generator.
sage: A.newform('alpha')
q + alpha*q^2 + (-alpha - 3)*q^3 + (-3*alpha - 3)*q^4 - 3*q^5 + O(q^6)
If the eigenform is actually over `\QQ` then we don't have to specify
the name::
sage: A = AbelianVariety('67a')
sage: A.newform()
q + 2*q^2 - 2*q^3 + 2*q^4 + 2*q^5 + O(q^6)
"""
try:
return self.__named_newforms[names]
except KeyError:
self.__named_newforms[names] = Newform(self.__f.parent().change_ring(QQ), self.__f.modular_symbols(1), names=names, check=False)
return self.__named_newforms[names]
def label(self) -> str:
"""
Return canonical label that defines this newform modular
abelian variety.
OUTPUT:
string
EXAMPLES::
sage: A = AbelianVariety('43b')
sage: A.label()
'43b'
"""
G = self.__f.group()
if is_Gamma0(G):
group = ''
elif is_Gamma1(G):
group = 'G1'
elif is_GammaH(G):
group = 'GH[' + ','.join(str(z) for z in G._generators_for_H()) + ']'
return '%s%s%s' % (self.level(), cremona_letter_code(self.factor_number()), group)
def factor_number(self):
"""
Return factor number.
OUTPUT:
int
EXAMPLES::
sage: A = AbelianVariety('43b')
sage: A.factor_number()
1
"""
try:
return self.__factor_number
except AttributeError:
self.__factor_number = self.__f.number()
return self.__factor_number
def _repr_(self) -> str:
"""
String representation of this modular abelian variety.
EXAMPLES::
sage: AbelianVariety('37a')._repr_()
'Newform abelian subvariety 37a of dimension 1 of J0(37)'
"""
return "Newform abelian subvariety %s of dimension %s of %s" % (
self.newform_label(), self.dimension(), self._ambient_repr())
def endomorphism_ring(self):
"""
Return the endomorphism ring of this newform abelian variety.
EXAMPLES::
sage: A = AbelianVariety('23a')
sage: E = A.endomorphism_ring(); E
Endomorphism ring of Newform abelian subvariety 23a of dimension 2 of J0(23)
We display the matrices of these two basis matrices::
sage: E.0.matrix()
[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
sage: E.1.matrix()
[ 0 1 -1 0]
[ 0 1 -1 1]
[-1 2 -2 1]
[-1 1 0 -1]
The result is cached::
sage: E is A.endomorphism_ring()
True
"""
try:
return self.__endomorphism_ring
except AttributeError:
pass
E = homspace.EndomorphismSubring(self)
self.__endomorphism_ring = E
return self.__endomorphism_ring
def _calculate_endomorphism_generators(self):
"""
EXAMPLES::
sage: A = AbelianVariety('43b')
sage: B = A.endomorphism_ring(); B # indirect doctest
Endomorphism ring of Newform abelian subvariety 43b of dimension 2 of J0(43)
sage: [b.matrix() for b in B.gens()]
[
[1 0 0 0] [ 0 1 0 0]
[0 1 0 0] [ 1 -2 0 0]
[0 0 1 0] [ 1 0 -2 -1]
[0 0 0 1], [ 0 1 -1 0]
]
"""
M = self.modular_symbols()
bound = M.sturm_bound()
d = self.dimension()
T1list = self.hecke_operator(1).matrix().list()
EndVecZ = ZZ**(len(T1list))
V = EndVecZ.submodule([T1list])
n = 2
while V.dimension() < d:
W = EndVecZ.submodule([((self.hecke_operator(n).matrix())**i).list()
for i in range(1, d + 1)])
V = V + W
n += 1
if n > bound:
raise ArithmeticError("Error computing endomorphism generators")
return V.saturation().basis() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/abvar/abvar_newform.py | 0.737914 | 0.365513 | abvar_newform.py | pypi |
from copy import copy
from sage.categories.homset import HomsetWithBase
from sage.structure.all import parent
from sage.misc.lazy_attribute import lazy_attribute
from . import morphism
import sage.rings.integer_ring
import sage.rings.all
from sage.rings.ring import Ring
from sage.matrix.matrix_space import MatrixSpace
from sage.matrix.constructor import Matrix, identity_matrix
from sage.structure.element import is_Matrix
ZZ = sage.rings.integer_ring.ZZ
class Homspace(HomsetWithBase):
"""
A space of homomorphisms between two modular abelian varieties.
"""
Element = morphism.Morphism
def __init__(self, domain, codomain, cat):
"""
Create a homspace.
INPUT:
- ``domain, codomain`` - modular abelian varieties
- ``cat`` - category
EXAMPLES::
sage: H = Hom(J0(11), J0(22)); H
Space of homomorphisms from Abelian variety J0(11) of dimension 1 to Abelian variety J0(22) of dimension 2
sage: Hom(J0(11), J0(11))
Endomorphism ring of Abelian variety J0(11) of dimension 1
sage: type(H)
<class 'sage.modular.abvar.homspace.Homspace_with_category'>
sage: H.homset_category()
Category of modular abelian varieties over Rational Field
"""
from .abvar import is_ModularAbelianVariety
if not is_ModularAbelianVariety(domain):
raise TypeError("domain must be a modular abelian variety")
if not is_ModularAbelianVariety(codomain):
raise TypeError("codomain must be a modular abelian variety")
self._gens = None
HomsetWithBase.__init__(self, domain, codomain, category=cat)
def identity(self):
"""
Return the identity endomorphism.
EXAMPLES::
sage: E = End(J0(11))
sage: E.identity()
Abelian variety endomorphism of Abelian variety J0(11) of dimension 1
sage: E.one()
Abelian variety endomorphism of Abelian variety J0(11) of dimension 1
sage: H = Hom(J0(11), J0(22))
sage: H.identity()
Traceback (most recent call last):
...
TypeError: the identity map is only defined for endomorphisms
"""
if self.domain() is not self.codomain():
raise TypeError("the identity map is only defined for endomorphisms")
M = self.matrix_space().one()
return self.element_class(self, M)
@lazy_attribute
def _matrix_space(self):
"""
Return the matrix space of ``self``.
.. WARNING::
During unpickling, the domain and codomain may be unable to
provide the necessary information. This is why this is a lazy
attribute. See :trac:`14793`.
EXAMPLES::
sage: Hom(J0(11), J0(22))._matrix_space
Full MatrixSpace of 2 by 4 dense matrices over Integer Ring
"""
return MatrixSpace(ZZ,2*self.domain().dimension(), 2*self.codomain().dimension())
def _element_constructor_from_element_class(self, *args, **keywords):
"""
Used in the coercion framework. Unfortunately, the default method
would get the order of parent and data different from what is expected
in ``MatrixMorphism.__init__``.
EXAMPLES::
sage: H = Hom(J0(11), J0(22))
sage: phi = H(matrix(ZZ,2,4,[5..12])); phi # indirect doctest
Abelian variety morphism:
From: Abelian variety J0(11) of dimension 1
To: Abelian variety J0(22) of dimension 2
"""
return self.element_class(self, *args, **keywords)
def __call__(self, M, **kwds):
r"""
Create a homomorphism in this space from M. M can be any of the
following:
- a Morphism of abelian varieties
- a matrix of the appropriate size
(i.e. 2\*self.domain().dimension() x
2\*self.codomain().dimension()) whose entries are coercible
into self.base_ring()
- anything that can be coerced into self.matrix_space()
EXAMPLES::
sage: H = Hom(J0(11), J0(22))
sage: phi = H(matrix(ZZ,2,4,[5..12])) ; phi
Abelian variety morphism:
From: Abelian variety J0(11) of dimension 1
To: Abelian variety J0(22) of dimension 2
sage: phi.matrix()
[ 5 6 7 8]
[ 9 10 11 12]
sage: phi.matrix().parent()
Full MatrixSpace of 2 by 4 dense matrices over Integer Ring
::
sage: H = J0(22).Hom(J0(11)*J0(11))
sage: m1 = J0(22).degeneracy_map(11,1).matrix() ; m1
[ 0 1]
[-1 1]
[-1 0]
[ 0 -1]
sage: m2 = J0(22).degeneracy_map(11,2).matrix() ; m2
[ 1 -2]
[ 0 -2]
[ 1 -1]
[ 0 -1]
sage: m = m1.transpose().stack(m2.transpose()).transpose() ; m
[ 0 1 1 -2]
[-1 1 0 -2]
[-1 0 1 -1]
[ 0 -1 0 -1]
sage: phi = H(m) ; phi
Abelian variety morphism:
From: Abelian variety J0(22) of dimension 2
To: Abelian variety J0(11) x J0(11) of dimension 2
sage: phi.matrix()
[ 0 1 1 -2]
[-1 1 0 -2]
[-1 0 1 -1]
[ 0 -1 0 -1]
"""
side = kwds.get("side", "left")
if isinstance(M, morphism.Morphism):
if M.parent() is self:
return M
elif M.domain() == self.domain() and M.codomain() == self.codomain():
M = M.matrix()
else:
raise ValueError("cannot convert %s into %s" % (M, self))
elif is_Matrix(M):
if M.base_ring() != ZZ:
M = M.change_ring(ZZ)
if side == "left":
if M.nrows() != 2*self.domain().dimension() or M.ncols() != 2*self.codomain().dimension():
raise TypeError("matrix has wrong dimension")
else:
if M.ncols() != 2*self.domain().dimension() or M.nrows() != 2*self.codomain().dimension():
raise TypeError("matrix has wrong dimension")
elif self.matrix_space().has_coerce_map_from(parent(M)):
M = self.matrix_space()(M)
else:
raise TypeError("can only coerce in matrices or morphisms")
return self.element_class(self, M, side)
def _coerce_impl(self, x):
"""
Coerce x into self, if possible.
EXAMPLES::
sage: J = J0(37) ; J.Hom(J)._coerce_impl(matrix(ZZ,4,[5..20]))
Abelian variety endomorphism of Abelian variety J0(37) of dimension 2
sage: K = J0(11) * J0(11) ; J.Hom(K)._coerce_impl(matrix(ZZ,4,[5..20]))
Abelian variety morphism:
From: Abelian variety J0(37) of dimension 2
To: Abelian variety J0(11) x J0(11) of dimension 2
"""
if self.matrix_space().has_coerce_map_from(parent(x)):
return self(x)
else:
return HomsetWithBase._coerce_impl(self, x)
def _repr_(self):
"""
String representation of a modular abelian variety homspace.
EXAMPLES::
sage: J = J0(11)
sage: End(J)._repr_()
'Endomorphism ring of Abelian variety J0(11) of dimension 1'
"""
return "Space of homomorphisms from %s to %s"%\
(self.domain(), self.codomain())
def _get_matrix(self, g):
"""
Given an object g, try to return a matrix corresponding to g with
dimensions the same as those of self.matrix_space().
INPUT:
- ``g`` - a matrix or morphism or object with a list
method
OUTPUT: a matrix
EXAMPLES::
sage: E = End(J0(11))
sage: E._get_matrix(matrix(QQ,2,[1,2,3,4]))
[1 2]
[3 4]
sage: E._get_matrix(J0(11).hecke_operator(2))
[-2 0]
[ 0 -2]
::
sage: H = Hom(J0(11) * J0(17), J0(22))
sage: H._get_matrix(tuple([8..23]))
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
[20 21 22 23]
sage: H._get_matrix(tuple([8..23]))
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
[20 21 22 23]
sage: H._get_matrix([8..23])
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
[20 21 22 23]
"""
try:
if g.parent() is self.matrix_space():
return g
except AttributeError:
pass
if isinstance(g, morphism.Morphism):
return g.matrix()
elif hasattr(g, 'list'):
return self.matrix_space()(g.list())
else:
return self.matrix_space()(g)
def free_module(self):
r"""
Return this endomorphism ring as a free submodule of a big
`\ZZ^{4nm}`, where `n` is the dimension of
the domain abelian variety and `m` the dimension of the
codomain.
OUTPUT: free module
EXAMPLES::
sage: E = Hom(J0(11), J0(22))
sage: E.free_module()
Free module of degree 8 and rank 2 over Integer Ring
Echelon basis matrix:
[ 1 0 -3 1 1 1 -1 -1]
[ 0 1 -3 1 1 1 -1 0]
"""
self.calculate_generators()
V = ZZ**(4*self.domain().dimension() * self.codomain().dimension())
return V.submodule([ V(m.matrix().list()) for m in self.gens() ])
def gen(self, i=0):
"""
Return i-th generator of self.
INPUT:
- ``i`` - an integer
OUTPUT: a morphism
EXAMPLES::
sage: E = End(J0(22))
sage: E.gen(0).matrix()
[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
"""
self.calculate_generators()
if i > self.ngens():
raise ValueError("self only has %s generators"%self.ngens())
return self.element_class(self, self._gens[i])
def ngens(self):
"""
Return number of generators of self.
OUTPUT: integer
EXAMPLES::
sage: E = End(J0(22))
sage: E.ngens()
4
"""
self.calculate_generators()
return len(self._gens)
def gens(self):
"""
Return tuple of generators for this endomorphism ring.
EXAMPLES::
sage: E = End(J0(22))
sage: E.gens()
(Abelian variety endomorphism of Abelian variety J0(22) of dimension 2,
Abelian variety endomorphism of Abelian variety J0(22) of dimension 2,
Abelian variety endomorphism of Abelian variety J0(22) of dimension 2,
Abelian variety endomorphism of Abelian variety J0(22) of dimension 2)
"""
try:
return self._gen_morphisms
except AttributeError:
self.calculate_generators()
self._gen_morphisms = tuple([self.gen(i) for i in range(self.ngens())])
return self._gen_morphisms
def matrix_space(self):
"""
Return the underlying matrix space that we view this endomorphism
ring as being embedded into.
EXAMPLES::
sage: E = End(J0(22))
sage: E.matrix_space()
Full MatrixSpace of 4 by 4 dense matrices over Integer Ring
"""
return self._matrix_space
def calculate_generators(self):
"""
If generators haven't already been computed, calculate generators
for this homspace. If they have been computed, do nothing.
EXAMPLES::
sage: E = End(J0(11))
sage: E.calculate_generators()
"""
if self._gens is not None:
return
if (self.domain() == self.codomain()) and (self.domain().dimension() == 1):
self._gens = tuple([ identity_matrix(ZZ,2) ])
return
phi = self.domain()._isogeny_to_product_of_powers()
psi = self.codomain()._isogeny_to_product_of_powers()
H_simple = phi.codomain().Hom(psi.codomain())
im_gens = H_simple._calculate_product_gens()
M = phi.matrix()
Mt = psi.complementary_isogeny().matrix()
R = ZZ**(4*self.domain().dimension()*self.codomain().dimension())
gens = R.submodule([ (M*self._get_matrix(g)*Mt).list()
for g in im_gens ]).saturation().basis()
self._gens = tuple([ self._get_matrix(g) for g in gens ])
def _calculate_product_gens(self):
"""
For internal use.
Calculate generators for self, assuming that self is a product of
simple factors.
EXAMPLES::
sage: E = End(J0(37))
sage: E.gens()
(Abelian variety endomorphism of Abelian variety J0(37) of dimension 2,
Abelian variety endomorphism of Abelian variety J0(37) of dimension 2)
sage: [ x.matrix() for x in E.gens() ]
[
[1 0 0 0] [ 0 1 1 -1]
[0 1 0 0] [ 1 0 1 0]
[0 0 1 0] [ 0 0 -1 1]
[0 0 0 1], [ 0 0 0 1]
]
sage: E._calculate_product_gens()
[
[1 0 0 0] [0 0 0 0]
[0 1 0 0] [0 0 0 0]
[0 0 0 0] [0 0 1 0]
[0 0 0 0], [0 0 0 1]
]
"""
Afactors = self.domain().decomposition(simple=False)
Bfactors = self.codomain().decomposition(simple=False)
if len(Afactors) == 1 and len(Bfactors) == 1:
Asimples = Afactors[0].decomposition()
Bsimples = Bfactors[0].decomposition()
if len(Asimples) == 1 and len(Bsimples) == 1:
# Handle the base case of A, B simple
gens = self._calculate_simple_gens()
else:
# Handle the case of A, B simple powers
gens = []
phi_matrix = Afactors[0]._isogeny_to_product_of_simples().matrix()
psi_t_matrix = Bfactors[0]._isogeny_to_product_of_simples().complementary_isogeny().matrix()
for i in range(len(Asimples)):
for j in range(len(Bsimples)):
hom_gens = Asimples[i].Hom(Bsimples[j]).gens()
for sub_gen in hom_gens:
sub_mat = sub_gen.matrix()
M = copy(self.matrix_space().zero_matrix())
M.set_block(sub_mat.nrows()*i, sub_mat.ncols()*j, sub_mat)
gens.append(phi_matrix * M * psi_t_matrix)
else:
# Handle the case of A, B generic
gens = []
cur_row = 0
for Afactor in Afactors:
cur_row += Afactor.dimension() * 2
cur_col = 0
for Bfactor in Bfactors:
cur_col += Bfactor.dimension() * 2
Asimple = Afactor[0]
Bsimple = Bfactor[0]
if Asimple.newform_label() == Bsimple.newform_label():
for sub_gen in Afactor.Hom(Bfactor).gens():
sub_mat = sub_gen.matrix()
M = copy(self.matrix_space().zero_matrix())
M.set_block(cur_row - sub_mat.nrows(),
cur_col - sub_mat.ncols(),
sub_mat)
gens.append(M)
return gens
def _calculate_simple_gens(self):
"""
Calculate generators for self, where both the domain and codomain
for self are assumed to be simple abelian varieties. The saturation
of the span of these generators in self will be the full space of
homomorphisms from the domain of self to its codomain.
EXAMPLES::
sage: H = Hom(J0(11), J0(22)[0])
sage: H._calculate_simple_gens()
[
[1 0]
[1 1]
]
sage: J = J0(11) * J0(33) ; J.decomposition()
[
Simple abelian subvariety 11a(1,11) of dimension 1 of J0(11) x J0(33),
Simple abelian subvariety 11a(1,33) of dimension 1 of J0(11) x J0(33),
Simple abelian subvariety 11a(3,33) of dimension 1 of J0(11) x J0(33),
Simple abelian subvariety 33a(1,33) of dimension 1 of J0(11) x J0(33)
]
sage: J[0].Hom(J[1])._calculate_simple_gens()
[
[ 0 -1]
[ 1 -1]
]
sage: J[0].Hom(J[2])._calculate_simple_gens()
[
[-1 0]
[-1 -1]
]
sage: J[0].Hom(J[0])._calculate_simple_gens()
[
[1 0]
[0 1]
]
sage: J[1].Hom(J[2])._calculate_simple_gens()
[
[ 0 -4]
[ 4 0]
]
::
sage: J = J0(23) ; J.decomposition()
[
Simple abelian variety J0(23) of dimension 2
]
sage: J[0].Hom(J[0])._calculate_simple_gens()
[
[1 0 0 0] [ 0 1 -1 0]
[0 1 0 0] [ 0 1 -1 1]
[0 0 1 0] [-1 2 -2 1]
[0 0 0 1], [-1 1 0 -1]
]
sage: J.hecke_operator(2).matrix()
[ 0 1 -1 0]
[ 0 1 -1 1]
[-1 2 -2 1]
[-1 1 0 -1]
::
sage: H = Hom(J0(11), J0(22)[0])
sage: H._calculate_simple_gens()
[
[1 0]
[1 1]
]
"""
A = self.domain()
B = self.codomain()
if A.newform_label() != B.newform_label():
return []
f = A._isogeny_to_newform_abelian_variety()
g = B._isogeny_to_newform_abelian_variety().complementary_isogeny()
Af = f.codomain()
ls = Af._calculate_endomorphism_generators()
Mf = f.matrix()
Mg = g.matrix()
return [ Mf * self._get_matrix(e) * Mg for e in ls ]
# NOTE/WARNING/TODO: Below in the __init__, etc. we do *not* check
# that the input gens are give something that spans a sub*ring*, as apposed
# to just a subgroup.
class EndomorphismSubring(Homspace, Ring):
def __init__(self, A, gens=None, category=None):
"""
A subring of the endomorphism ring.
INPUT:
- ``A`` - an abelian variety
- ``gens`` - (default: None); optional; if given
should be a tuple of the generators as matrices
EXAMPLES::
sage: J0(23).endomorphism_ring()
Endomorphism ring of Abelian variety J0(23) of dimension 2
sage: sage.modular.abvar.homspace.EndomorphismSubring(J0(25))
Endomorphism ring of Abelian variety J0(25) of dimension 0
sage: E = J0(11).endomorphism_ring()
sage: type(E)
<class 'sage.modular.abvar.homspace.EndomorphismSubring_with_category'>
sage: E.homset_category()
Category of modular abelian varieties over Rational Field
sage: E.category()
Category of endsets of modular abelian varieties over Rational Field
sage: E in Rings()
True
sage: TestSuite(E).run(skip=["_test_prod"])
TESTS:
The following tests against a problem on 32 bit machines that
occurred while working on :trac:`9944`::
sage: sage.modular.abvar.homspace.EndomorphismSubring(J1(12345))
Endomorphism ring of Abelian variety J1(12345) of dimension 5405473
:trac:`16275` removed the custom ``__reduce__`` method, since
:meth:`Homset.__reduce__` already implements appropriate
unpickling by construction::
sage: E.__reduce__.__module__
'sage.categories.homset'
sage: E.__reduce__()
(<function Hom at ...>,
(Abelian variety J0(11) of dimension 1,
Abelian variety J0(11) of dimension 1,
Category of modular abelian varieties over Rational Field,
False))
"""
self._J = A.ambient_variety()
self._A = A
# Initialise self with the correct category.
# We need to initialise it as a ring first
if category is None:
homset_cat = A.category()
else:
homset_cat = category
# Remark: Ring.__init__ will automatically form the join
# of the category of rings and of homset_cat
Ring.__init__(self, A.base_ring(), category=homset_cat.Endsets())
Homspace.__init__(self, A, A, cat=homset_cat)
if gens is None:
self._gens = None
else:
self._gens = tuple([ self._get_matrix(g) for g in gens ])
self._is_full_ring = gens is None
def _repr_(self):
"""
Return the string representation of self.
EXAMPLES::
sage: J0(31).endomorphism_ring()._repr_()
'Endomorphism ring of Abelian variety J0(31) of dimension 2'
sage: J0(31).endomorphism_ring().image_of_hecke_algebra()._repr_()
'Subring of endomorphism ring of Abelian variety J0(31) of dimension 2'
"""
if self._is_full_ring:
return "Endomorphism ring of %s" % self._A
else:
return "Subring of endomorphism ring of %s" % self._A
def abelian_variety(self):
"""
Return the abelian variety that this endomorphism ring is attached
to.
EXAMPLES::
sage: J0(11).endomorphism_ring().abelian_variety()
Abelian variety J0(11) of dimension 1
"""
return self._A
def index_in(self, other, check=True):
"""
Return the index of self in other.
INPUT:
- ``other`` - another endomorphism subring of the
same abelian variety
- ``check`` - bool (default: True); whether to do some
type and other consistency checks
EXAMPLES::
sage: R = J0(33).endomorphism_ring()
sage: R.index_in(R)
1
sage: J = J0(37) ; E = J.endomorphism_ring() ; T = E.image_of_hecke_algebra()
sage: T.index_in(E)
1
sage: J = J0(22) ; E = J.endomorphism_ring() ; T = E.image_of_hecke_algebra()
sage: T.index_in(E)
+Infinity
"""
if check:
if not isinstance(other, EndomorphismSubring):
raise ValueError("other must be a subring of an endomorphism ring of an abelian variety.")
if not (self.abelian_variety() == other.abelian_variety()):
raise ValueError("self and other must be endomorphisms of the same abelian variety")
M = self.free_module()
N = other.free_module()
if M.rank() < N.rank():
return sage.rings.all.Infinity
return M.index_in(N)
def index_in_saturation(self):
"""
Given a Hecke algebra T, compute its index in its saturation.
EXAMPLES::
sage: End(J0(23)).image_of_hecke_algebra().index_in_saturation()
1
sage: End(J0(44)).image_of_hecke_algebra().index_in_saturation()
2
"""
A = self.abelian_variety()
d = A.dimension()
M = ZZ**(4*d**2)
gens = [ x.matrix().list() for x in self.gens() ]
R = M.submodule(gens)
return R.index_in_saturation()
def discriminant(self):
"""
Return the discriminant of this ring, which is the discriminant of
the trace pairing.
.. note::
One knows that for modular abelian varieties, the
endomorphism ring should be isomorphic to an order in a
number field. However, the discriminant returned by this
function will be `2^n` ( `n =`
self.dimension()) times the discriminant of that order,
since the elements are represented as 2d x 2d
matrices. Notice, for example, that the case of a one
dimensional abelian variety, whose endomorphism ring must
be ZZ, has discriminant 2, as in the example below.
EXAMPLES::
sage: J0(33).endomorphism_ring().discriminant()
-64800
sage: J0(46).endomorphism_ring().discriminant() # long time (6s on sage.math, 2011)
24200000000
sage: J0(11).endomorphism_ring().discriminant()
2
"""
g = self.gens()
M = Matrix(ZZ,len(g), [ (g[i]*g[j]).trace()
for i in range(len(g)) for j in range(len(g)) ])
return M.determinant()
def image_of_hecke_algebra(self, check_every=1):
"""
Compute the image of the Hecke algebra inside this endomorphism
subring.
We simply calculate Hecke operators up to the Sturm bound, and look
at the submodule spanned by them. While computing, we can check to
see if the submodule spanned so far is saturated and of maximal
dimension, in which case we may be done. The optional argument
check_every determines how many Hecke operators we add in before
checking to see if this condition is met.
INPUT:
- ``check_every`` -- integer (default: 1) If this integer is positive,
this integer determines how many Hecke operators we add in before
checking to see if the submodule spanned so far is maximal and
saturated.
OUTPUT:
- The image of the Hecke algebra as an subring of ``self``.
EXAMPLES::
sage: E = J0(33).endomorphism_ring()
sage: E.image_of_hecke_algebra()
Subring of endomorphism ring of Abelian variety J0(33) of dimension 3
sage: E.image_of_hecke_algebra().gens()
(Abelian variety endomorphism of Abelian variety J0(33) of dimension 3,
Abelian variety endomorphism of Abelian variety J0(33) of dimension 3,
Abelian variety endomorphism of Abelian variety J0(33) of dimension 3)
sage: [ x.matrix() for x in E.image_of_hecke_algebra().gens() ]
[
[1 0 0 0 0 0] [ 0 2 0 -1 1 -1] [ 0 0 1 -1 1 -1]
[0 1 0 0 0 0] [-1 -2 2 -1 2 -1] [ 0 -1 1 0 1 -1]
[0 0 1 0 0 0] [ 0 0 1 -1 3 -1] [ 0 0 1 0 2 -2]
[0 0 0 1 0 0] [-2 2 0 1 1 -1] [-2 0 1 1 1 -1]
[0 0 0 0 1 0] [-1 1 0 2 0 -3] [-1 0 1 1 0 -1]
[0 0 0 0 0 1], [-1 1 -1 1 1 -2], [-1 0 0 1 0 -1]
]
sage: J0(33).hecke_operator(2).matrix()
[-1 0 1 -1 1 -1]
[ 0 -2 1 0 1 -1]
[ 0 0 0 0 2 -2]
[-2 0 1 0 1 -1]
[-1 0 1 1 -1 -1]
[-1 0 0 1 0 -2]
"""
try:
return self.__hecke_algebra_image
except AttributeError:
pass
A = self.abelian_variety()
if not A.is_hecke_stable():
raise ValueError("ambient variety is not Hecke stable")
M = A.modular_symbols()
d = A.dimension()
EndVecZ = ZZ**(4*d**2)
if d == 1:
self.__hecke_algebra_image = EndomorphismSubring(A, [[1,0,0,1]])
return self.__hecke_algebra_image
V = EndVecZ.submodule([A.hecke_operator(1).matrix().list()])
for n in range(2,M.sturm_bound()+1):
if (check_every > 0 and
n % check_every == 0 and
V.dimension() == d and
V.index_in_saturation() == 1):
break
V += EndVecZ.submodule([ A.hecke_operator(n).matrix().list() ])
self.__hecke_algebra_image = EndomorphismSubring(A, V.basis())
return self.__hecke_algebra_image | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/abvar/homspace.py | 0.759315 | 0.46223 | homspace.py | pypi |
from sage.structure.element import ModuleElement
from sage.structure.richcmp import richcmp, rich_to_bool
class TorsionPoint(ModuleElement):
r"""
An element of a finite subgroup of a modular abelian variety.
INPUT:
- ``parent`` -- a finite subgroup of a modular abelian variety
- ``element`` -- a `\QQ`-vector space element that represents
this element in terms of the ambient rational homology
- ``check`` -- bool (default: ``True``): whether to check that
element is in the appropriate vector space
EXAMPLES:
The following calls the :class:`TorsionPoint` constructor implicitly::
sage: J = J0(11)
sage: G = J.finite_subgroup([[1/3,0], [0,1/5]]); G
Finite subgroup with invariants [15] over QQbar of Abelian variety J0(11) of dimension 1
sage: type(G.0)
<class 'sage.modular.abvar.finite_subgroup.FiniteSubgroup_lattice_with_category.element_class'>
"""
def __init__(self, parent, element, check=True):
"""
Initialize ``self``.
EXAMPLES::
sage: J = J0(11)
sage: G = J.finite_subgroup([[1/2,0], [0,1/2]])
sage: TestSuite(G).run() # long time
"""
ModuleElement.__init__(self, parent)
if check:
if element not in parent.abelian_variety().vector_space():
raise TypeError("element must be a vector in the abelian variety's rational homology (embedded in the ambient Jacobian product)")
if element.denominator() == 1:
element = element.parent().zero_vector()
self.__element = element
def element(self):
r"""
Return a vector over `\QQ` defining ``self``.
OUTPUT:
- A vector in the rational homology of the ambient modular
Jacobian variety.
EXAMPLES:
We create some elements of `J_0(11)`::
sage: J = J0(11)
sage: G = J.finite_subgroup([[1/3,0], [0,1/5]]); G
Finite subgroup with invariants [15] over QQbar of Abelian variety J0(11) of dimension 1
sage: G.0.element()
(1/3, 0)
The underlying element is a vector over the rational numbers::
sage: v = (G.0-G.1).element(); v
(1/3, -1/5)
sage: type(v)
<class 'sage.modules.vector_rational_dense.Vector_rational_dense'>
"""
return self.__element
def _repr_(self):
r"""
Return a string representation of ``self``.
.. note::
Since they are represented as equivalences classes of
rational homology modulo integral homology, we represent
an element corresponding to `v` in the rational homology
by ``[v]``.
EXAMPLES::
sage: J = J0(11)
sage: G = J.finite_subgroup([[1/3,0], [0,1/5]]); G
Finite subgroup with invariants [15] over QQbar of Abelian variety J0(11) of dimension 1
sage: G.0._repr_()
'[(1/3, 0)]'
"""
return '[%s]' % self.__element
def _add_(self, other):
"""
Add two finite subgroup elements with the same parent. This is
called implicitly by +.
EXAMPLES::
sage: J = J0(11); G = J.finite_subgroup([[1/3,0], [0,1/5]])
sage: G.0._add_(G.1)
[(1/3, 1/5)]
sage: G.0 + G.1
[(1/3, 1/5)]
"""
P = self.parent()
return P.element_class(P, self.__element + other.__element, check=False)
def _sub_(self, other):
"""
Subtract two finite subgroup elements with the same parent. This is
called implicitly by +.
EXAMPLES::
sage: J = J0(11); G = J.finite_subgroup([[1/3,0], [0,1/5]])
sage: G.0._sub_(G.1)
[(1/3, -1/5)]
sage: G.0 - G.1
[(1/3, -1/5)]
"""
P = self.parent()
return P.element_class(P, self.__element - other.__element, check=False)
def _neg_(self):
"""
Negate a finite subgroup element.
EXAMPLES::
sage: J = J0(11); G = J.finite_subgroup([[1/3,0], [0,1/5]])
sage: G.0._neg_()
[(-1/3, 0)]
"""
P = self.parent()
return P.element_class(P, -self.__element, check=False)
def _rmul_(self, left):
"""
Left multiply a finite subgroup element by an integer.
EXAMPLES::
sage: J = J0(11); G = J.finite_subgroup([[1/3,0], [0,1/5]])
sage: G.0._rmul_(2)
[(2/3, 0)]
sage: 2*G.0
[(2/3, 0)]
"""
P = self.parent()
return P.element_class(P, left * self.__element, check=False)
def _lmul_(self, right):
"""
Right multiply a finite subgroup element by an integer.
EXAMPLES::
sage: J = J0(11); G = J.finite_subgroup([[1/3,0], [0,1/5]])
sage: G.0._lmul_(2)
[(2/3, 0)]
sage: G.0 * 2
[(2/3, 0)]
"""
P = self.parent()
return P.element_class(P, self.__element * right, check=False)
def _richcmp_(self, right, op):
"""
Compare ``self`` and ``right``.
INPUT:
- ``self, right`` -- elements of the same finite abelian
variety subgroup.
- ``op`` -- comparison operator (see :mod:`sage.structure.richcmp`)
OUTPUT: boolean
EXAMPLES::
sage: J = J0(11); G = J.finite_subgroup([[1/3,0], [0,1/5]])
sage: G.0 > G.1
True
sage: G.0 == G.0
True
sage: 3*G.0 == 0
True
sage: 3*G.0 == 5*G.1
True
We make sure things that should not be equal are not::
sage: H = J0(14).finite_subgroup([[1/3,0]])
sage: G.0 == H.0
False
sage: G.0
[(1/3, 0)]
sage: H.0
[(1/3, 0)]
"""
A = self.parent().abelian_variety()
from sage.rings.rational_field import QQ
if self.__element.change_ring(QQ) - right.__element.change_ring(QQ) in A.lattice():
return rich_to_bool(op, 0)
return richcmp(self.__element, right.__element, op)
def additive_order(self):
"""
Return the additive order of ``self``.
EXAMPLES::
sage: J = J0(11); G = J.finite_subgroup([[1/3,0], [0,1/5]])
sage: G.0.additive_order()
3
sage: G.1.additive_order()
5
sage: (G.0 + G.1).additive_order()
15
sage: (3*G.0).additive_order()
1
"""
return self._relative_element().denominator()
def _relative_element(self):
"""
Return coordinates of ``self`` on a basis for the integral
homology of the containing abelian variety.
OUTPUT: vector
EXAMPLES::
sage: A = J0(43)[1]; A
Simple abelian subvariety 43b(1,43) of dimension 2 of J0(43)
sage: C = A.cuspidal_subgroup(); C
Finite subgroup with invariants [7] over QQ of Simple abelian subvariety 43b(1,43) of dimension 2 of J0(43)
sage: x = C.0; x
[(0, 1/7, 0, 6/7, 0, 5/7)]
sage: x._relative_element()
(0, 1/7, 6/7, 5/7)
"""
# check=False prevents testing that the element is really in
# the lattice, not just in the corresponding QQ-vector space.
return self.parent().abelian_variety().lattice().coordinate_vector(self.__element, check=False) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/abvar/torsion_point.py | 0.943138 | 0.693753 | torsion_point.py | pypi |
import weakref
from sage.rings.integer import Integer
from sage.modular.arithgroup.all import is_CongruenceSubgroup, Gamma0
from sage.modular.modsym.space import is_ModularSymbolsSpace
from .abvar_newform import ModularAbelianVariety_newform
import sage.modular.modform.element
from . import abvar
_cache = {}
def _get(key):
"""
Returns the cached abelian variety with given key. This is used
internally by the abelian varieties constructor.
INPUT:
- ``key`` - hashable
EXAMPLES::
sage: sage.modular.abvar.constructor._saved('a', J0(37))
Abelian variety J0(37) of dimension 2
sage: sage.modular.abvar.constructor._get('a')
Abelian variety J0(37) of dimension 2
sage: sage.modular.abvar.constructor._get('b')
Traceback (most recent call last):
...
ValueError: element not in cache
"""
if key in _cache:
z = _cache[key]()
if z is not None:
return z
raise ValueError("element not in cache")
def _saved(key, J):
"""
Returns the cached abelian variety with given key. This is used
internally by the abelian varieties constructor.
INPUT:
- ``key`` - hashable
- ``J`` - modular abelian variety
OUTPUT:
- ``J`` - returns the modabvar, to make code that uses
this simpler
EXAMPLES::
sage: sage.modular.abvar.constructor._saved('37', J0(37))
Abelian variety J0(37) of dimension 2
"""
_cache[key] = weakref.ref(J)
return J
def J0(N):
"""
Return the Jacobian `J_0(N)` of the modular curve
`X_0(N)`.
EXAMPLES::
sage: J0(389)
Abelian variety J0(389) of dimension 32
The result is cached::
sage: J0(33) is J0(33)
True
"""
key = 'J0(%s)'%N
try:
return _get(key)
except ValueError:
from sage.modular.arithgroup.all import Gamma0
J = Gamma0(N).modular_abelian_variety()
return _saved(key, J)
def J1(N):
"""
Return the Jacobian `J_1(N)` of the modular curve
`X_1(N)`.
EXAMPLES::
sage: J1(389)
Abelian variety J1(389) of dimension 6112
"""
key = 'J1(%s)'%N
try:
return _get(key)
except ValueError:
from sage.modular.arithgroup.all import Gamma1
return _saved(key, Gamma1(N).modular_abelian_variety())
def JH(N, H):
"""
Return the Jacobian `J_H(N)` of the modular curve
`X_H(N)`.
EXAMPLES::
sage: JH(389,[16])
Abelian variety JH(389,[16]) of dimension 64
"""
key = 'JH(%s,%s)'%(N,H)
try:
return _get(key)
except ValueError:
from sage.modular.arithgroup.all import GammaH
return _saved(key, GammaH(N, H).modular_abelian_variety())
def AbelianVariety(X):
"""
Create the abelian variety corresponding to the given defining
data.
INPUT:
- ``X`` - an integer, string, newform, modsym space,
congruence subgroup or tuple of congruence subgroups
OUTPUT: a modular abelian variety
EXAMPLES::
sage: AbelianVariety(Gamma0(37))
Abelian variety J0(37) of dimension 2
sage: AbelianVariety('37a')
Newform abelian subvariety 37a of dimension 1 of J0(37)
sage: AbelianVariety(Newform('37a'))
Newform abelian subvariety 37a of dimension 1 of J0(37)
sage: AbelianVariety(ModularSymbols(37).cuspidal_submodule())
Abelian variety J0(37) of dimension 2
sage: AbelianVariety((Gamma0(37), Gamma0(11)))
Abelian variety J0(37) x J0(11) of dimension 3
sage: AbelianVariety(37)
Abelian variety J0(37) of dimension 2
sage: AbelianVariety([1,2,3])
Traceback (most recent call last):
...
TypeError: X must be an integer, string, newform, modsym space, congruence subgroup or tuple of congruence subgroups
"""
if isinstance(X, (int, Integer)):
X = Gamma0(X)
if is_CongruenceSubgroup(X):
X = X.modular_symbols().cuspidal_submodule()
elif isinstance(X, str):
from sage.modular.modform.constructor import Newform
f = Newform(X, names='a')
return ModularAbelianVariety_newform(f, internal_name=True)
elif isinstance(X, sage.modular.modform.element.Newform):
return ModularAbelianVariety_newform(X)
if is_ModularSymbolsSpace(X):
return abvar.ModularAbelianVariety_modsym(X)
if isinstance(X, (tuple,list)) and all(is_CongruenceSubgroup(G) for G in X):
return abvar.ModularAbelianVariety(X)
raise TypeError("X must be an integer, string, newform, modsym space, congruence subgroup or tuple of congruence subgroups") | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/modular/abvar/constructor.py | 0.712132 | 0.531392 | constructor.py | pypi |
r"""
Universal cyclotomic field
The universal cyclotomic field is the smallest subfield of the complex field
containing all roots of unity. It is also the maximal Galois Abelian extension
of the rational numbers.
The implementation simply wraps GAP Cyclotomic. As mentioned in their
documentation: arithmetical operations are quite expensive, so the use of
internally represented cyclotomics is not recommended for doing arithmetic over
number fields, such as calculations with matrices of cyclotomics.
.. NOTE::
There used to be a native Sage version of the universal cyclotomic field
written by Christian Stump (see :trac:`8327`). It was slower on most
operations and it was decided to use a version based on GAP instead (see
:trac:`18152`). One main difference in the design choices is that GAP stores
dense vectors whereas the native ones used Python dictionaries (storing only
nonzero coefficients). Most operations are faster with GAP except some
operation on very sparse elements. All details can be found in
:trac:`18152`.
REFERENCES:
- [Bre1997]
EXAMPLES::
sage: UCF = UniversalCyclotomicField(); UCF
Universal Cyclotomic Field
To generate cyclotomic elements::
sage: UCF.gen(5)
E(5)
sage: UCF.gen(5,2)
E(5)^2
sage: E = UCF.gen
Equality and inequality checks::
sage: E(6,2) == E(6)^2 == E(3)
True
sage: E(6)^2 != E(3)
False
Addition and multiplication::
sage: E(2) * E(3)
-E(3)
sage: f = E(2) + E(3); f
2*E(3) + E(3)^2
Inverses::
sage: f^-1
1/3*E(3) + 2/3*E(3)^2
sage: f.inverse()
1/3*E(3) + 2/3*E(3)^2
sage: f * f.inverse()
1
Conjugation and Galois conjugates::
sage: f.conjugate()
E(3) + 2*E(3)^2
sage: f.galois_conjugates()
[2*E(3) + E(3)^2, E(3) + 2*E(3)^2]
sage: f.norm_of_galois_extension()
3
One can create matrices and polynomials::
sage: m = matrix(2,[E(3),1,1,E(4)]); m
[E(3) 1]
[ 1 E(4)]
sage: m.parent()
Full MatrixSpace of 2 by 2 dense matrices over Universal Cyclotomic Field
sage: m**2
[ -E(3) E(12)^4 - E(12)^7 - E(12)^11]
[E(12)^4 - E(12)^7 - E(12)^11 0]
sage: m.charpoly()
x^2 + (-E(12)^4 + E(12)^7 + E(12)^11)*x + E(12)^4 + E(12)^7 + E(12)^8
sage: m.echelon_form()
[1 0]
[0 1]
sage: m.pivots()
(0, 1)
sage: m.rank()
2
sage: R.<x> = PolynomialRing(UniversalCyclotomicField(), 'x')
sage: E(3) * x - 1
E(3)*x - 1
TESTS::
sage: UCF.one()
1
sage: UCF.zero()
0
sage: UCF.one().is_one()
True
sage: UCF.one().is_zero()
False
sage: UCF.zero().is_zero()
True
Check that :trac:`14240` is fixed::
sage: K.<rho> = CyclotomicField(245)
sage: h = K.random_element()
sage: h_rho = rho.coordinates_in_terms_of_powers()(h)
sage: h_ucf = sum( c * E(245, i) for (i, c) in enumerate(h_rho) )
sage: h_ucf**2 # random
-169539876343/589714020*E(245) + 27815735177/20058300*E(245)^2 + ... + + 7828432097501/842448600*E(245)^244
Check that :trac:`16130` is fixed::
sage: mat = matrix(UCF, 2, [-4, 2*E(7)^6, -5*E(13)^3 + 5*E(13)^8 - 4*E(13)^9, 0])
sage: mat._echelon_classical()
[1 0]
[0 1]
Check that :trac:`16631` is fixed::
sage: UCF.one() / 2
1/2
sage: UCF.one() / 2r
1/2
Check that :trac:`17117` is fixed::
sage: e3 = UCF.gen(3)
sage: N(e3)
-0.500000000000000 + 0.866025403784439*I
sage: real(e3)
-1/2
sage: imag(e3)
-1/2*E(12)^7 + 1/2*E(12)^11
Check that :trac:`25686` is fixed::
sage: UCF = UniversalCyclotomicField()
sage: UCF.is_finite()
False
AUTHORS:
- Christian Stump (2013): initial Sage version (see :trac:`8327`)
- Vincent Delecroix (2015): complete rewriting using libgap (see :trac:`18152`)
- Sebastian Oehms (2018): deleting the method is_finite since it returned the wrong result (see :trac:`25686`)
- Sebastian Oehms (2019): add :meth:`_factor_univariate_polynomial` (see :trac:`28631`)
"""
from sage.misc.cachefunc import cached_method
from sage.structure.richcmp import rich_to_bool
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.element import FieldElement, parent
from sage.structure.coerce import py_scalar_to_element
from sage.categories.morphism import Morphism
from sage.rings.ring import Field
from sage.rings.integer import Integer
from sage.rings.rational import Rational
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.infinity import Infinity
from sage.rings.qqbar import AA, QQbar
libgap = GapElement_Integer = GapElement_Rational = GapElement_Cyclotomic = None
gap = gap3 = None
def late_import():
r"""
This function avoids importing libgap on startup. It is called once through
the constructor of :class:`UniversalCyclotomicField`.
EXAMPLES::
sage: import sage.rings.universal_cyclotomic_field as ucf
sage: _ = UniversalCyclotomicField() # indirect doctest
sage: ucf.libgap is None # indirect doctest
False
"""
global gap, gap3, libgap
global GapElement_Integer, GapElement_Rational, GapElement_Cyclotomic
from sage.libs.gap.libgap import libgap
from sage.libs.gap.element import (GapElement_Integer,
GapElement_Rational,
GapElement_Cyclotomic)
from sage.interfaces import (gap, gap3)
def UCF_sqrt_int(N, UCF):
r"""
Return the square root of the integer ``N``.
EXAMPLES::
sage: from sage.rings.universal_cyclotomic_field import UCF_sqrt_int
sage: UCF = UniversalCyclotomicField()
sage: UCF_sqrt_int(0, UCF)
0
sage: UCF_sqrt_int(1, UCF)
1
sage: UCF_sqrt_int(-1, UCF)
E(4)
sage: UCF_sqrt_int(2, UCF)
E(8) - E(8)^3
sage: UCF_sqrt_int(-2, UCF)
E(8) + E(8)^3
TESTS::
sage: from sage.rings.universal_cyclotomic_field import UCF_sqrt_int
sage: all(UCF_sqrt_int(ZZ(n), UCF)**2 == n for n in range(-10, 10))
True
"""
if not N:
return UCF.zero()
res = UCF.one() if N > 0 else UCF.zeta(4)
for p, e in N.factor():
if p == 2:
res *= (UCF.zeta(8) + UCF.zeta(8, 7))**e
else:
res *= UCF.sum(UCF.zeta(p, n**2) for n in range(p))**e
if p % 4 == 3:
res *= (UCF.zeta(4))**e
return res
class UCFtoQQbar(Morphism):
r"""
Conversion to ``QQbar``.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: QQbar(UCF.gen(3))
-0.500000000000000? + 0.866025403784439?*I
sage: CC(UCF.gen(7,2) + UCF.gen(7,6))
0.400968867902419 + 0.193096429713793*I
sage: complex(E(7)+E(7,2))
(0.40096886790241915+1.7567593946498534j)
sage: complex(UCF.one()/2)
(0.5+0j)
"""
def __init__(self, UCF):
r"""
INPUT:
- ``UCF`` -- a universal cyclotomic field
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: UCF.coerce_embedding()
Generic morphism:
From: Universal Cyclotomic Field
To: Algebraic Field
"""
Morphism.__init__(self, UCF, QQbar)
def _call_(self, x):
r"""
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: UCFtoQQbar = UCF.coerce_embedding()
sage: UCFtoQQbar(UCF.gen(3)) # indirect doctest
-0.500000000000000? + 0.866025403784439?*I
Test that the bug reported in :trac:`19912` has been fixed::
sage: UCFtoQQbar(UCF.gen(4)+1)
I + 1
"""
obj = x._obj
QQbar = self.codomain()
if obj.IsRat():
return QQbar(obj.sage())
k = obj.Conductor().sage()
coeffs = obj.CoeffsCyc(k).sage()
zeta = QQbar.zeta(k)
return QQbar(sum(coeffs[a] * zeta**a for a in range(k)))
class UniversalCyclotomicFieldElement(FieldElement):
def __init__(self, parent, obj):
r"""
INPUT:
- ``parent`` -- a universal cyclotomic field
- ``obj`` -- a libgap element (either an integer, a rational or a
cyclotomic)
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: a = UCF.an_element()
sage: TestSuite(a).run()
"""
self._obj = obj
FieldElement.__init__(self, parent)
def __bool__(self):
r"""
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: list(map(bool, [UCF.zero(), UCF.one(), UCF.gen(3), UCF.gen(5) + UCF.gen(5,3)]))
[False, True, True, True]
"""
return bool(self._obj)
def __reduce__(self):
r"""
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: a = UCF.zero()
sage: loads(dumps(a))
0
sage: parent(_)
Universal Cyclotomic Field
sage: b = UCF.gen(5,1) - 3*UCF.gen(5,4)
sage: c = loads(dumps(b))
sage: c
E(5) - 3*E(5)^4
sage: c == b
True
sage: parent(c)
Universal Cyclotomic Field
"""
return self.parent(), (str(self),)
def __eq__(self, other):
r"""
Equality test.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF.one() == 1
True
sage: 1 == UCF.one()
True
sage: UCF(2/3) == 2/3
True
sage: 2/3 == UCF(2/3)
True
sage: UCF.gen(3) == UCF.gen(5)
False
sage: UCF.gen(5) + UCF.gen(3) == UCF.gen(3) + UCF.gen(5)
True
sage: UCF.zero() == None
False
sage: QQbar.zeta(5) == UCF.gen(5)
True
sage: UCF.gen(5) == QQbar.zeta(5)
True
sage: QQbar.zeta(5) == UCF.gen(5,2)
False
sage: UCF.gen(5,2) == QQbar.zeta(5)
False
"""
if parent(self) is not parent(other):
from sage.structure.element import coercion_model as cm
try:
self, other = cm.canonical_coercion(self, other)
except TypeError:
return False
return self == other
return self._obj == other._obj
def __ne__(self, other):
r"""
Difference test.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF.one() != 1
False
sage: 1 != UCF.one()
False
sage: UCF(2/3) != 3/2
True
sage: 3/2 != UCF(2/3)
True
sage: UCF.gen(3) != UCF.gen(5)
True
sage: UCF.gen(3) + UCF.gen(5) != UCF.gen(5) + UCF.gen(3)
False
sage: UCF.gen(7) != QQbar.zeta(7)
False
sage: UCF.gen(7,2) != QQbar.zeta(7)
True
"""
return not self == other
def real(self):
r"""
Return the real part of this element.
EXAMPLES::
sage: E(3).real()
-1/2
sage: E(5).real()
1/2*E(5) + 1/2*E(5)^4
sage: a = E(5) - 2*E(3)
sage: AA(a.real()) == QQbar(a).real()
True
"""
P = self.parent()
return P.element_class(P, self._obj.RealPart())
real_part = real
def imag(self):
r"""
Return the imaginary part of this element.
EXAMPLES::
sage: E(3).imag()
-1/2*E(12)^7 + 1/2*E(12)^11
sage: E(5).imag()
1/2*E(20) - 1/2*E(20)^9
sage: a = E(5) - 2*E(3)
sage: AA(a.imag()) == QQbar(a).imag()
True
"""
P = self.parent()
return P.element_class(P, self._obj.ImaginaryPart())
imag_part = imag
def is_real(self):
r"""
Test whether this element is real.
EXAMPLES::
sage: E(3).is_real()
False
sage: (E(3) + E(3,2)).is_real()
True
sage: a = E(3) - 2*E(7)
sage: a.real_part().is_real()
True
sage: a.imag_part().is_real()
True
"""
return self._obj.RealPart() == self._obj
def is_integral(self):
"""
Return whether ``self`` is an algebraic integer.
This just wraps ``IsIntegralCyclotomic`` from GAP.
.. SEEALSO:: :meth:`denominator`
EXAMPLES::
sage: E(6).is_integral()
True
sage: (E(4)/2).is_integral()
False
"""
return self._obj.IsIntegralCyclotomic().sage()
def conductor(self):
r"""
Return the conductor of ``self``.
EXAMPLES::
sage: E(3).conductor()
3
sage: (E(5) + E(3)).conductor()
15
"""
return ZZ(self._obj.Conductor())
def _symbolic_(self, R):
r"""
TESTS::
sage: SR(E(7))
e^(2/7*I*pi)
sage: SR(E(5) + 2*E(5,2) + 3*E(5,3))
-sqrt(5) + 1/4*I*sqrt(2*sqrt(5) + 10) - 1/4*I*sqrt(-2*sqrt(5) + 10) - 3/2
Test that the bug reported in :trac:`19912` has been fixed::
sage: SR(1+E(4))
I + 1
"""
from sage.symbolic.constants import pi, I
k = ZZ(self._obj.Conductor())
coeffs = self._obj.CoeffsCyc(k).sage()
s = R.zero()
for a in range(k):
if coeffs[a]:
s += coeffs[a] * (2 * a * I * pi / k).exp()
return s
def to_cyclotomic_field(self, R=None):
r"""
Return this element as an element of a cyclotomic field.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF.gen(3).to_cyclotomic_field()
zeta3
sage: UCF.gen(3,2).to_cyclotomic_field()
-zeta3 - 1
sage: CF = CyclotomicField(5)
sage: CF(E(5)) # indirect doctest
zeta5
sage: CF = CyclotomicField(7)
sage: CF(E(5)) # indirect doctest
Traceback (most recent call last):
...
TypeError: Cannot coerce zeta5 into Cyclotomic Field of order 7 and
degree 6
sage: CF = CyclotomicField(10)
sage: CF(E(5)) # indirect doctest
zeta10^2
Matrices are correctly dealt with::
sage: M = Matrix(UCF,2,[E(3),E(4),E(5),E(6)]); M
[ E(3) E(4)]
[ E(5) -E(3)^2]
sage: Matrix(CyclotomicField(60),M) # indirect doctest
[zeta60^10 - 1 zeta60^15]
[ zeta60^12 zeta60^10]
Using a non-standard embedding::
sage: CF = CyclotomicField(5,embedding=CC(exp(4*pi*i/5)))
sage: x = E(5)
sage: CC(x)
0.309016994374947 + 0.951056516295154*I
sage: CC(CF(x))
0.309016994374947 + 0.951056516295154*I
Test that the bug reported in :trac:`19912` has been fixed::
sage: a = 1+E(4); a
1 + E(4)
sage: a.to_cyclotomic_field()
zeta4 + 1
"""
from sage.rings.number_field.number_field import CyclotomicField
k = ZZ(self._obj.Conductor())
Rcan = CyclotomicField(k)
if R is None:
R = Rcan
obj = self._obj
if obj.IsRat():
return R(obj.sage())
zeta = Rcan.gen()
coeffs = obj.CoeffsCyc(k).sage()
return R(sum(coeffs[a] * zeta**a for a in range(k)))
def __hash__(self):
r"""
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: hash(UCF.zero()) # indirect doctest
0
sage: hash(UCF.gen(3,2)) == hash((3,0,0,1))
True
TESTS:
See :trac:`19514`::
sage: hash(UCF.one())
1
"""
k = ZZ(self._obj.Conductor())
coeffs = self._obj.CoeffsCyc(k).sage()
if k == 1:
return hash(coeffs[0])
else:
return hash((k,) + tuple(coeffs))
def _algebraic_(self, R):
r"""
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: AA(UCF.gen(5) + UCF.gen(5,4))
0.618033988749895?
sage: AA(UCF.gen(5))
Traceback (most recent call last):
...
ValueError: Cannot coerce algebraic number with non-zero imaginary
part to algebraic real
"""
return R(QQbar(self))
def __float__(self):
r"""
TESTS::
sage: float(E(7) + E(7,6))
1.246979603717467
"""
from sage.rings.real_mpfr import RR
return float(RR(self))
def __complex__(self):
r"""
TESTS::
sage: complex(E(3))
(-0.5+0.8660254037844386j)
"""
f = self.parent().coerce_embedding()
return complex(f(self))
def _eval_complex_(self, R):
r"""
Return a complex value of this element in ``R``.
TESTS::
sage: CC(E(3))
-0.500000000000000 + 0.866025403784439*I
Check that :trac:`19825` is fixed::
sage: CIF(E(3))
-0.500000000000000? + 0.866025403784439?*I
sage: CIF(E(5))
0.309016994374948? + 0.9510565162951536?*I
sage: CIF(E(12))
0.86602540378444? + 0.50000000000000?*I
If the input is real, the imaginary part is exactly 0::
sage: CIF(E(17,2) + E(17,15))
1.47801783444132?
sage: _.imag().is_zero()
True
Check that units are evaluated correctly (:trac:`23775`)::
sage: CIF(1 + E(8) - E(8,3))
2.41421356237310?
sage: (1 + E(8) - E(8,3))._eval_complex_(CC)
2.41421356237309
sage: (1 + E(8) - E(8,3))._eval_complex_(CDF) # abs tol 1e-14
2.414213562373095
"""
if self._obj.IsRat():
return R(self._obj.sage())
k = ZZ(self._obj.Conductor())
coeffs = self._obj.CoeffsCyc(k).sage()
zeta = R.zeta(k)
s = sum(coeffs[i] * zeta ** i for i in range(k))
if self.is_real():
return R(s.real())
return s
_complex_mpfi_ = _eval_complex_
_complex_mpfr_field_ = _eval_complex_
def _eval_real_(self, R):
r"""
Return a real value of this element in ``R``.
TESTS::
sage: RR(E(7) + E(7,6))
1.24697960371747
sage: 2*cos(2*pi/7).n()
1.24697960371747
Check that units are evaluated correctly (:trac:`23775`)::
sage: RIF(1 + E(8) - E(8,3))
2.414213562373095?
sage: RR(1 + E(8) - E(8,3))
2.41421356237309
sage: RDF(1 + E(8) - E(8,3))
2.414213562373095
"""
if not self.is_real():
raise TypeError("self is not real")
if self._obj.IsRat():
return R(self._obj.sage())
k = ZZ(self._obj.Conductor())
coeffs = self._obj.CoeffsCyc(k).sage()
t = (2 * R.pi()) / k
return sum(coeffs[i] * (i * t).cos() for i in range(k))
_mpfr_ = _eval_real_
def _richcmp_(self, other, op):
r"""
Comparison (using the complex embedding).
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: l = [UCF.gen(3), UCF.gen(3)+1, UCF.gen(5), UCF.gen(5,2),
....: UCF.gen(4), 2*UCF.gen(4), UCF.gen(5)-22/3]
sage: lQQbar = list(map(QQbar,l))
sage: lQQbar.sort()
sage: l.sort()
sage: lQQbar == list(map(QQbar,l))
True
sage: for i in range(len(l)):
....: assert l[i] >= l[i] and l[i] <= l[i]
....: for j in range(i):
....: assert l[i] > l[j] and l[j] < l[i]
sage: fibonacci(200)*(E(5)+E(5,4)) <= fibonacci(199)
True
sage: fibonacci(201)*(E(5)+E(5,4)) <= fibonacci(200)
False
"""
if self._obj == other._obj:
return rich_to_bool(op, 0)
s = self.real_part()
o = other.real_part()
if s == o:
s = self.imag_part()
o = other.imag_part()
from sage.rings.real_mpfi import RealIntervalField
prec = 53
R = RealIntervalField(prec)
sa = s._eval_real_(R)
oa = o._eval_real_(R)
while sa.overlaps(oa):
prec <<= 2
R = RealIntervalField(prec)
sa = s._eval_real_(R)
oa = o._eval_real_(R)
return sa._richcmp_(oa, op)
def denominator(self):
r"""
Return the denominator of this element.
.. SEEALSO:: :meth:`is_integral`
EXAMPLES::
sage: a = E(5) + 1/2*E(5,2) + 1/3*E(5,3)
sage: a
E(5) + 1/2*E(5)^2 + 1/3*E(5)^3
sage: a.denominator()
6
sage: parent(_)
Integer Ring
"""
return ZZ(self._obj.DenominatorCyc())
def multiplicative_order(self):
r"""
Return the multiplicative order.
EXAMPLES::
sage: E(5).multiplicative_order()
5
sage: (E(5) + E(12)).multiplicative_order()
+Infinity
sage: UniversalCyclotomicField().zero().multiplicative_order()
Traceback (most recent call last):
...
GAPError: Error, argument must be nonzero
"""
return self._obj.Order().sage()
def additive_order(self):
r"""
Return the additive order.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF.zero().additive_order()
0
sage: UCF.one().additive_order()
+Infinity
sage: UCF.gen(3).additive_order()
+Infinity
"""
return Infinity if self else ZZ.zero()
def is_rational(self):
r"""
Test whether this element is a rational number.
EXAMPLES::
sage: E(3).is_rational()
False
sage: (E(3) + E(3,2)).is_rational()
True
TESTS::
sage: type(E(3).is_rational())
<... 'bool'>
"""
return self._obj.IsRat().sage()
def _rational_(self):
r"""
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: QQ(UCF.zero()) # indirect doctest
0
sage: parent(_)
Rational Field
sage: QQ(UCF.one()) # indirect doctest
1
sage: parent(_)
Rational Field
sage: QQ(E(3)/2 + E(3,2)/2) # indirect doctest
-1/2
"""
if not self._obj.IsRat():
raise TypeError("Unable to coerce to a rational")
return Rational(self._obj.sage())
def _repr_(self):
r"""
TESTS::
sage: U1 = UniversalCyclotomicField(names='E')
sage: U2 = UniversalCyclotomicField(names='UCF')
sage: U1.gen(5,2)
E(5)^2
sage: U2.gen(5,2)
E(5)^2
"""
s = str(self._obj)
first_char = s[0]
s = s[1:].replace('+', ' + ').replace('-', ' - ')
return first_char + s
def _add_(self, other):
r"""
TESTS::
sage: E(3) + E(5)
-E(15)^2 - 2*E(15)^8 - E(15)^11 - E(15)^13 - E(15)^14
sage: 1/2 + E(3)
1/2*E(3) - 1/2*E(3)^2
"""
P = self.parent()
return P.element_class(P, self._obj + other._obj)
def _sub_(self, other):
r"""
TESTS::
sage: E(3) - E(5)
-E(15)^2 - E(15)^11 + E(15)^13 - E(15)^14
"""
P = self.parent()
return P.element_class(P, self._obj - other._obj)
def __neg__(self):
r"""
Return the inverse of ``self``.
TESTS::
sage: -E(5)
-E(5)
"""
P = self.parent()
return P.element_class(P, -self._obj)
def _mul_(self, other):
r"""
TESTS::
sage: E(3) * E(4)
E(12)^7
sage: 3 * E(4)
3*E(4)
sage: E(4) * 3
3*E(4)
"""
P = self.parent()
return P.element_class(P, self._obj * other._obj)
def _div_(self, other):
r"""
TESTS::
sage: E(3)/2
1/2*E(3)
sage: 2/E(3)
2*E(3)^2
"""
P = self.parent()
try:
return P.element_class(P, self._obj / other._obj)
except ValueError:
raise ZeroDivisionError("division by zero")
def __invert__(self):
r"""
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: ~(UCF.one())
1
sage: ~UCF.gen(4)
-E(4)
"""
P = self.parent()
return P.element_class(P, ~self._obj)
inverse = __invert__
def _pow_(self, other):
r"""
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: UCF(3/2) ** (1/2)
-1/2*E(24) + 1/2*E(24)^11 + 1/2*E(24)^17 - 1/2*E(24)^19
sage: (1/2 + UCF.zeta(4)) ** (1/2)
Traceback (most recent call last):
...
NotImplementedError: no powering implemented beyond square root of rationals
sage: UCF(3/2) ** UCF.zeta(3)
Traceback (most recent call last):
...
NotImplementedError: no powering implemented for non-rational exponents
"""
if other._obj.IsRat():
other = other._obj.sage()
num = other.numerator()
den = other.denominator()
if den.is_one():
return self ** num
if den == 2 and self._obj.IsRat():
return self.sqrt() ** num
else:
raise NotImplementedError("no powering implemented beyond square root of rationals")
raise NotImplementedError("no powering implemented for non-rational exponents")
def is_square(self):
r"""
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF(5/2).is_square()
True
sage: UCF.zeta(7,3).is_square()
True
sage: (2 + UCF.zeta(3)).is_square()
Traceback (most recent call last):
...
NotImplementedError: is_square() not fully implemented for elements of Universal Cyclotomic Field
"""
if self._obj.IsRat():
return True
k = self._obj.Conductor()
coeffs = self._obj.CoeffsCyc(k).sage()
if sum(bool(x) for x in coeffs) == 1:
return True
raise NotImplementedError("is_square() not fully implemented for elements of Universal Cyclotomic Field")
def sqrt(self, extend=True, all=False):
"""
Return a square root of ``self``.
With default options, the output is an element of the universal
cyclotomic field when this element is expressed via a single root
of unity (including rational numbers). Otherwise, return an algebraic
number.
INPUT:
- ``extend`` -- bool (default: ``True``); if ``True``, might return a
square root in the algebraic closure of the rationals. If false,
return a square root in the universal cyclotomic field or raises
an error.
- ``all`` -- bool (default: ``False``); if ``True``, return a
list of all square roots.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF(3).sqrt()
E(12)^7 - E(12)^11
sage: (UCF(3).sqrt())**2
3
sage: r = UCF(-1400 / 143).sqrt()
sage: r**2
-1400/143
sage: E(33).sqrt()
-E(33)^17
sage: E(33).sqrt() ** 2
E(33)
sage: (3 * E(5)).sqrt()
-E(60)^11 + E(60)^31
sage: (3 * E(5)).sqrt() ** 2
3*E(5)
Setting ``all=True`` you obtain the two square roots in a list::
sage: UCF(3).sqrt(all=True)
[E(12)^7 - E(12)^11, -E(12)^7 + E(12)^11]
sage: (1 + UCF.zeta(5)).sqrt(all=True)
[1.209762576525833? + 0.3930756888787117?*I,
-1.209762576525833? - 0.3930756888787117?*I]
In the following situation, Sage is not (yet) able to compute a
square root within the universal cyclotomic field::
sage: (E(5) + E(5, 2)).sqrt()
0.7476743906106103? + 1.029085513635746?*I
sage: (E(5) + E(5, 2)).sqrt(extend=False)
Traceback (most recent call last):
...
NotImplementedError: sqrt() not fully implemented for elements of Universal Cyclotomic Field
"""
if all:
s = self.sqrt(all=False)
return [s, -s]
UCF = self.parent()
# rational case
if self._obj.IsRat():
D = self._obj.sage()
if self._obj.IsInt():
return UCF_sqrt_int(D, UCF)
else:
return UCF_sqrt_int(D.numerator(), UCF) / \
UCF_sqrt_int(D.denominator(), UCF)
# root of unity
k = self._obj.Conductor()
coeffs = self._obj.CoeffsCyc(k).sage()
if sum(bool(x) for x in coeffs) == 1:
for i, x in enumerate(coeffs):
if x:
break
return UCF(x).sqrt() * UCF.zeta(2 * k, i)
# no method to construct square roots yet...
if extend:
return QQbar(self).sqrt()
else:
raise NotImplementedError("sqrt() not fully implemented for elements of Universal Cyclotomic Field")
def conjugate(self):
r"""
Return the complex conjugate.
EXAMPLES::
sage: (E(7) + 3*E(7,2) - 5 * E(7,3)).conjugate()
-5*E(7)^4 + 3*E(7)^5 + E(7)^6
"""
P = self.parent()
return P.element_class(P, self._obj.ComplexConjugate())
def galois_conjugates(self, n=None):
r"""
Return the Galois conjugates of ``self``.
INPUT:
- ``n`` -- an optional integer. If provided, return the orbit of the
Galois group of the ``n``-th cyclotomic field over `\QQ`. Note that
``n`` must be such that this element belongs to the ``n``-th
cyclotomic field (in other words, it must be a multiple of the
conductor).
EXAMPLES::
sage: E(6).galois_conjugates()
[-E(3)^2, -E(3)]
sage: E(6).galois_conjugates()
[-E(3)^2, -E(3)]
sage: (E(9,2) - E(9,4)).galois_conjugates()
[E(9)^2 - E(9)^4,
E(9)^2 + E(9)^4 + E(9)^5,
-E(9)^2 - E(9)^5 - E(9)^7,
-E(9)^2 - E(9)^4 - E(9)^7,
E(9)^4 + E(9)^5 + E(9)^7,
-E(9)^5 + E(9)^7]
sage: zeta = E(5)
sage: zeta.galois_conjugates(5)
[E(5), E(5)^2, E(5)^3, E(5)^4]
sage: zeta.galois_conjugates(10)
[E(5), E(5)^3, E(5)^2, E(5)^4]
sage: zeta.galois_conjugates(15)
[E(5), E(5)^2, E(5)^4, E(5)^2, E(5)^3, E(5), E(5)^3, E(5)^4]
sage: zeta.galois_conjugates(17)
Traceback (most recent call last):
...
ValueError: n = 17 must be a multiple of the conductor (5)
"""
P = self.parent()
obj = self._obj
k = obj.Conductor().sage()
n = k if n is None else ZZ(n)
if not k.divides(n):
raise ValueError("n = {} must be a multiple of the conductor ({})".format(n, k))
return [P.element_class(P, obj.GaloisCyc(i))
for i in n.coprime_integers(n)]
def __abs__(self):
"""
Return the absolute value (or complex modulus) of ``self``.
The absolute value is returned as an algebraic real number.
EXAMPLES::
sage: f = 5/2*E(3)+E(5)/7
sage: f.abs()
2.597760303873084?
sage: abs(f)
2.597760303873084?
sage: a = E(8)
sage: abs(a)
1
sage: v, w = vector([a]), vector([a, a])
sage: v.norm(), w.norm()
(1, 1.414213562373095?)
sage: v.norm().parent()
Algebraic Real Field
TESTS::
sage: [abs(E(n)) for n in range(1, 11)]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
sage: UniversalCyclotomicField().zero().abs()
0
"""
square = self * self.conjugate()
return AA(square).sqrt()
abs = __abs__
def norm_of_galois_extension(self):
r"""
Return the norm as a Galois extension of `\QQ`, which is
given by the product of all galois_conjugates.
EXAMPLES::
sage: E(3).norm_of_galois_extension()
1
sage: E(6).norm_of_galois_extension()
1
sage: (E(2) + E(3)).norm_of_galois_extension()
3
sage: parent(_)
Integer Ring
"""
obj = self._obj
k = obj.Conductor().sage()
return libgap.Product(libgap([obj.GaloisCyc(i) for i in range(k)
if k.gcd(i) == 1])).sage()
def minpoly(self, var='x'):
r"""
The minimal polynomial of ``self`` element over `\QQ`.
INPUT:
- ``var`` -- (optional, default 'x') the name of the variable to use.
EXAMPLES::
sage: UCF.<E> = UniversalCyclotomicField()
sage: UCF(4).minpoly()
x - 4
sage: UCF(4).minpoly(var='y')
y - 4
sage: E(3).minpoly()
x^2 + x + 1
sage: E(3).minpoly(var='y')
y^2 + y + 1
TESTS::
sage: for elt in UCF.some_elements():
....: assert elt.minpoly() == elt.to_cyclotomic_field().minpoly()
....: assert elt.minpoly(var='y') == elt.to_cyclotomic_field().minpoly(var='y')
.. TODO::
Polynomials with libgap currently does not implement a ``.sage()`` method
(see :trac:`18266`). It would be faster/safer to not use string to
construct the polynomial.
"""
gap_p = libgap.MinimalPolynomial(libgap.eval("Rationals"), self._obj)
return QQ[var](QQ['x_1'](str(gap_p)))
class UniversalCyclotomicField(UniqueRepresentation, Field):
r"""
The universal cyclotomic field.
The universal cyclotomic field is the infinite algebraic extension of `\QQ`
generated by the roots of unity. It is also the maximal Abelian extension of
`\QQ` in the sense that any Abelian Galois extension of `\QQ` is also a
subfield of the universal cyclotomic field.
"""
Element = UniversalCyclotomicFieldElement
@staticmethod
def __classcall__(cls, names=None):
r"""
Just ignoring the argument ``names``.
TESTS::
sage: UCF.<E> = UniversalCyclotomicField()
sage: E(3,1)
E(3)
sage: E(3,2)
E(3)^2
"""
return super().__classcall__(cls, None)
def __init__(self, names=None):
r"""
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: TestSuite(UCF).run()
sage: UniversalCyclotomicField().is_finite()
False
"""
from sage.categories.fields import Fields
Field.__init__(self, base_ring=QQ, category=Fields().Infinite())
self._populate_coercion_lists_(embedding=UCFtoQQbar(self))
late_import()
def _first_ngens(self, n):
r"""
Return the function :meth:`gen` if ``n=1``, and raises an error otherwise.
This method is needed to make the following work::
sage: UCF.<E> = UniversalCyclotomicField() # indirect doctest
"""
if n == 1:
return (self.gen,)
else:
raise ValueError("This ring has only a single generator method.")
def an_element(self):
r"""
Return an element.
EXAMPLES::
sage: UniversalCyclotomicField().an_element()
E(5) - 3*E(5)^2
"""
return self.gen(5, 1) - self(3) * self.gen(5, 2)
def some_elements(self):
r"""
Return a tuple of some elements in the universal cyclotomic field.
EXAMPLES::
sage: UniversalCyclotomicField().some_elements()
(0, 1, -1, E(3), E(7) - 2/3*E(7)^2)
sage: all(parent(x) is UniversalCyclotomicField() for x in _)
True
"""
return (self.zero(), self.one(), -self.one(),
self.gen(3, 1),
self.gen(7, 1) - self(2) / self(3) * self.gen(7, 2))
def _repr_(self):
r"""
TESTS::
sage: UniversalCyclotomicField() # indirect doctest
Universal Cyclotomic Field
"""
return "Universal Cyclotomic Field"
def is_exact(self):
r"""
Return ``True`` as this is an exact ring (i.e. not numerical).
EXAMPLES::
sage: UniversalCyclotomicField().is_exact()
True
"""
return True
@cached_method
def zero(self):
r"""
Return zero.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF.zero()
0
sage: parent(_)
Universal Cyclotomic Field
"""
return self.element_class(self, libgap.zero())
@cached_method
def one(self):
r"""
Return one.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF.one()
1
sage: parent(_)
Universal Cyclotomic Field
"""
return self.element_class(self, libgap.one())
def characteristic(self):
r"""
Return the characteristic.
EXAMPLES::
sage: UniversalCyclotomicField().characteristic()
0
sage: parent(_)
Integer Ring
"""
return ZZ.zero()
def gen(self, n, k=1):
r"""
Return the standard primitive ``n``-th root of unity.
If ``k`` is not ``None``, return the ``k``-th power of it.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF.gen(15)
E(15)
sage: UCF.gen(7,3)
E(7)^3
sage: UCF.gen(4,2)
-1
There is an alias ``zeta`` also available::
sage: UCF.zeta(6)
-E(3)^2
"""
return self.element_class(self, libgap.E(n)**k)
zeta = gen
def _element_constructor_(self, elt):
r"""
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: UCF(3)
3
sage: UCF(3/2)
3/2
sage: C = CyclotomicField(13)
sage: UCF(C.gen())
E(13)
sage: UCF(C.gen() - 3*C.gen()**2 + 5*C.gen()**5)
E(13) - 3*E(13)^2 + 5*E(13)^5
sage: C = CyclotomicField(12)
sage: zeta12 = C.gen()
sage: a = UCF(zeta12 - 3* zeta12**2)
sage: a
-E(12)^7 + 3*E(12)^8
sage: C(_) == a
True
sage: UCF('[[0, 1], [0, 2]]')
Traceback (most recent call last):
...
TypeError: [ [ 0, 1 ], [ 0, 2 ] ]
of type <class 'sage.libs.gap.element.GapElement_List'> not valid
to initialize an element of the universal cyclotomic field
Some conversions from symbolic functions are possible::
sage: UCF = UniversalCyclotomicField()
sage: [UCF(sin(pi/k, hold=True)) for k in range(1,10)]
[0,
1,
-1/2*E(12)^7 + 1/2*E(12)^11,
1/2*E(8) - 1/2*E(8)^3,
-1/2*E(20)^13 + 1/2*E(20)^17,
1/2,
-1/2*E(28)^19 + 1/2*E(28)^23,
1/2*E(16)^3 - 1/2*E(16)^5,
-1/2*E(36)^25 + 1/2*E(36)^29]
sage: [UCF(cos(pi/k, hold=True)) for k in range(1,10)]
[-1,
0,
1/2,
1/2*E(8) - 1/2*E(8)^3,
-1/2*E(5)^2 - 1/2*E(5)^3,
-1/2*E(12)^7 + 1/2*E(12)^11,
-1/2*E(7)^3 - 1/2*E(7)^4,
1/2*E(16) - 1/2*E(16)^7,
-1/2*E(9)^4 - 1/2*E(9)^5]
sage: UCF(1 + sqrt(-3/5))
4/5*E(15) + 4/5*E(15)^2 + 4/5*E(15)^4 + 6/5*E(15)^7 + 4/5*E(15)^8 + 6/5*E(15)^11 + 6/5*E(15)^13 + 6/5*E(15)^14
.. TODO::
Implement conversion from QQbar (and as a consequence from the
symbolic ring)
"""
elt = py_scalar_to_element(elt)
if isinstance(elt, (Integer, Rational)):
return self.element_class(self, libgap(elt))
elif isinstance(elt, (GapElement_Integer, GapElement_Rational, GapElement_Cyclotomic)):
return self.element_class(self, elt)
elif not elt:
return self.zero()
obj = None
if isinstance(elt, gap.GapElement):
obj = libgap(elt)
elif isinstance(elt, gap3.GAP3Element):
obj = libgap.eval(str(elt))
elif isinstance(elt, str):
obj = libgap.eval(elt)
if obj is not None:
if not isinstance(obj, (GapElement_Integer, GapElement_Rational, GapElement_Cyclotomic)):
raise TypeError("{} of type {} not valid to initialize an element of the universal cyclotomic field".format(obj, type(obj)))
return self.element_class(self, obj)
# late import to avoid slowing down the above conversions
import sage.rings.abc
P = parent(elt)
if isinstance(P, sage.rings.abc.NumberField_cyclotomic):
from sage.rings.number_field.number_field_element import NumberFieldElement
if isinstance(elt, NumberFieldElement):
from sage.rings.number_field.number_field import CyclotomicField
n = P.gen().multiplicative_order()
elt = CyclotomicField(n)(elt)
return sum(c * self.gen(n, i)
for i, c in enumerate(elt._coefficients()))
if hasattr(elt, '_algebraic_'):
return elt._algebraic_(self)
raise TypeError("{} of type {} not valid to initialize an element of the universal cyclotomic field".format(elt, type(elt)))
def _coerce_map_from_(self, other):
r"""
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: UCF.has_coerce_map_from(ZZ)
True
sage: UCF.has_coerce_map_from(QQ)
True
sage: ZZ.has_coerce_map_from(UCF)
False
sage: QQ.has_coerce_map_from(UCF)
False
sage: QQbar.has_coerce_map_from(UCF)
True
sage: CC.has_coerce_map_from(UCF)
True
"""
if other is ZZ or other is QQ:
return True
import sage.rings.abc
if isinstance(other, sage.rings.abc.NumberField_cyclotomic):
return True
def _factor_univariate_polynomial(self, f):
"""
Factor the univariate polynomial ``f``.
INPUT:
- ``f`` -- a univariate polynomial defined over self
OUTPUT:
- A factorization of ``f`` over self into a unit and monic irreducible
factors
.. NOTE::
This is a helper method for
:meth:`sage.rings.polynomial.polynomial_element.Polynomial.factor`.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: x = polygen(UCF)
sage: p = x^2 +x +1
sage: p.factor() # indirect doctest
(x - E(3)) * (x - E(3)^2)
sage: p.roots() # indirect doctest
[(E(3), 1), (E(3)^2, 1)]
sage: (p^2).factor()
(x - E(3))^2 * (x - E(3)^2)^2
sage: cyclotomic_polynomial(12).change_ring(UCF).factor()
(x + E(12)^7) * (x - E(12)^11) * (x + E(12)^11) * (x - E(12)^7)
sage: p = (UCF.zeta(5) + 1) * (x^2 - 2)^2 * (x^2 - 3) * (x - 5)**2 * (x^2 - x + 1)
sage: p.factor()
(-E(5)^2 - E(5)^3 - E(5)^4) * (x + E(12)^7 - E(12)^11) * (x + E(3)^2) * (x + E(3)) * (x - E(12)^7 + E(12)^11) * (x - 5)^2 * (x - E(8) + E(8)^3)^2 * (x + E(8) - E(8)^3)^2
sage: p.factor().value() == p
True
sage: (x^3 - 8).factor()
(x - 2) * (x - 2*E(3)) * (x - 2*E(3)^2)
In most situations, the factorization will fail with a ``NotImplementedError``::
sage: (x^3 - 2).factor()
Traceback (most recent call last):
...
NotImplementedError: no known factorization for this polynomial
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: x = polygen(UCF)
sage: p = (x - 2/7) * (x - 3/5)
sage: sorted(p.roots(multiplicities=False))
[2/7, 3/5]
sage: p = UCF.zeta(3) * x - 1 + UCF.zeta(5,2)
sage: r = p.roots()
sage: r
[(-2*E(15) - E(15)^4 - E(15)^7 - E(15)^13, 1)]
sage: p(r[0][0])
0
"""
from sage.structure.factorization import Factorization
UCF = self
x = f.parent().gen()
# make the polynomial monic
unit = f.leading_coefficient()
f /= unit
# trivial degree one case
if f.degree() == 1:
return Factorization([(f, 1)], unit)
# From now on, we restrict to polynomial with rational cofficients. The
# factorization is provided only in the case it is a product of
# cyclotomic polynomials and quadratic polynomials. In this situation
# the roots belong to UCF and the polynomial factorizes as a product of
# degree one factors.
if any(ZZ(cf._obj.Conductor()) != 1 for cf in f):
raise NotImplementedError('no known factorization for this polynomial')
f = f.change_ring(QQ)
factors = []
for p, e in f.factor():
if p.degree() == 1:
factors.append((x + p[0], e))
elif p.degree() == 2:
c = p[0]
b = p[1]
a = p[2]
D = UCF(b**2 - 4 * a * c).sqrt()
r1 = (-b - D) / (2 * a)
r2 = (-b + D) / (2 * a)
factors.append((x - r1, e))
factors.append((x - r2, e))
else:
m = p.is_cyclotomic(certificate=True)
if not m:
raise NotImplementedError('no known factorization for this polynomial')
for i in m.coprime_integers(m):
factors.append((x - UCF.zeta(m, i), e))
return Factorization(factors, unit)
def degree(self):
r"""
Return the *degree* of ``self`` as a field extension over the Rationals.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF.degree()
+Infinity
"""
return Infinity
def _gap_init_(self):
r"""
Return gap string representation of ``self``.
EXAMPLES::
sage: UCF = UniversalCyclotomicField()
sage: UCF._gap_init_()
'Cyclotomics'
"""
return 'Cyclotomics'
def algebraic_closure(self):
r"""
The algebraic closure.
EXAMPLES::
sage: UniversalCyclotomicField().algebraic_closure()
Algebraic Field
"""
return QQbar
def E(n, k=1):
r"""
Return the ``n``-th root of unity as an element of the universal cyclotomic
field.
EXAMPLES::
sage: E(3)
E(3)
sage: E(3) + E(5)
-E(15)^2 - 2*E(15)^8 - E(15)^11 - E(15)^13 - E(15)^14
"""
return UniversalCyclotomicField().gen(n, k) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/universal_cyclotomic_field.py | 0.895668 | 0.728435 | universal_cyclotomic_field.py | pypi |
r"""
Signed and Unsigned Infinities
The unsigned infinity "ring" is the set of two elements
1. infinity
2. A number less than infinity
The rules for arithmetic are that the unsigned infinity ring does
not canonically coerce to any other ring, and all other rings
canonically coerce to the unsigned infinity ring, sending all
elements to the single element "a number less than infinity" of the
unsigned infinity ring. Arithmetic and comparisons then take place
in the unsigned infinity ring, where all arithmetic operations that
are well-defined are defined.
The infinity "ring" is the set of five elements
1. plus infinity
2. a positive finite element
3. zero
4. a negative finite element
5. negative infinity
The infinity ring coerces to the unsigned infinity ring, sending
the infinite elements to infinity and the non-infinite elements to
"a number less than infinity." Any ordered ring coerces to the
infinity ring in the obvious way.
.. NOTE::
The shorthand ``oo`` is predefined in Sage to be the same as
``+Infinity`` in the infinity ring. It is considered equal to, but not
the same as ``Infinity`` in the
:class:`UnsignedInfinityRing<UnsignedInfinityRing_class>`.
EXAMPLES:
We fetch the unsigned infinity ring and create some elements::
sage: P = UnsignedInfinityRing; P
The Unsigned Infinity Ring
sage: P(5)
A number less than infinity
sage: P.ngens()
1
sage: unsigned_oo = P.0; unsigned_oo
Infinity
We compare finite numbers with infinity::
sage: 5 < unsigned_oo
True
sage: 5 > unsigned_oo
False
sage: unsigned_oo < 5
False
sage: unsigned_oo > 5
True
Demonstrating the shorthand ``oo`` versus ``Infinity``::
sage: oo
+Infinity
sage: oo is InfinityRing.0
True
sage: oo is UnsignedInfinityRing.0
False
sage: oo == UnsignedInfinityRing.0
True
We do arithmetic::
sage: unsigned_oo + 5
Infinity
We make ``1 / unsigned_oo`` return the integer 0 so that arithmetic of
the following type works::
sage: (1/unsigned_oo) + 2
2
sage: 32/5 - (2.439/unsigned_oo)
32/5
Note that many operations are not defined, since the result is not
well-defined::
sage: unsigned_oo/0
Traceback (most recent call last):
...
ValueError: quotient of number < oo by number < oo not defined
What happened above is that 0 is canonically coerced to "A number less
than infinity" in the unsigned infinity ring. Next, Sage tries to divide
by multiplying with its inverse. Finally, this inverse is not
well-defined.
::
sage: 0/unsigned_oo
0
sage: unsigned_oo * 0
Traceback (most recent call last):
...
ValueError: unsigned oo times smaller number not defined
sage: unsigned_oo/unsigned_oo
Traceback (most recent call last):
...
ValueError: unsigned oo times smaller number not defined
In the infinity ring, we can negate infinity, multiply positive
numbers by infinity, etc.
::
sage: P = InfinityRing; P
The Infinity Ring
sage: P(5)
A positive finite number
The symbol ``oo`` is predefined as a shorthand for ``+Infinity``::
sage: oo
+Infinity
We compare finite and infinite elements::
sage: 5 < oo
True
sage: P(-5) < P(5)
True
sage: P(2) < P(3)
False
sage: -oo < oo
True
We can do more arithmetic than in the unsigned infinity ring::
sage: 2 * oo
+Infinity
sage: -2 * oo
-Infinity
sage: 1 - oo
-Infinity
sage: 1 / oo
0
sage: -1 / oo
0
We make ``1 / oo`` and ``1 / -oo`` return the integer 0 instead of the
infinity ring Zero so that arithmetic of the following type works::
sage: (1/oo) + 2
2
sage: 32/5 - (2.439/-oo)
32/5
If we try to subtract infinities or multiply infinity by zero we
still get an error::
sage: oo - oo
Traceback (most recent call last):
...
SignError: cannot add infinity to minus infinity
sage: 0 * oo
Traceback (most recent call last):
...
SignError: cannot multiply infinity by zero
sage: P(2) + P(-3)
Traceback (most recent call last):
...
SignError: cannot add positive finite value to negative finite value
Signed infinity can also be represented by RR / RDF elements. But
unsigned infinity cannot::
sage: oo in RR, oo in RDF
(True, True)
sage: unsigned_infinity in RR, unsigned_infinity in RDF
(False, False)
TESTS::
sage: P = InfinityRing
sage: P == loads(dumps(P))
True
::
sage: P(2) == loads(dumps(P(2)))
True
The following is assumed in a lot of code (i.e., "is" is used for
testing whether something is infinity), so make sure it is satisfied::
sage: loads(dumps(infinity)) is infinity
True
We check that :trac:`17990` is fixed::
sage: m = Matrix([Infinity])
sage: m.rows()
[(+Infinity)]
"""
#*****************************************************************************
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from sys import maxsize
from sage.rings.ring import Ring
from sage.structure.element import RingElement, InfinityElement
from sage.structure.richcmp import rich_to_bool, richcmp
from sage.misc.fast_methods import Singleton
import sage.rings.abc
import sage.rings.integer
import sage.rings.rational
import sage.rings.integer_ring
_obj = {}
class _uniq():
def __new__(cls, *args):
"""
This ensures uniqueness of these objects.
EXAMPLES::
sage: sage.rings.infinity.UnsignedInfinityRing_class() is sage.rings.infinity.UnsignedInfinityRing_class()
True
"""
if cls in _obj:
return _obj[cls]
_obj[cls] = O = cls.__bases__[-1].__new__(cls, *args)
return O
class AnInfinity():
"""
TESTS::
sage: oo == oo
True
sage: oo < oo
False
sage: -oo < oo
True
sage: -oo < 3 < oo
True
sage: unsigned_infinity == 3
False
sage: unsigned_infinity == unsigned_infinity
True
sage: unsigned_infinity == oo
True
"""
def _repr_(self):
"""
Return a string representation of ``self``.
TESTS::
sage: [x._repr_() for x in [unsigned_infinity, oo, -oo]]
['Infinity', '+Infinity', '-Infinity']
"""
return self._sign_char + "Infinity"
def _giac_init_(self):
"""
TESTS::
sage: [x._giac_init_() for x in [unsigned_infinity, oo, -oo]]
['infinity', '+infinity', '-infinity']
"""
return self._sign_char + "infinity"
def _maxima_init_(self):
"""
TESTS::
sage: maxima(-oo)
minf
sage: [x._maxima_init_() for x in [unsigned_infinity, oo, -oo]]
['inf', 'inf', 'minf']
"""
if self._sign < 0:
return 'minf'
else:
return 'inf'
def _fricas_init_(self):
"""
TESTS::
sage: fricas(-oo) # optional - fricas
- infinity
sage: [x._fricas_init_() for x in [unsigned_infinity, oo, -oo]] # optional - fricas
['%infinity', '%plusInfinity', '%minusInfinity']
sage: [fricas(x) for x in [unsigned_infinity, oo, -oo]] # optional - fricas
[infinity, + infinity, - infinity]
"""
if self._sign_char == '':
return r"%infinity"
elif self._sign > 0:
return r"%plusInfinity"
else:
return r"%minusInfinity"
def __pari__(self):
"""
Convert ``self`` to a Pari object.
EXAMPLES::
sage: pari(-oo)
-oo
sage: pari(oo)
+oo
"""
# For some reason, it seems problematic to import sage.libs.all.pari,
# so we call it directly.
if self._sign >= 0:
return sage.libs.all.pari('oo')
else:
return sage.libs.all.pari('-oo')
def _latex_(self):
r"""
Return a latex representation of ``self``.
EXAMPLES::
sage: latex(oo) # indirect doctest
+\infty
sage: [x._latex_() for x in [unsigned_infinity, oo, -oo]]
['\\infty', '+\\infty', '-\\infty']
"""
return self._sign_char + "\\infty"
def __abs__(self):
"""
EXAMPLES::
sage: [abs(x) for x in [UnsignedInfinityRing.gen(), oo, -oo]]
[Infinity, +Infinity, +Infinity]
"""
return -self if self._sign < 0 else self
def _add_(self, other):
"""
Add ``self`` to ``other``.
EXAMPLES::
sage: -oo + -oo # indirect doctest
-Infinity
sage: -oo + 3
-Infinity
sage: oo + -100
+Infinity
sage: oo + -oo
Traceback (most recent call last):
...
SignError: cannot add infinity to minus infinity
sage: unsigned_infinity = UnsignedInfinityRing.gen()
sage: unsigned_infinity + unsigned_infinity
Traceback (most recent call last):
...
SignError: cannot add unsigned infinities
sage: unsigned_infinity + oo*i
Traceback (most recent call last):
...
SignError: cannot add unsigned infinities
sage: unsigned_infinity + 88/3
Infinity
"""
if isinstance(other, AnInfinity):
if self._sign == 0:
# just like oo - oo is undefined
raise SignError("cannot add unsigned infinities")
if self._sign != other._sign:
raise SignError("cannot add infinity to minus infinity")
return self
def _sub_(self, other):
"""
EXAMPLES::
sage: -oo - oo # indirect doctest
-Infinity
sage: oo - -oo
+Infinity
sage: oo - 4
+Infinity
sage: -oo - 1
-Infinity
sage: oo - oo
Traceback (most recent call last):
...
SignError: cannot add infinity to minus infinity
sage: unsigned_infinity - 4
Infinity
sage: unsigned_infinity - unsigned_infinity
Traceback (most recent call last):
...
SignError: cannot subtract unsigned infinities
sage: unsigned_infinity - oo*i
Traceback (most recent call last):
...
SignError: cannot subtract unsigned infinities
"""
if isinstance(other, AnInfinity):
if self._sign == 0:
raise SignError("cannot subtract unsigned infinities")
elif self._sign == other._sign:
raise SignError("cannot add infinity to minus infinity")
return self
def _mul_(self, other):
"""
EXAMPLES::
sage: oo * 19 # indirect doctest
+Infinity
sage: oo * oo
+Infinity
sage: -oo * oo
-Infinity
sage: -oo * 4
-Infinity
sage: -oo * -2/3
+Infinity
sage: -oo * 0
Traceback (most recent call last):
...
SignError: cannot multiply infinity by zero
"""
if other < 0:
return -self
if other > 0:
return self
raise SignError("cannot multiply infinity by zero")
def _div_(self, other):
"""
EXAMPLES::
sage: 1.5 / oo # indirect doctest
0
sage: oo / -4
-Infinity
sage: oo / oo
Traceback (most recent call last):
...
SignError: cannot multiply infinity by zero
Check that :trac:`14857` is fixed::
sage: infinity / unsigned_infinity
Traceback (most recent call last):
...
ValueError: unsigned oo times smaller number not defined
sage: SR(infinity) / unsigned_infinity
Traceback (most recent call last):
...
RuntimeError: indeterminate expression: 0 * infinity encountered.
"""
return self * ~other
def __float__(self):
r"""
Generate a floating-point infinity. The printing of
floating-point infinity varies across platforms.
EXAMPLES::
sage: RDF(infinity)
+infinity
sage: float(infinity) # random
+infinity
sage: CDF(infinity)
+infinity
sage: infinity.__float__() # random
+infinity
sage: RDF(-infinity)
-infinity
sage: float(-infinity) # random
-inf
sage: CDF(-infinity)
-infinity
sage: (-infinity).__float__() # random
-inf
sage: float(unsigned_infinity)
Traceback (most recent call last):
...
ValueError: unsigned infinity cannot be represented in a float
"""
if self._sign == 0:
raise ValueError('unsigned infinity cannot be represented in a float')
return float(self._sign_char + 'inf')
def lcm(self, x):
"""
Return the least common multiple of ``oo`` and ``x``, which
is by definition oo unless ``x`` is 0.
EXAMPLES::
sage: oo.lcm(0)
0
sage: oo.lcm(oo)
+Infinity
sage: oo.lcm(-oo)
+Infinity
sage: oo.lcm(10)
+Infinity
sage: (-oo).lcm(10)
+Infinity
"""
if x == 0:
return x
else:
return abs(self)
def _sage_input_(self, sib, coerced):
"""
Produce an expression which will reproduce this value when evaluated.
TESTS::
sage: sage_input(-oo)
-oo
sage: sage_input(oo)
oo
sage: sage_input(unsigned_infinity)
unsigned_infinity
"""
if self._sign == 0:
return sib.name('unsigned_infinity')
elif self._sign > 0:
return sib.name('oo')
else:
return -sib.name('oo')
class UnsignedInfinityRing_class(Singleton, Ring):
def __init__(self):
"""
Initialize ``self``.
TESTS::
sage: sage.rings.infinity.UnsignedInfinityRing_class() is sage.rings.infinity.UnsignedInfinityRing_class() is UnsignedInfinityRing
True
Sage can understand SymPy's complex infinity (:trac:`17493`)::
sage: import sympy
sage: SR(sympy.zoo)
Infinity
Some equality checks::
sage: infinity == UnsignedInfinityRing.gen()
True
sage: UnsignedInfinityRing(3) == UnsignedInfinityRing(-19.5)
True
"""
Ring.__init__(self, self, names=('oo',), normalize=False)
def ngens(self):
"""
The unsigned infinity ring has one "generator."
EXAMPLES::
sage: UnsignedInfinityRing.ngens()
1
sage: len(UnsignedInfinityRing.gens())
1
"""
return 1
def fraction_field(self):
"""
The unsigned infinity ring isn't an integral domain.
EXAMPLES::
sage: UnsignedInfinityRing.fraction_field()
Traceback (most recent call last):
...
TypeError: infinity 'ring' has no fraction field
"""
raise TypeError("infinity 'ring' has no fraction field")
def gen(self, n=0):
"""
The "generator" of ``self`` is the infinity object.
EXAMPLES::
sage: UnsignedInfinityRing.gen()
Infinity
sage: UnsignedInfinityRing.gen(1)
Traceback (most recent call last):
...
IndexError: UnsignedInfinityRing only has one generator
"""
if n == 0:
try:
return self._gen
except AttributeError:
self._gen = UnsignedInfinity()
return self._gen
else:
raise IndexError("UnsignedInfinityRing only has one generator")
def gens(self):
"""
The "generator" of ``self`` is the infinity object.
EXAMPLES::
sage: UnsignedInfinityRing.gens()
[Infinity]
"""
return [self.gen()]
def less_than_infinity(self):
"""
This is the element that represents a finite value.
EXAMPLES::
sage: UnsignedInfinityRing.less_than_infinity()
A number less than infinity
sage: UnsignedInfinityRing(5) is UnsignedInfinityRing.less_than_infinity()
True
"""
try:
return self._less_than_infinity
except AttributeError:
self._less_than_infinity = LessThanInfinity(self)
return self._less_than_infinity
def _repr_(self):
"""
Return a string representation of ``self``.
TESTS::
sage: UnsignedInfinityRing._repr_()
'The Unsigned Infinity Ring'
"""
return "The Unsigned Infinity Ring"
def _element_constructor_(self, x):
"""
The element constructor
TESTS::
sage: UnsignedInfinityRing(2) # indirect doctest
A number less than infinity
sage: UnsignedInfinityRing(I)
A number less than infinity
sage: UnsignedInfinityRing(unsigned_infinity)
Infinity
sage: UnsignedInfinityRing(oo)
Infinity
sage: UnsignedInfinityRing(-oo)
Infinity
sage: K.<a> = QuadraticField(3)
sage: UnsignedInfinityRing(a)
A number less than infinity
sage: UnsignedInfinityRing(a - 2)
A number less than infinity
sage: UnsignedInfinityRing(RDF(oo)), UnsignedInfinityRing(RDF(-oo))
(Infinity, Infinity)
sage: UnsignedInfinityRing(RR(oo)), UnsignedInfinityRing(RR(-oo))
(Infinity, Infinity)
sage: UnsignedInfinityRing(CDF(oo)), UnsignedInfinityRing(CDF(-oo))
(Infinity, Infinity)
sage: UnsignedInfinityRing(CC(oo)), UnsignedInfinityRing(CC(-oo))
(Infinity, Infinity)
sage: UnsignedInfinityRing(RIF(oo)), UnsignedInfinityRing(RIF(-oo))
(Infinity, Infinity)
sage: UnsignedInfinityRing(float('+inf')), UnsignedInfinityRing(float('-inf'))
(Infinity, Infinity)
sage: UnsignedInfinityRing(SR(oo)), UnsignedInfinityRing(SR(-oo))
(Infinity, Infinity)
The following rings have a ``is_infinity`` method::
sage: RR(oo).is_infinity()
True
sage: SR(oo).is_infinity()
True
"""
# Lazy elements can wrap infinity or not, unwrap first
try:
from sage.rings.real_lazy import LazyWrapper
except ImportError:
pass
else:
if isinstance(x, LazyWrapper):
x = x._value
# Handle all ways to represent infinity first
if isinstance(x, InfinityElement):
return self.gen()
elif isinstance(x, float):
if x in [float('+inf'), float('-inf')]:
return self.gen()
elif isinstance(x, RingElement) and isinstance(x.parent(), sage.rings.abc.RealIntervalField):
if x.upper().is_infinity() or x.lower().is_infinity():
return self.gen()
else:
try:
# For example, RealField() implements this
if x.is_infinity():
return self.gen()
except AttributeError:
pass
# If we got here then x is not infinite
return self.less_than_infinity()
def _coerce_map_from_(self, R):
"""
EXAMPLES::
sage: UnsignedInfinityRing.has_coerce_map_from(int) # indirect doctest
True
sage: UnsignedInfinityRing.has_coerce_map_from(CC)
True
sage: UnsignedInfinityRing.has_coerce_map_from(QuadraticField(-163, 'a'))
True
sage: UnsignedInfinityRing.has_coerce_map_from(QQ^3)
False
sage: UnsignedInfinityRing.has_coerce_map_from(SymmetricGroup(13))
False
"""
return isinstance(R, Ring) or R in (int, float, complex)
UnsignedInfinityRing = UnsignedInfinityRing_class()
class LessThanInfinity(_uniq, RingElement):
def __init__(self, parent=UnsignedInfinityRing):
"""
Initialize ``self``.
EXAMPLES::
sage: sage.rings.infinity.LessThanInfinity() is UnsignedInfinityRing(5)
True
"""
RingElement.__init__(self, parent)
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: UnsignedInfinityRing(5)._repr_()
'A number less than infinity'
"""
return "A number less than infinity"
def _latex_(self):
"""
Return a latex representation of ``self``.
EXAMPLES::
sage: UnsignedInfinityRing(5)._latex_()
'(<\\infty)'
"""
return "(<\\infty)"
def _add_(self, other):
"""
EXAMPLES::
sage: UnsignedInfinityRing(5) + UnsignedInfinityRing(-3) # indirect doctest
A number less than infinity
sage: UnsignedInfinityRing(5) + unsigned_infinity
Infinity
"""
if isinstance(other, UnsignedInfinity):
return other
return self
def _sub_(self, other):
"""
EXAMPLES::
sage: UnsignedInfinityRing(5) - UnsignedInfinityRing(-3) # indirect doctest
A number less than infinity
sage: UnsignedInfinityRing(5) - unsigned_infinity
Infinity
"""
if isinstance(other, UnsignedInfinity):
return other
return self
def _mul_(self, other):
"""
EXAMPLES::
sage: UnsignedInfinityRing(4) * UnsignedInfinityRing(-3) # indirect doctest
A number less than infinity
sage: 5 * unsigned_infinity
Traceback (most recent call last):
...
ValueError: oo times number < oo not defined
sage: unsigned_infinity * unsigned_infinity
Infinity
"""
if isinstance(other, UnsignedInfinity):
raise ValueError("oo times number < oo not defined")
return self
def _div_(self, other):
"""
Can't eliminate possibility of zero division....
EXAMPLES::
sage: UnsignedInfinityRing(2) / UnsignedInfinityRing(5) # indirect doctest
Traceback (most recent call last):
...
ValueError: quotient of number < oo by number < oo not defined
sage: 1 / unsigned_infinity
0
"""
if isinstance(other, UnsignedInfinity):
return sage.rings.integer_ring.ZZ(0)
raise ValueError("quotient of number < oo by number < oo not defined")
def _richcmp_(self, other, op):
"""
Compare ``self`` to ``other``.
EXAMPLES::
sage: 1 == unsigned_infinity
False
"""
if isinstance(other, UnsignedInfinity):
return rich_to_bool(op, -1)
return rich_to_bool(op, 0)
def sign(self):
"""
Raise an error because the sign of self is not well defined.
EXAMPLES::
sage: sign(UnsignedInfinityRing(2))
Traceback (most recent call last):
...
NotImplementedError: sign of number < oo is not well defined
sage: sign(UnsignedInfinityRing(0))
Traceback (most recent call last):
...
NotImplementedError: sign of number < oo is not well defined
sage: sign(UnsignedInfinityRing(-2))
Traceback (most recent call last):
...
NotImplementedError: sign of number < oo is not well defined
"""
raise NotImplementedError("sign of number < oo is not well defined")
class UnsignedInfinity(_uniq, AnInfinity, InfinityElement):
_sign = 0
_sign_char = ''
def __init__(self):
"""
Initialize ``self``.
TESTS::
sage: sage.rings.infinity.UnsignedInfinity() is sage.rings.infinity.UnsignedInfinity() is unsigned_infinity
True
"""
InfinityElement.__init__(self, UnsignedInfinityRing)
def __hash__(self):
r"""
TESTS::
sage: hash(unsigned_infinity)
9223372036854775806 # 64-bit
2147483646 # 32-bit
"""
return maxsize-1
def _mul_(self, other):
"""
Can't rule out an attempt at multiplication by 0.
EXAMPLES::
sage: unsigned_infinity * unsigned_infinity # indirect doctest
Infinity
sage: unsigned_infinity * 0
Traceback (most recent call last):
...
ValueError: unsigned oo times smaller number not defined
sage: unsigned_infinity * 3
Traceback (most recent call last):
...
ValueError: unsigned oo times smaller number not defined
"""
if isinstance(other, UnsignedInfinity):
return self
raise ValueError("unsigned oo times smaller number not defined")
def _sympy_(self):
"""
Converts ``unsigned_infinity`` to sympy ``zoo``.
EXAMPLES::
sage: import sympy
sage: SR(unsigned_infinity)._sympy_()
zoo
sage: gamma(-3)._sympy_() is sympy.factorial(-2)
True
sage: gamma(-3) is sympy.factorial(-2)._sage_()
True
"""
import sympy
return sympy.zoo
def _richcmp_(self, other, op):
"""
Compare ``self`` to ``other``.
EXAMPLES::
sage: 1 == unsigned_infinity
False
"""
if isinstance(other, LessThanInfinity):
return rich_to_bool(op, 1)
return rich_to_bool(op, 0)
unsigned_infinity = UnsignedInfinityRing.gen(0)
less_than_infinity = UnsignedInfinityRing.less_than_infinity()
def is_Infinite(x):
"""
This is a type check for infinity elements.
EXAMPLES::
sage: sage.rings.infinity.is_Infinite(oo)
True
sage: sage.rings.infinity.is_Infinite(-oo)
True
sage: sage.rings.infinity.is_Infinite(unsigned_infinity)
True
sage: sage.rings.infinity.is_Infinite(3)
False
sage: sage.rings.infinity.is_Infinite(RR(infinity))
False
sage: sage.rings.infinity.is_Infinite(ZZ)
False
"""
return isinstance(x, InfinityElement)
class SignError(ArithmeticError):
"""
Sign error exception.
"""
pass
class InfinityRing_class(Singleton, Ring):
def __init__(self):
"""
Initialize ``self``.
TESTS::
sage: sage.rings.infinity.InfinityRing_class() is sage.rings.infinity.InfinityRing_class() is InfinityRing
True
Comparison tests::
sage: InfinityRing == InfinityRing
True
sage: InfinityRing == UnsignedInfinityRing
False
"""
Ring.__init__(self, self, names=('oo',), normalize=False)
def fraction_field(self):
"""
This isn't really a ring, let alone an integral domain.
TESTS::
sage: InfinityRing.fraction_field()
Traceback (most recent call last):
...
TypeError: infinity 'ring' has no fraction field
"""
raise TypeError("infinity 'ring' has no fraction field")
def ngens(self):
"""
The two generators are plus and minus infinity.
EXAMPLES::
sage: InfinityRing.ngens()
2
sage: len(InfinityRing.gens())
2
"""
return 2
def gen(self, n=0):
"""
The two generators are plus and minus infinity.
EXAMPLES::
sage: InfinityRing.gen(0)
+Infinity
sage: InfinityRing.gen(1)
-Infinity
sage: InfinityRing.gen(2)
Traceback (most recent call last):
...
IndexError: n must be 0 or 1
"""
try:
if n == 0:
return self._gen0
elif n == 1:
return self._gen1
else:
raise IndexError("n must be 0 or 1")
except AttributeError:
if n == 0:
self._gen0 = PlusInfinity()
return self._gen0
elif n == 1:
self._gen1 = MinusInfinity()
return self._gen1
def gens(self):
"""
The two generators are plus and minus infinity.
EXAMPLES::
sage: InfinityRing.gens()
[+Infinity, -Infinity]
"""
return [self.gen(0), self.gen(1)]
def is_zero(self):
"""
The Infinity Ring is not zero
EXAMPLES::
sage: InfinityRing.is_zero()
False
"""
return False
def is_commutative(self):
"""
The Infinity Ring is commutative
EXAMPLES::
sage: InfinityRing.is_commutative()
True
"""
return True
def _repr_(self):
"""
Return a string representation of ``self``.
TESTS::
sage: InfinityRing._repr_()
'The Infinity Ring'
"""
return "The Infinity Ring"
def _element_constructor_(self, x):
"""
The element constructor
TESTS::
sage: InfinityRing(-oo) # indirect doctest
-Infinity
sage: InfinityRing(3)
A positive finite number
sage: InfinityRing(-1.5)
A negative finite number
sage: [InfinityRing(a) for a in [-2..2]]
[A negative finite number, A negative finite number, Zero, A positive finite number, A positive finite number]
sage: K.<a> = QuadraticField(3)
sage: InfinityRing(a)
A positive finite number
sage: InfinityRing(a - 2)
A negative finite number
sage: InfinityRing(RDF(oo)), InfinityRing(RDF(-oo))
(+Infinity, -Infinity)
sage: InfinityRing(RR(oo)), InfinityRing(RR(-oo))
(+Infinity, -Infinity)
sage: InfinityRing(RIF(oo)), InfinityRing(RIF(-oo))
(+Infinity, -Infinity)
sage: InfinityRing(float('+inf')), InfinityRing(float('-inf'))
(+Infinity, -Infinity)
sage: InfinityRing(SR(oo)), InfinityRing(SR(-oo))
(+Infinity, -Infinity)
The following rings have ``is_positive_infinity`` /
``is_negative_infinity`` methods::
sage: RR(oo).is_positive_infinity(), RR(-oo).is_negative_infinity()
(True, True)
sage: SR(oo).is_positive_infinity(), SR(-oo).is_negative_infinity()
(True, True)
Complex infinity raises an exception. This is fine (there is
no coercion, so there is no promise of functoriality)::
sage: i_infinity = CC(0, oo)
sage: InfinityRing(CC(oo)), InfinityRing(CC(-oo))
(+Infinity, -Infinity)
sage: InfinityRing(i_infinity)
Traceback (most recent call last):
...
ValueError: infinite but not with +/- phase
sage: InfinityRing(CDF(oo)), InfinityRing(CDF(-oo))
(+Infinity, -Infinity)
sage: InfinityRing(CDF(i_infinity))
Traceback (most recent call last):
...
ValueError: infinite but not with +/- phase
"""
# Lazy elements can wrap infinity or not, unwrap first
try:
from sage.rings.real_lazy import LazyWrapper
except ImportError:
pass
else:
if isinstance(x, LazyWrapper):
x = x._value
# Handle all ways to represent infinity first
if isinstance(x, InfinityElement):
if x < 0:
return self.gen(1)
else:
return self.gen(0)
elif isinstance(x, float):
if x == float('+inf'):
return self.gen(0)
if x == float('-inf'):
return self.gen(1)
elif isinstance(x, RingElement) and isinstance(x.parent(), sage.rings.abc.RealIntervalField):
if x.upper().is_positive_infinity():
return self.gen(0)
if x.lower().is_negative_infinity():
return self.gen(1)
else:
try:
# For example, RealField() implements this
if x.is_positive_infinity():
return self.gen(0)
if x.is_negative_infinity():
return self.gen(1)
if x.is_infinity():
raise ValueError('infinite but not with +/- phase')
except AttributeError:
pass
# If we got here then x is not infinite
c = int(bool(x > 0)) - int(bool(x < 0))
return FiniteNumber(self, c)
def _coerce_map_from_(self, R):
r"""
There is a coercion from anything that has a coercion into the reals.
The way Sage works is that everything that should be
comparable with infinity can be coerced into the infinity
ring, so if you ever compare with infinity the comparison is
done there. If you don't have a coercion then you will get
undesirable answers from the fallback comparison (likely
memory location).
EXAMPLES::
sage: InfinityRing.has_coerce_map_from(int) # indirect doctest
True
sage: InfinityRing.has_coerce_map_from(AA)
True
sage: InfinityRing.has_coerce_map_from(RDF)
True
sage: InfinityRing.has_coerce_map_from(RIF)
True
As explained above, comparison works by coercing to the
infinity ring::
sage: cm = get_coercion_model()
sage: cm.explain(AA(3), oo, operator.lt)
Coercion on left operand via
Coercion map:
From: Algebraic Real Field
To: The Infinity Ring
Arithmetic performed after coercions.
Result lives in The Infinity Ring
The Infinity Ring
The symbolic ring does not coerce to the infinity ring, so
symbolic comparisons with infinities all happen in the
symbolic ring::
sage: SR.has_coerce_map_from(InfinityRing)
True
sage: InfinityRing.has_coerce_map_from(SR)
False
Complex numbers do not coerce into the infinity ring (what
would `i \infty` coerce to?). This is fine since they can not
be compared, so we do not have to enforce consistency when
comparing with infinity either::
sage: InfinityRing.has_coerce_map_from(CDF)
False
sage: InfinityRing.has_coerce_map_from(CC)
False
sage: CC(0, oo) < CC(1) # does not coerce to infinity ring
True
"""
from sage.structure.coerce import parent_is_real_numerical
if parent_is_real_numerical(R):
return True
if isinstance(R, (sage.rings.abc.RealIntervalField, sage.rings.abc.RealBallField)):
return True
return False
def _pushout_(self, other):
r"""
EXAMPLES::
sage: QQbar(-2*i)*infinity
(-I)*Infinity
"""
from sage.symbolic.ring import SR
if SR.has_coerce_map_from(other):
return SR
class FiniteNumber(RingElement):
def __init__(self, parent, x):
"""
Initialize ``self``.
TESTS::
sage: sage.rings.infinity.FiniteNumber(InfinityRing, 1)
A positive finite number
sage: sage.rings.infinity.FiniteNumber(InfinityRing, -1)
A negative finite number
sage: sage.rings.infinity.FiniteNumber(InfinityRing, 0)
Zero
"""
RingElement.__init__(self, parent)
self.value = x
def _richcmp_(self, other, op):
"""
Compare ``self`` and ``other``.
EXAMPLES::
sage: P = InfinityRing
sage: -oo < P(-5) < P(0) < P(1.5) < oo
True
sage: P(1) < P(100)
False
sage: P(-1) == P(-100)
True
"""
if isinstance(other, PlusInfinity):
return rich_to_bool(op, -1)
if isinstance(other, MinusInfinity):
return rich_to_bool(op, 1)
return richcmp(self.value, other.value, op)
def _add_(self, other):
"""
EXAMPLES::
sage: P = InfinityRing
sage: 4 + oo # indirect doctest
+Infinity
sage: P(4) + P(2)
A positive finite number
sage: P(-1) + P(1)
Traceback (most recent call last):
...
SignError: cannot add positive finite value to negative finite value
Subtraction is implemented by adding the negative::
sage: P = InfinityRing
sage: 4 - oo # indirect doctest
-Infinity
sage: 5 - -oo
+Infinity
sage: P(44) - P(4)
Traceback (most recent call last):
...
SignError: cannot add positive finite value to negative finite value
sage: P(44) - P(-1)
A positive finite number
TESTS:
Check that :trac:`34231` is fixed::
sage: R = InfinityRing
sage: all(R(0) + x == x + R(0) == x for x in [-oo, R(-1), R(0), R(1), oo])
True
"""
if isinstance(other, InfinityElement):
return other
if self.value * other.value < 0:
raise SignError("cannot add positive finite value to negative finite value")
return FiniteNumber(self.parent(), self.value + other.value)
def _mul_(self, other):
"""
EXAMPLES::
sage: P = InfinityRing
sage: 0 * oo # indirect doctest
Traceback (most recent call last):
...
SignError: cannot multiply infinity by zero
sage: -1 * oo
-Infinity
sage: -2 * oo
-Infinity
sage: 3 * oo
+Infinity
sage: -oo * oo
-Infinity
sage: P(0) * 3
0
sage: P(-3) * P(2/3)
A negative finite number
"""
if other.is_zero():
if isinstance(self, InfinityElement):
raise SignError("cannot multiply infinity by zero")
return sage.rings.integer_ring.ZZ(0)
if self.value < 0:
if isinstance(other, InfinityElement):
return -other
return FiniteNumber(self.parent(), self.value * other.value)
if self.value > 0:
if isinstance(other, InfinityElement):
return other
return FiniteNumber(self.parent(), self.value * other.value)
if self.value == 0:
if isinstance(other, InfinityElement):
raise SignError("cannot multiply infinity by zero")
return sage.rings.integer_ring.ZZ(0)
def _div_(self, other):
"""
EXAMPLES::
sage: P = InfinityRing
sage: 1 / oo # indirect doctest
0
sage: oo / 4
+Infinity
sage: oo / -4
-Infinity
sage: P(1) / P(-4)
A negative finite number
"""
return self * ~other
def __invert__(self):
"""
EXAMPLES::
sage: P = InfinityRing
sage: ~P(2)
A positive finite number
sage: ~P(-7)
A negative finite number
sage: ~P(0)
Traceback (most recent call last):
...
ZeroDivisionError: Cannot divide by zero
"""
if self.value == 0:
raise ZeroDivisionError("Cannot divide by zero")
return self
def _neg_(self):
"""
EXAMPLES::
sage: a = InfinityRing(5); a
A positive finite number
sage: -a # indirect doctest
A negative finite number
sage: -(-a) == a
True
sage: -InfinityRing(0)
Zero
"""
return FiniteNumber(self.parent(), -self.value)
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: InfinityRing(-2)._repr_()
'A negative finite number'
sage: InfinityRing(7)._repr_()
'A positive finite number'
sage: InfinityRing(0)._repr_()
'Zero'
"""
if self.value < 0:
return "A negative finite number"
if self.value > 0:
return "A positive finite number"
return "Zero"
def _latex_(self):
"""
Return a latex representation of ``self``.
TESTS::
sage: a = InfinityRing(pi); a
A positive finite number
sage: a._latex_()
'A positive finite number'
sage: [latex(InfinityRing(a)) for a in [-2..2]]
[A negative finite number, A negative finite number, Zero, A positive finite number, A positive finite number]
"""
return self._repr_()
def __abs__(self):
"""
EXAMPLES::
sage: abs(InfinityRing(-3))
A positive finite number
sage: abs(InfinityRing(3))
A positive finite number
sage: abs(InfinityRing(0))
Zero
"""
if self.value == 0:
return FiniteNumber(self.parent(), 0)
return FiniteNumber(self.parent(), 1)
def sign(self):
"""
Return the sign of self.
EXAMPLES::
sage: sign(InfinityRing(2))
1
sage: sign(InfinityRing(0))
0
sage: sign(InfinityRing(-2))
-1
TESTS::
sage: sgn(InfinityRing(7))
1
sage: sgn(InfinityRing(0))
0
sage: sgn(InfinityRing(-7))
-1
"""
if self.value == 0:
return 0
if self.value > 0:
return 1
return -1
def sqrt(self):
"""
EXAMPLES::
sage: InfinityRing(7).sqrt()
A positive finite number
sage: InfinityRing(0).sqrt()
Zero
sage: InfinityRing(-.001).sqrt()
Traceback (most recent call last):
...
SignError: cannot take square root of a negative number
"""
if self.value < 0:
raise SignError("cannot take square root of a negative number")
return self
class MinusInfinity(_uniq, AnInfinity, InfinityElement):
_sign = -1
_sign_char = '-'
def __init__(self):
"""
Initialize ``self``.
TESTS::
sage: sage.rings.infinity.MinusInfinity() is sage.rings.infinity.MinusInfinity() is -oo
True
"""
InfinityElement.__init__(self, InfinityRing)
def __hash__(self):
r"""
TESTS::
sage: hash(-infinity)
-9223372036854775808 # 64-bit
-2147483648 # 32-bit
"""
return ~maxsize
def _richcmp_(self, other, op):
"""
Compare ``self`` and ``other``.
EXAMPLES::
sage: P = InfinityRing
sage: -oo < P(-5) < P(0) < P(1.5) < oo
True
sage: P(1) < P(100)
False
sage: P(-1) == P(-100)
True
"""
if isinstance(other, MinusInfinity):
return rich_to_bool(op, 0)
return rich_to_bool(op, -1)
def _neg_(self):
"""
EXAMPLES::
sage: -(-oo) # indirect doctest
+Infinity
"""
return self.parent().gen(0)
def sqrt(self):
"""
EXAMPLES::
sage: (-oo).sqrt()
Traceback (most recent call last):
...
SignError: cannot take square root of negative infinity
"""
raise SignError("cannot take square root of negative infinity")
def _sympy_(self):
"""
Converts ``-oo`` to sympy ``-oo``.
Then you don't have to worry which ``oo`` you use, like in these
examples:
EXAMPLES::
sage: import sympy
sage: bool(-oo == -sympy.oo)
True
sage: bool(SR(-oo) == -sympy.oo)
True
sage: bool((-oo)._sympy_() == -sympy.oo)
True
"""
import sympy
return -sympy.oo
def _gap_init_(self):
r"""
Conversion to gap and libgap.
EXAMPLES::
sage: gap(-Infinity)
-infinity
sage: libgap(-Infinity)
-infinity
"""
return '-infinity'
class PlusInfinity(_uniq, AnInfinity, InfinityElement):
_sign = 1
_sign_char = '+'
def __init__(self):
"""
Initialize ``self``.
TESTS::
sage: sage.rings.infinity.PlusInfinity() is sage.rings.infinity.PlusInfinity() is oo
True
"""
InfinityElement.__init__(self, InfinityRing)
def __hash__(self):
r"""
TESTS::
sage: hash(+infinity)
9223372036854775807 # 64-bit
2147483647 # 32-bit
"""
return maxsize
def _richcmp_(self, other, op):
"""
Compare ``self`` and ``other``.
EXAMPLES::
sage: P = InfinityRing
sage: -oo < P(-5) < P(0) < P(1.5) < oo
True
sage: P(1) < P(100)
False
sage: P(-1) == P(-100)
True
"""
if isinstance(other, PlusInfinity):
return rich_to_bool(op, 0)
return rich_to_bool(op, 1)
def _neg_(self):
"""
TESTS::
sage: -oo # indirect doctest
-Infinity
"""
return self.parent().gen(1)
def sqrt(self):
"""
The square root of ``self``.
The square root of infinity is infinity.
EXAMPLES::
sage: oo.sqrt()
+Infinity
"""
return self
def _sympy_(self):
"""
Converts ``oo`` to sympy ``oo``.
Then you don't have to worry which ``oo`` you use, like in these
examples:
EXAMPLES::
sage: import sympy
sage: bool(oo == sympy.oo) # indirect doctest
True
sage: bool(SR(oo) == sympy.oo)
True
"""
import sympy
return sympy.oo
def _gap_init_(self):
r"""
Conversion to gap and libgap.
EXAMPLES::
sage: gap(+Infinity)
infinity
sage: libgap(+Infinity)
infinity
"""
return 'infinity'
InfinityRing = InfinityRing_class()
infinity = InfinityRing.gen(0)
Infinity = infinity
minus_infinity = InfinityRing.gen(1)
def test_comparison(ring):
"""
Check comparison with infinity
INPUT:
- ``ring`` -- a sub-ring of the real numbers
OUTPUT:
Various attempts are made to generate elements of ``ring``. An
assertion is triggered if one of these elements does not compare
correctly with plus/minus infinity.
EXAMPLES::
sage: from sage.rings.infinity import test_comparison
sage: rings = [ZZ, QQ, RR, RealField(200), RDF, RLF, AA, RIF]
sage: for R in rings:
....: print('testing {}'.format(R))
....: test_comparison(R)
testing Integer Ring
testing Rational Field
testing Real Field with 53 bits of precision
testing Real Field with 200 bits of precision
testing Real Double Field
testing Real Lazy Field
testing Algebraic Real Field
testing Real Interval Field with 53 bits of precision
Comparison with number fields does not work::
sage: K.<sqrt3> = NumberField(x^2-3)
sage: (-oo < 1+sqrt3) and (1+sqrt3 < oo) # known bug
False
The symbolic ring handles its own infinities, but answers
``False`` (meaning: cannot decide) already for some very
elementary comparisons::
sage: test_comparison(SR) # known bug
Traceback (most recent call last):
...
AssertionError: testing -1000.0 in Symbolic Ring: id = ...
"""
from sage.symbolic.ring import SR
from sage.rings.rational_field import QQ
elements = [-1e3, 99.9999, -SR(2).sqrt(), 0, 1,
3 ** (-QQ.one()/3), SR.pi(), 100000]
elements.append(ring.an_element())
elements.extend(ring.some_elements())
for z in elements:
try:
z = ring(z)
except (ValueError, TypeError):
continue # ignore if z is not in ring
msg = 'testing {} in {}: id = {}, {}, {}'.format(z, ring, id(z), id(infinity), id(minus_infinity))
assert minus_infinity < z, msg
assert z > minus_infinity, msg
assert z < infinity, msg
assert infinity > z, msg
assert minus_infinity <= z, msg
assert z >= minus_infinity, msg
assert z <= infinity, msg
assert infinity >= z, msg
def test_signed_infinity(pos_inf):
"""
Test consistency of infinity representations.
There are different possible representations of infinity in
Sage. These are all consistent with the infinity ring, that is,
compare with infinity in the expected way. See also :trac:`14045`
INPUT:
- ``pos_inf`` -- a representation of positive infinity.
OUTPUT:
An assertion error is raised if the representation is not
consistent with the infinity ring.
Check that :trac:`14045` is fixed::
sage: InfinityRing(float('+inf'))
+Infinity
sage: InfinityRing(float('-inf'))
-Infinity
sage: oo > float('+inf')
False
sage: oo == float('+inf')
True
EXAMPLES::
sage: from sage.rings.infinity import test_signed_infinity
sage: for pos_inf in [oo, float('+inf'), RLF(oo), RIF(oo), SR(oo)]:
....: test_signed_infinity(pos_inf)
"""
msg = 'testing {} ({})'.format(pos_inf, type(pos_inf))
assert InfinityRing(pos_inf) is infinity, msg
assert InfinityRing(-pos_inf) is minus_infinity, msg
assert infinity == pos_inf, msg
assert not(infinity > pos_inf), msg
assert not(infinity < pos_inf), msg
assert minus_infinity == -pos_inf, msg
assert not(minus_infinity > -pos_inf), msg
assert not(minus_infinity < -pos_inf), msg
assert pos_inf > -pos_inf, msg
assert infinity > -pos_inf, msg
assert pos_inf > minus_infinity, msg | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/infinity.py | 0.866557 | 0.689175 | infinity.py | pypi |
from sage.misc.decorators import decorator_keywords, sage_wraps
@decorator_keywords
def handle_AA_and_QQbar(func):
r"""
Decorator to call a function that only accepts arguments in number fields.
The argument list is scanned for ideals and/or polynomials over algebraic
fields (``QQbar`` or ``AA``). If any exist, they are converted to a common
number field before calling the function, and the results are converted back.
Lists, dictionaries (values only), sets, and tuples are converted recursively.
This decorator can not used with methods that depend on factoring, since
factorization might require larger number fields than those required to
express the polynomials. No means is provided to check whether factoring
is being attempted by a wrapped method, and if a method invoked a library
or subprocess (like Singular), it's hard to imagine how such a check could
be performed.
See https://mathoverflow.net/questions/304525 for a discussion of why a
simple attempt to overcome this limitation didn't work.
"""
@sage_wraps(func)
def wrapper(*args, **kwds):
"""
TESTS::
sage: from sage.rings.qqbar_decorators import handle_AA_and_QQbar
sage: @handle_AA_and_QQbar
....: def return_base_ring(x):
....: return x.base_ring()
sage: P.<x> = QQbar[]
sage: return_base_ring(x)
Rational Field
sage: P.<y,z> = QQbar[]
sage: return_base_ring(y)
Rational Field
sage: return_base_ring(ideal(y,z))
Rational Field
Check that :trac:`29468` is fixed::
sage: J = QQbar['x,y'].ideal('x^2 - y')
sage: type(J.groebner_basis())
<class 'sage.rings.polynomial.multi_polynomial_sequence.PolynomialSequence_generic'>
sage: J.groebner_basis().is_immutable()
True
::
sage: @handle_AA_and_QQbar
....: def f(x):
....: print(x.ring().base_ring())
....: return x
sage: R.<x,y> = QQbar[]
sage: s = Sequence([x, R(sqrt(2)) * y], immutable=True)
sage: t = f(s)
Number Field in a with defining polynomial y^2 - 2
sage: t.ring().base_ring()
Algebraic Field
sage: t.is_immutable()
True
sage: s == t
True
"""
from sage.misc.flatten import flatten
from sage.rings.polynomial.polynomial_element import Polynomial
from sage.rings.polynomial.multi_polynomial import MPolynomial
from sage.rings.polynomial.multi_polynomial_sequence import PolynomialSequence, is_PolynomialSequence
from sage.rings.ideal import Ideal, Ideal_generic
from sage.rings.qqbar import AlgebraicField_common, number_field_elements_from_algebraics
if not any(isinstance(a, (Polynomial, MPolynomial, Ideal_generic))
and isinstance(a.base_ring(), AlgebraicField_common)
or is_PolynomialSequence(a)
and isinstance(a.ring().base_ring(), AlgebraicField_common) for a in args):
return func(*args, **kwds)
polynomials = []
for a in flatten(args, ltypes=(list, tuple, set)):
if isinstance(a, Ideal_generic):
polynomials.extend(a.gens())
elif isinstance(a, Polynomial):
polynomials.append(a)
elif isinstance(a, MPolynomial):
polynomials.append(a)
orig_elems = flatten([p.coefficients() for p in polynomials])
# We need minimal=True if these elements are over AA, because
# same_field=True might trigger an exception otherwise.
numfield, new_elems, morphism = number_field_elements_from_algebraics(orig_elems, same_field=True, minimal=True)
elem_dict = dict(zip(orig_elems, new_elems))
def forward_map(item):
if isinstance(item, Ideal_generic):
return Ideal([forward_map(g) for g in item.gens()])
elif isinstance(item, Polynomial):
return item.map_coefficients(elem_dict.__getitem__, new_base_ring=numfield)
elif isinstance(item, MPolynomial):
return item.map_coefficients(elem_dict.__getitem__, new_base_ring=numfield)
elif is_PolynomialSequence(item):
return PolynomialSequence(map(forward_map, item),
immutable=item.is_immutable())
elif isinstance(item, list):
return list(map(forward_map, item))
elif isinstance(item, dict):
return {k: forward_map(v) for k,v in item.items()}
elif isinstance(item, tuple):
return tuple(map(forward_map, item))
elif isinstance(item, set):
return set(map(forward_map, list(item)))
else:
return item
def reverse_map(item):
if isinstance(item, Ideal_generic):
return Ideal([reverse_map(g) for g in item.gens()])
elif isinstance(item, Polynomial):
return item.map_coefficients(morphism)
elif isinstance(item, MPolynomial):
return item.map_coefficients(morphism)
elif is_PolynomialSequence(item):
return PolynomialSequence(map(reverse_map, item),
immutable=item.is_immutable())
elif isinstance(item, list):
return list(map(reverse_map, item))
elif isinstance(item, tuple):
return tuple(map(reverse_map, item))
elif isinstance(item, set):
return set(map(reverse_map, list(item)))
else:
return item
args = forward_map(args)
kwds = forward_map(kwds)
return reverse_map(func(*args, **kwds))
return wrapper | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/qqbar_decorators.py | 0.939255 | 0.696532 | qqbar_decorators.py | pypi |
from sage.structure.parent import Parent
import sage.rings.integer_ring
from . import ideal
from sage.categories.monoids import Monoids
def IdealMonoid(R):
r"""
Return the monoid of ideals in the ring ``R``.
EXAMPLES::
sage: R = QQ['x']
sage: sage.rings.ideal_monoid.IdealMonoid(R)
Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
"""
return IdealMonoid_c(R)
class IdealMonoid_c(Parent):
r"""
The monoid of ideals in a commutative ring.
TESTS::
sage: R = QQ['x']
sage: M = sage.rings.ideal_monoid.IdealMonoid(R)
sage: TestSuite(M).run()
Failure in _test_category:
...
The following tests failed: _test_elements
(The "_test_category" test fails but I haven't the foggiest idea why.)
"""
Element = ideal.Ideal_generic # this doesn't seem to do anything
def __init__(self, R):
r"""
Initialize ``self``.
TESTS::
sage: R = QuadraticField(-23, 'a')
sage: M = sage.rings.ideal_monoid.IdealMonoid(R); M # indirect doctest
Monoid of ideals of Number Field in a with defining polynomial x^2 + 23 with a = 4.795831523312720?*I
sage: id = QQ.ideal(6)
sage: id.parent().category()
Category of commutative monoids
sage: MS = MatrixSpace(QQ,3,3)
sage: MS.ideal(MS.one()).parent().category()
Category of monoids
"""
self.__R = R
cat = Monoids()
if R.is_commutative():
cat = cat.Commutative()
Parent.__init__(self, base=sage.rings.integer_ring.ZZ,
category=cat)
self._populate_coercion_lists_()
def _repr_(self):
r"""
Return a string representation of ``self``.
TESTS::
sage: R = QuadraticField(-23, 'a')
sage: M = sage.rings.ideal_monoid.IdealMonoid(R); M._repr_()
'Monoid of ideals of Number Field in a with defining polynomial x^2 + 23 with a = 4.795831523312720?*I'
"""
return "Monoid of ideals of %s" % self.__R
def ring(self):
r"""
Return the ring of which this is the ideal monoid.
EXAMPLES::
sage: R = QuadraticField(-23, 'a')
sage: M = sage.rings.ideal_monoid.IdealMonoid(R); M.ring() is R
True
"""
return self.__R
def _element_constructor_(self, x):
r"""
Create an ideal in this monoid from ``x``.
EXAMPLES::
sage: R.<a> = QuadraticField(-23)
sage: M = sage.rings.ideal_monoid.IdealMonoid(R)
sage: M(a) # indirect doctest
Fractional ideal (a)
sage: M([a-4, 13])
Fractional ideal (13, 1/2*a + 9/2)
"""
try:
side = x.side()
except (AttributeError, TypeError):
side = None
try:
x = x.gens()
except AttributeError:
pass
if side is None:
y = self.__R.ideal(x)
else:
y = self.__R.ideal(x, side=side)
y._set_parent(self)
return y
def _coerce_map_from_(self, x):
r"""
Used by coercion framework.
EXAMPLES::
sage: R = QuadraticField(-23, 'a')
sage: M = R.ideal_monoid()
sage: M.has_coerce_map_from(R) # indirect doctest
True
sage: M.has_coerce_map_from(QQ.ideal_monoid())
True
sage: M.has_coerce_map_from(Zmod(6))
False
sage: M.has_coerce_map_from(loads(dumps(M)))
True
"""
if isinstance(x, IdealMonoid_c):
return self.ring().has_coerce_map_from(x.ring())
else:
return self.ring().has_coerce_map_from(x)
def __eq__(self, other):
r"""
Check whether ``self`` is not equal to ``other``.
EXAMPLES::
sage: R = QuadraticField(-23, 'a')
sage: M = R.ideal_monoid()
sage: M == QQ
False
sage: M == 17
False
sage: M == R.ideal_monoid()
True
"""
if not isinstance(other, IdealMonoid_c):
return False
else:
return self.ring() == other.ring()
def __ne__(self, other):
r"""
Check whether ``self`` is not equal to ``other``.
EXAMPLES::
sage: R = QuadraticField(-23, 'a')
sage: M = R.ideal_monoid()
sage: M != QQ
True
sage: M != 17
True
sage: M != R.ideal_monoid()
False
"""
return not (self == other)
def __hash__(self):
"""
Return the hash of ``self``.
EXAMPLES::
sage: R = QuadraticField(-23, 'a')
sage: M = R.ideal_monoid()
sage: hash(M) == hash(QQ)
False
sage: hash(M) == 17
False
sage: hash(M) == hash(R.ideal_monoid())
True
"""
# uses a random number, to have a distinct hash
return hash((1580963238588124931699, self.ring())) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/ideal_monoid.py | 0.872605 | 0.676206 | ideal_monoid.py | pypi |
r"""
Algebraic closures of finite fields
Let `\Bold{F}` be a finite field, and let `\overline{\Bold{F}}` be an
algebraic closure of `\Bold{F}`; this is unique up to (non-canonical)
isomorphism. For every `n\ge 1`, there is a unique subfield
`\Bold{F}_n` of `\overline{\Bold{F}}` such that
`\Bold{F}\subset\Bold{F}_n` and `[\Bold{F}_n:\Bold{F}]=n`.
In Sage, algebraic closures of finite fields are implemented using
compatible systems of finite fields. The resulting Sage object keeps
track of a finite lattice of the subfields `\Bold{F}_n` and the
embeddings between them. This lattice is extended as necessary.
The Sage class corresponding to `\overline{\Bold{F}}` can be
constructed from the finite field `\Bold{F}` by using the
:meth:`~sage.rings.finite_rings.finite_field_base.FiniteField.algebraic_closure`
method.
The Sage class for elements of `\overline{\Bold{F}}` is
:class:`AlgebraicClosureFiniteFieldElement`. Such an element is
represented as an element of one of the `\Bold{F}_n`. This means that
each element `x\in\Bold{F}` has infinitely many different
representations, one for each `n` such that `x` is in `\Bold{F}_n`.
.. NOTE::
Only prime finite fields are currently accepted as base fields for
algebraic closures. To obtain an algebraic closure of a non-prime
finite field `\Bold{F}`, take an algebraic closure of the prime
field of `\Bold{F}` and embed `\Bold{F}` into this.
Algebraic closures of finite fields are currently implemented
using (pseudo-)Conway polynomials; see
:class:`AlgebraicClosureFiniteField_pseudo_conway` and the module
:mod:`~sage.rings.finite_rings.conway_polynomials`. Other
implementations may be added by creating appropriate subclasses of
:class:`AlgebraicClosureFiniteField_generic`.
In the current implementation, algebraic closures do not satisfy
the unique parent condition. Moreover, there is no coercion map
between different algebraic closures of the same finite field.
There is a conceptual reason for this, namely that the definition
of pseudo-Conway polynomials only determines an algebraic closure
up to *non-unique* isomorphism. This means in particular that
different algebraic closures, and their respective elements, never
compare equal.
AUTHORS:
- Peter Bruin (August 2013): initial version
- Vincent Delecroix (November 2013): additional methods
"""
from sage.misc.abstract_method import abstract_method
from sage.misc.fast_methods import WithEqualityById
from sage.rings.finite_rings.element_base import is_FiniteFieldElement
from sage.rings.finite_rings.finite_field_base import is_FiniteField
from sage.rings.ring import Field
from sage.structure.element import FieldElement
from sage.structure.richcmp import richcmp
class AlgebraicClosureFiniteFieldElement(FieldElement):
"""
Element of an algebraic closure of a finite field.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F.gen(2)
z2
sage: type(F.gen(2))
<class 'sage.rings.algebraic_closure_finite_field.AlgebraicClosureFiniteField_pseudo_conway_with_category.element_class'>
"""
def __init__(self, parent, value):
"""
TESTS::
sage: F = GF(3).algebraic_closure()
sage: TestSuite(F.gen(2)).run(skip=['_test_pickling'])
.. NOTE::
The ``_test_pickling`` test has to be skipped because
there is no coercion map between the parents of ``x``
and ``loads(dumps(x))``.
"""
if is_FiniteFieldElement(value):
n = value.parent().degree()
else:
from sage.rings.integer import Integer
n = Integer(1)
self._value = parent._subfield(n).coerce(value)
self._level = n
FieldElement.__init__(self, parent)
def __hash__(self):
r"""
TESTS::
sage: F = GF(2).algebraic_closure()
sage: hash(F.zero())
0
sage: hash(F.one())
1
sage: z1 = F.gen(1)
sage: z2 = F.gen(2)
sage: z3 = F.gen(3)
sage: z4 = F.gen(4)
sage: hash(z2) == hash(z3+z2-z3)
True
sage: hash(F.zero()) == hash(z3+z2-z3-z2)
True
sage: X = [z4**i for i in range(2**4-1)]
sage: X.append(F.zero())
sage: X.extend([z3, z3**2, z3*z4])
sage: assert len(X) == len(set(hash(x) for x in X))
sage: F = GF(3).algebraic_closure()
sage: z1 = F.gen(1)
sage: z2 = F.gen(2)
sage: z3 = F.gen(3)
sage: z4 = F.gen(4)
sage: hash(z2) == hash(z3+z2-z3)
True
sage: X = [z4**i for i in range(3**4-1)]
sage: X.append(F.zero())
sage: X.extend([z3, z3**2, z3*z4])
sage: assert len(X) == len(set(hash(x) for x in X))
Check that :trac:`19956` is fixed::
sage: R.<x,y> = GF(2).algebraic_closure()[]
sage: x.resultant(y)
y
"""
# TODO: this is *very* slow
# NOTE: the hash of a generator (e.g. z2, z3, ...) is always the
# characteristic! In particular its hash value is not compatible with
# sections.
F, x, _ = self.as_finite_field_element(minimal=True)
if F.degree() == 1:
return hash(x)
else:
return hash((x, F.degree()))
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F._repr_()
'Algebraic closure of Finite Field of size 3'
"""
return self._value._repr_()
def _richcmp_(self, right, op):
"""
Compare ``self`` with ``right``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F.gen(2) == F.gen(3)
False
"""
x, y = self.parent()._to_common_subfield(self, right)
return richcmp(x, y, op)
def __pow__(self, exp):
r"""
TESTS::
sage: F2 = GF(2).algebraic_closure()
sage: z12 = F2.gen(3*4)
sage: z12**3
z12^3
sage: z12**13
z12^8 + z12^7 + z12^6 + z12^4 + z12^2 + z12
"""
return self.__class__(self.parent(), self._value ** exp)
def _add_(self, right):
"""
Return ``self`` + ``right``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F.gen(2) + F.gen(3)
z6^5 + 2*z6^4 + 2*z6^3 + z6^2 + 2*z6 + 1
"""
F = self.parent()
x, y = F._to_common_subfield(self, right)
return self.__class__(F, x + y)
def _sub_(self, right):
"""
Return ``self`` - ``right``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F.gen(2) - F.gen(3)
z6^4 + 2*z6^3 + z6^2 + 2*z6
"""
F = self.parent()
x, y = F._to_common_subfield(self, right)
return self.__class__(F, x - y)
def _mul_(self, right):
"""
Return ``self`` * ``right``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F.gen(2) * F.gen(3)
z6^5 + 2*z6^4 + z6^2 + 2
"""
F = self.parent()
x, y = F._to_common_subfield(self, right)
return self.__class__(F, x * y)
def _div_(self, right):
"""
Return ``self`` / ``right``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F.gen(2) / F.gen(3)
z6^5 + 2*z6^4 + z6^3 + 1
"""
F = self.parent()
x, y = F._to_common_subfield(self, right)
return self.__class__(F, x / y)
def change_level(self, n):
"""
Return a representation of ``self`` as an element of the
subfield of degree `n` of the parent, if possible.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: z = F.gen(4)
sage: (z^10).change_level(6)
2*z6^5 + 2*z6^3 + z6^2 + 2*z6 + 2
sage: z.change_level(6)
Traceback (most recent call last):
...
ValueError: z4 is not in the image of Ring morphism:
From: Finite Field in z2 of size 3^2
To: Finite Field in z4 of size 3^4
Defn: z2 |--> 2*z4^3 + 2*z4^2 + 1
sage: a = F(1).change_level(3); a
1
sage: a.change_level(2)
1
sage: F.gen(3).change_level(1)
Traceback (most recent call last):
...
ValueError: z3 is not in the image of Ring morphism:
From: Finite Field of size 3
To: Finite Field in z3 of size 3^3
Defn: 1 |--> 1
"""
F = self.parent()
l = self._level
m = l.gcd(n)
xl = self._value
xm = F.inclusion(m, l).section()(xl)
xn = F.inclusion(m, n)(xm)
return self.__class__(F, xn)
def _latex_(self):
"""
Return a LaTeX representation of ``self``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: s = F.gen(1) + F.gen(2) + F.gen(3)
sage: s
z6^5 + 2*z6^4 + 2*z6^3 + z6^2 + 2*z6 + 2
sage: latex(s)
z_{6}^{5} + 2 z_{6}^{4} + 2 z_{6}^{3} + z_{6}^{2} + 2 z_{6} + 2
"""
return self._value._latex_()
def minpoly(self):
"""
Return the minimal polynomial of ``self`` over the prime
field.
EXAMPLES::
sage: F = GF(11).algebraic_closure()
sage: F.gen(3).minpoly()
x^3 + 2*x + 9
"""
return self._value.minpoly()
minimal_polynomial = minpoly
def is_square(self):
"""
Return ``True`` if ``self`` is a square.
This always returns ``True``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F.gen(2).is_square()
True
"""
return True
def sqrt(self):
"""
Return a square root of ``self``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F.gen(2).sqrt()
z4^3 + z4 + 1
"""
F = self.parent()
x = self._value
if x.is_square():
return self.__class__(F, x.sqrt(extend=False))
else:
l = self._level
x = F.inclusion(l, 2*l)(x)
return self.__class__(F, x.sqrt(extend=False))
def nth_root(self, n):
"""
Return an `n`-th root of ``self``.
EXAMPLES::
sage: F = GF(5).algebraic_closure()
sage: t = F.gen(2) + 1
sage: s = t.nth_root(15); s
4*z6^5 + 3*z6^4 + 2*z6^3 + 2*z6^2 + 4
sage: s**15 == t
True
.. TODO::
This function could probably be made faster.
"""
from sage.rings.integer import Integer
F = self.parent()
x = self._value
n = Integer(n)
l = self._level
# In order to be smart we look for the smallest subfield that
# actually contains the root.
for d in n.divisors():
xx = F.inclusion(l, d*l)(x)
try:
y = xx.nth_root(n, extend=False)
except ValueError:
continue
return self.__class__(F, y)
raise AssertionError('cannot find n-th root in algebraic closure of finite field')
def multiplicative_order(self):
"""
Return the multiplicative order of ``self``.
EXAMPLES::
sage: K = GF(7).algebraic_closure()
sage: K.gen(5).multiplicative_order()
16806
sage: (K.gen(1) + K.gen(2) + K.gen(3)).multiplicative_order()
7353
"""
return self._value.multiplicative_order()
def pth_power(self, k=1):
"""
Return the `p^k`-th power of ``self``, where `p` is the
characteristic of ``self.parent()``.
EXAMPLES::
sage: K = GF(13).algebraic_closure('t')
sage: t3 = K.gen(3)
sage: s = 1 + t3 + t3**2
sage: s.pth_power()
10*t3^2 + 6*t3
sage: s.pth_power(2)
2*t3^2 + 6*t3 + 11
sage: s.pth_power(3)
t3^2 + t3 + 1
sage: s.pth_power(3).parent() is K
True
"""
return self.__class__(self.parent(), self._value.pth_power(k))
def pth_root(self, k=1):
"""
Return the unique `p^k`-th root of ``self``, where `p` is the
characteristic of ``self.parent()``.
EXAMPLES::
sage: K = GF(13).algebraic_closure('t')
sage: t3 = K.gen(3)
sage: s = 1 + t3 + t3**2
sage: s.pth_root()
2*t3^2 + 6*t3 + 11
sage: s.pth_root(2)
10*t3^2 + 6*t3
sage: s.pth_root(3)
t3^2 + t3 + 1
sage: s.pth_root(2).parent() is K
True
"""
return self.__class__(self.parent(), self._value.pth_root(k))
def as_finite_field_element(self, minimal=False):
"""
Return ``self`` as a finite field element.
INPUT:
- ``minimal`` -- boolean (default: ``False``). If ``True``,
always return the smallest subfield containing ``self``.
OUTPUT:
- a triple (``field``, ``element``, ``morphism``) where
``field`` is a finite field, ``element`` an element of
``field`` and ``morphism`` a morphism from ``field`` to
``self.parent()``.
EXAMPLES::
sage: F = GF(3).algebraic_closure('t')
sage: t = F.gen(5)
sage: t.as_finite_field_element()
(Finite Field in t5 of size 3^5,
t5,
Ring morphism:
From: Finite Field in t5 of size 3^5
To: Algebraic closure of Finite Field of size 3
Defn: t5 |--> t5)
By default, ``field`` is not necessarily minimal. We can
force it to be minimal using the ``minimal`` option::
sage: s = t + 1 - t
sage: s.as_finite_field_element()[0]
Finite Field in t5 of size 3^5
sage: s.as_finite_field_element(minimal=True)[0]
Finite Field of size 3
This also works when the element has to be converted between
two non-trivial finite subfields (see :trac:`16509`)::
sage: K = GF(5).algebraic_closure()
sage: z = K.gen(5) - K.gen(5) + K.gen(2)
sage: z.as_finite_field_element(minimal=True)
(Finite Field in z2 of size 5^2, z2, Ring morphism:
From: Finite Field in z2 of size 5^2
To: Algebraic closure of Finite Field of size 5
Defn: z2 |--> z2)
There are automatic coercions between the various
subfields::
sage: a = K.gen(2) + 1
sage: _,b,_ = a.as_finite_field_element()
sage: K4 = K.subfield(4)[0]
sage: K4(b)
z4^3 + z4^2 + z4 + 4
sage: b.minimal_polynomial() == K4(b).minimal_polynomial()
True
sage: K(K4(b)) == K(b)
True
You can also use the inclusions that are implemented at
the level of the algebraic closure::
sage: f = K.inclusion(2,4); f
Ring morphism:
From: Finite Field in z2 of size 5^2
To: Finite Field in z4 of size 5^4
Defn: z2 |--> z4^3 + z4^2 + z4 + 3
sage: f(b)
z4^3 + z4^2 + z4 + 4
"""
Fbar = self.parent()
x = self._value
l = self._level
if minimal:
m = x.minpoly().degree()
if m == 1:
x = Fbar.base_ring()(x)
else:
x = Fbar.inclusion(m, l).section()(x)
l = m
F, phi = Fbar.subfield(l)
return (F, x, phi)
class AlgebraicClosureFiniteField_generic(Field):
"""
Algebraic closure of a finite field.
TESTS::
sage: GF(3).algebraic_closure().cardinality()
+Infinity
sage: GF(3).algebraic_closure().is_finite()
False
"""
def __init__(self, base_ring, name, category=None):
"""
TESTS::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField_generic
sage: F = AlgebraicClosureFiniteField_generic(GF(5), 'z')
sage: F
Algebraic closure of Finite Field of size 5
"""
Field.__init__(self, base_ring=base_ring, names=name,
normalize=False, category=category)
def __eq__(self, other):
"""
Compare ``self`` with ``other``.
TESTS::
sage: F3 = GF(3).algebraic_closure()
sage: F3 == F3
True
sage: F5 = GF(5).algebraic_closure()
sage: F3 == F5
False
"""
if self is other:
return True
if type(self) != type(other):
return False
return ((self.base_ring(), self.variable_name(), self.category()) ==
(other.base_ring(), other.variable_name(), other.category()))
def __ne__(self, other):
"""
Check whether ``self`` and ``other`` are not equal.
TESTS::
sage: F3 = GF(3).algebraic_closure()
sage: F3 != F3
False
sage: F5 = GF(5).algebraic_closure()
sage: F3 != F5
True
"""
return not (self == other)
def characteristic(self):
"""
Return the characteristic of ``self``.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField
sage: p = next_prime(1000)
sage: F = AlgebraicClosureFiniteField(GF(p), 'z')
sage: F.characteristic() == p
True
"""
return self.base_ring().characteristic()
Element = AlgebraicClosureFiniteFieldElement
def _element_constructor_(self, x):
"""
Construct an element of ``self``.
TESTS::
sage: F = GF(5).algebraic_closure()
sage: type(F(3))
<class 'sage.rings.algebraic_closure_finite_field.AlgebraicClosureFiniteField_pseudo_conway_with_category.element_class'>
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField
sage: F1 = AlgebraicClosureFiniteField(GF(3), 'z')
sage: F2 = AlgebraicClosureFiniteField(GF(3), 'z')
sage: F1(F2.gen(1))
Traceback (most recent call last):
...
ValueError: no conversion defined between different algebraic closures
"""
if isinstance(x, self.element_class):
if x.parent() is not self:
raise ValueError('no conversion defined between different algebraic closures')
return x
else:
return self.element_class(self, x)
def _coerce_map_from_(self, other):
"""
Return ``True`` if elements of ``other`` can be coerced into
``self``.
EXAMPLES::
sage: F = GF(7).algebraic_closure()
sage: F.has_coerce_map_from(Integers())
True
"""
if other is self:
return True
elif is_FiniteField(other) and self._subfield(other.degree()) is other:
return True
elif self._subfield(1).has_coerce_map_from(other):
return True
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField
sage: F = AlgebraicClosureFiniteField(GF(5), 'z')
sage: F._repr_()
'Algebraic closure of Finite Field of size 5'
"""
return 'Algebraic closure of %s' % self.base_ring()
def _latex_(self):
r"""
Return a LaTeX representation of ``self``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: latex(F)
\overline{\Bold{F}_{3}}
"""
return "\\overline{{{}}}".format(self.base_ring()._latex_())
def _to_common_subfield(self, x, y):
"""
Coerce `x` and `y` to a common subfield of ``self``.
TESTS::
sage: F = GF(3).algebraic_closure()
sage: x, y = F._to_common_subfield(F.gen(2), F.gen(3))
sage: x.parent()
Finite Field in z6 of size 3^6
sage: y.parent()
Finite Field in z6 of size 3^6
"""
if x._level == y._level:
return x._value, y._value
n = x._level.lcm(y._level)
mx = self.inclusion(x._level, n)
my = self.inclusion(y._level, n)
return mx(x._value), my(y._value)
@abstract_method
def _get_polynomial(self, n):
"""
Return the polynomial defining the unique subfield of degree
`n` of ``self``.
This must be implemented by subclasses.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField_generic
sage: F = AlgebraicClosureFiniteField_generic(GF(5), 'z')
sage: F._get_polynomial(1)
Traceback (most recent call last):
...
NotImplementedError: <abstract method _get_polynomial at ...>
"""
@abstract_method
def _get_im_gen(self, m, n):
"""
Return the image of ``self.gen(m)`` under the canonical
inclusion into ``self.subfield(n)``.
This must be implemented by subclasses.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField_generic
sage: F = AlgebraicClosureFiniteField_generic(GF(5), 'z')
sage: F._get_im_gen(2, 4)
Traceback (most recent call last):
...
NotImplementedError: <abstract method _get_im_gen at ...>
"""
def _subfield(self, n):
"""
Return the unique subfield of degree `n` of ``self``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F._subfield(4)
Finite Field in z4 of size 3^4
"""
if n == 1:
return self.base_ring()
else:
from sage.rings.finite_rings.finite_field_constructor import FiniteField
return FiniteField(self.base_ring().cardinality() ** n,
name=self.variable_name() + str(n),
prefix=self.variable_name(),
modulus=self._get_polynomial(n),
check_irreducible=False)
def subfield(self, n):
"""
Return the unique subfield of degree `n` of ``self``
together with its canonical embedding into ``self``.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F.subfield(1)
(Finite Field of size 3,
Ring morphism:
From: Finite Field of size 3
To: Algebraic closure of Finite Field of size 3
Defn: 1 |--> 1)
sage: F.subfield(4)
(Finite Field in z4 of size 3^4,
Ring morphism:
From: Finite Field in z4 of size 3^4
To: Algebraic closure of Finite Field of size 3
Defn: z4 |--> z4)
"""
Fn = self._subfield(n)
return Fn, Fn.hom( (self.gen(n),), check=False)
def inclusion(self, m, n):
"""
Return the canonical inclusion map from the subfield
of degree `m` to the subfield of degree `n`.
EXAMPLES::
sage: F = GF(3).algebraic_closure()
sage: F.inclusion(1, 2)
Ring morphism:
From: Finite Field of size 3
To: Finite Field in z2 of size 3^2
Defn: 1 |--> 1
sage: F.inclusion(2, 4)
Ring morphism:
From: Finite Field in z2 of size 3^2
To: Finite Field in z4 of size 3^4
Defn: z2 |--> 2*z4^3 + 2*z4^2 + 1
"""
if m.divides(n):
# check=False is required to avoid "coercion hell": an
# infinite loop in checking the morphism involving
# polynomial_compiled.pyx on the modulus().
return self._subfield(m).hom( (self._get_im_gen(m, n),), check=False)
else:
raise ValueError("subfield of degree %s not contained in subfield of degree %s" % (m, n))
def ngens(self):
"""
Return the number of generators of ``self``, which is
infinity.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField
sage: AlgebraicClosureFiniteField(GF(5), 'z').ngens()
+Infinity
"""
from sage.rings.infinity import Infinity
return Infinity
def gen(self, n):
"""
Return the `n`-th generator of ``self``.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField
sage: F = AlgebraicClosureFiniteField(GF(5), 'z')
sage: F.gen(2)
z2
"""
F = self._subfield(n)
return self(F.gen())
def gens(self):
"""
Return a family of generators of ``self``.
OUTPUT:
- a :class:`~sage.sets.family.Family`, indexed by the positive
integers, whose `n`-th element is ``self.gen(n)``.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField
sage: F = AlgebraicClosureFiniteField(GF(5), 'z')
sage: g = F.gens(); g
Lazy family (...(i))_{i in Positive integers}
sage: g[3]
z3
"""
from sage.sets.family import Family
from sage.sets.positive_integers import PositiveIntegers
return Family(PositiveIntegers(), self.gen)
def _first_ngens(self, n):
"""
Return the first `n` generators of ``self``.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField
sage: F = AlgebraicClosureFiniteField(GF(5), 'z')
sage: F._first_ngens(3)
(1, z2, z3)
"""
return tuple(self.gen(i + 1) for i in range(n))
def algebraic_closure(self):
"""
Return an algebraic closure of ``self``.
This always returns ``self``.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField
sage: F = AlgebraicClosureFiniteField(GF(5), 'z')
sage: F.algebraic_closure() is F
True
"""
return self
def _an_element_(self):
"""
TESTS::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField
sage: F = AlgebraicClosureFiniteField(GF(5), 'w')
sage: F.an_element() # indirect doctest
w2
"""
return self.gen(2)
def some_elements(self):
r"""
Return some elements of this field.
EXAMPLES::
sage: F = GF(7).algebraic_closure()
sage: F.some_elements()
(1, z2, z3 + 1)
"""
return (self(1), self.gen(2), 1+self.gen(3))
def _roots_univariate_polynomial(self, p, ring=None, multiplicities=None, algorithm=None):
r"""
Return a list of pairs ``(root,multiplicity)`` of roots of the polynomial ``p``.
If the argument ``multiplicities`` is set to ``False`` then return the
list of roots.
.. SEEALSO::
:meth:`_factor_univariate_polynomial`
EXAMPLES::
sage: R.<x> = PolynomialRing(GF(5),'x')
sage: K = GF(5).algebraic_closure('t')
sage: sorted((x^6 - 1).roots(K,multiplicities=False))
[1, 4, 2*t2 + 1, 2*t2 + 2, 3*t2 + 3, 3*t2 + 4]
sage: ((K.gen(2)*x - K.gen(3))**2).roots(K)
[(3*t6^5 + 2*t6^4 + 2*t6^2 + 3, 2)]
sage: for _ in range(10):
....: p = R.random_element(degree=randint(2,8))
....: for r in p.roots(K, multiplicities=False):
....: assert p(r).is_zero(), "r={} is not a root of p={}".format(r,p)
"""
from sage.arith.functions import lcm
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
# first build a polynomial over some finite field
coeffs = [v.as_finite_field_element(minimal=True) for v in p.list()]
l = lcm([c[0].degree() for c in coeffs])
F, phi = self.subfield(l)
P = p.parent().change_ring(F)
new_coeffs = [self.inclusion(c[0].degree(), l)(c[1]) for c in coeffs]
polys = [(g,m,l,phi) for g,m in P(new_coeffs).factor()]
roots = [] # a list of pair (root,multiplicity)
while polys:
g,m,l,phi = polys.pop()
if g.degree() == 1: # found a root
r = phi(-g.constant_coefficient())
roots.append((r,m))
else: # look at the extension of degree g.degree() which contains at
# least one root of g
ll = l * g.degree()
psi = self.inclusion(l, ll)
FF, pphi = self.subfield(ll)
# note: there is no coercion from the l-th subfield to the ll-th
# subfield. The line below does the conversion manually.
g = PolynomialRing(FF, 'x')([psi(_) for _ in g])
polys.extend((gg,m,ll,pphi) for gg,_ in g.factor())
if multiplicities:
return roots
else:
return [r[0] for r in roots]
def _factor_univariate_polynomial(self, p, **kwds):
r"""
Factorization of univariate polynomials.
EXAMPLES::
sage: K = GF(3).algebraic_closure()
sage: R = PolynomialRing(K, 'T')
sage: T = R.gen()
sage: (K.gen(2) * T^2 - 1).factor()
(z2) * (T + z4^3 + z4^2 + z4) * (T + 2*z4^3 + 2*z4^2 + 2*z4)
sage: for d in range(10):
....: p = R.random_element(degree=randint(2,8))
....: assert p.factor().prod() == p, "error in the factorization of p={}".format(p)
"""
from sage.structure.factorization import Factorization
R = p.parent()
return Factorization([(R([-root, self.one()]), m) for root, m in p.roots()], unit=p[p.degree()])
class AlgebraicClosureFiniteField_pseudo_conway(WithEqualityById, AlgebraicClosureFiniteField_generic):
"""
Algebraic closure of a finite field, constructed using
pseudo-Conway polynomials.
EXAMPLES::
sage: F = GF(5).algebraic_closure(implementation='pseudo_conway')
sage: F.cardinality()
+Infinity
sage: F.algebraic_closure() is F
True
sage: x = F(3).nth_root(12); x
z4^3 + z4^2 + 4*z4
sage: x**12
3
TESTS::
sage: F3 = GF(3).algebraic_closure()
sage: F3 == F3
True
sage: F5 = GF(5).algebraic_closure()
sage: F3 == F5
False
"""
def __init__(self, base_ring, name, category=None, lattice=None, use_database=True):
"""
INPUT:
- ``base_ring`` -- the finite field of which to construct an
algebraic closure. Currently only prime fields are
accepted.
- ``name`` -- prefix to use for generators of the finite
subfields.
- ``category`` -- if provided, specifies the category in which
this algebraic closure will be placed.
- ``lattice`` -- :class:`~sage.rings.finite_rings.conway_polynomials.PseudoConwayPolynomialLattice`
(default: None). If provided, use this pseudo-Conway
polynomial lattice to construct an algebraic closure.
- ``use_database`` -- boolean. If True (default), use actual
Conway polynomials whenever they are available in the
database. If False, always compute pseudo-Conway
polynomials from scratch.
TESTS::
sage: F = GF(5).algebraic_closure(implementation='pseudo_conway')
sage: print(F.__class__.__name__)
AlgebraicClosureFiniteField_pseudo_conway_with_category
sage: TestSuite(F).run(skip=['_test_elements', '_test_pickling'])
sage: from sage.rings.finite_rings.conway_polynomials import PseudoConwayLattice
sage: L = PseudoConwayLattice(11, use_database=False)
sage: F = GF(7).algebraic_closure(lattice=L)
Traceback (most recent call last):
...
TypeError: lattice must be a pseudo-Conway lattice with characteristic 7
sage: F = GF(11).algebraic_closure(lattice=L)
sage: F.gen(2).minimal_polynomial()
x^2 + 4*x + 2
sage: F = GF(11).algebraic_closure(use_database=True)
sage: F.gen(2).minimal_polynomial()
x^2 + 7*x + 2
.. NOTE::
In the test suite, ``_test_pickling`` has to be skipped
because ``F`` and ``loads(dumps(F))`` cannot consistently
be made to compare equal, and ``_test_elements`` has to be
skipped for the reason described in
:meth:`AlgebraicClosureFiniteFieldElement.__init__`.
"""
if not (is_FiniteField(base_ring) and base_ring.is_prime_field()):
raise NotImplementedError('algebraic closures of finite fields are only implemented for prime fields')
from sage.rings.finite_rings.conway_polynomials import PseudoConwayLattice
p = base_ring.characteristic()
if lattice is None:
lattice = PseudoConwayLattice(p, use_database)
elif not isinstance(lattice, PseudoConwayLattice) or lattice.p != p:
raise TypeError('lattice must be a pseudo-Conway lattice with characteristic %s' % p)
self._pseudo_conway_lattice = lattice
AlgebraicClosureFiniteField_generic.__init__(self, base_ring, name, category)
def _get_polynomial(self, n):
"""
Return the defining polynomial of the unique subfield of
degree `n` of ``self``.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField_pseudo_conway
sage: F = AlgebraicClosureFiniteField_pseudo_conway(GF(5), 'z')
sage: F._get_polynomial(1)
x + 3
"""
return self._pseudo_conway_lattice.polynomial(n)
def _get_im_gen(self, m, n):
"""
Return the image of ``self.gen(m)`` under the canonical
inclusion into ``self.subfield(n)``.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField_pseudo_conway
sage: F = AlgebraicClosureFiniteField_pseudo_conway(GF(5), 'z')
sage: F._get_im_gen(2, 4)
z4^3 + z4^2 + z4 + 3
"""
p = self.characteristic()
if m == 1:
return self._subfield(n).one()
return self._subfield(n).gen() ** ((p**n - 1)//(p**m - 1))
def AlgebraicClosureFiniteField(base_ring, name, category=None, implementation=None, **kwds):
"""
Construct an algebraic closure of a finite field.
The recommended way to use this functionality is by calling the
:meth:`~sage.rings.finite_rings.finite_field_base.FiniteField.algebraic_closure`
method of the finite field.
.. NOTE::
Algebraic closures of finite fields in Sage do not have the
unique representation property, because they are not
determined up to unique isomorphism by their defining data.
EXAMPLES::
sage: from sage.rings.algebraic_closure_finite_field import AlgebraicClosureFiniteField
sage: F = GF(2).algebraic_closure()
sage: F1 = AlgebraicClosureFiniteField(GF(2), 'z')
sage: F1 is F
False
In the pseudo-Conway implementation, non-identical instances never
compare equal::
sage: F1 == F
False
sage: loads(dumps(F)) == F
False
This is to ensure that the result of comparing two instances
cannot change with time.
"""
if category is None:
from sage.categories.fields import Fields
category = Fields().Infinite()
if implementation is None:
implementation = 'pseudo_conway'
if implementation == 'pseudo_conway':
return AlgebraicClosureFiniteField_pseudo_conway(base_ring, name, category, **kwds)
else:
raise ValueError('unknown implementation for algebraic closure of finite field: %s'
% implementation) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/algebraic_closure_finite_field.py | 0.900312 | 0.815637 | algebraic_closure_finite_field.py | pypi |
import sage.libs.pari.all as pari
import sage.rings.ring as ring
from sage.structure.element import RingElement
from sage.structure.richcmp import richcmp
from sage.misc.fast_methods import Singleton
class Pari(RingElement):
"""
Element of Pari pseudo-ring.
"""
def __init__(self, x, parent=None):
"""
EXAMPLES::
sage: R = PariRing()
sage: f = R('x^3 + 1/2')
sage: f
x^3 + 1/2
sage: type(f)
<class 'sage.rings.pari_ring.PariRing_with_category.element_class'>
sage: loads(f.dumps()) == f
True
"""
if parent is None:
parent = _inst
RingElement.__init__(self, parent)
self.__x = pari.pari(x)
def __repr__(self):
"""
EXAMPLES::
sage: R = PariRing()
sage: a = R(3); a
3
"""
return str(self.__x)
def _add_(self, other):
"""
EXAMPLES::
sage: R = PariRing()
sage: b = R(11)
sage: a = R(3)
sage: a + b
14
"""
return self.__class__(self.__x + other.__x, parent=_inst)
def _sub_(self, other):
"""
EXAMPLES::
sage: R = PariRing()
sage: a = R(3)
sage: b = R(11)
sage: b - a
8
"""
return self.__class__(self.__x - other.__x, parent=_inst)
def _mul_(self, other):
"""
EXAMPLES::
sage: R = PariRing()
sage: a = R(3)
sage: b = R(11)
sage: b * a
33
"""
return self.__class__(self.__x * other.__x, parent=_inst)
def _div_(self, other):
"""
EXAMPLES::
sage: R = PariRing()
sage: a = R(3)
sage: b = R(11)
sage: b / a
11/3
"""
return self.__x * (~other.__x)
def __neg__(self):
"""
EXAMPLES::
sage: R = PariRing()
sage: a = R(3)
sage: -a
-3
"""
return self.__class__(-self.__x, parent=_inst)
def __pow__(self, other):
"""
EXAMPLES::
sage: R = PariRing()
sage: a = R(3)
sage: a^2
9
"""
if not(other in PariRing()):
other = Pari(other)
return self.__class__(self.__x ** other.__x, parent=_inst)
def __invert__(self):
"""
EXAMPLES::
sage: R = PariRing()
sage: a = R(3)
sage: ~a
1/3
"""
return self.__class__(~self.__x, parent=_inst)
def _richcmp_(self, other, op):
"""
EXAMPLES::
sage: R = PariRing()
sage: a = R(3)
sage: b = R(11)
sage: a < b
True
sage: a == b
False
sage: a > b
False
"""
return richcmp(self.__x, other.__x, op)
def __int__(self):
return int(self.__x)
class PariRing(Singleton, ring.Ring):
"""
EXAMPLES::
sage: R = PariRing(); R
Pseudoring of all PARI objects.
sage: loads(R.dumps()) is R
True
"""
Element = Pari
def __init__(self):
ring.Ring.__init__(self, self)
def __repr__(self):
return 'Pseudoring of all PARI objects.'
def _element_constructor_(self, x):
if isinstance(x, Pari):
return x
return self.element_class(x, parent=self)
def is_field(self, proof=True):
return False
def characteristic(self):
raise RuntimeError("Not defined.")
def random_element(self, x=None, y=None, distribution=None):
"""
Return a random integer in Pari.
.. NOTE::
The given arguments are passed to ``ZZ.random_element(...)``.
INPUT:
- `x`, `y` -- optional integers, that are lower and upper bound
for the result. If only `x` is provided, then the result is
between 0 and `x-1`, inclusive. If both are provided, then the
result is between `x` and `y-1`, inclusive.
- `distribution` -- optional string, so that ``ZZ`` can make sense
of it as a probability distribution.
EXAMPLES::
sage: R = PariRing()
sage: R.random_element().parent() is R
True
sage: R(5) <= R.random_element(5,13) < R(13)
True
sage: R.random_element(distribution="1/n").parent() is R
True
"""
from sage.rings.integer_ring import ZZ
return self(ZZ.random_element(x, y, distribution))
def zeta(self):
"""
Return -1.
EXAMPLES::
sage: R = PariRing()
sage: R.zeta()
-1
"""
return self(-1)
_inst = PariRing() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/pari_ring.py | 0.821617 | 0.460774 | pari_ring.py | pypi |
import sage.arith.all as arith
from . import laurent_series_ring_element
from sage.rings.puiseux_series_ring_element import PuiseuxSeries
import sage.rings.padics.factory as padics_factory
import sage.rings.padics.padic_generic_element as padic_generic_element
from . import power_series_ring_element
from . import integer
from . import rational
from sage.rings.polynomial.polynomial_element import Polynomial
from . import multi_power_series_ring_element
def O(*x, **kwds):
"""
Big O constructor for various types.
EXAMPLES:
This is useful for writing power series elements::
sage: R.<t> = ZZ[['t']]
sage: (1+t)^10 + O(t^5)
1 + 10*t + 45*t^2 + 120*t^3 + 210*t^4 + O(t^5)
A power series ring is created implicitly if a polynomial
element is passed::
sage: R.<x> = QQ['x']
sage: O(x^100)
O(x^100)
sage: 1/(1+x+O(x^5))
1 - x + x^2 - x^3 + x^4 + O(x^5)
sage: R.<u,v> = QQ[[]]
sage: 1 + u + v^2 + O(u, v)^5
1 + u + v^2 + O(u, v)^5
This is also useful to create `p`-adic numbers::
sage: O(7^6)
O(7^6)
sage: 1/3 + O(7^6)
5 + 4*7 + 4*7^2 + 4*7^3 + 4*7^4 + 4*7^5 + O(7^6)
It behaves well with respect to adding negative powers of `p`::
sage: a = O(11^-32); a
O(11^-32)
sage: a.parent()
11-adic Field with capped relative precision 20
There are problems if you add a rational with very negative
valuation to an `O`-Term::
sage: 11^-12 + O(11^15)
11^-12 + O(11^8)
The reason that this fails is that the constructor doesn't know
the right precision cap to use. If you cast explicitly or use
other means of element creation, you can get around this issue::
sage: K = Qp(11, 30)
sage: K(11^-12) + O(11^15)
11^-12 + O(11^15)
sage: 11^-12 + K(O(11^15))
11^-12 + O(11^15)
sage: K(11^-12, absprec = 15)
11^-12 + O(11^15)
sage: K(11^-12, 15)
11^-12 + O(11^15)
We can also work with `asymptotic expansions`_::
sage: A.<n> = AsymptoticRing(growth_group='QQ^n * n^QQ * log(n)^QQ', coefficient_ring=QQ); A
Asymptotic Ring <QQ^n * n^QQ * log(n)^QQ * Signs^n> over Rational Field
sage: O(n)
O(n)
Application with Puiseux series::
sage: P.<y> = PuiseuxSeriesRing(ZZ)
sage: y^(1/5) + O(y^(1/3))
y^(1/5) + O(y^(1/3))
sage: y^(1/3) + O(y^(1/5))
O(y^(1/5))
TESTS::
sage: var('x, y')
(x, y)
sage: O(x)
Traceback (most recent call last):
...
ArithmeticError: O(x) not defined
sage: O(y)
Traceback (most recent call last):
...
ArithmeticError: O(y) not defined
sage: O(x, y)
Traceback (most recent call last):
...
ArithmeticError: O(x, y) not defined
sage: O(4, 2)
Traceback (most recent call last):
...
ArithmeticError: O(4, 2) not defined
"""
if len(x) > 1:
if isinstance(x[0], multi_power_series_ring_element.MPowerSeries):
return multi_power_series_ring_element.MO(x, **kwds)
else:
raise ArithmeticError("O(%s) not defined" %
(', '.join(str(e) for e in x),))
x = x[0]
if isinstance(x, power_series_ring_element.PowerSeries):
return x.parent()(0, x.degree(), **kwds)
elif isinstance(x, Polynomial):
if x.parent().ngens() != 1:
raise NotImplementedError("completion only currently defined "
"for univariate polynomials")
if not x.is_monomial():
raise NotImplementedError("completion only currently defined "
"for the maximal ideal (x)")
return x.parent().completion(x.parent().gen())(0, x.degree(), **kwds)
elif isinstance(x, laurent_series_ring_element.LaurentSeries):
return laurent_series_ring_element.LaurentSeries(x.parent(), 0).\
add_bigoh(x.valuation(), **kwds)
elif isinstance(x, PuiseuxSeries):
return x.add_bigoh(x.valuation(), **kwds)
elif isinstance(x, (int, integer.Integer, rational.Rational)):
# p-adic number
if x <= 0:
raise ArithmeticError("x must be a prime power >= 2")
F = arith.factor(x)
if len(F) != 1:
raise ArithmeticError("x must be prime power")
p, r = F[0]
if r >= 0:
return padics_factory.Zp(p, prec=max(r, 20),
type='capped-rel')(0, absprec=r, **kwds)
else:
return padics_factory.Qp(p, prec=max(r, 20),
type='capped-rel')(0, absprec=r, **kwds)
elif isinstance(x, padic_generic_element.pAdicGenericElement):
return x.parent()(0, absprec=x.valuation(), **kwds)
elif hasattr(x, 'O'):
return x.O(**kwds)
raise ArithmeticError("O(%s) not defined" % (x,)) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/big_oh.py | 0.736401 | 0.640847 | big_oh.py | pypi |
from sage.categories.rings import Rings
from sage.rings.infinity import infinity
from sage.categories.algebras import Algebras
from sage.categories.integral_domains import IntegralDomains
from sage.categories.fields import Fields
from sage.categories.complete_discrete_valuation import CompleteDiscreteValuationFields
from .laurent_series_ring_element import LaurentSeries
from .ring import CommutativeRing
from sage.structure.unique_representation import UniqueRepresentation
from sage.misc.cachefunc import cached_method
from sage.rings.integer_ring import ZZ
def is_LaurentSeriesRing(x):
"""
Return ``True`` if this is a *univariate* Laurent series ring.
This is in keeping with the behavior of ``is_PolynomialRing``
versus ``is_MPolynomialRing``.
TESTS::
sage: from sage.rings.laurent_series_ring import is_LaurentSeriesRing
sage: K.<q> = LaurentSeriesRing(QQ)
sage: is_LaurentSeriesRing(K)
True
"""
return isinstance(x, LaurentSeriesRing)
class LaurentSeriesRing(UniqueRepresentation, CommutativeRing):
r"""
Univariate Laurent Series Ring.
EXAMPLES::
sage: R = LaurentSeriesRing(QQ, 'x'); R
Laurent Series Ring in x over Rational Field
sage: x = R.0
sage: g = 1 - x + x^2 - x^4 +O(x^8); g
1 - x + x^2 - x^4 + O(x^8)
sage: g = 10*x^(-3) + 2006 - 19*x + x^2 - x^4 +O(x^8); g
10*x^-3 + 2006 - 19*x + x^2 - x^4 + O(x^8)
You can also use more mathematical notation when the base is a
field::
sage: Frac(QQ[['x']])
Laurent Series Ring in x over Rational Field
sage: Frac(GF(5)['y'])
Fraction Field of Univariate Polynomial Ring in y over Finite Field of size 5
When the base ring is a domain, the fraction field is the
Laurent series ring over the fraction field of the base ring::
sage: Frac(ZZ[['t']])
Laurent Series Ring in t over Rational Field
Laurent series rings are determined by their variable and the base
ring, and are globally unique::
sage: K = Qp(5, prec = 5)
sage: L = Qp(5, prec = 200)
sage: R.<x> = LaurentSeriesRing(K)
sage: S.<y> = LaurentSeriesRing(L)
sage: R is S
False
sage: T.<y> = LaurentSeriesRing(Qp(5,prec=200))
sage: S is T
True
sage: W.<y> = LaurentSeriesRing(Qp(5,prec=199))
sage: W is T
False
sage: K = LaurentSeriesRing(CC, 'q')
sage: K
Laurent Series Ring in q over Complex Field with 53 bits of precision
sage: loads(K.dumps()) == K
True
sage: P = QQ[['x']]
sage: F = Frac(P)
sage: TestSuite(F).run()
When the base ring `k` is a field, the ring `k((x))` is a CDVF, that is
a field equipped with a discrete valuation for which it is complete.
The appropriate (sub)category is automatically set in this case::
sage: k = GF(11)
sage: R.<x> = k[[]]
sage: F = Frac(R)
sage: F.category()
Join of Category of complete discrete valuation fields and Category of commutative algebras over (finite enumerated fields and subquotients of monoids and quotients of semigroups) and Category of infinite sets
sage: TestSuite(F).run()
TESTS:
Check if changing global series precision does it right (and
that :trac:`17955` is fixed)::
sage: set_series_precision(3)
sage: R.<x> = LaurentSeriesRing(ZZ)
sage: 1/(1 - 2*x)
1 + 2*x + 4*x^2 + O(x^3)
sage: set_series_precision(5)
sage: R.<x> = LaurentSeriesRing(ZZ)
sage: 1/(1 - 2*x)
1 + 2*x + 4*x^2 + 8*x^3 + 16*x^4 + O(x^5)
sage: set_series_precision(20)
Check categories (:trac:`24420`)::
sage: LaurentSeriesRing(ZZ, 'x').category()
Category of infinite commutative no zero divisors algebras over (euclidean domains and infinite enumerated sets and metric spaces)
sage: LaurentSeriesRing(QQ, 'x').category()
Join of Category of complete discrete valuation fields and Category of commutative algebras over (number fields and quotient fields and metric spaces) and Category of infinite sets
sage: LaurentSeriesRing(Zmod(4), 'x').category()
Category of infinite commutative algebras over (finite commutative rings and subquotients of monoids and quotients of semigroups and finite enumerated sets)
Check coercions (:trac:`24431`)::
sage: pts = [LaurentSeriesRing,
....: PolynomialRing,
....: PowerSeriesRing,
....: LaurentPolynomialRing]
sage: LS = LaurentSeriesRing(QQ, 'x')
sage: LSx = LS.gen()
sage: for P in pts:
....: x = P(QQ, 'x').gen()
....: assert parent(LSx * x) is LS, "wrong parent for {}".format(P)
sage: for P in pts:
....: y = P(QQ, 'y').gen()
....: try:
....: LSx * y
....: except TypeError:
....: pass
....: else:
....: print("wrong coercion {}".format(P))
"""
Element = LaurentSeries
@staticmethod
def __classcall__(cls, *args, **kwds):
r"""
TESTS::
sage: L = LaurentSeriesRing(QQ, 'q')
sage: L is LaurentSeriesRing(QQ, name='q')
True
sage: loads(dumps(L)) is L
True
sage: L.variable_names()
('q',)
sage: L.variable_name()
'q'
"""
from .power_series_ring import PowerSeriesRing, is_PowerSeriesRing
if not kwds and len(args) == 1 and is_PowerSeriesRing(args[0]):
power_series = args[0]
else:
power_series = PowerSeriesRing(*args, **kwds)
return UniqueRepresentation.__classcall__(cls, power_series)
def __init__(self, power_series):
"""
Initialization
EXAMPLES::
sage: K.<q> = LaurentSeriesRing(QQ, default_prec=4); K
Laurent Series Ring in q over Rational Field
sage: 1 / (q-q^2)
q^-1 + 1 + q + q^2 + O(q^3)
sage: RZZ = LaurentSeriesRing(ZZ, 't')
sage: RZZ.category()
Category of infinite commutative no zero divisors algebras over (euclidean domains and infinite enumerated sets and metric spaces)
sage: TestSuite(RZZ).run()
sage: R1 = LaurentSeriesRing(Zmod(1), 't')
sage: R1.category()
Category of finite commutative algebras over (finite commutative rings and subquotients of monoids and quotients of semigroups and finite enumerated sets)
sage: TestSuite(R1).run()
sage: R2 = LaurentSeriesRing(Zmod(2), 't')
sage: R2.category()
Join of Category of complete discrete valuation fields and Category of commutative algebras over (finite enumerated fields and subquotients of monoids and quotients of semigroups) and Category of infinite sets
sage: TestSuite(R2).run()
sage: R4 = LaurentSeriesRing(Zmod(4), 't')
sage: R4.category()
Category of infinite commutative algebras over (finite commutative rings and subquotients of monoids and quotients of semigroups and finite enumerated sets)
sage: TestSuite(R4).run()
sage: RQQ = LaurentSeriesRing(QQ, 't')
sage: RQQ.category()
Join of Category of complete discrete valuation fields and Category of commutative algebras over (number fields and quotient fields and metric spaces) and Category of infinite sets
sage: TestSuite(RQQ).run()
"""
base_ring = power_series.base_ring()
category = Algebras(base_ring.category())
if base_ring in Fields():
category &= CompleteDiscreteValuationFields()
elif base_ring in IntegralDomains():
category &= IntegralDomains()
elif base_ring in Rings().Commutative():
category = category.Commutative()
if base_ring.is_zero():
category = category.Finite()
else:
category = category.Infinite()
self._power_series_ring = power_series
self._one_element = self.element_class(self, power_series.one())
CommutativeRing.__init__(self, base_ring,
names=power_series.variable_names(),
category=category)
def base_extend(self, R):
"""
Return the Laurent series ring over R in the same variable as
self, assuming there is a canonical coerce map from the base ring
of self to R.
EXAMPLES::
sage: K.<x> = LaurentSeriesRing(QQ, default_prec=4)
sage: K.base_extend(QQ['t'])
Laurent Series Ring in x over Univariate Polynomial Ring in t over Rational Field
"""
if R.has_coerce_map_from(self.base_ring()):
return self.change_ring(R)
else:
raise TypeError("no valid base extension defined")
def fraction_field(self):
r"""
Return the fraction field of this ring of Laurent series.
If the base ring is a field, then Laurent series are already a field.
If the base ring is a domain, then the Laurent series over its fraction
field is returned. Otherwise, raise a ``ValueError``.
EXAMPLES::
sage: R = LaurentSeriesRing(ZZ, 't', 30).fraction_field()
sage: R
Laurent Series Ring in t over Rational Field
sage: R.default_prec()
30
sage: LaurentSeriesRing(Zmod(4), 't').fraction_field()
Traceback (most recent call last):
...
ValueError: must be an integral domain
"""
from sage.categories.integral_domains import IntegralDomains
from sage.categories.fields import Fields
if self in Fields():
return self
elif self in IntegralDomains():
return LaurentSeriesRing(self.base_ring().fraction_field(),
self.variable_names(),
self.default_prec())
else:
raise ValueError('must be an integral domain')
def change_ring(self, R):
"""
EXAMPLES::
sage: K.<x> = LaurentSeriesRing(QQ, default_prec=4)
sage: R = K.change_ring(ZZ); R
Laurent Series Ring in x over Integer Ring
sage: R.default_prec()
4
"""
return LaurentSeriesRing(R, self.variable_names(),
default_prec=self.default_prec(),
sparse=self.is_sparse())
def is_sparse(self):
"""
Return if ``self`` is a sparse implementation.
EXAMPLES::
sage: K.<x> = LaurentSeriesRing(QQ, sparse=True)
sage: K.is_sparse()
True
"""
return self.power_series_ring().is_sparse()
def is_field(self, proof=True):
"""
A Laurent series ring is a field if and only if the base ring
is a field.
TESTS::
sage: LaurentSeriesRing(QQ,'t').is_field()
True
sage: LaurentSeriesRing(ZZ,'t').is_field()
False
"""
return self.base_ring().is_field()
def is_dense(self):
"""
EXAMPLES::
sage: K.<x> = LaurentSeriesRing(QQ, sparse=True)
sage: K.is_dense()
False
"""
return self.power_series_ring().is_dense()
def _repr_(self):
"""
EXAMPLES::
sage: LaurentSeriesRing(QQ,'q') # indirect doctest
Laurent Series Ring in q over Rational Field
sage: LaurentSeriesRing(ZZ,'t',sparse=True)
Sparse Laurent Series Ring in t over Integer Ring
"""
s = "Laurent Series Ring in %s over %s" % (self.variable_name(), self.base_ring())
if self.is_sparse():
s = 'Sparse ' + s
return s
def _element_constructor_(self, x, n=0, prec=infinity):
r"""
Construct a Laurent series from `x`.
INPUT:
- ``x`` -- object that can be converted into a Laurent series
- ``n`` -- (default: 0) multiply the result by `t^n`
- ``prec`` -- (default: ``infinity``) the precision of the series
as an integer.
EXAMPLES::
sage: R.<u> = LaurentSeriesRing(Qp(5, 10))
sage: S.<t> = LaurentSeriesRing(RationalField())
sage: R(t + t^2 + O(t^3))
(1 + O(5^10))*u + (1 + O(5^10))*u^2 + O(u^3)
sage: R(t + t^2 + O(t^3), prec=2)
(1 + O(5^10))*u + O(u^2)
Coercing an element into its own parent produces that element
again, unless a different ``n`` or ``prec`` is given::
sage: u is R(u)
True
sage: R(u, n=3, prec=7)
(1 + O(5^10))*u^4 + O(u^7)
Rational functions are accepted::
sage: I = sqrt(-1)
sage: K.<I> = QQ[I]
sage: P.<t> = PolynomialRing(K)
sage: L.<u> = LaurentSeriesRing(QQ[I])
sage: L((t*I)/(t^3+I*2*t))
1/2 + 1/4*I*u^2 - 1/8*u^4 - 1/16*I*u^6 + 1/32*u^8 +
1/64*I*u^10 - 1/128*u^12 - 1/256*I*u^14 + 1/512*u^16 +
1/1024*I*u^18 + O(u^20)
::
sage: L(t*I) / L(t^3+I*2*t)
1/2 + 1/4*I*u^2 - 1/8*u^4 - 1/16*I*u^6 + 1/32*u^8 +
1/64*I*u^10 - 1/128*u^12 - 1/256*I*u^14 + 1/512*u^16 +
1/1024*I*u^18 + O(u^20)
TESTS:
Check that :trac:`28993` is fixed::
sage: from sage.modular.etaproducts import qexp_eta
sage: qexp_eta(S, prec=30)
1 - t - t^2 + t^5 + t^7 - t^12 - t^15 + t^22 + t^26 + O(t^30)
When converting from `R((z))` to `R((z))((w))`, the variable
`z` is sent to `z` rather than to `w` (see :trac:`7085`)::
sage: A.<z> = LaurentSeriesRing(QQ)
sage: B.<w> = LaurentSeriesRing(A)
sage: B(z)
z
sage: z/w
z*w^-1
Various conversions from PARI (see also :trac:`2508`)::
sage: L.<q> = LaurentSeriesRing(QQ, default_prec=10)
sage: L(pari('1/x'))
q^-1
sage: L(pari('polchebyshev(5)'))
5*q - 20*q^3 + 16*q^5
sage: L(pari('polchebyshev(5) - 1/x^4'))
-q^-4 + 5*q - 20*q^3 + 16*q^5
sage: L(pari('1/polchebyshev(5)'))
1/5*q^-1 + 4/5*q + 64/25*q^3 + 192/25*q^5 + 2816/125*q^7 + O(q^9)
sage: L(pari('polchebyshev(5) + O(x^40)'))
5*q - 20*q^3 + 16*q^5 + O(q^40)
sage: L(pari('polchebyshev(5) - 1/x^4 + O(x^40)'))
-q^-4 + 5*q - 20*q^3 + 16*q^5 + O(q^40)
sage: L(pari('1/polchebyshev(5) + O(x^10)'))
1/5*q^-1 + 4/5*q + 64/25*q^3 + 192/25*q^5 + 2816/125*q^7 + 8192/125*q^9 + O(q^10)
sage: L(pari('1/polchebyshev(5) + O(x^10)'), -10) # Multiply by q^-10
1/5*q^-11 + 4/5*q^-9 + 64/25*q^-7 + 192/25*q^-5 + 2816/125*q^-3 + 8192/125*q^-1 + O(1)
sage: L(pari('O(x^-10)'))
O(q^-10)
Check that :trac:`30073` is fixed::
sage: P.<x> = LaurentSeriesRing(QQ)
sage: P({-3: 1})
x^-3
"""
from sage.rings.fraction_field_element import is_FractionFieldElement
from sage.rings.polynomial.polynomial_element import is_Polynomial
from sage.rings.polynomial.multi_polynomial_element import is_MPolynomial
from sage.structure.element import parent
from sage.libs.pari.all import pari_gen
P = parent(x)
if isinstance(x, self.element_class) and n == 0 and P is self:
return x.add_bigoh(prec) # ok, since Laurent series are immutable (no need to make a copy)
elif P is self.base_ring():
# Convert x into a power series; if P is itself a Laurent
# series ring A((t)), this prevents the implementation of
# LaurentSeries.__init__() from effectively applying the
# ring homomorphism A((t)) -> A((t))((u)) sending t to u
# instead of the one sending t to t. We cannot easily
# tell LaurentSeries.__init__() to be more strict, because
# A((t)) -> B((u)) is expected to send t to u if A admits
# a coercion to B but A((t)) does not, and this condition
# would be inefficient to check there.
x = self.power_series_ring()(x)
elif isinstance(x, pari_gen):
t = x.type()
if t == "t_RFRAC": # Rational function
x = self(self.polynomial_ring()(x.numerator())) / \
self(self.polynomial_ring()(x.denominator()))
return (x << n).add_bigoh(prec)
elif t == "t_SER": # Laurent series
n += x._valp()
bigoh = n + x.length()
x = self(self.polynomial_ring()(x.Vec()))
return (x << n).add_bigoh(bigoh)
else: # General case, pretend to be a polynomial
return (self(self.polynomial_ring()(x)) << n).add_bigoh(prec)
elif (is_FractionFieldElement(x)
and (x.base_ring() is self.base_ring() or x.base_ring() == self.base_ring())
and (is_Polynomial(x.numerator()) or is_MPolynomial(x.numerator()))):
x = self(x.numerator()) / self(x.denominator())
return (x << n).add_bigoh(prec)
return self.element_class(self, x, n).add_bigoh(prec)
def random_element(self, algorithm='default'):
r"""
Return a random element of this Laurent series ring.
The optional ``algorithm`` parameter decides how elements are generated.
Algorithms currently implemented:
- ``'default'``: Choose an integer ``shift`` using the standard
distribution on the integers. Then choose a list of coefficients
using the ``random_element`` function of the base ring, and construct
a new element based on those coefficients, so that the i-th
coefficient corresponds to the (i+shift)-th power of the uniformizer.
The amount of coefficients is determined by the ``default_prec``
of the ring. Note that this method only creates non-exact elements.
EXAMPLES::
sage: S.<s> = LaurentSeriesRing(GF(3))
sage: S.random_element() # random
s^-8 + s^-7 + s^-6 + s^-5 + s^-1 + s + s^3 + s^4
+ s^5 + 2*s^6 + s^7 + s^11 + O(s^12)
"""
if algorithm == 'default':
shift = ZZ.random_element()
return self([self.base_ring().random_element()
for k in range(self.default_prec())],
shift).O(shift + self.default_prec())
else:
raise ValueError("algorithm cannot be %s" % algorithm)
def construction(self):
r"""
Return the functorial construction of this Laurent power series ring.
The construction is given as the completion of the Laurent polynomials.
EXAMPLES::
sage: L.<t> = LaurentSeriesRing(ZZ, default_prec=42)
sage: phi, arg = L.construction()
sage: phi
Completion[t, prec=42]
sage: arg
Univariate Laurent Polynomial Ring in t over Integer Ring
sage: phi(arg) is L
True
Because of this construction, pushout is automatically available::
sage: 1/2 * t
1/2*t
sage: parent(1/2 * t)
Laurent Series Ring in t over Rational Field
sage: QQbar.gen() * t
I*t
sage: parent(QQbar.gen() * t)
Laurent Series Ring in t over Algebraic Field
"""
from sage.categories.pushout import CompletionFunctor
from sage.rings.polynomial.laurent_polynomial_ring import LaurentPolynomialRing
L = LaurentPolynomialRing(self.base_ring(), self._names[0])
return CompletionFunctor(self._names[0], self.default_prec()), L
def _coerce_map_from_(self, P):
"""
Return a coercion map from `P` to ``self``, or True, or None.
The following rings admit a coercion map to the Laurent series
ring `A((t))`:
- any ring that admits a coercion map to `A` (including `A`
itself);
- any Laurent series ring, power series ring or polynomial
ring in the variable `t` over a ring admitting a coercion
map to `A`.
EXAMPLES::
sage: S.<t> = LaurentSeriesRing(ZZ)
sage: S.has_coerce_map_from(ZZ)
True
sage: S.has_coerce_map_from(PolynomialRing(ZZ, 't'))
True
sage: S.has_coerce_map_from(LaurentPolynomialRing(ZZ, 't'))
True
sage: S.has_coerce_map_from(PowerSeriesRing(ZZ, 't'))
True
sage: S.has_coerce_map_from(S)
True
sage: S.has_coerce_map_from(QQ)
False
sage: S.has_coerce_map_from(PolynomialRing(QQ, 't'))
False
sage: S.has_coerce_map_from(LaurentPolynomialRing(QQ, 't'))
False
sage: S.has_coerce_map_from(PowerSeriesRing(QQ, 't'))
False
sage: S.has_coerce_map_from(LaurentSeriesRing(QQ, 't'))
False
sage: R.<t> = LaurentSeriesRing(QQ['x'])
sage: R.has_coerce_map_from(QQ[['t']])
True
sage: R.has_coerce_map_from(QQ['t'])
True
sage: R.has_coerce_map_from(ZZ['x']['t'])
True
sage: R.has_coerce_map_from(ZZ['t']['x'])
False
sage: R.has_coerce_map_from(ZZ['x'])
True
"""
A = self.base_ring()
from sage.rings.polynomial.polynomial_ring import is_PolynomialRing
from sage.rings.power_series_ring import is_PowerSeriesRing
from sage.rings.polynomial.laurent_polynomial_ring import is_LaurentPolynomialRing
if ((is_LaurentSeriesRing(P) or
is_LaurentPolynomialRing(P) or
is_PowerSeriesRing(P) or
is_PolynomialRing(P))
and P.variable_name() == self.variable_name()
and A.has_coerce_map_from(P.base_ring())):
return True
def _is_valid_homomorphism_(self, codomain, im_gens, base_map=None):
"""
EXAMPLES::
sage: R.<x> = LaurentSeriesRing(GF(17))
sage: S.<y> = LaurentSeriesRing(GF(19))
sage: R.hom([y], S) # indirect doctest
Traceback (most recent call last):
...
ValueError: relations do not all (canonically) map to 0 under map determined by images of generators
sage: f = R.hom(x+x^3,R)
sage: f(x^2)
x^2 + 2*x^4 + x^6
The image of the generator needs to be a unit::
sage: R.<x> = LaurentSeriesRing(ZZ)
sage: R._is_valid_homomorphism_(R, [2*x])
False
"""
# NOTE: There are no ring homomorphisms from the ring of
# all formal power series to most rings, e.g, the p-adic
# field, since you can always (mathematically!) construct
# some power series that does not converge.
# NOTE: The above claim is wrong when the base ring is Z.
# See trac 28486.
if base_map is None and not codomain.has_coerce_map_from(self.base_ring()):
return False
# Note that 0 is not a *ring* homomorphism, and you cannot map to a power series ring
if is_LaurentSeriesRing(codomain):
return im_gens[0].valuation() > 0 and im_gens[0].is_unit()
return False
def characteristic(self):
"""
EXAMPLES::
sage: R.<x> = LaurentSeriesRing(GF(17))
sage: R.characteristic()
17
"""
return self.base_ring().characteristic()
def residue_field(self):
"""
Return the residue field of this Laurent series field
if it is a complete discrete valuation field (i.e. if
the base ring is a field, in which base it is also the
residue field).
EXAMPLES::
sage: R.<x> = LaurentSeriesRing(GF(17))
sage: R.residue_field()
Finite Field of size 17
sage: R.<x> = LaurentSeriesRing(ZZ)
sage: R.residue_field()
Traceback (most recent call last):
...
TypeError: the base ring is not a field
"""
if not self.base_ring().is_field():
raise TypeError("the base ring is not a field")
return self.base_ring()
def default_prec(self):
"""
Get the precision to which exact elements are truncated when
necessary (most frequently when inverting).
EXAMPLES::
sage: R.<x> = LaurentSeriesRing(QQ, default_prec=5)
sage: R.default_prec()
5
"""
return self._power_series_ring.default_prec()
def is_exact(self):
"""
Laurent series rings are inexact.
EXAMPLES::
sage: R = LaurentSeriesRing(QQ, "x")
sage: R.is_exact()
False
"""
return False
@cached_method
def gen(self, n=0):
"""
EXAMPLES::
sage: R = LaurentSeriesRing(QQ, "x")
sage: R.gen()
x
"""
if n != 0:
raise IndexError("generator {} not defined".format(n))
return self.element_class(self, [0, 1])
def uniformizer(self):
"""
Return a uniformizer of this Laurent series field if it is
a discrete valuation field (i.e. if the base ring is actually
a field). Otherwise, an error is raised.
EXAMPLES::
sage: R.<t> = LaurentSeriesRing(QQ)
sage: R.uniformizer()
t
sage: R.<t> = LaurentSeriesRing(ZZ)
sage: R.uniformizer()
Traceback (most recent call last):
...
TypeError: the base ring is not a field
"""
if not self.base_ring().is_field():
raise TypeError("the base ring is not a field")
return self.gen()
def ngens(self):
"""
Laurent series rings are univariate.
EXAMPLES::
sage: R = LaurentSeriesRing(QQ, "x")
sage: R.ngens()
1
"""
return 1
def polynomial_ring(self):
r"""
If this is the Laurent series ring `R((t))`, return the
polynomial ring `R[t]`.
EXAMPLES::
sage: R = LaurentSeriesRing(QQ, "x")
sage: R.polynomial_ring()
Univariate Polynomial Ring in x over Rational Field
"""
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
return PolynomialRing(self.base_ring(), self.variable_name(),
sparse=self.is_sparse())
def laurent_polynomial_ring(self):
r"""
If this is the Laurent series ring `R((t))`, return the Laurent
polynomial ring `R[t,1/t]`.
EXAMPLES::
sage: R = LaurentSeriesRing(QQ, "x")
sage: R.laurent_polynomial_ring()
Univariate Laurent Polynomial Ring in x over Rational Field
"""
from sage.rings.polynomial.laurent_polynomial_ring import LaurentPolynomialRing
return LaurentPolynomialRing(self.base_ring(), self.variable_name(),
sparse=self.is_sparse())
def power_series_ring(self):
r"""
If this is the Laurent series ring `R((t))`, return the
power series ring `R[[t]]`.
EXAMPLES::
sage: R = LaurentSeriesRing(QQ, "x")
sage: R.power_series_ring()
Power Series Ring in x over Rational Field
"""
return self._power_series_ring | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/laurent_series_ring.py | 0.921931 | 0.515559 | laurent_series_ring.py | pypi |
from sage.categories.homset import HomsetWithBase
from sage.categories.rings import Rings
_Rings = Rings()
from . import morphism
from . import quotient_ring
def is_RingHomset(H):
"""
Return ``True`` if ``H`` is a space of homomorphisms between two rings.
EXAMPLES::
sage: from sage.rings.homset import is_RingHomset as is_RH
sage: is_RH(Hom(ZZ, QQ))
True
sage: is_RH(ZZ)
False
sage: is_RH(Hom(RR, CC))
True
sage: is_RH(Hom(FreeModule(ZZ,1), FreeModule(QQ,1)))
False
"""
return isinstance(H, RingHomset_generic)
def RingHomset(R, S, category = None):
"""
Construct a space of homomorphisms between the rings ``R`` and ``S``.
For more on homsets, see :func:`Hom()`.
EXAMPLES::
sage: Hom(ZZ, QQ) # indirect doctest
Set of Homomorphisms from Integer Ring to Rational Field
"""
if quotient_ring.is_QuotientRing(R):
from .polynomial.polynomial_quotient_ring import is_PolynomialQuotientRing
if not is_PolynomialQuotientRing(R): # backwards compatibility
return RingHomset_quo_ring(R, S, category = category)
return RingHomset_generic(R, S, category = category)
class RingHomset_generic(HomsetWithBase):
"""
A generic space of homomorphisms between two rings.
EXAMPLES::
sage: Hom(ZZ, QQ)
Set of Homomorphisms from Integer Ring to Rational Field
sage: QQ.Hom(ZZ)
Set of Homomorphisms from Rational Field to Integer Ring
"""
Element = morphism.RingHomomorphism
def __init__(self, R, S, category = None):
"""
Initialize ``self``.
EXAMPLES::
sage: Hom(ZZ, QQ)
Set of Homomorphisms from Integer Ring to Rational Field
"""
if category is None:
category = _Rings
HomsetWithBase.__init__(self, R, S, category)
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: Hom(ZZ, QQ) # indirect doctest
Set of Homomorphisms from Integer Ring to Rational Field
"""
return "Set of Homomorphisms from %s to %s"%(self.domain(), self.codomain())
def has_coerce_map_from(self, x):
"""
The default for coercion maps between ring homomorphism spaces is
very restrictive (until more implementation work is done).
Currently this checks if the domains and the codomains are equal.
EXAMPLES::
sage: H = Hom(ZZ, QQ)
sage: H2 = Hom(QQ, ZZ)
sage: H.has_coerce_map_from(H2)
False
"""
return (x.domain() == self.domain() and x.codomain() == self.codomain())
def _element_constructor_(self, x, check=True, base_map=None):
"""
Construct an element of ``self`` from ``x``.
EXAMPLES::
sage: H = Hom(ZZ, QQ)
sage: phi = H([1]); phi
Ring morphism:
From: Integer Ring
To: Rational Field
Defn: 1 |--> 1
sage: H2 = Hom(QQ, QQ)
sage: phi2 = H2(phi); phi2
Ring endomorphism of Rational Field
Defn: 1 |--> 1
sage: H(phi2)
Ring morphism:
From: Integer Ring
To: Rational Field
Defn: 1 |--> 1
You can provide a morphism on the base::
sage: k = GF(9)
sage: z2 = k.gen()
sage: cc = k.frobenius_endomorphism()
sage: R.<x> = k[]
sage: H = Hom(R, R)
sage: phi = H([x^2], base_map=cc); phi
Ring endomorphism of Univariate Polynomial Ring in x over Finite Field in z2 of size 3^2
Defn: x |--> x^2
with map of base ring
sage: phi(z2*x) == z2^3 * x^2
True
sage: R.<x> = ZZ[]
sage: K.<a> = GF(7^2)
sage: L.<u> = K.extension(x^3 - 3)
sage: phi = L.hom([u^7], base_map=K.frobenius_endomorphism())
sage: phi(u) == u^7
True
sage: phi(a) == a^7
True
TESTS::
sage: H = Hom(ZZ, QQ)
sage: H == loads(dumps(H))
True
"""
from sage.categories.map import Map
# Case 0: the homomorphism is given by images of generators
if not (isinstance(x, Map) and x.category_for().is_subcategory(Rings())):
return morphism.RingHomomorphism_im_gens(self, x, base_map=base_map, check=check)
if base_map is not None:
raise ValueError("cannot specify base_map when providing a map")
# Case 1: the parent fits
if x.parent() == self:
if isinstance(x, morphism.RingHomomorphism_im_gens):
return morphism.RingHomomorphism_im_gens(self, x.im_gens())
elif isinstance(x, morphism.RingHomomorphism_cover):
return morphism.RingHomomorphism_cover(self)
elif isinstance(x, morphism.RingHomomorphism_from_base):
return morphism.RingHomomorphism_from_base(self, x.underlying_map())
# Case 2: unique extension via fraction field
try:
if (isinstance(x, morphism.RingHomomorphism_im_gens)
and x.domain().fraction_field().has_coerce_map_from(self.domain())):
return morphism.RingHomomorphism_im_gens(self, x.im_gens())
except (TypeError, ValueError):
pass
# Case 3: the homomorphism can be extended by coercion
try:
return x.extend_codomain(self.codomain()).extend_domain(self.domain())
except (TypeError, ValueError):
pass
# Case 4: the homomorphism is induced from the base ring
if (self.domain() != self.domain().base()
or self.codomain() != self.codomain().base()):
x = self.domain().base().Hom(self.codomain().base())(x)
return morphism.RingHomomorphism_from_base(self, x)
raise ValueError('cannot convert {} to an element of {}'.format(x, self))
def natural_map(self):
"""
Returns the natural map from the domain to the codomain.
The natural map is the coercion map from the domain ring to the
codomain ring.
EXAMPLES::
sage: H = Hom(ZZ, QQ)
sage: H.natural_map()
Natural morphism:
From: Integer Ring
To: Rational Field
"""
f = self.codomain().coerce_map_from(self.domain())
if f is None:
raise TypeError("natural coercion morphism from %s to %s not defined"%(self.domain(), self.codomain()))
return f
def zero(self):
r"""
Return the zero element of this homset.
EXAMPLES:
Since a ring homomorphism maps 1 to 1, there can only be a zero
morphism when mapping to the trivial ring::
sage: Hom(ZZ, Zmod(1)).zero()
Ring morphism:
From: Integer Ring
To: Ring of integers modulo 1
Defn: 1 |--> 0
sage: Hom(ZZ, Zmod(2)).zero()
Traceback (most recent call last):
...
ValueError: homset has no zero element
"""
if not self.codomain().is_zero():
raise ValueError("homset has no zero element")
# there is only one map in this homset
return self.an_element()
class RingHomset_quo_ring(RingHomset_generic):
"""
Space of ring homomorphisms where the domain is a (formal) quotient
ring.
EXAMPLES::
sage: R.<x,y> = PolynomialRing(QQ, 2)
sage: S.<a,b> = R.quotient(x^2 + y^2)
sage: phi = S.hom([b,a]); phi
Ring endomorphism of Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2)
Defn: a |--> b
b |--> a
sage: phi(a)
b
sage: phi(b)
a
TESTS:
We test pickling of a homset from a quotient.
::
sage: R.<x,y> = PolynomialRing(QQ, 2)
sage: S.<a,b> = R.quotient(x^2 + y^2)
sage: H = S.Hom(R)
sage: H == loads(dumps(H))
True
We test pickling of actual homomorphisms in a quotient::
sage: phi = S.hom([b,a])
sage: phi == loads(dumps(phi))
True
"""
Element = morphism.RingHomomorphism_from_quotient
def _element_constructor_(self, x, base_map=None, check=True):
"""
Construct an element of ``self`` from ``x``.
EXAMPLES::
sage: R.<x,y> = PolynomialRing(QQ, 2)
sage: S.<a,b> = R.quotient(x^2 + y^2)
sage: H = S.Hom(R)
sage: phi = H([b, a]); phi
Ring morphism:
From: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2)
To: Multivariate Polynomial Ring in x, y over Rational Field
Defn: a |--> b
b |--> a
sage: R2.<x,y> = PolynomialRing(ZZ, 2)
sage: H2 = Hom(R2, S)
sage: H2(phi)
Composite map:
From: Multivariate Polynomial Ring in x, y over Integer Ring
To: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2)
Defn: Coercion map:
From: Multivariate Polynomial Ring in x, y over Integer Ring
To: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2)
then
Ring morphism:
From: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2)
To: Multivariate Polynomial Ring in x, y over Rational Field
Defn: a |--> b
b |--> a
then
Coercion map:
From: Multivariate Polynomial Ring in x, y over Rational Field
To: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2)
"""
if isinstance(x, morphism.RingHomomorphism_from_quotient):
phi = x._phi()
else:
pi = self.domain().cover()
phi = pi.domain().hom(x, base_map=base_map, check=check)
return self.element_class(self, phi) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/homset.py | 0.855504 | 0.551695 | homset.py | pypi |
r"""
Generic data structures and algorithms for rings
AUTHORS:
- Lorenz Panny (2022): :class:`ProductTree`, :func:`prod_with_derivative`
"""
from sage.misc.misc_c import prod
class ProductTree:
r"""
A simple binary product tree, i.e., a tree of ring elements in
which every node equals the product of its children.
(In particular, the *root* equals the product of all *leaves*.)
Product trees are a very useful building block for fast computer
algebra. For example, a quasilinear-time Discrete Fourier Transform
(the famous *Fast* Fourier Transform) can be implemented as follows
using the :meth:`remainders` method of this class::
sage: from sage.rings.generic import ProductTree
sage: F = GF(65537)
sage: a = F(1111)
sage: assert a.multiplicative_order() == 1024
sage: R.<x> = F[]
sage: ms = [x - a^i for i in range(1024)] # roots of unity
sage: ys = [F.random_element() for _ in range(1024)] # input vector
sage: zs = ProductTree(ms).remainders(R(ys)) # compute FFT!
sage: zs == [R(ys) % m for m in ms]
True
This class encodes the tree as *layers*: Layer `0` is just a tuple
of the leaves. Layer `i+1` is obtained from layer `i` by replacing
each pair of two adjacent elements by their product, starting from
the left. (If the length is odd, the unpaired element at the end is
simply copied as is.) This iteration stops as soon as it yields a
layer containing only a single element (the root).
.. NOTE::
Use this class if you need the :meth:`remainders` method.
To compute just the product, :func:`prod` is likely faster.
INPUT:
- ``leaves`` -- an iterable of elements in a common ring
EXAMPLES::
sage: from sage.rings.generic import ProductTree
sage: R.<x> = GF(101)[]
sage: vs = [x - i for i in range(1,10)]
sage: tree = ProductTree(vs)
sage: tree.root()
x^9 + 56*x^8 + 62*x^7 + 44*x^6 + 47*x^5 + 42*x^4 + 15*x^3 + 11*x^2 + 12*x + 13
sage: tree.remainders(x^7 + x + 1)
[3, 30, 70, 27, 58, 72, 98, 98, 23]
sage: tree.remainders(x^100)
[1, 1, 1, 1, 1, 1, 1, 1, 1]
::
sage: vs = prime_range(100)
sage: tree = ProductTree(vs)
sage: tree.root().factor()
2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37 * 41 * 43 * 47 * 53 * 59 * 61 * 67 * 71 * 73 * 79 * 83 * 89 * 97
sage: tree.remainders(3599)
[1, 2, 4, 1, 2, 11, 12, 8, 11, 3, 3, 10, 32, 30, 27, 48, 0, 0, 48, 49, 22, 44, 30, 39, 10]
We can access the individual layers of the tree::
sage: tree.layers
[(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97),
(6, 35, 143, 323, 667, 1147, 1763, 2491, 3599, 4757, 5767, 7387, 97),
(210, 46189, 765049, 4391633, 17120443, 42600829, 97),
(9699690, 3359814435017, 729345064647247, 97),
(32589158477190044730, 70746471270782959),
(2305567963945518424753102147331756070,)]
"""
def __init__(self, leaves):
r"""
Initialize a product tree having the given ring elements
as its leaves.
EXAMPLES::
sage: from sage.rings.generic import ProductTree
sage: vs = prime_range(100)
sage: tree = ProductTree(vs)
"""
V = tuple(leaves)
self.layers = [V]
while len(V) > 1:
V = tuple(prod(V[i:i+2]) for i in range(0,len(V),2))
self.layers.append(V)
def __len__(self):
r"""
Return the number of leaves of this product tree.
EXAMPLES::
sage: from sage.rings.generic import ProductTree
sage: R.<x> = GF(101)[]
sage: vs = [x - i for i in range(1,10)]
sage: tree = ProductTree(vs)
sage: len(tree)
9
sage: len(tree) == len(vs)
True
sage: len(tree.remainders(x^2))
9
"""
return len(self.layers[0])
def __iter__(self):
r"""
Return an iterator over the leaves of this product tree.
EXAMPLES::
sage: from sage.rings.generic import ProductTree
sage: R.<x> = GF(101)[]
sage: vs = [x - i for i in range(1,10)]
sage: tree = ProductTree(vs)
sage: next(iter(tree)) == vs[0]
True
sage: list(tree) == vs
True
"""
return iter(self.layers[0])
def root(self):
r"""
Return the value at the root of this product tree (i.e., the product of all leaves).
EXAMPLES::
sage: from sage.rings.generic import ProductTree
sage: R.<x> = GF(101)[]
sage: vs = [x - i for i in range(1,10)]
sage: tree = ProductTree(vs)
sage: tree.root()
x^9 + 56*x^8 + 62*x^7 + 44*x^6 + 47*x^5 + 42*x^4 + 15*x^3 + 11*x^2 + 12*x + 13
sage: tree.root() == prod(vs)
True
"""
assert len(self.layers[-1]) == 1
return self.layers[-1][0]
def leaves(self):
r"""
Return a tuple containing the leaves of this product tree.
EXAMPLES::
sage: from sage.rings.generic import ProductTree
sage: R.<x> = GF(101)[]
sage: vs = [x - i for i in range(1,10)]
sage: tree = ProductTree(vs)
sage: tree.leaves()
(x + 100, x + 99, x + 98, ..., x + 93, x + 92)
sage: tree.leaves() == tuple(vs)
True
"""
return self.layers[0]
def remainders(self, x):
r"""
Given a value `x`, return a list of all remainders of `x`
modulo the leaves of this product tree.
The base ring must support the ``%`` operator for this
method to work.
INPUT:
- ``x`` -- an element of the base ring of this product tree
EXAMPLES::
sage: from sage.rings.generic import ProductTree
sage: vs = prime_range(100)
sage: tree = ProductTree(vs)
sage: n = 1085749272377676749812331719267
sage: tree.remainders(n)
[1, 1, 2, 1, 9, 1, 7, 15, 8, 20, 15, 6, 27, 11, 2, 6, 0, 25, 49, 5, 51, 4, 19, 74, 13]
sage: [n % v for v in vs]
[1, 1, 2, 1, 9, 1, 7, 15, 8, 20, 15, 6, 27, 11, 2, 6, 0, 25, 49, 5, 51, 4, 19, 74, 13]
"""
X = [x]
for V in reversed(self.layers):
X = [X[i // 2] % V[i] for i in range(len(V))]
return X
def prod_with_derivative(pairs):
r"""
Given an iterable of pairs `(f, \partial f)` of ring elements,
return the pair `(\prod f, \partial \prod f)`, assuming `\partial`
is an operator obeying the standard product rule.
This function is entirely algebraic, hence still works when the
elements `f` and `\partial f` are all passed through some ring
homomorphism first. One particularly useful instance of this is
evaluating the derivative of a product of polynomials at a point
without fully expanding the product; see the second example below.
INPUT:
- ``pairs`` -- an iterable of tuples `(f, \partial f)` of elements
of a common ring
ALGORITHM: Repeated application of the product rule.
EXAMPLES::
sage: from sage.rings.generic import prod_with_derivative
sage: R.<x> = ZZ[]
sage: fs = [x^2 + 2*x + 3, 4*x + 5, 6*x^7 + 8*x + 9]
sage: prod(fs)
24*x^10 + 78*x^9 + 132*x^8 + 90*x^7 + 32*x^4 + 140*x^3 + 293*x^2 + 318*x + 135
sage: prod(fs).derivative()
240*x^9 + 702*x^8 + 1056*x^7 + 630*x^6 + 128*x^3 + 420*x^2 + 586*x + 318
sage: F, dF = prod_with_derivative((f, f.derivative()) for f in fs)
sage: F
24*x^10 + 78*x^9 + 132*x^8 + 90*x^7 + 32*x^4 + 140*x^3 + 293*x^2 + 318*x + 135
sage: dF
240*x^9 + 702*x^8 + 1056*x^7 + 630*x^6 + 128*x^3 + 420*x^2 + 586*x + 318
The main reason for this function to exist is that it allows us to
*evaluate* the derivative of a product of polynomials at a point
`\alpha` without ever fully expanding the product *as a polynomial*::
sage: alpha = 42
sage: F(alpha)
442943981574522759
sage: dF(alpha)
104645261461514994
sage: us = [f(alpha) for f in fs]
sage: vs = [f.derivative()(alpha) for f in fs]
sage: prod_with_derivative(zip(us, vs))
(442943981574522759, 104645261461514994)
"""
class _aux:
def __init__(self, f, df):
self.f, self.df = f, df
def __mul__(self, other):
return _aux(self.f * other.f, self.df * other.f + self.f * other.df)
def __iter__(self):
yield self.f
yield self.df
return tuple(prod(_aux(*tup) for tup in pairs)) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/generic.py | 0.913722 | 0.756425 | generic.py | pypi |
from sage.categories.morphism import Morphism
from sage.categories.homset import Hom
from .generic_nodes import pAdicFixedModRingGeneric, pAdicCappedAbsoluteRingGeneric, pAdicCappedRelativeRingGeneric, pAdicCappedRelativeFieldGeneric, pAdicFloatingPointRingGeneric, pAdicFloatingPointFieldGeneric
from .eisenstein_extension_generic import EisensteinExtensionGeneric
from .relative_ramified_FM import RelativeRamifiedFixedModElement
from .relative_ramified_CA import RelativeRamifiedCappedAbsoluteElement
from .relative_ramified_CR import RelativeRamifiedCappedRelativeElement
from .relative_ramified_FP import RelativeRamifiedFloatingPointElement
from .pow_computer_relative import PowComputer_relative_maker
class pAdicRelativeBaseringInjection(Morphism):
"""
The injection of the unramified base into the two-step extension.
INPUT:
- ``R`` -- an unramified `p`-adic ring or field
- ``S`` -- an eisenstein extension of ``R``.
EXAMPLES::
sage: K.<a> = Qq(125)
sage: R.<x> = K[]
sage: W.<w> = K.extension(x^3 + 15*a*x - 5*(1+a^2))
sage: f = W.coerce_map_from(K); f
Generic morphism:
From: 5-adic Unramified Extension Field in a defined by x^3 + 3*x + 3
To: 5-adic Eisenstein Extension Field in w defined by x^3 + 15*a*x - 5*a^2 - 5 over its base field
"""
def __init__(self, R, S):
"""
Initialization.
EXAMPLES::
sage: K.<a> = Qq(125)
sage: R.<x> = K[]
sage: W.<w> = K.extension(x^3 + 15*a*x - 5*(1+a^2))
sage: f = W.coerce_map_from(K)
sage: type(f)
<class 'sage.rings.padics.relative_extension_leaves.pAdicRelativeBaseringInjection'>
"""
if not R.is_field() or S.is_field():
Morphism.__init__(self, Hom(R, S))
else:
from sage.categories.sets_with_partial_maps import SetsWithPartialMaps
Morphism.__init__(self, Hom(R, S, SetsWithPartialMaps()))
def _call_(self, x):
"""
Evaluation.
EXAMPLES::
sage: K.<a> = Qq(125,2)
sage: R.<x> = K[]
sage: W.<w> = K.extension(x^3 + 15*a*x - 5*(1+a^2))
sage: f = W.coerce_map_from(K)
sage: f(a+5) # indirect doctest
a + (4*a^2 + 4*a + 3)*w^3 + (a + 2)*w^4 + (2*a^2 + 4*a + 2)*w^5 + O(w^6)
"""
if x.is_zero():
return self.codomain()(0,x.precision_absolute())
else:
return self.codomain()([x])
def _call_with_args(self, x, args=(), kwds={}):
"""
This function is used when some precision cap is passed in
(relative or absolute or both).
EXAMPLES::
sage: K.<a> = Qq(125,2)
sage: R.<x> = K[]
sage: W.<w> = K.extension(x^3 + 15*a*x - 5*(1+a^2))
sage: f = W.coerce_map_from(K)
sage: f(5*a,5)
(4*a^2 + a + 3)*w^3 + (a^2 + 2*a)*w^4 + O(w^5)
sage: f(5*a,8,2) # indirect doctest
(4*a^2 + a + 3)*w^3 + (a^2 + 2*a)*w^4 + O(w^5)
"""
return self.codomain()([x], *args, **kwds)
def section(self):
"""
Map back to the base ring.
EXAMPLES::
sage: K.<a> = Qq(125,2)
sage: R.<x> = K[]
sage: W.<w> = K.extension(x^3 + 15*a*x - 5*(1+a^2))
sage: f = W.coerce_map_from(K)
sage: g = f.section()
sage: g(a + w - w)
a + O(5^2)
"""
return pAdicRelativeBaseringSection(self.codomain(), self.domain())
class pAdicRelativeBaseringSection(Morphism):
"""
The map from a two-step extension back to its maximal unramified subextension.
EXAMPLES::
sage: K.<a> = Qq(2^10)
sage: R.<x> = K[]
sage: W.<w> = K.extension(x^4 + 2*a*x^2 - 16*x - 6)
sage: f = K.convert_map_from(W); f
Generic morphism:
From: 2-adic Eisenstein Extension Field in w defined by x^4 + 2*a*x^2 - 16*x - 6 over its base field
To: 2-adic Unramified Extension Field in a defined by x^10 + x^6 + x^5 + x^3 + x^2 + x + 1
"""
def __init__(self, S, R):
"""
Initialization.
EXAMPLES::
sage: K.<a> = Qq(2^10)
sage: R.<x> = K[]
sage: W.<w> = K.extension(x^4 + 2*a*x^2 - 16*x - 6*a)
sage: f = K.convert_map_from(W); type(f)
<class 'sage.rings.padics.relative_extension_leaves.pAdicRelativeBaseringSection'>
"""
from sage.categories.sets_with_partial_maps import SetsWithPartialMaps
Morphism.__init__(self, Hom(S, R, SetsWithPartialMaps()))
def _call_(self, x):
"""
Evaluation.
EXAMPLES::
sage: K.<a> = Qq(2^10)
sage: R.<x> = K[]
sage: W.<w> = K.extension(x^4 + 2*a*x^2 - 16*x - 6*a)
sage: f = K.convert_map_from(W)
sage: f(a + w - w) # indirect doctest
a + O(2^20)
sage: f(w)
Traceback (most recent call last):
...
ValueError: Element not contained in base ring
"""
f = x.polynomial()
if f.degree() > 0:
raise ValueError("Element not contained in base ring")
return f[0]
def _call_with_args(self, x, args=(), kwds={}):
"""
Used when specifying absolute or relative precision.
EXAMPLES::
sage: K.<a> = Qq(2^10)
sage: R.<x> = K[]
sage: W.<w> = K.extension(x^4 + 2*a*x^2 - 16*x - 6*a)
sage: f = K.convert_map_from(W)
sage: f(a, 5) # indirect doctest
a + O(2^5)
"""
return self.codomain()(self._call_(x), *args, **kwds)
class RelativeRamifiedExtensionRingFixedMod(EisensteinExtensionGeneric, pAdicFixedModRingGeneric):
"""
Two-step extension ring with fixed-mod precision.
EXAMPLES::
sage: A.<a> = ZqFM(2^10)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^4 + 2*a*x^2 - 16*x - 6*a); W
2-adic Eisenstein Extension Ring in w defined by x^4 + 2*a*x^2 - 16*x - 6*a over its base ring
sage: w^4 + 2*a*w^2 - 16*w - 6*a == 0
True
"""
def __init__(self, exact_modulus, approx_modulus, prec, print_mode, shift_seed, names, implementation):
"""
Initialization.
EXAMPLES::
sage: A.<a> = ZqFM(5^4)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^3 - 25*(a+1)*x + 10*(a^2+2))
sage: TestSuite(W).run(max_samples=16) # long time
"""
self._exact_modulus = exact_modulus
unram_prec = (prec + approx_modulus.degree() - 1) // approx_modulus.degree()
KFP = approx_modulus.base_ring().change(prec = unram_prec+1)
self.prime_pow = PowComputer_relative_maker(approx_modulus.base_ring().prime(), max(min(unram_prec - 1, 30), 1), unram_prec, prec, False, exact_modulus.change_ring(KFP), shift_seed.change_ring(KFP), 'fixed-mod')
self._implementation = 'Polynomial'
EisensteinExtensionGeneric.__init__(self, approx_modulus, prec, print_mode, names, RelativeRamifiedFixedModElement)
from .relative_ramified_FM import pAdicCoercion_ZZ_FM, pAdicConvert_QQ_FM
self.register_coercion(pAdicCoercion_ZZ_FM(self))
self.register_coercion(pAdicRelativeBaseringInjection(approx_modulus.base_ring(), self))
self.register_conversion(pAdicConvert_QQ_FM(self))
class RelativeRamifiedExtensionRingCappedAbsolute(EisensteinExtensionGeneric, pAdicCappedAbsoluteRingGeneric):
"""
Two-step extension ring with capped absolute precision.
EXAMPLES::
sage: A.<a> = ZqCA(2^10)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^4 + 2*a*x^2 - 16*x - 6*a); W
2-adic Eisenstein Extension Ring in w defined by x^4 + 2*a*x^2 - 16*x - 6*a over its base ring
sage: w^4 + 2*a*w^2 - 16*w - 6*a == 0
True
"""
def __init__(self, exact_modulus, approx_modulus, prec, print_mode, shift_seed, names, implementation):
"""
Initialization.
EXAMPLES::
sage: A.<a> = ZqCA(5^4)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^3 - 25*(a+1)*x + 10*(a^2+2))
sage: TestSuite(W).run(max_samples=16) # long time
"""
self._exact_modulus = exact_modulus
unram_prec = (prec + approx_modulus.degree() - 1) // approx_modulus.degree()
KFP = approx_modulus.base_ring().change(show_prec=False, type='floating-point')
self.prime_pow = PowComputer_relative_maker(approx_modulus.base_ring().prime(), max(min(unram_prec - 1, 30), 1), unram_prec, prec, False, exact_modulus.change_ring(KFP), shift_seed.change_ring(KFP), 'capped-abs')
self._implementation = 'Polynomial'
EisensteinExtensionGeneric.__init__(self, approx_modulus, prec, print_mode, names, RelativeRamifiedCappedAbsoluteElement)
from .relative_ramified_CA import pAdicCoercion_ZZ_CA, pAdicConvert_QQ_CA
self.register_coercion(pAdicCoercion_ZZ_CA(self))
self.register_coercion(pAdicRelativeBaseringInjection(approx_modulus.base_ring(), self))
self.register_conversion(pAdicConvert_QQ_CA(self))
class RelativeRamifiedExtensionRingCappedRelative(EisensteinExtensionGeneric, pAdicCappedRelativeRingGeneric):
"""
Two-step extension ring with capped relative precision.
EXAMPLES::
sage: A.<a> = ZqCR(2^10)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^4 + 2*a*x^2 - 16*x - 6*a); W
2-adic Eisenstein Extension Ring in w defined by x^4 + 2*a*x^2 - 16*x - 6*a over its base ring
sage: w^4 + 2*a*w^2 - 16*w - 6*a == 0
True
"""
def __init__(self, exact_modulus, approx_modulus, prec, print_mode, shift_seed, names, implementation):
"""
Initialization.
EXAMPLES::
sage: A.<a> = ZqCR(5^4)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^3 - 25*(a+1)*x + 10*(a^2+2))
sage: TestSuite(W).run(max_samples=16) # long time
"""
self._exact_modulus = exact_modulus
unram_prec = (prec + approx_modulus.degree() - 1) // approx_modulus.degree()
KFP = approx_modulus.base_ring().change(show_prec=False, type='floating-point')
self.prime_pow = PowComputer_relative_maker(approx_modulus.base_ring().prime(), max(min(unram_prec - 1, 30), 1), unram_prec, prec, False, exact_modulus.change_ring(KFP), shift_seed.change_ring(KFP), 'capped-rel')
self._implementation = 'Polynomial'
EisensteinExtensionGeneric.__init__(self, approx_modulus, prec, print_mode, names, RelativeRamifiedCappedRelativeElement)
from .relative_ramified_CR import pAdicCoercion_ZZ_CR, pAdicConvert_QQ_CR
self.register_coercion(pAdicCoercion_ZZ_CR(self))
self.register_coercion(pAdicRelativeBaseringInjection(approx_modulus.base_ring(), self))
self.register_conversion(pAdicConvert_QQ_CR(self))
class RelativeRamifiedExtensionFieldCappedRelative(EisensteinExtensionGeneric, pAdicCappedRelativeFieldGeneric):
"""
Two-step extension field with capped relative precision.
EXAMPLES::
sage: A.<a> = QqCR(2^10)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^4 + 2*a*x^2 - 16*x - 6*a); W
2-adic Eisenstein Extension Field in w defined by x^4 + 2*a*x^2 - 16*x - 6*a over its base field
sage: w^4 + 2*a*w^2 - 16*w - 6*a == 0
True
"""
def __init__(self, exact_modulus, approx_modulus, prec, print_mode, shift_seed, names, implementation):
"""
Initialization.
EXAMPLES::
sage: A.<a> = QqCR(5^4)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^3 - 25*(a+1)*x + 10*(a^2+2))
sage: TestSuite(W).run(max_samples=16) # long time
"""
self._exact_modulus = exact_modulus
unram_prec = (prec + approx_modulus.degree() - 1) // approx_modulus.degree()
KFP = approx_modulus.base_ring().change(show_prec=False, type='floating-point')
self.prime_pow = PowComputer_relative_maker(approx_modulus.base_ring().prime(), max(min(unram_prec - 1, 30), 1), unram_prec, prec, True, exact_modulus.change_ring(KFP), shift_seed.change_ring(KFP), 'capped-rel')
self._implementation = 'Polynomial'
EisensteinExtensionGeneric.__init__(self, approx_modulus, prec, print_mode, names, RelativeRamifiedCappedRelativeElement)
from .relative_ramified_CR import pAdicCoercion_ZZ_CR, pAdicCoercion_QQ_CR
self.register_coercion(pAdicCoercion_ZZ_CR(self))
self.register_coercion(pAdicRelativeBaseringInjection(approx_modulus.base_ring(), self))
# We also want to convert down to the ring of integers: this is used in teichmuller expansion
self.register_coercion(pAdicRelativeBaseringInjection(approx_modulus.base_ring().integer_ring(), self))
self.register_coercion(pAdicCoercion_QQ_CR(self))
class RelativeRamifiedExtensionRingFloatingPoint(EisensteinExtensionGeneric, pAdicFloatingPointRingGeneric):
"""
Two-step extension ring with floating point precision.
EXAMPLES::
sage: A.<a> = ZqFP(2^10)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^4 + 2*a*x^2 - 16*x - 6*a); W
2-adic Eisenstein Extension Ring in w defined by x^4 + 2*a*x^2 - 16*x - 6*a over its base ring
sage: w^4 + 2*a*w^2 - 16*w - 6*a == 0
True
"""
def __init__(self, exact_modulus, approx_modulus, prec, print_mode, shift_seed, names, implementation):
"""
Initialization.
EXAMPLES::
sage: A.<a> = ZqFP(5^4)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^3 - 25*(a+1)*x + 10*(a^2+2))
sage: TestSuite(W).run(max_samples=16) # long time
"""
self._exact_modulus = exact_modulus
unram_prec = (prec + approx_modulus.degree() - 1) // approx_modulus.degree()
KFP = approx_modulus.base_ring()#.change(field=False, show_prec=False)
self.prime_pow = PowComputer_relative_maker(approx_modulus.base_ring().prime(), max(min(unram_prec - 1, 30), 1), unram_prec, prec, False, exact_modulus.change_ring(KFP), shift_seed.change_ring(KFP), 'floating-point')
self._implementation = 'Polynomial'
EisensteinExtensionGeneric.__init__(self, approx_modulus, prec, print_mode, names, RelativeRamifiedFloatingPointElement)
from .relative_ramified_FP import pAdicCoercion_ZZ_FP, pAdicConvert_QQ_FP
self.register_coercion(pAdicCoercion_ZZ_FP(self))
self.register_coercion(pAdicRelativeBaseringInjection(approx_modulus.base_ring(), self))
self.register_conversion(pAdicConvert_QQ_FP(self))
class RelativeRamifiedExtensionFieldFloatingPoint(EisensteinExtensionGeneric, pAdicFloatingPointFieldGeneric):
"""
Two-step extension field with floating point precision.
EXAMPLES::
sage: A.<a> = QqFP(2^10)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^4 + 2*a*x^2 - 16*x - 6*a); W
2-adic Eisenstein Extension Field in w defined by x^4 + 2*a*x^2 - 16*x - 6*a over its base field
sage: w^4 + 2*a*w^2 - 16*w - 6*a == 0
True
"""
def __init__(self, exact_modulus, approx_modulus, prec, print_mode, shift_seed, names, implementation):
"""
Initialization.
EXAMPLES::
sage: A.<a> = QqFP(5^4)
sage: R.<x> = A[]
sage: W.<w> = A.extension(x^3 - 25*(a+1)*x + 10*(a^2+2))
sage: TestSuite(W).run(max_samples=16) # long time
"""
self._exact_modulus = exact_modulus
unram_prec = (prec + approx_modulus.degree() - 1) // approx_modulus.degree()
KFP = approx_modulus.base_ring()#.change(field=False, show_prec=False)
self.prime_pow = PowComputer_relative_maker(approx_modulus.base_ring().prime(), max(min(unram_prec - 1, 30), 1), unram_prec, prec, True, exact_modulus.change_ring(KFP), shift_seed.change_ring(KFP), 'floating-point')
self._implementation = 'Polynomial'
EisensteinExtensionGeneric.__init__(self, approx_modulus, prec, print_mode, names, RelativeRamifiedFloatingPointElement)
from .relative_ramified_FP import pAdicCoercion_ZZ_FP, pAdicCoercion_QQ_FP
self.register_coercion(pAdicCoercion_ZZ_FP(self))
self.register_coercion(pAdicRelativeBaseringInjection(approx_modulus.base_ring(), self))
# We also want to convert down to the ring of integers: this is used in teichmuller expansion
self.register_coercion(pAdicRelativeBaseringInjection(approx_modulus.base_ring().integer_ring(), self))
self.register_coercion(pAdicCoercion_QQ_FP(self)) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/padics/relative_extension_leaves.py | 0.799951 | 0.338159 | relative_extension_leaves.py | pypi |
r"""
Introduction to the `p`-adics
==========================================
This tutorial outlines what you need to know in order to use
`p`-adics in Sage effectively.
Our goal is to create a rich structure of different options that
will reflect the mathematical structures of the `p`-adics.
This is very much a work in progress: some of the classes that we
eventually intend to include have not yet been written, and some of
the functionality for classes in existence has not yet been
implemented. In addition, while we strive for perfect code, bugs
(both subtle and not-so-subtle) continue to evade our clutches. As
a user, you serve an important role. By writing non-trivial code
that uses the `p`-adics, you both give us insight into what
features are actually used and also expose problems in the code for
us to fix.
Our design philosophy has been to create a robust, usable interface
working first, with simple-minded implementations underneath. We
want this interface to stabilize rapidly, so that users' code does
not have to change. Once we get the framework in place, we can go
back and work on the algorithms and implementations underneath. All
of the current `p`-adic code is currently written in pure
Python, which means that it does not have the speed advantage of
compiled code. Thus our `p`-adics can be painfully slow at
times when you're doing real computations. However, finding and
fixing bugs in Python code is *far* easier than finding and fixing
errors in the compiled alternative within Sage (Cython), and Python
code is also faster and easier to write. We thus have significantly
more functionality implemented and working than we would have if we
had chosen to focus initially on speed. And at some point in the
future, we will go back and improve the speed. Any code you have
written on top of our `p`-adics will then get an immediate
performance enhancement.
If you do find bugs, have feature requests or general comments,
please email sage-support@groups.google.com or
roed@math.harvard.edu.
Terminology and types of `p`-adics
==========================================
To write down a general `p`-adic element completely would
require an infinite amount of data. Since computers do not have
infinite storage space, we must instead store finite approximations
to elements. Thus, just as in the case of floating point numbers
for representing reals, we have to store an element to a finite
precision level. The different ways of doing this account for the
different types of `p`-adics.
We can think of `p`-adics in two ways. First, as a
projective limit of finite groups:
.. MATH::
\ZZ_p = \lim_{\leftarrow n} \ZZ/p^n\ZZ.
Secondly, as Cauchy sequences of rationals (or integers, in the
case of `\ZZ_p`) under the `p`-adic metric.
Since we only need to consider these sequences up to equivalence,
this second way of thinking of the `p`-adics is the same as
considering power series in `p` with integral coefficients
in the range `0` to `p-1`. If we only allow
nonnegative powers of `p` then these power series converge
to elements of `\ZZ_p`, and if we allow bounded
negative powers of `p` then we get `\QQ_p`.
Both of these representations give a natural way of thinking about
finite approximations to a `p`-adic element. In the first
representation, we can just stop at some point in the projective
limit, giving an element of `\ZZ/p^n\ZZ`. As
`\ZZ_p / p^n\ZZ_p \cong \ZZ/p^n\ZZ`, this
is equivalent to specifying our element modulo
`p^n\ZZ_p`.
The *absolute precision* of a finite approximation
`\bar{x} \in \ZZ/p^n\ZZ` to `x \in \ZZ_p`
is the non-negative integer `n`.
In the second representation, we can achieve the same thing by
truncating a series
.. MATH::
a_0 + a_1 p + a_2 p^2 + \cdots
at `p^n`, yielding
.. MATH::
a_0 + a_1 p + \cdots + a_{n-1} p^{n-1} + O(p^n).
As above, we call this `n` the absolute precision of our
element.
Given any `x \in \QQ_p` with `x \ne 0`, we
can write `x = p^v u` where `v \in \ZZ` and
`u \in \ZZ_p^{\times}`. We could thus also store an element
of `\QQ_p` (or `\ZZ_p`) by storing
`v` and a finite approximation of `u`. This
motivates the following definition: the *relative precision* of an
approximation to `x` is defined as the absolute precision
of the approximation minus the valuation of `x`. For
example, if
`x = a_k p^k + a_{k+1} p^{k+1} +
\cdots + a_{n-1} p^{n-1} + O(p^n)`
then the absolute precision of `x` is `n`, the
valuation of `x` is `k` and the relative precision
of `x` is `n-k`.
There are three different representations of `\ZZ_p`
in Sage and one representation of `\QQ_p`:
- the fixed modulus ring
- the capped absolute precision ring
- the capped relative precision ring, and
- the capped relative precision field.
Fixed Modulus Rings
-------------------
The first, and simplest, type of `\ZZ_p` is basically
a wrapper around `\ZZ/p^n\ZZ`, providing a unified
interface with the rest of the `p`-adics. You specify a
precision, and all elements are stored to that absolute precision.
If you perform an operation that would normally lose precision, the
element does not track that it no longer has full precision.
The fixed modulus ring provides the lowest level of convenience,
but it is also the one that has the lowest computational overhead.
Once we have ironed out some bugs, the fixed modulus elements will
be those most optimized for speed.
As with all of the implementations of `\ZZ_p`, one
creates a new ring using the constructor ``Zp``, and passing in
``'fixed-mod'`` for the ``type`` parameter. For example,
::
sage: R = Zp(5, prec = 10, type = 'fixed-mod', print_mode = 'series')
sage: R
5-adic Ring of fixed modulus 5^10
One can create elements as follows::
sage: a = R(375)
sage: a
3*5^3
sage: b = R(105)
sage: b
5 + 4*5^2
Now that we have some elements, we can do arithmetic in the ring.
::
sage: a + b
5 + 4*5^2 + 3*5^3
sage: a * b
3*5^4 + 2*5^5 + 2*5^6
Floor division (//) divides even though the result isn't really
known to the claimed precision; note that division isn't defined::
sage: a // 5
3*5^2
::
sage: a / 5
Traceback (most recent call last):
...
ValueError: cannot invert non-unit
Since elements don't actually store their actual precision, one can
only divide by units::
sage: a / 2
4*5^3 + 2*5^4 + 2*5^5 + 2*5^6 + 2*5^7 + 2*5^8 + 2*5^9
sage: a / b
Traceback (most recent call last):
...
ValueError: cannot invert non-unit
If you want to divide by a non-unit, do it using the ``//``
operator::
sage: a // b
3*5^2 + 3*5^3 + 2*5^5 + 5^6 + 4*5^7 + 2*5^8 + 3*5^9
Capped Absolute Rings
---------------------
The second type of implementation of `\ZZ_p` is
similar to the fixed modulus implementation, except that individual
elements track their known precision. The absolute precision of
each element is limited to be less than the precision cap of the
ring, even if mathematically the precision of the element would be
known to greater precision (see Appendix A for the reasons for the
existence of a precision cap).
Once again, use ``Zp`` to create a capped absolute `p`-adic
ring.
::
sage: R = Zp(5, prec = 10, type = 'capped-abs', print_mode = 'series')
sage: R
5-adic Ring with capped absolute precision 10
We can do similar things as in the fixed modulus case::
sage: a = R(375)
sage: a
3*5^3 + O(5^10)
sage: b = R(105)
sage: b
5 + 4*5^2 + O(5^10)
sage: a + b
5 + 4*5^2 + 3*5^3 + O(5^10)
sage: a * b
3*5^4 + 2*5^5 + 2*5^6 + O(5^10)
sage: c = a // 5
sage: c
3*5^2 + O(5^9)
Note that when we divided by 5, the precision of ``c`` dropped.
This lower precision is now reflected in arithmetic.
::
sage: c + b
5 + 2*5^2 + 5^3 + O(5^9)
Division is allowed: the element that results is a capped relative
field element, which is discussed in the next section::
sage: 1 / (c + b)
5^-1 + 3 + 2*5 + 5^2 + 4*5^3 + 4*5^4 + 3*5^6 + O(5^7)
Capped Relative Rings and Fields
--------------------------------
Instead of restricting the absolute precision of elements (which
doesn't make much sense when elements have negative valuations),
one can cap the relative precision of elements. This is analogous
to floating point representations of real numbers. As in the reals,
multiplication works very well: the valuations add and the relative
precision of the product is the minimum of the relative precisions
of the inputs. Addition, however, faces similar issues as floating
point addition: relative precision is lost when lower order terms
cancel.
To create a capped relative precision ring, use ``Zp`` as before.
To create capped relative precision fields, use ``Qp``.
::
sage: R = Zp(5, prec = 10, type = 'capped-rel', print_mode = 'series')
sage: R
5-adic Ring with capped relative precision 10
sage: K = Qp(5, prec = 10, type = 'capped-rel', print_mode = 'series')
sage: K
5-adic Field with capped relative precision 10
We can do all of the same operations as in the other two cases, but
precision works a bit differently: the maximum precision of an
element is limited by the precision cap of the ring.
::
sage: a = R(375)
sage: a
3*5^3 + O(5^13)
sage: b = K(105)
sage: b
5 + 4*5^2 + O(5^11)
sage: a + b
5 + 4*5^2 + 3*5^3 + O(5^11)
sage: a * b
3*5^4 + 2*5^5 + 2*5^6 + O(5^14)
sage: c = a // 5
sage: c
3*5^2 + O(5^12)
sage: c + 1
1 + 3*5^2 + O(5^10)
As with the capped absolute precision rings, we can divide,
yielding a capped relative precision field element.
::
sage: 1 / (c + b)
5^-1 + 3 + 2*5 + 5^2 + 4*5^3 + 4*5^4 + 3*5^6 + 2*5^7 + 5^8 + O(5^9)
Unramified Extensions
---------------------
One can create unramified extensions of `\ZZ_p` and
`\QQ_p` using the functions ``Zq`` and ``Qq``.
In addition to requiring a prime power as the first argument,
``Zq`` also requires a name for the generator of the residue field.
One can specify this name as follows::
sage: R.<c> = Zq(125, prec = 20); R
5-adic Unramified Extension Ring in c defined by x^3 + 3*x + 3
Eisenstein Extensions
---------------------
It is also possible to create Eisenstein extensions of `\ZZ_p`
and `\QQ_p`. In order to do so, create the ground field first::
sage: R = Zp(5, 2)
Then define the polynomial yielding the desired extension.::
sage: S.<x> = ZZ[]
sage: f = x^5 - 25*x^3 + 15*x - 5
Finally, use the ``ext`` function on the ground field to create the
desired extension.::
sage: W.<w> = R.ext(f)
You can do arithmetic in this Eisenstein extension::
sage: (1 + w)^7
1 + 2*w + w^2 + w^5 + 3*w^6 + 3*w^7 + 3*w^8 + w^9 + O(w^10)
Note that the precision cap increased by a factor of 5, since the
ramification index of this extension over `\ZZ_p` is 5.
""" | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/padics/tutorial.py | 0.936256 | 0.976957 | tutorial.py | pypi |
import os
import sage.misc.misc
def coefficients_to_power_sums(n, m, a):
r"""
Takes the list a, representing a list of initial coefficients of
a (monic) polynomial of degree n, and returns the power sums
of the roots of f up to (m-1)th powers.
INPUT:
- n -- integer, the degree
- a -- list of integers, the coefficients
OUTPUT:
list of integers.
.. NOTE::
This uses Newton's relations, which are classical.
AUTHORS:
- John Voight (2007-09-19)
EXAMPLES::
sage: from sage.rings.number_field.totallyreal_phc import coefficients_to_power_sums
sage: coefficients_to_power_sums(3,2,[1,5,7])
[3, -7, 39]
sage: coefficients_to_power_sums(5,4,[1,5,7,9,8])
[5, -8, 46, -317, 2158]
"""
S = [n] + [0]*m
for k in range(1,m+1):
S[k] = -sum([a[n-i]*S[k-i] for i in range(1,k)])-k*a[n-k]
return S
def __lagrange_bounds_phc(n, m, a, tmpfile=None):
r"""
This function determines the bounds on the roots in
the enumeration of totally real fields via Lagrange multipliers.
It is used internally by the main function
enumerate_totallyreal_fields_prim(), which should be consulted for
further information.
INPUT:
- k -- integer, the index of the next coefficient
- a -- list of integers, the coefficients
OUTPUT:
the lower and upper bounds as real numbers.
.. NOTE::
See Cohen [Coh2000]_ for the general idea and unpublished work of the
author for more detail.
AUTHORS:
- John Voight (2007-09-19)
EXAMPLES::
sage: from sage.rings.number_field.totallyreal_phc import __lagrange_bounds_phc
sage: __lagrange_bounds_phc(3,5,[8,1,2,0,1]) # optional - phc
[]
sage: x, y = __lagrange_bounds_phc(3,2,[8,1,2,0,1]) # optional - phc
sage: x # optional - phc
-1.3333333333333299
sage: y < 0.00000001 # optional - phc
True
sage: __lagrange_bounds_phc(3,1,[8,1,2,0,1]) # optional - phc
[]
"""
# Compute power sums.
S = coefficients_to_power_sums(n,m,a)
# Look for phc.
fi, fo = os.popen2('which phc')
find_phc = fo.readlines()
fi.close()
fo.close()
if find_phc == []:
raise RuntimeError("PHCpack not installed.")
# Initialization.
if tmpfile is None:
tmpfile = sage.misc.misc.tmp_filename()
f = open(tmpfile + '.phc', 'w')
f.close()
output_data = []
# By the method of Lagrange multipliers, if we maximize x_n subject to
# S_j(x) = S[j] (j = 1, ..., m),
# then there are at most m-1 distinct values amongst the x_i.
# Therefore we must solve the implied equations for each partition of n-1
# into m-1 parts.
for P in sage.combinat.partition.Partitions(n-1,length=m-1):
f = open(tmpfile, 'w')
# First line: number of variables/equations
f.write('%d'%m + '\n')
# In the next m-1 lines, write the equation S_j(x) = S[j]
for j in range(1,m+1):
for i in range(m-1):
f.write('%d'%P[i] + '*x%d'%i + '**%d'%j + ' + ')
f.write('xn**%d'%j + ' - (%d'%S[j] + ');\n')
f.close()
os.remove(tmpfile + '.phc')
os.popen('phc -b ' + tmpfile + ' ' + tmpfile + '.phc')
f = open(tmpfile + '.phc', 'r')
f_str = f.read()
pos = f_str.find('= real ')
crits = []
while pos != -1:
posl = f_str.rfind('xn', 0, pos)
f_str_split = f_str[posl:pos].split()
crits += [float(f_str_split[2])]
pos = f_str.find('= real ', pos+1)
if len(crits) > 0:
output_data += [[P, min(crits), max(crits)]]
if len(output_data) > 0:
return [min([v[1] for v in output_data]), max([v[2] for v in output_data])]
else:
return [] | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/number_field/totallyreal_phc.py | 0.538983 | 0.69938 | totallyreal_phc.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.misc.superseded import deprecation
from sage.rings.homset import RingHomset_generic
from sage.rings.number_field.morphism import (NumberFieldHomomorphism_im_gens,
RelativeNumberFieldHomomorphism_from_abs,
CyclotomicFieldHomomorphism_im_gens)
from sage.rings.integer import Integer
from sage.rings.finite_rings.integer_mod_ring import Zmod
from sage.structure.sequence import Sequence
class NumberFieldHomset(RingHomset_generic):
"""
Set of homomorphisms with domain a given number field.
TESTS::
sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b'))
sage: TestSuite(H).run()
"""
Element = NumberFieldHomomorphism_im_gens
def __init__(self, R, S, category=None):
"""
TESTS:
Check that :trac:`23647` is fixed::
sage: K.<a, b> = NumberField([x^2 - 2, x^2 - 3])
sage: e, u, v, w = End(K)
sage: e.abs_hom().parent().category()
Category of homsets of number fields
sage: (v*v).abs_hom().parent().category()
Category of homsets of number fields
"""
if category is None:
from sage.categories.fields import Fields
from sage.categories.number_fields import NumberFields
if S in NumberFields():
category = NumberFields()
elif S in Fields():
category = Fields()
RingHomset_generic.__init__(self, R, S, category)
def _element_constructor_(self, x, check=True):
"""
Construct an element of ``self`` from ``x``.
EXAMPLES::
sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b'))
sage: phi = H([H.domain().gen()]); phi
Ring morphism:
From: Number Field in a with defining polynomial x^2 + 1 with a = 1*I
To: Number Field in b with defining polynomial x^2 + 1 with b = 1*I
Defn: a |--> b
sage: H1 = End(QuadraticField(-1, 'a'))
sage: H1.coerce(loads(dumps(H1[1])))
Ring endomorphism of Number Field in a with defining polynomial x^2 + 1 with a = 1*I
Defn: a |--> -a
TESTS:
We can move morphisms between categories::
sage: f = H1.an_element()
sage: g = End(H1.domain(), category=Rings())(f)
sage: f == End(H1.domain(), category=NumberFields())(g)
True
Check that :trac:`28869` is fixed::
sage: K.<a> = CyclotomicField(8)
sage: L.<b> = K.absolute_field()
sage: H = L.Hom(K)
sage: phi = L.structure()[0]
sage: phi.parent() is H
True
sage: H(phi)
Isomorphism given by variable name change map:
From: Number Field in b with defining polynomial x^4 + 1
To: Cyclotomic Field of order 8 and degree 4
sage: R.<x> = L[]
sage: (x^2 + b).change_ring(phi)
x^2 + a
"""
if not isinstance(x, NumberFieldHomomorphism_im_gens):
return self.element_class(self, x, check=check)
from sage.categories.number_fields import NumberFields
from sage.categories.rings import Rings
if (x.parent() == self or
(x.domain() == self.domain() and x.codomain() == self.codomain() and
# This would be the better check, however it returns False currently:
# self.homset_category().is_full_subcategory(x.category_for())
# So we check instead that this is a morphism anywhere between
# Rings and NumberFields where the hom spaces do not change.
NumberFields().is_subcategory(self.homset_category()) and
self.homset_category().is_subcategory(Rings()) and
NumberFields().is_subcategory(x.category_for()) and
x.category_for().is_subcategory(Rings()))):
return self.element_class(self, x.im_gens(), check=False)
def _an_element_(self):
r"""
Return an element of this set of embeddings.
EXAMPLES::
sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b'))
sage: H.an_element() # indirect doctest
Ring morphism:
From: Number Field in a with defining polynomial x^2 + 1 with a = 1*I
To: Number Field in b with defining polynomial x^2 + 1 with b = 1*I
Defn: a |--> b
sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-2, 'b'))
sage: H.an_element()
Traceback (most recent call last):
...
EmptySetError: There is no morphism from Number Field in a with defining polynomial x^2 + 1 with a = 1*I to Number Field in b with defining polynomial x^2 + 2 with b = 1.414213562373095?*I
"""
L = self.list()
if len(L) != 0:
return L[0]
else:
from sage.categories.sets_cat import EmptySetError
raise EmptySetError("There is no morphism from {} to {}".format(
self.domain(), self.codomain()))
def _repr_(self):
r"""
String representation of this homset.
EXAMPLES::
sage: repr(Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b'))) # indirect doctest
'Set of field embeddings from Number Field in a with defining polynomial x^2 + 1 with a = 1*I to Number Field in b with defining polynomial x^2 + 1 with b = 1*I'
sage: repr(Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'a'))) # indirect doctest
'Automorphism group of Number Field in a with defining polynomial x^2 + 1 with a = 1*I'
"""
D = self.domain()
C = self.codomain()
if C == D:
return "Automorphism group of {}".format(D)
else:
return "Set of field embeddings from {} to {}".format(D, C)
def order(self):
"""
Return the order of this set of field homomorphism.
EXAMPLES::
sage: k.<a> = NumberField(x^2 + 1)
sage: End(k)
Automorphism group of Number Field in a with defining polynomial x^2 + 1
sage: End(k).order()
2
sage: k.<a> = NumberField(x^3 + 2)
sage: End(k).order()
1
sage: K.<a> = NumberField( [x^3 + 2, x^2 + x + 1] )
sage: End(K).order()
6
"""
return Integer(len(self.list()))
cardinality = order
@cached_method
def list(self):
"""
Return a list of all the elements of self.
EXAMPLES::
sage: K.<a> = NumberField(x^3 - 3*x + 1)
sage: End(K).list()
[
Ring endomorphism of Number Field in a with defining polynomial x^3 - 3*x + 1
Defn: a |--> a,
Ring endomorphism of Number Field in a with defining polynomial x^3 - 3*x + 1
Defn: a |--> a^2 - 2,
Ring endomorphism of Number Field in a with defining polynomial x^3 - 3*x + 1
Defn: a |--> -a^2 - a + 2
]
sage: Hom(K, CyclotomicField(9))[0] # indirect doctest
Ring morphism:
From: Number Field in a with defining polynomial x^3 - 3*x + 1
To: Cyclotomic Field of order 9 and degree 6
Defn: a |--> -zeta9^4 + zeta9^2 - zeta9
An example where the codomain is a relative extension::
sage: K.<a> = NumberField(x^3 - 2)
sage: L.<b> = K.extension(x^2 + 3)
sage: Hom(K, L).list()
[
Ring morphism:
From: Number Field in a with defining polynomial x^3 - 2
To: Number Field in b with defining polynomial x^2 + 3 over its base field
Defn: a |--> a,
Ring morphism:
From: Number Field in a with defining polynomial x^3 - 2
To: Number Field in b with defining polynomial x^2 + 3 over its base field
Defn: a |--> -1/2*a*b - 1/2*a,
Ring morphism:
From: Number Field in a with defining polynomial x^3 - 2
To: Number Field in b with defining polynomial x^2 + 3 over its base field
Defn: a |--> 1/2*a*b - 1/2*a
]
"""
D = self.domain()
C = self.codomain()
if D.degree().divides(C.absolute_degree()):
roots = D.polynomial().roots(ring=C, multiplicities=False)
v = [D.hom([r], codomain=C, check=False) for r in roots]
else:
v = []
return Sequence(v, universe=self, check=False, immutable=True, cr=v!=[])
def __getitem__(self, n):
r"""
Return the ``n``th element of ``self.list()``.
EXAMPLES::
sage: End(CyclotomicField(37))[3] # indirect doctest
Ring endomorphism of Cyclotomic Field of order 37 and degree 36
Defn: zeta37 |--> zeta37^4
"""
return self.list()[n]
class RelativeNumberFieldHomset(NumberFieldHomset):
"""
Set of homomorphisms with domain a given relative number field.
EXAMPLES:
We construct a homomorphism from a relative field by giving
the image of a generator::
sage: L.<cuberoot2, zeta3> = CyclotomicField(3).extension(x^3 - 2)
sage: phi = L.hom([cuberoot2 * zeta3]); phi
Relative number field endomorphism of Number Field in cuberoot2 with defining polynomial x^3 - 2 over its base field
Defn: cuberoot2 |--> zeta3*cuberoot2
zeta3 |--> zeta3
sage: phi(cuberoot2 + zeta3)
zeta3*cuberoot2 + zeta3
In fact, this phi is a generator for the Kummer Galois group of this
cyclic extension::
sage: phi(phi(cuberoot2 + zeta3))
(-zeta3 - 1)*cuberoot2 + zeta3
sage: phi(phi(phi(cuberoot2 + zeta3)))
cuberoot2 + zeta3
"""
Element = RelativeNumberFieldHomomorphism_from_abs
def _element_constructor_(self, x, base_map=None, base_hom=None, check=True):
"""
Construct an element of ``self`` from ``x``.
INPUT:
- ``x`` -- one of the following (here `L` is the domain of
``self`` and `K` is its base field):
- A homomorphism from `L`.
- A homomorphism from the absolute number field
corresponding to `L`.
- An element of a ring into which `K` coerces, specifying
the image of the distinguished generator of `L` over `K`.
- A pair consisting of an element of a ring `R` and a
homomorphism from `K` to `R`.
EXAMPLES::
sage: K.<a> = NumberField(x^2 + 1)
sage: L.<b> = K.extension(x^4 - 2)
sage: E = End(L)
sage: E(E[0])
Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field
Defn: b |--> b
a |--> a
sage: E(L.absolute_field('c').hom(b+a, L))
Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field
Defn: b |--> b
a |--> -a
sage: E(-b*a)
Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field
Defn: b |--> -a*b
a |--> a
sage: E(-a*b, K.hom([-a]))
Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field
Defn: b |--> -a*b
a |--> -a
You can specify a map on the base field::
sage: R.<x> = ZZ[]
sage: K.<i> = NumberField(x^2 + 1)
sage: L.<b> = K.extension(x^2-17)
sage: cc = K.hom([-i])
sage: phi = L.hom([-b],base_map=cc); phi
Relative number field endomorphism of Number Field in b with defining polynomial x^2 - 17 over its base field
Defn: b |--> -b
i |--> -i
Using ``check=False``, it is possible to construct
homomorphisms into fields such as ``CC`` where calculations
are only approximate::
sage: K.<a> = QuadraticField(-7)
sage: f = K.hom([CC(sqrt(-7))], check=False)
sage: x = polygen(K)
sage: L.<b> = K.extension(x^2 - a - 5)
sage: L.Hom(CC)(f(a + 5).sqrt(), f, check=False)
Relative number field morphism:
From: Number Field in b with defining polynomial x^2 - a - 5 over its base field
To: Complex Field with 53 bits of precision
Defn: b |--> 2.30833860703888 + 0.573085617291335*I
a |--> -8.88178419700125e-16 + 2.64575131106459*I
TESTS::
sage: x = polygen(QQ)
sage: L.<a, b> = NumberField([x^3 - x + 1, x^2 + 23])
sage: E = End(L)
sage: E.coerce(loads(dumps(E[0])))
Relative number field endomorphism of Number Field in a with defining polynomial x^3 - x + 1 over its base field
Defn: a |--> a
b |--> b
Check that :trac:`28869` is fixed::
sage: K.<a,b> = NumberField((x^2 + 1, x^2 - 2))
sage: L.<c> = K.absolute_field()
sage: H = K.Hom(L)
sage: phi = L.structure()[1]; phi
Isomorphism map:
From: Number Field in a with defining polynomial x^2 + 1 over its base field
To: Number Field in c with defining polynomial x^4 - 2*x^2 + 9
sage: H(phi) is phi
True
sage: R.<x> = K[]
sage: (x^2 + a).change_ring(phi)
x^2 + 1/6*c^3 + 1/6*c
"""
if base_hom is not None:
deprecation(26105, "Use base_map rather than base_hom")
base_map = base_hom
if isinstance(x, NumberFieldHomomorphism_im_gens):
# Then it must be a homomorphism from the corresponding
# absolute number field
if x.domain() != self.domain().absolute_field(x.domain().variable_name()):
raise TypeError("domain of morphism must be absolute field of domain.")
if x.codomain() != self.codomain():
raise ValueError("codomain of absolute homomorphism must be codomain of this homset.")
return self.element_class(self, x)
if (isinstance(x, RelativeNumberFieldHomomorphism_from_abs)
and x.parent() == self):
return self.element_class(self, x.abs_hom())
if base_map is None:
base_map = self.default_base_hom()
if isinstance(x, (list, tuple)) and len(x) == 1:
x = x[0]
if check:
x = self.codomain()(x)
return self._from_im(x, base_map=base_map, check=check)
def _from_im(self, im_gen, base_map, check=True):
"""
Return the homomorphism that acts on the base as given and
sends the generator of the domain to im_gen.
EXAMPLES::
sage: K.<a> = NumberField(x^2 + 23)
sage: L.<b> = K.extension(x^3 - x + 1)
sage: End(L)._from_im( -3/23*a*b^2 + (-9/46*a - 1/2)*b + 2/23*a, K.hom([-a], K))
Relative number field endomorphism of Number Field in b with defining polynomial x^3 - x + 1 over its base field
Defn: b |--> -3/23*a*b^2 + (-9/46*a - 1/2)*b + 2/23*a
a |--> -a
"""
K = self.domain().absolute_field('a')
from_K, to_K = K.structure()
a = from_K(K.gen())
# We just have to figure out where a goes to
# under the morphism defined by im_gen and base_map.
L = self.codomain()
R = L['x']
f = R([base_map(x) for x in a.list()])
b = f(im_gen)
abs_hom = K.hom([b], check=check)
return self.element_class(self, abs_hom)
@cached_method
def default_base_hom(self):
r"""
Pick an embedding of the base field of self into the codomain of this
homset. This is done in an essentially arbitrary way.
EXAMPLES::
sage: L.<a, b> = NumberField([x^3 - x + 1, x^2 + 23])
sage: M.<c> = NumberField(x^4 + 80*x^2 + 36)
sage: Hom(L, M).default_base_hom()
Ring morphism:
From: Number Field in b with defining polynomial x^2 + 23
To: Number Field in c with defining polynomial x^4 + 80*x^2 + 36
Defn: b |--> 1/12*c^3 + 43/6*c
TESTS:
Check that :trac:`30518` is fixed::
sage: K.<i> = QuadraticField(-1, embedding=QQbar.gen())
sage: L.<a> = K.extension(x^2 - 6*x - 4)
sage: a0, a1 = a.galois_conjugates(QQbar)
sage: f0 = hom(L, QQbar, a0)
sage: assert f0(i) == QQbar.gen()
sage: f1 = hom(L, QQbar, a1)
sage: assert f1(i) == QQbar.gen()
sage: K.<i> = QuadraticField(-1, embedding=-QQbar.gen())
sage: L.<a> = K.extension(x^2 - 6*x - 4)
sage: a0, a1 = a.galois_conjugates(QQbar)
sage: f0 = hom(L, QQbar, a0)
sage: assert f0(i) == -QQbar.gen()
sage: f1 = hom(L, QQbar, a1)
sage: assert f1(i) == -QQbar.gen()
"""
K = self.domain().base_field()
C = self.codomain()
f = C.coerce_map_from(K)
if f is not None:
return f
v = K.embeddings(C)
if len(v) == 0:
raise ValueError("no way to map base field to codomain.")
return v[0]
@cached_method
def list(self):
"""
Return a list of all the elements of self (for which the domain
is a relative number field).
EXAMPLES::
sage: K.<a, b> = NumberField([x^2 + x + 1, x^3 + 2])
sage: End(K).list()
[
Relative number field endomorphism of Number Field in a with defining polynomial x^2 + x + 1 over its base field
Defn: a |--> a
b |--> b,
...
Relative number field endomorphism of Number Field in a with defining polynomial x^2 + x + 1 over its base field
Defn: a |--> a
b |--> -b*a - b
]
An example with an absolute codomain::
sage: K.<a, b> = NumberField([x^2 - 3, x^2 + 2])
sage: Hom(K, CyclotomicField(24, 'z')).list()
[
Relative number field morphism:
From: Number Field in a with defining polynomial x^2 - 3 over its base field
To: Cyclotomic Field of order 24 and degree 8
Defn: a |--> z^6 - 2*z^2
b |--> -z^5 - z^3 + z,
...
Relative number field morphism:
From: Number Field in a with defining polynomial x^2 - 3 over its base field
To: Cyclotomic Field of order 24 and degree 8
Defn: a |--> -z^6 + 2*z^2
b |--> z^5 + z^3 - z
]
"""
D = self.domain()
C = self.codomain()
D_abs = D.absolute_field('a')
v = [self(f, check=False) for f in D_abs.Hom(C).list()]
return Sequence(v, universe=self, check=False, immutable=True, cr=v!=[])
class CyclotomicFieldHomset(NumberFieldHomset):
"""
Set of homomorphisms with domain a given cyclotomic field.
EXAMPLES::
sage: End(CyclotomicField(16))
Automorphism group of Cyclotomic Field of order 16 and degree 8
"""
Element = CyclotomicFieldHomomorphism_im_gens
def _element_constructor_(self, x, check=True):
"""
Construct an element of ``self`` from ``x``.
EXAMPLES::
sage: K.<z> = CyclotomicField(16)
sage: E = End(K)
sage: E(E[0])
Ring endomorphism of Cyclotomic Field of order 16 and degree 8
Defn: z |--> z
sage: E(z^5)
Ring endomorphism of Cyclotomic Field of order 16 and degree 8
Defn: z |--> z^5
sage: E(z^6)
Traceback (most recent call last):
...
ValueError: relations do not all (canonically) map to 0 under map determined by images of generators
sage: E = End(CyclotomicField(16))
sage: E.coerce(E[0])
Ring endomorphism of Cyclotomic Field of order 16 and degree 8
Defn: zeta16 |--> zeta16
sage: E.coerce(17)
Traceback (most recent call last):
...
TypeError: no canonical coercion from Integer Ring to Automorphism group of Cyclotomic Field of order 16 and degree 8
TESTS:
Check that :trac:`28869` is fixed::
sage: K.<a> = CyclotomicField(8)
sage: L.<b> = K.absolute_field()
sage: phi = L.structure()[1]; phi
Isomorphism given by variable name change map:
From: Cyclotomic Field of order 8 and degree 4
To: Number Field in b with defining polynomial x^4 + 1
sage: phi.parent() is K.Hom(L)
True
sage: R.<x> = K[]
sage: (x^2 + a).change_ring(phi)
x^2 + b
"""
if (isinstance(x, CyclotomicFieldHomomorphism_im_gens)
and x.parent() == self):
return self.element_class(self, x.im_gens())
return self.element_class(self, x, check=check)
@cached_method
def list(self):
"""
Return a list of all the elements of self (for which the domain
is a cyclotomic field).
EXAMPLES::
sage: K.<z> = CyclotomicField(12)
sage: G = End(K); G
Automorphism group of Cyclotomic Field of order 12 and degree 4
sage: [g(z) for g in G]
[z, z^3 - z, -z, -z^3 + z]
sage: L.<a, b> = NumberField([x^2 + x + 1, x^4 + 1])
sage: L
Number Field in a with defining polynomial x^2 + x + 1 over its base field
sage: Hom(CyclotomicField(12), L)[3]
Ring morphism:
From: Cyclotomic Field of order 12 and degree 4
To: Number Field in a with defining polynomial x^2 + x + 1 over its base field
Defn: zeta12 |--> -b^2*a
sage: list(Hom(CyclotomicField(5), K))
[]
sage: Hom(CyclotomicField(11), L).list()
[]
"""
D = self.domain()
C = self.codomain()
z = D.gen()
n = z.multiplicative_order()
if not n.divides(C.zeta_order()):
v =[]
else:
if D == C:
w = z
else:
w = C.zeta(n)
v = [self([w**k], check=False) for k in Zmod(n) if k.is_unit()]
return Sequence(v, universe=self, check=False, immutable=True, cr=v!=[]) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/number_field/homset.py | 0.908305 | 0.535281 | homset.py | pypi |
from sage.misc.latex import latex
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.parent import Parent
from sage.structure.element import ModuleElement
from sage.structure.richcmp import richcmp
from sage.sets.family import Family
from sage.categories.modules import Modules
from sage.categories.morphism import Morphism
class FunctionFieldDifferential(ModuleElement):
"""
Base class for differentials on function fields.
INPUT:
- ``f`` -- element of the function field
- ``t`` -- element of the function field; if `t` is not specified, the generator
of the base differential is assumed
EXAMPLES::
sage: F.<x>=FunctionField(QQ)
sage: f = x/(x^2 + x + 1)
sage: f.differential()
((-x^2 + 1)/(x^4 + 2*x^3 + 3*x^2 + 2*x + 1)) d(x)
::
sage: K.<x> = FunctionField(QQ); _.<Y> = K[]
sage: L.<y> = K.extension(Y^3 + x + x^3*Y)
sage: L(x).differential()
d(x)
sage: y.differential()
((21/4*x/(x^7 + 27/4))*y^2 + ((3/2*x^7 + 9/4)/(x^8 + 27/4*x))*y + 7/2*x^4/(x^7 + 27/4)) d(x)
"""
def __init__(self, parent, f, t=None):
"""
Initialize the differential `fdt`.
TESTS::
sage: F.<x> = FunctionField(GF(7))
sage: f = x/(x^2 + x + 1)
sage: w = f.differential()
sage: TestSuite(w).run()
"""
ModuleElement.__init__(self, parent)
if t is not None:
f *= parent._derivation(t) * parent._gen_derivative_inv
self._f = f
def _repr_(self):
"""
Return the string representation of the differential.
EXAMPLES::
sage: K.<x> = FunctionField(GF(4)); _.<Y>=K[]
sage: L.<y> = K.extension(Y^3+x+x^3*Y)
sage: y.differential()
(x*y^2 + 1/x*y) d(x)
sage: F.<x>=FunctionField(QQ)
sage: f = 1/x
sage: f.differential()
(-1/x^2) d(x)
"""
if self._f.is_zero(): # zero differential
return '0'
r = 'd({})'.format(self.parent()._gen_base_differential)
if self._f.is_one():
return r
return '({})'.format(self._f) + ' ' + r
def _latex_(self):
r"""
Return a latex representation of the differential.
EXAMPLES::
sage: K.<x> = FunctionField(GF(4)); _.<Y>=K[]
sage: L.<y> = K.extension(Y^3+x+x^3*Y)
sage: w = y.differential()
sage: latex(w)
\left( x y^{2} + \frac{1}{x} y \right)\, dx
"""
if self._f.is_zero(): # zero differential
return '0'
r = 'd{}'.format(self.parent()._gen_base_differential)
if self._f.is_one():
return r
return '\\left(' + latex(self._f) + '\\right)\\,' + r
def __hash__(self):
"""
Return the hash of ``self``.
EXAMPLES::
sage: K.<x>=FunctionField(GF(2)); _.<Y> = K[]
sage: L.<y>=K.extension(Y^3 + x + x^3*Y)
sage: {x.differential(): 1}
{d(x): 1}
sage: {y.differential(): 1}
{(x*y^2 + 1/x*y) d(x): 1}
"""
return hash((self.parent(), self._f))
def _richcmp_(self, other, op):
"""
Compare the differential and the other differential with respect to the
comparison operator.
INPUT:
- ``other`` -- differential
- ``op`` -- comparison operator
EXAMPLES::
sage: K.<x> = FunctionField(GF(4)); _.<Y>=K[]
sage: L.<y> = K.extension(Y^3+x+x^3*Y)
sage: w1 = y.differential()
sage: w2 = L(x).differential()
sage: w3 = (x*y).differential()
sage: w1 < w2
False
sage: w2 < w1
True
sage: w3 == x * w1 + y * w2
True
sage: F.<x>=FunctionField(QQ)
sage: w1 = ((x^2+x+1)^10).differential()
sage: w2 = (x^2+x+1).differential()
sage: w1 < w2
False
sage: w1 > w2
True
sage: w1 == 10*(x^2+x+1)^9 * w2
True
"""
return richcmp(self._f, other._f, op)
def _add_(self, other):
"""
Return the sum of the differential and the other differential.
INPUT:
- ``other`` -- differential
EXAMPLES::
sage: K.<x> = FunctionField(GF(4)); _.<Y>=K[]
sage: L.<y> = K.extension(Y^3+x+x^3*Y)
sage: w1 = y.differential()
sage: w2 = (1/y).differential()
sage: w1 + w2
(((x^3 + 1)/x^2)*y^2 + 1/x*y) d(x)
sage: F.<x> = FunctionField(QQ)
sage: w1 = (1/x).differential()
sage: w2 = (x^2+1).differential()
sage: w1 + w2
((2*x^3 - 1)/x^2) d(x)
"""
W = self.parent()
return W.element_class(W, self._f + other._f)
def _div_(self, other):
"""
Return the quotient of ``self`` and ``other``
INPUT:
- ``other`` -- differential
OUTPUT: an element of the function field
EXAMPLES::
sage: K.<x> = FunctionField(GF(4)); _.<Y>=K[]
sage: L.<y> = K.extension(Y^3+x+x^3*Y)
sage: w1 = y.differential()
sage: w2 = (1/y).differential()
sage: w1 / w2
y^2
sage: F.<x> = FunctionField(QQ)
sage: w1 = (1/x).differential()
sage: w2 = (x^2+1).differential()
sage: w1 / w2
-1/2/x^3
"""
if other._f.is_zero():
raise ZeroDivisionError("division by zero differential")
return self._f / other._f
def _neg_(self):
"""
Return the negation of the differential.
EXAMPLES::
sage: K.<x> = FunctionField(GF(5)); _.<Y>=K[]
sage: L.<y> = K.extension(Y^3+x+x^3*Y)
sage: w1 = y.differential()
sage: w2 = (-y).differential()
sage: -w1 == w2
True
sage: F.<x> = FunctionField(QQ)
sage: w1 = (1/x).differential()
sage: w2 = (-1/x).differential()
sage: -w1 == w2
True
"""
W = self.parent()
return W.element_class(W, -self._f)
def _rmul_(self, f):
"""
Return the differential multiplied by the element of the function
field.
INPUT:
- ``f`` -- element of the function field
EXAMPLES::
sage: K.<x> = FunctionField(GF(5)); _.<Y>=K[]
sage: L.<y> = K.extension(Y^3+x+x^3*Y)
sage: w1 = (1/y).differential()
sage: w2 = (-1/y^2) * y.differential()
sage: w1 == w2
True
sage: F.<x>=FunctionField(QQ)
sage: w1 = (x^2*(x^2+x+1)).differential()
sage: w2 = (x^2).differential()
sage: w3 = (x^2+x+1).differential()
sage: w1 == (x^2) * w3 + (x^2+x+1) * w2
True
"""
W = self.parent()
return W.element_class(W, f * self._f)
def _acted_upon_(self, f, self_on_left):
"""
Define multiplication of ``self`` with an element ``f`` of a function
field, by coercing ``self`` to the space of differentials of the
function field.
INPUT:
- ``f`` -- an element of a function field
EXAMPLES::
sage: K.<x> = FunctionField(GF(31)); _.<Y> = K[]
sage: L.<y> = K.extension(Y^2 - x); _.<Z> = L[]
sage: M.<z> = L.extension(Z^2 - y)
sage: z.differential()
(8/x*z) d(x)
sage: 1/(2*z) * y.differential()
(8/x*z) d(x)
sage: z * x.differential()
(z) d(x)
sage: z * (y^2).differential()
(z) d(x)
sage: z * (z^4).differential()
(z) d(x)
::
sage: K.<x>=FunctionField(GF(4)); _.<Y> = K[]
sage: L.<y>=K.extension(Y^3 + x + x^3*Y)
sage: y * x.differential()
(y) d(x)
"""
F = f.parent()
if self.parent().function_field() is not F:
phi = F.space_of_differentials().coerce_map_from(self.parent())
if phi is not None:
return phi(self)._rmul_(f)
raise TypeError
def divisor(self):
"""
Return the divisor of the differential.
EXAMPLES::
sage: K.<x> = FunctionField(GF(5)); _.<Y>=K[]
sage: L.<y> = K.extension(Y^3+x+x^3*Y)
sage: w = (1/y) * y.differential()
sage: w.divisor()
- Place (1/x, 1/x^3*y^2 + 1/x)
- Place (1/x, 1/x^3*y^2 + 1/x^2*y + 1)
- Place (x, y)
+ Place (x + 2, y + 3)
+ Place (x^6 + 3*x^5 + 4*x^4 + 2*x^3 + x^2 + 3*x + 4, y + x^5)
::
sage: F.<x> = FunctionField(QQ)
sage: w = (1/x).differential()
sage: w.divisor()
-2*Place (x)
"""
F = self.parent().function_field()
x = F.base_field().gen()
return self._f.divisor() + (-2)*F(x).divisor_of_poles() + F.different()
def valuation(self, place):
"""
Return the valuation of the differential at the place.
INPUT:
- ``place`` -- a place of the function field
EXAMPLES::
sage: K.<x> = FunctionField(GF(5)); _.<Y>=K[]
sage: L.<y> = K.extension(Y^3+x+x^3*Y)
sage: w = (1/y) * y.differential()
sage: [w.valuation(p) for p in L.places()]
[-1, -1, -1, 0, 1, 0]
"""
F = self.parent().function_field()
x = F.base_field().gen()
return (self._f.valuation(place) + 2*min(F(x).valuation(place), 0)
+ F.different().valuation(place))
def residue(self, place):
"""
Return the residue of the differential at the place.
INPUT:
- ``place`` -- a place of the function field
OUTPUT:
- an element of the residue field of the place
EXAMPLES:
We verify the residue theorem in a rational function field::
sage: F.<x> = FunctionField(GF(4))
sage: f = 0
sage: while f == 0:
....: f = F.random_element()
sage: w = 1/f * f.differential()
sage: d = f.divisor()
sage: s = d.support()
sage: sum([w.residue(p).trace() for p in s])
0
and in an extension field::
sage: K.<x> = FunctionField(GF(7)); _.<Y> = K[]
sage: L.<y> = K.extension(Y^3 + x + x^3*Y)
sage: f = 0
sage: while f == 0:
....: f = L.random_element()
sage: w = 1/f * f.differential()
sage: d = f.divisor()
sage: s = d.support()
sage: sum([w.residue(p).trace() for p in s])
0
and also in a function field of characteristic zero::
sage: R.<x> = FunctionField(QQ)
sage: L.<Y> = R[]
sage: F.<y> = R.extension(Y^2 - x^4 - 4*x^3 - 2*x^2 - 1)
sage: a = 6*x^2 + 5*x + 7
sage: b = 2*x^6 + 8*x^5 + 3*x^4 - 4*x^3 -1
sage: w = y*a/b*x.differential()
sage: d = w.divisor()
sage: sum([QQ(w.residue(p)) for p in d.support()])
0
"""
R,fr_R,to_R = place._residue_field()
# Step 1: compute f such that fds equals this differential.
s = place.local_uniformizer()
dxds = ~(s.derivative())
g = self._f * dxds
# Step 2: compute c that is the coefficient of s^-1 in
# the power series expansion of f
r = g.valuation(place)
if r >= 0:
return R.zero()
else:
g_shifted = g * s**(-r)
c = g_shifted.higher_derivative(-r-1, s)
return to_R(c)
def monomial_coefficients(self, copy=True):
"""
Return a dictionary whose keys are indices of basis elements in the
support of ``self`` and whose values are the corresponding coefficients.
EXAMPLES::
sage: K.<x> = FunctionField(GF(5)); _.<Y> = K[]
sage: L.<y> = K.extension(Y^3+x+x^3*Y)
sage: d = y.differential()
sage: d
((4*x/(x^7 + 3))*y^2 + ((4*x^7 + 1)/(x^8 + 3*x))*y + x^4/(x^7 + 3)) d(x)
sage: d.monomial_coefficients()
{0: (4*x/(x^7 + 3))*y^2 + ((4*x^7 + 1)/(x^8 + 3*x))*y + x^4/(x^7 + 3)}
"""
return {0: self._f}
class FunctionFieldDifferential_global(FunctionFieldDifferential):
"""
Differentials on global function fields.
EXAMPLES::
sage: F.<x>=FunctionField(GF(7))
sage: f = x/(x^2 + x + 1)
sage: f.differential()
((6*x^2 + 1)/(x^4 + 2*x^3 + 3*x^2 + 2*x + 1)) d(x)
::
sage: K.<x> = FunctionField(GF(4)); _.<Y> = K[]
sage: L.<y> = K.extension(Y^3 + x + x^3*Y)
sage: y.differential()
(x*y^2 + 1/x*y) d(x)
"""
def cartier(self):
r"""
Return the image of the differential by the Cartier operator.
The Cartier operator operates on differentials. Let `x` be a separating
element of the function field. If a differential `\omega` is written
in prime-power representation
`\omega=(f_0^p+f_1^px+\dots+f_{p-1}^px^{p-1})dx`, then the Cartier
operator maps `\omega` to `f_{p-1}dx`. It is known that this definition
does not depend on the choice of `x`.
The Cartier operator has interesting properties. Notably, the set of
exact differentials is precisely the kernel of the Cartier operator and
logarithmic differentials are stable under the Cartier operation.
EXAMPLES::
sage: K.<x> = FunctionField(GF(4)); _.<Y> = K[]
sage: L.<y> = K.extension(Y^3 + x + x^3*Y)
sage: f = x/y
sage: w = 1/f*f.differential()
sage: w.cartier() == w
True
::
sage: F.<x> = FunctionField(GF(4))
sage: f = x/(x^2 + x + 1)
sage: w = 1/f*f.differential()
sage: w.cartier() == w
True
"""
W = self.parent()
F = W.function_field()
der = F.higher_derivation()
power_repr = der._prime_power_representation(self._f)
return W.element_class(W, power_repr[-1])
class DifferentialsSpace(UniqueRepresentation, Parent):
"""
Space of differentials of a function field.
INPUT:
- ``field`` -- function field
EXAMPLES::
sage: K.<x> = FunctionField(GF(4)); _.<Y> = K[]
sage: L.<y> = K.extension(Y^3 + x^3*Y + x)
sage: L.space_of_differentials()
Space of differentials of Function field in y defined by y^3 + x^3*y + x
The space of differentials is a one-dimensional module over the function
field. So a base differential is chosen to represent differentials.
Usually the generator of the base rational function field is a separating
element and used to generate the base differential. Otherwise a separating
element is automatically found and used to generate the base differential
relative to which other differentials are denoted::
sage: K.<x> = FunctionField(GF(5))
sage: R.<y> = K[]
sage: L.<y> = K.extension(y^5 - 1/x)
sage: L(x).differential()
0
sage: y.differential()
d(y)
sage: (y^2).differential()
(2*y) d(y)
"""
Element = FunctionFieldDifferential
def __init__(self, field, category=None):
"""
Initialize the space of differentials of the function field.
TESTS::
sage: K.<x>=FunctionField(GF(4)); _.<Y>=K[]
sage: L.<y>=K.extension(Y^3+x+x^3*Y)
sage: W = L.space_of_differentials()
sage: TestSuite(W).run()
"""
Parent.__init__(self, base=field, category=Modules(field).FiniteDimensional().WithBasis().or_subcategory(category))
# Starting from the base rational function field, find the first
# generator x of an intermediate function field that doesn't map to zero
# by the derivation map and use dx as our base differential.
der = field.derivation()
for F in reversed(field._intermediate_fields(field.rational_function_field())):
if der(F.gen()) != 0:
break
self._derivation = der
self._gen_base_differential = F.gen()
self._gen_derivative_inv = ~der(F.gen()) # used for fast computation
def _repr_(self):
"""
Return the string representation of the space of differentials.
EXAMPLES::
sage: K.<x>=FunctionField(GF(4)); _.<Y>=K[]
sage: L.<y>=K.extension(Y^3+x+x^3*Y)
sage: w = y.differential()
sage: w.parent()
Space of differentials of Function field in y defined by y^3 + x^3*y + x
"""
return "Space of differentials of {}".format(self.base())
def _element_constructor_(self, f):
"""
Construct differential `df` in the space from `f`.
INPUT:
- ``f`` -- element of the function field
EXAMPLES::
sage: K.<x>=FunctionField(GF(4)); _.<Y>=K[]
sage: L.<y>=K.extension(Y^3+x+x^3*Y)
sage: S = L.space_of_differentials()
sage: S(y)
(x*y^2 + 1/x*y) d(x)
sage: S(y) in S
True
sage: S(1)
0
"""
if f in self.base():
return self.element_class(self, self.base().one(), f)
raise ValueError
def _coerce_map_from_(self, S):
"""
Define coercions.
We can coerce from any DifferentialsSpace whose underlying field
can be coerced into our underlying field.
EXAMPLES::
sage: K.<x> = FunctionField(QQ); R.<y> = K[]
sage: L.<y> = K.extension(y^2 - x*y + 4*x^3)
sage: L.space_of_differentials().coerce_map_from(K.space_of_differentials())
Inclusion morphism:
From: Space of differentials of Rational function field in x over Rational Field
To: Space of differentials of Function field in y defined by y^2 - x*y + 4*x^3
"""
if isinstance(S, DifferentialsSpace):
if self.function_field().has_coerce_map_from(S.function_field()):
return DifferentialsSpaceInclusion(S, self)
def function_field(self):
"""
Return the function field to which the space of differentials
is attached.
EXAMPLES::
sage: K.<x> = FunctionField(GF(4)); _.<Y> = K[]
sage: L.<y> = K.extension(Y^3 + x^3*Y + x)
sage: S = L.space_of_differentials()
sage: S.function_field()
Function field in y defined by y^3 + x^3*y + x
"""
return self.base()
def _an_element_(self):
"""
Return a differential.
EXAMPLES::
sage: K.<x>=FunctionField(GF(4)); _.<Y>=K[]
sage: L.<y>=K.extension(Y^3+x+x^3*Y)
sage: S = L.space_of_differentials()
sage: S.an_element() # random
(x*y^2 + 1/x*y) d(x)
"""
F = self.base()
return self.element_class(self, F.one(), F.an_element())
def basis(self):
"""
Return a basis.
EXAMPLES::
sage: K.<x> = FunctionField(GF(4)); _.<Y> = K[]
sage: L.<y> = K.extension(Y^3 + x^3*Y + x)
sage: S = L.space_of_differentials()
sage: S.basis()
Family (d(x),)
"""
return Family([self.element_class(self, self.base().one())])
class DifferentialsSpace_global(DifferentialsSpace):
"""
Space of differentials of a global function field.
INPUT:
- ``field`` -- function field
EXAMPLES::
sage: K.<x> = FunctionField(GF(4)); _.<Y> = K[]
sage: L.<y> = K.extension(Y^3 + x^3*Y + x)
sage: L.space_of_differentials()
Space of differentials of Function field in y defined by y^3 + x^3*y + x
"""
Element = FunctionFieldDifferential_global
class DifferentialsSpaceInclusion(Morphism):
"""
Inclusion morphisms for extensions of function fields.
EXAMPLES::
sage: K.<x> = FunctionField(QQ); R.<y> = K[]
sage: L.<y> = K.extension(y^2 - x*y + 4*x^3)
sage: OK = K.space_of_differentials()
sage: OL = L.space_of_differentials()
sage: OL.coerce_map_from(OK)
Inclusion morphism:
From: Space of differentials of Rational function field in x over Rational Field
To: Space of differentials of Function field in y defined by y^2 - x*y + 4*x^3
"""
def _repr_(self):
"""
Return the string representation of this morphism.
EXAMPLES::
sage: K.<x> = FunctionField(QQ); R.<y> = K[]
sage: L.<y> = K.extension(y^2 - x*y + 4*x^3)
sage: OK = K.space_of_differentials()
sage: OL = L.space_of_differentials()
sage: OL.coerce_map_from(OK)
Inclusion morphism:
From: Space of differentials of Rational function field in x over Rational Field
To: Space of differentials of Function field in y defined by y^2 - x*y + 4*x^3
"""
s = "Inclusion morphism:"
s += "\n From: {}".format(self.domain())
s += "\n To: {}".format(self.codomain())
return s
def is_injective(self):
"""
Return ``True``, since the inclusion morphism is injective.
EXAMPLES::
sage: K.<x> = FunctionField(QQ); R.<y> = K[]
sage: L.<y> = K.extension(y^2 - x*y + 4*x^3)
sage: OK = K.space_of_differentials()
sage: OL = L.space_of_differentials()
sage: OL.coerce_map_from(OK).is_injective()
True
"""
return True
def is_surjective(self):
"""
Return ``True`` if the inclusion morphism is surjective.
EXAMPLES::
sage: K.<x> = FunctionField(QQ); R.<y> = K[]
sage: L.<y> = K.extension(y^2 - x*y + 4*x^3)
sage: OK = K.space_of_differentials()
sage: OL = L.space_of_differentials()
sage: OL.coerce_map_from(OK).is_surjective()
False
sage: S.<z> = L[]
sage: M.<z> = L.extension(z - 1)
sage: OM = M.space_of_differentials()
sage: OM.coerce_map_from(OL).is_surjective()
True
"""
K = self.domain().function_field()
L = self.codomain().function_field()
return L.degree(K) == 1
def _call_(self, v):
"""
Map ``v`` to a differential in the codomain.
INPUT:
- ``v`` -- a differential in the domain
EXAMPLES::
sage: K.<x> = FunctionField(QQbar); _.<Y> = K[]
sage: L.<y> = K.extension(Y^2 - x*Y + 4*x^3)
sage: OK = K.space_of_differentials()
sage: OL = L.space_of_differentials()
sage: mor = OL.coerce_map_from(OK)
sage: mor(x.differential()).parent()
Space of differentials of Function field in y defined by y^2 - x*y + 4*x^3
"""
domain = self.domain()
F = self.codomain().function_field()
return F(v._f)*F(domain._gen_base_differential).differential() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/function_field/differential.py | 0.916283 | 0.603757 | differential.py | pypi |
r"""
Special extensions of function fields
This module currently implements only constant field extension.
Constant field extensions
-------------------------
EXAMPLES:
Constant field extension of the rational function field over rational numbers::
sage: K.<x> = FunctionField(QQ)
sage: N.<a> = QuadraticField(2)
sage: L = K.extension_constant_field(N)
sage: L
Rational function field in x over Number Field in a with defining
polynomial x^2 - 2 with a = 1.4142... over its base
sage: d = (x^2 - 2).divisor()
sage: d
-2*Place (1/x)
+ Place (x^2 - 2)
sage: L.conorm_divisor(d)
-2*Place (1/x)
+ Place (x - a)
+ Place (x + a)
Constant field extension of a function field over a finite field::
sage: K.<x> = FunctionField(GF(2)); R.<Y> = K[]
sage: F.<y> = K.extension(Y^3 - x^2*(x^2 + x + 1)^2)
sage: E = F.extension_constant_field(GF(2^3))
sage: E
Function field in y defined by y^3 + x^6 + x^4 + x^2 over its base
sage: p = F.get_place(3)
sage: E.conorm_place(p) # random
Place (x + z3, y + z3^2 + z3)
+ Place (x + z3^2, y + z3)
+ Place (x + z3^2 + z3, y + z3^2)
sage: q = F.get_place(2)
sage: E.conorm_place(q) # random
Place (x + 1, y^2 + y + 1)
sage: E.conorm_divisor(p + q) # random
Place (x + 1, y^2 + y + 1)
+ Place (x + z3, y + z3^2 + z3)
+ Place (x + z3^2, y + z3)
+ Place (x + z3^2 + z3, y + z3^2)
AUTHORS:
- Kwankyu Lee (2021-12-24): added constant field extension
"""
from sage.rings.ring_extension import RingExtension_generic
from .constructor import FunctionField
class FunctionFieldExtension(RingExtension_generic):
"""
Abstract base class of function field extensions.
"""
pass
class ConstantFieldExtension(FunctionFieldExtension):
"""
Constant field extension.
INPUT:
- ``F`` -- a function field whose constant field is `k`
- ``k_ext`` -- an extension of `k`
"""
def __init__(self, F, k_ext):
"""
Initialize.
TESTS::
sage: K.<x> = FunctionField(GF(2)); R.<Y> = K[]
sage: F.<y> = K.extension(Y^3 - x^2*(x^2 + x + 1)^2)
sage: E = F.extension_constant_field(GF(2^3))
sage: TestSuite(E).run(skip=['_test_elements', '_test_pickling'])
"""
k = F.constant_base_field()
F_base = F.base_field()
F_ext_base = FunctionField(k_ext, F_base.variable_name())
if F.degree() > 1:
# construct constant field extension F_ext of F
def_poly = F.polynomial().base_extend(F_ext_base)
F_ext = F_ext_base.extension(def_poly, names=def_poly.variable_name())
else: # rational function field
F_ext = F_ext_base
# embedding of F into F_ext
embedk = k_ext.coerce_map_from(k)
embedF_base = F_base.hom(F_ext_base.gen(), embedk)
if F.degree() > 1:
embedF = F.hom(F_ext.gen(), embedF_base)
else:
embedF = embedF_base
self._embedk = embedk
self._embedF = embedF
self._F_ext = F_ext
self._k = k
super().__init__(embedF, is_backend_exposed=True)
def top(self):
"""
Return the top function field of this extension.
EXAMPLES::
sage: K.<x> = FunctionField(GF(2)); R.<Y> = K[]
sage: F.<y> = K.extension(Y^3 - x^2*(x^2 + x + 1)^2)
sage: E = F.extension_constant_field(GF(2^3))
sage: E.top()
Function field in y defined by y^3 + x^6 + x^4 + x^2
"""
return self._F_ext
def defining_morphism(self):
"""
Return the defining morphism of this extension.
This is the morphism from the base to the top.
EXAMPLES::
sage: K.<x> = FunctionField(GF(2)); R.<Y> = K[]
sage: F.<y> = K.extension(Y^3 - x^2*(x^2 + x + 1)^2)
sage: E = F.extension_constant_field(GF(2^3))
sage: E.defining_morphism()
Function Field morphism:
From: Function field in y defined by y^3 + x^6 + x^4 + x^2
To: Function field in y defined by y^3 + x^6 + x^4 + x^2
Defn: y |--> y
x |--> x
1 |--> 1
"""
return self._embedF
def conorm_place(self, p):
"""
Return the conorm of the place `p` in this extension.
INPUT:
- ``p`` -- place of the base function field
OUTPUT: divisor of the top function field
EXAMPLES::
sage: K.<x> = FunctionField(GF(2)); R.<Y> = K[]
sage: F.<y> = K.extension(Y^3 - x^2*(x^2 + x + 1)^2)
sage: E = F.extension_constant_field(GF(2^3))
sage: p = F.get_place(3)
sage: d = E.conorm_place(p)
sage: [pl.degree() for pl in d.support()]
[1, 1, 1]
sage: p = F.get_place(2)
sage: d = E.conorm_place(p)
sage: [pl.degree() for pl in d.support()]
[2]
"""
embedF = self.defining_morphism()
O_ext = self.maximal_order()
Oinf_ext = self.maximal_order_infinite()
if p.is_infinite_place():
ideal = Oinf_ext.ideal([embedF(g) for g in p.prime_ideal().gens()])
else:
ideal = O_ext.ideal([embedF(g) for g in p.prime_ideal().gens()])
return ideal.divisor()
def conorm_divisor(self, d):
"""
Return the conorm of the divisor ``d`` in this extension.
INPUT:
- ``d`` -- divisor of the base function field
OUTPUT: a divisor of the top function field
EXAMPLES::
sage: K.<x> = FunctionField(GF(2)); R.<Y> = K[]
sage: F.<y> = K.extension(Y^3 - x^2*(x^2 + x + 1)^2)
sage: E = F.extension_constant_field(GF(2^3))
sage: p1 = F.get_place(3)
sage: p2 = F.get_place(2)
sage: c = E.conorm_divisor(2*p1+ 3*p2)
sage: c1 = E.conorm_place(p1)
sage: c2 = E.conorm_place(p2)
sage: c == 2*c1 + 3*c2
True
"""
div_top = self.divisor_group()
c = div_top.zero()
for pl, mul in d.list():
c += mul * self.conorm_place(pl)
return c | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/function_field/extensions.py | 0.907999 | 0.748513 | extensions.py | pypi |
from sage.rings.finite_rings.finite_field_base import FiniteField as FiniteField_generic
from sage.categories.finite_fields import FiniteFields
_FiniteFields = FiniteFields()
import sage.rings.finite_rings.integer_mod_ring as integer_mod_ring
from sage.rings.integer import Integer
import sage.rings.finite_rings.integer_mod as integer_mod
from sage.rings.integer_ring import ZZ
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing_generic
from sage.misc.persist import register_unpickle_override
class FiniteField_prime_modn(FiniteField_generic, integer_mod_ring.IntegerModRing_generic):
r"""
Finite field of order `p` where `p` is prime.
EXAMPLES::
sage: FiniteField(3)
Finite Field of size 3
sage: FiniteField(next_prime(1000))
Finite Field of size 1009
"""
def __init__(self, p, check=True, modulus=None):
"""
Return a new finite field of order `p` where `p` is prime.
INPUT:
- ``p`` -- an integer at least 2
- ``check`` -- bool (default: ``True``); if ``False``, do not
check ``p`` for primality
EXAMPLES::
sage: F = FiniteField(3); F
Finite Field of size 3
"""
p = Integer(p)
if check and not p.is_prime():
raise ArithmeticError("p must be prime")
self.__char = p
# FiniteField_generic does nothing more than IntegerModRing_generic, and
# it saves a non trivial overhead
integer_mod_ring.IntegerModRing_generic.__init__(self, p, category=_FiniteFields)
# If modulus is None, it will be created on demand as x-1
# by the modulus() method.
if modulus is not None:
self._modulus = modulus
def __reduce__(self):
"""
For pickling.
EXAMPLES::
sage: k = FiniteField(5); type(k)
<class 'sage.rings.finite_rings.finite_field_prime_modn.FiniteField_prime_modn_with_category'>
sage: k is loads(dumps(k))
True
"""
return self._factory_data[0].reduce_data(self)
def _coerce_map_from_(self, S):
"""
This is called implicitly by arithmetic methods.
EXAMPLES::
sage: k = GF(7)
sage: e = k(6)
sage: e * 2 # indirect doctest
5
sage: 12 % 7
5
sage: ZZ.residue_field(7).hom(GF(7))(1) # See trac 11319
1
sage: K.<w> = QuadraticField(337) # See trac 11319
sage: pp = K.ideal(13).factor()[0][0]
sage: RF13 = K.residue_field(pp)
sage: RF13.hom([GF(13)(1)])
Ring morphism:
From: Residue field of Fractional ideal (-w - 18)
To: Finite Field of size 13
Defn: 1 |--> 1
Check that :trac:`19573` is resolved::
sage: Integers(9).hom(GF(3))
Natural morphism:
From: Ring of integers modulo 9
To: Finite Field of size 3
sage: Integers(9).hom(GF(5))
Traceback (most recent call last):
...
TypeError: natural coercion morphism from Ring of integers modulo 9 to Finite Field of size 5 not defined
There is no coercion from a `p`-adic ring to its residue field::
sage: GF(3).has_coerce_map_from(Zp(3))
False
"""
if S is int:
return integer_mod.Int_to_IntegerMod(self)
elif S is ZZ:
return integer_mod.Integer_to_IntegerMod(self)
elif isinstance(S, IntegerModRing_generic):
from .residue_field import ResidueField_generic
if (S.characteristic() % self.characteristic() == 0 and
(not isinstance(S, ResidueField_generic) or
S.degree() == 1)):
try:
return integer_mod.IntegerMod_to_IntegerMod(S, self)
except TypeError:
pass
to_ZZ = ZZ._internal_coerce_map_from(S)
if to_ZZ is not None:
return integer_mod.Integer_to_IntegerMod(self) * to_ZZ
def _convert_map_from_(self, R):
"""
Conversion from p-adic fields.
EXAMPLES::
sage: GF(3).convert_map_from(Qp(3))
Reduction morphism:
From: 3-adic Field with capped relative precision 20
To: Finite Field of size 3
sage: GF(3).convert_map_from(Zp(3))
Reduction morphism:
From: 3-adic Ring with capped relative precision 20
To: Finite Field of size 3
"""
from sage.rings.padics.padic_generic import pAdicGeneric, ResidueReductionMap
if isinstance(R, pAdicGeneric) and R.residue_field() is self:
return ResidueReductionMap._create_(R, self)
def construction(self):
"""
Returns the construction of this finite field (for use by sage.categories.pushout)
EXAMPLES::
sage: GF(3).construction()
(QuotientFunctor, Integer Ring)
"""
return integer_mod_ring.IntegerModRing_generic.construction(self)
def characteristic(self):
r"""
Return the characteristic of \code{self}.
EXAMPLES::
sage: k = GF(7)
sage: k.characteristic()
7
"""
return self.__char
def is_prime_field(self):
"""
Return ``True`` since this is a prime field.
EXAMPLES::
sage: k.<a> = GF(3)
sage: k.is_prime_field()
True
sage: k.<a> = GF(3^2)
sage: k.is_prime_field()
False
"""
return True
def polynomial(self, name=None):
"""
Returns the polynomial ``name``.
EXAMPLES::
sage: k.<a> = GF(3)
sage: k.polynomial()
x
"""
if name is None:
name = self.variable_name()
try:
return self.__polynomial[name]
except AttributeError:
f = self[name]([0, 1])
try:
self.__polynomial[name] = f
except (KeyError, AttributeError):
self.__polynomial = {}
self.__polynomial[name] = f
return f
def order(self):
"""
Return the order of this finite field.
EXAMPLES::
sage: k = GF(5)
sage: k.order()
5
"""
return self.__char
def gen(self, n=0):
"""
Return a generator of ``self`` over its prime field, which is a
root of ``self.modulus()``.
Unless a custom modulus was given when constructing this prime
field, this returns `1`.
INPUT:
- ``n`` -- must be 0
OUTPUT:
An element `a` of ``self`` such that ``self.modulus()(a) == 0``.
.. WARNING::
This generator is not guaranteed to be a generator for the
multiplicative group. To obtain the latter, use
:meth:`~sage.rings.finite_rings.finite_field_base.FiniteFields.multiplicative_generator()`
or use the ``modulus="primitive"`` option when constructing
the field.
EXAMPLES::
sage: k = GF(13)
sage: k.gen()
1
sage: k = GF(1009, modulus="primitive")
sage: k.gen() # this gives a primitive element
11
sage: k.gen(1)
Traceback (most recent call last):
...
IndexError: only one generator
"""
if n:
raise IndexError("only one generator")
try:
return self.__gen
except AttributeError:
pass
try:
self.__gen = -(self._modulus[0])
except AttributeError:
self.__gen = self.one()
return self.__gen
def __iter__(self):
"""
Return an iterator over ``self``.
EXAMPLES::
sage: list(GF(7))
[0, 1, 2, 3, 4, 5, 6]
We can even start iterating over something that would be too big
to actually enumerate::
sage: K = GF(next_prime(2^256))
sage: all = iter(K)
sage: next(all)
0
sage: next(all)
1
sage: next(all)
2
"""
yield self(0)
i = one = self(1)
while i:
yield i
i += one
def degree(self):
"""
Return the degree of ``self`` over its prime field.
This always returns 1.
EXAMPLES::
sage: FiniteField(3).degree()
1
"""
return Integer(1)
register_unpickle_override(
'sage.rings.finite_field_prime_modn', 'FiniteField_prime_modn',
FiniteField_prime_modn) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/finite_rings/finite_field_prime_modn.py | 0.918923 | 0.438004 | finite_field_prime_modn.py | pypi |
from sage.rings.finite_rings.finite_field_base import FiniteField
from sage.rings.integer import Integer
from sage.rings.finite_rings.element_givaro import Cache_givaro
from sage.libs.pari.all import pari
from sage.misc.superseded import deprecated_function_alias
class FiniteField_givaro(FiniteField):
"""
Finite field implemented using Zech logs and the cardinality must be
less than `2^{16}`. By default, Conway polynomials are used as minimal
polynomials.
INPUT:
- ``q`` -- `p^n` (must be prime power)
- ``name`` -- (default: ``'a'``) variable used for
:meth:`~sage.rings.finite_rings.element_givaro.FiniteField_givaroElement.poly_repr()`
- ``modulus`` -- A minimal polynomial to use for reduction.
- ``repr`` -- (default: ``'poly'``) controls the way elements are printed
to the user:
- 'log': repr is
:meth:`~sage.rings.finite_rings.element_givaro.FiniteField_givaroElement.log_repr()`
- 'int': repr is
:meth:`~sage.rings.finite_rings.element_givaro.FiniteField_givaroElement.int_repr()`
- 'poly': repr is
:meth:`~sage.rings.finite_rings.element_givaro.FiniteField_givaroElement.poly_repr()`
- cache -- (default: ``False``) if ``True`` a cache of all elements of
this field is created. Thus, arithmetic does not create new elements
which speeds calculations up. Also, if many elements are needed during a
calculation this cache reduces the memory requirement as at most
:meth:`order` elements are created.
OUTPUT:
Givaro finite field with characteristic `p` and cardinality `p^n`.
EXAMPLES:
By default, Conway polynomials are used for extension fields::
sage: k.<a> = GF(2**8)
sage: -a ^ k.degree()
a^4 + a^3 + a^2 + 1
sage: f = k.modulus(); f
x^8 + x^4 + x^3 + x^2 + 1
You may enforce a modulus::
sage: P.<x> = PolynomialRing(GF(2))
sage: f = x^8 + x^4 + x^3 + x + 1 # Rijndael Polynomial
sage: k.<a> = GF(2^8, modulus=f)
sage: k.modulus()
x^8 + x^4 + x^3 + x + 1
sage: a^(2^8)
a
You may enforce a random modulus::
sage: k = GF(3**5, 'a', modulus='random')
sage: k.modulus() # random polynomial
x^5 + 2*x^4 + 2*x^3 + x^2 + 2
Three different representations are possible::
sage: FiniteField(9, 'a', impl='givaro', repr='poly').gen()
a
sage: FiniteField(9, 'a', impl='givaro', repr='int').gen()
3
sage: FiniteField(9, 'a', impl='givaro', repr='log').gen()
1
For prime fields, the default modulus is the polynomial `x - 1`,
but you can ask for a different modulus::
sage: GF(1009, impl='givaro').modulus()
x + 1008
sage: GF(1009, impl='givaro', modulus='conway').modulus()
x + 998
"""
def __init__(self, q, name="a", modulus=None, repr="poly", cache=False):
"""
Initialize ``self``.
EXAMPLES::
sage: k.<a> = GF(2^3)
sage: j.<b> = GF(3^4)
sage: k == j
False
sage: GF(2^3,'a') == copy(GF(2^3,'a'))
True
sage: TestSuite(GF(2^3, 'a')).run()
"""
if repr not in ['int', 'log', 'poly']:
raise ValueError("Unknown representation %s" % repr)
q = Integer(q)
if q < 2:
raise ValueError("q must be a prime power")
F = q.factor()
if len(F) > 1:
raise ValueError("q must be a prime power")
p = F[0][0]
k = F[0][1]
if q >= 1 << 16:
raise ValueError("q must be < 2^16")
from .finite_field_constructor import GF
FiniteField.__init__(self, GF(p), name, normalize=False)
from sage.rings.polynomial.polynomial_element import is_Polynomial
if not is_Polynomial(modulus):
raise TypeError("modulus must be a polynomial")
self._cache = Cache_givaro(self, p, k, modulus, repr, cache)
self._modulus = modulus
def characteristic(self):
"""
Return the characteristic of this field.
EXAMPLES::
sage: p = GF(19^5,'a').characteristic(); p
19
sage: type(p)
<class 'sage.rings.integer.Integer'>
"""
return Integer(self._cache.characteristic())
def order(self):
"""
Return the cardinality of this field.
OUTPUT:
Integer -- the number of elements in ``self``.
EXAMPLES::
sage: n = GF(19^5,'a').order(); n
2476099
sage: type(n)
<class 'sage.rings.integer.Integer'>
"""
return self._cache.order()
def degree(self):
r"""
If the cardinality of ``self`` is `p^n`, then this returns `n`.
OUTPUT:
Integer -- the degree
EXAMPLES::
sage: GF(3^4,'a').degree()
4
"""
return Integer(self._cache.exponent())
def _repr_option(self, key):
"""
Metadata about the :meth:`_repr_` output.
See :meth:`sage.structure.parent._repr_option` for details.
EXAMPLES::
sage: GF(23**3, 'a', repr='log')._repr_option('element_is_atomic')
True
sage: GF(23**3, 'a', repr='int')._repr_option('element_is_atomic')
True
sage: GF(23**3, 'a', repr='poly')._repr_option('element_is_atomic')
False
"""
if key == 'element_is_atomic':
return self._cache.repr != 0 # 0 means repr='poly'
return super()._repr_option(key)
def random_element(self, *args, **kwds):
"""
Return a random element of ``self``.
EXAMPLES::
sage: k = GF(23**3, 'a')
sage: e = k.random_element()
sage: e.parent() is k
True
sage: type(e)
<class 'sage.rings.finite_rings.element_givaro.FiniteField_givaroElement'>
sage: P.<x> = PowerSeriesRing(GF(3^3, 'a'))
sage: P.random_element(5).parent() is P
True
"""
return self._cache.random_element()
def _element_constructor_(self, e):
"""
Coerces several data types to ``self``.
INPUT:
- ``e`` -- data to coerce
EXAMPLES:
:class:`FiniteField_givaroElement` are accepted where the parent
is either ``self``, equals ``self`` or is the prime subfield::
sage: k = GF(2**8, 'a')
sage: k.gen() == k(k.gen())
True
Floats, ints, longs, Integer are interpreted modulo characteristic::
sage: k(2) # indirect doctest
0
Floats are converted like integers::
sage: k(float(2.0))
0
Rational are interpreted as ``self(numerator)/self(denominator)``.
Both may not be greater than :meth:`characteristic`.
::
sage: k = GF(3**8, 'a')
sage: k(1/2) == k(1)/k(2)
True
Free module elements over :meth:`prime_subfield()` are interpreted
'little endian'::
sage: k = GF(2**8, 'a')
sage: e = k.vector_space(map=False).gen(1); e
(0, 1, 0, 0, 0, 0, 0, 0)
sage: k(e)
a
``None`` yields zero::
sage: k(None)
0
Strings are evaluated as polynomial representation of elements in
``self``::
sage: k('a^2+1')
a^2 + 1
Univariate polynomials coerce into finite fields by evaluating
the polynomial at the field's generator::
sage: R.<x> = QQ[]
sage: k.<a> = FiniteField(5^2, 'a', impl='givaro')
sage: k(R(2/3))
4
sage: k(x^2)
a + 3
sage: R.<x> = GF(5)[]
sage: k(x^3-2*x+1)
2*a + 4
sage: x = polygen(QQ)
sage: k(x^25)
a
sage: Q.<q> = FiniteField(5^3, 'q', impl='givaro')
sage: L = GF(5)
sage: LL.<xx> = L[]
sage: Q(xx^2 + 2*xx + 4)
q^2 + 2*q + 4
Multivariate polynomials only coerce if constant::
sage: R = k['x,y,z']; R
Multivariate Polynomial Ring in x, y, z over Finite Field in a of size 5^2
sage: k(R(2))
2
sage: R = QQ['x,y,z']
sage: k(R(1/5))
Traceback (most recent call last):
...
ZeroDivisionError: division by zero in finite field
PARI elements are interpreted as finite field elements; this PARI
flexibility is (absurdly!) liberal::
sage: k.<a> = GF(2^8)
sage: k(pari('Mod(1,2)'))
1
sage: k(pari('Mod(2,3)'))
a
sage: k(pari('Mod(1,3)*a^20'))
a^7 + a^5 + a^4 + a^2
sage: k(pari('O(x)'))
Traceback (most recent call last):
...
TypeError: unable to convert PARI t_SER to Finite Field in a of size 2^8
We can coerce from PARI finite field implementations::
sage: K.<a> = GF(3^10, impl="givaro")
sage: a^20
2*a^9 + 2*a^8 + a^7 + 2*a^5 + 2*a^4 + 2*a^3 + 1
sage: M.<c> = GF(3^10, impl="pari_ffelt")
sage: K(c^20)
2*a^9 + 2*a^8 + a^7 + 2*a^5 + 2*a^4 + 2*a^3 + 1
GAP elements need to be finite field elements::
sage: x = gap('Z(13)')
sage: F = FiniteField(13, impl='givaro')
sage: F(x)
2
sage: F(gap('0*Z(13)'))
0
sage: F = FiniteField(13^2, 'a', impl='givaro')
sage: x = gap('Z(13)')
sage: F(x)
2
sage: x = gap('Z(13^2)^3')
sage: F(x)
12*a + 11
sage: F.multiplicative_generator()^3
12*a + 11
sage: k.<a> = GF(29^3)
sage: k(48771/1225)
28
sage: F9 = FiniteField(9, impl='givaro', prefix='a')
sage: F81 = FiniteField(81, impl='givaro', prefix='a')
sage: F81(F9.gen())
2*a4^3 + 2*a4^2 + 1
"""
return self._cache.element_from_data(e)
def gen(self, n=0):
r"""
Return a generator of ``self`` over its prime field, which is a
root of ``self.modulus()``.
INPUT:
- ``n`` -- must be 0
OUTPUT:
An element `a` of ``self`` such that ``self.modulus()(a) == 0``.
.. WARNING::
This generator is not guaranteed to be a generator for the
multiplicative group. To obtain the latter, use
:meth:`~sage.rings.finite_rings.finite_field_base.FiniteFields.multiplicative_generator()`
or use the ``modulus="primitive"`` option when constructing
the field.
EXAMPLES::
sage: k = GF(3^4, 'b'); k.gen()
b
sage: k.gen(1)
Traceback (most recent call last):
...
IndexError: only one generator
sage: F = FiniteField(31, impl='givaro')
sage: F.gen()
1
"""
if n:
raise IndexError("only one generator")
return self._cache.gen()
def prime_subfield(self):
r"""
Return the prime subfield `\GF{p}` of self if ``self`` is `\GF{p^n}`.
EXAMPLES::
sage: GF(3^4, 'b').prime_subfield()
Finite Field of size 3
sage: S.<b> = GF(5^2); S
Finite Field in b of size 5^2
sage: S.prime_subfield()
Finite Field of size 5
sage: type(S.prime_subfield())
<class 'sage.rings.finite_rings.finite_field_prime_modn.FiniteField_prime_modn_with_category'>
"""
try:
return self._prime_subfield
except AttributeError:
from .finite_field_constructor import GF
self._prime_subfield = GF(self.characteristic())
return self._prime_subfield
def log_to_int(self, n):
r"""
Given an integer `n` this method returns ``i`` where ``i``
satisfies `g^n = i` where `g` is the generator of ``self``; the
result is interpreted as an integer.
INPUT:
- ``n`` -- log representation of a finite field element
OUTPUT:
integer representation of a finite field element.
EXAMPLES::
sage: k = GF(2**8, 'a')
sage: k.log_to_int(4)
16
sage: k.log_to_int(20)
180
"""
return self._cache.log_to_int(n)
def int_to_log(self, n):
r"""
Given an integer `n` this method returns `i` where `i` satisfies
`g^i = n \mod p` where `g` is the generator and `p` is the
characteristic of ``self``.
INPUT:
- ``n`` -- integer representation of an finite field element
OUTPUT:
log representation of ``n``
EXAMPLES::
sage: k = GF(7**3, 'a')
sage: k.int_to_log(4)
228
sage: k.int_to_log(3)
57
sage: k.gen()^57
3
"""
return self._cache.int_to_log(n)
def from_integer(self, n):
r"""
Given an integer `n` return a finite field element in ``self``
which equals `n` under the condition that :meth:`gen()` is set to
:meth:`characteristic()`.
EXAMPLES::
sage: k.<a> = GF(2^8)
sage: k.from_integer(8)
a^3
sage: e = k.from_integer(151); e
a^7 + a^4 + a^2 + a + 1
sage: 2^7 + 2^4 + 2^2 + 2 + 1
151
"""
return self._cache.fetch_int(n)
fetch_int = deprecated_function_alias(33941, from_integer)
def _pari_modulus(self):
"""
Return the modulus of ``self`` in a format for PARI.
EXAMPLES::
sage: GF(3^4,'a')._pari_modulus()
Mod(1, 3)*a^4 + Mod(2, 3)*a^3 + Mod(2, 3)
"""
f = pari(str(self.modulus()))
return f.subst('x', 'a') * pari("Mod(1,%s)"%self.characteristic())
def __iter__(self):
"""
Finite fields may be iterated over.
EXAMPLES::
sage: list(GF(2**2, 'a'))
[0, a, a + 1, 1]
"""
from .element_givaro import FiniteField_givaro_iterator
return FiniteField_givaro_iterator(self._cache)
def a_times_b_plus_c(self, a, b, c):
"""
Return ``a*b + c``. This is faster than multiplying ``a`` and ``b``
first and adding ``c`` to the result.
INPUT:
- ``a,b,c`` -- :class:`~~sage.rings.finite_rings.element_givaro.FiniteField_givaroElement`
EXAMPLES::
sage: k.<a> = GF(2**8)
sage: k.a_times_b_plus_c(a,a,k(1))
a^2 + 1
"""
return self._cache.a_times_b_plus_c(a, b, c)
def a_times_b_minus_c(self, a, b, c):
"""
Return ``a*b - c``.
INPUT:
- ``a,b,c`` -- :class:`~sage.rings.finite_rings.element_givaro.FiniteField_givaroElement`
EXAMPLES::
sage: k.<a> = GF(3**3)
sage: k.a_times_b_minus_c(a,a,k(1))
a^2 + 2
"""
return self._cache.a_times_b_minus_c(a, b, c)
def c_minus_a_times_b(self, a, b, c):
"""
Return ``c - a*b``.
INPUT:
- ``a,b,c`` -- :class:`~sage.rings.finite_rings.element_givaro.FiniteField_givaroElement`
EXAMPLES::
sage: k.<a> = GF(3**3)
sage: k.c_minus_a_times_b(a,a,k(1))
2*a^2 + 1
"""
return self._cache.c_minus_a_times_b(a, b, c)
def frobenius_endomorphism(self, n=1):
"""
INPUT:
- ``n`` -- an integer (default: 1)
OUTPUT:
The `n`-th power of the absolute arithmetic Frobenius
endomorphism on this finite field.
EXAMPLES::
sage: k.<t> = GF(3^5)
sage: Frob = k.frobenius_endomorphism(); Frob
Frobenius endomorphism t |--> t^3 on Finite Field in t of size 3^5
sage: a = k.random_element()
sage: Frob(a) == a^3
True
We can specify a power::
sage: k.frobenius_endomorphism(2)
Frobenius endomorphism t |--> t^(3^2) on Finite Field in t of size 3^5
The result is simplified if possible::
sage: k.frobenius_endomorphism(6)
Frobenius endomorphism t |--> t^3 on Finite Field in t of size 3^5
sage: k.frobenius_endomorphism(5)
Identity endomorphism of Finite Field in t of size 3^5
Comparisons work::
sage: k.frobenius_endomorphism(6) == Frob
True
sage: from sage.categories.morphism import IdentityMorphism
sage: k.frobenius_endomorphism(5) == IdentityMorphism(k)
True
AUTHOR:
- Xavier Caruso (2012-06-29)
"""
from sage.rings.finite_rings.hom_finite_field_givaro import FrobeniusEndomorphism_givaro
return FrobeniusEndomorphism_givaro(self, n) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/finite_rings/finite_field_givaro.py | 0.921019 | 0.513425 | finite_field_givaro.py | pypi |
from sage.rings.finite_rings.finite_field_base import FiniteField
from sage.libs.pari.all import pari
from sage.rings.integer import Integer
from sage.misc.superseded import deprecated_function_alias
def late_import():
"""
Imports various modules after startup.
EXAMPLES::
sage: sage.rings.finite_rings.finite_field_ntl_gf2e.late_import()
sage: sage.rings.finite_rings.finite_field_ntl_gf2e.GF2 is None # indirect doctest
False
"""
if "GF2" in globals():
return
global is_FiniteField, exists_conway_polynomial, conway_polynomial, Cache_ntl_gf2e, GF, GF2, is_Polynomial
import sage.rings.finite_rings.finite_field_base
is_FiniteField = sage.rings.finite_rings.finite_field_base.is_FiniteField
import sage.rings.finite_rings.conway_polynomials
exists_conway_polynomial = sage.rings.finite_rings.conway_polynomials.exists_conway_polynomial
conway_polynomial = sage.rings.finite_rings.conway_polynomials.conway_polynomial
import sage.rings.finite_rings.element_ntl_gf2e
Cache_ntl_gf2e = sage.rings.finite_rings.element_ntl_gf2e.Cache_ntl_gf2e
import sage.rings.finite_rings.finite_field_constructor
GF = sage.rings.finite_rings.finite_field_constructor.GF
GF2 = GF(2)
import sage.rings.polynomial.polynomial_element
is_Polynomial = sage.rings.polynomial.polynomial_element.is_Polynomial
class FiniteField_ntl_gf2e(FiniteField):
"""
Finite Field of characteristic 2 and order `2^n`.
INPUT:
- ``q`` -- `2^n` (must be 2 power)
- ``names`` -- variable used for poly_repr (default: ``'a'``)
- ``modulus`` -- A minimal polynomial to use for reduction.
- ``repr`` -- controls the way elements are printed to the user:
(default: ``'poly'``)
- ``'poly'``: polynomial representation
OUTPUT:
Finite field with characteristic 2 and cardinality `2^n`.
EXAMPLES::
sage: k.<a> = GF(2^16)
sage: type(k)
<class 'sage.rings.finite_rings.finite_field_ntl_gf2e.FiniteField_ntl_gf2e_with_category'>
sage: k.<a> = GF(2^1024)
sage: k.modulus()
x^1024 + x^19 + x^6 + x + 1
sage: set_random_seed(6397)
sage: k.<a> = GF(2^17, modulus='random')
sage: k.modulus()
x^17 + x^16 + x^15 + x^10 + x^8 + x^6 + x^4 + x^3 + x^2 + x + 1
sage: k.modulus().is_irreducible()
True
sage: k.<a> = GF(2^211, modulus='minimal_weight')
sage: k.modulus()
x^211 + x^11 + x^10 + x^8 + 1
sage: k.<a> = GF(2^211, modulus='conway')
sage: k.modulus()
x^211 + x^9 + x^6 + x^5 + x^3 + x + 1
sage: k.<a> = GF(2^23, modulus='conway')
sage: a.multiplicative_order() == k.order() - 1
True
"""
def __init__(self, q, names="a", modulus=None, repr="poly"):
"""
Initialize ``self``.
TESTS::
sage: k.<a> = GF(2^100, modulus='strangeinput')
Traceback (most recent call last):
...
ValueError: no such algorithm for finding an irreducible polynomial: strangeinput
sage: k.<a> = GF(2^20) ; type(k)
<class 'sage.rings.finite_rings.finite_field_ntl_gf2e.FiniteField_ntl_gf2e_with_category'>
sage: loads(dumps(k)) is k
True
sage: k1.<a> = GF(2^16)
sage: k2.<a> = GF(2^17)
sage: k1 == k2
False
sage: k3.<a> = GF(2^16, impl="pari_ffelt")
sage: k1 == k3
False
sage: TestSuite(k).run()
sage: k.<a> = GF(2^64)
sage: k._repr_option('element_is_atomic')
False
sage: P.<x> = PolynomialRing(k)
sage: (a+1)*x # indirect doctest
(a + 1)*x
"""
late_import()
q = Integer(q)
if q < 2:
raise ValueError("q must be a 2-power")
k = q.exact_log(2)
if q != 1 << k:
raise ValueError("q must be a 2-power")
FiniteField.__init__(self, GF2, names, normalize=True)
from sage.rings.polynomial.polynomial_element import is_Polynomial
if not is_Polynomial(modulus):
raise TypeError("modulus must be a polynomial")
self._cache = Cache_ntl_gf2e(self, k, modulus)
self._modulus = modulus
def characteristic(self):
"""
Return the characteristic of ``self`` which is 2.
EXAMPLES::
sage: k.<a> = GF(2^16,modulus='random')
sage: k.characteristic()
2
"""
return Integer(2)
def order(self):
"""
Return the cardinality of this field.
EXAMPLES::
sage: k.<a> = GF(2^64)
sage: k.order()
18446744073709551616
"""
return self._cache.order()
def degree(self):
r"""
If this field has cardinality `2^n` this method returns `n`.
EXAMPLES::
sage: k.<a> = GF(2^64)
sage: k.degree()
64
"""
return self._cache.degree()
def _element_constructor_(self, e):
"""
Coerces several data types to ``self``.
INPUT:
- ``e`` -- data to coerce
EXAMPLES::
sage: k.<a> = GF(2^20)
sage: k(1) # indirect doctest
1
sage: k(int(2))
0
sage: k('a+1')
a + 1
sage: k('b+1')
Traceback (most recent call last):
...
NameError: name 'b' is not defined
sage: R.<x>=GF(2)[]
sage: k(1+x+x^10+x^55)
a^19 + a^17 + a^16 + a^15 + a^12 + a^11 + a^8 + a^6 + a^4 + a^2 + 1
sage: V = k.vector_space(map=False)
sage: v = V.random_element()
sage: k(v) == sum(a^i if v[i] else 0 for i in range(len(v)))
True
sage: vector(k(v)) == v
True
sage: k(pari('Mod(1,2)*a^20'))
a^10 + a^9 + a^7 + a^6 + a^5 + a^4 + a + 1
"""
return self._cache.import_data(e)
def gen(self, n=0):
r"""
Return a generator of ``self`` over its prime field, which is a
root of ``self.modulus()``.
INPUT:
- ``n`` -- must be 0
OUTPUT:
An element `a` of ``self`` such that ``self.modulus()(a) == 0``.
.. WARNING::
This generator is not guaranteed to be a generator for the
multiplicative group. To obtain the latter, use
:meth:`~sage.rings.finite_rings.finite_field_base.FiniteFields.multiplicative_generator()`
or use the ``modulus="primitive"`` option when constructing
the field.
EXAMPLES::
sage: k.<a> = GF(2^19)
sage: k.gen() == a
True
sage: a
a
TESTS::
sage: GF(2, impl='ntl').gen()
1
sage: GF(2, impl='ntl', modulus=polygen(GF(2)) ).gen()
0
sage: GF(2^19, 'a').gen(1)
Traceback (most recent call last):
...
IndexError: only one generator
"""
if n:
raise IndexError("only one generator")
return self._cache._gen
def prime_subfield(self):
r"""
Return the prime subfield `\GF{p}` of ``self`` if ``self`` is
`\GF{p^n}`.
EXAMPLES::
sage: F.<a> = GF(2^16)
sage: F.prime_subfield()
Finite Field of size 2
"""
return GF2
def from_integer(self, number):
r"""
Given an integer `n` less than :meth:`cardinality` with base `2`
representation `a_0 + 2 \cdot a_1 + \cdots + 2^k a_k`, returns
`a_0 + a_1 \cdot x + \cdots + a_k x^k`, where `x` is the
generator of this finite field.
INPUT:
- ``number`` -- an integer
EXAMPLES::
sage: k.<a> = GF(2^48)
sage: k.from_integer(2^43 + 2^15 + 1)
a^43 + a^15 + 1
sage: k.from_integer(33793)
a^15 + a^10 + 1
sage: 33793.digits(2) # little endian
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
"""
return self._cache.fetch_int(number)
fetch_int = deprecated_function_alias(33941, from_integer)
def _pari_modulus(self):
"""
Return PARI object which is equivalent to the
polynomial/modulus of ``self``.
EXAMPLES::
sage: k1.<a> = GF(2^16)
sage: k1._pari_modulus()
Mod(1, 2)*a^16 + Mod(1, 2)*a^5 + Mod(1, 2)*a^3 + Mod(1, 2)*a^2 + Mod(1, 2)
"""
f = pari(str(self.modulus()))
return f.subst('x', 'a') * pari("Mod(1,%s)"%self.characteristic()) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/finite_rings/finite_field_ntl_gf2e.py | 0.883958 | 0.449211 | finite_field_ntl_gf2e.py | pypi |
from .element_pari_ffelt import FiniteFieldElement_pari_ffelt
from .finite_field_base import FiniteField
from .finite_field_constructor import GF
class FiniteField_pari_ffelt(FiniteField):
"""
Finite fields whose cardinality is a prime power (not a prime),
implemented using PARI's ``FFELT`` type.
INPUT:
- ``p`` -- prime number
- ``modulus`` -- an irreducible polynomial of degree at least 2
over the field of `p` elements
- ``name`` -- string: name of the distinguished generator
(default: variable name of ``modulus``)
OUTPUT:
A finite field of order `q = p^n`, generated by a distinguished
element with minimal polynomial ``modulus``. Elements are
represented as polynomials in ``name`` of degree less than `n`.
.. NOTE::
Direct construction of :class:`FiniteField_pari_ffelt` objects
requires specifying a characteristic and a modulus. To
construct a finite field by specifying a cardinality and an
algorithm for finding an irreducible polynomial, use the
``FiniteField`` constructor with ``impl='pari_ffelt'``.
EXAMPLES:
Some computations with a finite field of order 9::
sage: k = FiniteField(9, 'a', impl='pari_ffelt')
sage: k
Finite Field in a of size 3^2
sage: k.is_field()
True
sage: k.characteristic()
3
sage: a = k.gen()
sage: a
a
sage: a.parent()
Finite Field in a of size 3^2
sage: a.charpoly('x')
x^2 + 2*x + 2
sage: [a^i for i in range(8)]
[1, a, a + 1, 2*a + 1, 2, 2*a, 2*a + 2, a + 2]
sage: TestSuite(k).run()
Next we compute with a finite field of order 16::
sage: k16 = FiniteField(16, 'b', impl='pari_ffelt')
sage: z = k16.gen()
sage: z
b
sage: z.charpoly('x')
x^4 + x + 1
sage: k16.is_field()
True
sage: k16.characteristic()
2
sage: z.multiplicative_order()
15
Illustration of dumping and loading::
sage: K = FiniteField(7^10, 'b', impl='pari_ffelt')
sage: loads(K.dumps()) == K
True
sage: K = FiniteField(10007^10, 'a', impl='pari_ffelt')
sage: loads(K.dumps()) == K
True
"""
def __init__(self, p, modulus, name=None):
"""
Create a finite field of characteristic `p` defined by the
polynomial ``modulus``, with distinguished generator called
``name``.
EXAMPLES::
sage: from sage.rings.finite_rings.finite_field_pari_ffelt import FiniteField_pari_ffelt
sage: R.<x> = PolynomialRing(GF(3))
sage: k = FiniteField_pari_ffelt(3, x^2 + 2*x + 2, 'a'); k
Finite Field in a of size 3^2
"""
n = modulus.degree()
if n < 2:
raise ValueError("the degree must be at least 2")
FiniteField.__init__(self, base=GF(p), names=name, normalize=True)
self._modulus = modulus
self._degree = n
self._gen_pari = modulus._pari_with_name(self._names[0]).ffgen()
self._zero_element = self.element_class(self, 0)
self._one_element = self.element_class(self, 1)
self._gen = self.element_class(self, self._gen_pari)
Element = FiniteFieldElement_pari_ffelt
def __reduce__(self):
"""
For pickling.
EXAMPLES::
sage: k.<b> = FiniteField(5^20, impl='pari_ffelt')
sage: type(k)
<class 'sage.rings.finite_rings.finite_field_pari_ffelt.FiniteField_pari_ffelt_with_category'>
sage: k is loads(dumps(k))
True
"""
return self._factory_data[0].reduce_data(self)
def gen(self, n=0):
"""
Return a generator of ``self`` over its prime field, which is a
root of ``self.modulus()``.
INPUT:
- ``n`` -- must be 0
OUTPUT:
An element `a` of ``self`` such that ``self.modulus()(a) == 0``.
.. WARNING::
This generator is not guaranteed to be a generator for the
multiplicative group. To obtain the latter, use
:meth:`~sage.rings.finite_rings.finite_field_base.FiniteFields.multiplicative_generator()`
or use the ``modulus="primitive"`` option when constructing
the field.
EXAMPLES::
sage: R.<x> = PolynomialRing(GF(2))
sage: FiniteField(2^4, 'b', impl='pari_ffelt').gen()
b
sage: k = FiniteField(3^4, 'alpha', impl='pari_ffelt')
sage: a = k.gen()
sage: a
alpha
sage: a^4
alpha^3 + 1
"""
if n:
raise IndexError("only one generator")
return self._gen
def characteristic(self):
"""
Return the characteristic of ``self``.
EXAMPLES::
sage: F = FiniteField(3^4, 'a', impl='pari_ffelt')
sage: F.characteristic()
3
"""
# This works since self is not its own prime field.
return self.base_ring().characteristic()
def degree(self):
"""
Returns the degree of ``self`` over its prime field.
EXAMPLES::
sage: F = FiniteField(3^20, 'a', impl='pari_ffelt')
sage: F.degree()
20
"""
return self._degree | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/finite_rings/finite_field_pari_ffelt.py | 0.905375 | 0.650273 | finite_field_pari_ffelt.py | pypi |
r"""
Galois groups of Finite Fields
"""
from sage.groups.abelian_gps.abelian_group_element import AbelianGroupElement
from sage.groups.galois_group import GaloisGroup_cyc
from sage.rings.integer_ring import ZZ
from sage.rings.finite_rings.hom_finite_field import FiniteFieldHomomorphism_generic, FrobeniusEndomorphism_finite_field
class GaloisGroup_GFElement(AbelianGroupElement):
def as_hom(self):
r"""
Return the automorphism of the finite field corresponding to this element.
EXAMPLES::
sage: GF(3^6).galois_group()([4]).as_hom()
Frobenius endomorphism z6 |--> z6^(3^4) on Finite Field in z6 of size 3^6
"""
n = self.exponents()[0]
return self.parent()._field.frobenius_endomorphism(n)
def __call__(self, x):
r"""
Return the action of this automorphism on an element `x` of the finite field.
EXAMPLES::
sage: k.<a> = GF(3^6)
sage: g = k.galois_group()([4])
sage: g(a) == a^(3^4)
True
"""
return self.as_hom()(x)
def fixed_field(self):
r"""
The fixed field of this automorphism.
EXAMPLES::
sage: k.<a> = GF(3^12)
sage: g = k.galois_group()([8])
sage: k0, embed = g.fixed_field()
sage: k0.cardinality()
81
sage: embed.domain() is k0
True
sage: embed.codomain() is k
True
"""
return self.as_hom().fixed_field()
class GaloisGroup_GF(GaloisGroup_cyc):
r"""
The Galois group of a finite field.
"""
Element = GaloisGroup_GFElement
def __init__(self, field):
r"""
Create a Galois group.
TESTS::
sage: TestSuite(GF(9).galois_group()).run()
"""
GaloisGroup_cyc.__init__(self, field, (field.degree(),), gen_names="Frob")
def _repr_(self):
r"""
String representation of this Galois group
EXAMPLES::
sage: GF(9).galois_group()
Galois group C2 of GF(3^2)
"""
return "Galois group C{0} of GF({1}^{0})".format(self._field.degree(), self._field.characteristic())
def _element_constructor_(self, x, check=True):
r"""
Create an element of this Galois group from ``x``.
INPUT:
- ``x`` -- one of the following (`G` is this Galois group):
- the integer 1, denoting the identity of `G`;
- an element of `G`;
- a list of length 1, giving the exponent of Frobenius
- a permutation of the right length that defines an element of `G`,
or anything that coerces into such a permutation;
- an automorphism of the finite field.
- ``check`` -- check that automorphisms have the correct domain and codomain
EXAMPLES::
sage: k = GF(3^3)
sage: G = k.galois_group()
sage: G(1)
1
sage: G([2])
Frob^2
sage: G(G.gens()[0])
Frob
sage: G([(1,3,2)])
Frob^2
sage: G(k.hom(k.gen()^3, k))
Frob
sage: G(k.frobenius_endomorphism())
Frob
"""
if x == 1:
return self.element_class(self, [0])
k = self._field
d = k.degree()
n = None
if isinstance(x, GaloisGroup_GFElement) and x.parent() is self:
n = x.exponents()[0]
elif isinstance(x, FiniteFieldHomomorphism_generic):
if check and not (x.domain() is k and x.codomain() is k):
raise ValueError("Not an automorphism of the correct finite field")
a = k.gen()
b = x(a)
q = k.base_ring().cardinality()
n = 0
while n < d:
if a == b:
break
n += 1
a = a**q
else:
raise RuntimeError("Automorphism was not a power of Frobenius")
elif isinstance(x, FrobeniusEndomorphism_finite_field):
if check and not x.domain() is k:
raise ValueError("Not an automorphism of the correct finite field")
n = x.power()
elif isinstance(x, list) and len(x) == 1 and x[0] in ZZ:
n = x[0]
else:
g = self.permutation_group()(x)
n = g(1) - 1
return self.element_class(self, [n]) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/finite_rings/galois_group.py | 0.894332 | 0.595287 | galois_group.py | pypi |
from sage.categories.morphism import Morphism
class FiniteFieldVectorSpaceIsomorphism(Morphism):
"""
Base class of the vector space isomorphism between a finite field
and a vector space over a subfield of the finite field.
"""
def _repr_(self):
"""
Return the string representation of this isomorphism
between a finite field and a vector space.
EXAMPLES::
sage: E = GF(16)
sage: F = GF(4)
sage: V, phi, psi = E.vector_space(E, map=True)
sage: phi
Isomorphism:
From: Vector space of dimension 1 over Finite Field in z4 of size 2^4
To: Finite Field in z4 of size 2^4
"""
s = "Isomorphism:"
s += "\n From: {}".format(self.domain())
s += "\n To: {}".format(self.codomain())
return s
def is_injective(self):
"""
EXAMPLES::
sage: E = GF(9)
sage: F = GF(3)
sage: V, phi, psi = E.vector_space(E, map=True)
sage: phi.is_injective()
True
"""
return True
def is_surjective(self):
"""
EXAMPLES::
sage: E = GF(9)
sage: F = GF(3)
sage: V, phi, psi = E.vector_space(E, map=True)
sage: phi.is_surjective()
True
"""
return True
class MorphismVectorSpaceToFiniteField(FiniteFieldVectorSpaceIsomorphism):
"""
Isomorphisms from vector spaces to finite fields.
"""
def __init__(self, V, K, C):
"""
Initialize.
INPUT:
- ``V`` -- vector space
- ``K`` -- finite field
- ``C`` -- matrix
EXAMPLES::
sage: E = GF(16)
sage: F = GF(4)
sage: V, phi, psi = E.vector_space(E, map=True)
sage: phi
Isomorphism:
From: Vector space of dimension 1 over Finite Field in z4 of size 2^4
To: Finite Field in z4 of size 2^4
"""
if C.is_mutable():
C = C.__copy__()
C.set_immutable()
self._C = C
FiniteFieldVectorSpaceIsomorphism.__init__(self, V, K)
def _call_(self, v):
r"""
TESTS::
sage: E = GF(64)
sage: F = GF(4)
sage: V, phi, psi = E.vector_space(F, map=True)
sage: phi(V.zero())
0
sage: [phi(v) for v in V.basis()]
[1, z6, z6^2]
"""
E = self.codomain() # = GF((p^n)^m)
V = self.domain() # = GF(p^n)^m
m = V.dimension()
F = V.base_ring() # = GF(p^n)
n = F.degree()
if m == n == 1:
# 1x1 matrix
return self._C[0][0] * v[0]
else:
# expand v as a vector over GF(p)
w = self._C.row_ambient_module()()
for i in range(m):
w[i*n:(i+1)*n] = v[i]._vector_()
return E(w * self._C)
class MorphismFiniteFieldToVectorSpace(FiniteFieldVectorSpaceIsomorphism):
"""
Isomorphisms from finite fields to vector spaces
"""
def __init__(self, K, V, C):
"""
Initialize.
INPUT:
- ``K`` -- finite field GF((p^m)^n)
- ``V`` -- vector space of rank n over GF(p^m)
- ``C`` -- matrix
EXAMPLES::
sage: E = GF(16)
sage: F = GF(4)
sage: V, phi, psi = E.vector_space(E, map=True)
sage: psi
Isomorphism:
From: Finite Field in z4 of size 2^4
To: Vector space of dimension 1 over Finite Field in z4 of size 2^4
"""
if C.is_mutable():
C = C.__copy__()
C.set_immutable()
self._C = C
FiniteFieldVectorSpaceIsomorphism.__init__(self, K, V)
def _call_(self, e):
r"""
TESTS::
sage: E = GF(64)
sage: F = GF(4)
sage: V, phi, psi = E.vector_space(F, map=True)
sage: psi(E.zero())
(0, 0, 0)
sage: psi(E.one())
(1, 0, 0)
sage: psi(E.gen())
(0, 1, 0)
"""
V = self.codomain() # = GF(p^n)^m
m = V.dimension()
F = V.base_ring() # = GF(p^n)
n = F.degree()
w = e._vector_() * self._C
if F.degree() > 1:
return V([F(w[i*n:(i+1)*n]) for i in range(m)])
else:
return w | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/finite_rings/maps_finite_field.py | 0.884533 | 0.676854 | maps_finite_field.py | pypi |
r"""
Educational versions of Groebner basis algorithms: triangular factorization
In this file is the implementation of two algorithms in [Laz1992]_.
The main algorithm is ``Triangular``; a secondary algorithm, necessary for the
first, is ``ElimPolMin``. As per Lazard's formulation, the implementation works
with any term ordering, not only lexicographic.
Lazard does not specify a few of the subalgorithms implemented as the
functions
* ``is_triangular``,
* ``is_linearly_dependent``, and
* ``linear_representation``.
The implementations are not hard, and the choice of algorithm is described
with the relevant function.
No attempt was made to optimize these algorithms as the emphasis of this
implementation is a clean and easy presentation.
Examples appear with the appropriate function.
AUTHORS:
- John Perry (2009-02-24): initial version, but some words of
documentation were stolen shamelessly from Martin Albrecht's
``toy_buchberger.py``.
"""
def is_triangular(B) -> bool:
"""
Check whether the basis ``B`` of an ideal is triangular.
That is: check whether the largest variable in ``B[i]`` with
respect to the ordering of the base ring ``R`` is ``R.gens()[i]``.
The algorithm is based on the definition of a triangular basis,
given by Lazard in 1992 in [Laz1992]_.
INPUT:
- ``B`` -- a list/tuple of polynomials or a multivariate polynomial ideal
OUTPUT:
``True`` if the basis is triangular; ``False`` otherwise.
EXAMPLES::
sage: from sage.rings.polynomial.toy_variety import is_triangular
sage: R.<x,y,z> = PolynomialRing(QQ)
sage: p1 = x^2*y + z^2
sage: p2 = y*z + z^3
sage: p3 = y+z
sage: is_triangular(R.ideal(p1,p2,p3))
False
sage: p3 = z^2 - 3
sage: is_triangular(R.ideal(p1,p2,p3))
True
"""
# type checking in a probably vain attempt to avoid stupid errors
if isinstance(B, (list, tuple)):
G = B
else:
try:
G = B.gens()
except Exception:
raise TypeError("is_triangular wants as input an ideal, or a list of polynomials\n")
vars = G[0].parent().gens()
n = len(G)
# We expect the polynomials of G to be ordered G[i].lm() > G[i+1].lm();
# by definition, the largest variable that appears in G[i] must be vars[i].
for i in range(n):
for t in G[i].monomials():
for x in vars[0:i]:
if t.degree(x) != 0:
return False
return True
def coefficient_matrix(polys):
"""
Generate the matrix ``M`` whose entries are the coefficients of ``polys``.
The entries of row ``i`` of ``M`` consist of the coefficients of
``polys[i]``.
INPUT:
- ``polys`` -- a list/tuple of polynomials
OUTPUT:
A matrix ``M`` of the coefficients of ``polys``
EXAMPLES::
sage: from sage.rings.polynomial.toy_variety import coefficient_matrix
sage: R.<x,y> = PolynomialRing(QQ)
sage: coefficient_matrix([x^2 + 1, y^2 + 1, x*y + 1])
[1 0 0 1]
[0 0 1 1]
[0 1 0 1]
.. NOTE::
This function may be merged with
:meth:`sage.rings.polynomial.multi_polynomial_sequence.PolynomialSequence_generic.coefficient_matrix()` in the future.
"""
from sage.matrix.constructor import matrix
R = polys[0].base_ring()
mons = set()
for each in polys:
mons = mons.union(each.monomials())
mons = list(mons)
mons.sort(reverse=True)
M = matrix(R, len(polys), len(mons))
for i in range(len(polys)):
imons = polys[i].monomials()
icoeffs = polys[i].coefficients()
for j in range(len(imons)):
M[i, mons.index(imons[j])] = icoeffs[j]
return M
def is_linearly_dependent(polys) -> bool:
"""
Decide whether the polynomials of ``polys`` are linearly dependent.
Here ``polys`` is a collection of polynomials.
The algorithm creates a matrix of coefficients of the monomials of
``polys``. It computes the echelon form of the matrix, then checks whether
any of the rows is the zero vector.
Essentially this relies on the fact that the monomials are linearly
independent, and therefore is building a linear map from the vector space of
the monomials to the canonical basis of ``R^n``, where ``n`` is the number of
distinct monomials in ``polys``. There is a zero vector iff there is a
linear dependence among ``polys``.
The case where ``polys=[]`` is considered to be not linearly dependent.
INPUT:
- ``polys`` -- a list/tuple of polynomials
OUTPUT:
``True`` if the elements of ``polys`` are linearly dependent;
``False`` otherwise.
EXAMPLES::
sage: from sage.rings.polynomial.toy_variety import is_linearly_dependent
sage: R.<x,y> = PolynomialRing(QQ)
sage: B = [x^2 + 1, y^2 + 1, x*y + 1]
sage: p = 3*B[0] - 2*B[1] + B[2]
sage: is_linearly_dependent(B + [p])
True
sage: p = x*B[0]
sage: is_linearly_dependent(B + [p])
False
sage: is_linearly_dependent([])
False
"""
if not polys:
return False
M = coefficient_matrix(polys).echelon_form()
return any(M.row(each).is_zero() for each in range(M.nrows()))
def linear_representation(p, polys):
"""
Assuming that ``p`` is a linear combination of ``polys``,
determine coefficients that describe the linear combination.
This probably does not work for any inputs except ``p``, a polynomial,
and ``polys``, a sequence of polynomials.
If ``p`` is not in fact a linear combination of ``polys``,
the function raises an exception.
The algorithm creates a matrix of coefficients of the monomials of
``polys`` and ``p``, with the coefficients of ``p`` in the last
row. It augments this matrix with the appropriate identity matrix, then
computes the echelon form of the augmented matrix. The last row should
contain zeroes in the first columns, and the last
columns contain a linear dependence relation. Solving for
the desired linear relation is straightforward.
INPUT:
- ``p`` -- a polynomial
- ``polys`` -- a list/tuple of polynomials
OUTPUT:
If ``n == len(polys)``, returns ``[a[0],a[1],...,a[n-1]]``
such that ``p == a[0]*poly[0] + ... + a[n-1]*poly[n-1]``.
EXAMPLES::
sage: from sage.rings.polynomial.toy_variety import linear_representation
sage: R.<x,y> = PolynomialRing(GF(32003))
sage: B = [x^2 + 1, y^2 + 1, x*y + 1]
sage: p = 3*B[0] - 2*B[1] + B[2]
sage: linear_representation(p, B)
[3, 32001, 1]
"""
from sage.matrix.constructor import diagonal_matrix
R = p.base_ring()
M = coefficient_matrix(polys + [p]).augment(diagonal_matrix(R, [1 for each in range(len(polys) + 1)]))
M.echelonize()
j = M.ncols() - 1
n = M.nrows() - 1
offset = M.ncols() - M.nrows()
return [M[n, offset + each] / (-M[n, j]) for each in range(len(polys))]
def triangular_factorization(B, n=-1):
"""
Compute the triangular factorization of the Groebner basis ``B`` of an ideal.
This will not work properly if ``B`` is not a Groebner basis!
The algorithm used is that described in a 1992 paper by Daniel Lazard [Laz1992]_.
It is not necessary for the term ordering to be lexicographic.
INPUT:
- ``B`` -- a list/tuple of polynomials or a multivariate polynomial ideal
- ``n`` -- the recursion parameter (default: ``-1``)
OUTPUT:
A list ``T`` of triangular sets ``T_0``, ``T_1``, etc.
EXAMPLES::
sage: from sage.misc.verbose import set_verbose
sage: set_verbose(0)
sage: from sage.rings.polynomial.toy_variety import triangular_factorization
sage: R.<x,y,z> = PolynomialRing(GF(32003))
sage: p1 = x^2*(x-1)^3*y^2*(z-3)^3
sage: p2 = z^2 - z
sage: p3 = (x-2)^2*(y-1)^3
sage: I = R.ideal(p1,p2,p3)
sage: triangular_factorization(I.groebner_basis())
[[x^2 - 4*x + 4, y, z],
[x^5 - 3*x^4 + 3*x^3 - x^2, y - 1, z],
[x^2 - 4*x + 4, y, z - 1],
[x^5 - 3*x^4 + 3*x^3 - x^2, y - 1, z - 1]]
"""
# type checking in a probably vain attempt to avoid stupid errors
if isinstance(B, (tuple, list)):
G = B
else:
try:
G = B.gens()
except Exception:
raise TypeError("triangular_factorization wants as input an ideal, or a list of polynomials\n")
# easy cases
if not G:
return []
if is_triangular(G):
return [G]
# this is what we get paid for...
# first, find the univariate polynomial in the ideal
# corresponding to the smallest variable under consideration
p = elim_pol(G, n)
R = p.parent()
family = []
# recursively build the family,
# looping through the factors of p
for q, a in p.factor():
# Construct an analog to I in (R.quotient(R.ideal(q)))[x_0,x_1,...x_{n-1}]
ideal_I = R.ideal([each.reduce([q]) for each in G])
if len(ideal_I.gens()) == 1:
# save some effort
H = [ideal_I.gens()[0]]
else:
H = ideal_I.groebner_basis()
T = triangular_factorization(list(H), n - 1)
# now add the current factor q of p to the factorization
for each in T:
each.append(q)
for each in T:
family.append(each)
return family
def elim_pol(B, n=-1):
"""
Find the unique monic polynomial of lowest degree and lowest variable
in the ideal described by ``B``.
For the purposes of the triangularization algorithm, it is necessary to
preserve the ring, so ``n`` specifies which variable to check.
By default, we check the last one, which should also be the smallest.
The algorithm may not work if you are trying to cheat:
``B`` should describe the Groebner basis of a zero-dimensional ideal.
However, it is not necessary for the Groebner basis to be lexicographic.
The algorithm is taken from a 1993 paper by Lazard [Laz1992]_.
INPUT:
- ``B`` -- a list/tuple of polynomials or a multivariate polynomial ideal
- ``n`` -- the variable to check (see above) (default: ``-1``)
EXAMPLES::
sage: from sage.misc.verbose import set_verbose
sage: set_verbose(0)
sage: from sage.rings.polynomial.toy_variety import elim_pol
sage: R.<x,y,z> = PolynomialRing(GF(32003))
sage: p1 = x^2*(x-1)^3*y^2*(z-3)^3
sage: p2 = z^2 - z
sage: p3 = (x-2)^2*(y-1)^3
sage: I = R.ideal(p1,p2,p3)
sage: elim_pol(I.groebner_basis())
z^2 - z
"""
# type checking in a probably vain attempt to avoid stupid errors
if isinstance(B, (list, tuple)):
G = B
else:
try:
G = B.gens()
except Exception:
raise TypeError("elim_pol wants as input an ideal or a list of polynomials")
# setup -- main algorithm
x = G[0].parent().gens()[n]
monom = x**0
nfm = monom.reduce(G)
lnf = []
listmonom = []
# ratchet up the degree of monom, adding each time a normal form,
# until finally the normal form is a linear combination
# of the previous normal forms
while not is_linearly_dependent(lnf + [nfm]):
lnf.insert(0, nfm)
listmonom.append(monom)
monom = x * monom
nfm = monom.reduce(G)
result = monom
coeffs = linear_representation(nfm, lnf)
for each in range(len(coeffs)):
result -= coeffs[each] * lnf[each]
return result | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/toy_variety.py | 0.949424 | 0.887156 | toy_variety.py | pypi |
from copy import copy
from sage.rings.complex_mpfr import ComplexField
from sage.rings.complex_interval_field import ComplexIntervalField
from sage.rings.qqbar import AA, QQbar
from sage.arith.misc import sort_complex_numbers_for_display
from sage.rings.polynomial.refine_root import refine_root
def interval_roots(p, rts, prec):
"""
We are given a squarefree polynomial p, a list of estimated roots,
and a precision.
We attempt to verify that the estimated roots are in fact distinct
roots of the polynomial, using interval arithmetic of precision prec.
If we succeed, we return a list of intervals bounding the roots; if we
fail, we return None.
EXAMPLES::
sage: x = polygen(ZZ)
sage: p = x^3 - 1
sage: rts = [CC.zeta(3)^i for i in range(0, 3)]
sage: from sage.rings.polynomial.complex_roots import interval_roots
sage: interval_roots(p, rts, 53)
[1, -0.500000000000000? + 0.866025403784439?*I, -0.500000000000000? - 0.866025403784439?*I]
sage: interval_roots(p, rts, 200)
[1, -0.500000000000000000000000000000000000000000000000000000000000? + 0.866025403784438646763723170752936183471402626905190314027904?*I, -0.500000000000000000000000000000000000000000000000000000000000? - 0.866025403784438646763723170752936183471402626905190314027904?*I]
"""
CIF = ComplexIntervalField(prec)
CIFX = CIF['x']
ip = CIFX(p)
ipd = CIFX(p.derivative())
irts = []
for rt in rts:
irt = refine_root(ip, ipd, CIF(rt), CIF)
if irt is None:
return None
irts.append(irt)
return irts
def intervals_disjoint(intvs):
"""
Given a list of complex intervals, check whether they are pairwise
disjoint.
EXAMPLES::
sage: from sage.rings.polynomial.complex_roots import intervals_disjoint
sage: a = CIF(RIF(0, 3), 0)
sage: b = CIF(0, RIF(1, 3))
sage: c = CIF(RIF(1, 2), RIF(1, 2))
sage: d = CIF(RIF(2, 3), RIF(2, 3))
sage: intervals_disjoint([a,b,c,d])
False
sage: d2 = CIF(RIF(2, 3), RIF(2.001, 3))
sage: intervals_disjoint([a,b,c,d2])
True
"""
# This may be quadratic in perverse cases, but will take only
# n log(n) time in typical cases.
intvs = sorted(copy(intvs))
column = []
prev_real = None
def column_disjoint():
column.sort()
row = []
prev_imag = None
def row_disjoint():
for a in range(len(row)):
for b in range(a+1, len(row)):
if row[a].overlaps(row[b]):
return False
return True
for (y_imag, y) in column:
if prev_imag is not None and y_imag > prev_imag:
if not row_disjoint():
return False
row = []
prev_imag = y_imag
row.append(y)
if not row_disjoint():
return False
return True
for x in intvs:
x_real = x.real()
if prev_real is not None and x_real > prev_real:
if not column_disjoint():
return False
column = []
prev_real = x_real
column.append((x.imag(), x))
if not column_disjoint():
return False
return True
def complex_roots(p, skip_squarefree=False, retval='interval', min_prec=0):
"""
Compute the complex roots of a given polynomial with exact
coefficients (integer, rational, Gaussian rational, and algebraic
coefficients are supported). Returns a list of pairs of a root
and its multiplicity.
Roots are returned as a ComplexIntervalFieldElement; each interval
includes exactly one root, and the intervals are disjoint.
By default, the algorithm will do a squarefree decomposition
to get squarefree polynomials. The skip_squarefree parameter
lets you skip this step. (If this step is skipped, and the polynomial
has a repeated root, then the algorithm will loop forever!)
You can specify retval='interval' (the default) to get roots as
complex intervals. The other options are retval='algebraic' to
get elements of QQbar, or retval='algebraic_real' to get only
the real roots, and to get them as elements of AA.
EXAMPLES::
sage: from sage.rings.polynomial.complex_roots import complex_roots
sage: x = polygen(ZZ)
sage: complex_roots(x^5 - x - 1)
[(1.167303978261419?, 1), (-0.764884433600585? - 0.352471546031727?*I, 1), (-0.764884433600585? + 0.352471546031727?*I, 1), (0.181232444469876? - 1.083954101317711?*I, 1), (0.181232444469876? + 1.083954101317711?*I, 1)]
sage: v=complex_roots(x^2 + 27*x + 181)
Unfortunately due to numerical noise there can be a small imaginary part to each
root depending on CPU, compiler, etc, and that affects the printing order. So we
verify the real part of each root and check that the imaginary part is small in
both cases::
sage: v # random
[(-14.61803398874990?..., 1), (-12.3819660112501...? + 0.?e-27*I, 1)]
sage: sorted((v[0][0].real(),v[1][0].real()))
[-14.61803398874989?, -12.3819660112501...?]
sage: v[0][0].imag().upper() < 1e25
True
sage: v[1][0].imag().upper() < 1e25
True
sage: K.<im> = QuadraticField(-1)
sage: eps = 1/2^100
sage: x = polygen(K)
sage: p = (x-1)*(x-1-eps)*(x-1+eps)*(x-1-eps*im)*(x-1+eps*im)
This polynomial actually has all-real coefficients, and is very, very
close to (x-1)^5::
sage: [RR(QQ(a)) for a in list(p - (x-1)^5)]
[3.87259191484932e-121, -3.87259191484932e-121]
sage: rts = complex_roots(p)
sage: [ComplexIntervalField(10)(rt[0] - 1) for rt in rts]
[-7.8887?e-31, 0, 7.8887?e-31, -7.8887?e-31*I, 7.8887?e-31*I]
We can get roots either as intervals, or as elements of QQbar or AA.
::
sage: p = (x^2 + x - 1)
sage: p = p * p(x*im)
sage: p
-x^4 + (im - 1)*x^3 + im*x^2 + (-im - 1)*x + 1
Two of the roots have a zero real component; two have a zero
imaginary component. These zero components will be found slightly
inaccurately, and the exact values returned are very sensitive to
the (non-portable) results of NumPy. So we post-process the roots
for printing, to get predictable doctest results.
::
sage: def tiny(x):
....: return x.contains_zero() and x.absolute_diameter() < 1e-14
sage: def smash(x):
....: x = CIF(x[0]) # discard multiplicity
....: if tiny(x.imag()): return x.real()
....: if tiny(x.real()): return CIF(0, x.imag())
sage: rts = complex_roots(p); type(rts[0][0]), sorted(map(smash, rts))
(<class 'sage.rings.complex_interval.ComplexIntervalFieldElement'>, [-1.618033988749895?, -0.618033988749895?*I, 1.618033988749895?*I, 0.618033988749895?])
sage: rts = complex_roots(p, retval='algebraic'); type(rts[0][0]), sorted(map(smash, rts))
(<class 'sage.rings.qqbar.AlgebraicNumber'>, [-1.618033988749895?, -0.618033988749895?*I, 1.618033988749895?*I, 0.618033988749895?])
sage: rts = complex_roots(p, retval='algebraic_real'); type(rts[0][0]), rts
(<class 'sage.rings.qqbar.AlgebraicReal'>, [(-1.618033988749895?, 1), (0.618033988749895?, 1)])
TESTS:
Verify that :trac:`12026` is fixed::
sage: f = matrix(QQ, 8, lambda i, j: 1/(i + j + 1)).charpoly()
sage: from sage.rings.polynomial.complex_roots import complex_roots
sage: len(complex_roots(f))
8
"""
if skip_squarefree:
factors = [(p, 1)]
else:
factors = p.squarefree_decomposition()
prec = 53
while True:
CC = ComplexField(prec)
CCX = CC['x']
all_rts = []
ok = True
for (factor, exp) in factors:
cfac = CCX(factor)
rts = cfac.roots(multiplicities=False)
# Make sure the number of roots we found is the degree. If
# we don't find that many roots, it's because the
# precision isn't big enough and though the (possibly
# exact) polynomial "factor" is squarefree, it is not
# squarefree as an element of CCX.
if len(rts) < factor.degree():
ok = False
break
irts = interval_roots(factor, rts, max(prec, min_prec))
if irts is None:
ok = False
break
if retval != 'interval':
factor = QQbar.common_polynomial(factor)
for irt in irts:
all_rts.append((irt, factor, exp))
if ok and intervals_disjoint([rt for (rt, fac, mult) in all_rts]):
all_rts = sort_complex_numbers_for_display(all_rts)
if retval == 'interval':
return [(rt, mult) for (rt, fac, mult) in all_rts]
elif retval == 'algebraic':
return [(QQbar.polynomial_root(fac, rt), mult) for (rt, fac, mult) in all_rts]
elif retval == 'algebraic_real':
rts = []
for (rt, fac, mult) in all_rts:
qqbar_rt = QQbar.polynomial_root(fac, rt)
if qqbar_rt.imag().is_zero():
rts.append((AA(qqbar_rt), mult))
return rts
prec = prec * 2 | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/complex_roots.py | 0.761272 | 0.682858 | complex_roots.py | pypi |
r"""
Educational version of the `d`-Groebner basis algorithm over PIDs
No attempt was made to optimize this algorithm as the emphasis of this
implementation is a clean and easy presentation.
.. NOTE::
The notion of 'term' and 'monomial' in [BW1993]_ is swapped from the
notion of those words in Sage (or the other way around, however you
prefer it). In Sage a term is a monomial multiplied by a
coefficient, while in [BW1993]_ a monomial is a term multiplied by a
coefficient. Also, what is called LM (the leading monomial) in
Sage is called HT (the head term) in [BW1993]_.
EXAMPLES::
sage: from sage.rings.polynomial.toy_d_basis import d_basis
First, consider an example from arithmetic geometry::
sage: A.<x,y> = PolynomialRing(ZZ, 2)
sage: B.<X,Y> = PolynomialRing(Rationals(),2)
sage: f = -y^2 - y + x^3 + 7*x + 1
sage: fx = f.derivative(x)
sage: fy = f.derivative(y)
sage: I = B.ideal([B(f),B(fx),B(fy)])
sage: I.groebner_basis()
[1]
Since the output is 1, we know that there are no generic
singularities.
To look at the singularities of the arithmetic surface, we need to do
the corresponding computation over `\ZZ`::
sage: I = A.ideal([f,fx,fy])
sage: gb = d_basis(I); gb
[x - 2020, y - 11313, 22627]
sage: gb[-1].factor()
11^3 * 17
This Groebner Basis gives a lot of information. First, the only
fibers (over `\ZZ`) that are not smooth are at 11 = 0, and 17 = 0.
Examining the Groebner Basis, we see that we have a simple node in
both the fiber at 11 and at 17. From the factorization, we see that
the node at 17 is regular on the surface (an `I_1` node), but the node
at 11 is not. After blowing up this non-regular point, we find that
it is an `I_3` node.
Another example. This one is from the Magma Handbook::
sage: P.<x, y, z> = PolynomialRing(IntegerRing(), 3, order='lex')
sage: I = ideal( x^2 - 1, y^2 - 1, 2*x*y - z)
sage: I = Ideal(d_basis(I))
sage: x.reduce(I)
x
sage: (2*x).reduce(I)
y*z
To compute modulo 4, we can add the generator 4 to our basis.::
sage: I = ideal( x^2 - 1, y^2 - 1, 2*x*y - z, 4)
sage: gb = d_basis(I)
sage: R = P.change_ring(IntegerModRing(4))
sage: gb = [R(f) for f in gb if R(f)]; gb
[x^2 - 1, x*z + 2*y, 2*x - y*z, y^2 - 1, z^2, 2*z]
A third example is also from the Magma Handbook.
This example shows how one can use Groebner bases over the integers to
find the primes modulo which a system of equations has a solution,
when the system has no solutions over the rationals.
We first form a certain ideal `I` in `\ZZ[x, y, z]`, and note that the
Groebner basis of `I` over `\QQ` contains 1, so there are no solutions
over `\QQ` or an algebraic closure of it (this is not surprising as
there are 4 equations in 3 unknowns). ::
sage: P.<x, y, z> = PolynomialRing(IntegerRing(), 3, order='degneglex')
sage: I = ideal( x^2 - 3*y, y^3 - x*y, z^3 - x, x^4 - y*z + 1 )
sage: I.change_ring(P.change_ring(RationalField())).groebner_basis()
[1]
However, when we compute the Groebner basis of I (defined over `\ZZ`), we
note that there is a certain integer in the ideal which is not 1::
sage: gb = d_basis(I); gb
[z ..., y ..., x ..., 282687803443]
Now for each prime `p` dividing this integer 282687803443, the Groebner
basis of I modulo `p` will be non-trivial and will thus give a solution
of the original system modulo `p`.::
sage: factor(282687803443)
101 * 103 * 27173681
sage: I.change_ring( P.change_ring( GF(101) ) ).groebner_basis()
[z - 33, y + 48, x + 19]
sage: I.change_ring( P.change_ring( GF(103) ) ).groebner_basis()
[z - 18, y + 8, x + 39]
sage: I.change_ring( P.change_ring( GF(27173681) ) ).groebner_basis()
[z + 10380032, y + 3186055, x - 536027]
Of course, modulo any other prime the Groebner basis is trivial so
there are no other solutions. For example::
sage: I.change_ring( P.change_ring( GF(3) ) ).groebner_basis()
[1]
AUTHOR:
- Martin Albrecht (2008-08): initial version
"""
from sage.rings.integer_ring import ZZ
from sage.arith.functions import lcm
from sage.arith.misc import XGCD as xgcd, GCD as gcd
from sage.rings.polynomial.toy_buchberger import inter_reduction
from sage.structure.sequence import Sequence
def spol(g1, g2):
"""
Return the S-Polynomial of ``g_1`` and ``g_2``.
Let `a_i t_i` be `LT(g_i)`, `b_i = a/a_i` with `a = LCM(a_i,a_j)`,
and `s_i = t/t_i` with `t = LCM(t_i,t_j)`. Then the S-Polynomial
is defined as: `b_1s_1g_1 - b_2s_2g_2`.
INPUT:
- ``g1`` -- polynomial
- ``g2`` -- polynomial
EXAMPLES::
sage: from sage.rings.polynomial.toy_d_basis import spol
sage: P.<x, y, z> = PolynomialRing(IntegerRing(), 3, order='lex')
sage: f = x^2 - 1
sage: g = 2*x*y - z
sage: spol(f,g)
x*z - 2*y
"""
a1, a2 = g1.lc(), g2.lc()
a = a1.lcm(a2)
b1, b2 = a // a1, a // a2
t1, t2 = g1.lm(), g2.lm()
t = t1.parent().monomial_lcm(t1, t2)
s1, s2 = t // t1, t // t2
return b1 * s1 * g1 - b2 * s2 * g2
def gpol(g1, g2):
"""
Return the G-Polynomial of ``g_1`` and ``g_2``.
Let `a_i t_i` be `LT(g_i)`, `a = a_i*c_i + a_j*c_j` with `a =
GCD(a_i,a_j)`, and `s_i = t/t_i` with `t = LCM(t_i,t_j)`. Then the
G-Polynomial is defined as: `c_1s_1g_1 - c_2s_2g_2`.
INPUT:
- ``g1`` -- polynomial
- ``g2`` -- polynomial
EXAMPLES::
sage: from sage.rings.polynomial.toy_d_basis import gpol
sage: P.<x, y, z> = PolynomialRing(IntegerRing(), 3, order='lex')
sage: f = x^2 - 1
sage: g = 2*x*y - z
sage: gpol(f,g)
x^2*y - y
"""
a1, a2 = g1.lc(), g2.lc()
a, c1, c2 = xgcd(a1, a2)
t1, t2 = g1.lm(), g2.lm()
t = t1.parent().monomial_lcm(t1, t2)
s1, s2 = t // t1, t // t2
return c1 * s1 * g1 + c2 * s2 * g2
def LM(f):
return f.lm()
def LC(f):
return f.lc()
def d_basis(F, strat=True):
r"""
Return the `d`-basis for the Ideal ``F`` as defined in [BW1993]_.
INPUT:
- ``F`` -- an ideal
- ``strat`` -- use update strategy (default: ``True``)
EXAMPLES::
sage: from sage.rings.polynomial.toy_d_basis import d_basis
sage: A.<x,y> = PolynomialRing(ZZ, 2)
sage: f = -y^2 - y + x^3 + 7*x + 1
sage: fx = f.derivative(x)
sage: fy = f.derivative(y)
sage: I = A.ideal([f,fx,fy])
sage: gb = d_basis(I); gb
[x - 2020, y - 11313, 22627]
"""
R = F.ring()
G = set(inter_reduction(F.gens()))
B = set((f1, f2) for f1 in G for f2 in G if f1 != f2)
D = set()
C = set(B)
LCM = R.monomial_lcm
divides = R.monomial_divides
def divides_ZZ(x, y):
return ZZ(x).divides(ZZ(y))
while B:
while C:
f1, f2 = select(C)
C.remove((f1, f2))
lcm_lmf1_lmf2 = LCM(LM(f1), LM(f2))
if not any(divides(LM(g), lcm_lmf1_lmf2) and
divides_ZZ(LC(g), LC(f1)) and
divides_ZZ(LC(g), LC(f2))
for g in G):
h = gpol(f1, f2)
h0 = h.reduce(G)
if h0.lc() < 0:
h0 *= -1
if not strat:
D = D.union([(g, h0) for g in G])
G.add(h0)
else:
G, D = update(G, D, h0)
G = inter_reduction(G)
f1, f2 = select(B)
B.remove((f1, f2))
h = spol(f1, f2)
h0 = h.reduce(G)
if h0 != 0:
if h0.lc() < 0:
h0 *= -1
if not strat:
D = D.union([(g, h0) for g in G])
G.add(h0)
else:
G, D = update(G, D, h0)
B = B.union(D)
C = D
D = set()
return Sequence(sorted(inter_reduction(G), reverse=True))
def select(P):
"""
The normal selection strategy.
INPUT:
- ``P`` -- a list of critical pairs
OUTPUT:
an element of P
EXAMPLES::
sage: from sage.rings.polynomial.toy_d_basis import select
sage: A.<x,y> = PolynomialRing(ZZ, 2)
sage: f = -y^2 - y + x^3 + 7*x + 1
sage: fx = f.derivative(x)
sage: fy = f.derivative(y)
sage: G = [f, fx, fy]
sage: B = set((f1, f2) for f1 in G for f2 in G if f1 != f2)
sage: select(B)
(-2*y - 1, 3*x^2 + 7)
"""
min_d = 2**20
min_pair = 0, 0
for fi, fj in sorted(P):
d = fi.parent().monomial_lcm(fi.lm(), fj.lm()).total_degree()
if d < min_d:
min_d = d
min_pair = fi, fj
return min_pair
def update(G, B, h):
"""
Update ``G`` using the list of critical pairs ``B`` and the
polynomial ``h`` as presented in [BW1993]_, page 230. For this,
Buchberger's first and second criterion are tested.
This function uses the Gebauer-Moeller Installation.
INPUT:
- ``G`` -- an intermediate Groebner basis
- ``B`` -- a list of critical pairs
- ``h`` -- a polynomial
OUTPUT:
``G,B`` where ``G`` and ``B`` are updated
EXAMPLES::
sage: from sage.rings.polynomial.toy_d_basis import update
sage: A.<x,y> = PolynomialRing(ZZ, 2)
sage: G = set([3*x^2 + 7, 2*y + 1, x^3 - y^2 + 7*x - y + 1])
sage: B = set()
sage: h = x^2*y - x^2 + y - 3
sage: update(G,B,h)
({2*y + 1, 3*x^2 + 7, x^2*y - x^2 + y - 3, x^3 - y^2 + 7*x - y + 1},
{(x^2*y - x^2 + y - 3, 2*y + 1),
(x^2*y - x^2 + y - 3, 3*x^2 + 7),
(x^2*y - x^2 + y - 3, x^3 - y^2 + 7*x - y + 1)})
"""
R = h.parent()
LCM = R.monomial_lcm
def lt_divides(x, y):
return R.monomial_divides(LM(h), LM(g)) and LC(h).divides(LC(g))
def lt_pairwise_prime(x, y):
return (R.monomial_pairwise_prime(LM(x), LM(y))
and gcd(LC(x), LC(y)) == 1)
def lcm_divides(f, g1, h):
return (R.monomial_divides(LCM(LM(h), LM(f[1])), LCM(LM(h), LM(g1)))
and lcm(LC(h), LC(f[1])).divides(lcm(LC(h), LC(g1))))
C = set((h, g) for g in G)
D = set()
while C:
(h, g1) = C.pop()
if (lt_pairwise_prime(h, g1) or
(not any(lcm_divides(f, g1, h) for f in C) and
not any(lcm_divides(f, g1, h) for f in D))):
D.add((h, g1))
E = set()
while D:
(h, g) = D.pop()
if not lt_pairwise_prime(h, g):
E.add((h, g))
B_new = set()
while B:
g1, g2 = B.pop()
lcm_12 = lcm(LC(g1), LC(g2)) * LCM(LM(g1), LM(g2))
if (not lt_divides(lcm_12, h) or
lcm(LC(g1), LC(h)) * R.monomial_lcm(LM(g1), LM(h)) == lcm_12 or
lcm(LC(h), LC(g2)) * R.monomial_lcm(LM(h), LM(g2)) == lcm_12):
B_new.add((g1, g2))
B_new = B_new.union(E)
G_new = set()
while G:
g = G.pop()
if not lt_divides(g, h):
G_new.add(g)
G_new.add(h)
return G_new, B_new | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/toy_d_basis.py | 0.925496 | 0.825555 | toy_d_basis.py | pypi |
r"""
Polynomial Sequences
We call a finite list of polynomials a ``Polynomial Sequence``.
Polynomial sequences in Sage can optionally be viewed as consisting of
various parts or sub-sequences. These kind of polynomial sequences
which naturally split into parts arise naturally for example in
algebraic cryptanalysis of symmetric cryptographic primitives. The
most prominent examples of these systems are: the small scale variants
of the AES [CMR2005]_ (cf. :func:`sage.crypto.mq.sr.SR`) and Flurry/Curry [BPW2006]_. By
default, a polynomial sequence has exactly one part.
AUTHORS:
- Martin Albrecht (2007ff): initial version
- Martin Albrecht (2009): refactoring, clean-up, new functions
- Martin Albrecht (2011): refactoring, moved to sage.rings.polynomial
- Alex Raichev (2011-06): added algebraic_dependence()
- Charles Bouillaguet (2013-1): added solve()
EXAMPLES:
As an example consider a small scale variant of the AES::
sage: sr = mq.SR(2,1,2,4,gf2=True,polybori=True)
sage: sr
SR(2,1,2,4)
We can construct a polynomial sequence for a random plaintext-ciphertext
pair and study it::
sage: set_random_seed(1)
sage: while True: # workaround (see :trac:`31891`)
....: try:
....: F, s = sr.polynomial_system()
....: break
....: except ZeroDivisionError:
....: pass
sage: F
Polynomial Sequence with 112 Polynomials in 64 Variables
sage: r2 = F.part(2); r2
(w200 + k100 + x100 + x102 + x103,
w201 + k101 + x100 + x101 + x103 + 1,
w202 + k102 + x100 + x101 + x102 + 1,
w203 + k103 + x101 + x102 + x103,
w210 + k110 + x110 + x112 + x113,
w211 + k111 + x110 + x111 + x113 + 1,
w212 + k112 + x110 + x111 + x112 + 1,
w213 + k113 + x111 + x112 + x113,
x100*w100 + x100*w103 + x101*w102 + x102*w101 + x103*w100,
x100*w100 + x100*w101 + x101*w100 + x101*w103 + x102*w102 + x103*w101,
x100*w101 + x100*w102 + x101*w100 + x101*w101 + x102*w100 + x102*w103 + x103*w102,
x100*w100 + x100*w102 + x100*w103 + x101*w100 + x101*w101 + x102*w102 + x103*w100 + x100,
x100*w101 + x100*w103 + x101*w101 + x101*w102 + x102*w100 + x102*w103 + x103*w101 + x101,
x100*w100 + x100*w102 + x101*w100 + x101*w102 + x101*w103 + x102*w100 + x102*w101 + x103*w102 + x102,
x100*w101 + x100*w102 + x101*w100 + x101*w103 + x102*w101 + x103*w103 + x103,
x100*w100 + x100*w101 + x100*w103 + x101*w101 + x102*w100 + x102*w102 + x103*w100 + w100,
x100*w102 + x101*w100 + x101*w101 + x101*w103 + x102*w101 + x103*w100 + x103*w102 + w101,
x100*w100 + x100*w101 + x100*w102 + x101*w102 + x102*w100 + x102*w101 + x102*w103 + x103*w101 + w102,
x100*w101 + x101*w100 + x101*w102 + x102*w100 + x103*w101 + x103*w103 + w103,
x100*w102 + x101*w101 + x102*w100 + x103*w103 + 1,
x110*w110 + x110*w113 + x111*w112 + x112*w111 + x113*w110,
x110*w110 + x110*w111 + x111*w110 + x111*w113 + x112*w112 + x113*w111,
x110*w111 + x110*w112 + x111*w110 + x111*w111 + x112*w110 + x112*w113 + x113*w112,
x110*w110 + x110*w112 + x110*w113 + x111*w110 + x111*w111 + x112*w112 + x113*w110 + x110,
x110*w111 + x110*w113 + x111*w111 + x111*w112 + x112*w110 + x112*w113 + x113*w111 + x111,
x110*w110 + x110*w112 + x111*w110 + x111*w112 + x111*w113 + x112*w110 + x112*w111 + x113*w112 + x112,
x110*w111 + x110*w112 + x111*w110 + x111*w113 + x112*w111 + x113*w113 + x113,
x110*w110 + x110*w111 + x110*w113 + x111*w111 + x112*w110 + x112*w112 + x113*w110 + w110,
x110*w112 + x111*w110 + x111*w111 + x111*w113 + x112*w111 + x113*w110 + x113*w112 + w111,
x110*w110 + x110*w111 + x110*w112 + x111*w112 + x112*w110 + x112*w111 + x112*w113 + x113*w111 + w112,
x110*w111 + x111*w110 + x111*w112 + x112*w110 + x113*w111 + x113*w113 + w113,
x110*w112 + x111*w111 + x112*w110 + x113*w113 + 1)
We separate the system in independent subsystems::
sage: C = Sequence(r2).connected_components(); C
[[w213 + k113 + x111 + x112 + x113,
w212 + k112 + x110 + x111 + x112 + 1,
w211 + k111 + x110 + x111 + x113 + 1,
w210 + k110 + x110 + x112 + x113,
x110*w112 + x111*w111 + x112*w110 + x113*w113 + 1,
x110*w112 + x111*w110 + x111*w111 + x111*w113 + x112*w111 + x113*w110 + x113*w112 + w111,
x110*w111 + x111*w110 + x111*w112 + x112*w110 + x113*w111 + x113*w113 + w113,
x110*w111 + x110*w113 + x111*w111 + x111*w112 + x112*w110 + x112*w113 + x113*w111 + x111,
x110*w111 + x110*w112 + x111*w110 + x111*w113 + x112*w111 + x113*w113 + x113,
x110*w111 + x110*w112 + x111*w110 + x111*w111 + x112*w110 + x112*w113 + x113*w112,
x110*w110 + x110*w113 + x111*w112 + x112*w111 + x113*w110,
x110*w110 + x110*w112 + x111*w110 + x111*w112 + x111*w113 + x112*w110 + x112*w111 + x113*w112 + x112,
x110*w110 + x110*w112 + x110*w113 + x111*w110 + x111*w111 + x112*w112 + x113*w110 + x110,
x110*w110 + x110*w111 + x111*w110 + x111*w113 + x112*w112 + x113*w111,
x110*w110 + x110*w111 + x110*w113 + x111*w111 + x112*w110 + x112*w112 + x113*w110 + w110,
x110*w110 + x110*w111 + x110*w112 + x111*w112 + x112*w110 + x112*w111 + x112*w113 + x113*w111 + w112],
[w203 + k103 + x101 + x102 + x103,
w202 + k102 + x100 + x101 + x102 + 1,
w201 + k101 + x100 + x101 + x103 + 1,
w200 + k100 + x100 + x102 + x103,
x100*w102 + x101*w101 + x102*w100 + x103*w103 + 1,
x100*w102 + x101*w100 + x101*w101 + x101*w103 + x102*w101 + x103*w100 + x103*w102 + w101,
x100*w101 + x101*w100 + x101*w102 + x102*w100 + x103*w101 + x103*w103 + w103,
x100*w101 + x100*w103 + x101*w101 + x101*w102 + x102*w100 + x102*w103 + x103*w101 + x101,
x100*w101 + x100*w102 + x101*w100 + x101*w103 + x102*w101 + x103*w103 + x103, x100*w101 + x100*w102 + x101*w100 + x101*w101 + x102*w100 + x102*w103 + x103*w102,
x100*w100 + x100*w103 + x101*w102 + x102*w101 + x103*w100,
x100*w100 + x100*w102 + x101*w100 + x101*w102 + x101*w103 + x102*w100 + x102*w101 + x103*w102 + x102,
x100*w100 + x100*w102 + x100*w103 + x101*w100 + x101*w101 + x102*w102 + x103*w100 + x100,
x100*w100 + x100*w101 + x101*w100 + x101*w103 + x102*w102 + x103*w101,
x100*w100 + x100*w101 + x100*w103 + x101*w101 + x102*w100 + x102*w102 + x103*w100 + w100,
x100*w100 + x100*w101 + x100*w102 + x101*w102 + x102*w100 + x102*w101 + x102*w103 + x103*w101 + w102]]
sage: C[0].groebner_basis()
Polynomial Sequence with 30 Polynomials in 16 Variables
and compute the coefficient matrix::
sage: A,v = Sequence(r2).coefficient_matrix()
sage: A.rank()
32
Using these building blocks we can implement a simple XL algorithm
easily::
sage: sr = mq.SR(1,1,1,4, gf2=True, polybori=True, order='lex')
sage: while True: # workaround (see :trac:`31891`)
....: try:
....: F, s = sr.polynomial_system()
....: break
....: except ZeroDivisionError:
....: pass
sage: monomials = [a*b for a in F.variables() for b in F.variables() if a<b]
sage: len(monomials)
190
sage: F2 = Sequence(map(mul, cartesian_product_iterator((monomials, F))))
sage: A,v = F2.coefficient_matrix(sparse=False)
sage: A.echelonize()
sage: A
6840 x 4474 dense matrix over Finite Field of size 2 (use the '.str()' method to see the entries)
sage: A.rank()
4056
sage: A[4055]*v
(k001*k003)
TESTS::
sage: P.<x,y> = PolynomialRing(QQ)
sage: I = [[x^2 + y^2], [x^2 - y^2]]
sage: F = Sequence(I, P)
sage: loads(dumps(F)) == F
True
.. NOTE::
In many other computer algebra systems (cf. Singular) this class
would be called ``Ideal`` but an ideal is a very distinct object
from its generators and thus this is not an ideal in Sage.
Classes
-------
"""
from sage.misc.cachefunc import cached_method
from sage.misc.converting_dict import KeyConvertingDict
from sage.structure.sequence import Sequence_generic
from sage.rings.infinity import Infinity
from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF
from sage.rings.finite_rings.finite_field_base import FiniteField
from sage.rings.polynomial.multi_polynomial_ring import is_MPolynomialRing
from sage.rings.quotient_ring import is_QuotientRing
from sage.rings.polynomial.multi_polynomial_ideal import MPolynomialIdeal
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.interfaces.singular import singular_gb_standard_options
from sage.libs.singular.standard_options import libsingular_gb_standard_options
from sage.interfaces.singular import singular
def is_PolynomialSequence(F):
"""
Return ``True`` if ``F`` is a ``PolynomialSequence``.
INPUT:
- ``F`` - anything
EXAMPLES::
sage: P.<x,y> = PolynomialRing(QQ)
sage: I = [[x^2 + y^2], [x^2 - y^2]]
sage: F = Sequence(I, P); F
[x^2 + y^2, x^2 - y^2]
sage: from sage.rings.polynomial.multi_polynomial_sequence import is_PolynomialSequence
sage: is_PolynomialSequence(F)
True
"""
return isinstance(F,PolynomialSequence_generic)
def PolynomialSequence(arg1, arg2=None, immutable=False, cr=False, cr_str=None):
"""
Construct a new polynomial sequence object.
INPUT:
- ``arg1`` - a multivariate polynomial ring, an ideal or a matrix
- ``arg2`` - an iterable object of parts or polynomials
(default:``None``)
- ``immutable`` - if ``True`` the sequence is immutable (default: ``False``)
- ``cr`` - print a line break after each element (default: ``False``)
- ``cr_str`` - print a line break after each element if 'str' is
called (default: ``None``)
EXAMPLES::
sage: P.<a,b,c,d> = PolynomialRing(GF(127),4)
sage: I = sage.rings.ideal.Katsura(P)
If a list of tuples is provided, those form the parts::
sage: F = Sequence([I.gens(),I.gens()], I.ring()); F # indirect doctest
[a + 2*b + 2*c + 2*d - 1,
a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a,
2*a*b + 2*b*c + 2*c*d - b,
b^2 + 2*a*c + 2*b*d - c,
a + 2*b + 2*c + 2*d - 1,
a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a,
2*a*b + 2*b*c + 2*c*d - b,
b^2 + 2*a*c + 2*b*d - c]
sage: F.nparts()
2
If an ideal is provided, the generators are used::
sage: Sequence(I)
[a + 2*b + 2*c + 2*d - 1,
a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a,
2*a*b + 2*b*c + 2*c*d - b,
b^2 + 2*a*c + 2*b*d - c]
If a list of polynomials is provided, the system has only one part::
sage: F = Sequence(I.gens(), I.ring()); F
[a + 2*b + 2*c + 2*d - 1,
a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a,
2*a*b + 2*b*c + 2*c*d - b,
b^2 + 2*a*c + 2*b*d - c]
sage: F.nparts()
1
We test that the ring is inferred correctly::
sage: P.<x,y,z> = GF(2)[]
sage: from sage.rings.polynomial.multi_polynomial_sequence import PolynomialSequence
sage: PolynomialSequence([1,x,y]).ring()
Multivariate Polynomial Ring in x, y, z over Finite Field of size 2
sage: PolynomialSequence([[1,x,y], [0]]).ring()
Multivariate Polynomial Ring in x, y, z over Finite Field of size 2
TESTS:
A PolynomialSequence can exist with elements in an infinite field of
characteristic 2 (see :trac:`19452`)::
sage: from sage.rings.polynomial.multi_polynomial_sequence import PolynomialSequence
sage: F = GF(2)
sage: L.<t> = PowerSeriesRing(F,'t')
sage: R.<x,y> = PolynomialRing(L,'x,y')
sage: PolynomialSequence([0], R)
[0]
A PolynomialSequence can be created from an iterator (see :trac:`25989`)::
sage: R.<x,y,z> = QQ[]
sage: PolynomialSequence(iter(R.gens()))
[x, y, z]
sage: PolynomialSequence(iter(R.gens()), R)
[x, y, z]
sage: PolynomialSequence(iter([(x,y), (z,)]), R)
[x, y, z]
"""
from sage.structure.element import is_Matrix
from sage.rings.polynomial.pbori.pbori import BooleanMonomialMonoid
is_ring = lambda r: is_MPolynomialRing(r) or isinstance(r, BooleanMonomialMonoid) or (is_QuotientRing(r) and is_MPolynomialRing(r.cover_ring()))
if is_ring(arg1):
ring, gens = arg1, arg2
elif is_ring(arg2):
ring, gens = arg2, arg1
elif is_Matrix(arg1):
ring, gens = arg1.base_ring(), arg1.list()
elif isinstance(arg1, MPolynomialIdeal):
ring, gens = arg1.ring(), arg1.gens()
else:
gens = list(arg1)
if arg2:
ring = arg2
if not is_ring(ring):
raise TypeError("Ring '%s' not supported."%ring)
else:
try:
e = next(iter(gens))
except StopIteration:
raise ValueError("Cannot determine ring from provided information.")
import sage.structure.element as coerce
el = 0
for f in gens:
try:
el, _ = coerce.canonical_coercion(el, f)
except TypeError:
el = 0
for part in gens:
for f in part:
el, _ = coerce.canonical_coercion(el, f)
if is_ring(el.parent()):
ring = el.parent()
else:
raise TypeError("Cannot determine ring.")
try:
gens = iter(gens)
e = next(gens)
# fast path for known collection types
if isinstance(e, (tuple, list, Sequence_generic, PolynomialSequence_generic)):
nested = True
else:
nested = False
try:
e2 = ring(e)
except TypeError:
nested = True
from itertools import chain
if nested:
parts = tuple(tuple(ring(f) for f in part) for part in chain([e], gens))
else:
parts = tuple(chain([e2], map(ring, gens))),
except StopIteration:
parts = ((),)
K = ring.base_ring()
# make sure we use the polynomial ring as ring not the monoid
ring = (ring(1) + ring(1)).parent()
if not isinstance(K, FiniteField) or K.characteristic() != 2:
return PolynomialSequence_generic(parts, ring, immutable=immutable, cr=cr, cr_str=cr_str)
elif K.degree() == 1:
return PolynomialSequence_gf2(parts, ring, immutable=immutable, cr=cr, cr_str=cr_str)
elif K.degree() > 1:
return PolynomialSequence_gf2e(parts, ring, immutable=immutable, cr=cr, cr_str=cr_str)
class PolynomialSequence_generic(Sequence_generic):
def __init__(self, parts, ring, immutable=False, cr=False, cr_str=None):
"""
Construct a new system of multivariate polynomials.
INPUT:
- ``part`` - a list of lists with polynomials
- ``ring`` - a multivariate polynomial ring
- ``immutable`` - if ``True`` the sequence is immutable (default: ``False``)
- ``cr`` - print a line break after each element (default: ``False``)
- ``cr_str`` - print a line break after each element if 'str'
is called (default: ``None``)
EXAMPLES::
sage: P.<a,b,c,d> = PolynomialRing(GF(127),4)
sage: I = sage.rings.ideal.Katsura(P)
sage: Sequence([I.gens()], I.ring()) # indirect doctest
[a + 2*b + 2*c + 2*d - 1, a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a, 2*a*b + 2*b*c + 2*c*d - b, b^2 + 2*a*c + 2*b*d - c]
If an ideal is provided, the generators are used.::
sage: Sequence(I)
[a + 2*b + 2*c + 2*d - 1, a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a, 2*a*b + 2*b*c + 2*c*d - b, b^2 + 2*a*c + 2*b*d - c]
If a list of polynomials is provided, the system has only one
part.::
sage: Sequence(I.gens(), I.ring())
[a + 2*b + 2*c + 2*d - 1, a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a, 2*a*b + 2*b*c + 2*c*d - b, b^2 + 2*a*c + 2*b*d - c]
"""
Sequence_generic.__init__(self, sum(parts,tuple()), ring, check=False, immutable=immutable,
cr=cr, cr_str=cr_str, use_sage_types=True)
self._ring = ring
self._parts = parts
def __copy__(self):
"""
Return a copy of this system.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system()
sage: copy(F) # indirect doctest
Polynomial Sequence with 40 Polynomials in 20 Variables
sage: type(F) == type(copy(F))
True
"""
return self.__class__(self._parts, self._ring, immutable=self.is_immutable())
def ring(self):
"""
Return the polynomial ring all elements live in.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True,gf2=True,order='block')
sage: F,s = sr.polynomial_system()
sage: print(F.ring().repr_long())
Polynomial Ring
Base Ring : Finite Field of size 2
Size : 20 Variables
Block 0 : Ordering : deglex
Names : k100, k101, k102, k103, x100, x101, x102, x103, w100, w101, w102, w103, s000, s001, s002, s003
Block 1 : Ordering : deglex
Names : k000, k001, k002, k003
"""
return self._ring
universe = ring
def nparts(self):
"""
Return number of parts of this system.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system()
sage: F.nparts()
4
"""
return len(self._parts)
def parts(self):
"""
Return a tuple of parts of this system.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system()
sage: l = F.parts()
sage: len(l)
4
"""
return tuple(self._parts)
def part(self, i):
"""
Return ``i``-th part of this system.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system()
sage: R0 = F.part(1)
sage: R0
(k000^2 + k001, k001^2 + k002, k002^2 + k003, k003^2 + k000)
"""
return self._parts[i]
def ideal(self):
"""
Return ideal spanned by the elements of this system.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system()
sage: P = F.ring()
sage: I = F.ideal()
sage: J = I.elimination_ideal(P.gens()[4:-4])
sage: J <= I
True
sage: set(J.gens().variables()).issubset(P.gens()[:4] + P.gens()[-4:])
True
"""
return self._ring.ideal(tuple(self))
def groebner_basis(self, *args, **kwargs):
"""
Compute and return a Groebner basis for the ideal spanned by
the polynomials in this system.
INPUT:
- ``args`` - list of arguments passed to
``MPolynomialIdeal.groebner_basis`` call
- ``kwargs`` - dictionary of arguments passed to
``MPolynomialIdeal.groebner_basis`` call
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system()
sage: gb = F.groebner_basis()
sage: Ideal(gb).basis_is_groebner()
True
TESTS:
Check that this method also works for boolean polynomials
(:trac:`10680`)::
sage: B.<a,b,c,d> = BooleanPolynomialRing()
sage: F0 = Sequence(map(lambda f: f.lm(),[a,b,c,d]))
sage: F0.groebner_basis()
[a, b, c, d]
sage: F1 = Sequence([a,b,c*d,d^2])
sage: F1.groebner_basis()
[a, b, d]
"""
return self.ideal().groebner_basis(*args, **kwargs)
def monomials(self):
"""
Return an unordered tuple of monomials in this polynomial system.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system()
sage: len(F.monomials())
49
"""
M = set()
for f in self:
for m in f.monomials():
M.add(m)
return tuple(M)
def nmonomials(self):
"""
Return the number of monomials present in this system.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system()
sage: F.nmonomials()
49
"""
return len(self.monomials())
def variables(self):
"""
Return all variables present in this system. This tuple may or
may not be equal to the generators of the ring of this system.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system()
sage: F.variables()[:10]
(k003, k002, k001, k000, s003, s002, s001, s000, w103, w102)
"""
V = set()
for f in self:
for v in f.variables():
V.add(v)
return tuple(sorted(V))
def nvariables(self):
"""
Return number of variables present in this system.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system()
sage: F.nvariables()
20
"""
return len(self.variables())
def algebraic_dependence(self):
r"""
Returns the ideal of annihilating polynomials for the
polynomials in ``self``, if those polynomials are algebraically
dependent.
Otherwise, returns the zero ideal.
OUTPUT:
If the polynomials `f_1,\ldots,f_r` in ``self`` are algebraically
dependent, then the output is the ideal
`\{F \in K[T_1,\ldots,T_r] : F(f_1,\ldots,f_r) = 0\}` of
annihilating polynomials of `f_1,\ldots,f_r`.
Here `K` is the coefficient ring of polynomial ring of `f_1,\ldots,f_r`
and `T_1,\ldots,T_r` are new indeterminates.
If `f_1,\ldots,f_r` are algebraically independent, then the output
is the zero ideal in `K[T_1,\ldots,T_r]`.
EXAMPLES::
sage: R.<x,y> = PolynomialRing(QQ)
sage: S = Sequence([x, x*y])
sage: I = S.algebraic_dependence(); I
Ideal (0) of Multivariate Polynomial Ring in T0, T1 over Rational Field
::
sage: R.<x,y> = PolynomialRing(QQ)
sage: S = Sequence([x, (x^2 + y^2 - 1)^2, x*y - 2])
sage: I = S.algebraic_dependence(); I
Ideal (16 + 32*T2 - 8*T0^2 + 24*T2^2 - 8*T0^2*T2 + 8*T2^3 + 9*T0^4 - 2*T0^2*T2^2 + T2^4 - T0^4*T1 + 8*T0^4*T2 - 2*T0^6 + 2*T0^4*T2^2 + T0^8) of Multivariate Polynomial Ring in T0, T1, T2 over Rational Field
sage: [F(S) for F in I.gens()]
[0]
::
sage: R.<x,y> = PolynomialRing(GF(7))
sage: S = Sequence([x, (x^2 + y^2 - 1)^2, x*y - 2])
sage: I = S.algebraic_dependence(); I
Ideal (2 - 3*T2 - T0^2 + 3*T2^2 - T0^2*T2 + T2^3 + 2*T0^4 - 2*T0^2*T2^2 + T2^4 - T0^4*T1 + T0^4*T2 - 2*T0^6 + 2*T0^4*T2^2 + T0^8) of Multivariate Polynomial Ring in T0, T1, T2 over Finite Field of size 7
sage: [F(S) for F in I.gens()]
[0]
.. NOTE::
This function's code also works for sequences of polynomials from a
univariate polynomial ring, but i don't know where in the Sage codebase
to put it to use it to that effect.
AUTHORS:
- Alex Raichev (2011-06-22)
"""
R = self.ring()
K = R.base_ring()
Xs = list(R.gens())
r = len(self)
d = len(Xs)
# Expand R by r new variables.
T = 'T'
while T in [str(x) for x in Xs]:
T = T+'T'
Ts = [T + str(j) for j in range(r)]
RR = PolynomialRing(K,d+r,tuple(Xs+Ts))
Vs = list(RR.gens())
Xs = Vs[0 :d]
Ts = Vs[d:]
J = RR.ideal([ Ts[j] - RR(self[j]) for j in range(r)])
JJ = J.elimination_ideal(Xs)
# By the elimination theorem, JJ is the kernel of the ring morphism
# `phi:K[\bar T] \to K[\bar X]` that fixes `K` and sends each
# `T_i` to `f_i`.
# So JJ is the ideal of annihilating polynomials of `f_1,\ldots,f_r`,
# which is the zero ideal in case `f_1,\ldots,f_r` are algebraically
# independent.
# Coerce JJ into `K[T_1,\ldots,T_r]`.
# Choosing the negdeglex order simply because i find it useful in my work.
RRR = PolynomialRing(K,r,tuple(Ts),order='negdeglex')
return RRR.ideal(JJ.gens())
def coefficient_matrix(self, sparse=True):
"""
Return tuple ``(A,v)`` where ``A`` is the coefficient matrix
of this system and ``v`` the matching monomial vector.
Thus value of ``A[i,j]`` corresponds the coefficient of the
monomial ``v[j]`` in the ``i``-th polynomial in this system.
Monomials are order w.r.t. the term ordering of
``self.ring()`` in reverse order, i.e. such that the smallest
entry comes last.
INPUT:
- ``sparse`` - construct a sparse matrix (default: ``True``)
EXAMPLES::
sage: P.<a,b,c,d> = PolynomialRing(GF(127),4)
sage: I = sage.rings.ideal.Katsura(P)
sage: I.gens()
[a + 2*b + 2*c + 2*d - 1,
a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a,
2*a*b + 2*b*c + 2*c*d - b,
b^2 + 2*a*c + 2*b*d - c]
sage: F = Sequence(I)
sage: A,v = F.coefficient_matrix()
sage: A
[ 0 0 0 0 0 0 0 0 0 1 2 2 2 126]
[ 1 0 2 0 0 2 0 0 2 126 0 0 0 0]
[ 0 2 0 0 2 0 0 2 0 0 126 0 0 0]
[ 0 0 1 2 0 0 2 0 0 0 0 126 0 0]
sage: v
[a^2]
[a*b]
[b^2]
[a*c]
[b*c]
[c^2]
[b*d]
[c*d]
[d^2]
[ a]
[ b]
[ c]
[ d]
[ 1]
sage: A*v
[ a + 2*b + 2*c + 2*d - 1]
[a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a]
[ 2*a*b + 2*b*c + 2*c*d - b]
[ b^2 + 2*a*c + 2*b*d - c]
"""
R = self.ring()
m = sorted(self.monomials(),reverse=True)
nm = len(m)
f = tuple(self)
nf = len(f)
#construct dictionary for fast lookups
v = dict( zip( m , range(len(m)) ) )
from sage.matrix.constructor import Matrix
A = Matrix( R.base_ring(), nf, nm, sparse=sparse )
for x in range( nf ):
poly = f[x]
for y in poly.monomials():
A[ x , v[y] ] = poly.monomial_coefficient(y)
return A, Matrix(R,nm,1,m)
def subs(self, *args, **kwargs):
"""
Substitute variables for every polynomial in this system and
return a new system. See ``MPolynomial.subs`` for calling
convention.
INPUT:
- ``args`` - arguments to be passed to ``MPolynomial.subs``
- ``kwargs`` - keyword arguments to be passed to ``MPolynomial.subs``
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True)
sage: F,s = sr.polynomial_system(); F
Polynomial Sequence with 40 Polynomials in 20 Variables
sage: F = F.subs(s); F
Polynomial Sequence with 40 Polynomials in 16 Variables
"""
return PolynomialSequence(self._ring, [tuple([f.subs(*args,**kwargs) for f in r]) for r in self._parts])
def _singular_(self):
"""
Return Singular ideal representation of this system.
EXAMPLES::
sage: P.<a,b,c,d> = PolynomialRing(GF(127))
sage: I = sage.rings.ideal.Katsura(P)
sage: F = Sequence(I); F
[a + 2*b + 2*c + 2*d - 1,
a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a,
2*a*b + 2*b*c + 2*c*d - b,
b^2 + 2*a*c + 2*b*d - c]
sage: F._singular_()
a+2*b+2*c+2*d-1,
a^2+2*b^2+2*c^2+2*d^2-a,
2*a*b+2*b*c+2*c*d-b,
b^2+2*a*c+2*b*d-c
"""
return singular.ideal(list(self))
def _magma_init_(self, magma):
"""
Return Magma ideal representation of the ideal spanned by this
system.
EXAMPLES::
sage: sr = mq.SR(allow_zero_inversions=True,gf2=True)
sage: F,s = sr.polynomial_system()
sage: F.set_immutable()
sage: magma(F) # indirect doctest; optional - magma
Ideal of Boolean polynomial ring of rank 20 over GF(2)
Order: Graded Lexicographical (bit vector word)
Variables: k100, k101, k102, k103, x100, x101, x102, x103, w100, w101, w102, w103, s000, s001, s002, s003, k000, k001, k002, k003
Basis:
[
...
]
"""
P = magma(self.ring()).name()
v = [x._magma_init_(magma) for x in list(self)]
return 'ideal<%s|%s>'%(P, ','.join(v))
def _repr_(self):
"""
Return a string representation of this system.
EXAMPLES::
sage: P.<a,b,c,d> = PolynomialRing(GF(127))
sage: I = sage.rings.ideal.Katsura(P)
sage: F = Sequence(I); F # indirect doctest
[a + 2*b + 2*c + 2*d - 1,
a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a,
2*a*b + 2*b*c + 2*c*d - b,
b^2 + 2*a*c + 2*b*d - c]
If the system contains 20 or more polynomials, a short summary
is printed::
sage: sr = mq.SR(allow_zero_inversions=True,gf2=True)
sage: F,s = sr.polynomial_system(); F
Polynomial Sequence with 36 Polynomials in 20 Variables
"""
if len(self) < 20:
return Sequence_generic._repr_(self)
else:
return "Polynomial Sequence with %d Polynomials in %d Variables"%(len(self),self.nvariables())
def __add__(self, right):
"""
Add polynomial systems together, i.e. create a union of their
polynomials.
EXAMPLES::
sage: P.<a,b,c,d> = PolynomialRing(GF(127))
sage: I = sage.rings.ideal.Katsura(P)
sage: F = Sequence(I)
sage: F + [a^127 + a]
[a + 2*b + 2*c + 2*d - 1,
a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a,
2*a*b + 2*b*c + 2*c*d - b,
b^2 + 2*a*c + 2*b*d - c,
a^127 + a]
sage: F + P.ideal([a^127 + a])
[a + 2*b + 2*c + 2*d - 1,
a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a,
2*a*b + 2*b*c + 2*c*d - b,
b^2 + 2*a*c + 2*b*d - c,
a^127 + a]
sage: F + Sequence([a^127 + a], P)
[a + 2*b + 2*c + 2*d - 1,
a^2 + 2*b^2 + 2*c^2 + 2*d^2 - a,
2*a*b + 2*b*c + 2*c*d - b,
b^2 + 2*a*c + 2*b*d - c,
a^127 + a]
"""
if is_PolynomialSequence(right) and right.ring() == self.ring():
return PolynomialSequence(self.ring(), self.parts() + right.parts())
elif isinstance(right,(tuple,list)) and all((x.parent() == self.ring() for x in right)):
return PolynomialSequence(self.ring(), self.parts() + (right,))
elif isinstance(right,MPolynomialIdeal) and (right.ring() is self.ring() or right.ring() == self.ring()):
return PolynomialSequence(self.ring(), self.parts() + (right.gens(),))
else:
raise TypeError("right must be a system over same ring as self.")
def connection_graph(self):
"""
Return the graph which has the variables of this system as
vertices and edges between two variables if they appear in the
same polynomial.
EXAMPLES::
sage: B.<x,y,z> = BooleanPolynomialRing()
sage: F = Sequence([x*y + y + 1, z + 1])
sage: F.connection_graph()
Graph on 3 vertices
"""
V = sorted(self.variables())
from sage.graphs.graph import Graph
g = Graph()
g.add_vertices(sorted(V))
for f in self:
v = f.variables()
a,tail = v[0],v[1:]
for b in tail:
g.add_edge((a,b))
return g
def connected_components(self):
"""
Split the polynomial system in systems which do not share any
variables.
EXAMPLES:
As an example consider one part of AES, which naturally
splits into four subsystems which are independent::
sage: sr = mq.SR(2,4,4,8,gf2=True,polybori=True)
sage: while True: # workaround (see :trac:`31891`)
....: try:
....: F, s = sr.polynomial_system()
....: break
....: except ZeroDivisionError:
....: pass
sage: Fz = Sequence(F.part(2))
sage: Fz.connected_components()
[Polynomial Sequence with 128 Polynomials in 128 Variables,
Polynomial Sequence with 128 Polynomials in 128 Variables,
Polynomial Sequence with 128 Polynomials in 128 Variables,
Polynomial Sequence with 128 Polynomials in 128 Variables]
"""
g = self.connection_graph()
C = sorted(g.connected_components())
P = [[] for _ in range(len(C))]
for f in self:
for i,c in enumerate(C):
if len(set(f.variables()).difference(c)) == 0:
P[i].append(f)
break
P = sorted([PolynomialSequence(sorted(p)) for p in P])
return P
def _groebner_strategy(self):
"""
Return the Singular Groebner Strategy object.
This object allows to compute normal forms efficiently, since
all conversion overhead is avoided.
EXAMPLES::
sage: P.<x,y,z> = PolynomialRing(GF(127))
sage: F = Sequence([x*y + z, y + z + 1])
sage: F._groebner_strategy()
Groebner Strategy for ideal generated by 2 elements over
Multivariate Polynomial Ring in x, y, z over Finite Field of size 127
"""
from sage.libs.singular.groebner_strategy import GroebnerStrategy
return GroebnerStrategy(self.ideal())
def maximal_degree(self):
"""
Return the maximal degree of any polynomial in this sequence.
EXAMPLES::
sage: P.<x,y,z> = PolynomialRing(GF(7))
sage: F = Sequence([x*y + x, x])
sage: F.maximal_degree()
2
sage: P.<x,y,z> = PolynomialRing(GF(7))
sage: F = Sequence([], universe=P)
sage: F.maximal_degree()
-1
"""
try:
return max(f.degree() for f in self)
except ValueError:
return -1 # empty sequence
def __reduce__(self):
"""
TESTS::
sage: P.<x,y,z> = PolynomialRing(GF(127))
sage: F = Sequence([x*y + z, y + z + 1])
sage: loads(dumps(F)) == F # indirect doctest
True
We check that :trac:`26354` is fixed::
sage: f = P.hom([y,z,x])
sage: hash(f) == hash(loads(dumps(f)))
True
"""
return PolynomialSequence, (self._ring, self._parts, self._is_immutable,
self._Sequence_generic__cr, self._Sequence_generic__cr_str)
@singular_gb_standard_options
@libsingular_gb_standard_options
def reduced(self):
r"""
If this sequence is `(f_1, ..., f_n)` then this method
returns `(g_1, ..., g_s)` such that:
- `(f_1,...,f_n) = (g_1,...,g_s)`
- `LT(g_i) != LT(g_j)` for all `i != j`
- `LT(g_i)` does not divide `m` for all monomials `m` of
`\{g_1,...,g_{i-1},g_{i+1},...,g_s\}`
- `LC(g_i) == 1` for all `i` if the coefficient ring is a field.
EXAMPLES::
sage: R.<x,y,z> = PolynomialRing(QQ)
sage: F = Sequence([z*x+y^3,z+y^3,z+x*y])
sage: F.reduced()
[y^3 + z, x*y + z, x*z - z]
Note that tail reduction for local orderings is not well-defined::
sage: R.<x,y,z> = PolynomialRing(QQ,order='negdegrevlex')
sage: F = Sequence([z*x+y^3,z+y^3,z+x*y])
sage: F.reduced()
[z + x*y, x*y - y^3, x^2*y - y^3]
A fixed error with nonstandard base fields::
sage: R.<t>=QQ['t']
sage: K.<x,y>=R.fraction_field()['x,y']
sage: I=t*x*K
sage: I.basis.reduced()
[x]
The interreduced basis of 0 is 0::
sage: P.<x,y,z> = GF(2)[]
sage: Sequence([P(0)]).reduced()
[0]
Leading coefficients are reduced to 1::
sage: P.<x,y> = QQ[]
sage: Sequence([2*x,y]).reduced()
[x, y]
sage: P.<x,y> = CC[]
sage: Sequence([2*x,y]).reduced()
[x, y]
ALGORITHM:
Uses Singular's interred command or
:func:`sage.rings.polynomial.toy_buchberger.inter_reduction`
if conversion to Singular fails.
TESTS:
Check that :trac:`26952` is fixed::
sage: Qp = pAdicField(2)
sage: R.<x,y,z> = PolynomialRing(Qp, implementation="generic")
sage: F = Sequence([z*x+y^3,z+y^3,3*z+x*y])
sage: F.reduced()
[y^3 + z, x*y + (1 + 2 + O(2^20))*z, x*z - z]
"""
from sage.rings.polynomial.multi_polynomial_ideal_libsingular import interred_libsingular
from sage.rings.polynomial.multi_polynomial_libsingular import MPolynomialRing_libsingular
R = self.ring()
if isinstance(R,MPolynomialRing_libsingular):
return PolynomialSequence(R, interred_libsingular(self), immutable=True)
else:
try:
s = self._singular_().parent()
o = s.option("get")
s.option("redTail")
ret = []
for f in self._singular_().interred():
f = R(f)
ret.append(f.lc()**(-1)*f) # lead coeffs are not reduced by interred
s.option("set",o)
except TypeError:
from sage.rings.polynomial.toy_buchberger import inter_reduction
ret = inter_reduction(self)
ret = sorted(ret, reverse=True)
ret = PolynomialSequence(R, ret, immutable=True)
return ret
@cached_method
@singular_gb_standard_options
def is_groebner(self, singular=singular):
r"""
Returns ``True`` if the generators of this ideal (``self.gens()``)
form a Groebner basis.
Let `I` be the set of generators of this ideal. The check is
performed by trying to lift `Syz(LM(I))` to `Syz(I)` as `I`
forms a Groebner basis if and only if for every element `S` in
`Syz(LM(I))`:
`S * G = \sum_{i=0}^{m} h_ig_i ---->_G 0.`
EXAMPLES::
sage: R.<a,b,c,d,e,f,g,h,i,j> = PolynomialRing(GF(127),10)
sage: I = sage.rings.ideal.Cyclic(R,4)
sage: I.basis.is_groebner()
False
sage: I2 = Ideal(I.groebner_basis())
sage: I2.basis.is_groebner()
True
"""
return self.ideal().basis_is_groebner()
class PolynomialSequence_gf2(PolynomialSequence_generic):
r"""
Polynomial Sequences over `\GF{2}`.
"""
def eliminate_linear_variables(self, maxlength=Infinity, skip=None, return_reductors=False, use_polybori=False):
"""
Return a new system where linear leading variables are
eliminated if the tail of the polynomial has length at most
``maxlength``.
INPUT:
- ``maxlength`` - an optional upper bound on the number of
monomials by which a variable is replaced. If
``maxlength==+Infinity`` then no condition is checked.
(default: +Infinity).
- ``skip`` - an optional callable to skip eliminations. It
must accept two parameters and return either ``True`` or
``False``. The two parameters are the leading term and the
tail of a polynomial (default: ``None``).
- ``return_reductors`` - if ``True`` the list of polynomials
with linear leading terms which were used for reduction is
also returned (default: ``False``).
- ```use_polybori`` - if ``True`` then ``polybori.ll.eliminate`` is
called. While this is typically faster what is implemented here, it
is less flexible (``skip`` is not supported) and may increase the
degree (default: ``False``)
OUTPUT:
When ``return_reductors==True``, then a pair of sequences of
boolean polynomials are returned, along with the promises that:
1. The union of the two sequences spans the
same boolean ideal as the argument of the method
2. The second sequence only contains linear polynomials, and
it forms a reduced groebner basis (they all have pairwise
distinct leading variables, and the leading variable of a
polynomial does not occur anywhere in other polynomials).
3. The leading variables of the second sequence do not occur
anywhere in the first sequence (these variables have been
eliminated).
When ``return_reductors==False``, only the first sequence is
returned.
EXAMPLES::
sage: B.<a,b,c,d> = BooleanPolynomialRing()
sage: F = Sequence([c + d + b + 1, a + c + d, a*b + c, b*c*d + c])
sage: F.eliminate_linear_variables() # everything vanishes
[]
sage: F.eliminate_linear_variables(maxlength=2)
[b + c + d + 1, b*c + b*d + c, b*c*d + c]
sage: F.eliminate_linear_variables(skip=lambda lm,tail: str(lm)=='a')
[a + c + d, a*c + a*d + a + c, c*d + c]
The list of reductors can be requested by setting 'return_reductors' to ``True``::
sage: B.<a,b,c,d> = BooleanPolynomialRing()
sage: F = Sequence([a + b + d, a + b + c])
sage: F,R = F.eliminate_linear_variables(return_reductors=True)
sage: F
[]
sage: R
[a + b + d, c + d]
If the input system is detected to be inconsistent then [1] is returned
and the list of reductors is empty::
sage: R.<x,y,z> = BooleanPolynomialRing()
sage: S = Sequence([x*y*z+x*y+z*y+x*z, x+y+z+1, x+y+z])
sage: S.eliminate_linear_variables()
[1]
sage: R.<x,y,z> = BooleanPolynomialRing()
sage: S = Sequence([x*y*z+x*y+z*y+x*z, x+y+z+1, x+y+z])
sage: S.eliminate_linear_variables(return_reductors=True)
([1], [])
TESTS:
The function should really dispose of linear equations (:trac:`13968`)::
sage: R.<x,y,z> = BooleanPolynomialRing()
sage: S = Sequence([x+y+z+1, y+z])
sage: S.eliminate_linear_variables(return_reductors=True)
([], [x + 1, y + z])
The function should take care of linear variables created by previous
substitution of linear variables ::
sage: R.<x,y,z> = BooleanPolynomialRing()
sage: S = Sequence([x*y*z+x*y+z*y+x*z, x+y+z+1, x+y])
sage: S.eliminate_linear_variables(return_reductors=True)
([], [x + y, z + 1])
We test a case which would increase the degree with ``polybori=True``::
sage: B.<a,b,c,d> = BooleanPolynomialRing()
sage: f = a*d + a + b*d + c*d + 1
sage: Sequence([f, a + b*c + c+d + 1]).eliminate_linear_variables()
[a*d + a + b*d + c*d + 1, a + b*c + c + d + 1]
sage: B.<a,b,c,d> = BooleanPolynomialRing()
sage: f = a*d + a + b*d + c*d + 1
sage: Sequence([f, a + b*c + c+d + 1]).eliminate_linear_variables(use_polybori=True)
[b*c*d + b*c + b*d + c + d]
.. NOTE::
This is called "massaging" in [BCJ2007]_.
"""
from sage.rings.polynomial.pbori.pbori import BooleanPolynomialRing,gauss_on_polys
from sage.rings.polynomial.pbori.ll import eliminate,ll_encode,ll_red_nf_redsb
R = self.ring()
if not isinstance(R, BooleanPolynomialRing):
raise NotImplementedError("Only BooleanPolynomialRing's are supported.")
F = self
reductors = []
if use_polybori and skip is None and maxlength == Infinity:
# faster solution based on polybori.ll.eliminate
while True:
(this_step_reductors, _, higher) = eliminate(F)
if this_step_reductors == []:
break
reductors.extend(this_step_reductors)
F = higher
else:
# slower, more flexible solution
if skip is None:
skip = lambda lm, tail: False
while True:
linear = []
higher = []
for f in F:
if f.degree() == 1 and len(f) <= maxlength + 1:
flm = f.lex_lead()
if skip(flm, f-flm):
higher.append(f)
continue
linear.append(f)
else:
higher.append(f)
if not linear:
break
linear = gauss_on_polys(linear)
if 1 in linear:
if return_reductors:
return PolynomialSequence(R, [R(1)]), PolynomialSequence(R, [])
else:
return PolynomialSequence(R, [R(1)])
rb = ll_encode(linear)
reductors.extend(linear)
F = []
for f in higher:
f = ll_red_nf_redsb(f, rb)
if f != 0:
F.append(f)
ret = PolynomialSequence(R, higher)
if return_reductors:
reduced_reductors = gauss_on_polys(reductors)
return ret, PolynomialSequence(R, reduced_reductors)
else:
return ret
def _groebner_strategy(self):
"""
Return the Singular Groebner Strategy object.
This object allows to compute normal forms efficiently, since
all conversion overhead is avoided.
EXAMPLES::
sage: P.<x,y,z> = PolynomialRing(GF(2))
sage: F = Sequence([x*y + z, y + z + 1])
sage: F._groebner_strategy()
Groebner Strategy for ideal generated by 2 elements over
Multivariate Polynomial Ring in x, y, z over Finite Field of size 2
sage: P.<x,y,z> = BooleanPolynomialRing()
sage: F = Sequence([x*y + z, y + z + 1])
sage: F._groebner_strategy()
<sage.rings.polynomial.pbori.pbori.GroebnerStrategy object at 0x...>
"""
from sage.rings.polynomial.pbori.pbori import BooleanPolynomialRing
R = self.ring()
if not isinstance(R, BooleanPolynomialRing):
from sage.libs.singular.groebner_strategy import GroebnerStrategy
return GroebnerStrategy(self.ideal())
else:
from sage.rings.polynomial.pbori.pbori import GroebnerStrategy
g = GroebnerStrategy(R)
for p in self:
g.add_as_you_wish(p)
g.reduction_strategy.opt_red_tail=True
return g
def solve(self, algorithm='polybori', n=1, eliminate_linear_variables=True, verbose=False, **kwds):
r"""
Find solutions of this boolean polynomial system.
This function provide a unified interface to several algorithms
dedicated to solving systems of boolean equations. Depending on
the particular nature of the system, some might be much faster
than some others.
INPUT:
* ``self`` - a sequence of boolean polynomials
* ``algorithm`` - the method to use. Possible values are
``polybori``, ``sat`` and ``exhaustive_search``. (default:
``polybori``, since it is always available)
* ``n`` - number of solutions to return. If ``n == +Infinity``
then all solutions are returned. If `n < \infty` then `n`
solutions are returned if the equations have at least `n`
solutions. Otherwise, all the solutions are
returned. (default: ``1``)
* ``eliminate_linear_variables`` - whether to eliminate
variables that appear linearly. This reduces the number of
variables (makes solving faster a priori), but is likely to
make the equations denser (may make solving slower depending
on the method).
* ``verbose`` - whether to display progress and (potentially)
useful information while the computation runs. (default:
``False``)
EXAMPLES:
Without argument, a single arbitrary solution is returned::
sage: from sage.doctest.fixtures import reproducible_repr
sage: R.<x,y,z> = BooleanPolynomialRing()
sage: S = Sequence([x*y+z, y*z+x, x+y+z+1])
sage: sol = S.solve()
sage: print(reproducible_repr(sol))
[{x: 0, y: 1, z: 0}]
We check that it is actually a solution::
sage: S.subs( sol[0] )
[0, 0, 0]
We obtain all solutions::
sage: sols = S.solve(n=Infinity)
sage: print(reproducible_repr(sols))
[{x: 0, y: 1, z: 0}, {x: 1, y: 1, z: 1}]
sage: [S.subs(x) for x in sols]
[[0, 0, 0], [0, 0, 0]]
We can force the use of exhaustive search if the optional
package ``FES`` is present::
sage: sol = S.solve(algorithm='exhaustive_search') # optional - FES
sage: print(reproducible_repr(sol)) # optional - FES
[{x: 1, y: 1, z: 1}]
sage: S.subs( sol[0] )
[0, 0, 0]
And we may use SAT-solvers if they are available::
sage: sol = S.solve(algorithm='sat') # optional - pycryptosat
sage: print(reproducible_repr(sol)) # optional - pycryptosat
[{x: 0, y: 1, z: 0}]
sage: S.subs( sol[0] )
[0, 0, 0]
TESTS:
Make sure that variables not occurring in the equations are no problem::
sage: R.<x,y,z,t> = BooleanPolynomialRing()
sage: S = Sequence([x*y+z, y*z+x, x+y+z+1])
sage: sols = S.solve(n=Infinity)
sage: [S.subs(x) for x in sols]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
Not eliminating linear variables::
sage: sols = S.solve(n=Infinity, eliminate_linear_variables=False)
sage: [S.subs(x) for x in sols]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
A tricky case where the linear equations are insatisfiable::
sage: R.<x,y,z> = BooleanPolynomialRing()
sage: S = Sequence([x*y*z+x*y+z*y+x*z, x+y+z+1, x+y+z])
sage: S.solve()
[]
"""
from sage.rings.polynomial.pbori.pbori import BooleanPolynomialRing
from sage.modules.free_module import VectorSpace
S = self
R_origin = R_solving = self.ring()
reductors = []
if eliminate_linear_variables:
T, reductors = self.eliminate_linear_variables(return_reductors=True)
if T.variables() != ():
R_solving = BooleanPolynomialRing( T.nvariables(), [str(_) for _ in list(T.variables())] )
S = PolynomialSequence( R_solving, [ R_solving(f) for f in T] )
if S != []:
if algorithm == "polybori":
I = S.ideal()
if verbose:
I.groebner_basis(full_prot=True, **kwds)
else:
I.groebner_basis(**kwds)
solutions = I.variety()
if len(solutions) >= n:
solutions = solutions[:n]
elif algorithm == "sat":
from sage.sat.boolean_polynomials import solve as solve_sat
if verbose:
solutions = solve_sat(S, n=n, s_verbosity=1, **kwds)
else:
solutions = solve_sat(S, n=n, **kwds)
else:
raise ValueError("unknown 'algorithm' value")
else:
solutions = []
if S.variables() == ():
solved_variables = set()
else:
solved_variables = { R_origin(x).lm() for x in R_solving.gens() }
eliminated_variables = { f.lex_lead() for f in reductors }
leftover_variables = { x.lm() for x in R_origin.gens() } - solved_variables - eliminated_variables
key_convert = lambda x: R_origin(x).lm()
if leftover_variables != set():
partial_solutions = solutions
solutions = []
for sol in partial_solutions:
for v in VectorSpace( GF(2), len(leftover_variables) ):
new_solution = KeyConvertingDict(key_convert, sol)
for var,val in zip(leftover_variables, v):
new_solution[ var ] = val
solutions.append( new_solution )
else:
solutions = [ KeyConvertingDict(key_convert, sol)
for sol in solutions ]
for r in reductors:
for sol in solutions:
sol[ r.lm() ] = r.subs(sol).constant_coefficient()
return solutions
def reduced(self):
"""
If this sequence is `(f_1, ..., f_n)` this method returns `(g_1, ..., g_s)` such that:
- `<f_1,...,f_n> = <g_1,...,g_s>`
- `LT(g_i) != LT(g_j)` for all `i != j``
- `LT(g_i)` does not divide `m` for all monomials `m` of
`{g_1,...,g_{i-1},g_{i+1},...,g_s}`
EXAMPLES::
sage: sr = mq.SR(1, 1, 1, 4, gf2=True, polybori=True)
sage: while True: # workaround (see :trac:`31891`)
....: try:
....: F, s = sr.polynomial_system()
....: break
....: except ZeroDivisionError:
....: pass
sage: g = F.reduced()
sage: len(g) == len(set(gi.lt() for gi in g))
True
sage: for i in range(len(g)):
....: for j in range(len(g)):
....: if i == j:
....: continue
....: for t in list(g[j]):
....: assert g[i].lt() not in t.divisors()
"""
from sage.rings.polynomial.pbori.pbori import BooleanPolynomialRing
R = self.ring()
if isinstance(R, BooleanPolynomialRing):
from sage.rings.polynomial.pbori.interred import interred as inter_red
l = [p for p in self if not p==0]
l = sorted(inter_red(l, completely=True), reverse=True)
return PolynomialSequence(l, R, immutable=True)
else:
return PolynomialSequence_generic.reduced(self)
class PolynomialSequence_gf2e(PolynomialSequence_generic):
r"""
PolynomialSequence over `\GF{2^e}`, i.e extensions over
`\GF(2)`.
"""
def weil_restriction(self):
r"""
Project this polynomial system to `\GF{2}`.
That is, compute the Weil restriction of scalars for the
variety corresponding to this polynomial system and express it
as a polynomial system over `\GF{2}`.
EXAMPLES::
sage: k.<a> = GF(2^2)
sage: P.<x,y> = PolynomialRing(k,2)
sage: a = P.base_ring().gen()
sage: F = Sequence([x*y + 1, a*x + 1], P)
sage: F2 = F.weil_restriction()
sage: F2
[x0*y0 + x1*y1 + 1, x1*y0 + x0*y1 + x1*y1, x1 + 1, x0 + x1, x0^2 + x0,
x1^2 + x1, y0^2 + y0, y1^2 + y1]
Another bigger example for a small scale AES::
sage: sr = mq.SR(1,1,1,4,gf2=False)
sage: while True: # workaround (see :trac:`31891`)
....: try:
....: F, s = sr.polynomial_system()
....: break
....: except ZeroDivisionError:
....: pass
sage: F
Polynomial Sequence with 40 Polynomials in 20 Variables
sage: F2 = F.weil_restriction(); F2
Polynomial Sequence with 240 Polynomials in 80 Variables
"""
from sage.rings.ideal import FieldIdeal
J = self.ideal().weil_restriction()
J += FieldIdeal(J.ring())
return PolynomialSequence(J)
from sage.misc.persist import register_unpickle_override
register_unpickle_override("sage.crypto.mq.mpolynomialsystem","MPolynomialSystem_generic", PolynomialSequence_generic)
register_unpickle_override("sage.crypto.mq.mpolynomialsystem","MPolynomialRoundSystem_generic", PolynomialSequence_generic) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/multi_polynomial_sequence.py | 0.844553 | 0.734143 | multi_polynomial_sequence.py | pypi |
from sage.rings.polynomial.polynomial_element import Polynomial_generic_dense, Polynomial
from sage.rings.polynomial.padics.polynomial_padic import Polynomial_padic
from sage.rings.infinity import infinity
from sage.libs.pari.all import pari_gen
import sage.rings.padics.misc
class Polynomial_padic_flat(Polynomial_generic_dense, Polynomial_padic):
def __init__(self, parent, x=None, check=True, is_gen=False, construct=False, absprec=None):
"""
TESTS:
Check that :trac:`13620` has been fixed::
sage: K = ZpFM(3)
sage: R.<t> = K[]
sage: R(R.zero())
0
"""
if x is None:
Polynomial_generic_dense.__init__(self, parent, x, check, is_gen, construct)
return
R = parent.base_ring()
if sage.rings.fraction_field_element.is_FractionFieldElement(x):
if x.denominator() != 1:
raise TypeError("denominator must be 1")
else:
x = x.numerator()
if isinstance(x, Polynomial):
if x.base_ring() is R:
x = list(x.list())
else:
x = [R(a) for a in x.list()]
elif isinstance(x, list):
if check:
x = [R(a) for a in x]
elif isinstance(x, dict):
if check:
m = infinity
zero = R(0)
n = max(x) if x else 0
v = [zero] * (n + 1)
for i, z in x.items():
v[i] = R(z)
m = min(m, v[i].precision_absolute())
x = v
else:
m = sage.rings.padics.misc.min(a.precision_absolute()
for a in x.values())
if absprec is not None:
m = min(m, absprec)
Polynomial_generic_dense.__init__(self, parent, x, absprec=m)
return
elif isinstance(x, pari_gen):
x = [R(w) for w in x.list()]
else:
x = [R(x)]
if absprec is None:
absprec = infinity
m = min([a.precision_absolute() for a in x] + [absprec])
Polynomial_generic_dense.__init__(self, parent, x, absprec=m) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/padics/polynomial_padic_flat.py | 0.787319 | 0.483526 | polynomial_padic_flat.py | pypi |
from .pbori import (top_index, if_then_else,
mod_mon_set, BooleSet, BooleConstant)
from .PyPolyBoRi import (Polynomial, Monomial, Variable)
def all_monomials_of_degree_d_old(d, variables):
"""
Return monomials of degree d in the given variables.
Obsolete version ?
"""
if d == 0:
return BooleConstant(1)
if not variables:
return []
variables = sorted(set(variables), reverse=True, key=top_index)
m = variables[-1]
for v in variables[:-1]:
m = v + m
m = m.set()
i = 0
res = Polynomial(variables[0].ring().one()).set()
while i < d:
i += 1
res = res.cartesian_product(m).diff(res)
return res
def all_monomials_of_degree_d(d, variables):
"""
Return monomials of degree d in the given variables.
"""
variables = Monomial(variables)
variables = list(variables.variables())
if not variables:
assert d == 0
return BooleConstant(1)
ring = variables[0].ring()
if d > len(variables):
return Polynomial(0, ring)
if d < 0:
return Polynomial(1, ring)
deg_variables = variables[-d:]
# this ensures sorting by indices
res = Monomial(deg_variables)
for i in range(1, len(variables) - d + 1):
deg_variables = variables[-d - i:-i]
res = Polynomial(res)
nav = res.navigation()
navs = []
while not nav.constant():
navs.append(BooleSet(nav, ring))
nav = nav.then_branch()
acc = Polynomial(1, ring)
for (nav, v) in reversed(zip(navs, deg_variables)):
acc = if_then_else(v, acc, nav)
res = acc
return res.set()
def power_set(variables):
"""
Return all subsets of the given variables.
"""
if not variables:
return BooleConstant(1)
variables = sorted(set(variables), reverse=True, key=top_index)
res = Polynomial(1, variables[0].ring()).set()
for v in variables:
res = if_then_else(v, res, res)
return res
if __name__ == '__main__':
from .blocks import declare_ring, Block
r = declare_ring([Block("x", 10000)], globals())
print(list(all_monomials_of_degree_d(0, [Variable(i) for i in range(100)])))
print(list(all_monomials_of_degree_d(1, [Variable(i) for i in range(10)])))
print(list(all_monomials_of_degree_d(2, [Variable(i) for i in range(4)])))
print(list(all_monomials_of_degree_d(3, [Variable(i) for i in range(4)])))
print(list(all_monomials_of_degree_d(4, [Variable(i) for i in range(4)])))
print(list(all_monomials_of_degree_d(0, [])))
print(list(all_monomials_of_degree_d(1, [])))
print(list(power_set([Variable(i) for i in range(2)])))
print(list(power_set([Variable(i) for i in range(4)])))
print(list(power_set([])))
# every monomial in the first 8 var, which is at most linear in the first 5
print(list(mod_mon_set(power_set([Variable(i) for i in range(8)]),
all_monomials_of_degree_d(2, [Variable(i) for i in range(5)]))))
# specialized normal form computation
print(Polynomial(
mod_mon_set(
(x(1) * x(2) + x(1) + 1).set(),
all_monomials_of_degree_d(2, [Variable(i) for i in range(1000)]))))
print(list(mod_mon_set(power_set([Variable(i) for i in range(50)]),
all_monomials_of_degree_d(2, [Variable(i) for i in range(1000)]))))
def monomial_from_indices(ring, indices):
res = Monomial(ring)
for i in sorted(indices, reverse=True):
res = res * ring.variable(i)
return res | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/pbori/specialsets.py | 0.707809 | 0.61927 | specialsets.py | pypi |
r"""
PolyBoRi's interface to libpolybori/BRiAL
This file makes interfaces to PolyBoRi's runtime libraries available in Python via sage.
AUTHOR:
- The PolyBoRi Team, 2007-2012
EXAMPLES::
sage: from sage.rings.polynomial.pbori.pbori import *
sage: from sage.rings.polynomial.pbori.blocks import declare_ring
sage: r=declare_ring(["x0","x1","x2","y0","y1","y2"], globals())
sage: x0>x1
True
sage: x0>x1*x2
True
sage: y0>y1
True
sage: y0>y1*y2
True
sage: r = r.clone(ordering=dlex)
sage: r(x0) > r(x1)
True
sage: r(x0) > r(x1*x2)
False
sage: r = r.clone(ordering=dp_asc)
sage: r(x0) > r(x1)
False
sage: r(x0) > r(x1*x2)
False
sage: r = r.clone(ordering=block_dlex, blocks=[3])
sage: r(x0) > r(x1)
True
sage: r(x0) > r(x1*x2)
False
sage: r(x0) > r(y0*y1*y2)
True
sage: r = r.clone(ordering=block_dp_asc)
sage: r(x0) > r(x1)
False
sage: r(x0) > r(y0)
False
sage: r(x0) > r(x1*x2)
False
sage: r = r.clone(ordering=block_dp_asc, blocks=[3])
sage: r(x0) > r(y0)
True
sage: r(x0) > r(y0*y1)
True
sage: r = r.clone(names=["z17", "z7"])
sage: [r.variable(idx) for idx in range(3)]
[z17, z7, x2]
sage: r = r.clone(names="abcde")
sage: [r.variable(idx) for idx in range(6)]
[a, b, c, d, e, y2]
"""
from .pbori import (order_dict, TermOrder_from_pb_order, BooleanPolynomialRing,
BooleanPolynomialVector, MonomialFactory,
PolynomialFactory, VariableFactory, add_up_polynomials)
from .pbori import gauss_on_polys as _gauss_on_polys
import weakref
OrderCode = type('OrderCode', (object,), order_dict)
def Ring(n, order='lp', names=None, blocks=None):
if blocks is None:
blocks = []
pbnames = names
if pbnames is None:
pbnames = ['x(' + str(idx) + ')' for idx in range(n)]
order = TermOrder_from_pb_order(n, order, blocks)
return BooleanPolynomialRing(n, names=pbnames, order=order)
BoolePolynomialVector = BooleanPolynomialVector
# todo: PolyBoRi's original interface uses its WeakRingPtr here
def WeakRingRef(ring):
return weakref.weakref(ring)
Monomial = MonomialFactory()
Polynomial = PolynomialFactory()
Variable = VariableFactory()
_add_up_polynomials = add_up_polynomials
def add_up_polynomials(polys, init):
r"""
Adds up the polynomials in polys (which should be a BoolePolynomialVector or a sequence of ???
"""
if not isinstance(polys, BoolePolynomialVector):
vec = BoolePolynomialVector
for p in polys:
vec.append(p)
polys = vec
return _add_up_polynomials(polys, init)
def gauss_on_polys(l):
vec = BoolePolynomialVector(l)
return list(_gauss_on_polys(vec)) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/pbori/PyPolyBoRi.py | 0.553626 | 0.702288 | PyPolyBoRi.py | pypi |
from random import Random
from sage.rings.polynomial.pbori.pbori import if_then_else as ite
from .PyPolyBoRi import Polynomial
from .statistics import used_vars_set
class CNFEncoder():
def __init__(self, r, random_seed=16):
self.random_generator = Random(random_seed)
self.one_set = r.one().set()
self.empty_set = r.zero().set()
self.r = r
def zero_blocks(self, f):
r"""
Divide the zero set of f into blocks.
TESTS::
sage: from sage.rings.polynomial.pbori import *
sage: r = declare_ring(["x", "y", "z"], dict())
sage: from sage.rings.polynomial.pbori.cnf import CNFEncoder
sage: e = CNFEncoder(r)
sage: e.zero_blocks(r.variable(0)*r.variable(1)*r.variable(2))
[{z: 0}, {y: 0}, {x: 0}]
"""
f = Polynomial(f)
variables = f.vars_as_monomial()
space = variables.divisors()
variables = list(variables.variables())
zeros = f.zeros_in(space)
rest = zeros
res = []
# inefficient compared to polynomials lex_lead
def choose(s):
indices = []
assert not s.empty()
nav = s.navigation()
while not nav.constant():
e = nav.else_branch()
t = nav.then_branch()
if e.constant() and not e.terminal_one():
indices.append(nav.value())
nav = t
else:
if self.random_generator.randint(0, 1):
indices.append(nav.value())
nav = t
else:
nav = e
assert nav.terminal_one()
res = self.one_set
for i in reversed(indices):
res = ite(i, res, self.empty_set)
return next(iter(res))
while not rest.empty():
l = choose(rest)
l_variables = set(l.variables())
def get_val(var):
if var in l_variables:
return 1
return 0
block_dict = {v: get_val(v) for v in variables}
l = l.set()
self.random_generator.shuffle(variables)
for v in variables:
candidate = l.change(v.index())
if candidate.diff(zeros).empty():
l = l.union(candidate)
del block_dict[v]
rest = rest.diff(l)
res.append(block_dict)
return res
def clauses(self, f):
r"""
TESTS::
sage: from sage.rings.polynomial.pbori import *
sage: r = declare_ring(["x", "y", "z"], dict())
sage: from sage.rings.polynomial.pbori.cnf import CNFEncoder
sage: e = CNFEncoder(r)
sage: sorted(e.clauses(r.variable(0)*r.variable(1)*r.variable(2)), key=lambda d: sorted(d.items()))
[{z: 0, y: 0, x: 0}]
sage: sorted(e.clauses(r.variable(Integer(1))+r.variable(Integer(0))), key=lambda d: sorted(d.items()))
[{y: 0, x: 1}, {y: 1, x: 0}]
"""
# we form an expression for a var configuration *not* lying in the
# block it is evaluated to 0 by f, iff it is not lying in any zero
# block of f+1
return [{variable: 1 - value for variable, value in b.items()}
for b in self.zero_blocks(f + 1)]
def polynomial_clauses(self, f):
r"""
TESTS::
sage: from sage.rings.polynomial.pbori import *
sage: r = declare_ring(["x", "y", "z"], dict())
sage: from sage.rings.polynomial.pbori.cnf import CNFEncoder
sage: e = CNFEncoder(r)
sage: e.polynomial_clauses(r.variable(0)*r.variable(1)*r.variable(2))
[x*y*z]
sage: v = r.variable
sage: p = v(1)*v(2)+v(2)*v(0)+1
sage: groebner_basis([p], heuristic = False)==groebner_basis(e.polynomial_clauses(p), heuristic = False)
True
"""
def product(l):
res = l[0]
for p in l[1:]:
res = res * p
# please care about the order of these multiplications for
# performance
return res
return [product([variable + value for (variable, value)
in b.items()]) for b in self.clauses(f)]
def to_dimacs_index(self, v):
return v.index() + 1
def dimacs_encode_clause(self, c):
def get_sign(value):
if value == 1:
return 1
return -1
items = sorted(c.items(), reverse=True)
return " ".join([str(v) for v in [
get_sign(value) * self.to_dimacs_index(variable)
for (variable, value) in items] + [0]])
def dimacs_encode_polynomial(self, p):
r"""
TESTS::
sage: from sage.rings.polynomial.pbori import *
sage: d=dict()
sage: r = declare_ring(["x", "y", "z"], d)
sage: from sage.rings.polynomial.pbori.cnf import CNFEncoder
sage: e = CNFEncoder(r)
sage: sorted(e.dimacs_encode_polynomial(d["x"]+d["y"]+d["z"]))
['-1 -2 -3 0', '-1 2 3 0', '1 -2 3 0', '1 2 -3 0']
"""
clauses = self.clauses(p)
res = []
for c in clauses:
res.append(self.dimacs_encode_clause(c))
return res
def dimacs_cnf(self, polynomial_system):
r"""
TESTS::
sage: from sage.rings.polynomial.pbori import *
sage: r = declare_ring(["x", "y", "z"], dict())
sage: from sage.rings.polynomial.pbori.cnf import CNFEncoder
sage: e = CNFEncoder(r)
sage: e.dimacs_cnf([r.variable(0)*r.variable(1)*r.variable(2)])
'c cnf generated by PolyBoRi\np cnf 3 1\n-1 -2 -3 0'
sage: e.dimacs_cnf([r.variable(1)+r.variable(0)])
'c cnf generated by PolyBoRi\np cnf 3 2\n-1 2 0\n1 -2 0'
sage: e.dimacs_cnf([r.variable(0)*r.variable(1)*r.variable(2), r.variable(1)+r.variable(0)])
'c cnf generated by PolyBoRi\np cnf 3 3\n-1 -2 -3 0\n1 -2 0\n-1 2 0'
"""
clauses_list = [c for p in polynomial_system for c in self.
dimacs_encode_polynomial(p)]
res = ["c cnf generated by PolyBoRi"]
r = polynomial_system[0].ring()
n_variables = r.n_variables()
res.append("p cnf %s %s" % (n_variables, len(clauses_list)))
for c in clauses_list:
res.append(c)
return "\n".join(res)
class CryptoMiniSatEncoder(CNFEncoder):
group_counter = 0
def dimacs_encode_polynomial(self, p):
r"""
TESTS::
sage: from sage.rings.polynomial.pbori import *
sage: d=dict()
sage: r = declare_ring(["x", "y", "z"], d)
sage: from sage.rings.polynomial.pbori.cnf import CryptoMiniSatEncoder
sage: e = CryptoMiniSatEncoder(r)
sage: p = d["x"]+d["y"]+d["z"]
sage: p.deg()
1
sage: len(p)
3
sage: e.dimacs_encode_polynomial(p)
['x1 2 3 0\nc g 1 x + y + z']
sage: e.dimacs_encode_polynomial(p+1)
['x1 2 -3 0\nc g 2 x + y + z + 1']
"""
if p.deg() != 1 or len(p) <= 1:
res = super().dimacs_encode_polynomial(p)
else:
invert_last = bool(p.has_constant_part())
variables = list(p.vars_as_monomial().variables())
indices = [self.to_dimacs_index(v) for v in variables]
if invert_last:
indices[-1] = -indices[-1]
indices.append(0)
res = ["x" + " ".join(str(v) for v in indices)]
self.group_counter = self.group_counter + 1
group_comment = "\nc g %s %s" % (self.group_counter, str(p)[:30])
return [c + group_comment for c in res]
def dimacs_cnf(self, polynomial_system):
r"""
TESTS::
sage: from sage.rings.polynomial.pbori import *
sage: r = declare_ring(["x", "y", "z"], dict())
sage: from sage.rings.polynomial.pbori.cnf import CryptoMiniSatEncoder
sage: e = CryptoMiniSatEncoder(r)
sage: e.dimacs_cnf([r.variable(0)*r.variable(1)*r.variable(2)])
'c cnf generated by PolyBoRi\np cnf 3 1\n-1 -2 -3 0\nc g 1 x*y*z\nc v 1 x\nc v 2 y\nc v 3 z'
sage: e.dimacs_cnf([r.variable(1)+r.variable(0)])
'c cnf generated by PolyBoRi\np cnf 3 1\nx1 2 0\nc g 2 x + y\nc v 1 x\nc v 2 y'
sage: e.dimacs_cnf([r.variable(0)*r.variable(1)*r.variable(2), r.variable(1)+r.variable(0)])
'c cnf generated by PolyBoRi\np cnf 3 2\n-1 -2 -3 0\nc g 3 x*y*z\nx1 2 0\nc g 4 x + y\nc v 1 x\nc v 2 y\nc v 3 z'
"""
uv = list(used_vars_set(polynomial_system).variables())
res = super().dimacs_cnf(polynomial_system)
res = res + "\n" + "\n".join(["c v %s %s" % (self.to_dimacs_index(v),
v) for v in uv])
return res | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/pbori/cnf.py | 0.514644 | 0.442998 | cnf.py | pypi |
r"""
parallel.py
PolyBoRi
Created by Michael Brickenstein on 2008-10-31.
Copyright 2008 The PolyBoRi Team
"""
from zlib import compress, decompress
import copyreg
from .pbori import if_then_else, BooleSet, CCuddNavigator
from .PyPolyBoRi import (Polynomial, Ring, WeakRingRef, Monomial, Variable)
from .gbcore import groebner_basis
def to_fast_pickable(l):
r"""
Convert a list of polynomials into a builtin Python value, which is fast pickable and compact.
INPUT:
- a list of Boolean polynomials
OUTPUT:
It is converted to a tuple consisting of
- codes referring to the polynomials
- list of conversions of nodes.
The nodes are sorted, so that n occurs before n.else_branch(), n.then_branch()
nodes are only listed, if they are not constant.
A node is converted in this way:
0 -> 0
1 -> 1
if_then_else(v,t,e) -> (v, index of then branch +2, index of else branch +2)
the shift of +2 is for the constant values implicitly contained in the list.
Each code c refers to the c-2-th position in the conversion list, if c >=2, else to
the corresponding Boolean constant if c in {0, 1}
EXAMPLES::
sage: from sage.rings.polynomial.pbori import Ring, Polynomial
sage: from sage.rings.polynomial.pbori.parallel import to_fast_pickable, from_fast_pickable
sage: r = Ring(1000)
sage: x = r.variable
sage: to_fast_pickable([Polynomial(1, r)])
[[1], []]
sage: to_fast_pickable([Polynomial(0, r)])
[[0], []]
sage: to_fast_pickable([x(0)])
[[2], [(0, 1, 0)]]
sage: to_fast_pickable([x(0)*x(1)+x(1)])
[[2], [(0, 3, 3), (1, 1, 0)]]
sage: to_fast_pickable([x(1)])
[[2], [(1, 1, 0)]]
sage: to_fast_pickable([x(0)+1])
[[2], [(0, 1, 1)]]
sage: to_fast_pickable([x(0)*x(1)])
[[2], [(0, 3, 0), (1, 1, 0)]]
sage: to_fast_pickable([x(0)*x(1)+x(1)])
[[2], [(0, 3, 3), (1, 1, 0)]]
sage: to_fast_pickable([x(0)*x(1)+x(2)])
[[2], [(0, 3, 4), (1, 1, 0), (2, 1, 0)]]
sage: p=x(5)*x(23) + x(5)*x(24)*x(59) + x(5) + x(6)*x(23)*x(89) + x(6)*x(60)*x(89) + x(23) + x(24)*x(89) + x(24) + x(60)*x(89) + x(89) + 1
sage: from_fast_pickable(to_fast_pickable([p]), r)==[p]
True
sage: to_fast_pickable([x(0)*x(1), Polynomial(0, r), Polynomial(1, r), x(3)])
[[2, 0, 1, 4], [(0, 3, 0), (1, 1, 0), (3, 1, 0)]]
"""
if not l:
return [[], []]
f = l[0]
f = f.set()
r = f.ring()
one = r.one().navigation()
zero = r.zero().navigation()
nodes = set()
def find_navs(nav):
if nav not in nodes and not nav.constant():
nodes.add(nav)
find_navs(nav.then_branch())
find_navs(nav.else_branch())
for f in l:
f_nav = f.set().navigation()
find_navs(f_nav)
nodes_sorted = sorted(nodes, key=CCuddNavigator.value)
nodes2i = {one: 1, zero: 0}
for (i, n) in enumerate(nodes_sorted):
nodes2i[n] = i + 2
for i in range(len(nodes_sorted)):
n = nodes_sorted[i]
t = nodes2i[n.then_branch()]
e = nodes2i[n.else_branch()]
nodes_sorted[i] = (n.value(), t, e)
return [[nodes2i[f.set().navigation()] for f in l], nodes_sorted]
def from_fast_pickable(l, r):
r"""
Undo the operation :func:`to_fast_pickable`.
The first argument is an object created by :func:`to_fast_pickable`.
For the specified format, see the documentation of :func:`to_fast_pickable`.
The second argument is ring, in which this polynomial should be created.
INPUT:
See OUTPUT of :func:`to_fast_pickable`
OUTPUT:
a list of Boolean polynomials
EXAMPLES::
sage: from sage.rings.polynomial.pbori import Ring
sage: from sage.rings.polynomial.pbori.parallel import from_fast_pickable
sage: r = Ring(1000)
sage: x = r.variable
sage: from_fast_pickable([[1], []], r)
[1]
sage: from_fast_pickable([[0], []], r)
[0]
sage: from_fast_pickable([[2], [(0, 1, 0)]], r)
[x(0)]
sage: from_fast_pickable([[2], [(1, 1, 0)]], r)
[x(1)]
sage: from_fast_pickable([[2], [(0, 1, 1)]], r)
[x(0) + 1]
sage: from_fast_pickable([[2], [(0, 3, 0), (1, 1, 0)]], r)
[x(0)*x(1)]
sage: from_fast_pickable([[2], [(0, 3, 3), (1, 1, 0)]], r)
[x(0)*x(1) + x(1)]
sage: from_fast_pickable([[2], [(0, 3, 4), (1, 1, 0), (2, 1, 0)]], r)
[x(0)*x(1) + x(2)]
sage: from_fast_pickable([[2, 0, 1, 4], [(0, 3, 0), (1, 1, 0), (3, 1, 0)]], r)
[x(0)*x(1), 0, 1, x(3)]
"""
i2poly = {0: r.zero(), 1: r.one()}
(indices, terms) = l
for i in reversed(range(len(terms))):
(v, t, e) = terms[i]
t = i2poly[t]
e = i2poly[e]
terms[i] = if_then_else(v, t, e)
i2poly[i + 2] = terms[i]
return [Polynomial(i2poly[i]) for i in indices]
def _calculate_gb_with_keywords(args):
(I, kwds_as_single_arg) = args
return groebner_basis(I, **kwds_as_single_arg)
def _decode_polynomial(code):
return from_fast_pickable(*code)[0]
def _encode_polynomial(poly):
return (to_fast_pickable([poly]), poly.ring())
def pickle_polynomial(self):
return (_decode_polynomial, (_encode_polynomial(self), ))
copyreg.pickle(Polynomial, pickle_polynomial)
def pickle_bset(self):
return (BooleSet, (Polynomial(self), ))
copyreg.pickle(BooleSet, pickle_bset)
def pickle_monom(self):
return (Monomial, (list(self.variables()),))
copyreg.pickle(Monomial, pickle_monom)
def pickle_var(self):
return (Variable, (self.index(), self.ring()))
copyreg.pickle(Variable, pickle_var)
def _decode_ring(code):
import os
(identifier, data, varnames, blocks) = code
global _polybori_parallel_rings
try:
_polybori_parallel_rings
except NameError:
_polybori_parallel_rings = {}
for key in [key for key in _polybori_parallel_rings
if not _polybori_parallel_rings[key][0]()]:
del _polybori_parallel_rings[key]
if identifier in _polybori_parallel_rings:
ring = _polybori_parallel_rings[identifier][0]()
else:
ring = None
if not ring:
varnames = decompress(varnames).split('\n')
(nvars, ordercode) = data
ring = Ring(nvars, ordercode, names=varnames, blocks=blocks)
storage_data = (WeakRingRef(ring), code)
_polybori_parallel_rings[identifier] = storage_data
_polybori_parallel_rings[(ring.id(), os.getpid())] = storage_data
return ring
def _encode_ring(ring):
import os
identifier = (ring.id(), os.getpid())
global _polybori_parallel_rings
try:
_polybori_parallel_rings
except NameError:
_polybori_parallel_rings = {}
for key in [key for key in _polybori_parallel_rings
if not _polybori_parallel_rings[key][0]()]:
del _polybori_parallel_rings[key]
if identifier in _polybori_parallel_rings:
code = _polybori_parallel_rings[identifier][1]
else:
nvars = ring.n_variables()
data = (nvars, ring.get_order_code())
varnames = '\n'.join(str(ring.variable(idx))
for idx in range(nvars))
blocks = list(ring.blocks())
code = (identifier, data, compress(varnames), blocks[:-1])
_polybori_parallel_rings[identifier] = (WeakRingRef(ring), code)
return code
def pickle_ring(self):
return (_decode_ring, (_encode_ring(self), ))
copyreg.pickle(Ring, pickle_ring)
def groebner_basis_first_finished(I, *l):
r"""
INPUT:
- ``I`` -- ideal
- ``l`` -- keyword dictionaries, which will be keyword arguments to groebner_basis.
OUTPUT:
- tries to compute ``groebner_basis(I, **kwd)`` for kwd in l
- returns the result of the first terminated computation
EXAMPLES::
sage: from sage.rings.polynomial.pbori.PyPolyBoRi import Ring
sage: r = Ring(1000)
sage: ideal = [r.variable(1)*r.variable(2)+r.variable(2)+r.variable(1)]
sage: from sage.rings.polynomial.pbori.parallel import groebner_basis_first_finished
sage: groebner_basis_first_finished(ideal, dict(heuristic=True), dict(heuristic=False))
[x1, x2]
"""
if not I:
return []
from multiprocessing import Pool
pool = Pool(processes=len(l))
it = pool.imap_unordered(_calculate_gb_with_keywords,
[(I, kwds) for kwds in l])
res = next(it)
pool.terminate()
return res | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/pbori/parallel.py | 0.673406 | 0.68616 | parallel.py | pypi |
from .pbori import (top_index, if_then_else,
substitute_variables, BooleSet,
ll_red_nf_redsb, ll_red_nf_noredsb,
ll_red_nf_noredsb_single_recursive_call)
from .PyPolyBoRi import (Polynomial, Monomial, Ring, BoolePolynomialVector)
from .statistics import used_vars_set
from .rank import rank
lead_index = top_index
def combine(reductors, p, reduce=None):
p_nav = p.navigation()
assert p_nav.value() < reductors.navigation().value()
p_else = BooleSet(p_nav.else_branch(), p.ring())
if reduce:
p_else = reduce(p_else, reductors)
return if_then_else(p_nav.value(), reductors, p_else)
def llredsb_Cudd_style(polys):
if polys:
reductors = Polynomial(polys[0].ring().one()).set()
else:
reductors = None
linear_lead = sorted(polys, key=lead_index, reverse=True)
assert len(set(p.lex_lead() for p in linear_lead)) == len(polys)
assert not any(p.constant() for p in polys)
assert len([p for p in polys if p.lex_lead_deg() == 1]) == len(polys)
assert len(set(p.navigation().value() for p in polys)) == len(polys)
for p in linear_lead:
reductors = combine(reductors, p, reduce=ll_red_nf_redsb)
return reductors
def ll_encode(polys, reduce=False, prot=False, reduce_by_linear=True):
polys = [Polynomial(p) for p in polys]
linear_lead = sorted(polys, key=lead_index, reverse=True)
assert len(set(p.lex_lead() for p in linear_lead)) == len(polys)
assert not any(p.constant() for p in polys)
assert len([p for p in polys if p.lex_lead_deg() == 1]) == len(polys)
assert len(set(p.navigation().value() for p in polys)) == len(polys)
if (not reduce) and reduce_by_linear:
linear_polys = [p for p in polys if p.deg() == 1]
if linear_polys:
linear_ll = ll_encode(linear_polys, reduce=True,
reduce_by_linear=False)
polys = [p.lex_lead() + ll_red_nf_redsb(p + p.lex_lead(),
linear_ll) for p in polys]
if reduce:
reduce = ll_red_nf_redsb
else:
reduce = None
if polys:
reductors = Polynomial(polys[0].ring().one()).set()
else:
reductors = None
last = None
counter = 0
for p in linear_lead:
if prot:
counter = counter + 1
progress = (counter * 100) / len(linear_lead)
if last != progress:
print(str(progress) + "%")
last = progress
reductors = combine(reductors, p, reduce=reduce)
return reductors
def eliminate(polys, on_the_fly=False, prot=False, reduction_function=None,
optimized=True):
r"""
There exists an optimized variant, which reorders the variable in a different ring.
"""
polys = [Polynomial(p) for p in polys]
rest = []
linear_leads = []
linear_leading_monomials = set()
for p in polys:
if p.is_zero():
continue
lm = p.lex_lead()
if lm.deg() == 1:
if not (lm in linear_leading_monomials):
linear_leading_monomials.add(lm)
linear_leads.append(p)
else:
rest.append(p)
else:
rest.append(p)
if not linear_leads:
def identity(p):
return p
return (linear_leads, identity, rest)
if reduction_function is None:
if on_the_fly:
if optimized:
reduction_function = ll_red_nf_noredsb_single_recursive_call
else:
reduction_function = ll_red_nf_noredsb
else:
reduction_function = ll_red_nf_redsb
if optimized:
llnf, reduced_list = eliminate_ll_ranked(linear_leads, rest,
reduction_function=reduction_function,
reduce_ll_system=(not on_the_fly),
prot=prot)
else:
def llnf(p):
return reduction_function(p, reductors)
reduced_list = []
reductors = ll_encode(linear_leads, reduce=(not on_the_fly), prot=prot)
for p in rest:
p = reduction_function(p, reductors)
if p.is_one():
reduced_list = [p]
break
reduced_list.append(p)
return (linear_leads, llnf, reduced_list)
def construct_map_by_indices(to_ring, idx_mapping):
v = BoolePolynomialVector((max(idx_mapping.keys()) + 1) * [to_ring.zero()])
for (from_idx, to_idx) in idx_mapping.items():
val = to_ring.variable(to_idx)
v[from_idx] = val
return v
def eliminate_ll_ranked(ll_system, to_reduce,
reduction_function=ll_red_nf_noredsb,
reduce_ll_system=False, prot=False):
assert(ll_system)
from_ring = ll_system[0].ring()
ll_ranks = rank(ll_system)
add_vars = set(used_vars_set(to_reduce).variables()).difference(ll_ranks.
keys())
for v in add_vars:
ll_ranks[v] = -1
# pushing variables ignored by ll to the front means,
# that the routines will quickly eliminate them
# and they won't give any overhead
def sort_key(v):
return (ll_ranks[v], v.index())
sorted_vars = sorted(ll_ranks.keys(), key=sort_key)
def var_index(v):
return next(iter(Monomial(v).variables())).index()
to_ring = Ring(len(sorted_vars))
map_back_indices = {i: var_index(v) for i, v in enumerate(sorted_vars)}
map_from_indices = {var_index(v): i for i, v in enumerate(sorted_vars)}
var_names = [str(v) for v in sorted_vars]
try:
for (i, v) in enumerate(sorted_vars):
assert var_names[i] == str(v), (var_names[i], v, var_index(v), i)
finally:
pass
try:
map_from_vec = construct_map_by_indices(to_ring, map_from_indices)
finally:
pass
map_back_vec = construct_map_by_indices(from_ring, map_back_indices)
def map_from(p):
res = substitute_variables(to_ring, map_from_vec, p)
return res
def map_back(p):
return substitute_variables(from_ring, map_back_vec, p)
try:
ll_opt_encoded = ll_encode([map_from(p) for p in ll_system],
prot=False,
reduce=reduce_ll_system)
def llnf(p):
return map_back(reduction_function(map_from(p), ll_opt_encoded))
opt_eliminated = [llnf(p) for p in to_reduce]
finally:
pass
return (llnf, opt_eliminated)
class RingMap():
r"""
Define a mapping between two rings by common variable names.
TESTS::
sage: from sage.rings.polynomial.pbori.pbori import *
sage: from sage.rings.polynomial.pbori.blocks import declare_ring, Block
sage: to_ring = declare_ring([Block("x", 10)], globals())
sage: from_ring = declare_ring([Block("y", 5), Block("x", 10)], globals())
sage: from sage.rings.polynomial.pbori.ll import RingMap
sage: mapping = RingMap(to_ring, from_ring)
sage: (x(1)+1).navigation().value()
6
sage: mapping(x(1)+1)
x(1) + 1
sage: mapping(x(1)+1).navigation().value()
1
sage: mapping.invert(mapping(x(1)+1))
x(1) + 1
sage: mapping.invert(mapping(x(1)+1)).navigation().value()
6
sage: mapping(y(1)+1)
Traceback (most recent call last):
...
RuntimeError: Operands come from different manager.
"""
def __init__(self, to_ring, from_ring):
r"""
Initialize map by two given rings.
TESTS::
sage: from sage.rings.polynomial.pbori.pbori import *
sage: from sage.rings.polynomial.pbori.blocks import declare_ring, Block
sage: to_ring = declare_ring([Block("x", 10)], globals())
sage: from_ring = declare_ring([Block("y", 5), Block("x", 10)], globals())
sage: from sage.rings.polynomial.pbori.ll import RingMap
sage: mapping = RingMap(to_ring, from_ring)
sage: mapping(x(1)+1)
x(1) + 1
"""
def vars(ring):
return [ring.variable(i) for i in range(ring.n_variables())]
def indices(vars):
return {str(v): idx for idx, v in enumerate(vars)}
self.to_ring = to_ring
self.from_ring = from_ring
to_vars = vars(to_ring)
from_vars = vars(from_ring)
to_indices = indices(to_vars)
from_indices = indices(from_vars)
common = list(set(to_indices.keys()) & set(from_indices.keys()))
to_map = list(from_vars)
for elt in common:
to_map[from_indices[elt]] = to_vars[to_indices[elt]]
from_map = list(to_vars)
for elt in common:
from_map[to_indices[elt]] = from_vars[from_indices[elt]]
self.to_map = BoolePolynomialVector(to_map)
self.from_map = BoolePolynomialVector(from_map)
def __call__(self, poly):
r"""
Execute the map to change rings.
TESTS::
sage: from sage.rings.polynomial.pbori.pbori import *
sage: from sage.rings.polynomial.pbori.blocks import declare_ring, Block
sage: to_ring = declare_ring([Block("x", 10)], globals())
sage: from_ring = declare_ring([Block("y", 5), Block("x", 10)], globals())
sage: from sage.rings.polynomial.pbori.ll import RingMap
sage: mapping = RingMap(to_ring, from_ring)
sage: mapping(x(1)+1)
x(1) + 1
"""
return substitute_variables(self.to_ring, self.to_map, poly)
def invert(self, poly):
r"""
Inverted map to initial ring.
sage: from sage.rings.polynomial.pbori.pbori import *
sage: from sage.rings.polynomial.pbori.blocks import declare_ring, Block
sage: to_ring = declare_ring([Block("x", 10)], globals())
sage: from_ring = declare_ring([Block("y", 5), Block("x", 10)], globals())
sage: from sage.rings.polynomial.pbori.ll import RingMap
sage: mapping = RingMap(to_ring, from_ring)
sage: mapping.invert(mapping(x(1)+1))
x(1) + 1
"""
return substitute_variables(self.from_ring, self.from_map, poly) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/pbori/ll.py | 0.459319 | 0.496521 | ll.py | pypi |
from random import Random
from pprint import pformat
from .PyPolyBoRi import (Monomial, Polynomial, Variable)
from .pbori import random_set, set_random_seed, ll_red_nf_redsb
from .ll import ll_encode
from .blocks import declare_ring
def gen_random_poly(ring, l, deg, vars_set, seed=123):
"""
Generate a random polynomial with coefficients in ``ring``.
EXAMPLES::
sage: from sage.rings.polynomial.pbori.PyPolyBoRi import Ring, Variable
sage: from sage.rings.polynomial.pbori.randompoly import gen_random_poly
sage: r = Ring(16)
sage: vars = [Variable(i,r) for i in range(10)]
sage: gen_random_poly(r, 4, 10, vars) # random
x(0)*x(1)*x(2)*x(5)*x(8)*x(9) + x(0)*x(1)*x(4)*x(6) + x(0)*x(2)*x(3)*x(7)*x(9) + x(5)*x(8)
"""
myrange = vars_set
r = Random(seed)
def helper(samples):
if samples == 0:
return Polynomial(ring.zero())
if samples == 1:
d = r.randint(0, deg)
variables = r.sample(myrange, d)
m = Monomial(ring)
for v in sorted(set(variables), reverse=True):
m = m * Variable(v, ring)
return Polynomial(m)
assert samples >= 2
return helper(samples // 2) + helper(samples - samples // 2)
p = Polynomial(ring.zero())
while len(p) < l:
p = Polynomial(p.set().union(helper(l - len(p)).set()))
return p
def sparse_random_system(ring, number_of_polynomials, variables_per_polynomial,
degree, random_seed=None):
r"""
Generate a sparse random system.
Generate a system, which is sparse in the sense, that each polynomial
contains only a small subset of variables. In each variable that occurrs
in a polynomial it is dense in the terms up to the given degree
(every term occurs with probability 1/2).
The system will be satisfiable by at least one solution.
TESTS::
sage: from sage.rings.polynomial.pbori import Ring, groebner_basis
sage: r = Ring(10)
sage: from sage.rings.polynomial.pbori.randompoly import sparse_random_system
sage: s = sparse_random_system(r, number_of_polynomials=20, variables_per_polynomial=3, degree=2, random_seed=int(123))
sage: [p.deg() for p in s]
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
sage: sorted(groebner_basis(s), reverse=True)
[x(0), x(1) + 1, x(2), x(3) + 1, x(4) + 1, x(5), x(6), x(7) + 1, x(8) + 1, x(9) + 1]
"""
if random_seed is not None:
set_random_seed(random_seed)
random_generator = Random(random_seed)
solutions = []
variables = [ring.variable(i) for i in range(ring.n_variables())]
for v in variables:
solutions.append(v + random_generator.randint(0, 1))
solutions = ll_encode(solutions)
res = []
while len(res) < number_of_polynomials:
variables_as_monomial = Monomial(
random_generator.sample(
variables,
variables_per_polynomial)
)
p = Polynomial(random_set(variables_as_monomial, 2 ** (
variables_per_polynomial - 1)))
p = sum([p.graded_part(i) for i in range(degree + 1)])
if p.deg() == degree:
res.append(p)
# evaluate it to guarantee a solution
return [p + ll_red_nf_redsb(p, solutions) for p in res]
def sparse_random_system_data_file_content(number_of_variables, **kwds):
r"""
TESTS::
sage: from sage.rings.polynomial.pbori.randompoly import sparse_random_system_data_file_content
sage: sparse_random_system_data_file_content(10, number_of_polynomials=5, variables_per_polynomial=3, degree=2, random_seed=int(123))
"declare_ring(['x'+str(i) for in range(10)])\nideal=\\\n[...]\n\n"
"""
dummy_dict = {}
r = declare_ring(['x' + str(i) for i in range(number_of_variables)],
dummy_dict)
polynomials = sparse_random_system(r, **kwds)
polynomials = pformat(polynomials)
return "declare_ring(['x'+str(i) for in range(%s)])\nideal=\\\n%s\n\n" % (
number_of_variables, polynomials) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/pbori/randompoly.py | 0.645008 | 0.550547 | randompoly.py | pypi |
from .PyPolyBoRi import Polynomial, BoolePolynomialVector
from .pbori import FGLMStrategy, BooleSet
def _fglm(I, from_ring, to_ring):
r"""
Unchecked variant of fglm
"""
vec = BoolePolynomialVector(I)
return FGLMStrategy(from_ring, to_ring, vec).main()
def fglm(I, from_ring, to_ring):
r"""
Convert *reduced* Groebner Basis in ``from_ring`` to a GroebnerBasis
in ``to_ring``.
It acts independent of the global ring, which is restored at the end of the
computation.
TESTS::
sage: from sage.rings.polynomial.pbori import *
sage: from sage.rings.polynomial.pbori.PyPolyBoRi import OrderCode
sage: dp_asc = OrderCode.dp_asc
sage: r=declare_ring(['x','y','z'],dict())
sage: old_ring = r
sage: new_ring = old_ring.clone(ordering=dp_asc)
sage: (x,y,z) = [old_ring.variable(i) for i in range(3)]
sage: ideal=[x+z, y+z]# lp Groebner basis
sage: from sage.rings.polynomial.pbori.fglm import fglm
sage: list(fglm(ideal, old_ring, new_ring))
[y + x, z + x]
"""
for poly in I:
if poly.ring().id() != from_ring.id():
raise ValueError("Ideal I must be from the first ring argument")
return _fglm(I, from_ring, to_ring)
def vars_real_divisors(monomial, monomial_set):
r"""
Return all elements of ``monomial_set``, which result multiplied by a variable in monomial.
EXAMPLES::
sage: from sage.rings.polynomial.pbori.pbori import *
sage: from sage.rings.polynomial.pbori.PyPolyBoRi import OrderCode
sage: dp_asc = OrderCode.dp_asc
sage: from sage.rings.polynomial.pbori.PyPolyBoRi import Ring
sage: r = Ring(1000)
sage: x = r.variable
sage: b = BooleSet([x(1)*x(2),x(2)])
sage: from sage.rings.polynomial.pbori.fglm import vars_real_divisors
sage: vars_real_divisors(x(1)*x(2)*x(3),b)
{{x(1),x(2)}}
"""
return BooleSet(Polynomial(monomial_set.divisors_of(monomial)).
graded_part(monomial.deg() - 1))
def m_k_plus_one(completed_elements, variables):
r"""
Calculate `m_{k+1}` from the FGLM algorithm.
Calculate `m_{k+1}` from the FGLM algorithm as described in Wichmann [Wich1997]_.
.. NOTE::
It would be nice to be able to efficiently extract the smallest term of a polynomial.
EXAMPLES::
sage: from sage.rings.polynomial.pbori.pbori import *
sage: from sage.rings.polynomial.pbori.PyPolyBoRi import OrderCode
sage: from sage.rings.polynomial.pbori.fglm import m_k_plus_one
sage: dp_asc = OrderCode.dp_asc
sage: from sage.rings.polynomial.pbori.PyPolyBoRi import Ring
sage: r = Ring(1000)
sage: x = r.variable
sage: from sage.rings.polynomial.pbori.PyPolyBoRi import Monomial
sage: s = BooleSet([x(1)*x(2),x(1),x(2),Monomial(r),x(3)])
sage: variables = BooleSet([x(1),x(2),x(3)])
sage: m_k_plus_one(s,variables)
x(2)*x(3)
sage: r2 = r.clone(ordering=dp_asc)
sage: m_k_plus_one(r2(s).set(),r2(variables).set())
x(1)*x(3)
"""
return sorted(completed_elements.cartesian_product(variables).diff(
completed_elements))[0] | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/pbori/fglm.py | 0.837686 | 0.678194 | fglm.py | pypi |
from sage.misc.lazy_import import lazy_import
from .PyPolyBoRi import Ring, Polynomial, Monomial, Variable
# Get all-inclusive groebner routine
from .gbcore import groebner_basis
from .nf import normal_form
# Import some high-level modelling functionality
from .blocks import declare_ring
from .blocks import HigherOrderBlock, AlternatingBlock, Block
from .gbrefs import load_file
from .specialsets import all_monomials_of_degree_d, power_set
# Advertised reimports
# ... any from below? ...
# Deprecated reimports
lazy_import('sage.rings.polynomial.pbori.pbori',
['BooleConstant',
'BooleSet',
'BooleSetIterator',
'BooleanMonomial',
'BooleanMonomialIterator',
'BooleanMonomialMonoid',
'BooleanMonomialVariableIterator',
'BooleanMulAction',
'BooleanPolynomial',
'BooleanPolynomialEntry',
'BooleanPolynomialIdeal',
'BooleanPolynomialIterator',
'BooleanPolynomialRing',
'BooleanPolynomialVector',
'BooleanPolynomialVectorIterator',
'CCuddNavigator',
'FGLMStrategy',
'GroebnerStrategy',
'MonomialConstruct',
'MonomialFactory',
'PolynomialConstruct',
'PolynomialFactory',
'ReductionStrategy',
'TermOrder_from_pb_order',
'VariableBlock',
'VariableConstruct',
'add_up_polynomials',
'block_dlex',
'block_dp_asc',
'contained_vars',
'dlex',
'dp',
'dp_asc',
'easy_linear_factors',
'gauss_on_polys',
'get_var_mapping',
'if_then_else',
'interpolate',
'interpolate_smallest_lex',
'inv_order_dict',
'll_red_nf_noredsb',
'll_red_nf_noredsb_single_recursive_call',
'll_red_nf_redsb',
'lp',
'map_every_x_to_x_plus_one',
'mod_mon_set',
'mod_var_set',
'mult_fact_sim_C',
'nf3',
'order_dict',
'order_mapping',
'parallel_reduce',
'random_set',
'recursively_insert',
'red_tail',
'rings',
'set_random_seed',
'singular_default',
'substitute_variables',
'top_index',
'unpickle_BooleanPolynomial',
'unpickle_BooleanPolynomial0',
'unpickle_BooleanPolynomialRing',
'zeros'],
deprecation=30332) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/pbori/__init__.py | 0.474388 | 0.17971 | __init__.py | pypi |
from time import process_time as clock
from random import Random
from .PyPolyBoRi import (Polynomial, Variable, Monomial,
BoolePolynomialVector)
from .randompoly import gen_random_poly
from .pbori import (BooleSet, add_up_polynomials, interpolate_smallest_lex,
interpolate)
from .blocks import Block, declare_ring
generator = Random()
def add_up_poly_list(l, init):
v = BoolePolynomialVector()
for p in l:
v.append(p)
return add_up_polynomials(v, init)
def bench_interpolate(degree, nvariables, points):
c = points
h = len(points) / 2
terms = set(c.terms())
part1 = generator.sample(terms, h)
part1 = add_up_poly_list(part1, Polynomial(c.ring().zero()))
part2 = c + part1
p = part1
q = part2
assert part1.set().intersect(part2).empty()
c1 = clock()
res2 = interpolate_smallest_lex(p, q)
c2 = clock()
print("finished interpolate_smallest_lex(p,q),len:", len(res2),
"time", c2 - c1)
c1 = clock()
res1 = interpolate(p, q)
c2 = clock()
print("finished interpolate(p,q)" + len("_smallest_lex") * " " + ",len:",
res1.set().size_double(), "time:", c2 - c1)
return res2
def nf_lex_points(f, p):
f = Polynomial(f)
p = BooleSet(p)
z = f.zeros_in(p)
return interpolate_smallest_lex(z, p.diff(z))
def gen_random_o_z(points, points_p):
k = generator.randrange(len(points) + 1)
ones = generator.sample(points, k)
vec = BoolePolynomialVector()
for p in ones:
vec.append(p)
ones = add_up_polynomials(vec, Polynomial(points_p.ring().zero()))
return interpolate_smallest_lex(points_p.set().diff(ones), ones)
def variety_lex_leading_terms(points, variables):
assert isinstance(points, BooleSet), "Points needs to be a BooleSet"
ring = variables.ring()
standards = BooleSet(ring.zero())
points_tuple = tuple(points)
myvars_div = variables.divisors()
if points != myvars_div:
standards = BooleSet(ring.one())
len_standards = len(standards)
standards_old = standards
while len_standards < len(points):
standards = standards.union(gen_random_o_z(points_tuple, points))
if standards_old != standards:
standards = BooleSet(standards).include_divisors()
len_standards = len(standards)
standards_old = standards
return BooleSet(myvars_div.diff(standards)).minimal_elements()
def lex_groebner_basis_points(points, variables):
leads = variety_lex_leading_terms(points, variables)
return [nf_lex_points(l, points) + l for l in leads]
def lex_groebner_basis_for_polynomial_via_variety(p):
variables = p.vars_as_monomial()
return lex_groebner_basis_points(p.zeros_in(variables.divisors()),
variables)
if __name__ == '__main__':
nvariables = 100
r = declare_ring([Block("x", nvariables)])
for number_of_points in (100, 500, 1000, 2000, 3000,
4000, 5000, 10000,
20000, 50000, 100000):
print("----------")
print("number_of_points:", number_of_points)
print("generate points")
points = gen_random_poly(r, number_of_points,
nvariables,
[Variable(i, r) for i in range(nvariables)])
print("points generated")
bench_interpolate(nvariables, nvariables, points)
vars_mon = Monomial(r)
for i in reversed(range(nvariables)):
vars_mon = vars_mon * Variable(i, r)
print(len(variety_lex_leading_terms(points, vars_mon)),
"elements in groebner basis") | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/rings/polynomial/pbori/interpolate.py | 0.624866 | 0.576363 | interpolate.py | pypi |
from sage.misc.superseded import deprecation
from sage.modules.free_module_element import vector
from sage.rings.real_double import RDF
def find_root(f, a, b, xtol=10e-13, rtol=2.0**-50, maxiter=100, full_output=False):
r"""
Numerically find a root of ``f`` on the closed interval `[a,b]`
(or `[b,a]`) if possible, where ``f`` is a function in the one variable.
Note: this function only works in fixed (machine) precision, it is not
possible to get arbitrary precision approximations with it.
INPUT:
- ``f`` -- a function of one variable or symbolic equality
- ``a``, ``b`` -- endpoints of the interval
- ``xtol``, ``rtol`` -- the routine converges when a root is known
to lie within ``xtol`` of the value return. Should be `\geq 0`.
The routine modifies this to take into account the relative precision
of doubles. By default, rtol is ``4*numpy.finfo(float).eps``, the
minimum allowed value for ``scipy.optimize.brentq``, which is what
this method uses underneath. This value is equal to ``2.0**-50`` for
IEEE-754 double precision floats as used by Python.
- ``maxiter`` -- integer; if convergence is not achieved in
``maxiter`` iterations, an error is raised. Must be `\geq 0`.
- ``full_output`` -- bool (default: ``False``), if ``True``, also return
object that contains information about convergence.
EXAMPLES:
An example involving an algebraic polynomial function::
sage: R.<x> = QQ[]
sage: f = (x+17)*(x-3)*(x-1/8)^3
sage: find_root(f, 0,4)
2.999999999999995
sage: find_root(f, 0,1) # abs tol 1e-6 (note -- precision of answer isn't very good on some machines)
0.124999
sage: find_root(f, -20,-10)
-17.0
In Pomerance's book on primes he asserts that the famous Riemann
Hypothesis is equivalent to the statement that the function `f(x)`
defined below is positive for all `x \geq 2.01`::
sage: def f(x):
....: return sqrt(x) * log(x) - abs(Li(x) - prime_pi(x))
We find where `f` equals, i.e., what value that is slightly smaller
than `2.01` that could have been used in the formulation of the Riemann
Hypothesis::
sage: find_root(f, 2, 4, rtol=0.0001)
2.0082...
This agrees with the plot::
sage: plot(f,2,2.01)
Graphics object consisting of 1 graphics primitive
The following example was added due to :trac:`4942` and demonstrates that
the function need not be defined at the endpoints::
sage: find_root(x^2*log(x,2)-1,0, 2) # abs tol 1e-6
1.41421356237
The following is an example, again from :trac:`4942` where Brent's method
fails. Currently no other method is implemented, but at least we
acknowledge the fact that the algorithm fails::
sage: find_root(1/(x-1)+1,0, 2)
0.0
sage: find_root(1/(x-1)+1,0.00001, 2)
Traceback (most recent call last):
...
NotImplementedError: Brent's method failed to find a zero for f on the interval
An example of a function which evaluates to NaN on the entire interval::
sage: f(x) = 0.0 / max(0, x)
sage: find_root(f, -1, 0)
Traceback (most recent call last):
...
RuntimeError: f appears to have no zero on the interval
"""
try:
return f.find_root(a=a,b=b,xtol=xtol,rtol=rtol,maxiter=maxiter,full_output=full_output)
except AttributeError:
pass
a = float(a)
b = float(b)
if a > b:
a, b = b, a
left = f(a)
right = f(b)
if left > 0 and right > 0:
# Refine further -- try to find a point where this
# function is negative in the interval
val, s = find_local_minimum(f, a, b)
if val > 0:
if val < rtol:
if full_output:
return s, "No extra data"
else:
return s
raise RuntimeError("f appears to have no zero on the interval")
# If we found such an s, then we just instead find
# a root between left and s or s and right.
a = s # arbitrary choice -- maybe should try both and take one that works?
elif left < 0 and right < 0:
# Refine further
val, s = find_local_maximum(f, a, b)
if val < 0:
if abs(val) < rtol:
if full_output:
return s, "No extra data"
else:
return s
raise RuntimeError("f appears to have no zero on the interval")
a = s
# Fixing :trac:`4942` - if the answer on any of the endpoints is NaN,
# we restrict to looking between minimum and maximum values in the segment
# Note - this could be used in all cases, but it requires some more
# computation
if (left != left) or (right != right):
minval, s_1 = find_local_minimum(f, a, b)
maxval, s_2 = find_local_maximum(f, a, b)
if ((minval > 0) or (maxval < 0) or
(minval != minval) or (maxval != maxval)):
raise RuntimeError("f appears to have no zero on the interval")
a = min(s_1, s_2)
b = max(s_1, s_2)
import scipy.optimize
brentqRes = scipy.optimize.brentq(f, a, b,
full_output=full_output, xtol=xtol, rtol=rtol, maxiter=maxiter)
# A check following :trac:`4942`, to ensure we actually found a root
# Maybe should use a different tolerance here?
# The idea is to take roughly the derivative and multiply by estimated
# value of the root
root = 0
if full_output:
root = brentqRes[0]
else:
root = brentqRes
if abs(f(root)) > max(abs(root * rtol * (right - left) / (b - a)), 1e-6):
raise NotImplementedError("Brent's method failed to find a zero for f on the interval")
return brentqRes
def find_local_maximum(f, a, b, tol=1.48e-08, maxfun=500):
"""
Numerically find a local maximum of the expression `f` on the interval
`[a,b]` (or `[b,a]`) along with the point at which the maximum is attained.
Note that this function only finds a *local* maximum, and not the
global maximum on that interval -- see the examples with
:func:`find_local_maximum`.
See the documentation for :func:`find_local_maximum` for more
details and possible workarounds for finding the global minimum on
an interval.
EXAMPLES::
sage: f = lambda x: x*cos(x)
sage: find_local_maximum(f, 0, 5)
(0.561096338191..., 0.8603335890...)
sage: find_local_maximum(f, 0, 5, tol=0.1, maxfun=10)
(0.561090323458..., 0.857926501456...)
sage: find_local_maximum(8*e^(-x)*sin(x) - 1, 0, 7)
(1.579175535558..., 0.7853981...)
"""
try:
return f.find_local_maximum(a=a, b=b, tol=tol, maxfun=maxfun)
except AttributeError:
pass
minval, x = find_local_minimum(lambda z: -f(z), a=a, b=b, tol=tol, maxfun=maxfun)
return -minval, x
def find_local_minimum(f, a, b, tol=1.48e-08, maxfun=500):
"""
Numerically find a local minimum of the expression ``f`` on the
interval `[a,b]` (or `[b,a]`) and the point at which it attains that
minimum. Note that ``f`` must be a function of (at most) one
variable.
Note that this function only finds a *local* minimum, and not the
global minimum on that interval -- see the examples below.
INPUT:
- ``f`` -- a function of at most one variable.
- ``a``, ``b`` -- endpoints of interval on which to minimize self.
- ``tol`` -- the convergence tolerance
- ``maxfun`` -- maximum function evaluations
OUTPUT:
- ``minval`` -- (float) the minimum value that self takes on in the
interval `[a,b]`
- ``x`` -- (float) the point at which self takes on the minimum value
EXAMPLES::
sage: f = lambda x: x*cos(x)
sage: find_local_minimum(f, 1, 5)
(-3.28837139559..., 3.4256184695...)
sage: find_local_minimum(f, 1, 5, tol=1e-3)
(-3.28837136189098..., 3.42575079030572...)
sage: find_local_minimum(f, 1, 5, tol=1e-2, maxfun=10)
(-3.28837084598..., 3.4250840220...)
sage: show(plot(f, 0, 20))
sage: find_local_minimum(f, 1, 15)
(-9.4772942594..., 9.5293344109...)
Only local minima are found; if you enlarge the interval, the
returned minimum may be *larger*! See :trac:`2607`.
::
sage: f(x) = -x*sin(x^2)
sage: find_local_minimum(f, -2.5, -1)
(-2.182769784677722, -2.1945027498534686)
Enlarging the interval returns a larger minimum::
sage: find_local_minimum(f, -2.5, 2)
(-1.3076194129914434, 1.3552111405712108)
One work-around is to plot the function and grab the minimum from
that, although the plotting code does not necessarily do careful
numerics (observe the small number of decimal places that we
actually test)::
sage: plot(f, (x,-2.5, -1)).ymin()
-2.182...
sage: plot(f, (x,-2.5, 2)).ymin()
-2.182...
ALGORITHM:
Uses `scipy.optimize.fminbound
<http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fminbound.html>`_
which uses Brent's method.
AUTHOR:
- William Stein (2007-12-07)
"""
try:
return f.find_local_minimum(a=a, b=b, tol=tol, maxfun=maxfun)
except AttributeError:
pass
a = float(a)
b = float(b)
import scipy.optimize
xmin, fval, iter, funcalls = scipy.optimize.fminbound(f, a, b, full_output=1, xtol=tol, maxfun=maxfun)
return fval, xmin
def minimize(func, x0, gradient=None, hessian=None, algorithm="default",
verbose=False, **args):
r"""
This function is an interface to a variety of algorithms for computing
the minimum of a function of several variables.
INPUT:
- ``func`` -- Either a symbolic function or a Python function whose
argument is a tuple with `n` components
- ``x0`` -- Initial point for finding minimum.
- ``gradient`` -- Optional gradient function. This will be computed
automatically for symbolic functions. For Python functions, it allows
the use of algorithms requiring derivatives. It should accept a
tuple of arguments and return a NumPy array containing the partial
derivatives at that point.
- ``hessian`` -- Optional hessian function. This will be computed
automatically for symbolic functions. For Python functions, it allows
the use of algorithms requiring derivatives. It should accept a tuple
of arguments and return a NumPy array containing the second partial
derivatives of the function.
- ``algorithm`` -- String specifying algorithm to use. Options are
``'default'`` (for Python functions, the simplex method is the default)
(for symbolic functions bfgs is the default):
- ``'simplex'`` -- using the downhill simplex algorithm
- ``'powell'`` -- use the modified Powell algorithm
- ``'bfgs'`` -- (Broyden-Fletcher-Goldfarb-Shanno) requires gradient
- ``'cg'`` -- (conjugate-gradient) requires gradient
- ``'ncg'`` -- (newton-conjugate gradient) requires gradient and hessian
- ``verbose`` -- (optional, default: False) print convergence message
.. NOTE::
For additional information on the algorithms implemented in this function,
consult SciPy's `documentation on optimization and root
finding <https://docs.scipy.org/doc/scipy/reference/optimize.html>`_
EXAMPLES:
Minimize a fourth order polynomial in three variables (see the
:wikipedia:`Rosenbrock_function`)::
sage: vars = var('x y z')
sage: f = 100*(y-x^2)^2+(1-x)^2+100*(z-y^2)^2+(1-y)^2
sage: minimize(f, [.1,.3,.4]) # abs tol 1e-6
(1.0, 1.0, 1.0)
Try the newton-conjugate gradient method; the gradient and hessian are
computed automatically::
sage: minimize(f, [.1, .3, .4], algorithm="ncg") # abs tol 1e-6
(1.0, 1.0, 1.0)
We get additional convergence information with the `verbose` option::
sage: minimize(f, [.1, .3, .4], algorithm="ncg", verbose=True)
Optimization terminated successfully.
...
(0.9999999..., 0.999999..., 0.999999...)
Same example with just Python functions::
sage: def rosen(x): # The Rosenbrock function
....: return sum(100.0r*(x[1r:]-x[:-1r]**2.0r)**2.0r + (1r-x[:-1r])**2.0r)
sage: minimize(rosen, [.1,.3,.4]) # abs tol 3e-5
(1.0, 1.0, 1.0)
Same example with a pure Python function and a Python function to
compute the gradient::
sage: def rosen(x): # The Rosenbrock function
....: return sum(100.0r*(x[1r:]-x[:-1r]**2.0r)**2.0r + (1r-x[:-1r])**2.0r)
sage: import numpy
sage: from numpy import zeros
sage: def rosen_der(x):
....: xm = x[1r:-1r]
....: xm_m1 = x[:-2r]
....: xm_p1 = x[2r:]
....: der = zeros(x.shape, dtype=float)
....: der[1r:-1r] = 200r*(xm-xm_m1**2r) - 400r*(xm_p1 - xm**2r)*xm - 2r*(1r-xm)
....: der[0] = -400r*x[0r]*(x[1r]-x[0r]**2r) - 2r*(1r-x[0])
....: der[-1] = 200r*(x[-1r]-x[-2r]**2r)
....: return der
sage: minimize(rosen, [.1,.3,.4], gradient=rosen_der, algorithm="bfgs") # abs tol 1e-6
(1.0, 1.0, 1.0)
"""
from sage.structure.element import Expression
from sage.ext.fast_callable import fast_callable
import numpy
from scipy import optimize
if isinstance(func, Expression):
var_list=func.variables()
var_names = [str(_) for _ in var_list]
fast_f=fast_callable(func, vars=var_names, domain=float)
f=lambda p: fast_f(*p)
gradient_list=func.gradient()
fast_gradient_functions=[fast_callable(gradient_list[i], vars=var_names, domain=float) for i in range(len(gradient_list))]
gradient=lambda p: numpy.array([ a(*p) for a in fast_gradient_functions])
else:
f=func
if algorithm=="default":
if gradient is None:
min = optimize.fmin(f, [float(_) for _ in x0], disp=verbose, **args)
else:
min= optimize.fmin_bfgs(f, [float(_) for _ in x0],fprime=gradient, disp=verbose, **args)
else:
if algorithm=="simplex":
min= optimize.fmin(f, [float(_) for _ in x0], disp=verbose, **args)
elif algorithm=="bfgs":
min= optimize.fmin_bfgs(f, [float(_) for _ in x0], fprime=gradient, disp=verbose, **args)
elif algorithm=="cg":
min= optimize.fmin_cg(f, [float(_) for _ in x0], fprime=gradient, disp=verbose, **args)
elif algorithm=="powell":
min= optimize.fmin_powell(f, [float(_) for _ in x0], disp=verbose, **args)
elif algorithm=="ncg":
if isinstance(func, Expression):
hess=func.hessian()
hess_fast= [ [fast_callable(a, vars=var_names, domain=float) for a in row] for row in hess]
hessian=lambda p: [[a(*p) for a in row] for row in hess_fast]
from scipy import dot
hessian_p=lambda p,v: dot(numpy.array(hessian(p)),v)
min = optimize.fmin_ncg(f, [float(_) for _ in x0], fprime=gradient,
fhess=hessian, fhess_p=hessian_p, disp=verbose, **args)
return vector(RDF, min)
def minimize_constrained(func,cons,x0,gradient=None,algorithm='default', **args):
r"""
Minimize a function with constraints.
INPUT:
- ``func`` -- Either a symbolic function, or a Python function whose
argument is a tuple with n components
- ``cons`` -- constraints. This should be either a function or list of
functions that must be positive. Alternatively, the constraints can
be specified as a list of intervals that define the region we are
minimizing in. If the constraints are specified as functions, the
functions should be functions of a tuple with `n` components
(assuming `n` variables). If the constraints are specified as a list
of intervals and there are no constraints for a given variable, that
component can be (``None``, ``None``).
- ``x0`` -- Initial point for finding minimum
- ``algorithm`` -- Optional, specify the algorithm to use:
- ``'default'`` -- default choices
- ``'l-bfgs-b'`` -- only effective if you specify bound constraints.
See [ZBN1997]_.
- ``gradient`` -- Optional gradient function. This will be computed
automatically for symbolic functions. This is only used when the
constraints are specified as a list of intervals.
EXAMPLES:
Let us maximize `x + y - 50` subject to the following constraints:
`50x + 24y \leq 2400`, `30x + 33y \leq 2100`, `x \geq 45`,
and `y \geq 5`::
sage: y = var('y')
sage: f = lambda p: -p[0]-p[1]+50
sage: c_1 = lambda p: p[0]-45
sage: c_2 = lambda p: p[1]-5
sage: c_3 = lambda p: -50*p[0]-24*p[1]+2400
sage: c_4 = lambda p: -30*p[0]-33*p[1]+2100
sage: a = minimize_constrained(f,[c_1,c_2,c_3,c_4],[2,3])
sage: a
(45.0, 6.25...)
Let's find a minimum of `\sin(xy)`::
sage: x,y = var('x y')
sage: f(x,y) = sin(x*y)
sage: minimize_constrained(f, [(None,None),(4,10)],[5,5])
(4.8..., 4.8...)
Check if L-BFGS-B finds the same minimum::
sage: minimize_constrained(f, [(None,None),(4,10)],[5,5], algorithm='l-bfgs-b')
(4.7..., 4.9...)
Rosenbrock function (see the :wikipedia:`Rosenbrock_function`)::
sage: from scipy.optimize import rosen, rosen_der
sage: minimize_constrained(rosen, [(-50,-10),(5,10)],[1,1],gradient=rosen_der,algorithm='l-bfgs-b')
(-10.0, 10.0)
sage: minimize_constrained(rosen, [(-50,-10),(5,10)],[1,1],algorithm='l-bfgs-b')
(-10.0, 10.0)
TESTS:
Check if :trac:`6592` is fixed::
sage: x, y = var('x y')
sage: f(x,y) = (100 - x) + (1000 - y)
sage: c(x,y) = x + y - 479 # > 0
sage: minimize_constrained(f, [c], [100, 300])
(805.985..., 1005.985...)
sage: minimize_constrained(f, c, [100, 300])
(805.985..., 1005.985...)
If ``func`` is symbolic, its minimizer should be in the same order
as its arguments (:trac:`32511`)::
sage: x,y = SR.var('x,y')
sage: f(y,x) = x - y
sage: c1(y,x) = x
sage: c2(y,x) = 1-y
sage: minimize_constrained(f, [c1, c2], (0,0))
(1.0, 0.0)
"""
from sage.structure.element import Expression
from sage.ext.fast_callable import fast_callable
import numpy
from scipy import optimize
function_type = type(lambda x,y: x+y)
if isinstance(func, Expression):
var_list = func.arguments()
fast_f = fast_callable(func, vars=var_list, domain=float)
f = lambda p: fast_f(*p)
gradient_list = func.gradient()
fast_gradient_functions = [ fast_callable(gi,
vars=var_list,
domain=float)
for gi in gradient_list ]
gradient = lambda p: numpy.array([ a(*p) for a in fast_gradient_functions])
if isinstance(cons, Expression):
fast_cons = fast_callable(cons, vars=var_list, domain=float)
cons = lambda p: numpy.array([fast_cons(*p)])
elif isinstance(cons, list) and isinstance(cons[0], Expression):
fast_cons = [ fast_callable(ci, vars=var_list, domain=float)
for ci in cons ]
cons = lambda p: numpy.array([a(*p) for a in fast_cons])
else:
f = func
if isinstance(cons, list):
if isinstance(cons[0], (tuple, list)) or cons[0] is None:
if gradient is not None:
if algorithm == 'l-bfgs-b':
min = optimize.fmin_l_bfgs_b(f, x0, gradient, bounds=cons, iprint=-1, **args)[0]
else:
min = optimize.fmin_tnc(f, x0, gradient, bounds=cons, messages=0, **args)[0]
else:
if algorithm == 'l-bfgs-b':
min = optimize.fmin_l_bfgs_b(f, x0, approx_grad=True, bounds=cons, iprint=-1, **args)[0]
else:
min = optimize.fmin_tnc(f, x0, approx_grad=True, bounds=cons, messages=0, **args)[0]
elif isinstance(cons[0], (function_type, Expression)):
min = optimize.fmin_cobyla(f, x0, cons, **args)
elif isinstance(cons, function_type) or isinstance(cons, Expression):
min = optimize.fmin_cobyla(f, x0, cons, **args)
return vector(RDF, min)
def linear_program(c, G, h, A=None, b=None, solver=None):
r"""
Solve the dual linear programs:
- Minimize `c'x` subject to `Gx + s = h`, `Ax = b`, and `s \geq 0` where
`'` denotes transpose.
- Maximize `-h'z - b'y` subject to `G'z + A'y + c = 0` and `z \geq 0`.
This function is deprecated. Use :class:`MixedIntegerLinearProgram` instead.
This function depends on the optional package ``cvxopt``.
INPUT:
- ``c`` -- a vector
- ``G`` -- a matrix
- ``h`` -- a vector
- ``A`` -- a matrix
- ``b`` --- a vector
- ``solver`` (optional) --- solver to use. If None, the cvxopt's lp-solver
is used. If it is 'glpk', then glpk's solver
is used.
These can be over any field that can be turned into a floating point
number.
OUTPUT:
A dictionary ``sol`` with keys ``x``, ``s``, ``y``, ``z`` corresponding
to the variables above:
- ``sol['x']`` -- the solution to the linear program
- ``sol['s']`` -- the slack variables for the solution
- ``sol['z']``, ``sol['y']`` -- solutions to the dual program
EXAMPLES:
First, we minimize `-4x_1 - 5x_2` subject to `2x_1 + x_2 \leq 3`,
`x_1 + 2x_2 \leq 3`, `x_1 \geq 0`, and `x_2 \geq 0`::
sage: c=vector(RDF,[-4,-5])
sage: G=matrix(RDF,[[2,1],[1,2],[-1,0],[0,-1]])
sage: h=vector(RDF,[3,3,0,0])
sage: sol=linear_program(c,G,h) # optional - cvxopt
doctest:warning...
DeprecationWarning: linear_program is deprecated; use MixedIntegerLinearProgram instead
See https://trac.sagemath.org/32226 for details.
sage: sol['x'] # optional - cvxopt
(0.999..., 1.000...)
Here we solve the same problem with 'glpk' interface to 'cvxopt'::
sage: sol=linear_program(c,G,h,solver='glpk') # optional - cvxopt
GLPK Simplex Optimizer...
...
OPTIMAL LP SOLUTION FOUND
sage: sol['x'] # optional - cvxopt
(1.0, 1.0)
Next, we maximize `x+y-50` subject to `50x + 24y \leq 2400`,
`30x + 33y \leq 2100`, `x \geq 45`, and `y \geq 5`::
sage: v=vector([-1.0,-1.0,-1.0])
sage: m=matrix([[50.0,24.0,0.0],[30.0,33.0,0.0],[-1.0,0.0,0.0],[0.0,-1.0,0.0],[0.0,0.0,1.0],[0.0,0.0,-1.0]])
sage: h=vector([2400.0,2100.0,-45.0,-5.0,1.0,-1.0])
sage: sol=linear_program(v,m,h) # optional - cvxopt
sage: sol['x'] # optional - cvxopt
(45.000000..., 6.2499999..., 1.00000000...)
sage: sol=linear_program(v,m,h,solver='glpk') # optional - cvxopt
GLPK Simplex Optimizer...
OPTIMAL LP SOLUTION FOUND
sage: sol['x'] # optional - cvxopt
(45.0..., 6.25..., 1.0...)
"""
deprecation(32226, 'linear_program is deprecated; use MixedIntegerLinearProgram instead')
from cvxopt.base import matrix as m
from cvxopt import solvers
solvers.options['show_progress']=False
if solver=='glpk':
from cvxopt import glpk
glpk.options['LPX_K_MSGLEV'] = 0
c_=m(c.base_extend(RDF).numpy())
G_=m(G.base_extend(RDF).numpy())
h_=m(h.base_extend(RDF).numpy())
if A is not None and b is not None:
A_=m(A.base_extend(RDF).numpy())
b_=m(b.base_extend(RDF).numpy())
sol=solvers.lp(c_,G_,h_,A_,b_,solver=solver)
else:
sol=solvers.lp(c_,G_,h_,solver=solver)
status = sol['status']
if status != 'optimal':
return {'primal objective': None, 'x': None, 's': None, 'y': None,
'z': None, 'status': status}
x = vector(RDF, list(sol['x']))
s = vector(RDF, list(sol['s']))
y = vector(RDF, list(sol['y']))
z = vector(RDF, list(sol['z']))
return {'primal objective': sol['primal objective'],
'x': x, 's': s, 'y': y, 'z': z, 'status': status}
def find_fit(data, model, initial_guess = None, parameters = None, variables = None, solution_dict = False):
r"""
Finds numerical estimates for the parameters of the function model to
give a best fit to data.
INPUT:
- ``data`` -- A two dimensional table of floating point numbers of the
form `[[x_{1,1}, x_{1,2}, \ldots, x_{1,k}, f_1],
[x_{2,1}, x_{2,2}, \ldots, x_{2,k}, f_2],
\ldots,
[x_{n,1}, x_{n,2}, \ldots, x_{n,k}, f_n]]` given as either a list of
lists, matrix, or numpy array.
- ``model`` -- Either a symbolic expression, symbolic function, or a
Python function. ``model`` has to be a function of the variables
`(x_1, x_2, \ldots, x_k)` and free parameters
`(a_1, a_2, \ldots, a_l)`.
- ``initial_guess`` -- (default: ``None``) Initial estimate for the
parameters `(a_1, a_2, \ldots, a_l)`, given as either a list, tuple,
vector or numpy array. If ``None``, the default estimate for each
parameter is `1`.
- ``parameters`` -- (default: ``None``) A list of the parameters
`(a_1, a_2, \ldots, a_l)`. If model is a symbolic function it is
ignored, and the free parameters of the symbolic function are used.
- ``variables`` -- (default: ``None``) A list of the variables
`(x_1, x_2, \ldots, x_k)`. If model is a symbolic function it is
ignored, and the variables of the symbolic function are used.
- ``solution_dict`` -- (default: ``False``) if ``True``, return the
solution as a dictionary rather than an equation.
EXAMPLES:
First we create some data points of a sine function with some "random"
perturbations::
sage: set_random_seed(0)
sage: data = [(i, 1.2 * sin(0.5*i-0.2) + 0.1 * normalvariate(0, 1)) for i in xsrange(0, 4*pi, 0.2)]
sage: var('a, b, c, x')
(a, b, c, x)
We define a function with free parameters `a`, `b` and `c`::
sage: model(x) = a * sin(b * x - c)
We search for the parameters that give the best fit to the data::
sage: find_fit(data, model)
[a == 1.21..., b == 0.49..., c == 0.19...]
We can also use a Python function for the model::
sage: def f(x, a, b, c): return a * sin(b * x - c)
sage: fit = find_fit(data, f, parameters = [a, b, c], variables = [x], solution_dict = True)
sage: fit[a], fit[b], fit[c]
(1.21..., 0.49..., 0.19...)
We search for a formula for the `n`-th prime number::
sage: dataprime = [(i, nth_prime(i)) for i in range(1, 5000, 100)]
sage: find_fit(dataprime, a * x * log(b * x), parameters = [a, b], variables = [x])
[a == 1.11..., b == 1.24...]
ALGORITHM:
Uses ``scipy.optimize.leastsq`` which in turn uses MINPACK's lmdif and
lmder algorithms.
"""
import numpy
if not isinstance(data, numpy.ndarray):
try:
data = numpy.array(data, dtype = float)
except (ValueError, TypeError):
raise TypeError("data has to be a list of lists, a matrix, or a numpy array")
elif data.dtype == object:
raise ValueError("the entries of data have to be of type float")
if data.ndim != 2:
raise ValueError("data has to be a two dimensional table of floating point numbers")
from sage.structure.element import Expression
if isinstance(model, Expression):
if variables is None:
variables = list(model.arguments())
if parameters is None:
parameters = list(model.variables())
for v in variables:
parameters.remove(v)
if data.shape[1] != len(variables) + 1:
raise ValueError("each row of data needs %d entries, only %d entries given" % (len(variables) + 1, data.shape[1]))
if parameters is None or len(parameters) == 0 or \
variables is None or len(variables) == 0:
raise ValueError("no variables given")
if initial_guess is None:
initial_guess = len(parameters) * [1]
if not isinstance(initial_guess, numpy.ndarray):
try:
initial_guess = numpy.array(initial_guess, dtype = float)
except (ValueError, TypeError):
raise TypeError("initial_guess has to be a list, tuple, or numpy array")
elif initial_guess.dtype == object:
raise ValueError("the entries of initial_guess have to be of type float")
if len(initial_guess) != len(parameters):
raise ValueError("length of initial_guess does not coincide with the number of parameters")
if isinstance(model, Expression):
from sage.ext.fast_callable import fast_callable
var_list = variables + parameters
func = fast_callable(model, vars=var_list, domain=float)
else:
func = model
def function(x_data, params):
result = numpy.zeros(len(x_data))
for row in range(len(x_data)):
fparams = numpy.hstack((x_data[row], params)).tolist()
result[row] = func(*fparams)
return result
def error_function(params, x_data, y_data):
result = numpy.zeros(len(x_data))
for row in range(len(x_data)):
fparams = x_data[row].tolist() + params.tolist()
result[row] = func(*fparams)
return result - y_data
x_data = data[:, 0:len(variables)]
y_data = data[:, -1]
from scipy.optimize import leastsq
estimated_params, d = leastsq(error_function, initial_guess,
args=(x_data, y_data))
if isinstance(estimated_params, float):
estimated_params = [estimated_params]
else:
estimated_params = estimated_params.tolist()
if solution_dict:
return {i0: i1 for i0, i1 in zip(parameters, estimated_params)}
return [item[0] == item[1] for item in zip(parameters, estimated_params)]
def binpacking(items, maximum=1, k=None, solver=None, verbose=0,
*, integrality_tolerance=1e-3):
r"""
Solve the bin packing problem.
The Bin Packing problem is the following :
Given a list of items of weights `p_i` and a real value `k`, what is the
least number of bins such that all the items can be packed in the bins,
while ensuring that the sum of the weights of the items packed in each bin
is at most `k` ?
For more informations, see :wikipedia:`Bin_packing_problem`.
Two versions of this problem are solved by this algorithm :
- Is it possible to put the given items in `k` bins ?
- What is the assignment of items using the least number of bins with
the given list of items ?
INPUT:
- ``items`` -- list or dict; either a list of real values (the items'
weight), or a dictionary associating to each item its weight.
- ``maximum`` -- (default: 1); the maximal size of a bin
- ``k`` -- integer (default: ``None``); Number of bins
- When set to an integer value, the function returns a partition of the
items into `k` bins if possible, and raises an exception otherwise.
- When set to ``None``, the function returns a partition of the items
using the least possible number of bins.
- ``solver`` -- (default: ``None``) Specify a Mixed Integer Linear Programming
(MILP) solver to be used. If set to ``None``, the default one is used. For
more information on MILP solvers and which default solver is used, see
the method
:meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`
of the class
:class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.
- ``verbose`` -- integer (default: ``0``); sets the level of verbosity. Set
to 0 by default, which means quiet.
- ``integrality_tolerance`` -- parameter for use with MILP solvers over an
inexact base ring; see :meth:`MixedIntegerLinearProgram.get_values`.
OUTPUT:
A list of lists, each member corresponding to a bin and containing either
the list of the weights inside it when ``items`` is a list of items' weight,
or the list of items inside it when ``items`` is a dictionary. If there is
no solution, an exception is raised (this can only happen when ``k`` is
specified or if ``maximum`` is less than the weight of one item).
EXAMPLES:
Trying to find the minimum amount of boxes for 5 items of weights
`1/5, 1/4, 2/3, 3/4, 5/7`::
sage: from sage.numerical.optimize import binpacking
sage: values = [1/5, 1/3, 2/3, 3/4, 5/7]
sage: bins = binpacking(values)
sage: len(bins)
3
Checking the bins are of correct size ::
sage: all(sum(b) <= 1 for b in bins)
True
Checking every item is in a bin ::
sage: b1, b2, b3 = bins
sage: all((v in b1 or v in b2 or v in b3) for v in values)
True
And only in one bin ::
sage: sum(len(b) for b in bins) == len(values)
True
One way to use only three boxes (which is best possible) is to put
`1/5 + 3/4` together in a box, `1/3+2/3` in another, and `5/7`
by itself in the third one.
Of course, we can also check that there is no solution using only two boxes ::
sage: from sage.numerical.optimize import binpacking
sage: binpacking([0.2,0.3,0.8,0.9], k=2)
Traceback (most recent call last):
...
ValueError: this problem has no solution
We can also provide a dictionary keyed by items and associating to each item
its weight. Then, the bins contain the name of the items inside it ::
sage: values = {'a':1/5, 'b':1/3, 'c':2/3, 'd':3/4, 'e':5/7}
sage: bins = binpacking(values)
sage: set(flatten(bins)) == set(values.keys())
True
TESTS:
Wrong type for parameter items::
sage: binpacking(set())
Traceback (most recent call last):
...
TypeError: parameter items must be a list or a dictionary.
"""
if isinstance(items, list):
weight = {i:w for i,w in enumerate(items)}
elif isinstance(items, dict):
weight = items
else:
raise TypeError("parameter items must be a list or a dictionary.")
if max(weight.values()) > maximum:
raise ValueError("this problem has no solution")
if k is None:
from sage.functions.other import ceil
k = ceil(sum(weight.values())/maximum)
while True:
from sage.numerical.mip import MIPSolverException
try:
return binpacking(items, k=k, maximum=maximum, solver=solver, verbose=verbose,
integrality_tolerance=integrality_tolerance)
except MIPSolverException:
k = k + 1
from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException
p = MixedIntegerLinearProgram(solver=solver)
# Boolean variable indicating whether the ith element belongs to box b
box = p.new_variable(binary=True)
# Capacity constraint of each bin
for b in range(k):
p.add_constraint(p.sum(weight[i]*box[i,b] for i in weight) <= maximum)
# Each item is assigned exactly one bin
for i in weight:
p.add_constraint(p.sum(box[i,b] for b in range(k)) == 1)
try:
p.solve(log=verbose)
except MIPSolverException:
raise ValueError("this problem has no solution")
box = p.get_values(box, convert=bool, tolerance=integrality_tolerance)
boxes = [[] for i in range(k)]
for i,b in box:
if box[i,b]:
boxes[b].append(weight[i] if isinstance(items, list) else i)
return boxes | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/numerical/optimize.py | 0.930954 | 0.716281 | optimize.py | pypi |
r"""
Base classes for reflexive modules
"""
from sage.misc.abstract_method import abstract_method
from sage.structure.parent import Parent
class ReflexiveModule_abstract(Parent):
r"""
Abstract base class for reflexive modules.
An `R`-module `M` is *reflexive* if the natural map from `M` to its double
dual `M^{**}` is an isomorphism.
In the category of `R`-modules, the dual module `M^*` is
the `R`-module of linear functionals `\phi:\ M \longrightarrow R`.
However, we do not make the assumption that the dual module
(obtained by :meth:`dual`) is in the category :class:`Homsets`.
We identify the double dual `M^{**}` with `M`.
Tensor products of reflexive modules are reflexive. We identify all
tensor products of `k` copies of `M` and `l` copies of `M^*` and
denote it by `T^{(k,l)}(M)`. The :meth:`tensor_type` of such a tensor
product is the pair `(k, l)`, and `M` is called its :meth:`base_module`.
There are three abstract subclasses:
- :class:`ReflexiveModule_base` is the base class for implementations
of base modules `M`.
- :class:`ReflexiveModule_dual` is the base class for implementations
of duals `M^*`.
- :class:`ReflexiveModule_tensor` is the base class for implementations
of tensor modules `T^{(k,l)}(M)`.
TESTS::
sage: from sage.tensor.modules.reflexive_module import (
....: ReflexiveModule_abstract, ReflexiveModule_base,
....: ReflexiveModule_dual, ReflexiveModule_tensor)
sage: M = FiniteRankFreeModule(ZZ, 3)
sage: isinstance(M, ReflexiveModule_abstract)
True
sage: isinstance(M, ReflexiveModule_base)
True
sage: isinstance(M.dual(), ReflexiveModule_abstract)
True
sage: isinstance(M.dual(), ReflexiveModule_dual)
True
sage: isinstance(M.tensor_module(1, 1), ReflexiveModule_abstract)
True
sage: isinstance(M.tensor_module(1, 1), ReflexiveModule_tensor)
True
"""
@abstract_method(optional=True)
def tensor_type(self):
r"""
Return the tensor type of ``self``.
OUTPUT:
- pair `(k,l)` such that ``self`` is the module tensor product
`T^{(k,l)}(M)`, where `M` is the :meth:`base_module` of ``self``.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3)
sage: T = M.tensor_module(1, 2)
sage: T.tensor_type()
(1, 2)
"""
@abstract_method
def base_module(self):
r"""
Return the module on which ``self`` is constructed.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3)
sage: M.base_module() is M
True
sage: M.dual().base_module() is M
True
sage: M.tensor_module(1, 2).base_module() is M
True
"""
def dual(self):
r"""
Return the dual module.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3)
sage: M.dual()
Dual of the Rank-3 free module over the Integer Ring
sage: M.dual().dual()
Rank-3 free module over the Integer Ring
sage: M.tensor_module(1, 2)
Free module of type-(1,2) tensors on the Rank-3 free module over the Integer Ring
sage: M.tensor_module(1, 2).dual()
Free module of type-(2,1) tensors on the Rank-3 free module over the Integer Ring
"""
k, l = self.tensor_type()
return self.base_module().tensor_module(l, k)
def tensor(self, *args, **kwds):
# Until https://trac.sagemath.org/ticket/30373 is done,
# TensorProductFunctor._functor_name is "tensor", so here we delegate.
r"""
Return the tensor product of ``self`` and ``others``.
This method is invoked when :class:`~sage.categories.tensor.TensorProductFunctor`
is applied to parents.
It just delegates to :meth:`tensor_product`.
EXAMPLES::
sage: M = FiniteRankFreeModule(QQ, 2); M
2-dimensional vector space over the Rational Field
sage: M20 = M.tensor_module(2, 0); M20
Free module of type-(2,0) tensors on the 2-dimensional vector space over the Rational Field
sage: tensor([M20, M20])
Free module of type-(4,0) tensors on the 2-dimensional vector space over the Rational Field
"""
return self.tensor_product(*args, **kwds)
def tensor_power(self, n):
r"""
Return the ``n``-fold tensor product of ``self``.
EXAMPLES::
sage: M = FiniteRankFreeModule(QQ, 2)
sage: M.tensor_power(3)
Free module of type-(3,0) tensors on the 2-dimensional vector space over the Rational Field
sage: M.tensor_module(1,2).tensor_power(3)
Free module of type-(3,6) tensors on the 2-dimensional vector space over the Rational Field
"""
tensor_type = self.tensor_type()
return self.base_module().tensor_module(n * tensor_type[0], n * tensor_type[1])
def tensor_product(self, *others):
r"""
Return the tensor product of ``self`` and ``others``.
EXAMPLES::
sage: M = FiniteRankFreeModule(QQ, 2)
sage: M.tensor_product(M)
Free module of type-(2,0) tensors on the 2-dimensional vector space over the Rational Field
sage: M.tensor_product(M.dual())
Free module of type-(1,1) tensors on the 2-dimensional vector space over the Rational Field
sage: M.dual().tensor_product(M, M.dual())
Free module of type-(1,2) tensors on the 2-dimensional vector space over the Rational Field
sage: M.tensor_product(M.tensor_module(1,2))
Free module of type-(2,2) tensors on the 2-dimensional vector space over the Rational Field
sage: M.tensor_module(1,2).tensor_product(M)
Free module of type-(2,2) tensors on the 2-dimensional vector space over the Rational Field
sage: M.tensor_module(1,1).tensor_product(M.tensor_module(1,2))
Free module of type-(2,3) tensors on the 2-dimensional vector space over the Rational Field
sage: Sym2M = M.tensor_module(2, 0, sym=range(2)); Sym2M
Free module of fully symmetric type-(2,0) tensors on the 2-dimensional vector space over the Rational Field
sage: Sym01x23M = Sym2M.tensor_product(Sym2M); Sym01x23M
Free module of type-(4,0) tensors on the 2-dimensional vector space over the Rational Field,
with symmetry on the index positions (0, 1), with symmetry on the index positions (2, 3)
sage: Sym01x23M._index_maps
((0, 1), (2, 3))
sage: N = M.tensor_module(3, 3, sym=[1, 2], antisym=[3, 4]); N
Free module of type-(3,3) tensors on the 2-dimensional vector space over the Rational Field,
with symmetry on the index positions (1, 2),
with antisymmetry on the index positions (3, 4)
sage: NxN = N.tensor_product(N); NxN
Free module of type-(6,6) tensors on the 2-dimensional vector space over the Rational Field,
with symmetry on the index positions (1, 2), with symmetry on the index positions (4, 5),
with antisymmetry on the index positions (6, 7), with antisymmetry on the index positions (9, 10)
sage: NxN._index_maps
((0, 1, 2, 6, 7, 8), (3, 4, 5, 9, 10, 11))
"""
from sage.modules.free_module_element import vector
from .comp import CompFullySym, CompFullyAntiSym, CompWithSym
base_module = self.base_module()
if not all(module.base_module() == base_module for module in others):
raise NotImplementedError('all factors must be tensor modules over the same base module')
factors = [self] + list(others)
result_tensor_type = sum(vector(factor.tensor_type()) for factor in factors)
result_sym = []
result_antisym = []
# Keep track of reordering of the contravariant and covariant indices
# (compatible with FreeModuleTensor.__mul__)
index_maps = []
running_indices = vector([0, result_tensor_type[0]])
for factor in factors:
tensor_type = factor.tensor_type()
index_map = tuple(i + running_indices[0] for i in range(tensor_type[0]))
index_map += tuple(i + running_indices[1] for i in range(tensor_type[1]))
index_maps.append(index_map)
if tensor_type[0] + tensor_type[1] > 1:
basis_sym = factor._basis_sym()
all_indices = tuple(range(tensor_type[0] + tensor_type[1]))
if isinstance(basis_sym, CompFullySym):
sym = [all_indices]
antisym = []
elif isinstance(basis_sym, CompFullyAntiSym):
sym = []
antisym = [all_indices]
elif isinstance(basis_sym, CompWithSym):
sym = basis_sym._sym
antisym = basis_sym._antisym
else:
sym = antisym = []
def map_isym(isym):
return tuple(index_map[i] for i in isym)
result_sym.extend(tuple(index_map[i] for i in isym) for isym in sym)
result_antisym.extend(tuple(index_map[i] for i in isym) for isym in antisym)
running_indices += vector(tensor_type)
result = base_module.tensor_module(*result_tensor_type,
sym=result_sym, antisym=result_antisym)
result._index_maps = tuple(index_maps)
return result
class ReflexiveModule_base(ReflexiveModule_abstract):
r"""
Abstract base class for reflexive modules that are base modules.
TESTS::
sage: from sage.tensor.modules.reflexive_module import ReflexiveModule_base
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: isinstance(M, ReflexiveModule_base)
True
"""
def base_module(self):
r"""
Return the free module on which ``self`` is constructed, namely ``self`` itself.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: M.base_module() is M
True
sage: M = Manifold(2, 'M')
sage: XM = M.vector_field_module()
sage: XM.base_module() is XM
True
"""
return self
def tensor_type(self):
r"""
Return the tensor type of ``self``, the pair `(1, 0)`.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3)
sage: M.tensor_type()
(1, 0)
sage: M = Manifold(2, 'M')
sage: XM = M.vector_field_module()
sage: XM.tensor_type()
(1, 0)
"""
return (1, 0)
def dual(self):
r"""
Return the dual module.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: M.dual()
Dual of the Rank-3 free module M over the Integer Ring
"""
return self.tensor_module(0, 1)
@abstract_method
def tensor_module(self, k, l, **kwds):
r"""
Return the module of all tensors of type `(k, l)` defined on ``self``.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3)
sage: M.tensor_module(1, 2)
Free module of type-(1,2) tensors on the Rank-3 free module over the Integer Ring
"""
class ReflexiveModule_dual(ReflexiveModule_abstract):
r"""
Abstract base class for reflexive modules that are the duals of base modules.
TESTS::
sage: from sage.tensor.modules.reflexive_module import ReflexiveModule_dual
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: isinstance(M.dual(), ReflexiveModule_dual)
True
"""
def tensor_type(self):
r"""
Return the tensor type of ``self``.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: M.dual().tensor_type()
(0, 1)
"""
return (0, 1)
def construction(self):
r"""
Return the functorial construction of ``self``.
This implementation just returns ``None``, as no functorial construction is implemented.
TESTS::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: A = M.dual()
sage: A.construction() is None
True
"""
# Until https://trac.sagemath.org/ticket/34605 is done
return None
class ReflexiveModule_tensor(ReflexiveModule_abstract):
r"""
Abstract base class for reflexive modules that are tensor products of base modules.
TESTS::
sage: from sage.tensor.modules.reflexive_module import ReflexiveModule_tensor
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: isinstance(M.tensor_module(1, 1), ReflexiveModule_tensor)
True
"""
def tensor_factors(self):
r"""
Return the tensor factors of this tensor module.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: T = M.tensor_module(2, 3)
sage: T.tensor_factors()
[Rank-3 free module M over the Integer Ring,
Rank-3 free module M over the Integer Ring,
Dual of the Rank-3 free module M over the Integer Ring,
Dual of the Rank-3 free module M over the Integer Ring,
Dual of the Rank-3 free module M over the Integer Ring]
"""
tensor_type = self.tensor_type()
if tensor_type == (0,1): # case of the dual
raise NotImplementedError
bmodule = self.base_module()
factors = [bmodule] * tensor_type[0]
dmodule = bmodule.dual()
if tensor_type[1]:
factors += [dmodule] * tensor_type[1]
return factors | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/tensor/modules/reflexive_module.py | 0.942009 | 0.820613 | reflexive_module.py | pypi |
from sage.algebras.iwahori_hecke_algebra import IwahoriHeckeAlgebra
from sage.combinat.sf.sf import SymmetricFunctions
from sage.misc.misc_c import prod
from sage.rings.rational_field import QQ
from sage.combinat.partition import Partitions
class NilCoxeterAlgebra(IwahoriHeckeAlgebra.T):
r"""
Construct the Nil-Coxeter algebra of given type.
This is the algebra
with generators `u_i` for every node `i` of the corresponding Dynkin
diagram. It has the usual braid relations (from the Weyl group) as well
as the quadratic relation `u_i^2 = 0`.
INPUT:
- ``W`` -- a Weyl group
OPTIONAL ARGUMENTS:
- ``base_ring`` -- a ring (default is the rational numbers)
- ``prefix`` -- a label for the generators (default "u")
EXAMPLES::
sage: U = NilCoxeterAlgebra(WeylGroup(['A',3,1]))
sage: u0, u1, u2, u3 = U.algebra_generators()
sage: u1*u1
0
sage: u2*u1*u2 == u1*u2*u1
True
sage: U.an_element()
u[0,1,2,3] + 2*u[0] + 3*u[1] + 1
"""
def __init__(self, W, base_ring=QQ, prefix='u'):
r"""
Initiate the affine nil-Coxeter algebra corresponding to the Weyl
group `W` over the base ring.
EXAMPLES::
sage: U = NilCoxeterAlgebra(WeylGroup(['A',3,1])); U
The Nil-Coxeter Algebra of Type A3~ over Rational Field
sage: TestSuite(U).run()
sage: U = NilCoxeterAlgebra(WeylGroup(['C',3]), ZZ); U
The Nil-Coxeter Algebra of Type C3 over Integer Ring
sage: TestSuite(U).run()
"""
self._W = W
self._n = W.n
self._base_ring = base_ring
self._cartan_type = W.cartan_type()
H = IwahoriHeckeAlgebra(W, 0, 0, base_ring=base_ring)
super(IwahoriHeckeAlgebra.T, self).__init__(H, prefix=prefix)
def _repr_(self):
r"""
EXAMPLES::
sage: NilCoxeterAlgebra(WeylGroup(['A',3,1])) # indirect doctest
The Nil-Coxeter Algebra of Type A3~ over Rational Field
"""
return "The Nil-Coxeter Algebra of Type %s over %s" % (self._cartan_type._repr_(compact=True), self.base_ring())
def homogeneous_generator_noncommutative_variables(self, r):
r"""
Give the `r^{th}` homogeneous function inside the Nil-Coxeter algebra.
In finite type `A` this is the sum of all decreasing elements of length `r`.
In affine type `A` this is the sum of all cyclically decreasing elements of length `r`.
This is only defined in finite type `A`, `B` and affine types `A^{(1)}`, `B^{(1)}`, `C^{(1)}`, `D^{(1)}`.
INPUT:
- ``r`` -- a positive integer at most the rank of the Weyl group
EXAMPLES::
sage: U = NilCoxeterAlgebra(WeylGroup(['A',3,1]))
sage: U.homogeneous_generator_noncommutative_variables(2)
u[1,0] + u[2,0] + u[0,3] + u[3,2] + u[3,1] + u[2,1]
sage: U = NilCoxeterAlgebra(WeylGroup(['B',4]))
sage: U.homogeneous_generator_noncommutative_variables(2)
u[1,2] + u[2,1] + u[3,1] + u[4,1] + u[2,3] + u[3,2] + u[4,2] + u[3,4] + u[4,3]
sage: U = NilCoxeterAlgebra(WeylGroup(['C',3]))
sage: U.homogeneous_generator_noncommutative_variables(2)
Traceback (most recent call last):
...
AssertionError: Analogue of symmetric functions in noncommutative variables is not defined in type ['C', 3]
TESTS::
sage: U = NilCoxeterAlgebra(WeylGroup(['B',3,1]))
sage: U.homogeneous_generator_noncommutative_variables(-1)
0
sage: U.homogeneous_generator_noncommutative_variables(0)
1
"""
assert (len(self._cartan_type) == 2 and self._cartan_type[0] in ['A','B']) or (len(self._cartan_type) == 3 and self._cartan_type[2] == 1), "Analogue of symmetric functions in noncommutative variables is not defined in type %s"%(self._cartan_type)
if r >= self._n:
return self.zero()
return self.sum_of_monomials(w for w in self._W.pieri_factors() if w.length() == r)
def homogeneous_noncommutative_variables(self,la):
r"""
Give the homogeneous function indexed by `la`, viewed inside the Nil-Coxeter algebra.
This is only defined in finite type `A`, `B` and affine types `A^{(1)}`, `B^{(1)}`, `C^{(1)}`, `D^{(1)}`.
INPUT:
- ``la`` -- a partition with first part bounded by the rank of the Weyl group
EXAMPLES::
sage: U = NilCoxeterAlgebra(WeylGroup(['B',2,1]))
sage: U.homogeneous_noncommutative_variables([2,1])
u[1,2,0] + 2*u[2,1,0] + u[0,2,0] + u[0,2,1] + u[1,2,1] + u[2,1,2] + u[2,0,2] + u[1,0,2]
TESTS::
sage: U = NilCoxeterAlgebra(WeylGroup(['B',2,1]))
sage: U.homogeneous_noncommutative_variables([])
1
"""
return prod(self.homogeneous_generator_noncommutative_variables(p) for p in la)
def k_schur_noncommutative_variables(self, la):
r"""
In type `A^{(1)}` this is the `k`-Schur function in noncommutative variables
defined by Thomas Lam [Lam2005]_.
This function is currently only defined in type `A^{(1)}`.
INPUT:
- ``la`` -- a partition with first part bounded by the rank of the Weyl group
EXAMPLES::
sage: A = NilCoxeterAlgebra(WeylGroup(['A',3,1]))
sage: A.k_schur_noncommutative_variables([2,2])
u[0,3,1,0] + u[3,1,2,0] + u[1,2,0,1] + u[3,2,0,3] + u[2,0,3,1] + u[2,3,1,2]
TESTS::
sage: A = NilCoxeterAlgebra(WeylGroup(['A',3,1]))
sage: A.k_schur_noncommutative_variables([])
1
sage: A.k_schur_noncommutative_variables([1,2])
Traceback (most recent call last):
...
AssertionError: [1, 2] is not a partition.
sage: A.k_schur_noncommutative_variables([4,2])
Traceback (most recent call last):
...
AssertionError: [4, 2] is not a 3-bounded partition.
sage: C = NilCoxeterAlgebra(WeylGroup(['C',3,1]))
sage: C.k_schur_noncommutative_variables([2,2])
Traceback (most recent call last):
...
AssertionError: Weyl Group of type ['C', 3, 1] (as a matrix group acting on the root space) is not affine type A.
"""
assert self._cartan_type[0] == 'A' and len(self._cartan_type) == 3 and self._cartan_type[2] == 1, "%s is not affine type A."%(self._W)
assert la in Partitions(), "%s is not a partition."%(la)
assert (len(la) == 0 or la[0] < self._W.n), "%s is not a %s-bounded partition."%(la, self._W.n-1)
Sym = SymmetricFunctions(self._base_ring)
h = Sym.homogeneous()
ks = Sym.kschur(self._n-1,1)
f = h(ks[la])
return sum(f.coefficient(x)*self.homogeneous_noncommutative_variables(x) for x in f.support()) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/nil_coxeter_algebra.py | 0.881028 | 0.495484 | nil_coxeter_algebra.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.categories.magmatic_algebras import MagmaticAlgebras
from sage.categories.magmas import Magmas
from sage.categories.pushout import (ConstructionFunctor,
CompositeConstructionFunctor,
IdentityConstructionFunctor)
from sage.categories.coalgebras_with_basis import CoalgebrasWithBasis
from sage.categories.rings import Rings
from sage.categories.functor import Functor
from sage.categories.sets_cat import Sets
from sage.combinat.free_module import CombinatorialFreeModule
from sage.combinat.words.words import Words
from sage.combinat.words.alphabet import Alphabet
from sage.sets.family import Family
from sage.structure.coerce_exceptions import CoercionException
class FreeZinbielAlgebra(CombinatorialFreeModule):
r"""
The free Zinbiel algebra on `n` generators.
Let `R` be a ring. A *Zinbiel algebra* is a non-associative
algebra with multiplication `\circ` that satisfies
.. MATH::
(a \circ b) \circ c = a \circ (b \circ c) + a \circ (c \circ b).
Zinbiel algebras were first introduced by Loday (see [Lod1995]_ and
[LV2012]_) as the Koszul dual to Leibniz algebras (hence the name
coined by Lemaire).
By default, the convention above is used. The opposite product,
which satisfy the opposite axiom, can be used instead by setting
the ``side`` parameter to ``'>'`` instead of the default value ``'<'``.
Zinbiel algebras are divided power algebras, in that for
.. MATH::
x^{\circ n} = \bigl(x \circ (x \circ \cdots \circ( x \circ x) \cdots
) \bigr)
we have
.. MATH::
x^{\circ m} \circ x^{\circ n} = \binom{n+m-1}{m} x^{n+m}
and
.. MATH::
\underbrace{\bigl( ( x \circ \cdots \circ x \circ (x \circ x) \cdots
) \bigr)}_{n+1 \text{ times}} = n! x^n.
.. NOTE::
This implies that Zinbiel algebras are not power associative.
To every Zinbiel algebra, we can construct a corresponding commutative
associative algebra by using the symmetrized product:
.. MATH::
a * b = a \circ b + b \circ a.
The free Zinbiel algebra on `n` generators is isomorphic as `R`-modules
to the reduced tensor algebra `\bar{T}(R^n)` with the product
.. MATH::
(x_0 x_1 \cdots x_p) \circ (x_{p+1} x_{p+2} \cdots x_{p+q})
= \sum_{\sigma \in S_{p,q}} x_0 (x_{\sigma(1)} x_{\sigma(2)}
\cdots x_{\sigma(p+q)},
where `S_{p,q}` is the set of `(p,q)`-shuffles.
The free Zinbiel algebra is free as a divided power algebra. Moreover,
the corresponding commutative algebra is isomorphic to the (non-unital)
shuffle algebra.
INPUT:
- ``R`` -- a ring
- ``n`` -- (optional) the number of generators
- ``names`` -- the generator names
.. WARNING::
Currently the basis is indexed by all finite words over the variables,
including the empty word. This is a slight abuse as it is supposed
to be indexed by all non-empty words.
EXAMPLES:
We create the free Zinbiel algebra and check the defining relation::
sage: Z.<x,y,z> = algebras.FreeZinbiel(QQ)
sage: (x*y)*z
Z[xyz] + Z[xzy]
sage: x*(y*z) + x*(z*y)
Z[xyz] + Z[xzy]
We see that the Zinbiel algebra is not associative, not even
power associative::
sage: x*(y*z)
Z[xyz]
sage: x*(x*x)
Z[xxx]
sage: (x*x)*x
2*Z[xxx]
We verify that it is a divided power algebra::
sage: (x*(x*x)) * (x*(x*(x*x)))
15*Z[xxxxxxx]
sage: binomial(3+4-1,4)
15
sage: (x*(x*(x*x))) * (x*(x*x))
20*Z[xxxxxxx]
sage: binomial(3+4-1,3)
20
sage: ((x*x)*x)*x
6*Z[xxxx]
sage: (((x*x)*x)*x)*x
24*Z[xxxxx]
A few tests with the opposite convention for the product::
sage: Z.<x,y,z> = algebras.FreeZinbiel(QQ, side='>')
sage: (x*y)*z
Z[xyz]
sage: x*(y*z)
Z[xyz] + Z[yxz]
TESTS::
sage: Z.<x,y,z> = algebras.FreeZinbiel(QQ)
sage: Z.basis().keys()
Finite words over {'x', 'y', 'z'}
sage: A = algebras.FreeZinbiel(QQ,'z2,z3')
sage: x, y = A.gens()
sage: x*y
Z[z2,z3]
REFERENCES:
- :wikipedia:`Zinbiel_algebra`
- [Lod1995]_
- [LV2012]_
"""
@staticmethod
def __classcall_private__(cls, R, n=None, names=None,
prefix=None, side=None):
"""
Standardize input to ensure a unique representation.
TESTS::
sage: Z1.<x,y,z> = algebras.FreeZinbiel(QQ)
sage: Z2.<x,y,z> = algebras.FreeZinbiel(QQ, 3)
sage: Z3 = algebras.FreeZinbiel(QQ, 3, 'x,y,z')
sage: Z4.<x,y,z> = algebras.FreeZinbiel(QQ, 'x,y,z')
sage: Z1 is Z2 and Z1 is Z3 and Z1 is Z4
True
sage: algebras.FreeZinbiel(QQ, ['x', 'y'])
Free Zinbiel algebra on generators (Z[x], Z[y]) over Rational Field
sage: algebras.FreeZinbiel(QQ, ('x', 'y'))
Free Zinbiel algebra on generators (Z[x], Z[y]) over Rational Field
sage: Z = algebras.FreeZinbiel(QQ, ZZ)
"""
if isinstance(n, (list, tuple)):
names = n
n = len(names)
elif isinstance(n, str):
names = n.split(',')
n = len(names)
elif isinstance(names, str):
names = names.split(',')
elif n is None:
n = len(names)
if R not in Rings():
raise TypeError("argument R must be a ring")
if prefix is None:
prefix = 'Z'
if side is None:
side = '<'
if side not in ['<', '>']:
raise ValueError("side must be either '<' or '>'")
if names is None:
return super().__classcall__(cls, R, n, None, prefix, side)
return super().__classcall__(cls, R, n, tuple(names), prefix, side)
def __init__(self, R, n, names, prefix, side):
"""
Initialize ``self``.
EXAMPLES::
sage: Z.<x,y,z> = algebras.FreeZinbiel(QQ)
sage: TestSuite(Z).run()
sage: Z = algebras.FreeZinbiel(QQ, ZZ)
sage: G = Z.algebra_generators()
sage: TestSuite(Z).run(elements=[Z.an_element(), G[1], G[1]*G[2]*G[0]])
TESTS::
sage: Z.<x,y,z> = algebras.FreeZinbiel(5)
Traceback (most recent call last):
...
TypeError: argument R must be a ring
sage: algebras.FreeZinbiel(QQ, ['x', 'y'], prefix='f')
Free Zinbiel algebra on generators (f[x], f[y]) over Rational Field
"""
if R not in Rings():
raise TypeError("argument R must be a ring")
if names is None:
indices = Words(Alphabet(n), infinite=False)
self._n = None
else:
indices = Words(Alphabet(n, names=names), infinite=False)
self._n = n
self._side = side
if side == '<':
self.product_on_basis = self.product_on_basis_left
else:
self.product_on_basis = self.product_on_basis_right
cat = MagmaticAlgebras(R).WithBasis().Graded()
cat &= CoalgebrasWithBasis(R)
CombinatorialFreeModule.__init__(self, R, indices, prefix=prefix,
category=cat)
if self._n is not None:
self._assign_names(names)
def _repr_term(self, t):
"""
Return a string representation of the basis element indexed by ``t``.
EXAMPLES::
sage: Z.<x,y,z> = algebras.FreeZinbiel(QQ)
sage: Z._repr_term(Z._indices('xyzxxy'))
'Z[xyzxxy]'
"""
return "{!s}[{!s}]".format(self._print_options['prefix'], repr(t)[6:])
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: Z.<x,y> = algebras.FreeZinbiel(QQ)
sage: Z
Free Zinbiel algebra on generators (Z[x], Z[y]) over Rational Field
sage: Z = algebras.FreeZinbiel(QQ, ZZ)
sage: Z
Free Zinbiel algebra on generators indexed by Integer Ring over Rational Field
"""
if self._n is None:
return "Free Zinbiel algebra on generators indexed by {} over {}".format(
self._indices.alphabet(), self.base_ring())
return "Free Zinbiel algebra on generators {} over {}".format(
self.gens(), self.base_ring())
def side(self):
"""
Return the choice of side for the product.
This is either ``'<'`` or ``'>'``.
EXAMPLES::
sage: Z.<x,y,z> = algebras.FreeZinbiel(QQ)
sage: Z.side()
'<'
"""
return self._side
@cached_method
def algebra_generators(self):
"""
Return the algebra generators of ``self``.
EXAMPLES::
sage: Z.<x,y,z> = algebras.FreeZinbiel(QQ)
sage: list(Z.algebra_generators())
[Z[x], Z[y], Z[z]]
"""
if self._n is None:
A = self._indices.alphabet()
else:
A = self.variable_names()
return Family(A, lambda g: self.monomial(self._indices([g])))
def change_ring(self, R):
"""
Return the free Zinbiel algebra in the same variables over ``R``.
INPUT:
- ``R`` -- a ring
The same side convention is used for the product.
EXAMPLES::
sage: A = algebras.FreeZinbiel(ZZ, 'f,g,h')
sage: A.change_ring(QQ)
Free Zinbiel algebra on generators (Z[f], Z[g], Z[h])
over Rational Field
"""
A = self.variable_names()
return FreeZinbielAlgebra(R, n=len(A), names=A, side=self._side)
@cached_method
def gens(self):
"""
Return the generators of ``self``.
EXAMPLES::
sage: Z.<x,y,z> = algebras.FreeZinbiel(QQ)
sage: Z.gens()
(Z[x], Z[y], Z[z])
"""
if self._n is None:
return self.algebra_generators()
return tuple(self.algebra_generators())
def degree_on_basis(self, t):
"""
Return the degree of a word in the free Zinbiel algebra.
This is the length.
EXAMPLES::
sage: A = algebras.FreeZinbiel(QQ, 'x,y')
sage: W = A.basis().keys()
sage: A.degree_on_basis(W('xy'))
2
"""
return len(t)
def product_on_basis_left(self, x, y):
"""
Return the product < of the basis elements indexed by ``x`` and ``y``.
This is one half of the shuffle product, where the first letter
comes from the first letter of the first argument.
INPUT:
- ``x``, ``y`` -- two words
EXAMPLES::
sage: Z.<x,y,z> = algebras.FreeZinbiel(QQ)
sage: (x*y)*z # indirect doctest
Z[xyz] + Z[xzy]
TESTS::
sage: Z.<x,y> = algebras.FreeZinbiel(QQ)
sage: Z.product_on_basis(Word(), Word('y'))
Z[y]
"""
if not x:
return self.monomial(y)
x0 = self._indices([x[0]])
return self.sum_of_monomials(x0 + sh for sh in x[1:].shuffle(y))
def product_on_basis_right(self, x, y):
"""
Return the product > of the basis elements indexed by ``x`` and ``y``.
This is one half of the shuffle product, where the last letter
comes from the last letter of the second argument.
INPUT:
- ``x``, ``y`` -- two words
EXAMPLES::
sage: Z.<x,y,z> = algebras.FreeZinbiel(QQ, side='>')
sage: (x*y)*z # indirect doctest
Z[xyz]
TESTS::
sage: Z.<x,y> = algebras.FreeZinbiel(QQ, side='>')
sage: Z.product_on_basis(Word('x'), Word())
Z[x]
"""
if not y:
return self.monomial(x)
yf = self._indices([y[-1]])
return self.sum_of_monomials(sh + yf for sh in x.shuffle(y[:-1]))
def coproduct_on_basis(self, w):
"""
Return the coproduct of the element of the basis indexed by
the word ``w``.
The coproduct is given by deconcatenation.
INPUT:
- ``w`` -- a word
EXAMPLES::
sage: F = algebras.FreeZinbiel(QQ,['a','b'])
sage: F.coproduct_on_basis(Word('a'))
Z[] # Z[a] + Z[a] # Z[]
sage: F.coproduct_on_basis(Word('aba'))
Z[] # Z[aba] + Z[a] # Z[ba] + Z[ab] # Z[a] + Z[aba] # Z[]
sage: F.coproduct_on_basis(Word())
Z[] # Z[]
TESTS::
sage: F = algebras.FreeZinbiel(QQ,['a','b'])
sage: S = F.an_element(); S
Z[] + 2*Z[a] + 3*Z[b] + Z[bab]
sage: F.coproduct(S)
Z[] # Z[] + 2*Z[] # Z[a] + 3*Z[] # Z[b] + Z[] # Z[bab] +
2*Z[a] # Z[] + 3*Z[b] # Z[] + Z[b] # Z[ab] + Z[ba] # Z[b] +
Z[bab] # Z[]
"""
TS = self.tensor_square()
return TS.sum_of_monomials((w[:i], w[i:]) for i in range(len(w) + 1))
def counit(self, S):
"""
Return the counit of ``S``.
EXAMPLES::
sage: F = algebras.FreeZinbiel(QQ,['a','b'])
sage: S = F.an_element(); S
Z[] + 2*Z[a] + 3*Z[b] + Z[bab]
sage: F.counit(S)
1
"""
W = self.basis().keys()
return S.coefficient(W())
def _element_constructor_(self, x):
r"""
Convert ``x`` into ``self``.
EXAMPLES::
sage: R = algebras.FreeZinbiel(QQ, 'x,y')
sage: x, y = R.gens()
sage: R(x)
Z[x]
sage: R(x+4*y)
Z[x] + 4*Z[y]
sage: W = R.basis().keys()
sage: R(W('x'))
Z[x]
sage: D = algebras.FreeZinbiel(ZZ, 'x,y')
sage: X, Y = D.gens()
sage: R(X-Y).parent()
Free Zinbiel algebra on generators (Z[x], Z[y]) over Rational Field
TESTS::
sage: R.<x,y> = algebras.FreeZinbiel(QQ)
sage: S.<z> = algebras.FreeZinbiel(GF(3))
sage: R(z)
Traceback (most recent call last):
...
TypeError: not able to convert this to this algebra
"""
if x in self.basis().keys():
return self.monomial(x)
try:
P = x.parent()
except AttributeError:
raise TypeError('not able to convert this to this algebra')
if isinstance(P, FreeZinbielAlgebra) and self._coerce_map_from_(P):
if self._side == P._side:
return self.element_class(self,
x.monomial_coefficients(copy=False))
else:
dic = x.monomial_coefficients(copy=False)
# canonical isomorphism when switching side
return self.element_class(self,
{w.reversal(): cf
for w, cf in dic.items()})
else:
raise TypeError('not able to convert this to this algebra')
# Ok, not a Zinbiel algebra element (or should not be viewed as one).
def _coerce_map_from_(self, R):
r"""
Return ``True`` if there is a coercion from ``R`` into ``self``
and ``False`` otherwise.
The things that coerce into ``self`` are
- free Zinbiel algebras whose set `E` of labels is
a subset of the corresponding self of ``set`, and whose base
ring has a coercion map into ``self.base_ring()``
EXAMPLES::
sage: F = algebras.FreeZinbiel(GF(7), 'x,y,z'); F
Free Zinbiel algebra on generators (Z[x], Z[y], Z[z])
over Finite Field of size 7
Elements of the free Zinbiel algebra canonically coerce in::
sage: x, y, z = F.gens()
sage: F.coerce(x+y) == x+y
True
The free Zinbiel algebra over `\ZZ` on `x, y, z` coerces in, since
`\ZZ` coerces to `\GF{7}`::
sage: G = algebras.FreeZinbiel(ZZ, 'x,y,z')
sage: Gx,Gy,Gz = G.gens()
sage: z = F.coerce(Gx+Gy); z
Z[x] + Z[y]
sage: z.parent() is F
True
However, `\GF{7}` does not coerce to `\ZZ`, so the free Zinbiel
algebra over `\GF{7}` does not coerce to the one over `\ZZ`::
sage: G.coerce(y)
Traceback (most recent call last):
...
TypeError: no canonical coercion from Free Zinbiel algebra on
generators (Z[x], Z[y], Z[z]) over Finite Field of size 7 to
Free Zinbiel algebra on generators (Z[x], Z[y], Z[z])
over Integer Ring
TESTS::
sage: F = algebras.FreeZinbiel(ZZ, 'x,y,z')
sage: G = algebras.FreeZinbiel(QQ, 'x,y,z')
sage: H = algebras.FreeZinbiel(ZZ, 'y')
sage: F._coerce_map_from_(G)
False
sage: G._coerce_map_from_(F)
True
sage: F._coerce_map_from_(H)
True
sage: F._coerce_map_from_(QQ) is None
True
sage: G._coerce_map_from_(QQ) is None
True
sage: F.has_coerce_map_from(PolynomialRing(ZZ, 3, 'x,y,z'))
False
sage: I = algebras.FreeZinbiel(ZZ, ZZ)
sage: F._coerce_map_from_(I)
False
sage: I._coerce_map_from_(F)
False
"""
# free Zinbiel algebras in a subset of variables
# over any base that coerces in:
if isinstance(R, FreeZinbielAlgebra):
if self._n is None or R._n is None:
return False
return (all(x in self.variable_names()
for x in R.variable_names()) and
self.base_ring().has_coerce_map_from(R.base_ring()))
return super()._coerce_map_from_(R)
def construction(self):
"""
Return a pair ``(F, R)``, where ``F`` is a :class:`ZinbielFunctor`
and ``R`` is a ring, such that ``F(R)`` returns ``self``.
EXAMPLES::
sage: P = algebras.FreeZinbiel(ZZ, 'x,y')
sage: x,y = P.gens()
sage: F, R = P.construction()
sage: F
Zinbiel[x,y]
sage: R
Integer Ring
sage: F(ZZ) is P
True
sage: F(QQ)
Free Zinbiel algebra on generators (Z[x], Z[y]) over Rational Field
"""
if self._n is None:
A = self._indices.alphabet()
else:
A = self.variable_names()
return ZinbielFunctor(A, side=self._side), self.base_ring()
class ZinbielFunctor(ConstructionFunctor):
"""
A constructor for free Zinbiel algebras.
EXAMPLES::
sage: P = algebras.FreeZinbiel(ZZ, 'x,y')
sage: x,y = P.gens()
sage: F = P.construction()[0]; F
Zinbiel[x,y]
sage: A = GF(5)['a,b']
sage: a, b = A.gens()
sage: F(A)
Free Zinbiel algebra on generators (Z[x], Z[y])
over Multivariate Polynomial Ring in a, b over Finite Field of size 5
sage: f = A.hom([a+b,a-b],A)
sage: F(f)
Generic endomorphism of Free Zinbiel algebra on generators (Z[x], Z[y])
over Multivariate Polynomial Ring in a, b over Finite Field of size 5
sage: F(f)(a * F(A)(x))
(a+b)*Z[x]
"""
rank = 9
def __init__(self, variables, side):
"""
EXAMPLES::
sage: functor = sage.algebras.free_zinbiel_algebra.ZinbielFunctor
sage: F = functor(['x','y'], '<'); F
Zinbiel[x,y]
sage: F(ZZ)
Free Zinbiel algebra on generators (Z[x], Z[y]) over Integer Ring
"""
Functor.__init__(self, Rings(), Magmas())
self.vars = variables
self._side = side
self._finite_vars = bool(isinstance(variables, (list, tuple)) or variables in Sets().Finite())
def _apply_functor(self, R):
"""
Apply the functor to an object of ``self``'s domain.
EXAMPLES::
sage: R = algebras.FreeZinbiel(ZZ, 'x,y,z')
sage: F = R.construction()[0]; F
Zinbiel[x,y,z]
sage: type(F)
<class 'sage.algebras.free_zinbiel_algebra.ZinbielFunctor'>
sage: F(ZZ) # indirect doctest
Free Zinbiel algebra on generators (Z[x], Z[y], Z[z])
over Integer Ring
sage: R = algebras.FreeZinbiel(QQ, ZZ)
sage: F = R.construction()[0]; F
Zinbiel[Integer Ring]
sage: F(ZZ) # indirect doctest
Free Zinbiel algebra on generators indexed by Integer Ring over Integer Ring
"""
if self._finite_vars:
return FreeZinbielAlgebra(R, len(self.vars), self.vars,
side=self._side)
return FreeZinbielAlgebra(R, self.vars, side=self._side)
def _apply_functor_to_morphism(self, f):
"""
Apply the functor ``self`` to the ring morphism `f`.
TESTS::
sage: R = algebras.FreeZinbiel(ZZ, 'x').construction()[0]
sage: R(ZZ.hom(GF(3))) # indirect doctest
Generic morphism:
From: Free Zinbiel algebra on generators (Z[x],)
over Integer Ring
To: Free Zinbiel algebra on generators (Z[x],)
over Finite Field of size 3
"""
dom = self(f.domain())
codom = self(f.codomain())
def action(x):
return codom._from_dict({a: f(b)
for a, b in x.monomial_coefficients(copy=False).items()})
return dom.module_morphism(function=action, codomain=codom)
def __eq__(self, other):
"""
EXAMPLES::
sage: F = algebras.FreeZinbiel(ZZ, 'x,y,z').construction()[0]
sage: G = algebras.FreeZinbiel(QQ, 'x,y,z').construction()[0]
sage: F == G
True
sage: G == loads(dumps(G))
True
sage: G = algebras.FreeZinbiel(QQ, 'x,y').construction()[0]
sage: F == G
False
"""
if not isinstance(other, ZinbielFunctor):
return False
return self.vars == other.vars and self._side == other._side
def __hash__(self):
"""
Return the hash of ``self``.
EXAMPLES::
sage: F = algebras.FreeZinbiel(ZZ, 'x,y,z').construction()[0]
sage: G = algebras.FreeZinbiel(QQ, 'x,y,z').construction()[0]
sage: hash(F) == hash(G)
True
"""
return hash(repr(self))
def __mul__(self, other):
"""
If two Zinbiel functors are given in a row, form a single
Zinbiel functor with all of the variables.
EXAMPLES::
sage: from sage.algebras.free_zinbiel_algebra import ZinbielFunctor as functor
sage: F = functor(['x','y'], '<')
sage: G = functor(['t'], '<')
sage: G * F
Zinbiel[x,y,t]
With an infinite generating set::
sage: H = functor(ZZ, '<')
sage: H * G
Traceback (most recent call last):
...
CoercionException: Unable to determine overlap for infinite sets
sage: G * H
Traceback (most recent call last):
...
CoercionException: Unable to determine overlap for infinite sets
"""
if isinstance(other, IdentityConstructionFunctor):
return self
if isinstance(other, ZinbielFunctor):
if self._side != other._side:
raise CoercionException("detection of distinct sides")
if not self._finite_vars or not other._finite_vars:
raise CoercionException("Unable to determine overlap for infinite sets")
if set(self.vars).intersection(other.vars):
raise CoercionException("Overlapping variables (%s,%s)" %
(self.vars, other.vars))
return ZinbielFunctor(other.vars + self.vars, self._side)
elif (isinstance(other, CompositeConstructionFunctor) and
isinstance(other.all[-1], ZinbielFunctor)):
return CompositeConstructionFunctor(other.all[:-1],
self * other.all[-1])
else:
return CompositeConstructionFunctor(other, self)
def merge(self, other):
"""
Merge ``self`` with another construction functor, or return ``None``.
EXAMPLES::
sage: functor = sage.algebras.free_zinbiel_algebra.ZinbielFunctor
sage: F = functor(['x','y'], '<')
sage: G = functor(['t'], '<')
sage: F.merge(G)
Zinbiel[x,y,t]
sage: F.merge(F)
Zinbiel[x,y]
With an infinite generating set::
sage: H = functor(ZZ, '<')
sage: H.merge(H) is H
True
sage: H.merge(F) is None
True
sage: F.merge(H) is None
True
Now some actual use cases::
sage: R = algebras.FreeZinbiel(ZZ, 'x,y,z')
sage: x,y,z = R.gens()
sage: 1/2 * x
1/2*Z[x]
sage: parent(1/2 * x)
Free Zinbiel algebra on generators (Z[x], Z[y], Z[z])
over Rational Field
sage: S = algebras.FreeZinbiel(QQ, 'z,t')
sage: z,t = S.gens()
sage: x * t
Z[xt]
sage: parent(x * t)
Free Zinbiel algebra on generators (Z[z], Z[t], Z[x], Z[y])
over Rational Field
TESTS:
Using the other side convention::
sage: F = functor(['x','y'], '>')
sage: G = functor(['t'], '>')
sage: H = functor(['t'], '<')
sage: F.merge(G)
Zinbiel[x,y,t]
sage: F.merge(H)
Traceback (most recent call last):
...
TypeError: cannot merge free Zinbiel algebras with distinct sides
"""
if isinstance(other, ZinbielFunctor):
if self._side != other._side:
raise TypeError('cannot merge free Zinbiel algebras '
'with distinct sides')
if self.vars == other.vars:
return self
def check(x):
return isinstance(x, (list, tuple)) or x in Sets().Finite()
if not check(self.vars) or not check(other.vars):
return None
ret = list(self.vars)
cur_vars = set(ret)
for v in other.vars:
if v not in cur_vars:
ret.append(v)
return ZinbielFunctor(ret, self._side)
else:
return None
def _repr_(self):
"""
TESTS::
sage: algebras.FreeZinbiel(QQ,'x,y,z,t').construction()[0]
Zinbiel[x,y,z,t]
sage: algebras.FreeZinbiel(QQ, ZZ).construction()[0]
Zinbiel[Integer Ring]
"""
if self._finite_vars:
return "Zinbiel[%s]" % ','.join(self.vars)
return "Zinbiel[{}]".format(self.vars) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/free_zinbiel_algebra.py | 0.85738 | 0.521349 | free_zinbiel_algebra.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.rings.polynomial.laurent_polynomial_ring import LaurentPolynomialRing
from sage.rings.rational_field import QQ
from sage.categories.algebras import Algebras
from sage.categories.rings import Rings
from sage.combinat.free_module import CombinatorialFreeModule
from sage.combinat.permutation import Permutations
from sage.sets.family import Family
class YokonumaHeckeAlgebra(CombinatorialFreeModule):
r"""
The Yokonuma-Hecke algebra `Y_{d,n}(q)`.
Let `R` be a commutative ring and `q` be a unit in `R`. The
*Yokonuma-Hecke algebra* `Y_{d,n}(q)` is the associative, unital
`R`-algebra generated by `t_1, t_2, \ldots, t_n, g_1, g_2, \ldots,
g_{n-1}` and subject to the relations:
- `g_i g_j = g_j g_i` for all `|i - j| > 1`,
- `g_i g_{i+1} g_i = g_{i+1} g_i g_{i+1}`,
- `t_i t_j = t_j t_i`,
- `t_j g_i = g_i t_{j s_i}`, and
- `t_j^d = 1`,
where `s_i` is the simple transposition `(i, i+1)`, along with
the quadratic relation
.. MATH::
g_i^2 = 1 + \frac{(q - q^{-1})}{d} \left( \sum_{s=0}^{d-1}
t_i^s t_{i+1}^{-s} \right) g_i.
Thus the Yokonuma-Hecke algebra can be considered a quotient of
the framed braid group `(\ZZ / d\ZZ) \wr B_n`, where `B_n` is the
classical braid group on `n` strands, by the quadratic relations.
Moreover, all of the algebra generators are invertible. In
particular, we have
.. MATH::
g_i^{-1} = g_i - (q - q^{-1}) e_i.
When we specialize `q = \pm 1`, we obtain the group algebra of
the complex reflection group `G(d, 1, n) = (\ZZ / d\ZZ) \wr S_n`.
Moreover for `d = 1`, the Yokonuma-Hecke algebra is equal to the
:class:`Iwahori-Hecke <IwahoriHeckeAlgebra>` of type `A_{n-1}`.
INPUT:
- ``d`` -- the maximum power of `t`
- ``n`` -- the number of generators
- ``q`` -- (optional) an invertible element in a commutative ring;
the default is `q \in \QQ[q,q^{-1}]`
- ``R`` -- (optional) a commutative ring containing ``q``; the
default is the parent of `q`
EXAMPLES:
We construct `Y_{4,3}` and do some computations::
sage: Y = algebras.YokonumaHecke(4, 3)
sage: g1, g2, t1, t2, t3 = Y.algebra_generators()
sage: g1 * g2
g[1,2]
sage: t1 * g1
t1*g[1]
sage: g2 * t2
t3*g[2]
sage: g2 * t3
t2*g[2]
sage: (g2 + t1) * (g1 + t2*t3)
g[2,1] + t2*t3*g[2] + t1*g[1] + t1*t2*t3
sage: g1 * g1
1 - (1/4*q^-1-1/4*q)*g[1] - (1/4*q^-1-1/4*q)*t1*t2^3*g[1]
- (1/4*q^-1-1/4*q)*t1^2*t2^2*g[1] - (1/4*q^-1-1/4*q)*t1^3*t2*g[1]
sage: g2 * g1 * t1
t3*g[2,1]
We construct the elements `e_i` and show that they are idempotents::
sage: e1 = Y.e(1); e1
1/4 + 1/4*t1*t2^3 + 1/4*t1^2*t2^2 + 1/4*t1^3*t2
sage: e1 * e1 == e1
True
sage: e2 = Y.e(2); e2
1/4 + 1/4*t2*t3^3 + 1/4*t2^2*t3^2 + 1/4*t2^3*t3
sage: e2 * e2 == e2
True
REFERENCES:
- [CL2013]_
- [CPdA2014]_
- [ERH2015]_
- [JPdA15]_
"""
@staticmethod
def __classcall_private__(cls, d, n, q=None, R=None):
"""
Standardize input to ensure a unique representation.
TESTS::
sage: Y1 = algebras.YokonumaHecke(5, 3)
sage: q = LaurentPolynomialRing(QQ, 'q').gen()
sage: Y2 = algebras.YokonumaHecke(5, 3, q)
sage: Y3 = algebras.YokonumaHecke(5, 3, q, q.parent())
sage: Y1 is Y2 and Y2 is Y3
True
"""
if q is None:
q = LaurentPolynomialRing(QQ, 'q').gen()
if R is None:
R = q.parent()
q = R(q)
if R not in Rings().Commutative():
raise TypeError("base ring must be a commutative ring")
return super().__classcall__(cls, d, n, q, R)
def __init__(self, d, n, q, R):
"""
Initialize ``self``.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(5, 3)
sage: elts = Y.some_elements() + list(Y.algebra_generators())
sage: TestSuite(Y).run(elements=elts)
"""
self._d = d
self._n = n
self._q = q
self._Pn = Permutations(n)
import itertools
C = itertools.product(*([range(d)]*n))
indices = list(itertools.product(C, self._Pn))
cat = Algebras(R).WithBasis()
CombinatorialFreeModule.__init__(self, R, indices, prefix='Y',
category=cat)
self._assign_names(self.algebra_generators().keys())
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: algebras.YokonumaHecke(5, 2)
Yokonuma-Hecke algebra of rank 5 and order 2 with q=q
over Univariate Laurent Polynomial Ring in q over Rational Field
"""
return "Yokonuma-Hecke algebra of rank {} and order {} with q={} over {}".format(
self._d, self._n, self._q, self.base_ring())
def _latex_(self):
r"""
Return a latex representation of ``self``.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(5, 2)
sage: latex(Y)
\mathcal{Y}_{5,2}(q)
"""
return "\\mathcal{Y}_{%s,%s}(%s)"%(self._d, self._n, self._q)
def _repr_term(self, m):
"""
Return a string representation of the basis element indexed by ``m``.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(4, 3)
sage: Y._repr_term( ((1, 0, 2), Permutation([3,2,1])) )
't1*t3^2*g[2,1,2]'
"""
gen_str = lambda e: '' if e == 1 else '^%s'%e
lhs = '*'.join('t%s'%(j+1) + gen_str(i) for j,i in enumerate(m[0]) if i > 0)
redword = m[1].reduced_word()
if not redword:
if not lhs:
return '1'
return lhs
rhs = 'g[{}]'.format(','.join(str(i) for i in redword))
if not lhs:
return rhs
return lhs + '*' + rhs
def _latex_term(self, m):
r"""
Return a latex representation for the basis element indexed by ``m``.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(4, 3)
sage: Y._latex_term( ((1, 0, 2), Permutation([3,2,1])) )
't_{1} t_{3}^2 g_{2} g_{1} g_{2}'
"""
gen_str = lambda e: '' if e == 1 else '^%s'%e
lhs = ' '.join('t_{%s}'%(j+1) + gen_str(i) for j,i in enumerate(m[0]) if i > 0)
redword = m[1].reduced_word()
if not redword:
if not lhs:
return '1'
return lhs
return lhs + ' ' + ' '.join("g_{%d}"%i for i in redword)
@cached_method
def algebra_generators(self):
"""
Return the algebra generators of ``self``.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(5, 3)
sage: dict(Y.algebra_generators())
{'g1': g[1], 'g2': g[2], 't1': t1, 't2': t2, 't3': t3}
"""
one = self._Pn.one()
zero = [0]*self._n
d = {}
for i in range(self._n):
r = list(zero) # Make a copy
r[i] = 1
d['t%s'%(i+1)] = self.monomial( (tuple(r), one) )
G = self._Pn.group_generators()
for i in range(1, self._n):
d['g%s'%i] = self.monomial( (tuple(zero), G[i]) )
return Family(sorted(d), lambda i: d[i])
@cached_method
def gens(self):
"""
Return the generators of ``self``.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(5, 3)
sage: Y.gens()
(g[1], g[2], t1, t2, t3)
"""
return tuple(self.algebra_generators())
@cached_method
def one_basis(self):
"""
Return the index of the basis element of `1`.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(5, 3)
sage: Y.one_basis()
((0, 0, 0), [1, 2, 3])
"""
one = self._Pn.one()
zero = [0]*self._n
return (tuple(zero), one)
@cached_method
def e(self, i):
"""
Return the element `e_i`.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(4, 3)
sage: Y.e(1)
1/4 + 1/4*t1*t2^3 + 1/4*t1^2*t2^2 + 1/4*t1^3*t2
sage: Y.e(2)
1/4 + 1/4*t2*t3^3 + 1/4*t2^2*t3^2 + 1/4*t2^3*t3
"""
if i < 1 or i >= self._n:
raise ValueError("invalid index")
c = ~self.base_ring()(self._d)
zero = [0]*self._n
one = self._Pn.one()
d = {}
for s in range(self._d):
r = list(zero) # Make a copy
r[i-1] = s
if s != 0:
r[i] = self._d - s
d[(tuple(r), one)] = c
return self._from_dict(d, remove_zeros=False)
def g(self, i=None):
"""
Return the generator(s) `g_i`.
INPUT:
- ``i`` -- (default: ``None``) the generator `g_i` or if ``None``,
then the list of all generators `g_i`
EXAMPLES::
sage: Y = algebras.YokonumaHecke(8, 3)
sage: Y.g(1)
g[1]
sage: Y.g()
[g[1], g[2]]
"""
G = self.algebra_generators()
if i is None:
return [G['g%s'%i] for i in range(1, self._n)]
return G['g%s'%i]
def t(self, i=None):
"""
Return the generator(s) `t_i`.
INPUT:
- ``i`` -- (default: ``None``) the generator `t_i` or if ``None``,
then the list of all generators `t_i`
EXAMPLES::
sage: Y = algebras.YokonumaHecke(8, 3)
sage: Y.t(2)
t2
sage: Y.t()
[t1, t2, t3]
"""
G = self.algebra_generators()
if i is None:
return [G['t%s'%i] for i in range(1, self._n+1)]
return G['t%s'%i]
def product_on_basis(self, m1, m2):
"""
Return the product of the basis elements indexed by ``m1`` and ``m2``.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(4, 3)
sage: m = ((1, 0, 2), Permutations(3)([2,1,3]))
sage: 4 * Y.product_on_basis(m, m)
-(q^-1-q)*t2^2*g[1] + 4*t1*t2 - (q^-1-q)*t1*t2*g[1]
- (q^-1-q)*t1^2*g[1] - (q^-1-q)*t1^3*t2^3*g[1]
Check that we apply the permutation correctly on `t_i`::
sage: Y = algebras.YokonumaHecke(4, 3)
sage: g1, g2, t1, t2, t3 = Y.algebra_generators()
sage: g21 = g2 * g1
sage: g21 * t1
t3*g[2,1]
"""
t1,g1 = m1
t2,g2 = m2
# Commute g1 and t2, then multiply t1 and t2
# ig1 = g1
t = [(t1[i] + t2[g1.index(i+1)]) % self._d for i in range(self._n)]
one = self._Pn.one()
if g1 == one:
return self.monomial((tuple(t), g2))
ret = self.monomial((tuple(t), g1))
# We have to reverse the reduced word due to Sage's convention
# for permutation multiplication
for i in g2.reduced_word():
ret = self.linear_combination((self._product_by_basis_gen(m, i), c)
for m,c in ret)
return ret
def _product_by_basis_gen(self, m, i):
r"""
Return the product `t g_w g_i`.
If the quadratic relation is `g_i^2 = 1 + (q + q^{-1})e_i g_i`,
then we have
.. MATH::
g_w g_i = \begin{cases}
g_{ws_i} & \text{if } \ell(ws_i) = \ell(w) + 1, \\
g_{ws_i} - (q - q^{-1}) g_w e_i & \text{if }
\ell(w s_i) = \ell(w) - 1.
\end{cases}
INPUT:
- ``m`` -- a pair ``[t, w]``, where ``t`` encodes the monomial
and ``w`` is an element of the permutation group
- ``i`` -- an element of the index set
EXAMPLES::
sage: Y = algebras.YokonumaHecke(4, 3)
sage: m = ((1, 0, 2), Permutations(3)([2,1,3]))
sage: 4 * Y._product_by_basis_gen(m, 1)
-(q^-1-q)*t2*t3^2*g[1] + 4*t1*t3^2 - (q^-1-q)*t1*t3^2*g[1]
- (q^-1-q)*t1^2*t2^3*t3^2*g[1] - (q^-1-q)*t1^3*t2^2*t3^2*g[1]
"""
t, w = m
wi = w.apply_simple_reflection(i, side="right")
if not w.has_descent(i, side="right"):
return self.monomial((t, wi))
R = self.base_ring()
c = (self._q - ~self._q) * ~R(self._d)
d = {(t, wi): R.one()}
# We commute g_w and e_i and then multiply by t
for s in range(self._d):
r = list(t)
r[w[i-1]-1] = (r[w[i-1]-1] + s) % self._d
if s != 0:
r[w[i]-1] = (r[w[i]-1] + self._d - s) % self._d
d[(tuple(r), w)] = c
return self._from_dict(d, remove_zeros=False)
@cached_method
def inverse_g(self, i):
r"""
Return the inverse of the generator `g_i`.
From the quadratic relation, we have
.. MATH::
g_i^{-1} = g_i - (q - q^{-1}) e_i.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(2, 4)
sage: [2*Y.inverse_g(i) for i in range(1, 4)]
[(q^-1+q) + 2*g[1] + (q^-1+q)*t1*t2,
(q^-1+q) + 2*g[2] + (q^-1+q)*t2*t3,
(q^-1+q) + 2*g[3] + (q^-1+q)*t3*t4]
"""
if i < 1 or i >= self._n:
raise ValueError("invalid index")
return self.g(i) + (~self._q + self._q) * self.e(i)
class Element(CombinatorialFreeModule.Element):
def __invert__(self):
r"""
Return the inverse if ``self`` is a basis element.
EXAMPLES::
sage: Y = algebras.YokonumaHecke(3, 3)
sage: t = prod(Y.t()); t
t1*t2*t3
sage: t.inverse() # indirect doctest
t1^2*t2^2*t3^2
sage: [3*~(t*g) for g in Y.g()]
[(q^-1+q)*t2*t3^2 + (q^-1+q)*t1*t3^2
+ (q^-1+q)*t1^2*t2^2*t3^2 + 3*t1^2*t2^2*t3^2*g[1],
(q^-1+q)*t1^2*t3 + (q^-1+q)*t1^2*t2
+ (q^-1+q)*t1^2*t2^2*t3^2 + 3*t1^2*t2^2*t3^2*g[2]]
TESTS:
Check that :trac:`26424` is fixed::
sage: Y = algebras.YokonumaHecke(3, 3)
sage: t = 3 * prod(Y.t())
sage: ~t
1/3*t1^2*t2^2*t3^2
sage: ~Y.zero()
Traceback (most recent call last):
...
ZeroDivisionError
"""
if not self:
raise ZeroDivisionError
if len(self) != 1:
raise NotImplementedError("inverse only implemented for basis elements (monomials in the generators)"%self)
H = self.parent()
t,w = self.support_of_term()
c = ~self.coefficients()[0]
telt = H.monomial( (tuple((H._d - e) % H._d for e in t), H._Pn.one()) )
return c * telt * H.prod(H.inverse_g(i) for i in reversed(w.reduced_word())) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/yokonuma_hecke_algebra.py | 0.917006 | 0.697301 | yokonuma_hecke_algebra.py | pypi |
from sage.misc.repr import repr_lincomb
from sage.structure.element import RingElement, AlgebraElement
from sage.structure.parent_gens import localvars
from sage.structure.richcmp import richcmp
from sage.rings.integer import Integer
from sage.modules.free_module_element import FreeModuleElement
from sage.monoids.free_monoid_element import FreeMonoidElement
from sage.algebras.free_algebra_element import FreeAlgebraElement
def is_FreeAlgebraQuotientElement(x):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: sage.algebras.free_algebra_quotient_element.is_FreeAlgebraQuotientElement(i)
True
Of course this is testing the data type::
sage: sage.algebras.free_algebra_quotient_element.is_FreeAlgebraQuotientElement(1)
False
sage: sage.algebras.free_algebra_quotient_element.is_FreeAlgebraQuotientElement(H(1))
True
"""
return isinstance(x, FreeAlgebraQuotientElement)
class FreeAlgebraQuotientElement(AlgebraElement):
def __init__(self, A, x):
"""
Create the element x of the FreeAlgebraQuotient A.
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(ZZ)
sage: sage.algebras.free_algebra_quotient.FreeAlgebraQuotientElement(H, i)
i
sage: a = sage.algebras.free_algebra_quotient.FreeAlgebraQuotientElement(H, 1); a
1
sage: a in H
True
TESTS::
sage: TestSuite(i).run()
"""
AlgebraElement.__init__(self, A)
Q = self.parent()
if isinstance(x, FreeAlgebraQuotientElement) and x.parent() == Q:
self.__vector = Q.module()(x.vector())
return
if isinstance(x, (Integer, int)):
self.__vector = Q.module().gen(0) * x
return
elif isinstance(x, FreeModuleElement) and x.parent() is Q.module():
self.__vector = x
return
elif isinstance(x, FreeModuleElement) and x.parent() == A.module():
self.__vector = x
return
R = A.base_ring()
M = A.module()
F = A.monoid()
B = A.monomial_basis()
if isinstance(x, (Integer, int)):
self.__vector = x*M.gen(0)
elif isinstance(x, RingElement) and not isinstance(x, AlgebraElement) and x in R:
self.__vector = x * M.gen(0)
elif isinstance(x, FreeMonoidElement) and x.parent() is F:
if x in B:
self.__vector = M.gen(B.index(x))
else:
raise AttributeError("argument x (= %s) is not in monomial basis" % x)
elif isinstance(x, list) and len(x) == A.dimension():
try:
self.__vector = M(x)
except TypeError:
raise TypeError("argument x (= %s) is of the wrong type" % x)
elif isinstance(x, FreeAlgebraElement) and x.parent() is A.free_algebra():
# Need to do more work here to include monomials not
# represented in the monomial basis.
self.__vector = M(0)
for m, c in x._FreeAlgebraElement__monomial_coefficients.items():
self.__vector += c*M.gen(B.index(m))
elif isinstance(x, dict):
self.__vector = M(0)
for m, c in x.items():
self.__vector += c*M.gen(B.index(m))
elif isinstance(x, AlgebraElement) and x.parent().ambient_algebra() is A:
self.__vector = x.ambient_algebra_element().vector()
else:
raise TypeError("argument x (= %s) is of the wrong type" % x)
def _repr_(self):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(ZZ)
sage: i._repr_()
'i'
"""
Q = self.parent()
M = Q.monoid()
with localvars(M, Q.variable_names()):
cffs = list(self.__vector)
mons = Q.monomial_basis()
return repr_lincomb(zip(mons, cffs), strip_one=True)
def _latex_(self):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: ((2/3)*i - j)._latex_()
'\\frac{2}{3} i - j'
"""
Q = self.parent()
M = Q.monoid()
with localvars(M, Q.variable_names()):
cffs = tuple(self.__vector)
mons = Q.monomial_basis()
return repr_lincomb(zip(mons, cffs), is_latex=True, strip_one=True)
def vector(self):
"""
Return underlying vector representation of this element.
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: ((2/3)*i - j).vector()
(0, 2/3, -1, 0)
"""
return self.__vector
def _richcmp_(self, right, op):
"""
Compare two quotient algebra elements; done by comparing the
underlying vector representatives.
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: i > j
True
sage: i == i
True
sage: i == 1
False
sage: i + j == j + i
True
"""
return richcmp(self.vector(), right.vector(), op)
def __neg__(self):
"""
Return negative of self.
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: -i
-i
sage: -(2/3*i - 3/7*j + k)
-2/3*i + 3/7*j - k
"""
y = self.parent()(0)
y.__vector = -self.__vector
return y
def _add_(self, y):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: 2/3*i + 4*j + k
2/3*i + 4*j + k
"""
A = self.parent()
z = A(0)
z.__vector = self.__vector + y.__vector
return z
def _sub_(self, y):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: 2/3*i - 4*j
2/3*i - 4*j
sage: a = 2/3*i - 4*j; a
2/3*i - 4*j
sage: a - a
0
"""
A = self.parent()
z = A(0)
z.__vector = self.__vector - y.__vector
return z
def _mul_(self, y):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: a = (5 + 2*i - 3/5*j + 17*k); a*(a+10)
-5459/25 + 40*i - 12*j + 340*k
Double check that the above is actually right::
sage: R.<i,j,k> = QuaternionAlgebra(QQ,-1,-1)
sage: a = (5 + 2*i - 3/5*j + 17*k); a*(a+10)
-5459/25 + 40*i - 12*j + 340*k
"""
A = self.parent()
def monomial_product(X, w, m):
mats = X._FreeAlgebraQuotient__matrix_action
for j, k in m._element_list:
M = mats[int(j)]
for _ in range(k):
w *= M
return w
u = self.__vector.__copy__()
v = y.__vector
z = A(0)
B = A.monomial_basis()
for i in range(A.dimension()):
c = v[i]
if c != 0:
z.__vector += monomial_product(A,c*u,B[i])
return z
def _rmul_(self, c):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: 3 * (-1+i-2*j+k)
-3 + 3*i - 6*j + 3*k
sage: (-1+i-2*j+k)._rmul_(3)
-3 + 3*i - 6*j + 3*k
"""
return self.parent([c*a for a in self.__vector])
def _lmul_(self, c):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: (-1+i-2*j+k) * 3
-3 + 3*i - 6*j + 3*k
sage: (-1+i-2*j+k)._lmul_(3)
-3 + 3*i - 6*j + 3*k
"""
return self.parent([a*c for a in self.__vector]) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/free_algebra_quotient_element.py | 0.780662 | 0.385519 | free_algebra_quotient_element.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.misc.lazy_attribute import lazy_attribute
from sage.categories.algebras import Algebras
from sage.combinat.free_module import CombinatorialFreeModule
from sage.combinat.root_system.cartan_type import CartanType
from sage.combinat.root_system.cartan_matrix import CartanMatrix
from sage.combinat.root_system.root_system import RootSystem
from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets
from sage.sets.family import Family
from sage.monoids.indexed_free_monoid import IndexedFreeAbelianMonoid
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.rational_field import QQ
class RationalCherednikAlgebra(CombinatorialFreeModule):
r"""
A rational Cherednik algebra.
Let `k` be a field. Let `W` be a complex reflection group acting on
a vector space `\mathfrak{h}` (over `k`). Let `\mathfrak{h}^*` denote
the corresponding dual vector space. Let `\cdot` denote the
natural action of `w` on `\mathfrak{h}` and `\mathfrak{h}^*`. Let
`\mathcal{S}` denote the set of reflections of `W` and `\alpha_s`
and `\alpha_s^{\vee}` are the associated root and coroot of `s`. Let
`c = (c_s)_{s \in W}` such that `c_s = c_{tst^{-1}}` for all `t \in W`.
The *rational Cherednik algebra* is the `k`-algebra
`H_{c,t}(W) = T(\mathfrak{h} \oplus \mathfrak{h}^*) \otimes kW` with
parameters `c, t \in k` that is subject to the relations:
.. MATH::
\begin{aligned}
w \alpha & = (w \cdot \alpha) w,
\\ \alpha^{\vee} w & = w (w^{-1} \cdot \alpha^{\vee}),
\\ \alpha \alpha^{\vee} & = \alpha^{\vee} \alpha
+ t \langle \alpha^{\vee}, \alpha \rangle
+ \sum_{s \in \mathcal{S}} c_s \frac{\langle \alpha^{\vee},
\alpha_s \rangle \langle \alpha^{\vee}_s, \alpha \rangle}{
\langle \alpha^{\vee}, \alpha \rangle} s,
\end{aligned}
where `w \in W` and `\alpha \in \mathfrak{h}` and
`\alpha^{\vee} \in \mathfrak{h}^*`.
INPUT:
- ``ct`` -- a finite Cartan type
- ``c`` -- the parameters `c_s` given as an element or a tuple, where
the first entry is the one for the long roots and (for
non-simply-laced types) the second is for the short roots
- ``t`` -- the parameter `t`
- ``base_ring`` -- (optional) the base ring
- ``prefix`` -- (default: ``('a', 's', 'ac')``) the prefixes
.. TODO::
Implement a version for complex reflection groups.
REFERENCES:
- [GGOR2003]_
- [EM2001]_
"""
@staticmethod
def __classcall_private__(cls, ct, c=1, t=None, base_ring=None, prefix=('a', 's', 'ac')):
"""
Normalize input to ensure a unique representation.
EXAMPLES::
sage: R1 = algebras.RationalCherednik(['B',2], 1, 1, QQ)
sage: R2 = algebras.RationalCherednik(CartanType(['B',2]), [1,1], 1, QQ, ('a', 's', 'ac'))
sage: R1 is R2
True
"""
ct = CartanType(ct)
if not ct.is_finite():
raise ValueError("the Cartan type must be finite")
if base_ring is None:
if t is None:
base_ring = QQ
else:
base_ring = t.parent()
if t is None:
t = base_ring.one()
else:
t = base_ring(t)
# Normalize the parameter c
if isinstance(c, (tuple, list)):
if ct.is_simply_laced():
if len(c) != 1:
raise ValueError("1 parameter c_s must be given for simply-laced types")
c = (base_ring(c[0]),)
else:
if len(c) != 2:
raise ValueError("2 parameters c_s must be given for non-simply-laced types")
c = (base_ring(c[0]), base_ring(c[1]))
else:
c = base_ring(c)
if ct.is_simply_laced():
c = (c,)
else:
c = (c, c)
return super().__classcall__(cls, ct, c, t, base_ring, tuple(prefix))
def __init__(self, ct, c, t, base_ring, prefix):
r"""
Initialize ``self``.
EXAMPLES::
sage: k = QQ['c,t']
sage: R = algebras.RationalCherednik(['A',2], k.gen(0), k.gen(1))
sage: TestSuite(R).run() # long time
"""
self._c = c
self._t = t
self._cartan_type = ct
self._weyl = RootSystem(ct).root_lattice().weyl_group(prefix=prefix[1])
self._hd = IndexedFreeAbelianMonoid(ct.index_set(), prefix=prefix[0],
bracket=False)
self._h = IndexedFreeAbelianMonoid(ct.index_set(), prefix=prefix[2],
bracket=False)
indices = DisjointUnionEnumeratedSets([self._hd, self._weyl, self._h])
CombinatorialFreeModule.__init__(self, base_ring, indices,
category=Algebras(base_ring).WithBasis().Graded(),
sorting_key=self._genkey)
def _genkey(self, t):
r"""
Construct a key for comparison for a term indexed by ``t``.
The key we create is the tuple in the following order:
- overall degree
- length of the Weyl group element
- the Weyl group element
- the element of `\mathfrak{h}`
- the element of `\mathfrak{h}^*`
EXAMPLES::
sage: R = algebras.RationalCherednik(['A',2], 1, 1, QQ)
sage: R.an_element()**2 # indirect doctest
9*ac1^2 + 10*I + 6*a1*ac1 + 6*s1 + 3/2*s2 + 3/2*s1*s2*s1 + a1^2
"""
return (self.degree_on_basis(t), t[1].length(), t[1], str(t[0]), str(t[2]))
@lazy_attribute
def _reflections(self):
"""
A dictionary of reflections to a pair of the associated root
and coroot.
EXAMPLES::
sage: R = algebras.RationalCherednik(['B',2], [1,2], 1, QQ)
sage: [R._reflections[k] for k in sorted(R._reflections, key=str)]
[(alpha[1], alphacheck[1], 1),
(alpha[1] + alpha[2], 2*alphacheck[1] + alphacheck[2], 2),
(alpha[2], alphacheck[2], 2),
(alpha[1] + 2*alpha[2], alphacheck[1] + alphacheck[2], 1)]
"""
d = {}
for r in RootSystem(self._cartan_type).root_lattice().positive_roots():
s = self._weyl.from_reduced_word(r.associated_reflection())
if r.is_short_root():
c = self._c[1]
else:
c = self._c[0]
d[s] = (r, r.associated_coroot(), c)
return d
def _repr_(self) -> str:
r"""
Return a string representation of ``self``.
EXAMPLES::
sage: RationalCherednikAlgebra(['A',4], 2, 1, QQ)
Rational Cherednik Algebra of type ['A', 4] with c=2 and t=1
over Rational Field
sage: algebras.RationalCherednik(['B',2], [1,2], 1, QQ)
Rational Cherednik Algebra of type ['B', 2] with c_L=1 and c_S=2
and t=1 over Rational Field
"""
ret = "Rational Cherednik Algebra of type {} with ".format(self._cartan_type)
if self._cartan_type.is_simply_laced():
ret += "c={}".format(self._c[0])
else:
ret += "c_L={} and c_S={}".format(*self._c)
return ret + " and t={} over {}".format(self._t, self.base_ring())
def _repr_term(self, t):
"""
Return a string representation of the term indexed by ``t``.
EXAMPLES::
sage: R = algebras.RationalCherednik(['A',2], 1, 1, QQ)
sage: R.an_element() # indirect doctest
3*ac1 + 2*s1 + a1
sage: R.one() # indirect doctest
I
"""
r = []
if t[0] != self._hd.one():
r.append(t[0])
if t[1] != self._weyl.one():
r.append(t[1])
if t[2] != self._h.one():
r.append(t[2])
if not r:
return 'I'
return '*'.join(repr(x) for x in r)
def algebra_generators(self):
"""
Return the algebra generators of ``self``.
EXAMPLES::
sage: R = algebras.RationalCherednik(['A',2], 1, 1, QQ)
sage: list(R.algebra_generators())
[a1, a2, s1, s2, ac1, ac2]
"""
keys = ['a'+str(i) for i in self._cartan_type.index_set()]
keys += ['s'+str(i) for i in self._cartan_type.index_set()]
keys += ['ac'+str(i) for i in self._cartan_type.index_set()]
def gen_map(k):
if k[0] == 's':
i = int(k[1:])
return self.monomial( (self._hd.one(),
self._weyl.group_generators()[i],
self._h.one()) )
if k[1] == 'c':
i = int(k[2:])
return self.monomial( (self._hd.one(),
self._weyl.one(),
self._h.monoid_generators()[i]) )
i = int(k[1:])
return self.monomial( (self._hd.monoid_generators()[i],
self._weyl.one(),
self._h.one()) )
return Family(keys, gen_map)
@cached_method
def one_basis(self):
"""
Return the index of the element `1`.
EXAMPLES::
sage: R = algebras.RationalCherednik(['A',2], 1, 1, QQ)
sage: R.one_basis()
(1, 1, 1)
"""
return (self._hd.one(), self._weyl.one(), self._h.one())
def product_on_basis(self, left, right):
r"""
Return ``left`` multiplied by ``right`` in ``self``.
EXAMPLES::
sage: R = algebras.RationalCherednik(['A',2], 1, 1, QQ)
sage: a2 = R.algebra_generators()['a2']
sage: ac1 = R.algebra_generators()['ac1']
sage: a2 * ac1 # indirect doctest
a2*ac1
sage: ac1 * a2
-I + a2*ac1 - s1 - s2 + 1/2*s1*s2*s1
sage: x = R.an_element()
sage: [y * x for y in R.some_elements()]
[0,
3*ac1 + 2*s1 + a1,
9*ac1^2 + 10*I + 6*a1*ac1 + 6*s1 + 3/2*s2 + 3/2*s1*s2*s1 + a1^2,
3*a1*ac1 + 2*a1*s1 + a1^2,
3*a2*ac1 + 2*a2*s1 + a1*a2,
3*s1*ac1 + 2*I - a1*s1,
3*s2*ac1 + 2*s2*s1 + a1*s2 + a2*s2,
3*ac1^2 - 2*s1*ac1 + 2*I + a1*ac1 + 2*s1 + 1/2*s2 + 1/2*s1*s2*s1,
3*ac1*ac2 + 2*s1*ac1 + 2*s1*ac2 - I + a1*ac2 - s1 - s2 + 1/2*s1*s2*s1]
sage: [x * y for y in R.some_elements()]
[0,
3*ac1 + 2*s1 + a1,
9*ac1^2 + 10*I + 6*a1*ac1 + 6*s1 + 3/2*s2 + 3/2*s1*s2*s1 + a1^2,
6*I + 3*a1*ac1 + 6*s1 + 3/2*s2 + 3/2*s1*s2*s1 - 2*a1*s1 + a1^2,
-3*I + 3*a2*ac1 - 3*s1 - 3*s2 + 3/2*s1*s2*s1 + 2*a1*s1 + 2*a2*s1 + a1*a2,
-3*s1*ac1 + 2*I + a1*s1,
3*s2*ac1 + 3*s2*ac2 + 2*s1*s2 + a1*s2,
3*ac1^2 + 2*s1*ac1 + a1*ac1,
3*ac1*ac2 + 2*s1*ac2 + a1*ac2]
"""
# Make copies of the internal dictionaries
dl = dict(left[2]._monomial)
dr = dict(right[0]._monomial)
# If there is nothing to commute
if not dl and not dr:
return self.monomial((left[0], left[1] * right[1], right[2]))
R = self.base_ring()
I = self._cartan_type.index_set()
P = PolynomialRing(R, 'x', len(I))
G = P.gens()
gens_dict = {a:G[i] for i,a in enumerate(I)}
Q = RootSystem(self._cartan_type).root_lattice()
alpha = Q.simple_roots()
alphacheck = Q.simple_coroots()
def commute_w_hd(w, al): # al is given as a dictionary
ret = P.one()
for k in al:
x = sum(c * gens_dict[i] for i,c in alpha[k].weyl_action(w))
ret *= x**al[k]
ret = ret.dict()
for k in ret:
yield (self._hd({I[i]: e for i,e in enumerate(k) if e != 0}), ret[k])
# Do Lac Ra if they are both non-trivial
if dl and dr:
il = next(iter(dl.keys()))
ir = next(iter(dr.keys()))
# Compute the commutator
terms = self._product_coroot_root(il, ir)
# remove the generator from the elements
dl[il] -= 1
if dl[il] == 0:
del dl[il]
dr[ir] -= 1
if dr[ir] == 0:
del dr[ir]
# We now commute right roots past the left reflections: s Ra = Ra' s
cur = self._from_dict({ (hd, s*right[1], right[2]): c * cc
for s,c in terms
for hd, cc in commute_w_hd(s, dr) })
cur = self.monomial( (left[0], left[1], self._h(dl)) ) * cur
# Add back in the commuted h and hd elements
rem = self.monomial( (left[0], left[1], self._h(dl)) )
rem = rem * self.monomial( (self._hd({ir:1}), self._weyl.one(),
self._h({il:1})) )
rem = rem * self.monomial( (self._hd(dr), right[1], right[2]) )
return cur + rem
if dl:
# We have La Ls Lac Rs Rac,
# so we must commute Lac Rs = Rs Lac'
# and obtain La (Ls Rs) (Lac' Rac)
ret = P.one()
for k in dl:
x = sum(c * gens_dict[i]
for i,c in alphacheck[k].weyl_action(right[1].reduced_word(),
inverse=True))
ret *= x**dl[k]
ret = ret.dict()
w = left[1]*right[1]
return self._from_dict({ (left[0], w,
self._h({I[i]: e for i,e in enumerate(k)
if e != 0}) * right[2]
): ret[k]
for k in ret })
# Otherwise dr is non-trivial and we have La Ls Ra Rs Rac,
# so we must commute Ls Ra = Ra' Ls
w = left[1]*right[1]
return self._from_dict({ (left[0] * hd, w, right[2]): c
for hd, c in commute_w_hd(left[1], dr) })
@cached_method
def _product_coroot_root(self, i, j):
r"""
Return the product `\alpha^{\vee}_i \alpha_j`.
EXAMPLES::
sage: k = QQ['c,t']
sage: R = algebras.RationalCherednik(['A',3], k.gen(0), k.gen(1))
sage: sorted(R._product_coroot_root(1, 1))
[(s1, 2*c),
(s1*s2*s1, 1/2*c),
(s1*s2*s3*s2*s1, 1/2*c),
(1, 2*t),
(s3, 0),
(s2, 1/2*c),
(s2*s3*s2, 1/2*c)]
sage: sorted(R._product_coroot_root(1, 2))
[(s1, -c),
(s1*s2*s1, 1/2*c),
(s1*s2*s3*s2*s1, 0),
(1, -t),
(s3, 0),
(s2, -c),
(s2*s3*s2, -1/2*c)]
sage: sorted(R._product_coroot_root(1, 3))
[(s1, 0),
(s1*s2*s1, -1/2*c),
(s1*s2*s3*s2*s1, 1/2*c),
(1, 0),
(s3, 0),
(s2, 1/2*c),
(s2*s3*s2, -1/2*c)]
"""
Q = RootSystem(self._cartan_type).root_lattice()
ac = Q.simple_coroot(i)
al = Q.simple_root(j)
R = self.base_ring()
terms = [( self._weyl.one(), self._t * R(ac.scalar(al)) )]
for s in self._reflections:
# p[0] is the root, p[1] is the coroot, p[2] the value c_s
pr, pc, c = self._reflections[s]
terms.append(( s, c * R(ac.scalar(pr) * pc.scalar(al)
/ pc.scalar(pr)) ))
return tuple(terms)
def degree_on_basis(self, m):
"""
Return the degree on the monomial indexed by ``m``.
EXAMPLES::
sage: R = algebras.RationalCherednik(['A',2], 1, 1, QQ)
sage: [R.degree_on_basis(g.leading_support())
....: for g in R.algebra_generators()]
[1, 1, 0, 0, -1, -1]
"""
return m[0].length() - m[2].length()
@cached_method
def trivial_idempotent(self):
r"""
Return the trivial idempotent of ``self``.
Let `e = |W|^{-1} \sum_{w \in W} w` is the trivial idempotent.
Thus `e^2 = e` and `eW = We`. The trivial idempotent is used
in the construction of the spherical Cherednik algebra from
the rational Cherednik algebra by `U_{c,t}(W) = e H_{c,t}(W) e`.
EXAMPLES::
sage: R = algebras.RationalCherednik(['A',2], 1, 1, QQ)
sage: R.trivial_idempotent()
1/6*I + 1/6*s1 + 1/6*s2 + 1/6*s2*s1 + 1/6*s1*s2 + 1/6*s1*s2*s1
"""
coeff = self.base_ring()(~self._weyl.cardinality())
hd_one = self._hd.one() # root - a
h_one = self._h.one() # coroot - ac
return self._from_dict({(hd_one, w, h_one): coeff for w in self._weyl},
remove_zeros=False)
@cached_method
def deformed_euler(self):
"""
Return the element `eu_k`.
EXAMPLES::
sage: R = algebras.RationalCherednik(['A',2], 1, 1, QQ)
sage: R.deformed_euler()
2*I + 2/3*a1*ac1 + 1/3*a1*ac2 + 1/3*a2*ac1 + 2/3*a2*ac2
+ s1 + s2 + s1*s2*s1
"""
I = self._cartan_type.index_set()
G = self.algebra_generators()
cm = ~CartanMatrix(self._cartan_type)
n = len(I)
ac = [G['ac'+str(i)] for i in I]
la = [sum(cm[i,j]*G['a'+str(I[i])] for i in range(n)) for j in range(n)]
return self.sum(ac[i]*la[i] for i in range(n))
@cached_method
def an_element(self):
"""
Return an element of ``self``.
EXAMPLES::
sage: R = algebras.RationalCherednik(['A',2], 1, 1, QQ)
sage: R.an_element()
3*ac1 + 2*s1 + a1
"""
G = self.algebra_generators()
i = str(self._cartan_type.index_set()[0])
return G['a'+i] + 2*G['s'+i] + 3*G['ac'+i]
def some_elements(self):
"""
Return some elements of ``self``.
EXAMPLES::
sage: R = algebras.RationalCherednik(['A',2], 1, 1, QQ)
sage: R.some_elements()
[0, I, 3*ac1 + 2*s1 + a1, a1, a2, s1, s2, ac1, ac2]
"""
ret = [self.zero(), self.one(), self.an_element()]
ret += list(self.algebra_generators())
return ret | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/rational_cherednik_algebra.py | 0.840488 | 0.610366 | rational_cherednik_algebra.py | pypi |
r"""
Catalog of Algebras
The ``algebras`` object may be used to access examples of various algebras
currently implemented in Sage. Using tab-completion on this object is an
easy way to discover and quickly create the algebras that are available
(as listed here).
Let ``<tab>`` indicate pressing the :kbd:`Tab` key. So begin by typing
``algebras.<tab>`` to the see the currently implemented named algebras.
- :class:`algebras.AlternatingCentralExtensionQuantumOnsager
<sage.algebras.quantum_groups.ace_quantum_onsager.ACEQuantumOnsagerAlgebra>`
- :class:`algebras.ArikiKoike
<sage.algebras.hecke_algebras.ariki_koike_algebra.ArikiKoikeAlgebra>`
- :class:`algebras.AskeyWilson <sage.algebras.askey_wilson.AskeyWilsonAlgebra>`
- :class:`algebras.Blob <sage.combinat.blob_algebra.BlobAlgebra>`
- :class:`algebras.Brauer <sage.combinat.diagram_algebras.BrauerAlgebra>`
- :class:`algebras.Clifford <sage.algebras.clifford_algebra.CliffordAlgebra>`
- :class:`algebras.ClusterAlgebra <sage.algebras.cluster_algebra.ClusterAlgebra>`
- :class:`algebras.CubicHecke
<sage.algebras.hecke_algebras.cubic_hecke_algebra.CubicHeckeAlgebra>`
- :class:`algebras.Descent <sage.combinat.descent_algebra.DescentAlgebra>`
- :class:`algebras.DifferentialWeyl
<sage.algebras.weyl_algebra.DifferentialWeylAlgebra>`
- :class:`algebras.Exterior <sage.algebras.clifford_algebra.ExteriorAlgebra>`
- :class:`algebras.FiniteDimensional
<sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra.FiniteDimensionalAlgebra>`
- :class:`algebras.FQSym <sage.combinat.fqsym.FreeQuasisymmetricFunctions>`
- :class:`algebras.Free <sage.algebras.free_algebra.FreeAlgebraFactory>`
- :class:`algebras.FreeZinbiel <sage.algebras.free_zinbiel_algebra.FreeZinbielAlgebra>`
- :class:`algebras.FreePreLie <sage.combinat.free_prelie_algebra.FreePreLieAlgebra>`
- :class:`algebras.FreeDendriform <sage.combinat.free_dendriform_algebra.FreeDendriformAlgebra>`
- :class:`algebras.FSym <sage.combinat.chas.fsym.FreeSymmetricFunctions>`
- :func:`algebras.GradedCommutative
<sage.algebras.commutative_dga.GradedCommutativeAlgebra>`
- :class:`algebras.Group <sage.algebras.group_algebra.GroupAlgebra>`
- :class:`algebras.GrossmanLarson <sage.combinat.grossman_larson_algebras.GrossmanLarsonAlgebra>`
- :class:`algebras.Hall <sage.algebras.hall_algebra.HallAlgebra>`
- :class:`algebras.Incidence <sage.combinat.posets.incidence_algebras.IncidenceAlgebra>`
- :class:`algebras.IwahoriHecke
<sage.algebras.iwahori_hecke_algebra.IwahoriHeckeAlgebra>`
- :class:`algebras.Moebius <sage.combinat.posets.moebius_algebra.MoebiusAlgebra>`
- :class:`algebras.Jordan
<sage.algebras.jordan_algebra.JordanAlgebra>`
- :class:`algebras.Lie <sage.algebras.lie_algebras.lie_algebra.LieAlgebra>`
- :class:`algebras.MalvenutoReutenauer <sage.combinat.fqsym.FreeQuasisymmetricFunctions>`
- :class:`algebras.NilCoxeter
<sage.algebras.nil_coxeter_algebra.NilCoxeterAlgebra>`
- :class:`algebras.OrlikTerao
<sage.algebras.orlik_terao.OrlikTeraoAlgebra>`
- :class:`algebras.OrlikSolomon
<sage.algebras.orlik_solomon.OrlikSolomonAlgebra>`
- :class:`algebras.QuantumClifford
<sage.algebras.quantum_clifford.QuantumCliffordAlgebra>`
- :class:`algebras.QuantumGL
<sage.algebras.quantum_matrix_coordinate_algebra.QuantumGL>`
- :class:`algebras.QuantumMatrixCoordinate
<sage.algebras.quantum_matrix_coordinate_algebra.QuantumMatrixCoordinateAlgebra>`
- :class:`algebras.QSym <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions>`
- :class:`algebras.Partition <sage.combinat.diagram_algebras.PartitionAlgebra>`
- :class:`algebras.PlanarPartition <sage.combinat.diagram_algebras.PlanarAlgebra>`
- :class:`algebras.qCommutingPolynomials
<sage.algebras.q_commuting_polynomials.qCommutingPolynomials>`
- :class:`algebras.QuantumGroup
<sage.algebras.quantum_groups.quantum_group_gap.QuantumGroup>`
- :func:`algebras.Quaternion
<sage.algebras.quatalg.quaternion_algebra.QuaternionAlgebraFactory>`
- :class:`algebras.RationalCherednik
<sage.algebras.rational_cherednik_algebra.RationalCherednikAlgebra>`
- :class:`algebras.Schur <sage.algebras.schur_algebra.SchurAlgebra>`
- :class:`algebras.Shuffle <sage.algebras.shuffle_algebra.ShuffleAlgebra>`
- :class:`algebras.Steenrod
<sage.algebras.steenrod.steenrod_algebra.SteenrodAlgebra>`
- :class:`algebras.TemperleyLieb <sage.combinat.diagram_algebras.TemperleyLiebAlgebra>`
- :class:`algebras.Tensor <sage.algebras.tensor_algebra.TensorAlgebra>`
- :class:`algebras.WQSym <sage.combinat.chas.wqsym.WordQuasiSymmetricFunctions>`
- :class:`algebras.Yangian <sage.algebras.yangian.Yangian>`
- :class:`algebras.YokonumaHecke
<sage.algebras.yokonuma_hecke_algebra.YokonumaHeckeAlgebra>`
"""
from sage.algebras.free_algebra import FreeAlgebra as Free
from sage.algebras.quatalg.quaternion_algebra import QuaternionAlgebra as Quaternion
from sage.algebras.steenrod.steenrod_algebra import SteenrodAlgebra as Steenrod
from sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra import FiniteDimensionalAlgebra as FiniteDimensional
from sage.algebras.group_algebra import GroupAlgebra as Group
from sage.algebras.clifford_algebra import CliffordAlgebra as Clifford
from sage.algebras.clifford_algebra import ExteriorAlgebra as Exterior
from sage.algebras.weyl_algebra import DifferentialWeylAlgebra as DifferentialWeyl
from sage.algebras.lie_algebras.lie_algebra import LieAlgebra as Lie
from sage.misc.lazy_import import lazy_import
lazy_import('sage.algebras.iwahori_hecke_algebra', 'IwahoriHeckeAlgebra', 'IwahoriHecke')
lazy_import('sage.algebras.nil_coxeter_algebra', 'NilCoxeterAlgebra', 'NilCoxeter')
lazy_import('sage.algebras.free_zinbiel_algebra', 'FreeZinbielAlgebra', 'FreeZinbiel')
lazy_import('sage.algebras.askey_wilson', 'AskeyWilsonAlgebra', 'AskeyWilson')
lazy_import('sage.algebras.hall_algebra', 'HallAlgebra', 'Hall')
lazy_import('sage.algebras.jordan_algebra', 'JordanAlgebra', 'Jordan')
lazy_import('sage.algebras.orlik_solomon', 'OrlikSolomonAlgebra', 'OrlikSolomon')
lazy_import('sage.algebras.orlik_terao', 'OrlikTeraoAlgebra', 'OrlikTerao')
lazy_import('sage.algebras.shuffle_algebra', 'ShuffleAlgebra', 'Shuffle')
lazy_import('sage.algebras.schur_algebra', 'SchurAlgebra', 'Schur')
lazy_import('sage.algebras.commutative_dga', 'GradedCommutativeAlgebra', 'GradedCommutative')
lazy_import('sage.algebras.hecke_algebras.ariki_koike_algebra', 'ArikiKoikeAlgebra', 'ArikiKoike')
lazy_import('sage.algebras.hecke_algebras.cubic_hecke_algebra', 'CubicHeckeAlgebra', 'CubicHecke')
lazy_import('sage.algebras.rational_cherednik_algebra', 'RationalCherednikAlgebra', 'RationalCherednik')
lazy_import('sage.algebras.yokonuma_hecke_algebra', 'YokonumaHeckeAlgebra', 'YokonumaHecke')
lazy_import('sage.combinat.posets.incidence_algebras', 'IncidenceAlgebra', 'Incidence')
lazy_import('sage.combinat.descent_algebra', 'DescentAlgebra', 'Descent')
lazy_import('sage.combinat.diagram_algebras', 'BrauerAlgebra', 'Brauer')
lazy_import('sage.combinat.diagram_algebras', 'PartitionAlgebra', 'Partition')
lazy_import('sage.combinat.diagram_algebras', 'PlanarAlgebra', 'PlanarPartition')
lazy_import('sage.combinat.diagram_algebras', 'TemperleyLiebAlgebra', 'TemperleyLieb')
lazy_import('sage.combinat.blob_algebra', 'BlobAlgebra', 'Blob')
lazy_import('sage.combinat.posets.moebius_algebra', 'MoebiusAlgebra', 'Moebius')
lazy_import('sage.combinat.free_prelie_algebra', 'FreePreLieAlgebra', 'FreePreLie')
lazy_import('sage.combinat.free_dendriform_algebra', 'FreeDendriformAlgebra', 'FreeDendriform')
lazy_import('sage.combinat.fqsym', 'FreeQuasisymmetricFunctions', 'FQSym')
lazy_import('sage.combinat.fqsym', 'FreeQuasisymmetricFunctions', 'MalvenutoReutenauer')
lazy_import('sage.combinat.chas.wqsym', 'WordQuasiSymmetricFunctions', 'WQSym')
lazy_import('sage.combinat.chas.fsym', 'FreeSymmetricFunctions', 'FSym')
lazy_import('sage.combinat.ncsf_qsym.qsym', 'QuasiSymmetricFunctions', 'QSym')
lazy_import('sage.combinat.grossman_larson_algebras', 'GrossmanLarsonAlgebra', 'GrossmanLarson')
lazy_import('sage.algebras.quantum_clifford', 'QuantumCliffordAlgebra', 'QuantumClifford')
lazy_import('sage.algebras.quantum_matrix_coordinate_algebra',
'QuantumMatrixCoordinateAlgebra', 'QuantumMatrixCoordinate')
lazy_import('sage.algebras.quantum_matrix_coordinate_algebra', 'QuantumGL')
lazy_import('sage.algebras.q_commuting_polynomials', 'qCommutingPolynomials')
lazy_import('sage.algebras.tensor_algebra', 'TensorAlgebra', 'Tensor')
lazy_import('sage.algebras.quantum_groups.quantum_group_gap', 'QuantumGroup')
lazy_import('sage.algebras.quantum_groups.ace_quantum_onsager',
'ACEQuantumOnsagerAlgebra', 'AlternatingCentralExtensionQuantumOnsager')
lazy_import('sage.algebras.yangian', 'Yangian')
del lazy_import # We remove the object from here so it doesn't appear under tab completion | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/catalog.py | 0.865821 | 0.662892 | catalog.py | pypi |
from sage.modules.free_module import FreeModule
from sage.rings.ring import Algebra
from sage.algebras.free_algebra import is_FreeAlgebra
from sage.algebras.free_algebra_quotient_element import FreeAlgebraQuotientElement
from sage.structure.unique_representation import UniqueRepresentation
class FreeAlgebraQuotient(UniqueRepresentation, Algebra, object):
@staticmethod
def __classcall__(cls, A, mons, mats, names):
"""
Used to support unique representation.
EXAMPLES::
sage: H = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)[0] # indirect doctest
sage: H1 = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)[0]
sage: H is H1
True
"""
new_mats = []
for M in mats:
M = M.parent()(M)
M.set_immutable()
new_mats.append(M)
return super().__classcall__(cls, A, tuple(mons),
tuple(new_mats), tuple(names))
Element = FreeAlgebraQuotientElement
def __init__(self, A, mons, mats, names):
"""
Return a quotient algebra defined via the action of a free algebra
A on a (finitely generated) free module.
The input for the quotient algebra is a list of monomials (in
the underlying monoid for A) which form a free basis for the
module of A, and a list of matrices, which give the action of
the free generators of A on this monomial basis.
EXAMPLES:
Quaternion algebra defined in terms of three generators::
sage: n = 3
sage: A = FreeAlgebra(QQ,n,'i')
sage: F = A.monoid()
sage: i, j, k = F.gens()
sage: mons = [ F(1), i, j, k ]
sage: M = MatrixSpace(QQ,4)
sage: mats = [M([0,1,0,0, -1,0,0,0, 0,0,0,-1, 0,0,1,0]), M([0,0,1,0, 0,0,0,1, -1,0,0,0, 0,-1,0,0]), M([0,0,0,1, 0,0,-1,0, 0,1,0,0, -1,0,0,0]) ]
sage: H3.<i,j,k> = FreeAlgebraQuotient(A,mons,mats)
sage: x = 1 + i + j + k
sage: x
1 + i + j + k
sage: x**128
-170141183460469231731687303715884105728 + 170141183460469231731687303715884105728*i + 170141183460469231731687303715884105728*j + 170141183460469231731687303715884105728*k
Same algebra defined in terms of two generators, with some penalty
on already slow arithmetic.
::
sage: n = 2
sage: A = FreeAlgebra(QQ,n,'x')
sage: F = A.monoid()
sage: i, j = F.gens()
sage: mons = [ F(1), i, j, i*j ]
sage: r = len(mons)
sage: M = MatrixSpace(QQ,r)
sage: mats = [M([0,1,0,0, -1,0,0,0, 0,0,0,-1, 0,0,1,0]), M([0,0,1,0, 0,0,0,1, -1,0,0,0, 0,-1,0,0]) ]
sage: H2.<i,j> = A.quotient(mons,mats)
sage: k = i*j
sage: x = 1 + i + j + k
sage: x
1 + i + j + i*j
sage: x**128
-170141183460469231731687303715884105728 + 170141183460469231731687303715884105728*i + 170141183460469231731687303715884105728*j + 170141183460469231731687303715884105728*i*j
TESTS::
sage: TestSuite(H2).run()
"""
if not is_FreeAlgebra(A):
raise TypeError("argument A must be an algebra")
R = A.base_ring()
n = A.ngens()
assert n == len(mats)
self.__free_algebra = A
self.__ngens = n
self.__dim = len(mons)
self.__module = FreeModule(R, self.__dim)
self.__matrix_action = mats
self.__monomial_basis = mons # elements of free monoid
Algebra.__init__(self, R, names, normalize=True)
def _element_constructor_(self, x):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: H(i) is i
True
sage: a = H._element_constructor_(1); a
1
sage: a in H
True
sage: a = H._element_constructor_([1,2,3,4]); a
1 + 2*i + 3*j + 4*k
"""
return self.element_class(self, x)
def _coerce_map_from_(self, S):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: H._coerce_map_from_(H)
True
sage: H._coerce_map_from_(QQ)
True
sage: H._coerce_map_from_(GF(7))
False
"""
return S == self or self.__free_algebra.has_coerce_map_from(S)
def _repr_(self):
"""
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: H._repr_()
"Free algebra quotient on 3 generators ('i', 'j', 'k') and dimension 4 over Rational Field"
"""
R = self.base_ring()
n = self.__ngens
r = self.__module.dimension()
x = self.variable_names()
return "Free algebra quotient on %s generators %s and dimension %s over %s" % (n, x, r, R)
def gen(self, i):
"""
The i-th generator of the algebra.
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)
sage: H.gen(0)
i
sage: H.gen(2)
k
An IndexError is raised if an invalid generator is requested::
sage: H.gen(3)
Traceback (most recent call last):
...
IndexError: argument i (= 3) must be between 0 and 2
Negative indexing into the generators is not supported::
sage: H.gen(-1)
Traceback (most recent call last):
...
IndexError: argument i (= -1) must be between 0 and 2
"""
n = self.__ngens
if i < 0 or not i < n:
raise IndexError("argument i (= %s) must be between 0 and %s" % (i, n - 1))
R = self.base_ring()
F = self.__free_algebra.monoid()
return self.element_class(self, {F.gen(i): R.one()})
def ngens(self):
"""
The number of generators of the algebra.
EXAMPLES::
sage: sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)[0].ngens()
3
"""
return self.__ngens
def dimension(self):
"""
The rank of the algebra (as a free module).
EXAMPLES::
sage: sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)[0].dimension()
4
"""
return self.__dim
def matrix_action(self):
"""
EXAMPLES::
sage: sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)[0].matrix_action()
(
[ 0 1 0 0] [ 0 0 1 0] [ 0 0 0 1]
[-1 0 0 0] [ 0 0 0 1] [ 0 0 -1 0]
[ 0 0 0 -1] [-1 0 0 0] [ 0 1 0 0]
[ 0 0 1 0], [ 0 -1 0 0], [-1 0 0 0]
)
"""
return self.__matrix_action
def monomial_basis(self):
"""
The free monoid of generators of the algebra as elements of a free
monoid.
EXAMPLES::
sage: sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)[0].monomial_basis()
(1, i0, i1, i2)
"""
return self.__monomial_basis
def rank(self):
"""
The rank of the algebra (as a free module).
EXAMPLES::
sage: sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)[0].rank()
4
"""
return self.__dim
def module(self):
"""
The free module of the algebra.
sage: H = sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)[0]; H
Free algebra quotient on 3 generators ('i', 'j', 'k') and dimension 4 over Rational Field
sage: H.module()
Vector space of dimension 4 over Rational Field
"""
return self.__module
def monoid(self):
"""
The free monoid of generators of the algebra.
EXAMPLES::
sage: sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)[0].monoid()
Free monoid on 3 generators (i0, i1, i2)
"""
return self.__free_algebra.monoid()
def free_algebra(self):
"""
The free algebra generating the algebra.
EXAMPLES::
sage: sage.algebras.free_algebra_quotient.hamilton_quatalg(QQ)[0].free_algebra()
Free Algebra on 3 generators (i0, i1, i2) over Rational Field
"""
return self.__free_algebra
def hamilton_quatalg(R):
"""
Hamilton quaternion algebra over the commutative ring R,
constructed as a free algebra quotient.
INPUT:
- R -- a commutative ring
OUTPUT:
- Q -- quaternion algebra
- gens -- generators for Q
EXAMPLES::
sage: H, (i,j,k) = sage.algebras.free_algebra_quotient.hamilton_quatalg(ZZ)
sage: H
Free algebra quotient on 3 generators ('i', 'j', 'k') and dimension 4 over Integer Ring
sage: i^2
-1
sage: i in H
True
Note that there is another vastly more efficient models for
quaternion algebras in Sage; the one here is mainly for testing
purposes::
sage: R.<i,j,k> = QuaternionAlgebra(QQ,-1,-1) # much fast than the above
"""
n = 3
from sage.algebras.free_algebra import FreeAlgebra
from sage.matrix.all import MatrixSpace
A = FreeAlgebra(R, n, 'i')
F = A.monoid()
i, j, k = F.gens()
mons = [F(1), i, j, k]
M = MatrixSpace(R, 4)
mats = [M([0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0]),
M([0, 0, 1, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, -1, 0, 0]),
M([0, 0, 0, 1, 0, 0, -1, 0, 0, 1, 0, 0, -1, 0, 0, 0])]
H3 = FreeAlgebraQuotient(A, mons, mats, names=('i', 'j', 'k'))
return H3, H3.gens() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/free_algebra_quotient.py | 0.73848 | 0.333883 | free_algebra_quotient.py | pypi |
from sage.categories.all import AlgebrasWithBasis
from sage.combinat.root_system.cartan_type import CartanType
from sage.combinat.root_system.weyl_group import WeylGroup
from sage.rings.ring import Ring
from sage.rings.integer_ring import ZZ
from sage.combinat.free_module import CombinatorialFreeModule
from sage.misc.cachefunc import cached_method
class AffineNilTemperleyLiebTypeA(CombinatorialFreeModule):
r"""
Construct the affine nilTemperley Lieb algebra of type `A_{n-1}^{(1)}` as used in [Pos2005]_.
INPUT:
- ``n`` -- a positive integer
The affine nilTemperley Lieb algebra is generated by `a_i` for `i=0,1,\ldots,n-1`
subject to the relations `a_i a_i = a_i a_{i+1} a_i = a_{i+1} a_i a_{i+1} = 0` and
`a_i a_j = a_j a_i` for `i-j \not \equiv \pm 1`, where the indices are taken modulo `n`.
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(4)
sage: a = A.algebra_generators(); a
Finite family {0: a0, 1: a1, 2: a2, 3: a3}
sage: a[1]*a[2]*a[0] == a[1]*a[0]*a[2]
True
sage: a[0]*a[3]*a[0]
0
sage: A.an_element()
2*a0 + 1 + 3*a1 + a0*a1*a2*a3
"""
def __init__(self, n, R=ZZ, prefix='a'):
"""
Initiate the affine nilTemperley Lieb algebra over the ring `R`.
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(3, prefix="a"); A
The affine nilTemperley Lieb algebra A3 over the ring Integer Ring
sage: TestSuite(A).run()
sage: A = AffineNilTemperleyLiebTypeA(3, QQ); A
The affine nilTemperley Lieb algebra A3 over the ring Rational Field
"""
if not isinstance(R, Ring):
raise TypeError("argument R must be a ring")
self._cartan_type = CartanType(['A', n - 1, 1])
self._n = n
W = WeylGroup(self._cartan_type)
self._prefix = prefix
self._index_set = W.index_set()
self._base_ring = R
category = AlgebrasWithBasis(R)
CombinatorialFreeModule.__init__(self, R, W, category=category)
def _element_constructor_(self, w):
"""
Constructs a basis element from an element of the Weyl group.
If `w = w_1 ... w_k` is a reduced word for `w`, then `A(w)` returns
zero if `w` contains braid relations.
TODO: Once the functorial construction is in sage, perhaps this should be
handled constructing the affine nilTemperley Lieb algebra as a quotient algebra.
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(3, prefix="a")
sage: W = A.weyl_group()
sage: w = W.from_reduced_word([2,1,2])
sage: A(w)
0
sage: w = W.from_reduced_word([2,1])
sage: A(w)
a2*a1
"""
W = self.weyl_group()
assert w in W
word = w.reduced_word()
if all(self.has_no_braid_relation(W.from_reduced_word(word[:i]), word[i]) for i in range(len(word))):
return self.monomial(w)
return self.zero()
@cached_method
def one_basis(self):
"""
Return the unit of the underlying Weyl group, which index
the one of this algebra, as per
:meth:`AlgebrasWithBasis.ParentMethods.one_basis`.
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(3)
sage: A.one_basis()
[1 0 0]
[0 1 0]
[0 0 1]
sage: A.one_basis() == A.weyl_group().one()
True
sage: A.one()
1
"""
return self.weyl_group().one()
def _repr_(self):
"""
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(3); A
The affine nilTemperley Lieb algebra A3 over the ring Integer Ring
"""
return "The affine nilTemperley Lieb algebra A%s over the ring %s"%(self._n, self._base_ring)
def weyl_group(self):
"""
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(3)
sage: A.weyl_group()
Weyl Group of type ['A', 2, 1] (as a matrix group acting on the root space)
"""
return self.basis().keys()
def index_set(self):
"""
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(3)
sage: A.index_set()
(0, 1, 2)
"""
return self._index_set
@cached_method
def algebra_generators(self):
r"""
Return the generators `a_i` for `i=0,1,2,\ldots,n-1`.
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(3)
sage: a = A.algebra_generators();a
Finite family {0: a0, 1: a1, 2: a2}
sage: a[1]
a1
"""
return self.weyl_group().simple_reflections().map(self.monomial)
def algebra_generator(self, i):
"""
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(3)
sage: A.algebra_generator(1)
a1
sage: A = AffineNilTemperleyLiebTypeA(3, prefix = 't')
sage: A.algebra_generator(1)
t1
"""
return self.algebra_generators()[i]
def product_on_basis(self, w, w1):
"""
Return `a_w a_{w1}`, where `w` and `w1` are in the Weyl group
assuming that `w` does not contain any braid relations.
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(5)
sage: W = A.weyl_group()
sage: s = W.simple_reflections()
sage: [A.product_on_basis(s[1],x) for x in s]
[a1*a0, 0, a1*a2, a3*a1, a4*a1]
sage: a = A.algebra_generators()
sage: x = a[1] * a[2]
sage: x
a1*a2
sage: x * a[1]
0
sage: x * a[2]
0
sage: x * a[0]
a1*a2*a0
sage: [x * a[1] for x in a]
[a0*a1, 0, a2*a1, a3*a1, a4*a1]
sage: w = s[1]*s[2]*s[1]
sage: A.product_on_basis(w,s[1])
Traceback (most recent call last):
...
AssertionError
"""
assert self(w) != self.zero()
for i in w1.reduced_word():
if self.has_no_braid_relation(w, i):
w = w.apply_simple_reflection(i)
else:
return self.zero()
return self.monomial(w)
@cached_method
def has_no_braid_relation(self, w, i):
"""
Assuming that `w` contains no relations of the form `s_i^2` or `s_i s_{i+1} s_i` or
`s_i s_{i-1} s_i`, tests whether `w s_i` contains terms of this form.
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(5)
sage: W = A.weyl_group()
sage: s=W.simple_reflections()
sage: A.has_no_braid_relation(s[2]*s[1]*s[0]*s[4]*s[3],0)
False
sage: A.has_no_braid_relation(s[2]*s[1]*s[0]*s[4]*s[3],2)
True
sage: A.has_no_braid_relation(s[4],2)
True
"""
if w == w.parent().one():
return True
if i in w.descents():
return False
s = w.parent().simple_reflections()
wi = w*s[i]
adjacent = [(i-1)%w.parent().n, (i+1)%w.parent().n]
for j in adjacent:
if j in w.descents():
if j in wi.descents():
return False
else:
return True
return self.has_no_braid_relation(w*s[w.first_descent()],i)
def _repr_term(self, t, short_display=True):
"""
EXAMPLES::
sage: A = AffineNilTemperleyLiebTypeA(3)
sage: W = A.weyl_group()
sage: A._repr_term(W.from_reduced_word([1,2,0]))
'a1*a2*a0'
sage: A._repr_term(W.from_reduced_word([1,2,0]), short_display = False)
'a[1]*a[2]*a[0]'
"""
redword = t.reduced_word()
if len(redword) == 0:
return "1"
elif short_display:
return "*".join("%s%d"%(self._prefix, i) for i in redword)
else:
return "*".join("%s[%d]"%(self._prefix, i) for i in redword) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/affine_nil_temperley_lieb.py | 0.822046 | 0.641394 | affine_nil_temperley_lieb.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.categories.algebras import Algebras
from sage.categories.cartesian_product import cartesian_product
from sage.categories.rings import Rings
from sage.combinat.free_module import CombinatorialFreeModule
from sage.modules.with_basis.morphism import ModuleMorphismByLinearity
from sage.sets.family import Family
from sage.rings.polynomial.laurent_polynomial_ring import LaurentPolynomialRing
from sage.sets.non_negative_integers import NonNegativeIntegers
class AskeyWilsonAlgebra(CombinatorialFreeModule):
r"""
The (universal) Askey-Wilson algebra.
Let `R` be a commutative ring. The *universal Askey-Wilson* algebra
is an associative unital algebra `\Delta_q` over `R[q,q^-1]` given
by the generators `A, B, C, \alpha, \beta, \gamma` that satisfy the
following relations:
.. MATH::
\begin{aligned}
(q-q^{-1}) \alpha &= (q^2-q^{-2}) A + qBC - q^{-1}CB, \\
(q-q^{-1}) \beta &= (q^2-q^{-2}) B + qCA - q^{-1}AC, \\
(q-q^{-1}) \gamma &= (q^2-q^{-2}) C + qAB - q^{-1}BA.
\end{aligned}
The universal Askey-Wilson contains a
:meth:`Casimir element <casimir_element>` `\Omega`, and the elements
`\alpha`, `\beta`, `\gamma`, `\Omega` generate the center of `\Delta_q`,
which is isomorphic to the polynomial ring
`(R[q,q^-1])[\alpha,\beta,\gamma,\Omega]` (assuming `q` is not a root
of unity). Furthermore, the relations imply that `\Delta_q` has a basis
given by monomials `A^i B^j C^k \alpha^r \beta^s \gamma^t`, where
`i, j, k, r, s, t \in \ZZ_{\geq 0}`.
The universal Askey-Wilson algebra also admits a faithful action
of `PSL_2(\ZZ)` given by the automorphisms `\rho`
(:meth:`permutation_automorphism`):
.. MATH::
A \mapsto B \mapsto C \mapsto A,
\qquad
\alpha \mapsto \beta \mapsto \gamma \mapsto \alpha.
and `\sigma` (:meth:`reflection_automorphism`):
.. MATH::
A \mapsto B \mapsto A,
C \mapsto C + \frac{AB - BA}{q-q^{-1}},
\qquad
\alpha \mapsto \beta \mapsto \alpha,
\gamma \mapsto \gamma.
Note that `\rho^3 = \sigma^2 = 1` and
.. MATH::
\sigma(C) = C - q AB - (1+q^2) C + q \gamma
= C - q AB - q^2 C + q \gamma.
The Askey-Wilson `AW_q(a,b,c)` algebra is a specialization of the
universal Askey-Wilson algebra by `\alpha = a`, \beta = b`,
`\gamma = c`, where `a,b,c \in R`. `AW_q(a,b,c)` was first introduced
by [Zhedanov1991]_ to describe the Askey-Wilson polynomials. The
Askey-Wilson algebra has a central extension of `\Delta_q`.
INPUT:
- ``R`` -- a commutative ring
- ``q`` -- (optional) the parameter `q`; must be invertible in ``R``
If ``q`` is not specified, then ``R`` is taken to be the base
ring of a Laurent polynomial ring with variable `q`. Otherwise
the element ``q`` must be an element of ``R``.
.. NOTE::
No check is performed to ensure ``q`` is not a root of unity,
which may lead to violations of the results in [Terwilliger2011]_.
EXAMPLES:
We create the universal Askey-Wilson algebra and check
the defining relations::
sage: AW = algebras.AskeyWilson(QQ)
sage: AW.inject_variables()
Defining A, B, C, a, b, g
sage: q = AW.q()
sage: (q^2-q^-2)*A + q*B*C - q^-1*C*B == (q-q^-1)*a
True
sage: (q^2-q^-2)*B + q*C*A - q^-1*A*C == (q-q^-1)*b
True
sage: (q^2-q^-2)*C + q*A*B - q^-1*B*A == (q-q^-1)*g
True
Next, we perform some computations::
sage: C * A
(q^-2)*A*C + (q^-3-q)*B - (q^-2-1)*b
sage: B^2 * g^2 * A
q^4*A*B^2*g^2 - (q^-1-q^7)*B*C*g^2 + (1-q^4)*B*g^3
+ (1-2*q^4+q^8)*A*g^2 - (q-q^3-q^5+q^7)*a*g^2
sage: (B^3 - A) * (C^2 + q*A*B)
q^7*A*B^4 + B^3*C^2 - (q^2-q^14)*B^3*C + (q-q^7)*B^3*g - q*A^2*B
+ (3*q^3-4*q^7+q^19)*A*B^2 - A*C^2 - (1-q^6-q^8+q^14)*B^2*a
- (q^-2-3*q^6+3*q^14-q^22)*B*C
+ (q^-1+q-3*q^3-q^5+2*q^7-q^9+q^13+q^15-q^19)*B*g
+ (2*q^-1-6*q^3+5*q^7-2*q^19+q^23)*A
- (2-2*q^2-4*q^4+4*q^6+q^8-q^10+q^12-q^14+q^16-q^18-q^20+q^22)*a
We check the elements `\alpha`, `\beta`, and `\gamma`
are in the center::
sage: all(x * gen == gen * x for gen in AW.algebra_generators() for x in [a,b,g])
True
We verify that the :meth:`Casimir element <casimir_element>`
is in the center::
sage: Omega = AW.casimir_element()
sage: all(x * Omega == Omega * x for x in [A,B,C])
True
sage: x = AW.an_element()
sage: O2 = Omega^2
sage: x * O2 == O2 * x
True
We prove Lemma 2.1 in [Terwilliger2011]_::
sage: (q^2-q^-2) * C == (q-q^-1) * g - (q*A*B - q^-1*B*A)
True
sage: (q-q^-1) * (q^2-q^-2) * a == (B^2*A - (q^2+q^-2)*B*A*B + A*B^2
....: + (q^2-q^-2)^2*A + (q-q^-1)^2*B*g)
True
sage: (q-q^-1) * (q^2-q^-2) * b == (A^2*B - (q^2+q^-2)*A*B*A + B*A^2
....: + (q^2-q^-2)^2*B + (q-q^-1)^2*A*g)
True
We prove Theorem 2.2 in [Terwilliger2011]_::
sage: q3 = q^-2 + 1 + q^2
sage: A^3*B - q3*A^2*B*A + q3*A*B*A^2 - B*A^3 == -(q^2-q^-2)^2 * (A*B - B*A)
True
sage: B^3*A - q3*B^2*A*B + q3*B*A*B^2 - A*B^3 == -(q^2-q^-2)^2 * (B*A - A*B)
True
sage: (A^2*B^2 - B^2*A^2 + (q^2+q^-2)*(B*A*B*A-A*B*A*B)
....: == -(q^1-q^-1)^2 * (A*B - B*A) * g)
True
We construct an Askey-Wilson algebra over `\GF{5}` at `q=2`::
sage: AW = algebras.AskeyWilson(GF(5), q=2)
sage: A,B,C,a,b,g = AW.algebra_generators()
sage: q = AW.q()
sage: Omega = AW.casimir_element()
sage: B * A
4*A*B + 2*g
sage: C * A
4*A*C + 2*b
sage: C * B
4*B*C + 2*a
sage: Omega^2
A^2*B^2*C^2 + A^3*B*C + A*B^3*C + A*B*C^3 + A^4 + 4*A^3*a
+ 2*A^2*B^2 + A^2*B*b + 2*A^2*C^2 + 4*A^2*C*g + 4*A^2*a^2
+ 4*A*B^2*a + 4*A*C^2*a + B^4 + B^3*b + 2*B^2*C^2 + 4*B^2*C*g
+ 4*B^2*b^2 + B*C^2*b + C^4 + 4*C^3*g + 4*C^2*g^2 + 2*a*b*g
sage: (q^2-q^-2)*A + q*B*C - q^-1*C*B == (q-q^-1)*a
True
sage: (q^2-q^-2)*B + q*C*A - q^-1*A*C == (q-q^-1)*b
True
sage: (q^2-q^-2)*C + q*A*B - q^-1*B*A == (q-q^-1)*g
True
sage: all(x * Omega == Omega * x for x in [A,B,C])
True
REFERENCES:
- [Terwilliger2011]_
"""
@staticmethod
def __classcall_private__(cls, R, q=None):
r"""
Normalize input to ensure a unique representation.
TESTS::
sage: R.<q> = LaurentPolynomialRing(QQ)
sage: AW1 = algebras.AskeyWilson(QQ)
sage: AW2 = algebras.AskeyWilson(R, q)
sage: AW1 is AW2
True
sage: AW = algebras.AskeyWilson(ZZ, 0)
Traceback (most recent call last):
...
ValueError: q cannot be 0
sage: AW = algebras.AskeyWilson(ZZ, 3)
Traceback (most recent call last):
...
ValueError: q=3 is not invertible in Integer Ring
"""
if q is None:
R = LaurentPolynomialRing(R, 'q')
q = R.gen()
else:
q = R(q)
if q == 0:
raise ValueError("q cannot be 0")
if 1/q not in R:
raise ValueError("q={} is not invertible in {}".format(q, R))
if R not in Rings().Commutative():
raise ValueError("{} is not a commutative ring".format(R))
return super().__classcall__(cls, R, q)
def __init__(self, R, q):
r"""
Initialize ``self``.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: TestSuite(AW).run() # long time
"""
self._q = q
cat = Algebras(Rings().Commutative()).WithBasis()
indices = cartesian_product([NonNegativeIntegers()]*6)
CombinatorialFreeModule.__init__(self, R, indices, prefix='AW',
sorting_key=_basis_key,
sorting_reverse=True,
category=cat)
self._assign_names('A,B,C,a,b,g')
def _repr_term(self, t):
r"""
Return a string representation of the basis element indexed by ``t``.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: AW._repr_term((0,0,0,0,0,0))
'1'
sage: AW._repr_term((5,1,2,3,7,2))
'A^5*B*C^2*a^3*b^7*g^2'
sage: AW._repr_term((0,1,0,3,7,2))
'B*a^3*b^7*g^2'
"""
def exp(l, e):
if e == 0:
return ''
if e == 1:
return '*' + l
return '*' + l + '^{}'.format(e)
ret = ''.join(exp(l, e) for l, e in zip(['A','B','C','a','b','g'], t))
if not ret:
return '1'
if ret[0] == '*':
ret = ret[1:]
return ret
def _latex_term(self, t):
r"""
Return a latex representation of the basis element indexed by ``t``.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: AW._latex_term((0,0,0,0,0,0))
'1'
sage: AW._latex_term((5,1,2,3,7,2))
'A^{5}BC^{2}\\alpha^{3}\\beta^{7}\\gamma^{2}'
sage: AW._latex_term((0,1,0,3,7,2))
'B\\alpha^{3}\\beta^{7}\\gamma^{2}'
"""
if sum(t) == 0:
return '1'
def exp(l, e):
if e == 0:
return ''
if e == 1:
return l
return l + '^{{{}}}'.format(e)
var_names = ['A', 'B', 'C', '\\alpha', '\\beta', '\\gamma']
return ''.join(exp(l, e) for l, e in zip(var_names, t))
def _repr_(self):
r"""
Return a string representation of ``self``.
EXAMPLES::
sage: algebras.AskeyWilson(QQ)
Askey-Wilon algebra with q=q over
Univariate Laurent Polynomial Ring in q over Rational Field
"""
return "Askey-Wilon algebra with q={} over {}".format(self._q, self.base_ring())
@cached_method
def algebra_generators(self):
r"""
Return the algebra generators of ``self``.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: G = AW.algebra_generators()
sage: G['A']
A
sage: G['a']
a
sage: list(G)
[A, B, C, a, b, g]
"""
A = self.variable_names()
def build_monomial(g):
exp = [0] * 6
exp[A.index(g)] = 1
return self.monomial(self._indices(exp))
return Family(A, build_monomial)
@cached_method
def gens(self):
r"""
Return the generators of ``self``.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: AW.gens()
(A, B, C, a, b, g)
"""
return tuple(self.algebra_generators())
@cached_method
def one_basis(self):
r"""
Return the index of the basis element `1` of ``self``.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: AW.one_basis()
(0, 0, 0, 0, 0, 0)
"""
return self._indices([0]*6)
def q(self):
r"""
Return the parameter `q` of ``self``.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: q = AW.q()
sage: q
q
sage: q.parent()
Univariate Laurent Polynomial Ring in q over Rational Field
"""
return self._q
@cached_method
def an_element(self):
r"""
Return an element of ``self``.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: AW.an_element()
(q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A
"""
q = self._q
I = self._indices
R = self.base_ring()
elt = {I((1,0,0,0,0,0)): R(1),
I((1,0,2,0,1,0)): R.an_element(),
I((0,1,0,2,0,1)): q**2 * R(3),
I((0,0,0,1,1,3)): q**-3 + R(3) + R(2)*q + q**2}
return self.element_class(self, elt)
def some_elements(self):
r"""
Return some elements of ``self``.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: AW.some_elements()
(A, B, C, a, b, g, 1,
(q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A,
q*A*B*C + q^2*A^2 - q*A*a + (q^-2)*B^2 - (q^-1)*B*b + q^2*C^2 - q*C*g)
"""
return self.gens() + (self.one(), self.an_element(), self.casimir_element())
@cached_method
def casimir_element(self):
r"""
Return the Casimir element of ``self``.
The Casimir element of the Askey-Wilson algebra `\Delta_q` is
.. MATH::
\Omega = q ABC + q^2 A^2 + q^{-2} B^2 + q^2 C^2
- q A\alpha - q^{-1} B\beta - q C\gamma.
The center `Z(\Delta_q)` is generated by `\alpha`, `\beta`,
`\gamma`, and `\Omega`.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: AW.casimir_element()
q*A*B*C + q^2*A^2 - q*A*a + (q^-2)*B^2 - (q^-1)*B*b + q^2*C^2 - q*C*g
We check that the Casimir element is in the center::
sage: Omega = AW.casimir_element()
sage: all(Omega * gen == gen * Omega for gen in AW.algebra_generators())
True
"""
q = self._q
I = self._indices
d = {I((1,1,1,0,0,0)): q, # q ABC
I((2,0,0,0,0,0)): q**2, # q^2 A^2
I((0,2,0,0,0,0)): q**-2, # q^-2 B^2
I((0,0,2,0,0,0)): q**2, # q^2 C^2
I((1,0,0,1,0,0)): -q, # -q A\alpha
I((0,1,0,0,1,0)): -q**-1, # -q^-1 B\beta
I((0,0,1,0,0,1)): -q} # -q C\gamma
return self.element_class(self, d)
@cached_method
def product_on_basis(self, x, y):
"""
Return the product of the basis elements indexed by ``x`` and ``y``.
INPUT:
- ``x``, ``y`` -- tuple of length 6
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: AW.product_on_basis((0,0,0,0,0,0), (3,5,2,0,12,3))
A^3*B^5*C^2*b^12*g^3
sage: AW.product_on_basis((0,0,0,5,3,5), (3,5,2,0,12,3))
A^3*B^5*C^2*a^5*b^15*g^8
sage: AW.product_on_basis((7,0,0,5,3,5), (0,5,2,0,12,3))
A^7*B^5*C^2*a^5*b^15*g^8
sage: AW.product_on_basis((7,3,0,5,3,5), (0,2,2,0,12,3))
A^7*B^5*C^2*a^5*b^15*g^8
sage: AW.product_on_basis((0,1,0,5,3,5), (2,0,0,0,5,3))
q^4*A^2*B*a^5*b^8*g^8 - (q^-3-q^5)*A*C*a^5*b^8*g^8
+ (1-q^4)*A*a^5*b^8*g^9 - (q^-4-2+q^4)*B*a^5*b^8*g^8
+ (q^-3-q^-1-q+q^3)*a^5*b^9*g^8
sage: AW.product_on_basis((0,2,1,0,2,0), (1,1,0,2,1,0))
q^4*A*B^3*C*a^2*b^3 - (q^5-q^9)*A^2*B^2*a^2*b^3
+ (q^2-q^4)*A*B^2*a^3*b^3 + (q^-3-q)*B^4*a^2*b^3
- (q^-2-1)*B^3*a^2*b^4 - (q-q^9)*B^2*C^2*a^2*b^3
+ (1-q^4)*B^2*C*a^2*b^3*g + (q^-4+2-5*q^4+2*q^12)*A*B*C*a^2*b^3
- (q^-1+q-2*q^3-2*q^5+q^7+q^9)*A*B*a^2*b^3*g
- (q^-3-q^3-2*q^5+q^7+q^9)*B*C*a^3*b^3
+ (q^-2-1-q^2+q^4)*B*a^3*b^3*g
- (q^-3-2*q+2*q^9-q^13)*A^2*a^2*b^3
+ (2*q^-2-2-3*q^2+3*q^4+q^10-q^12)*A*a^3*b^3
+ (q^-7-2*q^-3+2*q^5-q^9)*B^2*a^2*b^3
- (q^-6-q^-4-q^-2+1-q^2+q^4+q^6-q^8)*B*a^2*b^4
- (q^-7-q^-3-2*q+2*q^5+q^9-q^13)*C^2*a^2*b^3
+ (q^-6-3-2*q^2+5*q^4-q^8+q^10-q^12)*C*a^2*b^3*g
- (q^-1-2*q+2*q^5-q^7)*a^4*b^3
- (q^-3-q^-1-2*q+2*q^3+q^5-q^7)*a^2*b^3*g^2
"""
I = self._indices
# Commute the central parts to the right
lhs = list(x[:3])
rhs = list(y)
for i in range(3,6):
rhs[i] += x[i]
# No ABC variables on the RHS to move past
if sum(rhs[:3]) == 0:
return self.monomial(I(lhs + rhs[3:]))
# We recurse using the PBW-type basis property:
# that YX = XY + lower order terms (see Theorem 4.1 in Terwilliger).
q = self._q
if lhs[2] > 0: # lhs has a C
if rhs[0] > 0: # rhs has an A to commute with C
lhs[2] -= 1
rhs[0] -= 1
rel = {I((1,0,1,0,0,0)): q**-2, # q^2 AC
I((0,1,0,0,0,0)): q**-3 - q**1, # q^-1(q^-2-q^2) B
I((0,0,0,0,1,0)): 1 - q**-2} # -q^-1(q^-1-q) b
rel = self.element_class(self, rel)
return self.monomial(I(lhs+[0]*3)) * (rel * self.monomial(I(rhs)))
elif rhs[1] > 0: # rhs has a B to commute with C
lhs[2] -= 1
rhs[1] -= 1
rel = {I((0,1,1,0,0,0)): q**2, # q^2 BC
I((1,0,0,0,0,0)): q**3 - q**-1, # q(q^2-q^-2) A
I((0,0,0,1,0,0)): -q**2 + 1} # -q(q-q^-1) a
rel = self.element_class(self, rel)
return self.monomial(I(lhs+[0]*3)) * (rel * self.monomial(I(rhs)))
else: # nothing to commute as rhs has no A nor B
rhs[2] += lhs[2]
rhs[1] = lhs[1]
rhs[0] = lhs[0]
return self.monomial(I(rhs))
elif lhs[1] > 0: # lhs has a B
if rhs[0] > 0: # rhs has an A to commute with B
lhs[1] -= 1
rhs[0] -= 1
rel = {I((1,1,0,0,0,0)): q**2, # q^2 AB
I((0,0,1,0,0,0)): q**3 - q**-1, # q(q^2-q^-2) C
I((0,0,0,0,0,1)): -q**2 + 1} # -q(q-q^-1) g
rel = self.element_class(self, rel)
return self.monomial(I(lhs+[0]*3)) * (rel * self.monomial(I(rhs)))
else: # nothing to commute as rhs has no A
rhs[1] += lhs[1]
rhs[0] = lhs[0]
return self.monomial(I(rhs))
elif lhs[0] > 0: # lhs has an A
rhs[0] += lhs[0]
return self.monomial(I(rhs))
# otherwise, lhs is just 1
return self.monomial(I(rhs))
def permutation_automorphism(self):
r"""
Return the permutation automorphism `\rho` of ``self``.
We define the automorphism `\rho` by
.. MATH::
A \mapsto B \mapsto C \mapsto A,
\qquad
\alpha \mapsto \beta \mapsto \gamma \mapsto \alpha.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: rho = AW.permutation_automorphism()
sage: [rho(gen) for gen in AW.algebra_generators()]
[B, C, A, b, g, a]
sage: AW.an_element()
(q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A
sage: rho(AW.an_element())
(q^-3+3+2*q+q^2)*a^3*b*g + q^5*A^2*B*g + 3*q^2*C*a*b^2
- (q^-2-q^6)*A*C*g + (q-q^5)*A*g^2 - (q^-3-2*q+q^5)*B*g
+ (q^-2-1-q^2+q^4)*b*g + B
sage: r3 = rho * rho * rho
sage: [r3(gen) for gen in AW.algebra_generators()]
[A, B, C, a, b, g]
sage: r3(AW.an_element()) == AW.an_element()
True
"""
A,B,C,a,b,g = self.gens()
return AlgebraMorphism(self, [B,C,A,b,g,a], codomain=self)
rho = permutation_automorphism
def reflection_automorphism(self):
r"""
Return the reflection automorphism `\sigma` of ``self``.
We define the automorphism `\sigma` by
.. MATH::
A \mapsto B \mapsto A,
\qquad
C \mapsto C + \frac{AB - BA}{q-q^{-1}}
= C - qAB - (1+q^2) C + q \gamma,
.. MATH::
\alpha \mapsto \beta \mapsto \alpha,
\gamma \mapsto \gamma.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: sigma = AW.reflection_automorphism()
sage: [sigma(gen) for gen in AW.algebra_generators()]
[B, A, -q*A*B - q^2*C + q*g, b, a, g]
sage: AW.an_element()
(q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A
sage: sigma(AW.an_element())
q^9*A^2*B^3*a + (q^10+q^14)*A*B^2*C*a - (q^7+q^9)*A*B^2*a*g
+ (q^-3+3+2*q+q^2)*a*b*g^3 + (q-3*q^9+q^13+q^17)*A^2*B*a
- (q^2-q^6-q^8+q^14)*A*B*a^2 + 3*q^2*A*b^2*g + (q^5-q^9)*B^3*a
- (q^6-q^8)*B^2*a*b + q^13*B*C^2*a - 2*q^10*B*C*a*g + q^7*B*a*g^2
+ (q^2-2*q^10+q^18)*A*C*a - (q-q^7-2*q^9+2*q^11-q^15+q^17)*A*a*g
- (q^3-q^7-q^9+q^13)*C*a^2 + (q^2-q^6-2*q^8+2*q^10)*a^2*g
+ (q-3*q^5+3*q^9-q^13)*B*a - (q^2-q^4-2*q^6+2*q^8+q^10-q^12)*a*b + B
sage: s2 = sigma * sigma
sage: [s2(gen) for gen in AW.algebra_generators()]
[A, B, C, a, b, g]
sage: s2(AW.an_element()) == AW.an_element()
True
"""
A,B,C,a,b,g = self.gens()
q = self._q
# Note that sage: (A*B-B*A) / (q-q^-1) == -q*A*B - (1+q^2)*C + q*g
Cp = C - q*A*B - (1+q**2)*C + q*g
return AlgebraMorphism(self, [B,A,Cp,b,a,g], codomain=self)
sigma = reflection_automorphism
def loop_representation(self):
r"""
Return the map `\pi` from ``self`` to `2 \times 2` matrices
over `R[\lambda,\lambda^{-1}]`, where `F` is the fraction field
of the base ring of ``self``.
Let `AW` be the Askey-Wilson algebra over `R`, and let `F` be
the fraction field of `R`. Let `M` be the space of `2 \times 2`
matrices over `F[\lambda, \lambda^{-1}]`. Consider the following
elements of `M`:
.. MATH::
\mathcal{A} = \begin{pmatrix}
\lambda & 1 - \lambda^{-1} \\ 0 & \lambda^{-1}
\end{pmatrix},
\qquad
\mathcal{B} = \begin{pmatrix}
\lambda^{-1} & 0 \\ \lambda - 1 & \lambda
\end{pmatrix},
\qquad
\mathcal{C} = \begin{pmatrix}
1 & \lambda - 1 \\ 1 - \lambda^{-1} & \lambda + \lambda^{-1} - 1
\end{pmatrix}.
From Lemma 3.11 of [Terwilliger2011]_, we define a
representation `\pi: AW \to M` by
.. MATH::
A \mapsto q \mathcal{A} + q^{-1} \mathcal{A}^{-1},
\qquad
B \mapsto q \mathcal{B} + q^{-1} \mathcal{B}^{-1},
\qquad
C \mapsto q \mathcal{C} + q^{-1} \mathcal{C}^{-1},
.. MATH::
\alpha, \beta, \gamma \mapsto \nu I,
where `\nu = (q^2 + q^-2)(\lambda + \lambda^{-1})
+ (\lambda + \lambda^{-1})^2`.
We call this representation the *loop representation* as
it is a representation using the loop group
`SL_2(F[\lambda,\lambda^{-1}])`.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: q = AW.q()
sage: pi = AW.loop_representation()
sage: A,B,C,a,b,g = [pi(gen) for gen in AW.algebra_generators()]
sage: A
[ 1/q*lambda^-1 + q*lambda ((-q^2 + 1)/q)*lambda^-1 + ((q^2 - 1)/q)]
[ 0 q*lambda^-1 + 1/q*lambda]
sage: B
[ q*lambda^-1 + 1/q*lambda 0]
[((-q^2 + 1)/q) + ((q^2 - 1)/q)*lambda 1/q*lambda^-1 + q*lambda]
sage: C
[1/q*lambda^-1 + ((q^2 - 1)/q) + 1/q*lambda ((q^2 - 1)/q) + ((-q^2 + 1)/q)*lambda]
[ ((q^2 - 1)/q)*lambda^-1 + ((-q^2 + 1)/q) q*lambda^-1 + ((-q^2 + 1)/q) + q*lambda]
sage: a
[lambda^-2 + ((q^4 + 1)/q^2)*lambda^-1 + 2 + ((q^4 + 1)/q^2)*lambda + lambda^2 0]
[ 0 lambda^-2 + ((q^4 + 1)/q^2)*lambda^-1 + 2 + ((q^4 + 1)/q^2)*lambda + lambda^2]
sage: a == b
True
sage: a == g
True
sage: AW.an_element()
(q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A
sage: x = pi(AW.an_element())
sage: y = (q^-3+3+2*q+q^2)*a*b*g^3 + q*A*C^2*b + 3*q^2*B*a^2*g + A
sage: x == y
True
We check the defining relations of the Askey-Wilson algebra::
sage: A + (q*B*C - q^-1*C*B) / (q^2 - q^-2) == a / (q + q^-1)
True
sage: B + (q*C*A - q^-1*A*C) / (q^2 - q^-2) == b / (q + q^-1)
True
sage: C + (q*A*B - q^-1*B*A) / (q^2 - q^-2) == g / (q + q^-1)
True
We check Lemma 3.12 in [Terwilliger2011]_::
sage: M = pi.codomain()
sage: la = M.base_ring().gen()
sage: p = M([[0,-1],[1,1]])
sage: s = M([[0,1],[la,0]])
sage: rho = AW.rho()
sage: sigma = AW.sigma()
sage: all(p*pi(gen)*~p == pi(rho(gen)) for gen in AW.algebra_generators())
True
sage: all(s*pi(gen)*~s == pi(sigma(gen)) for gen in AW.algebra_generators())
True
"""
from sage.matrix.matrix_space import MatrixSpace
q = self._q
base = LaurentPolynomialRing(self.base_ring().fraction_field(), 'lambda')
la = base.gen()
inv = ~la
M = MatrixSpace(base, 2)
A = M([[la,1-inv],[0,inv]])
Ai = M([[inv,inv-1],[0,la]])
B = M([[inv,0],[la-1,la]])
Bi = M([[la,0],[1-la,inv]])
C = M([[1,1-la],[inv-1,la+inv-1]])
Ci = M([[la+inv-1,la-1],[1-inv,1]])
mu = la + inv
nu = (self._q**2 + self._q**-2) * mu + mu**2
nuI = M(nu)
# After #29374 is fixed, the category can become
# Algebras(Rings().Commutative()) as it was before #29399.
category = Rings()
return AlgebraMorphism(self, [q*A + q**-1*Ai, q*B + q**-1*Bi, q*C + q**-1*Ci,
nuI, nuI, nuI],
codomain=M, category=category)
pi = loop_representation
def _basis_key(t):
"""
Return a key for the basis element of the Askey-Wilson algebra
indexed by ``t``.
EXAMPLES::
sage: from sage.algebras.askey_wilson import _basis_key
sage: I = algebras.AskeyWilson(QQ).indices()
sage: _basis_key(I((0,2,3,1,2,5)))
(13, (0, 2, 3, 1, 2, 5))
"""
return (sum(t), t.value)
class AlgebraMorphism(ModuleMorphismByLinearity):
"""
An algebra morphism of the Askey-Wilson algebra defined by
the images of the generators.
"""
def __init__(self, domain, on_generators, position=0, codomain=None,
category=None):
"""
Given a map on the multiplicative basis of a free algebra, this method
returns the algebra morphism that is the linear extension of its image
on generators.
INPUT:
- ``domain`` -- an Askey-Wilson algebra
- ``on_generators`` -- a list of length 6 corresponding to
the images of the generators
- ``codomain`` -- (optional) the codomain
- ``position`` -- (default: 0) integer
- ``category`` -- (optional) category
OUTPUT:
- module morphism
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: sigma = AW.sigma()
sage: TestSuite(sigma).run()
"""
if category is None:
category = Algebras(Rings().Commutative()).WithBasis()
self._on_generators = tuple(on_generators)
ModuleMorphismByLinearity.__init__(self, domain=domain, codomain=codomain,
position=position, category=category)
def __eq__(self, other):
"""
Check equality.
EXAMPLES::
sage: from sage.algebras.askey_wilson import AlgebraMorphism
sage: AW = algebras.AskeyWilson(QQ)
sage: rho = AW.rho()
sage: sigma = AW.sigma()
sage: id = AlgebraMorphism(AW, AW.gens(), codomain=AW)
sage: sigma * sigma == id
True
sage: id == rho * rho * rho
True
"""
return (self.__class__ is other.__class__ and self.parent() == other.parent()
and self._zero == other._zero
and self._on_generators == other._on_generators
and self._position == other._position
and self._is_module_with_basis_over_same_base_ring
== other._is_module_with_basis_over_same_base_ring)
def _on_basis(self, c):
r"""
Computes the image of this morphism on the basis element
indexed by ``c``.
INPUT:
- ``c`` -- a tuple of length 6
OUTPUT:
- element of the codomain
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: AW.inject_variables()
Defining A, B, C, a, b, g
sage: rho = AW.rho()
sage: sigma = AW.sigma()
sage: rho._on_basis((2,1,1,2,0,5))
q^2*A*B^2*C*a^5*b^2 + (q^-3-q)*B^3*a^5*b^2 - (q^-2-1)*B^2*a^5*b^3
- (q^-3-q^5)*B*C^2*a^5*b^2 + (q^-2-q^2)*B*C*a^5*b^2*g
+ (q^-2-2*q^2+q^6)*A*C*a^5*b^2 - (q^-1-q-q^3+q^5)*C*a^6*b^2
sage: sigma._on_basis((2,1,1,2,0,5))
-q^9*A^2*B^3*b^2*g^5 + (q^2-q^10-q^14)*A*B^2*C*b^2*g^5
- (q^3-q^7-q^9)*A*B^2*b^2*g^6
- (2*q-q^5-3*q^9+q^13+q^17)*A^2*B*b^2*g^5
+ (1-q^6-q^8+q^14)*A*B*a*b^2*g^5 + (q^-3-q-q^5+q^9)*B^3*b^2*g^5
- (q^-2-1-q^6+q^8)*B^2*b^3*g^5 + (q^5-q^13)*B*C^2*b^2*g^5
- (q^2+q^6-2*q^10)*B*C*b^2*g^6 + (q^3-q^7)*B*b^2*g^7
+ (q^-6-4*q^2+2*q^6+2*q^10-q^18)*A*C*b^2*g^5
- (q^-3+q^-1-3*q-2*q^3+q^5+2*q^7+2*q^9-2*q^11+q^15-q^17)*A*b^2*g^6
- (q^-3-2*q-q^3+q^5+q^7+q^9-q^13)*C*a*b^2*g^5
+ (q^-2-1-q^2-q^4+2*q^6+2*q^8-2*q^10)*a*b^2*g^6
+ (q^-7-3*q^-3+2*q+2*q^5-3*q^9+q^13)*B*b^2*g^5
- (q^-6-q^-4-2*q^-2+2+2*q^6-2*q^8-q^10+q^12)*b^3*g^5
sage: rho(B*A)
q^2*B*C - (q^-1-q^3)*A + (1-q^2)*a
sage: rho(A*B)
B*C
sage: rho(A*B*C)
A*B*C + (q^-3-q)*B^2 - (q^-2-1)*B*b - (q^-3-q)*C^2 + (q^-2-1)*C*g
sage: rho(B*C*A)
A*B*C - (q^-3-q)*A^2 + (q^-2-1)*A*a + (q^-3-q)*B^2 - (q^-2-1)*B*b
sage: rho(C*A*B)
A*B*C
sage: rho(C^2*a*b^6*g^2)
A^2*a^2*b*g^6
sage: sigma(C^2)
q^4*A^2*B^2 + (q^3+q^7)*A*B*C - (q^2+q^4)*A*B*g
- (q^4-q^8)*A^2 + (q^5-q^7)*A*a + (1-q^4)*B^2
- (q-q^3)*B*b + q^4*C^2 - 2*q^3*C*g + q^2*g^2
sage: sigma(A*B)
q^2*A*B - (q^-1-q^3)*C + (1-q^2)*g
sage: sigma(C + 3*g*A*B)
3*q^2*A*B*g - q*A*B - (3*q^-1-3*q^3)*C*g
+ (3-3*q^2)*g^2 - q^2*C + q*g
"""
return self.codomain().prod(self._on_generators[i]**exp
for i,exp in enumerate(c))
def _composition_(self, right, homset):
"""
Return the composition of ``self`` and ``right`` in ``homset``.
EXAMPLES::
sage: AW = algebras.AskeyWilson(QQ)
sage: rho = AW.rho()
sage: sigma = AW.sigma()
sage: s2 = sigma * sigma
sage: s2._on_generators
(A, B, C, a, b, g)
sage: sr = sigma * rho
sage: sr._on_generators
(C, B, -q*B*C - q^2*A + q*a, g, b, a)
sage: rs = rho * sigma
sage: rs._on_generators
(A, -q*A*B - q^2*C + q*g, B, a, g, b)
"""
if isinstance(right, AlgebraMorphism):
cat = homset.homset_category()
return AlgebraMorphism(homset.domain(),
[right(g) for g in self._on_generators],
codomain=homset.codomain(), category=cat)
return super()._composition_(right, homset) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/askey_wilson.py | 0.895902 | 0.689378 | askey_wilson.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.misc.lazy_attribute import lazy_attribute
from sage.categories.algebras import Algebras
from sage.combinat.free_module import CombinatorialFreeModule
from sage.monoids.indexed_free_monoid import IndexedFreeAbelianMonoid
from sage.sets.positive_integers import PositiveIntegers
from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets
from sage.sets.family import Family
from sage.rings.integer_ring import ZZ
class ACEQuantumOnsagerAlgebra(CombinatorialFreeModule):
r"""
The alternating central extension of the `q`-Onsager algebra.
The *alternating central extension* `\mathcal{A}_q` of the `q`-Onsager
algebra `O_q` is a current algebra of `O_q` introduced by Baseilhac
and Koizumi [BK2005]_. A presentation was given by Baseilhac
and Shigechi [BS2010]_, which was then reformulated in terms of currents
in [Ter2021]_ and then used to prove that the generators form a PBW basis.
.. NOTE::
This is only for the `q`-Onsager algebra with parameter
`c = q^{-1} (q - q^{-1})^2`.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: AG = A.algebra_generators()
We construct the generators `\mathcal{G}_3`, `\mathcal{W}_{-5}`,
`\mathcal{W}_2`, and `\widetilde{\mathcal{G}}_{4}` and perform
some computations::
sage: G3 = AG[0,3]
sage: Wm5 = AG[1,-5]
sage: W2 = AG[1,2]
sage: Gt4 = AG[2,4]
sage: [G3, Wm5, W2, Gt4]
[G[3], W[-5], W[2], Gt[4]]
sage: Gt4 * G3
G[3]*Gt[4] + ((-q^12+3*q^8-3*q^4+1)/q^6)*W[-6]*W[1]
+ ((-q^12+3*q^8-3*q^4+1)/q^6)*W[-5]*W[2]
+ ((q^12-3*q^8+3*q^4-1)/q^6)*W[-4]*W[1]
+ ((-q^12+3*q^8-3*q^4+1)/q^6)*W[-4]*W[3]
+ ((-q^12+3*q^8-3*q^4+1)/q^6)*W[-3]*W[-2]
+ ((q^12-3*q^8+3*q^4-1)/q^6)*W[-3]*W[2]
+ ((q^12-3*q^8+3*q^4-1)/q^6)*W[-2]*W[5]
+ ((-q^12+3*q^8-3*q^4+1)/q^6)*W[-1]*W[4]
+ ((q^12-3*q^8+3*q^4-1)/q^6)*W[-1]*W[6]
+ ((-q^12+3*q^8-3*q^4+1)/q^6)*W[0]*W[5]
+ ((q^12-3*q^8+3*q^4-1)/q^6)*W[0]*W[7]
+ ((q^12-3*q^8+3*q^4-1)/q^6)*W[3]*W[4]
sage: Wm5 * G3
((q^2-1)/q^2)*G[1]*W[-7] + ((-q^2+1)/q^2)*G[1]*W[7]
+ ((q^2-1)/q^2)*G[2]*W[-6] + ((-q^2+1)/q^2)*G[2]*W[6] + G[3]*W[-5]
+ ((-q^2+1)/q^2)*G[6]*W[-2] + ((q^2-1)/q^2)*G[6]*W[2]
+ ((-q^2+1)/q^2)*G[7]*W[-1] + ((q^2-1)/q^2)*G[7]*W[1]
+ ((-q^2+1)/q^2)*G[8]*W[0] + ((-q^8+2*q^4-1)/q^5)*W[-8]
+ ((q^8-2*q^4+1)/q^5)*W[8]
sage: W2 * G3
(q^2-1)*G[1]*W[-2] + (-q^2+1)*G[1]*W[4] + (-q^2+1)*G[3]*W[0]
+ q^2*G[3]*W[2] + (q^2-1)*G[4]*W[1] + ((-q^8+2*q^4-1)/q^3)*W[-3]
+ ((q^8-2*q^4+1)/q^3)*W[5]
sage: W2 * Wm5
(q^4/(q^8+2*q^6-2*q^2-1))*G[1]*Gt[6] + (-q^4/(q^8+2*q^6-2*q^2-1))*G[6]*Gt[1]
+ W[-5]*W[2] + (q/(q^2+1))*G[7] + (-q/(q^2+1))*Gt[7]
sage: Gt4 * Wm5
((q^2-1)/q^2)*W[-8]*Gt[1] + ((q^2-1)/q^2)*W[-7]*Gt[2]
+ ((q^2-1)/q^2)*W[-6]*Gt[3] + W[-5]*Gt[4] + ((-q^2+1)/q^2)*W[-3]*Gt[6]
+ ((-q^2+1)/q^2)*W[-2]*Gt[7] + ((-q^2+1)/q^2)*W[-1]*Gt[8]
+ ((-q^2+1)/q^2)*W[0]*Gt[9] + ((q^2-1)/q^2)*W[1]*Gt[8]
+ ((q^2-1)/q^2)*W[2]*Gt[7] + ((q^2-1)/q^2)*W[3]*Gt[6]
+ ((-q^2+1)/q^2)*W[6]*Gt[3] + ((-q^2+1)/q^2)*W[7]*Gt[2]
+ ((-q^2+1)/q^2)*W[8]*Gt[1] + ((-q^8+2*q^4-1)/q^5)*W[-9]
+ ((q^8-2*q^4+1)/q^5)*W[9]
sage: Gt4 * W2
(q^2-1)*W[-3]*Gt[1] + (-q^2+1)*W[0]*Gt[4] + (q^2-1)*W[1]*Gt[5]
+ q^2*W[2]*Gt[4] + (-q^2+1)*W[5]*Gt[1] + ((-q^8+2*q^4-1)/q^3)*W[-4]
+ ((q^8-2*q^4+1)/q^3)*W[6]
REFERENCES:
- [BK2005]_
- [BS2010]_
- [Ter2021]_
"""
@staticmethod
def __classcall_private__(cls, R=None, q=None):
"""
Normalize input to ensure a unique representation.
TESTS::
sage: A1 = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: R.<q> = QQ[]
sage: q = R.gen()
sage: A2 = algebras.AlternatingCentralExtensionQuantumOnsager(R.fraction_field(), q)
sage: A1 is A2
True
sage: A2.q().parent() is R.fraction_field()
True
sage: q = R.fraction_field().gen()
sage: A3 = algebras.AlternatingCentralExtensionQuantumOnsager(q=q)
sage: A1 is A3
True
"""
if q is None:
if R is None:
raise ValueError("either base ring or q must be specified")
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
q = PolynomialRing(R, 'q').fraction_field().gen()
R = q.parent()
else:
if R is None:
R = q.parent()
else:
q = R(q)
return super().__classcall__(cls, R, q)
def __init__(self, R, q):
r"""
Initialize ``self``.
TESTS::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: TestSuite(A).run() # long time
"""
I = DisjointUnionEnumeratedSets([PositiveIntegers(), ZZ, PositiveIntegers()],
keepkey=True, facade=True)
monomials = IndexedFreeAbelianMonoid(I, prefix='A', bracket=False)
self._q = q
CombinatorialFreeModule.__init__(self, R, monomials,
prefix='', bracket=False, latex_bracket=False,
sorting_key=self._monomial_key,
category=Algebras(R).WithBasis().Filtered())
def _monomial_key(self, x):
r"""
Compute the key for ``x`` so that the comparison is done by
reverse degree lexicographic order.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: AG = A.algebra_generators()
sage: AG[1,1] * AG[1,0] * AG[0,1] # indirect doctest
G[1]*W[0]*W[1] + (q/(q^2+1))*G[1]^2 + (-q/(q^2+1))*G[1]*Gt[1]
+ ((-q^8+2*q^4-1)/q^5)*W[-1]*W[1] + ((-q^8+2*q^4-1)/q^5)*W[0]^2
+ ((q^8-2*q^4+1)/q^5)*W[0]*W[2] + ((q^8-2*q^4+1)/q^5)*W[1]^2
"""
return (-len(x), x.to_word_list())
def _repr_(self):
r"""
Return a string representation of ``self``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: A
Alternating Central Extension of q-Onsager algebra over Fraction
Field of Univariate Polynomial Ring in q over Rational Field
"""
return "Alternating Central Extension of {}-Onsager algebra over {}".format(
self._q, self.base_ring())
def _latex_(self):
r"""
Return a latex representation of ``self``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: latex(A)
\mathcal{A}_{q,\mathrm{Frac}(\Bold{Q}[q])}
"""
from sage.misc.latex import latex
return "\\mathcal{{A}}_{{{},{}}}".format(latex(self._q),
latex(self.base_ring()))
def _repr_term(self, m):
r"""
Return a string representation of the term indexed by ``m``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: I = A._indices.gens()
sage: A._repr_term(I[0,3])
'G[3]'
sage: A._repr_term(I[1,-2])
'W[-2]'
sage: A._repr_term(I[1,3])
'W[3]'
sage: A._repr_term(I[2,5])
'Gt[5]'
sage: A._repr_term(I[0,1]^2 * I[1,0] * I[1,3]^13 * I[2,3])
'G[1]^2*W[0]*W[3]^13*Gt[3]'
"""
def to_str(x):
k, e = x
if k[0] == 0:
ret = "G[{}]".format(k[1])
elif k[0] == 1:
ret = "W[{}]".format(k[1])
elif k[0] == 2:
ret = "Gt[{}]".format(k[1])
if e > 1:
ret = ret + "^{}".format(e)
return ret
return '*'.join(to_str(x) for x in m._sorted_items())
def _latex_term(self, m):
r"""
Return a latex representation of the term indexed by ``m``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: I = A._indices.gens()
sage: A._latex_term(I[0,3])
'\\mathcal{G}_{3}'
sage: A._latex_term(I[1,-2])
'\\mathcal{W}_{-2}'
sage: A._latex_term(I[1,3])
'\\mathcal{W}_{3}'
sage: A._latex_term(I[2,5])
'\\widetilde{\\mathcal{G}}_{5}'
sage: A._latex_term(I[0,1]^2 * I[1,0] * I[1,3]^13 * I[2,3])
'\\mathcal{G}_{1}^{2} \\mathcal{W}_{0} \\mathcal{W}_{3}^{13} \\widetilde{\\mathcal{G}}_{3}'
"""
def to_str(x):
k, e = x
if k[0] == 0:
ret = "\\mathcal{{G}}_{{{}}}".format(k[1])
elif k[0] == 1:
ret = "\\mathcal{{W}}_{{{}}}".format(k[1])
elif k[0] == 2:
ret = "\\widetilde{{\\mathcal{{G}}}}_{{{}}}".format(k[1])
if e > 1:
ret = ret + '^{{{}}}'.format(e)
return ret
return ' '.join(to_str(x) for x in m._sorted_items())
@cached_method
def algebra_generators(self):
r"""
Return the algebra generators of ``self``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: A.algebra_generators()
Lazy family (generator map(i))_{i in Disjoint union of
Family (Positive integers, Integer Ring, Positive integers)}
"""
G = self._indices.gens()
q = self._q
def monomial_map(x):
if x[0] != 1 and x[1] == 0:
return self.term(self.one_basis(), -(q-~q)*(q+~q)**2)
return self.monomial(G[x])
return Family(self._indices._indices, monomial_map,
name="generator map")
gens = algebra_generators
def q(self):
r"""
Return the parameter `q` of ``self``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: A.q()
q
"""
return self._q
@cached_method
def one_basis(self):
r"""
Return the basis element indexing `1`.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: ob = A.one_basis(); ob
1
sage: ob.parent()
Free abelian monoid indexed by Disjoint union of
Family (Positive integers, Integer Ring, Positive integers)
"""
return self._indices.one()
def _an_element_(self):
r"""
Return an element of ``self``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: A.an_element()
q*G[2] - 2*W[-3] + W[2] - q*Gt[1]
"""
G = self.algebra_generators()
return G[1,2] - 2*G[1,-3] + self.base_ring().an_element()*(G[0,2] - G[2,1])
def some_elements(self):
r"""
Return some elements of ``self``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: A.some_elements()
[W[0], W[3], W[-1], W[1], W[-2], G[1], G[2], Gt[1], Gt[2]]
"""
G = self.algebra_generators()
return [G[1,0], G[1,3], G[1,-1], G[1,1], G[1,-2], G[0,1], G[0,2], G[2,1], G[2,2]]
def degree_on_basis(self, m):
r"""
Return the degree of the basis element indexed by ``m``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: G = A.algebra_generators()
sage: A.degree_on_basis(G[0,1].leading_support())
2
sage: A.degree_on_basis(G[0,2].leading_support())
4
sage: A.degree_on_basis(G[1,-1].leading_support())
3
sage: A.degree_on_basis(G[1,0].leading_support())
1
sage: A.degree_on_basis(G[1,1].leading_support())
1
sage: A.degree_on_basis(G[2,1].leading_support())
2
sage: A.degree_on_basis(G[2,2].leading_support())
4
sage: [x.degree() for x in A.some_elements()]
[1, 5, 3, 1, 5, 2, 4, 2, 4]
"""
def deg(k):
if k[0] != 1:
return 2*k[1]
return -2*k[1]+1 if k[1] <= 0 else 2*k[1] - 1
return ZZ.sum(deg(k) * c for k, c in m._monomial.items())
@cached_method
def quantum_onsager_pbw_generator(self, i):
r"""
Return the image of the PBW generator of the `q`-Onsager algebra
in ``self``.
INPUT:
- ``i`` -- a pair ``(k, m)`` such that
* ``k=0`` and ``m`` is an integer
* ``k=1`` and ``m`` is a positive integer
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: A.quantum_onsager_pbw_generator((0,0))
W[1]
sage: A.quantum_onsager_pbw_generator((0,1))
(q^3/(q^4-1))*W[1]*Gt[1] - q^2*W[0] + (q^2+1)*W[2]
sage: A.quantum_onsager_pbw_generator((0,2))
(q^6/(q^8-2*q^4+1))*W[1]*Gt[1]^2 + (-q^5/(q^4-1))*W[0]*Gt[1]
+ (q^3/(q^2-1))*W[1]*Gt[2] + (q^3/(q^2-1))*W[2]*Gt[1]
+ (-q^4-q^2)*W[-1] - q^2*W[1] + (q^4+2*q^2+1)*W[3]
sage: A.quantum_onsager_pbw_generator((0,-1))
W[0]
sage: A.quantum_onsager_pbw_generator((0,-2))
(q/(q^4-1))*W[0]*Gt[1] + ((q^2+1)/q^2)*W[-1] - 1/q^2*W[1]
sage: A.quantum_onsager_pbw_generator((0,-3))
(q^2/(q^8-2*q^4+1))*W[0]*Gt[1]^2 + (1/(q^3-q))*W[-1]*Gt[1]
+ (1/(q^3-q))*W[0]*Gt[2] - (1/(q^5-q))*W[1]*Gt[1]
+ ((q^4+2*q^2+1)/q^4)*W[-2] - 1/q^2*W[0] + ((-q^2-1)/q^4)*W[2]
sage: A.quantum_onsager_pbw_generator((1,1))
((-q^2+1)/q^2)*W[0]*W[1] + (1/(q^3+q))*G[1] - (1/(q^3+q))*Gt[1]
sage: A.quantum_onsager_pbw_generator((1,2))
-1/q*W[0]*W[1]*Gt[1] + (1/(q^6+q^4-q^2-1))*G[1]*Gt[1]
+ ((-q^4+1)/q^4)*W[-1]*W[1] + (q^2-1)*W[0]^2
+ ((-q^4+1)/q^2)*W[0]*W[2] + ((q^2-1)/q^4)*W[1]^2
- (1/(q^6+q^4-q^2-1))*Gt[1]^2 + 1/q^3*G[2] - 1/q^3*Gt[2]
"""
W0 = self.algebra_generators()[1,0]
W1 = self.algebra_generators()[1,1]
q = self._q
if i[0] == 0:
if i[1] < 0:
if i[1] == -1:
return W0
Bd = self.quantum_onsager_pbw_generator((1, 1))
Bm1 = self.quantum_onsager_pbw_generator((0, i[1]+1))
Bm2 = self.quantum_onsager_pbw_generator((0, i[1]+2))
return Bm2 + q/(q**-3-~q-q+q**3) * (Bd * Bm1 - Bm1 * Bd)
else:
if i[1] == 0:
return W1
Bd = self.quantum_onsager_pbw_generator((1, 1))
Bm1 = self.quantum_onsager_pbw_generator((0, i[1]-1))
Bm2 = self.quantum_onsager_pbw_generator((0, i[1]-2))
return Bm2 - q/(q**-3-~q-q+q**3) * (Bd * Bm1 - Bm1 * Bd)
elif i[0] == 1:
if i[1] == 1:
return q**-2 * W1 * W0 - W0 * W1
if i[1] <= 0:
raise ValueError("not an index of a PBW basis element")
B = self.quantum_onsager_pbw_generator
n = i[1]
Bm1 = self.quantum_onsager_pbw_generator((0, n-1))
return (q**-2 * Bm1 * W0 - W0 * Bm1
+ (q**-2 - 1) * sum(B((0,ell)) * B((0,n-ell-2))
for ell in range(n-1)))
raise ValueError("not an index of a PBW basis element")
@cached_method
def product_on_basis(self, lhs, rhs):
r"""
Return the product of the two basis elements ``lhs`` and ``rhs``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: G = A.algebra_generators()
sage: q = A.q()
sage: rho = -(q^2 - q^-2)^2
We verify the PBW ordering::
sage: G[0,1] * G[1,1] # indirect doctest
G[1]*W[1]
sage: G[1,1] * G[0,1]
q^2*G[1]*W[1] + ((-q^8+2*q^4-1)/q^3)*W[0] + ((q^8-2*q^4+1)/q^3)*W[2]
sage: G[1,-1] * G[1,1]
W[-1]*W[1]
sage: G[1,1] * G[1,-1]
W[-1]*W[1] + (q/(q^2+1))*G[2] + (-q/(q^2+1))*Gt[2]
sage: G[1,1] * G[2,1]
W[1]*Gt[1]
sage: G[2,1] * G[1,1]
q^2*W[1]*Gt[1] + ((-q^8+2*q^4-1)/q^3)*W[0] + ((q^8-2*q^4+1)/q^3)*W[2]
sage: G[0,1] * G[2,1]
G[1]*Gt[1]
sage: G[2,1] * G[0,1]
G[1]*Gt[1] + ((-q^12+3*q^8-3*q^4+1)/q^6)*W[-1]*W[1]
+ ((-q^12+3*q^8-3*q^4+1)/q^6)*W[0]^2
+ ((q^12-3*q^8+3*q^4-1)/q^6)*W[0]*W[2]
+ ((q^12-3*q^8+3*q^4-1)/q^6)*W[1]^2
We verify some of the defining relations (see Equations (3-14)
in [Ter2021]_), which are used to construct the PBW basis::
sage: G[0,1] * G[0,2] == G[0,2] * G[0,1]
True
sage: G[1,-1] * G[1,-2] == G[1,-2] * G[1,-1]
True
sage: G[1,1] * G[1,2] == G[1,2] * G[1,1]
True
sage: G[2,1] * G[2,2] == G[2,2] * G[2,1]
True
sage: G[1,0] * G[1,2] - G[1,2] * G[1,0] == G[1,-1] * G[1,1] - G[1,1] * G[1,-1]
True
sage: G[1,0] * G[1,2] - G[1,2] * G[1,0] == (G[2,2] - G[0,2]) / (q + ~q)
True
sage: q * G[1,0] * G[0,2] - ~q * G[0,2] * G[1,0] == q * G[2,2] * G[1,0] - ~q * G[1,0] * G[2,2]
True
sage: q * G[1,0] * G[0,2] - ~q * G[0,2] * G[1,0] == rho * G[1,-2] - rho * G[1,2]
True
sage: q * G[0,2] * G[1,1] - ~q * G[1,1] * G[0,2] == q * G[1,1] * G[2,2] - ~q * G[2,2] * G[1,1]
True
sage: q * G[0,2] * G[1,1] - ~q * G[1,1] * G[0,2] == rho * G[1,3] - rho * G[1,-1]
True
sage: G[1,-2] * G[1,2] - G[1,2] * G[1,-2] == G[1,-1] * G[1,3] - G[1,3] * G[1,-1]
True
sage: G[1,-2] * G[0,2] - G[0,2] * G[1,-2] == G[1,-1] * G[0,3] - G[0,3] * G[1,-1]
True
sage: G[1,1] * G[0,2] - G[0,2] * G[1,1] == G[1,2] * G[0,1] - G[0,1] * G[1,2]
True
sage: G[1,-2] * G[2,2] - G[2,2] * G[1,-2] == G[1,-1] * G[2,3] - G[2,3] * G[1,-1]
True
sage: G[1,1] * G[2,2] - G[2,2] * G[1,1] == G[1,2] * G[2,1] - G[2,1] * G[1,2]
True
sage: G[0,1] * G[2,2] - G[2,2] * G[0,1] == G[0,2] * G[2,1] - G[2,1] * G[0,2]
True
"""
# Some trivial base cases
if lhs == self.one_basis():
return self.monomial(rhs)
if rhs == self.one_basis():
return self.monomial(lhs)
I = self._indices
B = I.gens()
q = self._q
kl = lhs.trailing_support()
kr = rhs.leading_support()
if kl <= kr:
return self.monomial(lhs * rhs)
A = self.algebra_generators()
# Create the commutator
# We have xy - yx = [x, y] -> xy = yx + LOT for x > y
if kl[0] == kr[0]:
# Commuting elements
if kl[0] != 1 or (kl[1] > 0 and kr[1] > 0) or (kl[1] <= 0 and kr[1] <= 0):
return self.monomial(lhs * B[kr]) * self.monomial(rhs // B[kr])
# relation (ii)
i = kl[1] - 1
j = -kr[1]
denom = (q**2 - q**-2) * (q + q**-1)**2
terms = A[1,-j]*A[1,i+1] + self.sum(A[0,ell]*A[2,i+j+1-ell] - A[0,i+j+1-ell]*A[2,ell] for ell in range(min(i,j)+1)) / denom
elif kl[0] == 2 and kr[0] == 0:
# relation (iii)
i = kl[1] - 1
j = kr[1] - 1
coeff = (q**2 - q**-2)**3
terms = (A[0,j+1]*A[2,i+1] - coeff * A[1,-i]*A[1,-j] + coeff * A[1,i+1]*A[1,j+1]
+ coeff * sum(A[1,-ell]*A[1,i+j+2-ell] - A[1,ell-1-i-j]*A[1,ell+1] for ell in range(min(i,j)+1))
- coeff * sum(A[1,1-ell]*A[1,i+j+1-ell] - A[1,ell-i-j]*A[1,ell] for ell in range(1, min(i,j)+1)))
elif kl[0] == 1 and kr[0] == 0:
if kl[1] > 0:
# relation (vi)
i = kl[1] - 1
j = kr[1] - 1
coeff = q * (q - ~q)
terms = (A[0,j+1]*A[1,i+1] + coeff * sum(A[0,ell]*A[1,ell-i-j] for ell in range(min(i,j)+1))
+ coeff * sum(A[0,i+j+1-ell]*A[1,ell+1] - A[0,ell]*A[1,i+j+2-ell] for ell in range(min(i,j)+1))
- coeff * sum(A[0,i+j+1-ell]*A[1,1-ell] for ell in range(1, min(i,j)+1)))
else:
# relation (v)
i = -kl[1]
j = kr[1] - 1
coeff = ~q * (q - ~q)
terms = (A[0,j+1]*A[1,-i] - coeff * sum(A[0,ell]*A[1,i+j+1-ell] for ell in range(min(i,j)+1))
+ coeff * sum(A[0,ell]*A[1,ell-1-i-j] - A[0,i+j+1-ell]*A[1,-ell] for ell in range(min(i,j)+1))
+ coeff * sum(A[0,i+j+1-ell]*A[1,ell] for ell in range(1, min(i,j)+1)))
elif kl[0] == 2 and kr[0] == 1:
if kr[1] > 0:
# relation (vi)
i = kl[1] - 1
j = kr[1] - 1
coeff = q * (q - ~q)
terms = (A[1,j+1]*A[2,i+1] + coeff * sum(A[1,ell-i-j]*A[2,ell] for ell in range(min(i,j)+1))
+ coeff * sum(A[1,ell+1]*A[2,i+j+1-ell] - A[1,i+j+2-ell]*A[2,ell] for ell in range(min(i,j)+1))
- coeff * sum(A[1,1-ell]*A[2,i+j+1-ell] for ell in range(1, min(i,j)+1)))
else:
# relation (vii)
i = kl[1] - 1
j = -kr[1]
coeff = ~q * (q - ~q)
terms = (A[1,-j]*A[2,i+1] - coeff * sum(A[1,i+j+1-ell]*A[2,ell] for ell in range(min(i,j)+1))
+ coeff * sum(A[1,ell-1-i-j]*A[2,ell] - A[1,-ell]*A[2,i+j+1-ell] for ell in range(min(i,j)+1))
+ coeff * sum(A[1,ell]*A[2,i+j+1-ell] for ell in range(1, min(i,j)+1)))
return self.monomial(lhs // B[kl]) * terms * self.monomial(rhs // B[kr])
def _sigma_on_basis(self, x):
r"""
Return the action of the `\sigma` automorphism on the basis element
indexed by ``x``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: I = A._indices.monoid_generators()
sage: A._sigma_on_basis(I[1,-1] * I[1,1])
W[0]*W[2] + (q/(q^2+1))*G[2] + (-q/(q^2+1))*Gt[2]
sage: A._sigma_on_basis(I[0,1] * I[2,1])
G[1]*Gt[1] + ((-q^12+3*q^8-3*q^4+1)/q^6)*W[-1]*W[1]
+ ((-q^12+3*q^8-3*q^4+1)/q^6)*W[0]^2
+ ((q^12-3*q^8+3*q^4-1)/q^6)*W[0]*W[2]
+ ((q^12-3*q^8+3*q^4-1)/q^6)*W[1]^2
sage: [(x, A.sigma(x)) for x in A.some_elements()]
[(W[0], W[1]), (W[3], W[-2]), (W[-1], W[2]), (W[1], W[0]),
(W[-2], W[3]), (G[1], Gt[1]), (G[2], Gt[2]), (Gt[1], G[1]),
(Gt[2], G[2])]
"""
def tw(m):
if m[0] == 0:
return (2, m[1])
if m[0] == 1:
return (1, -m[1]+1)
if m[0] == 2:
return (0, m[1])
A = self.algebra_generators()
return self.prod(A[tw(m)]**e for m,e in x._sorted_items())
def _dagger_on_basis(self, x):
r"""
Return the action of the `\dagger` antiautomorphism on the basis element
indexed by ``x``.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: I = A._indices.monoid_generators()
sage: A._dagger_on_basis(I[0,1] * I[1,-1] * I[2,1])
G[1]*W[-1]*Gt[1]
sage: A._dagger_on_basis(I[1,-1] * I[1,1])
W[-1]*W[1] + (q/(q^2+1))*G[2] + (-q/(q^2+1))*Gt[2]
sage: A._dagger_on_basis(I[0,1] * I[1,-1] * I[1,2] * I[2,1])
(q^4/(q^8+2*q^6-2*q^2-1))*G[1]^2*Gt[1]*Gt[2]
+ (-q^4/(q^8+2*q^6-2*q^2-1))*G[1]*G[2]*Gt[1]^2
+ G[1]*W[-1]*W[2]*Gt[1] + (q/(q^2+1))*G[1]*G[3]*Gt[1]
+ (-q/(q^2+1))*G[1]*Gt[1]*Gt[3]
sage: [(x, A.dagger(x)) for x in A.some_elements()]
[(W[0], W[0]), (W[3], W[3]), (W[-1], W[-1]), (W[1], W[1]),
(W[-2], W[-2]), (G[1], Gt[1]), (G[2], Gt[2]), (Gt[1], G[1]),
(Gt[2], G[2])]
"""
def tw(m):
if m[0] == 0:
return (2, m[1])
if m[0] == 1:
return (1, m[1])
if m[0] == 2:
return (0, m[1])
A = self.algebra_generators()
return self.prod(A[tw(m)]**e for m,e in reversed(x._sorted_items()))
@lazy_attribute
def sigma(self):
r"""
The automorphism `\sigma`.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: G = A.algebra_generators()
sage: x = A.an_element()^2
sage: A.sigma(A.sigma(x)) == x
True
sage: A.sigma(G[1,-1] * G[1,1]) == A.sigma(G[1,-1]) * A.sigma(G[1,1])
True
sage: A.sigma(G[0,2] * G[1,3]) == A.sigma(G[0,2]) * A.sigma(G[1,3])
True
"""
return self.module_morphism(self._sigma_on_basis, codomain=self, category=self.category())
@lazy_attribute
def dagger(self):
r"""
The antiautomorphism `\dagger`.
EXAMPLES::
sage: A = algebras.AlternatingCentralExtensionQuantumOnsager(QQ)
sage: G = A.algebra_generators()
sage: x = A.an_element()^2
sage: A.dagger(A.dagger(x)) == x
True
sage: A.dagger(G[1,-1] * G[1,1]) == A.dagger(G[1,1]) * A.dagger(G[1,-1])
True
sage: A.dagger(G[0,2] * G[1,3]) == A.dagger(G[1,3]) * A.dagger(G[0,2])
True
sage: A.dagger(G[2,2] * G[1,3]) == A.dagger(G[1,3]) * A.dagger(G[2,2])
True
"""
return self.module_morphism(self._dagger_on_basis, codomain=self) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/quantum_groups/ace_quantum_onsager.py | 0.686895 | 0.596698 | ace_quantum_onsager.py | pypi |
from .finite_dimensional_algebra_element import FiniteDimensionalAlgebraElement
from .finite_dimensional_algebra_ideal import FiniteDimensionalAlgebraIdeal
from sage.rings.integer_ring import ZZ
from sage.categories.magmatic_algebras import MagmaticAlgebras
from sage.matrix.constructor import Matrix, matrix
from sage.structure.element import is_Matrix
from sage.rings.ring import Algebra
from sage.structure.category_object import normalize_names
from sage.structure.unique_representation import UniqueRepresentation
from sage.misc.cachefunc import cached_method
from functools import reduce
class FiniteDimensionalAlgebra(UniqueRepresentation, Algebra):
r"""
Create a finite-dimensional `k`-algebra from a multiplication table.
INPUT:
- ``k`` -- a field
- ``table`` -- a list of matrices
- ``names`` -- (default: ``'e'``) string; names for the basis
elements
- ``assume_associative`` -- (default: ``False``) boolean; if
``True``, then the category is set to ``category.Associative()``
and methods requiring associativity assume this
- ``category`` -- (default:
``MagmaticAlgebras(k).FiniteDimensional().WithBasis()``)
the category to which this algebra belongs
The list ``table`` must have the following form: there exists a
finite-dimensional `k`-algebra of degree `n` with basis
`(e_1, \ldots, e_n)` such that the `i`-th element of ``table`` is the
matrix of right multiplication by `e_i` with respect to the basis
`(e_1, \ldots, e_n)`.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A
Finite-dimensional algebra of degree 2 over Finite Field of size 3
sage: TestSuite(A).run()
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,0]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,0], [0,0,0], [0,0,1]])])
sage: B
Finite-dimensional algebra of degree 3 over Rational Field
TESTS::
sage: A.category()
Category of finite dimensional magmatic algebras with basis over Finite Field of size 3
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])], assume_associative=True)
sage: A.category()
Category of finite dimensional associative algebras with basis over Finite Field of size 3
"""
@staticmethod
def __classcall_private__(cls, k, table, names='e', assume_associative=False,
category=None):
"""
Normalize input.
TESTS::
sage: table = [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])]
sage: A1 = FiniteDimensionalAlgebra(GF(3), table)
sage: A2 = FiniteDimensionalAlgebra(GF(3), table, names='e')
sage: A3 = FiniteDimensionalAlgebra(GF(3), table, names=['e0', 'e1'])
sage: A1 is A2 and A2 is A3
True
The ``assume_associative`` keyword is built into the category::
sage: from sage.categories.magmatic_algebras import MagmaticAlgebras
sage: cat = MagmaticAlgebras(GF(3)).FiniteDimensional().WithBasis()
sage: A1 = FiniteDimensionalAlgebra(GF(3), table, category=cat.Associative())
sage: A2 = FiniteDimensionalAlgebra(GF(3), table, assume_associative=True)
sage: A1 is A2
True
Uniqueness depends on the category::
sage: cat = Algebras(GF(3)).FiniteDimensional().WithBasis()
sage: A1 = FiniteDimensionalAlgebra(GF(3), table)
sage: A2 = FiniteDimensionalAlgebra(GF(3), table, category=cat)
sage: A1 == A2
False
sage: A1 is A2
False
Checking that equality is still as expected::
sage: A = FiniteDimensionalAlgebra(GF(3), table)
sage: B = FiniteDimensionalAlgebra(GF(5), [Matrix([0])])
sage: A == A
True
sage: B == B
True
sage: A == B
False
sage: A != A
False
sage: B != B
False
sage: A != B
True
"""
n = len(table)
table = [b.base_extend(k) for b in table]
for b in table:
b.set_immutable()
if not (is_Matrix(b) and b.dimensions() == (n, n)):
raise ValueError("input is not a multiplication table")
table = tuple(table)
cat = MagmaticAlgebras(k).FiniteDimensional().WithBasis()
cat = cat.or_subcategory(category)
if assume_associative:
cat = cat.Associative()
names = normalize_names(n, names)
return super().__classcall__(cls, k, table,
names, category=cat)
def __init__(self, k, table, names='e', category=None):
"""
TESTS::
sage: A = FiniteDimensionalAlgebra(QQ, [])
sage: A
Finite-dimensional algebra of degree 0 over Rational Field
sage: type(A)
<class 'sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra.FiniteDimensionalAlgebra_with_category'>
sage: TestSuite(A).run()
sage: B = FiniteDimensionalAlgebra(GF(7), [Matrix([1])])
sage: B
Finite-dimensional algebra of degree 1 over Finite Field of size 7
sage: TestSuite(B).run()
sage: C = FiniteDimensionalAlgebra(CC, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: C
Finite-dimensional algebra of degree 2 over Complex Field with 53 bits of precision
sage: TestSuite(C).run()
sage: FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]])])
Traceback (most recent call last):
...
ValueError: input is not a multiplication table
sage: D.<a,b> = FiniteDimensionalAlgebra(RR, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [-1, 0]])])
sage: D.gens()
(a, b)
sage: E = FiniteDimensionalAlgebra(QQ, [Matrix([0])])
sage: E.gens()
(e,)
"""
self._table = table
self._assume_associative = "Associative" in category.axioms()
# No further validity checks necessary!
Algebra.__init__(self, base_ring=k, names=names, category=category)
def _repr_(self):
"""
Return a string representation of ``self``.
TESTS::
sage: FiniteDimensionalAlgebra(RR, [Matrix([1])])._repr_()
'Finite-dimensional algebra of degree 1 over Real Field with 53 bits of precision'
"""
return "Finite-dimensional algebra of degree {} over {}".format(self.degree(), self.base_ring())
def _coerce_map_from_(self, S):
"""
TESTS::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.has_coerce_map_from(ZZ)
True
sage: A.has_coerce_map_from(GF(3))
True
sage: A.has_coerce_map_from(GF(5))
False
sage: A.has_coerce_map_from(QQ)
False
"""
return S == self or (self.base_ring().has_coerce_map_from(S) and self.is_unitary())
Element = FiniteDimensionalAlgebraElement
def _element_constructor_(self, x):
"""
TESTS::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([0])])
sage: a = A(0)
sage: a.parent()
Finite-dimensional algebra of degree 1 over Rational Field
sage: A(1)
Traceback (most recent call last):
...
TypeError: algebra is not unitary
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,0]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,0], [0,0,0], [0,0,1]])])
sage: B(17)
17*e0 + 17*e2
"""
return self.element_class(self, x)
# This is needed because the default implementation
# assumes that the algebra is unitary.
from_base_ring = _element_constructor_
def _Hom_(self, B, category):
"""
Construct a homset of ``self`` and ``B``.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A._Hom_(B, A.category())
Set of Homomorphisms from Finite-dimensional algebra of degree 1 over Rational Field to Finite-dimensional algebra of degree 2 over Rational Field
"""
cat = MagmaticAlgebras(self.base_ring()).FiniteDimensional().WithBasis()
if category.is_subcategory(cat):
from sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra_morphism import FiniteDimensionalAlgebraHomset
return FiniteDimensionalAlgebraHomset(self, B, category=category)
return super()._Hom_(B, category)
def ngens(self):
"""
Return the number of generators of ``self``, i.e., the degree
of ``self`` over its base field.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.ngens()
2
"""
return len(self._table)
degree = ngens
@cached_method
def gen(self, i):
"""
Return the `i`-th basis element of ``self``.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.gen(0)
e0
"""
return self.element_class(self, [j == i for j in range(self.ngens())])
@cached_method
def basis(self):
"""
Return a list of the basis elements of ``self``.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.basis()
Family (e0, e1)
"""
from sage.sets.family import Family
return Family(self.gens())
def __iter__(self):
"""
Iterates over the elements of ``self``.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: list(A)
[0, e0, 2*e0, e1, e0 + e1, 2*e0 + e1, 2*e1, e0 + 2*e1, 2*e0 + 2*e1]
This is used in the :class:`Testsuite`'s when ``self`` is
finite.
"""
if not self.is_finite():
raise NotImplementedError("object does not support iteration")
V = self.zero().vector().parent()
for v in V:
yield self(v)
def _ideal_class_(self, n=0):
"""
Return the ideal class of ``self`` (that is, the class that
all ideals of ``self`` inherit from).
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A._ideal_class_()
<class 'sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra_ideal.FiniteDimensionalAlgebraIdeal'>
"""
return FiniteDimensionalAlgebraIdeal
def table(self):
"""
Return the multiplication table of ``self``, as a list of
matrices for right multiplication by the basis elements.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.table()
(
[1 0] [0 1]
[0 1], [0 0]
)
"""
return self._table
@cached_method
def left_table(self):
"""
Return the list of matrices for left multiplication by the
basis elements.
EXAMPLES::
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0], [0,1]]), Matrix([[0,1],[-1,0]])])
sage: T = B.left_table(); T
(
[1 0] [ 0 1]
[0 1], [-1 0]
)
We check immutability::
sage: T[0] = "vandalized by h4xx0r"
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
sage: T[1][0] = [13, 37]
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).
"""
B = self.table()
n = self.degree()
table = [Matrix([B[j][i] for j in range(n)]) for i in range(n)]
for b in table:
b.set_immutable()
return tuple(table)
def base_extend(self, F):
"""
Return ``self`` base changed to the field ``F``.
EXAMPLES::
sage: C = FiniteDimensionalAlgebra(GF(2), [Matrix([1])])
sage: k.<y> = GF(4)
sage: C.base_extend(k)
Finite-dimensional algebra of degree 1 over Finite Field in y of size 2^2
"""
# Base extension of the multiplication table is done by __classcall_private__.
return FiniteDimensionalAlgebra(F, self.table())
def cardinality(self):
"""
Return the cardinality of ``self``.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(7), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [2, 3]])])
sage: A.cardinality()
49
sage: B = FiniteDimensionalAlgebra(RR, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [2, 3]])])
sage: B.cardinality()
+Infinity
sage: C = FiniteDimensionalAlgebra(RR, [])
sage: C.cardinality()
1
"""
n = self.degree()
return ZZ.one() if not n else self.base_ring().cardinality() ** n
def ideal(self, gens=None, given_by_matrix=False, side=None):
"""
Return the right ideal of ``self`` generated by ``gens``.
INPUT:
- ``A`` -- a :class:`FiniteDimensionalAlgebra`
- ``gens`` -- (default: None) - either an element of ``A`` or a
list of elements of ``A``, given as vectors, matrices, or
FiniteDimensionalAlgebraElements. If ``given_by_matrix`` is
``True``, then ``gens`` should instead be a matrix whose rows
form a basis of an ideal of ``A``.
- ``given_by_matrix`` -- boolean (default: ``False``) - if
``True``, no checking is done
- ``side`` -- ignored but necessary for coercions
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.ideal(A([1,1]))
Ideal (e0 + e1) of Finite-dimensional algebra of degree 2 over Finite Field of size 3
"""
return self._ideal_class_()(self, gens=gens,
given_by_matrix=given_by_matrix)
@cached_method
def is_associative(self):
"""
Return ``True`` if ``self`` is associative.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0], [0,1]]), Matrix([[0,1],[-1,0]])])
sage: A.is_associative()
True
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,1]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,1], [0,0,0], [1,0,0]])])
sage: B.is_associative()
False
sage: e = B.basis()
sage: (e[1]*e[2])*e[2]==e[1]*(e[2]*e[2])
False
"""
B = self.table()
n = self.degree()
for i in range(n):
for j in range(n):
eiej = B[j][i]
if B[i]*B[j] != sum(eiej[k] * B[k] for k in range(n)):
return False
return True
@cached_method
def is_commutative(self):
"""
Return ``True`` if ``self`` is commutative.
EXAMPLES::
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,0]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,0], [0,0,0], [0,0,1]])])
sage: B.is_commutative()
True
sage: C = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,0,0], [0,0,0]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,0], [0,1,0], [0,0,1]])])
sage: C.is_commutative()
False
"""
# Equivalent to self.table() == self.left_table()
B = self.table()
for i in range(self.degree()):
for j in range(i):
if B[j][i] != B[i][j]:
return False
return True
def is_finite(self):
"""
Return ``True`` if the cardinality of ``self`` is finite.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(7), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [2, 3]])])
sage: A.is_finite()
True
sage: B = FiniteDimensionalAlgebra(RR, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [2, 3]])])
sage: B.is_finite()
False
sage: C = FiniteDimensionalAlgebra(RR, [])
sage: C.is_finite()
True
"""
return self.degree() == 0 or self.base_ring().is_finite()
@cached_method
def is_unitary(self):
"""
Return ``True`` if ``self`` has a two-sided multiplicative
identity element.
.. WARNING::
This uses linear algebra; thus expect wrong results when
the base ring is not a field.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(QQ, [])
sage: A.is_unitary()
True
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0], [0,1]]), Matrix([[0,1], [-1,0]])])
sage: B.is_unitary()
True
sage: C = FiniteDimensionalAlgebra(QQ, [Matrix([[0,0], [0,0]]), Matrix([[0,0], [0,0]])])
sage: C.is_unitary()
False
sage: D = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0], [0,1]]), Matrix([[1,0], [0,1]])])
sage: D.is_unitary()
False
sage: E = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0],[1,0]]), Matrix([[0,1],[0,1]])])
sage: E.is_unitary()
False
sage: F = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,1]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,1], [0,0,0], [1,0,0]])])
sage: F.is_unitary()
True
sage: G = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,1]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,1,0], [0,0,0], [1,0,0]])])
sage: G.is_unitary() # Unique right identity, but no left identity.
False
"""
n = self.degree()
k = self.base_ring()
if n == 0:
self._one = matrix(k, 1, n)
return True
B1 = reduce(lambda x, y: x.augment(y),
self._table, Matrix(k, n, 0))
B2 = reduce(lambda x, y: x.augment(y),
self.left_table(), Matrix(k, n, 0))
# This is the vector obtained by concatenating the rows of the
# n times n identity matrix:
kone = k.one()
kzero = k.zero()
v = matrix(k, 1, n**2, (n - 1) * ([kone] + n * [kzero]) + [kone])
try:
sol1 = B1.solve_left(v)
sol2 = B2.solve_left(v)
except ValueError:
return False
assert sol1 == sol2
self._one = sol1
return True
def is_zero(self):
"""
Return ``True`` if ``self`` is the zero ring.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(QQ, [])
sage: A.is_zero()
True
sage: B = FiniteDimensionalAlgebra(GF(7), [Matrix([0])])
sage: B.is_zero()
False
"""
return self.degree() == 0
def one(self):
"""
Return the multiplicative identity element of ``self``, if it
exists.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(QQ, [])
sage: A.one()
0
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0], [0,1]]), Matrix([[0,1], [-1,0]])])
sage: B.one()
e0
sage: C = FiniteDimensionalAlgebra(QQ, [Matrix([[0,0], [0,0]]), Matrix([[0,0], [0,0]])])
sage: C.one()
Traceback (most recent call last):
...
TypeError: algebra is not unitary
sage: D = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,1]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,1], [0,0,0], [1,0,0]])])
sage: D.one()
e0
sage: E = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,1]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,1,0], [0,0,0], [1,0,0]])])
sage: E.one()
Traceback (most recent call last):
...
TypeError: algebra is not unitary
"""
if not self.is_unitary():
raise TypeError("algebra is not unitary")
else:
return self(self._one)
def random_element(self, *args, **kwargs):
"""
Return a random element of ``self``.
Optional input parameters are propagated to the ``random_element``
method of the underlying :class:`VectorSpace`.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.random_element() # random
e0 + 2*e1
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,0]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,0], [0,0,0], [0,0,1]])])
sage: B.random_element(num_bound=1000) # random
215/981*e0 + 709/953*e1 + 931/264*e2
"""
return self(self.zero().vector().parent().random_element(*args, **kwargs))
def _is_valid_homomorphism_(self, other, im_gens, base_map=None):
"""
TESTS::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: Hom(A, B)(Matrix([[1], [0]]))
Morphism from Finite-dimensional algebra of degree 2 over Rational Field to Finite-dimensional algebra of degree 1 over Rational Field given by matrix
[1]
[0]
sage: Hom(B, A)(Matrix([[1, 0]]))
Morphism from Finite-dimensional algebra of degree 1 over Rational Field to Finite-dimensional algebra of degree 2 over Rational Field given by matrix
[1 0]
sage: H = Hom(A, A)
sage: H(Matrix.identity(QQ, 2))
Morphism from Finite-dimensional algebra of degree 2 over Rational Field to Finite-dimensional algebra of degree 2 over Rational Field given by matrix
[1 0]
[0 1]
sage: H(Matrix([[1, 0], [0, 0]]))
Morphism from Finite-dimensional algebra of degree 2 over Rational Field to Finite-dimensional algebra of degree 2 over Rational Field given by matrix
[1 0]
[0 0]
sage: H(Matrix([[1, 0], [1, 1]]))
Traceback (most recent call last):
...
ValueError: relations do not all (canonically) map to 0 under map determined by images of generators
sage: Hom(B, B)(Matrix([[2]]))
Traceback (most recent call last):
...
ValueError: relations do not all (canonically) map to 0 under map determined by images of generators
"""
assert len(im_gens) == self.degree()
if base_map is None:
base_map = lambda x: x
B = self.table()
for i,gi in enumerate(im_gens):
for j,gj in enumerate(im_gens):
eiej = B[j][i]
if (sum([other(im_gens[k]) * base_map(v) for k,v in enumerate(eiej)])
!= other(gi) * other(gj)):
return False
return True
def quotient_map(self, ideal):
"""
Return the quotient of ``self`` by ``ideal``.
INPUT:
- ``ideal`` -- a ``FiniteDimensionalAlgebraIdeal``
OUTPUT:
- :class:`~sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra_morphism.FiniteDimensionalAlgebraMorphism`;
the quotient homomorphism
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: q0 = A.quotient_map(A.zero_ideal())
sage: q0
Morphism from Finite-dimensional algebra of degree 2 over Finite Field of size 3 to Finite-dimensional algebra of degree 2 over Finite Field of size 3 given by matrix
[1 0]
[0 1]
sage: q1 = A.quotient_map(A.ideal(A.gen(1)))
sage: q1
Morphism from Finite-dimensional algebra of degree 2 over Finite Field of size 3 to Finite-dimensional algebra of degree 1 over Finite Field of size 3 given by matrix
[1]
[0]
"""
k = self.base_ring()
f = ideal.basis_matrix().transpose().kernel().basis_matrix().echelon_form().transpose()
pivots = f.pivot_rows()
table = []
for p in pivots:
v = matrix(k, 1, self.degree())
v[0,p] = 1
v = self.element_class(self, v)
table.append(f.solve_right(v.matrix() * f))
B = FiniteDimensionalAlgebra(k, table)
return self.hom(f, codomain=B, check=False)
def maximal_ideal(self):
"""
Compute the maximal ideal of the local algebra ``self``.
.. NOTE::
``self`` must be unitary, commutative, associative and local
(have a unique maximal ideal).
OUTPUT:
- :class:`~sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra_ideal.FiniteDimensionalAlgebraIdeal`;
the unique maximal ideal of ``self``. If ``self`` is not a local
algebra, a ``ValueError`` is raised.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.maximal_ideal()
Ideal (0, e1) of Finite-dimensional algebra of degree 2 over Finite Field of size 3
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,0]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,0], [0,0,0], [0,0,1]])])
sage: B.maximal_ideal()
Traceback (most recent call last):
...
ValueError: algebra is not local
"""
if self.degree() == 0:
raise ValueError("the zero algebra is not local")
if not (self.is_unitary() and self.is_commutative()
and (self._assume_associative or self.is_associative())):
raise TypeError("algebra must be unitary, commutative and associative")
gens = []
for x in self.gens():
f = x.characteristic_polynomial().factor()
if len(f) != 1:
raise ValueError("algebra is not local")
if f[0][1] > 1:
gens.append(f[0][0](x))
return FiniteDimensionalAlgebraIdeal(self, gens)
def primary_decomposition(self):
"""
Return the primary decomposition of ``self``.
.. NOTE::
``self`` must be unitary, commutative and associative.
OUTPUT:
- a list consisting of the quotient maps ``self`` -> `A`,
with `A` running through the primary factors of ``self``
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.primary_decomposition()
[Morphism from Finite-dimensional algebra of degree 2 over Finite Field of size 3 to Finite-dimensional algebra of degree 2 over Finite Field of size 3 given by matrix [1 0]
[0 1]]
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,0]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,0], [0,0,0], [0,0,1]])])
sage: B.primary_decomposition()
[Morphism from Finite-dimensional algebra of degree 3 over Rational Field to Finite-dimensional algebra of degree 1 over Rational Field given by matrix [0]
[0]
[1], Morphism from Finite-dimensional algebra of degree 3 over Rational Field to Finite-dimensional algebra of degree 2 over Rational Field given by matrix [1 0]
[0 1]
[0 0]]
"""
k = self.base_ring()
n = self.degree()
if n == 0:
return []
if not (self.is_unitary() and self.is_commutative()
and (self._assume_associative or self.is_associative())):
raise TypeError("algebra must be unitary, commutative and associative")
# Start with the trivial decomposition of self.
components = [Matrix.identity(k, n)]
for b in self.table():
# Use the action of the basis element b to refine our
# decomposition of self.
components_new = []
for c in components:
# Compute the matrix of b on the component c, find its
# characteristic polynomial, and factor it.
b_c = c.solve_left(c * b)
fact = b_c.characteristic_polynomial().factor()
if len(fact) == 1:
components_new.append(c)
else:
for f in fact:
h, a = f
e = h(b_c) ** a
ker_e = e.kernel().basis_matrix()
components_new.append(ker_e * c)
components = components_new
quotients = []
for i in range(len(components)):
I = Matrix(k, 0, n)
for j,c in enumerate(components):
if j != i:
I = I.stack(c)
quotients.append(self.quotient_map(self.ideal(I, given_by_matrix=True)))
return quotients
def maximal_ideals(self):
"""
Return a list consisting of all maximal ideals of ``self``.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.maximal_ideals()
[Ideal (e1) of Finite-dimensional algebra of degree 2 over Finite Field of size 3]
sage: B = FiniteDimensionalAlgebra(QQ, [])
sage: B.maximal_ideals()
[]
"""
P = self.primary_decomposition()
return [f.inverse_image(f.codomain().maximal_ideal()) for f in P] | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra.py | 0.924743 | 0.699928 | finite_dimensional_algebra.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.rings.morphism import RingHomomorphism_im_gens
from sage.rings.homset import RingHomset_generic
from sage.structure.element import is_Matrix
class FiniteDimensionalAlgebraMorphism(RingHomomorphism_im_gens):
"""
Create a morphism between two :class:`finite-dimensional algebras <FiniteDimensionalAlgebra>`.
INPUT:
- ``parent`` -- the parent homset
- ``f`` -- matrix of the underlying `k`-linear map
- ``unitary`` -- boolean (default: ``True``); if ``True`` and ``check``
is also ``True``, raise a ``ValueError`` unless ``A`` and ``B`` are
unitary and ``f`` respects unit elements
- ``check`` -- boolean (default: ``True``); check whether the given
`k`-linear map really defines a (not necessarily unitary)
`k`-algebra homomorphism
The algebras ``A`` and ``B`` must be defined over the same base field.
EXAMPLES::
sage: from sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra_morphism import FiniteDimensionalAlgebraMorphism
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: H = Hom(A, B)
sage: f = H(Matrix([[1], [0]]))
sage: f.domain() is A
True
sage: f.codomain() is B
True
sage: f(A.basis()[0])
e
sage: f(A.basis()[1])
0
.. TODO:: An example illustrating unitary flag.
"""
def __init__(self, parent, f, check=True, unitary=True):
"""
TESTS::
sage: from sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra_morphism import FiniteDimensionalAlgebraMorphism
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: H = Hom(A, B)
sage: phi = FiniteDimensionalAlgebraMorphism(H, Matrix([[1, 0]]))
sage: TestSuite(phi).run(skip="_test_category")
"""
A = parent.domain()
B = parent.codomain()
RingHomomorphism_im_gens.__init__(self, parent=parent, im_gens=f.rows(), check=check)
self._matrix = f
if unitary and check and (not A.is_unitary()
or not B.is_unitary()
or self(A.one()) != B.one()):
raise ValueError("homomorphism does not respect unit elements")
def _repr_(self):
r"""
TESTS::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: I = A.maximal_ideal()
sage: q = A.quotient_map(I)
sage: q._repr_()
'Morphism from Finite-dimensional algebra of degree 2 over Rational Field to Finite-dimensional algebra of degree 1 over Rational Field given by matrix\n[1]\n[0]'
"""
return "Morphism from {} to {} given by matrix\n{}".format(
self.domain(), self.codomain(), self._matrix)
def __call__(self, x):
"""
TESTS::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: I = A.maximal_ideal()
sage: q = A.quotient_map(I)
sage: q(0) == 0 and q(1) == 1
True
"""
x = self.domain()(x)
B = self.codomain()
return B.element_class(B, x.vector() * self._matrix)
def __eq__(self, other):
"""
Check equality.
TESTS::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: H = Hom(A, B)
sage: phi = H(Matrix([[1, 0]]))
sage: psi = H(Matrix([[1, 0]]))
sage: phi == psi
True
sage: phi == H.zero()
False
"""
return (isinstance(other, FiniteDimensionalAlgebraMorphism)
and self.parent() == other.parent()
and self._matrix == other._matrix)
def __ne__(self, other):
"""
Check not equals.
TESTS::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: H = Hom(A, B)
sage: phi = H(Matrix([[1, 0]]))
sage: psi = H(Matrix([[1, 0]]))
sage: phi != psi
False
sage: phi != H.zero()
True
"""
return not self == other
def matrix(self):
"""
Return the matrix of ``self``.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: M = Matrix([[1], [0]])
sage: H = Hom(A, B)
sage: f = H(M)
sage: f.matrix() == M
True
"""
return self._matrix
def inverse_image(self, I):
"""
Return the inverse image of ``I`` under ``self``.
INPUT:
- ``I`` -- ``FiniteDimensionalAlgebraIdeal``, an ideal of ``self.codomain()``
OUTPUT:
-- ``FiniteDimensionalAlgebraIdeal``, the inverse image of `I` under ``self``.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: I = A.maximal_ideal()
sage: q = A.quotient_map(I)
sage: B = q.codomain()
sage: q.inverse_image(B.zero_ideal()) == I
True
"""
coker_I = I.basis_matrix().transpose().kernel().basis_matrix().transpose()
return self.domain().ideal((self._matrix * coker_I).kernel().basis_matrix(), given_by_matrix=True)
class FiniteDimensionalAlgebraHomset(RingHomset_generic):
"""
Set of morphisms between two finite-dimensional algebras.
"""
@cached_method
def zero(self):
"""
Construct the zero morphism of ``self``.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: H = Hom(A, B)
sage: H.zero()
Morphism from Finite-dimensional algebra of degree 1 over Rational Field to
Finite-dimensional algebra of degree 2 over Rational Field given by matrix
[0 0]
"""
from sage.matrix.constructor import matrix
return FiniteDimensionalAlgebraMorphism(self, matrix.zero(self.domain().ngens(),
self.codomain().ngens()),
False, False)
def __call__(self, f, check=True, unitary=True):
"""
Construct a homomorphism.
.. TODO::
Implement taking generator images and converting them to a matrix.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: H = Hom(A, B)
sage: H(Matrix([[1, 0]]))
Morphism from Finite-dimensional algebra of degree 1 over Rational Field to
Finite-dimensional algebra of degree 2 over Rational Field given by matrix
[1 0]
"""
if isinstance(f, FiniteDimensionalAlgebraMorphism):
if f.parent() is self:
return f
if f.parent() == self:
return FiniteDimensionalAlgebraMorphism(self, f._matrix, check, unitary)
elif is_Matrix(f):
return FiniteDimensionalAlgebraMorphism(self, f, check, unitary)
try:
from sage.matrix.constructor import Matrix
return FiniteDimensionalAlgebraMorphism(self, Matrix(f), check, unitary)
except Exception:
return RingHomset_generic.__call__(self, f, check) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra_morphism.py | 0.904255 | 0.698426 | finite_dimensional_algebra_morphism.py | pypi |
from .finite_dimensional_algebra_element import FiniteDimensionalAlgebraElement
from sage.matrix.constructor import Matrix
from sage.structure.element import is_Matrix
from sage.rings.ideal import Ideal_generic
from sage.structure.element import parent
from sage.misc.cachefunc import cached_method
from functools import reduce
from sage.structure.richcmp import (op_LT, op_LE, op_EQ, op_NE,
op_GT, op_GE)
class FiniteDimensionalAlgebraIdeal(Ideal_generic):
"""
An ideal of a :class:`FiniteDimensionalAlgebra`.
INPUT:
- ``A`` -- a finite-dimensional algebra
- ``gens`` -- the generators of this ideal
- ``given_by_matrix`` -- (default: ``False``) whether the basis matrix is
given by ``gens``
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A.ideal(A([0,1]))
Ideal (e1) of Finite-dimensional algebra of degree 2 over Finite Field of size 3
"""
def __init__(self, A, gens=None, given_by_matrix=False):
"""
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: I = A.ideal(A([0,1]))
sage: TestSuite(I).run(skip="_test_category") # Currently ideals are not using the category framework
"""
k = A.base_ring()
n = A.degree()
if given_by_matrix:
self._basis_matrix = gens
gens = gens.rows()
elif gens is None:
self._basis_matrix = Matrix(k, 0, n)
elif isinstance(gens, (list, tuple)):
B = [FiniteDimensionalAlgebraIdeal(A, x).basis_matrix() for x in gens]
B = reduce(lambda x, y: x.stack(y), B, Matrix(k, 0, n))
self._basis_matrix = B.echelon_form().image().basis_matrix()
elif is_Matrix(gens):
gens = FiniteDimensionalAlgebraElement(A, gens)
elif isinstance(gens, FiniteDimensionalAlgebraElement):
gens = gens.vector()
B = Matrix([(gens * b).list() for b in A.table()])
self._basis_matrix = B.echelon_form().image().basis_matrix()
Ideal_generic.__init__(self, A, gens)
def _richcmp_(self, other, op):
r"""
Comparisons
TESTS::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: I = A.ideal(A([1,1]))
sage: J = A.ideal(A([0,1]))
sage: I == J
False
sage: I == I
True
sage: I == I + J
True
sage: A2 = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: A is A2
True
sage: A == A2
True
sage: I2 = A.ideal(A([1,1]))
sage: I == I2
True
sage: I != J, I != I, I != I+J
(True, False, False)
sage: I <= J, I <= I, I <= I+J
(False, True, True)
sage: I < J, I < I, I < I+J
(False, False, False)
sage: I >= J, I >= I, I >= I+J
(True, True, True)
sage: I > J, I > I, I > I+J
(True, False, False)
sage: I = A.ideal(A([1,1]))
sage: J = A.ideal(A([0,1]))
sage: I != J
True
sage: I != I
False
sage: I != I + J
False
"""
if self.basis_matrix() == other.basis_matrix():
return op == op_EQ or op == op_LE or op == op_GE
elif op == op_EQ:
return False
elif op == op_NE:
return True
if op == op_LE or op == op_LT:
return self.vector_space().is_subspace(other.vector_space())
elif op == op_GE or op == op_GT:
return other.vector_space().is_subspace(self.vector_space())
def __contains__(self, elt):
"""
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: J = A.ideal(A([0,1]))
sage: A([0,1]) in J
True
sage: A([1,0]) in J
False
"""
if self.ring() is not parent(elt):
return False
return elt.vector() in self.vector_space()
def basis_matrix(self):
"""
Return the echelonized matrix whose rows form a basis of ``self``.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: I = A.ideal(A([1,1]))
sage: I.basis_matrix()
[1 0]
[0 1]
"""
return self._basis_matrix
@cached_method
def vector_space(self):
"""
Return ``self`` as a vector space.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: I = A.ideal(A([1,1]))
sage: I.vector_space()
Vector space of degree 2 and dimension 2 over Finite Field of size 3
Basis matrix:
[1 0]
[0 1]
"""
return self.basis_matrix().image() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/finite_dimensional_algebras/finite_dimensional_algebra_ideal.py | 0.900327 | 0.68975 | finite_dimensional_algebra_ideal.py | pypi |
from sage.arith.all import factorial
from sage.misc.misc_c import prod
from sage.misc.repr import repr_lincomb
from sage.misc.latex import latex
from sage.modules.with_basis.indexed_element import IndexedFreeModuleElement
class LCAWithGeneratorsElement(IndexedFreeModuleElement):
"""
The element class of a Lie conformal algebra with a
preferred set of generators.
"""
def T(self, n=1):
r"""
The n-th derivative of this element.
INPUT:
- ``n`` -- a non-negative integer (default:``1``); how many
times to apply `T` to this element.
We use the *divided powers* notation
`T^{(j)} = \frac{T^j}{j!}`.
EXAMPLES::
sage: Vir = lie_conformal_algebras.Virasoro(QQ)
sage: Vir.inject_variables()
Defining L, C
sage: L.T()
TL
sage: L.T(3)
6*T^(3)L
sage: C.T()
0
sage: R = lie_conformal_algebras.NeveuSchwarz(QQbar); R.inject_variables()
Defining L, G, C
sage: (L + 2*G.T() + 4*C).T(2)
2*T^(2)L + 12*T^(3)G
"""
from sage.rings.integer_ring import ZZ
if n not in ZZ or n < 0:
raise ValueError("n must be a nonnegative Integer")
if n == 0 or self.is_zero():
return self
#it's faster to sum than to use recursion
if self.is_monomial():
p = self.parent()
a,m = self.index()
coef = self._monomial_coefficients[(a,m)]
if (a,m+n) in p._indices:
return coef*prod(j for j in range(m+1,m+n+1))\
*p.monomial((a,m+n))
else:
return p.zero()
return sum(mon.T(n) for mon in self.terms())
def is_monomial(self):
"""
Whether this element is a monomial.
EXAMPLES::
sage: Vir = lie_conformal_algebras.Virasoro(QQ); L = Vir.0
sage: (L + L.T()).is_monomial()
False
sage: L.T().is_monomial()
True
"""
return len(self._monomial_coefficients) == 1 or self.is_zero()
class LCAStructureCoefficientsElement(LCAWithGeneratorsElement):
"""
An element of a Lie conformal algebra given by structure
coefficients.
"""
def _bracket_(self, right):
"""
The lambda bracket of these two elements.
The result is a dictionary with non-negative integer keys.
The value corresponding to the entry `j` is ``self_{(j)}right``.
EXAMPLES::
sage: Vir = lie_conformal_algebras.Virasoro(QQ); L = Vir.0
sage: L.bracket(L)
{0: TL, 1: 2*L, 3: 1/2*C}
sage: L.T().bracket(L)
{1: -TL, 2: -4*L, 4: -2*C}
sage: R = lie_conformal_algebras.Affine(QQbar, 'A1', names=('e','h','f')); R
The affine Lie conformal algebra of type ['A', 1] over Algebraic Field
sage: R.inject_variables()
Defining e, h, f, K
sage: e.bracket(f)
{0: h, 1: K}
sage: h.bracket(h.T())
{2: 4*K}
"""
p = self.parent()
if self.is_monomial() and right.is_monomial():
if self.is_zero() or right.is_zero():
return {}
s_coeff = p._s_coeff
a,k = self.index()
coefa = self.monomial_coefficients()[(a,k)]
b,m = right.index()
coefb = right.monomial_coefficients()[(b,m)]
try:
mbr = dict(s_coeff[(a,b)])
except KeyError:
return {}
pole = max(mbr.keys())
ret = {l: coefa*coefb*(-1)**k/factorial(k)*sum(factorial(l)\
/factorial(m+k+j-l)/factorial(l-k-j)/factorial(j)*\
mbr[j].T(m+k+j-l) for j in mbr if j >= l-m-k and\
j <= l-k) for l in range(m+k+pole+1)}
return {k: v for k, v in ret.items() if v}
diclist = [i._bracket_(j) for i in self.terms() for
j in right.terms()]
ret = {}
pz = p.zero()
for d in diclist:
for k in d:
ret[k] = ret.get(k, pz) + d[k]
return {k: v for k, v in ret.items() if v}
def _repr_(self):
r"""
A visual representation of this element.
For a free generator `L`, the element `\frac{T^{j}}{j!}L` is
denoted by ``T^(j)L``.
EXAMPLES::
sage: V = lie_conformal_algebras.Virasoro(QQ); V.inject_variables()
Defining L, C
sage: v = L.T(5).nproduct(L,6); v
-1440*L
sage: L.T(2) + L + C
2*T^(2)L + L + C
sage: L.T(4)
24*T^(4)L
sage: R = lie_conformal_algebras.Affine(QQ, 'B3')
sage: R.2.T()+3*R.3
TB[alpha[1]] + 3*B[alpha[2] + alpha[3]]
"""
if self.is_zero():
return "0"
p = self.parent()
if p._names:
terms = [("T^({}){}".format(k1, p._names[p._index_to_pos[k0]]), v) if k1 > 1
else ("T{}".format(p._names[p._index_to_pos[k0]]), v) if k1 == 1
else ("{}".format(p._names[p._index_to_pos[k0]]), v)
for (k0, k1), v in self.monomial_coefficients().items()]
else:
terms = [("T^({}){}".format(k1, p._repr_generator(k0)), v) if k1 > 1
else ("T{}".format(p._repr_generator(k0)), v) if k1 == 1
else ("{}".format(p._repr_generator(k0)), v)
for (k0, k1), v in self.monomial_coefficients().items()]
return repr_lincomb(terms, strip_one=True)
def _latex_(self):
r"""
A visual representation of this element.
For a free generator `L`, the element `\frac{T^{j}}{j!}L` is
denoted by ``T^(j)L``.
EXAMPLES::
sage: V = lie_conformal_algebras.Virasoro(QQ); V.inject_variables()
Defining L, C
sage: latex(L.T(2))
2 T^{(2)}L
sage: R = lie_conformal_algebras.Affine(QQbar, 'A1', names=('e','h','f')); R.inject_variables()
Defining e, h, f, K
sage: latex(e.bracket(f))
\left\{0 : h, 1 : K\right\}
sage: latex(e.T(3))
6 T^{(3)}e
sage: R = lie_conformal_algebras.Affine(QQbar, 'A1')
sage: latex(R.0.bracket(R.2))
\left\{0 : \alpha^\vee_{1}, 1 : \text{\texttt{K}}\right\}
sage: R = lie_conformal_algebras.Affine(QQ, 'A1'); latex(R.0.T(3))
6 T^{(3)}\alpha_{1}
"""
if self.is_zero():
return "0"
p = self.parent()
try:
names = p.latex_variable_names()
except ValueError:
names = None
if names:
terms = [("T^{{({0})}}{1}".format(k1, names[p._index_to_pos[k0]]), v) if k1 > 1
else ("T{}".format(names[p._index_to_pos[k0]]), v) if k1 == 1
else ("{}".format(names[p._index_to_pos[k0]]), v)
for (k0, k1), v in self.monomial_coefficients().items()]
else:
terms = [("T^{{({0})}}{1}".format(k1, latex(k0)), v) if k1 > 1
else ("T{}".format(latex(k0)), v) if k1 == 1
else ("{}".format(latex(k0)), v)
for (k0, k1), v in self.monomial_coefficients().items()]
return repr_lincomb(terms, is_latex=True, strip_one=True) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_element.py | 0.742982 | 0.517144 | lie_conformal_algebra_element.py | pypi |
from sage.misc.cachefunc import cached_method
from sage.structure.element import get_coercion_model
from operator import mul
from sage.categories.algebras import Algebras
from sage.monoids.indexed_free_monoid import IndexedFreeAbelianMonoid
from sage.combinat.free_module import CombinatorialFreeModule
from sage.sets.family import Family
class PoincareBirkhoffWittBasis(CombinatorialFreeModule):
r"""
The Poincare-Birkhoff-Witt (PBW) basis of the universal enveloping
algebra of a Lie algebra.
Consider a Lie algebra `\mathfrak{g}` with ordered basis
`(b_1,\dots,b_n)`. Then the universal enveloping algebra `U(\mathfrak{g})`
is generated by `b_1,\dots,b_n` and subject to the relations
.. MATH::
[b_i, b_j] = \sum_{k = 1}^n c_{ij}^k b_k
where `c_{ij}^k` are the structure coefficients of `\mathfrak{g}`. The
Poincare-Birkhoff-Witt (PBW) basis is given by the monomials
`b_1^{e_1} b_2^{e_2} \cdots b_n^{e_n}`. Specifically, we can rewrite
`b_j b_i = b_i b_j + [b_j, b_i]` where `j > i`, and we can repeat
this to sort any monomial into
.. MATH::
b_{i_1} \cdots b_{i_k} = b_1^{e_1} \cdots b_n^{e_n} + LOT
where `LOT` are lower order terms. Thus the PBW basis is a filtered basis
for `U(\mathfrak{g})`.
EXAMPLES:
We construct the PBW basis of `\mathfrak{sl}_2`::
sage: L = lie_algebras.three_dimensional_by_rank(QQ, 3, names=['E','F','H'])
sage: PBW = L.pbw_basis()
We then do some computations; in particular, we check that `[E, F] = H`::
sage: E,F,H = PBW.algebra_generators()
sage: E*F
PBW['E']*PBW['F']
sage: F*E
PBW['E']*PBW['F'] - PBW['H']
sage: E*F - F*E
PBW['H']
Next we construct another instance of the PBW basis, but sorted in the
reverse order::
sage: def neg_key(x):
....: return -L.basis().keys().index(x)
sage: PBW2 = L.pbw_basis(prefix='PBW2', basis_key=neg_key)
We then check the multiplication is preserved::
sage: PBW2(E) * PBW2(F)
PBW2['F']*PBW2['E'] + PBW2['H']
sage: PBW2(E*F)
PBW2['F']*PBW2['E'] + PBW2['H']
sage: F * E + H
PBW['E']*PBW['F']
We now construct the PBW basis for Lie algebra of regular
vector fields on `\CC^{\times}`::
sage: L = lie_algebras.regular_vector_fields(QQ)
sage: PBW = L.pbw_basis()
sage: G = PBW.algebra_generators()
sage: G[2] * G[3]
PBW[2]*PBW[3]
sage: G[3] * G[2]
PBW[2]*PBW[3] + PBW[5]
sage: G[-2] * G[3] * G[2]
PBW[-2]*PBW[2]*PBW[3] + PBW[-2]*PBW[5]
"""
@staticmethod
def __classcall_private__(cls, g, basis_key=None, prefix='PBW', **kwds):
"""
Normalize input to ensure a unique representation.
TESTS::
sage: from sage.algebras.lie_algebras.poincare_birkhoff_witt import PoincareBirkhoffWittBasis
sage: L = lie_algebras.sl(QQ, 2)
sage: P1 = PoincareBirkhoffWittBasis(L)
sage: P2 = PoincareBirkhoffWittBasis(L, prefix='PBW')
sage: P1 is P2
True
"""
return super().__classcall__(cls,
g, basis_key, prefix, **kwds)
def __init__(self, g, basis_key, prefix, **kwds):
"""
Initialize ``self``.
TESTS::
sage: L = lie_algebras.sl(QQ, 2)
sage: PBW = L.pbw_basis()
sage: E,F,H = PBW.algebra_generators()
sage: TestSuite(PBW).run(elements=[E, F, H])
sage: TestSuite(PBW).run(elements=[E, F, H, E*F + H]) # long time
"""
if basis_key is not None:
self._basis_key = basis_key
else:
self._basis_key_inverse = None
R = g.base_ring()
self._g = g
monomials = IndexedFreeAbelianMonoid(g.basis().keys(), prefix,
sorting_key=self._monoid_key, **kwds)
CombinatorialFreeModule.__init__(self, R, monomials,
prefix='', bracket=False, latex_bracket=False,
sorting_key=self._monomial_key,
category=Algebras(R).WithBasis().Filtered())
def _basis_key(self, x):
"""
Return a key for sorting for the index ``x``.
TESTS::
sage: L = lie_algebras.three_dimensional_by_rank(QQ, 3, names=['E','F','H'])
sage: PBW = L.pbw_basis()
sage: PBW._basis_key('E') < PBW._basis_key('H')
True
::
sage: L = lie_algebras.sl(QQ, 2)
sage: def neg_key(x):
....: return -L.basis().keys().index(x)
sage: PBW = L.pbw_basis(basis_key=neg_key)
sage: prod(PBW.gens()) # indirect doctest
PBW[-alpha[1]]*PBW[alphacheck[1]]*PBW[alpha[1]]
- 4*PBW[-alpha[1]]*PBW[alpha[1]]
+ PBW[alphacheck[1]]^2
- 2*PBW[alphacheck[1]]
Check that :trac:`23266` is fixed::
sage: sl2 = lie_algebras.sl(QQ, 2, 'matrix')
sage: sl2.indices()
{'e1', 'f1', 'h1'}
sage: type(sl2.basis().keys())
<... 'list'>
sage: Usl2 = sl2.pbw_basis()
sage: Usl2._basis_key(2)
2
sage: Usl2._basis_key(3)
Traceback (most recent call last):
...
KeyError: 3
"""
if self._basis_key_inverse is None:
K = self._g.basis().keys()
if isinstance(K, (list, tuple)) or K.cardinality() < float('inf'):
self._basis_key_inverse = {k: i for i,k in enumerate(K)}
else:
self._basis_key_inverse = False
if self._basis_key_inverse is False:
return x
else:
return self._basis_key_inverse[x]
def _monoid_key(self, x):
"""
Comparison key for the underlying monoid.
EXAMPLES::
sage: L = lie_algebras.sl(QQ, 2)
sage: def neg_key(x):
....: return -L.basis().keys().index(x)
sage: PBW = L.pbw_basis(basis_key=neg_key)
sage: M = PBW.basis().keys()
sage: prod(M.gens()) # indirect doctest
PBW[-alpha[1]]*PBW[alphacheck[1]]*PBW[alpha[1]]
"""
return self._basis_key(x[0])
def _monomial_key(self, x):
"""
Compute the key for ``x`` so that the comparison is done by
reverse degree lexicographic order.
EXAMPLES::
sage: L = lie_algebras.sl(QQ, 2)
sage: PBW = L.pbw_basis()
sage: E,H,F = PBW.algebra_generators()
sage: F*H*H*E # indirect doctest
PBW[alpha[1]]*PBW[alphacheck[1]]^2*PBW[-alpha[1]]
+ 8*PBW[alpha[1]]*PBW[alphacheck[1]]*PBW[-alpha[1]]
- PBW[alphacheck[1]]^3 + 16*PBW[alpha[1]]*PBW[-alpha[1]]
- 4*PBW[alphacheck[1]]^2 - 4*PBW[alphacheck[1]]
sage: def neg_key(x):
....: return -L.basis().keys().index(x)
sage: PBW = L.pbw_basis(basis_key=neg_key)
sage: E,H,F = PBW.algebra_generators()
sage: E*H*H*F # indirect doctest
PBW[-alpha[1]]*PBW[alphacheck[1]]^2*PBW[alpha[1]]
- 8*PBW[-alpha[1]]*PBW[alphacheck[1]]*PBW[alpha[1]]
+ PBW[alphacheck[1]]^3 + 16*PBW[-alpha[1]]*PBW[alpha[1]]
- 4*PBW[alphacheck[1]]^2 + 4*PBW[alphacheck[1]]
"""
return (-len(x), [self._basis_key(l) for l in x.to_word_list()])
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: L = lie_algebras.sl(QQ, 2)
sage: L.pbw_basis()
Universal enveloping algebra of
Lie algebra of ['A', 1] in the Chevalley basis
in the Poincare-Birkhoff-Witt basis
"""
return "Universal enveloping algebra of {} in the Poincare-Birkhoff-Witt basis".format(self._g)
def _coerce_map_from_(self, R):
"""
Return ``True`` if there is a coercion map from ``R`` to ``self``.
EXAMPLES:
We lift from the Lie algebra::
sage: L = lie_algebras.sl(QQ, 2)
sage: PBW = L.pbw_basis()
sage: PBW.has_coerce_map_from(L)
True
sage: [PBW(g) for g in L.basis()]
[PBW[alpha[1]], PBW[alphacheck[1]], PBW[-alpha[1]]]
We can go between PBW bases under different sorting orders::
sage: def neg_key(x):
....: return -L.basis().keys().index(x)
sage: PBW2 = L.pbw_basis(basis_key=neg_key)
sage: E,H,F = PBW.algebra_generators()
sage: PBW2(E*H*F)
PBW[-alpha[1]]*PBW[alphacheck[1]]*PBW[alpha[1]]
- 4*PBW[-alpha[1]]*PBW[alpha[1]]
+ PBW[alphacheck[1]]^2
- 2*PBW[alphacheck[1]]
We can lift from another Lie algebra and its PBW basis that
coerces into the defining Lie algebra::
sage: L = lie_algebras.sl(QQ, 2)
sage: LZ = lie_algebras.sl(ZZ, 2)
sage: L.has_coerce_map_from(LZ) and L != LZ
True
sage: PBW = L.pbw_basis()
sage: PBWZ = LZ.pbw_basis()
sage: PBW.coerce_map_from(LZ)
Composite map:
From: Lie algebra of ['A', 1] in the Chevalley basis
To: Universal enveloping algebra of Lie algebra of ['A', 1] in the Chevalley basis
in the Poincare-Birkhoff-Witt basis
Defn: Coercion map:
From: Lie algebra of ['A', 1] in the Chevalley basis
To: Lie algebra of ['A', 1] in the Chevalley basis
then
Generic morphism:
From: Lie algebra of ['A', 1] in the Chevalley basis
To: Universal enveloping algebra of Lie algebra of ['A', 1] in the Chevalley basis
in the Poincare-Birkhoff-Witt basis
sage: PBW.coerce_map_from(PBWZ)
Generic morphism:
From: Universal enveloping algebra of Lie algebra of ['A', 1] in the Chevalley basis
in the Poincare-Birkhoff-Witt basis
To: Universal enveloping algebra of Lie algebra of ['A', 1] in the Chevalley basis
in the Poincare-Birkhoff-Witt basis
TESTS:
Check that we can take the preimage (:trac:`23375`)::
sage: L = lie_algebras.cross_product(QQ)
sage: pbw = L.pbw_basis()
sage: L(pbw(L.an_element()))
X + Y + Z
sage: L(pbw(L.an_element())) == L.an_element()
True
sage: L(prod(pbw.gens()))
Traceback (most recent call last):
...
ValueError: PBW['X']*PBW['Y']*PBW['Z'] is not in the image
sage: L(pbw.one())
Traceback (most recent call last):
...
ValueError: 1 is not in the image
"""
if R == self._g:
# Make this into the lift map
I = self._indices
def basis_function(x):
return self.monomial(I.gen(x))
def inv_supp(m):
return None if m.length() != 1 else m.leading_support()
# TODO: this diagonal, but with a smaller indexing set...
return self._g.module_morphism(basis_function, codomain=self,
triangular='upper', unitriangular=True,
inverse_on_support=inv_supp)
coerce_map = self._g.coerce_map_from(R)
if coerce_map:
return self.coerce_map_from(self._g) * coerce_map
if isinstance(R, PoincareBirkhoffWittBasis):
if self._g == R._g:
I = self._indices
def basis_function(x):
return self.prod(self.monomial(I.gen(g)**e)
for g, e in x._sorted_items())
# TODO: this diagonal, but with a smaller indexing set...
return R.module_morphism(basis_function, codomain=self)
coerce_map = self._g.coerce_map_from(R._g)
if coerce_map:
I = self._indices
lift = self.coerce_map_from(self._g)
def basis_function(x):
return self.prod(lift(coerce_map(g))**e
for g, e in x._sorted_items())
# TODO: this diagonal, but with a smaller indexing set...
return R.module_morphism(basis_function, codomain=self)
return super()._coerce_map_from_(R)
def lie_algebra(self):
"""
Return the underlying Lie algebra of ``self``.
EXAMPLES::
sage: L = lie_algebras.sl(QQ, 2)
sage: PBW = L.pbw_basis()
sage: PBW.lie_algebra() is L
True
"""
return self._g
def algebra_generators(self):
"""
Return the algebra generators of ``self``.
EXAMPLES::
sage: L = lie_algebras.sl(QQ, 2)
sage: PBW = L.pbw_basis()
sage: PBW.algebra_generators()
Finite family {alpha[1]: PBW[alpha[1]], alphacheck[1]: PBW[alphacheck[1]], -alpha[1]: PBW[-alpha[1]]}
"""
G = self._indices.gens()
return Family(self._indices._indices, lambda x: self.monomial(G[x]),
name="generator map")
gens = algebra_generators
@cached_method
def one_basis(self):
"""
Return the basis element indexing `1`.
EXAMPLES::
sage: L = lie_algebras.three_dimensional_by_rank(QQ, 3, names=['E','F','H'])
sage: PBW = L.pbw_basis()
sage: ob = PBW.one_basis(); ob
1
sage: ob.parent()
Free abelian monoid indexed by {'E', 'F', 'H'}
"""
return self._indices.one()
@cached_method
def product_on_basis(self, lhs, rhs):
"""
Return the product of the two basis elements ``lhs`` and ``rhs``.
EXAMPLES::
sage: L = lie_algebras.three_dimensional_by_rank(QQ, 3, names=['E','F','H'])
sage: PBW = L.pbw_basis()
sage: I = PBW.indices()
sage: PBW.product_on_basis(I.gen('E'), I.gen('F'))
PBW['E']*PBW['F']
sage: PBW.product_on_basis(I.gen('E'), I.gen('H'))
PBW['E']*PBW['H']
sage: PBW.product_on_basis(I.gen('H'), I.gen('E'))
PBW['E']*PBW['H'] + 2*PBW['E']
sage: PBW.product_on_basis(I.gen('F'), I.gen('E'))
PBW['E']*PBW['F'] - PBW['H']
sage: PBW.product_on_basis(I.gen('F'), I.gen('H'))
PBW['F']*PBW['H']
sage: PBW.product_on_basis(I.gen('H'), I.gen('F'))
PBW['F']*PBW['H'] - 2*PBW['F']
sage: PBW.product_on_basis(I.gen('H')**2, I.gen('F')**2)
PBW['F']^2*PBW['H']^2 - 8*PBW['F']^2*PBW['H'] + 16*PBW['F']^2
sage: E,F,H = PBW.algebra_generators()
sage: E*F - F*E
PBW['H']
sage: H * F * E
PBW['E']*PBW['F']*PBW['H'] - PBW['H']^2
sage: E * F * H * E
PBW['E']^2*PBW['F']*PBW['H'] + 2*PBW['E']^2*PBW['F']
- PBW['E']*PBW['H']^2 - 2*PBW['E']*PBW['H']
TESTS:
Check that :trac:`23268` is fixed::
sage: MS = MatrixSpace(QQ, 2,2)
sage: gl = LieAlgebra(associative=MS)
sage: Ugl = gl.pbw_basis()
sage: prod(Ugl.gens())
PBW[(0, 0)]*PBW[(0, 1)]*PBW[(1, 0)]*PBW[(1, 1)]
sage: prod(reversed(list(Ugl.gens())))
PBW[(0, 0)]*PBW[(0, 1)]*PBW[(1, 0)]*PBW[(1, 1)]
- PBW[(0, 0)]^2*PBW[(1, 1)] + PBW[(0, 0)]*PBW[(1, 1)]^2
"""
# Some trivial base cases
if lhs == self.one_basis():
return self.monomial(rhs)
if rhs == self.one_basis():
return self.monomial(lhs)
I = self._indices
trail = lhs.trailing_support()
lead = rhs.leading_support()
if self._basis_key(trail) <= self._basis_key(lead):
return self.monomial(lhs * rhs)
# Create the commutator
# We have xy - yx = [x, y] -> xy = yx + [x, y] and we have x > y
terms = self._g.monomial(trail).bracket(self._g.monomial(lead))
lead = I.gen(lead)
trail = I.gen(trail)
mc = terms.monomial_coefficients(copy=False)
terms = self.sum_of_terms((I.gen(t), c) for t,c in mc.items())
terms += self.monomial(lead * trail)
return self.monomial(lhs // trail) * terms * self.monomial(rhs // lead)
def degree_on_basis(self, m):
"""
Return the degree of the basis element indexed by ``m``.
EXAMPLES::
sage: L = lie_algebras.sl(QQ, 2)
sage: PBW = L.pbw_basis()
sage: E,H,F = PBW.algebra_generators()
sage: PBW.degree_on_basis(E.leading_support())
1
sage: m = ((H*F)^10).trailing_support(key=PBW._monomial_key) # long time
sage: PBW.degree_on_basis(m) # long time
20
sage: ((H*F*E)^4).maximal_degree() # long time
12
"""
return m.length()
class Element(CombinatorialFreeModule.Element):
def _act_on_(self, x, self_on_left):
"""
Return the action of ``self`` on ``x`` by seeing if there is an
action of the defining Lie algebra.
EXAMPLES::
sage: L = lie_algebras.VirasoroAlgebra(QQ)
sage: d = L.basis()
sage: x = d[-1]*d[-2]*d[-1] + 3*d[-3]
sage: x
PBW[-2]*PBW[-1]^2 + PBW[-3]*PBW[-1] + 3*PBW[-3]
sage: M = L.verma_module(1/2,3/4)
sage: v = M.highest_weight_vector()
sage: x * v
3*d[-3]*v + d[-3]*d[-1]*v + d[-2]*d[-1]*d[-1]*v
"""
# Try the _acted_upon_ first as it might have a direct PBW action
# implemented that is faster
ret = x._acted_upon_(self, not self_on_left)
if ret is not None:
return ret
cm = get_coercion_model()
L = self.parent()._g
if self_on_left:
if cm.discover_action(L, x.parent(), mul):
ret = x.parent().zero()
for mon, coeff in self._monomial_coefficients.items():
term = coeff * x
for k, exp in reversed(mon._sorted_items()):
for _ in range(exp):
term = L.monomial(k) * term
ret += term
return ret
else:
if cm.discover_action(x.parent(), L, mul):
ret = x.parent().zero()
for mon, coeff in self._monomial_coefficients.items():
term = coeff * x
for k, exp in reversed(mon._sorted_items()):
for _ in range(exp):
term = term * L.monomial(k)
ret += term
return ret
return None | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/algebras/lie_algebras/poincare_birkhoff_witt.py | 0.897819 | 0.575916 | poincare_birkhoff_witt.py | pypi |
r"""
Scheme implementation overview
Various parts of schemes were implemented by different authors. This document
aims to give an overview of the different classes of schemes working together
coherently.
Generic
-------
- **Scheme:**
A scheme whose datatype might not be defined in terms of algebraic equations:
e.g. the Jacobian of a curve may be represented by means of a Scheme.
- **AlgebraicScheme:**
A scheme defined by means of polynomial equations, which may be reducible or
defined over a ring other than a field. In particular, the defining ideal
need not be a radical ideal, and an algebraic scheme may be defined over
`\mathrm{Spec}(R)`.
- **AmbientSpaces:**
Most effective models of algebraic scheme will be defined not by generic
gluings, but by embeddings in some fixed ambient space.
Ambients
--------
- **AffineSpace:**
Affine spaces and their affine subschemes form the most important universal
objects from which algebraic schemes are built. The affine spaces form
universal objects in the sense that a morphism is uniquely determined by the
images of its coordinate functions and any such images determine a
well-defined morphism.
By default affine spaces will embed in some ordinary projective space, unless
it is created as an affine patch of another object.
- **ProjectiveSpace:**
Projective spaces are the most natural ambient spaces for most projective
objects. They are locally universal objects.
- **ProjectiveSpace_ordinary (not implemented):**
The ordinary projective spaces have the standard weights `[1,..,1]` on their
coefficients.
- **ProjectiveSpace_weighted (not implemented):**
A special subtype for non-standard weights.
- **ToricVariety:**
Toric varieties are (partial) compactifications of algebraic tori `(\CC^*)^n`
compatible with torus action. Affine and projective spaces are examples of
toric varieties, but it is not envisioned that these special cases should
inherit from :class:`~sage.schemes.toric.variety.ToricVariety`.
Subschemes
----------
- **AlgebraicScheme_subscheme_affine:**
An algebraic scheme defined by means of an embedding in a
fixed ambient affine space.
- **AlgebraicScheme_subscheme_projective:**
An algebraic scheme defined by means of an embedding in a fixed ambient
projective space.
- **QuasiAffineScheme (not yet implemented):**
An open subset `U = X \setminus Z` of a closed subset `X` of affine space;
note that this is mathematically a quasi-projective scheme, but its
ambient space is an affine space and its points are represented by
affine rather than projective points.
.. NOTE::
AlgebraicScheme_quasi is implemented, as a base class for this.
- **QuasiProjectiveScheme (not yet implemented):**
An open subset of a closed subset of projective space; this datatype
stores the defining polynomial, polynomials, or ideal defining the
projective closure `X` plus the closed subscheme `Z` of `X` whose complement
`U = X \setminus Z` is the quasi-projective scheme.
.. NOTE::
The quasi-affine and quasi-projective datatype lets one create schemes
like the multiplicative group scheme
`\mathbb{G}_m = \mathbb{A}^1\setminus \{(0)\}`
and the non-affine scheme `\mathbb{A}^2\setminus \{(0,0)\}`. The latter
is not affine and is not of the form `\mathrm{Spec}(R)`.
Point sets
----------
- **PointSets and points over a ring (to do):**
For algebraic schemes `X/S` and `T/S` over `S`, one can form the point set
`X(T)` of morphisms from `T\to X` over `S`.
A projective space object in the category of schemes is a locally free object
-- the images of the generator functions *locally* determine a point. Over a
field, one can choose one of the standard affine patches by the condition
that a coordinate function `X_i \ne 0`.
::
sage: PP.<X,Y,Z> = ProjectiveSpace(2, QQ)
sage: PP
Projective Space of dimension 2 over Rational Field
sage: PP(QQ)
Set of rational points of Projective Space
of dimension 2 over Rational Field
sage: PP(QQ)([-2, 3, 5])
(-2/5 : 3/5 : 1)
Over a ring, this is not true anymore. For example, even over an integral
domain which is not a PID, there may be no *single* affine patch which covers
a point.
::
sage: R.<x> = ZZ[]
sage: S.<t> = R.quo(x^2+5)
sage: P.<X,Y,Z> = ProjectiveSpace(2, S)
sage: P(S)
Set of rational points of Projective Space of dimension 2 over
Univariate Quotient Polynomial Ring in t over Integer Ring with
modulus x^2 + 5
In order to represent the projective point `(2:1+t) = (1-t:3)` we note that
the first representative is not well-defined at the prime `p = (2,1+t)` and
the second element is not well-defined at the prime `q = (1-t,3)`, but that
`p + q = (1)`, so globally the pair of coordinate representatives is
well-defined.
::
sage: P([2, 1 + t])
(2 : t + 1 : 1)
In fact, we need a test ``R.ideal([2, 1 + t]) == R.ideal([1])`` in order to make
this meaningful.
Berkovich Analytic Spaces
-------------------------
- **Berkovich Analytic Space (not yet implemented)**
The construction of analytic spaces from schemes due to Berkovich. Any Berkovich
space should inherit from :class:`Berkovich`
- **Berkovich Analytic Space over Cp**
A special case of the general Berkovich analytic space construction.
Affine Berkovich space over `\CC_p` is the set of seminorms on the polynomial
ring `\CC_p[x]`, while projective Berkovich space over `\CC_p` is the one-point compactification
of affine Berkovich space `\CC_p`. Points are represented using the classification (due
to Berkovich) of a corresponding decreasing sequence of disks in `\CC_p`.
AUTHORS:
- David Kohel, William Stein (2006-01-03): initial version
- Andrey Novoseltsev (2010-09-24): updated due to addition of toric varieties
""" | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/overview.py | 0.952386 | 0.86293 | overview.py | pypi |
from sage.schemes.generic.morphism import SchemeMorphism_polynomial
class WeierstrassTransformation(SchemeMorphism_polynomial):
def __init__(self, domain, codomain, defining_polynomials, post_multiplication):
r"""
A morphism of a genus-one curve to/from the Weierstrass form.
INPUT:
- ``domain``, ``codomain`` -- two schemes, one of which is an
elliptic curve.
- ``defining_polynomials`` -- triplet of polynomials that
define the transformation.
- ``post_multiplication`` -- a polynomial to homogeneously
rescale after substituting the defining polynomials.
EXAMPLES::
sage: P2.<u,v,w> = ProjectiveSpace(2,QQ)
sage: C = P2.subscheme(u^3 + v^3 + w^3)
sage: E = EllipticCurve([2, -1, -1/3, 1/3, -1/27])
sage: from sage.schemes.elliptic_curves.weierstrass_transform import WeierstrassTransformation
sage: f = WeierstrassTransformation(C, E, [w, -v-w, -3*u-3*v], 1); f
Scheme morphism:
From: Closed subscheme of Projective Space of dimension 2 over Rational Field defined by:
u^3 + v^3 + w^3
To: Elliptic Curve defined by y^2 + 2*x*y - 1/3*y = x^3 - x^2 + 1/3*x - 1/27
over Rational Field
Defn: Defined on coordinates by sending (u : v : w) to
(w : -v - w : -3*u - 3*v)
sage: f([-1, 1, 0])
(0 : 1 : 0)
sage: f([-1, 0, 1])
(1/3 : -1/3 : 1)
sage: f([ 0,-1, 1])
(1/3 : 0 : 1)
sage: A2.<a,b> = AffineSpace(2,QQ)
sage: C = A2.subscheme(a^3 + b^3 + 1)
sage: f = WeierstrassTransformation(C, E, [1, -b-1, -3*a-3*b], 1); f
Scheme morphism:
From: Closed subscheme of Affine Space of dimension 2 over Rational Field defined by:
a^3 + b^3 + 1
To: Elliptic Curve defined by y^2 + 2*x*y - 1/3*y
= x^3 - x^2 + 1/3*x - 1/27 over Rational Field
Defn: Defined on coordinates by sending (a, b) to
(1 : -b - 1 : -3*a - 3*b)
sage: f([-1,0])
(1/3 : -1/3 : 1)
sage: f([0,-1])
(1/3 : 0 : 1)
"""
Hom = domain.Hom(codomain)
super().__init__(Hom, defining_polynomials)
self._post = post_multiplication
def post_rescaling(self):
"""
Return the homogeneous rescaling to apply after the coordinate
substitution.
OUTPUT:
A polynomial. See the example below.
EXAMPLES::
sage: R.<a,b,c> = QQ[]
sage: cubic = a^3+7*b^3+64*c^3
sage: P = [2,2,-1]
sage: f = EllipticCurve_from_cubic(cubic, P, morphism=True).inverse()
sage: f.post_rescaling()
-1/7
So here is what it does. If we just plug in the coordinate
transformation, we get the defining polynomial up to
scale. This method returns the overall rescaling of the
equation to bring the result into the standard form::
sage: cubic(f.defining_polynomials())
7*x^3 - 7*y^2*z + 1806336*y*z^2 - 155373797376*z^3
sage: cubic(f.defining_polynomials()) * f.post_rescaling()
-x^3 + y^2*z - 258048*y*z^2 + 22196256768*z^3
"""
return self._post
def WeierstrassTransformationWithInverse(domain, codomain,
defining_polynomials, post_multiplication,
inv_defining_polynomials, inv_post_multiplication):
"""
Construct morphism of a genus-one curve to/from the Weierstrass
form with its inverse.
EXAMPLES::
sage: R.<u,v,w> = QQ[]
sage: f = EllipticCurve_from_cubic(u^3 + v^3 + w^3, [1,-1,0], morphism=True); f
Scheme morphism:
From: Projective Plane Curve over Rational Field defined by u^3 + v^3 + w^3
To: Elliptic Curve defined by y^2 - 9*y = x^3 - 27 over Rational Field
Defn: Defined on coordinates by sending (u : v : w) to
(-w : 3*u : 1/3*u + 1/3*v)
Scheme morphism:
From: Closed subscheme of Projective Space of dimension 2 over Rational Field defined by:
u^3 + v^3 + w^3
To: Elliptic Curve defined by y^2 + 2*x*y + 1/3*y
= x^3 - x^2 - 1/3*x - 1/27 over Rational Field
Defn: Defined on coordinates by sending (u : v : w) to
(-w : -v + w : 3*u + 3*v)
"""
fwd = WeierstrassTransformationWithInverse_class(
domain, codomain, defining_polynomials, post_multiplication)
inv = WeierstrassTransformationWithInverse_class(
codomain, domain, inv_defining_polynomials, inv_post_multiplication)
fwd._inverse = inv
inv._inverse = fwd
return fwd
class WeierstrassTransformationWithInverse_class(WeierstrassTransformation):
def inverse(self):
"""
Return the inverse.
OUTPUT:
A morphism in the opposite direction. This may be a rational
inverse or an analytic inverse.
EXAMPLES::
sage: R.<u,v,w> = QQ[]
sage: f = EllipticCurve_from_cubic(u^3 + v^3 + w^3, [1,-1,0], morphism=True)
sage: f.inverse()
Scheme morphism:
From: Elliptic Curve defined by y^2 - 9*y = x^3 - 27 over Rational Field
To: Projective Plane Curve over Rational Field defined by u^3 + v^3 + w^3
Defn: Defined on coordinates by sending (x : y : z) to
(1/3*y : -1/3*y + 3*z : -x)
"""
return self._inverse | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/elliptic_curves/weierstrass_transform.py | 0.952816 | 0.651204 | weierstrass_transform.py | pypi |
from .ell_field import EllipticCurve_field
from . import ell_point
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
# Elliptic curves are very different than genus > 1 hyperelliptic curves,
# there is an "is a" relationship here, and common implementation with regard
# Coleman integration.
from sage.schemes.hyperelliptic_curves.hyperelliptic_padic_field import HyperellipticCurve_padic_field
class EllipticCurve_padic_field(EllipticCurve_field, HyperellipticCurve_padic_field):
"""
Elliptic curve over a padic field.
EXAMPLES::
sage: Qp=pAdicField(17)
sage: E=EllipticCurve(Qp,[2,3]); E
Elliptic Curve defined by y^2 = x^3 + (2+O(17^20))*x + (3+O(17^20)) over 17-adic Field with capped relative precision 20
sage: E == loads(dumps(E))
True
"""
_point = ell_point.EllipticCurvePoint_field
_genus = 1
def frobenius(self, P=None):
"""
Return the Frobenius as a function on the group of points of
this elliptic curve.
EXAMPLES::
sage: Qp = pAdicField(13)
sage: E = EllipticCurve(Qp,[1,1])
sage: type(E.frobenius())
<... 'function'>
sage: point = E(0,1)
sage: E.frobenius(point)
(0 : 1 + O(13^20) : 1 + O(13^20))
Check that :trac:`29709` is fixed::
sage: Qp = pAdicField(13)
sage: E = EllipticCurve(Qp,[0,0,1,0,1])
sage: E.frobenius(E(1,1))
Traceback (most recent call last):
...
NotImplementedError: Curve must be in weierstrass normal form.
sage: E = EllipticCurve(Qp,[0,1,0,0,1])
sage: E.frobenius(E(0,1))
(0 : 1 + O(13^20) : 1 + O(13^20))
"""
try:
_frob = self._frob
except AttributeError:
K = self.base_field()
p = K.prime()
x = PolynomialRing(K, 'x').gen(0)
a1, a2, a3, a4, a6 = self.a_invariants()
if a1 != 0 or a3 != 0:
raise NotImplementedError("Curve must be in weierstrass normal form.")
f = x*x*x + a2*x*x + a4*x + a6
h = (f(x**p) - f**p)
# internal function: I don't know how to doctest it...
def _frob(P):
x0 = P[0]
y0 = P[1]
uN = (1 + h(x0)/y0**(2*p)).sqrt()
yres = y0**p * uN
xres = x0**p
if (yres-y0).valuation() == 0:
yres = -yres
return self.point([xres, yres, K(1)])
self._frob = _frob
if P is None:
return _frob
else:
return _frob(P) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/elliptic_curves/ell_padic_field.py | 0.782164 | 0.513181 | ell_padic_field.py | pypi |
r"""
Scalar-multiplication morphisms of elliptic curves
This class provides an :class:`EllipticCurveHom` instantiation for
multiplication-by-`m` maps on elliptic curves.
EXAMPLES:
We can construct and evaluate scalar multiplications::
sage: from sage.schemes.elliptic_curves.hom_scalar import EllipticCurveHom_scalar
sage: E = EllipticCurve('77a1')
sage: phi = E.scalar_multiplication(5); phi
Scalar-multiplication endomorphism [5] of Elliptic Curve defined by y^2 + y = x^3 + 2*x over Rational Field
sage: P = E(2,3)
sage: phi(P)
(30 : 164 : 1)
The usual :class:`EllipticCurveHom` methods are supported::
sage: phi.degree()
25
sage: phi.kernel_polynomial()
x^12 + 124/5*x^10 + 19*x^9 - 84*x^8 + 24*x^7 - 483*x^6 - 696/5*x^5 - 448*x^4 - 37*x^3 - 332*x^2 - 84*x + 47/5
sage: phi.rational_maps()
((x^25 - 200*x^23 - 520*x^22 + 9000*x^21 + ... + 1377010*x^3 + 20360*x^2 - 39480*x + 2209),
(10*x^36*y - 620*x^36 + 3240*x^34*y - 44880*x^34 + ... + 424927560*x*y + 226380480*x + 42986410*y + 20974090)/(1250*x^36 + 93000*x^34 + 71250*x^33 + 1991400*x^32 + ... + 1212964050*x^3 + 138715800*x^2 - 27833400*x + 1038230))
sage: phi.dual()
Scalar-multiplication endomorphism [5] of Elliptic Curve defined by y^2 + y = x^3 + 2*x over Rational Field
sage: phi.dual() is phi
True
sage: phi.formal()
5*t - 310*t^4 - 2496*t^5 + 10540*t^7 + ... - 38140146674516*t^20 - 46800256902400*t^21 + 522178541079910*t^22 + O(t^23)
sage: phi.is_normalized()
False
sage: phi.is_separable()
True
sage: phi.is_injective()
False
sage: phi.is_surjective()
True
Contrary to constructing an :class:`EllipticCurveIsogeny` from
the division polynomial, :class:`EllipticCurveHom_scalar` can
deal with huge scalars very quickly::
sage: E = EllipticCurve(GF(2^127-1), [1,2,3,4,5])
sage: phi = E.scalar_multiplication(9^99); phi
Scalar-multiplication endomorphism [29512665430652752148753480226197736314359272517043832886063884637676943433478020332709411004889] of Elliptic Curve defined by y^2 + x*y + 3*y = x^3 + 2*x^2 + 4*x + 5 over Finite Field of size 170141183460469231731687303715884105727
sage: phi(E(1,2))
(82124533143060719620799539030695848450 : 17016022038624814655722682134021402379 : 1)
Composition of scalar multiplications results in another scalar
multiplication::
sage: E = EllipticCurve(GF(19), [4,4])
sage: phi = E.scalar_multiplication(-3); phi
Scalar-multiplication endomorphism [-3] of Elliptic Curve defined by y^2 = x^3 + 4*x + 4 over Finite Field of size 19
sage: psi = E.scalar_multiplication(7); psi
Scalar-multiplication endomorphism [7] of Elliptic Curve defined by y^2 = x^3 + 4*x + 4 over Finite Field of size 19
sage: phi * psi
Scalar-multiplication endomorphism [-21] of Elliptic Curve defined by y^2 = x^3 + 4*x + 4 over Finite Field of size 19
sage: psi * phi
Scalar-multiplication endomorphism [-21] of Elliptic Curve defined by y^2 = x^3 + 4*x + 4 over Finite Field of size 19
sage: phi * psi == psi * phi
True
sage: -phi == E.scalar_multiplication(-1) * phi
True
The zero endomorphism `[0]` is supported::
sage: E = EllipticCurve(GF(71), [1,1])
sage: zero = E.scalar_multiplication(0); zero
Scalar-multiplication endomorphism [0] of Elliptic Curve defined by y^2 = x^3 + x + 1 over Finite Field of size 71
sage: zero.is_zero()
True
sage: zero.is_injective()
False
sage: zero.is_surjective()
False
sage: zero(E.random_point())
(0 : 1 : 0)
Due to a bug (:trac:`6413`), retrieving multiplication-by-`m` maps
when `m` is divisible by the characteristic currently fails::
sage: E = EllipticCurve(GF(7), [1,0])
sage: phi = E.scalar_multiplication(7); phi
Scalar-multiplication endomorphism [7] of Elliptic Curve defined by y^2 = x^3 + x over Finite Field of size 7
sage: phi.rational_maps() # known bug -- #6413
(x^49, y^49)
sage: phi.x_rational_map()
x^49
::
sage: E = EllipticCurve(GF(7), [0,1])
sage: phi = E.scalar_multiplication(7); phi
Scalar-multiplication endomorphism [7] of Elliptic Curve defined by y^2 = x^3 + 1 over Finite Field of size 7
sage: phi.rational_maps() # known bug -- #6413
((-3*x^49 - x^28 - x^7)/(x^42 - x^21 + 2),
(-x^72*y - 3*x^69*y - 3*x^66*y - x^63*y + 3*x^51*y + 2*x^48*y + 2*x^45*y + 3*x^42*y - x^9*y - 3*x^6*y - 3*x^3*y - y)/(x^63 + 2*x^42 - x^21 - 1))
sage: phi.x_rational_map()
(4*x^49 + 6*x^28 + 6*x^7)/(x^42 + 6*x^21 + 2)
TESTS::
sage: E = EllipticCurve(j = GF(65537^3).random_element())
sage: m = randrange(-2^99, +2^99)
sage: phi = E.scalar_multiplication(m)
sage: phi.degree() == m**2
True
sage: P = E.random_point()
sage: phi(P) == m*P
True
AUTHORS:
- Lorenz Panny (2021): implement :class:`EllipticCurveHom_scalar`
"""
from sage.misc.cachefunc import cached_method
from sage.structure.richcmp import richcmp
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.schemes.elliptic_curves.ell_generic import EllipticCurve_generic
from sage.schemes.elliptic_curves.weierstrass_morphism import negation_morphism
from sage.schemes.elliptic_curves.hom import EllipticCurveHom
class EllipticCurveHom_scalar(EllipticCurveHom):
def __init__(self, E, m):
"""
Construct a scalar-multiplication map on an elliptic curve.
TESTS::
sage: from sage.schemes.elliptic_curves.hom_scalar import EllipticCurveHom_scalar
sage: E = EllipticCurve([1,1])
sage: EllipticCurveHom_scalar(E, 123)
Scalar-multiplication endomorphism [123] of Elliptic Curve defined by y^2 = x^3 + x + 1 over Rational Field
"""
if not isinstance(E, EllipticCurve_generic):
raise ValueError(f'not an elliptic curve: {E}')
self._m = ZZ(m)
self._degree = self._m**2
self._domain = self._codomain = E
EllipticCurveHom.__init__(self, self._domain, self._codomain)
# TODO: should probably be in EllipticCurveHom?
self._base_ring = self._domain.base_ring()
self._poly_ring = PolynomialRing(self._base_ring, ['x'])
self._mpoly_ring = PolynomialRing(self._base_ring, ['x','y'])
self._rational_maps = None
def _call_(self, P):
"""
Evaluate this scalar-multiplication map `[m]` at a point `P`,
i.e., return `[m]P`.
TESTS::
sage: p = random_prime(2^22)
sage: q = p^randrange(1,5)
sage: E = EllipticCurve_from_j(GF(q).random_element())
sage: m = randrange(-9^99, 9^99)
sage: phi = E.scalar_multiplication(m)
sage: P = E.random_point()
sage: phi(P) == m*P
True
"""
if P not in self._domain:
raise ValueError(f'{P} is not a point on {self._domain}')
return self._m * P
def _eval(self, P):
"""
Less strict evaluation method for internal use.
In particular, this can be used to evaluate ``self`` at a
point defined over an extension field.
INPUT: a sequence of 3 coordinates defining a point on ``self``
OUTPUT: the result of evaluating ``self`` at the given point
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_scalar import EllipticCurveHom_scalar
sage: E = EllipticCurve(j=Mod(1728,419))
sage: psi = EllipticCurveHom_scalar(E, 13)
sage: P = E.change_ring(GF(419**2)).lift_x(5)
sage: P = min({P, -P}) # fix choice of y
sage: Q = psi._eval(P); Q
(134 : 210*z2 + 314 : 1)
sage: Q.curve()
Elliptic Curve defined by y^2 = x^3 + x over Finite Field in z2 of size 419^2
"""
if self._domain.defining_polynomial()(*P):
raise ValueError(f'{P} not on {self._domain}')
return self._m * P
def _repr_(self):
"""
Return basic facts about this scalar multiplication as a string.
TESTS::
sage: E = EllipticCurve([i,i])
sage: E.scalar_multiplication(777)
Scalar-multiplication endomorphism [777] of Elliptic Curve defined by y^2 = x^3 + I*x + I over Number Field in I with defining polynomial x^2 + 1 with I = 1*I
"""
return f'Scalar-multiplication endomorphism [{self._m}] of {self._domain}'
# EllipticCurveHom methods
@staticmethod
def _composition_impl(self, other):
"""
Helper method to compose other elliptic-curve morphisms with
:class:`EllipticCurveHom_scalar` objects. Called by
:meth:`EllipticCurveHom._composition_`.
This method only handles composing two scalar multiplications;
all other cases are dealt with elsewhere.
TESTS::
sage: E = EllipticCurve([1,2,3,4,5])
sage: phi = E.scalar_multiplication(5)
sage: psi = E.scalar_multiplication(-7)
sage: phi * psi # implicit doctest
Scalar-multiplication endomorphism [-35] of Elliptic Curve defined by y^2 + x*y + 3*y = x^3 + 2*x^2 + 4*x + 5 over Rational Field
::
sage: phi._composition_impl(phi, E.automorphisms()[0])
NotImplemented
"""
if isinstance(self, EllipticCurveHom_scalar) and isinstance(other, EllipticCurveHom_scalar):
assert self._domain == other._domain
return EllipticCurveHom_scalar(self._domain, self._m * other._m)
return NotImplemented
def degree(self):
"""
Return the degree of this scalar-multiplication morphism.
The map `[m]` has degree `m^2`.
EXAMPLES::
sage: E = EllipticCurve(GF(23), [0,1])
sage: phi = E.scalar_multiplication(1111111)
sage: phi.degree()
1234567654321
TESTS:
The degree is still `m^2` even in the inseparable case::
sage: E = EllipticCurve(GF(23), [1,1])
sage: E.scalar_multiplication(23).degree()
529
sage: E = EllipticCurve(GF(23), [0,1])
sage: E.scalar_multiplication(23).degree()
529
"""
return self._degree
def _richcmp_(self, other, op):
"""
Compare this scalar multiplication to another elliptic-curve morphism.
.. WARNING::
This method sometimes calls :meth:`EllipticCurveHom._richcmp_`,
which sometimes compares :meth:`rational_maps`. Therefore, the
complexity is at least quadratic in `m` in the worst case.
EXAMPLES::
sage: E = EllipticCurve([i,i])
sage: phi = E.scalar_multiplication(-5)
sage: psi = E.scalar_multiplication(5)
sage: phi == -psi
True
TESTS::
sage: from sage.schemes.elliptic_curves.weierstrass_morphism import negation_morphism
sage: neg = negation_morphism(E)
sage: phi == neg*psi == psi*neg == -psi
True
"""
if isinstance(other, EllipticCurveHom_scalar):
return richcmp((self._domain, self._m), (other._domain, other._m), op)
return EllipticCurveHom._richcmp_(self, other, op)
def rational_maps(self):
"""
Return the pair of explicit rational maps defining this scalar
multiplication.
ALGORITHM: :meth:`EllipticCurve_generic.multiplication_by_m`
EXAMPLES::
sage: E = EllipticCurve('77a1')
sage: phi = E.scalar_multiplication(5)
sage: phi.rational_maps()
((x^25 - 200*x^23 - 520*x^22 + ... + 368660*x^2 + 163195*x + 16456)/(25*x^24 + 1240*x^22 + 950*x^21 + ... + 20360*x^2 - 39480*x + 2209),
(10*x^36*y - 620*x^36 + 3240*x^34*y - ... + 226380480*x + 42986410*y + 20974090)/(1250*x^36 + 93000*x^34 + 71250*x^33 + ... + 138715800*x^2 - 27833400*x + 1038230))
sage: P = (2,3)
sage: Q = tuple(r(P) for r in phi.rational_maps()); Q
(30, 164)
sage: E(Q) == 5*E(P)
True
TESTS::
sage: {r.parent() for r in phi.rational_maps()}
{Fraction Field of Multivariate Polynomial Ring in x, y over Rational Field}
"""
if not self._rational_maps or None in self._rational_maps:
if not self._m:
raise ValueError('[0] is not expressible in (x,y) coordinates')
self._rational_maps = self._domain.multiplication_by_m(self._m)
return self._rational_maps
def x_rational_map(self):
"""
Return the `x`-coordinate rational map of this scalar
multiplication.
ALGORITHM: :meth:`EllipticCurve_generic.multiplication_by_m`
EXAMPLES::
sage: E = EllipticCurve(GF(65537), [1,2,3,4,5])
sage: phi = E.scalar_multiplication(7)
sage: phi.x_rational_map() == phi.rational_maps()[0]
True
TESTS::
sage: phi.x_rational_map().parent()
Fraction Field of Univariate Polynomial Ring in x over Finite Field of size 65537
"""
if not self._rational_maps:
if not self._m:
raise ValueError('[0] is not expressible in (x,y) coordinates')
h = self._domain.multiplication_by_m(self._m, x_only=True)
self._rational_maps = (self._mpoly_ring.fraction_field()(h), None)
f,g = map(self._poly_ring, (self._rational_maps[0].numerator(),
self._rational_maps[0].denominator()))
return f / g
def scaling_factor(self):
r"""
Return the Weierstrass scaling factor associated to this
scalar multiplication.
The scaling factor is the constant `u` (in the base field)
such that `\varphi^* \omega_2 = u \omega_1`, where
`\varphi: E_1\to E_2` is this morphism and `\omega_i` are
the standard Weierstrass differentials on `E_i` defined by
`\mathrm dx/(2y+a_1x+a_3)`.
EXAMPLES::
sage: E = EllipticCurve('11a1')
sage: phi = E.scalar_multiplication(5)
sage: u = phi.scaling_factor()
sage: u == phi.formal()[1]
True
sage: u == E.multiplication_by_m_isogeny(5).scaling_factor()
doctest:warning ... DeprecationWarning: ...
True
The scaling factor lives in the base ring::
sage: E = EllipticCurve(GF(101^2), [5,5])
sage: phi = E.scalar_multiplication(123)
sage: phi.scaling_factor()
22
sage: phi.scaling_factor().parent()
Finite Field in z2 of size 101^2
ALGORITHM: The scaling factor equals the scalar that is being
multiplied by.
"""
return self._base_ring(self._m)
@cached_method
def kernel_polynomial(self):
r"""
Return the kernel polynomial of this scalar-multiplication map.
(When `m=0`, return `0`.)
EXAMPLES::
sage: E = EllipticCurve(GF(997), [7,7,7,7,7])
sage: phi = E.scalar_multiplication(5)
sage: phi.kernel_polynomial()
x^12 + 77*x^11 + 380*x^10 + 198*x^9 + 840*x^8 + 376*x^7 + 946*x^6 + 848*x^5 + 246*x^4 + 778*x^3 + 77*x^2 + 518*x + 28
::
sage: E = EllipticCurve(GF(997), [5,6,7,8,9])
sage: phi = E.scalar_multiplication(11)
sage: phi.kernel_polynomial()
x^60 + 245*x^59 + 353*x^58 + 693*x^57 + 499*x^56 + 462*x^55 + 820*x^54 + 962*x^53 + ... + 736*x^7 + 939*x^6 + 429*x^5 + 267*x^4 + 116*x^3 + 770*x^2 + 491*x + 519
TESTS::
sage: E = EllipticCurve(j = GF(997^6).random_element())
sage: m = choice([+1,-1]) * randrange(1,8)
sage: phi = E.scalar_multiplication(m)
sage: phi.kernel_polynomial() == phi.x_rational_map().denominator().monic().radical()
True
::
sage: E.scalar_multiplication(randint(-10,+10)).kernel_polynomial().parent()
Univariate Polynomial Ring in x over Finite Field in z6 of size 997^6
"""
if not self._m:
return self._poly_ring(0)
# TODO: inseparable case should be consistent with Frobenius' .kernel_polynomial()
return self._domain.division_polynomial(self._m.abs()).monic().radical()
def dual(self):
"""
Return the dual isogeny of this scalar-multiplication map.
This method simply returns ``self`` as scalars are self-dual.
EXAMPLES::
sage: E = EllipticCurve([5,5])
sage: phi = E.scalar_multiplication(5)
sage: phi.dual() is phi
True
"""
return self
def is_separable(self):
"""
Determine whether this scalar-multiplication map is a
separable isogeny. (This is the case if and only if the
scalar `m` is coprime to the characteristic.)
EXAMPLES::
sage: E = EllipticCurve(GF(11), [4,4])
sage: E.scalar_multiplication(11).is_separable()
False
sage: E.scalar_multiplication(-11).is_separable()
False
sage: E.scalar_multiplication(777).is_separable()
True
sage: E.scalar_multiplication(-1).is_separable()
True
sage: E.scalar_multiplication(77).is_separable()
False
sage: E.scalar_multiplication(121).is_separable()
False
TESTS::
sage: E.scalar_multiplication(0).is_separable()
Traceback (most recent call last):
...
ValueError: [0] is not an isogeny
"""
if self._m.is_zero():
raise ValueError('[0] is not an isogeny')
return bool(self.scaling_factor())
def is_injective(self):
"""
Determine whether this scalar multiplication defines an
injective map (over the algebraic closure).
Equivalently, return ``True`` if and only if this scalar
multiplication is a purely inseparable isogeny.
EXAMPLES::
sage: E = EllipticCurve(GF(23), [1,0])
sage: E.scalar_multiplication(4).is_injective()
False
sage: E.scalar_multiplication(5).is_injective()
False
sage: E.scalar_multiplication(1).is_injective()
True
sage: E.scalar_multiplication(-1).is_injective()
True
sage: E.scalar_multiplication(23).is_injective()
True
sage: E.scalar_multiplication(-23).is_injective()
True
sage: E.scalar_multiplication(0).is_injective()
False
"""
if self._m.is_zero():
return False
p = self._domain.base_ring().characteristic()
return self._m.abs().is_power_of(p) and self._domain.is_supersingular()
def __neg__(self):
"""
Negate this scalar-multiplication map, i.e., return `[-m]`
when this morphism equals `[m]`.
If rational maps have been computed already, they will be
reused for the negated morphism.
EXAMPLES::
sage: E = EllipticCurve(GF(2^8), [1,0,1,0,1])
sage: phi = E.scalar_multiplication(23)
sage: -phi
Scalar-multiplication endomorphism [-23] of Elliptic Curve defined by y^2 + x*y + y = x^3 + 1 over Finite Field in z8 of size 2^8
TESTS::
sage: E = EllipticCurve(GF(79), [7,7])
sage: phi = E.scalar_multiplication(5)
sage: _ = phi.rational_maps()
sage: (-phi)._rational_maps
((x^25 + 11*x^23 - 24*x^22 - ... - 7*x^2 + 34*x + 21)/(25*x^24 - 5*x^22 - 23*x^21 - ... - 11*x^2 + 36*x + 21),
(29*x^36*y + 22*x^34*y - 27*x^33*y - ... + 14*x^2*y - 33*x*y + 37*y)/(9*x^36 + 21*x^34 - 14*x^33 + ... - 26*x^2 + 18*x + 7))
"""
result = EllipticCurveHom_scalar(self._domain, -self._m)
if self._rational_maps is not None:
w = negation_morphism(self._domain).rational_maps()
result._rational_maps = tuple(f(*w) if f is not None else None for f in self._rational_maps)
return result | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/elliptic_curves/hom_scalar.py | 0.87105 | 0.842151 | hom_scalar.py | pypi |
r"""
Frobenius isogenies of elliptic curves
Frobenius isogenies only exist in positive characteristic `p`. They
are given by `\pi_n:(x,y)\mapsto (x^{p^n},y^{p^n})`.
This class implements `\pi_n` for `n \geq 0`. Together with existing
tools for composing isogenies (see :class:`EllipticCurveHom_composite`),
we can therefore represent arbitrary inseparable isogenies in Sage.
EXAMPLES:
Constructing a Frobenius isogeny is straightforward::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: z5, = GF(17^5).gens()
sage: E = EllipticCurve([z5,1])
sage: pi = EllipticCurveHom_frobenius(E); pi
Frobenius isogeny of degree 17:
From: Elliptic Curve defined by y^2 = x^3 + z5*x + 1 over Finite Field in z5 of size 17^5
To: Elliptic Curve defined by y^2 = x^3 + (9*z5^4+7*z5^3+10*z5^2+z5+14)*x + 1 over Finite Field in z5 of size 17^5
By passing `n`, we can also construct higher-power Frobenius maps,
such as the Frobenius *endo*\morphism::
sage: z5, = GF(7^5).gens()
sage: E = EllipticCurve([z5,1])
sage: pi = EllipticCurveHom_frobenius(E,5); pi
Frobenius endomorphism of degree 16807 = 7^5:
From: Elliptic Curve defined by y^2 = x^3 + z5*x + 1 over Finite Field in z5 of size 7^5
To: Elliptic Curve defined by y^2 = x^3 + z5*x + 1 over Finite Field in z5 of size 7^5
The usual :class:`EllipticCurveHom` methods are supported::
sage: z5, = GF(7^5).gens()
sage: E = EllipticCurve([z5,1])
sage: pi = EllipticCurveHom_frobenius(E,5)
sage: pi.degree()
16807
sage: pi.rational_maps()
(x^16807, y^16807)
sage: pi.formal() # known bug
...
sage: pi.is_normalized() # known bug
...
sage: pi.is_separable()
False
sage: pi.is_injective()
True
sage: pi.is_surjective()
True
Computing the dual of Frobenius is supported as well::
sage: E = EllipticCurve([GF(17^6).gen(), 0])
sage: pi = EllipticCurveHom_frobenius(E)
sage: pihat = pi.dual(); pihat
Isogeny of degree 17 from Elliptic Curve defined by y^2 = x^3 + (15*z6^5+5*z6^4+8*z6^3+12*z6^2+11*z6+7)*x over Finite Field in z6 of size 17^6 to Elliptic Curve defined by y^2 = x^3 + z6*x over Finite Field in z6 of size 17^6
sage: pihat.is_separable()
True
sage: pihat * pi == EllipticCurveHom_scalar(E,17) # known bug -- #6413
True
A supersingular example (with purely inseparable dual)::
sage: E = EllipticCurve([0, GF(17^6).gen()])
sage: E.is_supersingular()
True
sage: pi1 = EllipticCurveHom_frobenius(E)
sage: pi1hat = pi1.dual(); pi1hat
Composite morphism of degree 17 = 17*1:
From: Elliptic Curve defined by y^2 = x^3 + (15*z6^5+5*z6^4+8*z6^3+12*z6^2+11*z6+7) over Finite Field in z6 of size 17^6
To: Elliptic Curve defined by y^2 = x^3 + z6 over Finite Field in z6 of size 17^6
sage: pi6 = EllipticCurveHom_frobenius(E,6)
sage: pi6hat = pi6.dual(); pi6hat
Composite morphism of degree 24137569 = 24137569*1:
From: Elliptic Curve defined by y^2 = x^3 + z6 over Finite Field in z6 of size 17^6
To: Elliptic Curve defined by y^2 = x^3 + z6 over Finite Field in z6 of size 17^6
sage: pi6hat.factors()
(Frobenius endomorphism of degree 24137569 = 17^6:
From: Elliptic Curve defined by y^2 = x^3 + z6 over Finite Field in z6 of size 17^6
To: Elliptic Curve defined by y^2 = x^3 + z6 over Finite Field in z6 of size 17^6,
Elliptic-curve endomorphism of Elliptic Curve defined by y^2 = x^3 + z6 over Finite Field in z6 of size 17^6
Via: (u,r,s,t) = (2*z6^5 + 10*z6^3 + z6^2 + 8, 0, 0, 0))
TESTS::
sage: z5, = GF(17^5).gens()
sage: E = EllipticCurve([z5,1])
sage: fs = [EllipticCurveHom_frobenius(E)]
sage: while fs[-1].codomain() != E:
....: fs.append(EllipticCurveHom_frobenius(fs[-1].codomain()))
sage: fs
[Frobenius isogeny of degree 17:
From: Elliptic Curve defined by y^2 = x^3 + z5*x + 1 over Finite Field in z5 of size 17^5
To: Elliptic Curve defined by y^2 = x^3 + (9*z5^4+7*z5^3+10*z5^2+z5+14)*x + 1 over Finite Field in z5 of size 17^5,
Frobenius isogeny of degree 17:
From: Elliptic Curve defined by y^2 = x^3 + (9*z5^4+7*z5^3+10*z5^2+z5+14)*x + 1 over Finite Field in z5 of size 17^5
To: Elliptic Curve defined by y^2 = x^3 + (14*z5^4+7*z5^3+16*z5^2+14*z5+1)*x + 1 over Finite Field in z5 of size 17^5,
Frobenius isogeny of degree 17:
From: Elliptic Curve defined by y^2 = x^3 + (14*z5^4+7*z5^3+16*z5^2+14*z5+1)*x + 1 over Finite Field in z5 of size 17^5
To: Elliptic Curve defined by y^2 = x^3 + (16*z5^4+6*z5^3+7*z5^2+14*z5+6)*x + 1 over Finite Field in z5 of size 17^5,
Frobenius isogeny of degree 17:
From: Elliptic Curve defined by y^2 = x^3 + (16*z5^4+6*z5^3+7*z5^2+14*z5+6)*x + 1 over Finite Field in z5 of size 17^5
To: Elliptic Curve defined by y^2 = x^3 + (12*z5^4+14*z5^3+z5^2+4*z5+13)*x + 1 over Finite Field in z5 of size 17^5,
Frobenius isogeny of degree 17:
From: Elliptic Curve defined by y^2 = x^3 + (12*z5^4+14*z5^3+z5^2+4*z5+13)*x + 1 over Finite Field in z5 of size 17^5
To: Elliptic Curve defined by y^2 = x^3 + z5*x + 1 over Finite Field in z5 of size 17^5]
sage: prod(fs[::-1])
Composite morphism of degree 1419857 = 17^5:
From: Elliptic Curve defined by y^2 = x^3 + z5*x + 1 over Finite Field in z5 of size 17^5
To: Elliptic Curve defined by y^2 = x^3 + z5*x + 1 over Finite Field in z5 of size 17^5
::
sage: EllipticCurveHom_frobenius(EllipticCurve(GF(5),[1,1]), -1)
Traceback (most recent call last):
...
ValueError: negative powers of Frobenius are not isogenies
::
sage: EllipticCurveHom_frobenius(EllipticCurve('11a1'))
Traceback (most recent call last):
...
ValueError: Frobenius isogenies do not exist in characteristic zero
AUTHORS:
- Lorenz Panny (2021): implement :class:`EllipticCurveHom_frobenius`
- Mickaël Montessinos (2021): computing the dual of a Frobenius isogeny
"""
from sage.misc.cachefunc import cached_method
from sage.structure.sequence import Sequence
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.finite_rings.finite_field_base import FiniteField
from sage.schemes.elliptic_curves.ell_generic import EllipticCurve_generic
from sage.schemes.elliptic_curves.constructor import EllipticCurve
from sage.schemes.elliptic_curves.hom import EllipticCurveHom, find_post_isomorphism
from sage.schemes.elliptic_curves.ell_curve_isogeny import EllipticCurveIsogeny
from sage.schemes.elliptic_curves.hom_composite import EllipticCurveHom_composite
from sage.schemes.elliptic_curves.hom_scalar import EllipticCurveHom_scalar
class EllipticCurveHom_frobenius(EllipticCurveHom):
_degree = None
def __init__(self, E, power=1):
r"""
Construct a Frobenius isogeny on a given curve with a given
power of the base-ring characteristic.
Writing `n` for the parameter ``power`` (default: `1`), the
isogeny is defined by `(x,y) \to (x^{p^n}, y^{p^n})` where
`p` is the characteristic of the base ring.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: E = EllipticCurve(j=GF(11^2).gen())
sage: EllipticCurveHom_frobenius(E)
Frobenius isogeny of degree 11:
From: Elliptic Curve defined by y^2 = x^3 + (2*z2+6)*x + (8*z2+8) over Finite Field in z2 of size 11^2
To: Elliptic Curve defined by y^2 = x^3 + (9*z2+3)*x + (3*z2+7) over Finite Field in z2 of size 11^2
sage: EllipticCurveHom_frobenius(E, 2)
Frobenius endomorphism of degree 121 = 11^2:
From: Elliptic Curve defined by y^2 = x^3 + (2*z2+6)*x + (8*z2+8) over Finite Field in z2 of size 11^2
To: Elliptic Curve defined by y^2 = x^3 + (2*z2+6)*x + (8*z2+8) over Finite Field in z2 of size 11^2
TESTS::
sage: EllipticCurveHom_frobenius(EllipticCurve('11a1'))
Traceback (most recent call last):
...
ValueError: Frobenius isogenies do not exist in characteristic zero
::
sage: EllipticCurveHom_frobenius(E, -1)
Traceback (most recent call last):
...
ValueError: negative powers of Frobenius are not isogenies
"""
if not isinstance(E, EllipticCurve_generic):
raise ValueError(f'not an elliptic curve: {E}')
self._base_ring = E.base_ring()
self._p = self._base_ring.characteristic()
if self._p == 0:
raise ValueError('Frobenius isogenies do not exist in characteristic zero')
self._n = ZZ(power)
if self._n < 0:
raise ValueError('negative powers of Frobenius are not isogenies')
self._degree = self._p ** self._n
self._domain = E
as_ = [a**self._degree for a in self._domain.a_invariants()]
self._codomain = EllipticCurve(as_)
EllipticCurveHom.__init__(self, self._domain, self._codomain)
# over finite fields, isogenous curves have the same number of points
# (see #32786)
if isinstance(self._base_ring, FiniteField):
self._domain._fetch_cached_order(self._codomain)
self._codomain._fetch_cached_order(self._domain)
self._poly_ring = PolynomialRing(self._base_ring, ['x'], sparse=True)
self._mpoly_ring = PolynomialRing(self._base_ring, ['x','y'], sparse=True)
self._xfield = self._poly_ring.fraction_field()
self._xyfield = self._mpoly_ring.fraction_field()
def _call_(self, P):
"""
Evaluate this Frobenius isogeny at a point `P`.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: z2 = GF(11^2).gen()
sage: E = EllipticCurve(j=z2)
sage: pi = EllipticCurveHom_frobenius(E)
sage: P = E(7, 9*z2+4)
sage: pi(P) # implicit doctest
(7 : 2*z2 + 7 : 1)
"""
return self._codomain(*(c**self._degree for c in P))
def _eval(self, P):
"""
Less strict evaluation method for internal use.
In particular, this can be used to evaluate ``self`` at a
point defined over an extension field.
INPUT: a sequence of 3 coordinates defining a point on ``self``
OUTPUT: the result of evaluating ``self`` at the given point
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: E = EllipticCurve(GF(11), [1,1])
sage: pi = EllipticCurveHom_frobenius(E)
sage: P = E.change_ring(GF(11^6)).lift_x(GF(11^3).gen()); P
(6*z6^5 + 8*z6^4 + 8*z6^3 + 6*z6^2 + 10*z6 + 5 : 2*z6^5 + 2*z6^4 + 2*z6^3 + 4*z6 + 6 : 1)
sage: pi._eval(P)
(z6^5 + 3*z6^4 + 3*z6^3 + 6*z6^2 + 9 : z6^5 + 10*z6^4 + 10*z6^3 + 5*z6^2 + 4*z6 + 8 : 1)
"""
if self._domain.defining_polynomial()(*P):
raise ValueError(f'{P} not on {self._domain}')
k = Sequence(P).universe()
return self._codomain.base_extend(k)(*(c**self._degree for c in P))
def _repr_(self):
"""
Return basic facts about this Frobenius isogeny as a string.
TESTS::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: z2 = GF(11^2).gen()
sage: E = EllipticCurve(j=z2)
sage: EllipticCurveHom_frobenius(E)
Frobenius isogeny of degree 11:
From: Elliptic Curve defined by y^2 = x^3 + (2*z2+6)*x + (8*z2+8) over Finite Field in z2 of size 11^2
To: Elliptic Curve defined by y^2 = x^3 + (9*z2+3)*x + (3*z2+7) over Finite Field in z2 of size 11^2
sage: EllipticCurveHom_frobenius(E, E.base_field().degree())
Frobenius endomorphism of degree 121 = 11^2:
From: Elliptic Curve defined by y^2 = x^3 + (2*z2+6)*x + (8*z2+8) over Finite Field in z2 of size 11^2
To: Elliptic Curve defined by y^2 = x^3 + (2*z2+6)*x + (8*z2+8) over Finite Field in z2 of size 11^2
"""
kind = 'endomorphism' if self._codomain == self._domain else 'isogeny'
degs_str = '' if self._n == 1 else f' = {self._p}^{self._n}'
return f'Frobenius {kind} of degree {self._degree}{degs_str}:' \
f'\n From: {self._domain}' \
f'\n To: {self._codomain}'
# EllipticCurveHom methods
def degree(self):
"""
Return the degree of this Frobenius isogeny.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: E = EllipticCurve(GF(11), [1,1])
sage: pi = EllipticCurveHom_frobenius(E, 4)
sage: pi.degree()
14641
"""
return self._degree
def rational_maps(self):
"""
Return the explicit rational maps defining this Frobenius
isogeny as (sparse) bivariate rational maps in `x` and `y`.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: E = EllipticCurve(GF(11), [1,1])
sage: pi = EllipticCurveHom_frobenius(E, 4)
sage: pi.rational_maps()
(x^14641, y^14641)
TESTS:
See :trac:`34811`::
sage: pi.rational_maps()[0].parent()
Fraction Field of Multivariate Polynomial Ring in x, y over Finite Field of size 11
sage: pi.rational_maps()[1].parent()
Fraction Field of Multivariate Polynomial Ring in x, y over Finite Field of size 11
"""
x,y = self._xyfield.gens()
return (x**self._degree, y**self._degree)
def x_rational_map(self):
"""
Return the `x`-coordinate rational map of this Frobenius
isogeny as a (sparse) univariate rational map in `x`.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: E = EllipticCurve(GF(11), [1,1])
sage: pi = EllipticCurveHom_frobenius(E, 4)
sage: pi.x_rational_map()
x^14641
TESTS:
See :trac:`34811`::
sage: pi.x_rational_map().parent()
Fraction Field of Sparse Univariate Polynomial Ring in x over Finite Field of size 11
"""
x, = self._xfield.gens()
return x**self._degree
def scaling_factor(self):
r"""
Return the Weierstrass scaling factor associated to this
Frobenius morphism.
The scaling factor is the constant `u` (in the base field)
such that `\varphi^* \omega_2 = u \omega_1`, where
`\varphi: E_1\to E_2` is this morphism and `\omega_i` are
the standard Weierstrass differentials on `E_i` defined by
`\mathrm dx/(2y+a_1x+a_3)`.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: E = EllipticCurve(GF(11), [1,1])
sage: pi = EllipticCurveHom_frobenius(E)
sage: pi.formal()
t^11 + O(t^33)
sage: pi.scaling_factor()
0
sage: pi = EllipticCurveHom_frobenius(E, 3)
sage: pi.formal()
t^1331 + O(t^1353)
sage: pi.scaling_factor()
0
sage: pi = EllipticCurveHom_frobenius(E, 0)
sage: pi == E.scalar_multiplication(1)
True
sage: pi.scaling_factor()
1
The scaling factor lives in the base ring::
sage: pi.scaling_factor().parent()
Finite Field of size 11
ALGORITHM: Inseparable isogenies of degree `>1` have scaling
factor `0`.
"""
if self._degree == 1:
return self._base_ring.one()
return self._base_ring.zero()
def kernel_polynomial(self):
"""
Return the kernel polynomial of this Frobenius isogeny
as a polynomial in `x`. This method always returns `1`.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: E = EllipticCurve(GF(11), [1,1])
sage: pi = EllipticCurveHom_frobenius(E, 5)
sage: pi.kernel_polynomial()
1
"""
return self._poly_ring(1)
@cached_method
def dual(self):
"""
Compute the dual of this Frobenius isogeny.
This method returns an :class:`EllipticCurveHom` object.
EXAMPLES:
An ordinary example::
sage: from sage.schemes.elliptic_curves.hom_scalar import EllipticCurveHom_scalar
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: E = EllipticCurve(GF(31), [0,1])
sage: f = EllipticCurveHom_frobenius(E)
sage: f.dual() * f == EllipticCurveHom_scalar(f.domain(), 31)
True
sage: f * f.dual() == EllipticCurveHom_scalar(f.codomain(), 31)
True
A supersingular example::
sage: E = EllipticCurve(GF(31), [1,0])
sage: f = EllipticCurveHom_frobenius(E)
sage: f.dual() * f == EllipticCurveHom_scalar(f.domain(), 31)
True
sage: f * f.dual() == EllipticCurveHom_scalar(f.codomain(), 31)
True
TESTS:
Some random testing (including small characteristic)::
sage: p = random_prime(50)
sage: q = p**randrange(1,10)
sage: n = randrange(20)
sage: while True:
....: try:
....: E = EllipticCurve([GF(q).random_element() for _ in range(5)])
....: break
....: except ArithmeticError:
....: pass
sage: f = EllipticCurveHom_frobenius(E, n)
sage: f.dual() * f == EllipticCurveHom_scalar(E, p**n)
True
sage: f * f.dual() == EllipticCurveHom_scalar(f.codomain(), p**n)
True
sage: f.dual().dual() == f # known bug -- broken in characteristic 2,3
True
sage: p in (2,3) or f.dual().dual() == f
True
ALGORITHM:
- For supersingular curves, the dual of Frobenius is again purely
inseparable, so we start out with a Frobenius isogeny of equal
degree in the opposite direction.
- For ordinary curves, we immediately reduce to the case of prime
degree. The kernel of the dual is the unique subgroup of size `p`,
which we compute from the `p`-division polynomial.
In both cases, we then search for the correct post-isomorphism
using :meth:`find_post_isomorphism`.
"""
if self._degree == 1:
return self
if self._domain.is_supersingular():
Phi = EllipticCurveHom_frobenius(self._codomain, self._n)
else:
E = self._domain
poly = self._domain.division_polynomial(self._p)
ker = self._poly_ring(list(poly)[::self._p]).monic()
Phis = []
for _ in range(self._n):
Ep = EllipticCurve([a**self._p for a in E.a_invariants()])
Phis.append(EllipticCurveIsogeny(Ep, ker, codomain=E))
E, ker = Ep, ker.map_coefficients(lambda c: c**self._p)
Phi = EllipticCurveHom_composite.from_factors(Phis[::-1], self._codomain)
scalar_mul = EllipticCurveHom_scalar(self._domain, self._degree)
iso = find_post_isomorphism(Phi * self, scalar_mul)
return iso * Phi
def is_separable(self):
"""
Determine whether or not this Frobenius isogeny is separable.
Since Frobenius isogenies are purely inseparable, this method
returns ``True`` if and only if the degree is `1`.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: E = EllipticCurve(GF(11), [1,1])
sage: pi = EllipticCurveHom_frobenius(E)
sage: pi.degree()
11
sage: pi.is_separable()
False
sage: pi = EllipticCurveHom_frobenius(E, 0)
sage: pi.degree()
1
sage: pi.is_separable()
True
"""
return self._degree == 1
def is_injective(self):
"""
Determine whether or not this Frobenius isogeny has trivial
kernel.
Since Frobenius isogenies are purely inseparable, this method
always returns ``True``.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.hom_frobenius import EllipticCurveHom_frobenius
sage: E = EllipticCurve(GF(11), [1,1])
sage: pi = EllipticCurveHom_frobenius(E, 5)
sage: pi.is_injective()
True
"""
return True | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/elliptic_curves/hom_frobenius.py | 0.884046 | 0.712745 | hom_frobenius.py | pypi |
from sage.structure.parent_gens import localvars
from sage.interfaces.gp import Gp
from sage.misc.sage_eval import sage_eval
from sage.misc.randstate import current_randstate
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
gp = None
def init():
"""
Function to initialize the gp process
"""
global gp
if gp is None:
import os
from sage.env import DOT_SAGE
logfile = os.path.join(DOT_SAGE, 'gp-simon.log')
gp = Gp(script_subdirectory='simon', logfile=logfile)
gp.read("ellQ.gp")
gp.read("ell.gp")
gp.read("qfsolve.gp")
gp.read("resultant3.gp")
def simon_two_descent(E, verbose=0, lim1=None, lim3=None, limtriv=None,
maxprob=20, limbigprime=30, known_points=[]):
"""
Interface to Simon's gp script for two-descent.
.. NOTE::
Users should instead run E.simon_two_descent()
EXAMPLES::
sage: import sage.schemes.elliptic_curves.gp_simon
sage: E=EllipticCurve('389a1')
sage: sage.schemes.elliptic_curves.gp_simon.simon_two_descent(E)
(2, 2, [(5/4 : 5/8 : 1), (-3/4 : 7/8 : 1)])
TESTS::
sage: E = EllipticCurve('37a1').change_ring(QuadraticField(-11,'x'))
sage: E.simon_two_descent()
(1, 1, [(0 : 0 : 1)])
An example with an elliptic curve defined over a relative number field::
sage: F.<a> = QuadraticField(29)
sage: x = QQ['x'].gen()
sage: K.<b> = F.extension(x^2-1/2*a+1/2)
sage: E = EllipticCurve(K,[1, 0, 5/2*a + 27/2, 0, 0]) # long time (about 3 s)
sage: E.simon_two_descent(lim1=2, limtriv=3)
(1, 1, ...)
Check that :trac:`16022` is fixed::
sage: K.<y> = NumberField(x^4 + x^2 - 7)
sage: E = EllipticCurve(K, [1, 0, 5*y^2 + 16, 0, 0])
sage: E.simon_two_descent(lim1=2, limtriv=3) # long time (about 3 s)
(1, 1, ...)
An example that checks that :trac:`9322` is fixed (it should take less than a second to run)::
sage: K.<w> = NumberField(x^2-x-232)
sage: E = EllipticCurve([2-w,18+3*w,209+9*w,2581+175*w,852-55*w])
sage: E.simon_two_descent()
(0, 2, [])
"""
init()
current_randstate().set_seed_gp(gp)
K = E.base_ring()
K_orig = K
# The following is to correct the bug at #5204: the gp script
# fails when K is a number field whose generator is called 'x'.
# It also deals with relative number fields.
E_orig = E
if K is not QQ:
K = K_orig.absolute_field('a')
from_K, to_K = K.structure()
E = E_orig.change_ring(to_K)
known_points = [P.change_ring(to_K) for P in known_points]
# Simon's program requires that this name be y.
with localvars(K.polynomial().parent(), 'y'):
gp.eval("K = bnfinit(%s);" % K.polynomial())
if verbose >= 2:
print("K = bnfinit(%s);" % K.polynomial())
gp.eval("%s = Mod(y,K.pol);" % K.gen())
if verbose >= 2:
print("%s = Mod(y,K.pol);" % K.gen())
else:
from_K = lambda x: x
to_K = lambda x: x
# The block below mimics the defaults in Simon's scripts, and needs to be changed
# when these are updated.
if K is QQ:
cmd = 'ellQ_ellrank(%s, %s);' % (list(E.ainvs()), [P.__pari__() for P in known_points])
if lim1 is None:
lim1 = 5
if lim3 is None:
lim3 = 50
if limtriv is None:
limtriv = 3
else:
cmd = 'bnfellrank(K, %s, %s);' % (list(E.ainvs()), [P.__pari__() for P in known_points])
if lim1 is None:
lim1 = 2
if lim3 is None:
lim3 = 4
if limtriv is None:
limtriv = 2
gp('DEBUGLEVEL_ell=%s; LIM1=%s; LIM3=%s; LIMTRIV=%s; MAXPROB=%s; LIMBIGPRIME=%s;'%(
verbose, lim1, lim3, limtriv, maxprob, limbigprime))
if verbose >= 2:
print(cmd)
s = gp.eval('ans=%s;'%cmd)
if s.find(" *** ") != -1:
raise RuntimeError("\n%s\nAn error occurred while running Simon's 2-descent program"%s)
if verbose > 0:
print(s)
v = gp.eval('ans')
if v=='ans': # then the call to ellQ_ellrank() or bnfellrank() failed
raise RuntimeError("An error occurred while running Simon's 2-descent program")
if verbose >= 2:
print("v = %s" % v)
# pari represents field elements as Mod(poly, defining-poly)
# so this function will return the respective elements of K
def _gp_mod(*args):
return args[0]
ans = sage_eval(v, {'Mod': _gp_mod, 'y': K.gen(0)})
lower = ZZ(ans[0])
upper = ZZ(ans[1])
points = [E_orig([from_K(c) for c in list(P)]) for P in ans[2]]
points = [P for P in points if P.has_infinite_order()]
return lower, upper, points | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/elliptic_curves/gp_simon.py | 0.610686 | 0.397675 | gp_simon.py | pypi |
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.rational_field import QQ
from .constructor import EllipticCurve
def mod5family(a, b):
"""
Formulas for computing the family of elliptic curves with
congruent mod-5 representation.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.mod5family import mod5family
sage: mod5family(0,1)
Elliptic Curve defined by y^2 = x^3 + (t^30+30*t^29+435*t^28+4060*t^27+27405*t^26+142506*t^25+593775*t^24+2035800*t^23+5852925*t^22+14307150*t^21+30045015*t^20+54627300*t^19+86493225*t^18+119759850*t^17+145422675*t^16+155117520*t^15+145422675*t^14+119759850*t^13+86493225*t^12+54627300*t^11+30045015*t^10+14307150*t^9+5852925*t^8+2035800*t^7+593775*t^6+142506*t^5+27405*t^4+4060*t^3+435*t^2+30*t+1) over Fraction Field of Univariate Polynomial Ring in t over Rational Field
"""
J = 4*a**3 / (4*a**3+27*b**2)
alpha = [0 for _ in range(21)]
alpha[0] = 1
alpha[1] = 0
alpha[2] = 190*(J - 1)
alpha[3] = -2280*(J - 1)**2
alpha[4] = 855*(J - 1)**2*(-17 + 16*J)
alpha[5] = 3648*(J - 1)**3*(17 - 9*J)
alpha[6] = 11400*(J - 1)**3*(17 - 8*J)
alpha[7] = -27360*(J - 1)**4*(17 + 26*J)
alpha[8] = 7410*(J - 1)**4*(-119 - 448*J + 432*J**2)
alpha[9] = 79040*(J - 1)**5*(17 + 145*J - 108*J**2)
alpha[10] = 8892*(J - 1)**5*(187 + 2640*J - 5104*J**2 + 1152*J**3)
alpha[11] = 98800*(J - 1)**6*(-17 - 388*J + 864*J**2)
alpha[12] = 7410*(J - 1)**6*(-187 - 6160*J + 24464*J**2 - 24192*J**3)
alpha[13] = 54720*(J - 1)**7*(17 + 795*J - 3944*J**2 + 9072*J**3)
alpha[14] = 2280*(J - 1)**7*(221 + 13832*J - 103792*J**2 + 554112*J**3 - 373248*J**4)
alpha[15] = 1824*(J - 1)**8*(-119 - 9842*J + 92608*J**2 - 911520*J**3 + 373248*J**4)
alpha[16] = 4275*(J - 1)**8*(-17 - 1792*J + 23264*J**2 - 378368*J**3 + 338688*J**4)
alpha[17] = 18240*(J - 1)**9*(1 + 133*J - 2132*J**2 + 54000*J**3 - 15552*J**4)
alpha[18] = 190*(J - 1)**9*(17 + 2784*J - 58080*J**2 + 2116864*J**3 - 946944*J**4 + 2985984*J**5)
alpha[19] = 360*(J - 1)**10*(-1 + 28*J - 1152*J**2)*(1 + 228*J + 176*J**2 + 1728*J**3)
alpha[20] = (J - 1)**10*(-19 - 4560*J + 144096*J**2 - 9859328*J**3 - 8798976*J**4 - 226934784*J**5 + 429981696*J**6)
beta = [0 for _ in range(31)]
beta[0] = 1
beta[1] = 30
beta[2] = -435*(J - 1)
beta[3] = 580*(J - 1)*(-7 + 9*J)
beta[4] = 3915*(J - 1)**2*(7 - 8*J)
beta[5] = 1566*(J - 1)**2*(91 - 78*J + 48*J**2)
beta[6] = -84825*(J - 1)**3*(7 + 16*J)
beta[7] = 156600*(J - 1)**3*(-13 - 91*J + 92*J**2)
beta[8] = 450225*(J - 1)**4*(13 + 208*J - 144*J**2)
beta[9] = 100050*(J - 1)**4*(143 + 4004*J - 5632*J**2 + 1728*J**3)
beta[10] = 30015*(J - 1)**5*(-1001 - 45760*J + 44880*J**2 - 6912*J**3)
beta[11] = 600300*(J - 1)**5*(-91 - 6175*J + 9272*J**2 - 2736*J**3)
beta[12] = 950475*(J - 1)**6*(91 + 8840*J - 7824*J**2)
beta[13] = 17108550*(J - 1)**6*(7 + 926*J - 1072*J**2 + 544*J**3)
beta[14] = 145422675*(J - 1)**7*(-1 - 176*J + 48*J**2 - 384*J**3)
beta[15] = 155117520*(J - 1)**8*(1 + 228*J + 176*J**2 + 1728*J**3)
beta[16] = 145422675*(J - 1)**8*(1 + 288*J + 288*J**2 + 5120*J**3 - 6912*J**4)
beta[17] = 17108550*(J - 1)**8*(7 + 2504*J + 3584*J**2 + 93184*J**3 - 283392*J**4 + 165888*J**5)
beta[18] = 950475*(J - 1)**9*(-91 - 39936*J - 122976*J**2 - 2960384*J**3 + 11577600*J**4 - 5971968*J**5)
beta[19] = 600300*(J - 1)**9*(-91 - 48243*J - 191568*J**2 - 6310304*J**3 + 40515072*J**4 - 46455552*J**5 + 11943936*J**6)
beta[20] = 30015*(J - 1)**10*(1001 + 634920*J + 3880800*J**2 + 142879744*J**3 - 1168475904*J**4 + 1188919296*J**5 - 143327232*J**6)
beta[21] = 100050*(J - 1)**10*(143 + 107250*J + 808368*J**2 + 38518336*J**3 - 451953408*J**4 + 757651968*J**5 - 367276032*J**6)
beta[22] = 450225*(J - 1)**11*(-13 - 11440*J - 117216*J**2 - 6444800*J**3 + 94192384*J**4 - 142000128*J**5 + 95551488*J**6)
beta[23] = 156600*(J - 1)**11*(-13 - 13299*J - 163284*J**2 - 11171552*J**3 + 217203840*J**4 - 474406656*J**5 + 747740160*J**6 - 429981696*J**7)
beta[24] = 6525*(J - 1)**12*(91 + 107536*J + 1680624*J**2 + 132912128*J**3 -\
3147511552*J**4 + 6260502528*J**5 - 21054173184*J**6 + 10319560704*J**7)
beta[25] = 1566*(J - 1)**12*(91 + 123292*J + 2261248*J**2 + 216211904*J**3 - \
6487793920*J**4 + 17369596928*J**5 - 97854234624*J**6 + 96136740864*J**7 - 20639121408*J**8)
beta[26] = 3915*(J - 1)**13*(-7 - 10816*J - 242352*J**2 - 26620160*J**3 + 953885440*J**4 - \
2350596096*J**5 + 26796552192*J**6 - 13329432576*J**7)
beta[27] = 580*(J - 1)**13*(-7 - 12259*J - 317176*J**2 - 41205008*J**3 + \
1808220160*J**4 - 5714806016*J**5 + 93590857728*J**6 - 70131806208*J**7 - 36118462464*J**8)
beta[28] = 435*(J - 1)**14*(1 + 1976*J + 60720*J**2 + 8987648*J**3 - 463120640*J**4 + 1359157248*J**5 - \
40644882432*J**6 - 5016453120*J**7 + 61917364224*J**8)
beta[29] = 30*(J - 1)**14*(1 + 2218*J + 77680*J**2 + 13365152*J**3 - \
822366976*J**4 + 2990693888*J**5 - 118286217216*J**6 - 24514928640*J**7 + 509958291456*J**8 - 743008370688*J**9)
beta[30] = (J - 1)**15*(-1 - 2480*J - 101040*J**2 - 19642496*J**3 + 1399023872*J**4 - \
4759216128*J**5 + 315623485440*J**6 + 471904911360*J**7 - 2600529297408*J**8 + 8916100448256*J**9)
R = PolynomialRing(QQ, 't')
c2 = a * R(alpha)
c3 = b * R(beta)
d = c2.denominator().lcm(c3.denominator())
F = R.fraction_field()
return EllipticCurve(F, [c2 * d**4, c3 * d**6]) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/elliptic_curves/mod5family.py | 0.481698 | 0.703359 | mod5family.py | pypi |
r"""
Tables of elliptic curves of given rank
The default database of curves contains the following data:
+------+------------------+--------------------+
| Rank | Number of curves | Maximal conductor |
+======+==================+====================+
| 0 | 30427 | 9999 |
+------+------------------+--------------------+
| 1 | 31871 | 9999 |
+------+------------------+--------------------+
| 2 | 2388 | 9999 |
+------+------------------+--------------------+
| 3 | 836 | 119888 |
+------+------------------+--------------------+
| 4 | 10 | 1175648 |
+------+------------------+--------------------+
| 5 | 5 | 37396136 |
+------+------------------+--------------------+
| 6 | 5 | 6663562874 |
+------+------------------+--------------------+
| 7 | 5 | 896913586322 |
+------+------------------+--------------------+
| 8 | 6 | 457532830151317 |
+------+------------------+--------------------+
| 9 | 7 | ~9.612839e+21 |
+------+------------------+--------------------+
| 10 | 6 | ~1.971057e+21 |
+------+------------------+--------------------+
| 11 | 6 | ~1.803406e+24 |
+------+------------------+--------------------+
| 12 | 1 | ~2.696017e+29 |
+------+------------------+--------------------+
| 14 | 1 | ~3.627533e+37 |
+------+------------------+--------------------+
| 15 | 1 | ~1.640078e+56 |
+------+------------------+--------------------+
| 17 | 1 | ~2.750021e+56 |
+------+------------------+--------------------+
| 19 | 1 | ~1.373776e+65 |
+------+------------------+--------------------+
| 20 | 1 | ~7.381324e+73 |
+------+------------------+--------------------+
| 21 | 1 | ~2.611208e+85 |
+------+------------------+--------------------+
| 22 | 1 | ~2.272064e+79 |
+------+------------------+--------------------+
| 23 | 1 | ~1.139647e+89 |
+------+------------------+--------------------+
| 24 | 1 | ~3.257638e+95 |
+------+------------------+--------------------+
| 28 | 1 | ~3.455601e+141 |
+------+------------------+--------------------+
Note that lists for r>=4 are not exhaustive; there may well be curves
of the given rank with conductor less than the listed maximal conductor,
which are not included in the tables.
AUTHORS:
- William Stein (2007-10-07): initial version
- Simon Spicer (2014-10-24): Added examples of more high-rank curves
See also the functions cremona_curves() and cremona_optimal_curves()
which enable easy looping through the Cremona elliptic curve database.
"""
import os
from ast import literal_eval
from .constructor import EllipticCurve
class EllipticCurves:
def rank(self, rank, tors=0, n=10, labels=False):
r"""
Return a list of at most `n` curves with given
rank and torsion order.
INPUT:
- ``rank`` (int) -- the desired rank
- ``tors`` (int, default 0) -- the desired torsion order (ignored if 0)
- ``n`` (int, default 10) -- the maximum number of curves returned.
- ``labels`` (bool, default False) -- if True, return Cremona
labels instead of curves.
OUTPUT:
(list) A list at most `n` of elliptic curves of required rank.
EXAMPLES::
sage: elliptic_curves.rank(n=5, rank=3, tors=2, labels=True)
['59450i1', '59450i2', '61376c1', '61376c2', '65481c1']
::
sage: elliptic_curves.rank(n=5, rank=0, tors=5, labels=True)
['11a1', '11a3', '38b1', '50b1', '50b2']
::
sage: elliptic_curves.rank(n=5, rank=1, tors=7, labels=True)
['574i1', '4730k1', '6378c1']
::
sage: e = elliptic_curves.rank(6)[0]; e.ainvs(), e.conductor()
((1, 1, 0, -2582, 48720), 5187563742)
sage: e = elliptic_curves.rank(7)[0]; e.ainvs(), e.conductor()
((0, 0, 0, -10012, 346900), 382623908456)
sage: e = elliptic_curves.rank(8)[0]; e.ainvs(), e.conductor()
((1, -1, 0, -106384, 13075804), 249649566346838)
For large conductors, the labels are not known::
sage: L = elliptic_curves.rank(6, n=3); L
[Elliptic Curve defined by y^2 + x*y = x^3 + x^2 - 2582*x + 48720 over Rational Field,
Elliptic Curve defined by y^2 + y = x^3 - 7077*x + 235516 over Rational Field,
Elliptic Curve defined by y^2 + x*y = x^3 - x^2 - 2326*x + 43456 over Rational Field]
sage: L[0].cremona_label()
Traceback (most recent call last):
...
LookupError: Cremona database does not contain entry for Elliptic Curve defined by y^2 + x*y = x^3 + x^2 - 2582*x + 48720 over Rational Field
sage: elliptic_curves.rank(6, n=3, labels=True)
[]
"""
from sage.env import ELLCURVE_DATA_DIR
data = os.path.join(ELLCURVE_DATA_DIR, 'rank%s'%rank)
try:
f = open(data)
except IOError:
return []
v = []
tors = int(tors)
for w in f.readlines():
N, iso, num, ainvs, r, t = w.split()
N = int(N)
t = int(t)
if tors and tors != t:
continue
# Labels are only known to be correct for small conductors.
# NOTE: only change this bound below after checking/fixing
# the Cremona labels in the elliptic_curves package!
if N <= 400000:
label = '%s%s%s'%(N, iso, num)
else:
label = None
if labels:
if label is not None:
v.append(label)
else:
E = EllipticCurve(literal_eval(ainvs))
E._set_rank(r)
E._set_torsion_order(t)
E._set_conductor(N)
if label is not None:
E._set_cremona_label(label)
v.append(E)
if len(v) >= n:
break
return v
elliptic_curves = EllipticCurves() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/elliptic_curves/ec_database.py | 0.886377 | 0.735784 | ec_database.py | pypi |
r"""
Berkovich Space over `\CC_p`
The Berkovich affine line is the set of seminorms on `\CC_p[x]`,
with the weakest topology that makes the map `| \cdot | \to |f|` continuous
for all `f \in \CC_p[x]`. The Berkovich projective line is the
one-point compactification of the Berkovich affine line.
The two main classes are :class:`Berkovich_Cp_Affine` and
:class:`Berkovich_Cp_Projective`, which implement the affine and
projective lines, respectively.
:class:`Berkovich_Cp_Affine` and :class:`Berkovich_Cp_Projective`
take as input one of the following: the prime `p`, a finite
extension of `\QQ_p`, or a number field and a place.
For an exposition of Berkovich space over `\CC_p`, see Chapter 6 of [Ben2019]_. For a more
involved exposition, see Chapter 1 and 2 of [BR2010]_.
AUTHORS:
- Alexander Galarraga (2020-06-22): initial implementation
"""
#*****************************************************************************
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from sage.schemes.berkovich.berkovich_cp_element import (Berkovich_Element_Cp_Affine,
Berkovich_Element_Cp_Projective)
from sage.structure.parent import Parent
from sage.schemes.affine.affine_space import is_AffineSpace
from sage.schemes.projective.projective_space import is_ProjectiveSpace, ProjectiveSpace
from sage.structure.unique_representation import UniqueRepresentation
from sage.categories.number_fields import NumberFields
import sage.rings.abc
from sage.rings.integer_ring import ZZ
from sage.rings.padics.factory import Qp
from sage.rings.rational_field import QQ
from sage.rings.number_field.number_field_ideal import NumberFieldFractionalIdeal
from sage.categories.topological_spaces import TopologicalSpaces
def is_Berkovich(space):
"""
Checks if ``space`` is a Berkovich space.
OUTPUT:
- ``True`` if ``space`` is a Berkovich space.
- ``False`` otherwise.
EXAMPLES::
sage: B = Berkovich_Cp_Projective(3)
sage: from sage.schemes.berkovich.berkovich_space import is_Berkovich
sage: is_Berkovich(B)
True
"""
return isinstance(space, Berkovich)
def is_Berkovich_Cp(space):
"""
Checks if ``space`` is a Berkovich space over ``Cp``.
OUTPUT:
- ``True`` if ``space`` is a Berkovich space over ``Cp``.
- ``False`` otherwise.
EXAMPLES::
sage: B = Berkovich_Cp_Projective(3)
sage: from sage.schemes.berkovich.berkovich_space import is_Berkovich
sage: is_Berkovich(B)
True
"""
return isinstance(space, Berkovich_Cp)
class Berkovich(UniqueRepresentation, Parent):
"""
The parent class for any Berkovich space
"""
pass
class Berkovich_Cp(Berkovich):
"""
Abstract parent class for Berkovich space over ``Cp``.
"""
def residue_characteristic(self):
"""
The residue characteristic of the ``base``.
EXAMPLES::
sage: B = Berkovich_Cp_Projective(3)
sage: B.prime()
3
::
sage: R.<x> = QQ[]
sage: A.<a> = NumberField(x^3 + 20)
sage: ideal = A.ideal(-1/2*a^2 + a - 3)
sage: B = Berkovich_Cp_Affine(A, ideal)
sage: B.residue_characteristic()
7
"""
return self._p
prime = residue_characteristic
def is_padic_base(self):
"""
Return ``True`` if this Berkovich space is backed by a p-adic field.
OUTPUT:
- ``True`` if this Berkovich space was created with a p-adic field.
- ``False`` otherwise.
EXAMPLES::
sage: B = Berkovich_Cp_Affine(Qp(3))
sage: B.is_padic_base()
True
::
sage: B = Berkovich_Cp_Affine(QQ, 3)
sage: B.is_padic_base()
False
"""
return self._base_type == 'padic field'
def is_number_field_base(self):
"""
Return ``True`` if this Berkovich space is backed by a p-adic field.
OUTPUT:
- ``True`` if this Berkovich space was created with a number field.
- ``False`` otherwise.
EXAMPLES::
sage: B = Berkovich_Cp_Affine(Qp(3))
sage: B.is_number_field_base()
False
::
sage: B = Berkovich_Cp_Affine(QQ, 3)
sage: B.is_number_field_base()
True
"""
return self._base_type == 'number field'
def ideal(self):
r"""
The ideal which defines an embedding of the ``base_ring`` into `\CC_p`.
If this Berkovich space is backed by a p-adic field, then an embedding is
already specified, and this returns ``None``.
OUTPUT:
- An ideal of a ``base_ring`` if ``base_ring`` is a number field.
- A prime of `\QQ` if ``base_ring`` is `\QQ`.
- ``None`` if ``base_ring`` is a p-adic field.
EXAMPLES::
sage: R.<z> = QQ[]
sage: A.<a> = NumberField(z^2 + 1)
sage: ideal = A.prime_above(5)
sage: B = Berkovich_Cp_Projective(A, ideal)
sage: B.ideal()
Fractional ideal (-a - 2)
::
sage: B = Berkovich_Cp_Projective(QQ, 3)
sage: B.ideal()
3
::
sage: B = Berkovich_Cp_Projective(Qp(3))
sage: B.ideal() is None
True
"""
return self._ideal
def __eq__(self,right):
"""
Equality operator.
EXAMPLES::
sage: B = Berkovich_Cp_Affine(3)
sage: A.<x> = Qq(27)
sage: C = Berkovich_Cp_Affine(A)
sage: B == C
True
::
sage: R.<x> = QQ[]
sage: A.<a> = NumberField(x^2 + 1)
sage: A_ideal = A.prime_above(2)
sage: B.<b> = NumberField(x^4 + 1)
sage: B_ideal = B.prime_above(2)
sage: C = Berkovich_Cp_Projective(A, A_ideal)
sage: D = Berkovich_Cp_Projective(B, B_ideal)
sage: C == D
False
::
sage: C = Berkovich_Cp_Affine(A, A_ideal)
sage: D = Berkovich_Cp_Affine(B, B_ideal)
sage: C == D
False
::
sage: A_ideal_2 = A.prime_above(5)
sage: E = Berkovich_Cp_Affine(A, A_ideal_2)
sage: C == E
False
"""
if not isinstance(right, Berkovich_Cp):
return False
if self._base_type != right._base_type:
return False
if self._base_type == 'padic field':
return self.prime() == right.prime()
else:
return self.base() == right.base() and self.ideal() == right.ideal()
def __ne__(self,right):
"""
Inequality operator.
EXAMPLES::
sage: B = Berkovich_Cp_Affine(5)
sage: A.<x> = Qq(25)
sage: C = Berkovich_Cp_Affine(A)
sage: B != C
False
"""
return not (self == right)
def __hash__(self):
"""
Hash function.
EXAMPLES::
sage: hash(Berkovich_Cp_Projective(3))
3
::
sage: R.<z> = QQ[]
sage: A.<a> = NumberField(z^2 + 1)
sage: B = Berkovich_Cp_Projective(A, A.primes_above(5)[0])
sage: C = Berkovich_Cp_Projective(A, A.primes_above(5)[1])
sage: hash(B) != hash(C)
True
"""
if self._base_type == 'padic field':
return hash(self.prime())
return hash(self.ideal())
class Berkovich_Cp_Affine(Berkovich_Cp):
r"""
The Berkovich affine line over `\CC_p`.
The Berkovich affine line is the set of seminorms on `\CC_p[x]`,
with the weakest topology such that the map `| \cdot | \to |f|` is continuous
for all `f \in \CC_p[x]`.
We can represent the Berkovich affine line in two separate ways:
either using a p-adic field to represent elements or using
a number field to represent elements while storing an ideal
of the ring of integers of the number field, which specifies
an embedding of the number field into `\CC_p`. See the examples.
INPUT:
- ``base`` -- Three cases:
* a prime number `p`. Centers of elements are then represented
as points of `\QQ_p`.
* `\QQ_p` or a finite extension of `\QQ_p`. Centers of elements
are then represented as points of ``base``.
* A number field `K`. Centers of elements are then represented
as points of `K`.
- ``ideal`` -- (optional) a prime ideal of ``base``. Must be
specified if a number field is passed to ``base``, otherwise
it is ignored.
EXAMPLES::
sage: B = Berkovich_Cp_Affine(3); B
Affine Berkovich line over Cp(3) of precision 20
We can create elements::
sage: B(-2)
Type I point centered at 1 + 2*3 + 2*3^2 + 2*3^3 + 2*3^4 + 2*3^5
+ 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^10 + 2*3^11 + 2*3^12 + 2*3^13
+ 2*3^14 + 2*3^15 + 2*3^16 + 2*3^17 + 2*3^18 + 2*3^19 + O(3^20)
::
sage: B(1, 2)
Type III point centered at 1 + O(3^20) of radius 2.00000000000000
For details on element creation, see the documentation
of :class:`Berkovich_Element_Cp_Affine`. Initializing by
passing in `\QQ_p` looks the same::
sage: B = Berkovich_Cp_Affine(Qp(3)); B
Affine Berkovich line over Cp(3) of precision 20
However, this method allows for more control over behind-the-scenes conversion::
sage: B = Berkovich_Cp_Affine(Qp(3, 1)); B
Affine Berkovich line over Cp(3) of precision 1
sage: B(1/2)
Type I point centered at 2 + O(3)
Note that this point has very low precision, as ``B`` was initialized
with a p-adic field of capped-relative precision one. For high precision,
pass in a high precision p-adic field::
sage: B = Berkovich_Cp_Affine(Qp(3, 1000)); B
Affine Berkovich line over Cp(3) of precision 1000
Points of Berkovich space can be created from points of
extensions of `\QQ_p`::
sage: B = Berkovich_Cp_Affine(3)
sage: A.<a> = Qp(3).extension(x^3 - 3)
sage: B(a)
Type I point centered at a + O(a^61)
For exact computation, a number field can be used::
sage: R.<x> = QQ[]
sage: A.<a> = NumberField(x^3 + 20)
sage: ideal = A.prime_above(3)
sage: B = Berkovich_Cp_Affine(A, ideal); B
Affine Berkovich line over Cp(3), with base Number
Field in a with defining polynomial x^3 + 20
Number fields have a major advantage of exact computation.
Number fields also have added functionality. Arbitrary extensions of
`\QQ` are supported, while there is currently limited functionality
for extensions of `\QQ_p`. As seen above, constructing a Berkovich
space backed by a number field requires specifying an ideal of the
ring of integers of the number field. Specifying the ideal uniquely
specifies an embedding of the number field into `\CC_p`.
Unlike in the case where Berkovich space is backed by a p-adic
field, any point of a Berkovich space backed by a number field
must be centered at a point of that number field::
sage: R.<x> = QQ[]
sage: A.<a> = NumberField(x^3 + 20)
sage: ideal = A.prime_above(3)
sage: B = Berkovich_Cp_Affine(A, ideal)
sage: C.<c> = NumberField(x^2 + 1)
sage: B(c)
Traceback (most recent call last):
...
ValueError: could not convert c to Number Field in a
with defining polynomial x^3 + 20
TESTS::
sage: A.<x> = AffineSpace(Qp(3), 1)
sage: Berkovich_Cp_Affine(A)
Affine Berkovich line over Cp(3) of precision 20
::
sage: B = Berkovich_Cp_Projective(3)
sage: TestSuite(B).run()
"""
Element = Berkovich_Element_Cp_Affine
def __init__(self, base, ideal=None):
"""
The Python constructor.
EXAMPLES::
sage: Berkovich_Cp_Affine(3)
Affine Berkovich line over Cp(3) of precision 20
"""
if base in ZZ:
if base.is_prime():
base = Qp(base) # change to Qpbar
else:
raise ValueError("non-prime passed into Berkovich space")
if is_AffineSpace(base):
base = base.base_ring()
if base in NumberFields():
if ideal is None:
raise ValueError('passed a number field but not an ideal')
if base is not QQ:
if not isinstance(ideal, NumberFieldFractionalIdeal):
raise ValueError('ideal was not an ideal of a number field')
if ideal.number_field() != base:
raise ValueError('passed number field ' + \
'%s but ideal was an ideal of %s' %(base, ideal.number_field()))
prime = ideal.smallest_integer()
else:
if ideal not in QQ:
raise ValueError('ideal was not an element of QQ')
prime = ideal
if not ideal.is_prime():
raise ValueError('passed non prime ideal')
self._base_type = 'number field'
elif isinstance(base, sage.rings.abc.pAdicField): # change base to Qpbar
prime = base.prime()
ideal = None
self._base_type = 'padic field'
else:
raise ValueError("base of Berkovich Space must be a padic field " + \
"or a number field")
self._ideal = ideal
self._p = prime
Parent.__init__(self, base=base, category=TopologicalSpaces())
def _repr_(self):
"""
String representation of this Berkovich Space.
EXAMPLES::
sage: B = Berkovich_Cp_Affine(3)
sage: B
Affine Berkovich line over Cp(3) of precision 20
::
sage: R.<z> = QQ[]
sage: A.<a> = NumberField(z^2 + 1)
sage: ideal = A.prime_above(3)
sage: Berkovich_Cp_Affine(A, ideal)
Affine Berkovich line over Cp(3), with base Number Field
in a with defining polynomial z^2 + 1
"""
if self._base_type == 'padic field':
return "Affine Berkovich line over Cp(%s) of precision %s" %(self.prime(),\
self.base().precision_cap())
else:
return "Affine Berkovich line over Cp(%s), with base %s" %(self.prime(),\
self.base())
def _latex_(self):
r"""
LaTeX representation of this Berkovich Space.
EXAMPLES:
sage: B = Berkovich_Cp_Affine(3)
sage: latex(B)
\text{Affine Berkovich line over } \Bold{C}_{3}
"""
return r"\text{Affine Berkovich line over } \Bold{C}_{%s}" % (self.prime())
class Berkovich_Cp_Projective(Berkovich_Cp):
r"""
The Berkovich projective line over `\CC_p`.
The Berkovich projective line is the one-point compactification
of the Berkovich affine line.
We can represent the Berkovich projective line in two separate ways:
either using a p-adic field to represent elements or using
a number field to represent elements while storing an ideal
of the ring of integers of the number field, which specifies
an embedding of the number field into `\CC_p`. See the examples.
INPUT:
- ``base`` -- Three cases:
* a prime number `p`. Centers of elements are then represented
as points of projective space of dimension 1 over `\QQ_p`.
* `\QQ_p` or a finite extension of `\QQ_p`. Centers of elements
are then represented as points of projective space of dimension 1
over ``base``.
* A number field `K`. Centers of elements are then represented
as points of projective space of dimension 1 over ``base``.
- ``ideal`` -- (optional) a prime ideal of ``base``. Must be
specified if a number field is passed to ``base``, otherwise
it is ignored.
EXAMPLES::
sage: B = Berkovich_Cp_Projective(3); B
Projective Berkovich line over Cp(3) of precision 20
Elements can be constructed::
sage: B(1/2)
Type I point centered at (2 + 3 + 3^2 + 3^3 + 3^4 + 3^5
+ 3^6 + 3^7 + 3^8 + 3^9 + 3^10 + 3^11 + 3^12 + 3^13 + 3^14
+ 3^15 + 3^16 + 3^17 + 3^18 + 3^19 + O(3^20) : 1 + O(3^20))
::
sage: B(2, 1)
Type II point centered at (2 + O(3^20) : 1 + O(3^20)) of radius 3^0
For details about element construction, see the documentation of
:class:`Berkovich_Element_Cp_Projective`. Initializing a Berkovich projective
line by passing in a p-adic space looks the same::
sage: B = Berkovich_Cp_Projective(Qp(3)); B
Projective Berkovich line over Cp(3) of precision 20
However, this method allows for more control over
behind-the-scenes conversion::
sage: S = Qp(3, 1)
sage: B = Berkovich_Cp_Projective(S); B
Projective Berkovich line over Cp(3) of precision 1
sage: Q1 = B(1/2); Q1
Type I point centered at (2 + O(3) : 1 + O(3))
Note that this point has very low precision, as S has low
precision cap. Berkovich space can also be created over
a number field, as long as an ideal is specified::
sage: R.<x> = QQ[]
sage: A.<a> = NumberField(x^2 + 1)
sage: ideal = A.prime_above(2)
sage: B = Berkovich_Cp_Projective(A, ideal); B
Projective Berkovich line over Cp(2), with base
Number Field in a with defining polynomial x^2 + 1
Number fields have the benefit that computation is exact,
but lack support for all of `\CC_p`.
Number fields also have the advantage of added functionality,
as arbitrary extensions of `\QQ` can be constructed while
there is currently limited functionality for extensions of `\QQ_p`.
As seen above, constructing a Berkovich space backed by a number
field requires specifying an ideal of the ring of integers
of the number field. Specifying the ideal uniquely specifies
an embedding of the number field into `\CC_p`.
Unlike in the case where Berkovich space is backed by a p-adic
field, any point of a Berkovich space backed by a number field
must be centered at a point of that number field::
sage: R.<x> = QQ[]
sage: A.<a> = NumberField(x^3 + 20)
sage: ideal = A.prime_above(3)
sage: B = Berkovich_Cp_Projective(A, ideal)
sage: C.<c> = NumberField(x^2 + 1)
sage: B(c)
Traceback (most recent call last):
...
TypeError: could not convert c to Projective Space
of dimension 1 over Number Field in a with defining polynomial x^3 + 20
TESTS::
sage: B = Berkovich_Cp_Projective(3)
sage: TestSuite(B).run()
"""
Element = Berkovich_Element_Cp_Projective
def __init__(self, base, ideal=None):
"""
The Python constructor.
EXAMPLES::
sage: Berkovich_Cp_Projective(3)
Projective Berkovich line over Cp(3) of precision 20
"""
if base in ZZ:
if base.is_prime():
base = ProjectiveSpace(Qp(base), 1)
else:
raise ValueError("non-prime passed into Berkovich space")
if base in NumberFields() or isinstance(base, sage.rings.abc.pAdicField):
base = ProjectiveSpace(base, 1)
if not is_ProjectiveSpace(base):
try:
base = ProjectiveSpace(base)
except (TypeError, ValueError):
raise ValueError("base of projective Berkovich space must be projective space")
if not isinstance(base.base_ring(), sage.rings.abc.pAdicField):
if base.base_ring() not in NumberFields():
raise ValueError("base of projective Berkovich space must be " + \
"projective space over Qp or a number field")
else:
if ideal is None:
raise ValueError('passed a number field but not an ideal')
if base.base_ring() is not QQ:
if not isinstance(ideal, NumberFieldFractionalIdeal):
raise ValueError('ideal was not a number field ideal')
if ideal.number_field() != base.base_ring():
raise ValueError('passed number field ' + \
'%s but ideal was an ideal of %s' %(base.base_ring(), ideal.number_field()))
prime = ideal.smallest_integer()
else:
if ideal not in QQ:
raise ValueError('ideal was not an element of QQ')
prime = ideal
if not ideal.is_prime():
raise ValueError('passed non prime ideal')
self._base_type = 'number field'
else:
prime = base.base_ring().prime()
ideal = None
self._base_type = 'padic field'
if base.dimension_relative() != 1:
raise ValueError("base of projective Berkovich space must be "
"projective space of dimension 1 over Qp or a number field")
self._p = prime
self._ideal = ideal
Parent.__init__(self, base=base, category=TopologicalSpaces())
def base_ring(self):
r"""
The base ring of this Berkovich Space.
OUTPUT: A field.
EXAMPLES::
sage: B = Berkovich_Cp_Projective(3)
sage: B.base_ring()
3-adic Field with capped relative precision 20
::
sage: C = Berkovich_Cp_Projective(ProjectiveSpace(Qp(3, 1), 1))
sage: C.base_ring()
3-adic Field with capped relative precision 1
::
sage: R.<x> = QQ[]
sage: A.<a> = NumberField(x^3 + 20)
sage: ideal = A.prime_above(3)
sage: D = Berkovich_Cp_Projective(A, ideal)
sage: D.base_ring()
Number Field in a with defining polynomial x^3 + 20
"""
return self.base().base_ring()
def _repr_(self):
"""
String representation of this Berkovich Space.
EXAMPLES::
sage: B = Berkovich_Cp_Projective(3)
sage: B
Projective Berkovich line over Cp(3) of precision 20
::
sage: R.<x> = QQ[]
sage: A.<a> = NumberField(x^2 + 1)
sage: v = A.ideal(a + 1)
sage: Berkovich_Cp_Projective(A, v)
Projective Berkovich line over Cp(2), with base Number Field in a with defining polynomial x^2 + 1
"""
if self._base_type == 'padic field':
return "Projective Berkovich line over Cp(%s) of precision %s" %(self.prime(),\
self.base().base_ring().precision_cap())
else:
return "Projective Berkovich line over Cp(%s), with base %s" %(self.prime(),\
self.base().base_ring())
def _latex_(self):
r"""
LaTeX representation of this Berkovich Space.
EXAMPLES:
sage: B = Berkovich_Cp_Projective(3)
sage: latex(B)
\text{Projective Berkovich line over } \Bold{C}_{3}
"""
return r"\text{Projective Berkovich line over } \Bold{C}_{%s}" %(self.prime()) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/berkovich/berkovich_space.py | 0.934574 | 0.69382 | berkovich_space.py | pypi |
r"""
Cyclic covers over a finite field
The most interesting feature is computation of Frobenius matrix on
Monsky-Washnitzer cohomology and the Frobenius polynomial.
REFERENCES:
- [ABCMT2019]_
EXAMPLES::
sage: p = 13
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(4, x^4 + 1)
sage: C.frobenius_polynomial()
x^6 - 6*x^5 + 3*x^4 + 60*x^3 + 39*x^2 - 1014*x + 2197
sage: R.<t> = PowerSeriesRing(Integers())
sage: C.projective_closure().zeta_series(2,t)
1 + 8*t + 102*t^2 + O(t^3)
sage: C.frobenius_polynomial().reverse()(t)/((1-t)*(1-p*t)) + O(t^5)
1 + 8*t + 102*t^2 + 1384*t^3 + 18089*t^4 + O(t^5)
sage: p = 49999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: CyclicCover(5, x^5 + x).frobenius_polynomial() # long time
x^12 + 299994*x^10 + 37498500015*x^8 + 2499850002999980*x^6 + 93742500224997000015*x^4 + 1874812507499850001499994*x^2 + 15623125093747500037499700001
sage: CyclicCover(5, 2*x^5 + x).frobenius_polynomial() # long time
x^12 + 299994*x^10 + 37498500015*x^8 + 2499850002999980*x^6 + 93742500224997000015*x^4 + 1874812507499850001499994*x^2 + 15623125093747500037499700001
sage: p = 107
sage: x = PolynomialRing(GF(p),"x").gen()
sage: CyclicCover(2, x^5 + x).frobenius_matrix()
[ O(107^2) 89*107 + O(107^2) O(107^2) O(107^2)]
[ 89*107 + O(107^2) O(107^2) O(107^2) O(107^2)]
[ O(107^2) O(107^2) O(107^2) 105 + 5*107 + O(107^2)]
[ O(107^2) O(107^2) 89 + 53*107 + O(107^2) O(107^2)]
sage: CyclicCover(2, 3*x^5 + x).frobenius_matrix()
[ O(107^2) 14*107 + O(107^2) O(107^2) O(107^2)]
[ 69*107 + O(107^2) O(107^2) O(107^2) O(107^2)]
[ O(107^2) O(107^2) O(107^2) 61 + 58*107 + O(107^2)]
[ O(107^2) O(107^2) 69 + 53*107 + O(107^2) O(107^2)]
sage: CyclicCover(3, x^3 + x).frobenius_matrix()
[ 0 0 O(107) O(107)]
[ 0 0 52 + O(107) O(107)]
[ O(107) 35 + O(107) 0 0]
[44 + O(107) O(107) 0 0]
sage: CyclicCover(3, 3*x^3 + x).frobenius_matrix()
[ 0 0 O(107) O(107)]
[ 0 0 79 + O(107) O(107)]
[ O(107) 42 + O(107) 0 0]
[30 + O(107) O(107) 0 0]
"""
# *****************************************************************************
# Copyright (C) 2018 Vishal Arul <varul@mit.edu>,
# Alex Best <alex.j.best@gmail.com>,
# Edgar Costa <edgarc@mit.edu>,
# Richard Magner <rmagner@bu.edu>,
# Nicholas Triantafillou <ngtriant@mit.edu>
# Distributed under the terms of the GNU General Public License (GPL)
# https://www.gnu.org/licenses/
# *****************************************************************************
from sage.arith.misc import euler_phi
from sage.functions.other import ceil, binomial, floor
from sage.functions.log import log
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.power_series_ring import PowerSeriesRing
from sage.rings.padics.factory import Zp, Zq, Qq
from sage.rings.integer_ring import ZZ
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing
from sage.matrix.constructor import matrix, zero_matrix
from sage.modules.free_module_element import vector
from sage.schemes.hyperelliptic_curves.hypellfrob import interval_products
from sage.misc.cachefunc import cached_method
from .charpoly_frobenius import charpoly_frobenius
from . import cycliccover_generic
def _N0_nodenominators(p, g, n):
"""
Return the necessary p-adic precision for the Frobenius matrix to deduce
the characteristic polynomial of Frobenius using the Newton identities,
using :meth:`charpoly_frobenius`, which assumes that the Frobenius matrix
is integral, i.e., has no denominators.
INPUT:
- `p` - prime
- `g` - genus
- `n` - degree of residue field
TESTS::
sage: sage.schemes.cyclic_covers.cycliccover_finite_field._N0_nodenominators(4999, 4, 5)
11
"""
return max(
ceil(log(2 * (2 * g) / ZZ(i), p) + (n * i) / ZZ(2)) for i in range(1, g + 1)
)
class CyclicCover_finite_field(cycliccover_generic.CyclicCover_generic):
def __init__(self, AA, r, f, names=None, verbose=0):
"""
EXAMPLES::
sage: p = 13
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(4, x^4 + 1)
sage: C.frobenius_polynomial()
x^6 - 6*x^5 + 3*x^4 + 60*x^3 + 39*x^2 - 1014*x + 2197
sage: R.<t> = PowerSeriesRing(Integers())
sage: C.projective_closure().zeta_series(2,t)
1 + 8*t + 102*t^2 + O(t^3)
sage: C.frobenius_polynomial().reverse()(t)/((1-t)*(1-p*t)) + O(t^5)
1 + 8*t + 102*t^2 + 1384*t^3 + 18089*t^4 + O(t^5)
"""
cycliccover_generic.CyclicCover_generic.__init__(self, AA, r, f, names=names)
self._verbose = verbose
self._init_frobQ = False
self._N0 = None
def _init_frob(self, desired_prec=None):
"""
Initialise everything for Frobenius polynomial computation.
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._init_frobQ
True
sage: C._plarge
True
sage: C._sqrtp
True
"""
def _N0_RH():
return ceil(
log(2 * binomial(2 * self._genus, self._genus), self._p)
+ self._genus * self._n / ZZ(2)
)
def _find_N0():
if self._nodenominators:
return _N0_nodenominators(self._p, self._genus, self._n)
else:
return _N0_RH() + self._extraprec
def _find_N_43():
"""
Find the precision used for thm 4.3 in Goncalves
for p >> 0, N = N0 + 2
"""
p = self._p
r = self._r
d = self._d
delta = self._delta
N0 = self._N0
left_side = N0 + floor(log((d * p * (r - 1) + r) / delta) / log(p))
def right_side_log(n):
return floor(log(p * (r * n - 1) - r) / log(p))
n = left_side
while n <= left_side + right_side_log(n):
n += 1
return n
if not self._init_frobQ or self._N0 != desired_prec:
if self._r < 2 or self._d < 2:
raise NotImplementedError("Only implemented for r, f.degree() >= 2")
self._init_frobQ = True
self._Fq = self._f.base_ring()
self._p = self._Fq.characteristic()
self._q = self._Fq.cardinality()
self._n = self._Fq.degree()
self._epsilon = 0 if self._delta == 1 else 1
# our basis choice doesn't always give an integral matrix
if self._epsilon == 0:
self._extraprec = floor(
log(self._r, self._p)
+ log((2 * self._genus + (self._delta - 2)) / self._delta, self._p)
)
else:
self._extraprec = floor(log(self._r * 2 - 1, self._p))
self._nodenominators = self._extraprec == 0
if desired_prec is None:
self._N0 = _find_N0()
else:
self._N0 = desired_prec
self._plarge = self._p > self._d * self._r * (self._N0 + self._epsilon)
# working prec
if self._plarge:
self._N = self._N0 + 1
else:
self._N = _find_N_43()
# we will use the sqrt(p) version?
self._sqrtp = self._plarge and self._p == self._q
self._extraworkingprec = self._extraprec
if not self._plarge:
# we might have some denominators showing up during horizontal
# and vertical reductions
self._extraworkingprec += 2 * ceil(
log(self._d * self._r * (self._N0 + self._epsilon), self._p)
)
# Rings
if self._plarge and self._nodenominators:
if self._n == 1:
# IntegerModRing is significantly faster than Zq
self._Zq = IntegerModRing(self._p**self._N)
if self._sqrtp:
self._Zq0 = IntegerModRing(self._p**(self._N - 1))
self._Qq = Qq(self._p, prec=self._N, type="capped-rel")
self._w = 1
else:
self._Zq = Zq(
self._q,
names="w",
modulus=self._Fq.polynomial(),
prec=self._N,
type="capped-abs",
)
self._w = self._Zq.gen()
self._Qq = self._Zq.fraction_field()
else:
self._Zq = Qq(
self._q,
names="w",
modulus=self._Fq.polynomial(),
prec=self._N + self._extraworkingprec,
)
self._w = self._Zq.gen()
self._Qq = self._Zq
self._Zp = Zp(self._p, prec=self._N + self._extraworkingprec)
self._Zqx = PolynomialRing(self._Zq, "x")
# Want to take a lift of f from Fq to Zq
if self._n == 1:
# When n = 1, can lift from Fp[x] to Z[x] and then to Zp[x]
self._flift = self._Zqx([elt.lift() for elt in self._f.list()])
self._frobf = self._Zqx(self._flift.list())
else: # When n > 1, need to be more careful with the lift
self._flift = self._Zqx(
[
elt.polynomial().change_ring(ZZ)(self._Zq.gen())
for elt in self._f.list()
]
)
self._frobf = self._Zqx([elt.frobenius() for elt in self._flift.list()])
self._dflift = self._flift.derivative()
# Set up local cache for Frob(f)^s
# This variable will store the powers of frob(f)
frobpow = [None] * (self._N0 + 2)
frobpow[0] = self._Zqx(1)
for k in range(self._N0 + 1):
frobpow[k + 1] = self._frobf * frobpow[k]
# We don't make it a polynomials as we need to keep track that the
# ith coefficient represents (i*p)-th
self._frobpow_list = [elt.list() for elt in frobpow]
if self._sqrtp:
# precision of self._Zq0
N = self._N - 1
vandermonde = matrix(self._Zq0, N, N)
for i in range(N):
vandermonde[i, 0] = 1
for j in range(1, N):
vandermonde[i, j] = vandermonde[i, j - 1] * (i + 1)
self._vandermonde = vandermonde.inverse()
self._horizontal_fat_s = {}
self._vertical_fat_s = {}
def _divide_vector(self, D, vect, R):
"""
Divide the vector `vect` by `D` as a vector over `R`.
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._divide_vector(p, vector(C._Qq, [p, p^2, p^3]), C._Qq)
(1 + O(4999^3), 4999 + O(4999^4), 4999^2 + O(4999^5))
"""
DQq = self._Qq(D).lift_to_precision(self._Qq.precision_cap())
m = 1 / DQq
if not R.is_field():
vectQq = vector(
self._Qq,
[
m * self._Qq(elt).lift_to_precision(self._Qq.precision_cap())
for elt in vect
],
)
return vector(R, [R(elt) for elt in vectQq])
else:
return vector(R, [(m * elt).lift_to_precision() for elt in vect])
def _frob_sparse(self, i, j, N0):
r"""
Compute `Frob(x^i y^(-j) dx ) / dx` for y^r = f(x) with N0 terms
INPUT:
- ``i`` - The power of x in the expression `Frob(x^i dx/y^j) / dx`
- ``j`` - The (negative) power of y in the expression
`Frob(x^i dx/y^j) / dx`
OUTPUT:
``frobij`` - a Matrix of size (d * (N0 - 1) + ) x (N0)
that represents the Frobenius expansion of
x^i dx/y^j modulo p^(N0 + 1)
the entry (l, s) corresponds to the coefficient associated
to the monomial x**(p * (i + 1 + l) -1) * y**(p * -(j + r*s))
(l, s) --> (p * (i + 1 + l) -1, p * -(j + r*s))
ALGORITHM:
Compute:
Frob(x^i dx/y^j) / dx = p * x ** (p * (i+1) - 1) * y ** (-j*p) * Sigma
where:
.. MATH::
Sigma = \sum_{k = 0} ^{N0-1}
\sum_{s = 0} ^k
(-1) ** (k-s) * binomial(k, s)
* binomial(-j/r, k)
* self._frobpow[s]
* self._y ** (-self._r * self._p * s)
= \sum_{s = 0} ^{N0 - 1}
\sum_{k = s} ^N0
(-1) ** (k-s) * binomial(k, s)
* binomial(-j/self._r, k)
* self._frobpow[s]
* self._y ** (-self._r*self._p*s)
= \sum_{s = 0} ^{N0-1}
D_{j, s}
* self._frobpow[s]
* self._y ** (-self._r * self._p * s)
= \sum_{s = 0} ^N0
\sum_{l = 0} ^(d*s)
D_{j, s} * self._frobpow[s][l]
* x ** (self._p ** l)
* y ** (-self._r * self._p ** s)
and:
.. MATH::
D_{j, s} = \sum_{k = s} ^N0 (-1) ** (k-s) * binomial(k, s) * binomial(-j/self._r, k) )
TESTS::
sage: p = 499
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._frob_sparse(2, 0, 1)
[499]
sage: C._frob_sparse(2, 0, 2)
[499 0]
[ 0 0]
[ 0 0]
[ 0 0]
[ 0 0]
sage: C._frob_sparse(2, 1, 1)
[499]
sage: C._frob_sparse(2, 1, 2)
[ 82834998 41417000]
[ 0 124251000]
[ 0 124250002]
[ 0 41416501]
[ 0 41417000]
sage: C._frob_sparse(2, 2, 1)
[499]
"""
def _extend_frobpow(power):
if power < len(self._frobpow_list):
pass
else:
frobpow = self._Zqx(self._frobpow_list[-1])
for k in range(len(self._frobpow_list), power + 1):
frobpow *= self._frobf
self._frobpow_list.extend([frobpow.list()])
assert power < len(self._frobpow_list)
_extend_frobpow(N0)
r = self._r
Dj = [
self._Zq(
sum(
[
(-1) ** (k - l) * binomial(k, l) * binomial(-ZZ(j) / r, k)
for k in range(l, N0)
]
)
)
for l in range(N0)
]
frobij = matrix(self._Zq, self._d * (N0 - 1) + 1, N0)
for s in range(N0):
for l in range(self._d * s + 1):
frobij[l, s] = self._p * Dj[s] * self._frobpow_list[s][l]
return frobij
def _horizontal_matrix_reduction(self, s):
r"""
Return the tuple of tuples that represents the horizontal matrix
reduction at pole order ``s``.
INPUT:
- ``s`` -- integer
OUTPUT:
A tuple of tuples ``( (D0, D1), (M0, M1) )``
where `MH_{e, s} = M0 + e * M1` and `DH_{e,s} = D0 + e * D1`
ALGORITHM:
Let `W_{e, s}` to be the Qq-vector space of differential forms
of the form:
.. MATH:: G x^e y^{-s} dx
where `\deg G \leq d - 1`.
Let `v = [G_0, ..., G_{d-1}]` represent G
There is a map:
`MH_{e, s} : W_{e, s} \to W_{e-1, s}`
and a function to:
`DH: \NN \times \NN \to Qq`
such that:
`G x^e y^{-s} dx \cong H x^{e - 1} y^{-s} dx`
where `H = DH(e, s)^{-1} * MH_{e,s} ( G )`
The matrix `MH_{e, s}` can be written as:
`MH_{e, s} = M0_{s} + e * M1_{s}`
similarly:
`DH_{e,s} = D0_{s} + e * D1_{s}`
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._horizontal_matrix_reduction(24995)
((99968, 124925014996),
(
[ 0 0 0 0]
[ 99968 0 0 124924940023]
[ 0 99968 0 124924565143]
[ 0 0 99968 124924715095],
<BLANKLINE>
[ 0 0 0 3]
[124925014996 0 0 9]
[ 0 124925014996 0 27]
[ 0 0 124925014996 12]
))
sage: C._horizontal_matrix_reduction(4999)
((19984, 124925014996),
(
[ 0 0 0 0]
[ 19984 0 0 124925000011]
[ 0 19984 0 124924925071]
[ 0 0 19984 124924955047],
<BLANKLINE>
[ 0 0 0 3]
[124925014996 0 0 9]
[ 0 124925014996 0 27]
[ 0 0 124925014996 12]
))
"""
f_co = self._flift.list()
# DH_{e,s} = ((s -r)*d - e * r) * f_d
m1 = -1 * self._r * f_co[-1] # r is a, g_co[-1] is lambda
m0 = (s - self._r) * self._d * f_co[-1] # j is a*t + beta
M1 = matrix(
self._Zq,
self._d,
lambda m, n: m1
if m == n + 1
else self._r * f_co[m]
if n == self._d - 1
else 0,
)
M0 = matrix(
self._Zq,
self._d,
lambda m, n: m0
if m == n + 1
else (self._r - s) * m * f_co[m]
if n == self._d - 1
else 0,
)
return ((m0, m1), (M0, M1))
def _vertical_matrix_reduction(self, s0):
r"""
Return the tuple of tuples that represents the vertical matrix reduction.
OUTPUT:
A tuple of tuples ``( (D0, D1), (M0, M1) )``
where MV_t = M0 + t * M1 and DV_t = D0 + t * D1
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._vertical_matrix_reduction(1)
((-2, 3),
(
[117410728377 65750007895 58235721278]
[ 67628579544 59175007105 15028573234]
[ 86414296088 0 27239288985],
<BLANKLINE>
[ 51660720493 75142866164 0]
[ 74203580341 2817857481 75142866164]
[108017870113 0 2817857481]
))
sage: C._vertical_matrix_reduction(2)
((-1, 3),
(
[92989296875 7514286617 58235721278]
[50721434658 60114292932 81717866955]
[80778581126 0 28178574812],
<BLANKLINE>
[ 51660720493 75142866164 0]
[ 74203580341 2817857481 75142866164]
[108017870113 0 2817857481]
))
"""
d = self._d
f_co = (
[0 for i in range(d - 2)] + self._flift.list() + [0 for i in range(d - 1)]
)
fd_co = (
[0 for i in range(d - 1)] + self._dflift.list() + [0 for i in range(d - 0)]
)
rows = [f_co[d - 2 - i : -i - 1] for i in range(d - 1)]
rows += [fd_co[d - 1 - i : -i - 1] for i in range(d)]
m = matrix(rows).transpose().inverse()
a_foo = m[0:d, 0:d]
b_foo = m[d - 1 : 2 * d - 1, 0:d]
a_foo = matrix(d, d, lambda i, j: 1 if i == j and i != d - 1 else 0) * a_foo
foo = matrix(d, d, lambda i, j: j if i == j - 1 else 0)
bp_foo = foo * b_foo
A_vert = a_foo.submatrix(0, 0, d - 1, d - 1)
Bd_vert = bp_foo.submatrix(0, 0, d - 1, d - 1)
M1 = (s0 - self._r) * A_vert + self._r * Bd_vert
M2 = self._r * A_vert
m1 = s0 - self._r
m2 = self._r
return ((m1, m2), (M1, M2))
def _reduce_vector_horizontal(self, G, e, s, k=1):
r"""
INPUT:
- a vector -- `G \in W_{e, s}`
OUTPUT:
- a vector -- `H \in W_{e - k, s}` such that
`G x^e y^{-s} dx \cong H x^{e - k} y^{-s} dx`
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._initialize_fat_horizontal(p, 3)
sage: C._reduce_vector_horizontal((83283349998, 0, 0, 0), 2*p - 1, p, p)
(23734897071, 84632332850, 44254975407, 23684517017)
sage: C._reduce_vector_horizontal((98582524551, 3200841460, 6361495378, 98571346457), 2*p - 1, p, p)
(96813533420, 61680190736, 123292559950, 96786566978)
"""
if self._sqrtp and k == self._p:
vect = self._reduce_vector_horizontal_BSGS(G, e, s)
else:
vect = self._reduce_vector_horizontal_plain(G, e, s, k)
return vect
def _reduce_vector_horizontal_BSGS(self, G, e, s):
r"""
INPUT:
- a vector -- `G \in W_{e, s}`
OUTPUT:
- a vector -- `H \in W_{e - p, s}` such that
`G x^e y^{-s} dx \cong H x^{e - p} y^{-s} dx`
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._initialize_fat_horizontal(p, 3)
sage: C._reduce_vector_horizontal_BSGS((0, 0, 0, 0), 2*p - 1, p)
(0, 0, 0, 0)
sage: C._reduce_vector_horizontal_BSGS((83283349998, 0, 0, 0), 2*p - 1, p)
(23734897071, 84632332850, 44254975407, 23684517017)
sage: C._reduce_vector_horizontal_BSGS((98582524551, 3200841460, 6361495378, 98571346457), 2*p - 1, p)
(96813533420, 61680190736, 123292559950, 96786566978)
"""
if G == 0:
return G
if self._verbose > 2:
print(
"_reduce_vector_horizontal_BSGS(self, %s, %s, %s)"
% (vector(self._Qq, G), e, s)
)
assert (e + 1) % self._p == 0
(m0, m1), (M0, M1) = self._horizontal_matrix_reduction(s)
vect = vector(self._Zq, G)
# we do the first d reductions carefully
D = 1
for i in reversed(range(e - self._d + 1, e + 1)):
Mi = M0 + i * M1
Di = m0 + i * m1
vect = Mi * vect
D *= Di
assert Di % self._p == 0
iD = 1 / self._Zq0(D.lift() / self._p)
vect = vector(self._Zq0, [iD * ZZ(elt.lift() / self._p) for elt in vect])
# use BSGS
iDH, MH = self._horizontal_fat_s[s][(e + 1) / self._p - 1]
vect = iDH * (MH * vect.change_ring(self._Zq0))
# last reduction
i = e - self._p + 1
Mi = M0 + i * M1
Di = 1 / (m0 + i * m1)
vect = Di * (Mi * vect.change_ring(self._Zq))
if self._verbose > 2:
print(
"done _reduce_vector_horizontal_BSGS(self, %s, %s, %s)"
% (vector(self._Qq, G), e, s)
)
print("return %s\n" % (vector(self._Qq, vect),))
return vect
def _initialize_fat_horizontal(self, s, L):
"""
Initialise reduction matrices for horizontal reductions for blocks from `s` to `L`.
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._initialize_fat_horizontal(p, 3)
sage: len(C._horizontal_fat_s[p])
3
"""
assert self._sqrtp
if s not in self._horizontal_fat_s:
N = self._N - 1 # padic precision of self._Zq0
d = self._d
L0 = min(L, N)
targets = [0] * (2 * L0)
for l in range(L0):
targets[2 * l] = self._p * l
targets[2 * l + 1] = self._p * (l + 1) - d - 1
(m0, m1), (M0, M1) = self._horizontal_matrix_reduction(s)
M0, M1 = [elt.change_ring(self._Zq0) for elt in [M0, M1]]
D0, D1 = [matrix(self._Zq0, [elt]) for elt in [m0, m1]]
MH = interval_products(M0, M1, targets)
DH = [elt[0, 0] for elt in interval_products(D0, D1, targets)]
if L > N: # Vandermonde interpolation
# f^{(r)}(0) p^r / r! for r = 0, ..., N-1,
MT = [None] * N
DT = [0] * N
for r in range(N):
MT[r] = matrix(self._Zq0, d, d)
for h in range(N):
v = self._vandermonde[r, h]
for i in range(d):
for j in range(d):
MT[r][i, j] += v * MH[h][i, j]
DT[r] += v * DH[h]
for k in range(N, L):
M = matrix(self._Zq0, d, d)
D = 0
k1pow = self._Zq0(1) # power of k + 1
for h in range(N):
for i in range(d):
for j in range(d):
M[i, j] += k1pow * MT[h][i, j]
D += k1pow * DT[h]
k1pow *= k + 1
MH.append(M)
DH.append(D)
iDH = [1 / elt for elt in DH]
self._horizontal_fat_s[s] = [(iDH[i], MH[i]) for i in range(L)]
assert len(self._horizontal_fat_s[s]) >= L
def _reduce_vector_horizontal_plain(self, G, e, s, k=1):
r"""
INPUT:
- a vector -- `G \in W_{e, s}`
OUTPUT:
- a vector -- `H \in W_{e - k, s}` such that
`G x^e y^{-s} dx \cong H x^{e - k} y^{-s} dx`
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._initialize_fat_horizontal(p, 3)
sage: C._reduce_vector_horizontal_plain((83283349998, 0, 0, 0), 2*p - 1, p, p)
(23734897071, 110671913892, 91161207284, 49524178051)
sage: C._reduce_vector_horizontal_plain((98582524551, 3200841460, 6361495378, 98571346457), 2*p - 1, p, p)
(96813533420, 65678590896, 12037075498, 66773575777)
sage: (C._reduce_vector_horizontal_plain((98582524551, 3200841460, 6361495378, 98571346457), 2*p - 1, p, p) - C._reduce_vector_horizontal_plain((98582524551, 3200841460, 6361495378, 98571346457), 2*p - 1, p, p)) % p^C._N0 == 0
True
"""
if self._verbose > 2:
print(
"_reduce_vector_horizontal_plain(self, G = %s, e = %s, s = %s, k = %s)"
% (vector(self._Qq, G), e, s, k)
)
if G == 0:
return G
(m0, m1), (M0, M1) = self._horizontal_matrix_reduction(s)
vect = vector(self._Zq, G)
D = self._Zq(1)
assert k <= self._p, "more than p reductions at a time should be avoided!"
assert e - k + 1 >= 0
for i in reversed(range(e - k + 1, e + 1)):
Mi = M0 + i * M1
Di = m0 + i * m1
vect = Mi * vect
D *= Di
if self._plarge and Di % self._p == 0:
assert (i + self._d) % self._p == 0
vect = self._divide_vector(D, vect, self._Zq)
D = self._Zq(1)
vect = self._divide_vector(D, vect, self._Zq)
if self._verbose > 2:
print(
"done _reduce_vector_horizontal_plain(self, %s, %s, %s, %s)"
% (vector(self._Qq, G), e, s, k)
)
print("return %s\n" % (vector(self._Qq, vect),))
return vect
def _reduce_vector_vertical(self, G, s0, s, k=1):
r"""
Reduce the vector `G` representing an element of `W_{-1,rs + s0}` by `r k` steps
INPUT:
- a vector -- `G \in W_{-1, r*s + s0}`
OUTPUT:
- a vector -- `H \in W_{-1, r*(s - k) + s0}` such that
`G y^{-(r*s + s0)} dx \cong H y^{-(r*(s -k) + s0)} dx`
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._reduce_vector_vertical((96683034459, 33074345103, 43132216686), 1, p // 3, p // 3)
(4364634303, 124117911400, 26239932330)
"""
def _reduce_vector_vertical_plain(G, s0, s, k=1):
r"""
INPUT:
- a vector -- `G \in W_{-1, r*s + s0}`
OUTPUT:
- a vector -- `H \in W_{-1, r*(s - k) + s0}` such that
`G y^{-(r*s + s0)} dx \cong H y^{-(r*(s -k) + s0)} dx`
"""
if self._verbose > 2:
print(
"_reduce_vector_vertical(self, G = %s, s0 = %s, s = %s, k = %s)"
% (vector(self._Qq, G), s0, s, k)
)
(m0, m1), (M0, M1) = self._vertical_matrix_reduction(s0)
vect = vector(self._Zq, G)
D = 1
assert k <= self._p, "more than p reductions at a time should be avoided!"
assert s - k >= 0
for i in reversed(range(s - k + 1, s + 1)):
Mi = M0 + i * M1
Di = m0 + i * m1
vect = Mi * vect
if self._plarge and Di % self._p != 0:
D *= Di
else:
vect = self._divide_vector(Di, vect, self._Zq)
vect = self._divide_vector(D, vect, self._Zq)
if self._verbose > 2:
print(
"done _reduce_vector_vertical(self, %s, %s, %s)"
% (vector(self._Qq, G), s, k)
)
print("return %s\n" % (vector(self._Qq, vect),))
return vect
G = vector(self._Zq, G)
if self._sqrtp:
self._initialize_fat_vertical(s0, s)
if k < self._p:
assert s - k == self._epsilon
MV = self._vertical_fat_s[s0][0]
elif k == self._p:
MV = self._vertical_fat_s[s0][s // self._p]
return MV * G
else:
return _reduce_vector_vertical_plain(G, s0, s, k)
def _initialize_fat_vertical(self, s0, max_upper_target):
"""
Initialise reduction matrices for vertical reductions for blocks from `s0` to `s0 + max_upper_target`.
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._initialize_fat_vertical(1, p + p // 3)
sage: len(C._vertical_fat_s[1])
2
"""
L = floor((max_upper_target - self._epsilon) / self._p) + 1
if s0 not in self._vertical_fat_s:
(m0, m1), (M0, M1) = self._vertical_matrix_reduction(s0)
D0, D1 = map(lambda y: matrix(self._Zq, [y]), [m0, m1])
targets = [0] * (2 * L)
for l in reversed(range(L)):
targets[2 * l] = max_upper_target - self._p * (L - l)
targets[2 * l + 1] = max_upper_target - self._p * (L - 1 - l)
if targets[0] < 0:
targets[0] = self._epsilon
MV = interval_products(M0, M1, targets)
DV = interval_products(D0, D1, targets)
for l in range(L):
D = DV[l][0, 0]
if D % self._p == 0:
iD = 1 / self._Zq(D.lift() / self._p)
MV[l] = matrix(
self._Zq,
[
[iD * ZZ(elt.lift() / self._p) for elt in row]
for row in MV[l].rows()
],
)
else:
MV[l] *= 1 / D
self._vertical_fat_s[s0] = MV
assert len(self._vertical_fat_s[s0]) >= L
def _frob(self, i, j, N0):
r"""
Compute `Frob(x^i dx/y^j) / dx` in terms of the cohomology basis,
whose `x` and `y` exponents are constrained to be in a particular range.
INPUT:
- `i`,`j` -- exponents of the basis differential
- `N0` -- desired p-adic precision for the Frobenius expansion
TESTS::
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1)
sage: C._init_frob()
sage: C._frob(2, 0, 1)
[3174 + O(4999)]
[1844 + O(4999)]
[4722 + O(4999)]
"""
# a Matrix that represents the Frobenius expansion of
# x^i dx/y^j modulo p^(N0 + 1)
# the entry (l, s) corresponds to the coefficient associated to the monomial x ** (p * (i + 1 + l) -1) * y ** (p * (j + r*s))
assert N0 <= self._N0
frobij = self._frob_sparse(i, j, N0)
# recall
# Frob(x^i dx/y^j) / dx
# = p * x ** (p * (i+1) - 1) * y ** (j*p)
# * = \sum_{s = 0} ^{N0-1}
# \sum_{l = 0} ^(d*s)
# D_{j, s} * Frobpow[s][l] * x ** (p ** l) y ** (r * p ** s)
# H represents H(x) * y^(-p**s) s /dx
# the entry (l, s) of frobij
# corresponds to the monomial (p * (i + 1 + l) -1, p * -(j + r*s))
d = self._d
r = self._r
p = self._p
H = vector(self._Zq, d - 1)
k = (p * j) // r
s0 = (p * j) % r
for s in reversed(range(N0)):
if self._sqrtp:
# (i + 1) <= d
self._initialize_fat_horizontal(
p * j + p * r * s, d * s + (d - 2) + 1
) # d * (s + 1) )
# G represents G(x) * x^(p ** l - 1) y^(-p(j + r*s)) /dx
G = vector(self._Zq, d)
for ell in reversed(range(1, d * s + (i + 1) + 1)):
if ell >= (i + 1):
G[0] += frobij[ell - (i + 1), s]
G = self._reduce_vector_horizontal(G, p * ell - 1, p * j + p * r * s, p)
assert G[0] == 0
H += vector(G.list()[1:])
if s > 0:
# y^(-p(j + r*s)) --- > y^(-p(j + r*(s-1)))
H = self._reduce_vector_vertical(H, s0, k + p * s, p)
# H represents
# H(x) y^-p*j = H(x) y^-(k*r + s0)
# now we reduce the pole order to s0 + r*epsilon, where s0 = p *j % r
while k > self._epsilon:
steps = p if k - self._epsilon > p else k - self._epsilon
H = self._reduce_vector_vertical(H, s0, k, steps)
k -= steps
assert k == self._epsilon
H = [self._Qq(elt).add_bigoh(N0) for elt in H]
return matrix(H).transpose()
@cached_method
def frobenius_matrix(self, N=None):
"""
Compute p-adic Frobenius matrix to precision p^N.
If `N` not supplied, a default value is selected, which is the minimum
needed to recover the charpoly unambiguously.
EXAMPLES::
sage: p = 107
sage: x = PolynomialRing(GF(p),"x").gen()
sage: CyclicCover(2, x^5 + x).frobenius_matrix()
[ O(107^2) 89*107 + O(107^2) O(107^2) O(107^2)]
[ 89*107 + O(107^2) O(107^2) O(107^2) O(107^2)]
[ O(107^2) O(107^2) O(107^2) 105 + 5*107 + O(107^2)]
[ O(107^2) O(107^2) 89 + 53*107 + O(107^2) O(107^2)]
sage: CyclicCover(2, 3*x^5 + x).frobenius_matrix()
[ O(107^2) 14*107 + O(107^2) O(107^2) O(107^2)]
[ 69*107 + O(107^2) O(107^2) O(107^2) O(107^2)]
[ O(107^2) O(107^2) O(107^2) 61 + 58*107 + O(107^2)]
[ O(107^2) O(107^2) 69 + 53*107 + O(107^2) O(107^2)]
sage: CyclicCover(3, x^3 + x).frobenius_matrix()
[ 0 0 O(107) O(107)]
[ 0 0 52 + O(107) O(107)]
[ O(107) 35 + O(107) 0 0]
[44 + O(107) O(107) 0 0]
sage: CyclicCover(3, 3*x^3 + x).frobenius_matrix()
[ 0 0 O(107) O(107)]
[ 0 0 79 + O(107) O(107)]
[ O(107) 42 + O(107) 0 0]
[30 + O(107) O(107) 0 0]
"""
def _frobenius_matrix_p(N0):
r"""
Compute the matrix that represents the p-power Frobenius
"""
assert self._init_frobQ
m = matrix(self._Qq, (self._d - 1) * (self._r - 1))
# Want to build m, "slice by slice" using the output of _frob
for j in range(1, self._r):
s0 = (j * self._p) % self._r
for i in range(self._d - 1):
m[
(s0 - 1) * (self._d - 1) : s0 * (self._d - 1),
i + (j - 1) * (self._d - 1),
] = self._frob(i, j + self._epsilon * self._r, N0)
return m
self._init_frob(N)
FrobP = _frobenius_matrix_p(self._N0)
assert N == self._N0 or N is None
if self._n == 1:
return FrobP
else:
current = FrobP
total = FrobP
for i in range(self._n - 1):
current = matrix(
[[entry.frobenius() for entry in row] for row in current]
)
total = total * current
total = matrix([[elt.add_bigoh(self._N0) for elt in row] for row in total])
return total
@cached_method
def frobenius_polynomial(self):
r"""
Return the characteristic polynomial of Frobenius.
EXAMPLES:
Hyperelliptic curves::
sage: p = 11
sage: x = PolynomialRing(GF(p),"x").gen()
sage: f = x^7 + 4*x^2 + 10*x + 4
sage: CyclicCover(2, f).frobenius_polynomial() == \
....: HyperellipticCurve(f).frobenius_polynomial()
True
sage: f = 2*x^5 + 4*x^3 + x^2 + 2*x + 1
sage: CyclicCover(2, f).frobenius_polynomial() == \
....: HyperellipticCurve(f).frobenius_polynomial()
True
sage: f = 2*x^6 + 4*x^4 + x^3 + 2*x^2 + x
sage: CyclicCover(2, f).frobenius_polynomial() == \
....: HyperellipticCurve(f).frobenius_polynomial()
True
sage: p = 1117
sage: x = PolynomialRing(GF(p),"x").gen()
sage: f = x^9 + 4*x^2 + 10*x + 4
sage: CyclicCover(2, f).frobenius_polynomial() == \
....: HyperellipticCurve(f).frobenius_polynomial() # long time
True
sage: f = 2*x^5 + 4*x^3 + x^2 + 2*x + 1
sage: CyclicCover(2, f).frobenius_polynomial() == \
....: HyperellipticCurve(f).frobenius_polynomial()
True
Superelliptic curves::
sage: p = 11
sage: x = PolynomialRing(GF(p),"x").gen()
sage: CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1).frobenius_polynomial()
x^6 + 21*x^4 + 231*x^2 + 1331
sage: CyclicCover(4, x^3 + x + 1).frobenius_polynomial()
x^6 + 2*x^5 + 11*x^4 + 121*x^2 + 242*x + 1331
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: CyclicCover(4, x^3 - 1).frobenius_polynomial() == \
....: CyclicCover(3, x^4 + 1).frobenius_polynomial()
True
sage: CyclicCover(3, x^4 + 4*x^3 + 9*x^2 + 3*x + 1).frobenius_polynomial()
x^6 + 180*x^5 + 20988*x^4 + 1854349*x^3 + 104919012*x^2 + 4498200180*x + 124925014999
sage: CyclicCover(4,x^5 + x + 1).frobenius_polynomial()
x^12 - 64*x^11 + 5018*x^10 - 488640*x^9 + 28119583*x^8 - 641791616*x^7 + 124245485932*x^6 - 3208316288384*x^5 + 702708407289583*x^4 - 61043359329111360*x^3 + 3133741752599645018*x^2 - 199800079984001599936*x + 15606259372500374970001
sage: CyclicCover(11, PolynomialRing(GF(1129), 'x')([-1] + [0]*(5-1) + [1])).frobenius_polynomial() # long time
x^40 + 7337188909826596*x^30 + 20187877911930897108199045855206*x^20 + 24687045654725446027864774006541463602997309796*x^10 + 11320844849639649951608809973589776933203136765026963553258401
sage: CyclicCover(3, PolynomialRing(GF(1009^2), 'x')([-1] + [0]*(5-1) + [1])).frobenius_polynomial() # long time
x^8 + 532*x^7 - 2877542*x^6 - 242628176*x^5 + 4390163797795*x^4 - 247015136050256*x^3 - 2982540407204025062*x^2 + 561382189105547134612*x + 1074309286591662654798721
A non-monic example checking that :trac:`29015` is fixed::
sage: a = 3
sage: K.<s>=GF(83^3);
sage: R.<x>= PolynomialRing(K)
sage: h = s*x^4 +x*3+ 8;
sage: C = CyclicCover(a,h)
sage: C.frobenius_polynomial()
x^6 + 1563486*x^4 + 893980969482*x^2 + 186940255267540403
Non-superelliptic curves::
sage: p = 13
sage: x = PolynomialRing(GF(p),"x").gen()
sage: C = CyclicCover(4, x^4 + 1)
sage: C.frobenius_polynomial()
x^6 - 6*x^5 + 3*x^4 + 60*x^3 + 39*x^2 - 1014*x + 2197
sage: R.<t> = PowerSeriesRing(Integers())
sage: C.projective_closure().zeta_series(2,t)
1 + 8*t + 102*t^2 + O(t^3)
sage: C.frobenius_polynomial().reverse()(t)/((1-t)*(1-p*t)) + O(t^5)
1 + 8*t + 102*t^2 + 1384*t^3 + 18089*t^4 + O(t^5)
sage: x = PolynomialRing(GF(11),"x").gen()
sage: CyclicCover(4, x^6 - 11*x^3 + 70*x^2 - x + 961).frobenius_polynomial() # long time
x^14 + 14*x^12 + 287*x^10 + 3025*x^8 + 33275*x^6 + 381997*x^4 + 2254714*x^2 + 19487171
sage: x = PolynomialRing(GF(4999),"x").gen()
sage: CyclicCover(4, x^6 - 11*x^3 + 70*x^2 - x + 961).frobenius_polynomial() # long time
x^14 - 4*x^13 - 2822*x^12 - 30032*x^11 + 37164411*x^10 - 152369520*x^9 + 54217349361*x^8 - 1021791160888*x^7 + 271032529455639*x^6 - 3807714457169520*x^5 + 4642764601604000589*x^4 - 18754988504199390032*x^3 - 8809934776794570547178*x^2 - 62425037490001499880004*x + 78015690603129374475034999
sage: p = 11
sage: x = PolynomialRing(GF(p),"x").gen()
sage: CyclicCover(3, 5*x^3 - 5*x + 13).frobenius_polynomial()
x^2 + 11
sage: CyclicCover(3, x^6 + x^4 - x^3 + 2*x^2 - x - 1).frobenius_polynomial()
x^8 + 32*x^6 + 462*x^4 + 3872*x^2 + 14641
sage: p = 4999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: CyclicCover(3, 5*x^3 - 5*x + 13).frobenius_polynomial()
x^2 - 47*x + 4999
sage: CyclicCover(3, x^6 + x^4 - x^3 + 2*x^2 - x - 1).frobenius_polynomial()
x^8 + 122*x^7 + 4594*x^6 - 639110*x^5 - 82959649*x^4 - 3194910890*x^3 + 114804064594*x^2 + 15240851829878*x + 624500149980001
sage: p = 11
sage: x = PolynomialRing(GF(p),"x").gen()
sage: CyclicCover(5, x^5 + x).frobenius_polynomial() # long time
x^12 + 4*x^11 + 22*x^10 + 108*x^9 + 503*x^8 + 1848*x^7 + 5588*x^6 + 20328*x^5 + 60863*x^4 + 143748*x^3 + 322102*x^2 + 644204*x + 1771561
sage: CyclicCover(5, 2*x^5 + x).frobenius_polynomial() # long time
x^12 - 9*x^11 + 42*x^10 - 108*x^9 - 47*x^8 + 1782*x^7 - 8327*x^6 + 19602*x^5 - 5687*x^4 - 143748*x^3 + 614922*x^2 - 1449459*x + 1771561
sage: p = 49999
sage: x = PolynomialRing(GF(p),"x").gen()
sage: CyclicCover(5, x^5 + x ).frobenius_polynomial() # long time
x^12 + 299994*x^10 + 37498500015*x^8 + 2499850002999980*x^6 + 93742500224997000015*x^4 + 1874812507499850001499994*x^2 + 15623125093747500037499700001
sage: CyclicCover(5, 2*x^5 + x).frobenius_polynomial() # long time
x^12 + 299994*x^10 + 37498500015*x^8 + 2499850002999980*x^6 + 93742500224997000015*x^4 + 1874812507499850001499994*x^2 + 15623125093747500037499700001
TESTS::
sage: for _ in range(5): # long time
....: fail = False
....: p = random_prime(500, lbound=5)
....: for i in range(1, 4):
....: F = GF((p, i))
....: Fx = PolynomialRing(F, 'x')
....: b = F.random_element()
....: while b == 0:
....: b = F.random_element()
....: E = EllipticCurve(F, [0, b])
....: C1 = CyclicCover(3, Fx([-b, 0, 1]))
....: C2 = CyclicCover(2, Fx([b, 0, 0, 1]))
....: frob = [elt.frobenius_polynomial() for elt in [E, C1, C2]]
....: if len(set(frob)) != 1:
....: E
....: C1
....: C2
....: frob
....: fail = True
....: break
....: if fail:
....: break
....: else:
....: True
True
"""
self._init_frob()
F = self.frobenius_matrix(self._N0)
def _denominator():
R = PolynomialRing(ZZ, "T")
T = R.gen()
denom = R(1)
lc = self._f.list()[-1]
if lc == 1: # MONIC
for i in range(2, self._delta + 1):
if self._delta % i == 0:
phi = euler_phi(i)
G = IntegerModRing(i)
ki = G(self._q).multiplicative_order()
denom = denom * (T ** ki - 1) ** (phi // ki)
return denom
else: # Non-monic
x = PolynomialRing(self._Fq, "x").gen()
f = x ** self._delta - lc
L = f.splitting_field("a")
roots = [r for r, _ in f.change_ring(L).roots()]
roots_dict = dict([(r, i) for i, r in enumerate(roots)])
rootsfrob = [L.frobenius_endomorphism(self._Fq.degree())(r) for r in roots]
m = zero_matrix(len(roots))
for i, r in enumerate(roots):
m[i, roots_dict[rootsfrob[i]]] = 1
return R(R(m.characteristic_polynomial()) // (T - 1))
denom = _denominator()
R = PolynomialRing(ZZ, "x")
if self._nodenominators:
min_val = 0
else:
# are there any denominators in F?
min_val = min(self._Qq(elt).valuation() for row in F.rows() for elt in row)
if min_val >= 0:
prec = _N0_nodenominators(self._p, self._genus, self._n)
charpoly_prec = [prec + i for i in reversed(range(1, self._genus + 1))] + [
prec
] * (self._genus + 1)
cp = charpoly_frobenius(F, charpoly_prec, self._p, 1, self._n, denom.list())
return R(cp)
else:
cp = F.charpoly().reverse()
denom = denom.reverse()
PS = PowerSeriesRing(self._Zp, "T")
cp = PS(cp) / PS(denom)
cp = cp.padded_list(self._genus + 1)
cpZZ = [None for _ in range(2 * self._genus + 1)]
cpZZ[0] = 1
cpZZ[-1] = self._p ** self._genus
for i in range(1, self._genus + 1):
cmod = cp[i]
bound = binomial(2 * self._genus, i) * self._p ** (i * self._n * 0.5)
localmod = self._p ** (ceil(log(bound, self._p)))
c = cmod.lift() % localmod
if c > bound:
c = -(-cmod.lift() % localmod)
cpZZ[i] = c
if i != self._genus + 1:
cpZZ[2 * self._genus - i] = c * self._p ** (self._genus - i)
cpZZ.reverse()
return R(cpZZ) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/cyclic_covers/cycliccover_finite_field.py | 0.762689 | 0.768625 | cycliccover_finite_field.py | pypi |
from sage.rings.polynomial.polynomial_element import is_Polynomial
from sage.rings.finite_rings.finite_field_constructor import is_FiniteField
from sage.schemes.affine.affine_space import AffineSpace
from .cycliccover_generic import CyclicCover_generic
from .cycliccover_finite_field import CyclicCover_finite_field
def CyclicCover(r, f, names=None, check_smooth=True):
r"""
Return the cyclic cover of the projective line given by `y^r = f`, for
a univariate polynomial `f`.
INPUT:
- ``r`` - the order of the cover
- ``f`` - univariate polynomial if not given, then it defaults to 0.
- ``names`` (default: ``["x","y"]``) - names for the
coordinate functions
- ``check_squarefree`` (default: ``True``) - test if
the input defines a unramified cover of the projective line.
.. WARNING::
When setting ``check_smooth=False`` or using a base ring that is
not a field, the output curves are not to be trusted. For example, the
output of ``is_singular`` or ``is_smooth`` only tests smoothness over
the field of fractions.
.. NOTE::
The words "cyclic cover" are usually used for covers of degree
greater than two.
We usually refer to smooth double covers of the projective line as
"hyperelliptic curves" or "elliptic curves" if the genus is one.
We allow such cases in this implementation, but we highly recommend
to use the more specific constructors/classes HyperellipticCurve and
EllipticCurve for a wider range of tools.
EXAMPLES:
Basic examples::
sage: R.<x> = QQ[]
sage: CyclicCover(2, x^5 + x + 1)
Cyclic Cover of P^1 over Rational Field defined by y^2 = x^5 + x + 1
sage: CyclicCover(3, x^5 + x + 1)
Cyclic Cover of P^1 over Rational Field defined by y^3 = x^5 + x + 1
sage: CyclicCover(5, x^5 + x + 1)
Cyclic Cover of P^1 over Rational Field defined by y^5 = x^5 + x + 1
sage: CyclicCover(15, x^9 + x + 1)
Cyclic Cover of P^1 over Rational Field defined by y^15 = x^9 + x + 1
sage: k.<a> = GF(9); R.<x> = k[]
sage: CyclicCover(5, x^9 + x + 1)
Cyclic Cover of P^1 over Finite Field in a of size 3^2 defined by y^5 = x^9 + x + 1
sage: CyclicCover(15, x^9 + x + 1)
Traceback (most recent call last):
...
ValueError: As the characteristic divides the order of the cover, this model is not smooth.
We can change the names of the variables in the output::
sage: k.<a> = GF(9); R.<x> = k[]
sage: CyclicCover(5, x^9 + x + 1, names = ["A","B"])
Cyclic Cover of P^1 over Finite Field in a of size 3^2 defined by B^5 = A^9 + A + 1
Double roots::
sage: P.<x> = GF(7)[]
sage: CyclicCover(2,(x^3-x+2)^2*(x^6-1))
Traceback (most recent call last):
...
ValueError: Not a smooth Cyclic Cover of P^1: singularity in the provided affine patch.
sage: CyclicCover(2, (x^3-x+2)^2*(x^6-1), check_smooth=False)
Cyclic Cover of P^1 over Finite Field of size 7 defined by y^2 = x^12 - 2*x^10 - 3*x^9 + x^8 + 3*x^7 + 3*x^6 + 2*x^4 + 3*x^3 - x^2 - 3*x + 3
Input with integer coefficients creates objects with the integers
as base ring, but only checks smoothness over `\QQ`, not over Spec(`\ZZ`).
In other words, it is checked that the discriminant is non-zero, but it is
not checked whether the discriminant is a unit in `\ZZ^*`.::
sage: R.<x> = ZZ[]
sage: CyclicCover(5,(x^3-x+2)*(x^6-1))
Cyclic Cover of P^1 over Integer Ring defined by y^5 = x^9 - x^7 + 2*x^6 - x^3 + x - 2
"""
if not is_Polynomial(f):
raise TypeError("Arguments f (= %s) must be a polynomial" % (f,))
P = f.parent()
f = P(f)
if check_smooth:
if P(r) == 0:
raise ValueError(
"As the characteristic divides the order of the cover, "
"this model is not smooth."
)
try:
smooth = f.is_squarefree()
except NotImplementedError as err:
raise NotImplementedError(
str(err) + "Use " "check_smooth=False to skip this check."
)
if not smooth:
raise ValueError(
"Not a smooth Cyclic Cover of P^1: "
"singularity in the provided affine patch."
)
R = P.base_ring()
if names is None:
names = ["x", "y"]
A2 = AffineSpace(2, R, names=names)
if is_FiniteField(R):
return CyclicCover_finite_field(A2, r, f, names=names)
else:
return CyclicCover_generic(A2, r, f, names=names) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/cyclic_covers/constructor.py | 0.923549 | 0.767886 | constructor.py | pypi |
from sage.rings.polynomial.all import PolynomialRing
from sage.structure.category_object import normalize_names
from sage.arith.misc import GCD
from sage.schemes.curves.affine_curve import AffinePlaneCurve
class CyclicCover_generic(AffinePlaneCurve):
def __init__(self, AA, r, f, names=None):
"""
Cyclic covers over a general ring
INPUT:
- ``A`` - ambient affine space
- ``r`` - degree of the cover
- ``f`` - univariate polynomial
- ``names`` (default: ``["x","y"]``) - names for the
coordinate functions
TESTS::
sage: ZZx.<x> = ZZ[]
sage: C = CyclicCover(5, x^5 + x + 1); C
Cyclic Cover of P^1 over Integer Ring defined by y^5 = x^5 + x + 1
sage: C.genus()
6
sage: D = C.projective_closure(); D
Projective Plane Curve over Integer Ring defined by x0^5 + x0^4*x1 + x1^5 - x2^5
sage: D.change_ring(QQ).genus()
6
sage: C.change_ring(GF(5))
Traceback (most recent call last):
...
ValueError: As the characteristic divides the order of the cover, this model is not smooth.
sage: GF7x.<x> = GF(7)[]
sage: C = CyclicCover(3, x^9 + x + 1)
sage: C
Cyclic Cover of P^1 over Finite Field of size 7 defined by y^3 = x^9 + x + 1
sage: C.genus()
7
sage: C.projective_closure()
Traceback (most recent call last):
...
NotImplementedError: Weighted Projective Space is not implemented
"""
x, y = AA.gens()
self._r = r
self._d = f.degree()
self._delta = GCD(self._r, self._d)
self._genus = ((self._d - 1) * (self._r - 1) - (self._delta - 1)) // 2
self._f = f
F = y**r - f(x)
AffinePlaneCurve.__init__(self, AA, F)
if names is None:
names = ("x", "y")
else:
names = normalize_names(2, names)
self._names = names
def change_ring(self, R):
"""
Return this CyclicCover over a new base ring R.
EXAMPLES::
sage: ZZx.<x> = ZZ[]
sage: C = CyclicCover(5, x^5 + x + 1)
sage: C.change_ring(GF(5))
Traceback (most recent call last):
...
ValueError: As the characteristic divides the order of the cover, this model is not smooth.
sage: C.change_ring(GF(3))
Traceback (most recent call last):
...
ValueError: Not a smooth Cyclic Cover of P^1: singularity in the provided affine patch.
sage: C.change_ring(GF(17))
Cyclic Cover of P^1 over Finite Field of size 17 defined by y^5 = x^5 + x + 1
"""
from .constructor import CyclicCover
return CyclicCover(self._r, self._f.change_ring(R), self._names)
base_extend = change_ring
def _repr_(self):
"""
String representation of cyclic covers.
EXAMPLES::
sage: R.<x> = QQ[]
sage: CyclicCover(2, x^5 + x + 1)
Cyclic Cover of P^1 over Rational Field defined by y^2 = x^5 + x + 1
sage: CyclicCover(3, x^5 + x + 1)
Cyclic Cover of P^1 over Rational Field defined by y^3 = x^5 + x + 1
sage: CyclicCover(5, x^5 + x + 1)
Cyclic Cover of P^1 over Rational Field defined by y^5 = x^5 + x + 1
sage: CyclicCover(15, x^9 + x + 1)
Cyclic Cover of P^1 over Rational Field defined by y^15 = x^9 + x + 1
"""
R = self.base_ring()
x, y = self.ambient_space().gens()
r = self._r
f = self._f
return "Cyclic Cover of P^1 over %s defined by %s = %s" % (R, y**r, f(x))
def __eq__(self, other):
"""
Test of equality.
EXAMPLES::
sage: ZZx.<x> = ZZ[]
sage: C0 = CyclicCover(5, x^5 + x + 1)
sage: C1 = C0.change_ring(QQ)
sage: C1 == C0
False
sage: C2 = CyclicCover(3, x^5 + x + 1)
sage: C2 == C0
False
sage: C3 = CyclicCover(5, x^6 + x + 1)
sage: C3 == C0
False
sage: C0 == CyclicCover(5, x^5 + x + 1)
True
"""
if not isinstance(other, CyclicCover_generic):
return False
return (
(self.base_ring() == other.base_ring())
and (self._r == other._r)
and (self._f == other._f)
)
def __ne__(self, other):
"""
Test of not equality.
EXAMPLES::
sage: ZZx.<x> = ZZ[]
sage: C0 = CyclicCover(5, x^5 + x + 1)
sage: C1 = C0.change_ring(QQ)
sage: C1 != C0
True
sage: C2 = CyclicCover(3, x^5 + x + 1)
sage: C2 != C0
True
sage: C3 = CyclicCover(5, x^6 + x + 1)
sage: C3 != C0
True
sage: C0 != CyclicCover(5, x^5 + x + 1)
False
"""
return not self == other
def order(self):
"""
The order of the cover.
EXAMPLES::
sage: ZZx.<x> = ZZ[]
sage: CyclicCover(5, x^5 + x + 1).order()
5
sage: CyclicCover(3, x^5 + x + 1).order()
3
"""
return self._r
def genus(self):
"""
The geometric genus of the curve.
EXAMPLES::
sage: ZZx.<x> = ZZ[]
sage: CyclicCover(5, x^5 + x + 1).genus()
6
sage: CyclicCover(3, x^5 + x + 1).genus()
4
"""
return self._genus
def projective_closure(self, **kwds):
"""
Return the projective closure of this affine curve.
EXAMPLES::
sage: GF7x.<x> = GF(7)[]
sage: CyclicCover(3, x^9 + x + 1).projective_closure()
Traceback (most recent call last):
...
NotImplementedError: Weighted Projective Space is not implemented
sage: ZZx.<x> = ZZ[]
sage: CyclicCover(5, x^5 + x + 1).projective_closure()
Projective Plane Curve over Integer Ring defined by x0^5 + x0^4*x1 + x1^5 - x2^5
"""
# test d = 3 and 4
if self._d == self._r:
return AffinePlaneCurve.projective_closure(self, **kwds)
else:
raise NotImplementedError("Weighted Projective Space is not implemented")
def cover_polynomial(self, K=None, var="x"):
"""
Return the polynomial defining the cyclic cover.
EXAMPLES::
sage: ZZx.<x> = ZZ[]; CyclicCover(5, x^5 + x + 1).cover_polynomial()
x^5 + x + 1
"""
if K is None:
return self._f
else:
P = PolynomialRing(K, var)
return P(self._f)
def is_singular(self):
r"""
Return if this curve is singular or not.
This just checks that the characteristic of the ring does not divide the
order of the cover and that the defining polynomial of the cover is
square free.
EXAMPLES::
sage: R.<x> = QQ[]
sage: CyclicCover(3, x^5 + x + 1).is_singular()
False
sage: CyclicCover(3, (x^5 + x + 1)^2, check_smooth=False).is_singular()
True
"""
P = self._f.parent()
r = self._r
if P(r) == 0:
return True
else:
return not self._f.is_squarefree()
def is_smooth(self):
r"""
Return if this curve is smooth or not.
This just checks that the characteristic of the ring does not divide the
order of the cover and that the defining polynomial of the cover is
square free.
EXAMPLES::
sage: R.<x> = QQ[]
sage: CyclicCover(3, x^5 + x + 1).is_smooth()
True
sage: CyclicCover(3, (x^5 + x + 1)^2, check_smooth=False).is_smooth()
False
"""
return not self.is_singular() | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/cyclic_covers/cycliccover_generic.py | 0.851413 | 0.616012 | cycliccover_generic.py | pypi |
r"""
Points of bounded height in projective spaces
This module defines functions to compute points of bounded height of a given
number field with height less than a specified bound in projective spaces.
Sage functions to list all elements of a given number field with height less
than a specified bound.
AUTHORS:
- Jing Guo (2022): initial version based on David Krumm's code
REFERENCES:
- [Krumm2016]
"""
import itertools
from math import floor
from sage.schemes.projective.projective_space import ProjectiveSpace
from sage.rings.rational_field import QQ
from sage.rings.all import RealField
from sage.rings.number_field.unit_group import UnitGroup
from sage.arith.all import gcd
from sage.matrix.constructor import matrix, column_matrix
from sage.libs.pari.all import pari
from sage.modules.free_module_element import vector
from sage.rings.integer import Integer
from sage.geometry.polyhedron.constructor import Polyhedron
def QQ_points_of_bounded_height(dim, bound):
r"""
Return an iterator of the points in ``self`` of absolute multiplicative
height of at most ``bound`` in the rational field.
INPUT:
- ``dim`` -- a positive integer
- ``bound`` -- a real number
OUTPUT:
- an iterator of points of bounded height
EXAMPLES:
sage: from sage.schemes.projective.proj_bdd_height import QQ_points_of_bounded_height
sage: sorted(list(QQ_points_of_bounded_height(1, 1)))
[(-1 : 1), (0 : 1), (1 : 0), (1 : 1)]
sage: len(list(QQ_points_of_bounded_height(1, 5)))
40
There are no points of negative height::
sage: from sage.schemes.projective.proj_bdd_height import QQ_points_of_bounded_height
sage: list(QQ_points_of_bounded_height(1, -3))
[]
"""
if bound < 1:
return iter(set([]))
PN = ProjectiveSpace(QQ, dim)
unit_tuples = list(itertools.product([-1, 1], repeat=dim))
points_of_bounded_height = set([])
increasing_tuples = itertools.combinations_with_replacement(range(floor(bound + 1)), dim + 1)
for t in increasing_tuples:
if gcd(t) == 1:
for p in itertools.permutations(t):
for u in unit_tuples:
point = PN([a*b for a, b in zip(u, p)] + [p[dim]])
if point not in points_of_bounded_height:
points_of_bounded_height.add(point)
yield point
def IQ_points_of_bounded_height(PN, K, dim, bound):
r"""
Return an iterator of the points in ``self`` of absolute multiplicative
height of at most ``bound`` in the imaginary quadratic field ``K``.
INPUT:
- ``PN`` -- a projective space
- ``K`` -- a number field
- ``dim`` -- a positive interger
- ``bound`` -- a real number
OUTPUT:
- an iterator of points of bounded height
EXAMPLES:
sage: from sage.schemes.projective.proj_bdd_height import IQ_points_of_bounded_height
sage: CF.<a> = CyclotomicField(3)
sage: P.<x,y,z> = ProjectiveSpace(CF, 2)
sage: len(list(IQ_points_of_bounded_height(P, CF, 2, -1)))
0
sage: len(list(IQ_points_of_bounded_height(P, CF, 2, 1)))
57
"""
if bound < 1:
return iter([])
unit_tuples = list(itertools.product(K.roots_of_unity(), repeat=dim))
class_group_ideals = [c.ideal() for c in K.class_group()]
class_group_ideal_norms = [i.norm() for i in class_group_ideals]
class_number = len(class_group_ideals)
possible_norm_set = set([])
for i in range(class_number):
for k in range(1, floor(bound + 1)):
possible_norm_set.add(k*class_group_ideal_norms[i])
coordinate_space = dict()
coordinate_space[0] = [K(0)]
for m in possible_norm_set:
coordinate_space[m] = K.elements_of_norm(m)
for i in range(class_number):
a = class_group_ideals[i]
a_norm = class_group_ideal_norms[i]
a_norm_bound = bound * a_norm
a_coordinates = []
for m in coordinate_space:
if m <= a_norm_bound:
for x in coordinate_space[m]:
if x in a:
a_coordinates.append(x)
points_in_class_a = set([])
t = len(a_coordinates) - 1
increasing_tuples = itertools.combinations_with_replacement(range(t + 1), dim + 1)
for index_tuple in increasing_tuples:
point_coordinates = [a_coordinates[i] for i in index_tuple]
if a == K.ideal(point_coordinates):
for p in itertools.permutations(point_coordinates):
for u in unit_tuples:
point = PN([i*j for i, j in zip(u, p)] + [p[dim]])
if point not in points_in_class_a:
points_in_class_a.add(point)
yield point
def points_of_bounded_height(PN, K, dim, bound, prec=53):
r"""
Return an iterator of the points in ``K`` with dimension ``dim`` of
absolute multiplicative height of at most ``bound``.
ALGORITHM:
This is an implementation of Algorithm 6 in [Krumm2016]_.
INPUT:
- ``PN`` -- a projective space
- ``K`` -- a number field
- ``dim`` -- a positive interger
- ``bound`` -- a real number
- ``prec`` -- (default: 53) a positive integer
OUTPUT:
- an iterator of points of bounded height
EXAMPLES:
sage: from sage.schemes.projective.proj_bdd_height import points_of_bounded_height
sage: K.<a> = NumberField(x^3 - 7)
sage: P.<x,y,z> = ProjectiveSpace(K, 2)
sage: len(list(points_of_bounded_height(P, K, 2, 1)))
13
"""
if bound < 1:
return iter([])
r1, r2 = K.signature()
r = r1 + r2 - 1
if K.is_relative():
K_degree = K.relative_degree()
else:
K_degree = K.degree()
roots_of_unity = K.roots_of_unity()
unit_tuples = list(itertools.product(roots_of_unity, repeat=dim))
log_embed = K.logarithmic_embedding()
Reals = RealField(prec)
logB = Reals(bound).log()
class_group_ideals = [c.ideal() for c in K.class_group()]
class_number = len(class_group_ideals)
if K.is_relative():
class_group_ideal_norms = [i.absolute_norm() for i in class_group_ideals]
else:
class_group_ideal_norms = [i.norm() for i in class_group_ideals]
norm_bound = bound * max(class_group_ideal_norms)
fundamental_units = UnitGroup(K).fundamental_units()
fund_unit_logs = list(map(log_embed, fundamental_units))
mat = column_matrix(fund_unit_logs)
test_matrix = mat
try:
test_matrix.change_ring(QQ)
except ValueError:
raise ValueError('prec too low.')
cut_fund_unit_logs = mat.delete_rows([r])
lll_fund_units = []
for c in pari(cut_fund_unit_logs).qflll().python():
new_unit = 1
for i in range(r):
new_unit *= fundamental_units[i]**c[i]
lll_fund_units.append(new_unit)
fundamental_units = lll_fund_units
fund_unit_logs = list(map(log_embed, fundamental_units))
possible_norm_set = set([])
for i in range(class_number):
for k in range(1, floor(bound + 1)):
possible_norm_set.add(k*class_group_ideal_norms[i])
principal_ideal_gens = dict()
negative_norm_units = K.elements_of_norm(-1)
if len(negative_norm_units) == 0:
for m in possible_norm_set:
principal_ideal_gens[m] = K.elements_of_norm(m) + K.elements_of_norm(-m)
else:
for m in possible_norm_set:
principal_ideal_gens[m] = K.elements_of_norm(m)
pr_ideal_gen_logs = dict()
for key in principal_ideal_gens:
for y in principal_ideal_gens[key]:
pr_ideal_gen_logs[y] = log_embed(y)
fund_parallelotope_vertices = []
for coefficient_tuple in itertools.product([-1/2, 1/2], repeat=r):
vertex = sum([coefficient_tuple[i]*fund_unit_logs[i] for i in range(r)])
fund_parallelotope_vertices.append(vertex)
D_numbers = []
for v in range(r + 1):
D_numbers.append(max([vertex[v] for vertex in fund_parallelotope_vertices]))
A_numbers = []
for v in range(r + 1):
A_numbers.append(min([pr_ideal_gen_logs[y][v] for y in pr_ideal_gen_logs]))
aux_constant = (1/K_degree) * Reals(norm_bound).log()
L_numbers = []
for v in range(r1):
L_numbers.append(aux_constant + D_numbers[v] - A_numbers[v])
for v in range(r1, r + 1):
L_numbers.append(2*aux_constant + D_numbers[v] - A_numbers[v])
L_numbers = vector(L_numbers).change_ring(QQ)
T = column_matrix(fund_unit_logs).delete_rows([r]).change_ring(QQ)
# insert_row only takes integers, see https://trac.sagemath.org/ticket/11328
M = ((-1)*matrix.identity(r)).insert_row(r, [Integer(1) for i in range(r)])
M = M.transpose().insert_row(0, [Integer(0) for i in range(r + 1)]).transpose()
M = M.change_ring(QQ)
M.set_column(0, L_numbers)
vertices = map(vector, Polyhedron(ieqs=list(M)).vertices())
T_it = T.inverse().transpose()
unit_polytope = Polyhedron([v*T_it for v in vertices])
coordinate_space = dict()
coordinate_space[0] = [[K(0), log_embed(0)]]
int_points = unit_polytope.integral_points()
units_with_logs = dict()
for n in int_points:
new_unit = 1
for j in range(r):
new_unit *= fundamental_units[j]**n[j]
new_unit_log = sum([n[j]*fund_unit_logs[j] for j in range(r)])
units_with_logs[n] = [new_unit, new_unit_log]
for norm in principal_ideal_gens:
coordinate_list = []
for y in principal_ideal_gens[norm]:
for n in int_points:
unit, unit_log = units_with_logs[n]
y_log = pr_ideal_gen_logs[y]
g_log = unit_log + y_log
bool1 = all(g_log[i] <= aux_constant + D_numbers[i] for i in range(r1))
bool2 = all(g_log[j] <= 2 * aux_constant + D_numbers[j] for j in range(r1, r + 1))
if bool1 and bool2:
g = unit * y
coordinate_list.append([g, g_log])
if len(coordinate_list) > 0:
coordinate_space[norm] = coordinate_list
for m in range(class_number):
a = class_group_ideals[m]
a_norm = class_group_ideal_norms[m]
log_a_norm = Reals(a_norm).log()
a_const = (logB + log_a_norm)/K_degree
a_coordinates = []
for k in range(floor(bound + 1)):
norm = k * a_norm
if norm in coordinate_space:
for pair in coordinate_space[norm]:
g, g_log = pair
if g in a:
bool1 = all(g_log[i] <= a_const + D_numbers[i] for i in range(r1))
bool2 = all(g_log[j] <= 2 * a_const + D_numbers[j] for j in range(r1, r + 1))
if bool1 and bool2:
a_coordinates.append(pair)
t = len(a_coordinates) - 1
points_in_class_a = set([])
increasing_tuples = itertools.combinations_with_replacement(range(t + 1), dim + 1)
log_arch_height_bound = logB + log_a_norm
for index_tuple in increasing_tuples:
point_coordinates = [a_coordinates[i][0] for i in index_tuple]
point_coordinate_logs = [a_coordinates[i][1] for i in index_tuple]
log_arch_height = sum([max([x[i] for x in point_coordinate_logs]) for i in range(r + 1)])
if log_arch_height <= log_arch_height_bound and a == K.ideal(point_coordinates):
for p in itertools.permutations(point_coordinates):
for u in unit_tuples:
point = PN([i*j for i, j in zip(u, p)] + [p[dim]])
if point not in points_in_class_a:
points_in_class_a.add(point)
yield point | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/projective/proj_bdd_height.py | 0.930836 | 0.781372 | proj_bdd_height.py | pypi |
from sage.categories.fields import Fields
_Fields = Fields()
from sage.schemes.generic.scheme import Scheme, is_Scheme
from sage.structure.richcmp import richcmp_method, richcmp
def is_Jacobian(J):
"""
Return True if `J` is of type Jacobian_generic.
EXAMPLES::
sage: from sage.schemes.jacobians.abstract_jacobian import Jacobian, is_Jacobian
sage: P2.<x, y, z> = ProjectiveSpace(QQ, 2)
sage: C = Curve(x^3 + y^3 + z^3)
sage: J = Jacobian(C)
sage: is_Jacobian(J)
True
::
sage: E = EllipticCurve('37a1')
sage: is_Jacobian(E)
False
"""
return isinstance(J, Jacobian_generic)
def Jacobian(C):
"""
EXAMPLES::
sage: from sage.schemes.jacobians.abstract_jacobian import Jacobian
sage: P2.<x, y, z> = ProjectiveSpace(QQ, 2)
sage: C = Curve(x^3 + y^3 + z^3)
sage: Jacobian(C)
Jacobian of Projective Plane Curve over Rational Field defined by x^3 + y^3 + z^3
"""
try:
return C.jacobian()
except AttributeError:
return Jacobian_generic(C)
@richcmp_method
class Jacobian_generic(Scheme):
"""
Base class for Jacobians of projective curves.
The input must be a projective curve over a field.
EXAMPLES::
sage: from sage.schemes.jacobians.abstract_jacobian import Jacobian
sage: P2.<x, y, z> = ProjectiveSpace(QQ, 2)
sage: C = Curve(x^3 + y^3 + z^3)
sage: J = Jacobian(C); J
Jacobian of Projective Plane Curve over Rational Field defined by x^3 + y^3 + z^3
"""
def __init__(self, C):
"""
Initialize.
TESTS::
sage: from sage.schemes.jacobians.abstract_jacobian import Jacobian_generic
sage: P2.<x, y, z> = ProjectiveSpace(QQ, 2)
sage: C = Curve(x^3 + y^3 + z^3)
sage: J = Jacobian_generic(C); J
Jacobian of Projective Plane Curve over Rational Field defined by x^3 + y^3 + z^3
sage: type(J)
<class 'sage.schemes.jacobians.abstract_jacobian.Jacobian_generic_with_category'>
Note: this is an abstract parent, so we skip element tests::
sage: TestSuite(J).run(skip =["_test_an_element",\
"_test_elements",\
"_test_elements_eq_reflexive",\
"_test_elements_eq_symmetric",\
"_test_elements_eq_transitive",\
"_test_elements_neq",\
"_test_some_elements"])
::
sage: Jacobian_generic(ZZ)
Traceback (most recent call last):
...
TypeError: Argument (=Integer Ring) must be a scheme.
sage: Jacobian_generic(P2)
Traceback (most recent call last):
...
ValueError: C (=Projective Space of dimension 2 over Rational Field)
must have dimension 1.
::
sage: P2.<x, y, z> = ProjectiveSpace(Zmod(6), 2)
sage: C = Curve(x + y + z, P2)
sage: Jacobian_generic(C)
Traceback (most recent call last):
...
TypeError: C (=Projective Plane Curve over Ring of integers modulo 6
defined by x + y + z) must be defined over a field.
"""
if not is_Scheme(C):
raise TypeError("Argument (=%s) must be a scheme."%C)
if C.base_ring() not in _Fields:
raise TypeError("C (=%s) must be defined over a field."%C)
if C.dimension() != 1:
raise ValueError("C (=%s) must have dimension 1."%C)
self.__curve = C
Scheme.__init__(self, C.base_scheme())
def __richcmp__(self, J, op):
"""
Compare the Jacobian self to `J`. If `J` is a Jacobian, then
self and `J` are equal if and only if their curves are equal.
EXAMPLES::
sage: from sage.schemes.jacobians.abstract_jacobian import Jacobian
sage: P2.<x, y, z> = ProjectiveSpace(QQ, 2)
sage: J1 = Jacobian(Curve(x^3 + y^3 + z^3))
sage: J1 == J1
True
sage: J1 == P2
False
sage: J1 != P2
True
sage: J2 = Jacobian(Curve(x + y + z))
sage: J1 == J2
False
sage: J1 != J2
True
"""
if not is_Jacobian(J):
return NotImplemented
return richcmp(self.curve(), J.curve(), op)
def _repr_(self):
"""
Return a string representation of this Jacobian.
EXAMPLES::
sage: from sage.schemes.jacobians.abstract_jacobian import Jacobian
sage: P2.<x, y, z> = ProjectiveSpace(QQ, 2)
sage: J = Jacobian(Curve(x^3 + y^3 + z^3)); J
Jacobian of Projective Plane Curve over Rational Field defined by x^3 + y^3 + z^3
sage: J._repr_()
'Jacobian of Projective Plane Curve over Rational Field defined by x^3 + y^3 + z^3'
"""
return "Jacobian of %s" % self.__curve
def _point(self):
"""
Return the Hom-set from some affine scheme to ``self``.
OUTPUT:
This method always raises a ``NotImplementedError``; it is
only abstract.
EXAMPLES::
sage: from sage.schemes.jacobians.abstract_jacobian import Jacobian
sage: P2.<x, y, z> = ProjectiveSpace(QQ, 2)
sage: J = Jacobian(Curve(x^3 + y^3 + z^3))
sage: J._point()
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
def curve(self):
"""
Return the curve of which self is the Jacobian.
EXAMPLES::
sage: from sage.schemes.jacobians.abstract_jacobian import Jacobian
sage: P2.<x, y, z> = ProjectiveSpace(QQ, 2)
sage: J = Jacobian(Curve(x^3 + y^3 + z^3))
sage: J.curve()
Projective Plane Curve over Rational Field defined by x^3 + y^3 + z^3
"""
return self.__curve
def change_ring(self, R):
r"""
Return the Jacobian over the ring `R`.
INPUT:
- ``R`` -- a field. The new base ring.
OUTPUT:
The Jacobian over the ring `R`.
EXAMPLES::
sage: R.<x> = QQ['x']
sage: H = HyperellipticCurve(x^3-10*x+9)
sage: Jac = H.jacobian(); Jac
Jacobian of Hyperelliptic Curve over Rational
Field defined by y^2 = x^3 - 10*x + 9
sage: Jac.change_ring(RDF)
Jacobian of Hyperelliptic Curve over Real Double
Field defined by y^2 = x^3 - 10.0*x + 9.0
"""
return self.curve().change_ring(R).jacobian()
def base_extend(self, R):
r"""
Return the natural extension of ``self`` over `R`
INPUT:
- ``R`` -- a field. The new base field.
OUTPUT:
The Jacobian over the ring `R`.
EXAMPLES::
sage: R.<x> = QQ['x']
sage: H = HyperellipticCurve(x^3-10*x+9)
sage: Jac = H.jacobian(); Jac
Jacobian of Hyperelliptic Curve over Rational Field defined by y^2 = x^3 - 10*x + 9
sage: F.<a> = QQ.extension(x^2+1)
sage: Jac.base_extend(F)
Jacobian of Hyperelliptic Curve over Number Field in a with defining
polynomial x^2 + 1 defined by y^2 = x^3 - 10*x + 9
"""
if R not in _Fields:
raise ValueError('Not a field: ' + str(R))
if self.base_ring() is R:
return self
if not R.has_coerce_map_from(self.base_ring()):
raise ValueError('no natural map from the base ring (=%s) to R (=%s)!'
% (self.base_ring(), R))
return self.change_ring(R) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/jacobians/abstract_jacobian.py | 0.925407 | 0.632105 | abstract_jacobian.py | pypi |
from sage.misc.latex import latex
from sage.categories.finite_fields import FiniteFields
from sage.categories.fields import Fields
from sage.schemes.generic.algebraic_scheme import AlgebraicScheme_subscheme
from sage.schemes.generic.divisor_group import DivisorGroup
from sage.schemes.generic.divisor import Divisor_curve
from sage.rings.integer import Integer
class Curve_generic(AlgebraicScheme_subscheme):
r"""
Generic curve class.
EXAMPLES::
sage: A.<x,y,z> = AffineSpace(QQ,3)
sage: C = Curve([x-y,z-2])
sage: loads(C.dumps()) == C
True
"""
def _repr_(self):
"""
Return a string representation of this curve.
EXAMPLES::
sage: A.<x,y,z> = AffineSpace(QQ,3)
sage: C = Curve([x-y,z-2])
sage: C
Affine Curve over Rational Field defined by x - y, z - 2
sage: P.<x,y,z> = ProjectiveSpace(QQ,2)
sage: C = Curve(x-y)
sage: C
Projective Plane Curve over Rational Field defined by x - y
"""
if self.defining_ideal().is_zero() and self.ambient_space().dimension() == 1:
return "{} Line over {}".format(self._repr_type(), self.base_ring())
return "{} Curve over {} defined by {}".format(self._repr_type(),
self.base_ring(),
', '.join(str(x) for x in self.defining_polynomials()))
def _repr_type(self):
r"""
Return a string representation of the type of this curve.
EXAMPLES::
sage: P.<x,y,z,w> = ProjectiveSpace(QQ, 3)
sage: C = Curve([w^3 - z^3, w*x - x^2])
sage: from sage.schemes.curves.curve import Curve_generic
sage: Curve_generic._repr_type(C)
'Generic'
"""
return "Generic"
def _latex_(self):
r"""
Return a latex representation of this curve.
EXAMPLES::
sage: x,y,z = PolynomialRing(QQ, 3, names='x,y,z').gens()
sage: C = Curve(y^2*z - x^3 - 17*x*z^2 + y*z^2)
sage: latex(C)
\text{Projective Plane curve over $\Bold{Q}$
defined by $-x^{3} + y^{2} z - 17 x z^{2} + y z^{2}$}
sage: A2 = AffineSpace(2, QQ, names=['x','y'])
sage: x, y = A2.coordinate_ring().gens()
sage: C = Curve(y^2 - x^3 - 17*x + y)
sage: latex(C)
\text{Affine Plane curve over $\Bold{Q}$
defined by $-x^{3} + y^{2} - 17 x + y$}
"""
if (self.defining_ideal().is_zero()
and self.ambient_space().dimension() == 1):
ambient_type, ring = self._repr_type(), latex(self.base_ring())
return fr"\text{{{ambient_type} line over ${ring}$}}"
else:
ambient_type, ring = self._repr_type(), latex(self.base_ring())
polys = ', '.join(f'${latex(p)}$' for p in self.defining_polynomials())
return fr"\text{{{ambient_type} curve over ${ring}$ defined by {polys}}}"
def dimension(self):
r"""
Return the dimension of the curve.
Curves have dimension one by definition.
EXAMPLES::
sage: x = polygen(QQ)
sage: C = HyperellipticCurve(x^7 + x^4 + x)
sage: C.dimension()
1
sage: from sage.schemes.projective.projective_subscheme import AlgebraicScheme_subscheme_projective
sage: AlgebraicScheme_subscheme_projective.dimension(C)
1
"""
return Integer(1)
def defining_polynomial(self):
"""
Return the defining polynomial of the curve.
EXAMPLES::
sage: x,y,z = PolynomialRing(QQ, 3, names='x,y,z').gens()
sage: C = Curve(y^2*z - x^3 - 17*x*z^2 + y*z^2)
sage: C.defining_polynomial()
-x^3 + y^2*z - 17*x*z^2 + y*z^2
"""
return self.defining_polynomials()[0]
def divisor_group(self, base_ring=None):
r"""
Return the divisor group of the curve.
INPUT:
- ``base_ring`` -- the base ring of the divisor group. Usually, this is
`\ZZ` (default) or `\QQ`.
OUTPUT: the divisor group of the curve
EXAMPLES::
sage: x,y,z = PolynomialRing(QQ, 3, names='x,y,z').gens()
sage: C = Curve(y^2*z - x^3 - 17*x*z^2 + y*z^2)
sage: Cp = Curve(y^2*z - x^3 - 17*x*z^2 + y*z^2)
sage: C.divisor_group() is Cp.divisor_group()
True
"""
return DivisorGroup(self, base_ring)
def divisor(self, v, base_ring=None, check=True, reduce=True):
r"""
Return the divisor specified by ``v``.
.. WARNING::
The coefficients of the divisor must be in the base ring
and the terms must be reduced. If you set ``check=False``
and/or ``reduce=False`` it is your responsibility to pass
a valid object ``v``.
EXAMPLES::
sage: x,y,z = PolynomialRing(QQ, 3, names='x,y,z').gens()
sage: C = Curve(y^2*z - x^3 - 17*x*z^2 + y*z^2)
"""
return Divisor_curve(v, check=check, reduce=reduce, parent=self.divisor_group(base_ring))
def genus(self):
"""
Return the geometric genus of the curve.
EXAMPLES::
sage: x,y,z = PolynomialRing(QQ, 3, names='x,y,z').gens()
sage: C = Curve(y^2*z - x^3 - 17*x*z^2 + y*z^2)
sage: C.genus()
1
"""
return self.geometric_genus()
def geometric_genus(self):
r"""
Return the geometric genus of the curve.
This is by definition the genus of the normalization of the projective
closure of the curve over the algebraic closure of the base field; the
base field must be a prime field.
.. NOTE::
This calls Singular's genus command.
EXAMPLES:
Examples of projective curves. ::
sage: P2 = ProjectiveSpace(2, GF(5), names=['x','y','z'])
sage: x, y, z = P2.coordinate_ring().gens()
sage: C = Curve(y^2*z - x^3 - 17*x*z^2 + y*z^2)
sage: C.geometric_genus()
1
sage: C = Curve(y^2*z - x^3)
sage: C.geometric_genus()
0
sage: C = Curve(x^10 + y^7*z^3 + z^10)
sage: C.geometric_genus()
3
Examples of affine curves. ::
sage: x, y = PolynomialRing(GF(5), 2, 'xy').gens()
sage: C = Curve(y^2 - x^3 - 17*x + y)
sage: C.geometric_genus()
1
sage: C = Curve(y^2 - x^3)
sage: C.geometric_genus()
0
sage: C = Curve(x^10 + y^7 + 1)
sage: C.geometric_genus()
3
"""
try:
return self._genus
except AttributeError:
self._genus = self.defining_ideal().genus()
return self._genus
def union(self, other):
"""
Return the union of ``self`` and ``other``.
EXAMPLES::
sage: x,y,z = PolynomialRing(QQ, 3, names='x,y,z').gens()
sage: C1 = Curve(z - x)
sage: C2 = Curve(y - x)
sage: C1.union(C2).defining_polynomial()
x^2 - x*y - x*z + y*z
"""
from .constructor import Curve
return Curve(AlgebraicScheme_subscheme.union(self, other))
__add__ = union
def singular_subscheme(self):
r"""
Return the subscheme of singular points of this curve.
OUTPUT:
- a subscheme in the ambient space of this curve.
EXAMPLES::
sage: A.<x,y> = AffineSpace(CC, 2)
sage: C = Curve([y^4 - 2*x^5 - x^2*y], A)
sage: C.singular_subscheme()
Closed subscheme of Affine Space of dimension 2 over Complex Field
with 53 bits of precision defined by:
(-2.00000000000000)*x^5 + y^4 - x^2*y,
(-10.0000000000000)*x^4 + (-2.00000000000000)*x*y,
4.00000000000000*y^3 - x^2
::
sage: P.<x,y,z,w> = ProjectiveSpace(QQ, 3)
sage: C = Curve([y^8 - x^2*z*w^5, w^2 - 2*y^2 - x*z], P)
sage: C.singular_subscheme()
Closed subscheme of Projective Space of dimension 3 over Rational
Field defined by:
y^8 - x^2*z*w^5,
-2*y^2 - x*z + w^2,
-x^3*y*z^4 + 3*x^2*y*z^3*w^2 - 3*x*y*z^2*w^4 + 8*x*y*z*w^5 + y*z*w^6,
x^2*z*w^5,
-5*x^2*z^2*w^4 - 4*x*z*w^6,
x^4*y*z^3 - 3*x^3*y*z^2*w^2 + 3*x^2*y*z*w^4 - 4*x^2*y*w^5 - x*y*w^6,
-2*x^3*y*z^3*w + 6*x^2*y*z^2*w^3 - 20*x^2*y*z*w^4 - 6*x*y*z*w^5 +
2*y*w^7,
-5*x^3*z*w^4 - 2*x^2*w^6
"""
return self.ambient_space().subscheme(self.Jacobian())
def singular_points(self, F=None):
r"""
Return the set of singular points of this curve.
INPUT:
- ``F`` -- (default: None) field over which to find the singular
points; if not given, the base ring of this curve is used
OUTPUT: a list of points in the ambient space of this curve
EXAMPLES::
sage: A.<x,y,z> = AffineSpace(QQ, 3)
sage: C = Curve([y^2 - x^5, x - z], A)
sage: C.singular_points()
[(0, 0, 0)]
::
sage: R.<a> = QQ[]
sage: K.<b> = NumberField(a^8 - a^4 + 1)
sage: P.<x,y,z> = ProjectiveSpace(QQ, 2)
sage: C = Curve([359/12*x*y^2*z^2 + 2*y*z^4 + 187/12*y^3*z^2 + x*z^4\
+ 67/3*x^2*y*z^2 + 117/4*y^5 + 9*x^5 + 6*x^3*z^2 + 393/4*x*y^4\
+ 145*x^2*y^3 + 115*x^3*y^2 + 49*x^4*y], P)
sage: sorted(C.singular_points(K), key=str)
[(-1/2*b^5 - 1/2*b^3 + 1/2*b - 1 : 1 : 0),
(-2/3*b^4 + 1/3 : 0 : 1),
(-b^6 : b^6 : 1),
(1/2*b^5 + 1/2*b^3 - 1/2*b - 1 : 1 : 0),
(2/3*b^4 - 1/3 : 0 : 1),
(b^6 : -b^6 : 1)]
"""
if F is None:
if not self.base_ring() in Fields():
raise TypeError("curve must be defined over a field")
F = self.base_ring()
elif F not in Fields():
raise TypeError("(=%s) must be a field" % F)
X = self.singular_subscheme()
return [self.point(p, check=False) for p in X.rational_points(F=F)]
def is_singular(self, P=None):
r"""
Return whether ``P`` is a singular point of this curve, or if no point
is passed, whether this curve is singular or not.
This just uses the is_smooth function for algebraic subschemes.
INPUT:
- ``P`` -- (default: None) a point on this curve
OUTPUT:
A boolean. If a point ``P`` is provided, and if ``P`` lies on this
curve, returns True if ``P`` is a singular point of this curve, and
False otherwise. If no point is provided, returns True or False
depending on whether this curve is or is not singular, respectively.
EXAMPLES::
sage: P.<x,y,z,w> = ProjectiveSpace(QQ, 3)
sage: C = P.curve([y^2 - x^2 - z^2, z - w])
sage: C.is_singular()
False
::
sage: A.<x,y,z> = AffineSpace(GF(11), 3)
sage: C = A.curve([y^3 - z^5, x^5 - y + 1])
sage: Q = A([7,0,0])
sage: C.is_singular(Q)
True
"""
return not self.is_smooth(P)
def intersects_at(self, C, P):
r"""
Return whether the point ``P`` is or is not in the intersection of this
curve with the curve ``C``.
INPUT:
- ``C`` -- a curve in the same ambient space as this curve.
- ``P`` -- a point in the ambient space of this curve.
EXAMPLES::
sage: P.<x,y,z,w> = ProjectiveSpace(QQ, 3)
sage: C = Curve([x^2 - z^2, y^3 - w*x^2], P)
sage: D = Curve([w^2 - 2*x*y + z^2, y^2 - w^2], P)
sage: Q1 = P([1,1,-1,1])
sage: C.intersects_at(D, Q1)
True
sage: Q2 = P([0,0,1,-1])
sage: C.intersects_at(D, Q2)
False
::
sage: A.<x,y> = AffineSpace(GF(13), 2)
sage: C = Curve([y + 12*x^5 + 3*x^3 + 7], A)
sage: D = Curve([y^2 + 7*x^2 + 8], A)
sage: Q1 = A([9,6])
sage: C.intersects_at(D, Q1)
True
sage: Q2 = A([3,7])
sage: C.intersects_at(D, Q2)
False
"""
if C.ambient_space() != self.ambient_space():
raise TypeError("(=%s) must be a curve in the same ambient space as (=%s)"%(C,self))
if not isinstance(C, Curve_generic):
raise TypeError("(=%s) must be a curve"%C)
try:
P = self.ambient_space()(P)
except TypeError:
raise TypeError("(=%s) must be a point in the ambient space of this curve"%P)
try:
P = self(P)
P = C(P)
except TypeError:
return False
return True
def intersection_points(self, C, F=None):
r"""
Return the points in the intersection of this curve and the curve ``C``.
If the intersection of these two curves has dimension greater than
zero, and if the base ring of this curve is not a finite field, then an
error is returned.
INPUT:
- ``C`` -- a curve in the same ambient space as this curve
- ``F`` -- (default: None); field over which to compute the
intersection points; if not specified, the base ring of this curve is
used
OUTPUT: a list of points in the ambient space of this curve
EXAMPLES::
sage: R.<a> = QQ[]
sage: K.<b> = NumberField(a^2 + a + 1)
sage: P.<x,y,z,w> = ProjectiveSpace(QQ, 3)
sage: C = Curve([y^2 - w*z, w^3 - y^3], P)
sage: D = Curve([x*y - w*z, z^3 - y^3], P)
sage: C.intersection_points(D, F=K)
[(-b - 1 : -b - 1 : b : 1), (b : b : -b - 1 : 1), (1 : 0 : 0 : 0),
(1 : 1 : 1 : 1)]
::
sage: A.<x,y> = AffineSpace(GF(7), 2)
sage: C = Curve([y^3 - x^3], A)
sage: D = Curve([-x*y^3 + y^4 - 2*x^3 + 2*x^2*y], A)
sage: C.intersection_points(D)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 3), (5, 5), (5, 6),
(6, 6)]
::
sage: A.<x,y> = AffineSpace(QQ, 2)
sage: C = Curve([y^3 - x^3], A)
sage: D = Curve([-x*y^3 + y^4 - 2*x^3 + 2*x^2*y], A)
sage: C.intersection_points(D)
Traceback (most recent call last):
...
NotImplementedError: the intersection must have dimension zero or
(=Rational Field) must be a finite field
"""
if C.ambient_space() != self.ambient_space():
raise TypeError("(=%s) must be a curve in the same ambient space as (=%s)"%(C,self))
if not isinstance(C, Curve_generic):
raise TypeError("(=%s) must be a curve"%C)
X = self.intersection(C)
if F is None:
F = self.base_ring()
if X.dimension() == 0 or F in FiniteFields():
return X.rational_points(F=F)
else:
raise NotImplementedError("the intersection must have dimension "
"zero or (={}) must be a finite field".format(F))
def change_ring(self, R):
r"""
Return a new curve which is this curve coerced to ``R``.
INPUT:
- ``R`` -- ring or embedding
OUTPUT: a new curve which is this curve coerced to ``R``
EXAMPLES::
sage: P.<x,y,z,w> = ProjectiveSpace(QQ, 3)
sage: C = Curve([x^2 - y^2, z*y - 4/5*w^2], P)
sage: C.change_ring(QuadraticField(-1))
Projective Curve over Number Field in a with defining polynomial x^2 + 1 with a = 1*I defined by x^2 - y^2, y*z - 4/5*w^2
::
sage: R.<a> = QQ[]
sage: K.<b> = NumberField(a^3 + a^2 - 1)
sage: A.<x,y> = AffineSpace(K, 2)
sage: C = Curve([K.0*x^2 - x + y^3 - 11], A)
sage: L = K.embeddings(QQbar)
sage: set_verbose(-1) # suppress warnings for slow computation
sage: C.change_ring(L[0])
Affine Plane Curve over Algebraic Field defined by y^3 +
(-0.8774388331233464? - 0.744861766619745?*I)*x^2 - x - 11
::
sage: P.<x,y,z> = ProjectiveSpace(QQ, 2)
sage: C = P.curve([y*x - 18*x^2 + 17*z^2])
sage: C.change_ring(GF(17))
Projective Plane Curve over Finite Field of size 17 defined by -x^2 + x*y
"""
new_AS = self.ambient_space().change_ring(R)
I = [f.change_ring(R) for f in self.defining_polynomials()]
return new_AS.curve(I) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/curves/curve.py | 0.946631 | 0.603961 | curve.py | pypi |
from sage.structure.richcmp import richcmp
from sage.schemes.generic.point import SchemeTopologicalPoint_prime_ideal
class CurveClosedPoint(SchemeTopologicalPoint_prime_ideal):
"""
Base class of closed points of curves.
"""
pass
class IntegralCurveClosedPoint(CurveClosedPoint):
"""
Closed points of integral curves.
INPUT:
- ``curve`` -- the curve to which the closed point belongs
- ``prime_ideal`` -- a prime ideal
- ``degree`` -- degree of the closed point
EXAMPLES::
sage: F.<a> = GF(4)
sage: P.<x,y> = AffineSpace(F, 2);
sage: C = Curve(y^2 + y - x^3)
sage: C.closed_points()
[Point (x, y),
Point (x, y + 1),
Point (x + a, y + a),
Point (x + a, y + (a + 1)),
Point (x + (a + 1), y + a),
Point (x + (a + 1), y + (a + 1)),
Point (x + 1, y + a),
Point (x + 1, y + (a + 1))]
"""
def __init__(self, curve, prime_ideal, degree):
"""
Initialize.
TESTS::
sage: F.<a> = GF(4)
sage: P.<x,y> = AffineSpace(F, 2);
sage: C = Curve(y^2 + y - x^3)
sage: p = C([0,0]); p
(0, 0)
sage: loads(dumps(p)) == p
True
"""
super().__init__(curve.ambient_space(), prime_ideal)
self._curve = curve
self._degree = degree
def __hash__(self):
"""
Return the hash of ``self``.
EXAMPLES::
sage: F.<a> = GF(4)
sage: P.<x,y> = AffineSpace(F, 2);
sage: C = Curve(y^2 + y - x^3)
sage: pts = C.closed_points()
sage: p = pts[0]
sage: {p: 1}
{Point (x, y): 1}
"""
return hash((self.parent(),self.prime_ideal()))
def _richcmp_(self, other, op):
"""
Compare ``self`` and ``other`` with respect to the operator.
INPUT:
- ``other`` -- a closed point
- ``op`` -- a comparison operator
EXAMPLES::
sage: F.<a> = GF(4)
sage: P.<x,y> = AffineSpace(F, 2);
sage: C = Curve(y^2 + y - x^3)
sage: pts = C.closed_points()
sage: pts[0] == pts[1]
False
"""
return richcmp((self._curve, self.prime_ideal()), (other._curve, other.prime_ideal()), op)
def _repr_(self):
"""
Return the string representation of the closed point.
EXAMPLES::
sage: F.<a> = GF(4)
sage: P.<x,y> = AffineSpace(F, 2);
sage: C = Curve(y^2 + y - x^3)
sage: pts = C.closed_points()
sage: pts[0]
Point (x, y)
"""
return "Point ({})".format(', '.join(repr(g) for g in self.prime_ideal().gens()))
def curve(self):
"""
Return the curve to which this point belongs.
EXAMPLES::
sage: F.<a> = GF(4)
sage: P.<x,y> = AffineSpace(F, 2);
sage: C = Curve(y^2 + y - x^3)
sage: pts = C.closed_points()
sage: p = pts[0]
sage: p.curve()
Affine Plane Curve over Finite Field in a of size 2^2 defined by x^3 + y^2 + y
"""
return self._curve
def degree(self):
"""
Return the degree of the point.
EXAMPLES::
sage: F.<a> = GF(4)
sage: P.<x,y> = AffineSpace(F, 2);
sage: C = Curve(y^2 + y - x^3)
sage: pts = C.closed_points()
sage: p = pts[0]
sage: p.degree()
1
"""
return self._degree
def places(self):
"""
Return all places on this closed point.
EXAMPLES::
sage: F.<a> = GF(4)
sage: P.<x,y> = AffineSpace(F, 2);
sage: C = Curve(y^2 + y - x^3)
sage: pts = C.closed_points()
sage: p = pts[0]
sage: p.places()
[Place (x, y)]
"""
return self._curve.places_on(self)
def place(self):
"""
Return a place on this closed point.
If there are more than one, arbitrary one is chosen.
EXAMPLES::
sage: F.<a> = GF(4)
sage: P.<x,y> = AffineSpace(F, 2);
sage: C = Curve(y^2 + y - x^3)
sage: pts = C.closed_points()
sage: p = pts[0]
sage: p.place()
Place (x, y)
"""
return self._curve.places_on(self)[0]
class IntegralAffineCurveClosedPoint(IntegralCurveClosedPoint):
"""
Closed points of affine curves.
"""
def rational_point(self):
"""
Return the rational point if this closed point is of degree `1`.
EXAMPLES::
sage: A.<x,y> = AffineSpace(GF(3^2),2)
sage: C = Curve(y^2 - x^5 - x^4 - 2*x^3 - 2*x-2)
sage: C.closed_points()
[Point (x, y + (z2 + 1)),
Point (x, y + (-z2 - 1)),
Point (x + (z2 + 1), y + (z2 - 1)),
Point (x + (z2 + 1), y + (-z2 + 1)),
Point (x - 1, y + (z2 + 1)),
Point (x - 1, y + (-z2 - 1)),
Point (x + (-z2 - 1), y + z2),
Point (x + (-z2 - 1), y + (-z2)),
Point (x + 1, y + 1),
Point (x + 1, y - 1)]
sage: [p.rational_point() for p in _]
[(0, 2*z2 + 2),
(0, z2 + 1),
(2*z2 + 2, 2*z2 + 1),
(2*z2 + 2, z2 + 2),
(1, 2*z2 + 2),
(1, z2 + 1),
(z2 + 1, 2*z2),
(z2 + 1, z2),
(2, 2),
(2, 1)]
sage: set(_) == set(C.rational_points())
True
"""
if self.degree() != 1:
raise ValueError("not a rational point")
G = self.prime_ideal().groebner_basis()
C = self._curve
return C([g.reduce(G) for g in C.ambient_space().gens()])
def projective(self, i=0):
"""
Return the point in the projective closure of the curve, of which this
curve is the ``i``-th affine patch.
INPUT:
- ``i`` -- an integer
EXAMPLES::
sage: F.<a> = GF(2)
sage: A.<x,y> = AffineSpace(F, 2)
sage: C = Curve(y^2 + y - x^3, A)
sage: p1, p2 = C.closed_points()
sage: p1
Point (x, y)
sage: p2
Point (x, y + 1)
sage: p1.projective()
Point (x1, x2)
sage: p2.projective(0)
Point (x1, x0 + x2)
sage: p2.projective(1)
Point (x0, x1 + x2)
sage: p2.projective(2)
Point (x0, x1 + x2)
"""
C = self.curve()
A = C.ambient_space()
ideal = self.prime_ideal()
phi = A.projective_embedding(i)
gs = list(phi.codomain().gens())
xi = gs.pop(i)
# gens of ideal is a groebner basis in degrevlex order
S = phi.codomain().coordinate_ring()
prime = S.ideal(ideal.subs(dict(zip(A.gens(), gs))).homogenize(xi))
Cp = C.projective_closure(i)
return Cp._closed_point(Cp, prime, self.degree())
class IntegralProjectiveCurveClosedPoint(IntegralCurveClosedPoint):
"""
Closed points of projective plane curves.
"""
def rational_point(self):
"""
Return the rational point if this closed point is of degree `1`.
EXAMPLES::
sage: F.<a> = GF(4)
sage: P.<x,y,z> = ProjectiveSpace(F, 2)
sage: C = Curve(x^3*y + y^3*z + x*z^3)
sage: C.closed_points()
[Point (x, z),
Point (x, y),
Point (y, z),
Point (x + a*z, y + (a + 1)*z),
Point (x + (a + 1)*z, y + a*z)]
sage: [p.rational_point() for p in _]
[(0 : 1 : 0), (0 : 0 : 1), (1 : 0 : 0), (a : a + 1 : 1), (a + 1 : a : 1)]
sage: set(_) == set(C.rational_points())
True
"""
if self.degree() != 1:
raise ValueError("not a rational point")
C = self.curve()
A = C.ambient_space().coordinate_ring()
prime_ideal = self.prime_ideal()
for i in range(A.ngens()):
G = (prime_ideal + A.ideal([A.gen(i) - 1])).groebner_basis()
if 1 not in G:
break
return C([A.gen(j).reduce(G) for j in range(A.ngens())])
def affine(self, i=None):
"""
Return the point in the ``i``-th affine patch of the curve.
INPUT:
- ``i`` -- an integer; if not specified, it is chosen automatically.
EXAMPLES::
sage: F.<a> = GF(2)
sage: P.<x,y,z> = ProjectiveSpace(F, 2)
sage: C = Curve(x^3*y + y^3*z + x*z^3)
sage: p1, p2, p3 = C.closed_points()
sage: p1.affine()
Point (x, z)
sage: p2.affine()
Point (x, y)
sage: p3.affine()
Point (y, z)
sage: p3.affine(0)
Point (y, z)
sage: p3.affine(1)
Traceback (most recent call last):
...
ValueError: not in the affine patch
"""
C = self.curve()
P = C.ambient_space()
ideal = self.prime_ideal()
if i is None:
for j in range(P.ngens()):
if not P.gen(j) in ideal:
i = j
break
else:
if P.gen(i) in ideal:
raise ValueError("not in the affine patch")
A = P.affine_patch(i)
phi = A.projective_embedding(i, P)
prime = A.coordinate_ring().ideal(ideal.subs(dict(zip(P.gens(), phi.defining_polynomials()))))
Ca = C.affine_patch(i)
return Ca._closed_point(Ca, prime, self.degree()) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/curves/closed_point.py | 0.939775 | 0.736851 | closed_point.py | pypi |
from sage.categories.fields import Fields
from sage.rings.polynomial.multi_polynomial_element import is_MPolynomial
from sage.rings.polynomial.multi_polynomial_ring import is_MPolynomialRing
from sage.rings.finite_rings.finite_field_constructor import is_FiniteField
from sage.rings.rational_field import QQ
from sage.structure.all import Sequence
from sage.schemes.affine.affine_space import is_AffineSpace
from sage.schemes.generic.ambient_space import is_AmbientSpace
from sage.schemes.generic.algebraic_scheme import is_AlgebraicScheme
from sage.schemes.projective.projective_space import is_ProjectiveSpace
from sage.schemes.affine.all import AffineSpace
from sage.schemes.projective.all import ProjectiveSpace
from .projective_curve import (ProjectiveCurve,
ProjectivePlaneCurve,
ProjectiveCurve_field,
ProjectivePlaneCurve_field,
ProjectivePlaneCurve_finite_field,
IntegralProjectiveCurve,
IntegralProjectiveCurve_finite_field,
IntegralProjectivePlaneCurve,
IntegralProjectivePlaneCurve_finite_field)
from .affine_curve import (AffineCurve,
AffinePlaneCurve,
AffineCurve_field,
AffinePlaneCurve_field,
AffinePlaneCurve_finite_field,
IntegralAffineCurve,
IntegralAffineCurve_finite_field,
IntegralAffinePlaneCurve,
IntegralAffinePlaneCurve_finite_field)
from sage.schemes.plane_conics.constructor import Conic
def _is_irreducible_and_reduced(F):
"""
Check if the polynomial F is irreducible and reduced.
TESTS::
sage: R.<x,y> = QQ[]
sage: F = x^2 + y^2
sage: from sage.schemes.curves.constructor import _is_irreducible_and_reduced
sage: _is_irreducible_and_reduced(F)
True
"""
factors = F.factor()
return len(factors) == 1 and factors[0][1] == 1
def Curve(F, A=None):
"""
Return the plane or space curve defined by ``F``, where ``F`` can be either
a multivariate polynomial, a list or tuple of polynomials, or an algebraic
scheme.
If no ambient space is passed in for ``A``, and if ``F`` is not an
algebraic scheme, a new ambient space is constructed.
Also not specifying an ambient space will cause the curve to be defined in
either affine or projective space based on properties of ``F``. In
particular, if ``F`` contains a nonhomogeneous polynomial, the curve is
affine, and if ``F`` consists of homogeneous polynomials, then the curve is
projective.
INPUT:
- ``F`` -- a multivariate polynomial, or a list or tuple of polynomials, or an algebraic scheme.
- ``A`` -- (default: None) an ambient space in which to create the curve.
EXAMPLES: A projective plane curve. ::
sage: x,y,z = QQ['x,y,z'].gens()
sage: C = Curve(x^3 + y^3 + z^3); C
Projective Plane Curve over Rational Field defined by x^3 + y^3 + z^3
sage: C.genus()
1
Affine plane curves. ::
sage: x,y = GF(7)['x,y'].gens()
sage: C = Curve(y^2 + x^3 + x^10); C
Affine Plane Curve over Finite Field of size 7 defined by x^10 + x^3 + y^2
sage: C.genus()
0
sage: x, y = QQ['x,y'].gens()
sage: Curve(x^3 + y^3 + 1)
Affine Plane Curve over Rational Field defined by x^3 + y^3 + 1
A projective space curve. ::
sage: x,y,z,w = QQ['x,y,z,w'].gens()
sage: C = Curve([x^3 + y^3 - z^3 - w^3, x^5 - y*z^4]); C
Projective Curve over Rational Field defined by x^3 + y^3 - z^3 - w^3, x^5 - y*z^4
sage: C.genus()
13
An affine space curve. ::
sage: x,y,z = QQ['x,y,z'].gens()
sage: C = Curve([y^2 + x^3 + x^10 + z^7, x^2 + y^2]); C
Affine Curve over Rational Field defined by x^10 + z^7 + x^3 + y^2, x^2 + y^2
sage: C.genus()
47
We can also make non-reduced non-irreducible curves. ::
sage: x,y,z = QQ['x,y,z'].gens()
sage: Curve((x-y)*(x+y))
Projective Conic Curve over Rational Field defined by x^2 - y^2
sage: Curve((x-y)^2*(x+y)^2)
Projective Plane Curve over Rational Field defined by x^4 - 2*x^2*y^2 + y^4
A union of curves is a curve. ::
sage: x,y,z = QQ['x,y,z'].gens()
sage: C = Curve(x^3 + y^3 + z^3)
sage: D = Curve(x^4 + y^4 + z^4)
sage: C.union(D)
Projective Plane Curve over Rational Field defined by
x^7 + x^4*y^3 + x^3*y^4 + y^7 + x^4*z^3 + y^4*z^3 + x^3*z^4 + y^3*z^4 + z^7
The intersection is not a curve, though it is a scheme. ::
sage: X = C.intersection(D); X
Closed subscheme of Projective Space of dimension 2 over Rational Field defined by:
x^3 + y^3 + z^3,
x^4 + y^4 + z^4
Note that the intersection has dimension 0. ::
sage: X.dimension()
0
sage: I = X.defining_ideal(); I
Ideal (x^3 + y^3 + z^3, x^4 + y^4 + z^4) of Multivariate Polynomial Ring in x, y, z over Rational Field
If only a polynomial in three variables is given, then it must be
homogeneous such that a projective curve is constructed. ::
sage: x,y,z = QQ['x,y,z'].gens()
sage: Curve(x^2+y^2)
Projective Conic Curve over Rational Field defined by x^2 + y^2
sage: Curve(x^2+y^2+z)
Traceback (most recent call last):
...
TypeError: x^2 + y^2 + z is not a homogeneous polynomial
An ambient space can be specified to construct a space curve in an affine
or a projective space. ::
sage: A.<x,y,z> = AffineSpace(QQ, 3)
sage: C = Curve([y - x^2, z - x^3], A)
sage: C
Affine Curve over Rational Field defined by -x^2 + y, -x^3 + z
sage: A == C.ambient_space()
True
The defining polynomial must be nonzero unless the ambient space itself is
of dimension 1. ::
sage: P1.<x,y> = ProjectiveSpace(1,GF(5))
sage: S = P1.coordinate_ring()
sage: Curve(S(0), P1)
Projective Line over Finite Field of size 5
sage: Curve(P1)
Projective Line over Finite Field of size 5
::
sage: A1.<x> = AffineSpace(1, QQ)
sage: R = A1.coordinate_ring()
sage: Curve(R(0), A1)
Affine Line over Rational Field
sage: Curve(A1)
Affine Line over Rational Field
"""
if A is None:
if is_AmbientSpace(F) and F.dimension() == 1:
return Curve(F.coordinate_ring().zero(), F)
if is_AlgebraicScheme(F):
return Curve(F.defining_polynomials(), F.ambient_space())
if isinstance(F, (list, tuple)):
P = Sequence(F).universe()
if not is_MPolynomialRing(P):
raise TypeError("universe of F must be a multivariate polynomial ring")
for f in F:
if not f.is_homogeneous():
A = AffineSpace(P.ngens(), P.base_ring(), names=P.variable_names())
A._coordinate_ring = P
break
else:
A = ProjectiveSpace(P.ngens()-1, P.base_ring(), names=P.variable_names())
A._coordinate_ring = P
elif is_MPolynomial(F): # define a plane curve
P = F.parent()
k = F.base_ring()
if not k.is_field():
if k.is_integral_domain(): # upgrade to a field
P = P.change_ring(k.fraction_field())
F = P(F)
k = F.base_ring()
else:
raise TypeError("not a multivariate polynomial over a field or an integral domain")
if F.parent().ngens() == 2:
if F == 0:
raise ValueError("defining polynomial of curve must be nonzero")
A = AffineSpace(2, P.base_ring(), names=P.variable_names())
A._coordinate_ring = P
elif F.parent().ngens() == 3:
if F == 0:
raise ValueError("defining polynomial of curve must be nonzero")
# special case: construct a conic curve
if F.total_degree() == 2 and k.is_field():
return Conic(k, F)
A = ProjectiveSpace(2, P.base_ring(), names=P.variable_names())
A._coordinate_ring = P
elif F.parent().ngens() == 1:
if not F.is_zero():
raise ValueError("defining polynomial of curve must be zero "
"if the ambient space is of dimension 1")
A = AffineSpace(1, P.base_ring(), names=P.variable_names())
A._coordinate_ring = P
else:
raise TypeError("number of variables of F (={}) must be 2 or 3".format(F))
F = [F]
else:
raise TypeError("F (={}) must be a multivariate polynomial".format(F))
else:
if not is_AmbientSpace(A):
raise TypeError("ambient space must be either an affine or projective space")
if not isinstance(F, (list, tuple)):
F = [F]
if not all(f.parent() == A.coordinate_ring() for f in F):
raise TypeError("need a list of polynomials of the coordinate ring of {}".format(A))
n = A.dimension_relative()
if n < 1:
raise TypeError("ambient space should be an affine or projective space of positive dimension")
k = A.base_ring()
if is_AffineSpace(A):
if n != 2:
if is_FiniteField(k):
if A.coordinate_ring().ideal(F).is_prime():
return IntegralAffineCurve_finite_field(A, F)
if k in Fields():
if k == QQ and A.coordinate_ring().ideal(F).is_prime():
return IntegralAffineCurve(A, F)
return AffineCurve_field(A, F)
return AffineCurve(A, F)
if not (len(F) == 1 and F[0] != 0 and F[0].degree() > 0):
raise TypeError("need a single nonconstant polynomial to define a plane curve")
F = F[0]
if is_FiniteField(k):
if _is_irreducible_and_reduced(F):
return IntegralAffinePlaneCurve_finite_field(A, F)
return AffinePlaneCurve_finite_field(A, F)
if k in Fields():
if k == QQ and _is_irreducible_and_reduced(F):
return IntegralAffinePlaneCurve(A, F)
return AffinePlaneCurve_field(A, F)
return AffinePlaneCurve(A, F)
elif is_ProjectiveSpace(A):
if n != 2:
if not all(f.is_homogeneous() for f in F):
raise TypeError("polynomials defining a curve in a projective space must be homogeneous")
if is_FiniteField(k):
if A.coordinate_ring().ideal(F).is_prime():
return IntegralProjectiveCurve_finite_field(A, F)
if k in Fields():
if k == QQ and A.coordinate_ring().ideal(F).is_prime():
return IntegralProjectiveCurve(A, F)
return ProjectiveCurve_field(A, F)
return ProjectiveCurve(A, F)
# There is no dimension check when initializing a plane curve, so check
# here that F consists of a single nonconstant polynomial.
if not (len(F) == 1 and F[0] != 0 and F[0].degree() > 0):
raise TypeError("need a single nonconstant polynomial to define a plane curve")
F = F[0]
if not F.is_homogeneous():
raise TypeError("{} is not a homogeneous polynomial".format(F))
if is_FiniteField(k):
if _is_irreducible_and_reduced(F):
return IntegralProjectivePlaneCurve_finite_field(A, F)
return ProjectivePlaneCurve_finite_field(A, F)
if k in Fields():
if k == QQ and _is_irreducible_and_reduced(F):
return IntegralProjectivePlaneCurve(A, F)
return ProjectivePlaneCurve_field(A, F)
return ProjectivePlaneCurve(A, F)
else:
raise TypeError('ambient space neither affine nor projective') | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/curves/constructor.py | 0.921838 | 0.532425 | constructor.py | pypi |
from sage.schemes.affine.affine_point import (SchemeMorphism_point_affine_field,
SchemeMorphism_point_affine_finite_field)
from sage.schemes.projective.projective_point import (SchemeMorphism_point_projective_field,
SchemeMorphism_point_projective_finite_field)
class ProjectiveCurvePoint_field(SchemeMorphism_point_projective_field):
"""
Point of a projective curve over a field.
"""
def is_singular(self):
r"""
Return whether this point is a singular point of the projective curve it is on.
EXAMPLES::
sage: P.<x,y,z,w> = ProjectiveSpace(QQ, 3)
sage: C = Curve([x^2 - y^2, z - w], P)
sage: Q1 = C([0,0,1,1])
sage: Q1.is_singular()
True
sage: Q2 = C([1,1,1,1])
sage: Q2.is_singular()
False
"""
return self.codomain().is_singular(self)
class ProjectivePlaneCurvePoint_field(ProjectiveCurvePoint_field):
"""
Point of a projective plane curve over a field.
"""
def multiplicity(self):
r"""
Return the multiplicity of this point with respect to the projective
curve it is on.
EXAMPLES::
sage: P.<x,y,z> = ProjectiveSpace(GF(17), 2)
sage: C = Curve([y^3*z - 16*x^4], P)
sage: Q = C([0,0,1])
sage: Q.multiplicity()
3
"""
return self.codomain().multiplicity(self)
def tangents(self):
r"""
Return the tangents at this point of the projective plane curve this point is on.
OUTPUT:
A list of polynomials in the coordinate ring of the ambient space
of the curve this point is on.
EXAMPLES::
sage: P.<x,y,z> = ProjectiveSpace(QQ, 2)
sage: C = Curve([y^2*z^3 - x^5 + 18*y*x*z^3])
sage: Q = C([0,0,1])
sage: Q.tangents()
[y, 18*x + y]
"""
return self.codomain().tangents(self)
def is_ordinary_singularity(self):
r"""
Return whether this point is an ordinary singularity of the projective
plane curve it is on.
EXAMPLES::
sage: P.<x,y,z> = ProjectiveSpace(QQ, 2)
sage: C = Curve([z^6 - x^6 - x^3*z^3 - x^3*y^3])
sage: Q = C([0,1,0])
sage: Q.is_ordinary_singularity()
False
::
sage: R.<a> = QQ[]
sage: K.<b> = NumberField(a^2 - 3)
sage: P.<x,y,z> = ProjectiveSpace(K, 2)
sage: C = P.curve([x^2*y^3*z^4 - y^6*z^3 - 4*x^2*y^4*z^3 -
....: 4*x^4*y^2*z^3 + 3*y^7*z^2 + 10*x^2*y^5*z^2 + 9*x^4*y^3*z^2 +
....: 5*x^6*y*z^2 - 3*y^8*z - 9*x^2*y^6*z - 11*x^4*y^4*z - 7*x^6*y^2*z -
....: 2*x^8*z + y^9 + 2*x^2*y^7 + 3*x^4*y^5 + 4*x^6*y^3 + 2*x^8*y])
sage: Q = C([-1/2, 1/2, 1])
sage: Q.is_ordinary_singularity()
True
"""
return self.codomain().is_ordinary_singularity(self)
def is_transverse(self, D):
r"""
Return whether the intersection of the curve ``D`` at this point with
the curve this point is on is transverse or not.
INPUT:
- ``D`` -- a curve in the same ambient space as the curve this point is on
EXAMPLES::
sage: P.<x,y,z> = ProjectiveSpace(QQ, 2)
sage: C = Curve([x^2 - 2*y^2 - 2*z^2], P)
sage: D = Curve([y - z], P)
sage: Q = C([2,1,1])
sage: Q.is_transverse(D)
True
::
sage: P.<x,y,z> = ProjectiveSpace(GF(17), 2)
sage: C = Curve([x^4 - 16*y^3*z], P)
sage: D = Curve([y^2 - z*x], P)
sage: Q = C([0,0,1])
sage: Q.is_transverse(D)
False
"""
return self.codomain().is_transverse(D, self)
class ProjectivePlaneCurvePoint_finite_field(ProjectivePlaneCurvePoint_field,
SchemeMorphism_point_projective_finite_field):
"""
Point of a projective plane curve over a finite field.
"""
pass
class IntegralProjectiveCurvePoint(ProjectiveCurvePoint_field):
def closed_point(self):
"""
Return the closed point corresponding to this rational point.
EXAMPLES::
sage: P.<x,y,z> = ProjectiveSpace(GF(17), 2)
sage: C = Curve([x^4 - 16*y^3*z], P)
sage: C.singular_points()
[(0 : 0 : 1)]
sage: p = _[0]
sage: p.closed_point()
Point (x, y)
"""
curve = self.codomain()
A = curve.ambient_space()
S = A.coordinate_ring()
hcoords = self._coords
for i in range(S.ngens()):
if hcoords[i]:
break
ai = hcoords[i]
xi = S.gen(i)
hgens = [ai*S.gen(j) - hcoords[j]*xi for j in range(S.ngens()) if j != i]
return curve._closed_point(curve, S.ideal(hgens), degree=1)
def places(self):
"""
Return all places on this point.
EXAMPLES::
sage: P.<x,y,z> = ProjectiveSpace(GF(17), 2)
sage: C = Curve([x^4 - 16*y^3*z], P)
sage: C.singular_points()
[(0 : 0 : 1)]
sage: p = _[0]
sage: p.places()
[Place (y)]
"""
return self.closed_point().places()
def place(self):
"""
Return a place on this point.
EXAMPLES::
sage: P.<x,y,z> = ProjectiveSpace(GF(17), 2)
sage: C = Curve([x^4 - 16*y^3*z], P)
sage: C.singular_points()
[(0 : 0 : 1)]
sage: p = _[0]
sage: p.place()
Place (y)
"""
return self.closed_point().place()
class IntegralProjectiveCurvePoint_finite_field(IntegralProjectiveCurvePoint):
"""
Point of an integral projective curve over a finite field.
"""
pass
class IntegralProjectivePlaneCurvePoint(IntegralProjectiveCurvePoint, ProjectivePlaneCurvePoint_field):
"""
Point of an integral projective plane curve over a field.
"""
pass
class IntegralProjectivePlaneCurvePoint_finite_field(ProjectivePlaneCurvePoint_finite_field, IntegralProjectiveCurvePoint_finite_field):
"""
Point of an integral projective plane curve over a finite field.
"""
pass
class AffineCurvePoint_field(SchemeMorphism_point_affine_field):
def is_singular(self):
r"""
Return whether this point is a singular point of the affine curve it is on.
EXAMPLES::
sage: K = QuadraticField(-1)
sage: A.<x,y,z> = AffineSpace(K, 3)
sage: C = Curve([(x^4 + 2*z + 2)*y, z - y + 1])
sage: Q1 = C([0,0,-1])
sage: Q1.is_singular()
True
sage: Q2 = C([-K.gen(),0,-1])
sage: Q2.is_singular()
False
"""
return self.codomain().is_singular(self)
class AffinePlaneCurvePoint_field(AffineCurvePoint_field):
"""
Point of an affine plane curve over a field.
"""
def multiplicity(self):
r"""
Return the multiplicity of this point with respect to the affine curve it is on.
EXAMPLES::
sage: A.<x,y> = AffineSpace(QQ, 2)
sage: C = A.curve([2*x^7 - 3*x^6*y + x^5*y^2 + 31*x^6 - 40*x^5*y +
....: 13*x^4*y^2 - x^3*y^3 + 207*x^5 - 228*x^4*y + 70*x^3*y^2 - 7*x^2*y^3
....: + 775*x^4 - 713*x^3*y + 193*x^2*y^2 - 19*x*y^3 + y^4 + 1764*x^3 -
....: 1293*x^2*y + 277*x*y^2 - 22*y^3 + 2451*x^2 - 1297*x*y + 172*y^2 +
....: 1935*x - 570*y + 675])
sage: Q = C([-2,1])
sage: Q.multiplicity()
4
"""
return self.codomain().multiplicity(self)
def tangents(self):
r"""
Return the tangents at this point of the affine plane curve this point is on.
OUTPUT: a list of polynomials in the coordinate ring of the ambient
space of the curve this point is on.
EXAMPLES::
sage: A.<x,y> = AffineSpace(QQ, 2)
sage: C = A.curve([x^5 - x^3*y^2 + 5*x^4 - x^3*y - 3*x^2*y^2 +
....: x*y^3 + 10*x^3 - 3*x^2*y - 3*x*y^2 + y^3 + 10*x^2 - 3*x*y - y^2 +
....: 5*x - y + 1])
sage: Q = C([-1,0])
sage: Q.tangents()
[y, x + 1, x - y + 1, x + y + 1]
"""
return self.codomain().tangents(self)
def is_ordinary_singularity(self):
r"""
Return whether this point is an ordinary singularity of the affine
plane curve it is on.
EXAMPLES::
sage: A.<x,y> = AffineSpace(QQ, 2)
sage: C = A.curve([x^5 - x^3*y^2 + 5*x^4 - x^3*y - 3*x^2*y^2 +
....: x*y^3 + 10*x^3 - 3*x^2*y - 3*x*y^2 + y^3 + 10*x^2 - 3*x*y - y^2 +
....: 5*x - y + 1])
sage: Q = C([-1,0])
sage: Q.is_ordinary_singularity()
True
::
sage: A.<x,y> = AffineSpace(GF(7), 2)
sage: C = A.curve([y^2 - x^7 - 6*x^3])
sage: Q = C([0,0])
sage: Q.is_ordinary_singularity()
False
"""
return self.codomain().is_ordinary_singularity(self)
def is_transverse(self, D):
r"""
Return whether the intersection of the curve ``D`` at this point with
the curve this point is on is transverse or not.
INPUT:
- ``D`` -- a curve in the same ambient space as the curve this point is on.
EXAMPLES::
sage: A.<x,y> = AffineSpace(QQ, 2)
sage: C = Curve([y - x^2], A)
sage: D = Curve([y], A)
sage: Q = C([0,0])
sage: Q.is_transverse(D)
False
::
sage: R.<a> = QQ[]
sage: K.<b> = NumberField(a^2 - 2)
sage: A.<x,y> = AffineSpace(K, 2)
sage: C = Curve([y^2 + x^2 - 1], A)
sage: D = Curve([y - x], A)
sage: Q = C([-1/2*b,-1/2*b])
sage: Q.is_transverse(D)
True
"""
return self.codomain().is_transverse(D, self)
class AffinePlaneCurvePoint_finite_field(AffinePlaneCurvePoint_field, SchemeMorphism_point_affine_finite_field):
"""
Point of an affine plane curve over a finite field.
"""
pass
class IntegralAffineCurvePoint(AffineCurvePoint_field):
"""
Point of an integral affine curve.
"""
def closed_point(self):
"""
Return the closed point that corresponds to this rational point.
EXAMPLES::
sage: A.<x,y> = AffineSpace(GF(8), 2)
sage: C = Curve(x^5 + y^5 + x*y + 1)
sage: p = C([1,1])
sage: p.closed_point()
Point (x + 1, y + 1)
"""
curve = self.codomain()
A = curve.ambient_space()
R = A.coordinate_ring()
coords = self._coords
gens = [R.gen(i) - coords[i] for i in range(R.ngens())]
return curve._closed_point(curve, R.ideal(gens), degree=1)
def places(self):
"""
Return all places on this point.
EXAMPLES::
sage: A.<x,y> = AffineSpace(GF(2), 2)
sage: C = Curve(x^5 + y^5 + x*y + 1)
sage: p = C(-1,-1)
sage: p
(1, 1)
sage: p.closed_point()
Point (x + 1, y + 1)
sage: _.places()
[Place (x + 1, (1/(x^5 + 1))*y^4 + ((x^5 + x^4 + 1)/(x^5 + 1))*y^3
+ ((x^5 + x^3 + 1)/(x^5 + 1))*y^2 + (x^2/(x^5 + 1))*y), Place (x +
1, (1/(x^5 + 1))*y^4 + ((x^5 + x^4 + 1)/(x^5 + 1))*y^3 + (x^3/(x^5
+ 1))*y^2 + (x^2/(x^5 + 1))*y + x + 1)]
"""
return self.closed_point().places()
def place(self):
"""
Return a place on this point.
EXAMPLES::
sage: A.<x,y> = AffineSpace(GF(2), 2)
sage: C = Curve(x^5 + y^5 + x*y + 1)
sage: p = C(-1,-1)
sage: p
(1, 1)
sage: p.closed_point()
Point (x + 1, y + 1)
sage: _.place()
Place (x + 1, (1/(x^5 + 1))*y^4 + ((x^5 + x^4 + 1)/(x^5 + 1))*y^3 +
((x^5 + x^3 + 1)/(x^5 + 1))*y^2 + (x^2/(x^5 + 1))*y)
"""
return self.closed_point().place()
class IntegralAffineCurvePoint_finite_field(IntegralAffineCurvePoint):
"""
Point of an integral affine curve over a finite field.
"""
pass
class IntegralAffinePlaneCurvePoint(IntegralAffineCurvePoint, AffinePlaneCurvePoint_field):
"""
Point of an integral affine plane curve over a finite field.
"""
pass
class IntegralAffinePlaneCurvePoint_finite_field(AffinePlaneCurvePoint_finite_field, IntegralAffineCurvePoint_finite_field):
"""
Point of an integral affine plane curve over a finite field.
"""
pass | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/curves/point.py | 0.922159 | 0.581927 | point.py | pypi |
from sage.rings.polynomial.all import PolynomialRing
from sage.rings.big_oh import O
from sage.rings.power_series_ring import PowerSeriesRing
from sage.rings.laurent_series_ring import LaurentSeriesRing
from sage.rings.real_mpfr import RR
from sage.functions.all import log
from sage.structure.category_object import normalize_names
import sage.schemes.curves.projective_curve as plane_curve
def is_HyperellipticCurve(C):
"""
EXAMPLES::
sage: R.<x> = QQ[]; C = HyperellipticCurve(x^3 + x - 1); C
Hyperelliptic Curve over Rational Field defined by y^2 = x^3 + x - 1
sage: sage.schemes.hyperelliptic_curves.hyperelliptic_generic.is_HyperellipticCurve(C)
True
"""
return isinstance(C,HyperellipticCurve_generic)
class HyperellipticCurve_generic(plane_curve.ProjectivePlaneCurve):
"""
TESTS::
sage: P.<x> = QQ[]
sage: f0 = 4*x^5 - 30*x^3 + 45*x - 22
sage: C0 = HyperellipticCurve(f0)
sage: f1 = x^5 - x^3 + x - 22
sage: C1 = HyperellipticCurve(f1)
sage: C0 == C1
False
sage: C0 == C0
True
sage: P.<x> = QQ[]
sage: f0 = 4*x^5 - 30*x^3 + 45*x - 22
sage: C0 = HyperellipticCurve(f0)
sage: f1 = x^5 - x^3 + x - 22
sage: C1 = HyperellipticCurve(f1)
sage: C0 != C1
True
sage: C0 != C0
False
sage: P.<x> = QQ[]
sage: f0 = 4*x^5 - 30*x^3 + 45*x - 22
sage: C0 = HyperellipticCurve(f0)
sage: f1 = x^5 - x^3 + x - 22
sage: C1 = HyperellipticCurve(f1)
sage: Q.<y> = GF(5)[]
sage: f2 = y^5 - y^3 + y - 22
sage: C2 = HyperellipticCurve(f2)
sage: hash(C0) == hash(C0)
True
sage: hash(C0) == hash(C1)
False
sage: hash(C1) == hash(C2)
False
"""
def __init__(self, PP, f, h=None, names=None, genus=None):
x, y, z = PP.gens()
df = f.degree()
F1 = sum([ f[i]*x**i*z**(df-i) for i in range(df+1) ])
if h is None:
F = y**2*z**(df-2) - F1
else:
dh = h.degree()
deg = max(df,dh+1)
F0 = sum([ h[i]*x**i*z**(dh-i) for i in range(dh+1) ])
F = y**2*z**(deg-2) + F0*y*z**(deg-dh-1) - F1*z**(deg-df)
plane_curve.ProjectivePlaneCurve.__init__(self,PP,F)
R = PP.base_ring()
if names is None:
names = ("x", "y")
else:
names = normalize_names(2, names)
self._names = names
P1 = PolynomialRing(R, name=names[0])
P2 = PolynomialRing(P1, name=names[1])
self._PP = PP
self._printing_ring = P2
self._hyperelliptic_polynomials = (f,h)
self._genus = genus
def change_ring(self, R):
"""
Returns this HyperellipticCurve over a new base ring R.
EXAMPLES::
sage: R.<x> = QQ[]
sage: H = HyperellipticCurve(x^5 - 10*x + 9)
sage: K = Qp(3,5)
sage: L.<a> = K.extension(x^30-3)
sage: HK = H.change_ring(K)
sage: HL = HK.change_ring(L); HL
Hyperelliptic Curve over 3-adic Eisenstein Extension Field in a defined by x^30 - 3 defined by (1 + O(a^150))*y^2 = (1 + O(a^150))*x^5 + (2 + 2*a^30 + a^60 + 2*a^90 + 2*a^120 + O(a^150))*x + a^60 + O(a^210)
sage: R.<x> = FiniteField(7)[]
sage: H = HyperellipticCurve(x^8 + x + 5)
sage: H.base_extend(FiniteField(7^2, 'a'))
Hyperelliptic Curve over Finite Field in a of size 7^2 defined by y^2 = x^8 + x + 5
"""
from .constructor import HyperellipticCurve
f, h = self._hyperelliptic_polynomials
y = self._printing_ring.variable_name()
x = self._printing_ring.base_ring().variable_name()
return HyperellipticCurve(f.change_ring(R), h.change_ring(R), "%s,%s"%(x,y))
base_extend = change_ring
def _repr_(self):
"""
String representation of hyperelliptic curves.
EXAMPLES::
sage: P.<x> = QQ[]
sage: f = 4*x^5 - 30*x^3 + 45*x - 22
sage: C = HyperellipticCurve(f); C
Hyperelliptic Curve over Rational Field defined by y^2 = 4*x^5 - 30*x^3 + 45*x - 22
sage: C = HyperellipticCurve(f,names='u,v'); C
Hyperelliptic Curve over Rational Field defined by v^2 = 4*u^5 - 30*u^3 + 45*u - 22
"""
f, h = self._hyperelliptic_polynomials
R = self.base_ring()
y = self._printing_ring.gen()
x = self._printing_ring.base_ring().gen()
if h == 0:
return "Hyperelliptic Curve over %s defined by %s = %s" % (R, y**2, f(x))
else:
return "Hyperelliptic Curve over %s defined by %s + %s = %s" % (R, y**2, h(x)*y, f(x))
def hyperelliptic_polynomials(self, K=None, var='x'):
"""
EXAMPLES::
sage: R.<x> = QQ[]; C = HyperellipticCurve(x^3 + x - 1, x^3/5); C
Hyperelliptic Curve over Rational Field defined by y^2 + 1/5*x^3*y = x^3 + x - 1
sage: C.hyperelliptic_polynomials()
(x^3 + x - 1, 1/5*x^3)
"""
if K is None:
return self._hyperelliptic_polynomials
else:
f, h = self._hyperelliptic_polynomials
P = PolynomialRing(K, var)
return (P(f), P(h))
def is_singular(self):
r"""
Returns False, because hyperelliptic curves are smooth projective
curves, as checked on construction.
EXAMPLES::
sage: R.<x> = QQ[]
sage: H = HyperellipticCurve(x^5+1)
sage: H.is_singular()
False
A hyperelliptic curve with genus at least 2 always has a singularity at
infinity when viewed as a *plane* projective curve. This can be seen in
the following example.::
sage: R.<x> = QQ[]
sage: H = HyperellipticCurve(x^5+2)
sage: from sage.misc.verbose import set_verbose
sage: set_verbose(-1)
sage: H.is_singular()
False
sage: from sage.schemes.curves.projective_curve import ProjectivePlaneCurve
sage: ProjectivePlaneCurve.is_singular(H)
True
"""
return False
def is_smooth(self):
r"""
Returns True, because hyperelliptic curves are smooth projective
curves, as checked on construction.
EXAMPLES::
sage: R.<x> = GF(13)[]
sage: H = HyperellipticCurve(x^8+1)
sage: H.is_smooth()
True
A hyperelliptic curve with genus at least 2 always has a singularity at
infinity when viewed as a *plane* projective curve. This can be seen in
the following example.::
sage: R.<x> = GF(27, 'a')[]
sage: H = HyperellipticCurve(x^10+2)
sage: from sage.misc.verbose import set_verbose
sage: set_verbose(-1)
sage: H.is_smooth()
True
sage: from sage.schemes.curves.projective_curve import ProjectivePlaneCurve
sage: ProjectivePlaneCurve.is_smooth(H)
False
"""
return True
def lift_x(self, x, all=False):
f, h = self._hyperelliptic_polynomials
x += self.base_ring()(0)
one = x.parent()(1)
if h.is_zero():
y2 = f(x)
if y2.is_square():
if all:
return [self.point([x, y, one], check=False) for y in y2.sqrt(all=True)]
else:
return self.point([x, y2.sqrt(), one], check=False)
else:
b = h(x)
D = b*b + 4*f(x)
if D.is_square():
if all:
return [self.point([x, (-b+d)/2, one], check=False) for d in D.sqrt(all=True)]
else:
return self.point([x, (-b+D.sqrt())/2, one], check=False)
if all:
return []
else:
raise ValueError("No point with x-coordinate %s on %s"%(x, self))
def genus(self):
return self._genus
def jacobian(self):
from . import jacobian_generic
return jacobian_generic.HyperellipticJacobian_generic(self)
def odd_degree_model(self):
r"""
Return an odd degree model of self, or raise ValueError if one does not exist over the field of definition.
EXAMPLES::
sage: x = QQ['x'].gen()
sage: H = HyperellipticCurve((x^2 + 2)*(x^2 + 3)*(x^2 + 5)); H
Hyperelliptic Curve over Rational Field defined by y^2 = x^6 + 10*x^4 + 31*x^2 + 30
sage: H.odd_degree_model()
Traceback (most recent call last):
...
ValueError: No odd degree model exists over field of definition
sage: K2 = QuadraticField(-2, 'a')
sage: Hp2 = H.change_ring(K2).odd_degree_model(); Hp2
Hyperelliptic Curve over Number Field in a with defining polynomial x^2 + 2 with a = 1.414213562373095?*I defined by y^2 = 6*a*x^5 - 29*x^4 - 20*x^2 + 6*a*x + 1
sage: K3 = QuadraticField(-3, 'b')
sage: Hp3 = H.change_ring(QuadraticField(-3, 'b')).odd_degree_model(); Hp3
Hyperelliptic Curve over Number Field in b with defining polynomial x^2 + 3 with b = 1.732050807568878?*I defined by y^2 = -4*b*x^5 - 14*x^4 - 20*b*x^3 - 35*x^2 + 6*b*x + 1
Of course, Hp2 and Hp3 are isomorphic over the composite
extension. One consequence of this is that odd degree models
reduced over "different" fields should have the same number of
points on their reductions. 43 and 67 split completely in the
compositum, so when we reduce we find:
sage: P2 = K2.factor(43)[0][0]
sage: P3 = K3.factor(43)[0][0]
sage: Hp2.change_ring(K2.residue_field(P2)).frobenius_polynomial()
x^4 - 16*x^3 + 134*x^2 - 688*x + 1849
sage: Hp3.change_ring(K3.residue_field(P3)).frobenius_polynomial()
x^4 - 16*x^3 + 134*x^2 - 688*x + 1849
sage: H.change_ring(GF(43)).odd_degree_model().frobenius_polynomial()
x^4 - 16*x^3 + 134*x^2 - 688*x + 1849
sage: P2 = K2.factor(67)[0][0]
sage: P3 = K3.factor(67)[0][0]
sage: Hp2.change_ring(K2.residue_field(P2)).frobenius_polynomial()
x^4 - 8*x^3 + 150*x^2 - 536*x + 4489
sage: Hp3.change_ring(K3.residue_field(P3)).frobenius_polynomial()
x^4 - 8*x^3 + 150*x^2 - 536*x + 4489
sage: H.change_ring(GF(67)).odd_degree_model().frobenius_polynomial()
x^4 - 8*x^3 + 150*x^2 - 536*x + 4489
TESTS::
sage: HyperellipticCurve(x^5 + 1, 1).odd_degree_model()
Traceback (most recent call last):
...
NotImplementedError: odd_degree_model only implemented for curves in Weierstrass form
sage: HyperellipticCurve(x^5 + 1, names="U, V").odd_degree_model()
Hyperelliptic Curve over Rational Field defined by V^2 = U^5 + 1
"""
f, h = self._hyperelliptic_polynomials
if h:
raise NotImplementedError("odd_degree_model only implemented for curves in Weierstrass form")
if f.degree() % 2:
# already odd, so just yield self
return self
rts = f.roots(multiplicities=False)
if not rts:
raise ValueError("No odd degree model exists over field of definition")
rt = rts[0]
x = f.parent().gen()
fnew = f((x*rt + 1)/x).numerator() # move rt to "infinity"
from .constructor import HyperellipticCurve
return HyperellipticCurve(fnew, 0, names=self._names, PP=self._PP)
def has_odd_degree_model(self):
r"""
Return True if an odd degree model of self exists over the field of definition; False otherwise.
Use ``odd_degree_model`` to calculate an odd degree model.
EXAMPLES::
sage: x = QQ['x'].0
sage: HyperellipticCurve(x^5 + x).has_odd_degree_model()
True
sage: HyperellipticCurve(x^6 + x).has_odd_degree_model()
True
sage: HyperellipticCurve(x^6 + x + 1).has_odd_degree_model()
False
"""
try:
return bool(self.odd_degree_model())
except ValueError:
return False
def _magma_init_(self, magma):
"""
Internal function. Returns a string to initialize this elliptic
curve in the Magma subsystem.
EXAMPLES::
sage: R.<x> = QQ[]; C = HyperellipticCurve(x^3 + x - 1, x); C
Hyperelliptic Curve over Rational Field defined by y^2 + x*y = x^3 + x - 1
sage: magma(C) # optional - magma
Hyperelliptic Curve defined by y^2 + x*y = x^3 + x - 1 over Rational Field
sage: R.<x> = GF(9,'a')[]; C = HyperellipticCurve(x^3 + x - 1, x^10); C
Hyperelliptic Curve over Finite Field in a of size 3^2 defined by y^2 + x^10*y = x^3 + x + 2
sage: D = magma(C); D # optional - magma
Hyperelliptic Curve defined by y^2 + (x^10)*y = x^3 + x + 2 over GF(3^2)
sage: D.sage() # optional - magma
Hyperelliptic Curve over Finite Field in a of size 3^2 defined by y^2 + x^10*y = x^3 + x + 2
"""
f, h = self._hyperelliptic_polynomials
return 'HyperellipticCurve(%s, %s)'%(f._magma_init_(magma), h._magma_init_(magma))
def monsky_washnitzer_gens(self):
import sage.schemes.hyperelliptic_curves.monsky_washnitzer as monsky_washnitzer
S = monsky_washnitzer.SpecialHyperellipticQuotientRing(self)
return S.gens()
def invariant_differential(self):
"""
Returns `dx/2y`, as an element of the Monsky-Washnitzer cohomology
of self
EXAMPLES::
sage: R.<x> = QQ['x']
sage: C = HyperellipticCurve(x^5 - 4*x + 4)
sage: C.invariant_differential()
1 dx/2y
"""
import sage.schemes.hyperelliptic_curves.monsky_washnitzer as m_w
S = m_w.SpecialHyperellipticQuotientRing(self)
MW = m_w.MonskyWashnitzerDifferentialRing(S)
return MW.invariant_differential()
def local_coordinates_at_nonweierstrass(self, P, prec=20, name='t'):
"""
For a non-Weierstrass point `P = (a,b)` on the hyperelliptic
curve `y^2 = f(x)`, return `(x(t), y(t))` such that `(y(t))^2 = f(x(t))`,
where `t = x - a` is the local parameter.
INPUT:
- ``P = (a, b)`` -- a non-Weierstrass point on self
- ``prec`` -- desired precision of the local coordinates
- ``name`` -- gen of the power series ring (default: ``t``)
OUTPUT:
`(x(t),y(t))` such that `y(t)^2 = f(x(t))` and `t = x - a`
is the local parameter at `P`
EXAMPLES::
sage: R.<x> = QQ['x']
sage: H = HyperellipticCurve(x^5-23*x^3+18*x^2+40*x)
sage: P = H(1,6)
sage: x,y = H.local_coordinates_at_nonweierstrass(P,prec=5)
sage: x
1 + t + O(t^5)
sage: y
6 + t - 7/2*t^2 - 1/2*t^3 - 25/48*t^4 + O(t^5)
sage: Q = H(-2,12)
sage: x,y = H.local_coordinates_at_nonweierstrass(Q,prec=5)
sage: x
-2 + t + O(t^5)
sage: y
12 - 19/2*t - 19/32*t^2 + 61/256*t^3 - 5965/24576*t^4 + O(t^5)
AUTHOR:
- Jennifer Balakrishnan (2007-12)
"""
d = P[1]
if d == 0:
raise TypeError("P = %s is a Weierstrass point. Use local_coordinates_at_weierstrass instead!"%P)
pol = self.hyperelliptic_polynomials()[0]
L = PowerSeriesRing(self.base_ring(), name, default_prec=prec)
t = L.gen()
K = PowerSeriesRing(L, 'x')
pol = K(pol)
b = P[0]
f = pol(t+b)
for i in range((RR(log(prec)/log(2))).ceil()):
d = (d + f/d)/2
return t+b+O(t**(prec)), d + O(t**(prec))
def local_coordinates_at_weierstrass(self, P, prec=20, name='t'):
"""
For a finite Weierstrass point on the hyperelliptic
curve `y^2 = f(x)`, returns `(x(t), y(t))` such that
`(y(t))^2 = f(x(t))`, where `t = y` is the local parameter.
INPUT:
- ``P`` -- a finite Weierstrass point on self
- ``prec`` -- desired precision of the local coordinates
- ``name`` -- gen of the power series ring (default: `t`)
OUTPUT:
`(x(t),y(t))` such that `y(t)^2 = f(x(t))` and `t = y`
is the local parameter at `P`
EXAMPLES::
sage: R.<x> = QQ['x']
sage: H = HyperellipticCurve(x^5-23*x^3+18*x^2+40*x)
sage: A = H(4, 0)
sage: x, y = H.local_coordinates_at_weierstrass(A, prec=7)
sage: x
4 + 1/360*t^2 - 191/23328000*t^4 + 7579/188956800000*t^6 + O(t^7)
sage: y
t + O(t^7)
sage: B = H(-5, 0)
sage: x, y = H.local_coordinates_at_weierstrass(B, prec=5)
sage: x
-5 + 1/1260*t^2 + 887/2000376000*t^4 + O(t^5)
sage: y
t + O(t^5)
AUTHOR:
- Jennifer Balakrishnan (2007-12)
- Francis Clarke (2012-08-26)
"""
if P[1] != 0:
raise TypeError("P = %s is not a finite Weierstrass point. Use local_coordinates_at_nonweierstrass instead!"%P)
L = PowerSeriesRing(self.base_ring(), name)
t = L.gen()
pol = self.hyperelliptic_polynomials()[0]
pol_prime = pol.derivative()
b = P[0]
t2 = t**2
c = b + t2/pol_prime(b)
c = c.add_bigoh(prec)
for _ in range(int(1 + log(prec, 2))):
c -= (pol(c) - t2)/pol_prime(c)
return (c, t.add_bigoh(prec))
def local_coordinates_at_infinity(self, prec=20, name='t'):
"""
For the genus `g` hyperelliptic curve `y^2 = f(x)`, return
`(x(t), y(t))` such that `(y(t))^2 = f(x(t))`, where `t = x^g/y` is
the local parameter at infinity
INPUT:
- ``prec`` -- desired precision of the local coordinates
- ``name`` -- generator of the power series ring (default: ``t``)
OUTPUT:
`(x(t),y(t))` such that `y(t)^2 = f(x(t))` and `t = x^g/y`
is the local parameter at infinity
EXAMPLES::
sage: R.<x> = QQ['x']
sage: H = HyperellipticCurve(x^5-5*x^2+1)
sage: x,y = H.local_coordinates_at_infinity(10)
sage: x
t^-2 + 5*t^4 - t^8 - 50*t^10 + O(t^12)
sage: y
t^-5 + 10*t - 2*t^5 - 75*t^7 + 50*t^11 + O(t^12)
::
sage: R.<x> = QQ['x']
sage: H = HyperellipticCurve(x^3-x+1)
sage: x,y = H.local_coordinates_at_infinity(10)
sage: x
t^-2 + t^2 - t^4 - t^6 + 3*t^8 + O(t^12)
sage: y
t^-3 + t - t^3 - t^5 + 3*t^7 - 10*t^11 + O(t^12)
AUTHOR:
- Jennifer Balakrishnan (2007-12)
"""
g = self.genus()
pol = self.hyperelliptic_polynomials()[0]
K = LaurentSeriesRing(self.base_ring(), name, default_prec=prec+2)
t = K.gen()
L = PolynomialRing(K,'x')
x = L.gen()
i = 0
w = (x**g/t)**2-pol
wprime = w.derivative(x)
x = t**-2
for i in range((RR(log(prec+2)/log(2))).ceil()):
x = x - w(x)/wprime(x)
y = x**g/t
return x+O(t**(prec+2)) , y+O(t**(prec+2))
def local_coord(self, P, prec=20, name='t'):
"""
Calls the appropriate local_coordinates function
INPUT:
- ``P`` -- a point on self
- ``prec`` -- desired precision of the local coordinates
- ``name`` -- generator of the power series ring (default: ``t``)
OUTPUT:
`(x(t),y(t))` such that `y(t)^2 = f(x(t))`, where `t`
is the local parameter at `P`
EXAMPLES::
sage: R.<x> = QQ['x']
sage: H = HyperellipticCurve(x^5-23*x^3+18*x^2+40*x)
sage: H.local_coord(H(1 ,6), prec=5)
(1 + t + O(t^5), 6 + t - 7/2*t^2 - 1/2*t^3 - 25/48*t^4 + O(t^5))
sage: H.local_coord(H(4, 0), prec=7)
(4 + 1/360*t^2 - 191/23328000*t^4 + 7579/188956800000*t^6 + O(t^7), t + O(t^7))
sage: H.local_coord(H(0, 1, 0), prec=5)
(t^-2 + 23*t^2 - 18*t^4 - 569*t^6 + O(t^7), t^-5 + 46*t^-1 - 36*t - 609*t^3 + 1656*t^5 + O(t^6))
AUTHOR:
- Jennifer Balakrishnan (2007-12)
"""
if P[1] == 0:
return self.local_coordinates_at_weierstrass(P, prec, name)
elif P[2] == 0:
return self.local_coordinates_at_infinity(prec, name)
else:
return self.local_coordinates_at_nonweierstrass(P, prec, name)
def rational_points(self, **kwds):
r"""
Find rational points on the hyperelliptic curve, all arguments are passed
on to :meth:`sage.schemes.generic.algebraic_scheme.rational_points`.
EXAMPLES:
For the LMFDB genus 2 curve `932.a.3728.1 <https://www.lmfdb.org/Genus2Curve/Q/932/a/3728/1>`::
sage: R.<x> = PolynomialRing(QQ); C = HyperellipticCurve(R([0, -1, 1, 0, 1, -2, 1]), R([1]));
sage: C.rational_points(bound=8)
[(-1 : -3 : 1),
(-1 : 2 : 1),
(0 : -1 : 1),
(0 : 0 : 1),
(0 : 1 : 0),
(1/2 : -5/8 : 1),
(1/2 : -3/8 : 1),
(1 : -1 : 1),
(1 : 0 : 1)]
Check that :trac:`29509` is fixed for the LMFDB genus 2 curve
`169.a.169.1 <https://www.lmfdb.org/Genus2Curve/Q/169/a/169/1>`::
sage: C = HyperellipticCurve(R([0, 0, 0, 0, 1, 1]), R([1, 1, 0, 1]));
sage: C.rational_points(bound=10)
[(-1 : 0 : 1),
(-1 : 1 : 1),
(0 : -1 : 1),
(0 : 0 : 1),
(0 : 1 : 0)]
An example over a number field::
sage: R.<x> = PolynomialRing(QuadraticField(2));
sage: C = HyperellipticCurve(R([1, 0, 0, 0, 0, 1]));
sage: C.rational_points(bound=2)
[(-1 : 0 : 1),
(0 : -1 : 1),
(0 : 1 : 0),
(0 : 1 : 1),
(1 : -a : 1),
(1 : a : 1)]
"""
from sage.schemes.curves.constructor import Curve
# we change C to be a plane curve to allow the generic rational
# points code to reduce mod any prime, whereas a HyperellipticCurve
# can only be base changed to good primes.
C = self
if 'F' in kwds:
C = C.change_ring(kwds['F'])
return [C(pt) for pt in Curve(self).rational_points(**kwds)] | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/hyperelliptic_curves/hyperelliptic_generic.py | 0.813387 | 0.623176 | hyperelliptic_generic.py | pypi |
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.integer_ring import ZZ
from sage.rings.integer import is_Integer, Integer
from sage.rings.polynomial.polynomial_element import is_Polynomial
from sage.schemes.generic.homset import SchemeHomset_points
from sage.schemes.generic.morphism import is_SchemeMorphism
from .jacobian_morphism import JacobianMorphism_divisor_class_field
class JacobianHomset_divisor_classes(SchemeHomset_points):
def __init__(self, Y, X, **kwds):
R = X.base_ring()
S = Y.coordinate_ring()
SchemeHomset_points.__init__(self, Y, X, **kwds)
P2 = X.curve()._printing_ring
if S != R:
y = str(P2.gen())
x = str(P2.base_ring().gen())
P1 = PolynomialRing(S, name=x)
P2 = PolynomialRing(P1, name=y)
self._printing_ring = P2
def __call__(self, P):
r"""
Return a rational point P in the abstract Homset J(K), given:
0. A point P in J = Jac(C), returning P;
1. A point P on the curve C such that J = Jac(C), where C is
an odd degree model, returning [P - oo];
2. A pair of points (P, Q) on the curve C such that J = Jac(C),
returning [P-Q];
3. A list of polynomials (a,b) such that `b^2 + h*b - f = 0 mod a`,
returning [(a(x),y-b(x))].
EXAMPLES::
sage: P.<x> = PolynomialRing(QQ)
sage: f = x^5 - x + 1; h = x
sage: C = HyperellipticCurve(f,h,'u,v')
sage: P = C(0,1,1)
sage: J = C.jacobian()
sage: Q = J(QQ)(P)
sage: for i in range(6): i*Q
(1)
(u, v - 1)
(u^2, v + u - 1)
(u^2, v + 1)
(u, v + 1)
(1)
::
sage: F.<a> = GF(3)
sage: R.<x> = F[]
sage: f = x^5-1
sage: C = HyperellipticCurve(f)
sage: J = C.jacobian()
sage: X = J(F)
sage: a = x^2-x+1
sage: b = -x +1
sage: c = x-1
sage: d = 0
sage: D1 = X([a,b])
sage: D1
(x^2 + 2*x + 1, y + x + 2)
sage: D2 = X([c,d])
sage: D2
(x + 2, y)
sage: D1+D2
(x^2 + 2*x + 2, y + 2*x + 1)
"""
if isinstance(P, (Integer, int)) and P == 0:
R = PolynomialRing(self.value_ring(), 'x')
return JacobianMorphism_divisor_class_field(self,
(R.one(), R.zero()))
elif isinstance(P, (list, tuple)):
if len(P) == 1 and P[0] == 0:
R = PolynomialRing(self.value_ring(), 'x')
return JacobianMorphism_divisor_class_field(self,
(R.one(), R.zero()))
elif len(P) == 2:
P1 = P[0]
P2 = P[1]
if is_Integer(P1) and is_Integer(P2):
R = PolynomialRing(self.value_ring(), 'x')
P1 = R(P1)
P2 = R(P2)
return JacobianMorphism_divisor_class_field(self, (P1, P2))
if is_Integer(P1) and is_Polynomial(P2):
R = PolynomialRing(self.value_ring(), 'x')
P1 = R(P1)
return JacobianMorphism_divisor_class_field(self, (P1, P2))
if is_Integer(P2) and is_Polynomial(P1):
R = PolynomialRing(self.value_ring(), 'x')
P2 = R(P2)
return JacobianMorphism_divisor_class_field(self, (P1, P2))
if is_Polynomial(P1) and is_Polynomial(P2):
return JacobianMorphism_divisor_class_field(self, tuple(P))
if is_SchemeMorphism(P1) and is_SchemeMorphism(P2):
return self(P1) - self(P2)
raise TypeError("argument P (= %s) must have length 2" % P)
elif isinstance(P, JacobianMorphism_divisor_class_field) and self == P.parent():
return P
elif is_SchemeMorphism(P):
x0 = P[0]
y0 = P[1]
R, x = PolynomialRing(self.value_ring(), 'x').objgen()
return self((x - x0, R(y0)))
raise TypeError("argument P (= %s) does not determine a divisor class" % P)
def _morphism(self, *args, **kwds):
return JacobianMorphism_divisor_class_field(*args, **kwds)
def curve(self):
return self.codomain().curve()
def value_ring(self):
"""
Return S for a homset X(T) where T = Spec(S).
"""
from sage.schemes.generic.scheme import is_AffineScheme
T = self.domain()
if is_AffineScheme(T):
return T.coordinate_ring()
else:
raise TypeError("domain of argument must be of the form Spec(S)")
def base_extend(self, R):
if R != ZZ:
raise NotImplementedError("Jacobian point sets viewed as modules over rings other than ZZ not implemented")
return self | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/hyperelliptic_curves/jacobian_homset.py | 0.902074 | 0.606032 | jacobian_homset.py | pypi |
r"""
Compute invariants of quintics and sextics via 'Ueberschiebung'
.. TODO::
* Implement invariants in small positive characteristic.
* Cardona-Quer and additional invariants for classifying automorphism groups.
AUTHOR:
- Nick Alexander
"""
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
def diffxy(f, x, xtimes, y, ytimes):
r"""
Differentiate a polynomial ``f``, ``xtimes`` with respect to ``x``, and
```ytimes`` with respect to ``y``.
EXAMPLES::
sage: R.<u, v> = QQ[]
sage: sage.schemes.hyperelliptic_curves.invariants.diffxy(u^2*v^3, u, 0, v, 0)
u^2*v^3
sage: sage.schemes.hyperelliptic_curves.invariants.diffxy(u^2*v^3, u, 2, v, 1)
6*v^2
sage: sage.schemes.hyperelliptic_curves.invariants.diffxy(u^2*v^3, u, 2, v, 2)
12*v
sage: sage.schemes.hyperelliptic_curves.invariants.diffxy(u^2*v^3 + u^4*v^4, u, 2, v, 2)
144*u^2*v^2 + 12*v
"""
h = f
for i in range(xtimes):
h = h.derivative(x)
for j in range(ytimes):
h = h.derivative(y)
return h
def differential_operator(f, g, k):
r"""
Return the differential operator `(f g)_k` symbolically in the polynomial ring in ``dfdx, dfdy, dgdx, dgdy``.
This is defined by Mestre on p 315 [Mes1991]_:
.. MATH::
(f g)_k = \frac{(m - k)! (n - k)!}{m! n!} \left(
\frac{\partial f}{\partial x} \frac{\partial g}{\partial y} -
\frac{\partial f}{\partial y} \frac{\partial g}{\partial x} \right)^k .
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.invariants import differential_operator
sage: R.<x, y> = QQ[]
sage: differential_operator(x, y, 0)
1
sage: differential_operator(x, y, 1)
-dfdy*dgdx + dfdx*dgdy
sage: differential_operator(x*y, x*y, 2)
1/4*dfdy^2*dgdx^2 - 1/2*dfdx*dfdy*dgdx*dgdy + 1/4*dfdx^2*dgdy^2
sage: differential_operator(x^2*y, x*y^2, 2)
1/36*dfdy^2*dgdx^2 - 1/18*dfdx*dfdy*dgdx*dgdy + 1/36*dfdx^2*dgdy^2
sage: differential_operator(x^2*y, x*y^2, 4)
1/576*dfdy^4*dgdx^4 - 1/144*dfdx*dfdy^3*dgdx^3*dgdy + 1/96*dfdx^2*dfdy^2*dgdx^2*dgdy^2 - 1/144*dfdx^3*dfdy*dgdx*dgdy^3 + 1/576*dfdx^4*dgdy^4
"""
(x, y) = f.parent().gens()
n = max(ZZ(f.degree()), ZZ(k))
m = max(ZZ(g.degree()), ZZ(k))
R, (fx, fy, gx, gy) = PolynomialRing(f.base_ring(), 4, 'dfdx,dfdy,dgdx,dgdy').objgens()
const = (m - k).factorial() * (n - k).factorial() / (m.factorial() * n.factorial())
U = f.base_ring()(const) * (fx*gy - fy*gx)**k
return U
def diffsymb(U, f, g):
r"""
Given a differential operator ``U`` in ``dfdx, dfdy, dgdx, dgdy``,
represented symbolically by ``U``, apply it to ``f, g``.
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.invariants import diffsymb
sage: R.<x, y> = QQ[]
sage: S.<dfdx, dfdy, dgdx, dgdy> = QQ[]
sage: [ diffsymb(dd, x^2, y*0 + 1) for dd in S.gens() ]
[2*x, 0, 0, 0]
sage: [ diffsymb(dd, x*0 + 1, y^2) for dd in S.gens() ]
[0, 0, 0, 2*y]
sage: [ diffsymb(dd, x^2, y^2) for dd in S.gens() ]
[2*x*y^2, 0, 0, 2*x^2*y]
sage: diffsymb(dfdx + dfdy*dgdy, y*x^2, y^3)
2*x*y^4 + 3*x^2*y^2
"""
(x, y) = f.parent().gens()
R, (fx, fy, gx, gy) = PolynomialRing(f.base_ring(), 4, 'dfdx,dfdy,dgdx,dgdy').objgens()
res = 0
for coeff, mon in list(U):
mon = R(mon)
a = diffxy(f, x, mon.degree(fx), y, mon.degree(fy))
b = diffxy(g, x, mon.degree(gx), y, mon.degree(gy))
temp = coeff * a * b
res = res + temp
return res
def Ueberschiebung(f, g, k):
r"""
Return the differential operator `(f g)_k`.
This is defined by Mestre on page 315 [Mes1991]_:
.. MATH::
(f g)_k = \frac{(m - k)! (n - k)!}{m! n!} \left(
\frac{\partial f}{\partial x} \frac{\partial g}{\partial y} -
\frac{\partial f}{\partial y} \frac{\partial g}{\partial x} \right)^k .
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.invariants import Ueberschiebung as ub
sage: R.<x, y> = QQ[]
sage: ub(x, y, 0)
x*y
sage: ub(x^5 + 1, x^5 + 1, 1)
0
sage: ub(x^5 + 5*x + 1, x^5 + 5*x + 1, 0)
x^10 + 10*x^6 + 2*x^5 + 25*x^2 + 10*x + 1
"""
U = differential_operator(f, g, k)
# U is the (f g)_k = ... of Mestre, p315, symbolically
return diffsymb(U, f, g)
def ubs(f):
r"""
Given a sextic form `f`, return a dictionary of the invariants of Mestre, p 317 [Mes1991]_.
`f` may be homogeneous in two variables or inhomogeneous in one.
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.invariants import ubs
sage: x = QQ['x'].0
sage: ubs(x^6 + 1)
{'A': 2,
'B': 2/3,
'C': -2/9,
'D': 0,
'Delta': -2/3*x^2*h^2,
'f': x^6 + h^6,
'i': 2*x^2*h^2,
'y1': 0,
'y2': 0,
'y3': 0}
sage: R.<u, v> = QQ[]
sage: ubs(u^6 + v^6)
{'A': 2,
'B': 2/3,
'C': -2/9,
'D': 0,
'Delta': -2/3*u^2*v^2,
'f': u^6 + v^6,
'i': 2*u^2*v^2,
'y1': 0,
'y2': 0,
'y3': 0}
sage: R.<t> = GF(31)[]
sage: ubs(t^6 + 2*t^5 + t^2 + 3*t + 1)
{'A': 0,
'B': -12,
'C': -15,
'D': -15,
'Delta': -10*t^4 + 12*t^3*h + 7*t^2*h^2 - 5*t*h^3 + 2*h^4,
'f': t^6 + 2*t^5*h + t^2*h^4 + 3*t*h^5 + h^6,
'i': -4*t^4 + 10*t^3*h + 2*t^2*h^2 - 9*t*h^3 - 7*h^4,
'y1': 4*t^2 - 10*t*h - 13*h^2,
'y2': 6*t^2 - 4*t*h + 2*h^2,
'y3': 4*t^2 - 4*t*h - 9*h^2}
"""
ub = Ueberschiebung
if f.parent().ngens() == 1:
f = PolynomialRing(f.parent().base_ring(), 1, f.parent().variable_name())(f)
x1, x2 = f.homogenize().parent().gens()
f = sum([ f[i]*x1**i*x2**(6-i) for i in range(7) ])
U = {}
U['f'] = f
U['i'] = ub(f, f, 4)
U['Delta'] = ub(U['i'], U['i'], 2)
U['y1'] = ub(f, U['i'], 4)
U['y2'] = ub(U['i'], U['y1'], 2)
U['y3'] = ub(U['i'], U['y2'], 2)
U['A'] = ub(f, f, 6)
U['B'] = ub(U['i'], U['i'], 4)
U['C'] = ub(U['i'], U['Delta'], 4)
U['D'] = ub(U['y3'], U['y1'], 2)
return U
def clebsch_to_igusa(A, B, C, D):
r"""
Convert Clebsch invariants `A, B, C, D` to Igusa invariants `I_2, I_4, I_6, I_{10}`.
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.invariants import clebsch_to_igusa, igusa_to_clebsch
sage: clebsch_to_igusa(2, 3, 4, 5)
(-240, 17370, 231120, -103098906)
sage: igusa_to_clebsch(*clebsch_to_igusa(2, 3, 4, 5))
(2, 3, 4, 5)
sage: Cs = tuple(map(GF(31), (2, 3, 4, 5))); Cs
(2, 3, 4, 5)
sage: clebsch_to_igusa(*Cs)
(8, 10, 15, 26)
sage: igusa_to_clebsch(*clebsch_to_igusa(*Cs))
(2, 3, 4, 5)
"""
I2 = -120*A
I4 = -720*A**2 + 6750*B
I6 = 8640*A**3 - 108000*A*B + 202500*C
I10 = -62208*A**5 + 972000*A**3*B + 1620000*A**2*C - 3037500*A*B**2 - 6075000*B*C - 4556250*D
return (I2, I4, I6, I10)
def igusa_to_clebsch(I2, I4, I6, I10):
r"""
Convert Igusa invariants `I_2, I_4, I_6, I_{10}` to Clebsch invariants `A, B, C, D`.
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.invariants import clebsch_to_igusa, igusa_to_clebsch
sage: igusa_to_clebsch(-2400, 173700, 23112000, -10309890600)
(20, 342/5, 2512/5, 43381012/1125)
sage: clebsch_to_igusa(*igusa_to_clebsch(-2400, 173700, 23112000, -10309890600))
(-2400, 173700, 23112000, -10309890600)
sage: Is = tuple(map(GF(31), (-2400, 173700, 23112000, -10309890600))); Is
(18, 7, 12, 27)
sage: igusa_to_clebsch(*Is)
(20, 25, 25, 12)
sage: clebsch_to_igusa(*igusa_to_clebsch(*Is))
(18, 7, 12, 27)
"""
A = -(+ I2) / 120
B = -(- I2**2 - 20*I4)/135000
C = -(+ I2**3 + 80*I2*I4 - 600*I6)/121500000
D = -(+ 9*I2**5 + 700*I2**3*I4 - 3600*I2**2*I6 - 12400*I2*I4**2 + 48000*I4*I6 + 10800000*I10) / 49207500000000
return (A, B, C, D)
def clebsch_invariants(f):
r"""
Given a sextic form `f`, return the Clebsch invariants `(A, B, C, D)` of
Mestre, p 317, [Mes1991]_.
`f` may be homogeneous in two variables or inhomogeneous in one.
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.invariants import clebsch_invariants
sage: R.<x, y> = QQ[]
sage: clebsch_invariants(x^6 + y^6)
(2, 2/3, -2/9, 0)
sage: R.<x> = QQ[]
sage: clebsch_invariants(x^6 + x^5 + x^4 + x^2 + 2)
(62/15, 15434/5625, -236951/140625, 229930748/791015625)
sage: magma(x^6 + 1).ClebschInvariants() # optional - magma
[ 2, 2/3, -2/9, 0 ]
sage: magma(x^6 + x^5 + x^4 + x^2 + 2).ClebschInvariants() # optional - magma
[ 62/15, 15434/5625, -236951/140625, 229930748/791015625 ]
"""
R = f.parent().base_ring()
if R.characteristic() in [2, 3, 5]:
raise NotImplementedError("Invariants of binary sextics/genus 2 hyperelliptic "
"curves not implemented in characteristics 2, 3, and 5")
U = ubs(f)
L = U['A'], U['B'], U['C'], U['D']
assert all(t.is_constant() for t in L)
return tuple([ t.constant_coefficient() for t in L ])
def igusa_clebsch_invariants(f):
r"""
Given a sextic form `f`, return the Igusa-Clebsch invariants `I_2, I_4,
I_6, I_{10}` of Igusa and Clebsch [IJ1960]_.
`f` may be homogeneous in two variables or inhomogeneous in one.
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.invariants import igusa_clebsch_invariants
sage: R.<x, y> = QQ[]
sage: igusa_clebsch_invariants(x^6 + y^6)
(-240, 1620, -119880, -46656)
sage: R.<x> = QQ[]
sage: igusa_clebsch_invariants(x^6 + x^5 + x^4 + x^2 + 2)
(-496, 6220, -955932, -1111784)
sage: magma(x^6 + 1).IgusaClebschInvariants() # optional - magma
[ -240, 1620, -119880, -46656 ]
sage: magma(x^6 + x^5 + x^4 + x^2 + 2).IgusaClebschInvariants() # optional - magma
[ -496, 6220, -955932, -1111784 ]
TESTS:
Let's check a symbolic example::
sage: R.<a, b, c, d, e> = QQ[]
sage: S.<x> = R[]
sage: igusa_clebsch_invariants(x^5 + a*x^4 + b*x^3 + c*x^2 + d*x + e)[0]
6*b^2 - 16*a*c + 40*d
sage: absolute_igusa_invariants_wamelen(GF(5)['x'](x^6 - 2*x))
Traceback (most recent call last):
...
NotImplementedError: Invariants of binary sextics/genus 2 hyperelliptic curves not implemented in characteristics 2, 3, and 5
"""
return clebsch_to_igusa(*clebsch_invariants(f))
def absolute_igusa_invariants_wamelen(f):
r"""
Given a sextic form `f`, return the three absolute Igusa invariants used by van Wamelen [Wam1999]_.
`f` may be homogeneous in two variables or inhomogeneous in one.
REFERENCES:
- [Wam1999]_
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.invariants import absolute_igusa_invariants_wamelen
sage: R.<x> = QQ[]
sage: absolute_igusa_invariants_wamelen(x^5 - 1)
(0, 0, 0)
The following example can be checked against van Wamelen's paper::
sage: i1, i2, i3 = absolute_igusa_invariants_wamelen(-x^5 + 3*x^4 + 2*x^3 - 6*x^2 - 3*x + 1)
sage: list(map(factor, (i1, i2, i3)))
[2^7 * 3^15, 2^5 * 3^11 * 5, 2^4 * 3^9 * 31]
TESTS::
sage: absolute_igusa_invariants_wamelen(GF(3)['x'](x^5 - 2*x))
Traceback (most recent call last):
...
NotImplementedError: Invariants of binary sextics/genus 2 hyperelliptic curves not implemented in characteristics 2, 3, and 5
"""
I2, I4, I6, I10 = igusa_clebsch_invariants(f)
i1 = I2**5/I10
i2 = I2**3*I4/I10
i3 = I2**2*I6/I10
return (i1, i2, i3)
def absolute_igusa_invariants_kohel(f):
r"""
Given a sextic form `f`, return the three absolute Igusa invariants used by Kohel [KohECHIDNA]_.
`f` may be homogeneous in two variables or inhomogeneous in one.
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.invariants import absolute_igusa_invariants_kohel
sage: R.<x> = QQ[]
sage: absolute_igusa_invariants_kohel(x^5 - 1)
(0, 0, 0)
sage: absolute_igusa_invariants_kohel(x^5 - x)
(100, -20000, -2000)
The following example can be checked against Kohel's database [KohECHIDNA]_ ::
sage: i1, i2, i3 = absolute_igusa_invariants_kohel(-x^5 + 3*x^4 + 2*x^3 - 6*x^2 - 3*x + 1)
sage: list(map(factor, (i1, i2, i3)))
[2^2 * 3^5 * 5 * 31, 2^5 * 3^11 * 5, 2^4 * 3^9 * 31]
sage: list(map(factor, (150660, 28343520, 9762768)))
[2^2 * 3^5 * 5 * 31, 2^5 * 3^11 * 5, 2^4 * 3^9 * 31]
TESTS::
sage: absolute_igusa_invariants_kohel(GF(2)['x'](x^5 - x))
Traceback (most recent call last):
...
NotImplementedError: Invariants of binary sextics/genus 2 hyperelliptic curves not implemented in characteristics 2, 3, and 5
"""
I2, I4, I6, I10 = igusa_clebsch_invariants(f)
i1 = I4*I6/I10
i2 = I2**3*I4/I10
i3 = I2**2*I6/I10
return (i1, i2, i3) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/hyperelliptic_curves/invariants.py | 0.70028 | 0.909103 | invariants.py | pypi |
from sage.schemes.projective.projective_space import ProjectiveSpace
from .hyperelliptic_generic import HyperellipticCurve_generic
from .hyperelliptic_finite_field import HyperellipticCurve_finite_field
from .hyperelliptic_rational_field import HyperellipticCurve_rational_field
from .hyperelliptic_padic_field import HyperellipticCurve_padic_field
from .hyperelliptic_g2 import HyperellipticCurve_g2
import sage.rings.abc
from sage.rings.rational_field import is_RationalField
from sage.rings.finite_rings.finite_field_constructor import is_FiniteField
from sage.rings.polynomial.polynomial_element import is_Polynomial
from sage.structure.dynamic_class import dynamic_class
def HyperellipticCurve(f, h=0, names=None, PP=None, check_squarefree=True):
r"""
Returns the hyperelliptic curve `y^2 + h y = f`, for
univariate polynomials `h` and `f`. If `h`
is not given, then it defaults to 0.
INPUT:
- ``f`` - univariate polynomial
- ``h`` - optional univariate polynomial
- ``names`` (default: ``["x","y"]``) - names for the
coordinate functions
- ``check_squarefree`` (default: ``True``) - test if
the input defines a hyperelliptic curve when f is
homogenized to degree `2g+2` and h to degree
`g+1` for some g.
.. WARNING::
When setting ``check_squarefree=False`` or using a base ring that is
not a field, the output curves are not to be trusted. For example, the
output of ``is_singular`` is always ``False``, without this being
properly tested in that case.
.. NOTE::
The words "hyperelliptic curve" are normally only used for curves of
genus at least two, but this class allows more general smooth double
covers of the projective line (conics and elliptic curves), even though
the class is not meant for those and some outputs may be incorrect.
EXAMPLES:
Basic examples::
sage: R.<x> = QQ[]
sage: HyperellipticCurve(x^5 + x + 1)
Hyperelliptic Curve over Rational Field defined by y^2 = x^5 + x + 1
sage: HyperellipticCurve(x^19 + x + 1, x-2)
Hyperelliptic Curve over Rational Field defined by y^2 + (x - 2)*y = x^19 + x + 1
sage: k.<a> = GF(9); R.<x> = k[]
sage: HyperellipticCurve(x^3 + x - 1, x+a)
Hyperelliptic Curve over Finite Field in a of size 3^2 defined by y^2 + (x + a)*y = x^3 + x + 2
Characteristic two::
sage: P.<x> = GF(8,'a')[]
sage: HyperellipticCurve(x^7+1, x)
Hyperelliptic Curve over Finite Field in a of size 2^3 defined by y^2 + x*y = x^7 + 1
sage: HyperellipticCurve(x^8+x^7+1, x^4+1)
Hyperelliptic Curve over Finite Field in a of size 2^3 defined by y^2 + (x^4 + 1)*y = x^8 + x^7 + 1
sage: HyperellipticCurve(x^8+1, x)
Traceback (most recent call last):
...
ValueError: Not a hyperelliptic curve: highly singular at infinity.
sage: HyperellipticCurve(x^8+x^7+1, x^4)
Traceback (most recent call last):
...
ValueError: Not a hyperelliptic curve: singularity in the provided affine patch.
sage: F.<t> = PowerSeriesRing(FiniteField(2))
sage: P.<x> = PolynomialRing(FractionField(F))
sage: HyperellipticCurve(x^5+t, x)
Hyperelliptic Curve over Laurent Series Ring in t over Finite Field of size 2 defined by y^2 + x*y = x^5 + t
We can change the names of the variables in the output::
sage: k.<a> = GF(9); R.<x> = k[]
sage: HyperellipticCurve(x^3 + x - 1, x+a, names=['X','Y'])
Hyperelliptic Curve over Finite Field in a of size 3^2 defined by Y^2 + (X + a)*Y = X^3 + X + 2
This class also allows curves of genus zero or one, which are strictly
speaking not hyperelliptic::
sage: P.<x> = QQ[]
sage: HyperellipticCurve(x^2+1)
Hyperelliptic Curve over Rational Field defined by y^2 = x^2 + 1
sage: HyperellipticCurve(x^4-1)
Hyperelliptic Curve over Rational Field defined by y^2 = x^4 - 1
sage: HyperellipticCurve(x^3+2*x+2)
Hyperelliptic Curve over Rational Field defined by y^2 = x^3 + 2*x + 2
Double roots::
sage: P.<x> = GF(7)[]
sage: HyperellipticCurve((x^3-x+2)^2*(x^6-1))
Traceback (most recent call last):
...
ValueError: Not a hyperelliptic curve: singularity in the provided affine patch.
sage: HyperellipticCurve((x^3-x+2)^2*(x^6-1), check_squarefree=False)
Hyperelliptic Curve over Finite Field of size 7 defined by y^2 = x^12 + 5*x^10 + 4*x^9 + x^8 + 3*x^7 + 3*x^6 + 2*x^4 + 3*x^3 + 6*x^2 + 4*x + 3
The input for a (smooth) hyperelliptic curve of genus `g` should not
contain polynomials of degree greater than `2g+2`. In the following
example, the hyperelliptic curve has genus 2 and there exists a model
`y^2 = F` of degree 6, so the model `y^2 + yh = f` of degree 200 is not
allowed.::
sage: P.<x> = QQ[]
sage: h = x^100
sage: F = x^6+1
sage: f = F-h^2/4
sage: HyperellipticCurve(f, h)
Traceback (most recent call last):
...
ValueError: Not a hyperelliptic curve: highly singular at infinity.
sage: HyperellipticCurve(F)
Hyperelliptic Curve over Rational Field defined by y^2 = x^6 + 1
An example with a singularity over an inseparable extension of the
base field::
sage: F.<t> = GF(5)[]
sage: P.<x> = F[]
sage: HyperellipticCurve(x^5+t)
Traceback (most recent call last):
...
ValueError: Not a hyperelliptic curve: singularity in the provided affine patch.
Input with integer coefficients creates objects with the integers
as base ring, but only checks smoothness over `\QQ`, not over Spec(`\ZZ`).
In other words, it is checked that the discriminant is non-zero, but it is
not checked whether the discriminant is a unit in `\ZZ^*`.::
sage: P.<x> = ZZ[]
sage: HyperellipticCurve(3*x^7+6*x+6)
Hyperelliptic Curve over Integer Ring defined by y^2 = 3*x^7 + 6*x + 6
TESTS:
Check that `f` can be a constant (see :trac:`15516`)::
sage: R.<u> = PolynomialRing(Rationals())
sage: HyperellipticCurve(-12, u^4 + 7)
Hyperelliptic Curve over Rational Field defined by y^2 + (x^4 + 7)*y = -12
Check that two curves with the same class name have the same class type::
sage: R.<t> = PolynomialRing(GF(next_prime(10^9)))
sage: C = HyperellipticCurve(t^5 + t + 1)
sage: C2 = HyperellipticCurve(t^5 + 3*t + 1)
sage: type(C2) == type(C)
True
Check that the inheritance is correct::
sage: R.<t> = PolynomialRing(GF(next_prime(10^9)))
sage: C = HyperellipticCurve(t^5 + t + 1)
sage: type(C).mro()
[<class 'sage.schemes.hyperelliptic_curves.constructor.HyperellipticCurve_g2_FiniteField_with_category'>,
<class 'sage.schemes.hyperelliptic_curves.constructor.HyperellipticCurve_g2_FiniteField'>,
<class 'sage.schemes.hyperelliptic_curves.hyperelliptic_g2.HyperellipticCurve_g2'>,
<class 'sage.schemes.hyperelliptic_curves.hyperelliptic_finite_field.HyperellipticCurve_finite_field'>,
<class 'sage.schemes.hyperelliptic_curves.hyperelliptic_generic.HyperellipticCurve_generic'>,
...]
"""
# F is the discriminant; use this for the type check
# rather than f and h, one of which might be constant.
F = h**2 + 4*f
if not is_Polynomial(F):
raise TypeError("Arguments f (= %s) and h (= %s) must be polynomials" % (f, h))
P = F.parent()
f = P(f)
h = P(h)
df = f.degree()
dh_2 = 2*h.degree()
if dh_2 < df:
g = (df-1)//2
else:
g = (dh_2-1)//2
if check_squarefree:
# Assuming we are working over a field, this checks that after
# resolving the singularity at infinity, we get a smooth double cover
# of P^1.
if P(2) == 0:
# characteristic 2
if h == 0:
raise ValueError("In characteristic 2, argument h (= %s) must be non-zero." % h)
if h[g+1] == 0 and f[2*g+1]**2 == f[2*g+2]*h[g]**2:
raise ValueError("Not a hyperelliptic curve: "
"highly singular at infinity.")
should_be_coprime = [h, f*h.derivative()**2+f.derivative()**2]
else:
# characteristic not 2
if not F.degree() in [2*g+1, 2*g+2]:
raise ValueError("Not a hyperelliptic curve: "
"highly singular at infinity.")
should_be_coprime = [F, F.derivative()]
try:
smooth = should_be_coprime[0].gcd(should_be_coprime[1]).degree() == 0
except (AttributeError, NotImplementedError, TypeError):
try:
smooth = should_be_coprime[0].resultant(should_be_coprime[1]) != 0
except (AttributeError, NotImplementedError, TypeError):
raise NotImplementedError("Cannot determine whether "
"polynomials %s have a common root. Use "
"check_squarefree=False to skip this check." %
should_be_coprime)
if not smooth:
raise ValueError("Not a hyperelliptic curve: "
"singularity in the provided affine patch.")
R = P.base_ring()
PP = ProjectiveSpace(2, R)
if names is None:
names = ["x", "y"]
superclass = []
cls_name = ["HyperellipticCurve"]
genus_classes = {2: HyperellipticCurve_g2}
is_pAdicField = lambda x: isinstance(x, sage.rings.abc.pAdicField)
fields = [
("FiniteField", is_FiniteField, HyperellipticCurve_finite_field),
("RationalField", is_RationalField, HyperellipticCurve_rational_field),
("pAdicField", is_pAdicField, HyperellipticCurve_padic_field)]
if g in genus_classes:
superclass.append(genus_classes[g])
cls_name.append("g%s" % g)
for name, test, cls in fields:
if test(R):
superclass.append(cls)
cls_name.append(name)
break
class_name = "_".join(cls_name)
cls = dynamic_class(class_name, tuple(superclass),
HyperellipticCurve_generic, doccls=HyperellipticCurve)
return cls(PP, f, h, names=names, genus=g) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/hyperelliptic_curves/constructor.py | 0.935013 | 0.618838 | constructor.py | pypi |
r"""
Jacobian 'morphism' as a class in the Picard group
This module implements the group operation in the Picard group of a
hyperelliptic curve, represented as divisors in Mumford
representation, using Cantor's algorithm.
A divisor on the hyperelliptic curve `y^2 + y h(x) = f(x)`
is stored in Mumford representation, that is, as two polynomials
`u(x)` and `v(x)` such that:
- `u(x)` is monic,
- `u(x)` divides `f(x) - h(x) v(x) - v(x)^2`,
- `deg(v(x)) < deg(u(x)) \le g`.
REFERENCES:
A readable introduction to divisors, the Picard group, Mumford
representation, and Cantor's algorithm:
- J. Scholten, F. Vercauteren. An Introduction to Elliptic and
Hyperelliptic Curve Cryptography and the NTRU Cryptosystem. To
appear in B. Preneel (Ed.) State of the Art in Applied Cryptography
- COSIC '03, Lecture Notes in Computer Science, Springer 2004.
A standard reference in the field of cryptography:
- R. Avanzi, H. Cohen, C. Doche, G. Frey, T. Lange, K. Nguyen, and F.
Vercauteren, Handbook of Elliptic and Hyperelliptic Curve
Cryptography. CRC Press, 2005.
EXAMPLES: The following curve is the reduction of a curve whose
Jacobian has complex multiplication.
::
sage: x = GF(37)['x'].gen()
sage: H = HyperellipticCurve(x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x); H
Hyperelliptic Curve over Finite Field of size 37 defined
by y^2 = x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x
At this time, Jacobians of hyperelliptic curves are handled
differently than elliptic curves::
sage: J = H.jacobian(); J
Jacobian of Hyperelliptic Curve over Finite Field of size 37 defined
by y^2 = x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x
sage: J = J(J.base_ring()); J
Set of rational points of Jacobian of Hyperelliptic Curve over Finite Field
of size 37 defined by y^2 = x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x
Points on the Jacobian are represented by Mumford's polynomials.
First we find a couple of points on the curve::
sage: P1 = H.lift_x(2); P1
(2 : 11 : 1)
sage: Q1 = H.lift_x(10); Q1
(10 : 18 : 1)
Observe that 2 and 10 are the roots of the polynomials in x,
respectively::
sage: P = J(P1); P
(x + 35, y + 26)
sage: Q = J(Q1); Q
(x + 27, y + 19)
::
sage: P + Q
(x^2 + 25*x + 20, y + 13*x)
sage: (x^2 + 25*x + 20).roots(multiplicities=False)
[10, 2]
Frobenius satisfies
.. MATH::
x^4 + 12*x^3 + 78*x^2 + 444*x + 1369
on the Jacobian of this reduction and the order of the Jacobian is
`N = 1904`.
::
sage: 1904*P
(1)
sage: 34*P == 0
True
sage: 35*P == P
True
sage: 33*P == -P
True
::
sage: Q*1904
(1)
sage: Q*238 == 0
True
sage: Q*239 == Q
True
sage: Q*237 == -Q
True
"""
#*****************************************************************************
# Copyright (C) 2005 David Kohel <kohel@maths.usyd.edu.au>
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#*****************************************************************************
from sage.misc.latex import latex
from sage.structure.element import AdditiveGroupElement
from sage.structure.richcmp import richcmp, op_NE
from sage.schemes.generic.morphism import SchemeMorphism
def cantor_reduction_simple(a, b, f, genus):
r"""
Return the unique reduced divisor linearly equivalent to
`(a, b)` on the curve `y^2 = f(x).`
See the docstring of
:mod:`sage.schemes.hyperelliptic_curves.jacobian_morphism` for
information about divisors, linear equivalence, and reduction.
EXAMPLES::
sage: x = QQ['x'].gen()
sage: f = x^5 - x
sage: H = HyperellipticCurve(f); H
Hyperelliptic Curve over Rational Field defined by y^2 = x^5 - x
sage: J = H.jacobian()(QQ); J
Set of rational points of Jacobian of Hyperelliptic Curve over Rational Field
defined by y^2 = x^5 - x
The following point is 2-torsion::
sage: P = J(H.lift_x(-1)); P
(x + 1, y)
sage: 2 * P # indirect doctest
(1)
"""
a2 = (f - b**2) // a
a2 = a2.monic()
b2 = -b % (a2)
if a2.degree() == a.degree():
# XXX
assert a2.degree() == genus + 1
print("Returning ambiguous form of degree genus+1.")
return (a2, b2)
elif a2.degree() > genus:
return cantor_reduction_simple(a2, b2, f, genus)
return (a2, b2)
def cantor_reduction(a, b, f, h, genus):
r"""
Return the unique reduced divisor linearly equivalent to
`(a, b)` on the curve `y^2 + y h(x) = f(x)`.
See the docstring of
:mod:`sage.schemes.hyperelliptic_curves.jacobian_morphism` for
information about divisors, linear equivalence, and reduction.
EXAMPLES::
sage: x = QQ['x'].gen()
sage: f = x^5 - x
sage: H = HyperellipticCurve(f, x); H
Hyperelliptic Curve over Rational Field defined by y^2 + x*y = x^5 - x
sage: J = H.jacobian()(QQ); J
Set of rational points of Jacobian of Hyperelliptic Curve over
Rational Field defined by y^2 + x*y = x^5 - x
The following point is 2-torsion::
sage: Q = J(H.lift_x(0)); Q
(x, y)
sage: 2*Q # indirect doctest
(1)
The next point is not 2-torsion::
sage: P = J(H.lift_x(-1)); P
(x + 1, y - 1)
sage: 2 * J(H.lift_x(-1)) # indirect doctest
(x^2 + 2*x + 1, y - 3*x - 4)
sage: 3 * J(H.lift_x(-1)) # indirect doctest
(x^2 - 487*x - 324, y - 10754*x - 7146)
"""
assert a.degree() < 2*genus+1
assert b.degree() < a.degree()
k = f - h*b - b**2
if 2*a.degree() == k.degree():
# must adjust b to include the point at infinity
g1 = a.degree()
x = a.parent().gen()
r = (x**2 + h[g1]*x - f[2*g1]).roots()[0][0]
b = b + r*(x**g1 - (x**g1) % (a))
k = f - h*b - b**2
assert k % (a) == 0
a = (k // a).monic()
b = -(b+h) % (a)
if a.degree() > genus:
return cantor_reduction(a, b, f, h, genus)
return (a, b)
def cantor_composition_simple(D1,D2,f,genus):
r"""
Given `D_1` and `D_2` two reduced Mumford
divisors on the Jacobian of the curve `y^2 = f(x)`,
computes a representative `D_1 + D_2`.
.. warning::
The representative computed is NOT reduced! Use
:func:`cantor_reduction_simple` to reduce it.
EXAMPLES::
sage: x = QQ['x'].gen()
sage: f = x^5 + x
sage: H = HyperellipticCurve(f); H
Hyperelliptic Curve over Rational Field defined by y^2 = x^5 + x
::
sage: F.<a> = NumberField(x^2 - 2, 'a')
sage: J = H.jacobian()(F); J
Set of rational points of Jacobian of Hyperelliptic Curve over
Number Field in a with defining polynomial x^2 - 2 defined
by y^2 = x^5 + x
::
sage: P = J(H.lift_x(F(1))); P
(x - 1, y - a)
sage: Q = J(H.lift_x(F(0))); Q
(x, y)
sage: 2*P + 2*Q # indirect doctest
(x^2 - 2*x + 1, y - 3/2*a*x + 1/2*a)
sage: 2*(P + Q) # indirect doctest
(x^2 - 2*x + 1, y - 3/2*a*x + 1/2*a)
sage: 3*P # indirect doctest
(x^2 - 25/32*x + 49/32, y - 45/256*a*x - 315/256*a)
"""
a1, b1 = D1
a2, b2 = D2
if a1 == a2 and b1 == b2:
# Duplication law:
d, h1, h3 = a1.xgcd(2*b1)
a = (a1 // d)**2
b = (b1 + h3*((f - b1**2) // d)) % (a)
else:
d0, _, h2 = a1.xgcd(a2)
if d0 == 1:
a = a1*a2
b = (b2 + h2*a2*(b1-b2)) % (a)
else:
d, l, h3 = d0.xgcd(b1 + b2)
a = (a1*a2) // (d**2)
b = ((b2 + l*h2*(b1-b2)*(a2 // d)) + h3*((f - b2**2) // d)) % (a)
a =a.monic()
return (a, b)
def cantor_composition(D1,D2,f,h,genus):
r"""
EXAMPLES::
sage: F.<a> = GF(7^2, 'a')
sage: x = F['x'].gen()
sage: f = x^7 + x^2 + a
sage: H = HyperellipticCurve(f, 2*x); H
Hyperelliptic Curve over Finite Field in a of size 7^2 defined by y^2 + 2*x*y = x^7 + x^2 + a
sage: J = H.jacobian()(F); J
Set of rational points of Jacobian of Hyperelliptic Curve over
Finite Field in a of size 7^2 defined by y^2 + 2*x*y = x^7 + x^2 + a
::
sage: Q = J(H.lift_x(F(1))); Q
(x + 6, y + 2*a + 2)
sage: 10*Q # indirect doctest
(x^3 + (3*a + 1)*x^2 + (2*a + 5)*x + a + 5, y + (4*a + 5)*x^2 + (a + 1)*x + 6*a + 3)
sage: 7*8297*Q
(1)
::
sage: Q = J(H.lift_x(F(a+1))); Q
(x + 6*a + 6, y + 2*a)
sage: 7*8297*Q # indirect doctest
(1)
A test over a prime field:
sage: F = GF(next_prime(10^30))
sage: x = F['x'].gen()
sage: f = x^7 + x^2 + 1
sage: H = HyperellipticCurve(f, 2*x); H
Hyperelliptic Curve over Finite Field of size 1000000000000000000000000000057 defined by y^2 + 2*x*y = x^7 + x^2 + 1
sage: J = H.jacobian()(F); J
Set of rational points of Jacobian of Hyperelliptic Curve over
Finite Field of size 1000000000000000000000000000057 defined
by y^2 + 2*x*y = x^7 + x^2 + 1
sage: Q = J(H.lift_x(F(1))); Q
(x + 1000000000000000000000000000056, y + 1000000000000000000000000000056)
sage: 10*Q # indirect doctest
(x^3 + 150296037169838934997145567227*x^2 + 377701248971234560956743242408*x + 509456150352486043408603286615, y + 514451014495791237681619598519*x^2 + 875375621665039398768235387900*x + 861429240012590886251910326876)
sage: 7*8297*Q
(x^3 + 35410976139548567549919839063*x^2 + 26230404235226464545886889960*x + 681571430588959705539385624700, y + 999722365017286747841221441793*x^2 + 262703715994522725686603955650*x + 626219823403254233972118260890)
"""
a1, b1 = D1
a2, b2 = D2
if a1 == a2 and b1 == b2:
# Duplication law:
d, h1, h3 = a1.xgcd(2*b1 + h)
a = (a1 // d)**2
b = (b1 + h3*((f-h*b1-b1**2) // d)) % (a)
else:
d0, _, h2 = a1.xgcd(a2)
if d0 == 1:
a = a1 * a2
b = (b2 + h2*a2*(b1-b2)) % (a)
else:
e0 = b1+b2+h
if e0 == 0:
a = (a1*a2) // (d0**2)
b = (b2 + h2*(b1-b2)*(a2 // d0)) % (a)
else:
d, l, h3 = d0.xgcd(e0)
a = (a1*a2) // (d**2)
b = (b2 + l*h2*(b1-b2)*(a2 // d) + h3*((f-h*b2-b2**2) // d)) % (a)
a = a.monic()
return (a, b)
class JacobianMorphism_divisor_class_field(AdditiveGroupElement, SchemeMorphism):
r"""
An element of a Jacobian defined over a field, i.e. in
`J(K) = \mathrm{Pic}^0_K(C)`.
"""
def __init__(self, parent, polys, check=True):
r"""
Create a new Jacobian element in Mumford representation.
INPUT:
- parent -- the parent Homset
- polys -- Mumford's `u` and `v` polynomials
- check (default: ``True``) -- if ``True``, ensure that
polynomials define a divisor on the appropriate curve and are
reduced
.. warning::
Not for external use! Use ``J(K)([u, v])`` instead.
EXAMPLES::
sage: x = GF(37)['x'].gen()
sage: H = HyperellipticCurve(x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x)
sage: J = H.jacobian()(GF(37)); J
Set of rational points of Jacobian of Hyperelliptic Curve over
Finite Field of size 37 defined by
y^2 = x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x
::
sage: P1 = J(H.lift_x(2)); P1 # indirect doctest
(x + 35, y + 26)
sage: P1.parent()
Set of rational points of Jacobian of Hyperelliptic Curve over
Finite Field of size 37 defined by
y^2 = x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x
sage: type(P1)
<class 'sage.schemes.hyperelliptic_curves.jacobian_morphism.JacobianMorphism_divisor_class_field'>
"""
SchemeMorphism.__init__(self, parent)
if check:
C = parent.curve()
f, h = C.hyperelliptic_polynomials()
a, b = polys
if not (b**2 + h*b - f)%a == 0:
raise ValueError("Argument polys (= %s) must be divisor on curve %s."%(
polys, C))
genus = C.genus()
if a.degree() > genus:
polys = cantor_reduction(a, b, f, h, genus)
self.__polys = polys
def _printing_polys(self):
r"""
Internal function formatting Mumford polynomials for printing.
TESTS::
sage: F.<a> = GF(7^2, 'a')
sage: x = F['x'].gen()
sage: f = x^7 + x^2 + a
sage: H = HyperellipticCurve(f, 2*x)
sage: J = H.jacobian()(F)
::
sage: Q = J(H.lift_x(F(1))); Q # indirect doctest
(x + 6, y + 2*a + 2)
"""
a, b = self.__polys
P = self.parent()._printing_ring
y = P.gen()
x = P.base_ring().gen()
return (a(x), y - b(x))
def _repr_(self):
r"""
Return a string representation of this Mumford divisor.
EXAMPLES::
sage: F.<a> = GF(7^2, 'a')
sage: x = F['x'].gen()
sage: f = x^7 + x^2 + a
sage: H = HyperellipticCurve(f, 2*x)
sage: J = H.jacobian()(F)
::
sage: Q = J(0); Q # indirect doctest
(1)
sage: Q = J(H.lift_x(F(1))); Q # indirect doctest
(x + 6, y + 2*a + 2)
sage: Q + Q # indirect doctest
(x^2 + 5*x + 1, y + 3*a*x + 6*a + 2)
"""
if self.is_zero():
return "(1)"
a, b = self._printing_polys()
return "(%s, %s)" % (a, b)
def _latex_(self):
r"""
Return a LaTeX string representing this Mumford divisor.
EXAMPLES::
sage: F.<alpha> = GF(7^2)
sage: x = F['x'].gen()
sage: f = x^7 + x^2 + alpha
sage: H = HyperellipticCurve(f, 2*x)
sage: J = H.jacobian()(F)
::
sage: Q = J(0); print(latex(Q)) # indirect doctest
\left(1\right)
sage: Q = J(H.lift_x(F(1))); print(latex(Q)) # indirect doctest
\left(x + 6, y + 2 \alpha + 2\right)
::
sage: print(latex(Q + Q))
\left(x^{2} + 5 x + 1, y + 3 \alpha x + 6 \alpha + 2\right)
"""
if self.is_zero():
return "\\left(1\\right)"
a, b = self._printing_polys()
return "\\left(%s, %s\\right)" % (latex(a), latex(b))
def scheme(self):
r"""
Return the scheme this morphism maps to; or, where this divisor
lives.
.. warning::
Although a pointset is defined over a specific field, the
scheme returned may be over a different (usually smaller)
field. The example below demonstrates this: the pointset
is determined over a number field of absolute degree 2 but
the scheme returned is defined over the rationals.
EXAMPLES::
sage: x = QQ['x'].gen()
sage: f = x^5 + x
sage: H = HyperellipticCurve(f)
sage: F.<a> = NumberField(x^2 - 2, 'a')
sage: J = H.jacobian()(F); J
Set of rational points of Jacobian of Hyperelliptic Curve over
Number Field in a with defining polynomial x^2 - 2 defined
by y^2 = x^5 + x
::
sage: P = J(H.lift_x(F(1)))
sage: P.scheme()
Jacobian of Hyperelliptic Curve over Rational Field defined by y^2 = x^5 + x
"""
return self.codomain()
def __list__(self):
r"""
Return a list `(a(x), b(x))` of the polynomials giving the
Mumford representation of self.
TESTS::
sage: x = QQ['x'].gen()
sage: f = x^5 + x
sage: H = HyperellipticCurve(f)
sage: F.<a> = NumberField(x^2 - 2, 'a')
sage: J = H.jacobian()(F); J
Set of rational points of Jacobian of Hyperelliptic Curve over
Number Field in a with defining polynomial x^2 - 2 defined
by y^2 = x^5 + x
::
sage: P = J(H.lift_x(F(1)))
sage: list(P) # indirect doctest
[x - 1, a]
"""
return list(self.__polys)
def __tuple__(self):
r"""
Return a tuple `(a(x), b(x))` of the polynomials giving the
Mumford representation of self.
TESTS::
sage: x = QQ['x'].gen()
sage: f = x^5 + x
sage: H = HyperellipticCurve(f)
sage: F.<a> = NumberField(x^2 - 2, 'a')
sage: J = H.jacobian()(F); J
Set of rational points of Jacobian of Hyperelliptic Curve over
Number Field in a with defining polynomial x^2 - 2 defined
by y^2 = x^5 + x
::
sage: P = J(H.lift_x(F(1)))
sage: tuple(P) # indirect doctest
(x - 1, a)
"""
return tuple(self.__polys)
def __getitem__(self, n):
r"""
Return the `n`-th item of the pair `(a(x), b(x))`
of polynomials giving the Mumford representation of self.
TESTS::
sage: x = QQ['x'].gen()
sage: f = x^5 + x
sage: H = HyperellipticCurve(f)
sage: F.<a> = NumberField(x^2 - 2, 'a')
sage: J = H.jacobian()(F); J
Set of rational points of Jacobian of Hyperelliptic Curve over
Number Field in a with defining polynomial x^2 - 2 defined
by y^2 = x^5 + x
::
sage: P = J(H.lift_x(F(1)))
sage: P[0] # indirect doctest
x - 1
sage: P[1] # indirect doctest
a
sage: P[-1] # indirect doctest
a
sage: P[:1] # indirect doctest
[x - 1]
"""
return list(self.__polys)[n]
def _richcmp_(self, other, op):
r"""
Compare self and other.
TESTS::
sage: x = QQ['x'].gen()
sage: f = x^5 - x
sage: H = HyperellipticCurve(f); H
Hyperelliptic Curve over Rational Field defined by y^2 = x^5 - x
sage: J = H.jacobian()(QQ); J
Set of rational points of Jacobian of Hyperelliptic Curve over
Rational Field defined by y^2 = x^5 - x
The following point is 2-torsion::
sage: P = J(H.lift_x(-1)); P
(x + 1, y)
sage: 0 == 2 * P # indirect doctest
True
sage: P == P
True
::
sage: Q = J(H.lift_x(-1))
sage: Q == P
True
::
sage: 2 == Q
False
sage: P == False
False
Let's verify the same "points" on different schemes are not equal::
sage: x = QQ['x'].gen()
sage: f = x^5 + x
sage: H2 = HyperellipticCurve(f)
sage: J2 = H2.jacobian()(QQ)
::
sage: P1 = J(H.lift_x(0)); P1
(x, y)
sage: P2 = J2(H2.lift_x(0)); P2
(x, y)
sage: P1 == P2
False
"""
if self.scheme() != other.scheme():
return op == op_NE
# since divisors are internally represented as Mumford divisors,
# comparing polynomials is well-defined
return richcmp(self.__polys, other.__polys, op)
def __bool__(self):
r"""
Return ``True`` if this divisor is not the additive identity element.
EXAMPLES::
sage: x = GF(37)['x'].gen()
sage: H = HyperellipticCurve(x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x)
sage: J = H.jacobian()(GF(37))
::
sage: P1 = J(H.lift_x(2)); P1
(x + 35, y + 26)
sage: P1 == 0 # indirect doctest
False
sage: P1 - P1 == 0 # indirect doctest
True
"""
return self.__polys[0] != 1
def __neg__(self):
r"""
Return the additive inverse of this divisor.
EXAMPLES::
sage: x = GF(37)['x'].gen()
sage: H = HyperellipticCurve(x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x)
sage: J = H.jacobian()(GF(37))
sage: P1 = J(H.lift_x(2)); P1
(x + 35, y + 26)
sage: - P1 # indirect doctest
(x + 35, y + 11)
sage: P1 + (-P1) # indirect doctest
(1)
::
sage: H2 = HyperellipticCurve(x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x, x)
sage: J2 = H2.jacobian()(GF(37))
sage: P2 = J2(H2.lift_x(2)); P2
(x + 35, y + 15)
sage: - P2 # indirect doctest
(x + 35, y + 24)
sage: P2 + (-P2) # indirect doctest
(1)
TESTS:
The following was fixed in :trac:`14264`::
sage: P.<x> = QQ[]
sage: f = x^5 - x + 1; h = x
sage: C = HyperellipticCurve(f,h,'u,v')
sage: J = C.jacobian()
sage: K.<t> = NumberField(x^2-2)
sage: R.<x> = K[]
sage: Q = J(K)([x^2-t,R(1)])
sage: Q
(u^2 - t, v - 1)
sage: -Q
(u^2 - t, v + u + 1)
sage: Q + (-Q) # indirect doctest
(1)
"""
if self.is_zero():
return self
polys = self.__polys
X = self.parent()
f, h = X.curve().hyperelliptic_polynomials()
if h.is_zero():
D = (polys[0],-polys[1])
else:
# It is essential that the modulus polys[0] can be converted into
# the parent of the dividend h. This is not always automatically
# the case (h can be a rational polynomial and polys[0] can a
# non-constant polynomial over a number field different from
# QQ). Hence, we force coercion into a common parent before
# computing the modulus. See trac #14249
D = (polys[0],-polys[1]-(h+polys[0]) % (polys[0]))
return JacobianMorphism_divisor_class_field(X, D, check=False)
def _add_(self,other):
r"""
Return a Mumford representative of the divisor self + other.
EXAMPLES::
sage: x = GF(37)['x'].gen()
sage: H = HyperellipticCurve(x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x)
sage: J = H.jacobian()(GF(37))
::
sage: P1 = J(H.lift_x(2)); P1
(x + 35, y + 26)
sage: P1 + P1 # indirect doctest
(x^2 + 33*x + 4, y + 13*x)
"""
X = self.parent()
C = X.curve()
f, h = C.hyperelliptic_polynomials()
genus = C.genus()
if h == 0:
D = cantor_composition_simple(self.__polys, other.__polys, f, genus)
if D[0].degree() > genus:
D = cantor_reduction_simple(D[0], D[1], f, genus)
else:
D = cantor_composition(self.__polys, other.__polys, f, h, genus)
if D[0].degree() > genus:
D = cantor_reduction(D[0], D[1], f, h, genus)
return JacobianMorphism_divisor_class_field(X, D, check=False)
def _sub_(self, other):
r"""
Return a Mumford representative of the divisor self - other.
EXAMPLES::
sage: x = GF(37)['x'].gen()
sage: H = HyperellipticCurve(x^5 + 12*x^4 + 13*x^3 + 15*x^2 + 33*x)
sage: J = H.jacobian()(GF(37))
::
sage: P1 = J(H.lift_x(2)); P1
(x + 35, y + 26)
sage: P1 - P1 # indirect doctest
(1)
::
sage: P2 = J(H.lift_x(4)); P2
(x + 33, y + 34)
Observe that the `x`-coordinates are the same but the
`y`-coordinates differ::
sage: P1 - P2 # indirect doctest
(x^2 + 31*x + 8, y + 7*x + 12)
sage: P1 + P2 # indirect doctest
(x^2 + 31*x + 8, y + 4*x + 18)
sage: (P1 - P2) - (P1 + P2) + 2*P2 # indirect doctest
(1)
"""
return self + (-other) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/hyperelliptic_curves/jacobian_morphism.py | 0.897485 | 0.916559 | jacobian_morphism.py | pypi |
from sage.misc.latex import latex
from sage.misc.repr import repr_lincomb
from sage.misc.search import search
from sage.rings.integer_ring import ZZ
from sage.structure.formal_sum import FormalSum
from .morphism import is_SchemeMorphism
from sage.schemes.affine.affine_space import is_AffineSpace
from sage.schemes.projective.projective_space import is_ProjectiveSpace
def CurvePointToIdeal(C,P):
r"""
Return the vanishing ideal of a point on a curve.
EXAMPLES::
sage: x,y = AffineSpace(2, QQ, names='xy').gens()
sage: C = Curve(y^2 - x^9 - x)
sage: from sage.schemes.generic.divisor import CurvePointToIdeal
sage: CurvePointToIdeal(C, (0,0))
Ideal (x, y) of Multivariate Polynomial Ring in x, y over Rational Field
"""
A = C.ambient_space()
R = A.coordinate_ring()
n = A.ngens()
x = A.gens()
polys = [ ]
m = n-1
while m > 0 and P[m] == 0:
m += -1
if is_ProjectiveSpace(A):
a_m = P[m]
x_m = x[m]
for i in range(m):
ai = P[i]
if ai == 0:
polys.append(x[i])
else:
polys.append(a_m*x[i]-ai*x_m)
elif is_AffineSpace(A):
for i in range(m+1):
ai = P[i]
if ai == 0:
polys.append(x[i])
else:
polys.append(x[i]-ai)
for i in range(m+1,n):
polys.append(x[i])
return R.ideal(polys)
def is_Divisor(x):
r"""
Test whether ``x`` is an instance of :class:`Divisor_generic`
INPUT:
- ``x`` -- anything.
OUTPUT:
``True`` or ``False``.
EXAMPLES::
sage: from sage.schemes.generic.divisor import is_Divisor
sage: x,y = AffineSpace(2, GF(5), names='xy').gens()
sage: C = Curve(y^2 - x^9 - x)
sage: is_Divisor( C.divisor([]) )
True
sage: is_Divisor("Ceci n'est pas un diviseur")
False
"""
return isinstance(x, Divisor_generic)
class Divisor_generic(FormalSum):
r"""
A Divisor.
"""
def __init__(self, v, parent, check=True, reduce=True):
r"""
Construct a :class:`Divisor_generic`.
INPUT:
INPUT:
- ``v`` -- object. Usually a list of pairs
``(coefficient,divisor)``.
- ``parent`` -- FormalSums(R) module (default: FormalSums(ZZ))
- ``check`` -- bool (default: True). Whether to coerce
coefficients into base ring. Setting it to ``False`` can
speed up construction.
- ``reduce`` -- reduce (default: True). Whether to combine
common terms. Setting it to ``False`` can speed up
construction.
.. WARNING::
The coefficients of the divisor must be in the base ring
and the terms must be reduced. If you set ``check=False``
and/or ``reduce=False`` it is your responsibility to pass
a valid object ``v``.
EXAMPLES::
sage: from sage.schemes.generic.divisor import Divisor_generic
sage: from sage.schemes.generic.divisor_group import DivisorGroup
sage: Divisor_generic( [(4,5)], DivisorGroup(Spec(ZZ)), False, False)
4*V(5)
"""
FormalSum.__init__(self, v, parent, check, reduce)
def _latex_(self):
r"""
Return a LaTeX representation of ``self``.
OUTPUT:
- string.
TESTS::
sage: R.<x, y> = ZZ[]
sage: S = Spec(R)
sage: from sage.schemes.generic.divisor import Divisor_generic
sage: from sage.schemes.generic.divisor_group import DivisorGroup
sage: Div = DivisorGroup(S)
sage: D = Divisor_generic([(4, x), (-5, y), (1, x+2*y)], Div)
sage: D._latex_()
'\\mathrm{V}\\left(x + 2 y\\right)
+ 4 \\mathrm{V}\\left(x\\right)
- 5 \\mathrm{V}\\left(y\\right)'
"""
# The code is copied from _repr_ with latex adjustments
terms = list(self)
# We sort the terms by variety. The order is "reversed" to keep it
# straight - as the test above demonstrates, it results in the first
# generator being in front of the second one
terms.sort(key=lambda x: x[1], reverse=True)
return repr_lincomb([(r"\mathrm{V}\left(%s\right)" % latex(v), c) for c,v in terms],
is_latex=True)
def _repr_(self):
r"""
Return a string representation of ``self``.
OUTPUT:
- string.
TESTS::
sage: R.<x, y> = ZZ[]
sage: S = Spec(R)
sage: from sage.schemes.generic.divisor import Divisor_generic
sage: from sage.schemes.generic.divisor_group import DivisorGroup
sage: Div = DivisorGroup(S)
sage: D = Divisor_generic([(4, x), (-5, y), (1, x+2*y)], Div)
sage: D._repr_()
'V(x + 2*y) + 4*V(x) - 5*V(y)'
"""
# The default representation coming from formal sums does not look
# very nice for divisors
terms = list(self)
# We sort the terms by variety. The order is "reversed" to keep it
# straight - as the test above demonstrates, it results in the first
# generator being in front of the second one
terms.sort(key=lambda x: x[1], reverse=True)
return repr_lincomb([("V(%s)" % v, c) for c,v in terms])
def scheme(self):
"""
Return the scheme that this divisor is on.
EXAMPLES::
sage: A.<x, y> = AffineSpace(2, GF(5))
sage: C = Curve(y^2 - x^9 - x)
sage: pts = C.rational_points(); pts
[(0, 0), (2, 2), (2, 3), (3, 1), (3, 4)]
sage: D = C.divisor(pts[0])*3 - C.divisor(pts[1]); D
3*(x, y) - (x - 2, y - 2)
sage: D.scheme()
Affine Plane Curve over Finite Field of size 5 defined by -x^9 + y^2 - x
"""
return self.parent().scheme()
class Divisor_curve(Divisor_generic):
r"""
For any curve `C`, use ``C.divisor(v)`` to
construct a divisor on `C`. Here `v` can be either
- a rational point on `C`
- a list of rational points
- a list of 2-tuples `(c,P)`, where `c` is an
integer and `P` is a rational point.
TODO: Divisors shouldn't be restricted to rational points. The
problem is that the divisor group is the formal sum of the group of
points on the curve, and there's no implemented notion of point on
`E/K` that has coordinates in `L`. This is what
should be implemented, by adding an appropriate class to
``schemes/generic/morphism.py``.
EXAMPLES::
sage: E = EllipticCurve([0, 0, 1, -1, 0])
sage: P = E(0,0)
sage: 10*P
(161/16 : -2065/64 : 1)
sage: D = E.divisor(P)
sage: D
(x, y)
sage: 10*D
10*(x, y)
sage: E.divisor([P, P])
2*(x, y)
sage: E.divisor([(3,P), (-4,5*P)])
3*(x, y) - 4*(x - 1/4*z, y + 5/8*z)
"""
def __init__(self, v, parent=None, check=True, reduce=True):
"""
Construct a divisor on a curve.
INPUT:
- ``v`` -- a list of pairs ``(c, P)``, where ``c`` is an
integer and ``P`` is a point on a curve. The P's must all
lie on the same curve.
- To create the divisor 0 use ``[(0, P)]``, so as to give the curve.
EXAMPLES::
sage: E = EllipticCurve([0, 0, 1, -1, 0])
sage: P = E(0,0)
sage: from sage.schemes.generic.divisor import Divisor_curve
sage: from sage.schemes.generic.divisor_group import DivisorGroup
sage: Divisor_curve([(1,P)], parent=DivisorGroup(E))
(x, y)
"""
from sage.schemes.generic.divisor_group import DivisorGroup_curve
if not isinstance(v, (list, tuple)):
v = [(1,v)]
if parent is None:
if v:
t = v[0]
if isinstance(t, tuple) and len(t) == 2:
try:
C = t[1].scheme()
except (TypeError, AttributeError):
raise TypeError("Argument v (= %s) must consist of multiplicities and points on a scheme.")
else:
try:
C = t.scheme()
except TypeError:
raise TypeError("Argument v (= %s) must consist of multiplicities and points on a scheme.")
parent = DivisorGroup_curve(C)
else:
raise TypeError("Argument v (= %s) must consist of multiplicities and points on a scheme.")
else:
if not isinstance(parent, DivisorGroup_curve):
raise TypeError("parent (of type %s) must be a DivisorGroup_curve" % type(parent))
C = parent.scheme()
if len(v) < 1:
check = False
know_points = False
if check:
w = []
points = []
know_points = True
for t in v:
if isinstance(t, tuple) and len(t) == 2:
n = ZZ(t[0])
I = t[1]
points.append((n,I))
else:
n = ZZ(1)
I = t
if is_SchemeMorphism(I):
I = CurvePointToIdeal(C,I)
else:
know_points = False
w.append((n,I))
v = w
Divisor_generic.__init__(
self, v, check=False, reduce=True, parent=parent)
if know_points:
self._points = points
def _repr_(self):
r"""
Return a string representation.
OUTPUT:
A string.
EXAMPLES::
sage: E = EllipticCurve([0, 0, 1, -1, 0])
sage: E.divisor( E(0,0) )._repr_()
'(x, y)'
"""
return repr_lincomb([(tuple(I.gens()), c) for c, I in self])
def support(self):
"""
Return the support of this divisor, which is the set of points that
occur in this divisor with nonzero coefficients.
EXAMPLES::
sage: x,y = AffineSpace(2, GF(5), names='xy').gens()
sage: C = Curve(y^2 - x^9 - x)
sage: pts = C.rational_points(); pts
[(0, 0), (2, 2), (2, 3), (3, 1), (3, 4)]
sage: D = C.divisor_group()([(3,pts[0]), (-1, pts[1])]); D
3*(x, y) - (x - 2, y - 2)
sage: D.support()
[(0, 0), (2, 2)]
TESTS:
This checks that :trac:`10732` is fixed::
sage: R.<x, y, z> = GF(5)[]
sage: C = Curve(x^7 + y^7 + z^7)
sage: pts = C.rational_points()
sage: D = C.divisor([(2, pts[0])])
sage: D.support()
[(0 : 4 : 1)]
sage: (D + D).support()
[(0 : 4 : 1)]
sage: E = C.divisor([(-3, pts[1]), (1, pts[2])])
sage: (D - 2*E).support()
[(0 : 4 : 1), (1 : 2 : 1), (2 : 1 : 1)]
sage: (D - D).support()
[]
"""
try:
return self._support
except AttributeError:
try:
pts = self._points
except AttributeError:
# TODO: in the next line, we should probably replace
# rational_points() with irreducible_components()
# once Sage can deal with divisors that are not only
# rational points (see trac #16225)
self._points = [(m, self.scheme().ambient_space().subscheme(p).rational_points()[0]) for (m, p) in self]
pts = self._points
self._support = [s[1] for s in pts]
return self._support
def coefficient(self, P):
"""
Return the coefficient of a given point P in this divisor.
EXAMPLES::
sage: x,y = AffineSpace(2, GF(5), names='xy').gens()
sage: C = Curve(y^2 - x^9 - x)
sage: pts = C.rational_points(); pts
[(0, 0), (2, 2), (2, 3), (3, 1), (3, 4)]
sage: D = C.divisor(pts[0])
sage: D.coefficient(pts[0])
1
sage: D = C.divisor([(3,pts[0]), (-1,pts[1])]); D
3*(x, y) - (x - 2, y - 2)
sage: D.coefficient(pts[0])
3
sage: D.coefficient(pts[1])
-1
"""
P = self.parent().scheme()(P)
if P not in self.support():
return self.base_ring().zero()
t, i = search(self.support(), P)
assert t
try:
return self._points[i][0]
except AttributeError:
raise NotImplementedError | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/generic/divisor.py | 0.78968 | 0.39129 | divisor.py | pypi |
from sage.structure.parent import Parent
from sage.misc.cachefunc import cached_method
from sage.rings.integer_ring import ZZ
from sage.categories.commutative_rings import CommutativeRings
from sage.rings.ideal import is_Ideal
from sage.structure.unique_representation import UniqueRepresentation
from sage.schemes.generic.point import SchemeTopologicalPoint_prime_ideal
def is_Scheme(x):
"""
Test whether ``x`` is a scheme.
INPUT:
- ``x`` -- anything.
OUTPUT:
Boolean. Whether ``x`` derives from :class:`Scheme`.
EXAMPLES::
sage: from sage.schemes.generic.scheme import is_Scheme
sage: is_Scheme(5)
False
sage: X = Spec(QQ)
sage: is_Scheme(X)
True
"""
return isinstance(x, Scheme)
class Scheme(Parent):
r"""
The base class for all schemes.
INPUT:
- ``X`` -- a scheme, scheme morphism, commutative ring,
commutative ring morphism, or ``None`` (optional). Determines
the base scheme. If a commutative ring is passed, the spectrum
of the ring will be used as base.
- ``category`` -- the category (optional). Will be automatically
constructed by default.
EXAMPLES::
sage: from sage.schemes.generic.scheme import Scheme
sage: Scheme(ZZ)
<sage.schemes.generic.scheme.Scheme_with_category object at ...>
A scheme is in the category of all schemes over its base::
sage: ProjectiveSpace(4, QQ).category()
Category of schemes over Rational Field
There is a special and unique `Spec(\ZZ)` that is the default base
scheme::
sage: Spec(ZZ).base_scheme() is Spec(QQ).base_scheme()
True
"""
def __init__(self, X=None, category=None):
"""
Construct a scheme.
TESTS:
The full test suite works since :trac:`7946`::
sage: R.<x, y> = QQ[]
sage: I = (x^2 - y^2)*R
sage: RmodI = R.quotient(I)
sage: X = Spec(RmodI)
sage: TestSuite(X).run()
"""
from sage.schemes.generic.morphism import is_SchemeMorphism
from sage.categories.map import Map
from sage.categories.rings import Rings
if X is None:
self._base_ring = ZZ
elif is_Scheme(X):
self._base_scheme = X
elif is_SchemeMorphism(X):
self._base_morphism = X
elif X in CommutativeRings():
self._base_ring = X
elif isinstance(X, Map) and X.category_for().is_subcategory(Rings()):
# X is a morphism of Rings
self._base_ring = X.codomain()
else:
raise ValueError('The base must be define by a scheme, '
'scheme morphism, or commutative ring.')
from sage.categories.schemes import Schemes
if X is None:
default_category = Schemes()
else:
default_category = Schemes(self.base_scheme())
if category is None:
category = default_category
else:
assert category.is_subcategory(default_category), \
"%s is not a subcategory of %s" % (category, default_category)
Parent.__init__(self, self.base_ring(), category=category)
def union(self, X):
"""
Return the disjoint union of the schemes ``self`` and ``X``.
EXAMPLES::
sage: S = Spec(QQ)
sage: X = AffineSpace(1, QQ)
sage: S.union(X)
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
__add__ = union
def _morphism(self, *args, **kwds):
"""
Construct a morphism determined by action on points of ``self``.
EXAMPLES::
sage: X = Spec(QQ)
sage: X._morphism()
Traceback (most recent call last):
...
NotImplementedError
TESTS:
This shows that issue at :trac:`7389` is solved::
sage: S = Spec(ZZ)
sage: f = S.identity_morphism()
sage: from sage.schemes.generic.glue import GluedScheme
sage: T = GluedScheme(f,f)
sage: S.hom([1],T)
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
def base_extend(self, Y):
"""
Extend the base of the scheme.
Derived classes must override this method.
EXAMPLES::
sage: from sage.schemes.generic.scheme import Scheme
sage: X = Scheme(ZZ)
sage: X.base_scheme()
Spectrum of Integer Ring
sage: X.base_extend(QQ)
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
def __call__(self, *args):
"""
Call syntax for schemes.
INPUT/OUTPUT:
The arguments must be one of the following:
- a ring or a scheme `S`. Output will be the set `X(S)` of
`S`-valued points on `X`.
- If `S` is a list or tuple or just the coordinates, return a
point in `X(T)`, where `T` is the base scheme of self.
EXAMPLES::
sage: A = AffineSpace(2, QQ)
We create some point sets::
sage: A(QQ)
Set of rational points of Affine Space of dimension 2 over Rational Field
sage: A(RR)
Set of rational points of Affine Space of dimension 2 over Real Field
with 53 bits of precision
Space of dimension 2 over Rational Field::
sage: R.<x> = PolynomialRing(QQ)
sage: A(NumberField(x^2+1, 'a'))
Set of rational points of Affine Space of dimension 2 over Number Field
in a with defining polynomial x^2 + 1
sage: A(GF(7))
Traceback (most recent call last):
...
ValueError: There must be a natural map S --> R, but
S = Rational Field and R = Finite Field of size 7
We create some points::
sage: A(QQ)([1, 0])
(1, 0)
We create the same point by giving the coordinates of the point
directly::
sage: A(1, 0)
(1, 0)
Check that :trac:`16832` is fixed::
sage: P.<x,y,z> = ProjectiveSpace(ZZ, 2)
sage: X=P.subscheme(x^2 - y^2)
sage: X(P([4, 4, 1]))
(4 : 4 : 1)
"""
if len(args) == 1:
from sage.schemes.generic.morphism import SchemeMorphism_point
S = args[0]
if S in CommutativeRings():
return self.point_homset(S)
elif is_Scheme(S):
return S.Hom(self)
elif isinstance(S, (list, tuple)):
args = S
elif isinstance(S, SchemeMorphism_point):
if S.codomain() is self:
return S
args = S
return self.point(args)
@cached_method
def point_homset(self, S=None):
"""
Return the set of S-valued points of this scheme.
INPUT:
- ``S`` -- a commutative ring.
OUTPUT:
The set of morphisms `Spec(S)\to X`.
EXAMPLES::
sage: P = ProjectiveSpace(ZZ, 3)
sage: P.point_homset(ZZ)
Set of rational points of Projective Space of dimension 3 over Integer Ring
sage: P.point_homset(QQ)
Set of rational points of Projective Space of dimension 3 over Rational Field
sage: P.point_homset(GF(11))
Set of rational points of Projective Space of dimension 3 over
Finite Field of size 11
TESTS::
sage: P = ProjectiveSpace(QQ,3)
sage: P.point_homset(GF(11))
Traceback (most recent call last):
...
ValueError: There must be a natural map S --> R, but
S = Rational Field and R = Finite Field of size 11
"""
if S is None:
S = self.base_ring()
SpecS = AffineScheme(S, self.base_ring())
from sage.schemes.generic.homset import SchemeHomset
return SchemeHomset(SpecS, self, as_point_homset=True)
def point(self, v, check=True):
"""
Create a point.
INPUT:
- ``v`` -- anything that defines a point
- ``check`` -- boolean (optional, default: ``True``); whether
to check the defining data for consistency
OUTPUT:
A point of the scheme.
EXAMPLES::
sage: A2 = AffineSpace(QQ,2)
sage: A2.point([4,5])
(4, 5)
sage: R.<t> = PolynomialRing(QQ)
sage: E = EllipticCurve([t + 1, t, t, 0, 0])
sage: E.point([0, 0])
(0 : 0 : 1)
"""
# todo: update elliptic curve stuff to take point_homset as argument
from sage.schemes.elliptic_curves.ell_generic import is_EllipticCurve
if is_EllipticCurve(self):
try:
return self._point(self.point_homset(), v, check=check)
except AttributeError: # legacy code without point_homset
return self._point(self, v, check=check)
return self.point_homset()(v, check=check)
def _point(self):
"""
Return the Hom-set from some affine scheme to ``self``.
OUTPUT:
A scheme Hom-set, see :mod:`~sage.schemes.generic.homset`.
EXAMPLES::
sage: X = Spec(QQ)
sage: X._point()
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
def _point_homset(self, *args, **kwds):
"""
Return the Hom-set from ``self`` to another scheme.
EXAMPLES::
sage: from sage.schemes.generic.scheme import Scheme
sage: X = Scheme(QQ)
sage: X._point_homset()
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
def __truediv__(self, Y):
"""
Return the base extension of self to Y.
See :meth:`base_extend` for details.
EXAMPLES::
sage: A = AffineSpace(3, ZZ)
sage: A
Affine Space of dimension 3 over Integer Ring
sage: A/QQ
Affine Space of dimension 3 over Rational Field
sage: A/GF(7)
Affine Space of dimension 3 over Finite Field of size 7
"""
return self.base_extend(Y)
def base_ring(self):
"""
Return the base ring of the scheme self.
OUTPUT:
A commutative ring.
EXAMPLES::
sage: A = AffineSpace(4, QQ)
sage: A.base_ring()
Rational Field
sage: X = Spec(QQ)
sage: X.base_ring()
Integer Ring
"""
try:
return self._base_ring
except AttributeError:
if hasattr(self, '_base_morphism'):
self._base_ring = self._base_morphism.codomain().coordinate_ring()
elif hasattr(self, '_base_scheme'):
self._base_ring = self._base_scheme.coordinate_ring()
else:
self._base_ring = ZZ
return self._base_ring
def base_scheme(self):
"""
Return the base scheme.
OUTPUT:
A scheme.
EXAMPLES::
sage: A = AffineSpace(4, QQ)
sage: A.base_scheme()
Spectrum of Rational Field
sage: X = Spec(QQ)
sage: X.base_scheme()
Spectrum of Integer Ring
"""
try:
return self._base_scheme
except AttributeError:
if hasattr(self, '_base_morphism'):
self._base_scheme = self._base_morphism.codomain()
elif hasattr(self, '_base_ring'):
self._base_scheme = AffineScheme(self._base_ring)
else:
from sage.schemes.generic.spec import SpecZ
self._base_scheme = SpecZ
return self._base_scheme
def base_morphism(self):
"""
Return the structure morphism from ``self`` to its base
scheme.
OUTPUT:
A scheme morphism.
EXAMPLES::
sage: A = AffineSpace(4, QQ)
sage: A.base_morphism()
Scheme morphism:
From: Affine Space of dimension 4 over Rational Field
To: Spectrum of Rational Field
Defn: Structure map
sage: X = Spec(QQ)
sage: X.base_morphism()
Scheme morphism:
From: Spectrum of Rational Field
To: Spectrum of Integer Ring
Defn: Structure map
"""
try:
return self._base_morphism
except AttributeError:
from sage.categories.schemes import Schemes
from sage.schemes.generic.spec import SpecZ
SCH = Schemes()
if hasattr(self, '_base_scheme'):
self._base_morphism = self.Hom(self._base_scheme, category=SCH).natural_map()
elif hasattr(self, '_base_ring'):
self._base_morphism = self.Hom(AffineScheme(self._base_ring), category=SCH).natural_map()
else:
self._base_morphism = self.Hom(SpecZ, category=SCH).natural_map()
return self._base_morphism
structure_morphism = base_morphism
def coordinate_ring(self):
"""
Return the coordinate ring.
OUTPUT:
The global coordinate ring of this scheme, if
defined. Otherwise raise a ``ValueError``.
EXAMPLES::
sage: R.<x, y> = QQ[]
sage: I = (x^2 - y^2)*R
sage: X = Spec(R.quotient(I))
sage: X.coordinate_ring()
Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 - y^2)
"""
try:
return self._coordinate_ring
except AttributeError:
raise ValueError("This scheme has no associated coordinated ring (defined).")
def dimension_absolute(self):
"""
Return the absolute dimension of this scheme.
OUTPUT:
Integer.
EXAMPLES::
sage: R.<x, y> = QQ[]
sage: I = (x^2 - y^2)*R
sage: X = Spec(R.quotient(I))
sage: X.dimension_absolute()
Traceback (most recent call last):
...
NotImplementedError
sage: X.dimension()
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError # override in derived class
dimension = dimension_absolute
def dimension_relative(self):
"""
Return the relative dimension of this scheme over its base.
OUTPUT:
Integer.
EXAMPLES::
sage: R.<x, y> = QQ[]
sage: I = (x^2 - y^2)*R
sage: X = Spec(R.quotient(I))
sage: X.dimension_relative()
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError # override in derived class
def identity_morphism(self):
"""
Return the identity morphism.
OUTPUT:
The identity morphism of the scheme ``self``.
EXAMPLES::
sage: X = Spec(QQ)
sage: X.identity_morphism()
Scheme endomorphism of Spectrum of Rational Field
Defn: Identity map
"""
from sage.schemes.generic.morphism import SchemeMorphism_id
return SchemeMorphism_id(self)
def hom(self, x, Y=None, check=True):
"""
Return the scheme morphism from ``self`` to ``Y`` defined by ``x``.
INPUT:
- ``x`` -- anything that determines a scheme morphism; if
``x`` is a scheme, try to determine a natural map to ``x``
- ``Y`` -- the codomain scheme (optional); if ``Y`` is not
given, try to determine ``Y`` from context
- ``check`` -- boolean (optional, default: ``True``); whether
to check the defining data for consistency
OUTPUT:
The scheme morphism from ``self`` to ``Y`` defined by ``x``.
EXAMPLES::
sage: P = ProjectiveSpace(ZZ, 3)
sage: P.hom(Spec(ZZ))
Scheme morphism:
From: Projective Space of dimension 3 over Integer Ring
To: Spectrum of Integer Ring
Defn: Structure map
"""
if Y is None:
if is_Scheme(x):
return self.Hom(x).natural_map()
else:
raise TypeError("unable to determine codomain")
return self.Hom(Y)(x, check=check)
def _Hom_(self, Y, category=None, check=True):
"""
Return the set of scheme morphisms from ``self`` to ``Y``.
INPUT:
- ``Y`` -- a scheme; the codomain of the Hom-set
- ``category`` -- a category (optional); the category of the
Hom-set
- ``check`` -- boolean (optional, default: ``True``); whether
to check the defining data for consistency.
OUTPUT:
The set of morphisms from ``self`` to ``Y``.
EXAMPLES::
sage: P = ProjectiveSpace(ZZ, 3)
sage: S = Spec(ZZ)
sage: S._Hom_(P)
Set of morphisms
From: Spectrum of Integer Ring
To: Projective Space of dimension 3 over Integer Ring
TESTS::
sage: S._Hom_(P).__class__
<class 'sage.schemes.generic.homset.SchemeHomset_generic_with_category'>
sage: E = EllipticCurve('37a1')
sage: Hom(E, E).__class__
<class 'sage.schemes.projective.projective_homset.SchemeHomset_polynomial_projective_space_with_category'>
sage: Hom(Spec(ZZ), Spec(ZZ)).__class__
<class 'sage.schemes.generic.homset.SchemeHomset_generic_with_category_with_equality_by_id'>
"""
from sage.schemes.generic.homset import SchemeHomset
return SchemeHomset(self, Y, category=category, check=check)
point_set = point_homset
def count_points(self, n):
r"""
Count points over finite fields.
INPUT:
- ``n`` -- integer.
OUTPUT:
An integer. The number of points over `\GF{q}, \ldots,
\GF{q^n}` on a scheme over a finite field `\GF{q}`.
EXAMPLES::
sage: P.<x> = PolynomialRing(GF(3))
sage: C = HyperellipticCurve(x^3+x^2+1)
sage: C.count_points(4)
[6, 12, 18, 96]
sage: C.base_extend(GF(9,'a')).count_points(2)
[12, 96]
::
sage: P.<x,y,z> = ProjectiveSpace(GF(4,'t'), 2)
sage: X = P.subscheme([y^2*z - x^3 - z^3])
sage: X.count_points(2)
[5, 17]
"""
F = self.base_ring()
if not F.is_finite():
raise TypeError("Point counting only defined for schemes over finite fields")
a = [len(self.rational_points())]
for i in range(2, n+1):
F1, psi = F.extension(i, map=True)
S1 = self.change_ring(psi)
a.append(len(S1.rational_points()))
return a
def zeta_function(self):
r"""
Compute the zeta function of a generic scheme.
Derived classes should override this method.
OUTPUT: rational function in one variable.
EXAMPLES::
sage: P.<x,y,z> = ProjectiveSpace(GF(4,'t'), 2)
sage: X = P.subscheme([y^2*z - x^3 - z^3])
sage: X.zeta_function()
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
def zeta_series(self, n, t):
"""
Return the zeta series.
Compute a power series approximation to the zeta function of a
scheme over a finite field.
INPUT:
- ``n`` -- the number of terms of the power series to compute
- ``t`` -- the variable which the series should be returned
OUTPUT:
A power series approximating the zeta function of ``self``
EXAMPLES::
sage: P.<x> = PolynomialRing(GF(3))
sage: C = HyperellipticCurve(x^3+x^2+1)
sage: R.<t> = PowerSeriesRing(Integers())
sage: C.zeta_series(4,t)
1 + 6*t + 24*t^2 + 78*t^3 + 240*t^4 + O(t^5)
sage: (1+2*t+3*t^2)/(1-t)/(1-3*t) + O(t^5)
1 + 6*t + 24*t^2 + 78*t^3 + 240*t^4 + O(t^5)
If the scheme has a method ``zeta_function``, this is used to
provide the required approximation.
Otherwise this function depends on ``count_points``, which is only
defined for prime order fields for general schemes.
Nonetheless, since :trac:`15108` and :trac:`15148`, it supports
hyperelliptic curves over non-prime fields::
sage: C.base_extend(GF(9,'a')).zeta_series(4,t)
1 + 12*t + 120*t^2 + 1092*t^3 + 9840*t^4 + O(t^5)
::
sage: P.<x,y,z> = ProjectiveSpace(GF(4,'t'), 2)
sage: X = P.subscheme([y^2*z - x^3 - z^3])
sage: R.<t> = PowerSeriesRing(Integers())
sage: X.zeta_series(2,t)
1 + 5*t + 21*t^2 + O(t^3)
TESTS::
sage: P.<x> = PolynomialRing(ZZ)
sage: C = HyperellipticCurve(x^3+x+1)
sage: R.<t> = PowerSeriesRing(Integers())
sage: C.zeta_series(4,t)
Traceback (most recent call last):
...
TypeError: zeta functions only defined for schemes
over finite fields
"""
F = self.base_ring()
if not F.is_finite():
raise TypeError('zeta functions only defined for schemes over finite fields')
R = t.parent()
u = t.O(n + 1)
try:
return self.zeta_function()(u)
except (AttributeError, NotImplementedError):
pass
try:
a = self.count_points(n)
except AttributeError:
raise NotImplementedError('count_points() required but not implemented')
temp = R.sum(a[i - 1] * u**i / i for i in range(1, n + 1))
return temp.exp()
def is_AffineScheme(x):
"""
Return True if `x` is an affine scheme.
EXAMPLES::
sage: from sage.schemes.generic.scheme import is_AffineScheme
sage: is_AffineScheme(5)
False
sage: E = Spec(QQ)
sage: is_AffineScheme(E)
True
"""
return isinstance(x, AffineScheme)
class AffineScheme(UniqueRepresentation, Scheme):
"""
Class for general affine schemes.
TESTS::
sage: from sage.schemes.generic.scheme import AffineScheme
sage: A = QQ['t']
sage: X_abs = AffineScheme(A); X_abs
Spectrum of Univariate Polynomial Ring in t over Rational Field
sage: X_rel = AffineScheme(A, QQ); X_rel
Spectrum of Univariate Polynomial Ring in t over Rational Field
sage: X_abs == X_rel
False
sage: X_abs.base_ring()
Integer Ring
sage: X_rel.base_ring()
Rational Field
.. SEEALSO::
For affine spaces over a base ring and subschemes thereof, see
:class:`sage.schemes.generic.algebraic_scheme.AffineSpace`.
"""
def __init__(self, R, S=None, category=None):
"""
Construct the affine scheme with coordinate ring `R`.
INPUT:
- ``R`` -- commutative ring
- ``S`` -- (optional) commutative ring admitting a natural map
to ``R``
OUTPUT:
The spectrum of `R`, i.e. the unique affine scheme with
coordinate ring `R` as a scheme over the base ring `S`.
EXAMPLES::
sage: from sage.schemes.generic.scheme import AffineScheme
sage: A.<x, y> = PolynomialRing(QQ)
sage: X = AffineScheme(A, QQ)
sage: X
Spectrum of Multivariate Polynomial Ring in x, y over Rational Field
sage: X.category()
Category of schemes over Rational Field
The standard way to construct an affine scheme is to use the
:func:`~sage.schemes.generic.spec.Spec` functor::
sage: S = Spec(ZZ)
sage: S
Spectrum of Integer Ring
sage: S.category()
Category of schemes
sage: type(S)
<class 'sage.schemes.generic.scheme.AffineScheme_with_category'>
"""
if R not in CommutativeRings():
raise TypeError("R (={}) must be a commutative ring".format(R))
self.__R = R
if S is not None:
if S not in CommutativeRings():
raise TypeError("S (={}) must be a commutative ring".format(S))
if not R.has_coerce_map_from(S):
raise ValueError("There must be a natural map S --> R, but S = {} and R = {}".format(S, R))
Scheme.__init__(self, S, category=category)
def __setstate__(self, state):
"""
Needed to unpickle old Spec objects.
The name-mangled attribute ``__R`` used to be in a class
called ``Spec``; we have to translate this mangled name.
TESTS::
sage: S = Spec(QQ)
sage: loads(dumps(S))
Spectrum of Rational Field
"""
if '_Spec__R' in state:
state['_AffineScheme__R'] = state.pop('_Spec__R')
super().__setstate__(state)
def _repr_(self):
"""
Return a string representation of ``self``.
OUTPUT:
A string.
EXAMPLES::
sage: Spec(PolynomialRing(QQ, 3, 'x'))
Spectrum of Multivariate Polynomial Ring in x0, x1, x2 over Rational Field
TESTS::
sage: Spec(PolynomialRing(QQ, 3, 'x'))._repr_()
'Spectrum of Multivariate Polynomial Ring in x0, x1, x2 over Rational Field'
"""
return "Spectrum of {}".format(self.__R)
def _latex_(self):
r"""
Return a LaTeX representation of ``self``.
OUTPUT:
A string.
EXAMPLES::
sage: S = Spec(PolynomialRing(ZZ, 2, 'x'))
sage: S
Spectrum of Multivariate Polynomial Ring in x0, x1 over Integer Ring
sage: S._latex_()
'\\mathrm{Spec}(\\Bold{Z}[x_{0}, x_{1}])'
"""
return "\\mathrm{{Spec}}({})".format(self.__R._latex_())
def __call__(self, *args):
"""
Construct a scheme-valued or topological point of ``self``.
INPUT/OUTPUT:
The argument ``x`` must be one of the following:
- a prime ideal of the coordinate ring; the output will
be the corresponding point of `X`
- a ring or a scheme `S`; the output will be the set `X(S)` of
`S`-valued points on `X`
EXAMPLES::
sage: S = Spec(ZZ)
sage: P = S(ZZ.ideal(3)); P
Point on Spectrum of Integer Ring defined by the Principal ideal (3) of Integer Ring
sage: type(P)
<class 'sage.schemes.generic.scheme.AffineScheme_with_category.element_class'>
sage: S(ZZ.ideal(next_prime(1000000)))
Point on Spectrum of Integer Ring defined by the Principal ideal (1000003) of Integer Ring
sage: R.<x, y, z> = QQ[]
sage: S = Spec(R)
sage: P = S(R.ideal(x, y, z)); P
Point on Spectrum of Multivariate Polynomial Ring
in x, y, z over Rational Field defined by the Ideal (x, y, z)
of Multivariate Polynomial Ring in x, y, z over Rational Field
This indicates the fix of :trac:`12734`::
sage: S = Spec(ZZ)
sage: S(ZZ)
Set of rational points of Spectrum of Integer Ring
Note the difference between the previous example and the
following one::
sage: S(S)
Set of morphisms
From: Spectrum of Integer Ring
To: Spectrum of Integer Ring
For affine or projective varieties, passing the correct number
of elements of the base ring constructs the rational point
with these elements as coordinates::
sage: S = AffineSpace(ZZ, 1)
sage: S(0)
(0)
To prevent confusion with this usage, topological points must
be constructed by explicitly specifying a prime ideal, not
just generators::
sage: R = S.coordinate_ring()
sage: S(R.ideal(0))
Point on Affine Space of dimension 1 over Integer Ring defined by the Ideal (0) of Multivariate Polynomial Ring in x over Integer Ring
This explains why the following example raises an error rather
than constructing the topological point defined by the prime
ideal `(0)` as one might expect::
sage: S = Spec(ZZ)
sage: S(0)
Traceback (most recent call last):
...
TypeError: cannot call Spectrum of Integer Ring with arguments (0,)
"""
if len(args) == 1:
x = args[0]
if ((isinstance(x, self.element_class) and (x.parent() is self or x.parent() == self))
or (is_Ideal(x) and x.ring() is self.coordinate_ring())):
# Construct a topological point from x.
return self._element_constructor_(x)
try:
# Construct a scheme homset or a scheme-valued point from
# args using the generic Scheme.__call__() method.
return super().__call__(*args)
except NotImplementedError:
# This arises from self._morphism() not being implemented.
# We must convert it into a TypeError to keep the coercion
# system working.
raise TypeError('cannot call %s with arguments %s' % (self, args))
Element = SchemeTopologicalPoint_prime_ideal
def _element_constructor_(self, x):
"""
Construct a topological point from `x`.
TESTS::
sage: S = Spec(ZZ)
sage: S(ZZ.ideal(0))
Point on Spectrum of Integer Ring defined by the Principal ideal (0) of Integer Ring
"""
if isinstance(x, self.element_class):
if x.parent() is self:
return x
elif x.parent() == self:
return self.element_class(self, x.prime_ideal())
elif is_Ideal(x) and x.ring() is self.coordinate_ring():
return self.element_class(self, x)
raise TypeError('cannot convert %s to a topological point of %s' % (x, self))
def _an_element_(self):
r"""
Return an element of the spectrum of the ring.
OUTPUT:
A point of the affine scheme ``self``.
EXAMPLES::
sage: Spec(QQ).an_element()
Point on Spectrum of Rational Field defined by the Principal ideal (0) of Rational Field
sage: Spec(ZZ).an_element() # random output
Point on Spectrum of Integer Ring defined by the Principal ideal (811) of Integer Ring
"""
if self.coordinate_ring() is ZZ:
from sage.arith.misc import random_prime
return self(ZZ.ideal(random_prime(1000)))
return self(self.coordinate_ring().zero_ideal())
def coordinate_ring(self):
"""
Return the underlying ring of this scheme.
OUTPUT:
A commutative ring.
EXAMPLES::
sage: Spec(QQ).coordinate_ring()
Rational Field
sage: Spec(PolynomialRing(QQ, 3, 'x')).coordinate_ring()
Multivariate Polynomial Ring in x0, x1, x2 over Rational Field
"""
return self.__R
def is_noetherian(self):
"""
Return ``True`` if ``self`` is Noetherian, ``False`` otherwise.
EXAMPLES::
sage: Spec(ZZ).is_noetherian()
True
"""
return self.__R.is_noetherian()
def dimension_absolute(self):
"""
Return the absolute dimension of this scheme.
OUTPUT:
Integer.
EXAMPLES::
sage: S = Spec(ZZ)
sage: S.dimension_absolute()
1
sage: S.dimension()
1
"""
return self.__R.krull_dimension()
dimension = dimension_absolute
def dimension_relative(self):
"""
Return the relative dimension of this scheme over its base.
OUTPUT:
Integer.
EXAMPLES::
sage: S = Spec(ZZ)
sage: S.dimension_relative()
0
"""
return self.__R.krull_dimension() - self.base_ring().krull_dimension()
def base_extend(self, R):
"""
Extend the base ring/scheme.
INPUT:
- ``R`` -- an affine scheme or a commutative ring
EXAMPLES::
sage: Spec_ZZ = Spec(ZZ); Spec_ZZ
Spectrum of Integer Ring
sage: Spec_ZZ.base_extend(QQ)
Spectrum of Rational Field
sage: Spec(ZZ['x']).base_extend(Spec(QQ))
Spectrum of Univariate Polynomial Ring in x over Rational Field
"""
if R in CommutativeRings():
return AffineScheme(self.coordinate_ring().base_extend(R), self.base_ring())
if not self.base_scheme() == R.base_scheme():
raise ValueError('the new base scheme must be a scheme over the old base scheme')
return AffineScheme(self.coordinate_ring().base_extend(R.coordinate_ring()),
self.base_ring())
def _point_homset(self, *args, **kwds):
"""
Construct a point Hom-set.
For internal use only. See :mod:`morphism` for more details.
EXAMPLES::
sage: Spec(QQ)._point_homset(Spec(QQ), Spec(ZZ))
Set of rational points of Spectrum of Integer Ring
"""
from sage.schemes.affine.affine_homset import SchemeHomset_points_spec
return SchemeHomset_points_spec(*args, **kwds)
def hom(self, x, Y=None):
r"""
Return the scheme morphism from ``self`` to ``Y`` defined by ``x``.
INPUT:
- ``x`` -- anything that determines a scheme morphism; if
``x`` is a scheme, try to determine a natural map to ``x``
- ``Y`` -- the codomain scheme (optional); if ``Y`` is not
given, try to determine ``Y`` from context
- ``check`` -- boolean (optional, default: ``True``); whether
to check the defining data for consistency
OUTPUT:
The scheme morphism from ``self`` to ``Y`` defined by ``x``.
EXAMPLES:
We construct the inclusion from `\mathrm{Spec}(\QQ)` into
`\mathrm{Spec}(\ZZ)` induced by the inclusion from `\ZZ` into
`\QQ`::
sage: X = Spec(QQ)
sage: X.hom(ZZ.hom(QQ))
Affine Scheme morphism:
From: Spectrum of Rational Field
To: Spectrum of Integer Ring
Defn: Natural morphism:
From: Integer Ring
To: Rational Field
TESTS:
We can construct a morphism to an affine curve (:trac:`7956`)::
sage: S.<p,q> = QQ[]
sage: A1.<r> = AffineSpace(QQ,1)
sage: A1_emb = Curve(p-2)
sage: A1.hom([2,r],A1_emb)
Scheme morphism:
From: Affine Space of dimension 1 over Rational Field
To: Affine Plane Curve over Rational Field defined by p - 2
Defn: Defined on coordinates by sending (r) to
(2, r)
"""
from sage.categories.map import Map
from sage.categories.rings import Rings
if is_Scheme(x):
return self.Hom(x).natural_map()
if Y is None and isinstance(x, Map) and x.category_for().is_subcategory(Rings()):
# x is a morphism of Rings
Y = AffineScheme(x.domain())
return Scheme.hom(self, x, Y) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/generic/scheme.py | 0.915642 | 0.51879 | scheme.py | pypi |
from sage.categories.functor import Functor
from sage.rings.integer_ring import ZZ
from sage.schemes.generic.scheme import AffineScheme
from sage.structure.unique_representation import UniqueRepresentation
def Spec(R, S=None):
r"""
Apply the Spec functor to `R`.
INPUT:
- ``R`` -- either a commutative ring or a ring homomorphism
- ``S`` -- a commutative ring (optional), the base ring
OUTPUT:
- ``AffineScheme`` -- the affine scheme `\mathrm{Spec}(R)`
EXAMPLES::
sage: Spec(QQ)
Spectrum of Rational Field
sage: Spec(PolynomialRing(QQ, 'x'))
Spectrum of Univariate Polynomial Ring in x over Rational Field
sage: Spec(PolynomialRing(QQ, 'x', 3))
Spectrum of Multivariate Polynomial Ring in x0, x1, x2 over Rational Field
sage: X = Spec(PolynomialRing(GF(49,'a'), 3, 'x')); X
Spectrum of Multivariate Polynomial Ring in x0, x1, x2 over Finite Field in a of size 7^2
sage: TestSuite(X).run()
Applying ``Spec`` twice to the same ring gives identical output
(see :trac:`17008`)::
sage: A = Spec(ZZ); B = Spec(ZZ)
sage: A is B
True
A ``TypeError`` is raised if the input is not a commutative ring::
sage: Spec(5)
Traceback (most recent call last):
...
TypeError: x (=5) is not in Category of commutative rings
sage: Spec(FreeAlgebra(QQ,2, 'x'))
Traceback (most recent call last):
...
TypeError: x (=Free Algebra on 2 generators (x0, x1) over Rational Field) is not in Category of commutative rings
TESTS::
sage: X = Spec(ZZ)
sage: X
Spectrum of Integer Ring
sage: X.base_scheme()
Spectrum of Integer Ring
sage: X.base_ring()
Integer Ring
sage: X.dimension()
1
sage: Spec(QQ,QQ).base_scheme()
Spectrum of Rational Field
sage: Spec(RDF,QQ).base_scheme()
Spectrum of Rational Field
"""
return SpecFunctor(S)(R)
class SpecFunctor(Functor, UniqueRepresentation):
"""
The Spec functor.
"""
def __init__(self, base_ring=None):
"""
EXAMPLES::
sage: from sage.schemes.generic.spec import SpecFunctor
sage: SpecFunctor()
Spec functor from Category of commutative rings to Category of schemes
sage: SpecFunctor(QQ)
Spec functor from Category of commutative rings to
Category of schemes over Rational Field
"""
from sage.categories.all import CommutativeRings, Schemes
if base_ring is None:
domain = CommutativeRings()
codomain = Schemes()
elif base_ring in CommutativeRings():
# We would like to use CommutativeAlgebras(base_ring) as
# the domain; we use CommutativeRings() instead because
# currently many algebras are not yet considered to be in
# CommutativeAlgebras(base_ring) by the category framework.
domain = CommutativeRings()
codomain = Schemes(AffineScheme(base_ring))
else:
raise TypeError('base (= {}) must be a commutative ring'.format(base_ring))
self._base_ring = base_ring
super().__init__(domain, codomain)
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: from sage.schemes.generic.spec import SpecFunctor
sage: SpecFunctor(QQ)
Spec functor from Category of commutative rings to
Category of schemes over Rational Field
"""
return 'Spec functor from {} to {}'.format(self.domain(), self.codomain())
def _latex_(self):
r"""
Return a LaTeX representation of ``self``.
EXAMPLES::
sage: from sage.schemes.generic.spec import SpecFunctor
sage: latex(SpecFunctor())
\mathrm{Spec}\colon \mathbf{CommutativeRings} \longrightarrow \mathbf{Schemes}
"""
return r'\mathrm{{Spec}}\colon {} \longrightarrow {}'.format(
self.domain()._latex_(), self.codomain()._latex_())
def _apply_functor(self, A):
"""
Apply the Spec functor to the commutative ring ``A``.
EXAMPLES::
sage: from sage.schemes.generic.spec import SpecFunctor
sage: F = SpecFunctor()
sage: F(RR) # indirect doctest
Spectrum of Real Field with 53 bits of precision
"""
# The second argument of AffineScheme defaults to None.
# However, AffineScheme has unique representation, so there is
# a difference between calling it with or without explicitly
# giving this argument.
if self._base_ring is None:
return AffineScheme(A)
return AffineScheme(A, self._base_ring)
def _apply_functor_to_morphism(self, f):
"""
Apply the Spec functor to the ring homomorphism ``f``.
EXAMPLES::
sage: from sage.schemes.generic.spec import SpecFunctor
sage: F = SpecFunctor(GF(7))
sage: A.<x, y> = GF(7)[]
sage: B.<t> = GF(7)[]
sage: f = A.hom((t^2, t^3))
sage: Spec(f) # indirect doctest
Affine Scheme morphism:
From: Spectrum of Univariate Polynomial Ring in t over Finite Field of size 7
To: Spectrum of Multivariate Polynomial Ring in x, y over Finite Field of size 7
Defn: Ring morphism:
From: Multivariate Polynomial Ring in x, y over Finite Field of size 7
To: Univariate Polynomial Ring in t over Finite Field of size 7
Defn: x |--> t^2
y |--> t^3
"""
A = f.domain()
B = f.codomain()
return self(B).hom(f, self(A))
SpecZ = Spec(ZZ)
# Compatibility with older versions of this module
from sage.misc.persist import register_unpickle_override
register_unpickle_override('sage.schemes.generic.spec', 'Spec', AffineScheme) | /sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/schemes/generic/spec.py | 0.929911 | 0.475971 | spec.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.