Esempio n. 1
0
 def __init__(self, group=0):
     self._group = group
     self._table = dict()
     db = connect_db()
     dims = db['dimensions']
     emf_logger.debug('dims table ={0}'.format(dims))
     emf_logger.debug('group={0}'.format(group))
     try: #this checks if there is any information about the group in question, sets rec to {'group': group} when it finds it
         if group == 0:
             rec = dims.find_one({'group': 'gamma0'})
             self.dimension = self.dimension_gamma0
             emf_logger.debug('rec={0}'.format(rec['_id']))
         elif group == 1:
             rec = dims.find_one({'group': 'gamma1'})
             self.dimension = self.dimension_gamma1
     except: #if rec hasn't been set, then it didn't find the group
         rec = None
         emf_logger.critical('Critical error: No dimension information for group={0}'.format(group))
     if rec!=None:
         self._table = loads(rec['data'])
     if rec != None:
         self._table = loads(rec['data']) #loads the data for the group in _table
     else:
         self._table = None
     if self._table != None:
         emf_logger.debug('Have information for levels {0}'.format(self._table.keys()))
Esempio n. 2
0
 def __init__(self, group=0):
     self._group = group
     self._table = dict()
     db = connect_db()
     dims = db['dimensions']
     emf_logger.debug('dims table ={0}'.format(dims))
     emf_logger.debug('group={0}'.format(group))
     try:  #this checks if there is any information about the group in question, sets rec to {'group': group} when it finds it
         if group == 0:
             rec = dims.find_one({'group': 'gamma0'})
             self.dimension = self.dimension_gamma0
             emf_logger.debug('rec={0}'.format(rec['_id']))
         elif group == 1:
             rec = dims.find_one({'group': 'gamma1'})
             self.dimension = self.dimension_gamma1
     except:  #if rec hasn't been set, then it didn't find the group
         rec = None
         emf_logger.critical(
             'Critical error: No dimension information for group={0}'.
             format(group))
     if rec != None:
         self._table = loads(rec['data'])
     if rec != None:
         self._table = loads(
             rec['data'])  #loads the data for the group in _table
     else:
         self._table = None
     if self._table != None:
         emf_logger.debug('Have information for levels {0}'.format(
             self._table.keys()))
Esempio n. 3
0
def get_downloads(level=None, weight=None, character=None, label=None, **kwds):
    keys = [
        'download', 'download_file', 'tempfile', 'format', 'number', 'bitprec'
    ]
    info = get_args(request, level, weight, character, label, keys=keys)
    # info = to_dict(request.form)
    # info['level']=level; info['weight']=weight; info['character']=character; info['label']=label
    if 'download' not in info:
        emf_logger.critical(
            "Download called without specifying what to download!")
        return ""
    emf_logger.debug("in get_downloads: info={0}".format(info))
    if info['download'] == 'file':
        # there are only a certain number of fixed files that we want people to download
        filename = info['download_file']
        if filename == "web_modforms.py":
            dirname = emf.app.root_static_folder
            try:
                emf_logger.debug("Dirname:{0}, Filename:{1}".format(
                    dirname, filename))
                return send_from_directory(dirname,
                                           filename,
                                           as_attachment=True,
                                           attachment_filename=filename)
            except IOError:
                info['error'] = "Could not find  file! "
    if info['download'] == 'coefficients':
        info['tempfile'] = "/tmp/tmp_web_mod_form.txt"
        return get_coefficients(info)
    if info['download'] == 'object':
        return download_web_modform(info)

        info['error'] = "Could not find  file! "
Esempio n. 4
0
    def __init__(self, modulus=1, number=1, update_from_db=True, compute=False):
        r"""
        Init self.

        """
        emf_logger.critical("In WebChar {0}".format((modulus, number, update_from_db, compute)))
        if not gcd(number, modulus) == 1:
            raise ValueError, "Character number {0} of modulus {1} does not exist!".format(number, modulus)
        if number > modulus:
            number = number % modulus
        self._properties = WebProperties(
            WebInt("conductor"),
            WebInt("modulus", value=modulus),
            WebInt("number", value=number),
            WebInt("modulus_euler_phi"),
            WebInt("order"),
            WebStr("latex_name"),
            WebStr("label", value="{0}.{1}".format(modulus, number)),
            WebNoStoreObject("sage_character", type(trivial_character(1))),
            WebDict("_values_algebraic"),
            WebDict("_values_float"),
            WebDict("_embeddings"),
            WebFloat("version", value=float(emf_version)),
        )
        emf_logger.debug("Set properties in WebChar!")
        super(WebChar, self).__init__(update_from_db=update_from_db)
        if self._has_updated_from_db is False:
            self.init_dynamic_properties()  # this was not done if we exited early
            compute = True
        if compute:
            self.compute(save=True)

        # emf_logger.debug('In WebChar, self.__dict__ = {0}'.format(self.__dict__))
        emf_logger.debug("In WebChar, self.number = {0}".format(self.number))
Esempio n. 5
0
 def save_to_db(self, update = True):
     r"""
      Saves ```self``` to the database, i.e.
      save the meta record and the file in the gridfs file system.
     """
     import pymongo
     from pymongo.errors import OperationFailure
     fs = self._files
     try: 
         self.authorize()
     except OperationFailure:
         emf_logger.critical("Authentication failed. You are not authorized to save data to the database!")
         return False
     file_key = self.file_key_dict()
     coll = self._file_collection
     if fs.exists(file_key):
         emf_logger.debug("File exists with key={0}".format(file_key))
         if not update:
             return True
         else:
             fid = coll.find_one(file_key, projection=['_id'])['_id']
             fs.delete(fid)
             emf_logger.debug("Deleted file with fid={0}".format(fid))
     # insert
     s = dumps(self.fs_dict())
     if not self._use_separate_db:
         file_key.update(self.db_dict())
     try:
         t = fs.put(s, **file_key)
         emf_logger.debug("Inserted file t={0}, filekey={1}".format(t,file_key))
     except Exception, e:
         emf_logger.debug("Could not insert file s={0}, filekey={1}".format(s,file_key))     
         emf_logger.warn("Error inserting record: {0}".format(e))
Esempio n. 6
0
 def __init__(self, group=0):
     self._group = group
     self._table = dict()
     db = connect_db()
     dims = db['dimensions']
     emf_logger.debug('dims table ={0}'.format(dims))
     emf_logger.debug('group={0}'.format(group))
     try:
         if group == 0:
             rec = dims.find_one({'group': 'gamma0'})
             self.dimension = self.dimension_gamma0
             emf_logger.debug('rec={0}'.format(rec['_id']))
         elif group == 1:
             rec = dims.find_one({'group': 'gamma1'})
             self.dimension = self.dimension_gamma1
     except:
         rec = None
         emf_logger.critical(
             'Critical error: No dimension information for group={0}'.
             format(group))
     if rec <> None:
         self._table = loads(rec['data'])
     else:
         self._table = None
     if self._table <> None:
         emf_logger.debug('Have information for levels {0}'.format(
             self._table.keys()))
Esempio n. 7
0
def get_downloads(level=None, weight=None, character=None, label=None, **kwds):
    keys = ['download', 'download_file', 'tempfile', 'format', 'number','bitprec']
    info = get_args(request, level, weight, character, label, keys=keys)
    # info = to_dict(request.form)
    # info['level']=level; info['weight']=weight; info['character']=character; info['label']=label
    if 'download' not in info:
        emf_logger.critical("Download called without specifying what to download!")
        return ""
    emf_logger.debug("in get_downloads: info={0}".format(info))
    if info['download'] == 'file':
        # there are only a certain number of fixed files that we want people to download
        filename = info['download_file']
        if filename == "web_modforms.py":
            dirname = emf.app.root_static_folder
            try:
                emf_logger.debug("Dirname:{0}, Filename:{1}".format(dirname, filename))
                return send_from_directory(dirname, filename, as_attachment=True, attachment_filename=filename)
            except IOError:
                info['error'] = "Could not find  file! "
    if info['download'] == 'coefficients':
        info['tempfile'] = "/tmp/tmp_web_mod_form.txt"
        return get_coefficients(info)
    if info['download'] == 'object':
        return download_web_modform(info)

        info['error'] = "Could not find  file! "
Esempio n. 8
0
def connect_to_modularforms_db(collection="", create=True):
    r"""
    Return a handle to a modular forms database or a specific collection.

    """
    db_name = "modularforms2"
    try:
        C = lmfdb.base.getDBConnection()
    except Exception as e:
        emf_logger.critical("Could not connect to Database! db={0}. Error: {1}".format(db_name, e.message))

    try:
        if collection != "":
            return C[db_name][collection]
        else:
            return C[db_name]
    except Exception as e:
        if collection != "":
            error_st = (
                "Either Database %s does not exist or Collection %s is not in database %s at connection %s. Error: %s"
                % (db_name, collection, db_name, C, e)
            )
        else:
            error_st = "Database %s does not exist at connection %s. Error: %s" % (db_name, C, e)
            raise ValueError, error_st
Esempio n. 9
0
def WebNewForm_cached(level,weight,character,label,parent=None, **kwds):
    if use_cache: 
        M = WebModFormSpace_cached(level, weight, character)
        return M.hecke_orbits[label]
    else:
        F = WebNewForm(level,weight,character,label,**kwds)
        emf_logger.critical("Computed F not using cache!")
    return F
Esempio n. 10
0
def WebNewForm_cached(level, weight, character, label, parent=None, **kwds):
    if use_cache:
        M = WebModFormSpace_cached(level, weight, character)
        return M.hecke_orbits[label]
    else:
        F = WebNewForm(level, weight, character, label, **kwds)
        emf_logger.critical("Computed F not using cache!")
    return F
Esempio n. 11
0
 def first_nonvanishing_coefficient_trace(self):
     if self._nv_coeff_trace is not None:
         return self._nv_coeff_trace
     try:
         a = self.first_nonvanishing_coefficient()
         self._nv_coeff_trace = a.trace()
         return self._nv_coeff_trace
     except AttributeError as e:
         emf_logger.critical(e)
Esempio n. 12
0
 def first_nonvanishing_coefficient_norm(self):
     if self._nv_coeff_norm is not None:
         return self._nv_coeff_norm
     try:
         a = self.first_nonvanishing_coefficient()
         self._nv_coeff_norm = a.norm()
         return self._nv_coeff_norm
     except AttributeError as e:
         emf_logger.critical(e)
Esempio n. 13
0
 def first_nonvanishing_coefficient_norm(self):
     if self._nv_coeff_norm is not None:
         return self._nv_coeff_norm
     try:
         a = self.first_nonvanishing_coefficient()
         self._nv_coeff_norm = a.norm()
         return self._nv_coeff_norm
     except AttributeError as e:
         emf_logger.critical(e)
Esempio n. 14
0
 def first_nonvanishing_coefficient_trace(self):
     if self._nv_coeff_trace is not None:
         return self._nv_coeff_trace
     try:
         a = self.first_nonvanishing_coefficient()
         self._nv_coeff_trace = a.trace()
         return self._nv_coeff_trace
     except AttributeError as e:
         emf_logger.critical(e)
Esempio n. 15
0
 def extend_from_db(self):
     setattr(self._value, "lmfdb_label", self._db_value)
     if not self._db_value is None and self._db_value != '':
         try:
             url =  url_for("number_fields.by_label", label=self._db_value)
         except RuntimeError:
             emf_logger.critical("could not set url for the label")
             url = ''
         setattr(self._value, "lmfdb_url",url)
         setattr(self._value, "lmfdb_pretty", field_pretty(self._db_value))
     else:
         setattr(self._value, "lmfdb_pretty", web_latex_split_on_pm(self._value.absolute_polynomial()))
Esempio n. 16
0
 def extend_from_db(self):
     setattr(self._value, "lmfdb_label", self._db_value)
     if not self._db_value is None and self._db_value != '':
         try:
             url = url_for("number_fields.by_label", label=self._db_value)
         except RuntimeError:
             emf_logger.critical("could not set url for the label")
             url = ''
         setattr(self._value, "lmfdb_url", url)
         setattr(self._value, "lmfdb_pretty", field_pretty(self._db_value))
     else:
         setattr(self._value, "lmfdb_pretty",
                 web_latex_split_on_pm(self._value.absolute_polynomial()))
Esempio n. 17
0
    def authorize(self):
        r"""
        Need to be authorized to insert data
        """
        from lmfdb.base import getDBConnection
        from os.path import dirname, join

        pw_filename = join(dirname(dirname(__file__)), "password")
        user = "******"
        password = open(pw_filename, "r").readlines()[0].strip()
        C = getDBConnection()
        C["modularforms2"].authenticate(user, password)
        emf_logger.critical("Authenticated with user:{0} and pwd:{1}".format(user, password))
Esempio n. 18
0
def WebChar_cached(modulus, number, **kwds):
    if use_cache:
        label = "{0}.{1}".format(modulus, number)
        X = cache.get(label)
        emf_logger.critical("Looking for cached  char:{0}".format(label))
        if X is None:
            emf_logger.debug("X was not in cache!")
            X = WebChar(modulus, number, **kwds)
            cache.set(label, X, timeout=5 * 60)
        else:
            emf_logger.critical("X was in cache!")
    else:
        X = WebChar(modulus, number, **kwds)
    return X
Esempio n. 19
0
def WebModFormSpace_cached(level, weight, character, **kwds):
    if use_cache:
        label = space_label(level, weight, character, make_cache_label=True)
        M = cache.get(label)
        emf_logger.critical("Looking for cached space:{0}".format(label))
        if M is None:
            emf_logger.debug("M was not in cache!")
            M = WebModFormSpace(level, weight, character, **kwds)
            cache.set(label, M, timeout=5 * 60)
        else:
            emf_logger.critical("M was in cache!")
    else:
        M = WebModFormSpace(level, weight, character, **kwds)
    return M
Esempio n. 20
0
 def __init__(self, name, level, weight, character, parent=None, **kwds):
     emf_logger.debug(
         "Get Hecke orbits! {0},{1},{2},{3},{4},kwds={5}".format(
             name, level, weight, character, type(parent), kwds))
     self.level = level
     self.weight = weight
     self.character = character
     self.parent = parent
     super(WebHeckeOrbits, self).__init__(name,
                                          None,
                                          save_to_db=True,
                                          save_to_fs=False,
                                          **kwds)
     emf_logger.critical("Initiated Hecke orbits!")
Esempio n. 21
0
def WebChar_cached(modulus, number, **kwds):
    if use_cache:
        label = "{0}.{1}".format(modulus, number)
        X = cache.get(label)
        emf_logger.critical("Looking for cached  char:{0}".format(label))
        if X is None:
            emf_logger.debug("X was not in cache!")
            X = WebChar(modulus, number, **kwds)
            cache.set(label, X, timeout=5 * 60)
        else:
            emf_logger.critical("X was in cache!")
    else:
        X = WebChar(modulus, number, **kwds)
    return X
Esempio n. 22
0
def get_files_from_gridfs(collection='',create=True):
    r"""
    Return a handle to a modular forms database or a specific collection.
    """
    C = connect_to_modularforms_db()
    if 'files' not in collection:
        collection_name = collection + '.files'
    else:
        collection_name = collection.split('.')[0]

    try:
        return gridfs.GridFS(C,collection)
    except Exception as e:
        error_st = "Collection {0} is not in database {1} at connection {2}.  Error: {3}".format(collection,db_name,C,e)
        emf_logger.critical(error_st)
        raise ValueError,error_st 
def render_web_modform_space(level=None, weight=None, character=None, label=None, **kwds):
    r"""
    Render the webpage for a elliptic modular forms space.
    """
    emf_logger.debug("In render_elliptic_modular_form_space kwds: {0}".format(kwds))
    emf_logger.debug(
        "Input: level={0},weight={1},character={2},label={3}".format(level, weight, character, label))
    info = to_dict(kwds)
    info['level'] = level
    info['weight'] = weight
    info['character'] = character
    try:
        info = set_info_for_modular_form_space(**info)
    except RuntimeError as e:
        errst = "The space {0}.{1}.{2} is not in the database!".format(level,weight,character)
        flash(errst,'error')
        info = {'error': ''}
    emf_logger.debug("keys={0}".format(info.keys()))
    if info.has_key('error'):
        emf_logger.critical("error={0}".format(info['error']))
    if 'download' in kwds and 'error' not in kwds:
        return send_file(info['tempfile'], as_attachment=True, attachment_filename=info['filename'])
    if 'dimension_newspace' in kwds and kwds['dimension_newspace'] == 1:
        # if there is only one orbit we list it
        emf_logger.debug("Dimension of newforms is one!")
        info['label'] = 'a'
        return redirect(url_for('emf.render_elliptic_modular_forms', **info))
    if character>1:
        info['title'] = "Newforms of weight %s for \(\Gamma_{0}(%s)\) with character \(\chi_{%s}(%s, \cdot)\)" % (weight, level, level, character)
    else:
        info['title'] = "Newforms of weight %s for \(\Gamma_{0}(%s)\)" % (weight, level)
    bread = [(EMF_TOP, url_for('emf.render_elliptic_modular_forms'))]
    bread.append(("Level %s" % level, url_for('emf.render_elliptic_modular_forms', level=level)))
    bread.append(
        ("Weight %s" % weight, url_for('emf.render_elliptic_modular_forms', level=level, weight=weight)))
    bread.append(
        ("Character \(\chi_{%s}(%s, \cdot)\)" % (level, character), url_for('emf.render_elliptic_modular_forms', level=level, weight=weight, character=character)))
    # emf_logger.debug("friends={0}".format(friends))
    info['bread'] = bread
    info['learnmore'] = [('History of Modular forms', url_for('holomorphic_mf_history'))]
    emf_logger.debug("info={0}".format(info))
    if info.has_key('space'):
        emf_logger.debug("space={0}".format(info['space']))        
        emf_logger.debug("dimension={0}".format(info['space'].dimension))
    if info.has_key('error'):
        emf_logger.debug("error={0}".format(info['error']))
    return render_template("emf_web_modform_space.html", **info)
Esempio n. 24
0
def render_web_modform_space(level=None, weight=None, character=None, label=None, **kwds):
    r"""
    Render the webpage for a elliptic modular forms space.
    """
    emf_logger.debug("In render_elliptic_modular_form_space kwds: {0}".format(kwds))
    emf_logger.debug(
        "Input: level={0},weight={1},character={2},label={3}".format(level, weight, character, label))
    info = to_dict(kwds)
    info['level'] = level
    info['weight'] = weight
    info['character'] = character
    try:
        info = set_info_for_modular_form_space(**info)
    except RuntimeError:
        errst = "The space {0}.{1}.{2} is not in the database!".format(level,weight,character)
        flash(errst,'error')
        info = {'error': ''}
    emf_logger.debug("keys={0}".format(info.keys()))
    if info.has_key('error'):
        emf_logger.critical("error={0}".format(info['error']))
    if 'download' in kwds and 'error' not in kwds:
        return send_file(info['tempfile'], as_attachment=True, attachment_filename=info['filename'], add_etags=False)
    if 'dimension_newspace' in kwds and kwds['dimension_newspace'] == 1:
        # if there is only one orbit we list it
        emf_logger.debug("Dimension of newforms is one!")
        info['label'] = 'a'
        return redirect(url_for('emf.render_elliptic_modular_forms', **info))
    if character>1:
        info['title'] = "Newforms of weight %s for \(\Gamma_{0}(%s)\) with character \(\chi_{%s}(%s, \cdot)\)" % (weight, level, level, character)
    else:
        info['title'] = "Newforms of weight %s for \(\Gamma_{0}(%s)\)" % (weight, level)
    bread = [(MF_TOP, url_for('mf.modular_form_main_page')), (EMF_TOP, url_for('emf.render_elliptic_modular_forms'))]
    bread.append(("Level %s" % level, url_for('emf.render_elliptic_modular_forms', level=level)))
    bread.append(
        ("Weight %s" % weight, url_for('emf.render_elliptic_modular_forms', level=level, weight=weight)))
    bread.append(
        ("Character \(\chi_{%s}(%s, \cdot)\)" % (level, character), url_for('emf.render_elliptic_modular_forms', level=level, weight=weight, character=character)))
    # emf_logger.debug("friends={0}".format(friends))
    info['bread'] = bread
    info['learnmore'] = [('History of modular forms', url_for('.holomorphic_mf_history'))]
    emf_logger.debug("info={0}".format(info))
    if info.has_key('space'):
        emf_logger.debug("space={0}".format(info['space']))        
        emf_logger.debug("dimension={0}".format(info['space'].dimension))
    if info.has_key('error'):
        emf_logger.debug("error={0}".format(info['error']))
    return render_template("emf_web_modform_space.html", **info)
Esempio n. 25
0
 def find(cls, query={}, projection=None, sort=[]):
     r'''
       Search the database using ```query``` and return
       an iterator over the set of matching objects of this WebObject
     '''
     coll = cls.connect_to_db(cls._collection_name)
     for s in coll.find(query, sort=sort, projection=projection):
         s.pop('_id')
         try:
             k = {key: s[key] for key in cls._key}
             o = cls(update_from_db=False, **k)
             o.update_db_properties_from_dict(s)
             yield o
         except KeyError as e:
             emf_logger.critical(
                 "Malformed data in the database {}, {}".format(e, s))
             continue
Esempio n. 26
0
def get_files_from_gridfs(collection="", create=True):
    r"""
    Return a handle to a modular forms database or a specific collection.
    """
    C = connect_to_modularforms_db()

    # FIXME collection_name is set but never used
    # if 'files' not in collection:
    #    collection_name = collection + '.files'
    # else:
    #    collection_name = collection.split('.')[0]

    try:
        return gridfs.GridFS(C, collection)
    except Exception as e:
        error_st = "Collection {0} is not in database {1}.  Error: {2}".format(collection, C, e)
        emf_logger.critical(error_st)
        raise ValueError, error_st
Esempio n. 27
0
 def save_to_db(self, update=True):
     r"""
      Saves ```self``` to the database, i.e.
      save the meta record and the file in the gridfs file system.
     """
     import pymongo
     from pymongo.errors import OperationFailure
     fs = self._files
     try:
         self.authorize()
     except OperationFailure:
         emf_logger.critical(
             "Authentication failed. You are not authorized to save data to the database!"
         )
         return False
     if self._use_gridfs:
         file_key = self.file_key_dict()
         coll = self._file_collection
         if fs.exists(file_key):
             emf_logger.debug("File exists with key={0}".format(file_key))
             if not update:
                 return True
             else:
                 fid = coll.find_one(file_key, projection=['_id'])['_id']
                 fs.delete(fid)
                 emf_logger.debug("Deleted file with fid={0}".format(fid))
         # insert
         s = dumps(self.fs_dict())
         if not self._use_separate_db:
             file_key.update(self.db_dict())
         try:
             t = fs.put(s, **file_key)
             emf_logger.debug("Inserted file with filekey={1}".format(
                 t, file_key))
         except Exception, e:
             emf_logger.debug(
                 "Could not insert file with filekey={1}".format(
                     s, file_key))
             emf_logger.warn("Error inserting record: {0}".format(e))
         #fid = coll.find_one(key)['_id']
         # insert extended record
         if not self._use_separate_db:
             self.logout()
             return True
Esempio n. 28
0
 def find(cls, query={}, projection = None, sort=[], gridfs_only=False):
     r'''
       Search the database using ```query``` and return
       an iterator over the set of matching objects of this WebObject
     '''
     if gridfs_only: # stupid hack, should be a property of the class or standard that way
         coll = cls.connect_to_db(cls._collection_name).files
     else:
         coll = cls.connect_to_db(cls._collection_name)
     for s in coll.find(query, sort=sort, projection=projection):
         s.pop('_id')
         try:
             k = {key:s[key] for key in cls._key}
             o = cls(update_from_db=False, init_dynamic_properties=False, **k)
             o.update_db_properties_from_dict(s)
             yield o
         except KeyError as e:
             emf_logger.critical("Malformed data in the database {}, {}".format(e,s))
             continue
Esempio n. 29
0
 def find(cls, query={}, projection = None, sort=[], gridfs_only=False):
     r'''
       Search the database using ```query``` and return
       an iterator over the set of matching objects of this WebObject
     '''
     if gridfs_only: # stupid hack, should be a property of the class or standard that way
         coll = cls.connect_to_db(cls._collection_name).files
     else:
         coll = cls.connect_to_db(cls._collection_name)
     for s in coll.find(query, sort=sort, projection=projection):
         s.pop('_id')
         try:
             k = {key:s[key] for key in cls._key}
             o = cls(update_from_db=False, init_dynamic_properties=False, **k)
             o.update_db_properties_from_dict(s)
             yield o
         except KeyError as e:
             emf_logger.critical("Malformed data in the database {}, {}".format(e,s))
             continue
Esempio n. 30
0
 def extend_from_db(self):
     setattr(self._value, "lmfdb_label", self._db_value)
     if not self._db_value is None and self._db_value != '':
         label = self._db_value
         setattr(self._value, "lmfdb_pretty", field_pretty(label))
     else:
         if self._value.absolute_degree() == 1:
             label = '1.1.1.1'
             setattr(self._value, "lmfdb_pretty", field_pretty(label))
             setattr(self._value, "lmfdb_label", label)
         else:
             emf_logger.critical("could not set lmfdb_pretty for the label")
             label = ''
     if label != '':
         try:
             url = url_for("number_fields.by_label", label=label)
             setattr(self._value, "lmfdb_url", url)
         except RuntimeError:
             emf_logger.critical("could not set url for the label")
Esempio n. 31
0
 def extend_from_db(self):
     setattr(self._value, "lmfdb_label", self._db_value)
     if not self._db_value is None and self._db_value != '':
         label = self._db_value
         setattr(self._value, "lmfdb_pretty", field_pretty(label))
     else:
         if self._value == QQ:
             label = '1.1.1.1'
             setattr(self._value, "lmfdb_pretty", field_pretty(label))
             setattr(self._value, "lmfdb_label", label)
         else:
             emf_logger.critical("could not set lmfdb_pretty for the label")
             label = ''
     if label != '':
         try:
             url =  url_for("number_fields.by_label", label=label)
             setattr(self._value, "lmfdb_url", url)
         except RuntimeError:
             emf_logger.critical("could not set url for the label")
Esempio n. 32
0
    def from_db(self, l):
        emf_logger.critical("Get Hecke orbits for labels : {0}!".format(l))
        from lmfdb.modular_forms.elliptic_modular_forms.backend.web_newforms import WebNewForm_cached, WebNewForm
        res = {}
        for lbl in l:
            F = WebNewForm(self.level,
                           self.weight,
                           self.character,
                           lbl,
                           parent=self.parent)
            #F = WebNewForm_cached(self.level, self.weight, self.character, lbl, parent=self.parent)
            emf_logger.debug("Got F for label {0} : {1}".format(lbl, F))
            res[lbl] = F


#            return {lbl : WebNewForm_cached(self.level, self.weight, self.character, lbl, parent=self.parent)
#                for lbl in l}
        emf_logger.critical("Got Hecke orbits!")

        return res
Esempio n. 33
0
    def __init__(self, group=0):
        self._group = group
        self._table = dict()
        db = connect_db()
        dims = db['dimensions']
        emf_logger.debug('group={0}'.format(group))
        try:
            if group == 0:
                rec = dims.find_one({'group': 'gamma0'})
                self.dimension = self.dimension_gamma0
#                emf_logger.debug('rec={0}'.format(rec))
            elif group == 1:
                rec = dims.find_one({'group': 'gamma1'})
                self.dimension = self.dimension_gamma1
        except:
            emf_logger.critical('Critical error: No dimension information for group={0}'.format(group))
        if rec:
            self._table = loads(rec['data'])
        else:
            self._table = None
Esempio n. 34
0
    def __init__(self, group=0):
        self._group = group
        self._table = dict()
        db = connect_db()
        dims = db['dimensions']
        emf_logger.debug('group={0}'.format(group))
        try:
            if group == 0:
                rec = dims.find_one({'group': 'gamma0'})
                self.dimension = self.dimension_gamma0
#                emf_logger.debug('rec={0}'.format(rec))
            elif group == 1:
                rec = dims.find_one({'group': 'gamma1'})
                self.dimension = self.dimension_gamma1
        except:
            emf_logger.critical('Critical error: No dimension information for group={0}'.format(group))
        if rec:
            self._table = loads(rec['data'])
        else:
            self._table = None
Esempio n. 35
0
def connect_to_modularforms_db(collection='',create=True):
    r"""
    Return a handle to a modular forms database or a specific collection.

    """
    db_name = 'modularforms2'
    try:
        C = lmfdb.base.getDBConnection()
    except Exception as e:
        emf_logger.critical("Could not connect to Database! db={0}. Error: {1}".format(db_name,e.message))
    
    try:
        if collection != '':
            return C[db_name][collection]
        else:
            return C[db_name]
    except Exception as e:
        if collection != '':
            error_st = "Either Database %s does not exist or Collection %s is not in database %s at connection %s. Error: %s" % (db_name, collection, db_name, C,e);
        else:
            error_st = "Database %s does not exist at connection %s. Error: %s" % (db_name, C,e);
            raise ValueError,error_st
Esempio n. 36
0
 def __init__(self, group=0):
     self._group = group
     self._table = dict()
     db = connect_db()
     dims = db["dimensions"]
     emf_logger.debug("dims table ={0}".format(dims))
     emf_logger.debug("group={0}".format(group))
     try:
         if group == 0:
             rec = dims.find_one({"group": "gamma0"})
             self.dimension = self.dimension_gamma0
             emf_logger.debug("rec={0}".format(rec["_id"]))
         elif group == 1:
             rec = dims.find_one({"group": "gamma1"})
             self.dimension = self.dimension_gamma1
     except:
         rec = None
         emf_logger.critical("Critical error: No dimension information for group={0}".format(group))
     if rec <> None:
         self._table = loads(rec["data"])
     else:
         self._table = None
     emf_logger.debug("Have information for levels {0}".format(self._table.keys()))
Esempio n. 37
0
def render_fd_plot(level, info, **kwds):
    group = None
    grouptype = None
    if ('group' in info):
        group = info['group']
        # we only allow standard groups
    if 'grouptype' in info:
        grouptype = int(info['grouptype'])
        if info['grouptype'] == 0:
            group = 'Gamma0'
        elif info['grouptype'] == 1:
            group = 'Gamma1'
    if (group not in ['Gamma0', 'Gamma', 'Gamma1']):
        group = 'Gamma0'
        grouptype = int(0)
    else:
        if grouptype is None:
            if group == 'Gamma':
                grouptype = int(-1)
            elif group == 'Gamma0':
                grouptype = int(0)
            else:
                grouptype = int(1)
    db_name = 'SL2Zsubgroups'
    collection = 'groups'
    C = lmfdb.base.getDBConnection()
    emf_logger.debug("C={0}, level={1}, grouptype={2}".format(
        C, level, grouptype))
    if not C:
        emf_logger.critical("Could not connect to Database! C={0}".format(C))
    if not db_name in C.database_names():
        emf_logger.critical(
            "Incorrect database name {0}. \n Available databases are:{1}".
            format(db_name, C.database_names()))
    if not collection in C[db_name].collection_names():
        emf_logger.critical(
            "Incorrect collection {0} in database {1}. \n Available collections are:{2}"
            .format(collection, db_name, C[db_name].collection_names()))

    find = C[db_name][collection].find_one({
        'level': int(level),
        'type': int(grouptype)
    })
    if find:
        if find.get('domain'):
            # domain=loads(str(find['domain']))
            domain = find['domain']
        emf_logger.debug('Found fundamental domain in database')
    else:
        emf_logger.debug(
            'Drawing fundamental domain for group {0}({1})'.format(
                group, level))
        domain = draw_fundamental_domain(level, group, **kwds)
        # G=Gamma0(level)
        # C[db_name][collection].insert({'level':int(level), 'type':type, 'index':int(G.index), 'G':bson.binary.Binary(dumps(G)), 'domain': bson.binary.Binary(dumps(domain))})
        # emf_logger.debug('Inserting group and fundamental domain in database')
    return domain
Esempio n. 38
0
 def __init__(self, group=0):
     self._group = group
     self._table = dict()
     db = connect_db()
     dims = db['dimensions']
     emf_logger.debug('dims table ={0}'.format(dims))
     emf_logger.debug('group={0}'.format(group))
     try:
         if group == 0:
             rec = dims.find_one({'group': 'gamma0'})
             self.dimension = self.dimension_gamma0
             emf_logger.debug('rec={0}'.format(rec['_id']))
         elif group == 1:
             rec = dims.find_one({'group': 'gamma1'})
             self.dimension = self.dimension_gamma1
     except:
         rec = None
         emf_logger.critical('Critical error: No dimension information for group={0}'.format(group))
     if rec<>None:
         self._table = loads(rec['data'])
     else:
         self._table = None
     if self._table <> None:
         emf_logger.debug('Have information for levels {0}'.format(self._table.keys()))
Esempio n. 39
0
    def __init__(self,
                 modulus=1,
                 number=1,
                 update_from_db=True,
                 compute=False):
        r"""
        Init self.

        """
        emf_logger.critical("In WebChar {0}".format(
            (modulus, number, update_from_db, compute)))
        if not gcd(number, modulus) == 1:
            raise ValueError, "Character number {0} of modulus {1} does not exist!".format(
                number, modulus)
        if number > modulus:
            number = number % modulus
        self._properties = WebProperties(
            WebInt('conductor'), WebInt('modulus', value=modulus),
            WebInt('number', value=number), WebInt('modulus_euler_phi'),
            WebInt('order'), WebStr('latex_name'),
            WebStr('label', value="{0}.{1}".format(modulus, number)),
            WebNoStoreObject('sage_character', type(trivial_character(1))),
            WebDict('_values_algebraic'), WebDict('_values_float'),
            WebDict('_embeddings'),
            WebFloat('version', value=float(emf_version)))
        emf_logger.debug('Set properties in WebChar!')
        super(WebChar, self).__init__(update_from_db=update_from_db)
        if self._has_updated_from_db is False:
            self.init_dynamic_properties(
            )  # this was not done if we exited early
            compute = True
        if compute:
            self.compute(save=True)

        #emf_logger.debug('In WebChar, self.__dict__ = {0}'.format(self.__dict__))
        emf_logger.debug('In WebChar, self.number = {0}'.format(self.number))
Esempio n. 40
0
def render_fd_plot(level, info, **kwds):
    group = None
    grouptype = None
    if('group' in info):
        group = info['group']
        # we only allow standard groups
    if 'grouptype' in info:
        grouptype = int(info['grouptype'])
        if info['grouptype'] == 0:
            group = 'Gamma0'
        elif info['grouptype'] == 1:
            group = 'Gamma1'
    if (group not in ['Gamma0', 'Gamma', 'Gamma1']):
        group = 'Gamma0'
        grouptype = int(0)
    else:
        if grouptype is None:
            if group == 'Gamma':
                grouptype = int(-1)
            elif group == 'Gamma0':
                grouptype = int(0)
            else:
                grouptype = int(1)
    db_name = 'SL2Zsubgroups'
    collection = 'groups'
    C = lmfdb.base.getDBConnection()
    emf_logger.debug("C={0}, level={1}, grouptype={2}".format(C, level, grouptype))
    if not C:
        emf_logger.critical("Could not connect to Database! C={0}".format(C))
    if not db_name in C.database_names():
        emf_logger.critical("Incorrect database name {0}. \n Available databases are:{1}".format(
            db_name, C.database_names()))
    if not collection in C[db_name].collection_names():
        emf_logger.critical("Incorrect collection {0} in database {1}. \n Available collections are:{2}".format(collection, db_name, C[db_name].collection_names()))

    find = C[db_name][collection].find_one({'level': int(level), 'type': int(grouptype)})
    if find:
        if find.get('domain'):
            # domain=loads(str(find['domain']))
            domain = find['domain']
        emf_logger.debug('Found fundamental domain in database')
    else:
        emf_logger.debug('Drawing fundamental domain for group {0}({1})'.format(group, level))
        domain = draw_fundamental_domain(level, group, **kwds)
            # G=Gamma0(level)
            # C[db_name][collection].insert({'level':int(level), 'type':type, 'index':int(G.index), 'G':bson.binary.Binary(dumps(G)), 'domain': bson.binary.Binary(dumps(domain))})
            # emf_logger.debug('Inserting group and fundamental domain in database')
    return domain
def set_info_for_modular_form_space(level=None, weight=None, character=None, label=None, **kwds):
    r"""
    Set information about a space of modular forms.
    """
    info = dict()
    info["level"] = level
    info["weight"] = weight
    info["character"] = character
    emf_logger.debug("info={0}".format(info))
    #    DB = connect_to_modularforms_db()
    #    if level <> None and weight <> None and character <> None:
    #        s = {'N':int(level),'k':int(weight),'chi':int(character)}
    #        if DB.Newform_factors.files.find(s).count()==0:
    #
    #    if(level > N_max_db or weight > k_max_db):
    #        info['error'] = "Currently not available"
    #
    WMFS = None
    if level <= 0:
        info["error"] = "Got wrong level: %s " % level
        return info
    try:
        WMFS = WebModFormSpace(N=level, k=weight, chi=character)
        if "download" in info and "tempfile" in info:
            WNF._save_to_file(info["tempfile"])
            info["filename"] = str(weight) + "-" + str(level) + "-" + str(character) + "-" + label + ".sobj"
            return info
    except Exception as e:
        if isinstance(e, IndexError):
            info["error"] = e.message
        WMFS = None
    if WMFS == None:
        info["error"] = "We are sorry. The sought space can not be found in the database."
        return info
    if WMFS.level() == 1:
        info["group"] = "\( \mathrm{SL}_{2}(\mathbb{Z})\)"
    else:
        info["group"] = "\( \Gamma_{{0}}( {0} ) \)".format(WMFS.level())
    if character == 0:
        info["name_new"] = "\(S_{ %s }^{new}(%s) \)" % (WMFS.weight(), WMFS.level())
        info["name_old"] = "\(S_{ %s }^{old}(%s) \)" % (WMFS.weight(), WMFS.level())
    else:
        conrey_char = WMFS.conrey_character()
        conrey_char_name = WMFS.conrey_character_name()
        info["conrey_character_name"] = "\( " + conrey_char_name + "\)"
        info["character_url"] = url_for(
            "characters.render_Dirichletwebpage", modulus=WMFS.level(), number=conrey_char.number()
        )
        info["name_new"] = "\(S_{ %s }^{new}(%s,%s) \)" % (WMFS.weight(), WMFS.level(), conrey_char_name)
        info["name_old"] = "\(S_{ %s }^{old}(%s,%s) \)" % (WMFS.weight(), WMFS.level(), conrey_char_name)
    info["dimension_cusp_forms"] = WMFS.dimension_cusp_forms()
    info["dimension_mod_forms"] = WMFS.dimension_modular_forms()
    info["dimension_new_cusp_forms"] = WMFS.dimension_new_cusp_forms()
    info["dimension_newspace"] = WMFS.dimension_newspace()
    info["dimension_oldspace"] = WMFS.dimension_oldspace()
    info["dimension"] = WMFS.dimension()
    info["galois_orbits"] = WMFS.get_all_galois_orbit_info()
    lifts = list()
    if WMFS.dimension() == 0:  # we don't need to work with an empty space
        info["sturm_bound"] = 0
        info["new_decomposition"] = ""
        info["is_empty"] = 1
        lifts.append(("Half-Integral Weight Forms", "/ModularForm/Mp2/Q"))
        lifts.append(("Siegel Modular Forms", "/ModularForm/GSp4/Q"))
        info["lifts"] = lifts
        return info
    info["sturm_bound"] = WMFS.sturm_bound()
    info["new_decomposition"] = WMFS.print_galois_orbits()
    emf_logger.debug("new_decomp={0}".format(info["new_decomposition"]))
    info["nontrivial_new"] = len(info["new_decomposition"])
    if info["new_decomposition"] == "":
        if info["dimension_newspace"] > 0:
            info["nontrivial_new_info"] = " is unfortunately not in the database yet!"
        else:
            info["nontrivial_new_info"] = " is empty!"
    ## we try to catch well-known bugs...
    info["old_decomposition"] = "n/a"
    if level < N_max_comp:
        try:
            O = WMFS.print_oldspace_decomposition()
            info["old_decomposition"] = O
        except:
            emf_logger.critical("Error in computing oldspace decomposition")
            O = []
            info["old_decomposition"] = ""
            (A, B, C) = sys.exc_info()
            # build an error message...
            errtype = A.__name__
            errmsg = B
            s = "%s: %s  at:" % (errtype, errmsg)
            next = C.tb_next
            while next:
                ln = next.tb_lineno
                filen = next.tb_frame.f_code.co_filename
                s += "\n line no. %s in file %s" % (ln, filen)
                next = next.tb_next
                info["error_note"] = "Could not construct oldspace!\n" + s
    # properties for the sidebar
    prop = []
    if WMFS._cuspidal == 1:
        prop = [("Dimension newforms", [info["dimension_newspace"]])]
        prop.append(("Dimension oldforms", [info["dimension_oldspace"]]))
    else:
        prop = [("Dimension modular forms", [info["dimension_mod_forms"]])]
        prop.append(("Dimension cusp forms", [info["dimension_cusp_forms"]]))
    prop.append(("Sturm bound", [WMFS.sturm_bound()]))
    info["properties2"] = prop
    ## Make parent spaces of S_k(N,chi) for the sidebar
    par_lbl = "\( S_{*} (\Gamma_0(" + str(level) + "),\cdot )\)"
    par_url = "?level=" + str(level)
    parents = [[par_lbl, par_url]]
    par_lbl = "\( S_{k} (\Gamma_0(" + str(level) + "),\cdot )\)"
    par_url = "?level=" + str(level) + "&weight=" + str(weight)
    parents.append((par_lbl, par_url))
    info["parents"] = parents
    if "character" in info:
        info["character_order"] = WMFS.character_order()
        info["character_conductor"] = WMFS.character_conductor()
    friends = list()
    lifts = list()
    if ("label" not in info) and info["old_decomposition"] != "n/a":
        O = WMFS.oldspace_decomposition()
        try:
            for (old_level, chi, mult, d) in O:
                if chi != 0:
                    s = "\(S_{%s}(\Gamma_0(%s),\chi_{%s}) \) " % (weight, old_level, chi)
                    friends.append(
                        (s, "?weight=" + str(weight) + "&level=" + str(old_level) + "&character=" + str(chi))
                    )
                else:
                    s = "\(S_{%s}(\Gamma_0(%s)) \) " % (weight, old_level)
                    friends.append((s, "?weight=" + str(weight) + "&level=" + str(old_level) + "&character=" + str(0)))
        except:
            pass
    info["friends"] = friends
    lifts.append(("Half-Integral Weight Forms", "/ModularForm/Mp2/Q"))
    lifts.append(("Siegel Modular Forms", "/ModularForm/GSp4/Q"))
    info["lifts"] = lifts
    # emf_logger.debug("Info = {0}".format(info))
    return info
Esempio n. 42
0
def emf_error(s):
    s = "ERROR: " + s
    s = "<span style='color:red;'>{0}</span>".format(s)
    emf_logger.critical(s)
    return s
Esempio n. 43
0
from lmfdb.utils import to_dict, image_src
from sage.all import dimension_new_cusp_forms, dimension_cusp_forms, dimension_eis, dimension_modular_forms, Zmod, DirichletGroup, latex
from lmfdb.modular_forms.elliptic_modular_forms import EMF, emf_logger, emf, EMF_TOP, N_max_Gamma0_fdraw, N_max_Gamma1_fdraw
from lmfdb.modular_forms.elliptic_modular_forms.backend.emf_core import get_geometric_data
from lmfdb.modular_forms.elliptic_modular_forms.backend.emf_utils import my_get, parse_range, extract_limits_as_tuple
from lmfdb.modular_forms.backend.mf_utils import my_get
from lmfdb.modular_forms import MF_TOP
from lmfdb.modular_forms.elliptic_modular_forms import N_max_comp, k_max_comp, N_max_db, k_max_db
from flask import render_template, url_for, request, redirect, make_response, send_file
from lmfdb.modular_forms.elliptic_modular_forms.backend.emf_classes import ClassicalMFDisplay, DimensionTable
list_of_implemented_dims = ['new', 'cusp', 'modular', 'eisenstein']

try:
    from dirichlet_conrey import *
except:
    emf_logger.critical("Could not import dirichlet_conrey!")

met = ['POST', 'GET']


@emf.route("/TablesMF/", methods=met)
@emf.route("/TablesMF/<int:nrows>/<int:ncols>/", methods=met)
def draw_table(nrows=None, ncols=None, **kwds):
    if request.method == 'GET':
        info = to_dict(request.args)
    else:
        info = to_dict(request.form)
    ncols = my_get(info, 'ncols', ncols, int)
    nrows = my_get(info, 'nrows', nrows, int)
    if nrows is None or ncols is None:
        return emf_error("Please supply level weight (and optional character)!"), 500
Esempio n. 44
0
def set_info_for_web_newform(level=None, weight=None, character=None, label=None, **kwds):
    r"""
    Set the info for on modular form.

    """
    info = to_dict(kwds)
    info['level'] = level
    info['weight'] = weight
    info['character'] = character
    info['label'] = label
    if level is None or weight is None or character is None or label is None:
        s = "In set info for one form but do not have enough args!"
        s += "level={0},weight={1},character={2},label={3}".format(level, weight, character, label)
        emf_logger.critical(s)
    emf_logger.debug("In set_info_for_one_mf: info={0}".format(info))
    prec = my_get(info, 'prec', default_prec, int)
    bprec = my_get(info, 'bprec', default_display_bprec, int)
    emf_logger.debug("PREC: {0}".format(prec))
    emf_logger.debug("BITPREC: {0}".format(bprec))    
    try:
        WNF = WebNewForm_cached(level=level, weight=weight, character=character, label=label)
        if not WNF.has_updated():
            raise IndexError("Unfortunately, we do not have this newform in the database.")
        info['character_order'] = WNF.character.order
        info['code'] = WNF.code
        emf_logger.debug("defined webnewform for rendering!")
    except IndexError as e:
        info['error'] = e.message
    url0 = url_for("mf.modular_form_main_page")
    url1 = url_for("emf.render_elliptic_modular_forms")
    url2 = url_for("emf.render_elliptic_modular_forms", level=level)
    url3 = url_for("emf.render_elliptic_modular_forms", level=level, weight=weight)
    url4 = url_for("emf.render_elliptic_modular_forms", level=level, weight=weight, character=character)
    bread = [(MF_TOP, url0), (EMF_TOP, url1)]
    bread.append(("Level %s" % level, url2))
    bread.append(("Weight %s" % weight, url3))
    bread.append(("Character \( %s \)" % (WNF.character.latex_name), url4))
    bread.append(("Newform %d.%d.%d.%s" % (level, weight, int(character), label),''))
    info['bread'] = bread
    
    properties2 = list()
    friends = list()
    space_url = url_for('emf.render_elliptic_modular_forms',level=level, weight=weight, character=character)
    friends.append(('\( S_{%s}(%s, %s)\)'%(WNF.weight, WNF.level, WNF.character.latex_name), space_url))
    if hasattr(WNF.base_ring, "lmfdb_url") and WNF.base_ring.lmfdb_url:
        friends.append(('Number field ' + WNF.base_ring.lmfdb_pretty, WNF.base_ring.lmfdb_url))
    if hasattr(WNF.coefficient_field, "lmfdb_url") and WNF.coefficient_field.lmfdb_label:
        friends.append(('Number field ' + WNF.coefficient_field.lmfdb_pretty, WNF.coefficient_field.lmfdb_url))
    friends = uniq(friends)
    friends.append(("Dirichlet character \(" + WNF.character.latex_name + "\)", WNF.character.url()))
    
    if WNF.dimension==0 and not info.has_key('error'):
        info['error'] = "This space is empty!"
    info['title'] = 'Newform ' + WNF.hecke_orbit_label
    info['learnmore'] = [('History of modular forms', url_for('.holomorphic_mf_history'))]    
    if 'error' in info:
        return info
    ## Until we have figured out how to do the embeddings correctly we don't display the Satake
    ## parameters for non-trivial characters....

    ## Example to illustrate the different cases
    ## base              = CyclotomicField(n) -- of degree phi(n) 
    ## coefficient_field = NumberField( p(x)) for some p in base['x'] of degree m
    ##   we would then have cdeg = m*phi(n) and bdeg = phi(n)
    ##   and rdeg = m
    ## Unfortunately, for e.g. base = coefficient_field = CyclotomicField(6)
    ## we get coefficient_field.relative_degree() == 2 although it should be 1
    cdeg = WNF.coefficient_field.absolute_degree()
    bdeg = WNF.base_ring.absolute_degree()
    if cdeg == 1:
        rdeg = 1
    else:
        ## just setting rdeg = WNF.coefficient_field.relative_degree() does not give correct result...
        ## 
        rdeg = QQ(cdeg)/QQ(bdeg)
    cf_is_QQ = (cdeg == 1)
    br_is_QQ = (bdeg == 1)
    if cf_is_QQ:
        info['satake'] = WNF.satake
    if WNF.complexity_of_first_nonvanishing_coefficients() > default_max_height:
        info['qexp'] = ""
        info['qexp_display'] = ''
        info['hide_qexp'] = True
        n,c = WNF.first_nonvanishing_coefficient()
        info['trace_nv'] = latex(WNF.first_nonvanishing_coefficient_trace())
        info['norm_nv'] = '\\approx ' + latex(WNF.first_nonvanishing_coefficient_norm().n())
        info['index_nv'] = n
    else:
        if WNF.prec < prec:
            #get WNF record at larger prec
            WNF.prec = prec
            WNF.update_from_db()
        info['qexp'] = WNF.q_expansion_latex(prec=10, name='\\alpha ')
        info['qexp_display'] = url_for(".get_qexp_latex", level=level, weight=weight, character=character, label=label)
        info["hide_qexp"] = False
    info['max_cn_qexp'] = WNF.q_expansion.prec()
    ## All combinations should be tested...
    ## 13/4/4/a -> base ring = coefficient_field = QQ(zeta_6)
    ## 13/3/8/a ->  base_ring = QQ(zeta_4), coefficient_field has poly x^2+(2\zeta_4+2x-3\zeta_$ over base_ring
    ## 13/4/3/a ->  base_ring = coefficient_field = QQ(zeta_3) 
    ## 13/4/1/a -> all rational
    ## 13/6/1/a/ -> base_ring = QQ, coefficient_field = Q(sqrt(17))
    ## These are variables which needs to be set properly below
    info['polvars'] = {'base_ring':'x','coefficient_field':'\\alpha'}
    if not cf_is_QQ:
        if rdeg>1: # not WNF.coefficient_field == WNF.base_ring:
            ## Here WNF.base_ring should be some cyclotomic field and we have an extension over this.
            p1 = WNF.coefficient_field.relative_polynomial()
            c_pol_ltx = web_latex_poly(p1, '\\alpha')  # make the variable \alpha
            c_pol_ltx_x = web_latex_poly(p1, 'x')
            zeta = p1.base_ring().gens()[0]
#           p2 = zeta.minpoly() #this is not used anymore
#           b_pol_ltx = web_latex_poly(p2, latex(zeta)) #this is not used anymore
            z1 = zeta.multiplicative_order() 
            info['coeff_field'] = [ WNF.coefficient_field.absolute_polynomial_latex('x'),c_pol_ltx_x, z1]
            if hasattr(WNF.coefficient_field, "lmfdb_url") and WNF.coefficient_field.lmfdb_url:
                info['coeff_field_pretty'] = [ WNF.coefficient_field.lmfdb_url, WNF.coefficient_field.lmfdb_pretty, WNF.coefficient_field.lmfdb_label]
            if z1==4:
                info['polynomial_st'] = '<div class="where">where</div> {0}\(\mathstrut=0\) and \(\zeta_4=i\).</div><br/>'.format(c_pol_ltx)
                info['polvars']['base_ring']='i'
            elif z1<=2:
                info['polynomial_st'] = '<div class="where">where</div> {0}\(\mathstrut=0\).</div><br/>'.format(c_pol_ltx)
            else:
                info['polynomial_st'] = '<div class="where">where</div> %s\(\mathstrut=0\) and \(\zeta_{%s}=e^{\\frac{2\\pi i}{%s}}\) '%(c_pol_ltx, z1,z1)
                info['polvars']['base_ring']='\zeta_{{ {0} }}'.format(z1)
                if z1==3:
                    info['polynomial_st'] += 'is a primitive cube root of unity.'
                else:
                    info['polynomial_st'] += 'is a primitive {0}-th root of unity.'.format(z1)
        elif not br_is_QQ:
            ## Now we have base and coefficient field being equal, meaning that since the coefficient field is not QQ it is some cyclotomic field
            ## generated by some \zeta_n 
            p1 = WNF.coefficient_field.absolute_polynomial()
            z1 = WNF.coefficient_field.gens()[0].multiplicative_order()
            c_pol_ltx = web_latex_poly(p1, '\\zeta_{{{0}}}'.format(z1))
            c_pol_ltx_x = web_latex_poly(p1, 'x')
            info['coeff_field'] = [ WNF.coefficient_field.absolute_polynomial_latex('x'), c_pol_ltx_x]
            if hasattr(WNF.coefficient_field, "lmfdb_url") and WNF.coefficient_field.lmfdb_url:
                info['coeff_field_pretty'] = [ WNF.coefficient_field.lmfdb_url, WNF.coefficient_field.lmfdb_pretty, WNF.coefficient_field.lmfdb_label]
            if z1==4:
                info['polynomial_st'] = '<div class="where">where \(\zeta_4=e^{{\\frac{{\\pi i}}{{ 2 }} }}=i \).</div>'.format(c_pol_ltx)
                info['polvars']['coefficient_field']='i'
            elif z1<=2:
                info['polynomial_st'] = '' 
            else:
                info['polynomial_st'] = '<div class="where">where \(\zeta_{{{0}}}=e^{{\\frac{{2\\pi i}}{{ {0} }} }}\) '.format(z1)
                info['polvars']['coefficient_field']='\zeta_{{{0}}}'.format(z1)
                if z1==3:
                    info['polynomial_st'] += 'is a primitive cube root of unity.</div>'
                else:
                    info['polynomial_st'] += 'is a primitive {0}-th root of unity.</div>'.format(z1)
    else:
        info['polynomial_st'] = ''
    if info["hide_qexp"]:
        info['polynomial_st'] = ''
    info['degree'] = int(cdeg)
    if cdeg==1:
        info['is_rational'] = 1
        info['coeff_field_pretty'] = [ WNF.coefficient_field.lmfdb_url, WNF.coefficient_field.lmfdb_pretty ]
    else:
        info['is_rational'] = 0
    emf_logger.debug("PREC2: {0}".format(prec))
    info['embeddings'] = WNF._embeddings['values'] #q_expansion_embeddings(prec, bprec,format='latex')
    info['embeddings_len'] = len(info['embeddings'])
    properties2 = [('Level', str(level)),
                       ('Weight', str(weight)),
                       ('Character', '$' + WNF.character.latex_name + '$'),
                       ('Label', WNF.hecke_orbit_label),
                       ('Dimension of Galois orbit', str(WNF.dimension))]
    if (ZZ(level)).is_squarefree():
        info['twist_info'] = WNF.twist_info
        if isinstance(info['twist_info'], list) and len(info['twist_info'])>0:
            info['is_minimal'] = info['twist_info'][0]
            if(info['twist_info'][0]):
                s = 'Is minimal<br>'
            else:
                s = 'Is a twist of lower level<br>'
            properties2 += [('Twist info', s)]
    else:
        info['twist_info'] = 'Twist info currently not available.'
        properties2 += [('Twist info', 'not available')]
    args = list()
    for x in range(5, 200, 10):
        args.append({'digits': x})
    alev = None
    CM = WNF._cm_values
    if CM is not None:
        if CM.has_key('tau') and len(CM['tau']) != 0:
            info['CM_values'] = CM
    info['is_cm'] = WNF.is_cm
    if WNF.is_cm == 1:
        info['cm_field'] = "2.0.{0}.1".format(-WNF.cm_disc)
        info['cm_disc'] = WNF.cm_disc
        info['cm_field_knowl'] = nf_display_knowl(info['cm_field'], getDBConnection(), field_pretty(info['cm_field']))
        info['cm_field_url'] = url_for("number_fields.by_label", label=info["cm_field"])
    if WNF.is_cm is None or WNF.is_cm==-1:
        s = '- Unknown (insufficient data)<br>'
    elif WNF.is_cm == 1:
        s = 'Yes<br>'
    else:
        s = 'No<br>'
    properties2.append(('CM', s))
    alev = WNF.atkin_lehner_eigenvalues()
    info['atkinlehner'] = None
    if isinstance(alev,dict) and len(alev.keys())>0 and level != 1:
        s1 = " Atkin-Lehner eigenvalues "
        s2 = ""
        for Q in alev.keys():
            s2 += "\( \omega_{ %s } \) : %s <br>" % (Q, alev[Q])
        properties2.append((s1, s2))
        emf_logger.debug("properties={0}".format(properties2))
        # alev = WNF.atkin_lehner_eigenvalues_for_all_cusps() 
        # if isinstance(alev,dict) and len(alev.keys())>0:
        #     emf_logger.debug("alev={0}".format(alev))
        #     info['atkinlehner'] = list()
        #     for Q in alev.keys():
        #         s = "\(" + latex(c) + "\)"
        #         Q = alev[c][0]
        #         ev = alev[c][1]
        #         info['atkinlehner'].append([Q, c, ev])
    if(level == 1):
        poly = WNF.explicit_formulas.get('as_polynomial_in_E4_and_E6','')
        if poly != '':
            d,monom,coeffs = poly
            emf_logger.critical("poly={0}".format(poly))
            info['explicit_formulas'] = '\('
            for i in range(len(coeffs)):
                c = QQ(coeffs[i])
                s = ""
                if d>1 and i >0 and c>0:
                    s="+"
                if c<0:
                    s="-"
                if c.denominator()>1:
                    cc = "\\frac{{ {0} }}{{ {1} }}".format(abs(c.numerator()),c.denominator())
                else:
                    cc = str(abs(c))
                s += "{0} \cdot ".format(cc)
                a = monom[i][0]; b = monom[i][1]
                if a == 0 and b != 0:
                    s+="E_6^{{ {0} }}".format(b)
                elif b ==0 and a != 0:
                    s+="E_4^{{ {0} }}".format(a)
                else:
                    s+="E_4^{{ {0} }}E_6^{{ {1} }}".format(a,b)
                info['explicit_formulas'] += s
            info['explicit_formulas'] += " \)"            
    # cur_url = '?&level=' + str(level) + '&weight=' + str(weight) + '&character=' + str(character) + '&label=' + str(label) # never used
    if len(WNF.parent.hecke_orbits) > 1:
        for label_other in WNF.parent.hecke_orbits.keys():
            if(label_other != label):
                s = 'Modular form '
                if character:
                    s += newform_label(level,weight,character,label_other)
                else:
                    s += newform_label(level,weight,1,label_other)

                url = url_for('emf.render_elliptic_modular_forms', level=level,
                              weight=weight, character=character, label=label_other)
                friends.append((s, url))

    s = 'L-Function '
    if character:
        s += newform_label(level,weight,character,label)
    else:
        s += newform_label(level,weight,1,label)
    # url =
    # "/L/ModularForm/GL2/Q/holomorphic?level=%s&weight=%s&character=%s&label=%s&number=%s"
    # %(level,weight,character,label,0)
    url = '/L' + url_for(
        'emf.render_elliptic_modular_forms', level=level, weight=weight, character=character, label=label)
    if WNF.coefficient_field_degree > 1:
        for h in range(WNF.coefficient_field_degree):
            s0 = s + ".{0}".format(h)
            url0 = url + "{0}/".format(h)
            friends.append((s0, url0))
    else:
        friends.append((s, url))
    # if there is an elliptic curve over Q associated to self we also list that
    if WNF.weight == 2 and WNF.coefficient_field_degree == 1:
        llabel = str(level) + '.' + label
        s = 'Elliptic curve isogeny class ' + llabel
        url = '/EllipticCurve/Q/' + llabel
        friends.append((s, url))
    info['properties2'] = properties2
    info['friends'] = friends
    info['max_cn'] = WNF.max_available_prec()
    return info
Esempio n. 45
0
    def __init__(self,
                 level=1,
                 weight=12,
                 character=1,
                 label='a',
                 prec=None,
                 parent=None,
                 update_from_db=True):
        emf_logger.critical("In WebNewForm {0}".format(
            (level, weight, character, label, parent, update_from_db)))
        self._reduction = (type(self), (level, weight, character, label), {
            'parent': parent,
            'update_from_db': update_from_db
        })
        if isinstance(character, WebChar):
            character_number = character.number
        else:
            character_number = character
            character = None if parent is None else parent.character
            if not isinstance(label, basestring):
                if isinstance(label, (int, Integer)):
                    label = orbit_label(label)
                else:
                    raise ValueError, "Need label either string or integer! We got:{0}".format(
                        label)

        emf_logger.critical("Before init properties 0")
        self._properties = WebProperties(
            WebInt('level', value=level), WebInt('weight', value=weight),
            WebCharProperty(
                'character',
                modulus=level,
                number=character_number,
                value=character,
                include_in_update=True if character is None else False),
            WebStr('character_naming_scheme', value='Conrey'),
            WebStr('hecke_orbit_label',
                   default_value=newform_label(level, weight, character_number,
                                               label)),
            WebStr('label', default_value=label), WebInt('dimension'),
            WebqExp('q_expansion'), WebDict('_coefficients'),
            WebDict('_embeddings'), WebInt('prec', value=0),
            WebNumberField('base_ring'), WebNumberField('coefficient_field'),
            WebInt('coefficient_field_degree'),
            WebList('twist_info', required=False),
            WebBool('is_cm', required=False),
            WebDict('_cm_values', required=False),
            WebBool('is_cuspidal', default_value=True),
            WebDict('satake', required=False),
            WebDict('_atkin_lehner_eigenvalues', required=False),
            WebBool('is_rational'), WebPoly('absolute_polynomial'),
            WebFloat('version', value=float(emf_version), save_to_fs=True),
            WebDict('explicit_formulas', required=False),
            WebModFormSpaceProperty('parent',
                                    value=parent,
                                    level=level,
                                    weight=weight,
                                    character=character_number,
                                    update_hecke_orbits=False)
            #                                    include_in_update = True if parent is None
            #                                    else False),
        )
        emf_logger.critical("After init properties 1")
        super(WebNewForm, self).__init__(update_from_db=update_from_db)
        emf_logger.critical("After init properties 2 prec={0}".format(
            self.prec))
        # We're setting the WebEigenvalues property after calling __init__ of the base class
        # because it will set hecke_orbit_label from the db first

        ##
        ## We don't init the eigenvalues (since E*v is slow)
        ## unless we (later) request a coefficient which is not
        ## in self._coefficients

        self.eigenvalues = WebEigenvalues(self.hecke_orbit_label,
                                          prec=self.prec,
                                          init_dynamic_properties=False)
        emf_logger.critical("After init properties 3")
def set_info_for_modular_form_space(level=None, weight=None, character=None, label=None, **kwds):
    r"""
    Set information about a space of modular forms.
    """
    info = dict()
    info['level'] = level
    info['weight'] = weight
    info['character'] = character
    emf_logger.debug("info={0}".format(info))
    if(level > N_max_db or weight > k_max_db):
        info['error'] = "Currently not available"
    WMFS = None
    if level <= 0:
        info['error'] = "Got wrong level: %s " % level
        return info
    try:
        if use_db:
            WMFS = WebModFormSpace(weight, level, character, use_db=True)
        else:
            WMFS = WebModFormSpace(weight, level, character)
        if 'download' in info and 'tempfile' in info:
            WNF._save_to_file(info['tempfile'])
            info['filename'] = str(weight) + '-' + str(level) + '-' + str(character) + '-' + label + '.sobj'
            return info
    except RuntimeError:
                info['error'] = "Sage error: Could not construct the desired space!"
    if WMFS.level() == 1:
        info['group'] = "\( \mathrm{SL}_{2}(\mathbb{Z})\)"
    else:
        info['group'] = "\( \Gamma_{{0}}( {0} ) \)".format(WMFS.level())
    if character == 0:
        info['name_new'] = "\(S_{ %s }^{new}(%s) \)" % (WMFS.weight(), WMFS.level())
        info['name_old'] = "\(S_{ %s }^{old}(%s) \)" % (WMFS.weight(), WMFS.level())
    else:
        conrey_char = WMFS.conrey_character()
        conrey_char_name = WMFS.conrey_character_name()
        info['conrey_character_name'] = '\( ' + conrey_char_name + '\)'
        info['character_url'] = url_character(type='Dirichlet', modulus=WMFS.level(), number=conrey_char.number())
        info['name_new'] = "\(S_{ %s }^{new}(%s,%s) \)" % (WMFS.weight(), WMFS.level(), conrey_char_name)
        info['name_old'] = "\(S_{ %s }^{old}(%s,%s) \)" % (WMFS.weight(), WMFS.level(), conrey_char_name)
    info['dimension_cusp_forms'] = WMFS.dimension_cusp_forms()
    info['dimension_mod_forms'] = WMFS.dimension_modular_forms()
    info['dimension_new_cusp_forms'] = WMFS.dimension_new_cusp_forms()
    info['dimension_newspace'] = WMFS.dimension_newspace()
    info['dimension_oldspace'] = WMFS.dimension_oldspace()
    info['dimension'] = WMFS.dimension()
    info['galois_orbits'] = WMFS.get_all_galois_orbit_info()
    lifts = list()
    if WMFS.dimension() == 0:  # we don't need to work with an empty space
        info['sturm_bound'] = 0
        info['new_decomposition'] = ''
        info['is_empty'] = 1
        lifts.append(('Half-Integral Weight Forms', '/ModularForm/Mp2/Q'))
        lifts.append(('Siegel Modular Forms', '/ModularForm/GSp4/Q'))
        info['lifts'] = lifts
        return info
    info['sturm_bound'] = WMFS.sturm_bound()
    info['new_decomposition'] = WMFS.print_galois_orbits()
    emf_logger.debug("new_decomp={0}".format(info['new_decomposition']))
    info['nontrivial_new'] = len(info['new_decomposition'])
    ## we try to catch well-known bugs...
    info['old_decomposition'] = "n/a"
    if level < N_max_comp:
        try:
            O = WMFS.print_oldspace_decomposition()
            info['old_decomposition'] = O
        except:
            emf_logger.critical("Error in computing oldspace decomposition")
            O = []
            info['old_decomposition'] = "n/a"
            (A, B, C) = sys.exc_info()
            # build an error message...
            errtype = A.__name__
            errmsg = B
            s = "%s: %s  at:" % (errtype, errmsg)
            next = C.tb_next
            while(next):
                ln = next.tb_lineno
                filen = next.tb_frame.f_code.co_filename
                s += "\n line no. %s in file %s" % (ln, filen)
                next = next.tb_next
                info['error_note'] = "Could not construct oldspace!\n" + s
    # properties for the sidebar
    prop = []
    if WMFS._cuspidal == 1:
        prop = [('Dimension newforms', [info['dimension_newspace']])]
        prop.append(('Dimension oldforms', [info['dimension_oldspace']]))
    else:
        prop = [('Dimension modular forms', [info['dimension_mod_forms']])]
        prop.append(('Dimension cusp forms', [info['dimension_cusp_forms']]))
    prop.append(('Sturm bound', [WMFS.sturm_bound()]))
    info['properties2'] = prop
    ## Make parent spaces of S_k(N,chi) for the sidebar
    par_lbl = '\( S_{*} (\Gamma_0(' + str(level) + '),\cdot )\)'
    par_url = '?level=' + str(level)
    parents = [[par_lbl, par_url]]
    par_lbl = '\( S_{k} (\Gamma_0(' + str(level) + '),\cdot )\)'
    par_url = '?level=' + str(level) + '&weight=' + str(weight)
    parents.append((par_lbl, par_url))
    info['parents'] = parents
    if 'character' in info:
        info['character_order'] = WMFS.character_order()
        info['character_conductor'] = WMFS.character_conductor()
    friends = list()
    lifts = list()
    if(('label' not in info) and info['old_decomposition'] != 'n/a'):
        O = WMFS.oldspace_decomposition()
        try:
            for (old_level, chi, mult, d) in O:
                if chi != 0:
                    s = "\(S_{%s}(\Gamma_0(%s),\chi_{%s}) \) " % (weight, old_level, chi)
                    friends.append((
                        s, '?weight=' + str(weight) + '&level=' + str(old_level) + '&character=' + str(chi)))
                else:
                    s = "\(S_{%s}(\Gamma_0(%s)) \) " % (weight, old_level)
                    friends.append(
                        (s, '?weight=' + str(weight) + '&level=' + str(old_level) + '&character=' + str(0)))
        except:
            pass
    info['friends'] = friends
    lifts.append(('Half-Integral Weight Forms', '/ModularForm/Mp2/Q'))
    lifts.append(('Siegel Modular Forms', '/ModularForm/GSp4/Q'))
    info['lifts'] = lifts
    return info
Esempio n. 47
0
def set_info_for_web_newform(level=None,
                             weight=None,
                             character=None,
                             label=None,
                             **kwds):
    r"""
    Set the info for on modular form.

    """
    info = to_dict(kwds)
    info['level'] = level
    info['weight'] = weight
    info['character'] = character
    info['label'] = label
    if level is None or weight is None or character is None or label is None:
        s = "In set info for one form but do not have enough args!"
        s += "level={0},weight={1},character={2},label={3}".format(
            level, weight, character, label)
        emf_logger.critical(s)
    emf_logger.debug("In set_info_for_one_mf: info={0}".format(info))
    prec = my_get(info, 'prec', default_prec, int)
    bprec = my_get(info, 'bprec', default_display_bprec, int)
    emf_logger.debug("PREC: {0}".format(prec))
    emf_logger.debug("BITPREC: {0}".format(bprec))
    try:
        WNF = WebNewForm_cached(level=level,
                                weight=weight,
                                character=character,
                                label=label)
        emf_logger.critical("defined webnewform for rendering!")
        # if info.has_key('download') and info.has_key('tempfile'):
        #     WNF._save_to_file(info['tempfile'])
        #     info['filename']=str(weight)+'-'+str(level)+'-'+str(character)+'-'+label+'.sobj'
        #     return info
    except IndexError as e:
        WNF = None
        info['error'] = e.message
    url1 = url_for("emf.render_elliptic_modular_forms")
    url2 = url_for("emf.render_elliptic_modular_forms", level=level)
    url3 = url_for("emf.render_elliptic_modular_forms",
                   level=level,
                   weight=weight)
    url4 = url_for("emf.render_elliptic_modular_forms",
                   level=level,
                   weight=weight,
                   character=character)
    bread = [(EMF_TOP, url1)]
    bread.append(("of level %s" % level, url2))
    bread.append(("weight %s" % weight, url3))
    if int(character) == 0:
        bread.append(("trivial character", url4))
    else:
        bread.append(("\( %s \)" % (WNF.character.latex_name), url4))
    info['bread'] = bread

    properties2 = list()
    friends = list()
    space_url = url_for('emf.render_elliptic_modular_forms',
                        level=level,
                        weight=weight,
                        character=character)
    friends.append(
        ('\( S_{%s}(%s, %s)\)' %
         (WNF.weight, WNF.level, WNF.character.latex_name), space_url))
    if WNF.coefficient_field_label(check=True):
        friends.append(('Number field ' + WNF.coefficient_field_label(),
                        WNF.coefficient_field_url()))
    friends.append(
        ('Number field ' + WNF.base_field_label(), WNF.base_field_url()))
    friends = uniq(friends)
    friends.append(("Dirichlet character \(" + WNF.character.latex_name + "\)",
                    WNF.character.url()))

    if WNF.dimension == 0:
        info['error'] = "This space is empty!"


#    emf_logger.debug("WNF={0}".format(WNF))

#info['name'] = name
    info['title'] = 'Modular Form ' + WNF.hecke_orbit_label

    if 'error' in info:
        return info
    # info['name']=WNF._name
    ## Until we have figured out how to do the embeddings correctly we don't display the Satake
    ## parameters for non-trivial characters....

    cdeg = WNF.coefficient_field.absolute_degree()
    bdeg = WNF.base_ring.absolute_degree()
    if WNF.coefficient_field.absolute_degree() == 1:
        rdeg = 1
    else:
        rdeg = WNF.coefficient_field.relative_degree()
    if cdeg == 1:
        info['satake'] = WNF.satake
    info['qexp'] = WNF.q_expansion_latex(prec=10, name='a')
    info['qexp_display'] = url_for(".get_qexp_latex",
                                   level=level,
                                   weight=weight,
                                   character=character,
                                   label=label)

    # info['qexp'] = WNF.q_expansion_latex(prec=prec)
    #c_pol_st = str(WNF.absolute_polynomial)
    #b_pol_st = str(WNF.polynomial(type='base_ring',format='str'))
    #b_pol_ltx = str(WNF.polynomial(type='base_ring',format='latex'))
    #print "c=",c_pol_ltx
    #print "b=",b_pol_ltx
    if cdeg > 1:  ## Field is QQ
        if bdeg > 1 and rdeg > 1:
            p1 = WNF.coefficient_field.relative_polynomial()
            c_pol_ltx = latex(p1)
            lgc = p1.variables()[0]
            c_pol_ltx = c_pol_ltx.replace(lgc, 'a')
            z = p1.base_ring().gens()[0]
            p2 = z.minpoly()
            b_pol_ltx = latex(p2)
            b_pol_ltx = b_pol_ltx.replace(latex(p2.variables()[0]), latex(z))
            info['polynomial_st'] = 'where \({0}=0\) and \({1}=0\).'.format(
                c_pol_ltx, b_pol_ltx)
        else:
            c_pol_ltx = latex(WNF.coefficient_field.relative_polynomial())
            lgc = str(
                latex(WNF.coefficient_field.relative_polynomial().variables()
                      [0]))
            c_pol_ltx = c_pol_ltx.replace(lgc, 'a')
            info['polynomial_st'] = 'where \({0}=0\)'.format(c_pol_ltx)
    else:
        info['polynomial_st'] = ''
    info['degree'] = int(cdeg)
    if cdeg == 1:
        info['is_rational'] = 1
    else:
        info['is_rational'] = 0
    # info['q_exp_embeddings'] = WNF.print_q_expansion_embeddings()
    # if(int(info['degree'])>1 and WNF.dimension()>1):
    #    s = 'One can embed it into \( \mathbb{C} \) as:'
    # bprec = 26
    # print s
    #    info['embeddings'] =  ajax_more2(WNF.print_q_expansion_embeddings,{'prec':[5,10,25,50],'bprec':[26,53,106]},text=['more coeffs.','higher precision'])
    # elif(int(info['degree'])>1):
    #    s = 'There are '+str(info['degree'])+' embeddings into \( \mathbb{C} \):'
    # bprec = 26
    # print s
    #    info['embeddings'] =  ajax_more2(WNF.print_q_expansion_embeddings,{'prec':[5,10,25,50],'bprec':[26,53,106]},text=['more coeffs.','higher precision'])
    # else:
    #    info['embeddings'] = ''
    emf_logger.debug("PREC2: {0}".format(prec))
    info['embeddings'] = WNF._embeddings[
        'values']  #q_expansion_embeddings(prec, bprec,format='latex')
    info['embeddings_len'] = len(info['embeddings'])
    properties2 = []
    if (ZZ(level)).is_squarefree():
        info['twist_info'] = WNF.twist_info
        if isinstance(info['twist_info'],
                      list) and len(info['twist_info']) > 0:
            info['is_minimal'] = info['twist_info'][0]
            if (info['twist_info'][0]):
                s = '- Is minimal<br>'
            else:
                s = '- Is a twist of lower level<br>'
            properties2 = [('Twist info', s)]
    else:
        info['twist_info'] = 'Twist info currently not available.'
        properties2 = [('Twist info', 'not available')]
    args = list()
    for x in range(5, 200, 10):
        args.append({'digits': x})
    alev = None
    CM = WNF._cm_values
    if CM is not None:
        if CM.has_key('tau') and len(CM['tau']) != 0:
            info['CM_values'] = CM
    info['is_cm'] = WNF.is_cm
    if WNF.is_cm is None:
        s = '- Unknown (insufficient data)<br>'
    elif WNF.is_cm is True:
        s = '- Is a CM-form<br>'
    else:
        s = '- Is not a CM-form<br>'
    properties2.append(('CM info', s))
    alev = WNF.atkin_lehner_eigenvalues()
    info['atkinlehner'] = None
    if isinstance(alev, dict) and len(alev.keys()) > 0 and level != 1:
        s1 = " Atkin-Lehner eigenvalues "
        s2 = ""
        for Q in alev.keys():
            s2 += "\( \omega_{ %s } \) : %s <br>" % (Q, alev[Q])
        properties2.append((s1, s2))
        emf_logger.debug("properties={0}".format(properties2))
        # alev = WNF.atkin_lehner_eigenvalues_for_all_cusps()
        # if isinstance(alev,dict) and len(alev.keys())>0:
        #     emf_logger.debug("alev={0}".format(alev))
        #     info['atkinlehner'] = list()
        #     for Q in alev.keys():
        #         s = "\(" + latex(c) + "\)"
        #         Q = alev[c][0]
        #         ev = alev[c][1]
        #         info['atkinlehner'].append([Q, c, ev])
    if (level == 1):
        poly = WNF.explicit_formulas.get('as_polynomial_in_E4_and_E6', '')
        if poly <> '':
            d, monom, coeffs = poly
            emf_logger.critical("poly={0}".format(poly))

            info['explicit_formulas'] = '\('
            for i in range(d):
                c = QQ(coeffs[i])
                s = ""
                if d > 1 and i > 0 and c > 0:
                    s = "+"
                if c < 0:
                    s = "-"
                if c.denominator() > 1:
                    cc = "\\frac{{ {0} }}{{ {1} }}".format(
                        abs(c.numerator()), c.denominator())
                else:
                    cc = str(abs(c))
                s += "{0} \cdot ".format(cc)
                a = monom[i][0]
                b = monom[i][1]
                if a == 0 and b <> 0:
                    s += "E_6^{{ {0} }}".format(b)
                elif b == 0 and a <> 0:
                    s += "E_4^{{ {0} }}".format(a)
                else:
                    s += "E_4^{{ {0} }}E_6^{{ {1} }}".format(a, b)
                info['explicit_formulas'] += s
            info['explicit_formulas'] += " \)"
    cur_url = '?&level=' + str(level) + '&weight=' + str(weight) + '&character=' + str(character) + \
        '&label=' + str(label)
    if len(WNF.parent.hecke_orbits) > 1:
        for label_other in WNF.parent.hecke_orbits.keys():
            if (label_other != label):
                s = 'Modular form '
                if character:
                    s = s + str(level) + '.' + str(weight) + '.' + str(
                        character) + str(label_other)
                else:
                    s = s + str(level) + '.' + str(weight) + str(label_other)
                url = url_for('emf.render_elliptic_modular_forms',
                              level=level,
                              weight=weight,
                              character=character,
                              label=label_other)
                friends.append((s, url))

    s = 'L-Function '
    if character:
        s = s + str(level) + '.' + str(weight) + '.' + str(character) + str(
            label)
    else:
        s = s + str(level) + '.' + str(weight) + str(label)
    # url =
    # "/L/ModularForm/GL2/Q/holomorphic?level=%s&weight=%s&character=%s&label=%s&number=%s"
    # %(level,weight,character,label,0)
    url = '/L' + url_for('emf.render_elliptic_modular_forms',
                         level=level,
                         weight=weight,
                         character=character,
                         label=label)
    if WNF.coefficient_field_degree > 1:
        for h in range(WNF.coefficient_field_degree):
            s0 = s + ".{0}".format(h)
            url0 = url + "{0}/".format(h)
            friends.append((s0, url0))
    else:
        friends.append((s, url))
    # if there is an elliptic curve over Q associated to self we also list that
    if WNF.weight == 2 and WNF.coefficient_field_degree == 1:
        llabel = str(level) + '.' + label
        s = 'Elliptic curve isogeny class ' + llabel
        url = '/EllipticCurve/Q/' + llabel
        friends.append((s, url))
    info['properties2'] = properties2
    info['friends'] = friends
    info['max_cn'] = WNF.max_cn()
    return info
def set_info_for_modular_form_space(level=None, weight=None, character=None, label=None, **kwds):
    r"""
      Set information about a space of modular forms.
    """
    info = dict()
    emf_logger.debug("info={0}".format(info))    
    WMFS = None
    if info.has_key('error'):
        return info
    if level <= 0:
        info['error'] = "Got wrong level: %s " % level
        return info
    try:
        WMFS = WebModFormSpace_cached(level = level, weight = weight, cuspidal=True, character = character, update_from_db=True)
        WMFS.update_from_db() ## Need to call an extra time for some reason...
        if not WMFS.has_updated():
            stop = False
            orbit = WMFS.character.character.galois_orbit()
            while not stop:
                if len(orbit) == 0:
                    stop = True
                    continue
                c = orbit.pop()
                if c.number() == WMFS.character.number:
                    continue
                print c.number()
                WMFS_rep = WebModFormSpace_cached(level = level, weight = weight, cuspidal=True, character = c.number(), update_from_db=True)
                if WMFS_rep.has_updated_from_db():
                    stop = True
                    info['wmfs_rep_url'] = url_for('emf.render_elliptic_modular_forms', level=level, weight=weight, character = c.number())
                    info['wmfs_rep_number'] =  c.number()
                    
        emf_logger.debug("Created WebModFormSpace %s"%WMFS)
        if 'download' in info and 'tempfile' in info:
            save(WNF,info['tempfile'])
            info['filename'] = str(weight) + '-' + str(level) + '-' + str(character) + '-' + label + '.sobj'
            return info
    except ValueError as e:
        emf_logger.debug(e)
        emf_logger.debug(e.message)
        #if isinstance(e,IndexError):
        info['error'] = e.message
        WMFS = None
    if WMFS is None:
        info['error'] = "We are sorry. The sought space can not be found in the database. "+"<br> Detailed information: {0}".format(info.get('error',''))
        return info
    else:
        ### Somehow the Hecke orbits are sometimes not in the space...
        #if WMFS.dimension_new_cusp_forms()!=len(WMFS.hecke_orbits):
        #    ## Try to add them here... 
        #    for d in range(len(WMFS.dimension_new_cusp_forms())):
        #        F = 
        #        WMFS.hecke_orbits.append(F)
        info['space'] = WMFS
#    info['old_decomposition'] = WMFS.oldspace_decomposition()
    info['oldspace_decomposition']=''
    try: 
        emf_logger.debug("Oldspace = {0}".format(WMFS.oldspace_decomposition))
        if WMFS.oldspace_decomposition != []:
            emf_logger.debug("oldspace={0}".format(WMFS.oldspace_decomposition))
            l = []
            for t in WMFS.oldspace_decomposition:
                emf_logger.debug("t={0}".format(t))
                N,k,chi,mult,d = t
                url = url_for('emf.render_elliptic_modular_forms', level=N, weight=k, character=chi)
                if chi != 1:
                    sname = "S^{{ new }}_{{ {k} }}(\\Gamma_0({N}),\\chi_{{ {N} }}({chi},\\cdot))".format(k=k,N=N,chi=chi)
                else:
                    sname = "S^{{ new }}_{{ {k} }}(\\Gamma_0({N}))".format(k=k,N=N)
                l.append("\href{{ {url} }}{{ {sname} }}^{{\oplus {mult} }}".format(sname=sname,mult=mult,url=url))
            if l != []:            
                s = "\\oplus ".join(l)
                info['oldspace_decomposition']=' $ {0} $'.format(s)
    except Exception as e:
        emf_logger.critical("Oldspace decomposition failed. Error:{0}".format(e))
    ## For side-bar
    lifts = list()
    lifts.append(('Half-Integral Weight Forms', '/ModularForm/Mp2/Q'))
    lifts.append(('Siegel Modular Forms', '/ModularForm/GSp4/Q'))
    info['lifts'] = lifts
    friends = list()
    for label in WMFS.hecke_orbits:
        f = WMFS.hecke_orbits[label]
        # catch the url being None or set to '':
        if hasattr(f.base_ring, "lmfdb_url") and f.base_ring.lmfdb_url:
            friends.append(('Number field ' + f.base_ring.lmfdb_pretty, f.base_ring.lmfdb_url))
        if hasattr(f.coefficient_field, "lmfdb_url") and f.coefficient_field.lmfdb_url:
            friends.append(('Number field ' + f.coefficient_field.lmfdb_pretty, f.coefficient_field.lmfdb_url))
    friends.append(("Dirichlet character \(" + WMFS.character.latex_name + "\)", WMFS.character.url()))
    friends = uniq(friends)
    info['friends'] = friends
    
    return info
Esempio n. 49
0
 def set_table_browsing(self,
                        skip=[0, 0],
                        limit=[(2, 16), (1, 50)],
                        keys=['Weight', 'Level'],
                        character=0,
                        dimension_table=None,
                        dimension_fun=dimension_new_cusp_forms,
                        title='Dimension of newforms',
                        check_db=True):
     r"""
     Table of Holomorphic modular forms spaces.
     Skip tells you how many chunks of data you want to skip (from the geginning) and limit tells you how large each chunk is.
     INPUT:
     - dimension_fun should be a function which gives you the desired dimensions, as functions of level N and weight k
     - character = 0 for trivial character and 1 for Kronecker symbol.
       set to 'all' for all characters.
     - check_db=True means, that we will only link to spaces which are in the database
     """
     self._keys = keys
     self._skip = skip
     self._limit = limit
     self._metadata = []
     self._title = ''
     self._cols = []
     self.table = {}
     self._character = character
     emf_logger.debug("skip= {0}".format(self._skip))
     emf_logger.debug("limit= {0}".format(self._limit))
     il = self._keys.index('Level')
     iwt = self._keys.index('Weight')
     level_len = self._limit[il][1] - self._limit[il][0] + 1
     level_ll = self._skip[il] * level_len + self._limit[il][0]
     level_ul = self._skip[il] * level_len + self._limit[il][1]
     wt_len = self._limit[iwt][1] - self._limit[iwt][0] + 1
     wt_ll = self._skip[iwt] * wt_len + self._limit[iwt][0]
     wt_ul = self._skip[iwt] * wt_len + self._limit[iwt][1]
     if level_ll < 1:
         level_l = 1
     self._table = {}
     self._table['rows'] = []
     self._table['col_heads'] = []  # range(wt_ll,wt_ul+1)
     self._table['row_heads'] = []  # range(level_ll,level_ul+1)
     emf_logger.debug("wt_range: {0} -- {1}".format(wt_ll, wt_ul))
     emf_logger.debug("level_range: {0} -- {1}".format(level_ll, level_ul))
     emf_logger.debug("character: {0}".format(character))
     self._table['characters'] = dict()
     if dimension_table is not None:
         dimension_fun = dimension_table.dimension
         is_data_in_db = dimension_table.is_in_db
     factors = connect_db()['Newform_factors.files']
     list_of_data = factors.distinct('hecke_orbit_label')
     #else:
     #def is_data_in_db(N, k, character):
     #    n = self._files.find({'N':int(N),'k':int(k),'chi':int(character)}).count()
     #    emf_logger.debug("is_Data_in: N,k,character: {0} no. recs: {1} in {2}".format((N,k,character),n,self._files))
     #    return n>0
     # fixed level
     if level_ll == level_ul:
         N = level_ll
         # specific character =0,1
         if character == 0 or character == 1:
             self._table['rowhead'] = 'Weight'
             if character == 0:
                 cchi = 1  #xc = DirichletGroup_conrey(N)[1]
             else:
                 D = DirichletGroup_conrey(N)
                 for xc in D:
                     x = xc.sage_character()
                     if x == kronecker_character_upside_down(N):
                         cchi = xc.number()
                         break
             row = dict()
             row['head'] = "\(\chi_{" + str(N) + "}(" + str(
                 cchi) + ",\cdot) \)"
             row['url'] = url_for('characters.render_Dirichletwebpage',
                                  modulus=N,
                                  number=cchi)
             row['cells'] = list()
             for k in range(wt_ll, wt_ul + 1):
                 if character == 0 and is_odd(k):
                     continue
                 try:
                     if character == 0:
                         d = dimension_fun(N, k)
                     elif character == 1:
                         d = dimension_fun(x, k)
                 except Exception as ex:
                     emf_logger.critical(
                         "Exception: {0}. \n Could not compute the dimension with function {0}"
                         .format(ex, dimension_fun))
                 if (not check_db) or "{0}.{1}.{2}a".format(
                         N, k, cchi
                 ) in list_of_data:  #is_data_in_db(N, k, character):
                     url = url_for('emf.render_elliptic_modular_forms',
                                   level=N,
                                   weight=k,
                                   character=character)
                 else:
                     url = ''
                 if not k in self._table['col_heads']:
                     self._table['col_heads'].append(k)
                 row['cells'].append({'N': N, 'k': k, 'url': url, 'dim': d})
             self._table['rows'].append(row)
         else:
             D = DirichletGroup(N)
             G = D.galois_orbits()
             Greps = [X[0] for X in G]
             Dc = DirichletGroup_conrey(N)
             Gcreps = dict()
             # A security check, if we have at least weight 2 and trivial character,
             # otherwise don't show anything
             #if check_db and not is_data_in_db(N, 2, 0):
             #    emf_logger.debug("No data for level {0} and weight 2, trivial character".format(N)#)
             #self._table = None
             #    return None
             Gc = dict()
             for xi, g in enumerate(G):
                 Gc[xi] = list()
             self._table['maxGalCount'] = 0
             for xc in Dc:
                 x = xc.sage_character()
                 xi = G.index(x.galois_orbit())
                 # emf_logger.debug('Dirichlet Character Conrey {0} = sage_char {1}, has
                 # Galois orbit nr. {2}'.format(xc,x,xi))
                 Gc[xi].append(xc)
                 if x == Greps[xi]:
                     Gcreps[xi] = xc
             emf_logger.debug('Gc={0}'.format(Gc))
             for xi in Gc:
                 g = Gc[xi]
                 if len(g) > self._table['maxGalCount']:
                     self._table['maxGalCount'] = len(g)
                 emf_logger.debug('xi,g={0},{1}'.format(xi, g))
                 x = Greps[xi]
                 xc = Gcreps[xi]
                 cchi = xc.number()
                 row = dict()
                 row['head'] = "\(\chi_{" + str(N) + "}(" + str(
                     cchi) + ",\cdot) \)"
                 row['url'] = url_for('characters.render_Dirichletwebpage',
                                      modulus=N,
                                      number=cchi)
                 row['galois_orbit'] = [{
                     'chi':
                     str(xc.number()),
                     'url':
                     url_for('characters.render_Dirichletwebpage',
                             modulus=N,
                             number=cchi)
                 } for xc in g]
                 row['cells'] = []
                 for k in range(wt_ll, wt_ul + 1):
                     if not k in self._table['col_heads']:
                         # emf_logger.debug("Adding to col_heads:{0}s".format(k))
                         self._table['col_heads'].append(k)
                     try:
                         d = dimension_fun(x, k)
                     except Exception as ex:
                         emf_logger.critical(
                             "Exception: {0} \n Could not compute the dimension with function {1}"
                             .format(ex, dimension_fun))
                     if (not check_db) or "{0}.{1}.{2}a".format(
                             N, k, cchi
                     ) in list_of_data:  #is_data_in_db(N, k, xi):
                         url = url_for('emf.render_elliptic_modular_forms',
                                       level=N,
                                       weight=k,
                                       character=xi)
                     else:
                         url = ''
                     row['cells'].append({
                         'N': N,
                         'k': k,
                         'chi': xi,
                         'url': url,
                         'dim': d
                     })
                 self._table['rows'].append(row)
     else:
         for k in range(wt_ll, wt_ul + 1):
             if character == 0 and is_odd(k):
                 continue
             row = []
             for N in range(level_ll, level_ul + 1):
                 if not N in self._table['col_heads']:
                     self._table['col_heads'].append(N)
                 try:
                     if character == 0:
                         d = dimension_fun(N, k)
                     elif character == 1:
                         x = kronecker_character_upside_down(N)
                         d = dimension_fun(x, k)
                     else:
                         d = dimension_fun(N, k)
                 except Exception as ex:
                     emf_logger.critical(
                         "Exception: {0}. \n Could not compute the dimension with function {0}"
                         .format(ex, dimension_fun))
                 # emf_logger.debug("N,k,char,dim: {0},{1},{2},{3}".format(N,k,character,d))
                 if character == 0 or character == 1:
                     if (not check_db) or "{0}.{1}.{2}a".format(
                             N, k, 1
                     ) in list_of_data:  #is_data_in_db(N, k, character):
                         url = url_for('emf.render_elliptic_modular_forms',
                                       level=N,
                                       weight=k,
                                       character=character)
                     else:
                         url = ''
                 else:
                     t1 = "{0}.{1}.{2}a".format(N, k, 1)
                     t2 = "{0}.{1}.{2}a".format(N, k, 2)
                     if (
                             not check_db
                     ) or t1 in list_of_data or t2 in list_of_data:  # is_data_in_db(N, k, character):
                         url = url_for('emf.render_elliptic_modular_forms',
                                       level=N,
                                       weight=k)
                     else:
                         url = ''
                 if not k in self._table['row_heads']:
                     self._table['row_heads'].append(k)
                 row.append({'N': N, 'k': k, 'url': url, 'dim': d})
             emf_logger.debug("row:{0}".format(row))
             self._table['rows'].append(row)
Esempio n. 50
0
    def update_from_db(self, ignore_non_existent = True, \
                       add_to_fs_query=None, add_to_db_query=None):
        r"""
        Updates the properties of ```self``` from the database using params and dbkey.
        """
        self._has_updated_from_db = False
        self._has_updated_from_fs = False
        if add_to_db_query is None:
            add_to_db_query = self._add_to_db_query
        elif self._add_to_db_query is not None:
            q = add_to_db_query
            add_to_db_query = copy(self._add_to_db_query)
            add_to_db_query.update(q)

        if add_to_fs_query is None:
            add_to_fs_query = self._add_to_fs_query
        elif self._add_to_fs_query is not None:
            q = add_to_fs_query
            add_to_fs_query = copy(self._add_to_fs_query)
            add_to_fs_query.update(q)

        #emf_logger.debug("add_to_fs_query: {0}".format(add_to_fs_query))
        #emf_logger.debug("self._add_to_fs_query: {0}".format(self._add_to_fs_query))
        emf_logger.debug("db_properties: {0}".format(self._db_properties))
        succ_db = False
        succ_fs = False
        if self._use_separate_db or not self._use_gridfs:
            coll = self._collection
            key = self.key_dict()
            if add_to_db_query is not None:
                key.update(add_to_db_query)
            emf_logger.debug("key: {0} for {1}".format(key,
                                                       self._collection_name))
            if coll.find(key).count() > 0:
                props_to_fetch = {}  #p.name:True for p in self._key}
                for p in self._db_properties:
                    if p.include_in_update and (
                            not p.name in self._fs_properties
                            or p._extend_fs_with_db):
                        props_to_fetch[p.name] = True
                        p.has_been_set(False)


#                props_to_fetch = {p.name:True for p in self._db_properties
#                                  if (p.include_in_update and not p.name in self._fs_properties)
#                                  or p.name in self._key}
                emf_logger.debug("props_to_fetch: {0}".format(props_to_fetch))
                rec = coll.find_one(key, projection=props_to_fetch)
                for pn in props_to_fetch:
                    p = self._properties[pn]
                    if rec.has_key(pn):
                        try:
                            p.set_from_db(rec[pn])
                            if not p.name in self._fs_properties:
                                p.has_been_set(True)
                        except NotImplementedError:
                            continue
                succ_db = True
            else:
                emf_logger.critical(
                    "record with key:{0} was not found!".format(key))
                if not ignore_non_existent:
                    raise IndexError("DB record does not exist")
                succ_db = False
        if self._use_gridfs:
            fs = self._files
            file_key = self.file_key_dict()
            if add_to_fs_query is not None:
                file_key.update(add_to_fs_query)
            emf_logger.debug("add_to_fs_query: {0}".format(add_to_fs_query))
            emf_logger.debug("file_key: {0} fs={1}".format(
                file_key, self._file_collection))
            if fs.exists(file_key):
                coll = self._file_collection
                r = coll.find_one(file_key)
                fid = r['_id']
                #emf_logger.debug("col={0}".format(coll))
                #emf_logger.debug("rec={0}".format(coll.find_one(file_key)))
                try:
                    d = loads(fs.get(fid).read())
                except ValueError as e:
                    raise ValueError(
                        "Wrong format in database! : {0} coll: {1} rec:{2}".
                        format(e, coll, r))
                #emf_logger.debug("type(d)={0}".format(type(d)))
                #emf_logger.debug("d.keys()={0}".format(d.keys()))
                for p in self._fs_properties:
                    #emf_logger.debug("p={0}, update:{1}".format(p,p.include_in_update))
                    #emf_logger.debug("d[{0}]={1}".format(p.name,type(d.get(p.name))))
                    if p.include_in_update and d.has_key(p.name):
                        emf_logger.debug("d[{0}]={1}".format(
                            p.name, type(d.get(p.name))))
                        p.has_been_set(False)

                        p.set_from_fs(d[p.name])
                succ_fs = True
            else:
                if not ignore_non_existent:
                    raise IndexError("File does not exist")
                succ_fs = False
            emf_logger.debug("loaded from fs")
        if succ_db: self._has_updated_from_db = True
        if succ_fs: self._has_updated_from_fs = True
Esempio n. 51
0
 def set_table_browsing(self, skip=[0, 0], limit=[(2, 16), (1, 50)], keys=['Weight', 'Level'], character=0, dimension_table=None, dimension_fun=dimension_new_cusp_forms, title='Dimension of newforms', check_db=True):
     r"""
     Table of Holomorphic modular forms spaces.
     Skip tells you how many chunks of data you want to skip (from the geginning) and limit tells you how large each chunk is.
     INPUT:
     - dimension_fun should be a function which gives you the desired dimensions, as functions of level N and weight k
     - character = 0 for trivial character and 1 for Kronecker symbol.
       set to 'all' for all characters.
     - check_db=True means, that we will only link to spaces which are in the database
     """
     self._keys = keys
     self._skip = skip
     self._limit = limit
     self._metadata = []
     self._title = ''
     self._cols = []
     self.table = {}
     self._character = character
     emf_logger.debug("skip= {0}".format(self._skip))
     emf_logger.debug("limit= {0}".format(self._limit))
     il = self._keys.index('Level')
     iwt = self._keys.index('Weight')
     level_len = self._limit[il][1] - self._limit[il][0] + 1
     level_ll = self._skip[il] * level_len + self._limit[il][0]
     level_ul = self._skip[il] * level_len + self._limit[il][1]
     wt_len = self._limit[iwt][1] - self._limit[iwt][0] + 1
     wt_ll = self._skip[iwt] * wt_len + self._limit[iwt][0]
     wt_ul = self._skip[iwt] * wt_len + self._limit[iwt][1]
     if level_ll < 1:
         level_l = 1
     self._table = {}
     self._table['rows'] = []
     self._table['col_heads'] = []  # range(wt_ll,wt_ul+1)
     self._table['row_heads'] = []  # range(level_ll,level_ul+1)
     emf_logger.debug("wt_range: {0} -- {1}".format(wt_ll, wt_ul))
     emf_logger.debug("level_range: {0} -- {1}".format(level_ll, level_ul))
     emf_logger.debug("character: {0}".format(character))
     self._table['characters'] = dict()
     if dimension_table is not None:
         dimension_fun = dimension_table.dimension
         is_data_in_db = dimension_table.is_in_db
     else:
         def is_data_in_db(N, k, character):
             return False
     # fixed level
     if level_ll == level_ul:
         N = level_ll
         # specific character =0,1
         if character == 0 or character == 1:
             self._table['rowhead'] = 'Weight'
             if character == 0:
                 xc = DirichletGroup_conrey(N)[1]
             else:
                 D = DirichletGroup_conrey(N)
                 for xc in D:
                     if xc.sage_character() == kronecker_character_upside_down(N):
                         break
             x = xc.sage_character()
             row = dict()
             row['head'] = "\(\chi_{" + str(N) + "}(" + str(xc.number()) + ",\cdot) \)"
             row['url'] = url_character(type='Dirichlet', modulus=N, number=xc.number())
             row['cells'] = list()
             for k in range(wt_ll, wt_ul + 1):
                 if character == 0 and is_odd(k):
                     continue
                 try:
                     if character == 0:
                         d = dimension_fun(N, k)
                     elif character == 1:
                         d = dimension_fun(x, k)
                 except Exception as ex:
                     emf_logger.critical("Exception: {0}. \n Could not compute the dimension with function {0}".format(ex, dimension_fun))
                 if (not check_db) or is_data_in_db(N, k, character):
                     url = url_for(
                         'emf.render_elliptic_modular_forms', level=N, weight=k, character=character)
                 else:
                     url = ''
                 if not k in self._table['col_heads']:
                     self._table['col_heads'].append(k)
                 row['cells'].append({'N': N, 'k': k, 'url': url, 'dim': d})
             self._table['rows'].append(row)
         else:
             D = DirichletGroup(N)
             G = D.galois_orbits()
             Greps = [X[0] for X in G]
             Dc = DirichletGroup_conrey(N)
             Gcreps = dict()
             # A security check, if we have at least weight 2 and trivial character,
             # otherwise don't show anything
             if check_db and not is_data_in_db(N, 2, 0):
                 emf_logger.debug("No data for level {0} and weight 2, trivial character".format(N))
                 self._table = None
                 return None
             Gc = dict()
             for xi, g in enumerate(G):
                 Gc[xi] = list()
             self._table['maxGalCount'] = 0
             for xc in Dc:
                 x = xc.sage_character()
                 xi = G.index(x.galois_orbit())
                 # emf_logger.debug('Dirichlet Character Conrey {0} = sage_char {1}, has
                 # Galois orbit nr. {2}'.format(xc,x,xi))
                 Gc[xi].append(xc)
                 if x == Greps[xi]:
                     Gcreps[xi] = xc
             emf_logger.debug('Gc={0}'.format(Gc))
             for xi in Gc:
                 g = Gc[xi]
                 if len(g) > self._table['maxGalCount']:
                     self._table['maxGalCount'] = len(g)
                 emf_logger.debug('xi,g={0},{1}'.format(xi, g))
                 x = Greps[xi]
                 xc = Gcreps[xi]
                 row = dict()
                 row['head'] = "\(\chi_{" + str(N) + "}(" + str(xc.number()) + ",\cdot) \)"
                 row['url'] = url_character(type='Dirichlet', modulus=N, number=xc.number())
                 row['galois_orbit'] = [
                     {'chi': str(xc.number()),
                      'url': url_character(type='Dirichlet', modulus=N, number=xc.number()) }
                     for xc in g]
                 row['cells'] = []
                 for k in range(wt_ll, wt_ul + 1):
                     if not k in self._table['col_heads']:
                         # emf_logger.debug("Adding to col_heads:{0}s".format(k))
                         self._table['col_heads'].append(k)
                     try:
                         d = dimension_fun(x, k)
                     except Exception as ex:
                         emf_logger.critical("Exception: {0} \n Could not compute the dimension with function {1}".format(ex, dimension_fun))
                     if (not check_db) or is_data_in_db(N, k, xi):
                         url = url_for(
                             'emf.render_elliptic_modular_forms', level=N, weight=k, character=xi)
                     else:
                         url = ''
                     row['cells'].append({'N': N, 'k': k, 'chi': xi, 'url': url, 'dim': d})
                 self._table['rows'].append(row)
     else:
         for k in range(wt_ll, wt_ul + 1):
             if character == 0 and is_odd(k):
                     continue
             row = []
             for N in range(level_ll, level_ul + 1):
                 if not N in self._table['col_heads']:
                     self._table['col_heads'].append(N)
                 try:
                     if character == 0:
                         d = dimension_fun(N, k)
                     elif character == 1:
                         x = kronecker_character_upside_down(N)
                         d = dimension_fun(x, k)
                     else:
                         d = dimension_fun(N, k)
                 except Exception as ex:
                     emf_logger.critical("Exception: {0}. \n Could not compute the dimension with function {0}".format(ex, dimension_fun))
                 # emf_logger.debug("N,k,char,dim: {0},{1},{2},{3}".format(N,k,character,d))
                 if character == 0 or character == 1:
                     if (not check_db) or is_data_in_db(N, k, character):
                         url = url_for(
                             'emf.render_elliptic_modular_forms', level=N, weight=k, character=character)
                     else:
                         url = ''
                 else:
                     url = url_for('emf.render_elliptic_modular_forms', level=N, weight=k)
                 if not k in self._table['row_heads']:
                     self._table['row_heads'].append(k)
                 row.append({'N': N, 'k': k, 'url': url, 'dim': d})
             self._table['rows'].append(row)
def set_info_for_gamma1(level,weight,weight2=None):
    dimension_table_name = WebModFormSpace._dimension_table_name
    if weight != None and weight2>weight:
        w1 = weight; w2 = weight2
    else:
        w1 = weight; w2 = weight
    table = {'galois_orbit':{},'galois_orbits_reps':{},'cells':{}}
    table['weights']=range(w1,w2+1)
    emf_logger.debug("dimension table name={0}".format(dimension_table_name))
    db_dim = getDBConnection()['modularforms2'][dimension_table_name]
    s = {'level':int(level),'weight':{"$lt":int(w2+1),"$gt":int(w1-1)},'cchi':{"$exists":True}}
    q = db_dim.find(s).sort([('cchi',int(1)),('weight',int(1))])
    if q.count() == 0:
        emf_logger.debug("No spaces in the database!")
        flash('The database does not currently contain any spaces matching these parameters. Please try again!')
        return None #'error':'The database does not currently contain any spaces matching these parameters!'}
    else:
        table['maxGalCount']=1
        for r in q:
            xi = r['cchi']
            orbit = r['character_orbit']
            k = r['weight']
            ## This is probably still quicker if it is in the database
            parity = r.get('character_parity','n/a')
            if parity == 'n/a':
                chi = ConreyCharacter(level,xi)
                if chi.is_odd():
                    parity = -1
                elif chi.is_even():
                    parity = 1
                else:
                    emf_logger.critical("Could not determine the parity of ConreyCharacter({0},{1})".format(xi,level))
                    trivial_trivially = ""
            if parity != 'n/a':
                if k % 2 == (1 + parity)/2:   # is space empty because of parity?
                    trivial_trivially = "yes"
                else:
                    trivial_trivially = ""
            if parity == 1:
                parity = 'even'
            elif parity == -1:
                parity = 'odd'
            d = r.get('d_newf',"n/a")
            indb = r.get('in_wdb',0)
            if d == 0:
                indb = 1
            if indb:
                url = url_for('emf.render_elliptic_modular_forms', level=level, weight=k, character=xi)
            else:
                url = ''
            if not table['galois_orbits_reps'].has_key(xi):
                table['galois_orbits_reps'][xi]={
                    'head' : "\(\chi_{{{0}}}({1},\cdot) \)".format(level,xi),  # yes, {{{ is required
                    'chi': "{0}".format(xi),
                    'url': url_for('characters.render_Dirichletwebpage', modulus=level, number=xi),
                    'parity':parity}
                table['galois_orbit'][xi]= [
                    {
                    #'head' : "\(\chi_{{{0}}}({1},\cdot) \)".format(level,xci),  # yes, {{{ is required
               ##     'head' : "\(S_{{{0}}}({1},\chi({2}, \cdot) ) \)".format(weight,level,xci),  # yes, {{{ is required
                ##    'head' : "\(S_{{{0}}}(\chi({1}, \cdot) ) \)".format(weight,xci),  # yes, {{{ is required
                    'head' : r"\(S_{{{0}}}(\chi_{{{1}}}({2}, \cdot)) \)".format(weight,level,xci),  # yes, {{{ is required
                    # 'head' : "\({0}\)".format(xci),
                     'chi': "{0}".format(xci),
                 #    'url': url_for('characters.render_Dirichletwebpage', modulus=level, number=xci)
                     'url': url_for('emf.render_elliptic_modular_forms', level=level, weight=k, character=xci) if indb else ''
                    }
                    for xci in orbit]
            if len(orbit)>table['maxGalCount']:
                table['maxGalCount']=len(orbit)
            table['cells'][xi]={}
            table['cells'][xi][k] ={'N': level, 'k': k, 'chi': xi, 'url': url, 'dim': d, 'trivial_trivially': trivial_trivially,}
    table['galois_orbits_reps_numbers']=table['galois_orbits_reps'].keys()
    table['galois_orbits_reps_numbers'].sort()
    #emf_logger.debug("Table:{0}".format(table))
    return table
def set_info_for_gamma1(level, weight, weight2=None):
    from lmfdb.modular_forms.elliptic_modular_forms.backend.emf_utils import (
        dimension_from_db,
        dirichlet_character_conrey_galois_orbits_reps,
        conrey_character_from_number,
    )

    from sage.all import DirichletGroup, dimension_new_cusp_forms
    from dirichlet_conrey import DirichletGroup_conrey
    from lmfdb.modular_forms.elliptic_modular_forms import WebModFormSpace

    dimension_table_name = WebModFormSpace._dimension_table_name
    dim_table = dimension_from_db(level, weight, chi="all", group="gamma1")
    if weight != None and weight2 > weight:
        w1 = weight
        w2 = weight2
    else:
        w1 = weight
        w2 = weight
    table = {"galois_orbit": {}, "galois_orbits_reps": {}, "cells": {}}
    table["weights"] = range(w1, w2 + 1)
    max_gal_count = 0
    from lmfdb.base import getDBConnection

    emf_logger.debug("dimension table name={0}".format(dimension_table_name))
    db_dim = getDBConnection()["modularforms2"][dimension_table_name]
    s = {"level": int(level), "weight": {"$lt": int(w2 + 1), "$gt": int(w1 - 1)}, "cchi": {"$exists": True}}
    q = db_dim.find(s).sort([("cchi", int(1)), ("weight", int(1))])
    if q.count() == 0:
        emf_logger.debug("No spaces in the database!")
        flash("The database does not currently contain any spaces matching these parameters. Please try again!")
        return None  #'error':'The database does not currently contain any spaces matching these parameters!'}
    else:
        table["maxGalCount"] = 1
        for r in q:
            xi = r["cchi"]
            orbit = r["character_orbit"]
            k = r["weight"]
            ## This is probably still quicker if it is in the database
            parity = r.get("character_parity", "n/a")
            if parity == "n/a":
                chi = ConreyCharacter(level, xi)
                if chi.is_odd():
                    parity = -1
                elif chi.is_even():
                    parity = 1
                else:
                    emf_logger.critical("Could not determine the parity of ConreyCharacter({0},{1})".format(xi, level))
                    trivial_trivially = ""
            if parity != "n/a":
                if k % 2 == (1 + parity) / 2:  # is space empty because of parity?
                    trivial_trivially = "yes"
                else:
                    trivial_trivially = ""
            if parity == 1:
                parity = "even"
            elif parity == -1:
                parity = "odd"
            d = r.get("d_newf", "n/a")
            indb = r.get("in_wdb", 0)
            if d == 0:
                indb = 1
            if indb:
                url = url_for("emf.render_elliptic_modular_forms", level=level, weight=k, character=xi)
            else:
                url = ""
            if not table["galois_orbits_reps"].has_key(xi):
                table["galois_orbits_reps"][xi] = {
                    "head": "\(\chi_{{{0}}}({1},\cdot) \)".format(level, xi),  # yes, {{{ is required
                    "chi": "{0}".format(xi),
                    "url": url_for("characters.render_Dirichletwebpage", modulus=level, number=xi),
                    "parity": parity,
                }
                table["galois_orbit"][xi] = [
                    {
                        #'head' : "\(\chi_{{{0}}}({1},\cdot) \)".format(level,xci),  # yes, {{{ is required
                        ##     'head' : "\(S_{{{0}}}({1},\chi({2}, \cdot) ) \)".format(weight,level,xci),  # yes, {{{ is required
                        ##    'head' : "\(S_{{{0}}}(\chi({1}, \cdot) ) \)".format(weight,xci),  # yes, {{{ is required
                        "head": r"\(S_{{{0}}}(\chi_{{{1}}}({2}, \cdot)) \)".format(
                            weight, level, xci
                        ),  # yes, {{{ is required
                        # 'head' : "\({0}\)".format(xci),
                        "chi": "{0}".format(xci),
                        #    'url': url_for('characters.render_Dirichletwebpage', modulus=level, number=xci)
                        "url": url_for("emf.render_elliptic_modular_forms", level=level, weight=k, character=xci)
                        if indb
                        else "",
                    }
                    for xci in orbit
                ]
            if len(orbit) > table["maxGalCount"]:
                table["maxGalCount"] = len(orbit)
            table["cells"][xi] = {}
            table["cells"][xi][k] = {
                "N": level,
                "k": k,
                "chi": xi,
                "url": url,
                "dim": d,
                "trivial_trivially": trivial_trivially,
            }
    table["galois_orbits_reps_numbers"] = table["galois_orbits_reps"].keys()
    table["galois_orbits_reps_numbers"].sort()
    # emf_logger.debug("Table:{0}".format(table))
    return table
Esempio n. 54
0
    def update_from_db(self, ignore_non_existent = True, \
                       add_to_fs_query=None, add_to_db_query=None):
        r"""
        Updates the properties of ```self``` from the database using params and dbkey.
        """
        self._has_updated_from_db = False
        self._has_updated_from_fs = False
        if add_to_db_query is None:
            add_to_db_query = self._add_to_db_query
        elif self._add_to_db_query is not None:
            q=add_to_db_query
            add_to_db_query = copy(self._add_to_db_query)
            add_to_db_query.update(q)

        if add_to_fs_query is None:
            add_to_fs_query = self._add_to_fs_query
        elif self._add_to_fs_query is not None:
            q=add_to_fs_query
            add_to_fs_query = copy(self._add_to_fs_query)
            add_to_fs_query.update(q)
            
        #emf_logger.debug("add_to_fs_query: {0}".format(add_to_fs_query))
        #emf_logger.debug("self._add_to_fs_query: {0}".format(self._add_to_fs_query))
        emf_logger.debug("db_properties: {0}".format(self._db_properties))
        succ_db = False
        succ_fs = False
        if self._use_separate_db or not self._use_gridfs:
            coll = self._collection
            key = self.key_dict()
            if add_to_db_query is not None:
                key.update(add_to_db_query)
            emf_logger.debug("key: {0} for {1}".format(key,self._collection_name))
            if coll.find(key).count()>0:
                props_to_fetch = { }  #p.name:True for p in self._key}
                for p in self._db_properties:
                    if p.include_in_update and (not p.name in self._fs_properties or p._extend_fs_with_db):
                        props_to_fetch[p.name] = True
                        p.has_been_set(False)
#                props_to_fetch = {p.name:True for p in self._db_properties
#                                  if (p.include_in_update and not p.name in self._fs_properties)
#                                  or p.name in self._key}
                emf_logger.debug("props_to_fetch: {0}".format(props_to_fetch))                
                rec = coll.find_one(key, projection = props_to_fetch)
                for pn in props_to_fetch:
                    p = self._properties[pn]
                    if rec.has_key(pn):
                        try:
                            p.set_from_db(rec[pn])
                            if not p.name in self._fs_properties:
                                p.has_been_set(True)
                        except NotImplementedError:
                            continue
                succ_db = True
            else:
                emf_logger.critical("record with key:{0} was not found!".format(key))
                if not ignore_non_existent:
                    raise IndexError("DB record does not exist")
                succ_db = False
        if self._use_gridfs:
            fs = self._files
            file_key = self.file_key_dict()
            if add_to_fs_query is not None:
                file_key.update(add_to_fs_query)
            emf_logger.debug("add_to_fs_query: {0}".format(add_to_fs_query))
            emf_logger.debug("file_key: {0}".format(file_key))
            if fs.exists(file_key):
                coll = self._file_collection
                fid = coll.find_one(file_key)['_id']
                #emf_logger.debug("col={0}".format(coll))
                #emf_logger.debug("rec={0}".format(coll.find_one(file_key)))
                try: 
                    d = loads(fs.get(fid).read())
                except ValueError as e:
                    raise ValueError("Wrong format in database! : {0}".format(e))
                #emf_logger.debug("type(d)={0}".format(type(d)))                                
                #emf_logger.debug("d.keys()={0}".format(d.keys()))                
                for p in self._fs_properties:
                    #emf_logger.debug("p={0}, update:{1}".format(p,p.include_in_update))
                    #emf_logger.debug("d[{0}]={1}".format(p.name,type(d.get(p.name))))
                    if p.include_in_update and d.has_key(p.name):
                        p.has_been_set(False)
                        p.set_from_fs(d[p.name])
                succ_fs = True
            else:
                if not ignore_non_existent:
                    raise IndexError("File does not exist")
                succ_fs = False
        if succ_db: self._has_updated_from_db = True
        if succ_fs: self._has_updated_from_fs = True
Esempio n. 55
0
def set_info_for_web_newform(level=None,
                             weight=None,
                             character=None,
                             label=None,
                             **kwds):
    r"""
    Set the info for on modular form.

    """
    info = to_dict(kwds)
    info['level'] = level
    info['weight'] = weight
    info['character'] = character
    info['label'] = label
    if level is None or weight is None or character is None or label is None:
        s = "In set info for one form but do not have enough args!"
        s += "level={0},weight={1},character={2},label={3}".format(
            level, weight, character, label)
        emf_logger.critical(s)
    emf_logger.debug("In set_info_for_one_mf: info={0}".format(info))
    prec = my_get(info, 'prec', default_prec, int)
    bprec = my_get(info, 'bprec', default_display_bprec, int)
    emf_logger.debug("PREC: {0}".format(prec))
    emf_logger.debug("BITPREC: {0}".format(bprec))
    try:
        WNF = WebNewForm_cached(level=level,
                                weight=weight,
                                character=character,
                                label=label)
        if not WNF.has_updated():
            raise IndexError(
                "Unfortunately, we do not have this newform in the database.")
        info['character_order'] = WNF.character.order
        info['code'] = WNF.code
        emf_logger.debug("defined webnewform for rendering!")
    except IndexError as e:
        info['error'] = e.message
    url0 = url_for("mf.modular_form_main_page")
    url1 = url_for("emf.render_elliptic_modular_forms")
    url2 = url_for("emf.render_elliptic_modular_forms", level=level)
    url3 = url_for("emf.render_elliptic_modular_forms",
                   level=level,
                   weight=weight)
    url4 = url_for("emf.render_elliptic_modular_forms",
                   level=level,
                   weight=weight,
                   character=character)
    bread = [(MF_TOP, url0), (EMF_TOP, url1)]
    bread.append(("Level %s" % level, url2))
    bread.append(("Weight %s" % weight, url3))
    bread.append(("Character \( %s \)" % (WNF.character.latex_name), url4))
    bread.append(
        ("Newform %d.%d.%d.%s" % (level, weight, int(character), label), ''))
    info['bread'] = bread

    properties2 = list()
    friends = list()
    space_url = url_for('emf.render_elliptic_modular_forms',
                        level=level,
                        weight=weight,
                        character=character)
    friends.append(
        ('\( S_{%s}(%s, %s)\)' %
         (WNF.weight, WNF.level, WNF.character.latex_name), space_url))
    if hasattr(WNF.base_ring, "lmfdb_url") and WNF.base_ring.lmfdb_url:
        friends.append(('Number field ' + WNF.base_ring.lmfdb_pretty,
                        WNF.base_ring.lmfdb_url))
    if hasattr(WNF.coefficient_field,
               "lmfdb_url") and WNF.coefficient_field.lmfdb_label:
        friends.append(('Number field ' + WNF.coefficient_field.lmfdb_pretty,
                        WNF.coefficient_field.lmfdb_url))
    friends = uniq(friends)
    friends.append(("Dirichlet character \(" + WNF.character.latex_name + "\)",
                    WNF.character.url()))

    if WNF.dimension == 0 and not info.has_key('error'):
        info['error'] = "This space is empty!"
    info['title'] = 'Newform ' + WNF.hecke_orbit_label
    info['learnmore'] = [('History of modular forms',
                          url_for('.holomorphic_mf_history'))]
    if 'error' in info:
        return info
    ## Until we have figured out how to do the embeddings correctly we don't display the Satake
    ## parameters for non-trivial characters....

    ## Example to illustrate the different cases
    ## base              = CyclotomicField(n) -- of degree phi(n)
    ## coefficient_field = NumberField( p(x)) for some p in base['x'] of degree m
    ##   we would then have cdeg = m*phi(n) and bdeg = phi(n)
    ##   and rdeg = m
    ## Unfortunately, for e.g. base = coefficient_field = CyclotomicField(6)
    ## we get coefficient_field.relative_degree() == 2 although it should be 1
    cdeg = WNF.coefficient_field.absolute_degree()
    bdeg = WNF.base_ring.absolute_degree()
    if cdeg == 1:
        rdeg = 1
    else:
        ## just setting rdeg = WNF.coefficient_field.relative_degree() does not give correct result...
        ##
        rdeg = QQ(cdeg) / QQ(bdeg)
    cf_is_QQ = (cdeg == 1)
    br_is_QQ = (bdeg == 1)
    if cf_is_QQ:
        info['satake'] = WNF.satake
    if WNF.complexity_of_first_nonvanishing_coefficients(
    ) > default_max_height:
        info['qexp'] = ""
        info['qexp_display'] = ''
        info['hide_qexp'] = True
        n, c = WNF.first_nonvanishing_coefficient()
        info['trace_nv'] = latex(WNF.first_nonvanishing_coefficient_trace())
        info['norm_nv'] = '\\approx ' + latex(
            WNF.first_nonvanishing_coefficient_norm().n())
        info['index_nv'] = n
    else:
        if WNF.prec < prec:
            #get WNF record at larger prec
            WNF.prec = prec
            WNF.update_from_db()
        info['qexp'] = WNF.q_expansion_latex(prec=10, name='\\alpha ')
        info['qexp_display'] = url_for(".get_qexp_latex",
                                       level=level,
                                       weight=weight,
                                       character=character,
                                       label=label)
        info["hide_qexp"] = False
    info['max_cn_qexp'] = WNF.q_expansion.prec()
    ## All combinations should be tested...
    ## 13/4/4/a -> base ring = coefficient_field = QQ(zeta_6)
    ## 13/3/8/a ->  base_ring = QQ(zeta_4), coefficient_field has poly x^2+(2\zeta_4+2x-3\zeta_$ over base_ring
    ## 13/4/3/a ->  base_ring = coefficient_field = QQ(zeta_3)
    ## 13/4/1/a -> all rational
    ## 13/6/1/a/ -> base_ring = QQ, coefficient_field = Q(sqrt(17))
    ## These are variables which needs to be set properly below
    info['polvars'] = {'base_ring': 'x', 'coefficient_field': '\\alpha'}
    if not cf_is_QQ:
        if rdeg > 1:  # not WNF.coefficient_field == WNF.base_ring:
            ## Here WNF.base_ring should be some cyclotomic field and we have an extension over this.
            p1 = WNF.coefficient_field.relative_polynomial()
            c_pol_ltx = web_latex_poly(p1,
                                       '\\alpha')  # make the variable \alpha
            c_pol_ltx_x = web_latex_poly(p1, 'x')
            zeta = p1.base_ring().gens()[0]
            #           p2 = zeta.minpoly() #this is not used anymore
            #           b_pol_ltx = web_latex_poly(p2, latex(zeta)) #this is not used anymore
            z1 = zeta.multiplicative_order()
            info['coeff_field'] = [
                WNF.coefficient_field.absolute_polynomial_latex('x'),
                c_pol_ltx_x, z1
            ]
            if hasattr(WNF.coefficient_field,
                       "lmfdb_url") and WNF.coefficient_field.lmfdb_url:
                info['coeff_field_pretty'] = [
                    WNF.coefficient_field.lmfdb_url,
                    WNF.coefficient_field.lmfdb_pretty,
                    WNF.coefficient_field.lmfdb_label
                ]
            if z1 == 4:
                info[
                    'polynomial_st'] = '<div class="where">where</div> {0}\(\mathstrut=0\) and \(\zeta_4=i\).</div><br/>'.format(
                        c_pol_ltx)
                info['polvars']['base_ring'] = 'i'
            elif z1 <= 2:
                info[
                    'polynomial_st'] = '<div class="where">where</div> {0}\(\mathstrut=0\).</div><br/>'.format(
                        c_pol_ltx)
            else:
                info[
                    'polynomial_st'] = '<div class="where">where</div> %s\(\mathstrut=0\) and \(\zeta_{%s}=e^{\\frac{2\\pi i}{%s}}\) ' % (
                        c_pol_ltx, z1, z1)
                info['polvars']['base_ring'] = '\zeta_{{ {0} }}'.format(z1)
                if z1 == 3:
                    info[
                        'polynomial_st'] += 'is a primitive cube root of unity.'
                else:
                    info[
                        'polynomial_st'] += 'is a primitive {0}-th root of unity.'.format(
                            z1)
        elif not br_is_QQ:
            ## Now we have base and coefficient field being equal, meaning that since the coefficient field is not QQ it is some cyclotomic field
            ## generated by some \zeta_n
            p1 = WNF.coefficient_field.absolute_polynomial()
            z1 = WNF.coefficient_field.gens()[0].multiplicative_order()
            c_pol_ltx = web_latex_poly(p1, '\\zeta_{{{0}}}'.format(z1))
            c_pol_ltx_x = web_latex_poly(p1, 'x')
            info['coeff_field'] = [
                WNF.coefficient_field.absolute_polynomial_latex('x'),
                c_pol_ltx_x
            ]
            if hasattr(WNF.coefficient_field,
                       "lmfdb_url") and WNF.coefficient_field.lmfdb_url:
                info['coeff_field_pretty'] = [
                    WNF.coefficient_field.lmfdb_url,
                    WNF.coefficient_field.lmfdb_pretty,
                    WNF.coefficient_field.lmfdb_label
                ]
            if z1 == 4:
                info[
                    'polynomial_st'] = '<div class="where">where \(\zeta_4=e^{{\\frac{{\\pi i}}{{ 2 }} }}=i \).</div>'.format(
                        c_pol_ltx)
                info['polvars']['coefficient_field'] = 'i'
            elif z1 <= 2:
                info['polynomial_st'] = ''
            else:
                info[
                    'polynomial_st'] = '<div class="where">where \(\zeta_{{{0}}}=e^{{\\frac{{2\\pi i}}{{ {0} }} }}\) '.format(
                        z1)
                info['polvars']['coefficient_field'] = '\zeta_{{{0}}}'.format(
                    z1)
                if z1 == 3:
                    info[
                        'polynomial_st'] += 'is a primitive cube root of unity.</div>'
                else:
                    info[
                        'polynomial_st'] += 'is a primitive {0}-th root of unity.</div>'.format(
                            z1)
    else:
        info['polynomial_st'] = ''
    if info["hide_qexp"]:
        info['polynomial_st'] = ''
    info['degree'] = int(cdeg)
    if cdeg == 1:
        info['is_rational'] = 1
        info['coeff_field_pretty'] = [
            WNF.coefficient_field.lmfdb_url, WNF.coefficient_field.lmfdb_pretty
        ]
    else:
        info['is_rational'] = 0
    emf_logger.debug("PREC2: {0}".format(prec))
    info['embeddings'] = WNF._embeddings[
        'values']  #q_expansion_embeddings(prec, bprec,format='latex')
    info['embeddings_len'] = len(info['embeddings'])
    properties2 = [('Level', str(level)), ('Weight', str(weight)),
                   ('Character', '$' + WNF.character.latex_name + '$'),
                   ('Label', WNF.hecke_orbit_label),
                   ('Dimension of Galois orbit', str(WNF.dimension))]
    if (ZZ(level)).is_squarefree():
        info['twist_info'] = WNF.twist_info
        if isinstance(info['twist_info'],
                      list) and len(info['twist_info']) > 0:
            info['is_minimal'] = info['twist_info'][0]
            if (info['twist_info'][0]):
                s = 'Is minimal<br>'
            else:
                s = 'Is a twist of lower level<br>'
            properties2 += [('Twist info', s)]
    else:
        info['twist_info'] = 'Twist info currently not available.'
        properties2 += [('Twist info', 'not available')]
    args = list()
    for x in range(5, 200, 10):
        args.append({'digits': x})
    alev = None
    CM = WNF._cm_values
    if CM is not None:
        if CM.has_key('tau') and len(CM['tau']) != 0:
            info['CM_values'] = CM
    info['is_cm'] = WNF.is_cm
    if WNF.is_cm == 1:
        info['cm_field'] = "2.0.{0}.1".format(-WNF.cm_disc)
        info['cm_disc'] = WNF.cm_disc
        info['cm_field_knowl'] = nf_display_knowl(
            info['cm_field'], getDBConnection(),
            field_pretty(info['cm_field']))
        info['cm_field_url'] = url_for("number_fields.by_label",
                                       label=info["cm_field"])
    if WNF.is_cm is None or WNF.is_cm == -1:
        s = '- Unknown (insufficient data)<br>'
    elif WNF.is_cm == 1:
        s = 'Yes<br>'
    else:
        s = 'No<br>'
    properties2.append(('CM', s))
    alev = WNF.atkin_lehner_eigenvalues()
    info['atkinlehner'] = None
    if isinstance(alev, dict) and len(alev.keys()) > 0 and level != 1:
        s1 = " Atkin-Lehner eigenvalues "
        s2 = ""
        for Q in alev.keys():
            s2 += "\( \omega_{ %s } \) : %s <br>" % (Q, alev[Q])
        properties2.append((s1, s2))
        emf_logger.debug("properties={0}".format(properties2))
        # alev = WNF.atkin_lehner_eigenvalues_for_all_cusps()
        # if isinstance(alev,dict) and len(alev.keys())>0:
        #     emf_logger.debug("alev={0}".format(alev))
        #     info['atkinlehner'] = list()
        #     for Q in alev.keys():
        #         s = "\(" + latex(c) + "\)"
        #         Q = alev[c][0]
        #         ev = alev[c][1]
        #         info['atkinlehner'].append([Q, c, ev])
    if (level == 1):
        poly = WNF.explicit_formulas.get('as_polynomial_in_E4_and_E6', '')
        if poly != '':
            d, monom, coeffs = poly
            emf_logger.critical("poly={0}".format(poly))
            info['explicit_formulas'] = '\('
            for i in range(len(coeffs)):
                c = QQ(coeffs[i])
                s = ""
                if d > 1 and i > 0 and c > 0:
                    s = "+"
                if c < 0:
                    s = "-"
                if c.denominator() > 1:
                    cc = "\\frac{{ {0} }}{{ {1} }}".format(
                        abs(c.numerator()), c.denominator())
                else:
                    cc = str(abs(c))
                s += "{0} \cdot ".format(cc)
                a = monom[i][0]
                b = monom[i][1]
                if a == 1:
                    a = ""
                if b == 1:
                    b = ""
                if a == 0 and b != 0:
                    s += "E_6^{{ {0} }}(z)".format(b)
                elif b == 0 and a != 0:
                    s += "E_4^{{ {0} }}(z)".format(a)
                else:
                    s += "E_4^{{ {0} }}(z) \cdot E_6^{{ {1} }}(z)".format(a, b)
                info['explicit_formulas'] += s
            info['explicit_formulas'] += " \)"
    # cur_url = '?&level=' + str(level) + '&weight=' + str(weight) + '&character=' + str(character) + '&label=' + str(label) # never used
    if len(WNF.parent.hecke_orbits) > 1:
        for label_other in WNF.parent.hecke_orbits.keys():
            if (label_other != label):
                s = 'Modular form '
                if character:
                    s += newform_label(level, weight, character, label_other)
                else:
                    s += newform_label(level, weight, 1, label_other)

                url = url_for('emf.render_elliptic_modular_forms',
                              level=level,
                              weight=weight,
                              character=character,
                              label=label_other)
                friends.append((s, url))

    s = 'L-Function '
    if character:
        s += newform_label(level, weight, character, label)
    else:
        s += newform_label(level, weight, 1, label)
    # url =
    # "/L/ModularForm/GL2/Q/holomorphic?level=%s&weight=%s&character=%s&label=%s&number=%s"
    # %(level,weight,character,label,0)
    url = '/L' + url_for('emf.render_elliptic_modular_forms',
                         level=level,
                         weight=weight,
                         character=character,
                         label=label)
    if WNF.coefficient_field_degree > 1:
        for h in range(WNF.coefficient_field_degree):
            s0 = s + ".{0}".format(h)
            url0 = url + "{0}/".format(h)
            friends.append((s0, url0))
    else:
        friends.append((s, url))
    # if there is an elliptic curve over Q associated to self we also list that
    if WNF.weight == 2 and WNF.coefficient_field_degree == 1:
        llabel = str(level) + '.' + label
        s = 'Elliptic curve isogeny class ' + llabel
        url = '/EllipticCurve/Q/' + llabel
        friends.append((s, url))
    info['properties2'] = properties2
    info['friends'] = friends
    info['max_cn'] = WNF.max_available_prec()
    return info
def set_info_for_modular_form_space(level=None,
                                    weight=None,
                                    character=None,
                                    label=None,
                                    **kwds):
    r"""
    Set information about a space of modular forms.
    """
    info = dict()
    info['level'] = level
    info['weight'] = weight
    info['character'] = character
    emf_logger.debug("info={0}".format(info))
    if (level > N_max_db or weight > k_max_db):
        info['error'] = "Currently not available"
    WMFS = None
    if level <= 0:
        info['error'] = "Got wrong level: %s " % level
        return info
    try:
        if use_db:
            WMFS = WebModFormSpace(weight, level, character, use_db=True)
        else:
            WMFS = WebModFormSpace(weight, level, character)
        if 'download' in info and 'tempfile' in info:
            WNF._save_to_file(info['tempfile'])
            info['filename'] = str(weight) + '-' + str(level) + '-' + str(
                character) + '-' + label + '.sobj'
            return info
    except RuntimeError:
        info['error'] = "Sage error: Could not construct the desired space!"
    if WMFS.level() == 1:
        info['group'] = "\( \mathrm{SL}_{2}(\mathbb{Z})\)"
    else:
        info['group'] = "\( \Gamma_{{0}}( {0} ) \)".format(WMFS.level())
    if character == 0:
        info['name_new'] = "\(S_{ %s }^{new}(%s) \)" % (WMFS.weight(),
                                                        WMFS.level())
        info['name_old'] = "\(S_{ %s }^{old}(%s) \)" % (WMFS.weight(),
                                                        WMFS.level())
    else:
        conrey_char = WMFS.conrey_character()
        conrey_char_name = WMFS.conrey_character_name()
        info['conrey_character_name'] = '\( ' + conrey_char_name + '\)'
        info['character_url'] = url_character(type='Dirichlet',
                                              modulus=WMFS.level(),
                                              number=conrey_char.number())
        info['name_new'] = "\(S_{ %s }^{new}(%s,%s) \)" % (
            WMFS.weight(), WMFS.level(), conrey_char_name)
        info['name_old'] = "\(S_{ %s }^{old}(%s,%s) \)" % (
            WMFS.weight(), WMFS.level(), conrey_char_name)
    info['dimension_cusp_forms'] = WMFS.dimension_cusp_forms()
    info['dimension_mod_forms'] = WMFS.dimension_modular_forms()
    info['dimension_new_cusp_forms'] = WMFS.dimension_new_cusp_forms()
    info['dimension_newspace'] = WMFS.dimension_newspace()
    info['dimension_oldspace'] = WMFS.dimension_oldspace()
    info['dimension'] = WMFS.dimension()
    info['galois_orbits'] = WMFS.get_all_galois_orbit_info()
    lifts = list()
    if WMFS.dimension() == 0:  # we don't need to work with an empty space
        info['sturm_bound'] = 0
        info['new_decomposition'] = ''
        info['is_empty'] = 1
        lifts.append(('Half-Integral Weight Forms', '/ModularForm/Mp2/Q'))
        lifts.append(('Siegel Modular Forms', '/ModularForm/GSp4/Q'))
        info['lifts'] = lifts
        return info
    info['sturm_bound'] = WMFS.sturm_bound()
    info['new_decomposition'] = WMFS.print_galois_orbits()
    emf_logger.debug("new_decomp={0}".format(info['new_decomposition']))
    info['nontrivial_new'] = len(info['new_decomposition'])
    ## we try to catch well-known bugs...
    info['old_decomposition'] = "n/a"
    if level < N_max_comp:
        try:
            O = WMFS.print_oldspace_decomposition()
            info['old_decomposition'] = O
        except:
            emf_logger.critical("Error in computing oldspace decomposition")
            O = []
            info['old_decomposition'] = "n/a"
            (A, B, C) = sys.exc_info()
            # build an error message...
            errtype = A.__name__
            errmsg = B
            s = "%s: %s  at:" % (errtype, errmsg)
            next = C.tb_next
            while (next):
                ln = next.tb_lineno
                filen = next.tb_frame.f_code.co_filename
                s += "\n line no. %s in file %s" % (ln, filen)
                next = next.tb_next
                info['error_note'] = "Could not construct oldspace!\n" + s
    # properties for the sidebar
    prop = []
    if WMFS._cuspidal == 1:
        prop = [('Dimension newforms', [info['dimension_newspace']])]
        prop.append(('Dimension oldforms', [info['dimension_oldspace']]))
    else:
        prop = [('Dimension modular forms', [info['dimension_mod_forms']])]
        prop.append(('Dimension cusp forms', [info['dimension_cusp_forms']]))
    prop.append(('Sturm bound', [WMFS.sturm_bound()]))
    info['properties2'] = prop
    ## Make parent spaces of S_k(N,chi) for the sidebar
    par_lbl = '\( S_{*} (\Gamma_0(' + str(level) + '),\cdot )\)'
    par_url = '?level=' + str(level)
    parents = [[par_lbl, par_url]]
    par_lbl = '\( S_{k} (\Gamma_0(' + str(level) + '),\cdot )\)'
    par_url = '?level=' + str(level) + '&weight=' + str(weight)
    parents.append((par_lbl, par_url))
    info['parents'] = parents
    if 'character' in info:
        info['character_order'] = WMFS.character_order()
        info['character_conductor'] = WMFS.character_conductor()
    friends = list()
    lifts = list()
    if (('label' not in info) and info['old_decomposition'] != 'n/a'):
        O = WMFS.oldspace_decomposition()
        try:
            for (old_level, chi, mult, d) in O:
                if chi != 0:
                    s = "\(S_{%s}(\Gamma_0(%s),\chi_{%s}) \) " % (
                        weight, old_level, chi)
                    friends.append((s, '?weight=' + str(weight) + '&level=' +
                                    str(old_level) + '&character=' + str(chi)))
                else:
                    s = "\(S_{%s}(\Gamma_0(%s)) \) " % (weight, old_level)
                    friends.append((s, '?weight=' + str(weight) + '&level=' +
                                    str(old_level) + '&character=' + str(0)))
        except:
            pass
    info['friends'] = friends
    lifts.append(('Half-Integral Weight Forms', '/ModularForm/Mp2/Q'))
    lifts.append(('Siegel Modular Forms', '/ModularForm/GSp4/Q'))
    info['lifts'] = lifts
    return info
Esempio n. 57
0
def set_info_for_gamma1(level, weight, weight2=None):
    dimension_table_name = WebModFormSpace._dimension_table_name
    if weight != None and weight2 > weight:
        w1 = weight
        w2 = weight2
    else:
        w1 = weight
        w2 = weight
    table = {'galois_orbit': {}, 'galois_orbits_reps': {}, 'cells': {}}
    table['weights'] = range(w1, w2 + 1)
    emf_logger.debug("dimension table name={0}".format(dimension_table_name))
    db_dim = getDBConnection()['modularforms2'][dimension_table_name]
    s = {
        'level': int(level),
        'weight': {
            "$lt": int(w2 + 1),
            "$gt": int(w1 - 1)
        },
        'cchi': {
            "$exists": True
        }
    }
    q = db_dim.find(s).sort([('cchi', int(1)), ('weight', int(1))])
    if q.count() == 0:
        emf_logger.debug("No spaces in the database!")
        flash(
            'The database does not currently contain any spaces matching these parameters. Please try again!'
        )
        return None  #'error':'The database does not currently contain any spaces matching these parameters!'}
    else:
        table['maxGalCount'] = 1
        for r in q:
            xi = r['cchi']
            orbit = r['character_orbit']
            k = r['weight']
            ## This is probably still quicker if it is in the database
            parity = r.get('character_parity', 'n/a')
            if parity == 'n/a':
                chi = ConreyCharacter(level, xi)
                if chi.is_odd():
                    parity = -1
                elif chi.is_even():
                    parity = 1
                else:
                    emf_logger.critical(
                        "Could not determine the parity of ConreyCharacter({0},{1})"
                        .format(xi, level))
                    trivial_trivially = ""
            if parity != 'n/a':
                if k % 2 == (1 +
                             parity) / 2:  # is space empty because of parity?
                    trivial_trivially = "yes"
                else:
                    trivial_trivially = ""
            if parity == 1:
                parity = 'even'
            elif parity == -1:
                parity = 'odd'
            d = r.get('d_newf', "n/a")
            indb = r.get('in_wdb', 0)
            if d == 0:
                indb = 1
            if indb:
                url = url_for('emf.render_elliptic_modular_forms',
                              level=level,
                              weight=k,
                              character=xi)
            else:
                url = ''
            if not table['galois_orbits_reps'].has_key(xi):
                table['galois_orbits_reps'][xi] = {
                    'head':
                    "\(\chi_{{{0}}}({1},\cdot) \)".format(
                        level, xi),  # yes, {{{ is required
                    'chi':
                    "{0}".format(xi),
                    'url':
                    url_for('characters.render_Dirichletwebpage',
                            modulus=level,
                            number=xi),
                    'parity':
                    parity
                }
                table['galois_orbit'][xi] = [
                    {
                        #'head' : "\(\chi_{{{0}}}({1},\cdot) \)".format(level,xci),  # yes, {{{ is required
                        ##     'head' : "\(S_{{{0}}}({1},\chi({2}, \cdot) ) \)".format(weight,level,xci),  # yes, {{{ is required
                        ##    'head' : "\(S_{{{0}}}(\chi({1}, \cdot) ) \)".format(weight,xci),  # yes, {{{ is required
                        'head':
                        r"\(S_{{{0}}}(\chi_{{{1}}}({2}, \cdot)) \)".format(
                            weight, level, xci),  # yes, {{{ is required
                        # 'head' : "\({0}\)".format(xci),
                        'chi':
                        "{0}".format(xci),
                        #    'url': url_for('characters.render_Dirichletwebpage', modulus=level, number=xci)
                        'url':
                        url_for('emf.render_elliptic_modular_forms',
                                level=level,
                                weight=k,
                                character=xci) if indb else ''
                    } for xci in orbit
                ]
            if len(orbit) > table['maxGalCount']:
                table['maxGalCount'] = len(orbit)
            table['cells'][xi] = {}
            table['cells'][xi][k] = {
                'N': level,
                'k': k,
                'chi': xi,
                'url': url,
                'dim': d,
                'trivial_trivially': trivial_trivially,
            }
    table['galois_orbits_reps_numbers'] = table['galois_orbits_reps'].keys()
    table['galois_orbits_reps_numbers'].sort()
    #emf_logger.debug("Table:{0}".format(table))
    return table