Пример #1
0
def relax(runID):
    db = connect(db_name)
    atoms = db.get_atoms(id=runID)

    con = sq.connect(db_name)
    cur = con.cursor()
    cur.execute("SELECT value FROM text_key_values WHERE id=? AND key='name'",
                (runID, ))
    name = cur.fetchone()[0]
    con.close()

    calc = gp.GPAW(mode=gp.PW(600),
                   xc="PBE",
                   kpts=(4, 4, 4),
                   nbands="120%",
                   symmetry="off")
    atoms.set_calculator(calc)
    precon = Exp(mu=1.0, mu_c=1.0)
    save_to_db = SaveToDB(db_name, runID, name)
    logfile = "logfile%d.log" % (runID)
    traj = "trajectory%d.traj" % (runID)
    uf = UnitCellFilter(atoms, hydrostatic_strain=True)
    relaxer = PreconLBFGS(uf, logfile=logfile, use_armijo=True, precon=precon)
    relaxer.attach(save_to_db, interval=1, atoms=atoms)
    trajObj = Trajectory(traj, "w", atoms)
    relaxer.attach(trajObj)
    relaxer.run(fmax=0.05, smax=0.003)
Пример #2
0
def main(argv):
    fname = argv[0]
    if (int(argv[1]) == 1):
        variable_cell = True
    else:
        variable_cell = False
    atoms = read(fname)
    #atoms = bulk("Al")

    calc = gp.GPAW(mode=gp.PW(500), kpts=(12, 12, 12), xc="PBE", nbands=-20)
    atoms.set_calculator(calc)
    prc = Exp(mu=1.0, mu_c=1.0)
    outfname = fname.split("/")[-1]
    outfname = outfname.split(".")[0]
    logfile = outfname + ".log"
    traj_file = outfname + ".traj"
    relaxer = PreconLBFGS(atoms,
                          logfile=logfile,
                          precon=prc,
                          use_armijo=True,
                          variable_cell=variable_cell)
    trajObj = Trajectory(traj_file, 'w', atoms)
    relaxer.attach(trajObj)
    if (variable_cell):
        relaxer.run(fmax=0.025, smax=0.003)
    else:
        relaxer.run(fmax=0.025)
    outfname = fname.split("/")[-1]
    outfname = outfname.split(".")[0]
    outfname += "_relaxed.xyz"
    print("Energy: {}".format(atoms.get_potential_energy()))
    write(outfname, atoms)
Пример #3
0
def main():
    atoms = bulk("Al", cubic=True)
    atoms = atoms * (3, 3, 3)
    for i in range(int(len(atoms) / 5)):
        atoms[i].symbol = "Mg"

    atoms.rattle(stdev=0.005)

    calc = gp.GPAW(mode=gp.PW(500), xc="PBE", kpts=(4, 4, 4), nbands="120%")
    atoms.set_calculator(calc)

    logfile = "relax250.log"
    traj = "relax250.traj"
    trajObj = Trajectory(traj, 'w', atoms)

    precon = Exp(mu=1)
    relaxer = PreconLBFGS(atoms,
                          logfile=logfile,
                          use_armijo=True,
                          precon=precon,
                          memory=50)
    #relaxer = PreconFIRE( atoms, logfile=logfile, use_armijo=True, precon=precon )
    relaxer.attach(trajObj)
    try:
        relaxer.run(fmax=0.05)
    except Exception as exc:
        print(exc)
Пример #4
0
def main(argv):
    n_mg = int(argv[0])
    atoms = bulk("Al")
    atoms = atoms * (4, 4, 4)
    for i in range(n_mg):
        atoms[i].symbol = "Mg"

    atoms.rattle(stdev=0.005)

    calc = gp.GPAW(mode=gp.PW(500), xc="PBE", kpts=(4, 4, 4), nbands="120%")
    atoms.set_calculator(calc)

    logfile = "preconTest%d.log" % (n_mg)
    traj = "preconTest%d.traj" % (n_mg)
    trajObj = Trajectory(traj, 'w', atoms)

    precon = Exp(mu=1)
    relaxer = PreconLBFGS(atoms,
                          logfile=logfile,
                          use_armijo=True,
                          precon=precon)
    relaxer.attach(trajObj)
    try:
        relaxer.run(fmax=0.05)
    except:
        pass
    print("Mu: %.2E" % (relaxer.precon.mu))
Пример #5
0
                         npj=96,
                         ppn=1,
                         exe=vasp,
                         mpirun=mpirun,
                         parmode='mpi',
                         ibrion=13,
                         nsw=1000000,
                         npar=4,
                         **vasp_args)

if not args.no_relax:
    traj = io.Trajectory('relaxation.traj', 'a', gam_cell)
    qm_pot = SocketCalculator(vasp_client)
    gam_cell.set_calculator(qm_pot)
    opt = PreconLBFGS(gam_cell)
    opt.attach(traj.write, interval=1)
    opt.run(fmax=args.fmax)
    traj.close()
    qm_pot.shutdown()

#remove defect atom with symbol
del gam_cell[[atom.symbol == args.symbol for atom in gam_cell]]
defect_cell = gam_cell.copy()
defect_cell.write('no_impurity.xyz')

#Need accurate forces
vasp_args['ediff'] = 1e-5
vasp_client = VaspClient(client_id=0,
                         npj=96,
                         ppn=1,
                         exe=vasp,
Пример #6
0
    bulk_mat = bulk('Fe','bcc',a)*(2,1,1)


    #bulk_mat.set_initial_magnetic_moments([2.2, 2.2])
    print(bulk_mat.get_positions())
    bulk_mat = bulk_mat#*(atoms,atoms,atoms)

    is_varying = 'nothing'



    calc = GPAW(mode=PW(e_cut), nbands = nbands,
                xc='PBE', spinpol = True, kpts=(k_pts,k_pts,k_pts),
                occupations=FermiDirac(smear , fixmagmom = True), txt='Fe.out')


    bulk_mat.set_calculator(calc)
    traj = Trajectory('some_test.traj', 'w', bulk_mat)
    bulk_mat = unitcellfilter...(bulk_mat, hydrotstatic_strain=True)
    relaxer = PreconLBFGS(bulk_mat, variable_cell = True, logfile = 'my_log.txt')
    relaxer.attach(traj)
    relaxer.run(fmax = 0.025, smax = 0.003)


    energy = bulk_mat.get_potential_energy()
    print(bulk_mat.get_magnetic_moments())
    print(bulk_mat.get_positions())
    print(energy)
    calc.write('Fe.gpw')
Пример #7
0
    if os.path.isfile('./' + system_name + '_relaxed.gpw'):
        #Recover past done calculations if available
        bulk_mat, calc = restart(system_name + '_relaxed.gpw', txt = None)
        bulk_mat.set_calculator(calc)

    else:
        #Initialize new calculations
        db = connect(sys.argv[8])
        bulk_mat = db.get_atoms(id = sys.argv[9])

        calc = GPAW(mode=PW(e_cut), nbands = nbands,
                    xc='PBE', spinpol=True, kpts=(k_pts,k_pts,k_pts),
                    occupations=FermiDirac(smear), txt=system_name + '.out')

        bulk_mat.set_calculator(calc)

        save_atoms(bulk_mat, e_cut, nbands, k_pts, smear, a, initial_magmom, 1, str(sys.argv[6]))


    saver = Gpw_save(calc, system_name + '_relaxed.gpw')
    traj = Trajectory(system_name + '_relaxed.traj', 'w', bulk_mat)
    relaxer = PreconLBFGS(bulk_mat, variable_cell = True, logfile = system_name + '.txt')
    relaxer.attach(traj)
    relaxer.attach(saver)
    relaxer.run(fmax = 0.025, smax = 0.003)
    bulk_mat.get_potential_energy()
    #Save the final state of the calculations
    calc.write(system_name + '_relaxer_final.gpw')
    save_atoms(bulk_mat, e_cut, nbands, k_pts, smear, a, initial_magmom, 0, str(sys.argv[6]))
Пример #8
0
def main(argv):
    relax_mode = "both"  # both, cell, positions
    system = "AlMg"
    runID = int(argv[0])
    nkpt = int(argv[1])

    single_point = False
    if (len(argv) >= 3):
        single_point = (int(argv[2]) == 1)
    print("Running job: %d" % (runID))
    db_paths = [
        "/home/ntnu/davidkl/GPAWTutorial/CE/almg_fcc_vac.db",
        "almg_fcc_vac.db", "/home/davidkl/GPAWTutorial/CE/almg_fcc_vac.db"
    ]
    for path in db_paths:
        if (os.path.isfile(path)):
            db_name = path
            break
    #db_name = "almgsi_test_db.db"
    db = ase.db.connect(db_name)
    name = db.get(id=runID).key_value_pairs["name"]
    new_run = not db.get(id=runID).key_value_pairs["started"]

    # Update the databse
    db.update(runID, started=True, converged=False)
    db.update(runID, nkpt=nkpt)

    atoms = db.get_atoms(id=runID)
    atoms = delete_vacancies(atoms)

    if (len(atoms) == 1):
        nbands = -10
    else:
        nbands = "120%"
    kpts = (nkpt, nkpt, nkpt)
    try:
        restart_name = SaveRestartFiles.restart_name(name)
        atoms, calc = gp.restart(restart_name)
    except:
        calc = gp.GPAW(mode=gp.PW(500), xc="PBE", kpts=kpts, nbands=nbands)
        atoms.set_calculator(calc)

    if (single_point):
        calc = gp.GPAW(mode=gp.PW(500), xc="PBE", kpts=kpts, nbands=nbands)
        atoms.set_calculator(calc)

    logfile = "almg_fcc_vac{}.log".format(name)
    traj = "almg_bcc{}.traj".format(name)
    db.update(runID, trajfile=traj)
    trajObj = Trajectory(traj, 'w', atoms)

    #storeBest = SaveToDB(db_name,runID,name,mode=relax_mode)
    save_calc = SaveRestartFiles(calc, name)
    update_db_info = UpdateDBInfo(db_name, runID, atoms)
    volume = atoms.get_volume()

    try:
        precon = Exp(mu=1.0, mu_c=1.0)
        fmax = 0.025
        smax = 0.003
        if (relax_mode == "both"):
            relaxer = PreconLBFGS(atoms,
                                  logfile=logfile,
                                  use_armijo=True,
                                  variable_cell=True)
        elif (relax_mode == "positions"):
            #relaxer = SciPyFminCG( atoms, logfile=logfile )
            relaxer = BFGS(atoms, logfile=logfile)
        elif (relax_mode == "cell"):
            str_f = StrainFilter(atoms, mask=[1, 1, 1, 0, 0, 0])
            relaxer = BFGS(str_f, logfile=logfile)
            fmax = smax * volume

        relaxer.attach(trajObj)
        #relaxer.attach( storeBest, interval=1, atoms=atoms )
        relaxer.attach(save_calc, interval=1)
        relaxer.attach(update_db_info, interval=1)
        if (not single_point):
            if (relax_mode == "both"):
                relaxer.run(fmax=fmax, smax=smax)
            else:
                relaxer.run(fmax=fmax)
        energy = atoms.get_potential_energy()

        orig_atoms = db.get_atoms(runID)
        single_p_calc = SinglePointCalculator(orig_atoms, energy=energy)
        orig_atoms.set_calculator(single_p_calc)
        kvp = db.get(name=name).key_value_pairs
        del db[runID]
        newID = db.write(orig_atoms, key_value_pairs=kvp)

        if (relax_mode == "positions"):
            db.update(newID, converged_force=True)
        elif (relax_mode == "cell"):
            db.update(newID, converged_stress=True)
        else:
            db.update(newID, converged_stress=True, converged_force=True)

        db.update(newID, single_point=single_point)
        db.update(newID, restart_file=SaveRestartFiles.restart_name(name))
        row = db.get(id=newID)
        conv_force = row.get("converged_force", default=0)
        conv_stress = row.get("converged_stress", default=0)
        if ((conv_force == 1) and (conv_stress == 1) and (nkpt == 4)):
            db.update(newID, converged=True)
    except Exception as exc:
        print(exc)
Пример #9
0
print("        Iteration       Time     Energy     max Force")

# loop to perform the successive small strain increments
for i in range(50):

    # record and print the current strain
    atoms.info["strain"] = (atoms.cell[0, 0] -
                            origLx) / origLx  # Engineering strain
    print "strain: ", atoms.info["strain"]

    # set up an optimizer, this is a particularly efficient one
    opt = PreconLBFGS(atoms, precon=Exp(3.0))

    # attach the optimiser to the atoms object, asking it to call our helper function
    # that writes out the atomic positions, after every 2nd iterations of the optimisation
    opt.attach(write_frame, 2, atoms)

    # run the optimizer, until the maximum force on any atom is less than a tolerance in eV/Ang
    opt.run(fmax=0.02)

    # update the "grip" by applying the small strain increment.
    s = 0.01  # small strain increment
    atoms.set_cell(atoms.cell * np.diag([1.0 + s, 1.0 - s * nu, 1.0 - s * nu]),
                   scale_atoms=True)

#######################################################################
#
# Notes
#
#######################################################################
Пример #10
0
def relax_config(atoms,
                 relax_pos,
                 relax_cell,
                 tol=1e-3,
                 method='lbfgs',
                 max_steps=200,
                 save_traj=False,
                 constant_volume=False,
                 refine_symmetry_tol=None,
                 keep_symmetry=False,
                 strain_mask=None,
                 config_label=None,
                 from_base_model=False,
                 save_config=False,
                 try_restart=False,
                 fix_cell_dependence=False,
                 applied_P=0.0,
                 hydrostatic_strain=False,
                 **kwargs):

    # get from base model if requested
    import model

    if config_label is not None:
        save_file = run_root + '-' + config_label + '-relaxed.xyz'
        traj_file = run_root + '-' + config_label + '-traj.xyz'
    else:
        save_file = None
        traj_file = None

    if try_restart:
        # try from saved final config
        try:
            atoms = read(save_file, format='extxyz')
            print("relax_config read config from final file", save_file)
            return atoms
        except:
            pass
        # try from last config in traj file
        try:
            atoms_in = read(traj_file, -1, format='extxyz')
            # set positions from atoms_in rescaling to match current cell
            saved_cell = atoms.get_cell().copy()
            atoms.set_cell(atoms_in.get_cell())
            atoms.set_positions(atoms_in.get_positions())
            atoms.set_cell(saved_cell, scale_atoms=True)
            print("relax_config read config from traj", traj_file)
        except:
            pass
    else:
        if from_base_model:
            if config_label is None:
                raise ValueError(
                    'from_base_model is set but no config_label provided')
            try:
                base_run_file = os.path.join(
                    '..', base_run_root,
                    base_run_root + '-' + config_label + '-relaxed.xyz')
                atoms_in = read(base_run_file, format='extxyz')
                # set positions from atoms_in rescaling to match current cell
                saved_cell = atoms.get_cell().copy()
                atoms.set_cell(atoms_in.get_cell())
                atoms.set_positions(atoms_in.get_positions())
                atoms.set_cell(saved_cell, scale_atoms=True)
                print("relax_config read config from base model ",
                      base_run_file)
            except:
                try:
                    print("relax_config failed to read base run config from ",
                          base_run_root + '-' + config_label + '-relaxed.xyz')
                except:
                    print("relax_config failed to determined base_run_root")

    print("relax_config symmetry before refinement at default tol 1.0e-6")
    check_symmetry(atoms, 1.0e-6, verbose=True)
    if refine_symmetry_tol is not None:
        refine_symmetry(atoms, refine_symmetry_tol)
        print("relax_config symmetry after refinement")
        check_symmetry(atoms, refine_symmetry_tol, verbose=True)
    if keep_symmetry:
        print("relax_config trying to maintain symmetry")
        atoms.set_constraint(FixSymmetry(atoms))

    # if needed, fix cell dependence before running
    if fix_cell_dependence and hasattr(model, "fix_cell_dependence"):
        model.fix_cell_dependence(atoms)

    atoms.set_calculator(model.calculator)

    if method == 'lbfgs' or method == 'sd2':
        if 'move_mask' in atoms.arrays:
            atoms.set_constraint(
                FixAtoms(np.where(atoms.arrays['move_mask'] == 0)[0]))
        if relax_cell:
            atoms_cell = ExpCellFilter(atoms,
                                       mask=strain_mask,
                                       constant_volume=constant_volume,
                                       scalar_pressure=applied_P * GPa,
                                       hydrostatic_strain=hydrostatic_strain)
        else:
            atoms_cell = atoms
        atoms.info["n_minim_iter"] = 0
        if method == 'sd2':
            (traj,
             run_stat) = sd2_run("", atoms_cell, tol,
                                 lambda i: sd2_converged(i, atoms_cell, tol),
                                 max_steps)
            if save_traj is not None:
                write(traj_file, traj)
        else:
            # precon="Exp" specified to resolve an error with the lbfgs not optimising
            opt = PreconLBFGS(atoms_cell, use_armijo=False, **kwargs)
            if save_traj:
                traj = open(traj_file, "w")

                def write_trajectory():
                    if "n_minim_iter" in atoms.info:
                        atoms.info["n_minim_iter"] += 1
                    write(traj, atoms, format='extxyz')
                    traj.flush()

                opt.attach(write_trajectory)
    elif method == 'cg_n':
        raise ValueError(
            'minim method cg_n not supported in new python3 quippy')
        # if strain_mask is not None:
        # raise(Exception("strain_mask not supported with method='cg_n'"))
        # atoms.info['Minim_Constant_Volume'] = constant_volume
        # opt = Minim(atoms, relax_positions=relax_pos, relax_cell=relax_cell, method='cg_n')
    else:
        raise ValueError('unknown method %s!' % method)

    if method != 'sd2':
        opt.run(tol, max_steps)

    if refine_symmetry_tol is not None:
        print("symmetry at end of relaxation at desired tol")
        check_symmetry(atoms, refine_symmetry_tol, verbose=True)
    print("symmetry at end of relaxation at default tol 1e-6")
    check_symmetry(atoms, 1.0e-6, verbose=True)

    # in case we had a trajectory saved
    try:
        traj.close()
    except:
        pass

    if save_config:
        if config_label is None:
            raise ValueError('save_config is set but no config_label provided')
        write(save_file, atoms, format='extxyz')

    if keep_symmetry:
        for (i_c, c) in enumerate(atoms.constraints):
            if isinstance(c, FixSymmetry):
                del atoms.constraints[i_c]
                break

    # undo fix cell dependence
    if fix_cell_dependence and hasattr(model, "fix_cell_dependence"):
        sys.stderr.write(
            "WARNING: relax_config undoing fix_cell_dependence, whether or not it was set before it started\n"
        )
        model.fix_cell_dependence()
        atoms.calc = model.calculator

    return atoms
def main():
    atoms = build.bulk("Al")
    atoms = atoms * (2, 2, 2)
    print(len(atoms))

    nRuns = 10
    optimizerFname = "optimizer.pck"
    for i in range(nRuns):
        nMgAtoms = np.random.randint(0, len(atoms) / 2)

        # Insert Mg atoms
        system = cp.copy(atoms)
        if (parallel.rank == 0):
            for j in range(nMgAtoms):
                system[i].symbol = "Mg"

            # Shuffle the list
            for j in range(10 * len(system)):
                first = np.random.randint(0, len(system))
                second = np.random.randint(0, len(system))
                symb1 = system[first].symbol
                system[first].symbol = system[second].symbol
                system[second].symbol = symb1
        system = parallel.broadcast(system)

        # Initialize the calculator
        calc = gp.GPAW(mode=gp.PW(400), xc="PBE", kpts=(4, 4, 4), nbands=-10)
        system.set_calculator(calc)

        traj = Trajectory("trajectoryResuse.traj", 'w', atoms)

        if (i == 0):
            relaxer = PreconLBFGS(UnitCellFilter(system), logfile="resuse.log")
        else:
            relaxer = None
            relaxParams = None
            if (parallel.rank == 0):
                with open(optimizerFname, 'rb') as infile:
                    relaxParams = pck.load(infile)
            relaxParams = parallel.broadcast(relaxParams)
            precon = Exp(r_cut=relaxParams["r_cut"],
                         r_NN=relaxParams["r_NN"],
                         mu=relaxParams["mu"],
                         mu_c=relaxParams["mu_c"])
            relaxer = PreconLBFGS(UnitCellFilter(system),
                                  logfile="resuse.log",
                                  precon=precon)

        relaxer.attach(traj)

        relaxer.run(fmax=0.05)
        print(relaxer.iteration)
        if (parallel.rank == 0):
            with open(optimizerFname, 'wb') as outfile:
                relaxParams = {
                    "r_cut": relaxer.precon.r_cut,
                    "r_NN": relaxer.precon.r_NN,
                    "mu": relaxer.precon.mu,
                    "mu_c": relaxer.precon.mu_c
                }
                pck.dump(relaxParams, outfile, pck.HIGHEST_PROTOCOL)
        parallel.barrier()
def main():
    runID = 20  # ID in the SQL database
    kpt_density = 5.4

    print("Running job: {}".format(runID))
    db_name = "database_with_structures.db"

    # Create a database connection
    db = connect(db_name)

    # Retrieve the unique name of this particular entry
    name = db.get(id=runID).key_value_pairs["name"]

    # Update the databse
    db.update(runID, started=True, converged=False)
    db.update(runID, kpt_density=kpt_density)

    # Get the atoms object from the database
    atoms = db.get_atoms(id=runID)
    nbands = "120%"  # Number of electronic bands

    kpts = {"density": kpt_density, "even": True}
    calc = gp.GPAW(mode=gp.PW(600), xc="PBE", kpts=kpts, nbands=nbands)
    atoms.set_calculator(calc)

    logfile = "prebeta{}.log".format(runID)
    traj = "prebeta{}.traj".format(runID)

    # Initialize a trajactory file
    trajObj = Trajectory(traj, 'w', atoms)

    # Initialize the relaxer
    relaxer = PreconLBFGS(atoms, logfile=logfile, use_armijo=True,
                          variable_cell=True)

    # Attach the trajectory file to the relaxer
    relaxer.attach(trajObj)

    # Run until force and stress criteria have been met
    fmax = 0.025  # Maximum force in eV/Å
    smax = 0.003  # Maximum stress in eV/Å^3
    relaxer.run(fmax=fmax, smax=smax)

    # Get and print the total energy
    energy = atoms.get_potential_energy()
    print("Energy: {}".format(energy))

    # What follows is very crucial that it is done exactly like this

    # Retrieve the original (unrelaxed object) from the database
    orig_atoms = db.get_atoms(id=runID)

    # Attacha singlet point calculator with the energy of the relaxed structure
    scalc = SinglePointCalculator(orig_atoms, energy=energy)
    orig_atoms.set_calculator(scalc)

    # Get a all the key_value_pairs
    kvp = db.get(id=runID).key_value_pairs

    # Delete the original entry
    del db[runID]

    # Write the new objet to the database
    # Unrelaxed system, with the energy of the relaxed one
    newID = db.write(orig_atoms, key_value_pairs=kvp)

    # Update the converged flag
    db.update(newID, converged=True)

    # Store also the relaxed object (NOTE: they are linked via their name)
    db.write(atoms, name=name, state="relaxed")
Пример #13
0
def main(argv):
    relax_mode = "cell"  # both, cell, positions
    system = "AlMg"
    runID = int(argv[0])
    print("Running job: %d" % (runID))
    db_paths = [
        "/home/ntnu/davidkl/GPAWTutorial/CE/almg_217.db", "almg_217.db",
        "/home/davidkl/GPAWTutorial/CE/almg_217.db"
    ]
    for path in db_paths:
        if (os.path.isfile(path)):
            db_name = path
            break
    #db_name = "test_db.db"
    db = ase.db.connect(db_name)

    con = sq.connect(db_name)
    cur = con.cursor()
    cur.execute("SELECT value FROM text_key_values WHERE id=? AND key='name'",
                (runID, ))
    name = cur.fetchone()[0]
    con.close()

    new_run = not db.get(id=runID).key_value_pairs["started"]
    # Update the databse
    db.update(runID, started=True, converged=False)

    atoms = db.get_atoms(id=runID)

    calc = gp.GPAW(mode=gp.PW(500), xc="PBE", kpts=(4, 4, 4), nbands="120%")
    #calc = gp.GPAW( mode=gp.PW(500), xc="PBE", kpts=(4,4,4), nbands=-10 )
    atoms.set_calculator(calc)

    logfile = "almg_bcc%d.log" % (runID)
    traj = "almg_bcc%d.traj" % (runID)
    trajObj = Trajectory(traj, 'w', atoms)

    storeBest = SaveToDB(db_name, runID, name, mode=relax_mode)
    volume = atoms.get_volume()

    try:
        precon = Exp(mu=1.0, mu_c=1.0)
        fmax = 0.025
        smax = 0.003
        if (relax_mode == "both"):
            relaxer = PreconLBFGS(atoms,
                                  logfile=logfile,
                                  use_armijo=True,
                                  precon=precon,
                                  variable_cell=True)
        elif (relax_mode == "positions"):
            relaxer = SciPyFminCG(atoms, logfile=logfile)
            #relaxer = BFGS( atoms, logfile=logfile )
        elif (relax_mode == "cell"):
            str_f = StrainFilter(atoms, mask=[1, 1, 1, 0, 0, 0])
            relaxer = BFGS(str_f, logfile=logfile)
            fmax = smax * volume

        relaxer.attach(trajObj)
        relaxer.attach(storeBest, interval=1, atoms=atoms)
        if (relax_mode == "both"):
            relaxer.run(fmax=fmax, smax=smax)
        else:
            relaxer.run(fmax=fmax)
        energy = atoms.get_potential_energy()

        if (relax_mode == "positions"):
            db.update(storeBest.runID, converged_force=True)
        elif (relax_mode == "cell"):
            db.update(storeBest.runID, converged_stress=True)
        else:
            db.update(storeBest.runID,
                      converged_stress=True,
                      converged_force=True)

        row = db.get(id=storeBest.runID)
        conv_force = row.get("converged_force", default=0)
        conv_stress = row.get("converged_stress", default=0)
        if ((conv_force == 1) and (conv_stress == 1)):
            db.update(storeBest.runID, converged=True)
    except Exception as exc:
        print(exc)
Пример #14
0
def main(argv):
    relaxCell = True
    system = "AlMg"
    runID = int(argv[0])
    print("Running job: %d" % (runID))
    db_paths = [
        "/home/ntnu/davidkl/GPAWTutorial/CE/ce_hydrostatic.db",
        "ce_hydrostatic.db", "/home/davidkl/GPAWTutorial/CE/ce_hydrostatic.db"
    ]
    for path in db_paths:
        if (os.path.isfile(path)):
            db_name = path
            break
    #db_name = "/home/ntnu/davidkl/Documents/GPAWTutorials/ceTest.db"
    db = ase.db.connect(db_name)

    con = sq.connect(db_name)
    cur = con.cursor()
    cur.execute("SELECT value FROM text_key_values WHERE id=? AND key='name'",
                (runID, ))
    name = cur.fetchone()[0]
    con.close()

    new_run = not db.get(id=runID).key_value_pairs["started"]
    # Update the databse
    db.update(runID, started=True, converged=False)

    atoms = db.get_atoms(id=runID)
    if (system == "AlMg" and new_run == False):
        atoms = change_cell_composition_AlMg(atoms)

    convergence = {"density": 1E-4, "eigenstates": 4E-8}
    calc = gp.GPAW(mode=gp.PW(500),
                   xc="PBE",
                   kpts=(4, 4, 4),
                   nbands="120%",
                   convergence=convergence)
    atoms.set_calculator(calc)

    logfile = "ceTest%d.log" % (runID)
    traj = "ceTest%d.traj" % (runID)
    trajObj = Trajectory(traj, 'w', atoms)

    storeBest = SaveToDB(db_name, runID, name)

    try:
        precon = Exp(mu=1.0, mu_c=1.0)
        if (relaxCell):
            uf = UnitCellFilter(atoms, hydrostatic_strain=True)
            relaxer = PreconLBFGS(uf,
                                  logfile=logfile,
                                  use_armijo=True,
                                  precon=precon)
        else:
            relaxer = PreconFIRE(atoms, logfile=logfile, precon=precon)
            relaxer = SciPyFminCG(atoms, logfile=logfile)
        relaxer.attach(trajObj)
        relaxer.attach(storeBest, interval=1, atoms=atoms)
        if (relaxCell):
            relaxer.run(fmax=0.025, smax=0.003)
        else:
            relaxer.run(fmax=0.025)
        energy = atoms.get_potential_energy()
        db.update(storeBest.runID, converged=True)
        print("Energy: %.2E eV/atom" % (energy / len(atoms)))
        print("Preconditioner parameters")
        print("Mu:", precon.mu)
        print("Mu_c:", precon.mu_c)
    except Exception as exc:
        print(exc)