diff --git a/mp_api/client/mprester.py b/mp_api/client/mprester.py index 0fab2eca..276134b7 100644 --- a/mp_api/client/mprester.py +++ b/mp_api/client/mprester.py @@ -1923,16 +1923,19 @@ def get_stability( """Get the energy above hull of a list of entries. Args: - entries (list of ComputedEntry or ComputedStructureEntry or PDEntry) : - List of entries with energy and composition information to compute - hull energies. - thermo_type (str or ThermoType) : The hull type to use. - Defaults to ThermoType.GGA_GGA_U_R2SCAN. + entries (list of ComputedEntry or ComputedStructureEntry or PDEntry): + List of entries with energy and composition information to compute + hull energies. Entries the corrections drop (for the GGA(+U)/r2SCAN + mixing scheme, those without a structure or `entry_id`, and duplicates + of a structure) are only assigned an energy above hull if computed + with the functional the hull is anchored on, else None. + thermo_type (str or ThermoType) : The hull type to use. + Defaults to ThermoType.GGA_GGA_U_R2SCAN. Returns: list of dict: { - "e_above_hull": float, # energy above the hull + "e_above_hull": float | None, # energy above the hull, or None "composition": dict[str,float], # composition as dict "energy": float, # energy with mixing / corrections "entry_id": str, # optional identifier @@ -2011,15 +2014,66 @@ def get_stability( ) new_pd = PhaseDiagram(processed) # type: ignore[arg-type] - return [ - { - "e_above_hull": new_pd.get_e_above_hull(entry), # type: ignore[arg-type] - "composition": entry.composition.as_dict(), - "energy": entry.energy, - "entry_id": getattr(entry, "entry_id", f"user-entry-{idx}"), - } - for idx, entry in enumerate(entries) - ] + # The corrector works in place, so the entries it kept are the input objects. The + # mixing scheme leaves the energies of the functional the hull is anchored on as + # compat_1/compat_2 corrected them, so entries of that functional it dropped (e.g. + # duplicates of MP structures) are on the hull's scale once corrected the same way + kept = {id(entry) for entry in processed} + anchor_run_types: list[str] = [] + anchor_compat: Compatibility | None = None + if isinstance(corrector, mixing_scheme_class()): + # it only keeps r2SCAN entries unadjusted if the hull is anchored on r2SCAN + r2scan_anchored = any( + e.parameters["run_type"] in corrector.valid_rtypes_2 + and not e.energy_adjustments + for e in processed + if isinstance(e, ComputedStructureEntry) # all the scheme keeps + ) + anchor_run_types, anchor_compat = ( + (corrector.valid_rtypes_2, corrector.compat_2) + if r2scan_anchored + else (corrector.valid_rtypes_1, corrector.compat_1) + ) + + def placed(entry): + """`entry` with its energy on the hull's scale, or None if it isn't.""" + if id(entry) in kept: + return entry + if entry.parameters.get("run_type") not in anchor_run_types: + return None + if anchor_compat is None: # not corrected (r2SCAN's compat_2 here) + return entry + try: # MP2020's POTCAR check raises for entries without POTCAR info + return anchor_compat.process_entry(entry, inplace=False) + except (KeyError, ValueError): + return None + + results, unplaced = [], [] + for idx, entry in enumerate(entries): + label = getattr(entry, "entry_id", None) or f"user-entry-{idx}" + if (placement := placed(entry)) is None: + unplaced.append(label) + results.append( + { + "e_above_hull": ( + None + if placement is None + # a dropped entry is not on the hull, so can lie below it + else new_pd.get_e_above_hull(placement, allow_negative=True) + ), + "composition": entry.composition.as_dict(), + "energy": (entry if placement is None else placement).energy, + "entry_id": label, + } + ) + if unplaced: + mp_warning( + f"{type(corrector).__name__} dropped {len(unplaced):,} of your entries, " + f"which are off the {thermo_type_valid_str} hull's energy scale, so their " + f"`e_above_hull` is None: {', '.join(unplaced)}", + stacklevel=2, + ) + return results def get_oxygen_evolution( self, diff --git a/tests/client/test_entry_progress.py b/tests/client/test_entry_progress.py index 21f5a6d2..7622a8aa 100644 --- a/tests/client/test_entry_progress.py +++ b/tests/client/test_entry_progress.py @@ -430,4 +430,53 @@ def test_get_stability_shows_progress(mpr, thermo, monkeypatch, term): mine = [gga[3]] result = mpr.get_stability(mine, thermo_type="GGA_GGA+U") assert result and result[0]["entry_id"] == "GGA-4" + assert result[0]["e_above_hull"] is not None assert "Corrected 4 entries (4 kept)" in plain(term.getvalue()) + + +@pytest.mark.parametrize( + "without, e_above_hull", + [ # MP's Li, O2 and Li2O ground states all have r2SCAN twins, so r2SCAN anchors: + (None, [None, None, 0.05, None, None, None]), + # without Li2O's r2SCAN twin, GGA(+U) anchors: + ("r2SCAN-3", [0.05, 0.05, None, None, -0.05, None]), + ], + ids=["r2SCAN", "GGA(+U)"], +) +def test_get_stability_dropped_entries( + mpr, thermo, monkeypatch, pipe, without, e_above_hull +): + """Dropped entries only get an `e_above_hull` if on the hull's energy scale.""" + from pymatgen.analysis.phase_diagram import PhaseDiagram + from pymatgen.entries.computed_entries import ComputedEntry + from pymatgen.io.vasp.sets import MPRelaxSet + + mp = [e for e in li_o_entries() if e.entry_id != without] + thermo("get_phase_diagram_from_chemsys", lambda self, *a, **k: PhaseDiagram(mp)) + monkeypatch.setattr(type(mpr), "_get_unmixed_entries", lambda self, *a, **k: mp) + li = (["Li"], [[0, 0, 0]], 3.4) # MP's Li structure + li2o = (["Li", "Li", "O"], [[0, 0, 0], [0.5, 0.5, 0.5], [0.25, 0.25, 0.25]], 4.6) + bad_u = _entry("gga-bad-u", "GGA+U", *li2o, -4.75) # MP2020 rejects U on Li + bad_u.parameters |= {"hubbards": {"Li": 3.0}, "is_hubbard": True} + mine = [ # twins of MP's materials, 0.05 eV/atom higher in energy: + _entry("gga", "GGA", *li, -1.85), + ComputedEntry("Li2O", 3 * -4.75, parameters={"run_type": "GGA"}), # an oxide + _entry("r2scan", "r2SCAN", *li, -2.85), + bad_u, + ComputedEntry( + "Li", -1.95, parameters={"run_type": "GGA"}, entry_id="gga-below" + ), + ] + # get_stability checks POTCARs; all but the last entry have them + for entry in [*mp, *mine]: + entry.parameters["potcar_symbols"] = [ + f"PAW_PBE {MPRelaxSet.CONFIG['POTCAR'][el.symbol]}" for el in entry.elements + ] + mine.append(ComputedEntry("Li", -1.85, parameters={"run_type": "GGA"})) + labels = ["gga", "user-entry-1", "r2scan", "gga-bad-u", "gga-below", "user-entry-5"] + unplaced = ", ".join(labels[i] for i, e in enumerate(e_above_hull) if e is None) + with pytest.warns(MPRestWarning, match=f"None: {unplaced}$"): + result = mpr.get_stability(mine, thermo_type="GGA_GGA+U_R2SCAN") + + assert [r["entry_id"] for r in result] == labels + assert [r["e_above_hull"] for r in result] == pytest.approx(e_above_hull) diff --git a/tests/client/test_mprester.py b/tests/client/test_mprester.py index 1dbb8f04..e3981ae8 100644 --- a/tests/client/test_mprester.py +++ b/tests/client/test_mprester.py @@ -27,18 +27,13 @@ BandStructureSymmLine, ) from pymatgen.electronic_structure.dos import CompleteDos, Dos -from pymatgen.entries.compatibility import ( - MaterialsProject2020Compatibility, - MaterialsProjectAqueousCompatibility, -) +from pymatgen.entries.compatibility import MaterialsProjectAqueousCompatibility from pymatgen.entries.computed_entries import ( ComputedEntry, + ComputedStructureEntry, ConstantEnergyAdjustment, GibbsComputedStructureEntry, ) -from pymatgen.analysis.compatibility.mixing_scheme import ( - MaterialsProjectDFTMixingScheme, -) from pymatgen.io.cif import CifParser from pymatgen.io.vasp import Chgcar @@ -715,14 +710,18 @@ def test_get_stability(self, thermo_type, caplog): to include more diverse chemical environments and thermo types which reflect the scope of the current MP database. """ + # nb: comparing to a ThermoType member instead raises for "r2SCAN" + mixed = thermo_type == "GGA_GGA+U_R2SCAN" + n_compared = 0 with warnings.catch_warnings(): # ignore some common pmg warnings: failed to guess oxi states, discarding entries, etc. warnings.filterwarnings("ignore", category=UserWarning) with MPRester() as mpr: - # No golden test data. Always test on fetched thermo data - chemsys_to_test: set[str] = { + # No golden test data. Always test on fetched thermo data, plus Ni-S (a + # GGA(+U)-anchored mixed hull) + chemsys_to_test: set[str] = {"Ni-S"} | { doc.chemsys for doc in mpr.materials.thermo.search( thermo_types=[thermo_type], @@ -734,66 +733,48 @@ def test_get_stability(self, thermo_type, caplog): } for chemsys in chemsys_to_test: - # RETURN ORDER NOT DETERMINISTIC entries = mpr.get_entries_in_chemsys( chemsys, additional_criteria={"thermo_types": [thermo_type]} ) - - modified_entries = [ - ComputedEntry( - entry.composition, - entry.uncorrected_energy + 0.01, - parameters=entry.parameters, - entry_id=f"mod_{entry.entry_id}", - ) - for entry in entries - # MIXING SCHEME - ONLY PASSES IF A "GOOD" ENTRY IS RETURNED FIRST?? - if entry.entry_id == entries[0].entry_id + mp_pd = PhaseDiagram(entries) + compounds = [ + e + for e in entries + if len(e.composition.elements) > 1 + # the mixing scheme can give an r2SCAN entry the GGA(+U) energy + # of the structure it matches, so only GGA(+U) polymorphs here + and not (mixed and e.parameters["run_type"] == "r2SCAN") ] - - if ( - all(len(entry.composition.elements) == 1 for entry in entries) - and chemsys.count("-") > 0 - ): - # For a multi-element chemsys with no multinaries, only elementals, - # there should be no phase diagram data available. - # a data event, so a log record rather than a warning - with caplog.at_level(logging.WARNING, logger="mp_api.client"): - assert ( - mpr.get_stability( - modified_entries, thermo_type=thermo_type - ) - is None - ) - assert "No phase diagram data available" in caplog.text - return - - else: - rester_ehulls = mpr.get_stability( - modified_entries, thermo_type=thermo_type - ) - - all_entries = entries + modified_entries - - compat = None - if thermo_type == "GGA_GGA+U": - compat = MaterialsProject2020Compatibility() - elif thermo_type == "GGA_GGA+U_R2SCAN": - compat = MaterialsProjectDFTMixingScheme(run_type_2="r2SCAN") - - if compat: - all_entries = compat.process_entries(all_entries) - - pd = PhaseDiagram(all_entries) - for entry in all_entries: - if str(entry.entry_id).startswith("mod"): - for dct in rester_ehulls: - if dct["entry_id"] == entry.entry_id: - data = dct - break - assert pd.get_e_above_hull(entry) == pytest.approx( - data["e_above_hull"] + new_entries = [ + ComputedStructureEntry( + # perturbed, as the mixing scheme drops duplicate structures + e.structure.copy().perturb(0.5, seed=0), + e.uncorrected_energy + 0.01 * e.composition.num_atoms, + parameters=e.parameters, + data=dict(e.data), # e.g. MP2020 reads oxide_type here + entry_id=f"new_{e.entry_id}", ) + for e in compounds + ] + results = mpr.get_stability(new_entries, thermo_type=thermo_type) + for entry, result in zip(compounds, results, strict=True): + if result["e_above_hull"] is None: + # it still matched MP's structure, so was dropped + assert mixed, (chemsys, entry.entry_id) + continue + assert result["e_above_hull"] == pytest.approx( + mp_pd.get_e_above_hull(entry) + 0.01, abs=1e-6 + ), (chemsys, entry.entry_id) + n_compared += 1 + + # A multi-element chemsys with only elementals has no phase diagram; + # a data event, so a log record rather than a warning + with caplog.at_level(logging.WARNING, logger="mp_api.client"): + he_ne = [ComputedEntry("HeNe", 0.0)] + assert mpr.get_stability(he_ne, thermo_type=thermo_type) is None + assert "No phase diagram data available" in caplog.text + + assert n_compared > 0 @pytest.mark.parametrize( "mpid, working_ion, thermo_type",