Beispiel #1
0
def step2(**kwargs):
    """
    post process:
       get energies from the jobs in the previous step and 
       generate the phase diagram
    """
    chkfile = kwargs['checkpoint_files'][0]
    all_jobs = jobs_from_file(chkfile)
    entries = []
    # add endpoint data
    Al = Composition("Al1O0")
    energy_al = -3.36
    O = Composition("Al0O1")
    energy_o = -2.58
    entries.append(PDEntry(Al, energy_al))
    entries.append(PDEntry(O, energy_o))
    # get data and create entries
    for job in all_jobs:
        comp = job.vis.mplmp.structure.composition
        energy = job.final_energy
        entries.append(PDEntry(comp, energy))
    pd = PhaseDiagram(entries)
    plotter = PDPlotter(pd, show_unstable=True)
    plotter.write_image('Al_O_phasediagram.jpg')
    return None
Beispiel #2
0
def pd_plot(system='Ni-Nb'):

    object_file = pickle.load(open('form_en_gbsave_v25h', "rb"))
    output = []
    l = system.split('-')
    comb = []
    for i in range(len(l)):
        comb += itertools.combinations(l, i + 1)
    comb_list = [list(t) for t in comb]
    #  comb_list=['Zn','O','Zn-O']
    with MPRester("") as m:
        for i in comb_list:
            dd = '-'.join(i)
            print dd
            data = m.get_data(dd)
            for d in data:
                x = {}
                x['material_id'] = str(d['material_id'])
                structure = m.get_structure_by_material_id(x['material_id'])
                X = get_comp_descp(struct=structure)
                print "X", X
                pred = object_file.predict(X)
                print structure.composition.reduced_formula, pred[0], d[
                    'formation_energy_per_atom'], str(d['material_id'])
                output.append(
                    PDEntry(Composition(structure.composition),
                            float(pred[0])))
    pd = PhaseDiagram(output)
    print output
    plotter = PDPlotter(pd, show_unstable=True)
    name = str(system) + str('_phasediagram.png')
    plotter.write_image(name, image_format="png")
Beispiel #3
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"])
Beispiel #4
0
 def test_1d_pd(self):
     entry = PDEntry('H', 0)
     pd = PhaseDiagram([entry])
     pda = PDAnalyzer(pd)
     decomp, e = pda.get_decomp_and_e_above_hull(PDEntry('H', 1))
     self.assertAlmostEqual(e, 1)
     self.assertAlmostEqual(decomp[entry], 1.0)
Beispiel #5
0
    def extract_phase_diagram_info(self, MP_phase_diagram_json_data_filename):

        computed_entries = self._extract_MP_data(
            MP_phase_diagram_json_data_filename)
        processed_entries = self.compat.process_entries(computed_entries)

        pd = PhaseDiagram(processed_entries)
        self.phase_diagram_analyser = PDAnalyzer(pd)

        return
Beispiel #6
0
class PhaseDiagramTest(unittest.TestCase):
    def setUp(self):
        module_dir = os.path.dirname(os.path.abspath(__file__))
        (self.elements, self.entries) = \
            PDEntryIO.from_csv(os.path.join(module_dir, "pdentries_test.csv"))
        self.pd = PhaseDiagram(self.entries)

    def test_init(self):
        #Ensure that a bad set of entries raises a PD error. Remove all Li
        #from self.entries.
        entries = filter(
            lambda e: (not e.composition.is_element) or e.composition.elements[
                0] != Element("Li"), self.entries)
        self.assertRaises(PhaseDiagramError, PhaseDiagram, entries,
                          self.elements)

    def test_stable_entries(self):
        stable_formulas = [
            ent.composition.reduced_formula for ent in self.pd.stable_entries
        ]
        expected_stable = [
            "Fe2O3", "Li5FeO4", "LiFeO2", "Fe3O4", "Li", "Fe", "Li2O", "O2",
            "FeO"
        ]
        for formula in expected_stable:
            self.assertTrue(formula in stable_formulas,
                            formula + " not in stable entries!")

    def test_get_formation_energy(self):
        stable_formation_energies = {
            ent.composition.reduced_formula: self.pd.get_form_energy(ent)
            for ent in self.pd.stable_entries
        }
        expected_formation_energies = {
            'Li5FeO4': -164.8117344866667,
            'Li2O2': -14.119232793333332,
            'Fe2O3': -16.574164339999996,
            'FeO': -5.7141519966666685,
            'Li': 0.0,
            'LiFeO2': -7.732752316666666,
            'Li2O': -6.229303868333332,
            'Fe': 0.0,
            'Fe3O4': -22.565714456666683,
            'Li2FeO3': -45.67166036000002,
            'O2': 0.0
        }
        for formula, energy in expected_formation_energies.items():
            self.assertAlmostEqual(energy, stable_formation_energies[formula],
                                   7)

    def test_all_entries_hulldata(self):
        self.assertEqual(len(self.pd.all_entries_hulldata), 492)

    def test_str(self):
        self.assertIsNotNone(str(self.pd))
Beispiel #7
0
    def test_planar_inputs(self):
        e1 = PDEntry('H', 0)
        e2 = PDEntry('He', 0)
        e3 = PDEntry('Li', 0)
        e4 = PDEntry('Be', 0)
        e5 = PDEntry('B', 0)
        e6 = PDEntry('Rb', 0)

        pd = PhaseDiagram([e1, e2, e3, e4, e5, e6],
                          map(Element, ['Rb', 'He', 'B', 'Be', 'Li', 'H']))

        self.assertEqual(len(pd.facets), 1)
Beispiel #8
0
    def __init__(self, entries, working_ion_entry):
        """
        Create a new InsertionElectrode.

        Args:
            entries:
                A list of ComputedStructureEntries (or subclasses) representing
                the different topotactic states of the battery, e.g. TiO2 and
                LiTiO2.
            working_ion_entry:
                A single ComputedEntry or PDEntry representing the element that
                carries charge across the battery, e.g. Li.
        """

        self._entries = entries
        self._working_ion = working_ion_entry.composition.elements[0]
        self._working_ion_entry = working_ion_entry

        #Prepare to make phase diagram: determine elements and set their energy
        #to be very high
        elements = set()
        map(elements.update, [entry.composition.elements for entry in entries])

        #Set an artificial energy for each element for convex hull generation
        element_energy = max([entry.energy_per_atom for entry in entries]) + 10

        pdentries = []
        pdentries.extend(entries)
        pdentries.extend(
            [PDEntry(Composition({el: 1}), element_energy) for el in elements])

        #Make phase diagram to determine which entries are stable vs. unstable
        pd = PhaseDiagram(pdentries)

        lifrac = lambda e: e.composition.get_atomic_fraction(self._working_ion)

        #stable entries ordered by amount of Li asc
        self._stable_entries = tuple(
            sorted([e for e in pd.stable_entries if e in entries], key=lifrac))

        #unstable entries ordered by amount of Li asc
        self._unstable_entries = tuple(
            sorted([e for e in pd.unstable_entries if e in entries],
                   key=lifrac))

        #create voltage pairs
        self._vpairs = tuple([
            InsertionVoltagePair(self._stable_entries[i],
                                 self._stable_entries[i + 1],
                                 working_ion_entry)
            for i in range(len(self._stable_entries) - 1)
        ])
Beispiel #9
0
    def test_planar_inputs(self):
        e1 = PDEntry('H', 0)
        e2 = PDEntry('HLiB', 0)
        e3 = PDEntry('He', 0)
        e4 = PDEntry('Li', 0)
        e5 = PDEntry('Be', 0)
        e6 = PDEntry('B', 0)
        e7 = PDEntry('HBe', 0)
        e8 = PDEntry('Rb', 0)

        pd = PhaseDiagram([e1, e2, e3, e4, e5, e6, e7, e8],
                          map(Element,
                              ['Rb', 'He', 'B', 'Be', 'Li', 'He', 'H']))
Beispiel #10
0
    def test_dim1(self):
        #Ensure that dim 1 PDs can eb generated.
        for el in ["Li", "Fe", "O2"]:
            entries = [
                e for e in self.entries if e.composition.reduced_formula == el
            ]
            pd = PhaseDiagram(entries)
            self.assertEqual(len(pd.stable_entries), 1)

            a = PDAnalyzer(pd)
            for e in entries:
                decomp, ehull = a.get_decomp_and_e_above_hull(e)
                self.assertGreaterEqual(ehull, 0)
            plotter = PDPlotter(pd)
            lines, stable_entries, unstable_entries = plotter.pd_plot_data
            self.assertEqual(lines[0][1], [0, 0])
Beispiel #11
0
class PhaseDiagramTest(unittest.TestCase):

    def setUp(self):
        module_dir = os.path.dirname(os.path.abspath(__file__))
        (self.elements, self.entries) = \
            PDEntryIO.from_csv(os.path.join(module_dir, "pdentries_test.csv"))
        self.pd = PhaseDiagram(self.entries)

    def test_init(self):
        #Ensure that a bad set of entries raises a PD error. Remove all Li
        #from self.entries.
        entries = filter(lambda e: (not e.composition.is_element) or
                         e.composition.elements[0] != Element("Li"),
                         self.entries)
        self.assertRaises(PhaseDiagramError, PhaseDiagram, entries,
                          self.elements)

    def test_stable_entries(self):
        stable_formulas = [ent.composition.reduced_formula
                           for ent in self.pd.stable_entries]
        expected_stable = ["Fe2O3", "Li5FeO4", "LiFeO2", "Fe3O4", "Li", "Fe",
                           "Li2O", "O2", "FeO"]
        for formula in expected_stable:
            self.assertTrue(formula in stable_formulas,
                            formula + " not in stable entries!")

    def test_get_formation_energy(self):
        stable_formation_energies = {ent.composition.reduced_formula:
                                     self.pd.get_form_energy(ent)
                                     for ent in self.pd.stable_entries}
        expected_formation_energies = {'Li5FeO4': -164.8117344866667,
                                       'Li2O2': -14.119232793333332,
                                       'Fe2O3': -16.574164339999996,
                                       'FeO': -5.7141519966666685, 'Li': 0.0,
                                       'LiFeO2': -7.732752316666666,
                                       'Li2O': -6.229303868333332,
                                       'Fe': 0.0, 'Fe3O4': -22.565714456666683,
                                       'Li2FeO3': -45.67166036000002,
                                       'O2': 0.0}
        for formula, energy in expected_formation_energies.items():
            self.assertAlmostEqual(energy, stable_formation_energies[formula],
                                   7)
    def test_all_entries_hulldata(self):
        self.assertEqual(len(self.pd.all_entries_hulldata), 492)

    def test_str(self):
        self.assertIsNotNone(str(self.pd))
Beispiel #12
0
    def from_composition_and_entries(comp,
                                     entries_in_chemsys,
                                     working_ion_symbol="Li"):
        """
        Convenience constructor to make a ConversionElectrode from a
        composition and all entries in a chemical system.

        Args:
            comp: Starting composition for ConversionElectrode, e.g.,
                Composition("FeF3")
            entries_in_chemsys: Sequence containing all entries in a
               chemical system. E.g., all Li-Fe-F containing entries.
            working_ion_symbol: Element symbol of working ion. Defaults to Li.
        """
        pd = PhaseDiagram(entries_in_chemsys)
        return ConversionElectrode.from_composition_and_pd(
            comp, pd, working_ion_symbol)
Beispiel #13
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
Beispiel #14
0
class PhaseDiagramTest(unittest.TestCase):

    def setUp(self):
        module_dir = os.path.dirname(os.path.abspath(__file__))
        (self.elements, self.entries) = PDEntryIO.from_csv(os.path.join(module_dir,"pdentries_test.csv"))
        self.pd = PhaseDiagram(self.entries)
        
    def test_stable_entries(self):
        stable_formulas = [ent.composition.reduced_formula for ent in self.pd.stable_entries]
        expected_stable = ["Fe2O3", "Li5FeO4", "LiFeO2", "Fe3O4", "Li", "Fe", "Li2O", "O2", "FeO"]
        for formula in expected_stable:
            self.assertTrue(formula in stable_formulas, formula + " not in stable entries!")
    
    def test_get_formation_energy(self):
        stable_formation_energies = {ent.composition.reduced_formula:self.pd.get_form_energy(ent) for ent in self.pd.stable_entries}
        expected_formation_energies = {'Li5FeO4': -164.8117344866667, 'Li2O2': -14.119232793333332, 'Fe2O3': -16.574164339999996, 'FeO': -5.7141519966666685, 'Li': 0.0, 'LiFeO2': -7.732752316666666, 'Li2O': -6.229303868333332, 'Fe': 0.0, 'Fe3O4': -22.565714456666683, 'Li2FeO3': -45.67166036000002, 'O2': 0.0}
        for formula, energy in expected_formation_energies.items():
            self.assertAlmostEqual(energy, stable_formation_energies[formula], 7, "Calculated formation for " + formula + " is not correct!")
Beispiel #15
0
    def get_equilibrium_reaction_energy(self, entry):
        """
        Provides the reaction energy of a stable entry from the neighboring
        equilibrium stable entries (also known as the inverse distance to
        hull).

        Args:
            entry: A PDEntry like object

        Returns:
            Equilibrium reaction energy of entry. Stable entries should have
            equilibrium reaction energy <= 0.
        """
        if entry not in self._pd.stable_entries:
            raise ValueError("Equilibrium reaction energy is available only "
                             "for stable entries.")
        if entry.is_element:
            return 0
        entries = [e for e in self._pd.stable_entries if e != entry]
        modpd = PhaseDiagram(entries, self._pd.elements)
        analyzer = PDAnalyzer(modpd)
        return analyzer.get_decomp_and_e_above_hull(entry,
                                                    allow_negative=True)[1]
Beispiel #16
0
    def get_lowest_decomposition(self, composition):
        """
        Get the decomposition leading to lowest cost

        Args:
            composition:
                Composition as a pymatgen.core.structure.Composition
        Returns:
            Decomposition as a dict of {Entry: amount}
        """

        entries_list = []
        elements = [e.symbol for e in composition.elements]
        for i in range(len(elements)):
            for combi in itertools.combinations(elements, i + 1):
                chemsys = [Element(e) for e in combi]
                x = self.costdb.get_entries(chemsys)
                entries_list.extend(x)
        try:
            pd = PhaseDiagram(entries_list)
            return PDAnalyzer(pd).get_decomposition(composition)
        except IndexError:
            raise ValueError("Error during PD building; most likely, "
                             "cost data does not exist!")
Beispiel #17
0
                criteria=criteria,
                projection=projection,
                collection="compositions",
                contributor_only=False,
            )[0]
            # append spectra to output PDF
            plotly_urls = doc[cid]["LBNL"][str(cid)]["plotly_urls"]
            for plotly_url in plotly_urls:
                image_bytes = requests.get("{}.pdf".format(plotly_url)).content
                merger.append(StringIO(image_bytes))

    # get phase diagram from MP and append to PDF
    chemsys = ["Co", "Fe", "V"]  # ["Ni", "Fe", "Pt"] # alphabetic
    cmap = ["Reds", "Blues", "Greens"]
    entries = mpr.get_entries_in_chemsys(chemsys)
    pd = PhaseDiagram(entries)
    plotter = PDPlotter(pd)

    # grid
    gx, gy = [], []
    n = 20
    fn = float(n)
    for i in range(0, n, 1):
        for k in range(n - i + 1, 0, -1):
            j = n + 1 - i - k
            x0, x1, x2 = i / fn, k / fn, j / fn
            gx.append(x0 +
                      x2 / 2.0)  # NOTE x0 might need to be replace with x1
            gy.append(x2 * math.sqrt(3.0) / 2.0)
    grid_triang = tri.Triangulation(gx, gy)
Beispiel #18
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
Beispiel #19
0
 def setUp(self):
     module_dir = os.path.dirname(os.path.abspath(__file__))
     (self.elements, self.entries) = \
         PDEntryIO.from_csv(os.path.join(module_dir, "pdentries_test.csv"))
     self.pd = PhaseDiagram(self.entries)
Beispiel #20
0
 def setUp(self):
     (elements, entries) = PDEntryIO.from_csv(
         os.path.join(module_dir, "pdentries_test.csv"))
     self.pd = PhaseDiagram(entries)
     self.plotter = PDPlotter(self.pd)
Beispiel #21
0
 def setUp(self):
     module_dir = os.path.dirname(os.path.abspath(__file__))
     (elements, entries) = PDEntryIO.from_csv(
         os.path.join(module_dir, "pdentries_test.csv"))
     self.pd = PhaseDiagram(entries)
     self.analyzer = PDAnalyzer(self.pd)
Beispiel #22
0
class PhaseDiagramTest(unittest.TestCase):
    def setUp(self):
        module_dir = os.path.dirname(os.path.abspath(__file__))
        (self.elements, self.entries) = \
            PDEntryIO.from_csv(os.path.join(module_dir, "pdentries_test.csv"))
        self.pd = PhaseDiagram(self.entries)

    def test_init(self):
        #Ensure that a bad set of entries raises a PD error. Remove all Li
        #from self.entries.
        entries = filter(
            lambda e: (not e.composition.is_element) or e.composition.elements[
                0] != Element("Li"), self.entries)
        self.assertRaises(PhaseDiagramError, PhaseDiagram, entries,
                          self.elements)

    def test_dim1(self):
        #Ensure that dim 1 PDs can eb generated.
        for el in ["Li", "Fe", "O2"]:
            entries = [
                e for e in self.entries if e.composition.reduced_formula == el
            ]
            pd = PhaseDiagram(entries)
            self.assertEqual(len(pd.stable_entries), 1)

            a = PDAnalyzer(pd)
            for e in entries:
                decomp, ehull = a.get_decomp_and_e_above_hull(e)
                self.assertGreaterEqual(ehull, 0)
            plotter = PDPlotter(pd)
            lines, stable_entries, unstable_entries = plotter.pd_plot_data
            self.assertEqual(lines[0][1], [0, 0])

    def test_stable_entries(self):
        stable_formulas = [
            ent.composition.reduced_formula for ent in self.pd.stable_entries
        ]
        expected_stable = [
            "Fe2O3", "Li5FeO4", "LiFeO2", "Fe3O4", "Li", "Fe", "Li2O", "O2",
            "FeO"
        ]
        for formula in expected_stable:
            self.assertTrue(formula in stable_formulas,
                            formula + " not in stable entries!")

    def test_get_formation_energy(self):
        stable_formation_energies = {
            ent.composition.reduced_formula: self.pd.get_form_energy(ent)
            for ent in self.pd.stable_entries
        }
        expected_formation_energies = {
            'Li5FeO4': -164.8117344866667,
            'Li2O2': -14.119232793333332,
            'Fe2O3': -16.574164339999996,
            'FeO': -5.7141519966666685,
            'Li': 0.0,
            'LiFeO2': -7.732752316666666,
            'Li2O': -6.229303868333332,
            'Fe': 0.0,
            'Fe3O4': -22.565714456666683,
            'Li2FeO3': -45.67166036000002,
            'O2': 0.0
        }
        for formula, energy in expected_formation_energies.items():
            self.assertAlmostEqual(energy, stable_formation_energies[formula],
                                   7)

    def test_all_entries_hulldata(self):
        self.assertEqual(len(self.pd.all_entries_hulldata), 492)

    def test_planar_inputs(self):
        e1 = PDEntry('H', 0)
        e2 = PDEntry('He', 0)
        e3 = PDEntry('Li', 0)
        e4 = PDEntry('Be', 0)
        e5 = PDEntry('B', 0)
        e6 = PDEntry('Rb', 0)

        pd = PhaseDiagram([e1, e2, e3, e4, e5, e6],
                          map(Element, ['Rb', 'He', 'B', 'Be', 'Li', 'H']))

        self.assertEqual(len(pd.facets), 1)

    def test_str(self):
        self.assertIsNotNone(str(self.pd))
 def setUp(self):
     module_dir = os.path.dirname(os.path.abspath(__file__))
     (self.elements, self.entries) = \
         PDEntryIO.from_csv(os.path.join(module_dir, "pdentries_test.csv"))
     self.pd = PhaseDiagram(self.entries)
class PhaseDiagramTest(unittest.TestCase):

    def setUp(self):
        module_dir = os.path.dirname(os.path.abspath(__file__))
        (self.elements, self.entries) = \
            PDEntryIO.from_csv(os.path.join(module_dir, "pdentries_test.csv"))
        self.pd = PhaseDiagram(self.entries)

    def test_init(self):
        #Ensure that a bad set of entries raises a PD error. Remove all Li
        #from self.entries.
        entries = filter(lambda e: (not e.composition.is_element) or
                         e.composition.elements[0] != Element("Li"),
                         self.entries)
        self.assertRaises(PhaseDiagramError, PhaseDiagram, entries,
                          self.elements)

    def test_dim1(self):
        #Ensure that dim 1 PDs can eb generated.
        for el in ["Li", "Fe", "O2"]:
            entries = [e for e in self.entries
                       if e.composition.reduced_formula == el]
            pd = PhaseDiagram(entries)
            self.assertEqual(len(pd.stable_entries), 1)

            a = PDAnalyzer(pd)
            for e in entries:
                decomp, ehull = a.get_decomp_and_e_above_hull(e)
                self.assertGreaterEqual(ehull, 0)
            plotter = PDPlotter(pd)
            lines, stable_entries, unstable_entries = plotter.pd_plot_data
            self.assertEqual(lines[0][1], [0, 0])

    def test_stable_entries(self):
        stable_formulas = [ent.composition.reduced_formula
                           for ent in self.pd.stable_entries]
        expected_stable = ["Fe2O3", "Li5FeO4", "LiFeO2", "Fe3O4", "Li", "Fe",
                           "Li2O", "O2", "FeO"]
        for formula in expected_stable:
            self.assertTrue(formula in stable_formulas,
                            formula + " not in stable entries!")

    def test_get_formation_energy(self):
        stable_formation_energies = {ent.composition.reduced_formula:
                                     self.pd.get_form_energy(ent)
                                     for ent in self.pd.stable_entries}
        expected_formation_energies = {'Li5FeO4': -164.8117344866667,
                                       'Li2O2': -14.119232793333332,
                                       'Fe2O3': -16.574164339999996,
                                       'FeO': -5.7141519966666685, 'Li': 0.0,
                                       'LiFeO2': -7.732752316666666,
                                       'Li2O': -6.229303868333332,
                                       'Fe': 0.0, 'Fe3O4': -22.565714456666683,
                                       'Li2FeO3': -45.67166036000002,
                                       'O2': 0.0}
        for formula, energy in expected_formation_energies.items():
            self.assertAlmostEqual(energy, stable_formation_energies[formula],
                                   7)
    def test_all_entries_hulldata(self):
        self.assertEqual(len(self.pd.all_entries_hulldata), 492)

    def test_planar_inputs(self):
        e1 = PDEntry('H',    0)
        e2 = PDEntry('HLiB', 0)
        e3 = PDEntry('He',   0)
        e4 = PDEntry('Li',   0)
        e5 = PDEntry('Be',   0)
        e6 = PDEntry('B',    0)
        e7 = PDEntry('HBe',  0)
        e8 = PDEntry('Rb',   0)

        pd = PhaseDiagram([e1, e2, e3, e4, e5, e6, e7, e8],
                          map(Element, ['Rb', 'He', 'B', 'Be','Li', 'He', 'H']))


    def test_str(self):
        self.assertIsNotNone(str(self.pd))
Beispiel #25
0
def material_load_binary(d, sep='-', p=prop):
    return_data = []

    d = d.split(sep)

    # Create a phase diagram object for the following system:
    entry = mp.get_entries_in_chemsys(
        [d[0], d[1]])  # gets the entries of the chemical system
    pd = PhaseDiagram(entry)  # creates a phasediagram object
    pd_analyse = PDAnalyzer(pd)  # creates a phase Diagram analysis object

    # Get the features for various proportions Using the get_hull_energy method;
    # (Need to add documentation)
    for i in range(0, len(p)):
        temp_data = {}
        prop_a = p[i]
        prop_b = p[-(i + 1)]
        try:
            temp_data['system'] = d[0] + '-' + d[1]
            temp_data['A'] = d[0]
            temp_data['B'] = d[1]
            temp_data[d[0] + '_prop'] = prop_a
            temp_data[d[1] + '_prop'] = prop_b
            temp_data['formation_energy'] = pd_analyse.get_hull_energy(
                Composition.from_dict({
                    d[0]: prop_a,
                    d[1]: prop_b
                }))

            # Element Property extraction

            temp_data['avg_atomic_mass'] = prop_a * elements.loc[
                d[0]].mass + prop_b * elements.loc[d[1]].mass
            temp_data['avg_row'] = prop_a * elements.loc[
                d[0]].period + prop_b * elements.loc[d[1]].period
            temp_data['avg_col'] = prop_a * elements.loc[
                d[0]].group + prop_b * elements.loc[d[1]].group
            temp_data['max_z_diff'] = abs(
                elements.loc[d[0]].z -
                elements.loc[d[1]].z)  # Max Difference in atomic number
            temp_data['avg_z'] = prop_a * elements.loc[
                d[0]].z + prop_b * elements.loc[d[1]].z
            temp_data['max_radius_diff'] = abs(
                elements.loc[d[0]].atomic_radii -
                elements.loc[d[1]].atomic_radii
            )  # Max Difference in atomic radius
            temp_data['avg_radius'] = prop_a * elements.loc[
                d[0]].atomic_radii + prop_b * elements.loc[d[1]].atomic_radii
            temp_data['max_en_diff'] = abs(
                elements.loc[d[0]].electronegativity -
                elements.loc[d[1]].electronegativity
            )  # Max Difference in electronegativity
            temp_data['avg_en'] = prop_a * elements.loc[
                d[0]].electronegativity + prop_b * elements.loc[d[
                    1]].electronegativity  # Avg Difference in electronegativity
            temp_data['avg_s_elec'] = prop_a * elements.loc[
                d[0]].s_elec + prop_b * elements.loc[d[1]].s_elec
            temp_data['avg_p_elec'] = prop_a * elements.loc[
                d[0]].p_elec + prop_b * elements.loc[d[1]].p_elec
            temp_data['avg_d_elec'] = prop_a * elements.loc[
                d[0]].d_elec + prop_b * elements.loc[d[1]].d_elec
            temp_data['avg_f_elec'] = prop_a * elements.loc[
                d[0]].f_elec + prop_b * elements.loc[d[1]].f_elec

            temp_sum = temp_data['avg_s_elec'] + temp_data[
                'avg_p_elec'] + temp_data['avg_d_elec'] + temp_data[
                    'avg_f_elec']

            temp_data['prop_s_elec'] = temp_data['avg_s_elec'] / temp_sum
            temp_data['prop_p_elec'] = temp_data['avg_p_elec'] / temp_sum
            temp_data['prop_d_elec'] = temp_data['avg_d_elec'] / temp_sum
            temp_data['prop_f_elec'] = temp_data['avg_f_elec'] / temp_sum

            return_data.append(temp_data)
        except:
            pass
    return return_data, temp_data['system']