Example #1
0
def relax(input_atoms, ref_db):
    atoms_string = input_atoms.get_chemical_symbols()

    # Open connection to the database with reference data
    db = connect(ref_db)

    # Load our model structure which is just FCC
    atoms = FaceCenteredCubic('X', latticeconstant=1.)
    atoms.set_chemical_symbols(atoms_string)

    # Compute the average lattice constant of the metals in this individual
    # and the sum of energies of the constituent metals in the fcc lattice
    # we will need this for calculating the heat of formation
    a = 0
    ei = 0
    for m in set(atoms_string):
        dct = db.get(metal=m)
        count = atoms_string.count(m)
        a += count * dct.latticeconstant
        ei += count * dct.energy_per_atom
    a /= len(atoms_string)
    atoms.set_cell([a, a, a], scale_atoms=True)

    # Since calculations are extremely fast with EMT we can also do a volume
    # relaxation
    atoms.set_calculator(EMT())
    eps = 0.05
    volumes = (a * np.linspace(1 - eps, 1 + eps, 9))**3
    energies = []
    for v in volumes:
        atoms.set_cell([v**(1. / 3)] * 3, scale_atoms=True)
        energies.append(atoms.get_potential_energy())

    eos = EquationOfState(volumes, energies)
    v1, ef, B = eos.fit()
    latticeconstant = v1**(1. / 3)

    # Calculate the heat of formation by subtracting ef with ei
    hof = (ef - ei) / len(atoms)

    # Place the calculated parameters in the info dictionary of the
    # input_atoms object
    input_atoms.info['key_value_pairs']['hof'] = hof
    
    # Raw score must always be set
    # Use one of the following two; they are equivalent
    input_atoms.info['key_value_pairs']['raw_score'] = -hof
    # set_raw_score(input_atoms, -hof)
    
    input_atoms.info['key_value_pairs']['latticeconstant'] = latticeconstant

    # Setting the atoms_string directly for easier analysis
    atoms_string = ''.join(input_atoms.get_chemical_symbols())
    input_atoms.info['key_value_pairs']['atoms_string'] = atoms_string
Example #2
0
def MakeCu(T=300, size=(29,29,30)):
    print "Preparing", T, "K Copper system."
    atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]],
                              symbol='Cu', size=size)
    atoms.set_calculator(EMT())
    MaxwellBoltzmannDistribution(atoms, 2*T * units.kB)
    #dyn = VelocityVerlet(atoms, 5*units.fs)
    dyn = Langevin(atoms, 5*units.fs, T*units.kB, 0.05)
    dyn.run(50)
    print "Done.  Temperature =", temperature(atoms), \
          "K.  Number of atoms: ", len(atoms)
    return atoms
Example #3
0
    def test_stress(self):
        a = FaceCenteredCubic('Au', size=[2,2,2])
        calc = EAM('Au-Grochola-JCP05.eam.alloy')
        a.set_calculator(calc)
        self.assertArrayAlmostEqual(a.get_stress(), calc.calculate_numerical_stress(a), tol=self.tol)

        sx, sy, sz = a.cell.diagonal()
        a.set_cell([sx, 0.9*sy, 1.2*sz], scale_atoms=True)
        self.assertArrayAlmostEqual(a.get_stress(), calc.calculate_numerical_stress(a), tol=self.tol)

        a.set_cell([[sx, 0.1*sx, 0], [0, 0.9*sy, 0], [0, -0.1*sy, 1.2*sz]], scale_atoms=True)
        self.assertArrayAlmostEqual(a.get_stress(), calc.calculate_numerical_stress(a), tol=self.tol)
Example #4
0
 def test_Grochola(self):
     a = FaceCenteredCubic('Au', size=[2,2,2])
     calc = EAM('Au-Grochola-JCP05.eam.alloy')
     a.set_calculator(calc)
     FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
     a0 = a.cell.diagonal().mean()/2
     self.assertTrue(abs(a0-4.0701)<2e-5)
     self.assertTrue(abs(a.get_potential_energy()/len(a)+3.924)<0.0003)
     C, C_err = fit_elastic_constants(a, symmetry='cubic', verbose=False)
     C11, C12, C44 = Voigt_6x6_to_cubic(C)
     self.assertTrue(abs((C11-C12)/GPa-32.07)<0.7)
     self.assertTrue(abs(C44/GPa-45.94)<0.5)
Example #5
0
    def test_CuZr(self):
        # This is a test for the potential published in:
        # Mendelev, Sordelet, Kramer, J. Appl. Phys. 102, 043501 (2007)
        a = FaceCenteredCubic('Cu', size=[2,2,2])
        calc = EAM('CuZr_mm.eam.fs', kind='eam/fs')
        a.set_calculator(calc)
        FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        a_Cu = a.cell.diagonal().mean()/2
        #print('a_Cu (3.639) = ', a_Cu)
        self.assertAlmostEqual(a_Cu, 3.639, 3)

        a = HexagonalClosedPacked('Zr', size=[2,2,2])
        a.set_calculator(calc)
        FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        a, b, c = a.cell/2
        #print('a_Zr (3.220) = ', norm(a), norm(b))
        #print('c_Zr (5.215) = ', norm(c))
        self.assertAlmostEqual(norm(a), 3.220, 3)
        self.assertAlmostEqual(norm(b), 3.220, 3)
        self.assertAlmostEqual(norm(c), 5.215, 3)

        # CuZr3
        a = L1_2(['Cu', 'Zr'], size=[2,2,2], latticeconstant=4.0)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        self.assertAlmostEqual(a.cell.diagonal().mean()/2, 4.324, 3)

        # Cu3Zr
        a = L1_2(['Zr', 'Cu'], size=[2,2,2], latticeconstant=4.0)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        self.assertAlmostEqual(a.cell.diagonal().mean()/2, 3.936, 3)

        # CuZr
        a = B2(['Zr', 'Cu'], size=[2,2,2], latticeconstant=3.3)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        self.assertAlmostEqual(a.cell.diagonal().mean()/2, 3.237, 3)
Example #6
0
#nsteps = 5000
nprint = 50000
nequil = 100000
nminor = 25
nequilprint = 200
tolerance = 0.01
timestep = 5 # fs
frict = 0.001
temp = 100 # K
repeats = 5

# Set up atoms in a regular simple-cubic lattice.
initial = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]],
                            size = (1,5,5), symbol="Cu", latticeconstant=3.5,
                            pbc=False, debug=0)
initial.set_calculator(EMT())
    
ReportTest("Number of atoms", len(initial), 100, 0)

# Make a small perturbation of the momenta
initial.set_momenta(1e-6 * np.random.normal(size=[len(initial), 3]))
print "Initializing (1) ..."
predyn = VelocityVerlet(initial, 0.5)
predyn.run(2500)

initial2 = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]],
                             size = (4,4,4), symbol="Cu", debug=0)
initial2.set_calculator(EMT())
# Make a small perturbation of the momenta
initial2.set_momenta(1e-6 * np.random.normal(size=[len(initial2), 3]))
print "Initializing (2) ..."
Example #7
0
from ase.calculators.vasp import Vasp
from ase.lattice.cubic import FaceCenteredCubic
from ase.io import write
calc = Vasp(xc='PBE', kpts=(3,3,3), ismear=0, sigma=0.1, ediff=1e-10, lcharg=False, lwave=False, encut=400,
            nelmin=4, nelmdl=6, ispin=1,lvdw=True, vdw_version=3,isif=3,ibrion=1,nsw=500)

#a = 5.0
#c = 3.5
#iro2 = crystal(['Ir', 'O'], basis=[(0,0,0), (0.3,0.3,0)], cellpar=[a, a, c, 90, 90, 90], spacegroup=136)
#FCC

Cell = FaceCenteredCubic(symbol='Ag') 
Cell.set_calculator(calc)

calc.initialize(Cell)
calc.write_incar(Cell)
calc.write_potcar()
calc.write_kpoints()
write('POSCAR', calc.atoms_sorted)  # this will write a "sorted" POSCAR


#sf = StrainFilter(Cell)

#opt = LBFGS(sf, trajectory=traj('atom-cell.traj', 'w', Cell))
#opt.run(fmax=0.01)

#opt = LBFGS(Cell, trajectory=traj('atom.traj', 'w', Cell))
#opt.run(fmax=0.01)

    def test_direct_evaluation(self):
        a = FaceCenteredCubic('Au', size=[2, 2, 2])
        a.rattle(0.1)
        calc = EAM('Au-Grochola-JCP05.eam.alloy')
        a.set_calculator(calc)
        f = a.get_forces()

        calc2 = EAM('Au-Grochola-JCP05.eam.alloy')
        i_n, j_n, dr_nc, abs_dr_n = neighbour_list('ijDd',
                                                   a,
                                                   cutoff=calc2.cutoff)
        epot, virial, f2 = calc2.energy_virial_and_forces(
            a.numbers, i_n, j_n, dr_nc, abs_dr_n)
        self.assertArrayAlmostEqual(f, f2)

        a = FaceCenteredCubic('Cu', size=[2, 2, 2])
        calc = EAM('CuAg.eam.alloy')
        a.set_calculator(calc)
        FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0]),
             logfile=None).run(fmax=0.001)
        e_Cu = a.get_potential_energy() / len(a)

        a = FaceCenteredCubic('Ag', size=[2, 2, 2])
        a.set_calculator(calc)
        FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0]),
             logfile=None).run(fmax=0.001)
        e_Ag = a.get_potential_energy() / len(a)
        self.assertTrue(abs(e_Ag + 2.85) < 1e-6)

        a = L1_2(['Ag', 'Cu'], size=[2, 2, 2], latticeconstant=4.0)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]),
             logfile=None).run(fmax=0.001)
        e = a.get_potential_energy()
        syms = np.array(a.get_chemical_symbols())
        self.assertTrue(
            abs((e - (syms == 'Cu').sum() * e_Cu -
                 (syms == 'Ag').sum() * e_Ag) / len(a) - 0.096) < 0.0005)

        a = B1(['Ag', 'Cu'], size=[2, 2, 2], latticeconstant=4.0)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]),
             logfile=None).run(fmax=0.001)
        e = a.get_potential_energy()
        syms = np.array(a.get_chemical_symbols())
        self.assertTrue(
            abs((e - (syms == 'Cu').sum() * e_Cu -
                 (syms == 'Ag').sum() * e_Ag) / len(a) - 0.516) < 0.0005)

        a = B2(['Ag', 'Cu'], size=[2, 2, 2], latticeconstant=4.0)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]),
             logfile=None).run(fmax=0.001)
        e = a.get_potential_energy()
        syms = np.array(a.get_chemical_symbols())
        self.assertTrue(
            abs((e - (syms == 'Cu').sum() * e_Cu -
                 (syms == 'Ag').sum() * e_Ag) / len(a) - 0.177) < 0.0003)

        a = L1_2(['Cu', 'Ag'], size=[2, 2, 2], latticeconstant=4.0)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]),
             logfile=None).run(fmax=0.001)
        e = a.get_potential_energy()
        syms = np.array(a.get_chemical_symbols())
        self.assertTrue(
            abs((e - (syms == 'Cu').sum() * e_Cu -
                 (syms == 'Ag').sum() * e_Ag) / len(a) - 0.083) < 0.0005)
Example #9
0
lasttime = targettime
results = {}
for nthreads in threads:
    try:
        AsapThreads(nthreads)
    except ValueError:
        break
    maxthread = nthreads
    for natoms in sizes:
        print "Timing with %i atoms (%i threads)" % (natoms, nthreads)
        blocksize = int(np.ceil((natoms/4)**(1./3.)))
        atoms = FaceCenteredCubic(symbol='Cu', size=(blocksize,blocksize,blocksize), pbc=False)
        print "Creating block with %i atoms, cutting to %i atoms" % (len(atoms), natoms)
        atoms = atoms[:natoms]
        assert len(atoms) == natoms
        atoms.set_calculator(EMT())
        MaxwellBoltzmannDistribution(atoms, 2 * T * units.kB)
        dyn = VelocityVerlet(atoms, 5*units.fs)
        ptsteps = int(laststeps * (0.1 * targettime / lasttime) * lastsize / natoms)
        if ptsteps < 100:
            ptsteps = 100
        print "Running pre-timing (%i steps)..." % (ptsteps,)
        t1 = time.time()
        dyn.run(ptsteps - 50)
        MaxwellBoltzmannDistribution(atoms, (2 * T - atoms.get_temperature()) * units.kB)
        dyn.run(50)
        t1 = time.time() - t1
        steps = int(ptsteps * targettime / t1)
        if steps < 200:
            steps = 200 
        print "Temperature is %.1f K" % (atoms.get_temperature(),)
Example #10
0
import numpy as np

from ase.constraints import UnitCellFilter
from ase.lattice.cubic import FaceCenteredCubic
from ase.optimize import FIRE
from ase.utils.eos import EquationOfState

from atomistica import TabulatedAlloyEAM

###

n = 2
a = FaceCenteredCubic('Au', size=[n, n, n])
x0 = a.cell[0, 0]/n
c = TabulatedAlloyEAM(fn='Au-Grochola-JCP05.eam.alloy')
a.set_calculator(c)

# Vary volume and fit minimum
def en(a, x):
	a.set_cell([x, x, x], scale_atoms=True)
	return a.get_potential_energy()
x = np.linspace(0.9*x0, 1.1*x0, 101)
e = [ en(a, n*_x)/(n**3) for _x in x ]
eos = EquationOfState(x**3, e)
v0, e0, B = eos.fit()

print 'lattice constant (from equation of state) =', v0**(1./3)

# Keep cell rectangular during optimization
FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.0001)
Example #11
0
 txt = nbltype + (" PBC=%1i%1i%1i " % pbc)
 # Test that EMT reimported through OpenKIM gives the right results.
 atoms_kim = FaceCenteredCubic(size=(10,10,10), symbol='Cu')
 #atoms_kim = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]],
 #                    size=(30, 30, 30),
 #                    symbol="Cu")
 natoms = len(atoms_kim)
 atoms_kim.set_pbc(pbc)
 r = atoms_kim.get_positions()
 r.flat[:] += 0.1 * np.sin(np.arange(3*natoms))
 atoms_kim.set_positions(r)
 atoms_emt = atoms_kim.copy()
 kim = OpenKIMcalculator(openkimmodel, allowed=nbltype)
 emt = EMT()
 emt.set_subtractE0(False)
 atoms_kim.set_calculator(kim)
 atoms_emt.set_calculator(emt)
 ek = atoms_kim.get_potential_energy()
 ee = atoms_emt.get_potential_energy()
 ReportTest(txt+"Total energy", ek, ee, 1e-8)
 ek = atoms_kim.get_potential_energies()
 ee = atoms_emt.get_potential_energies()
 for i in range(0, natoms, step):
     ReportTest(txt+"Energy of atom %i" % (i,), ek[i], ee[i], 1e-8)
 fk = atoms_kim.get_forces()
 fe = atoms_emt.get_forces()
 n = 0
 for i in range(0, natoms, step):
     n = (n + 1) % 3
     ReportTest(txt+"Force(%i) of atom %i" % (n, i), fk[i, n], fe[i, n], 1e-8)
 sk = atoms_kim.get_stress()
            for i2, p2 in enumerate(positions[:i1]):
                diff = p2 - p1
                d2 = np.dot(diff, diff)
                c6 = (self.sigma**2 / d2)**3
                c12 = c6**2
                if d2 < self.cutoff**2:
                    self.energy += 4 * self.epsilon * (c12 - c6) - self.shift
                F = 24 * self.epsilon * (2 * c12 - c6) / d2 * diff
                self._forces[i1] -= F
                self._forces[i2] += F
        self.positions = positions.copy()



N = 5
ar = FaceCenteredCubic('Ar', pbc=[(0,0,0)], directions=[[1,0,0],[0,1,0],[0,0,1]], size=[N,N,N])
print ar.get_cell()
#view(ar) 

calc1 = KIMCalculator("ex_model_Ar_P_LJ")
ar.set_calculator(calc1)
kim_energy = ar.get_potential_energy()
print "kim energy = ", kim_energy 

calc2 = LennardJones(epsilon=epsilon, sigma=sigma, cutoff=cutoff)
ar.set_calculator(calc2)
ase_energy = ar.get_potential_energy()
print "ase energy = ", ase_energy 

print "difference = ", kim_energy - ase_energy
Example #13
0
from ase.calculators.emt import EMT

#from asap3 import EMT  # Way too slow with ase.EMT !

size = 10

T = 1500  # Kelvin

# Set up a crystal
atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                          symbol="Cu",
                          size=(size, size, size),
                          pbc=False)

# Describe the interatomic interactions with the Effective Medium Theory
atoms.set_calculator(EMT())

# We want to run MD with constant energy using the Langevin algorithm
# with a time step of 5 fs, the temperature T and the friction
# coefficient to 0.02 atomic units.
dyn = Langevin(atoms, 5 * units.fs, T * units.kB, 0.002)


def printenergy(a=atoms):  # store a reference to atoms in the definition.
    """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))

Example #14
0
"""Check that energy is correct even after wrapping through periodic boundary conditions.
"""

from ase.lattice.cubic import FaceCenteredCubic
from asap3 import *
from asap3.testtools import *
import random

ref_atoms = FaceCenteredCubic(size=(7,7,7), symbol="Cu", pbc=(True, False, True))
ref_atoms.set_calculator(EMT())

ref_energy = ref_atoms.get_potential_energy()
ref_energies = ref_atoms.get_potential_energies()
ref_forces = ref_atoms.get_forces()

passes = 5
for ps in range(passes):
    print "Pass", ps, "of", passes

    atoms = ref_atoms.copy()
    atoms.set_calculator(EMT())
    nat = random.randint(0, len(atoms))
    assert nat < len(atoms)
    pos0 = atoms[nat].position
    cell = atoms.get_cell()
    for d in range(1,4):
        for dx in (-d, 0, d):
            #for dy in (-d, 0, d):
            for dy in (0,):
                for dz in (-d, 0 ,d):
                    deltar = dx * cell[0] + dy * cell[1] + dz * cell[2]
Example #15
0
from ase.io import write, read
from ase import units
from ase.lattice.cubic import FaceCenteredCubic
from ase.md.verlet import VelocityVerlet
from ase.optimize import FIRE

# Parameters for the Morse potential for Cu
D = 0.3429
r0 = 2.866
alpha = 1.3588


atoms = FaceCenteredCubic(latticeconstant=1.5, symbol='Cu', pbc=False, size=(3,3,3))
atoms.center(vacuum=100)

atoms.set_calculator(MorsePotential(D=D, alpha=alpha, r0=r0))

dyn = FIRE(atoms, trajectory='relax.traj')

dyn.run(fmax=0.01)

write('relax.xyz', read('relax.traj@:')) # uncomment this line for Task 2


open('md_fire.log', 'w').close() # clean current log file
dyn = VelocityVerlet(atoms, dt=1 * units.fs,
                     trajectory='md_fire.traj', logfile='md_fire.log')

dyn.run(1000)
write('md_fire.xyz', read('md_fire.traj@:'))
# write('langevin.xyz', read('langevin.traj@:')) # uncomment this line for Task 3
Example #16
0
    return p


def MakeEMT2013():
    "EMT2013 potential."
    return EMT2013(PtY_parameters)


for pot in (EMT, MakeLJ, MakeEMT2013):
    print "Testing:", pot.__doc__.split("\n")[0]

    atoms1 = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                               size=(6, 6, 6),
                               symbol="Pt")
    emt = pot()
    atoms1.set_calculator(emt)
    f1 = atoms1.get_forces()

    atoms2 = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                               size=(5, 5, 5),
                               symbol="Pt")
    atoms2.set_calculator(emt)
    f3 = atoms1.get_forces()
    maxdev = abs(f3 - f1).max()
    print maxdev
    ReportTest("Max error 1:", maxdev, 0.0, 1e-6)

    atoms1 = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                               size=(6, 6, 6),
                               symbol="Pt")
    emt = pot()
Example #17
0
                                         delta=0.01,
                                         full_output=True,
                                         disp=False)
    #print "Minimize unit cell:", xopt, fopt, iter, calls


if __name__ == '__main__':
    from asap3 import EMT, units, EMThcpParameters
    from ase.lattice.cubic import FaceCenteredCubic
    from ase.lattice.hexagonal import HexagonalClosedPacked

    print "Calculating cubic constants for Cu"
    atoms = FaceCenteredCubic(size=(5, 5, 5),
                              symbol='Cu',
                              latticeconstant=3.59495722231)
    atoms.set_calculator(EMT())
    e = ElasticConstants(atoms, 'cubic')
    print np.array(e) / units.GPa

    print "Pretending that Cu is hexagonal"
    e = ElasticConstants(atoms, 'hexagonal', sanity=False)
    print np.array(e) / units.GPa

    print "Calculating elastic constants for Ru"
    atoms = HexagonalClosedPacked(size=(5, 5, 5),
                                  symbol='Ru',
                                  directions=[[1, -2, 1, 0], [1, 0, -1, 0],
                                              [0, 0, 0, 1]])
    atoms.set_calculator(EMT(EMThcpParameters()))
    e = ElasticConstants(atoms, 'hexagonal', minimize=True)
    print np.array(e) / units.GPa
potential_path = os.environ.get('LAMMPS_POTENTIALS_PATH', '.')
cmds = [
    "pair_style eam/alloy", "pair_coeff * * {path}/NiAlH_jea.eam.alloy Ni H"
    "".format(path=potential_path)
]
lammps = LAMMPSlib(lmpcmds=cmds,
                   atom_types={
                       'Ni': 1,
                       'H': 2
                   },
                   log_file='test.log',
                   keep_alive=True)
atoms = FaceCenteredCubic(size=(2, 2, 2),
                          latticeconstant=3.52,
                          symbol="Ni",
                          pbc=True)
atoms.set_calculator(lammps)

energy_ppp_ref = -142.400000403
energy_ppp = atoms.get_potential_energy()
print("Computed energy with boundary ppp = {}".format(energy_ppp))
diff_ppp = abs((energy_ppp - energy_ppp_ref) / energy_ppp_ref)
assert diff_ppp < 1e-10, "Expected " + str(energy_ppp_ref)

atoms.set_pbc((False, False, True))
energy_ssp_ref = -114.524625705
energy_ssp = atoms.get_potential_energy()
print("Computed energy with boundary ssp = {}".format(energy_ssp))
diff_ssp = abs((energy_ssp - energy_ssp_ref) / energy_ssp_ref)
assert diff_ssp < 1e-10, "Expected " + str(energy_ssp_ref)
Example #19
0
    def test_mix_eam_alloy(self):
        if False:
            source,parameters,F,f,rep = read_eam("CuAu_Zhou.eam.alloy",kind="eam/alloy")
            source1,parameters1,F1,f1,rep1 = mix_eam(["Cu_Zhou.eam.alloy","Au_Zhou.eam.alloy"],"eam/alloy","weight")
            write_eam(source1,parameters1,F1,f1,rep1,"CuAu_mixed.eam.alloy",kind="eam/alloy")

            calc0 = EAM('CuAu_Zhou.eam.alloy')
            calc1 = EAM('CuAu_mixed.eam.alloy')
       
            a = FaceCenteredCubic('Cu', size=[2,2,2])
            a.set_calculator(calc0)
            FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
            e0 = a.get_potential_energy()/len(a)
            a = FaceCenteredCubic('Cu', size=[2,2,2])
            a.set_calculator(calc1)
            FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
            e1 = a.get_potential_energy()/len(a)
            self.assertTrue(e0-e1 < 0.0005)

            a = FaceCenteredCubic('Au', size=[2,2,2])
            a.set_calculator(calc0)
            FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
            e0 = a.get_potential_energy()/len(a)
            a = FaceCenteredCubic('Au', size=[2,2,2])
            a.set_calculator(calc1)
            FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
            e1 = a.get_potential_energy()/len(a)
            self.assertTrue(e0-e1 < 0.0005)

            a = L1_2(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0)
            a.set_calculator(calc0)
            FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
            e0 = a.get_potential_energy()/len(a)
            a = L1_2(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0)
            a.set_calculator(calc1)
            FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
            e1 = a.get_potential_energy()/len(a)
            self.assertTrue(e0-e1 < 0.0005)

            a = L1_2(['Cu', 'Au'], size=[2,2,2], latticeconstant=4.0)
            a.set_calculator(calc0)
            FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
            e0 = a.get_potential_energy()/len(a)
            a = L1_2(['Cu', 'Au'], size=[2,2,2], latticeconstant=4.0)
            a.set_calculator(calc1)
            FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
            e1 = a.get_potential_energy()/len(a)
            self.assertTrue(e0-e1 < 0.0005)

            a = B1(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0)
            a.set_calculator(calc0)
            FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
            e0 = a.get_potential_energy()/len(a)
            a = B1(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0)
            a.set_calculator(calc1)
            FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
            e1 = a.get_potential_energy()/len(a)
            self.assertTrue(e0-e1 < 0.0005)
          
            os.remove("CuAu_mixed.eam.alloy")
Example #20
0
    nrun = 1

for ntest in range(nrun):
    print
    print "Running pass", ntest+1, "of", nrun
    print
    if pbcrnd:
        pbc =   tuple(random.randint(0,2,3))
    print "Periodic boundaries:", pbc
    if nrun > 1:
        time.sleep(1)
    atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], size=(10,10,10),
                              symbol=element, pbc=pbc)
    atoms = MonteCarloAtoms(atoms)
    print "Number of atoms:", len(atoms)
    atoms.set_calculator(MonteCarloEMT())
    atoms.get_potential_energies()  # Force creation of neighbor list.
    atoms2 = atoms.copy()
    atoms2.set_calculator(EMT())

    print 
    print "Testing perturbations of single atoms"

    pick1 = argsort(random.random((len(magnarr),)))
    for magn in take(magnarr, pick1):
        pick2 = argsort(random.random((len(numarr),)))
        for number in take(numarr, pick2):
            # Pick number random atoms.
            if number < 0:
                # Find N neighboring atoms and perturb them
                number = -number
Example #21
0
elif world.size == 3:
    cpulayout = [1,3,1]
elif world.size == 4:
    cpulayout = [1,2,2]

print_version(1)

if ismaster:
    atoms = FaceCenteredCubic(size=(2,10,10), symbol="Cu", pbc=False,
                              latticeconstant = 3.5)
else:
    atoms = None

if isparallel:
    atoms = MakeParallelAtoms(atoms, cpulayout)
atoms.set_calculator(asap3.EMT())
natoms = atoms.get_number_of_atoms()
    
ReportTest("Number of atoms", natoms, 800, 0)

# Make a small perturbation of the momenta
atoms.set_momenta(1e-6 * random.random([len(atoms), 3]))
print "Initializing ..."
predyn = VelocityVerlet(atoms, 0.5)
try:
    predyn.run(2500)
except:
    print atoms.arrays['positions']
    print atoms.arrays['momenta']
    print atoms.arrays['momenta'].shape
    print atoms.get_masses()
Example #22
0
            for j in range(3):
                if i != j and np.abs(uc[i,j]) > 1e-15:
                    diagonal = False  
        if not (self.allow_mi_opbc and atoms.get_pbc().all() and diagonal):
            # Minimum Image Orthogonal Periodic Boundary Conditions
            # are not allowed
            remove.extend(["MI_OPBC_H", "MI_OPBC_F"])
        if  atoms.get_pbc().any():
            # Cluster method is not allowed
            remove.append("CLUSTER")
        for rem in remove:
            if rem in allowed:
                allowed.remove(rem)
        if self.verbose:
            print "Allowed PBC:", allowed
        return allowed
    
if __name__ == '__main__':
    from ase.lattice.cubic import FaceCenteredCubic
    atoms = FaceCenteredCubic(size=(10,10,10), symbol='Cu')
    print "Creating calculator"
    pot = OpenKIMcalculator('EMT_Asap_Standard_AlAgAuCuNiPdPt__MO_118428466217_000')
    print "Setting atoms"
    atoms.set_calculator(pot)
    print "Calculating energy"
    print atoms.get_potential_energy()
    print atoms.get_forces()[10:]
    print atoms.get_stress()
    
    
    
Example #23
0
def main(element, T_up, T_low, T_expect, bulkmodulus, makepot):
    def set_temp_fric(dyn, atoms):
        z = atoms.get_positions()[:,2]
        zmax = atoms.get_cell()[2,2]
        zmin = 0
        T = T_low + (T_up - T_low) * (z - zmin) / (zmax - zmin)
        dyn.set_temperature(T * units.kB)

    rnd = world.sum(random.randint(0,2**32)) # Insures the same number on all nodes.
    prefix = "melt-%s-%s" % (element, hex(rnd)[2:])
    if master:
        print "Using output directory", prefix
        os.mkdir(prefix)
    else:
        while not os.path.exists(prefix):
            time.sleep(1)
    if master:
        atoms = FaceCenteredCubic(symbol=element, size=size, pbc=(True, True, False))
        atoms.center(vacuum=10.0, axis=2)
    else:
        atoms = None
    atoms = MakeParallelAtoms(atoms, cpulayout1)
    print world.rank, '-', len(atoms), atoms.get_number_of_atoms()
    atoms.set_calculator(makepot())
    #view(atoms)
    
    dyn = Langevin(atoms, 5*units.fs, 0.0, friction)
    logger = MDLogger(dyn, atoms, prefix+'/Melt-phase1.log', stress=True, peratom=True)
    dyn.attach(logger, interval=100)
    set_temp_fric(dyn, atoms)
    unstress = Inhomogeneous_NPTBerendsen(atoms, 50*units.fs, 0, taup=500*units.fs,
                                          compressibility=1/bulkmodulus)
    dyn.attach(unstress.scale_positions_and_cell, interval=10)
    #traj = PickleTrajectory("melting-phase1.traj", "w", atoms)
    fn1 = prefix + "/Melt-phase1.bundle" 
    if master:
        print "Opening file", fn1
    traj = BundleTrajectory(fn1, "w", atoms, split=True)
    dyn.attach(traj, interval=500)
    
    therm = Thermometer(atoms, prefix+"/TempProfile-phase1.dat")
    dyn.attach(therm.update, interval=500)
    
    for i in range(steps1 / 100):
        dyn.run(100)
        set_temp_fric(dyn, atoms)
    if master:
        print "Closing file", fn1
    traj.close()
    del traj, atoms
    
    # Reread the bundle
    atoms = BundleTrajectory(fn1).get_atoms(-1, cpulayout2)
    atoms.set_calculator(makepot())
    dyn = VelocityVerlet(atoms, 5*units.fs)
    logger = MDLogger(dyn, atoms, prefix+'/PtMelt-phase2.log', stress=True, peratom=True)
    dyn.attach(logger, interval=1000)
    unstress = Inhomogeneous_NPTBerendsen(atoms, 50*units.fs, 0,
                                          taup=5000*units.fs,
                                          compressibility=1/bulkmodulus)
    dyn.attach(unstress.scale_positions_and_cell, interval=10)
    fn2 = prefix + "/Melt-phase2.bundle" 
    if master:
        print "Opening file", fn2
    traj = BundleTrajectory(fn2, "w", atoms)
    dyn.attach(traj, interval=steps2/100)
    
    therm = Thermometer(atoms, prefix+"/TempProfile-phase2.dat")
    dyn.attach(therm.update, interval=steps2/10)
    
    dyn.run(steps2 - takedata)
    therm2 = AveragingThermometer(atoms)
    dyn.attach(therm2.update, interval=100)
    dyn.run(takedata)  # Run the last part
    T = therm2.get_temp()
    if master:
        print "Melting temperature:", T
    ReportTest("Melting temperature", T, T_expect, 3)
    if cleanup:
        world.barrier()
        # Cleanup may fail due to the directory not being updated from
        # writes on the other nodes.  Wait for NFS file system.
        time.sleep(60)
        if master:
            shutil.rmtree(prefix)
    world.barrier()
    ReportTest.Summary()    
Example #24
0
def pot():
    #return EMT2013(PtY_parameters)
    return EMT()


#set_verbose(1)
master = world.rank == 0

if master:
    atoms0 = FaceCenteredCubic(symbol='Pt', size=(15, 15, 30))
else:
    atoms0 = None

atoms0 = MakeParallelAtoms(atoms0, (1, 1, 2))
atoms0.set_calculator(pot())

print >> sys.stderr, "*********** FIRST FORCE CALCULATION ************"
print >> sys.stderr, "len(atoms) =", len(
    atoms0), "   no. atoms =", atoms0.get_number_of_atoms()
f0 = atoms0.get_forces()
perturbation = 0.01 * np.random.standard_normal(atoms0.get_positions().shape)
r = atoms0.get_positions() + perturbation
atoms0.set_positions(r)
print >> sys.stderr, "*********** SECOND FORCE CALCULATION ************"

f1 = atoms0.get_forces()

print >> sys.stderr, "*********** COPYING ATOMS **************"
atoms2 = ParallelAtoms((1, 1, 2), atoms0.comm, atoms0, distribute=False)
atoms2.set_calculator(pot())
Example #25
0
from hotbit import *
from ase.lattice.cubic import FaceCenteredCubic
import numpy as np
import pylab
from box.interpolation import interpolate_path

pi = np.pi

d = 4.08
atoms = FaceCenteredCubic('Au',
                          latticeconstant=d,
                          directions=((0, 1, 1), (1, 0, 1), (1, 1, 0)),
                          align=False)

calc = Hotbit(SCC=False, kpts=(8, 8, 8), txt='bs.cal')
atoms.set_calculator(calc)
atoms.get_potential_energy()

# reciprocal lattice vectors
V = atoms.get_volume()
a, b, c = atoms.get_cell()
a_ = 2 * pi / V * np.cross(b, c)
b_ = 2 * pi / V * np.cross(c, a)
c_ = 2 * pi / V * np.cross(a, b)

gamma = np.array((0, 0, 0))

# a path which connects the L-points and gamma-point
kpts, distances, label_points = interpolate_path(
    (-a_ / 2, a_ / 2, gamma, -b_ / 2, b_ / 2, gamma, -c_ / 2, c_ / 2, gamma,
     (-a_ - b_ - c_) / 2, (a_ + b_ + c_) / 2), 500)
Example #26
0
    def test_CuAg(self):
        a = FaceCenteredCubic('Cu', size=[2,2,2])
        calc = EAM('CuAg.eam.alloy')
        a.set_calculator(calc)
        FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        e_Cu = a.get_potential_energy()/len(a)

        a = FaceCenteredCubic('Ag', size=[2,2,2])
        a.set_calculator(calc)
        FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        e_Ag = a.get_potential_energy()/len(a)
        self.assertTrue(abs(e_Ag+2.85)<1e-6)

        a = L1_2(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        e = a.get_potential_energy()
        syms = np.array(a.get_chemical_symbols())
        self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu-
                               (syms=='Ag').sum()*e_Ag)/len(a)-0.096)<0.0005)

        a = B1(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        e = a.get_potential_energy()
        syms = np.array(a.get_chemical_symbols())
        self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu-
                               (syms=='Ag').sum()*e_Ag)/len(a)-0.516)<0.0005)

        a = B2(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        e = a.get_potential_energy()
        syms = np.array(a.get_chemical_symbols())
        self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu-
                               (syms=='Ag').sum()*e_Ag)/len(a)-0.177)<0.0003)

        a = L1_2(['Cu', 'Ag'], size=[2,2,2], latticeconstant=4.0)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001)
        e = a.get_potential_energy()
        syms = np.array(a.get_chemical_symbols())
        self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu-
                               (syms=='Ag').sum()*e_Ag)/len(a)-0.083)<0.0005)
Example #27
0
        a.set_cell(newcell, scale_atoms=True)
        #if len(v) > 1:
        #    print "fmin: %.4f  %7.4f  %8.4f  %8.4f" % (v[0], v[1], a.get_positions()[1792,2], a.get_potential_energy())
        return a.get_potential_energy()
    xopt, fopt, iter, calls, flag = fmin(energy, var, delta=0.01, full_output=True, disp=False)
    #print "Minimize unit cell:", xopt, fopt, iter, calls

if __name__ == '__main__':
    from asap3 import EMT, units, EMThcpParameters
    from ase.lattice.cubic import FaceCenteredCubic
    from ase.lattice.hexagonal import HexagonalClosedPacked
    
    print "Calculating cubic constants for Cu"
    atoms = FaceCenteredCubic(size=(5,5,5), symbol='Cu', 
                              latticeconstant=3.59495722231)
    atoms.set_calculator(EMT())
    e = ElasticConstants(atoms, 'cubic')
    print np.array(e) / units.GPa
    
    print "Pretending that Cu is hexagonal"
    e = ElasticConstants(atoms, 'hexagonal', sanity=False)
    print np.array(e) / units.GPa
    
    print "Calculating elastic constants for Ru"
    atoms = HexagonalClosedPacked(size=(5,5,5), symbol='Ru',
                                  directions=[[1,-2,1,0], 
                                              [1,0,-1,0],
                                              [0,0,0,1]])
    atoms.set_calculator(EMT(EMThcpParameters()))
    e = ElasticConstants(atoms, 'hexagonal', minimize=True)
    print np.array(e) / units.GPa
Example #28
0
                                j in fnb[i], silent=True)
            ReportTest.BoolTest("Atom %d on list %d (reverse)" % (i, j),
                                i in fnb[j], silent=True)
        if ReportTest.GetNumberOfErrors() > 10:
            print "*** Too many errors - giving up! ***"
            break
    

print_version(1)

element = "Cu"
latconst = ase.data.reference_states[ase.data.atomic_numbers[element]]['a']

atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,1],[0,0,1]], size=(9,7,5),
                          symbol=element, debug=0)
atoms.set_calculator(EMT(minimum_image=True))
epot = atoms.get_potential_energy()

nblist = atoms.get_calculator().get_neighborlist()
count = {}
for lst in nblist:
    n = len(lst)
    try:
        count[n] += 1
    except KeyError:
        count[n] = 1
# print "Histogram:"
numbers = count.keys()
numbers.sort()
sum = 0
for i in numbers:
Example #29
0
 def test_mask_decomposition_lj_cut(self):
     a = FaceCenteredCubic('Au', size=[2,2,2])
     c = LJCut(el1='Au', el2='Au', epsilon=1.0, sigma=1.0, cutoff=6.0)
     a.set_calculator(c)
     self.random_mask_test(a)
elif str == "hcp":
    from math import sqrt

    a = lp
    b = sqrt(3.0) * lp
    c = lp * sqrt(8.0 / 3.0) * catoi
    # this did not work
    # maybe wrong setting of LAMMPS volume optimization for triclinic cell
    # from ase.lattice.hexagonal import HexagonalClosedPacked
    # atoms = HexagonalClosedPacked(symbol=el1,latticeconstant=(lp,c),size=(5,5,5))
    atoms = HCPO(symbol=el1, latticeconstant=(a, b, c), size=(8, 4, 4))

else:
    raise RuntimeError, 'unknown structure "' + str + '"'

atoms.set_calculator(calc)

print "el:", el1, "str:", str, "lp:", lp
if str == "hcp":
    print "catoi:", catoi

v1 = atoms.get_volume()
print "v1:", v1
n1 = atoms.get_number_of_atoms()
print "n1:", n1
v1pa = v1 / n1
print "v1pa:", v1pa

# initial
ene0 = atoms.get_potential_energy()
print "ene0:", ene0
Example #31
0
 def test_mask_decomposition_tabulated_alloy_eam(self):
     a = FaceCenteredCubic('Au', size=[2,2,2])
     c = TabulatedAlloyEAM(fn='Au-Grochola-JCP05.eam.alloy')
     a.set_calculator(c)
     self.random_mask_test(a)
Example #32
0
if len(sys.argv) == 2:
    arg = sys.argv[1]
else:
    arg = 'Wrong number of arguments.'
if arg == 'EMT':
    filename = 'small_EMT.dat'
elif arg == 'EMT2013':
    filename = 'small_EMT2013.dat'
else:
    print __doc__
    sys.exit(1)

    
T = 450
atoms = FaceCenteredCubic(size=(10,10,10), symbol='Cu', pbc=False)
if arg == 'EMT':
    atoms.set_calculator(EMT())
else:
    atoms.set_calculator(EMT2013(EMT2013_parameters))
    
print "Setting temperature:", T, "K"
MaxwellBoltzmannDistribution(atoms, 2*T*units.kB)
Stationary(atoms)

dyn1 = Langevin(atoms, 2*units.fs, temperature=T*units.kB, friction=0.05)
dyn1.run(200)

dyn = VelocityVerlet(atoms, 3*units.fs, logfile=filename, loginterval=25)
dyn.run(10000000) # 10^7 timesteps is 3 ns.

Example #33
0
# Attach VASP calculation to Optimize Nuclei position
''' 
    From the calculation, the lattice constants can be obtained,
    and the constants are used to creat Surface_Au in the next
    step.
'''
from ase.calculators.vasp import Vasp

calc = Vasp(
    xc='PBE',  #Level of theory (density functional)
    encut=
    520,  #plane-wave kinetic energy cutoff (convergence test; I usually use about 520)
    kpts=[
        10, 10, 10
    ],  #number of k-points, e.g. [3,3,3] (convergence test; fewer kpoints are needed if lattice dimension is large)
    isif=3,  #relaxation method (2 = positions, 3 = positions+volume)
    prec='Accurate',  #accuracy (don't change this)
    sigma=0.01,  #don't need to change (smearing width)
    ismear=0,  #don't need to change (smearing method)
    isym=0,  #disables symmetry
    ediffg=
    -0.03,  #force tolerance, |ediffg| (eV/A) (I generally use 0.01 --> 0.03; lower is better but will take longer)
    nsw=1000,  #maximum number of steps
    #ivdw=12, #enable van der Waals interactions
    ibrion=2
)  #geom opt algorithm (dont need change; default is conjugate gradient -- works fine)

Bulk_Au.set_calculator(calc)

Bulk_Au.get_potential_energy()