当前位置: 首页>>代码示例>>Python>>正文


Python all.NumberField类代码示例

本文整理汇总了Python中sage.all.NumberField的典型用法代码示例。如果您正苦于以下问题:Python NumberField类的具体用法?Python NumberField怎么用?Python NumberField使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了NumberField类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: find_field

def find_field(pol, verbose=False):
    """
    pol is a string holding a list of coefficients, constant first, 1 last, e.g. '-2,0,1'

    Looks up this defining polynomial kn LMFDB and returns its label, or None
    """
    coeffs = str_to_list(pol)
    deg = len(coeffs)-1
    if deg==2:
        c, b, a = coeffs
        d = ZZ(b*b-4*a*c).squarefree_part()
        D = d if (d-1)%4==0 else 4*d
        absD = D.abs()
        s = 0 if d<0 else 2
        return '2.{}.{}.1'.format(s,absD)

    from lmfdb.number_fields.number_field import poly_to_field_label
    poly = Qx(coeffs)
    Flabel = poly_to_field_label(poly)
    if Flabel==None:
        print("********* field with polynomial {} is not in the database!".format(poly))
        K = NumberField(poly, 'a')
        poly = K.optimized_representation()[0].defining_polynomial()
        print("********* using optimised polynomial {}".format(poly))
        return poly_to_str(poly)
    else:
        if verbose:
            print("{} has label {}".format(pol,Flabel))
        return Flabel
开发者ID:davidfarmer,项目名称:lmfdb,代码行数:29,代码来源:import_torsion_data.py

示例2: get_number_field_integral_basis

def get_number_field_integral_basis(c_string):
    r"""Get the integral basis for the field specified by the string.

    INPUT:
        c_string -- string, a string of comma-separated coefficients with no spaces: the coefficients of the normalized (using gp.polredabs) defining polynomial

    OUTPUT:
        fld_bool -- bool, True if the number field has a page in the LMFDB, False otherwise
        K_new -- number field, the number field with defining polynomial that is the normalized version (given by gp.polredabs) of the one with coefficients specified by c_string
        a -- number field element, generator for K_new
        the integral basis for K_new recorded on its LMFDB page 
    """
    C = getDBconnection()
    c_hash = field_coeffs_string_to_hash(c_string)
    field = C.numberfields.fields.find_one({'coeffhash':c_hash})
    fld_bool = True
    try:
        field['degree']
    except TypeError:
        fld_bool = False
    if fld_bool:
        field_str = field['coeffs']
        int_basis_str = field['zk']
        poly = coeffs_to_poly(field_str)
        K_new = NumberField(poly, names=('a',))
        (a,) = K_new._first_ngens(1)
        return fld_bool, K_new, a, [K_new(eval(preparse(el))) for el in int_basis_str]
    else:
        # could add polynomial to list of number fields missing from LMFDB here
        return fld_bool, None, None, None
开发者ID:LMFDB,项目名称:lmfdb,代码行数:30,代码来源:hecke_eigenvals.py

示例3: _check

 def _check(k, j):
     M = vvsmf(j, k, prec)
     if M.dimension() > 0:
         self.assertEqual(M.dimension(), len(M.basis()))
         _chply = M.hecke_charpoly(2)
         for cply, _ in _chply.factor():
             K = NumberField(cply, names="a")
             a = K.gens()[0]
             f = M.eigenform_with_eigenvalue_t2(a)
             self.assert_hecke_eigen_values(f)
开发者ID:stakemori,项目名称:degree2,代码行数:10,代码来源:test_eigenvalue.py

示例4: test_web_latex_ideal_fact

 def test_web_latex_ideal_fact(self):
     r"""
     Checking utility: web_latex_ideal_fact
     """
     from sage.all import NumberField
     x = var('x')
     K = NumberField(x**2 - 5, 'a')
     a = K.gen()
     I = K.ideal(2/(5+a)).factor()
     self.assertEqual(web_latex_ideal_fact(I),
                      '\\( \\left(-a\\right)^{-1} \\)')
开发者ID:edgarcosta,项目名称:lmfdb,代码行数:11,代码来源:test_utils.py

示例5: upsert_embedding

def upsert_embedding(id_number, skip = False):
    rowcc = db.mf_hecke_cc.lucky({'id':id_number}, projection=['an', 'hecke_orbit_code','id','lfunction_label', 'embedding_root_imag','embedding_root_real'])
    if rowcc is None:
        return
    if skip:
        if rowcc.get("embedding_root_imag", None) is not None:
            if rowcc.get("embedding_root_real", None) is not None:
                return
    row_embeddings =  {}
    hecke_orbit_code = rowcc['hecke_orbit_code']
    newform = db.mf_newforms.lucky({'hecke_orbit_code':hecke_orbit_code})
    if newform is None:
        # No newform in db
        return
    if newform['dim'] == 1:
        row_embeddings['embedding_root_imag'] = 0
        row_embeddings['embedding_root_real'] = 0
    elif newform['weight'] == 1:
        return
    elif newform.get('field_poly', None) is None:
	    return
    else:
        # print rowcc['lfunction_label']
        HF = NumberField(ZZx(newform['field_poly']), "v")
        numerators =  newform['hecke_ring_numerators']
        denominators = newform['hecke_ring_denominators']
        betas = [HF(elt)/denominators[i] for i, elt in enumerate(numerators)]

        embeddings = HF.complex_embeddings(prec=2000)
        an_nf = list(db.mf_hecke_nf.search({'hecke_orbit_code':hecke_orbit_code}, ['n','an'], sort=['n']))
        betas_embedded = [map(elt, betas) for elt in embeddings]
        CCC = betas_embedded[0][0].parent()
        qexp = [convert_eigenvals_to_qexp(elt, an_nf) for elt in betas_embedded]
        min_len = min(len(rowcc['an']), len(qexp[0]))
        an_cc = vector(CCC, map(lambda x: CCC(x[0], x[1]), rowcc['an'][:min_len]))
        #qexp_diff = [ (vector(CCC, elt[:min_len]) - an_cc).norm() for elt in qexp ]
        # normalized, to avoid the unstability comming from large weight
        qexp_diff = [ vector([(elt- an_cc[i])/elt.abs() for i, elt in enumerate(q) if elt != 0]).norm() for j,q in enumerate(qexp)]

        qexp_diff_sorted = sorted(qexp_diff)
        min_diff = qexp_diff_sorted[0]
        #print "min_diff = %.2e \t min_diff/2nd = %.2e" % (min_diff, min_diff/qexp_diff_sorted[1])

        #assuring that is something close to zero, and that no other value is close to it
        assert min_diff < 1e-6
        assert min_diff/qexp_diff_sorted[1] < 1e-15

        for i, elt in enumerate(qexp_diff):
            if elt == min_diff:
                row_embeddings['embedding_root_real'] = float(embeddings[i](HF.gen()).real())
                row_embeddings['embedding_root_imag'] = float(embeddings[i](HF.gen()).imag())
                break
    assert len(row_embeddings) == 2
    db.mf_hecke_cc.upsert({'id': rowcc['id']}, row_embeddings)
开发者ID:koffie,项目名称:lmfdb,代码行数:54,代码来源:populate_embeddings_mf_hecke_cc.py

示例6: list_factored_to_factored_poly_otherorder

def list_factored_to_factored_poly_otherorder(sfacts_fc_list, galois=False, vari = 'T', p = None):
    """
        Either return the polynomial in a nice factored form,
        or return a pair, with first entry the factored polynomial
        and the second entry a list describing the Galois groups
        of the factors.
        vari allows to choose the variable of the polynomial to be returned.
    """
    gal_list=[]
    ZZpT  = PolynomialRing(ZZ, ['p',vari], order = 'negdeglex')
    ZZT = PolynomialRing(ZZ, vari)
    outstr = ''
    for g, e in sfacts_fc_list:
        if galois:
            # hack because currently sage only handles monic polynomials:
            this_poly = ZZT(list(reversed(g)))
            this_degree = this_poly.degree()
            this_number_field = NumberField(this_poly, "a")
            this_gal = this_number_field.galois_group(type='pari')
            this_t_number = this_gal.group().__pari__()[2].sage()
            gal_list.append([this_degree, this_t_number])

        # casting from ZZT -> ZZpT
        if p is None:
            gtoprint = dict( zip( zip( [0]*len(g), range(len(g))), g) )
        else:
            gtoprint = {}
            for i, elt in enumerate(g):
                if elt != 0:
                    val =  ZZ(elt).valuation(p)
                    gtoprint[(val, i)] = elt/p**val
        glatex = latex(ZZpT(gtoprint))
        if  e > 1:
            outstr += '( %s )^{%d}' % (glatex, e)
        elif len(sfacts_fc_list) > 1:
            outstr += '( %s )' % (glatex,)
        else:
            outstr += glatex

    if galois:
        # 2 factors of degree 2
        if len(sfacts_fc_list)==2:
            if len(sfacts_fc_list[0][0]) == 3 and len(sfacts_fc_list[1][0]) == 3:
                troubletest = ZZT(sfacts_fc_list[0][0]).disc()*ZZT(sfacts_fc_list[1][0]).disc()
                if troubletest.is_square():
                    gal_list=[[2,1]]
        return outstr, gal_list
    return outstr
开发者ID:LMFDB,项目名称:lmfdb,代码行数:48,代码来源:utilities.py

示例7: _test_an_dict_over_Q

def _test_an_dict_over_Q(ainvs, B=100):
    """
    Test that the an_dict function works and gives the correct answer
    for an elliptic curve defined over QQ, by computing using the
    generic code in this file, and comparing with the output of Sage's
    anlist function for rational elliptic curves.
    """
    from sage.all import polygen, QQ, NumberField, EllipticCurve
    x = polygen(QQ,'x')
    F = NumberField(x - 1,'a'); a = F.gen()
    E = EllipticCurve(F, ainvs)
    EQ = EllipticCurve(QQ, ainvs)
    v = EQ.anlist(B)
    an = an_dict(E, B)
    for i, j in an.iteritems():
        assert j == v[i[0]]
开发者ID:Alwnikrotikz,项目名称:purplesage,代码行数:16,代码来源:aplist.py

示例8: test_ramanujan_conj

 def test_ramanujan_conj(self):
     '''Test Ramanujan conjectures for eigenforms of determinant weights
     less than or equal to 29.
     '''
     prec = 6
     hpl = hilbert_series_maybe(10)
     for k in range(22, 30):
         if hpl[k] != 0:
             N = sym10_space(k, prec, data_directory=data_dir)
             self.assertEqual(N.dimension(), len(N.basis()))
             _chply = N.hecke_charpoly(2)
             for cply, _ in _chply.factor():
                 K = NumberField(cply, names="a")
                 a = K.gens()[0]
                 f = N.eigenform_with_eigenvalue_t2(a)
                 self.assert_ramanujan_conj_eigenform(f)
开发者ID:stakemori,项目名称:degree2,代码行数:16,代码来源:test_ramanujan_conj.py

示例9: create_small_record

 def create_small_record(self, min_prec=10, want_prec=100, max_length = 5242880, max_height_qexp = default_max_height):
     ### creates a duplicate record (fs) of this webnewform
     ### with lower precision to load faster on the web
     ### we aim to have at most max_length bytes
     ### but at least min_prec coefficients and we desire to have want_prec
     if min_prec>=self.prec:
         raise ValueError("Need higher precision, self.prec = {}".format(self.prec))
     if not hasattr(self, '_file_record_length'):
         self.update_from_db()
     l = self._file_record_length
         
     if l > max_length or self.prec > want_prec:
         nl = float(l)/float(self.prec)*float(want_prec)
         if nl > max_length:
             prec = max([floor(float(self.prec)/float(l)*float(max_length)), min_prec])
         else:
             prec = want_prec
         emf_logger.debug("Creating a new record with prec = {}".format(prec))
         self.prec = prec
         include_coeffs = self.complexity_of_first_nonvanishing_coefficients() <= default_max_height
         if include_coeffs:
             self.q_expansion = self.q_expansion.truncate_powerseries(prec)
             self._coefficients = {n:c for n,c in self._coefficients.iteritems() if n<prec}
         else:
             self.q_expansion = self.q_expansion.truncate_powerseries(1)
             self._coefficients = {}
             self.prec = 0
             self.coefficient_field = NumberField(self.absolute_polynomial, names=str(self.coefficient_field.gen()))
         self._embeddings['values'] = {n:c for n,c in self._embeddings['values'].iteritems() if n<prec}
         self._embeddings['prec'] = prec
         self.save_to_db()
开发者ID:jwj61,项目名称:lmfdb,代码行数:31,代码来源:web_newforms.py

示例10: test1

def test1(B=50):
    """
    Tests that the functions all run without crashing over a specific number field.
    Does not test that the output is correct.  That should be in
    another test.
    """
    from sage.all import polygen, QQ, NumberField, EllipticCurve
    x = polygen(QQ,'x')
    F = NumberField(x**2 - x - 1,'a'); a = F.gen()
    E = EllipticCurve([1,a+1,a,a,0])
    ap(E,F.ideal(3))
    primes_of_bounded_norm(F,B)
    ap_list(E,B)
    assert len(ap_list(E,B,primes=True)) == 2
    apd = ap_dict(E,B)
    reduced_rep(F.ideal(3))
    assert an_dict(E,B) == an_dict_from_ap(apd, E.conductor(), B)
开发者ID:Alwnikrotikz,项目名称:purplesage,代码行数:17,代码来源:aplist.py

示例11: number_field_from_dict

def number_field_from_dict(d):
    r"""
    INPUT:

    - 'd' -- {'base':F,'p':p,'g':g } where p is a polynomial in the variable(s) xN with coefficients in K. (The 'x' is just a convention)

    OUTPUT:

    - 'F' -- Number field extending K with relative minimal polynomial p.
    """
    K = d['base']; p=d['relative polynomial']; g=d['gens']
    if K=='QQ':
        K = QQ
    elif isinstance(K,dict):
        K = number_field_from_dict(K)
    else:
        raise ValueError,"Could not construct number field!"
    F = NumberField(K[g](p),names=g)
    if F.absolute_degree()==1:
        F = QQ
    return F
开发者ID:am-github,项目名称:lmfdb,代码行数:21,代码来源:web_object.py

示例12: get_hmfs_hecke_field_and_eigenvals

def get_hmfs_hecke_field_and_eigenvals(label):
    """Get the Hecke field and eigenvalues for the Hilbert modular form with given label.

    INPUT:
        label -- string, the label of the Hilbert modular form

    OUTPUT:
        K_old -- number field, the field containing the Hecke eigenvalues
        e -- number field element, a generator for K_old over QQ
        eigenvals -- list, a list of the Hecke eigenvalues
    """
    C = getDBconnection()
    # Should I use find_one, or something else?
    R = PolynomialRing(QQ,names=('x'))
    form = C.hmfs.forms.find_one({'label':label})
    poly = R(str(form['hecke_polynomial']))
    K_old = NumberField(poly, names=('e',))
    (e,) = K_old._first_ngens(1)
    eigenvals_str = form['hecke_eigenvalues']
    eigenvals = [K_old(eval(preparse(el))) for el in eigenvals_str]
    return K_old, e, eigenvals
开发者ID:LMFDB,项目名称:lmfdb,代码行数:21,代码来源:hecke_eigenvals.py

示例13: find_newform_label

def find_newform_label(level,weight,character,field,aps):
    r"""
    Find the label of the newform orbit in the database which matches the input.
    
    INPUT:
    - 'level'     -- the level,
    - 'weight'    -- the weight
    - 'character' -- the character'
    - 'field'     -- the field, given in terms of a list of integer coefficients for the absolute polynomial  
    - 'aps'       -- the coefficients - given as a dictionary of lists giving the coefficient in terms of the generator of the field as above.
    
    
    EXAMPLE:
    
    sage: find_newform_label(9,16,1,[-119880,0,1],{2:[0,1]})
    u'e'
    sage: find_newform_label(71,2,1,[-3,-4,1,1],{3:[0,-1,0]})
    u'a'
    sage: find_newform_label(71,2,1,[-3,-4,1,1],{5:[5,1,-1]})
    u'a'
    
    NOTE: We implicitly assume that the input given is correct in the sense that 
        if there is a unique orbit with a coefficient field of the same degree as the input
        then we simply return that label. (This will save a lot of time...)
        
    """
    from web_modform_space import WebModFormSpace
    from sage.all import NumberField,QQ
    M = WebModFormSpace(level=level,weight=weight,character=character)
    if M.dimension_new_cusp_forms==1:
        return 'a'
    orbits = M.hecke_orbits
    ## construct field from field input... 
    if not isinstance(field,list):
        raise ValueError,"Need to give field as a list!"
    if not isinstance(aps,dict):
        raise ValueError,"Need to give aps as a dict!"
    if field == [1]:
        NF = QQ
    else:
        NF = NumberField(QQ['x'](field),names='x')
    degree_of_input = NF.absolute_degree()
    degrees = map(lambda x:x[1].coefficient_field_degree,orbits.viewitems())
    if degrees.count(degree_of_input)==0:
        raise ValueError,"No newform with this level, weight, character and field degree!"
    if degrees.count(degree_of_input)==1:
        ## If there is a unique mathcing field we return this orbit label.
        l = filter(lambda x: x[1].coefficient_field_degree==degree_of_input,orbits.viewitems() )
        return l[0][0]
    aps_input = { p: NF(a) for p,a in aps.viewitems()}
    possible_labels = orbits.keys()
    for label,f in orbits.viewitems():
        if f.coefficient_field_degree != degree_of_input:
            possible_labels.remove(label)
            continue
        try:
            for p,ap_input in aps_input.viewitems():
                if f.coefficient_field == QQ:
                    homs = [lambda x: x]
                else:
                    homs = f.coefficient(p).parent().Hom(NF)
                for h in homs:
                    ap = h(f.coefficient(p))
                    if ap_input != ap:
                        possible_labels.remove(label)
                        raise StopIteration
        except StopIteration:
            continue
    if len(possible_labels) > 1:
        raise ArithmeticError,"Not sufficient data (or errors) to determine orbit!"
    if len(possible_labels) == 0:
        raise ArithmeticError,"Not sufficient data (or errors) to determine orbit! NO matching label found!"
    return possible_labels[0]
开发者ID:kedlaya,项目名称:lmfdb,代码行数:73,代码来源:emf_utils.py

示例14: hecke_ops

    sage: c = F.primes_above(389)[0]
    sage: T = hecke_ops(c, TH)
    sage: for nm,p,t in T:
    ...       print nm, p, t.charpoly().factor()
    5 a + 2 (x - 6) * (x^2 + 4*x - 1) * (x^2 - x - 4)^2
    9 3 (x - 10) * (x^2 + 3*x - 9) * (x^4 - 5*x^3 + 3*x^2 + 6*x - 4)
    11 a + 3 (x - 12) * (x + 3)^2 * (x^4 - 17*x^2 + 68)
    11 2*a + 3 (x - 12) * (x^2 + 5*x + 5) * (x^4 - x^3 - 23*x^2 + 18*x + 52)
"""


from sage.all import (NumberField, polygen, QQ, ZZ, QuaternionAlgebra,
                      cached_function, disk_cached_function)

x = polygen(QQ,'x')
F = NumberField(x**2 - x -1, 'a')
O_F = F.ring_of_integers()
B = QuaternionAlgebra(F, -1, -1, 'i,j,k')

def modp_splitting(p):
    """
    INPUT:
        
        - p -- ideal of the number field K = B.base() with ring O of integers.
        
    OUTPUT:
        
        - matrices I, J in M_2(O/p) such that i |--> I and j |--> J defines 
          an algebra morphism, i.e., I^2=a, J^2=b, I*J=-J*I.

    EXAMPLES::    
开发者ID:williamstein,项目名称:hilbert-sqrt5,代码行数:31,代码来源:sqrt5.py

示例15: upsert_embedding

def upsert_embedding(id_number, skip = True):
    rowcc = db.mf_hecke_cc.lucky({'id':id_number}, projection=['an_normalized', 'hecke_orbit_code','id','lfunction_label', 'embedding_root_imag','embedding_root_real'])
    if rowcc is None:
        return
    if skip:
        if rowcc.get("embedding_root_imag", None) is not None:
            if rowcc.get("embedding_root_real", None) is not None:
                return
    row_embeddings =  {}
    hecke_orbit_code = rowcc['hecke_orbit_code']
    newform = db.mf_newforms.lucky({'hecke_orbit_code':hecke_orbit_code},['label','weight','field_poly','dim'])
    if newform is None:
        # No newform in db
        return
    if newform['dim'] == 1:
        row_embeddings['embedding_root_imag'] = 0
        row_embeddings['embedding_root_real'] = 0
    elif newform['weight'] == 1:
        return
    elif newform.get('field_poly', None) is None:
	    return
    else:
        # print rowcc['lfunction_label']
        HF = NumberField(ZZx(newform['field_poly']), "v")
        hecke_nf = db.mf_hecke_nf.lucky({'hecke_orbit_code':hecke_orbit_code}, ['hecke_ring_cyclotomic_generator','an','field_poly','hecke_ring_numerators','hecke_ring_denominators', 'hecke_ring_power_basis'])
        assert hecke_nf is not None
        assert newform['field_poly'] == hecke_nf['field_poly']
        assert hecke_nf['hecke_ring_cyclotomic_generator'] == 0
        if hecke_nf['hecke_ring_power_basis']:
            v = HF.gens()[0]
            betas = [ v**i for i in range(len(newform['field_poly'])) ]
        else:
            numerators =  hecke_nf.get('hecke_ring_numerators')
            denominators = hecke_nf.get('hecke_ring_denominators')
            betas = [HF(elt)/denominators[i] for i, elt in enumerate(numerators)]

        embeddings = HF.complex_embeddings(prec=2000)
        an_nf = hecke_nf['an']
        betas_embedded = [map(elt, betas) for elt in embeddings]
        CCC = betas_embedded[0][0].parent()
        normalization = -CCC(newform['weight'] - 1).real()/2
        qexp = [convert_eigenvals_to_qexp(elt, an_nf, normalization) for elt in betas_embedded]
        min_len = min(len(rowcc['an_normalized']), len(qexp[0]))
        an_cc = vector(CCC, map(lambda x: CCC(x[0], x[1]), rowcc['an_normalized'][:min_len]))
        #qexp_diff = [ (vector(CCC, elt[:min_len]) - an_cc).norm() for elt in qexp ]
        # normalized, to avoid the unstability comming from large weight
        qexp_diff = [ vector([(elt- an_cc[i])/elt.abs() for i, elt in enumerate(q) if elt != 0]).norm() for j,q in enumerate(qexp)]

        qexp_diff_sorted = sorted(qexp_diff)
        min_diff = qexp_diff_sorted[0]

        #assuring that is something close to zero, and that no other value is close to it
        assert min_diff < 1e-6 and min_diff/qexp_diff_sorted[1] < 1e-15, "id = %d label = %s\nmin_diff = %.2e \t min_diff/2nd = %.2e\nan_cc = %s\nqexp = %s" % (id_number, rowcc['lfunction_label'], min_diff, min_diff/qexp_diff_sorted[1], vector(ComplexField(20), an_cc[:5]), matrix(ComplexField(20), [elt[:5] for elt in qexp]))

        for i, elt in enumerate(qexp_diff):
            if elt == min_diff:
                row_embeddings['embedding_root_real'] = float(embeddings[i](HF.gen()).real())
                row_embeddings['embedding_root_imag'] = float(embeddings[i](HF.gen()).imag())
                break
    assert len(row_embeddings) == 2
    db.mf_hecke_cc.upsert({'id': rowcc['id']}, row_embeddings)
开发者ID:LMFDB,项目名称:lmfdb,代码行数:61,代码来源:populate_embeddings_mf_hecke_cc.py


注:本文中的sage.all.NumberField类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。