Exemplo n.º 1
0
    def representativeParameters(self):
        if self._representativeParameters :
            return self._representativeParameters

        initial = numerical_approx(self.pI) 
        final = numerical_approx(self.pF)
    
        curvature_Llam=[]
        linear_Llam=[]
        if self.curvature_plotpoints :
            print("Taking "+str(self.curvature_plotpoints)+" curvature points (can take a long time) ...")
            curvature_Llam=self.getRegularCurvatureParameter(initial,final,self.total_curvature()/self.curvature_plotpoints,initial_point=True,final_point=True)
            print("... done")
        if self.linear_plotpoints:
            import numpy
            # If not RR, the elements of Llam are type numpy.float64. In this case, computing the sqrt of negative return NaN instead of complex. Then we cannot remove the probably fake imaginary part. It happens for the function sqrt(cos(x)) with x=3*pi/2. 
            linear_Llam=[ RR(s) for s in  numpy.linspace(initial,final,self.linear_plotpoints)]
        Llam=[]
        Llam.extend(self.added_plotpoints)
        Llam.extend(linear_Llam)
        Llam.extend(curvature_Llam)
        Llam.sort()

        # seem to me that these two lines do not serve : (June 2017)
        #for llam in Llam:
        #    P=self.get_point(llam,advised=False)

        self._representativeParameters = Llam
        return Llam
Exemplo n.º 2
0
    def T(self, n):
        """
        Return matrix mod 2 of the n-th Hecke operator on the +1
        quotient of cuspidal modular symbols.

        INPUT:

            - `n` -- integer

        OUTPUT:

            matrix modulo 2

        EXAMPLES::

            sage: from mdsage import *
            sage: C = KamiennyCriterion(29)
            sage: C.T(2)
            22 x 22 dense matrix over Finite Field of size 2 (use the '.str()' method to see the entries)
            sage: C.T(2)[0]
            (1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1)
        """
        if self.verbose: tm = cputime(); mem = get_memory_usage(); print("T(%s) start" % (n))
        
        T = self.M.hecke_matrix(n).restrict(self.S_integral, check=False)
    
        if self.verbose: print("time and mem", cputime(tm), get_memory_usage(mem), "T created")
        if self.verbose: print("sparsity", len(T.nonzero_positions()) / RR(T.nrows()**2), T.nrows())
        T = matrix_modp(T)
        if self.verbose: print("time and mem", cputime(tm), get_memory_usage(mem), "T reduced")
        #self.M._hecke_matrices={}
        #self.S._hecke_matrices={}
        #if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "T freed"
        return matrix_modp(T)
Exemplo n.º 3
0
def make_y_coord(ainvs, x):
    a1, a2, a3, a4, a6 = ainvs
    f = ((x + a2) * x + a4) * x + a6
    b = (a1 * x + a3)
    d = (RR(b * b + 4 * f)).sqrt()
    y = ZZ((-b + d) / 2)
    return y, ZZ(d)
Exemplo n.º 4
0
def _draw_funddom_d(coset_reps,format="MP",z0=I):
    r""" Draw a fundamental domain for self in the circle model
    INPUT:
    - ''format''  -- (default 'Disp') How to present the f.d.
    =  'S'  -- Display directly on the screen
    - z0          -- (default I) the upper-half plane is mapped to the disk by z-->(z-z0)/(z-z0.conjugate())
    EXAMPLES::
        

    sage: G=MySubgroup(Gamma0(3))
    sage: G._draw_funddom_d()
        
    """
    # The fundamental domain consists of copies of the standard fundamental domain
    pi=RR.pi()
    from sage.plot.plot import (Graphics,line)
    g=Graphics()
    bdcirc=_circ_arc(0 ,2 *pi,0 ,1 ,1000 )
    g=g+bdcirc
    # Corners
    x1=-RR(0.5) ; y1=RR(sqrt(3 )/2)
    x2=RR(0.5) ; y2=RR(sqrt(3 )/2)
    z_inf=1 
    l1 = _geodesic_between_two_points_d(x1,y1,x1,infinity)
    l2 = _geodesic_between_two_points_d(x2,y2,x2,infinity)
    c0 = _geodesic_between_two_points_d(x1,y1,x2,y2)
    tri=c0+l1+l2
    g=g+tri
    for A in coset_reps:
        [a,b,c,d]=A
        if(a==1  and b==0  and c==0  and d==1 ):
            continue
        if(a<0 ):
            a=-a; b=-b; c=-c; d=-1 
        if(c==0 ): # then this is easier
            l1 = _geodesic_between_two_points_d(x1+b,y1,x1+b,infinity)
            l2 = _geodesic_between_two_points_d(x2+b,y2,x2+b,infinity)
            c0 = _geodesic_between_two_points_d(x1+b,y1,x2+b,y2)
            # c0=line(L0); l1=line(L1); l2=line(L2); l3=line(L3)
            tri=c0+l1+l2
            g=g+tri
        else:
            den=(c*x1+d)**2 +c**2 *y1**2 
            x1_t=(a*c*(x1**2 +y1**2 )+(a*d+b*c)*x1+b*d)/den
            y1_t=y1/den
            den=(c*x2+d)**2 +c**2 *y2**2 
            x2_t=(a*c*(x2**2 +y2**2 )+(a*d+b*c)*x2+b*d)/den
            y2_t=y2/den
            inf_t=a/c
            c0=_geodesic_between_two_points_d(x1_t,y1_t,x2_t,y2_t)
            c1=_geodesic_between_two_points_d(x1_t,y1_t,inf_t,0.0 )
            c2=_geodesic_between_two_points_d(x2_t,y2_t,inf_t,0.0 )
            tri=c0+c1+c2
            g=g+tri
    g.xmax(1 )
    g.ymax(1 )
    g.xmin(-1 )
    g.ymin(-1 )
    g.set_aspect_ratio(1 )
    return g
Exemplo n.º 5
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.º 6
0
def _draw_funddom(coset_reps,format="S"):
    r""" Draw a fundamental domain for G.
    
    INPUT:
    
    - ``format``  -- (default 'Disp') How to present the f.d.
    -   ``S`` -- Display directly on the screen
    
    EXAMPLES::        


    sage: G=MySubgroup(Gamma0(3))
    sage: G._draw_funddom()
        
    """
    pi=RR.pi()
    pi_3 = pi / RR(3.0)
    from sage.plot.plot import (Graphics,line)
    from sage.functions.trig import (cos,sin)
    g=Graphics()
    x1=RR(-0.5) ; y1=RR(sqrt(3 )/2 )
    x2=RR(0.5) ; y2=RR(sqrt(3 )/2 )
    xmax=RR(20.0) 
    l1 = line([[x1,y1],[x1,xmax]])
    l2 = line([[x2,y2],[x2,xmax]])
    l3 = line([[x2,xmax],[x1,xmax]]) # This is added to make a closed contour
    c0=_circ_arc(RR(pi/3.0) ,RR(2.0*pi)/RR(3.0) ,0 ,1 ,100 )
    tri=c0+l1+l3+l2
    g=g+tri
    for A in coset_reps:
        [a,b,c,d]=A
        if(a==1  and b==0  and c==0  and d==1 ):
            continue
        if(a<0 ):
            a=RR(-a); b=RR(-b); c=RR(-c); d=RR(-d) 
        else:
            a=RR(a); b=RR(b); c=RR(c); d=RR(d) 
        if(c==0 ): # then this is easier
            L0 = [[cos(pi_3*RR(i/100.0))+b,sin(pi_3*RR(i/100.0))] for i in range(100 ,201 )]
            L1 = [[x1+b,y1],[x1+b,xmax]]
            L2 = [[x2+b,y2],[x2+b,xmax]]
            L3 = [[x2+b,xmax],[x1+b,xmax]]
            c0=line(L0); l1=line(L1); l2=line(L2); l3=line(L3)
            tri=c0+l1+l3+l2
            g=g+tri
        else:
            den=(c*x1+d)**2 +c**2 *y1**2 
            x1_t=(a*c*(x1**2 +y1**2 )+(a*d+b*c)*x1+b*d)/den
            y1_t=y1/den
            den=(c*x2+d)**2 +c**2 *y2**2 
            x2_t=(a*c*(x2**2 +y2**2 )+(a*d+b*c)*x2+b*d)/den
            y2_t=y2/den
            inf_t=a/c
            c0=_geodesic_between_two_points(x1_t,y1_t,x2_t,y2_t)
            c1=_geodesic_between_two_points(x1_t,y1_t,inf_t,0. )
            c2=_geodesic_between_two_points(x2_t,y2_t,inf_t,0.0)
            tri=c0+c1+c2
            g=g+tri
    return g
Exemplo n.º 7
0
 def cnf(self):
     if self.degree()==1:
         return r'=\frac{2^1\cdot (2\pi)^0 \cdot 1\cdot 1}{2\sqrt 1}=1$'
     if not self.haskey('class_group'):
         return r'$<td>  '+na_text()
     # Otherwise we should have what we need
     [r1,r2] = self.signature()
     reg = self.regulator()
     h = self.class_number()
     w = self.root_of_1_order()
     r1term= r'2^{%s}\cdot'% r1
     r2term= r'(2\pi)^{%s}\cdot'% r2
     disc = ZZ(self._data['disc_abs'])
     approx1 = r'\approx' if self.unit_rank()>0 else r'='
     ltx = r'%s\frac{%s%s %s \cdot %s}{%s\sqrt{%s}}'%(approx1,r1term,r2term,str(reg),h,w,disc)
     ltx += r'\approx %s$'%(2**r1*(2*RR(pi))**r2*reg*h/(w*sqrt(RR(disc))))
     return ltx
Exemplo n.º 8
0
def _circ_arc(t0, t1, c, r, num_pts=5000):
    r""" Circular arc
    INPUTS:
    - ''t0'' -- starting parameter
    - ''t1'' -- ending parameter
    - ''c''  -- center point of the circle
    - ''r''  -- radius of circle
    - ''num_pts''  -- (default 100) number of points on polygon
    OUTPUT:
    - ''ca'' -- a polygonal approximation of a circular arc centered
    at c and radius r, starting at t0 and ending at t1

    
    EXAMPLES::

        sage: ca=_circ_arc(0.1,0.2,0.0,1.0,100)
    
    """
    from sage.plot.plot import line, parametric_plot
    from sage.functions.trig import (cos, sin)
    from sage.all import var
    t00 = t0
    t11 = t1
    ## To make sure the line is correct we reduce all arguments to the same branch,
    ## e.g. [0,2pi]
    pi = RR.pi()
    while (t00 < 0.0):
        t00 = t00 + RR(2.0 * pi)
    while (t11 < 0):
        t11 = t11 + RR(2.0 * pi)
    while (t00 > 2 * pi):
        t00 = t00 - RR(2.0 * pi)
    while (t11 > 2 * pi):
        t11 = t11 - RR(2.0 * pi)

    xc = CC(c).real()
    yc = CC(c).imag()
    num_pts = 3
    t = var('t')
    if t11 > t00:
        ca = parametric_plot((r * cos(t) + xc, r * sin(t) + yc), (t, t00, t11))
    else:
        ca = parametric_plot((r * cos(t) + xc, r * sin(t) + yc), (t, t11, t00))
    #L0 = [[RR(r*cos(t00+i*(t11-t00)/num_pts))+xc,RR(r*sin(t00+i*(t11-t00)/num_pts))+yc] for i in range(0 ,num_pts)]
    #ca=line(L0)
    return ca
Exemplo n.º 9
0
def cli_handler(args):  # pylint: disable=redefined-outer-name

    f = R(args.f)

    K = NumberField(f, name="a")

    loglevel = logging.DEBUG if args.verbose else logging.INFO
    logging.basicConfig(
        format="%(asctime)s %(levelname)s: %(message)s",
        datefmt="%H:%M:%S",
        level=loglevel,
    )
    logging.debug("Debugging level for log messages set.")

    if args.dlmv:
        dlmv_bound = DLMV(K)
        logging.info(
            "DLMV bound for {} is:\n\n{}\n\nwhich is approximately {}".format(
                K, dlmv_bound, RR(dlmv_bound)))
    else:
        logging.warning(
            "Only checking Type 2 primes up to %s. "
            "To check all, use the PARI/GP script.",
            args.bound,
        )

        if args.norm_bound:
            norm_bound = args.norm_bound
            auto_stop_strategy = False
        else:
            norm_bound = 50  # still needed for Type 1
            auto_stop_strategy = True

        superset, type_3_fields = get_isogeny_primes(
            K,
            args.bound,
            args.ice,
            args.appendix_bound,
            norm_bound=norm_bound,
            auto_stop_strategy=auto_stop_strategy,
        )

        superset_list = list(superset)
        superset_list.sort()
        logging.info(f"superset = {superset_list}")

        possible_new_isog_primes = superset - EC_Q_ISOGENY_PRIMES
        possible_new_isog_primes_list = list(possible_new_isog_primes)
        possible_new_isog_primes_list.sort()
        logging.info(
            f"Possible new isogeny primes = {possible_new_isog_primes_list}")
        if type_3_fields:
            how_many_fields = len(type_3_fields)
            logging.info(
                f"Outside of the above set, any isogeny primes must be "
                f"of Momose Type 3 with imaginary quadratic field L, for L one "
                f"of the following {how_many_fields} field(s):\n {type_3_fields}"
            )
Exemplo n.º 10
0
def allbsd(line):
    r""" Parses one line from an allbsd file.  Returns the label and a
    dict containing fields with keys 'conductor', 'iso', 'number',
    'ainvs', 'rank', 'torsion', 'torsion_primes', 'tamagawa_product',
    'real_period', 'special_value', 'regulator', 'sha_an', 'sha',
    'sha_primes', all values being strings or floats or ints or lists
    of ints.

    Input line fields:

    conductor iso number ainvs rank torsion tamagawa_product real_period special_value regulator sha_an

    Sample input line:

    11 a 1 [0,-1,1,-10,-20] 0 5 5 1.2692093042795534217 0.25384186085591068434 1 1.00000000000000000000

    """
    data = split(line)
    label = data[0] + data[1] + data[2]
    ainvs = parse_ainvs(data[3])

    torsion = ZZ(data[5])
    sha_an = RR(data[10])
    sha = sha_an.round()
    sha_primes = sha.prime_divisors()
    torsion_primes = torsion.prime_divisors()

    data = {
        'conductor': int(data[0]),
        'iso': data[0] + data[1],
        'number': int(data[2]),
        'ainvs': ainvs,
        'rank': int(data[4]),
        'tamagawa_product': int(data[6]),
        'real_period': float(data[7]),
        'special_value': float(data[8]),
        'regulator': float(data[9]),
        'sha_an': float(sha_an),
        'sha':  int(sha),
        'sha_primes':  [int(p) for p in sha_primes],
        'torsion':  int(torsion),
        'torsion_primes':  [int(p) for p in torsion_primes]
        }

    return label, data
Exemplo n.º 11
0
def allbsd(line):
    r""" Parses one line from an allbsd file.  Returns the label and a
    dict containing fields with keys 'conductor', 'iso', 'number',
    'ainvs', 'rank', 'torsion', 'torsion_primes', 'tamagawa_product',
    'real_period', 'special_value', 'regulator', 'sha_an', 'sha',
    'sha_primes', all values being strings or floats or ints or lists
    of ints.

    Input line fields:

    conductor iso number ainvs rank torsion tamagawa_product real_period special_value regulator sha_an

    Sample input line:

    11 a 1 [0,-1,1,-10,-20] 0 5 5 1.2692093042795534217 0.25384186085591068434 1 1.00000000000000000000

    """
    data = split(line)
    label = data[0] + data[1] + data[2]
    ainvs = parse_ainvs(data[3])

    torsion = ZZ(data[5])
    sha_an = RR(data[10])
    sha = sha_an.round()
    sha_primes = sha.prime_divisors()
    torsion_primes = torsion.prime_divisors()

    data = {
        'conductor': int(data[0]),
        'iso': data[0] + data[1],
        'number': int(data[2]),
        'ainvs': ainvs,
        'rank': int(data[4]),
        'tamagawa_product': int(data[6]),
        'real_period': float(data[7]),
        'special_value': float(data[8]),
        'regulator': float(data[9]),
        'sha_an': float(sha_an),
        'sha': int(sha),
        'sha_primes': [int(p) for p in sha_primes],
        'torsion': int(torsion),
        'torsion_primes': [int(p) for p in torsion_primes]
    }

    return label, data
Exemplo n.º 12
0
def _geodesic_between_two_points(x1, y1, x2, y2):
    r""" Geodesic path between two points hyperbolic upper half-plane

    INPUTS:

    - ''(x1,y1)'' -- starting point (0<y1<=infinity)
    - ''(x2,y2)'' -- ending point   (0<y2<=infinity)
    - ''z0''  -- (default I) the point in the upper corresponding
                 to the point 0 in the disc. I.e. the transform is
                 w -> (z-I)/(z+I)
    OUTPUT:

    - ''ca'' -- a polygonal approximation of a circular arc centered
    at c and radius r, starting at t0 and ending at t1


    EXAMPLES::


        sage: l=_geodesic_between_two_points(0.1,0.2,0.0,0.5)

    """
    pi = RR.pi()
    from sage.plot.plot import line
    from sage.functions.trig import arcsin

    # logging.debug("z1=%s,%s" % (x1,y1))
    # logging.debug("z2=%s,%s" % (x2,y2))
    if abs(x1 - x2) < 1e-10:
        # The line segment [x=x1, y0<= y <= y1]
        return line([[x1, y1], [x2, y2]])  # [0,0,x0,infinity]
    c = RR(y1 ** 2 - y2 ** 2 + x1 ** 2 - x2 ** 2) / RR(2 * (x1 - x2))
    r = RR(sqrt(y1 ** 2 + (x1 - c) ** 2))
    r1 = RR(y1 / r)
    r2 = RR(y2 / r)
    if abs(r1 - 1) < 1e-12:
        r1 = RR(1.0)
    elif abs(r2 + 1) < 1e-12:
        r2 = -RR(1.0)
    if abs(r2 - 1) < 1e-12:
        r2 = RR(1.0)
    elif abs(r2 + 1) < 1e-12:
        r2 = -RR(1.0)
    if x1 >= c:
        t1 = RR(arcsin(r1))
    else:
        t1 = RR(pi) - RR(arcsin(r1))
    if x2 >= c:
        t2 = RR(arcsin(r2))
    else:
        t2 = RR(pi) - arcsin(r2)
    # tmid = (t1 + t2) * RR(0.5)
    # a0 = min(t1, t2)
    # a1 = max(t1, t2)
    # logging.debug("c,r=%s,%s" % (c,r))
    # logging.debug("t1,t2=%s,%s"%(t1,t2))
    return _circ_arc(t1, t2, c, r)
Exemplo n.º 13
0
def compare_formulas_2a(D, k):
    d1 = dimension_new_cusp_forms(kronecker_character(D), k)
    if D < 0:
        D = -D
    d2 = RR(1 / pi * sqrt(D) * sum([
        log(d) * sigma(old_div(D, d), 0) for d in divisors(D) if Zmod(d)
        (old_div(D, d)).is_square() and is_fundamental_discriminant(-d)
    ]))
    return d1 - d2
Exemplo n.º 14
0
 def Cn_symmetric_k_points(n,k, alpha=Integer(1) ):   
     n = Integer(n)
     k = Integer(k) 
     if not mod(k,n) in [Integer(0) ,Integer(1) ]:
         raise ValueError('Only possible if k mod n in {{0,1}}, here {} mod {} = {}.'.format(k,n,mod(k,n)))
     res = {
             i : vector([RR(cos(RR(Integer(2) *pi*i)/n)),RR(sin(RR(Integer(2) *pi*i)/n))]) for i in range(Integer(0) ,n)
         }
     N = k
     if mod(k,n)==Integer(1) :
         res[N-Integer(1) ] = vector([Integer(0) ,Integer(0) ])
         N = N-Integer(1) 
     for i in range(n,N):
         r = (i-i%n)/n +Integer(1) 
         res[i] = r*res[i%n]
     for i in res:
         res[i] = alpha*vector([res[i][Integer(0) ], res[i][Integer(1) ]])
     return [res[i] for i in sorted(res.keys())]
Exemplo n.º 15
0
def findrotationmulticiphertexts(lwe_n, q, sd, B, m, name):
    n = 2 * RR(lwe_n)
    q = RR(q)
    B = RR(B)
    vars = RR(sd**2)
    varc = vars

    #####################
    #  precalculations  #
    #####################

    # qt
    qt = q / 2**(B + 1)

    # |s| and |c*|
    norms = ZZ(ceil(sqrt(n *
                         vars)))  # This is an approximation of the mean value
    normc = norms

    ##################
    #  calculations  #
    ##################
    numsucces = 0
    for CIPHERTEXTS in [3, 4, 5]:
        results = []

        import pathos
        pool = pathos.pools._ProcessPool(4, maxtasksperchild=1)
        results = pool.map(
            lambda x: findonemulticiphertextrotation(n, varc, CIPHERTEXTS, qt,
                                                     norms), range(0, TESTS))
        pool.terminate()
        pool.join()

        numsucces = np.sum(results)

        print(
            'experimental probability of combining %d ciphertexts in %d rounds, succesprob %f'
            % (CIPHERTEXTS, REP, numsucces / TESTS))
        with open(name + '/findingfailurelocation.txt', 'a') as f:
            print(
                'experimental probability of combining %d ciphertexts in %d rounds, succesprob %f'
                % (CIPHERTEXTS, REP, numsucces / TESTS),
                file=f)
Exemplo n.º 16
0
    def ghf(cls, m, p, klen_list, prec=53):
        """
        Estimate norm of shortest vector according to Gaussian Heuristic.

        :param m: number of samples
        :param p: ECDSA modulus
        :param klen_list: list of lengths of key to recover
        :param prec: precision to use

        """
        # NOTE: The Gaussian Heuristic does not hold in small dimensions
        w = 2 ** (max(klen_list) - 1)
        RR = RealField(prec)
        w = RR(w)
        f_list = [Integer(w / (2 ** (klen - 1))) for klen in klen_list]
        d = m + 1
        log_vol = log(p) * (m - 1) + sum(map(log, f_list)) + log(w)
        lgh = log_gamma(1 + d / 2.0) * (1.0 / d) - log(sqrt(pi)) + log_vol * (1.0 / d)
        return RR(exp(lgh))
Exemplo n.º 17
0
def compare_floats(a, b, prec=52):
    if a == b:
        return True
    if None in [a, b]:
        return False
    if b == 0:
        b, a = a, b
    if a == 0:
        return b == 0 or abs(b) < 1e-60
    else:
        return RR(abs((a - b) / a)).log(2) < -prec
Exemplo n.º 18
0
def formtest_2(minD, maxD):
    s = 0
    for D in range(minD, maxD):
        if is_fundamental_discriminant(-D):
            for d in divisors(D):
                if is_fundamental_discriminant(-d):
                    sd = RR(
                        RR(1) / RR(6) * (RR(d) + old_div(RR(D), RR(d))) -
                        RR(sqrt(D)) / RR(pi) * log(d))
                    print(D, d, sd)
                    s += sd
        if s <= 0:
            print("s= {0}  D={1}".format(s, D))
Exemplo n.º 19
0
def RIF_to_float(x):
    x = RRR(x)
    if x.contains_zero():
        return int(0)
    else:
        fx = float(x)
        if fx == Infinity:
            return repr(RR(x))
        else:
            return float(x)
        return float(x)
Exemplo n.º 20
0
def ratproc(inp):
    if '.' in inp:
        inp = RR(inp)
    qs = QQ(inp)
    sstring = str(qs*1.)
    sstring += '0'*14
    if qs < 10:
        sstring = '0'+sstring
    sstring = sstring[0:12]
    sstring += str(qs)
    return sstring
Exemplo n.º 21
0
def babai_probability_wun16(r, norm):
    """
     Compute the probability of Babai's Nearest Plane, using techniques from the NTRULPrime submission to NIST

     :param r: squared GSO lengths
     :param norm: expected norm of the target vector

     """
    R = [RR(sqrt(t) / (2 * norm)) for t in r]
    T = RealDistribution('beta', ((len(r) - 1) / 2, 1. / 2))
    probs = [1 - T.cum_distribution_function(1 - s**2) for s in R]
    return prod(probs)
Exemplo n.º 22
0
def dirichlet(R, euler_factors):
    PS = PowerSeriesRing(R)
    pef = zip(primes_first_n(len(euler_factors)), euler_factors)
    an_list_bound = next_prime(pef[-1][0])
    res = [1]*an_list_bound
    for p, ef in pef:
        k = RR(an_list_bound).log(p).floor()+1
        foo = (1/PS(ef)).padded_list(k)
        for i in range(1, k):
            res[p**i] = foo[i]
    extend_multiplicatively(res)
    return res
Exemplo n.º 23
0
def RIF_to_float(x):
    x = RRR(x)
    if x.contains_zero():
        return 0
    elif x.abs() < 1e-70:
        return 0
    else:
        fx = float(x)
        if fx == Infinity or fx == -Infinity:
            return repr(RR(x))
        else:
            return float(x)
Exemplo n.º 24
0
def draw_funddom(coset_reps, format="S"):
    r""" Draw a fundamental domain for G.
    
    INPUT:
    
    - ``format``  -- (default 'Disp') How to present the f.d.
    -   ``S`` -- Display directly on the screen
    
    EXAMPLES::        


    sage: G=MySubgroup(Gamma0(3))
    sage: G._draw_funddom()
        
    """
    pi = RR.pi()
    pi_3 = pi / RR(3.0)
    from sage.plot.plot import (Graphics, line)
    from sage.functions.trig import (cos, sin)
    g = Graphics()
    x1 = RR(-0.5)
    y1 = RR(sqrt(3) / 2)
    x2 = RR(0.5)
    y2 = RR(sqrt(3) / 2)
    xmax = RR(20.0)
    l1 = line([[x1, y1], [x1, xmax]])
    l2 = line([[x2, y2], [x2, xmax]])
    l3 = line([[x2, xmax], [x1,
                            xmax]])  # This is added to make a closed contour
    c0 = _circ_arc(RR(pi / 3.0), RR(2.0 * pi) / RR(3.0), 0, 1, 100)
    tri = c0 + l1 + l3 + l2
    g = g + tri
    for A in coset_reps:
        if list(A) == [1, 0, 0, 1]:
            continue

        tri = draw_transformed_triangle_H(A, xmax=xmax)
        g = g + tri
    return g
Exemplo n.º 25
0
    def dlmv_table(self):
        """generate the dlmv table"""

        output_str = (
            r"${Delta_K}$ & $\Q(\sqrt{{{D}}})$ & ${rem} \times 10^{{{exp_at_10}}}$\\"
        )
        for D in range(-self.range, self.range + 1):
            if Integer(D).is_squarefree():
                if not D in CLASS_NUMBER_ONE_DISCS:
                    if D != 1:
                        K = QuadraticField(D)
                        Delta_K = K.discriminant()
                        dlmv_bound = RR(DLMV(K))
                        log_dlmv_bound = dlmv_bound.log10()
                        exp_at_10 = int(log_dlmv_bound)
                        rem = log_dlmv_bound - exp_at_10
                        rem = 10**rem
                        rem = rem.numerical_approx(digits=3)
                        output_here = output_str.format(Delta_K=Delta_K,
                                                        D=D,
                                                        rem=rem,
                                                        exp_at_10=exp_at_10)
                        print(output_here)
Exemplo n.º 26
0
    def volf(cls, m, p, klen_list, prec=53):
        """
        Lattice volume.

        :param m: number of samples
        :param p: ECDSA modulus
        :param klen_list: list of lengths of key to recover
        :param prec: precision to use

        """
        w = 2 ** (max(klen_list) - 1)
        RR = RealField(prec)
        f_list = [Integer(w / (2 ** (klen - 1))) for klen in klen_list]
        return RR(exp(log(p) * (m - 1) + sum(map(log, f_list)) + log(w)))
Exemplo n.º 27
0
def prime_pol(s, p, k):
    A = RR(s.order())
    A2 = RR(s.torsion(2))
    A3 = RR(s.torsion(3))
    p = RR(p)
    k = RR(k)

    return A * (p**2 - 1) * (k - 1) / 24 - A2 / 2 \
             - (2 + 2 * A3) / (3 * RR(3).sqrt()) - 3 * (p-1) * A / 2
Exemplo n.º 28
0
def test_sigma_rep(Dmin=1, Dmax=1000, print_divisors=False):
    n = 0
    sa = 0
    sw = [1, 0]
    sm = [1, 0]
    for D in range(Dmin, Dmax):
        if is_fundamental_discriminant(-D):
            n += 1
            sr = sigma_rep(D, True)
            sa += sr
            sm[1] = max(sr, sm[1])
            swt = old_div(sr, D)
            sw[1] = max(swt, RR(sw[1]))
            if sm[1] == sr:
                sm[0] = -D
            if sw[1] == swt:
                sw[0] = -D
            ct = RR(100) * (RR(D)**(old_div(1.0, 25)))
            #if ct<=RR(sr):
            print(-D, sr, ct, sigma(D, 0))
    sa = old_div(sa, n)
    print("Max: {0}".format(sm))
    print("Avg: {0}, {1}".format(sa, RR(sa)))
    print("Worst case: {0}".format(sw))
Exemplo n.º 29
0
def showMatrix(rewards, cards1, cards2):
    result = []
    for r in range(len(rewards)):
        payoffMatrix = createPayoffMatrix(rewards, r, cards1, cards2)
        result.append(solveNash(payoffMatrix)[1])

    decimal_result = []
    for r in range(len(result)):
        decimal_result.append([])
        for c in range(len(result[r])):
            decimal_result[-1].append("%.4f" % RR(result[c][r]))

    for c in decimal_result:
        print(c)
    return decimal_result
Exemplo n.º 30
0
def add_sha_tor_primes(N1, N2):
    """
    Add the 'sha', 'sha_primes', 'torsion_primes' fields to every
    curve in the database whose conductor is between N1 and N2
    inclusive.
    """
    query = {}
    query['conductor'] = {'$gte': int(N1), '$lte': int(N2)}
    res = curves.find(query)
    res = res.sort([('conductor', pymongo.ASCENDING)])
    n = 0
    for C in res:
        label = C['lmfdb_label']
        if n % 1000 == 0: print label
        n += 1
        torsion = ZZ(C['torsion'])
        sha = RR(C['sha_an']).round()
        sha_primes = sha.prime_divisors()
        torsion_primes = torsion.prime_divisors()
        data = {}
        data['sha'] = int(sha)
        data['sha_primes'] = [int(p) for p in sha_primes]
        data['torsion_primes'] = [int(p) for p in torsion_primes]
        curves.update({'lmfdb_label': label}, {"$set": data}, upsert=True)
Exemplo n.º 31
0
def add_sha_tor_primes(N1,N2):
    """
    Add the 'sha', 'sha_primes', 'torsion_primes' fields to every
    curve in the database whose conductor is between N1 and N2
    inclusive.
    """
    query = {}
    query['conductor'] = { '$gte': int(N1), '$lte': int(N2) }
    res = curves.find(query)
    res = res.sort([('conductor', pymongo.ASCENDING)])
    n = 0
    for C in res:
        label = C['lmfdb_label']
        if n%1000==0: print label
        n += 1
        torsion = ZZ(C['torsion'])
        sha = RR(C['sha_an']).round()
        sha_primes = sha.prime_divisors()
        torsion_primes = torsion.prime_divisors()
        data = {}
        data['sha'] = int(sha)
        data['sha_primes'] = [int(p) for p in sha_primes]
        data['torsion_primes'] = [int(p) for p in torsion_primes]
        curves.update({'lmfdb_label': label}, {"$set": data}, upsert=True)
Exemplo n.º 32
0
    def build_poly(vts, ts, is_max_plus):
        """
        Build a MPP convex polyhedron over vts and
        return a set of constraints

        Examples:
        sage: var('y')
        y
        sage: rs = IeqMPPGen.build_poly([[0,0,0],[3,3,0]], [x,y,SR(0)], is_max_plus=True)
        dig_polynomials:Debug:Build (gen max-plus) poly from 2 vts in 3 dims: [x, y, 0]
        sage: print '\n'.join(map(str,sorted(rs)))
        ('lambda x,y: -x + y >= 0', 'y >= x')
        ('lambda x,y: x - y >= 0', 'x >= y')
        ('lambda x: -x + 3 >= 0', '0 >= x - 3')
        ('lambda x: x >= 0', 'x >= 0')
        ('lambda y: -y + 3 >= 0', '0 >= y - 3')
        ('lambda y: y >= 0', 'y >= 0')
        """

        opt_arg = ''

        if is_max_plus:
            mpp_str = 'max-plus'
        else:
            mpp_str = 'min-plus'
            opt_arg = "{} {}".format(opt_arg, '-{}'.format(mpp_str))

        # if any vertex is float
        if any(any(not SR(v).is_integer() for v in vt) for vt in vts):
            vts = [[RR(v).n() for v in vt] for vt in vts]
            opt_arg = "{} -numerical-data ocaml_float".format(opt_arg)

        # exec external program
        # important, has to end with newline \n !!!
        vts_s = '\n'.join(str(vt).replace(' ', '') for vt in vts) + '\n'
        logger.debug('Build (gen {}) poly from {} vts in {} dims: {}'.format(
            mpp_str, len(vts), len(vts[0]), ts))

        cmd = 'compute_ext_rays_polar {} {}'.format(opt_arg, len(vts[0]))
        rs, _ = vcmd(cmd, vts_s)
        rs = [sage_eval(s.replace('oo', 'Infinity')) for s in rs.split()]

        rs = IeqMPPGen.group_rs(rs)

        rs = map(lambda ls: [x + y for x, y in zip(ls, ts + ts)], rs)
        rs = map(lambda ls: IeqMPP.sparse(ls, is_max_plus), rs)
        rs = filter(None, rs)
        return rs
Exemplo n.º 33
0
def compute_kernel(args):
    if args.seed is not None:
        set_random_seed(args.seed)
        FPLLL.set_random_seed(args.seed)

    ecdsa = ECDSA(nbits=args.nlen)

    lines, k_list, _ = ecdsa.sample(m=args.m, klen_list=args.klen_list, seed=args.seed, errors=args.e)
    w_list = [2 ** (klen - 1) for klen in args.klen_list]
    f_list = [Integer(max(w_list) / wi) for wi in w_list]

    targetvector = vector([(k - w) * f for k, w, f in zip(k_list, w_list, f_list)] + [max(w_list)])

    try:
        solver = ECDSASolver(ecdsa, lines, m=args.m, d=args.d, threads=args.threads)
    except KeyError:
        raise ValueError("Algorithm {alg} unknown".format(alg=args.alg))

    expected_length = solver.evf(args.m, max(args.klen_list), prec=args.nlen // 2)
    gh = solver.ghf(args.m, ecdsa.n, args.klen_list, prec=args.nlen // 2)
    params = args.params if args.params else {}
    key, res = solver(solver=args.algorithm, flavor=args.flavor, **params)

    RR = RealField(args.nlen // 2)
    logging.info(
        (
            "try: {i:3d}, tag: 0x{tag:016x}, success: {success:1d}, "
            "|v|: 2^{v:.2f}, |b[0]|: 2^{b0:.2f}, "
            "|v|/|b[0]|: {b0r:.3f}, "
            "E|v|/|b[0]|: {eb0r:.3f}, "
            "|v|/E|b[0]|: {b0er:.3f}, "
            "cpu: {cpu:10.1f}s, "
            "wall: {wall:10.1f}s, "
            "work: {total:d}"
        ).format(
            i=args.i,
            tag=args.tag,
            success=int(res.success),
            v=float(log(RR(targetvector.norm()), 2)),
            b0=float(log(RR(res.b0), 2)),
            b0r=float(RR(targetvector.norm()) / RR(res.b0)),
            eb0r=float(RR(expected_length) / RR(res.b0)),
            b0er=float(RR(targetvector.norm()) / gh),
            cpu=float(res.cputime),
            wall=float(res.walltime),
            total=res.ntests,
        )
    )

    return key, res, float(targetvector.norm())
Exemplo n.º 34
0
def _circ_arc(t0, t1, c, r, num_pts=500):
    r""" Circular arc
    INPUTS:
    - ''t0'' -- starting parameter
    - ''t1'' -- ending parameter
    - ''c''  -- center point of the circle
    - ''r''  -- radius of circle
    - ''num_pts''  -- (default 100) number of points on polygon
    OUTPUT:
    - ''ca'' -- a polygonal approximation of a circular arc centered
    at c and radius r, starting at t0 and ending at t1


    EXAMPLES::

        sage: ca=_circ_arc(0.1,0.2,0.0,1.0,100)

    """
    from sage.plot.plot import parametric_plot
    from sage.functions.trig import cos, sin
    from sage.all import var

    t00 = t0
    t11 = t1
    ## To make sure the line is correct we reduce all arguments to the same branch,
    ## e.g. [0,2pi]
    pi = RR.pi()
    while t00 < 0.0:
        t00 = t00 + RR(2.0 * pi)
    while t11 < 0:
        t11 = t11 + RR(2.0 * pi)
    while t00 > 2 * pi:
        t00 = t00 - RR(2.0 * pi)
    while t11 > 2 * pi:
        t11 = t11 - RR(2.0 * pi)

    xc = CC(c).real()
    yc = CC(c).imag()
    # L0 =
    # [[RR(r*cos(t00+i*(t11-t00)/num_pts))+xc,RR(r*sin(t00+i*(t11-t00)/num_pts))+yc]
    # for i in range(0 ,num_pts)]
    t = var("t")
    if t11 > t00:
        ca = parametric_plot((r * cos(t) + xc, r * sin(t) + yc), (t, t00, t11))
    else:
        ca = parametric_plot((r * cos(t) + xc, r * sin(t) + yc), (t, t11, t00))
    return ca
Exemplo n.º 35
0
    def build_poly(vts, ts, is_max_plus):
        """
        Build a MPP convex polyhedron over vts and
        return a set of constraints

        Examples:

        sage: logger.set_level(VLog.DEBUG)
        sage: IeqMPP.build_poly([[0,0,0],[3,3,0]], is_max_plus=True)
        dig_polynomials:Debug:Ieq: Build (MPP max-plus) polyhedra from  2 vertices in 3 dim
        ['[-oo,0,-oo,-oo,-oo,0]', '[0,-oo,-oo,-oo,-oo,0]', '[0,-oo,-oo,-oo,-oo,-oo]',
        '[-oo,0,-oo,-oo,-oo,-oo]', '[-oo,-oo,0,-oo,-oo,-oo]', '[-oo,-oo,0,-oo,-oo,0]',
        '[-oo,-oo,0,-oo,-3,-oo]', '[-oo,-oo,0,-3,-oo,-oo]', '[-oo,0,-oo,-oo,0,-oo]',
        '[-oo,0,-oo,0,-oo,-oo]', '[0,-oo,-oo,-oo,0,-oo]', '[0,-oo,-oo,0,-oo,-oo]']

        """
        opt_arg = ''

        if is_max_plus:
            mpp_str = 'max-plus'
        else:
            mpp_str = 'min-plus'
            opt_arg = "{} {}".format(opt_arg, '-{}'.format(mpp_str))

        #if any vertex is float
        if any(any(not SR(v).is_integer() for v in vt) for vt in vts):
            vts = [[RR(v).n() for v in vt] for vt in vts]
            opt_arg = "{} -numerical-data ocaml_float".format(opt_arg)

        #exec external program
        #important, has to end with newline \n !!!
        vts_s = '\n'.join(str(vt).replace(' ', '') for vt in vts) + '\n'
        logger.debug('Build (gen {}) poly from {} vts in {} dims: {}'.format(
            mpp_str, len(vts), len(vts[0]), ts))

        cmd = 'compute_ext_rays_polar {} {}'.format(opt_arg, len(vts[0]))
        rs, _ = vcmd(cmd, vts_s)
        rs = [sage_eval(s.replace('oo', 'Infinity')) for s in rs.split()]

        rs = IeqMPPGen.group_rs(rs)

        rs = map(lambda ls: [x + y for x, y in zip(ls, ts + ts)], rs)
        rs = map(lambda ls: IeqMPP.sparse(ls, is_max_plus), rs)
        rs = filter(None, rs)
        return rs
Exemplo n.º 36
0
def find_rational_point(f, N = 2**8):
    out_rational = [];
    out_quad = [];
    for z in range(0, N):
        fz = f(z)
        fmz = f(-z)

        if is_square(fz) and fz != 0:
            out_rational += [(z, sqrt(fz))]
        elif fz != 0:
            out_quad += [(z, sqrt(fz))]
        if z != 0:
            if is_square(fmz) and fmz != 0:
                out_rational += [(-z, sqrt(fmz))]
            elif fmz != 0:
                out_quad += [(-z, sqrt(fmz))]

    return out_rational + sorted( out_quad, key=lambda point: RR(abs(point[1])) );
Exemplo n.º 37
0
def draw_transformed_triangle_H(A,xmax=20):
    r"""
    Draw the modular triangle translated by A=[a,b,c,d]
    """
    #print "A=",A,type(A)
    pi=RR.pi()
    pi_3 = pi / RR(3.0)
    from sage.plot.plot import (Graphics,line)
    from sage.functions.trig import (cos,sin)
    x1=RR(-0.5) ; y1=RR(sqrt(3 )/2 )
    x2=RR(0.5) ; y2=RR(sqrt(3 )/2 )
    a,b,c,d = A #[0,0]; b=A[0,1]; c=A[1,0]; d=A[1,1]
    if a<0:
        a=RR(-a); b=RR(-b); c=RR(-c); d=RR(-d) 
    else:
        a=RR(a); b=RR(b); c=RR(c); d=RR(d) 
    if c==0: # then this is easier
        if a*d<>0:
            a=a/d; b=b/d; 
        L0 = [[a*cos(pi_3*RR(i/100.0))+b,a*sin(pi_3*RR(i/100.0))] for i in range(100 ,201 )]
        L1 = [[a*x1+b,a*y1],[a*x1+b,xmax]]
        L2 = [[a*x2+b,a*y2],[a*x2+b,xmax]]
        L3 = [[a*x2+b,xmax],[a*x1+b,xmax]]
        c0=line(L0); l1=line(L1); l2=line(L2); l3=line(L3)
        tri=c0+l1+l3+l2
    else:
        den=(c*x1+d)**2 +c**2 *y1**2 
        x1_t=(a*c*(x1**2 +y1**2 )+(a*d+b*c)*x1+b*d)/den
        y1_t=y1/den
        den=(c*x2+d)**2 +c**2 *y2**2 
        x2_t=(a*c*(x2**2 +y2**2 )+(a*d+b*c)*x2+b*d)/den
        y2_t=y2/den
        inf_t=a/c
        #print "A=",A
        #print "arg1=",x1_t,y1_t,x2_t,y2_t
        c0=_geodesic_between_two_points(x1_t,y1_t,x2_t,y2_t)
        #print "arg1=",x1_t,y1_t,inf_t
        c1=_geodesic_between_two_points(x1_t,y1_t,inf_t,0. )
        #print "arg1=",x2_t,y2_t,inf_t
        c2=_geodesic_between_two_points(x2_t,y2_t,inf_t,0.0)
        tri=c0+c1+c2
    return tri
Exemplo n.º 38
0
def draw_funddom(coset_reps,format="S"):
    r""" Draw a fundamental domain for G.
    
    INPUT:
    
    - ``format``  -- (default 'Disp') How to present the f.d.
    -   ``S`` -- Display directly on the screen
    
    EXAMPLES::        


    sage: G=MySubgroup(Gamma0(3))
    sage: G._draw_funddom()
        
    """
    pi=RR.pi()
    pi_3 = pi / RR(3.0)
    from sage.plot.plot import (Graphics,line)
    from sage.functions.trig import (cos,sin)
    g=Graphics()
    x1=RR(-0.5) ; y1=RR(sqrt(3 )/2 )
    x2=RR(0.5) ; y2=RR(sqrt(3 )/2 )
    xmax=RR(20.0) 
    l1 = line([[x1,y1],[x1,xmax]])
    l2 = line([[x2,y2],[x2,xmax]])
    l3 = line([[x2,xmax],[x1,xmax]]) # This is added to make a closed contour
    c0=_circ_arc(RR(pi/3.0) ,RR(2.0*pi)/RR(3.0) ,0 ,1 ,100 )
    tri=c0+l1+l3+l2
    g=g+tri
    for A in coset_reps:
        if list(A)==[1,0,0,1]:
            continue

        tri=draw_transformed_triangle_H(A,xmax=xmax)
        g=g+tri
    return g
Exemplo n.º 39
0
Arquivo: mf.py Projeto: LMFDB/lmfdb
def kbarbar(weight):
    # The weight part of the analytic conductor
    return psi(RR(weight)/2).exp() / (2*RR.pi())
Exemplo n.º 40
0
def _geodesic_between_two_points_d(x1,y1,x2,y2,z0=I):
    r""" Geodesic path between two points represented in the unit disc
         by the map w = (z-I)/(z+I)
    INPUTS:
    - ''(x1,y1)'' -- starting point (0<y1<=infinity)
    - ''(x2,y2)'' -- ending point   (0<y2<=infinity)
    - ''z0''  -- (default I) the point in the upper corresponding
                 to the point 0 in the disc. I.e. the transform is
                 w -> (z-I)/(z+I)
    OUTPUT:
    - ''ca'' -- a polygonal approximation of a circular arc centered
    at c and radius r, starting at t0 and ending at t1

    
    EXAMPLES::

        sage: l=_geodesic_between_two_points_d(0.1,0.2,0.0,0.5)
    
    """
    pi=RR.pi()
    from sage.plot.plot import line
    from sage.functions.trig import (cos,sin)    
    # First compute the points
    if(y1<0  or y2<0 ):
        raise ValueError,"Need points in the upper half-plane! Got y1=%s, y2=%s" %(y1,y2)
    if(y1==infinity):
        P1=CC(1 )
    else:
        P1=CC((x1+I*y1-z0)/(x1+I*y1-z0.conjugate()))
    if(y2==infinity):
        P2=CC(1 )
    else:
        P2=CC((x2+I*y2-z0)/(x2+I*y2-z0.conjugate()))
        # First find the endpoints of the completed geodesic in D
    if(x1==x2):
        a=CC((x1-z0)/(x1-z0.conjugate()))
        b=CC(1 )
    else:
        c=RR(y1**2 -y2**2 +x1**2 -x2**2 )/RR(2 *(x1-x2))
        r=RR(sqrt(y1**2 +(x1-c)**2 ))
        a=c-r
        b=c+r
        a=CC((a-z0)/(a-z0.conjugate()))
        b=CC((b-z0)/(b-z0.conjugate()))
    if( abs(a+b) < 1E-10 ): # On a diagonal
        return line([[P1.real(),P1.imag()],[P2.real(),P2.imag()]])
    th_a=a.argument()
    th_b=b.argument()
    # Compute the center of the circle in the disc model
    if( min(abs(b-1 ),abs(b+1 ))< 1E-10  and  min(abs(a-1 ),abs(a+1 ))>1E-10 ):
        c=b+I*(1 -b*cos(th_a))/sin(th_a)
    elif( min(abs(b-1 ),abs(b+1 ))> 1E-10  and  min(abs(a-1 ),abs(a+1 ))<1E-10 ):
        c=a+I*(1 -a*cos(th_b))/RR(sin(th_b))
    else:
        cx=(sin(th_b)-sin(th_a))/sin(th_b-th_a)
        c=cx+I*(1 -cx*cos(th_b))/RR(sin(th_b))
    # First find the endpoints of the completed geodesic
    r=abs(c-a)
    t1=CC(P1-c).argument()
    t2=CC(P2-c).argument()
    #print "t1,t2=",t1,t2
    return _circ_arc(t1,t2,c,r)