Skip to content

Summary aliasing of search fields #978

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 60 additions & 1 deletion mp_api/client/mprester.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from emmet.core.mpid import MPID
from emmet.core.settings import EmmetSettings
from emmet.core.tasks import TaskDoc
from emmet.core.thermo import ThermoType
from emmet.core.vasp.calc_types import CalcType
from monty.json import MontyDecoder
from packaging import version
Expand Down Expand Up @@ -61,8 +62,10 @@
from mp_api.client.routes.molecules import MoleculeRester

if TYPE_CHECKING:
from typing import Literal
from typing import Any, Literal

from pymatgen.analysis.phase_diagram import PDEntry
from pymatgen.entries.computed_entries import ComputedEntry

_EMMET_SETTINGS = EmmetSettings()
_MAPI_SETTINGS = MAPIClientSettings()
Expand Down Expand Up @@ -1620,3 +1623,59 @@ def _get_cohesive_energy(
elif normalization == "formula_unit":
num_form_unit = comp.get_reduced_composition_and_factor()[1]
return (energy_per_atom * natom - atomic_energy) / num_form_unit

def get_stability(
self,
entries: ComputedEntry | ComputedStructureEntry | PDEntry,
thermo_type: str | ThermoType = ThermoType.GGA_GGA_U,
) -> list[dict[str, Any]] | None:
chemsys = set()
for entry in entries:
chemsys.update(entry.composition.elements)
chemsys_str = "-".join(sorted(str(ele) for ele in chemsys))

thermo_type = (
ThermoType(thermo_type) if isinstance(thermo_type, str) else thermo_type
)

corrector = None
if thermo_type == ThermoType.GGA_GGA_U:
from pymatgen.entries.compatibility import MaterialsProject2020Compatibility

corrector = MaterialsProject2020Compatibility()

elif thermo_type == ThermoType.GGA_GGA_U_R2SCAN:
from pymatgen.entries.mixing_scheme import MaterialsProjectDFTMixingScheme

corrector = MaterialsProjectDFTMixingScheme(run_type_2="r2SCAN")

try:
pd = self.thermo.get_phase_diagram_from_chemsys(
chemsys_str, thermo_type=thermo_type
)
except OSError:
pd = None

if not pd:
warnings.warn(
f"No phase diagram data available for chemical system {chemsys_str} "
f"and thermo type {thermo_type}."
)
return

if corrector:
corrected_entries = corrector.process_entries(entries + pd.all_entries)
else:
corrected_entries = [*entries, *pd.all_entries]

new_pd = PhaseDiagram(corrected_entries)

return [
{
"e_above_hull": new_pd.get_e_above_hull(entry),
"composition": entry.composition.as_dict(),
"energy": entry.energy,
"entry_id": getattr(entry, "entry_id", f"user-entry-{idx}"),
}
for idx, entry in enumerate(entries)
]
72 changes: 46 additions & 26 deletions mp_api/client/routes/materials/summary.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import warnings
from collections import defaultdict

from emmet.core.summary import HasProps, SummaryDoc
Expand Down Expand Up @@ -47,6 +48,7 @@ def search(
magnetic_ordering: Ordering | None = None,
material_ids: str | list[str] | None = None,
n: tuple[float, float] | None = None,
nelements: tuple[int, int] | None = None,
num_elements: tuple[int, int] | None = None,
num_sites: tuple[int, int] | None = None,
num_magnetic_sites: tuple[int, int] | None = None,
Expand Down Expand Up @@ -117,7 +119,8 @@ def search(
material_ids (str, List[str]): A single Material ID string or list of strings
(e.g., mp-149, [mp-149, mp-13]).
n (Tuple[float,float]): Minimum and maximum refractive index to consider.
num_elements (Tuple[int,int]): Minimum and maximum number of elements to consider.
nelements (Tuple[int,int]): Minimum and maximum number of elements to consider.
num_elements (Tuple[int,int]): Alias for `nelements`, deprecated. Minimum and maximum number of elements to consider.
num_sites (Tuple[int,int]): Minimum and maximum number of sites to consider.
num_magnetic_sites (Tuple[int,int]): Minimum and maximum number of magnetic sites to consider.
num_unique_magnetic_sites (Tuple[int,int]): Minimum and maximum number of unique magnetic sites to consider.
Expand Down Expand Up @@ -153,43 +156,60 @@ def search(
"""
query_params = defaultdict(dict) # type: dict

not_aliased_kwargs = [
"energy_above_hull",
"nsites",
"volume",
"density",
"band_gap",
"efermi",
"total_magnetization",
"total_magnetization_normalized_vol",
"total_magnetization_normalized_formula_units",
"num_magnetic_sites",
"num_unique_magnetic_sites",
"k_voigt",
"k_reuss",
"k_vrh",
"g_voigt",
"g_reuss",
"g_vrh",
"e_total",
"e_ionic",
"e_electronic",
"n",
"nelements",
"weighted_surface_energy",
"weighted_work_function",
"shape_factor",
]

min_max_name_dict = {
"total_energy": "energy_per_atom",
"formation_energy": "formation_energy_per_atom",
"energy_above_hull": "energy_above_hull",
"uncorrected_energy": "uncorrected_energy_per_atom",
"equilibrium_reaction_energy": "equilibrium_reaction_energy_per_atom",
"nsites": "nsites",
"volume": "volume",
"density": "density",
"band_gap": "band_gap",
"efermi": "efermi",
"total_magnetization": "total_magnetization",
"total_magnetization_normalized_vol": "total_magnetization_normalized_vol",
"total_magnetization_normalized_formula_units": "total_magnetization_normalized_formula_units",
"num_magnetic_sites": "num_magnetic_sites",
"num_unique_magnetic_sites": "num_unique_magnetic_sites",
"k_voigt": "k_voigt",
"k_reuss": "k_reuss",
"k_vrh": "k_vrh",
"g_voigt": "g_voigt",
"g_reuss": "g_reuss",
"g_vrh": "g_vrh",
"elastic_anisotropy": "universal_anisotropy",
"poisson_ratio": "homogeneous_poisson",
"e_total": "e_total",
"e_ionic": "e_ionic",
"e_electronic": "e_electronic",
"n": "n",
"num_sites": "nsites",
"num_elements": "nelements",
"piezoelectric_modulus": "e_ij_max",
"weighted_surface_energy": "weighted_surface_energy",
"weighted_work_function": "weighted_work_function",
"surface_energy_anisotropy": "surface_anisotropy",
"shape_factor": "shape_factor",
}

min_max_name_dict.update({k: k for k in not_aliased_kwargs})

if num_elements:
if nelements:
warnings.warn(
"You have set both `nelements` and `num_elements`. As `num_elements`"
"is a deprecated alias for `nelements`, this key will be ignored."
)
else:
nelements = num_elements
warnings.warn(
"The `num_elements` tag is being deprecated in favor of `nelements`."
)

for param, value in locals().items():
if param in min_max_name_dict and value:
if isinstance(value, (int, float)):
Expand Down
1 change: 1 addition & 0 deletions tests/materials/test_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"theoretical": True,
"has_reconstructed": False,
"magnetic_ordering": Ordering.FM,
"nelements": (8, 9),
} # type: dict


Expand Down
77 changes: 76 additions & 1 deletion tests/test_mprester.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import numpy as np
import pytest
from emmet.core.tasks import TaskDoc
from emmet.core.thermo import ThermoType
from emmet.core.vasp.calc_types import CalcType
from pymatgen.analysis.phase_diagram import PhaseDiagram
from pymatgen.analysis.pourbaix_diagram import IonEntry, PourbaixDiagram, PourbaixEntry
Expand All @@ -18,7 +19,11 @@
BandStructureSymmLine,
)
from pymatgen.electronic_structure.dos import CompleteDos
from pymatgen.entries.compatibility import MaterialsProjectAqueousCompatibility
from pymatgen.entries.compatibility import (
MaterialsProjectAqueousCompatibility,
MaterialsProject2020Compatibility,
)
from pymatgen.entries.mixing_scheme import MaterialsProjectDFTMixingScheme
from pymatgen.entries.computed_entries import ComputedEntry, GibbsComputedStructureEntry
from pymatgen.io.cif import CifParser
from pymatgen.io.vasp import Chgcar
Expand Down Expand Up @@ -429,3 +434,73 @@ def test_get_cohesive_energy(self):
assert all(
v == pytest.approx(e_coh["noserial"][k]) for k, v in e_coh["serial"].items()
)

@pytest.mark.parametrize(
"chemsys, thermo_type",
[
[("Fe", "P"), "GGA_GGA+U"],
[("Li", "S"), ThermoType.GGA_GGA_U_R2SCAN],
[("Ni", "Se"), ThermoType.R2SCAN],
[("Ni", "Kr"), "R2SCAN"],
],
)
def test_get_stability(self, chemsys, thermo_type):
with MPRester() as mpr:
entries = mpr.get_entries_in_chemsys(
chemsys, additional_criteria={"thermo_types": [thermo_type]}
)

no_compound_entries = all(
len(entry.composition.elements) == 1 for entry in entries
)

modified_entries = [
ComputedEntry(
entry.composition,
entry.uncorrected_energy + 0.01,
parameters=entry.parameters,
entry_id=f"mod_{entry.entry_id}",
)
for entry in entries
if entry.composition.reduced_formula in ["Fe2P", "".join(chemsys)]
]

if len(modified_entries) == 0:
# create fake entry to get PD retrieval to fail
modified_entries = [
ComputedEntry(
"".join(chemsys),
np.average([entry.energy for entry in entries]),
entry_id=f"hypothetical",
)
]

if no_compound_entries:
with pytest.warns(UserWarning, match="No phase diagram data available"):
mpr.get_stability(modified_entries, thermo_type=thermo_type)
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"])
Loading