Exemplo n.º 1
0
def _pell_solve_1(D,m): # m^2 < D
    root_d = Integer(floor(sqrt(D)))
    a = Integer(floor(root_d))
    P = Integer(0)
    Q = Integer(1)
    p = [Integer(1),Integer(a)]
    q = [Integer(0),Integer(1)]
    i = Integer(1)
    x0 = Integer(0)
    y0 = Integer(0)
    prim_sols = []
    test = Integer(0)
    while not (Q == 1 and i%2 == 1) or i == 1:
        test = p[i]**2 - D* (q[i]**2)
        if test == 1:
            x0 = p[i]
            y0 = q[i]
        test = (m/test)
        if is_square(test) and test >= 1:
            test = Integer(test)
            prim_sols.append((test*p[i],test*q[i]))
        i+=1
        P = a*Q - P
        Q = (D-P**2)/Q
        a = Integer(floor((P+root_d)/Q))
        p.append(a*p[i-1]+p[i-2])
        q.append(a*q[i-1]+q[i-2])
    return (x0,y0), prim_sols
Exemplo n.º 2
0
def saw_tooth_fn(x):
    if floor(x) == ceil(x):
        return 0
    elif x in QQ:
        return QQ(x) - QQ(floor(x)) - QQ(1) / QQ(2)
    else:
        return x - floor(x) - 0.5
def MainGridArray(mx, Mx, Dx):
    """
    Return the list of number that are
    1. integer multiple of Dx
    2. between mx and Mx

    If mx=-1.4 and Dx=0.5, the first element of the list will be -1
    If mx=-1.5 and Dx=0.5, the first element of the list will be -1.5
    If mx=0 and Dx=1, the first element of the list will be 0.
    """
    m = mx / Dx
    if not m.is_integer():
        m = floor(mx / Dx - 1)
    M = Mx / Dx
    if not M.is_integer():
        M = ceil(Mx / Dx + 1)
    a = []
    # These two lines are cancelling all the previous ones.
    m = floor(mx / Dx - 1)
    M = ceil(Mx / Dx + 1)
    for i in range(m, M):
        tentative = i * Dx
        if (tentative >= mx) and (tentative <= Mx):
            a.append(tentative)
    return a
Exemplo n.º 4
0
def saw_tooth_fn(x):
    if floor(x) == ceil(x):
        return 0
    elif x in QQ:
        return QQ(x)-QQ(floor(x))-QQ(1)/QQ(2)
    else:
        return x-floor(x)-0.5
Exemplo n.º 5
0
def instances(GD, N, MD, p):
    """
    The formula from "Optimizing the oracle under a depth limit". Assuming single-target, t = 1.

    :params GD: Grover's oracle depth
    :params N:  keyspace size
    :params MD: MAXDEPTH
    :params p:  target success probability

    Assuming p = 1
        In depth MD can fit j = floor(MD/GD) iterations.
        These give probability 1 for a search space of size M. 
            p(j) = sin((2j+1)theta)**2
            1 = sin((2j+1)theta)**2
            1 = sin((2j+1)theta)
            (2j+1)theta = pi/2
            theta = pi/(2(2j+1)) = sqrt(t/M) = 1/sqrt(M).
            sqrt(M) = 2(2j+1)/pi
            M = (2(2j+1)/pi)**2

        Hence need S = ceil(N/M) machines.
            S = ceil(N/(2(2*floor(MD/GD)+1)/pi)**2)
    Else
        Could either lower each individual computer's success prob, since the target is inside only one computer's state.
            Then given a requested p, we have
            p = sin((2j+1)theta)**2
            arcsine(sqrt(p)) = (2j+1)theta = (2j+1)/sqrt(M)
            M = (2j+1)**2/arcsine(sqrt(p))**2
            S = ceil(N*(arcsine(sqrt(p))/(2j+1))**2)

        Or could just run full depth but have less machines.
            For a target p, one would choose to have ceil(p*S) machines, where S is chosen as in the p = 1 case.
        Then look at which of both strategies gives lower cost.
    """

    # compute the p=1 case first
    S1 = ceil(N / (2 * (2 * floor(MD / GD) + 1) / pi)**2)

    # An alternative reasoning giving the same result for p == 1 (up to a very small difference):
    # Inner parallelisation gives sqrt(S) speedup without loosing success prob.
    # Set ceil(sqrt(N) * pi/4) * GD/sqrt(S) = MAXDEPTH
    # S1 = float(ceil(((pi*sqrt(N)/4) * GD / MD)**2))

    if p == 1:
        return S1
    else:
        Sp = ceil(N * (arcsin(sqrt(R(p))) / (2 * floor(MD / GD) + 1))**2)
        if ceil(p * S1) == Sp:
            print(
                "NOTE: for (GD, log2(N), log2(MD), p) == (%d, %.2f, %.2f, %.2f) naive reduction of parallel machines is not worse!"
                % (GD, log(N, 2).n(), log(MD, 2).n(), p))
        elif ceil(p * S1) < Sp:
            print(
                "NOTE: for (GD, log2(N), log2(MD), p) == (%d, %.2f, %.2f, %.2f) naive reduction of parallel machines is better!"
                % (GD, log(N, 2).n(), log(MD, 2).n(), p))

        res = min(Sp, ceil(p * S1))
        return res
Exemplo n.º 6
0
def tuples_even_wt_modular_forms(wt):
    '''
    Returns the list of tuples (p, q, r, s) such that
    4p + 6q + 10r +12s = wt.
    '''
    if wt < 0 or wt % 2 == 1:
        return []
    w = wt / 2
    return [(p, q, r, s) for p in range(0, floor(w / 2) + 1)
            for q in range(0, floor(w / 3) + 1)
            for r in range(0, floor(w / 5) + 1)
            for s in range(0, floor(w / 6) + 1)
            if 2 * p + 3 * q + 5 * r + 6 * s == w]
Exemplo n.º 7
0
def _to_polynomial(f, val1):
    prec = f.prec.value
    R = PolynomialRing(QQ if f.base_ring == ZZ else f.base_ring,
                       names="q1, q2")
    q1, q2 = R.gens()
    I = R.ideal([q1 ** (prec + 1), q2 ** (prec + 1)])
    S = R.quotient_ring(I)
    res = sum([sum([f.fc_dct.get((n, r, m), 0) * QQ(val1) ** r
                    for r in range(-int(floor(2 * sqrt(n * m))), int(floor(2 * sqrt(n * m))) + 1)])
               * q1 ** n * q2 ** m
               for n in range(prec + 1)
               for m in range(prec + 1)])
    return S(res)
Exemplo n.º 8
0
def small_box(n, pc, pspict):
    x0 = n * 1.1
    rect = Rectangle(Point(x0, 1), Point(x0 + 1, 0))
    if n < floor(pc / 10):
        rect.filled()
        rect.fill_parameters.color = "lightgray"
    pspict.DrawGraphs(rect)
    if n == floor(pc / 10):
        reste = (pc - 10 * n) / 10
        x1 = x0 + reste
        part = Rectangle(Point(x0, 1), Point(x1, 0))
        part.filled()
        part.fill_parameters.color = "lightgray"
        pspict.DrawGraphs(part)
Exemplo n.º 9
0
def make_curve(num_bits, num_curves=1): 
    """
    Description:
    
        Finds num_curves Barreto-Naehrig curves with a prime order that is at least 2^num_bits.
    
    Input:
    
        num_bits - number of bits for the prime order of the curve
        num_curves - number of curves to find
    
    Output:
    
        curves - list of the first num_curves BN curves each of prime order at least 2^num_bits;
                 each curve is represented as a tuple (q,t,r,k,D)
    
    """
    def P(y):
        x = Integer(y)
        return 36*pow(x,4) + 36*pow(x,3) + 24*pow(x,2) + 6*x + 1
    x = Integer(floor(pow(2, (num_bits)/4.0)/(sqrt(6))))
    q = 0
    r = 0
    t = 0
    curve_num = 0
    curves = []
    while curve_num < num_curves or (log(q).n()/log(2).n() < 2*num_bits and not (utils.is_suitable_q(q) and utils.is_suitable_r(r) and utils.is_suitable_curve(q,t,r,12,-3,num_bits))):
        t = Integer(6*pow(x,2) + 1)
        q = P(-x)
        r = q + 1 - t
        b = utils.is_suitable_q(q) and utils.is_suitable_r(r) and utils.is_suitable_curve(q,t,r,12,-3,num_bits)
        if b:
            try:
                assert floor(log(r)/log(2)) + 1 >= num_bits, 'Subgroup not large enough'  
                curves.append((q,t,r,12,-3))
                curve_num += 1
            except AssertionError as e:
                pass
        if curve_num < num_curves or not b:
            q = P(x)
            r = q+1-t
            if (utils.is_suitable_q(q) and utils.is_suitable_r(r) and utils.is_suitable_curve(q,t,r,12,-3,num_bits)):
                try:
                    assert floor(log(r)/log(2)) + 1 >= num_bits, 'Subgroup not large enough'  
                    curves.append((q,t,r,12,-3))
                    curve_num += 1
                except AssertionError as e:
                    pass  
        x += 1
    return curves
Exemplo n.º 10
0
def x5_jacobi_pwsr(prec):
    mx = int(ceil(sqrt(8 * prec) / QQ(2)) + 1)
    mn = int(floor(-(sqrt(8 * prec) - 1) / QQ(2)))
    mx1 = int(ceil((sqrt(8 * prec + 1) - 1) / QQ(2)) + 1)
    mn1 = int(floor((-sqrt(8 * prec + 1) - 1) / QQ(2)))
    R = LaurentPolynomialRing(QQ, names="t")
    t = R.gens()[0]
    S = PowerSeriesRing(R, names="q1")
    q1 = S.gens()[0]
    eta_3 = sum([QQ(-1) ** n * (2 * n + 1) * q1 ** (n * (n + 1) // 2)
                 for n in range(mn1, mx1)]) + bigO(q1 ** (prec + 1))
    theta = sum([QQ(-1) ** n * q1 ** (((2 * n + 1) ** 2 - 1) // 8) * t ** (n + 1)
                 for n in range(mn, mx)])
    # ct = qexp_eta(ZZ[['q1']], prec + 1)
    return theta * eta_3 ** 3 * QQ(8) ** (-1)
Exemplo n.º 11
0
def dual_C_coeff(i,j,parity):
  #global dual_C_coeff_dict
  #key = (i,j,parity % 2)
  #if dual_C_coeff_dict.has_key(key):
  #  return dual_C_coeff_dict[key]
  total = 0
  k = parity % 2
  while (floor(k/3) <= i):
    if (k % 3) == 2:
      k += 2
      continue
    total += (-1)**(floor(k/3))*C_coeff(k,i)*C_coeff(-2-k,j)
    k += 2
  #dual_C_coeff_dict[key] = total
  return total
Exemplo n.º 12
0
 def all_abstract_groups(self, maxord=None, chunksize=1000):
     inputs = []
     if maxord is None:
         from lmfdb import db
         maxord = db.gps_groups.max("order")
     for n in range(1, maxord+1):
         numgps = ZZ(libgap.NrSmallGroups(n))
         numchunks = ceil(numgps / chunksize)
         for i in range(numchunks):
             inputs.append((n, 1 + floor(i / numchunks * numgps), floor((i+1) / numchunks * numgps)))
     res = sum((outp for (inp, outp) in self.abstract_groups_of_order(inputs)), [])
     errors = [url for (t, url) in res if t is None]
     errors
     working_urls = [(t, url) for (t, url) in res if t is not None]
     working_urls.sort()
     times = [t for (t, url) in working_urls]
     total = len(times)
     if errors:
         print(f"Tested {total + len(errors)} pages with {len(errors)} errors occurring on the following pages:")
         for url in errors[:10]:
             print(url)
         if len(errors) > 10:
             print(f"Plus {len(errors) - 10} more")
     else:
         print("No errors while running the tests!")
     print(f"Average loading time: {sum(times)/total:.2f}")
     print(f"Min: {times[0]:.2f}, Max: {times[-1]:.2f}")
     print("Quartiles: %.2f %.2f %.2f" % tuple(times[max(0, int(total*f) - 1)] for f in [0.25, 0.5, 0.75]))
     print("Slowest pages:")
     for t, u in working_urls[-10:]:
         print(f"{t:.2f} - {u}")
     if total > 2:
         print("Histogram")
     h = 0.5
     nbins = (times[-1] - times[0]) / h
     while nbins < 50:
         h *= 0.5
         nbins = (times[-1] - times[0]) / h
     nbins = ceil(nbins)
     bins = [0]*nbins
     i = 0
     for t in times:
         while t > (i+1)*h + times[0]:
             i += 1
         bins[i] += 1
     for i, b in enumerate(bins):
         d = 100*float(b)/total
         print('%.2f\t|' %((i + 0.5)*h +  times[0]) + '-'*(int(d)-1) + '| - %.2f%%' % d)
Exemplo n.º 13
0
    def __init__(self,G,k=QQ(1)/QQ(2),number=0,ch=None,dual=False,version=1,dimension=1,**kwargs):
        r"""
        Initialize the Eta multiplier system: $\nu_{\eta}^{2(k+r)}$.
        INPUT:

        - G -- Group
        - ch -- character
        - dual -- if we have the dual (in this case conjugate)
        - weight -- Weight (recall that eta has weight 1/2 and eta**2k has weight k. If weight<>k we adjust the power accordingly.
        - number -- we consider eta^power (here power should be an integer so as not to change the weight...)
                
        """
        self._weight=QQ(k)
        if floor(self._weight-QQ(1)/QQ(2))==ceil(self._weight-QQ(1)/QQ(2)):
            self._half_integral_weight=1
        else:
            self._half_integral_weight=0
        MultiplierSystem.__init__(self,G,character=ch,dual=dual,dimension=dimension)
        number = number % 12
        if not is_even(number):
            raise ValueError,"Need to have v_eta^(2(k+r)) with r even!"
        self._pow=QQ((self._weight+number)) ## k+r
        self._k_den=self._pow.denominator()
        self._k_num=self._pow.numerator()
        self._K = CyclotomicField(12*self._k_den)
        self._z = self._K.gen()**self._k_num
        self._i = CyclotomicField(4).gen()
        self._fak = CyclotomicField(2*self._k_den).gen()**-self._k_num
        self._version = version
        
        self.is_consistent(k) # test consistency
Exemplo n.º 14
0
 def __init__(self,
              group,
              dchar=(0, 0),
              dual=False,
              is_trivial=False,
              dimension=1,
              **kwargs):
     if not ZZ(4).divides(group.level()):
         raise ValueError(" Need level divisible by 4. Got: {0} ".format(
             self._group.level()))
     MultiplierSystem.__init__(self,
                               group,
                               dchar=dchar,
                               dual=dual,
                               is_trivial=is_trivial,
                               dimension=dimension,
                               **kwargs)
     self._i = CyclotomicField(4).gen()
     self._one = self._i**4
     self._weight = QQ(kwargs.get("weight", QQ(1) / QQ(2)))
     ## We have to make sure that we have the correct multiplier & character
     ## for the desired weight
     if self._weight != None:
         if floor(2 * self._weight) != ceil(2 * self._weight):
             raise ValueError(
                 " Use ThetaMultiplier for half integral or integral weight only!"
             )
         t = self.is_consistent(self._weight)
         if not t:
             self.set_dual()
             t1 = self.is_consistent(self._weight)
             if not t1:
                 raise ArithmeticError(
                     "Could not find consistent theta multiplier! Try to add a character."
                 )
Exemplo n.º 15
0
 def cutout_digits(elt):
     digits = 1 if elt == 0 else floor(RR(abs(elt)).log(10)) + 1
     if digits > bigint_cutoff:
         # a large number would be replaced by ab...cd
         return digits - 7
     else:
         return 0
Exemplo n.º 16
0
 def create_small_record(self, min_prec=10, want_prec=100, max_length = 5242880, max_height_qexp = default_max_height):
     ### creates a duplicate record (fs) of this webnewform
     ### with lower precision to load faster on the web
     ### we aim to have at most max_length bytes
     ### but at least min_prec coefficients and we desire to have want_prec
     if min_prec>=self.prec:
         raise ValueError("Need higher precision, self.prec = {}".format(self.prec))
     if not hasattr(self, '_file_record_length'):
         self.update_from_db()
     l = self._file_record_length
         
     if l > max_length or self.prec > want_prec:
         nl = float(l)/float(self.prec)*float(want_prec)
         if nl > max_length:
             prec = max([floor(float(self.prec)/float(l)*float(max_length)), min_prec])
         else:
             prec = want_prec
         emf_logger.debug("Creating a new record with prec = {}".format(prec))
         self.prec = prec
         include_coeffs = self.complexity_of_first_nonvanishing_coefficients() <= default_max_height
         if include_coeffs:
             self.q_expansion = self.q_expansion.truncate_powerseries(prec)
             self._coefficients = {n:c for n,c in self._coefficients.iteritems() if n<prec}
         else:
             self.q_expansion = self.q_expansion.truncate_powerseries(1)
             self._coefficients = {}
             self.prec = 0
             self.coefficient_field = NumberField(self.absolute_polynomial, names=str(self.coefficient_field.gen()))
         self._embeddings['values'] = {n:c for n,c in self._embeddings['values'].iteritems() if n<prec}
         self._embeddings['prec'] = prec
         self.save_to_db()
Exemplo n.º 17
0
 def get_regular_points(self, dx):
     """
     Notice that it does not return the last point of the segment, unless the length is a multiple of dx.
        this is why we add by hand the last point in GetWavyPoint
     """
     n = floor(self.length/dx)
     return [self.get_point_proportion(float(i)/n) for i in range(0, n)]
Exemplo n.º 18
0
 def cutout_digits(elt):
     digits = 1 if elt == 0 else floor(RR(abs(elt)).log(10)) + 1
     if digits > bigint_cutoff:
         # a large number would be replaced by ab...cd
         return digits - 7
     else:
         return 0
Exemplo n.º 19
0
def get_all_combis(g, n):
    dim = 3 * g - 3 + n
    reducible_boundaries = 0
    marks = list(range(1, n + 1))
    if n != 0:
        first_mark_list = [marks.pop()]
        for g1 in range(0, g + 1):
            for p in subsets(marks):
                r_marks = set(first_mark_list + p)
                if 3 * g1 - 3 + len(r_marks) + 1 >= 0 and 3 * (
                        g - g1) - 3 + n - len(r_marks) + 1 >= 0:
                    reducible_boundaries += 1

    else:  #self.n == 0
        for g1 in range(1, floor(g / 2.0) + 1):
            reducible_boundaries += 1

    #print "computed red bound"
    indexes = list(range(1, n + dim + 1)) + list(
        range(n + dim + g + 1, n + dim + g + reducible_boundaries + 2))
    codims = [1] * n + list(range(1,
                                  dim + 1)) + [1] * (reducible_boundaries + 1)

    for w in WeightedIntegerVectors(dim, codims):
        combi = []
        #print w
        for index, wi in zip(indexes, w):
            combi += [index] * wi
        yield combi
Exemplo n.º 20
0
    def exact_cm_at_i_level_1(self, N=10,insert_in_db=True):
        r"""
        Use formula by Zagier (taken from pari implementation by H. Cohen) to compute the geodesic expansion of self at i
        and evaluate the constant term.

        INPUT:
        -''N'' -- integer, the length of the expansion to use.
        """
        try:
            [poldeg, monomials, X] = self.as_polynomial_in_E4_and_E6()
        except:
            return ""
        k = self.weight()
        tab = dict()
        QQ['x']
        tab[0] = 0 * x ** 0
        tab[1] = X[0] * x ** poldeg
        for ix in range(1, len(X)):
            tab[1] = tab[1] + QQ(X[ix]) * x ** monomials[ix][1]
        for n in range(1, N + 1):
            tmp = -QQ(k + 2 * n - 2) / QQ(12) * x * tab[n] + (x ** 2 - QQ(1)) / QQ(2) * ((tab[
                                                                                          n]).derivative())
            tab[n + 1] = tmp - QQ((n - 1) * (n + k - 2)) / QQ(144) * tab[n - 1]
        res = 0
        for n in range(1, N + 1):
            term = (tab[n](x=0)) * 12 ** (floor(QQ(n - 1) / QQ(2))) * x ** (n - 1) / factorial(n - 1)
            res = res + term
        
        return res
Exemplo n.º 21
0
    def dirichlet_series_coeffs(self, prec, eps=1e-10):
        """
        Return the coefficients of the Dirichlet series representation
        of self, up to the given precision.

        INPUT:
           - prec -- positive integer
           - eps -- None or a positive real; any coefficient with absolute
             value less than eps is set to 0.
        """
        # Use multiplicativity to compute the Dirichlet series
        # coefficients, then make a DirichletSeries object.
        zero = RDF(0)
        coeffs = [RDF(0), RDF(1)] + [None] * (prec - 2)

        from sage.all import log, floor  # TODO: slow

        # prime-power indexed coefficients
        for p in prime_range(2, prec):
            B = floor(log(prec, p)) + 1
            series = self._local_series(p, B)
            p_pow = p
            for i in range(1, B):
                coeffs[p_pow] = series[i] if (
                    eps is None or abs(series[i]) > eps) else zero
                p_pow *= p

        # non-prime-powers
        from sage.all import factor
        for n in range(2, prec):
            if coeffs[n] is None:
                a = prod(coeffs[p**e] for p, e in factor(n))
                coeffs[n] = a if (eps is None or abs(a) > eps) else zero

        return coeffs
Exemplo n.º 22
0
    def __init__(self,G,k=QQ(1)/QQ(2),number=0,ch=None,dual=False,version=1,dimension=1,**kwargs):
        r"""
        Initialize the Eta multiplier system: $\nu_{\eta}^{2(k+r)}$.
        INPUT:

        - G -- Group
        - ch -- character
        - dual -- if we have the dual (in this case conjugate)
        - weight -- Weight (recall that eta has weight 1/2 and eta**2k has weight k. If weight<>k we adjust the power accordingly.
        - number -- we consider eta^power (here power should be an integer so as not to change the weight...)
                
        """
        self._weight=QQ(k)
        if floor(self._weight-QQ(1)/QQ(2))==ceil(self._weight-QQ(1)/QQ(2)):
            self._half_integral_weight=1
        else:
            self._half_integral_weight=0
        MultiplierSystem.__init__(self,G,character=ch,dual=dual,dimension=dimension)
        number = number % 12
        if not is_even(number):
            raise ValueError,"Need to have v_eta^(2(k+r)) with r even!"
        self._pow=QQ((self._weight+number)) ## k+r
        self._k_den=self._pow.denominator()
        self._k_num=self._pow.numerator()
        self._K = CyclotomicField(12*self._k_den)
        self._z = self._K.gen()**self._k_num
        self._i = CyclotomicField(4).gen()
        self._fak = CyclotomicField(2*self._k_den).gen()**-self._k_num
        self._version = version
        
        self.is_consistent(k) # test consistency
Exemplo n.º 23
0
 def create_small_record(self, min_prec=10, want_prec=100, max_length = 5242880, max_height_qexp = default_max_height):
     ### creates a duplicate record (fs) of this webnewform
     ### with lower precision to load faster on the web
     ### we aim to have at most max_length bytes
     ### but at least min_prec coefficients and we desire to have want_prec
     if min_prec>=self.prec:
         raise ValueError("Need higher precision, self.prec = {}".format(self.prec))
     l = self._file_record_length
     if l > max_length or self.prec > want_prec:
         nl = float(l)/float(self.prec)*float(want_prec)
         if nl > max_length:
             prec = max([floor(float(self.prec)/float(l)*float(max_length)), min_prec])
         else:
             prec = want_prec
         emf_logger.debug("Creating a new record with prec = {}".format(prec))
         self.prec=prec
         include_qexp = self.complexity_of_first_nonvanishing_coefficients() <= default_max_height
         if include_qexp:
             self.q_expansion = self.q_expansion.truncate_powerseries(prec)
         else:
             self.q_expansion = self.q_expansion.truncate_powerseries(1)
         self._coefficients = {n:c for n,c in self._coefficients.iteritems() if n<prec}
         self._embeddings['values'] = {n:c for n,c in self._embeddings['values'].iteritems() if n<prec}
         self._embeddings['prec'] = prec
         self.save_to_db()
Exemplo n.º 24
0
def get_all_combis(g,n):
    dim = 3*g-3 + n
    reducible_boundaries = 0
    marks = range(1,n+1)
    if n != 0:
        first_mark_list = [marks.pop()]            
        for g1 in range(0, g + 1):
            for p in subsets(marks):
                r_marks = set(first_mark_list + p)
                if 3*g1 - 3 + len(r_marks) + 1 >= 0 and 3*(g-g1) - 3 + n - len(r_marks) + 1 >= 0:
                    reducible_boundaries+=1  
    
    else: #self.n == 0
        for g1 in range(1, floor(g/2.0)+1):
            reducible_boundaries+=1

    #print "computed red bound"
    indexes = range(1,n+dim+1) + range(n+dim+g+1, n+dim+g+reducible_boundaries + 2)
    codims = [1]*n + range(1,dim+1) + [1]*(reducible_boundaries +1)
    
    for w in WeightedIntegerVectors(dim,codims):
        combi = []
        #print w
        for index, wi in zip(indexes,w):
            combi += [index]*wi
        yield combi
Exemplo n.º 25
0
    def dirichlet_series_coeffs(self, prec, eps=1e-10):
        """
        Return the coefficients of the Dirichlet series representation
        of self, up to the given precision.

        INPUT:
           - prec -- positive integer
           - eps -- None or a positive real; any coefficient with absolute
             value less than eps is set to 0.
        """
        # Use multiplicativity to compute the Dirichlet series
        # coefficients, then make a DirichletSeries object.
        zero = RDF(0)
        coeffs = [RDF(0),RDF(1)] + [None]*(prec-2)

        from sage.all import log, floor   # TODO: slow
        
        # prime-power indexed coefficients
        for p in prime_range(2, prec):
            B = floor(log(prec, p)) + 1
            series = self._local_series(p, B)
            p_pow = p
            for i in range(1, B):
                coeffs[p_pow] = series[i] if (eps is None or abs(series[i])>eps) else zero
                p_pow *= p

        # non-prime-powers
        from sage.all import factor
        for n in range(2, prec):
            if coeffs[n] is None:
                a = prod(coeffs[p**e] for p, e in factor(n))
                coeffs[n] = a if (eps is None or abs(a) > eps) else zero

        return coeffs
Exemplo n.º 26
0
def NF_embedding_linear(z, numberfield, ithcomplex_embedding = 0, known_bits = None ):
    """
    Input:
        z \in Complex Number
        numberfield a NumberField
        ithcomplex_embedding uses the i-th embedding of self in the complex numbers
        known_bits to pass to algdep
    Output:
        returns z in terms of generators for the numberfield respecting the embedding

    Examples:
        QQx.<x> = QQ[]
        L.<a> = NumberField(x**2 + 3)
        NF_embedding_algdep(ComplexField(100)(2*sqrt(-3) + 1000000), L)
    """

    if known_bits is None:
        prec = floor(z.prec()*0.8)
    else:
        prec = known_bits
    w = numberfield.gen();
    wcc = w.complex_embedding(prec = prec, i = ithcomplex_embedding);
    n = numberfield.degree();

    V=[z] + [wcc**i for i in range(n)]
    r = list(gp.lindep(V))
    print r
    if r[0] == 0:
        return None
    z_alg =  numberfield([QQ(-r[i]/r[0]) for i in range(1,n+1)])
    assert almost_equal(z, z_alg,  ithcomplex_embedding = ithcomplex_embedding, prec = known_bits);
    return z_alg
Exemplo n.º 27
0
def make_klen_list(klen, m):
    if klen in ZZ:
        klen_list = [int(klen)] * m
    else:
        nz = int(round((ceil(klen) - klen) * m))
        klen_list = [floor(klen)] * nz + [ceil(klen)] * (m - nz)
    return klen_list
Exemplo n.º 28
0
def roca(n):

    keySize = n.bit_length()

    if keySize <= 960:
        M_prime = 0x1B3E6C9433A7735FA5FC479FFE4027E13BEA
        m = 5

    elif 992 <= keySize <= 1952:
        M_prime = (
            0x24683144F41188C2B1D6A217F81F12888E4E6513C43F3F60E72AF8BD9728807483425D1E
        )
        m = 4
        print("Have you several days/months to spend on this ?")

    elif 1984 <= keySize <= 3936:
        M_prime = 0x16928DC3E47B44DAF289A60E80E1FC6BD7648D7EF60D1890F3E0A9455EFE0ABDB7A748131413CEBD2E36A76A355C1B664BE462E115AC330F9C13344F8F3D1034A02C23396E6
        m = 7
        print("You'll change computer before this scripts ends...")

    elif 3968 <= keySize <= 4096:
        print("Just no.")
        return None

    else:
        print("Invalid key size: {}".format(keySize))
        return None

    beta = 0.1
    a3 = Zmod(M_prime)(n).log(65537)
    order = Zmod(M_prime)(65537).multiplicative_order()
    inf = a3 >> 1
    sup = (a3 + order) >> 1
    # Upper bound for the small root x0
    XX = floor(2 * n ** 0.5 / M_prime)
    invmod_Mn = inverse_mod(M_prime, n)
    # Create the polynom f(x)
    F = PolynomialRing(Zmod(n), implementation="NTL", names=("x",))
    (x,) = F._first_ngens(1)
    # Search 10 000 values at a time, using multiprocess
    # too big chunks is slower, too small chunks also
    chunk_size = 10000
    for inf_a in range(inf, sup, chunk_size):
        # create an array with the parameter for the solve function
        inputs = [
            ((M_prime, n, a, m, XX, invmod_Mn, F, x, beta), {})
            for a in range(inf_a, inf_a + chunk_size)
        ]
        # the sage builtin multiprocessing stuff
        from sage.parallel.multiprocessing_sage import parallel_iter
        from multiprocessing import cpu_count

        for k, val in parallel_iter(cpu_count(), solve, inputs):
            if val:
                p = val[0]
                q = val[1]
                print("{}:{}".format(p, q))
                return val
        return "Fail"
Exemplo n.º 29
0
def red_mod1(z):
    """
    Compute z mod 1 in [0,1)
    :param z:
    :return:
    """
    if z > 0:
        return z - floor(z)
Exemplo n.º 30
0
def C_coeff(m,term):
  n = term - floor(m/3)
  if n < 0:
    return 0
  if (m % 3) == 0:
    return A_list[n]
  else:
    return B_list[n]
Exemplo n.º 31
0
 def merge_animations(self, motions, total_time=12, fps=25, **kwargs):
     r"""
     Return an animation by concatenating a list of motions.
     """
     realizations = []
     for M in motions:
         realizations += M.sample_motion(floor(total_time*fps/len(motions)))
     return super(ParametricGraphMotion, self).animation_SVG(realizations, **kwargs)
Exemplo n.º 32
0
def _pell_solve_2(D,m): # m^2 >= D
    prim_sols = []
    t,u = _pell_solve_1(D,1)[0]
    if m > 0:
        L = Integer(0)
        U = Integer(floor(sqrt(m*(t-1)/(2*D))))
    else:
        L = Integer(ceil(sqrt(-m/D)))
        U = Integer(floor(sqrt(-m*(t+1)/(2*D))))
    for y in range(L,U+1):
        y = Integer(y)
        x = (m + D*(y**2))
        if is_square(x):
            x = Integer(sqrt(x))
            prim_sols.append((x,y))
            if not ((-x*x - y*y*D) % m == 0 and (2*y*x) % m == 0): # (x,y) and (-x,y) are in different solution classes, so add both
                prim_sols.append((-x,y))
    return (t,u),prim_sols
Exemplo n.º 33
0
def make_plot(row, params=plot_default, extra_plots=None):
    if row['trans_arcs_highres'] is not None:
        arcs = row['trans_arcs_highres'].unpickle()
    else:
        arcs = row['trans_arcs'].unpickle()
    title = '$' + row['name'] + '$: genus = ' + repr(row['alex_deg'] // 2)
    plot = params['plot_cls'](arcs, title=title)
    ax = plot.figure.axis

    if extra_plots:
        for x, y in extra_plots:
            ax.plot(x, y)

    k = order_of_longitude(snappy.Manifold(row['name']))

    ax.plot((0, k), (0, 0))
    ax.legend_.remove()

    ax.set_xbound(0, k)
    ax.get_xaxis().tick_bottom()

    yvals = [p.imag for arc in arcs for p in arc]
    ax.set_ybound(1.1 * min(yvals), 1.1 * max(yvals))

    ytop = floor(1.1 * max(yvals))
    if 1 <= ytop <= 10:
        ax.set_yticks(range(-ytop, ytop + 1))
    elif 25 <= ytop <= 100:
        ticks = range(10, ytop, 10)
        ticks = [-y for y in ticks] + [0] + ticks
        ax.set_yticks(ticks)
    alex = PolynomialRing(QQ, 'a')(row['alex'])
    for z, e in unimodular_roots(alex):
        theta = k * rotation_angle(z)
        if e == 1:
            color = params['simple alex root']
        else:
            color = params['mult alex root']
        ax.plot([theta], [0], color=color, marker='o', markeredgecolor='black')

    M = snappy.Manifold(row['name'])
    for parabolic in eval(row['parabolic_PSL2R_details']):
        if len(parabolic) == 2:
            L, is_galois_conj_of_geom = parabolic
            points = [(0, L), (0, -L), (1, L), (1, -L)]
        else:
            x, y, is_galois_conj_of_geom = parabolic
            points = [(x, y)]
        if is_galois_conj_of_geom:
            color = params['galois of geom']
        else:
            color = params['other parabolic']
        for x, y in points:
            ax.plot([x], [y], color=color, marker='o', markeredgecolor='black')

    plot.figure.draw()
    return plot
Exemplo n.º 34
0
 def as_polynomial_in_E4_and_E6(self,insert_in_db=True):
     r"""
     If self is on the full modular group writes self as a polynomial in E_4 and E_6.
     OUTPUT:
     -''X'' -- vector (x_1,...,x_n)
     with f = Sum_{i=0}^{k/6} x_(n-i) E_6^i * E_4^{k/4-i}
     i.e. x_i is the coefficient of E_6^(k/6-i)*
     """
     if(self.level() != 1):
         raise NotImplementedError("Only implemented for SL(2,Z). Need more generators in general.")
     if(self._as_polynomial_in_E4_and_E6 is not None and self._as_polynomial_in_E4_and_E6 != ''):
         return self._as_polynomial_in_E4_and_E6
     d = self._parent.dimension_modular_forms()  # dimension of space of modular forms
     k = self.weight()
     K = self.base_ring()
     l = list()
     # for n in range(d+1):
     #    l.append(self._f.q_expansion(d+2)[n])
     # v=vector(l) # (self._f.coefficients(d+1))
     v = vector(self.coefficients(range(d),insert_in_db=insert_in_db))
     d = dimension_modular_forms(1, k)
     lv = len(v)
     if(lv < d):
         raise ArithmeticError("not enough Fourier coeffs")
     e4 = EisensteinForms(1, 4).basis()[0].q_expansion(lv + 2)
     e6 = EisensteinForms(1, 6).basis()[0].q_expansion(lv + 2)
     m = Matrix(K, lv, d)
     lima = floor(k / 6)  # lima=k\6;
     if((lima - (k / 2)) % 2 == 1):
         lima = lima - 1
     poldeg = lima
     col = 0
     monomials = dict()
     while(lima >= 0):
         deg6 = ZZ(lima)
         deg4 = (ZZ((ZZ(k / 2) - 3 * lima) / 2))
         e6p = (e6 ** deg6)
         e4p = (e4 ** deg4)
         monomials[col] = [deg4, deg6]
         eis = e6p * e4p
         for i in range(1, lv + 1):
             m[i - 1, col] = eis.coefficients()[i - 1]
         lima = lima - 2
         col = col + 1
     if (col != d):
         raise ArithmeticError("bug dimension")
     # return [m,v]
     if self._verbose > 0:
         wmf_logger.debug("m={0}".format(m, type(m)))
         wmf_logger.debug("v={0}".format(v, type(v)))
     try:
         X = m.solve_right(v)
     except:
         return ""
     self._as_polynomial_in_E4_and_E6 = [poldeg, monomials, X]
     return [poldeg, monomials, X]
Exemplo n.º 35
0
def euler_p_factor(root_list, PREC):
    ''' computes the coefficients of the pth Euler factor expanded as a geometric series
      ax^n is the Dirichlet series coefficient p^(-ns)
    '''
    PREC = floor(PREC)
    # return satake_list
    R = LaurentSeriesRing(CF, 'x')
    x = R.gens()[0]
    ep = prod([1 / (1 - a * x) for a in root_list])
    return ep + O(x ** (PREC + 1))
def orbit_label(j):
    x = AlphabeticStrings().gens()
    if(j < 26):
        label = str(x[j]).lower()
    else:
        j1 = j % 26
        j2 = floor(QQ(j) / QQ(26))
        label = str(x[j1]).lower()
        label = label + str(j2)
    return label
Exemplo n.º 37
0
def prop_int_pretty(n):
    """
    This function should be called whenever displaying an integer in the
    properties table so that we can keep the formatting consistent
    """
    if abs(n) >= 10**12:
        e = floor(log(abs(n),10))
        return r'$%.3f\times 10^{%d}$' % (n/10**e, e)
    else:
        return '$%s$' % n
Exemplo n.º 38
0
def euler_p_factor(root_list, PREC):
    ''' computes the coefficients of the pth Euler factor expanded as a geometric series
      ax^n is the Dirichlet series coefficient p^(-ns)
    '''
    PREC = floor(PREC)
    # return satake_list
    R = LaurentSeriesRing(CF, 'x')
    x = R.gens()[0]
    ep = prod([1 / (1 - a * x) for a in root_list])
    return ep + O(x ** (PREC + 1))
Exemplo n.º 39
0
def euler_p_factor(root_list, PREC):
    ''' computes the coefficients of the pth Euler factor expanded as a geometric series
      ax^n is the Dirichlet series coefficient p^(-ns)
    '''
    PREC = floor(PREC)
    # return satake_list
    R = PowerSeriesRing(CF, 'x')
    x = R.gen()
    ep = ~R.prod([1 - a * x for a in root_list])
    return ep.O(PREC + 1)
Exemplo n.º 40
0
def HasFinitePointAt(F, p, c):
    # Tests whether y²=c*F(x) has a finite Qp-point with x and y both in Zp,
    # assuming that deg F = 6 and F integral
    Fp = GF(p)
    if p > 2 and Fp(
            F.leading_coefficient()):  # Tests to accelerate case of large p
        # Write F(x) = c*lc(F)*R(x)²*S(x) mod p, R as big as possible
        R = F.parent()(1)
        S = F.parent()(1)
        for X in (F.base_extend(Fp) /
                  Fp(F.leading_coefficient())).squarefree_decomposition():
            [
                G, v
            ] = X  # Term of the form G(x)^v in the factorisation of F(x) mod p
            S *= G**(v % 2)
            R *= G**(v // 2)
        r = R.degree()
        s = S.degree()
        if s == 0:  # F(x) = C*R(x)² mod p, C = c*lc(F) constant
            if IsSquareInQp(c * F.leading_coefficient(), p):
                if p > r:  # Then there is x s.t. R(x) nonzero and C is a square
                    return true
            #else: # C nonsquare, so if we have a Zp-point it must have R(x) = 0 mod p
            #Z = R.roots()
            ##TODO
        else:
            g = S.degree() // 2 - 1  # genus of the curve y²=C*S(x)
            B = floor(
                p - 1 - 2 * g * sqrt(p)
            )  # lower bound on number of points on y²=C*S(x) not at infty
            if B > r + s:  # Then there is a point on y²=C*S(x) not at infty and with R(x) and S(x) nonzero
                return true
    #Now p is small, we can run a naive search
    q = p
    Z = []
    if p == 2:
        q = 8
    for x in range(q):
        y = F(x)
        # If we have found a root, save it (take care of the case p=2!)
        if (p > 2 or x < 2) and Fp(y) == 0:
            Z.append(x)
        # If we have a mod p point with y nonzero mod p, then it lifts, so we're done
        if IsSquareInQp(c * y, p):
            return true
    #So now, if we have a Qp-point, then its y-coordinate must be 0 mod p
    t = F.variables()[0]
    for z in Z:
        F1 = F(z + p * t)
        c1 = F1.content()
        F1 //= c1
        if HasFinitePointAt(F1, p, (c * c1).squarefree_part()):
            return true
    return false
Exemplo n.º 41
0
def interpolate_deg2(dct, bd, autom=True, parity=None):
    '''parity is 0 if the parity of the weight and the character coincide
    else 1.
    '''
    t_ring = PolynomialRing(QQ, names="t")
    t = t_ring.gens()[0]
    u_ring = PolynomialRing(QQ, names="u")
    u = u_ring.gens()[0]

    # lift the values of dct
    dct = {k: v.lift() for k, v in dct.items()}

    def interpolate_pol(x, d):
        prd = mul([x - a for a in d])
        prd_dff = prd.derivative(x)
        return sum([v * prd_dff.subs({x: k}) ** (-1) * prd // (x - k)
                    for k, v in d.items()])

    def t_pol_dct(n, m):
        if not autom:
            dct_t = {a: v[(n, m)] * a ** (2 * bd) for a, v in dct.items()}
            return t_ring(interpolate_pol(t, dct_t))
        # put u = t + t^(-1)
        elif parity == 0:
            dct_u = {a + a ** (-1): v[(n, m)] for a, v in dct.items()}
            u_pol = interpolate_pol(u, dct_u)
            return t_ring(t ** (2 * bd) * u_pol.subs({u: t + t ** (-1)}))
        else:
            dct_u = {a + a ** (-1): v[(n, m)] / (a - a ** (-1))
                     for a, v in dct.items()}
            u_pol = interpolate_pol(u, dct_u)
            return t_ring(t ** (2 * bd) * u_pol.subs({u: t + t ** (-1)}) *
                          (t - t ** (-1)))

    fc_dct = {}
    for n in range(bd + 1):
        for m in range(bd + 1):
            pl = t_pol_dct(n, m)
            for r in range(-int(floor(2 * sqrt(n * m))), int(floor(2 * sqrt(n * m))) + 1):
                fc_dct[(n, r, m)] = pl[r + 2 * bd]
    return fc_dct
Exemplo n.º 42
0
def PartieEntiere():
    pspict, fig = SinglePicture("PartieEntiere")

    x = var('x')
    f = phyFunction(floor(x)).graph(-2, 3)
    f.linear_plotpoints = 1000

    pspict.DrawGraphs(f)
    pspict.DrawDefaultAxes()
    pspict.dilatation(1)
    fig.conclude()
    fig.write_the_file()
Exemplo n.º 43
0
 def find_prec(s):
     if isinstance(s, string_types):
         # strip negatives, period and exponent
         s = s.replace("-","").replace(".","").lstrip("0")
         if "e" in s:
             s = s[:s.find("e")]
         return floor(len(s) * 3.32192809488736)
     else:
         try:
             return s.parent().precision()
         except Exception:
             return 53
Exemplo n.º 44
0
    def MgnLb_class(self, index):
        """
        Returns the class corresponding to the index from Carl Faber's ``MgnLb`` Maple program.
        This is useful for testing purposes. ::

            sage: from strataalgebra import *
            sage: s = StrataAlgebra(QQ,1,(1,2))
            sage: s.MgnLb_class(1)
            ps1
            sage: s.MgnLb_class(4)
            ka2
            sage: s.MgnLb_class(6)
            1/2*D_irr
            sage: s.MgnLb_class(2)
            ps2

        """
        #print "making classes again!"
        if index <= len(self.markings):
            return self.psi(index)
        index -= len(self.markings)
        if index <= self.moduli_dim:
            return self.kappa(index)
        index -= self.moduli_dim
        if index <= self.g:
            raise Exception("We don't do the ch classes!")
        index -= self.g
        if index == 1:
            return self.irr()
        index -= 1

        marks = set(self.markings)
        reducible_boundaries = []
        if len(self.markings) != 0:
            first_mark_list = [marks.pop()]
            for g1 in range(0, self.g + 1):
                for p in subsets(marks):
                    r_marks = set(first_mark_list + p)
                    if 3 * g1 - 3 + len(
                            r_marks) + 1 >= 0 and 3 * (self.g - g1) - 3 + len(
                                self.markings) - len(r_marks) + 1 >= 0:
                        reducible_boundaries.append((g1, r_marks))

            reducible_boundaries.sort(key=lambda b: sorted(list(b[1])))
            reducible_boundaries.sort(key=lambda b: len(b[1]))
            reducible_boundaries.sort(key=lambda b: b[0])

        else:  #self.n == 0
            for g1 in range(1, floor(self.g / 2.0) + 1):
                reducible_boundaries.append((g1, []))

        return self.boundary(*reducible_boundaries[index - 1])
Exemplo n.º 45
0
    def MgnLb_class(self,index):
        """
        Returns the class corresponding to the index from Carl Faber's ``MgnLb`` Maple program.
        This is useful for testing purposes. ::

            sage: from strataalgebra import *
            sage: s = StrataAlgebra(QQ,1,(1,2))
            sage: s.MgnLb_class(1)
            ps1
            sage: s.MgnLb_class(4)
            ka2
            sage: s.MgnLb_class(6)
            1/2*D_irr
            sage: s.MgnLb_class(2)
            ps2

        """
        #print "making classes again!"
        if index <= len(self.markings):
            return self.psi(index)
        index -= len(self.markings)
        if index <= self.moduli_dim:
            return self.kappa(index)
        index -= self.moduli_dim
        if index <= self.g:
            raise Exception("We don't do the ch classes!")
        index -= self.g
        if index == 1:
            return self.irr()
        index -=1
        
        marks = set(self.markings)
        reducible_boundaries = []
        if len(self.markings) != 0:
            first_mark_list = [marks.pop()]            
            for g1 in range(0, self.g + 1):
                for p in subsets(marks):
                    r_marks = set(first_mark_list + p)
                    if 3*g1 - 3 + len(r_marks) + 1 >= 0 and 3*(self.g-g1) - 3 + len(self.markings) - len(r_marks) + 1 >= 0:
                        reducible_boundaries.append( (g1, r_marks) )  
                        
            reducible_boundaries.sort(key = lambda b: sorted(list(b[1])))
            reducible_boundaries.sort(key = lambda b: len(b[1]))
            reducible_boundaries.sort(key = lambda b: b[0])
        
        else: #self.n == 0
            for g1 in range(1, floor(self.g/2.0)+1):
                reducible_boundaries.append( (g1, [])) 
            
        return self.boundary(*reducible_boundaries[index-1])   
Exemplo n.º 46
0
def run(num_bits,k):
    """
    Description:
    
        Runs the Dupont-Enge-Morain method multiple times until a valid curve is found
    
    Input:
    
        num_bits - number of bits
        k - an embedding degree
    
    Output:
    
        (q,t,r,k,D) - an elliptic curve;
                      if no curve is found, the algorithm returns (0,0,0,k,0)
    
    """
    j,r,q,t = 0,0,0,0
    num_generates = 512
    h = num_bits/(euler_phi(k))
    tried = [(0,0)] # keep track of random values tried for efficiency
    for i in range(0,num_generates):
        D = 0
        y = 0
        while (D,y) in tried: # find a pair that we have not tried
            D = -randint(1, 1024) # pick a small D so that the CM method is fast
            D = fundamental_discriminant(D)
            m = 0.5*(h - log(-D).n()/(2*log(2)).n())
            if m < 1:
                m = 1
            y = randint(floor(2**(m-1)), floor(2**m))
        tried.append((D,y))
        q,t,r,k,D = method(num_bits,k,D,y) # run DEM
        if q != 0 and t != 0 and r != 0 and k != 0 and D != 0: # found an answer, so output it
            assert is_valid_curve(q,t,r,k,D), 'Invalid output'
            return q,t,r,k,D
    return 0,0,0,k,0 # found nothing
Exemplo n.º 47
0
def HasFinitePointAt(F,p,c):
    # Tests whether y²=c*F(x) has a finite Qp-point with x and y both in Zp,
    # assuming that deg F = 6 and F integral
    Fp = GF(p)
    if p > 2 and Fp(F.leading_coefficient()): # Tests to accelerate case of large p
        # Write F(x) = c*lc(F)*R(x)²*S(x) mod p, R as big as possible
        R = F.parent()(1)
        S = F.parent()(1)
        for X in (F.base_extend(Fp)/Fp(F.leading_coefficient())).squarefree_decomposition():
            [G,v] = X # Term of the form G(x)^v in the factorisation of F(x) mod p
            S *= G**(v%2)
            R *= G**(v//2)
        r = R.degree()
        s = S.degree()
        if s == 0: # F(x) = C*R(x)² mod p, C = c*lc(F) constant
            if IsSquareInQp(c*F.leading_coefficient(),p):
                if p>r:# Then there is x s.t. R(x) nonzero and C is a square
                    return true
            #else: # C nonsquare, so if we have a Zp-point it must have R(x) = 0 mod p
            #Z = R.roots()
            ##TODO
        else:
            g = S.degree()//2 - 1 # genus of the curve y²=C*S(x)
            B = floor(p-1-2*g*sqrt(p)) # lower bound on number of points on y²=C*S(x) not at infty
            if B > r+s: # Then there is a point on y²=C*S(x) not at infty and with R(x) and S(x) nonzero
                return true
    #Now p is small, we can run a naive search
    q = p
    Z = []
    if p == 2:
        q = 8
    for x in range(q):
        y = F(x)
        # If we have found a root, save it (take care of the case p=2!)
        if (p > 2 or x < 2) and Fp(y) == 0:
            Z.append(x)
        # If we have a mod p point with y nonzero mod p, then it lifts, so we're done
        if IsSquareInQp(c*y, p):
            return true
    #So now, if we have a Qp-point, then its y-coordinate must be 0 mod p
    t = F.variables()[0]
    for z in Z:
        F1 = F(z+p*t)
        c1 = F1.content()
        F1 //= c1
        if HasFinitePointAt(F1,p,(c*c1).squarefree_part()):
            return true
    return false
Exemplo n.º 48
0
def _spos_def_mats_lt(tpl):
    '''
    Returns an iterator of tuples.
    '''
    n, r, m = tpl
    for n1 in range(n + 1):
        for m1 in range(m + 1):
            a = 4 * (n - n1) * (m - m1)
            if r ** 2 <= a:
                yield (n1, 0, m1)
            sq = int(floor(2 * sqrt(n1 * m1)))
            for r1 in range(1, sq + 1):
                if (r - r1) ** 2 <= a:
                    yield (n1, r1, m1)
                if (r + r1) ** 2 <= a:
                    yield (n1, -r1, m1)
Exemplo n.º 49
0
 def __init__(self,group,dchar=(0,0),dual=False,is_trivial=False,dimension=1,**kwargs):
     if not ZZ(4).divides(group.level()):
         raise ValueError," Need level divisible by 4. Got:%s " % self._group.level()
     MultiplierSystem.__init__(self,group,dchar=dchar,dual=dual,is_trivial=is_trivial,dimension=dimension,**kwargs)
     self._i = CyclotomicField(4).gen()
     self._one = self._i**4
     self._weight= QQ(kwargs.get("weight",QQ(1)/QQ(2)))
     ## We have to make sure that we have the correct multiplier & character 
     ## for the desired weight
     if self._weight<>None:
         if floor(2*self._weight)<>ceil(2*self._weight):
             raise ValueError," Use ThetaMultiplier for half integral or integral weight only!"
         t = self.is_consistent(self._weight)
         if not t:
             self.set_dual()
             t1 = self.is_consistent(self._weight)    
             if not t1:
                 raise ArithmeticError,"Could not find consistent theta multiplier! Try to add a character."
Exemplo n.º 50
0
def list_zeros(N=None,
               t=None,
               limit=None,
               fmt=None,
               download=None):
    if N is None:
        N = request.args.get("N", None, int)
    if t is None:
        t = request.args.get("t", 0, float)
    if limit is None:
        limit = request.args.get("limit", 100, int)
    if fmt is None:
        fmt = request.args.get("format", "plain")
    if download is None:
        download = request.args.get("download", "no")

    if limit < 0:
        limit = 100
    if N is not None:  # None is < 0!! WHAT THE WHAT!
        if N < 0:
            N = 0
    if t < 0:
        t = 0

    if limit > 100000:
        # limit = 100000
        #
        bread = [("L-functions", url_for("l_functions.l_function_top_page")),("Zeros of $\zeta(s)$", url_for(".zetazeros"))]
        return render_template('single.html', title="Too many zeros", bread=bread, kid = "dq.zeros.zeta.toomany")

    if N is not None:
        zeros = zeros_starting_at_N(N, limit)
    else:
        zeros = zeros_starting_at_t(t, limit)

    if fmt == 'plain':
        response = flask.Response(("%d %s\n" % (n, nstr(z,31+floor(log(z,10))+1,strip_zeros=False,min_fixed=-inf,max_fixed=+inf)) for (n, z) in zeros))
        response.headers['content-type'] = 'text/plain'
        if download == "yes":
            response.headers['content-disposition'] = 'attachment; filename=zetazeros'
    else:
        response = str(list(zeros))

    return response
Exemplo n.º 51
0
def my_complex_latex(c,bitprec):
    x = c.real().n(bitprec)
    y = c.imag().n(bitprec)
    d = floor(bitprec/3.4)
    if x >= 0:
        prefx = "\\hphantom{-}"
    else:
        prefx = ""
    if y < 0:
        prefy = ""
    else:
        prefy = "+"
    xi,xf = str(x).split(".")
    xstr = "{0}.{1:0<{d}}".format(xi,xf,d=d)
    #print "xstr=",xstr
    yi,yf = str(y).split(".")
    ystr = "{0}.{1:0<{d}}".format(yi,yf,d=d)
    t = "{prefx}{x}{prefy}{y}i".format(prefx=prefx,x=xstr,prefy=prefy,y=ystr)
    return t
Exemplo n.º 52
0
def _number_of_bits(n):
    """
    Description:
        
        Returns the number of bits in the binary representation of n
    
    Input:
    
        n - integer
    
    Output:
    
        num_bits - number of bits
    
    """    
    if n == 0:
        return 1
    else:
        return floor(log(n).n()/log(2).n()) + 1
Exemplo n.º 53
0
    def __init__(self,args=[1],exponents=[1],ch=None,dual=False,version=1,**kwargs):
        r"""
        Initialize the Eta multiplier system: $\nu_{\eta}^{2(k+r)}$.
        INPUT:

        - G -- Group
        - ch -- character
        - dual -- if we have the dual (in this case conjugate)
        - weight -- Weight (recall that eta has weight 1/2 and eta**2k has weight k. If weight<>k we adjust the power accordingly.
        - number -- we consider eta^power (here power should be an integer so as not to change the weight...)

        EXAMPLE:
        
                
        """
        assert len(args) == len(exponents)
        self._level=lcm(args)
        G = Gamma0(self._level)
        k = sum([QQ(x)*QQ(1)/QQ(2) for x in exponents])
        self._weight=QQ(k)
        if floor(self._weight-QQ(1)/QQ(2))==ceil(self._weight-QQ(1)/QQ(2)):
            self._half_integral_weight=1
        else:
            self._half_integral_weight=0
        MultiplierSystem.__init__(self,G,dimension=1,character=ch,dual=dual)
        self._arguments = args
        self._exponents =exponents
        self._pow=QQ((self._weight)) ## k+r
        self._k_den = self._weight.denominator()
        self._k_num = self._weight.numerator()
        self._K = CyclotomicField(12*self._k_den)
        self._z = self._K.gen()**self._k_num
        self._i = CyclotomicField(4).gen()
        self._fak = CyclotomicField(2*self._k_den).gen()**-self._k_num
        self._version = version
        self.is_consistent(k) # test consistency
 def galois_decomposition(self):
     r"""
     We compose the new subspace into galois orbits of new cusp forms.
     """
     from sage.monoids.all import AlphabeticStrings
     if(len(self._galois_decomposition) != 0):
         return self._galois_decomposition
     if '_HeckeModule_free_module__decomposition' in self._newspace.__dict__:
         L = self._newspace.decomposition()
     else:
         decomp = self.newform_factors()
         if len(decomp)>0:
             L = filter(lambda x: x.is_new() and x.is_cuspidal(), decomp)
             wmf_logger.debug("found L:{0}".format(L))
         elif self._computation_too_hard():
             L = []
             raise IndexError,"No decomposition was found in the database!"
             wmf_logger.debug("no decomp in database!")
         else: # compute
             L = self._newspace.decomposition()
             wmf_logger.debug("newspace :".format(self._newspace))                                
             wmf_logger.debug("computed L:".format(L))
     self._galois_decomposition = L
     # we also label the compnents
     x = AlphabeticStrings().gens()
     for j in range(len(L)):
         if(j < 26):
             label = str(x[j]).lower()
         else:
             j1 = j % 26
             j2 = floor(QQ(j) / QQ(26))
             label = str(x[j1]).lower()
             label = label + str(j2)
         if label not in self._galois_orbits_labels:
             self._galois_orbits_labels.append(label)
     return L
Exemplo n.º 55
0
 def _dimension_formula(self,k,eps=1,cuspidal=1):
     ep = 0
     N = self._N
     if (2*k) % 4 == 1: ep = 1
     if (2*k) % 4 == 3: ep = -1
     if ep==0: return 0,0
     if eps==-1:
         ep = -ep
     twok = ZZ(2*k)
     K0 = 1
     sqf = ZZ(N).divide_knowing_divisible_by(squarefree_part(N))
     if sqf>12:
         b2 = max(sqf.divisors())
     else:
         b2 = 1
     b = sqrt(b2)
     if ep==1:
         K0 = floor(QQ(b+2)/QQ(2))
     else:
         # print "b=",b
         K0 = floor(QQ(b-1)/QQ(2))
     if is_even(N):
         e2 = ep*kronecker(2,twok)/QQ(4)
     else:
         e2 = 0
     N2 = odd_part(N)
     N22 = ZZ(N).divide_knowing_divisible_by(N2)
     k3 = kronecker(3,twok)
     if gcd(3,N)>1:
         if eps==1:
             e3 = -ep*kronecker(-3,4*k+ep-1)/QQ(3)
         else:
             e3 = -1*ep*kronecker(-3,4*k+ep+1)/QQ(3)
         #e3 = -1/3*ep
     else:
         f1 = kronecker(3,2*N22)*kronecker(-12,N2) - ep
         f2 = kronecker(-3,twok+1)
         e3 = f1*f2/QQ(6)
     ID = QQ(N+ep)*(k-1)/QQ(12)
     P = 0
     for d in ZZ(4*N).divisors():
         dm4=d % 4
         if dm4== 2 or dm4 == 1:
             h = 0
         elif d == 3:
             h = QQ(1)/QQ(3)
         elif d == 4:
             h = QQ(1)/QQ(2)
         else:
             h = class_nr_pos_def_qf(-d)
         if self._verbose>1:
             print "h({0})={1}".format(d,h)
         if h<>0:
             P= P + h
     P = QQ(P)/QQ(4)
     if self._verbose>0:
         print "P=",P
     P=P + QQ(ep)*kronecker(-4,N)/QQ(8)
     if eps==-1:
         P = -P
     if self._verbose>0:
         print "P=",P
     # P = -2*N**2 + N*(twok+10-ep*3) +(twok+10)*ep-1
     if self._verbose>0:
         print "ID=",ID
     P =  P - QQ(1)/QQ(2*K0)
     # P = QQ(P)/QQ(24) - K0
     # P = P - K0
     res = ID + P + e2 + e3
     if self._verbose>1:
         print "twok=",twok
         print "K0=",K0
         print "ep=",ep
         print "e2=",e2
         print "e3=",e3
         print "P=",P
     if cuspidal==0:
         res = res + K0
     return res   #,ep
Exemplo n.º 56
0
def _r_iter(n, m):
    sq = int(floor(2 * sqrt(n * m)))
    for r in range(-sq, sq + 1):
        yield r
Exemplo n.º 57
0
def BB(x):
    RF=RealField(100)
    x = RF(x)
    onehalf = RF(1)/2
    return x - onehalf*(floor(x)-floor(-x))