def make_input(potcar_path, amobt_path, scripts_path, id='noid', GEOM=False, SELF=False, NSELF=False, NSELF_AMOBT=False, DIEL=False, PHONON=False, DEFORM=False, AMOBT=False, SOC=False, computer='partita'): mp_api_key = 'fDJKEZpxSyvsXdCt' with open('MIKECAR', 'w') as input: input.write('EMAIL = [email protected] \n') input.write('MP_API_KEY = ' + mp_api_key + ' \n') input.write('JOB_NAME = See_Folder \n') input.write('COMP_NAME = ' + id + ' \n') input.write('%s %s \n' % ('GEOM =', GEOM)) input.write('%s %s \n' % ('SELF =', SELF)) input.write('%s %s \n' % ('NSELF =', NSELF)) input.write('%s %s \n' % ('NSELF_AMOBT =', NSELF_AMOBT)) input.write('%s %s \n' % ('DIEL =', DIEL)) input.write('%s %s \n' % ('PHONON =', PHONON)) api = mp.MPRester(mp_api_key) if ('mp-' in id) or ('mvc-' in id): structure = api.get_structure_by_material_id(id) structure.to(filename="POSCAR") with open('POSCAR', 'r') as poscar: counter = 0 natoms = 0 for line in poscar: counter += 1 if counter == 7: for i in line.split(): natoms += int(i) os.system('rm POSCAR') if natoms < 15: input.write('DIM = 2x2x2 \n') else: input.write('DIM = 1x1x1 \n') else: input.write('DIM = 1x1x1 \n') input.write('%s %s \n' % ('DEFORM =', DEFORM)) input.write('RANGE = -5,5 \n') input.write('POSCAR = default \n') input.write('INCAR = default \n') input.write('%s %s \n' % ('AMOBT =', AMOBT)) input.write('%s %s \n' % ('SOC =', SOC)) input.write('%s %s \n' % ('COMPUTER =', computer)) input.write('%s %s \n' % ('AMOBT_PATH =', amobt_path)) input.write('%s %s \n' % ('SCRIPTS_PATH =', scripts_path)) input.write('%s %s \n' % ('POTCAR_PATH =', potcar_path))
def cubic_searcher(): with pymatgen.MPRester('3GmMFkADz6xU7aJ1') as REST: infos = REST.query(criteria={ 'has_bandstructure': True, 'is_hubbard': False, 'crystal_system': 'cubic' }, properties=['material_id']) ids = [] for info in infos: ids += [info['material_id']] with open('saved_ids', 'w') as saved_ids: json.dump(ids, saved_ids) print(len(ids))
def band_crawler(): with open('saved_ids', 'r') as saved_ids: ids = json.load(saved_ids) with pymatgen.MPRester('3GmMFkADz6xU7aJ1') as REST: bands = [] for id in ids: band = REST.get_bandstructure_by_material_id(id).as_dict() band['id'] = id for i in range(len(band['vbm']['kpoint_index'])): band['vbm']['kpoint_index'][i] = str( band['vbm']['kpoint_index'][i]) for i in range(len(band['cbm']['kpoint_index'])): band['cbm']['kpoint_index'][i] = str( band['cbm']['kpoint_index'][i]) bands += [band] print(len(bands)) with open('saved_bands', 'w') as saved_bands: json.dump(bands, saved_bands)
def structure_crawler(gener): with open(str(gener) + '/saved_trimmed_bands', 'r') as saved_bands: bands = json.load(saved_bands) ids = [band[0] for band in bands] tem = ids batch = 1000 structures = [] for i in range(math.ceil(len(ids) / batch)): if len(tem) >= batch: par = tem[:batch] tem = tem[batch:] else: par = tem with pymatgen.MPRester('3GmMFkADz6xU7aJ1') as REST: structure = REST.query( criteria={'material_id': { '$in': par }}, properties=['material_id', 'final_structure'], mp_decode=False) structures += structure with open(str(gener) + '/saved_structures', 'w') as saved_structures: json.dump(structures, saved_structures)
#!/usr/bin/env python import pymatgen import pymatgen.structure_prediction as sp import pymatgen.core.structure as stt from pymatgen.structure_prediction import substitutor from pymatgen.core.periodic_table import Specie from pymatgen.transformations.standard_transformations import AutoOxiStateDecorationTransformation mp_api_key = 'fDJKEZpxSyvsXdCt' api = pymatgen.MPRester(mp_api_key) id = 'mp-2068' st = api.get_structure_by_material_id(id) # print(st.composition) # #print(structure.atomic_numbers) # # print(structure) # print(dir(st)) # j = st.SiteCollection.get_distance(0,4) # j = st.lattice_vectors # print(j) # list = pymatgen.structure_prediction.pred_from_structures(st) # print(dir(sp)) # print(sp.__path__) # print(sp.__doc__) # print(dir(pymatgen.core.structure)) # print(dir(stt.SiteCollection)) # print(sp.__builtins__) # print(dir(test))
def get_structure(run_specs): """ Get pymatgen.Structure. There are many ways to get a structure. They are all specified under 'poscar' tag in the specs file. There are two ways to get a structure. 1. From an already made structure, either from a template POSCAR, or a Materials Project database entry. (Recommended) If 'template' is present in 'poscar', you can either set the VASP_TEMPLATES_DIR environmental variable, or just leave it to the default 'INPUT/TEMPLATES'. After that, this specified POSCAR-type template file path will be used to obtain the structure from the VASP_TEMPLATES_DIR, and a structure is returned. If you set 'rel_to_run_dir' to True, 'template' refers to the file relative to the 'run_dir'. If 'material_id' is present in 'poscar', MAPI_KEY environmental variable needs to be set according to the Materials Project (materialsproject.org). An optional 'get_structure' can be set to one of ['primitive', 'reduced', 'sorted', 'conventional_standard', 'primitive_standard', 'refined'] For 'primitive', 'conventional_standard' and so on, an additional tag 'prec' controls the tolerence/symmetry finding precision threshold. The 'primitive', 'reduced' and 'sorted' are methods of the object pmg.Structure, while the rest are methods of pmg.symmetry.analyzer.SpacegroupAnalyzer. Please refer to the pymatgen docs to see what they are exactly. Be careful about whether the resultent structure is what you want. When in doubt, always manually run the pymatgen commands and see the outcome. By default, the code uses the element types written in the structure to generate the POTCAR by maintaining the existence of 'elem_types'. However, if you set 'repl_elems' with a dict, like {N: C, Ti: Ti_sv}, the elements in the structure will be accordingly replaced and the necessary mechanism is in place to make sure POTCAR is to be generated with the flavored potentials. Setting 'elem_types' in the specs file as a list of potentials (can have flavors like Ti_sv) in the same sequence as in the structure also works, but one has to be careful to match the sequence correctly. Not recommended. An optional 'volume' can be set to scale the structure of the template. 2. From manual description. (Cumbersome) The manual generation from spacegroup is done by specifying 'spacegroup' (international number or symbol) 'cryst_sys' (one of the seven) 'lattice_params' ('a', 'b', 'c', 'alpha', 'beta', 'gamma', some of which 'can be omitted because of a more symmetric crystallographic system) 'elem_types' (the elements in the structure, which can be flavored 'potentials, e.g. Ti_sv) 'atoms_multitude' (multitude of atoms of the same element type in a list, 'the sequence following 'elem_types'. Only symmetrically distinct species and 'coords should be provided, according to the Wychoff positions) 'atoms_direct_coords' (direct locations, relative to the lattice vectors 'of the symmetrically distinct atoms. There should be the same number of 'them as the sum of atoms_multitude) """ is_template = None is_material_id = None poscar_specs = run_specs['poscar'] if 'template' in poscar_specs: is_template = True if 'rel_to_run_dir' in poscar_specs and poscar_specs['rel_to_run_dir']: poscar = mg.io.vasp.Poscar.from_file(poscar_specs['template']) else: poscar = mg.io.vasp.Poscar.from_file( os.path.join(VASP_TEMPLATES_DIR, poscar_specs['template'])) structure = poscar.structure elif 'material_id' in poscar_specs: is_material_id = True m = mg.MPRester() structure = m.get_structure_by_material_id(poscar_specs['material_id']) if is_template or is_material_id: if 'get_structure' in poscar_specs: prec = poscar_specs['prec'] if 'prec' in poscar_specs else 1e-3 sga = mg.symmetry.analyzer.SpacegroupAnalyzer(structure, symprec=prec) if poscar_specs['get_structure'] == 'sorted': structure = structure.get_sorted_structure() if poscar_specs['get_structure'] == 'reduced': structure = structure.get_reduced_structure() elif poscar_specs['get_structure'] == 'primitive': structure = structure.get_primitive_structure(prec) elif poscar_specs['get_structure'] == 'primitive_standard': structure = sga.get_primitive_standard_structure() elif poscar_specs['get_structure'] == 'conventional_standard': structure = sga.get_conventional_standard_structure() elif poscar_specs['get_structure'] == 'refined': structure = sga.get_refined_structure() symbol_set = list(structure.symbol_set) if 'repl_elems' in run_specs: for idx, symbol in enumerate(symbol_set): if symbol in run_specs['repl_elems']: symbol_set[idx] = run_specs['repl_elems'][symbol] repl_elems_struct = { key: re.sub(r'_.*', '', value) for key, value in run_specs['repl_elems'].items() } structure.replace_species(repl_elems_struct) run_specs['elem_types'] = symbol_set if 'volume' in poscar_specs: structure.scale_lattice(poscar_specs['volume']) return structure else: cryst_sys = poscar_specs['cryst_sys'] lattice_params = poscar_specs['lattice_params'] if cryst_sys == 'cubic': lattice = mg.Lattice.cubic(lattice_params['a']) elif cryst_sys == 'hexagonal': lattice = mg.Lattice.hexagonal(lattice_params['a'], lattice_params['alpha']) elif cryst_sys == 'tetragonal': lattice = mg.Lattice.tetragonal(lattice_params['a'], lattice_params['c']) elif cryst_sys == 'orthorhombic': lattice = mg.Lattice.orthorhombic(lattice_params['a'], lattice_params['b'], lattice_params['c']) elif cryst_sys == 'rhombohedral': lattice = mg.Lattice.rhombohedral(lattice_params['a'], lattice_params['alpha']) elif cryst_sys == 'monoclinic': lattice = mg.Lattice.orthorhombic(lattice_params['a'], lattice_params['b'], lattice_params['c'], lattice_params['beta']) else: lattice = mg.Lattice.orthorhombic(lattice_params['a'], lattice_params['b'], lattice_params['c'], lattice_params['alpha'], lattice_params['beta'], lattice_params['gamma']) elem_types_struct = [ re.sub(r'_.*', '', i) for i in poscar_specs['elem_types'] ] elem_types_struct_multi = [] for i, elem in enumerate(elem_types_struct): elem_types_struct_multi.extend([elem] * poscar_specs['atoms_multitude'][i]) structure = mg.Structure.from_spacegroup( poscar_specs['spacegroup'], lattice, elem_types_struct_multi, poscar_specs['atoms_direct_coords']) run_specs['elem_types'] = poscar_specs['elem_types'] return structure
参考自 1. https://github.com/materialsproject/mapidoc/blob/master/index.ipynb 2. https://docs.materialsproject.org/open-apis/the-materials-api/#pymatgen-wrapper 3. https://www.slideshare.net/shyuep/the-materials-api-v1/11-More_information_Materials_API_pymatgen 4. https://github.com/materialsproject/mapidoc @author: Xuan Ai [email protected] """ import pymatgen as mg import pymatgen.io.cif #这里填上自己申请的API keys 百度一下教程很多 api_keys = "XXXXXXXXXXXX" mpapi = mg.MPRester(api_keys) """ 关于关键词keywords 1. Formulae, e.g., "Li2O", "Fe2O3", "*TiO3" 2. Chemical systems, e.g., "Li-Fe-O", "*-Fe-O" 3. Materials ids, e.g., "mp-1234" 上面是官方给出的样例 """ datas = [] keywords = ["Fe2O3", "*TiO3", "*-Ti-O"] for keyword in keywords: datas.append(mpapi.get_data(keyword, prop="icsd_ids")) #datas[0]就是Fe2O3的结果 for i in range(0, len(datas[0])): #这里最蛋疼的地方就是没法一次性获得所有信息 但是参考1里面有高级玩法 暂时先套娃吧
] candidates = [s for s in all_labels if symbol == s.split('_')[0]] if ftype is not None: final = [ s for s in candidates if '_{}'.format(ftype) == s[-(len(ftype) + 1):] ] if len(final) > 0: potential_labels.append(final[0]) continue potential_labels.append(candidates[0]) return potential_labels # Get the crystal structure and other info. from Materials Project (using pymatgen) rester = pymatgen.MPRester(os.environ['PMG_MAPI_KEY']) pmg_structure = rester.get_structure_by_material_id(structure_id) pmg_band = rester.get_bandstructure_by_material_id(structure_id) material_name = pmg_structure.formula.replace('1', '').replace(' ', '') print(material_name) spa = SpacegroupAnalyzer(pmg_structure) conventional = spa.get_conventional_standard_structure() primitive = spa.get_primitive_standard_structure() primitive_matrix = np.dot(np.linalg.inv(conventional.lattice.matrix), primitive.lattice.matrix) primitive_matrix = np.round(primitive_matrix, decimals=6).tolist()
# -*- coding: utf-8 -*- """ Created on Fri Feb 6 13:35:07 2015 @author: cabinian """ import pymatgen as mg with mg.MPRester() as m: #Bandstructure for material id bandstructure = m.get_bandstructure_by_material_id("mp-149") #obviously not anything interesting.. don't know how to get stuff out of the bandstructure object print(bandstructure)
inplace=True) # %% query the materials project # select the "formula" & "spacegroup_number" columns for query and remove duplicated rows mp_query_df = all_oxides[["formula", "spacegroup_number"]].drop_duplicates(ignore_index=True) # load in the api key # NOTE: If you want to run this script yourself, # you need to include your own Materials Project API key in a JSON format as a txt file under this directory with open(API_PATH) as f: api_key = json.load(f)["api_key"] # initialize a list to store all the structures struct_lst = [] with mg.MPRester(api_key) as m: for formula, spacegroup_number in zip(mp_query_df.formula, mp_query_df.spacegroup_number): try: # query structures based on the pretty formula and spacegroup number struct = m.query(criteria={"pretty_formula": formula, "spacegroup.number": spacegroup_number}, properties=["structure"])[0]["structure"] except IndexError: # if there isn't an exact, get the pretty formula struct = formula struct_lst.append(struct) # %% examine the query result # check which compounds don't have an exact match in Materials Project unmatched_struct = [structure for structure in struct_lst if isinstance(structure, str)] print("Number of unmatched structures: {}\n {}".format(len(unmatched_struct), unmatched_struct))
#!/usr/bin/python import sys import pymatgen as pm import pymatgen.io.cifio as cif for id in sys.argv[1:]: m = pm.MPRester("") struct = m.get_structure_by_material_id(id, False) ciff = cif.CifWriter(struct) ciff.write_file(id + '.cif')
import numpy as np import pymatgen # from pymatgen import MPRester from matminer.featurizers.site import CrystalNNFingerprint from matminer.featurizers.structure import SiteStatsFingerprint structuraldif = [] with pymatgen.MPRester("iUCzg5aBMJ1w30KT") as mpr: # Get structures. SnSelow = mpr.get_structure_by_material_id("mp-1984") SnSehigh = mpr.get_structure_by_material_id("mp-1411") # Calculate structure fingerprints. ssf = SiteStatsFingerprint(CrystalNNFingerprint.from_preset('cn')) v_SnSelow = np.array(ssf.featurize(SnSelow)) v_SnSehigh = np.array(ssf.featurize(SnSehigh)) v_SnSelow = v_SnSelow / np.linalg.norm(v_SnSelow) v_SnSehigh = v_SnSehigh / np.linalg.norm(v_SnSehigh) # Print out distance between structures. fish = '{:.4f}'.format(np.linalg.norm(v_SnSehigh - v_SnSelow)) structuraldif.append(fish) print(structuraldif)
if os.path.isfile("vasp-ib.csh") == True: y = "vasp-ib.csh" if os.path.isfile("vasp-mpi.csh") == True: y = "vasp-mpi.csh" if SOC in ['TRUE', 'True', 'true' ] and geom not in ['t', 'T', 'TRUE', 'True', 'true']: os.system('cp ~/vasp53_spin-orbit-coupling.mpi .') y = 'vasp53_spin-orbit-coupling.mpi' ############################################################ ###################### write POSCAR, POTCAR, KPOINTS, KPOINTS_NSELF ################## if poscar == "default": try: matproj = mp.MPRester(mp_api_key) structure = matproj.get_structure_by_material_id(comp_name) structure.to(filename="POSCAR") dum = matproj.query( criteria=comp_name, properties=["potcar_symbols", "potcar_spec", "pseudo_potential"]) potcar_labels = dum[0]["pseudo_potential"]["labels"] print( "The followng POTCAR labels have been read from The Materials Project and will be used:" ) print(potcar_labels) except: raise ValueError( comp_name + " could NOT be found in the Materials Project. Set poscar and incar to given if this is not a valid MPID" )
import numpy as np import pymatgen from matminer.featurizers.site import CrystalNNFingerprint from matminer.featurizers.structure import SiteStatsFingerprint f = open('2ddata_all.txt', 'r') lines = f.readlines() f.close() mpr = pymatgen.MPRester("iUCzg5aBMJ1w30KT") #the segment below captures the entire list, unfiltered all_mat_names = [] complete_list = [] for line in lines[1:]: if line[0] != "\n": parsed = line.split('\t') all_mat_names.append(parsed[1]) complete_list.append(parsed) #the segment below creates two new identical lists for furhter use, which contain all of the phase change materials PC_mats = [] chem_formulas = [] for index, list in enumerate(complete_list): mat_name = list[1] if all_mat_names.count(mat_name) > 1: PC_mats.append(list) chem_formulas.append(list) un_red = [] red_pc_mats = [] other_half = [] placeholderred_pc_mats = [] object = [] #below, it picks the highest e hull from each monolayer