Skip to content

Commit

Permalink
Read API key from pymatgen config (#856)
Browse files Browse the repository at this point in the history
* use pymatgen.core.SETTINGS.get("PMG_MAPI_KEY") as final api_key fallback

* add test_pmg_api_key()

* monkeypatch.delenv("MP_API_KEY")

* fix test_pmg_api_key not unsetting DEFAULT_API_KEY

* fix typo
  • Loading branch information
janosh authored Oct 17, 2023
1 parent 47fc608 commit 9a971c2
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 18 deletions.
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,24 @@ ci:

repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.284
rev: v0.0.292
hooks:
- id: ruff
args: [--fix, --show-fixes]

- repo: https://github.com/psf/black
rev: 23.7.0
rev: 23.9.1
hooks:
- id: black

- repo: https://github.com/asottile/blacken-docs
rev: "1.15.0"
rev: "1.16.0"
hooks:
- id: blacken-docs
additional_dependencies: [black>=23.7.0]

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: check-case-conflict
- id: check-symlinks
Expand All @@ -34,7 +34,7 @@ repos:
- id: trailing-whitespace

- repo: https://github.com/codespell-project/codespell
rev: v2.2.4
rev: v2.2.6
hooks:
- id: codespell
stages: [commit, commit-msg]
Expand Down
7 changes: 5 additions & 2 deletions mp_api/client/mprester.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from packaging import version
from pymatgen.analysis.phase_diagram import PhaseDiagram
from pymatgen.analysis.pourbaix_diagram import IonEntry
from pymatgen.core import Element, Structure
from pymatgen.core import SETTINGS, Element, Structure
from pymatgen.core.ion import Ion
from pymatgen.entries.computed_entries import ComputedStructureEntry
from pymatgen.io.vasp import Chgcar
Expand Down Expand Up @@ -165,14 +165,17 @@ def __init__(
headers (dict): Custom headers for localhost connections.
mute_progress_bars (bool): Whether to mute progress bars.
"""
# SETTINGS tries to read API key from ~/.config/.pmgrc.yaml
api_key = api_key or DEFAULT_API_KEY or SETTINGS.get("PMG_MAPI_KEY")

if api_key and len(api_key) != 32:
raise ValueError(
"Please use a new API key from https://materialsproject.org/api "
"Keys for the new API are 32 characters, whereas keys for the legacy "
"API are 16 characters."
)

self.api_key = api_key or DEFAULT_API_KEY
self.api_key = api_key
self.endpoint = endpoint
self.headers = headers or {}
self.session = session or BaseRester._create_session(
Expand Down
2 changes: 1 addition & 1 deletion mp_api/client/routes/materials/substrates.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def search(
"""Query equations of state docs using a variety of search criteria.
Arguments:
area (Tuple[float,float]): Minimum and maximum volume in Ų to consider for the minimim coincident
area (Tuple[float,float]): Minimum and maximum volume in Ų to consider for the minimum coincident
interface area range.
energy (Tuple[float,float]): Minimum and maximum energy in meV to consider for the elastic energy range.
film_id (str): Materials Project ID of the film material.
Expand Down
36 changes: 26 additions & 10 deletions tests/test_mprester.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
from mp_api.client import MPRester
from mp_api.client.core.settings import MAPIClientSettings

os.environ["MP_API_KEY"] = "test"


@pytest.fixture()
def mpr():
Expand Down Expand Up @@ -68,14 +70,14 @@ def test_get_materials_ids_references(self, mpr):
assert len(data) > 5

def test_get_materials_ids_doc(self, mpr):
mpids = mpr.get_materials_ids("Al2O3")
random.shuffle(mpids)
doc = mpr.materials.get_data_by_id(mpids.pop(0))
mp_ids = mpr.get_materials_ids("Al2O3")
random.shuffle(mp_ids)
doc = mpr.materials.get_data_by_id(mp_ids.pop(0))
assert doc.formula_pretty == "Al2O3"

mpids = mpr.get_materials_ids("Al-O")
random.shuffle(mpids)
doc = mpr.materials.get_data_by_id(mpids.pop(0))
mp_ids = mpr.get_materials_ids("Al-O")
random.shuffle(mp_ids)
doc = mpr.materials.get_data_by_id(mp_ids.pop(0))
assert doc.chemsys == "Al-O"

def test_get_structures(self, mpr):
Expand All @@ -99,9 +101,9 @@ def test_find_structure(self, mpr):
def test_get_bandstructure_by_material_id(self, mpr):
bs = mpr.get_bandstructure_by_material_id("mp-149")
assert isinstance(bs, BandStructureSymmLine)
bs_unif = mpr.get_bandstructure_by_material_id("mp-149", line_mode=False)
assert isinstance(bs_unif, BandStructure)
assert not isinstance(bs_unif, BandStructureSymmLine)
bs_uniform = mpr.get_bandstructure_by_material_id("mp-149", line_mode=False)
assert isinstance(bs_uniform, BandStructure)
assert not isinstance(bs_uniform, BandStructureSymmLine)

def test_get_dos_by_id(self, mpr):
dos = mpr.get_dos_by_material_id("mp-149")
Expand Down Expand Up @@ -268,7 +270,7 @@ def test_get_ion_entries(self, mpr):
itertools.chain.from_iterable(i.elements for i in ion_ref_comps)
)
ion_ref_entries = mpr.get_entries_in_chemsys(
list([str(e) for e in ion_ref_elts] + ["O", "H"])
[*map(str, ion_ref_elts), "O", "H"]
)
mpc = MaterialsProjectAqueousCompatibility()
ion_ref_entries = mpc.process_entries(ion_ref_entries)
Expand Down Expand Up @@ -322,3 +324,17 @@ def test_large_list(self, mpr):
]
docs = mpr.summary.search(material_ids=mpids, fields=["material_ids"])
assert len(docs) == 15000


def test_pmg_api_key(monkeypatch: pytest.MonkeyPatch):
from pymatgen.core import SETTINGS

# unset DEFAULT_API_KEY
monkeypatch.setattr("mp_api.client.mprester.DEFAULT_API_KEY", None)

fake_api_key = "12345678901234567890123456789012" # 32 chars
# patch pymatgen.core.SETTINGS to contain PMG_MAPI_KEY
monkeypatch.setitem(SETTINGS, "PMG_MAPI_KEY", fake_api_key)

# create MPRester and check that it picked up the API key from pymatgen SETTINGS
assert MPRester().api_key == fake_api_key

0 comments on commit 9a971c2

Please sign in to comment.