Esempio n. 1
0
    def setUp(self):
        warnings.simplefilter("ignore")
        self.compat = MITCompatibility(check_potcar_hash=True)
        self.ggacompat = MITCompatibility("GGA", check_potcar_hash=True)
        self.entry_O = ComputedEntry(
            'Fe2O3', -1, 0.0,
            parameters={'is_hubbard': True,
                        'hubbards': {'Fe': 4.0, 'O': 0},
                        'run_type': 'GGA+U',
                        'potcar_spec': [{'titel':'PAW_PBE Fe 06Sep2000',
                                         'hash': '9530da8244e4dac17580869b4adab115'},
                                        {'titel': 'PAW_PBE O 08Apr2002',
                                         'hash': '7a25bc5b9a5393f46600a4939d357982'}]})

        self.entry_F = ComputedEntry(
            'FeF3', -2, 0.0,
            parameters={'is_hubbard': True,
                        'hubbards': {'Fe': 4.0, 'F': 0},
                        'run_type': 'GGA+U',
                        'potcar_spec': [{'titel':'PAW_PBE Fe 06Sep2000',
                                         'hash': '9530da8244e4dac17580869b4adab115'},
                                        {'titel': 'PAW_PBE F 08Apr2002',
                                         'hash': '180141c33d032bfbfff30b3bea9d23dd'}]})
        self.entry_S = ComputedEntry(
            'FeS2', -2, 0.0,
            parameters={'is_hubbard': True,
                        'hubbards': {'Fe': 1.9, 'S': 0},
                        'run_type': 'GGA+U',
                        'potcar_spec': [{'titel':'PAW_PBE Fe 06Sep2000',
                                            'hash': '9530da8244e4dac17580869b4adab115'},
                                           {'titel': 'PAW_PBE S 08Apr2002',
                                            'hash': 'd368db6899d8839859bbee4811a42a88'}]})
Esempio n. 2
0
    def test_U_value(self):
        # MIT should have a U value for Fe containing sulfides
        self.assertIsNotNone(self.compat.process_entry(self.entry_S))

        # MIT should not have a U value for Ni containing sulfides
        entry = ComputedEntry(
            'NiS2', -2, 0.0,
            parameters={'is_hubbard': True,
                        'hubbards': {'Ni': 1.9, 'S': 0},
                        'run_type': 'GGA+U',
                        'potcar_spec': [{'titel':'PAW_PBE Ni 06Sep2000',
                                            'hash': '653f5772e68b2c7fd87ffd1086c0d710'},
                                           {'titel': 'PAW_PBE S 08Apr2002',
                                            'hash': 'd368db6899d8839859bbee4811a42a88'}]})

        self.assertIsNone(self.compat.process_entry(entry))

        entry = ComputedEntry(
            'NiS2', -2, 0.0,
            parameters={'is_hubbard': True,
                        'hubbards': None,
                        'run_type': 'GGA',
                        'potcar_spec': [{'titel':'PAW_PBE Ni 06Sep2000',
                                            'hash': '653f5772e68b2c7fd87ffd1086c0d710'},
                                           {'titel': 'PAW_PBE S 08Apr2002',
                                            'hash': 'd368db6899d8839859bbee4811a42a88'}]})

        self.assertIsNotNone(self.ggacompat.process_entry(entry))
Esempio n. 3
0
    def test_process_entry(self):
        #Correct parameters
        self.assertIsNotNone(self.compat.process_entry(self.entry1))
        self.assertIsNone(self.ggacompat.process_entry(self.entry1))

        #Correct parameters
        entry = ComputedEntry(
            'Fe2O3', -1, 0.0,
            parameters={'is_hubbard': False, "hubbards": {}, 'run_type': 'GGA',
                        'potcar_spec': [{'titel':'PAW_PBE Fe_pv 06Sep2000',
                                         'hash': '994537de5c4122b7f1b77fb604476db4'},
                                        {'titel': 'PAW_PBE O 08Apr2002',
                                         'hash': '7a25bc5b9a5393f46600a4939d357982'}]})
        self.assertIsNone(self.compat.process_entry(entry))
        self.assertIsNotNone(self.ggacompat.process_entry(entry))

        entry = ComputedEntry(
            'Fe2O3', -1, 0.0,
            parameters={'is_hubbard': True, 'hubbards': {'Fe': 5.3, 'O': 0},
                        'run_type': 'GGA+U',
                        'potcar_spec': [{'titel':'PAW_PBE Fe_pv 06Sep2000',
                                         'hash': '994537de5c4122b7f1b77fb604476db4'},
                                        {'titel': 'PAW_PBE O 08Apr2002',
                                         'hash': '7a25bc5b9a5393f46600a4939d357982'}]})
        self.assertIsNotNone(self.compat.process_entry(entry))
Esempio n. 4
0
    def test_same_potcar_symbol(self):
        # Same symbol different hash thus a different potcar
        #Correct Hash Correct Symbol
        entry = ComputedEntry(
            'Fe2O3', -1, 0.0,
            parameters={'is_hubbard': True,
                        'hubbards': {'Fe': 4.0, 'O': 0},
                        'run_type': 'GGA+U',
                        'potcar_spec': [{'titel':'PAW_PBE Fe 06Sep2000',
                                         'hash': '9530da8244e4dac17580869b4adab115'},
                                        {'titel': 'PAW_PBE O 08Apr2002',
                                         'hash': '7a25bc5b9a5393f46600a4939d357982'}]})
        #Incorrect Hash Correct Symbol
        entry2 = ComputedEntry(
            'Fe2O3', -1, 0.0,
            parameters={'is_hubbard': True,
                        'hubbards': {'Fe': 4.0, 'O': 0},
                        'run_type': 'GGA+U',
                        'potcar_spec': [{'titel':'PAW_PBE Fe 06Sep2000',
                                         'hash': 'DifferentHash'},
                                        {'titel': 'PAW_PBE O 08Apr2002',
                                         'hash': '7a25bc5b9a5393f46600a4939d357982'}]})

        compat = MITCompatibility()
        self.assertEqual(len(compat.process_entries([entry, entry2])), 2)
        self.assertEqual(len(self.compat.process_entries([entry, entry2])), 1)
Esempio n. 5
0
    def test_wrong_U_value(self):
        #Wrong U value
        entry = ComputedEntry(
            'Fe2O3', -1, 0.0,
            parameters={'is_hubbard': True,
                        'hubbards': {'Fe': 5.2, 'O': 0},
                        'run_type': 'GGA+U',
                        'potcar_spec': [{'titel':'PAW_PBE Fe 06Sep2000',
                                         'hash': '9530da8244e4dac17580869b4adab115'},
                                        {'titel': 'PAW_PBE O 08Apr2002',
                                         'hash': '7a25bc5b9a5393f46600a4939d357982'}]})

        self.assertIsNone(self.compat.process_entry(entry))

        #GGA run
        entry = ComputedEntry(
            'Fe2O3', -1, 0.0,
            parameters={'is_hubbard': False,
                        'hubbards': None,
                        'run_type': 'GGA',
                        'potcar_spec': [{'titel':'PAW_PBE Fe 06Sep2000',
                                         'hash': '9530da8244e4dac17580869b4adab115'},
                                        {'titel': 'PAW_PBE O 08Apr2002',
                                         'hash': '7a25bc5b9a5393f46600a4939d357982'}]})
        self.assertIsNone(self.compat.process_entry(entry))
        self.assertIsNotNone(self.ggacompat.process_entry(entry))
 def setUp(self):
     self.entry = ComputedEntry(vasprun.final_structure.composition,
                                vasprun.final_energy,
                                parameters=vasprun.incar)
     self.entry2 = ComputedEntry({"Fe": 2, "O": 3}, 2.3)
     self.entry3 = ComputedEntry("Fe2O3", 2.3)
     self.entry4 = ComputedEntry("Fe2O3", 2.3, entry_id=1)
Esempio n. 7
0
def get_hull_distance(competing_phase_directory='../competing_phases'):
    """
    Calculate the material's distance to the thermodynamic hull,
    based on species in the Materials Project database.

    Args:
        competing_phase_directory (str): absolute or relative path
            to the location where your competing phases have been
            relaxed. The default expectation is that they are stored
            in a directory named 'competing_phases' at the same level
            as your material's relaxation directory.
    Returns:
        float. distance (eV/atom) between the material and the
            hull.
    """

    finished_competitors = {}
    original_directory = os.getcwd()
    # Determine which competing phases have been relaxed in the current
    # framework and store them in a dictionary ({formula: entry}).
    if os.path.isdir(competing_phase_directory):
        os.chdir(competing_phase_directory)
        for comp_dir in [
                dir for dir in os.listdir(os.getcwd())
                if os.path.isdir(dir) and is_converged(dir)
        ]:
            vasprun = Vasprun('{}/vasprun.xml'.format(comp_dir))
            composition = vasprun.final_structure.composition
            energy = vasprun.final_energy
            finished_competitors[comp_dir] = ComputedEntry(composition, energy)
        os.chdir(original_directory)
    else:
        raise ValueError('Competing phase directory does not exist.')

    composition = Structure.from_file('POSCAR').composition
    try:
        energy = Vasprun('vasprun.xml').final_energy
    except:
        raise ValueError(
            'This directory does not have a converged vasprun.xml')
    my_entry = ComputedEntry(composition, energy)  # 2D material
    entries = MPR.get_entries_in_chemsys([elt.symbol for elt in composition])

    # If the energies of competing phases have been calculated in
    # the current framework, put them in the phase diagram instead
    # of the MP energies.
    for i in range(len(entries)):
        formula = entries[i].composition.reduced_formula
        if formula in finished_competitors:
            entries[i] = finished_competitors[formula]
        else:
            entries[i] = ComputedEntry(entries[i].composition, 100)

    entries.append(my_entry)  # 2D material

    pda = PDAnalyzer(PhaseDiagram(entries))
    decomp = pda.get_decomp_and_e_above_hull(my_entry, allow_negative=True)

    return decomp[1]
def mp_query_mock(mocker):
    mock = mocker.patch(
        "pydefect.cli.vasp.make_composition_energies_from_mp.MpEntries")
    mock.return_value.materials = \
        [ComputedEntry(Composition("O8"), -39.58364375, entry_id="mp-1"),
         ComputedEntry(Composition("Mg3"), -4.79068775, entry_id="mp-2"),
         ComputedEntry(Composition("Mg1O1"), -11.96742144, entry_id="mp-3")]
    return mock
Esempio n. 9
0
    def __init__(self,
                 entries,
                 comp_dict=None,
                 conc_dict=None,
                 filter_multielement=False):
        # Get non-OH elements
        pbx_elts = set(
            itertools.chain.from_iterable(
                [entry.composition.elements for entry in entries]))
        pbx_elts = list(pbx_elts - elements_HO)

        # Set default conc/comp dicts
        if not comp_dict:
            comp_dict = {elt.symbol: 1. / len(pbx_elts) for elt in pbx_elts}
        if not conc_dict:
            conc_dict = {elt.symbol: 1e-6 for elt in pbx_elts}

        self._elt_comp = comp_dict
        self.pourbaix_elements = pbx_elts

        solid_entries = [
            entry for entry in entries if entry.phase_type == "Solid"
        ]
        ion_entries = [entry for entry in entries if entry.phase_type == "Ion"]

        for entry in ion_entries:
            ion_elts = list(set(entry.composition.elements) - elements_HO)
            if len(ion_elts) != 1:
                raise ValueError("Elemental concentration not compatible "
                                 "with multi-element ions")
            entry.conc = conc_dict[ion_elts[0].symbol]

        if not len(solid_entries + ion_entries) == len(entries):
            raise ValueError("All supplied entries must have a phase type of "
                             "either \"Solid\" or \"Ion\"")

        self._unprocessed_entries = entries

        if len(comp_dict) > 1:
            self._multielement = True
            if filter_multielement:
                # Add two high-energy H/O entries that ensure the hull
                # includes all stable solids.
                entries_HO = [
                    ComputedEntry('H', 10000),
                    ComputedEntry('O', 10000)
                ]
                solid_pd = PhaseDiagram(solid_entries + entries_HO)
                solid_entries = list(
                    set(solid_pd.stable_entries) - set(entries_HO))
            self._processed_entries = self._generate_multielement_entries(
                solid_entries + ion_entries)
        else:
            self._multielement = False

            self._processed_entries = solid_entries + ion_entries
        self._make_pourbaix_diagram()
Esempio n. 10
0
 def __init__(self, structure, kpoints, incar, energy, correction=0.0,
              parameters=None, data=None, entry_id=None):
     ComputedEntry.__init__(self, structure.composition, energy,
                            correction=correction,
                            parameters=parameters,
                            data=data, entry_id=entry_id)
     self.structure = structure
     self.kpoints = kpoints
     self.incar = incar
 def __init__(self, structure, kpoints, incar, energy, correction=0.0,
              parameters=None, data=None, entry_id=None):
     ComputedEntry.__init__(self, structure.composition, energy,
                            correction=correction,
                            parameters=parameters,
                            data=data, entry_id=entry_id)
     self.structure = structure
     self.kpoints = kpoints
     self.incar = incar
Esempio n. 12
0
 def as_entry(self, energies):
     """
     Returns a ComputedEntry representation of the reaction.
     :return:
     """
     comp = sum(self._all_comp, Composition())
     entry = ComputedEntry(0.5 * comp, self.calculate_energy(energies))
     entry.name = self.__str__()
     return entry
Esempio n. 13
0
 def as_entry(self, energies):
     """
     Returns a ComputedEntry representation of the reaction.
     :return:
     """
     relevant_comp = [comp * abs(coeff) for coeff, comp in zip(self._coeffs, self._all_comp)]
     comp = sum(relevant_comp, Composition())
     entry = ComputedEntry(0.5 * comp, self.calculate_energy(energies))
     entry.name = self.__str__()
     return entry
Esempio n. 14
0
 def setUp(self):
     self.entry = ComputedEntry(vasprun.final_structure.composition,
                                vasprun.final_energy,
                                parameters=vasprun.incar)
     self.entry2 = ComputedEntry({"Fe": 2, "O": 3}, 2.3)
     self.entry3 = ComputedEntry("Fe2O3", 2.3)
     self.entry4 = ComputedEntry("Fe2O3", 2.3, entry_id=1)
     self.entry5 = ComputedEntry("Fe6O9", 6.9)
     ea = ConstantEnergyAdjustment(-5, name="Dummy adjustment")
     self.entry6 = ComputedEntry("Fe6O9", 6.9, correction=-10)
     self.entry7 = ComputedEntry("Fe6O9", 6.9, energy_adjustments=[ea])
Esempio n. 15
0
 def as_entry(self, energies):
     """
     Returns a ComputedEntry representation of the reaction.
     :return:
     """
     relevant_comp = [comp * abs(coeff) for coeff, comp
                      in zip(self._coeffs, self._all_comp)]
     comp = sum(relevant_comp, Composition())
     entry = ComputedEntry(0.5 * comp, self.calculate_energy(energies))
     entry.name = self.__str__()
     return entry
Esempio n. 16
0
def computeValuesTernary(elems, nameDatabase):
    df_a = pd.read_hdf(nameDatabase, key='a')
    df_abc = pd.read_hdf(nameDatabase, key='abc_with_total')
    collect = combinations(elems, 3)
    numberofElements = []
    final_energy = []
    counter = 0
    for element in collect:
        df_stable = pd.read_hdf('data_FCC.h5', key="stable_binaries_Hull")
        counter += 1
        print(counter, element)
        try:
            if not totalDf.empty:
                pass
        except:
            totalDf = pd.DataFrame()
            totalDf_stable = pd.DataFrame()
        entriesInside = []
        counter += 1
        computedEntries = ComputedEntry(
            element[0],
            df_a[df_a['reduced'] == element[0]].etotal.values[0],
            attribute=1)
        entriesInside.append(computedEntries)
        computedEntries = ComputedEntry(
            element[1],
            df_a[df_a['reduced'] == element[1]].etotal.values[0],
            attribute=1)
        entriesInside.append(computedEntries)
        computedEntries = ComputedEntry(
            element[2],
            df_a[df_a['reduced'] == element[2]].etotal.values[0],
            attribute=1)
        entriesInside.append(computedEntries)
        for index, row in df_stable.iterrows():
            if set(SplitUpperCase(row['Composition'])).issubset(element):
                computedEntries = ComputedEntry(row['Formula'],
                                                row['energy'],
                                                attribute=row['NElements'])
                entriesInside.append(computedEntries)
        for index, row in df_abc.iterrows():
            if set(row['decomposition']).issubset(element):
                computedEntries = ComputedEntry(
                    row['decomposition'][0] + "12" + row['decomposition'][1] +
                    "12" + row['decomposition'][2] + "12",
                    row['Total_energy'],
                    attribute=3)
                entriesInside.append(computedEntries)
                break
        df, df_stable = convexHull(entriesInside)
        totalDf_stable = totalDf_stable.append(df_stable, ignore_index=True)
        totalDf = totalDf.append(df, ignore_index=True)
    return totalDf, totalDf_stable
Esempio n. 17
0
    def test_compound_energy(self):
        entry = ComputedEntry(Composition("H2O"), -16)
        entry = self.corr.correct_entry(entry)
        self.assertAlmostEqual(entry.energy, -15.10057, 4)

        entry = ComputedEntry(Composition("H2O"), -24)
        entry = self.corr.correct_entry(entry)
        self.assertAlmostEqual(entry.energy, -15.10057, 4)

        entry = ComputedEntry(Composition("Cl"), -24)
        entry = self.corr.correct_entry(entry)
        self.assertAlmostEqual(entry.energy, -24.344373, 4)
Esempio n. 18
0
 def test_normalize_energy_adjustments(self):
     ealist = [ManualEnergyAdjustment(5),
               ConstantEnergyAdjustment(5),
               CompositionEnergyAdjustment(1, 5, uncertainty_per_atom=0, name="Na"),
               TemperatureEnergyAdjustment(0.005, 100, 10, uncertainty_per_degK=0)
               ]
     entry = ComputedEntry("Na5Cl5", 6.9, energy_adjustments=ealist)
     assert entry.correction == 20
     entry.normalize()
     assert entry.correction == 4
     for ea in entry.energy_adjustments:
         assert ea.value == 1
Esempio n. 19
0
    def test_normalize_not_in_place(self):
        ealist = [
            ManualEnergyAdjustment(5),
            ConstantEnergyAdjustment(5),
            CompositionEnergyAdjustment(1, 5, uncertainty_per_atom=0, name="Na"),
            TemperatureEnergyAdjustment(0.005, 100, 10, uncertainty_per_deg=0),
        ]
        entry = ComputedEntry("Na5Cl5", 6.9, energy_adjustments=ealist)

        normed_entry = entry.normalize(inplace=False)
        entry.normalize()

        self.assertEqual(normed_entry, entry)
Esempio n. 20
0
 def test_normalize(self):
     entry = ComputedEntry("Fe6O9", 6.9, correction=1)
     entry_formula = entry.normalize()
     self.assertEqual(entry_formula.composition.formula, "Fe2 O3")
     self.assertAlmostEqual(entry_formula.uncorrected_energy, 6.9 / 3)
     self.assertAlmostEqual(entry_formula.correction, 1 / 3)
     self.assertAlmostEqual(entry_formula.energy * 3, 6.9 + 1)
     self.assertAlmostEqual(entry_formula.energy_adjustments[0].value, 1 / 3)
     entry_atom = entry.normalize("atom")
     self.assertEqual(entry_atom.composition.formula, "Fe0.4 O0.6")
     self.assertAlmostEqual(entry_atom.uncorrected_energy, 6.9 / 15)
     self.assertAlmostEqual(entry_atom.correction, 1 / 15)
     self.assertAlmostEqual(entry_atom.energy * 15, 6.9 + 1)
     self.assertAlmostEqual(entry_atom.energy_adjustments[0].value, 1 / 15)
Esempio n. 21
0
    def get_entries(self, criteria, inc_structure=False, optional_data=None):
        """
        Get ComputedEntries satisfying a particular criteria.

        .. note::

            The get_entries_in_system and get_entries  methods should be used
            with care. In essence, all entries, GGA, GGA+U or otherwise,
            are returned.  The dataset is very heterogeneous and not
            directly comparable.  It is highly recommended that you perform
            post-processing using pymatgen.entries.compatibility.

        Args:
            criteria:
                Criteria obeying the same syntax as query.
            inc_structure:
                Optional parameter as to whether to include a structure with
                the ComputedEntry. Defaults to False. Use with care - including
                structures with a large number of entries can potentially slow
                down your code to a crawl.
            optional_data:
                Optional data to include with the entry. This allows the data
                to be access via entry.data[key].

        Returns:
            List of pymatgen.entries.ComputedEntries satisfying criteria.
        """
        all_entries = list()
        optional_data = [] if not optional_data else list(optional_data)
        fields = [k for k in optional_data]
        fields.extend(["task_id", "unit_cell_formula", "energy", "is_hubbard",
                       "hubbards", "pseudo_potential.labels",
                       "pseudo_potential.functional", "run_type",
                       "input.is_lasph", "input.xc_override", "input.potcar_spec"])
        for c in self.query(fields, criteria):
            func = c["pseudo_potential.functional"]
            labels = c["pseudo_potential.labels"]
            symbols = ["{} {}".format(func, label) for label in labels]
            parameters = {"run_type": c["run_type"],
                          "is_hubbard": c["is_hubbard"],
                          "hubbards": c["hubbards"],
                          "potcar_symbols": symbols,
                          "is_lasph": c.get("input.is_lasph") or False,
                          "potcar_spec": c.get("input.potcar_spec"),
                          "xc_override": c.get("input.xc_override")}
            optional_data = {k: c[k] for k in optional_data}
            if inc_structure:
                struct = self.get_structure_from_id(c["task_id"])
                entry = ComputedStructureEntry(struct, c["energy"],
                                               0.0, parameters=parameters,
                                               data=optional_data,
                                               entry_id=c["task_id"])
            else:
                entry = ComputedEntry(Composition(c["unit_cell_formula"]),
                                      c["energy"], 0.0, parameters=parameters,
                                      data=optional_data,
                                      entry_id=c["task_id"])
            all_entries.append(entry)

        return all_entries
class ComputedEntryTest(unittest.TestCase):
    def setUp(self):
        self.entry = ComputedEntry(vasprun.final_structure.composition, vasprun.final_energy, parameters=vasprun.incar)
        self.entry2 = ComputedEntry({"Fe": 2, "O": 3}, 2.3)
        self.entry3 = ComputedEntry("Fe2O3", 2.3)
        self.entry4 = ComputedEntry("Fe2O3", 2.3, entry_id=1)

    def test_energy(self):
        self.assertAlmostEqual(self.entry.energy, -269.38319884)
        self.entry.correction = 1.0
        self.assertAlmostEqual(self.entry.energy, -268.38319884)
        self.assertAlmostEqual(self.entry3.energy_per_atom, 2.3 / 5)

    def test_composition(self):
        self.assertEqual(self.entry.composition.reduced_formula, "LiFe4(PO4)4")
        self.assertEqual(self.entry2.composition.reduced_formula, "Fe2O3")

    def test_to_from_dict(self):
        d = self.entry.as_dict()
        e = ComputedEntry.from_dict(d)
        self.assertAlmostEqual(e.energy, -269.38319884)

    def test_entry_id(self):
        self.assertEqual(self.entry4.entry_id, 1)
        self.assertEqual(self.entry2.entry_id, None)

    def test_str(self):
        self.assertIsNotNone(str(self.entry))
Esempio n. 23
0
def get_competing_phases_new(structure):
    """
    Collect the species to which the 2D materials might decompose to.
    Since a lot of 2D materials with similar compositions will have the
    same competing phases, duplicates aren't counted.
    """

    total_competing_phases = []
    composition = structure.composition
    energy = 100
    my_entry = ComputedEntry(composition, energy)  # 2D material
    entries = MPR.get_entries_in_chemsys(
        elements=[elt.symbol for elt in composition])

    entries.append(my_entry)  # 2D material

    pda = PDAnalyzer(PhaseDiagram(entries))
    decomp = pda.get_decomp_and_e_above_hull(my_entry, allow_negative=True)
    competing_phases = [(entry.composition.reduced_formula, entry.entry_id)
                        for entry in decomp[0]]

    # Keep a running list of all unique competing phases, since in
    # high throughput 2D searches there is usually some overlap in
    # competing phases for different materials.
    for specie in competing_phases:
        if specie not in total_competing_phases:
            total_competing_phases.append(specie)

    return total_competing_phases
Esempio n. 24
0
 def setUp(self):
     self.entry = ComputedEntry(vasprun.final_structure.composition,
                                vasprun.final_energy,
                                parameters=vasprun.incar)
     self.entry2 = ComputedEntry({"Fe": 2, "O": 3}, 2.3)
     self.entry3 = ComputedEntry("Fe2O3", 2.3)
     self.entry4 = ComputedEntry("Fe2O3", 2.3, entry_id=1)
Esempio n. 25
0
    def test_get_entry_by_material_id(self, mongo_mprester):
        reference_file = Path(
            __file__).absolute().parent / "mp-9029_entry_by_material_id.json"

        e = mongo_mprester.get_entry_by_material_id('mp-9029')

        assert e == ComputedEntry.from_dict(json.load(open(reference_file)))
Esempio n. 26
0
    def setUp(self):
        self.entry_Li = ComputedEntry("Li", -1.90753119)

        with open(os.path.join(test_dir, "LiTiO2_batt.json"), "r") as f:
            self.entries_LTO = json.load(f, cls=PMGJSONDecoder)

        self.ie_LTO = InsertionElectrode(self.entries_LTO, self.entry_Li)
Esempio n. 27
0
def get_competing_phases():
    """
    Collect the species to which the material might decompose to.

    Returns:
        A list of phases as tuples formatted as
        [(formula_1, Materials_Project_ID_1),
        (formula_2, Materials_Project_ID_2), ...]
    """

    composition = Structure.from_file('POSCAR').composition
    try:
        energy = Vasprun('vasprun.xml').final_energy
    except:
        energy = 100  # The function can work without a vasprun.xml
    entries = MPR.get_entries_in_chemsys([elt.symbol for elt in composition])
    my_entry = ComputedEntry(composition, energy)
    entries.append(my_entry)

    pda = PDAnalyzer(PhaseDiagram(entries))
    decomp = pda.get_decomp_and_e_above_hull(my_entry, allow_negative=True)
    competing_phases = [(entry.composition.reduced_formula, entry.entry_id)
                        for entry in decomp[0]]

    return competing_phases
Esempio n. 28
0
File: gsr.py Progetto: gmrigna/abipy
    def get_computed_entry(self, inc_structure=False, parameters=None, data=None):
        """
        Returns a pymatgen :class:`ComputedStructureEntry` from the GSR file.
        Same API as the one used in vasp_output.get_computed_entry.

        Args:
            inc_structure (bool): Set to True if you want
                ComputedStructureEntries to be returned instead of
                ComputedEntries.
            parameters (list): Input parameters to include. It has to be one of
                the properties supported by the GSR object. If
                parameters == None, a default set of parameters that are
                necessary for typical post-processing will be set.
            data (list): Output data to include. Has to be one of the properties
                supported by the GSR object.

        Returns:
            ComputedStructureEntry/ComputedEntry
        """
        #raise NotImplementedError("")
        # TODO
        #param_names = {"is_hubbard", "hubbards", "potcar_symbols", "run_type"}
        #if parameters:
        #    param_names.update(parameters)
        #params = {p: getattr(self, p) for p in param_names}
        #data = {p: getattr(self, p) for p in data} if data is not None else {}
        params, data = {}, {}

        if inc_structure:
            return ComputedStructureEntry(self.structure, self.energy, 
                                          parameters=params, data=data)
        else:
            return ComputedEntry(self.structure.composition, self.energy,   
                                 parameters=params, data=data)
    def setUp(self):
        d = [
            {"correction": 0.0, "data": {}, "energy": -108.56492362, "parameters": {}, "composition": {"Li": 54}},
            {
                "correction": 0.0,
                "data": {},
                "energy": -577.94689128,
                "parameters": {},
                "composition": {"O": 32, "Li": 64},
            },
            {"correction": 0.0, "data": {}, "energy": -17.02844794, "parameters": {}, "composition": {"O": 2}},
            {
                "correction": 0.0,
                "data": {},
                "energy": -959.64693323,
                "parameters": {},
                "composition": {"O": 72, "Li": 72},
            },
        ]
        entries = []
        for e in d:
            entries.append(ComputedEntry.from_dict(e))
        rcts = list(filter(lambda e: e.composition.reduced_formula in ["Li", "O2"], entries))
        prods = list(filter(lambda e: e.composition.reduced_formula == "Li2O2", entries))

        self.rxn = ComputedReaction(rcts, prods)
Esempio n. 30
0
    def assimilate(self, path):
        """
        Assimilate data in a directory path into a ComputedEntry object.

        Args:
            path: directory path

        Returns:
            ComputedEntry
        """
        try:
            gaurun = GaussianOutput(path)
        except Exception as ex:
            logger.debug("error in {}: {}".format(path, ex))
            return None
        param = {}
        for p in self._parameters:
            param[p] = getattr(gaurun, p)
        data = {}
        for d in self._data:
            data[d] = getattr(gaurun, d)
        if self._inc_structure:
            entry = ComputedStructureEntry(gaurun.final_structure,
                                           gaurun.final_energy,
                                           parameters=param,
                                           data=data)
        else:
            entry = ComputedEntry(gaurun.final_structure.composition,
                                  gaurun.final_energy, parameters=param,
                                  data=data)
        return entry
Esempio n. 31
0
def get_entry(doc):
    """
    Helper function to get a processed computed entry from the document

    Args:
        doc ({}): doc from which to get the entry

    Returns:
        (ComputedEntry) computed entry derived from doc

    """
    params = [
        "run_type", "is_hubbard", "pseudo_potential", "hubbards",
        "potcar_symbols", "oxide_type"
    ]
    doc["potcar_symbols"] = [
        "%s %s" % (doc["pseudo_potential"]["functional"], l)
        for l in doc["pseudo_potential"]["labels"]
    ]
    entry = ComputedEntry(doc["unit_cell_formula"],
                          doc["final_energy"],
                          parameters={k: doc[k]
                                      for k in params},
                          data={"oxide_type": doc['oxide_type']},
                          entry_id=doc["task_id"])
    entry = MaterialsProjectCompatibility().process_entries([entry])[0]
    return entry
Esempio n. 32
0
    def get_computed_entry(self,
                           inc_structure=True,
                           parameters=None,
                           data=None):
        """
        Returns a pymatgen :class:`ComputedStructureEntry` from the GSR file.
        Same API as the one used in vasp_output.get_computed_entry.

        Args:
            inc_structure (bool): Set to True if you want
                ComputedStructureEntries to be returned instead of ComputedEntries.
            parameters (list): Input parameters to include. It has to be one of
                the properties supported by the GSR object. If
                parameters is None, a default set of parameters that are
                necessary for typical post-processing will be set.
            data (list): Output data to include. Has to be one of the properties
                supported by the GSR object.

        Returns:
            ComputedStructureEntry/ComputedEntry
        """
        # TODO
        #param_names = {"is_hubbard", "hubbards", "potcar_symbols", "run_type"}
        if inc_structure:
            return ComputedStructureEntry(self.structure,
                                          self.energy,
                                          correction=0.0,
                                          parameters=parameters,
                                          data=data)
        else:
            return ComputedEntry(self.structure.composition,
                                 self.energy,
                                 parameters=parameters,
                                 data=data)
Esempio n. 33
0
class ComputedEntryTest(unittest.TestCase):
    def setUp(self):
        self.entry = ComputedEntry(vasprun.final_structure.composition,
                                   vasprun.final_energy,
                                   parameters=vasprun.incar)
        self.entry2 = ComputedEntry({"Fe": 2, "O": 3}, 2.3)
        self.entry3 = ComputedEntry("Fe2O3", 2.3)
        self.entry4 = ComputedEntry("Fe2O3", 2.3, entry_id=1)

    def test_energy(self):
        self.assertAlmostEqual(self.entry.energy, -269.38319884)
        self.entry.correction = 1.0
        self.assertAlmostEqual(self.entry.energy, -268.38319884)
        self.assertAlmostEqual(self.entry3.energy_per_atom, 2.3 / 5)

    def test_composition(self):
        self.assertEqual(self.entry.composition.reduced_formula, "LiFe4(PO4)4")
        self.assertEqual(self.entry2.composition.reduced_formula, "Fe2O3")

    def test_to_from_dict(self):
        d = self.entry.as_dict()
        e = ComputedEntry.from_dict(d)
        self.assertAlmostEqual(e.energy, -269.38319884)

    def test_entry_id(self):
        self.assertEqual(self.entry4.entry_id, 1)
        self.assertEqual(self.entry2.entry_id, None)

    def test_str(self):
        self.assertIsNotNone(str(self.entry))
Esempio n. 34
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)
     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(pd.get_e_above_hull(e),
                                    data["e_above_hull"])
Esempio n. 35
0
 def setUp(self):
     # comp = Composition("Mn2O3")
     self.solentry = ComputedEntry("Mn2O3", 49)
     ion = Ion.from_formula("MnO4-")
     self.ionentry = IonEntry(ion, 25)
     self.PxIon = PourbaixEntry(self.ionentry)
     self.PxSol = PourbaixEntry(self.solentry)
     self.PxIon.concentration = 1e-4
Esempio n. 36
0
 def remove_structure(entries):
     ents = []
     for ient in entries:
         dd = ient.as_dict()
         ent = ComputedEntry.from_dict(dd)
         ent.data["volume"] = ient.structure.volume
         ents.append(ent)
     return ents
Esempio n. 37
0
    def test_get_corrections_dict(self):
        compat = MaterialsProjectCompatibility()
        ggacompat = MaterialsProjectCompatibility("GGA")

        #Correct parameters
        entry = ComputedEntry(
            'Fe2O3', -1, 0.0,
            parameters={'is_hubbard': True, 'hubbards': {'Fe': 5.3, 'O': 0},
                        'run_type': 'GGA+U',
                        'potcar_symbols': ['PAW_PBE Fe_pv 06Sep2000',
                                           'PAW_PBE O 08Apr2002']})
        c = compat.get_corrections_dict(entry)

        self.assertAlmostEqual(c["MP Gas Correction"], -2.10687)
        self.assertAlmostEqual(c["MP Advanced Correction"], -5.466)

        entry.parameters["is_hubbard"] = False
        del entry.parameters["hubbards"]
        c = ggacompat.get_corrections_dict(entry)
        self.assertNotIn("MP Advanced Correction", c)
Esempio n. 38
0
    def test_get_corrections_dict(self):
        compat = MaterialsProjectCompatibility(check_potcar_hash=False)
        ggacompat = MaterialsProjectCompatibility("GGA", check_potcar_hash=False)

        #Correct parameters
        entry = ComputedEntry(
            'Fe2O3', -1, 0.0,
            parameters={'is_hubbard': True, 'hubbards': {'Fe': 5.3, 'O': 0},
                        'run_type': 'GGA+U',
                        'potcar_spec': [{'titel':'PAW_PBE Fe_pv 06Sep2000',
                                            'hash': '994537de5c4122b7f1b77fb604476db4'},
                                           {'titel': 'PAW_PBE O 08Apr2002',
                                            'hash': "7a25bc5b9a5393f46600a4939d357982"}]})
        c = compat.get_corrections_dict(entry)
        self.assertAlmostEqual(c["MP Anion Correction"], -2.10687)
        self.assertAlmostEqual(c["MP Advanced Correction"], -5.466)

        entry.parameters["is_hubbard"] = False
        del entry.parameters["hubbards"]
        c = ggacompat.get_corrections_dict(entry)
        self.assertNotIn("MP Advanced Correction", c)
Esempio n. 39
0
 def from_dict(cls, d):
     entries = [ComputedEntry.from_dict(dd) for dd in d["all_entries"]]
     elements = [Element.from_dict(dd) for dd in d["elements"]]
     return cls(entries, elements)
Esempio n. 40
0
 def convert(self, d):
     if 'structure' in d:
         return ComputedStructureEntry.from_dict(d)
     else:
         return ComputedEntry.from_dict(d)
Esempio n. 41
0
 def test_to_from_dict(self):
     d = self.entry.to_dict
     e = ComputedEntry.from_dict(d)
     self.assertAlmostEqual(e.energy, -269.38319884)
Esempio n. 42
0
 def test_sulfide_energy(self):
     self.entry = ComputedEntry("BaS", -10.21249155)
     self.assertAlmostEqual(self.entry.energy, -10.21249155)
     self.assertAlmostEqual(self.entry.energy_per_atom, -10.21249155 / 2)
     self.entry.correction = 1.0
     self.assertAlmostEqual(self.entry.energy, -9.21249155)