Пример #1
0
    def _verify_inputs(self):
        """Validation of input files under user NEB directory."""
        user_incar = Incar.from_file(os.path.join(self.user_dir, "INCAR"))
        ref_incar = Incar.from_file(os.path.join(self.ref_dir_input, "INCAR"))

        # Check INCAR
        params_to_check = self.get("params_to_check", [])
        defaults = {"ICHAIN": 0, "LCLIMB": True}
        for p in params_to_check:
            if user_incar.get(p, defaults.get(p)) != ref_incar.get(p, defaults.get(p)):
                raise ValueError("INCAR value of {} is inconsistent!".format(p))

        # Check KPOINTS
        user_kpoints = Kpoints.from_file(os.path.join(self.user_dir, "KPOINTS"))
        ref_kpoints = Kpoints.from_file(os.path.join(self.ref_dir_input, "KPOINTS"))
        if user_kpoints.style != ref_kpoints.style or user_kpoints.num_kpts != ref_kpoints.num_kpts:
            raise ValueError("KPOINT files are inconsistent! "
                             "Paths are:\n{}\n{} with kpts = {} {}".format(
                self.user_dir, self.ref_dir_input, user_kpoints, ref_kpoints))

        # Check POTCAR
        user_potcar = Potcar.from_file(os.path.join(self.user_dir, "POTCAR"))
        ref_potcar = Potcar.from_file(os.path.join(self.ref_dir_input, "POTCAR"))
        if user_potcar.symbols != ref_potcar.symbols:
            raise ValueError("POTCAR files are inconsistent! "
                             "Paths are:\n{}\n{}".format(self.user_dir, self.ref_dir_input))

        # Check POSCARs
        for u, r in zip(self.user_sdir, self.ref_sdir_input):
            user_poscar = Poscar.from_file(os.path.join(u, "POSCAR"))
            ref_poscar = Poscar.from_file(os.path.join(r, "POSCAR"))
            if user_poscar.natoms != ref_poscar.natoms or \
                            user_poscar.site_symbols != ref_poscar.site_symbols:
                raise ValueError("POSCAR files are inconsistent! Paths are:\n{}\n{}".format(u, r))
Пример #2
0
    def test_setup(self):
        if "VASP_PSP_DIR" not in os.environ:
            os.environ["VASP_PSP_DIR"] = test_dir
        os.chdir(os.path.join(test_dir, 'setup_neb'))

        v = VaspNEBJob("hello", half_kpts=True)
        v.setup()

        incar = Incar.from_file("INCAR")
        count = multiprocessing.cpu_count()
        if count > 1:
            self.assertGreater(incar["NPAR"], 1)

        kpt = Kpoints.from_file("KPOINTS")
        kpt_pre = Kpoints.from_file("KPOINTS.orig")
        self.assertEqual(kpt_pre.style.name, "Monkhorst")
        self.assertEqual(kpt.style.name, "Gamma")

        shutil.copy("KPOINTS.orig", "KPOINTS")
        os.remove("INCAR.orig")
        os.remove("KPOINTS.orig")
        os.remove("POTCAR.orig")
        poscars = glob.glob("[0-9][0-9]/POSCAR.orig")
        for p in poscars:
            os.remove(p)
Пример #3
0
    def test_setup(self):
        if "VASP_PSP_DIR" not in os.environ:
            os.environ["VASP_PSP_DIR"] = test_dir
        os.chdir(os.path.join(test_dir, 'setup_neb'))

        v = VaspNEBJob("hello", half_kpts=True)
        v.setup()

        incar = Incar.from_file("INCAR")
        count = multiprocessing.cpu_count()
        if count > 1:
            self.assertGreater(incar["NPAR"], 1)

        kpt = Kpoints.from_file("KPOINTS")
        kpt_pre = Kpoints.from_file("KPOINTS.orig")
        self.assertEqual(kpt_pre.style.name, "Monkhorst")
        self.assertEqual(kpt.style.name, "Gamma")

        shutil.copy("KPOINTS.orig", "KPOINTS")
        os.remove("INCAR.orig")
        os.remove("KPOINTS.orig")
        os.remove("POTCAR.orig")
        poscars = glob.glob("[0-9][0-9]/POSCAR.orig")
        for p in poscars:
            os.remove(p)
Пример #4
0
    def _verify_inputs(self):
        user_incar = Incar.from_file(os.path.join(os.getcwd(), "INCAR"))
        ref_incar = Incar.from_file(os.path.join(self["ref_dir"], "inputs", "INCAR"))

        # perform some BASIC tests

        # check INCAR
        params_to_check = self.get("params_to_check", [])
        defaults = {"ISPIN": 1, "ISMEAR": 1, "SIGMA": 0.2}
        for p in params_to_check:
            if user_incar.get(p, defaults.get(p)) != ref_incar.get(p, defaults.get(p)):
                raise ValueError("INCAR value of {} is inconsistent!".format(p))

        # check KPOINTS
        user_kpoints = Kpoints.from_file(os.path.join(os.getcwd(), "KPOINTS"))
        ref_kpoints = Kpoints.from_file(os.path.join(self["ref_dir"], "inputs", "KPOINTS"))
        if user_kpoints.style != ref_kpoints.style or user_kpoints.num_kpts != ref_kpoints.num_kpts:
            raise ValueError("KPOINT files are inconsistent! Paths are:\n{}\n{}".format(
                os.getcwd(), os.path.join(self["ref_dir"], "inputs")))

        # check POSCAR
        user_poscar = Poscar.from_file(os.path.join(os.getcwd(), "POSCAR"))
        ref_poscar = Poscar.from_file(os.path.join(self["ref_dir"], "inputs", "POSCAR"))
        if user_poscar.natoms != ref_poscar.natoms or user_poscar.site_symbols != ref_poscar.site_symbols:
            raise ValueError("POSCAR files are inconsistent! Paths are:\n{}\n{}".format(
                os.getcwd(), os.path.join(self["ref_dir"], "inputs")))

        # check POTCAR
        user_potcar = Potcar.from_file(os.path.join(os.getcwd(), "POTCAR"))
        ref_potcar = Potcar.from_file(os.path.join(self["ref_dir"], "inputs", "POTCAR"))
        if user_potcar.symbols != ref_potcar.symbols:
            raise ValueError("POTCAR files are inconsistent! Paths are:\n{}\n{}".format(
                os.getcwd(), os.path.join(self["ref_dir"], "inputs")))
        logger.info("RunVaspFake: verified inputs successfully")
Пример #5
0
    def _verify_inputs(self):
        """Validation of input files under user NEB directory."""
        user_incar = Incar.from_file(os.path.join(self.user_dir, "INCAR"))
        ref_incar = Incar.from_file(os.path.join(self.ref_dir_input, "INCAR"))

        # Check INCAR
        params_to_check = self.get("params_to_check", [])
        defaults = {"ICHAIN": 0, "LCLIMB": True}
        for p in params_to_check:
            if user_incar.get(p, defaults.get(p)) != ref_incar.get(p, defaults.get(p)):
                raise ValueError("INCAR value of {} is inconsistent!".format(p))

        # Check KPOINTS
        user_kpoints = Kpoints.from_file(os.path.join(self.user_dir, "KPOINTS"))
        ref_kpoints = Kpoints.from_file(os.path.join(self.ref_dir_input, "KPOINTS"))
        if user_kpoints.style != ref_kpoints.style or user_kpoints.num_kpts != ref_kpoints.num_kpts:
            raise ValueError("KPOINT files are inconsistent! "
                             "Paths are:\n{}\n{} with kpts = {} {}".format(
                self.user_dir, self.ref_dir_input, user_kpoints, ref_kpoints))

        # Check POTCAR
        user_potcar = Potcar.from_file(os.path.join(self.user_dir, "POTCAR"))
        ref_potcar = Potcar.from_file(os.path.join(self.ref_dir_input, "POTCAR"))
        if user_potcar.symbols != ref_potcar.symbols:
            raise ValueError("POTCAR files are inconsistent! "
                             "Paths are:\n{}\n{}".format(self.user_dir, self.ref_dir_input))

        # Check POSCARs
        for u, r in zip(self.user_sdir, self.ref_sdir_input):
            user_poscar = Poscar.from_file(os.path.join(u, "POSCAR"))
            ref_poscar = Poscar.from_file(os.path.join(r, "POSCAR"))
            if user_poscar.natoms != ref_poscar.natoms or \
                            user_poscar.site_symbols != ref_poscar.site_symbols:
                raise ValueError("POSCAR files are inconsistent! Paths are:\n{}\n{}".format(u, r))
Пример #6
0
    def _verify_inputs(self):
        user_incar = Incar.from_file(os.path.join(os.getcwd(), "INCAR"))

        # Carry out some BASIC tests.

        # Check INCAR
        if self.get("check_incar", True):
            ref_incar = Incar.from_file(
                os.path.join(self["ref_dir"], "inputs", "INCAR"))
            params_to_check = self.get("params_to_check", [])
            defaults = {"ISPIN": 1, "ISMEAR": 1, "SIGMA": 0.2}
            for p in params_to_check:
                if user_incar.get(p, defaults.get(p)) != ref_incar.get(
                        p, defaults.get(p)):
                    raise ValueError(
                        "INCAR value of {} is inconsistent!".format(p))

        # Check KPOINTS
        if self.get("check_kpoints", True):
            user_kpoints = Kpoints.from_file(
                os.path.join(os.getcwd(), "KPOINTS"))
            ref_kpoints = Kpoints.from_file(
                os.path.join(self["ref_dir"], "inputs", "KPOINTS"))
            if user_kpoints.style != ref_kpoints.style or \
                            user_kpoints.num_kpts != ref_kpoints.num_kpts:
                raise ValueError(
                    "KPOINT files are inconsistent! Paths are:\n{}\n{} with kpoints {} and {}"
                    .format(os.getcwd(), os.path.join(self["ref_dir"],
                                                      "inputs"), user_kpoints,
                            ref_kpoints))

        # Check POSCAR
        if self.get("check_poscar", True):
            user_poscar = Poscar.from_file(os.path.join(os.getcwd(), "POSCAR"))
            ref_poscar = Poscar.from_file(
                os.path.join(self["ref_dir"], "inputs", "POSCAR"))
            if user_poscar.natoms != ref_poscar.natoms or user_poscar.site_symbols != \
                    ref_poscar.site_symbols:
                raise ValueError(
                    "POSCAR files are inconsistent! Paths are:\n{}\n{}".format(
                        os.getcwd(), os.path.join(self["ref_dir"], "inputs")))

        # Check POTCAR
        if self.get("check_potcar", True):
            user_potcar = Potcar.from_file(os.path.join(os.getcwd(), "POTCAR"))
            ref_potcar = Potcar.from_file(
                os.path.join(self["ref_dir"], "inputs", "POTCAR"))
            if user_potcar.symbols != ref_potcar.symbols:
                raise ValueError(
                    "POTCAR files are inconsistent! Paths are:\n{}\n{}".format(
                        os.getcwd(), os.path.join(self["ref_dir"], "inputs")))

        logger.info("RunVaspFake: verified inputs successfully")
Пример #7
0
    def test_setup(self):
        with cd(os.path.join(test_dir, 'setup_neb')):
            with ScratchDir('.', copy_from_current_on_enter=True) as d:
                v = VaspNEBJob("hello", half_kpts=True)
                v.setup()

                incar = Incar.from_file("INCAR")
                count = multiprocessing.cpu_count()
                if count > 3:
                    self.assertGreater(incar["NPAR"], 1)

                kpt = Kpoints.from_file("KPOINTS")
                kpt_pre = Kpoints.from_file("KPOINTS.orig")
                self.assertEqual(kpt_pre.style.name, "Monkhorst")
                self.assertEqual(kpt.style.name, "Gamma")
Пример #8
0
    def test_setup(self):
        with cd(os.path.join(test_dir, 'setup_neb')):
            with ScratchDir('.', copy_from_current_on_enter=True) as d:
                v = VaspNEBJob("hello", half_kpts=True)
                v.setup()

                incar = Incar.from_file("INCAR")
                count = multiprocessing.cpu_count()
                if count > 3:
                    self.assertGreater(incar["NPAR"], 1)

                kpt = Kpoints.from_file("KPOINTS")
                kpt_pre = Kpoints.from_file("KPOINTS.orig")
                self.assertEqual(kpt_pre.style.name, "Monkhorst")
                self.assertEqual(kpt.style.name, "Gamma")
Пример #9
0
    def setUpClass(cls):
        if not os.environ.get("VASP_PSP_DIR"):
            os.environ["VASP_PSP_DIR"] = os.path.join(module_dir,
                                                      "reference_files")
            print(
                'Note: This system is not set up to run VASP jobs. '
                'Please set your VASP_PSP_DIR environment variable.')

        cls.struct_si = PymatgenTest.get_structure("Si")

        cls.ref_incar = Incar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test", "INCAR"))
        cls.ref_poscar = Poscar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "POSCAR"))
        cls.ref_potcar = Potcar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "POTCAR"))
        cls.ref_kpoints = Kpoints.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "KPOINTS"))
        cls.ref_incar_preserve = Incar.from_file(os.path.join(module_dir,
                                                              "reference_files",
                                                              "preserve_incar",
                                                              "INCAR"))
Пример #10
0
 def run_task(self, fw_spec):
     from pymatgen.io.vasp import Kpoints
     modify_kpoints_params = self.get('modify_kpoints_params')
     kpoint = Kpoints.from_file('KPOINTS')
     if 'kpts' in modify_kpoints_params.keys():
         kpoint.kpts = modify_kpoints_params['kpts']
     kpoint.write_file('KPOINTS')
Пример #11
0
    def setup(self):
        """
        Performs initial setup for VaspNEBJob, including overriding any settings
        and backing up.
        """
        neb_dirs = self.neb_dirs

        if self.backup:
            # Back up KPOINTS, INCAR, POTCAR
            for f in VASP_NEB_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))
            # Back up POSCARs
            for path in neb_dirs:
                poscar = os.path.join(path, "POSCAR")
                shutil.copy(poscar, "{}.orig".format(poscar))

        if self.half_kpts and os.path.exists("KPOINTS"):
            kpts = Kpoints.from_file("KPOINTS")
            kpts.kpts = np.maximum(np.array(kpts.kpts) / 2, 1)
            kpts.kpts = kpts.kpts.astype(int).tolist()
            if tuple(kpts.kpts[0]) == (1, 1, 1):
                kpt_dic = kpts.as_dict()
                kpt_dic["generation_style"] = 'Gamma'
                kpts = Kpoints.from_dict(kpt_dic)
            kpts.write_file("KPOINTS")

        if self.auto_npar:
            try:
                incar = Incar.from_file("INCAR")
                import multiprocessing
                # Try sge environment variable first
                # (since multiprocessing counts cores on the current
                # machine only)
                ncores = os.environ.get(
                    'NSLOTS') or multiprocessing.cpu_count()
                ncores = int(ncores)
                for npar in range(int(math.sqrt(ncores)), ncores):
                    if ncores % npar == 0:
                        incar["NPAR"] = npar
                        break
                incar.write_file("INCAR")
            except:
                pass

        if self.auto_continue and \
                os.path.exists("STOPCAR") and \
                not os.access("STOPCAR", os.W_OK):
            # Remove STOPCAR
            os.chmod("STOPCAR", 0o644)
            os.remove("STOPCAR")

            # Copy CONTCAR to POSCAR
            for path in self.neb_sub:
                contcar = os.path.join(path, "CONTCAR")
                poscar = os.path.join(path, "POSCAR")
                shutil.copy(contcar, poscar)

            if self.settings_override is not None:
                VaspModder().apply_actions(self.settings_override)
Пример #12
0
    def setup(self):
        """
        Performs initial setup for VaspNEBJob, including overriding any settings
        and backing up.
        """
        neb_dirs = self.neb_dirs

        if self.backup:
            # Back up KPOINTS, INCAR, POTCAR
            for f in VASP_NEB_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))
            # Back up POSCARs
            for path in neb_dirs:
                poscar = os.path.join(path, "POSCAR")
                shutil.copy(poscar, "{}.orig".format(poscar))

        if self.half_kpts and os.path.exists("KPOINTS"):
            kpts = Kpoints.from_file("KPOINTS")
            kpts.kpts = np.maximum(np.array(kpts.kpts) / 2, 1)
            kpts.kpts = kpts.kpts.astype(int).tolist()
            if tuple(kpts.kpts[0]) == (1, 1, 1):
                kpt_dic = kpts.as_dict()
                kpt_dic["generation_style"] = 'Gamma'
                kpts = Kpoints.from_dict(kpt_dic)
            kpts.write_file("KPOINTS")

        if self.auto_npar:
            try:
                incar = Incar.from_file("INCAR")
                import multiprocessing
                # Try sge environment variable first
                # (since multiprocessing counts cores on the current
                # machine only)
                ncores = os.environ.get('NSLOTS') or multiprocessing.cpu_count()
                ncores = int(ncores)
                for npar in range(int(math.sqrt(ncores)),
                                  ncores):
                    if ncores % npar == 0:
                        incar["NPAR"] = npar
                        break
                incar.write_file("INCAR")
            except:
                pass

        if self.auto_continue and \
                os.path.exists("STOPCAR") and \
                not os.access("STOPCAR", os.W_OK):
            # Remove STOPCAR
            os.chmod("STOPCAR", 0o644)
            os.remove("STOPCAR")

            # Copy CONTCAR to POSCAR
            for path in self.neb_sub:
                contcar = os.path.join(path, "CONTCAR")
                poscar = os.path.join(path, "POSCAR")
                shutil.copy(contcar, poscar)

        if self.settings_override is not None:
            VaspModder().apply_actions(self.settings_override)
Пример #13
0
 def _verify_files(self):
     self.assertEqual(Incar.from_file(os.path.join(module_dir, "INCAR")), self.ref_incar)
     self.assertEqual(str(Poscar.from_file(os.path.join(module_dir, "POSCAR"))),
                      str(self.ref_poscar))
     self.assertEqual(Potcar.from_file(os.path.join(module_dir, "POTCAR")).symbols,
                      self.ref_potcar.symbols)
     self.assertEqual(str(Kpoints.from_file(os.path.join(module_dir, "KPOINTS"))),
                      str(self.ref_kpoints))
Пример #14
0
    def setUpClass(cls):
        cls.struct_si = PymatgenTest.get_structure("Si")

        cls.ref_incar = Incar.from_file(p_setup_test / "INCAR")
        cls.ref_poscar = Poscar.from_file(p_setup_test / "POSCAR")
        cls.ref_potcar = Potcar.from_file(p_setup_test / "POTCAR")
        cls.ref_kpoints = Kpoints.from_file(p_setup_test / "KPOINTS")
        cls.ref_incar_preserve = Incar.from_file(p_preserve_incar / "INCAR")
Пример #15
0
 def _verify_files(self, skip_kpoints=False, preserve_incar=False):
     if not preserve_incar:
         self.assertEqual(Incar.from_file(os.path.join(module_dir, "INCAR")), self.ref_incar)
         self.assertEqual(str(Poscar.from_file(os.path.join(module_dir, "POSCAR"))), str(self.ref_poscar))
         self.assertEqual((Potcar.from_file(os.path.join(module_dir, "POTCAR"))).symbols, self.ref_potcar.symbols)
         if not skip_kpoints:
             self.assertEqual(str(Kpoints.from_file(os.path.join(module_dir, "KPOINTS"))), str(self.ref_kpoints))
     else:
         self.assertEqual(Incar.from_file(os.path.join(module_dir, "INCAR")), self.ref_incar_preserve)
Пример #16
0
    def double_relaxation_run(cls, vasp_cmd, auto_npar=True, ediffg=-0.05,
                              half_kpts_first_relax=False, auto_continue=False):
        """
        Returns a list of two jobs corresponding to an AFLOW style double
        relaxation run.

        Args:
            vasp_cmd (str): Command to run vasp as a list of args. For example,
                if you are using mpirun, it can be something like
                ["mpirun", "pvasp.5.2.11"]
            auto_npar (bool): Whether to automatically tune NPAR to be sqrt(
                number of cores) as recommended by VASP for DFT calculations.
                Generally, this results in significant speedups. Defaults to
                True. Set to False for HF, GW and RPA calculations.
            ediffg (float): Force convergence criteria for subsequent runs (
                ignored for the initial run.)
            half_kpts_first_relax (bool): Whether to halve the kpoint grid
                for the first relaxation. Speeds up difficult convergence
                considerably. Defaults to False.

        Returns:
            List of two jobs corresponding to an AFLOW style run.
        """
        incar_update = {"ISTART": 1}
        if ediffg:
            incar_update["EDIFFG"] = ediffg
        settings_overide_1 = None
        settings_overide_2 = [
            {"dict": "INCAR",
             "action": {"_set": incar_update}},
            {"file": "CONTCAR",
             "action": {"_file_copy": {"dest": "POSCAR"}}}]
        if half_kpts_first_relax and os.path.exists("KPOINTS") and \
                os.path.exists("POSCAR"):
            kpts = Kpoints.from_file("KPOINTS")
            orig_kpts_dict = kpts.as_dict()
            # lattice vectors with length < 8 will get >1 KPOINT
            kpts.kpts = np.round(np.maximum(np.array(kpts.kpts) / 2,
                                            1)).astype(int).tolist()
            low_kpts_dict = kpts.as_dict()
            settings_overide_1 = [
                {"dict": "KPOINTS",
                 "action": {"_set": low_kpts_dict}}
            ]
            settings_overide_2.append(
                {"dict": "KPOINTS",
                 "action": {"_set": orig_kpts_dict}}
            )

        return [VaspJob(vasp_cmd, final=False, suffix=".relax1",
                        auto_npar=auto_npar, auto_continue=auto_continue,
                        settings_override=settings_overide_1),
                VaspJob(vasp_cmd, final=True, backup=False, suffix=".relax2",
                        auto_npar=auto_npar, auto_continue=auto_continue,
                        settings_override=settings_overide_2)]
Пример #17
0
    def double_relaxation_run(cls, vasp_cmd, auto_npar=True, ediffg=-0.05,
                              half_kpts_first_relax=False, auto_continue=False):
        """
        Returns a list of two jobs corresponding to an AFLOW style double
        relaxation run.

        Args:
            vasp_cmd (str): Command to run vasp as a list of args. For example,
                if you are using mpirun, it can be something like
                ["mpirun", "pvasp.5.2.11"]
            auto_npar (bool): Whether to automatically tune NPAR to be sqrt(
                number of cores) as recommended by VASP for DFT calculations.
                Generally, this results in significant speedups. Defaults to
                True. Set to False for HF, GW and RPA calculations.
            ediffg (float): Force convergence criteria for subsequent runs (
                ignored for the initial run.)
            half_kpts_first_relax (bool): Whether to halve the kpoint grid
                for the first relaxation. Speeds up difficult convergence
                considerably. Defaults to False.

        Returns:
            List of two jobs corresponding to an AFLOW style run.
        """
        incar_update = {"ISTART": 1}
        if ediffg:
            incar_update["EDIFFG"] = ediffg
        settings_overide_1 = None
        settings_overide_2 = [
            {"dict": "INCAR",
             "action": {"_set": incar_update}},
            {"file": "CONTCAR",
             "action": {"_file_copy": {"dest": "POSCAR"}}}]
        if half_kpts_first_relax and os.path.exists("KPOINTS") and \
                os.path.exists("POSCAR"):
            kpts = Kpoints.from_file("KPOINTS")
            orig_kpts_dict = kpts.as_dict()
            # lattice vectors with length < 8 will get >1 KPOINT
            kpts.kpts = np.round(np.maximum(np.array(kpts.kpts) / 2,
                                            1)).astype(int).tolist()
            low_kpts_dict = kpts.as_dict()
            settings_overide_1 = [
                {"dict": "KPOINTS",
                 "action": {"_set": low_kpts_dict}}
            ]
            settings_overide_2.append(
                {"dict": "KPOINTS",
                 "action": {"_set": orig_kpts_dict}}
            )

        return [VaspJob(vasp_cmd, final=False, suffix=".relax1",
                        auto_npar=auto_npar, auto_continue=auto_continue,
                        settings_override=settings_overide_1),
                VaspJob(vasp_cmd, final=True, backup=False, suffix=".relax2",
                        auto_npar=auto_npar, auto_continue=auto_continue,
                        settings_override=settings_overide_2)]
Пример #18
0
 def _verify_files(self):
     self.assertEqual(Incar.from_file(os.path.join(module_dir, "INCAR")),
                      self.ref_incar)
     self.assertEqual(
         str(Poscar.from_file(os.path.join(module_dir, "POSCAR"))),
         str(self.ref_poscar))
     self.assertEqual(
         Potcar.from_file(os.path.join(module_dir, "POTCAR")).symbols,
         self.ref_potcar.symbols)
     self.assertEqual(
         str(Kpoints.from_file(os.path.join(module_dir, "KPOINTS"))),
         str(self.ref_kpoints))
Пример #19
0
    def run_task(self, fw_spec):

        kpoints_name = self.get("input_filename", "KPOINTS")
        kpoints = Kpoints.from_file(kpoints_name)

        kpoints_update = env_chk(self.get("kpoints_update"), fw_spec)

        if kpoints_update:
            for key, value in kpoints_update.items():
                setattr(kpoints, key, value)

        kpoints.write_file(self.get("output_filename", "KPOINTS"))
Пример #20
0
    def test_modify_kpoints(self):
        # create an KPOINTS
        kpoints = self.ref_kpoints
        kpoints.write_file("KPOINTS")

        # modify and test
        ft = ModifyKpoints(kpoints_update={"kpts": [[3, 4, 5]]}, )
        ft = load_object(ft.to_dict())  # simulate database insertion
        ft.run_task({})

        kpoints_mod = Kpoints.from_file("KPOINTS")
        self.assertEqual(kpoints_mod.kpts, [[3, 4, 5]])
Пример #21
0
 def _verify_files(self, skip_kpoints=False, preserve_incar=False):
     if not preserve_incar:
         self.assertEqual(Incar.from_file("INCAR"), self.ref_incar)
         self.assertEqual(str(Poscar.from_file("POSCAR")), str(self.ref_poscar))
         self.assertEqual(Potcar.from_file("POTCAR").symbols,
                          self.ref_potcar.symbols)
         if not skip_kpoints:
             self.assertEqual(str(Kpoints.from_file("KPOINTS")),
                              str(self.ref_kpoints))
     else:
         self.assertEqual(Incar.from_file("INCAR"),
                          self.ref_incar_preserve)
Пример #22
0
 def test_run(self):
     with ScratchDir(".") as d:
         for f in ["INCAR", "POSCAR", "POTCAR", "KPOINTS"]:
             shutil.copy(os.path.join('..', test_dir, f), f)
         oldincar = Incar.from_file("INCAR")
         v = GenerateVaspInputJob("pymatgen.io.vasp.sets.MPNonSCFSet",
                                  contcar_only=False)
         v.run()
         incar = Incar.from_file("INCAR")
         self.assertEqual(incar["ICHARG"], 11)
         self.assertEqual(oldincar["ICHARG"], 1)
         kpoints = Kpoints.from_file("KPOINTS")
         self.assertEqual(str(kpoints.style), "Reciprocal")
Пример #23
0
 def test_run(self):
     with ScratchDir(".") as d:
         for f in ["INCAR", "POSCAR", "POTCAR", "KPOINTS"]:
             shutil.copy(os.path.join(test_dir, f), f)
         oldincar = Incar.from_file("INCAR")
         v = GenerateVaspInputJob("pymatgen.io.vasp.sets.MPNonSCFSet",
                                  contcar_only=False)
         v.run()
         incar = Incar.from_file("INCAR")
         self.assertEqual(incar["ICHARG"], 11)
         self.assertEqual(oldincar["ICHARG"], 1)
         kpoints = Kpoints.from_file("KPOINTS")
         self.assertEqual(str(kpoints.style), "Reciprocal")
Пример #24
0
    def setUpClass(cls):
        if not SETTINGS.get("VASP_PSP_DIR"):
            SETTINGS["VASP_PSP_DIR"] = os.path.join(module_dir, "reference_files")
            print(
                "This system is not set up to run VASP jobs. "
                "Please set VASP_PSP_DIR variable in your ~/.pmgrc.yaml file."
            )

        cls.struct_si = PymatgenTest.get_structure("Si")

        cls.ref_incar = Incar.from_file(os.path.join(module_dir, "reference_files", "setup_test", "INCAR"))
        cls.ref_poscar = Poscar.from_file(os.path.join(module_dir, "reference_files", "setup_test", "POSCAR"))
        cls.ref_potcar = Potcar.from_file(os.path.join(module_dir, "reference_files", "setup_test", "POTCAR"))
        cls.ref_kpoints = Kpoints.from_file(os.path.join(module_dir, "reference_files", "setup_test", "KPOINTS"))
        cls.ref_incar_preserve = Incar.from_file(os.path.join(module_dir, "reference_files", "preserve_incar", "INCAR"))
Пример #25
0
    def setUpClass(cls):
        coords = [[0, 0, 0], [0.75, 0.5, 0.75]]
        lattice = Lattice([[3.8401979337, 0.00, 0.00],
                           [1.9200989668, 3.3257101909, 0.00],
                           [0.00, -2.2171384943, 3.1355090603]])
        cls.struct_si = IStructure(lattice, ["Si"] * 2, coords)

        cls.ref_incar = Incar.from_file(
            os.path.join(module_dir, "..", "test_files", "setup_test", "INCAR"))
        cls.ref_poscar = Poscar.from_file(
            os.path.join(module_dir, "..", "test_files", "setup_test", "POSCAR"))
        cls.ref_potcar = Potcar.from_file(
            os.path.join(module_dir, "..", "test_files", "setup_test", "POTCAR"))
        cls.ref_kpoints = Kpoints.from_file(
            os.path.join(module_dir, "..", "test_files", "setup_test", "KPOINTS"))
Пример #26
0
    def setUpClass(cls):
        cls.struct_si = PymatgenTest.get_structure("Si")

        cls.ref_incar = Incar.from_file(
            os.path.join(module_dir, "..", "..", "test_files", "setup_test", "INCAR"))
        cls.ref_poscar = Poscar.from_file(
            os.path.join(module_dir, "..", "..", "test_files", "setup_test",
                         "POSCAR"))
        cls.ref_potcar = Potcar.from_file(
            os.path.join(module_dir, "..", "..", "test_files", "setup_test",
                         "POTCAR"))
        cls.ref_kpoints = Kpoints.from_file(
            os.path.join(module_dir, "..", "..", "test_files", "setup_test",
                         "KPOINTS"))
        cls.ref_incar_preserve = Incar.from_file(os.path.join(module_dir,
                                                              "..", "..", "test_files",
                                                              "preserve_incar", "INCAR"))
Пример #27
0
    def setUpClass(cls):
        cls.struct_si = PymatgenTest.get_structure("Si")

        cls.ref_incar = Incar.from_file(
            os.path.join(module_dir, "..", "..", "test_files", "setup_test", "INCAR"))
        cls.ref_poscar = Poscar.from_file(
            os.path.join(module_dir, "..", "..", "test_files", "setup_test",
                         "POSCAR"))
        cls.ref_potcar = Potcar.from_file(
            os.path.join(module_dir, "..", "..", "test_files", "setup_test",
                         "POTCAR"))
        cls.ref_kpoints = Kpoints.from_file(
            os.path.join(module_dir, "..", "..", "test_files", "setup_test",
                         "KPOINTS"))
        cls.ref_incar_preserve = Incar.from_file(os.path.join(module_dir,
                                                              "..", "..", "test_files",
                                                              "preserve_incar", "INCAR"))
Пример #28
0
    def setUpClass(cls):
        if not SETTINGS.get("VASP_PSP_DIR"):
            raise unittest.SkipTest(
                "This system is not set up to run VASP jobs. "
                "Please set VASP_PSP_DIR variable in your ~/.pmgrc.yaml file."
            )

        coords = [[0, 0, 0], [0.75, 0.5, 0.75]]
        lattice = Lattice(
            [[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]
        )
        cls.struct_si = IStructure(lattice, ["Si"] * 2, coords)

        cls.ref_incar = Incar.from_file(os.path.join(module_dir, "reference_files", "setup_test", "INCAR"))
        cls.ref_poscar = Poscar.from_file(os.path.join(module_dir, "reference_files", "setup_test", "POSCAR"))
        cls.ref_potcar = Potcar.from_file(os.path.join(module_dir, "reference_files", "setup_test", "POTCAR"))
        cls.ref_kpoints = Kpoints.from_file(os.path.join(module_dir, "reference_files", "setup_test", "KPOINTS"))
Пример #29
0
def _check_kpoints(testCase, idx) :
    fp_path = os.path.join('iter.%06d' % idx, '02.fp')
    tasks = glob.glob(os.path.join(fp_path, 'task.*'))
    for ii in tasks :
        kpoints=Kpoints.from_file(os.path.join(os.path.join(ii, 'KPOINTS')))
        incar=Incar.from_file(os.path.join(os.path.join(ii, 'INCAR')))
        kspacing = incar['KSPACING']
        gamma = incar['KGAMMA']
        if isinstance(gamma,bool):
           pass
        else:
           if gamma[0].upper()=="T":
              gamma=True
           else:
              gamma=False
        ret=make_kspacing_kpoints(os.path.join(os.path.join(ii, 'POSCAR')), kspacing, gamma)
        kpoints_ref=Kpoints.from_string(ret)
        testCase.assertEqual(repr(kpoints), repr(kpoints_ref))
Пример #30
0
    def setUpClass(cls):
        coords = [[0, 0, 0], [0.75, 0.5, 0.75]]
        lattice = Lattice([[3.8401979337, 0.00, 0.00],
                           [1.9200989668, 3.3257101909, 0.00],
                           [0.00, -2.2171384943, 3.1355090603]])
        cls.struct_si = IStructure(lattice, ["Si"] * 2, coords)

        cls.ref_incar = Incar.from_file(
            os.path.join(module_dir, "..", "test_files", "setup_test",
                         "INCAR"))
        cls.ref_poscar = Poscar.from_file(
            os.path.join(module_dir, "..", "test_files", "setup_test",
                         "POSCAR"))
        cls.ref_potcar = Potcar.from_file(
            os.path.join(module_dir, "..", "test_files", "setup_test",
                         "POTCAR"))
        cls.ref_kpoints = Kpoints.from_file(
            os.path.join(module_dir, "..", "test_files", "setup_test",
                         "KPOINTS"))
Пример #31
0
    def _verify_files(self,
                      skip_kpoints=False,
                      preserve_incar=False,
                      potcar_spec=False):
        if not preserve_incar:
            self.assertEqual(Incar.from_file("INCAR"), self.ref_incar)

            poscar = Poscar.from_file("POSCAR")
            self.assertEqual(str(poscar), str(self.ref_poscar))

            if potcar_spec:
                symbols = Path("POTCAR.spec").read_text().split()
                self.assertEqual(symbols, self.ref_potcar.symbols)
            else:
                potcar = Potcar.from_file("POTCAR")
                self.assertEqual(potcar.symbols, self.ref_potcar.symbols)

            if not skip_kpoints:
                kpoints = Kpoints.from_file("KPOINTS")
                self.assertEqual(str(kpoints), str(self.ref_kpoints))
        else:
            self.assertEqual(Incar.from_file("INCAR"), self.ref_incar_preserve)
Пример #32
0
    def setUpClass(cls):
        if not SETTINGS.get("VASP_PSP_DIR"):
            raise unittest.SkipTest(
                'This system is not set up to run VASP jobs. '
                'Please set VASP_PSP_DIR variable in your ~/.pmgrc.yaml file.')

        coords = [[0, 0, 0], [0.75, 0.5, 0.75]]
        lattice = Lattice([[3.8401979337, 0.00, 0.00],
                           [1.9200989668, 3.3257101909, 0.00],
                           [0.00, -2.2171384943, 3.1355090603]])
        cls.struct_si = IStructure(lattice, ["Si"] * 2, coords)

        cls.ref_incar = Incar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test", "INCAR"))
        cls.ref_poscar = Poscar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "POSCAR"))
        cls.ref_potcar = Potcar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "POTCAR"))
        cls.ref_kpoints = Kpoints.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "KPOINTS"))
Пример #33
0
    def setUpClass(cls):
        if not SETTINGS.get("VASP_PSP_DIR"):
            SETTINGS["VASP_PSP_DIR"] = os.path.join(module_dir,
                                                    "reference_files")
            print(
                'This system is not set up to run VASP jobs. '
                'Please set VASP_PSP_DIR variable in your ~/.pmgrc.yaml file.')

        cls.struct_si = PymatgenTest.get_structure("Si")

        cls.ref_incar = Incar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test", "INCAR"))
        cls.ref_poscar = Poscar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "POSCAR"))
        cls.ref_potcar = Potcar.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "POTCAR"))
        cls.ref_kpoints = Kpoints.from_file(
            os.path.join(module_dir, "reference_files", "setup_test",
                         "KPOINTS"))
        cls.ref_incar_preserve = Incar.from_file(
            os.path.join(module_dir, "reference_files", "preserve_incar",
                         "INCAR"))
Пример #34
0
    def run(self):
        """
        Perform the actual VASP run.

        Returns:
            (subprocess.Popen) Used for monitoring.
        """
        cmd = list(self.vasp_cmd)
        if self.auto_gamma:
            kpts = Kpoints.from_file("KPOINTS")
            if kpts.style == Kpoints.supported_modes.Gamma \
                    and tuple(kpts.kpts[0]) == (1, 1, 1):
                if self.gamma_vasp_cmd is not None and which(
                        self.gamma_vasp_cmd[-1]):
                    cmd = self.gamma_vasp_cmd
                elif which(cmd[-1] + ".gamma"):
                    cmd[-1] += ".gamma"
        logger.info("Running {}".format(" ".join(cmd)))
        with open(self.output_file, 'w') as f_std, \
                open(self.stderr_file, "w", buffering=1) as f_err:

            # Use line buffering for stderr
            p = subprocess.Popen(cmd, stdout=f_std, stderr=f_err)
        return p
Пример #35
0
    def run(self):
        """
        Perform the actual VASP run.

        Returns:
            (subprocess.Popen) Used for monitoring.
        """
        cmd = list(self.vasp_cmd)
        if self.auto_gamma:
            kpts = Kpoints.from_file("KPOINTS")
            if kpts.style == Kpoints.supported_modes.Gamma \
                    and tuple(kpts.kpts[0]) == (1, 1, 1):
                if self.gamma_vasp_cmd is not None and which(
                        self.gamma_vasp_cmd[-1]):
                    cmd = self.gamma_vasp_cmd
                elif which(cmd[-1] + ".gamma"):
                    cmd[-1] += ".gamma"
        logger.info("Running {}".format(" ".join(cmd)))
        with open(self.output_file, 'w') as f_std, \
                open(self.stderr_file, "w", buffering=1) as f_err:

            # Use line buffering for stderr
            p = subprocess.Popen(cmd, stdout=f_std, stderr=f_err)
        return p
Пример #36
0
    def full_opt_run(cls,
                     vasp_cmd,
                     auto_npar=True,
                     vol_change_tol=0.02,
                     max_steps=10,
                     ediffg=-0.05,
                     half_kpts_first_relax=False):
        """
        Returns a generator of jobs for a full optimization run. Basically,
        this runs an infinite series of geometry optimization jobs until the
        % vol change in a particular optimization is less than vol_change_tol.

        Args:
            vasp_cmd (str): Command to run vasp as a list of args. For example,
                if you are using mpirun, it can be something like
                ["mpirun", "pvasp.5.2.11"]
            auto_npar (bool): Whether to automatically tune NPAR to be sqrt(
                number of cores) as recommended by VASP for DFT calculations.
                Generally, this results in significant speedups. Defaults to
                True. Set to False for HF, GW and RPA calculations.
            vol_change_tol (float): The tolerance at which to stop a run.
                Defaults to 0.05, i.e., 5%.
            max_steps (int): The maximum number of runs. Defaults to 10 (
                highly unlikely that this limit is ever reached).
            ediffg (float): Force convergence criteria for subsequent runs (
                ignored for the initial run.)
            half_kpts_first_relax (bool): Whether to halve the kpoint grid
                for the first relaxation. Speeds up difficult convergence
                considerably. Defaults to False.

        Returns:
            Generator of jobs.
        """
        for i in range(max_steps):
            if i == 0:
                settings = None
                backup = True
                if half_kpts_first_relax and os.path.exists("KPOINTS") and \
                        os.path.exists("POSCAR"):
                    kpts = Kpoints.from_file("KPOINTS")
                    orig_kpts_dict = kpts.as_dict()
                    kpts.kpts = np.maximum(np.array(kpts.kpts) / 2, 1).tolist()
                    low_kpts_dict = kpts.as_dict()
                    settings = [{
                        "dict": "KPOINTS",
                        "action": {
                            "_set": low_kpts_dict
                        }
                    }]
            else:
                backup = False
                initial = Poscar.from_file("POSCAR").structure
                final = Poscar.from_file("CONTCAR").structure
                vol_change = (final.volume - initial.volume) / initial.volume

                logging.info("Vol change = %.1f %%!" % (vol_change * 100))
                if abs(vol_change) < vol_change_tol:
                    logging.info("Stopping optimization!")
                    break
                else:
                    incar_update = {"ISTART": 1}
                    if ediffg:
                        incar_update["EDIFFG"] = ediffg
                    settings = [{
                        "dict": "INCAR",
                        "action": {
                            "_set": incar_update
                        }
                    }, {
                        "file": "CONTCAR",
                        "action": {
                            "_file_copy": {
                                "dest": "POSCAR"
                            }
                        }
                    }]
                    if i == 1 and half_kpts_first_relax:
                        settings.append({
                            "dict": "KPOINTS",
                            "action": {
                                "_set": orig_kpts_dict
                            }
                        })
            logging.info("Generating job = %d!" % (i + 1))
            yield VaspJob(vasp_cmd,
                          final=False,
                          backup=backup,
                          suffix=".relax%d" % (i + 1),
                          auto_npar=auto_npar,
                          settings_override=settings)
Пример #37
0
    def process_killed_run(self, dir_name):
        """
        Process a killed vasp run.
        """
        fullpath = os.path.abspath(dir_name)
        logger.info("Processing Killed run " + fullpath)
        d = {"dir_name": fullpath, "state": "killed", "oszicar": {}}

        for f in os.listdir(dir_name):
            filename = os.path.join(dir_name, f)
            if fnmatch(f, "INCAR*"):
                try:
                    incar = Incar.from_file(filename)
                    d["incar"] = incar.as_dict()
                    d["is_hubbard"] = incar.get("LDAU", False)
                    if d["is_hubbard"]:
                        us = np.array(incar.get("LDAUU", []))
                        js = np.array(incar.get("LDAUJ", []))
                        if sum(us - js) == 0:
                            d["is_hubbard"] = False
                            d["hubbards"] = {}
                    else:
                        d["hubbards"] = {}
                    if d["is_hubbard"]:
                        d["run_type"] = "GGA+U"
                    elif incar.get("LHFCALC", False):
                        d["run_type"] = "HF"
                    else:
                        d["run_type"] = "GGA"
                except Exception as ex:
                    print(str(ex))
                    logger.error(
                        "Unable to parse INCAR for killed run {}.".format(
                            dir_name))
            elif fnmatch(f, "KPOINTS*"):
                try:
                    kpoints = Kpoints.from_file(filename)
                    d["kpoints"] = kpoints.as_dict()
                except:
                    logger.error(
                        "Unable to parse KPOINTS for killed run {}.".format(
                            dir_name))
            elif fnmatch(f, "POSCAR*"):
                try:
                    s = Poscar.from_file(filename).structure
                    comp = s.composition
                    el_amt = s.composition.get_el_amt_dict()
                    d.update({
                        "unit_cell_formula": comp.as_dict(),
                        "reduced_cell_formula": comp.to_reduced_dict,
                        "elements": list(el_amt.keys()),
                        "nelements": len(el_amt),
                        "pretty_formula": comp.reduced_formula,
                        "anonymous_formula": comp.anonymized_formula,
                        "nsites": comp.num_atoms,
                        "chemsys": "-".join(sorted(el_amt.keys()))
                    })
                    d["poscar"] = s.as_dict()
                except:
                    logger.error(
                        "Unable to parse POSCAR for killed run {}.".format(
                            dir_name))
            elif fnmatch(f, "POTCAR*"):
                try:
                    potcar = Potcar.from_file(filename)
                    d["pseudo_potential"] = {
                        "functional": potcar.functional.lower(),
                        "pot_type": "paw",
                        "labels": potcar.symbols
                    }
                except:
                    logger.error(
                        "Unable to parse POTCAR for killed run in {}.".format(
                            dir_name))
            elif fnmatch(f, "OSZICAR"):
                try:
                    d["oszicar"]["root"] = \
                        Oszicar(os.path.join(dir_name, f)).as_dict()
                except:
                    logger.error(
                        "Unable to parse OSZICAR for killed run in {}.".format(
                            dir_name))
            elif re.match("relax\d", f):
                if os.path.exists(os.path.join(dir_name, f, "OSZICAR")):
                    try:
                        d["oszicar"][f] = Oszicar(
                            os.path.join(dir_name, f, "OSZICAR")).as_dict()
                    except:
                        logger.error("Unable to parse OSZICAR for killed "
                                     "run in {}.".format(dir_name))
        return d
Пример #38
0
    def process_killed_run(self, dir_name):
        """
        Process a killed vasp run.
        """
        fullpath = os.path.abspath(dir_name)
        logger.info("Processing Killed run " + fullpath)
        d = {"dir_name": fullpath, "state": "killed", "oszicar": {}}

        for f in os.listdir(dir_name):
            filename = os.path.join(dir_name, f)
            if fnmatch(f, "INCAR*"):
                try:
                    incar = Incar.from_file(filename)
                    d["incar"] = incar.as_dict()
                    d["is_hubbard"] = incar.get("LDAU", False)
                    if d["is_hubbard"]:
                        us = np.array(incar.get("LDAUU", []))
                        js = np.array(incar.get("LDAUJ", []))
                        if sum(us - js) == 0:
                            d["is_hubbard"] = False
                            d["hubbards"] = {}
                    else:
                        d["hubbards"] = {}
                    if d["is_hubbard"]:
                        d["run_type"] = "GGA+U"
                    elif incar.get("LHFCALC", False):
                        d["run_type"] = "HF"
                    else:
                        d["run_type"] = "GGA"
                except Exception as ex:
                    print(str(ex))
                    logger.error("Unable to parse INCAR for killed run {}."
                                 .format(dir_name))
            elif fnmatch(f, "KPOINTS*"):
                try:
                    kpoints = Kpoints.from_file(filename)
                    d["kpoints"] = kpoints.as_dict()
                except:
                    logger.error("Unable to parse KPOINTS for killed run {}."
                                 .format(dir_name))
            elif fnmatch(f, "POSCAR*"):
                try:
                    s = Poscar.from_file(filename).structure
                    comp = s.composition
                    el_amt = s.composition.get_el_amt_dict()
                    d.update({"unit_cell_formula": comp.as_dict(),
                              "reduced_cell_formula": comp.to_reduced_dict,
                              "elements": list(el_amt.keys()),
                              "nelements": len(el_amt),
                              "pretty_formula": comp.reduced_formula,
                              "anonymous_formula": comp.anonymized_formula,
                              "nsites": comp.num_atoms,
                              "chemsys": "-".join(sorted(el_amt.keys()))})
                    d["poscar"] = s.as_dict()
                except:
                    logger.error("Unable to parse POSCAR for killed run {}."
                                 .format(dir_name))
            elif fnmatch(f, "POTCAR*"):
                try:
                    potcar = Potcar.from_file(filename)
                    d["pseudo_potential"] = {
                        "functional": potcar.functional.lower(),
                        "pot_type": "paw",
                        "labels": potcar.symbols}
                except:
                    logger.error("Unable to parse POTCAR for killed run in {}."
                                 .format(dir_name))
            elif fnmatch(f, "OSZICAR"):
                try:
                    d["oszicar"]["root"] = \
                        Oszicar(os.path.join(dir_name, f)).as_dict()
                except:
                    logger.error("Unable to parse OSZICAR for killed run in {}."
                                 .format(dir_name))
            elif re.match("relax\d", f):
                if os.path.exists(os.path.join(dir_name, f, "OSZICAR")):
                    try:
                        d["oszicar"][f] = Oszicar(
                            os.path.join(dir_name, f, "OSZICAR")).as_dict()
                    except:
                        logger.error("Unable to parse OSZICAR for killed "
                                     "run in {}.".format(dir_name))
        return d
Пример #39
0
    def __init__(self, kpoints_name, vasprun_name, is_projection=False):

        kpoints = Kpoints.from_file(kpoints_name)

        # BSVasprun cannot be used when the electronic convergence is checked.
        if is_projection:
            vasprun = Vasprun(filename=vasprun_name,
                              parse_projected_eigen=True)
        else:
            vasprun = Vasprun(filename=vasprun_name)

        if vasprun.converged_electronic is False:
            logger.warning("SCF is not attained!!!!!")

        eigenvalues = vasprun.eigenvalues
        lattice_rec = vasprun.final_structure.lattice.reciprocal_lattice
        efermi = vasprun.efermi

        first_index_wo_weight = 0
        for w in kpoints.kpts_weights:
            if w > 0:
                first_index_wo_weight += 1
                continue

        kpts_wo_weight = kpoints.kpts[first_index_wo_weight:]

        eigenvalues_wo_weight = {}
        for s in eigenvalues:
            # transpose is essential
            # When parsing vasprun.xml using BSVasprun,
            # eigenvalues[kpt-index][band-index] = [energy, occupation]
            # For BSPlotter
            # eigenvalues[band-index][kpt-index] = energy
            eigenvalues_wo_weight[Spin(s)] = \
                eigenvalues[Spin(s)][first_index_wo_weight:, :, 0].transpose()

        # Store label except for "None".
        labels_dict = {}
        for i, label in enumerate(kpoints.labels):
            if label != "None" and label is not None:
                # TODO: Add more greek letters
                if label == "GAMMA":
                    labels_dict["\u0393"] = kpoints.kpts[i]
                elif label == "SIGMA_0":
                    labels_dict["\u03A3" + "_0"] = kpoints.kpts[i]
                elif label == "DELTA_0":
                    labels_dict["\u0394" + "_0"] = kpoints.kpts[i]
                else:
                    labels_dict[label] = kpoints.kpts[i]

        structure = vasprun.final_structure
        if is_projection:
            v = vasprun.projected_eigenvalues
            projections = {}
            for s in eigenvalues:
                # swapaxes is essential
                # When parsing vasprun.xml using BSVasprun,
                #  Vasprun.projected_eigenvalues[spin][kpoint index][band index]
                #                               [atom index][orbital_index]
                # For BSPlotter
                # projections: dict of orbital projections as {spin: ndarray}.
                # The indices of the ndarray are [band_index, kpoint_index,
                #                                 orbital_index, ion_index].

                projections[Spin(s)] = v[Spin(s)].swapaxes(0, 1).swapaxes(2, 3)
                print(projections)
            super().__init__(kpts_wo_weight,
                             eigenvalues_wo_weight,
                             lattice_rec,
                             efermi,
                             labels_dict,
                             structure=structure,
                             projections=projections)

        else:
            super().__init__(kpts_wo_weight,
                             eigenvalues_wo_weight,
                             lattice_rec,
                             efermi,
                             labels_dict,
                             structure=structure)
Пример #40
0
    def full_opt_run(cls, vasp_cmd, vol_change_tol=0.02,
                     max_steps=10, ediffg=-0.05, half_kpts_first_relax=False,
                     **vasp_job_kwargs):
        """
        Returns a generator of jobs for a full optimization run. Basically,
        this runs an infinite series of geometry optimization jobs until the
        % vol change in a particular optimization is less than vol_change_tol.

        Args:
            vasp_cmd (str): Command to run vasp as a list of args. For example,
                if you are using mpirun, it can be something like
                ["mpirun", "pvasp.5.2.11"]
            vol_change_tol (float): The tolerance at which to stop a run.
                Defaults to 0.05, i.e., 5%.
            max_steps (int): The maximum number of runs. Defaults to 10 (
                highly unlikely that this limit is ever reached).
            ediffg (float): Force convergence criteria for subsequent runs (
                ignored for the initial run.)
            half_kpts_first_relax (bool): Whether to halve the kpoint grid
                for the first relaxation. Speeds up difficult convergence
                considerably. Defaults to False.
            \*\*vasp_job_kwargs: Passthrough kwargs to VaspJob. See
                :class:`custodian.vasp.jobs.VaspJob`.

        Returns:
            Generator of jobs.
        """
        for i in range(max_steps):
            if i == 0:
                settings = None
                backup = True
                if half_kpts_first_relax and os.path.exists("KPOINTS") and \
                        os.path.exists("POSCAR"):
                    kpts = Kpoints.from_file("KPOINTS")
                    orig_kpts_dict = kpts.as_dict()
                    kpts.kpts = np.maximum(np.array(kpts.kpts) / 2, 1).tolist()
                    low_kpts_dict = kpts.as_dict()
                    settings = [
                        {"dict": "KPOINTS",
                         "action": {"_set": low_kpts_dict}}
                    ]
            else:
                backup = False
                initial = Poscar.from_file("POSCAR").structure
                final = Poscar.from_file("CONTCAR").structure
                vol_change = (final.volume - initial.volume) / initial.volume

                logger.info("Vol change = %.1f %%!" % (vol_change * 100))
                if abs(vol_change) < vol_change_tol:
                    logger.info("Stopping optimization!")
                    break
                else:
                    incar_update = {"ISTART": 1}
                    if ediffg:
                        incar_update["EDIFFG"] = ediffg
                    settings = [
                        {"dict": "INCAR",
                         "action": {"_set": incar_update}},
                        {"file": "CONTCAR",
                         "action": {"_file_copy": {"dest": "POSCAR"}}}]
                    if i == 1 and half_kpts_first_relax:
                        settings.append({"dict": "KPOINTS",
                                         "action": {"_set": orig_kpts_dict}})
            logger.info("Generating job = %d!" % (i+1))
            yield VaspJob(vasp_cmd, final=False, backup=backup,
                          suffix=".relax%d" % (i+1), settings_override=settings,
                          **vasp_job_kwargs)