Example #1
0
    def get_cohp(self, spin=None, integrated=False):
        """
        Returns the COHP or ICOHP for a particular spin.

        Args:
            spin: Spin. Can be parsed as spin object, integer (-1/1)
                or str ("up"/"down")
            integrated: Return COHP (False) or ICOHP (True)

        Returns:
            Returns the CHOP or ICOHP for the input spin. If Spin is
            None and both spins are present, both spins will be returned
            as a dictionary.
        """
        if not integrated:
            populations = self.cohp
        else:
            populations = self.icohp

        if populations is None:
            return None
        elif spin is None:
            return populations
        else:
            if isinstance(spin, int):
                spin = Spin(spin)
            elif isinstance(spin, str):
                s = {"up": 1, "down": -1}[spin.lower()]
                spin = Spin(s)
            return {spin: populations[spin]}
Example #2
0
    def has_antibnd_states_below_efermi(self, spin=None, limit=0.01):
        """
        Returns dict indicating if there are antibonding states below the Fermi level depending on the spin
            spin: Spin
            limit: -COHP smaller -limit will be considered.

        """
        warnings.warn("This method has not been tested on many examples. Check the parameter limit, pls!")

        populations = self.cohp
        number_energies_below_efermi = len([x for x in self.energies if x <= self.efermi])

        if populations is None:
            return None
        elif spin is None:
            dict_to_return = {}
            for spin, cohpvalues in populations.items():
                if (max(cohpvalues[0:number_energies_below_efermi])) > limit:
                    dict_to_return[spin] = True
                else:
                    dict_to_return[spin] = False
        else:
            dict_to_return = {}
            if isinstance(spin, int):
                spin = Spin(spin)
            elif isinstance(spin, str):
                s = {"up": 1, "down": -1}[spin.lower()]
                spin = Spin(s)
            if (max(populations[spin][0:number_energies_below_efermi])) > limit:
                dict_to_return[spin] = True
            else:
                dict_to_return[spin] = False

        return dict_to_return
    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)
Example #4
0
    def from_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 d.get('projections'):
            structure = Structure.from_dict(d['structure'])
            projections = {
                Spin(int(spin)): np.array(v)
                for spin, v in d["projections"].items()
            }

        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)
Example #5
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])):
                        ddd.append(d["projections"][spin][i][j])
                    dd.append(np.array(ddd))
                projections[Spin(int(spin))] = np.array(dd)

        return LobsterBandStructureSymmLine(
            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,
        )
Example #6
0
    def from_dict(cls, d):
        """
        Create from dict.

        Args:
            A dict with all data for a band structure object.

        Returns:
            A BandStructure object
        """
        labels_dict = d['labels_dict']
        projections = {}
        structure = None
        if isinstance(list(d['bands'].values())[0], dict):
            eigenvals = {
                Spin(int(k)): np.array(d['bands'][k]['data'])
                for k in d['bands']
            }
        else:
            eigenvals = {Spin(int(k)): d['bands'][k] for k in d['bands']}
        if 'structure' in d:
            structure = Structure.from_dict(d['structure'])
        if d.get('projections'):
            projections = {
                Spin(int(spin)): np.array(v)
                for spin, v in d["projections"].items()
            }

        return BandStructure(d['kpoints'],
                             eigenvals,
                             Lattice(d['lattice_rec']['matrix']),
                             d['efermi'],
                             labels_dict,
                             structure=structure,
                             projections=projections)
Example #7
0
    def read_vasprun(vasprunfile):
        vasprun = BSVasprun(vasprunfile)
        vdata = vasprun.as_dict()
        # pprint(vdata['input']['crystal']['lattice']['matrix'])
        # pprint(vdata['input']['lattice_rec']['matrix'])
        real_latt = vdata['input']['crystal']['lattice']['matrix']
        real_latt = np.array(real_latt)
        reci_matrix = 2 * np.pi * np.linalg.inv(real_latt).T
        eigens_all = vasprun.eigenvalues
        if Spin(-1) not in eigens_all.keys():
            eigens_up = eigens_all[Spin(1)]
            eigens_down = None
        else:
            eigens_up = eigens_all[Spin(1)]
            eigens_down = eigens_all[Spin(
                -1)]  # eigens[ikpt][iband] = eigen, occu
        nelect = vdata['input']['parameters']['NELECT']
        efermi = vasprun.efermi
        kcoords = []
        for kpt in vdata['input']['kpoints']['actual_points']:
            kcoords.append(kpt['abc'])

        d = OrderedDict()
        d['reci_mat'] = reci_matrix
        d['nelect'] = int(nelect)
        d['efermi'] = efermi
        d['eigens_up'] = eigens_up
        d['eigens_down'] = eigens_down
        d['kcoords'] = np.array(kcoords)
        return d
Example #8
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)
Example #9
0
    def has_antibnd_states_below_efermi(self, spin=None, limit=0.01):
        """
        Returns dict indicating if there are antibonding states below the Fermi level depending on the spin
            spin: Spin
            limit: -COHP smaller -limit will be considered.

        """
        warnings.warn("This method has not been tested on many examples. Check the parameter limit, pls!")

        populations = self.cohp
        number_energies_below_efermi = len([x for x in self.energies if x <= self.efermi])

        if populations is None:
            return None
        elif spin is None:
            dict_to_return = {}
            for spin, cohpvalues in populations.items():
                if (max(cohpvalues[0:number_energies_below_efermi])) > limit:
                    dict_to_return[spin] = True
                else:
                    dict_to_return[spin] = False
        else:
            dict_to_return = {}
            if isinstance(spin, int):
                spin = Spin(spin)
            elif isinstance(spin, str):
                s = {"up": 1, "down": -1}[spin.lower()]
                spin = Spin(s)
            if (max(populations[spin][0:number_energies_below_efermi])) > limit:
                dict_to_return[spin] = True
            else:
                dict_to_return[spin] = False

        return dict_to_return
Example #10
0
    def from_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 = {
                Spin(int(spin)): [[{
                    Orbital[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(int(k)): d['bands'][k]
                           for k in d['bands']},
            Lattice(d['lattice_rec']['matrix']),
            d['efermi'],
            labels_dict,
            structure=structure,
            projections=projections)
Example #11
0
    def get_cohp(self, spin=None, integrated=False):
        """
        Returns the COHP or ICOHP for a particular spin.

        Args:
            spin: Spin. Can be parsed as spin object, integer (-1/1)
                or str ("up"/"down")
            integrated: Return COHP (False) or ICOHP (True)

        Returns:
            Returns the CHOP or ICOHP for the input spin. If Spin is
            None and both spins are present, both spins will be returned
            as a dictionary.
        """
        if not integrated:
            populations = self.cohp
        else:
            populations = self.icohp

        if populations is None:
            return None
        elif spin is None:
            return populations
        else:
            if isinstance(spin, six.integer_types):
                spin = Spin(spin)
            elif isinstance(spin, six.string_types):
                s = {"up": 1, "down": -1}[spin.lower()]
                spin = Spin(s)
            return {spin: populations[spin]}
Example #12
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)
Example #13
0
    def from_dict(cls, d):
        """
        Args:
            d (dict): A dict with all data for a band structure symm line
                object.

        Returns:
            A BandStructureSymmLine object
        """
        try:
            # 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 d.get('projections'):
                if isinstance(d["projections"]['1'][0][0], dict):
                    raise ValueError("Old band structure dict format detected!")
                structure = Structure.from_dict(d['structure'])
                projections = {Spin(int(spin)): np.array(v)
                               for spin, v in d["projections"].items()}

            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)
        except:
            warnings.warn("Trying from_dict failed. Now we are trying the old "
                          "format. Please convert your BS dicts to the new "
                          "format. The old format will be retired in pymatgen "
                          "5.0.")
            return BandStructureSymmLine.from_old_dict(d)
Example #14
0
    def from_dict(cls, d):
        """
        Returns CompleteCohp object from dict representation.
        """
        cohp_dict = {}
        efermi = d["efermi"]
        energies = d["energies"]
        structure = Structure.from_dict(d["structure"])
        if "bonds" in d.keys():
            bonds = {
                bond: {
                    "length":
                    d["bonds"][bond]["length"],
                    "sites":
                    tuple(
                        PeriodicSite.from_dict(site)
                        for site in d["bonds"][bond]["sites"])
                }
                for bond in d["bonds"]
            }
        else:
            bonds = None
        for label in d["COHP"]:
            cohp = {
                Spin(int(spin)): np.array(d["COHP"][label][spin])
                for spin in d["COHP"][label]
            }
            try:
                icohp = {
                    Spin(int(spin)): np.array(d["ICOHP"][label][spin])
                    for spin in d["ICOHP"][label]
                }
            except KeyError:
                icohp = None
            if label == "average":
                avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)
            else:
                cohp_dict[label] = Cohp(efermi, energies, cohp, icohp=icohp)
        if "average" not in d["COHP"].keys():
            # calculate average
            cohp = np.array([np.array(c)
                             for c in d["COHP"].values()]).mean(axis=0)
            try:
                icohp = np.array([np.array(c)
                                  for c in d["ICOHP"].values()]).mean(axis=0)
            except KeyError:
                icohp = None
            avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)

        return CompleteCohp(structure,
                            avg_cohp,
                            cohp_dict,
                            bonds=bonds,
                            are_coops=d["are_coops"])
Example #15
0
    def from_dict(cls, d):
        """
        Create from dict.

        Args:
            A dict with all data for a band structure object.

        Returns:
            A BandStructure 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 isinstance(list(d["bands"].values())[0], dict):
            eigenvals = {
                Spin(int(k)): np.array(d["bands"][k]["data"])
                for k in d["bands"]
            }
        else:
            eigenvals = {Spin(int(k)): d["bands"][k] for k in d["bands"]}

        if "structure" in d:
            structure = Structure.from_dict(d["structure"])

        try:
            if d.get("projections"):
                if isinstance(d["projections"]["1"][0][0], dict):
                    raise ValueError(
                        "Old band structure dict format detected!")
                projections = {
                    Spin(int(spin)): np.array(v)
                    for spin, v in d["projections"].items()
                }

            return cls(
                d["kpoints"],
                eigenvals,
                Lattice(d["lattice_rec"]["matrix"]),
                d["efermi"],
                labels_dict,
                structure=structure,
                projections=projections,
            )

        except Exception:
            warnings.warn("Trying from_dict failed. Now we are trying the old "
                          "format. Please convert your BS dicts to the new "
                          "format. The old format will be retired in pymatgen "
                          "5.0.")
            return cls.from_old_dict(d)
Example #16
0
    def from_dict(cls, d):
        """
        Returns a COHP object from a dict representation of the COHP.

        """
        if "ICOHP" in d:
            icohp = {Spin(int(key)): np.array(val)
                     for key, val in d["ICOHP"].items()}
        else:
            icohp = None
        return Cohp(d["efermi"], d["energies"],
                    {Spin(int(key)): np.array(val)
                     for key, val in d["COHP"].items()},
                    icohp=icohp, are_coops=d["are_coops"])
Example #17
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
Example #18
0
    def from_dict(cls, d):
        eigenvalues = {}
        # Programmatic access to enumeration members in Enum class.
        for s, v in d["eigenvalues"].items():
            eigenvalues[Spin(int(s))] = np.array(v)

        final_structure = d["final_structure"]
        if isinstance(final_structure, dict):
            final_structure = Structure.from_dict(final_structure)

        band_edge_energies = str_key_to_spin(d["band_edge_energies"])
        participation_ratio = str_key_to_spin(d["participation_ratio"])
        orbital_character = str_key_to_spin(d["orbital_character"])

        return cls(
            final_structure=final_structure,
            site_symmetry=d["site_symmetry"],
            total_energy=d["total_energy"],
            total_magnetization=d["total_magnetization"],
            eigenvalues=eigenvalues,
            kpoint_coords=d["kpoint_coords"],
            kpoint_weights=d["kpoint_weights"],
            electrostatic_potential=d["electrostatic_potential"],
            vbm=d["vbm"],
            cbm=d["cbm"],
            volume=d["volume"],
            fermi_level=d["fermi_level"],
            is_converged=d["is_converged"],
            defect_center=d["defect_center"],
            defect_coords=d["defect_coords"],
            displacements=d["displacements"],
            neighboring_sites_after_relax=d["neighboring_sites_after_relax"],
            band_edge_energies=band_edge_energies,
            participation_ratio=participation_ratio,
            orbital_character=orbital_character)
Example #19
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
Example #20
0
 def from_dict(cls, d):
     """
     Returns Dos object from dict representation of Dos.
     """
     return Dos(d["efermi"], d["energies"],
                {Spin.from_int(int(k)): v
                 for k, v in d["densities"].items()})
Example #21
0
 def from_dict(cls, d):
     """
     Returns Dos object from dict representation of Dos.
     """
     return Dos(d["efermi"], d["energies"],
                {Spin(int(k)): v
                 for k, v in d["densities"].items()})
Example #22
0
 def from_dict(cls, d):
     """
     Returns Dos object from dict representation of Dos.
     """
     dos = Dos(d["efermi"], d["energies"],
               {Spin(int(k)): v for k, v in d["densities"].items()})
     return FermiDosCarriersInfo(dos, structure=Structure.from_dict(d["structure"]),
                     nelecs=d["nelecs"])
Example #23
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"]),
     )
Example #24
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,
        )
Example #25
0
    def from_dict(cls, d):
        eigenvalues = {}
        # Programmatic access to enumeration members in Enum class.
        for s, v in d["eigenvalues"].items():
            eigenvalues[Spin(int(s))] = np.array(v)

        initial_structure = d["initial_structure"]
        perturbed_initial_structure = d["perturbed_initial_structure"]
        final_structure = d["final_structure"]

        if isinstance(initial_structure, dict):
            initial_structure = Structure.from_dict(initial_structure)
        if isinstance(perturbed_initial_structure, dict):
            perturbed_initial_structure = \
                Structure.from_dict(perturbed_initial_structure)
        if isinstance(final_structure, dict):
            final_structure = Structure.from_dict(final_structure)

        orbital_character = str_key_to_spin(d["orbital_character"])
        band_edge_states = \
            str_key_to_spin(d["band_edge_states"], BandEdgeState.from_string)

        return cls(name=d["name"],
                   charge=d["charge"],
                   annotation=d["annotation"],
                   is_converged=d["is_converged"],
                   relative_total_energy=d["relative_total_energy"],
                   correction_energy=d["correction_energy"],
                   initial_structure=initial_structure,
                   perturbed_initial_structure=perturbed_initial_structure,
                   final_structure=final_structure,
                   final_volume=d["final_volume"],
                   defect_center=d["defect_center"],
                   anchor_atom_index=d["anchor_atom_index"],
                   changes_of_num_elements=d["changes_of_num_elements"],
                   displacements=d["displacements"],
                   neighboring_sites=d["neighboring_sites"],
                   defect_center_coords=d["defect_center_coords"],
                   initial_symmetry=d["initial_symmetry"],
                   final_symmetry=d["final_symmetry"],
                   initial_multiplicity=d["initial_multiplicity"],
                   final_multiplicity=d["final_multiplicity"],
                   magnetization=d["magnetization"],
                   kpoint_coords=d["kpoint_coords"],
                   eigenvalues=eigenvalues,
                   supercell_vbm=d["supercell_vbm"],
                   supercell_cbm=d["supercell_cbm"],
                   fermi_level=d["fermi_level"],
                   orbital_character=orbital_character,
                   band_edge_states=band_edge_states)
Example #26
0
File: dos.py Project: tllu/pymatgen
 def from_dict(cls, d) -> "LobsterCompleteDos":
     """
     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 = orb_str
             orb_dos[orb] = {Spin(int(k)): v for k, v in odos["densities"].items()}
         pdoss[at] = orb_dos
     return LobsterCompleteDos(struct, tdos, pdoss)
Example #27
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)
Example #28
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 xrange(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)
Example #29
0
    def from_dict(cls, d):
        """
        Returns CompleteCohp object from dict representation.
        """
        cohp_dict = {}
        efermi = d["efermi"]
        energies = d["energies"]
        structure = Structure.from_dict(d["structure"])
        if "bonds" in d.keys():
            bonds = {bond: {"length": d["bonds"][bond]["length"],
                            "sites": tuple(PeriodicSite.from_dict(site)
                                           for site in d["bonds"][bond]["sites"])}
                     for bond in d["bonds"]}
        else:
            bonds = None
        for label in d["COHP"]:
            cohp = {Spin(int(spin)): np.array(d["COHP"][label][spin])
                    for spin in d["COHP"][label]}
            try:
                icohp = {Spin(int(spin)): np.array(d["ICOHP"][label][spin])
                         for spin in d["ICOHP"][label]}
            except KeyError:
                icohp = None
            if label == "average":
                avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)
            else:
                cohp_dict[label] = Cohp(efermi, energies, cohp, icohp=icohp)

        if "orb_res_cohp" in d.keys():
            orb_cohp = {}
            for label in d["orb_res_cohp"]:
                orb_cohp[label] = {}
                for orb in d["orb_res_cohp"][label]:
                    cohp = {Spin(int(s)): np.array(
                        d["orb_res_cohp"][label][orb]["COHP"][s],
                        dtype=float)
                        for s in d["orb_res_cohp"][label][orb]["COHP"]}
                    try:
                        icohp = {Spin(int(s)): np.array(
                            d["orb_res_cohp"][label][orb]["ICOHP"][s],
                            dtype=float)
                            for s in d["orb_res_cohp"][label][orb]["ICOHP"]}
                    except KeyError:
                        icohp = None
                    orbitals = [tuple((int(o[0]), Orbital[o[1]])) for o in
                                d["orb_res_cohp"][label][orb]["orbitals"]]
                    orb_cohp[label][orb] = {"COHP": cohp, "ICOHP": icohp,
                                            "orbitals": orbitals}
                # If no total COHPs are present, calculate the total
                # COHPs from the single-orbital populations. Total COHPs
                # may not be present when the cohpgenerator keyword is used
                # in LOBSTER versions 2.2.0 and earlier.
                if label not in d["COHP"] or d["COHP"][label] is None:
                    cohp = {Spin.up: np.sum(np.array(
                        [orb_cohp[label][orb]["COHP"][Spin.up]
                         for orb in orb_cohp[label]]), axis=0)}
                    try:
                        cohp[Spin.down] = np.sum(np.array(
                            [orb_cohp[label][orb]["COHP"][Spin.down]
                             for orb in orb_cohp[label]]), axis=0)
                    except KeyError:
                        pass

                orb_res_icohp = None in [orb_cohp[label][orb]["ICOHP"] for orb in orb_cohp[label]]
                if (label not in d["ICOHP"] or d["ICOHP"][label] is None) and orb_res_icohp:
                    icohp = {Spin.up: np.sum(np.array([orb_cohp[label][orb]["ICOHP"][Spin.up]
                             for orb in orb_cohp[label]]), axis=0)}
                    try:
                        icohp[Spin.down] = np.sum(np.array(
                            [orb_cohp[label][orb]["ICOHP"][Spin.down]
                             for orb in orb_cohp[label]]), axis=0)
                    except KeyError:
                        pass
        else:
            orb_cohp = None

        if "average" not in d["COHP"].keys():
            # calculate average
            cohp = np.array([np.array(c)
                             for c in d["COHP"].values()]).mean(axis=0)
            try:
                icohp = np.array([np.array(c)
                                  for c in d["ICOHP"].values()]).mean(axis=0)
            except KeyError:
                icohp = None
            avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)

        return CompleteCohp(structure, avg_cohp, cohp_dict, bonds=bonds,
                            are_coops=d["are_coops"], orb_res_cohp=orb_cohp)
 def test_from_int(self):
     self.assertEquals(Spin.from_int(1), Spin.up)
     self.assertEquals(Spin.from_int(-1), Spin.down)
     self.assertRaises(ValueError, Spin.from_int, 0)
 def test_cached(self):
     self.assertEquals(id(Spin.from_int(1)), id(Spin.up))
    def get_plot(self,
                 xlim=None,
                 ylims=None,
                 cbm_vbm=None,
                 legend=True,
                 crop_first_value=False,
                 title=None):
        """
        Get a matplotlib plot showing the DOS.

        Args:
            xlim (list):
                Specifies the x-axis limits. Set to None for automatic
                determination.
            ylims (list):
                Specifies the y-axes limits. Two types of input.
                [[y1min, y1max], [y2min, y2max], ..]
            cbm_vbm (list):
                Specify cbm and vbm [cbm, vbm]
            legend (bool):
                Whether to show the figure legend.
            crop_first_value (bool):
                Whether to crop the fist DOS.
            title (str):
                Title of the figure
        """

        ncolors = max(3, len(self._doses))
        ncolors = min(9, ncolors)
        import palettable
        colors = palettable.colorbrewer.qualitative.Set1_9.mpl_colors

        y = None
        all_densities = []
        all_energies = []

        # The DOS calculated using VASP holds a spuriously large value at the
        # first mesh to keep the consistency with the integrated DOS in DOSCAR
        # file. An example is shown below.
        # ------------- DOSCAR --------------------
        # 10 10 1 0
        # 0.1173120E+02 0.5496895E-09 0.5496895E-09 0.5496895E-09 0.5000000E-15
        # 1.000000000000000E-004
        # CAR
        # unknown system
        #     23.00000000 - 9.00000000 3201 6.62000004 1.00000000
        #     -9.000 0.6000E+03 0.6000E+03 0.6000E+01 0.6000E+01 <-- large DOS
        #     -8.990 0.0000E+00 0.0000E+00 0.6000E+01 0.6000E+01

        i = 1 if crop_first_value else 0

        for key, dos in self._doses.items():
            energies = dos['energies'][i:]
            densities = {Spin(k): v[i:] for k, v in dos['densities'].items()}
            if not y:
                y = {
                    Spin.up: np.zeros(energies.shape),
                    Spin.down: np.zeros(energies.shape)
                }
            all_energies.append(energies)
            all_densities.append(densities)

        # Make groups to be shown in the same figure.
        # Example, ZrTiSe4
        # keys = ['Total', 'Site:1 Zr-s', 'Site:1 Zr-p', 'Site:1 Zr-d',
        #         'Site:2 Ti-s', 'Site:2 Ti-p', 'Site:2 Ti-d', 'Site:3 Se-s',
        #         'Site:3 Se-p', 'Site:3 Se-d', 'Site:5 Se-s', 'Site:5 Se-p',
        #         'Site:5 Se-d']
        keys = list(self._doses.keys())
        grouped_keys = OrderedDict()
        for k in keys:
            first_word = k.split()[0]
            if first_word in grouped_keys:
                grouped_keys[first_word].append(k)
            else:
                grouped_keys[first_word] = [k]

        import matplotlib.pyplot as plt
        num_figs = len(grouped_keys)
        fig, axs = plt.subplots(num_figs, 1, sharex=True)

        if xlim:
            axs[0].set_xlim(xlim)

        n = 0
        for i, gk in enumerate(grouped_keys):
            all_pts = []
            for j, key in enumerate(grouped_keys[gk]):
                x = []
                y = []
                for spin in [Spin.up, Spin.down]:
                    if spin in all_densities[n]:
                        densities = list(int(spin) * all_densities[n][spin])
                        energies = list(all_energies[n])
                        x.extend(energies)
                        y.extend(densities)
                all_pts.extend(list(zip(x, y)))
                axs[i].plot(x,
                            y,
                            color=colors[j % ncolors],
                            label=str(key),
                            linewidth=2)
                n += 1

            # plot vertical lines for band edges or Fermi level
            if self.zero_at_efermi:
                # plot a line
                axs[i].axvline(0, color="black", linestyle="--", linewidth=0.5)
                if cbm_vbm:
                    axs[i].axvline(cbm_vbm[0] - cbm_vbm[1],
                                   color="black",
                                   linestyle="--",
                                   linewidth=0.5)
            else:
                axs[i].axvline(self._doses[key]['efermi'],
                               color="black",
                               linestyle="--",
                               linewidth=0.5)
                if cbm_vbm:
                    axs[i].axvline(cbm_vbm[0],
                                   color="black",
                                   linestyle="--",
                                   linewidth=0.5)

            if legend:
                axs[i].legend(loc="best", markerscale=0.1)
                #                axs[i].legend(bbox_to_anchor=(1.1, 0.8), loc="best")
                leg = axs[i].get_legend()
                for legobj in leg.legendHandles:
                    legobj.set_linewidth(1.2)
                ltext = leg.get_texts()
                plt.setp(ltext, fontsize=7)
            else:
                axs[i].set_title(key, fontsize=7)

            axs[i].axhline(0, color="black", linewidth=0.5)

        if ylims and len(ylims) not in (num_figs, 2):
            raise ValueError("The number of y-ranges is not proper.")

        if ylims and len(ylims) == 2:
            if ylims[0][1] > 1.0:
                axs[0].set_ylim(ylims[0])
            for i in range(1, len(axs)):
                axs[i].set_ylim(ylims[1])

        elif ylims:
            for i in range(len(axs)):
                axs[i].set_ylim(ylims[i])
        # else:
        #     for i in range(len(axs)):
        #         ylim = axs[i].get_ylim()
        #         print(ylim)
        #         relevanty = [p[1] for p in all_pts
        #                      if ylim[0] < p[0] < ylim[1]]
        #         axs[i].set_ylim((min(relevanty), max(relevanty)))e

        axs[-1].set_xlabel('Energy (eV)')
        plt.tight_layout()

        plt.subplots_adjust(left=None,
                            bottom=None,
                            right=None,
                            top=None,
                            wspace=0.2,
                            hspace=0.2)

        if title:
            axs[0].title.set_text(title)

        return plt
Example #33
0
 def from_dict(cls, d) -> "FermiSurface":
     """Return FermiSurface object from dict."""
     fs = super().from_dict(d)
     fs.isosurfaces = {Spin(int(k)): v for k, v in fs.isosurfaces.items()}
     return fs
Example #34
0
def get_effective_mass():
    """
    This function is in a beta stage, and its results are not
    guaranteed to be useful.

    Finds effective masses from a band structure, using parabolic
    fitting to determine the band curvature at the CBM
    for electrons and at the VBM for holes. This curvature enters
    the equation m* = (hbar)**2 / (d^2E/dk^2).

    To consider anisotropy, the k-space directions to the left and right
    of the CBM/VBM in the band diagram are returned separately.

    *NOTE* Only works for semiconductors and linemode calculations (non-
           spin polarized).
           >30 k-points per string recommended to obtain
           reliable curvatures.

    *NOTE* The parabolic fit can be quite sensitive to the number of
           k-points fit to, so it might be worthwhile adjusting N_KPTS
           to obtain some sense of the error bar.

    TODO: Warn user if CBM/VBM is at the edge of the diagram, and which
          direction (either left or right) was not actually fit to.
          Until fixed, this (most likely) explains any negative masses
          returned.

    Returns:
        Dictionary of the form
            {'electron': {'left': e_m_eff_l, 'right': e_m_eff_r},
             'hole': {'left': h_m_eff_l, 'right': h_m_eff_r}}
            where 'left' and 'right' indicate the reciprocal
            directions to the left and right of the extremum in the
            band structure.
    """

    H_BAR = 6.582119514e-16  # eV*s
    M_0 = 9.10938356e-31  # kg
    N_KPTS = 6  # Number of k-points included in the parabola.

    spin_up = Spin(1)

    band_structure = Vasprun('vasprun.xml').get_band_structure()

    # Locations of CBM and VBM in band_structure.bands
    cbm_band_index = band_structure.get_cbm()['band_index'][spin_up][0]
    cbm_kpoint_index = band_structure.get_cbm()['kpoint_index'][0]

    vbm_band_index = band_structure.get_vbm()['band_index'][spin_up][0]
    vbm_kpoint_index = band_structure.get_vbm()['kpoint_index'][0]

    k = {
        'electron': {
            'left': [],
            'right': []
        },
        'hole': {
            'left': [],
            'right': []
        }
    }
    E = {
        'electron': {
            'left': [],
            'right': []
        },
        'hole': {
            'left': [],
            'right': []
        }
    }

    e_ref_coords = band_structure.kpoints[cbm_kpoint_index]._ccoords
    h_ref_coords = band_structure.kpoints[vbm_kpoint_index]._ccoords

    for n in range(-N_KPTS, 1):
        e_coords = band_structure.kpoints[cbm_kpoint_index + n]._ccoords
        h_coords = band_structure.kpoints[vbm_kpoint_index + n]._ccoords

        k['electron']['left'].append(((e_coords[0] - e_ref_coords[0])**2 +
                                      (e_coords[1] - e_ref_coords[1])**2 +
                                      (e_coords[2] - e_ref_coords[2])**2)**0.5)
        k['hole']['left'].append(((h_coords[0] - h_ref_coords[0])**2 +
                                  (h_coords[1] - h_ref_coords[1])**2 +
                                  (h_coords[2] - h_ref_coords[2])**2)**0.5)

        e_energy = band_structure.bands[spin_up][cbm_band_index][
            cbm_kpoint_index + n]
        h_energy = band_structure.bands[spin_up][vbm_band_index][
            vbm_kpoint_index + n]

        E['electron']['left'].append(e_energy)
        E['hole']['left'].append(h_energy)

    for n in range(1, 1 + N_KPTS):
        e_coords = band_structure.kpoints[cbm_kpoint_index + n]._ccoords
        h_coords = band_structure.kpoints[vbm_kpoint_index + n]._ccoords

        k['electron']['right'].append(
            ((e_coords[0] - e_ref_coords[0])**2 +
             (e_coords[1] - e_ref_coords[1])**2 +
             (e_coords[2] - e_ref_coords[2])**2)**0.5)
        k['hole']['right'].append(((h_coords[0] - h_ref_coords[0])**2 +
                                   (h_coords[1] - h_ref_coords[1])**2 +
                                   (h_coords[2] - h_ref_coords[2])**2)**0.5)

        e_energy = band_structure.bands[spin_up][cbm_band_index][
            cbm_kpoint_index + n]
        h_energy = band_structure.bands[spin_up][vbm_band_index][
            vbm_kpoint_index + n]

        E['electron']['right'].append(e_energy)
        E['hole']['right'].append(h_energy)

    # 2nd order fits
    e_l_fit = np.poly1d(
        np.polyfit(k['electron']['left'], E['electron']['left'], 2))
    e_r_fit = np.poly1d(
        np.polyfit(k['electron']['right'], E['electron']['right'], 2))
    h_l_fit = np.poly1d(np.polyfit(k['hole']['left'], E['hole']['left'], 2))
    h_r_fit = np.poly1d(np.polyfit(k['hole']['right'], E['hole']['right'], 2))

    # Curvatures
    e_l_curvature = e_l_fit.deriv().deriv()[0]
    e_r_curvature = e_r_fit.deriv().deriv()[0]
    h_l_curvature = h_l_fit.deriv().deriv()[0]
    h_r_curvature = h_r_fit.deriv().deriv()[0]

    # Unit conversion
    e_m_eff_l = 10 * ((H_BAR**2) / e_l_curvature) / M_0
    e_m_eff_r = 10 * ((H_BAR**2) / e_r_curvature) / M_0
    h_m_eff_l = -10 * ((H_BAR**2) / h_l_curvature) / M_0
    h_m_eff_r = -10 * ((H_BAR**2) / h_r_curvature) / M_0

    return {
        'electron': {
            'left': e_m_eff_l,
            'right': e_m_eff_r
        },
        'hole': {
            'left': h_m_eff_l,
            'right': h_m_eff_r
        }
    }
    def __init__(self, kpoints_name, vasprun_name, is_projection=False):

        kpoints = Kpoints.from_file(kpoints_name)

        # BSVasprun cannot be used when the electronic convergence is checked.
        if is_projection:
            vasprun = Vasprun(filename=vasprun_name,
                              parse_projected_eigen=True)
        else:
            vasprun = Vasprun(filename=vasprun_name)

        if vasprun.converged_electronic is False:
            logger.warning("SCF is not attained!!!!!")

        eigenvalues = vasprun.eigenvalues
        lattice_rec = vasprun.final_structure.lattice.reciprocal_lattice
        efermi = vasprun.efermi

        first_index_wo_weight = 0
        for w in kpoints.kpts_weights:
            if w > 0:
                first_index_wo_weight += 1
                continue

        kpts_wo_weight = kpoints.kpts[first_index_wo_weight:]

        eigenvalues_wo_weight = {}
        for s in eigenvalues:
            # transpose is essential
            # When parsing vasprun.xml using BSVasprun,
            # eigenvalues[kpt-index][band-index] = [energy, occupation]
            # For BSPlotter
            # eigenvalues[band-index][kpt-index] = energy
            eigenvalues_wo_weight[Spin(s)] = \
                eigenvalues[Spin(s)][first_index_wo_weight:, :, 0].transpose()

        # Store label except for "None".
        labels_dict = {}
        for i, label in enumerate(kpoints.labels):
            if label != "None" and label is not None:
                # TODO: Add more greek letters
                if label == "GAMMA":
                    labels_dict["\u0393"] = kpoints.kpts[i]
                elif label == "SIGMA_0":
                    labels_dict["\u03A3" + "_0"] = kpoints.kpts[i]
                elif label == "DELTA_0":
                    labels_dict["\u0394" + "_0"] = kpoints.kpts[i]
                else:
                    labels_dict[label] = kpoints.kpts[i]

        structure = vasprun.final_structure
        if is_projection:
            v = vasprun.projected_eigenvalues
            projections = {}
            for s in eigenvalues:
                # swapaxes is essential
                # When parsing vasprun.xml using BSVasprun,
                #  Vasprun.projected_eigenvalues[spin][kpoint index][band index]
                #                               [atom index][orbital_index]
                # For BSPlotter
                # projections: dict of orbital projections as {spin: ndarray}.
                # The indices of the ndarray are [band_index, kpoint_index,
                #                                 orbital_index, ion_index].

                projections[Spin(s)] = v[Spin(s)].swapaxes(0, 1).swapaxes(2, 3)
                print(projections)
            super().__init__(kpts_wo_weight,
                             eigenvalues_wo_weight,
                             lattice_rec,
                             efermi,
                             labels_dict,
                             structure=structure,
                             projections=projections)

        else:
            super().__init__(kpts_wo_weight,
                             eigenvalues_wo_weight,
                             lattice_rec,
                             efermi,
                             labels_dict,
                             structure=structure)
Example #36
0
for m in range(len(lattice)):
    for i in range(len(z_atoms)):

        print(lattice[m], z_atoms[i])     
                
        xml = Vasprun('/home/buche/VaspTesting/Danil/X2YZ_Half_metall/Fe2RhZ/SCAN/band/{}/step1/{}/vasprun.xml'.format(lattice[m], z_atoms[i]))
            
        if xml.converged:
            fig = plt.figure()
            ax = fig.add_subplot(111)
            ax.set_xlabel(r"Z atom", size=18, labelpad = 0.0)
            ax.set_ylabel(r"$\Delta$ Energy (eV/atom)", size=18, labelpad = -1.0)

            t_energies = xml.tdos.energies - xml.tdos.efermi
            t_dos_up = xml.tdos.get_densities(Spin(1))
            t_dos_down = -xml.tdos.get_densities(Spin(-1))
            t_data = np.column_stack((t_energies, t_dos_up, t_dos_down))

            t_condition = ((t_data[:,0]>e_min) & (t_data[:,0]<e_max))
            ax.fill_between(t_data[t_condition,0], t_data[t_condition,1], t_data[t_condition,2], alpha=0.5, label = 'Total')
                
                    
            ax.plot([e_min, e_max], [0.0, 0.0], '--', linewidth=0.8, color='black')#Ноли
            ax.plot([0.0, 0.0], [min(t_data[t_condition,2]), max(t_data[t_condition,1])], '--', linewidth=1, color='black') #Ноли
                    
            #ax.text(0.1, 0.1, '{:.0f} %'.format(xml.complete_dos.spin_polarization*100), horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize = 18)
                    
            #ax.text(0.9, 0.1, z_atoms[i], horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize = 18)

Example #37
0
 def test_cached(self):
     self.assertEqual(id(Spin(1)), id(Spin.up))
Example #38
0
 def test_from_int(self):
     self.assertEqual(Spin(1), Spin.up)
     self.assertEqual(Spin(-1), Spin.down)
     self.assertRaises(ValueError, Spin, 0)
Example #39
0
if not os.path.isdir('DOS'):
    os.makedirs('DOS')
      

xml = Vasprun('vasprun.xml')

if xml.converged:
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel(r"$E-E_F$", size=18, labelpad = 0.0)
    ax.set_ylabel(r"DOS (st./eV/atom)", size=18, labelpad = -1.0)

    if plot_total == True:
        t_energies = xml.tdos.energies - xml.tdos.efermi
        t_dos_up = xml.tdos.get_densities(Spin(1))
        t_dos_down = -xml.tdos.get_densities(Spin(-1))
        t_data = np.column_stack((t_energies, t_dos_up, t_dos_down))

        t_condition = ((t_data[:,0]>e_min) & (t_data[:,0]<e_max))
        ax.fill_between(t_data[t_condition,0], t_data[t_condition,1], t_data[t_condition,2], alpha=0.5, label = 'Total')
        
        ax.plot([e_min, e_max], [0.0, 0.0], '--', linewidth=0.8, color='black')#Ноли
        ax.plot([0.0, 0.0], [min(t_data[t_condition,2]), max(t_data[t_condition,1])], '--', linewidth=1, color='black') #Ноли
        
 
    ax.text(0.1, 0.1, '{:.0f} %'.format(xml.complete_dos.spin_polarization*100), horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize = 18)
        

    for s in sites:
        energies = xml.complete_dos.get_site_dos(xml.structures[-1][s]).energies - xml.complete_dos.get_site_dos(xml.structures[-1][s]).efermi
 def from_dict(cls, d):
     kwargs = deepcopy(d)
     kwargs["spin"] = Spin(d["spin"])
     kwargs.pop("@module", None)
     kwargs.pop("@class", None)
     return cls(**kwargs)
Example #41
0
 def test_cached(self):
     self.assertEquals(id(Spin.from_int(1)), id(Spin.up))