def get_kpoints(self, structure): """ Get a KPOINTS file for NonSCF calculation. In "Line" mode, kpoints are generated along high symmetry lines. In "Uniform" mode, kpoints are Gamma-centered mesh grid. Kpoints are written explicitly in both cases. Args: structure (Structure/IStructure): structure to get Kpoints """ if self.mode == "Line": kpath = HighSymmKpath(structure) cart_k_points, k_points_labels = kpath.get_kpoints() frac_k_points = [kpath._prim_rec.get_fractional_coords(k) for k in cart_k_points] return Kpoints(comment="Non SCF run along symmetry lines", style="Reciprocal", num_kpts=len(frac_k_points), kpts=frac_k_points, labels=k_points_labels, kpts_weights=[1] * len(cart_k_points)) else: num_kpoints = self.kpoints_settings["kpoints_density"] * \ structure.lattice.reciprocal_lattice.volume kpoints = Kpoints.automatic_density( structure, num_kpoints * structure.num_sites) mesh = kpoints.kpts[0] ir_kpts = SymmetryFinder(structure, symprec=self.sym_prec) \ .get_ir_reciprocal_mesh(mesh) kpts = [] weights = [] for k in ir_kpts: kpts.append(k[0]) weights.append(int(k[1])) return Kpoints(comment="Non SCF run on uniform grid", style="Reciprocal", num_kpts=len(ir_kpts), kpts=kpts, kpts_weights=weights)
def get_band_structure(self): """Return a BandStructureSymmLine object interpolating bands along a High symmetry path calculated from the structure using HighSymmKpath function""" kpath = HighSymmKpath(self.data.structure) kpt_line = [ Kpoint(k, self.data.structure.lattice) for k in kpath.get_kpoints(coords_are_cartesian=False)[0] ] kpoints = np.array([kp.frac_coords for kp in kpt_line]) labels_dict = { l: k for k, l in zip(*kpath.get_kpoints(coords_are_cartesian=False)) if l } lattvec = self.data.get_lattvec() egrid, vgrid = fite.getBands(kpoints, self.equivalences, lattvec, self.coeffs) bands_dict = {Spin.up: (egrid / units.eV)} sbs = BandStructureSymmLine( kpoints, bands_dict, self.data.structure.lattice.reciprocal_lattice, self.efermi / units.eV, labels_dict=labels_dict) return sbs
def test_kpath_generation(self): triclinic = [1, 2] monoclinic = range(3, 16) orthorhombic = range(16, 75) tetragonal = range(75, 143) rhombohedral = range(143, 168) hexagonal = range(168, 195) cubic = range(195, 231) species = ["K", "La", "Ti"] coords = [[0.345, 5, 0.77298], [0.1345, 5.1, 0.77298], [0.7, 0.8, 0.9]] for i in range(230): sg_num = i + 1 if sg_num in triclinic: lattice = Lattice( [[3.0233057319441246, 1, 0], [0, 7.9850357844548681, 1], [0, 1.2, 8.1136762279561818]] ) elif sg_num in monoclinic: lattice = Lattice.monoclinic(2, 9, 1, 99) elif sg_num in orthorhombic: lattice = Lattice.orthorhombic(2, 9, 1) elif sg_num in tetragonal: lattice = Lattice.tetragonal(2, 9) elif sg_num in rhombohedral: lattice = Lattice.hexagonal(2, 95) elif sg_num in hexagonal: lattice = Lattice.hexagonal(2, 9) elif sg_num in cubic: lattice = Lattice.cubic(2) struct = Structure.from_spacegroup(sg_num, lattice, species, coords) # Throws error if something doesn't work, causing test to fail. kpath = HighSymmKpath(struct, path_type="all") kpoints = kpath.get_kpoints()
def get_band_structure(self): """Return a BandStructureSymmLine object interpolating bands along a High symmetry path calculated from the structure using HighSymmKpath function""" kpath = HighSymmKpath(self.data.structure) kpt_line = [Kpoint(k, self.data.structure.lattice) for k in kpath.get_kpoints(coords_are_cartesian=False)[ 0]] kpoints = np.array( [kp.frac_coords for kp in kpt_line]) labels_dict = {l: k for k, l in zip( *kpath.get_kpoints(coords_are_cartesian=False)) if l} lattvec = self.data.get_lattvec() egrid, vgrid = fite.getBands(kpoints, self.equivalences, lattvec, self.coeffs) bands_dict = {Spin.up: (egrid / units.eV)} sbs = BandStructureSymmLine(kpoints, bands_dict, self.data.structure.lattice.reciprocal_lattice, self.efermi / units.eV, labels_dict=labels_dict) return sbs
def test_kpath_generation(self): triclinic = [1, 2] monoclinic = range(3, 16) orthorhombic = range(16, 75) tetragonal = range(75, 143) rhombohedral = range(143, 168) hexagonal = range(168, 195) cubic = range(195, 231) species = ['K', 'La', 'Ti'] coords = [[.345, 5, .77298], [.1345, 5.1, .77298], [.7, .8, .9]] for i in range(230): sg_num = i + 1 if sg_num in triclinic: lattice = Lattice([[3.0233057319441246, 0, 0], [0, 7.9850357844548681, 0], [0, 0, 8.1136762279561818]]) elif sg_num in monoclinic: lattice = Lattice.monoclinic(2, 9, 1, 99) elif sg_num in orthorhombic: lattice = Lattice.orthorhombic(2, 9, 1) elif sg_num in tetragonal: lattice = Lattice.tetragonal(2, 9) elif sg_num in rhombohedral: lattice = Lattice.hexagonal(2, 95) elif sg_num in hexagonal: lattice = Lattice.hexagonal(2, 9) elif sg_num in cubic: lattice = Lattice.cubic(2) struct = Structure.from_spacegroup(sg_num, lattice, species, coords) kpath = HighSymmKpath(struct) # Throws error if something doesn't work, causing test to fail. struct_file_path = os.path.join(test_dir_structs, 'ICSD_170.cif') struct = Structure.from_file(struct_file_path) hkp = HighSymmKpath(struct) self.assertEqual(hkp.name, 'MCLC5')
def get_symmetry_points(fermi_surface) -> Tuple[np.ndarray, List[str]]: """ Get the high symmetry k-points and labels for the Fermi surface. Args: fermi_surface: A fermi surface. Returns: The high symmetry k-points and labels. """ kpoints, labels = [], [] hskp = HighSymmKpath(fermi_surface.structure) all_kpoints, all_labels = hskp.get_kpoints(coords_are_cartesian=False) for kpoint, label in zip(all_kpoints, all_labels): if not len(label) == 0: kpoints.append(kpoint) labels.append(label) if isinstance(fermi_surface.reciprocal_space, ReciprocalCell): kpoints = kpoints_to_first_bz(np.array(kpoints)) kpoints = np.dot(kpoints, fermi_surface.reciprocal_space.reciprocal_lattice) return kpoints, labels
def test_continuous_kpath(self): bs = loadfn(os.path.join(PymatgenTest.TEST_FILES_DIR, "Cu2O_361_bandstructure.json")) cont_bs = loadfn( os.path.join(PymatgenTest.TEST_FILES_DIR, "Cu2O_361_bandstructure_continuous.json") ) alt_bs = HighSymmKpath(bs.structure).get_continuous_path(bs) self.assertEqual(cont_bs.as_dict(), alt_bs.as_dict())
def get_line_mode_band_structure( self, line_density: int = 50, energy_cutoff: Optional[float] = None, scissor: Optional[float] = None, bandgap: Optional[float] = None, symprec: float = 0.01, ) -> BandStructureSymmLine: """Gets the interpolated band structure along high symmetry directions. Args: line_density: The maximum number of k-points between each two consecutive high-symmetry k-points energy_cutoff: The energy cut-off to determine which bands are included in the interpolation. If the energy of a band falls within the cut-off at any k-point it will be included. For metals the range is defined as the Fermi level ± energy_cutoff. For gapped materials, the energy range is from the VBM - energy_cutoff to the CBM + energy_cutoff. scissor: The amount by which the band gap is scissored. Cannot be used in conjunction with the ``bandgap`` option. Has no effect for metallic systems. bandgap: Automatically adjust the band gap to this value. Cannot be used in conjunction with the ``scissor`` option. Has no effect for metallic systems. symprec: The symmetry tolerance used to determine the space group and high-symmetry path. Returns: The line mode band structure. """ hsk = HighSymmKpath(self._band_structure.structure, symprec=symprec) kpoints, labels = hsk.get_kpoints(line_density=line_density, coords_are_cartesian=True) labels_dict = { label: kpoint for kpoint, label in zip(kpoints, labels) if label != "" } energies = self.get_energies( kpoints, scissor=scissor, bandgap=bandgap, atomic_units=False, energy_cutoff=energy_cutoff, coords_are_cartesian=True, ) return BandStructureSymmLine( kpoints, energies, self._band_structure.structure.lattice, self._band_structure.efermi, labels_dict, coords_are_cartesian=True, )
def get_band_structure(self, kpaths=None, kpoints_lbls_dict=None, density=20): """ Return a BandStructureSymmLine object interpolating bands along a High symmetry path calculated from the structure using HighSymmKpath function. If kpaths and kpoints_lbls_dict are provided, a custom path is interpolated. kpaths: List of lists of following kpoints labels defining the segments of the path. E.g. [['L','M'],['L','X']] kpoints_lbls_dict: Dict where keys are the kpoint labels used in kpaths and values are their fractional coordinates. E.g. {'L':np.array(0.5,0.5,0.5)}, 'M':np.array(0.5,0.,0.5), 'X':np.array(0.5,0.5,0.)} density: Number of points in each segment. """ if isinstance(kpaths, list) and isinstance(kpoints_lbls_dict, dict): kpoints = [] for kpath in kpaths: for i, k in enumerate(kpath[:-1]): sta = kpoints_lbls_dict[kpath[i]] end = kpoints_lbls_dict[kpath[i + 1]] kpoints.append(np.linspace(sta, end, density)) kpoints = np.concatenate(kpoints) else: kpath = HighSymmKpath(self.data.structure) kpoints = np.vstack( kpath.get_kpoints(density, coords_are_cartesian=False)[0]) kpoints_lbls_dict = kpath.kpath["kpoints"] lattvec = self.data.get_lattvec() egrid, vgrid = fite.getBands(kpoints, self.equivalences, lattvec, self.coeffs) # print(egrid.shape) if self.data.is_spin_polarized: h = sum(np.array_split(self.accepted, 2)[0]) egrid = np.array_split(egrid, [h], axis=0) bands_dict = { Spin.up: (egrid[0] / units.eV), Spin.down: (egrid[1] / units.eV), } else: bands_dict = {Spin.up: (egrid / units.eV)} sbs = BandStructureSymmLine( kpoints, bands_dict, self.data.structure.lattice.reciprocal_lattice, self.efermi / units.eV, labels_dict=kpoints_lbls_dict, ) return sbs
def get_symkpath(atol=1.e-6): struct = get_structure() kpath = HighSymmKpath(struct) # check warning and perform transformation if needed. if not numpy.allclose(kpath._structure.lattice.matrix, kpath._prim.lattice.matrix, atol=atol): warnings.warn("Input structure does not match expected standard " "primitive! Try k-path transformation.") ktrans = kpath._prim.lattice.reciprocal_lattice.matrix.dot(\ numpy.linalg.inv(kpath._structure.lattice.\ reciprocal_lattice.matrix)) for kname in kpath.kpath["kpoints"]: kpath.kpath["kpoints"][kname] = \ kpath.kpath["kpoints"][kname].dot(ktrans) return kpath
def test_automatic_line_mode(minimal_pymatgen_structure): # setup minimal structure structure = minimal_pymatgen_structure # build high symmetry path sympath = HighSymmKpath(structure, path_type='sc') generated_kpoints = [ # list of kpoints forming HighSymmKpath ([0.0, 0.0, 0.0], "\\Gamma"), ([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.0], "M"), ([0.0, 0.0, 0.0], "\\Gamma"), ([0.0, 0.0, 0.0], "\\Gamma"), ([0.5, 0.5, 0.5], "R"), ([0.5, 0.5, 0.5], "R"), ([0.0, 0.5, 0.0], "X"), ([0.5, 0.5, 0.0], "M"), ([0.5, 0.5, 0.5], "R"), ] # setup the kpoints object using the wrapper kpoint_params = { 'mode': 'line', 'kpoints': 100, 'sympath': sympath, } kpoints = KpointWrapper(kpoints=kpoint_params) # need to use real list of lists here because pytest is a bit picky here kpts = list(list(zip(*generated_kpoints))[0]) labels = list(list(zip(*generated_kpoints))[1]) assert kpoints.style == Kpoints_supported_modes.Line_mode # transform kpoint list of numpy.arrays to list of lists assert list(map(list, kpoints.kpts)) == kpts assert kpoints.num_kpts == 100 assert kpoints.labels == labels assert kpoints.kpts_shift == (0., 0., 0.)
def write_band_structure_kpoints(structure, n_kpts=20, dim=2, ibzkpt_path="../"): """ Writes a KPOINTS file for band structure calculations. Does not use the typical linemode syntax for NSCF calculations, but uses the IBZKPT + high-symmetry path syntax described in http://cms.mpi.univie.ac.at/wiki/index.php/Si_bandstructure so that SCF calculations can be performed. This is more reliable than re-using the CHGCAR from a previous run, which often results in "dimensions on the CHGCAR are different" errors in VASP. Args: structure (Structure): structure for determining k-path n_kpts (int): number of divisions along high-symmetry lines dim (int): 2 for a 2D material, 3 for a 3D material. ibzkpt_path (str): location of IBZKPT file. Defaults to one directory up. """ ibz_lines = open(os.path.join(ibzkpt_path, "IBZKPT")).readlines() n_ibz_kpts = int(ibz_lines[1].split()[0]) kpath = HighSymmKpath(structure) Kpoints.automatic_linemode(n_kpts, 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)))
def extract_bs(mat): bs = None # Process the bandstructure for information if "bs" in mat["bandstructure"]: bs_dict = mat["bandstructure"]["bs"] # Add in structure if not already there if "structure" not in bs_dict: bs_dict["structure"] = mat["structure"] # Add in High Symm K Path if not already there if len(bs_dict.get("labels_dict", {})) == 0: labels = get(mat, "inputs.nscf_line.kpoints.labels", None) kpts = get(mat, "inputs.nscf_line.kpoints.kpoints", None) if labels and kpts: labels_dict = dict(zip(labels, kpts)) labels_dict.pop(None, None) else: struc = Structure.from_dict(mat["structure"]) labels_dict = HighSymmKpath(struc)._kpath["kpoints"] bs_dict["labels_dict"] = labels_dict bs = BandStructureSymmLine.from_dict( BandStructure.from_dict(bs_dict).as_dict()) return bs
def setUp(self): with open(os.path.join(test_dir, 'si_structure.json'), 'r') as sth: si_str = Structure.from_dict(json.load(sth)) with open(os.path.join(test_dir, 'si_bandstructure_line.json'), 'r') as bsh: si_bs_line = BandStructureSymmLine.from_dict(json.load(bsh)) si_bs_line.structure = si_str with open(os.path.join(test_dir, 'si_bandstructure_uniform.json'), 'r') as bsh: si_bs_uniform = BandStructure.from_dict(json.load(bsh)) si_bs_uniform.structure = si_str self.si_kpts = list(HighSymmKpath(si_str).kpath['kpoints'].values()) self.df = pd.DataFrame({ 'bs_line': [si_bs_line], 'bs_uniform': [si_bs_uniform] }) with open(os.path.join(test_dir, 'VBr2_971787_bandstructure.json'), 'r') as bsh: vbr2_uniform = BandStructure.from_dict(json.load(bsh)) self.vbr2kpts = [ k.frac_coords for k in vbr2_uniform.labels_dict.values() ] self.vbr2kpts = [ [0.0, 0.0, 0.0], # \\Gamma [0.2, 0.0, 0.0], # between \\Gamma and M [0.5, 0.0, 0.0], # M [0.5, 0.0, 0.5] ] # L self.df2 = pd.DataFrame({'bs_line': [vbr2_uniform]})
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 set_kpath(self, ndivsm, kptbounds=None, iscf=-2): """ Set the variables for the computation of the electronic band structure. Args: ndivsm: Number of divisions for the smallest segment. kptbounds: k-points defining the path in k-space. If None, we use the default high-symmetry k-path defined in the pymatgen database. """ if kptbounds is None: from pymatgen.symmetry.bandstructure import HighSymmKpath hsym_kpath = HighSymmKpath(self.structure) name2frac_coords = hsym_kpath.kpath["kpoints"] kpath = hsym_kpath.kpath["path"] frac_coords, names = [], [] for segment in kpath: for name in segment: fc = name2frac_coords[name] frac_coords.append(fc) names.append(name) kptbounds = np.array(frac_coords) kptbounds = np.reshape(kptbounds, (-1, 3)) # self.pop_vars(["ngkpt", "shiftk"]) ?? return self.set_vars(kptbounds=kptbounds, kptopt=-(len(kptbounds) - 1), ndivsm=ndivsm, iscf=iscf)
def write_band_conf(self): """ prepare the input file(band.conf) for phonon band structure """ primi_structure = self.struc.get_primitive_structure() primi_lattice = primi_structure.lattice.matrix.T lattice = self.struc.lattice.matrix.T transformation = np.round(inv(lattice) @ primi_lattice, 5).flatten().tolist() t_string = [str(i) for i in transformation] kpath = HighSymmKpath(self.struc.get_primitive_structure()).kpath ##the primitive structure??? print(primi_structure.get_space_group_info()) kpath_string = 'BAND =' print('Please indicate the k-path, disconnect paths are indicated by \',\', we have the following kpoints:') print(kpath['kpoints']) a = input('Enter your input:') self.kpath_name = a a_split = a.split(',') for i, item in enumerate(a_split): for point in item.strip().split(' '): kpath_string += ' ' kpath_string += ' '.join([str(i) for i in kpath['kpoints'][point].tolist()]) if i < len(a_split)-1: kpath_string += ',' a = a.replace('\Gamma', '$\Gamma$') label_string = 'BAND_LABELS = ' + a with open(os.path.join(self.wd, self.dfpt_folder+'/band.conf'), 'w') as f: f.write('DIM = {} {} {}\n'.format(self.scaling_matrix[0], self.scaling_matrix[1], self.scaling_matrix[2])) f.write('PRIMITIVE_AXIS = ' + ' '.join(t_string) + '\n') f.write(kpath_string + '\n') f.write(label_string + '\n') f.write('FORCE_CONSTANTS = READ\n')
def get_symmetry_points( fermi_slice: FermiSlice) -> Tuple[np.ndarray, List[str]]: """ Get the high symmetry k-points and labels for the Fermi slice. Args: fermi_slice: A fermi slice. Returns: The high symmetry k-points and labels for points that lie on the slice. """ hskp = HighSymmKpath(fermi_slice.structure) labels, kpoints = list(zip(*hskp.kpath["kpoints"].items())) if isinstance(fermi_slice.reciprocal_slice.reciprocal_space, ReciprocalCell): kpoints = kpoints_to_first_bz(np.array(kpoints)) kpoints = np.dot( kpoints, fermi_slice.reciprocal_slice.reciprocal_space.reciprocal_lattice) kpoints = transform_points(kpoints, fermi_slice.reciprocal_slice.transformation) # filter points that do not lie very close to the plane on_plane = np.where(np.abs(kpoints[:, 2]) < 1e-4)[0] kpoints = kpoints[on_plane] labels = [labels[i] for i in on_plane] return kpoints[:, :2], labels
def run_task(self, fw_spec): user_incar_settings = {"NCORE": 8} # vol = Poscar.from_file("POSCAR").structure.volume # kppra_vol = self.kpoints_density / vol if self.line: MPNonSCFSet.from_prev_calc( os.getcwd(), mode="Line", copy_chgcar=False, user_incar_settings=user_incar_settings, kpoints_line_density=self.kpoints_line_density).write_input( '.') kpath = HighSymmKpath(Poscar.from_file("POSCAR").structure) return FWAction(stored_data={ "kpath": kpath.kpath, "kpath_name": kpath.name }) else: MPNonSCFSet.from_prev_calc( os.getcwd(), mode="Uniform", copy_chgcar=False, user_incar_settings=user_incar_settings, reciprocal_density=self.kpoints_density).write_input('.') return FWAction()
def _path(cls, ndivsm, structure=None, kpath_bounds=None, comment=None): """ Static constructor for path in k-space. Args: structure: :class:`Structure` object. kpath_bounds: List with the reduced coordinates of the k-points defining the path. ndivsm: Number of division for the smallest segment. comment: Comment string. Returns: :class:`KSampling` object. """ if kpath_bounds is None: # Compute the boundaries from the input structure. from pymatgen.symmetry.bandstructure import HighSymmKpath sp = HighSymmKpath(structure) # Flat the array since "path" is a a list of lists! kpath_labels = [] for labels in sp.kpath["path"]: kpath_labels.extend(labels) kpath_bounds = [] for label in kpath_labels: red_coord = sp.kpath["kpoints"][label] #print("label %s, red_coord %s" % (label, red_coord)) kpath_bounds.append(red_coord) return cls(mode=KSamplingModes.path, num_kpts=ndivsm, kpts=kpath_bounds, comment=comment if comment else "K-Path scheme")
def run_task(self, fw_spec): try: vasp_run = Vasprun("vasprun.xml", parse_dos=False, parse_eigen=False) outcar = Outcar(os.path.join(os.getcwd(), "OUTCAR")) except Exception as e: raise RuntimeError("Can't get valid results from relaxed run: " + str(e)) user_incar_settings = MPNonSCFVaspInputSet.get_incar_settings( vasp_run, outcar) user_incar_settings.update({"NPAR": 2}) structure = MPNonSCFVaspInputSet.get_structure(vasp_run, outcar, initial_structure=True) if self.line: mpnscfvip = MPNonSCFVaspInputSet(user_incar_settings, mode="Line") for k, v in mpnscfvip.get_all_vasp_input( structure, generate_potcar=True).items(): v.write_file(os.path.join(os.getcwd(), k)) kpath = HighSymmKpath(structure) else: mpnscfvip = MPNonSCFVaspInputSet(user_incar_settings, mode="Uniform") for k, v in mpnscfvip.get_all_vasp_input( structure, generate_potcar=True).items(): v.write_file(os.path.join(os.getcwd(), k)) if self.line: return FWAction(stored_data={"kpath": kpath.kpath, "kpath_name": kpath.name}) else: return FWAction()
def test_continuous_kpath(self): bs = loadfn(os.path.join(test_dir, "Cu2O_361_bandstructure.json")) hskp = HighSymmKpath(bs.structure).get_continuous_path(bs) distance_map = [ (3, False), (5, True), (1, True), (4, True), (3, True), (2, True), (1, True), (0, True), ] labels = [ ("\\Gamma", "R"), ("R", "M"), ("M", "X"), ("X", "R"), ("R", "\\Gamma"), ("\\Gamma", "M"), ("M", "X"), ("X", "\\Gamma"), ] self.assertEqual(hskp, (distance_map, labels))
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 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 testKpoints(self): """ Kpointsをチェック """ # for Band src = os.path.join(self.path, 'src_poscar') poscar = vasp.Poscar.from_file(src, check_for_POTCAR=False) hsk = HighSymmKpath(poscar.structure) kpts = hsk.get_kpoints() args = {'comment': "Kpoints for band calc", 'kpts': kpts[0], 'num_kpts': len(kpts[0]), 'labels': kpts[1], 'style': 'Reciprocal', 'kpts_weights': [1]*len(kpts[0])} kpoints = vasp.Kpoints(**args) print(kpoints)
def get_phonon_band_structure_symm_line_from_fc( structure: Structure, supercell_matrix: np.ndarray, force_constants: np.ndarray, line_density: float = 20.0, symprec: float = 0.01, **kwargs, ) -> PhononBandStructureSymmLine: """ Get a phonon band structure along a high symmetry path from phonopy force constants. Args: structure: A structure. supercell_matrix: The supercell matrix used to generate the force constants. force_constants: The force constants in phonopy format. line_density: The density along the high symmetry path. symprec: Symmetry precision passed to phonopy and used for determining the band structure path. **kwargs: Additional kwargs passed to the Phonopy constructor. Returns: The line mode band structure. """ structure_phonopy = get_phonopy_structure(structure) phonon = Phonopy(structure_phonopy, supercell_matrix=supercell_matrix, symprec=symprec, **kwargs) phonon.set_force_constants(force_constants) kpath = HighSymmKpath(structure, symprec=symprec) kpoints, labels = kpath.get_kpoints(line_density=line_density, coords_are_cartesian=False) phonon.run_qpoints(kpoints) frequencies = phonon.qpoints.get_frequencies().T labels_dict = {a: k for a, k in zip(labels, kpoints) if a != ""} return PhononBandStructureSymmLine(kpoints, frequencies, structure.lattice, labels_dict=labels_dict)
def hse06_bandstructure_kpoints(struct, nkpts=20, kmesh=(11, 11, 11), is_shift=(0, 0, 0), ibzkpt_file=False): ''' 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") # high-symmetry k-points kpts = sym_kpts.kpts nsegs = sym_kpts.num_kpts # Line mode k-points line_kpts = [] for rng in chunks(kpts, 2): start, end = rng line_kpts.append(np.linspace(start, end, nsegs)) ln_kpts_vec = np.array(line_kpts).reshape((-1, 3)) ln_kpts_wht = np.zeros(ln_kpts_vec.shape[0]) ln_kpts = np.c_[ln_kpts_vec, ln_kpts_wht] if ibzkpt_file: kpoints = open('IBZKPT', "r").readlines() kpoints[1] = "{:8}\n".format( int(kpoints[1].strip()) + ln_kpts.shape[0]) with open("KPOINTS", "w") as K: K.write("".join(kpoints)) np.savetxt(K, ln_kpts, fmt="%20.14f%20.14f%20.14f%14d") else: # generate irreducible k-points in the BZ ana_struct = SpacegroupAnalyzer(struct) ir_kpts_with_wht = ana_struct.get_ir_reciprocal_mesh(mesh=kmesh, is_shift=is_shift) ir_kpts_vec = np.array([x[0] for x in ir_kpts_with_wht]) ir_kpts_wht = np.array([x[1] for x in ir_kpts_with_wht]) ir_kpts = np.c_[ir_kpts_vec, ir_kpts_wht] with open("KPOINTS", "w") as K: K.write("Generated by MAPTOOL\n") K.write("{:8d}\n".format(ln_kpts.shape[0] + ir_kpts.shape[0])) K.write("Reciprocal Lattice\n") np.savetxt(K, ir_kpts, fmt="%20.14f%20.14f%20.14f%14d") np.savetxt(K, ln_kpts, fmt="%20.14f%20.14f%20.14f%14d")
def get_kpoints(strt=''): kpath = HighSymmKpath(strt) kp=kpath.kpath['kpoints'] uniqe_lbl=[] uniqe_k=[] for i, j in kp.items(): uniqe_lbl.append(j) uniqe_k.append(i) return uniqe_lbl,uniqe_k
def get_kpoints(self, structure, kpoints_density=1000): """ Get a KPOINTS file for NonSCF calculation. In "Line" mode, kpoints are generated along high symmetry lines. In "Uniform" mode, kpoints are Gamma-centered mesh grid. Kpoints are written explicitly in both cases. Args: kpoints_density: kpoints density for the reciprocal cell of structure. Suggest to use a large kpoints_density. Might need to increase the default value when calculating metallic materials. """ if self.mode == "Line": kpath = HighSymmKpath(structure) cart_k_points, k_points_labels = kpath.get_kpoints() frac_k_points = [ kpath._prim_rec.get_fractional_coords(k) for k in cart_k_points ] return Kpoints(comment="Non SCF run along symmetry lines", style="Reciprocal", num_kpts=len(frac_k_points), kpts=frac_k_points, labels=k_points_labels, kpts_weights=[1] * len(cart_k_points)) else: num_kpoints = kpoints_density * \ structure.lattice.reciprocal_lattice.volume kpoints = Kpoints.automatic_density( structure, num_kpoints * structure.num_sites) mesh = kpoints.kpts[0] ir_kpts = SymmetryFinder(structure, symprec=0.01)\ .get_ir_reciprocal_mesh(mesh) kpts = [] weights = [] for k in ir_kpts: kpts.append(k[0]) weights.append(int(k[1])) return Kpoints(comment="Non SCF run on uniform grid", style="Reciprocal", num_kpts=len(ir_kpts), kpts=kpts, kpts_weights=weights)
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 get_kpoints_wannier(structure, n_kpts=1, dim=2): kpath = HighSymmKpath(structure) os.system('mv KPOINTS K_temp') Kpoints.automatic_linemode(n_kpts, kpath).write_file('KPOINTS') if dim == 2: remove_z_kpoints() path = find_kpath(f='KPOINTS') os.system('rm KPOINTS') os.system('mv K_temp KPOINTS') return path
def test_kpath_acentered(self): species = ['K', 'La', 'Ti'] coords = [[.345, 5, .77298], [.1345, 5.1, .77298], [.7, .8, .9]] lattice = Lattice.orthorhombic(2, 9, 1) struct = Structure.from_spacegroup(38, lattice, species, coords) kpath = HighSymmKpath(struct) kpoints = kpath._kpath['kpoints'] labels = list(kpoints.keys()) self.assertEqual( sorted(labels), sorted( ['\\Gamma', 'A', 'A_1', 'R', 'S', 'T', 'X', 'X_1', 'Y', 'Z'])) self.assertEqual(kpoints['\\Gamma'][0], 0.00000000) self.assertAlmostEqual(kpoints['\\Gamma'][1], 0.00000000) self.assertAlmostEqual(kpoints['\\Gamma'][2], 0.00000000) self.assertAlmostEqual(kpoints['A'][0], 0.25308642) self.assertAlmostEqual(kpoints['A'][1], 0.25308642) self.assertAlmostEqual(kpoints['A'][2], 0.50000000) self.assertAlmostEqual(kpoints['A_1'][0], -0.25308642) self.assertAlmostEqual(kpoints['A_1'][1], 0.74691358) self.assertAlmostEqual(kpoints['A_1'][2], 0.50000000) self.assertAlmostEqual(kpoints['R'][0], 0.00000000) self.assertAlmostEqual(kpoints['R'][1], 0.50000000) self.assertAlmostEqual(kpoints['R'][2], 0.50000000) self.assertAlmostEqual(kpoints['S'][0], 0.00000000) self.assertAlmostEqual(kpoints['S'][1], 0.50000000) self.assertAlmostEqual(kpoints['S'][2], 0.00000000) self.assertAlmostEqual(kpoints['T'][0], -0.50000000) self.assertAlmostEqual(kpoints['T'][1], 0.50000000) self.assertAlmostEqual(kpoints['T'][2], 0.50000000) self.assertAlmostEqual(kpoints['X'][0], 0.25308642) self.assertAlmostEqual(kpoints['X'][1], 0.25308642) self.assertAlmostEqual(kpoints['X'][2], 0.00000000) self.assertAlmostEqual(kpoints['X_1'][0], -0.25308642) self.assertAlmostEqual(kpoints['X_1'][1], 0.74691358) self.assertAlmostEqual(kpoints['X_1'][2], 0.00000000) self.assertAlmostEqual(kpoints['Y'][0], -0.50000000) self.assertAlmostEqual(kpoints['Y'][1], 0.50000000) self.assertAlmostEqual(kpoints['Y'][2], 0.00000000) self.assertAlmostEqual(kpoints['Z'][0], 0.00000000) self.assertAlmostEqual(kpoints['Z'][1], 0.00000000) self.assertAlmostEqual(kpoints['Z'][2], 0.50000000)
def calculate_standard_path(structure): lattice = mg.Lattice(structure.lattice_vectors) atoms = structure.atoms structure_mg = mg.Structure(lattice, atoms[:, 3], atoms[:, :3]) hs_path = HighSymmKpath(structure_mg, symprec=0.1) if not hs_path.kpath: # fix for bug in pymatgen that for certain structures no path is returned raise Exception('High symmetry path generation failed.') conv_path = convert_hs_path_to_own(hs_path) return conv_path
def get_kpoints(self, structure, kpoints_density=1000): """ Get a KPOINTS file for NonSCF calculation. In "Line" mode, kpoints are generated along high symmetry lines. In "Uniform" mode, kpoints are Gamma-centered mesh grid. Kpoints are written explicitly in both cases. Args: kpoints_density: kpoints density for the reciprocal cell of structure. Suggest to use a large kpoints_density. Might need to increase the default value when calculating metallic materials. """ if self.mode == "Line": kpath = HighSymmKpath(structure) cart_k_points, k_points_labels = kpath.get_kpoints() frac_k_points = [kpath._prim_rec.get_fractional_coords(k) for k in cart_k_points] return Kpoints(comment="Non SCF run along symmetry lines", style="Reciprocal", num_kpts=len(frac_k_points), kpts=frac_k_points, labels=k_points_labels, kpts_weights=[1]*len(cart_k_points)) else: num_kpoints = kpoints_density * \ structure.lattice.reciprocal_lattice.volume kpoints = Kpoints.automatic_density( structure, num_kpoints * structure.num_sites) mesh = kpoints.kpts[0] ir_kpts = SymmetryFinder(structure, symprec=0.01)\ .get_ir_reciprocal_mesh(mesh) kpts = [] weights = [] for k in ir_kpts: kpts.append(k[0]) weights.append(int(k[1])) return Kpoints(comment="Non SCF run on uniform grid", style="Reciprocal", num_kpts=len(ir_kpts), kpts=kpts, kpts_weights=weights)
# read structure if os.path.exists(fstruct): struct = mg.read_structure(fstruct) else: print("File %s does not exist" % fstruct) exit(1) # symmetry information struct_sym = SymmetryFinder(struct) print("lattice type : {0}".format(struct_sym.get_lattice_type())) print("space group : {0} ({1})".format(struct_sym.get_spacegroup_symbol(), struct_sym.get_spacegroup_number())) # Compute first brillouin zone ibz = HighSymmKpath(struct) ibz.get_kpath_plot(savefig="path.png") print("ibz type : {0}".format(ibz.name)) # print specific kpoints in the first brillouin zone for key, val in ibz.kpath["kpoints"].items(): print("%8s %s" % (key, str(val))) # suggested path for the band structure print("paths in first brillouin zone :") for path in ibz.kpath["path"]: print(path) # write the KPOINTS file Kpoints.automatic_linemode(ndiv, ibz).write_file("KPOINTS")
def main(): """ Main routine """ parser = argparse.ArgumentParser(description='Calculate the band structure of a vasp calculation.') parser.add_argument('-d', '--density', nargs='?', default=10, type=int, help='k-point density of the bands (default: 10)') parser.add_argument('-s', '--sigma', nargs='?', default=0.04, type=float, help='SIGMA value in eV (default: 0.04)') parser.add_argument('-l', '--linemode', nargs='?', default=None, type=str, help='linemode file') parser.add_argument('-v', '--vasp', nargs='?', default='vasp', type=str, help='vasp executable') args = parser.parse_args() line_density = args.density line_file = args.linemode # Check that required files exist _check('vasprun.xml') _check('INCAR') _check('POSCAR') _check('POTCAR') _check('CHGCAR') # Get IBZ from vasprun vasprun = Vasprun('vasprun.xml') ibz = HighSymmKpath(vasprun.final_structure) # Create a temp directory print('Create temporary directory ... ', end='') tempdir = mkdtemp() print(tempdir) # Edit the inputs print('Saving new inputs in temporary directory ... ') incar = Incar.from_file('INCAR') print('Making the following changes to the INCAR:') print(' ICHARG = 11') print(' ISMEAR = 0') print(' SIGMA = %f' % args.sigma) incar['ICHARG'] = 11 # Constant density incar['ISMEAR'] = 0 # Gaussian Smearing incar['SIGMA'] = args.sigma # Smearing temperature incar.write_file(os.path.join(tempdir, 'INCAR')) # Generate line-mode kpoint file if line_file is None: print('Creating a new KPOINTS file:') kpoints = _automatic_kpoints(line_density, ibz) kpoints.write_file(os.path.join(tempdir, 'KPOINTS')) print('### BEGIN KPOINTS') print(kpoints) print('### END KPOINTS') else: cp(line_file, os.path.join(tempdir, 'KPOINTS')) # Copy other files (May take some time...) print('Copying POSCAR, POTCAR and CHGCAR to the temporary directory.') cp('POSCAR', os.path.join(tempdir, 'POSCAR')) cp('POTCAR', os.path.join(tempdir, 'POTCAR')) cp('CHGCAR', os.path.join(tempdir, 'CHGCAR')) # cd to temp directory and run vasp path = os.getcwd() os.chdir(tempdir) print('Running VASP in the temporary directory ...') try: check_call(args.vasp) except CalledProcessError: print('There was an error running VASP') _clean_exit(path, tempdir) # Read output vasprun = Vasprun('vasprun.xml') ibz = HighSymmKpath(vasprun.final_structure) _, _ = ibz.get_kpoints(line_density) bands = vasprun.get_band_structure() print('Success! Efermi = %f' % bands.efermi) # Backup vasprun.xml only print('Making a gzip backup of vasprun.xml called bands_vasprun.xml.gz') zfile = os.path.join(path, 'bands_vasprun.xml.gz') try: with gzip.open(zfile, 'wb') as gz, open('vasprun.xml', 'rb') as vr: gz.writelines(vr) except (OSError, IOError): print('There was an error with gzip') _clean_exit(path, tempdir) # Return to original path os.chdir(path) # Write band structure # There may be multiple bands due to spin or noncollinear. for key, item in bands.bands.items(): print('Preparing bands_%s.csv' % key) kpts = [] # Get list of kpoints for kpt in bands.kpoints: kpts.append(kpt.cart_coords) # Subtract fermi energy print('Shifting energies so Efermi = 0.') band = numpy.array(item) - bands.efermi # Prepend kpoint vector as label out = numpy.hstack([kpts, band.T]) final = [] lastrow = float('inf') * numpy.ones(3) for row in out: if numpy.linalg.norm(row[:3] - lastrow) > 1.e-12: final.append(row) lastrow = row[:3] # Write bands to csv file. print('Writing bands_%s.csv to disk' % key) with open('bands_%s.csv' % key, 'w+') as f: numpy.savetxt(f, numpy.array(final), delimiter=',', header=' kptx, kpty, kptz, band1, band2, ... ') # Delete temporary directory _clean_exit(path, tempdir, 0)
def __init__(self, structure): HighSymmKpath.__init__(self, structure)