Ejemplo n.º 1
0
def spin_boltz(vrunfile="", spin=1, k_latt=1.0, write_json=True):
    fname = vrunfile.replace("vasprun.xml", "boltz2data.json")
    if not os.path.isfile(fname):
        kp = vrunfile.replace("vasprun.xml", "KPOINTS")
        v = Vasprun(vrunfile)
        nelect = v.parameters["NELECT"]
        bs = v.get_band_structure(kp, line_mode=False)
        # doping=10.**np.arange(20,22)
        temp_r = np.array([300, 400, 500, 600, 700, 800])
        doping = np.array([0, 10**18, 10**19, 10**20, 10**21, 10**22])
        loader = BandstructureLoader(bs,
                                     v.structures[-1],
                                     spin=spin,
                                     nelect=nelect)
        bztInterp = BztInterpolator(loader, lpfac=2, curvature=True)
        bztTransp = BztTransportProperties(bztInterp,
                                           doping=doping,
                                           temp_r=temp_r)
        xx = bztTransp.compute_properties_doping(doping=doping)
        # 4 temps, 2 doping
        Conductivity_doping = bztTransp.Conductivity_doping
        Seebeck_doping = bztTransp.Seebeck_doping
        Kappa_doping = bztTransp.Kappa_doping
        Effective_mass_doping = bztTransp.Effective_mass_doping
        Power_Factor_doping = bztTransp.Power_Factor_doping
        mu_r_eV = bztTransp.mu_r_eV

        info = {}
        info["mu_r_eV"] = mu_r_eV
        info["temp_r"] = temp_r
        info["doping"] = doping
        info["Conductivity_doping"] = Conductivity_doping
        info["Seebeck_doping"] = Seebeck_doping
        info["Kappa_doping"] = Kappa_doping
        info["Effective_mass_doping"] = Effective_mass_doping
        info["Power_Factor_doping"] = Power_Factor_doping

        info["Conductivity_mu"] = bztTransp.Conductivity_mu
        info["Seebeck_mu"] = bztTransp.Seebeck_mu
        info["Kappa_mu"] = bztTransp.Kappa_mu
        info["Power_Factor_mu"] = bztTransp.Power_Factor_mu
        info["Effective_mass_mu"] = bztTransp.Effective_mass_mu
        info[
            "Hall_carrier_conc_trace_mu"] = bztTransp.Hall_carrier_conc_trace_mu
        zt = []
        temp_zt = []
        for i, ii in enumerate(info["temp_r"]):
            for j, k in zip(info["Power_Factor_mu"][i], info["Kappa_mu"][i]):
                temp_zt.append(0.001 * j * ii / (k + k_latt))
            zt.append(temp_zt)
            temp_zt = []
        zt = np.array(zt)
        info["zt_mu"] = zt
        if write_json == True:
            f = open(fname, "w")
            f.write(json.dumps(info, cls=MontyEncoder))
            f.close()
        return info
    else:
        print("File exists")
Ejemplo n.º 2
0
    def process_vasprun(self, dir_name, taskname, filename):
        """
        Adapted from matgendb.creator

        Process a vasprun.xml file.
        """
        vasprun_file = os.path.join(dir_name, filename)
        if self.bandstructure_mode:
            vrun = Vasprun(vasprun_file, parse_eigen=True, parse_projected_eigen=True)
        else:
            vrun = Vasprun(vasprun_file)

        d = vrun.as_dict()
        for k, v in {"formula_pretty": "pretty_formula",
                     "composition_reduced": "reduced_cell_formula",
                     "composition_unit_cell": "unit_cell_formula"}.items():
            d[k] = d.pop(v)

        for k in ["eigenvalues", "projected_eigenvalues"]:  # large storage space breaks some docs
            if k in d["output"]:
                del d["output"][k]

        comp = Composition(d["composition_unit_cell"])
        d["formula_anonymous"] = comp.anonymized_formula
        d["formula_reduced_abc"] = comp.reduced_composition.alphabetical_formula
        d["dir_name"] = os.path.abspath(dir_name)
        d["completed_at"] = str(datetime.datetime.fromtimestamp(os.path.getmtime(vasprun_file)))
        d["density"] = vrun.final_structure.density
        # replace 'crystal' with 'structure'
        d["input"]["structure"] = d["input"].pop("crystal")
        d["output"]["structure"] = d["output"].pop("crystal")
        for k, v in {"energy": "final_energy", "energy_per_atom": "final_energy_per_atom"}.items():
            d["output"][k] = d["output"].pop(v)

        if self.parse_dos and self.parse_dos != 'final':
            try:
                d["dos"] = vrun.complete_dos.as_dict()
            except:
                raise ValueError("No valid dos data exist in {}.".format(dir_name))

        if self.bandstructure_mode:
            bs = vrun.get_band_structure(line_mode=(self.bandstructure_mode == "line"))
        else:
            bs = vrun.get_band_structure()

        d["bandstructure"] = bs.as_dict()

        d["output"]["vbm"] = bs.get_vbm()["energy"]
        d["output"]["cbm"] = bs.get_cbm()["energy"]
        bs_gap = bs.get_band_gap()
        d["output"]["bandgap"] = bs_gap["energy"]
        d["output"]["is_gap_direct"] = bs_gap["direct"]
        d["output"]["is_metal"] = bs.is_metal()
        d["task"] = {"type": taskname, "name": taskname}
        # phonon-dfpt
        if hasattr(vrun, "force_constants"):
            d["output"]["force_constants"] = vrun.force_constants.tolist()
            d["output"]["normalmode_eigenvals"] = vrun.normalmode_eigenvals.tolist()
            d["output"]["normalmode_eigenvecs"] = vrun.normalmode_eigenvecs.tolist()
        return d
Ejemplo n.º 3
0
 def process_vasprun(self, dir_name, taskname, filename):
     """
     Process a vasprun.xml file.
     """
     vasprun_file = os.path.join(dir_name, filename)
     if self.parse_projected_eigen and (self.parse_projected_eigen != 'final' or \
                          taskname == self.runs[-1]):
         parse_projected_eigen = True
     else:
         parse_projected_eigen = False
     r = Vasprun(vasprun_file, parse_projected_eigen=parse_projected_eigen)
     d = r.as_dict()
     d["dir_name"] = os.path.abspath(dir_name)
     d["completed_at"] = \
         str(datetime.datetime.fromtimestamp(os.path.getmtime(
             vasprun_file)))
     d["cif"] = str(CifWriter(r.final_structure))
     d["density"] = r.final_structure.density
     if self.parse_dos and (self.parse_dos != 'final' \
                            or taskname == self.runs[-1]):
         try:
             d["dos"] = r.complete_dos.as_dict()
         except Exception:
             logger.warning(
                 "No valid dos data exist in {}.\n Skipping dos".format(
                     dir_name))
     if taskname == "relax1" or taskname == "relax2":
         d["task"] = {"type": "aflow", "name": taskname}
     else:
         d["task"] = {"type": taskname, "name": taskname}
     d["oxide_type"] = oxide_type(r.final_structure)
     return d
Ejemplo n.º 4
0
 def process_vasprun(self, dir_name, taskname, filename):
     """
     Process a vasprun.xml file.
     """
     vasprun_file = os.path.join(dir_name, filename)
     r = Vasprun(vasprun_file)
     d = r.as_dict()
     d["dir_name"] = os.path.abspath(dir_name)
     d["completed_at"] = \
         str(datetime.datetime.fromtimestamp(os.path.getmtime(
             vasprun_file)))
     d["cif"] = str(CifWriter(r.final_structure))
     d["density"] = r.final_structure.density
     if self.parse_dos and (self.parse_dos != 'final' \
                            or taskname == self.runs[-1]):
         try:
             d["dos"] = r.complete_dos.as_dict()
         except Exception:
             logger.warn("No valid dos data exist in {}.\n Skipping dos"
                         .format(dir_name))
     if taskname == "relax1" or taskname == "relax2":
         d["task"] = {"type": "aflow", "name": taskname}
     else:
         d["task"] = {"type": taskname, "name": taskname}
     return d
Ejemplo n.º 5
0
    def run_task(self, fw_spec):
        vr_path = self.get("vasprun_path", "vasprun.xml")
        min_gap = self.get("min_gap", None)
        max_gap = self.get("max_gap", None)

        vr_path = zpath(vr_path)

        if not os.path.exists(vr_path):
            relax_paths = sorted(glob.glob(vr_path + ".relax*"), reverse=True)
            if relax_paths:
                if len(relax_paths) > 9:
                    raise ValueError(
                        "CheckBandgap doesn't properly handle >9 relaxations!")
                vr_path = relax_paths[0]

        print("Checking the gap of file: {}".format(vr_path))
        vr = Vasprun(vr_path)
        gap = vr.get_band_structure().get_band_gap()["energy"]
        stored_data = {"band_gap": gap}
        print("The gap is: {}. Min gap: {}. Max gap: {}".format(
            gap, min_gap, max_gap))

        if min_gap and gap < min_gap or max_gap and gap > max_gap:
            print("Defusing based on band gap!")
            return FWAction(stored_data=stored_data,
                            exit=True,
                            defuse_workflow=True)

        print("Gap OK...")
        return FWAction(stored_data=stored_data)
Ejemplo n.º 6
0
    def run_task(self, fw_spec):
        vr_path = zpath(self.get("vasprun_path", "vasprun.xml"))
        min_gap = self.get("min_gap", None)
        max_gap = self.get("max_gap", None)

        if not os.path.exists(vr_path):
            relax_paths = sorted(glob.glob(vr_path + ".relax*"))
            if relax_paths:
                if len(relax_paths) > 9:
                    raise ValueError(
                        "CheckBandgap doesn't properly handle >9 relaxations!")
                vr_path = relax_paths[-1]

        logger.info("Checking the gap of file: {}".format(vr_path))
        vr = Vasprun(vr_path)
        gap = vr.get_band_structure().get_band_gap()["energy"]
        stored_data = {"band_gap": gap}
        logger.info("The gap is: {}. Min gap: {}. Max gap: {}".format(
            gap, min_gap, max_gap))

        if (min_gap and gap < min_gap) or (max_gap and gap > max_gap):
            logger.info("CheckBandgap: failed test!")
            return FWAction(stored_data=stored_data,
                            exit=True,
                            defuse_workflow=True)

        return FWAction(stored_data=stored_data)
Ejemplo n.º 7
0
    def run_task(self, fw_spec):
        vr_path = zpath(self.get("vasprun_path", "vasprun.xml"))
        min_gap = self.get("min_gap", None)
        max_gap = self.get("max_gap", None)

        if not os.path.exists(vr_path):
            relax_paths = sorted(glob.glob(vr_path + ".relax*"))
            if relax_paths:
                if len(relax_paths) > 9:
                    raise ValueError(
                        "CheckBandgap doesn't properly handle >9 relaxations!")
                vr_path = relax_paths[-1]

        logger.info("Checking the gap of file: {}".format(vr_path))
        vr = Vasprun(vr_path)
        gap = vr.get_band_structure().get_band_gap()["energy"]
        stored_data = {"band_gap": gap}
        logger.info(
            "The gap is: {}. Min gap: {}. Max gap: {}".format(gap, min_gap,
                                                              max_gap))

        if (min_gap and gap < min_gap) or (max_gap and gap > max_gap):
            logger.info("CheckBandgap: failed test!")
            return FWAction(stored_data=stored_data, exit=True,
                            defuse_workflow=True)

        return FWAction(stored_data=stored_data)
Ejemplo n.º 8
0
    def run_task(self, fw_spec):
        vr_path = self.get("vasprun_path", "vasprun.xml")
        min_gap = self.get("min_gap", None)
        max_gap = self.get("max_gap", None)

        vr_path = zpath(vr_path)

        if not os.path.exists(vr_path):
            relax_paths = sorted(glob.glob(vr_path + ".relax*"), reverse=True)
            if relax_paths:
                if len(relax_paths) > 9:
                    raise ValueError(
                        "CheckBandgap doesn't properly handle >9 relaxations!")
                vr_path = relax_paths[0]


        print("Checking the gap of file: {}".format(vr_path))
        vr = Vasprun(vr_path)
        gap = vr.get_band_structure().get_band_gap()["energy"]
        stored_data = {"band_gap": gap}
        print("The gap is: {}. Min gap: {}. Max gap: {}".format(gap,
                                                                min_gap,
                                                                max_gap))

        if min_gap and gap < min_gap or max_gap and gap > max_gap:
            print("Defusing based on band gap!")
            return FWAction(stored_data=stored_data, exit=True,
                            defuse_workflow=True)

        print("Gap OK...")
        return FWAction(stored_data=stored_data)
Ejemplo n.º 9
0
def test_make_effective_mass(test_data_files):
    #def test_make_effective_mass(mocker, test_data_files):
    from vise.analyzer.effective_mass import EffectiveMass
    from vise.analyzer.vasp.make_effective_mass import make_effective_mass
    v = Vasprun(test_data_files / "MgSe_absorption_vasprun.xml")
    # mock_vl = mocker.patch("vise.analyzer.vasp.make_effective_mass.VasprunBSLoader")
    # mock_bi = mocker.patch("vise.analyzer.vasp.make_effective_mass.BztInterpolator")
    # mock_btp = mocker.patch("vise.analyzer.vasp.make_effective_mass.BztTransportProperties")

    p = [[[2.27995989e+00, -7.16015256e-17, -1.92884504e-16],
          [-7.16015256e-17, 2.27995989e+00, -1.17150055e-16],
          [-1.92884504e-16, -1.17150055e-16, 2.27995989e+00]]]
    n = [[[5.49195397e-01, -1.09903151e-17, -3.07622696e-17],
          [-1.09903151e-17, 5.49195397e-01, -5.50277544e-17],
          [-3.07622696e-17, -5.50277544e-17, 5.49195397e-01]]]
    # mock_btp.return_value.Effective_mass_doping = {"p": np.array([p]),
    #                                                "n": np.array([n])}
    # assume the situation where the efermi locates lower than CBM.
    v.efermi = 0.55
    actual = make_effective_mass(vasprun=v,
                                 temp=300,
                                 concentrations=[1e18],
                                 vbm=0.5614,
                                 cbm=3.0904)

    # mock_bi.assert_called_with(mock_vl.return_value, energy_range=3.0)
    # mock_btp.assert_called_with(mock_bi.return_value, temp_r=np.array([300]))
    # mock_btp.return_value.compute_properties_doping.assert_called_with([1e18])

    expected = EffectiveMass(p=p, n=n, temperature=300, concentrations=[1e+18])
    np.testing.assert_array_almost_equal(actual.p, expected.p)
    np.testing.assert_array_almost_equal(actual.n, expected.n)
    np.testing.assert_array_almost_equal(actual.concentrations,
                                         expected.concentrations)
Ejemplo n.º 10
0
    def get_bandgap_from_aexx(self,
                              structure,
                              aexx,
                              outdir=None,
                              previous=None):
        vasprun_location = os.path.join(outdir,
                                        str(aexx).zfill(2), self.names[-1],
                                        'vasprun.xml')

        # try:
        #     vasprun = Vasprun(vasprun_location, parse_projected_eigen=False)
        #     band_gap = vasprun.get_band_structure().get_band_gap()['energy']
        # except:
        def set_aexx(vasp: Vasp, structure=None):
            vasp.add_keyword('aexx', aexx / 100)
            return vasp

        for x in self.functionals:  # Set nupdown
            x.modifications.append(set_aexx)
        (_, output) = super().call_with_output(structure,
                                               outdir=os.path.join(
                                                   outdir,
                                                   str(aexx).zfill(2)),
                                               previous=previous)
        vasprun = Vasprun(vasprun_location, parse_projected_eigen=False)
        band_gap = vasprun.get_band_structure().get_band_gap()['energy']
        return (band_gap, output)
Ejemplo n.º 11
0
    def from_directory(
        directory: Union[str, Path] = ".",
        vasprun: Optional[Union[str, Path]] = None,
        settings_file: Optional[Union[str, Path]] = None,
        settings_override: Optional[Dict[str, Any]] = None,
    ):
        if not vasprun:
            vr_file = joinpath(directory, "vasprun.xml")
            vr_file_gz = joinpath(directory, "vasprun.xml.gz")

            if os.path.exists(vr_file):
                vasprun = Vasprun(vr_file, parse_projected_eigen=True)
            elif os.path.exists(vr_file_gz):
                vasprun = Vasprun(vr_file_gz, parse_projected_eigen=True)
            else:
                msg = "No vasprun.xml found in {}".format(directory)
                logger.error(msg)
                raise FileNotFoundError(msg)

        if not settings_file:
            settings_file = joinpath(directory, "settings.yaml")
        settings = load_settings_from_file(settings_file)

        if settings_override:
            settings.update(settings_override)

        return AmsetRunner.from_vasprun(vasprun, settings)
Ejemplo n.º 12
0
    def setUp(self):
        vr = Vasprun(os.path.join(amset_files, 'vasprun.xml'))
        bs = vr.get_band_structure()
        num_electrons = vr.parameters['NELECT']

        self.kpoints = np.array(vr.actual_kpoints)
        self.interpolater = BoltzTraP2Interpolater(bs, num_electrons)
Ejemplo n.º 13
0
 def test_methods(self):
     v = Vasprun(os.path.join(test_dir, "vasprun_Si_bands.xml"))
     p = BSDOSPlotter()
     plt = p.get_plot(v.get_band_structure(
         kpoints_filename=os.path.join(test_dir, "KPOINTS_Si_bands")))
     plt = p.get_plot(v.get_band_structure(
         kpoints_filename=os.path.join(test_dir, "KPOINTS_Si_bands")),
         v.complete_dos)
Ejemplo n.º 14
0
 def test_methods(self):
     v = Vasprun(os.path.join(test_dir, "vasprun_Si_bands.xml"))
     p = BSDOSPlotter()
     plt = p.get_plot(v.get_band_structure(
         kpoints_filename=os.path.join(test_dir, "KPOINTS_Si_bands")))
     plt = p.get_plot(v.get_band_structure(
         kpoints_filename=os.path.join(test_dir, "KPOINTS_Si_bands")),
         v.complete_dos)
Ejemplo n.º 15
0
def select_one_band_structure():
   check_matplotlib()
   step_count=1
   filename='vasprun.xml'
   check_file(filename)
   proc_str="Reading Data From "+ filename +" File ..."
   procs(proc_str,step_count,sp='-->>')
   vsr=Vasprun(filename)

   step_count+=1
   filename='KPOINTS'
   check_file(filename)
   proc_str="Reading Data From "+ filename +" File ..."
   procs(proc_str,step_count,sp='-->>')
   bands = vsr.get_band_structure(filename, line_mode=True, efermi=vsr.efermi)
   nelect=vsr.parameters['NELECT']
   nbands=bands.nb_bands
   if vsr.is_spin:
      proc_str="This Is a Spin-polarized Calculation."
      procs(proc_str,0,sp='-->>')
      ISPIN=2
   else:
      if vsr.parameters['LNONCOLLINEAR']:
         proc_str="This Is a Non-Collinear Calculation."
         procs(proc_str,0,sp='-->>')
         ISPIN=3
      else:
         proc_str="This Is a Non-Spin Calculation."
         procs(proc_str,0,sp='-->>')
         ISPIN=1
   proc_str="Total band number is "+str(nbands)
   procs(proc_str,0,sp='-->>')
   proc_str="Total electron number is "+str(nelect)
   procs(proc_str,0,sp='-->>')

   print("which band would like to select ?")
   wait_sep()
   in_str=""
   while in_str=="":
         in_str=input().strip()
   selected_band=int(in_str)

   step_count+=1
   filename="BAND_"+str(selected_band)+'.dat'
   proc_str="Writting Selected Band Structure Data to "+ filename +" File ..."
   procs(proc_str,step_count,sp='-->>')
   if ISPIN==1 or ISPIN==3:
      band_data=bands.bands[Spin.up][selected_band-1]-vsr.efermi
      data=np.vstack((bands.distance,band_data)).T
      head_line="#%(key1)+12s%(key2)+13s"%{'key1':'K-Distance','key2':'Energy(ev)'}
      write_col_data(filename,data,head_line,len(band_data))
   else:
      band_data_up=bands.bands[Spin.up][selected_band-1]-vsr.efermi
      band_data_down=bands.bands[Spin.down][selected_band-1]-vsr.efermi
      data=np.vstack((bands.distance,band_data_up,band_data_down)).T
      head_line="#%(key1)+12s%(key2)+13s%(key3)+15s"%{'key1':'K-Distance','key2':'UpEnergy(ev)','key3':'DownEnergy(ev)'}
      write_col_data(filename,data,head_line,len(band_data_up))
   return
Ejemplo n.º 16
0
    def setUp(self):
        vr = Vasprun(os.path.join(gaas_files, "vasprun.xml.gz"),
                     parse_projected_eigen=True)
        bs = vr.get_band_structure()
        num_electrons = vr.parameters["NELECT"]

        self.kpoints = np.array(vr.actual_kpoints)
        self.interpolater = Interpolator(bs,
                                         num_electrons,
                                         interpolate_projections=True,
                                         interpolation_factor=1)
Ejemplo n.º 17
0
    def run_task(self, fw_spec):

        kwargs = self.get("override_default_vasp_params")
        potcar_spec = self.get("potcar_spec", False)

        os.chdir(os.getcwd())
        vrun = Vasprun("vasprun.xml", parse_potcar_file=False)
        bandgap = vrun.get_band_structure().get_band_gap()["energy"]
        structure = vrun.final_structure
        vis = MPScanRelaxSet(structure, bandgap=bandgap, **kwargs)
        vis.write_input(".", potcar_spec=potcar_spec)
Ejemplo n.º 18
0
 def test_methods(self):
     v = Vasprun(
         os.path.join(PymatgenTest.TEST_FILES_DIR, "vasprun_Si_bands.xml"))
     p = BSDOSPlotter()
     plt = p.get_plot(
         v.get_band_structure(kpoints_filename=os.path.join(
             PymatgenTest.TEST_FILES_DIR, "KPOINTS_Si_bands")))
     plt.close()
     plt = p.get_plot(
         v.get_band_structure(kpoints_filename=os.path.join(
             PymatgenTest.TEST_FILES_DIR, "KPOINTS_Si_bands")),
         v.complete_dos,
     )
     plt.close("all")
Ejemplo n.º 19
0
def loadfn(fname):
    """
    Convenience method to perform quick loading of data from a filename. The
    type of object returned depends the file type.

    Args:
        fname (string): A filename.

    Returns:
        Note that fname is matched using unix-style, i.e., fnmatch.
        (Structure) if *POSCAR*/*CONTCAR*/*.cif
        (Vasprun) *vasprun*
        (obj) if *json* (passthrough to monty.serialization.loadfn)
    """
    if (fnmatch(fname, "*POSCAR*") or fnmatch(fname, "*CONTCAR*")
            or ".cif" in fname.lower()) or fnmatch(fname, "*.vasp"):
        return Structure.from_file(fname)
    if fnmatch(fname, "*vasprun*"):
        from pymatgen.io.vasp import Vasprun

        return Vasprun(fname)
    if fnmatch(fname, "*.json*"):
        from monty.serialization import loadfn

        return loadfn(fname)
    raise ValueError("Unable to determine how to process %s." % fname)
Ejemplo n.º 20
0
def test_make_perfect_band_edge_state_from_vasp(vasp_files):
    procar = Procar(vasp_files / "MgO_2x2x2_perfect" / "PROCAR")
    vasprun = Vasprun(vasp_files / "MgO_2x2x2_perfect" / "vasprun.xml")
    outcar = Outcar(vasp_files / "MgO_2x2x2_perfect" / "OUTCAR")
    actual = make_perfect_band_edge_state_from_vasp(procar, vasprun, outcar)

    vbm_info = EdgeInfo(band_idx=127,
                        kpt_coord=(0.25, 0.25, 0.25),
                        orbital_info=OrbitalInfo(energy=2.7746,
                                                 orbitals={
                                                     'Mg':
                                                     [0.0, 0.0, 0.0, 0.0],
                                                     'O':
                                                     [0.0, 0.704, 0.0, 0.0]
                                                 },
                                                 occupation=1.0))
    cbm_info = EdgeInfo(band_idx=128,
                        kpt_coord=(0.25, 0.25, 0.25),
                        orbital_info=OrbitalInfo(energy=8.2034,
                                                 orbitals={
                                                     'Mg':
                                                     [0.192, 0.0, 0.0, 0.0],
                                                     'O':
                                                     [0.224, 0.096, 0.0, 0.0]
                                                 },
                                                 occupation=0.0))
    expected = PerfectBandEdgeState(vbm_info=vbm_info, cbm_info=cbm_info)
    assert actual == expected
Ejemplo n.º 21
0
def test_unitcell(vasp_files):
    """
    HEAD OF MICROSCOPIC STATIC DIELECTRIC TENSOR (INDEPENDENT PARTICLE, excluding Hartree and local field effects)
 ------------------------------------------------------
           1.269877     0.000000    -0.000000
           0.000000     1.269877     0.000000
           0.000000     0.000000     1.269877
 ------------------------------------------------------

 MACROSCOPIC STATIC DIELECTRIC TENSOR (including local field effects in DFT)
 ------------------------------------------------------
           1.255879     0.000000    -0.000000
          -0.000000     1.255879     0.000000
          -0.000000     0.000000     1.255879
 ------------------------------------------------------
    """

    path = vasp_files / "unitcell_He_solid"
    unitcell = make_unitcell_from_vasp(
        vasprun_band=Vasprun(path / "vasprun-band.xml"),
        outcar_band=Outcar(path / "OUTCAR-band"),
        outcar_dielectric_clamped=Outcar(path / "OUTCAR-dielectric"),
        outcar_dielectric_ionic=Outcar(path / "OUTCAR-dielectric"),
    )

    assert unitcell.vbm == -10.3168
    assert unitcell.cbm == 1.2042
    assert unitcell.ele_dielectric_const[0][0] == 1.255879
    assert unitcell.ion_dielectric_const[0][0] == 0.0
Ejemplo n.º 22
0
 def test_from_dos(self):
     v = Vasprun(PymatgenTest.TEST_FILES_DIR / "vasprun.xml.LiF")
     dos = v.complete_dos
     xps = XPS.from_dos(dos)
     self.assertEqual(len(xps), 301)
     xps.smear(0.3)
     self.assertEqual(len(xps), 301)
Ejemplo n.º 23
0
def read_density_matrices(rundirs = None,
                          datafile = 'data/density_matrices.pickle'):
    if os.path.exists(datafile):
        print("Loading density matrices from pickle...")
        with open(datafile, 'rb') as f:
            DMs = pickle.load(f)
        return DMs

    print("Parsing density matrices and storing to pickle...")

    if not rundirs:
        basedir = "/home/adler/work/lowest_energy_comparison"
        rundirs = glob.glob(os.path.join(basedir, "Ispin*/*adler"))

    DMs = []
    for dirname in rundirs:
        vasprun = os.path.join(dirname, 'vasprun.xml')
        outcar = os.path.join(dirname, 'OUTCAR')
        try:
            print(vasprun)
            v = Vasprun(vasprun)
            name, U, spin = params_from_dir(outcar)
            data = {'NAME': name, 'U': U, 'SPIN': spin,
                    'CONVERGED': v.converged,
                    'DATA': read_outcar_density_matrix(outcar)}
            DMs.append(data)
        except:
            print("Failed to parse file", vasprun)

    with open(datafile, 'wb') as f:
        pickle.dump(DMs, f)

    return DMs
Ejemplo n.º 24
0
    def setUp(self):
        ge_vasprun_path = resource_filename(
            __name__, path_join("..", "data", "Ge", "vasprun.xml.gz"))
        self.ge_vasprun = Vasprun(ge_vasprun_path)

        self.ge_text_file = resource_filename(
            __name__, path_join("..", "data", "Ge", "optics.txt"))
Ejemplo n.º 25
0
 def __init__(self):
     self.vasprun = Vasprun('vasprun.xml')
     self.s = self.vasprun.final_structure
     self.complete_dos = self.vasprun.complete_dos
     self.atom: PeriodicSite = self.s.sites[283]
     self.atoms = [283, 279, 275, 271, 266]
     self.shells = 5
Ejemplo n.º 26
0
def test_band_edge_properties_from_vasp(test_data_files):
    vasprun_file = str(test_data_files / "MnO_uniform_vasprun.xml")
    vasprun = Vasprun(vasprun_file)
    outcar_file = str(test_data_files / "MnO_uniform_OUTCAR")
    outcar = Outcar(outcar_file)
    band_edge = VaspBandEdgeProperties(vasprun, outcar)
    assert pytest.approx(band_edge.band_gap) == 0.4702
Ejemplo n.º 27
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f',
                        '--file',
                        default='vasprun.xml',
                        type=str,
                        help='path to input file')
    parser.add_argument('-o',
                        '--output',
                        default='totdos.dat',
                        help='output file format')
    parser.add_argument('-s',
                        '--spin',
                        help='yes, if spin polarised, otherwise leave blank')

    args = parser.parse_args()
    dosrun = Vasprun(args.file)

    totdos = dosrun.tdos.energies - dosrun.efermi  #Set VBM to 0 eV
    sc_input = np.column_stack((totdos, dosrun.tdos.densities[Spin.up]
                                ))  #Create Array of Energy against density
    np.savetxt("totdos.dat", sc_input)  #Save as totdos.dat file

    if args.spin is not None:  # Use this if dos is spin polarised
        sc_input = np.column_stack(
            (totdos, dosrun.tdos.densities[Spin.up],
             dosrun.tdos.densities[Spin.up]
             ))  # Create array of energy against spin polarised density
        np.savetxt("totdos.dat", sc_input)  # Save as totdos.dat
Ejemplo n.º 28
0
def get_wavefunction(potcar="POTCAR",
                     wavecar="WAVECAR",
                     vasprun="vasprun.xml",
                     directory=None):
    from pawpyseed.core import pawpyc
    from pawpyseed.core.wavefunction import CoreRegion, Wavefunction

    if directory:
        wf = Wavefunction.from_directory(path=directory)
    else:
        if isinstance(vasprun, str):
            vasprun = Vasprun(vasprun)

        if isinstance(potcar, str):
            potcar = Potcar.from_file(potcar)

        ngx = vasprun.parameters["NGX"]
        ngy = vasprun.parameters["NGY"]
        ngz = vasprun.parameters["NGZ"]
        dim = np.array([ngx, ngy, ngz])
        symprec = vasprun.parameters["SYMPREC"]
        structure = vasprun.final_structure

        pwf = pawpyc.PWFPointer(wavecar, vasprun)
        core_region = CoreRegion(potcar)

        wf = Wavefunction(structure, pwf, core_region, dim, symprec, False)

    wf = wf.desymmetrized_copy(time_reversal_symmetry=False, symprec=1e-4)
    return wf
Ejemplo n.º 29
0
    def _get_vbm_band_dict(self, path, vbm):
        # ASSUMING KYLE PATH ALREADY SET UP, RETURNS A BAND_DICT to be used by run_pawpy
        # (band numbers are keys, contains maxmin window of band energies (along with occupation),
        #  and stores percentage of band character after pawpy is run...)
        vr = Vasprun(os.path.join(path, "kyle_file", "vasprun.xml"))
        max_num = 0
        band_dict = {
            bandindex: {
                "max_eigen": [-10000.0, 0.0],
                "min_eigen": [10000.0, 0.0],
                "VB_projection": None,
                "CB_projection": None,
            }
            for bandindex in range(len(list(vr.eigenvalues.values())[0][0]))
        }

        for spin, spinset in vr.eigenvalues.items():
            for kptset in spinset:
                for bandnum, eigenset in enumerate(kptset):
                    if eigenset[1] and (eigenset[0] <= vbm) and (bandnum >
                                                                 max_num):
                        max_num = bandnum
                    # see if this is lowest eigenvalue for this band so far
                    if eigenset[0] < band_dict[bandnum]["min_eigen"][0]:
                        band_dict[bandnum]["min_eigen"] = eigenset[:]
                    # see if this is highest eigenvalue for this band so far
                    if eigenset[0] > band_dict[bandnum]["max_eigen"][0]:
                        band_dict[bandnum]["max_eigen"] = eigenset[:]

        trim_band_dict = {
            band_index: band_dict[band_index].copy()
            for band_index in range(max_num - 20, max_num + 21)
        }

        return trim_band_dict, vr.is_spin
Ejemplo n.º 30
0
    def check(self):
        msg = "Reciprocal lattice and k-lattice belong to different class of" \
              " lattices."

        vi = VaspInput.from_directory('.')
        # According to VASP admins, you can disregard this error
        # if symmetry is off
        # Also disregard if automatic KPOINT generation is used
        if (not vi["INCAR"].get('ISYM', True)) or \
                        vi[
                            "KPOINTS"].style == Kpoints.supported_modes.Automatic:
            return False

        try:
            v = Vasprun(self.output_vasprun)
            if v.converged:
                return False
        except:
            pass
        with open(self.output_filename, "r") as f:
            for line in f:
                l = line.strip()
                if l.find(msg) != -1:
                    return True
        return False
Ejemplo n.º 31
0
def make_calc_results(args):
    for d in args.dirs:
        logger.info(f"Parsing data in {d} ...")
        calc_results = make_calc_results_from_vasp(
            vasprun=Vasprun(d / defaults.vasprun),
            outcar=Outcar(d / defaults.outcar))
        calc_results.to_json_file(filename=Path(d) / "calc_results.json")
Ejemplo n.º 32
0
    def check(self):
        try:
            Vasprun("vasprun.xml")
        except Exception:
            exception_context = {}

            if os.path.exists(self.output_file):
                with open(self.output_file, "r") as output_file:
                    output_file_tail = deque(output_file, maxlen=10)
                exception_context["output_file_tail"] = "".join(
                    output_file_tail)

            if os.path.exists(self.stderr_file):
                with open(self.stderr_file, "r") as stderr_file:
                    stderr_file_tail = deque(stderr_file, maxlen=10)
                exception_context["stderr_file_tail"] = "".join(
                    stderr_file_tail)

            if os.path.exists("vasprun.xml"):
                stat = os.stat("vasprun.xml")
                exception_context["vasprun_st_size"] = stat.st_size
                exception_context["vasprun_st_atime"] = stat.st_atime
                exception_context["vasprun_st_mtime"] = stat.st_mtime
                exception_context["vasprun_st_ctime"] = stat.st_ctime

                with open("vasprun.xml", "r") as vasprun:
                    vasprun_tail = deque(vasprun, maxlen=10)
                exception_context["vasprun_tail"] = "".join(vasprun_tail)

            self.logger.error("Failed to load vasprun.xml",
                              exc_info=True,
                              extra=exception_context)

            return True
        return False
Ejemplo n.º 33
0
def test_make_diele_func(test_data_files):
    v = Vasprun(test_data_files / "MgSe_absorption_vasprun_gamma.xml")
    o = Outcar(test_data_files / "MgSe_absorption_OUTCAR_gamma")
    actual = make_diele_func(v, o)
    #    print(VaspBandEdgeProperties(v, o))
    print(actual.diele_func_real)
    assert actual.energies[1] == 0.0407
    def test_bandfilling_SOC_calc(self):
        v = Vasprun(os.path.join(PymatgenTest.TEST_FILES_DIR, "vasprun.xml.int_Te_SOC.gz"))
        struc = v.structures[0]
        interstitial = Interstitial(struc, struc.sites[-1], charge=-2)
        eigenvalues = v.eigenvalues.copy()
        kptweights = v.actual_kpoints_weights
        potalign = -0.1
        defect_incar = v.incar

        bandfill_params = {
            "eigenvalues": eigenvalues,
            "kpoint_weights": kptweights,
            "potalign": potalign,
            "vbm": 1.6465,  # bulk VBM
            "cbm": 3.1451,  # bulk CBM
            "run_metadata": {"defect_incar": defect_incar},
        }

        soc_dentry = DefectEntry(
            interstitial,
            0.0,
            corrections={},
            parameters=bandfill_params,
            entry_id=None,
        )
        dc = DefectCompatibility()
        soc_dentry = dc.process_entry(soc_dentry)

        self.assertAlmostEqual(soc_dentry.corrections["bandfilling_correction"], -1.9628402187500003)
Ejemplo n.º 35
0
def get_dos_plot(args):
    v = Vasprun(args.dos_file)
    dos = v.complete_dos

    all_dos = OrderedDict()
    all_dos["Total"] = dos

    structure = v.final_structure

    if args.site:
        for i in range(len(structure)):
            site = structure[i]
            all_dos["Site " + str(i) + " " + site.specie.symbol] = \
                dos.get_site_dos(site)

    if args.element:
        syms = [tok.strip() for tok in args.element[0].split(",")]
        all_dos = {}
        for el, dos in dos.get_element_dos().items():
            if el.symbol in syms:
                all_dos[el] = dos
    if args.orbital:
        all_dos = dos.get_spd_dos()

    plotter = DosPlotter()
    plotter.add_dos_dict(all_dos)
    return plotter.get_plot()
Ejemplo n.º 36
0
def read_structure(filename, primitive=True, sort=False):
    """
    Reads a structure based on file extension. For example, anything ending in
    a "cif" is assumed to be a Crystallographic Information Format file.
    Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT,
    vasprun.xml, CSSR and pymatgen's JSON serialized structures.

    Args:
        filename (str): A filename to read from.
        primitive (bool): Whether to convert to a primitive cell for cifs.
            Defaults to True.
        sort (bool): Whether to sort sites. Default to False.

    Returns:
        A Structure object.
    """
    fname = os.path.basename(filename)
    if fnmatch(fname.lower(), "*.cif*"):
        parser = CifParser(filename)
        s = parser.get_structures(primitive=primitive)[0]
    elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"):
        s = Poscar.from_file(filename, False).structure
    elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"):
        s = Chgcar.from_file(filename).structure
    elif fnmatch(fname, "vasprun*.xml*"):
        s = Vasprun(filename).final_structure
    elif fnmatch(fname.lower(), "*.cssr*"):
        cssr = Cssr.from_file(filename)
        s = cssr.structure
    elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
        with zopen(filename) as f:
            s = json.load(f, cls=MontyDecoder)
            if type(s) != Structure:
                raise IOError("File does not contain a valid serialized "
                              "structure")
    else:
        raise ValueError("Unrecognized file extension!")
    if sort:
        s = s.get_sorted_structure()
    return s
Ejemplo n.º 37
0
from pymatgen.io.vasp import Vasprun
from pymatgen.electronic_structure.plotter import BSPlotter, BSPlotterProjected

vr = Vasprun("nself/vasprun.xml")
bs = vr.get_band_structure(kpoints_filename="nself/KPOINTS", line_mode=True)
bsp = BSPlotter(bs)
#plt = bsp.get_elt_projected_plots(zero_to_efermi=False)
#plt.savefig("band_structure.png", format="png")
bsp.save_plot(filename="band_structure.png", img_format="png")
Ejemplo n.º 38
0
def plot_bands(vasprun_dos, vasprun_bands, kpoints, element, ylim = (None, None)):
    # read data
    # ---------

    # kpoints labels
    # labels = [r"$L$", r"$\Gamma$", r"$X$", r"$U,K$", r"$\Gamma$"]

    labels = read_kpoint_labels(kpoints)


    # density of states
    # dosrun = Vasprun(vasprun_dos)
    dosrun = Vasprun(vasprun_bands)
    spd_dos = dosrun.complete_dos.get_spd_dos()

    # bands
    run = Vasprun(vasprun_bands, parse_projected_eigen=True)
    bands = run.get_band_structure(kpoints,
                                   line_mode=True,
                                   efermi=dosrun.efermi)

    # set up matplotlib plot
    # ----------------------

    # general options for plot
    font = {'family': 'serif', 'size': 24}
    plt.rc('font', **font)

    # set up 2 graph with aspec ration 2/1
    # plot 1: bands diagram
    # plot 2: Density of States
    gs = GridSpec(1, 2, width_ratios=[2, 1])
    fig = plt.figure(figsize=(11.69, 8.27))
    # fig.suptitle("Bands diagram of copper")
    ax1 = plt.subplot(gs[0])
    ax2 = plt.subplot(gs[1])  # , sharey=ax1)

    # set ylim for the plot
    # ---------------------
    if ylim[0]:
        emin = ylim[0]
    else: 
        emin = -10.
    if ylim[1]:
        emax = ylim[1]
    else: 
        emax =  10.

    ax1.set_ylim(emin, emax)
    ax2.set_ylim(emin, emax)

    # Band Diagram
    # ------------
    name = element 
    pbands = bands.get_projections_on_elements_and_orbitals({name: ["s", "p", "d"]})
    # print(pbands)

    # compute s, p, d normalized contributions
    contrib = np.zeros((bands.nb_bands, len(bands.kpoints), 3))
    for b in range(bands.nb_bands):
        for k in range(len(bands.kpoints)):
            sc = pbands[Spin.up][b][k][name]["s"]**2
            pc = pbands[Spin.up][b][k][name]["p"]**2
            dc = pbands[Spin.up][b][k][name]["d"]**2
            tot = sc + pc + dc
            if tot != 0.0:
                contrib[b, k, 0] = sc / tot
                contrib[b, k, 1] = pc / tot
                contrib[b, k, 2] = dc / tot

    # plot bands using rgb mapping
    for b in range(bands.nb_bands):
        rgbline(ax1,
                range(len(bands.kpoints)),
                [e - bands.efermi for e in bands.bands[Spin.up][b]],
                contrib[b, :, 0],
                contrib[b, :, 1],
                contrib[b, :, 2])

    # style
    ax1.set_xlabel("k-points")
    ax1.set_ylabel(r"$E - E_f$   /   eV")
    ax1.grid()

    # fermi level at 0
    ax1.hlines(y=0, xmin=0, xmax=len(bands.kpoints), color="k", linestyle = '--', lw=1)

    # labels
    nlabs = len(labels)
    step = len(bands.kpoints) / (nlabs - 1)
    for i, lab in enumerate(labels):
        ax1.vlines(i * step, emin, emax, "k")
    ax1.set_xticks([i * step for i in range(nlabs)])
    ax1.set_xticklabels(labels)

    ax1.set_xlim(0, len(bands.kpoints))

    # Density of states
    # ----------------

    ax2.set_yticklabels([])
    ax2.grid()
    ax2.set_xlim(1e-4, 5)
    ax2.set_xticklabels([])
    ax2.hlines(y=0, xmin=0, xmax=5, color="k", lw=2)
    ax2.set_xlabel("Density of States", labelpad=28)

    # spd contribution
    ax2.plot(spd_dos[OrbitalType.s].densities[Spin.up],
             dosrun.tdos.energies - dosrun.efermi,
             "r-", label="3s", lw=2)
    ax2.plot(spd_dos[OrbitalType.p].densities[Spin.up],
             dosrun.tdos.energies - dosrun.efermi,
             "g-", label="3p", lw=2)
    ax2.plot(spd_dos[OrbitalType.d].densities[Spin.up],
             dosrun.tdos.energies - dosrun.efermi,
             "b-", label="3d", lw=2)

    # total dos
    ax2.fill_between(dosrun.tdos.densities[Spin.up],
                     0,
                     dosrun.tdos.energies - dosrun.efermi,
                     color=(0.7, 0.7, 0.7),
                     facecolor=(0.7, 0.7, 0.7))

    ax2.plot(dosrun.tdos.densities[Spin.up],
             dosrun.tdos.energies - dosrun.efermi,
             color=(0.6, 0.6, 0.6),
             label="total DOS")

    # plot format style
    # -----------------
    ax2.legend(fancybox=True, shadow=True, prop={'size': 18})
    plt.subplots_adjust(wspace=0)

    # plt.show()
    plt.savefig("figs/bands.png")