当前位置: 首页>>代码示例>>Python>>正文


Python pymatgen.MPRester类代码示例

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


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

示例1: submit_tests

def submit_tests(names=None, params=None):
    sma = SubmissionMongoAdapter.auto_load()

    # note: TiO2 is duplicated twice purposely, duplicate check should catch this
    compounds = {"Si": 149, "Al": 134, "ZnO": 2133, "FeO": 18905,
                 "LiCoO2": 601860, "LiFePO4": 585433, "GaAs": 2534, "Ge": 32, "PbTe": 19717,
                 "YbO": 1216, "SiC": 567551, "Fe3C": 510623, "SiO2": 547211, "Na2O": 2352,
                 "InSb (unstable)": 10148, "Sb2O5": 1705, "N2O5": 554368, "BaTiO3": 5020,
                 "Rb2O": 1394, "TiO2": 554278, "TiO2 (2)": 554278, 'BaNbTePO8': 560794,
                 "AgCl": 22922, "AgCl (2)": 570858, "SiO2 (2)": 555211, "Mg2SiO4": 2895, "CO2": 20066,
                 "PbSO4": 22298, "SrTiO3": 5532, "FeAl": 2658, "AlFeCo2": 10884, "NaCoO2": 554427,
                 "ReO3": 547271, "LaH2": 24153, "SiH3I": 28538, "LiBH4": 30209, "H8S5N2": 28143,
                 "LiOH": 23856, "SrO2": 2697, "Mn": 35, "Hg4Pt": 2312,
                 "PdF4": 13868, "Gd2WO6": 651333, 'MnO2': 19395, 'VO2': 504800}

    mpr = MPRester()

    for name, sid in compounds.iteritems():
        if not names or name in names:
            sid = mpr.get_materials_id_from_task_id("mp-{}".format(sid))
            s = mpr.get_structure_by_material_id(sid, final=False)

            snl = StructureNL(s, 'Anubhav Jain <[email protected]>')

            parameters = {'priority': 10} if name == 'Si' else None
            if params:
                parameters.update(params)
            sma.submit_snl(snl, '[email protected]', parameters=parameters)
开发者ID:image-tester,项目名称:MPWorks,代码行数:28,代码来源:submit_canonical.py

示例2: test

    def test(self, structure):
        failures = []

        if self.is_valid:
            if not structure.is_valid():
                failures.append("IS_VALID=False")

        if self.potcar_exists:
            elements = structure.composition.elements
            if set(elements).intersection(set(self.NO_POTCARS)):
                failures.append("POTCAR_EXISTS=False")

        if self.max_natoms:
            if structure.num_sites > self.max_natoms:
                failures.append("MAX_NATOMS=Exceeded")

        if self.is_ordered:
            if not structure.is_ordered:
                failures.append("IS_ORDERED=False")

        if self.not_in_MP:
            mpr = MPRester(self.MAPI_KEY)
            mpids = mpr.find_structure(structure)
            if mpids:
                if self.require_bandstructure:
                    for mpid in mpids:
                        try:
                            bs = mpr.get_bandstructure_by_material_id(mpid)
                            if bs:
                                failures.append("NOT_IN_MP=False ({})".format(mpid))
                        except:
                            pass
                else:
                    failures.append("NOT_IN_MP=False ({})".format(mpids[0]))
        return True if not failures else False
开发者ID:montoyjh,项目名称:MatMethods,代码行数:35,代码来源:submission_filter.py

示例3: run_task

    def run_task(self, fw_spec):

        mpr = MPRester(env_chk(self.get("MAPI_KEY"), fw_spec))
        vasprun, outcar = get_vasprun_outcar(self.get("calc_dir", "."), parse_dos=False, parse_eigen=False)

        my_entry = vasprun.get_computed_entry(inc_structure=False)
        stored_data = mpr.get_stability([my_entry])[0]

        if stored_data["e_above_hull"] > self.get("ehull_cutoff", 0.05):
            return FWAction(stored_data=stored_data, exit=True, defuse_workflow=True)

        else:
            return FWAction(stored_data=stored_data)
开发者ID:hackingmaterials,项目名称:MatMethods,代码行数:13,代码来源:glue_tasks.py

示例4: __init__

 def __init__(self, api_key=None):
     """
     Args:
         api_key: (str) Your Materials Project API key, or None if you've
             set up your pymatgen config.
     """
     self.mprester = MPRester(api_key=api_key)
开发者ID:ardunn,项目名称:MatMiner,代码行数:7,代码来源:retrieve_MP.py

示例5: get_materials_list

def get_materials_list():
    """Fetch data (from local cache if available)."""
    try:
        _log.info('Trying data cache for materials')
        with open('materials_list.pickle') as f:
            return pickle.load(f)

    except IOError:
        _log.info('Fetching remote data')
        m = MPRester()
        materials_list = m.query(
            criteria={"elasticity": {"$exists": True}},
            properties=['pretty_formula', 'reduced_cell_formula', 'task_id',
                        "elasticity.K_VRH", "elasticity.K_VRH", 'volume',
                        'density', 'formation_energy_per_atom', 'nsites'])
        # Save for later
        with open('materials_list.pickle', 'w') as f:
            pickle.dump(materials_list, f)
        _log.info('Data loaded')
        return materials_list
开发者ID:HGeerlings,项目名称:eratosthenes,代码行数:20,代码来源:neigh_perf.py

示例6: __init__

 def __init__(self, materials_write, mapi_key=None, update_all=False):
     """
     Starting with an existing materials collection, adds stability information and The Materials Project ID.
     Args:
         materials_write: mongodb collection for materials (write access needed)
         mapi_key: (str) Materials API key (if MAPI_KEY env. var. not set)
         update_all: (bool) - if true, updates all docs. If false, only updates docs w/o a stability key
     """
     self._materials = materials_write
     self.mpr = MPRester(api_key=mapi_key)
     self.update_all = update_all
开发者ID:aykol,项目名称:MatMethods,代码行数:11,代码来源:materials_ehull.py

示例7: do_query

def do_query(args):
    m = MPRester()
    try:
        criteria = json.loads(args.criteria)
    except json.decoder.JSONDecodeError:
        criteria = args.criteria
    if args.structure:
        count = 0
        for d in m.query(criteria, properties=["structure", "task_id"]):
            s = d["structure"]
            formula = re.sub("\s+", "", s.formula)
            if args.structure == "poscar":
                fname = "POSCAR.%s_%s" % (d["task_id"], formula)
            else:
                fname = "%s-%s.%s" % (d["task_id"], formula, args.structure)
            s.to(filename=fname)
            count += 1
        print("%d structures written!" % count)
    elif args.entries:
        entries = m.get_entries(criteria)
        dumpfn(entries, args.entries)
        print("%d entries written to %s!" % (len(entries), args.entries))
    else:
        props = ["e_above_hull", "spacegroup"]
        props += args.data
        entries = m.get_entries(criteria, property_data=props)
        t = []
        headers = ["mp-id", "Formula", "Spacegroup", "E/atom (eV)",
                   "E above hull (eV)"] + args.data
        for e in entries:
            row = [e.entry_id, e.composition.reduced_formula,
                   e.data["spacegroup"]["symbol"],
                   e.energy_per_atom, e.data["e_above_hull"]]
            row += [e.data[s] for s in args.data]

            t.append(row)

        t = sorted(t, key=lambda x: x[headers.index("E above hull (eV)")])
        print(tabulate(t, headers=headers, tablefmt="pipe", floatfmt=".3f"))
开发者ID:adozier,项目名称:pymatgen,代码行数:39,代码来源:pmg_query.py

示例8: test_mpr_pipeline

    def test_mpr_pipeline(self):
        from pymatgen import MPRester
        mpr = MPRester()
        data = mpr.get_pourbaix_entries(["Zn"])
        pbx = PourbaixDiagram(data, filter_solids=True, conc_dict={"Zn": 1e-8})
        pbx.find_stable_entry(10, 0)

        data = mpr.get_pourbaix_entries(["Ag", "Te"])
        pbx = PourbaixDiagram(data, filter_solids=True,
                              conc_dict={"Ag": 1e-8, "Te": 1e-8})
        self.assertEqual(len(pbx.stable_entries), 30)
        test_entry = pbx.find_stable_entry(8, 2)
        self.assertAlmostEqual(test_entry.energy, 2.393900378500001)

        # Test custom ions
        entries = mpr.get_pourbaix_entries(["Sn", "C", "Na"])
        ion = IonEntry(Ion.from_formula("NaO28H80Sn12C24+"), -161.676)
        custom_ion_entry = PourbaixEntry(ion, entry_id='my_ion')
        pbx = PourbaixDiagram(entries + [custom_ion_entry], filter_solids=True,
                              comp_dict={"Na": 1, "Sn": 12, "C": 24})
        self.assertAlmostEqual(pbx.get_decomposition_energy(custom_ion_entry, 5, 2),
                               8.31082110278154)
开发者ID:mbkumar,项目名称:pymatgen,代码行数:22,代码来源:test_pourbaix_diagram.py

示例9: run

def run(mpfile, **kwargs):
    from pymatgen import MPRester, Composition
    import pandas as pd

    input_file = mpfile.document['_hdata'].pop('input_file')
    file_path = os.path.join(os.environ['HOME'], 'work', input_file)
    if not os.path.exists(file_path):
        return 'Please upload', file_path
    df_dct = pd.read_excel(file_path)
    columns_units = [
        ('A-Site', ''), ('B-Site', ''), ('a', 'Å'),
        ('Eᶠ|ABO₃', 'eV'), ('Eᶠ|Yᴮ', 'eV'), ('Eᶠ|Vᴼ', 'eV'),
        ('Eᶠ|Hᵢ', 'eV'), ('ΔEᵢ|Yᴮ-Hᵢ', 'eV')
    ]
    columns = df_dct.columns
    mpr = MPRester(endpoint="http://materialsproject.org:8080/rest/v2")

    for row_idx, row in df_dct.iterrows():
        formula = '{}{}O3'.format(row[columns[0]], row[columns[1]])
        comp = Composition(formula)
        crit = {"reduced_cell_formula": comp.to_reduced_dict, "nsites": 5}
        docs = mpr.query(criteria=crit, properties=["task_id", "volume"])
        if len(docs) > 1:
            volume = row[columns[2]]**3
            volumes = pd.np.array([r['volume'] for r in docs])
            idx = pd.np.abs(volumes-volume).argmin()
            identifier = docs[idx]['task_id']
            continue
        elif not docs:
            print formula, 'not found on MP'
            continue
        else:
            identifier = docs[0]['task_id']
        print formula, '->', identifier
        d = RecursiveDict()
        for col, (key, unit) in zip(columns, columns_units):
            d[key] = clean_value(row[col], unit)
        mpfile.add_hierarchical_data(nest_dict(d, ['data']), identifier=identifier)
开发者ID:ATNDiaye,项目名称:MPContribsUsers,代码行数:38,代码来源:pre_submission.py

示例10: __init__

class MaterialsEhullBuilder:
    def __init__(self, materials_write, mapi_key=None, update_all=False):
        """
        Starting with an existing materials collection, adds stability information and
        The Materials Project ID.
        Args:
            materials_write: mongodb collection for materials (write access needed)
            mapi_key: (str) Materials API key (if MAPI_KEY env. var. not set)
            update_all: (bool) - if true, updates all docs. If false, only updates
                docs w/o a stability key
        """
        self._materials = materials_write
        self.mpr = MPRester(api_key=mapi_key)
        self.update_all = update_all

    def run(self):
        print("MaterialsEhullBuilder starting...")
        self._build_indexes()

        q = {"thermo.energy": {"$exists": True}}
        if not self.update_all:
            q["stability"] = {"$exists": False}

        mats = [m for m in self._materials.find(q, {"calc_settings": 1, "structure": 1,
                                                    "thermo.energy": 1, "material_id": 1})]
        pbar = tqdm(mats)
        for m in pbar:
            pbar.set_description("Processing materials_id: {}".format(m['material_id']))
            try:
                params = {}
                for x in ["is_hubbard", "hubbards", "potcar_spec"]:
                    params[x] = m["calc_settings"][x]

                structure = Structure.from_dict(m["structure"])
                energy = m["thermo"]["energy"]
                my_entry = ComputedEntry(structure.composition, energy, parameters=params)
                self._materials.update_one({"material_id": m["material_id"]},
                                           {"$set": {"stability": self.mpr.get_stability([my_entry])[0]}})

                mpids = self.mpr.find_structure(structure)
                self._materials.update_one({"material_id": m["material_id"]}, {"$set": {"mpids": mpids}})

            except:
                import traceback
                print("<---")
                print("There was an error processing material_id: {}".format(m))
                traceback.print_exc()
                print("--->")

        print("MaterialsEhullBuilder finished processing.")


    def reset(self):
        self._materials.update_many({}, {"$unset": {"stability": 1}})
        self._build_indexes()

    def _build_indexes(self):
        self._materials.create_index("stability.e_above_hull")


    @staticmethod
    def from_db_file(db_file, m="materials", **kwargs):
        """
        Get a MaterialsEhullBuilder using only a db file
        Args:
            db_file: (str) path to db file
            m: (str) name of "materials" collection
            **kwargs: other parameters to feed into the builder, e.g. mapi_key
        """
        db_write = get_database(db_file, admin=True)
        return MaterialsEhullBuilder(db_write[m], **kwargs)
开发者ID:saurabh02,项目名称:MatMethods,代码行数:71,代码来源:materials_ehull.py

示例11: MaterialsEhullBuilder

class MaterialsEhullBuilder(AbstractBuilder):
    def __init__(self, materials_write, mapi_key=None, update_all=False):
        """
        Starting with an existing materials collection, adds stability information and
        The Materials Project ID.
        Args:
            materials_write: mongodb collection for materials (write access needed)
            mapi_key: (str) Materials API key (if MAPI_KEY env. var. not set)
            update_all: (bool) - if true, updates all docs. If false, only updates
                docs w/o a stability key
        """
        self._materials = materials_write
        self.mpr = MPRester(api_key=mapi_key)
        self.update_all = update_all

    def run(self):
        logger.info("MaterialsEhullBuilder starting...")
        self._build_indexes()

        q = {"thermo.energy": {"$exists": True}}
        if not self.update_all:
            q["stability"] = {"$exists": False}

        mats = [m for m in self._materials.find(q, {"calc_settings": 1, "structure": 1,
                                                    "thermo.energy": 1, "material_id": 1})]
        pbar = tqdm(mats)
        for m in pbar:
            pbar.set_description("Processing materials_id: {}".format(m['material_id']))
            try:
                params = {}
                for x in ["is_hubbard", "hubbards", "potcar_spec"]:
                    params[x] = m["calc_settings"][x]

                structure = Structure.from_dict(m["structure"])
                energy = m["thermo"]["energy"]
                my_entry = ComputedEntry(structure.composition, energy, parameters=params)

                # TODO: @computron This only calculates Ehull with respect to Materials Project.
                # It should also account for the current database's results. -computron
                self._materials.update_one({"material_id": m["material_id"]},
                                           {"$set": {"stability": self.mpr.get_stability([my_entry])[0]}})

                # TODO: @computron: also add additional properties like inverse hull energy?

                # TODO: @computron it's better to use PD tool or reaction energy calculator
                # Otherwise the compatibility schemes might have issues...one strategy might be
                # use MP only to retrieve entries but compute the PD locally -computron
                for el, elx in my_entry.composition.items():
                    entries = self.mpr.get_entries(el.symbol, compatible_only=True)
                    min_e = min(entries, key=lambda x: x.energy_per_atom).energy_per_atom
                    energy -= elx * min_e
                self._materials.update_one({"material_id": m["material_id"]},
                                           {"$set": {"thermo.formation_energy_per_atom": energy / structure.num_sites}})

                mpids = self.mpr.find_structure(structure)
                self._materials.update_one({"material_id": m["material_id"]}, {"$set": {"mpids": mpids}})

            except:
                import traceback
                logger.exception("<---")
                logger.exception("There was an error processing material_id: {}".format(m))
                logger.exception(traceback.format_exc())
                logger.exception("--->")

        logger.info("MaterialsEhullBuilder finished processing.")

    def reset(self):
        logger.info("Resetting MaterialsEhullBuilder")
        self._materials.update_many({}, {"$unset": {"stability": 1}})
        self._build_indexes()
        logger.info("Finished resetting MaterialsEhullBuilder")

    def _build_indexes(self):
        self._materials.create_index("stability.e_above_hull")

    @classmethod
    def from_file(cls, db_file, m="materials", **kwargs):
        """
        Get a MaterialsEhullBuilder using only a db file
        Args:
            db_file: (str) path to db file
            m: (str) name of "materials" collection
            **kwargs: other parameters to feed into the builder, e.g. mapi_key
        """
        db_write = get_database(db_file, admin=True)
        return cls(db_write[m], **kwargs)
开发者ID:montoyjh,项目名称:MatMethods,代码行数:86,代码来源:materials_ehull.py

示例12: SurfaceEnergyAnalyzer

class SurfaceEnergyAnalyzer(object):

    """
    A class used for analyzing the surface energies of a material of a given
        material_id. By default, this will use entries calculated from the
        Materials Project to obtain chemical potential and bulk energy. As a
        result, the difference in VASP parameters between the user's entry
        (vasprun_dict) and the parameters used by Materials Project, may lead
        to a rough estimate of the surface energy. For best results, it is
        recommend that the user calculates all decomposition components first,
        and insert the results into their own database as a pymatgen-db entry
        and use those entries instead (custom_entries). In addition, this code
        will only use one bulk entry to calculate surface energy. Ideally, to
        get the most accurate surface energy, the user should compare their
        slab energy to the energy of the oriented unit cell with both calculations
        containing consistent k-points to avoid converegence problems as the
        slab size is varied. See:
            Sun, W.; Ceder, G. Efficient creation and convergence of surface slabs,
                Surface Science, 2013, 617, 53–59, doi:10.1016/j.susc.2013.05.016.
        and
            Rogal, J., & Reuter, K. (2007). Ab Initio Atomistic Thermodynamics for
                Surfaces : A Primer. Experiment, Modeling and Simulation of Gas-Surface
                Interactions for Reactive Flows in Hypersonic Flights, 2–1 – 2–18.

    .. attribute:: ref_element

        All chemical potentials cna be written in terms of the range of chemical
            potential of this element which will be used to calculate surface energy.

    .. attribute:: mprester

        Materials project rester for querying entries from the materials project.
            Requires user MAPIKEY.

    .. attribute:: ucell_entry

        Materials Project entry of the material of the slab.

    .. attribute:: x

        Reduced amount composition of decomposed compound A in the bulk.

    .. attribute:: y

        Reduced amount composition of ref_element in the bulk.

    .. attribute:: gbulk

        Gibbs free energy of the bulk per formula unit

    .. attribute:: chempot_range

        List of the min and max chemical potential of ref_element.

    .. attribute:: e_of_element

        Energy per atom of ground state ref_element, eg. if ref_element=O,
            than e_of_element=1/2*E_O2.

    .. attribute:: vasprun_dict

        Dictionary containing a list of Vaspruns for slab calculations as
            items and the corresponding Miller index of the slab as the key

    """

    def __init__(self, material_id, vasprun_dict, ref_element,
                 exclude_ids=[], custom_entries=[], mapi_key=None):
        """
        Analyzes surface energies and Wulff shape of a particular
            material using the chemical potential.
        Args:
            material_id (str): Materials Project material_id (a string,
                e.g., mp-1234).
            vasprun_dict (dict): Dictionary containing a list of Vaspruns
                for slab calculations as items and the corresponding Miller
                index of the slab as the key.
                eg. vasprun_dict = {(1,1,1): [vasprun_111_1, vasprun_111_2,
                vasprun_111_3], (1,1,0): [vasprun_111_1, vasprun_111_2], ...}
            element: element to be considered as independent
                variables. E.g., if you want to show the stability
                ranges of all Li-Co-O phases wrt to uLi
            exclude_ids (list of material_ids): List of material_ids
                to exclude when obtaining the decomposition components
                to calculate the chemical potential
            custom_entries (list of pymatgen-db type entries): List of
                user specified pymatgen-db type entries to use in finding
                decomposition components for the chemical potential
            mapi_key (str): Materials Project API key for accessing the
                MP database via MPRester
        """

        self.ref_element = ref_element
        self.mprester = MPRester(mapi_key) if mapi_key else MPRester()
        self.ucell_entry = \
            self.mprester.get_entry_by_material_id(material_id,
                                                   inc_structure=True,
                                                   property_data=
                                                   ["formation_energy_per_atom"])
        ucell = self.ucell_entry.structure
#.........这里部分代码省略.........
开发者ID:matk86,项目名称:pymatgen,代码行数:101,代码来源:surface_analysis.py

示例13: MPRester

from pymatgen import MPRester
from pymatgen.analysis.defects import point_defects
from pymatgen.io import vasp
from pymatgen.io.vasp.sets import MPStaticVaspInputSet
from pymatgen.io.zeoone import get_voronoi_nodes, get_void_volume_surfarea, get_high_accuracy_voronoi_nodes
try:
    from zeo.netstorage import AtomNetwork, VoronoiNetwork
    from zeo.area_volume import volume, surface_area
    from zeo.cluster import get_nearest_largest_diameter_highaccuracy_vornode,\
            generate_simplified_highaccuracy_voronoi_network, \
            prune_voronoi_network_close_node
    zeo_found = True
except ImportError:
    zeo_found = False		 

m = MPRester(key)

#def get_POSCAR(elements, interstitial, supercell_size, ):

results = m.query("Fe", ['structure'])
print(type(results[2]['structure']))
#Mg_cell = mg.Lattice.hexagonal(3.184, 5.249)

#print(Mg_cell.lengths_and_angles)

#Mg_Lattice = mg.Structure(Mg_cell, ["Mg","Mg"], [[.333333333,.66666666666,.25], [.66666666666,.33333333333333,.75]])
print(results[2]['structure'])
Mg_Lattice=results[2]['structure']
#Mg_Lattice = results[0]

Mg_Interstitial = point_defects.Interstitial(Mg_Lattice, {u"Fe":0}, {u"Fe":1.26}, 'voronoi_vertex',accuracy=u'Normal',symmetry_flag=True,oxi_state=False)
开发者ID:HGeerlings,项目名称:dislocat,代码行数:31,代码来源:defects.py

示例14: __init__

    def __init__(self, material_id, vasprun_dict, ref_element,
                 exclude_ids=[], custom_entries=[], mapi_key=None):
        """
        Analyzes surface energies and Wulff shape of a particular
            material using the chemical potential.
        Args:
            material_id (str): Materials Project material_id (a string,
                e.g., mp-1234).
            vasprun_dict (dict): Dictionary containing a list of Vaspruns
                for slab calculations as items and the corresponding Miller
                index of the slab as the key.
                eg. vasprun_dict = {(1,1,1): [vasprun_111_1, vasprun_111_2,
                vasprun_111_3], (1,1,0): [vasprun_111_1, vasprun_111_2], ...}
            element: element to be considered as independent
                variables. E.g., if you want to show the stability
                ranges of all Li-Co-O phases wrt to uLi
            exclude_ids (list of material_ids): List of material_ids
                to exclude when obtaining the decomposition components
                to calculate the chemical potential
            custom_entries (list of pymatgen-db type entries): List of
                user specified pymatgen-db type entries to use in finding
                decomposition components for the chemical potential
            mapi_key (str): Materials Project API key for accessing the
                MP database via MPRester
        """

        self.ref_element = ref_element
        self.mprester = MPRester(mapi_key) if mapi_key else MPRester()
        self.ucell_entry = \
            self.mprester.get_entry_by_material_id(material_id,
                                                   inc_structure=True,
                                                   property_data=
                                                   ["formation_energy_per_atom"])
        ucell = self.ucell_entry.structure

        # Get x and y, the number of species in a formula unit of the bulk
        reduced_comp = ucell.composition.reduced_composition.as_dict()
        if len(reduced_comp.keys()) == 1:
            x = y = reduced_comp[ucell[0].species_string]
        else:
            for el in reduced_comp.keys():
                if self.ref_element == el:
                    y = reduced_comp[el]
                else:
                    x = reduced_comp[el]

        # Calculate Gibbs free energy of the bulk per unit formula
        gbulk = self.ucell_entry.energy /\
                (len([site for site in ucell
                      if site.species_string == self.ref_element]) / y)

        entries = [entry for entry in
                   self.mprester.get_entries_in_chemsys(list(reduced_comp.keys()),
                                                        property_data=["e_above_hull",
                                                                       "material_id"])
                   if entry.data["e_above_hull"] == 0 and
                   entry.data["material_id"] not in exclude_ids] \
            if not custom_entries else custom_entries

        pd = PhaseDiagram(entries)
        chempot_ranges = pd.get_chempot_range_map([Element(self.ref_element)])
        # If no chemical potential is found, we return u=0, eg.
        # for a elemental system, the relative u of Cu for Cu is 0
        chempot_range = [chempot_ranges[entry] for entry in chempot_ranges.keys()
                         if entry.composition ==
                         self.ucell_entry.composition][0][0]._coords if \
            chempot_ranges else [[0,0], [0,0]]

        e_of_element = [entry.energy_per_atom for entry in
                        entries if str(entry.composition.reduced_composition)
                        == self.ref_element + "1"][0]

        self.x = x
        self.y = y
        self.gbulk = gbulk
        chempot_range = list(chempot_range)
        self.chempot_range = sorted([chempot_range[0][0], chempot_range[1][0]])
        self.e_of_element = e_of_element
        self.vasprun_dict = vasprun_dict
开发者ID:matk86,项目名称:pymatgen,代码行数:79,代码来源:surface_analysis.py

示例15: MPDataRetrieval

class MPDataRetrieval(BaseDataRetrieval):
    """
    Retrieves data from the Materials Project database.

    If you use this data retrieval class, please additionally cite:

    Ong, S.P., Cholia, S., Jain, A., Brafman, M., Gunter, D., Ceder, G.,
    Persson, K.A., 2015. The Materials Application Programming Interface
    (API): A simple, flexible and efficient API for materials data based on
    REpresentational State Transfer (REST) principles. Computational
    Materials Science 97, 209–215.
    https://doi.org/10.1016/j.commatsci.2014.10.037

    """

    def __init__(self, api_key=None):
        """
        Args:
            api_key: (str) Your Materials Project API key, or None if you've
                set up your pymatgen config.
        """
        self.mprester = MPRester(api_key=api_key)

    def api_link(self):
        return "https://materialsproject.org/wiki/index.php/The_Materials_API"

    def get_dataframe(self, criteria, properties, index_mpid=True, **kwargs):
        """
        Gets data from MP in a dataframe format. See api_link for more details.

        Args:
            criteria (dict): the same as in get_data
            properties ([str]): the same properties supported as in get_data
                plus: "structure", "initial_structure", "final_structure",
                "bandstructure" (line mode), "bandstructure_uniform",
                "phonon_bandstructure", "phonon_ddb", "phonon_bandstructure",
                "phonon_dos". Note that for a long list of compounds, it may
                take a long time to retrieve some of these objects.
            index_mpid (bool): the same as in get_data
            kwargs (dict): the same keyword arguments as in get_data

        Returns (pandas.Dataframe):
        """
        data = self.get_data(criteria=criteria, properties=properties,
                             index_mpid=index_mpid, **kwargs)
        df = pd.DataFrame(data, columns=properties)
        for prop in ["dos", "phonon_dos",
                     "phonon_bandstructure", "phonon_ddb"]:
            if prop in properties:
                df[prop] = self.try_get_prop_by_material_id(
                    prop=prop, material_id_list=df["material_id"].values)
        if "bandstructure" in properties:
            df["bandstructure"] = self.try_get_prop_by_material_id(
                prop="bandstructure",
                material_id_list=df["material_id"].values,
                line_mode=True)
        if "bandstructure_uniform" in properties:
            df["bandstructure_uniform"] = self.try_get_prop_by_material_id(
                prop="bandstructure",
                material_id_list=df["material_id"].values,
                line_mode=False)
        if index_mpid:
            df = df.set_index("material_id")
        return df

    def get_data(self, criteria, properties, mp_decode=False, index_mpid=True):
        """
        Args:
            criteria: (str/dict) see MPRester.query() for a description of this
                parameter. String examples: "mp-1234", "Fe2O3", "Li-Fe-O',
                "\\*2O3". Dict example: {"band_gap": {"$gt": 1}}

            properties: (list) see MPRester.query() for a description of this
                parameter. Example: ["formula", "formation_energy_per_atom"]

            mp_decode: (bool) see MPRester.query() for a description of this
                parameter. Whether to decode to a Pymatgen object where
                possible.

            index_mpid: (bool) Whether to set the materials_id as the dataframe
                index.

        Returns ([dict]):
            a list of jsons that match the criteria and contain properties
        """
        if index_mpid and "material_id" not in properties:
            properties.append("material_id")
        data = self.mprester.query(criteria, properties, mp_decode)
        return data

    def try_get_prop_by_material_id(self, prop, material_id_list, **kwargs):
        """
        Call the relevant get_prop_by_material_id. "prop" is a property such
        as bandstructure that is not readily available in supported properties
        of the get_data function but via the get_bandstructure_by_material_id
        method for example.

        Args:
            prop (str): the name of the property. Options are:
                "bandstructure", "dos", "phonon_dos", "phonon_bandstructure",
#.........这里部分代码省略.........
开发者ID:ardunn,项目名称:MatMiner,代码行数:101,代码来源:retrieve_MP.py


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