Example #1
0
    def run_task(self, fw_spec):
        unitcell = Structure.from_file("POSCAR")
        supercell = self.get("supercell", None)
        if supercell is not None:
            os.system('cp POSCAR POSCAR-unitcell')
            unitcell.make_supercell(supercell)

        lepsilon = self.get("lepsilon", False)
        standardize = self.get("standardize", False)
        other_params = self.get("other_params", {})
        user_incar_settings = self.get("user_incar_settings", {})
        finder = SpacegroupAnalyzer(unitcell)
        prims = finder.get_primitive_standard_structure()
        # for lepsilon runs, the kpoints should be denser
        if lepsilon:
            kpoint_set = Generate_kpoints(prims, 0.02)
            struct = prims
        elif standardize:
            kpoint_set = Generate_kpoints(prims, 0.03)
            struct = prims
        else:
            kpoint_set = Generate_kpoints(unitcell, 0.03)
            struct = unitcell

        vis = MPStaticSet(struct,
                          user_incar_settings=user_incar_settings,
                          user_kpoints_settings=kpoint_set,
                          sym_prec=self.get("sym_prec", 0.1),
                          lepsilon=lepsilon,
                          **other_params)
        vis.write_input(".")
Example #2
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)
    # Prepare the vasp working directory
    working_path = os.getcwd()

    vasp_path = os.path.join(working_path, 'vasp_tmp')
    if not os.path.exists(vasp_path):
        os.makedirs(vasp_path)
    else:
        shutil.rmtree(vasp_path)
        os.makedirs(vasp_path)

    staticset = MPStaticSet(struc,
                            force_gamma=True,
                            user_incar_settings={"ICHARG": 2})
    staticset.write_input(vasp_path)
    # chdir to vasp running directory
    os.chdir(vasp_path)
    subprocess.call("mpirun -np 10 vasp5.2-openmpi", shell=True)
Example #3
0
 def write_vasp_files_static(self):
     """
     Writes:
         a folder that includes vasp input file for a single structure
     """
     mpset = MPStaticSet(self.out_struc, reciprocal_density=1, user_incar_settings={'EDIFF': 1e-5, 'ALGO': 'F', 'ISMEAR': 0})
     mpset.write_input(self.wd)
Example #4
0
    def write_vasp_files_disp(self, incar_path):
        try:
            poscar_list = glob(self.wd + '/POSCAR-[0-9][0-9][0-9]')
            print('{} displacement poscar in total'.format(len(poscar_list)))

            for poscar in poscar_list:
                folder = 'disp-' + poscar.split('-')[-1]
                structure = Poscar.from_file(poscar).structure
                mpset = MPStaticSet(
                    structure,
                    user_kpoints_settings={'reciprocal_density': 250},
                    force_gamma=True)
                mpset.write_input(os.path.join(self.wd, folder))
                p = subprocess.Popen(['cp', incar_path, 'INCAR'],
                                     cwd=os.path.join(self.wd, folder))
                p.wait()
        except:
            print('No displacement poscars')
Example #5
0
    def write_vasp_files_dfpt(self, incar_path):
        """
        should run only after tight, proper relaxation

        Write vasp files to a folder named dfpt

        pymatgen inputset may not work very well, so just copy incar from a source
        """
        try:
            relaxed_structure = Poscar.from_file(os.path.join(self.wd, 'relax/CONTCAR')).structure
            supercell = self.generate_structure(relaxed_structure)
            mpset = MPStaticSet(supercell, user_kpoints_settings={'reciprocal_density': 250}, force_gamma=True)
            mpset.write_input(os.path.join(self.wd, self.dfpt_folder))

            p = subprocess.Popen(['cp', incar_path, 'INCAR'], cwd=os.path.join(self.wd, self.dfpt_folder))
            p.wait()

        except:
            print('make sure you have relaxed the structure in tight criteria(ediff 1e-8, ediffg 1e-3')
Example #6
0
        opt = MPRelaxSet(struc, user_incar_settings=myset)
        opt.write_input(opt_dir)
        run_vasp(cmd, opt_dir)
        shutil.rmtree(opt_dir)

        myset = {
            "ISPIN": 1,
            "LAECHG": "False",
            "LVHAR": "False",
            "LWAVE": "True",
            "ISMEAR": 1,
            "LELF": "True"
        }

        static = MPStaticSet(struc, user_incar_settings=myset)
        static.write_input(static_dir)
        run_vasp(cmd, static_dir)
        if os.stat(static_dir + '/CONTCAR').st_size == 0:
            myset = {
                "ISPIN": 1,
                "LAECHG": "False",
                'NELM': 60,
                "LVHAR": "False",
                # "LWAVE": "True",
                "ISMEAR": 1,
                "SYMPREC": 1e-8,
                # "LELF": "True",
            }
            static = MPStaticSet(struc, user_incar_settings=myset)
            static.write_input(static_dir)
            run_vasp(cmd, static_dir)
Example #7
0
def transition(directory,
               functional=("pbe", {}),
               is_metal=False,
               is_migration=False,
               optimize_initial=False):
    """
    Set up the geometry optimizations for a transition for a structure, i.e. using
    ISIF = 2. By default, it is assumed that the initial structure is already
    optimized, unless the user specifically requests its optimization.

    If requested, a charge density calculation will be set up for the
    "host structure", i.e. the structure with vacancies at the initial and
    final locations of the migrating ion. This can be used later to provide an
    estimated path for the nudged elastic band calculations. (WIP)

    Args:
        directory (str): Directory in which the transition calculations should be
            set up.
        functional (tuple): Tuple with the functional choices. The first element
            contains a string that indicates the functional used ("pbe", "hse", ...),
            whereas the second element contains a dictionary that allows the user
            to specify the various functional tags.
        is_metal (bool): Flag that indicates the material being studied is a
            metal, which changes the smearing from Gaussian to second order
            Methfessel-Paxton of 0.2 eV.
        is_migration (bool): Flag that indicates that the transition is a migration
            of an atom in the structure.
        optimize_initial (bool): Flag that indicates that the initial structure
            should also be optimized.

    Returns:
        None

    """
    # Make sure the directory is written as an absolute path
    directory = os.path.abspath(directory)

    # Obtain the initial and final Cathodes
    (initial_cathode, final_cathode) = find_transition_cathodes(directory)

    # Check if a magnetic moment was not provided for the sites
    if "magmom" not in initial_cathode.site_properties.keys():
        # If not, set it to zero for all sites
        initial_cathode.add_site_property("magmom",
                                          [0] * len(initial_cathode.sites))

    if "magmom" not in final_cathode.site_properties.keys():
        # If not, set it to zero for all sites
        final_cathode.add_site_property("magmom",
                                        [0] * len(initial_cathode.sites))

    # Set up the calculations
    user_incar_settings = {"ISIF": 2}

    # Functional
    if functional[0] != "pbe":
        functional_config = _load_yaml_config(functional[0] + "Set")
        functional_config["INCAR"].update(functional[1])
        user_incar_settings.update(functional_config["INCAR"])

    # For metals, add some Methfessel Paxton smearing
    if is_metal:
        user_incar_settings.update({"ISMEAR": 2, "SIGMA": 0.2})

    # If requested, set up the initial structure optimization calculation
    if optimize_initial:
        initial_optimization = BulkRelaxSet(
            structure=initial_cathode.as_ordered_structure(),
            potcar_functional=DFT_FUNCTIONAL,
            user_incar_settings=user_incar_settings)
        initial_optimization.write_input(os.path.join(directory, "initial"))
        initial_cathode.to(
            "json", os.path.join(directory, "initial", "initial_cathode.json"))
    else:
        os.makedirs(os.path.join(directory, "initial"), exist_ok=True)
        initial_cathode.to(
            "json", os.path.join(directory, "initial", "final_cathode.json"))

    # Set up the final structure optimization calculation
    final_optimization = BulkRelaxSet(
        structure=final_cathode.as_ordered_structure(),
        potcar_functional=DFT_FUNCTIONAL,
        user_incar_settings=user_incar_settings)
    final_optimization.write_input(os.path.join(directory, "final"))

    # Write the initial structure of the final Cathode to the optimization
    # directory
    final_cathode.to("json",
                     os.path.join(directory, "final", "initial_cathode.json"))

    # If the transition is a migration of an atom in the structure, set up the
    # calculation for the charge density, used to find a better initial pathway
    if is_migration:
        migration_site_index = find_migrating_ion(initial_cathode,
                                                  final_cathode)

        host_structure = initial_cathode.copy()
        host_structure.remove_sites([migration_site_index])
        host_scf = MPStaticSet(host_structure,
                               potcar_functional=DFT_FUNCTIONAL)
        host_scf.write_input(os.path.join(directory, "host"))
Example #8
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))
Example #9
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s',
                        '--structure',
                        dest='structure',
                        help='POSCAR file of the structure.')
    args = parser.parse_args()

    stru = Structure.from_file(args.structure)
    # Prepare the vasp working directory
    working_path = os.getcwd()

    l_kp = range(20, 100, 10)
    toten = []
    for kp in l_kp:
        vasp_path = os.path.join(working_path, 'vasp_tmp')
        if not os.path.exists(vasp_path):
            os.makedirs(vasp_path)
        else:
            shutil.rmtree(vasp_path)
            os.makedirs(vasp_path)

        staticset = MPStaticSet(
            stru,
            force_gamma=True,
            user_incar_settings={
                "ENCUT": 500,
                "ISPIN": 1,
                "LWAVE": 'FALSE',
                "ICHARG": 2,
                "LREAL": 'FALSE',
                "ISMEAR": 0,
                "EDIFF": 0.001,
                "NPAR": 5
            },
            user_kpoints_settings={"reciprocal_density": kp})
        staticset.config_dict['POTCAR']['Cu'] = 'Cu'
        staticset.config_dict['POTCAR']['Si'] = 'Si'
        staticset.write_input(vasp_path)
        # chdir to vasp running directory
        os.chdir(vasp_path)
        subprocess.call("mpirun -np 10 vasp5.4.1-std", shell=True)

        # find energy total lines and the total energy
        regex = re.compile(
            "energy\s+without\s+entropy\s*=\s*(\S+)\s+energy\(sigma->0\)\s+=\s+(\S+)"
        )

        with open(os.path.join(vasp_path, 'OUTCAR')) as f:
            for line in f:
                found = regex.search(line)
                if found is not None:
                    result = found.group(1)

        toten.append(float(result))
        # print("The energy for ENCUT = {0:4d} is {1:0.6f}\n\n\n".format(ecut, float(result)))

    # print to the stdout
    for kp, energy in zip(l_kp, toten):
        print("The energy for K_Density = {0:4d} is {1:0.6f}".format(
            kp, energy))

    # draw convert line using matplotlib
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.gca()
    ax.plot(l_kp, toten)
    ax.grid()
    ax.set_ylabel('Total Energy (eV)')
    ax.set_xlabel('Reciprocal Density p/A^-3')
    fig.savefig(os.path.join(working_path, 'conv_test_KPOINT.png'))