Пример #1
0
def symbolic_sis(n, alpha, q, m=None, epsilon=None):
    if epsilon is None:
        epsilon = var("epsilon")
        assume(epsilon>0)
        assume(epsilon<ZZ(1)/2)
    delta_0 = var("delta_0")
    assume(delta_0>=1.0)

    e = alpha*q/sqrt(2*pi)

    if m is None:
        m = sqrt(n*log(q)/log(delta_0))

    v = e * delta_0**m * q**(n/m)  # norm of the vector

    # epsilon = exp(-pi*(|v|^2/q^2))
    f = log(1/epsilon)/pi == (v/q)**2

    # solve
    f = 2* q**2 * m * f * pi
    f = f.simplify_full()
    f = f.solve(delta_0**(2*m))[0]
    f = f.log().canonicalize_radical()
    f = f.solve(log(delta_0))[0]
    f = f.simplify_log()
    return f
Пример #2
0
def download_hecke_algebras_full_lists_mod_op(**args):
    label = str(args['orbit_label'])
    ell = int(args['prime'])
    index = int(args['index'])
    res = db.hecke_ladic.lucky({
        'orbit_label': label,
        'index': index,
        'ell': ell
    })
    mydate = time.strftime("%d %B %Y")
    if res is None:
        return "No mod %s operators available" % ell
    lang = args['lang']
    c = download_comment_prefix[lang]
    field = 'GF(%s), %s, %s, ' % (res['ell'], sqrt(len(
        res['operators'][0])), sqrt(len(res['operators'][0])))
    mat_start = "Mat(" + field if lang == 'gp' else "Matrix(" + field
    mat_end = "~)" if lang == 'gp' else ")"
    entry = lambda r: "".join([mat_start, str(r), mat_end])

    outstr = c + ' List of Hecke operators T_1, ..., T_%s mod %s for orbit %s index %s downloaded from the LMFDB on %s. \n\n' % (
        len(res['operators']), ell, label, index, mydate)
    outstr += download_assignment_start[lang] + '[\\\n'
    outstr += ",\\\n".join([entry(r) for r in res['operators']])
    outstr += ']'
    outstr += download_assignment_end[lang]
    outstr += '\n'
    return outstr
Пример #3
0
    def PointMinusInfinity(self, P, sign = 0):
        # Creates a divisor class of P- \inty_{(-1)**sign}
        maxlower = self.lower 
        assert self.f.degree() == 2*self.g + 2;
        sqrtan = (-1)**sign * self.Rextraprec( sqrt( self.Rdoubleextraprec(self.an)) );

        xP, yP = self.Rextraprec(P[0]),self.Rextraprec(P[1])
        assert (self.f(xP) - yP**2).abs() <= (yP**2).abs() * self.almostzero

        if xP != 0 and self.a0 != 0:
            x0 = self.Rextraprec(0);    
        else:
            x0 = xP
            while x0 == xP:
                x0 = self.Rextraprec(ZZ.random_element())
            
        y0 =  self.Rextraprec( sqrt( self.Rdoubleextraprec( self.f( x0 )))) # P0 = (x0, y0) 

        WP1 = Matrix(self.Rextraprec, self.nZ, 3 * self.g + 6) # H0(3D0 - P0 - g \infty) = H0(3D0 - P0 - g(\infty_{+} + \infty_{-}))
        EvP = Matrix(self.Rextraprec, 1, 3 * self.g + 6) # the functions of  H0(3D0-P0-g \infty) at P
        B =  Matrix(self.Rextraprec, self.nZ, 3 * self.g + 5) # H0(3D0 - \infty_{sign} - P0 - g\infty)

        # adds the functions x - x0, (x - x0)**1,  ..., (x - x0)**(2g+2) to it
        for j in xrange(2 * self.g + 2 ):
            for i, (x, y) in enumerate( self.Z ):
                WP1[ i, j] = B[ i, j] = (x - x0) ** (j + 1)
            EvP[ 0, j] = (xP - x0) ** (j + 1)
        
        # adds y - y0
        for i, (x, y) in enumerate( self.Z ):
            WP1[ i, 2 * self.g + 2 ] = B[ i, 2 * self.g + 2] = y - y0
        EvP[ 0, 2 * self.g + 2] = yP - y0

        # adds (x - x0) * y ... (x-x0)**(g+1)*y
        for j in range(1, self.g + 2):
            for i, (x,y) in enumerate( self.Z ):
                WP1[ i, 2 * self.g + 2 + j ] = B[ i, 2 * self.g + 2 + j] = (x-x0)**j * y 
            EvP[ 0, 2 * self.g + 2 + j] = (xP - x0)**j * yP


        # adds (x - x0)**(2g + 3) and  y *  (x - x0)**(g + 2)
        for i,(x,y) in enumerate(self.Z):
            WP1[ i, 3 * self.g + 4 ] =  (x - x0)**( 2 * self.g + 3)
            WP1[ i, 3 * self.g + 5 ] = y *  (x - x0)**(self.g + 2)
            B[ i, 3 * self.g + 4 ] =  (x - x0)**( self.g + 2) * ( y - sqrtan * x**(self.g + 1) )

        EvP[ 0, 3 * self.g + 4] = (xP - x0) ** ( 2 * self.g + 3)
        EvP[ 0, 3 * self.g + 5] = yP * (xP - x0)**(self.g + 2)
        
        # A = functions in  H0(3D0-P0-g \infty) that vanish at P
        # = H**0(3D0 - P0 - P -g \infty)
        K, upper, lower = Kernel(EvP, EvP.ncols() - (3 * self.g + 5))
        assert self.threshold_check(upper, lower), "upper = %s lower = %s" % (RealField(35)(upper), RealField(35)(lower))
        maxlower = max(maxlower, lower);

        A = WP1 * K
        # A - B = P0 + P + g \infty - (\infty_{+} + P0 + g\infty) = P - \inty_{+}
        res, lower = self.Sub(A,B)
        maxlower = max(maxlower, lower);
        return res.change_ring(self.R), maxlower;
Пример #4
0
def symbolic_modulus_switching(n, alpha, q, h, m=None, epsilon=None):
    if epsilon is None:
        epsilon = var("epsilon")
        assume(epsilon>0)
        assume(epsilon<ZZ(1)/2)

    delta_0 = var("delta_0")
    assume(delta_0>=1.0)

    if m is None:
        m = sqrt(n*log(q)/log(delta_0))

    e = alpha*q/sqrt(2*pi)

    c = e * sqrt(m-n)/sqrt(h)

    v = delta_0**m * (q/c)**(n/m)  # norm of the vector
    v_ = v**2/m  # variance of each component

    v_r = (m-n) * e**2 *v_   # noise contribution
    v_l = h * v_ * c**2  # nose contribution of rounding noise

    # epsilon = exp(-pi*(|v|^2/q^2))

    f = log(1/epsilon)/pi == (v_l + v_r)/q**2

    # solve
    f = 2* q**2 * m * f * pi
    f = f.simplify_full()
    f = f.solve(delta_0**(2*m))[0]
    f = f.log().canonicalize_radical()
    f = f.solve(log(delta_0))[0]
    f = f.simplify_log()
    return f
Пример #5
0
def factorize(n, r_p, r_q):
    """
    Recovers the prime factors from a modulus using the Ghafar-Ariffin-Asbullah attack.
    More information: Ghafar AHA. et al., "A New LSB Attack on Special-Structured RSA Primes"
    :param n: the modulus
    :param r_p: the value r_p
    :param r_q: the value r_q
    :return: a tuple containing the prime factors
    """
    i = ceil(sqrt(r_p * r_q))
    x = ZZ["x"].gen()
    while True:
        sigma = (round(int(sqrt(n))) - i)**2
        z = (n - (r_p * r_q)) % sigma
        f = x**2 - z * x + sigma * r_p * r_q
        for root, _ in f.roots():
            if root % r_p == 0:
                p = int((root // r_p) + r_q)
                assert n % p == 0
                return p, n // p
            if root % r_q == 0:
                p = int((root // r_q) + r_p)
                assert n % p == 0
                return p, n // p

        i += 1
Пример #6
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
Пример #7
0
def symbolic_sis(n, alpha, q, m=None, epsilon=None):
    if epsilon is None:
        epsilon = var("epsilon")
        assume(epsilon > 0)
        assume(epsilon < ZZ(1) / 2)
    delta_0 = var("delta_0")
    assume(delta_0 >= 1.0)

    e = alpha * q / sqrt(2 * pi)

    if m is None:
        m = sqrt(n * log(q) / log(delta_0))

    v = e * delta_0**m * q**(n / m)  # norm of the vector

    # epsilon = exp(-pi*(|v|^2/q^2))
    f = log(1 / epsilon) / pi == (v / q)**2

    # solve
    f = 2 * q**2 * m * f * pi
    f = f.simplify_full()
    f = f.solve(delta_0**(2 * m))[0]
    f = f.log().canonicalize_radical()
    f = f.solve(log(delta_0))[0]
    f = f.simplify_log()
    return f
Пример #8
0
def symbolic_modulus_switching(n, alpha, q, h, m=None, epsilon=None):
    if epsilon is None:
        epsilon = var("epsilon")
        assume(epsilon > 0)
        assume(epsilon < ZZ(1) / 2)

    delta_0 = var("delta_0")
    assume(delta_0 >= 1.0)

    if m is None:
        m = sqrt(n * log(q) / log(delta_0))

    e = alpha * q / sqrt(2 * pi)

    c = e * sqrt(m - n) / sqrt(h)

    v = delta_0**m * (q / c)**(n / m)  # norm of the vector
    v_ = v**2 / m  # variance of each component

    v_r = (m - n) * e**2 * v_  # noise contribution
    v_l = h * v_ * c**2  # nose contribution of rounding noise

    # epsilon = exp(-pi*(|v|^2/q^2))

    f = log(1 / epsilon) / pi == (v_l + v_r) / q**2

    # solve
    f = 2 * q**2 * m * f * pi
    f = f.simplify_full()
    f = f.solve(delta_0**(2 * m))[0]
    f = f.log().canonicalize_radical()
    f = f.solve(log(delta_0))[0]
    f = f.simplify_log()
    return f
Пример #9
0
def branch(g, P):
    x0, y0 = P
    val = [(y0 - sqrt(g(x0))).norm(), (y0 + sqrt(g(x0))).norm() ];
    if val[0] < val[1]:
        return 1
    else:
        return -1
Пример #10
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
Пример #11
0
def quadratic_L_function__exact(n, d):
    r"""
    Returns the exact value of a quadratic twist of the Riemann Zeta function
    by `\chi_d(x) = \left(\frac{d}{x}\right)`.

    The input `n` must be a critical value.

    EXAMPLES::

        sage: quadratic_L_function__exact(1, -4)
        1/4*pi
        sage: quadratic_L_function__exact(-4, -4)
        5/2
        sage: quadratic_L_function__exact(2, 1)
        1/6*pi^2

    TESTS::

        sage: quadratic_L_function__exact(2, -4)
        Traceback (most recent call last):
        ...
        TypeError: n must be a critical value (i.e. odd > 0 or even <= 0)

    REFERENCES:

    - [Iwa1972]_, pp 16-17, Special values of `L(1-n, \chi)` and `L(n, \chi)`
    - [IR1990]_
    - [Was1997]_
    """
    from sage.all import SR, sqrt
    if n <= 0:
        return QuadraticBernoulliNumber(1 - n, d) / (n - 1)
    elif n >= 1:
        # Compute the kind of critical values (p10)
        if kronecker_symbol(fundamental_discriminant(d), -1) == 1:
            delta = 0
        else:
            delta = 1

        # Compute the positive special values (p17)
        if ((n - delta) % 2 == 0):
            f = abs(fundamental_discriminant(d))
            if delta == 0:
                GS = sqrt(f)
            else:
                GS = I * sqrt(f)
            ans = SR(ZZ(-1)**(1 + (n - delta) / 2))
            ans *= (2 * pi / f)**n
            ans *= GS  # Evaluate the Gauss sum here! =0
            ans *= QQ.one() / (2 * I**delta)
            ans *= QuadraticBernoulliNumber(n, d) / factorial(n)
            return ans
        else:
            if delta == 0:
                raise TypeError(
                    "n must be a critical value (i.e. even > 0 or odd < 0)")
            if delta == 1:
                raise TypeError(
                    "n must be a critical value (i.e. odd > 0 or even <= 0)")
def _branch_safe_sqrt(z):
    if z != 0:
        return sqrt(z)

    d = sqrt(abs(z)).upper()
    RIF = z.real().parent()
    CIF = z.parent()

    return CIF(RIF(-d, d), RIF(-d, d))
Пример #13
0
def test_almost_equal():
    echo_function("test_almost_equal")
    s = Segment(Point(1, 1), Point(2, 2))
    v = s.get_normal_vector()
    assert_equal(v.I, Point(1.5, 1.5))
    assert_almost_equal(v.length, 1, epsilon=0.001)
    assert_almost_equal(v.F,
                        Point(1 / 2 * sqrt(2) + 1.5, -1 / 2 * sqrt(2) + 1.5),
                        epsilon=0.001)
Пример #14
0
def crack_when_pq_close(n):
    t = Integer(ceil(sqrt(n)))
    while True:
        k = t**2 - n
        if k > 0:
            s = Integer(int(round(sqrt(t**2 - n))))
            if s**2 + n == t**2:
                return t + s, t - s
        t += 1
Пример #15
0
def quadratic_L_function__exact(n, d):
    r"""
    Returns the exact value of a quadratic twist of the Riemann Zeta function
    by `\chi_d(x) = \left(\frac{d}{x}\right)`.

    The input `n` must be a critical value.

    EXAMPLES::

        sage: quadratic_L_function__exact(1, -4)
        1/4*pi
        sage: quadratic_L_function__exact(-4, -4)
        5/2
        sage: quadratic_L_function__exact(2, 1)
        1/6*pi^2

    TESTS::

        sage: quadratic_L_function__exact(2, -4)
        Traceback (most recent call last):
        ...
        TypeError: n must be a critical value (i.e. odd > 0 or even <= 0)

    REFERENCES:

    - [Iwa1972]_, pp 16-17, Special values of `L(1-n, \chi)` and `L(n, \chi)`
    - [IR1990]_
    - [Was1997]_
    """
    from sage.all import SR, sqrt
    if n <= 0:
        return QuadraticBernoulliNumber(1-n,d)/(n-1)
    elif n >= 1:
        # Compute the kind of critical values (p10)
        if kronecker_symbol(fundamental_discriminant(d), -1) == 1:
            delta = 0
        else:
            delta = 1

        # Compute the positive special values (p17)
        if ((n - delta) % 2 == 0):
            f = abs(fundamental_discriminant(d))
            if delta == 0:
                GS = sqrt(f)
            else:
                GS = I * sqrt(f)
            ans = SR(ZZ(-1)**(1+(n-delta)/2))
            ans *= (2*pi/f)**n
            ans *= GS     # Evaluate the Gauss sum here! =0
            ans *= QQ.one()/(2 * I**delta)
            ans *= QuadraticBernoulliNumber(n,d)/factorial(n)
            return ans
        else:
            if delta == 0:
                raise TypeError("n must be a critical value (i.e. even > 0 or odd < 0)")
            if delta == 1:
                raise TypeError("n must be a critical value (i.e. odd > 0 or even <= 0)")
Пример #16
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
Пример #17
0
def matrices_are_close(m1, m2, epsilon=1e-6):
    m1 = m1 / sqrt(m1.det())
    m2 = m2 / sqrt(m2.det())

    return any([
        all([
            abs(m1[i, j] - s * m2[i, j]) < 1e-6 for i in range(2)
            for j in range(2)
        ]) for s in [+1, -1]
    ])
Пример #18
0
def compare_formulas_2(D, k):
    d1 = old_div(RR(abs(D)), RR(6))
    if D < 0:
        D = -D
    s1 = RR(
        sqrt(abs(D)) * sum([
            log(d) for d in divisors(D) if is_fundamental_discriminant(-d)
            and kronecker(-d, old_div(D, d)) == 1
        ]))
    d2 = RR((old_div(2, (sqrt(3) * pi))) * s1)
    return d1 - d2, d2, RR(2 * sqrt(D) * log(D) / pi)
Пример #19
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)
Пример #20
0
def good_bezier(p1, angle1, angle2, p2, tension1=1.0, tension2=1.0):
    """
    Compute a nice curve from p1 to p2 with specified tangents
    """
    l, psi = to_polar(p2 - p1)
    ctheta, stheta = polar(1.0, angle1 - psi)
    cphi, sphi = polar(1.0, psi - angle2)
    a = sqrt(2.0)
    b = 1.0 / 16.0
    c = (3.0 - sqrt(5.0)) / 2.0
    alpha = a * (stheta - b * sphi) * (sphi - b * stheta) * (ctheta - cphi)
    rho = (2 + alpha) / (1 + (1 - c) * ctheta + c * cphi) / tension1
    sigma = (2 - alpha) / (1 + (1 - c) * cphi + c * ctheta) / tension2
    return (p1 + polar(l * rho / 3, angle1), p2 - polar(l * sigma / 3, angle2))
Пример #21
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)
Пример #22
0
    def curvature(self):
        """
        return the curvature function.
        """
        gp = self.derivative()
        gpp = self.derivative(n=2)

        fp1 = gp.f1.sage
        fp2 = gp.f2.sage

        fpp1 = gpp.f1.sage
        fpp2 = gpp.f2.sage

        mixed = fpp1 * fp1 + fpp2 * fp2
        mixed = mixed.simplify_full()

        num1 = fpp1 * self.speed - 2 * fp1 * mixed
        num2 = fpp2 * self.speed - 2 * fp2 * mixed
        num1 = num1.simplify_full()
        num2 = num2.simplify_full()

        tau1 = num1 / (self.speed**2)
        tau2 = num2 / (self.speed**2)
        tau1 = tau1.simplify_full()
        tau2 = tau2.simplify_full()

        c = sqrt(tau1**2 + tau2**2)
        return c.full_simplify()
Пример #23
0
    def derivative_of_single_dihedral_angle(self, tetIndex, i, j):
        """
        Gives the derivative of the single dihedral angle between face i and j
        of tetrahedron tetIndex with respect to the edge parameters.
        """

        s = len(self.mcomplex.Edges)
        result = vector(self.vertex_gram_matrices[0].base_ring(), s)

        tet = self.mcomplex.Tetrahedra[tetIndex]

        cofactor_matrices = _cofactor_matrices_for_submatrices(
            self.vertex_gram_matrices[tetIndex])
        vga = self.vertex_gram_adjoints[tetIndex]

        cii = vga[i, i]
        cij = vga[i, j]
        cjj = vga[j, j]

        dcij = -1 / sqrt(cii * cjj - cij**2)
        tmp = -dcij * cij / 2
        dcii = tmp / cii
        dcjj = tmp / cjj

        for length_edge, (m, n) in _OneSubsimplicesWithVertexIndices:
            l = tet.Class[length_edge].Index

            result[l] += (
                dcij * _cofactor_derivative(cofactor_matrices, i, j, m, n) +
                dcii * _cofactor_derivative(cofactor_matrices, i, i, m, n) +
                dcjj * _cofactor_derivative(cofactor_matrices, j, j, m, n))

        return result
Пример #24
0
def visual_length(v, l, xunit=None, yunit=None, pspict=None):
    """
    Return a vector which as the requested *visual* length.

    Return a vector in the direction of v that has *visual* length
    l taking xunit and yunit into account.
    """
    from yanntricks.src.affine_vector import AffineVector
    if pspict:
        xunit = pspict.xunit
        yunit = pspict.yunit
    Dx = v.Dx
    Dy = v.Dy
    if not v.is_vertical:
        slope = v.slope
        x = l / sqrt(xunit**2 + slope**2 * yunit**2)

        if numerical_is_negative(Dx):
            x = -x
        y = slope * x
    else:
        x = 0
        y = l / yunit
        if numerical_is_negative(Dy):
            y = -l / yunit
    return AffineVector(v.I, v.I + (x, y))
Пример #25
0
def is_quotient(M, sym, rank):
    symbol = GenusSymbol_global_ring(MatrixSpace(ZZ, rank, rank).one())
    symbol._local_symbols = [
        Genus_Symbol_p_adic_ring(p, syms) for p, syms in sym.iteritems()
    ]
    s = get_symbol_string(symbol)
    print s
    N = FiniteQuadraticModule(s)
    t = N.order() / M.order()
    if not Integer(t).is_square():
        return False
    else:
        t = sqrt(t)
    for p in Integer(N.order()).prime_factors():
        if not N.signature(p) == M.signature(p):
            return False
    # if not N.signature() == M.signature():
    #    return False
    for G in N.subgroups():
        if G.order() == t and G.is_isotropic():
            Q = G.quotient()
            if Q.is_isomorphic(M):
                print Q
                return N
            else:
                del Q
    del N
    return False
Пример #26
0
def sqrt_poly(g):
    if g.degree() == 0:
        return sqrt(g[0])

    d = GCD(g, g.derivative(g.parent().gen()))
    sg = g // d
    return sg * sqrt_poly(g // sg**2)
Пример #27
0
def is_quotient(M, sym, rank):
    symbol = GenusSymbol_global_ring(MatrixSpace(ZZ, rank, rank).one())
    symbol._local_symbols = [
        Genus_Symbol_p_adic_ring(p, syms) for p, syms in sym.iteritems()]
    s = get_symbol_string(symbol)
    print s
    N = FiniteQuadraticModule(s)
    t = N.order() / M.order()
    if not Integer(t).is_square():
        return False
    else:
        t = sqrt(t)
    for p in Integer(N.order()).prime_factors():
        if not N.signature(p) == M.signature(p):
            return False
    # if not N.signature() == M.signature():
    #    return False
    for G in N.subgroups():
        if G.order() == t and G.is_isotropic():
            Q = G.quotient()
            if Q.is_isomorphic(M):
                print Q
                return N
            else:
                del Q
    del N
    return False
Пример #28
0
def class_nr_pos_def_qf(D):
    r"""
    Compute the class number of positive definite quadratic forms.
    For fundamental discriminants this is the class number of Q(sqrt(D)),
    otherwise it is computed using: Cohen 'A course in Computational Algebraic Number Theory', p. 233
    """
    if D>0:
        return 0
    D4 = D % 4
    if D4 == 3 or D4==2:
        return 0
    K = QuadraticField(D)
    if is_fundamental_discriminant(D):
        return K.class_number()
    else:
        D0 = K.discriminant()
        Df = ZZ(D).divide_knowing_divisible_by(D0)
        if not is_square(Df):
            raise ArithmeticError("Did not get a discrimimant * square! D={0} disc(D)={1}".format(D,D0))
        D2 = sqrt(Df)
        h0 = QuadraticField(D0).class_number()
        w0 = _get_w(D0)
        w = _get_w(D)
        #print "w,w0=",w,w0
        #print "h0=",h0
        h = 1
        for p in prime_divisors(D2):
            h = QQ(h)*(1-kronecker(D0,p)/QQ(p))
        #print "h=",h
        #print "fak=",
        h=QQ(h*h0*D2*w)/QQ(w0)
        return h
Пример #29
0
def greedy_cusp_areas_from_cusp_area_matrix(cusp_area_matrix):
    """

        sage: from sage.all import matrix, RIF
        sage: greedy_cusp_areas_from_cusp_area_matrix(
        ...             matrix([[RIF(9.0,9.0005),RIF(6.0, 6.001)],
        ...                     [RIF(6.0,6.001 ),RIF(10.0, 10.001)]]))
        [3.0001?, 2.000?]

        >>> from snappy.SnapPy import matrix
        >>> greedy_cusp_areas_from_cusp_area_matrix(
        ...             matrix([[10.0, 40.0],
        ...                     [40.0, 20.0]]))
        [3.1622776601683795, 4.47213595499958]
    
    """

    num_cusps = cusp_area_matrix.dimensions()[0]

    result = []

    for i in range(num_cusps):
        stoppers = [cusp_area_matrix[i, j] / result[j] for j in range(i)]
        self_stopper = sqrt(cusp_area_matrix[i, i])

        result.append(interval_aware_min(stoppers + [self_stopper]))

    return result
Пример #30
0
def test_elliptic_curve(a, b, alpha=7, angles=12):
    from sage.all import cos, sin, pi
    E = EllipticCurve(QQ, [a, b])
    rationalpoints = E.point_search(10)
    EQbar = EllipticCurve(QQbar, [a, b])
    infx, infy, _ = rationalpoints[0]
    inf = EQbar(infx, infy)
    print inf
    R = PolynomialRing(QQ, "w")
    w = R.gen()
    f = w**3 + a * w + b
    iaj = InvertAJlocal(f, 256, method='gauss-legendre')
    iaj.set_basepoints([(mpmath.mpf(infx), mpmath.mpf(infy))])
    for eps in [
            cos(theta * 2 * pi / angles) + I * sin(theta * 2 * pi / angles)
            for theta in range(0, angles)
    ]:
        px = infx + eps
        py = iaj.sign * sqrt(-E.defining_polynomial().subs(x=px, y=0, z=1))
        P = EQbar(px, py)
        try:
            (v, errorv) = iaj.to_J(px, infx)
            qx = (alpha * P - (alpha - 1) * inf).xy()[0]
            qxeps = CC(qx) + (mpmath.rand() + I * mpmath.rand()) / 1000
            (t1, errort1) = iaj.solve(alpha * v, 100, iaj.error, [qxeps])
            qxguess = t1[0, 0]
            print mpmath.fabs(qxguess - qx) < 2**(-mpmath.mp.prec / 2)
        except RuntimeWarning as detail:
            print detail
Пример #31
0
def greedy_cusp_areas_from_cusp_area_matrix(cusp_area_matrix, first_cusps=[]):
    """

        sage: from sage.all import matrix, RIF
        sage: greedy_cusp_areas_from_cusp_area_matrix(
        ...             matrix([[RIF(9.0,9.0005),RIF(6.0, 6.001)],
        ...                     [RIF(6.0,6.001 ),RIF(10.0, 10.001)]]))
        [3.0001?, 2.000?]

        >>> from snappy.SnapPy import matrix
        >>> greedy_cusp_areas_from_cusp_area_matrix(
        ...             matrix([[10.0, 40.0],
        ...                     [40.0, 20.0]]))
        [3.1622776601683795, 4.47213595499958]
    
    """

    num_cusps = cusp_area_matrix.dimensions()[0]

    result = list(
        range(num_cusps))  # Make space for range; initial values irrelevant

    # Cusp permutation given in Cayley notation
    sigma = first_cusps + [i for i in range(num_cusps) if i not in first_cusps]

    for i in range(num_cusps):
        stoppers = [
            cusp_area_matrix[sigma[i], sigma[j]] / result[sigma[j]]
            for j in range(i)
        ]
        self_stopper = sqrt(cusp_area_matrix[sigma[i], sigma[i]])

        result[sigma[i]] = interval_aware_min(stoppers + [self_stopper])

    return result
Пример #32
0
    def jacobian(self):
        s = len(self.mcomplex.Edges)
        result = matrix(self.vertex_gram_matrices[0].base_ring(), s, s)

        for tet in self.mcomplex.Tetrahedra:
            cofactor_matrices = _cofactor_matrices_for_submatrices(
                self.vertex_gram_matrices[tet.Index])
            vga = self.vertex_gram_adjoints[tet.Index]

            for angle_edge, (i, j) in _OneSubsimplicesWithVertexIndices:
                cii = vga[i, i]
                cij = vga[i, j]
                cjj = vga[j, j]

                dcij = -1 / sqrt(cii * cjj - cij**2)
                tmp = -dcij * cij / 2
                dcii = tmp / cii
                dcjj = tmp / cjj

                a = tet.Class[t3m.comp(angle_edge)].Index

                for length_edge, (m, n) in _OneSubsimplicesWithVertexIndices:
                    l = tet.Class[length_edge].Index

                    result[a, l] += (
                        dcij *
                        _cofactor_derivative(cofactor_matrices, i, j, m, n) +
                        dcii *
                        _cofactor_derivative(cofactor_matrices, i, i, m, n) +
                        dcjj *
                        _cofactor_derivative(cofactor_matrices, j, j, m, n))
        return result
Пример #33
0
def visual_length(v, l, xunit=None, yunit=None, pspict=None):
    """
    Return a vector in the direction of v that has *visual* length
    l taking xunit and yunit into account.
    """
    from Numerical import numerical_is_negative
    if pspict:
        xunit = pspict.xunit
        yunit = pspict.yunit
    Dx = v.Dx
    Dy = v.Dy
    if not v.is_vertical:
        slope = v.slope
        x = l / sqrt(xunit**2 + slope**2 * yunit**2)

        if numerical_is_negative(Dx):
            x = -x
        y = slope * x
    else:
        x = 0
        y = l / yunit
        if numerical_is_negative(Dy):
            y = -l / yunit
    if hasattr(v, "I"):
        from phystricks import AffineVector
        return AffineVector(v.I, v.I + (x, y))
Пример #34
0
def insert_EC_L_functions(start=1, end=100):
    curves = C.ellcurves.curves
    for N in range(start, end):
        print "Processing conductor", N
        sys.stdout.flush()
        query = curves.find({'conductor': N, 'number': 1})
        for curve in query:
            E = EllipticCurve([int(x) for x in curve['ainvs']])
            L = lc.Lfunction_from_elliptic_curve(E)
            first_zeros = L.find_zeros_via_N(curve['rank'] + 1)
            if len(first_zeros) > 1:
                if not first_zeros[-2] == 0:
                    print "problem"

            z = float(first_zeros[-1])

            Lfunction_data = {}
            Lfunction_data['first_zero'] = z
            Lfunction_data['description'] = 'Elliptic curve L-function for curve ' + str(curve['label'][:-1])
            Lfunction_data['degree'] = 2
            Lfunction_data['signature'] = [0, 1]
            Lfunction_data['eta'] = [(1.0, 0), ]

            Lfunction_data['level'] = N
            Lfunction_data['special'] = {'type': 'elliptic', 'label': curve['label'][:-1]}

            coeffs = []

            for k in range(1, 11):
                coeffs.append(CC(E.an(k) / sqrt(k)))

            Lfunction_data['coeffs'] = [(float(x.real()), float(x.imag())) for x in coeffs]

            Lfunctions.insert(Lfunction_data)
Пример #35
0
def do_Nk2(Nk2, only_traces=False):
    todo = []
    for N in ZZ(Nk2).divisors():
        k = sqrt(Nk2 / N)
        if k in ZZ and k > 1:
            if Nk2 > 4000 and (N > 100 or k > 12):
                print "skipping N = %d k = %d" % (N, k)
            else:
                todo.append((N, k))

    lfun_filename = os.path.join(base_export, 'CMF_Lfunctions_%d.txt' % (Nk2))
    instances_filename = os.path.join(base_export,
                                      'CMF_instances_%d.txt' % (Nk2))
    hecke_filename = os.path.join(base_export, 'CMF_hecke_cc_%d.txt' % (Nk2))
    traces_filename = os.path.join(base_export, 'CMF_traces_%d.txt' % (Nk2))
    for F in [
            lfun_filename, instances_filename, hecke_filename, traces_filename
    ]:
        if os.path.exists(F):
            os.remove(F)
    start_time = time.time()
    for i, (N, k) in enumerate(todo):
        do_time = time.time()
        do(N, k, lfun_filename, instances_filename, hecke_filename,
           traces_filename, only_traces)
        print "done, N = %s, k = %s" % (N, k)
        now = time.time()
        print "Progress: %.2f %%" % (100. * i / len(todo))
        print "Timing: %.2f\nTotal: %.2f\n\n" % (now - do_time,
                                                 now - start_time)
        sys.stdout.flush()
def testAngleMeasure():
    echo_function("testAngleMeasure")

    comparison()

    alpha = AngleMeasure(value_degree=360)
    assert_equal(alpha.__repr__(),
                 "AngleMeasure, degree=360.000000000000,radian=2*pi")

    alpha = AngleMeasure(value_degree=30)
    assert_equal(cos(alpha.radian), 1 / 2 * sqrt(3))

    alpha = AngleMeasure(value_degree=180)
    beta = AngleMeasure(alpha)
    assert_equal(beta.degree, 180)

    alpha = AngleMeasure(value_degree=-(3.47548077273962e-14) / pi + 360)
    assert_equal(alpha.degree, 360)
    assert_equal(alpha.radian, 2 * pi)

    alpha = AngleMeasure(value_degree=-30)
    assert_equal(alpha.positive().degree, 330)

    alpha = AngleMeasure(value_degree=45)
    beta = AngleMeasure(value_radian=pi / 3)
    assert_equal(alpha.degree, 45)
    assert_equal(alpha.radian, 1 / 4 * pi)
    assert_equal(beta.degree, 60)
    assert_equal(beta.radian, 1 / 3 * pi)

    a_sum_b = alpha + beta
    assert_equal(a_sum_b.degree, 105)
    assert_equal(a_sum_b.radian, 7 / 12 * pi)
Пример #37
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
Пример #38
0
def class_nr_pos_def_qf(D):
    r"""
    Compute the class number of positive definite quadratic forms.
    For fundamental discriminants this is the class number of Q(sqrt(D)),
    otherwise it is computed using: Cohen 'A course in Computational Algebraic Number Theory', p. 233
    """
    if D>0:
        return 0
    D4 = D % 4
    if D4 == 3 or D4==2:
        return 0
    K = QuadraticField(D)
    if is_fundamental_discriminant(D):
        return K.class_number()
    else:
        D0 = K.discriminant()
        Df = ZZ(D).divide_knowing_divisible_by(D0)
        if not is_square(Df):
            raise ArithmeticError,"DId not get a discrinimant * square! D={0} disc(D)={1}".format(D,D0)
        D2 = sqrt(Df)
        h0 = QuadraticField(D0).class_number()
        w0 = _get_w(D0)
        w = _get_w(D)
        #print "w,w0=",w,w0
        #print "h0=",h0
        h = 1
        for p in prime_divisors(D2):
            h = QQ(h)*(1-kronecker(D0,p)/QQ(p))
        #print "h=",h
        #print "fak=",
        h=QQ(h*h0*D2*w)/QQ(w0)
        return h
Пример #39
0
    def init_vertices_kernel(self):
        """
        Computes vertices for the initial tetrahedron matching the choices
        made by the SnapPea kernel.
        """

        tet = self.mcomplex.ChooseGenInitialTet

        for perm in Perm4.A4():
            z = tet.ShapeParameters[perm.image(simplex.E01)]
            NumericField = z.parent()
            one = NumericField(1)
            minus_one = NumericField(-1)
            sqrt_z = sqrt(z)
            sqrt_z_inv = one / sqrt_z

            for sign in [one, minus_one]:
                candidates = {
                    perm.image(simplex.V0): NumericField(0),
                    perm.image(simplex.V1): Infinity,
                    perm.image(simplex.V2): sign * sqrt_z,
                    perm.image(simplex.V3): sign * sqrt_z_inv
                }

                if _are_vertices_close_to_kernel(candidates,
                                                 tet.SnapPeaIdealVertices):
                    return candidates

        raise Exception(
            "Could not match vertices to vertices from SnapPea kernel")
Пример #40
0
def quadratic_L_function__exact(n, d):
    r"""
    Returns the exact value of a quadratic twist of the Riemann Zeta function
    by `\chi_d(x) = \left(\frac{d}{x}\right)`.

    References:

    - Iwasawa's "Lectures on p-adic L-functions", p16-17, "Special values of
      `L(1-n, \chi)` and `L(n, \chi)`
    - Ireland and Rosen's "A Classical Introduction to Modern Number Theory"
    - Washington's "Cyclotomic Fields"

    EXAMPLES::

        sage: bool(quadratic_L_function__exact(1, -4) == pi/4)
        True

    """
    from sage.all import SR, sqrt
    if n <= 0:
        k = 1 - n
        return -QuadraticBernoulliNumber(k, d) / k
    elif n >= 1:
        ## Compute the kind of critical values (p10)
        if kronecker_symbol(fundamental_discriminant(d), -1) == 1:
            delta = 0
        else:
            delta = 1

        ## Compute the positive special values (p17)
        if ((n - delta) % 2 == 0):
            f = abs(fundamental_discriminant(d))
            if delta == 0:
                GS = sqrt(f)
            else:
                GS = I * sqrt(f)
            ans = SR(ZZ(-1)**(1 + (n - delta) / 2))
            ans *= (2 * pi / f)**n
            ans *= GS  ## Evaluate the Gauss sum here! =0
            ans *= 1 / (2 * I**delta)
            ans *= QuadraticBernoulliNumber(n, d) / factorial(n)
            return ans
        else:
            if delta == 0:
                raise TypeError, "n must be a critical value!\n" + "(I.e. even > 0 or odd < 0.)"
            if delta == 1:
                raise TypeError, "n must be a critical value!\n" + "(I.e. odd > 0 or even <= 0.)"
Пример #41
0
def quadratic_L_function__exact(n, d):
    r"""
    Returns the exact value of a quadratic twist of the Riemann Zeta function
    by `\chi_d(x) = \left(\frac{d}{x}\right)`.  

    References:

    - Iwasawa's "Lectures on p-adic L-functions", p16-17, "Special values of
      `L(1-n, \chi)` and `L(n, \chi)`
    - Ireland and Rosen's "A Classical Introduction to Modern Number Theory"
    - Washington's "Cyclotomic Fields"

    EXAMPLES::

        sage: bool(quadratic_L_function__exact(1, -4) == pi/4)
        True

    """
    from sage.all import SR, sqrt
    if n<=0:
        k = 1-n
        return -QuadraticBernoulliNumber(k,d)/k
    elif n>=1:
        ## Compute the kind of critical values (p10)
        if kronecker_symbol(fundamental_discriminant(d), -1) == 1:
            delta = 0
        else:
            delta = 1        

        ## Compute the positive special values (p17)
        if ((n - delta) % 2 == 0):
            f = abs(fundamental_discriminant(d))
            if delta == 0:                            
                GS = sqrt(f)
            else:
                GS = I * sqrt(f)
            ans = SR(ZZ(-1)**(1+(n-delta)/2))
            ans *= (2*pi/f)**n
            ans *= GS     ## Evaluate the Gauss sum here! =0
            ans *= 1/(2 * I**delta)
            ans *= QuadraticBernoulliNumber(n,d)/factorial(n)
            return ans
        else:
            if delta == 0:
                raise TypeError, "n must be a critical value!\n" + "(I.e. even > 0 or odd < 0.)"
            if delta == 1:
                raise TypeError, "n must be a critical value!\n" + "(I.e. odd > 0 or even <= 0.)"
Пример #42
0
    def get_trace_in_PSL(m):
        """
        Given an (extended) matrix acting in an orientation preserving way,
        computes the trace after normalizing the matrix to be in SL(2,C).
        """

        m = ExtendedMatrix.extract_matrix_for_orientation_preserving(m)
        return (m[0, 0] + m[1, 1]) / sqrt(m.det())
Пример #43
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)
Пример #44
0
def gamma__exact(n):
    """
    Evaluates the exact value of the gamma function at an integer or
    half-integer argument.

    EXAMPLES::

        sage: gamma__exact(4)
        6
        sage: gamma__exact(3)
        2
        sage: gamma__exact(2)
        1
        sage: gamma__exact(1)
        1

        sage: gamma__exact(1/2)
        sqrt(pi)
        sage: gamma__exact(3/2)
        1/2*sqrt(pi)
        sage: gamma__exact(5/2)
        3/4*sqrt(pi)
        sage: gamma__exact(7/2)
        15/8*sqrt(pi)

        sage: gamma__exact(-1/2)
        -2*sqrt(pi)
        sage: gamma__exact(-3/2)
        4/3*sqrt(pi)
        sage: gamma__exact(-5/2)
        -8/15*sqrt(pi)
        sage: gamma__exact(-7/2)
        16/105*sqrt(pi)

    """
    from sage.all import sqrt
    ## SANITY CHECK
    if (not n in QQ) or (denominator(n) > 2):
        raise TypeError, "Oops!  You much give an integer or half-integer argument."

    if (denominator(n) == 1):
        if n <= 0:
            return infinity
        if n > 0:
            return factorial(n-1) 
    else:
        ans = QQ(1)
        while (n != QQ(1)/2):
            if (n<0): 
                ans *= QQ(1)/n
                n = n + 1
            elif (n>0):
                n = n - 1
                ans *= n 
            
        ans *= sqrt(pi)
        return ans
Пример #45
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
Пример #46
0
 def renormalise_coefficients(self):
     """
     This turns a list of algebraically normalised coefficients
     as above into a list of automorphically normalised,
     i.e. s <-> 1-s
     """
     # this also turns them into floats and complex.
     for n in range(len(self.dirichlet_coefficients)):
         self.dirichlet_coefficients[n] /= sqrt(float(n+1)**self.motivic_weight)
Пример #47
0
def vect_to_sym(v):
    n = ZZ(round((-1+sqrt(1+8*len(v)))/2))
    M = matrix(n)
    k = 0
    for i in range(n):
        for j in range(i, n):
            M[i,j] = v[k]
            M[j,i] = v[k]
            k=k+1
    return [[int(M[i,j]) for i in range(n)] for j in range(n)]
Пример #48
0
def download_hecke_algebras_full_lists_gen(**args):
    label = str(args['orbit_label'])
    res = db.hecke_orbits.lucky({'orbit_label': label})
    mydate = time.strftime("%d %B %Y")
    if res is None:
        return "No generators available"
    lang = args['lang']
    c = download_comment_prefix[lang]
    mat_start = "Mat(" if lang == 'gp' else "Matrix("
    mat_end = "~)" if lang == 'gp' else ")"
    entry = lambda r: "".join([mat_start,str(r),mat_end])

    outstr = c + 'Hecke algebra for Gamma0(%s) and weight %s, orbit label %s. List of generators for the algebra. Downloaded from the LMFDB on %s. \n\n'%(res['level'], res['weight'], res['orbit_label'], mydate)
    outstr += download_assignment_start[lang] + '[\\\n'
    outstr += ",\\\n".join([entry([list(k) for k in matrix(sqrt(len(r)), sqrt(len(r)), r).rows()]) for r in [[int(i) for i in j] for j in res['Zbasis']] ])
    outstr += ']'
    outstr += download_assignment_end[lang]
    outstr += '\n'
    return outstr
Пример #49
0
    def init_dir_char(self, chi):
        """
        Initiate with a Web Dirichlet character.
        """
        self.original_object = [chi]
        chi = chi.chi.primitive_character()
        self.object_type = "dirichletcharacter"
        self.dim = 1
        self.motivic_weight = 0
        self.conductor = ZZ(chi.conductor())
        self.bad_semistable_primes = []
        self.bad_pot_good = self.conductor.prime_factors()
        if chi.is_odd():
            aa = 1
            bb = I
        else:
            aa = 0
            bb = 1
        self.sign = chi.gauss_sum_numerical() / (bb * float(sqrt(chi.modulus())) )
        # this has now type python complex. later we need a gp complex
        self.sign = ComplexField()(self.sign)
        self.mu_fe = [aa]
        self.nu_fe = []
        self.gammaV = [aa]
        self.langlands = True
        self.selfdual = (chi.multiplicative_order() <= 2)
        # rather than all(  abs(chi(m).imag) < 0.0001 for m in range(chi.modulus() ) )
        self.primitive = True
        self.set_dokchitser_Lfunction()
        self.set_number_of_coefficients()
        self.dirichlet_coefficients = [ chi(m) for m in range(self.numcoeff + 1) ]
        if self.selfdual:
            self.coefficient_type = 2
        else:
            self.coefficient_type = 3
        self.coefficient_period = chi.modulus()
        self.besancon_bound = 10000

        def eu(p):
            """
            local euler factor
            """
            if self.selfdual:
                K = QQ
            else:
                K = ComplexField()
            R = PolynomialRing(K, "T")
            T = R.gens()[0]
            if self.conductor % p != 0:
                return  1 - ComplexField()(chi(p)) * T
            else:
                return R(1)

        self.local_euler_factor = eu
        self.ld.gp().quit()
Пример #50
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
Пример #51
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
Пример #52
0
def eqn_list_to_curve_plot(L,rat_pts):
    xpoly_rng = PolynomialRing(QQ,'x')
    poly_tup = [xpoly_rng(tup) for tup in L]
    f = poly_tup[0]
    h = poly_tup[1]
    g = f+h**2/4
    if len(g.real_roots())==0 and g(0)<0:
        return text("$X(\mathbb{R})=\emptyset$",(1,1),fontsize=50)
    X0 = [real(z[0]) for z in g.base_extend(CC).roots()]+[real(z[0]) for z in g.derivative().base_extend(CC).roots()]
    a,b = inflate_interval(min(X0),max(X0),1.5)
    groots = [a]+g.real_roots()+[b]
    if b-a<1e-7:
        a=-3
        b=3
        groots=[a,b]
    ngints = len(groots)-1
    plotzones = []
    npts = 100
    for j in range(ngints):
        c = groots[j]
        d = groots[j+1]
        if g((c+d)/2)<0:
            continue
        (c,d) = inflate_interval(c,d,1.1)
        s = (d-c)/npts
        u = c
        yvals = []
        for i in range(npts+1):
            v = g(u)
            if v>0:
                v = sqrt(v)
                w = -h(u)/2
                yvals.append(w+v)
                yvals.append(w-v)
            u += s
        (m,M) = inflate_interval(min(yvals),max(yvals),1.2)
        plotzones.append((c,d,m,M))
    x = var('x')
    y = var('y')
    plot=sum(implicit_plot(y**2 + y*h(x) - f(x), (x,R[0],R[1]),(y,R[2],R[3]), aspect_ratio='automatic', plot_points=500, zorder=1) for R in plotzones)
    xmin=min([R[0] for R in plotzones])
    xmax=max([R[1] for R in plotzones])
    ymin=min([R[2] for R in plotzones])
    ymax=max([R[3] for R in plotzones])
    for P in rat_pts:
    	(x,y,z)=eval(P.replace(':',','))
        z=ZZ(z)
     	if z: # Do not attempt to plot points at infinity
      		x=ZZ(x)/z
      		y=ZZ(y)/z**3
      		if x >= xmin and x <= xmax and y >= ymin and y <= ymax:
       			plot += point((x,y),color='red',size=40,zorder=2)
    return plot
Пример #53
0
def download_hecke_algebras_full_lists_mod_op(**args):
    label = str(args['orbit_label'])
    ell=int(args['prime'])
    index=int(args['index'])
    res = db.hecke_ladic.lucky({'orbit_label': label, 'index': index, 'ell': ell})
    mydate = time.strftime("%d %B %Y")
    if res is None:
        return "No mod %s operators available"%ell
    lang = args['lang']
    c = download_comment_prefix[lang]
    field='GF(%s), %s, %s, '%(res['ell'], sqrt(len(res['operators'][0])), sqrt(len(res['operators'][0])))
    mat_start = "Mat("+field if lang == 'gp' else "Matrix("+field 
    mat_end = "~)" if lang == 'gp' else ")"
    entry = lambda r: "".join([mat_start,str(r),mat_end])

    outstr = c + ' List of Hecke operators T_1, ..., T_%s mod %s for orbit %s index %s downloaded from the LMFDB on %s. \n\n'%(len(res['operators']), ell, label, index, mydate)
    outstr += download_assignment_start[lang] +'[\\\n'
    outstr += ",\\\n".join([entry(r) for r in res['operators']])
    outstr += ']'
    outstr += download_assignment_end[lang]
    outstr += '\n'
    return outstr
Пример #54
0
 def test_many(self):
     from sage.all import ZZ, sqrt
     for Nk2 in range(1,2001):
         for N in ZZ(Nk2).divisors():
                 k = sqrt(Nk2/N)
                 if k in ZZ and k > 1:
                     print("testing (N, k) = (%s, %s)" % (N, k))
                     url  = "/ModularForm/GL2/Q/holomorphic/{0}/{1}/".format(N, k)
                     rv = self.tc.get(url,follow_redirects=True)
                     self.assertTrue(rv.status_code==200,"Request failed for {0}".format(url))
                     assert str(N) in rv.data
                     assert str(k) in rv.data
                     assert str(N)+'.'+str(k) in rv.data
Пример #55
0
def prime_range(n):
    X = [x for x in range(3, n + 1) if is_odd(x)]
    P = [2]

    p = X[0]
    while p <= sqrt(n):
        P.append(p)
        X = [x for x in X if x % p != 0]
        p = X[0]

    P.extend(X)

    return P
Пример #56
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
def babystepgiantstep(g, h):
    n = g.multiplicative_order()
    m = ceil(sqrt(n))
    babysteps = {}
    for j in range(m):
        babysteps[g ** j] = j

    X = g ** -m
    a = h
    for i in range(m - 1):
        if a in babysteps:
            return i*m + babysteps[a]
        else:
            a = a * X
Пример #58
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
Пример #59
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