Exemple #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))
Exemple #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)
Exemple #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)
Exemple #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")
Exemple #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))
Exemple #6
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)
Exemple #7
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)
Exemple #8
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")
Exemple #9
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")
Exemple #10
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")
def band_path(line_density):
    """
    for band calculation
    """
    poscar = Poscar.from_file('POSCAR', check_for_POTCAR=False)
    highsymmkp = MyHighSymmKpath(poscar.structure)
    kpts = highsymmkp.get_kpoints(line_density)
    args = {'comment': "Kpoints for band calc",
            'kpts': kpts[0],
            'num_kpts': len(kpts[0]),
            'labels': kpts[1],
            'style': 'Reciprocal',
            'kpts_weights': [1]*len(kpts[0])}
    kpoints = Kpoints(**args)
    kpoints.write_file('KPOINTS_band')
Exemple #12
0
 def post_process(self, task_list):
     cwd = os.getcwd()
     poscar_start = os.path.abspath(
         os.path.join(task_list[0], '..', 'POSCAR'))
     os.chdir(os.path.join(task_list[0], '..'))
     if os.path.isfile(os.path.join(task_list[0], 'INCAR')):
         incar = incar_upper(
             Incar.from_file(os.path.join(task_list[0], 'INCAR')))
         kspacing = incar.get('KSPACING')
         kgamma = incar.get('KGAMMA', False)
         ret = vasp.make_kspacing_kpoints(poscar_start, kspacing, kgamma)
         kp = Kpoints.from_string(ret)
         if os.path.isfile('KPOINTS'):
             os.remove('KPOINTS')
         kp.write_file("KPOINTS")
         os.chdir(cwd)
         kpoints_universal = os.path.abspath(
             os.path.join(task_list[0], '..', 'KPOINTS'))
         for ii in task_list:
             if os.path.isfile(os.path.join(ii, 'KPOINTS')):
                 os.remove(os.path.join(ii, 'KPOINTS'))
             if os.path.islink(os.path.join(ii, 'KPOINTS')):
                 os.remove(os.path.join(ii, 'KPOINTS'))
             os.chdir(ii)
             os.symlink(os.path.relpath(kpoints_universal), 'KPOINTS')
     os.chdir(cwd)
Exemple #13
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"))
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 #15
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')
Exemple #16
0
def make_vasp_kpoints_from_incar(work_dir, jdata):
    cwd = os.getcwd()
    fp_aniso_kspacing = jdata.get('fp_aniso_kspacing')
    os.chdir(work_dir)
    # get kspacing and kgamma from incar
    assert (os.path.exists('INCAR'))
    with open('INCAR') as fp:
        incar = fp.read()
    standard_incar = incar_upper(Incar.from_string(incar))
    if fp_aniso_kspacing is None:
        try:
            kspacing = standard_incar['KSPACING']
        except KeyError:
            raise RuntimeError("KSPACING must be given in INCAR")
    else:
        kspacing = fp_aniso_kspacing
    try:
        gamma = standard_incar['KGAMMA']
        if isinstance(gamma, bool):
            pass
        else:
            if gamma[0].upper() == "T":
                gamma = True
            else:
                gamma = False
    except KeyError:
        raise RuntimeError("KGAMMA must be given in INCAR")
    # check poscar
    assert (os.path.exists('POSCAR'))
    # make kpoints
    ret = make_kspacing_kpoints('POSCAR', kspacing, gamma)
    kp = Kpoints.from_string(ret)
    kp.write_file("KPOINTS")
    os.chdir(cwd)
Exemple #17
0
    def testEntry(self):
        entries = []
        for i, f in enumerate(self.iter_path):
            vi = VaspInput.from_directory(f)
            ls = LabeledSystem(os.path.join(f, 'OUTCAR'))
            attrib = loadfn(os.path.join(f, 'job.json'))
            comp = vi['POSCAR'].structure.composition
            entry = Entry(comp,
                          'vasp',
                          vi.as_dict(),
                          ls.as_dict(),
                          entry_id='pku-' + str(i),
                          attribute=attrib)
            entries.append(entry)
        self.assertEqual(len(entries), len(self.ref_entries))
        ret0 = entries[0]
        r0 = self.ref_entries[0]
        self.assertEqual(Incar.from_dict(ret0.inputs['INCAR']),
                         Incar.from_dict(r0.inputs['INCAR']))
        self.assertEqual(str(r0.inputs['KPOINTS']),
                         str(Kpoints.from_dict(ret0.inputs['KPOINTS'])))

        self.assertEqual(ret0.inputs['POTCAR'], r0.inputs['POTCAR'].as_dict())
        self.assertEqual(
            Poscar.from_dict(ret0.inputs['POSCAR']).structure,
            r0.inputs['POSCAR'].structure)
        self.assertEqual(ret0.entry_id, 'pku-0')
Exemple #18
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")
Exemple #19
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))
Exemple #20
0
def _get_kpoints(kpoint_mesh: Union[float, int, List[int]],
                 structure: Structure,
                 symprec: float = 0.01,
                 return_full_kpoints: bool = False
                 ) -> Tuple[np.ndarray, ...]:
    """Gets the symmetry inequivalent k-points from a k-point mesh.

    Follows the same process as SpacegroupAnalyzer.get_ir_reciprocal_mesh
    but is faster and allows returning of the full k-point mesh and mapping.

    Args:
        kpoint_mesh: The k-point mesh as a 1x3 array. E.g.,``[6, 6, 6]``.
            Alternatively, if a single value is provided this will be
            treated as a reciprocal density and the k-point mesh dimensions
            generated automatically.
        structure: A structure.
        symprec: Symmetry tolerance used when determining the symmetry
            inequivalent k-points on which to interpolate.
        return_full_kpoints: Whether to return the full list of k-points
            covering the entire Brillouin zone and the indices of
            inequivalent k-points.

    Returns:
        The irreducible k-points and their weights as tuple, formatted as::

            (ir_kpoints, weights)

        If return_full_kpoints, the data will be returned as::

            (ir_kpoints, weights, full_kpoints, ir_kpoints_idx, ir_to_full_idx)

        Where ``ir_kpoints_idx`` is the index of the unique irreducible k-points
        in ``full_kpoints``. ``ir_to_full_idx`` is a list of indices that can be
        used to construct the full Brillouin zone from the ir_mesh. Note the
        ir -> full conversion will only work with calculated scalar properties
        such as energy (not vector properties such as velocity).
    """
    if isinstance(kpoint_mesh, (int, float)):
        # TODO: Update this to use reciprocal length as in kgrid
        kpoint_mesh = Kpoints.automatic_density_by_vol(structure, kpoint_mesh)

    atoms = AseAtomsAdaptor().get_atoms(structure)

    if not symprec:
        symprec = 0.1

    mapping, grid = spglib.get_ir_reciprocal_mesh(
        kpoint_mesh, atoms, symprec=symprec)
    full_kpoints = grid / kpoint_mesh

    ir_kpoints_idx, ir_to_full_idx, weights = np.unique(
        mapping, return_inverse=True, return_counts=True)
    ir_kpoints = full_kpoints[ir_kpoints_idx]

    if return_full_kpoints:
        return ir_kpoints, weights, full_kpoints, ir_kpoints_idx, ir_to_full_idx
    else:
        return ir_kpoints, weights
Exemple #21
0
    def setUp(self):
        lattice = [[10, 0, 0], [-5, 8.660254, 0], [0, 0, 5]]
        self.hexagonal = Structure(lattice=lattice,
                                   species=["H"],
                                   coords=[[0, 0, 0]])
        self.kpoints_g = Kpoints.gamma_automatic(kpts=(2, 2, 2))

        lattice2 = [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
        self.ortho = Structure(lattice=lattice2,
                               species=["H"],
                               coords=[[0, 0, 0]])
        self.kpoints_mp = Kpoints.monkhorst_automatic(kpts=(2, 2, 2))

        self.kpoints_reciprocal = \
            Kpoints(style=Kpoints.supported_modes.Reciprocal,
                    num_kpts=2,
                    kpts=((0, 0, 0), (0.5, 0.5, 0.5)),
                    kpts_weights=[1, 1])
Exemple #22
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))
 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)
Exemple #24
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)]
Exemple #25
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)]
Exemple #26
0
 def _get_dos_calc(self, phonon, structure, kpoint_density):
     tempfilename = tempfile.gettempprefix() + '.yaml'
     kpoint = Kpoints.automatic_density(structure=structure,
                                        kppa=kpoint_density,
                                        force_gamma=True)
     phonon.run_mesh(kpoint.kpts[0])
     phonon.run_total_dos()
     phonon.write_total_dos(filename=tempfilename)
     dos = get_ph_dos(tempfilename)
     os.remove(tempfilename)
     return dos
Exemple #27
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)
Exemple #28
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]])
Exemple #29
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"))
Exemple #30
0
    def _get_phono3pyobject_phono3py(self, structure, potential,
                                     kpoint_density,
                                     displacementdistancephono3py,
                                     max_distance_third_order):
        cell = get_phonopy_structure(structure)

        kpoint = Kpoints.automatic_density(structure=structure,
                                           kppa=kpoint_density,
                                           force_gamma=True)
        mesh = kpoint.kpts[0]
        phono3py = Phono3py(cell,
                            self.smat,
                            primitive_matrix=[[1, 0., 0.], [0., 1, 0.],
                                              [0., 0., 1]],
                            mesh=mesh,
                            log_level=1)

        phono3py.generate_displacements(
            distance=displacementdistancephono3py,
            cutoff_pair_distance=max_distance_third_order)
        scells_with_disps = phono3py.get_supercells_with_displacements()

        disp_dataset = phono3py.get_displacement_dataset()
        numatoms = len(scells_with_disps[0].get_scaled_positions())
        dummy_force = np.zeros((numatoms, 3))

        set_of_forces = []
        for scell in scells_with_disps:
            if scell is not None:
                # this part is adapted from: https://web.archive.org/web/20200610084959/https://github.com/phonopy/phonopy/blob/develop/example/ase/8Si-phonon.py
                # Copyright by Atsushi Togo
                cell = Atoms(symbols=scell.get_chemical_symbols(),
                             scaled_positions=scell.get_scaled_positions(),
                             cell=scell.get_cell(),
                             pbc=True)
                cell.set_calculator(potential)
                forces = cell.get_forces()
                drift_force = forces.sum(axis=0)
                print(("[Phonopy] Drift force:" + "%11.5f" * 3) %
                      tuple(drift_force))
                for force in forces:
                    force -= drift_force / forces.shape[0]
                set_of_forces.append(forces)
            else:
                set_of_forces.append(dummy_force)
        phono3py.produce_fc3(set_of_forces,
                             displacement_dataset=disp_dataset,
                             symmetrize_fc3r=True)

        fc3 = phono3py.get_fc3()

        show_drift_fc3(fc3)
        return phono3py
Exemple #31
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))
Exemple #32
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")
Exemple #33
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")
Exemple #34
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"))
    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"))
Exemple #36
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"))
    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"))
    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"))
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 #40
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"))
Exemple #41
0
    def from_structure(cls,
                       structure: Structure,
                       reciprocal_density: Optional[int] = 50000,
                       **kwargs):
        """
        Get a ShengBTE control object from a structure.

        Args:
            structure: A structure object.
            reciprocal_density: If not None, the q-point grid ("ngrid") will be
                set using this density.
            kwargs: Additional options to be passed to the Control constructor.
                See the docstring of the __init__ method for more details

        Returns:
            A ShengBTE control object.
        """

        elements = list(map(str, structure.composition.elements))

        unique_nums = np.unique(structure.atomic_numbers)
        types_dict = dict(zip(unique_nums, range(len(unique_nums))))
        types = [types_dict[i] + 1 for i in structure.atomic_numbers]

        control_dict = {
            "nelements": structure.ntypesp,
            "natoms": structure.num_sites,
            "norientations": 0,
            "lfactor": 0.1,
            "lattvec": structure.lattice.matrix.tolist(),
            "elements": elements,
            "types": types,
            "positions": structure.frac_coords.tolist(),
        }

        if reciprocal_density:
            kpoints = Kpoints.automatic_density(structure, reciprocal_density)
            control_dict["ngrid"] = kpoints.kpts[0]

        control_dict.update(**kwargs)

        return Control(**control_dict)
Exemple #42
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)
Exemple #43
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"))
    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"))
Exemple #45
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
Exemple #46
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
Exemple #47
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)
Exemple #48
0
def vac_antisite_def_struct_gen(args):
    mpid = args.mpid
    mapi_key = args.mapi_key
    cellmax = args.cellmax

    if not mpid:
        print ("============\nERROR: Provide an mpid\n============")
        return

    if not mapi_key:
        with MPRester() as mp:
            struct = mp.get_structure_by_material_id(mpid)
    else:
        with MPRester(mapi_key) as mp:
            struct = mp.get_structure_by_material_id(mpid)

    prim_struct_sites = len(struct.sites)
    struct = SpacegroupAnalyzer(struct).get_conventional_standard_structure()
    conv_struct_sites = len(struct.sites)
    conv_prim_rat = int(conv_struct_sites/prim_struct_sites)
    sc_scale = get_sc_scale(struct,cellmax)

    mpvis = MPRelaxSet(struct, user_incar_settings={"LDAU": False})

    # Begin defaults: All default settings.
    blk_vasp_incar_param = {'IBRION':-1,'EDIFF':1e-4,'EDIFFG':0.001,'NSW':0,}
    def_vasp_incar_param = {'ISIF':2,'NELM':99,'IBRION':2,'EDIFF':1e-6, 
                            'EDIFFG':0.001,'NSW':40,}
    kpoint_den = 6000
    # End defaults
    
    ptcr_flag = True
    try:
        potcar = mpvis.potcar
    except:
        print ("VASP POTCAR folder not detected.\n" \
              "Only INCAR, POSCAR, KPOINTS are generated.\n" \
              "If you have VASP installed on this system, \n" \
              "refer to pymatgen documentation for configuring the settings.")
        ptcr_flag = False


    vac = Vacancy(struct, {}, {})
    scs = vac.make_supercells_with_defects(sc_scale)
    site_no = scs[0].num_sites
    if site_no > cellmax:
        max_sc_dim = max(sc_scale)
        i = sc_scale.index(max_sc_dim)
        sc_scale[i] -= 1
        scs = vac.make_supercells_with_defects(sc_scale)

    for i in range(len(scs)):
        sc = scs[i]
        mpvis = MPRelaxSet(sc, user_incar_settings={"LDAU": False})
        poscar = mpvis.poscar
        kpoints = Kpoints.automatic_density(sc,kpoint_den)
        incar = mpvis.incar
        if ptcr_flag:
            potcar = mpvis.potcar

        interdir = mpid
        if not i:
            fin_dir = os.path.join(interdir,'bulk')
            try:
                os.makedirs(fin_dir)
            except:
                pass
            incar.update(blk_vasp_incar_param)
            incar.write_file(os.path.join(fin_dir,'INCAR'))
            poscar.write_file(os.path.join(fin_dir,'POSCAR'))
            if ptcr_flag:
                potcar.write_file(os.path.join(fin_dir,'POTCAR'))
            kpoints.write_file(os.path.join(fin_dir,'KPOINTS'))
        else:
            blk_str_sites = set(scs[0].sites)
            vac_str_sites = set(sc.sites)
            vac_sites = blk_str_sites - vac_str_sites
            vac_site = list(vac_sites)[0]
            site_mult = int(vac.get_defectsite_multiplicity(i-1)/conv_prim_rat)
            vac_site_specie = vac_site.specie
            vac_symbol = vac_site.specie.symbol

            vac_dir ='vacancy_{}_mult-{}_sitespecie-{}'.format(str(i),
                    site_mult, vac_symbol)
            fin_dir = os.path.join(interdir,vac_dir)
            try:
                os.makedirs(fin_dir)
            except:
                pass
            incar.update(def_vasp_incar_param)
            poscar.write_file(os.path.join(fin_dir,'POSCAR'))
            incar.write_file(os.path.join(fin_dir,'INCAR'))
            if ptcr_flag:
                potcar.write_file(os.path.join(fin_dir,'POTCAR'))
            kpoints.write_file(os.path.join(fin_dir,'KPOINTS'))

            # Antisite generation at all vacancy sites
            struct_species = scs[0].types_of_specie
            for specie in set(struct_species)-set([vac_site_specie]):
                subspecie_symbol = specie.symbol
                anti_struct = sc.copy()
                anti_struct.append(specie, vac_site.frac_coords)
                mpvis = MPRelaxSet(anti_struct, user_incar_settings={"LDAU": False})
                poscar = mpvis.poscar
                incar = mpvis.incar
                incar.update(def_vasp_incar_param)
                as_dir ='antisite_{}_mult-{}_sitespecie-{}_subspecie-{}'.format(
                        str(i), site_mult, vac_symbol, subspecie_symbol)
                fin_dir = os.path.join(interdir,as_dir)
                try:
                    os.makedirs(fin_dir)
                except:
                    pass
                poscar.write_file(os.path.join(fin_dir,'POSCAR'))
                incar.write_file(os.path.join(fin_dir,'INCAR'))
                if ptcr_flag:
                    potcar.write_file(os.path.join(fin_dir,'POTCAR'))
                kpoints.write_file(os.path.join(fin_dir,'KPOINTS'))
Exemple #49
0
def get_jobs(args):
    # Returns a generator of jobs. Allows of "infinite" jobs.
    vasp_command = args.command.split()
    # save initial INCAR for rampU runs
    n_ramp_u = args.jobs.count('rampU')
    ramps = 0
    if n_ramp_u:
        incar = Incar.from_file('INCAR')
        ldauu = incar['LDAUU']
        ldauj = incar['LDAUJ']

    njobs = len(args.jobs)
    post_settings = []  # append to this list to have settings applied on next job
    for i, job in enumerate(args.jobs):
        final = False if i != njobs - 1 else True
        if any(c.isdigit() for c in job):
            suffix = "." + job
        else:
            suffix = ".{}{}".format(job, i + 1)
        settings = post_settings
        post_settings = []
        backup = True if i == 0 else False
        copy_magmom = False
        vinput = VaspInput.from_directory(".")
        if i > 0:
            settings.append(
                {"file": "CONTCAR",
                 "action": {"_file_copy": {"dest": "POSCAR"}}})

        job_type = job.lower()
        auto_npar = True

        if args.no_auto_npar:
            auto_npar = False

        if job_type.startswith("static_derived"):
            from pymatgen.io.vasp.sets import MPStaticSet
            vis = MPStaticSet.from_prev_calc(
                ".", user_incar_settings={"LWAVE": True, "EDIFF": 1e-6},
                ediff_per_atom=False)
            settings.extend([
                {"dict"  : "INCAR",
                 "action": {"_set": dict(vis.incar)}},
                {'dict': 'KPOINTS',
                 'action': {'_set': vis.kpoints.as_dict()}}])

        if job_type.startswith("static_dielectric_derived"):
            from pymatgen.io.vasp.sets import MPStaticSet, MPStaticDielectricDFPTVaspInputSet

            # vis = MPStaticSet.from_prev_calc(
            #     ".", user_incar_settings={"EDIFF": 1e-6, "IBRION": 8,
            #                               "LEPSILON": True, 'LREAL':False,
            #                               "LPEAD": True, "ISMEAR": 0,
            #                               "SIGMA": 0.01},
            #     ediff_per_atom=False)
            vis = MPStaticDielectricDFPTVaspInputSet()
            incar = vis.get_incar(vinput["POSCAR"].structure)
            unset = {}
            for k in ["NPAR", "KPOINT_BSE", "LAECHG", "LCHARG", "LVHAR",
                      "NSW"]:
                incar.pop(k, None)
                if k in vinput["INCAR"]:
                    unset[k] = 1
            kpoints = vis.get_kpoints(vinput["POSCAR"].structure)
            settings.extend([
                {"dict": "INCAR",
                 "action": {"_set": dict(incar),
                            "_unset": unset}},
                {'dict': 'KPOINTS',
                 'action': {'_set': kpoints.as_dict()}}])
            auto_npar = False
        elif job_type.startswith("static"):
            m = [i * args.static_kpoint for i in vinput["KPOINTS"].kpts[0]]
            settings.extend([
                {"dict": "INCAR",
                 "action": {"_set": {"NSW": 0}}},
                {'dict': 'KPOINTS',
                 'action': {'_set': {'kpoints': [m]}}}])

        elif job_type.startswith("nonscf_derived"):
            from pymatgen.io.vasp.sets import MPNonSCFSet
            vis = MPNonSCFSet.from_prev_calc(".", copy_chgcar=False,
                                             user_incar_settings={"LWAVE": True})
            settings.extend([
                {"dict": "INCAR",
                 "action": {"_set": dict(vis.incar)}},
                {'dict': 'KPOINTS',
                 'action': {'_set': vis.kpoints.as_dict()}}])

        elif job_type.startswith("optics_derived"):
            from pymatgen.io.vasp.sets import MPNonSCFSet
            vis = MPNonSCFSet.from_prev_calc(
                ".", optics=True, copy_chgcar=False,
                nedos=2001, mode="uniform", nbands_factor=5,
                user_incar_settings={"LWAVE": True, "ALGO": "Exact", "SIGMA": 0.01, "EDIFF": 1e-6},
                ediff_per_atom=False)
            settings.extend([
                {"dict": "INCAR",
                 "action": {"_set": dict(vis.incar)}},
                {'dict': 'KPOINTS',
                 'action': {'_set': vis.kpoints.as_dict()}}])

        elif job_type.startswith("rampu"):
            f = ramps / (n_ramp_u - 1)
            settings.append(
                {"dict": "INCAR",
                 "action": {"_set": {"LDAUJ": [j * f for j in ldauj],
                                     "LDAUU": [u * f for u in ldauu]}}})
            copy_magmom = True
            ramps += 1
        elif job_type.startswith("quick_relax") or job_type.startswith(\
                "quickrelax"):
            kpoints = vinput["KPOINTS"]
            incar = vinput["INCAR"]
            structure = vinput["POSCAR"].structure
            if "ISMEAR" in incar:
                post_settings.append(
                    {"dict": "INCAR",
                     "action": {"_set": {"ISMEAR": incar["ISMEAR"]}}})
            else:
                post_settings.append(
                    {"dict": "INCAR",
                     "action": {"_unset": {"ISMEAR": 1}}})
            post_settings.append({"dict": "KPOINTS",
                                  "action": {"_set": kpoints.as_dict()}})
            # lattice vectors with length < 9 will get >1 KPOINT
            low_kpoints = Kpoints.gamma_automatic(
                [max(int(18/l), 1) for l in structure.lattice.abc])
            settings.extend([
                {"dict": "INCAR",
                 "action": {"_set": {"ISMEAR": 0}}},
                {'dict': 'KPOINTS',
                 'action': {'_set': low_kpoints.as_dict()}}])

            # let vasp determine encut (will be lower than
            # needed for compatibility with other runs)
            if "ENCUT" in incar:
                post_settings.append(
                    {"dict": "INCAR",
                     "action": {"_set": {"ENCUT": incar["ENCUT"]}}})
                settings.append(
                    {"dict": "INCAR",
                     "action": {"_unset": {"ENCUT": 1}}})

        elif job_type.startswith("relax"):
            pass
        elif job_type.startswith("full_relax"):
            for j in VaspJob.full_opt_run(
                    vasp_command):
                yield j
        else:
            print("Unsupported job type: {}".format(job))
            sys.exit(-1)

        if not job_type.startswith("full_relax"):
            yield VaspJob(vasp_command, final=final, suffix=suffix,
                          backup=backup, settings_override=settings,
                          copy_magmom=copy_magmom, auto_npar=auto_npar)
Exemple #50
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