def get_energies(model, symbol, lattice, q):
    calc = KIMCalculator(str(model))
    
    slab = bulk(str(symbol), str(lattice), a=1)
    #slab = slab.repeat((6,6,6))
    cell = slab.get_cell()
    positions = slab.get_positions()
    slab.set_calculator(calc)
    lattice_constant = 6

    aopt_arr, eopt, iterations, funccalls, warnflag = \
            opt.fmin(energy, lattice_constant, args=(slab,cell,positions),
                    full_output=True, disp=False, xtol=1e-12, maxfun=100)
    lattice_constant = aopt_arr
    cohesive_energy = -eopt/len(slab)
    dx = 1e-6*lattice_constant
    d2v = (energy(lattice_constant - dx, slab, cell, positions) -
            2*energy(lattice_constant, slab, cell, positions) +
            energy(lattice_constant + dx, slab, cell, positions)) / (dx*dx)

    l = np.sqrt( cohesive_energy / d2v )

    list_a = np.linspace(lattice_constant/2.0, lattice_constant*2., 101)
    list_E = np.array([energy(ta, slab, cell, positions) for ta in list_a])

    astar = (list_a - lattice_constant) / l
    Estar = list_E / cohesive_energy

    #return (astar, Estar)
    q.put((astar,Estar))
Example #2
0
def vasp_vol_relax():
    Al = bulk('Al', 'fcc', a=4.5, cubic=True)
    calc = Vasp(xc='LDA',
                isif=7,
                nsw=5,
                ibrion=1,
                ediffg=-1e-3,
                lwave=False,
                lcharg=False)
    calc.calculate(Al)

    # Explicitly parse atomic position output file from Vasp
    CONTCAR_Al = io.read('CONTCAR', format='vasp')

    print 'Stress after relaxation:\n', calc.read_stress()

    print 'Al cell post relaxation from calc:\n', calc.get_atoms().get_cell()
    print 'Al cell post relaxation from atoms:\n', Al.get_cell()
    print 'Al cell post relaxation from CONTCAR:\n', CONTCAR_Al.get_cell()

    # All the cells should be the same.
    assert (calc.get_atoms().get_cell() == CONTCAR_Al.get_cell()).all()
    assert (Al.get_cell() == CONTCAR_Al.get_cell()).all()

    return Al
    def create_slab(self):
	# Request the FCCLattice constant
	a = request(self.potentialname, self.element, 'FCCLattice', 'FCCLatticeConstant' )

	slab = bulk(self.element,a=a,crystalstructure='fcc',cubic=True)
	if self.potentialname == 'ASAP':
	    slab = slab.repeat((8,8,8))

	return slab
def calcEnergy(a, calc):
    
    atoms = bulk(symbol,lattice,a=a)
    atoms.set_calculator(calc)
    try:
        energy = atoms.get_potential_energy()
    except:
        energy = 1e10
    
    return energy
def get_energy(x):
    "Function to create an atoms object with lattice parameters specified by x and obtain its energy using calc."
    global iter
    iter += 1
    a = x[0]
    atoms = bulk(symbols[0], crystalstructure='fcc', a=x)
    atoms_list.append(atoms)
    atoms.set_calculator(calc)
    write('out.traj', atoms_list)
    energy = atoms.get_potential_energy()
    with paropen('lattice_opt.log', 'a') as logfile:
        logfile.write('%s\\t%s\\n' % (energy, x))
    return energy
Example #6
0
def test_asap():
	""" Do an ASAP default run """	
	logging.info("\nInside test_asap TEST")
	logging.info("Creating a slab of Cu")
	slab = bulk('Cu','fcc',cubic=True).repeat((5,5,5))

	logging.info("loading the ASAP calculator")
	slab.set_calculator(potential.load('ASAP'))

	logging.info("Getting the potential energy")
	energy = slab.get_potential_energy()
	logging.info("Obtained: {}".format(energy))
	logging.info("Leaving test_asap TEST\n")
Example #7
0
def Qtest_gpaw():
	""" Do a GPAW default run """	
	logging.info("\nInside test_gpaw TEST")
	logging.info("Creating a slab of Cu")
	slab = bulk('Cu','fcc',cubic=True)

	logging.info("loading the GPAW calculator")
	slab.set_calculator(potential.load('GPAW'))

	logging.info("Getting the potential energy")
	energy = slab.get_potential_energy()
	logging.info("Obtained: {}".format(energy))
	logging.info("Leaving test_GPAW TEST\n")
Example #8
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
def sweepSurfaces(calc):

    surfaceEnergyDict = {}
    energies=[]
    skipped_indices=[]
    indices_calculated=[]
    file = open('IndexList.pkl','r')
    list_of_indices = pickle.load(file)
    file.close()
    # list of indices for testing
    list_of_indices = [[1,0,0],[1,1,1],[1,2,1],[1,1,0],[1,8,9]]
    latticeconstant = findLatticeConstant(calc)
    atoms = bulk(symbol,lattice,a=latticeconstant)
    atoms.set_calculator(calc)
    unit_e_bulk = atoms.get_potential_energy()/atoms.get_number_of_atoms()
    
    # testing time for the calculation of 1 surface
    # start an alarm
    signal.signal(signal.SIGALRM, handler1)
    signal.alarm(TIME_CUTOFF)
    start_time = time.time()
    if lattice == 'fcc':
        miller = [1,1,1]
    elif lattice == 'bcc':
        miller = [1,0,0]
    else:
        miller = [1,0,0]
    #E_unrelaxed, E_relaxed = getSurfaceEnergy(miller, calc, unit_e_bulk, latticeconstant)
    signal.alarm(0)
    end_time = time.time()
    calcTime = end_time - start_time

    counter = 0
    signal.signal(signal.SIGALRM, handler2)
    for miller in list_of_indices:
        signal.alarm(TIME_CUTOFF)
        try:
            print miller
            E_unrelaxed, E_relaxed = getSurfaceEnergy(miller, calc, unit_e_bulk, latticeconstant)
            surfaceEnergyDict['Surface Energy ' +str(miller)] = E_relaxed
            energies.append(E_relaxed) 
            indices_calculated.append(miller)
        except TimeoutException:
            skipped_indices.append(miller)
            print "surface took too long, skipping", miller
        except:
            raise
        signal.alarm(0)
    return indices_calculated, np.array(energies), surfaceEnergyDict, calcTime 
Example #10
0
    def BCCEnergy(self,a):
        """This function computes the energy of the crystal formation given 
        a certain lattice constant
        
        It uses the ase helper function bulk to create a 1 atom periodic boundary
        condition crystal with a specific structure"""
        self.slab = bulk(self.element,'bcc',a=a)
        if self.potentialname.lower() == 'asap':
            self.slab = self.slab.repeat((10,10,10))

        #set the calculator
        self.slab.set_calculator(self.calculator)
        
        #calculate and return the potential energy
        return self.slab.get_potential_energy()        
Example #11
0
    def results(self):
	a = request(self.potentialname,self.element,'FCCLattice','FCCLatticeConstant')
	self.slab = bulk(self.element,'fcc',a=a,cubic=True)
	
	#repeat the cell 8 times
	self.slab = self.slab.repeat((8,8,8))

	self.slab.set_calculator(self.calculator)
	
	energy1 = self.slab.get_potential_energy()
	volume1 = self.slab.get_volume()
	Natoms1 = len(self.slab)

	#remove an atom
	del self.slab[0]
	
	#attach calculator again
	self.slab.set_calculator(self.calculator)
	
	energy2 = self.slab.get_potential_energy()
	volume2 = self.slab.get_volume()
	Natoms2 = len(self.slab)

	#relax the crystal using FIRE
	dyn = FIRE(self.slab)
	dyn.run(fmax=0.01)

	energy3 = self.slab.get_potential_energy()
	volume3 = self.slab.get_volume()
	Natoms3 = len(self.slab)

	vacancy_formation_energy = energy3 - (Natoms1 - 1.)/(1.*Natoms1) * energy1

	results_dict = { 'VacancyFormationEnergy' : vacancy_formation_energy,
			 'NAtoms': Natoms1 }

	return results_dict	
def findLatticeConstant(calc):
    """
    temporary copy of Alex's LatticeConstantCubicEnergy Test
    in the future we want to look up the result of this as input to the test
    """
    
    XTOL = 1e-8    

    nn_dist_lookup = {"sc": 1.,
        "fcc" : 1./np.sqrt(2),
        "bcc": np.sqrt(3)/2.,
        "diamond": np.sqrt(3)/4. }

    nn_dist = nn_dist_lookup[lattice]
    
    atoms = bulk(symbol,lattice,a=100)
    atoms.set_calculator(calc)
    cutoff = KIM_API_get_data_double(calc.pkim,"cutoff")[0]

    min_a = (cutoff/30.0)/nn_dist
    max_a = cutoff/nn_dist

    aopt, eopt, ier, funccalls = opt.fminbound(calcEnergy, min_a, max_a, args= (calc,),full_output = True, xtol=XTOL)

    #results = opt.fmin(calcEnergy, cutoff/2.0, args=(calc,))[0]
    
    hit_bound = False
    if np.allclose(aopt,min_a,atol=2*XTOL):
        hit_bound = True    
    elif np.allclose(aopt,max_a,atol=2*XTOL):
        hit_bound = True

    if hit_bound:
        raise Exception("Lattice constant computation hit bounds")    

    return aopt
Example #13
0
# creates: a1.png a2.png a3.png cnt1.png cnt2.png gnr1.png gnr2.png
from ase.io import write
from ase.structure import bulk, nanotube, graphene_nanoribbon
import numpy as np

for i, a in enumerate([
    bulk('Cu', 'fcc', a=3.6),
    bulk('Cu', 'fcc', a=3.6, orthorhombic=True),
    bulk('Cu', 'fcc', a=3.6, cubic=True)]):
    write('a%d.pov' % (i + 1), a,
          show_unit_cell=2, display=False, run_povray=True)

cnt1 = nanotube(6, 0, length=4)
cnt1.rotate('x', 'z', rotate_cell=True)
cnt2 = nanotube(3, 3, length=6, bond=1.4, symbol='Si')
cnt2.rotate('x', 'z', rotate_cell=True)

for i, a in enumerate([cnt1, cnt2]):
    write('cnt%d.pov' % (i + 1), a,
          show_unit_cell=2, display=False, run_povray=True)

ind = [2, 0, 1]
gnr1 = graphene_nanoribbon(3, 4, type='armchair')
gnr1.set_cell(np.diag(gnr1.cell)[ind])
gnr1.positions = gnr1.positions[:, ind]
gnr2 = graphene_nanoribbon(2, 6, type='zigzag', saturated=True,
                           C_H=1.1, C_C=1.4, vacuum=3.0, 
                           magnetic=True, initial_mag=1.12)
gnr2.set_cell(np.diag(gnr2.cell)[ind])
gnr2.positions = gnr2.positions[:, ind]
Example #14
0
File: hcp.py Project: slabanja/ase
    raise NotAvailable('This test needs scipy module.')

import numpy as np
from ase.io import read, PickleTrajectory
from ase.structure import bulk
from ase.calculators.emt import EMT

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 = PickleTrajectory('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)

    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]
    from ase.optimize import polyfit
    p = polyfit(ac, energies)
    from scipy.optimize import fmin_bfgs
    a0, c0 = fmin_bfgs(p, (a0, c0))
    print '%.4f %.3f' % (a0, c0 / a0)
assert abs(a0 - 2.469) < 0.001
assert abs(c0 / a0 - 1.624) < 0.005
Example #15
0
relax_fmax = 0.025 * units.eV / units.Ang  # Maximum force criteria for relaxation

param_file = 'params.xml'  # XML file containing interatomic potential parameters
mm_init_args = 'IP SW'  # Initialisation arguments for the classical potential

output_file = 'crack.xyz'  # File to which structure will be written

# ******* End of parameters *************

set_fortran_indexing(False)

# ********** Build unit cell ************

# 8-atom diamond cubic unit cell for silicon, with guess at lattice
# constant of 5.44 A
si_bulk = bulk('Si', 'diamond', a=5.44, cubic=True)

# ********** Setup potential ************

# Stillinger-Weber (SW) classical interatomic potential, from QUIP
mm_pot = Potential(mm_init_args, param_filename=param_file)

# ***** Find eqm. lattice constant ******

# find the equilibrium lattice constant by minimising atoms wrt virial
# tensor given by SW pot (possibly replace this with parabola fit in
# another script and hardcoded a0 here)
si_bulk.set_calculator(mm_pot)

print('Minimising bulk unit cell...')
minim = Minim(si_bulk, relax_positions=True, relax_cell=True)
Example #16
0
    'PourierTarantola',
    'Vinet',
    'AntonSchmidt',
    ]

# AntonSchmidt fails with ASE3!
# RuntimeError: Optimal parameters not found:
# Number of calls to function has reached maxfev = 1000.
eos_strl3 = [m for m in eos_strl]
eos_strl3.remove('AntonSchmidt')

results = {}

# prepare energies and volumes

b = bulk('Al', 'fcc', a=4.0, orthorhombic=True)
b.set_calculator(EMT())
cell = b.get_cell()

volumes = []
energies = []
traj = PickleTrajectory('eos.traj', 'w')
for x in np.linspace(0.97, 1.03, 5):
    b.set_cell(cell * x, scale_atoms=True)
    volumes.append(b.get_volume())
    energies.append(b.get_potential_energy())
    traj.write(b)

for n, (v, e) in enumerate(zip(volumes, energies)):
    vref = ref['volumes'][n]
    eref = ref['energies'][n]
Example #17
0
# creates: Al_phonon.png Al_mode.gif Al_mode.pdf

from ase.structure import bulk
from ase.calculators.emt import EMT
from ase.dft.kpoints import ibz_points, get_bandpath
from ase.phonons import Phonons

# Setup crystal and EMT calculator
atoms = bulk('Al', 'fcc', a=4.05)
calc = EMT()

# Phonon calculator
N = 6
ph = Phonons(atoms, calc, supercell=(N, N, N))
ph.run()

# Read forces and assemble the dynamical matrix
ph.read(acoustic=True)

# High-symmetry points in the Brillouin zone
points = ibz_points['fcc']
G = points['Gamma']
X = points['X']
W = points['W']
K = points['K']
L = points['L']
U = points['U']

point_names = ['$\Gamma$', 'X', 'U', 'L', '$\Gamma$', 'K']
path = [G, X, U, L, G, K]
Example #18
0
"""This calculation has the following structure.
1) Calculate the ground state of Diamond.
2) Calculate the band structure of diamond in order to obtain accurate KS band gap for Diamond.
3) Calculate ground state again, and calculate the potential discontinuity using accurate band gap.
4) Calculate band structure again, and apply the discontinuity to CBM.

Compare to reference.
"""

xc = 'GLLBSC'
gen('C',xcname=xc)
setup_paths.insert(0, '.')

# Calculate ground state
atoms = bulk('C', 'diamond', a=3.567)
calc = GPAW(h=0.15, kpts=(4,4,4), xc=xc, nbands = 6, eigensolver='cg')
atoms.set_calculator(calc)
atoms.get_potential_energy()
calc.write('Cgs.gpw')

# Calculate accurate KS-band gap from band structure
points = ibz_points['fcc']

# CMB is in G-X
G = points['Gamma']
X = points['X']

#W = points['W']
#K = points['K']
#L = points['L']
Example #19
0
from ase.dft import monkhorst_pack

assert [0, 0, 0] in  monkhorst_pack((1, 3, 5)).tolist()
assert [0, 0, 0] not in  monkhorst_pack((1, 3, 6)).tolist()
assert len(monkhorst_pack((3, 4, 6))) == 3 * 4 * 6

from ase.units import Hartree, Bohr, kJ, mol, kcal, kB, fs
print Hartree, Bohr, kJ/mol, kcal/mol, kB*300, fs, 1/fs

from ase.structure import bulk
ru = bulk('Ru', 'hcp', a=2.7) * (2, 2, 1)
assert abs(ru.get_distance(0, 7, mic=True) - ru.get_distance(1, 6)) < 1e-14
assert abs(ru.get_distance(0, 5, mic=True) - 2.7) < 1e-14
import numpy as np
from ase.structure import bulk
from gpaw import GPAW
from gpaw.response.df import DF

# Part 1: Ground state calculation
atoms = bulk('Si', 'diamond', a=5.431)   # Generate diamond crystal structure for silicon
calc = GPAW(h=0.20, kpts=(4,4,4))        # GPAW calculator initialization
 
atoms.set_calculator(calc)               
atoms.get_potential_energy()             # Ground state calculation is performed
calc.write('si.gpw','all')               # Use 'all' option to write wavefunction

# Part 2 : Spectrum calculation          # DF: dielectric function object
df = DF(calc='si.gpw',                   # Ground state gpw file (with wavefunction) as input
        q=np.array([0.0, 0.00001, 0.0]), # Momentum transfer, here excites in y-direction
        w=np.linspace(0,14,141),         # The Energies (eV) for spectrum: from 0-14 eV with 0.1 eV spacing
        optical_limit=True)              # Indicates that its a optical spectrum calculation

df.get_absorption_spectrum()             # By default, a file called 'Absorption.dat' is generated
Example #21
0
from gpaw.mpi import serial_comm, rank, size
from gpaw.utilities import devnull
from gpaw.response.df import DF


if rank != 0:
    sys.stdout = devnull

GS = 1
ABS = 1

if GS:

    # Ground state calculation
    a = 5.431  # 10.16 * Bohr
    atoms = bulk("Si", "diamond", a=a)

    calc = GPAW(
        h=0.20,
        kpts=(12, 12, 12),
        xc="LDA",
        basis="dzp",
        txt="si_gs.txt",
        nbands=80,
        eigensolver="cg",
        occupations=FermiDirac(0.001),
        convergence={"bands": 70},
    )
    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    calc.write("si.gpw", "all")
Example #22
0
import numpy as np
from ase.structure import bulk
from gpaw import FermiDirac, MethfesselPaxton, MixerSum
from gpaw.utilities.bulk2 import GPAWRunner

strains = np.linspace(0.98, 1.02, 9)
a0 = 2.84
atoms = bulk('Fe', 'bcc', a0)
atoms.set_initial_magnetic_moments([2.3])


def f(name, dist, k, g):
    tag = '%s-%02d-%2d' % (name, k, g)
    r = GPAWRunner('Fe', atoms, strains, tag=tag)
    r.set_parameters(xc='PBE',
                     occupations=dist,
                     basis='dzp',
                     nbands=9,
                     kpts=(k, k, k),
                     gpts=(g, g, g))
    r.run()


for width in [0.05, 0.1, 0.15, 0.2]:
    for k in [2, 4, 6, 8, 10, 12]:
        f('FD-%.2f' % width, FermiDirac(width), k, 12)
        f('MP-%.2f' % width, MethfesselPaxton(width), k, 12)
for g in range(8, 32, 4):
    f('FD-%.2f' % 0.1, FermiDirac(0.1), 8, g)
Example #23
0
def diamond2(symbol, a):
    return bulk(symbol, 'diamond', a=a)
Example #24
0
File: iron.py Project: qsnake/gpaw
import numpy as np
from ase.structure import bulk
from gpaw import FermiDirac, MethfesselPaxton, MixerSum
from gpaw.utilities.bulk2 import GPAWRunner

strains = np.linspace(0.98, 1.02, 9)
a0 = 2.84
atoms = bulk('Fe', 'bcc', a0)
atoms.set_initial_magnetic_moments([2.3])
def f(name, dist, k, g):
    tag = '%s-%02d-%2d' % (name, k, g)
    r = GPAWRunner('Fe', atoms, strains, tag=tag)
    r.set_parameters(xc='PBE',
                     occupations=dist,
                     basis='dzp',
                     nbands=9,
                     kpts=(k, k, k),
                     gpts=(g, g, g))
    r.run()

for width in [0.05, 0.1, 0.15, 0.2]:
    for k in [2, 4, 6, 8, 10, 12]:
        f('FD-%.2f' % width, FermiDirac(width), k, 12)
        f('MP-%.2f' % width, MethfesselPaxton(width), k, 12)
for g in range(8, 32, 4):
    f('FD-%.2f' % 0.1, FermiDirac(0.1), 8, g)
Example #25
0
import os
"""This calculation has the following structure.
1) Calculate the ground state of Diamond.
2) Calculate the band structure of diamond in order to obtain accurate KS band gap for Diamond.
3) Calculate ground state again, and calculate the potential discontinuity using accurate band gap.
4) Calculate band structure again, and apply the discontinuity to CBM.

Compare to reference.
"""

xc = 'GLLBSC'
gen('C', xcname=xc)
setup_paths.insert(0, '.')

# Calculate ground state
atoms = bulk('C', 'diamond', a=3.567)
calc = GPAW(h=0.15, kpts=(4, 4, 4), xc=xc, nbands=6, eigensolver='cg')
atoms.set_calculator(calc)
atoms.get_potential_energy()
calc.write('Cgs.gpw')

# Calculate accurate KS-band gap from band structure
points = ibz_points['fcc']

# CMB is in G-X
G = points['Gamma']
X = points['X']

#W = points['W']
#K = points['K']
#L = points['L']
Example #26
0
import numpy as np
from ase.structure import bulk
from gpaw import GPAW
from gpaw.response.df import DF

# Part 1: Ground state calculation
atoms = bulk('Al', 'fcc', a=4.043)  # Generate fcc crystal structure for aluminum
calc = GPAW(h=0.2, kpts=(4,4,4))    # GPAW calculator initialization

atoms.set_calculator(calc)
atoms.get_potential_energy()        # Ground state calculation is performed
calc.write('Al.gpw','all')          # Use 'all' option to write wavefunctions

# Part 2: Spectrum calculation      # DF: dielectric function object
df = DF(calc='Al.gpw',              # Ground state gpw file as input
        q=np.array([1./4., 0, 0]),  # Momentum transfer, must be the difference between two kpoints !
        w=np.linspace(0, 24, 241))  # The Energies (eV) for spectrum: from 0-24 eV with 0.1 eV spacing

df.get_EELS_spectrum()              # By default, a file called 'EELS.dat' is generated
Example #27
0
from ase import Atom, Atoms
from ase.structure import bulk
from ase.units import Hartree, Bohr
from gpaw import GPAW, FermiDirac
from gpaw.response.bse import BSE


GS = 1
bse = 1
df = 1
check_spectrum = 1

if GS:

    a = 6.75 * Bohr
    atoms = bulk('C', 'diamond', a=a)

    calc = GPAW(h=0.2,
                kpts=(2,2,2),
                occupations=FermiDirac(0.001),
                nbands=8,
                convergence={'band':'all'})

    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    calc.write('C_kpt8.gpw','all')

if bse:
    
    bse = BSE('C_kpt8.gpw',w=np.linspace(0,20,201),
              q=np.array([0,0,0.5]),optical_limit=True,ecut=50.,
Example #28
0
from ase.structure import bulk
from gpaw import GPAW
si = bulk('Si', 'diamond', a=5.5, cubic=not True)
si.set_calculator(GPAW(setups='ah', kpts=(2, 2, 2)))
si.get_potential_energy()
si.calc.write('Si.gpw', 'all')
GPAW('Si.gpw')
Example #29
0
import numpy as np
from ase.units import Bohr, Hartree
from ase.structure import bulk
from gpaw import GPAW
from gpaw.response.df import DF
from gpaw.response.bse import BSE

GS = 1
df = 1
bse = 1
check_spectrum = 1

if GS:
    a = 4.043
    atoms = bulk('Al', 'fcc', a=a)
    atoms.center()
    calc = GPAW(h=0.2,
                kpts=(4,2,2),
                xc='LDA',
                nbands=4,
                convergence={'band':'all'})
    
    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    calc.write('Al.gpw','all')

if bse:
    
    bse = BSE('Al.gpw',w=np.linspace(0,24,241),
              q=np.array([0.25, 0, 0]),ecut=50., eta=0.2)
def energy(a, calc):
    atoms = bulk(symbol, 'fcc', a=a)
    atoms.set_calculator(calc)
    return atoms.get_potential_energy()
Example #31
0
""" This will serve as a test of using ASE
to drive LAMMPS
to drive KIM
"""

import ase
from ase.structure import bulk
from bin.lammps import LAMMPS

el1 = 'Cu'
slab = bulk(el1,'fcc',a=3.1)
slab = slab.repeat((5,5,5))


pair_style = "meam"
meamf = "meamf"
meamp = "meam.alsimgcufe"
subspec = [ el1 ]
pair_coeff = [ "* * meamf AlS SiS MgS CuS FeS "\
                   + meamp + " " + subspec[0] + "S " ]
parameters = { "pair_style" : pair_style, "pair_coeff" : pair_coeff }
files = [ meamf, meamp ]


calc = LAMMPS(parameters=parameters, specorder=subspec, tmp_dir = 'tmp',
              keep_tmp_files=True, keep_alive=False,files=files)

slab.set_calculator(calc)

print slab.get_potential_energy()
Example #32
0
from numpy import linspace

from ase.calculators.fleur import FLEUR
from ase.structure import bulk
from ase.io.trajectory import PickleTrajectory

atoms = bulk('Ni', 'fcc', a=3.52)
calc = FLEUR(xc='PBE', kmax=3.6, kpts=(10, 10, 10), workdir='lat_const')
atoms.set_calculator(calc)
traj = PickleTrajectory('Ni.traj','w', atoms)
cell0 = atoms.get_cell()
for s in linspace(0.95, 1.05, 7):
    cell = cell0 * s
    atoms.set_cell((cell))
    ene = atoms.get_potential_energy()
    traj.write()

Example #33
0
from gpaw import GPAW
from ase.structure import bulk
from ase.dft.kpoints import ibz_points, get_bandpath
import numpy as np

si = bulk('Si', 'diamond', a=5.459)

if 1:
    k = 6
    calc = GPAW(kpts=(k, k, k),
                xc='PBE')
    si.set_calculator(calc)
    e = si.get_potential_energy()
    efermi = calc.get_fermi_level()
    calc.write('Si-gs.gpw')
else:
    efermi = GPAW('Si-gs.gpw', txt=None).get_fermi_level()

points = ibz_points['fcc']
G = points['Gamma']
X = points['X']
W = points['W']
K = points['K']
L = points['L']
kpts, x, X = get_bandpath([W, L, G, X, W, K], si.cell)
print len(kpts), len(x), len(X)
point_names = ['W', 'L', '\Gamma', 'X', 'W', 'K']

if 1:
    calc = GPAW('Si-gs.gpw',
                kpts=kpts,
Example #34
0
# creates: a1.png a2.png a3.png cnt1.png cnt2.png gnr1.png gnr2.png
from ase.io import write
from ase.structure import bulk, nanotube, graphene_nanoribbon
import numpy as np

for i, a in enumerate([
        bulk('Cu', 'fcc', a=3.6),
        bulk('Cu', 'fcc', a=3.6, orthorhombic=True),
        bulk('Cu', 'fcc', a=3.6, cubic=True)
]):
    write('a%d.pov' % (i + 1),
          a,
          show_unit_cell=2,
          display=False,
          run_povray=True)

cnt1 = nanotube(6, 0, length=4)
cnt1.rotate('x', 'z', rotate_cell=True)
cnt2 = nanotube(3, 3, length=6, bond=1.4, symbol='Si')
cnt2.rotate('x', 'z', rotate_cell=True)

for i, a in enumerate([cnt1, cnt2]):
    write('cnt%d.pov' % (i + 1),
          a,
          show_unit_cell=2,
          display=False,
          run_povray=True)

ind = [2, 0, 1]
gnr1 = graphene_nanoribbon(3, 4, type='armchair')
gnr1.set_cell(np.diag(gnr1.cell)[ind])
Example #35
0
from gpaw import GPAW, FermiDirac
from gpaw.mpi import serial_comm, rank, size
from gpaw.utilities import devnull
from gpaw.response.df import DF

if rank != 0:
    sys.stdout = devnull

GS = 1
ABS = 1

if GS:

    # Ground state calculation
    a = 5.431  #10.16 * Bohr
    atoms = bulk('Si', 'diamond', a=a)

    calc = GPAW(h=0.20,
                kpts=(12, 12, 12),
                xc='LDA',
                basis='dzp',
                txt='si_gs.txt',
                nbands=80,
                eigensolver='cg',
                occupations=FermiDirac(0.001),
                convergence={'bands': 70})
    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    calc.write('si.gpw', 'all')

if ABS:
Example #36
0
"""This test checks that the StrainFilter works using the default
built-in EMT calculator."""

from ase.constraints import StrainFilter
from ase.optimize.mdmin import MDMin
from ase.calculators.emt import EMT
from ase.structure import bulk

cu = bulk("Cu", "fcc", a=3.6)

cu.set_calculator(EMT(fakestress=True))
f = StrainFilter(cu)
opt = MDMin(f, dt=0.01)
opt.run(0.1, steps=2)
def energy(a, calc):
    atoms = bulk(symbol, 'fcc', a=a)
    atoms.set_calculator(calc)
    return atoms.get_potential_energy()
Example #38
0
import numpy as np
from ase.structure import bulk
from gpaw import GPAW
from gpaw.response.df import DF

# Part 1: Ground state calculation
atoms = bulk('Al', 'fcc',
             a=4.043)  # Generate fcc crystal structure for aluminum
calc = GPAW(h=0.2, kpts=(4, 4, 4))  # GPAW calculator initialization

atoms.set_calculator(calc)
atoms.get_potential_energy()  # Ground state calculation is performed
calc.write('Al.gpw', 'all')  # Use 'all' option to write wavefunctions

# Part 2: Spectrum calculation      # DF: dielectric function object
df = DF(
    calc='Al.gpw',  # Ground state gpw file as input
    q=np.array([
        1. / 4., 0, 0
    ]),  # Momentum transfer, must be the difference between two kpoints !
    w=np.linspace(0, 24, 241)
)  # The Energies (eV) for spectrum: from 0-24 eV with 0.1 eV spacing

df.get_EELS_spectrum()  # By default, a file called 'EELS.dat' is generated
Example #39
0
"""This test checks that the StrainFilter works using the default
built-in EMT calculator."""

from ase.constraints import StrainFilter
from ase.optimize.mdmin import MDMin
from ase.calculators.emt import EMT
from ase.structure import bulk

cu = bulk('Cu', 'fcc', a=3.6)

cu.set_calculator(EMT(fakestress=True))
f = StrainFilter(cu)
opt = MDMin(f, dt=0.01)
opt.run(0.1, steps=2)
Example #40
0
from gpaw.atom.basis import BasisMaker
from gpaw.response.df import DF
from gpaw.mpi import serial_comm, rank, size
from gpaw.utilities import devnull

if rank != 0:
    sys.stdout = devnull

assert size <= 4**3

# Ground state calculation

t1 = time.time()

a = 4.043
atoms = bulk('Al', 'fcc', a=a)
atoms.center()
calc = GPAW(
    h=0.2,
    kpts=(4, 4, 4),
    parallel={
        'domain': 1,
        'band': 1
    },
    idiotproof=False,  # allow uneven distribution of k-points
    xc='LDA')

atoms.set_calculator(calc)
atoms.get_potential_energy()
#calc.write('Al.gpw','all')
t2 = time.time()
Example #41
0
from gpaw.mpi import serial_comm, rank, size
from gpaw.utilities import devnull
from gpaw.response.df import DF


if rank != 0:
    sys.stdout = devnull 

GS = 1
ABS = 1

if GS:

    # Ground state calculation
    a = 5.431 #10.16 * Bohr 
    atoms = bulk('Si', 'diamond', a=a)

    calc = GPAW(h=0.20,
            kpts=(12,12,12),
            xc='LDA',
            basis='dzp',
            txt='si_gs.txt',
            nbands=80,
            eigensolver='cg',
            occupations=FermiDirac(0.001),
            convergence={'bands':70})
    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    calc.write('si.gpw','all')

Example #42
0
"""This test checks that the StrainFilter works using the default
built-in EMT calculator."""

import numpy as np
from ase.constraints import StrainFilter
from ase.optimize.mdmin import MDMin
from ase.calculators.emt import EMT
from ase.structure import bulk

cu = bulk('Cu', 'fcc', a=3.6)

class EMTPlus(EMT):
    def get_stress(self, atoms):
        return np.zeros(6)

cu.set_calculator(EMTPlus())
f = StrainFilter(cu)
opt = MDMin(f, dt=0.01)
opt.run(0.1, steps=2)
Example #43
0
File: si.py Project: qsnake/gpaw
def diamond2(symbol, a):
    return bulk(symbol, "diamond", a=a)
Example #44
0
from ase import *
from ase.structure import bulk
import numpy as np
from gpaw import *
from gpaw.mpi import serial_comm
from gpaw.test import equal
from gpaw.xc.rpa_correlation_energy import RPACorrelation

calc = GPAW(h=0.18, xc='LDA', kpts=(4,4,4), #usesymm=None,
            nbands=15, eigensolver='cg', 
            convergence={'bands': -5},
            communicator=serial_comm)

V = 30.
a0 = (4.*V)**(1/3.)
Kr = bulk('Kr', 'fcc', a=a0)

Kr.set_calculator(calc)
Kr.get_potential_energy()

ecut = 30.
w = np.linspace(0.0, 50., 8)
rpa = RPACorrelation(calc)
E_rpa = rpa.get_rpa_correlation_energy(ecut=ecut, w=w)

equal(E_rpa, -3.2, 0.1)
Example #45
0
def run(argv=None):
    if argv is None:
        argv = sys.argv[1:]
    elif isinstance(argv, str):
        argv = argv.split()
        
    parser = build_parser()
    opt, args = parser.parse_args(argv)
    
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    name = args[0]

    if world.rank == 0:
        out = sys.stdout#open('%s-%s.results' % (name, opt.identifier), 'w')
    else:
        out = devnull

    a = None
    try:
        symbols = string2symbols(name)
    except ValueError:
        # name was not a chemical formula - must be a file name:
        atoms = read(name)
    else:
        if opt.crystal_structure:
            a = opt.lattice_constant
            if a is None:
                a = estimate_lattice_constant(name, opt.crystal_structure,
                                              opt.c_over_a)
                out.write('Using an estimated lattice constant of %.3f Ang\n' %
                          a)

            atoms = bulk(name, opt.crystal_structure, a, covera=opt.c_over_a,
                         orthorhombic=opt.orthorhombic, cubic=opt.cubic)
        else:
            try:
                # Molecule?
                atoms = molecule(name)
            except NotImplementedError:
                if len(symbols) == 1:
                    # Atom
                    atoms = Atoms(name)
                elif len(symbols) == 2:
                    # Dimer
                    atoms = Atoms(name, positions=[(0, 0, 0),
                                                   (opt.bond_length, 0, 0)])
                else:
                    raise ValueError('Unknown molecule: ' + name)

    if opt.magnetic_moment:
        magmom = opt.magnetic_moment.split(',')
        atoms.set_initial_magnetic_moments(np.tile(magmom,
                                                   len(atoms) // len(magmom)))

    if opt.repeat is not None:
        r = opt.repeat.split(',')
        if len(r) == 1:
            r = 3 * r
        atoms = atoms.repeat([int(c) for c in r])

    if opt.gui:
        view(atoms)
        return

    if opt.write_to_file:
        write(opt.write_to_file, atoms)
        return

    if opt.effective_medium_theory:
        Runner = EMTRunner
    else:
        Runner = GPAWRunner

    if opt.fit:
        strains = np.linspace(0.98, 1.02, 5)
    else:
        strains = None

    if opt.constrain_tags:
        tags = [int(t) for t in opt.constrain_tags.split(',')]
        constrain = FixAtoms(mask=[t in tags for t in atoms.get_tags()])
        atoms.constraints = [constrain]

    runner = Runner(name, atoms, strains, tag=opt.identifier,
                    clean=not opt.read,
                    fmax=opt.relax, out=out)

    if not opt.effective_medium_theory:
        # Import stuff that eval() may need to know:
        from gpaw.wavefunctions.pw import PW
        from gpaw.occupations import FermiDirac, MethfesselPaxton
            
        if opt.parameters:
            input_parameters = eval(open(opt.parameters).read())
        else:
            input_parameters = {}
        for key in defaults:
            value = getattr(opt, key)
            if value is not None:
                try:
                    input_parameters[key] = eval(value)
                except (NameError, SyntaxError):
                    input_parameters[key] = value

        runner.set_parameters(vacuum=opt.vacuum,
                              write_gpw_file=opt.write_gpw_file,
                              **input_parameters)

    runner.run()

    runner.summary(plot=opt.plot, a0=a)

    return runner
Example #46
0
                assert abs(dd) < 1e-10
                assert not (c2 - c).any()

h2 = Atoms('H2', positions=[(0, 0, 0), (0, 0, 1)])
nl = NeighborList([0.5, 0.5], skin=0.1, sorted=True, self_interaction=False)
assert nl.update(h2)
assert not nl.update(h2)
assert (nl.get_neighbors(0)[0] == [1]).all()

h2[1].z += 0.09
assert not nl.update(h2)
assert (nl.get_neighbors(0)[0] == [1]).all()

h2[1].z += 0.09
assert nl.update(h2)
assert (nl.get_neighbors(0)[0] == []).all()
assert nl.nupdates == 2

x = bulk('X', 'fcc', a=2**0.5)
print x

nl = NeighborList([0.5], skin=0.01, bothways=True, self_interaction=False)
nl.update(x)
assert len(nl.get_neighbors(0)[0]) == 12

nl = NeighborList([0.5] * 27, skin=0.01, bothways=True, self_interaction=False)
nl.update(x * (3, 3, 3))
for a in range(27):
    assert len(nl.get_neighbors(a)[0]) == 12
assert not np.any(nl.get_neighbors(13)[1])