Exemple #1
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 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')
Exemple #3
0
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
Exemple #4
0
 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()
Exemple #5
0
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
Exemple #6
0
    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 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 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('../')
Exemple #9
0
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)
Exemple #10
0
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"))
Exemple #11
0
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")
Exemple #12
0
    def write_kpoints_along_hs_path(self, divisions=5):
        """
        writes a KPOINTS file for band structure calculation  use
        """
        hs_kpoints_file_name = os.path.join(self._save_to_path, 'KPOINTS')

        structure = Structure.from_file(
            os.path.join(self._save_to_path, 'POSCAR'))
        kpath = HighSymmKpath(structure)
        kpts = Kpoints.automatic_linemode(divisions=divisions, ibz=kpath)
        kpts.write_file(hs_kpoints_file_name)
Exemple #13
0
def band_structure_kpath(struct, dirname, nkpts=30):
    """
    Generate KPOINTS file for band structure calculation via pymatgen's symmetry
    analyzing system.
    """
    #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"))
Exemple #14
0
 def get_path_dependent_Kpoints(self, divisions = 10):
     
     ''' Gets the primitive unit cell from the CONTCAR file as primitive_structure '''
     ''' Gets the high symmetry k path of the primitive unit cell as k_path '''
     ''' Returns the pymatgen.io.vasp.inputs.Kpoints object, with symmetric k points specified '''
     ''' NOTE: divisions is the number of points sampled along each path between k points, default = 10'''
     
     primitive_structure = Structure.from_file(self.cwd + '/CONTCAR', primitive=True)
     k_path = HighSymmKpath(primitive_structure)
     kpoints = Kpoints.automatic_linemode(divisions, k_path)
     
     return kpoints
Exemple #15
0
 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))
Exemple #16
0
 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))
Exemple #17
0
def generate_line(ndiv=20, dim=2, for_scan_hse=False):
    """ 
    Generate linemode KPOINTS.
    
    Parameters
    ----------
    [optional] ndiv (int): number of divisions along high-symmetry lines. Default=20.
    [optional] dim (int): dimensionality of structure. Default=2.
    [optional] for_scan_hse (bool): to generate special KPOINTS for SCAN/HSE?. Default=False.
       
    """

    dir_sub = os.getcwd()

    poscar = Poscar.from_file(os.path.join(dir_sub, "POSCAR"),
                              check_for_POTCAR=False,
                              read_velocities=False)
    structure = poscar.structure

    ## use pymatgen symmetry functions to determine the high-symmetry k-path
    kpts_line = Kpoints.automatic_linemode(int(ndiv), HighSymmKpath(structure))
    ## if 2D structure specified, remove k-points with non-zero z-component
    if int(dim) == 2:
        kpts_line = remove_z_kpoints(kpts_line)

    if not for_scan_hse:
        ## write out regular KPOINT file for bandstructure calc. with PBE
        kpts_line.write_file(os.path.join(dir_sub, "KPOINTS_bands"))

    else:
        ## get regular grid kpoints from IBZKPT file
        ibz_lines, n_ibz_kpts = get_ibzkpts()
        ## get explicit kpoints between each high-symmetry point
        abs_path = get_kpts_line_explicit(kpts_line, int(ndiv))
        ## write out special KPOINT file for bandstructure calc. with SCAN/HSE
        with open(os.path.join(dir_sub, "KPOINTS_bands_SCAN"), 'w') as f:
            f.write('Special KPOINTS file\n')
            f.write('{}\n'.format(n_ibz_kpts + len(abs_path)))
            f.write('Reciprocal Lattice\n')
            for line in ibz_lines[3:]:
                f.write(line)
            for point in abs_path:
                f.write('{}\n'.format(' '.join(point)))
Exemple #18
0
 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
Exemple #19
0
 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
Exemple #20
0
# Requires: pymatgen module
# Generates KPOINTS.bands file with high symmetry lines added for
# an arbitrary POSCAR with symmetry precision=1e-3

import pymatgen as mg
from pymatgen.symmetry.bandstructure import HighSymmKpath
from pymatgen.io.vasp.inputs import Kpoints

struct = mg.Structure.from_file("POSCAR")
kpath = HighSymmKpath(struct)
kpoints = Kpoints.automatic_linemode(16, kpath)
kpoints.write_file("KPOINTS.bands")
Exemple #21
0
 def write_hs_kpoints(self):
     save_dir = 'VaspInputsDir/' + self.mp_id + '/'
     kpts = Kpoints.automatic_linemode(divisions=1, ibz=self.kpath)
     kpts.write_file(save_dir + 'KPOINTS')
Exemple #22
0
from pymatgen.io.vasp.inputs import Kpoints
from pymatgen.core import Structure
from pymatgen.symmetry.bandstructure import HighSymmKpath

struct = Structure.from_file("POSCAR")
kpath = HighSymmKpath(struct)
kpts = Kpoints.automatic_linemode(divisions=40, ibz=kpath)
kpts.write_file("KPOINTS")
print(kpts)
Exemple #23
0
def get_2D_hse_kpoints(struct_for_path, ibzkpth):
    """
    Args:
        struct_for_path: Structure from which linemode k-points will
            be generated.
        ibzkpth:

    Returns:
        the Kpoints file object in the form of a string
              ready for execution by MPInterfaces
              calibrate objects
    """
    # Read IBZKPT from prep step
    ibz_lines = open(ibzkpth).readlines()
    n_ibz_kpts = int(ibz_lines[1].split()[0])

    # Read linemode KPOINTs from the dict (makes sure it is Kpoints
    # file with only 20 per atom for the optimized settings
    # Kpoints.from_dict(kpoint_dict).write_file('linemode_KPOINTS')
    kpath = HighSymmKpath(struct_for_path)
    Kpoints.automatic_linemode(20, kpath).write_file('KPOINTS_linemode')
    remove_z_kpoints_linemode()
    linemode_lines = open('KPOINTS_linemode').readlines()

    # put them together
    abs_path = []
    for i in range(4, len(linemode_lines), 3):
        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]])

    n_linemode_kpts = len(abs_path)

    # write out the kpoints file and return the object

    Kpoints_hse_file = '\n'.join(
        ['Automatically generated mesh',
         '{}'.format(n_ibz_kpts + n_linemode_kpts),
         'Reciprocal Lattice',
         '{}'.format(str(''.join([line for line in ibz_lines[3:]])))]) + \
                       '{}'.format(str('\n'.join(
                           [' '.join(point) for point in abs_path])))

    ## can be used for test print out
    # with open('KPOINTS_HSE', '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)))

    return Kpoints_hse_file
Exemple #24
0
def run_hse_calculation(dim=2,
                        submit=True,
                        force_overwrite=False,
                        destroy_prep_directory=False):
    """
    Setup/submit an HSE06 calculation to get an accurate band structure.
    Requires a previous IBZKPT from a standard DFT run. See
    http://cms.mpi.univie.ac.at/wiki/index.php/Si_bandstructure for more
    details.

    Args:
        dim (int): 2 for relaxing a 2D material, 3 for a 3D material.
        submit (bool): Whether or not to submit the job.
        force_overwrite (bool): Whether or not to overwrite files
            if an already converged vasprun.xml exists in the
            directory.
        destroy_prep_directory (bool): whether or not to remove
            (rm -r) the hse_prep directory, if it exists. This
            can help to automatically clean up and save space.
    """

    HSE_INCAR_DICT = {
        'LHFCALC': True,
        'HFSCREEN': 0.2,
        'AEXX': 0.25,
        'ALGO': 'D',
        'TIME': 0.4,
        'NSW': 0,
        'LVTOT': True,
        'LVHAR': True,
        'LORBIT': 11,
        'LWAVE': True,
        'NPAR': 8,
        'PREC': 'Accurate',
        'EDIFF': 1e-4,
        'ENCUT': 450,
        'ICHARG': 2,
        'ISMEAR': 1,
        'SIGMA': 0.1,
        'IBRION': 2,
        'ISIF': 3,
        'ISPIN': 2
    }

    if not os.path.isdir('hse_bands'):
        os.mkdir('hse_bands')
    if force_overwrite or not is_converged('hse_bands'):
        os.chdir('hse_bands')
        os.system('cp ../CONTCAR ./POSCAR')
        if os.path.isfile('../POTCAR'):
            os.system('cp ../POTCAR .')
        HSE_INCAR_DICT.update(
            {'MAGMOM': get_magmom_string(Structure.from_file('POSCAR'))})
        Incar.from_dict(HSE_INCAR_DICT).write_file('INCAR')

        # Re-use the irreducible brillouin zone KPOINTS from a
        # previous standard DFT run.
        if os.path.isdir('../hse_prep'):
            ibz_lines = open('../hse_prep/IBZKPT').readlines()
            if destroy_prep_directory:
                os.system('rm -r ../hse_prep')
        else:
            ibz_lines = open('../IBZKPT').readlines()

        n_ibz_kpts = int(ibz_lines[1].split()[0])
        kpath = HighSymmKpath(Structure.from_file('POSCAR'))
        Kpoints.automatic_linemode(20, kpath).write_file('KPOINTS')
        if dim == 2:
            remove_z_kpoints()
        linemode_lines = open('KPOINTS').readlines()

        abs_path = []
        i = 4
        while i < len(linemode_lines):
            start_kpt = linemode_lines[i].split()
            end_kpt = linemode_lines[i + 1].split()
            increments = [(float(end_kpt[0]) - float(start_kpt[0])) / 20,
                          (float(end_kpt[1]) - float(start_kpt[1])) / 20,
                          (float(end_kpt[2]) - float(start_kpt[2])) / 20]

            abs_path.append(start_kpt[:3] + ['0', start_kpt[4]])
            for n in range(1, 20):
                abs_path.append([
                    str(float(start_kpt[0]) + increments[0] * n),
                    str(float(start_kpt[1]) + increments[1] * n),
                    str(float(start_kpt[2]) + increments[2] * n), '0'
                ])
            abs_path.append(end_kpt[:3] + ['0', end_kpt[4]])
            i += 3

        n_linemode_kpts = len(abs_path)

        with open('KPOINTS', 'w') as kpts:
            kpts.write('Automatically generated mesh\n')
            kpts.write('{}\n'.format(n_ibz_kpts + n_linemode_kpts))
            kpts.write('Reciprocal Lattice\n')
            for line in ibz_lines[3:]:
                kpts.write(line)
            for point in abs_path:
                kpts.write('{}\n'.format(' '.join(point)))

        if QUEUE_SYSTEM == 'pbs':
            write_pbs_runjob('{}_hsebands'.format(os.getcwd().split('/')[-2]),
                             2, 64, '1800mb', '50:00:00', VASP_STD_BIN)
            submission_command = 'qsub runjob'

        elif QUEUE_SYSTEM == 'slurm':
            write_slurm_runjob(
                '{}_hsebands'.format(os.getcwd().split('/')[-2]), 64, '1800mb',
                '50:00:00', VASP_STD_BIN)
            submission_command = 'sbatch runjob'

        if submit:
            _ = subprocess.check_output(submission_command.split())

        os.chdir('../')
def gen_hs_kpoints(structure):
    kpath = HighSymmKpath(structure)
    kpts = Kpoints.automatic_linemode(divisions=7, ibz=kpath)
    kpts.write_file('KPOINTS')
Exemple #26
0
def run_hse_calculation(dim=2, submit=True, force_overwrite=False,
                        destroy_prep_directory=False):
    """
    Setup/submit an HSE06 calculation to get an accurate band structure.
    Requires a previous IBZKPT from a standard DFT run. See
    http://cms.mpi.univie.ac.at/wiki/index.php/Si_bandstructure for more
    details.

    Args:
        dim (int): 2 for relaxing a 2D material, 3 for a 3D material.
        submit (bool): Whether or not to submit the job.
        force_overwrite (bool): Whether or not to overwrite files
            if an already converged vasprun.xml exists in the
            directory.
        destroy_prep_directory (bool): whether or not to remove
            (rm -r) the hse_prep directory, if it exists. This
            can help you to automatically clean up and save space.
    """

    HSE_INCAR_DICT = {'LHFCALC': True, 'HFSCREEN': 0.2, 'AEXX': 0.25,
                      'ALGO': 'D', 'TIME': 0.4, 'NSW': 0,
                      'LVTOT': True, 'LVHAR': True, 'LORBIT': 11,
                      'LWAVE': True, 'NPAR': 8, 'PREC': 'Accurate',
                      'EDIFF': 1e-4, 'ENCUT': 450, 'ICHARG': 2, 'ISMEAR': 1,
                      'SIGMA': 0.1, 'IBRION': 2, 'ISIF': 3, 'ISPIN': 2}

    if not os.path.isdir('hse_bands'):
        os.mkdir('hse_bands')
    if force_overwrite or not is_converged('hse_bands'):
        os.chdir('hse_bands')
        os.system('cp ../CONTCAR ./POSCAR')
        if os.path.isfile('../POTCAR'):
            os.system('cp ../POTCAR .')
        HSE_INCAR_DICT.update({'MAGMOM': get_magmom_string()})
        Incar.from_dict(HSE_INCAR_DICT).write_file('INCAR')

        # Re-use the irreducible brillouin zone KPOINTS from a
        # previous standard DFT run.
        if os.path.isdir('../hse_prep'):
            ibz_lines = open('../hse_prep/IBZKPT').readlines()
            if destroy_prep_directory:
                os.system('rm -r ../hse_prep')
        else:
            ibz_lines = open('../IBZKPT').readlines()

        n_ibz_kpts = int(ibz_lines[1].split()[0])
        kpath = HighSymmKpath(Structure.from_file('POSCAR'))
        Kpoints.automatic_linemode(20, kpath).write_file('KPOINTS')
        if dim == 2:
            remove_z_kpoints()
        linemode_lines = open('KPOINTS').readlines()

        abs_path = []
        i = 4
        while i < len(linemode_lines):
            start_kpt = linemode_lines[i].split()
            end_kpt = linemode_lines[i+1].split()
            increments = [
                (float(end_kpt[0]) - float(start_kpt[0])) / 20,
                (float(end_kpt[1]) - float(start_kpt[1])) / 20,
                (float(end_kpt[2]) - float(start_kpt[2])) / 20
            ]

            abs_path.append(start_kpt[:3] + ['0', start_kpt[4]])
            for n in range(1, 20):
                abs_path.append(
                    [str(float(start_kpt[0]) + increments[0] * n),
                     str(float(start_kpt[1]) + increments[1] * n),
                     str(float(start_kpt[2]) + increments[2] * n), '0']
                    )
            abs_path.append(end_kpt[:3] + ['0', end_kpt[4]])
            i += 3

        n_linemode_kpts = len(abs_path)

        with open('KPOINTS', 'w') as kpts:
            kpts.write('Automatically generated mesh\n')
            kpts.write('{}\n'.format(n_ibz_kpts + n_linemode_kpts))
            kpts.write('Reciprocal Lattice\n')
            for line in ibz_lines[3:]:
                kpts.write(line)
            for point in abs_path:
                kpts.write('{}\n'.format(' '.join(point)))

        if QUEUE == 'pbs':
            write_pbs_runjob('{}_hsebands'.format(
                os.getcwd().split('/')[-2]), 2, 64, '1800mb', '50:00:00', VASP)
            submission_command = 'qsub runjob'

        elif QUEUE == 'slurm':
            write_slurm_runjob('{}_hsebands'.format(
                os.getcwd().split('/')[-2]), 64, '1800mb', '50:00:00', VASP)
            submission_command = 'sbatch runjob'

        if submit:
            os.system(submission_command)

        os.chdir('../')
Exemple #27
0
    exit(1)

# symmetry information
struct_sym = SpacegroupAnalyzer(struct)
print("\nLattice details:")
print("----------------")
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)
print("ibz type     : {0}".format(ibz.name))
ibz.get_kpath_plot(savefig="path.png")

# print specific kpoints in the first brillouin zone
print("\nList of high symmetry k-points:")
print("-------------------------------")
for key, val in ibz.kpath["kpoints"].items():
    print("%8s %s" % (key, str(val)))

# suggested path for the band structure
print("\nSuggested paths in first brillouin zone:")
print("----------------------------------------")
for i, path in enumerate(ibz.kpath["path"]):
    print("   %2d:" % (i + 1), " -> ".join(path))

# write the KPOINTS file
print("\nWrite file KPOINTS")
Kpoints.automatic_linemode(ndiv, ibz).write_file("KPOINTS")
Exemple #28
0
def drawkpt(struct, ndiv="10"):

    # symmetry information
    struct_sym = SpacegroupAnalyzer(struct)
    print("\nLattice details:")
    print("----------------")
    print("lattice type : {0}".format(struct_sym.get_lattice_type()))
    print(
        "space group  : {0} ({1})".format(
            struct_sym.get_space_group_symbol(),
            struct_sym.get_space_group_number()))

    # Compute first brillouin zone

    ibz = HighSymmKpath(struct)
    print("ibz type     : {0}".format(ibz.name))
    [x, y, z] = list(map(list, zip(*ibz.get_kpoints()[0])))

    fig = plt.figure("Brillouin Zone and High Symm Pts")
    ax = fig.gca(projection='3d')
    ax.plot(x, y, z)

    for i, name in enumerate(ibz.get_kpoints()[1]):
        if name != '':
            #print(" name {0} : [{1},{2},{3}]".format(name, x[i],y[i],z[i]))
            ax.text(x[i], y[i], z[i], '%s' % (name),
                    color='k', size="15")

    new_lat = ibz.prim_rec
    bz_array = new_lat.get_wigner_seitz_cell()
    bz_faces = Poly3DCollection(bz_array)

    bz_faces.set_edgecolor('k')
    bz_faces.set_facecolor((0, 1, 1, 0.4))
    ax.add_collection3d(bz_faces)

    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)
    ax.set_zlim(-1, 1)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')

    fig.suptitle(
        "Brillouin Zone and K_Path of \n {0}".format(
            struct.get_primitive_structure().formula))

    fig.show()

    # if input("press [s]ave to save brillouin zone figure as it is \n") == "s":
    #     fig.savefig("BZ_KPath.svg", bbox_inches='tight')

    # plt.close(fig)

    # print specific kpoints in the first brillouin zone
    print("\nList of high symmetry k-points:")
    print("-------------------------------")
    for key, val in ibz.kpath["kpoints"].items():
        print("%8s %s" % (key, str(val)))

    # suggested path for the band structure
    print("\nSuggested paths in first brillouin zone:")
    print("----------------------------------------")
    for i, path in enumerate(ibz.kpath["path"]):
        print("   %2d:" % (i + 1), " -> ".join(path))

    # write the KPOINTS file
    print("\nWrite file KPOINTS")
    kpt = Kpoints.automatic_linemode(ndiv, ibz)

    # if input("write kpt in cwd ?") == "Y":
    #     kpt.write_file(os.path.join(
    #                    folder, "linear_KPOINTS"))
    return(kpt)
Exemple #29
0
    exit(1)

# symmetry information
struct_sym = SpacegroupAnalyzer(struct)
print("\nLattice details:")
print("----------------")
print("lattice type : {0}".format(struct_sym.get_lattice_type()))
print("space group  : {0} ({1})".format(struct_sym.get_space_group_symbol(),
                                        struct_sym.get_space_group_number()))

# Compute first brillouin zone
ibz = HighSymmKpath(struct)
print("ibz type     : {0}".format(ibz.name))
#ibz.get_kpath_plot(savefig="path.png")

# print specific kpoints in the first brillouin zone
print("\nList of high symmetry k-points:")
print("-------------------------------")
for key, val in ibz.kpath["kpoints"].items():
    print("%8s %s" % (key, str(val)))

# suggested path for the band structure
print("\nSuggested paths in first brillouin zone:")
print("----------------------------------------")
for i, path in enumerate(ibz.kpath["path"]):
    print("   %2d:" % (i + 1), " -> ".join(path))

# write the KPOINTS file
print("\nWrite file KPOINTS")
Kpoints.automatic_linemode(ndiv, ibz).write_file("KPOINTS")
Exemple #30
0
def hs_kpath_gen(working_dir: str = './'):
    structure = Structure.from_file(working_dir+'POSCAR')
    kpath = HighSymmKpath(structure)
    kpts = Kpoints.automatic_linemode(divisions=1, ibz=kpath)
    kpts.write_file(working_dir+'KPOINTS')
Exemple #31
0
    def set_kpoints(self, kpoint=None, poscar=None, ibzkpth=None):
        """
        set the kpoint
        """
        # useful to check if a poscar is supplied from setup_poscar_jobs (most often the case)
        # or this is a single poscar use case
        if not poscar:
            poscar = self.poscar

        # splitting into two if elif branches means fewer if statements to check on
        # a run

        # Most general method of setting the k-points for
        # different grid types
        # NOTE: requires that at least one k-points value be passed
        # as a turn - knobs list value
        # this is not true for values that may be caculated out of
        # a database
        # use this part only if this is a non-database run for example
        # for k-points calibration

        if not self.database:

            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 == '3D_vol':
                self.kpoints = Kpoints.automatic_density_by_vol(structure=poscar.structure,
                                                                kppvol=kpoint)
            elif self.Grid_type == 'bulk_bands_pbe':
                self.kpoints = Kpoints.automatic_linemode(divisions=kpoint,
                                                          ibz=HighSymmKpath(
                                                              poscar.structure))

            elif self.Grid_type == 'D':
                self.kpoints = Kpoints.automatic_density(structure=poscar.structure,kppa=kpoint)

            elif self.Grid_type == 'Finer_G_Mesh':
                # kpoint is the scaling factor and self.kpoints is the old kpoint mesh
                self.logger.info('Setting Finer G Mesh for {0} by scale {1}'.format(kpoint, self.finer_kpoint))
                self.kpoints = Kpoints.gamma_automatic(kpts = \
                   [i * self.finer_kpoint for i in kpoint])
                self.logger.info('Finished scaling operation of k-mesh')

        # applicable for database runs
        # future constructs or settinsg can be activated via a yaml file
        # database yaml file or better still the input deck from its speification
        # decides what combination of input calibrate constructor settings to use
        # one of them being the grid_type tag

        elif self.database == 'twod':

            # set of kpoints settings according to the 2D database profile
            # the actual settings of k-points density
            # will in future come from any database input file set

            if self.Grid_type == 'hse_bands_2D_prep':
                kpoint_dict = Kpoints.automatic_gamma_density(poscar.structure,
                                                              200).as_dict()
                kpoint_dict['kpoints'][0][2] = 1  # remove z kpoints
                self.kpoints = Kpoints.from_dict(kpoint_dict)

            elif self.Grid_type == 'hse_bands_2D':
                # can at most return the path to the correct kpoints file
                # needs kpoints to be written out in instrument in a different way
                # not using the Kpoints object
                self.kpoints = get_2D_hse_kpoints(poscar.structure, ibzkpth)

            elif self.Grid_type == 'bands_2D':
                kpoint_dict = Kpoints.automatic_linemode(divisions=20,
                                                         ibz=HighSymmKpath(poscar.structure)).as_dict()
                self.kpoints = Kpoints.from_dict(kpoint_dict)

            elif self.Grid_type == 'relax_2D':
                # general relaxation settings for 2D
                kpoint_dict = Kpoints.automatic_gamma_density(poscar.structure,
                                                              1000).as_dict()
                kpoint_dict['kpoints'][0][2] = 1
                self.kpoints = Kpoints.from_dict(kpoint_dict)

            elif self.Grid_type == 'relax_3D':
                # general relaxation settings for 3D
                kpoint_dict = Kpoints.automatic_gamma_density(
                    poscar.structure, 1000)
                self.kpoints = Kpoints.from_dict(kpoint_dict)