Ejemplo n.º 1
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
Ejemplo n.º 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)
Ejemplo n.º 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)
Ejemplo n.º 4
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)
Ejemplo n.º 5
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)
Ejemplo n.º 6
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)
Ejemplo n.º 7
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))
Ejemplo n.º 8
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
Ejemplo n.º 9
0
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 )
Ejemplo n.º 10
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')
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)
Ejemplo n.º 12
0
 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)
Ejemplo n.º 13
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
Ejemplo n.º 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'))
Ejemplo n.º 15
0
vasp_args = dict(xc='PBE', amix=0.22, amin=0.02, bmix=0.6, amix_mag=1.0, bmix_mag=0.9, lorbit=11,
                 kpts=[1, 6, 6], kpar=args.kpar, lreal='auto', nelmdl=-15, ispin=2, prec='Accurate', ediff=1.e-4,
                 encut=420, nelm=100, algo='VeryFast', lplane=False, lwave=False, lcharg=False, istart=0,
                 magmom=magmoms, maxmix=25, #https://www.vasp.at/vasp-workshop/slides/handsonIV.pdf #for badly behaved clusters.
                 voskown=0, ismear=1, sigma=0.1, isym=2, iwavpr=11) 

mpirun = spawn.find_executable('mpirun')
vasp = '/home/mmm0007/vasp/vasp.5.4.1/bin/vasp_std'

vasp_client = VaspClient(client_id=0, npj=96, ppn=1,
                         exe=vasp, mpirun=mpirun, parmode='mpi',
                         ibrion=13, nsw=1000000,
                         npar=6, **vasp_args)

traj = io.Trajectory('relaxation.traj','a', gam_cell)

qm_pot = SocketCalculator(vasp_client)
gam_cell.set_calculator(qm_pot)

fixed_line=[]
for at in gam_cell:
    fixed_line.append(FixedLine(at.index, (1,0,0)))
gam_cell.set_constraint(fixed_line)
opt = PreconLBFGS(Atoms(gam_cell))
#opt.attach(traj_writer, interval=1)
opt.attach(traj.write, interval=1)
opt.run(fmax=0.01)
traj.close()

Ejemplo n.º 16
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)
Ejemplo n.º 17
0
    else:
        sc.rescale_k(k * k1g)

    if fit_alpha:
        sc.alpha, = sc.fit_cle(variable_alpha=True, variable_k=False)
        print(f'Fitted value of alpha: {sc.alpha}')
    print(f'k = {sc.k / k1g} * k1g')
    print(f'alpha = {sc.alpha}')

    if lbfgs:
        print('Optimizing with LBFGS')
        atoms = sc.atoms.copy()
        atoms.calc = sc.calc
        atoms.set_constraint(FixAtoms(mask=np.logical_not(sc.regionI)))
        opt = PreconLBFGS(atoms)
        opt.run(fmax=fmax)
        sc.set_atoms(atoms)
    else:
        if prerelax:
            print('Pre-relaxing with Conjugate-Gradients')
            sc.optimize(ftol=1e-5, steps=max_steps, dump=dump, method='cg')

        sc.optimize(fmax,
                    steps=max_steps,
                    dump=dump,
                    precon=precon,
                    method='krylov')

    if flexible:
        print(f'Optimized alpha = {sc.alpha:.3f}')
    ks_out.append(k)
Ejemplo n.º 18
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
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")
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()
Ejemplo n.º 21
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
Ejemplo n.º 22
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)
Ejemplo n.º 23
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')
Ejemplo n.º 24
0
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
#
#######################################################################

# A much faster model is available in the "quippy" package, which in turn comes with the QUIP package
#                                             http://github.com/libatoms/QUIP
# whose installation is more complicated (needs a Fortran compiler, e.g. gfortran, and the use of the
Ejemplo n.º 25
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)
Ejemplo n.º 26
0
    # perturb the atoms
    s = a0.get_scaled_positions()
    s[:, 0] *= 0.995
    a0.set_scaled_positions(s)

    atoms = a0.copy()
    atoms.set_calculator(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)
Ejemplo n.º 27
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')
Ejemplo n.º 28
0
                         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,
                         mpirun=mpirun,
Ejemplo n.º 29
0
def calc(primitive,
         cachedir=None,
         supercell=(1, 1, 1),
         delta=0.01,
         quick=True):
    """Calculates the Hessian for a given atoms object (which *must* have an
    attached calculator).

    .. note:: We choose to use the Hessian as the fundamental quantity in
      vibrational analysis in `matdb`.

    .. note:: `atoms` will be relaxed before calculating the Hessian.

    Args:
        primitive (matdb.atoms.Atoms): atomic structure of the *primitive*.
        cachedir (str): path to the directory where phonon calculations are
          cached. If not specified, a temporary directory will be used.
        supercell (tuple): number of times to duplicate the cell when
          forming the supercell.
        delta (float): displacement in Angstroms of each atom when computing the
          phonons. 
        quick (bool): when True, use symmetry to speed up the Hessian
          calculation. See :func:`_calc_quick`.

    Returns:
        numpy.ndarray: Hessian matrix that has dimension `(natoms*3, natoms*3)`,
        where `natoms` is the number of atoms in the *supercell*.
    """
    if quick:
        return _calc_quick(primitive, supercell, delta)
    else:
        atoms = primitive.make_supercell(supercell)
        atoms.set_calculator(primitive.get_calculator())

    from ase.vibrations import Vibrations

    #The phonon calculator caches the displacements and force sets for each
    #atomic displacement using pickle. This generates three files for each
    #atomic degree of freedom (one for each cartesian direction). We want to
    #save these in a special directory.
    tempcache = False
    if cachedir is None:
        cachedir = mkdtemp()
        tempcache = True
    else:
        cachedir = path.abspath(path.expanduser(cachedir))
    if not path.isdir(cachedir):
        mkdir(cachedir)

    result = None
    precon = Exp(A=3)
    aphash = None

    #Calculate a hash of the calculator and atoms object that we are calculating
    #for. If the potential doesn't have a `to_dict` method, then we ignore the
    #hashing.
    if not tempcache and hasattr(atoms, "to_dict") and hasattr(
            atoms._calc, "to_dict"):
        atoms_pot = {"atoms": atoms.to_dict(), "pot": atoms._calc.to_dict()}
        #This UUID will probably be different, even if the positions and species
        #are identical.
        del atoms_pot["atoms"]["uuid"]
        hash_str = convert_dict_to_str(atoms_pot)
        aphash = str(sha1(hash_str).hexdigest())

    if not tempcache:
        #Check whether we should clobber the cache or not.
        extras = ["vibsummary.log", "vib.log", "phonons.log"]

        with chdir(cachedir):
            hash_match = False
            if path.isfile("atomspot.hash"):
                with open("atomspot.hash") as f:
                    xhash = f.read()
                hash_match = xhash == aphash

            hascache = False
            if not hash_match:
                for vibfile in glob("vib.*.pckl"):
                    remove(vibfile)
                    hascache = True

                for xfile in extras:
                    if path.isfile(xfile):
                        remove(xfile)
                        hascache = True

            if hascache:
                msg.warn(
                    "Using hard-coded cache directory. We were unable to "
                    "verify that the atoms-potential combination matches "
                    "the one for which existing cache files exist. So, we "
                    "clobbered the existing files to get the science "
                    "right. You can fix this by using `matdb.atoms.Atoms` "
                    "and `matdb.calculators.*Calculator` objects.")

    with chdir(cachedir):
        #Relax the cell before we calculate the Hessian; this gets the forces
        #close to zero before we make harmonic approximation.
        try:
            with open("phonons.log") as f:
                with redirect_stdout(f):
                    minim = PreconLBFGS(atoms, precon=precon, use_armijo=True)
                    minim.run(fmax=1e-5)
        except:
            #The potential is unstable probably. Issue a warning.
            msg.warn(
                "Couldn't optimize the atoms object. Potential may be unstable."
            )

        vib = Vibrations(atoms, delta=delta)
        with open("vib.log", 'a') as f:
            with redirect_stdout(f):
                vib.run()

        vib.summary(log="vibsummary.log")
        result = vib.H

        #Cache the hash of the atoms object and potential that we were using so
        #that we can check next time whether we should clobber the cache or not.
        if aphash is not None and not tempcache:
            with open(path.join(cachedir, "atomspot.hash"), 'w') as f:
                f.write(aphash)

    return result
Ejemplo n.º 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
Ejemplo n.º 31
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)