예제 #1
1
def test_emt1():
    from ase import Atoms
    from ase.calculators.emt import EMT
    from ase.constraints import FixBondLength
    from ase.io import Trajectory
    from ase.optimize import BFGS

    a = 3.6
    b = a / 2
    cu = Atoms('Cu2Ag',
               positions=[(0, 0, 0), (b, b, 0), (a, a, b)],
               calculator=EMT())
    e0 = cu.get_potential_energy()
    print(e0)

    d0 = cu.get_distance(0, 1)
    cu.set_constraint(FixBondLength(0, 1))
    t = Trajectory('cu2ag.traj', 'w', cu)
    qn = BFGS(cu)
    qn.attach(t.write)

    def f():
        print(cu.get_distance(0, 1))

    qn.attach(f)
    qn.run(fmax=0.001)
    assert abs(cu.get_distance(0, 1) - d0) < 1e-14
예제 #2
0
def test_external_force():
    """Tests for class ExternalForce in ase/constraints.py"""
    f_ext = 0.2

    atom1 = 0
    atom2 = 1
    atom3 = 2

    atoms = Atoms('H3', positions=[(0, 0, 0), (0.751, 0, 0), (0, 1., 0)])
    atoms.calc = EMT()

    # Without external force
    optimize(atoms)
    dist1 = atoms.get_distance(atom1, atom2)

    # With external force
    con1 = ExternalForce(atom1, atom2, f_ext)
    atoms.set_constraint(con1)
    optimize(atoms)
    dist2 = atoms.get_distance(atom1, atom2)
    # Distance should increase due to the external force
    assert dist2 > dist1

    # Combine ExternalForce with FixBondLength

    # Fix the bond on which the force acts
    con2 = FixBondLength(atom1, atom2)
    # ExternalForce constraint at the beginning of the list!!!
    atoms.set_constraint([con1, con2])
    optimize(atoms)
    f_con = con2.constraint_forces

    # It was already optimized with this external force, therefore
    # the constraint force should be almost zero
    assert norm(f_con[0]) <= fmax

    # To get the complete constraint force (with external force),
    # use only the FixBondLength constraint, after the optimization with
    # ExternalForce
    atoms.set_constraint(con2)
    optimize(atoms)
    f_con = con2.constraint_forces[0]
    assert round(norm(f_con), 2) == round(abs(f_ext), 2)

    # Fix another bond and incrase the external force
    f_ext *= 2
    con1 = ExternalForce(atom1, atom2, f_ext)
    d1 = atoms.get_distance(atom1, atom3)
    con2 = FixBondLength(atom1, atom3)
    # ExternalForce constraint at the beginning of the list!!!
    atoms.set_constraint([con1, con2])
    optimize(atoms)
    d2 = atoms.get_distance(atom1, atom3)
    # Fixed distance should not change
    assert round(d1, 5) == round(d2, 5)
예제 #3
0
def test_fix_bond_length_mic():
    import ase
    from ase.calculators.lj import LennardJones
    from ase.constraints import FixBondLength
    from ase.optimize import FIRE

    for wrap in [False, True]:
        a = ase.Atoms('CCC',
                      positions=[[1, 0, 5],
                                 [0, 1, 5],
                                 [-1, 0.5, 5]],
                      cell=[10, 10, 10],
                      pbc=True)

        if wrap:
            a.set_scaled_positions(a.get_scaled_positions() % 1.0)
        a.calc = LennardJones()
        a.set_constraint(FixBondLength(0, 2))

        d1 = a.get_distance(0, 2, mic=True)

        FIRE(a, logfile=None).run(fmax=0.01)
        e = a.get_potential_energy()
        d2 = a.get_distance(0, 2, mic=True)
        assert abs(e - -2.034988) < 1e-6
        assert abs(d1 - d2) < 1e-6
예제 #4
0
def test_mirror():
    from ase.build import molecule
    from ase.constraints import MirrorForce, FixBondLength, MirrorTorque
    from ase.constraints import ExternalForce
    from ase.optimize import FIRE
    from ase.calculators.emt import EMT

    atoms = molecule('cyclobutene')
    dist = atoms.get_distance(0, 1)
    con1 = MirrorForce(2, 3, max_dist=5., fmax=0.05)
    con2 = FixBondLength(0, 1)
    atoms.set_constraint([con1, con2])
    atoms.calc = EMT()
    opt = FIRE(atoms)
    opt.run(fmax=0.05)
    assert round(dist - atoms.get_distance(0, 1), 5) == 0

    atoms = molecule('butadiene')
    # Break symmetry
    atoms[0].position[2] += 0.2
    dist = atoms.get_distance(1, 2)
    con1 = MirrorTorque(0, 1, 2, 3, fmax=0.05)
    con2 = ExternalForce(9, 4, f_ext=0.1)
    atoms.set_constraint([con1, con2])
    atoms.calc = EMT()
    opt = FIRE(atoms)
    opt.run(fmax=0.05, steps=300)
예제 #5
0
def test_constraint_and_momenta():
    a = Atoms('H2',
              positions=[(0, 0, 0), (0, 0, 1)],
              momenta=[(1, 0, 0), (0, 0, 0)])
    a.constraints = [FixBondLength(0, 1)]
    with Trajectory('constraint.traj', 'w', a) as t:
        t.write()
    b = read('constraint.traj')
    assert not (b.get_momenta() - a.get_momenta()).any()
예제 #6
0
def test_trajectory_heterogeneous():
    from ase.constraints import FixAtoms, FixBondLength
    from ase.build import molecule, bulk
    from ase.io.trajectory import Trajectory, get_header_data
    from ase.io import read

    a0 = molecule('H2O')
    a1 = a0.copy()
    a1.rattle(stdev=0.5)
    a2 = a0.copy()
    a2.set_masses()
    a2.center(vacuum=2.0)
    a2.rattle(stdev=0.2)
    a3 = molecule('CH3CH2OH')
    a4 = bulk('Au').repeat((2, 2, 2))
    a5 = bulk('Cu').repeat((2, 2, 3))

    # Add constraints to some of the images:
    images = [a0, a1, a2, a3, a4, a5]
    for i, img in enumerate(images[3:]):
        img.set_constraint(FixAtoms(indices=range(i + 3)))
        if i == 2:
            img.constraints.append(FixBondLength(5, 6))

    traj = Trajectory('out.traj', 'w')
    for i, img in enumerate(images):
        traj.write(img)
        print(i, traj.multiple_headers)
        assert traj.multiple_headers == (i >= 2)
    traj.close()

    rtraj = Trajectory('out.traj')
    newimages = list(rtraj)

    assert len(images) == len(newimages)
    for i in range(len(images)):
        assert images[i] == newimages[i], i
        h1 = get_header_data(images[i])
        h2 = get_header_data(newimages[i])
        print(i, images[i])
        print(h1)
        print(h2)
        print()
        # assert headers_equal(h1, h2)

    # Test append mode:
    with Trajectory('out.traj', 'a') as atraj:
        atraj.write(molecule('H2'))
        atraj.write(molecule('H2'))
    read('out.traj', index=':')
예제 #7
0
def _ref_vacancy_global(_setup_images_global):
    # use distance from moving atom to one of its neighbours as reaction coord
    # relax intermediate image to the saddle point using a bondlength constraint
    images, i1, i2 = _setup_images_global
    initial, saddle, final = (images[0].copy(), images[2].copy(),
                              images[4].copy())
    initial.calc = calc()
    saddle.calc = calc()
    final.calc = calc()
    saddle.set_constraint(FixBondLength(i1, i2))
    opt = ODE12r(saddle)
    opt.run(fmax=1e-2)
    nebtools = NEBTools([initial, saddle, final])
    Ef_ref, dE_ref = nebtools.get_barrier(fit=False)
    print('REF:', Ef_ref, dE_ref)
    return Ef_ref, dE_ref, saddle
예제 #8
0
def test_dimer():
    from ase import Atom, Atoms
    from ase.calculators.lj import LennardJones
    from ase.constraints import FixBondLength

    dimer = Atoms([Atom('X',
                        (0, 0, 0)), Atom('X', (0, 0, 1))],
                  calculator=LennardJones(),
                  constraint=FixBondLength(0, 1))
    print(dimer.get_forces())
    print(dimer.positions)
    dimer.positions[:] += 0.1
    print(dimer.positions)
    dimer.positions[:, 2] += 5.1
    print(dimer.positions)
    dimer.positions[:] = [(1, 2, 3), (4, 5, 6)]
    print(dimer.positions)
    dimer.set_positions([(1, 2, 3), (4, 5, 6.2)])
    print(dimer.positions)
def test_fix_bond_length_mic(wrap):
    a = ase.Atoms('CCC',
                  positions=[[1, 0, 5], [0, 1, 5], [-1, 0.5, 5]],
                  cell=[10, 10, 10],
                  pbc=True)

    if wrap:
        a.set_scaled_positions(a.get_scaled_positions() % 1.0)
    a.calc = LennardJones()
    a.set_constraint(FixBondLength(0, 2))

    d1 = a.get_distance(0, 2, mic=True)

    with FIRE(a, logfile=None) as opt:
        opt.run(fmax=0.01)
    e = a.get_potential_energy()
    d2 = a.get_distance(0, 2, mic=True)
    assert abs(e - -2.034988) < 1e-6
    assert abs(d1 - d2) < 1e-6
예제 #10
0
def test_preconlbfgs():
    N = 1
    a0 = bulk('Cu', cubic=True)
    a0 *= (N, N, N)

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

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

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

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

        assert abs(cu.get_distance(0, 1) / a0 - 1.2) < 1e-3
        assert np.all(abs(cu.positions[2] - cu0.positions[2]) < 1e-3)
        assert np.all(abs(cu.positions[3] - cu0.positions[3]) < 1e-3)
예제 #11
0
nsteps = []
energies = []
for OPT in [PreconLBFGS, PreconFIRE]:
    for precon in [None, Exp(A=3, mu=1.0)]:
        atoms = a0.copy()
        atoms.set_calculator(EMT())
        opt = OPT(atoms, precon=precon, use_armijo=True)
        opt.run(1e-4)
        energies += [atoms.get_potential_energy()]
        nsteps += [opt.get_number_of_steps()]

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

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

    assert abs(cu.get_distance(0, 1)/a0 - 1.2) < 1e-3
    assert np.all(abs(cu.positions[2] - cu0.positions[2]) < 1e-3)
    assert np.all(abs(cu.positions[3] - cu0.positions[3]) < 1e-3)
예제 #12
0
    c = connect(name)
    print(name, c)

    if 'postgres' in name or 'mysql' in name or 'mariadb' in name:
        c.delete([row.id for row in c.select()])

    id = c.reserve(abc=7)
    c.delete([d.id for d in c.select(abc=7)])
    id = c.reserve(abc=7)
    assert c[id].abc == 7

    a = c.get_atoms(id)
    c.write(Atoms())
    ch4 = molecule('CH4', calculator=EMT())
    ch4.constraints = [FixAtoms(indices=[1]), FixBondLength(0, 2)]
    f1 = ch4.get_forces()
    print(f1)

    c.delete([d.id for d in c.select(C=1)])
    chi = np.array([1 + 0.5j, 0.5])
    id = c.write(ch4, data={'1-butyne': 'bla-bla', 'chi': chi})

    row = c.get(id)
    print(row.data['1-butyne'], row.data.chi)
    assert (row.data.chi == chi).all()
    print(row)

    assert len(c.get_atoms(C=1).constraints) == 2

    f2 = c.get(C=1).forces
예제 #13
0
def dissociation(atoms,
                 i1,
                 i2,
                 step_size=0.05,
                 n_steps=20,
                 final_distance=None,
                 group_move=None,
                 z_bias=False):
    '''
    This function is a tool for investigating bond dissociation.
    Bond length of interest is fixed and is increased by step_size in each iteration.
    This aims to help with obtaining activation energies for surface calculations, e.g. hydrogenation,
    where metastability of optimal starting position is often low and thus hard to obtain.
    Returns a list of Atoms objects with changed positions and constraints applied,
    which can be optimised by the user.

    Args:
        atoms: Atoms object
        i1: int
            Index of atom remaining as part of a molecule
        i2: int
            Index of atom dissociating from molecule
        step_size: float
            Distance moved during dissociation in Angstrom per iteration, not used
            when final_distance is specified.
            If negative value - Association is examined instead
        n_steps: int
            Total number of steps
        final_distance: None/float
            User can specify the final distance, the increments will be then based
            on a fraction of n_steps/final_distance instead of step_size
        group_move: list of integers
            User can specify a list of indices of atoms that need to be moved
            together with atom with index i2, e.g. OH group etc.
        z_bias: boolean of float
            If float - bias z-coord of moving atom to approach set value
            WARNING - If TRUE this will make steps vary from defined step_size!
            Bias to adjust the Z-coordinate of atom/group moving to approach
            the surface in periodic calculations rather than just elongate the
            bond.
    '''

    from ase.constraints import FixBondLength
    import copy
    import numpy as np

    # retrieve initial atom - atom distance and atom[i2] position
    pos_diff = atoms[i1].position - atoms[i2].position
    initial_dist = np.linalg.norm(pos_diff)
    initial_i2_pos = copy.deepcopy(atoms[i2].position)
    z_diff = 2.0
    # retrieve z-coordinate for z_bias
    if z_bias:
        if isinstance(z_bias, (int, float)) and not isinstance(z_bias, bool):
            surf_z = z_bias - z_diff
        else:
            # make sure it works if no tags are set for atoms
            # should be more reliable if available
            surf_z_list = [atom.z for atom in atoms if atom.tag > 0]
            if surf_z_list == []:
                # Define a list of atom chemical symbols and their count
                # Take the z coordinate of the most abundant element in the surface slab
                chem_symbol_count = [[
                    x, atoms.get_chemical_symbols().count(x)
                ] for x in set(atoms.get_chemical_symbols())]

                # Sort the list by the count
                def take_second(n):
                    return n[1]

                chem_symbol_count.sort(key=take_second)

                surf_z_list = [
                    atom.z for atom in atoms
                    if atom.symbol == chem_symbol_count[-1][0]
                ]
            # The maximum z-coordinate of the surface atoms is retrieved
            surf_z = np.amax(surf_z_list)

    atoms_list = []
    distance_list = []

    # Retrieve previous constraints info
    if not atoms.constraints:
        initial_constraint = None
    else:
        initial_constraint = copy.deepcopy(atoms.constraints)

    for i in range(1, n_steps + 1):
        # operate on a deepcopy for intended functionality
        atoms = copy.deepcopy(atoms)
        # remove previous constraints and set up new ones
        atoms.set_constraint()

        # initial moving atom position
        imap = copy.deepcopy(atoms[i2].position)

        # move atoms and fix bond length in fixed increments or fraction of final_distance
        measured_distance = (initial_dist + i * step_size)

        if final_distance:
            measured_distance = initial_dist + (
                i / n_steps * (final_distance - initial_dist))

        atoms.set_distance(i1, i2, measured_distance, fix=0)

        # apply bias in z-coordinate towards the surface atoms
        if z_bias:
            # TODO: consult minimum distance from surface (can cause trouble for group)
            # min distance in Angstrom from surf atoms
            z_threshold_min = surf_z + z_diff
            # make sure atoms from a group do not clash into surface atoms
            # move towards the surface or away if necessary
            if group_move:
                z_threshold_max = np.amin(
                    [atom.z for atom in atoms[group_move]])
            else:
                z_threshold_max = atoms[i2].z

            if z_threshold_max > z_threshold_min:
                atoms[i2].z -= (initial_i2_pos[2] - surf_z) / n_steps
            elif z_threshold_max < z_threshold_min:
                atoms[i2].z += (initial_i2_pos[2] - surf_z) / n_steps

        # move other specified atoms as part of a molecule, e.g. OH group
        if group_move:
            for m in group_move:
                if not m == i2:
                    atoms[m].position = atoms[m].position + (
                        atoms[i2].position - imap)

        # adjust contraints
        if initial_constraint is not None:
            new_constraint = initial_constraint + [FixBondLength(i1, i2)]
            atoms.set_constraint(new_constraint)
        else:
            new_constraint = FixBondLength(i1, i2)
            atoms.set_constraint(new_constraint)

        # Record the size of fixed bond
        atoms_list += [copy.deepcopy(atoms)]
        distance_list += [
            np.linalg.norm(atoms[i1].position - atoms[i2].position)
        ]

    return atoms_list, distance_list
예제 #14
0
def test_db2(testdir, name):
    if name == 'postgresql':
        pytest.importorskip('psycopg2')
        if os.environ.get('POSTGRES_DB'):  # gitlab-ci
            name = 'postgresql://*****:*****@postgres:5432/testase'
        else:
            name = os.environ.get('ASE_TEST_POSTGRES_URL')
            if name is None:
                return
    elif name == 'mysql':
        pytest.importorskip('pymysql')
        if os.environ.get('CI_PROJECT_DIR'):  # gitlab-ci
            name = 'mysql://*****:*****@mysql:3306/testase_mysql'
        else:
            name = os.environ.get('MYSQL_DB_URL')

        if name is None:
            return
    elif name == 'mariadb':
        pytest.importorskip('pymysql')
        if os.environ.get('CI_PROJECT_DIR'):  # gitlab-ci
            name = 'mariadb://*****:*****@mariadb:3306/testase_mysql'
        else:
            name = os.environ.get('MYSQL_DB_URL')

        if name is None:
            return

    c = connect(name)
    print(name, c)

    if 'postgres' in name or 'mysql' in name or 'mariadb' in name:
        c.delete([row.id for row in c.select()])

    id = c.reserve(abc=7)
    c.delete([d.id for d in c.select(abc=7)])
    id = c.reserve(abc=7)
    assert c[id].abc == 7

    a = c.get_atoms(id)
    c.write(Atoms())
    ch4 = molecule('CH4', calculator=EMT())
    ch4.constraints = [FixAtoms(indices=[1]), FixBondLength(0, 2)]
    f1 = ch4.get_forces()
    print(f1)

    c.delete([d.id for d in c.select(C=1)])
    chi = np.array([1 + 0.5j, 0.5])
    if 'db' in name:
        kvp = {
            'external_tables': {
                'blabla': {
                    'a': 1,
                    'b': 2,
                    'c': 3
                },
                'lala': {
                    'a': 0.01,
                    'b': 0.02,
                    'c': 0.0
                }
            }
        }

    else:
        kvp = {'a': 1}

    id = c.write(ch4,
                 key_value_pairs=kvp,
                 data={
                     '1-butyne': 'bla-bla',
                     'chi': chi
                 })

    row = c.get(id)
    print(row.data['1-butyne'], row.data.chi)
    assert (row.data.chi == chi).all(), (row.data.chi, chi)
    print(row)

    assert len(c.get_atoms(C=1).constraints) == 2

    f2 = c.get(C=1).forces
    assert abs(f2.sum(0)).max() < 1e-14
    f3 = c.get_atoms(C=1).get_forces()
    assert abs(f1 - f3).max() < 1e-14

    a = read(name, index='id={}'.format(id))[0]
    f4 = a.get_forces()
    assert abs(f1 - f4).max() < 1e-14

    with pytest.raises(ValueError):
        c.update(id, abc={'a': 42})

    c.update(id, grr='hmm')
    row = c.get(C=1)
    assert row.id == id
    assert (row.data.chi == chi).all()

    for row in c.select(include_data=False):
        assert len(row.data) == 0

    with pytest.raises(ValueError):
        c.write(ch4, foo=['bar', 2])  # not int, bool, float or str

    with pytest.raises(ValueError):
        c.write(Atoms(), pi='3.14')  # number as a string

    with pytest.raises(ValueError):
        c.write(Atoms(), fmax=0.0)  # reserved word

    with pytest.raises(ValueError):
        c.write(Atoms(), S=42)  # chemical symbol as key

    id = c.write(Atoms(),
                 b=np.bool_(True),
                 i=np.int64(42),
                 n=np.nan,
                 x=np.inf,
                 s='NaN2',
                 A=42)
    row = c[id]
    assert isinstance(row.b, bool)
    assert isinstance(row.i, int)
    assert np.isnan(row.n)
    assert np.isinf(row.x)

    # Make sure deleting a single key works:
    id = c.write(Atoms(), key=7)
    c.update(id, delete_keys=['key'])
    assert 'key' not in c[id]

    e = [row.get('energy') for row in c.select(sort='energy')]
    assert len(e) == 5 and abs(e[0] - 1.991) < 0.0005

    # Test the offset keyword
    ids = [row.get('id') for row in c.select()]
    offset = 2
    assert next(c.select(offset=offset)).id == ids[offset]
예제 #15
0
a1 = a0.copy()
a1.rattle(stdev=0.5)
a2 = a0.copy()
a2.set_masses()
a2.center(vacuum=2.0)
a2.rattle(stdev=0.2)
a3 = molecule('CH3CH2OH')
a4 = bulk('Au').repeat((2, 2, 2))
a5 = bulk('Cu').repeat((2, 2, 3))

# Add constraints to some of the images:
images = [a0, a1, a2, a3, a4, a5]
for i, img in enumerate(images[3:]):
    img.set_constraint(FixAtoms(indices=range(i + 3)))
    if i == 2:
        img.constraints.append(FixBondLength(5, 6))

traj = Trajectory('out.traj', 'w')
for i, img in enumerate(images):
    traj.write(img)
    print(i, traj.multiple_headers)
    assert traj.multiple_headers == (i >= 2)
traj.close()

rtraj = Trajectory('out.traj')
newimages = list(rtraj)

assert len(images) == len(newimages)
for i in range(len(images)):
    assert images[i] == newimages[i], i
    h1 = get_header_data(images[i])
예제 #16
0
opt.run(fmax=fmax)
dist1 = atoms.get_distance(atom1, atom2)

# With external force
con1 = ExternalForce(atom1, atom2, f_ext)
atoms.set_constraint(con1)
opt = FIRE(atoms)
opt.run(fmax=fmax)
dist2 = atoms.get_distance(atom1, atom2)
# Distance should increase due to the external force
assert dist2 > dist1

# Combine ExternalForce with FixBondLength

# Fix the bond on which the force acts
con2 = FixBondLength(atom1, atom2)
# ExternalForce constraint at the beginning of the list!!!
atoms.set_constraint([con1, con2])
opt = FIRE(atoms)
opt.run(fmax=fmax)
f_con = con2.constraint_forces

# It was already optimized with this external force, therefore
# the constraint force should be almost zero
assert norm(f_con[0]) <= fmax

# To get the complete constraint force (with external force),
# use only the FixBondLength constraint, after the optimization with
# ExternalForce
atoms.set_constraint(con2)
opt = FIRE(atoms)
예제 #17
0
from ase import Atoms
from ase.calculators.emt import EMT
from ase.constraints import FixBondLength
from ase.io import Trajectory
from ase.optimize import BFGS

a = 3.6
b = a / 2
cu = Atoms('Cu2Ag',
           positions=[(0, 0, 0),
                      (b, b, 0),
                      (a, a, b)],
           calculator=EMT())
e0 = cu.get_potential_energy()
print(e0)

d0 = cu.get_distance(0, 1)
cu.set_constraint(FixBondLength(0, 1))
t = Trajectory('cu2ag.traj', 'w', cu)
qn = BFGS(cu)
qn.attach(t.write)
def f(): print(cu.get_distance(0,1))
qn.attach(f)
qn.run(fmax=0.01)
assert abs(cu.get_distance(0, 1) - d0) < 1e-14
예제 #18
0
import ase
from ase.calculators.lj import LennardJones
from ase.constraints import FixBondLength
from ase.optimize import FIRE

for wrap in [False, True]:
    a = ase.Atoms('CCC',
                  positions=[[1, 0, 5],
                             [0, 1, 5],
                             [-1, 0.5, 5]],
                  cell=[10, 10, 10],
                  pbc=True)
    
    if wrap:
        a.set_scaled_positions(a.get_scaled_positions() % 1.0)
    a.set_calculator(LennardJones())
    a.set_constraint(FixBondLength(0, 2))

    d1 = a.get_distance(0, 2, mic=True)

    FIRE(a, logfile=None).run(fmax=0.01)
    e = a.get_potential_energy()
    d2 = a.get_distance(0, 2, mic=True)
    assert abs(e - -2.034988) < 1e-6
    assert abs(d1 - d2) < 1e-6
예제 #19
0
from ase.build import molecule
from ase.constraints import MirrorForce, FixBondLength, MirrorTorque
from ase.constraints import ExternalForce
from ase.optimize import FIRE
from ase.calculators.emt import EMT

atoms = molecule('cyclobutene')
dist = atoms.get_distance(0, 1)
con1 = MirrorForce(2, 3, max_dist=5., fmax=0.05)
con2 = FixBondLength(0, 1)
atoms.set_constraint([con1, con2])
atoms.set_calculator(EMT())
opt = FIRE(atoms)
opt.run(fmax=0.05)
assert round(dist - atoms.get_distance(0, 1), 5) == 0

atoms = molecule('butadiene')
# Break symmetry
atoms[0].position[2] += 0.2
dist = atoms.get_distance(1, 2)
con1 = MirrorTorque(0, 1, 2, 3, fmax=0.05)
con2 = ExternalForce(9, 4, f_ext=0.1)
atoms.set_constraint([con1, con2])
atoms.set_calculator(EMT())
opt = FIRE(atoms)
opt.run(fmax=0.05, steps=300)
# The result is not realistic because of EMT
예제 #20
0
#! /usr/bin/env python
from common_initialiser import *
from ase.constraints import FixBondLength

# warm_start_file = '../c0.35/crack-300K.xyz'

# conserve the weak bond
fix_dist = FixBondLength(*params.tipatoms)

# apply constraints
other_constraints = at.constraints
at.set_constraint(other_constraints + [fix_dist])

init_temp = 300.
temperature_step = (params.sim_T - init_temp) / params.n_steps


def temperature_break(at, dynamics):
    KinEng = at.get_kinetic_energy()
    n_steps = dynamics.get_number_of_steps()
    T_target = init_temp + n_steps * temperature_step
    KinEng_target = 1.5 * at.get_number_of_atoms() * units.kB * T_target
    at.set_momenta(KinEng_target / KinEng * at.get_momenta())
    print("Adjust momenta...")
    return


if params.warm_start_file is not None:
    at_help = quippy.AtomsList(params.warm_start_file, start=-1)[0]
    p = at_help.get_momenta()
    at.set_momenta(p)
예제 #21
0
import ase
import ase.io as io
from ase.calculators.lj import LennardJones
from ase.constraints import FixBondLength
from ase.optimize import FIRE

for mic in [False, True]:
    a = ase.Atoms('CCC', positions=[[1,0,5],[0,1,5],[-1,0.5,5]], cell=[10,10,10], pbc=True)
    a.set_scaled_positions(a.get_scaled_positions()%1.0)
    a.set_calculator(LennardJones())
    a.set_constraint(FixBondLength(0, 2, mic=mic, atoms=a))

    dist = a.get_distance(0, 2, mic=mic)

    FIRE(a, logfile=None).run(fmax=0.01)

    assert abs(a.get_distance(0, 2, mic=mic) - dist) < 1e-6

예제 #22
0
# Create CO molecule:
d = 1.1
co = Atoms('CO', positions=[(0, 0, 0), (0, 0, d)])

# Create slab:
slab = fcc111('Al', size=(2,2,3), vacuum=10.0)
slab = fcc111('Al', size=(2,2,3))

# Add CO on the slab:
add_adsorbate(slab, co, 2., 'bridge')
slab.center(vacuum=10.0, axis=2)

# Set constraints:
c1 = FixAtoms(indices=[atom.index for atom in slab if atom.symbol == 'Al'])
c2 = FixBondLength(12, 13)
slab.set_constraint([c1, c2])

atoms = slab.copy()

# 2. Benchmark.
###############################################################################

# 2.A. Optimize structure using MLMin (CatLearn).
initial_mlmin = atoms.copy()
initial_mlmin.set_calculator(calc)
mlmin_opt = MLMin(initial_mlmin, trajectory='results_catlearn.traj')
mlmin_opt.run(fmax=0.01, kernel='SQE')

final_atoms = read('results_catlearn.traj', ':')
예제 #23
0
        lwave  = True,
        lcharg = True,
        ###############################
        # Vdw Correction
        ###############################
        ivdw   = 10,
        ###############################
        # Dipole Correction
        ###############################
        # ldipol = True,
        # idipol = 3,
        # dipol  = (0.5, 0.5, 0.5)
       )
geo.set_calculator(calc)

# stress mask [XX, YY, ZZ, YZ, XZ, XY]
# 0 if fixed else 1
# unf = UnitCellFilter(geo, mask=[1,1,1,1,1,1])
# unf = UnitCellFilter(geo, mask=[1,1,0,0,0,1])
ch_bond_fix = FixBondLength(129, 143)
geo.constraints += [ch_bond_fix]
dyn = QuasiNewton(geo, logfile='opt.log', trajectory='opt.traj')

dyn.run(fmax=0.01)

write('final.vasp', geo, vasp5=True, direct=True)
EOF

rm -rf vasp

예제 #24
0
# FOR SURFACES, set to the height below which atoms are fixed.
# This is needed as the fixed bong length is a constraint and all of them need to be set again
# if your system is a cluster, this setting will be ignored
z_height = 10.0

# threshold bond-length for terminating the FBL calculation
threshold = 0.9

## CORRECT KPTS SET AUTOMATICALLY

#########################################################################################################
#####                                     END                                                       #####
#########################################################################################################

# apply all constraints
constraints = [FixBondLength(atom1, atom2)]

metal_atoms = [atom.index for atom in atoms if atom.symbol not in ['N', 'H']]
num_atoms = len(metal_atoms)

### NO NEED TO DO ANYTHING HERE ###
# the if conditions take care of everything
# checks which type of system it is and sets the right constraints

if num_atoms == 16:
    print "slab calculation..."
    kpts = (4, 4, 1)
    mask = [atom.z < z_height
            for atom in atoms]  # atoms in the structure to be fixed
    constraints.append(FixAtoms(mask=mask))
elif num_atoms == 13:
예제 #25
0
from ase import Atom, Atoms
from ase.calculators.lj import LennardJones
from ase.constraints import FixBondLength

dimer = Atoms([Atom('X', (0, 0, 0)),
               Atom('X', (0, 0, 1))],
              calculator=LennardJones(),
              constraint=FixBondLength(0, 1))
print dimer.get_forces()
print dimer.positions
dimer.positions[:] += 0.1
print dimer.positions
dimer.positions[:, 2] += 5.1
print dimer.positions
dimer.positions[:] = [(1,2,3),(4,5,6)]
print dimer.positions
dimer.set_positions([(1,2,3),(4,5,6.2)])
print dimer.positions

예제 #26
0
if os.path.exists('qn.traj') and os.path.getsize('qn.traj') != 0:
    atoms = io.read('qn.traj', index=-1)
else:
    atoms = io.read('InitialGeom.xyz')

cell = ([18.21500974, 0, 0], [-7.2860039, 8.92349591, 0], [0, 0, 34.94966576])
atoms.set_cell(cell)
atoms.set_pbc([1, 1, 1])

constraint_s = " ".join(
    [str(i + 1) for i in range(len(atoms)) if atoms[i].position[2] < 9])
print constraint_s
constraint = FixAtoms(
    indices=[atom.index for atom in atoms if atom.position[2] < 9])
c = FixBondLength(274, 276)

atoms.set_constraint([constraint, c])
io.write('InitialGeom.traj', atoms)

SYSNAME = 'MgAl2O4'

calc = CP2K(label=SYSNAME,
            xc='PBE',
            cutoff=None,
            basis_set_file=None,
            potential_file=None,
            basis_set=None,
            pseudo_potential=None,
            stress_tensor=False,
            max_scf=None,
예제 #27
0
파일: db2.py 프로젝트: uu1477/MyAse

for name in ['y2.json', 'y2.db']:
    c = connect(name)
    print(name, c)

    id = c.reserve(abc=7)
    c.delete([d.id for d in c.select(abc=7)])
    id = c.reserve(abc=7)
    assert c[id].abc == 7
    
    a = c.get_atoms(id)
    c.write(Atoms())
    ch4 = molecule('CH4', calculator=EMT())
    ch4.constraints = [FixAtoms(indices=[1]),
                       FixBondLength(0, 2)]
    f1 = ch4.get_forces()
    print(f1)
    
    c.delete([d.id for d in c.select(C=1)])
    chi = np.array([1 + 0.5j, 0.5])
    id = c.write(ch4, data={'1-butyne': 'bla-bla', 'chi': chi})

    row = c.get(id)
    print(row.data['1-butyne'], row.data.chi)
    assert (row.data.chi == chi).all()
    
    assert len(c.get_atoms(C=1).constraints) == 2

    f2 = c.get(C=1).forces
    assert abs(f2.sum(0)).max() < 1e-14
예제 #28
0
t = Trajectory(fname, 'a', co)
t.close()
os.remove(fname)

t = Trajectory('empty.traj', 'w')
t.close()
t = Trajectory('empty.traj', 'r')
assert len(t) == 0

t = Trajectory('fake.traj', 'w')
t.write(Atoms('H'), energy=-42.0, forces=[[1, 2, 3]])

t = Trajectory('only-energy.traj', 'w', properties=['energy'])
a = read('fake.traj')
t.write(a)
b = read('only-energy.traj')
e = b.get_potential_energy()
assert e + 42 == 0
with must_raise(PropertyNotImplementedError):
    f = b.get_forces()

# Make sure constraints play well with momenta:
a = Atoms('H2',
          positions=[(0, 0, 0), (0, 0, 1)],
          momenta=[(1, 0, 0), (0, 0, 0)])
a.constraints = [FixBondLength(0, 1)]
t = Trajectory('constraint.traj', 'w', a)
t.write()
b = read('constraint.traj')
assert not (b.get_momenta() - a.get_momenta()).any()
예제 #29
0
def test_trajectory():
    import pytest

    import os
    from ase import Atom, Atoms
    from ase.io import Trajectory, read
    from ase.constraints import FixBondLength
    from ase.calculators.calculator import PropertyNotImplementedError

    co = Atoms([Atom('C', (0, 0, 0)),
                Atom('O', (0, 0, 1.2))])
    traj = Trajectory('1.traj', 'w', co)

    written = []

    for i in range(5):
        co.positions[:, 2] += 0.1
        traj.write()
        written.append(co.copy())

    traj = Trajectory('1.traj', 'a')
    co = read('1.traj')
    print(co.positions)
    co.positions[:] += 1
    traj.write(co)
    written.append(co.copy())

    for a in Trajectory('1.traj'):
        print(1, a.positions[-1, 2])
    co.positions[:] += 1
    t = Trajectory('1.traj', 'a')
    t.write(co)
    written.append(co.copy())
    assert len(t) == 7

    co[0].number = 1
    t.write(co)
    written.append(co.copy())

    co[0].number = 6
    co.pbc = True
    t.write(co)
    written.append(co.copy())

    co.pbc = False
    o = co.pop(1)
    t.write(co)
    written.append(co.copy())

    co.append(o)
    t.write(co)
    written.append(co.copy())

    imgs = read('1.traj', index=':')
    assert len(imgs) == len(written)
    for img1, img2 in zip(imgs, written):
        assert img1 == img2

    # Verify slicing works.
    read_traj = Trajectory('1.traj', 'r')
    sliced_traj = read_traj[3:8]
    assert len(sliced_traj) == 5
    sliced_again = sliced_traj[1:-1]
    assert len(sliced_again) == 3
    assert sliced_traj[1] == sliced_again[0]

    # append to a nonexisting file:
    fname = '2.traj'
    if os.path.isfile(fname):
        os.remove(fname)
    t = Trajectory(fname, 'a', co)
    t.close()
    os.remove(fname)

    t = Trajectory('empty.traj', 'w')
    t.close()
    t = Trajectory('empty.traj', 'r')
    assert len(t) == 0

    t = Trajectory('fake.traj', 'w')
    t.write(Atoms('H'), energy=-42.0, forces=[[1, 2, 3]])

    t = Trajectory('only-energy.traj', 'w', properties=['energy'])
    a = read('fake.traj')
    t.write(a)
    b = read('only-energy.traj')
    e = b.get_potential_energy()
    assert e + 42 == 0
    with pytest.raises(PropertyNotImplementedError):
        b.get_forces()

    # Make sure constraints play well with momenta:
    a = Atoms('H2',
              positions=[(0, 0, 0), (0, 0, 1)],
              momenta=[(1, 0, 0), (0, 0, 0)])
    a.constraints = [FixBondLength(0, 1)]
    t = Trajectory('constraint.traj', 'w', a)
    t.write()
    b = read('constraint.traj')
    assert not (b.get_momenta() - a.get_momenta()).any()
예제 #30
-1
def test_emt1(testdir):
    a = 3.6
    b = a / 2
    cu = Atoms('Cu2Ag',
               positions=[(0, 0, 0),
                          (b, b, 0),
                          (a, a, b)],
               calculator=EMT())
    e0 = cu.get_potential_energy()
    print(e0)

    d0 = cu.get_distance(0, 1)
    cu.set_constraint(FixBondLength(0, 1))

    def f():
        print(cu.get_distance(0, 1))

    qn = BFGS(cu)
    with Trajectory('cu2ag.traj', 'w', cu) as t:
        qn.attach(t.write)

        qn.attach(f)
        qn.run(fmax=0.001)

    assert abs(cu.get_distance(0, 1) - d0) < 1e-14