Example #1
0
def calculate_eos(atoms, npoints=5, eps=0.04, trajectory=None, callback=None):
    """Calculate equation-of-state.

    atoms: Atoms object
        System to calculate EOS for.  Must have a calculator attached.
    npoints: int
        Number of points.
    eps: float
        Variation in volume from v0*(1-eps) to v0*(1+eps).
    trajectory: Trjectory object or str
        Write configurations to a trajectory file.
    callback: function
        Called after every energy calculation.

    >>> from ase.build import bulk
    >>> from ase.calculators.emt import EMT
    >>> a = bulk('Cu', 'fcc', a=3.6)
    >>> a.calc = EMT()
    >>> eos = calculate_eos(a, trajectory='Cu.traj')
    >>> v, e, B = eos.fit()
    >>> a = (4 * v)**(1 / 3.0)
    >>> print('{0:.6f}'.format(a))
    3.589825
    """

    # Save original positions and cell:
    p0 = atoms.get_positions()
    c0 = atoms.get_cell()

    if isinstance(trajectory, basestring):
        from ase.io import Trajectory
        trajectory = Trajectory(trajectory, 'w', atoms)

    if trajectory is not None:
        trajectory.set_description({'type': 'eos',
                                    'npoints': npoints,
                                    'eps': eps})

    try:
        energies = []
        volumes = []
        for x in np.linspace(1 - eps, 1 + eps, npoints)**(1 / 3):
            atoms.set_cell(x * c0, scale_atoms=True)
            volumes.append(atoms.get_volume())
            energies.append(atoms.get_potential_energy())
            if callback:
                callback()
            if trajectory is not None:
                trajectory.write()
        return EquationOfState(volumes, energies)
    finally:
        atoms.cell = c0
        atoms.positions = p0
        if trajectory is not None:
            trajectory.close()
Example #2
0
import sys

from ase.test import NotAvailable, must_raise

if sys.platform in ['win32']:
    raise NotAvailable('Fails on Windows '
                       'https://trac.fysik.dtu.dk/projects/ase/ticket/62')

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

co = Atoms([Atom('C', (0, 0, 0)),
            Atom('O', (0, 0, 1.2))])
traj = Trajectory('1.traj', 'w', co)
for i in range(5):
    co.positions[:, 2] += 0.1
    traj.write()

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

for a in Trajectory('1.traj'):
    print(1, a.positions[-1, 2])
co.positions[:] += 1
t = Trajectory('1.traj', 'a')
t.write(co)
Example #3
0
N = len(initial)  # number of atoms

# 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)
initial.set_constraint(constraint)

# Calculate using EMT:
initial.set_calculator(EMT())

# Relax the initial state:
QuasiNewton(initial).run(fmax=0.05)
e0 = initial.get_potential_energy()

traj = Trajectory('dimer_along.traj', 'w', initial)
traj.write()

# Making dimer mask list:
d_mask = [False] * (N - 1) + [True]

# Set up the dimer:
d_control = DimerControl(initial_eigenmode_method='displacement',
                         displacement_method='vector',
                         logfile=None,
                         mask=d_mask)
d_atoms = MinModeAtoms(initial, d_control)

# Displacement settings:
displacement_vector = np.zeros((N, 3))
# Strength of displacement along y axis = along row:
Example #4
0
# creates: lattice_constant.csv

import numpy as np
a0 = 3.52 / np.sqrt(2)
c0 = np.sqrt(8 / 3.0) * a0

from ase.io import Trajectory
traj = Trajectory('Ni.traj', 'w')

from ase.lattice import bulk
from ase.calculators.emt import EMT
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):
        ni = bulk('Ni', 'hcp', a=a, c=c)
        ni.set_calculator(EMT())
        ni.get_potential_energy()
        traj.write(ni)

from ase.io import read
configs = read('Ni.traj@:')
energies = [config.get_potential_energy() for config in configs]
a = np.array([config.cell[0, 0] for config in configs])
c = np.array([config.cell[2, 2] for config in configs])

functions = np.array([a**0, a, c, a**2, a * c, c**2])
p = np.linalg.lstsq(functions.T, energies)[0]

p0 = p[0]
p1 = p[1:3]
p2 = np.array([(2 * p[3], p[4]),
    linspace = (1.0, 1.0, 1)  # eos numpy's linspace
linspacestr = ''.join([str(t) + 'x' for t in linspace])[:-1]

code = category + '_gpaw' + '-' + mode + str(e) + '_c' + str(constant_basis)
code = code + '_e' + linspacestr
code = code + '_k' + str(kptdensity) + '_w' + str(width)
code = code + '_r' + str(relativistic)

for name in names:
    # save all steps in one traj file in addition to the database
    # we should only used the database c.reserve, but here
    # traj file is used as another lock ...
    fd = opencew(name + '_' + code + '.traj')
    if fd is None:
        continue
    traj = Trajectory(name + '_' + code + '.traj', 'w')
    atoms = collection[name]
    cell = atoms.get_cell()
    kpts = tuple(kpts2mp(atoms, kptdensity, even=True))
    kwargs = {}
    if mode == 'fd':
        if constant_basis:
            # gives more smooth EOS in fd mode
            kwargs.update({'gpts': h2gpts(e, cell)})
        else:
            kwargs.update({'h': e})
    elif mode == 'pw':
        if constant_basis:
            kwargs.update({'mode': PW(e, cell=cell)})
        else:
            kwargs.update({'mode': PW(e)})
Example #6
0
import numpy as np
from ase import Atoms
from ase.calculators.emt import EMT
from ase.io import Trajectory

Cu = Atoms('Cu', pbc=(1, 0, 0), calculator=EMT())
traj = Trajectory('Cu.traj', 'w')
for a in np.linspace(2.0, 4.0, 20):
    Cu.set_cell([a, 1, 1], scale_atoms=True)
    traj.write(Cu)
Example #7
0
from ase.calculators.emt import EMT
from ase.collections import dcdft
from ase.io import Trajectory

for symbol in ['Al', 'Ni', 'Cu', 'Pd', 'Ag', 'Pt', 'Au']:
    traj = Trajectory('{}.traj'.format(symbol), 'w')
    for s in range(94, 108, 2):
        atoms = dcdft[symbol]
        atoms.set_cell(atoms.cell * (s / 100)**(1 / 3), scale_atoms=True)
        atoms.calc = EMT()
        atoms.get_potential_energy()
        traj.write(atoms)
Example #8
0
    def execute_one_neb(self, n_cur, to_run, climb=False, many_steps=False):
        '''Internal method which executes one NEB optimization.'''
        self.iteration += 1
        # First we copy around all the images we are not using in this
        # neb (for reproducability purposes)
        if self.world.rank == 0:
            for i in range(n_cur):
                if i not in to_run[1:-1]:
                    filename = '%s%03d.traj' % (self.prefix, i)
                    t = Trajectory(filename,
                                   mode='w',
                                   atoms=self.all_images[i])
                    t.write()
                    filename_ref = self.iter_folder + \
                        '/%s%03diter%03d.traj' % (self.prefix, i,
                                                  self.iteration)
                    if os.path.isfile(filename):
                        shutil.copy2(filename, filename_ref)
        if self.world.rank == 0:
            print('Now starting iteration %d on ' % self.iteration, to_run)
        # Attach calculators to all the images we will include in the NEB
        self.attach_calculators([self.all_images[i] for i in to_run[1:-1]])
        neb = NEB([self.all_images[i] for i in to_run],
                  k=[self.k[i] for i in to_run[0:-1]],
                  method=self.method,
                  parallel=self.parallel,
                  remove_rotation_and_translation=self.
                  remove_rotation_and_translation,
                  climb=climb)

        # Do the actual NEB calculation
        qn = self.optimizer(neb,
                            logfile=self.iter_folder + '/%s_log_iter%03d.log' %
                            (self.prefix, self.iteration))

        # Find the ranks which are masters for each their calculation
        if self.parallel:
            nneb = to_run[0]
            nim = len(to_run) - 2
            n = self.world.size // nim  # number of cpu's per image
            j = 1 + self.world.rank // n  # my image number
            assert nim * n == self.world.size
            traj = Trajectory('%s%03d.traj' % (self.prefix, j + nneb),
                              'w',
                              self.all_images[j + nneb],
                              master=(self.world.rank % n == 0))
            filename_ref = self.iter_folder + \
                '/%s%03diter%03d.traj' % (self.prefix,
                                          j + nneb, self.iteration)
            trajhist = Trajectory(filename_ref,
                                  'w',
                                  self.all_images[j + nneb],
                                  master=(self.world.rank % n == 0))
            qn.attach(traj)
            qn.attach(trajhist)
        else:
            num = 1
            for i, j in enumerate(to_run[1:-1]):
                filename_ref = self.iter_folder + \
                    '/%s%03diter%03d.traj' % (self.prefix, j, self.iteration)
                trajhist = Trajectory(filename_ref, 'w', self.all_images[j])
                qn.attach(seriel_writer(trajhist, i, num).write)

                traj = Trajectory('%s%03d.traj' % (self.prefix, j), 'w',
                                  self.all_images[j])
                qn.attach(seriel_writer(traj, i, num).write)
                num += 1

        if isinstance(self.maxsteps, (list, tuple)) and many_steps:
            steps = self.maxsteps[1]
        elif isinstance(self.maxsteps, (list, tuple)) and not many_steps:
            steps = self.maxsteps[0]
        else:
            steps = self.maxsteps

        if isinstance(self.fmax, (list, tuple)) and many_steps:
            fmax = self.fmax[1]
        elif isinstance(self.fmax, (list, tuple)) and not many_steps:
            fmax = self.fmax[0]
        else:
            fmax = self.fmax
        qn.run(fmax=fmax, steps=steps)

        # Remove the calculators and replace them with single
        # point calculators and update all the nodes for
        # preperration for next iteration
        neb.distribute = types.MethodType(store_E_and_F_in_spc, neb)
        neb.distribute()
Example #9
0
    # Set calculator
    # loop a number of times to capture if minimization stops with high force
    # due to the VariansBreak calls
    niter = 0

    # If the structure is already fully relaxed just return it
    traj = Trajectory(label + '_lcao.traj', 'w', structure)
    while (structure.get_forces()**
           2).sum(axis=1).max()**0.5 > forcemax and niter < niter_max:
        dyn = BFGS(structure, logfile=label + '.log')
        vb = VariansBreak(structure, dyn, min_stdev=0.01, N=15)
        dyn.attach(traj)
        dyn.attach(vb)
        dyn.run(fmax=forcemax, steps=steps)
        niter += 1
    #print('relaxgpaw over',flush=True)
    return structure


calc = GPAW(mode=PW(500), xc='PBE', basis='dzp', kpts=(3, 3, 1))

traj = Trajectory('V2O5_2H2OTiO2_101_DFTrelaxed.traj', 'w')
name = 'V2O5_2H2OTiO2_101surface_gm'
data = read('V2O5_2H2O_TiO2_I3s.traj@:')
for i in range(0, len(data)):
    name = 'V2O5_2H2OTiO2_101surface_isomer_{}'.format(i)
    a = data[i]
    a.set_calculator(calc)
    a_relaxed = relaxGPAW(a, name, forcemax=0.01, niter_max=2, steps=100)
    traj.write(a_relaxed)
Example #10
0
def polyfit(x, y, order=3):
    """Fit polynomium at points in x to values in y.

    With D dimensions and N points, x must have shape (N, D) and y
    must have length N."""
    
    p = NDPoly(len(x[0]), order)
    p.fit(x, y)
    return p

    
a0 = 3.52 / np.sqrt(2)
c0 = np.sqrt(8 / 3.0) * a0
print('%.4f %.3f' % (a0, c0 / a0))
for i in range(3):
    traj = Trajectory('Ni.traj', 'w')
    eps = 0.01
    for a in a0 * np.linspace(1 - eps, 1 + eps, 4):
        for c in c0 * np.linspace(1 - eps, 1 + eps, 4):
            ni = bulk('Ni', 'hcp', a=a, covera=c / a)
            ni.set_calculator(EMT())
            ni.get_potential_energy()
            traj.write(ni)
    traj.close()

    configs = read('Ni.traj@:')
    energies = [config.get_potential_energy() for config in configs]
    ac = [(config.cell[0, 0], config.cell[2, 2]) for config in configs]
    p = polyfit(ac, energies, 2)
    from scipy.optimize import fmin_bfgs
    a0, c0 = fmin_bfgs(p, (a0, c0))
Example #11
0
import sys

from ase.test import NotAvailable, must_raise

if sys.platform in ['win32']:
    raise NotAvailable('Fails on Windows '
                       'https://trac.fysik.dtu.dk/projects/ase/ticket/62')

import os
from ase import Atom, Atoms
from ase.io import Trajectory, read

co = Atoms([Atom('C', (0, 0, 0)),
            Atom('O', (0, 0, 1.2))])
traj = Trajectory('1.traj', 'w', co)
for i in range(5):
    co.positions[:, 2] += 0.1
    traj.write()

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

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