• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python composition.Composition类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pymatgen.core.composition.Composition的典型用法代码示例。如果您正苦于以下问题:Python Composition类的具体用法?Python Composition怎么用?Python Composition使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Composition类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: parse_tok

 def parse_tok(t):
     if re.match("\w+-\d+", t):
         return {"task_id": t}
     elif "-" in t:
         elements = [parse_sym(sym) for sym in t.split("-")]
         chemsyss = []
         for cs in itertools.product(*elements):
             if len(set(cs)) == len(cs):
                 # Check for valid symbols
                 cs = [Element(s).symbol for s in cs]
                 chemsyss.append("-".join(sorted(cs)))
         return {"chemsys": {"$in": chemsyss}}
     else:
         all_formulas = set()
         explicit_els = []
         wild_card_els = []
         for sym in re.findall(
                 r"(\*[\.\d]*|\{.*\}[\.\d]*|[A-Z][a-z]*)[\.\d]*", t):
             if ("*" in sym) or ("{" in sym):
                 wild_card_els.append(sym)
             else:
                 m = re.match("([A-Z][a-z]*)[\.\d]*", sym)
                 explicit_els.append(m.group(1))
         nelements = len(wild_card_els) + len(set(explicit_els))
         parts = re.split(r"(\*|\{.*\})", t)
         parts = [parse_sym(s) for s in parts if s != ""]
         for f in itertools.product(*parts):
             c = Composition("".join(f))
             if len(c) == nelements:
                 # Check for valid Elements in keys.
                 for e in c.keys():
                     Element(e.symbol)
                 all_formulas.add(c.reduced_formula)
         return {"pretty_formula": {"$in": list(all_formulas)}}
开发者ID:zulissi,项目名称:pymatgen,代码行数:34,代码来源:rest.py


示例2: parse_tok

 def parse_tok(t):
     if re.match("\w+-\d+", t):
         return {"task_id": t}
     elif "-" in t:
         elements = t.split("-")
         elements = [[Element(el).symbol] if el != "*" else
                     ALL_ELEMENT_SYMBOLS for el in elements]
         chemsyss = []
         for cs in itertools.product(*elements):
             if len(set(cs)) == len(cs):
                 chemsyss.append("-".join(sorted(set(cs))))
         return {"chemsys": {"$in": chemsyss}}
     else:
         all_formulas = set()
         syms = re.findall("[A-Z][a-z]*", t)
         to_permute = ALL_ELEMENT_SYMBOLS.difference(syms)
         parts = t.split("*")
         for syms in itertools.permutations(to_permute,
                                            len(parts) - 1):
             f = []
             for p in zip(parts, syms):
                 f.extend(p)
             f.append(parts[-1])
             c = Composition("".join(f))
             #Check for valid Elements in keys.
             map(lambda e: Element(e.symbol), c.keys())
             all_formulas.add(c.reduced_formula)
         return {"pretty_formula": {"$in": list(all_formulas)}}
开发者ID:maksimovica,项目名称:pymatgen,代码行数:28,代码来源:rest.py


示例3: __init__

    def __init__(self, atoms_n_occu, coords, properties=None):
        """
        Create a *non-periodic* site.

        Args:
            atoms_n_occu: Species on the site. Can be:

                i.  A sequence of element / specie specified either as string
                    symbols, e.g. ["Li", "Fe2+", "P", ...] or atomic numbers,
                    e.g., (3, 56, ...) or actual Element or Specie objects.
                ii. List of dict of elements/species and occupancies, e.g.,
                    [{"Fe" : 0.5, "Mn":0.5}, ...]. This allows the setup of
                    disordered structures.
            coords: Cartesian coordinates of site.
            properties: Properties associated with the site as a dict, e.g.
                {"magmom": 5}. Defaults to None.
        """
        if isinstance(atoms_n_occu, collections.Mapping):
            self._species = Composition(atoms_n_occu)
            totaloccu = self._species.num_atoms
            if totaloccu > 1 + Composition.amount_tolerance:
                raise ValueError("Species occupancies sum to more than 1!")
            self._is_ordered = totaloccu == 1 and len(self._species) == 1
        else:
            self._species = Composition({get_el_sp(atoms_n_occu): 1})
            self._is_ordered = True

        self._coords = coords
        self._properties = properties if properties else {}
开发者ID:dbroberg,项目名称:pymatgen_chgdef,代码行数:29,代码来源:sites.py


示例4: test_negative_compositions

    def test_negative_compositions(self):
        self.assertEqual(Composition('Li-1(PO-1)4', allow_negative=True).formula,
                         'Li-1 P4 O-4')
        self.assertEqual(Composition('Li-1(PO-1)4', allow_negative=True).reduced_formula,
                         'Li-1(PO-1)4')
        self.assertEqual(Composition('Li-2Mg4', allow_negative=True).reduced_composition,
                         Composition('Li-1Mg2', allow_negative=True))
        self.assertEqual(Composition('Li-2.5Mg4', allow_negative=True).reduced_composition,
                         Composition('Li-2.5Mg4', allow_negative=True))

        #test math
        c1 = Composition('LiCl', allow_negative=True)
        c2 = Composition('Li')
        self.assertEqual(c1 - 2 * c2, Composition({'Li': -1, 'Cl': 1},
                                                  allow_negative=True))
        self.assertEqual((c1 + c2).allow_negative, True)
        self.assertEqual(c1 / -1, Composition('Li-1Cl-1', allow_negative=True))

        #test num_atoms
        c1 = Composition('Mg-1Li', allow_negative=True)
        self.assertEqual(c1.num_atoms, 2)
        self.assertEqual(c1.get_atomic_fraction('Mg'), 0.5)
        self.assertEqual(c1.get_atomic_fraction('Li'), 0.5)
        self.assertEqual(c1.fractional_composition,
                         Composition('Mg-0.5Li0.5', allow_negative=True))

        #test copy
        self.assertEqual(c1.copy(), c1)

        #test species
        c1 = Composition({'Mg':1, 'Mg2+':-1}, allow_negative=True)
        self.assertEqual(c1.num_atoms, 2)
        self.assertEqual(c1.element_composition, Composition())
        self.assertEqual(c1.average_electroneg, 1.31)
开发者ID:AtlasL,项目名称:pymatgen,代码行数:34,代码来源:test_composition.py


示例5: test_negative_compositions

    def test_negative_compositions(self):
        self.assertEqual(Composition("Li-1(PO-1)4", allow_negative=True).formula, "Li-1 P4 O-4")
        self.assertEqual(Composition("Li-1(PO-1)4", allow_negative=True).reduced_formula, "Li-1(PO-1)4")
        self.assertEqual(
            Composition("Li-2Mg4", allow_negative=True).reduced_composition, Composition("Li-1Mg2", allow_negative=True)
        )
        self.assertEqual(
            Composition("Li-2.5Mg4", allow_negative=True).reduced_composition,
            Composition("Li-2.5Mg4", allow_negative=True),
        )

        # test math
        c1 = Composition("LiCl", allow_negative=True)
        c2 = Composition("Li")
        self.assertEqual(c1 - 2 * c2, Composition({"Li": -1, "Cl": 1}, allow_negative=True))
        self.assertEqual((c1 + c2).allow_negative, True)
        self.assertEqual(c1 / -1, Composition("Li-1Cl-1", allow_negative=True))

        # test num_atoms
        c1 = Composition("Mg-1Li", allow_negative=True)
        self.assertEqual(c1.num_atoms, 2)
        self.assertEqual(c1.get_atomic_fraction("Mg"), 0.5)
        self.assertEqual(c1.get_atomic_fraction("Li"), 0.5)
        self.assertEqual(c1.fractional_composition, Composition("Mg-0.5Li0.5", allow_negative=True))

        # test copy
        self.assertEqual(c1.copy(), c1)

        # test species
        c1 = Composition({"Mg": 1, "Mg2+": -1}, allow_negative=True)
        self.assertEqual(c1.num_atoms, 2)
        self.assertEqual(c1.element_composition, Composition())
        self.assertEqual(c1.average_electroneg, 1.31)
开发者ID:anhhv,项目名称:pymatgen,代码行数:33,代码来源:test_composition.py


示例6: test_from_dict

 def test_from_dict(self):
     sym_dict = {"Fe": 6, "O": 8}
     self.assertEqual(
         Composition.from_dict(sym_dict).reduced_formula, "Fe3O4", "Creation form sym_amount dictionary failed!"
     )
     comp = Composition({"Fe2+": 2, "Fe3+": 4, "O2-": 8})
     comp2 = Composition.from_dict(comp.as_dict())
     self.assertEqual(comp, comp2)
开发者ID:anhhv,项目名称:pymatgen,代码行数:8,代码来源:test_composition.py


示例7: test_almost_equals

 def test_almost_equals(self):
     c1 = Composition({'Fe': 2.0, 'O': 3.0, 'Mn': 0})
     c2 = Composition({'O': 3.2, 'Fe': 1.9, 'Zn': 0})
     c3 = Composition({'Ag': 2.0, 'O': 3.0})
     c4 = Composition({'Fe': 2.0, 'O': 3.0, 'Ag': 2.0})
     self.assertTrue(c1.almost_equals(c2, rtol=0.1))
     self.assertFalse(c1.almost_equals(c2, rtol=0.01))
     self.assertFalse(c1.almost_equals(c3, rtol=0.1))
     self.assertFalse(c1.almost_equals(c4, rtol=0.1))
开发者ID:AtlasL,项目名称:pymatgen,代码行数:9,代码来源:test_composition.py


示例8: to_reduced_dict

 def to_reduced_dict(self):
     """
     Returns:
         dict with element symbol and reduced amount e.g.,
         {"Fe": 2.0, "O":3.0}.
     """
     reduced_formula = self._composition.reduced_formula
     c = Composition(reduced_formula)
     d = c.as_dict()
     d['charge'] = self._charge
     return d
开发者ID:bocklund,项目名称:pymatgen,代码行数:11,代码来源:ion.py


示例9: test_Metallofullerene

 def test_Metallofullerene(self):
     # Test: Parse Metallofullerene formula (e.g. [email protected])
     formula = "[email protected]"
     sym_dict = {"Y": 3, "N": 1, "C": 80}
     cmp = Composition(formula)
     cmp2 = Composition.from_dict(sym_dict)
     self.assertEqual(cmp, cmp2)
开发者ID:davidwaroquiers,项目名称:pymatgen,代码行数:7,代码来源:test_composition.py


示例10: __init__

    def __init__(self, composition, energy, correction=0.0, parameters=None,
                 data=None, entry_id=None, attribute=None):
        """
        Initializes a ComputedEntry.

        Args:
            composition (Composition): Composition of the entry. For
                flexibility, this can take the form of all the typical input
                taken by a Composition, including a {symbol: amt} dict,
                a string formula, and others.
            energy (float): Energy of the entry. Usually the final calculated
                energy from VASP or other electronic structure codes.
            correction (float): A correction to be applied to the energy.
                This is used to modify the energy for certain analyses.
                Defaults to 0.0.
            parameters (dict): An optional dict of parameters associated with
                the entry. Defaults to None.
            data (dict): An optional dict of any additional data associated
                with the entry. Defaults to None.
            entry_id (obj): An optional id to uniquely identify the entry.
            attribute: Optional attribute of the entry. This can be used to
                specify that the entry is a newly found compound, or to specify
                a particular label for the entry, or else ... Used for further
                analysis and plotting purposes. An attribute can be anything
                but must be MSONable.
        """
        self.uncorrected_energy = energy
        self.composition = Composition(composition)
        self.correction = correction
        self.parameters = parameters if parameters else {}
        self.data = data if data else {}
        self.entry_id = entry_id
        self.name = self.composition.reduced_formula
        self.attribute = attribute
开发者ID:bocklund,项目名称:pymatgen,代码行数:34,代码来源:computed_entries.py


示例11: test_sub

 def test_sub(self):
     self.assertEqual((self.comp[0]
                       - Composition.from_formula("Li2O")).formula,
                      "Li1 Fe2 P3 O11",
                      "Incorrect composition after addition!")
     self.assertEqual((self.comp[0] - {"Fe": 2, "O": 3}).formula,
                      "Li3 P3 O9")
开发者ID:zacharygibbs,项目名称:pymatgen,代码行数:7,代码来源:test_composition.py


示例12: __init__

    def __init__(self, formula):
        '''
        Args:
            chemical formula as a string. formula must have integer subscripts
            Ex: 'SrTiO3'

        Attributes:
            composition: the composition as a dictionary.
                         Ex: {'Sr': 1, 'Ti': 1, 'O', 3}
            elements:    the dictionary keys for the composition
            elec_neg:    the maximum pairwise electronegetivity difference
            aos:         the consituant atomic orbitals for each element as a
                         dictionary
            band_edges:  dictionary containing the highest occupied molecular
                         orbital (HOMO), lowest unocupied molecular orbital
                         (LUMO), and whether the material is predicted to be a
                         metal
        '''
        self.composition = Composition(formula).as_dict()
        self.elements = self.composition.keys()
        for subscript in self.composition.values():
            if not float(subscript).is_integer():
                raise ValueError('composition subscripts must be integers')

        self.elec_neg = self.max_electronegativity()
        self.aos = {str(el): [[str(el), k, v]
                              for k, v in Element(el).atomic_orbitals.items()]
                    for el in self.elements}
        self.band_edges = self.obtain_band_edges()
开发者ID:ExpHP,项目名称:pymatgen,代码行数:29,代码来源:molecular_orbitals.py


示例13: __init__

 def __init__(self, composition, charge=0.0, properties=None):
     """
     Flexible Ion construction, similar to Composition.
     For more information, please see pymatgen.core.Composition
     """
     self._composition = Composition(composition)
     self._charge = charge
     self._properties = properties if properties else {}
开发者ID:bocklund,项目名称:pymatgen,代码行数:8,代码来源:ion.py


示例14: test_equals

 def test_equals(self):
     random_z = random.randint(1, 92)
     fixed_el = Element.from_Z(random_z)
     other_z = random.randint(1, 92)
     while other_z == random_z:
         other_z = random.randint(1, 92)
     comp1 = Composition({fixed_el: 1, Element.from_Z(other_z): 0})
     other_z = random.randint(1, 92)
     while other_z == random_z:
         other_z = random.randint(1, 92)
     comp2 = Composition({fixed_el: 1, Element.from_Z(other_z): 0})
     self.assertEqual(
         comp1,
         comp2,
         "Composition equality test failed. " + "%s should be equal to %s" % (comp1.formula, comp2.formula),
     )
     self.assertEqual(comp1.__hash__(), comp2.__hash__(), "Hashcode equality test failed!")
开发者ID:anhhv,项目名称:pymatgen,代码行数:17,代码来源:test_composition.py


示例15: test_getmu_vertices_stability_phase

 def test_getmu_vertices_stability_phase(self):
     results = self.analyzer.getmu_vertices_stability_phase(Composition.from_formula("LiFeO2"), Element("O"))
     self.assertAlmostEqual(len(results), 6)
     test_equality = False
     for c in results:
         if abs(c[Element("O")]+7.115) < 1e-2 and abs(c[Element("Fe")]+6.596) < 1e-2 and \
                 abs(c[Element("Li")]+3.931) < 1e-2:
             test_equality = True
     self.assertTrue(test_equality,"there is an expected vertex missing in the list")
开发者ID:malvo06,项目名称:pymatgen,代码行数:9,代码来源:test_pdanalyzer.py


示例16: are_equal

    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()
开发者ID:blondegeek,项目名称:pymatgen,代码行数:18,代码来源:structure_matcher.py


示例17: test_as_dict

 def test_as_dict(self):
     c = Composition.from_dict({'Fe': 4, 'O': 6})
     d = c.as_dict()
     correct_dict = {'Fe': 4.0, 'O': 6.0}
     self.assertEqual(d['Fe'], correct_dict['Fe'])
     self.assertEqual(d['O'], correct_dict['O'])
     correct_dict = {'Fe': 2.0, 'O': 3.0}
     d = c.to_reduced_dict
     self.assertEqual(d['Fe'], correct_dict['Fe'])
     self.assertEqual(d['O'], correct_dict['O'])
开发者ID:AtlasL,项目名称:pymatgen,代码行数:10,代码来源:test_composition.py


示例18: test_indeterminate_formula

 def test_indeterminate_formula(self):
     correct_formulas = [["Co1"], ["Co1", "C1 O1"], ["Co2 O3", "C1 O5"],
                         ["N1 Ca1 Lu1", "U1 Al1 C1 N1"],
                         ["N1 Ca1 Lu1", "U1 Al1 C1 N1"],
                         ["Li1 Co1 P2 N1 O10", "Li1 P2 C1 N1 O11",
                          "Li1 Co1 Po8 N1 O2", "Li1 Po8 C1 N1 O3"],
                         ["Co2 P4 O4", "Co2 Po4", "P4 C2 O6",
                          "Po4 C2 O2"], []]
     for i, c in enumerate(correct_formulas):
         self.assertEqual([Composition.from_formula(comp) for comp in c],
                          self.indeterminate_comp[i])
开发者ID:zacharygibbs,项目名称:pymatgen,代码行数:11,代码来源:test_composition.py


示例19: __init__

    def __init__(self, atoms_n_occu, coords, properties=None):
        """
        Create a *non-periodic* site.

        Args:
            atoms_n_occu: Species on the site. Can be:
                i.  A Composition object (preferred)
                ii. An  element / specie specified either as a string
                    symbols, e.g. "Li", "Fe2+", "P" or atomic numbers,
                    e.g., 3, 56, or actual Element or Specie objects.
                iii.Dict of elements/species and occupancies, e.g.,
                    {"Fe" : 0.5, "Mn":0.5}. This allows the setup of
                    disordered structures.
            coords: Cartesian coordinates of site.
            properties: Properties associated with the site as a dict, e.g.
                {"magmom": 5}. Defaults to None.
        """
        if isinstance(atoms_n_occu, Composition):
            # Compositions are immutable, so don't need to copy (much faster)
            self._species = atoms_n_occu
            # Kludgy lookup of private attribute, but its faster
            totaloccu = atoms_n_occu._natoms
            if totaloccu > 1 + Composition.amount_tolerance:
                raise ValueError("Species occupancies sum to more than 1!")
            # Another kludgy lookup of private attribute, but its faster
            self._is_ordered = totaloccu == 1 and len(self._species._data) == 1
        else:
            try:
                self._species = Composition({get_el_sp(atoms_n_occu): 1})
                self._is_ordered = True
            except TypeError:
                self._species = Composition(atoms_n_occu)
                totaloccu = self._species.num_atoms
                if totaloccu > 1 + Composition.amount_tolerance:
                    raise ValueError("Species occupancies sum to more than 1!")
                self._is_ordered = totaloccu == 1 and len(self._species) == 1

        self._coords = np.array(coords)
        self._coords.setflags(write=False)
        self._properties = properties if properties else {}
开发者ID:dongsenfo,项目名称:pymatgen,代码行数:40,代码来源:sites.py


示例20: __str__

 def __str__(self):
     reactant_str = []
     product_str = []
     for i in range(self._num_comp):
         comp = self._all_comp[i]
         coeff = self._coeffs[i]
         red_comp = Composition.from_formula(comp.reduced_formula)
         scale_factor = comp.num_atoms / red_comp.num_atoms
         scaled_coeff = coeff * scale_factor
         if scaled_coeff < 0:
             reactant_str.append("{:.3f} {}".format(-scaled_coeff, comp.reduced_formula))
         elif scaled_coeff > 0:
             product_str.append("{:.3f} {}".format(scaled_coeff, comp.reduced_formula))
     return " + ".join(reactant_str) + " -> " + " + ".join(product_str)
开发者ID:hgfb,项目名称:pymatgen,代码行数:14,代码来源:reaction_calculator.py



注:本文中的pymatgen.core.composition.Composition类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python ion.Ion类代码示例发布时间:2022-05-25
下一篇:
Python core.Structure类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap