def generate_nscf_soc_folders(structures, saxis, user_incar): """ Generate the non self-consistent calculation with the spin-orbit coupling """ for name in structures: # add magmom as a site property for each atom outcar = Outcar(filename=os.path.join(name, 'OUTCAR')) for i, atom in enumerate(structures[name].sites): atom.properties = { "magmom": [0., 0., round(outcar.magnetization[i]['tot'], 2)] } # geterate calculation from the MPSOCSet mpsoc = MPSOCSet(structures[name], saxis=saxis, user_incar_settings=user_incar, user_kpoints_settings={"reciprocal_density": 500}) mpsoc.write_input(os.path.join(name, 'nscf_SOC')) # walk around the bug in MPSICSet to introduce LDAUU and LDAUL into INCAR dic = mpsoc.incar.as_dict() dic["LDAUU"] = list(dic["LDAUU"].values()) dic["LDAUL"] = list(dic["LDAUL"].values()) Incar.from_dict(dic).write_file(os.path.join(name, 'nscf_SOC/INCAR')) shutil.copy(os.path.join(name, 'CHGCAR'), os.path.join(name, 'nscf_SOC'))
def test_as_dict_and_from_dict(self): d = self.incar.as_dict() incar2 = Incar.from_dict(d) self.assertEqual(self.incar, incar2) d["MAGMOM"] = [Magmom([1, 2, 3]).as_dict()] incar3 = Incar.from_dict(d) self.assertEqual(incar3["MAGMOM"], [Magmom([1, 2, 3])])
def run_major_axis_anisotropy_calculations(submit=True): """ Perform static calculations with the magnetic axis along 100, 010, and 001. Kwargs: submit (bool): Whether or not to submit the job. """ if not os.path.isdir('MAE'): os.mkdir('MAE') os.chdir('MAE') for d in ['100', '010', '001']: if not os.path.isdir(d): os.path.mkdir(d) os.chdir(d) os.system('cp ../CONTCAR POSCAR') os.system('cp ../POTCAR .') axis = [float(char) for char in d] # Small positive number, see vasp manual if d in ['001', '010']: axis[0] = 0.00000001 else: axis[1] = 0.00000001 saxis = ' '.join(axis) incar_dict = INCAR_DICT incar_dict.update({'EDIFF': 1e-8, 'GGA_COMPAT': False, 'ISMEAR': -5, 'LORBIT': 11, 'LSORBIT': True, 'LWAVE': False, 'LCHARG': False, 'LAECHG': False, 'MAGMOM': get_magmom_string(), 'SAXIS': saxis}) Incar.from_dict(incar_dict).write_file('INCAR') if submit: os.system(submission_command)
def test_as_dict_and_from_dict(self): d = self.incar.as_dict() incar2 = Incar.from_dict(d) self.assertEqual(self.incar, incar2) d["MAGMOM"] = [Magmom([1, 2, 3]).as_dict()] incar3 = Incar.from_dict(d) self.assertEqual(incar3["MAGMOM"], [Magmom([1, 2, 3])])
def relax(dim=2, submit=True, force_overwrite=False): """ Writes input files and (optionally) submits a self-consistent relaxation. Should be run before pretty much anything else, in order to get the right energy and structure of the material. Args: dim (int): 2 for relaxing a 2D material, 3 for a 3D material. submit (bool): Whether or not to submit the job. force_overwrite (bool): Whether or not to overwrite files if an already converged vasprun.xml exists in the directory. """ if force_overwrite or not utl.is_converged(os.getcwd()): directory = os.getcwd().split('/')[-1] # vdw_kernel.bindat file required for VDW calculations. if VDW_KERNEL: os.system('cp {} .'.format(VDW_KERNEL)) # KPOINTS Kpoints.automatic_density(Structure.from_file('POSCAR'), 1000).write_file('KPOINTS') # INCAR INCAR_DICT.update( {'MAGMOM': utl.get_magmom_string(Structure.from_file('POSCAR'))} ) Incar.from_dict(INCAR_DICT).write_file('INCAR') # POTCAR utl.write_potcar() # Special tasks only performed for 2D materials. if dim == 2: # Ensure 20A interlayer vacuum utl.ensure_vacuum(Structure.from_file('POSCAR'), 20) # Remove all z k-points. kpts_lines = open('KPOINTS').readlines() with open('KPOINTS', 'w') as kpts: for line in kpts_lines[:3]: kpts.write(line) kpts.write(kpts_lines[3].split()[0] + ' ' + kpts_lines[3].split()[1] + ' 1') # Submission script if dim == 2: binary = VASP_TWOD_BIN elif dim == 3: binary = VASP_STD_BIN if QUEUE_SYSTEM == 'pbs': utl.write_pbs_runjob(directory, 1, 16, '800mb', '6:00:00', binary) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': utl.write_slurm_runjob(directory, 16, '800mb', '6:00:00', binary) submission_command = 'sbatch runjob' if submit: os.system(submission_command)
def relax(dim=2, submit=True, force_overwrite=False): """ Writes input files and (optionally) submits a self-consistent relaxation. Should be run before pretty much anything else, in order to get the right energy and structure of the material. Args: dim (int): 2 for relaxing a 2D material, 3 for a 3D material. submit (bool): Whether or not to submit the job. force_overwrite (bool): Whether or not to overwrite files if an already converged vasprun.xml exists in the directory. """ if force_overwrite or not utl.is_converged(os.getcwd()): directory = os.getcwd().split('/')[-1] # vdw_kernel.bindat file required for VDW calculations. if VDW_KERNEL: os.system('cp {} .'.format(VDW_KERNEL)) # KPOINTS Kpoints.automatic_density(Structure.from_file('POSCAR'), 1000).write_file('KPOINTS') # INCAR INCAR_DICT.update( {'MAGMOM': utl.get_magmom_string(Structure.from_file('POSCAR'))}) Incar.from_dict(INCAR_DICT).write_file('INCAR') # POTCAR utl.write_potcar() # Special tasks only performed for 2D materials. if dim == 2: # Ensure 20A interlayer vacuum utl.ensure_vacuum(Structure.from_file('POSCAR'), 20) # Remove all z k-points. kpts_lines = open('KPOINTS').readlines() with open('KPOINTS', 'w') as kpts: for line in kpts_lines[:3]: kpts.write(line) kpts.write(kpts_lines[3].split()[0] + ' ' + kpts_lines[3].split()[1] + ' 1') # Submission script if dim == 2: binary = VASP_TWOD_BIN elif dim == 3: binary = VASP_STD_BIN if QUEUE_SYSTEM == 'pbs': utl.write_pbs_runjob(directory, 1, 16, '800mb', '6:00:00', binary) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': utl.write_slurm_runjob(directory, 16, '800mb', '6:00:00', binary) submission_command = 'sbatch runjob' if submit: os.system(submission_command)
def run_hse_prep_calculation(dim=2, submit=True): """ Submits a quick static calculation to calculate the IBZKPT file using a smaller number of k-points (200/atom instead of 1000/atom). The other outputs from this calculation are essentially useless. Args: dim (int): 2 for relaxing a 2D material, 3 for a 3D material. submit (bool): Whether or not to submit the job. """ if not os.path.isdir('hse_prep'): os.mkdir('hse_prep') os.chdir('hse_prep') shutil.copy('../CONTCAR', 'POSCAR') if os.path.isfile('../POTCAR'): shutil.copy('POTCAR', '.') relax(dim=2, submit=False) incar_dict = Incar.from_file('INCAR').as_dict() incar_dict.update({ 'NSW': 0, 'NELM': 1, 'LWAVE': False, 'LCHARG': False, 'LAECHG': False }) Incar.from_dict(incar_dict).write_file('INCAR') Kpoints.automatic_density(Structure.from_file('POSCAR'), 200).write_file('KPOINTS') if dim == 2: kpts_lines = open('KPOINTS').readlines() with open('KPOINTS', 'w') as kpts: for line in kpts_lines[:3]: kpts.write(line) kpts.write(kpts_lines[3].split()[0] + ' ' + kpts_lines[3].split()[1] + ' 1') if QUEUE_SYSTEM == 'pbs': write_pbs_runjob('{}_prep'.format(os.getcwd().split('/')[-2]), 1, 16, '800mb', '6:00:00', VASP_STD_BIN) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': write_slurm_runjob('{}_prep'.format(os.getcwd().split('/')[-2]), 16, '800mb', '6:00:00', VASP_STD_BIN) submission_command = 'sbatch runjob' if submit: _ = subprocess.check_output(submission_command.split()) os.chdir('../')
def run_major_axis_anisotropy_calculations(submit=True): """ Perform static calculations with the magnetic axis along 100, 010, and 001. Args: submit (bool): Whether or not to submit the job. """ if not os.path.isdir('MAE'): os.mkdir('MAE') os.chdir('MAE') for d in ['100', '010', '001']: if not os.path.isdir(d): os.mkdir(d) os.chdir(d) os.system('cp ../CONTCAR POSCAR') os.system('cp ../POTCAR .') axis = [float(char) for char in d] # Small positive number, see vasp manual if d in ['001', '010']: axis[0] = 0.00000001 else: axis[1] = 0.00000001 saxis = ' '.join(axis) incar_dict = INCAR_DICT incar_dict.update({'EDIFF': 1e-8, 'GGA_COMPAT': False, 'ISMEAR': -5, 'LORBIT': 11, 'LSORBIT': True, 'LWAVE': False, 'LCHARG': False, 'LAECHG': False, 'MAGMOM': get_magmom_string( Structure.from_file('POSCAR') ), 'SAXIS': saxis}) Incar.from_dict(incar_dict).write_file('INCAR') if QUEUE_SYSTEM == 'pbs': utl.write_pbs_runjob(directory, 1, 16, '800mb', '6:00:00', VASP_TWOD_BIN) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': utl.write_slurm_runjob(directory, 16, '800mb', '6:00:00', VASP_TWOD_BIN) submission_command = 'sbatch runjob' if submit: os.system(submission_command)
def run_hse_prep_calculation(dim=2, submit=True): """ Submits a quick static calculation to calculate the IBZKPT file using a smaller number of k-points (200/atom instead of 1000/atom). The other outputs from this calculation are essentially useless. Args: dim (int): 2 for relaxing a 2D material, 3 for a 3D material. submit (bool): Whether or not to submit the job. """ if not os.path.isdir('hse_prep'): os.mkdir('hse_prep') os.chdir('hse_prep') os.system('cp ../CONTCAR ./POSCAR') if os.path.isfile('../POTCAR'): os.system('cp POTCAR .') relax(dim=2, submit=False) incar_dict = Incar.from_file('INCAR').as_dict() incar_dict.update({'NSW': 0, 'NELM': 1, 'LWAVE': False, 'LCHARG': False, 'LAECHG': False}) Incar.from_dict(incar_dict).write_file('INCAR') Kpoints.automatic_density( Structure.from_file('POSCAR'), 200 ).write_file('KPOINTS') if dim == 2: kpts_lines = open('KPOINTS').readlines() with open('KPOINTS', 'w') as kpts: for line in kpts_lines[:3]: kpts.write(line) kpts.write(kpts_lines[3].split()[0] + ' ' + kpts_lines[3].split()[1] + ' 1') if QUEUE == 'pbs': write_pbs_runjob('{}_prep'.format( os.getcwd().split('/')[-2]), 1, 16, '800mb', '6:00:00', VASP) submission_command = 'qsub runjob' elif QUEUE == 'slurm': write_slurm_runjob('{}_prep'.format( os.getcwd().split('/')[-2]), 16, '800mb', '6:00:00', VASP) submission_command = 'sbatch runjob' if submit: os.system(submission_command) os.chdir('../')
def from_dict(d): path = d['path'] inputs = {} inputs["structures"] = [ Structure.from_dict(s) for s in d['inputs']['structures'] ] inputs["INCAR"] = Incar.from_dict(d['inputs']['INCAR']) inputs["KPOINTS"] = Kpoints.from_dict(d['inputs']['KPOINTS']) inputs["POTCAR"] = Potcar.from_dict(d['inputs']['POTCAR']) job_settings = d['job_settings'] job_script_filename = d['job_script_filename'] name = d['name'] outputs = {} vaspNEBjob = VaspNEBJob(path, inputs, job_settings, outputs, job_script_filename, name) vaspNEBjob._is_step_limit_reached = d['is_step_limit_reached'] vaspNEBjob._is_converged = d['is_converged'] vaspNEBjob._r = np.array(d['r']) vaspNEBjob._energies = np.array(d['energies']) vaspNEBjob._forces = np.array(d['forces']) return vaspNEBjob
def hse(): allline = '' s = Structure.from_file("POSCAR") incar_dict = dict(PREC='Accurate', ENCUT=45678, NBANDS=456789, ISMEAR=0, EDIFF='1E-7', LCHARG='.FALSE.', NEDOS=5000, ISPIN=2, ISIF=2, IBRION=1, NELM=400, LORBIT=11, NPAR=4, LWAVE='.FALSE.') incar = Incar.from_dict(incar_dict) user_incar_settings = { "EDIFF": 1E-6, "ISIF": 2, "NSW": 0, "LORBIT": 11, "ENCUT": 34, "LWAVE": '.FALSE.', "PREC": 'Accurate' } mpvis = MPBSHSEVaspInputSet(user_incar_settings=incar) kpoints = mpvis.get_kpoints(s) kpoints.write_file("KPOINTS")
def __init__(self, name, incar, poscar, potcar, kpoints, qadapter=None, **kwargs ): """ default INCAR from config_dict """ self.name = name self.incar = Incar.from_dict(incar.as_dict()) self.poscar = Poscar.from_dict(poscar.as_dict()) self.potcar = Potcar.from_dict(potcar.as_dict()) self.kpoints = Kpoints.from_dict(kpoints.as_dict()) self.extra = kwargs if qadapter is not None: self.qadapter = qadapter.from_dict(qadapter.to_dict()) else: self.qadapter = None config_dict = {} config_dict['INCAR'] = self.incar.as_dict() config_dict['POSCAR'] = self.poscar.as_dict() #caution the key and the value are not always the same config_dict['POTCAR'] = self.potcar.as_dict() #dict(zip(self.potcar.as_dict()['symbols'], #self.potcar.as_dict()['symbols'])) config_dict['KPOINTS'] = self.kpoints.as_dict() #self.user_incar_settings = self.incar.as_dict() DictVaspInputSet.__init__(self, name, config_dict, ediff_per_atom=False, **kwargs)
def __init__(self, name, incar, poscar, potcar, kpoints, qadapter=None, script_name='submit_script', vis_logger=None, **kwargs): """ default INCAR from config_dict """ self.name = name self.incar = Incar.from_dict(incar.as_dict()) self.poscar = Poscar.from_dict(poscar.as_dict()) self.potcar = Potcar.from_dict(potcar.as_dict()) self.kpoints = Kpoints.from_dict(kpoints.as_dict()) self.extra = kwargs if qadapter is not None: self.qadapter = qadapter.from_dict(qadapter.to_dict()) else: self.qadapter = None self.script_name = script_name config_dict = {} config_dict['INCAR'] = self.incar.as_dict() config_dict['POSCAR'] = self.poscar.as_dict() # caution the key and the value are not always the same config_dict['POTCAR'] = self.potcar.as_dict() # dict(zip(self.potcar.as_dict()['symbols'], # self.potcar.as_dict()['symbols'])) config_dict['KPOINTS'] = self.kpoints.as_dict() # self.user_incar_settings = self.incar.as_dict() DictVaspInputSet.__init__(self, name, config_dict, ediff_per_atom=False, **kwargs) if vis_logger: self.logger = vis_logger else: self.logger = logger
def run_pbe_calculation(dim=2, submit=True, force_overwrite=False): """ Setup and submit a normal PBE calculation for band structure along high symmetry k-paths. Args: dim (int): 2 for relaxing a 2D material, 3 for a 3D material. submit (bool): Whether or not to submit the job. force_overwrite (bool): Whether or not to overwrite files if an already converged vasprun.xml exists in the directory. """ PBE_INCAR_DICT = {'EDIFF': 1e-6, 'IBRION': 2, 'ISIF': 3, 'ISMEAR': 1, 'NSW': 0, 'LVTOT': True, 'LVHAR': True, 'LORBIT': 1, 'LREAL': 'Auto', 'NPAR': 4, 'PREC': 'Accurate', 'LWAVE': True, 'SIGMA': 0.1, 'ENCUT': 500, 'ISPIN': 2} directory = os.getcwd().split('/')[-1] if not os.path.isdir('pbe_bands'): os.mkdir('pbe_bands') if force_overwrite or not is_converged('pbe_bands'): os.system('cp CONTCAR pbe_bands/POSCAR') if os.path.isfile('POTCAR'): os.system('cp POTCAR pbe_bands/') PBE_INCAR_DICT.update({'MAGMOM': get_magmom_string()}) Incar.from_dict(PBE_INCAR_DICT).write_file('pbe_bands/INCAR') structure = Structure.from_file('POSCAR') kpath = HighSymmKpath(structure) Kpoints.automatic_linemode(20, kpath).write_file('pbe_bands/KPOINTS') os.chdir('pbe_bands') if dim == 2: remove_z_kpoints() if QUEUE == 'pbs': write_pbs_runjob(directory, 1, 16, '800mb', '6:00:00', VASP) submission_command = 'qsub runjob' elif QUEUE == 'slurm': write_slurm_runjob(directory, 16, '800mb', '6:00:00', VASP) submission_command = 'sbatch runjob' if submit: os.system(submission_command) os.chdir('../')
def fff(): allline = '' s = Structure.from_file("POSCAR") incar_dict = dict(PREC='Accurate', ENCUT=45678, NBANDS=456789, ISMEAR=0, EDIFF='1E-7', LCHARG='.FALSE.', NEDOS=5000, ISPIN=2, ISIF=2, IBRION=1, NELM=400, LORBIT=11, NPAR=4, LWAVE='.FALSE.') incar = Incar.from_dict(incar_dict) user_incar_settings = { "EDIFF": 1E-6, "ISIF": 2, "NSW": 0, "LORBIT": 11, "ENCUT": 34, "LWAVE": '.FALSE.', "PREC": 'Accurate' } mpvis = MPBSHSEVaspInputSet(user_incar_settings=incar) #mpvis = MPNonSCFVaspInputSet(user_incar_settings=incar) kpoints = mpvis.get_kpoints(s) kpoints.write_file("KPOINTS") print kpoints import sys sys.exit() all_kp = kpoints.kpts labels = kpoints.labels all_labels = '' for l in labels: all_labels = all_labels + str(l) + str(' ') for k in all_kp: #allline=allline+str(k) allline = allline + str(k[0]) + str(' ') + str(k[1]) + str(' ') + str( k[2]) + str(' ') print allline file = open('bandd.conf', 'w') line = str('FREQUENCY_CONVERSION_FACTOR = 521.471') + '\n' file.write(line) line = str('ATOM_NAME = Si O') + '\n' file.write(line) line = str('DIM = 1 1 1') + '\n' file.write(line) line = str('FORCE_CONSTANTS = READ') + '\n' file.write(line) line = str("BAND= ") + str(allline) + '\n' file.write(line) line = str("BAND_LABELS= ") + str(all_labels) + '\n' file.write(line) file.close()
def __init__(self, name, incar, poscar, kpoints, potcar=None, qadapter=None, script_name='submit_script', vis_logger=None, reuse_path=None, test=False, **kwargs): """ default INCAR from config_dict """ self.name = name self.test = test #print (test) self.incar_init = Incar.from_dict(incar.as_dict()) self.poscar_init = Poscar.from_dict(poscar.as_dict()) if not self.test: self.potcar_init = Potcar.from_dict(potcar.as_dict()) if not isinstance(kpoints, str): self.kpoints_init = Kpoints.from_dict(kpoints.as_dict()) #print (kpoints) else: self.kpoints_init = kpoints self.reuse_path = reuse_path # complete reuse paths self.extra = kwargs if qadapter is not None: self.qadapter = qadapter.from_dict(qadapter.to_dict()) else: self.qadapter = None self.script_name = script_name config_dict = {} config_dict['INCAR'] = self.incar_init.as_dict() config_dict['POSCAR'] = self.poscar_init.as_dict() # caution the key and the value are not always the same if not self.test: config_dict['POTCAR'] = self.potcar_init.as_dict() # dict(zip(self.potcar.as_dict()['symbols'], # self.potcar.as_dict()['symbols'])) if not isinstance(kpoints, str): #print (self.kpoints_init) config_dict['KPOINTS'] = self.kpoints_init.as_dict() else: # need to find a way to dictify this kpoints string more # appropriately config_dict['KPOINTS'] = {'kpts_hse': self.kpoints_init} # self.user_incar_settings = self.incar.as_dict() DictSet.__init__(self, poscar.structure, config_dict) #**kwargs) if vis_logger: self.logger = vis_logger else: self.logger = logger
def run_major_axis_anisotropy_calculations(submit=True): """ Perform static calculations with the magnetic axis along 100, 010, and 001. Kwargs: submit (bool): Whether or not to submit the job. """ if not os.path.isdir('MAE'): os.mkdir('MAE') os.chdir('MAE') for d in ['100', '010', '001']: if not os.path.isdir(d): os.path.mkdir(d) os.chdir(d) os.system('cp ../CONTCAR POSCAR') os.system('cp ../POTCAR .') axis = [float(char) for char in d] # Small positive number, see vasp manual if d in ['001', '010']: axis[0] = 0.00000001 else: axis[1] = 0.00000001 saxis = ' '.join(axis) incar_dict = INCAR_DICT incar_dict.update({ 'EDIFF': 1e-8, 'GGA_COMPAT': False, 'ISMEAR': -5, 'LORBIT': 11, 'LSORBIT': True, 'LWAVE': False, 'LCHARG': False, 'LAECHG': False, 'MAGMOM': get_magmom_string(), 'SAXIS': saxis }) Incar.from_dict(incar_dict).write_file('INCAR') if submit: os.system(submission_command)
def from_dict(cls, d): incar = Incar.from_dict(d["incar"]) poscar = Poscar.from_dict(d["poscar"]) potcar = Potcar.from_dict(d["potcar"]) kpoints = Kpoints.from_dict(d["kpoints"]) qadapter = None if d["qadapter"] is not None: qadapter = CommonAdapter.from_dict(d["qadapter"]) return MPINTVaspInputSet(d["name"], incar, poscar, potcar, kpoints, qadapter, **d["kwargs"])
def get_incar(self): """ get_incar() Create and return a :class:`~pymatgen.io.vasp.inputs.Incar` instance initialized from the node's stored incar data contents. :return: a pymatgen Incar data instance :rtype: :class:`pymatgen.io.vasp.inputs.Incar` """ return Incar.from_dict(self.get_dict())
def from_dict(cls, d): incar = Incar.from_dict(d["incar"]) poscar = Poscar.from_dict(d["poscar"]) potcar = Potcar.from_dict(d["potcar"]) kpoints = Kpoints.from_dict(d["kpoints"]) qadapter = None if d["qadapter"] is not None: qadapter = CommonAdapter.from_dict(d["qadapter"]) script_name = d["script_name"] return MPINTVaspInputSet(d["name"], incar, poscar, potcar, kpoints, qadapter, script_name=script_name, vis_logger=logging.getLogger(d["logger"]), **d["kwargs"])
def from_dict(cls, d): incar = Incar.from_dict(d["incar"]) poscar = Poscar.from_dict(d["poscar"]) potcar = Potcar.from_dict(d["potcar"]) kpoints = Kpoints.from_dict(d["kpoints"]) cal = Calibrate(incar, poscar, potcar, kpoints, system=d["system"], is_matrix=d["is_matrix"], Grid_type=d["Grid_type"], parent_job_dir=d["parent_job_dir"], job_dir=d["job_dir"], qadapter=d.get("qadapter"), job_cmd=d["job_cmd"], wait=d["wait"], turn_knobs=d["turn_knobs"]) cal.job_dir_list = d["job_dir_list"] cal.job_ids = d["job_ids"] return cal
def from_dict(cls, d): incar = Incar.from_dict(d["incar"]) poscar = Poscar.from_dict(d["poscar"]) potcar = Potcar.from_dict(d["potcar"]) kpoints = Kpoints.from_dict(d["kpoints"]) cal = Calibrate(incar, poscar, potcar, kpoints, system=d["system"], is_matrix = d["is_matrix"], Grid_type = d["Grid_type"], parent_job_dir=d["parent_job_dir"], job_dir=d["job_dir"], qadapter=d.get("qadapter"), job_cmd=d["job_cmd"], wait=d["wait"], turn_knobs=d["turn_knobs"]) cal.job_dir_list = d["job_dir_list"] cal.job_ids = d["job_ids"] return cal
def __init__(self, name, incar, poscar, kpoints, potcar=None, qadapter=None, script_name='submit_script', vis_logger=None, reuse_path=None, test=False, **kwargs): """ default INCAR from config_dict """ self.name = name self.test = test self.incar_init = Incar.from_dict(incar.as_dict()) self.poscar_init = Poscar.from_dict(poscar.as_dict()) if not self.test: self.potcar_init = Potcar.from_dict(potcar.as_dict()) if not isinstance(kpoints, str): self.kpoints_init = Kpoints.from_dict(kpoints.as_dict()) else: self.kpoints_init = kpoints self.reuse_path = reuse_path # complete reuse paths self.extra = kwargs if qadapter is not None: self.qadapter = qadapter.from_dict(qadapter.to_dict()) else: self.qadapter = None self.script_name = script_name config_dict = {} config_dict['INCAR'] = self.incar_init.as_dict() config_dict['POSCAR'] = self.poscar_init.as_dict() # caution the key and the value are not always the same if not self.test: config_dict['POTCAR'] = self.potcar_init.as_dict() # dict(zip(self.potcar.as_dict()['symbols'], # self.potcar.as_dict()['symbols'])) if not isinstance(kpoints, str): config_dict['KPOINTS'] = self.kpoints_init.as_dict() else: # need to find a way to dictify this kpoints string more # appropriately config_dict['KPOINTS'] = {'kpts_hse':self.kpoints_init} # self.user_incar_settings = self.incar.as_dict() DictSet.__init__(self, poscar.structure, config_dict) #**kwargs) if vis_logger: self.logger = vis_logger else: self.logger = logger
def StepVASP0(my_project, struct_list, order_key=0): """ 1. reads a poscar list of a 2D motif(s) 2. sets the default incar, kpoints and potcar as per mw database Returns: checkpoint Motif_like_2D_relax.json, Motif_like_bulk_relax.json """ WORKFLOWS = my_project['Workflow'] Workflow_Params = WORKFLOWS['Steps'][order_key] Workflow_name = Workflow_Params['NAME'] job_dir = my_project['NAME'] + Workflow_Params['NAME'] logger = get_logger(job_dir) chkpt = job_dir + '.json' incar_dict = my_project['Incar_General'] incar_init = Incar.from_dict(incar_dict) kpoints_init = Kpoints.monkhorst_automatic( [18, 18, 18]) # an initialization to anything sensible # Decide the Kpoints density per atom setting here turn_knobs= OrderedDict({'POSCAR': struct_list,'KPOINTS':Workflow_Params['KPOINTS'],\ 'POTCAR_pseudopotential':Workflow_Params['PSEUDOPOTENTIAL']}) if Workflow_Params['Other_Knobs']: #for k in Workflow_Params['Other_Knobs']: #print (type(Workflow_Params['Other_Knobs'])) turn_knobs.update(Workflow_Params['Other_Knobs']) job_bin = vasp_config[Workflow_Params['Queue']['Bin']] qdict = Workflow_Params['Queue'] # Decide general queue settings for all runs in this step #print (turn_knobs) qadapter, job_cmd = get_run_cmmnd(partition=qdict['Partition'],ntasks=qdict['Ntasks'],\ nnodes = qdict['Nnodes'],walltime=qdict['Walltime'],job_bin=job_bin,\ mem=qdict['Memory'], job_name=job_dir) # run the jobs in this step run_cal(turn_knobs, qadapter, job_cmd, job_dir, logger, chkpt, incar=incar_init, kpoints=kpoints_init, poscar=struct_list[0], magnetism=Workflow_Params['Magnetism'],\ is_matrix=Workflow_Params['Matrix'],\ Grid_type=Workflow_Params['Kpt_Grid']) return [chkpt]
def converge_incar(args, console): table = Table(title="{} Convergence Study".format(args.tag)) table.add_column("Directory") table.add_column("{} Value".format(args.tag)) for i, value in enumerate(args.values): dirname = "{}_{}".format(args.tag, i) os.mkdir(dirname) shutil.copy("POSCAR", os.path.join(dirname, "POSCAR")) shutil.copy("POTCAR", os.path.join(dirname, "POTCAR")) shutil.copy("KPOINTS", os.path.join(dirname, "KPOINTS")) shutil.copy(args.jobfile, os.path.join(dirname, args.jobfile)) tags = Incar.from_file("INCAR").as_dict() tags[args.tag] = value incar = Incar.from_dict(tags) incar.write_file(os.path.join(dirname, "INCAR")) os.chdir(dirname) #os.system("{} {}".format(args.jobcmd, args.jobfile)) os.chdir("..") table.add_row(dirname, "{}".format(value)) console.print(table)
def converg_kpoints(length=0,mat=None): """ Function to converg K-points Args: lenght: K-point line density mat: Poscar object with structure information Returns: length1: K-point line density """ en1=-10000 encut=550 convg_kp1=False convg_kp2=False length1=length kp_list=[] while convg_kp2 !=True: #while convg_kp1 !=True and convg_kp2 !=True: tol=0.001 #change 0.001 incar_dict = use_incar_dict incar_dict.update({"ENCUT":encut}) incar = Incar.from_dict(incar_dict) length1=length1+5 print ("Incrementing length",length1) kpoints=Auto_Kpoints(mat=mat,length=length1) mesh=kpoints.kpts[0] if mesh not in kp_list: kp_list.append(mesh) en2,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('KPOINTS')+str(mat.comment)+str('-')+str(length1)) while abs(en2-en1)>tol: en1=en2 print ("Incrementing length",length1) incar_dict = use_incar_dict incar_dict.update({"ENCUT":encut}) incar = Incar.from_dict(incar_dict) while mesh in kp_list: length1=length1+5 ##Assuming you are not super unlucky kpoints=Auto_Kpoints(mat=mat,length=length1) mesh=kpoints.kpts[0] kpoints=Auto_Kpoints(mat=mat,length=length1) mesh=kpoints.kpts[0] if mesh not in kp_list: kp_list.append(mesh) en2,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('KPOINTS')+str(mat.comment)+str('-')+str(length1)) else: length1=length1+5 ##Assuming you are not super unlucky kpoints=Auto_Kpoints(mat=mat,length=length1) mesh=kpoints.kpts[0] kp_list.append(mesh) en2,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('KPOINTS')+str(mat.comment)+str('-')+str(length1)) convg_kp1=True # Some extra points to check print ("Some extra points to check for KPOINTS") length3=length1+5 kpoints=Auto_Kpoints(mat=mat,length=length3) mesh=kpoints.kpts[0] kp_list.append(mesh) en3,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('KPOINTS')+str(mat.comment)+str('-')+str(length3)) length4=length3+5 kpoints=Auto_Kpoints(mat=mat,length=length4) mesh=kpoints.kpts[0] kp_list.append(mesh) en4,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('KPOINTS')+str(mat.comment)+str('-')+str(length4)) length5=length4+5 kpoints=Auto_Kpoints(mat=mat,length=length5) mesh=kpoints.kpts[0] kp_list.append(mesh) en5,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('KPOINTS')+str(mat.comment)+str('-')+str(length5)) length6=length5+5 kpoints=Auto_Kpoints(mat=mat,length=length6) mesh=kpoints.kpts[0] kp_list.append(mesh) en6,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('KPOINTS')+str(mat.comment)+str('-')+str(length6)) length7=length6+5 kpoints=Auto_Kpoints(mat=mat,length=length7) mesh=kpoints.kpts[0] kp_list.append(mesh) en7,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('KPOINTS')+str(mat.comment)+str('-')+str(length7)) #if en3-en2>tol or en4-en2>tol or en5-en2>tol or en6-en2>tol or en7-en2>tol: #if abs(en3-en2)>tol and abs(en4-en2)>tol and abs(en5-en2)>tol and abs(en6-en2)>tol and abs(en7-en2)>tol: if abs(en3-en2)>tol or abs(en4-en2)>tol or abs(en5-en2)>tol or abs(en6-en2)>tol or abs(en7-en2)>tol: fkp=open("EXTRA_KPOINTS","w") line=str("Extra KPOINTS needed ")+str(length1)+'\n' fkp.write(line) line=str("en2 length1 ")+str (" ")+str(en2)+str(" ")+str(length1)+'\n' fkp.write(line) line=str("en3 length3 ")+str (" ")+str(en3)+str(" ")+str(length3)+'\n' fkp.write(line) line=str("en4 length4 ")+str (" ")+str(en4)+str(" ")+str(length4)+'\n' fkp.write(line) line=str("en5 length5 ")+str (" ")+str(en5)+str(" ")+str(length5)+'\n' fkp.write(line) fkp.close() en1=en3 length1=length3 else: print ("KPOINTS convergence achieved for ",mat.comment,length1) convg_kp2=True return length1
def converg_encut(encut=500,mat=None): """ Function to converg plane-wave cut-off Args: encut: intial cutoff mat: Poscar object Returns: encut: converged cut-off """ en1=-10000 encut1=encut convg_encut1=False convg_encut2=False while convg_encut2 !=True: #while convg_encut1 !=True and convg_encut2 !=True: tol=0.001 #change 0.001 encut_list=[] encut_list.append(encut) length=10 encut1=encut+50 incar_dict = use_incar_dict incar_dict.update({"ENCUT":encut}) #print (use_incar_dict) incar = Incar.from_dict(incar_dict) kpoints=Auto_Kpoints(mat=mat,length=length) print ("running smart_converge for",str(mat.comment)+str('-')+str('ENCUT')+str('-')+str(encut)) en2,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('ENCUT')+str(mat.comment)+str('-')+str(encut)) while abs(en2-en1)>tol: en1=en2 encut1=encut+50 encut_list.append(encut) print("Incrementing encut",encut) incar_dict = use_incar_dict incar_dict.update({"ENCUT":encut1}) incar = Incar.from_dict(incar_dict) print ("running smart_converge for",str(mat.comment)+str('-')+str('ENCUT')+str('-')+str(encut)) en2,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('ENCUT')+str(mat.comment)+str('-')+str(encut)) convg_encut1=True # Some extra points to check print ("Some extra points to check for ENCUT") encut2=encut1+50 incar['ENCUT']=encut2 en3,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('ENCUT')+str(mat.comment)+str('-')+str(encut2)) encut3=encut2+50 incar['ENCUT']=encut3 en4,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('ENCUT')+str(mat.comment)+str('-')+str(encut3)) encut4=encut3+50 incar['ENCUT']=encut4 en5,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('ENCUT')+str(mat.comment)+str('-')+str(encut4)) encut5=encut4+50 incar['ENCUT']=encut5 en6,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('ENCUT')+str(mat.comment)+str('-')+str(encut5)) encut6=encut5+50 incar['ENCUT']=encut6 en7,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('ENCUT')+str(mat.comment)+str('-')+str(encut6)) #if en3-en2>tol or en4-en2>tol or en5-en2>tol or en6-en2>tol or en7-en2>tol: #if abs(en3-en2)>tol and abs(en4-en2)>tol and abs(en5-en2)>tol and abs(en6-en2)>tol and abs(en7-en2)>tol: if abs(en3-en2)>tol or abs(en4-en2)>tol or abs(en5-en2)>tol or abs(en6-en2)>tol or abs(en7-en2)>tol: en1=en3 encut=encut1 fen=open("EXTRA_ENCUT","w") line=str("Extra ENCUT needed ")+str(encut)+'\n' fen.write(line) fen.close() else: print ("ENCUT convergence achieved for ",mat.comment,encut) convg_encut2=True return encut
def run_gamma_calculations(submit=True, step_size=0.5): """ Setup a 2D grid of static energy calculations to plot the Gamma surface between two layers of the 2D material. These calculations are run and stored in subdirectories under 'friction/lateral'. Args: submit (bool): Whether or not to submit the jobs. step_size (float): the distance between grid points in Angstroms. """ if not os.path.isdir('friction'): os.mkdir('friction') os.chdir('friction') if not os.path.isdir('lateral'): os.mkdir('lateral') os.chdir('lateral') os.system('cp ../../CONTCAR POSCAR') # Pad the bottom layer with 20 Angstroms of vacuum. utl.ensure_vacuum(Structure.from_file('POSCAR'), 20) structure = Structure.from_file('POSCAR') n_sites_per_layer = structure.num_sites n_divs_x = int(math.ceil(structure.lattice.a / step_size)) n_divs_y = int(math.ceil(structure.lattice.b / step_size)) # Get the thickness of the material. max_height = max([site.coords[2] for site in structure.sites]) min_height = min([site.coords[2] for site in structure.sites]) thickness = max_height - min_height # Make a new layer. species, coords = [], [] for site in structure.sites: # Original site species.append(site.specie) coords.append(site.coords) # New layer site species.append(site.specie) coords.append( [site.coords[0], site.coords[1], site.coords[2] + thickness + 3.5]) Structure(structure.lattice, species, coords, coords_are_cartesian=True).to('POSCAR', 'POSCAR') for x in range(n_divs_x): for y in range(n_divs_y): dir = '{}x{}'.format(x, y) if not os.path.isdir(dir): os.mkdir(dir) # Copy input files os.chdir(dir) os.system('cp ../../../INCAR .') os.system('cp ../../../KPOINTS .') os.system('cp ../POSCAR .') if VDW_KERNEL: os.system('cp {} .'.format(VDW_KERNEL)) # Shift the top layer structure = Structure.from_file("POSCAR") all_z_coords = [s.coords[2] for s in structure.sites] top_layer = [ s for s in structure.sites if s.coords[2] > np.mean(all_z_coords) ] structure.remove_sites( [i for i, s in enumerate(structure.sites) if s in top_layer]) for site in top_layer: structure.append(site.specie, [ site.coords[0] + float(x) / float(n_divs_x), site.coords[1] + float(y) / float(n_divs_y), site.coords[2] ], coords_are_cartesian=True) structure = structure.get_sorted_structure() structure.to("POSCAR", "POSCAR") utl.write_potcar() incar_dict = Incar.from_file('INCAR').as_dict() incar_dict.update({ 'NSW': 0, 'LAECHG': False, 'LCHARG': False, 'LWAVE': False, 'LVTOT': False, 'MAGMOM': utl.get_magmom_string(structure) }) incar_dict.pop('NPAR', None) Incar.from_dict(incar_dict).write_file('INCAR') if QUEUE_SYSTEM == 'pbs': utl.write_pbs_runjob(dir, 1, 8, '1000mb', '2:00:00', VASP_STD_BIN) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': utl.write_slurm_runjob(dir, 8, '1000mb', '2:00:00', VASP_STD_BIN) submission_command = 'sbatch runjob' if submit: os.system(submission_command) os.chdir('../') os.chdir('../../')
def step3(): """ put aligned & relaxed 2d materials in all possible ways on the aligned & relaxed slab, relax interface ionic positions(ISIF=2) - uses info from step2_sub.json and step2_2d.json - creates required input files and submits the jobs to the que - 8(pairs) * 2(atoms in graphene basis) = 16 jobs - returns: step3.json """ seperation = 3 # in angstroms nlayers_2d = 1 nlayers_sub = 2 hkl_sub = [1,1,1] hkl_2d = [0,0,1] #job directory for the runs name = 'step3' job_dir = 'step3' # incar incar = Incar.from_dict(incar_dict) incar['ISMEAR'] = 1 incar['ISIF'] = 2 # kpoints kpoints = Kpoints.monkhorst_automatic(kpts=(18, 18, 1)) # load in previous jobs relaxed_sub_jobs = Calibrate.jobs_from_file('step2_sub.json') relaxed_2d_jobs = Calibrate.jobs_from_file('step2_2d.json') # create list of all substrate poscars all_poscars = [] # loop over aligned & relaxed substrates and 2d for jsub, j2d in zip(relaxed_sub_jobs,relaxed_2d_jobs): # substrate job_dir_sub = os.path.join(jsub.parent_job_dir, jsub.job_dir) contcar_file = os.path.join(job_dir_sub, 'CONTCAR') # read in as structure object substrate_slab_aligned = Structure.from_file(contcar_file) species_sub = ''.join([tos.symbol for tos in substrate_slab_aligned.types_of_specie]) # 2d job_dir_2d = os.path.join(j2d.parent_job_dir, j2d.job_dir) contcar_file = os.path.join(job_dir_2d, 'CONTCAR') # read in as structure object mat2d_slab_aligned = Structure.from_file(contcar_file) species_2d = ''.join([tos.symbol for tos in mat2d_slab_aligned.types_of_specie]) # position the aligned materials in all possible ways hetero_interfaces = generate_all_configs(mat2d_slab_aligned, substrate_slab_aligned, nlayers_2d, nlayers_sub, seperation ) # loop over all hetero-interfaces for i, iface in enumerate(hetero_interfaces): sd_flags = CalibrateSlab.set_sd_flags(interface=iface, n_layers=nlayers_2d+nlayers_sub, top=True, bottom=False) poscar = Poscar(iface, selective_dynamics=sd_flags) poscar.comment = '_'.join([species_sub,species_2d,str(i)]) all_poscars.append(poscar) # setup calibrate and run'em turn_knobs = OrderedDict( [ ('POSCAR', all_poscars) ]) qadapter, job_cmd = get_run_cmmnd(nnodes=nnodes, nprocs=nprocs, walltime=walltime, job_bin=bin_sub, mem=mem) run_cal(turn_knobs, qadapter, job_cmd, job_dir, name, incar=incar, kpoints=kpoints) return [name+'.json']
def run_gamma_calculations(submit=True, step_size=0.5): """ Setup a 2D grid of static energy calculations to plot the Gamma surface between two layers of the 2D material. These calculations are run and stored in subdirectories under 'friction/lateral'. Args: submit (bool): Whether or not to submit the jobs. step_size (float): the distance between grid points in Angstroms. """ if not os.path.isdir('friction'): os.mkdir('friction') os.chdir('friction') if not os.path.isdir('lateral'): os.mkdir('lateral') os.chdir('lateral') try: os.system('cp ../../CONTCAR POSCAR') except: try: os.system('cp ../../POSCAR .') except: raise IOError('No POSCAR or CONTCAR found in ' + os.path.dirname(os.path.dirname(os.getcwd()))) # Pad the bottom layer with 20 Angstroms of vacuum. utl.ensure_vacuum(Structure.from_file('POSCAR'), 20) structure = Structure.from_file('POSCAR') n_sites_per_layer = structure.num_sites n_divs_x = int(math.ceil(structure.lattice.a / step_size)) n_divs_y = int(math.ceil(structure.lattice.b / step_size)) # Get the thickness of the material. max_height = max([site.coords[2] for site in structure.sites]) min_height = min([site.coords[2] for site in structure.sites]) thickness = max_height - min_height # Make a new layer. species, coords = [], [] for site in structure.sites: # Original site species.append(site.specie) coords.append(site.coords) # New layer site species.append(site.specie) coords.append( [site.coords[0], site.coords[1], site.coords[2] + thickness + 3.5]) Structure(structure.lattice, species, coords).to('POSCAR', 'POSCAR') for x in range(n_divs_x): for y in range(n_divs_y): dir = '{}x{}'.format(x, y) if not os.path.isdir(dir): os.mkdir(dir) # Copy input files os.chdir(dir) if not os.path.exists('../../INCAR'): raise IOError('No INCAR found in ' + os.path.dirname(os.path.dirname(os.getcwd()))) if not os.path.exists('../../KPOINTS'): raise IOError('No KPOINTS found in ' + os.path.dirname(os.path.dirname(os.getcwd()))) os.system('cp ../../../INCAR .') os.system('cp ../../../KPOINTS .') os.system('cp ../POSCAR .') if VDW_KERNEL: os.system('cp {} .'.format(VDW_KERNEL)) utl.write_potcar() incar_dict = Incar.from_file('INCAR').as_dict() incar_dict.update({ 'NSW': 0, 'LAECHG': False, 'LCHARG': False, 'LWAVE': False, 'LVTOT': False, 'MAGMOM': utl.get_magmom_string(Structure.from_file('POSCAR')) }) incar_dict.pop('NPAR', None) Incar.from_dict(incar_dict).write_file('INCAR') # Shift the top layer poscar_lines = open('POSCAR').readlines() with open('POSCAR', 'w') as poscar: for line in poscar_lines[:8 + n_sites_per_layer]: poscar.write(line) for line in poscar_lines[8 + n_sites_per_layer:]: split_line = line.split() new_coords = [ float(split_line[0]) + float(x) / float(n_divs_x), float(split_line[1]) + float(y) / float(n_divs_y), float(split_line[2]) ] poscar.write(' '.join([str(i) for i in new_coords]) + '\n') sub_exe = True if VASP_STD_BIN == 'None': print 'Executable is missing in ' + os.getcwd() + '/runjob' print 'Configure mpint_config.yaml file with your executable!' sub_exe = False if QUEUE_SYSTEM == 'pbs': utl.write_pbs_runjob(dir, 1, 8, '1000mb', '2:00:00', VASP_STD_BIN) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': utl.write_slurm_runjob(dir, 8, '1000mb', '2:00:00', VASP_STD_BIN) submission_command = 'sbatch runjob' if submit and sub_exe: os.system(submission_command) os.chdir('../') os.chdir('../../')
# sort structure into groups of elements atoms for Potcar mapping iface.sort() # vasp input incar_dict = { 'SYSTEM': 'test', 'ENCUT': 500, 'ISIF': 2, 'IBRION': 2, 'ISMEAR': 1, 'EDIFF': 1e-06, 'NPAR': 8, 'SIGMA': 0.1, 'NSW': 100, 'PREC': 'Accurate' } incar = Incar.from_dict(incar_dict) poscar = Poscar(iface) potcar = Potcar(poscar.site_symbols) kpoints = Kpoints.automatic(20) #set job list. if empty a single job will be run encut_list = [] #range(400,800,100) turn_knobs = OrderedDict([('ENCUT', encut_list)]) #job directory job_dir = 'vasp_job' # run settings qadapter = None job_cmd = None nprocs = 16 nnodes = 1 walltime = '24:00:00' mem = 1000
def run_normal_force_calculations(basin_and_saddle_dirs, spacings=np.arange(1.5, 4.25, 0.25), submit=True): """ Set up and run static calculations of the basin directory and saddle directory at specified interlayer spacings to get f_N and f_F. Args: basin_and_saddle_dirs (tuple): Can be obtained by the get_basin_and_peak_locations() function under friction.analysis. For example, run_normal_force_calculations(('0x0', '3x6')) or run_normal_force_calculations(get_basin_and_peak_locations()) will both work. spacings (tuple): list of interlayer spacings (in Angstroms, as floats) at which to run the calculations. submit (bool): Whether or not to submit the jobs. """ spacings = [str(spc) for spc in spacings] os.chdir('friction') if not os.path.isdir('normal'): os.mkdir('normal') os.chdir('normal') for spacing in spacings: if not os.path.isdir(spacing): os.mkdir(spacing) for subdirectory in basin_and_saddle_dirs: os.system('cp -r ../lateral/{} {}/'.format(subdirectory, spacing)) os.chdir('{}/{}'.format(spacing, subdirectory)) structure = Structure.from_file('POSCAR') n_sites = len(structure.sites) all_z_coords = [s.coords[2] for s in structure.sites] top_layer = [ s for s in structure.sites if s.coords[2] > np.mean(all_z_coords) ] bottom_of_top_layer = min([site.coords[2] for site in top_layer]) remove_indices = [ i for i, s in enumerate(structure.sites) if s in top_layer ] structure.remove_sites(remove_indices) top_of_bottom_layer = max( [site.coords[2] for site in structure.sites]) for site in top_layer: structure.append(site.specie, [ site.coords[0], site.coords[1], site.coords[2] - bottom_of_top_layer + top_of_bottom_layer + float(spacing) ], coords_are_cartesian=True) structure = structure.get_sorted_structure() structure.to('POSCAR', 'POSCAR') utl.write_potcar() incar_dict = Incar.from_file('INCAR').as_dict() incar_dict.update({"MAGMOM": utl.get_magmom_string(structure)}) Incar.from_dict(incar_dict).write_file("INCAR") if QUEUE_SYSTEM == 'pbs': utl.write_pbs_runjob('{}_{}'.format(subdirectory, spacing), 1, 8, '1000mb', '2:00:00', VASP_STD_BIN) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': utl.write_slurm_runjob('{}_{}'.format(subdirectory, spacing), 8, '1000mb', '2:00:00', VASP_STD_BIN) submission_command = 'sbatch runjob' if submit: os.system(submission_command) os.chdir('../../') os.chdir('../../')
def run_major_axis_anisotropy_calculations(submit=True): """ Perform static calculations with the magnetic axis along 100, 010, and 001. Args: submit (bool): Whether or not to submit the job. """ if not os.path.isdir('MAE'): os.mkdir('MAE') os.chdir('MAE') for d in ['100', '010', '001']: if not os.path.isdir(d): os.mkdir(d) os.chdir(d) os.system('cp ../CONTCAR POSCAR') os.system('cp ../POTCAR .') axis = [float(char) for char in d] # Small positive number, see vasp manual if d in ['001', '010']: axis[0] = 0.00000001 else: axis[1] = 0.00000001 saxis = ' '.join(axis) incar_dict = INCAR_DICT incar_dict.update({ 'EDIFF': 1e-8, 'GGA_COMPAT': False, 'ISMEAR': -5, 'LORBIT': 11, 'LSORBIT': True, 'LWAVE': False, 'LCHARG': False, 'LAECHG': False, 'MAGMOM': get_magmom_string(Structure.from_file('POSCAR')), 'SAXIS': saxis }) Incar.from_dict(incar_dict).write_file('INCAR') if QUEUE_SYSTEM == 'pbs': utl.write_pbs_runjob(directory, 1, 16, '800mb', '6:00:00', VASP_TWOD_BIN) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': utl.write_slurm_runjob(directory, 16, '800mb', '6:00:00', VASP_TWOD_BIN) submission_command = 'sbatch runjob' if submit: os.system(submission_command)
def run_hse_calculation(dim=2, submit=True, force_overwrite=False, destroy_prep_directory=False): """ Setup/submit an HSE06 calculation to get an accurate band structure. Requires a previous IBZKPT from a standard DFT run. See http://cms.mpi.univie.ac.at/wiki/index.php/Si_bandstructure for more details. Args: dim (int): 2 for relaxing a 2D material, 3 for a 3D material. submit (bool): Whether or not to submit the job. force_overwrite (bool): Whether or not to overwrite files if an already converged vasprun.xml exists in the directory. destroy_prep_directory (bool): whether or not to remove (rm -r) the hse_prep directory, if it exists. This can help to automatically clean up and save space. """ HSE_INCAR_DICT = { 'LHFCALC': True, 'HFSCREEN': 0.2, 'AEXX': 0.25, 'ALGO': 'D', 'TIME': 0.4, 'NSW': 0, 'LVTOT': True, 'LVHAR': True, 'LORBIT': 11, 'LWAVE': True, 'NPAR': 8, 'PREC': 'Accurate', 'EDIFF': 1e-4, 'ENCUT': 450, 'ICHARG': 2, 'ISMEAR': 1, 'SIGMA': 0.1, 'IBRION': 2, 'ISIF': 3, 'ISPIN': 2 } if not os.path.isdir('hse_bands'): os.mkdir('hse_bands') if force_overwrite or not is_converged('hse_bands'): os.chdir('hse_bands') os.system('cp ../CONTCAR ./POSCAR') if os.path.isfile('../POTCAR'): os.system('cp ../POTCAR .') HSE_INCAR_DICT.update( {'MAGMOM': get_magmom_string(Structure.from_file('POSCAR'))}) Incar.from_dict(HSE_INCAR_DICT).write_file('INCAR') # Re-use the irreducible brillouin zone KPOINTS from a # previous standard DFT run. if os.path.isdir('../hse_prep'): ibz_lines = open('../hse_prep/IBZKPT').readlines() if destroy_prep_directory: os.system('rm -r ../hse_prep') else: ibz_lines = open('../IBZKPT').readlines() n_ibz_kpts = int(ibz_lines[1].split()[0]) kpath = HighSymmKpath(Structure.from_file('POSCAR')) Kpoints.automatic_linemode(20, kpath).write_file('KPOINTS') if dim == 2: remove_z_kpoints() linemode_lines = open('KPOINTS').readlines() abs_path = [] i = 4 while i < len(linemode_lines): start_kpt = linemode_lines[i].split() end_kpt = linemode_lines[i + 1].split() increments = [(float(end_kpt[0]) - float(start_kpt[0])) / 20, (float(end_kpt[1]) - float(start_kpt[1])) / 20, (float(end_kpt[2]) - float(start_kpt[2])) / 20] abs_path.append(start_kpt[:3] + ['0', start_kpt[4]]) for n in range(1, 20): abs_path.append([ str(float(start_kpt[0]) + increments[0] * n), str(float(start_kpt[1]) + increments[1] * n), str(float(start_kpt[2]) + increments[2] * n), '0' ]) abs_path.append(end_kpt[:3] + ['0', end_kpt[4]]) i += 3 n_linemode_kpts = len(abs_path) with open('KPOINTS', 'w') as kpts: kpts.write('Automatically generated mesh\n') kpts.write('{}\n'.format(n_ibz_kpts + n_linemode_kpts)) kpts.write('Reciprocal Lattice\n') for line in ibz_lines[3:]: kpts.write(line) for point in abs_path: kpts.write('{}\n'.format(' '.join(point))) if QUEUE_SYSTEM == 'pbs': write_pbs_runjob('{}_hsebands'.format(os.getcwd().split('/')[-2]), 2, 64, '1800mb', '50:00:00', VASP_STD_BIN) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': write_slurm_runjob( '{}_hsebands'.format(os.getcwd().split('/')[-2]), 64, '1800mb', '50:00:00', VASP_STD_BIN) submission_command = 'sbatch runjob' if submit: _ = subprocess.check_output(submission_command.split()) os.chdir('../')
def run_gamma_calculations(submit=True, step_size=0.5): """ Setup a 2D grid of static energy calculations to plot the Gamma surface between two layers of the 2D material. These calculations are run and stored in subdirectories under 'friction/lateral'. Args: submit (bool): Whether or not to submit the jobs. step_size (float): the distance between grid points in Angstroms. """ if not os.path.isdir('friction'): os.mkdir('friction') os.chdir('friction') if not os.path.isdir('lateral'): os.mkdir('lateral') os.chdir('lateral') os.system('cp ../../CONTCAR POSCAR') # Pad the bottom layer with 20 Angstroms of vacuum. utl.add_vacuum(20 - utl.get_spacing(), 0.8) structure = Structure.from_file('POSCAR') n_sites_per_layer = structure.num_sites n_divs_x = int(math.ceil(structure.lattice.a / step_size)) n_divs_y = int(math.ceil(structure.lattice.b / step_size)) # Get the thickness of the material. max_height = max([site.coords[2] for site in structure.sites]) min_height = min([site.coords[2] for site in structure.sites]) thickness = max_height - min_height # Make a new layer. new_sites = [] for site in structure.sites: new_sites.append((site.specie, [site.coords[0], site.coords[1], site.coords[2] + thickness + 3.5])) for site in new_sites: structure.append(site[0], site[1], coords_are_cartesian=True) #structure.get_sorted_structure().to('POSCAR', 'POSCAR') structure.to('POSCAR', 'POSCAR') for x in range(n_divs_x): for y in range(n_divs_y): dir = '{}x{}'.format(x, y) if not os.path.isdir(dir): os.mkdir(dir) # Copy input files os.chdir(dir) os.system('cp ../../../INCAR .') os.system('cp ../../../KPOINTS .') os.system('cp ../POSCAR .') if VDW_KERNEL != '/path/to/vdw_kernel.bindat': os.system('cp {} .'.format(VDW_KERNEL)) utl.write_potcar() incar_dict = Incar.from_file('INCAR').as_dict() incar_dict.update({'NSW': 0, 'LAECHG': False, 'LCHARG': False, 'LWAVE': False, 'MAGMOM': utl.get_magmom_string()}) incar_dict.pop('NPAR', None) Incar.from_dict(incar_dict).write_file('INCAR') # Shift the top layer poscar_lines = open('POSCAR').readlines() with open('POSCAR', 'w') as poscar: for line in poscar_lines[:8 + n_sites_per_layer]: poscar.write(line) for line in poscar_lines[8 + n_sites_per_layer:]: split_line = line.split() new_coords = [ float(split_line[0]) + float(x)/float(n_divs_x), float(split_line[1]) + float(y)/float(n_divs_y), float(split_line[2])] poscar.write(' '.join([str(i) for i in new_coords]) + '\n') if QUEUE == 'pbs': utl.write_pbs_runjob(dir, 1, 4, '800mb', '1:00:00', VASP) submission_command = 'qsub runjob' elif QUEUE == 'slurm': utl.write_slurm_runjob(dir, 4, '800mb', '1:00:00', VASP) submission_command = 'sbatch runjob' if submit: os.system(submission_command) os.chdir('../') os.chdir('../../')
def run_gamma_calculations(submit=True, step_size=0.5): """ Setup a 2D grid of static energy calculations to plot the Gamma surface between two layers of the 2D material. These calculations are run and stored in subdirectories under 'friction/lateral'. Args: submit (bool): Whether or not to submit the jobs. step_size (float): the distance between grid points in Angstroms. """ if not os.path.isdir('friction'): os.mkdir('friction') os.chdir('friction') if not os.path.isdir('lateral'): os.mkdir('lateral') os.chdir('lateral') os.system('cp ../../CONTCAR POSCAR') # Pad the bottom layer with 20 Angstroms of vacuum. utl.ensure_vacuum(Structure.from_file('POSCAR'), 20) structure = Structure.from_file('POSCAR') n_sites_per_layer = structure.num_sites n_divs_x = int(math.ceil(structure.lattice.a / step_size)) n_divs_y = int(math.ceil(structure.lattice.b / step_size)) # Get the thickness of the material. max_height = max([site.coords[2] for site in structure.sites]) min_height = min([site.coords[2] for site in structure.sites]) thickness = max_height - min_height # Make a new layer. species, coords = [], [] for site in structure.sites: # Original site species.append(site.specie) coords.append(site.coords) # New layer site species.append(site.specie) coords.append([site.coords[0], site.coords[1], site.coords[2] + thickness + 3.5]) Structure(structure.lattice, species, coords, coords_are_cartesian=True).to('POSCAR', 'POSCAR') for x in range(n_divs_x): for y in range(n_divs_y): dir = '{}x{}'.format(x, y) if not os.path.isdir(dir): os.mkdir(dir) # Copy input files os.chdir(dir) os.system('cp ../../../INCAR .') os.system('cp ../../../KPOINTS .') os.system('cp ../POSCAR .') if VDW_KERNEL: os.system('cp {} .'.format(VDW_KERNEL)) # Shift the top layer structure = Structure.from_file("POSCAR") all_z_coords = [s.coords[2] for s in structure.sites] top_layer = [s for s in structure.sites if s.coords[2] > np.mean(all_z_coords)] structure.remove_sites([i for i, s in enumerate(structure.sites) if s in top_layer]) for site in top_layer: structure.append( site.specie, [site.coords[0]+float(x)/float(n_divs_x), site.coords[1]+float(y)/float(n_divs_y), site.coords[2]], coords_are_cartesian=True ) structure = structure.get_sorted_structure() structure.to("POSCAR", "POSCAR") utl.write_potcar() incar_dict = Incar.from_file('INCAR').as_dict() incar_dict.update({'NSW': 0, 'LAECHG': False, 'LCHARG': False, 'LWAVE': False, 'LVTOT': False, 'MAGMOM': utl.get_magmom_string(structure)}) incar_dict.pop('NPAR', None) Incar.from_dict(incar_dict).write_file('INCAR') if QUEUE_SYSTEM == 'pbs': utl.write_pbs_runjob(dir, 1, 8, '1000mb', '2:00:00', VASP_STD_BIN) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': utl.write_slurm_runjob(dir, 8, '1000mb', '2:00:00', VASP_STD_BIN) submission_command = 'sbatch runjob' if submit: os.system(submission_command) os.chdir('../') os.chdir('../../')
def smart_converge(mat=None,encut='',leng='',band_str=True,elast_prop=True,optical_prop=True,mbj_prop=True,spin_orb=False,phonon=False,surf_en=False,def_en=False): """ Main function to converge k-points/cut-off optimize structure, and run subsequent property calculations Args: mat: Poscar object with structure information encut: if '' then automataic convergence, else use defined fixed-cutoff leng: if '' then automataic convergence, else use defined fixed-line density band_str: if True then do band-structure calculations along high-symmetry points elast_prop: if True then do elastic property calculations using finite-difference optical_prop: if True do frequency dependent dielectric function calculations using he independent-particle (IP) approximation mbj_prop: if True do METAGGA-TBmBJ optical property calculations with IP approximation spin_orb: if True do spin-orbit calculations phonon: if True do phonon calculations using DFPT surf_en: if True do surface enrgy calculations def_en: if True do defect enrgy calculations Returns: en2: final energy mat_f: final structure """ if encut=="": encut=converg_encut(encut=500,mat=mat) if leng=="": leng= converg_kpoints(length=0,mat=mat) kpoints=Auto_Kpoints(mat=mat,length=leng) isif=2 commen=str(mat.comment) lcharg='.FALSE.' if commen.split('@')[0] =='bulk' : isif=3 lcharg='.TRUE.' if commen.split('@')[0] == 'sbulk': isif=3 incar_dict = use_incar_dict incar_dict.update({"ENCUT":encut,"EDIFFG":-1E-3,"ISIF":3,"NEDOS":5000,"NSW":500,"NELM":500,"LORBIT":11,"LVTOT":'.TRUE.',"LVHAR":'.TRUE.',"ISPIN":2,"LCHARG":'.TRUE.'}) incar = Incar.from_dict(incar_dict) try: if mat.comment.startswith('Mol'): incar.update({"ISIF": '2'}) except: print ("Mol error") pass #if commen.startswith('Surf-') : # pol=check_polar(mat_f.structure) # if pol==True: # ase_atoms = AseAtomsAdaptor().get_atoms(mat_f.structure) # COM=ase_atoms.get_center_of_mass(scaled=True) # incar.update({"LDIPOL": '.TRUE.',"IDIPOL":4,"ISYM": 0,"DIPOL":COM}) print ("running smart_converge for",str(mat.comment)+str('-')+str('MAIN-RELAX')) cwd=str(os.getcwd()) en2,contc=run_job(mat=mat,incar=incar,kpoints=kpoints,jobname=str('MAIN-RELAX')+str('-')+str(mat.comment)) os.chdir(cwd) path=str(contc.split('/CONTCAR')[0])+str('/vasprun.xml') v=open(path,"r").readlines() for line in v: if "NBANDS" in line: nbands=int(line.split(">")[1].split("<")[0]) print ("nbands=",nbands) break strt=Structure.from_file(contc) mat_f=Poscar(strt) mat_f.comment=str(mat.comment) if band_str==True: incar_dict = use_incar_dict incar_dict.update({"ISPIN":2,"NEDOS":5000,"LORBIT":11,"IBRION":1,"ENCUT":encut,"NBANDS":int(nbands)+10}) incar = Incar.from_dict(incar_dict) kpath = HighSymmKpath(mat_f.structure) frac_k_points, k_points_labels = kpath.get_kpoints(line_density=20,coords_are_cartesian=False) kpoints = Kpoints(comment="Non SCF run along symmetry lines",style=Kpoints.supported_modes.Reciprocal,num_kpts=len(frac_k_points),kpts=frac_k_points, labels=k_points_labels,kpts_weights=[1] * len(frac_k_points)) try: print ("running MAIN-BAND") kpoints=mpvis.get_kpoints(mat_f.structure) en2B,contcB=run_job(mat=mat_f,incar=incar,kpoints=kpoints,jobname=str('MAIN-BAND')+str('-')+str(mat_f.comment)) # kpoints=mpvis.get_kpoints(mat_f.structure) # en2B,contcB=run_job(mat=mat_f,incar=incar,kpoints=kpoints,jobname=str('MAIN-BAND')+str('-')+str(mat_f.comment)) except: print ("No band str calc.") if str(os.getcwd)!=cwd: print ("Changing directory") line=str("cd ")+str(cwd) os.chdir(cwd) print (os.getcwd()) pass os.chdir(cwd) if surf_en==True: incar_dict = use_incar_dict incar_dict.update({"ENCUT":encut,"NEDOS":5000,"IBRION":1,"NSW":500,"LORBIT":11}) incar = Incar.from_dict(incar_dict) surf=surfer(mat=mat_f.structure,layers=3) for i in surf: try: print ("running MAIN-BAND") #NSCF #chg_file=str(contc).replace('CONTCAR','CHGCAR') #print ('chrfile',chg_file) #shutil.copy2(chg_file,'./') kpoints=Auto_Kpoints(mat=i,length=leng) en2s,contcs=run_job(mat=i,incar=incar,kpoints=kpoints,jobname=str('Surf_en-')+str(i.comment)+str('-')+str(mat_f.comment)) #kpoints=mpvis.get_kpoints(mat_f.structure) #en2B,contcB=run_job(mat=mat_f,incar=incar,kpoints=kpoints,jobname=str('MAIN-BAND')+str('-')+str(mat_f.comment)) except: pass os.chdir(cwd) if def_en==True: incar_dict = use_incar_dict incar_dict.update({"ENCUT":encut,"NEDOS":5000,"IBRION":1,"NSW":500,"LORBIT":11}) incar = Incar.from_dict(incar_dict) #surf=surfer(mat=mat_f.structure,layers=3) vac=vac_antisite_def_struct_gen(cellmax=3,struct=mat_f.structure) for i in vac: try: print ("running MAIN-vac") kpoints=Auto_Kpoints(mat=i,length=leng) en2d,contcd=run_job(mat=i,incar=incar,kpoints=kpoints,jobname=str('Def_en-')+str(i.comment)+str('-')+str(mat_f.comment)) # kpoints=mpvis.get_kpoints(mat_f.structure) # en2B,contcB=run_job(mat=mat_f,incar=incar,kpoints=kpoints,jobname=str('MAIN-BAND')+str('-')+str(mat_f.comment)) except: pass os.chdir(cwd) #surf=surfer(mat=strt,layers=layers) #surf=surfer(mat=strt,layers=layers) if spin_orb==True: #chg_file=str(contc).replace('CONTCAR','CHGCAR') #print ('chrfile',chg_file) #shutil.copy2(chg_file,'./') incar_dict = use_incar_dict incar_dict.update({"ENCUT":encut,"NPAR":ncores,"GGA_COMPAT":'.FALSE.',"LSORBIT":'.TRUE.',"IBRION":1,"ISYM":0,"NEDOS":5000,"IBRION":1,"NSW":500,"LORBIT":11}) incar = Incar.from_dict(incar_dict) sg_mat = SpacegroupAnalyzer(mat_f.structure) mat_cvn = sg_mat.get_conventional_standard_structure() mat_cvn.sort() kpoints=Auto_Kpoints(mat=Poscar(mat_cvn),length=leng/2) try: en2S,contcS=run_job(mat=Poscar(mat_cvn),incar=incar,kpoints=kpoints,jobname=str('MAIN-SOC')+str('-')+str(mat_f.comment)) except: pass os.chdir(cwd) if optical_prop==True: incar_dict = use_incar_dict incar_dict.update({"NEDOS":5000,"LORBIT":11,"IBRION":1,"ENCUT":encut,"NBANDS":3*int(nbands),"LOPTICS":'.TRUE.'}) incar = Incar.from_dict(incar_dict) kpoints=Auto_Kpoints(mat=mat_f,length=leng) try: en2OP,contcOP=run_job(mat=mat_f,incar=incar,kpoints=kpoints,jobname=str('MAIN-OPTICS')+str('-')+str(mat_f.comment)) except: pass os.chdir(cwd) if mbj_prop==True: incar_dict = use_incar_dict incar_dict.update({"NEDOS":5000,"LORBIT":11,"IBRION":1,"ENCUT":encut,"NBANDS":3*int(nbands),"LOPTICS":'.TRUE.','METAGGA':'MBJ','ISYM':0,"SIGMA":0.1}) incar = Incar.from_dict(incar_dict) kpoints=Auto_Kpoints(mat=mat_f,length=leng) try: en2OP,contcOP=run_job(mat=mat_f,incar=incar,kpoints=kpoints,jobname=str('MAIN-MBJ')+str('-')+str(mat_f.comment)) except: pass os.chdir(cwd) if elast_prop==True: incar_dict = use_incar_dict incar_dict.update({"NEDOS":5000,"IBRION":6,"ENCUT":1.3*float(encut),"ISIF":3,"POTIM":0.015,"NPAR":ncores,"ISPIN":2}) incar = Incar.from_dict(incar_dict) sg_mat = SpacegroupAnalyzer(mat_f.structure) mat_cvn = sg_mat.get_conventional_standard_structure() mat_cvn.sort() kpoints=Auto_Kpoints(mat=Poscar(mat_cvn),length=leng) try: en2E,contcE=run_job(mat=Poscar(mat_cvn),incar=incar,kpoints=kpoints,jobname=str('MAIN-ELASTIC')+str('-')+str(mat_f.comment)) except: pass os.chdir(cwd) if phonon==True: incar_dict = use_incar_dict incar_dict.update({"IBRION":8,"ENCUT":float(encut),"ISYM":0,"ADDGRID":'.TRUE.','EDIFF': 1e-09,'LORBIT': 11}) incar = Incar.from_dict(incar_dict) kpoints=Auto_Kpoints(mat=mat_f,length=leng) mat_pho=make_big(poscar=mat_f,size=11.0) try: en2P,contcP=run_job(mat=mat_pho,incar=incar,kpoints=kpoints,jobname=str('MAIN-PHO8')+str('-')+str(mat_f.comment)) except: pass os.chdir(cwd) #if Raman_calc==True: # Raman(strt=mat_f,encut=encut,length=leng) os.chdir(cwd) return en2,mat_f
def prepare(self, submit=False): """ Set up calculation directories to calibrate the ion corrections to match a specified framework of INCAR parameters, k-points, and potcar hashes. Args: submit (bool): whether or not to submit each job after preparing it. """ for elt in self._potcar_dict: # Set up reference directory for the pure element. if not os.path.isdir(elt): os.mkdir(elt) os.chdir(elt) # Poscar s = MPR.get_structure_by_material_id( self._config['Mpids'][elt]['self']) s.to('POSCAR', 'POSCAR') plines = open('POSCAR').readlines() elements = plines[5].split() # Kpoints kp = Kpoints.automatic_density(s, self._n_kpts_per_atom) kp.write_file('KPOINTS') # Incar incar = Incar.from_dict(self._incar_dict) incar.write_file('INCAR') # Potcar utl.write_potcar(types=[self._potcar_dict[el] for el in elements]) # Runjob if QUEUE == 'pbs': utl.write_pbs_runjob('{}_cal'.format(elt), self._ncores, self._nprocs, self._pmem, self._walltime, self._binary) submission_command = 'qsub runjob' elif QUEUE == 'slurm': utl.write_slurm_runjob('{}_cal'.format(elt), self._nprocs, self._pmem, self._walltime, self._binary) submission_command = 'sbatch runjob' if submit: os.system(submission_command) # Set up reference oxide compound subdirectory. if elt not in ['O', 'S', 'F', 'Cl', 'Br', 'I']: if not os.path.isdir('ref'): os.mkdir('ref') os.chdir('ref') # Poscar s = MPR.get_structure_by_material_id( self._config['Mpids'][elt]['ref']) s.to('POSCAR', 'POSCAR') plines = open('POSCAR').readlines() elements = plines[5].split() # Kpoints kp = Kpoints.automatic_density(s, self._n_kpts_per_atom) kp.write_file('KPOINTS') # Incar incar = Incar.from_dict(self._incar_dict) incar.write_file('INCAR') # Potcar utl.write_potcar( types=[self._potcar_dict[el] for el in elements]) # Runjob if QUEUE == 'slurm': utl.write_pbs_runjob('{}_cal'.format(elt), self._ncores, self._nprocs, self._pmem, self._walltime, self._binary) submission_command = 'qsub runjob' elif QUEUE == 'pbs': utl.write_slurm_runjob('{}_cal'.format(elt), self._nprocs, self._pmem, self._walltime, self._binary) submission_command = 'sbatch runjob' if submit: os.system(submission_command) os.chdir('../') os.chdir('../')
from rich.console import console if __name__ == "__main__": console = Console() parser = argparse.ArgumentParser( description="Restarts a calculation after timeout or failure.") parser.add_argument("--jobcmd", default=os.environ.get("JOBCMD"), help="command used to submit a job file") parser.add_argument("--jobfile", default=os.environ.get("JOBFILE"), help="filename of the job submission file") args = parser.parse_args() if args.jobcmd is None: args.jobcmd = "sbatch" if args.jobfile is None: args.jobfile = "runjob.slurm" os.remove("POSCAR") os.rename("CONTCAR", "POSCAR") incar = Incar.from_file("INCAR") incar_tags = incar.as_dict() incar_tags["ISTART"] = 1 incar = Incar.from_dict(incar_tags) incar.write_file("INCAR") os.system("{} {}".format(args.jobcmd, args.jobfile)) console.print("[bold green]SUCCESS:[/bold green] job restarted")
def run_gamma_calculations(submit=True, step_size=0.5): """ Setup a 2D grid of static energy calculations to plot the Gamma surface between two layers of the 2D material. These calculations are run and stored in subdirectories under 'friction/lateral'. Args: submit (bool): Whether or not to submit the jobs. step_size (float): the distance between grid points in Angstroms. """ if not os.path.isdir('friction'): os.mkdir('friction') os.chdir('friction') if not os.path.isdir('lateral'): os.mkdir('lateral') os.chdir('lateral') os.system('cp ../../CONTCAR POSCAR') # Pad the bottom layer with 20 Angstroms of vacuum. utl.add_vacuum(20 - utl.get_spacing(), 0.8) structure = Structure.from_file('POSCAR') n_sites_per_layer = structure.num_sites n_divs_x = int(math.ceil(structure.lattice.a / step_size)) n_divs_y = int(math.ceil(structure.lattice.b / step_size)) # Get the thickness of the material. max_height = max([site.coords[2] for site in structure.sites]) min_height = min([site.coords[2] for site in structure.sites]) thickness = max_height - min_height # Make a new layer. new_sites = [] for site in structure.sites: new_sites.append((site.specie, [site.coords[0], site.coords[1], site.coords[2] + thickness + 3.5])) for site in new_sites: structure.append(site[0], site[1], coords_are_cartesian=True) #structure.get_sorted_structure().to('POSCAR', 'POSCAR') structure.to('POSCAR', 'POSCAR') for x in range(n_divs_x): for y in range(n_divs_y): dir = '{}x{}'.format(x, y) if not os.path.isdir(dir): os.mkdir(dir) # Copy input files os.chdir(dir) os.system('cp ../../../INCAR .') os.system('cp ../../../KPOINTS .') os.system('cp ../POSCAR .') if VDW_KERNEL != '/path/to/vdw_kernel.bindat': os.system('cp {} .'.format(VDW_KERNEL)) utl.write_potcar() incar_dict = Incar.from_file('INCAR').as_dict() incar_dict.update({'NSW': 0, 'LAECHG': False, 'LCHARG': False, 'LWAVE': False, 'LVTOT': False, 'MAGMOM': utl.get_magmom_string()}) incar_dict.pop('NPAR', None) Incar.from_dict(incar_dict).write_file('INCAR') # Shift the top layer poscar_lines = open('POSCAR').readlines() with open('POSCAR', 'w') as poscar: for line in poscar_lines[:8 + n_sites_per_layer]: poscar.write(line) for line in poscar_lines[8 + n_sites_per_layer:]: split_line = line.split() new_coords = [ float(split_line[0]) + float(x)/float(n_divs_x), float(split_line[1]) + float(y)/float(n_divs_y), float(split_line[2])] poscar.write(' '.join([str(i) for i in new_coords]) + '\n') if QUEUE == 'pbs': utl.write_pbs_runjob(dir, 1, 8, '1000mb', '2:00:00', VASP) submission_command = 'qsub runjob' elif QUEUE == 'slurm': utl.write_slurm_runjob(dir, 8, '1000mb', '2:00:00', VASP) submission_command = 'sbatch runjob' if submit: os.system(submission_command) os.chdir('../') os.chdir('../../')
def setup_poscar_jobs(self, scale_list=None, poscar_list=None): """ for scaling the latice vectors of the original structure, scale_list is volume scaling factor list """ if scale_list: for scale in scale_list: self.set_poscar(scale=scale) self.set_potcar() if not self.is_matrix: job_dir = self.job_dir + os.sep + 'POS' + \ os.sep + 'VOLUME_' + str(scale) self.add_job(name=job_dir, job_dir=job_dir) elif poscar_list: for pos in poscar_list: # if it is a twod_database run or any general standard database run, # the incar, kpoints and potcar follow a standard input set # which will be activated by the twod_database tag set to true # NOTE: this implementation means that the first turn_knobs tag # needs to be the poscar objects list # the database tag will be set to the name of the yaml file with the # standard input deck definition for that database # this incar dict provided as the init can be general format # based on the chosen functional, cutoff # so self.incar is a vdW incar for re-relaxation in vdW, gga for every # other calculation or LDA+U for LSDA+U calculations incar_dict = self.incar.as_dict() if self.reuse: # if this is a true list minimally, ['CONTCAR'] # it is to be ensured that the poscar list is a # list of paths as opposed to list of poscar objects by the turn knobs # values # Here pos is the path and r in each self.reuse is the name of the file(s) # to be reused # in a reuse calculation the following are possible: # update incar (Solvation calculations) or reset incar (HSE calculations) # reset kpoints file with IBZKPT # copy a CHGCAR or WAVECAR or both perhaps try: # first setup of POSCAR initial, INCAR, KPOINTS poscar = Poscar.from_file(pos + os.sep + 'CONTCAR') self.logger.info('Read previous relaxed CONTCAR file from {}'. format(pos)) # check if it is KPOINTS altering job like HSE if self.Grid_type == 'hse_bands_2D_prep': # HSE prep calcualtions # reset the INCAR file with a magmom only if exists try: incar_dict = { 'MAGMOM': get_magmom_string(poscar)} except: incar_dict = {} incar_dict = get_2D_incar_hse_prep(incar_dict) self.set_kpoints(poscar=poscar) self.logger.info( 'updated input set for HSE 2D prep calcaultion') elif self.Grid_type == 'hse_bands_2D': # HSE calculation # reset the incar and kpoints file builds # on the preceding calculations (prep calculation) # IBZKPT try: incar_dict = { 'MAGMOM': get_magmom_string(poscar)} except: incar_dict = {} incar_dict = get_2D_incar_hse(incar_dict) self.set_kpoints(poscar=poscar, ibzkpth=pos + os.sep + 'IBZKPT') self.logger.info('updated input set for HSE calcaultion\ using IBZKPT from {0}'.format(pos + os.sep + 'IBZKPT')) elif self.Grid_type == 'hse_bands': # general HSE bands pass elif self.Grid_type == 'Finer_G_Mesh': self.logger.info('updating to Finer G Mesh') kpoint = Kpoints.from_file(pos+os.sep+'KPOINTS') self.set_kpoints(kpoint=kpoint.kpts[0]) else: # use the same kpoints file and build from the old # incar self.kpoints = Kpoints.from_file( pos + os.sep + 'KPOINTS') # decide on how to use incar, use same one or # update or afresh if self.reuse_incar == 'old': incar_dict = Incar.from_file( pos + os.sep + 'INCAR').as_dict() elif self.reuse_incar == 'update': # way to go for cutoff updates, convergence, etc. # but retain the old functional incar_dict.update(Incar.from_file(pos + os.sep + 'INCAR'). as_dict()) else: # use a fresh incar as specified by the init # way to go for example for LDAU or other # major removals done to INCAR # but always retain the MAGMOM if present old_incar_dict = Incar.from_file( pos + os.sep + 'INCAR').as_dict() if 'MAGMOM' in old_incar_dict.keys(): incar_dict['MAGMOM'] = old_incar_dict[ 'MAGMOM'] else: incar_dict = incar_dict if isinstance(self.reuse, list): reuse_paths = [ pos + os.sep + r for r in self.reuse] self.reuse_paths = reuse_paths # Magnetism use cases, updates to be made to the INCAR (MAE) # and poscar (AFM) # MAE and AFM if self.magnetism == 'MAE': # remove vdW tags for MAE calculations vdW_tags = ('GGA', 'AGGAC', 'LUSE_VDW', 'PARAM1', 'PARAM2') for key in vdW_tags: if key in incar_dict: del incar_dict[key] self.logger.info( 'updating input set for MAE calculation') self.mag_init = Outcar( pos + os.sep + 'OUTCAR').total_mag nbands = 2 * \ Vasprun(pos + os.sep + 'vasprun.xml').parameters['NBANDS'] # u_value = Vasprun(pos+os.sep+'vasprun.xml').incar['LDAUU'] # u_value = 4.0 self.logger.info( "updating mag mom with value {0}".format(self.mag_init)) self.logger.info( "updating NBANDS with {0}".format(nbands)) incar_dict.update({'NBANDS': nbands, 'LSORBIT': True, 'EDIFF': 1e-08, 'ICHARG': 11, 'LMAXMIX': 4, 'LCHARG': False, 'ISYM': 0, 'NSW': 0, 'ISPIN': 2, 'IBRION': -1, 'LORBIT': 11, 'MAGMOM': get_magmom_mae(poscar, self.mag_init) }) # incar_dict.update({'LDAUU': u_value}) elif self.magnetism == 'AFM': self.logger.info( 'updating INCAR and POSCAR for AFM calculation') afm, poscar = get_magmom_afm(poscar, self.database) incar_dict.update({'MAGMOM': afm}) except: # check what to do if the previous calculation being reused is not # actuall done .. system exit or adopt a user override # with POSCAR self.logger.warn( 'Empty relaxed CONTCAR file .. Probably job not done') if not self.reuse_override: self.logger.warn( 'You can set reuse_override to continue with POSCAR file, exiting now ..') sys.exit(0) else: self.logger.info('Using old Poscar for rerun') poscar = Poscar.from_file(pos + os.sep + 'POSCAR') # case for non - reuse else: poscar = pos # temporary: magnetism only set if twod flag is activated if self.database == 'twod': incar_dict.update( {'MAGMOM': get_magmom_string(poscar)}) self.set_kpoints(poscar=poscar) self.incar = Incar.from_dict(incar_dict) self.set_poscar(poscar=poscar) self.set_potcar() if not self.is_matrix: job_dir = self.job_dir + os.sep + 'POS' + \ os.sep + self.val_to_name(poscar) self.add_job(name=job_dir, job_dir=job_dir)
def test_as_dict_and_from_dict(self): d = self.incar.as_dict() incar2 = Incar.from_dict(d) self.assertEqual(self.incar, incar2)
PREC = 'Accurate', ENCUT = 400, ISMEAR = 0, EDIFF = '1E-6', ISIF = 3, IBRION = 2, NSW = 500, NPAR = 4, LCHARG = '.FALSE.', GGA = 'BO', PARAM1 = 0.1833333333, PARAM2 = 0.2200000000, LUSE_VDW = '.TRUE.', AGGAC = 0.0000 ) # INCAR incar_sub = Incar.from_dict(incar_dict) incar_sub['ISMEAR'] = 1 incar_2d = Incar.from_dict(incar_dict) # KPOINTS kpoints_sub = Kpoints.monkhorst_automatic(kpts=(18, 18, 18)) kpoints_2d = Kpoints.monkhorst_automatic(kpts=(18, 18, 1)) # QUE nprocs = 32 nnodes = 1 mem='1000' walltime = '24:00:00' bin_sub = '/home/km468/Software/VASP/vasp.5.3.5/vasp' bin_2d = '/home/km468/Software/VASP/vasp.5.3.5/vasp_noz' # STRUCTURES substrates = [ 'Pt', 'Ag', 'Cu', 'Ni', 'Al' , 'Au', 'Pd', 'Ir'] mat2ds = ['POSCAR_graphene']
def run_pbe_calculation(dim=2, submit=True, force_overwrite=False): """ Setup and submit a normal PBE calculation for band structure along high symmetry k-paths. Args: dim (int): 2 for relaxing a 2D material, 3 for a 3D material. submit (bool): Whether or not to submit the job. force_overwrite (bool): Whether or not to overwrite files if an already converged vasprun.xml exists in the directory. """ PBE_INCAR_DICT = { 'EDIFF': 1e-6, 'IBRION': 2, 'ICHARG': 2, 'ISIF': 3, 'ISMEAR': 1, 'NSW': 0, 'LVTOT': True, 'LVHAR': True, 'LORBIT': 1, 'LREAL': 'Auto', 'NPAR': 4, 'PREC': 'Accurate', 'LWAVE': True, 'SIGMA': 0.1, 'ENCUT': 500, 'ISPIN': 2 } directory = os.path.basename(os.getcwd()) if not os.path.isdir('pbe_bands'): os.mkdir('pbe_bands') if force_overwrite or not is_converged('pbe_bands'): shutil.copy("CONTCAR", "pbe_bands/POSCAR") structure = Structure.from_file("pbe_bands/POSCAR") if os.path.isfile("POTCAR"): shutil.copy("POTCAR", "pbe_bands") shutil.copy("CHGCAR", "pbe_bands") PBE_INCAR_DICT.update({'MAGMOM': get_magmom_string(structure)}) Incar.from_dict(PBE_INCAR_DICT).write_file('pbe_bands/INCAR') os.chdir('pbe_bands') write_band_structure_kpoints(structure, dim=dim) if QUEUE_SYSTEM == 'pbs': write_pbs_runjob(directory, 1, 16, '800mb', '6:00:00', VASP_STD_BIN) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': write_slurm_runjob(directory, 16, '800mb', '6:00:00', VASP_STD_BIN) submission_command = 'sbatch runjob' if submit: _ = subprocess.check_output(submission_command.split()) os.chdir('../')
def test_as_dict_and_from_dict(self): d = self.incar.as_dict() incar2 = Incar.from_dict(d) self.assertEqual(self.incar, incar2)
from mpinterfaces.utils import * # all the info/warnings/outputs redirected to the log file: convg.log logger = get_logger('convg') incar_dict = dict( PREC='Accurate', ENCUT=400, ISMEAR=1, EDIFF='1E-6', NSW=0, NPAR=4, LCHARG='.FALSE.', LWAVE='.FALSE.') # INCAR incar = Incar.from_dict(incar_dict) # KPOINTS kpoints = Kpoints.monkhorst_automatic(kpts=(12, 12, 12)) # QUE nprocs = 8 nnodes = 1 mem = '1000' walltime = '1:00:00' job_bin = '/home/km468/Software/VASP/vasp.5.3.5/vasp' qadapter, job_cmd = get_run_cmmnd(nnodes=nnodes, nprocs=nprocs, walltime=walltime, job_bin=job_bin, mem=mem) # STRUCTURES structures = ['Pt', 'Ag', 'Cu'] poscar_list = []
def run_normal_force_calculations(basin_and_saddle_dirs, spacings=np.arange(1.5, 4.25, 0.25), submit=True): """ Set up and run static calculations of the basin directory and saddle directory at specified interlayer spacings to get f_N and f_F. Args: basin_and_saddle_dirs (tuple): Can be obtained by the get_basin_and_peak_locations() function under friction.analysis. For example, run_normal_force_calculations(('0x0', '3x6')) or run_normal_force_calculations(get_basin_and_peak_locations()) will both work. spacings (tuple): list of interlayer spacings (in Angstroms, as floats) at which to run the calculations. submit (bool): Whether or not to submit the jobs. """ spacings = [str(spc) for spc in spacings] os.chdir('friction') if not os.path.isdir('normal'): os.mkdir('normal') os.chdir('normal') for spacing in spacings: if not os.path.isdir(spacing): os.mkdir(spacing) for subdirectory in basin_and_saddle_dirs: os.system('cp -r ../lateral/{} {}/'.format(subdirectory, spacing)) os.chdir('{}/{}'.format(spacing, subdirectory)) structure = Structure.from_file('POSCAR') n_sites = len(structure.sites) all_z_coords = [s.coords[2] for s in structure.sites] top_layer = [s for s in structure.sites if s.coords[2] > np.mean(all_z_coords)] bottom_of_top_layer = min([site.coords[2] for site in top_layer]) remove_indices = [i for i, s in enumerate(structure.sites) if s in top_layer] structure.remove_sites(remove_indices) top_of_bottom_layer = max( [site.coords[2] for site in structure.sites] ) for site in top_layer: structure.append( site.specie, [site.coords[0], site.coords[1], site.coords[2] - bottom_of_top_layer + top_of_bottom_layer + float(spacing)], coords_are_cartesian=True) structure = structure.get_sorted_structure() structure.to('POSCAR', 'POSCAR') utl.write_potcar() incar_dict = Incar.from_file('INCAR').as_dict() incar_dict.update({"MAGMOM": utl.get_magmom_string(structure)}) Incar.from_dict(incar_dict).write_file("INCAR") if QUEUE_SYSTEM == 'pbs': utl.write_pbs_runjob('{}_{}'.format( subdirectory, spacing), 1, 8, '1000mb', '2:00:00', VASP_STD_BIN) submission_command = 'qsub runjob' elif QUEUE_SYSTEM == 'slurm': utl.write_slurm_runjob('{}_{}'.format( subdirectory, spacing), 8, '1000mb', '2:00:00', VASP_STD_BIN) submission_command = 'sbatch runjob' if submit: os.system(submission_command) os.chdir('../../') os.chdir('../../')
def run_hse_calculation(dim=2, submit=True, force_overwrite=False, destroy_prep_directory=False): """ Setup/submit an HSE06 calculation to get an accurate band structure. Requires a previous IBZKPT from a standard DFT run. See http://cms.mpi.univie.ac.at/wiki/index.php/Si_bandstructure for more details. Args: dim (int): 2 for relaxing a 2D material, 3 for a 3D material. submit (bool): Whether or not to submit the job. force_overwrite (bool): Whether or not to overwrite files if an already converged vasprun.xml exists in the directory. destroy_prep_directory (bool): whether or not to remove (rm -r) the hse_prep directory, if it exists. This can help you to automatically clean up and save space. """ HSE_INCAR_DICT = {'LHFCALC': True, 'HFSCREEN': 0.2, 'AEXX': 0.25, 'ALGO': 'D', 'TIME': 0.4, 'NSW': 0, 'LVTOT': True, 'LVHAR': True, 'LORBIT': 11, 'LWAVE': True, 'NPAR': 8, 'PREC': 'Accurate', 'EDIFF': 1e-4, 'ENCUT': 450, 'ICHARG': 2, 'ISMEAR': 1, 'SIGMA': 0.1, 'IBRION': 2, 'ISIF': 3, 'ISPIN': 2} if not os.path.isdir('hse_bands'): os.mkdir('hse_bands') if force_overwrite or not is_converged('hse_bands'): os.chdir('hse_bands') os.system('cp ../CONTCAR ./POSCAR') if os.path.isfile('../POTCAR'): os.system('cp ../POTCAR .') HSE_INCAR_DICT.update({'MAGMOM': get_magmom_string()}) Incar.from_dict(HSE_INCAR_DICT).write_file('INCAR') # Re-use the irreducible brillouin zone KPOINTS from a # previous standard DFT run. if os.path.isdir('../hse_prep'): ibz_lines = open('../hse_prep/IBZKPT').readlines() if destroy_prep_directory: os.system('rm -r ../hse_prep') else: ibz_lines = open('../IBZKPT').readlines() n_ibz_kpts = int(ibz_lines[1].split()[0]) kpath = HighSymmKpath(Structure.from_file('POSCAR')) Kpoints.automatic_linemode(20, kpath).write_file('KPOINTS') if dim == 2: remove_z_kpoints() linemode_lines = open('KPOINTS').readlines() abs_path = [] i = 4 while i < len(linemode_lines): start_kpt = linemode_lines[i].split() end_kpt = linemode_lines[i+1].split() increments = [ (float(end_kpt[0]) - float(start_kpt[0])) / 20, (float(end_kpt[1]) - float(start_kpt[1])) / 20, (float(end_kpt[2]) - float(start_kpt[2])) / 20 ] abs_path.append(start_kpt[:3] + ['0', start_kpt[4]]) for n in range(1, 20): abs_path.append( [str(float(start_kpt[0]) + increments[0] * n), str(float(start_kpt[1]) + increments[1] * n), str(float(start_kpt[2]) + increments[2] * n), '0'] ) abs_path.append(end_kpt[:3] + ['0', end_kpt[4]]) i += 3 n_linemode_kpts = len(abs_path) with open('KPOINTS', 'w') as kpts: kpts.write('Automatically generated mesh\n') kpts.write('{}\n'.format(n_ibz_kpts + n_linemode_kpts)) kpts.write('Reciprocal Lattice\n') for line in ibz_lines[3:]: kpts.write(line) for point in abs_path: kpts.write('{}\n'.format(' '.join(point))) if QUEUE == 'pbs': write_pbs_runjob('{}_hsebands'.format( os.getcwd().split('/')[-2]), 2, 64, '1800mb', '50:00:00', VASP) submission_command = 'qsub runjob' elif QUEUE == 'slurm': write_slurm_runjob('{}_hsebands'.format( os.getcwd().split('/')[-2]), 64, '1800mb', '50:00:00', VASP) submission_command = 'sbatch runjob' if submit: os.system(submission_command) os.chdir('../')