Exemple #1
0
    def install_scripts(self):
        scripts_dir = Path("/usr/local/scripts")
        system.gitclone(GIT_SCRIPTS_REPO, scripts_dir)
        system.chown(scripts_dir, self.username, self.username)
        system.link_impl(scripts_dir, self.userhome / "dev" / "scripts")

        p = Path("/etc/profile.d/scripts_path.sh")
        if not p.exists():
            fwrite(p, f"export PATH=$PATH:{str(scripts_dir)}")
Exemple #2
0
 def store(self, dct):
     dct = dict(sorted(dct.items()))
     enc = ""
     if (len(dct) > self.dblimit):
         lst = sorted(dct.items())
         cmd = "rm %s%s" % (self.dir, list(lst)[0][0])
         os.system(cmd)
         cut = dict(list(lst)[1:])
         enc = json.dumps(cut, sort_keys=True)
         self.snapshots_cnt = len(cut)
         self.snapshots = cut
     else:
         dct = dict(sorted(dct.items()))
         enc = json.dumps(dct, sort_keys=True)
         self.snapshots_cnt = len(dct)
         self.snapshots = dct
     util.fwrite(self.dbfile, "w", enc)
Exemple #3
0
def check_listI10(xvec, prec, data, **kwargs):
    list_I10 = kwargs.get('list_I10')
    list_I10_padic = kwargs.get('list_I10_padic')
    base = kwargs.get('base')
    threshold = kwargs.get('threshold')
    outfile = kwargs.get('outfile')
    try:
        j1 = j1_inv_padic_from_xvec(xvec, prec, threshold = .8)
        if j1 is None:
            return ''
    except (ValueError,RuntimeError,PrecisionError):
        return ''
    for I10new, I10p in zip(list_I10,list_I10_padic):
        I2c_list = our_nroot( j1 * I10p, 5, return_all = True)

        for I2c in I2c_list:
            try:
                I2new = recognize_invariant(I2c,base = base,threshold = threshold,prec = prec,  outfile = outfile, twopowlist = range(10))
                fwrite('# Possible I2 = %s'%(I2new),outfile)
                j1, j2, j3 = absolute_igusa_padic_from_xvec(xvec,prec)
                I4new = recognize_invariant(j2 * I10p / I2c**3,base = base,threshold = threshold,prec = prec,  outfile = outfile, twopowlist = range(12))
                fwrite('# Possible I4 = %s'%I4new,outfile)
                I6new = recognize_invariant(j3 * I10p / I2c**2,base = base,threshold = threshold,prec = prec,  outfile = outfile, twopowlist = range(20))
                fwrite('# Possible I6 = %s'%I6new,outfile)
                out_str = '# Candidate = %s, %s, %s, %s (%s)'%(I2new,I4new,I6new,I10new,data)
                return out_str
            except ValueError:
                pass
    return ''
Exemple #4
0
def check_absoluteinvs(xvec,prec,data, **kwargs):
    base = kwargs.get('base')
    threshold = kwargs.get('threshold')
    outfile = kwargs.get('outfile')
    try:
        j1 = j1_inv_padic_from_xvec(xvec, prec, threshold = .8)
        if j1 is None:
            return ''
    except (ValueError,RuntimeError,PrecisionError):
        return ''
    try:
        j1n = recognize_invariant(j1,base = base,threshold = threshold,prec = prec,  outfile = outfile)
        fwrite('# Possible j1 = %s'%(j1n),outfile)
        j1, j2, j3 = absolute_igusa_padic_from_xvec(xvec,prec)
        j2n = recognize_invariant(j2,base = base,threshold = threshold,prec = prec,  outfile = outfile)
        fwrite('# Possible j2 = %s'%(j2n),outfile)
        j3n = recognize_invariant(j3,base = base,threshold = threshold,prec = prec,  outfile = outfile)
        fwrite('# Possible j3 = %s'%(j3n),outfile)
        out_str = '# Candidate js = %s, %s, %s (%s) jpadic = (%s, %s, %s)'%(j1n,j2n,j3n,data, j1,j2,j3)
        return out_str
    except ValueError:
        return ''
Exemple #5
0
def find_igusa_invariants_from_AB(A,B,T,scaling, prec, **kwargs):
    global success_list
    Lambdalist = build_Lambdalist_from_AB(A,B,T, scaling)
    K0 = Lambdalist[0].parent().base_ring()
    p = K0.prime()
    phi = kwargs.get('phi',lambda x:Qp(p,prec)(x))
    mat_coeffs_range = kwargs.get('mat_coeffs_range',3)
    base = kwargs.setdefault('base',QQ)
    if kwargs.has_key('list_I10'):
        list_I10 = kwargs['list_I10']
        kwargs['list_I10_padic'] = [phi(o) for o in list_I10]
    # matlists = kwargs.get('matlists',generate_matlists(Lambdalist,mat_coeffs_range))
    outfile = kwargs.get('outfile')
    K = QuadExt(K0,p)
    total_tests = '?' #len(matlists)
    fwrite('# Starting search for Igusa invariants. Number of tests = %s'%(total_tests), outfile)
    ntests = 0
    success_list = []
    for X, Y, YLXinv, delta in generate_matlists(Lambdalist,mat_coeffs_range):
        data = 'X = %s, Y = %s'%(X.list(),Y.list())
        ntests += 1
        if ntests % 1000 == 0:
            fwrite('# num_tests = %s / %s (successes = %s)'%(ntests, total_tests, len(success_list)), outfile)
        Ag,Bg,_,Dg = YLXinv.list()
        q1inv = (Bg * Dg)**-1
        q2inv = (Bg * Ag)**-1
        q3inv = Bg
        try:
            p1, p2, p3 = K(q1inv).sqrt(), K(q2inv).sqrt(), K(q3inv).sqrt()
            xvec = xvec_padic(p1, p2, p3, q1inv, q2inv, q3inv, prec)
        except (ValueError,RuntimeError,PrecisionError):
            continue
        out_str = check_generic(xvec,prec,data,**kwargs)
        if out_str != '':
            success_list.append(out_str)
            fwrite('# Success! data = %s'%out_str, outfile)
    return success_list
Exemple #6
0
def sudo_nopasswd(user: str):
    fwrite(Path(f"/etc/sudoers.d/01{user}"),
           f"{user} ALL=(ALL) NOPASSWD: ALL\n")
Exemple #7
0
def create_hosts():
    fwrite(Path("/etc/hosts"),
           "127.0.0.1     localhost\n::1           localhost\n")
Exemple #8
0
def set_hostname(hostname: str):
    if hostname:
        fwrite(Path("/etc/hostname"), hostname)
Exemple #9
0
def set_keymap(keymap: str):
    fwrite(Path("/etc/vconsole.conf"), "KEYMAP=" + keymap)
Exemple #10
0
def set_lang(lang: str):
    fwrite(Path("/etc/locale.conf"), "LANG=" + lang)
    shuffle=False,
    class_mode='categorical')
print(valid_generator.class_indices)

label_idxs = sorted(valid_generator.class_indices.items(),
                    key=operator.itemgetter(1))
test_generator = test_datagen.flow_from_directory(
    '/home/zyh/PycharmProjects/baidu_dog/crop_test_img',
    target_size=(299, 299),
    batch_size=batch_size,
    shuffle=False,
    class_mode='categorical')
# print test_generator.filenameenames

from keras.optimizers import SGD
model.compile(optimizer=SGD(lr=0.0001, momentum=0.9),
              loss='categorical_crossentropy',
              metrics=['accuracy'])
y = model.predict_generator(test_generator,
                            10593 / batch_size + 1,
                            use_multiprocessing=True)
y_i = np.argmax(y, 1)
predict_path = 'predict.txt'
if path.exists(predict_path):
    remove(predict_path)
for i, idx in enumerate(y_i):
    fwrite(
        predict_path,
        str(label_idxs[idx][0]).split('_')[-1] + '\t' +
        test_generator.filenames[i][6:-4] + '\n')
Exemple #12
0
def find_curve(P,
               DB,
               NE,
               prec,
               sign_ap=None,
               magma=None,
               return_all=False,
               initial_data=None,
               ramification_at_infinity=None,
               **kwargs):
    r'''
    EXAMPLES:

    First example::

    sage: from darmonpoints.findcurve import find_curve
    sage: find_curve(5,6,30,20) # long time # optional - magma
    # B = F<i,j,k>, with i^2 = -1 and j^2 = 3
    ...
    '(1, 0, 1, -289, 1862)'

    A second example, now over a real quadratic::

    sage: from darmonpoints.findcurve import find_curve
    sage: F.<r> = QuadraticField(5)
    sage: P = F.ideal(3/2*r + 1/2)
    sage: D = F.ideal(3)
    sage: find_curve(P,D,P*D,30,ramification_at_infinity = F.real_places()[:1]) # long time # optional - magma
    ...

    Now over a cubic of mixed signature::

    sage: from darmonpoints.findcurve import find_curve
    sage: F.<r> = NumberField(x^3 -3)
    sage: P = F.ideal(r-2)
    sage: D = F.ideal(r-1)
    sage: find_curve(P,D,P*D,30) # long time # optional - magma
    ...

    '''
    config = ConfigParser.ConfigParser()
    config.read('config.ini')
    param_dict = config_section_map(config, 'General')
    param_dict.update(config_section_map(config, 'FindCurve'))
    param_dict.update(kwargs)
    param = Bunch(**param_dict)

    # Get general parameters
    outfile = param.get('outfile')
    use_ps_dists = param.get('use_ps_dists', False)
    use_shapiro = param.get('use_shapiro', True)
    use_sage_db = param.get('use_sage_db', False)
    magma_seed = param.get('magma_seed', 1515316)
    parallelize = param.get('parallelize', False)
    Up_method = param.get('up_method', 'naive')
    use_magma = param.get('use_magma', True)
    progress_bar = param.get('progress_bar', True)
    sign_at_infinity = param.get('sign_at_infinity', ZZ(1))

    # Get find_curve specific parameters
    grouptype = param.get('grouptype')
    hecke_bound = param.get('hecke_bound', 3)
    timeout = param.get('timeout', 0)
    check_conductor = param.get('check_conductor', True)

    if initial_data is None:
        page_path = os.path.dirname(__file__) + '/KleinianGroups-1.0/klngpspec'
        if magma is None:
            from sage.interfaces.magma import Magma
            quit_when_done = True
            magma = Magma()
        else:
            quit_when_done = False
        if magma_seed is not None:
            magma.eval('SetSeed(%s)' % magma_seed)
        magma.attach_spec(page_path)
        magma.eval('Page_initialized := true')
    else:
        quit_when_done = False

    sys.setrecursionlimit(10**6)

    # global qE, Linv, G, Coh, phiE, xgen, xi1, xi2, Phi

    try:
        F = P.ring()
        Fdisc = F.discriminant()
        if not (P * DB).divides(NE):
            raise ValueError, 'Conductor (NE) should be divisible by P*DB'
        p = ZZ(P.norm()).abs()

    except AttributeError:
        F = QQ
        P = ZZ(P)
        p = ZZ(P)
        Fdisc = ZZ(1)
        if NE % (P * DB) != 0:
            raise ValueError, 'Conductor (NE) should be divisible by P*DB'

    Ncartan = kwargs.get('Ncartan', None)
    Np = NE / (P * DB)
    if Ncartan is not None:
        Np = Np / Ncartan**2
    if use_ps_dists is None:
        use_ps_dists = False  # More efficient our own implementation

    if not p.is_prime():
        raise ValueError, 'P (= %s) should be a prime, of inertia degree 1' % P

    working_prec = max([2 * prec + 10, 100])

    sgninfty = 'plus' if sign_at_infinity == 1 else 'minus'
    fname = 'moments_%s_%s_%s_%s_%s_%s.sobj' % (Fdisc, p, DB, NE, sgninfty,
                                                prec)

    if outfile == 'log':
        outfile = '%s_%s_%s_%s_%s.log' % (
            P, NE, sgninfty, prec,
            datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
        outfile = outfile.replace('/', 'div')
        outfile = '/tmp/findcurve_' + outfile

    if F != QQ and ramification_at_infinity is None:
        if F.signature()[0] > 1:
            if F.signature()[1] == 1:
                ramification_at_infinity = F.real_places(
                    prec=Infinity)  # Totally 'definite'
            else:
                raise ValueError, 'Please specify the ramification at infinity'
        elif F.signature()[0] == 1:
            if len(F.ideal(DB).factor()) % 2 == 0:
                ramification_at_infinity = []  # Split at infinity
            else:
                ramification_at_infinity = F.real_places(
                    prec=Infinity)  # Ramified at infinity
        else:
            ramification_at_infinity = None

    if outfile is not None:
        print("Partial results will be saved in %s" % outfile)

    if initial_data is not None:
        G, phiE = initial_data
    else:
        # Define the S-arithmetic group
        try:
            if F == QQ:
                abtuple = QuaternionAlgebra(DB).invariants()
            else:
                abtuple = quaternion_algebra_invariants_from_ramification(
                    F, DB, ramification_at_infinity)
            G = BigArithGroup(P,
                              abtuple,
                              Np,
                              use_sage_db=use_sage_db,
                              grouptype=grouptype,
                              magma=magma,
                              seed=magma_seed,
                              timeout=timeout,
                              use_shapiro=use_shapiro,
                              nscartan=Ncartan)
        except RuntimeError as e:
            if quit_when_done:
                magma.quit()
            mystr = str(e)
            if len(mystr) > 30:
                mystr = mystr[:14] + ' ... ' + mystr[-14:]
            if return_all:
                return ['Error when computing G: ' + mystr]
            else:
                return 'Error when computing G: ' + mystr

        # Define phiE, the cohomology class associated to the system of eigenvalues.
        Coh = ArithCoh(G)
        try:
            phiE = Coh.get_rational_cocycle(sign=sign_at_infinity,
                                            bound=hecke_bound,
                                            return_all=return_all,
                                            use_magma=True)
        except Exception as e:
            if quit_when_done:
                magma.quit()
            if return_all:
                return ['Error when finding cohomology class: ' + str(e)]
            else:
                return 'Error when finding cohomology class: ' + str(e)
        if use_sage_db:
            G.save_to_db()
        fwrite('Cohomology class found', outfile)
    try:
        ker = [G.inverse_shapiro(o) for o in G.get_homology_kernel()]
    except Exception as e:
        if quit_when_done:
            magma.quit()
        if return_all:
            return ['Problem calculating homology kernel: ' + str(e)]
        else:
            return 'Problem calculating homology kernel: ' + str(e)

    if not return_all:
        phiE = [phiE]
    ret_vals = []
    for phi in phiE:
        try:
            Phi = get_overconvergent_class_quaternionic(
                P,
                phi,
                G,
                prec,
                sign_at_infinity,
                sign_ap,
                use_ps_dists,
                method=Up_method,
                progress_bar=progress_bar)
        except ValueError as e:
            ret_vals.append('Problem when getting overconvergent class: ' +
                            str(e))
            continue
        fwrite('Done overconvergent lift', outfile)
        # Find an element x of Gpn for not in the kernel of phi,
        # and such that both x and wp^-1 * x * wp are trivial in the abelianization of Gn.
        try:
            found = False
            for o in ker:
                phi_o = sum([phi.evaluate(t**a) for t, a in o], 0)
                if use_shapiro:
                    phi_o = phi_o.evaluate_at_identity()
                if phi_o != 0:
                    found = True
                    break
            if not found:
                raise RuntimeError('Cocycle evaluates always to zero')
        except Exception as e:
            ret_vals.append('Problem when choosing element in kernel: ' +
                            str(e))
            continue
        xgenlist = o
        found = False
        while not found:
            try:
                xi1, xi2 = lattice_homology_cycle(G,
                                                  xgenlist,
                                                  working_prec,
                                                  outfile=outfile)
                found = True
            except PrecisionError:
                working_prec = 2 * working_prec
                verbose('Setting working_prec to %s' % working_prec)
            except Exception as e:
                ret_vals.append('Problem when computing homology cycle: ' +
                                str(e))
                verbose('Exception occurred: ' + str(e))
                break
        if not found:
            continue
        try:
            qE1 = integrate_H1(G,
                               xi1,
                               Phi,
                               1,
                               method='moments',
                               prec=working_prec,
                               twist=False,
                               progress_bar=progress_bar)
            qE2 = integrate_H1(G,
                               xi2,
                               Phi,
                               1,
                               method='moments',
                               prec=working_prec,
                               twist=True,
                               progress_bar=progress_bar)
        except Exception as e:
            ret_vals.append('Problem with integration: %s' % str(e))
            continue

        qE = qE1 / qE2
        qE = qE.add_bigoh(prec + qE.valuation())
        Linv = qE.log(p_branch=0) / qE.valuation()

        fwrite('Integral done. Now trying to recognize the curve', outfile)
        fwrite('F.<r> = NumberField(%s)' % (F.gen(0).minpoly()), outfile)
        fwrite('N_E = %s = %s' % (NE, factor(NE)), outfile)
        fwrite('D_B = %s = %s' % (DB, factor(DB)), outfile)
        fwrite('Np = %s = %s' % (Np, factor(Np)), outfile)
        if Ncartan is not None:
            fwrite('Ncartan = %s' % (Ncartan), outfile)
        fwrite(
            'Calculation with p = %s and prec = %s+%s' %
            (P, prec, working_prec - prec), outfile)
        fwrite('qE = %s' % qE, outfile)
        fwrite('Linv = %s' % Linv, outfile)
        curve = discover_equation(qE,
                                  G._F_to_local,
                                  NE,
                                  prec,
                                  check_conductor=check_conductor)
        if curve is None:
            if quit_when_done:
                magma.quit()
            ret_vals.append('None')
        else:
            try:
                curve = curve.global_minimal_model()
            except AttributeError, NotImplementedError:
                pass
            fwrite('EllipticCurve(F, %s )' % (list(curve.a_invariants())),
                   outfile)
            fwrite('=' * 60, outfile)
            ret_vals.append(str(curve.a_invariants()))
Exemple #13
0
    def install_configs(self):
        conf_dirs = [
            self.git_conf_dir(),
            self.xdg_conf_dir(),
            Path("/etc/lightdm"),
            Path("/etc/default"),
            Path("/usr/share/wallpapers"),
            Path("/usr/share/themes"),
            Path("/usr/share/vim/vimfiles/ftdetect"),
            Path("/usr/share/vim/vimfiles/syntax"),
            Path("/usr/share/grub/themes"),
            self.xdg_conf_dir() / "alacritty",
            self.xdg_conf_dir() / "bspwm",
            self.xdg_conf_dir() / "nvim",
            self.xdg_conf_dir() / "polybar",
            self.xdg_conf_dir() / "sxhkd",
            self.xdg_conf_dir() / "termite",
            self.xdg_conf_dir() / "gtk-3.0",
            self.xdg_conf_dir() / "dunst",
            self.xdg_conf_dir() / "rofi",
            self.xdg_conf_dir() / "picom",
            self.xdg_conf_dir() / "zathura",
            self.userhome / "newsboat",
        ]

        for d in conf_dirs:
            d.mkdir(parents=True, exist_ok=True)

        system.link_impl(Path("/usr/share/wallpapers"),
                         self.userhome / "wallpapers")
        system.gitclone(GIT_CONF_REPO, self.git_conf_dir())
        system.link_impl(self.git_conf_dir(),
                         self.userhome / "dev" / "configs")

        conf_files = [
            ".bashrc",
            ".gtkrc-2.0",
            ".gitconfig",
            ".newsboat",
            ".tmux.conf",
            ".xinitrc",
            ".Xresources",
            ".config/alacritty/alacritty.yml",
            ".config/bspwm/bspwmrc",
            ".config/nvim/init.vim",
            ".config/nvim/coc-settings.json",
            ".config/polybar/colors.ini",
            ".config/polybar/config.ini",
            ".config/polybar/modules.ini",
            ".config/sxhkd/sxhkdrc",
            ".config/termite/config",
            ".config/dunst/dunstrc",
            ".config/gtk-3.0/settings.ini",
            ".config/gtk-3.0/gtk.css",
            ".config/picom/picom.conf",
            ".config/rofi/config.rasi",
            ".config/zathura/zathurarc",
        ]

        for f in conf_files:
            system.link(self.git_conf_dir(), f, self.userhome)

        global_files = [
            "/etc/default/grub",
            "/etc/lightdm/lightdm.conf",
            "/etc/lightdm/lightdm-gtk-greeter.conf",
            "/etc/mkinitcpio.conf",
            "/usr/share/vim/vimfiles/syntax/notes.vim",
            "/usr/share/vim/vimfiles/ftdetect/notes.vim",
            "/usr/share/grub/themes/mytheme",
            "/etc/pacman.conf",
        ]

        for f in global_files:
            system.link(self.git_conf_dir(), f, Path("/"))

        system.chmod("+x", self.git_conf_dir() / ".config/bspwm/bspwmrc")

        fwrite(Path("/etc/profile"), "export XDG_CONFIG_DIR=$HOME/.config")

        system.chown(self.git_conf_dir(), self.username, self.username)
        system.chown(self.userhome, self.username, self.username)
Exemple #14
0
def guess_equation(code,pol,Pgen,Dgen,Npgen, Sinf = None,  sign_ap = None, prec = -1, hecke_data_init = None, working_prec = None, recognize_invariants = True, return_all = True, compute_G = True, compute_cohomology = True, abtuple = None, logfile = None, **kwargs):

    config = ConfigParser.ConfigParser()
    config.read('config.ini')
    param_dict = config_section_map(config, 'General')
    param_dict.update(config_section_map(config, 'GuessEquation'))
    param_dict.update(kwargs)
    param = Bunch(**param_dict)

    # Get general parameters
    outfile = param.outfile
    use_ps_dists = param.use_ps_dists
    use_shapiro = param.use_shapiro
    use_sage_db = param.use_sage_db
    magma_seed = param.magma_seed
    parallelize = param.parallelize
    Up_method = param.up_method
    use_magma = param.use_magma
    progress_bar = param.progress_bar
    sign_at_infinity = param.sign_at_infinity

    # Get find_curve specific parameters
    grouptype = param.grouptype
    hecke_bound = param.hecke_bound
    timeout = param.timeout

    if Up_method == "bigmatrix" and use_shapiro == True:
        import warnings
        warnings.warn('Use of "bigmatrix" for Up iteration is incompatible with Shapiro Lemma trick. Using "naive" method for Up.')
        Up_method = 'naive'

    global G, Coh, flist, hecke_data, g0, g1, Alog, Aval, Amul, Blog, Bval, Bmul, Dlog, Dval, Dmul, a, b, T, xi10, xi20, xi11, xi21, Phif
    if pol is None or pol.degree() == 1:
        F = QQ
        P = Pgen
        Pnrm = Pgen
        Pring = QQ
        D = Dgen
        Np = Npgen
        Sinv_places = []
        if abtuple is None:
            abtuple = QuaternionAlgebra(D).invariants()
        else:
            abtuple = (QQ(abtuple[0]), QQ(abtuple[1]))

        if outfile is None:
            outfile = 'periods_%s_%s_%s_%s_%s.sage'%(code,1,P,D,(P*D*Np))
    else:
        F = NumberField(pol, name = 'r')
        r = F.gen()
        P = F.ideal(Pgen)
        Pnrm = P.norm()
        Pring = P.ring()
        D = F.ideal(Dgen)
        Np = F.ideal(Npgen)
        if Sinf is None:
            Sinf = [-1 for i in F.real_places()]
        Sinf_places = [v for v,o in zip(F.real_places(prec = Infinity),Sinf) if o == -1]
        if abtuple is None:
            abtuple = quaternion_algebra_invariants_from_ramification(F,D,Sinf_places)
        else:
            abtuple = (F(abtuple[0]), F(abtuple[1]))
        if outfile is None:
            outfile = 'periods_%s_%s_%s_%s_%s.sage'%(code,F.discriminant().abs(),Pnrm,D.norm(),(P*D*Np).norm())
    if os.path.isfile(outfile):
        return 'Skipping because outfile exists'

    if Pnrm > 31:
        return 'Giving up, prime norm is too large (Pnrm = %s)'%Pnrm
    fwrite('# Starting computation for candidate %s'%str((code,pol,Pgen,Dgen,Npgen,Sinf)),outfile)
    fwrite('p = %s'%Pnrm, outfile)
    if compute_G:
        G = BigArithGroup(P,abtuple,Np,base = F, use_shapiro = use_shapiro, seed = magma_seed, outfile = outfile, use_sage_db = use_sage_db, magma = None, timeout = timeout, grouptype = grouptype, logfile = logfile)
    if compute_cohomology:
        Coh = ArithCoh(G)
        fwrite('# Computed Cohomology group',outfile)
    fwrite('# dim H^1 = %s'%Coh.dimension(),outfile)
    if hecke_data_init is not None and return_all:
        fwrite('# Warning: setting return_all to False because user passed hecke_data_init value', outfile)
        return_all = False

    if return_all:
        all_twodim_cocycles = Coh.get_twodim_cocycle(sign_at_infinity, hecke_data = hecke_data_init, bound = hecke_bound, return_all = True, outfile = outfile)
    else:
        try:
            all_twodim_cocycles = [ Coh.get_twodim_cocycle(sign_at_infinity, hecke_data = hecke_data_init, bound = hecke_bound, return_all = False, outfile = outfile) ]
        except ValueError:
            all_twodim_cocycles = []
    if len(all_twodim_cocycles) == 0:
        fwrite('# Group not attached to surface',outfile)
        fwrite('# DONE WITH COMPUTATION',outfile)
        return 'DONE'
    fwrite('# Obtained cocycles',outfile)
    for flist, hecke_data in all_twodim_cocycles:
        fwrite('Hecke data: %s'%str(hecke_data),outfile)
        g0, g1, scaling = G.get_pseudo_orthonormal_homology(flist, hecke_data = hecke_data, outfile = outfile)
        g0_shapiro, g1_shapiro = G.inverse_shapiro(g0), G.inverse_shapiro(g1)
        fwrite('# Obtained homology generators',outfile)
        if working_prec is None:
            working_prec = max([2 * prec + 10, 30])
        found = False
        while not found:
            try:
                xi10,xi20 = lattice_homology_cycle(G, g0_shapiro, working_prec)
                xi11,xi21 = lattice_homology_cycle(G, g1_shapiro, working_prec)
                found = True
            except PrecisionError:
                working_prec *= 2
                fwrite('# Raising working precision to %s and trying again'%working_prec, outfile)
        fwrite('# Defined homology cycles', outfile)
        Phif = get_overconvergent_class_quaternionic(P, flist[0], G, prec, sign_at_infinity,sign_ap,use_ps_dists = use_ps_dists,use_sage_db = use_sage_db,parallelize = parallelize,method = Up_method, progress_bar = progress_bar)
        fwrite('# Overconvergent lift completed', outfile)

        from integrals import integrate_H1
        numadd, numval, numroot = integrate_H1(G, xi10, Phif, 1, method = 'moments', prec = working_prec, twist = False, progress_bar = progress_bar, multiplicative = False, return_valuation = True)
        denadd, denval, denroot = integrate_H1(G, xi20, Phif, 1, method = 'moments', prec = working_prec, twist = True, progress_bar = progress_bar, multiplicative = False, return_valuation = True)
        Alog = take_to_Qp(numadd - denadd)
        Aval = numval - denval
        Amul = numroot / denroot
        fwrite('# Finished computation of A period', outfile)
        # A = A.add_bigoh(prec + A.valuation())
        fwrite('A0 = p**(%s) * (%s) * (%s).exp()'%(Aval, Amul, Alog), outfile)

        numadd, numval, numroot = integrate_H1(G, xi11, Phif, 1, method = 'moments', prec = working_prec, twist = False, progress_bar = progress_bar, multiplicative = False, return_valuation = True)
        denadd, denval, denroot = integrate_H1(G, xi21,Phif, 1, method = 'moments', prec = working_prec, twist = True, progress_bar = progress_bar, multiplicative = False, return_valuation = True)
        Blog = take_to_Qp(numadd - denadd)
        Bval = numval - denval
        Bmul = numroot / denroot
        fwrite('# Finished computation of B period', outfile)
        # B = B.add_bigoh(prec + B.valuation())
        fwrite('B0 = p**(%s) * (%s) * (%s).exp()'%(Bval, Bmul, Blog), outfile)

        found = False
        for ell, T0 in hecke_data:
            fwrite('ell = %s'%ell, outfile)
            fwrite('T_ell = Matrix(ZZ,2,2,%s)'%str(T0.list()), outfile)
            if T0.charpoly().is_irreducible():
                found = True
                T = T0
                fwrite('# The above is the good T', outfile)
        if not found:
            fwrite('# Good T not found...', outfile)
            return('DONE WITH ERROR')

        Dlog = Alog + T.trace()*Blog
        Dval = Aval + T.trace()*Bval
        Dmul = Amul * Bmul**(ZZ(T.trace()))
        fwrite('D0 = p**(%s) * (%s) * (%s).exp()'%(Dval, Dmul, Dlog), outfile)

        Fp = Alog.parent()
        TFp = T.change_ring(Fp)
        a, b = p_adic_l_invariant_additive(Alog, Blog, Aval, Bval, TFp)
        a = take_to_Qp(a)
        b = take_to_Qp(b)
        Lp = a + b * T
        fwrite('a = %s'%a, outfile)
        fwrite('b = %s'%b, outfile)
        fwrite('Lp = Matrix(2,2,%s)'%str(Lp.list()), outfile)
        if recognize_invariants:
               K0 = Qq(Pnrm**2, prec,names = 's')
               A = K0(take_to_Qp(Pnrm**Aval * Alog.exp() * Amul))
               B = K0(take_to_Qp(Pnrm**Bval * Blog.exp() * Bmul))
               if not param_dict.has_key('list_I10'):
                   param_dict['list_I10'] = generate_listI10(G.F, G.ideal_p*G.discriminant*G.level)
               param_dict['outfile'] = outfile
               find_igusa_invariants_from_AB(A, B, T, scaling, prec = prec, phi = G._F_to_local, **param_dict)
    fwrite('# DONE WITH COMPUTATION', outfile)
    return('DONE')
Exemple #15
0
def find_igusa_invariants(a, b, T, embedding, prec = None, outfile = None, list_I10 = None, Pgen = None, N = 6, cheatjs = None, parallelize = True):
    fwrite('# Trying to recognize invariants...',outfile)
    Pring = embedding.domain()
    if prec is None:
        prec = a.parent().precision_cap()
    Tlist = []
    fT = T.charpoly()
    fT_trace = -fT.list()[1]
    for x0,y,z in product(range(-N, N+1), range(-N, N+1), range(-N, N+1)):
        t = fT_trace - x0
        if x0*t - y*z == fT.list()[0]:
            M = matrix(ZZ,2,2,[x0,y,z,t])
            assert fT == M.charpoly()
            Tlist.append(M)
    Tlist = sorted(Tlist, key = lambda x: max(x[0,0].abs(), x[0,1].abs(), x[1,0].abs(), x[1,1].abs()))
    for ii, tt in enumerate(Tlist):
        fwrite('# Doing matrix %s / %s ( = %s)'%(ii,len(Tlist),tt.list()),outfile)
        Lp = a + b * tt
        inp_vec = [(Lp, ordmat, prec, Pring, cheatjs, embedding, 3, list_I10, Pgen, outfile) for ordmat in all_possible_ordmats(Lp,20)]

        num_inpts = len(inp_vec)
        jj = 0
        if parallelize:
            for inpt, outt in parallel(find_igusa_invariants_from_L_inv)(inp_vec):
                jj += 1
                if outt != 'Nope' and outt != '' and 'indistinguishable' not in outt and 'Error' not in outt:
                    fwrite('# (%s/%s) %s %s %s %s'%(jj, num_inpts, str(tt.list()), str(inpt[0][0].list()),str(inpt[0][1].list()),str(outt)), outfile)
                elif outt != 'Nope':
                    fwrite('# (%s/%s) (%s)...Out: %s'%(jj, num_inpts, inpt[0][1].list(),str(outt)), outfile)
        else:
            for inpt in inp_vec:
                outt = find_igusa_invariants_from_L_inv(*inpt)
                jj += 1
                if outt != 'Nope' and outt != '' and 'indistinguishable' not in outt and 'Error' not in outt:
                    fwrite('# (%s/%s) %s %s %s %s'%(jj, num_inpts, str(tt.list()), str(inpt[0][0].list()),str(inpt[0][1].list()),str(outt)), outfile)
                elif outt != 'Nope':
                    fwrite('# (%s/%s) (%s)...Out: %s'%(jj, num_inpts, inpt[0][1].list(),str(outt)), outfile)
Exemple #16
0
def find_curve(P, DB, NE, prec, sign_ap = None, magma = None, return_all = False, initial_data = None, ramification_at_infinity = None, **kwargs):
    r'''
    EXAMPLES:

    First example::

    sage: from darmonpoints.findcurve import find_curve
    sage: find_curve(5,6,30,20) # long time # optional - magma
    # B = F<i,j,k>, with i^2 = -1 and j^2 = 3
    ...
    '(1, 0, 1, -289, 1862)'

    A second example, now over a real quadratic::

    sage: from darmonpoints.findcurve import find_curve
    sage: F.<r> = QuadraticField(5)
    sage: P = F.ideal(3/2*r + 1/2)
    sage: D = F.ideal(3)
    sage: find_curve(P,D,P*D,30,ramification_at_infinity = F.real_places()[:1]) # long time # optional - magma
    ...

    Now over a cubic of mixed signature::

    sage: from darmonpoints.findcurve import find_curve
    sage: F.<r> = NumberField(x^3 -3)
    sage: P = F.ideal(r-2)
    sage: D = F.ideal(r-1)
    sage: find_curve(P,D,P*D,30) # long time # optional - magma
    ...

    '''
    config = ConfigParser.ConfigParser()
    config.read('config.ini')
    param_dict = config_section_map(config, 'General')
    param_dict.update(config_section_map(config, 'FindCurve'))
    param_dict.update(kwargs)
    param = Bunch(**param_dict)

    # Get general parameters
    outfile = param.get('outfile')
    use_ps_dists = param.get('use_ps_dists',False)
    use_shapiro = param.get('use_shapiro',True)
    use_sage_db = param.get('use_sage_db',False)
    magma_seed = param.get('magma_seed',1515316)
    parallelize = param.get('parallelize',False)
    Up_method = param.get('up_method','naive')
    use_magma = param.get('use_magma',True)
    progress_bar = param.get('progress_bar',True)
    sign_at_infinity = param.get('sign_at_infinity',ZZ(1))

    # Get find_curve specific parameters
    grouptype = param.get('grouptype')
    hecke_bound = param.get('hecke_bound',3)
    timeout = param.get('timeout',0)
    check_conductor = param.get('check_conductor',True)

    if initial_data is None:
        page_path = os.path.dirname(__file__) + '/KleinianGroups-1.0/klngpspec'
        if magma is None:
            from sage.interfaces.magma import Magma
            quit_when_done = True
            magma = Magma()
        else:
            quit_when_done = False
        if magma_seed is not None:
            magma.eval('SetSeed(%s)'%magma_seed)
        magma.attach_spec(page_path)
        magma.eval('Page_initialized := true')
    else:
        quit_when_done = False

    sys.setrecursionlimit(10**6)

    # global qE, Linv, G, Coh, phiE, xgen, xi1, xi2, Phi

    try:
        F = P.ring()
        Fdisc = F.discriminant()
        if not (P*DB).divides(NE):
            raise ValueError,'Conductor (NE) should be divisible by P*DB'
        p = ZZ(P.norm()).abs()

    except AttributeError:
        F = QQ
        P = ZZ(P)
        p = ZZ(P)
        Fdisc = ZZ(1)
        if NE % (P*DB) != 0:
            raise ValueError,'Conductor (NE) should be divisible by P*DB'

    Ncartan = kwargs.get('Ncartan',None)
    Np = NE / (P * DB)
    if Ncartan is not None:
        Np = Np / Ncartan**2
    if use_ps_dists is None:
        use_ps_dists = False # More efficient our own implementation

    if not p.is_prime():
        raise ValueError,'P (= %s) should be a prime, of inertia degree 1'%P

    working_prec = max([2 * prec + 10, 100])

    sgninfty = 'plus' if sign_at_infinity == 1 else 'minus'
    fname = 'moments_%s_%s_%s_%s_%s_%s.sobj'%(Fdisc,p,DB,NE,sgninfty,prec)

    if outfile == 'log':
        outfile = '%s_%s_%s_%s_%s.log'%(P,NE,sgninfty,prec,datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
        outfile = outfile.replace('/','div')
        outfile = '/tmp/findcurve_' + outfile

    if F != QQ and ramification_at_infinity is None:
        if F.signature()[0] > 1:
            if F.signature()[1] == 1:
                ramification_at_infinity = F.real_places(prec = Infinity) # Totally 'definite'
            else:
                raise ValueError,'Please specify the ramification at infinity'
        elif F.signature()[0] == 1:
            if len(F.ideal(DB).factor()) % 2 == 0:
                ramification_at_infinity = [] # Split at infinity
            else:
                ramification_at_infinity = F.real_places(prec = Infinity) # Ramified at infinity
        else:
            ramification_at_infinity = None

    if outfile is not None:
        print("Partial results will be saved in %s"%outfile)

    if initial_data is not None:
        G,phiE = initial_data
    else:
        # Define the S-arithmetic group
        try:
            if F == QQ:
                abtuple = QuaternionAlgebra(DB).invariants()
            else:
                abtuple = quaternion_algebra_invariants_from_ramification(F,DB,ramification_at_infinity)
            G = BigArithGroup(P, abtuple, Np, use_sage_db = use_sage_db, grouptype = grouptype, magma = magma, seed = magma_seed, timeout = timeout, use_shapiro = use_shapiro, nscartan = Ncartan)
        except RuntimeError as e:
            if quit_when_done:
                magma.quit()
            mystr = str(e)
            if len(mystr) > 30:
                mystr = mystr[:14] + ' ... ' + mystr[-14:]
            if return_all:
                return ['Error when computing G: ' + mystr]
            else:
                return 'Error when computing G: ' + mystr

        # Define phiE, the cohomology class associated to the system of eigenvalues.
        Coh = ArithCoh(G)
        try:
            phiE = Coh.get_rational_cocycle(sign = sign_at_infinity,bound = hecke_bound,return_all = return_all,use_magma = True)
        except Exception as e:
            if quit_when_done:
                magma.quit()
            if return_all:
                return ['Error when finding cohomology class: ' + str(e)]
            else:
                return 'Error when finding cohomology class: ' + str(e)
        if use_sage_db:
            G.save_to_db()
        fwrite('Cohomology class found', outfile)
    try:
        ker = [G.inverse_shapiro(o) for o in G.get_homology_kernel()]
    except Exception as e:
        if quit_when_done:
            magma.quit()
        if return_all:
            return ['Problem calculating homology kernel: ' + str(e)]
        else:
            return 'Problem calculating homology kernel: ' + str(e)

    if not return_all:
        phiE = [phiE]
    ret_vals = []
    for phi in phiE:
        try:
            Phi = get_overconvergent_class_quaternionic(P,phi,G,prec,sign_at_infinity,sign_ap,use_ps_dists,method = Up_method, progress_bar = progress_bar)
        except ValueError as e:
            ret_vals.append('Problem when getting overconvergent class: ' + str(e))
            continue
        fwrite('Done overconvergent lift', outfile)
        # Find an element x of Gpn for not in the kernel of phi,
        # and such that both x and wp^-1 * x * wp are trivial in the abelianization of Gn.
        try:
            found = False
            for o in ker:
                phi_o = sum( [phi.evaluate(t**a) for t, a in o], 0 )
                if use_shapiro:
                    phi_o = phi_o.evaluate_at_identity()
                if phi_o != 0:
                    found = True
                    break
            if not found:
                raise RuntimeError('Cocycle evaluates always to zero')
        except Exception as e:
            ret_vals.append('Problem when choosing element in kernel: ' + str(e))
            continue
        xgenlist = o
        found = False
        while not found:
            try:
                xi1, xi2 = lattice_homology_cycle(G,xgenlist,working_prec,outfile = outfile)
                found = True
            except PrecisionError:
                working_prec  = 2 * working_prec
                verbose('Setting working_prec to %s'%working_prec)
            except Exception as e:
                ret_vals.append('Problem when computing homology cycle: ' + str(e))
                verbose('Exception occurred: ' + str(e))
                break
        if not found:
            continue
        try:
            qE1 = integrate_H1(G,xi1,Phi,1,method = 'moments',prec = working_prec, twist = False,progress_bar = progress_bar)
            qE2 = integrate_H1(G,xi2,Phi,1,method = 'moments',prec = working_prec, twist = True,progress_bar = progress_bar)
        except Exception as e:
            ret_vals.append('Problem with integration: %s'%str(e))
            continue

        qE = qE1/qE2
        qE = qE.add_bigoh(prec + qE.valuation())
        Linv = qE.log(p_branch = 0)/qE.valuation()

        fwrite('Integral done. Now trying to recognize the curve', outfile)
        fwrite('F.<r> = NumberField(%s)'%(F.gen(0).minpoly()),outfile)
        fwrite('N_E = %s = %s'%(NE,factor(NE)),outfile)
        fwrite('D_B = %s = %s'%(DB,factor(DB)),outfile)
        fwrite('Np = %s = %s'%(Np,factor(Np)),outfile)
        if Ncartan is not None:
            fwrite('Ncartan = %s'%(Ncartan),outfile)
        fwrite('Calculation with p = %s and prec = %s+%s'%(P,prec,working_prec-prec),outfile)
        fwrite('qE = %s'%qE,outfile)
        fwrite('Linv = %s'%Linv,outfile)
        curve = discover_equation(qE,G._F_to_local,NE,prec,check_conductor = check_conductor)
        if curve is None:
            if quit_when_done:
                magma.quit()
            ret_vals.append('None')
        else:
            try:
                curve = curve.global_minimal_model()
            except AttributeError,NotImplementedError:
                pass
            fwrite('EllipticCurve(F, %s )'%(list(curve.a_invariants())), outfile)
            fwrite('=' * 60, outfile)
            ret_vals.append(str(curve.a_invariants()))
Exemple #17
0
                                                   shuffle=False,
                                                   class_mode='categorical')
print(valid_generator.class_indices)

label_idxs = sorted(valid_generator.class_indices.items(),
                    key=operator.itemgetter(1))
test_generator = test_datagen.flow_from_directory('/hdd/cwh/test',
                                                  target_size=(299, 299),
                                                  batch_size=batch_size,
                                                  shuffle=False,
                                                  class_mode='categorical')
# print test_generator.filenameenames

from keras.optimizers import SGD

model.compile(optimizer=SGD(lr=0.0001, momentum=0.9),
              loss='categorical_crossentropy',
              metrics=['accuracy'])
y = model.predict_generator(test_generator,
                            10593 / batch_size + 1,
                            use_multiprocessing=True)
y_i = np.argmax(y, 1)
predict_path = 'predict.txt'
if path.exists(predict_path):
    remove(predict_path)
for i, idx in enumerate(y_i):
    fwrite(
        predict_path,
        str(label_idxs[idx][0]) + '\t' + test_generator.filenames[i][2:-4] +
        '\n')
Exemple #18
0
def darmon_point(P, E, beta, prec, ramification_at_infinity = None, input_data = None, magma = None, working_prec = None, **kwargs):
    r'''

    EXAMPLES:

    We first need to import the module::

    sage: from darmonpoints.darmonpoints import darmon_point

    A first example (Stark--Heegner point)::

    sage: from darmonpoints.darmonpoints import darmon_point
    sage: darmon_point(7,EllipticCurve('35a1'),41,20, cohomological=False, use_magma=False, use_ps_dists = True)
    Starting computation of the Darmon point
    ...
    (-70*alpha + 449 : 2100*alpha - 13444 : 1)

    A quaternionic (Greenberg) point::

    sage: darmon_point(13,EllipticCurve('78a1'),5,20) # long time # optional - magma

    A Darmon point over a cubic (1,1) field::

    sage: F.<r> = NumberField(x^3 - x^2 - x + 2)
    sage: E = EllipticCurve([-r -1, -r, -r - 1,-r - 1, 0])
    sage: N = E.conductor()
    sage: P = F.ideal(r^2 - 2*r - 1)
    sage: beta = -3*r^2 + 9*r - 6
    sage: darmon_point(P,E,beta,20) # long time # optional - magma

    '''
    # global G, Coh, phiE, Phi, dK, J, J1, cycleGn, nn, Jlist

    config = ConfigParser.ConfigParser()
    config.read('config.ini')
    param_dict = config_section_map(config, 'General')
    param_dict.update(config_section_map(config, 'DarmonPoint'))
    param_dict.update(kwargs)
    param = Bunch(**param_dict)

    # Get general parameters
    outfile = param.get('outfile')
    use_ps_dists = param.get('use_ps_dists',False)
    use_shapiro = param.get('use_shapiro',True)
    use_sage_db = param.get('use_sage_db',False)
    magma_seed = param.get('magma_seed',1515316)
    parallelize = param.get('parallelize',False)
    Up_method = param.get('up_method','naive')
    use_magma = param.get('use_magma',True)
    progress_bar = param.get('progress_bar',True)
    sign_at_infinity = param.get('sign_at_infinity',ZZ(1))

    # Get darmon_point specific parameters
    idx_orientation = param.get('idx_orientation')
    idx_embedding = param.get('idx_embedding',0)
    algorithm = param.get('algorithm')
    quaternionic = param.get('quaternionic')
    cohomological = param.get('cohomological',True)

    if Up_method == "bigmatrix" and use_shapiro == True:
        import warnings
        warnings.warn('Use of "bigmatrix" for Up iteration is incompatible with Shapiro Lemma trick. Using "naive" method for Up.')
        Up_method = 'naive'

    if working_prec is None:
        working_prec = max([2 * prec + 10, 30])

    if use_magma:
        page_path = os.path.dirname(__file__) + '/KleinianGroups-1.0/klngpspec'
        if magma is None:
            from sage.interfaces.magma import Magma
            magma = Magma()
            quit_when_done = True
        else:
            quit_when_done = False
        magma.attach_spec(page_path)
    else:
        quit_when_done = False

    sys.setrecursionlimit(10**6)

    F = E.base_ring()
    beta = F(beta)
    DB,Np,Ncartan = get_heegner_params(P,E,beta)
    if quaternionic is None:
        quaternionic = ( DB != 1 )
    if cohomological is None:
        cohomological = quaternionic
    if quaternionic and not cohomological:
        raise ValueError("Need cohomological algorithm when dealing with quaternions")
    if use_ps_dists is None:
        use_ps_dists = False if cohomological else True
    try:
        p = ZZ(P)
    except TypeError:
        p = ZZ(P.norm())
    if not p.is_prime():
        raise ValueError,'P (= %s) should be a prime, of inertia degree 1'%P

    if F == QQ:
        dK = ZZ(beta)
        extra_conductor_sq = dK/fundamental_discriminant(dK)
        assert ZZ(extra_conductor_sq).is_square()
        extra_conductor = extra_conductor_sq.sqrt()
        dK = dK / extra_conductor_sq
        assert dK == fundamental_discriminant(dK)
        if dK % 4 == 0:
            dK = ZZ(dK/4)
        beta = dK
    else:
        dK = beta

    # Compute the completion of K at p
    x = QQ['x'].gen()
    K = F.extension(x*x - dK,names = 'alpha')
    if F == QQ:
        dK = K.discriminant()
    else:
        dK = K.relative_discriminant()

    hK = K.class_number()

    sgninfty = 'plus' if sign_at_infinity == 1 else 'minus'
    if hasattr(E,'cremona_label'):
        Ename = E.cremona_label()
    elif hasattr(E,'ainvs'):
        Ename = E.ainvs()
    else:
        Ename = 'unknown'
    fname = 'moments_%s_%s_%s_%s.sobj'%(P,Ename,sgninfty,prec)

    if use_sage_db:
        print("Moments will be stored in database as %s"%(fname))

    if outfile == 'log':
        outfile = '%s_%s_%s_%s_%s_%s.log'%(P,Ename,dK,sgninfty,prec,datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
        outfile = outfile.replace('/','div')
        outfile = '/tmp/darmonpoint_' + outfile

    fwrite("Starting computation of the Darmon point",outfile)
    fwrite('D_B = %s  %s'%(DB,factor(DB)),outfile)
    fwrite('Np = %s'%Np,outfile)
    if Ncartan is not None:
        fwrite('Ncartan = %s'%Ncartan,outfile)
    fwrite('dK = %s (class number = %s)'%(dK,hK),outfile)
    fwrite('Calculation with p = %s and prec = %s'%(P,prec),outfile)
    fwrite('Elliptic curve %s: %s'%(Ename,E),outfile)
    if outfile is not None:
        print("Partial results will be saved in %s"%outfile)

    if input_data is None:
        if cohomological:
            # Define the S-arithmetic group
            if F != QQ and ramification_at_infinity is None:
                if F.signature()[0] > 1:
                    if F.signature()[1] == 1:
                        ramification_at_infinity = F.real_places(prec = Infinity) # Totally 'definite'
                    else:
                        raise ValueError,'Please specify the ramification at infinity'
                elif F.signature()[0] == 1:
                    if len(F.ideal(DB).factor()) % 2 == 0:
                        ramification_at_infinity = [] # Split at infinity
                    else:
                        ramification_at_infinity = F.real_places(prec = Infinity) # Ramified at infinity
                else:
                    ramification_at_infinity = None
            if F == QQ:
                abtuple = QuaternionAlgebra(DB).invariants()
            else:
                abtuple = quaternion_algebra_invariants_from_ramification(F, DB, ramification_at_infinity)

            G = BigArithGroup(P,abtuple,Np,base = F,outfile = outfile,seed = magma_seed,use_sage_db = use_sage_db,magma = magma, use_shapiro = use_shapiro, nscartan=Ncartan)

            # Define the cycle ( in H_1(G,Div^0 Hp) )
            Coh = ArithCoh(G)
            while True:
                try:
                    cycleGn,nn,ell = construct_homology_cycle(G,beta,working_prec,lambda q: Coh.hecke_matrix(q).minpoly(), outfile = outfile, elliptic_curve = E)
                    break
                except PrecisionError:
                    working_prec *= 2
                    verbose('Encountered precision error, trying with higher precision (= %s)'%working_prec)
                except ValueError:
                    fwrite('ValueError occurred when constructing homology cycle. Returning the S-arithmetic group.', outfile)
                    if quit_when_done:
                        magma.quit()
                    return G
                except AssertionError as e:
                    fwrite('Assertion occurred when constructing homology cycle. Returning the S-arithmetic group.', outfile)
                    fwrite('%s'%str(e), outfile)
                    if quit_when_done:
                        magma.quit()
                    return G
            eisenstein_constant = -ZZ(E.reduction(ell).count_points())
            fwrite('r = %s, so a_r(E) - r - 1 = %s'%(ell,eisenstein_constant), outfile)
            fwrite('exponent = %s'%nn, outfile)
            phiE = Coh.get_cocycle_from_elliptic_curve(E, sign = sign_at_infinity)
            if hasattr(E,'ap'):
                sign_ap = E.ap(P)
            else:
                try:
                    sign_ap = ZZ(P.norm() + 1 - E.reduction(P).count_points())
                except ValueError:
                    sign_ap = ZZ(P.norm() + 1 - Curve(E).change_ring(P.residue_field()).count_points(1)[0])

            Phi = get_overconvergent_class_quaternionic(P,phiE,G,prec,sign_at_infinity,sign_ap,use_ps_dists = use_ps_dists,use_sage_db = use_sage_db,parallelize = parallelize,method = Up_method, progress_bar = progress_bar,Ename = Ename)
            # Integration with moments
            tot_time = walltime()
            J = integrate_H1(G,cycleGn,Phi,1,method = 'moments',prec = working_prec,parallelize = parallelize,twist = True,progress_bar = progress_bar)
            verbose('integration tot_time = %s'%walltime(tot_time))
            if use_sage_db:
                G.save_to_db()
        else: # not cohomological
            nn = 1
            eisenstein_constant = 1
            if algorithm is None:
                if Np == 1:
                    algorithm = 'darmon_pollack'
                else:
                    algorithm = 'guitart_masdeu'
            w = K.maximal_order().ring_generators()[0]
            r0,r1 = w.coordinates_in_terms_of_powers()(K.gen())
            QQp = Qp(p,working_prec)
            Cp = QQp.extension(w.minpoly().change_ring(QQp),names = 'g')
            v0 = K.hom([r0 + r1 * Cp.gen()])

            # Optimal embeddings of level one
            fwrite("Computing optimal embeddings of level one...", outfile)
            Wlist = find_optimal_embeddings(K,use_magma = use_magma, extra_conductor = extra_conductor)
            fwrite("Found %s such embeddings."%len(Wlist), outfile)
            if idx_embedding is not None:
                if idx_embedding >= len(Wlist):
                    fwrite('There are not enough embeddings. Taking the index modulo %s'%len(Wlist), outfile)
                    idx_embedding = idx_embedding % len(Wlist)
                fwrite('Taking only embedding number %s'%(idx_embedding), outfile)
                Wlist = [Wlist[idx_embedding]]

            # Find the orientations
            orients = K.maximal_order().ring_generators()[0].minpoly().roots(Zmod(Np),multiplicities = False)
            fwrite("Possible orientations: %s"%orients, outfile)
            if len(Wlist) == 1 or idx_orientation == -1:
                fwrite("Using all orientations, since hK = 1", outfile)
                chosen_orientation = None
            else:
                fwrite("Using orientation = %s"%orients[idx_orientation], outfile)
                chosen_orientation = orients[idx_orientation]

            emblist = []
            for i,W in enumerate(Wlist):
                tau, gtau,sign,limits = find_tau0_and_gtau(v0,Np,W,algorithm = algorithm,orientation = chosen_orientation,extra_conductor = extra_conductor)
                fwrite('n_evals = %s'%sum((num_evals(t1,t2) for t1,t2 in limits)), outfile)
                emblist.append((tau,gtau,sign,limits))

            # Get the cohomology class from E
            Phi = get_overconvergent_class_matrices(P,E,prec,sign_at_infinity,use_ps_dists = use_ps_dists,use_sage_db = use_sage_db,parallelize = parallelize,progress_bar = progress_bar)

            J = 1
            Jlist = []
            for i,emb in enumerate(emblist):
                fwrite("Computing %s-th period, attached to the embedding: %s"%(i,Wlist[i].list()), outfile)
                tau, gtau,sign,limits = emb
                n_evals = sum((num_evals(t1,t2) for t1,t2 in limits))
                fwrite("Computing one period...(total of %s evaluations)"%n_evals, outfile)
                newJ = prod((double_integral_zero_infty(Phi,t1,t2) for t1,t2 in limits))**ZZ(sign)
                Jlist.append(newJ)
                J *= newJ
    else: # input_data is not None
        Phi,J = input_data[1:3]
    fwrite('Integral done. Now trying to recognize the point', outfile)
    fwrite('J_psi = %s'%J,outfile)
    fwrite('g belongs to %s'%J.parent(),outfile)
    #Try to recognize a generator
    if quaternionic:
        local_embedding = G.base_ring_local_embedding(working_prec)
        twopowlist = [4, 3, 2, 1, QQ(1)/2, QQ(3)/2, QQ(1)/3, QQ(2)/3, QQ(1)/4, QQ(3)/4, QQ(5)/2, QQ(4)/3]
    else:
        local_embedding = Qp(p,working_prec)
        twopowlist = [4, 3, 2, 1, QQ(1)/2, QQ(3)/2, QQ(1)/3, QQ(2)/3, QQ(1)/4, QQ(3)/4, QQ(5)/2, QQ(4)/3]

    known_multiple = QQ(nn * eisenstein_constant) # It seems that we are not getting it with present algorithm.
    while known_multiple % p == 0:
        known_multiple = ZZ(known_multiple / p)

    candidate,twopow,J1 = recognize_J(E,J,K,local_embedding = local_embedding,known_multiple = known_multiple,twopowlist = twopowlist,prec = prec, outfile = outfile)

    if candidate is not None:
        HCF = K.hilbert_class_field(names = 'r1') if hK > 1 else K
        if hK == 1:
            try:
                verbose('candidate = %s'%candidate)
                Ptsmall = E.change_ring(HCF)(candidate)
                fwrite('twopow = %s'%twopow,outfile)
                fwrite('Computed point:  %s * %s * %s'%(twopow,known_multiple,Ptsmall),outfile)
                fwrite('(first factor is not understood, second factor is)',outfile)
                fwrite('(r satisfies %s = 0)'%(Ptsmall[0].parent().gen().minpoly()),outfile)
                fwrite('================================================',outfile)
                if quit_when_done:
                    magma.quit()
                return Ptsmall
            except (TypeError,ValueError):
                verbose("Could not recognize the point.")
        else:
            verbose('candidate = %s'%candidate)
            fwrite('twopow = %s'%twopow,outfile)
            fwrite('Computed point:  %s * %s * (x,y)'%(twopow,known_multiple),outfile)
            fwrite('(first factor is not understood, second factor is)',outfile)
            try:
                pols = [HCF(c).relative_minpoly() for c in candidate[:2]]
            except AttributeError:
                pols = [HCF(c).minpoly() for c in candidate[:2]]
            fwrite('Where x satisfies %s'%pols[0],outfile)
            fwrite('and y satisfies %s'%pols[1],outfile)
            fwrite('================================================',outfile)
            if quit_when_done:
                magma.quit()
            return candidate
    else:
        fwrite('================================================',outfile)
        if quit_when_done:
            magma.quit()
        return []