def make_parchg_dir(args):
    os.chdir(args.dir)
    if is_file("WAVECAR") is False:
        raise FileNotFoundError("WAVECAR does not exist or is empty.")

    try:
        calc_results: CalcResults = loadfn("calc_results.json")
    except FileNotFoundError:
        logger.info("Need to create calc_results.json beforehand.")
        raise
    calc_results.show_convergence_warning()

    # Increment index by 1 as VASP band index begins from 1.
    incar = ViseIncar.from_file("INCAR")
    band_edge_states = loadfn("band_edge_states.json")
    iband = [i + 1 for i in band_edge_states.band_indices_from_vbm_to_cbm]
    incar.update({"LPARD": True, "LSEPB": True, "KPAR": 1, "IBAND": iband})

    parchg = Path("parchg")
    parchg.mkdir()
    os.chdir("parchg")
    incar.write_file("INCAR")
    FileLink(Path("../WAVECAR")).transfer(Path.cwd())
    FileLink(Path("../POSCAR")).transfer(Path.cwd())
    FileLink(Path("../POTCAR")).transfer(Path.cwd())
    FileLink(Path("../KPOINTS")).transfer(Path.cwd())
    os.chdir("..")
Beispiel #2
0
def test_make_parchg_dir(tmpdir, mocker):
    print(tmpdir)
    tmpdir.chdir()
    Path("WAVECAR").touch()
    Path("INCAR").write_text("ALGO  =  Normal")
    Path("POSCAR").write_text("a")
    Path("POTCAR").write_text("b")
    Path("KPOINTS").write_text("c")

    band_edge_states = mocker.Mock(spec=BandEdgeStates, autospec=True)
    band_edge_states.band_indices_from_vbm_to_cbm = [1, 2]

    calc_results = mocker.Mock(spec=CalcResults, autospec=True)

    def side_effect(key):
        if str(key) == "band_edge_states.json":
            return band_edge_states
        elif str(key) == "calc_results.json":
            return calc_results
        else:
            raise ValueError

    mock_loadfn = mocker.patch(f"{_filepath}.loadfn", side_effect=side_effect)
    args = Namespace(dir=Path(tmpdir))

    with pytest.raises(FileNotFoundError):
        make_parchg_dir(args)

    Path("WAVECAR").write_text("d")
    make_parchg_dir(args)

    assert Path("parchg/POSCAR").read_text() == "a"
    assert Path("parchg/POTCAR").read_text() == "b"
    assert Path("parchg/KPOINTS").read_text() == "c"
    assert Path("parchg/WAVECAR").read_text() == "d"

    actual = ViseIncar.from_file("parchg/INCAR")
    expected = {
        "ALGO": "Normal",
        "LPARD": True,
        "LSEPB": True,
        "KPAR": 1,
        "IBAND": "2 3"
    }
    assert actual == expected
Beispiel #3
0
 def incar(self) -> ViseIncar:
     incar = ViseIncar.from_dict(self._incar_settings)
     return incar
    def from_prev_calc(cls,
                       dirname: str,
                       task: Optional[Task] = None,
                       xc: Optional[Xc] = None,
                       json_filename: str = "vise.json",
                       parse_calc_results: bool = True,
                       parse_incar: bool = True,
                       sort_structure: bool = True,
                       standardize_structure: bool = False,
                       files_to_transfer: Optional[dict] = None,
                       user_incar_settings: Optional[dict] = None,
                       contcar_filename: str = "CONTCAR",
                       **kwargs) -> "ViseInputSet":
        """Constructor based on the previous calculations.

        If the task and/or xc are not set, the previous ones are assumed.

        Args:
            dirname (str):
                Directory name to be parsed.
            xc (Xc):
                Exchange-correlation (xc) defined in Xc.
            task (Task):
                Task defined in Task.
            json_filename (str):
                Json filename including ViseInputSet data.
            parse_calc_results (bool):
                Whether to parse the previous calculation results for band
                edges, magnetization.
            parse_incar (bool):
                Whether to parse the previous INCAR files, which could include
                other options that are not determined in vise.
            sort_structure (bool):
                Whether to sort the elements using get_sorted_structure method
                of Structure class in pymatgen.
            standardize_structure (bool):
                Whether to convert the structure to a standardized primitive.
            files_to_transfer (dict):
                Keys are file names to be transferred in the directory.
                Values mean the transfer modes, where there are three modes,
                "c": copy file, "m": move file, "l": make symbolic link
                e.g., {"CHGCAR": "c", "WAVECAR": "l", ..}
            user_incar_settings (dict):
                User INCAR settings.
                e.g., {"NSW": 100, "LWAVE": True, "LASPH": "A", ..}
            contcar_filename (str):
                CONTCAR type filename. Used if the user change the name.
            kwargs:
                Other OPTION arguments.

        Return:
            ViseInputSet class object.
        """
        kwargs = kwargs or {}
        kwargs["sort_structure"] = sort_structure
        kwargs["standardize_structure"] = standardize_structure

        path = Path(dirname)

        input_set = ViseInputSet.load_json(path / json_filename)

        if parse_calc_results:
            vasprun, outcar = get_vasprun_outcar(dirname)
            structure = get_structure_from_prev_run(vasprun, outcar)

            gap_properties = band_gap_properties(vasprun)
            if gap_properties:
                _, vbm, cbm = gap_properties
                kwargs["vbm_cbm"] = [vbm["energy"], cbm["energy"]]

            if "magmom" in structure.site_properties.keys():
                abs_max_mag = abs(
                    max(structure.site_properties["magmom"], key=abs))
            else:
                abs_max_mag = 0
            if vasprun.is_spin and abs_max_mag > 0.05:
                kwargs["is_magnetization"] = True

        else:
            contcar = path / contcar_filename
            poscar = path / "POSCAR"
            if contcar.is_file and os.stat(contcar).st_size != 0:
                logger.info(f"{contcar} is parsed for structure.")
                structure = Structure.from_file(contcar)
            elif poscar.is_file and os.stat(poscar).st_size != 0:
                logger.warning(f"{poscar} is parsed for structure.")
                structure = Structure.from_file(poscar)
            else:
                raise FileNotFoundError("CONTCAR or POSCAR does not exist.")

        if parse_incar:
            input_set.incar_settings = ViseIncar.from_file(path / "INCAR")

        if files_to_transfer:
            abs_files_to_transfer = {}
            for filename, value in files_to_transfer.items():
                f = path / filename
                if not f.is_file():
                    logger.warning(f"{f} does not exist.")
                elif os.stat(f).st_size == 0:
                    logger.warning(f"{f} is empty.")
                elif value[0].lower() not in ["l", "c", "m"]:
                    logger.warning(
                        f"{value} option for {filename} is invalid.")
                else:
                    abs_files_to_transfer[str(f)] = value[0].lower()
            files_to_transfer = abs_files_to_transfer

        return cls.make_input(structure=structure,
                              task=task or input_set.task,
                              xc=xc or input_set.xc,
                              prev_set=input_set,
                              abs_files_to_transfer=files_to_transfer,
                              user_incar_settings=user_incar_settings,
                              **kwargs)
 def incar(self):
     print(self.incar_settings)
     incar = ViseIncar.from_dict(self.incar_settings)
     return incar