Beispiel #1
0
 def init_belyi_stats(self):
     if self._stats:
         return
     galmaps = belyi_db_galmaps()
     counts = self._counts
     total = counts["ngalmaps"]
     stats = {}
     dists = []
     # TODO use aggregate $group to speed this up and/or just store these counts in the database
     for attr in stats_attribute_list:
         counts = attribute_value_counts(galmaps, attr['name'])
         counts = [c for c in counts if c[0] != None]
         if len(counts) == 0:
             continue
         vcounts = []
         rows = []
         avg = 0
         total = sum([c[1] for c in counts])
         for value, n in counts:
             prop = format_percentage(n, total)
             if 'avg' in attr and attr['avg'] and (type(value) == int
                                                   or type(value) == float):
                 avg += n * value
             value_string = attr['format'](
                 value) if 'format' in attr else value
             vcounts.append({
                 'value':
                 value_string,
                 'curves':
                 n,
                 'query':
                 url_for(".index") + '?' + attr['name'] + '=' + str(value),
                 'proportion':
                 prop
             })
             if len(vcounts) == 10:
                 rows.append(vcounts)
                 vcounts = []
         if len(vcounts):
             rows.append(vcounts)
         if 'avg' in attr and attr['avg']:
             vcounts.append({
                 'value':
                 '\(\\mathrm{avg}\\ %.2f\)' % (float(avg) / total),
                 'galmaps':
                 total,
                 'query':
                 url_for(".index") + '?' + attr['name'],
                 'proportion':
                 format_percentage(1, 1)
             })
         dists.append({'attribute': attr, 'rows': rows})
     stats["distributions"] = dists
     self._stats = stats
Beispiel #2
0
 def init_belyi_count(self):
     if self._counts:
         return
     galmaps = belyi_db_galmaps()
     counts = {}
     ngalmaps = galmaps.count()
     counts['ngalmaps'] = ngalmaps
     counts['ngalmaps_c'] = comma(ngalmaps)
     passports = belyi_db_passports()
     npassports = passports.count()
     counts['npassports'] = npassports
     counts['npassports_c'] = comma(npassports)
     max_deg = passports.find().sort('deg', DESCENDING).limit(1)[0]['deg']
     counts['max_deg'] = max_deg
     counts['max_deg_c'] = comma(max_deg)
     self._counts = counts
Beispiel #3
0
def random_belyi_galmap():
    label = random_value_from_collection(belyi_db_galmaps(), 'label')
    return redirect(url_for_belyi_galmap_label(label), 307)
Beispiel #4
0
def download_search(info):
    download_comment_prefix = {
        'magma': '//',
        'sage': '#',
        'gp': '\\\\',
        'text': '#'
    }
    download_assignment_defn = {
        'magma': ':=',
        'sage': ' = ',
        'gp': ' = ',
        'text': '='
    }
    delim_start = {'magma': '[*', 'sage': '[', 'gp': '[', 'text': ' ['}
    delim_end = {'magma': '*]', 'sage': ']', 'gp': ']', 'text': ' ]'}
    start_and_end = {
        'magma': ['[*', '*];'],
        'sage': ['[', '];'],
        'gp': ['{[', ']}'],
        'text': ['[', '];']
    }
    file_suffix = {'magma': '.m', 'sage': '.sage', 'gp': '.gp', 'text': '.txt'}
    lang = info.get('download', 'text').strip()
    filename = 'belyi_maps' + file_suffix[lang]
    mydate = time.strftime("%d %B %Y")
    start = delim_start[lang]
    end = delim_end[lang]
    # reissue query here
    try:
        res = belyi_db_galmaps().find(literal_eval(info.get('query', '{}')), {
            '_id': False,
            'label': True,
            'triples': True
        })
    except Exception as err:
        return "Unable to parse query: %s" % err
    # list of labels and triples

    def coerce_triples(triples):
        deg = len(triples[0][0])
        if lang == 'sage':
            return '[' + ',\n'.join(
                ["map(SymmetricGroup(%d), %s)" % (deg, s)
                 for s in triples]) + ']'
        elif lang == "magma":
            return '[' + ',\n'.join([
                '[' + ',\n'.join(["Sym(%d) ! %s" % (deg, t) for t in s]) + ']'
                for s in triples
            ]) + ']'

            return '[' + ',\n'.join(
                ["Sym(%d) ! %s" % (deg, s) for s in triples]) + ']'
        else:
            return str(triples)

    res_list = [
        start + str(r['label']).__repr__().replace("'", "\"") + ", " +
        coerce_triples(r['triples']) + end for r in res
    ]
    c = download_comment_prefix[lang]
    s = '\n'
    s += c + ' Belye maps downloaded from the LMFDB, downloaded on %s.\n' % mydate
    s += c + ' Query "%s" returned %d maps.\n\n' % (str(
        info.get('query')), res.count())
    s += c + ' Below is a list called data. Each entry has the form:\n'
    s += c + '   [label, permutation_triples]\n'
    s += c + ' where the permutation triples are in one line notation\n'
    s += c + '\n'
    s += '\n'
    s += 'data ' + download_assignment_defn[lang] + start_and_end[lang][
        0] + '\\\n'
    s += str(',\n'.join(res_list))
    s += start_and_end[lang][1]
    s += '\n\n'
    strIO = StringIO.StringIO()
    strIO.write(s)
    strIO.seek(0)
    return send_file(strIO,
                     attachment_filename=filename,
                     as_attachment=True,
                     add_etags=False)
Beispiel #5
0
def belyi_search(info):
    if 'jump' in info:
        jump = info["jump"].strip()
        if re.match(r'^\d+T\d+-\[\d+,\d+,\d+\]-\d+-\d+-\d+-g\d+-[a-z]+$',
                    jump):
            return redirect(url_for_belyi_galmap_label(jump), 301)
        else:
            if re.match(r'^\d+T\d+-\[\d+,\d+,\d+\]-\d+-\d+-\d+-g\d+$', jump):
                return redirect(url_for_belyi_passport_label(jump), 301)
            else:
                errmsg = "%s is not a valid Belyi map or passport label"
        flash_error(errmsg, jump)
        return redirect(url_for(".index"))
    if info.get('download', '').strip():
        return download_search(info)

    #search options
    info['geometry_types_list'] = geometry_types_list
    info['geometry_types_dict'] = geometry_types_dict

    bread = info.get('bread', (('Belyi Maps', url_for(".index")),
                               ('Search Results', '.')))

    query = {}
    try:
        if 'group' in query:
            info['group'] = query['group']
        parse_bracketed_posints(info,
                                query,
                                'abc_list',
                                'a, b, c',
                                maxlength=3)
        if query.get('abc_list'):
            if len(query['abc_list']) == 3:
                a, b, c = sorted(query['abc_list'])
                query['a_s'] = a
                query['b_s'] = b
                query['c_s'] = c
            elif len(query['abc_list']) == 2:
                a, b = sorted(query['abc_list'])
                sub_query = []
                sub_query.append({
                    'a_s': a,
                    'b_s': b
                })
                sub_query.append({
                    'b_s': a,
                    'c_s': b
                })
                query['$or'] = sub_query
            elif len(query['abc_list']) == 1:
                a = query['abc_list'][0]
                query['$or'] = [{
                    'a_s': a
                }, {
                    'b_s': a
                }, {
                    'c_s': a
                }]
            query.pop('abc_list')

        # a naive hack
        if info.get('abc'):
            for elt in ['a_s', 'b_s', 'c_s']:
                info_hack = {}
                info_hack[elt] = info['abc']
                parse_ints(info_hack, query, elt)

        parse_ints(info, query, 'g', 'g')
        parse_ints(info, query, 'deg', 'deg')
        parse_ints(info, query, 'orbit_size', 'orbit_size')
        # invariants and drop-list items don't require parsing -- they are all strings (supplied by us, not the user)
        for fld in ['geomtype', 'group']:
            if info.get(fld):
                query[fld] = info[fld]
    except ValueError as err:
        info['err'] = str(err)
        return render_template("belyi_search_results.html",
                               info=info,
                               title='Belyi Maps Search Input Error',
                               bread=bread,
                               credit=credit_string)

    # Database query happens here
    info["query"] = query  # save query for reuse in download_search
    cursor = belyi_db_galmaps().find(
        query, {
            '_id': False,
            'label': True,
            'group': True,
            'abc': True,
            'g': True,
            'deg': True,
            'geomtype': True,
            'orbit_size': True
        })

    count = parse_count(info, 50)
    start = parse_start(info)
    nres = cursor.count()
    if (start >= nres):
        start -= (1 + (start - nres) / count) * count
    if (start < 0):
        start = 0

    res = cursor.sort([("deg", ASCENDING), ("group_num", ASCENDING),
                       ("g", ASCENDING),
                       ("label", ASCENDING)]).skip(start).limit(count)
    nres = res.count()

    if nres == 1:
        info["report"] = "unique match"
    else:
        if nres > count or start != 0:
            info['report'] = 'displaying matches %s-%s of %s' % (
                start + 1, min(nres, start + count), nres)
        else:
            info['report'] = 'displaying all %s matches' % nres
    res_clean = []

    for v in res:
        v_clean = {}
        for key in ('label', 'group', 'deg', 'g', 'orbit_size'):
            v_clean[key] = v[key]
        v_clean['geomtype'] = geometry_types_dict[v['geomtype']]
        res_clean.append(v_clean)

    info["belyi_galmaps"] = res_clean
    info["belyi_galmap_url"] = lambda label: url_for_belyi_galmap_label(label)
    info["start"] = start
    info["count"] = count
    info["more"] = int(start + count < nres)

    title = info.get('title', 'Belyi map search results')
    credit = credit_string

    return render_template("belyi_search_results.html",
                           info=info,
                           credit=credit,
                           learnmore=learnmore_list(),
                           bread=bread,
                           title=title)