def write_vasp(self, k0_rlv, scfdir, destdir): '''Generate VASP nscf input files ''' r = Vasprun(join(scfdir, 'vasprun.xml')) rlv = r.lattice_rec.matrix is_k_spin = True try: len(k0_rlv[0]) except: is_k_spin = False k0_up = k0_rlv k0_dn = None if is_k_spin: k0_up, k0_dn = k0_rlv[0], k0_rlv[1] list_k = self.kpoints(rlv, k0_up) if r.is_spin and is_k_spin: list_k = np.concatenate((list_k, self.kpoints(rlv, k0_dn))) nscf = MPNonSCFSet.from_prev_calc(scfdir, user_incar_settings={ "NCORE": 4, "EDIFF": "1E-7" }) nscf.write_input(destdir) mode = Kpoints.supported_modes.Reciprocal kpt = Kpoints(style=mode, kpts=list_k, num_kpts=len(list_k), kpts_weights=[1.0] * len(list_k), comment="5-point stencil h:{}".format(self.h)) kpt.write_file(join(destdir, 'KPOINTS'))
def kpt4pbeband(self, path, import_kpath): if import_kpath: special_kpoints = kpath_dict else: special_kpoints = get_special_points(self.atoms.cell) num_kpts = self.struct_info['num_kpts'] labels=self.struct_info['kpath'] kptset = list() lbs = list() if labels[0] in special_kpoints.keys(): kptset.append(special_kpoints[labels[0]]) lbs.append(labels[0]) for i in range(1,len(labels)-1): if labels[i] in special_kpoints.keys(): kptset.append(special_kpoints[labels[i]]) lbs.append(labels[i]) kptset.append(special_kpoints[labels[i]]) lbs.append(labels[i]) if labels[-1] in special_kpoints.keys(): kptset.append(special_kpoints[labels[-1]]) lbs.append(labels[-1]) # Hardcoded for EuS and EuTe since one of the k-point is not in the special kpoints list. if 'EuS' in self.atoms.symbols or 'EuTe' in self.atoms.symbols: kptset[0] = np.array([0.5,0.5,1]) kpt = Kpoints(comment='band', kpts=kptset, num_kpts = num_kpts, style='Line_mode',coord_type="Reciprocal",labels=lbs) kpt.write_file(path+'/KPOINTS')
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 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 generateBsKpoints(structure, file, divisions = 15, path = None): ibz = HighSymmKpath(structure, symprec=0.01, angle_tolerance=5) print(ibz.kpath['kpoints']) if not path: kpoints = [] labels = [] for path in ibz.kpath['path']: k, l = helper(path, ibz) kpoints += k labels += l else: kpoints, labels = helper(path, ibz) kp = Kpoints("Line_mode KPOINTS file", style=Kpoints.supported_modes.Line_mode, coord_type="Reciprocal", kpts=kpoints, labels=labels, num_kpts=int(divisions)) kp.write_file(file)
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 write_KPOINTS( POSCAR_input: str = "POSCAR", KPOINTS_output="KPOINTS.lobster", reciprocal_density: int = 100, isym: int = -1, from_grid: bool = False, input_grid: list = [5, 5, 5], line_mode: bool = True, kpoints_line_density: int = 20, symprec: float = 0.01, ): """ writes a KPOINT file for lobster (only ISYM=-1 and ISYM=0 are possible), grids are gamma centered Args: POSCAR_input (str): path to POSCAR KPOINTS_output (str): path to output KPOINTS reciprocal_density (int): Grid density isym (int): either -1 or 0. Current Lobster versions only allow -1. from_grid (bool): If True KPOINTS will be generated with the help of a grid given in input_grid. Otherwise, they will be generated from the reciprocal_density input_grid (list): grid to generate the KPOINTS file line_mode (bool): If True, band structure will be generated kpoints_line_density (int): density of the lines in the band structure symprec (float): precision to determine symmetry """ structure = Structure.from_file(POSCAR_input) if not from_grid: kpointgrid = Kpoints.automatic_density_by_vol( structure, reciprocal_density).kpts mesh = kpointgrid[0] else: mesh = input_grid # The following code is taken from: SpacegroupAnalyzer # we need to switch off symmetry here latt = structure.lattice.matrix positions = structure.frac_coords unique_species = [] # type: List[Any] zs = [] magmoms = [] for species, g in itertools.groupby(structure, key=lambda s: s.species): if species in unique_species: ind = unique_species.index(species) zs.extend([ind + 1] * len(tuple(g))) else: unique_species.append(species) zs.extend([len(unique_species)] * len(tuple(g))) for site in structure: if hasattr(site, "magmom"): magmoms.append(site.magmom) elif site.is_ordered and hasattr(site.specie, "spin"): magmoms.append(site.specie.spin) else: magmoms.append(0) # For now, we are setting magmom to zero. (Taken from INCAR class) cell = latt, positions, zs, magmoms # TODO: what about this shift? mapping, grid = spglib.get_ir_reciprocal_mesh(mesh, cell, is_shift=[0, 0, 0]) # exit() # get the kpoints for the grid if isym == -1: kpts = [] weights = [] all_labels = [] for gp in grid: kpts.append(gp.astype(float) / mesh) weights.append(float(1)) all_labels.append("") elif isym == 0: # time reversal symmetry: k and -k are equivalent kpts = [] weights = [] all_labels = [] newlist = [list(gp) for gp in list(grid)] mapping = [] for gp in newlist: minus_gp = [-k for k in gp] if minus_gp in newlist and minus_gp not in [[0, 0, 0]]: mapping.append(newlist.index(minus_gp)) else: mapping.append(newlist.index(gp)) for igp, gp in enumerate(newlist): if mapping[igp] > igp: kpts.append(np.array(gp).astype(float) / mesh) weights.append(float(2)) all_labels.append("") elif mapping[igp] == igp: kpts.append(np.array(gp).astype(float) / mesh) weights.append(float(1)) all_labels.append("") else: ValueError("Only isym=-1 and isym=0 are allowed.") # line mode if line_mode: kpath = HighSymmKpath(structure, symprec=symprec) if not np.allclose(kpath.prim.lattice.matrix, structure.lattice.matrix): raise ValueError( "You are not using the standard primitive cell. The k-path is not correct. Please generate a " "standard primitive cell first.") frac_k_points, labels = kpath.get_kpoints( line_density=kpoints_line_density, coords_are_cartesian=False) for k, f in enumerate(frac_k_points): kpts.append(f) weights.append(0.0) all_labels.append(labels[k]) if isym == -1: comment = ("ISYM=-1, grid: " + str(mesh) if not line_mode else "ISYM=-1, grid: " + str(mesh) + " plus kpoint path") elif isym == 0: comment = ("ISYM=0, grid: " + str(mesh) if not line_mode else "ISYM=0, grid: " + str(mesh) + " plus kpoint path") KpointObject = Kpoints( comment=comment, style=Kpoints.supported_modes.Reciprocal, num_kpts=len(kpts), kpts=kpts, kpts_weights=weights, labels=all_labels, ) KpointObject.write_file(filename=KPOINTS_output)
def write_kpoint_files(filename, kpoints, labels, make_folders=False, ibzkpt=None, kpts_per_split=None, directory=None, cart_coords=False): r"""Write the k-points data to VASP KPOINTS files. Folders are named as 'split-01', 'split-02', etc ... KPOINTS files are named KPOINTS_band_split_01 etc ... Args: filename (:obj:`str`): Path to VASP structure file. kpoints (:obj:`numpy.ndarray`): The k-point coordinates along the high-symmetry path. For example:: [[0, 0, 0], [0.25, 0, 0], [0.5, 0, 0], [0.5, 0, 0.25], [0.5, 0, 0.5]] labels (:obj:`list`) The high symmetry labels for each k-point (will be an empty :obj:`str` if the k-point has no label). For example:: ['\Gamma', '', 'X', '', 'Y'] make_folders (:obj:`bool`, optional): Generate folders and copy in required files (INCAR, POTCAR, POSCAR, and possibly CHGCAR) from the current directory. ibzkpt (:obj:`str`, optional): Path to IBZKPT file. If set, the generated k-points will be appended to the k-points in this file and given a weight of 0. This is necessary for hybrid band structure calculations. kpts_per_split (:obj:`int`, optional): If set, the k-points are split into separate k-point files (or folders) each containing the number of k-points specified. This is useful for hybrid band structure calculations where it is often intractable to calculate all k-points in the same calculation. directory (:obj:`str`, optional): The output file directory. cart_coords (:obj:`bool`, optional): Whether the k-points are returned in cartesian or reciprocal coordinates. Defaults to ``False`` (fractional coordinates). """ if kpts_per_split: kpt_splits = [ kpoints[i:i + kpts_per_split] for i in range(0, len(kpoints), kpts_per_split) ] label_splits = [ labels[i:i + kpts_per_split] for i in range(0, len(labels), kpts_per_split) ] else: kpt_splits = [kpoints] label_splits = [labels] if cart_coords: coord_type = 'cartesian' style = Kpoints.supported_modes.Cartesian else: coord_type = 'reciprocal' style = Kpoints.supported_modes.Reciprocal kpt_files = [] for kpt_split, label_split in zip(kpt_splits, label_splits): if ibzkpt: # hybrid calculation so set k-point weights to 0 kpt_weights = ibzkpt.kpts_weights + [0] * len(kpt_split) kpt_split = ibzkpt.kpts + kpt_split label_split = [''] * len(ibzkpt.labels) + label_split else: # non-SCF calculation so set k-point weights to 1 kpt_weights = [1] * len(kpt_split) segment = ' -> '.join([label for label in label_split if label]) kpt_file = Kpoints(comment=segment, num_kpts=len(kpt_split), kpts=kpt_split, kpts_weights=kpt_weights, style=style, coord_type=coord_type, labels=label_split) kpt_files.append(kpt_file) pad = int(math.floor(math.log10(len(kpt_files)))) + 2 if make_folders: for i, kpt_file in enumerate(kpt_files): folder = 'split-{}'.format(str(i + 1).zfill(pad)) if directory: folder = os.path.join(directory, folder) try: os.makedirs(folder) except OSError as e: if e.errno == errno.EEXIST: logging.error("\nERROR: Folders already exist, won't " "overwrite.") sys.exit() else: raise kpt_file.write_file(os.path.join(folder, 'KPOINTS')) vasp_files = [filename, "INCAR", "POTCAR", "job"] vasp_files += [] if ibzkpt else ['CHGCAR'] for vasp_file in vasp_files: if os.path.isfile(vasp_file): shutil.copyfile(vasp_file, os.path.join(folder, vasp_file)) else: for i, kpt_file in enumerate(kpt_files): if len(kpt_files) > 1: kpt_filename = 'KPOINTS_band_split_{:0d}'.format(i + 1) else: kpt_filename = 'KPOINTS_band' if directory: kpt_filename = os.path.join(directory, kpt_filename) kpt_file.write_file(kpt_filename)
help='kpt density (pra)', default=440) ## read in the above arguments from command line args = parser.parse_args() ## the bash script already put us in the appropriate subdirectory dir_sub = os.getcwd() poscar = Poscar.from_file(os.path.join(dir_sub, "POSCAR")) kpts = automatic_density_2d(poscar.structure, args.kppa, force_gamma=False) # poscar = Poscar.from_file(dir_sub+"POSCAR") # kpts = Kpoints.automatic_density(poscar.structure, kppa=8000, force_gamma=False) Kpoints.write_file(kpts, os.path.join(dir_sub, "KPOINTS")) # dir_main = "mp-2815_MoS2/" # dir_main = "Y:/WSe2/monolayer/SCAN_vdW/mag/" # for q in [0,-1]: # for cell in [(5,5)]: # for vac in [15,20]: # # dir_sub = dir_main+"charge_%d/%dx%dx1/vac_%d/"%(q,cell[0],cell[1],vac) # # kpts = Kpoints.gamma_automatic(kpts=(3, 3, 1), shift=(0, 0, 0)) # ## poscar = Poscar.from_file(dir_sub+"POSCAR") ## kpts = automatic_density_2d(poscar.structure, kppa=440, force_gamma=False) #
def write_kpoints(file_path, kpts_dict): kpt_obj = Kpoints().from_dict(kpts_dict) kpt_obj.write_file(file_path)