def fractional_CRT_split(residues, ps_roots, K, BI_coordinates = None):
    if K is QQ:
        return fractional_CRT_QQ(residues, ps_roots);

    OK = K.ring_of_integers();
    BOK = OK.basis();

    residues_ZZ = [ r.lift() for r in residues];
    primes = [p for p, _ in ps_roots];
    lift = CRT_list(residues_ZZ, primes);
    lift_coordinates = OK.coordinates(lift);

    if BI_coordinates is None:
        p_ideals = [ OK.ideal(p, K.gen() - root) for p, root in ps_roots ];
        I = prod(p_ideals);
        BI = I.basis(); # basis as a ZZ-module
        BI_coordinates = [ OK.coordinates(b) for b in BI ];

    M = Matrix(Integers(), [ [ kronecker_delta(i,j) for j,_ in enumerate(BOK) ] + [ lift_coordinates[i] ] + [ b[i] for b in BI_coordinates ] for i in range(len(BOK)) ])
    # v = short_vector
    Kernel_Basis =  Matrix(Integers(), M.transpose().kernel().basis())
    v =Kernel_Basis.LLL()[0];
    #print v[:len(BOK)]
    if v[len(BOK)] == 0:
        return 0;
    return (-1/v[len(BOK)]) * sum( v[i] * b for i, b in enumerate(BOK));
Example #2
0
def polynomial_conjugacy_class_matcher_fn(input):
    """ Given an input of the form
        [{"RootOf":["0","1"], "ConjugacyClass":3}, {"RootOf":["-7","1"], "ConjugacyClass":4}]
        returns a function that
            - takes an argument alpha
            - matches alpha as a root to one of the 'RootsOf'
            - returns the value in the corresponding 'ConjugacyClass'
    """
    P = PolynomialRing(Integers(), "x")
    fn_cc_pairs = []
    for d in input:
        pol = P([Integer(int_val) for int_val in d["RootOf"]])
        fn_cc_pairs.append((pol, d["ConjugacyClass"]))

    def polynomial_conjugacy_class_matcher(alpha):
        """
        A function that has an internal list of pairs (pol, return_val). Given alpha, finds the pol that it is a root of and returns
        the associated return_val
        """
        for pol_fn, conjugacy_class_index in fn_cc_pairs:
            if pol_fn(alpha) == 0:
                return conjugacy_class_index
        raise AssertionError("alpha = %s is supposed to be root of one of %s" %
                             (alpha, input))

    return polynomial_conjugacy_class_matcher
Example #3
0
def congruence_groups_between_gamma0_and_gamma1(N):
    """
    INPUT:
        
    - N - an integer
    
    OUTPUT:
        
    - The set of all congruence subgroups contained in Gamma0(N) that contain Gamma1(N)
    
    EXAMPLES::

        sage: from mdsage import *
        sage: congruence_groups_between_gamma0_and_gamma1(1)
        {Modular Group SL(2,Z)}
    
        sage: congruence_groups_between_gamma0_and_gamma1(15)
        {Congruence Subgroup Gamma_H(15) with H generated by [14],
         Congruence Subgroup Gamma_H(15) with H generated by [4, 11, 14],
         Congruence Subgroup Gamma0(15)}
    """
    if N == 1:
        return set([Gamma0(1)])
    level_N_modular_groups = set([])
    for gens in generators_of_subgroups_of_unit_group(Integers(N)):
        gens = gens+[-1]
        H = sage.modular.arithgroup.congroup_gammaH._list_subgroup(N,gens)
        G = GammaH(N,H)
        level_N_modular_groups.add(G)
    return level_N_modular_groups
Example #4
0
def order(g, p):
    """
	Compute multiplicative order of g mod p.
	"""
    from sage.all import Integers

    R = Integers(p)
    return R(g).multiplicative_order()
Example #5
0
class WebSmallDirichletGroup(WebDirichletGroup):
    def _compute(self):
        if self.modlabel:
            self.modulus = m = int(self.modlabel)
            self.H = Integers(m).unit_group()
        self.codelangs = ('pari', 'sage')

    @lazy_attribute
    def contents(self):
        return None

    @lazy_attribute
    def gens(self):
        return self.H.gens_values()

    @lazy_attribute
    def generators(self):
        return self.textuple([str(v) for v in self.H.gens_values()])
Example #6
0
def kernel_lattice(A, mod=None):
    ''' Lattice of vectors x with Ax = 0 (potentially mod m) '''
    A = matrix(ZZ if mod is None else Integers(mod), A)
    L = [vector(ZZ, row) for row in A.right_kernel().basis()]
    if mod is not None:
        cols = len(L[0])
        for i in range(cols):
            L.append([0]*i + [mod] + [0]*(cols-i-1))
    return matrix(L)
Example #7
0
 def first_chars(self):
     if self.modulus == 1:
         return [1]
     r = []
     for i,c in enumerate(Integers(self.modulus).list_of_elements_of_multiplicative_group()):
         r.append(c)
         if i > self.maxrows:
             self.rowtruncate = True
             break
     return r
Example #8
0
class WebSmallDirichletGroup(WebDirichletGroup):
    def _compute(self):
        if self.modlabel:
            self.modulus = m = int(self.modlabel)
            self.H = Integers(m).unit_group()
        self.credit = 'SageMath'
        self.codelangs = ('pari', 'sage')

    @property
    def contents(self):
        return None

    @property
    def gens(self):
        return self.H.gens_values()

    @property
    def generators(self):
        return self.textuple(map(str, self.H.gens_values()))
Example #9
0
class WebSmallDirichletGroup(WebDirichletGroup):

    def _compute(self):
        if self.modlabel:
            self.modulus = m = int(self.modlabel)
            self.H = Integers(m).unit_group()
        self.credit = 'SageMath'
        self.codelangs = ('pari', 'sage')

    @property
    def contents(self):
        return None

    @property
    def gens(self):
        return self.H.gens_values()

    @property
    def generators(self):
        return self.textuple(map(str, self.H.gens_values()))
Example #10
0
    def dbd(self, d):
        """
        Return matrix of <d>.

        INPUT:

            - `d` -- integer

        OUTPUT:

            - a matrix modulo 2

        EXAMPLES::

            sage: from mdsage import *
            sage: C = KamiennyCriterion(29)
            sage: C.dbd(2)
            22 x 22 dense matrix over Finite Field of size 2 (use the '.str()' method to see the entries)
            sage: C.dbd(2)^14==1
            True
            sage: C.dbd(2)[0]
            (0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1)
        """
        d=ZZ(d)
        if self.verbose: tm = cputime(); mem = get_memory_usage(); print("dbd start")
        try: return self._dbd[d % self.p]
        except AttributeError: pass
        # Find generators of the integers modulo p:
        gens = Integers(self.p).unit_gens()
        orders = [g.multiplicative_order() for g in gens]
        # Compute corresponding <z> operator on integral cuspidal modular symbols
        
        X = [self.M.diamond_bracket_operator(z).matrix() for z in gens]
        if self.verbose: print("time and mem", cputime(tm), get_memory_usage(mem), "create d")
        X = [x.restrict(self.S_integral, check=False) for x in X]
        if self.verbose: print("time and mem", cputime(tm), get_memory_usage(mem), "restrict d")
        
        X = [matrix_modp(x) for x in X]
        if self.verbose: print("time and mem", cputime(tm), get_memory_usage(mem), "mod d")
        # Take combinations to make list self._dbd of all dbd's such that
        # self._dbd[d] = <d>
        from itertools import product
        v = [None] * self.p
        for ei in product(*[list(range(i)) for i in orders]):
            di = prod(g**e for e,g in zip(ei,gens)).lift()
            m = prod(g**e for e,g in zip(ei,X))
            v[di] = m
        if self.verbose: print("time and mem", cputime(tm), get_memory_usage(mem), "mul")

        assert v.count(None) == (self.p-euler_phi(self.p))
        self._dbd = v
        if self.verbose: print("time and mem", cputime(tm), get_memory_usage(mem), "bdb finnished")
        return v[d % self.p]
Example #11
0
def alpha_res_fn(data):
    powers = data["Powers"]
    P = PolynomialRing(Integers(), "x")
    gamma_polynomial = P(data["Resolvent"])

    def alpha_res(roots, p):
        """ Computes invariant alpha in the 'RES' case
        """
        return sum(
            gamma_polynomial(r) * powers_sum(r, powers, p) for r in roots)

    return alpha_res
Example #12
0
def get_character_modulus(a, b, limit=7):
    """ this function is also used by lfunctions/LfunctionPlot.py """
    headers = list(range(1, limit))
    headers.append("more")
    entries = {}
    rows = list(range(a, b + 1))
    for row in rows:
        if row != 1:
            G = Integers(row).list_of_elements_of_multiplicative_group()
        else:
            G = [1]
        for chi_n in G:
            chi = ConreyCharacter(row, chi_n)
            multorder = chi.multiplicative_order()
            if multorder <= limit:
                el = chi
                col = multorder
                entry = entries.get((row, col), [])
                entry.append(el)
                entries[(row, col)] = entry
    entries2 = {}
    out = lambda chi: (chi.number, chi.is_primitive(),
                       chi.multiplicative_order(), chi.is_even())
    for k, v in entries.items():
        l = []
        v = sorted(v, key=lambda x: x.number)
        while v:
            e1 = v.pop(0)
            e1_num = e1.number
            inv_num = 1 if e1_num == 1 else e1_num.inverse_mod(e1.modulus)

            inv = ConreyCharacter(e1.modulus, inv_num)

            if e1_num == inv_num:
                l.append((out(e1), ))
            else:
                l.append((out(e1), out(inv)))
                v = [
                    x for x in v
                    if (x.modulus, x.number) != (inv.modulus, inv.number)
                ]
        if k[1] == "more":
            l = sorted(l, key=lambda e: e[0][2])
        entries2[k] = l
    cols = headers
    return headers, entries2, rows, cols
Example #13
0
def endomorphism_frob(f):
    r"""
    INPUT:

    -   ``f`` -- a Frobenius polynomial of an Abelian variety

    OUTPUT: A tuple:
            - dim_Q ( End(A^{al} )
            - k, the degree of field ext where all endomorphism are defined
            - a sorted list that represents the geometric isogeny decomposition
              over an algebraic closure.
              Let
                    A^{al} = (A_1)^n_1 x ... x (A_k)^n_t
              and write
                    det(1 - T Frob^k | H^1(Ai^n_i)) = c_i (T)^m_i.
              Then we return:
                    [ (m_i, m_i * deg(c_i), c_i) for i in range(1, t) ].

    """
    if f(0) != 1:
        f = f.reverse()
    assert f(0) == 1
    g = f.degree() / 2
    flist = f.list()
    q = Integers()(flist[-1]).nth_root(g)

    T = f.parent().gen()

    fof = tensor_charpoly(f, f)
    g = fof.change_ring(Rationals())(T / q)

    dimtotal = 0
    fieldext = 1

    for factor, power in g.factor():
        iscyclo = factor.is_cyclotomic(certificate=True)
        if iscyclo > 0:
            dimtotal += power * factor.degree()
            fieldext = LCM(fieldext, iscyclo)

    fext = power_charpoly(f, fieldext)

    endo = sorted([(power, power * factor.degree(), factor)
                   for factor, power in fext.factor()])

    return dimtotal, fieldext, endo
Example #14
0
def cuspidal_rational_subgroup_mod_rational_cuspidal_subgroup(G):
    """On input a congruence subgroup G that contains Gamma1(N) checks whether there are cuspsums that are not equivalent to a cuspsum defined over `\QQ` but that are equivalent to a divisor defined over `\QQ`.
    
    INPUT:
    
    - G - a congruence subgroup
    
    OUTPUT:
    
    - the invariants of the cuspidal rational subgroup divided out by the rational cuspidal subgroup 
    
    EXAMPLES::
        
        sage: from mdsage import *
        sage: cuspidal_rational_subgroup_mod_rational_cuspidal_subgroup(Gamma1(26))
        ()
    """
    if G.genus() == 0:
        return tuple()

    N = G.level()
    ZZcusp = ZZ**G.ncusps()
    unit_gens = Integers(N).unit_gens()
    L, D = modular_unit_lattice(G)
    Lrat, Drat = rational_modular_unit_lattice(G)
    DmodL = D.quotient(L)
    #DmodLrat=Drat.quotient(Lrat)
    kernels = []
    for g in unit_gens:
        m = Matrix([
            ZZcusp.gen(G.cusps().index(G.reduce_cusp(galois_action(c, g, N))))
            for c in G.cusps()
        ])
        f = DmodL.hom([DmodL(i.lift() * (m - 1)) for i in DmodL.gens()])
        kernels.append(f.kernel())
        #print kernels[-1]
    rat_cusp_tors = reduce(intersection, kernels)
    return rat_cusp_tors.V().quotient(Drat + L).invariants()
Example #15
0
    def coset_representatives_H(self):
        """
        Return representatives of Z/NZ^*/H where H is a subgroup of the
        diamond operators and N is the level. H=Z/NZ^* for Gamma0 and H=1 
        for Gamma1

        EXAMPLES::

            sage: from mdsage import *
            sage: C = KamiennyCriterion(GammaH(31,[3^5]))
            sage: C.coset_representatives_H()
            (1, 2, 3, 4, 8)
            sage: C = KamiennyCriterion(13)
        """
        G = self.congruence_group
        coset_reps = []
        done = set([])
        for i in Integers(self.p):
            if not i.is_unit() or i in done:
                continue
            coset_reps.append(i)
            done.update([i*h for h in G._list_of_elements_in_H()])
        return tuple(coset_reps)
Example #16
0
def order(g, p):
    from sage.all import Integers

    R = Integers(p)
    return R(g).multiplicative_order()
Example #17
0
 def gens(self):
     return Integers(self.modulus).unit_gens()
Example #18
0
p256 = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF

# Curve parameters for the curve equation: y^2 = x^3 + a256*x +b256
a256 = p256 - 3
b256 = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B

qq = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551

# Base point (x, y)
gx = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296
gy = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5

# Create a finite field of order p256
FF = GF(p256)

Fq = Integers(qq)
# Define a curve over that field with specified Weierstrass a and b parameters
EC = EllipticCurve(FF, [a256, b256])
EC.set_order(qq)

g = EC(FF(gx), FF(gy))

r = Fq.random_element()
x_u = Fq.random_element()

X_u = x_u.lift() * g


def pad(point):
    """
    Cette méthode va prendre les coordonnées d'un point,
Example #19
0
def modular_symbols_from_curve(C, N, num_factors=3):
    """
    Find the modular symbols spaces that shoudl correspond to the
    Jacobian of the given hyperelliptic curve, up to the number of
    factors we consider.
    
    INPUT:
        - C -- a hyperelliptic curve over QQ
        - N -- a positive integer
        - num_factors -- number of Euler factors to verify match up; this is
          important, because if, e.g., there is only one factor of degree g(C), we
          don't want to just immediately conclude that Jac(C) = A_f. 
        
    OUTPUT:
        - list of all sign 1 simple modular symbols factor of level N
          that correspond to a simple modular abelian A_f
          that is isogenous to Jac(C).  

    EXAMPLES::

        sage: from psage.modform.rational.unfiled import modular_symbols_from_curve

        sage: R.<x> = ZZ[]
        sage: f = x^7+4*x^6+5*x^5+x^4-3*x^3-2*x^2+1
        sage: C1 = HyperellipticCurve(f)
        sage: modular_symbols_from_curve(C1, 284)
        [Modular Symbols subspace of dimension 3 of Modular Symbols space of dimension 39 for Gamma_0(284) of weight 2 with sign 1 over Rational Field]
        
        sage: f = x^7-7*x^5-11*x^4+5*x^3+18*x^2+4*x-11
        sage: C2 = HyperellipticCurve(f)
        sage: modular_symbols_from_curve(C2, 284)
        [Modular Symbols subspace of dimension 3 of Modular Symbols space of dimension 39 for Gamma_0(284) of weight 2 with sign 1 over Rational Field]
    """
    # We will use the Eichler-Shimura relation and David Harvey's
    # p-adic point counting hypellfrob.  Harvey's code has the
    # constraint:   p > (2*g + 1)*(2*prec - 1).
    # So, find the smallest p not dividing N that satisfies the
    # above constraint, for our given choice of prec.

    f, f2 = C.hyperelliptic_polynomials()
    if f2 != 0:
        raise NotImplementedError, "curve must be of the form y^2 = f(x)"
    if f.degree() % 2 == 0:
        raise NotImplementedError, "curve must be of the form y^2 = f(x) with f(x) odd"

    prec = 1
    
    g = C.genus()
    B = (2*g + 1)*(2*prec - 1)

    from sage.rings.all import next_prime
    p = B

    # We use that if F(X) is the characteristic polynomial of the
    # Hecke operator T_p, then X^g*F(X+p/X) is the characteristic
    # polynomial of Frob_p, because T_p = Frob_p + p/Frob_p, according
    # to Eichler-Shimura.  Use this to narrow down the factors. 

    from sage.all import ModularSymbols, Integers, get_verbose
    D = ModularSymbols(N,sign=1).cuspidal_subspace().new_subspace().decomposition()
    D = [A for A in D if A.dimension() == g]

    from sage.schemes.hyperelliptic_curves.hypellfrob import hypellfrob

    while num_factors > 0:
        p = next_prime(p)
        while N % p == 0: p = next_prime(p)
        
        R = Integers(p**prec)['X']
        X = R.gen()
        D2 = []
        # Compute the charpoly of Frobenius using hypellfrob
        M = hypellfrob(p, 1, f)
        H = R(M.charpoly())
        
        for A in D:
            F = R(A.hecke_polynomial(p))
            # Compute charpoly of Frobenius from F(X)
            G = R(F.parent()(X**g * F(X + p/X)))
            if get_verbose(): print (p, G, H)
            if G == H:
                D2.append(A)
        D = D2
        num_factors -= 1

    return D
Example #20
0
    def tobyte(bits):
        v = 0
        for i,b in enumerate(bits):
            v |= b<<i
        return v
    return bytes(tobyte(v[i*8:(i+1)*8]) for i in range(len(v)//8))

def bytes2bits(v):
    ret = []
    for byteidx,v in enumerate(v):
        for bitidx in range(8):
            ret.append((v >> bitidx) & 1)
    return ret

from sage.all import Integers, Matrix, vector
GF2=Integers(2)
def computeFMatrix(F, input_nbits):
    ret_cols = []
    for bin_ in range(input_nbits):
        in_ = [0]*NBITS
        in_[bin_] = 1
        in_ = bits2bytes(in_)
        out = F(in_)
        out = bytes2bits(out)
        ret_cols.append(out)
    return Matrix(GF2, ret_cols).transpose()
NBITS=64*8
M=computeFMatrix(F, NBITS)

print("[+] Matrix kernel")
print(M.kernel())
Example #21
0
 def _compute(self):
     if self.modlabel:
         self.modulus = m = int(self.modlabel)
         self.H = Integers(m).unit_group()
     self.codelangs = ('pari', 'sage')
Example #22
0
 def unpack_vector(s):
     return sage_vector(Integers(), map(int, s.split(",")))
Example #23
0
def QuotientRing(R, I, names=None):
    r"""
    Creates a quotient ring of the ring `R` by the twosided ideal `I`.

    Variables are labeled by ``names`` (if the quotient ring is a quotient
    of a polynomial ring).  If ``names`` isn't given, 'bar' will be appended
    to the variable names in `R`.
    
    INPUTS:

    - ``R`` - a ring.

    - ``I`` - a twosided ideal of `R`.

    - ``names`` (optional) - a list of strings to be used as names for
      the variables in the quotient ring `R/I`.
    
    OUTPUTS: `R/I` - the quotient ring `R` mod the ideal `I`
    
    ASSUMPTION:

    ``I`` has a method ``I.reduce(x)`` returning the normal form
    of elements `x\in R`. In other words, it is required that
    ``I.reduce(x)==I.reduce(y)`` `\iff x-y \in I`, and
    ``x-I.reduce(x) in I``, for all `x,y\in R`.

    EXAMPLES:

    Some simple quotient rings with the integers::
    
        sage: R = QuotientRing(ZZ,7*ZZ); R
        Quotient of Integer Ring by the ideal (7)
        sage: R.gens()
        (1,)
        sage: 1*R(3); 6*R(3); 7*R(3)
        3
        4
        0
    
    ::
    
        sage: S = QuotientRing(ZZ,ZZ.ideal(8)); S
        Quotient of Integer Ring by the ideal (8)
        sage: 2*S(4)
        0
    
    With polynomial rings: (note that the variable name of the quotient
    ring can be specified as shown below)
    
    ::
    
        sage: R.<xx> = QuotientRing(QQ[x], QQ[x].ideal(x^2 + 1)); R
        Univariate Quotient Polynomial Ring in xx over Rational Field with modulus x^2 + 1
        sage: R.gens(); R.gen()
        (xx,)
        xx
        sage: for n in range(4): xx^n
        1
        xx
        -1
        -xx
    
    ::
    
        sage: S = QuotientRing(QQ[x], QQ[x].ideal(x^2 - 2)); S
        Univariate Quotient Polynomial Ring in xbar over Rational Field with
        modulus x^2 - 2
        sage: xbar = S.gen(); S.gen()
        xbar
        sage: for n in range(3): xbar^n
        1
        xbar
        2
    
    Sage coerces objects into ideals when possible::
    
        sage: R = QuotientRing(QQ[x], x^2 + 1); R
        Univariate Quotient Polynomial Ring in xbar over Rational Field with
        modulus x^2 + 1
    
    By Noether's homomorphism theorems, the quotient of a quotient ring
    of `R` is just the quotient of `R` by the sum of the ideals. In this
    example, we end up modding out the ideal `(x)` from the ring
    `\QQ[x,y]`::
    
        sage: R.<x,y> = PolynomialRing(QQ,2)
        sage: S.<a,b> = QuotientRing(R,R.ideal(1 + y^2))
        sage: T.<c,d> = QuotientRing(S,S.ideal(a))
        sage: T
        Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x, y^2 + 1)
        sage: R.gens(); S.gens(); T.gens()
        (x, y)
        (a, b)
        (0, d)
        sage: for n in range(4): d^n
        1
        d
        -1
        -d

    TESTS:

    By trac ticket #11068, the following does not return a generic
    quotient ring but a usual quotient of the integer ring::

        sage: R = Integers(8)
        sage: I = R.ideal(2)
        sage: R.quotient(I)
        Ring of integers modulo 2

    """
    # 1. Not all rings inherit from the base class of rings.
    # 2. We want to support quotients of free algebras by homogeneous two-sided ideals.
    #if not isinstance(R, commutative_ring.CommutativeRing):
    #    raise TypeError, "R must be a commutative ring."
    from sage.all import Integers, ZZ
    if not R in Rings():
        raise TypeError, "R must be a ring."
    try:
        is_commutative = R.is_commutative()
    except (AttributeError, NotImplementedError):
        is_commutative = False
    if names is None:
        try:
            names = tuple([x + 'bar' for x in R.variable_names()])
        except ValueError:  # no names are assigned
            pass
    else:
        names = sage.structure.parent_gens.normalize_names(R.ngens(), names)
    if not isinstance(I, ideal.Ideal_generic) or I.ring() != R:
        I = R.ideal(I)
    try:
        if I.is_principal():
            return R.quotient_by_principal_ideal(I.gen(), names)
    except (AttributeError, NotImplementedError):
        pass
    if not is_commutative:
        try:
            if I.side() != 'twosided':
                raise AttributeError
        except AttributeError:
            raise TypeError, "A twosided ideal is required."
    if isinstance(R, QuotientRing_nc):
        pi = R.cover()
        S = pi.domain()
        G = [pi.lift(x) for x in I.gens()]
        I_lift = S.ideal(G)
        J = R.defining_ideal()
        if S == ZZ:
            return Integers((I_lift + J).gen())
        return R.__class__(S, I_lift + J, names=names)
    if isinstance(R, sage.rings.commutative_ring.CommutativeRing):
        return QuotientRing_generic(R, I, names)
    return QuotientRing_nc(R, I, names)
Example #24
0
def getu(p):
    if p == 2:
        return 5
    return int(Integers(p).quadratic_nonresidue())
Example #25
0
def modular_symbols_from_curve(C, N, num_factors=3):
    """
    Find the modular symbols spaces that shoudl correspond to the
    Jacobian of the given hyperelliptic curve, up to the number of
    factors we consider.
    
    INPUT:
        - C -- a hyperelliptic curve over QQ
        - N -- a positive integer
        - num_factors -- number of Euler factors to verify match up; this is
          important, because if, e.g., there is only one factor of degree g(C), we
          don't want to just immediately conclude that Jac(C) = A_f. 
        
    OUTPUT:
        - list of all sign 1 simple modular symbols factor of level N
          that correspond to a simple modular abelian A_f
          that is isogenous to Jac(C).  

    EXAMPLES::

        sage: from psage.modform.rational.unfiled import modular_symbols_from_curve

        sage: R.<x> = ZZ[]
        sage: f = x^7+4*x^6+5*x^5+x^4-3*x^3-2*x^2+1
        sage: C1 = HyperellipticCurve(f)
        sage: modular_symbols_from_curve(C1, 284)
        [Modular Symbols subspace of dimension 3 of Modular Symbols space of dimension 39 for Gamma_0(284) of weight 2 with sign 1 over Rational Field]
        
        sage: f = x^7-7*x^5-11*x^4+5*x^3+18*x^2+4*x-11
        sage: C2 = HyperellipticCurve(f)
        sage: modular_symbols_from_curve(C2, 284)
        [Modular Symbols subspace of dimension 3 of Modular Symbols space of dimension 39 for Gamma_0(284) of weight 2 with sign 1 over Rational Field]
    """
    # We will use the Eichler-Shimura relation and David Harvey's
    # p-adic point counting hypellfrob.  Harvey's code has the
    # constraint:   p > (2*g + 1)*(2*prec - 1).
    # So, find the smallest p not dividing N that satisfies the
    # above constraint, for our given choice of prec.

    f, f2 = C.hyperelliptic_polynomials()
    if f2 != 0:
        raise NotImplementedError, "curve must be of the form y^2 = f(x)"
    if f.degree() % 2 == 0:
        raise NotImplementedError, "curve must be of the form y^2 = f(x) with f(x) odd"

    prec = 1

    g = C.genus()
    B = (2 * g + 1) * (2 * prec - 1)

    from sage.rings.all import next_prime
    p = B

    # We use that if F(X) is the characteristic polynomial of the
    # Hecke operator T_p, then X^g*F(X+p/X) is the characteristic
    # polynomial of Frob_p, because T_p = Frob_p + p/Frob_p, according
    # to Eichler-Shimura.  Use this to narrow down the factors.

    from sage.all import ModularSymbols, Integers, get_verbose
    D = ModularSymbols(
        N, sign=1).cuspidal_subspace().new_subspace().decomposition()
    D = [A for A in D if A.dimension() == g]

    from sage.schemes.hyperelliptic_curves.hypellfrob import hypellfrob

    while num_factors > 0:
        p = next_prime(p)
        while N % p == 0:
            p = next_prime(p)

        R = Integers(p**prec)['X']
        X = R.gen()
        D2 = []
        # Compute the charpoly of Frobenius using hypellfrob
        M = hypellfrob(p, 1, f)
        H = R(M.charpoly())

        for A in D:
            F = R(A.hecke_polynomial(p))
            # Compute charpoly of Frobenius from F(X)
            G = R(F.parent()(X**g * F(X + p / X)))
            if get_verbose(): print(p, G, H)
            if G == H:
                D2.append(A)
        D = D2
        num_factors -= 1

    return D
Example #26
0
p256 = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF

# Curve parameters for the curve equation: y^2 = x^3 + a256*x +b256
a256 = p256 - 3
b256 = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B

qq = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551

# Base point (x, y)
gx = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296
gy = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5

# Create a finite field of order p256
FF = GF(p256)

Fq = Integers(qq)
# Define a curve over that field with specified Weierstrass a and b parameters
EC = EllipticCurve(FF, [a256, b256])
EC.set_order(qq)

g = EC(FF(gx), FF(gy))


##########################################################
##################### Methode utiles #####################
##########################################################

def pad(point):
    """
    Cette méthode va prendre les coordonnées d'un point, les mettre en
    binaire et ajouter des 0 pour avoir une taille de 256bits (512 total
Example #27
0
def sym_pol_gen(n):
    S = PolynomialRing(Integers(), 2, "a, p")
    R = PolynomialRing(S, "T")
    L = R("1 - a*T + p*T^2")
    return sym_pol(L, n).list()
set_seed(SEED + 202)
X = [random.randint(1, 1_000_000_000) for _ in range(20)]
Z = [0,]*len(X)
for i in range(len(X)):
    x = X[i]
    z = carmichael_lambda(x)
    Z[i] = int(z)
d = {"X": X, "Z": Z}
save_pickle(d, FOLDER, "carmichael_lambda.pkl")

set_seed(SEED + 203)
X = list(range(1, 257)) + [random.randint(1, 1_000_000_000) for _ in range(20)]
Z = [False,]*len(X)
for i in range(len(X)):
    x = X[i]
    z = Integers(X[i]).multiplicative_group_is_cyclic()
    Z[i] = bool(z)
d = {"X": X, "Z": Z}
save_pickle(d, FOLDER, "is_cyclic.pkl")


###############################################################################
# Prime number functions
###############################################################################

set_seed(SEED + 301)
X = [random.randint(1, 1000) for _ in range(10)]
Z = [0,]*len(X)
for i in range(len(X)):
    x = X[i]
    z = prime_range(x)  # Returns primes 0 <= p < x
Example #29
0
 def _compute(self):
     if self.modlabel:
         self.modulus = m = int(self.modlabel)
         self.H = Integers(m).unit_group()
     self.credit = 'SageMath'
     self.codelangs = ('pari', 'sage')
Example #30
0
 def _compute(self):
     if self.modlabel:
         self.modulus = m = int(self.modlabel)
         self.H = Integers(m).unit_group()
     self.credit = "Sage"
     self.codelangs = ("pari", "sage")
Example #31
0
def QuotientRing(R, I, names=None):
    r"""
    Creates a quotient ring of the ring `R` by the twosided ideal `I`.

    Variables are labeled by ``names`` (if the quotient ring is a quotient
    of a polynomial ring).  If ``names`` isn't given, 'bar' will be appended
    to the variable names in `R`.

    INPUT:

    - ``R`` -- a ring.

    - ``I`` -- a twosided ideal of `R`.

    - ``names`` -- (optional) a list of strings to be used as names for
      the variables in the quotient ring `R/I`.

    OUTPUT: `R/I` - the quotient ring `R` mod the ideal `I`

    ASSUMPTION:

    ``I`` has a method ``I.reduce(x)`` returning the normal form
    of elements `x\in R`. In other words, it is required that
    ``I.reduce(x)==I.reduce(y)`` `\iff x-y \in I`, and
    ``x-I.reduce(x) in I``, for all `x,y\in R`.

    EXAMPLES:

    Some simple quotient rings with the integers::

        sage: R = QuotientRing(ZZ,7*ZZ); R
        Quotient of Integer Ring by the ideal (7)
        sage: R.gens()
        (1,)
        sage: 1*R(3); 6*R(3); 7*R(3)
        3
        4
        0

    ::

        sage: S = QuotientRing(ZZ,ZZ.ideal(8)); S
        Quotient of Integer Ring by the ideal (8)
        sage: 2*S(4)
        0

    With polynomial rings (note that the variable name of the quotient
    ring can be specified as shown below)::

        sage: R.<xx> = QuotientRing(QQ[x], QQ[x].ideal(x^2 + 1)); R
        Univariate Quotient Polynomial Ring in xx over Rational Field with modulus x^2 + 1
        sage: R.gens(); R.gen()
        (xx,)
        xx
        sage: for n in range(4): xx^n
        1
        xx
        -1
        -xx

    ::

        sage: S = QuotientRing(QQ[x], QQ[x].ideal(x^2 - 2)); S
        Univariate Quotient Polynomial Ring in xbar over Rational Field with
        modulus x^2 - 2
        sage: xbar = S.gen(); S.gen()
        xbar
        sage: for n in range(3): xbar^n
        1
        xbar
        2

    Sage coerces objects into ideals when possible::

        sage: R = QuotientRing(QQ[x], x^2 + 1); R
        Univariate Quotient Polynomial Ring in xbar over Rational Field with
        modulus x^2 + 1

    By Noether's homomorphism theorems, the quotient of a quotient ring
    of `R` is just the quotient of `R` by the sum of the ideals. In this
    example, we end up modding out the ideal `(x)` from the ring
    `\QQ[x,y]`::

        sage: R.<x,y> = PolynomialRing(QQ,2)
        sage: S.<a,b> = QuotientRing(R,R.ideal(1 + y^2))
        sage: T.<c,d> = QuotientRing(S,S.ideal(a))
        sage: T
        Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x, y^2 + 1)
        sage: R.gens(); S.gens(); T.gens()
        (x, y)
        (a, b)
        (0, d)
        sage: for n in range(4): d^n
        1
        d
        -1
        -d

    TESTS:

    By :trac:`11068`, the following does not return a generic
    quotient ring but a usual quotient of the integer ring::

        sage: R = Integers(8)
        sage: I = R.ideal(2)
        sage: R.quotient(I)
        Ring of integers modulo 2

    Here is an example of the quotient of a free algebra by a
    twosided homogeneous ideal (see :trac:`7797`)::

        sage: F.<x,y,z> = FreeAlgebra(QQ, implementation='letterplace')
        sage: I = F*[x*y+y*z,x^2+x*y-y*x-y^2]*F
        sage: Q.<a,b,c> = F.quo(I); Q
        Quotient of Free Associative Unital Algebra on 3 generators (x, y, z) over Rational Field by the ideal (x*y + y*z, x*x + x*y - y*x - y*y)
        sage: a*b
        -b*c
        sage: a^3
        -b*c*a - b*c*b - b*c*c
        sage: J = Q*[a^3-b^3]*Q
        sage: R.<i,j,k> = Q.quo(J); R
        Quotient of Free Associative Unital Algebra on 3 generators (x, y, z) over Rational Field by the ideal (-y*y*z - y*z*x - 2*y*z*z, x*y + y*z, x*x + x*y - y*x - y*y)
        sage: i^3
        -j*k*i - j*k*j - j*k*k
        sage: j^3
        -j*k*i - j*k*j - j*k*k

    Check that :trac:`5978` is fixed by if we quotient by the zero ideal `(0)`
    then we just return ``R``::

        sage: R = QQ['x']
        sage: R.quotient(R.zero_ideal())
        Univariate Polynomial Ring in x over Rational Field
        sage: R.<x> = PolynomialRing(ZZ)
        sage: R is R.quotient(R.zero_ideal())
        True
        sage: I = R.ideal(0)
        sage: R is R.quotient(I)
        True
    """
    # 1. Not all rings inherit from the base class of rings.
    # 2. We want to support quotients of free algebras by homogeneous two-sided ideals.
    #if not isinstance(R, commutative_ring.CommutativeRing):
    #    raise TypeError, "R must be a commutative ring."
    from sage.all import Integers, ZZ
    if not R in Rings():
        raise TypeError("R must be a ring.")
    try:
        is_commutative = R.is_commutative()
    except (AttributeError, NotImplementedError):
        is_commutative = False
    if names is None:
        try:
            names = tuple([x + 'bar' for x in R.variable_names()])
        except ValueError:  # no names are assigned
            pass
    else:
        names = normalize_names(R.ngens(), names)
    if not isinstance(I, ideal.Ideal_generic) or I.ring() != R:
        I = R.ideal(I)
    if I.is_zero():
        return R
    try:
        if I.is_principal():
            return R.quotient_by_principal_ideal(I.gen(), names)
    except (AttributeError, NotImplementedError):
        pass
    if not is_commutative:
        try:
            if I.side() != 'twosided':
                raise AttributeError
        except AttributeError:
            raise TypeError("A twosided ideal is required.")
    if isinstance(R, QuotientRing_nc):
        pi = R.cover()
        S = pi.domain()
        G = [pi.lift(x) for x in I.gens()]
        I_lift = S.ideal(G)
        J = R.defining_ideal()
        if S == ZZ:
            return Integers((I_lift + J).gen())
        return R.__class__(S, I_lift + J, names=names)
    if isinstance(R, ring.CommutativeRing):
        return QuotientRing_generic(R, I, names)
    return QuotientRing_nc(R, I, names)
Example #32
0
    n = A.ncols()
    A = list(matrix(ZZ, A))
    for i in range(n):
        A.append([0]*i + [mod] + [0]*(n-i-1))

    L = matrix(ZZ, A).LLL()
    W1 = L*vector(ZZ, y)
    W2 = vector([int(round(RR(w)/mod))*mod - w for w in W1])
    return L.solve_right(W2) + y


if __name__ == "__main__":
    test = 0
    while True:
        print '  Testing heterogenous LGS mod composite'
        # from secrets import key
        # p = 2**126
        # p = 2**135
        p = 21652247421304131782679331804390761485569
        assert not is_prime(p)
        Zp = Integers(p)

        n = 40 # num vars
        m = n-1 # num equations

        x = vector([randrange(lo) for _ in range(n)])
        A = matrix([[randrange(lo) for _ in range(n)] for _ in range(m)])
        c = vector(ZZ,matrix(Zp,A)*x)
        assert x == small_lgs2(A, c, p)