def test_as_dict_from_dict(self): k = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0]) d = k.as_dict() k2 = Kpoints.from_dict(d) self.assertEqual(k.kpts, k2.kpts) self.assertEqual(k.style, k2.style) self.assertEqual(k.kpts_shift, k2.kpts_shift)
def run_task(self, fw_spec): prev_dir = fw_spec.get('PREV_DIR', None) self.custom_params = self.get('custom_params', None) if isinstance(self["structure"], Structure): s = self["structure"] elif isinstance(self["structure"], dict): s = Structure.from_dict(self["structure"]) else: s = Structure.from_file(os.path.join(prev_dir, self["structure"])) vis = load_class("pymatgen.io.vasp.sets", self["vasp_input_set"])( **self.get("input_set_params", {})) vis.write_input(s, ".") # Write Custom KPOINTS settings if necessary ksettings = self.custom_params.get('user_kpts_settings', None) if isinstance( self.custom_params, dict) else None if ksettings: style = ksettings.get('kpts_style', 'Gamma') kpoints = ksettings.get('kpts', [16,16,16]) shift = ksettings.get('kpts_shift', [0,0,0]) k = Kpoints(kpts=[kpoints], kpts_shift=shift) k.style = style k.write_file("KPOINTS")
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 test_remove_z_kpoints(self): os.chdir(os.path.join(PACKAGE_PATH, 'stability/tests/BiTeCl')) structure = Structure.from_file('POSCAR') kpath = HighSymmKpath(structure) Kpoints.automatic_linemode(20, kpath).write_file('KPOINTS') remove_z_kpoints() test_lines = open('KPOINTS').readlines() control_lines = open('../BiTeCl_control/KPOINTS').readlines() self.assertEqual(test_lines, control_lines) os.system('rm KPOINTS')
def test_kpt_bands_as_dict_from_dict(self): file_name = os.path.join(test_dir, 'KPOINTS.band') k = Kpoints.from_file(file_name) d = k.as_dict() import json json.dumps(d) # This doesn't work k2 = Kpoints.from_dict(d) self.assertEqual(k.kpts, k2.kpts) self.assertEqual(k.style, k2.style) self.assertEqual(k.kpts_shift, k2.kpts_shift) self.assertEqual(k.num_kpts, k2.num_kpts)
def get_kpoints(self, structure): """ Writes out a KPOINTS file using the automated gamma grid method. VASP crashes GW calculations on none gamma centered meshes. """ if self.sort_structure: structure = structure.get_sorted_structure() dens = int(self.kpoints_settings['grid_density']) if dens == 1: return Kpoints.gamma_automatic() else: return Kpoints.automatic_gamma_density(structure, dens)
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 test_static_constructors(self): kpoints = Kpoints.gamma_automatic([3, 3, 3], [0, 0, 0]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) self.assertEqual(kpoints.kpts, [[3, 3, 3]]) kpoints = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Monkhorst) self.assertEqual(kpoints.kpts, [[2, 2, 2]]) kpoints = Kpoints.automatic(100) self.assertEqual(kpoints.style, Kpoints.supported_modes.Automatic) self.assertEqual(kpoints.kpts, [[100]]) filepath = PymatgenTest.TEST_FILES_DIR / "POSCAR" poscar = Poscar.from_file(filepath) kpoints = Kpoints.automatic_density(poscar.structure, 500) self.assertEqual(kpoints.kpts, [[1, 3, 3]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints = Kpoints.automatic_density(poscar.structure, 500, True) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints = Kpoints.automatic_density_by_vol(poscar.structure, 1000) self.assertEqual(kpoints.kpts, [[6, 10, 13]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) s = poscar.structure s.make_supercell(3) kpoints = Kpoints.automatic_density(s, 500) self.assertEqual(kpoints.kpts, [[1, 1, 1]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints = Kpoints.from_string("""k-point mesh 0 G 10 10 10 0.5 0.5 0.5 """) self.assertArrayAlmostEqual(kpoints.kpts_shift, [0.5, 0.5, 0.5])
def test_remove_z_kpoints(self): os.chdir(os.path.join(ROOT, 'BiTeCl')) structure = Structure.from_file('POSCAR') kpath = HighSymmKpath(structure) Kpoints.automatic_linemode(20, kpath).write_file('KPOINTS') remove_z_kpoints() test_file = open('KPOINTS') test_lines = test_file.readlines() control_file = open('../BiTeCl_control/KPOINTS') control_lines = control_file.readlines() self.assertEqual(test_lines, control_lines) os.system('rm KPOINTS') test_file.close() control_file.close()
def test_static_constructors(self): kpoints = Kpoints.gamma_automatic([3, 3, 3], [0, 0, 0]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) self.assertEqual(kpoints.kpts, [[3, 3, 3]]) kpoints = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Monkhorst) self.assertEqual(kpoints.kpts, [[2, 2, 2]]) kpoints = Kpoints.automatic(100) self.assertEqual(kpoints.style, Kpoints.supported_modes.Automatic) self.assertEqual(kpoints.kpts, [[100]]) filepath = os.path.join(test_dir, 'POSCAR') poscar = Poscar.from_file(filepath) kpoints = Kpoints.automatic_density(poscar.structure, 500) self.assertEqual(kpoints.kpts, [[1, 3, 3]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints = Kpoints.automatic_density(poscar.structure, 500, True) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints = Kpoints.automatic_density_by_vol(poscar.structure, 1000) self.assertEqual(kpoints.kpts, [[6, 10, 13]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) s = poscar.structure s.make_supercell(3) kpoints = Kpoints.automatic_density(s, 500) self.assertEqual(kpoints.kpts, [[1, 1, 1]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints = Kpoints.from_string("""k-point mesh 0 G 10 10 10 0.5 0.5 0.5 """) self.assertArrayAlmostEqual(kpoints.kpts_shift, [0.5, 0.5, 0.5])
def Auto_Kpoints(mat=None, length=20): """ Geting Kpoints object from structure and line-density Args: mat: Poscar object with structure information length: line-density Returns: kpp: Kpoint object """ b1 = LA.norm( np.array(mat.structure.lattice.reciprocal_lattice_crystallographic. matrix[0])) b2 = LA.norm( np.array(mat.structure.lattice.reciprocal_lattice_crystallographic. matrix[1])) b3 = LA.norm( np.array(mat.structure.lattice.reciprocal_lattice_crystallographic. matrix[2])) n1 = int(max(1, length * b1 + 0.5)) n2 = int(max(1, length * b2 + 0.5)) n3 = int(max(1, length * b3 + 0.5)) kpp = Kpoints.gamma_automatic(kpts=(n1, n2, n3)) return kpp
def dielectric(self,uc_type='prim',output_dir='./'): if uc_type == 'prim': uc_type = 'primitive' stru = self.stru_prim.copy() elif uc_type == 'conv': uc_type = 'conventional' stru = self.stru_conv.copy() path = os.path.join(output_dir,self.name) inputs = MPStaticSet(stru).all_input transf = {'history':[{'source':self.mpid,'unit_cell':uc_type}],'defect_type':'dielectric'} incar = inputs['INCAR'] kpoints = Kpoints.automatic_gamma_density(stru,2000) if self.is_spin_polarized: incar['ISPIN']=2 else: incar['ISPIN']=1 incar['IBRION']=8 incar['LEPSILON']=True incar['LPEAD']=True incar['EDIFF']=0.000001 incar['LWAVE']=False incar['LCHARG']=False incar['ISMEAR']=0 incar['ALGO']="Normal" incar['SIGMA']=0.01 del incar['NSW'], incar['LVHAR'], incar['LAECHG'] os.mkdir(path) f=open(path+"/transformations.json",'w') f.write(json.dumps(jsanitize(transf))) inputs['POTCAR'].write_file(path+"/POTCAR") incar.write_file(path+"/INCAR") kpoints.write_file(path+"/KPOINTS") inputs['POSCAR'].write_file(path+"/POSCAR")
def set_kpoints(self, kpoint): """ set the kpoint """ if self.Grid_type == 'M': self.kpoints = Kpoints.monkhorst_automatic(kpts=kpoint) elif self.Grid_type == 'A': self.kpoints = Kpoints.automatic(subdivisions=kpoint) elif self.Grid_type == 'G': self.kpoints = Kpoints.gamma_automatic(kpts=kpoint) elif self.Grid_type == '3DD': self.kpoints = Kpoints.automatic_density_by_vol(structure= \ self.poscar.structure, kppvol=kpoint) elif self.Grid_type == 'band': self.kpoints = Kpoints.automatic_linemode(divisions=kpoint, \ ibz=HighSymmKpath(self.poscar.structure))
def __init__(self, structure, isif=2, a_kwargs={}, **kwargs): # pop the old kwargs, backwards compatibility from the complex StaticSet self.isif = isif self.a_kwargs = a_kwargs old_kwargs = [ 'prev_incar', 'prev_kpoints', 'grid_density', 'lepsilon', 'lcalcpol' ] for k in old_kwargs: try: kwargs.pop(k) except KeyError: pass self.kwargs = copy.deepcopy(kwargs) uis = copy.deepcopy(self.kwargs.get('user_incar_settings', {})) uis['ISIF'] = isif new_config = copy.deepcopy(StaticSet.CONFIG) if 'ISPIN' not in uis: if magnetic_check(structure): uis.update({'ISPIN': 2}) else: uis.update({'ISPIN': 1}) if 'magmom' in uis: if 'MAGMOM' in new_config['INCAR']: new_config['INCAR'].pop('MAGMOM') elif uis['ISPIN'] == 1: if 'MAGMON' in uis.keys(): uis.pop['MAGMOM'] if 'MAGMON' in new_config['INCAR']: new_config['INCAR'].pop['MAGMOM'] settings = self.a_kwargs.get('settings', {}) new_vasp_settings = settings.get('Static_settings', None) or uis.get( 'Static_settings', None) if new_vasp_settings: for ff in new_vasp_settings: if ff.lower() == 'prec': if 'ENCUT' in new_config['INCAR']: new_config['INCAR'].pop('ENCUT') new_config['INCAR'].update({ff: new_vasp_settings.get(ff)}) elif ff == 'grid_density': new_config['KPOINTS'].update( {ff: new_vasp_settings.get(ff)}) elif ff == 'k_mesh': kpoints = Kpoints(kpts=new_vasp_settings.get(ff)) new_config['KPOINTS'] = kpoints else: new_config['INCAR'].update({ff: new_vasp_settings.get(ff)}) new_config['INCAR'].update(uis) pot = self.kwargs.get('user_potcar_functional', None) if pot: new_config['POTCAR_FUNCTIONAL'] = pot super(StaticSet, self).__init__(structure, new_config, sort_structure=False, **self.kwargs) self.config = new_config
def converge_kpoints(args, console): density_values = np.linspace(args.min, args.max, args.n) mode = Kpoints_supported_modes.from_string(args.mode) structure = Poscar.from_file("POSCAR").structure table = Table(title="K-point Convergence Summary") table.add_column("Directory") table.add_column("Density (atoms^-1)", justify="right") grids = [] for density in density_values: kpoints = Kpoints.automatic_density(structure, density) kpoints.style = mode grid = (kpoints.kpts[0][0], kpoints.kpts[0][1], kpoints.kpts[0][2]) if grid in grids: console.print( "[bold yellow]WARNING:[/bold yellow] density {:.2f} does not produce a unique grid (skipping...)" .format(density)) continue grids.append(grid) dirname = "{}x{}x{}".format(grid[0], grid[1], grid[2]) os.mkdir(dirname) shutil.copy("INCAR", os.path.join(dirname, "INCAR")) shutil.copy("POSCAR", os.path.join(dirname, "POSCAR")) shutil.copy("POTCAR", os.path.join(dirname, "POTCAR")) shutil.copy(args.jobfile, os.path.join(dirname, args.jobfile)) kpoints.write_file(os.path.join(dirname, "KPOINTS")) os.chdir(dirname) #os.system("{} {}".format(args.jobcmd, args.jobfile)) os.chdir("..") table.add_row(dirname, "{:.2f}".format(density)) console.print(table)
def setup(self): """ setup static jobs for all the calibrate objects copies CONTCAR to POSCAR sets NSW = 0 """ for cal in self.cal_objs: for i, jdir in enumerate(cal.old_job_dir_list): job_dir = self.job_dir + os.sep \ + jdir.replace(os.sep, '_').replace('.', '_') \ + os.sep + 'STATIC' logger.info('setting up job in {}'.format(job_dir)) cal.incar = Incar.from_file(jdir + os.sep + 'INCAR') cal.incar['EDIFF'] = '1E-6' cal.incar['NSW'] = 0 cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR') cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS') contcar_file = jdir + os.sep + 'CONTCAR' if os.path.isfile(contcar_file): logger.info( 'setting poscar file from {}'.format(contcar_file)) cal.poscar = Poscar.from_file(contcar_file) cal.add_job(job_dir=job_dir) else: logger.critical("""CONTCAR doesnt exist. Setting up job using input set in the old calibration directory""") cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR') cal.add_job(job_dir=job_dir)
def convert_computed_entry_to_job(self,entry): """ Convert ComputedStructureEntry into VaspJob object Parameters ---------- entry : ComputedStructureEntry. Returns ------- vaspjob : VaspJob object. """ e = entry path = e.data['dir_name'] inp = e.data['calculations'][0]['input'] incar = Incar(inp['incar']) kpoints = Kpoints.from_dict(inp['kpoints']) poscar = Poscar(e.structure) potcar = Potcar(inp['potcar']) inputs = VaspInput(incar, kpoints, poscar, potcar) job_settings = e.data['job_settings'] job_script_filename = e.data['job_script_filename'] name = e.data['job_name'] outputs = {'ComputedStructureEntry':e} vaspjob = VaspJob(path,inputs,job_settings,outputs,job_script_filename,name) vaspjob._is_converged = e.data['is_converged'] vaspjob._band_structure = None return vaspjob
def _find_irr_k_points(directory): """ Determine the number of irreducible k-points based on the VASP input files in a directory. Args: directory (str): Path to the directory that contains the VASP input files. Returns: int: Number of irreducible k-points. """ # TODO Still fails for many calculations. warnings.warn("Currently, the _find_irr_k_points method still fails regularly " "to find the same number of irreducible k-points as VASP. Use " "with care.") directory = os.path.abspath(directory) structure = Structure.from_file(os.path.join(directory, "POSCAR")) incar = Incar.from_file(os.path.join(directory, "INCAR")) if incar.get("MAGMOM", None) is not None: structure.add_site_property("magmom", incar.get("MAGMOM", None)) structure.add_oxidation_state_by_site( [round(magmom, 3) for magmom in structure.site_properties["magmom"]] ) kpoints = Kpoints.from_file(os.path.join(directory, "KPOINTS")) spg = SpacegroupAnalyzer(structure, symprec=1e-5) return len(spg.get_ir_reciprocal_mesh(kpoints.kpts))
def setup(self): """ setup static jobs for all the calibrate objects copies CONTCAR to POSCAR sets NSW = 0 """ for cal in self.cal_objs: for i, jdir in enumerate(cal.old_job_dir_list): job_dir = self.job_dir + os.sep \ + jdir.replace(os.sep, '_').replace('.', '_') \ + os.sep + 'STATIC' logger.info('setting up job in {}'.format(job_dir)) cal.incar = Incar.from_file(jdir + os.sep + 'INCAR') cal.incar['EDIFF'] = '1E-6' cal.incar['NSW'] = 0 cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR') cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS') contcar_file = jdir + os.sep + 'CONTCAR' if os.path.isfile(contcar_file): logger.info('setting poscar file from {}' .format(contcar_file)) cal.poscar = Poscar.from_file(contcar_file) cal.add_job(job_dir=job_dir) else: logger.critical("""CONTCAR doesnt exist. Setting up job using input set in the old calibration directory""") cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR') cal.add_job(job_dir=job_dir)
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 setup_kpoints_jobs(self, Grid_type='M', kpoints_list=None, conv_step=1): self.logger.warn("Its a molecule ! no need for kpoint convergence") self.kpoints = Kpoints.monkhorst_automatic(kpts=[1, 1, 1]) return
def hse06_bandstructure_kpoints(struct, nkpts=20): ''' Generate HSE06 bandstructure KPOINTS Append high-symmetry path points to the IBZKPT file and set weight of all the high-symmetry path points to zero and then write to "KPOINTS" High-symmetry path kpoints is saved as a backup file named 'KPOINTS_bak' Note: We asssert the IBZKPT file is valid ''' def chunks(lst, n): for i in range(0, len(lst), n): yield lst[i:i + n] hsk = HighSymmKpath(struct) sym_kpts = Kpoints.automatic_linemode(nkpts, hsk) sym_kpts.write_file("KPOINTS_bak") kpts = sym_kpts.kpts nsegs = sym_kpts.num_kpts kpoints_result = [] for rng in chunks(kpts, 2): start, end = rng kpoints_result.append(np.linspace(start, end, nsegs)) kpoints_result = np.array(kpoints_result).reshape((-1, 3)) KPOINTS = open('IBZKPT').readlines() for i in range(kpoints_result.shape[0]): x, y, z = kpoints_result[i, :] KPOINTS.append("{:20.14f}{:20.14f}{:20.14f}{:14}\n".format(x, y, z, 0)) KPOINTS[1] = "{:8}\n".format(len(KPOINTS) - 3) with open("KPOINTS", 'w') as f: print("".join(KPOINTS), file=f) pass
def test_remove_z_kpoints(self): os.chdir(os.path.join(ROOT, 'BiTeCl')) structure = Structure.from_file('POSCAR') kpath = HighSymmKpath(structure) Kpoints.automatic_linemode(20, kpath).write_file('KPOINTS') remove_z_kpoints() test_file = open('KPOINTS') test_lines = test_file.readlines() print (test_lines) control_file = open('../BiTeCl_control/KPOINTS') control_lines = control_file.readlines() print (control_lines) self.assertEqual(test_lines, control_lines) os.system('rm KPOINTS') test_file.close() control_file.close()
def Generate_kpoints(struct, kppa): ''' Gererate KPOINTS file with desired grid resolution. Parameters: ---------- struct: pmg.structure object kppa: float The grid resolution in the reciprocal space, the unit is A-1. ''' comment = "Kpoints with grid resolution = %.3f / A-1" % (kppa) recip_lattice = np.array( struct.lattice.reciprocal_lattice.abc) / (2 * np.pi) num_div = [int(round(l / kppa)) for l in recip_lattice] # ensure that numDiv[i] > 0 num_div = [i if i > 0 else 1 for i in num_div] # VASP documentation recommends to use even grids for n <= 8 and odd # grids for n > 8. num_div = [i + i % 2 if i <= 8 else i - i % 2 + 1 for i in num_div] style = Kpoints.supported_modes.Gamma num_kpts = 0 return Kpoints(comment, num_kpts, style, [num_div], [0, 0, 0])
def correct(self): kpoints = Kpoints.from_file("KPOINTS") kpoints.kpts[0] = [ int(self.kpoints_multiplier * k) for k in kpoints.kpts[0] ] kpoints.write_file("KPOINTS")
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 get_directories_VaspJobNotDone(root_dir): with cd(root_dir): ### avoid the link problems root_dir_real = os.getcwd() scan = subprocess.Popen(['find', root_dir_real, '-name', 'POSCAR'], stdout=subprocess.PIPE) scan.wait() pos_coll = scan.stdout.read().split() pos_dirs = [os.path.split(i)[0] for i in pos_coll] vaspjob_dirs = [] for dir in pos_dirs: try: pos = Poscar.from_file(os.path.join(dir, 'POSCAR')) pot = Potcar.from_file(os.path.join(dir, 'POTCAR')) incar = Incar.from_file(os.path.join(dir, 'INCAR')) kpt = Kpoints.from_file(os.path.join(dir, 'KPOINTS')) except: print 'input files are not ready in %s' % dir else: try: out = Outcar(os.path.join(dir, 'OUTCAR')) if len(out.run_stats) != 7: vaspjob_dir.append(dir) except: vaspjob_dirs.append(dir) return vaspjob_dirs
def get_inputs(self, sync=False): """ Read inputs from Job directory """ if sync: self.sync_from_hpc() inputs = {} structures = [] path = op.abspath(self.path) dirs = [d[0] for d in os.walk(path)] for d in dirs: image_name = op.relpath(d, start=path) if all( c.isdigit() for c in list(image_name) ): #check if folder is image (all characters in folder rel path need to be numbers) image_path = d structure = Poscar.from_file(op.join(image_path, 'POSCAR')).structure structures.append(structure) inputs['structures'] = structures inputs['INCAR'] = Incar.from_file(op.join(path, 'INCAR')) inputs['KPOINTS'] = Kpoints.from_file(op.join(path, 'KPOINTS')) inputs['POTCAR'] = Potcar.from_file(op.join(path, 'POTCAR')) self.inputs = inputs return
def run(self): """ Perform the actual VASP run. Returns: (subprocess.Popen) Used for monitoring. """ cmd = list(self.vasp_cmd) if self.auto_gamma: kpts = Kpoints.from_file("KPOINTS") if kpts.style == Kpoints.supported_modes.Gamma and tuple(kpts.kpts[0]) == ( 1, 1, 1, ): if self.gamma_vasp_cmd is not None and which(self.gamma_vasp_cmd[-1]): cmd = self.gamma_vasp_cmd elif which(cmd[-1] + ".gamma"): cmd[-1] += ".gamma" logger.info("Running {}".format(" ".join(cmd))) with open(self.output_file, "w") as f_std, open( self.stderr_file, "w", buffering=1 ) as f_err: # Use line buffering for stderr p = subprocess.Popen(cmd, stdout=f_std, stderr=f_err) return p
def pbe_scf_gamma(self,setname='PBE-SCF-Gamma',pathname='PBE-SCF-Gamma'): """ Set up PBE-SCF calculation only in gamma point """ vaspjob = self.pbe_scf(setname,pathname) vaspjob.inputs['KPOINTS'] = Kpoints().gamma_automatic(kpts=(1,1,1)) return vaspjob
def generate_uniform(kppa=400): """ Generate uniform mesh KPOINTS. Parameters ---------- [optional] kppa (int): kpoint density per reciprocal atom. Default=400 pra. """ dir_sub = os.getcwd() poscar = Poscar.from_file(os.path.join(dir_sub, "POSCAR")) kpts = automatic_density_2d(poscar.structure, int(kppa), force_gamma=False) Kpoints.write_file(kpts, os.path.join(dir_sub, "KPOINTS"))
def monkhorst_list(cls): """ Initialize Monkhorst grid from a list explicitly defining the number of kpoint subdivisions along the crystal axis Example: .. code-block:: python Automatic Kpoint Scheme 0 Monkhorst 4 4 4 """ if cls.kpoint_params['sympath'] is not None: warnings.warn("Explicit monkhorst grid mode: Ignoring defined " "high symmetry path object") kpoints = cls.kpoint_params['kpoints'] if len(kpoints) != 3: raise KpointWrapperError("Expected list of length 3 for explict " "k-point grid input") shift = cls.kpoint_params['shift'] or [.0, .0, .0] if len(shift) != 3: raise KpointWrapperError("Expected list of length 3 for k-point " "grid shift") return Kpoints.monkhorst_automatic(kpts=kpoints, shift=shift)
def automatic_density_2d(structure, kppa, force_gamma=False): comment = "automatically generated KPOINTS with 2d grid density = " + \ "%.0f per reciprocal atom" % kppa # if math.fabs((math.floor(kppa ** (1 / 3) + 0.5)) ** 3 - kppa) < 1: if math.fabs((math.floor(kppa**(1 / 2) + 0.5))**2 - kppa) < 1: kppa += kppa * 0.01 latt = structure.lattice lengths = latt.abc ngrid = kppa / structure.num_sites # mult = (ngrid * lengths[0] * lengths[1] * lengths[2]) ** (1 / 3) mult = (ngrid * lengths[0] * lengths[1])**(1 / 2) num_div = [int(math.floor(max(mult / l, 1))) for l in lengths] num_div[2] = 1 ## force only 1 kpt in c direction is_hexagonal = latt.is_hexagonal() has_odd = any([i % 2 == 1 for i in num_div]) if has_odd or is_hexagonal or force_gamma: style = Kpoints.supported_modes.Gamma else: style = Kpoints.supported_modes.Monkhorst return Kpoints(comment, 0, style, [num_div], [0, 0, 0])
def test_get_kpoints(self): kpoints = MPRelaxSet(self.structure).kpoints self.assertEqual(kpoints.kpts, [[2, 4, 5]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints = MPRelaxSet(self.structure, user_kpoints_settings={ "reciprocal_density": 1000 }).kpoints self.assertEqual(kpoints.kpts, [[6, 10, 13]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints_obj = Kpoints(kpts=[[3, 3, 3]]) kpoints_return = MPRelaxSet(self.structure, user_kpoints_settings=kpoints_obj).kpoints self.assertEqual(kpoints_return.kpts, [[3, 3, 3]]) kpoints = self.mitset.kpoints self.assertEqual(kpoints.kpts, [[25]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Automatic) recip_paramset = MPRelaxSet(self.structure, force_gamma=True) recip_paramset.kpoints_settings = {"reciprocal_density": 40} kpoints = recip_paramset.kpoints self.assertEqual(kpoints.kpts, [[2, 4, 5]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma)
def convergence_kpoints(self,kpoints_meshes=[]): """ Scheme for kpoints convergence. Parameters ---------- kpoints_meshes : (list), optional List of kpoints meshes to use. If not provided a range from 2x2x2 to 7x7x7 is used.The default is []. Returns ------- jobs : (list) List of VaspJob objects. """ jobs = [] if not kpoints_meshes: kpoints_meshes = [] for k in range(2,9): kpoints_meshes.append((k,k,k)) for kmesh in kpoints_meshes: stepname = 'k%ix%ix%i' %(kmesh[0],kmesh[1],kmesh[2]) vaspjob = self.get_vaspjob(setname=stepname,pathname=stepname) vaspjob.incar.pop('KPAR', None) vaspjob.incar['NSW'] = 0 vaspjob.inputs['KPOINTS'] = Kpoints().gamma_automatic(kpts=kmesh) jobs.append(vaspjob) return jobs
def line_int(cls): """ Initialize list of kpoints along a high-symmetry path through the Brillouin zone. Uses a path defined by the pymatgen HighSymmPath class with a defined number of kpoint subdivisions between the path nodes. Example:: Line_mode KPOINTS file 100 Line_mode Reciprocal 0.0 0.0 0.0 ! Gamma 0.0 0.5 0.0 ! X 0.0 0.5 0.0 ! X ... 0.0 0.5 0.0 ! X 0.5 0.5 0.0 ! M 0.5 0.5 0.5 ! R """ if cls.kpoint_params['shift'] is not None: warnings.warn("Line kpoint mode: Ignoring defined shift") if cls.kpoint_params['sympath'] is None: raise KpointWrapperError("Missing non-optional kpoint line mode " "parameter 'sympath'") divisions = cls.kpoint_params['kpoints'] sympath = cls.kpoint_params['sympath'] return Kpoints.automatic_linemode(divisions, sympath)
def pbe_ionic_rel_gamma(self,setname='PBE-rel-Gamma',pathname='PBE-rel-gamma'): """ Set up PBE ionic relaxation only in gamma point """ vaspjob = self.pbe_ionic_rel(setname,pathname) vaspjob.inputs['KPOINTS'] = Kpoints().gamma_automatic(kpts=(1,1,1)) return vaspjob
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 generate_3Dkpoints(struct,dirname): #print(" input the dimensionality and mesh grid density ") tip=''' Accuracy Levels: (1) Low: 0.04~0.03; (2) Medium: 0.03~0.02; (2) Fine: 0.02~0.01; ''' warn_tip(1,tip) print("Input KP-Resolved Value (unit: 2*PI/Ang):") wait_sep() in_str="" while in_str=="": in_str=input().strip() delta_k=float(in_str) (lka,lkb,lkc)=struct.lattice.reciprocal_lattice.abc ka=ceil(lka/(2*np.pi)/delta_k) kb=ceil(lkb/(2*np.pi)/delta_k) ka_dis=np.linspace(-0.5,0.5,ka) kb_dis=np.linspace(-0.5,0.5,kb) kxx,kyy=np.meshgrid(ka_dis,kb_dis) kpts=[[i[0], i[1], 0.0] for i in zip(kxx.flat,kyy.flat)] tmp_K="3D K-meshs by maptool with : "+ str(ka)+"x"+ str(kb)+ "\n 1\nReciprocal\n 0 0 0 1" # initialize a Kpionts instance from template string reciprocal_kpoints=Kpoints.from_string(tmp_K) reciprocal_kpoints.labels=None reciprocal_kpoints.kpts=kpts reciprocal_kpoints.num_kpts=ka*kb reciprocal_kpoints.kpts_weights=[1.0]*(ka*kb) reciprocal_kpoints.write_file(os.path.join(dirname, "KPOINTS"))
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 write_vasp_input(structure: IStructure, kpath_division: int, write_dir: str = "."): vasp_input = VaspInput( Incar.from_file("INCAR"), Kpoints.automatic_linemode(kpath_division, HighSymmKpath(structure)), Poscar(structure), Potcar.from_file("POTCAR")) vasp_input.write_input(write_dir)
def band_structure_kpath(struct,dirname,nkpts=30): #struct=Structure.from_file('POSCAR') #ana_struct=SpacegroupAnalyzer(struct) #pst=ana_struct.find_primitive() # First brillouin zone ibz = HighSymmKpath(struct) linemode_kpoints = Kpoints.automatic_linemode(nkpts,ibz) linemode_kpoints.write_file(os.path.join(dirname, "KPOINTS"))
def test_static_constructors(self): kpoints = Kpoints.gamma_automatic([3, 3, 3], [0, 0, 0]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) self.assertEqual(kpoints.kpts, [[3, 3, 3]]) kpoints = Kpoints.monkhorst_automatic([2, 2, 2], [0, 0, 0]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Monkhorst) self.assertEqual(kpoints.kpts, [[2, 2, 2]]) kpoints = Kpoints.automatic(100) self.assertEqual(kpoints.style, Kpoints.supported_modes.Automatic) self.assertEqual(kpoints.kpts, [[100]]) filepath = os.path.join(test_dir, "POSCAR") poscar = Poscar.from_file(filepath) kpoints = Kpoints.automatic_density(poscar.structure, 500) self.assertEqual(kpoints.kpts, [[2, 4, 4]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Monkhorst) kpoints = Kpoints.automatic_density(poscar.structure, 500, True) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints = Kpoints.automatic_density_by_vol(poscar.structure, 1000) self.assertEqual(kpoints.kpts, [[6, 11, 13]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) s = poscar.structure s.make_supercell(3) kpoints = Kpoints.automatic_density(s, 500) self.assertEqual(kpoints.kpts, [[1, 1, 1]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma)
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 set_kpoints(self, kpoint): """ set the kpoint """ if self.Grid_type == 'M': self.kpoints = Kpoints.monkhorst_automatic(kpts = kpoint) elif self.Grid_type == 'A': self.kpoints = Kpoints.automatic(subdivisions = kpoint) elif self.Grid_type == 'G': self.kpoints = Kpoints.gamma_automatic(kpts = kpoint) elif self.Grid_type == '3DD': self.kpoints = Kpoints.automatic_density_by_vol(structure=\ self.poscar.structure, kppvol=kpoint) elif self.Grid_type == 'band': self.kpoints = Kpoints.automatic_linemode(divisions=kpoint,\ ibz=HighSymmKpath(self.poscar.structure)) name = self.kpoint_to_name(kpoint, self.Grid_type) job_dir = self.job_dir +os.sep+ self.key_to_name('KPOINTS') \ + os.sep + name return job_dir
def setUp(self): filepath = self.TEST_FILES_DIR / 'INCAR' incar = Incar.from_file(filepath) filepath = self.TEST_FILES_DIR / 'POSCAR' poscar = Poscar.from_file(filepath,check_for_POTCAR=False) if "PMG_VASP_PSP_DIR" not in os.environ: os.environ["PMG_VASP_PSP_DIR"] = str(self.TEST_FILES_DIR) filepath = self.TEST_FILES_DIR / 'POTCAR' potcar = Potcar.from_file(filepath) filepath = self.TEST_FILES_DIR / 'KPOINTS.auto' kpoints = Kpoints.from_file(filepath) self.vinput = VaspInput(incar, kpoints, poscar, potcar)
def test_automatic_kpoint(self): # s = PymatgenTest.get_structure("Li2O") p = Poscar.from_string("""Al1 1.0 2.473329 0.000000 1.427977 0.824443 2.331877 1.427977 0.000000 0.000000 2.855955 Al 1 direct 0.000000 0.000000 0.000000 Al""") kpoints = Kpoints.automatic_density(p.structure, 1000) self.assertArrayAlmostEqual(kpoints.kpts[0], [10, 10, 10])
def write_input_task(self, dir='.'): self.custom_params = self.get('custom_params', None) if isinstance(self["structure"], Structure): s = self["structure"] elif isinstance(self["structure"], dict): s = Structure.from_dict(self["structure"]) else: s = Structure.from_file(self["structure"]) if os.environ.get('VASP_PSP_DIR') == None: print "VASP_PSP_DIR not set. Checking User's HOME directory for VASP potentials." if os.path.exists(os.path.join(os.environ.get('HOME'), 'Potentials')): os.environ['VASP_PSP_DIR'] = os.path.join(os.environ.get('HOME'), 'Potentials') else: print "VASP Potentials not found!" print "Please copy the Potentials Folder" print "from VASP into your HOME directory" sys.exit() vis = load_class("pymatgen.io.vasp.sets", self["vasp_input_set"])( **self.get("input_set_params", {})) vis.write_input(s, dir) # Write Custom KPOINTS settings if necessary ksettings = self.custom_params.get('user_kpts_settings', None) if isinstance( self.custom_params, dict) else None if ksettings: style = ksettings.get('kpts_style', 'Gamma') kpoints = ksettings.get('kpts', [16,16,16]) shift = ksettings.get('kpts_shift', [0,0,0]) k = Kpoints(kpts=[kpoints], kpts_shift=shift) k.style = style filename = os.path.join(dir, 'KPOINTS') k.write_file(filename) print "Wrote VASP input files to '{}'".format(dir)
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 update_spec_force_convergence(spec, user_vasp_settings=None): fw_spec = spec update_set = {"ENCUT": 700, "EDIFF": 0.000001, "ALGO":"N", "NPAR":2} if user_vasp_settings and user_vasp_settings.get("incar"): update_set.update(user_vasp_settings["incar"]) fw_spec['vasp']['incar'].update(update_set) old_struct=Poscar.from_dict(fw_spec["vasp"]["poscar"]).structure if user_vasp_settings and user_vasp_settings.get("kpoints"): kpoints_density = user_vasp_settings["kpoints"]["kpoints_density"] else: kpoints_density = 7000 k=Kpoints.automatic_density(old_struct, kpoints_density) fw_spec['vasp']['kpoints'] = k.as_dict() return fw_spec
def test_write_inputset(self): name = 'Test' incar= Incar.from_file(TEST_STEP1+os.sep+'INCAR') kpoints = Kpoints.from_file(TEST_STEP1+os.sep+'KPOINTS') poscar = Poscar.from_file(TEST_STEP1+os.sep+'POSCAR') potcar = TEST_STEP1+os.sep+'DUMMY_POTSPEC' #potcar = #Potcar.from_dict({'@class': 'Potcar', 'functional': 'PBE',\ # 'symbols': ['Al'], '@module': 'pymatgen.io.vasp.inputs'}) reuse_path = [TEST_STEP1 + os.sep + 'COPY_FILE'] print (reuse_path) mvis = MPINTVaspInputSet(name,incar,poscar,potcar,kpoints,reuse_path=reuse_path,test=True) mvis.write_input(job_dir=TEST_STEP2) self.assertCountEqual(os.listdir(TEST_STEP2), ['INCAR','KPOINTS','POSCAR','COPY_FILE']) cleanup = [os.remove(TEST_STEP2+os.sep+f) for f in os.listdir(TEST_STEP2)]
def setUp(self): filepath = os.path.join(test_dir, 'INCAR') incar = Incar.from_file(filepath) filepath = os.path.join(test_dir, 'POSCAR') poscar = Poscar.from_file(filepath,check_for_POTCAR=False) if "PMG_VASP_PSP_DIR" not in os.environ: test_potcar_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "test_files")) os.environ["PMG_VASP_PSP_DIR"] = test_potcar_dir filepath = os.path.join(test_dir, 'POTCAR') potcar = Potcar.from_file(filepath) filepath = os.path.join(test_dir, 'KPOINTS.auto') kpoints = Kpoints.from_file(filepath) self.vinput = VaspInput(incar, kpoints, poscar, potcar)
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 setUp(self): filepath = os.path.join(test_dir, "INCAR") incar = Incar.from_file(filepath) filepath = os.path.join(test_dir, "POSCAR") poscar = Poscar.from_file(filepath) if "VASP_PSP_DIR" not in os.environ: test_potcar_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "test_files") ) os.environ["VASP_PSP_DIR"] = test_potcar_dir filepath = os.path.join(test_dir, "POTCAR") potcar = Potcar.from_file(filepath) filepath = os.path.join(test_dir, "KPOINTS.auto") kpoints = Kpoints.from_file(filepath) self.vinput = VaspInput(incar, kpoints, poscar, potcar)
def setup(self): """ setup solvation jobs for the calibrate objects copies WAVECAR and sets the solvation params in the incar file also dumps system.json file in each directory for the database crawler mind: works only for cal objects that does only single calculations """ for cal in self.cal_objs: jdir = cal.old_job_dir_list[0] cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR') cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR') cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS') cal.incar = Incar.from_file(jdir + os.sep + 'INCAR') cal.incar['LSOL'] = '.TRUE.' syms = [site.specie.symbol for site in cal.poscar.structure] zvals = {p.symbol: p.nelectrons for p in cal.potcar} nelectrons = sum([zvals[a[0]] * len(tuple(a[1])) for a in itertools.groupby(syms)]) keys = [k for k in self.sol_params.keys() if self.sol_params[k]] prod_list = [self.sol_params.get(k) for k in keys] for params in itertools.product(*tuple(prod_list)): job_dir = self.job_dir + os.sep \ + cal.old_job_dir_list[0].replace(os.sep, '_').replace('.', '_') \ + os.sep + 'SOL' for i, k in enumerate(keys): if k == 'NELECT': cal.incar[k] = params[i] + nelectrons else: cal.incar[k] = params[i] job_dir = job_dir + os.sep + k + os.sep + str( cal.incar[k]).replace('.', '_') if not os.path.exists(job_dir): os.makedirs(job_dir) with open(job_dir + os.sep + 'system.json', 'w') as f: json.dump(dict(list(zip(keys, params))), f) wavecar_file = cal.old_job_dir_list[0] + os.sep + 'WAVECAR' if os.path.isfile(wavecar_file): shutil.copy(wavecar_file, job_dir + os.sep + 'WAVECAR') cal.add_job(job_dir=job_dir) else: logger.critical('WAVECAR doesnt exist. Aborting ...') sys.exit(0)
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 setup(self): """ setup static jobs for the calibrate objects copies CONTCAR to POSCAR sets NSW = 0 write system.json file for database crawler """ d = {} for cal in self.cal_objs: for i, jdir in enumerate(cal.old_job_dir_list): job_dir = self.job_dir + os.sep \ + jdir.replace(os.sep, '_').replace('.', '_') + \ os.sep + 'STATIC' cal.incar = Incar.from_file(jdir + os.sep + 'INCAR') cal.incar['EDIFF'] = '1E-6' cal.incar['NSW'] = 0 cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR') cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS') contcar_file = jdir + os.sep + 'CONTCAR' if os.path.isfile(contcar_file): cal.poscar = Poscar.from_file(contcar_file) if cal in self.cal_slabs or cal in self.cal_interfaces: try: d['hkl'] = cal.system['hkl'] except: logger.critical("""the calibrate object doesnt have a system set for calibrating""") if cal in self.cal_interfaces: try: d['ligand'] = cal.system['ligand']['name'] except: logger.critical("""the calibrate object doesnt have a system set for calibrating""") if not os.path.exists(job_dir): os.makedirs(job_dir) if d: with open(job_dir + os.sep + 'system.json', 'w') as f: json.dump(d, f) cal.add_job(job_dir=job_dir) else: logger.critical("""CONTCAR doesnt exist. Setting up job using input set in the old calibration directory""") cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR') cal.add_job(job_dir=job_dir)
def test_init(self): prev_run = os.path.join(test_dir, "relaxation") vis = MPNonSCFSet.from_prev_calc( prev_calc_dir=prev_run, mode="Line", copy_chgcar=False) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal) # Check as from dict. vis = MPNonSCFSet.from_dict(vis.as_dict()) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal) vis.write_input(self.tmp) self.assertFalse(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) vis = MPNonSCFSet.from_prev_calc(prev_calc_dir=prev_run, mode="Line", copy_chgcar=True) vis.write_input(self.tmp) self.assertTrue(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) # Code below is just to make sure that the parameters are the same # between the old MPStaticVaspInputSet and the new MPStaticSet. # TODO: Delete code below in future. MPNonSCFVaspInputSet.from_previous_vasp_run( previous_vasp_dir=prev_run, output_dir=self.tmp, mode="Line") incar = Incar.from_file(os.path.join(self.tmp, "INCAR")) for k, v1 in vis.incar.items(): v2 = incar.get(k) try: v1 = v1.upper() v2 = v2.upper() except: # Convert strings to upper case for comparison. Ignore other # types. pass self.assertEqual(v1, v2, str(v1)+str(v2)) kpoints = Kpoints.from_file(os.path.join(self.tmp, "KPOINTS")) self.assertEqual(kpoints.style, vis.kpoints.style) self.assertArrayAlmostEqual(kpoints.kpts, vis.kpoints.kpts)
def test_init(self): filepath = os.path.join(test_dir, 'KPOINTS.auto') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.kpts, [[10]], "Wrong kpoint lattice read") filepath = os.path.join(test_dir, 'KPOINTS.cartesian') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.kpts, [[0.25, 0, 0], [0, 0.25, 0], [0, 0, 0.25]], "Wrong kpoint lattice read") self.assertEqual(kpoints.kpts_shift, [0.5, 0.5, 0.5], "Wrong kpoint shift read") filepath = os.path.join(test_dir, 'KPOINTS') kpoints = Kpoints.from_file(filepath) self.kpoints = kpoints self.assertEqual(kpoints.kpts, [[2, 4, 6]]) filepath = os.path.join(test_dir, 'KPOINTS.band') kpoints = Kpoints.from_file(filepath) self.assertIsNotNone(kpoints.labels) self.assertEqual(kpoints.style, Kpoints.supported_modes.Line_mode) kpoints_str = str(kpoints) self.assertEqual(kpoints_str.split("\n")[3], "Reciprocal") filepath = os.path.join(test_dir, 'KPOINTS.explicit') kpoints = Kpoints.from_file(filepath) self.assertIsNotNone(kpoints.kpts_weights) self.assertEqual(str(kpoints).strip(), """Example file 4 Cartesian 0.0 0.0 0.0 1 None 0.0 0.0 0.5 1 None 0.0 0.5 0.5 2 None 0.5 0.5 0.5 4 None""") filepath = os.path.join(test_dir, 'KPOINTS.explicit_tet') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.tet_connections, [(6, [1, 2, 3, 4])])