Exemple #1
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s',
                        '--structure',
                        dest='structure',
                        help='POSCAR file of the structure.')
    args = parser.parse_args()

    struc = Structure.from_file(args.structure)
    working_path = os.getcwd()
    import random
    import string
    rd_suffix = ''.join(
        random.choices(string.ascii_uppercase + string.digits, k=4))
    vasp_path = os.path.join(working_path, 'vasp_tmp_{0:}'.format(rd_suffix))
    if not os.path.exists(vasp_path):
        os.makedirs(vasp_path)
    else:
        shutil.rmtree(vasp_path)
        os.makedirs(vasp_path)

    relaxset = MPRelaxSet(struc,
                          force_gamma=True,
                          user_incar_settings={
                              "ISMEAR": 1,
                              "SIGMA": 0.2
                          })
    relaxset.write_input(vasp_path)
    os.chdir(vasp_path)
    subprocess.call("mpirun -np 10 vasp5.2-openmpi", shell=True)

    contcar = os.path.join(vasp_path, 'CONTCAR')
    dst = os.path.join(working_path, 'POSCAR_optimized')
    shutil.copyfile(contcar, dst)
Exemple #2
0
    def disorder(self,apecies,spacegroup="C2"):
        from pymatgen import Structure, Lattice
        from pymatgen.io.vasp.sets import MPRelaxSet
        import numpy as np
        import os

        cod=[]
        for i in apecies:
            cod.append(np.random.rand(3).tolist())

        # print(cod)


        custom_settings = {"NELMIN": 5}
        specie = apecies
     
        cuau = Structure.from_spacegroup(sg=spacegroup, lattice=Lattice.cubic(10), species=apecies, coords=cod)
        relax = MPRelaxSet(cuau, user_incar_settings=custom_settings)
        os.chdir(self.dire)
        print (os.getcwd())
        gge=[]
        for n in specie:
            for key,value in n.items():

                gge.append(key)
        jji=[]
        for j in gge:
            jji.append(str(j)[:-2])

        str1 = "-".join(jji)
        print (str1)


        relax.write_input(str(str1)) 
def make_atom_mp_relax_set():
    for element, potcar in PotcarSet.mp_relax_set.potcar_dict().items():
        if potcar is None:
            continue

        if is_target_element(element) is False:
            continue

        structure = Structure(Lattice.cubic(10),
                              coords=[[0.5] * 3],
                              species=[element])

        mp_set = MPRelaxSet(structure,
                            user_kpoints_settings=Kpoints(kpts=((1, 1, 1), )),
                            user_incar_settings={
                                "ALGO": "D",
                                "ISIF": 2,
                                "ISMEAR": 0,
                                "MAGMOM": {
                                    "H": 1.0
                                },
                                "NELM": 300
                            })
        Path(element).mkdir()
        mp_set.write_input(element)
Exemple #4
0
 def write_vasp_files(self):
     """
     Writes:
         a folder that includes vasp input file for a single structure, this is for relaxation
     """
     mpset = MPRelaxSet(self.out_struc, user_incar_settings={'EDIFF': 1e-5, 'EDIFFG': 0.001, 'ALGO': 'F', 'ISMEAR': 0, 'ISIF': 2, 'IBRION': 2, 'NSW': 500}, \
         user_kpoints_settings={'reciprocal_density': 1})
     mpset.write_input(self.wd)
Exemple #5
0
    def Phonopy (self,mpid,supcell):
        from pymatgen.io.vasp.outputs import Poscar
        from pymatgen.io.vasp.inputs import Kpoints, Poscar
        from pymatgen.io.vasp.outputs import Potcar
        from pymatgen.io.vasp.sets import MPNMRSet
        from pymatgen.io.phonopy import get_displaced_structures
        from pymatgen.symmetry.bandstructure import HighSymmKpath
        import shutil
        import os
        import subprocess
        from pymatgen import Structure
        from pymatgen.io.vasp.sets import MPRelaxSet
        from pymatgen.ext.matproj import MPRester
        import shutil
        from shutil import copyfile
        import sys

        os.chdir(self.dire)
        print (os.getcwd()) 

        # isExists=os.path.exists(mpid+"isotope")
        # if not isExists:
        #     os.mkdir( mpid+"isotope" )
        #     print ("Directory created")

        # else:
        #     print (' directory already exists')



        # pat = os.path.join(self.dire, mpid+"isotope")
        # diree = os.chdir(pat)
        # print (os.getcwd()) 
        # print ("Directory entered ") 
        

        mpr = MPRester() 
        mp_id = mpid
        structure = mpr.get_structure_by_material_id(mp_id)
        relax = MPRelaxSet(structure)
        relax.write_input(mp_id+"isotope")       
        print ("Input created") 

        pat = os.path.join(self.dire, mpid+"isotope")
        os.chdir(pat)
        print (os.getcwd()) 
        print ("Directory entered ") 
        
                    
        eb=str("phonopy -d --dim="+supcell)

        with open('command.bat', 'w') as file_object:
            file_object.write(eb )
        subprocess.Popen("command.bat")
        for filenames in os.walk(pat):
            print (filenames)
Exemple #6
0
    def write_vasp_files_relax(self, incar_path):
        """
        should relax the structure again in tight criteria before running dfpt calculation

        pymatgen inputset may not work very well, so just copy incar from a source
        """
        mpset = MPRelaxSet(self.struc, user_kpoints_settings={'reciprocal_density': 250}, force_gamma=True)
        mpset.write_input(os.path.join(self.wd, 'relax'))
  
        p = subprocess.Popen(['cp', incar_path, 'INCAR'], cwd=os.path.join(self.wd, 'relax'))
        p.wait()
Exemple #7
0
    def phase_sol(self, EB_K_2, judge='', appendage=""):
        import os
        from pymatgen import Structure
        from pymatgen.io.vasp.sets import MPRelaxSet
        from pymatgen import Structure, Lattice, MPRester, Molecule
        import shutil

        ass = self.cif_route
        print(ass)
        # os.chdir(r"D:\Desktop\VASP practical\Input")
        # print (os.getcwd())

        # Note that you must provide your own API Key, which can
        # be accessed via the Dashboard at materialsproject.org
        #mpr = MPRester()#密钥
        molecule = Molecule.from_file(ass)
        structure = molecule.get_boxed_structure(self.a, self.b, self.c)
        print(structure)

        os.chdir(r"D:\Desktop\VASP practical\Input")
        print(os.getcwd())
        custom_settings = {"NELMIN": 5}  # user custom incar settings
        relax = MPRelaxSet(structure, user_incar_settings=custom_settings)
        os.chdir(r"D:\Desktop\VASP practical\Input")
        print(os.getcwd())
        relax.write_input(ass + '---' + "sol" + str(EB_K_2) + 'phase')
        os.chdir("./" + ass + '---' + "sol" + str(EB_K_2) + 'phase')
        #定义一个更改当前目录的变量
        dire2 = './vaspstd_sub'
        #确立脚本名称
        shutil.copy(r"C:\Users\41958\.spyder-py3\vaspstd_sub", dire2)

        eb = str(EB_K_2)  #将介电常数参数作为字符串
        ls = str('TURE')  #加入开启溶剂参数
        with open('INCAR', 'a') as file_object:
            file_object.write('LSOL = ' + ls + '\n' + 'EB_K = ' + eb)
            #将两个参数写入INCAR
        eb = appendage  #储存WAVECAR

        with open('INCAR', 'r') as f1:
            lines = f1.readlines()

        with open('INCAR', 'w') as f2:
            for line in lines:
                if judge in line:
                    continue
                f2.write(line)

        with open('INCAR', 'a') as f3:
            f3.write(eb)

        os.chdir(r"D:\Desktop\VASP practical\workdir")
        print(os.getcwd())
Exemple #8
0
        def download_structure(file_timestamp, download_option, data):
            if not file_timestamp:
                raise PreventUpdate

            structure = self.from_data(data)
            if isinstance(structure, StructureGraph):
                structure = structure.structure

            file_prefix = structure.composition.reduced_formula

            if "VASP" not in download_option:

                extension = self.download_options["Structure"][
                    download_option]["fmt"]
                options = self.download_options["Structure"][download_option]

                try:
                    contents = structure.to(**options)
                except Exception as exc:
                    # don't fail silently, tell user what went wrong
                    contents = exc

                base64 = b64encode(contents.encode("utf-8")).decode("ascii")

                download_data = {
                    "content": base64,
                    "base64": True,
                    "type": "text/plain",
                    "filename": f"{file_prefix}.{extension}",
                }

            else:

                if "Relax" in download_option:
                    vis = MPRelaxSet(structure)
                    expected_filename = "MPRelaxSet.zip"
                else:
                    raise ValueError(
                        "No other VASP input sets currently supported.")

                with TemporaryDirectory() as tmpdir:
                    vis.write_input(tmpdir, potcar_spec=True, zip_output=True)
                    path = Path(tmpdir) / expected_filename
                    bytes = b64encode(path.read_bytes()).decode("ascii")

                download_data = {
                    "content": bytes,
                    "base64": True,
                    "type": "application/zip",
                    "filename": f"{file_prefix} {expected_filename}",
                }

            return download_data
Exemple #9
0
    def phase(self, judge='', appendage=""):
        import os
        import re
        from pymatgen import Structure
        from pymatgen.io.vasp.sets import MPRelaxSet
        from pymatgen.io.cif import CifParser
        import shutil

        ass = self.cif_route
        print(ass)
        # os.chdir(r"E:\VASP practical\Input")
        # print (os.getcwd())

        # Note that you must provide your own API Key, which can
        # be accessed via the Dashboard at materialsproject.org
        #mpr = MPRester()#密钥
        struct = CifParser(ass)
        structure = struct.get_structures()[0]
        print(structure)

        os.chdir(r"E:\VASP practical\Input")
        print(os.getcwd())
        structure.make_supercell(self.supercell)

        custom_settings = {"NPAR": 4}  # user custom incar settings
        relax = MPRelaxSet(structure, user_incar_settings=custom_settings)
        os.chdir(r"E:\VASP practical\Input")
        print(os.getcwd())
        relax.write_input(ass + '---' + 'phase')
        os.chdir("./" + ass + '---' + 'phase')
        #定义一个更改当前目录的变量
        dire2 = './vaspstd_sub'
        #确立脚本名称
        shutil.copy(r"C:\Users\41958\.spyder-py3\vaspstd_sub", dire2)

        eb = appendage  #储存WAVECAR

        with open('INCAR', 'r') as f1:
            lines = f1.readlines()

        with open('INCAR', 'w') as f2:
            for line in lines:
                if judge in line:
                    continue
                f2.write(line)

        with open('INCAR', 'a') as f3:
            f3.write(eb)

            #将两个参数写入INCAR

        os.chdir(r"D:\Desktop\VASP practical\workdir")
        print(os.getcwd())
Exemple #10
0
    def test_setup(self):
        try:
            vi = MPRelaxSet(self.struct_si, force_gamma=True)
            vi.write_input(".")
        except ValueError:
            import traceback
            traceback.print_exc()

            help_str = "This system is not set up to run VASP jobs. See further error tracebacks " \
                       "for help. Try making sure your PMG_VASP_PSP_DIR has the proper subdirs as " \
                       "outlined in PotcarSingle class of pymatgen, e.g. POT_GGA_PAW_PBE subdir."
            raise ValueError(help_str)

        self._verify_files()
Exemple #11
0
    def test_setup(self):
        try:
            vi = MPRelaxSet(self.struct_si, force_gamma=True)
            vi.write_input(".")
        except ValueError:
            import traceback
            traceback.print_exc()

            help_str = "This system is not set up to run VASP jobs. See further error tracebacks " \
                       "for help. Try making sure your PMG_VASP_PSP_DIR has the proper subdirs as " \
                       "outlined in PotcarSingle class of pymatgen, e.g. POT_GGA_PAW_PBE subdir."
            raise ValueError(help_str)

        self._verify_files()
def make_atom_mp_relax_set():
    for element, potcar in PotcarSet.mp_relax_set.potcar_dict().items():
        if potcar is None:
            continue
        Path(element).mkdir()
        structure = Structure(Lattice.cubic(10),
                              coords=[[0.5] * 3],
                              species=[element])

        mp_set = MPRelaxSet(structure,
                            user_kpoints_settings=Kpoints(kpts=((1, 1, 1), )),
                            user_incar_settings={
                                "ISIF": 2,
                                "ISMEAR": 0,
                                "NUPDOWN": nupdown[element],
                                "NELM": 300
                            })
        mp_set.write_input(element)
Exemple #13
0
    def phase(self, judge='', appendage=""):
        import os
        import re
        os.chdir(r"F:\VASP practical\Input")
        print(os.getcwd())
        from pymatgen import Structure
        from pymatgen.io.vasp.sets import MPRelaxSet
        from pymatgen.ext.matproj import MPRester
        import shutil

        mpr = MPRester()
        mp_id = self.mp_id
        structure = mpr.get_structure_by_material_id(mp_id)
        structure.make_supercell(self.supercell)

        custom_settings = {"NPAR": 4}  # user custom incar settings
        relax = MPRelaxSet(structure, user_incar_settings=custom_settings)
        relax.write_input(mp_id + '---' + 'phase')
        os.chdir("./" + mp_id + '---' + 'phase')
        #定义一个更改当前目录的变量
        dire2 = './vaspstd_sub'
        #确立脚本名称
        shutil.copy(r"C:\Users\41958\.spyder-py3\vaspstd_sub", dire2)

        eb = appendage  #储存WAVECAR

        with open('INCAR', 'r') as f1:
            lines = f1.readlines()

        with open('INCAR', 'w') as f2:
            for line in lines:
                if judge in line:
                    continue
                f2.write(line)

        with open('INCAR', 'a') as f3:
            f3.write(eb)

            #将两个参数写入INCAR

        os.chdir(r"D:\Desktop\VASP practical\workdir")
        print(os.getcwd())
Exemple #14
0
    def phase_sol(self, EB_K_2, judge='', appendage=""):
        import os
        os.chdir(r"F:\VASP practical\Input")
        print(os.getcwd())
        from pymatgen import Structure
        from pymatgen.io.vasp.sets import MPRelaxSet
        from pymatgen.ext.matproj import MPRester
        import shutil

        mpr = MPRester()
        mp_id = self.mp_id
        structure = mpr.get_structure_by_material_id(mp_id)
        custom_settings = {"NPAR": 4}  # user custom incar settings
        relax = MPRelaxSet(structure, user_incar_settings=custom_settings)
        relax.write_input(mp_id + '---' + "sol" + str(EB_K_2) + 'phase')
        os.chdir("./" + mp_id + '---' + "sol" + str(EB_K_2) + 'phase')
        #定义一个更改当前目录的变量
        dire2 = './vaspstd_sub'
        #确立脚本名称
        shutil.copy(r"C:\Users\41958\.spyder-py3\vaspstd_sub", dire2)

        eb = str(EB_K_2)  #将介电常数参数作为字符串
        ls = str('TURE')  #加入开启溶剂参数
        with open('INCAR', 'a') as file_object:
            file_object.write('LSOL = ' + ls + '\n' + 'EB_K = ' + eb)
            #将两个参数写入INCAR
        eb = appendage  #储存WAVECAR

        with open('INCAR', 'r') as f1:
            lines = f1.readlines()

        with open('INCAR', 'w') as f2:
            for line in lines:
                if judge in line:
                    continue
                f2.write(line)

        with open('INCAR', 'a') as f3:
            f3.write(eb)

        os.chdir(r"D:\Desktop\VASP practical\workdir")
        print(os.getcwd())
def Write_MPRelax_vasp_input_set(cif_filename,
                                 where_to_write=".",
                                 sort_structure=True,
                                 **kwargs):
    """
    generate and write down the Vasp Input Set (VIS) for an input structure by pymatgen.io.vasp.sets.MPRelaxSet.
    input arguments:
        - cif_filename (str): path of the cif file.
        - where_to_write (str): the path to write down INCAR, POTCAR, KPOINTS, POSCAR.
        - sort_structure (bool): Sites are sorted by the electronegativity of the species if True,
                                If False, keep the original site order.
                                Default: True
                                Note that if False, the input structure specified by cif_filename should be in the format of 
                                    POSCAR, not cif.
    """
    struct = Structure.from_file(cif_filename).get_sorted_structure()
    vis = MPRelaxSet(struct, **kwargs)
    vis.write_input(where_to_write)

    if sort_structure == False:
        shutil.copyfile(cif_filename, os.path.join(where_to_write, "POSCAR"))
Exemple #16
0
 def write_vasp_files(self):
     for i in self.percent_list:
         ssm = SolidSolutionMaker(self.struc1,
                                  self.struc2,
                                  i,
                                  scaling_list=self.scaling_list)
         e1, e2 = ssm.get_mixing_elements()
         struc, percent = ssm.get_random_supercell()
         if percent == 1.0 or percent == 0.0:
             pass
         else:
             mpset = MPRelaxSet(struc,
                                user_incar_settings={
                                    'EDIFF': 1e-5,
                                    'EDIFFG': -0.01,
                                    'ALGO': 'F',
                                    'ISMEAR': 0
                                })
             mpset.write_input(self.wd + '_' + e1.symbol +
                               '_{0:.3f}'.format(percent) + '_' +
                               e2.symbol + '_{0:.3f}'.format(1 - percent))
Exemple #17
0
    def phase(self):
        import os
        import re
        from pymatgen import Structure
        from pymatgen.io.vasp.sets import MPRelaxSet
        from pymatgen import Structure, Lattice, MPRester, Molecule
        import shutil

        ass = self.cif_route
        print(ass)

        for dirpath, dirnames, filenames in os.walk(self.cif_route):
            # print(dirpath)
            for name in filenames:
                path = os.path.join(self.cif_route, name)

                molecule = Molecule.from_file(path)
                molecule.apply_operation()
                structure = molecule.get_boxed_structure(
                    self.a, self.b, self.c)

                os.chdir(r"E:\VASP practical\Input")
                print(os.getcwd())
                structure.make_supercell(self.supercell)

                custom_settings = {"NELMIN": 5}  # user custom incar settings
                relax = MPRelaxSet(structure,
                                   user_incar_settings=custom_settings)
                os.chdir(r"E:\VASP practical\Input")
                print(os.getcwd())
                relax.write_input(str(name))
                os.chdir("./" + str(name))
                #定义一个更改当前目录的变量
                dire2 = './vaspstd_sub'
                #确立脚本名称
                shutil.copy(r"C:\Users\41958\.spyder-py3\vaspstd_sub", dire2)

                os.chdir(r"D:\Desktop\VASP practical\workdir")
                print(os.getcwd())
Exemple #18
0
    def write_vasp_files(self):
        #clean the folder
        for path in glob(self.wd + '/strain_*'):
            rmtree(path)

        #prepare inputs
        for strain in self.strain_list:
            struc_new = self.sm.iso_strain(strain)
            subfolder = self.wd + '/strain_' + '{0:.3f}'.format(strain)

            if self.copy_input:
                os.mkdir(subfolder)
                print(subfolder)
                copyfile(self.wd + '/KPOINTS', subfolder + '/KPOINTS')
                copyfile(self.wd + '/INCAR', subfolder + '/INCAR')
                copyfile(self.wd + '/POTCAR', subfolder + '/POTCAR')
                Poscar(struc_new).write_file(subfolder + '/POSCAR')

            else:
                mpset = MPRelaxSet(struc_new,  user_incar_settings={'EDIFF': 1e-5, 'EDIFFG': -0.01, 'ALGO': 'N', 'ISMEAR': 0, 'ISIF': 2},\
                user_kpoints_settings={"reciprocal_density": 100}, force_gamma=True)

                mpset.write_input(subfolder)
Exemple #19
0
    def run_task(self, fw_spec):

        # get database connection
        db_file = env_chk(self["db_file"], fw_spec)
        mmdb = VaspCalcDb.from_db_file(db_file, admin=True)
        mmdb.collection = mmdb.db["approx_neb"]

        # get structure from approx_neb collection
        try:
            wf_uuid = self["approx_neb_wf_uuid"]
            structure_path = self.get("structure_path",
                                      fw_spec.get("structure_path"))
            approx_neb_doc = mmdb.collection.find_one({"wf_uuid": wf_uuid})
            structure = Structure.from_dict(get(approx_neb_doc,
                                                structure_path))

        except:
            raise ValueError(
                "Error getting structure from approx_neb collection")

        # get vasp input set and write files
        override_default_vasp_params = self.get(
            "override_default_vasp_params") or {}
        if self["vasp_input_set"] == None or override_default_vasp_params != {}:
            vis = MPRelaxSet(structure,
                             **override_default_vasp_params,
                             sort_structure=False)
            # note sort_structure = False required to retain original site order of structure
        elif hasattr(self["vasp_input_set"], "write_input"):
            vis = self["vasp_input_set"]
        else:
            raise TypeError("ApproxNEB: Error using vasp_input_set")

        potcar_spec = self.get("potcar_spec", False)

        vis.write_input(".", potcar_spec=potcar_spec)
Exemple #20
0
class VaspInputs:

    def __init__(self, mp_id, incar_settings: dict):

        self.mp_id = str(mp_id)

        self.structure = mpr.get_structure_by_material_id(self.mp_id)
        self.primitive_structure = self.structure.get_primitive_structure()

        self.kpath = HighSymmKpath(self.primitive_structure)
        # self.new_kpoints = self.add_kpoints(self.kpath)

        self.add_kpoints(self.kpath)  # Add inverse kpoints intp kpath.__dict__['kpoints ']
        self.relaxed_structure = MPRelaxSet(self.structure,
                                            user_incar_settings=incar_settings)
        self.relaxed_structure.potcar_functional = 'PW91'  # Vasp functional set as potpaw_GGA

    @staticmethod
    def get_incar(working_dir: str, incar_config: dict):
        file_name = working_dir+'INCAR'
        Incar(incar_config).write_file(file_name)

    def get_poscar(self):
        pass

    def get_kpoints(self):
        pass

    def get_potcar_map(self):
        pass

    # def add_kpoints(self, kpath):
    #     # Add inverse of high symmetry kpoints
    #
    #     kpoints_dict = OrderedDict(kpath.__dict__['_kpath']['kpoints'])
    #     new_kpoints_list = []
    #
    #     for k, v in kpoints_dict.items():
    #         new_kpoints_list.append(v)
    #         new_kpoints_list.append(v*(-1))
    #
    #     return new_kpoints_list

    def add_kpoints(self, kpath):
        kpoints_dict = kpath.__dict__['_kpath']['kpoints']
        kpath_list = kpath.__dict__['_kpath']['path']

        print(kpath.__dict__)

        total_kpath = len(kpath_list)

        for i in range(total_kpath):
            tmp_list = []
            for c in kpath_list[i]:
                tmp_list.append(c)

            for c in tmp_list:
                c_inv = c+'_inv'
                kpath_list[i].append(c_inv)
                kpoints_dict[c_inv] = kpoints_dict[c]*(-1)

        print(kpath_list)
        print(kpoints_dict)
        pass

    def write_inputs(self):
        save_dir = 'VaspInputsDir/'+self.mp_id+'/'
        self.relaxed_structure.write_input(save_dir, make_dir_if_not_present=True)  # save_dir: mp_id

    # def write_kpoints(self):
    #     save_dir = 'VaspInputsDir/'+self.mp_id+'/'
    #     file_name = save_dir+'KPOINTS'
    #
    #     if os.path.isfile(file_name):
    #         os.remove(file_name)
    #
    #     with open(file_name, 'w') as f:
    #         print('KPOINTS', file=f)
    #         print(1, file=f)
    #         print('Reciprocal', file=f)
    #         for coord in self.new_kpoints:
    #             for index, i in enumerate(coord):
    #                 if index != 2:
    #                     print(i, file=f, end=' ')
    #                 else:
    #                     print(i, file=f)

    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 #21
0
 def write_vasp_files(self):
     struc = self.generate_structure()
     mpset = MPRelaxSet(struc, user_incar_settings={'GGA': 'PS', 'EDIFF': 1e-5, 'EDIFFG': -0.01, 'ALGO': 'F', 'ISMEAR': 0}, \
               user_kpoints_settings={'reciprocal_density': 100}, force_gamma=True)
     mpset.write_input(self.wd)
Exemple #22
0
    if os.path.exists('static-vasprun.xml') is False:

        myset = {
            "ISPIN": 1,
            "ALGO": 'Normal',
            "PREC": 'Normal',
            "ENCUT": 400,
            "ICHARG": 0,
            "LAECHG": "False",
            'NELM': 60,
            "LVHAR": "False",
            "ISMEAR": 1,
        }

        opt = MPRelaxSet(struc, user_incar_settings=myset)
        opt.write_input(opt_dir)
        run_vasp(cmd, opt_dir)

        if os.stat(opt_dir + '/CONTCAR').st_size == 0:
            myset = {
                "ISPIN": 1,
                "ALGO": 'Normal',
                "PREC": 'Normal',
                "ENCUT": 400,
                "ICHARG": 0,
                "LAECHG": "False",
                'NELM': 60,
                "LVHAR": "False",
                "ISMEAR": 1,
                "SYMPREC": 1e-8,
            }
    relevant_entries = [
        entry for entry in all_entries if entry.composition.reduced_formula ==
        Composition(formula).reduced_formula
    ]
    return relevant_entries


def find_entry_index(formula, all_entries):
    entry_index = [
        all_entries.index(entry) for entry in all_entries
        if entry.composition.reduced_formula == Composition(
            formula).reduced_formula
    ]
    return entry_index


#rester = MPRester('5TxDLF4Iwa7rGcAl') #Generate your own key from materials project..
#mp_entries = rester.get_entries_in_chemsys(["Li", "Fe", "O","S"])

structure = Structure.from_file("LMO.cif")
v = MPRelaxSet(structure)
v.write_input("MyInputFiles")

#or use the following to generate a list of input
# ciflist = ['1.cif', '2.cif', '3.cif']
# structures=[]
# for x in ciflist:
# structures.append(Structure.from_file(x))

# batch_write_input(structures, vasp_input_set=MPRelaxSet, output_dir="vasp_inputs")
Exemple #24
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s',
                        '--structure',
                        dest='structure',
                        help='POSCAR file of the structure.')
    parser.add_argument('-c',
                        '--comment-file-name',
                        dest='comment',
                        help='File name of comment')
    args = parser.parse_args()

    stru = Structure.from_file(args.structure)
    fn = args.structure
    formula = stru.formula
    working_path = os.getcwd()

    # comment file stay in the working path and
    # initiat file with head if not exist
    comment_file = os.path.join(working_path, args.comment)
    if not os.path.isfile(comment_file):
        f = open(comment_file, 'w')
        f.write(
            'POSCAR_FILE, formular, ion_conv, ele_conv, final_energy, out_dir\n'
        )
        f.close()

    import random
    import string
    rd_suffix = ''.join(
        random.choices(string.ascii_uppercase + string.digits, k=6))
    vasp_path = os.path.join(working_path, 'vasp_tmp_{0:}'.format(rd_suffix))
    if not os.path.exists(vasp_path):
        os.makedirs(vasp_path)
    else:
        shutil.rmtree(vasp_path)
        os.makedirs(vasp_path)

    try:
        ###########################################
        # RUNING ION RELAXED
        ###########################################
        vasp_relax_path = os.path.join(vasp_path, 'relax')
        relaxset = MPRelaxSet(stru,
                              force_gamma=True,
                              user_incar_settings={
                                  "ISMEAR": 0,
                                  "SIGMA": 0.2,
                                  "NPAR": 5,
                                  "NSW": 20,
                                  "ISPIN": 1,
                                  "LREAL": ".FALSE.",
                                  "PREC": "NORMAL",
                                  "EDIFF": 0.0001,
                                  "ENCUT": 400,
                                  "ISYM": 0,
                                  "NELM": 60,
                                  "LCHARG": ".FALSE.",
                                  "LAECHG": ".FALSE.",
                                  "ALGO": "ALL"
                              },
                              user_kpoints_settings={"reciprocal_density": 64})
        relaxset.config_dict['POTCAR']['Cu'] = 'Cu'
        relaxset.config_dict['POTCAR']['Si'] = 'Si'
        relaxset.write_input(vasp_relax_path)
        os.chdir(vasp_relax_path)
        subprocess.call("mpirun -np 10 vasp5.4.1-std", shell=True)
        time.sleep(10)

        # Extract the output information
        vasprun_relax = os.path.join(vasp_relax_path, 'vasprun.xml')
        out_relax = Vasprun(vasprun_relax)
        ion_conv = out_relax.converged_ionic
        # if not converged also put energy
        energy = out_relax.final_energy

        ###########################################
        # Done: add all files to compress
        ###########################################
        f_list = os.listdir(vasp_relax_path)
        for f in f_list:
            fname = os.path.join(vasp_relax_path, f)
            with open(fname, 'rb') as f_in:
                with gzip.open("{}{}".format(fname, '.relax.gz'),
                               'wb') as f_out:
                    shutil.copyfileobj(f_in, f_out)
                    os.remove(fname)
    except:
        ion_conv = "ERROR"
        energy = "ERROR"

    try:
        ###########################################
        # CALCULATING THE STATIC ENERGY
        ###########################################
        vasp_static_path = os.path.join(vasp_path, 'static')
        stru_static = out_relax.final_structure

        staticset = MPStaticSet(
            stru_static,
            force_gamma=True,
            user_incar_settings={
                "ICHARG": 2,
                "NPAR": 5,
                "NELM": 40,
                "LREAL": ".FALSE.",
                "ISPIN": 1,
                "EDIFF": 0.0001,
                "ENCUT": 400,
                "ISMEAR": 0,
                "SIGMA": 0.2,
                "LCHARG": ".FALSE.",
                "LAECHG": ".FALSE.",
                "ISYM": 0
            },
            user_kpoints_settings={"reciprocal_density": 64})
        staticset.config_dict['POTCAR']['Cu'] = 'Cu'
        staticset.config_dict['POTCAR']['Si'] = 'Si'
        staticset.write_input(vasp_static_path)
        os.chdir(vasp_static_path)
        subprocess.call("mpirun -np 10 vasp5.4.1-std", shell=True)
        time.sleep(10)

        vasprun_static = os.path.join(vasp_static_path, 'vasprun.xml')
        out_static = Vasprun(vasprun_static)
        elec_conv = out_static.converged_electronic
        energy = out_static.final_energy

        ###########################################
        # Done: add all files to compress
        ###########################################
        f_list = os.listdir(vasp_static_path)
        for f in f_list:
            fname = os.path.join(vasp_static_path, f)
            with open(fname, 'rb') as f_in:
                with gzip.open("{}{}".format(fname, '.static.gz'),
                               'wb') as f_out:
                    shutil.copyfileobj(f_in, f_out)
                    os.remove(fname)
    except:
        elec_conv = "ERROR"
        energy = "ERROR"

    with open(comment_file, 'a') as f:
        f.write("{0:}, {1:}, {2:}, {3:}, {4:}, {5:}\n".format(
            fn, formula, ion_conv, elec_conv, energy, vasp_path))
from pymatgen import Structure
from pymatgen.io.vasp.sets import MPRelaxSet

s = Structure.from_file("ICSD_182730_Si.cif", primitive=True)
custom_settings = {"NELMIN": 5} # user custom incar settings
relax = MPRelaxSet(s, user_incar_settings=custom_settings)
relax.write_input("Si-relax")
Exemple #26
0
 def write_vasp_files(self):
     mpset = MPRelaxSet(self.out_struc, user_incar_settings={'EDIFF': 1e-5, 'EDIFFG': -0.01, 'ALGO': 'F', 'ISMEAR': 0}, \
         user_kpoints_settings={'reciprocal_density': 250})
     mpset.write_input(self.wd)
from pymatgen.ext.matproj import MPRester
from pymatgen.io.vasp.sets import MPRelaxSet, VaspInputSet
import pandas as pd

data = pd.read_csv('new_materials.csv')

mpr = MPRester()

user_incar_settings = {}
hubbard_off = False

i = 0
for mp_id in data['task_id']:
    struct = mpr.get_structure_by_material_id(str(mp_id))
    relaxed = MPRelaxSet(struct)
    relaxed.write_input("/tmp/structs/%s_%s" % (mp_id, data['labels'].iloc[i]),
                        make_dir_if_not_present=True,
                        potcar_spec=True)
    i += 1
Exemple #28
0
from pymatgen import Structure
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.io.vasp.sets import batch_write_input, MPRelaxSet
import os
from pymatgen.io.vasp.inputs import Kpoints

for file in os.listdir():
    if file.endswith(".cif"):
        structure = Structure.from_file(file)
        relax = MPRelaxSet(structure)
        relax.write_input(file.replace('.cif', ''))