class PotcarSettings: def __init__(self, species=None, functionals=None): if species and functionals: self._potcar = Potcar(species, functionals) self._species = species self._functionals = functionals else: self._potcar = None self._species = None self._functionals = None self._file_path = None def from_file(self, file_path): #add exception handeling self._file_path = file_path self._potcar = Potcar().from_file(file_path) self._species = self._potcar.symbols self._functionals = self._potcar.FUNCTIONAL_CHOICES def write_file(self, path): if self._potcar: self._potcar.write_file(path) else: pass
def update_pot_by_symbols(InputSet, write_file=True): """ Update POTCAR by symbols considering the MAGMOM difference Parameter --------- InputSet: VaspInputSet The input set defined by pymatgen, e.g. MPRelaxSet write_file: bool Write POSCAR (True) or not (False) Return ------ potcar: Potcar (in pymatgen) The Potcar type defined in pymatgen """ symbol, natom = check_symbol(InputSet) potcar_symbols = [] settings = InputSet._config_dict["POTCAR"] if isinstance(settings[symbol[-1]], dict): for el in symbol: potcar_symbols.append(settings[el]["symbol"] if el in settings else el) else: for el in symbol: potcar_symbols.append(settings.get(el, el)) potcar = Potcar(symbols=potcar_symbols, functional=InputSet.potcar_functional) if write_file: potcar.write_file(filename="POTCAR") return potcar
def generate_files(args): from pymatgen.io.vasp.inputs import Potcar if args.symbols: try: p = Potcar(args.symbols, functional=args.functional) p.write_file("POTCAR") except Exception as ex: print("An error has occurred: {}".format(str(ex))) else: print("No valid options selected.")
def generate_potcar(struct,dirname='.'): avail_pot =" ".join(Potcar.FUNCTIONAL_CHOICES) tip=""" Available Pseudo-potentials are: """ tip+=avail_pot+'\n' warn_tip(1,tip) print('your choice ?') wait_sep() in_str="" while in_str=="": in_str=input().strip() assert in_str.upper() in avail_pot potcar=Potcar([el.value for el in struct.types_of_specie],functional=in_str) potcar.write_file(os.path.join(dirname, "POTCAR"))
def generate_potcar(struct, dirname='.'): """ Generate POTCAR according to input structure via pymatgen's POTCAR module """ avail_pot = " ".join(Potcar.FUNCTIONAL_CHOICES) tip = """ Available Pseudo-potentials are: """ tip += avail_pot + '\n' warn_tip(1, tip) print('your choice ?') wait_sep() in_str = wait() assert in_str.upper() in avail_pot potcar = Potcar([el.value for el in struct.types_of_specie], functional=in_str) potcar.write_file(os.path.join(dirname, "POTCAR"))
potcar_symbols.sort() POTCAR = Potcar(potcar_symbols) f.writelines(['\tPOTCAR_symbols: ',str(potcar_symbols), '\n']) potcar_symbols.remove('H') else: f.writelines('\tLDAUL: %s\t LDAUU: %s\tLDAUJ: %s\n' % (INCAR['LDAUL'], INCAR['LDAUU'], INCAR['LDAUJ'])) POTCAR = Potcar(potcar_symbols) f.writelines(['\tPOTCAR_symbols: ',str(potcar_symbols), '\n']) view(slab_sorted) write_vasp(file_path + '%s/POSCAR' % (adsorbate_names[ads_idx]), slab_sorted) # Put AFM, def in the path if requried INCAR.write_file(file_path + '%s/INCAR' % (adsorbate_names[ads_idx])) # Put AFM, def in the path if requried KPOINTS.write_file(file_path + '%s/KPOINTS' % (adsorbate_names[ads_idx])) # Put AFM, def in the path if requried POTCAR.write_file(file_path + '%s/POTCAR' % (adsorbate_names[ads_idx])) # Put AFM, def in the path if requried # jobscript copy for n, line in enumerate(fileinput.FileInput('jobscript_vasp.sh')): if '#PBS -N' in line: n_line = n elif '#PBS -q' in line: q_line = n PBS_N = '#PBS -N %03d_%s\n' % (idx + 1.0, adsorbate_names[ads_idx]) replace_line('jobscript_vasp.sh', n_line, PBS_N) queue = 'normal' # Change queue name if required PBS_q = '#PBS -q %s\n' % (queue) replace_line('jobscript_vasp.sh', q_line, PBS_q)
def run_job(mat=None,incar=None,kpoints=None,jobname='',copy_file=[]): """ Generic function to run a VASP job, error correction implemented using custodian package A jobname+.json file is produced after successful completion of the job A first_cust.py file is generated which is invoked using python command Args: mat: Poscar object with structure information incar: Incar object with control information kpoints: Kpoints object with mesh information jobname: a uniq name for a job-type, say MAIN-ELAST for elastic properties copy_file: copy file from previous runs, say CHGCAR for Non-SCF bandstructure calculations Returns: f_energy: final energy contcar: path to final relaxed structure """ #hostname=str(socket.gethostname()) poscar_list=[(mat)] cwd=str(os.getcwd()) job_name=str(mat.comment) job_dir=str(jobname) run_file = str(os.getcwd())+str('/')+str(jobname)+str('.json') run_dir = str(os.getcwd())+str('/')+str(jobname) if mat.comment.startswith('Surf'): [a,b,c]=kpoints.kpts[0] kpoints.kpts=[[a,b,1]] try: pol=check_polar(mat.structure) if pol==True: ase_atoms = AseAtomsAdaptor().get_atoms(mat.structure) COM=ase_atoms.get_center_of_mass(scaled=True) print ("COM=",COM) print ('Found polar surface, will be setting dipole corrections') incar.update({"LDIPOL": '.TRUE.',"IDIPOL":3,"ISYM": 0,"DIPOL":str(COM[0])+str(" ")+str(COM[2])+str(" ")+str(COM[2])}) print ("Polar surface encountered in run_job",mat.comment) except: pass wait=False json_file=str(jobname)+str('.json') print ('json should be here=',str(os.getcwd())+str('/')+str(json_file)) #print ('json should be=',json_file,run_file,os.getcwd()) if os.path.exists(str(os.getcwd())+str('/')+str(json_file)): try: data_cal=loadfn(str(os.getcwd())+str('/')+str(json_file),cls=MontyDecoder) tmp_outcar=str(os.getcwd())+str('/')+str(json_file.split('.json')[0])+str('/OUTCAR') print ('outcar is',tmp_outcar) wait=main_outcar(tmp_outcar) #True print ('outcar status',wait) if wait==True: f_energy=data_cal[0]['final_energy'] contcar=str(os.getcwd())+str('/')+str(json_file.split('.json')[0])+str('/CONTCAR') return f_energy,contcar except: pass while wait==False: print ("Setting up POTCAR") with open(pot_yaml, 'r') as f: doc = yaml.load(f) pots=doc['POTCAR'] new_symb=[] for el in mat.site_symbols: new_symb.append(pots[el]) #potcar = Potcar(symbols=new_symb,functional=functional) try: potcar = Potcar(symbols=new_symb,functional=functional) except: print ('JARVIS-ERROR: Could not set POTCAR, check POTCAR yaml file and VASP_PSP_DIR') pass if not os.path.exists(run_dir): print ('Starting new job') os.makedirs(run_dir) os.chdir(run_dir) incar.write_file("INCAR") potcar.write_file("POTCAR") kpoints.write_file("KPOINTS") mat.write_file("POSCAR") for i in copy_file: print ('copying',i) shutil.copy2(i,'./') #f=open('job.out','w') cmd=str('python first_cust.py >out_dat')+'\n' cust_file=open("first_cust.py","w") cline=str('from pymatgen.io.vasp.inputs import Incar, Poscar, VaspInput,Potcar, Kpoints')+'\n' cust_file.write(cline) cline=str('import os,shutil')+'\n' cust_file.write(cline) cline=str('from custodian.vasp.jobs import VaspJob')+'\n' cust_file.write(cline) cline=str('from custodian.vasp.handlers import VaspErrorHandler, UnconvergedErrorHandler,MeshSymmetryErrorHandler, NonConvergingErrorHandler, PotimErrorHandler')+'\n' cust_file.write(cline) cline=str('from custodian.vasp.validators import VaspFilesValidator,VasprunXMLValidator')+'\n' cust_file.write(cline) cline=str('from custodian.custodian import Custodian')+'\n' cust_file.write(cline) cline=str('inc=Incar.from_file("INCAR")')+'\n' cust_file.write(cline) cline=str('pot=Potcar.from_file("POTCAR")')+'\n' cust_file.write(cline) cline=str('pos=Poscar.from_file("POSCAR")')+'\n' cust_file.write(cline) cline=str('kp=Kpoints.from_file("KPOINTS")')+'\n' cust_file.write(cline) cline=str("shutil.copy2('")+vdw_dat+str("','./')")+'\n' cust_file.write(cline) cline=str('vinput = VaspInput.from_directory(".")')+'\n' cust_file.write(cline) cline=str("job=VaspJob(['mpirun', '")+str(main_exe)+str("'], final=False, backup=False)")+'\n' if mat.comment.startswith('Surf'): cline=str("job=VaspJob(['mpirun', '")+str(surf_exe)+str("'], final=False, backup=False)")+'\n' if 'SOC' in jobname: cline=str("job=VaspJob(['mpirun', '")+str(soc_exe)+str("'], final=False, backup=False)")+'\n' cust_file.write(cline) cline=str('handlers = [VaspErrorHandler(), MeshSymmetryErrorHandler(),UnconvergedErrorHandler(), NonConvergingErrorHandler(),PotimErrorHandler()]')+'\n' cust_file.write(cline) cline=str('validators = [VasprunXMLValidator()]')+'\n' #cline=str('validators = [VaspFilesValidator()]')+'\n' cust_file.write(cline) cline=str('c = Custodian(handlers, [job],max_errors=5,validators=validators)')+'\n' cust_file.write(cline) cline=str('c.run()')+'\n' cust_file.write(cline) cust_file.close() print ("I AM HERE 2") os.system(cmd) if os.path.isfile('OUTCAR'): try: wait=main_outcar('OUTCAR') #Vasprun("vasprun.xml").converged except: pass print ("End of the first loop",os.getcwd(),wait) else : print ('Jobs seens to have started before') os.chdir(run_dir) wait=False if os.path.isfile('OUTCAR'): try: wait=main_outcar('OUTCAR') #Vasprun("vasprun.xml").converged #wait=Vasprun("vasprun.xml").converged except: pass print ("Tried to find OUTCAR, wait is=",wait) if wait==False: incar.write_file("INCAR") kpoints.write_file("KPOINTS") mat.write_file("POSCAR") try: potcar.write_file("POTCAR") print ('FOUND OLD CONTCAR in', os.getcwd()) old_contcar=Poscar.from_file('CONTCAR') #old_contcar.write_file('POSCAR') copy_cmd=str('cp CONTCAR POSCAR') print ('copy_cmd=',copy_cmd) if 'ELAST' not in jobname: #Because in ELASTIC calculations structures are deformed os.system(copy_cmd) #time.sleep(3) except: pass for i in copy_file: print ('copying',i) shutil.copy2(i,'./') cmd=str('python first_cust.py >out_dat')+'\n' cust_file=open("first_cust.py","w") cline=str('from pymatgen.io.vasp.inputs import Incar, Poscar, VaspInput,Potcar, Kpoints')+'\n' cust_file.write(cline) cline=str('import os,shutil')+'\n' cust_file.write(cline) cline=str('from custodian.vasp.jobs import VaspJob')+'\n' cust_file.write(cline) cline=str('from custodian.vasp.handlers import VaspErrorHandler, UnconvergedErrorHandler,MeshSymmetryErrorHandler, NonConvergingErrorHandler, PotimErrorHandler')+'\n' cust_file.write(cline) cline=str('from custodian.vasp.validators import VaspFilesValidator,VasprunXMLValidator')+'\n' cust_file.write(cline) cline=str('from custodian.custodian import Custodian')+'\n' cust_file.write(cline) cline=str('inc=Incar.from_file("INCAR")')+'\n' cust_file.write(cline) cline=str('pot=Potcar.from_file("POTCAR")')+'\n' cust_file.write(cline) cline=str('pos=Poscar.from_file("POSCAR")')+'\n' cust_file.write(cline) cline=str('kp=Kpoints.from_file("KPOINTS")')+'\n' cust_file.write(cline) cline=str("shutil.copy2('")+vdw_dat+str("','./')")+'\n' cust_file.write(cline) cline=str('vinput = VaspInput.from_directory(".")')+'\n' cust_file.write(cline) cline=str("job=VaspJob(['mpirun', '")+str(main_exe)+str("'], final=False, backup=False)")+'\n' if mat.comment.startswith('Surf'): cline=str("job=VaspJob(['mpirun', '")+str(surf_exe)+str("'], final=False, backup=False)")+'\n' if 'SOC' in jobname: cline=str("job=VaspJob(['mpirun', '")+str(soc_exe)+str("'], final=False, backup=False)")+'\n' cust_file.write(cline) cline=str('handlers = [VaspErrorHandler(), MeshSymmetryErrorHandler(),UnconvergedErrorHandler(), NonConvergingErrorHandler(),PotimErrorHandler()]')+'\n' cust_file.write(cline) #cline=str('validators = [VaspFilesValidator()]')+'\n' cline=str('validators = [VasprunXMLValidator()]')+'\n' cust_file.write(cline) cline=str('c = Custodian(handlers, [job],max_errors=5,validators=validators)')+'\n' cust_file.write(cline) cline=str('c.run()')+'\n' cust_file.write(cline) cust_file.close() os.system(cmd) if os.path.isfile('OUTCAR'): try: wait=main_outcar('OUTCAR') #Vasprun("vasprun.xml").converged #wait=Vasprun("vasprun.xml").converged except: pass f_energy='na' enp='na' contcar=str(os.getcwd())+str('/')+str('CONTCAR') final_str=Structure.from_file(contcar) try: oszicar = Oszicar("OSZICAR") f_energy=float(oszicar.final_energy) enp=float(oszicar.final_energy)/float(final_str.composition.num_atoms) except: print ('Error in OSZICAR file during re-run jpb') pass natoms=final_str.composition.num_atoms os.chdir('../') if wait==True: data_cal=[] data_cal.append({'jobname':jobname,'poscar_initial':mat.as_dict(),'poscar_final':final_str.as_dict(),'incar':incar.as_dict(),'kpoints':kpoints.as_dict(),'final_energy':(f_energy),'contcar':final_str.as_dict()}) json_file=str(jobname)+str('.json') f_json=open(json_file,'w') f_json.write(json.dumps(data_cal,indent=4,cls=MontyEncoder)) f_json.close() print ('Wrote json file',contcar) return f_energy,contcar
INCAR['LDAUL'] = [2, -1] INCAR['LDAUU'] = [U_dict[TM], 0.0] INCAR['LDAUJ'] = [0.0, 0.0] else: INCAR['LDAU'] = '.FALSE.' INCAR['LDAUL'] = [-1, -1] INCAR['LDAUU'] = [0.0, 0.0] INCAR['LDAUJ'] = [0.0, 0.0] INCAR.write_file('%02d_%s/INCAR' % (idx + 1.0, formula)) KPOINTS.write_file('%02d_%s/KPOINTS' % (idx + 1.0, formula)) # Potcar setup POTCAR = Potcar([PP_dict[TM], PP_dict['O']]) POTCAR.write_file('%02d_%s/POTCAR' % (idx + 1.0, formula)) # jobscript copy for n, line in enumerate(fileinput.FileInput('jobscript_vasp.sh')): if '#PBS -N' in line: n_line = n PBS_N = '#PBS -N %02d_%s_np\n' % (idx + 1.0, formula) replace_line('jobscript_vasp.sh', n_line, PBS_N) destination = '%02d_%s/' % (idx + 1.0, formula) job_file = os.getcwd() + '/jobscript_vasp.sh' shutil.copy(job_file, destination) end_time = time.time() print('Execution time for script (sec) : %5.1f\n' % (end_time - start_time))
f.writelines([ '\t', 'LDAUL: ', str(INCAR['LDAUL']), '\t', 'LDAUU: ', str(INCAR['LDAUU']), '\t', 'LDAUJ: ', str(INCAR['LDAUJ']), '\n' ]) f.writelines(['\t', 'MAGMOM: ', str(magm), '\n']) """ Write files """ write_vasp(file_path + 'surface/POSCAR', slab_sorted) INCAR.write_file(file_path + 'surface/INCAR') KPOINTS.write_file(file_path + 'surface/KPOINTS') POTCAR.write_file(file_path + 'surface/POTCAR') # jobscript copy for n, line in enumerate(fileinput.FileInput('jobscript_vasp.sh')): if '#PBS -N' in line: n_line = n elif '#PBS -q' in line: q_line = n PBS_N = '#PBS -N %03d_%s\n' % (idx + 1.0, formula) replace_line('jobscript_vasp.sh', n_line, PBS_N) queue = 'flat' # Change queue name if required PBS_q = '#PBS -q %s\n' % (queue) replace_line('jobscript_vasp.sh', q_line, PBS_q) destination = file_path + 'surface/'
f.writelines(['\t', 'POTCAR_symbols: ', str(potcar_symbols), '\n']) f.writelines([ '\t', 'LDAUL: ', str(INCAR['LDAUL']), '\t', 'LDAUU: ', str(INCAR['LDAUU']), '\t', 'LDAUJ: ', str(INCAR['LDAUJ']), '\n' ]) f.writelines(['\t', 'MAGMOM: ', str(magm), '\n']) """ Write files """ write_vasp('%03d_%s/2nd/surface/POSCAR' % (idx + 1.0, formula), slab_sorted) INCAR.write_file('%03d_%s/2nd/surface/INCAR' % (idx + 1.0, formula)) KPOINTS.write_file('%03d_%s/2nd/surface/KPOINTS' % (idx + 1.0, formula)) POTCAR.write_file('%03d_%s/2nd/surface/POTCAR' % (idx + 1.0, formula)) # jobscript copy destination = '%03d_%s/2nd/surface/' % (idx + 1.0, formula) job_file = os.getcwd() + '/jobscript_vasp.sh' shutil.copy(job_file, destination) f.writelines(['#' * 80, '\n']) end_time = time.time() f.writelines('Execution time for script (sec) : %6.1f\n' % (end_time - start_time))
from pymatgen.io.vasp.inputs import Incar, Poscar from pymatgen.io.vasp.inputs import Potcar import yaml import os os.environ["VASP_PSP_DIR"] = "/home/knc6/Software/VASP-POTENTIAL" with open('/home/knc6/bin/Special_POTCAR.yaml', 'r') as f: doc = yaml.load(f) pots = doc['POTCAR'] mat = Poscar.from_file('POSCAR') new_symb = [] for el in mat.site_symbols: new_symb.append(pots[el]) potcar = Potcar(symbols=new_symb, functional="PBE") potcar.write_file("POTCAR")
INCAR['LDAUU'][index] = U_dict[element] INCAR.write_file('%03d_%s/INCAR' % (idx + 1.0, formula)) KPOINTS.write_file('%03d_%s/KPOINTS' % (idx + 1.0, formula)) # Potcar setup mp_calc = mpr.get_entry_by_material_id({'material_id': mp_id}) mp_potcar_symbols = mp_calc.parameters['potcar_symbols'] for i in range(len(mp_potcar_symbols)): mp_potcar_symbols[i] = mp_potcar_symbols[i].replace("PBE ", "") if 'W_pv' in mp_potcar_symbols: mp_potcar_symbols[1] = 'W_sv' POTCAR = Potcar(mp_potcar_symbols) POTCAR.write_file(file_path + 'POTCAR') print('%02d' % (idx + 1.0), " ", formula, " ", conv_struc.formula, " ", len(conv_struc), " %4.3f %4.3f %4.3f" % (conv_struc.lattice.abc), " ", mp_potcar_symbols, " ", INCAR['LDAUU'], " %s" % INCAR['MAGMOM']) f.writelines([ '%02d' % (idx + 1.0), " ", formula, " ", conv_struc.formula, " ", str(len(conv_struc)), " %4.3f %4.3f %4.3f" % (conv_struc.lattice.abc), " %s" % mp_potcar_symbols, " %s" % INCAR['LDAUU'], " %s\n" % INCAR['MAGMOM'] ]) # jobscript copy
KPOINTS.write_file('%03d_%s/KPOINTS' % (i + 1.0, formula)) # Potcar setup mp_calc = mpr.get_entry_by_material_id({'material_id': mp_id}) mp_potcar_symbols = mp_calc.parameters['potcar_symbols'] for idx in range(len(mp_potcar_symbols)): mp_potcar_symbols[idx] = mp_potcar_symbols[idx].replace("PBE ", "") if 'W_pv' in mp_potcar_symbols: mp_potcar_symbols[1] = 'W_sv' # ordering for exception_list if mp_potcar_symbols[-1] != 'O': # print(i," ", formula," ",mp_potcar_symbols) mp_potcar_symbols.reverse() POTCAR = Potcar(mp_potcar_symbols) print('%d\t%s\t%s\t%s' % (i + 1, formula, mp_potcar_symbols, INCAR['LDAUU'])) f.writelines('%d\t%s\t%s\t%s\n' % (i + 1, formula, mp_potcar_symbols, INCAR['LDAUU'])) POTCAR.write_file('%03d_%s/POTCAR' % (i + 1.0, formula)) # jobscript copy destination = '%03d_%s/' % (i + 1.0, formula) job_file = os.getcwd() + '/jobscript_vasp.sh' shutil.copy(job_file, destination) end_time = time.time() f.writelines('Execution time for script (sec) : %6.1f\n' % (end_time - start_time))
f.writelines(['\t', 'LDAUL: ',str(INCAR['LDAUL']),'\t', 'LDAUU: ',str(INCAR['LDAUU']),'\t', 'LDAUJ: ',str(INCAR['LDAUJ']),'\n']) f.writelines(['\t','MAGMOM: ',str(magm),'\n']) print(sorted(elements)," ",INCAR['LDAUU']," ",magm," ",potcar_symbols) """ Write files """ write_vasp(file_path + 'slab_100/POSCAR', slab_sorted) INCAR.write_file(file_path + 'slab_100/INCAR') KPOINTS.write_file(file_path + 'slab_100/KPOINTS') POTCAR.write_file(file_path + 'slab_100/POTCAR') # view(slab_sorted) # jobscript copy for n, line in enumerate(fileinput.FileInput('jobscript_vasp.sh')): if '#PBS -N' in line: n_line = n elif '#PBS -q' in line: q_line = n elif '#PBS -l' in line: w_line = n PBS_N = '#PBS -N %02d_%s\n' % (idx + 1.0, formula) replace_line('jobscript_vasp.sh', n_line, PBS_N) if idx < 15: queue = 'normal' # Change queue name if required
INCAR['LDAUU'] = [LDAUU_dic[x] for x in sorted(elements)] INCAR['LDAUJ'] = [LDAUJ_dic[x] for x in sorted(elements)] f.writelines('\tLDAUL: %s\t LDAUU: %s\tLDAUJ: %s\n' % (INCAR['LDAUL'], INCAR['LDAUU'], INCAR['LDAUJ'])) potcar_symbols.append('H') potcar_symbols.sort() POTCAR = Potcar(potcar_symbols) f.writelines(['\tPOTCAR_symbols: ',str(potcar_symbols), '\n']) potcar_symbols.remove('H') else: f.writelines('\tLDAUL: %s\t LDAUU: %s\tLDAUJ: %s\n' % (INCAR['LDAUL'], INCAR['LDAUU'], INCAR['LDAUJ'])) POTCAR = Potcar(potcar_symbols) f.writelines(['\tPOTCAR_symbols: ',str(potcar_symbols), '\n']) # view(slab_sorted) write_vasp(file_path + '%s/POSCAR' % (adsorbate_names[ads_idx]), slab_sorted) INCAR.write_file(file_path + '%s/INCAR' % (adsorbate_names[ads_idx])) KPOINTS.write_file(file_path + '%s/KPOINTS' % (adsorbate_names[ads_idx])) POTCAR.write_file(file_path + '%s/POTCAR' % (adsorbate_names[ads_idx])) # jobscript copy destination = file_path + adsorbate_names[ads_idx] + '/' job_file = os.getcwd() + '/jobscript_vasp.sh' shutil.copy(job_file, destination) f.writelines(['#'*80,'\n']) end_time = time.time() f.writelines('Execution time for script (sec) : %6.1f\n' % (end_time - start_time))