コード例 #1
0
 def test_avg_core_poten(self):
     filepath = os.path.join(test_dir, "OUTCAR.lepsilon")
     cp = Outcar(filepath).read_avg_core_poten()
     self.assertAlmostEqual(cp[-1][1], -90.0487)
     filepath = os.path.join(test_dir, "OUTCAR")
     cp = Outcar(filepath).read_avg_core_poten()
     self.assertAlmostEqual(cp[0][6], -73.1068)
コード例 #2
0
 def test_core_state_eigen(self):
     filepath = os.path.join(test_dir, "OUTCAR.CL")
     cl = Outcar(filepath).read_core_state_eigen()
     self.assertAlmostEqual(cl[6]["2s"][-1], -174.4779)
     filepath = os.path.join(test_dir, "OUTCAR.icorelevel")
     cl = Outcar(filepath).read_core_state_eigen()
     self.assertAlmostEqual(cl[4]["3d"][-1], -31.4522)
コード例 #3
0
    def test_drift(self):
        outcar = Outcar(os.path.join(test_dir, "OUTCAR"))
        self.assertEqual(len(outcar.drift),5)
        self.assertAlmostEqual(np.sum(outcar.drift),0)

        outcar = Outcar(os.path.join(test_dir, "OUTCAR.CL"))
        self.assertEqual(len(outcar.drift), 79)
        self.assertAlmostEqual(np.sum(outcar.drift),  0.448010)
コード例 #4
0
def get_structure(directory, write_cif=False):
    """
    Construct a .json file with the structure and magnetic moment from the
    output of a VASP calculation, i.e. the CONTCAR and OUTCAR file.

    Args:
        directory (str): Directory in which the geometry optimization
                output files (i.e. CONTCAR and OUTCAR) are stored.
        write_cif (bool): Flag that indicates whether the structure should
            also be written as a .cif file.
    """
    directory = os.path.abspath(directory)
    structure = Structure.from_file(os.path.join(directory, "CONTCAR"))
    out = Outcar(os.path.join(directory, "OUTCAR"))

    magmom = [site["tot"] for site in out.magnetization]

    # Add the magnetic moments to the Structure
    try:
        structure.add_site_property("magmom", magmom)
    except ValueError:
        # If something goes wrong in assigning the magnetic moments,
        # give the user a warning and assign magnetic moment zero to all sites.
        print("WARNING: Could not assign the magnetic moments found in the "
              "OUTCAR file. They may be missing.")
        structure.add_site_property("magmom", len(structure.sites) * [0])

    structure.to("json", "structure.json")

    if write_cif:
        structure.to("cif", "structure.cif")
コード例 #5
0
ファイル: utils.py プロジェクト: GuodongYu/high_throughput
def get_directories_VaspJobNotDone(root_dir):
    with cd(root_dir):  ### avoid the link problems
        root_dir_real = os.getcwd()
    scan = subprocess.Popen(['find', root_dir_real, '-name', 'POSCAR'],
                            stdout=subprocess.PIPE)
    scan.wait()
    pos_coll = scan.stdout.read().split()
    pos_dirs = [os.path.split(i)[0] for i in pos_coll]
    vaspjob_dirs = []
    for dir in pos_dirs:
        try:
            pos = Poscar.from_file(os.path.join(dir, 'POSCAR'))
            pot = Potcar.from_file(os.path.join(dir, 'POTCAR'))
            incar = Incar.from_file(os.path.join(dir, 'INCAR'))
            kpt = Kpoints.from_file(os.path.join(dir, 'KPOINTS'))
        except:
            print 'input files are not ready in %s' % dir
        else:
            try:
                out = Outcar(os.path.join(dir, 'OUTCAR'))
                if len(out.run_stats) != 7:
                    vaspjob_dir.append(dir)
            except:
                vaspjob_dirs.append(dir)
    return vaspjob_dirs
コード例 #6
0
ファイル: core.py プロジェクト: zezhong-zhang/vsc-workflows
    def run_task(self, fw_spec):

        directory = self.get("directory", os.getcwd())
        multiplier = self.get("multiplier", 3)

        os.chdir(directory)

        nelect_written = False

        try:
            with open("OUTCAR", "r") as file:
                if "NELECT" in file.read():
                    nelect_written = True
        except FileNotFoundError:
            pass

        if not nelect_written:

            # Do a trial run to figure out the number of standard bands
            stdout_file = "temp.out"
            stderr_file = "temp.out"
            vasp_cmd = fw_spec["_fw_env"]["vasp_cmd"].split(" ")

            with open(stdout_file, 'w') as f_std, \
                    open(stderr_file, "w", buffering=1) as f_err:
                p = subprocess.Popen(vasp_cmd, stdout=f_std, stderr=f_err,
                                     preexec_fn=os.setsid)

                while not nelect_written:
                    try:
                        with open("OUTCAR", "r") as file:
                            if "NELECT" in file.read():
                                nelect_written = True
                    except FileNotFoundError:
                        pass
                    time.sleep(1)

                os.killpg(os.getpgid(p.pid), signal.SIGTERM)

            time.sleep(3)
            os.remove(os.path.join(directory, "temp.out"))

        outcar = Outcar("OUTCAR")
        incar = Incar.from_file("INCAR")
        pattern = r"\s+NELECT\s=\s+(\d+).\d+\s+total\snumber\sof\selectrons"
        outcar.read_pattern({"nelect": pattern})

        nions = len(Structure.from_file("POSCAR"))
        nelect = int(outcar.data["nelect"][0][0])
        ispin = int(incar.get("ISPIN", 1))

        if ispin == 1:
            nbands = int(round(nelect / 2 + nions / 2)) * multiplier
        elif ispin == 2:
            nbands = int(nelect * 3 / 5 + nions) * multiplier
        else:
            raise ValueError("ISPIN Value is not set to 1 or 2!")

        incar.update({"NBANDS": nbands})
        incar.write_file("INCAR")
コード例 #7
0
 def parse_outcar(self):
     """Try to parse the OUTCAR file."""
     outcar_path = self.get_file('OUTCAR')
     if not outcar_path:
         return None
     parsed_outcar = Outcar(outcar_path)
     return parsed_outcar
コード例 #8
0
 def from_files(poscar_filename, locpot_filename, outcar_filename, shift=0):
     p = Poscar.from_file(poscar_filename)
     l = Locpot.from_file(locpot_filename)
     o = Outcar(outcar_filename)
     return WorkFunctionAnalyzer(p.structure,
                                 l.get_average_along_axis(int(sys.argv[1])),
                                 o.efermi, shift=shift)
コード例 #9
0
ファイル: io.py プロジェクト: hackingmaterials/amset
def parse_calculation(folder,
                      zero_weighted_kpoints=defaults["zero_weighted_kpoints"]):
    vr = Vasprun(get_gzipped_file("vasprun.xml", folder))
    out = Outcar(get_gzipped_file("OUTCAR", folder))
    bs = get_band_structure(vr, zero_weighted=zero_weighted_kpoints)
    reference_level = get_reference_energy(bs, out)
    return {"reference": reference_level, "bandstructure": bs}
コード例 #10
0
    def test_electrostatic_potential(self):

        outcar = Outcar(os.path.join(test_dir,"OUTCAR"))
        self.assertEqual(outcar.ngf,[54,30,54])
        self.assertTrue(np.allclose(outcar.sampling_radii,[0.9748, 0.9791, 0.7215]))
        self.assertTrue(np.allclose(outcar.electrostatic_potential,
          [-26.0704, -45.5046, -45.5046, -72.9539, -73.0621, -72.9539, -73.0621]))
コード例 #11
0
 def test_read_fermi_contact_shift(self):
     filepath = os.path.join(test_dir, "OUTCAR_fc")
     outcar = Outcar(filepath)
     outcar.read_fermi_contact_shift()
     self.assertAlmostEqual(outcar.data["fermi_contact_shift"][u'fch'][0][0], -0.002)
     self.assertAlmostEqual(outcar.data["fermi_contact_shift"][u'th'][0][0], -0.052)
     self.assertAlmostEqual(outcar.data["fermi_contact_shift"][u'dh'][0][0], 0.0)
コード例 #12
0
 def test_dielectric(self):
     filepath = os.path.join(test_dir, "OUTCAR.dielectric")
     outcar = Outcar(filepath)
     outcar.read_corrections()
     self.assertAlmostEqual(outcar.data["dipol_quadrupol_correction"],
                            0.03565)
     self.assertAlmostEqual(outcar.final_energy, -797.46760559)
コード例 #13
0
ファイル: jobs.py プロジェクト: sayred1/custodian
    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 Exception:
                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")
コード例 #14
0
def generate_nscf_soc_folders(structures, saxis, user_incar):
    """
    Generate the non self-consistent calculation with the spin-orbit coupling 
    """
    for name in structures:
        # add magmom as a site property for each atom
        outcar = Outcar(filename=os.path.join(name, 'OUTCAR'))
        for i, atom in enumerate(structures[name].sites):
            atom.properties = {
                "magmom": [0., 0.,
                           round(outcar.magnetization[i]['tot'], 2)]
            }
        # geterate calculation from the MPSOCSet
        mpsoc = MPSOCSet(structures[name],
                         saxis=saxis,
                         user_incar_settings=user_incar,
                         user_kpoints_settings={"reciprocal_density": 500})
        mpsoc.write_input(os.path.join(name, 'nscf_SOC'))

        # walk around the bug in MPSICSet to introduce LDAUU and LDAUL into INCAR
        dic = mpsoc.incar.as_dict()
        dic["LDAUU"] = list(dic["LDAUU"].values())
        dic["LDAUL"] = list(dic["LDAUL"].values())
        Incar.from_dict(dic).write_file(os.path.join(name, 'nscf_SOC/INCAR'))
        shutil.copy(os.path.join(name, 'CHGCAR'),
                    os.path.join(name, 'nscf_SOC'))
コード例 #15
0
 def set_ionic_dielectric_tensor_from_vasp(self,
                                           directory_path: str,
                                           outcar_name: str = "OUTCAR"
                                           ) -> None:
     outcar = Outcar(os.path.join(directory_path, outcar_name))
     outcar.read_lepsilon_ionic()
     self._ionic_dielectric_tensor = outcar.dielectric_ionic_tensor
コード例 #16
0
    def test_read_piezo_tensor(self):
        filepath = os.path.join(test_dir, "OUTCAR.lepsilon.gz")
        outcar = Outcar(filepath)

        outcar.read_piezo_tensor()
        self.assertAlmostEqual(outcar.data["piezo_tensor"][0][0], 0.52799)
        self.assertAlmostEqual(outcar.data["piezo_tensor"][1][3], 0.35998)
        self.assertAlmostEqual(outcar.data["piezo_tensor"][2][5], 0.35997)
コード例 #17
0
 def test_pseudo_zval(self):
     filepath = os.path.join(test_dir, "OUTCAR.BaTiO3.polar")
     outcar = Outcar(filepath)
     self.assertDictEqual({
         'Ba': 10.00,
         'Ti': 10.00,
         'O': 6.00
     }, outcar.zval_dict)
コード例 #18
0
def get_endiff(directory):
    """
    Calculate the energy difference for a transition in a directory.

    Args:
        directory:

    Returns:

    """
    initial_outcar = Outcar(os.path.join(directory, "initial", "OUTCAR"))
    final_outcar = Outcar(os.path.join(directory, "final", "OUTCAR"))

    initial_energy = initial_outcar.final_energy
    final_energy = final_outcar.final_energy

    print("The energy difference is: ", end="")
    print(str(final_energy - initial_energy) + " eV")
コード例 #19
0
 def test_freq_dielectric(self):
     filepath = os.path.join(test_dir, "OUTCAR.LOPTICS")
     outcar = Outcar(filepath)
     outcar.read_freq_dielectric()
     self.assertAlmostEqual(outcar.frequencies[0], 0)
     self.assertAlmostEqual(outcar.frequencies[-1], 39.826101)
     self.assertAlmostEqual(outcar.dielectric_tensor_function[0][0, 0], 8.96938800)
     self.assertAlmostEqual(outcar.dielectric_tensor_function[-1][0, 0], 7.36167000e-01 +1.53800000e-03j)
     self.assertEqual(len(outcar.frequencies), len(outcar.dielectric_tensor_function))
コード例 #20
0
 def test_cs_core_contribution(self):
     filename = os.path.join(test_dir, "nmr", "cs", "core.diff",
                             "core.diff.chemical.shifts.OUTCAR")
     outcar = Outcar(filename)
     core_contrib = outcar.read_cs_core_contribution()
     self.assertEqual(core_contrib,
                      {'Mg': -412.8248405,
                       'C': -200.5098812,
                       'O': -271.0766979})
コード例 #21
0
    def test_elastic_tensor(self):
        filepath = os.path.join(test_dir, "OUTCAR.total_tensor.Li2O.gz")
        outcar = Outcar(filepath)

        elastic_tensor = outcar.elastic_tensor

        self.assertAlmostEqual(elastic_tensor[0][0], 1986.3391)
        self.assertAlmostEqual(elastic_tensor[0][1], 187.8324)
        self.assertAlmostEqual(elastic_tensor[3][3], 586.3034)
コード例 #22
0
 def test_cs_g0_contribution(self):
     filename = os.path.join(test_dir, "nmr", "cs", "core.diff",
                             "core.diff.chemical.shifts.OUTCAR")
     outcar = Outcar(filename)
     g0_contrib = outcar.read_cs_g0_contribution()
     self.assertEqual(
         g0_contrib,
         [[-8.773535, 9e-06, 1e-06], [1.7e-05, -8.773536, -0.0792],
          [-6e-06, -0.008328, -9.320237]])
コード例 #23
0
    def test_read_elastic_tensor(self):
        filepath = os.path.join(test_dir, "OUTCAR.total_tensor.Li2O.gz")
        outcar = Outcar(filepath)

        outcar.read_elastic_tensor()

        self.assertAlmostEqual(outcar.data["elastic_tensor"][0][0], 1986.3391)
        self.assertAlmostEqual(outcar.data["elastic_tensor"][0][1], 187.8324)
        self.assertAlmostEqual(outcar.data["elastic_tensor"][3][3], 586.3034)
コード例 #24
0
 def test_freq_dielectric_vasp544(self):
     filepath = os.path.join(test_dir, "OUTCAR.LOPTICS.vasp544")
     outcar = Outcar(filepath)
     outcar.read_freq_dielectric()
     self.assertAlmostEqual(outcar.frequencies[0], 0)
     self.assertAlmostEqual(outcar.frequencies[-1], 39.63964)
     self.assertAlmostEqual(outcar.dielectric_tensor_function[0][0, 0], 12.769435+0j)
     self.assertAlmostEqual(outcar.dielectric_tensor_function[-1][0, 0], 0.828615+0.016594j)
     self.assertEqual(len(outcar.frequencies), len(outcar.dielectric_tensor_function))
     np.testing.assert_array_equal( outcar.dielectric_tensor_function[0], outcar.dielectric_tensor_function[0].transpose())
コード例 #25
0
ファイル: vasp_outcar.py プロジェクト: aiida-cusp/aiida-cusp
    def get_outcar(self):
        """
        Return a :class:`pymatgen.io.vasp.outputs.Outcar` instance
        initialized from the OUTCAR data stored by the node

        :returns: Outcar instance initialized from the node's stored
            OUTCAR data
        :rtype: :class:`~pymatgen.io.vasp.outputs.Outcar`
        """
        parsed_outcar = Outcar(self.filepath)
        return parsed_outcar
コード例 #26
0
def test_get_outcar_method(testdata):
    from pymatgen.io.vasp.outputs import Outcar
    from aiida_cusp.data.outputs.vasp_outcar import VaspOutcarData
    outcar = testdata / 'OUTCAR'
    outcar_node = VaspOutcarData(file=outcar)
    # create Outcar object from node and compare to the original
    # pymatgen class generated from the test file
    outcar_obj_node = outcar_node.get_outcar()
    outcar_obj_pmg = Outcar(outcar)
    node_contents = json.dumps(outcar_obj_node.as_dict(), sort_keys=True)
    pmg_contents = json.dumps(outcar_obj_pmg.as_dict(), sort_keys=True)
    assert node_contents == pmg_contents
コード例 #27
0
    def set_band_edge_from_vasp(self,
                                directory_path: str,
                                vasprun_name: str = "vasprun.xml",
                                outcar_name: str = "OUTCAR") -> None:
        vasprun = Vasprun(os.path.join(directory_path, vasprun_name))
        outcar = Outcar(os.path.join(directory_path, outcar_name))

        # 2019/7/13 NEVER USE Vasprun.eigenvalue_band_properties
        # THERE IS A BUG TO ESTIMATE VBM AND CBM of lower band gap materials.
        _, vbm_info, cbm_info = band_gap_properties(vasprun, outcar)
        self.is_direct = vbm_info["kpoints"] == cbm_info["kpoints"]
        self._band_edge = [vbm_info["energy"], cbm_info["energy"]]
コード例 #28
0
 def test_cs_raw_tensors(self):
     filename = os.path.join(test_dir, "nmr", "cs", "core.diff",
                             "core.diff.chemical.shifts.OUTCAR")
     outcar = Outcar(filename)
     unsym_tensors = outcar.read_cs_raw_symmetrized_tensors()
     self.assertEqual(unsym_tensors[0],
                      [[-145.814605, -4.263425, 0.000301],
                       [4.263434, -145.812238, -8.7e-05],
                       [0.000136, -0.000189, -142.794068]])
     self.assertEqual(unsym_tensors[29],
                      [[287.789318, -53.799325, 30.900024],
                       [-53.799571, 225.668117, -17.839598],
                       [3.801103, -2.195218, 88.896756]])
コード例 #29
0
 def test_chemical_shifts_with_different_core_contribution(self):
     filename = os.path.join(test_dir, "nmr", "cs", "core.diff",
                             "core.diff.chemical.shifts.OUTCAR")
     outcar = Outcar(filename)
     outcar.read_chemical_shifts()
     c_vo = outcar.data["chemical_shifts"]["valence_only"][
         7].maryland_values
     for x1, x2 in zip(list(c_vo), [198.7009, 73.7484, 1.0000]):
         self.assertAlmostEqual(x1, x2)
     c_vc = outcar.data["chemical_shifts"]["valence_and_core"][
         7].maryland_values
     for x1, x2 in zip(list(c_vc), [-1.9406, 73.7484, 1.0000]):
         self.assertAlmostEqual(x1, x2)
コード例 #30
0
 def test_polarization(self):
     filepath = os.path.join(test_dir, "OUTCAR.BaTiO3.polar")
     outcar = Outcar(filepath)
     self.assertEqual(outcar.spin, True)
     self.assertEqual(outcar.noncollinear, False)
     self.assertAlmostEqual(outcar.p_ion[0], 0.0)
     self.assertAlmostEqual(outcar.p_ion[1], 0.0)
     self.assertAlmostEqual(outcar.p_ion[2], -5.56684)
     self.assertAlmostEqual(outcar.p_sp1[0], 2.00068)
     self.assertAlmostEqual(outcar.p_sp2[0], -2.00044)
     self.assertAlmostEqual(outcar.p_elec[0], 0.00024)
     self.assertAlmostEqual(outcar.p_elec[1], 0.00019)
     self.assertAlmostEqual(outcar.p_elec[2], 3.61674)