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 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 write_interstitials(ats, ttol=0.5): vasp_args = dict(xc='PBE', amix=0.01, amin=0.001, bmix=0.001, amix_mag=0.01, bmix_mag=0.001, kpts=[3, 3, 3], kpar=6, lreal='auto', ibrion=1, nsw=50, nelmdl=-15, ispin=2, prec='High', nelm=100, algo='VeryFast', npar=24, lplane=False, lwave=False, lcharg=False, istart=0, voskown=0, ismear=1, sigma=0.1, isym=2) vasp = Vasp(**vasp_args) vasp.initialize(ats) write_vasp('POSCAR', vasp.atoms_sorted, symbol_count=vasp.symbol_count, vasp5=True)
def test_vasp_charge(): """ Run VASP tests to ensure that determining number of electrons from user-supplied charge works correctly. This is conditional on the existence of the VASP_COMMAND or VASP_SCRIPT environment variables. """ from ase.build import bulk from ase.calculators.vasp import Vasp from ase.test import must_raise from ase.test.vasp import installed assert installed() system = bulk('Al', 'fcc', a=4.5, cubic=True) # Dummy calculation to let VASP determine default number of electrons calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False) calc.calculate(system) default_nelect_from_vasp = calc.get_number_of_electrons() assert default_nelect_from_vasp == 12 # Make sure that no nelect was written into INCAR yet (as it wasn't necessary) calc = Vasp() calc.read_incar() assert calc.float_params['nelect'] is None # Compare VASP's output nelect from before minus charge to default nelect # determined by us minus charge charge = -2 calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False, charge=charge) calc.initialize(system) calc.write_input(system) calc.read_incar() assert calc.float_params['nelect'] == default_nelect_from_vasp - charge # Test that conflicts between explicitly given nelect and charge are detected with must_raise(ValueError): calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False, nelect=default_nelect_from_vasp-charge+1, charge=charge) calc.calculate(system) # Test that nothing is written if charge is 0 and nelect not given calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False, charge=0) calc.initialize(system) calc.write_input(system) calc.read_incar() assert calc.float_params['nelect'] is None # Test that explicitly given nelect still works as expected calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False, nelect=15) calc.calculate(system) assert calc.get_number_of_electrons() == 15
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 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 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()
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
calc.calculate(system) default_nelect_from_vasp = calc.get_number_of_electrons() assert default_nelect_from_vasp == 12 # Compare VASP's output nelect from before + net charge to default nelect # determined by us + net charge with must_warn(FutureWarning): net_charge = -2 calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False, net_charge=net_charge) calc.initialize(system) calc.write_input(system) calc.read_incar() assert calc.float_params['nelect'] == default_nelect_from_vasp + net_charge # Test that conflicts between explicitly given nelect and net charge are # detected with must_raise(ValueError): with must_warn(FutureWarning): calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False, nelect=default_nelect_from_vasp + net_charge + 1,
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) calc.write_incar(molecule) calc.write_potcar() calc.write_kpoints() write('POSCAR', calc.atoms_sorted) # this will write a "sorted" POSCAR
def gamma_surf(h_pos=np.array([1.41, 1.500, 22.48])): """ :method:`gamma_surf` generates a set of directories with the upper half unit cell displaced along a certain distance along a particular lattice vector. Hydrogens can be added by setting vector in h_pos. TODO: h_pos should be a list of vectors and atom type for this to be more general. """ vasp_exe = '/projects/SiO2_Fracture/iron/vasp.bgq' crack_geom = { 'cleavage_plane': (1, 1, 0), 'crack_front': (1, -1, 0), 'crack_direction': (0, 0, 1) } crack_direction = crack_geom['crack_direction'] crack_front = crack_geom['crack_front'] cleavage_plane = crack_geom['cleavage_plane'] fe_unit = BodyCenteredCubic( directions=[crack_direction, crack_front, cleavage_plane], size=(1, 1, 1), symbol='Fe', pbc=(1, 1, 1), latticeconstant=2.83) nunits = 8 fe_bulk = BodyCenteredCubic( directions=[crack_direction, crack_front, cleavage_plane], size=(2, 2, nunits), symbol='Fe', pbc=(1, 1, 1), latticeconstant=2.83) fe_unit = Atoms(fe_unit) fe_bulk = Atoms(fe_bulk) ycut = 5.0 + float(nunits) / 2.0 * fe_unit.lattice[2, 2] fe_bulk.center(vacuum=5.0, axis=2) print 'lattice', fe_bulk.lattice[1, 1] print 'ycut', ycut a1 = fe_unit.lattice[0, 0] a2 = fe_unit.lattice[1, 1] POT_DIR = os.environ['POTDIR'] eam_pot = os.path.join(POT_DIR, 'PotBH.xml') r_scale = 1.00894848312 #eam_pot = os.path.join(POT_DIR, 'iron_mish.xml') #r_scale = 1.0129007626 pot = Potential( 'IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale), param_filename=eam_pot) fe_bulk.set_calculator(pot) print 'Bulk Energy', fe_bulk.get_potential_energy() refen = fe_bulk.get_potential_energy() A = fe_bulk.get_volume() / fe_bulk.lattice[2, 2] vasp_args = dict( xc='PBE', amix=0.01, amin=0.001, bmix=0.001, amix_mag=0.01, bmix_mag=0.001, kpts=[8, 8, 1], kpar=32, lreal='auto', ibrion=2, nsw=40, nelmdl=-15, ispin=2, nelm=100, algo='VeryFast', npar=8, lplane=False, lwave=False, lcharg=False, istart=0, voskown=1, ismear=1, sigma=0.1, isym=2) # possibly try iwavpr=12, should be faster if it works dir_name = 'b111shiftsym' #dir_name = 'b001shiftsym' f = open('_patdon123{0}H1.dat'.format(dir_name), 'w') WRITEVASP = True a0 = 2.83 for inum, ashift in enumerate(np.arange(0, 1.10, 0.10)): try: os.mkdir('{0}{1}'.format(dir_name, ashift)) except: pass print 'Directory already exists' os.chdir('{0}{1}'.format(dir_name, ashift)) fe_shift = fe_bulk.copy() fe_shift.set_calculator(pot) for at in fe_shift: if at.position[2] > ycut: #[00-1](110) # at.position += ashift*np.array([-a1,0,0]) #[1-11](110) at.position += 0.5 * ashift * np.array([a1, a2, 0]) # print >> fil1, ashift, (units.m**2/units.J)*(fe_shift.get_potential_energy()-refen)/A line = [] for at in fe_shift: line.append(FixedLine(at.index, (0, 0, 1))) #Now add Hydrogen # fe_shift.add_atoms(np.array([0.53*a0, 0.53*a0, 21.0+a0/2]),1) # at relaxed position: fe_shift.add_atoms(h_pos, 1) fix_atoms_mask = [at.number == 1 for at in fe_shift] fixedatoms = FixAtoms(mask=fix_atoms_mask) fe_shift.set_constraint(line + [fixedatoms]) opt = LBFGS(fe_shift) opt.run(fmax=0.1, steps=1000) if inum == 0: print 'Setting Reference Energy' refen = fe_shift.get_potential_energy() print >> f, ashift, (units.m**2 / units.J) * ( fe_shift.get_potential_energy() - refen) / A fe_shift.write('feb{0}.xyz'.format(ashift)) if WRITEVASP: vasp = Vasp(**vasp_args) vasp.initialize(fe_shift) write_vasp('POSCAR', vasp.atoms_sorted, symbol_count=vasp.symbol_count, vasp5=True) vasp.write_incar(fe_shift) vasp.write_potcar() vasp.write_kpoints() os.chdir('../') f.close()
check_kpoints_line(1, '0\n') check_kpoints_line(2, 'Auto\n') check_kpoints_line(3, '20 \n') calc.clean() # 1-element list ok, Gamma ok calc = Vasp(kpts=[20], gamma=True) calc.write_kpoints() check_kpoints_line(1, '0\n') check_kpoints_line(2, 'Auto\n') check_kpoints_line(3, '20 \n') calc.clean() # KSPACING suppresses KPOINTS file calc = Vasp(kspacing=0.23) calc.initialize(Al) calc.write_kpoints() calc.write_incar(Al) assert not os.path.isfile('KPOINTS') with open('INCAR', 'r') as f: assert ' KSPACING = 0.230000\n' in f.readlines() calc.clean() # Negative KSPACING raises an error calc = Vasp(kspacing=-0.5) try: calc.write_kpoints() except ValueError: pass else:
def generate_different_lattice_constant_inputs(self, initial_lattice_constant, range, samples, kpts, vacuum): ''' :param initial_lattice_constant: center value to search the lattice constant :param range: percentage to search the lattice constant :param samples: number of samples :param kpts: k-point sampling like (12,12,1) :param vacuum: unit cell size to z direction :return: ''' #in MX2, I set initial guess of thickness of the layer = initial_lattice_constant #this is Ok for typical MX2 like MoS2, WSe2, but be careful #set range to seardh start=initial_lattice_constant-initial_lattice_constant*range/100.0 last=initial_lattice_constant+initial_lattice_constant*range/100.0 latta = np.linspace(start, last, samples) dirs=[] for a in latta: dirname=self.config['formula']+"-a-"+str(a) dirs.append(dirname) os.makedirs(dirname, exist_ok=True) atoms=None if(self.config['type']=='MX2'): atoms=monolayer_MX2(self.config['formula'], a, initial_lattice_constant, vacuum) elif(self.config['type'] == 'Xene'): atoms = monolayer_Xene(self.config['formula'], a, self.config['buckling'], vacuum) #write('CONTCAR',atoms,format='vasp', vasp5=True) write(str(dirname) + '/POSCAR', atoms, format='vasp', vasp5=True) if(self.input_data['luse_vdw']): calc=Vasp(xc=self.input_data['xc'],encut=self.input_data['encut'], kpts=kpts,ismear=self.input_data['ismear'], luse_vdw=self.input_data['luse_vdw'], ibrion=self.input_data['ibrion'], potim=self.input_data['potim'], nsw=self.input_data['nsw'], gga=self.input_data['gga'], param1=self.input_data['param1'], param2=self.input_data['param2'], aggac=self.input_data['aggac'], zab_vdw=self.input_data['zab_vdw'], lasph=self.input_data['lasph'], sigma=self.input_data['sigma'],setups='recommended') shutil.copy('vdw_kernel.bindat',str(dirname)+'/vdw_kernel.bindat') else: calc = Vasp(xc=self.input_data['xc'], encut=self.input_data['encut'], kpts=kpts, ismear=self.input_data['ismear'], ibrion=self.input_data['ibrion'], potim=self.input_data['potim'], nsw=self.input_data['nsw'], sigma=self.input_data['sigma'], setups='recommended') atoms.set_calculator(calc) calc.initialize(atoms) calc.write_kpoints(directory=str(dirname)) calc.write_potcar(directory=str(dirname)) calc.write_incar(atoms,directory=str(dirname)) #shutil.copyfile(INCAR, os.path.join(dirname,INCAR)) #generate run script with open("run.sh" ,"w") as f: f.write(self.PBS_header+'\n') directory=self.config['formula']+"-a-" f.write("for dir in ./"+directory+"*; do \n") f.write("echo $dir \n") f.write("cd $dir \n") f.write(self.config['mpicommand'] +" "+self.config['path']+"/vasp_std " + " > scf.out \n") f.write("cd ../ \n") f.write("done \n") #create log file logfilename="log_lattice_optim-"+str(datetime.datetime.now()) with open(logfilename,"w") as log: for d in dirs: log.write(d+"\n") return
pp = [] with open(filename, 'r') as f: for line in f: if 'TITEL' in line.split(): pp.append(line.split()[3]) for setup in setups: assert setup in pp # Write some POTCARs and check they are ok potcar = 'POTCAR' try: atoms = Atoms('CaGdCs', positions=[[0, 0, 1], [0, 0, 2], [0, 0, 3]], cell=[5, 5, 5]) calc = Vasp(xc='pbe') calc.initialize(atoms) calc.write_potcar() check_potcar(('Ca_pv', 'Gd', 'Cs_sv'), filename=potcar) calc = Vasp(xc='pbe', setups='recommended') calc.initialize(atoms) calc.write_potcar() check_potcar(('Ca_sv', 'Gd_3', 'Cs_sv'), filename=potcar) calc = Vasp(xc='pbe', setups='materialsproject') calc.initialize(atoms) calc.write_potcar() check_potcar(('Ca_sv', 'Gd', 'Cs_sv'), filename=potcar) atoms = Atoms('CaInI', positions=[[0, 0, 1], [0, 0, 2], [0, 0, 3]], cell=[5, 5, 5])
def test_vasp_kpoints(): """ Check the many ways of specifying KPOINTS """ import os import filecmp from ase.calculators.vasp import Vasp from ase.build import bulk from ase.test.vasp import installed assert installed() 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() check_kpoints_line(1, '0\n') check_kpoints_line(2, 'Auto\n') check_kpoints_line(3, '20 \n') calc.clean() # 1-element list ok, Gamma ok calc = Vasp(kpts=[20], gamma=True) calc.write_kpoints() check_kpoints_line(1, '0\n') check_kpoints_line(2, 'Auto\n') check_kpoints_line(3, '20 \n') calc.clean() # KSPACING suppresses KPOINTS file calc = Vasp(kspacing=0.23) calc.initialize(Al) calc.write_kpoints() calc.write_incar(Al) assert not os.path.isfile('KPOINTS') with open('INCAR', 'r') as f: assert ' KSPACING = 0.230000\n' in f.readlines() calc.clean() # Negative KSPACING raises an error calc = Vasp(kspacing=-0.5) try: calc.write_kpoints() except ValueError: pass else: raise AssertionError("Negative KSPACING did not raise ValueError") calc.clean() # Explicit weighted points with nested lists, Cartesian if not specified calc = Vasp( kpts=[[0.1, 0.2, 0.3, 2], [0.0, 0.0, 0.0, 1], [0.0, 0.5, 0.5, 2]]) calc.write_kpoints() with open('KPOINTS.ref', 'w') as f: f.write("""KPOINTS created by Atomic Simulation Environment 3 Cartesian 0.100000 0.200000 0.300000 2.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.500000 0.500000 2.000000 """) assert filecmp.cmp('KPOINTS', 'KPOINTS.ref') os.remove('KPOINTS.ref') # Explicit points as list of tuples, automatic weighting = 1. calc = Vasp(kpts=[(0.1, 0.2, 0.3), (0.0, 0.0, 0.0), (0.0, 0.5, 0.5)], reciprocal=True) calc.write_kpoints() with open('KPOINTS.ref', 'w') as f: f.write("""KPOINTS created by Atomic Simulation Environment 3 Reciprocal 0.100000 0.200000 0.300000 1.0 0.000000 0.000000 0.000000 1.0 0.000000 0.500000 0.500000 1.0 """) assert filecmp.cmp('KPOINTS', 'KPOINTS.ref') os.remove('KPOINTS.ref')
def test_vasp_setup(require_vasp): """ Run some tests to ensure that VASP calculator constructs correct POTCAR files """ from os import remove from os.path import isfile from ase.atoms import Atoms from ase.calculators.vasp import Vasp from ase.test.calculator.vasp import installed assert installed() def check_potcar(setups, filename='POTCAR'): """Return true if labels in setups are found in POTCAR""" pp = [] with open(filename, 'r') as f: for line in f: if 'TITEL' in line.split(): pp.append(line.split()[3]) for setup in setups: assert setup in pp # Write some POTCARs and check they are ok potcar = 'POTCAR' try: atoms = Atoms('CaGdCs', positions=[[0, 0, 1], [0, 0, 2], [0, 0, 3]], cell=[5, 5, 5]) calc = Vasp(xc='pbe') calc.initialize(atoms) calc.write_potcar() check_potcar(('Ca_pv', 'Gd', 'Cs_sv'), filename=potcar) calc = Vasp(xc='pbe', setups='recommended') calc.initialize(atoms) calc.write_potcar() check_potcar(('Ca_sv', 'Gd_3', 'Cs_sv'), filename=potcar) calc = Vasp(xc='pbe', setups='materialsproject') calc.initialize(atoms) calc.write_potcar() check_potcar(('Ca_sv', 'Gd', 'Cs_sv'), filename=potcar) atoms = Atoms('CaInI', positions=[[0, 0, 1], [0, 0, 2], [0, 0, 3]], cell=[5, 5, 5]) calc = Vasp(xc='pbe', setups={'base': 'gw'}) calc.initialize(atoms) calc.write_potcar() check_potcar(('Ca_sv_GW', 'In_d_GW', 'I_GW'), filename=potcar) calc = Vasp(xc='pbe', setups={'base': 'gw', 'I': ''}) calc.initialize(atoms) calc.write_potcar() check_potcar(('Ca_sv_GW', 'In_d_GW', 'I'), filename=potcar) calc = Vasp(xc='pbe', setups={'base': 'gw', 'Ca': '_sv', 2: 'I'}) calc.initialize(atoms) calc.write_potcar() check_potcar(('Ca_sv', 'In_d_GW', 'I'), filename=potcar) finally: if isfile(potcar): remove(potcar)
def _prepare_for_submission(self, tempfolder, inputdict): try: import ase except: print 'ase needs to be installed' # ---------- get input data ---------- incar_data = inputdict['settings'] poscar_data = inputdict['structure_in'] potcar_data = inputdict['potentials_in'] kpoints_data = inputdict['kpoints_in'] chgcar_data = inputdict['chgcar_in'] # ---------- set up an ase Vasp calculation ---------- from ase.calculators.vasp import Vasp as AseVasp asevasp = AseVasp(xc='PBE') # push incar info for k, v in incar_data.get_dict().iteritems(): try: asevasp.set(**{k.lower(): v}) except TypeError as te: print 'ASE: ' + te.message asevasp.string_params[k.lower()] = _incarify(v) # push kpoints info kpoints_dict = kpoints_data.get_dict() if kpoints_dict.get('generation_style') == 'Gamma': asevasp.set(gamma=True) else: asevasp.set(gamma=False) kp = np.array(kpoints_dict['kpoints']) if len(kp.flatten()) == 3: kp = kp.flatten() asevasp.set(kpts=kp) # check wether potcar is parameter if isinstance(potcar_data, ParameterData): potcar_dict = potcar_data.get_dict() if potcar_dict.get('potpaw_path'): os.environ['VASP_PP_PATH'] = potcar_dict['potpaw_path'] else: if not os.environ['VASP_PP_PATH']: raise InputValidationError( 'No VASP_PP_PATH env variable is set. '+\ 'Please provide a potpaw_path parameter with the path containing '+\ 'your potpaw_XXX directory in the ParameterData passed to '+\ 'use_potentials or export VASP_PP_PATH=<path containing potpaw> '+\ 'or consider passing a POTCAR in a SinglefileData instance.') asevasp.set(setups=potcar_dict['special_symbols']) # push structure info asevasp.set_atoms(poscar_data.get_ase()) asevasp.initialize(asevasp.atoms) # ---------- write input files ---------- os.chdir(tempfolder.get_abs_path('')) from ase.io import vasp as vio vio.write_vasp('POSCAR', asevasp.atoms, direct=True, vasp5=True) asevasp.write_incar(asevasp.atoms) write_kpoints(kpoints_dict) if isinstance(potcar_data, ParameterData): asevasp.write_potcar() else: import shutil potcar_src = potcar_data.get_file_abs_path() potcar_dst = tempfolder.get_abs_path('POTCAR') shutil.copy(potcar_src, potcar_dst) #~ with open(potcar_data.get_file_abs_path()) as potcar_in: #~ with open(potcar_file, 'w') as potcar_out: #~ potcar_out.write(potcar_in.read()) icharg = incar_data.get_dict().get('icharg') if not icharg: icharg = incar_data.get_dict().get('ICHARG') if icharg < 10: if chgcar_data: self.logger.warning( 'ICHARG tag in INCAR file is {}, input CHGCAR not used!'. format(icharg)) elif icharg >= 10: if not chgcar_data: raise InputValidationError( 'ICHARG tag in INCAR file is {}, you must give a CHGCAR file!' .format(icharg)) else: import shutil chgcar_src = chgcar_data.get_file_abs_path() chgcar_dst = tempfolder.get_abs_path('CHGCAR') shutil.copy(chgcar_src, chgcar_dst) #~ with open(chgcar_data.get_file_abs_path()) as chgcar_in: #~ with open(chgcar_file, 'w') as chgcar_out: #~ chgcar_out.write(chgcar_in.read()) # ---------- set up and return calcinfo ---------- calcinfo = CalcInfo() calcinfo.uuid = self.uuid calcinfo.local_copy_list = [] calcinfo.remote_copy_list = [] #~ calcinfo.stdin_name = self._INPUT_FILE_NAME #~ calcinfo.stdout_name = self._OUTPUT_FILE_NAME calcinfo.retrieve_list = [ 'INCAR', 'KPOINTS', 'POSCAR', 'POTCAR', 'CHG', 'CHGCAR', 'CONTCAR', 'DOSCAR', 'EIGENVAL', 'OSZICAR', 'OUTCAR', 'PCDAT', 'PROCAR', 'WAVECAR', 'XDATCAR', 'vasprun.xml' ] return calcinfo
def test_vasp_net_charge(): """ Run VASP tests to ensure that determining number of electrons from user-supplied net charge (via the deprecated net_charge parameter) works correctly. This is conditional on the existence of the VASP_COMMAND or VASP_SCRIPT environment variables. This is mainly a slightly reduced duplicate of the vasp_charge test, but with flipped signs and with checks that ensure FutureWarning is emitted. Should be removed along with the net_charge parameter itself at some point. """ from ase.build import bulk from ase.calculators.vasp import Vasp from ase.test import must_raise, must_warn from ase.test.vasp import installed assert installed() system = bulk('Al', 'fcc', a=4.5, cubic=True) # Dummy calculation to let VASP determine default number of electrons calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False) calc.calculate(system) default_nelect_from_vasp = calc.get_number_of_electrons() assert default_nelect_from_vasp == 12 # Compare VASP's output nelect from before + net charge to default nelect # determined by us + net charge with must_warn(FutureWarning): net_charge = -2 calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False, net_charge=net_charge) calc.initialize(system) calc.write_input(system) calc.read_incar() assert calc.float_params['nelect'] == default_nelect_from_vasp + net_charge # Test that conflicts between explicitly given nelect and net charge are # detected with must_raise(ValueError): with must_warn(FutureWarning): calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False, nelect=default_nelect_from_vasp + net_charge + 1, net_charge=net_charge) calc.calculate(system) # Test that conflicts between charge and net_charge are detected with must_raise(ValueError): with must_warn(FutureWarning): calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False, charge=-net_charge - 1, net_charge=net_charge) calc.calculate(system) # Test that nothing is written if net charge is 0 and nelect not given with must_warn(FutureWarning): calc = Vasp(xc='LDA', nsw=-1, ibrion=-1, nelm=1, lwave=False, lcharg=False, net_charge=0) calc.initialize(system) calc.write_input(system) calc.read_incar() assert calc.float_params['nelect'] is None
:method:`write_incar` write the vasp INCAR file. """ with open('INCAR','w') as f: print >> f, self.incar_str def gen_vasp(self, struct_file) from ase import Atoms from ase.io.vasp import write_vasp from ase.calculators.vasp import Vasp ats = Atoms(struct_file) vasp_args=dict(xc='PBE', amix=0.01, amin=0.001, bmix=0.001, amix_mag=0.01, bmix_mag=0.001, ediff=1.0e-8, kpts=[3, 3, 3], kpar=9, lreal='auto', ibrion=-1, nsw=0, nelmdl=-15, ispin=2, prec='Accurate', nelm=100, algo='VeryFast', npar=24, lplane=False, lwave=False, lcharg=False, istart=0, voskown=0, ismear=1, sigma=0.1, isym=2) # possibly try iwavpr=12, should be faster if it works vasp = Vasp(**vasp_args) vasp.initialize(ats) write_vasp('POSCAR', vasp.atoms_sorted, symbol_count=vasp.symbol_count, vasp5=True) vasp.write_incar(ats) vasp.write_potcar() vasp.write_kpoints() if __name__=='__main__': parser = argparse.ArgumentParser() parser.add_argument('-s', '--submit', help='If present jobs will be submitted to scheduler.', action='store_true') parser.add_argument('-m', '--mod_key', help='INCAR file will be modified.', action='store_true') parser.add_argument('-u', '--update', help='If present CONTCAR will be copied to POSCAR before job is resubmitted.', action='store_true') parser.add_argument('-p', '--pattern', help='If directory pattern for submitting jobs. first characters for job pattern.') args = parser.parse_args() jobs = glob.glob('{}*'.format(args.pattern)) jobs = filter(lambda x: os.path.isdir(x), jobs)