Пример #1
0
    def _get_cdos(pdos_file, site_file):
        if not (pdos_file and site_file):
            raise ValueError('Both dos.ext and site.ext are needed for PDOS')
        energies, data, efermi, nsp = _read_dos_data(pdos_file)
        if nsp == 1:
            fake_tdos = Dos(efermi, energies, {Spin.up: 0 * energies})
            spins = (Spin.up, )
        elif nsp == 2:
            fake_tdos = Dos(efermi, energies, {
                Spin.up: 0 * energies,
                Spin.down: 0 * energies
            })
            spins = (Spin.up, Spin.down)
        else:
            raise ValueError('There can\'t be {} spin channels, that makes '
                             'no sense!'.format(nsp))

        site_data = QuestaalSite.from_file(site_file)
        structure = site_data.structure

        pdoss = {}
        for site, orbital, spin in product(
                range(len(site_data.sites)),
                range(16),  # forget about g orbs
                range(len(spins))):
            if structure.sites[site] not in pdoss:
                pdoss.update({structure.sites[site]: {}})
            if Orbital(orbital) not in pdoss[structure.sites[site]]:
                pdoss[structure.sites[site]].update({Orbital(orbital): {}})

            pdoss[structure.sites[site]][Orbital(orbital)].update(
                {spins[spin]: data[site * (25 * nsp) + orbital * nsp + spin]})

        return CompleteDos(structure, fake_tdos, pdoss)
Пример #2
0
    def test_orbital_resolved_cohp(self):
        orbitals = [
            tuple((Orbital(i), Orbital(j))) for j in range(4) for i in range(4)
        ]
        self.assertIsNone(self.cohp_bise.orb_res_cohp)
        self.assertIsNone(self.coop_bise.orb_res_cohp)
        self.assertIsNone(self.cohp_fe.orb_res_cohp)
        self.assertIsNone(self.coop_fe.orb_res_cohp)
        self.assertIsNone(self.orb_notot.cohp_data["Ga1-As2"]["COHP"])
        self.assertIsNone(self.orb_notot.cohp_data["Ga1-As2"]["ICOHP"])
        for o, orbs in enumerate(self.orb.orb_res_cohp["Ga1-As2"]):
            orb_set = self.orb.orb_res_cohp["Ga1-As2"][orbs]["orbitals"]
            self.assertEqual(orb_set[0][0], 4)
            self.assertEqual(orb_set[1][0], 4)
            self.assertIn(tuple((orb_set[0][1], orb_set[1][1])), orbitals)

        # The sum of the orbital-resolved COHPs should be approximately
        # the total COHP. Due to small deviations in the LOBSTER calculation,
        # the precision is not very high though.
        cohp = self.orb.cohp_data["Ga1-As2"]["COHP"][Spin.up]
        icohp = self.orb.cohp_data["Ga1-As2"]["ICOHP"][Spin.up]
        tot = np.sum([
            self.orb.orb_res_cohp["Ga1-As2"][orbs]["COHP"][Spin.up]
            for orbs in self.orb.orb_res_cohp["Ga1-As2"]
        ],
                     axis=0)
        self.assertArrayAlmostEqual(tot, cohp, decimal=3)
        tot = np.sum([
            self.orb.orb_res_cohp["Ga1-As2"][orbs]["ICOHP"][Spin.up]
            for orbs in self.orb.orb_res_cohp["Ga1-As2"]
        ],
                     axis=0)
        self.assertArrayAlmostEqual(tot, icohp, decimal=3)
Пример #3
0
    def from_dict(d):
        """
        Args:
            A dict with all data for a band structure symm line object.

        Returns:
            A BandStructureSymmLine object
        """
        labels_dict = d['labels_dict']
        projections = {}
        structure = None
        if 'projections' in d and len(d['projections']) != 0:
            structure = Structure.from_dict(d['structure'])
            projections = {
                Spin.from_int(int(spin)): [
                    [{Orbital.from_string(orb): [
                        d['projections'][spin][i][j][orb][k]
                        for k in range(len(d['projections'][spin][i][j][orb]))]
                      for orb in d['projections'][spin][i][j]}
                     for j in range(len(d['projections'][spin][i]))]
                    for i in range(len(d['projections'][spin]))]
                for spin in d['projections']}

        return BandStructureSymmLine(
            d['kpoints'], {Spin.from_int(int(k)): d['bands'][k]
                           for k in d['bands']},
            Lattice(d['lattice_rec']['matrix']), d['efermi'],
            labels_dict, structure=structure, projections=projections)
Пример #4
0
def _get_orb_lobster(orb):
    """
    Args:
        orb: string representation of orbital
    Returns:
         Orbital
    """
    orb_labs = [
        "s",
        "p_y",
        "p_z",
        "p_x",
        "d_xy",
        "d_yz",
        "d_z^2",
        "d_xz",
        "d_x^2-y^2",
        "f_y(3x^2-y^2)",
        "f_xyz",
        "f_yz^2",
        "f_z^3",
        "f_xz^2",
        "f_z(x^2-y^2)",
        "f_x(x^2-3y^2)",
    ]

    try:
        orbital = Orbital(orb_labs.index(orb[1:]))
        return orbital
    except AttributeError:
        print("Orb not in list")
    return None
Пример #5
0
    def from_dict(cls, d):
        """
        Args:
            A dict with all data for a band structure symm line object.

        Returns:
            A BandStructureSymmLine object
        """
        # Strip the label to recover initial string (see trick used in as_dict to handle $ chars)
        labels_dict = {k.strip(): v for k, v in d['labels_dict'].items()}
        projections = {}
        structure = None
        if 'projections' in d and len(d['projections']) != 0:
            structure = Structure.from_dict(d['structure'])
            projections = {
                Spin.from_int(int(spin)): [
                    [{Orbital.from_string(orb): [
                        d['projections'][spin][i][j][orb][k]
                        for k in range(len(d['projections'][spin][i][j][orb]))]
                      for orb in d['projections'][spin][i][j]}
                     for j in range(len(d['projections'][spin][i]))]
                    for i in range(len(d['projections'][spin]))]
                for spin in d['projections']}

        return BandStructureSymmLine(
            d['kpoints'], {Spin.from_int(int(k)): d['bands'][k]
                           for k in d['bands']},
            Lattice(d['lattice_rec']['matrix']), d['efermi'],
            labels_dict, structure=structure, projections=projections)
Пример #6
0
 def get_dos_from_id(self, task_id):
     """
     Overrides the get_dos_from_id for the MIT gridfs format.
     """
     args = {'task_id': task_id}
     fields = ['calculations']
     structure = self.get_structure_from_id(task_id)
     dosid = None
     for r in self.query(fields, args):
         dosid = r['calculations'][-1]['dos_fs_id']
     if dosid != None:
         self._fs = gridfs.GridFS(self.db, 'dos_fs')
         with self._fs.get(dosid) as dosfile:
             s = dosfile.read()
             try:
                 d = json.loads(s)
             except:
                 s = zlib.decompress(s)
                 d = json.loads(s)
             tdos = Dos.from_dict(d)
             pdoss = {}
             for i in range(len(d['pdos'])):
                 ados = d['pdos'][i]
                 all_ados = {}
                 for j in range(len(ados)):
                     orb = Orbital.from_vasp_index(j)
                     odos = ados[str(orb)]
                     all_ados[orb] = {Spin.from_int(int(k)): v
                                      for k, v
                                      in odos['densities'].items()}
                 pdoss[structure[i]] = all_ados
             return CompleteDos(structure, tdos, pdoss)
     return None
Пример #7
0
    def from_dict(cls, d):
        """
        Args:
            A dict with all data for a band structure symm line object.

        Returns:
            A BandStructureSymmLine object
        """
        labels_dict = d['labels_dict']
        projections = {}
        structure = None
        if 'projections' in d and len(d['projections']) != 0:
            structure = Structure.from_dict(d['structure'])
            projections = {
                Spin.from_int(int(spin)):
                [[{
                    Orbital.from_string(orb): [
                        d['projections'][spin][i][j][orb][k]
                        for k in range(len(d['projections'][spin][i][j][orb]))
                    ]
                    for orb in d['projections'][spin][i][j]
                } for j in range(len(d['projections'][spin][i]))]
                 for i in range(len(d['projections'][spin]))]
                for spin in d['projections']
            }

        return BandStructureSymmLine(
            d['kpoints'],
            {Spin.from_int(int(k)): d['bands'][k]
             for k in d['bands']},
            Lattice(d['lattice_rec']['matrix']),
            d['efermi'],
            labels_dict,
            structure=structure,
            projections=projections)
Пример #8
0
 def get_dos_from_id(self, task_id):
     """
     Overrides the get_dos_from_id for the MIT gridfs format.
     """
     args = {'task_id': task_id}
     fields = ['calculations']
     structure = self.get_structure_from_id(task_id)
     dosid = None
     for r in self.query(fields, args):
         dosid = r['calculations'][-1]['dos_fs_id']
     if dosid is not None:
         self._fs = gridfs.GridFS(self.db, 'dos_fs')
         with self._fs.get(dosid) as dosfile:
             s = dosfile.read()
             try:
                 d = json.loads(s)
             except:
                 s = zlib.decompress(s)
                 d = json.loads(s.decode("utf-8"))
             tdos = Dos.from_dict(d)
             pdoss = {}
             for i in range(len(d['pdos'])):
                 ados = d['pdos'][i]
                 all_ados = {}
                 for j in range(len(ados)):
                     orb = Orbital(j)
                     odos = ados[str(orb)]
                     all_ados[orb] = {Spin(int(k)): v
                                      for k, v
                                      in odos['densities'].items()}
                 pdoss[structure[i]] = all_ados
             return CompleteDos(structure, tdos, pdoss)
     return None
Пример #9
0
    def _get_bond_data(line):
        """
        Subroutine to extract bond label, site indices, and length from
        a LOBSTER header line. The site indices are zero-based, so they
        can be easily used with a Structure object.

        Example header line: No.4:Fe1->Fe9(2.4524893531900283)
        Example header line for orbtial-resolved COHP:
            No.1:Fe1[3p_x]->Fe2[3d_x^2-y^2](2.456180552772262)

        Args:
            line: line in the COHPCAR header describing the bond.

        Returns:
            Dict with the bond label, the bond length, a tuple of the site
            indices, a tuple containing the orbitals (if orbital-resolved),
            and a label for the orbitals (if orbital-resolved).
        """

        orb_labs = [
            "s", "p_y", "p_z", "p_x", "d_xy", "d_yz", "d_z^2", "d_xz",
            "d_x^2-y^2", "f_y(3x^2-y^2)", "f_xyz", "f_yz^2", "f_z^3", "f_xz^2",
            "f_z(x^2-y^2)", "f_x(x^2-3y^2)"
        ]

        line = line.rsplit("(", 1)
        # bondnumber = line[0].replace("->", ":").replace(".", ":").split(':')[1]
        length = float(line[-1][:-1])

        sites = line[0].replace("->", ":").split(":")[1:3]
        site_indices = tuple(
            int(re.split(r"\D+", site)[1]) - 1 for site in sites)

        # species = tuple(re.split(r"\d+", site)[0] for site in sites)
        if "[" in sites[0]:
            orbs = [re.findall(r"\[(.*)\]", site)[0] for site in sites]
            orbitals = [
                tuple((int(orb[0]), Orbital(orb_labs.index(orb[1:]))))
                for orb in orbs
            ]
            orb_label = "%d%s-%d%s" % (orbitals[0][0], orbitals[0][1].name,
                                       orbitals[1][0], orbitals[1][1].name)

        else:
            orbitals = None
            orb_label = None

        # a label based on the species alone is not feasible, there can be more than one bond for each atom combination
        # label = "%s" % (bondnumber)

        bond_data = {
            "length": length,
            "sites": site_indices,
            "orbitals": orbitals,
            "orb_label": orb_label
        }
        return bond_data
Пример #10
0
    def get_complete_dos(self, structure):
        """
        Gives a CompleteDos object with the DOS from the interpolated projected band structure
        Args:
            the structure (necessary to identify sites for projection)

        Returns:
            a CompleteDos object
        """
        pdoss = {}
        for s in self._dos_partial:
            if structure.sites[int(s)] not in pdoss:
                pdoss[structure.sites[int(s)]] = {}
            for o in self._dos_partial[s]:
                if Orbital.from_string(o) not in pdoss[structure.sites[int(s)]]:
                    pdoss[structure.sites[int(s)]][Orbital.from_string(o)] = {}
                pdoss[structure.sites[int(s)]][Orbital.from_string(o)][Spin.up] = self._dos_partial[s][o]
        return CompleteDos(structure, total_dos=self.dos, pdoss=pdoss)
Пример #11
0
    def get_complete_dos(self, structure):
        """
        Gives a CompleteDos object with the DOS from the interpolated projected band structure
        Args:
            the structure (necessary to identify sites for projection)

        Returns:
            a CompleteDos object
        """
        pdoss = {}
        for s in self._dos_partial:
            if structure.sites[int(s)] not in pdoss:
                pdoss[structure.sites[int(s)]] = {}
            for o in self._dos_partial[s]:
                if Orbital.from_string(o) not in pdoss[structure.sites[int(s)]]:
                    pdoss[structure.sites[int(s)]][Orbital.from_string(o)] = {}
                pdoss[structure.sites[int(s)]][Orbital.from_string(o)][Spin.up] = self._dos_partial[s][o]
        return CompleteDos(structure, total_dos=self.dos, pdoss=pdoss)
Пример #12
0
 def from_dict(d):
     """
     Returns PDos object from dict representation.
     """
     return PDos(
         d["efermi"],
         d["energies"],
         {Spin.from_int(int(k)): v for k, v in d["densities"].items()},
         Orbital.from_string(d["orbital"]),
     )
Пример #13
0
    def get_orbital_resolved_cohp(self, label, orbitals):
        """
        Get orbital-resolved COHP.

        Args:
            label: bond label (Lobster: labels as in ICOHPLIST/ICOOPLIST.lobster).

            orbitals: The orbitals as a label, or list or tuple of the form
                [(n1, orbital1), (n2, orbital2)]. Orbitals can either be str,
                int, or Orbital.

        Returns:
            A Cohp object if CompleteCohp contains orbital-resolved cohp,
            or None if it doesn't.

        Note: It currently assumes that orbitals are str if they aren't the
            other valid types. This is not ideal, but the easiest way to
            avoid unicode issues between python 2 and python 3.
        """
        if self.orb_res_cohp is None:
            return None
        if isinstance(orbitals, (list, tuple)):
            cohp_orbs = [
                d["orbitals"] for d in self.orb_res_cohp[label].values()
            ]
            orbs = []
            for orbital in orbitals:
                if isinstance(orbital[1], int):
                    orbs.append(tuple((orbital[0], Orbital(orbital[1]))))
                elif isinstance(orbital[1], Orbital):
                    orbs.append(tuple((orbital[0], orbital[1])))
                elif isinstance(orbital[1], str):
                    orbs.append(tuple((orbital[0], Orbital[orbital[1]])))
                else:
                    raise TypeError("Orbital must be str, int, or Orbital.")
            orb_index = cohp_orbs.index(orbs)
            orb_label = list(self.orb_res_cohp[label].keys())[orb_index]
        elif isinstance(orbitals, str):
            orb_label = orbitals
        else:
            raise TypeError("Orbitals must be str, list, or tuple.")
        try:
            icohp = self.orb_res_cohp[label][orb_label]["ICOHP"]
        except KeyError:
            icohp = None
        return Cohp(
            self.efermi,
            self.energies,
            self.orb_res_cohp[label][orb_label]["COHP"],
            icohp=icohp,
            are_coops=self.are_coops,
        )
Пример #14
0
 def from_dict(cls, d):
     """
     Returns CompleteDos object from dict representation.
     """
     tdos = Dos.from_dict(d)
     struct = Structure.from_dict(d["structure"])
     pdoss = {}
     for i in range(len(d["pdos"])):
         at = struct[i]
         orb_dos = {}
         for orb_str, odos in d["pdos"][i].items():
             orb = Orbital.from_string(orb_str)
             orb_dos[orb] = {Spin.from_int(int(k)): v
                             for k, v in odos["densities"].items()}
         pdoss[at] = orb_dos
     return CompleteDos(struct, tdos, pdoss)
Пример #15
0
 def from_dict(cls, d):
     """
     Returns CompleteDos object from dict representation.
     """
     tdos = Dos.from_dict(d)
     struct = Structure.from_dict(d["structure"])
     pdoss = {}
     for i in range(len(d["pdos"])):
         at = struct[i]
         orb_dos = {}
         for orb_str, odos in d["pdos"][i].items():
             orb = Orbital.from_string(orb_str)
             orb_dos[orb] = {Spin.from_int(int(k)): v
                             for k, v in odos["densities"].items()}
         pdoss[at] = orb_dos
     return CompleteDos(struct, tdos, pdoss)
Пример #16
0
    def from_old_dict(cls, d):
        """
        Args:
            d (dict): A dict with all data for a band structure symm line
                object.
        Returns:
            A BandStructureSymmLine object
        """
        # Strip the label to recover initial string (see trick used in as_dict to handle $ chars)
        labels_dict = {k.strip(): v for k, v in d["labels_dict"].items()}
        projections = {}
        structure = None
        if "projections" in d and len(d["projections"]) != 0:
            structure = Structure.from_dict(d["structure"])
            projections = {}
            for spin in d["projections"]:
                dd = []
                for i in range(len(d["projections"][spin])):
                    ddd = []
                    for j in range(len(d["projections"][spin][i])):
                        dddd = []
                        for k in range(len(d["projections"][spin][i][j])):
                            ddddd = []
                            orb = Orbital(k).name
                            for l in range(
                                    len(d["projections"][spin][i][j][orb])):
                                ddddd.append(
                                    d["projections"][spin][i][j][orb][l])
                            dddd.append(np.array(ddddd))
                        ddd.append(np.array(dddd))
                    dd.append(np.array(ddd))
                projections[Spin(int(spin))] = np.array(dd)

        return BandStructure(
            d["kpoints"],
            {Spin(int(k)): d["bands"][k]
             for k in d["bands"]},
            Lattice(d["lattice_rec"]["matrix"]),
            d["efermi"],
            labels_dict,
            structure=structure,
            projections=projections,
        )
Пример #17
0
    def get_projections_on_elements_and_orbitals(self, el_orb_spec):
        """
        Method returning a dictionary of projections on elements and specific
        orbitals

        Args:
            el_orb_spec: A dictionary of Elements and Orbitals for which we want
                to have projections on. It is given as: {Element:[orbitals]},
                e.g., {'Cu':['d','s']}

        Returns:
            A dictionary of projections on elements in the
            {Spin.up:[][{Element:{orb:values}}],
            Spin.down:[][{Element:{orb:values}}]} format
            if there is no projections in the band structure returns an empty
            dict.
        """
        result = {}
        structure = self.structure
        el_orb_spec = {get_el_sp(el): orbs for el, orbs in el_orb_spec.items()}
        for spin, v in self.projections.items():
            result[spin] = [
                [
                    {str(e): collections.defaultdict(float) for e in el_orb_spec}
                    for i in range(len(self.kpoints))
                ]
                for j in range(self.nb_bands)
            ]

            for i, j, k in itertools.product(
                range(self.nb_bands),
                range(len(self.kpoints)),
                range(structure.num_sites),
            ):
                sp = structure[k].specie
                for orb_i in range(len(v[i][j])):
                    o = Orbital(orb_i).name[0]
                    if sp in el_orb_spec:
                        if o in el_orb_spec[sp]:
                            result[spin][i][j][str(sp)][o] += v[i][j][orb_i][k]
        return result
Пример #18
0
    def from_old_dict(cls, d):
        """
        Args:
            d (dict): A dict with all data for a band structure symm line
                object.
        Returns:
            A BandStructureSymmLine object
        """
        # Strip the label to recover initial string (see trick used in as_dict to handle $ chars)
        labels_dict = {k.strip(): v for k, v in d['labels_dict'].items()}
        projections = {}
        structure = None
        if 'projections' in d and len(d['projections']) != 0:
            structure = Structure.from_dict(d['structure'])
            projections = {}
            for spin in d['projections']:
                dd = []
                for i in range(len(d['projections'][spin])):
                    ddd = []
                    for j in range(len(d['projections'][spin][i])):
                        dddd = []
                        for k in range(len(d['projections'][spin][i][j])):
                            ddddd = []
                            orb = Orbital(k).name
                            for l in range(
                                    len(d['projections'][spin][i][j][orb])):
                                ddddd.append(
                                    d['projections'][spin][i][j][orb][l])
                            dddd.append(ddddd)
                        ddd.append(dddd)
                    dd.append(ddd)
                projections[spin] = dd

        return BandStructureSymmLine(
            d['kpoints'], {Spin(int(k)): d['bands'][k]
                           for k in d['bands']},
            Lattice(d['lattice_rec']['matrix']),
            d['efermi'],
            labels_dict,
            structure=structure,
            projections=projections)
Пример #19
0
    def from_dict(cls, d):
        """
        Args:
            A dict with all data for a band structure symm line object.

        Returns:
            A BandStructureSymmLine object
        """
        labels_dict = d["labels_dict"]
        projections = {}
        structure = None
        if "projections" in d and len(d["projections"]) != 0:
            structure = Structure.from_dict(d["structure"])
            projections = {
                Spin.from_int(int(spin)): [
                    [
                        {
                            Orbital.from_string(orb): [
                                d["projections"][spin][i][j][orb][k]
                                for k in range(len(d["projections"][spin][i][j][orb]))
                            ]
                            for orb in d["projections"][spin][i][j]
                        }
                        for j in range(len(d["projections"][spin][i]))
                    ]
                    for i in range(len(d["projections"][spin]))
                ]
                for spin in d["projections"]
            }

        return BandStructureSymmLine(
            d["kpoints"],
            {Spin.from_int(int(k)): d["bands"][k] for k in d["bands"]},
            Lattice(d["lattice_rec"]["matrix"]),
            d["efermi"],
            labels_dict,
            structure=structure,
            projections=projections,
        )
Пример #20
0
    def from_dict(cls, d):
        """
        Args:
            A dict with all data for a band structure symm line object.

        Returns:
            A BandStructureSymmLine object
        """
        # Strip the label to recover initial string (see trick used in as_dict to handle $ chars)
        labels_dict = {k.strip(): v for k, v in d['labels_dict'].items()}
        projections = {}
        structure = None
        if 'projections' in d and len(d['projections']) != 0:
            structure = Structure.from_dict(d['structure'])
            projections = {
                Spin.from_int(int(spin)):
                [[{
                    Orbital.from_string(orb): [
                        d['projections'][spin][i][j][orb][k]
                        for k in range(len(d['projections'][spin][i][j][orb]))
                    ]
                    for orb in d['projections'][spin][i][j]
                } for j in range(len(d['projections'][spin][i]))]
                 for i in range(len(d['projections'][spin]))]
                for spin in d['projections']
            }

        return BandStructureSymmLine(
            d['kpoints'],
            {Spin.from_int(int(k)): d['bands'][k]
             for k in d['bands']},
            Lattice(d['lattice_rec']['matrix']),
            d['efermi'],
            labels_dict,
            structure=structure,
            projections=projections)
Пример #21
0
 def test_init(self):
     for i, orb in enumerate(Orbital.all_orbitals):
         self.assertEqual(Orbital.from_vasp_index(i), orb)
     self.assertRaises(IndexError, Orbital.from_vasp_index, 100)
Пример #22
0
 def test_init(self):
     for i, orb in enumerate(Orbital.all_orbitals):
         self.assertEqual(Orbital.from_vasp_index(i), orb)
     self.assertRaises(IndexError, Orbital.from_vasp_index, 100)
Пример #23
0
 def test_cached(self):
     self.assertEquals(id(Orbital.from_vasp_index(0)), id(Orbital.s))
Пример #24
0
 def test_cached(self):
     self.assertEqual(id(Orbital(0)), id(Orbital.s))
Пример #25
0
 def test_init(self):
     for orb in Orbital:
         self.assertEqual(Orbital(orb.value), orb)
     self.assertRaises(ValueError, Orbital, 100)
Пример #26
0
 def test_cached(self):
     self.assertEqual(id(Orbital.from_vasp_index(0)), id(Orbital.s))
Пример #27
0
    def test_orbital_resolved_cohp(self):
        orbitals = [
            tuple((Orbital(i), Orbital(j))) for j in range(4) for i in range(4)
        ]
        self.assertIsNone(self.cohp_bise.orb_res_cohp)
        self.assertIsNone(self.coop_bise.orb_res_cohp)
        self.assertIsNone(self.cohp_fe.orb_res_cohp)
        self.assertIsNone(self.coop_fe.orb_res_cohp)
        self.assertIsNone(self.orb_notot.cohp_data["1"]["COHP"])
        self.assertIsNone(self.orb_notot.cohp_data["1"]["ICOHP"])
        for orbs in self.orb.orb_res_cohp["1"]:
            orb_set = self.orb.orb_res_cohp["1"][orbs]["orbitals"]
            # print(orb_set[0][0])
            self.assertEqual(orb_set[0][0], 4)
            self.assertEqual(orb_set[1][0], 4)
            self.assertIn(tuple((orb_set[0][1], orb_set[1][1])), orbitals)

        # test d and f orbitals
        comparelist = [
            5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
            5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
            6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7,
            7, 7
        ]
        comparelist2 = [
            "f0", "f0", "f0", "f0", "f1", "f1", "f1", "f1", "f2", "f2", "f2",
            "f2", "f3", "f3", "f3", "f3", "f_1", "f_1", "f_1", "f_1", "f_2",
            "f_2", "f_2", "f_2", "f_3", "f_3", "f_3", "f_3", "dx2", "dx2",
            "dx2", "dx2", "dxy", "dxy", "dxy", "dxy", "dxz", "dxz", "dxz",
            "dxz", "dyz", "dyz", "dyz", "dyz", "dz2", "dz2", "dz2", "dz2",
            "px", "px", "px", "px", "py", "py", "py", "py", "pz", "pz", "pz",
            "pz", "s", "s", "s", "s", "s", "s", "s", "s"
        ]
        for iorb, orbs in enumerate(sorted(
                self.cohp_Na2UO4.orb_res_cohp["49"])):
            orb_set = self.cohp_Na2UO4.orb_res_cohp["49"][orbs]["orbitals"]
            self.assertEqual(orb_set[0][0], comparelist[iorb])
            self.assertEqual(str(orb_set[0][1]), comparelist2[iorb])

        # The sum of the orbital-resolved COHPs should be approximately
        # the total COHP. Due to small deviations in the LOBSTER calculation,
        # the precision is not very high though.
        cohp = self.orb.cohp_data["1"]["COHP"][Spin.up]
        icohp = self.orb.cohp_data["1"]["ICOHP"][Spin.up]
        tot = np.sum([
            self.orb.orb_res_cohp["1"][orbs]["COHP"][Spin.up]
            for orbs in self.orb.orb_res_cohp["1"]
        ],
                     axis=0)
        self.assertArrayAlmostEqual(tot, cohp, decimal=3)
        tot = np.sum([
            self.orb.orb_res_cohp["1"][orbs]["ICOHP"][Spin.up]
            for orbs in self.orb.orb_res_cohp["1"]
        ],
                     axis=0)
        self.assertArrayAlmostEqual(tot, icohp, decimal=3)

        # Lobster 3.1
        cohp_KF = self.cohp_KF.cohp_data["1"]["COHP"][Spin.up]
        icohp_KF = self.cohp_KF.cohp_data["1"]["ICOHP"][Spin.up]
        tot_KF = np.sum([
            self.cohp_KF.orb_res_cohp["1"][orbs]["COHP"][Spin.up]
            for orbs in self.cohp_KF.orb_res_cohp["1"]
        ],
                        axis=0)
        self.assertArrayAlmostEqual(tot_KF, cohp_KF, decimal=3)
        tot_KF = np.sum([
            self.cohp_KF.orb_res_cohp["1"][orbs]["ICOHP"][Spin.up]
            for orbs in self.cohp_KF.orb_res_cohp["1"]
        ],
                        axis=0)
        self.assertArrayAlmostEqual(tot_KF, icohp_KF, decimal=3)

        # d and f orbitals
        cohp_Na2UO4 = self.cohp_Na2UO4.cohp_data["49"]["COHP"][Spin.up]
        icohp_Na2UO4 = self.cohp_Na2UO4.cohp_data["49"]["ICOHP"][Spin.up]
        tot_Na2UO4 = np.sum([
            self.cohp_Na2UO4.orb_res_cohp["49"][orbs]["COHP"][Spin.up]
            for orbs in self.cohp_Na2UO4.orb_res_cohp["49"]
        ],
                            axis=0)
        self.assertArrayAlmostEqual(tot_Na2UO4, cohp_Na2UO4, decimal=3)
        tot_Na2UO4 = np.sum([
            self.cohp_Na2UO4.orb_res_cohp["49"][orbs]["ICOHP"][Spin.up]
            for orbs in self.cohp_Na2UO4.orb_res_cohp["49"]
        ],
                            axis=0)
        self.assertArrayAlmostEqual(tot_Na2UO4, icohp_Na2UO4, decimal=3)
Пример #28
0
def projected_dos():
   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)
   nedos=vsr.parameters['NEDOS']
   struct=vsr.final_structure
   pdos=vsr.pdos

   filename='PROCAR'
   check_file(filename)
   step_count+=1
   proc_str="Reading Data From "+ filename +" File ..."
   procs(proc_str,step_count,sp='-->>')
   procar=Procar(filename)
   nbands=procar.nbands
   nions=procar.nions
   norbitals=len(procar.orbitals)
   nkpoints=procar.nkpoints

   (atom_index,in_str)=atom_selection(struct)

   if len(atom_index)==0:
      print("No atoms selected!")
      return
#   print(atom_index)

   if vsr.is_spin:
      proc_str="This Is a Spin-polarized Calculation."
      procs(proc_str,0,sp='-->>')

      contrib=np.zeros((nedos,norbitals+1,2))
      energies=vsr.tdos.energies-vsr.efermi
      for ispin in [0,1]:
          if ispin==0:
              spin=Spin.up
              s_name='Up'
          else:
              spin=Spin.down
              s_name='Down'

          contrib[:,0,ispin]=energies  
          for i in atom_index:
                for j in range(norbitals):
                     contrib[:,j+1,ispin]=contrib[:,j+1,ispin]+pdos[i][Orbital(j)][spin]

          step_count+=1
          filename="PDOS_"+s_name+".dat"
          proc_str="Writting Projected DOS Data to "+ filename +" File ..."
          procs(proc_str,step_count,sp='-->>')
          tmp1_str="#%%(key1)+12s"
          tmp2_dic={'key1':'Energy(ev)'}
          for i in range(norbitals):
              tmp1_str+="%(key"+str(i+2)+")+12s"
              tmp2_dic["key"+str(i+2)]=procar.orbitals[i]

#          print(tmp1_str)
          atom_index_str=[str(x+1) for x in atom_index]
          head_line1="#String: "+in_str+'\n#Selected atom: ' +' '.join(atom_index_str)+'\n'
          head_line2=tmp1_str % tmp2_dic
          head_line=head_line1+head_line2
          write_col_data(filename,contrib[:,:,ispin],head_line)

   else:
      if vsr.parameters['LNONCOLLINEAR']:
         proc_str="This Is a Non-Collinear Calculation."
         procs(proc_str,0,sp='-->>')
      else:
         proc_str="This Is a Non-Spin Calculation."
         procs(proc_str,0,sp='-->>')

      contrib=np.zeros((nedos,norbitals+1))
      energies=vsr.tdos.energies-vsr.efermi
      contrib[:,0]=energies
      for i in atom_index:
            for j in range(norbitals):
                 contrib[:,j+1]=contrib[:,j+1]+pdos[i][Orbital(j)][Spin.up]

      step_count+=1
      filename="PDOS.dat"
      proc_str="Writting Projected DOS Data to "+ filename +" File ..."
      procs(proc_str,step_count,sp='-->>')
      tmp1_str="#%(key1)+12s%(key2)+12s"
      tmp2_dic={'key1':'K-Distance','key2':'Energy(ev)'}
      for i in range(norbitals):
          tmp1_str+="%(key"+str(i+3)+")+12s"
          tmp2_dic["key"+str(i+3)]=procar.orbitals[i]

#      print(tmp1_str)
      atom_index_str=[str(x+1) for x in atom_index]
      head_line1="#String: "+in_str+'\n#Selected atom: ' +' '.join(atom_index_str)+'\n'
      head_line2=tmp1_str % tmp2_dic
      head_line=head_line1+head_line2
      write_col_data(filename,contrib,head_line)