Esempio n. 1
0
def queryUploadDatabase(filename, path, limit=0):
    file = getDBConnection().upload.fs.files.find_one({
        "metadata.related_to": path,
        "filename": filename
    })
    upload_fs = GridFS(getDBConnection().upload)
    return upload_fs.get(file['_id']).read(limit)
Esempio n. 2
0
def profile(userid):
    getDBConnection().knowledge.knowls.ensure_index('title')
    user = LmfdbUser(userid)
    bread = base_bread() + [
        (user.name, url_for('.profile', userid=user.get_id()))
    ]
    userknowls = getDBConnection().knowledge.knowls.find(
        {
            'authors': userid
        }, fields=['title']).sort([('title', ASC)])
    userfiles = getDBConnection().upload.fs.files.find({
        'metadata.uploader_id':
        userid,
        'metadata.status':
        'approved'
    })
    userfilesmod = getDBConnection().upload.fs.files.find({
        'metadata.uploader_id':
        userid,
        'metadata.status':
        'unmoderated'
    })
    return render_template("user-detail.html",
                           user=user,
                           title="%s" % user.name,
                           bread=bread,
                           userknowls=userknowls,
                           userfiles=userfiles,
                           userfilesmod=userfilesmod)
Esempio n. 3
0
def updateMetadata():
  db = getDBConnection().upload
  id = request.values['id']
  property = request.values['property']
  value = request.values['value']
  db.fs.files.update({"_id" : ObjectId(id)}, {"$set": {"metadata."+property : value}})
  if property == "status":
    db.fs.files.update({"metadata.parent_archive_id" : ObjectId(id)}, {"$set": {"metadata.status" : value+"child"}}, multi=1)
  return getDBConnection().upload.fs.files.find_one({"_id" : ObjectId(id)})['metadata'][property]
Esempio n. 4
0
def profile(userid):
  getDBConnection().knowledge.knowls.ensure_index('title')
  user = LmfdbUser(userid)
  bread = base_bread() + [(user.name, url_for('.profile', userid=user.get_id()))]
  userknowls = getDBConnection().knowledge.knowls.find({'authors' : userid}, fields=['title']).sort([('title', ASC)])
  userfiles = getDBConnection().upload.fs.files.find({'metadata.uploader_id' : userid, 'metadata.status': 'approved'})
  userfilesmod = getDBConnection().upload.fs.files.find({'metadata.uploader_id' : userid, 'metadata.status': 'unmoderated'})
  return render_template("user-detail.html", user=user, 
      title="%s" % user.name, bread= bread, userknowls = userknowls, userfiles = userfiles, userfilesmod = userfilesmod)
Esempio n. 5
0
 def field_knowl(self):
     from WebNumberField import nf_display_knowl
     nfgg = self.number_field_galois_group()
     if nfgg.url_for():
         return nf_display_knowl(nfgg.label(), getDBConnection(), nfgg.polredabshtml())
     else:
         return nfgg.polredabshtml()
Esempio n. 6
0
    def __init__(self, dbname='', **kwds):
        r"""
        For 'one-dimensiona' data sets the second skip parameter does not have a meaning but should be present anyway...

        """
        self._skip = kwds.get('skip', [])
        self._limit = kwds.get('limit', [])
        self._keys = kwds.get('keys', [])
        self._db = getDBConnection()[dbname]
        self._collection_name = kwds.get('collection', 'all')
        self._collection = []
        self._skip_rec = 0
        self._props = {}
        if self._limit and self._skip:
            self._nrows = self._limit[0]
            if len(self._limit) > 1:
                self._ncols = self._limit[1]
            else:
                self._ncols = 1
            if len(self._skip) == 2:
                self._skip_rows = self._skip[0]
                self._skip_cols = self._skip[1]
            else:
                self._skip_rec = self._skip[0]
        self._table = dict()
        self._is_set = False
        self._set_collection()
        self._row_heads = []
        self._col_heads = []
Esempio n. 7
0
def query(**kwargs):
    C = getDBConnection()
    degree = request.args.get("degree", 0, type=int)
    level = request.args.get("level", 0, type=int)
    first_zero_start = request.args.get("zerolowerbound", -1.0, type=float)
    first_zero_end = request.args.get("zeroupperbound", -1.0, type=float)
    sort = request.args.get("sort", "first_zero", type=str)
    direction = request.args.get("direction", "up", type=str)

    if sort not in ['degree', 'first_zero', 'level', 'coeffs']:
        sort = "first_zero"
    if direction not in ["up", "down"]:
        direction = "up"

    if direction == "up":
        direction = pymongo.ASCENDING
    else:
        direction = pymongo.DESCENDING

    filter = {}
    if degree:
        filter['degree'] = degree
    if level:
        filter['level'] = level

    if first_zero_start != -1.0 or first_zero_end != -1.0:
        filter['first_zero'] = {}
    if first_zero_start != -1.0:
        filter['first_zero']['$gte'] = float(first_zero_start)
    if first_zero_end != -1.0:
        filter['first_zero']['$lte'] = float(first_zero_end)

    query = C.test.Lfunctions_test2.find(filter).sort(sort, direction)
    pagination = LazyMongoDBPagination(query = query, per_page=50, page=request.args.get('page', 1), endpoint=".query", endpoint_params=dict(request.args))
    return render_template('lf-list.html', pagination=pagination, title=title)
Esempio n. 8
0
def alive():
    try:
        conn = getDBConnection()
        assert conn.userdb.users.count()
    except:
        abort(503)
    return "LMFDB!"
Esempio n. 9
0
def admin_update():

    db = getDBConnection().upload
    fs = GridFS(db)
    id = request.form['id']

    if request.form.has_key('approve'):
        db.fs.files.update({"_id": ObjectId(id)},
                           {"$set": {
                               "metadata.status": "approved"
                           }})
        db.fs.files.update({"metadata.parent_archive_id": ObjectId(id)},
                           {"$set": {
                               "metadata.status": "approvedchild"
                           }},
                           multi=1)
        flask.flash('Approved')
    if request.form.has_key('disapprove'):
        db.fs.files.update({"_id": ObjectId(id)},
                           {"$set": {
                               "metadata.status": "disapproved"
                           }})
        db.fs.files.update({"metadata.parent_archive_id": ObjectId(id)},
                           {"$set": {
                               "metadata.status": "disapprovedchild"
                           }},
                           multi=1)
        flask.flash('Disapproved')

    return flask.redirect(url_for(".admin"))
Esempio n. 10
0
def download(id, filename):
    file = GridFS(getDBConnection().upload).get(ObjectId(id))
    response = flask.Response(file.__iter__())
    response.headers['content-type'] = file.metadata['content_type']
    response.content_length = file.length

    return response
Esempio n. 11
0
def download(id, filename):
  file = GridFS(getDBConnection().upload).get(ObjectId(id))
  response = flask.Response(file.__iter__())
  response.headers['content-type'] = file.metadata['content_type']
  response.content_length=file.length
  
  return response
Esempio n. 12
0
    def __init__(self,dbname='',**kwds):
        r"""
        For 'one-dimensiona' data sets the second skip parameter does not have a meaning but should be present anyway...

        """
        self._skip = kwds.get('skip',[])
        self._limit= kwds.get('limit',[])
        self._keys= kwds.get('keys',[])
        self._db = getDBConnection()[dbname]
        self._collection_name=kwds.get('collection','all')
        self._collection = []
        self._skip_rec=0
        self._props = {}
        if self._limit and self._skip:
            self._nrows = self._limit[0]
            if len(self._limit)>1:
                self._ncols = self._limit[1]
            else:
                self._ncols = 1
            if len(self._skip)==2:
                self._skip_rows=self._skip[0]
                self._skip_cols=self._skip[1]
            else:
                self._skip_rec = self._skip[0]
        self._table=dict()
        self._is_set=False
        self._set_collection()
        self._row_heads=[]
        self._col_heads=[]
Esempio n. 13
0
def alive():
    try:
        conn = getDBConnection()
        assert conn.userdb.users.count()
    except:
        abort(503)
    return "LMFDB!"
Esempio n. 14
0
def zero_search(**kwargs):
    C = getDBConnection()
    if not 'zero' in kwargs:
        query = C.test.Lfunctions_test2.find().sort('first_zero')
    else:
        zero = float(kwargs['zero'])
        query = C.test.Lfunctions_test2.find({
            'first_zero': {
                '$lt': zero + .1,
                '$gt': zero - .1
            }
        }).sort('first_zero')
    pagination = LazyMongoDBPagination(query=query,
                                       per_page=50,
                                       page=request.args.get('page', 1),
                                       endpoint=".zero_search",
                                       endpoint_params=kwargs)
    #result_string = ""
    #printed_arrow = False
    #for x in L:
    #    if x['zero'] > zero and printed_arrow == False:
    #        result_string = result_string + "-------->"
    #        printed_arrow = True
    #    result_string = result_string + str(x['zero']) + " " + str(x['modulus']) + " " + str(x['character']) + "<br>\n"
    #return result_string
    return render_template('lf-list.html', pagination=pagination, title=title)
Esempio n. 15
0
def updateMetadata():
    db = getDBConnection().upload
    id = request.values['id']
    property = request.values['property']
    value = request.values['value']
    db.fs.files.update({"_id": ObjectId(id)},
                       {"$set": {
                           "metadata." + property: value
                       }})
    if property == "status":
        db.fs.files.update({"metadata.parent_archive_id": ObjectId(id)},
                           {"$set": {
                               "metadata.status": value + "child"
                           }},
                           multi=1)
    return getDBConnection().upload.fs.files.find_one({"_id": ObjectId(id)
                                                       })['metadata'][property]
Esempio n. 16
0
 def field_knowl(self):
     from WebNumberField import nf_display_knowl
     nfgg = self.number_field_galois_group()
     if nfgg.url_for():
         return nf_display_knowl(nfgg.label(), getDBConnection(),
                                 nfgg.polredabshtml())
     else:
         return nfgg.polredabshtml()
Esempio n. 17
0
def download_hmf_magma(**args):
    C = getDBConnection()
    data = None
    label = str(args['label'])
    f = C.hmfs.forms.find_one({'label': label})
    if f is None:
        return "No such form"

    F = WebNumberField(f['field_label'])
    F_hmf = C.hmfs.fields.find_one({'label': f['field_label']})

    outstr = 'P<x> := PolynomialRing(Rationals());\n'
    outstr += 'g := P!' + str(F.coeffs()) + ';\n'
    outstr += 'F<w> := NumberField(g);\n'
    outstr += 'ZF := Integers(F);\n\n'
    #    outstr += 'ideals_str := [' + ','.join([st for st in F_hmf["ideals"]]) + '];\n'
    #    outstr += 'ideals := [ideal<ZF | {F!x : x in I}> : I in ideals_str];\n\n'

    outstr += 'NN := ideal<ZF | {' + f["level_ideal"][1:-1] + '}>;\n\n'

    outstr += 'primesArray := [\n' + ','.join(
        [st for st in F_hmf["primes"]]).replace('],[', '],\n[') + '];\n'
    outstr += 'primes := [ideal<ZF | {F!x : x in I}> : I in primesArray];\n\n'

    if f["hecke_polynomial"] != 'x':
        outstr += 'heckePol := ' + f["hecke_polynomial"] + ';\n'
        outstr += 'K<e> := NumberField(heckePol);\n'
    else:
        outstr += 'heckePol := x;\nK := Rationals(); e := 1;\n'

    outstr += '\nheckeEigenvaluesArray := [' + ', '.join(
        [st for st in f["hecke_eigenvalues"]]) + '];'
    outstr += '\nheckeEigenvalues := AssociativeArray();\n'
    outstr += 'for i := 1 to #heckeEigenvaluesArray do\n  heckeEigenvalues[primes[i]] := heckeEigenvaluesArray[i];\nend for;\n\n'

    outstr += 'ALEigenvalues := AssociativeArray();\n'
    for s in f["AL_eigenvalues"]:
        outstr += 'ALEigenvalues[ideal<ZF | {' + s[0][1:-1] + '}>] := ' + s[
            1] + ';\n'

    outstr += '\n// EXAMPLE:\n// pp := Factorization(2*ZF)[1][1];\n// heckeEigenvalues[pp];\n\n'

    outstr += '/* EXTRA CODE: recompute eigenform (warning, may take a few minutes or longer!):\n'
    outstr += 'M := HilbertCuspForms(F, NN);\n'
    outstr += 'S := NewSubspace(M);\n'
    outstr += '// SetVerbose("ModFrmHil", 1);\n'
    outstr += 'newspaces := NewformDecomposition(S);\n'
    outstr += 'newforms := [Eigenform(U) : U in newspaces];\n'
    outstr += 'ppind := 0;\n'
    outstr += 'while #newforms gt 1 do\n'
    outstr += '  pp := primes[ppind];\n'
    outstr += '  newforms := [f : f in newforms | HeckeEigenvalue(f,pp) eq heckeEigenvalues[pp]];\n'
    outstr += 'end while;\n'
    outstr += 'f := newforms[1];\n'
    outstr += '// [HeckeEigenvalue(f,pp) : pp in primes] eq heckeEigenvaluesArray;\n'
    outstr += '*/\n'

    return outstr
def render_hmf_webpage(**args):
    C = getDBConnection()
    data = None
    if 'label' in args:
        label = str(args['label'])
        data = C.hmfs.forms.find_one({'label': label})
    if data is None:
        return "No such field"    
    info = {}
    try:
        info['count'] = args['count']
    except KeyError:
        info['count'] = 10

    hmf_field  = C.hmfs.fields.find_one({'label': data['field_label']})
    field_info = C.numberfields.fields.find_one({'label': data['field_label']})
    field_info['galois_group'] = str(field_info['galois_group'][3])
    info['field_info'] = field_info
    info['field_poly'] = pol_to_html(str(coeff_to_poly(field_info['coefficients'])))

    data['field_label'] = field_pretty(data['field_label'])
    info.update(data)
    info['downloads_visible'] = True
    info['downloads'] = [('worksheet (not yet)', '/')]
    info['friends'] = [('L-function (not yet)', '/')]
#    info['learnmore'] = [('Number Field labels', url_for("render_labels_page")), ('Galois group labels',url_for("render_groups_page")), ('Discriminant ranges',url_for("render_discriminants_page"))]
    bread = [('Hilbert Modular Forms', url_for("hilbert_modular_form_render_webpage")),('%s'%data['label'],' ')]

    t = "Hilbert Cusp Form %s" % info['label']
    credit = 'L. Dembele, S. Donnelly and J. Voight'

    eigs = eval(data['hecke_eigenvalues'])
    primes = hmf_field['primes']
    w = polygen(QQ,'w')
    n = min(len(eigs),len(primes))
    info['eigs'] = [{'eigenvalue': eigs[i],
                     'prime_ideal': primes[i], 
                     'prime_norm': primes[i][0]} for i in range(n)]
        
    properties = []
    properties = ['<br>']
    properties.extend('<table>')
    properties.extend('<tr><td align=left>Field:<td align=left>%s</td>'%data["field_label"])
    properties.extend('<tr><td align=left>Degree:<td align=left> %s</td>'%field_info['degree'])
    properties.extend('<tr><td align=left>Discriminant:<td align=left>%s</td>'%field_info['discriminant'])
    properties.extend('<tr><td align=left>Polynomial:<td align=left>%s</td>'%field_info['discriminant'])
    properties.extend('<tr><td align=left>Class number:<td align=left>%s</td>'%field_info['class_number'])
    properties.extend('<tr><td align=left>Galois group:<td align=left>%s</td>'%field_info['galois_group'])
    properties.extend('</table>')
    properties.extend('<hr>')
    properties.extend('<table>')
    properties.extend('<tr><td align=left>Weight:<td align=left>%s</td>'%data["weight"])
    properties.extend('<tr><td align=left>Level:<td align=left> %s</td>'%data['level_ideal'])
    properties.extend('<tr><td align=left>Level Norm:<td align=left>%s</td>'%data['level_norm'])
    properties.extend('<tr><td align=left>Label:<td align=left>%s</td>'%data['label_suffix'])
    properties.extend('</table>')

    return render_template("hilbert_modular_form/hilbert_modular_form.html", info = info, properties=properties, credit=credit, title = t, bread=bread)
Esempio n. 19
0
def database_list():
    all_db = []
    C = base.getDBConnection()
    for db_name in C.database_names():
        if db_name in ('admin', 'local'):
            continue
        db = getattr(C, db_name)
        all_db.append((db_name, filter(is_safe, db.collection_names())))
    return render_template("raw/index.html", all_db = all_db, title="Number Theory Database")
Esempio n. 20
0
def upload():

  stream = None
  fn = None
  content_type = None
  if request.form['url'] != "":
    stream = urlopen(request.form['url'])
    fn = path.basename(urlparse(request.form['url']).path)
    content_type = stream.info().gettype()
  else:
    stream = request.files['file']
    fn = request.files['file'].filename
    content_type = request.files['file'].content_type

  metadata = {
    "name": request.form['name'],
    "full_description": request.form['full_description'],
    "related_to": request.form['related_to'],
    "data_format": request.form['data_format'],
    "creator": request.form['creator'],
    "reference": request.form['reference'],
    "bibtex": request.form['bibtex'],
    "comments": request.form['comments'],
    "uploader": current_user.name,
    "uploader_id": current_user.id,
    "time": datetime.datetime.utcnow(),
    "original_file_name": fn,
    "status": "unmoderated",
    "version": "1",
    "file_url": request.form['url'],
    "content_type": content_type
  }
  flask.flash("Received file '%s' and awaiting moderation from an administrator" % fn)

  upload_db = getDBConnection().upload
  upload_fs = GridFS(upload_db)
  db_id = upload_fs.put(stream.read(), metadata = metadata, filename=fn)
  
  logging.info("file '%s' receieved and data with id '%s' stored" % (fn, db_id))

  if fn[-4:] == ".tgz" or fn[-4:] == ".tar" or fn[-7:] == ".tar.gz" :
    child_index = []
    tar = tarfile.open(fileobj=upload_fs.get(ObjectId(db_id)))
    for tarinfo in tar:
      if tarinfo.isfile():
        metadata2 = copy.copy(metadata)
        metadata2['parent_archive_id'] = db_id
        metadata2['parent_archive_filename'] = fn
        metadata2['status'] = "unmoderatedchild"
        metadata2['original_file_name'] = fn+"/"+tarinfo.name
        metadata2['related_to'] = ""
        metadata2['content_type'] = ""
        id = upload_fs.put( tar.extractfile(tarinfo).read(), metadata = metadata2, filename=fn+"/"+tarinfo.name )
        child_index.append([id, tarinfo.name]);
    upload_db.fs.files.update({"_id": db_id}, {"$set": {"metadata.child_index": child_index}})
  
  return flask.redirect("/upload/view/"+str(db_id))
Esempio n. 21
0
def viewAll():

  db = getDBConnection().upload
  fs = GridFS(db)

  approved = [ fs.get(x['_id']) for x in db.fs.files.find({"metadata.status" : "approved"}) ]
  unmoderated = [ fs.get(x['_id']) for x in db.fs.files.find({"metadata.status" : "unmoderated"}) ]

  return render_template("upload-view.html", title = "Uploaded data", bread = get_bread(), approved=approved, unmoderated2=unmoderated)
Esempio n. 22
0
def get_knowls():
  _C = getDBConnection()
  knowls = _C.knowledge.knowls
  knowls.ensure_index('authors')
  # _keywords is used for the full text search
  knowls.ensure_index('title')
  knowls.ensure_index('cat')
  knowls.ensure_index('_keywords')
  return knowls
Esempio n. 23
0
def get_knowls():
    _C = getDBConnection()
    knowls = _C.knowledge.knowls
    knowls.ensure_index('authors')
    # _keywords is used for the full text search
    knowls.ensure_index('title')
    knowls.ensure_index('cat')
    knowls.ensure_index('_keywords')
    return knowls
Esempio n. 24
0
def admin():

  db = getDBConnection().upload
  fs = GridFS(db)

  unmoderated = [ fs.get(x['_id']) for x in db.fs.files.find({"metadata.status" : "unmoderated"}) ]
  approved = [ fs.get(x['_id']) for x in db.fs.files.find({"metadata.status" : "approved"}) ]
  disapproved = [ fs.get(x['_id']) for x in db.fs.files.find({"metadata.status" : "disapproved"}) ]

  return render_template("upload-view.html", title = "Moderate uploaded data", bread = get_bread(), unmoderated=unmoderated)#, approved=approved, disapproved=disapproved)
Esempio n. 25
0
def download_hmf_magma(**args):
    C = getDBConnection()
    data = None
    label = str(args['label'])
    f = C.hmfs.forms.find_one({'label': label})
    if f is None:
        return "No such form"

    F = WebNumberField(f['field_label'])
    F_hmf = C.hmfs.fields.find_one({'label': f['field_label']})

    outstr = 'P<x> := PolynomialRing(Rationals());\n'
    outstr += 'g := P!' + str(F.coeffs()) + ';\n'
    outstr += 'F<w> := NumberField(g);\n'
    outstr += 'ZF := Integers(F);\n\n'
#    outstr += 'ideals_str := [' + ','.join([st for st in F_hmf["ideals"]]) + '];\n'
#    outstr += 'ideals := [ideal<ZF | {F!x : x in I}> : I in ideals_str];\n\n'

    outstr += 'NN := ideal<ZF | {' + f["level_ideal"][1:-1] + '}>;\n\n'

    outstr += 'primesArray := [\n' + ','.join([st for st in F_hmf["primes"]]).replace('],[', '],\n[') + '];\n'
    outstr += 'primes := [ideal<ZF | {F!x : x in I}> : I in primesArray];\n\n'

    if f["hecke_polynomial"] != 'x':
        outstr += 'heckePol := ' + f["hecke_polynomial"] + ';\n'
        outstr += 'K<e> := NumberField(heckePol);\n'
    else:
        outstr += 'heckePol := x;\nK := Rationals(); e := 1;\n'

    outstr += '\nheckeEigenvaluesArray := [' + ', '.join([st for st in f["hecke_eigenvalues"]]) + '];'
    outstr += '\nheckeEigenvalues := AssociativeArray();\n'
    outstr += 'for i := 1 to #heckeEigenvaluesArray do\n  heckeEigenvalues[primes[i]] := heckeEigenvaluesArray[i];\nend for;\n\n'

    outstr += 'ALEigenvalues := AssociativeArray();\n'
    for s in f["AL_eigenvalues"]:
        outstr += 'ALEigenvalues[ideal<ZF | {' + s[0][1:-1] + '}>] := ' + s[1] + ';\n'

    outstr += '\n// EXAMPLE:\n// pp := Factorization(2*ZF)[1][1];\n// heckeEigenvalues[pp];\n\n'

    outstr += '/* EXTRA CODE: recompute eigenform (warning, may take a few minutes or longer!):\n'
    outstr += 'M := HilbertCuspForms(F, NN);\n'
    outstr += 'S := NewSubspace(M);\n'
    outstr += '// SetVerbose("ModFrmHil", 1);\n'
    outstr += 'newspaces := NewformDecomposition(S);\n'
    outstr += 'newforms := [Eigenform(U) : U in newspaces];\n'
    outstr += 'ppind := 0;\n'
    outstr += 'while #newforms gt 1 do\n'
    outstr += '  pp := primes[ppind];\n'
    outstr += '  newforms := [f : f in newforms | HeckeEigenvalue(f,pp) eq heckeEigenvalues[pp]];\n'
    outstr += 'end while;\n'
    outstr += 'f := newforms[1];\n'
    outstr += '// [HeckeEigenvalue(f,pp) : pp in primes] eq heckeEigenvaluesArray;\n'
    outstr += '*/\n'

    return outstr
Esempio n. 26
0
 def author_links(self):
    """
    Basically finds all full names for all the referenced authors.
    (lookup for all full names in just *one* query, hence the or)
    """
    a_query = [{'_id': _} for _ in self.authors]
    a = []
    if len(a_query) > 0:
      users = getDBConnection().userdb.users
      a = users.find({"$or" : a_query}, fields=["full_name"])
    return a
Esempio n. 27
0
 def author_links(self):
     """
  Basically finds all full names for all the referenced authors.
  (lookup for all full names in just *one* query, hence the or)
  """
     a_query = [{'_id': _} for _ in self.authors]
     a = []
     if len(a_query) > 0:
         users = getDBConnection().userdb.users
         a = users.find({"$or": a_query}, fields=["full_name"])
     return a
Esempio n. 28
0
def render_isogeny_class(iso_class):
    info = {}
    credit = 'John Cremona'
    label = iso_class

    C = base.getDBConnection()
    data = C.ellcurves.isogeny.find_one({'label': label})
    if data is None:
        return "No such isogeny class"
    ainvs = [int(a) for a in data['ainvs_for_optimal_curve']]
    E = EllipticCurve(ainvs)
    info = {'label': label}
    info['optimal_ainvs'] = ainvs
    if 'imag' in data:
        info['imag'] = data['imag']
    if 'real' in data:
        info['real'] = data['real']
    info['rank'] = data['rank']
    info['isogeny_matrix'] = latex(matrix(eval(data['isogeny_matrix'])))
    info['modular_degree'] = data['degree']
    #info['f'] = ajax_more(E.q_eigenform, 10, 20, 50, 100, 250)
    info['f'] = web_latex(E.q_eigenform(10))
    G = E.isogeny_graph()
    n = G.num_verts()
    G.relabel(range(1, n + 1))  # proper cremona labels...
    info['graph_img'] = image_src(G.plot(edge_labels=True))
    curves = data['label_of_curves_in_the_class']
    info['curves'] = list(curves)
    info['download_qexp_url'] = url_for('download_qexp',
                                        limit=100,
                                        ainvs=','.join([str(a)
                                                        for a in ainvs]))
    info['download_all_url'] = url_for('download_all', label=str(label))
    friends = [('Elliptic Curve %s' % l, "/EllipticCurve/Q/%s" % l)
               for l in data['label_of_curves_in_the_class']]
    friends.append(('Quadratic Twist', "/quadratic_twists/%s" % (label)))
    friends.append(('Modular Form',
                    url_for("emf.render_classical_modular_form_from_label",
                            label="%s" % (label))))
    info['friends'] = friends

    t = "Elliptic Curve Isogeny Class %s" % info['label']
    bread = [('Elliptic Curves ', url_for("rational_elliptic_curves")),
             ('isogeny class %s' % info['label'], ' ')]

    return render_template("elliptic_curve/iso_class.html",
                           info=info,
                           bread=bread,
                           credit=credit,
                           title=t)
def hilbert_modular_form_search(**args):
    C = getDBConnection()
    info = to_dict(args) # what has been entered in the search boxes
    if 'natural' in info:
        return render_hmf_webpage({'label' : info['natural']})
    query = {}
    for field in ['field_label', 'weight', 'level_norm', 'dimension']:
        if info.get(field):
            if field == 'weight':
                query[field] = parse_list(info[field])
            else:
                if field == 'field_label':
                    query[field] = parse_field_string(info[field])
                else:
                    query[field] = info[field]

    if info.get('count'):        
        try:
            count = int(info['count'])
        except:
            count = 10
    else:
        info['count'] = 10
        count = 10

    info['query'] = dict(query)
#    C.hmfs.forms.ensure_index([('label',pymongo.ASCENDING)])
    res = C.hmfs.forms.find(query).sort([('label',pymongo.ASCENDING)]).limit(count)
    nres = res.count()
        
    info['forms'] = res
    if nres>0:
        info['field_pretty_name'] = field_pretty(res[0]['field_label'])
    else:
        info['field_pretty_name'] = ''
    info['number'] = nres
    if nres==1:
        info['report'] = 'unique match'
    else:
        if nres>count:
            info['report'] = 'displaying first %s of %s matches'%(count,nres)
        else:
            info['report'] = 'displaying all %s matches'%nres

#    info['learnmore'] = [('Number Field labels', url_for("render_labels_page")), ('Galois group labels',url_for("render_groups_page")), ('Discriminant ranges',url_for("render_discriminants_page"))]
    t = 'Hilbert Modular Form search results'

    bread = [('Hilbert Modular Forms', url_for("hilbert_modular_form_render_webpage")),('Search results',' ')]
    properties = []
    return render_template("hilbert_modular_form/hilbert_modular_form_search.html", info = info, title=t, properties=properties, bread=bread)
Esempio n. 30
0
def plot_ec(label):
    C = base.getDBConnection()
    data = C.ellcurves.curves.find_one({'label': label})
    if data is None:
        return "No such curve"    
    ainvs = [int(a) for a in data['ainvs']]
    E = EllipticCurve(ainvs)
    P = E.plot()
    _, filename = tempfile.mkstemp('.png')
    P.save(filename)
    data = open(filename).read()
    os.unlink(filename)
    response = make_response(data)
    response.headers['Content-type'] = 'image/png'
    return response
Esempio n. 31
0
def plot_ec(label):
    C = base.getDBConnection()
    data = C.ellcurves.curves.find_one({'label': label})
    if data is None:
        return "No such curve"
    ainvs = [int(a) for a in data['ainvs']]
    E = EllipticCurve(ainvs)
    P = E.plot()
    _, filename = tempfile.mkstemp('.png')
    P.save(filename)
    data = open(filename).read()
    os.unlink(filename)
    response = make_response(data)
    response.headers['Content-type'] = 'image/png'
    return response
Esempio n. 32
0
def updateMappingRule():
  id = request.form['id']
  print id
  rules = filter(lambda x: x.strip()!="", request.form['rule'].splitlines())
  db = getDBConnection().upload
  child_index = db.fs.files.find_one({"_id": ObjectId(id)})['metadata']['child_index']
  for child in child_index:
    url = ""
    for i in range(len(rules)/2):
      if re.search(rules[i+i], child[1]) is not None:
        url = re.sub(rules[i+i], rules[i+i+1], child[1])
        break
    db.fs.files.update({"_id": child[0]}, {"$set": {"metadata.related_to": url}})
    print child[0], child[1], url
        
  return "resp"
Esempio n. 33
0
def admin_update():

  db = getDBConnection().upload
  fs = GridFS(db)
  id = request.form['id']

  if request.form.has_key('approve'):
    db.fs.files.update({"_id" : ObjectId(id)}, {"$set": {"metadata.status" : "approved"}})
    db.fs.files.update({"metadata.parent_archive_id" : ObjectId(id)}, {"$set": {"metadata.status" : "approvedchild"}}, multi=1)
    flask.flash('Approved')
  if request.form.has_key('disapprove'):
    db.fs.files.update({"_id" : ObjectId(id)}, {"$set": {"metadata.status" : "disapproved"}})
    db.fs.files.update({"metadata.parent_archive_id" : ObjectId(id)}, {"$set": {"metadata.status" : "disapprovedchild"}}, multi=1)
    flask.flash('Disapproved')

  return flask.redirect(url_for(".admin"))
Esempio n. 34
0
def getUploadedFor(path):
    files = getDBConnection().upload.fs.files.find({
        "metadata.related_to":
        path,
        "$or": [{
            "metadata.status": "approved"
        }, {
            "metadata.status": "approvedchild"
        }]
    })
    ret = [[x['metadata']['name'],
            "/upload/view/%s" % x['_id']] for x in files]
    ret.insert(0, [
        "Upload your data here",
        url_for("upload.index") + "?related_to=" + request.path
    ])
    return ret
Esempio n. 35
0
def poly_to_field_label(pol):
    try:
        pol=PolynomialRing(QQ,'x')(str(pol))
        pol *= pol.denominator()
        R = pol.parent()
        pol = R(pari(pol).polredabs())
    except:
        return None
    coeffs = [int(c) for c in pol.coeffs()]
    d = int(pol.degree())
    query = {'degree': d, 'coefficients': coeffs}
    import base
    C = base.getDBConnection()
    one = C.numberfields.fields.find_one(query)
    if one:
        return one['label']
    return None
Esempio n. 36
0
def poly_to_field_label(pol):
    try:
        pol = PolynomialRing(QQ, 'x')(str(pol))
        pol *= pol.denominator()
        R = pol.parent()
        pol = R(pari(pol).polredabs())
    except:
        return None
    coeffs = [int(c) for c in pol.coeffs()]
    d = int(pol.degree())
    query = {'degree': d, 'coefficients': coeffs}
    import base
    C = base.getDBConnection()
    one = C.numberfields.fields.find_one(query)
    if one:
        return one['label']
    return None
Esempio n. 37
0
def zero_search(**kwargs):
    C = getDBConnection()
    if not 'zero' in kwargs:
        query = C.test.Lfunctions_test2.find().sort('first_zero')
    else:
        zero = float(kwargs['zero'])
        query = C.test.Lfunctions_test2.find({'first_zero' : {'$lt' : zero + .1, '$gt' : zero - .1 } }).sort('first_zero')
    pagination = LazyMongoDBPagination(query = query, per_page=50, page=request.args.get('page', 1), endpoint=".zero_search", endpoint_params=kwargs)
        #result_string = ""
        #printed_arrow = False
        #for x in L:
        #    if x['zero'] > zero and printed_arrow == False:
        #        result_string = result_string + "-------->"
        #        printed_arrow = True
        #    result_string = result_string + str(x['zero']) + " " + str(x['modulus']) + " " + str(x['character']) + "<br>\n"
        #return result_string
    return render_template('lf-list.html', pagination=pagination, title=title)
Esempio n. 38
0
def download_Rub_data():
    import gridfs
    label = (request.args.get('label'))
    limit = (request.args.get('limit'))
    C = base.getDBConnection()
    fs = gridfs.GridFS(C.quadratic_twists, 'isogeny')
    isogeny = C.quadratic_twists.isogeny.files
    filename = isogeny.find_one({'label': label})['filename']
    d = fs.get_last_version(filename)
    if limit is None:
        response = flask.Response(d.__iter__())
        response.headers['Content-disposition'] = 'attachment; filename=%s' % label
        response.content_length = d.length
    else:
        limit = int(limit)
        response = make_response(''.join(str(d.readline()) for i in srange(limit)))
    response.headers['Content-type'] = 'text/plain'
    return response
Esempio n. 39
0
 def inject_database(self, relevant_info, time_limit = None):
     #   relevant_methods are text strings 
     #    desired_database_fields = [Lfunction.original_mathematical_object, Lfunction.level]
     #    also zeroes, degree, conductor, type, real_coeff, rational_coeff, algebraic_coeff, critical_value, value_at_1, sign
     #    ok_methods = [Lfunction.math_id, Lfunction.level]
     #   
     # Is used to inject the data in relevant_fields
     
     logger.info("Trying to inject")
     import base
     db = base.getDBConnection().Lfunctions
     Lfunctions = db.full_collection
     update_dict = dict([(method_name,get_attr_or_method(self,method_name)) for method_name in relevant_info])
     
     logger.info("injecting " + str(update_dict))
     search_dict = {"original_mathematical_object()": get_attr_or_method(self, "original_mathematical_object()")}
     
     my_find_update(Lfunctions, search_dict, update_dict)
Esempio n. 40
0
def download_Rub_data():
    import gridfs
    label = (request.args.get('label'))
    limit = (request.args.get('limit'))
    C = base.getDBConnection()
    fs = gridfs.GridFS(C.quadratic_twists, 'isogeny')
    isogeny = C.quadratic_twists.isogeny.files
    filename = isogeny.find_one({'label': label})['filename']
    d = fs.get_last_version(filename)
    if limit is None:
        response = flask.Response(d.__iter__())
        response.headers['Content-disposition'] = 'attachment; filename=%s' % label
        response.content_length = d.length
    else:
        limit = int(limit)
        response = make_response(''.join(str(d.readline()) for i in srange(limit)))
    response.headers['Content-type'] = 'text/plain'
    return response
Esempio n. 41
0
def download_all():
    label=(request.args.get('label'))
    C = base.getDBConnection()
    data = C.ellcurves.isogeny.find_one({'label': label})
    #all data about this isogeny
    data1=[str(c)+'='+str(data[c]) for c in data]
    curves=data['label_of_curves_in_the_class']
    #titles of all entries of curves
    lab=curves[0]
    titles_curves=[str(c) for c in C.ellcurves.curves.find_one({'label': lab})]
    data1.append(titles_curves)
    for lab in curves:
        print lab
        data_curves=C.ellcurves.curves.find_one({'label': lab})
        data1.append([data_curves[t] for t in titles_curves])
    response=make_response('\n'.join(str(an) for an in  data1))
    response.headers['Content-type'] = 'text/plain'
    return response
Esempio n. 42
0
def viewAll():

    db = getDBConnection().upload
    fs = GridFS(db)

    approved = [
        fs.get(x['_id'])
        for x in db.fs.files.find({"metadata.status": "approved"})
    ]
    unmoderated = [
        fs.get(x['_id'])
        for x in db.fs.files.find({"metadata.status": "unmoderated"})
    ]

    return render_template("upload-view.html",
                           title="Uploaded data",
                           bread=get_bread(),
                           approved=approved,
                           unmoderated2=unmoderated)
Esempio n. 43
0
def render_isogeny_class(label):
    credit = ' '
    label = "%s" % label
    C = base.getDBConnection()
    info = C.quadratic_twists.isogeny.files.find_one({'label': label})
    data = C.quadratic_twists.isogeny.find_one({'label': label})
    if data is None:
        return "No such curves"
    data['download_Rub_data_100'] = url_for('download_Rub_data', label=str(label), limit=100)
    data['download_Rub_data'] = url_for('download_Rub_data', label=str(label))
    if info and 'related_to' in info:
        data['related_to'] = info['related_to']
    else:
        data['related_to'] = ''
    if data['type'] == 'r':
        type = 'real'
    else:
        type = 'imaginary'
    t = "Quadratic Twist for isogeny class %s %s" % (data['iso_class'], type)
    return render_template("quadratic_twists/iso_class.html", info=data, title=t)
Esempio n. 44
0
def render_isogeny_class(label):
    credit = ' '
    label = "%s" % label
    C = base.getDBConnection()
    info = C.quadratic_twists.isogeny.files.find_one({'label': label})
    data = C.quadratic_twists.isogeny.find_one({'label': label})
    if data is None:
        return "No such curves"
    data['download_Rub_data_100'] = url_for('download_Rub_data', label=str(label), limit=100)
    data['download_Rub_data'] = url_for('download_Rub_data', label=str(label))
    if info and 'related_to' in info:
        data['related_to'] = info['related_to']
    else:
        data['related_to'] = ''
    if data['type'] == 'r':
        type = 'real'
    else:
        type = 'imaginary'
    t = "Quadratic Twist for isogeny class %s %s" % (data['iso_class'], type)
    return render_template("quadratic_twists/iso_class.html", info=data, title=t)
Esempio n. 45
0
def download_all():
    label = (request.args.get('label'))
    C = base.getDBConnection()
    data = C.ellcurves.isogeny.find_one({'label': label})
    #all data about this isogeny
    data1 = [str(c) + '=' + str(data[c]) for c in data]
    curves = data['label_of_curves_in_the_class']
    #titles of all entries of curves
    lab = curves[0]
    titles_curves = [
        str(c) for c in C.ellcurves.curves.find_one({'label': lab})
    ]
    data1.append(titles_curves)
    for lab in curves:
        print lab
        data_curves = C.ellcurves.curves.find_one({'label': lab})
        data1.append([data_curves[t] for t in titles_curves])
    response = make_response('\n'.join(str(an) for an in data1))
    response.headers['Content-type'] = 'text/plain'
    return response
Esempio n. 46
0
def updateMappingRule():
    id = request.form['id']
    print id
    rules = filter(lambda x: x.strip() != "",
                   request.form['rule'].splitlines())
    db = getDBConnection().upload
    child_index = db.fs.files.find_one({"_id": ObjectId(id)
                                        })['metadata']['child_index']
    for child in child_index:
        url = ""
        for i in range(len(rules) / 2):
            if re.search(rules[i + i], child[1]) is not None:
                url = re.sub(rules[i + i], rules[i + i + 1], child[1])
                break
        db.fs.files.update({"_id": child[0]},
                           {"$set": {
                               "metadata.related_to": url
                           }})
        print child[0], child[1], url

    return "resp"
Esempio n. 47
0
def download_hmf_sage(**args):
    C = getDBConnection()
    data = None
    label = str(args['label'])
    f = C.hmfs.forms.find_one({'label': label})
    if f is None:
        return "No such form"

    F = WebNumberField(f['field_label'])
    F_hmf = C.hmfs.fields.find_one({'label': f['field_label']})

    outstr = 'P.<x> = PolynomialRing(QQ)\n'
    outstr += 'g = P(' + str(F.coeffs()) + ')\n'
    outstr += 'F.<w> = NumberField(g)\n'
    outstr += 'ZF = F.ring_of_integers()\n\n'

    outstr += 'NN = ZF.ideal(' + f["level_ideal"] + ')\n\n'

    outstr += 'primes_array = [\n' + ','.join(
        [st for st in F_hmf["primes"]]).replace('],[', '],\\\n[') + ']\n'
    outstr += 'primes = [ZF.ideal(I) for I in primes_array]\n\n'

    if f["hecke_polynomial"] != 'x':
        outstr += 'hecke_pol = ' + f["hecke_polynomial"] + '\n'
        outstr += 'K.<e> = NumberField(heckePol)\n'
    else:
        outstr += 'heckePol = x\nK = QQ\ne = 1\n'

    outstr += '\nhecke_eigenvalues_array = [' + ', '.join(
        [st for st in f["hecke_eigenvalues"]]) + ']'
    outstr += '\nhecke_eigenvalues = {}\n'
    outstr += 'for i in range(len(hecke_eigenvalues_array)):\n    hecke_eigenvalues[primes[i]] = hecke_eigenvalues_array[i]\n\n'

    outstr += 'AL_eigenvalues = {}\n'
    for s in f["AL_eigenvalues"]:
        outstr += 'ALEigenvalues[ZF.ideal(s[0])] = s[1]\n'

    outstr += '\n# EXAMPLE:\n# pp = ZF.ideal(2).factor()[0][0]\n# hecke_eigenvalues[pp]\n'

    return outstr
Esempio n. 48
0
def download_hmf_sage(**args):
    C = getDBConnection()
    data = None
    label = str(args['label'])
    f = C.hmfs.forms.find_one({'label': label})
    if f is None:
        return "No such form"

    F = WebNumberField(f['field_label'])
    F_hmf = C.hmfs.fields.find_one({'label': f['field_label']})

    outstr = 'P.<x> = PolynomialRing(QQ)\n'
    outstr += 'g = P(' + str(F.coeffs()) + ')\n'
    outstr += 'F.<w> = NumberField(g)\n'
    outstr += 'ZF = F.ring_of_integers()\n\n'

    outstr += 'NN = ZF.ideal(' + f["level_ideal"] + ')\n\n'

    outstr += 'primes_array = [\n' + ','.join([st for st in F_hmf["primes"]]).replace('],[',
                                                                                      '],\\\n[') + ']\n'
    outstr += 'primes = [ZF.ideal(I) for I in primes_array]\n\n'

    if f["hecke_polynomial"] != 'x':
        outstr += 'hecke_pol = ' + f["hecke_polynomial"] + '\n'
        outstr += 'K.<e> = NumberField(heckePol)\n'
    else:
        outstr += 'heckePol = x\nK = QQ\ne = 1\n'

    outstr += '\nhecke_eigenvalues_array = [' + ', '.join([st for st in f["hecke_eigenvalues"]]) + ']'
    outstr += '\nhecke_eigenvalues = {}\n'
    outstr += 'for i in range(len(hecke_eigenvalues_array)):\n    hecke_eigenvalues[primes[i]] = hecke_eigenvalues_array[i]\n\n'

    outstr += 'AL_eigenvalues = {}\n'
    for s in f["AL_eigenvalues"]:
        outstr += 'ALEigenvalues[ZF.ideal(s[0])] = s[1]\n'

    outstr += '\n# EXAMPLE:\n# pp = ZF.ideal(2).factor()[0][0]\n# hecke_eigenvalues[pp]\n'

    return outstr
Esempio n. 49
0
def query(**kwargs):
    C = getDBConnection()
    degree = request.args.get("degree", 0, type=int)
    level = request.args.get("level", 0, type=int)
    first_zero_start = request.args.get("zerolowerbound", -1.0, type=float)
    first_zero_end = request.args.get("zeroupperbound", -1.0, type=float)
    sort = request.args.get("sort", "first_zero", type=str)
    direction = request.args.get("direction", "up", type=str)

    if sort not in ['degree', 'first_zero', 'level', 'coeffs']:
        sort = "first_zero"
    if direction not in ["up", "down"]:
        direction = "up"

    if direction == "up":
        direction = pymongo.ASCENDING
    else:
        direction = pymongo.DESCENDING

    filter = {}
    if degree:
        filter['degree'] = degree
    if level:
        filter['level'] = level

    if first_zero_start != -1.0 or first_zero_end != -1.0:
        filter['first_zero'] = {}
    if first_zero_start != -1.0:
        filter['first_zero']['$gte'] = float(first_zero_start)
    if first_zero_end != -1.0:
        filter['first_zero']['$lte'] = float(first_zero_end)

    query = C.test.Lfunctions_test2.find(filter).sort(sort, direction)
    pagination = LazyMongoDBPagination(query=query,
                                       per_page=50,
                                       page=request.args.get('page', 1),
                                       endpoint=".query",
                                       endpoint_params=dict(request.args))
    return render_template('lf-list.html', pagination=pagination, title=title)
Esempio n. 50
0
def padic_data():
    info = {}
    label = request.args['label']
    p = int(request.args['p'])
    info['p'] = p
    N, iso, number = cremona_label_regex.match(label).groups()
    #print N, iso, number
    if request.args['rank'] == '0':
        info['reg'] = 1
    elif number == '1':
        C = base.getDBConnection()
        data = C.ellcurves.padic_db.find_one({'label': N + iso, 'p': p})
        info['data'] = data
        if data is None:
            info['reg'] = 'no data'
        else:
            reg = sage.all.Qp(p, data['prec'])(int(data['unit'])) * sage.all.Integer(p)**int(data['val'])
            reg = reg.add_bigoh(min(data['prec'], data['prec'] + data['val']))
            info['reg'] = web_latex(reg)
    else:
        info['reg'] = "no data"
    return render_template("elliptic_curve/elliptic_curve_padic.html", info = info)
Esempio n. 51
0
def render_isogeny_class(iso_class):
    info = {}
    credit = 'John Cremona'
    label=iso_class

    C = base.getDBConnection()
    data = C.ellcurves.isogeny.find_one({'label': label})
    if data is None:
        return "No such isogeny class"
    ainvs = [int(a) for a in data['ainvs_for_optimal_curve']]
    E = EllipticCurve(ainvs)
    info = {'label': label}
    info['optimal_ainvs'] = ainvs
    if 'imag' in data:
        info['imag']=data['imag']
    if 'real' in data:
        info['real']=data['real']
    info['rank'] = data['rank'] 
    info['isogeny_matrix']=latex(matrix(eval(data['isogeny_matrix'])))
    info['modular_degree']=data['degree']
    #info['f'] = ajax_more(E.q_eigenform, 10, 20, 50, 100, 250)
    info['f'] = web_latex(E.q_eigenform(10))
    G = E.isogeny_graph(); n = G.num_verts()
    G.relabel(range(1,n+1)) # proper cremona labels...
    info['graph_img'] = image_src(G.plot(edge_labels=True))
    curves = data['label_of_curves_in_the_class']
    info['curves'] = list(curves)
    info['download_qexp_url'] = url_for('download_qexp', limit=100, ainvs=','.join([str(a) for a in ainvs]))
    info['download_all_url'] = url_for('download_all', label=str(label))
    friends=[('Elliptic Curve %s' % l , "/EllipticCurve/Q/%s" % l) for l in data['label_of_curves_in_the_class']]
    friends.append(('Quadratic Twist', "/quadratic_twists/%s" % (label)))
    friends.append(('Modular Form', url_for("emf.render_classical_modular_form_from_label",label="%s" %(label))))
    info['friends'] = friends

    t= "Elliptic Curve Isogeny Class %s" % info['label']
    bread = [('Elliptic Curves ', url_for("rational_elliptic_curves")),('isogeny class %s' %info['label'],' ')]

    return render_template("elliptic_curve/iso_class.html", info = info,bread=bread, credit=credit,title = t)
Esempio n. 52
0
def admin():

    db = getDBConnection().upload
    fs = GridFS(db)

    unmoderated = [
        fs.get(x['_id'])
        for x in db.fs.files.find({"metadata.status": "unmoderated"})
    ]
    approved = [
        fs.get(x['_id'])
        for x in db.fs.files.find({"metadata.status": "approved"})
    ]
    disapproved = [
        fs.get(x['_id'])
        for x in db.fs.files.find({"metadata.status": "disapproved"})
    ]

    return render_template("upload-view.html",
                           title="Moderate uploaded data",
                           bread=get_bread(),
                           unmoderated=unmoderated
                           )  #, approved=approved, disapproved=disapproved)
Esempio n. 53
0
def main(argv):
    file_name = argv[0]
    database_collection = argv[1]
    assert "." in database_collection
    database_name, collection_name = database_collection.split(".")
    # If you know what you are doing, remove the line below.
    # In general you should just avoid using this with an existing collection as it might overwrite information
    assert database_name == "limbo"

    print "Importing file ", file_name, " to database ", database_name, " and collection ", collection_name
    import json
    import sys
    sys.path.append("../")
    import base
    print "getting connection"
    base._init(37010, "")
    print "I have it"

    C = base.getDBConnection()
    
    collection = C[database_name][collection_name]
    print "Got a collectiopn: ", collection
    with open(file_name, "r") as f:
        print "Loading data in memory"
        data = json.load(f)
        print "Done"
	print "There are ", len(data), " items "
        import sys
        sys.path.append("../")
        print "Uploading"
        for x in data:
            try:
                collection.save(x)
            except OverflowError:
                print x
                raise OverflowError
        print "Done"
def main(argv):
    file_name = argv[0]
    database_collection = argv[1]
    assert "." in database_collection
    database_name, collection_name = database_collection.split(".")
    # If you know what you are doing, remove the line below.
    # In general you should just avoid using this with an existing collection as it might overwrite information
    assert database_name == "limbo"

    print("Importing file ", file_name, " to database ", database_name, " and collection ", collection_name)
    import json
    import sys
    sys.path.append("../")
    import base
    print("getting connection")
    base._init(37010, "")
    print("I have it")

    C = base.getDBConnection()
    
    collection = C[database_name][collection_name]
    print("Got a collectiopn: ", collection)
    with open(file_name, "r") as f:
        print("Loading data in memory")
        data = json.load(f)
        print("Done")
        print("There are ", len(data), " items ")
        import sys
        sys.path.append("../")
        print("Uploading")
        for x in data:
            try:
                collection.save(x)
            except OverflowError:
                print(x)
                raise OverflowError
        print("Done")
Esempio n. 55
0
def padic_data():
    info = {}
    label = request.args['label']
    p = int(request.args['p'])
    info['p'] = p
    N, iso, number = cremona_label_regex.match(label).groups()
    #print N, iso, number
    if request.args['rank'] == '0':
        info['reg'] = 1
    elif number == '1':
        C = base.getDBConnection()
        data = C.ellcurves.padic_db.find_one({'label': N + iso, 'p': p})
        info['data'] = data
        if data is None:
            info['reg'] = 'no data'
        else:
            reg = sage.all.Qp(p, data['prec'])(int(
                data['unit'])) * sage.all.Integer(p)**int(data['val'])
            reg = reg.add_bigoh(min(data['prec'], data['prec'] + data['val']))
            info['reg'] = web_latex(reg)
    else:
        info['reg'] = "no data"
    return render_template("elliptic_curve/elliptic_curve_padic.html",
                           info=info)
Esempio n. 56
0
#
#
# Do not use this script -- it is out of date
#
#

import os.path
import gzip
import re
import sys
import time
import pymongo
import base

fields = base.getDBConnection().numberfields.fields
fields.ensure_index('degree')
fields.ensure_index('galois_group')
fields.ensure_index('signature')
fields.ensure_index('discriminant')
fields.ensure_index('class_number')
fields.ensure_index([('degree', pymongo.ASCENDING), ('discriminant', pymongo.DESCENDING)])
fields.ensure_index([('degree', pymongo.ASCENDING), ('discriminant', pymongo.ASCENDING)])


def coeffs(s):
    return [a for a in s[1:-1].split(',')]


def base_label(d, r1, D, ind):
    return str(d) + "." + str(r1) + "." + str(abs(D)) + "." + str(ind)
Esempio n. 57
0
def number_field_search(**args):
    info = to_dict(args)
    if 'natural' in info:
        field_id = info['natural']
        field_id = parse_field_string(info['natural'])
        return render_field_webpage({'label': field_id})
    query = {}
    for field in [
            'degree', 'signature', 'discriminant', 'class_number',
            'class_group', 'galois_group'
    ]:
        if info.get(field):
            if field in ['class_group', 'signature']:
                query[field] = parse_list(info[field])
            else:
                if field == 'galois_group':
                    query[field] = complete_group_code(info[field])
                else:
                    ran = info[field]
                    ran = ran.replace('..', '-')
                    query[field] = parse_range(ran)
    if info.get('ur_primes'):
        ur_primes = [int(a) for a in str(info['ur_primes']).split(',')]
    else:
        ur_primes = []

    if info.get('count'):
        try:
            count = int(info['count'])
        except:
            count = 10
    else:
        info['count'] = 10
        count = 10

    if info.get('start'):
        try:
            start = int(info['start'])
            if (start < 0): start += (1 - (start + 1) / count) * count
        except:
            start = 0
    else:
        start = 0

    info['query'] = dict(query)
    if 'lucky' in args:
        import base
        C = base.getDBConnection()
        one = C.numberfields.fields.find_one(query)
        if one:
            label = one['label']
            return render_field_webpage({'label': label})

    if 'discriminant' in query:
        import base
        C = base.getDBConnection()
        res = C.numberfields.fields.find(query).sort([
            ('degree', pymongo.ASCENDING), ('signature', pymongo.DESCENDING),
            ('discriminant', pymongo.ASCENDING)
        ])  # TODO: pages
        nres = res.count()
    else:
        # find matches with negative discriminant:
        neg_query = dict(query)
        neg_query['discriminant'] = {'$lt': 0}
        import base
        C = base.getDBConnection()
        res_neg = C.numberfields.fields.find(neg_query).sort([
            ('degree', pymongo.ASCENDING), ('discriminant', pymongo.DESCENDING)
        ])
        nres_neg = res_neg.count()
        # TODO: pages

        # find matches with positive discriminant:
        pos_query = dict(query)
        pos_query['discriminant'] = {'$gt': 0}
        import base
        C = base.getDBConnection()
        res_pos = C.numberfields.fields.find(pos_query).sort([
            ('degree', pymongo.ASCENDING), ('discriminant', pymongo.ASCENDING)
        ])
        nres_pos = res_pos.count()
        # TODO: pages

        res = merge_sort(iter(res_neg), iter(res_pos))
        nres = nres_pos + nres_neg

    if ur_primes:
        res = filter_ur_primes(res, ur_primes)

    if (start >= nres): start -= (1 + (start - nres) / count) * count
    if (start < 0): start = 0

    res = iter_limit(res, count, start)

    info['fields'] = res
    info['number'] = nres
    info['start'] = start
    if nres == 1:
        info['report'] = 'unique match'
    else:
        if nres > count or start != 0:
            info['report'] = 'displaying matches %s-%s of %s' % (
                start + 1, min(nres, start + count), nres)
        else:
            info['report'] = 'displaying all %s matches' % nres
    info['format_coeffs'] = format_coeffs
    info['learnmore'] = [
        ('Number Field labels', url_for("render_labels_page")),
        ('Galois group labels', url_for("render_groups_page")),
        ('Discriminant ranges', url_for("render_discriminants_page"))
    ]
    t = 'Number Field search results'
    bread = [('Number Fields', url_for("number_field_render_webpage")),
             ('Search results', ' ')]
    properties = []
    return render_template("number_field/number_field_search.html",
                           info=info,
                           title=t,
                           properties=properties,
                           bread=bread)
Esempio n. 58
0
def render_field_webpage(args):
    data = None
    if 'label' in args:
        label = str(args['label'])
        import base
        C = base.getDBConnection()
        data = C.numberfields.fields.find_one({'label': label})
    if data is None:
        return "No such field: " + label + " in the database"
    info = {}

    try:
        info['count'] = args['count']
    except KeyError:
        info['count'] = 10
    K = coeff_to_nf(data['coefficients'])
    D = data['discriminant']
    h = data['class_number']
    data['galois_group'] = str(data['galois_group'][3])
    data['class_group_invs'] = data['class_group']
    if data['class_group_invs'] == []:
        data['class_group_invs'] = 'Trivial'
    data['class_group'] = str(AbelianGroup(data['class_group']))
    sig = data['signature']
    D = ZZ(data['discriminant'])
    ram_primes = D.prime_factors()
    npr = len(ram_primes)
    ram_primes = str(ram_primes)[1:-1]
    Gorder, Gsign, Gab = GG_data(data['galois_group'])
    if Gab:
        Gab = 'abelian'
    else:
        Gab = 'non-abelian'
    unit_rank = sig[0] + sig[1] - 1
    if unit_rank == 0:
        reg = 1
    else:
        reg = K.regulator()
    UK = K.unit_group()

    info.update(data)
    info.update({
        'label':
        field_pretty(label),
        'polynomial':
        web_latex(K.defining_polynomial()),
        'ram_primes':
        ram_primes,
        'integral_basis':
        web_latex(K.integral_basis()),
        'regulator':
        web_latex(reg),
        'unit_rank':
        unit_rank,
        'root_of_unity':
        web_latex(UK.torsion_generator()),
        'fund_units':
        ',&nbsp; '.join([web_latex(u) for u in UK.fundamental_units()]),
        'Gorder':
        Gorder,
        'Gsign':
        Gsign,
        'Gab':
        Gab
    })
    info['downloads_visible'] = True
    info['downloads'] = [('worksheet', '/')]
    #    info['friends'] = [('L-function', '/')]
    info['friends'] = [('L-function', "/L/NumberField/%s" % label)]
    info['learnmore'] = [
        ('Number Field labels', url_for("render_labels_page")),
        ('Galois group labels', url_for("render_groups_page")),
        ('Discriminant ranges', url_for("render_discriminants_page"))
    ]
    bread = [('Number Fields', url_for("number_field_render_webpage")),
             ('%s' % info['label'], ' ')]
    t = "Number Field %s" % info['label']

    properties = ['<br>']
    properties.extend('<table>')
    properties.extend(
        '<tr><td align=left><b>Degree:</b><td align=left> %s</td>' %
        data['degree'])
    properties.extend(
        '<tr><td align=left><b>Signature:</b><td align=left>%s</td>' %
        data['signature'])
    properties.extend(
        '<tr><td align=left><b>Discriminant:</b><td align=left>%s</td>' %
        data['discriminant'])
    if npr == 1:
        properties.extend(
            '<tr><td align=left><b>Ramified prime:</b><td align=left>%s</td>' %
            ram_primes)
    else:
        if npr == 0:
            properties.extend(
                '<tr><td align=left><b>Ramified primes:</b><td align=left>%s</td>'
                % "None")
        else:
            properties.extend(
                '<tr><td align=left><b>Ramified primes:</b><td align=left>%s</td>'
                % ram_primes)
    properties.extend(
        '<tr><td align=left><b>Class number:</b><td align=left>%s</td>' %
        data['class_number'])
    properties.extend(
        '<tr><td align=left><b>Class group:</b><td align=left>%s</td>' %
        data['class_group_invs'])
    properties.extend(
        '<tr><td align=left><b>Galois group:</b><td align=left>%s</td>' %
        data['galois_group'])
    properties.extend('</table>')
    del info['_id']
    return render_template("number_field/number_field.html",
                           properties=properties,
                           credit=NF_credit,
                           title=t,
                           bread=bread,
                           friends=info.pop('friends'),
                           info=info)