예제 #1
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")
예제 #2
0
    def test_postprocess(self):
        with cd(os.path.join(test_dir, "postprocess")):
            with ScratchDir(".", copy_from_current_on_enter=True):
                shutil.copy("INCAR", "INCAR.backup")

                v = VaspJob("hello",
                            final=False,
                            suffix=".test",
                            copy_magmom=True)
                v.postprocess()
                incar = Incar.from_file("INCAR")
                incar_prev = Incar.from_file("INCAR.test")

                for f in [
                        "INCAR",
                        "KPOINTS",
                        "CONTCAR",
                        "OSZICAR",
                        "OUTCAR",
                        "POSCAR",
                        "vasprun.xml",
                ]:
                    self.assertTrue(os.path.isfile(f"{f}.test"))
                    os.remove(f"{f}.test")
                shutil.move("INCAR.backup", "INCAR")

                self.assertAlmostEqual(incar["MAGMOM"],
                                       [3.007, 1.397, -0.189, -0.189])
                self.assertAlmostEqual(incar_prev["MAGMOM"], [5, -5, 0.6, 0.6])
예제 #3
0
    def test_make_equi(self):
        confs = self.jdata["structures"]
        inter_param = self.jdata["interaction"]
        relax_param = self.jdata["relaxation"]
        make_equi(confs, inter_param, relax_param)

        target_path = 'confs/hp-Li/relaxation/relax_task'
        source_path = 'vasp_input'

        incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR'))
        incar1 = Incar.from_file(os.path.join(target_path, 'INCAR'))
        self.assertTrue(incar0 == incar1)

        with open(os.path.join('vasp_input', 'POTCAR')) as fp:
            pot0 = fp.read()
        with open(os.path.join(target_path, 'POTCAR')) as fp:
            pot1 = fp.read()
        self.assertEqual(pot0, pot1)

        self.assertTrue(os.path.isfile(os.path.join(target_path, 'KPOINTS')))

        task_json_file = os.path.join(target_path, 'task.json')
        self.assertTrue(os.path.isfile(task_json_file))
        task_json = loadfn(task_json_file)
        self.assertEqual(task_json, relax_param)

        inter_json_file = os.path.join(target_path, 'inter.json')
        self.assertTrue(os.path.isfile(inter_json_file))
        inter_json = loadfn(inter_json_file)
        self.assertEqual(inter_json, inter_param)

        self.assertTrue(os.path.islink(os.path.join(target_path, 'POSCAR')))
예제 #4
0
파일: neb_tasks.py 프로젝트: FilipchukB/P1
    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))
예제 #5
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"))
예제 #6
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))
예제 #7
0
 def test_continue(self):
     # Test the continuation functionality
     with cd(os.path.join(test_dir, 'postprocess')):
         # Test default functionality
         with ScratchDir('.', copy_from_current_on_enter=True) as d:
             v = VaspJob("hello", auto_continue=True)
             v.setup()
             self.assertTrue(os.path.exists("continue.json"), "continue.json not created")
             v.setup()
             self.assertEqual(Poscar.from_file("CONTCAR").structure,
                              Poscar.from_file("POSCAR").structure)
             self.assertEqual(Incar.from_file('INCAR')['ISTART'], 1)
             v.postprocess()
             self.assertFalse(os.path.exists("continue.json"),
                              "continue.json not deleted after postprocessing")
         # Test explicit action functionality
         with ScratchDir('.', copy_from_current_on_enter=True) as d:
             v = VaspJob("hello", auto_continue=[{"dict": "INCAR",
                                                  "action": {"_set": {"ISTART": 1}}}])
             v.setup()
             v.setup()
             self.assertNotEqual(Poscar.from_file("CONTCAR").structure,
                                 Poscar.from_file("POSCAR").structure)
             self.assertEqual(Incar.from_file('INCAR')['ISTART'], 1)
             v.postprocess()
예제 #8
0
def diff_incar(args):
    """
    Handle diff commands.

    :param args: Args from command.
    """
    filepath1 = args.incars[0]
    filepath2 = args.incars[1]
    incar1 = Incar.from_file(filepath1)
    incar2 = Incar.from_file(filepath2)

    def format_lists(v):
        if isinstance(v, (tuple, list)):
            return " ".join([
                "%d*%.2f" % (len(tuple(group)), i)
                for (i, group) in itertools.groupby(v)
            ])
        return v

    d = incar1.diff(incar2)
    output = [['SAME PARAMS', '', ''], ['---------------', '', ''],
              ['', '', ''], ['DIFFERENT PARAMS', '', ''],
              ['----------------', '', '']]
    output.extend([(k, format_lists(d['Same'][k]), format_lists(d['Same'][k]))
                   for k in sorted(d['Same'].keys()) if k != "SYSTEM"])
    output.extend([(k, format_lists(d['Different'][k]['INCAR1']),
                    format_lists(d['Different'][k]['INCAR2']))
                   for k in sorted(d['Different'].keys()) if k != "SYSTEM"])
    print(tabulate(output, headers=['', filepath1, filepath2]))
    return 0
예제 #9
0
    def test_static_run_correction(self):
        shutil.copy("OSZICAR.empty", "OSZICAR")
        s1 = Structure.from_file("POSCAR")
        incar = Incar.from_file("INCAR")

        # Test for NSW 0
        incar.update({"NSW": 0})
        incar.write_file("INCAR")
        h = VaspErrorHandler("vasp.out")
        self.assertEqual(h.check(), True)
        d = h.correct()
        self.assertEqual(d['errors'], ['zpotrf'])
        s2 = Structure.from_file("POSCAR")
        self.assertAlmostEqual(s2.volume, s1.volume, 3)
        self.assertEqual(Incar.from_file("INCAR")["ISYM"], 0)

        # Test for ISIF 0-2
        incar.update({"NSW":99, "ISIF":2})
        incar.write_file("INCAR")
        h = VaspErrorHandler("vasp.out")
        self.assertEqual(h.check(), True)
        d = h.correct()
        self.assertEqual(d['errors'], ['zpotrf'])
        s2 = Structure.from_file("POSCAR")
        self.assertAlmostEqual(s2.volume, s1.volume, 3)
        self.assertEqual(Incar.from_file("INCAR")["ISYM"], 0)
예제 #10
0
    def test_static_run_correction(self):
        shutil.copy("OSZICAR.empty", "OSZICAR")
        s1 = Structure.from_file("POSCAR")
        incar = Incar.from_file("INCAR")

        # Test for NSW 0
        incar.update({"NSW": 0})
        incar.write_file("INCAR")
        h = VaspErrorHandler("vasp.out")
        self.assertEqual(h.check(), True)
        d = h.correct()
        self.assertEqual(d['errors'], ['zpotrf'])
        s2 = Structure.from_file("POSCAR")
        self.assertAlmostEqual(s2.volume, s1.volume, 3)
        self.assertEqual(Incar.from_file("INCAR")["ISYM"], 0)

        # Test for ISIF 0-2
        incar.update({"NSW":99, "ISIF":2})
        incar.write_file("INCAR")
        h = VaspErrorHandler("vasp.out")
        self.assertEqual(h.check(), True)
        d = h.correct()
        self.assertEqual(d['errors'], ['zpotrf'])
        s2 = Structure.from_file("POSCAR")
        self.assertAlmostEqual(s2.volume, s1.volume, 3)
        self.assertEqual(Incar.from_file("INCAR")["ISYM"], 0)
예제 #11
0
    def test_SCAN_large_bandgap(self):
        # A structure with a large bandgap (LiF) should result in KSPACING
        # hitting the maximum allowed value of 0.44

        structure = Structure.from_file(
            os.path.join(reference_dir,
                         "SCAN_structure_optimization_LiF/inputs", "POSCAR"))

        my_wf = get_wf(structure,
                       "SCAN_optimization.yaml",
                       vis=MPScanRelaxSet(structure),
                       common_params={"vasp_cmd": VASP_CMD})

        self._run_scan_relax(my_wf, "SCAN_structure_optimization_LiF")

        # Check INCAR.orig generated by the InputSet
        incar_orig = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.orig.gz"))
        ref_incar = Incar.from_file(
            os.path.join(reference_dir,
                         "SCAN_structure_optimization_LiF/inputs",
                         "INCAR.orig"))
        for p in incar_orig.keys():
            if p == "MAGMOM":  # Ignore MAGMOM b/c structure initialized from POSCAR cannot have a MAGMOM
                pass
            else:
                self.assertEqual(incar_orig[p], ref_incar[p])

        # Check INCAR.relax1 generated by the Workflow
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.relax1.gz"))
        self.assertEqual(incar["METAGGA"], "None")
        self.assertEqual(incar["EDIFFG"], -0.05)
        self.assertEqual(incar["LWAVE"], False)

        # Check INCAR.relax2
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.relax2.gz"))
        self.assertEqual(incar["METAGGA"], "None")
        self.assertEqual(incar["LWAVE"], True)
        self.assertEqual(incar["NSW"], 0)
        self.assertEqual(incar["EDIFFG"], -0.05)
        self.assertEqual(incar["ICHARG"], 1)
        self.assertEqual(incar["ISTART"], 0)

        # Check INCAR.relax3 for the correct kspacing
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.relax3.gz"))
        for p in incar.keys():
            if p == "KSPACING":
                self.assertEqual(incar[p], 0.44)
            elif p == "ICHARG" or p == "ISTART":
                self.assertEqual(incar[p], 1)
            elif p == "ISMEAR":
                self.assertEqual(incar[p], -5)
            elif p == "SIGMA":
                self.assertEqual(incar[p], 0.05)
            else:
                self.assertEqual(incar_orig[p], incar[p])
예제 #12
0
    def test_SCAN_small_bandgap(self):
        # A structure with a small bandgap (LiH) should result in a KSPACING
        # value of 0.351275

        structure = Structure.from_file(
            os.path.join(reference_dir,
                         "SCAN_structure_optimization_LiH/inputs", "POSCAR"))

        my_wf = get_wf(structure,
                       "SCAN_optimization.yaml",
                       vis=MPScanRelaxSet(structure),
                       common_params={"vasp_cmd": VASP_CMD})

        self._run_scan_relax(my_wf, "SCAN_structure_optimization_LiH")

        # Check INCAR.orig
        incar_orig = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.orig.gz"))
        ref_incar = Incar.from_file(
            os.path.join(reference_dir,
                         "SCAN_structure_optimization_LiH/inputs",
                         "INCAR.orig"))
        for p in incar_orig.keys():
            if p == "MAGMOM":  # Ignore MAGMOM b/c structure initialized from POSCAR cannot have a MAGMOM
                pass
            else:
                self.assertEqual(incar_orig[p], ref_incar[p])

        # Check INCAR.relax1
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.relax1.gz"))
        self.assertEqual(incar["METAGGA"], "None")
        self.assertEqual(incar["EDIFFG"], -0.05)
        self.assertEqual(incar["LWAVE"], False)

        # Check INCAR.relax2
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.relax2.gz"))
        self.assertEqual(incar["METAGGA"], "None")
        self.assertEqual(incar["LWAVE"], True)
        self.assertEqual(incar["NSW"], 0)
        self.assertEqual(incar["EDIFFG"], -0.05)
        self.assertEqual(incar["ICHARG"], 1)
        self.assertEqual(incar["ISTART"], 0)

        # Check INCAR.relax3
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.relax3.gz"))
        for p in incar.keys():
            if p == "KSPACING":
                self.assertAlmostEqual(incar[p], 0.351275, 4)
            elif p == "ICHARG" or p == "ISTART":
                self.assertEqual(incar[p], 1)
            elif p == "ISMEAR":
                self.assertEqual(incar[p], -5)
            elif p == "SIGMA":
                self.assertEqual(incar[p], 0.05)
            else:
                self.assertEqual(incar_orig[p], incar[p])
예제 #13
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")
예제 #14
0
 def test_eddrmm(self):
     h = VaspErrorHandler("vasp.eddrmm")
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["eddrmm"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["ALGO"], "Normal")
     self.assertEqual(h.correct()["errors"], ["eddrmm"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["POTIM"], 0.25)
예제 #15
0
 def test_rhosyg(self):
     h = VaspErrorHandler("vasp.rhosyg")
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["rhosyg"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["SYMPREC"], 1e-4)
     self.assertEqual(h.correct()["errors"], ["rhosyg"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["ISYM"], 0)
예제 #16
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)
예제 #17
0
 def test_eddrmm(self):
     h = VaspErrorHandler("vasp.eddrmm")
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["eddrmm"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["ALGO"], "Normal")
     self.assertEqual(h.correct()["errors"], ["eddrmm"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["POTIM"], 0.25)
예제 #18
0
 def test_rhosyg(self):
     h = VaspErrorHandler("vasp.rhosyg")
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["rhosyg"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["SYMPREC"], 1e-4)
     self.assertEqual(h.correct()["errors"], ["rhosyg"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["ISYM"], 0)
예제 #19
0
    def test_SCAN_large_bandgap(self):
        # A structure with a large bandgap (LiF) should result in KSPACING
        # hitting the maximum allowed value of 0.44

        structure = Structure.from_file(
            os.path.join(reference_dir, "PBESol_pre_opt_for_SCAN_LiF/inputs",
                         "POSCAR"))

        my_wf = get_wf(structure, "metagga_optimization.yaml")
        fw_ids = self._run_scan_relax(my_wf, "LiF")

        # Check PBESol INCAR
        ref_incar = Incar.from_file(
            os.path.join(reference_dir, "PBESol_pre_opt_for_SCAN_LiF/inputs",
                         "INCAR"))
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir()[0], "INCAR.gz"))
        for p in incar.keys():
            if p == "KSPACING":
                self.assertEqual(incar[p], 0.22)
            elif p == "ICHARG" or p == "ISTART":
                self.assertEqual(incar[p], 1)
            elif p == "METAGGA":
                self.assertEqual(incar[p], "None")
            elif p == "GGA":
                self.assertEqual(incar[p], "Ps")
            elif p == "EDIFFG":
                self.assertEqual(incar[p], -0.05)
            elif p == "MAGMOM":  # Ignore MAGMOM b/c structure initialized from POSCAR cannot have a MAGMOM
                pass
            else:
                self.assertEqual(incar[p], ref_incar[p])

        # Check SCAN INCAR
        ref_incar = Incar.from_file(
            os.path.join(reference_dir,
                         "SCAN_structure_optimization_LiF/inputs", "INCAR"))
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir()[1], "INCAR.gz"))
        for p in incar.keys():
            if p == "KSPACING":
                self.assertEqual(incar[p], 0.44)
            elif p == "SIGMA":
                self.assertEqual(incar[p], 0.05)
            elif p == "ICHARG":
                self.assertEqual(incar[p], 1)
            else:
                self.assertEqual(incar[p], ref_incar[p])

        # get a fw that can be used to identify the workflow
        fw_id = list(fw_ids.values())[0]

        # check workflow finished without error
        wf = self.lp.get_wf_by_fw_id(fw_id)
        is_completed = [s == "COMPLETED" for s in wf.fw_states.values()]
        self.assertTrue(all(is_completed))
예제 #20
0
파일: jobs.py 프로젝트: xhqu1981/custodian
    def setup(self):
        """
        Performs initial setup for VaspJob, including overriding any settings
        and backing up.
        """

        if self.backup:
            for f in VASP_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))

        if self.auto_npar:
            try:
                incar = Incar.from_file("INCAR")
                # Only optimized NPAR for non-HF and non-RPA calculations.
                if not (incar.get("LHFCALC") or incar.get("LRPA") or
                        incar.get("LEPSILON")):
                    if incar.get("IBRION") in [5, 6, 7, 8]:
                        # NPAR should not be set for Hessian matrix
                        # calculations, whether in DFPT or otherwise.
                        del incar["NPAR"]
                    else:
                        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

        # Auto continue if a read-only STOPCAR is present
        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")

            # Setup INCAR to continue
            incar = Incar.from_file("INCAR")
            incar['ISTART'] = 1
            incar.write_file("INCAR")

            shutil.copy('CONTCAR', 'POSCAR')

        if self.settings_override is not None:
            VaspModder().apply_actions(self.settings_override)
예제 #21
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")
예제 #22
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)
예제 #23
0
파일: jobs.py 프로젝트: matk86/custodian
    def setup(self):
        """
        Performs initial setup for VaspJob, including overriding any settings
        and backing up.
        """

        if self.backup:
            for f in VASP_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))

        if self.auto_npar:
            try:
                incar = Incar.from_file("INCAR")
                # Only optimized NPAR for non-HF and non-RPA calculations.
                if not (incar.get("LHFCALC") or incar.get("LRPA")
                        or incar.get("LEPSILON")):
                    if incar.get("IBRION") in [5, 6, 7, 8]:
                        # NPAR should not be set for Hessian matrix
                        # calculations, whether in DFPT or otherwise.
                        del incar["NPAR"]
                    else:
                        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

        # Auto continue if a read-only STOPCAR is present
        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")

            # Setup INCAR to continue
            incar = Incar.from_file("INCAR")
            incar['ISTART'] = 1
            incar.write_file("INCAR")

            shutil.copy('CONTCAR', 'POSCAR')

        if self.settings_override is not None:
            VaspModder().apply_actions(self.settings_override)
예제 #24
0
    def test_SCAN_with_vdw(self):
        # Verify appropriate changes to the INCAR when VdW is enabled
        # VdW should be off for relax1 (GGA) and re-enabled for relax2 (SCAN)

        structure = Structure.from_file(os.path.join(reference_dir, "SCAN_structure_optimization_LiF_vdw/inputs", "POSCAR"))

        my_wf = get_wf(structure, "SCAN_optimization.yaml", vis=MPScanRelaxSet(structure, vdw="rvv10"),
                       common_params={"vasp_cmd": VASP_CMD, "vdw_kernel_dir": os.path.join(reference_dir, "SCAN_structure_optimization_LiF_vdw/inputs")})

        self._run_scan_relax(my_wf, "SCAN_structure_optimization_LiF_vdw")

        # Check INCAR.orig
        incar_orig = Incar.from_file(os.path.join(self._get_launch_dir(), "INCAR.orig.gz"))
        ref_incar = Incar.from_file(os.path.join(reference_dir, "SCAN_structure_optimization_LiF_vdw/inputs", "INCAR.orig"))
        for p in incar_orig.keys():
            if p == "MAGMOM":  # Ignore MAGMOM b/c structure initialized from POSCAR cannot have a MAGMOM
                pass
            else:
                self.assertEqual(incar_orig[p], ref_incar[p])

        # Check INCAR.relax1
        incar = Incar.from_file(os.path.join(self._get_launch_dir(), "INCAR.relax1.gz"))
        self.assertIsNone(incar.get("LUSE_VDW", None))
        self.assertIsNone(incar.get("BPARAM", None))
        self.assertEqual(incar["METAGGA"], "None")
        self.assertEqual(incar["EDIFFG"], -0.05)
        self.assertEqual(incar["LWAVE"], False)

        # Check INCAR.relax2
        incar = Incar.from_file(os.path.join(self._get_launch_dir(), "INCAR.relax2.gz"))
        self.assertEqual(incar["METAGGA"], "None")
        self.assertEqual(incar["LWAVE"], True)
        self.assertEqual(incar["NSW"], 0)
        self.assertEqual(incar["EDIFFG"], -0.05)
        self.assertEqual(incar["ICHARG"], 1)
        self.assertEqual(incar["ISTART"], 0)

        # Check INCAR.relax3
        incar = Incar.from_file(os.path.join(self._get_launch_dir(), "INCAR.relax3.gz"))
        for p in incar.keys():
            if p == "KSPACING":
                self.assertEqual(incar[p], 0.44)
            elif p == "ICHARG" or p == "ISTART":
                self.assertEqual(incar[p], 1)
            elif p == "ISMEAR":
                self.assertEqual(incar[p], -5)
            elif p == "SIGMA":
                self.assertEqual(incar[p], 0.05)
            elif p == "MAGMOM":  # Ignore MAGMOM b/c structure initialized from POSCAR cannot have a MAGMOM
                pass
            else:
                self.assertEqual(incar_orig[p], incar[p])
예제 #25
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")
예제 #26
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")
예제 #27
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"))
예제 #28
0
    def postprocess(self):
        """
        Postprocessing includes renaming and gzipping where necessary.
        Also copies the magmom to the incar if necessary
        """
        for f in VASP_OUTPUT_FILES + [self.output_file]:
            if os.path.exists(f):
                if self.final and self.suffix != "":
                    shutil.move(f, "{}{}".format(f, self.suffix))
                elif self.suffix != "":
                    shutil.copy(f, "{}{}".format(f, self.suffix))

        if self.copy_magmom and not self.final:
            try:
                outcar = Outcar("OUTCAR")
                magmom = [m['tot'] for m in outcar.magnetization]
                incar = Incar.from_file("INCAR")
                incar['MAGMOM'] = magmom
                incar.write_file("INCAR")
            except:
                logger.error('MAGMOM copy from OUTCAR to INCAR failed')

        # Remove continuation so if a subsequent job is run in
        # the same directory, will not restart this job.
        if os.path.exists("continue.json"):
            os.remove("continue.json")
예제 #29
0
    def test_check(self):

        shutil.copy("INCAR", "INCAR.orig")

        h = DriftErrorHandler(max_drift=0.05, to_average=11)
        self.assertFalse(h.check())

        h = DriftErrorHandler(max_drift=0.05)
        self.assertFalse(h.check())

        h = DriftErrorHandler(max_drift=0.0001)
        self.assertFalse(h.check())

        incar = Incar.from_file("INCAR")
        incar["EDIFFG"] = -0.01
        incar.write_file("INCAR")

        h = DriftErrorHandler(max_drift=0.0001)
        self.assertTrue(h.check())

        h = DriftErrorHandler()
        h.check()
        self.assertEqual(h.max_drift,0.01)

        clean_dir()
        shutil.move("INCAR.orig", "INCAR")
예제 #30
0
    def test_make_confs_0(self):
        if not os.path.exists(os.path.join(self.equi_path, 'CONTCAR')):
            with self.assertRaises(RuntimeError):
                self.surface.make_confs(self.target_path, self.equi_path)
        shutil.copy(os.path.join(self.source_path, 'mp-141.vasp'),
                    os.path.join(self.equi_path, 'CONTCAR'))
        task_list = self.surface.make_confs(self.target_path, self.equi_path)
        self.assertEqual(len(task_list), 7)
        dfm_dirs = glob.glob(os.path.join(self.target_path, 'task.*'))

        incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR.rlx'))
        incar0['ISIF'] = 4

        self.assertEqual(
            os.path.realpath(os.path.join(self.equi_path, 'CONTCAR')),
            os.path.realpath(os.path.join(self.target_path, 'POSCAR')))
        ref_st = Structure.from_file(os.path.join(self.target_path, 'POSCAR'))
        dfm_dirs.sort()
        for ii in dfm_dirs:
            st_file = os.path.join(ii, 'POSCAR')
            self.assertTrue(os.path.isfile(st_file))
            st0 = Structure.from_file(st_file)
            st1_file = os.path.join(ii, 'POSCAR.tmp')
            self.assertTrue(os.path.isfile(st1_file))
            st1 = Structure.from_file(st1_file)
            miller_json_file = os.path.join(ii, 'miller.json')
            self.assertTrue(os.path.isfile(miller_json_file))
            miller_json = loadfn(miller_json_file)
            sl = SlabGenerator(ref_st, miller_json,
                               self.prop_param[0]["min_slab_size"],
                               self.prop_param[0]["min_vacuum_size"])
            slb = sl.get_slab()
            st2 = Structure(slb.lattice, slb.species, slb.frac_coords)
            self.assertEqual(len(st1), len(st2))
예제 #31
0
    def test_aliasing_incar(self):
        os.chdir(os.path.join(test_dir, "aliasing"))
        shutil.copy("INCAR", "INCAR.orig")
        h = AliasingErrorHandler("vasp.aliasing_incar")
        h.check()
        d = h.correct()

        self.assertEqual(d["errors"], ['aliasing_incar'])
        self.assertEqual(d["actions"],
                         [{'action': {'_unset': {'NGY':1, 'NGZ': 1}},
                           'dict': 'INCAR'}, {"file": "CHGCAR",
                            "action": {"_file_delete": {'mode': "actual"}}},
                          {"file": "WAVECAR",
                            "action": {"_file_delete": {'mode': "actual"}}}])

        incar = Incar.from_file('INCAR.orig')
        incar["ICHARG"] = 10
        incar.write_file("INCAR")
        d = h.correct()
        self.assertEqual(d["errors"], ['aliasing_incar'])
        self.assertEqual(d["actions"],
                         [{'action': {'_unset': {'NGY': 1, 'NGZ': 1}},
                           'dict': 'INCAR'}])

        shutil.move("INCAR.orig", "INCAR")
        clean_dir()
        os.chdir(test_dir)
예제 #32
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)
예제 #33
0
 def test_nicht_konv(self):
     h = VaspErrorHandler("vasp.nicht_konvergent")
     h.natoms_large_cell = 5
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["nicht_konv"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["LREAL"], True)
예제 #34
0
    def test_make_confs_0(self):
        if not os.path.exists(os.path.join(self.equi_path, 'CONTCAR')):
            with self.assertRaises(RuntimeError):
                self.vacancy.make_confs(self.target_path, self.equi_path)
        shutil.copy(os.path.join(self.source_path, 'CONTCAR'),
                    os.path.join(self.equi_path, 'CONTCAR'))
        task_list = self.vacancy.make_confs(self.target_path, self.equi_path)
        dfm_dirs = glob.glob(os.path.join(self.target_path, 'task.*'))
        self.assertEqual(len(dfm_dirs), 5)

        incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR.rlx'))
        incar0['ISIF'] = 4

        self.assertEqual(
            os.path.realpath(os.path.join(self.equi_path, 'CONTCAR')),
            os.path.realpath(os.path.join(self.target_path, 'POSCAR')))
        ref_st = Structure.from_file(os.path.join(self.target_path, 'POSCAR'))
        sga = SpacegroupAnalyzer(ref_st)
        sym_st = sga.get_symmetrized_structure()
        equiv_site_seq = list(sym_st.equivalent_sites)
        dfm_dirs.sort()
        for ii in dfm_dirs:
            st_file = os.path.join(ii, 'POSCAR')
            self.assertTrue(os.path.isfile(st_file))
            st0 = Structure.from_file(st_file)
            vac_site = equiv_site_seq.pop(0)
            vac = pmg_Vacancy(ref_st, vac_site[0], charge=0.0)
            st1 = vac.generate_defect_structure(
                self.prop_param[0]['supercell'])
            self.assertEqual(st0, st1)
예제 #35
0
    def test_make_confs_0(self):

        if not os.path.exists(os.path.join(self.equi_path, 'CONTCAR')):
            with self.assertRaises(RuntimeError):
                self.eos.make_confs(self.target_path, self.equi_path)
        shutil.copy(os.path.join(self.source_path, 'CONTCAR'),
                    os.path.join(self.equi_path, 'CONTCAR'))
        task_list = self.eos.make_confs(self.target_path, self.equi_path)
        dfm_dirs = glob.glob(os.path.join(self.target_path, 'task.*'))

        incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR.rlx'))
        incar0['ISIF'] = 4

        for ii in dfm_dirs:
            self.assertTrue(os.path.isfile(os.path.join(ii, 'POSCAR')))
            eos_json_file = os.path.join(ii, 'eos.json')
            self.assertTrue(os.path.isfile(eos_json_file))
            eos_json = loadfn(eos_json_file)
            self.assertEqual(
                os.path.realpath(os.path.join(ii, 'POSCAR.orig')),
                os.path.realpath(os.path.join(self.equi_path, 'CONTCAR')))
            sys = dpdata.System(os.path.join(ii, 'POSCAR'))
            natoms = sys.get_natoms()
            self.assertAlmostEqual(eos_json['volume'],
                                   np.linalg.det(sys['cells'][0]) / natoms)
예제 #36
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)
예제 #37
0
    def postprocess(self):
        """
        Postprocessing includes renaming and gzipping where necessary.
        Also copies the magmom to the incar if necessary
        """
        for f in VASP_OUTPUT_FILES + [self.output_file]:
            if os.path.exists(f):
                if self.final and self.suffix != "":
                    shutil.move(f, "{}{}".format(f, self.suffix))
                elif self.suffix != "":
                    shutil.copy(f, "{}{}".format(f, self.suffix))

        if self.copy_magmom and not self.final:
            try:
                outcar = Outcar("OUTCAR")
                magmom = [m['tot'] for m in outcar.magnetization]
                incar = Incar.from_file("INCAR")
                incar['MAGMOM'] = magmom
                incar.write_file("INCAR")
            except:
                logger.error('MAGMOM copy from OUTCAR to INCAR failed')

        # Remove continuation so if a subsequent job is run in
        # the same directory, will not restart this job.
        if os.path.exists("continue.json"):
            os.remove("continue.json")
예제 #38
0
    def test_aliasing_incar(self):
        os.chdir(os.path.join(test_dir, "aliasing"))
        shutil.copy("INCAR", "INCAR.orig")
        h = AliasingErrorHandler("vasp.aliasing_incar")
        h.check()
        d = h.correct()

        self.assertEqual(d["errors"], ['aliasing_incar'])
        self.assertEqual(d["actions"],
                         [{'action': {'_unset': {'NGY':1, 'NGZ': 1}},
                           'dict': 'INCAR'}, {"file": "CHGCAR",
                            "action": {"_file_delete": {'mode': "actual"}}},
                          {"file": "WAVECAR",
                            "action": {"_file_delete": {'mode': "actual"}}}])

        incar = Incar.from_file('INCAR.orig')
        incar["ICHARG"] = 10
        incar.write_file("INCAR")
        d = h.correct()
        self.assertEqual(d["errors"], ['aliasing_incar'])
        self.assertEqual(d["actions"],
                         [{'action': {'_unset': {'NGY': 1, 'NGZ': 1}},
                           'dict': 'INCAR'}])

        shutil.move("INCAR.orig", "INCAR")
        clean_dir()
        os.chdir(test_dir)
예제 #39
0
    def test_make_confs(self):

        shutil.copy(os.path.join(self.source_path, 'Al-fcc.json'),
                    os.path.join(self.equi_path, 'result.json'))
        if not os.path.exists(os.path.join(self.equi_path, 'CONTCAR')):
            with self.assertRaises(RuntimeError):
                self.elastic.make_confs(self.target_path, self.equi_path)
        shutil.copy(os.path.join(self.source_path, 'CONTCAR_Al_fcc'),
                    os.path.join(self.equi_path, 'CONTCAR'))
        task_list = self.elastic.make_confs(self.target_path, self.equi_path)
        dfm_dirs = glob.glob(os.path.join(self.target_path, 'task.*'))

        incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR.rlx'))
        incar0['ISIF'] = 4

        self.assertEqual(
            os.path.realpath(os.path.join(self.equi_path, 'CONTCAR')),
            os.path.realpath(os.path.join(self.target_path, 'POSCAR')))
        ref_st = Structure.from_file(os.path.join(self.target_path, 'POSCAR'))
        dfm_dirs.sort()
        for ii in dfm_dirs:
            st_file = os.path.join(ii, 'POSCAR')
            self.assertTrue(os.path.isfile(st_file))
            strain_json_file = os.path.join(ii, 'strain.json')
            self.assertTrue(os.path.isfile(strain_json_file))
예제 #40
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)
예제 #41
0
 def test_nicht_konv(self):
     h = VaspErrorHandler("vasp.nicht_konvergent")
     h.natoms_large_cell = 5
     self.assertEqual(h.check(), True)
     self.assertEqual(h.correct()["errors"], ["nicht_konv"])
     i = Incar.from_file("INCAR")
     self.assertEqual(i["LREAL"], True)
예제 #42
0
    def test_check(self):

        shutil.copy("INCAR", "INCAR.orig")

        h = DriftErrorHandler(max_drift=0.05, to_average=11)
        self.assertFalse(h.check())

        h = DriftErrorHandler(max_drift=0.05)
        self.assertFalse(h.check())

        h = DriftErrorHandler(max_drift=0.0001)
        self.assertFalse(h.check())

        incar = Incar.from_file("INCAR")
        incar["EDIFFG"] = -0.01
        incar.write_file("INCAR")

        h = DriftErrorHandler(max_drift=0.0001)
        self.assertTrue(h.check())

        h = DriftErrorHandler()
        h.check()
        self.assertEqual(h.max_drift,0.01)

        clean_dir()
        shutil.move("INCAR.orig", "INCAR")
예제 #43
0
    def test_modifyincar(self):
        # create an INCAR
        incar = self.ref_incar
        incar.write_file(os.path.join(module_dir, "INCAR"))

        # modify and test
        ft = ModifyIncar({
            "incar_update": {
                "ISMEAR": 1000
            },
            "incar_multiply": {
                "ENCUT": 1.5
            },
            "incar_dictmod": {
                "_inc": {
                    "ISPIN": -1
                }
            }
        })
        ft = load_object(ft.to_dict())  # simulate database insertion
        ft.run_task({})

        incar_mod = Incar.from_file("INCAR")
        self.assertEqual(incar_mod['ISMEAR'], 1000)
        self.assertEqual(incar_mod['ENCUT'], 780)
        self.assertEqual(incar_mod['ISPIN'], 1)
예제 #44
0
    def test_SCAN_incar_override(self):
        # user incar settings should be passed all the way through the workflow

        structure = Structure.from_file(
            os.path.join(reference_dir,
                         "SCAN_structure_optimization_LiH/inputs", "POSCAR"))

        my_wf = get_wf(structure,
                       "SCAN_optimization.yaml",
                       vis=MPScanRelaxSet(structure,
                                          user_potcar_functional="PBE_52",
                                          user_incar_settings={
                                              "NSW": 10,
                                              "SYMPREC": 1e-6,
                                              "SIGMA": 0.1
                                          }),
                       common_params={"vasp_cmd": VASP_CMD})

        self._run_scan_relax(my_wf, "SCAN_structure_optimization_LiH")

        # Check INCAR.orig
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.orig.gz"))
        self.assertEqual(incar["NSW"], 10)
        self.assertEqual(incar["SYMPREC"], 1e-6)
        self.assertEqual(incar["SIGMA"], 0.1)

        # Check INCAR.relax1
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.relax1.gz"))
        self.assertEqual(incar["NSW"], 10)
        self.assertEqual(incar["SYMPREC"], 1e-6)
        self.assertEqual(incar["SIGMA"], 0.1)

        # Check INCAR.relax2
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.relax2.gz"))
        self.assertEqual(incar["NSW"], 0)
        self.assertEqual(incar["SYMPREC"], 1e-6)
        self.assertEqual(incar["SIGMA"], 0.1)

        # Check INCAR.relax3
        incar = Incar.from_file(
            os.path.join(self._get_launch_dir(), "INCAR.relax3.gz"))
        self.assertEqual(incar["NSW"], 10)
        self.assertEqual(incar["SYMPREC"], 1e-6)
        self.assertEqual(incar["SIGMA"], 0.1)
예제 #45
0
    def setup(self):
        """
        Method is identical to custodian.vasp.jobs.setup(), except that the
        environment variable PBS_NUM_PPN is checked first when auto_npar =
        True.
        """
        files = os.listdir(".")
        num_structures = 0
        if not set(files).issuperset(VASP_INPUT_FILES):
            for f in files:
                try:
                    struct = read_structure(f)
                    num_structures += 1
                except:
                    pass
            if num_structures != 1:
                raise RuntimeError("{} structures found. Unable to continue."
                                   .format(num_structures))
            else:
                self.default_vis.write_input(struct, ".")

        if self.backup:
            for f in VASP_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))

        if self.auto_npar:
            try:
                incar = Incar.from_file("INCAR")
                # Only optimized NPAR for non-HF and non-RPA calculations.
                if not (incar.get("LHFCALC") or incar.get("LRPA") or
                        incar.get("LEPSILON")):
                    if incar.get("IBRION") in [5, 6, 7, 8]:
                        # NPAR should not be set for Hessian matrix
                        # calculations, whether in DFPT or otherwise.
                        del incar["NPAR"]
                    else:
                        import multiprocessing
                        # try pbs environment variable first
                        # try sge environment variable second
                        # Note!
                        # multiprocessing.cpu_count() will include hyperthreads
                        # in the CPU count, which will set NPAR to be too large
                        # and can cause the job to hang if you use compute
                        # nodes with scratch partitions.
                        ncores = (os.environ.get("PBS_NUM_PPN") or
                                  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.settings_override is not None:
            VaspModder().apply_actions(self.settings_override)
예제 #46
0
    def setup(self):
        """
        Performs initial setup for VaspJob, including overriding any settings
        and backing up.
        """
        decompress_dir('.')

        if self.backup:
            for f in VASP_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))

        if self.auto_npar:
            try:
                incar = Incar.from_file("INCAR")
                # Only optimized NPAR for non-HF and non-RPA calculations.
                if not (incar.get("LHFCALC") or incar.get("LRPA") or
                        incar.get("LEPSILON")):
                    if incar.get("IBRION") in [5, 6, 7, 8]:
                        # NPAR should not be set for Hessian matrix
                        # calculations, whether in DFPT or otherwise.
                        del incar["NPAR"]
                    else:
                        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:
            if os.path.exists("continue.json"):
                actions = loadfn("continue.json").get("actions")
                logger.info("Continuing previous VaspJob. Actions: {}".format(actions))
                backup(VASP_BACKUP_FILES, prefix="prev_run")
                VaspModder().apply_actions(actions)

            else:
                # Default functionality is to copy CONTCAR to POSCAR and set
                # ISTART to 1 in the INCAR, but other actions can be specified
                if self.auto_continue is True:
                    actions = [{"file": "CONTCAR",
                                "action": {"_file_copy": {"dest": "POSCAR"}}},
                               {"dict": "INCAR",
                                "action": {"_set": {"ISTART": 1}}}]
                else:
                    actions = self.auto_continue
                dumpfn({"actions": actions}, "continue.json")

        if self.settings_override is not None:
            VaspModder().apply_actions(self.settings_override)
예제 #47
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)
예제 #48
0
파일: jobs.py 프로젝트: matk86/custodian
    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)
예제 #49
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))
예제 #50
0
    def test_postprocess(self):
        os.chdir(os.path.join(test_dir, 'postprocess'))
        shutil.copy('INCAR', 'INCAR.backup')

        v = VaspJob("hello", final=False, suffix=".test", copy_magmom=True)
        v.postprocess()
        incar = Incar.from_file("INCAR")
        incar_prev = Incar.from_file("INCAR.test")

        for f in ['INCAR', 'KPOINTS', 'CONTCAR', 'OSZICAR', 'OUTCAR',
                  'POSCAR', 'vasprun.xml']:
            self.assertTrue(os.path.isfile('{}.test'.format(f)))
            os.remove('{}.test'.format(f))
        shutil.move('INCAR.backup', 'INCAR')

        self.assertAlmostEqual(incar['MAGMOM'], [3.007, 1.397, -0.189, -0.189])
        self.assertAlmostEqual(incar_prev["MAGMOM"], [5, -5, 0.6, 0.6])
예제 #51
0
    def test_correct(self):

        shutil.copy("INCAR", "INCAR.orig")

        h = DriftErrorHandler(max_drift=0.0001,enaug_multiply=2)
        h.check()
        d = h.correct()
        incar = Incar.from_file("INCAR")
        self.assertTrue(incar.get("ADDGRID",False))

        d = h.correct()
        incar = Incar.from_file("INCAR")
        self.assertEqual(incar.get("PREC"),"High")
        self.assertEqual(incar.get("ENAUG",0),incar.get("ENCUT",2)*2)

        clean_dir()
        shutil.move("INCAR.orig", "INCAR")
예제 #52
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"))
예제 #53
0
 def test_setup(self):
     with cd(test_dir):
         with ScratchDir('.', copy_from_current_on_enter=True) as d:
             v = VaspJob("hello")
             v.setup()
             incar = Incar.from_file("INCAR")
             count = multiprocessing.cpu_count()
             if count > 1:
                 self.assertGreater(incar["NPAR"], 1)
예제 #54
0
 def test_setup(self):
     with cd(test_dir):
         with ScratchDir('.', copy_from_current_on_enter=True) as d:
             v = VaspJob("hello", auto_npar=True)
             v.setup()
             incar = Incar.from_file("INCAR")
             count = multiprocessing.cpu_count()
             # Need at least 3 CPUs for NPAR to be greater than 1
             if count > 3:
                 self.assertGreater(incar["NPAR"], 1)
예제 #55
0
 def test_potim_correction(self):
     shutil.copy("OSZICAR.one_step", "OSZICAR")
     s1 = Structure.from_file("POSCAR")
     h = VaspErrorHandler("vasp.out")
     self.assertEqual(h.check(), True)
     d = h.correct()
     self.assertEqual(d['errors'], ['zpotrf'])
     s2 = Structure.from_file("POSCAR")
     self.assertAlmostEqual(s2.volume, s1.volume, 3)
     self.assertAlmostEqual(Incar.from_file("INCAR")['POTIM'], 0.25)
예제 #56
0
 def test_ioset_params(self):
     ft = WriteVaspFromIOSet(
         dict(structure=self.struct_si, vasp_input_set="MPRelaxSet",
              vasp_input_params={"user_incar_settings": {"ISMEAR": 1000}}))
     ft = load_object(ft.to_dict())  # simulate database insertion
     ft.run_task({})
     incar = Incar.from_file("INCAR")
     self.assertEqual(incar["ISMEAR"], 1000)  # make sure override works
     incar['ISMEAR'] = -5  # switch back to default
     incar.write_file("INCAR")
     self._verify_files(skip_kpoints=True)
예제 #57
0
 def test_setup(self):
     os.chdir(test_dir)
     v = VaspJob("hello")
     v.setup()
     incar = Incar.from_file("INCAR")
     count = multiprocessing.cpu_count()
     if count > 1:
         self.assertGreater(incar["NPAR"], 1)
     shutil.copy("INCAR.orig", "INCAR")
     os.remove("INCAR.orig")
     os.remove("KPOINTS.orig")
     os.remove("POTCAR.orig")
     os.remove("POSCAR.orig")
예제 #58
0
    def check(self):
        incar = Incar.from_file("INCAR")
        is_npt = incar.get("MDALGO") == 3
        if not is_npt:
            return False

        outcar = Outcar("OUTCAR")
        patterns = {"MDALGO": "MDALGO\s+=\s+([\d]+)"}
        outcar.read_pattern(patterns=patterns)
        if outcar.data["MDALGO"] == [['3']]:
            return False
        else:
            return True
예제 #59
0
파일: pmg.py 프로젝트: adozier/pymatgen
def diff_incar(args):
    filepath1 = args.incars[0]
    filepath2 = args.incars[1]
    incar1 = Incar.from_file(filepath1)
    incar2 = Incar.from_file(filepath2)

    def format_lists(v):
        if isinstance(v, (tuple, list)):
            return " ".join(["%d*%.2f" % (len(tuple(group)), i)
                             for (i, group) in itertools.groupby(v)])
        return v

    d = incar1.diff(incar2)
    output = [['SAME PARAMS', '', ''], ['---------------', '', ''],
              ['', '', ''], ['DIFFERENT PARAMS', '', ''],
              ['----------------', '', '']]
    output.extend([(k, format_lists(d['Same'][k]), format_lists(d['Same'][k]))
                   for k in sorted(d['Same'].keys()) if k != "SYSTEM"])
    output.extend([(k, format_lists(d['Different'][k]['INCAR1']),
                    format_lists(d['Different'][k]['INCAR2']))
                   for k in sorted(d['Different'].keys()) if k != "SYSTEM"])
    print(tabulate(output, headers=['', filepath1, filepath2]))