def run_energy_eval(totalsol, calc_method='LAMMPS', fx_region=False, fit_scheme='totalenfit', STR='', static_calc=None): if calc_method=='VASP': en=totalsol.get_potential_energy() calcb=Vasp(restart=True) totalsol=calcb.get_atoms() stress=calcb.read_stress() else: totcop = totalsol.copy() OUT = totalsol.calc.calculate(totalsol) totalsol = OUT['atoms'] totalsol.set_pbc(True) if fx_region: STR+='Energy of fixed region calc = {0}\n'.format(OUT['thermo'][-1]['pe']) totalsol.set_calculator(static_calc) OUT=totalsol.calc.calculate(totalsol) totalsol=OUT['atoms'] totalsol.set_pbc(True) STR+='Energy of static calc = {0}\n'.format(OUT['thermo'][-1]['pe']) en=OUT['thermo'][-1]['pe'] stress=numpy.array([OUT['thermo'][-1][i] for i in ('pxx','pyy','pzz','pyz','pxz','pxy')])*(-1e-4*GPa) if fit_scheme == 'enthalpyfit': pressure = totalsol.get_isotropic_pressure(stress) else: pressure = 0 volume = totalsol.get_volume() energy=en STR+='Energy per atom = {0}\n'.format(energy/len(totalsol)) return totalsol, energy, pressure, volume, STR
def defect_strain_matrices(label,conc,Latt): from ase.calculators.vasp import Vasp calc = Vasp(restart=1) atoms = calc.get_atoms() LattDef = numpy.array(atoms.get_cell()) # LattDef = correct_lattice_matrix(numpy.array(atoms.get_cell())) dstrain = (1/conc)*numpy.dot(numpy.subtract(LattDef,Latt),numpy.linalg.inv(Latt)) dstrain_vec = asetools.tensorise(dstrain) outfile = 'defect_strain.txt' fout = open(outfile,'w') print>>fout, label print>>fout, "concentration {:^10}".format(conc) print>>fout, "defect strain matrix" for item in dstrain: print>>fout, ' '.join(map(str, item)) print>>fout, "defect strain vector" for item in dstrain_vec: print>>fout, item print>>fout, "Defect supercell lattice" for item in LattDef: print>>fout, ' '.join(map(str, item)) print>>fout, "Perfect supercell lattice" for item in Latt: print>>fout, ' '.join(map(str, item)) fout.close
def calculate(self, atoms): ''' Blocking/Non-blocking calculate method If we are in blocking mode we just run, wait for the job to end and read in the results. Easy ... The non-blocking mode is a little tricky. We need to start the job and guard against it reading back possible old data from the directory - the queuing system may not even started the job when we get control back from the starting script. Thus anything we read after invocation is potentially garbage - even if it is a converged calculation data. We handle it by custom run function above which raises an exception after submitting the job. This skips post-run processing in the calculator, preserves the state of the data and signals here that we need to wait for results. ''' with work_dir(self.working_dir) : self.prepare_calc_dir() self.calc_running=True #print('Run VASP.calculate') try : Vasp.calculate(self, atoms) self.calc_running=False #print('VASP.calculate returned') except _NonBlockingRunException as e: # We have nothing else to docs # until the job finishes #print('Interrupted ', self.working_dir, os.getcwd()) pass
def update(self, atoms): if self.calc_running : # we have started the calculation and have # nothing to read really. But we need to check # first if this is still true. if self.calc_finished(): # We were running but recently finished => read the results # This is a piece of copy-and-paste programming # This is a copy of code from Vasp.calculate self.calc_running=False with work_dir(self.working_dir) : atoms_sorted = ase.io.read('CONTCAR', format='vasp') if self.int_params['ibrion'] > -1 and self.int_params['nsw'] > 0: # Update atomic positions and unit cell with the ones read # from CONTCAR. atoms.positions = atoms_sorted[self.resort].positions atoms.cell = atoms_sorted.cell self.converged = self.read_convergence() Vasp.set_results(self,atoms) return else : return # We are not in the middle of calculation. # Update as normal Vasp.update(self, atoms)
def main(): if sys.version_info < (2, 7): raise NotAvailable('read_xml requires Python version 2.7 or greater') assert installed() # simple test calculation of CO molecule d = 1.14 co = Atoms('CO', positions=[(0, 0, 0), (0, 0, d)], pbc=True) co.center(vacuum=5.) calc = Vasp(xc='PBE', prec='Low', algo='Fast', ismear=0, sigma=1., istart=0, lwave=False, lcharg=False) co.set_calculator(calc) energy = co.get_potential_energy() forces = co.get_forces() # check that parsing of vasprun.xml file works conf = read('vasprun.xml') assert conf.calc.parameters['kpoints_generation'] assert conf.calc.parameters['sigma'] == 1.0 assert conf.calc.parameters['ialgo'] == 68 assert energy - conf.get_potential_energy() == 0.0 assert array_almost_equal(conf.get_forces(), forces, tol=1e-4) # Cleanup calc.clean()
def __init__(self, nodes=1, ppn=8, block=True, ncl=False, **kwargs): Vasp.__init__(self, **kwargs) self.nodes=nodes self.ppn=ppn self.block=block self.ncl=ncl self.calc_running=False self.working_dir=os.getcwd()
def calc_defect_strain_matrix(Latt): from ase.calculators.vasp import Vasp # defect lattice calc = Vasp(restart=1) atoms = calc.get_atoms() LattDef = numpy.array(atoms.get_cell()) dstrain = conc*numpy.dot(numpy.subtract(LattDef,Latt.T),numpy.linalg.inv(Latt.T)) dstrain=asetools.symmetrize(dstrain) return dstrain
def get_locpot_array(file): """ Returns the charge densities on the fine FFT-grid in a numpy array.""" from ase.calculators.vasp import VaspChargeDensity from ase.calculators.vasp import Vasp calc = Vasp(restart=True) cell = calc.get_atoms() vol = cell.get_volume() pot_array = numpy.vstack((VaspChargeDensity(file)).chg) numpy.divide(pot_array,vol) return pot_array
def write_input_files(self, at, label): global _chdir_lock # For LOTF Simulations active number of quantum # atoms vary and must wait to this stage in order for # magnetic moments to be set properly. If magnetic moments # not set defaults to 0. self.vasp_args['magmom'] = at.get_initial_magnetic_moments() vasp = Vasp(**self.vasp_args) vasp.initialize(at) # chdir not thread safe, so acquire global lock before using it orig_dir = os.getcwd() try: _chdir_lock.acquire() os.chdir(self.subdir) if os.path.exists('OUTCAR'): n = 1 while os.path.exists('OUTCAR.%d' % n): n += 1 shutil.copyfile('OUTCAR', 'OUTCAR.%d' % n) shutil.copyfile('POSCAR', 'POSCAR.%d' % n) write_vasp('POSCAR', vasp.atoms_sorted, symbol_count=vasp.symbol_count, vasp5='5' in self.exe) vasp.write_incar(at) vasp.write_potcar() vasp.write_kpoints() finally: os.chdir(orig_dir) _chdir_lock.release()
def neb_initialize(neb_images, kwargs): """Creates necessary files for an NEB calculation""" for a in neb_images: log.debug(a.numbers) calc = Vasp() # how to get the initial and final energies? initial = neb_images[0] log.debug(initial.numbers) calc0 = initial.get_calculator() log.debug('Calculator cwd = %s', calc0.cwd) log.debug('Calculator vaspdir = %s', calc0.vaspdir) # we have to store the initial and final energies because # otherwise they will not be available when reread the # directory in another script, e.g. jaspsum. The only other # option is to make the initial and final directories full # vasp calculations. CWD = os.getcwd() try: os.chdir(os.path.join(calc0.cwd, calc0.vaspdir)) e0 = calc0.read_energy()[1] calc.neb_initial_energy = e0 finally: os.chdir(CWD) final = neb_images[-1] log.debug(final.numbers) calc_final = final.get_calculator() log.debug(calc_final.cwd) log.debug(calc_final.vaspdir) try: os.chdir(os.path.join(calc_final.cwd, calc_final.vaspdir)) efinal = calc_final.read_energy()[1] calc.neb_final_energy = efinal finally: os.chdir(CWD) # make a Vasp object and set inputs to initial image calc.int_params.update(calc0.int_params) calc.float_params.update(calc0.float_params) calc.exp_params.update(calc0.exp_params) calc.string_params.update(calc0.string_params) calc.bool_params.update(calc0.bool_params) calc.list_params.update(calc0.list_params) calc.dict_params.update(calc0.dict_params) calc.input_params.update(calc0.input_params) calc.neb_kwargs = kwargs # this is the vasp images tag. it does not include the endpoints IMAGES = len(neb_images) - 2 calc.set(images=IMAGES) calc.neb_images = neb_images calc.neb_nimages = IMAGES calc.neb = True return calc
def set(self,**kwargs): if 'block' in kwargs : self.block=kwargs['block'] del kwargs['block'] else : self.block=True if 'ncl' in kwargs : self.ncl=kwargs['ncl'] del kwargs['ncl'] else : self.ncl=False Vasp.set(self, **kwargs)
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 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 run(self): ''' Blocking/Non-blocing run method. In blocking mode it just runs parent run method. In non-blocking mode it raises the __NonBlockingRunException to bail out of the processing of standard calculate method (or any other method in fact) and signal that the data is not ready to b collected. ''' # This is only called from self.calculate - thus # we do not need to change to working_dir # since calculate already did Vasp.run(self) if not self.block : #print('Interrupt processing of calculate', os.getcwd()) raise _NonBlockingRunException
def preprocess(self, at, label, force_restart=False): self.logger.pr('vasp client %d preprocessing atoms label %d' % (self.client_id, label)) # make a copy and then sort atoms in the same way that vasp # calculator will when it writes POSCAR. We use a new # calculator and store the sort order in the Atoms so it can # be reversed when results are ready. vasp = Vasp(**self.vasp_args) vasp.initialize(at) at = at.copy() order = np.array(range(len(at))) at.set_array('vasp_sort_order', order) at = at[vasp.resort] # finally, call the parent method return Client.preprocess(self, at, label, force_restart)
def test_ase_relax(): slab = create_slab_with_constraints() calc = Vasp(xc='LDA', ediffg=-1e-3, lwave=False, lcharg=False) slab.set_calculator(calc) opt = BFGS(slab, logfile=None) opt.run(fmax=0.1, steps=3) init_slab = create_slab_with_constraints() res = read('OUTCAR') assert np.allclose(res.positions[0], init_slab.positions[0]) assert not np.allclose(res.positions[2], init_slab.positions[2])
def setup_dvol_corrections_evq(self): from ase.calculators.vasp import Vasp calc = Vasp(restart=True) atoms = calc.get_atoms() cell = atoms.get_cell() #Create small and large lattice matrices small = cell*0.99 large = cell*1.01 # Setup the large and small POSCAR files atoms.set_cell(small, scale_atoms=True) ase.io.write('POSCAR99pc',atoms,format='vasp', direct=1) atoms.set_cell(large, scale_atoms=True) ase.io.write('POSCAR101pc',atoms,format='vasp', direct=1 ) # copy the basic VASP files to the new directories directories = ['0x99pc','1x00pc','1x01pc'] files = ['KPOINTS','POTCAR','WAVECAR','CHGCAR'] for dir in directories: if not os.path.exists(dir): os.makedirs(dir) for file in files: if os.path.exists(file): shutil.copy(file,dir) # copy the new POSCAR files to the new directories shutil.copy('POSCAR','1x00pc') shutil.copy('POSCAR99pc','0x99pc/POSCAR') shutil.copy('POSCAR101pc','1x01pc/POSCAR') # Edit INCAR to create a single point calculations, and save in new directories EVQ_INCAR = 'INCAR_EVQ' bad_words = ['NSW', 'LVTOT', 'NELM ', 'ISTART', 'ICHARG'] with open('INCAR') as oldfile, open(EVQ_INCAR, 'w') as newfile: for line in oldfile: if not any(bad_word in line for bad_word in bad_words): newfile.write(line) newfile.write('ISTART = 0\nICHARGE = 2\nNSW = 0\nLVTOT = .TRUE.\nNELM = 60\n') # Save the new INCAR in directories shutil.copy(EVQ_INCAR,'1x00pc/INCAR') shutil.copy(EVQ_INCAR,'0x99pc/INCAR') shutil.copy(EVQ_INCAR,'1x01pc/INCAR')
def run_energy_eval(totalsol, calc_method='LAMMPS', fx_region=False, fit_scheme='totalenfit', STR='', static_calc=None): if calc_method == 'VASP': en = totalsol.get_potential_energy() calcb = Vasp(restart=True) totalsol = calcb.get_atoms() stress = calcb.read_stress() else: totcop = totalsol.copy() OUT = totalsol.calc.calculate(totalsol) totalsol = OUT['atoms'] totalsol.set_pbc(True) if fx_region: STR += 'Energy of fixed region calc = {0}\n'.format( OUT['thermo'][-1]['pe']) totalsol.set_calculator(static_calc) OUT = totalsol.calc.calculate(totalsol) totalsol = OUT['atoms'] totalsol.set_pbc(True) STR += 'Energy of static calc = {0}\n'.format( OUT['thermo'][-1]['pe']) en = OUT['thermo'][-1]['pe'] stress = numpy.array([ OUT['thermo'][-1][i] for i in ('pxx', 'pyy', 'pzz', 'pyz', 'pxz', 'pxy') ]) * (-1e-4 * GPa) if fit_scheme == 'enthalpyfit': pressure = totalsol.get_isotropic_pressure(stress) else: pressure = 0 volume = totalsol.get_volume() energy = en STR += 'Energy per atom = {0}\n'.format(energy / len(totalsol)) return totalsol, energy, pressure, volume, STR
def isif3(bulk,max_steps=20, np = 12, kp = 4,gga = 'pbesol'): calc_opt = Vasp(system = "System", istart = 1,iniwav = 1,icharg = 0,gamma=True,reciprocal=True, prec="Accurate", lreal = False, algo = "Normal", encut = 500.00, nelm = 200, ediff = 1e-6, xc=gga, kspacing=0.242, ediffg = -1e-2, nsw = max_steps, ibrion = 1, isif = 3, isym = 0, npar = np,kpar = kp, ismear = 0) bulk.set_calculator(calc_opt) energy = bulk.get_potential_energy() print("Energy: {}".format(energy)) cmdstring = "mv OUTCAR OUTCAR.i3" os.system(cmdstring) return energy
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 ase_run_vasp(mol, calc, job_dir, init_only=False): """ This is used to set a vasp calculation in an ASE-based script mode = 0: only create input files needed to run a vasp calculation mode """ wdir = os.getcwd() if init_only: if not os.path.isdir(job_dir): os.mkdir(job_dir) os.chdir(job_dir) mol.set_calculator(calc) calc.initialize(mol) calc.write_input(mol) os.chdir(wdir) return 0.0 if not os.path.isdir(job_dir): os.mkdir(job_dir) os.chdir(job_dir) mol.set_calculator(calc) else: os.chdir(job_dir) calc = Vasp(restart=True) mol = calc.get_atoms() try: ene = mol.get_potential_energy() except: print "ERROR: Fail when running vasp in " + job_dir os.system("touch ERROR") ene = 0.0 os.chdir(wdir) return ene
def test_vasp_relax(): slab = create_slab_with_constraints() calc = Vasp(xc='LDA', isif=0, nsw=3, ibrion=1, ediffg=-1e-3, lwave=False, lcharg=False) calc.calculate(slab) init_slab = create_slab_with_constraints() res = read('OUTCAR') assert np.allclose(res.positions[0], init_slab.positions[0]) assert not np.allclose(res.positions[2], init_slab.positions[2])
def write_input_files(self, at, label): global _chdir_lock vasp = Vasp(**self.vasp_args) vasp.initialize(at) # chdir not thread safe, so acquire global lock before using it orig_dir = os.getcwd() try: _chdir_lock.acquire() os.chdir(self.subdir) if os.path.exists('OUTCAR'): n = 1 while os.path.exists('OUTCAR.%d' % n): n += 1 shutil.copyfile('OUTCAR', 'OUTCAR.%d' % n) shutil.copyfile('POSCAR', 'POSCAR.%d' % n) write_vasp('POSCAR', vasp.atoms_sorted, symbol_count=vasp.symbol_count, vasp5='5' in self.exe) vasp.write_incar(at) vasp.write_potcar() vasp.write_kpoints() finally: os.chdir(orig_dir) _chdir_lock.release()
def output_cell_params(): import fnmatch from ase.calculators.vasp import Vasp outfile = 'cell_params.txt' fout = open(outfile,'w') prelim_matches = [] matches = [] for root, dirnames, filenames in os.walk('.'): for filename in fnmatch.filter(filenames, 'OUTCAR'): prelim_matches.append(os.path.abspath(root)) for dir in prelim_matches: if os.path.isfile(os.path.join(dir,"CONTCAR")): matches.append(dir) for dir in matches: os.chdir(dir) label = os.path.abspath(".") print>>fout, label print>>fout, "{:<14} {:^14} {:^14} {:^14} {:^14} {:^14} {:^14} ".format('volume','a','b','c','alpha','beta','gamma') calc = Vasp(restart=1) atoms = calc.get_atoms() params = asetools.cellparam(atoms) volume = atoms.get_volume() print>>fout, "{:<14} {:^14} {:^14} {:^14} {:^14} {:^14} {:^14} ".format(volume,params[0],params[1],params[2],params[3],params[4],params[5]) fout.close
def test_vasp2_xc(): """ Run some tests to ensure that the xc setting in the VASP calculator works. """ from ase.test.vasp import installed2 as installed from ase.calculators.vasp import Vasp2 as Vasp assert installed() def dict_is_subset(d1, d2): """True if all the key-value pairs in dict 1 are in dict 2""" for key, value in d1.items(): if key not in d2: return False elif d2[key] != value: return False else: return True calc_vdw = Vasp(xc='optb86b-vdw') assert dict_is_subset({ 'param1': 0.1234, 'param2': 1.0 }, calc_vdw.float_params) calc_hse = Vasp(xc='hse06', hfscreen=0.1, gga='RE', encut=400, sigma=0.5) assert dict_is_subset({ 'hfscreen': 0.1, 'encut': 400, 'sigma': 0.5 }, calc_hse.float_params) assert dict_is_subset({'gga': 'RE'}, calc_hse.string_params)
def write_incar(self, atoms, directory='./', **kwargs): Vasp.write_incar(self, atoms,directory=directory, **kwargs) incar = open(join(directory, 'INCAR'), 'a') vca_written=False if self.vca is not None and not vca_written: vcalist='' for symbol in self.symbol_count: vcalist+=' %.3f'%(self.vca.get(symbol[0], 1.0)) incar.write('VCA = %s\n'%(vcalist)) #if self.vca is not None and not vca_written: # print(self.vca) # vca=self.vca[self.sort] # list = [[1, vca[0]]] # for n in range(1, len(vca)): # if vca[n] == vca[n - 1]: # list[-1][0] += 1 # else: # list.append([1, vca[n]]) # incar.write(' vca= '.upper()) # [incar.write('%i*%.4f ' % (v[0], v[1])) for v in list] # incar.write('\n') incar.close()
def test_bad_pbc(atoms, pbc): """Test handling of PBC""" atoms.pbc = pbc check_cell(atoms) # We have a cell, so this should not raise # Check that our helper functions raises the expected error with pytest.raises(CalculatorSetupError): check_pbc(atoms) with pytest.raises(CalculatorSetupError): check_atoms(atoms) # Check we also raise in the calculator when launching # a calculation, but before VASP is actually executed calc = Vasp() atoms.calc = calc with pytest.raises(CalculatorSetupError): atoms.get_potential_energy()
def __main__(): bulk = read('POSCAR') #c = FixAtoms(mask=[s == 'Cu' for s in adsorbedH.get_chemical_symbols()]) #adsorbedH.set_constraint(c) calc = Vasp( encut=500, ispin=2, prec="Accurate", # ismear = -1, sigma=0.1, ediff=1e-8, ediffg=-0.01, algo="Fast", gga="RP", xc="PBE", kpts=(1, 1, 1), # isif = 0, # ibrion = 5, # nsw = 0, # nfree = 2 ) adsorbedH.set_calculator(calc) electronicenergy = adsorbedH.get_potential_energy() print("electronic energy is %.5f" % electronicenergy) vib = Vibrations(adsorbedH, indices=[23], delta=0.01, nfree=2) vib.run() print(vib.get_frequencies()) vib.summary() print(vib.get_mode(-1)) vib.write_mode(-1) vib_energies = vib.get_energies() thermo = HarmonicThermo(vib_energies=vib_energies, electronicenergy=electronicenergy) thermo.get_entropy(temperature=298.15) thermo.get_internal_energy(temperature=298.15) thermo.get_free_energy(temperature=298.15) #exitcode = os.system('vasp') exitcode = os.system('mpirun -np 4 vasp')
def test_vasp_input(require_vasp): """ Check VASP input handling """ from ase.calculators.vasp import Vasp # Molecules come with no unit cell atoms = molecule('CH4') calc = Vasp() with pytest.raises(RuntimeError): atoms.write('POSCAR') with pytest.raises(ValueError): atoms.calc = calc atoms.get_total_energy()
def test_vasp_no_cell(testdir): """Check missing cell handling.""" # Molecules come with no unit cell atoms = molecule('CH4') # We should not have a cell assert atoms.cell.rank == 0 with pytest.raises(CalculatorSetupError): check_cell(atoms) with pytest.raises(CalculatorSetupError): check_atoms(atoms) with pytest.raises(RuntimeError): atoms.write('POSCAR') calc = Vasp() atoms.calc = calc with pytest.raises(CalculatorSetupError): atoms.get_total_energy()
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 run_vasp(structure, vasp_settings): """ Run a single VASP calculation using an ASE calculator. This routine will make use of WAVECAR and CONTCAR files if they are available. Parameters ---------- structure : ASE atoms The structure used in the VASP calculation vasp_settings : dict The set of VASP options to apply with their values. Returns ------- structure : ase atoms The structure after performing this calculation. energy : float Energy of the structure in eV. result : string The result of the VASP calculation, either "converged", "unconverged", "vasp failure", or "timed out" --------------------------------------------------------------------------- Paul Sharp 25/09/2017 """ # Set files for calculation energy = 0.0 result = "" # Use ASE calculator -- the use of **kwargs in the function call allows us to set the desired arguments using a dictionary structure.set_calculator(Vasp(**vasp_settings)) # Run calculation, and consider any exception to be a VASP failure try: energy = structure.get_potential_energy() except: result = "vasp failure" return structure, energy, result
def test_vasp2_cell(): """ Check the unit cell is handled correctly """ from ase.test.vasp import installed2 as installed from ase.calculators.vasp import Vasp2 as Vasp from ase.build import molecule from ase.test import must_raise assert installed() # Molecules come with no unit cell atoms = molecule('CH4') calc = Vasp() with must_raise(ValueError): atoms.set_calculator(calc) atoms.get_total_energy()
def test_vasp2_cell(require_vasp): """ Check the unit cell is handled correctly """ import pytest from ase.test.calculator.vasp import installed2 as installed from ase.calculators.vasp import Vasp2 as Vasp from ase.build import molecule assert installed() # Molecules come with no unit cell atoms = molecule('CH4') calc = Vasp() with pytest.raises(ValueError): atoms.calc = calc atoms.get_total_energy()
def test_vasp_cell(): """ Check the unit cell is handled correctly """ from ase.calculators.vasp import Vasp from ase.build import molecule from ase.test import must_raise # Molecules come with no unit cell atoms = molecule('CH4') calc = Vasp() with must_raise(RuntimeError): atoms.write('POSCAR') with must_raise(ValueError): atoms.calc = calc atoms.get_total_energy()
def main(): if sys.version_info < (2, 7): raise unittest.SkipTest( 'read_xml requires Python version 2.7 or greater') assert installed() # simple test calculation of CO molecule d = 1.14 co = Atoms('CO', positions=[(0, 0, 0), (0, 0, d)], pbc=True) co.center(vacuum=5.) calc = Vasp(xc='PBE', prec='Low', algo='Fast', ismear=0, sigma=1., istart=0, lwave=False, lcharg=False, ldipol=True) co.set_calculator(calc) energy = co.get_potential_energy() forces = co.get_forces() dipole_moment = co.get_dipole_moment() # check that parsing of vasprun.xml file works conf = read('vasprun.xml') assert conf.calc.parameters['kpoints_generation'] assert conf.calc.parameters['sigma'] == 1.0 assert conf.calc.parameters['ialgo'] == 68 assert energy - conf.get_potential_energy() == 0.0 assert np.allclose(conf.get_forces(), forces) assert np.allclose(conf.get_dipole_moment(), dipole_moment, atol=1e-6) # Cleanup calc.clean()
def get_calculator(self): calc_paras = self.calc_paras if self.calc_type == 'vasp': from ase.calculators.vasp import Vasp calc = Vasp(xc = calc_paras.get('xc') # for MD, coarse prec prec = calc_paras.get('prec'), istart = calc_paras.getint('istart'), icharg = calc_paras.getint('icharg'), ispin = calc_paras.getint('ispin'), encut = calc_paras.getfloat('encut'), ismear = calc_paras.getint('ismear'), sigma = calc_paras.getfloat('sigma'), nelm = calc_paras.getint('nelm'), nelmin = calc_paras.getint('nelmin'), ediff = calc_paras.getint('ediff'), algo = calc_paras.get('algo'), lwave = calc_paras.getboolean('lwave'), lcharg = calc_paras.getboolean('lcharg'), lreal = calc_paras.get('lreal'), lplane = calc_paras.getboolean('lplane'), npar = calc_paras.getint('npar'), nsim = calc_paras.getint('nsim') )
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 set_bader_calc(atoms_obj, xc = "PBE", kpts = (1,1,1), encut = 400, ismear = 0, sigma = 0.1, ediff = 1e-4, prec = 'normal', lcharg = True, lwave = True, nelmin = 4, nelmdl = 6, npar = 2, algo = 'fast', lreal = 'auto', ispin = 2, magmom = 0, laechg = True, istart = 0): calc = Vasp(xc = xc, kpts = kpts, encut = encut, ismear = ismear, sigma = sigma, ediff = ediff, prec = prec, lcharg = lcharg, lwave = lwave, nelmin = nelmin, nelmdl = nelmdl, npar = npar, algo = algo, lreal = lreal, ispin = ispin, laechg = laechg) if istart == 0: calc.set(magmom = [magmom]*len(atoms_obj)) else: calc.set(istart = istart) print_vasp_param(calc) atoms_obj.set_calculator(calc) return calc
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
from ase.calculators.vasp import Vasp from ase.build import bulk Al = bulk('Al', 'fcc', a=4.5, cubic=True) def check_kpoints_line(n, contents): """Assert the contents of a line""" with open('KPOINTS', 'r') as f: lines = f.readlines() assert lines[n] == contents # Default to (1 1 1) calc = Vasp(gamma=True) calc.write_kpoints() check_kpoints_line(2, 'Gamma\n') check_kpoints_line(3, '1 1 1 \n') calc.clean() # 3-tuple prints mesh calc = Vasp(gamma=False, kpts=(4, 4, 4)) calc.write_kpoints() check_kpoints_line(2, 'Monkhorst-Pack\n') check_kpoints_line(3, '4 4 4 \n') calc.clean() # Auto mode calc = Vasp(kpts=20) calc.write_kpoints()
else: outt=find_defects(totalsol,Optimizer.solidbulk,Optimizer.sf,atomlistcheck=Optimizer.atomlist,trackvacs=Optimizer.trackvacs,trackswaps=Optimizer.trackswaps,debug=False) individ[0]=outt[0] bul=outt[1] individ.vacancies = outt[2] individ.swaps = outt[3] STR += outt[4] indiv=individ[0] else: top,bul=find_top_layer(totalsol,Optimizer.surftopthick) indiv=top.copy() individ[0]=top.copy() else: if Optimizer.calc_method=='VASP': en=totalsol.get_potential_energy() calcb=Vasp(restart=True) totalsol=calcb.get_atoms() stress=calcb.read_stress() else: OUT=indiv.calc.calculate(indiv) en=OUT['thermo'][-1]['pe'] #indiv.set_positions(OUT['atoms'].get_positions()) #indiv.set_cell(OUT['atoms'].get_cell()) indiv=OUT['atoms'] indiv.set_pbc(True) stress=numpy.array([OUT['thermo'][-1][i] for i in ('pxx','pyy','pzz','pyz','pxz','pxy')])*(-1e-4*GPa) if Optimizer.fitness_scheme == 'enthalpyfit': pressure=indiv.get_isotropic_pressure(stress) cell_max=numpy.maximum.reduce(indiv.get_positions()) cell_min=numpy.minimum.reduce(indiv.get_positions()) cell=cell_max-cell_min
def set_results(self, atoms): with work_dir(self.working_dir): #print('set_results') Vasp.set_results(self, atoms)
from ase import Atoms from ase.lattice import surface from ase.constraints import FixAtoms from ase.calculators.vasp import Vasp from ase.visualize import view from ase.io import write from ase.io import read #sigma=0.01 for gases and edif=13-8 calc = Vasp(xc='PBE', kpts=(3,3,1), lwave=False, lcharg=False,lvtot=False, nwrite=1 , encut=400, algo='Fast', ismear=0, sigma=0.0031, voskown=1, istart=0, nelm=400, nelmdl=-10, ediff=1e-8, ispin=2 ,nsw=1, isif=2, ibrion=5, nfree=2, potim=0.015, ediffg=-0.05, isym=0 ,lvdw=True, vdw_version=3 ,lreal='Auto') slab = read('../CONTCAR') slab.center(vacuum=20.0,axis=2) view(slab) # View the slab, frozen atoms will be marked with a "X" #slab.set_calculator(calc) calc.initialize(slab) calc.write_incar(slab) calc.write_potcar() calc.write_kpoints() write('POSCAR', calc.atoms_sorted) # this will write a "sorted" POSCAR
from vibrations import Vibrations from ase.calculators.vasp import Vasp from ase.io import read vasp_calc = Vasp(istart=0, # Start from scratch. gga='PE', # Method. kpts = (1,1,1), # k-points. gamma = True, # Gamma-centered (defaults to Monkhorst-Pack) encut=400, # Cutoff. ismear=1, # Smearing sigma = 0.1, # Smearing ediffg=-0.015, # Convergence criteria. ediff=1e-6, # Convergence criteria. nsw=250, # Number of optimization steps. nelmin=10, # Min. electronic steps. nelm=250, # Max. electronic steps. prec='Accurate', # Precision. ibrion=2, # Optimization algorithm. algo = 'Fast', # Optimization algorithm. ispin=1, # Spin-polarization. #npar=12, # Parallelization. #ncore=4, # Parallelization. lwave=False, # Output. lcharg=False, # Output. nfree=2, # Degrees of freedom. isym=False, # Remove symmetry. lreal=True # Reciprocal space. ) vib = Vibrations(ase_calculator=vasp_calc, anharmonic_correction=True)
def test_vasp2_wdir(require_vasp): """ Run tests to ensure that the VASP txt and label arguments function correctly, i.e. correctly sets the working directories and works in that directory. This is conditional on the existence of the ASE_VASP_COMMAND, VASP_COMMAND or VASP_SCRIPT environment variables """ import filecmp import os from ase.test.calculator.vasp import installed2 as installed from ase import Atoms from ase.calculators.vasp import Vasp2 as Vasp assert installed() def compare_paths(path1, path2): assert os.path.abspath(path1) == os.path.abspath(path2) # Test setup system, borrowed from vasp_co.py d = 1.14 atoms = Atoms('CO', positions=[(0, 0, 0), (0, 0, d)], pbc=True) atoms.center(vacuum=5.) file1 = '_vasp_dummy_str.out' file2 = '_vasp_dummy_io.out' file3 = '_vasp_dummy_2.out' testdir = '_dummy_txt_testdir' label = os.path.join(testdir, 'vasp') # Test settings = dict(label=label, xc='PBE', prec='Low', algo='Fast', ismear=0, sigma=1., istart=0, lwave=False, lcharg=False) # Make 2 copies of the calculator object calc = Vasp(**settings) calc2 = Vasp(**settings) # Check the calculator path is the expected path compare_paths(calc.directory, testdir) calc.set(txt=file1) atoms.calc = calc en1 = atoms.get_potential_energy() # Check that the output files are in the correct directory for fi in ['OUTCAR', 'CONTCAR', 'vasprun.xml']: fi = os.path.join(testdir, fi) assert os.path.isfile(fi) # We open file2 in our current directory, so we don't want it to write # in the label directory with open(file2, 'w') as f: calc2.set(txt=f) atoms.calc = calc2 atoms.get_potential_energy() # Make sure the two outputfiles are identical assert filecmp.cmp(os.path.join(calc.directory, file1), file2) # Test restarting from working directory in test directory label2 = os.path.join(testdir, file3) calc2 = Vasp(restart=label, label=label2) # Check the calculator path is the expected path compare_paths(calc2.directory, testdir) assert not calc2.calculation_required(calc2.atoms, ['energy', 'forces']) en2 = calc2.get_potential_energy() # Check that the restarted calculation didn't run, i.e. write to output file assert not os.path.isfile(os.path.join(calc.directory, file3)) # Check that we loaded energy correctly assert en1 == en2
import os import ase from ase.calculators.vasp import Vasp mof = ase.io.read('POSCAR.init') calc_opt = Vasp(system="MOF-7", istart=0, iniwav=1, icharg=0, gamma=True, reciprocal=True, prec="Accurate", lreal=False, algo="Normal", encut=500.00, nelm=200, ediff=1e-6, gga="PS", kpts=(1, 1, 1), ediffg=1e-3, nsw=100, ibrion=1, isif=3, isym=2, ismear=0) mof.set_calculator(calc_opt) energy = mof.get_potential_energy() print("Energy: ", energy)
def calcs(calc_name): """ Define the default calculators for relaxations Note: it should not include the kpts, gamma, or images keywords! Args: calc_name (string): name of calculator Returns: calc (dict): ASE Vasp calculator dictionary """ if calc_name == 'scf_test': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=defaults['ediff'], nelm=defaults['nelm'], nelmin=defaults['nelmin'], lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=True, lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], nsw=0, istart=0, ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'ase_bfgs': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=defaults['ediff'], nelm=defaults['nelm'], nelmin=defaults['nelmin'], lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=True, lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'isif2_lowacc': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=defaults['ediff'], nelm=defaults['nelm'], nelmin=defaults['nelmin'], lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=True, ibrion=2, isif=2, nsw=250, ediffg=-0.05, lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'isif2_medacc': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=1e-6, nelm=defaults['nelm'], nelmin=8, lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=True, ibrion=3, iopt=7, potim=0, isif=2, nsw=defaults['nsw'], ediffg=-0.05, lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'isif2_highacc': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], encut=defaults['encut'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=1e-6, nelm=defaults['nelm'], nelmin=8, lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=True, ibrion=3, iopt=7, potim=0, isif=2, nsw=defaults['nsw'], ediffg=defaults['ediffg'], lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'isif3_lowacc': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], encut=defaults['encut'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=1e-6, nelm=defaults['nelm'], nelmin=defaults['nelmin'], lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=True, ibrion=2, isif=3, nsw=30, ediffg=defaults['ediffg'], lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'isif3_highacc': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], encut=defaults['encut'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=1e-6, nelm=defaults['nelm'], nelmin=defaults['nelmin'], lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=True, ibrion=2, isif=3, nsw=30, ediffg=defaults['ediffg'], lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'final_spe': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], encut=defaults['encut'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=1e-6, nelm=defaults['nelm'], lreal=False, ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=True, laechg=True, lwave=True, nsw=0, lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], addgrid=False, ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'cineb_lowacc': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=1e-6, nelm=100, nelmin=defaults['nelmin'], lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=False, ibrion=3, potim=0, iopt=1, nsw=defaults['nsw'], ediffg=-1.0, lclimb=True, lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], ichain=0, ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'dimer_lowacc': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=1e-8, nelm=defaults['nelm'], nelmin=defaults['nelmin'], lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=True, ibrion=3, potim=0, iopt=7, nsw=defaults['nsw']*4, ediffg=-0.075, lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], ichain=2, ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'dimer_medacc': calc = Vasp( xc=defaults['xc'], setups=defaults['setups'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=1e-8, nelm=defaults['nelm'], nelmin=defaults['nelmin'], lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=True, ibrion=3, potim=0, iopt=7, nsw=defaults['nsw']*2, ediffg=-0.075, lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], ichain=2, ldau_luj=defaults['ldau_luj'] ) elif calc_name == 'dimer_highacc': calc = Vasp( xc=defaults['xc'], encut=defaults['encut'], setups=defaults['setups'], ivdw=defaults['ivdw'], prec=defaults['prec'], algo=defaults['algo'], ediff=1e-8, nelm=defaults['nelm'], nelmin=defaults['nelmin'], lreal=defaults['lreal'], ismear=defaults['ismear'], sigma=defaults['sigma'], lcharg=False, lwave=True, ibrion=3, potim=0, iopt=7, nsw=defaults['nsw']*2, ediffg=defaults['ediffg'], lorbit=defaults['lorbit'], isym=defaults['isym'], symprec=defaults['symprec'], ichain=2, ldau_luj=defaults['ldau_luj'] ) else: raise ValueError('Out of range for calculators') return calc
d = 1.14 atoms = Atoms('CO', positions=[(0, 0, 0), (0, 0, d)], pbc=True) atoms.center(vacuum=5.) # Test settings = dict(xc='PBE', prec='Low', algo='Fast', ismear=0, sigma=1., istart=0, lwave=False, lcharg=False) calc = Vasp(**settings) atoms.set_calculator(calc) en1 = atoms.get_potential_energy() # Make a parameter change to the calculator calc.set(sigma=0.5) # Check that we capture a change for float params assert calc.check_state(atoms) == ['float_params'] assert calc.calculation_required(atoms, ['energy', 'forces']) en2 = atoms.get_potential_energy() # The change in sigma should result in a small change in energy
from amptorch.model import CustomMSELoss import multiprocessing as mp if __name__ == "__main__": random.seed(1) mp.set_start_method("spawn") emt_calc = EMT() dft_calc = Vasp(prec='Normal', algo='Normal', ncore=4, xc='PBE', gga='RP', lreal=False, ediff=1e-4, ispin=1, nelm=100, encut=400, lwave=False, lcharg=False, nsw=0, kpts=(1, 1, 1)) # Define initial set of images, can be as few as 1. If 1, make sure to slab = fcc100("Cu", size=(3, 3, 3)) ads = molecule("CO") add_adsorbate(slab, ads, 3, offset=(1, 1)) cons = FixAtoms(indices=[atom.index for atom in slab if (atom.tag == 3)]) slab.set_constraint(cons) slab.center(vacuum=13.0, axis=2) slab.set_pbc(True)
import io, os from ase.parallel import rank, size # Read initial and final states: initial = read('initial.traj') final = read('final.traj') numOfImages = 9 # Set calculators: images = [initial] constraint = FixAtoms(mask=[atom.tag > 2 for atom in initial]) calc = Vasp(xc='PBE', lreal='Auto', kpts=[1, 1, 1], ismear=1, sigma=0.2, algo='fast', istart=0, npar=8, encut=300) n = size // numOfImages #j = rank * numOfImages // size j = (((2 * rank) + 2) // n) - 1 #calc = EMT() for i in range(0, numOfImages): #determines the number of nodes image = initial.copy() if i == j: image.set_calculator(calc) image.set_constraint(constraint) images.append(image) images.append(final)
def read_neb_calculator(): """Read calculator from the current working directory. Static method that returns a :mod:`jasp.Jasp` calculator. """ log.debug('Entering read_neb_calculator in {0}'.format(os.getcwd())) calc = Vasp() calc.vaspdir = os.getcwd() calc.read_incar() calc.read_kpoints() if calc.in_queue(): return ([None for i in range(calc.int_params['images'] + 2)], [None for i in range(calc.int_params['images'] + 2)]) # set default functional # if both gga and xc are not specified if calc.string_params['gga'] is None: if calc.input_params['xc'] is None: calc.input_params['xc'] = 'PBE' images = [] log.debug('calc.int_params[images] = %i', calc.int_params['images']) # Add 2 to IMAGES flag from INCAR to get # first and last images for i in range(calc.int_params['images'] + 2): log.debug('reading neb calculator: 0%i', i) cwd = os.getcwd() os.chdir('{0}'.format(str(i).zfill(2))) if os.path.exists('CONTCAR'): f = open('CONTCAR') if f.read() == '': log.debug('CONTCAR was empty, vasp probably still running') fname = 'POSCAR' else: fname = 'CONTCAR' else: fname = 'POSCAR' atoms = read(fname, format='vasp') f = open('ase-sort.dat') sort, resort = [], [] for line in f: s, r = [int(x) for x in line.split()] sort.append(s) resort.append(r) images += [atoms[resort]] os.chdir(cwd) log.debug('len(images) = %i', len(images)) calc.neb_images = images calc.neb_nimages = len(images) - 2 calc.neb = True return calc
def clean(self): with work_dir(self.working_dir) : Vasp.clean(self)
from __future__ import division import numpy as np from ase import Atoms from ase.io.trajectory import Trajectory as traj from ase.lattice import surface from ase.constraints import FixAtoms from ase.optimize import LBFGS from ase.calculators.vasp import Vasp from ase.io.vasp import write_vasp from ase.visualize import view from ase.io import write calc = Vasp(xc='PBE', kpts=(1,1,1), nwrite=1, lwave=False, lcharg=False,lvtot=False , encut=400, algo='Fast', ismear=0, sigma=0.003, voskown=1, istart=0, nelm=400, nelmdl=-10, ediff=1e-6, ispin=2 ,nsw=1000, isif=2, ibrion=1, nfree=2, potim=0.2,lvdw=True, vdw_version=3 ,isym=0 ,lreal='Auto') # Create a c(2x2) surface with 4 layers and 14 Angstrom of vacuum d=0.9575 t = np.pi/180*104.51 molecule = Atoms('H2O', positions=[(d, 0, 0),(d * np.cos(t), d * np.sin(t), 0),(0, 0, 0)]) molecule.center(vacuum=20.0) view(molecule) # View the slab, frozen atoms will be marked with a "X" #slab.set_calculator(calc) calc.initialize(molecule)
def set_results(self, atoms): with work_dir(self.working_dir) : #print('set_results') Vasp.set_results(self, atoms)
import numpy as np def array_almost_equal(a1, a2, tol=np.finfo(type(1.0)).eps): """Replacement for old numpy.testing.utils.array_almost_equal.""" return (np.abs(a1 - a2) < tol).all() d = 1.14 co = Atoms('CO', positions=[(0, 0, 0), (0, 0, d)], pbc=True) co.center(vacuum=5.) calc = Vasp( xc = 'PBE', prec = 'Low', algo = 'Fast', ismear= 0, sigma = 1., istart = 0, lwave = False, lcharg = False) co.set_calculator(calc) en = co.get_potential_energy() assert abs(en + 14.918933) < 1e-4 # Secondly, check that restart from the previously created VASP output works calc2 = Vasp(restart=True) co2 = calc2.get_atoms() # Need tolerance of 1e-14 because VASP itself changes coordinates
G = points['Gamma'] A = points['A'] M = points['M'] H = points['H'] L = points['L'] kpoints, x, X = get_bandpath([A,L,M,G,A,H], zns.cell, npoints=60) # Point names for plot axis point_names = ['A','L','M','G','A','H'] # FROM HERE ON NO REAL INPUT IS NEEDED, UNLESS ONE WISHES TO # CHANGE SOME VASP INCAR PARAMETERS # Define the first calculation calc_single = Vasp(system = "Generic System Name", istart = 0,iniwav = 1,icharg = 0,gamma=True,reciprocal=True, prec="Accurate", lreal = False, algo = "Normal", encut = 500.00, nelm = 200, ediff = 1e-6, gga = "PS",kpts=(4,4,4), ediffg = 1e-3, nsw = 0, ibrion = 1, isif = 3, isym = 2, ismear = -5) zns.set_calculator(calc_single) energy = zns.get_potential_energy() print("Energy: ",energy) print("Moving to band structure calculation") # Get the kpoints from run 1 and make the VASP kpoint file for run 2 ibzkpts = calc_single.get_ibz_k_points() weights = calc_single.read_k_point_weights() kpts = np.concatenate((ibzkpts,kpoints)) dummy = np.zeros(shape=(len(kpts),4)) for i in range(len(ibzkpts)): dummy[i,3] = weights[i]
def clean(self): with work_dir(self.working_dir): Vasp.clean(self)
def eval_energy(input): """Function to evaluate energy of an individual Inputs: input = [Optimizer class object with parameters, Individual class structure to be evaluated] Outputs: energy, bul, individ, signal energy = energy of Individual evaluated bul = bulk structure of Individual if simulation structure is Defect individ = Individual class structure evaluated signal = string of information about evaluation """ if input[0]==None: energy=0 bul=0 individ=0 rank = MPI.COMM_WORLD.Get_rank() signal='Evaluated none individual on '+repr(rank)+'\n' else: [Optimizer, individ]=input if Optimizer.calc_method=='MAST': energy = individ.energy bul = individ.energy signal = 'Recieved MAST structure\n' else: if Optimizer.parallel: rank = MPI.COMM_WORLD.Get_rank() if not Optimizer.genealogy: STR='----Individual ' + str(individ.index)+ ' Optimization----\n' else: STR='----Individual ' + str(individ.history_index)+ ' Optimization----\n' indiv=individ[0] if 'EE' in Optimizer.debug: debug = True else: debug = False if debug: write_xyz(Optimizer.debugfile,indiv,'Recieved by eval_energy') Optimizer.debugfile.flush() if Optimizer.structure=='Defect': indi=indiv.copy() if Optimizer.alloy==True: bulk=individ.bulki else: bulk=individ.bulko nat=indi.get_number_of_atoms() csize=bulk.get_cell() totalsol=Atoms(cell=csize, pbc=True) totalsol.extend(indi) totalsol.extend(bulk) for sym,c,m,u in Optimizer.atomlist: nc=len([atm for atm in totalsol if atm.symbol==sym]) STR+='Defect configuration contains '+repr(nc)+' '+repr(sym)+' atoms\n' elif Optimizer.structure=='Surface': totalsol=Atoms() totalsol.extend(indiv) nat=indiv.get_number_of_atoms() totalsol.extend(individ.bulki) for sym,c,m,u in Optimizer.atomlist: nc=len([atm for atm in totalsol if atm.symbol==sym]) STR+='Surface-Bulk configuration contains '+repr(nc)+' '+repr(sym)+' atoms\n' cell=numpy.maximum.reduce(indiv.get_cell()) totalsol.set_cell([cell[0],cell[1],500]) totalsol.set_pbc([True,True,False]) if Optimizer.constrain_position: ts = totalsol.copy() indc,indb,vacant,swap,stro = find_defects(ts,Optimizer.solidbulk,0) sbulk = Optimizer.solidbulk.copy() bcom = sbulk.get_center_of_mass() #totalsol.translate(-bulkcom) #indc.translate(-bulkcom) #totalsol.append(Atom(position=[0,0,0])) # for one in indc: # index = [atm.index for atm in totalsol if atm.position[0]==one.position[0] and atm.position[1]==one.position[1] and atm.position[2]==one.position[2]][0] # if totalsol.get_distance(-1,index) > Optimizer.sf: # r = random.random() # totalsol.set_distance(-1,index,Optimizer.sf*r,fix=0) # totalsol.pop() # totalsol.translate(bulkcom) com = indc.get_center_of_mass() dist = (sum((bcom[i] - com[i])**2 for i in range(3)))**0.5 if dist > Optimizer.sf: STR+='Shifting structure to within region\n' r = random.random()*Optimizer.sf comv = numpy.linalg.norm(com) ncom = [one*r/comv for one in com] trans = [ncom[i]-com[i] for i in range(3)] indices = [] for one in indc: id = [atm.index for atm in totalsol if atm.position[0]==one.position[0] and atm.position[1]==one.position[1] and atm.position[2]==one.position[2]][0] totalsol[id].position += trans # Check for atoms that are too close min_len=0.7 #pdb.set_trace() if not Optimizer.fixed_region: if Optimizer.structure=='Defect' or Optimizer.structure=='Surface': cutoffs=[2.0 for one in totalsol] nl=NeighborList(cutoffs,bothways=True,self_interaction=False) nl.update(totalsol) for one in totalsol[0:nat]: nbatoms=Atoms() nbatoms.append(one) indices, offsets=nl.get_neighbors(one.index) for index, d in zip(indices,offsets): index = int(index) sym=totalsol[index].symbol pos=totalsol[index].position + numpy.dot(d,totalsol.get_cell()) at=Atom(symbol=sym,position=pos) nbatoms.append(at) while True: dflag=False for i in range(1,len(nbatoms)): d=nbatoms.get_distance(0,i) if d < min_len: nbatoms.set_distance(0,i,min_len+.01,fix=0.5) STR+='--- WARNING: Atoms too close (<0.7A) - Implement Move ---\n' dflag=True if dflag==False: break for i in range(len(indices)): totalsol[indices[i]].position=nbatoms[i+1].position totalsol[one.index].position=nbatoms[0].position nl.update(totalsol) if debug: write_xyz(Optimizer.debugfile,totalsol,'After minlength check') Optimizer.debugfile.flush() else: for i in range(len(indiv)): for j in range(len(indiv)): if i != j: d=indiv.get_distance(i,j) if d < min_len: indiv.set_distance(i,j,min_len,fix=0.5) STR+='--- WARNING: Atoms too close (<0.7A) - Implement Move ---\n' if debug: write_xyz(Optimizer.debugfile,indiv,'After minlength check') Optimizer.debugfile.flush() # Set calculator to use to get forces/energies if Optimizer.parallel: calc = setup_calculator(Optimizer) if Optimizer.fixed_region: pms=copy.deepcopy(calc.parameters) try: pms['mass'][len(pms['mass'])-1] += '\ngroup RO id >= '+repr(nat)+'\nfix freeze RO setforce 0.0 0.0 0.0\n' except KeyError: pms['pair_coeff'][0] += '\ngroup RO id >= '+repr(nat)+'\nfix freeze RO setforce 0.0 0.0 0.0\n' calc = LAMMPS(parameters=pms, files=calc.files, keep_tmp_files=calc.keep_tmp_files, tmp_dir=calc.tmp_dir) lmin = copy.copy(Optimizer.lammps_min) Optimizer.lammps_min = None Optimizer.static_calc = setup_calculator(Optimizer) Optimizer.lammps_min = lmin else: calc=Optimizer.calc if Optimizer.structure=='Defect' or Optimizer.structure=='Surface': totalsol.set_calculator(calc) totalsol.set_pbc(True) else: indiv.set_calculator(calc) indiv.set_pbc(True) #Current bug in ASE optimizer-Lammps prevents pbc=false if Optimizer.structure=='Cluster': indiv.set_cell([500,500,500]) indiv.translate([250,250,250]) cwd=os.getcwd() # Perform Energy Minimization if not Optimizer.parallel: Optimizer.output.flush() if Optimizer.ase_min == True: try: if Optimizer.structure=='Defect' or Optimizer.structure=='Surface': dyn=BFGS(totalsol) else: dyn=BFGS(indiv) dyn.run(fmax=Optimizer.ase_min_fmax, steps=Optimizer.ase_min_maxsteps) except OverflowError: STR+='--- Error: Infinite Energy Calculated - Implement Random ---\n' box=Atoms() indiv=gen_pop_box(Optimizer.natoms, Optimizer.atomlist, Optimizer.size) indiv.set_calculator(calc) dyn=BFGS(indiv) dyn.run(fmax=fmax, steps=steps) except numpy.linalg.linalg.LinAlgError: STR+='--- Error: Singular Matrix - Implement Random ---\n' indiv=gen_pop_box(Optimizer.natoms, Optimizer.atomlist, Optimizer.size) indiv.set_calculator(calc) dyn=BFGS(indiv) dyn.run(fmax=fmax, steps=steps) # Get Energy of Minimized Structure if Optimizer.structure=='Defect' or Optimizer.structure=='Surface': en=totalsol.get_potential_energy() #force=numpy.maximum.reduce(abs(totalsol.get_forces())) if Optimizer.fitness_scheme == 'enthalpyfit': pressure=totalsol.get_isotropic_pressure(totalsol.get_stress()) cell_max=numpy.maximum.reduce(totalsol.get_positions()) cell_min=numpy.minimum.reduce(totalsol.get_positions()) cell=cell_max-cell_min volume=cell[0]*cell[1]*cell[2] else: pressure=0 volume=0 na=totalsol.get_number_of_atoms() ena=en/na energy=en individ[0]=totalsol[0:nat] bul=totalsol[(nat):len(totalsol)] STR+='Number of positions = '+repr(len(bul)+len(individ[0]))+'\n' individ[0].set_cell(csize) indiv=individ[0] else: en=indiv.get_potential_energy() if Optimizer.fitness_scheme == 'enthalpyfit': pressure=indiv.get_isotropic_pressure(indiv.get_stress()) cell_max=numpy.maximum.reduce(indiv.get_positions()) cell_min=numpy.minimum.reduce(indiv.get_positions()) cell=cell_max-cell_min volume=cell[0]*cell[1]*cell[2] else: pressure=0 volume=0 na=indiv.get_number_of_atoms() ena=en/na energy=ena individ[0]=indiv bul=0 else: if Optimizer.structure=='Defect' or Optimizer.structure=='Surface': if Optimizer.calc_method=='VASP': en=totalsol.get_potential_energy() calcb=Vasp(restart=True) totalsol=calcb.get_atoms() stress=calcb.read_stress() else: try: totcop=totalsol.copy() if debug: write_xyz(Optimizer.debugfile,totcop,'Individual sent to lammps') OUT=totalsol.calc.calculate(totalsol) totalsol=OUT['atoms'] totalsol.set_pbc(True) if Optimizer.fixed_region: if debug: print 'Energy of fixed region calc = ', OUT['thermo'][-1]['pe'] totalsol.set_calculator(Optimizer.static_calc) OUT=totalsol.calc.calculate(totalsol) totalsol=OUT['atoms'] totalsol.set_pbc(True) if debug: print 'Energy of static calc = ', OUT['thermo'][-1]['pe'] en=OUT['thermo'][-1]['pe'] stress=numpy.array([OUT['thermo'][-1][i] for i in ('pxx','pyy','pzz','pyz','pxz','pxy')])*(-1e-4*GPa) #force=numpy.maximum.reduce(abs(totalsol.get_forces())) if debug: write_xyz(Optimizer.debugfile,totalsol,'After Lammps Minimization') Optimizer.debugfile.flush() except Exception, e: os.chdir(cwd) STR+='WARNING: Exception during energy eval:\n'+repr(e)+'\n' f=open('problem-structures.xyz','a') write_xyz(f,totcop,data='Starting structure hindex='+individ.history_index) write_xyz(f,totalsol,data='Lammps Min structure') en=10 stress=0 f.close() if Optimizer.fitness_scheme == 'enthalpyfit': pressure=totalsol.get_isotropic_pressure(stress) cell_max=numpy.maximum.reduce(totalsol.get_positions()) cell_min=numpy.minimum.reduce(totalsol.get_positions()) cell=cell_max-cell_min volume=cell[0]*cell[1]*cell[2] else: pressure=totalsol.get_isotropic_pressure(stress) volume=0 na=totalsol.get_number_of_atoms() ena=en/na energy=en if Optimizer.structure=='Defect': if Optimizer.fixed_region==True or Optimizer.finddefects==False: individ[0]=totalsol[0:nat] bul=totalsol[(nat):len(totalsol)] individ[0].set_cell(csize) else: if 'FI' in Optimizer.debug: outt=find_defects(totalsol,Optimizer.solidbulk,Optimizer.sf,atomlistcheck=Optimizer.atomlist,trackvacs=Optimizer.trackvacs,trackswaps=Optimizer.trackswaps,debug=Optimizer.debugfile) else: outt=find_defects(totalsol,Optimizer.solidbulk,Optimizer.sf,atomlistcheck=Optimizer.atomlist,trackvacs=Optimizer.trackvacs,trackswaps=Optimizer.trackswaps,debug=False) individ[0]=outt[0] bul=outt[1] individ.vacancies = outt[2] individ.swaps = outt[3] STR += outt[4] indiv=individ[0] else: top,bul=find_top_layer(totalsol,Optimizer.surftopthick) indiv=top.copy() individ[0]=top.copy() else: