示例#1
0
def get_optimal_h(atoms, natoms, dyn = False, show = False):
    
    # This find the optimal h - when the top is sliding:
    
    if not dyn:
        from scipy.optimize import fmin
        pos_init    =   atoms.positions.copy()
        
        def get_epot(z):
            
            new_pos         =   pos_init
            new_pos[:,2]    =   z 
            atoms.positions =   new_pos
            
            e   = atoms.get_potential_energy()/natoms
            #print   z, e
            return  e  
        
        hmin    =   fmin(get_epot, 3.4, disp = 0)
        emin    =   get_epot(hmin)
        
        atoms.positions = pos_init
        
        if show:    print 'optimal height= %.2f and e=%.2f' %(hmin, emin) 
        return emin, hmin
    else:
        dyn         =   BFGS(atoms)
        dyn.run(fmax=0.03)
        e           =   atoms.get_potential_energy()/natoms
        hmin        =   np.average(atoms.positions[:,2])
        return e, hmin
def get_optimal_h(atoms, bottom, top, natoms, dyn = False):
    
    # This find the optimal h - when the top is sliding:
    
    if not dyn:
        from scipy.optimize import fmin
        pos_init    =   atoms.positions.copy()
        
        zmax        =   np.amax(atoms.positions[bottom][:,2])
        
        def get_epot(z):
            
            new_pos     =   pos_init
            for iat in range(len(atoms)):
                if top[iat]:
                    new_pos[iat][2] = z + zmax
            
            atoms.positions =   new_pos
            e   = atoms.get_potential_energy()/natoms
            print z, e
            return e  
        
        hmin    =   fmin(get_epot, 3.34)
        emin    =   get_epot(hmin)
        
        atoms.positions = pos_init
        print 'optimal height= %.2f and e=%.2f' %(hmin, emin) 
        return emin, hmin
    else:
        dyn         =   BFGS(atoms)
        dyn.run(fmax=0.03)
        e           =   atoms.get_potential_energy()/natoms
        layers      =   find_layers(atoms.positions)[0]
        hmin        =   layers[1] - layers[0]
        return e, hmin
示例#3
0
文件: cp2k_test.py 项目: ltalirz/ase
def test_geopt():
    calc = CP2K(label='test_geopt')
    h2 = molecule('H2', calculator=calc)
    h2.center(vacuum=2.0)
    dyn = BFGS(h2)
    dyn.run(fmax=0.05)
    dist = h2.get_distance(0, 1)
    diff = abs((dist - 1.36733746519) / dist)
    assert(diff < 1e-10)
    print('passed test "geopt"')
示例#4
0
def run(sigma, atoms):
    calc = CP2K(label = 'molecules/co-relax/sigma{0}'.format(sigma),
          xc='PBE')
    atoms.set_calculator(calc)
    gopt = BFGS(atoms, logfile=None)
    gopt.run(fmax=1e-2)
    e = atoms.get_potential_energy()
    pos = atoms.get_positions()
    d = ((pos[0] - pos[1])**2).sum()**0.5
    print('{0:1.2f}  {1:1.4f}  {2:1.4f}'.format(sigma, e, d))
示例#5
0
文件: neb.py 项目: misdoro/python-ase
 def idpp_interpolate(self, traj='idpp.traj', log='idpp.log', fmax=0.1,
                      optimizer=BFGS):
     d1 = self.images[0].get_all_distances()
     d2 = self.images[-1].get_all_distances()
     d = (d2 - d1) / (self.nimages - 1)
     old = []
     for i, image in enumerate(self.images):
         old.append(image.calc)
         image.calc = IDPP(d1 + i * d)
     opt = BFGS(self, trajectory=traj, logfile=log)
     opt.run(fmax=0.1)
     for image, calc in zip(self.images, old):
         image.calc = calc
示例#6
0
def ase_vol_relax():
    Al = bulk('Al', 'fcc', a=4.5, cubic=True)
    calc = Vasp(xc='LDA')
    Al.set_calculator(calc)

    from ase.constraints import StrainFilter
    sf = StrainFilter(Al)
    qn = QuasiNewton(sf, logfile='relaxation.log')
    qn.run(fmax=0.1, steps=5)

    print 'Stress:\n', calc.read_stress()
    print 'Al post ASE volume relaxation\n', calc.get_atoms().get_cell()

    return Al
示例#7
0
def ase_vol_relax():
    Al = bulk("Al", "fcc", a=4.5, cubic=True)
    calc = Vasp(xc="LDA")
    Al.set_calculator(calc)

    from ase.constraints import StrainFilter

    sf = StrainFilter(Al)
    qn = QuasiNewton(sf, logfile="relaxation.log")
    qn.run(fmax=0.1, steps=5)

    print("Stress:\n", calc.read_stress())
    print("Al post ASE volume relaxation\n", calc.get_atoms().get_cell())

    return Al
示例#8
0
def run_neb_calculation(cpu):
    images = [PickleTrajectory('H.traj')[-1]]
    for i in range(nimages):
        images.append(images[0].copy())
    images[-1].positions[6, 1] = 2 - images[0].positions[6, 1]
    neb = NEB(images, parallel=True, world=cpu)
    neb.interpolate()

    images[cpu.rank + 1].set_calculator(Calculator())

    dyn = BFGS(neb)
    dyn.run(fmax=fmax)

    if cpu.rank == 1:
        results.append(images[2].get_potential_energy())
示例#9
0
def test_pwscf_calculator():
    if not have_ase():
        skip("no ASE found, skipping test")
    elif not have_pwx():
        skip("no pw.x found, skipping test")
    else:
        pseudo_dir = pj(testdir, prefix, 'pseudo')
        print common.backtick("mkdir -pv {p}; cp files/qe_pseudos/*.gz {p}/; \
            gunzip {p}/*".format(p=pseudo_dir))
        at = get_atoms_with_calc_pwscf(pseudo_dir)

        print "scf"
        # trigger calculation here
        forces = at.get_forces()
        etot = at.get_potential_energy()
        stress = at.get_stress(voigt=False) # 3x3
        
        st = io.read_pw_scf(at.calc.label + '.out')
        assert np.allclose(forces, st.forces)
        assert np.allclose(etot, st.etot)
        assert np.allclose(st.stress, -stress * constants.eV_by_Ang3_to_GPa)
        
        # files/ase/pw.scf.out.start is a norm-conserving LDA struct,
        # calculated with pz-vbc.UPF, so the PBE vc-relax will make the cell
        # a bit bigger
        print "vc-relax"
        from ase.optimize import BFGS
        from ase.constraints import UnitCellFilter
        opt = BFGS(UnitCellFilter(at))
        cell = parse.arr2d_from_txt("""
            -1.97281509  0.          1.97281509
             0.          1.97281509  1.97281509
            -1.97281509  1.97281509  0.""")        
        assert np.allclose(cell, at.get_cell())
        opt.run(fmax=0.05) # run only 2 steps
        cell = parse.arr2d_from_txt("""
            -2.01837531  0.          2.01837531
             0.          2.01837531  2.01837531
            -2.01837531  2.01837531  0""")
        assert np.allclose(cell, at.get_cell())

        # at least 1 backup files must exist: pw.*.0 is the SCF run, backed up
        # in the first iter of the vc-relax
        assert os.path.exists(at.calc.infile + '.0')
示例#10
0
def relaxBend(bend, left_idxs, right_idxs, edge, bond, mdrelax):
    
    constraints =   []
    constraints.append(FixAtoms(indices = left_idxs))        
    constraints.append(FixAtoms(indices = right_idxs))        
    #twist       =   twistConst_Rod(bend, 1, edge, bond ,F = 20)
    #twist.set_angle(np.pi/3 + 2./180*np.pi)
    #constraints.append(twist)
    
    add_pot =   LJ_potential_smooth(bend, bond)
    constraints.append(add_pot)
    
    calc    =   LAMMPS(parameters=get_lammps_params()) 
    bend.set_calculator(calc)
    # END CALCULATOR
    
    # RELAX
    bend.set_constraint(constraints)
    dyn     =   BFGS(bend, trajectory = mdrelax)
    dyn.run(fmax=0.05)
示例#11
0
def test_lammps_calculator():
    if not have_ase():
        skip("no ASE found, skipping test")
    elif not have_lmp():
        skip("no lammps found, skipping test")
    else:
        at = get_atoms_with_calc_lammps()
        at.rattle(stdev=0.001, seed=int(time.time()))
        common.makedirs(at.calc.directory)
        print common.backtick("cp -v utils/lammps/AlN.tersoff {p}/".format(
            p=at.calc.directory))

        print "scf"
        forces = at.get_forces()
        etot = at.get_potential_energy()
        stress = at.get_stress(voigt=False) # 3x3
        
        st = io.read_lammps_md_txt(at.calc.label + '.out')[0]
        assert np.allclose(forces, st.forces)
        assert np.allclose(etot, st.etot)
        assert np.allclose(st.stress, -stress * constants.eV_by_Ang3_to_GPa,
                           atol=1e-10)
        
        print "relax"
        from ase.optimize import BFGS
        opt = BFGS(at, maxstep=0.04)
        opt.run(fmax=0.001, steps=10)
        coords_frac = parse.arr2d_from_txt("""
            3.3333341909920072e-01    6.6666683819841532e-01    4.4325467247779138e-03
            6.6666681184103216e-01    3.3333362368205072e-01    5.0443254824788963e-01
            3.3333341909918301e-01    6.6666683819838046e-01    3.8356759709402671e-01
            6.6666681184101539e-01    3.3333362368201563e-01    8.8356759861713752e-01
            """)
        assert np.allclose(coords_frac, at.get_scaled_positions(), atol=1e-2)

        # at least 1 backup files must exist
        assert os.path.exists(at.calc.infile + '.0')
        assert os.path.exists(at.calc.outfile + '.0')
        assert os.path.exists(at.calc.dumpfile + '.0')
        assert os.path.exists(at.calc.structfile + '.0')
示例#12
0
def main():
    if "ASE_CP2K_COMMAND" not in os.environ:
        raise NotAvailable('$ASE_CP2K_COMMAND not defined')

    calc = CP2K(label='test_H2_GOPT')
    atoms = molecule('H2', calculator=calc)
    atoms.center(vacuum=2.0)

    # Run Geo-Opt
    gopt = BFGS(atoms, logfile=None)
    gopt.run(fmax=1e-6)

    # check distance
    dist = atoms.get_distance(0, 1)
    dist_ref = 0.7245595
    assert (dist - dist_ref) / dist_ref < 1e-7

    # check energy
    energy_ref = -30.7025616943
    energy = atoms.get_potential_energy()
    assert (energy - energy_ref) / energy_ref < 1e-10
    print('passed test "H2_GEO_OPT"')
示例#13
0
def test(size, R, nk):

    
    atoms_flat  =   get_square_uCell(size)
    
    view(atoms_flat)
    
    # CALCULATOR FLAT
    calc_f      =   Hotbit(SCC=False, kpts=(nk,nk,1),  \
                           txt= path + 'test_consistency/optimization_flat.cal')
    atoms_flat.set_calculator(calc_f)
    
    opt_f       =   BFGS(atoms_flat)
    opt_f.run(fmax = 0.05)
    e_flat      =   atoms_flat.get_potential_energy()
    

    
    
    atoms_c     =   atoms_flat.copy()
    
    L           =   atoms_c.get_cell().diagonal()
     
    atoms_c.set_cell(L) 
    angle       =   L[1]/R
    atoms_c.rotate('y', np.pi/2)
    atoms_c.translate((-atoms_c[0].x, 0, 0) )
    
    for a in atoms_c:
        r0      =   a.position
        phi     =   r0[1]/L[1]*angle
        a.position[0]   =   R*np.cos(phi)
        a.position[1]   =   R*np.sin(phi)
    
    
    atoms_c       =   Atoms(atoms = atoms_c, container = 'Wedge')
    atoms_c.set_container(angle = angle, height = L[0], physical = False, pbcz = True)
    
    if R < 100:
        view(atoms_c.extended_copy((8,1,3)))
    
    # CALCULATOR Cyl
    calc_c      =   Hotbit(SCC=False, kpts=(nk,1, nk), physical_k = False, \
                           txt= path + 'test_consistency/optimization_cyl.cal')
    atoms_c.set_calculator(calc_c)
    
    opt_c       =   BFGS(atoms_c)
    opt_c.run(fmax = 0.05)
    
    
    e_cyl       =   atoms_c.get_potential_energy()

    print 'R = %.2f' %R
    print 'energy flat     = %.6f' %e_flat
    print 'energy cylinder = %.6f' %e_cyl
    print 'energy dif (e_cylinder - eflat)/nAtoms  = %.6f \n' %(-(e_flat - e_cyl)/len(atoms_flat))
    
    return e_flat, e_cyl, len(atoms_flat)
示例#14
0
def ase_minimization(indiv, Optimizer):
    """Function to use built in ASE minimizers to minimize atomic positions in structure.
    Input:
        indiv = Individual class object to be optimized
        Optimizer = Optimizer class object with needed parameters
    Output:
        indiv = Optimized Individual class object.
    """
    if 'MU' in Optimizer.debug:
        debug = True
    else:
        debug = False
    cwd1=os.getcwd()
    olammpsmin = Optimizer.lammps_min
    if Optimizer.lammps_min:
        Optimizer.lammps_min = None
    calc2 = setup_calculator(Optimizer)
#     if 'mass' in indiv[0].get_calculator():
#         mass2 = ['1 '+ str(Optimizer.atomlist[0][2])]
#         if len(Optimizer.atomlist) > 1:
#             for i in range(len(Optimizer.atomlist)-1):
#                 mass2.append(str(i+2) + ' ' + str(Optimizer.atomlist[i+1][2]))
#         calc2=LAMMPS(parameters={ 'pair_style' : Optimizer.pair_style, 'pair_coeff' : Optimizer.pair_coeff , 'mass' : mass2 },files=[ Optimizer.pot_file ])
#     else:
#         calc2=LAMMPS(parameters={ 'pair_style' : Optimizer.pair_style, 'pair_coeff' : Optimizer.pair_coeff},files=[ Optimizer.pot_file ])
    if Optimizer.structure==Defect:
        nat=indiv[0].get_number_of_atoms
        sol=Atoms()
        sol.extend(indiv[0])
        sol.extend(indiv.bulko)
        sol.set_calculator(calc2)
        sol.set_cell(indiv.bulko.get_cell())
        sol.set_pbc(True)
        dyn=BFGS(sol)
        dyn.run(fmax=0.001, steps=2500)
        positions=sol[0:nat].get_positions()
        indiv[0].set_positions(positions)
    else:
        atomsdup=indiv[0].copy()
        atomsdup.set_calculator(calc2)
        dyn=BFGS(indiv[0])
        dyn.run(fmax=0.001, steps=2500)
        positions=atomsdup.get_positions()
        indiv[0].set_positions(positions)
    os.chdir(cwd1)
    calc2.clean()
    Optimizer.lammps_min = olammpsmin
    Optimizer.output.write('ASE Minimization mutation performed on individual = '+repr(indiv.index)+'\n')
    muttype='ASEM'
    if indiv.energy==0:
        indiv.history_index=indiv.history_index+'m'+muttype
    else:
        indiv.history_index=repr(indiv.index)+'m'+muttype
    return indiv
		
		
示例#15
0
def run_ase_min(totalsol, fmax=0.01, mxstep=1000, fitscheme='totalenfit', STR=''):
    try:
        dyn=BFGS(totalsol)
        dyn.run(fmax=fmax, steps=mxstep)
    except OverflowError:
        STR+='--- Error: Infinite Energy Calculated - Implement Random shake---\n'
        totalsol.rattle(stdev=0.3)
        dyn=BFGS(totalsol)
        dyn.run(fmax=fmax, steps=mxstep)
    except numpy.linalg.linalg.LinAlgError:
        STR+='--- Error: Singular Matrix - Implement Random shake ---\n'
        totalsol.rattle(stdev=0.2)
        dyn=BFGS(totalsol)
        dyn.run(fmax=fmax, steps=mxstep)
    # Get Energy of Minimized Structure
    en=totalsol.get_potential_energy()
    if fitscheme == 'enthalpyfit':
        pressure=totalsol.get_isotropic_pressure(totalsol.get_stress())
    else:
        pressure=0
    volume = totalsol.get_volume()
    energy=en
    return totalsol, energy, pressure, volume, STR
import os

from ase.io import read
from ase.neb import NEB
from ase.calculators.turbomole import Turbomole
from ase.optimize import BFGS

initial = read('initial.coord')
final = read('final.coord')
os.system('rm -f coord; cp initial.coord coord')

# Make a band consisting of 5 configs:
configs = [initial]
configs += [initial.copy() for i in range(3)]
configs += [final]

band = NEB(configs, climb=True)
# Interpolate linearly the positions of the not-endpoint-configs:
band.interpolate()

#Set calculators
for config in configs:
    config.set_calculator(Turbomole())

# Optimize the Path:
relax = BFGS(band, trajectory='neb.traj')
relax.run(fmax=0.05)


示例#17
0
def run(gl):
    #Read reactant definition
    if gl.StartType == 'file':
        Reac = read(gl.Start)
    elif gl.StartType == 'Smile':
        Reac = tl.getMolFromSmile(gl.Start)
    #Read product definition
    if gl.EndType == 'file':
        Prod= read(gl.End)
    elif gl.EndType == 'Smile':
        Prod = tl.getMolFromSmile(gl.End)

    #Set calculatiors
    #Reac = tl.setCalc(Reac,"DOS/", gl.trajMethod, gl.atomTypes)
    if gl.trajMethod == "openMM":
        Reac = tl.setCalc(Reac,"GenBXD/", gl.trajMethod, gl)
    else:
        Reac = tl.setCalc(Reac,"GenBXD/", gl.trajMethod, gl.trajLevel)
        Prod = tl.setCalc(Prod,"GenBXD/", gl.trajMethod, gl.trajLevel)
    # Partially minimise both reactant and product
    if gl.GenBXDrelax:
        min = BFGS(Reac)
        try:
            min.run(fmax=0.1, steps=20)
        except:
            min.run(fmax=0.1, steps=20)
        min2 = BFGS(Prod)
        try:
            min2.run(fmax=0.1, steps=20)
        except:
            min2.run(fmax=0.1, steps=20)

    # Get important interatomic distances
    if gl.CollectiveVarType == "changedBonds":
        cbs = ct.getChangedBonds2(Reac, Prod)
    elif gl.CollectiveVarType == "all":
        cbs = ct.getChangedBonds2(Reac, Prod)
    elif gl.CollectiveVarType == "specified":
        cbs = gl.CollectiveVar
    elif gl.CollectiveVarType == "file":
        cbs = gl.principalCoordinates

    #Get path to project along
    distPath = []
    totalPathLength = 0
    if gl.PathType == 'curve' or gl.PathType == 'gates':
        if gl.PathFile == 'none':
            Path = getPath(Reac,Prod,gl)
        else:
            Path = read(gl.PathFile,index=('::'+str(gl.pathStride)))

        distPath.append((ct.getDistMatrix(Path[0],cbs)[0],0))
        for i in range(1,len(Path)):
            l = np.linalg.norm(ct.getDistMatrix(Path[i],cbs)[0] - ct.getDistMatrix(Path[i-1], cbs)[0])
            totalPathLength += l
            distPath.append((ct.getDistMatrix(Path[i],cbs)[0],totalPathLength))
    elif gl.PathType == 'linear':
        distPath = ct.getDistMatrix(Prod,cbs)[0] - ct.getDistMatrix(Reac, cbs)[0]

    if gl.PathType == 'curve' or gl.PathType == 'gates':
        pathFile = open('reducedPath.txt','w')
        for p in distPath:
            pathFile.write('s = ' + str(p[0]) + '\n')
        pathFile.close()



    # initialise then run trajectory
    t = Trajectory.Trajectory(Reac,gl,os.getcwd(),0,False)
    t.runGenBXD(Reac,Prod,gl.maxHits,gl.maxAdapSteps,gl.PathType,distPath, cbs, gl.decorrelationSteps, gl.histogramBins,totalPathLength, gl.fixToPath, gl.pathDistCutOff,gl.epsilon)
                                     dE=0.02,
                                     mic=False)

pairing = CutAndSplicePairing(slab, n_to_optimize, blmin)
mutations = OperationSelector([1., 1., 1.], [
    MirrorMutation(blmin, n_to_optimize),
    RattleMutation(blmin, n_to_optimize),
    PermutationMutation(n_to_optimize)
])

# Relax all unrelaxed structures (e.g. the starting population)
while da.get_number_of_unrelaxed_candidates() > 0:
    a = da.get_an_unrelaxed_candidate()
    a.set_calculator(EMT())
    print('Relaxing starting candidate {0}'.format(a.info['confid']))
    dyn = BFGS(a, trajectory=None, logfile=None)
    dyn.run(fmax=0.05, steps=100)
    a.info['key_value_pairs']['raw_score'] = -a.get_potential_energy()
    da.add_relaxed_step(a)

# create the population
population = Population(data_connection=da,
                        population_size=population_size,
                        comparator=comp)

# test n_to_test new candidates
for i in range(n_to_test):
    print('Now starting configuration number {0}'.format(i))
    a1, a2 = population.get_two_candidates()
    a3, desc = pairing.get_new_individual([a1, a2])
    if a3 is None:
示例#19
0
def test_h2o():
    from ase.calculators.demonnano import DemonNano
    from ase import Atoms
    from ase.optimize import BFGS
    from ase.units import Bohr, Hartree
    import numpy as np

    d = 0.9775
    t = np.pi / 180 * 110.51
    atoms = Atoms('H2O',
                  positions=[(d, 0, 0), (d * np.cos(t), d * np.sin(t), 0),
                             (0, 0, 0)])

    input_arguments = {'DFTB': 'SCC', 'CHARGE': '0.0', 'PARAM': 'PTYPE=MAT'}

    calc = DemonNano(input_arguments=input_arguments)

    atoms.calc = calc

    # energy
    energy = atoms.get_potential_energy()
    ref = -4.08209 * Hartree

    print('energy')
    print(energy)

    error = np.sqrt(np.sum((energy - ref)**2))
    print('diff from reference:')
    print(error)

    tol = 1.0e-6
    assert (error < tol)

    # analytical forces
    forces_an = atoms.get_forces()
    ref = np.array([[0.11381E-01, -0.16761E-01, 0.0],
                    [-0.19688E-01, 0.47899E-02, 0.0],
                    [0.83062E-02, 0.11971E-01, 0.0]])

    ref *= -Hartree / Bohr

    error = np.sqrt(np.sum((forces_an - ref)**2))
    print('forces_an')
    print(forces_an)
    print('diff from reference:')
    print(error)

    tol = 1.0e-3
    assert (error < tol)

    # optimize geometry
    with BFGS(atoms) as dyn:
        dyn.run(fmax=0.01)

    positions = atoms.get_positions()

    ref = np.array([[0.943765, 0.046188, 0.0], [-0.287409, 0.900126, 0.0],
                    [-0.021346, -0.030774, 0.0]])

    error = np.sqrt(np.sum((positions - ref)**2))
    print('positions')
    print(positions)
    print('diff from reference:')
    print(error)

    tol = 1.0e-3
    assert (error < tol)

    print('tests passed')
示例#20
0
文件: co.py 项目: thonmaker/gpaw
import numpy as np

from ase.build import bulk
from ase.optimize import BFGS
from ase.io import Trajectory
from ase.constraints import StrainFilter

from gpaw import GPAW, PW

co = bulk('Co')
co.set_initial_magnetic_moments([1.6, 1.6])
co.calc = GPAW(mode=PW(700), xc='PBE', kpts=(8, 8, 4), txt='co.txt')

BFGS(StrainFilter(co)).run(0.005)

a0 = co.cell[0, 0]
c0 = co.cell[2, 2]

traj = Trajectory('co.traj', 'w')
eps = 0.01
for a in a0 * np.linspace(1 - eps, 1 + eps, 3):
    for c in c0 * np.linspace(1 - eps, 1 + eps, 3):
        co.set_cell(bulk('Co', a=a, covera=c / a).cell, scale_atoms=True)
        co.get_potential_energy()
        traj.write(co)
示例#21
0
n = size // numOfImages
#j = rank * numOfImages // size
j = (((2 * rank) + 2) // n) - 1
#calc = EMT()
for i in range(0, numOfImages):  #determines the number of nodes
    image = initial.copy()
    if i == j:
        image.set_calculator(calc)
    image.set_constraint(constraint)
    images.append(image)
images.append(final)

neb = NEB(images, climb=True, parallel=True)
neb.interpolate()

dyn = BFGS(neb, logfile="logFile")
#if rank % (size // ) == 0:
#        traj = PickleTrajectory('neb%d.traj' % j, 'w', images[j], master=True)
#        qn.attach(traj)

for i in range(0, numOfImages):
    dyn.attach(PickleTrajectory('neb-%d.traj' % i, 'w', images[i]),
               master=True)
dyn.run(fmax=0.014)

#writes the coordinates for each image in NEB path in .xyz format
string = 'structure'

path = os.getcwd()
path = path + '/neb-scratch'
if not os.path.exists(path): os.makedirs(path)
示例#22
0
def find_adhesion_potential(params):
    
    bond    =   params['bond']
    a       =   np.sqrt(3)*bond # 2.462
    h       =   params['h']
    CperArea=   (a**2*np.sqrt(3)/4)**(-1)
    
    atoms   =   make_graphene_slab(a,h,width,length,N, (True, True, False))[3]
    
    # FIX
    constraints =   []
    top         =   get_mask(atoms.positions.copy(), 'top', 1, h)
    
    bottom      =   np.logical_not(top)
    fix_bot     =   FixAtoms(mask = bottom)
    constraints.append(fix_bot)
    # END FIX
    
    # DEF CALC AND RELAX
    parameters = {'pair_style':'airebo 3.0',
                  'pair_coeff':['* * CH.airebo C'],
                  'mass'      :['* 12.01'],
                  'units'     :'metal', 
                  'boundary'  :'p p f'}
    
    calc    =   LAMMPS(parameters=parameters) #, files=['lammps.data'])
    atoms.set_calculator(calc)
    
    dyn     =   BFGS(atoms)
    dyn.run(fmax=0.05)
    # SLAB IS RELAXED
    
    atoms.set_constraint(constraints)
    zmax    =   np.amax(atoms.positions[bottom][:,2])
    
    natoms  =   0
    for i in range(len(top)):
        if top[i]: natoms += 1
    
    def get_epot(z):
        
        new_pos     =   atoms.positions.copy()
        for iat in range(len(atoms)):
            if top[iat]:
                new_pos[iat][2] = z
        
        atoms.positions =   new_pos
        return atoms.get_potential_energy()/natoms  

    
    def lj(z):
        
        ecc     =   0.002843732471143
        sigmacc =   3.4
        return 2./5*np.pi*CperArea*ecc*(2*(sigmacc**6/z**5)**2 - 5*(sigmacc**3/z**2)**2), \
            8.*ecc*CperArea*np.pi*(sigmacc**12/z**11 - sigmacc**6/z**5)
    
    # Start to move the top layer in z direction
    zrange  =   np.linspace(h - .7, h + 8, 100)
    adh_pot =   np.zeros((len(zrange), 2))
    
    for i, z in enumerate(zrange):
        adh_pot[i]  =   [z, get_epot(zmax + z)]
    
    adh_pot[:,1]    =   adh_pot[:,1] - np.min(adh_pot[:,1])   
    hmin            =   adh_pot[np.where(adh_pot[:,1] == np.min(adh_pot[:,1]))[0][0], 0]
    
    np.savetxt('adh_potential.gz', adh_pot, fmt='%.12f')
        
    fig         =   plt.figure()
    ax          =   fig.add_subplot(111)
    
    ax.plot(adh_pot[:,0], adh_pot[:,1], label = 'lamps')
    ax.plot(zrange, lj(zrange)[0] - np.min(lj(zrange)[0]), label = 'lj')
    ax.plot(zrange, lj(zrange)[1], label = 'lj')
    
    ax.scatter(hmin, 0)

    ax.set_title('Adhesion energy')
    ax.set_xlabel('height, Angst')
    ax.set_ylabel('Pot. E, eV')
    plt.legend(frameon = False)
    plt.savefig('Adhesion_energy.svg')
    plt.show()
示例#23
0
def do_short_relax(atoms, index=None, vc_relax=False, precon=True,
                   maxsteps=20):
    ''' Performs a (usually short) local optimization.

    atoms: an Atoms object 
    index: index to be used as suffix for the output files
    vc_relax: whether to also optimize the cell vectors
              (after having run several steps with fixed cell)
    precon: whether to use the preconditioned optimizers
    maxsteps: maximum number of ionic steps
    '''
    if vc_relax:
        assert precon

    t = time()
    label = 'opt' if index is None else 'opt_' + str(index)
    logfile = '%s.log' % label
    trajfile = '%s.traj' % label

    traj = Trajectory(trajfile, 'a', atoms)
    nsteps = 0
    maxsteps_no_vc = maxsteps / 2 if vc_relax else maxsteps
    fmax = 2. if vc_relax else 0.1

    try:
        if precon:
            dyn = PreconLBFGS_My(atoms, precon=Exp(A=3), variable_cell=False,
                                 use_armijo=True, a_min=1e-2, logfile=logfile)
        else:
            dyn = BFGS(atoms, maxstep=0.4, logfile=logfile)
        dyn.attach(traj)
        dyn.run(fmax=fmax, steps=maxsteps_no_vc)
    except RuntimeError:
        nsteps += dyn.get_number_of_steps()
        if precon:
            dyn = PreconFIRE_My(atoms, precon=Exp(A=3), variable_cell=False,
                                use_armijo=False, logfile=logfile,
                                dt=0.1, maxmove=0.5, dtmax=1.0, finc=1.1)
        else:
            dyn = FIRE(atoms, logfile=logfile, dt=0.1, maxmove=0.5, dtmax=1.0,
                       finc=1.1)
        dyn.attach(traj)
        steps = maxsteps_no_vc - nsteps
        dyn.run(fmax=fmax, steps=steps)

    nsteps += dyn.get_number_of_steps()

    if vc_relax:
        L = atoms.get_volume() / 4.  # largest cell vector length allowed
        cellbounds = CellBounds(bounds={'phi':[20., 160.], 'a':[1.5, L],
                                        'chi':[20., 160.], 'b':[1.5, L],
                                        'psi':[20., 160.], 'c':[1.5, L]})
        try:
            dyn = PreconLBFGS_My(atoms, precon=Exp(A=3), variable_cell=True,
                                 use_armijo=True, logfile=logfile,
                                 cellbounds=cellbounds, a_min=1e-2)
            dyn.e1 = None
            try:
                dyn._just_reset_hessian
            except AttributeError:
                dyn._just_reset_hessian = True
            dyn.attach(traj)
            steps = maxsteps - nsteps
            dyn.run(fmax=0., smax=0., steps=steps)
        except RuntimeError:
            nsteps += dyn.get_number_of_steps()
            dyn = PreconFIRE_My(atoms, precon=Exp(A=3), variable_cell=True,
                                use_armijo=False, logfile=logfile,
                                cellbounds=cellbounds,
                                dt=0.1, maxmove=0.5, dtmax=1.0, finc=1.1)
            dyn.attach(traj)
            steps = maxsteps - nsteps
            dyn.run(fmax=0., steps=steps)

    name = atoms.calc.name
    print('%s relaxation took %.3f seconds' % (name, time()-t))
    return atoms
示例#24
0
import os
from ase import Atoms
from ase.test import require
from ase.calculators.dftb import Dftb
from ase.optimize import BFGS

require('dftb')

p = os.path.dirname(__file__)
os.environ['DFTB_PREFIX'] = p if p else './'

calc = Dftb(
    label='dftb',
    Hamiltonian_SCC='No',
    Hamiltonian_PolynomialRepulsive='SetForAll {Yes}',
)

atoms = Atoms('Si2',
              positions=[[5., 5., 5.], [7., 5., 5.]],
              cell=[12.] * 3,
              pbc=False)
atoms.set_calculator(calc)

dyn = BFGS(atoms, logfile='-')
dyn.run(fmax=0.1)

e = atoms.get_potential_energy()
assert abs(e - -64.830901) < 1., e
示例#25
0
from ase.optimize import BFGS
from ase.io import read, write
from ase.calculators.emt import EMT
from ase.ga.relax_attaches import VariansBreak
import sys


fname = sys.argv[1]

print("Now relaxing {0}".format(fname))
a = read(fname)

a.set_calculator(EMT())
dyn = BFGS(a, trajectory=None, logfile=None)
vb = VariansBreak(a, dyn)
dyn.attach(vb.write)
dyn.run(fmax=0.05)

a.info["key_value_pairs"]["raw_score"] = -a.get_potential_energy()

write(fname[:-5] + "_done.traj", a)

print("Done relaxing {0}".format(fname))
示例#26
0
文件: neb1.py 项目: qsnake/gpaw
# Make a mask of zeros and ones that select fixed atoms (the
# two bottom layers):
mask = initial.positions[:, 2] - min(initial.positions[:, 2]) < 1.5 * h
constraint = FixAtoms(mask=mask)
print mask

for image in images:
    # Let all images use an EMT calculator:
    image.set_calculator(EMT())
    image.set_constraint(constraint)

# Relax the initial and final states:
QuasiNewton(initial).run(fmax=0.05)
QuasiNewton(final).run(fmax=0.05)

# Create a Nudged Elastic Band:
neb = NEB(images)

# Make a starting guess for the minimum energy path (a straight line
# from the initial to the final state):
neb.interpolate()

# Relax the NEB path:
minimizer = BFGS(neb)
minimizer.run(fmax=0.05)

# Write the path to a trajectory:
view(images)  # 126 meV
write('jump1.traj', images)
示例#27
0
from ase.structure import molecule
from ase.optimize import BFGS
from gpaw import GPAW
from gpaw.mixer import MixerDif

for name in ['H2', 'N2', 'O2', 'NO']:
    mol = molecule(name)
    mol.center(vacuum=5.0)
    calc = GPAW(xc='PBE',
                h=0.2,
                txt=name + '.txt')
    if name == 'NO':
        mol.translate((0, 0.1, 0))
        calc.set(mixer=MixerDif(0.05,5))
    mol.set_calculator(calc)
  
    opt = BFGS(mol, logfile=name + '.log', trajectory=name + '.traj')
    opt.run(fmax=0.05)
    calc.write(name)
示例#28
0
    def optNEB(self, trans, path, changePoints, mols):

        # Open files for saving IRCdata
        xyzfile3 = open((path + "/IRC3.xyz"), "w")
        MEP = open((path + "/MEP.txt"), "w")
        imagesTemp1 = []
        index = changePoints[0] - 100
        molTemp = mols[index].copy()
        imagesTemp1.append(molTemp.copy())
        for i in range(0, 100):
            imagesTemp1.append(mols[changePoints[0] - 100].copy())
        try:
            imagesTemp1.append(mols[changePoints[-1] + 300])
        except:
            imagesTemp1.append(self.CombProd.copy())
        neb1 = NEB(imagesTemp1, k=1.0, remove_rotation_and_translation=True)
        try:
            neb1.interpolate('idpp')
        except:
            neb1.interpolate()

        for i in range(0, len(imagesTemp1)):
            try:
                imagesTemp1[i] = tl.setCalc(imagesTemp1[i], self.lowString,
                                            self.lowMeth, self.lowLev)
                for i in range(0, len(trans)):
                    c = FixAtoms(trans)
                    imagesTemp1[i].set_constraint(c)
                min = BFGS(imagesTemp1[i])
                min.run(fmax=0.005, steps=40)
                del imagesTemp1[i].constraints
            except:
                pass

        optimizer = FIRE(neb1)
        try:
            optimizer.run(fmax=0.07, steps=300)
        except:
            pass
            print("passed seccond neb")

        neb1_2 = NEB(imagesTemp1, k=0.01, remove_rotation_and_translation=True)
        try:
            optimizer.run(fmax=0.07, steps=200)
        except:
            pass

        neb2 = NEB(imagesTemp1,
                   climb=True,
                   remove_rotation_and_translation=True)
        try:
            optimizer.run(fmax=0.07, steps=200)
        except:
            pass

        for i in range(0, len(imagesTemp1)):
            tl.printTraj(xyzfile3, imagesTemp1[i])

        print("NEB printed")

        xyzfile3.close()

        point = 0
        maxEne = -50000000

        try:
            for i in range(0, len(imagesTemp1)):
                MEP.write(
                    str(i) + ' ' + str(imagesTemp1[i].get_potential_energy()) +
                    '\n')
                if imagesTemp1[i].get_potential_energy() > maxEne and i > 5:
                    point = i
                    maxEne = imagesTemp1[i].get_potential_energy()
            self.TS2 = imagesTemp1[point]
        except:
            point = 0

        print("TS Climb part")
        write(path + '/TSClimbGuess.xyz', self.TS2)
        try:
            self.TS2Freqs, self.imaginaryFreq2, zpe, energy, self.TS2, rmol, pmol = self.characteriseTSExt(
                self.TS2, False, path, self.QTS3)
        except:
            self.TS2Freqs, self.imaginaryFreq2, zpe, energy, self.TS2, rmol, pmol = self.characteriseTSExt(
                self.TS2, True, path, self.QTS3)

        self.TScorrect = self.compareRandP(rmol, pmol)
        self.forwardBarrier2 = energy + zpe
blmin = closest_distances_generator(all_atom_types, ratio_of_covalent_radii=0.7)

comp = InteratomicDistanceComparator(n_top=n_to_optimize, pair_cor_cum_diff=0.015, pair_cor_max=0.7, dE=0.02, mic=False)

pairing = CutAndSplicePairing(slab, n_to_optimize, blmin)
mutations = OperationSelector(
    [1.0, 1.0, 1.0],
    [MirrorMutation(blmin, n_to_optimize), RattleMutation(blmin, n_to_optimize), PermutationMutation(n_to_optimize)],
)

# Relax all unrelaxed structures (e.g. the starting population)
while da.get_number_of_unrelaxed_candidates() > 0:
    a = da.get_an_unrelaxed_candidate()
    a.set_calculator(EMT())
    print("Relaxing starting candidate {0}".format(a.info["confid"]))
    dyn = BFGS(a, trajectory=None, logfile=None)
    dyn.run(fmax=0.05, steps=100)
    a.set_raw_score(-a.get_potential_energy())
    da.add_relaxed_step(a)

# create the population
population = Population(data_connection=da, population_size=population_size, comparator=comp)

# test n_to_test new candidates
for i in xrange(n_to_test):
    print("Now starting configuration number {0}".format(i))
    a1, a2 = population.get_two_candidates()
    a3, desc = pairing.get_new_individual([a1, a2])
    if a3 == None:
        continue
    da.add_unrelaxed_candidate(a3, description=desc)
示例#30
0
fmax = 0.05

nimages = 3

print [a.get_potential_energy() for a in PickleTrajectory('H.traj')]
images = [PickleTrajectory('H.traj')[-1]]
for i in range(nimages):
    images.append(images[0].copy())
images[-1].positions[6, 1] = 2 - images[0].positions[6, 1]
neb = NEB(images)
neb.interpolate()

for image in images[1:]:
    image.set_calculator(Calculator())

dyn = BFGS(neb, trajectory='mep.traj')

dyn.run(fmax=fmax)

for a in neb.images:
    print a.positions[-1], a.get_potential_energy()

results = [images[2].get_potential_energy()]

def run_neb_calculation(cpu):
    images = [PickleTrajectory('H.traj')[-1]]
    for i in range(nimages):
        images.append(images[0].copy())
    images[-1].positions[6, 1] = 2 - images[0].positions[6, 1]
    neb = NEB(images, parallel=True, world=cpu)
    neb.interpolate()
示例#31
0
forces_an = atoms.get_forces()

ref = np.array([[-1.26446863e-01, 4.09628186e-01, -0.00000000e+00],
                [4.27934442e-01, 2.50425467e-02, -5.14220671e-05],
                [-2.99225008e-01, -4.31533987e-01, -5.14220671e-05]])

error = np.sqrt(np.sum((forces_an - ref)**2))
print('forces_an')
print(forces_an)
print('diff from reference:')
print(error)

assert(error < tol)

# optimize geometry
dyn = BFGS(atoms)
dyn.run(fmax=0.01)

positions = atoms.get_positions()

ref = np.array([[  9.61364579e-01, 2.81689367e-02, -1.58730770e-06],
                [ -3.10444398e-01, 9.10289261e-01, -5.66399075e-06],
                [ -1.56957763e-02, -2.26044053e-02, -2.34155615e-06]])

error = np.sqrt(np.sum((positions - ref)**2))
print('positions')
print(positions)
print('diff from reference:')
print(error)

assert(error < tol)
示例#32
0
#neb = NEB(images, dynamic_relaxation=True, scale_fmax=1.)

# Interpolate the interiorimages
#neb.interpolate('idpp',mic=True)

# Give each image its respective directory and assign a calculator
home = os.getcwd()
for i in range(nimages + 2):
    imgdir = '%02d' % i
    if imgdir not in os.listdir(home):
        os.mkdir(imgdir)
    write(imgdir + '/POSCAR', images[i])
    if i not in [0, nimages + 1]:
        images[i].set_calculator(calculator(imgdir))

# Run without climbing
#opt = BFGS(neb, trajectory='neb_noclimb.traj', logfile='neb_noclimb.log')
#opt.run(fmax=0.05)
#write('Final_NEB_non_climbed.traj', images)

# Run with climbing and tighter convergence
neb = NEB(images,
          dynamic_relaxation=True,
          scale_fmax=2.,
          fmax=0.03,
          climb=True)

opt = BFGS(neb, trajectory='neb_climb.traj', logfile='neb_climb.log')
opt.run(fmax=0.03)
write('Final_NEB_climbed.traj', images)
示例#33
0
import sys
import pathlib
current_dir = pathlib.Path(__file__).resolve().parent
sys.path.append( str(current_dir) + '/../' )
from aseInterface import *
from ase.build import bulk, make_supercell
from ase.optimize import BFGS

hdnnpy=hdnnpy()
hdnnpy.set_label('./Crystal')
a1 = bulk('Si', 'diamond', a=3.6)
super=make_supercell(a1,[[2,1,1],[1,2,1],[1,1,2]])
super.set_calculator(hdnnpy)
e=super.get_potential_energy()
print(e)
f=super.get_forces()
print(f)
dyn=BFGS(super)
dyn.run(fmax=0.05)
示例#34
0
from ase import Atoms
from ase.optimize import BFGS
from gpaw import GPAW

atoms = Atoms('HOH', positions=[[0, 0, -1], [0, 1, 0], [0, 0, 1]])
atoms.center(vacuum=3.0)

calc = GPAW(mode='lcao', basis='dzp', txt='gpaw.txt')
atoms.calc = calc

opt = BFGS(atoms, trajectory='opt.traj')
opt.run(fmax=0.05)
示例#35
0
# Make a mask of zeros and ones that select fixed atoms (the
# two bottom layers):
mask = initial.positions[:, 2] - min(initial.positions[:, 2]) < 1.5 * h
constraint = FixAtoms(mask=mask)
print(mask)

for image in images:
    # Let all images use an EMT calculator:
    image.set_calculator(EMT())
    image.set_constraint(constraint)

# Relax the initial and final states:
QuasiNewton(initial).run(fmax=0.05)
QuasiNewton(final).run(fmax=0.05)

# Create a Nudged Elastic Band:
neb = NEB(images)

# Make a starting guess for the minimum energy path (a straight line
# from the initial to the final state):
neb.interpolate()

# Relax the NEB path:
minimizer = BFGS(neb)
minimizer.run(fmax=0.05)

# Write the path to a trajectory:
view(images)  # 126 meV
write('jump1.traj', images)
示例#36
0
def test_qmmm_tip4p():
    from math import cos, sin, pi

    import numpy as np
    #import matplotlib.pyplot as plt

    import ase.units as units
    from ase import Atoms
    from ase.calculators.tip4p import TIP4P, epsilon0, sigma0, rOH, angleHOH
    from ase.calculators.qmmm import (SimpleQMMM, EIQMMM, LJInteractions,
                                      LJInteractionsGeneral)
    from ase.constraints import FixInternals
    from ase.optimize import BFGS

    r = rOH
    a = angleHOH * pi / 180

    # From https://doi.org/10.1063/1.445869
    eexp = 6.24 * units.kcal / units.mol
    dexp = 2.75
    aexp = 46

    D = np.linspace(2.5, 3.5, 30)

    i = LJInteractions({('O', 'O'): (epsilon0, sigma0)})

    # General LJ interaction object
    sigma_mm = np.array([sigma0, 0, 0])
    epsilon_mm = np.array([epsilon0, 0, 0])
    sigma_qm = np.array([sigma0, 0, 0])
    epsilon_qm = np.array([epsilon0, 0, 0])
    ig = LJInteractionsGeneral(sigma_qm, epsilon_qm, sigma_mm, epsilon_mm, 3)

    for calc in [
            TIP4P(),
            SimpleQMMM([0, 1, 2], TIP4P(), TIP4P(), TIP4P()),
            SimpleQMMM([0, 1, 2], TIP4P(), TIP4P(), TIP4P(), vacuum=3.0),
            EIQMMM([0, 1, 2], TIP4P(), TIP4P(), i),
            EIQMMM([3, 4, 5], TIP4P(), TIP4P(), i, vacuum=3.0),
            EIQMMM([0, 1, 2], TIP4P(), TIP4P(), i, vacuum=3.0),
            EIQMMM([0, 1, 2], TIP4P(), TIP4P(), ig),
            EIQMMM([3, 4, 5], TIP4P(), TIP4P(), ig, vacuum=3.0),
            EIQMMM([0, 1, 2], TIP4P(), TIP4P(), ig, vacuum=3.0)
    ]:
        dimer = Atoms('OH2OH2', [(0, 0, 0), (r * cos(a), 0, r * sin(a)),
                                 (r, 0, 0), (0, 0, 0),
                                 (r * cos(a / 2), r * sin(a / 2), 0),
                                 (r * cos(a / 2), -r * sin(a / 2), 0)])
        dimer.calc = calc

        E = []
        F = []
        for d in D:
            dimer.positions[3:, 0] += d - dimer.positions[3, 0]
            E.append(dimer.get_potential_energy())
            F.append(dimer.get_forces())

        F = np.array(F)

        #plt.plot(D, E)

        F1 = np.polyval(np.polyder(np.polyfit(D, E, 7)), D)
        F2 = F[:, :3, 0].sum(1)
        error = abs(F1 - F2).max()
        assert error < 0.01

        dimer.constraints = FixInternals(bonds=[(r, (0, 1)), (r, (0, 2)),
                                                (r, (3, 4)), (r, (3, 5))],
                                         angles=[(a, (2, 0, 1)),
                                                 (a, (5, 3, 4))])
        opt = BFGS(dimer,
                   maxstep=0.04,
                   trajectory=calc.name + '.traj',
                   logfile=calc.name + 'd.log')
        opt.run(0.01)

        e0 = dimer.get_potential_energy()
        d0 = dimer.get_distance(0, 3)
        R = dimer.positions
        v1 = R[2] - R[3]
        v2 = R[3] - (R[5] + R[4]) / 2
        a0 = np.arccos(
            np.dot(v1, v2) /
            (np.dot(v1, v1) * np.dot(v2, v2))**0.5) / np.pi * 180
        fmt = '{0:>23}: {1:.3f} {2:.3f} {3:.3f} {4:.1f}'
        print(fmt.format(calc.name, -min(E), -e0, d0, a0))
        assert abs(e0 + eexp) < 0.002
        assert abs(d0 - dexp) < 0.006
        assert abs(a0 - aexp) < 2.5

    print(fmt.format('reference', 9.999, eexp, dexp, aexp))
示例#37
0
params['pair_coeff'] = ['1 1 {}'.format(pot_fn)]
calc = LAMMPS(specorder=['Pt'], files=[pot_fn], **params)

rng = np.random.RandomState(17)

atoms = bulk('Pt') * (2, 2, 2)
atoms.rattle(stdev=0.1)
atoms.cell += 2 * rng.rand(3, 3)
atoms.calc = calc

assert_allclose(atoms.get_stress(),
                calc.calculate_numerical_stress(atoms),
                atol=1e-4,
                rtol=1e-4)

opt = BFGS(ExpCellFilter(atoms), trajectory='opt.traj')
for i, _ in enumerate(opt.irun(fmax=0.05)):
    pass

cell1_ref = np.array([[0.16298762, 3.89912471, 3.92825365],
                      [4.21007577, 0.63362427, 5.04668170],
                      [4.42895706, 3.29171414, 0.44623618]])

assert_allclose(np.asarray(atoms.cell), cell1_ref, atol=1e-4, rtol=1e-4)
assert_allclose(atoms.get_stress(),
                calc.calculate_numerical_stress(atoms),
                atol=1e-4,
                rtol=1e-4)

assert i < 80, 'Expected 59 iterations, got many more: {}'.format(i)
示例#38
0
from ase.optimize import BFGS
from ase.io import read, write

initial_structure = "input.traj"
calc = Vasp2(encut=400,
             ispin=2,
             ediff=1.0e-5,
             nelm=120,
             nelmin=5,
             xc='pbe',
             kpts=(1, 1, 1),
             gamma=True,
             prec="N",
             algo="N",
             ismear=0,
             sigma=0.1,
             npar=8,
             lreal="Auto",
             lcharg=False,
             lwave=True,
             directory='calculator')

atoms = read(initial_structure)
if "initial_magmoms" in atoms.arrays.keys():
    del atoms.arrays['initial_magmoms']

atoms.set_calculator(calc)
opt = BFGS(atoms, trajectory="vasp_opt.traj", logfile="vasp_opt.log")
opt.run(fmax=0.01)
write("vasp_optimized.traj", atoms)
示例#39
0
    nsteps = '0',
    nstfout = '1',
    nstlog = '1',
    nstenergy = '1',
    nstlist = '1',
    ns_type = 'grid',
    pbc = 'xyz',
    rlist = '1.15',
    coulombtype = 'PME-Switch',
    rcoulomb = '0.8',
    vdwtype = 'shift',
    rvdw = '0.8',
    rvdw_switch = '0.75',
    DispCorr = 'Ener')
CALC_MM.generate_topology_and_g96file()
CALC_MM.generate_gromacs_run_file()

CALC_QMMM = AseQmmmManyqm(nqm_regions = 3, 
                          qm_calculators = [CALC_QM1, CALC_QM2, CALC_QM3], 
                          mm_calculator = CALC_MM,
                          link_info = 'byQM')
#                         link_info = 'byFILE') 

SYSTEM = read_gromos('gromacs_qm.g96')
SYSTEM.set_calculator(CALC_QMMM)
DYN = BFGS(SYSTEM)
DYN.run(fmax = 0.05)

print('exiting fine')
LOG_FILE.close()
#     Regardless of the dtype you use in your model, when converting it to ASE
#     calculator, it always automatically the dtype to ``torch.float64``. The
#     reason for this behavior is, at many cases, the rounding error is too
#     large for structure minimization. If you insist on using
#     ``torch.float32``, do the following instead:
#
#     .. code-block:: python
#
#         calculator = torchani.models.ANI1ccx().ase(dtype=torch.float32)

# Now let's set the calculator for ``atoms``:
atoms.set_calculator(calculator)

# Now let's minimize the structure:
print("Begin minimizing...")
opt = BFGS(atoms)
opt.run(fmax=0.001)
print()


# Now create a callback function that print interesting physical quantities:
def printenergy(a=atoms):
    """Function to print the potential, kinetic and total energy."""
    epot = a.get_potential_energy() / len(a)
    ekin = a.get_kinetic_energy() / len(a)
    print('Energy per atom: Epot = %.3feV  Ekin = %.3feV (T=%3.0fK)  '
          'Etot = %.3feV' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin))


# We want to run MD with constant energy using the Langevin algorithm
# with a time step of 1 fs, the temperature 300K and the friction
示例#41
0
    def characteriseMinExt(self, mol, high):
        # Low level optimisation with BFGS
        os.chdir((self.workingDir))
        mol = tl.setCalc(mol, self.lowString, self.lowMeth, self.lowLev)
        min = BFGS(mol)
        try:
            min.run(fmax=0.1, steps=100)
        except:
            min.run(fmax=0.1, steps=100)
        if high:
            if self.highMeth == "gauss":
                mol, freqs, zpe = tl.getGausOut(
                    self.workingDir + '/Raw/calcHigh' + self.procNum,
                    self.highLev, mol)
                os.chdir((self.workingDir))
            else:
                # Higher level optimisation via some external program
                mol = tl.setCalc(mol, self.highString, self.highMeth + 'Opt',
                                 self.highLev)
                try:
                    mol.get_forces()
                except:
                    pass
                mol = tl.getOptGeom(
                    self.workingDir + '/' + 'Raw/calcHigh' + self.procNum +
                    '/', 'none', self.Reac, self.highMeth)

                # Then calculate frequencies
                os.chdir((self.workingDir + '/Raw/' + self.procNum))
                mol = tl.setCalc(mol, self.highString, self.highMeth + 'Freq',
                                 self.highLev)
                try:
                    mol.get_forces()
                except:
                    pass
                freqs, zpe = tl.getFreqs(
                    self.workingDir + '/Raw/' + self.procNum +
                    '/Raw/calcHigh' + self.procNum, self.highMeth)
                os.chdir((self.workingDir))
        else:
            if self.lowMeth == "gauss":
                mol, freqs, zpe = tl.getGausOut(
                    self.workingDir + '/Raw/calcLow' + self.procNum,
                    self.lowLev, mol)
                os.chdir((self.workingDir))
            else:
                # Higher level optimisation via some external program
                mol = tl.setCalc(mol, self.lowString, self.lowMeth + 'Opt',
                                 self.lowLev)
                try:
                    mol.get_forces()
                except:
                    pass
                mol = tl.getOptGeom(
                    self.workingDir + '/Raw/' + 'calcLow' + self.procNum + '/',
                    'none', self.Reac, self.lowMeth)

                # Then calculate frequencies
                os.chdir((self.workingDir + '/Raw/' + self.procNum))
                mol = tl.setCalc(mol, self.lowString, self.lowMeth + 'Freq',
                                 self.lowLev)
                try:
                    mol.get_forces()
                except:
                    pass
                freqs, zpe = tl.getFreqs(
                    self.workingDir + '/Raw/' + self.procNum + '/Raw/calcLow' +
                    self.procNum, self.lowMeth)
                os.chdir((self.workingDir))
        # Finally get single point energy
        mol = tl.setCalc(mol, self.singleString, self.singleMeth,
                         self.singleLev)
        energy = mol.get_potential_energy() + zpe
        return freqs, energy, mol
示例#42
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 00:45:20 2020

@author: macenrola
"""

from ase import Atoms, io, calculators
import ase.calculators.cp2k
from gpaw import GPAW, PW
from ase.optimize import BFGS
from ase.vibrations import Vibrations

mol = io.read(
    "/home/macenrola/Documents/cb8_MV_electrochemistry_JIA/apbs_ref/benzene.pdb"
)
mol.center(vacuum=3.5)
print(mol.cell)
print(mol.positions)
c = ase.calculators.cp2k.CP2K()
CP2K.command = "env OMP_NUM_THREADS=2 mpirun -np 4 cp2k"
print(mol.set_calculator(c))

BFGS(mol).run(fmax=0.01)
vib = Vibrations(mol)

vib.run()

print(vib.summary())
示例#43
0
    def optDynPath(self, trans, path, MolList, changePoints):

        # Open files for saving IRCdata
        xyzfile = open((path + "/Data/dynPath.xyz"), "w")
        MEP = open((path + "/Data/MEP.txt"), "w")
        dyn = open((path + "/Data/traj.xyz"), "w")

        dynList = []
        end = int(changePoints + self.dynPrintStart)
        length = int(len(MolList))
        if end < length:
            endFrame = end
        else:
            endFrame = length
        for i in range(int(changePoints - self.dynPrintStart), int(endFrame),
                       self.inc):
            iMol = MolList[i].copy()
            tl.printTraj(dyn, iMol)
            iMol = tl.setCalc(iMol, self.lowString, self.lowMeth, self.lowLev)
            c = FixAtoms(trans)
            iMol.set_constraint(c)
            min = BFGS(iMol)
            try:
                min.run(fmax=0.1, steps=50)
            except:
                min.run(fmax=0.1, steps=1)
            del iMol.constraints
            tl.printTraj(xyzfile, iMol)
            dynList.append(iMol.copy())

        maxEne = -50000
        point = 0
        for i in range(0, len(dynList)):
            dynList[i] = tl.setCalc(dynList[i], self.lowString, self.lowMeth,
                                    self.lowLev)
            MEP.write(
                str(i) + ' ' + str(dynList[i].get_potential_energy()) + '\n')
            if dynList[i].get_potential_energy() > maxEne:
                point = i
                maxEne = dynList[i].get_potential_energy()

        self.TS2 = dynList[point]
        TS2Guess = self.TS2.copy()
        write(path + '/Data/TS2guess.xyz', self.TS2)
        try:
            self.TS2Freqs, self.imaginaryFreq2, zpe, energy, self.TS2, rmol, pmol = self.characteriseTSExt(
                self.TS2, True, path, self.QTS3)
        except:
            try:
                self.TS2Freqs, self.imaginaryFreq2, zpe, energy, self.TS2, rmol, pmol = self.characteriseTSExt(
                    self.TS2, False, path, self.QTS3)
            except:
                pass
        try:
            self.TS2correct = self.compareRandP(rmol, pmol)
        except:
            print("TS2 does not connect products")
            self.TS2correct = False
            self.TS2 = TS2Guess
            self.TS2Freqs, self.imaginaryFreq2, zpe, energy = self.characteriseTSinternal(
                self.TS2)

        write(path + '/TS2.xyz', self.TS2)
        self.forwardBarrier2 = energy
示例#44
0
           scale_atoms=True)

a *= (1, 2, 3)
cell0 *= np.array([1, 2, 3])[:, np.newaxis]

a.rattle()

# Verify analytical stress tensor against numerical value
s_analytical = a.get_stress()
s_numerical = a.calc.calculate_numerical_stress(a, 1e-5)
s_p_err = 100 * (s_numerical - s_analytical) / s_numerical

print("Analytical stress:\n", s_analytical)
print("Numerical stress:\n", s_numerical)
print("Percent error in stress:\n", s_p_err)
assert np.all(abs(s_p_err) < 1e-5)

# Minimize unit cell
opt = BFGS(UnitCellFilter(a))
opt.run(fmax=1e-3)

# Verify minimized unit cell using Niggli tensors
g_minimized = np.dot(a.cell, a.cell.T)
g_theory = np.dot(cell0, cell0.T)
g_p_err = 100 * (g_minimized - g_theory) / g_theory

print("Minimized Niggli tensor:\n", g_minimized)
print("Theoretical Niggli tensor:\n", g_theory)
print("Percent error in Niggli tensor:\n", g_p_err)
assert np.all(abs(g_p_err) < 1)
示例#45
0
#constraint = FixAtoms(mask=[0,1,0,1,0]) # fix OO    #Works without patch
for image in images:
    image.set_calculator(Turbomole())  #BUG No.2: (Over-)writes coord file
    image.set_constraint(constraint)

# Write all commands for the define command in a string
define_str = '\n\na coord\n\n*\nno\nb all 3-21g hondo\n*\neht\n\n-1\nno\ns\n*\n\ndft\non\nfunc pwlda\n\n\nscf\niter\n300\n\n*'
# Run define
p = Popen('define', stdout=PIPE, stdin=PIPE, stderr=STDOUT)
stdout = p.communicate(input=define_str)

# Relax initial and final states:
if 1:
    dyn1 = QuasiNewton(images[0])
    dyn1.run(fmax=0.10)
    dyn2 = QuasiNewton(images[-1])
    dyn2.run(fmax=0.10)


# Interpolate positions between initial and final states:
neb.interpolate()
if 1:
    for image in images:
        print image.get_distance(1, 2), image.get_potential_energy()

dyn = BFGS(neb, trajectory='turbomole_h3o2m.traj')
dyn.run(fmax=0.10)

for image in images:
    print image.get_distance(1, 2), image.get_potential_energy()
示例#46
0
        E.append(dimer.get_potential_energy())
        F.append(dimer.get_forces())

    F = np.array(F)

    # plt.plot(D, E)

    F1 = np.polyval(np.polyder(np.polyfit(D, E, 7)), D)
    F2 = F[:, :3, 0].sum(1)
    error = abs(F1 - F2).max()

    dimer.constraints = FixInternals(
        bonds=[(r, (0, 2)), (r, (1, 2)),
               (r, (3, 5)), (r, (4, 5))],
        angles=[(a, (0, 2, 1)), (a, (3, 5, 4))])
    opt = BFGS(dimer,
               trajectory=calc.name + '.traj', logfile=calc.name + 'd.log')
    opt.run(0.01)

    e0 = dimer.get_potential_energy()
    d0 = dimer.get_distance(2, 5)
    R = dimer.positions
    v1 = R[1] - R[5]
    v2 = R[5] - (R[3] + R[4]) / 2
    a0 = np.arccos(np.dot(v1, v2) /
                   (np.dot(v1, v1) * np.dot(v2, v2))**0.5) / np.pi * 180
    fmt = '{0:>20}: {1:.3f} {2:.3f} {3:.3f} {4:.1f}'
    print(fmt.format(calc.name, -min(E), -e0, d0, a0))
    assert abs(e0 + eexp) < 0.002
    assert abs(d0 - dexp) < 0.006
    assert abs(a0 - aexp) < 2
示例#47
0
#!/usr/bin/env python
from ase import Atom, Atoms
from ase.structure import molecule
from ase.calculators.cp2k import CP2K
from ase.optimize import BFGS
from ase.vibrations import Vibrations
from multiprocessing import Pool
import os
from time import time

atoms = molecule('H2O')
atoms.center(vacuum=5.0)


start = time()
calc = CP2K(label = 'molecules/h2o',
      xc='PBE')
atoms.set_calculator(calc)
gopt = BFGS(atoms, logfile=None)
gopt.run(fmax=1e-2)
end = time()
e = atoms.get_potential_energy()
pos = atoms.get_positions()
d = ((pos[0] - pos[1])**2).sum()**0.5
print('*===============================*')
print('{0:1.4f}  {1:1.4f} '.format( e, d))
print('time = {0}'.format(end - start))
示例#48
0
文件: neb.py 项目: robwarm/gpaw-symm
for i in range(3):

    ranks = range(i * n, (i + 1) * n)
    image = initial.copy()

    if rank in ranks:

        calc = GPAW(h=0.3,
                    kpts=(2, 2, 1),
                    txt='neb%d.txt' % j,
                    communicator=ranks)
        
        image.set_calculator(calc)
        
    image.set_constraint(constraint)
    images.append(image)
    
images.append(final)

neb = NEB(images, parallel=True)
neb.interpolate()

qn = BFGS(neb, logfile='qn.log')

traj = PickleTrajectory('neb%d.traj' % j, 'w', images[j],
                        master=(rank % n == 0))

qn.attach(traj)
qn.run(fmax=0.05)
示例#49
0
from ase.calculators.emt import EMT
from ase.optimize import BFGS
from ase.constraints import FixCom
from ase.build import molecule

atoms = molecule('H2O')
atoms.center(vacuum=4)
atoms.set_calculator(EMT())
cold = atoms.get_center_of_mass()
atoms.set_constraint(FixCom())

opt = BFGS(atoms)
opt.run(steps=5)

cnew = atoms.get_center_of_mass()

assert max(abs(cnew - cold)) < 1e-8
示例#50
0
    2.A. NEB optimization using CI-NEB as implemented in ASE. 
    2.B. NEB optimization using our machine-learning surrogate model.
    3. Comparison between the ASE NEB and our ML-NEB algorithm.
"""

# Define number of images:
n_images = 11

# 1. Structural relaxation. ##################################################

# Setup calculator:
ase_calculator = EMT()
#
slab = read('initial.traj')
slab.set_calculator(copy.deepcopy(ase_calculator))
qn = BFGS(slab, trajectory='initial_opt.traj')
qn.run(fmax=0.01)

# Final end-point:
slab = read('final.traj')
slab.set_calculator(copy.deepcopy(ase_calculator))
qn = BFGS(slab, trajectory='final_opt.traj')
qn.run(fmax=0.01)

# 2.A. NEB using ASE #########################################################

initial_ase = read('initial_opt.traj')
final_ase = read('final_opt.traj')
constraint = FixAtoms(mask=[atom.tag > 1 for atom in initial_ase])

images_ase = [initial_ase]
示例#51
0
from math import sqrt, pi
from ase import Atoms
from ase.calculators.emt import EMT
from ase.constraints import FixBondLengths
from ase.optimize import BFGS, QuasiNewton
from ase.neb import SingleCalculatorNEB
from ase.lattice.surface import fcc111, add_adsorbate
from math import sqrt, cos, sin

zpos = cos(134.3 / 2.0 * pi / 180.0) * 1.197
xpos = sin(134.3 / 2.0 * pi / 180.0) * 1.19
co2 = Atoms('COO',
            positions=[(-xpos + 1.2, 0, -zpos), (-xpos + 1.2, -1.1, -zpos),
                       (-xpos + 1.2, 1.1, -zpos)])

slab = fcc111('Au', size=(2, 2, 4), vacuum=2 * 5, orthogonal=True)
slab.center()
add_adsorbate(slab, co2, 1.5, 'bridge')
slab.set_pbc((True, True, False))
d0 = co2.get_distance(-3, -2)
d1 = co2.get_distance(-3, -1)

calc = EMT()
slab.set_calculator(calc)
constraint = FixBondLengths([[-3, -2], [-3, -1]])
slab.set_constraint(constraint)
dyn = BFGS(slab, trajectory='relax.traj')
dyn.run(fmax=0.05)
assert abs(co2.get_distance(-3, -2) - d0) < 1e-14
assert abs(co2.get_distance(-3, -1) - d1) < 1e-14
示例#52
0
constraint = FixAtoms(indices=[1, 3])  # fix OO
for image in images:
    image.set_calculator(EMT())
    image.set_constraint(constraint)

for image in images:  # O-H(shared) distance
    print(image.get_distance(1, 2), image.get_potential_energy())

# Relax initial and final states:
if 1:
    # XXX: Warning:
    # One would have to optimize more tightly in order to get
    # symmetric anion from both images[0] and [1], but
    # if one optimizes tightly one gets rotated(H2O) ... OH- instead
    dyn1 = QuasiNewton(images[0])
    dyn1.run(fmax=0.01)
    dyn2 = QuasiNewton(images[-1])
    dyn2.run(fmax=0.01)

# Interpolate positions between initial and final states:
neb.interpolate()

for image in images:
    print(image.get_distance(1, 2), image.get_potential_energy())

dyn = BFGS(neb, trajectory='emt_h3o2m.traj')
dyn.run(fmax=0.05)

for image in images:
    print(image.get_distance(1, 2), image.get_potential_energy())
示例#53
0
 def compareRandP(self, rmol, pmol):
     #Check if TS links reac and prod
     rmol = tl.setCalc(rmol, self.lowString, self.lowMeth, self.lowLev)
     min = BFGS(rmol)
     try:
         min.run(fmax=0.1, steps=50)
     except:
         min.run(fmax=0.1, steps=50)
     Name = tl.getSMILES(rmol, False).strip('\n\t')
     FullName = Name.split('____')
     if len(FullName) > 1:
         FullName = FullName[0]
     pmol = tl.setCalc(pmol, self.lowString, self.lowMeth, self.lowLev)
     min = BFGS(pmol)
     try:
         min.run(fmax=0.1, steps=50)
     except:
         min.run(fmax=0.1, steps=50)
     Name2 = tl.getSMILES(pmol, False).strip('\n\t')
     FullName2 = Name2.split('____')
     if len(FullName2) > 1:
         FullName2 = FullName2[0]
     if ((FullName == self.ReacName and FullName2 == self.ProdName)
             or (FullName2 == self.ReacName and FullName == self.ProdName)):
         TScorrect = True
     else:
         TScorrect = False
         print('TS1 try does not connect reactants and products')
     return TScorrect
示例#54
0
    if rank in ranks:
        calc = GPAW(mode=PW(500),
                    xc='PBE',
                    basis='dzp',
                    maxiter=99,
                    kpts=(2, 2, 1),
                    txt='neb{}.txt'.format(j),
                    communicator=ranks)
        image.set_calculator(calc)
    images.append(image)

images.append(final)

# Initialize neb object
neb = NEB(images, k=0.5, parallel=True, method='eb', climb=False)
#neb.interpolate()

# Converge path roughly before invoking the CI method
qn = BFGS(neb, trajectory='neb_rough.traj')
qn.run(fmax=0.15)

# Turn on CI
neb.climb = True

# Fully converge the path including an image climbing to the saddle point
qn = BFGS(neb, trajectory='neb_CI.traj')
qn.run(fmax=0.09)

write('neb_done.traj', images)
示例#55
0
def run_moldy(N, save = False):
    
    # 
    params      =   {'bond':bond, 'a':a, 'h':h}
    
    # DEFINE FILES
    mdfile, mdlogfile, mdrelax  =   get_fileName(N, 'tear_E_rebo+KC_v', taito, v, edge)  
    
    # GRAPHENE SLAB
    atoms               =   make_graphene_slab(a,h,width,length,N, \
                                               edge_type = edge, h_pass = True, \
                                               stacking = 'abc')[3]
    
    view(atoms)
    #exit()
    params['ncores']    =   ncores
    params['positions'] =   atoms.positions.copy() 
    params['pbc']       =   atoms.get_pbc()
    params['cell']      =   atoms.get_cell().diagonal()
    params['ia_dist']   =   10
    params['chemical_symbols']  \
                        =   atoms.get_chemical_symbols()
    
    # FIX
    constraints =   []
    print 'hii'
    left        =   get_ind(atoms.positions.copy(), 'left', 2, bond)
    top         =   get_ind(atoms.positions.copy(), 'top', fixtop - 1, left)
    rend_t      =   get_ind(atoms.positions.copy(), 'rend', atoms.get_chemical_symbols(), 1, edge)
    rend        =   get_ind(atoms.positions.copy(), 'rend', atoms.get_chemical_symbols(), fixtop, edge)
    
    print rend
    print 'hoo' 
    exit()
    
    fix_left    =   FixAtoms(indices = left)
    fix_top     =   FixAtoms(indices = top)
    
    add_kc      =   KC_potential_p(params)

    
    for ind in rend:
        fix_deform  =   FixedPlane(ind, (0., 0., 1.))
        constraints.append(fix_deform)
    
    for ind in rend_t:
        fix_deform  =   FixedPlane(ind, (0., 0., 1.))
        constraints.append(fix_deform)
    
    constraints.append(fix_left)
    constraints.append(fix_top)
    constraints.append(add_kc)
    # END FIX
    
    # CALCULATOR LAMMPS 
    parameters = {'pair_style':'rebo',
                  'pair_coeff':['* * CH.airebo C H'],
                  'mass'      :['1 12.0', '2 1.0'],
                  'units'     :'metal', 
                  'boundary'  :'f p f'}
    
    calc    =   LAMMPS(parameters=parameters) 
    atoms.set_calculator(calc)
    # END CALCULATOR
    
    #view(atoms)
    
    # TRAJECTORY
    if save:    traj    =   PickleTrajectory(mdfile, 'w', atoms)
    else:       traj    =   None
    
    #data    =   np.zeros((M/interval, 5))
    
    # RELAX
    atoms.set_constraint(add_kc)
    dyn     =   BFGS(atoms, trajectory = mdrelax)
    dyn.run(fmax=0.05)
    
    # FIX AFTER RELAXATION
    atoms.set_constraint(constraints)
    
    # DYNAMICS
    dyn     =   Langevin(atoms, dt*units.fs, T*units.kB, fric)
    n       =   0
    header  =   '#t [fs], d [Angstrom], epot_tot [eV], ekin_tot [eV], etot_tot [eV] \n'
    log_f   =   open(mdlogfile, 'w')
    log_f.write(header)            
    log_f.close()

    if T != 0:
        # put initial MaxwellBoltzmann velocity distribution
        mbd(atoms, T*units.kB)
    
    
    print 'Start the dynamics for N = %i' %N
    
    for i in range(0, M):
        
        if T == 0:
            for ind in rend:
                atoms[ind].position[2] -= dz 
        elif T != 0:
            if tau < i*dt:
                hw   =   i*dz
                for ind in rend:
                    atoms[ind].position[2] -= dz 
            
        dyn.run(1)
        
        if i%interval == 0:

            epot, ekin  =   saveAndPrint(atoms, traj, False)[:2]
            
            if T != 0:
                if tau < i*dt:  hw   =   i*dz - tau*v
                else: hw =   0
            else:   hw = i*dz
                
            data        =   [i*dt, hw, epot, ekin, epot + ekin]
            
            if save:
                log_f   =   open(mdlogfile, 'a')
                stringi =   ''
                for k,d in enumerate(data):
                    if k == 0:           
                        stringi += '%.2f ' %d
                    elif k == 1:
                        stringi += '%.6f ' %d
                    else:
                        stringi += '%.12f ' %d
                
                log_f.write(stringi +  '\n')
                log_f.close()
                  

            n += 1
        
        
        if save and T != 0 and i*dt == tau:
            log_f   =   open(mdlogfile, 'a')
            log_f.write('# Thermalization complete. ' +  '\n')
            log_f.close()
            
            
        if 1e2 <= M:    
            if i%(int(M/100)) == 0: print 'ready = %.1f' %(i/(int(M/100))) + '%' 
示例#56
0
from ase.io import read
from ase.constraints import FixAtoms
from ase.neb import NEB
from JDFTx import JDFTx
from ase.optimize import BFGS
from ase.parallel import rank, size

initial = read('initial.traj')
final = read('final.traj')


constraint = FixAtoms(mask=[atom.tag > 1 for atom in initial])
images = [initial]



for i in range(3):
    image = initial.copy()
    image.set_calculator(JDFTx(executable='mpirun -n 1 -N 1 -c 12 --exclude=node[1001-1032] /home/jfm343/JDFTXDIR/build/jdftx', pseudoDir='/home/jfm343/JDFTXDIR/build/pseudopotentials',pseudoSet='GBRV-pbe',commands={'elec-cutoff' : '20 100','kpoint-folding' : '2 2 1'}))
    image.set_constraint(constraint)
    images.append(image)
images.append(final)

neb = NEB(images, parallel=True)
neb.interpolate()
qn = BFGS(neb, trajectory='neb.traj')
qn.run(fmax=0.05)
示例#57
0
文件: neb.py 项目: essil1/ase-laser
print([a.get_potential_energy() for a in Trajectory('H.traj')])
images = [Trajectory('H.traj')[-1]]
for i in range(nimages):
    images.append(images[0].copy())
images[-1].positions[6, 1] = 2 - images[0].positions[6, 1]
neb = NEB(images)
neb.interpolate()
if 0:  # verify that initial images make sense
    from ase.visualize import view
    view(neb.images)

for image in images:
    image.set_calculator(MorsePotential())

dyn = BFGS(neb, trajectory='mep.traj')  # , logfile='mep.log')

dyn.run(fmax=fmax)

for a in neb.images:
    print(a.positions[-1], a.get_potential_energy())

neb.climb = True
dyn.run(fmax=fmax)

# Check NEB tools.
nt_images = read('mep.traj@-4:')
nebtools = NEBTools(nt_images)
nt_fmax = nebtools.get_fmax(climb=True)
Ef, dE = nebtools.get_barrier()
print(Ef, dE, fmax, nt_fmax)
示例#58
0
def test_dynamic_neb():
    # Global counter of force evaluations:
    force_evaluations = [0]

    class EMT(OrigEMT):
        def calculate(self, *args, **kwargs):
            force_evaluations[0] += 1
            OrigEMT.calculate(self, *args, **kwargs)

    # Build Pt(111) slab with six surface atoms and add oxygen adsorbate
    initial = fcc111('Pt', size=(3, 2, 3), orthogonal=True)
    initial.center(axis=2, vacuum=10)
    oxygen = Atoms('O')
    oxygen.translate(initial[7].position + (0., 0., 3.5))
    initial.extend(oxygen)

    # EMT potential
    initial.calc = EMT()

    # Optimize initial state
    opt = BFGS(initial)
    opt.run(fmax=0.03)

    # Move oxygen adsorbate to neighboring hollow site
    final = initial.copy()
    final[18].x += 2.8
    final[18].y += 1.8

    final.calc = EMT()

    opt = BFGS(final)
    opt.run(fmax=0.03)

    # NEB with seven interior images
    images = [initial]
    for i in range(7):
        images.append(initial.copy())
    images.append(final)

    fmax = 0.03  # Same for NEB and optimizer

    for i in range(1, len(images) - 1):
        calc = EMT()
        images[i].calc = calc

    def run_NEB():
        if method == 'dyn':
            neb = DyNEB(images, fmax=fmax, dynamic_relaxation=True)
            neb.interpolate()
        elif method == 'dyn_scale':
            neb = DyNEB(images,
                        fmax=fmax,
                        dynamic_relaxation=True,
                        scale_fmax=6.)
            neb.interpolate()
        else:
            # Default NEB
            neb = DyNEB(images, dynamic_relaxation=False)
            neb.interpolate()

        # Optimize and check number of calculations.
        # We use a hack with a global counter to count the force evaluations:
        force_evaluations[0] = 0
        opt = BFGS(neb)
        opt.run(fmax=fmax)
        force_calls.append(force_evaluations[0])

        # Get potential energy of transition state.
        Emax.append(
            np.sort([image.get_potential_energy()
                     for image in images[1:-1]])[-1])

    force_calls, Emax = [], []
    for method in ['def', 'dyn', 'dyn_scale']:
        run_NEB()

    # Check force calculation count for default and dynamic NEB implementations
    print('\n# Force calls with default NEB: {}'.format(force_calls[0]))
    print('# Force calls with dynamic NEB: {}'.format(force_calls[1]))
    print('# Force calls with dynamic and scaled NEB: {}\n'.format(
        force_calls[2]))
    assert force_calls[2] < force_calls[1] < force_calls[0]

    # Assert reaction barriers are within 1 meV of default NEB
    assert (abs(Emax[1] - Emax[0]) < 1e-3)
    assert (abs(Emax[2] - Emax[0]) < 1e-3)
from ase.build import fcc111, add_adsorbate
slab = fcc111('Al', size=(2, 2, 3))
add_adsorbate(slab, 'Al', 2, 'hcp')
slab.center(vacuum=5.0, axis=2)

#view and set calculator
from ase.visualize import view
view(slab, viewer='x3d')
slab.set_calculator(zhou)
slab.get_potential_energy()
print(slab.get_calculator())
print(slab.get_potential_energy())

#relax structure
from ase.optimize import BFGS
dyn = BFGS(slab)
dyn.run(fmax=0.0001)

#make second endpoint structure, add adatom and relax
slab_2 = fcc111('Al', size=(2, 2, 3))
add_adsorbate(slab_2, 'Al', 2, 'fcc')
slab_2.center(vacuum=5.0, axis=2)
slab_2.set_calculator(EAM(potential=pot_file))

view(slab_2, viewer='x3d')
dyn = BFGS(slab_2)
slab_2.get_potential_energy()
print(slab_2.get_potential_energy())
dyn.run(fmax=0.0001)

#import NEB
示例#60
-1
def eval_energy(input):
    """Function to evaluate energy of an individual
    Inputs:
        input = [Optimizer class object with parameters, Individual class structure to be evaluated]
    Outputs:
        energy, bul, individ, signal
        energy = energy of Individual evaluated
        bul = bulk structure of Individual if simulation structure is Defect
        individ = Individual class structure evaluated
        signal = string of information about evaluation
    """
    if input[0]==None:
        energy=0
        bul=0
        individ=0
        rank = MPI.COMM_WORLD.Get_rank()
        signal='Evaluated none individual on '+repr(rank)+'\n'
    else:
        [Optimizer, individ]=input
    if Optimizer.calc_method=='MAST':
        energy = individ.energy
        bul = individ.energy
        signal = 'Recieved MAST structure\n'
    else:
        if Optimizer.parallel: rank = MPI.COMM_WORLD.Get_rank()
        if not Optimizer.genealogy:
            STR='----Individual ' + str(individ.index)+ ' Optimization----\n'
        else:
            STR='----Individual ' + str(individ.history_index)+ ' Optimization----\n'
        indiv=individ[0]
        if 'EE' in Optimizer.debug:
            debug = True
        else:
            debug = False
        if debug: 
            write_xyz(Optimizer.debugfile,indiv,'Recieved by eval_energy')
            Optimizer.debugfile.flush()
        if Optimizer.structure=='Defect':
            indi=indiv.copy()
            if Optimizer.alloy==True:
                bulk=individ.bulki
            else:
                bulk=individ.bulko
            nat=indi.get_number_of_atoms()
            csize=bulk.get_cell()                                                                                                         
            totalsol=Atoms(cell=csize, pbc=True)
            totalsol.extend(indi)
            totalsol.extend(bulk)
            for sym,c,m,u in Optimizer.atomlist:
                nc=len([atm for atm in totalsol if atm.symbol==sym])
                STR+='Defect configuration contains '+repr(nc)+' '+repr(sym)+' atoms\n'
    
        elif Optimizer.structure=='Surface':
            totalsol=Atoms()
            totalsol.extend(indiv)
            nat=indiv.get_number_of_atoms()
            totalsol.extend(individ.bulki)
            for sym,c,m,u in Optimizer.atomlist:
                nc=len([atm for atm in totalsol if atm.symbol==sym])
                STR+='Surface-Bulk configuration contains '+repr(nc)+' '+repr(sym)+' atoms\n'
            cell=numpy.maximum.reduce(indiv.get_cell())
            totalsol.set_cell([cell[0],cell[1],500])
            totalsol.set_pbc([True,True,False])
    
        if Optimizer.constrain_position:
            ts = totalsol.copy()
            indc,indb,vacant,swap,stro = find_defects(ts,Optimizer.solidbulk,0)
            sbulk = Optimizer.solidbulk.copy()
            bcom = sbulk.get_center_of_mass()
            #totalsol.translate(-bulkcom)
            #indc.translate(-bulkcom)
            #totalsol.append(Atom(position=[0,0,0]))
    # 			for one in indc:
    # 				index = [atm.index for atm in totalsol if atm.position[0]==one.position[0] and atm.position[1]==one.position[1] and atm.position[2]==one.position[2]][0]
    # 				if totalsol.get_distance(-1,index) > Optimizer.sf:
    # 					r = random.random()
    # 					totalsol.set_distance(-1,index,Optimizer.sf*r,fix=0)
    # 			totalsol.pop()
    # 			totalsol.translate(bulkcom)
            com = indc.get_center_of_mass()
            dist = (sum((bcom[i] - com[i])**2 for i in range(3)))**0.5
            if dist > Optimizer.sf:
                STR+='Shifting structure to within region\n'
                r = random.random()*Optimizer.sf
                comv = numpy.linalg.norm(com)
                ncom = [one*r/comv for one in com]
                trans = [ncom[i]-com[i] for i in range(3)]
                indices = []
                for one in indc:
                    id = [atm.index for atm in totalsol if atm.position[0]==one.position[0] and atm.position[1]==one.position[1] and atm.position[2]==one.position[2]][0]
                    totalsol[id].position += trans
    
        # Check for atoms that are too close
        min_len=0.7
        #pdb.set_trace()
        if not Optimizer.fixed_region:
            if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                cutoffs=[2.0 for one in totalsol]
                nl=NeighborList(cutoffs,bothways=True,self_interaction=False)
                nl.update(totalsol)
                for one in totalsol[0:nat]:
                    nbatoms=Atoms()
                    nbatoms.append(one)
                    indices, offsets=nl.get_neighbors(one.index)
                    for index, d in zip(indices,offsets):
                        index = int(index)
                        sym=totalsol[index].symbol
                        pos=totalsol[index].position + numpy.dot(d,totalsol.get_cell())
                        at=Atom(symbol=sym,position=pos)
                        nbatoms.append(at)
                    while True:
                        dflag=False
                        for i in range(1,len(nbatoms)):
                            d=nbatoms.get_distance(0,i)
                            if d < min_len:
                                nbatoms.set_distance(0,i,min_len+.01,fix=0.5)
                                STR+='--- WARNING: Atoms too close (<0.7A) - Implement Move ---\n'
                                dflag=True
                        if dflag==False:
                            break
                    for i in range(len(indices)):
                        totalsol[indices[i]].position=nbatoms[i+1].position
                    totalsol[one.index].position=nbatoms[0].position
                    nl.update(totalsol)
                if debug:
                    write_xyz(Optimizer.debugfile,totalsol,'After minlength check')
                    Optimizer.debugfile.flush()
            else:
                for i in range(len(indiv)):
                    for j in range(len(indiv)):
                        if i != j:
                            d=indiv.get_distance(i,j)
                            if d < min_len:
                                indiv.set_distance(i,j,min_len,fix=0.5)
                                STR+='--- WARNING: Atoms too close (<0.7A) - Implement Move ---\n'
                if debug:
                    write_xyz(Optimizer.debugfile,indiv,'After minlength check')
                    Optimizer.debugfile.flush()
    
        # Set calculator to use to get forces/energies
        if Optimizer.parallel:
            calc = setup_calculator(Optimizer)
            if Optimizer.fixed_region:
                pms=copy.deepcopy(calc.parameters)
                try:
                    pms['mass'][len(pms['mass'])-1] += '\ngroup RO id >= '+repr(nat)+'\nfix freeze RO setforce 0.0 0.0 0.0\n'
                except KeyError:
                    pms['pair_coeff'][0] += '\ngroup RO id >= '+repr(nat)+'\nfix freeze RO setforce 0.0 0.0 0.0\n'
                calc = LAMMPS(parameters=pms, files=calc.files, keep_tmp_files=calc.keep_tmp_files, tmp_dir=calc.tmp_dir)
                lmin = copy.copy(Optimizer.lammps_min)
                Optimizer.lammps_min = None
                Optimizer.static_calc = setup_calculator(Optimizer)
                Optimizer.lammps_min = lmin
        else:
            calc=Optimizer.calc
        if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
            totalsol.set_calculator(calc)
            totalsol.set_pbc(True)
        else:
            indiv.set_calculator(calc)
            indiv.set_pbc(True)	#Current bug in ASE optimizer-Lammps prevents pbc=false 
            if Optimizer.structure=='Cluster':
                indiv.set_cell([500,500,500])
                indiv.translate([250,250,250])
    
        cwd=os.getcwd()
        # Perform Energy Minimization
        if not Optimizer.parallel:
            Optimizer.output.flush()
        if Optimizer.ase_min == True:
            try:
                if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                    dyn=BFGS(totalsol)
                else:
                    dyn=BFGS(indiv)
                dyn.run(fmax=Optimizer.ase_min_fmax, steps=Optimizer.ase_min_maxsteps)
            except OverflowError:
                STR+='--- Error: Infinite Energy Calculated - Implement Random ---\n'
                box=Atoms()
                indiv=gen_pop_box(Optimizer.natoms, Optimizer.atomlist, Optimizer.size)
                indiv.set_calculator(calc)
                dyn=BFGS(indiv)
                dyn.run(fmax=fmax, steps=steps)
            except numpy.linalg.linalg.LinAlgError:
                STR+='--- Error: Singular Matrix - Implement Random ---\n'
                indiv=gen_pop_box(Optimizer.natoms, Optimizer.atomlist, Optimizer.size)
                indiv.set_calculator(calc)
                dyn=BFGS(indiv)
                dyn.run(fmax=fmax, steps=steps)
            # Get Energy of Minimized Structure
            if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                en=totalsol.get_potential_energy()
                #force=numpy.maximum.reduce(abs(totalsol.get_forces()))
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure=totalsol.get_isotropic_pressure(totalsol.get_stress())
                    cell_max=numpy.maximum.reduce(totalsol.get_positions())
                    cell_min=numpy.minimum.reduce(totalsol.get_positions())
                    cell=cell_max-cell_min
                    volume=cell[0]*cell[1]*cell[2]
                else:
                    pressure=0
                    volume=0
                na=totalsol.get_number_of_atoms()
                ena=en/na
                energy=en
                individ[0]=totalsol[0:nat]
                bul=totalsol[(nat):len(totalsol)]
                STR+='Number of positions = '+repr(len(bul)+len(individ[0]))+'\n'
                individ[0].set_cell(csize)
                indiv=individ[0]
            else:
                en=indiv.get_potential_energy()
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure=indiv.get_isotropic_pressure(indiv.get_stress())
                    cell_max=numpy.maximum.reduce(indiv.get_positions())
                    cell_min=numpy.minimum.reduce(indiv.get_positions())
                    cell=cell_max-cell_min
                    volume=cell[0]*cell[1]*cell[2]
                else: 
                    pressure=0
                    volume=0
                na=indiv.get_number_of_atoms()
                ena=en/na
                energy=ena
                individ[0]=indiv
                bul=0
        else:
            if Optimizer.structure=='Defect' or Optimizer.structure=='Surface':
                if Optimizer.calc_method=='VASP':
                    en=totalsol.get_potential_energy()
                    calcb=Vasp(restart=True)
                    totalsol=calcb.get_atoms()
                    stress=calcb.read_stress()
                else:
                    try:
                        totcop=totalsol.copy()
                        if debug: write_xyz(Optimizer.debugfile,totcop,'Individual sent to lammps')
                        OUT=totalsol.calc.calculate(totalsol)
                        totalsol=OUT['atoms']
                        totalsol.set_pbc(True)
                        if Optimizer.fixed_region:
                            if debug:
                                print 'Energy of fixed region calc = ', OUT['thermo'][-1]['pe']
                            totalsol.set_calculator(Optimizer.static_calc)
                            OUT=totalsol.calc.calculate(totalsol)
                            totalsol=OUT['atoms']
                            totalsol.set_pbc(True)
                            if debug:
                                print 'Energy of static calc = ', OUT['thermo'][-1]['pe']
                        en=OUT['thermo'][-1]['pe']
                        stress=numpy.array([OUT['thermo'][-1][i] for i in ('pxx','pyy','pzz','pyz','pxz','pxy')])*(-1e-4*GPa)
                        #force=numpy.maximum.reduce(abs(totalsol.get_forces()))
                        if debug:
                            write_xyz(Optimizer.debugfile,totalsol,'After Lammps Minimization')
                            Optimizer.debugfile.flush()
                    except Exception, e:
                        os.chdir(cwd)
                        STR+='WARNING: Exception during energy eval:\n'+repr(e)+'\n'
                        f=open('problem-structures.xyz','a')
                        write_xyz(f,totcop,data='Starting structure hindex='+individ.history_index)
                        write_xyz(f,totalsol,data='Lammps Min structure')
                        en=10
                        stress=0
                        f.close()
                if Optimizer.fitness_scheme == 'enthalpyfit':
                    pressure=totalsol.get_isotropic_pressure(stress)
                    cell_max=numpy.maximum.reduce(totalsol.get_positions())
                    cell_min=numpy.minimum.reduce(totalsol.get_positions())
                    cell=cell_max-cell_min
                    volume=cell[0]*cell[1]*cell[2]
                else:
                    pressure=totalsol.get_isotropic_pressure(stress)
                    volume=0
                na=totalsol.get_number_of_atoms()
                ena=en/na
                energy=en
                if Optimizer.structure=='Defect':
                    if Optimizer.fixed_region==True or Optimizer.finddefects==False:
                        individ[0]=totalsol[0:nat]
                        bul=totalsol[(nat):len(totalsol)]
                        individ[0].set_cell(csize)
                    else:
                        if 'FI' in Optimizer.debug:
                            outt=find_defects(totalsol,Optimizer.solidbulk,Optimizer.sf,atomlistcheck=Optimizer.atomlist,trackvacs=Optimizer.trackvacs,trackswaps=Optimizer.trackswaps,debug=Optimizer.debugfile)
                        else:
                            outt=find_defects(totalsol,Optimizer.solidbulk,Optimizer.sf,atomlistcheck=Optimizer.atomlist,trackvacs=Optimizer.trackvacs,trackswaps=Optimizer.trackswaps,debug=False)
                        individ[0]=outt[0]
                        bul=outt[1]
                        individ.vacancies = outt[2]
                        individ.swaps = outt[3]
                        STR += outt[4]
                    indiv=individ[0]
                else:
                    top,bul=find_top_layer(totalsol,Optimizer.surftopthick)
                    indiv=top.copy()
                    individ[0]=top.copy()
            else: