Beispiel #1
0
def test_precon(N):
    a0 = bulk('Cu', cubic=True)
    a0 *= (N, N, N)

    # perturb the atoms
    s = a0.get_scaled_positions()
    s[:, 0] *= 0.995
    a0.set_scaled_positions(s)

    atoms = a0.copy()
    atoms.calc = EMT()

    # check we get a warning about small system
    with warnings.catch_warnings(record=True) as w:
        # Cause all warnings to always be triggered.
        warnings.simplefilter("always")
        opt = PreconLBFGS(atoms, precon="auto")
        if N == 1:
            assert len(w) == 1
            assert "The system is likely too small" in str(w[-1].message)
        else:
            assert len(w) == 0

    # check we get a warning about bad estimate for mu with big cell
    with warnings.catch_warnings(record=True) as w:
        # Cause all warnings to always be triggered.
        warnings.simplefilter("always")
        opt.run(1e-3)
        if N == 1:
            assert len(w) == 0
        else:
            assert len(w) == 1
            assert "capping at mu=1.0" in str(w[-1].message)
Beispiel #2
0
def relax(atoms):
    """Performs a variable-cell optimization of the Atoms object."""
    t1 = time()

    # LJ parameters from G. Galassi and D.J. Tildesley,
    # "Phase Diagrams of Diatomic Molecules:
    #  Using the Gibbs Ensemble Monte Carlo Method",
    # Molecular Simulations, 13, 11 (1994).
    calc = HarmonicPlusLennardJones(epsilon=37.3 * kB, sigma=3.31, rc=12.,
                                    r0=1.12998, k=10.)
    atoms.calc = calc

    dyn = PreconLBFGS(atoms, variable_cell=True, maxstep=0.2,
                      use_armijo=True, logfile='opt.log', trajectory='opt.traj')
    dyn.run(fmax=3e-2, smax=5e-4, steps=250)

    e = atoms.get_potential_energy()
    f = atoms.get_forces()
    s = atoms.get_stress()
    finalize(atoms, energy=e, forces=f, stress=s)

    os.system('mv opt.log prev.log')
    os.system('mv opt.traj prev.traj')

    t2 = time()
    print('Relaxation took %.3f seconds.' % (t2 - t1), flush=True)
Beispiel #3
0
 def g(k, do_abs=True):
     print(f'Static minimisation with k={k}, alpha={alpha0}.')
     sc.k = k * k1g
     sc.alpha = alpha0
     sc.variable_alpha = False
     sc.variable_k = False
     sc.update_atoms()
     atoms = sc.atoms.copy()
     atoms.calc = sc.calc
     atoms.set_constraint(FixAtoms(mask=~sc.regionI))
     print('I think it gets to here')
     if preconlbfgs:
         opt = PreconLBFGS(atoms, logfile=None)
     if lbfgs:
         opt = LBFGS(atoms, logfile=None)
     opt.run(fmax=1e-5)
     print('I do not know if it gets to here')
     atoms.write(traj, format="extxyz")
     sc.set_atoms(atoms)
     f_alpha = sc.get_crack_tip_force(mask=mask)
     print(
         f'Static minimisation with k={k}, alpha={alpha0} --> f_alpha={f_alpha}'
     )
     if do_abs:
         f_alpha = abs(f_alpha)
     return f_alpha
Beispiel #4
0
def test_precon_amin():
    cu0 = bulk("Cu") * (2, 2, 2)
    sigma = cu0.get_distance(0, 1) * (2.**(-1. / 6))
    lj = LennardJones(sigma=sigma)

    # perturb the cell
    cell = cu0.get_cell()
    cell *= 0.95
    cell[1, 0] += 0.2
    cell[2, 1] += 0.5
    cu0.set_cell(cell, scale_atoms=True)

    energies = []
    for use_armijo in [True, False]:
        for a_min in [None, 1e-3]:
            atoms = cu0.copy()
            atoms.calc = lj
            opt = PreconLBFGS(atoms,
                              precon=Exp(A=3),
                              use_armijo=use_armijo,
                              a_min=a_min,
                              variable_cell=True)
            opt.run(fmax=1e-3, smax=1e-4)
            energies.append(atoms.get_potential_energy())

    # check we get the expected energy for all methods
    assert np.abs(np.array(energies) - -63.5032311942).max() < 1e-4
def relax(fname):
    atoms = read(fname)
    calc = gp.GPAW(mode=gp.PW(600),kpts=(4,4,4),xc="PBE")
    atoms.set_calculator(calc)
    uf = UnitCellFilter(atoms,hydrostatic_strain=True)
    relaxer = PreconLBFGS( uf, logfile="logfile.log" )
    relaxer.run( fmax=0.025,smax=0.003 )
    write( fname, atoms )
Beispiel #6
0
def main(runId):
    db = connect(DB_NAME)
    row = db.get(id=runId)
    group = row.group
    atoms = row.toatoms()
    niggli_reduce(atoms)
    calc = EMT()
    atoms.set_calculator(calc)
    ucell = UnitCellFilter(atoms)
    opt = PreconLBFGS(ucell)
    opt.run(fmax=0.02, smax=0.003)

    db.write(atoms, group=group, struct_type='relaxed')
Beispiel #7
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)
Beispiel #8
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)
Beispiel #9
0
 def func(self, x):
     """ Check cell shape to avoid the occasional crazy
     cells attempted by the optimizer.
     """
     if not self.accept_step(x):
         return 1e64
     return PreconLBFGS.func(self, x)
 def g(k):
     print(f'Static minimisation with k={k}, alpha={alpha0}.')
     sc.k = k * k1g
     sc.alpha = alpha0
     sc.variable_alpha = False
     sc.variable_k = False
     sc.update_atoms()
     atoms = sc.atoms.copy()
     atoms.calc = sc.calc
     atoms.set_constraint(FixAtoms(mask=~sc.regionI))
     opt = PreconLBFGS(atoms, logfile=None)
     opt.run(fmax=1e-5)
     sc.set_atoms(atoms)
     f_alpha = sc.get_crack_tip_force(mask=mask)
     print(
         f'Static minimisation with k={k}, alpha={alpha0} --> f_alpha={f_alpha}'
     )
     return abs(f_alpha)
def main(runID):
    db = connect(db_name)
    atoms = db.get_atoms(id=runID)
    N = 14
    calc = gp.GPAW(mode=gp.PW(500),
                   xc="PBE",
                   kpts=(N, N, N),
                   nbands=-50,
                   symmetry={'do_not_symmetrize_the_density': True})
    atoms.set_calculator(calc)
    precon = Exp(mu=1.0, mu_c=1.0)
    uf = UnitCellFilter(atoms, hydrostatic_strain=True)
    logfile = "al3mg2{}.log".format(runID)
    relaxer = PreconLBFGS(uf, logfile=logfile, use_armijo=True, precon=precon)
    relaxer.run(fmax=0.025, smax=0.003)
    energy = atoms.get_potential_energy()
    del db[db.get(id=runID)]
    db.write(atoms)
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)
Beispiel #13
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))
Beispiel #14
0
def run_dftb_precon(folder, param_file):
    """ Run DFTB+ using a preconditioned optimizer

    Unlike a regular DFTB+ run a result.tag file is not produced because ASE
    deletes the file. Instead we dump the energy and forces to a json file so
    we cna load it back in later.

    Args:
        folder (str): directory containing a structure to optimize
        param_file (str): path to the parameter file for this structure.
    """

    if param_file is None:
        raise RuntimeError("A parameter file must be supplied to run \
                           batch_dftb+ in precon mode")

    hsd_file = os.path.join(folder, 'dftb_pin.hsd')
    file_name = 'dftb_pin.hsd' if os.path.isfile(hsd_file) else 'geo_end.gen'
    atoms = io.read(os.path.join(folder, file_name))
    params = load_input_file(param_file)
    calc = make_dftb_calc(atoms, folder, params)
    atoms.set_calculator(calc)

    try:
        opt = PreconLBFGS(atoms,
                          precon=Exp(A=3),
                          use_armijo=True,
                          logfile=None)
        opt.run(steps=int(params['geom_steps']))
    except:
        return

    results = {
        'energy': calc.get_potential_energy(),
        'forces': calc.get_forces().tolist()
    }

    json.dump(results, open(os.path.join(folder, "results.json"), 'w'))
 def full_relaxation(self, fmax=0.025, smax=0.003):
     """
     Perform a full relaxation of the system
     """
     if (len(self.atoms) == 1):
         strfilter = StrainFilter(self.atoms)
         relaxer = BFGS(strfilter)
         fmax = smax * self.atoms.get_volume()
         relaxer.run(fmax=fmax)
     else:
         relaxer = PreconLBFGS(self.atoms, variable_cell=True)
         relaxer.run(fmax=fmax, smax=smax)
     db = connect(self.db_name)
     db.write(self.atoms, key_value_pairs={"full_relaxation": True})
Beispiel #16
0
def test_precon():
    cu0 = bulk("Cu") * (2, 2, 2)
    lj = LennardJones(sigma=cu0.get_distance(0,1))

    cu = cu0.copy()
    cu.set_cell(1.2*cu.get_cell())
    cu.calc = lj
    ucf = UnitCellFilter(cu, constant_volume=True)
    opt = PreconLBFGS(ucf, precon=Exp(mu=1.0, mu_c=1.0))
    opt.run(fmax=1e-3)
    assert abs(np.linalg.det(cu.cell)/np.linalg.det(cu0.cell) - 1.2**3) < 1e-3

    # EcpCellFilter allows relaxing to lower tolerance
    cu = cu0.copy()
    cu.set_cell(1.2*cu.get_cell())
    cu.calc = lj
    ecf = ExpCellFilter(cu, constant_volume=True)
    opt = PreconLBFGS(ecf, precon=Exp(mu=1.0, mu_c=1.0))
    opt.run(fmax=1e-3)
    assert abs(np.linalg.det(cu.cell)/np.linalg.det(cu0.cell) - 1.2**3) < 1e-7
Beispiel #17
0
    def optimise_positions(self, fmax=0.01, use_precon=None, use_armijo=None):
        """ Relax atoms positions with the fixed cell to a given force
        threshold """
        if use_precon is None:
            use_precon = self.parameters.use_precon
        if use_armijo is None:
            use_armijo = self.parameters.use_armijo

        if use_precon:
            precon = Exp(A=3, use_pyamg=False)
        else:
            precon = None
        if self.parameters.optimizer == 'BFGS':
            relax = BFGS(self.atoms)
        elif self.parameters.optimizer == 'FIRE':
            relax = PreconFIRE(self.atoms, precon=precon)
        elif self.parameters.optimizer == 'ase-FIRE':
            relax = ASEFIRE(self.atoms)
        elif self.parameters.optimizer == 'LBFGS':
            relax = PreconLBFGS(self.atoms,
                                precon=precon,
                                use_armijo=use_armijo)
        elif self.parameters.optimizer == 'ase-LBFGS':
            relax = ASELBFGS(self.atoms)
        else:
            parprint("ERROR: unknown optimizer {}. "
                     "Reverting to BFGS".format(self.parameters.optimizer))
            relax = BFGS(self.atoms)
        name = self.atoms.get_chemical_formula()
        relax.attach(
            lambda: self.atoms.calc.write(name + '_relax.gpw', mode='all'))
        relax.attach(lambda: write_atat_input(self.atoms, 'str_last.out'))
        relax.run(fmax=fmax, steps=100)
        if not relax.converged():
            relax = ASELBFGS(self.atoms)
            relax.run(fmax=fmax, steps=100)
            if not relax.converged():
                max_force = self.atoms.get_forces()
                max_force = np.sqrt((max_force**2).sum(axis=1).max())
                print('WARNING: optimisation not converged.' +
                      ' Maximum force: %.4f' % max_force)
Beispiel #18
0
def test_preconlbfgs():
    N = 1
    a0 = bulk('Cu', cubic=True)
    a0 *= (N, N, N)

    # perturb the atoms
    s = a0.get_scaled_positions()
    s[:, 0] *= 0.995
    a0.set_scaled_positions(s)

    nsteps = []
    energies = []
    for OPT in [PreconLBFGS, PreconFIRE]:
        for precon in [None, Exp(A=3, mu=1.0)]:
            atoms = a0.copy()
            atoms.calc = EMT()
            opt = OPT(atoms, precon=precon, use_armijo=True)
            opt.run(1e-4)
            energies += [atoms.get_potential_energy()]
            nsteps += [opt.get_number_of_steps()]

    # check we get the expected energy for all methods
    assert np.abs(np.array(energies) - -0.022726045433998365).max() < 1e-4

    # test with fixed bondlength and fixed atom constraints
    cu0 = bulk("Cu") * (2, 2, 2)
    cu0.rattle(0.01)
    a0 = cu0.get_distance(0, 1)
    cons = [FixBondLength(0, 1), FixAtoms([2, 3])]
    for precon in [None, Exp(mu=1.0)]:
        cu = cu0.copy()
        cu.calc = EMT()
        cu.set_distance(0, 1, a0 * 1.2)
        cu.set_constraint(cons)
        opt = PreconLBFGS(cu, precon=precon, use_armijo=True)
        opt.run(fmax=1e-3)

        assert abs(cu.get_distance(0, 1) / a0 - 1.2) < 1e-3
        assert np.all(abs(cu.positions[2] - cu0.positions[2]) < 1e-3)
        assert np.all(abs(cu.positions[3] - cu0.positions[3]) < 1e-3)
Beispiel #19
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')
Beispiel #20
0
import gpaw as gp
from ase.build import bulk
from ase.visualize import view
from ase.optimize.precon import PreconLBFGS
from ase.io import write
from ase.calculators.emt import EMT

atoms = bulk("Mg", crystalstructure="fcc", a=4.1)
atoms = atoms * (2, 2, 2)
si_indx = [1, 2, 4, 7]
for indx in si_indx:
    atoms[indx].symbol = "Si"

calc = gp.GPAW(mode=gp.PW(600), xc="PBE", kpts=(2, 2, 2), nbands=-100)
atoms.set_calculator(calc)

opt = PreconLBFGS(atoms, variable_cell=True)
opt.run(fmax=0.025, smax=0.003)
write("data/relaxed_mgsi.xyz", atoms)
Beispiel #21
0
def main(argv):
    uid = int(argv[0])

    attempt_restart = 1
    kpts_density = 1.37
    lattice_param = 4.05
    relax_atoms = 0
    final_structure = 0
    optimizer = "lbfgs"
    init_from_traj = 0
    for arg in argv:
        if arg.find("--restart=") != -1:
            attempt_restart = int(arg.split("--restart")[1])
        elif "--kpt=" in arg:
            kpts_density = float(arg.split("--kpt=")[1])
        elif "--a=" in arg:
            lattice_param = float(arg.split("--a=")[1])
        elif "--relax=" in arg:
            relax_atoms = int(arg.split("--relax=")[1])
        elif "--final=" in arg:
            final_structure = int(arg.split("--final=")[1])
        elif "--opt=" in arg:
            optimizer = arg.split("--opt=")[1]
        elif "--traj=" in arg:
            init_from_traj = int(arg.split("--traj=")[1])

    db = connect(db_name)
    atoms = db.get(id=uid).toatoms()
    atoms = delete_vacancies(atoms)
    name = db.get(id=uid).name

    kpt = {"density": kpts_density, "even": True}
    # calc = gp.GPAW(h=0.32, kpts=kpt, xc="PBE", nbands="120%")
    calc = gp.GPAW(mode=gp.PW(600), kpts=kpt, xc="PBE", nbands="120%")
    atoms.set_calculator(calc)
    restart_file = db.get(id=uid).get("restart_file", "")

    if relax_atoms == 0 and final_structure == 0:
        atoms.get_potential_energy()

        # Store the energy of the atoms object with the correct name
        # and lattice parameter
        db.write(atoms,
                 name=name,
                 lattice_param=lattice_param,
                 run_type="lattice_param_estimation")
    elif relax_atoms == 1:
        if os.path.exists(restart_file) and attempt_restart == 1:
            atoms, calc = gp.restart(restart_file)
        elif init_from_traj:
            trajfile = "trajectory{}.traj".format(name)
            traj = Trajectory(trajfile, 'r')
            atoms = traj[-1]
            atoms.set_calculator(calc)
        else:
            db.update(uid, restart_file=SaveRestartFiles.restart_name(name))
        restart_saver = SaveRestartFiles(calc, name)
        trajObj = Trajectory("trajectory{}.traj".format(name), 'a', atoms)
        ucf = UnitCellFilter(atoms, hydrostatic_strain=True)
        logfile = "log_{}.txt".format(name)
        if optimizer == "cg":
            relaxer = SciPyFminCG(ucf, logfile=logfile)
        elif optimizer == "fire":
            relaxer = PreconFIRE(ucf, logfile=logfile)
        else:
            relaxer = PreconLBFGS(ucf, logfile=logfile)

        relaxer.attach(trajObj)
        relaxer.attach(restart_saver, interval=1)
        relaxer.run(fmax=0.025)
        db.write(atoms,
                 name=name,
                 lattice_param=lattice_param,
                 run_type="geometry_opt",
                 restart_file=SaveRestartFiles.restart_name(name))
    elif final_structure:
        atoms.get_potential_energy()
        uid = db.write(atoms,
                       name=name,
                       struct_type="final",
                       kpts_density=kpts_density)
        init_id = db.get(name=name, struct_type='initial').id
        db.update(init_id, final_struct_id=uid, converged=1)
Beispiel #22
0
    dimer.positions[3:, 0] += 2.8
    dimer.constraints = FixBondLengths([
        ((selection[i] + 3) % 6, (selection[i - 1] + 3) % 6) for i in range(3)
    ])

    dimer.calc = EIQMMM(selection,
                        GPAW(txt=name + '.txt', h=0.16),
                        TIP4P(),
                        interaction,
                        vacuum=4,
                        embedding=Embedding(rc=0.2, rc2=20, width=1),
                        output=name + '.out')
    opt = LBFGS(dimer, trajectory=name + '.traj')
    opt.run(0.02)

    monomer = dimer[selection]
    monomer.center(vacuum=4)
    monomer.calc = GPAW(txt=name + 'M.txt', h=0.16)
    opt = PreconLBFGS(monomer, precon=Exp(A=3), trajectory=name + 'M.traj')
    opt.run(0.02)
    e0 = monomer.get_potential_energy()
    be = dimer.get_potential_energy() - e0
    d = dimer.get_distance(0, 3)
    print(name, be, d)
    if name == '012':
        assert abs(be - -0.288) < 0.002
        assert abs(d - 2.76) < 0.02
    else:
        assert abs(be - -0.316) < 0.002
        assert abs(d - 2.67) < 0.02
Beispiel #23
0
def relax_config(atoms,
                 calculator,
                 relax_pos,
                 relax_cell,
                 tol=1e-3,
                 method='lbfgs',
                 max_steps=200,
                 traj_file=None,
                 constant_volume=False,
                 refine_symmetry_tol=None,
                 keep_symmetry=False,
                 strain_mask=None,
                 config_label=None,
                 from_base_model=False,
                 save_config=False,
                 fix_cell_dependence=False,
                 applied_P=0.0,
                 **kwargs):

    # get from base model if requested
    #import model
    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_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))

    atoms.set_calculator(calculator)

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

    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)
        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 traj_file 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 traj_file is not None:
                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')

                #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('-'+config_label+'-relaxed.xyz', 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()

    return atoms
Beispiel #24
0
atoms.set_cell(atoms.cell * np.diag([1.0 + s, 1.0 - s * nu, 1.0 - s * nu]),
               scale_atoms=True)

# simple header for the output
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)

#######################################################################
#
Beispiel #25
0
vasp_client = VaspClient(client_id=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,
Beispiel #26
0
import numpy as np

from ase.build import bulk
from ase.calculators.lj import LennardJones
from ase.optimize.precon import PreconLBFGS, Exp
from ase.constraints import UnitCellFilter

cu0 = bulk("Cu") * (2, 2, 2)
lj = LennardJones(sigma=cu0.get_distance(0, 1))

cu = cu0.copy()
cu.set_cell(1.2 * cu.get_cell())
cu.set_calculator(lj)

ucf = UnitCellFilter(cu, constant_volume=True)
opt = PreconLBFGS(ucf, precon=Exp(mu=1.0, mu_c=1.0))
opt.run(fmax=1e-3)

assert abs(np.linalg.det(cu.cell) / np.linalg.det(cu0.cell) - 1.2**3) < 1e-3
Beispiel #27
0
def do_lattice(test_dir,
               lattice_type,
               dV=0.025,
               n_steps=(-10, 10),
               tol=1.0e-2,
               method='lbfgs',
               applied_P=0.0):

    bulk = ase.io.read(test_dir + "/bulk.xyz", format="extxyz")

    results_dict = {}

    print("relax bulk")
    # relax the initial unit cell and atomic positions
    (orig_cell, new_cell) = (None, None)
    while new_cell is None or np.max(
            np.abs(np.dot(np.linalg.inv(new_cell), orig_cell) -
                   np.eye(3))) > 0.05:
        if hasattr(model, "fix_cell_dependence"):
            model.fix_cell_dependence(bulk)
        orig_cell = bulk.get_cell()
        bulk = relax_config(bulk,
                            relax_pos=True,
                            relax_cell=True,
                            tol=tol,
                            traj_file="lattice_bulk_traj.xyz",
                            method=method,
                            refine_symmetry_tol=1.0e-2,
                            keep_symmetry=True,
                            config_label="bulk",
                            from_base_model=True,
                            save_config=True,
                            applied_P=applied_P)
        new_cell = bulk.get_cell()
        if hasattr(model, "fix_cell_dependence"):
            model.fix_cell_dependence()
        else:
            break

    print("final relaxed bulk")
    ase.io.write(sys.stdout, bulk, format='extxyz')
    ase.io.write(os.path.join("..", "relaxed.xyz"), bulk, format='extxyz')

    print("calculating E vs. V")
    E_vs_V = calc_E_vs_V(bulk, dV=dV, n_steps=n_steps, tol=tol)
    results_dict.update({'E_vs_V': E_vs_V})

    print("calculating elastic constants")

    if hasattr(model, "fix_cell_dependence"):
        model.fix_cell_dependence(bulk)

    opt = lambda atoms, **kwargs: PreconLBFGS(atoms, **kwargs)
    if lattice_type == 'cubic':
        elastic_consts = matscipy.elasticity.fit_elastic_constants(
            bulk, symmetry='cubic', optimizer=opt, logfile=sys.stdout)
        c11 = elastic_consts[0][0, 0] / GPa
        c12 = elastic_consts[0][0, 1] / GPa
        c44 = elastic_consts[0][3, 3] / GPa
        results_dict.update({
            'c11': c11,
            'c12': c12,
            'c44': c44,
            'B': (c11 + 2.0 * c12) / 3.0
        })
    elif lattice_type == 'orthorhombic':
        elastic_consts = matscipy.elasticity.fit_elastic_constants(
            bulk, optimizer=opt, logfile=sys.stdout)
        c11 = elastic_consts[0][0, 0] / GPa
        c22 = elastic_consts[0][1, 1] / GPa
        c33 = elastic_consts[0][2, 2] / GPa
        c12 = elastic_consts[0][0, 1] / GPa
        c13 = elastic_consts[0][0, 2] / GPa
        c23 = elastic_consts[0][1, 2] / GPa
        c44 = elastic_consts[0][3, 3] / GPa
        c55 = elastic_consts[0][4, 4] / GPa
        c66 = elastic_consts[0][5, 5] / GPa
        results_dict.update({
            'c11': c11,
            'c22': c22,
            'c33': c33,
            'c12': c12,
            'c13': c13,
            'c23': c23,
            'c44': c44,
            'c55': c55,
            'c66': c66
        })
    elif lattice_type == 'tetragonal':
        elastic_consts = matscipy.elasticity.fit_elastic_constants(
            bulk,
            symmetry='tetragonal_high',
            optimizer=opt,
            logfile=sys.stdout)
        c11 = elastic_consts[0][0, 0] / GPa
        c33 = elastic_consts[0][2, 2] / GPa
        c12 = elastic_consts[0][0, 1] / GPa
        c13 = elastic_consts[0][0, 2] / GPa
        c44 = elastic_consts[0][3, 3] / GPa
        c66 = elastic_consts[0][5, 5] / GPa
        results_dict.update({
            'c11': c11,
            'c33': c33,
            'c12': c12,
            'c13': c13,
            'c44': c44,
            'c66': c66,
            'B': VRH_B(c11, c33, c12, c13, c44, c66)
        })
    elif lattice_type == 'hexagonal':
        # Need to check if hexagonal structures are truly trigonal_high
        # symmetry=triginal_high not hexagonal until matscipy is debugged
        elastic_consts = matscipy.elasticity.fit_elastic_constants(
            bulk, symmetry='trigonal_high', optimizer=opt, logfile=sys.stdout)
        c11 = elastic_consts[0][0, 0] / GPa
        c33 = elastic_consts[0][2, 2] / GPa
        c12 = elastic_consts[0][0, 1] / GPa
        c13 = elastic_consts[0][0, 2] / GPa
        c44 = elastic_consts[0][3, 3] / GPa
        c14 = elastic_consts[0][0, 3] / GPa
        c15 = elastic_consts[0][0, 4] / GPa
        c25 = elastic_consts[0][1, 4] / GPa
        c66 = elastic_consts[0][5, 5] / GPa
        results_dict.update({
            'c11': c11,
            'c33': c33,
            'c12': c12,
            'c13': c13,
            'c44': c44,
            'c14': c14,
            'c15': c15,
            'c25': c25,
            'c66': c66,
            'B': HTT_B(c11, c33, c12, c13)
        })
    elif lattice_type == 'trigonal':
        elastic_consts = matscipy.elasticity.fit_elastic_constants(
            bulk, symmetry='trigonal_high', optimizer=opt, logfile=sys.stdout)
        c11 = elastic_consts[0][0, 0] / GPa
        c33 = elastic_consts[0][2, 2] / GPa
        c12 = elastic_consts[0][0, 1] / GPa
        c13 = elastic_consts[0][0, 2] / GPa
        c44 = elastic_consts[0][3, 3] / GPa
        c14 = elastic_consts[0][0, 3] / GPa
        c15 = elastic_consts[0][0, 4] / GPa
        c25 = elastic_consts[0][1, 4] / GPa
        c66 = elastic_consts[0][5, 5] / GPa
        results_dict.update({
            'c11': c11,
            'c33': c33,
            'c12': c12,
            'c13': c13,
            'c44': c44,
            'c14': c14,
            'c15': c15,
            'c25': c25,
            'c66': c66,
            'B': HTT_B(c11, c33, c12, c13)
        })

    if hasattr(model, "fix_cell_dependence"):
        model.fix_cell_dependence()

    return results_dict
Beispiel #28
0
# creates: precon.png

from ase.build import bulk
from ase.calculators.emt import EMT
from ase.optimize.precon import Exp, PreconLBFGS

from ase.calculators.loggingcalc import LoggingCalculator
import matplotlib.pyplot as plt

a0 = bulk('Cu', cubic=True)
a0 *= [3, 3, 3]
del a0[0]
a0.rattle(0.1)

nsteps = []
energies = []
log_calc = LoggingCalculator(EMT())

for precon, label in [(None, 'None'), (Exp(A=3), 'Exp(A=3)')]:
    log_calc.label = label
    atoms = a0.copy()
    atoms.set_calculator(log_calc)
    opt = PreconLBFGS(atoms, precon=precon, use_armijo=True)
    opt.run(fmax=1e-3)

log_calc.plot(markers=['r-', 'b-'], energy=False, lw=2)
plt.savefig('precon.png')
    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]))
Beispiel #30
0
import numpy as np

from ase.build import bulk
from ase.calculators.lj import LennardJones
from ase.optimize.precon import Exp, PreconLBFGS

cu0 = bulk("Cu") * (2, 2, 2)
sigma = cu0.get_distance(0,1)*(2.**(-1./6))
lj = LennardJones(sigma=sigma)

# perturb the cell
cell = cu0.get_cell()
cell *= 0.95
cell[1,0] += 0.2
cell[2,1] += 0.5
cu0.set_cell(cell, scale_atoms=True)

energies = []
for use_armijo in [True, False]:
    for a_min in [None, 1e-3]:
        atoms = cu0.copy()
        atoms.set_calculator(lj)
        opt = PreconLBFGS(atoms, precon=Exp(A=3), use_armijo=use_armijo,
                          a_min=a_min, variable_cell=True)
        opt.run(fmax=1e-3, smax=1e-4)
        energies.append(atoms.get_potential_energy())

# check we get the expected energy for all methods
assert np.abs(np.array(energies) - -63.5032311942).max() < 1e-4
Beispiel #31
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)