Пример #1
0
 def calc_stacking_fault(self, structure, elements):
     if structure != 'fcc':
         raise ValueError(
             "Cannot calculate stacking fault energy of structure " +
             structure)
     a = self.latticeconstants[(structure, elements)]
     atoms = fcc111(elements[0], (1, 2, 5), orthogonal=True, a=a)
     atoms.set_pbc(True)
     atoms = atoms.repeat(self.properties['sf_repeat'])
     atoms.set_calculator(self.get_calc())
     dyn = QuasiNewton(atoms, logfile=None, trajectory=None)
     dyn.run(fmax=0.02)
     e_sf = atoms.get_potential_energy()
     n_sf = len(atoms)
     atoms = fcc111(elements[0], (1, 2, 6), orthogonal=True, a=a)
     atoms.set_pbc(True)
     atoms = atoms.repeat(self.properties['sf_repeat'])
     atoms.set_calculator(self.get_calc())
     dyn = QuasiNewton(atoms, logfile=None, trajectory=None)
     dyn.run(fmax=0.02)
     e_bulk = atoms.get_potential_energy()
     n_bulk = len(atoms)
     layers = self.properties['sf_repeat'][2]
     uc = atoms.get_cell()
     area = uc[0, 0] * uc[1, 1]
     result = (e_sf - e_bulk * n_sf / n_bulk) / layers / area
     result /= 1e-3 * kJ * 1e-20
     self.values[('stacking_fault', structure, elements)] = result
Пример #2
0
    def evaluate(self, imember):
        entry = self.population.get_entry(imember)
        pcm_structure = pychemia.Structure.from_dict(entry['structure'])

        ase_structure = pychemia.external.ase.pychemia2ase(pcm_structure)
        ase_structure.set_calculator(LennardJones())

        dyn = QuasiNewton(ase_structure)
        dyn.run()

        ase_structure.set_constraint(
            FixAtoms(mask=[True for atom in ase_structure]))
        ucf = UnitCellFilter(ase_structure)
        qn = QuasiNewton(ucf)
        qn.run()

        new_structure = pychemia.external.ase.ase2pychemia(ase_structure)
        energy = ase_structure.get_potential_energy()
        forces = ase_structure.get_forces()
        stress = ase_structure.get_stress()
        new_properties = {
            'energy': float(energy),
            'forces': generic_serializer(forces),
            'stress': generic_serializer(stress)
        }

        self.population.db.update(imember,
                                  structure=new_structure,
                                  properties=new_properties)
Пример #3
0
def test_replay(testdir):
    # Distance between Cu atoms on a (100) surface:
    d = 3.6 / sqrt(2)
    a = Atoms('Cu',
              positions=[(0, 0, 0)],
              cell=(d, d, 1.0),
              pbc=(True, True, False))
    a *= (2, 2, 1)  # 2x2 (100) surface-cell

    # Approximate height of Ag atom on Cu(100) surfece:
    h0 = 2.0
    a += Atom('Ag', (d / 2, d / 2, h0))

    if 0:
        view(a)

    constraint = FixAtoms(range(len(a) - 1))
    a.calc = EMT()
    a.set_constraint(constraint)

    with QuasiNewton(a, trajectory='AgCu1.traj', logfile='AgCu1.log') as dyn1:
        dyn1.run(fmax=0.1)

    a = read('AgCu1.traj')
    a.calc = EMT()
    print(a.constraints)

    with QuasiNewton(a, trajectory='AgCu2.traj', logfile='AgCu2.log') as dyn2:
        dyn2.replay_trajectory('AgCu1.traj')
        dyn2.run(fmax=0.01)
Пример #4
0
def test_turbomole_h3o2m():
    # http://jcp.aip.org/resource/1/jcpsa6/v97/i10/p7507_s1
    doo = 2.74
    doht = 0.957
    doh = 0.977
    angle = radians(104.5)
    initial = Atoms('HOHOH',
                    positions=[(-sin(angle) * doht, 0., cos(angle) * doht),
                               (0., 0., 0.), (0., 0., doh), (0., 0., doo),
                               (sin(angle) * doht, 0., doo - cos(angle) * doht)
                               ])
    if 0:
        view(initial)

    final = Atoms('HOHOH',
                  positions=[(-sin(angle) * doht, 0., cos(angle) * doht),
                             (0., 0., 0.), (0., 0., doo - doh), (0., 0., doo),
                             (sin(angle) * doht, 0., doo - cos(angle) * doht)])
    if 0:
        view(final)

    # Make band:
    images = [initial.copy()]
    for i in range(3):
        images.append(initial.copy())
    images.append(final.copy())
    neb = NEB(images, climb=True)

    # 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*')

    # Set constraints and calculator:
    constraint = FixAtoms(indices=[1,
                                   3])  # fix OO BUG No.1: fixes atom 0 and 1
    # constraint = FixAtoms(mask=[0,1,0,1,0]) # fix OO    #Works without patch
    for image in images:
        image.calc = Turbomole(define_str=define_str)
        image.set_constraint(constraint)

    # 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())
Пример #5
0
def test_Ag_Cu100():
    from math import sqrt
    from ase import Atom, Atoms
    from ase.neb import NEB
    from ase.constraints import FixAtoms
    from ase.vibrations import Vibrations
    from ase.calculators.emt import EMT
    from ase.optimize import QuasiNewton, BFGS

    # Distance between Cu atoms on a (100) surface:
    d = 3.6 / sqrt(2)
    initial = Atoms('Cu',
                    positions=[(0, 0, 0)],
                    cell=(d, d, 1.0),
                    pbc=(True, True, False))
    initial *= (2, 2, 1)  # 2x2 (100) surface-cell

    # Approximate height of Ag atom on Cu(100) surfece:
    h0 = 2.0
    initial += Atom('Ag', (d / 2, d / 2, h0))

    # Make band:
    images = [initial.copy() for i in range(6)]
    neb = NEB(images, climb=True)

    # Set constraints and calculator:
    constraint = FixAtoms(range(len(initial) - 1))
    for image in images:
        image.calc = EMT()
        image.set_constraint(constraint)

    # Displace last image:
    images[-1].positions[-1] += (d, 0, 0)

    # Relax height of Ag atom for initial and final states:
    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.positions[-1], image.get_potential_energy())

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

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

    a = images[0]
    vib = Vibrations(a, [4])
    vib.run()
    print(vib.get_frequencies())
    vib.summary()
    print(vib.get_mode(-1))
    vib.write_mode(-1, nimages=20)
Пример #6
0
def test_h3o2m():
    # http://jcp.aip.org/resource/1/jcpsa6/v97/i10/p7507_s1
    doo = 2.74
    doht = 0.957
    doh = 0.977
    angle = radians(104.5)
    initial = Atoms('HOHOH',
                    positions=[(-sin(angle) * doht, 0, cos(angle) * doht),
                               (0., 0., 0.), (0., 0., doh), (0., 0., doo),
                               (sin(angle) * doht, 0., doo - cos(angle) * doht)
                               ])
    if 0:
        view(initial)

    final = Atoms('HOHOH',
                  positions=[(-sin(angle) * doht, 0., cos(angle) * doht),
                             (0., 0., 0.), (0., 0., doo - doh), (0., 0., doo),
                             (sin(angle) * doht, 0., doo - cos(angle) * doht)])
    if 0:
        view(final)

    # Make band:
    images = [initial.copy()]
    for i in range(3):
        images.append(initial.copy())
    images.append(final.copy())
    neb = NEB(images, climb=True)

    def calculator():
        return NWChem(task='gradient', theory='scf', charge=-1)

    # Set constraints and calculator:
    constraint = FixAtoms(indices=[1, 3])  # fix OO
    for image in images:
        image.calc = calculator()
        image.set_constraint(constraint)

    # 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='nwchem_h3o2m.traj')
    dyn.run(
        fmax=0.10)  # use better basis (e.g. aug-cc-pvdz) for NEB to converge

    for image in images:
        print(image.get_distance(1, 2), image.get_potential_energy())
Пример #7
0
Файл: neb.py Проект: lqcata/ase
def get_atoms():
    # 2x2-Al(001) surface with 3 layers and an
    # Au atom adsorbed in a hollow site:
    slab = fcc100('Al', size=(2, 2, 3))
    add_adsorbate(slab, 'Au', 1.7, 'hollow')
    slab.center(axis=2, vacuum=4.0)

    # Fix second and third layers:
    mask = [atom.tag > 1 for atom in slab]
    slab.set_constraint(FixAtoms(mask=mask))

    # Use EMT potential:
    slab.set_calculator(EMT())

    # Initial state:
    qn = QuasiNewton(slab, logfile=None)
    qn.run(fmax=0.05)
    initial = slab.copy()

    # Final state:
    slab[-1].x += slab.get_cell()[0, 0] / 2
    qn = QuasiNewton(slab, logfile=None)
    qn.run(fmax=0.05)
    final = slab.copy()

    # Setup a NEB calculation
    constraint = FixAtoms(mask=[atom.tag > 1 for atom in initial])

    images = [initial]
    for i in range(3):
        image = initial.copy()
        image.set_constraint(constraint)
        images.append(image)

    images.append(final)

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

    def set_calculator(calc):
        i = 0
        for image in neb.images[1:-1]:
            if not mpi.parallel or mpi.rank // (mpi.size // 3) == i:
                image.set_calculator(calc)
            i += 1

    neb.set_calculator = set_calculator

    return neb
Пример #8
0
def test_example():
    from ase import Atoms
    from ase.constraints import FixAtoms
    from ase.io import Trajectory
    from ase.optimize import QuasiNewton
    from ase.calculators.morse import MorsePotential

    atoms = Atoms('H7',
                  positions=[(0, 0, 0),
                             (1, 0, 0),
                             (0, 1, 0),
                             (1, 1, 0),
                             (0, 2, 0),
                             (1, 2, 0),
                             (0.5, 0.5, 1)],
                  constraint=[FixAtoms(range(6))],
                  calculator=MorsePotential())

    traj = Trajectory('H.traj', 'w', atoms)
    dyn = QuasiNewton(atoms, maxstep=0.2)
    dyn.attach(traj.write)
    dyn.run(fmax=0.01, steps=100)

    print(atoms)
    del atoms[-1]
    print(atoms)
    del atoms[5]
    print(atoms)
    assert len(atoms.constraints[0].index) == 5
Пример #9
0
def test_md(factory):
    # XXX ugly hack
    ver = factory.factory.version()
    if LooseVersion(ver) < '3.8':
        pytest.skip('No stress tensor until openmx 3.8+')

    bud = Atoms('CH4',
                np.array([[0.000000, 0.000000, 0.100000],
                          [0.682793, 0.682793, 0.682793],
                          [-0.682793, -0.682793, 0.68279],
                          [-0.682793, 0.682793, -0.682793],
                          [0.682793, -0.682793, -0.682793]]),
                cell=[10, 10, 10])

    calc = factory.calc(
        label='ch4',
        xc='GGA',
        energy_cutoff=300 * Ry,
        convergence=1e-4 * Ha,
        # Use 'C_PBE19' and 'H_PBE19' for version 3.9
        definition_of_atomic_species=[['C', 'C5.0-s1p1', 'C_PBE13'],
                                      ['H', 'H5.0-s1', 'H_PBE13']],
        kpts=(1, 1, 1),
        eigensolver='Band')

    bud.calc = calc
    with Trajectory('example.traj', 'w', bud) as traj:
        ucf = UnitCellFilter(bud,
                             mask=[True, True, False, False, False, False])
        dyn = QuasiNewton(ucf)
        dyn.attach(traj.write)
        dyn.run(fmax=0.1)
        bud.get_potential_energy()
Пример #10
0
def generate_data(count, filename, temp, hook, cons_t=False):
    """Generates test or training data with a simple MD simulation."""
    traj = ase.io.Trajectory(filename, "w")
    slab = fcc100("Cu", size=(3, 3, 3))
    ads = molecule("CO")
    add_adsorbate(slab, ads, 5, offset=(1, 1))
    cons = FixAtoms(indices=[
        atom.index for atom in slab if (atom.tag == 2 or atom.tag == 3)
    ])
    if hook:
        cons2 = Hookean(a1=28, a2=27, rt=1.58, k=10.0)
        slab.set_constraint([cons, cons2])
    else:
        slab.set_constraint(cons)
    slab.center(vacuum=13., axis=2)
    slab.set_pbc(True)
    slab.wrap(pbc=[True] * 3)
    slab.set_calculator(EMT())
    slab.get_forces()
    dyn = QuasiNewton(slab)
    dyn.run(fmax=0.05)
    traj.write(slab)
    if cons_t is True:
        dyn = Langevin(slab, 1.0 * units.fs, temp * units.kB, 0.002)
    else:
        dyn = VelocityVerlet(slab, dt=1.0 * units.fs)
    for step in range(count):
        dyn.run(20)
        traj.write(slab)
Пример #11
0
def runVaspASEOptimizer(fname_in, fname_out, vaspflags):
    fname_in = str(fname_in)
    fname_out = str(fname_out)

    #read the input atoms object
    atoms = read(str(fname_in))

    #set ibrion=-1 and nsw=0
    vaspflags['ibrion'] = -1
    vaspflags['nsw'] = 0

    #update vasprc file to set mode to "run" to ensure that this runs immediately
    Vasp.vasprc(mode='run')
    #set ppn>1 so that it knows to do an mpi job, the actual ppn will guessed by Vasp module
    Vasp.VASPRC['queue.ppn'] = 2
    vaspflags['NPAR'] = 4
    #set up the calculation and run
    calc = Vasp('./', atoms=atoms, **vaspflags)
    #calc.update()
    #calc.read_results()

    qn = QuasiNewton(atoms, logfile='relax.log', trajectory='relax.traj')
    qn.run(fmax=vaspflags['ediffg'] if 'ediffg' in vaspflags else 0.05)

    atoms.write(fname_out)

    #Write a text file with the energy
    with open('energy.out', 'w') as fhandle:
        fhandle.write(str(atoms.get_potential_energy()))

    return str(atoms), open(
        'relax.traj', 'r').read().encode('hex'), atoms.get_potential_energy()
Пример #12
0
def _main():
    si = make_displaced_Si_cell()

    # Set up GPAW calculator for the ground-state charge density.
    # This will be used repeatedly as the structure is moved toward the
    # equilibrium structure.
    calc = GPAW(
        mode=PW(200),  # plane-wave basis, 200 eV wavefunction cutoff energy
        # PBE exchange-correlation functional
        xc='PBE',
        # Sample the Brillouin zone with 8 k-points in each reciprocal lattice direction
        kpts=(8, 8, 8),
        # Smear step functions appearing in Brillouin zone integrals using Fermi-Dirac
        # distribution at temperature k_B T = 0.01 eV.
        occupations=FermiDirac(0.01),
        # Start calculation using random wavefunctions.
        # We have a physically-reasonable initial value for the charge density based
        # on the atomic positions.
        # The Hamiltonian is diagonalized iteratively, so we also need an initial guess for
        # the wavefunctions. Random starting wavefunctions generally work well.
        random=True,
        # Set the log file for the ground-state DFT calculation.
        txt="Si_relax.txt")

    si.calc = calc

    opt = QuasiNewton(
        si,
        # Set the (non-plaintext) log file for the structural optimization steps.
        trajectory="Si.traj")

    # Relax structure until all forces are less than 0.05 eV/Angstrom.
    opt.run(fmax=0.05)
Пример #13
0
def test_dftb_relax_bulk():
    import os
    from ase.test import require
    from ase.test.testsuite import datafiles_directory
    from ase.build import bulk
    from ase.calculators.dftb import Dftb
    from ase.optimize import QuasiNewton
    from ase.constraints import ExpCellFilter

    require('dftb')

    os.environ['DFTB_PREFIX'] = datafiles_directory

    calc = Dftb(label='dftb',
                kpts=(3,3,3),
                Hamiltonian_SCC='Yes')

    atoms = bulk('Si')
    atoms.set_calculator(calc)

    ecf = ExpCellFilter(atoms)
    dyn = QuasiNewton(ecf)
    dyn.run(fmax=0.01)

    e = atoms.get_potential_energy()
    assert abs(e - -73.150819) < 1., e
Пример #14
0
def main():
    CO = molecule("CO")
    fname = "data/CO.traj"

    calc = GPAW(h=0.2, txt="data/CO.txt")

    CO.set_cell([6, 6, 6])
    CO.center()

    if (os.path.isfile(fname)):
        traj = Trajectory(fname)
        CO = traj[-1]
    else:
        # Optimize the CO structure
        opt = QuasiNewton(CO, trajectory=fname)
        opt.run(fmax=0.05)

    fname = "data/CO.gpw"

    CO.set_calculator(calc)
    CO.get_potential_energy()
    calc.write(fname)

    for band in range(calc.get_number_of_bands()):
        wf = calc.get_pseudo_wave_function(band=band)
        with h5.File("data/CO_%d.cmap" % (band)) as hf:
            hf.create_dataset("wf", data=wf)
    def optimize(self, calculator='siesta'):
        from ase.optimize import QuasiNewton

        if calculator == 'siesta':
            calc = Siesta(
                label=self.label,
                xc='CA',
                mesh_cutoff=400 * eV,
                energy_shift=0.03 * eV,
                basis_set='SZ',
                fdf_arguments=self.extra_fdf,
            )
        elif calculator == 'dftb':
            extras = {}
            for S in set(self.mol.get_chemical_symbols()):
                key = 'Hamiltonian_MaxAngularMomentum_' + S
                if S == 'H':
                    value = '"s"'
                else:
                    value = '"p"'
                extras[key] = value
            calc = Dftb(label=self.label, atoms=self.mol, **extras)

        tempdir = "." + self.label
        try:
            os.mkdir(tempdir)
        except:
            pass

        os.chdir(tempdir)
        self.mol.set_calculator(calc)
        dyn = QuasiNewton(self.mol, trajectory=self.label + '.traj')
        dyn.run(fmax=0.5)
        os.chdir('../')
Пример #16
0
def test_NaCl_minimize():
    from ase.calculators.lammpsrun import LAMMPS
    from ase.spacegroup import crystal
    from ase.data import atomic_numbers, atomic_masses
    from ase.optimize import QuasiNewton
    from ase.constraints import UnitCellFilter
    from numpy.testing import assert_allclose

    a = 6.15
    n = 4
    nacl = crystal(['Na', 'Cl'], [(0, 0, 0), (0.5, 0.5, 0.5)],
                   spacegroup=225,
                   cellpar=[a, a, a, 90, 90, 90]).repeat((n, n, n))

    # Buckingham parameters from
    # https://physics.stackexchange.com/questions/250018

    pair_style = 'buck/coul/long 12.0'
    pair_coeff = ['1 1 3796.9 0.2603 124.90']
    pair_coeff += ['2 2 1227.2 0.3214 124.90']
    pair_coeff += ['1 2 4117.9 0.3048 0.0']
    masses = [
        '1 {}'.format(atomic_masses[atomic_numbers['Na']]),
        '2 {}'.format(atomic_masses[atomic_numbers['Cl']])
    ]

    with LAMMPS(
            specorder=['Na', 'Cl'],
            pair_style=pair_style,
            pair_coeff=pair_coeff,
            masses=masses,
            atom_style='charge',
            kspace_style='pppm 1.0e-5',
            keep_tmp_files=True,
    ) as calc:

        for a in nacl:
            if a.symbol == 'Na':
                a.charge = +1.
            else:
                a.charge = -1.

        nacl.set_calculator(calc)

        assert_allclose(nacl.get_potential_energy(),
                        -1896.216737561538,
                        atol=1e-4,
                        rtol=1e-4)

        nacl.get_potential_energy()

        ucf = UnitCellFilter(nacl)
        dyn = QuasiNewton(ucf, force_consistent=False)
        dyn.run(fmax=1.0E-2)

        assert_allclose(nacl.get_potential_energy(),
                        -1897.208861729178,
                        atol=1e-4,
                        rtol=1e-4)
Пример #17
0
def emtOptimize():
    system = Atoms("H2", positions=[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]])

    calc = EMT()

    system.set_calculator(calc)
    opt = QuasiNewton(system, trajectory="h2.emt.traj")
    opt.run(fmax=0.05)
Пример #18
0
def test_n2():
    from ase import Atoms
    from ase.calculators.emt import EMT
    from ase.optimize import QuasiNewton

    n2 = Atoms('N2', positions=[(0, 0, 0), (0, 0, 1.1)], calculator=EMT())
    QuasiNewton(n2).run(0.01)
    print(n2.get_distance(0, 1), n2.get_potential_energy())
Пример #19
0
def test_autoneb(asap3):
    EMT = asap3.EMT
    fmax = 0.02

    # Pt atom adsorbed in a hollow site:
    slab = fcc211('Pt', size=(3, 2, 2), vacuum=4.0)
    add_adsorbate(slab, 'Pt', 0.5, (-0.1, 2.7))

    # Fix second and third layers:
    slab.set_constraint(FixAtoms(range(6, 12)))

    # Use EMT potential:
    slab.calc = EMT()

    # Initial state:
    qn = QuasiNewton(slab, trajectory='neb000.traj')
    qn.run(fmax=fmax)

    # Final state:
    slab[-1].x += slab.get_cell()[0, 0]
    slab[-1].y += 2.8
    qn = QuasiNewton(slab, trajectory='neb001.traj')
    qn.run(fmax=fmax)

    # Stops PermissionError on Win32 for access to
    # the traj file that remains open.
    del qn

    def attach_calculators(images):
        for i in range(len(images)):
            images[i].calc = EMT()

    autoneb = AutoNEB(attach_calculators,
                      prefix='neb',
                      optimizer='BFGS',
                      n_simul=3,
                      n_max=7,
                      fmax=fmax,
                      k=0.5,
                      parallel=False,
                      maxsteps=[50, 1000])
    autoneb.run()

    nebtools = NEBTools(autoneb.all_images)
    assert abs(nebtools.get_barrier()[0] - 0.937) < 1e-3
Пример #20
0
def test_filter():
    """Test that the filter and trajectories are playing well together."""

    atoms = molecule('CO2')
    atoms.calc = EMT()
    filter = Filter(atoms, indices=[1, 2])

    with QuasiNewton(filter, trajectory='filter-test.traj', logfile='filter-test.log') as opt:
        opt.run()
Пример #21
0
def test_vib():
    import os
    from ase import Atoms
    from ase.calculators.emt import EMT
    from ase.optimize import QuasiNewton
    from ase.vibrations import Vibrations
    from ase.thermochemistry import IdealGasThermo

    n2 = Atoms('N2', positions=[(0, 0, 0), (0, 0, 1.1)], calculator=EMT())
    QuasiNewton(n2).run(fmax=0.01)
    vib = Vibrations(n2)
    vib.run()
    freqs = vib.get_frequencies()
    print(freqs)
    vib.summary()
    print(vib.get_mode(-1))
    vib.write_mode(n=None, nimages=20)
    vib_energies = vib.get_energies()

    for image in vib.iterimages():
        assert len(image) == 2

    thermo = IdealGasThermo(vib_energies=vib_energies,
                            geometry='linear',
                            atoms=n2,
                            symmetrynumber=2,
                            spin=0)
    thermo.get_gibbs_energy(temperature=298.15, pressure=2 * 101325.)

    assert vib.clean(empty_files=True) == 0
    assert vib.clean() == 13
    assert len(list(vib.iterimages())) == 13

    d = dict(vib.iterdisplace(inplace=False))

    for name, atoms in vib.iterdisplace(inplace=True):
        assert d[name] == atoms

    vib = Vibrations(n2)
    vib.run()
    assert vib.combine() == 13
    assert (freqs == vib.get_frequencies()).all()

    vib = Vibrations(n2)
    assert vib.split() == 1
    assert (freqs == vib.get_frequencies()).all()

    assert vib.combine() == 13
    # Read the data from other working directory
    dirname = os.path.basename(os.getcwd())
    os.chdir('..')  # Change working directory
    vib = Vibrations(n2, name=os.path.join(dirname, 'vib'))
    assert (freqs == vib.get_frequencies()).all()
    assert vib.clean() == 1
Пример #22
0
    def optimize(self):
        from ase.optimize import QuasiNewton
        self.add_calculator()
        tempdir = "."+self.label
        try:
            os.mkdir(tempdir)
        except:
            pass

        os.chdir(tempdir)
        dyn = QuasiNewton(self, trajectory=self.label+'.traj')
        dyn.run(fmax=0.5)
        os.chdir('../')
Пример #23
0
def main():
    molecule, calc = gp.restart("H2.gpw", txt="H2-relaxed.txt")
    print("Getting potential energy")
    e2 = molecule.get_potential_energy()
    d0 = molecule.get_distance(0, 1)

    # Find the minimum energy by Quasi-Newton
    relax = QuasiNewton(molecule, logfile="qn.log")
    relax.run(fmax=0.05)
    d1 = molecule.get_distance(0, 1)

    print("Original bondlength: %.2f" % (d0))
    print("Optimized bondlength: %.2f" % (d1))
Пример #24
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
Пример #25
0
def test_ideal_gas_thermo():
    atoms = Atoms('N2',
                  positions=[(0, 0, 0), (0, 0, 1.1)])
    atoms.calc = EMT()
    QuasiNewton(atoms).run(fmax=0.01)
    energy = atoms.get_potential_energy()
    vib = Vibrations(atoms, name='idealgasthermo-vib')
    vib.run()
    vib_energies = vib.get_energies()

    thermo = IdealGasThermo(vib_energies=vib_energies, geometry='linear',
                            atoms=atoms, symmetrynumber=2, spin=0,
                            potentialenergy=energy)
    thermo.get_gibbs_energy(temperature=298.15, pressure=2 * 101325.)
Пример #26
0
def traj(tmpdir_factory):
    slab = fcc100('Al', size=(2, 2, 3))
    add_adsorbate(slab, 'Au', 1.7, 'hollow')
    slab.center(axis=2, vacuum=4.0)
    mask = [atom.tag > 1 for atom in slab]
    fixlayers = FixAtoms(mask=mask)
    plane = FixedPlane(-1, (1, 0, 0))
    slab.set_constraint([fixlayers, plane])
    slab.set_calculator(EMT())

    fn = tmpdir_factory.mktemp("data").join("AlAu.traj")  # see /tmp/pytest-xx
    qn = QuasiNewton(slab, trajectory=str(fn))
    qn.run(fmax=0.02)
    return fn
Пример #27
0
def test_dftb_relax_bulk(dftb_factory):
    calc = dftb_factory.calc(label='dftb',
                             kpts=(3, 3, 3),
                             Hamiltonian_SCC='Yes')

    atoms = bulk('Si')
    atoms.calc = calc

    ecf = ExpCellFilter(atoms)
    with QuasiNewton(ecf) as dyn:
        dyn.run(fmax=0.01)

    e = atoms.get_potential_energy()
    assert abs(e - -73.150819) < 1., e
Пример #28
0
def test_emt_h3o2m(initial, final, testdir):
    # Make band:
    images = [initial.copy()]
    for i in range(3):
        images.append(initial.copy())
    images.append(final.copy())
    neb = NEB(images, climb=True)

    # Set constraints and calculator:
    constraint = FixAtoms(indices=[1, 3])  # fix OO
    for image in images:
        image.calc = 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:
    # 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())

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

    for image in images:
        print(image.get_distance(1, 2), image.get_potential_energy())
Пример #29
0
def test_md():
    import numpy as np
    import unittest

    from ase.units import Ry, Ha
    from ase.calculators.openmx import OpenMX
    from ase.io.trajectory import Trajectory
    from ase.optimize import QuasiNewton
    from ase.constraints import UnitCellFilter
    from ase.calculators.calculator import PropertyNotImplementedError
    from ase import Atoms
    """ Only OpenMX 3.8 or higher version pass this test"""

    bud = Atoms('CH4', np.array([
            [0.000000, 0.000000, 0.100000],
            [0.682793, 0.682793, 0.682793],
            [-0.682793, -0.682793, 0.68279],
            [-0.682793, 0.682793, -0.682793],
            [0.682793, -0.682793, -0.682793]]),
            cell=[10, 10, 10])

    calc = OpenMX(
        label='ch4',
        xc='GGA',
        energy_cutoff=300 * Ry,
        convergence=1e-4 * Ha,
        # Use 'C_PBE19' and 'H_PBE19' for version 3.9
        definition_of_atomic_species=[['C', 'C5.0-s1p1', 'C_PBE13'],
                                      ['H', 'H5.0-s1', 'H_PBE13']],
        kpts=(4, 4, 4),
        eigensolver='Band'
        )

    bud.set_calculator(calc)

    try:
        bud.get_stress()
    except PropertyNotImplementedError as err:
        raise unittest.SkipTest(err)

    traj = Trajectory('example.traj', 'w', bud)
    ucf = UnitCellFilter(bud, mask=[True, True, False, False, False, False])
    dyn = QuasiNewton(ucf)
    dyn.attach(traj.write)
    dyn.run(fmax=0.1)
    bud.get_potential_energy()
    # XXX maybe assert something?

    traj.close()
Пример #30
0
def traj(tmp_path_factory):
    slab = fcc100('Al', size=(2, 2, 3))
    add_adsorbate(slab, 'Au', 1.7, 'hollow')
    slab.center(axis=2, vacuum=4.0)
    mask = [atom.tag > 1 for atom in slab]
    fixlayers = FixAtoms(mask=mask)
    plane = FixedPlane(-1, (1, 0, 0))
    slab.set_constraint([fixlayers, plane])
    slab.calc = EMT()

    temp_path = tmp_path_factory.mktemp("data")
    trajectory = temp_path / 'AlAu.traj'
    qn = QuasiNewton(slab, trajectory=str(trajectory))
    qn.run(fmax=0.02)
    return str(trajectory)