本文整理匯總了Python中pymatgen.MPRester.query方法的典型用法代碼示例。如果您正苦於以下問題:Python MPRester.query方法的具體用法?Python MPRester.query怎麽用?Python MPRester.query使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pymatgen.MPRester
的用法示例。
在下文中一共展示了MPRester.query方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_materials_list
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
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
示例2: do_query
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
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"))
示例3: run
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
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)
示例4: MPRester
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
# Assuming you've done `export MAPI_KEY="USER_API_KEY"` at the command line
# See materialsproject.org/dashboard to get your API key
from pymatgen import MPRester
import numpy as np
import os
key = os.environ['MAPI_KEY']
m = MPRester(key)
e_cutoff = m.query("mp-46",
["elasticity.calculations.energy_cutoff"])[0]['elasticity.calculations.energy_cutoff'] # units (eV)
file = open("INCAR", "w")
file.write("LWAVE = .FALSE.\n")
file.write("LCHARG= .FALSE.\n")
file.write("PREC = Accurate\n")
file.write("LREAL = AUTO\n")
file.write("ADDGRID = .TRUE.\n")
file.write("POTIM = 0.1\n")
file.write("SIGMA = 0.05\n")
file.write("IBRION = 2\n")
file.write("NSW = 100\n")
file.write("ENCUT ={0:3d}\n".format(int(e_cutoff)))
file.write("EDIFF = 1e-8\n")
file.write("EDIFFG = -1e-3\n")
file.write("ISIF = 3\n")
file.close()
示例5: MPRester
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
# This script performs a blanket search for all systems with elasticity data.
from pymatgen import MPRester
import numpy as np
import os
key = os.environ['MAPI_KEY']
# Assuming you've done `export MAPI_KEY="USER_API_KEY"` at the command line
# See materialsproject.org/dashboard to get your API key
m = MPRester(key)
data = m.query(criteria={"elasticity": {"$exists": True}},
properties=["pretty_formula", "elasticity.elastic_tensor"])
示例6: MPRester
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
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)
print(Mg_Interstitial.enumerate_defectsites())
print(Mg_Interstitial.defectsite_count())
示例7: MPDataRetrieval
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
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",
#.........這裏部分代碼省略.........
示例8: get_tensor
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
def get_tensor(name):
m = MPRester(key)
tensor = m.query(criteria={"elasticity": {"$exists": True}, "pretty_formula": name},
properties=["elasticity.elastic_tensor"])
return tensor
示例9: structure
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
elif not job['is_ordered']:
print 'REJECTED WORKFLOW FOR {} - invalid structure (disordered)'.format(
snl.structure.formula)
else:
return True
return False
if __name__ == '__main__':
create_mincoll()
mp_unique_comps = set()
pf_unique_comps = set()
coll = db['pauling_file_mpmin']
new_coll = db['pf_to_mp']
new_coll.drop()
mp_comps = mpr.query(criteria={}, properties=["snl_final.reduced_cell_formula_abc"])
print 'Total number of MP comps = {}'.format(len(mp_comps))
for mp_comp in mp_comps:
mp_unique_comps.add(mp_comp["snl_final.reduced_cell_formula_abc"])
print 'Number of unique MP comps = {}'.format(len(mp_unique_comps))
x = 0
for doc in coll.find().batch_size(75):
x += 1
if x % 1000 == 0:
print x
# if x > 1:
# break
pf_unique_comps.add(doc['metadata']['_structure']['reduced_cell_formula_abc'])
if doc['metadata']['_structure']['reduced_cell_formula_abc'] not in mp_unique_comps:
new_coll.insert(doc_to_snl(doc).as_dict())
# with open('PaulingFile_example.json', 'w') as outfile:
示例10: data
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from pymatgen import MPRester
# import/truncate raw data (volume, density, energies, etc)
m = MPRester("ID")
data = m.query(criteria={"elasticity": {"$exists": True}},
properties=["pretty_formula", "volume", "K_VRH"])
# for now, import parameters and also bulk modulus (known), in future we will use parameters to select bulk moduli to be calculated
# subfunction for formatting
# define desired objectives and bounds/tolerances (GPa)
tolcost = 1e-5
kdes = 205
# define tuning/mating parameters
theta = 1/2
w1 = 1
# create objective function
cost = lambda k: w1*((kdes-k)/kdes)**2
# randomly sample data and calculate costs
示例11: get_avg_Z_num
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
def get_avg_Z_num(material, elem_list):
Z_list = []
for element in elem_list:
Z_list += [log(Element(element).Z)]
return np.average(Z_list)
def get_sd_X(material, elem_list):
X_list = []
for element in elem_list:
X_list += [log(Element(element).X)]
return np.std(X_list)
key = os.environ['MAPI_KEY']
m = MPRester(key)
materials_list = m.query(criteria={"elasticity": {"$exists": True}}, properties=['pretty_formula', 'reduced_cell_formula', "elasticity.K_VRH", 'volume', 'density', 'formation_energy_per_atom', 'formation_energy_per_atom', 'nsites'])
def vectorize_and_catalog(materials):
vector_list = []
catalog = {}
for material in materials:
element_list = element_lister(material)
vector = [get_ln_volume(material, element_list), get_c_energy_per_atom(material, element_list), get_avg_Z_num(material, element_list), get_sd_X(material, element_list)]
vector_list += [vector]
catalog[tuple(vector)] = material
return vector_list, catalog
def vector_to_material(vector):
return catalog[tuple(vector)]
示例12: cif_lib_build
# 需要導入模塊: from pymatgen import MPRester [as 別名]
# 或者: from pymatgen.MPRester import query [as 別名]
def cif_lib_build(self, crystal_system, size_limit=None):
''' function to build cif and pdf library based on space group symbol
Parameters
----------
crystal_system: str
name of crystal system. It capitalized, like CUBIC.
space group symbol will be generated by get_symbol_list method
size_list : int
optional. Uppder limit of data pulled out per symbol
'''
self.crystal_system = crystal_system
space_group_symbol = self.get_symbol_list(crystal_system)
if isinstance(space_group_symbol, list):
space_group_symbol_set = space_group_symbol
else:
space_group_symbol_set = list(spac_group_symbol)
## changing dir
data_dir = os.path.join(self.working_dir, crystal_system)
self.data_dir = data_dir
self._makedirs(data_dir)
os.chdir(data_dir)
if os.getcwd() == data_dir:
print('Library will be built at %s' % data_dir)
else:
e = 'Werid, return'
raise RuntimeError(e)
# summary lists
missed_list = [] # reference
m_id_list = [] # reference for searchs have been done in the past
time_info = time.strftime('%Y-%m-%d')
# create dirs, cif and calculated dir
cif_dir = os.path.join(data_dir, 'cif_data')
self._makedirs(cif_dir)
self.cif_dir = cif_dir
# looping
for space_group_symbol in space_group_symbol_set:
print('Building library with space_group symbol: {}'.format(space_group_symbol))
## search query
m = MPRester(self.API_key)
search = m.query(criteria = {"spacegroup.symbol": space_group_symbol},
properties = ["material_id"])
if search:
## crazy looping
if size_limit:
dim = 400 # 400 data sets per symbol
else:
dim = len(search)
print('Pull out %s data sets' % dim)
print('Now, starts to save cif and compute pdf...')
for i in range(dim):
# part 1: grab cif files from data base
m_id = search[i]['material_id']
m_id_list.append(m_id)
m_struc = m.get_structure_by_material_id(m_id)
m_formula = m_struc.formula
m_name = m_formula.replace(' ', '') # material name
cif_w = CifWriter(m_struc)
cif_name = '{}_{}.cif'.format(space_group_symbol, m_name)
cif_w_name = os.path.join(cif_dir, cif_name)
if os.path.isfile(cif_w_name):
print('already have {}, skip'.format(cif_name))
pass # skip files already exist
else:
cif_w.write_file(cif_w_name)
print('{} has been saved'.format(cif_name))
else:
print('Hmm, no reasult. Something wrong')
missed_list.append(space_group_symbol)
pass
m_id_list_name = '{}_{}_material_id.txt'.format(crystal_system, time_info)
m_id_list_w_name = os.path.join(data_dir, m_id_list_name)
np.savetxt(m_id_list_w_name, m_id_list)
print('''SUMMARY: for {} cystsal sytem,
Symbols {} can't be found from data base'''.format(crystal_system, missed_list))
return cif_dir