コード例 #1
0
 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.ProjectiveCurve_generic.__init__(self, PP, F)
     R = PP.base_ring()
     if names == None:
         names = ["x", "y"]
     elif isinstance(names, str):
         names = names.split(",")
     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
コード例 #2
0
 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))
コード例 #3
0
 def __init__(self, X, S):
     R = X.base_ring()
     SchemeHomset_generic.__init__(self, spec.Spec(S, R), X)
     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
コード例 #4
0
 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
コード例 #5
0
ファイル: ggh.py プロジェクト: ahrussell/mmap
    def __init__(self, params, asym=False):

        (self.n, self.q, sigma, self.sigma_prime, self.k) = params

        S, x = PolynomialRing(ZZ, 'x').objgen()
        self.R = S.quotient_ring(S.ideal(x**self.n + 1))

        Sq = PolynomialRing(Zmod(self.q), 'x')
        self.Rq = Sq.quotient_ring(Sq.ideal(x**self.n + 1))

        # draw z_is uniformly from Rq and compute its inverse in Rq
        if asym:
            z = [self.Rq.random_element() for i in range(self.k)]
            self.zinv = [z_i**(-1) for z_i in z]
        else:  # or do symmetric version
            z = self.Rq.random_element()
            zinv = z**(-1)
            z, self.zinv = zip(*[(z, zinv) for i in range(self.k)])

        # set up some discrete Gaussians
        DGSL_sigma = DGSL(ZZ**self.n, sigma)
        self.D_sigma = lambda: self.Rq(list(DGSL_sigma()))

        # discrete Gaussian in ZZ^n with stddev sigma_prime, yields random level-0 encodings
        DGSL_sigmap_ZZ = DGSL(ZZ**self.n, self.sigma_prime)
        self.D_sigmap_ZZ = lambda: self.Rq(list(DGSL_sigmap_ZZ()))

        # draw g repeatedly from a Gaussian distribution of Z^n (with param sigma)
        # until g^(-1) in QQ[x]/<x^n + 1> is small (< n^2)
        Sk = PolynomialRing(QQ, 'x')
        K = Sk.quotient_ring(Sk.ideal(x**self.n + 1))
        while True:
            l = self.D_sigma()
            ginv_K = K(mod_near_poly(l, self.q))**(-1)
            ginv_size = vector(ginv_K).norm()

            if ginv_size < self.n**2:
                g = self.Rq(l)
                self.ginv = g**(-1)
                break

        # discrete Gaussian in I = <g>, yields random encodings of 0
        short_g = vector(ZZ, mod_near_poly(g, self.q))
        DGSL_sigmap_I = DGSL(short_g, self.sigma_prime)
        self.D_sigmap_I = lambda: self.Rq(list(DGSL_sigmap_I()))

        # compute zero-testing parameter p_zt
        # randomly draw h (in Rq) from a discrete Gaussian with param q^(1/2)
        self.h = self.Rq(list(DGSL(ZZ**self.n, round(sqrt(self.q)))()))

        # create p_zt
        self.p_zt = self.ginv * self.h * prod(z)
コード例 #6
0
ファイル: velu.py プロジェクト: vojtechsu/isogenies
def velu(kernel, domain=None):
    E = kernel[0].curve()
    Q = PolynomialRing(E.base_field(), ['x', 'y'])
    x, y = Q.gens()
    X = x
    Y = y
    R = []
    v = 0
    w = 0

    for P in kernel:

        g_x = 3 * P[0]**2 + E.a4()
        g_y = -2 * P[1]
        u_P = g_y**2
        if 2 * P == E(0, 1, 0):
            R.append(P)
            v_P = g_x
        else:
            if not -P in R:
                R.append(P)
                v_P = 2 * g_x
            else:
                continue

        v += v_P
        w += (u_P + P[0] * v_P)
        X += (v_P / (x - P[0]) + u_P / (x - P[0])**2)
        Y -= (2 * u_P * y / (x - P[0])**3 + v_P * (y - P[1]) / (x - P[0])**2 -
              g_x * g_y / (x - P[0])**2)

    a = E.a4() - 5 * v
    b = E.a6() - 7 * w
    if domain != None:
        try:

            a = domain.base_field()(a)
            b = domain.base_field()(b)
            codomain = EllipticCurve(domain.base_field(), [a, b])
            R = PolynomialRing(E.base_field(), ['x', 'y'])
            Rf = R.fraction_field()
            X = Rf(X)
            Y = Rf(Y)
            f = standard_form((X, Y), domain)
        except:

            codomain = EllipticCurve(E.base_field(), [a, b])
            f = standard_form((X, Y), E)
    else:
        codomain = EllipticCurve(E.base_field(), [a, b])
        f = standard_form((X, Y), E)
    return codomain, f
コード例 #7
0
def _check_muqt(mu, q, t, pi=None):
    """
    EXAMPLES::

        sage: from sage.combinat.sf.ns_macdonald import _check_muqt
        sage: P, q, t, n, R, x = _check_muqt([0,0,1],None,None)
        sage: P
        Fraction Field of Multivariate Polynomial Ring in q, t over Rational Field
        sage: q
        q
        sage: t
        t
        sage: n
        Nonattacking fillings of [0, 0, 1]
        sage: R
        Multivariate Polynomial Ring in x0, x1, x2 over Fraction Field of Multivariate Polynomial Ring in q, t over Rational Field
        sage: x
        (x0, x1, x2)

    ::

        sage: q,t = var('q,t')
        sage: P, q, t, n, R, x = _check_muqt([0,0,1],q,None)
        Traceback (most recent call last):
        ...
        ValueError: you must specify either both q and t or neither of them

    ::

        sage: P, q, t, n, R, x = _check_muqt([0,0,1],q,2)
        Traceback (most recent call last):
        ...
        ValueError: the parents of q and t must be the same
    """
    if q is None and t is None:
        P = PolynomialRing(QQ, 'q,t').fraction_field()
        q, t = P.gens()
    elif q is not None and t is not None:
        if q.parent() != t.parent():
            raise ValueError("the parents of q and t must be the same")
        P = q.parent()
    else:
        raise ValueError(
            "you must specify either both q and t or neither of them")
    n = NonattackingFillings(mu, pi)
    R = PolynomialRing(P, len(n._shape), 'x')
    x = R.gens()
    return P, q, t, n, R, x
コード例 #8
0
    def __init__(self, R, n, q=None):
        """
        TESTS::
        
            sage: HeckeAlgebraSymmetricGroupT(QQ, 3)
            Hecke algebra of the symmetric group of order 3 on the T basis over Univariate Polynomial Ring in q over Rational Field
        
        ::
        
            sage: HeckeAlgebraSymmetricGroupT(QQ, 3, q=1)
            Hecke algebra of the symmetric group of order 3 with q=1 on the T basis over Rational Field
        """
        self.n = n
        self._basis_keys = permutation.Permutations(n)
        self._name = "Hecke algebra of the symmetric group of order %s"%self.n
        self._one = permutation.Permutation(range(1,n+1))

        if q is None:
            q = PolynomialRing(R, 'q').gen()
            R = q.parent()
        else:
            if q not in R:
                raise ValueError, "q must be in R (= %s)"%R
            self._name += " with q=%s"%q

        self._q = q
        
        CombinatorialAlgebra.__init__(self, R)
        # _repr_ customization: output the basis element indexed by [1,2,3] as [1,2,3]
        self.print_options(prefix="")
コード例 #9
0
ファイル: lfsr.py プロジェクト: ye-man/sage
def lfsr_connection_polynomial(s):
    """
    INPUT:

    - ``s`` -- a sequence of elements of a finite field of even length

    OUTPUT:

    - ``C(x)`` -- the connection polynomial of the minimal LFSR.

    This implements the algorithm in section 3 of J. L. Massey's article
    [Mas1969]_.

    EXAMPLES::

        sage: F = GF(2)
        sage: F
        Finite Field of size 2
        sage: o = F(0); l = F(1)
        sage: key = [l,o,o,l]; fill = [l,l,o,l]; n = 20
        sage: s = lfsr_sequence(key,fill,n); s
        [1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0]
        sage: lfsr_connection_polynomial(s)
        x^4 + x + 1
        sage: from sage.matrix.berlekamp_massey import berlekamp_massey
        sage: berlekamp_massey(s)
        x^4 + x^3 + 1

    Notice that ``berlekamp_massey`` returns the reverse of the connection
    polynomial (and is potentially must faster than this implementation).
    """
    # Initialization:
    FF = s[0].base_ring()
    R = PolynomialRing(FF, "x")
    x = R.gen()
    C = R(1); B = R(1); m = 1; b = FF(1); L = 0; N = 0

    while N < len(s):
        if L > 0:
            r = min(L+1,C.degree()+1)
            d = s[N] + sum([(C.list())[i]*s[N-i] for i in range(1,r)])
        if L == 0:
            d = s[N]
        if d == 0:
            m += 1
            N += 1
        if d > 0:
            if 2*L > N:
                C = C - d*b**(-1)*x**m*B
                m += 1
                N += 1
            else:
                T = C
                C = C - d*b**(-1)*x**m*B
                L = N + 1 - L
                m = 1
                b = d
                B = T
                N += 1
    return C
コード例 #10
0
ファイル: integrals.py プロジェクト: fchapoton/darmonpoints
def get_basic_integral(G, cocycle, gamma, center, j, prec=None):
    p = G.p
    HOC = cocycle.parent()
    V = HOC.coefficient_module()

    if prec is None:
        prec = V.precision_cap()
    Cp = Qp(p, prec)
    verbose('precision = %s' % prec)
    R = PolynomialRing(Cp, names='t')
    PS = PowerSeriesRing(Cp, names='z')
    t = R.gen()
    z = PS.gen()

    if prec is None:
        prec = V.precision_cap()
    try:
        coeff_depth = V.precision_cap()
    except AttributeError:
        coeff_depth = V.coefficient_module().precision_cap()
    resadd = ZZ(0)
    edgelist = G.get_covering(1)[1:]
    for rev, h in edgelist:
        a, b, c, d = [Cp(o) for o in G.embed(h, prec).list()]
        try:
            c0val = 0
            pol = PS(d * z + b) / PS(c * z + a)
            pol -= Cp.teichmuller(center)
            pol = pol**j
            pol = pol.polynomial()
            newgamma = G.Gpn(
                G.reduce_in_amalgam(h * gamma.quaternion_rep,
                                    return_word=False))
            if rev:  # DEBUG
                newgamma = newgamma.conjugate_by(G.wp())
                print 'reversing'
            if G.use_shapiro():
                mu_e = cocycle.evaluate_and_identity(newgamma)
            else:
                mu_e = cocycle.evaluate(newgamma)
            if newgamma.quaternion_rep != 1:
                print 'newgamma = ', newgamma
        except AttributeError:
            verbose('...')
            continue
        if HOC._use_ps_dists:
            tmp = sum(a * mu_e.moment(i)
                      for a, i in izip(pol.coefficients(), pol.exponents())
                      if i < len(mu_e._moments))
        else:
            tmp = mu_e.evaluate_at_poly(pol, Cp, coeff_depth)
        resadd += tmp
        try:
            if G.use_shapiro():
                tmp = cocycle.get_liftee().evaluate_and_identity(newgamma)
            else:
                tmp = cocycle.get_liftee().evaluate(newgamma)
        except IndexError:
            pass
    return resadd
コード例 #11
0
def compute_tau0(v0,gamma,wD,return_exact = False):
    r'''
    INPUT:

     - v0: F -> its localization at p
     - gamma: the image of wD (the generator for an order of F) under an optimal embedding

    OUTPUT:

     The element tau_0 such that gamma * [tau_0,1] = wD * [tau_0,1]

    '''
    R = PolynomialRing(QQ,names = 'X')
    X = R.gen()
    F = v0.domain()
    Cp = v0.codomain()
    assert wD.minpoly() == gamma.minpoly()
    a,b,c,d = gamma.list()
    tau0_vec = (c*X**2+(d-a)*X-b).roots(F)
    tau0 = v0(tau0_vec[0][0])
    idx = 0
    if c * tau0 + d != v0(wD):
        tau0 = v0(tau0_vec[1][0])
        idx = 1
    return tau0_vec[idx][0] if return_exact == True else tau0
コード例 #12
0
ファイル: hgm.py プロジェクト: edgarcosta/amortizedHGM
def padic_gauss_sum(a,
                    p,
                    f,
                    prec=20,
                    factored=False,
                    algorithm='pari',
                    parent=None):
    # Copied from Sage
    from sage.rings.padics.factory import Zp
    from sage.rings.all import PolynomialRing

    q = p**f
    a = a % (q - 1)
    if parent is None:
        R = Zp(p, prec)
    else:
        R = parent
    out = -R.one()
    if a != 0:
        t = R(1 / (q - 1))
        for i in range(f):
            out *= (a * t).gamma(algorithm)
            a = (a * p) % (q - 1)
    s = sum(a.digits(base=p))
    if factored:
        return (s, out)
    X = PolynomialRing(R, name='X').gen()
    pi = R.ext(X**(p - 1) + p, names='pi').gen()
    out *= pi**s
    return out
コード例 #13
0
    def coordinate_ring(self):
        """
        Return the coordinate ring of this scheme.

        EXAMPLES::

            sage: ProjectiveSpace(3, GF(19^2,'alpha'), 'abcd').coordinate_ring()
            Multivariate Polynomial Ring in a, b, c, d over Finite Field in alpha of size 19^2

        ::

            sage: ProjectiveSpace(3).coordinate_ring()
            Multivariate Polynomial Ring in x0, x1, x2, x3 over Integer Ring

        ::

            sage: ProjectiveSpace(2, QQ, ['alpha', 'beta', 'gamma']).coordinate_ring()
            Multivariate Polynomial Ring in alpha, beta, gamma over Rational Field
        """
        try:
            return self._coordinate_ring
        except AttributeError:
            self._coordinate_ring = PolynomialRing(
                self.base_ring(), self.variable_names(),
                self.dimension_relative() + 1)
            return self._coordinate_ring
コード例 #14
0
ファイル: supersingular.py プロジェクト: vojtechsu/isogenies
def is_supersingular(E):
    p = E.base_field().characteristic()
    j = E.j_invariant()
    if not j in GF(p**2):
        return False
    if p <= 3:
        return j == 0
    F = ClassicalModularPolynomialDatabase()[2]
    x = PolynomialRing(GF(p**2), 'x').gen()
    f = F(x, j)
    roots = [i[0] for i in f.roots() for _ in range(i[1])]
    if len(roots) < 3:
        return False
    vertices = [j, j, j]
    m = floor(log(p, 2)) + 1
    for k in range(1, m + 1):
        for i in range(3):
            f = F(x, roots[i])
            g = x - vertices[i]
            a = f.quo_rem(g)[0]
            vertices[i] = roots[i]
            attempt = a.roots()
            if len(attempt) == 0:
                return False
            roots[i] = attempt[0][0]
    return True
コード例 #15
0
ファイル: invariants.py プロジェクト: sajedel/testsage
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 [M]_:
    `(f g)_k = \frac{(m - k)! (n - k)!}{m! n!} \left(
    \frac{\del f}{\del x} \frac{\del g}{\del y} -
    \frac{\del f}{\del y} \frac{\del g}{\del 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
コード例 #16
0
ファイル: invariants.py プロジェクト: sajedel/testsage
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
コード例 #17
0
    def generator_relations(self, K):
        """
        An ideal `I` in a polynomial ring `R` over `K`, such that the
        associated ring is `R / I` surjects onto the ring of modular forms
        with coefficients in `K`.
        
        INPUT:
            - `K` -- A ring.
            
        OUTPUT:
            An ideal in a polynomial ring.
        
        TESTS::
            sage: from psage.modform.fourier_expansion_framework.modularforms.modularform_testtype import *
            sage: t = ModularFormTestType_scalar()
            sage: t.generator_relations(QQ)
            Ideal (g1^2 - g2, g1^3 - g3, g1^4 - g4, g1^5 - g5) of Multivariate Polynomial Ring in g1, g2, g3, g4, g5 over Rational Field
        """
        if K.has_coerce_map_from(ZZ):
            R = PolynomialRing(K, self._generator_names(K))
            g1 = R.gen(0)
            return R.ideal([
                g1**i - g
                for (i, g) in list(enumerate([None] + list(R.gens())))[2:]
            ])

        raise NotImplementedError
コード例 #18
0
ファイル: ell_local_data.py プロジェクト: ozzie00/sage
        def _pcubicroots(b, c, d):
            r"""
            Local function returning the number of roots of `x^3 +
            b*x^2 + c*x + d` modulo `P`, counting multiplicities
            """

            return sum([rr[1] for rr in PolynomialRing(F, 'x')([F(d), F(c), F(b), F(1)]).roots()],0)
コード例 #19
0
    def generator_relations(self, K):
        """
        An ideal `I` in a polynomial ring `R` over `K`, such that the
        associated ring is `R / I` surjects onto the ring of modular forms
        with coefficients in `K`.
        
        INPUT:
            - `K` -- A ring.
            
        OUTPUT:
            An ideal in a polynomial ring.
        
        TESTS::
            sage: from psage.modform.fourier_expansion_framework.modularforms.modularform_testtype import *
            sage: t = ModularFormTestType_vectorvalued()
            sage: t.generator_relations(QQ)
            Ideal (g1^2 - g2, g1^3 - g3, g1^4 - g4, g1^5 - g5) of Multivariate Polynomial Ring in g1, g2, g3, g4, g5, v1, v2, v3 over Rational Field
        """
        if K.has_coerce_map_from(ZZ):
            R = PolynomialRing(
                K,
                self.non_vector_valued()._generator_names(K) +
                self._generator_names(K))
            return R.ideal().parent()(
                self.non_vector_valued().generator_relations(K))

        raise NotImplementedError
コード例 #20
0
    def frobenius(self, P=None):
        """
        Returns 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)
コード例 #21
0
ファイル: schubert_polynomial.py プロジェクト: biasse/sage
    def expand(self):
        """
        EXAMPLES::

            sage: X = SchubertPolynomialRing(ZZ)
            sage: X([2,1,3]).expand()
            x0
            sage: map(lambda x: x.expand(), [X(p) for p in Permutations(3)])
            [1, x0 + x1, x0, x0*x1, x0^2, x0^2*x1]

        TESTS: Calling .expand() should always return an element of an
        MPolynomialRing

        ::

            sage: X = SchubertPolynomialRing(ZZ)
            sage: f = X([1]); f
            X[1]
            sage: type(f.expand())
            <type 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomial_libsingular'>
            sage: f.expand()
            1
            sage: f = X([1,2])
            sage: type(f.expand())
            <type 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomial_libsingular'>
            sage: f = X([1,3,2,4])
            sage: type(f.expand())
            <type 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomial_libsingular'>
        """
        p = symmetrica.t_SCHUBERT_POLYNOM(self)
        if not is_MPolynomial(p):
            R = PolynomialRing(self.parent().base_ring(), 1, 'x')
            p = R(p)
        return p
コード例 #22
0
    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)

        Note: if even degree model, just returns local coordinate above one point

        AUTHOR:
            - Jennifer Balakrishnan (2007-12)
        """
        g = self.genus()
        pol = self.hyperelliptic_polynomials()[0]
        K = LaurentSeriesRing(self.base_ring(), name)
        t = K.gen()
        K.set_default_prec(prec + 2)
        L = PolynomialRing(K, 'x')
        x = L.gen()
        i = 0
        w = (x**g / t)**2 - pol
        wprime = w.derivative(x)
        if pol.degree() == 2 * g + 1:
            x = t**-2
        else:
            x = t**-1
        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))
コード例 #23
0
ファイル: lie.py プロジェクト: shrutig/sage
    def _sage_(self):
        """
        EXAMPLES:
            sage: m = lie('[[1,0,3,3],[12,4,-4,7],[-1,9,8,0],[3,-5,-2,9]]') # optional - lie
            sage: m.sage()  # optional - lie
            [ 1  0  3  3]
            [12  4 -4  7]
            [-1  9  8  0]
            [ 3 -5 -2  9]

        """
        t = self.type()
        if t == 'grp':
            raise ValueError, "cannot convert Lie groups to native Sage objects"
        elif t == 'mat':
            import sage.matrix.constructor
            return  sage.matrix.constructor.matrix( eval( str(self).replace('\n','').strip())  )
        elif t == 'pol':
            import sage.misc.misc
            from sage.rings.all import PolynomialRing, QQ

            #Figure out the number of variables
            s = str(self)
            open_bracket = s.find('[')
            close_bracket = s.find(']')
            nvars = len(s[open_bracket:close_bracket].split(','))

            #create the polynomial ring
            R = PolynomialRing(QQ, nvars, 'x')
            x = R.gens()
            pol = R(0)

            #Split up the polynomials into terms
            terms = []
            for termgrp in s.split(' - '):
                #The first entry in termgrp has
                #a negative coefficient
                termgrp = "-"+termgrp.strip()
                terms += termgrp.split('+')
            #Make sure we don't accidentally add a negative
            #sign to the first monomial
            if s[0] != "-":
                terms[0] = terms[0][1:]

            #go through all the terms in s
            for term in terms:
                xpos = term.find('X')
                coef = eval(term[:xpos].strip())
                exps = eval(term[xpos+1:].strip())
                monomial = sage.misc.misc.prod(map(lambda i: x[i]**exps[i] , range(nvars)))
                pol += coef * monomial

            return pol
        elif t == 'tex':
            return repr(self)
        elif t == 'vid':
            return None
        else:
            return ExpectElement._sage_(self)
コード例 #24
0
def trace_of_frobenius_mod_2(E):
    F = E.base_field()
    x = PolynomialRing(F, 'x').gen()
    f = x ** 3 + E.a4() * x + E.a6()
    q = F.order()
    if gcd(f, power_mod(x, q, f) - x).is_constant():
        return 1
    else:
        return 0
コード例 #25
0
ファイル: special.py プロジェクト: merbst/psage
def eisenstein_basis(N, k, verbose=False):
    r"""
    Find spanning list of 'easy' generators for the subspace of
    `M_k(\Gamma_0(N))` generated by level 1 Eisenstein series and
    their images of even integer weights up to `k`.

    INPUT:
        - N -- positive integer
        - k -- positive integer
        - ``verbose`` -- bool (default: False)

    OUTPUT:
        - list of monomials in images of level 1 Eisenstein series
        - prec of q-expansions needed to determine element of
          `M_k(\Gamma_0(N))`.

    EXAMPLES::

        sage: from psage.modform.rational.special import eisenstein_basis
        sage: eisenstein_basis(5,4)
        ([E4(q^5)^1, E4(q^1)^1, E2^*(q^5)^2], 3)
        sage: eisenstein_basis(11,2,verbose=True)  # warning below because of verbose
        Warning -- not enough series.
        ([E2^*(q^11)^1], 2)
        sage: eisenstein_basis(11,2,verbose=False)
        ([E2^*(q^11)^1], 2)
    """
    assert N > 1
    if k % 2 != 0:
        return []
    # Make list E of Eisenstein series, to enough precision to
    # determine them, until we span space.
    M = ModularForms(N, k)
    prec = M.echelon_basis()[-1].valuation() + 1
    
    gens = eisenstein_gens(N, k, prec)
    R = PolynomialRing(ZZ, len(gens), ['E%sq%s'%(g[1],g[0]) for g in gens])
    z = [(R.gen(i), g[1]) for i, g in enumerate(gens)]
    m = monomials(z, k)
    
    A = QQ**prec
    V = A.zero_subspace()
    E = []
    for i, z in enumerate(m):
        d = z.degrees()
        f = prod(g[2]**d[i] for i, g in enumerate(gens) if d[i])
        v = A(f.padded_list(prec))
        if v not in V:
            V = V + A.span([v])
            w = [(gens[i][0],gens[i][1],d[i]) for i in range(len(d)) if d[i]]
            E.append(EisensteinMonomial(w))
            if V.dimension() == M.dimension():
                 return E, prec

    if verbose: print "Warning -- not enough series."
    return E, prec
コード例 #26
0
ファイル: vm_basis.py プロジェクト: ipozdnyakov/sage
def _delta_poly_modulo(N, prec=10):
    """
    Return the q-expansion of `\Delta` modulo `N`. Used internally by
    the :func:`~delta_qexp` function. See the docstring of :func:`~delta_qexp`
    for more information.

    INPUT:

    - `N` -- positive integer modulo which we want to compute `\Delta`

    - ``prec`` -- integer; the absolute precision of the output

    OUTPUT:

        the polynomial of degree ``prec``-1 which is the truncation
        of `\Delta` modulo `N`, as an element of the polynomial
        ring in `q` over the integers modulo `N`.

    EXAMPLES::

        sage: from sage.modular.modform.vm_basis import _delta_poly_modulo
        sage: _delta_poly_modulo(5, 7)
        2*q^6 + 3*q^4 + 2*q^3 + q^2 + q
        sage: _delta_poly_modulo(10, 12)
        2*q^11 + 7*q^9 + 6*q^7 + 2*q^6 + 8*q^4 + 2*q^3 + 6*q^2 + q
    """
    if prec <= 0:
        raise ValueError("prec must be positive")
    v = [0] * prec

    # Let F = \sum_{n >= 0} (-1)^n (2n+1) q^(floor(n(n+1)/2)).
    # Then delta is F^8.

    stop = int((-1 + math.sqrt(8 * prec)) / 2.0)

    for n in xrange(stop + 1):
        v[n * (n + 1) // 2] = ((N - 1) * (2 * n + 1) if (n & 1) else
                               (2 * n + 1))

    from sage.rings.all import Integers

    P = PolynomialRing(Integers(N), 'q')
    f = P(v)
    t = verbose('made series')
    # fast way of computing f*f truncated at prec
    f = f._mul_trunc_(f, prec)
    t = verbose('squared (1 of 3)', t)
    f = f._mul_trunc_(f, prec)
    t = verbose('squared (2 of 3)', t)
    f = f._mul_trunc_(f, prec - 1)
    t = verbose('squared (3 of 3)', t)
    f = f.shift(1)
    t = verbose('shifted', t)

    return f
コード例 #27
0
ファイル: integrals.py プロジェクト: fchapoton/darmonpoints
def integrate_H1(G,
                 cycle,
                 cocycle,
                 depth=1,
                 method='moments',
                 prec=None,
                 parallelize=False,
                 twist=False,
                 progress_bar=False,
                 multiplicative=True,
                 return_valuation=False):
    if prec is None:
        prec = cocycle.parent().coefficient_module().base_ring().precision_cap(
        )
    verbose('precision = %s' % prec)
    Cp = cycle.parent().coefficient_module().base_field()
    R = PolynomialRing(Cp, names='t')
    t = R.gen()
    if method == 'moments':
        integrate_H0 = integrate_H0_moments
    else:
        assert method == 'riemann'
        integrate_H0 = integrate_H0_riemann
    jj = 0
    total_integrals = cycle.size_of_support()
    verbose('Will do %s integrals' % total_integrals)
    input_vec = []
    resmul = Cp(1)
    resadd = Cp(0)
    resval = ZZ(0)
    for g, divisor in cycle.get_data():
        jj += 1
        if divisor.degree() != 0:
            raise ValueError(
                'Divisor must be of degree 0. Now it is of degree %s. And g = %s.'
                % (divisor.degree(), g.quaternion_rep))
        if twist:
            divisor = divisor.left_act_by_matrix(
                G.embed(G.wp(), prec).change_ring(Cp))
            g = g.conjugate_by(G.wp()**-1)
        newresadd, newresmul, newresval = integrate_H0(G, divisor, cocycle,
                                                       depth, g, prec, jj,
                                                       total_integrals,
                                                       progress_bar,
                                                       parallelize)
        resadd += newresadd
        resmul *= newresmul
        resval += newresval
    if not multiplicative:
        if return_valuation:
            return resadd, resval, Cp.teichmuller(resmul)
        else:
            return resadd
    else:
        return Cp.prime()**resval * Cp.teichmuller(resmul) * resadd.exp()
コード例 #28
0
ファイル: ell_local_data.py プロジェクト: ozzie00/sage
 def _pquadroots(a, b, c):
     r"""
     Local function returning True iff `ax^2 + bx + c` has roots modulo `P`
     """
     (a, b, c) = (F(a), F(b), F(c))
     if a == 0:
         return (b != 0) or (c == 0)
     elif p == 2:
         return len(PolynomialRing(F, "x")([c,b,a]).roots()) > 0
     else:
         return (b**2 - 4*a*c).is_square()
コード例 #29
0
    def root_extension_field(self):
        r"""
        Return the extension field of the base field of (the parent of)
        ``self`` in which the corresponding fixed points of ``self`` lie.

        The variable name of the corresponding generator is ``e``.
        It corresponds to ``e=sqrt(D)``, where ``D`` is the discriminant of ``self``.
        If the extension degree is ``1`` then the base field is returned.

        The correct embedding is the positive resp. positive imaginary one.
        Unfortunately no default embedding can be specified for relative
        number fields yet.

        EXAMPLES::

            sage: from sage.modular.modform_hecketriangle.hecke_triangle_groups import HeckeTriangleGroup
            sage: G = HeckeTriangleGroup(n=infinity)
            sage: G.V(3).root_extension_field()
            Number Field in e with defining polynomial x^2 - 32
            sage: G.T().root_extension_field() == G.base_field()
            True
            sage: (G.S()).root_extension_field()
            Number Field in e with defining polynomial x^2 + 4

            sage: G = HeckeTriangleGroup(n=7)
            sage: G.V(3).root_extension_field()
            Number Field in e with defining polynomial x^2 - 4*lam^2 - 4*lam + 4 over its base field
            sage: G.V(1).root_extension_field() == G.base_field()
            True
            sage: G.U().root_extension_field()
            Number Field in e with defining polynomial x^2 - lam^2 + 4 over its base field
        """

        K = self.parent().base_field()
        x = PolynomialRing(K, 'x').gen()
        D = self.discriminant()

        if D.is_square():
            return K
        else:
            # unfortunately we can't set embeddings for relative extensions :-(
            # return K.extension(x**2 - D, 'e', embedding=AA(D).sqrt())

            L = K.extension(x**2 - D, 'e')

            #e = AA(D).sqrt()
            #emb = L.hom([e])
            #L._unset_embedding()
            #L.register_embedding(emb)

            #return NumberField(L.absolute_polynomial(), 'e', structure=AbsoluteFromRelative(L), embedding=(???))
            return L
コード例 #30
0
    def rational_period_functions(self, k, D):
        r"""
        Return a list of basic rational period functions of weight ``k`` for discriminant ``D``.
        The list is expected to be a generating set for all rational period functions of the
        given weight and discriminant (unknown).

        The method assumes that ``D > 0``.
        Also see the element method `rational_period_function` for more information.

        - ``k`` -- An even integer, the desired weight of the rational period functions.

        - ``D`` -- An element of the base ring corresponding
                   to a valid discriminant.

        EXAMPLES::

            sage: from sage.modular.modform_hecketriangle.hecke_triangle_groups import HeckeTriangleGroup
            sage: G = HeckeTriangleGroup(n=4)
            sage: sorted(G.rational_period_functions(k=4, D=12))
            [(z^4 - 1)/z^4]
            sage: sorted(G.rational_period_functions(k=-2, D=12))
            [-z^2 + 1, 4*lam*z^2 - 4*lam]
            sage: sorted(G.rational_period_functions(k=2, D=14))
            [(24*z^6 - 120*z^4 + 120*z^2 - 24)/(9*z^8 - 80*z^6 + 146*z^4 - 80*z^2 + 9),
             (24*z^6 - 120*z^4 + 120*z^2 - 24)/(9*z^8 - 80*z^6 + 146*z^4 - 80*z^2 + 9),
             1/z,
             (z^2 - 1)/z^2]
            sage: sorted(G.rational_period_functions(k=-4, D=14))
            [-16*z^4 + 16, -z^4 + 1, 16*z^4 - 16]
        """
        try:
            k = ZZ(k)
            if not ZZ(2).divides(k):
                raise TypeError
        except TypeError:
            raise ValueError("k={} has to be an even integer!".format(k))

        z = PolynomialRing(self.base_ring(), 'z').gen()

        R = []
        if k != 0:
            R.append(ZZ(1) - z**(-k))
        if k == 2:
            R.append(z**(-1))

        L = self.class_representatives(D=D, primitive=True)
        for v in L:
            rat = v.rational_period_function(k)
            if rat != 0:
                R.append(rat)

        return R