from vasp import Vasp from ase.lattice.cubic import FaceCenteredCubic from ase import Atoms, Atom # bulk system atoms = FaceCenteredCubic(directions=[[0, 1, 1], [1, 0, 1], [1, 1, 0]], size=(1, 1, 1), symbol='Rh') calc = Vasp('bulk/bulk-rh', xc='PBE', encut=350, kpts=[4, 4, 4], isif=3, ibrion=2, nsw=10, atoms=atoms) bulk_energy = atoms.get_potential_energy() # atomic system atoms = Atoms([Atom('Rh',[5, 5, 5])], cell=(7, 8, 9)) calc = Vasp('bulk/atomic-rh', xc='PBE', encut=350, kpts=[1, 1, 1], atoms=atoms) atomic_energy = atoms.get_potential_energy() calc.stop_if(None in (bulk_energy, atomic_energy)) cohesive_energy = atomic_energy - bulk_energy print 'The cohesive energy is {0:1.3f} eV'.format(cohesive_energy)
def runVaspASEOptimizer(fname_in, fname_out, vaspflags): fname_in = str(fname_in) fname_out = str(fname_out) #read the input atoms object atoms = read(str(fname_in)) #set ibrion=-1 and nsw=0 vaspflags['ibrion'] = -1 vaspflags['nsw'] = 0 #update vasprc file to set mode to "run" to ensure that this runs immediately Vasp.vasprc(mode='run') #set ppn>1 so that it knows to do an mpi job, the actual ppn will guessed by Vasp module Vasp.VASPRC['queue.ppn'] = 2 vaspflags['NPAR'] = 4 #set up the calculation and run calc = Vasp('./', atoms=atoms, **vaspflags) #calc.update() #calc.read_results() qn = QuasiNewton(atoms, logfile='relax.log', trajectory='relax.traj') qn.run(fmax=vaspflags['ediffg'] if 'ediffg' in vaspflags else 0.05) atoms.write(fname_out) #Write a text file with the energy with open('energy.out', 'w') as fhandle: fhandle.write(str(atoms.get_potential_energy())) return str(atoms), open( 'relax.traj', 'r').read().encode('hex'), atoms.get_potential_energy()
def create_base(mat='graphene', layers=1, size=1): """Return a relaxed structure of the base material with n layers.""" name = 'vasp/type=base/mat={0}/layers={1}'.format(mat, layers) atoms = Vasp(name).get_atoms() atoms = atoms.repeat([size, size, 1]) return atoms
def run_vasp(atoms: Atoms): xc = 'PBE' init_kpoints = (5, 5, 5) incar = dict( isif=3, ibrion=1, sigma=0.05, nelm=200, nsw=200) calc = Vasp('', xc=xc, kpoints=init_kpoints, **incar) atoms.set_calculator(calc) calc_params = dict() plot_params = dict(save_plot=True) encut_params = dict(start=250, step=50) optimize(atoms, 'encut', params=encut_params, threshold=1e-2, plot_params=plot_params) # kpoint_params = dict(start=3, step=1) # optimize(atoms, 'kpoints', params=kpoint_params, # threshold=1e-2, plot_params=plot_params) return
def run_all(slab: Atoms, adsorbate: Atoms, config: dict, **opts): """ Write input files to run all combinations of slab + adsorbate :param slab: Atoms :param adsorbate: Atoms :param config: Dict, :param opts: gen_struct options :return: """ results = [] for ID, struct in gen_structs(slab, adsorbate, **opts): calc = Vasp(ID, atoms=struct, **config) logger.info(f'calculator for {ID} created') try: logger.info(f'{ID}: getting potential energy') toten = calc.potential_energy results.append(toten) # TODO: do something except (VaspSubmitted, VaspQueued) as e: logger.info(f"Couldn't get energy:\n{e}") results.append(None) print(e) all_jobs = len(results) jobs_finished = all_jobs - results.count(None) state = f'{jobs_finished}/{all_jobs} jobs finished' return state
def test0(): atoms = Atoms([Atom('O', [4, 5, 5], magmom=1), Atom('C', [5, 5, 5], magmom=2), Atom('O', [6, 5, 5], magmom=3)], cell=(10, 10, 10)) calc = Vasp('vasp', sigma=0.01, atoms=atoms) calc.write_db(fname='DB.db', append=False) with connect('DB.db') as con: data = con.get(1).data assert data['parameters']['sigma'] == 0.01 print 'done'
def test0(): atoms = Atoms([ Atom('O', [4, 5, 5], magmom=1), Atom('C', [5, 5, 5], magmom=2), Atom('O', [6, 5, 5], magmom=3) ], cell=(10, 10, 10)) calc = Vasp('vasp', sigma=0.01, atoms=atoms) calc.write_db(fname='DB.db', append=False) with connect('DB.db') as con: data = con.get(1).data assert data['parameters']['sigma'] == 0.01 print 'done'
def setup_func(): # Calculations can take awhile, so we # simulate a finished calc by copying it in. atoms0 = Atoms( [Atom('O', [4, 5, 5]), Atom('C', [5, 5, 5]), Atom('O', [6, 5, 5])], cell=(10, 10, 10)) calc = Vasp('atom-order-test', xc='PBE', encut=350, ediff=0.1, nsw=0, atoms=atoms0) calc.write_input()
def db_update(db_path, dft_path, delete=False, silent=False): """Update the database to include Vasp() calculations nested in dft_path.""" VASPRC['mode'] = None db = connect(db_path) old_size = sum(1 for _ in db.select()) db_paths = [] for d in db.select(): try: db_paths.append(d.data.path) except: pass for path in utils.calc_paths(dft_path): if os.path.abspath(path) in db_paths: continue calc = Vasp(path) if not calc.in_queue() and calc.potential_energy is None: for output_file in utils.calc_output_files(path): dead_file = os.path.join(path, output_file) if delete: os.remove(dead_file) if not silent: print("Dead output file: {}. Deleted: {}".format(dead_file, delete)) else: ctime = calc.get_elapsed_time() # The write_db method throws an AttributeError for new calcs. Remove this to debug. old_stdout = sys.stdout sys.stdout = open(os.devnull, "w") calc.write_db(db_path, parser='=', overwrite=False, data={'ctime': ctime}) sys.stdout.close() sys.stdout = old_stdout if not silent: print("Added calc to DB: {}".format(path)) new_size = sum(1 for _ in db.select()) added = new_size - old_size if not silent: print("{} total entries. {} new entries added.".format(new_size, added))
def update_db(self): """ update the db with computed energies""" db = connect(self.db_name) rows = db.count() + 1 for i in range(2, rows): calc = Vasp(self.directory.format(int(i))) #print(i) a = calc.get_atoms() if self.n_ads == 1: a.set_tags( np.concatenate( (np.zeros(len(self.FW)), np.ones(len(self.Ads))))) if self.n_ads == 2: a.set_tags( np.concatenate( (np.zeros(len(self.FW)), np.ones(len(self.Ads[0])), np.ones(len(self.Ads[1])) + 1))) db.update(i, a, relaxed=False)
def relax_struct(atoms: Atoms, config: dict): default_config = dict(encut=400, isif=3, ibrion=2, ispin=2, lreal='Auto') default_config.update(config) calc = Vasp('init_relax', atoms=atoms, **config) try: energy = calc.potential_energy print(energy) state = 'initial relaxation complete' except (VaspSubmitted, VaspQueued) as e: logger.info(f"Couldn't get energy:\n{e}") print(e) state = 'initial relaxation running' return state
def test(): # Test that atoms object agrees with calculator calc = Vasp('atom-order-test') atoms = calc.get_atoms() atoms0 = Atoms( [Atom('O', [4, 5, 5]), Atom('C', [5, 5, 5]), Atom('O', [6, 5, 5])], cell=(10, 10, 10)) # Check the atom order if not atoms.get_chemical_symbols() == \ atoms0.get_chemical_symbols(): raise Exception('Atom order not conserved') # Now call the calculator without assigning atoms calc2 = Vasp('atom-order-test') atoms = calc2.get_atoms() # Check the atom order if not atoms.get_chemical_symbols() == \ atoms0.get_chemical_symbols(): raise Exception('Atom order not conserved')
from ase import Atoms, Atom from vasp import Vasp Vasp.vasprc(mode=None) #Vasp.log.setLevel(10) import matplotlib.pyplot as plt import numpy as np from ase.dft import DOS import pylab as plt a = 3.9 # approximate lattice constant b = a / 2. bulk = Atoms([Atom('Pd', (0.0, 0.0, 0.0))], cell=[(0, b, b), (b, 0, b), (b, b, 0)]) kpts = [8, 10, 12, 14, 16, 18, 20] calcs = [ Vasp('bulk/pd-dos-k{0}-ismear-5'.format(k), encut=300, xc='PBE', kpts=[k, k, k], atoms=bulk) for k in kpts ] Vasp.wait(abort=True) for calc in calcs: # this runs the calculation if calc.potential_energy is not None: dos = DOS(calc, width=0.2) d = dos.get_dos() + k / 4.0 e = dos.get_energies() plt.plot(e, d, label='k={0}'.format(k)) else: pass plt.xlabel('energy (eV)')
from vasp import Vasp from ase import Atom, Atoms atoms = Atoms( [Atom('Cu', [0.000, 0.000, 0.000]), Atom('Pd', [-1.652, 0.000, 2.039])], cell=[[0.000, -2.039, 2.039], [0.000, 2.039, 2.039], [-3.303, 0.000, 0.000]]) atoms = atoms.repeat((2, 2, 2)) calc = Vasp('bulk/CuPd-cls-0', xc='PBE', encut=350, kpts=[4, 4, 4], ibrion=2, isif=3, nsw=40, atoms=atoms) print(atoms.get_potential_energy())
#+BEGIN_SRC python from vasp import Vasp calc = Vasp('bulk/Al-lda-vasp') calc.view() print[atoms.get_volume() for atoms in calc.traj] print[atoms.get_potential_energy() for atoms in calc.traj]
from vasp import Vasp # read in relaxed geometry calc = Vasp('molecules/h2o_relax') atoms = calc.get_atoms() # now define a new calculator calc = Vasp('molecules/h2o_vib_dfpt', xc='PBE', encut=400, ismear=0, # Gaussian smearing ibrion=7, # switches on the DFPT vibrational analysis (with # no symmetry constraints) nfree=2, potim=0.015, lepsilon=True, # enables to calculate and to print the BEC # tensors lreal=False, nsw=1, nwrite=3, # affects OUTCAR verbosity: explicitly forces # SQRT(mass)-divided eigenvectors to be printed atoms=atoms) print(calc.potential_energy)
from vasp import Vasp wd = 'bulk/Si-bandstructure' calc = Vasp('bulk/Si-selfconsistent') calc.clone(wd) kpts = [[0.5, 0.5, 0.0], # L [0, 0, 0], # Gamma [0, 0, 0], [0.5, 0.5, 0.5]] # X calc.set(kpts=kpts, reciprocal=True, kpts_nintersections=10, icharg=11) print calc.run()
from vasp import Vasp atoms = Vasp('bulk/Al-lda-vasp').get_atoms() atoms2 = Vasp('bulk/Al-lda-ase').get_atoms() import numpy as np cellA = atoms.get_cell() cellB = atoms2.get_cell() print((np.abs(cellA - cellB) < 0.01).all())
from vasp import Vasp print 'dE = {0:1.3f} eV'.format( Vasp('surfaces/Au-110-missing-row').potential_energy + Vasp('bulk/Au-fcc').potential_energy - Vasp('surfaces/Au-110').potential_energy)
from ase import Atoms, Atom from vasp import Vasp import matplotlib.pyplot as plt import numpy as np a = 3.9 # approximate lattice constant b = a / 2. bulk = Atoms([Atom('Pd', (0.0, 0.0, 0.0))], cell=[(0, b, b), (b, 0, b), (b, b, 0)]) calc = Vasp('bulk/pd-ados', encut=300, xc='PBE', lreal=False, rwigs={'Pd': 1.5}, # wigner-seitz radii for ados kpts=[8, 8, 8], atoms=bulk) # this runs the calculation calc.wait(abort=True) # now get results energies, ados = calc.get_ados(0, 'd') # we will select energies in the range of -10, 5 ind = (energies < 5) & (energies > -10) energies = energies[ind] dos = ados[ind] Nstates = np.trapz(dos, energies) occupied = energies <= 0.0 N_occupied_states = np.trapz(dos[occupied], energies[occupied]) # first moment ed = np.trapz(energies * dos, energies) / Nstates # second moment
# <<h2o-vib-vis>> from vasp import Vasp import numpy as np calc = Vasp('molecules/h2o_vib') energies, modes = calc.get_vibrational_modes(mode=0, massweighted=True, show=True)
from vasp import Vasp factors = [0.9, 0.95, 1.0, 1.05, 1.1] # to change volume by energies1, volumes1 = [], [] # from step 1 energies, volumes = [], [] # for step 2 ready = True for f in factors: calc = Vasp('bulk/tio2/step1-{0:1.2f}'.format(f)) atoms = calc.get_atoms() energies1.append(atoms.get_potential_energy()) volumes1.append(atoms.get_volume()) calc.clone('bulk/tio2/step2-{0:1.2f}'.format(f)) calc.set(isif=4) # You have to get the atoms again. atoms = calc.get_atoms() energies.append(atoms.get_potential_energy()) volumes.append(atoms.get_volume()) print(energies, volumes) calc.stop_if(None in energies) import matplotlib.pyplot as plt plt.plot(volumes1, energies1, volumes, energies) plt.xlabel('Vol. ($\AA^3)$') plt.ylabel('Total energy (eV)') plt.legend(['step 1', 'step 2'], loc='best') plt.savefig('images/tio2-step2.png')
from vasp import Vasp from ase.utils.eos import EquationOfState LC = [3.5, 3.55, 3.6, 3.65, 3.7, 3.75] energies = [] volumes = [] for a in LC: calc = Vasp('bulk/Cu-{0}'.format(a)) atoms = calc.get_atoms() volumes.append(atoms.get_volume()) energies.append(atoms.get_potential_energy()) calc.stop_if(None in energies) eos = EquationOfState(volumes, energies) v0, e0, B = eos.fit() print ''' v0 = {0} A^3 E0 = {1} eV B = {2} eV/A^3'''.format(v0, e0, B) eos.plot('images/Cu-fcc-eos.png')
from ase import Atoms, Atom from vasp import Vasp import matplotlib.pyplot as plt import numpy as np a = 3.9 # approximate lattice constant b = a / 2. bulk = Atoms([Atom('Pd', (0.0, 0.0, 0.0))], cell=[(0, b, b), (b, 0, b), (b, b, 0)]) RWIGS = [1.0, 1.1, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0 ] ED, WD, N = [], [], [] for rwigs in RWIGS: calc = Vasp('bulk/pd-ados') calc.clone('bulk/pd-ados-rwigs-{0}'.format(rwigs)) calc.set(rwigs={'Pd': rwigs}) if calc.potential_energy is None: continue # now get results ados = VaspDos(efermi=calc.get_fermi_level()) energies = ados.energy dos = ados.site_dos(0, 'd') #we will select energies in the range of -10, 5 ind = (energies < 5) & (energies > -10) energies = energies[ind] dos = dos[ind] Nstates = np.trapz(dos, energies) occupied = energies <= 0.0 N_occupied_states = np.trapz(dos[occupied], energies[occupied]) ed = np.trapz(energies * dos, energies) / np.trapz(dos, energies) wd2 = np.trapz(energies**2 * dos, energies) / np.trapz(dos, energies)
from vasp import Vasp calc = Vasp('bulk/tio2/step1-0.90') calc.clone('bulk/tio2/step2-0.90') #calc.set(isif=4) print calc.set(isif=4) print calc.calculation_required()
from vasp import Vasp from ase.lattice.cubic import FaceCenteredCubic from ase.dft import DOS atoms = FaceCenteredCubic(directions=[[0, 1, 1], [1, 0, 1], [1, 1, 0]], size=(1, 1, 1), symbol='Ni') atoms[0].magmom = 1 calc = Vasp('bulk/Ni-PBE', ismear=-5, kpts=[5, 5, 5], xc='PBE', ispin=2, lorbit=11, lwave=True, lcharg=True, # store for reuse atoms=atoms) e = atoms.get_potential_energy() print('PBE energy: ',e) calc.stop_if(e is None) dos = DOS(calc, width=0.2) e_pbe = dos.get_energies() d_pbe = dos.get_dos() calc.clone('bulk/Ni-PBE0') calc.set(xc='pbe0') atoms = calc.get_atoms() pbe0_e = atoms.get_potential_energy() if atoms.get_potential_energy() is not None: dos = DOS(calc, width=0.2) e_pbe0 = dos.get_energies() d_pbe0 = dos.get_dos()
#!/usr/bin/env python from ase import * from ase.structure import molecule from vasp import Vasp ### Setup calculators benzene = molecule('C6H6') benzene.set_cell([10, 10, 10]) benzene.center() calc1 = Vasp('molecules/benzene', xc='PBE', nbands=18, encut=350, atoms=benzene) calc1.set(lcharg=True) chlorobenzene = molecule('C6H6') chlorobenzene.set_cell([10, 10, 10]) chlorobenzene.center() chlorobenzene[11].symbol = 'Cl' calc2 = Vasp('molecules/chlorobenzene', xc='PBE', nbands=22, encut=350, atoms=chlorobenzene) calc2.set(lcharg=True) calc2.stop_if(None in (calc1.potential_energy, calc2.potential_energy)) x1, y1, z1, cd1 = calc1.get_charge_density() x2, y2, z2, cd2 = calc2.get_charge_density() cdiff = cd2 - cd1 print(cdiff.min(), cdiff.max()) ########################################## ##### set up visualization of charge difference
# Run NH3 NEB calculations from vasp import Vasp from ase.neb import NEB from ase.io import read atoms = Vasp('molecules/nh3-initial').get_atoms() atoms2 = Vasp('molecules/nh3-final').get_atoms() # 5 images including endpoints images = [atoms] # initial state images += [atoms.copy() for i in range(3)] images += [atoms2] # final state neb = NEB(images) neb.interpolate() calc = Vasp('molecules/nh3-neb', xc='PBE', ibrion=1, encut=350, nsw=90, spring=-5.0, atoms=images) #calc.write_db(atoms, 'molecules/nh3-neb/00/DB.db') #calc.write_db(atoms2, 'molecules/nh3-neb/04/DB.db') images, energies = calc.get_neb() calc.stop_if(None in energies) print images print energies p = calc.plot_neb(show=False) import matplotlib.pyplot as plt plt.savefig('images/nh3-neb.png')
from vasp import Vasp from ase.lattice.surface import fcc110 from ase.io import write from ase.constraints import FixAtoms atoms = fcc110('Au', size=(2, 1, 6), vacuum=10.0) del atoms[11] # delete surface row constraint = FixAtoms(mask=[atom.tag > 2 for atom in atoms]) atoms.set_constraint(constraint) write('images/Au-110-missing-row.png', atoms.repeat((2, 2, 1)), rotation='-90x', show_unit_cell=2) calc = Vasp('surfaces/Au-110-missing-row', xc='PBE', kpts=[6, 6, 1], encut=350, ibrion=2, isif=2, nsw=10, atoms=atoms) calc.update()
from vasp import Vasp e1, e2, e3 = [ Vasp(wd).potential_energy for wd in [ 'surfaces/Au-benzene-pbe-d2', 'surfaces/Au-pbe-d2', 'molecules/benzene-pbe-d2' ] ] print('Adsorption energy = {0:1.2f} eV'.format(e1 - e2 - e3))
from vasp import Vasp calc = Vasp('molecules/O2-sp-singlet') calc.clone('molecules/O2-sp-singlet-magmoms') calc.set(lorbit=11) atoms = calc.get_atoms() magmoms = atoms.get_magnetic_moments() print('singlet ground state') for i, atom in enumerate(atoms): print('atom {0}: magmom = {1}'.format(i, magmoms[i])) print(atoms.get_magnetic_moment()) calc = Vasp('molecules/O2-sp-triplet') calc.clone('molecules/O2-sp-triplet-magmoms') calc.set(lorbit=11) atoms = calc.get_atoms() magmoms = atoms.get_magnetic_moments() print() print('triplet ground state') for i, atom in enumerate(atoms): print('atom {0}: magmom = {1}'.format(i, magmoms[i])) print(atoms.get_magnetic_moment())
from vasp import Vasp from ase.structure import molecule atoms = molecule('H2O') atoms.center(vacuum=6) calc = Vasp('molecules/h2o-bader', xc='PBE', encut=350, lcharg=True, laechg=True, atoms=atoms) print calc.potential_energy
from vasp import Vasp from ase.structure import molecule atoms = molecule('CO') atoms.center(vacuum=5) calc = Vasp('molecules/CO-vacuum', encut=600, prec='Accurate', ismear=0, sigma=0.05, ibrion=2, nsw=0, ediff=1e-6, atoms=atoms) print(atoms.get_potential_energy()) print(atoms.get_forces()) print('Calculation time: {} seconds'.format(calc.get_elapsed_time()))
from vasp import Vasp from ase.lattice.cubic import BodyCenteredCubic atoms = BodyCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], size=(1, 1, 1), symbol='Fe') NUPDOWNS = [0.0, 2.0, 4.0, 5.0, 6.0, 8.0] energies = [] for B in NUPDOWNS: calc = Vasp('bulk/Fe-bcc-fixedmagmom-{0:1.2f}'.format(B), xc='PBE', encut=300, kpts=[4, 4, 4], ispin=2, nupdown=B, atoms=atoms) energies.append(atoms.get_potential_energy()) if None in energies: calc.abort() import matplotlib.pyplot as plt plt.plot(NUPDOWNS, energies) plt.xlabel('Total Magnetic Moment') plt.ylabel('Energy (eV)') plt.savefig('images/Fe-fixedmagmom.png')
from vasp import Vasp # don't forget to normalize your total energy to a formula unit. Cu2O # has 3 atoms, so the number of formula units in an atoms is # len(atoms)/3. calc = Vasp('bulk/Cu2O') atoms1 = calc.get_atoms() cu2o_energy = atoms1.get_potential_energy() calc = Vasp('bulk/CuO') atoms2 = calc.get_atoms() cuo_energy = atoms2.get_potential_energy() # make sure to use the same cutoff energy for the O2 molecule! calc = Vasp('molecules/O2-sp-triplet-400') atoms3 = calc.get_atoms() o2_energy = atoms3.get_potential_energy() calc.stop_if(None in [cu2o_energy, cuo_energy, o2_energy]) cu2o_energy /= (len(atoms1) / 3) # note integer math cuo_energy /= (len(atoms2) / 2) rxn_energy = 4.0 * cuo_energy - o2_energy - 2.0 * cu2o_energy print 'Reaction energy = {0} eV'.format(rxn_energy)
from vasp import Vasp from ase.lattice.surface import fcc111 import matplotlib.pyplot as plt Nlayers = [3, 4, 5, 6, 7, 8, 9, 10, 11] energies = [] sigmas = [] for n in Nlayers: slab = fcc111('Cu', size=(1, 1, n), vacuum=10.0) slab.center() calc = Vasp('bulk/Cu-layers/{0}'.format(n), xc='PBE', encut=350, kpts=[8, 8, 1], atoms=slab) calc.set_nbands(f=2) # the default nbands in VASP is too low for Cu energies.append(slab.get_potential_energy()) calc.stop_if(None in energies) for i in range(len(Nlayers) - 1): N = Nlayers[i] DeltaE_N = energies[i + 1] - energies[i] sigma = 0.5 * (-N * energies[i + 1] + (N + 1) * energies[i]) sigmas.append(sigma) print 'nlayers = {1:2d} sigma = {0:1.3f} eV/atom'.format(sigma, N) plt.plot(Nlayers[0:-1], sigmas, 'bo-') plt.xlabel('Number of layers') plt.ylabel('Surface energy (eV/atom)') plt.savefig('images/Cu-unrelaxed-surface-energy.png')
from vasp import Vasp calc = Vasp('molecules/CO-vacuum') calc.clone('molecules/CO-solvated') calc.set(istart=1, # lsol=True) print(calc.get_atoms().get_potential_energy()) print(calc.get_atoms().get_forces()) print('Calculation time: {} seconds'.format(calc.get_elapsed_time()))
import matplotlib.pyplot as plt DELTAS = np.linspace(-0.05, 0.05, 5) calcs = [] volumes = [] for delta in DELTAS: atoms = FaceCenteredCubic(symbol='Al') cell = atoms.cell T = np.array([[1 + delta, 0, 0], [0, 1, 0], [0, 0, 1]]) newcell = np.dot(cell, T) atoms.set_cell(newcell, scale_atoms=True) volumes += [atoms.get_volume()] calcs += [ Vasp('bulk/Al-c11-{}'.format(delta), xc='pbe', kpts=[12, 12, 12], encut=350, atoms=atoms) ] Vasp.run() energies = [calc.potential_energy for calc in calcs] # fit a parabola eos = np.polyfit(DELTAS, energies, 2) # first derivative d_eos = np.polyder(eos) print(np.roots(d_eos)) xfit = np.linspace(min(DELTAS), max(DELTAS)) yfit = np.polyval(eos, xfit) plt.plot(DELTAS, energies, 'bo', xfit, yfit, 'b-') plt.xlabel('$\delta$') plt.ylabel('Energy (eV)')
from vasp import Vasp atoms = molecule('N2') atoms.set_cell((10,10,10), scale_atoms=False) # first we relax a molecule calc = Vasp('molecules/n2-relax', xc='PBE', encut=300, ibrion=2, nsw=5, atoms=atoms) electronicenergy = atoms.get_potential_energy() # next, we get vibrational modes calc2 = Vasp('molecules/n2-vib', xc='PBE', encut=300, ibrion=6, nfree=2, potim=0.15, nsw=1, atoms=atoms) calc2.wait() vib_freq = calc2.get_vibrational_frequencies() # in cm^1 #convert wavenumbers to energy h = 4.1356675e-15 # eV*s c = 3.0e10 #cm/s vib_energies = [h*c*nu for nu in vib_freq] print('vibrational energies\n====================') for i,e in enumerate(vib_energies): print('{0:02d}: {1} eV'.format(i,e)) # # now we can get some properties. Note we only need one vibrational # energy since there is only one mode. This example does not work if # you give all the energies because one energy is zero.
from vasp import Vasp import matplotlib.pyplot as plt import numpy as np calc = Vasp('surfaces/Al-slab-relaxed') atoms = calc.get_atoms() calc = Vasp( 'surfaces/Al-slab-locpot', xc='PBE', kpts=[6, 6, 1], encut=350, lvtot=True, # write out local potential lvhar=True, # write out only electrostatic potential, not xc pot atoms=atoms) calc.wait() ef = calc.get_fermi_level() x, y, z, lp = calc.get_local_potential() nx, ny, nz = lp.shape axy = np.array([np.average(lp[:, :, z]) for z in range(nz)]) # setup the x-axis in realspace uc = atoms.get_cell() xaxis = np.linspace(0, uc[2][2], nz) plt.plot(xaxis, axy) plt.plot([min(xaxis), max(xaxis)], [ef, ef], 'k:') plt.xlabel('Position along z-axis') plt.ylabel('x-y averaged electrostatic potential') plt.savefig('images/Al-wf.png') ind = (xaxis > 0) & (xaxis < 5) wf = np.average(axy[ind]) - ef print ' The workfunction is {0:1.2f} eV'.format(wf)
from ase.lattice.surface import fcc111 from vasp import Vasp slab = fcc111('Al', size=(1, 1, 4), vacuum=10.0) calc = Vasp('surfaces/Al-bandstructure', xc='PBE', encut=300, kpts=[6, 6, 6], lcharg=True, # you need the charge density lwave=True, # and wavecar for the restart atoms=slab) n, bands, p = calc.get_bandstructure(kpts_path=[(r'$\Gamma$', [0, 0, 0]), ('$K1$', [0.5, 0.0, 0.0]), ('$K1$', [0.5, 0.0, 0.0]), ('$K2$', [0.5, 0.5, 0.0]), ('$K2$', [0.5, 0.5, 0.0]), (r'$\Gamma$', [0, 0, 0]), (r'$\Gamma$', [0, 0, 0]), ('$K3$', [0.0, 0.0, 1.0])], kpts_nintersections=10) p.savefig('images/Al-slab-bandstructure.png')
from vasp import Vasp import matplotlib.pyplot as plt calc = Vasp('surfaces/Al-Na-nodip') atoms = calc.get_atoms() x, y, z, lp = calc.get_local_potential() nx, ny, nz = lp.shape axy_1 = [np.average(lp[:, :, z]) for z in range(nz)] # setup the x-axis in realspace uc = atoms.get_cell() xaxis_1 = np.linspace(0, uc[2][2], nz) e1 = atoms.get_potential_energy() calc = Vasp('surfaces/Al-Na-dip-step2') atoms = calc.get_atoms() x, y, z, lp = calc.get_local_potential() nx, ny, nz = lp.shape axy_2 = [np.average(lp[:, :, z]) for z in range(nz)] # setup the x-axis in realspace uc = atoms.get_cell() xaxis_2 = np.linspace(0, uc[2][2], nz) ef2 = calc.get_fermi_level() e2 = atoms.get_potential_energy() print 'The difference in energy is {0} eV.'.format(e2-e1) plt.plot(xaxis_1, axy_1, label='no dipole correction') plt.plot(xaxis_2, axy_2, label='dipole correction') plt.plot([min(xaxis_2), max(xaxis_2)], [ef2, ef2], 'k:', label='Fermi level') plt.xlabel('z ($\AA$)') plt.ylabel('xy-averaged electrostatic potential') plt.legend(loc='best') plt.savefig('images/dip-vs-nodip-esp.png')
from vasp import Vasp # get relaxed geometry H2O = Vasp('molecules/wgs/H2O').get_atoms() # now do the vibrations calc = Vasp('molecules/wgs/H2O-vib', xc='PBE', encut=350, ismear=0, ibrion=6, nfree=2, potim=0.02, nsw=1, atoms=H2O) calc.wait() vib_freq = calc.get_vibrational_frequencies() for i, f in enumerate(vib_freq): print('{0:02d}: {1} cm^(-1)'.format(i, f))
from vasp import Vasp from ase import Atom, Atoms # square box origin atoms = Atoms([Atom('O', [0, 0, 0], magmom=2)], cell=(10, 10, 10)) pars = dict(xc='PBE', encut=400, ismear=0, sigma=0.01, ispin=2) calc = Vasp('molecules/O-square-box-origin', atoms=atoms, **pars) print('Square box (origin): E = {0} eV'.format(atoms.get_potential_energy())) # square box center atoms = Atoms([Atom('O', [5, 5, 5], magmom=2)], cell=(10, 10, 10)) calc = Vasp('molecules/O-square-box-center', atoms=atoms, **pars) print('Square box (center): E = {0} eV'.format(atoms.get_potential_energy())) # square box random atoms = Atoms([Atom('O', [2.13, 7.32, 1.11], magmom=2)], cell=(10, 10, 10)) calc = Vasp('molecules/O-square-box-random', atoms=atoms, **pars) print('Square box (random): E = {0} eV'.format(atoms.get_potential_energy()))
from vasp import Vasp from ase import Atom, Atoms bond_lengths = [1.05, 1.1, 1.15, 1.2, 1.25] energies = [] for d in bond_lengths: # possible bond lengths co = Atoms([Atom('C', [0, 0, 0]), Atom('O', [d, 0, 0])], cell=(6, 6, 6)) calc = Vasp( 'molecules/co-{0}'.format(d), # output dir xc='PBE', nbands=6, encut=350, ismear=1, sigma=0.01, atoms=co) energies.append(co.get_potential_energy()) print('d = {0:1.2f} ang'.format(d)) print('energy = {0:1.3f} eV'.format(energies[-1] or 0)) print('forces = (eV/ang)\n {0}'.format(co.get_forces())) print('') # blank line if None in energies: calc.abort() else: import matplotlib.pyplot as plt plt.plot(bond_lengths, energies, 'bo-') plt.xlabel(r'Bond length ($\AA$)') plt.ylabel('Total energy (eV)') plt.savefig('images/co-bondlengths.png')
from ase.structure import molecule from ase.thermochemistry import IdealGasThermo from vasp import Vasp atoms = molecule('N2') atoms.set_cell((10, 10, 10), scale_atoms=False) # first we relax a molecule calc = Vasp('molecules/n2-relax', xc='PBE', encut=300, ibrion=2, nsw=5, atoms=atoms) electronicenergy = atoms.get_potential_energy() # next, we get vibrational modes calc2 = Vasp('molecules/n2-vib', xc='PBE', encut=300, ibrion=6, nfree=2, potim=0.15, nsw=1, atoms=atoms) calc2.wait() vib_freq = calc2.get_vibrational_frequencies() # in cm^1 #convert wavenumbers to energy h = 4.1356675e-15 # eV*s c = 3.0e10 #cm/s vib_energies = [h * c * nu for nu in vib_freq] print('vibrational energies\n====================') for i, e in enumerate(vib_energies): print('{0:02d}: {1} eV'.format(i, e))
], cell=[a1, a2, a3]) v0 = atoms.get_volume() cell0 = atoms.get_cell() factors = [0.9, 0.95, 1.0, 1.05, 1.1] #to change volume by energies, volumes = [], [] ready = True for f in factors: v1 = f * v0 cell_factor = (v1 / v0)**(1. / 3.) atoms.set_cell(cell0 * cell_factor, scale_atoms=True) calc = Vasp( 'bulk/tio2/step1-{0:1.2f}'.format(f), encut=520, kpts=[5, 5, 5], isif=2, # relax internal degrees of freedom ibrion=1, nsw=50, xc='PBE', sigma=0.05, atoms=atoms) energies.append(atoms.get_potential_energy()) volumes.append(atoms.get_volume()) calc.stop_if(None in energies) plt.plot(volumes, energies) plt.xlabel('Vol. ($\AA^3)$') plt.ylabel('Total energy (eV)') plt.savefig('images/tio2-step1.png') print '#+tblname: tio2-vol-ene' print '#+caption: Total energy of TiO_{2} vs. volume.' print '| Volume ($\AA^3$) | Energy (eV) |' print '|-'
from vasp import Vasp from ase import Atom, Atoms atoms = Atoms([Atom('O', [4, 4.5, 5], magmom=2)], cell=(8, 9, 10)) calc = Vasp('molecules/O-sp-triplet-lowsym-s', xc='PBE', ismear=0, ispin=2, sigma=0.01, setups=[['O', '_s']], atoms=atoms) E_O = atoms.get_potential_energy() print('Magnetic moment on O = {0} Bohr' ' magnetons'.format(atoms.get_magnetic_moment())) # now relaxed O2 dimer atoms = Atoms( [Atom('O', [5, 5, 5], magmom=1), Atom('O', [6.22, 5, 5], magmom=1)], cell=(10, 10, 10)) calc = Vasp( 'molecules/O2-sp-triplet-s', xc='PBE', ismear=0, sigma=0.01, ispin=2, # turn spin-polarization on ibrion=2, # make sure we relax the geometry nsw=10, setups=[['O', '_s']], atoms=atoms) E_O2 = atoms.get_potential_energy() # verify magnetic moment print('Magnetic moment on O2 = {0} Bohr'
from ase.thermochemistry import IdealGasThermo from vasp import Vasp import numpy as np import matplotlib.pyplot as plt # first we get the electronic energies c1 = Vasp('molecules/wgs/CO') E_CO = c1.potential_energy CO = c1.get_atoms() c2 = Vasp('molecules/wgs/CO2') E_CO2 = c2.potential_energy CO2 = c2.get_atoms() c3 = Vasp('molecules/wgs/H2') E_H2 = c3.potential_energy H2 = c3.get_atoms() c4 = Vasp('molecules/wgs/H2O') E_H2O = c4.potential_energy H2O = c4.get_atoms() # now we get the vibrational energies h = 4.1356675e-15 # eV * s c = 3.0e10 # cm / s calc = Vasp('molecules/wgs/CO-vib') vib_freq = calc.get_vibrational_frequencies() CO_vib_energies = [h * c * nu for nu in vib_freq] calc = Vasp('molecules/wgs/CO2-vib') vib_freq = calc.get_vibrational_frequencies() CO2_vib_energies = [h * c * nu for nu in vib_freq] calc = Vasp('molecules/wgs/H2-vib') vib_freq = calc.get_vibrational_frequencies() H2_vib_energies = [h * c * nu for nu in vib_freq] calc = Vasp('molecules/wgs/H2O-vib') vib_freq = calc.get_vibrational_frequencies()
from vasp import Vasp from ase import Atom, Atoms encuts = [250, 300, 350, 400, 450, 500, 550] D = [] for encut in encuts: atoms = Atoms([Atom('O', [5, 5, 5], magmom=2)], cell=(10, 10, 10)) calc = Vasp('molecules/O-sp-triplet-{0}'.format(encut), xc='PBE', encut=encut, ismear=0, ispin=2, atoms=atoms) E_O = atoms.get_potential_energy() # now relaxed O2 dimer atoms = Atoms([Atom('O', [5, 5, 5], magmom=1), Atom('O', [6.22, 5, 5], magmom=1)], cell=(10, 10, 10)) calc = Vasp('molecules/O2-sp-triplet-{0}'.format(encut), xc='PBE', encut=encut, ismear=0, ispin=2, # turn spin-polarization on ibrion=2, # this turns relaxation on nsw=10, atoms=atoms) E_O2 = atoms.get_potential_energy() if None not in (E_O, E_O2): d = 2*E_O - E_O2 D.append(d) print('O2 -> 2O encut = {0} D = {1:1.3f} eV'.format(encut, d))
from vasp import Vasp from ase.lattice.surface import fcc110 from ase.io import write from ase.constraints import FixAtoms atoms = fcc110('Au', size=(2, 1, 6), vacuum=10.0) constraint = FixAtoms(mask=[atom.tag > 2 for atom in atoms]) atoms.set_constraint(constraint) write('images/Au-110.png', atoms.repeat((2, 2, 1)), rotation='-90x', show_unit_cell=2) print Vasp('surfaces/Au-110', xc='PBE', kpts=[6, 6, 1], encut=350, ibrion=2, isif=2, nsw=10, atoms=atoms).potential_energy
from vasp import Vasp # get relaxed geometry calc = Vasp('molecules/wgs/CO2') CO2 = calc.get_atoms() # now do the vibrations calc = Vasp('molecules/wgs/CO2-vib', xc='PBE', encut=350, ismear=0, ibrion=6, nfree=2, potim=0.02, nsw=1, atoms=CO2) calc.wait() vib_freq = calc.get_vibrational_frequencies() for i, f in enumerate(vib_freq): print('{0:02d}: {1} cm^(-1)'.format(i, f))
from ase import Atoms, Atom from vasp import Vasp import ase.units atoms = Atoms([ Atom('H', [0.5960812, -0.7677068, 0.0000000]), Atom('O', [0.0000000, 0.0000000, 0.0000000]), Atom('H', [0.5960812, 0.7677068, 0.0000000]) ], cell=(8, 8, 8)) atoms.center() calc = Vasp( 'molecules/h2o_vib', xc='PBE', encut=400, ismear=0, # Gaussian smearing ibrion=6, # finite differences with symmetry nfree=2, # central differences (default) potim=0.015, # default as well ediff=1e-8, # for vibrations you need precise energies nsw=1, # Set to 1 for vibrational calculation atoms=atoms) print('Forces') print('======') print(atoms.get_forces()) print('') calc.stop_if(calc.potential_energy is None) # vibrational energies are in eV energies, modes = calc.get_vibrational_modes() print('energies\n========') for i, e in enumerate(energies): print('{0:02d}: {1} eV'.format(i, e))
from vasp import Vasp from ase.units import Debye calc = Vasp('molecules/co-centered') dipole_moment = calc.get_dipole_moment() print('The dipole moment is {0:1.2f} Debye'.format(dipole_moment))
# the clean gold slab from vasp import Vasp from ase.lattice.surface import fcc111, add_adsorbate from ase.constraints import FixAtoms atoms = fcc111('Au', size=(3, 3, 3), vacuum=10) # now we constrain the slab c = FixAtoms(mask=[atom.symbol == 'Au' for atom in atoms]) atoms.set_constraint(c) print( Vasp('surfaces/Au-pbe-d2', xc='PBE', encut=350, kpts=[4, 4, 1], ibrion=1, nsw=100, lvdw=True, atoms=atoms).potential_energy)
from ase import Atoms, Atom from vasp import Vasp Vasp.vasprc(mode=None) #Vasp.log.setLevel(10) import matplotlib.pyplot as plt import numpy as np from ase.dft import DOS import pylab as plt a = 3.9 # approximate lattice constant b = a / 2. bulk = Atoms([Atom('Pd', (0.0, 0.0, 0.0))], cell=[(0, b, b), (b, 0, b), (b, b, 0)]) kpts = [8, 10, 12, 14, 16, 18, 20] calcs = [Vasp('bulk/pd-dos-k{0}-ismear-5'.format(k), encut=300, xc='PBE', kpts=[k, k, k], atoms=bulk) for k in kpts] Vasp.wait(abort=True) for calc in calcs: # this runs the calculation if calc.potential_energy is not None: dos = DOS(calc, width=0.2) d = dos.get_dos() + k / 4.0 e = dos.get_energies() plt.plot(e, d, label='k={0}'.format(k)) else: pass plt.xlabel('energy (eV)')