def input_box(default=None, label=None, type=lambda x: x, width=80, height=1, **kwargs): r""" An input box interactive control. Use this in conjunction with the :func:`interact` command. INPUT: - ``default`` - an object; the default put in this input box - ``label`` - a string; the label rendered to the left of the box. - ``type`` - a type; coerce inputs to this; this doesn't have to be an actual type, since anything callable will do. - ``height`` - an integer (default: 1); the number of rows. If greater than 1 a value won't be returned until something outside the textarea is clicked. - ``width`` - an integer; width of text box in characters - ``kwargs`` - a dictionary; additional keyword options EXAMPLES:: sage: input_box("2+2", 'expression') Interact input box labeled 'expression' with default value '2+2' sage: input_box('sage', label="Enter your name", type=str) Interact input box labeled 'Enter your name' with default value 'sage' sage: input_box('Multiline\nInput',label='Click to change value',type=str,height=5) Interact input box labeled 'Click to change value' with default value 'Multiline\nInput' """ # TODO: make input_box take a type from sagenb.misc.misc import Color if type is Color: # kwargs are only used if the type is Color. widget=kwargs.get('widget', None) hide_box=kwargs.get('hide_box', False) return color_selector(default=default, label=label, widget=widget, hide_box=hide_box) if not isinstance(default, basestring): default=repr(default) from sage.all import sage_eval if type is None: adapter = lambda x, globs: sage_eval(x, globs) elif type is str: adapter=lambda x, globs: x else: adapter = lambda x, globs: sage_eval(x, globs) return InputBox(default=default, width=width, label=label, adapter=adapter, height=height)
def getConstraints(m, resultAsDict=False): """ Input a model m, returns its set of constraints in either 1) sage dict {x:7,y:10} 1) z3 expr [x==7,y==0] sage: S = z3.Solver() sage: S.add(z3.Int('x') + z3.Int('y') == z3.IntVal('7')) sage: S.check() sat sage: M = S.model() sage: d = getConstraints(M, resultAsDict=True) sage: sorted(d.items(), key=lambda(k,_): str(k)) [(x, 7), (y, 0)] sage: getConstraints(M) [y == 0, x == 7] sage: S.reset() """ assert m is not None, m if resultAsDict: #sage format rs = [(var(str(v())),sage_eval(str(m[v]))) for v in m] rs = dict(rs) assert all(is_sage_expr(x) for x in rs.keys()) assert all(is_sage_real(x) or is_sage_int(x) for x in rs.values()) else: #z3 format rs = [v()==m[v] for v in m] assert all(z3.is_expr(x) for x in rs) return rs
def compute_conjectural_ranks(level_norms, address='localhost:29000'): """ For each level norm in the input list, compute the *conjectural* rank of the elliptic curve, and put that data in a field "r?" in the database. This uses Simon 2-descent if it works, and otherwise uses Dokchitser. This should not be considered super-reliable! """ from sage.all import sage_eval import util C = util.ellcurves_sqrt5(address) for N in level_norms: for E in C.find({ 'Nlevel': int(N), 'r?': { '$exists': False }, 'weq': { '$exists': True } }): print E weq = sage_eval(E['weq'], {'a': F.gen()}) E['r?'] = int(rank(weq)) print E C.update({'_id': E['_id']}, E, safe=True)
def eval_lambda(f, d, is_formula=True): """ Evaluates lambda function f Examples: sage: assert InvMPP.eval_lambda('lambda x,y: max(x - 13,-3) >= y', {'x':11,'y':100}) == False sage: assert InvMPP.eval_lambda('lambda x,y: x+y == 5', {'x':2,'y':3,'d':7}) sage: assert InvMPP.eval_lambda('lambda x,y: x+y == 6', {'x':2,'y':3,'d':7}) == False sage: assert InvMPP.eval_lambda('lambda x,y: x+y', {'x':2,'y':3,'d':7}, is_formula=False) == 5 sage: assert InvMPP.eval_lambda('lambda x,y: x+y == 10 or x + y == 5', {'x':2,'y':3,'d':7}) sage: assert InvMPP.eval_lambda('lambda x,y: x+y == 1 or x + y == 2', {'x':2,'y':3,'d':7}) == False """ if __debug__: assert is_str(f) and 'lambda' in f, f assert is_dict(d), d assert all(is_str(k) for k in d), d.keys() f = sage_eval(f) vs = f.func_code.co_varnames assert set(vs) <= set(d.keys()), (vs,d.keys()) #if d has more keys than variables in f then remove those extra keys d=dict([(k,d[k]) for k in vs]) rs = f(**d) return bool(rs) if is_formula else rs
def scl(chain, mode='local', args=[], return_fraction=True, verbose=1): if chain == '' or chain == ['']: return 0 if type(chain) == str: C = [chain] else : C = [x for x in chain if x != ''] cmd_list = ['scallop', '-' + mode] + args + C if verbose > 1: print "Running " + SCALLOPDIR+str(cmd_list) if sys.version[:3] == '2.7': mout = subprocess.check_output(cmd_list, \ executable=SCALLOPDIR+cmd_list[0], \ stderr=FNULL, \ cwd=SCALLOPDIR) else: sca = subprocess.Popen(cmd_list, \ executable=SCALLOPDIR+cmd_list[0], \ stdout=subprocess.PIPE, \ stderr=FNULL, \ cwd=SCALLOPDIR) mout = sca.communicate()[0] if return_fraction: dat = mout.split(' ')[-3] if dat == 'feasible': raise NameError('No feasible solution found') return sage_eval(dat) else: dat = mout.split(' ')[-1] return eval(dat)
def scylla(gen_string, C_input, method=None): if type(C_input) == str: C = [C_input] else : C = [x for x in C_input if x != ''] run_string = ['scallop'] if method != None: run_string += ['-m' + method] run_string += [gen_string] run_string += C if sys.version[:3] == '2.7': mout = subprocess.check_output(run_string, \ executable=SCALLOPDIR+run_string[0], \ stderr=FNULL, \ cwd=SCALLOPDIR) else: sca = subprocess.Popen(run_string, \ executable=SCALLOPDIR+run_string[0], \ stdout=subprocess.PIPE, \ stderr=FNULL, \ cwd=SCALLOPDIR) mout = sca.communicate()[0] dat = mout.split(' ')[-3] return sage_eval(dat)
def eval_lambda(f, d, is_formula=True): """ Evaluates lambda function f Examples: sage: assert InvMPP.eval_lambda('lambda x,y: max(x - 13,-3) >= y', {'x':11,'y':100}) == False sage: assert InvMPP.eval_lambda('lambda x,y: x+y == 5', {'x':2,'y':3,'d':7}) sage: assert InvMPP.eval_lambda('lambda x,y: x+y == 6', {'x':2,'y':3,'d':7}) == False sage: assert InvMPP.eval_lambda('lambda x,y: x+y', {'x':2,'y':3,'d':7}, is_formula=False) == 5 sage: assert InvMPP.eval_lambda('lambda x,y: x+y == 10 or x + y == 5', {'x':2,'y':3,'d':7}) sage: assert InvMPP.eval_lambda('lambda x,y: x+y == 1 or x + y == 2', {'x':2,'y':3,'d':7}) == False """ if __debug__: assert is_str(f) and 'lambda' in f, f assert is_dict(d), d assert all(is_str(k) for k in d), d.keys() f = sage_eval(f) vs = f.func_code.co_varnames assert set(vs) <= set(d.keys()), (vs, d.keys()) #if d has more keys than variables in f then remove those extra keys d = dict([(k, d[k]) for k in vs]) rs = f(**d) return bool(rs) if is_formula else rs
def download_search(info): lang = info["submit"] filename = 'Hecke_algebras' + download_file_suffix[lang] mydate = time.strftime("%d %B %Y") # reissue saved query here if 'ell' in info["query"]: res = hecke_l_adic_db().find(ast.literal_eval(info["query"])).sort([ ('level', ASC), ('weight', ASC), ('num_orbits', ASC) ]) else: res = hecke_orbits_db().find(ast.literal_eval(info["query"])).sort([ ('level', ASC), ('weight', ASC), ('num_orbits', ASC) ]) last = res.count() - 1 c = download_comment_prefix[lang] s = '\n' if 'ell' in info["query"]: s += c + ' Hecke algebras downloaded from the LMFDB on %s. Found %s algebras. The data is given in the following format: it is a list of lists, each containing level, weight and the Hecke orbits for which l-adic data is available.\n\n' % ( mydate, res.count()) else: s += c + ' Hecke algebras downloaded from the LMFDB on %s. Found %s algebras. The data is given in the following format: it is a list of lists, each containing level, weight, list of the first 10 Hecke operators (to download more operators for a given algebra, please visit its webpage).\n\n' % ( mydate, res.count()) # The list entries are matrices of different sizes. Sage and gp # do not mind this but Magma requires a different sort of list. list_start = '[*' if lang == 'magma' else '[' list_end = '*]' if lang == 'magma' else ']' s += download_assignment_start[lang] + list_start + '\\\n' mat_start = "Mat(" if lang == 'gp' else "Matrix(" mat_end = "~)" if lang == 'gp' else ")" entry = lambda r: "".join([mat_start, str(r), mat_end]) # loop through all search results and grab the Hecke operators stored for c, rr in enumerate(res): s += list_start s += ",".join([str(rr['level']), str(rr['weight']), ""]) if 'ell' in info["query"]: s += '"%s"' % (str(rr['orbit_label'])) else: s += ",".join([ entry(r) for r in [ sage_eval(rr['hecke_op'])[i] for i in range(0, min(10, rr['num_hecke_op'])) ] ]) if c != last: s += list_end + ',\\\n' else: s += list_end s += list_end s += download_assignment_end[lang] s += '\n' strIO = StringIO.StringIO() strIO.write(s) strIO.seek(0) return send_file(strIO, attachment_filename=filename, as_attachment=True, add_etags=False)
def convert_magma_matrix_to_sage(m, K): try: return Matrix(K, m.sage()); except: pass from re import sub text = str(m) text = sub('\[\s+', '[', text) text = sub('\s+', ' ', text) text = '['+text.replace(' ',', ').replace('\n',', ')+']' return Matrix(K, sage_eval(text, locals={'r': K.gens()}))
def curve_string_parser(self, rec): curve_str = rec["curve"] curve_str = curve_str.replace("^", "**") K = self.make_base_field(rec) nu = K.gens()[0] S0 = PolynomialRing(K, "x") x = S0.gens()[0] S = PolynomialRing(S0, "y") y = S.gens()[0] parts = curve_str.split("=") lhs_poly = sage_eval(parts[0], locals={"x": x, "y": y, "nu": nu}) lhs_cs = lhs_poly.coefficients() if len(lhs_cs) == 1: h = 0 elif len(lhs_cs) == 2: # if there is a cross-term h = lhs_poly.coefficients()[0] else: raise NotImplementedError("for genus > 2") # rhs_poly = sage_eval(parts[1], locals = {'x':x, 'y':y, 'nu':nu}) f = sage_eval(parts[1], locals={"x": x, "y": y, "nu": nu}) return f, h
def __init__(self, default="", label=None, width=0, height=1, adapter=None, evaluate=True): if not isinstance(default, basestring): default = repr(default) self.default=default self.width=int(width) self.height=int(height) self.raw=False self.label=label if evaluate: from sage.all import sage_eval if adapter is not None: self.adapter = lambda x,globs: adapter(sage_eval(x,globs), globs) else: self.adapter = lambda x,globs: sage_eval(x,globs) elif adapter is not None: self.adapter = lambda x,globs: adapter(x,globs) if self.height > 1: self.subtype = "textarea" self.raw = True else: self.subtype = "input"
def __init__(self, nrows=1, ncols=1, default='0', adapter=None, width=0, label=None, element_adapter=None, evaluate=True): self.nrows = int(nrows) self.ncols = int(ncols) self.width = int(width) self.label = label if evaluate: from sage.all import sage_eval if element_adapter is not None: self.element_adapter = lambda x,globs: element_adapter(sage_eval(x,globs), globs) else: self.element_adapter = lambda x,globs: sage_eval(x,globs) else: if element_adapter is not None: self.element_adapter = lambda x,globs: element_adapter(x,globs) else: self.element_adapter = lambda x,globs: x if adapter is None: self.adapter = lambda x,globs: [[self.element_adapter(i,globs) for i in xi] for xi in x] else: self.adapter = lambda x,globs: adapter([[self.element_adapter(i,globs) for i in xi] for xi in x],globs) def makestring(x): if isinstance(x, basestring): return x else: return repr(x) if not isinstance(default, list): self.default = [[makestring(default) for _ in range(self.ncols)] for _ in range(self.nrows)] # Allows 1-row input grids to use non-nested lists for default values elif not all(isinstance(entry, (list,tuple)) for entry in default): # the above test will exhaust an iterator... self.default = [[makestring(default[i * self.ncols + j]) for j in range(self.ncols)] for i in range(self.nrows)] else: self.default = [[makestring(default[r][c]) for c in range(self.ncols)] for r in range(self.nrows)]
def build_poly(vts, ts, is_max_plus): """ Build a MPP convex polyhedron over vts and return a set of constraints Examples: sage: var('y') y sage: rs = IeqMPPGen.build_poly([[0,0,0],[3,3,0]], [x,y,SR(0)], is_max_plus=True) dig_polynomials:Debug:Build (gen max-plus) poly from 2 vts in 3 dims: [x, y, 0] sage: print '\n'.join(map(str,sorted(rs))) ('lambda x,y: -x + y >= 0', 'y >= x') ('lambda x,y: x - y >= 0', 'x >= y') ('lambda x: -x + 3 >= 0', '0 >= x - 3') ('lambda x: x >= 0', 'x >= 0') ('lambda y: -y + 3 >= 0', '0 >= y - 3') ('lambda y: y >= 0', 'y >= 0') """ opt_arg = '' if is_max_plus: mpp_str = 'max-plus' else: mpp_str = 'min-plus' opt_arg = "{} {}".format(opt_arg, '-{}'.format(mpp_str)) # if any vertex is float if any(any(not SR(v).is_integer() for v in vt) for vt in vts): vts = [[RR(v).n() for v in vt] for vt in vts] opt_arg = "{} -numerical-data ocaml_float".format(opt_arg) # exec external program # important, has to end with newline \n !!! vts_s = '\n'.join(str(vt).replace(' ', '') for vt in vts) + '\n' logger.debug('Build (gen {}) poly from {} vts in {} dims: {}'.format( mpp_str, len(vts), len(vts[0]), ts)) cmd = 'compute_ext_rays_polar {} {}'.format(opt_arg, len(vts[0])) rs, _ = vcmd(cmd, vts_s) rs = [sage_eval(s.replace('oo', 'Infinity')) for s in rs.split()] rs = IeqMPPGen.group_rs(rs) rs = map(lambda ls: [x + y for x, y in zip(ls, ts + ts)], rs) rs = map(lambda ls: IeqMPP.sparse(ls, is_max_plus), rs) rs = filter(None, rs) return rs
def build_poly(vts, ts, is_max_plus): """ Build a MPP convex polyhedron over vts and return a set of constraints Examples: sage: logger.set_level(VLog.DEBUG) sage: IeqMPP.build_poly([[0,0,0],[3,3,0]], is_max_plus=True) dig_polynomials:Debug:Ieq: Build (MPP max-plus) polyhedra from 2 vertices in 3 dim ['[-oo,0,-oo,-oo,-oo,0]', '[0,-oo,-oo,-oo,-oo,0]', '[0,-oo,-oo,-oo,-oo,-oo]', '[-oo,0,-oo,-oo,-oo,-oo]', '[-oo,-oo,0,-oo,-oo,-oo]', '[-oo,-oo,0,-oo,-oo,0]', '[-oo,-oo,0,-oo,-3,-oo]', '[-oo,-oo,0,-3,-oo,-oo]', '[-oo,0,-oo,-oo,0,-oo]', '[-oo,0,-oo,0,-oo,-oo]', '[0,-oo,-oo,-oo,0,-oo]', '[0,-oo,-oo,0,-oo,-oo]'] """ opt_arg = '' if is_max_plus: mpp_str = 'max-plus' else: mpp_str = 'min-plus' opt_arg = "{} {}".format(opt_arg, '-{}'.format(mpp_str)) #if any vertex is float if any(any(not SR(v).is_integer() for v in vt) for vt in vts): vts = [[RR(v).n() for v in vt] for vt in vts] opt_arg = "{} -numerical-data ocaml_float".format(opt_arg) #exec external program #important, has to end with newline \n !!! vts_s = '\n'.join(str(vt).replace(' ', '') for vt in vts) + '\n' logger.debug('Build (gen {}) poly from {} vts in {} dims: {}'.format( mpp_str, len(vts), len(vts[0]), ts)) cmd = 'compute_ext_rays_polar {} {}'.format(opt_arg, len(vts[0])) rs, _ = vcmd(cmd, vts_s) rs = [sage_eval(s.replace('oo', 'Infinity')) for s in rs.split()] rs = IeqMPPGen.group_rs(rs) rs = map(lambda ls: [x + y for x, y in zip(ls, ts + ts)], rs) rs = map(lambda ls: IeqMPP.sparse(ls, is_max_plus), rs) rs = filter(None, rs) return rs
def build_poly(vts, ts, is_max_plus): """ Build a MPP convex polyhedron over vts and return a set of constraints Examples: sage: logger.set_level(VLog.DEBUG) sage: IeqMPP.build_poly([[0,0,0],[3,3,0]], is_max_plus=True) dig_polynomials:Debug:Ieq: Build (MPP max-plus) polyhedra from 2 vertices in 3 dim ['[-oo,0,-oo,-oo,-oo,0]', '[0,-oo,-oo,-oo,-oo,0]', '[0,-oo,-oo,-oo,-oo,-oo]', '[-oo,0,-oo,-oo,-oo,-oo]', '[-oo,-oo,0,-oo,-oo,-oo]', '[-oo,-oo,0,-oo,-oo,0]', '[-oo,-oo,0,-oo,-3,-oo]', '[-oo,-oo,0,-3,-oo,-oo]', '[-oo,0,-oo,-oo,0,-oo]', '[-oo,0,-oo,0,-oo,-oo]', '[0,-oo,-oo,-oo,0,-oo]', '[0,-oo,-oo,0,-oo,-oo]'] """ opt_arg = '' if is_max_plus: mpp_str = 'max-plus' else: mpp_str = 'min-plus' opt_arg = "{} {}".format(opt_arg, '-{}'.format(mpp_str)) #if any vertex is float if any(any(not SR(v).is_integer() for v in vt) for vt in vts): vts = [[RR(v).n() for v in vt] for vt in vts] opt_arg = "{} -numerical-data ocaml_float".format(opt_arg) #exec external program #important, has to end with newline \n !!! vts_s = '\n'.join(str(vt).replace(' ','') for vt in vts) + '\n' logger.debug('Build (gen {}) poly from {} vts in {} dims: {}' .format(mpp_str,len(vts),len(vts[0]),ts)) cmd = 'compute_ext_rays_polar {} {}'.format(opt_arg, len(vts[0])) rs,_ = vcmd(cmd, vts_s) rs = [sage_eval(s.replace('oo','Infinity')) for s in rs.split()] rs = IeqMPPGen.group_rs(rs) rs = map(lambda ls:[x+y for x,y in zip(ls,ts+ts)], rs) rs = map(lambda ls: IeqMPP.sparse(ls,is_max_plus), rs) rs = filter(None, rs) return rs
def safe_sage_eval(code, globs): """ Evaluate an expression using sage_eval, returning an ``Exception`` object if an exception occurs :arg str code: the expression to evaluate :arg dict globs: the global dictionary in which to evaluate the expression :returns: the value of the expression. If an exception occurs, the ``Exception`` object is returned instead. """ try: try: from sage.all import sage_eval return sage_eval(code, globs) except ImportError: return eval(code, globs) except Exception as e: return e
def download_search(info): lang = info["submit"] filename = 'Hecke_algebras' + download_file_suffix[lang] mydate = time.strftime("%d %B %Y") # reissue saved query here if 'ell' in info["query"]: res = list(db.hecke_ladic.search(ast.literal_eval(info["query"]))) else: res = list(db.hecke_orbits.search(ast.literal_eval(info["query"]))) last = len(res) c = download_comment_prefix[lang] s = '\n' if 'ell' in info["query"]: s += c + ' Hecke algebras downloaded from the LMFDB on %s. Found %s algebras. The data is given in the following format: it is a list of lists, each containing level, weight and the Hecke orbits for which l-adic data is available.\n\n'%(mydate, len(res)) else: s += c + ' Hecke algebras downloaded from the LMFDB on %s. Found %s algebras. The data is given in the following format: it is a list of lists, each containing level, weight, list of the first 10 Hecke operators (to download more operators for a given algebra, please visit its webpage).\n\n'%(mydate, len(res)) # The list entries are matrices of different sizes. Sage and gp # do not mind this but Magma requires a different sort of list. list_start = '[*' if lang=='magma' else '[' list_end = '*]' if lang=='magma' else ']' s += download_assignment_start[lang] + list_start + '\\\n' mat_start = "Mat(" if lang == 'gp' else "Matrix(" mat_end = "~)" if lang == 'gp' else ")" entry = lambda r: "".join([mat_start,str(r),mat_end]) # loop through all search results and grab the Hecke operators stored for c, rr in enumerate(res): s += list_start s += ",".join([str(rr['level']), str(rr['weight']),""]) if 'ell' in info["query"]: s += '"%s"' % (str(rr['orbit_label'])) else: s += ",".join([entry(r) for r in [sage_eval(rr['hecke_op'])[i] for i in range(0, min(10, rr['num_hecke_op']))]]) if c != last: s += list_end + ',\\\n' else: s += list_end s += list_end s += download_assignment_end[lang] s += '\n' strIO = StringIO.StringIO() strIO.write(s) strIO.seek(0) return send_file(strIO, attachment_filename=filename, as_attachment=True, add_etags=False)
def download_hecke_algebras_full_lists_op(**args): label = str(args['orbit_label']) res = hecke_orbits_db().find_one({'orbit_label': label}) mydate = time.strftime("%d %B %Y") if res is None: return "No operators available" lang = args['lang'] c = download_comment_prefix[lang] mat_start = "Mat(" if lang == 'gp' else "Matrix(" mat_end = "~)" if lang == 'gp' else ")" entry = lambda r: "".join([mat_start,str(r),mat_end]) outstr = c + 'Hecke algebra for Gamma0(%s) and weight %s, orbit label %s. List of Hecke operators T_1, ..., T_%s. Downloaded from the LMFDB on %s. \n\n'%(res['level'], res['weight'], res['orbit_label'],res['num_hecke_op'], mydate) outstr += download_assignment_start[lang] + '[\\\n' outstr += ",\\\n".join([entry(r) for r in [sage_eval(res['hecke_op'])[i] for i in range(0,res['num_hecke_op'])]]) outstr += ']' outstr += download_assignment_end[lang] outstr += '\n' return outstr
def download_hecke_algebras_full_lists_op(**args): label = str(args['orbit_label']) res = db.hecke_orbits.lucky({'orbit_label': label}) mydate = time.strftime("%d %B %Y") if res is None: return "No operators available" lang = args['lang'] c = download_comment_prefix[lang] mat_start = "Mat(" if lang == 'gp' else "Matrix(" mat_end = "~)" if lang == 'gp' else ")" entry = lambda r: "".join([mat_start,str(r),mat_end]) outstr = c + 'Hecke algebra for Gamma0(%s) and weight %s, orbit label %s. List of Hecke operators T_1, ..., T_%s. Downloaded from the LMFDB on %s. \n\n'%(res['level'], res['weight'], res['orbit_label'],res['num_hecke_op'], mydate) outstr += download_assignment_start[lang] + '[\\\n' outstr += ",\\\n".join([entry(r) for r in [sage_eval(res['hecke_op'])[i] for i in range(0,res['num_hecke_op'])]]) outstr += ']' outstr += download_assignment_end[lang] outstr += '\n' return outstr
def compute_conjectural_ranks(level_norms, address='localhost:29000'): """ For each level norm in the input list, compute the *conjectural* rank of the elliptic curve, and put that data in a field "r?" in the database. This uses Simon 2-descent if it works, and otherwise uses Dokchitser. This should not be considered super-reliable! """ from sage.all import sage_eval import util C = util.ellcurves_sqrt5(address) for N in level_norms: for E in C.find({'Nlevel':int(N), 'r?':{'$exists':False}, 'weq':{'$exists':True}}): print E weq = sage_eval(E['weq'], {'a':F.gen()}) E['r?'] = int(rank(weq)) print E C.update({'_id':E['_id']}, E, safe=True)
def get_constraints(m, result_as_dict=False): """ Input a model m, returns its set of constraints in either 1) sage dict {x:7,y:10} 1) z3 expr [x==7,y==0] sage: S = z3.Solver() sage: S.add(z3.Int('x') + z3.Int('y') == z3.IntVal('7')) sage: S.check() sat sage: M = S.model() sage: d = SMT_Z3.get_constraints(M, result_as_dict=True) sage: sorted(d.items(), key=lambda(k,_): str(k)) [(x, 7), (y, 0)] sage: SMT_Z3.get_constraints(M) [y == 0, x == 7] sage: S.reset() """ assert m is not None, m if result_as_dict: #sage format rs = [(var(str(v())),sage_eval(str(m[v]))) for v in m] rs = dict(rs) if __debug__: assert all(is_sage_expr(x) for x in rs.keys()) assert all(is_sage_real(x) or is_sage_int(x) for x in rs.values()) else: #z3 format rs = [v()==m[v] for v in m] if __debug__: assert all(z3.is_expr(x) for x in rs) return rs
def verify_curve_lmfdb(label, Lhash = None): from lmfdb import getDBconnection C = getDBconnection() curve = C.genus2_curves.curves.find_one({"label" : label}) endo_query = C.genus2_curves.endomorphisms.find_one({'label': label}) rank_endo = rank_from_endo(endo_query['factorsRR_geom']) if not endo_query['is_simple_geom']: assert rank_endo > 1 if Lhash is None: Lhash = curve['Lhash']; Lfunction_query = C. Lfunctions.Lfunctions.find_one({'Lhash': Lhash}) ef = sage_eval(str(Lfunction_query['euler_factors'])) rank_euler, _ = upperrank(ef) if endo_query['factorsRR_geom'] == [u'RR', u'RR'] and curve['is_simple_geom']: RM_coeff = endo_query['factorsQQ_geom'][0][1] checkRM = RM_and_notCM(ef, RM_coeff) return rank_endo == rank_euler and checkRM, rank_endo, rank_euler return rank_endo == rank_euler, rank_endo, rank_euler
def render_hecke_algebras_webpage_l_adic(**args): data = None if 'orbit_label' in args and 'prime' in args: lab = clean_input(args.get('orbit_label')) if lab != args.get('orbit_label'): base_lab=".".join([split(lab)[i] for i in [0,1,2]]) return redirect(url_for('.render_hecke_algebras_webpage', label=base_lab), 301) try: ell = int(args.get('prime')) except ValueError: base_lab=".".join([split(lab)[i] for i in [0,1,2]]) return redirect(url_for('.render_hecke_algebras_webpage', label=base_lab), 301) data = hecke_l_adic_db().find_one({'orbit_label': lab , 'ell': ell}) if data is None: t = "Hecke Agebras Search Error" bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage"))] flash(Markup("Error: <span style='color:black'>%s</span> is not a valid label for the ℓ-adic information for an Hecke Algebra orbit in the database." % (lab)),"error") return render_template("hecke_algebras-error.html", title=t, properties=[], bread=bread, learnmore=learnmore_list()) info = {} info.update(data) res = hecke_l_adic_db().find({'level': data['level'],'weight': data['weight'],'orbit_label': data['orbit_label'], 'ell': data['ell']}) info['num_l_adic_orbits']=res.count() res_clean = [] for f in res: f_clean = {} f_clean['index']=int(f['index']) f_clean['orbit_label']=str(f['orbit_label']) f_clean['ell']=int(f['ell']) if f['idempotent'] != "": f['dim']=len(sage_eval(f['idempotent'])) l_max= sage_eval(f['idempotent'])[0][0].ndigits() if f['dim']>4 or l_max>5: f_clean['idempotent_display']=[] elif f['dim']==1: f_clean['idempotent_display']=sage_eval(f['idempotent'])[0][0] else: f_clean['idempotent_display']=latex(matrix(sage_eval(f['idempotent']))) else: f_clean['idempotent_display']=latex(matrix([[1]])) f_clean['download_id'] = [(i, url_for(".render_hecke_algebras_webpage_ell_download", orbit_label=f_clean['orbit_label'], index=f_clean['index'], prime=f_clean['ell'], lang=i, obj='idempotents')) for i in ['magma','sage']] # for 'gp' the code does not work, since p-adics are not implemented try: f_clean['deg']=int(f['field'][1]) f_clean['field_poly']=str(f['field'][2]) f_clean['dim']=int(f['structure'][0]) f_clean['num_gen']=int(f['structure'][1]) f_clean['gens']=[[int(sage_eval(f['structure'][2]).index(i)+1), str(i)] for i in sage_eval(f['structure'][2])] f_clean['rel']=sage_eval(f['structure'][3]) f_clean['grading']=[int(i) for i in f['properties'][0]] f_clean['gorenstein_def']=int(f['properties'][1]) if f_clean['gorenstein_def']==0: f_clean['gorenstein']="yes" else: f_clean['gorenstein']="no" f_clean['operators_mod_l']=[[int(i) for i in j] for j in f['operators']] f_clean['num_hecke_op']=len(f_clean['operators_mod_l']) f_clean['download_op'] = [(i, url_for(".render_hecke_algebras_webpage_ell_download", orbit_label=f_clean['orbit_label'], index=f_clean['index'], prime=f_clean['ell'], lang=i, obj='operators')) for i in ['magma','sage']] # for 'gp' the code does not work f_clean['size_op']=sqrt(len(f_clean['operators_mod_l'][0])) if f_clean['size_op']>4: f_clean['operators_mod_l_display']=[] elif f_clean['size_op']==1: f_clean['operators_mod_l_display']=[[i+1, f_clean['operators_mod_l'][i][0]] for i in range(0,10)] else: f_clean['operators_mod_l_display']=[[i+1,latex(matrix(f_clean['size_op'],f_clean['size_op'], f_clean['operators_mod_l'][i]))] for i in range(0,5)] res_clean.append(f_clean) except KeyError: pass info['l_adic_orbits']=res_clean info['level']=int(data['level']) info['weight']= int(data['weight']) info['base_lab']=".".join([split(data['orbit_label'])[i] for i in [0,1,2]]) info['orbit_label']= str(data['orbit_label']) info['ell']=int(data['ell']) bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage")), ('%s' % info['base_lab'], url_for('.render_hecke_algebras_webpage', label=info['base_lab'])), ('%s' % info['ell'], ' ')] credit = hecke_algebras_credit info['properties'] = [ ('Level', '%s' %info['level']), ('Weight', '%s' %info['weight']), ('Characteristic', '%s' %info['ell']), ('Orbit label', '%s' %info['orbit_label'])] info['friends'] = [('Modular form ' + info['base_lab'], url_for("emf.render_elliptic_modular_forms", level=info['level'], weight=info['weight'], character=1))] t = "%s-adic and mod %s data for the Hecke Algebra orbit %s" % (info['ell'], info['ell'], info['orbit_label']) return render_template("hecke_algebras_l_adic-single.html", info=info, credit=credit, title=t, bread=bread, properties2=info['properties'], learnmore=learnmore_list(), friends=info['friends'])
def _element_constructor_(self, x): """ Convert ``x`` into ``self``. EXAMPLES:: sage: R.<x,y> = FreeAlgebra(QQ,2) sage: R(3) # indirect doctest 3 TESTS:: sage: F.<x,y,z> = FreeAlgebra(GF(5),3) sage: L.<x,y,z> = FreeAlgebra(ZZ,3,implementation='letterplace') sage: F(x) # indirect doctest x sage: F.1*L.2 y*z sage: (F.1*L.2).parent() is F True :: sage: K.<z> = GF(25) sage: F.<a,b,c> = FreeAlgebra(K,3) sage: L.<a,b,c> = FreeAlgebra(K,3, implementation='letterplace') sage: F.1+(z+1)*L.2 b + (z+1)*c Check that :trac:`15169` is fixed:: sage: A.<x> = FreeAlgebra(CC) sage: A(2) 2.00000000000000 We check that the string coercions work correctly over inexact fields:: sage: F.<x,y> = FreeAlgebra(CC) sage: F('2') 2.00000000000000 sage: F('x') 1.00000000000000*x Check that it also converts factorizations:: sage: f = Factorization([(x,2),(y,3)]); f 1.00000000000000*x^2 * 1.00000000000000*y^3 sage: F(f) 1.00000000000000*x^2*y^3 """ if isinstance(x, FreeAlgebraElement): P = x.parent() if P is self: return x if P is not self.base_ring(): return self.element_class(self, x) elif hasattr(x, 'letterplace_polynomial'): P = x.parent() if self.has_coerce_map_from(P): # letterplace versus generic ngens = P.ngens() M = self._indices def exp_to_monomial(T): out = [] for i in range(len(T)): if T[i]: out.append((i % ngens, T[i])) return M(out) return self.element_class( self, { exp_to_monomial(T): c for T, c in x.letterplace_polynomial().dict().items() }) # ok, not a free algebra element (or should not be viewed as one). if isinstance(x, str): from sage.all import sage_eval G = self.gens() d = {str(v): G[i] for i, v in enumerate(self.variable_names())} return self(sage_eval(x, locals=d)) R = self.base_ring() # coercion from free monoid if isinstance(x, FreeMonoidElement) and x.parent() is self._indices: return self.element_class(self, {x: R.one()}) # coercion from the PBW basis if isinstance(x, PBWBasisOfFreeAlgebra.Element) \ and self.has_coerce_map_from(x.parent()._alg): return self(x.parent().expansion(x)) # Check if it's a factorization from sage.structure.factorization import Factorization if isinstance(x, Factorization): return self.prod(f**i for f, i in x) # coercion via base ring x = R(x) if x == 0: return self.element_class(self, {}) return self.element_class(self, {self.one_basis(): x})
def eval_lambda(f, idx_info, tc): """ Evaluate array expression p, e.g. p: A[i,j,k]=B[2i+3j+k] if idx_info is specified then only test p on the idxs from idx_info Assumes: the first array in lambda is the pivot lambda A,B,i,j,k: ... => i,j,k belong to A inv = 'lambda B,C,D,i,j: B[i][j]=C[D[2i+3]]' returns true if inv is true on tc Examples: sage: var('a,b,c,i,j') (a, b, c, i, j) sage: InvArray.eval_lambda('lambda a,b,c,i,j: a[i][j]==2*b[i]+c[j]', None, {'a':[[4,-5],[20,11]],'b':[1,9],'c':[2,-7]}) True sage: InvArray.eval_lambda('lambda c,a,b,xor,i: c[i] == xor(a[i],b[i])', None, {'a': [147, 156, 184, 76], 'b': [51, 26, 247, 189], 'c': [160, 334, 79, 281]}) False sage: InvArray.eval_lambda('lambda c,a,b,xor,i1: c[i1] == xor(a[i1],b[i1])', None, {'a': [147, 156, 184, 76], 'b': [51, 26, 247, 189], 'c': [160, 134, 79, 241]}) True sage: InvArray.eval_lambda('lambda rvu, t, rvu1, rvu0: (rvu[rvu0][rvu1]) + (-t[4*rvu0 + rvu1]) == 0', None, {'t': [28, 131, 11, 85, 133, 46, 179, 20, 227, 148, 225, 197, 38, 221, 221, 126], 'rvu': [[28, 131, 11, 85], [133, 46, 179, 20], [227, 148, 225, 197], [38, 221, 221, 126]]}) True #The following illustrate the use of idxVals, #i.e. p is only true under certain array rages sage: InvArray.eval_lambda('lambda st, rvu, st0, st1: (-st[st0][st1]) + (rvu[4*st0 + st1]) == 0', None, tc = {'rvu': [28, 131, 11, 85, 193, 124, 103, 215, 66, 26, 68, 54, 176, 102, 15, 237], 'st': [[28, 131, 11, 85, 133, 46, 179, 20, 227, 148, 225, 197, 38, 221, 221, 126], [193, 124, 103, 215, 106, 229, 162, 168, 166, 78, 144, 234, 199, 254, 152, 250], [66, 26, 68, 54, 206, 16, 155, 248, 231, 198, 240, 43, 208, 205, 213, 26], [176, 102, 15, 237, 49, 141, 213, 97, 137, 155, 50, 243, 112, 51, 124, 107]]}) False sage: InvArray.eval_lambda('lambda st, rvu, st0, st1: (-st[st0][st1]) + (rvu[4*st0 + st1]) == 0', idx_info = [{'st0': 0, 'st1': 0}, {'st0': 0, 'st1': 1}, {'st0': 2, 'st1': 2}, {'st0': 2, 'st1': 3}, {'st0': 3, 'st1': 0}, {'st0': 3, 'st1': 1}, {'st0': 3, 'st1': 2}, {'st0': 3, 'st1': 3}, {'st0': 0, 'st1': 2}, {'st0': 0, 'st1': 3}, {'st0': 1, 'st1': 0}, {'st0': 1, 'st1': 1}, {'st0': 1, 'st1': 2}, {'st0': 1, 'st1': 3}, {'st0': 2, 'st1': 0}, {'st0': 2, 'st1': 1}], tc = {'rvu': [28, 131, 11, 85, 193, 124, 103, 215, 66, 26, 68, 54, 176, 102, 15, 237], 'st': [[28, 131, 11, 85, 133, 46, 179, 20, 227, 148, 225, 197, 38, 221, 221, 126], [193, 124, 103, 215, 106, 229, 162, 168, 166, 78, 144, 234, 199, 254, 152, 250], [66, 26, 68, 54, 206, 16, 155, 248, 231, 198, 240, 43, 208, 205, 213, 26], [176, 102, 15, 237, 49, 141, 213, 97, 137, 155, 50, 243, 112, 51, 124, 107]]}) True """ """ Note: sage_eval vs eval sage_eval works on str of the format 'lambda x,y: 2*x+y' whereas eval works on str of the format 2*x+y directly (no lambda) Also, the result of sage_eval can apply on dicts whose keys are str e.g. f(**{'x':2,'y':3}) whereas the result of eval applies on dict whose keys are variables e.g. f(**{x:2,y:3}) """ if __debug__: assert is_str(f) and 'lambda' in f, f assert (idx_info is None or is_list(idx_info) and all(is_dict(v) for v in idx_info)), indx_info assert is_dict(tc), tc assert all(is_str(k) for k in tc), tc.keys() f = sage_eval(f) vs = f.func_code.co_varnames arrs = [v for v in vs if v in tc] #A,B extfuns = [v for v in vs if v in ExtFun.efdict] idxStr = [v for v in vs if v not in arrs + extfuns] #i,j,k d_tc = dict([(v, tc[v]) for v in arrs]) d_extfun = dict([(v, ExtFun(v).get_fun()) for v in extfuns]) d_ = merge_dict([d_tc, d_extfun]) if idx_info is None: #obtain idxsVals from the pivot array pivotContents = tc[arrs[0]] idxVals = [idx for idx, _ in Miscs.travel(pivotContents)] idx_info = [dict(zip(idxStr, idxV)) for idxV in idxVals] ds = [merge_dict([d_, idx_info_]) for idx_info_ in idx_info] try: return all(f(**d) for d in ds) except IndexError: return False except TypeError: return False except NameError as msg: logger.warn(msg) return False
def _element_constructor_(self, x): """ Convert ``x`` into ``self``. EXAMPLES:: sage: R.<x,y> = FreeAlgebra(QQ,2) sage: R(3) # indirect doctest 3 TESTS:: sage: F.<x,y,z> = FreeAlgebra(GF(5),3) sage: L.<x,y,z> = FreeAlgebra(ZZ,3,implementation='letterplace') sage: F(x) # indirect doctest x sage: F.1*L.2 y*z sage: (F.1*L.2).parent() is F True :: sage: K.<z> = GF(25) sage: F.<a,b,c> = FreeAlgebra(K,3) sage: L.<a,b,c> = FreeAlgebra(K,3, implementation='letterplace') sage: F.1+(z+1)*L.2 b + (z+1)*c Check that :trac:`15169` is fixed:: sage: A.<x> = FreeAlgebra(CC) sage: A(2) 2.00000000000000 We check that the string coercions work correctly over inexact fields:: sage: F.<x,y> = FreeAlgebra(CC) sage: F('2') 2.00000000000000 sage: F('x') 1.00000000000000*x Check that it also converts factorizations:: sage: f = Factorization([(x,2),(y,3)]); f 1.00000000000000*x^2 * 1.00000000000000*y^3 sage: F(f) 1.00000000000000*x^2*y^3 """ if isinstance(x, FreeAlgebraElement): P = x.parent() if P is self: return x if P is not self.base_ring(): return self.element_class(self, x) elif hasattr(x,'letterplace_polynomial'): P = x.parent() if self.has_coerce_map_from(P): # letterplace versus generic ngens = P.ngens() M = self._indices def exp_to_monomial(T): out = [] for i in xrange(len(T)): if T[i]: out.append((i%ngens,T[i])) return M(out) return self.element_class(self, dict([(exp_to_monomial(T),c) for T,c in x.letterplace_polynomial().dict().iteritems()])) # ok, not a free algebra element (or should not be viewed as one). if isinstance(x, basestring): from sage.all import sage_eval G = self.gens() d = {str(v): G[i] for i,v in enumerate(self.variable_names())} return self(sage_eval(x, locals=d)) R = self.base_ring() # coercion from free monoid if isinstance(x, FreeMonoidElement) and x.parent() is self._indices: return self.element_class(self, {x: R.one()}) # coercion from the PBW basis if isinstance(x, PBWBasisOfFreeAlgebra.Element) \ and self.has_coerce_map_from(x.parent()._alg): return self(x.parent().expansion(x)) # Check if it's a factorization from sage.structure.factorization import Factorization if isinstance(x, Factorization): return self.prod(f**i for f,i in x) # coercion via base ring x = R(x) if x == 0: return self.element_class(self, {}) return self.element_class(self, {self.one_basis(): x})
def render_hecke_algebras_webpage(**args): data = None if 'label' in args: lab = clean_input(args.get('label')) if lab != args.get('label'): return redirect( url_for('.render_hecke_algebras_webpage', label=lab), 301) data = db.hecke_algebras.lookup(lab) if data is None: t = "Hecke algebra search error" bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage"))] flash_error( "%s is not a valid label for a Hecke algebra in the database.", lab) return render_template("hecke_algebras-error.html", title=t, properties=[], bread=bread, learnmore=learnmore_list()) info = {} info.update(data) bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage")), ('%s' % data['label'], ' ')] credit = hecke_algebras_credit info['level'] = int(data['level']) info['weight'] = int(data['weight']) info['num_orbits'] = int(data['num_orbits']) dim_count = "not available" proj = [ 'orbit_label', 'hecke_op', 'num_hecke_op', 'Zbasis', 'discriminant', 'disc_fac', 'Qbasis', 'Qalg_gen' ] orb = list(db.hecke_orbits.search({'parent_label': data['label']}, proj)) if orb: #consistency check if len(orb) != int(data['num_orbits']): return search_input_error(info) dim_count = 0 for v in orb: ops = sage_eval(v['hecke_op']) dim = int(matrix(ops[0]).nrows()) dim_count += dim if dim > 4: v['hecke_op_display'] = [] elif dim == 1: v['hecke_op_display'] = [[i + 1, ops[i][0][0]] for i in range(10)] else: v['hecke_op_display'] = [[i + 1, latex(matrix(ops[i]))] for i in range(5)] v['download_op'] = [ (lang, url_for(".render_hecke_algebras_webpage_download", orbit_label=v['orbit_label'], lang=lang, obj='operators')) for lang in ['gp', 'magma', 'sage'] ] if v['Zbasis'] is None: for key in [ 'Zbasis', 'discriminant', 'disc_fac', 'Qbasis', 'Qalg_gen' ]: del v[key] else: v['Zbasis'] = [[int(i) for i in j] for j in v['Zbasis']] v['disc_fac'] = [[int(i) for i in j] for j in v['disc_fac']] if dim > 4: v['gen_display'] = [] elif dim == 1: v['gen_display'] = [v['Zbasis'][0][0]] else: v['gen_display'] = [ latex(matrix(dim, dim, v['Zbasis'][i])) for i in range(dim) ] v['inner_twists'] = "not available" # not yet in the database v['download_gen'] = [ (lang, url_for(".render_hecke_algebras_webpage_download", orbit_label=v['orbit_label'], lang=lang, obj='gen')) for lang in ['gp', 'magma', 'sage'] ] info['orbits'] = orb info['dim_alg'] = dim_count info['l_adic'] = l_range info['properties'] = [('Label', '%s' % info['label']), ('Level', '%s' % info['level']), ('Weight', '%s' % info['weight'])] if info['num_orbits'] != 0: info['friends'] = [('Newforms space ' + info['label'], url_for("cmf.by_url_space_label", level=info['level'], weight=info['weight'], char_orbit_label='a'))] else: info['friends'] = [] t = "Hecke algebra %s" % info['label'] return render_template("hecke_algebras-single.html", info=info, credit=credit, title=t, bread=bread, properties=info['properties'], learnmore=learnmore_list(), friends=info['friends'], KNOWL_ID='hecke_algebra.%s' % (info['label']))
def main(): if len(sys.argv) == 2: print(prime_range(sage_eval(sys.argv[1])))
def _element_constructor_(self, x): """ Convert x into self. EXAMPLES:: sage: R.<x,y> = FreeAlgebra(QQ,2) sage: R(3) # indirect doctest 3 TESTS:: sage: F.<x,y,z> = FreeAlgebra(GF(5),3) sage: L.<x,y,z> = FreeAlgebra(ZZ,3,implementation='letterplace') sage: F(x) # indirect doctest x sage: F.1*L.2 y*z sage: (F.1*L.2).parent() is F True :: sage: K.<z> = GF(25) sage: F.<a,b,c> = FreeAlgebra(K,3) sage: L.<a,b,c> = FreeAlgebra(K,3, implementation='letterplace') sage: F.1+(z+1)*L.2 b + (z+1)*c """ if isinstance(x, FreeAlgebraElement): P = x.parent() if P is self: return x if not (P is self.base_ring()): return self.element_class(self, x) elif hasattr(x,'letterplace_polynomial'): P = x.parent() if self.has_coerce_map_from(P): # letterplace versus generic ngens = P.ngens() M = self.__monoid def exp_to_monomial(T): out = [] for i in xrange(len(T)): if T[i]: out.append((i%ngens,T[i])) return M(out) return self.element_class(self, dict([(exp_to_monomial(T),c) for T,c in x.letterplace_polynomial().dict().iteritems()])) # ok, not a free algebra element (or should not be viewed as one). if isinstance(x, basestring): from sage.all import sage_eval return sage_eval(x,locals=self.gens_dict()) F = self.__monoid R = self.base_ring() # coercion from free monoid if isinstance(x, FreeMonoidElement) and x.parent() is F: return self.element_class(self,{x:R(1)}) # coercion via base ring x = R(x) if x == 0: return self.element_class(self,{}) else: return self.element_class(self,{F(1):x})
def render_hecke_algebras_webpage_l_adic(**args): data = None if 'orbit_label' in args and 'prime' in args: lab = clean_input(args.get('orbit_label')) if lab != args.get('orbit_label'): base_lab=".".join([split(lab)[i] for i in [0,1,2]]) return redirect(url_for('.render_hecke_algebras_webpage', label=base_lab), 301) try: ell = int(args.get('prime')) except ValueError: base_lab=".".join([split(lab)[i] for i in [0,1,2]]) return redirect(url_for('.render_hecke_algebras_webpage', label=base_lab), 301) data = db.hecke_ladic.lucky({'orbit_label': lab , 'ell': ell}) if data is None: t = "Hecke Algebras Search Error" bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage"))] flash(Markup("Error: <span style='color:black'>%s</span> is not a valid label for the ℓ-adic information for an Hecke Algebra orbit in the database." % (lab)),"error") return render_template("hecke_algebras-error.html", title=t, properties=[], bread=bread, learnmore=learnmore_list()) info = {} info.update(data) proj = ['index','orbit_label','ell','idempotent','field','structure','properties','operators'] res = list(db.hecke_ladic.search({'level': data['level'],'weight': data['weight'],'orbit_label': data['orbit_label'], 'ell': data['ell']}, proj)) for f in res: if f['idempotent'] != "": dim = len(sage_eval(f['idempotent'])) l_max = sage_eval(f['idempotent'])[0][0].ndigits() if dim > 4 or l_max > 5: f['idempotent_display'] = [] elif dim == 1: f['idempotent_display'] = sage_eval(f['idempotent'])[0][0] else: f['idempotent_display'] = latex(matrix(sage_eval(f['idempotent']))) else: f['idempotent_display']=latex(matrix([[1]])) del f['idempotent'] f['download_id'] = [(i, url_for(".render_hecke_algebras_webpage_ell_download", orbit_label=f['orbit_label'], index=f['index'], prime=f['ell'], lang=i, obj='idempotents')) for i in ['magma','sage']] # for 'gp' the code does not work, since p-adics are not implemented field = f.pop('field') if field is not None: f['deg'] = field[1] f['field_poly'] = field[2] structure = f.pop('structure') if structure is not None: f['dim'] = structure[0] f['num_gen'] = structure[1] s2 = sage_eval(structure[2]) f['gens'] = [[int(s2.index(i)+1), str(i)] for i in s2] f['rel'] = sage_eval(structure[3]) properties = f.pop('properties') if properties is not None: f['grading'] = properties[0] f['gorenstein_def'] = properties[1] f['gorenstein'] = "yes" if properties[1] == 0 else "no" operators = f.pop('operators') if operators is not None: f['operators_mod_l'] = operators f['num_hecke_op'] = len(operators) f['size_op'] = size = sqrt(len(operators[0])) if size > 4: f['operators_mod_l_display'] = [] elif size == 1: f['operators_mod_l_display'] = [[i+1, operators[i][0]] for i in range(10)] else: f['operators_mod_l_display'] = [[i+1, latex(matrix(size,size,operators[i]))] for i in range(5)] f['download_op'] = [(lang, url_for(".render_hecke_algebras_webpage_ell_download", orbit_label=f['orbit_label'], index=f['index'], prime=f['ell'], lang=lang, obj='operators')) for lang in ['magma','sage']] # for 'gp' the code does not work info['num_l_adic_orbits'] = len(res) info['l_adic_orbits'] = res info['level']=int(data['level']) info['weight']= int(data['weight']) info['base_lab']=".".join([split(data['orbit_label'])[i] for i in [0,1,2]]) info['orbit_label']= str(data['orbit_label']) info['ell']=int(data['ell']) bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage")), ('%s' % info['base_lab'], url_for('.render_hecke_algebras_webpage', label=info['base_lab'])), ('%s' % info['ell'], ' ')] credit = hecke_algebras_credit info['properties'] = [ ('Level', '%s' %info['level']), ('Weight', '%s' %info['weight']), ('Characteristic', '%s' %info['ell']), ('Orbit label', '%s' %info['orbit_label'])] info['friends'] = [('Modular form ' + info['base_lab'], url_for("cmf.by_url_space_label", level=info['level'], weight=info['weight'], char_orbit_label='a'))] t = "%s-adic and mod %s Data for the Hecke Algebra Orbit %s" % (info['ell'], info['ell'], info['orbit_label']) return render_template("hecke_algebras_l_adic-single.html", info=info, credit=credit, title=t, bread=bread, properties2=info['properties'], learnmore=learnmore_list(), friends=info['friends'])
def get_number_from(e): if isinstance(e,unicode): return S.sage_eval(e) else: return e
def _element_constructor_(self, x): """ Convert ``x`` into ``self``. EXAMPLES:: sage: R.<x,y> = FreeAlgebra(QQ,2) sage: R(3) # indirect doctest 3 TESTS:: sage: F.<x,y,z> = FreeAlgebra(GF(5),3) sage: L.<x,y,z> = FreeAlgebra(ZZ,3,implementation='letterplace') sage: F(x) # indirect doctest x sage: F.1*L.2 y*z sage: (F.1*L.2).parent() is F True :: sage: K.<z> = GF(25) sage: F.<a,b,c> = FreeAlgebra(K,3) sage: L.<a,b,c> = FreeAlgebra(K,3, implementation='letterplace') sage: F.1+(z+1)*L.2 b + (z+1)*c Check that :trac:`15169` is fixed:: sage: A.<x> = FreeAlgebra(CC) sage: A(2) 2.00000000000000 """ if isinstance(x, FreeAlgebraElement): P = x.parent() if P is self: return x if not (P is self.base_ring()): return self.element_class(self, x) elif hasattr(x, 'letterplace_polynomial'): P = x.parent() if self.has_coerce_map_from(P): # letterplace versus generic ngens = P.ngens() M = self._basis_keys def exp_to_monomial(T): out = [] for i in xrange(len(T)): if T[i]: out.append((i % ngens, T[i])) return M(out) return self.element_class( self, dict([(exp_to_monomial(T), c) for T, c in x.letterplace_polynomial().dict().iteritems()])) # ok, not a free algebra element (or should not be viewed as one). if isinstance(x, basestring): from sage.all import sage_eval return sage_eval(x, locals=self.gens_dict()) R = self.base_ring() # coercion from free monoid if isinstance(x, FreeMonoidElement) and x.parent() is self._basis_keys: return self.element_class(self, {x: R(1)}) # coercion from the PBW basis if isinstance(x, PBWBasisOfFreeAlgebra.Element) \ and self.has_coerce_map_from(x.parent()._alg): return self(x.parent().expansion(x)) # coercion via base ring x = R(x) if x == 0: return self.element_class(self, {}) return self.element_class(self, {self._basis_keys.one(): x})
def render_hecke_algebras_webpage_l_adic(**args): data = None if 'orbit_label' in args and 'prime' in args: lab = clean_input(args.get('orbit_label')) if lab != args.get('orbit_label'): base_lab=".".join([split(lab)[i] for i in [0,1,2]]) return redirect(url_for('.render_hecke_algebras_webpage', label=base_lab), 301) try: ell = int(args.get('prime')) except ValueError: base_lab=".".join([split(lab)[i] for i in [0,1,2]]) return redirect(url_for('.render_hecke_algebras_webpage', label=base_lab), 301) data = hecke_l_adic_db().find_one({'orbit_label': lab , 'ell': ell}) if data is None: t = "Hecke Algebras Search Error" bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage"))] flash(Markup("Error: <span style='color:black'>%s</span> is not a valid label for the ℓ-adic information for an Hecke Algebra orbit in the database." % (lab)),"error") return render_template("hecke_algebras-error.html", title=t, properties=[], bread=bread, learnmore=learnmore_list()) info = {} info.update(data) res = hecke_l_adic_db().find({'level': data['level'],'weight': data['weight'],'orbit_label': data['orbit_label'], 'ell': data['ell']}) info['num_l_adic_orbits']=res.count() res_clean = [] for f in res: f_clean = {} f_clean['index']=int(f['index']) f_clean['orbit_label']=str(f['orbit_label']) f_clean['ell']=int(f['ell']) if f['idempotent'] != "": f['dim']=len(sage_eval(f['idempotent'])) l_max= sage_eval(f['idempotent'])[0][0].ndigits() if f['dim']>4 or l_max>5: f_clean['idempotent_display']=[] elif f['dim']==1: f_clean['idempotent_display']=sage_eval(f['idempotent'])[0][0] else: f_clean['idempotent_display']=latex(matrix(sage_eval(f['idempotent']))) else: f_clean['idempotent_display']=latex(matrix([[1]])) f_clean['download_id'] = [(i, url_for(".render_hecke_algebras_webpage_ell_download", orbit_label=f_clean['orbit_label'], index=f_clean['index'], prime=f_clean['ell'], lang=i, obj='idempotents')) for i in ['magma','sage']] # for 'gp' the code does not work, since p-adics are not implemented try: f_clean['deg']=int(f['field'][1]) f_clean['field_poly']=str(f['field'][2]) f_clean['dim']=int(f['structure'][0]) f_clean['num_gen']=int(f['structure'][1]) f_clean['gens']=[[int(sage_eval(f['structure'][2]).index(i)+1), str(i)] for i in sage_eval(f['structure'][2])] f_clean['rel']=sage_eval(f['structure'][3]) f_clean['grading']=[int(i) for i in f['properties'][0]] f_clean['gorenstein_def']=int(f['properties'][1]) if f_clean['gorenstein_def']==0: f_clean['gorenstein']="yes" else: f_clean['gorenstein']="no" f_clean['operators_mod_l']=[[int(i) for i in j] for j in f['operators']] f_clean['num_hecke_op']=len(f_clean['operators_mod_l']) f_clean['download_op'] = [(i, url_for(".render_hecke_algebras_webpage_ell_download", orbit_label=f_clean['orbit_label'], index=f_clean['index'], prime=f_clean['ell'], lang=i, obj='operators')) for i in ['magma','sage']] # for 'gp' the code does not work f_clean['size_op']=sqrt(len(f_clean['operators_mod_l'][0])) if f_clean['size_op']>4: f_clean['operators_mod_l_display']=[] elif f_clean['size_op']==1: f_clean['operators_mod_l_display']=[[i+1, f_clean['operators_mod_l'][i][0]] for i in range(0,10)] else: f_clean['operators_mod_l_display']=[[i+1,latex(matrix(f_clean['size_op'],f_clean['size_op'], f_clean['operators_mod_l'][i]))] for i in range(0,5)] res_clean.append(f_clean) except KeyError: pass info['l_adic_orbits']=res_clean info['level']=int(data['level']) info['weight']= int(data['weight']) info['base_lab']=".".join([split(data['orbit_label'])[i] for i in [0,1,2]]) info['orbit_label']= str(data['orbit_label']) info['ell']=int(data['ell']) bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage")), ('%s' % info['base_lab'], url_for('.render_hecke_algebras_webpage', label=info['base_lab'])), ('%s' % info['ell'], ' ')] credit = hecke_algebras_credit info['properties'] = [ ('Level', '%s' %info['level']), ('Weight', '%s' %info['weight']), ('Characteristic', '%s' %info['ell']), ('Orbit label', '%s' %info['orbit_label'])] info['friends'] = [('Modular form ' + info['base_lab'], url_for("emf.render_elliptic_modular_forms", level=info['level'], weight=info['weight'], character=1))] t = "%s-adic and mod %s Data for the Hecke Algebra Orbit %s" % (info['ell'], info['ell'], info['orbit_label']) return render_template("hecke_algebras_l_adic-single.html", info=info, credit=credit, title=t, bread=bread, properties2=info['properties'], learnmore=learnmore_list(), friends=info['friends'])
def render_hecke_algebras_webpage(**args): data = None if 'label' in args: lab = clean_input(args.get('label')) if lab != args.get('label'): return redirect(url_for('.render_hecke_algebras_webpage', label=lab), 301) data = hecke_db().find_one({'label': lab }) if data is None: t = "Hecke Algebras Search Error" bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage"))] flash(Markup("Error: <span style='color:black'>%s</span> is not a valid label for a Hecke Algebras in the database." % (lab)),"error") return render_template("hecke_algebras-error.html", title=t, properties=[], bread=bread, learnmore=learnmore_list()) info = {} info.update(data) bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage")), ('%s' % data['label'], ' ')] credit = hecke_algebras_credit f = hecke_db().find_one({'level': data['level'],'weight': data['weight'],'num_orbits': data['num_orbits']}) info['level']=int(f['level']) info['weight']= int(f['weight']) info['num_orbits']= int(f['num_orbits']) dim_count = "not available" orb = hecke_orbits_db().find({'parent_label': f['label']}).sort([('orbit', ASC)]) if orb.count()!=0: #consistency check if orb.count()!= int(f['num_orbits']): return search_input_error(info) dim_count=0 res_clean = [] for v in orb: v_clean = {} v_clean['orbit_label'] = v['orbit_label'] v_clean['hecke_op'] = v['hecke_op'] v_clean['gen'] = v['gen'] v_clean['dim'] = int(matrix(sage_eval(v_clean['hecke_op'])[0]).dimensions()[0]) dim_count = dim_count + v_clean['dim'] if v_clean['dim']>4: v_clean['hecke_op_display'] = [] elif v_clean['dim']==1: v_clean['hecke_op_display'] = [[i+1, (sage_eval(v_clean['hecke_op'])[i])[0][0]] for i in range(0,10)] else: v_clean['hecke_op_display'] = [[i+1, latex(matrix(sage_eval(v_clean['hecke_op'])[i]))] for i in range(0,5)] v_clean['num_hecke_op'] = v['num_hecke_op'] v_clean['download_op'] = [(i, url_for(".render_hecke_algebras_webpage_download", orbit_label=v_clean['orbit_label'], lang=i, obj='operators')) for i in ['gp', 'magma','sage']] if 'Zbasis' in v.keys(): v_clean['Zbasis'] = [[int(i) for i in j] for j in v['Zbasis']] if v_clean['dim']>4: v_clean['gen_display'] = [] elif v_clean['dim']==1: v_clean['gen_display'] = [v_clean['Zbasis'][0][0]] else: v_clean['gen_display'] = [latex(matrix(v_clean['dim'],v_clean['dim'], v_clean['Zbasis'][i])) for i in range(0,v_clean['dim'])] v_clean['discriminant'] = int(v['discriminant']) v_clean['disc_fac'] = [[int(i) for i in j] for j in v['disc_fac']] v_clean['Qbasis'] = [int(i) for i in v['Qbasis']] v_clean['Qalg_gen'] = [int(i) for i in v['Qalg_gen']] if 'inner_twists' in v.keys(): v_clean['inner_twists'] = [str(i) for i in v['inner_twists']] else: v_clean['inner_twists'] = "not available" v_clean['download_gen'] = [(i, url_for(".render_hecke_algebras_webpage_download", orbit_label=v_clean['orbit_label'], lang=i, obj='gen')) for i in ['gp', 'magma','sage']] res_clean.append(v_clean) info['orbits'] = res_clean info['dim_alg'] = dim_count info['l_adic'] = l_range info['properties'] = [ ('Label', '%s' %info['label']), ('Level', '%s' %info['level']), ('Weight', '%s' %info['weight'])] if info['num_orbits']!=0: info['friends'] = [('Newforms space ' + info['label'], url_for("emf.render_elliptic_modular_forms", level=info['level'], weight=info['weight'], character=1))] else: info['friends'] = [] t = "Hecke Algebra %s" % info['label'] return render_template("hecke_algebras-single.html", info=info, credit=credit, title=t, bread=bread, properties2=info['properties'], learnmore=learnmore_list(), friends=info['friends'])
def as_vector(self): return sage_eval(self.get_value())
def _element_constructor_(self, x): """ Convert x into self. EXAMPLES:: sage: R.<x,y> = FreeAlgebra(QQ,2) sage: R(3) # indirect doctest 3 TESTS:: sage: F.<x,y,z> = FreeAlgebra(GF(5),3) sage: L.<x,y,z> = FreeAlgebra(ZZ,3,implementation='letterplace') sage: F(x) # indirect doctest x sage: F.1*L.2 y*z sage: (F.1*L.2).parent() is F True :: sage: K.<z> = GF(25) sage: F.<a,b,c> = FreeAlgebra(K,3) sage: L.<a,b,c> = FreeAlgebra(K,3, implementation='letterplace') sage: F.1+(z+1)*L.2 b + (z+1)*c """ if isinstance(x, FreeAlgebraElement): P = x.parent() if P is self: return x if not (P is self.base_ring()): return self.element_class(self, x) elif hasattr(x, 'letterplace_polynomial'): P = x.parent() if self.has_coerce_map_from(P): # letterplace versus generic ngens = P.ngens() M = self.__monoid def exp_to_monomial(T): out = [] for i in xrange(len(T)): if T[i]: out.append((i % ngens, T[i])) return M(out) return self.element_class( self, dict([(exp_to_monomial(T), c) for T, c in x.letterplace_polynomial().dict().iteritems()])) # ok, not a free algebra element (or should not be viewed as one). if isinstance(x, basestring): from sage.all import sage_eval return sage_eval(x, locals=self.gens_dict()) F = self.__monoid R = self.base_ring() # coercion from free monoid if isinstance(x, FreeMonoidElement) and x.parent() is F: return self.element_class(self, {x: R(1)}) # coercion via base ring x = R(x) if x == 0: return self.element_class(self, {}) else: return self.element_class(self, {F(1): x})
def eval_lambda(f, idx_info, tc): """ Evaluate array expression p, e.g. p: A[i,j,k]=B[2i+3j+k] if idx_info is specified then only test p on the idxs from idx_info Assumes: the first array in lambda is the pivot lambda A,B,i,j,k: ... => i,j,k belong to A inv = 'lambda B,C,D,i,j: B[i][j]=C[D[2i+3]]' returns true if inv is true on tc Examples: sage: var('a,b,c,i,j') (a, b, c, i, j) sage: InvArray.eval_lambda('lambda a,b,c,i,j: a[i][j]==2*b[i]+c[j]', None, {'a':[[4,-5],[20,11]],'b':[1,9],'c':[2,-7]}) True sage: InvArray.eval_lambda('lambda c,a,b,xor,i: c[i] == xor(a[i],b[i])', None, {'a': [147, 156, 184, 76], 'b': [51, 26, 247, 189], 'c': [160, 334, 79, 281]}) False sage: InvArray.eval_lambda('lambda c,a,b,xor,i1: c[i1] == xor(a[i1],b[i1])', None, {'a': [147, 156, 184, 76], 'b': [51, 26, 247, 189], 'c': [160, 134, 79, 241]}) True sage: InvArray.eval_lambda('lambda rvu, t, rvu1, rvu0: (rvu[rvu0][rvu1]) + (-t[4*rvu0 + rvu1]) == 0', None, {'t': [28, 131, 11, 85, 133, 46, 179, 20, 227, 148, 225, 197, 38, 221, 221, 126], 'rvu': [[28, 131, 11, 85], [133, 46, 179, 20], [227, 148, 225, 197], [38, 221, 221, 126]]}) True #The following illustrate the use of idxVals, #i.e. p is only true under certain array rages sage: InvArray.eval_lambda('lambda st, rvu, st0, st1: (-st[st0][st1]) + (rvu[4*st0 + st1]) == 0', None, tc = {'rvu': [28, 131, 11, 85, 193, 124, 103, 215, 66, 26, 68, 54, 176, 102, 15, 237], 'st': [[28, 131, 11, 85, 133, 46, 179, 20, 227, 148, 225, 197, 38, 221, 221, 126], [193, 124, 103, 215, 106, 229, 162, 168, 166, 78, 144, 234, 199, 254, 152, 250], [66, 26, 68, 54, 206, 16, 155, 248, 231, 198, 240, 43, 208, 205, 213, 26], [176, 102, 15, 237, 49, 141, 213, 97, 137, 155, 50, 243, 112, 51, 124, 107]]}) False sage: InvArray.eval_lambda('lambda st, rvu, st0, st1: (-st[st0][st1]) + (rvu[4*st0 + st1]) == 0', idx_info = [{'st0': 0, 'st1': 0}, {'st0': 0, 'st1': 1}, {'st0': 2, 'st1': 2}, {'st0': 2, 'st1': 3}, {'st0': 3, 'st1': 0}, {'st0': 3, 'st1': 1}, {'st0': 3, 'st1': 2}, {'st0': 3, 'st1': 3}, {'st0': 0, 'st1': 2}, {'st0': 0, 'st1': 3}, {'st0': 1, 'st1': 0}, {'st0': 1, 'st1': 1}, {'st0': 1, 'st1': 2}, {'st0': 1, 'st1': 3}, {'st0': 2, 'st1': 0}, {'st0': 2, 'st1': 1}], tc = {'rvu': [28, 131, 11, 85, 193, 124, 103, 215, 66, 26, 68, 54, 176, 102, 15, 237], 'st': [[28, 131, 11, 85, 133, 46, 179, 20, 227, 148, 225, 197, 38, 221, 221, 126], [193, 124, 103, 215, 106, 229, 162, 168, 166, 78, 144, 234, 199, 254, 152, 250], [66, 26, 68, 54, 206, 16, 155, 248, 231, 198, 240, 43, 208, 205, 213, 26], [176, 102, 15, 237, 49, 141, 213, 97, 137, 155, 50, 243, 112, 51, 124, 107]]}) True """ """ Note: sage_eval vs eval sage_eval works on str of the format 'lambda x,y: 2*x+y' whereas eval works on str of the format 2*x+y directly (no lambda) Also, the result of sage_eval can apply on dicts whose keys are str e.g. f(**{'x':2,'y':3}) whereas the result of eval applies on dict whose keys are variables e.g. f(**{x:2,y:3}) """ if __debug__: assert is_str(f) and 'lambda' in f, f assert (idx_info is None or is_list(idx_info) and all(is_dict(v) for v in idx_info)), indx_info assert is_dict(tc), tc assert all(is_str(k) for k in tc), tc.keys() f = sage_eval(f) vs = f.func_code.co_varnames arrs = [v for v in vs if v in tc] #A,B extfuns = [v for v in vs if v in ExtFun.efdict] idxStr = [v for v in vs if v not in arrs+extfuns] #i,j,k d_tc = dict([(v,tc[v]) for v in arrs]) d_extfun= dict([(v,ExtFun(v).get_fun()) for v in extfuns]) d_ = merge_dict([d_tc,d_extfun]) if idx_info is None: #obtain idxsVals from the pivot array pivotContents = tc[arrs[0]] idxVals = [idx for idx,_ in Miscs.travel(pivotContents)] idx_info = [dict(zip(idxStr,idxV)) for idxV in idxVals] ds = [merge_dict([d_, idx_info_]) for idx_info_ in idx_info] try: return all(f(**d) for d in ds) except IndexError: return False except TypeError: return False except NameError as msg: logger.warn(msg) return False
def _element_constructor_(self, x): """ Convert ``x`` into ``self``. EXAMPLES:: sage: R.<x,y> = FreeAlgebra(QQ,2) sage: R(3) # indirect doctest 3 TESTS:: sage: F.<x,y,z> = FreeAlgebra(GF(5),3) sage: L.<x,y,z> = FreeAlgebra(ZZ,3,implementation='letterplace') sage: F(x) # indirect doctest x sage: F.1*L.2 y*z sage: (F.1*L.2).parent() is F True :: sage: K.<z> = GF(25) sage: F.<a,b,c> = FreeAlgebra(K,3) sage: L.<a,b,c> = FreeAlgebra(K,3, implementation='letterplace') sage: F.1+(z+1)*L.2 b + (z+1)*c Check that :trac:`15169` is fixed:: sage: A.<x> = FreeAlgebra(CC) sage: A(2) 2.00000000000000 """ if isinstance(x, FreeAlgebraElement): P = x.parent() if P is self: return x if not (P is self.base_ring()): return self.element_class(self, x) elif hasattr(x,'letterplace_polynomial'): P = x.parent() if self.has_coerce_map_from(P): # letterplace versus generic ngens = P.ngens() M = self._basis_keys def exp_to_monomial(T): out = [] for i in xrange(len(T)): if T[i]: out.append((i%ngens,T[i])) return M(out) return self.element_class(self, dict([(exp_to_monomial(T),c) for T,c in x.letterplace_polynomial().dict().iteritems()])) # ok, not a free algebra element (or should not be viewed as one). if isinstance(x, basestring): from sage.all import sage_eval return sage_eval(x,locals=self.gens_dict()) R = self.base_ring() # coercion from free monoid if isinstance(x, FreeMonoidElement) and x.parent() is self._basis_keys: return self.element_class(self,{x:R(1)}) # coercion from the PBW basis if isinstance(x, PBWBasisOfFreeAlgebra.Element) \ and self.has_coerce_map_from(x.parent()._alg): return self(x.parent().expansion(x)) # coercion via base ring x = R(x) if x == 0: return self.element_class(self,{}) return self.element_class(self,{self._basis_keys.one():x})
def render_hecke_algebras_webpage(**args): data = None if 'label' in args: lab = clean_input(args.get('label')) if lab != args.get('label'): return redirect(url_for('.render_hecke_algebras_webpage', label=lab), 301) data = db.hecke_algebras.lookup(lab) if data is None: t = "Hecke Algebras Search Error" bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage"))] flash(Markup("Error: <span style='color:black'>%s</span> is not a valid label for a Hecke Algebras in the database." % (lab)),"error") return render_template("hecke_algebras-error.html", title=t, properties=[], bread=bread, learnmore=learnmore_list()) info = {} info.update(data) bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage")), ('%s' % data['label'], ' ')] credit = hecke_algebras_credit info['level']=int(data['level']) info['weight']= int(data['weight']) info['num_orbits']= int(data['num_orbits']) dim_count = "not available" proj = ['orbit_label','hecke_op','num_hecke_op','Zbasis','discriminant','disc_fac','Qbasis','Qalg_gen'] orb = list(db.hecke_orbits.search({'parent_label': data['label']}, proj)) if orb: #consistency check if len(orb) != int(data['num_orbits']): return search_input_error(info) dim_count=0 for v in orb: ops = sage_eval(v['hecke_op']) dim = int(matrix(ops[0]).nrows()) dim_count += dim if dim > 4: v['hecke_op_display'] = [] elif dim == 1: v['hecke_op_display'] = [[i+1, ops[i][0][0]] for i in range(10)] else: v['hecke_op_display'] = [[i+1, latex(matrix(ops[i]))] for i in range(5)] v['download_op'] = [(lang, url_for(".render_hecke_algebras_webpage_download", orbit_label=v['orbit_label'], lang=lang, obj='operators')) for lang in ['gp', 'magma','sage']] if v['Zbasis'] is None: for key in ['Zbasis','discriminant','disc_fac','Qbasis','Qalg_gen']: del v[key] else: v['Zbasis'] = [[int(i) for i in j] for j in v['Zbasis']] v['disc_fac'] = [[int(i) for i in j] for j in v['disc_fac']] if dim > 4: v['gen_display'] = [] elif dim == 1: v['gen_display'] = [v['Zbasis'][0][0]] else: v['gen_display'] = [latex(matrix(dim,dim,v['Zbasis'][i])) for i in range(dim)] v['inner_twists'] = "not available" # not yet in the database v['download_gen'] = [(lang, url_for(".render_hecke_algebras_webpage_download", orbit_label=v['orbit_label'], lang=lang, obj='gen')) for lang in ['gp', 'magma','sage']] info['orbits'] = orb info['dim_alg'] = dim_count info['l_adic'] = l_range info['properties'] = [ ('Label', '%s' %info['label']), ('Level', '%s' %info['level']), ('Weight', '%s' %info['weight'])] if info['num_orbits']!=0: info['friends'] = [('Newforms space ' + info['label'], url_for("cmf.by_url_space_label", level=info['level'], weight=info['weight'], char_orbit_label='a'))] else: info['friends'] = [] t = "Hecke Algebra %s" % info['label'] return render_template("hecke_algebras-single.html", info=info, credit=credit, title=t, bread=bread, properties2=info['properties'], learnmore=learnmore_list(), friends=info['friends'])
def render_hecke_algebras_webpage_l_adic(**args): data = None if 'orbit_label' in args and 'prime' in args: lab = clean_input(args.get('orbit_label')) if lab != args.get('orbit_label'): base_lab = ".".join([split(lab)[i] for i in [0, 1, 2]]) return redirect( url_for('.render_hecke_algebras_webpage', label=base_lab), 301) try: ell = int(args.get('prime')) except ValueError: base_lab = ".".join([split(lab)[i] for i in [0, 1, 2]]) return redirect( url_for('.render_hecke_algebras_webpage', label=base_lab), 301) data = db.hecke_ladic.lucky({'orbit_label': lab, 'ell': ell}) if data is None: t = "Hecke algebra search error" bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage"))] flash_error( "%s is not a valid label for the ℓ-adic information for an Hecke algebra orbit in the database.", lab) return render_template("hecke_algebras-error.html", title=t, properties=[], bread=bread, learnmore=learnmore_list()) info = {} info.update(data) proj = [ 'index', 'orbit_label', 'ell', 'idempotent', 'field', 'structure', 'properties', 'operators' ] res = list( db.hecke_ladic.search( { 'level': data['level'], 'weight': data['weight'], 'orbit_label': data['orbit_label'], 'ell': data['ell'] }, proj)) for f in res: if f['idempotent'] != "": dim = len(sage_eval(f['idempotent'])) l_max = sage_eval(f['idempotent'])[0][0].ndigits() if dim > 4 or l_max > 5: f['idempotent_display'] = [] elif dim == 1: f['idempotent_display'] = sage_eval(f['idempotent'])[0][0] else: f['idempotent_display'] = latex( matrix(sage_eval(f['idempotent']))) else: f['idempotent_display'] = latex(matrix([[1]])) del f['idempotent'] f['download_id'] = [ (i, url_for(".render_hecke_algebras_webpage_ell_download", orbit_label=f['orbit_label'], index=f['index'], prime=f['ell'], lang=i, obj='idempotents')) for i in ['magma', 'sage'] ] # for 'gp' the code does not work, since p-adics are not implemented field = f.pop('field') if field is not None: f['deg'] = field[1] f['field_poly'] = field[2] structure = f.pop('structure') if structure is not None: f['dim'] = structure[0] f['num_gen'] = structure[1] s2 = sage_eval(structure[2]) f['gens'] = [[int(s2.index(i) + 1), str(i)] for i in s2] f['rel'] = sage_eval(structure[3]) properties = f.pop('properties') if properties is not None: f['grading'] = properties[0] f['gorenstein_def'] = properties[1] f['gorenstein'] = "yes" if properties[1] == 0 else "no" operators = f.pop('operators') if operators is not None: f['operators_mod_l'] = operators f['num_hecke_op'] = len(operators) f['size_op'] = size = sqrt(len(operators[0])) if size > 4: f['operators_mod_l_display'] = [] elif size == 1: f['operators_mod_l_display'] = [[i + 1, operators[i][0]] for i in range(10)] else: f['operators_mod_l_display'] = [[ i + 1, latex(matrix(size, size, operators[i])) ] for i in range(5)] f['download_op'] = [ (lang, url_for(".render_hecke_algebras_webpage_ell_download", orbit_label=f['orbit_label'], index=f['index'], prime=f['ell'], lang=lang, obj='operators')) for lang in ['magma', 'sage'] ] # for 'gp' the code does not work info['num_l_adic_orbits'] = len(res) info['l_adic_orbits'] = res info['level'] = int(data['level']) info['weight'] = int(data['weight']) info['base_lab'] = ".".join( [split(data['orbit_label'])[i] for i in [0, 1, 2]]) info['orbit_label'] = str(data['orbit_label']) info['ell'] = int(data['ell']) bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage")), ('%s' % info['base_lab'], url_for('.render_hecke_algebras_webpage', label=info['base_lab'])), ('%s' % info['ell'], ' ')] credit = hecke_algebras_credit info['properties'] = [('Level', '%s' % info['level']), ('Weight', '%s' % info['weight']), ('Characteristic', '%s' % info['ell']), ('Orbit label', '%s' % info['orbit_label'])] info['friends'] = [('Modular form ' + info['base_lab'], url_for("cmf.by_url_space_label", level=info['level'], weight=info['weight'], char_orbit_label='a'))] t = "%s-adic and mod %s data for the Hecke algebra orbit %s" % ( info['ell'], info['ell'], info['orbit_label']) return render_template("hecke_algebras_l_adic-single.html", info=info, credit=credit, title=t, bread=bread, properties=info['properties'], learnmore=learnmore_list(), friends=info['friends'], KNOWL_ID='hecke_algebra_l_adic.%s' % (info['orbit_label']))
def render_hecke_algebras_webpage(**args): data = None if 'label' in args: lab = clean_input(args.get('label')) if lab != args.get('label'): return redirect(url_for('.render_hecke_algebras_webpage', label=lab), 301) data = hecke_db().find_one({'label': lab }) if data is None: t = "Hecke Agebras Search Error" bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage"))] flash(Markup("Error: <span style='color:black'>%s</span> is not a valid label for a Hecke Algebras in the database." % (lab)),"error") return render_template("hecke_algebras-error.html", title=t, properties=[], bread=bread, learnmore=learnmore_list()) info = {} info.update(data) bread = [('HeckeAlgebra', url_for(".hecke_algebras_render_webpage")), ('%s' % data['label'], ' ')] credit = hecke_algebras_credit f = hecke_db().find_one({'level': data['level'],'weight': data['weight'],'num_orbits': data['num_orbits']}) info['level']=int(f['level']) info['weight']= int(f['weight']) info['num_orbits']= int(f['num_orbits']) dim_count = "not available" orb = hecke_orbits_db().find({'parent_label': f['label']}).sort([('orbit', ASC)]) if orb.count()!=0: #consistency check if orb.count()!= int(f['num_orbits']): return search_input_error(info) dim_count=0 res_clean = [] for v in orb: v_clean = {} v_clean['orbit_label'] = v['orbit_label'] v_clean['hecke_op'] = v['hecke_op'] v_clean['gen'] = v['gen'] v_clean['dim'] = int(matrix(sage_eval(v_clean['hecke_op'])[0]).dimensions()[0]) dim_count = dim_count + v_clean['dim'] if v_clean['dim']>4: v_clean['hecke_op_display'] = [] elif v_clean['dim']==1: v_clean['hecke_op_display'] = [[i+1, (sage_eval(v_clean['hecke_op'])[i])[0][0]] for i in range(0,10)] else: v_clean['hecke_op_display'] = [[i+1, latex(matrix(sage_eval(v_clean['hecke_op'])[i]))] for i in range(0,5)] v_clean['num_hecke_op'] = v['num_hecke_op'] v_clean['download_op'] = [(i, url_for(".render_hecke_algebras_webpage_download", orbit_label=v_clean['orbit_label'], lang=i, obj='operators')) for i in ['gp', 'magma','sage']] if 'Zbasis' in v.keys(): v_clean['Zbasis'] = [[int(i) for i in j] for j in v['Zbasis']] if v_clean['dim']>4: v_clean['gen_display'] = [] elif v_clean['dim']==1: v_clean['gen_display'] = [v_clean['Zbasis'][0][0]] else: v_clean['gen_display'] = [latex(matrix(v_clean['dim'],v_clean['dim'], v_clean['Zbasis'][i])) for i in range(0,v_clean['dim'])] v_clean['discriminant'] = int(v['discriminant']) v_clean['disc_fac'] = [[int(i) for i in j] for j in v['disc_fac']] v_clean['Qbasis'] = [int(i) for i in v['Qbasis']] v_clean['Qalg_gen'] = [int(i) for i in v['Qalg_gen']] if 'inner_twists' in v.keys(): v_clean['inner_twists'] = [str(i) for i in v['inner_twists']] else: v_clean['inner_twists'] = "not available" v_clean['download_gen'] = [(i, url_for(".render_hecke_algebras_webpage_download", orbit_label=v_clean['orbit_label'], lang=i, obj='gen')) for i in ['gp', 'magma','sage']] res_clean.append(v_clean) info['orbits'] = res_clean info['dim_alg'] = dim_count info['l_adic'] = l_range info['properties'] = [ ('Label', '%s' %info['label']), ('Level', '%s' %info['level']), ('Weight', '%s' %info['weight'])] if info['num_orbits']!=0: info['friends'] = [('Newforms space ' + info['label'], url_for("emf.render_elliptic_modular_forms", level=info['level'], weight=info['weight'], character=1))] else: info['friends'] = [] t = "Hecke Algebra %s" % info['label'] return render_template("hecke_algebras-single.html", info=info, credit=credit, title=t, bread=bread, properties2=info['properties'], learnmore=learnmore_list(), friends=info['friends'])