How to use the pymatgen.core.composition.Composition function in pymatgen

To help you get started, we’ve selected a few pymatgen examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github materialsproject / pymatgen / pymatgen / ext / cod.py View on Github external
"""
        Queries the COD for structures by formula. Requires mysql executable to
        be in the path.

        Args:
            cod_id (int): COD id.
            kwargs: All kwargs supported by
                :func:`pymatgen.core.structure.Structure.from_str`.

        Returns:
            A list of dict of the format
            [{"structure": Structure, "cod_id": cod_id, "sg": "P n m a"}]
        """
        structures = []
        sql = 'select file, sg from data where formula="- %s -"' % \
              Composition(formula).hill_formula
        text = self.query(sql).split("\n")
        text.pop(0)
        for l in text:
            if l.strip():
                cod_id, sg = l.split("\t")
                r = requests.get("http://www.crystallography.net/cod/%s.cif"
                                 % cod_id.strip())
                try:
                    s = Structure.from_str(r.text, fmt="cif", **kwargs)
                    structures.append({"structure": s, "cod_id": int(cod_id),
                                       "sg": sg})
                except Exception:
                    import warnings
                    warnings.warn("\nStructure.from_str failed while parsing CIF file:\n%s" % r.text)
                    raise
github materialsproject / pymatgen / pymatgen / io / vasp / outputs.py View on Github external
def as_dict(self):
        """
        Json-serializable dict representation.
        """
        d = {"vasp_version": self.vasp_version,
             "has_vasp_completed": self.converged,
             "nsites": len(self.final_structure)}
        comp = self.final_structure.composition
        d["unit_cell_formula"] = comp.as_dict()
        d["reduced_cell_formula"] = Composition(comp.reduced_formula).as_dict()
        d["pretty_formula"] = comp.reduced_formula
        symbols = [s.split()[1] for s in self.potcar_symbols]
        symbols = [re.split("_", s)[0] for s in symbols]
        d["is_hubbard"] = self.is_hubbard
        d["hubbards"] = {}
        if d["is_hubbard"]:
            us = self.incar.get("LDAUU", self.parameters.get("LDAUU"))
            js = self.incar.get("LDAUJ", self.parameters.get("LDAUJ"))
            if len(us) == len(symbols):
                d["hubbards"] = {symbols[i]: us[i] - js[i]
                                 for i in range(len(symbols))}
            else:
                raise VaspParserError("Length of U value parameters and atomic"
                                      " symbols are mismatched.")

        unique_symbols = sorted(list(set(self.atomic_symbols)))
github materialsproject / pymatgen / pymatgen / analysis / structure_matcher.py View on Github external
sp1 = struct1.composition.elements
        sp2 = struct2.composition.elements
        if len(sp1) != len(sp2):
            return None

        ratio = fu if s1_supercell else 1 / fu
        swapped = len(struct1) * ratio < len(struct2)

        s1_comp = struct1.composition
        s2_comp = struct2.composition
        matches = []
        for perm in itertools.permutations(sp2):
            sp_mapping = dict(zip(sp1, perm))

            # do quick check that compositions are compatible
            mapped_comp = Composition({sp_mapping[k]: v
                                       for k, v in s1_comp.items()})
            if (not self._subset) and (
                    self._comparator.get_hash(mapped_comp) !=
                    self._comparator.get_hash(s2_comp)):
                continue

            mapped_struct = struct1.copy()
            mapped_struct.replace_species(sp_mapping)
            if swapped:
                m = self._strict_match(struct2, mapped_struct, fu,
                                       (not s1_supercell), use_rms,
                                       break_on_match)
            else:
                m = self._strict_match(mapped_struct, struct2, fu, s1_supercell,
                                       use_rms, break_on_match)
            if m:
github materialsproject / MPContribs / mpcontribs-users / mpcontribs / users / redox_thermo_csp / rest / utils.py View on Github external
def get_most_stable_entry(formula):
        relevant_entries = [entry for entry in all_entries if
        entry.composition.reduced_formula == Composition(formula).reduced_formula]
        relevant_entries = sorted(relevant_entries, key=lambda e: e.energy_per_atom)
        return relevant_entries[0]
github materialsproject / pymatgen / pymatgen / analysis / structure_matcher.py View on Github external
def are_equal(self, sp1, sp2):
        """
        True if element:amounts are exactly the same, i.e.,
        oxidation state is not considered.

        Args:
            sp1: First species. A dict of {specie/element: amt} as per the
                definition in Site and PeriodicSite.
            sp2: Second species. A dict of {specie/element: amt} as per the
                definition in Site and PeriodicSite.

        Returns:
            Boolean indicating whether species are the same based on element
            and amounts.
        """
        comp1 = Composition(sp1)
        comp2 = Composition(sp2)
        return comp1.get_el_amt_dict() == comp2.get_el_amt_dict()
github materialsproject / pymatgen / pymatgen / analysis / reaction_calculator.py View on Github external
def from_dict(cls, d):
        """
        Args:
            d (dict): from as_dict()

        Returns:
            A Reaction object.
        """
        reactants = [Composition(sym_amt) for sym_amt in d["reactants"]]
        products = [Composition(sym_amt) for sym_amt in d["products"]]
        return cls(reactants, products)
github materialsproject / pymatgen / pymatgen / analysis / phase_diagram.py View on Github external
"""
        Get the CompoundPhaseDiagram object, which can then be used for
        plotting.

        Returns:
            (CompoundPhaseDiagram)
        """
        # For this plot, since the reactions are reported in formation
        # energies, we need to set the energies of the terminal compositions
        # to 0. So we make create copies with 0 energy.
        entry1 = PDEntry(self.entry1.composition, 0)
        entry2 = PDEntry(self.entry2.composition, 0)

        cpd = CompoundPhaseDiagram(
            self.rxn_entries + [entry1, entry2],
            [Composition(entry1.composition.reduced_formula),
             Composition(entry2.composition.reduced_formula)],
            normalize_terminal_compositions=False)
        return cpd
github materialsproject / MPContribs / MnO2_phase_selection / pre_submission.py View on Github external
print cid, 'inserted to update', mpid
                        break

    # "phase": 'postspinel-NaMn2O4', "Formula": 'Na0.5MnO2',
    # "dHf (eV/mol)": -1.415, "dHh (eV/mol)": '--', "Ground state?": 'Y',

    ################################################################################################################
    # Get mp-ids for all entries based on matching the VASP directory path names
    # Paths are different in the existing and new mp-id dictionary, so processing has to be independent
    ################################################################################################################

    print 'get all mp-ids based on VASP directory paths ...'

    for framework, fdat in mp_contrib_phases.items():
        for i, phase in enumerate(fdat):
            c = Composition(phase[0])
            for hstate in hull_states:
                if phase_names[framework] == hstate['phase'] and \
                        c.almost_equals(Composition.from_dict(hstate['c'])) and \
                        len(mp_contrib_phases[framework][i]) < 6:
                    mp_contrib_phases[framework][i].append(hstate['path'])
                    mp_contrib_phases[framework][i].append(hstate['s'])

    for framework, fdat in mp_contrib_phases.items():
        for i, phase in enumerate(fdat):
            match_path = phase[4].replace('all_states/', '')
            mp_ids = []
            for path, ids in mp_dup.items():
                mp_path = path.replace('/Users/patrick/Downloads/20160710_MPContrib_MnO2_DK/', '').replace(
                    '/3.double_relax/CONTCAR', '')
                if match_path == mp_path:
                    mp_ids.extend(ids)
github materialsproject / mpmorph / mpmorph / drones.py View on Github external
else:
            vrun = Vasprun(vasprun_file)

        d = vrun.as_dict()

        # rename formula keys
        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: