Skip to content
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

Update thermo rester methods #714

Merged
merged 7 commits into from
Dec 6, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
33 changes: 24 additions & 9 deletions mp_api/client/routes/thermo.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import warnings
from collections import defaultdict
from typing import List, Optional, Tuple, Union

from emmet.core.thermo import ThermoDoc
from pymatgen.analysis.phase_diagram import PhaseDiagram

from typing import Optional, List, Tuple, Union
from mp_api.client.core import BaseRester
from mp_api.client.core.utils import validate_ids
from emmet.core.thermo import ThermoDoc, ThermoType
from pymatgen.analysis.phase_diagram import PhaseDiagram


class ThermoRester(BaseRester[ThermoDoc]):
Expand Down Expand Up @@ -40,6 +38,8 @@ def search(
is_stable: Optional[bool] = None,
material_ids: Optional[List[str]] = None,
num_elements: Optional[Tuple[int, int]] = None,
thermo_ids: Optional[List[str]] = None,
thermo_types: Optional[List[ThermoType]] = None,
total_energy: Optional[Tuple[float, float]] = None,
uncorrected_energy: Optional[Tuple[float, float]] = None,
sort_fields: Optional[List[str]] = None,
Expand All @@ -63,6 +63,9 @@ def search(
(e.g., [Fe2O3, ABO3]).
is_stable (bool): Whether the material is stable.
material_ids (List[str]): List of Materials Project IDs to return data for.
thermo_ids (List[str]): List of thermo IDs to return data for. This is a combination of the Materials
Project ID and thermo type (e.g. mp-149_GGA_GGA+U).
thermo_types (List[ThermoType]): List of thermo types to return data for (e.g. ThermoType.GGA_GGA_U).
num_elements (Tuple[int,int]): Minimum and maximum number of elements in the material to consider.
total_energy (Tuple[float,float]): Minimum and maximum corrected total energy in eV/atom to consider.
uncorrected_energy (Tuple[float,float]): Minimum and maximum uncorrected total
Expand Down Expand Up @@ -95,6 +98,14 @@ def search(
if material_ids:
query_params.update({"material_ids": ",".join(validate_ids(material_ids))})

if thermo_ids:
query_params.update({"thermo_ids": ",".join(validate_ids(thermo_ids))})

if thermo_types:
query_params.update(
{"thermo_types": ",".join([t.value for t in thermo_types])}
)

if num_elements:
if isinstance(num_elements, int):
num_elements = (num_elements, num_elements)
Expand Down Expand Up @@ -141,19 +152,23 @@ def search(
**query_params,
)

def get_phase_diagram_from_chemsys(self, chemsys: str) -> PhaseDiagram:
def get_phase_diagram_from_chemsys(
self, chemsys: str, thermo_type: ThermoType = ThermoType.GGA_GGA_U
) -> PhaseDiagram:
"""
Get a pre-computed phase diagram for a given chemsys.

Arguments:
material_id (str): Materials project ID
chemsys (str): A chemical system (e.g. Li-Fe-O)
thermo_type (ThermoType): The thermo type for the phase diagram.
Defaults to ThermoType.GGA_GGA_U.
Returns:
phase_diagram (PhaseDiagram): Pymatgen phase diagram object.
"""

phase_diagram_id = f"{chemsys}_{thermo_type.value}"
response = self._query_resource(
fields=["phase_diagram"],
suburl=f"phase_diagram/{chemsys}",
suburl=f"phase_diagram/{phase_diagram_id}",
use_document_model=False,
num_chunks=1,
chunk_size=1,
Expand Down
34 changes: 12 additions & 22 deletions tests/test_thermo.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from pymatgen.analysis.phase_diagram import PhaseDiagram

from mp_api.client.routes.thermo import ThermoRester
from emmet.core.thermo import ThermoType


@pytest.fixture
Expand All @@ -21,13 +22,15 @@ def rester():
"all_fields",
"fields",
"equilibrium_reaction_energy",
"thermo_types",
]

sub_doc_fields = [] # type: list

alt_name_dict = {
"formula": "formula_pretty",
"material_ids": "material_id",
"thermo_ids": "thermo_id",
"total_energy": "energy_per_atom",
"formation_energy": "formation_energy_per_atom",
"uncorrected_energy": "uncorrected_energy_per_atom",
Expand All @@ -40,12 +43,11 @@ def rester():
"material_ids": ["mp-149"],
"formula": "SiO2",
"chemsys": "Si-O",
"thermo_ids": ["mp-149"],
} # type: dict


@pytest.mark.skipif(
os.environ.get("MP_API_KEY", None) is None, reason="No API key found."
)
@pytest.mark.skipif(os.environ.get("MP_API_KEY", None) is None, reason="No API key found.")
def test_client(rester):
search_method = rester.search

Expand All @@ -56,6 +58,7 @@ def test_client(rester):
# Query API for each numeric and boolean parameter and check if returned
for entry in param_tuples:
param = entry[0]
print(param)
if param not in excluded_params:
param_type = entry[1].__args__[0]
q = None
Expand All @@ -66,55 +69,42 @@ def test_client(rester):
param: (-100, 100),
"chunk_size": 1,
"num_chunks": 1,
"fields": [
project_field if project_field is not None else param
],
"fields": [project_field if project_field is not None else param],
}
elif param_type == typing.Tuple[float, float]:
project_field = alt_name_dict.get(param, None)
q = {
param: (-100.12, 100.12),
"chunk_size": 1,
"num_chunks": 1,
"fields": [
project_field if project_field is not None else param
],
"fields": [project_field if project_field is not None else param],
}
elif param_type is bool:
project_field = alt_name_dict.get(param, None)
q = {
param: False,
"chunk_size": 1,
"num_chunks": 1,
"fields": [
project_field if project_field is not None else param
],
"fields": [project_field if project_field is not None else param],
}
elif param in custom_field_tests:
project_field = alt_name_dict.get(param, None)
q = {
param: custom_field_tests[param],
"chunk_size": 1,
"num_chunks": 1,
"fields": [
project_field if project_field is not None else param
],
"fields": [project_field if project_field is not None else param],
}

doc = search_method(**q)[0].dict()
for sub_field in sub_doc_fields:
if sub_field in doc:
doc = doc[sub_field]

assert (
doc[project_field if project_field is not None else param]
is not None
)
assert doc[project_field if project_field is not None else param] is not None


def test_get_phase_diagram_from_chemsys():
# Test that a phase diagram is returned

assert isinstance(
ThermoRester().get_phase_diagram_from_chemsys("Hf-Pm"), PhaseDiagram
)
assert isinstance(ThermoRester().get_phase_diagram_from_chemsys("Hf-Pm"), PhaseDiagram)
26 changes: 7 additions & 19 deletions tests/test_xas.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,8 @@ def rester():
} # type: dict


@pytest.mark.skipif(
os.environ.get("MP_API_KEY", None) is None, reason="No API key found."
)
@pytest.mark.skip(reason="Temp skip until timeout update.")
@pytest.mark.skipif(os.environ.get("MP_API_KEY", None) is None, reason="No API key found.")
def test_client(rester):
search_method = rester.search

Expand All @@ -65,47 +64,36 @@ def test_client(rester):
param: (-100, 100),
"chunk_size": 1,
"num_chunks": 1,
"fields": [
project_field if project_field is not None else param
],
"fields": [project_field if project_field is not None else param],
}
elif param_type == typing.Tuple[float, float]:
project_field = alt_name_dict.get(param, None)
q = {
param: (-100.12, 100.12),
"chunk_size": 1,
"num_chunks": 1,
"fields": [
project_field if project_field is not None else param
],
"fields": [project_field if project_field is not None else param],
}
elif param_type is bool:
project_field = alt_name_dict.get(param, None)
q = {
param: False,
"chunk_size": 1,
"num_chunks": 1,
"fields": [
project_field if project_field is not None else param
],
"fields": [project_field if project_field is not None else param],
}
elif param in custom_field_tests:
project_field = alt_name_dict.get(param, None)
q = {
param: custom_field_tests[param],
"chunk_size": 1,
"num_chunks": 1,
"fields": [
project_field if project_field is not None else param
],
"fields": [project_field if project_field is not None else param],
}

doc = search_method(**q)[0].dict()
for sub_field in sub_doc_fields:
if sub_field in doc:
doc = doc[sub_field]

assert (
doc[project_field if project_field is not None else param]
is not None
)
assert doc[project_field if project_field is not None else param] is not None