Esempio n. 1
1
def get_structure_from_mp(formula):
    """
    Convenience method to get a crystal from the Materials Project database via
    the API. Requires PMG_MAPI_KEY to be set.

    Args:
        formula (str): A formula

    Returns:
        (Structure) The lowest energy structure in Materials Project with that
            formula.
    """
    if not SETTINGS.get("PMG_MAPI_KEY"):
        raise RuntimeError("PMG_MAPI_KEY must be set in .pmgrc.yaml to use this "
                           "function.")

    from pymatgen.matproj.rest import MPRester
    m = MPRester()
    entries = m.get_entries(formula, inc_structure=True)
    if len(entries) == 0:
        raise ValueError("No structure with formula %s in Materials Project!" %
                         formula)
    elif len(entries) > 1:
        warnings.warn("%d structures with formula %s found in Materials Project."
                      "The lowest energy structure will be returned." %
                      (len(entries), formula))
    return min(entries, key=lambda e: e.energy_per_atom).structure
Esempio n. 2
0
 def _test_from_pm(self):
     """
     MPのデータをプロット
     """
     ent_list = []
     mpr = MPRester("WTxsDhRV7g2Mcbqw")
     composition = ['Fe', 'Ni', 'Si']
     entries = mpr.get_entries_in_chemsys(composition)
     for entry in entries:
         formula = entry.as_dict()['data']['unit_cell_formula']
         formation_e = entry.as_dict()['data']['formation_energy_per_atom']
         if formation_e <= 0:
             single_data = []
             sum_atoms = 0
             for elements, index in formula.items():
                 sum_atoms += index
             for element in composition:
                 try:
                     single_data.append(formula[element] / sum_atoms)
                 except KeyError:
                     single_data.append(0)
             single_data.append(formation_e * 96.485344520851)
             ent_list.append(single_data)
     initial_base = [[x[0], x[1], x[3]] for x in ent_list[0:3]]
     not_base = [[x[0], x[1], x[3]] for x in ent_list[3:]]
     fig = pylab.figure()
     ax = Axes3D(fig)
     convex_hull.draw_convex_hull(ax, initial_base, not_base,
                                  ['Fe', 'Ni', 'Si'], [-60, 5],
                                  color='magenta')
     #pint(not_base)
     pylab.show()
Esempio n. 3
0
def main(api="", queryid=""):
    """Get VASP inputs for Materials Project structure
        Args:
            api <str>: Materials Project API key
            queryid <str>: Materials Project ID of the structure
        Returns:
            creates a folder named with that mpid, and including
            some VASP input files.
    """
    if api == "":
        print "Must have an API key from materialsproject.org"
        return None
    if queryid == "":
        print "No MP structure ID given. Exiting."
        return None
    rest_adapter = MPRester(api)
    entries=list()
    proplist=list()
    proplist.append('pretty_formula')
    proplist.append('structure')
    proplist.append('potcar')
    proplist.append('material_id')
    
    myentry = rest_adapter.mpquery(criteria={'material_id':queryid}, properties=proplist)
    if len(myentry) == 0:
        print "Could not find entry for %s as material_id. Trying entry_id." % queryid
        myentry = rest_adapter.mpquery(criteria={'entry_id':queryid}, properties=proplist)
    if len(myentry) == 0:
        print "Could not find entry for %s" % queryid
        return None
    entries.extend(myentry)

    workdir = os.getcwd()
    from pymatgen.io.vaspio_set import MITVaspInputSet, MPVaspInputSet
    for entry in entries: 
        mpvis = MPVaspInputSet()
        myname = str(entry['pretty_formula'])
        #print entry['structure'].composition
        #print entry['structure'].formula
        #myname = entry['pretty_formula']
        myname = myname.replace("(","_").replace(")","_")
        myname = myname + "_" + entry['material_id']
        os.mkdir(myname)
        os.chdir(myname)
        mystructure = entry['structure']
        if mystructure.num_sites <= 10:
            mystructure.make_supercell([2,2,2])
        #mystructure.perturb(0.01)
        incar = mpvis.get_incar(mystructure)
        incar.write_file("INCAR")
        potcar = mpvis.get_potcar(mystructure)
        potcar.write_file("POTCAR")
        #potcar_symbols = mpvis.get_potcar_symbols(mystructure) 
        myposcar=Poscar(mystructure)
        mykpoints=mpvis.get_kpoints(mystructure)
        mykpoints.write_file("KPOINTS")


        myposcar.write_file("POSCAR")
        os.chdir(workdir)
Esempio n. 4
0
def main(comp="La0.5Sr0.5MnO3", energy=-43.3610, ostart="", oend="", ostep=""):
    """Get energy above hull for a composition
        Args:
            comp <str>: Composition in string form
            energy <float>: Energy PER FORMULA UNIT of composition given
            (Leave the following arguments blank for a non-grand potential
                phase diagram.)
            ostart <float>: Starting oxygen chemical potential. 
            oend <float>: Ending oxygen chemical potential. 
            ostep <float>: Step for oxygen chemical potential
        Returns:
            Prints to screen
    """        
    #a = MPRester("<YOUR_MPREST_API_KEY_HERE>")
    a = MPRester("wfmUu5VSsDCvIrhz")
    
    mycomp=Composition(comp)
    print "Composition: ", mycomp
    myenergy=energy
    print "Energy: ", myenergy
    myPDEntry = PDEntry(mycomp, myenergy)

    elements = mycomp.elements
    ellist = map(str, elements)
    
    chemsys_entries = a.get_entries_in_chemsys(ellist)
    #For reference: other ways of getting entries
    #entries = a.mpquery(criteria={'elements':{'$in':['La','Mn'],'$all':['O']},'nelements':3})
    #entries = a.mpquery(criteria={'elements':{'$in':['La','Mn','O'],'$all':['O']}},properties=['pretty_formula'])
    #entries = a.get_entries_in_chemsys(['La', 'Mn', 'O', 'Sr'])
   
    if ostart=="": #Regular phase diagram
        entries = list(chemsys_entries)
        entries.append(myPDEntry)
        pd = PhaseDiagram(entries)
        #plotter = PDPlotter(gppd)
        #plotter.show()
        ppda = PDAnalyzer(pd)
        eabove=ppda.get_decomp_and_e_above_hull(myPDEntry)
        print "Energy above hull: ", eabove[1]
        print "Decomposition: ", eabove[0]
        return eabove
    else: #Grand potential phase diagram
        orange = np.arange(ostart, oend+ostep, ostep) #add ostep because otherwise the range ends before oend
        for o_chem_pot in orange:
            entries = list(chemsys_entries)
            myGrandPDEntry = GrandPotPDEntry(myPDEntry,{Element('O'): float(o_chem_pot)}) #need grand pot pd entry for GPPD
            entries.append(myGrandPDEntry)
            gppd = GrandPotentialPhaseDiagram(entries,{Element('O'): float(o_chem_pot)})
            gppda = PDAnalyzer(gppd)
            geabove=gppda.get_decomp_and_e_above_hull(myGrandPDEntry, True)
            print "******** Decomposition for mu_O = %s eV ********" % o_chem_pot
            print "%30s%1.4f" % ("mu_O: ",o_chem_pot)
            print "%30s%1.4f" % ("Energy above hull (eV): ",geabove[1])
            decomp=geabove[0]
            #print "Decomp: ", decomp
            print "%30s" % "Decomposition: "
            for dkey in decomp.keys():
                print "%30s:%1.4f" % (dkey.composition,decomp[dkey])
    return
Esempio n. 5
0
def mp_id(mpid):
    """
    materials project の ID から POSCAR を作成
    """
    mpr = MPRester("WTxsDhRV7g2Mcbqw")
    strctr = mpr.get_structure_by_material_id(mpid)
    poscar = Poscar(strctr)
    poscar.write_file('POSCAR_{0}'.format(mpid))
Esempio n. 6
0
 def test_find_structure(self):
     # nosetests pymatgen/matproj/tests/test_rest.py:MPResterTest.test_find_structure
     m = MPRester()
     ciffile = os.path.join(test_dir, 'Fe3O4.cif')
     data = m.find_structure(ciffile)
     self.assertTrue(len(data) > 1)
     s = CifParser(ciffile).get_structures()[0]
     data = m.find_structure(s)
     self.assertTrue(len(data) > 1)
Esempio n. 7
0
def get_INCARs(comp_name, mp_api_key, SOC):
    from pymatgen.matproj.rest import MPRester
    matproj = MPRester(mp_api_key)

    structure = matproj.get_structure_by_material_id(comp_name)
    from pymatgen.io.vasp.sets import MPVaspInputSet
    from pymatgen.io.vasp.sets import MPGGAVaspInputSet   # +U is turned off (if any)
    from pymatgen.io.vasp.sets import MPHSEVaspInputSet
    from pymatgen.io.vasp.sets import MPStaticVaspInputSet
    from pymatgen.io.vasp.sets import MPNonSCFVaspInputSet
    from pymatgen.io.vasp.sets import MPStaticDielectricDFPTVaspInputSet
    from pymatgen.io.vasp.sets import MPBSHSEVaspInputSet
    from pymatgen.io.vasp.sets import MPOpticsNonSCFVaspInputSet

    v = MPVaspInputSet()
    indic = v.get_incar(structure)
    k = v.get_all_vasp_input(structure,generate_potcar = False)
    incar_file = open('INCAR','w')
    if SOC in ['TRUE', 'True', 'true']:
	indic['LMAXMIX'] = 4
	indic['NBANDS'] = 128
	indic['LSORBIT'] = '.TRUE.'
	indic.pop('MAGMOM', None)
    incar_file.write(str(indic))

    self = MPStaticVaspInputSet()
    indic = self.get_incar(structure)
    indic['NEDOS'] = 9001
    incar_file = open('INCAR_SELF','w')
    if SOC in ['TRUE', 'True', 'true']:
	indic['LMAXMIX'] = 4
	indic['NBANDS'] = 128
	indic['LSORBIT'] = '.TRUE.'
	indic.pop('MAGMOM', None)
    incar_file.write(str(indic))

    user_incar_settings = {"NBANDS" : 100}
    nself = MPNonSCFVaspInputSet(user_incar_settings)
    indic = nself.get_incar(structure)
    incar_file = open('INCAR_NSELF','w')
    if SOC in ['TRUE', 'True', 'true']:
	indic['LMAXMIX'] = 4
	indic['NBANDS'] = 128
	indic['LSORBIT'] = '.TRUE.'
	indic.pop('MAGMOM', None)
    incar_file.write(str(indic))

    HSE = MPHSEVaspInputSet()
    indic = HSE.get_incar(structure)
    incar_file = open('INCAR_HSE','w')
    if SOC in ['TRUE', 'True', 'true']:
	indic['LMAXMIX'] = 4
	indic['NBANDS'] = 128
	indic['LSORBIT'] = '.TRUE.'
	indic.pop('MAGMOM', None)
    incar_file.write(str(indic))
Esempio n. 8
0
def benchmark_input_scf(request):
    pseudos = abidata.pseudos("14si.pspnc", "6c.pspnc", "3li.pspnc", "9f.pspnc",
                              "12mg.pspnc", "8o.pspnc", "31ga.pspnc", "7n.pspnc")
    rest = MPRester()
    structure = rest.get_structure_by_material_id(request.param)
    try:
        return ebands_input(structure, pseudos, kppa=100, ecut=6).split_datasets()[0]
    except:
        #to deal with missing pseudos
        pytest.skip('Cannot create input for material {}.'.format(request.param))
Esempio n. 9
0
 def test_find_structure(self):
     # nosetests pymatgen/matproj/tests/test_rest.py:MPResterTest.test_find_structure
     # self.rester points to rest/v2 by default which doesn't have the find_structure endpoint
     m = MPRester(endpoint="https://www.materialsproject.org/rest")
     ciffile = os.path.join(test_dir, 'Fe3O4.cif')
     data = m.find_structure(ciffile)
     self.assertTrue(len(data) > 1)
     s = CifParser(ciffile).get_structures()[0]
     data = m.find_structure(s)
     self.assertTrue(len(data) > 1)
Esempio n. 10
0
 def calculate_stability(self, d):
     m = MPRester(self.mapi_key)
     functional = d["pseudo_potential"]["functional"]
     syms = ["{} {}".format(functional, l) for l in d["pseudo_potential"]["labels"]]
     entry = ComputedEntry(
         Composition(d["unit_cell_formula"]),
         d["output"]["final_energy"],
         parameters={"hubbards": d["hubbards"], "potcar_symbols": syms},
     )
     data = m.get_stability([entry])[0]
     for k in ("e_above_hull", "decomposes_to"):
         d["analysis"][k] = data[k]
Esempio n. 11
0
    def _test_from_pm_volume(self):
        """
        MPのデータ volume をプリント
        MD 計算の初期値用
        """
        ent_list = []
        mpr = MPRester("WTxsDhRV7g2Mcbqw")
        composition = ['Fe', 'P']
        entries = mpr.get_entries_in_chemsys(composition)

        for entry in entries:
            if entry.as_dict()['data']['e_above_hull'] == 0:
                print(entry.as_dict()['data']['pretty_formula'])
                print(entry.as_dict()['data']['volume']/entry.as_dict()['data']['nsites'])
Esempio n. 12
0
    def _test_from_pm_volume(self):
        """
        MPのデータ volume をプリント
        MD 計算の初期値用
        """
        ent_list = []
        mpr = MPRester("WTxsDhRV7g2Mcbqw")
        composition = ["Fe", "P"]
        entries = mpr.get_entries_in_chemsys(composition)

        for entry in entries:
            if entry.as_dict()["data"]["e_above_hull"] == 0:
                print(entry.as_dict()["data"]["pretty_formula"])
                print(entry.as_dict()["data"]["volume"] / entry.as_dict()["data"]["nsites"])
Esempio n. 13
0
    def test_parse_criteria(self):
        crit = MPRester.parse_criteria("mp-1234 Li-*")
        self.assertIn("Li-O", crit["$or"][1]["chemsys"]["$in"])
        self.assertIn({"task_id": "mp-1234"}, crit["$or"])

        crit = MPRester.parse_criteria("Li2*")
        self.assertIn("Li2O", crit["pretty_formula"]["$in"])
        self.assertIn("Li2I", crit["pretty_formula"]["$in"])
        self.assertIn("CsLi2", crit["pretty_formula"]["$in"])

        crit = MPRester.parse_criteria("Li-*-*")
        self.assertIn("Li-Re-Ru", crit["chemsys"]["$in"])
        self.assertNotIn("Li-Li", crit["chemsys"]["$in"])

        comps = MPRester.parse_criteria("**O3")["pretty_formula"]["$in"]
        for c in comps:
            self.assertEqual(len(Composition(c)), 3, "Failed in %s" % c)

        chemsys = MPRester.parse_criteria("{Fe,Mn}-O")["chemsys"]["$in"]
        self.assertEqual(len(chemsys), 2)
        comps = MPRester.parse_criteria("{Fe,Mn,Co}O")["pretty_formula"]["$in"]
        self.assertEqual(len(comps), 3, comps)

        #Let's test some invalid symbols

        self.assertRaises(ValueError, MPRester.parse_criteria, "li-fe")
        self.assertRaises(ValueError, MPRester.parse_criteria, "LO2")

        crit = MPRester.parse_criteria("POPO2")
        self.assertIn("P2O3", crit["pretty_formula"]["$in"])
Esempio n. 14
0
    def __init__(self, api_key=None):
        """
        Args:
            api_key: (str) Your Citrine API key, or None if you've set the MAPI_KEY environment variable

        Returns: None
        """
        api_key = api_key if api_key else os.environ["MAPI_KEY"]
        self.mprester = MPRester(api_key=api_key)
Esempio n. 15
0
def get_decomp(o_chem_pot, mycomp, verbose=1):
    """Get decomposition from open phase diagram
        Args:
            o_chem_pot <float>: Oxygen chemical potential
            mycomp <pymatgen Composition>: Composition
            verbose <int>: 1 - verbose (default)
                           0 - silent
        Returns:
            decomposition string
    """        
    a = MPRester("<YOUR_MPREST_API_KEY_HERE>")
    elements = mycomp.elements
    ellist = map(str, elements)
    entries = a.get_entries_in_chemsys(ellist)
    #entries = a.get_entries_in_chemsys(['La', 'Mn', 'O', 'Fe'])
    pd = PhaseDiagram(entries)
    gppd = GrandPotentialPhaseDiagram(entries,{Element('O'): float(o_chem_pot)})
    print gppd
    #plotter = PDPlotter(gppd)
    #plotter.show()

    gppda = PDAnalyzer(gppd)
    #mychempots = gppda.get_composition_chempots(mycomp)
    #print "My chem pots:"
    #print mychempots
    mydecompgppd = gppda.get_decomposition(mycomp)
    #pdentry = PDEntry(mycomp, 0)
    #print "Decomp and energy:"
    #decompandenergy = gppda.get_decomp_and_e_above_hull(pdentry)
    #print decompandenergy
    #mydecomppd = pda.get_decomposition(mycomp)
    #print "Mn profile:"
    #mnprof= gppda.get_element_profile(Element('Mn'),mycomp)
    #print mnprof

    if verbose:
        for (entry,amount) in mydecompgppd.iteritems():
            print "%s: %3.3f" % (entry.name, amount)
            #mymurangegppd = gppda.getmu_range_stability_phase(Composition(entry.name),Element('O'))
            #print mymurangegppd
        #for (entry,amount) in mydecomppd.iteritems():
        #    print "%s: %3.3f" % (entry.name, amount)
        print ""
    return mydecompgppd
Esempio n. 16
0
def test():
    """for test"""
    #This initializes the REST adaptor. Put your own API key in.
    mpr = MPRester("WTxsDhRV7g2Mcbqw")
    #Entries are the basic unit for thermodynamic
    #and other analyses in pymatgen.
    #This gets all entries belonging to the Ca-C-O system.
    composition = ['Fe', 'Ni', 'Si']
    entries = mpr.get_entries_in_chemsys(composition)

    # entryの内容を確認
    entry = entries[0]
    print(entry.as_dict())
    print(entry.as_dict()['data']['volume']/6)

    #With entries, you can do many sophisticated analyses,
    #like creating phase diagrams.
    pd = PhaseDiagram(entries) #pylint: disable=C0103

    #print(dir(pd))
    #print(pd.get_form_energy_per_atom(list(pd.stable_entries)[0]))

    plotter = PDPlotter(pd)
Esempio n. 17
0
def calculate_phase_stability(args):
    #This initializes the REST adaptor.
    a = MPRester(args.api_key)

    drone = VaspToComputedEntryDrone()
    entry = drone.assimilate(args.directory)

    compat = MaterialsProjectCompatibility()
    entry = compat.process_entry(entry)

    if not entry:
        print "Calculation parameters are not consistent with Materials " + \
            "Project parameters."
        sys.exit()

    syms = [el.symbol for el in entry.composition.elements]
    #This gets all entries belonging to the relevant system.
    entries = a.get_entries_in_chemsys(syms)
    entries.append(entry)

    #Process entries with Materials Project compatibility.
    entries = compat.process_entries(entries)

    print [e.composition.reduced_formula for e in entries]
Esempio n. 18
0
def get_struct_from_mp(formula, MAPI_KEY="", all_structs=False):
    """
    fetches the structure corresponding to the given formula
    from the materialsproject database.
    
    Note: Get the api key from materialsproject website. The one used
    here is nolonger valid.
    
    Note: for the given formula there are many structures available, 
    this function returns the one with the lowest energy above the hull
    unless all_structs is set to True
    """
    if not MAPI_KEY:
        MAPI_KEY = os.environ.get("MAPI_KEY", "")
        if not MAPI_KEY:
            print('API key not provided')
            print(
                'get API KEY from materialsproject and set it to the MAPI_KEY environment variable. aborting ... '
            )
            sys.exit()
    with MPRester(MAPI_KEY) as m:
        data = m.get_data(formula)
        structures = []
        x = {}
        print("\nnumber of structures matching the chemical formula {0} = {1}".
              format(formula, len(data)))
        print(
            "The one with the the lowest energy above the hull is returned, unless all_structs is set to True"
        )
        for d in data:
            mpid = str(d['material_id'])
            x[mpid] = d['e_above_hull']
            if all_structs:
                structure = m.get_structure_by_material_id(mpid)
                structures.append(structure)
        if all_structs:
            return structures
        else:
            mineah_key = sorted(x.items(), key=operator.itemgetter(1))[0][0]
            print(
                "The id of the material corresponding to the lowest energy above the hull = {0}"
                .format(mineah_key))
            if mineah_key:
                return m.get_structure_by_material_id(mineah_key)
            else:
                return None
Esempio n. 19
0
 def fundamental_gaps(self, query=None, sort='system'):
     """
     print the gap info for all the systems in the database
     :param query:
     :param sort: default sort per system
     :return:
     """
     mp_key = os.environ['MP_KEY']
     if query is None:
         query = {}
     for item in self.col.find(query).sort(sort):
         print('')
         print('System    : ', item['system'].split('_')[0])
         print('Ps        : ', item['ps'])
         print('extra     : ', item['extra_vars'])
         print('gwresults : ', item['gw_results'])
         print('item      : ', item['item'])
         if 'mp-' in item['item']:
             try:
                 with MPRester(mp_key) as mp_database:
                     gap = {}
                     bandstructure = mp_database.get_bandstructure_by_material_id(item['item'])
                     gap['vbm_l'] = bandstructure.kpoints[bandstructure.get_vbm()['kpoint_index'][0]].label
                     gap['cbm_l'] = bandstructure.kpoints[bandstructure.get_cbm()['kpoint_index'][0]].label
                     gap['vbm_e'] = bandstructure.get_vbm()['energy']
                     gap['cbm_e'] = bandstructure.get_cbm()['energy']
                     gap['cbm'] = tuple(bandstructure.kpoints[bandstructure.get_cbm()['kpoint_index'][0]].frac_coords)
                     gap['vbm'] = tuple(bandstructure.kpoints[bandstructure.get_vbm()['kpoint_index'][0]].frac_coords)
             except (MPRestError, IndexError, KeyError) as err:
                 print(err.message)
                 gap = None
         else:
             gap = None
         if gap:
             print(gap['cbm_l'], gap['vbm_l'])
             print(gap['cbm'], gap['vbm'])
         try:
             data = self.gfs.get(item['results_file']).read()
             if len(data) > 1000:
                 srf = MySigResFile(data)
                 srf.print_gap_info()
         except IOError:
             print('No Sigres file in DataBase')
Esempio n. 20
0
def surfer(mpid='', vacuum=15, layers=2, mat=None, max_index=1):
    if mat == None:
        with MPRester() as mp:
            mat = mp.get_structure_by_material_id(mpid)
        if mpid == '':
            print('Provide structure')

    sg_mat = SpacegroupAnalyzer(mat)
    mat_cvn = sg_mat.get_conventional_standard_structure()
    mat_cvn.sort()
    indices = get_symmetrically_distinct_miller_indices(mat_cvn, max_index)
    ase_atoms = AseAtomsAdaptor().get_atoms(mat_cvn)

    structures = []
    pos = Poscar(mat_cvn)
    try:
        pos.comment = str('sbulk') + str('@') + str('vac') + str(vacuum) + str(
            '@') + str('layers') + str(layers)
    except:
        pass
    structures.append(pos)
    mat_cvn.to(fmt='poscar',
               filename=str('POSCAR-') + str('cvn') + str('.vasp'))
    for i in indices:
        ase_slab = surface(ase_atoms, i, layers)
        ase_slab.center(vacuum=vacuum, axis=2)
        slab_pymatgen = AseAtomsAdaptor().get_structure(ase_slab)
        slab_pymatgen.sort()
        surf_name = '_'.join(map(str, i))
        pos = Poscar(slab_pymatgen)
        try:
            pos.comment = str("Surf-") + str(surf_name) + str('@') + str(
                'vac') + str(vacuum) + str('@') + str('layers') + str(layers)
        except:
            pass
        pos.write_file(filename=str('POSCAR-') + str("Surf-") +
                       str(surf_name) + str('.vasp'))
        structures.append(pos)

    return structures
Esempio n. 21
0
    def from_material_id(cls,
                         material_id,
                         final=True,
                         api_key=None,
                         endpoint="https://www.materialsproject.org/rest/v2"):
        """
        Get a Structure corresponding to a material_id.

        Args:
            material_id (str): Materials Project material_id (a string, e.g., mp-1234).
            final (bool): Whether to get the final structure, or the initial
                (pre-relaxation) structure. Defaults to True.
            api_key (str): A String API key for accessing the MaterialsProject
                REST interface. Please apply on the Materials Project website for one.
                If this is None, the code will check if there is a "MAPI_KEY"
                environment variable set. If so, it will use that environment
                variable. This makes easier for heavy users to simply add
                this environment variable to their setups and MPRester can
                then be called without any arguments.
            endpoint (str): Url of endpoint to access the MaterialsProject REST interface.
                Defaults to the standard Materials Project REST address, but
                can be changed to other urls implementing a similar interface.

        Returns:
            Structure object.
        """
        if api_key is None:
            # Check if MP_KEY is defined, otherwise fallback to MAPI_KEY.
            api_key = os.environ.get('MP_KEY', None)

        # Get pytmatgen structure and convert it to abipy structure
        from pymatgen.matproj.rest import MPRester, MPRestError
        with MPRester(api_key=api_key, endpoint=endpoint) as database:
            new = database.get_structure_by_material_id(material_id,
                                                        final=final)
            new.__class__ = cls
            return new
Esempio n. 22
0
def get_struct_from_mp(formula, MAPI_KEY="", all_structs=False):

    if not MAPI_KEY:
        MAPI_KEY = os.environ.get("MAPI_KEY", "")
        if not MAPI_KEY:
            print('API key not provided')
            print(
                'get API KEY from materialsproject and set it to the MAPI_KEY environment variable. aborting ... '
            )
            sys.exit()
    with MPRester(MAPI_KEY) as m:
        data = m.get_data(formula)
        structures = []
        x = {}
        print("\nnumber of structures matching the chemical formula {0} = {1}".
              format(formula, len(data)))
        print(
            "The one with the the lowest energy above the hull is returned, unless all_structs is set to True"
        )
        for d in data:
            mpid = str(d['material_id'])
            x[mpid] = d['e_above_hull']
            if all_structs:
                structure = m.get_structure_by_material_id(mpid)
                structure.sort()
                structures.append(structure)
        if all_structs:
            return structures
        else:
            key = sorted(x.items(), key=operator.itemgetter(1))[0][0]
            print(
                "The id of the material corresponding to the lowest energy above the hull = {0}"
                .format(key))
            if key:
                return key, m.get_structure_by_material_id(key)
            else:
                return None
Esempio n. 23
0
    def __init__(self, code='vasp', system_id='mp-149', kpar=False, **kwargs):
        """
        system_id is to be a mp-id to take a base structure from the mp-database
        kwarg can be used to personalize all lists

        code specifies the name of the code to be tested, it is assumed that an executable with this name is
        present in the current work dir

        to generate the job scripts a taskmanager.yml file is needed in the current work dir
        #todo add example

        list of paralelizaions
        """
        self.code = code
        self.subject = os.path.join(os.getcwd(), code)
        self.manager = TaskManager.from_user_config()
        self.script_list = []
        self.system_id = system_id
        self.kpar = kpar
        self.kpden = None
        mp_key = os.environ['MP_KEY']
        with MPRester(mp_key) as mp_database:
            self.structure = mp_database.get_structure_by_material_id(
                system_id, final=True)
        self.name = str(
            self.structure.composition.reduced_formula) + "_" + str(
                self.system_id)
        self.np_list = [1, 4, 9, 16, 25, 36, 64, 100, 144]
        #self.np_list = [1, 8, 27, 64, 125, 216, 343]
        self.sizes = [1, 2, 3]
        self.parameter_lists = None
        if self.code == 'vasp':
            self.parameter_lists = {'NPAR': [0, 0.5, 1]}
        self.reset_bar()
        self.inpset = BenchVaspInputSet()
        self.inpset.set_input()
Esempio n. 24
0
 def __init__(self, material_id):
     self.mprester = MPRester("MATERIALSPROJECTID")
     self.material_id = material_id
from pymatgen import Composition, Element
from pymatgen.matproj.rest import MPRester

__author__ = 'Anubhav Jain'
__copyright__ = 'Copyright 2014, The Materials Project'
__version__ = '0.1'
__maintainer__ = 'Anubhav Jain'
__email__ = '*****@*****.**'
__date__ = 'Oct 01, 2014'


def get_band_center(form):
    c = Composition(str(form))
    prod = 1.0
    for el, amt in c.get_el_amt_dict().iteritems():
        prod = prod * (Element(el).X ** amt)

    return -prod ** (1 / sum(c.get_el_amt_dict().values()))


if __name__ == '__main__':
    mpr = MPRester()
    for i in mpr.query({"elements": {"$in": ["O", "S", "Se", "Te"]}, "nelements": 2, "e_above_hull": {"$lte": 0.05}},
                       properties=['band_gap', 'formula', 'material_id', 'icsd_id']):
        c = Composition(i['formula'])
        center = get_band_center(c)
        print ','.join([str(x) for x in
                        c.formula, c.reduced_formula, center, center + i['band_gap'] / 2, center - i['band_gap'] / 2, i[
                            'material_id'], i['icsd_id']])
Esempio n. 26
0
class MPResterTest(unittest.TestCase):

    def setUp(self):
        self.rester = MPRester()

    def test_get_data(self):
        props = ["energy", "energy_per_atom", "formation_energy_per_atom",
                 "nsites", "unit_cell_formula", "pretty_formula", "is_hubbard",
                 "elements", "nelements", "e_above_hull", "hubbards",
                 "is_compatible", "task_ids",
                 "density", "icsd_ids", "total_magnetization"]
        # unicode literals have been reintroduced in py>3.2
        expected_vals = [-191.33812137, -6.833504334642858, -2.551358929370749,
                         28, {k: v for k, v in {'P': 4, 'Fe': 4, 'O': 16, 'Li': 4}.items()},
                         "LiFePO4", True, ['Li', 'O', 'P', 'Fe'], 4, 0.0,
                         {k: v for k, v in {'Fe': 5.3, 'Li': 0.0, 'O': 0.0, 'P': 0.0}.items()}, True,
                         [u'mp-601412', u'mp-19017', u'mp-796535', u'mp-797820',
                          u'mp-540081', u'mp-797269'],
                         3.4662026991351147,
                         [159107, 154117, 160776, 99860, 181272, 166815,
                          260571, 92198, 165000, 155580, 38209, 161479, 153699,
                          260569, 260570, 200155, 260572, 181341, 181342,
                          72545, 56291, 97764, 162282, 155635],
                         16.0002716]

        for (i, prop) in enumerate(props):
            if prop not in ['hubbards', 'unit_cell_formula', 'elements',
                            'icsd_ids', 'task_ids']:
                val = self.rester.get_data("mp-19017", prop=prop)[0][prop]
                self.assertAlmostEqual(expected_vals[i], val)
            elif prop in ["elements", "icsd_ids", "task_ids"]:
                self.assertEqual(set(expected_vals[i]),
                                 set(self.rester.get_data("mp-19017",
                                                          prop=prop)[0][prop]))
            else:
                self.assertEqual(expected_vals[i],
                                 self.rester.get_data("mp-19017",
                                                      prop=prop)[0][prop])

        props = ['structure', 'initial_structure', 'final_structure', 'entry']
        for prop in props:
            print(prop)
            obj = self.rester.get_data("mp-19017", prop=prop)[0][prop]
            if prop.endswith("structure"):
                self.assertIsInstance(obj, Structure)
            elif prop == "entry":
                obj = self.rester.get_data("mp-19017", prop=prop)[0][prop]
                self.assertIsInstance(obj, ComputedEntry)

        #Test chemsys search
        data = self.rester.get_data('Fe-Li-O', prop='unit_cell_formula')
        self.assertTrue(len(data) > 1)
        elements = {Element("Li"), Element("Fe"), Element("O")}
        for d in data:
            self.assertTrue(
                set(Composition(d['unit_cell_formula']).elements).issubset(
                    elements))

        self.assertRaises(MPRestError, self.rester.get_data, "Fe2O3",
                          "badmethod")

    def test_get_materials_id_from_task_id(self):
        self.assertEqual(self.rester.get_materials_id_from_task_id(
            "mp-540081"), "mp-19017")

    def test_get_materials_id_references(self):
        # nosetests pymatgen/matproj/tests/test_rest.py:MPResterTest.test_get_materials_id_references
        m = MPRester()
        data = m.get_materials_id_references('mp-123')
        self.assertTrue(len(data) > 1000)

    def test_find_structure(self):
        # nosetests pymatgen/matproj/tests/test_rest.py:MPResterTest.test_find_structure
        m = MPRester()
        ciffile = os.path.join(test_dir, 'Fe3O4.cif')
        data = m.find_structure(ciffile)
        self.assertTrue(len(data) > 1)
        s = CifParser(ciffile).get_structures()[0]
        data = m.find_structure(s)
        self.assertTrue(len(data) > 1)

    def test_get_entries_in_chemsys(self):
        syms = ["Li", "Fe", "O"]
        entries = self.rester.get_entries_in_chemsys(syms)
        elements = set([Element(sym) for sym in syms])
        for e in entries:
            self.assertIsInstance(e, ComputedEntry)
            self.assertTrue(set(e.composition.elements).issubset(elements))

    def test_get_structure_by_material_id(self):
        s1 = self.rester.get_structure_by_material_id("mp-1")
        self.assertEqual(s1.formula, "Cs1")

    def test_get_entry_by_material_id(self):
        e = self.rester.get_entry_by_material_id("mp-19017")
        self.assertIsInstance(e, ComputedEntry)
        self.assertTrue(e.composition.reduced_formula, "LiFePO4")

    def test_query(self):
        criteria = {'elements': {'$in': ['Li', 'Na', 'K'], '$all': ['O']}}
        props = ['pretty_formula', 'energy']
        data = self.rester.query(criteria=criteria, properties=props)
        self.assertTrue(len(data) > 6)
        data = self.rester.query(criteria="*2O", properties=props)
        self.assertGreaterEqual(len(data), 52)
        self.assertIn("Li2O", (d["pretty_formula"] for d in data))

    def test_get_exp_thermo_data(self):
        data = self.rester.get_exp_thermo_data("Fe2O3")
        self.assertTrue(len(data) > 0)
        for d in data:
            self.assertEqual(d.formula, "Fe2O3")

    def test_get_dos_by_id(self):
        dos = self.rester.get_dos_by_material_id("mp-2254")
        self.assertIsInstance(dos, CompleteDos)

    def test_get_bandstructure_by_material_id(self):
        bs = self.rester.get_bandstructure_by_material_id("mp-2254")
        self.assertIsInstance(bs, BandStructureSymmLine)

    def test_get_structures(self):
        structs = self.rester.get_structures("Mn3O4")
        self.assertTrue(len(structs) > 0)

    def test_get_entries(self):
        entries = self.rester.get_entries("TiO2")
        self.assertTrue(len(entries) > 1)
        for e in entries:
            self.assertEqual(e.composition.reduced_formula, "TiO2")

        entries = self.rester.get_entries("TiO2", inc_structure="final")
        self.assertTrue(len(entries) > 1)
        for e in entries:
            self.assertEqual(e.structure.composition.reduced_formula, "TiO2")

        all_entries = self.rester.get_entries("Fe", compatible_only=False)
        entries = self.rester.get_entries("Fe", compatible_only=True)
        self.assertTrue(len(entries) < len(all_entries))

        entries = self.rester.get_entries("Fe", compatible_only=True,
                                          property_data=["cif"])
        self.assertIn("cif", entries[0].data)

    def test_get_exp_entry(self):
        entry = self.rester.get_exp_entry("Fe2O3")
        self.assertEqual(entry.energy, -825.5)

    def test_submit_query_delete_snl(self):
        s = Structure([[5, 0, 0], [0, 5, 0], [0, 0, 5]], ["Fe"], [[0, 0, 0]])
        # d = self.rester.submit_snl(
        #     [s, s], remarks=["unittest"],
        #     authors="Test User <*****@*****.**>")
        # self.assertEqual(len(d), 2)
        # data = self.rester.query_snl({"about.remarks": "unittest"})
        # self.assertEqual(len(data), 2)
        # snlids = [d["_id"] for d in data]
        # self.rester.delete_snl(snlids)
        # data = self.rester.query_snl({"about.remarks": "unittest"})
        # self.assertEqual(len(data), 0)

    def test_get_stability(self):
        entries = self.rester.get_entries_in_chemsys(["Fe", "O"])
        modified_entries = []
        for entry in entries:
            # Create modified entries with energies that are 0.01eV higher
            # than the corresponding entries.
            if entry.composition.reduced_formula == "Fe2O3":
                modified_entries.append(
                    ComputedEntry(entry.composition,
                                  entry.uncorrected_energy + 0.01,
                                  parameters=entry.parameters,
                                  entry_id="mod_{}".format(entry.entry_id)))
        rest_ehulls = self.rester.get_stability(modified_entries)
        all_entries = entries + modified_entries
        compat = MaterialsProjectCompatibility()
        all_entries = compat.process_entries(all_entries)
        pd = PhaseDiagram(all_entries)
        a = PDAnalyzer(pd)
        for e in all_entries:
            if str(e.entry_id).startswith("mod"):
                for d in rest_ehulls:
                    if d["entry_id"] == e.entry_id:
                        data = d
                        break
                self.assertAlmostEqual(a.get_e_above_hull(e),
                                       data["e_above_hull"])

    def test_get_reaction(self):
        rxn = self.rester.get_reaction(["Li", "O"], ["Li2O"])
        self.assertIn("Li2O", rxn["Experimental_references"])

    def test_get_substrates(self):
        substrate_data = self.rester.get_substrates('mp-123', 5, [1, 0, 0])
        substrates = [sub_dict['sub_id'] for sub_dict in substrate_data]
        self.assertIn("mp-2534", substrates)

    def test_parse_criteria(self):
        crit = MPRester.parse_criteria("mp-1234 Li-*")
        self.assertIn("Li-O", crit["$or"][1]["chemsys"]["$in"])
        self.assertIn({"task_id": "mp-1234"}, crit["$or"])

        crit = MPRester.parse_criteria("Li2*")
        self.assertIn("Li2O", crit["pretty_formula"]["$in"])
        self.assertIn("Li2I", crit["pretty_formula"]["$in"])
        self.assertIn("CsLi2", crit["pretty_formula"]["$in"])

        crit = MPRester.parse_criteria("Li-*-*")
        self.assertIn("Li-Re-Ru", crit["chemsys"]["$in"])
        self.assertNotIn("Li-Li", crit["chemsys"]["$in"])

        comps = MPRester.parse_criteria("**O3")["pretty_formula"]["$in"]
        for c in comps:
            self.assertEqual(len(Composition(c)), 3, "Failed in %s" % c)

        chemsys = MPRester.parse_criteria("{Fe,Mn}-O")["chemsys"]["$in"]
        self.assertEqual(len(chemsys), 2)
        comps = MPRester.parse_criteria("{Fe,Mn,Co}O")["pretty_formula"]["$in"]
        self.assertEqual(len(comps), 3, comps)

        #Let's test some invalid symbols

        self.assertRaises(ValueError, MPRester.parse_criteria, "li-fe")
        self.assertRaises(ValueError, MPRester.parse_criteria, "LO2")

        crit = MPRester.parse_criteria("POPO2")
        self.assertIn("P2O3", crit["pretty_formula"]["$in"])
Esempio n. 27
0
    def loop_structures(self, mode='i'):
        """
        reading the structures specified in spec, add special points, and excecute the specs
        mode:
        i: loop structures for input generation
        o: loop structures for output parsing
        w: print all results
        """
        print('loop structures mode ', mode)
        mp_key = os.environ['MP_KEY']

        mp_list_vasp = ['mp-149', 'mp-2534', 'mp-8062', 'mp-2469', 'mp-1550', 'mp-830', 'mp-1986', 'mp-10695', 'mp-66',
                        'mp-1639', 'mp-1265', 'mp-1138', 'mp-23155', 'mp-111']

        if self.data['source'] == 'mp-vasp':
            items_list = mp_list_vasp
        elif self.data['source'] in ['poscar', 'cif']:
            files = os.listdir('.')
            items_list = files
        elif self.data['source'] == 'mar_exp':
            items_list = []
            local_serv = pymongo.Connection("marilyn.pcpm.ucl.ac.be")
            local_db_gaps = local_serv.band_gaps
            pwd = os.environ['MAR_PAS']
            local_db_gaps.authenticate("setten", pwd)
            for c in local_db_gaps.exp.find():
                name = Structure.from_dict(c['icsd_data']['structure']).composition.reduced_formula, c['icsd_id'],\
                    c['MP_id']
                print(name)
                #Structure.from_dict(c['icsd_data']['structure']).to(fmt='cif',filename=name)
                items_list.append({'name': 'mp-' + c['MP_id'], 'icsd': c['icsd_id'], 'mp': c['MP_id']})
        else:
            items_list = [line.strip() for line in open(self.data['source'])]

        for item in items_list:
            print('\n')
            # special case, this should be encaptulated
            if self.data['source'] == 'mar_exp':
                print('structure from marilyn', item['name'], item['icsd'], item['mp'])
                exp = local_db_gaps.exp.find({'MP_id': item['mp']})[0]
                structure = Structure.from_dict(exp['icsd_data']['structure'])
                structure = refine_structure(structure)
                structure.to(fmt='cif', filename=item['name'])
                try:
                    kpts = local_db_gaps.GGA_BS.find({'transformations.history.0.id': item['icsd']})[0]['calculations']\
                    [-1]['band_structure']['kpoints']
                except (IndexError, KeyError):
                    kpts = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
                structure.kpts = kpts
                print('kpoints:', structure.kpts[0], structure.kpts[1])
                structure.item = item['name']
            else:
                if item.startswith('POSCAR_'):
                    structure = pmg.read_structure(item)
                    comment = Poscar.from_file(item).comment
                    # print comment
                    if comment.startswith("gap"):
                        structure.vbm_l = comment.split(" ")[1]
                        structure.vbm = (comment.split(" ")[2], comment.split(" ")[3], comment.split(" ")[4])
                        structure.cbm_l = comment.split(" ")[5]
                        structure.cbm = (comment.split(" ")[6], comment.split(" ")[7], comment.split(" ")[8])
                    else:
                        # print "no bandstructure information available, adding GG as 'gap'"
                        structure = add_gg_gap(structure)
                elif 'xyz' in item:
                    structure = pmg.read_structure(item)
                    raise NotImplementedError
                elif item.startswith('mp-'):
                    with MPRester(mp_key) as mp_database:
                        print('structure from mp database', item)
                        structure = mp_database.get_structure_by_material_id(item, final=True)
                        try:
                            bandstructure = mp_database.get_bandstructure_by_material_id(item)
                            structure.vbm_l = bandstructure.kpoints[bandstructure.get_vbm()['kpoint_index'][0]].label
                            structure.cbm_l = bandstructure.kpoints[bandstructure.get_cbm()['kpoint_index'][0]].label
                            structure.cbm = tuple(bandstructure.kpoints[bandstructure.get_cbm()['kpoint_index'][0]].frac_coords)
                            structure.vbm = tuple(bandstructure.kpoints[bandstructure.get_vbm()['kpoint_index'][0]].frac_coords)
                        except (MPRestError, IndexError, KeyError) as err:
                            print(err.message)
                            structure = add_gg_gap(structure)
                else:
                    continue
                structure.kpts = [list(structure.cbm), list(structure.vbm)]
                structure.item = item
            print(item, s_name(structure))
            if mode == 'i':
                self.excecute_flow(structure)
            elif mode == 'w':
                self.print_results(structure)
            elif mode == 's':
                self.insert_in_database(structure)
            elif mode == 'o':
                # if os.path.isdir(s_name(structure)) or os.path.isdir(s_name(structure)+'.conv'):
                self.process_data(structure)

        if 'ceci' in self.data['mode'] and mode == 'i':
            os.chmod("job_collection", stat.S_IRWXU)
Esempio n. 28
0
 def setUp(self):
     self.rester = MPRester()
Esempio n. 29
0
 def test_get_materials_id_references(self):
     # nosetests pymatgen/matproj/tests/test_rest.py:MPResterTest.test_get_materials_id_references
     m = MPRester()
     data = m.get_materials_id_references('mp-123')
     self.assertTrue(len(data) > 1000)
Esempio n. 30
0
            elif count == -2:
                y = float(lin[1])
            elif count == -1:
                z = float(lin[2])
                count = 0
    static_dielectric = (x + y + z) / 3
    highf_dielectric = static_dielectric * (TO_phonon / LO_phonon)**2
    return static_dielectric, highf_dielectric


#materials_list = ['mp-16764']
print(materials_list)

apikey = 'fDJKEZpxSyvsXdCt'
from pymatgen.matproj.rest import MPRester
matproj = MPRester(apikey)
with open('DATA_ALL.txt', 'w') as data:
    #	data.write('%12s %12s %9s %22s %22s %7s %7s %7s %8s %8s %8s %8s %16s %16s %11s \n' % ('MP-ID', 'Formula', 'gap(eV)', 'n-cond_' + stn + '_' + str(T) + 'K', 'p-cond_' + stn + '_' + str(T) + 'K', 'LO-phon', 'eps_0', 'eps_inf', 'm_e', 'm_h', 'mu_n', 'mu_p', 'time(s)'))
    data.write('%12s %12s %12s %5s %12s %9s %22s %22s %7s %7s %7s %8s %8s %8s %8s %11s \n' % ('mp-id', 'formula', 'spacegroup', 'sp#', 'sp-type', 'gap(eV)', 'n-cond_' + stn + '_' + str(T) + 'K', 'p-cond_' + stn + '_' + str(T) + 'K', \
    'LO-phon', 'eps_0', 'eps_inf', 'm_e', 'm_h', 'mu_n', 'mu_p', 'time(s)'))
    for id in materials_list:
        formula = matproj.get_data(id,
                                   prop="pretty_formula")[0]["pretty_formula"]
        spacegroup = matproj.get_data(id, prop="spacegroup")[0]["spacegroup"]
        if os.path.exists(id):
            print(id)
            os.chdir(id)
            os.chdir('nself')
            val_kpoint, con_kpoint, eval, econ, core = find_reference(
                scripts_path)
            os.chdir('../')
Esempio n. 31
0
class MPDataRetrieval:
    """
    MPDataRetrieval is used to retrieve data from the Materials Project database, print the results, and convert them
    into an indexed/unindexed Pandas dataframe.
    """
    def __init__(self, api_key=None):
        """
        Args:
            api_key: (str) Your Materials Project API key, or None if you've set the MAPI_KEY environment variable

        Returns: None
        """
        api_key = api_key if api_key else os.environ['MAPI_KEY']
        self.mprester = MPRester(api_key=api_key)

    def get_dataframe(self,
                      criteria,
                      properties,
                      mp_decode=False,
                      index_mpid=True):
        """
        Gets data from MP in a dataframe format.
        See API docs at https://materialsproject.org/wiki/index.php/The_Materials_API for more details.

        Args:
            criteria: (str/dict) Criteria of the query as a string or mongo-style dict. If string, it supports a
                powerful but simple string criteria. E.g., "Fe2O3" means search for materials with reduced_formula
                Fe2O3. Wild cards are also supported. E.g., "\*2O" means get all materials whose formula can be formed
                as \*2O, e.g., Li2O, K2O, etc.

                Other syntax examples:
                    mp-1234: Interpreted as a Materials ID.
                    Fe2O3 or \*2O3: Interpreted as reduced formulas.
                    Li-Fe-O or \*-Fe-O: Interpreted as chemical systems.

                You can mix and match with spaces, which are interpreted as "OR". E.g. "mp-1234 FeO" means query for
                all compounds with reduced formula FeO or with materials_id mp-1234.

                Using a full dict syntax, even more powerful queries can be constructed. For example,
                {"elements":{"$in":["Li", "Na", "K"], "$all": ["O"]}, "nelements":2} selects all Li, Na and K oxides.
                {"band_gap": {"$gt": 1}} selects all materials with band gaps greater than 1 eV.

            properties: (list) Properties to request for as a list. For example,
                ["formula", "formation_energy_per_atom"] returns the formula and formation energy per atom.

            mp_decode: (bool) Whether to do a decoding to a Pymatgen object where possible. In some cases, it might be
                useful to just get the raw python dict, i.e., set to False.

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

        Returns: A Pandas dataframe object

        """

        if index_mpid and "material_id" not in properties:
            properties.append("material_id")

        data = self.mprester.query(criteria, properties, mp_decode)
        df = pd.DataFrame(data, columns=properties)

        if index_mpid:
            df = df.set_index("material_id")

        return df
 def __init__(self, material_id):
     mpid = self.get_mp_id()
     self.mprester = MPRester(mpid)
     self.material_id = material_id
Esempio n. 33
0
    def run_task(self, fw_spec):
        logging.basicConfig(
            filename='chemenv_structure_environments.log',
            format='%(levelname)s:%(module)s:%(funcName)s:%(message)s',
            level=logging.DEBUG)
        lgf = LocalGeometryFinder()
        lgf.setup_parameters(
            centering_type='centroid',
            include_central_site_in_centroid=True,
            structure_refinement=lgf.STRUCTURE_REFINEMENT_NONE)
        if 'chemenv_parameters' in fw_spec:
            for param, value in fw_spec['chemenv_parameters'].items():
                lgf.setup_parameter(param, value)
        identifier = fw_spec['identifier']
        if 'structure' in fw_spec:
            structure = fw_spec['structure']
        else:
            if identifier[
                    'source'] == 'MaterialsProject' and 'material_id' in identifier:
                if not 'mapi_key' in fw_spec:
                    raise ValueError(
                        'The mapi_key should be provided to get the structure from the Materials Project'
                    )
                a = MPRester(fw_spec['mapi_key'])
                structure = a.get_structure_by_material_id(
                    identifier['material_id'])
            else:
                raise ValueError(
                    'Either structure or identifier with source = MaterialsProject and material_id '
                    'should be provided')

        info = {}
        # Compute the structure environments
        lgf.setup_structure(structure)
        if 'valences' in fw_spec:
            valences = fw_spec['valences']
        else:
            try:
                bva = BVAnalyzer()
                valences = bva.get_valences(structure=structure)
                info['valences'] = {'origin': 'BVAnalyzer'}
            except:
                valences = 'undefined'
                info['valences'] = {'origin': 'None'}
        excluded_atoms = None
        if 'excluded_atoms' in fw_spec:
            excluded_atoms = fw_spec['excluded_atoms']

        se = lgf.compute_structure_environments(only_cations=False,
                                                valences=valences,
                                                excluded_atoms=excluded_atoms)

        # Write to json file
        if 'json_file' in fw_spec:
            json_file = fw_spec['json_file']
        else:
            json_file = 'structure_environments.json'
        f = open(json_file, 'w')
        json.dump(se.as_dict(), f)
        f.close()

        # Save to database
        if 'mongo_database' in fw_spec:
            database = fw_spec['mongo_database']
            entry = {
                'identifier':
                identifier,
                'elements':
                [elmt.symbol for elmt in structure.composition.elements],
                'nelements':
                len(structure.composition.elements),
                'pretty_formula':
                structure.composition.reduced_formula,
                'nsites':
                len(structure)
            }

            saving_option = fw_spec['saving_option']
            if saving_option == 'gridfs':
                gridfs_msonables = {
                    'structure': structure,
                    'structure_environments': se
                }
            elif saving_option == 'storefile':
                gridfs_msonables = None
                if 'se_prefix' in fw_spec:
                    se_prefix = fw_spec['se_prefix']
                    if not se_prefix.isalpha():
                        raise ValueError(
                            'Prefix for structure_environments file is "{}" '
                            'while it should be alphabetic'.format(se_prefix))
                else:
                    se_prefix = ''
                if se_prefix:
                    se_rfilename = '{}_{}.json'.format(
                        se_prefix, fw_spec['storefile_basename'])
                else:
                    se_rfilename = '{}.json'.format(
                        fw_spec['storefile_basename'])
                se_rfilepath = '{}/{}'.format(fw_spec['storefile_dirpath'],
                                              se_rfilename)
                storage_server = fw_spec['storage_server']
                storage_server.put(localpath=json_file,
                                   remotepath=se_rfilepath,
                                   overwrite=True,
                                   makedirs=False)
                entry['structure_environments_file'] = se_rfilepath
            else:
                raise ValueError(
                    'Saving option is "{}" while it should be '
                    '"gridfs" or "storefile"'.format(saving_option))
            criteria = {'identifier': identifier}
            if database.collection.find(criteria).count() == 1:
                database.update_entry(query=criteria,
                                      entry_update=entry,
                                      gridfs_msonables=gridfs_msonables)
            else:
                database.insert_entry(entry=entry,
                                      gridfs_msonables=gridfs_msonables)
Esempio n. 34
0
    def run_task(self, fw_spec):
        logging.basicConfig(filename='chemenv_structure_environments.log',
                            format='%(levelname)s:%(module)s:%(funcName)s:%(message)s',
                            level=logging.DEBUG)
        lgf = LocalGeometryFinder()
        lgf.setup_parameters(centering_type='centroid', include_central_site_in_centroid=True,
                             structure_refinement=lgf.STRUCTURE_REFINEMENT_NONE)
        if 'chemenv_parameters' in fw_spec:
            for param, value in fw_spec['chemenv_parameters'].items():
                lgf.setup_parameter(param, value)
        identifier = fw_spec['identifier']
        if 'structure' in fw_spec:
            structure = fw_spec['structure']
        else:
            if identifier['source'] == 'MaterialsProject' and 'material_id' in identifier:
                if not 'mapi_key' in fw_spec:
                    raise ValueError('The mapi_key should be provided to get the structure from the Materials Project')
                # FIXME: Use MPRester from pymatgen
                from pymatgen.matproj.rest import MPRester
                a = MPRester(fw_spec['mapi_key'])
                structure = a.get_structure_by_material_id(identifier['material_id'])
            else:
                raise ValueError('Either structure or identifier with source = MaterialsProject and material_id '
                                 'should be provided')

        info = {}
        # Compute the structure environments
        lgf.setup_structure(structure)
        if 'valences' in fw_spec:
            valences = fw_spec['valences']
        else:
            try:
                bva = BVAnalyzer()
                valences = bva.get_valences(structure=structure)
                info['valences'] = {'origin': 'BVAnalyzer'}
            except:
                valences = 'undefined'
                info['valences'] = {'origin': 'None'}
        excluded_atoms = None
        if 'excluded_atoms' in fw_spec:
            excluded_atoms = fw_spec['excluded_atoms']

        se = lgf.compute_structure_environments(only_cations=False, valences=valences, excluded_atoms=excluded_atoms)

        # Write to json file
        if 'json_file' in fw_spec:
            json_file = fw_spec['json_file']
        else:
            json_file = 'structure_environments.json'
        f = open(json_file, 'w')
        json.dump(se.as_dict(), f)
        f.close()

        # Save to database
        if 'mongo_database' in fw_spec:
            database = fw_spec['mongo_database']
            entry = {'identifier': identifier,
                     'elements': [elmt.symbol for elmt in structure.composition.elements],
                     'nelements': len(structure.composition.elements),
                     'pretty_formula': structure.composition.reduced_formula,
                     'nsites': len(structure)
                     }

            saving_option = fw_spec['saving_option']
            if saving_option == 'gridfs':
                gridfs_msonables = {'structure': structure,
                                    'structure_environments': se}
            elif saving_option == 'storefile':
                gridfs_msonables = None
                if 'se_prefix' in fw_spec:
                    se_prefix = fw_spec['se_prefix']
                    if not se_prefix.isalpha():
                        raise ValueError('Prefix for structure_environments file is "{}" '
                                         'while it should be alphabetic'.format(se_prefix))
                else:
                    se_prefix = ''
                if se_prefix:
                    se_rfilename = '{}_{}.json'.format(se_prefix, fw_spec['storefile_basename'])
                else:
                    se_rfilename = '{}.json'.format(fw_spec['storefile_basename'])
                se_rfilepath = '{}/{}'.format(fw_spec['storefile_dirpath'], se_rfilename)
                storage_server = fw_spec['storage_server']
                storage_server.put(localpath=json_file, remotepath=se_rfilepath, overwrite=True, makedirs=False)
                entry['structure_environments_file'] = se_rfilepath
            else:
                raise ValueError('Saving option is "{}" while it should be '
                                 '"gridfs" or "storefile"'.format(saving_option))
            criteria = {'identifier': identifier}
            if database.collection.find(criteria).count() == 1:
                database.update_entry(query=criteria, entry_update=entry,
                                      gridfs_msonables=gridfs_msonables)
            else:
                database.insert_entry(entry=entry, gridfs_msonables=gridfs_msonables)
Esempio n. 35
0
PACKAGE_PATH = os.path.dirname(__file__)

try:
    MPINT_CONFIG = loadfn(os.path.join(PACKAGE_PATH, 'mpint_config.yaml'))
except:
    MPINT_CONFIG = {}
    warnings.warn('mpint_config.yaml file not configured.')

# set environ variables for MAPI_KEY and VASP_PSP_DIR
if MPINT_CONFIG.get('potentials', ''):
    os.environ['VASP_PSP_DIR'] = MPINT_CONFIG.get('potentials', '')
MP_API = MPINT_CONFIG.get('mp_api', '')
if MP_API:
    os.environ['MAPI_KEY'] = MP_API

MPR = MPRester(MP_API)
USERNAME = MPINT_CONFIG.get('username', None)
VASP_STD_BIN = MPINT_CONFIG.get('normal_binary', None)
VASP_TWOD_BIN = MPINT_CONFIG.get('twod_binary', None)
VDW_KERNEL = MPINT_CONFIG.get('vdw_kernel', None)
VASP_PSP = MPINT_CONFIG.get('potentials', None)
QUEUE_SYSTEM = MPINT_CONFIG.get('queue_system', None)
QUEUE_TEMPLATE = MPINT_CONFIG.get('queue_template', None)

if not QUEUE_SYSTEM:
    QUEUE_SYSTEM = 'slurm'


def get_struct_from_mp(formula, MAPI_KEY="", all_structs=False):
    """
    fetches the structure corresponding to the given formula
Esempio n. 36
0
 def setUp(self):
     self.rester = MPRester()
Esempio n. 37
0
__author__ = 'Qimin'

import json
from pymatgen.matproj.rest import MPRester

if __name__ == '__main__':
    mpr = MPRester(api_key="UhlZvcEux2kmJSQx")

id_expgap = open("ids.txt", "r")
for line in id_expgap:
    words=line.split()
    print words
    id_line=words[0]
    bs = mpr.get_bandstructure_by_material_id(1)
    if bs != None:
        target = json.dumps(bs.to_dict)
        obj = json.loads(target)
        print obj["band_gap"]["energy"], obj["vbm"]["energy"], obj["cbm"]["energy"]
id_expgap.close()
Esempio n. 38
0
#Search Band Gaps (eV)
BAND_GAP_LB = 5.2  #original = 0.8eV
BAND_GAP_UB = 7

#Test with just Si
# i = 149


#This exception is an empty exception to handle no material at a given ID
class NoMaterialAtIDError(Exception):
    pass
    #Don't need anything here, just define it as an exception


with MPRester() as mp:
    bandgap_filter = mp.query(
        {"band_gap": {
            "$gt": BAND_GAP_LB,
            "$lt": BAND_GAP_UB
        }}, ["pretty_formula", "band_gap", "material_id"])
    # filters out materials with bandgaps outside desired area, pulls formula and materials_id
    number_of_compounds = len(bandgap_filter)

    for i in range(0, number_of_compounds - 1):
        try:
            #bandstruct = mp.get_bandstructure_by_material_id("mp-" + str(i))
            #We copy the internals of the get_bandstructure_by_material_id method
            #to handle missing material ids
            banddata = mp.get_data(bandgap_filter[i]['material_id'],
                                   prop="bandstructure")
Esempio n. 39
0
class MPResterTest(unittest.TestCase):
    def setUp(self):
        self.rester = MPRester()

    def test_get_data(self):
        props = [
            "energy", "energy_per_atom", "formation_energy_per_atom", "nsites",
            "unit_cell_formula", "pretty_formula", "is_hubbard", "elements",
            "nelements", "e_above_hull", "hubbards", "is_compatible",
            "task_ids", "density", "icsd_ids", "total_magnetization"
        ]
        # unicode literals have been reintroduced in py>3.2
        expected_vals = [
            -191.33812137, -6.833504334642858, -2.551358929370749, 28,
            {k: v
             for k, v in {
                 'P': 4,
                 'Fe': 4,
                 'O': 16,
                 'Li': 4
             }.items()}, "LiFePO4", True, ['Li', 'O', 'P', 'Fe'], 4, 0.0,
            {
                k: v
                for k, v in {
                    'Fe': 5.3,
                    'Li': 0.0,
                    'O': 0.0,
                    'P': 0.0
                }.items()
            }, True,
            [
                u'mp-601412', u'mp-19017', u'mp-796535', u'mp-797820',
                u'mp-540081', u'mp-797269'
            ], 3.4662026991351147,
            [
                159107, 154117, 160776, 99860, 181272, 166815, 260571, 92198,
                165000, 155580, 38209, 161479, 153699, 260569, 260570, 200155,
                260572, 181341, 181342, 72545, 56291, 97764, 162282, 155635
            ], 16.0002716
        ]

        for (i, prop) in enumerate(props):
            if prop not in [
                    'hubbards', 'unit_cell_formula', 'elements', 'icsd_ids',
                    'task_ids'
            ]:
                val = self.rester.get_data("mp-19017", prop=prop)[0][prop]
                self.assertAlmostEqual(expected_vals[i], val)
            elif prop in ["elements", "icsd_ids", "task_ids"]:
                self.assertEqual(
                    set(expected_vals[i]),
                    set(self.rester.get_data("mp-19017", prop=prop)[0][prop]))
            else:
                self.assertEqual(
                    expected_vals[i],
                    self.rester.get_data("mp-19017", prop=prop)[0][prop])

        props = ['structure', 'initial_structure', 'final_structure', 'entry']
        for prop in props:
            obj = self.rester.get_data("mp-19017", prop=prop)[0][prop]
            if prop.endswith("structure"):
                self.assertIsInstance(obj, Structure)
            elif prop == "entry":
                obj = self.rester.get_data("mp-19017", prop=prop)[0][prop]
                self.assertIsInstance(obj, ComputedEntry)

        #Test chemsys search
        data = self.rester.get_data('Fe-Li-O', prop='unit_cell_formula')
        self.assertTrue(len(data) > 1)
        elements = {Element("Li"), Element("Fe"), Element("O")}
        for d in data:
            self.assertTrue(
                set(Composition(
                    d['unit_cell_formula']).elements).issubset(elements))

        self.assertRaises(MPRestError, self.rester.get_data, "Fe2O3",
                          "badmethod")

    def test_get_materials_id_from_task_id(self):
        self.assertEqual(
            self.rester.get_materials_id_from_task_id("mp-540081"), "mp-19017")

    def test_get_materials_id_references(self):
        # nosetests pymatgen/matproj/tests/test_rest.py:MPResterTest.test_get_materials_id_references
        m = MPRester()
        data = m.get_materials_id_references('mp-123')
        self.assertTrue(len(data) > 1000)

    def test_find_structure(self):
        # nosetests pymatgen/matproj/tests/test_rest.py:MPResterTest.test_find_structure
        m = MPRester()
        ciffile = os.path.join(test_dir, 'Fe3O4.cif')
        data = m.find_structure(ciffile)
        self.assertTrue(len(data) > 1)
        s = CifParser(ciffile).get_structures()[0]
        data = m.find_structure(s)
        self.assertTrue(len(data) > 1)

    def test_get_entries_in_chemsys(self):
        syms = ["Li", "Fe", "O"]
        entries = self.rester.get_entries_in_chemsys(syms)
        elements = set([Element(sym) for sym in syms])
        for e in entries:
            self.assertIsInstance(e, ComputedEntry)
            self.assertTrue(set(e.composition.elements).issubset(elements))

    def test_get_structure_by_material_id(self):
        s1 = self.rester.get_structure_by_material_id("mp-1")
        self.assertEqual(s1.formula, "Cs1")

    def test_get_entry_by_material_id(self):
        e = self.rester.get_entry_by_material_id("mp-19017")
        self.assertIsInstance(e, ComputedEntry)
        self.assertTrue(e.composition.reduced_formula, "LiFePO4")

    def test_query(self):
        criteria = {'elements': {'$in': ['Li', 'Na', 'K'], '$all': ['O']}}
        props = ['pretty_formula', 'energy']
        data = self.rester.query(criteria=criteria, properties=props)
        self.assertTrue(len(data) > 6)
        data = self.rester.query(criteria="*2O", properties=props)
        self.assertGreaterEqual(len(data), 52)
        self.assertIn("Li2O", (d["pretty_formula"] for d in data))

    def test_get_exp_thermo_data(self):
        data = self.rester.get_exp_thermo_data("Fe2O3")
        self.assertTrue(len(data) > 0)
        for d in data:
            self.assertEqual(d.formula, "Fe2O3")

    def test_get_dos_by_id(self):
        dos = self.rester.get_dos_by_material_id("mp-2254")
        self.assertIsInstance(dos, CompleteDos)

    def test_get_bandstructure_by_material_id(self):
        bs = self.rester.get_bandstructure_by_material_id("mp-2254")
        self.assertIsInstance(bs, BandStructureSymmLine)

    def test_get_structures(self):
        structs = self.rester.get_structures("Mn3O4")
        self.assertTrue(len(structs) > 0)

    def test_get_entries(self):
        entries = self.rester.get_entries("TiO2")
        self.assertTrue(len(entries) > 1)
        for e in entries:
            self.assertEqual(e.composition.reduced_formula, "TiO2")

        entries = self.rester.get_entries("TiO2", inc_structure="final")
        self.assertTrue(len(entries) > 1)
        for e in entries:
            self.assertEqual(e.structure.composition.reduced_formula, "TiO2")

        all_entries = self.rester.get_entries("Fe", compatible_only=False)
        entries = self.rester.get_entries("Fe", compatible_only=True)
        self.assertTrue(len(entries) < len(all_entries))

        entries = self.rester.get_entries("Fe",
                                          compatible_only=True,
                                          property_data=["cif"])
        self.assertIn("cif", entries[0].data)

    def test_get_exp_entry(self):
        entry = self.rester.get_exp_entry("Fe2O3")
        self.assertEqual(entry.energy, -825.5)

    def test_submit_query_delete_snl(self):
        s = Structure([[5, 0, 0], [0, 5, 0], [0, 0, 5]], ["Fe"], [[0, 0, 0]])
        # d = self.rester.submit_snl(
        #     [s, s], remarks=["unittest"],
        #     authors="Test User <*****@*****.**>")
        # self.assertEqual(len(d), 2)
        # data = self.rester.query_snl({"about.remarks": "unittest"})
        # self.assertEqual(len(data), 2)
        # snlids = [d["_id"] for d in data]
        # self.rester.delete_snl(snlids)
        # data = self.rester.query_snl({"about.remarks": "unittest"})
        # self.assertEqual(len(data), 0)

    def test_get_stability(self):
        entries = self.rester.get_entries_in_chemsys(["Fe", "O"])
        modified_entries = []
        for entry in entries:
            # Create modified entries with energies that are 0.01eV higher
            # than the corresponding entries.
            if entry.composition.reduced_formula == "Fe2O3":
                modified_entries.append(
                    ComputedEntry(entry.composition,
                                  entry.uncorrected_energy + 0.01,
                                  parameters=entry.parameters,
                                  entry_id="mod_{}".format(entry.entry_id)))
        rest_ehulls = self.rester.get_stability(modified_entries)
        all_entries = entries + modified_entries
        compat = MaterialsProjectCompatibility()
        all_entries = compat.process_entries(all_entries)
        pd = PhaseDiagram(all_entries)
        a = PDAnalyzer(pd)
        for e in all_entries:
            if str(e.entry_id).startswith("mod"):
                for d in rest_ehulls:
                    if d["entry_id"] == e.entry_id:
                        data = d
                        break
                self.assertAlmostEqual(a.get_e_above_hull(e),
                                       data["e_above_hull"])

    def test_get_reaction(self):
        rxn = self.rester.get_reaction(["Li", "O"], ["Li2O"])
        self.assertIn("Li2O", rxn["Experimental_references"])

    def test_parse_criteria(self):
        crit = MPRester.parse_criteria("mp-1234 Li-*")
        self.assertIn("Li-O", crit["$or"][1]["chemsys"]["$in"])
        self.assertIn({"task_id": "mp-1234"}, crit["$or"])

        crit = MPRester.parse_criteria("Li2*")
        self.assertIn("Li2O", crit["pretty_formula"]["$in"])
        self.assertIn("Li2I", crit["pretty_formula"]["$in"])
        self.assertIn("CsLi2", crit["pretty_formula"]["$in"])

        crit = MPRester.parse_criteria("Li-*-*")
        self.assertIn("Li-Re-Ru", crit["chemsys"]["$in"])
        self.assertNotIn("Li-Li", crit["chemsys"]["$in"])

        comps = MPRester.parse_criteria("**O3")["pretty_formula"]["$in"]
        for c in comps:
            self.assertEqual(len(Composition(c)), 3, "Failed in %s" % c)

        chemsys = MPRester.parse_criteria("{Fe,Mn}-O")["chemsys"]["$in"]
        self.assertEqual(len(chemsys), 2)
        comps = MPRester.parse_criteria("{Fe,Mn,Co}O")["pretty_formula"]["$in"]
        self.assertEqual(len(comps), 3, comps)

        #Let's test some invalid symbols

        self.assertRaises(ValueError, MPRester.parse_criteria, "li-fe")
        self.assertRaises(ValueError, MPRester.parse_criteria, "LO2")

        crit = MPRester.parse_criteria("POPO2")
        self.assertIn("P2O3", crit["pretty_formula"]["$in"])
Esempio n. 40
0
class MPResterTest(unittest.TestCase):

    def setUp(self):
        self.rester = MPRester()

    def test_get_data(self):
        props = ["energy", "energy_per_atom", "formation_energy_per_atom",
                 "nsites", "unit_cell_formula", "pretty_formula", "is_hubbard",
                 "elements", "nelements", "e_above_hull", "hubbards",
                 "is_compatible", "task_ids",
                 "density", "icsd_ids", "total_magnetization"]
        expected_vals = [-191.33812137, -6.833504334642858, -2.551358929370749,
                         28, {u'P': 4, u'Fe': 4, u'O': 16, u'Li': 4},
                         "LiFePO4", True, [u'Li', u'O', u'P', u'Fe'], 4, 0.0,
                         {u'Fe': 5.3, u'Li': 0.0, u'O': 0.0, u'P': 0.0}, True,
                         ['mp-540081', 'mp-601412', 'mp-19017'],
                         3.4662026991351147,
                         [159107, 154117, 160776, 99860, 181272, 166815,
                          260571, 92198, 165000, 155580, 38209, 161479, 153699,
                          260569, 260570, 200155, 260572, 181341, 181342,
                          72545, 56291, 97764, 162282, 155635],
                         16.0002716]

        for (i, prop) in enumerate(props):
            if prop not in ['hubbards', 'unit_cell_formula', 'elements',
                            'icsd_ids', 'task_ids']:
                val = self.rester.get_data("mp-19017", prop=prop)[0][prop]
                self.assertAlmostEqual(expected_vals[i], val)
            elif prop in ["elements", "icsd_ids", "task_ids"]:
                self.assertEqual(set(expected_vals[i]),
                                 set(self.rester.get_data("mp-19017",
                                                          prop=prop)[0][prop]))
            else:
                self.assertEqual(expected_vals[i],
                                 self.rester.get_data("mp-19017",
                                                      prop=prop)[0][prop])

        props = ['structure', 'initial_structure', 'final_structure', 'entry']
        for prop in props:
            obj = self.rester.get_data("mp-19017", prop=prop)[0][prop]
            if prop.endswith("structure"):
                self.assertIsInstance(obj, Structure)
            elif prop == "entry":
                obj = self.rester.get_data("mp-19017", prop=prop)[0][prop]
                self.assertIsInstance(obj, ComputedEntry)

        #Test chemsys search
        data = self.rester.get_data('Fe-Li-O', prop='unit_cell_formula')
        self.assertTrue(len(data) > 1)
        elements = {Element("Li"), Element("Fe"), Element("O")}
        for d in data:
            self.assertTrue(
                set(Composition(d['unit_cell_formula']).elements).issubset(
                    elements))

        self.assertRaises(MPRestError, self.rester.get_data, "Fe2O3",
                          "badmethod")

    def test_get_materials_id_from_task_id(self):
        self.assertEqual(self.rester.get_materials_id_from_task_id(
            "mp-540081"), "mp-19017")

    def test_get_entries_in_chemsys(self):
        syms = ["Li", "Fe", "O"]
        all_entries = self.rester.get_entries_in_chemsys(syms, False)
        entries = self.rester.get_entries_in_chemsys(syms)
        self.assertTrue(len(entries) <= len(all_entries))
        elements = set([Element(sym) for sym in syms])
        for e in entries:
            self.assertIsInstance(e, ComputedEntry)
            self.assertTrue(set(e.composition.elements).issubset(elements))

    def test_get_structure_by_material_id(self):
        s1 = self.rester.get_structure_by_material_id("mp-1")
        self.assertEqual(s1.formula, "Cs1")

    def test_get_entry_by_material_id(self):
        e = self.rester.get_entry_by_material_id("mp-19017")
        self.assertIsInstance(e, ComputedEntry)
        self.assertTrue(e.composition.reduced_formula, "LiFePO4")

    def test_query(self):
        criteria = {'elements': {'$in': ['Li', 'Na', 'K'], '$all': ['O']}}
        props = ['formula', 'energy']
        data = self.rester.query(criteria=criteria, properties=props)
        self.assertTrue(len(data) > 6)

    def test_get_exp_thermo_data(self):
        data = self.rester.get_exp_thermo_data("Fe2O3")
        self.assertTrue(len(data) > 0)
        for d in data:
            self.assertEqual(d.formula, "Fe2O3")

    def test_get_dos_by_id(self):
        dos = self.rester.get_dos_by_material_id("mp-2254")
        self.assertIsInstance(dos, CompleteDos)

    def test_get_bandstructure_by_material_id(self):
        bs = self.rester.get_bandstructure_by_material_id("mp-2254")
        self.assertIsInstance(bs, BandStructureSymmLine)

    def test_get_structures(self):
        structs = self.rester.get_structures("Mn3O4")
        self.assertTrue(len(structs) > 0)

    def test_get_entries(self):
        entries = self.rester.get_entries("TiO2")
        self.assertTrue(len(entries) > 1)
        for e in entries:
            self.assertEqual(e.composition.reduced_formula, "TiO2")

        entries = self.rester.get_entries("TiO2", inc_structure="final")
        self.assertTrue(len(entries) > 1)
        for e in entries:
            self.assertEqual(e.structure.composition.reduced_formula, "TiO2")

    def test_get_exp_entry(self):
        entry = self.rester.get_exp_entry("Fe2O3")
        self.assertEqual(entry.energy, -825.5)

    def test_submit_query_delete_snl(self):
        s = Structure([[5, 0, 0], [0, 5, 0], [0, 0, 5]], ["Fe"], [[0, 0, 0]])
        # d = self.rester.submit_snl(
        #     [s, s], remarks=["unittest"],
        #     authors="Test User <*****@*****.**>")
        # self.assertEqual(len(d), 2)
        # data = self.rester.query_snl({"about.remarks": "unittest"})
        # self.assertEqual(len(data), 2)
        # snlids = [d["_id"] for d in data]
        # self.rester.delete_snl(snlids)
        # data = self.rester.query_snl({"about.remarks": "unittest"})
        # self.assertEqual(len(data), 0)

    def test_get_stability(self):
        entries = self.rester.get_entries("Fe-O")
        modified_entries = []
        for entry in entries:
            # Create modified entries with energies that are 0.01eV higher
            # than the corresponding entries.
            if entry.composition.reduced_formula == "Fe2O3":
                modified_entries.append(
                    ComputedEntry(entry.composition,
                                  entry.uncorrected_energy + 0.01,
                                  parameters=entry.parameters,
                                  entry_id="mod_{}".format(entry.entry_id)))
        rest_ehulls = self.rester.get_stability(modified_entries)
        all_entries = entries + modified_entries
        compat = MaterialsProjectCompatibility()
        all_entries = compat.process_entries(all_entries)
        pd = PhaseDiagram(all_entries)
        a = PDAnalyzer(pd)
        for e in all_entries:
            if str(e.entry_id).startswith("mod"):
                for d in rest_ehulls:
                    if d["entry_id"] == e.entry_id:
                        data = d
                        break
                self.assertAlmostEqual(a.get_e_above_hull(e),
                                       data["e_above_hull"])

    def test_get_reaction(self):
        rxn = self.rester.get_reaction(["Li", "O"], ["Li2O"])
        self.assertIn("Li2O", rxn["Experimental_references"])
Esempio n. 41
0
 def test_get_materials_id_references(self):
     # nosetests pymatgen/matproj/tests/test_rest.py:MPResterTest.test_get_materials_id_references
     m = MPRester()
     data = m.get_materials_id_references('mp-123')
     self.assertTrue(len(data) > 1000)
__version__ = '0.1'
__maintainer__ = 'Saurabh Bajaj'
__email__ = '*****@*****.**'
__date__ = 'Feb 05, 2016'


def get_band_center(form):
    comp = Composition(str(form))
    prod = 1.0
    for el, amt in comp.get_el_amt_dict().iteritems():
        prod = prod * (Element(el).X ** amt)
        return -prod ** (1 / sum(comp.get_el_amt_dict().values()))


if __name__ == '__main__':
    mpr = MPRester()
    f_w = open('Best_n_p_TEs_out.csv', 'wb')
    csv_outfile = csv.writer(f_w)
    csv_outfile.writerow(['formula', 'band gap', '(band gap)/2', 'CBM', 'band center', 'VBM', 'materials_id', 'icsd_id',
                          'Umutlist_type'])
    colnames = ['p-type', 'n-type']
    df = pandas.read_csv('Best_n_p_TEs.csv', names=colnames)
    input_data_ptype = df['p-type'].tolist()[1:]
    y = 0
    compositions = []
    for column in df:
        if column == 'p-type':
            te_type = 'p-type'
        elif column == 'n-type':
            te_type = 'n-type'
        for compound in df[column].tolist()[1:]:
Esempio n. 43
0
import pymongo
from pymatgen.matproj.rest import MPRester
import re

client = pymongo.MongoClient()
db = client.springer
mpr = MPRester()

if __name__ == '__main__':
    ids_to_check = []
    x = 0
    for doc in db['pauling_file_tags'].find({
            'structure': {
                '$exists': True
            }
    }).batch_size(75):
        x += 1
        if x % 1000 == 0:
            print x
        title = doc['metadata']['_Springer']['title']
        phase = doc['metadata']['_Springer']['geninfo']['Phase Label(s)']
        if ' ht' not in title and 'T =' not in title and ' ht' not in phase:
            if 'temperature' in doc['metadata']['_Springer']['expdetails']:
                exp_t = doc['metadata']['_Springer']['expdetails'][
                    'temperature']
                try:
                    temp_str = re.findall(r'T\s*=\s*(.*)\s*K', exp_t)[0]
                    temp_exp = float(re.sub('\(.*\)', '', temp_str))
                    if temp_exp > 450:
                        ids_to_check.append(doc['key'])
                except:
'''

from ScreenSurf import ScreenSurf
from pymatgen.io.vasp import Poscar
from pymatgen.io.cif import CifParser
from pymatgen.matproj.rest import MPRester
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer

# Structures can be directly imported from the Materials Project, using the Materials Project API

# Here are some examples from the paper
# TiO2-Anatase:   'mp-390'
# Cu2O-Cuprite:   'mp-361'
# Al2O3-Corundum: 'mp-1143'

with MPRester("YOUR_API_KEY") as m:
    bulkstruct = m.get_structure_by_material_id('mp-1143')

# Initiate the surface screening algorithm
SS = ScreenSurf(bulkstruct)

index = SS.ScreenSurfaces(natomsinsphere=20,
                          keep=1,
                          samespeconly=True,
                          ignore=[])
# ScreenSurfaces uses the following parameters:
#    natomsinsphere = Increases radius of sphere until there are #natomsinsphere in the sphere. For simple structures this can be as low as 20.
#    keep = What percentage of the histogram to keep up to. Using keep=0.8 means we only keep the most common 80% of planes.
#    samespeconly = This is whether or not to search for only atoms of the same element in the sphere.
#    ignore = these are atoms to ignore. These often include small atoms on complex anions (e.g., O on CO_3^2-), or other moieties, like hydrogen.
Esempio n. 45
0
def vac_antisite_def_struct_gen(c_size=15, mpid='', struct=None):
    def_str = []
    if struct == None:
        with MPRester() as mp:
            struct = mp.get_structure_by_material_id(mpid)
        if mpid == '':
            print("Provide structure")
    dim1 = int((float(c_size) / float(max(abs(struct.lattice.matrix[0]))))) + 1
    dim2 = int(float(c_size) / float(max(abs(struct.lattice.matrix[1])))) + 1
    dim3 = int(float(c_size) / float(max(abs(struct.lattice.matrix[2])))) + 1
    cellmax = max(dim1, dim2, dim3)
    prim_struct_sites = len(struct.sites)
    struct = SpacegroupAnalyzer(struct).get_conventional_standard_structure()
    conv_struct_sites = len(struct.sites)
    conv_prim_rat = 1 + int(conv_struct_sites / prim_struct_sites)
    sc_scale = [dim1, dim2, dim3]
    print("sc_scale", sc_scale)

    struct_valrad_eval = ValenceIonicRadiusEvaluator(struct)
    val = struct_valrad_eval.valences
    rad = struct_valrad_eval.radii
    struct_val = val
    struct_rad = rad

    vac = Vacancy(struct, {}, {})
    scs = vac.make_supercells_with_defects(sc_scale)
    #print ('scssssss',scs[0].make_supercell([1,1,1]))

    for i in range(len(scs)):
        sc = scs[i]
        mpvis = MPRelaxSet(sc)  #VaspInputSet(struct)
        #print ('sccccc',sc,type(sc[0]))
        tmp = struct.copy()
        poscar = mpvis.poscar
        #kpoints = Kpoints.automatic_density(sc,kpoint_den)
        #incar = mpvis.get_incar(sc)
        #print ('big pos',poscar)
        interdir = mpid
        if not i:
            fin_dir = os.path.join(interdir, 'bulk')
            poscar.comment = str('bulk') + str('@') + str('cellmax') + str(
                cellmax)
            def_str.append(poscar)
            poscar.write_file('POSCAR-' + str('bulk') + str(".vasp"))
        else:
            blk_str_sites = set(scs[0].sites)
            vac_str_sites = set(sc.sites)
            vac_sites = blk_str_sites - vac_str_sites
            vac_site = list(vac_sites)[0]
            site_mult = int(
                vac.get_defectsite_multiplicity(i - 1) / conv_prim_rat)
            vac_site_specie = vac_site.specie
            vac_symbol = vac_site.specie.symbol

            vac_dir = 'vacancy_{}_mult-{}_sitespecie-{}'.format(
                str(i), site_mult, vac_symbol)
            fin_dir = os.path.join(interdir, vac_dir)
            try:
                poscar.comment = str(vac_dir) + str('@') + str(
                    'cellmax') + str(cellmax)
            except:
                pass
            pos = poscar
            def_str.append(pos)
            poscar.write_file('POSCAR-' + str(vac_dir) + str(".vasp"))
            struct_species = scs[0].types_of_specie
            for specie in set(struct_species) - set([vac_site_specie]):
                subspecie_symbol = specie.symbol
                anti_struct = sc.copy()
                anti_struct.append(specie, vac_site.frac_coords)
                mpvis = MPRelaxSet(anti_struct)  #VaspInputSet(struct)
                print('anti_struct', anti_struct)
                poscar = mpvis.poscar
                as_dir = 'antisite_{}_mult-{}_sitespecie-{}_subspecie-{}'.format(
                    str(i), site_mult, vac_symbol, subspecie_symbol)
                fin_dir = os.path.join(interdir, as_dir)
                poscar.comment = str(as_dir) + str('@') + str('cellmax') + str(
                    cellmax)
                pos = poscar
                def_str.append(pos)
                poscar.write_file('POSCAR-' + str(as_dir) + str(".vasp"))

    return def_str
    comps_cids = None
    try:
        from bson import ObjectId
        cids = open(cids_file).read().splitlines()
        comps_cids = [(None, ObjectId(cid_str)) for cid_str in cids]
        if args.dev:
            raise ValueError('need full MPFile for on-the-fly analysis!')
    except (InvalidId, TypeError):
        from mpcontribs.io.mpfile import MPFile
        mpfile = MPFile.from_file(cids_file) # TODO cid-only read mode?
        comps_cids = [(x[0], ObjectId(x[1])) for x in mpfile.get_identifiers()]

    # set up rester and PDF
    SITE = 'http://localhost:8000'
    ENDPOINT, API_KEY = "{}/rest".format(SITE), os.environ.get('MAPI_KEY_LOC')
    mpr = MPRester(API_KEY, endpoint=ENDPOINT)
    merger = PdfFileMerger()

    # get all XAS/XMCD spectra
    if args.dev:
        port = 5000 + random.randint(0, 999)
        url = "http://127.0.0.1:{0}/pdf?mpfile={1}".format(port, cids_file)
        #threading.Timer(1.25, lambda: webbrowser.open(url)).start()
        #app.run(port=port, debug=False)
        # TODO find way to automatically append to PDF
        #pdf = pdfkit.from_url(url, False)
        #merger.append(pdf)
    else:
        doc = {}
        for comp,cid in comps_cids:
            print cid
Esempio n. 47
0
__author__ = 'Qimin'

from pymatgen.matproj.rest import MPRester
from pymatgen.io.vaspio.vasp_input import Kpoints,Incar
from pymatgen.io.vaspio.vasp_output import Outcar, Vasprun
from pymatgen.io.vaspio_set import MPNonSCFVaspInputSet, MPStaticVaspInputSet
import os

if __name__ == '__main__':
    mpr = MPRester(api_key="UhlZvcEux2kmJSQx")

id_expgap = open("ids.txt", "r")

for line in id_expgap:
    words=line.split()
    print words
    id_line=words[0]

    vasp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), str(id_line))
    vasp_run = Vasprun(os.path.join(vasp_dir,"vasprun.xml")).to_dict
    nband = int(vasp_run['input']['parameters']['NBANDS'])
    

    os.chdir(id_line)

    user_incar_settings={"EDIFF":1E-4,"NBANDS":nband,"NSW":0}
    mpvis = MPNonSCFVaspInputSet(user_incar_settings=user_incar_settings)
    s = mpr.get_structure_by_material_id(id_line)
    mpvis.get_kpoints(s).write_file('KPOINTS')
    mpvis.get_incar(s).write_file('INCAR')
    
Esempio n. 48
0
            "pretty_formula"] + "x"  # just adding a character to avoid error in "coefficientof" function
        print(data[n]["pretty_formula"])
        n_e = coefficientof(element1, formula)
        n_d = coefficientof(dopant, formula)
        formation_energies[n] = (data[n]['energy_per_atom'] * (n_e + n_d) -
                                 n_e * energy1 - n_d * energy_dopant) / n_d
    formation_energies = np.append(formation_energies, 0)
    chem = np.min(np.append(formation_energies, [0]))
    return (chem)


if __name__ == "__main__":

    apikey = 'fDJKEZpxSyvsXdCt'
    from pymatgen.matproj.rest import MPRester
    matproj = MPRester(apikey)

    ### Check the input arguments
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-de",
        "--defect_names",
        help="The list of the name of defects (e.g. ['V_O', 'V_Zn'])",
        required=False)
    parser.add_argument(
        "-di",
        "--dielectric_constant",
        help=
        "The dielectric constant of the base material for 1st order Makov-Payne correction",
        required=False)
    args = parser.parse_args()
Esempio n. 49
0
import twod_materials


PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
CONFIG_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])

try:
    config_vars = loadfn(os.path.join(os.path.expanduser('~'), 'config.yaml'))
except:
    # For testing purposes.
    config_vars = loadfn(os.path.join(CONFIG_PATH, 'config.yaml'))

if 'MP_API' in os.environ:
    # For testing purposes.
    MPR = MPRester(os.environ['MP_API'])
else:
    MPR = MPRester(config_vars['mp_api'])


class UtilsTest(unittest.TestCase):


    def test_is_converged(self):
        false_control = is_converged(PACKAGE_PATH)
        true_control = is_converged(os.path.join(PACKAGE_PATH,
                                                 'stability/tests/BiTeCl'))
        self.assertTrue(true_control)
        self.assertFalse(false_control)

Esempio n. 50
0
    def __init__(
        self,
        api_key,
        list_of_elements=[],
        indices_dict=None,
        slab_size=10,
        vac_size=10,
        host=None,
        port=None,
        user=None,
        password=None,
        symprec=0.001,
        angle_tolerance=5,
        database=None,
        collection="Surface_Collection",
        fail_safe=True,
        reset=False,
    ):

        """
            Args:
                api_key (str): A String API key for accessing the MaterialsProject
                list_of_elements ([str, ...]): A list of compounds or elements to create
                    slabs from. Must be a string that can be searched for with MPRester.
                    Either list_of_elements or indices_dict has to be entered in.
                indices_dict ({element(str): [[h,k,l], ...]}): A dictionary of
                    miller indices corresponding to the composition formula
                    (key) to transform into a list of slabs. Either list_of_elements
                    or indices_dict has to be entered in.
                host (str): For database insertion
                port (int): For database insertion
                user (str): For database insertion
                password (str): For database insertion
                symprec (float): See SpaceGroupAnalyzer in analyzer.py
                angle_tolerance (int): See SpaceGroupAnalyzer in analyzer.py
                database (str): For database insertion
        """

        unit_cells_dict = {}
        vaspdbinsert_params = {
            "host": host,
            "port": port,
            "user": user,
            "password": password,
            "database": database,
            "collection": collection,
        }

        elements = [key for key in indices_dict.keys()] if indices_dict else list_of_elements

        # For loop will eneumerate through all the compositional
        # formulas in list_of_elements or indices_dict to get a
        # list of relaxed conventional unit cells froom MP. These
        # will be used to generate all oriented unit cells and slabs.

        for el in elements:

            """
            element: str, element name of Metal
            miller_index: hkl, e.g. [1, 1, 0]
            api_key: to get access to MP DB
            """

            # This initializes the REST adaptor. Put your own API key in.
            mprest = MPRester(api_key)
            # Returns a list of MPIDs with the compositional formular, the
            # first MPID IS NOT the lowest energy per atom
            entries = mprest.get_entries(el, inc_structure="final")

            e_per_atom = [entry.energy_per_atom for entry in entries]
            for entry in entries:
                if min(e_per_atom) == entry.energy_per_atom:
                    prim_unit_cell = entry.structure

            spa = SpacegroupAnalyzer(prim_unit_cell, symprec=symprec, angle_tolerance=angle_tolerance)
            conv_unit_cell = spa.get_conventional_standard_structure()
            print conv_unit_cell
            unit_cells_dict[el] = [conv_unit_cell, min(e_per_atom)]
            print el

        self.api_key = api_key
        self.vaspdbinsert_params = vaspdbinsert_params
        self.symprec = symprec
        self.angle_tolerance = angle_tolerance
        self.unit_cells_dict = unit_cells_dict
        self.indices_dict = indices_dict
        self.elements = elements
        self.ssize = slab_size
        self.vsize = vac_size
        self.reset = reset
        self.fail_safe = fail_safe
Esempio n. 51
0
  #f=open(ff,'r')
  os.chdir(str(folder1))
  #list_el=[]
  #lines=f.readlines()
  #content=(lines[3]).split(" ")
  #content=(lines[3]).split("' '|\n|\r\n")
  #for val in content:
  
 #     if val != '' and val !='\n' and val !='\r\n':
 #        list_el.append(val)
 # for i in range(0,len(list_el)):
 #      if i!=0:
 #          element_ff.append(list_el[i])    
 #    print ff,' ',element_ff
  element_ff=['Ti','O','N']
  with MPRester(MAPI_KEY) as m:
       data = m.get_entries_in_chemsys(element_ff,inc_structure='final', property_data=["unit_cell_formula","material_id","icsd_id","spacegroup","energy_per_atom","formation_energy_per_atom","pretty_formula","band_gap","total_magnetization","e_above_hull"])
       if (len(element_ff)>1):
           try:
               entries = m.get_entries_in_chemsys(element_ff)
               pd = PhaseDiagram(entries)
               plotter = PDPlotter(pd, show_unstable=True)
               image=str(ff)+str("_DFT")+str(".jpg")
               plotter.write_image(image)
           except:
               pass
       structures=[]
       structures_cvn=[]
       icsd_arr=[]
       mp_arr=[]
       sg_arr=[]
Esempio n. 52
0
	if args.detail == "less":
		stat.write('%30s%12s%12s%12s %10s%7s%10s%10s%10s%7s%9s%9s\n' % ('location_of_mp-id_if-any', 'formula', 'mu-cm2/V.s', 'sigma-S/cm', 'S-uV/K', 'PF', 'p_mu', 'p_sigma', 'p_S', 'p_PF', 'm_e', 'm_h'))
	elif args.detail == "more":
		stat.write('%30s%12s%12s%12s %10s%7s%10s%10s%10s%7s%9s%9s%8s%8s%7s%7s%6s%6s\n' % ('location_of_mp-id_if-any', 'formula', 'mu-cm2/V.s', 'sigma-S/cm', \
			'S-uV/K', 'PF', 'p_mu', 'p_sigma', 'p_S', 'p_PF', 'm_e', 'm_h',\
				'omegaLO', 'omegaTO', 'eps0', 'epsinf', 'nEdef', 'pEdef'))
	for c in clist:
		if ":" in c:
			stat.write(c + "\n")
			continue
		formula = c
		if args.formula:
			try:
				apikey = 'fDJKEZpxSyvsXdCt'
				from pymatgen.matproj.rest import MPRester
				matproj = MPRester(apikey)
				formula = matproj.get_data(c, prop="pretty_formula")[0]["pretty_formula"]
				spacegroup = matproj.get_data(c, prop="spacegroup")[0]["spacegroup"]
			except:
				formula = 'API-failed'
		proceed = False
		for subf in folders:
			if os.path.exists(subf + c):
				proceed = True
				c_path = subf + c
		if proceed:
			os.chdir(c_path)
			
			if args.detail == "more":
				os.chdir('nself')
        	                val_kpoint, con_kpoint, eval, econ, core = find_reference(scripts_path)
Esempio n. 53
0
class MPResterTest(unittest.TestCase):

    def setUp(self):
        self.rester = MPRester()

    def test_get_data(self):
        props = ["energy", "energy_per_atom", "formation_energy_per_atom",
                 "nsites", "unit_cell_formula", "pretty_formula", "is_hubbard",
                 "elements", "nelements", "e_above_hull", "hubbards",
                 "is_compatible", "task_ids",
                 "density", "icsd_id", "total_magnetization"]
        expected_vals = [-191.33812137, -6.833504334642858, -2.551358929370749,
                         28, {u'P': 4, u'Fe': 4, u'O': 16, u'Li': 4},
                         "LiFePO4", True, [u'Li', u'O', u'P', u'Fe'], 4, 0.0,
                         {u'Fe': 5.3, u'Li': 0.0, u'O': 0.0, u'P': 0.0}, True,
                         ['mp-540081', 'mp-601412', 'mp-19017'],
                         3.4662026991351147,
                         [159107, 154117, 160776, 99860, 181272, 166815,
                          260571, 92198, 165000, 155580, 38209, 161479, 153699,
                          260569, 260570, 200155, 260572, 181341, 181342,
                          72545, 56291, 97764, 162282, 155635],
                         16.0002716]

        for (i, prop) in enumerate(props):
            if prop not in ['hubbards', 'unit_cell_formula', 'elements',
                            'icsd_id']:
                val = self.rester.get_data("mp-19017", prop=prop)[0][prop]
                self.assertAlmostEqual(expected_vals[i], val)
            elif prop in ["elements", "icsd_id"]:
                self.assertEqual(set(expected_vals[i]),
                                 set(self.rester.get_data("mp-19017",
                                                          prop=prop)[0][prop]))
            else:
                self.assertEqual(expected_vals[i],
                                 self.rester.get_data("mp-19017",
                                                      prop=prop)[0][prop])

        props = ['structure', 'initial_structure', 'final_structure', 'entry']
        for prop in props:
            obj = self.rester.get_data("mp-19017", prop=prop)[0][prop]
            if prop.endswith("structure"):
                self.assertIsInstance(obj, Structure)
            elif prop == "entry":
                obj = self.rester.get_data("mp-19017", prop=prop)[0][prop]
                self.assertIsInstance(obj, ComputedEntry)

        #Test chemsys search
        data = self.rester.get_data('Fe-Li-O', prop='unit_cell_formula')
        self.assertTrue(len(data) > 1)
        elements = {Element("Li"), Element("Fe"), Element("O")}
        for d in data:
            self.assertTrue(
                set(Composition(d['unit_cell_formula']).elements).issubset(
                    elements))

        self.assertRaises(MPRestError, self.rester.get_data, "Fe2O3",
                          "badmethod")

    def test_get_materials_id_from_task_id(self):
        self.assertEqual(self.rester.get_materials_id_from_task_id(
            "mp-540081"), "mp-19017")

    def test_get_entries_in_chemsys(self):
        syms = ["Li", "Fe", "O"]
        all_entries = self.rester.get_entries_in_chemsys(syms, False)
        entries = self.rester.get_entries_in_chemsys(syms)
        self.assertTrue(len(entries) <= len(all_entries))
        elements = set([Element(sym) for sym in syms])
        for e in entries:
            self.assertIsInstance(e, ComputedEntry)
            self.assertTrue(set(e.composition.elements).issubset(elements))

    def test_get_structure_by_material_id(self):
        s1 = self.rester.get_structure_by_material_id("mp-1")
        self.assertEqual(s1.formula, "Cs1")

    def test_get_entry_by_material_id(self):
        e = self.rester.get_entry_by_material_id("mp-19017")
        self.assertIsInstance(e, ComputedEntry)
        self.assertTrue(e.composition.reduced_formula, "LiFePO4")

    def test_mpquery(self):
        criteria = {'elements': {'$in': ['Li', 'Na', 'K'], '$all': ['O']}}
        props = ['formula', 'energy']
        data = self.rester.mpquery(criteria=criteria, properties=props)
        self.assertTrue(len(data) > 6)

    def test_get_exp_thermo_data(self):
        data = self.rester.get_exp_thermo_data("Fe2O3")
        self.assertTrue(len(data) > 0)
        for d in data:
            self.assertEqual(d.formula, "Fe2O3")

    def test_get_dos_by_id(self):
        dos = self.rester.get_dos_by_material_id("mp-2254")
        self.assertIsInstance(dos, CompleteDos)

    def test_get_bandstructure_by_material_id(self):
        bs = self.rester.get_bandstructure_by_material_id("mp-2254")
        self.assertIsInstance(bs, BandStructureSymmLine)

    def test_get_structures(self):
        structs = self.rester.get_structures("Mn3O4")
        self.assertTrue(len(structs) > 0)
        for s in structs:
            self.assertEqual(s.composition.reduced_formula, "Mn3O4")

    def test_get_entries(self):
        entries = self.rester.get_entries("TiO2")
        self.assertTrue(len(entries) > 1)
        for e in entries:
            self.assertEqual(e.composition.reduced_formula, "TiO2")

        entries = self.rester.get_entries("TiO2", inc_structure="final")
        self.assertTrue(len(entries) > 1)
        for e in entries:
            self.assertEqual(e.structure.composition.reduced_formula, "TiO2")

    def test_get_exp_entry(self):
        entry = self.rester.get_exp_entry("Fe2O3")
        self.assertEqual(entry.energy, -825.5)

    def test_submit_query_delete_snl(self):
        s = Structure([[5, 0, 0], [0, 5, 0], [0, 0, 5]], ["Fe"], [[0, 0, 0]])
        # d = self.rester.submit_snl(
        #     [s, s], remarks=["unittest"],
        #     authors="Test User <*****@*****.**>")
        # self.assertEqual(len(d), 2)
        # data = self.rester.query_snl({"about.remarks": "unittest"})
        # self.assertEqual(len(data), 2)
        # snlids = [d["_id"] for d in data]
        # self.rester.delete_snl(snlids)
        # data = self.rester.query_snl({"about.remarks": "unittest"})
        # self.assertEqual(len(data), 0)

    def test_get_stability(self):
        entries = self.rester.get_entries("Fe-O")
        modified_entries = []
        for entry in entries:
            # Create modified entries with energies that are 0.01eV higher
            # than the corresponding entries.
            if entry.composition.reduced_formula == "Fe2O3":
                modified_entries.append(
                    ComputedEntry(entry.composition,
                                  entry.uncorrected_energy + 0.01,
                                  parameters=entry.parameters,
                                  entry_id="mod_{}".format(entry.entry_id)))
        rest_ehulls = self.rester.get_stability(modified_entries)
        all_entries = entries + modified_entries
        compat = MaterialsProjectCompatibility()
        all_entries = compat.process_entries(all_entries)
        pd = PhaseDiagram(all_entries)
        a = PDAnalyzer(pd)
        for e in all_entries:
            if str(e.entry_id).startswith("mod"):
                for d in rest_ehulls:
                    if d["entry_id"] == e.entry_id:
                        data = d
                        break
                self.assertAlmostEqual(a.get_e_above_hull(e),
                                       data["e_above_hull"])
Esempio n. 54
0
 def test_get_materials_id_references(self):
     # nosetests pymatgen/matproj/tests/test_rest.py:MPResterTest.test_get_materials_id_references
     # self.rester points to rest/v2 by default which doesn't have the refs endpoint
     m = MPRester(endpoint="https://www.materialsproject.org/rest")
     data = m.get_materials_id_references('mp-123')
     self.assertTrue(len(data) > 1000)
Esempio n. 55
0
 def test_get_materials_id_references(self):
     # nosetests pymatgen/matproj/tests/test_rest.py:MPResterTest.test_get_materials_id_references
     # self.rester points to rest/v2 by default which doesn't have the refs endpoint
     m = MPRester(endpoint="https://www.materialsproject.org/rest")
     data = m.get_materials_id_references('mp-123')
     self.assertTrue(len(data) > 1000)
Esempio n. 56
0
        f.write(str(targets) + '\n')
        f.close()
    return


API_Key = 'pF2RrzEPyZmIsLST'
MaxAtoms = 160

PlasmonicData = pd.read_csv('CompoundDescriptors-Gap.csv',
                            index_col=False,
                            sep=',')  #input descriptor data file
#print(PlasmonicData)

EValFiles = np.atleast_1d(['CoulombEValsGap.csv'])

with MPRester(API_Key) as mp:  # Materials Project API imported

    for i in range(0, len(PlasmonicData)):
        print(i)
        MPName = 'mp-' + str(PlasmonicData['MPID'][i])
        StructDat = mp.query(criteria={"task_id": MPName},
                             properties=['structure', 'nsites'])
        nAtoms = int(StructDat[0]['nsites'])

        NuclearCharges = []
        for qq in range(0, nAtoms):
            current = str(StructDat[0]['structure'].sites[qq]._species)
            elem = ''.join(ii for ii in current if not ii.isdigit())
            NuclearCharges.append(mg.Element(elem).Z)

        CMat = np.zeros(MaxAtoms**2).reshape(MaxAtoms, MaxAtoms)
Esempio n. 57
0
        from bson import ObjectId

        cids = open(cids_file).read().splitlines()
        comps_cids = [(None, ObjectId(cid_str)) for cid_str in cids]
        if args.dev:
            raise ValueError("need full MPFile for on-the-fly analysis!")
    except (InvalidId, TypeError):
        from mpcontribs.io.mpfile import MPFile

        mpfile = MPFile.from_file(cids_file)  # TODO cid-only read mode?
        comps_cids = [(x[0], ObjectId(x[1])) for x in mpfile.get_identifiers()]

    # set up rester and PDF
    SITE = "http://localhost:8000"
    ENDPOINT, API_KEY = "{}/rest".format(SITE), os.environ.get("MAPI_KEY_LOC")
    mpr = MPRester(API_KEY, endpoint=ENDPOINT)
    merger = PdfFileMerger()

    # get all XAS/XMCD spectra
    if args.dev:
        from mpcontribs.webui.webui import app

        port = 5000 + random.randint(0, 999)
        url = "http://127.0.0.1:{0}/pdf?mpfile={1}".format(port, cids_file)
        # threading.Timer(1.25, lambda: webbrowser.open(url)).start()
        # app.run(port=port, debug=False)
        # TODO find way to automatically append to PDF
        # pdf = pdfkit.from_url(url, False)
        # merger.append(pdf)
    else:
        doc = {}
Esempio n. 58
0
import requests
import json
import numpy as np
import itertools
import pandas as pd
from __future__ import division

from pymatgen.phasediagram.pdanalyzer import PDAnalyzer
from pymatgen.matproj.rest import MPRester
from pymatgen.phasediagram.pdmaker import PhaseDiagram
from pymatgen.core.periodic_table import Element
from pymatgen.core.composition import Composition

API_key = 'NrBIvm9wt7Hq1fSD'  # Get API key from https://materialsproject.org/open
mp = MPRester(API_key)

elements = pd.read_table('elements.txt', delimiter="\t")  # elements data
elements.index = elements.symbol  # Convert the index as the elements symbols
formation_energies = pd.read_table('formation_energies.txt',
                                   delimiter="\t")  # formation energy data

# Create a List of proportions for the binary system

prop = np.arange(0.05, 1, 0.05)
p = np.around(prop, decimals=2)
prop = prop.tolist()

# In[26]:

# In[13]:
def get_material(query_info):
	try:
		#We copy the internals of the get_bandstructure_by_material_id method
		#to handle missing material ids
		with MPRester() as mp:
			if query_info["has_bandstructure"] == False:
				raise NoMaterialAtIDError

			#check if material is stable
			if query_info["e_above_hull"] > 0:
				return

			formula_numbers = query_info["anonymous_formula"]
			first_elem_num = formula_numbers["A"] if "A" in formula_numbers else 0
			second_elem_num = formula_numbers["B"] if "B" in formula_numbers else 0
			third_elem_num = formula_numbers["C"] if "C" in formula_numbers else 0 
			if (first_elem_num > SINGLE_SUBSCRIPT or second_elem_num > SINGLE_SUBSCRIPT 
				or third_elem_num > SINGLE_SUBSCRIPT or first_elem_num + second_elem_num + third_elem_num > TOTAL_SUBSCRIPT):
				return

			name = query_info["pretty_formula"]
			if ('Cd' in name) or ('Hg' in name) or ('Pb' in name) or ('Cr' in name): #check if material has Cd
				if PRINT_DEBUG:
					print "Material with index " + query_info["material_id"] + " contains prohibited material!"
				return

			banddata = mp.get_data(query_info['material_id'], prop="bandstructure")
			bandstruct = banddata[0]["bandstructure"]
				
			bandinfo = bandstruct.get_band_gap()
			bandgap = CORRECTION_SLOPE*bandinfo["energy"]+CORRECTION_OFFSET
			
			if PRINT_INFO:
				print "For " + name + ", we have " + ("a direct" if bandinfo["direct"] else "an indirect") + " band gap of " + str(bandgap) + " eV."

			if (bandstruct.is_metal()):
				return

			# Save information
			oxidizedstates = query_info['bv_structure'].get_primitive_structure()
			total_e = 0
			if(type(oxidizedstates.species[0]) is not periodic_table.Specie):
				return

			#TODO: Investigate how specie_and_occu differs?
			#For now, assume we don't don't
			for specie in oxidizedstates.species:
				if specie.Z > MAX_ALLOWED_ELEMENT:
					return
				num_electrons = specie.Z+specie.oxi_state
				#skip if beyond known elements. This actually works for ions with
				#no electrons (ie H^+ or He^2+)
				if(num_electrons <= 0 or num_electrons > MAX_DEFINED_ELEMENT):
					continue
				#This is a hack of sorts. We get the element that has the same number 
				#of electrons as our ion, and use that as the electronic structure
				orbitals = periodic_table.get_el_sp(int(num_electrons)).full_electronic_structure
				if len(orbitals) <= 1:
					continue
				index = -1
				max_orb_num = orbitals[index][0]
				#This will exclude d and higher electrons because they will never be the top
				#principal quantum number. We could also grab this directly to be safe
				while orbitals[index][0] == max_orb_num:
					total_e += orbitals[index][2]
					index -= 1

			N_VB = total_e/4
			N_CB = total_e/8
			# Calculate branch point energy (ebp) and correct
			ebp = calcEBP(bandstruct, name, N_VB, N_CB, PRINT_DEBUG)
			return {'name':name, 'vbm': -ebp, 'cbm': bandgap-ebp, 'bandinfo': bandinfo}

	except NoMaterialAtIDError:
		if PRINT_DEBUG:
			print "Material with index " + query_info["material_id"] + " does not exist!"

	except MPRestError:
		if PRINT_DEBUG:
			print "No band struct or density of states at index " + query_info["material_id"] + "!"
Esempio n. 60
0
def entry_data(mtnme_1, mtnme_2, direct_0, mprester_key):
    """
    Obtaining entry and ion data from local source. If the data cannot be
    found, it will do an HTTP request to the Materials Project database.

    Args:
        mtnme_1: Material 1
        mtnme_2: Material 2
        direct_0: Directory of entry database for binary systems
    """
    #| -  entry_data
    from pymatgen.matproj.rest import MPRester # Access species in MP
    import warnings; import json; from monty.json import MontyDecoder
    warnings.filterwarnings('ignore')    # Ignore errors related to HTTP request
    mpr = MPRester(mprester_key)    # REST api adaptor, INPUT

    try:
        direct_0 = direct_0        #INPUT#
        direct = direct_0+mtnme_1+'_'+mtnme_2+'/'
        entries = json.loads(open(direct+'mp_entries.txt','r').read(), cls=MontyDecoder)
        ion_dict_1 = json.loads(open(direct+'ion_data_1.txt','r').read())

        if not mtnme_1==mtnme_2:
            ion_dict_2 = json.loads(open(direct+'ion_data_2.txt','r').read())
    except:
        pass

################################################################################
    ## Obtains all entries in MP corresponding to input element, O and H
    if mtnme_1==mtnme_2:
        try:
            entries = entries
        except:
            print 'pd_make.entry_data - made http request line 64'
            entries = mpr.get_entries_in_chemsys([mtnme_1, 'O', 'H'])

        ## Dictionary of reference state:experimental formation energy
        try:
            ion_dict_1 = ion_dict_1
        except:
            print 'pd_make.entry_data - made http request line 69'
            ion_dict_1 = mpr._make_request('/pourbaix_diagram/reference_data/'+mtnme_1)
        out_dict = {"entries" : entries, "ion_dict_1" : ion_dict_1}
        return out_dict

    if not mtnme_1==mtnme_2:
        try:
            entries = entries
        except:
            print 'pd_make.entry_data - made http request - line 146'
            ## Obtains all entries in MP corresponding to input element, O and H
            entries = mpr.get_entries_in_chemsys([mtnme_1, mtnme_2, 'O', 'H'])
            ## Dictionary of reference state:experimental formation energy
        try:
            ion_dict_1 == ion_dict_1
            ion_dict_2 == ion_dict_2
        except:
            print 'pd_make.entry_data - made http request - line 154'
            ion_dict_1 = mpr._make_request('/pourbaix_diagram/reference_data/'+mtnme_1)
            ion_dict_2 = mpr._make_request('/pourbaix_diagram/reference_data/'+mtnme_2)
        out_dict = {"entries" : entries, "ion_dict_1" : ion_dict_1, "ion_dict_2" : ion_dict_2}
        return out_dict