Skip to content
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
52 changes: 41 additions & 11 deletions mp_api/client/core/_display.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@
unreachable, data missing, a local dataset reused): `logger.warning/info`.
- Diagnostics: `logger.debug`.
- Transient progress: `progress_bar` / `status`, interactive output only.
Bars and summary lines report work the caller asked for: lookups the client
makes on its own behalf (resolving IDs, then fetching the data) run inside a
`status()`, which describes the whole operation and keeps the bars inside it
from drawing or printing anything.
- Output the user explicitly asked for (`notify_db_version`): `print_notice`.

So WARNING-level log records always mean something went wrong, and
Expand Down Expand Up @@ -119,6 +123,7 @@

from __future__ import annotations

import contextvars
import io
import logging
import threading
Expand Down Expand Up @@ -446,6 +451,13 @@ def update(self, advance: float = 1) -> None:
self._progress.advance(self._task_id, advance)


# Whether a `status()` block is running in this context. Contextvars are copied
# into worker threads by `_external.in_current_context`, so those inherit it.
_IN_OPERATION: contextvars.ContextVar[bool] = contextvars.ContextVar(
"mp_api_client_in_operation", default=False
)


def _as_int(value: float | None) -> float | None:
"""Show (near) whole-number counts as ints, without a trailing `.0`."""
if isinstance(value, float) and abs(value - round(value)) < 1e-6:
Expand All @@ -469,7 +481,9 @@ def progress_bar(
Args:
description (str) : label shown next to the bar
total (float or None) : expected number of units, None if unknown
enabled (bool) : if False, nothing is shown (a no-op handle is yielded)
enabled (bool) : if False, nothing is shown (a no-op handle is yielded).
Nothing is shown either inside a `status()` block, which describes
the whole operation itself.
delay (float) : seconds before the bar is shown, so quick
operations stay silent. Checked on each update.
unit (str) : unit name for the rate column
Expand All @@ -487,7 +501,7 @@ def progress_bar(
ProgressHandle
"""
console = get_console()
if not enabled or is_quiet():
if not enabled or is_quiet() or _IN_OPERATION.get():
yield ProgressHandle(total, summary=summary)
return
if not _is_interactive(console):
Expand Down Expand Up @@ -705,25 +719,41 @@ def status(message: str, *, enabled: bool = True) -> Iterator[None]:
of WARNING-level logs). If disabled (muted progress bars) or in quiet mode,
nothing is shown or logged.

The status describes the whole operation the caller asked for, so
everything inside it stays quiet:

- `progress_bar`s inside the block draw nothing, print no summary line and
log nothing (e.g. the lookup of a material's IDs the client makes on
its own behalf);
- a `status` nested in another one shows and logs nothing.

Work with countable progress that the caller should watch (a multi-page
download) needs a `progress_bar` instead of a `status`.

Args:
message (str) : what is happening, e.g. "Counting documents..."
enabled (bool) : if False, show nothing
"""
console = get_console()
if not enabled or is_quiet():
yield
return
if not (_is_interactive(console) and _can_draw_live(console)):
logging.getLogger(LOGGER_NAME).info(message)
if not enabled or is_quiet() or _IN_OPERATION.get():
yield
return

progress = _STATE.acquire(console)
task_id = progress.add_task(message, total=None, status=True)
token = _IN_OPERATION.set(True)
try:
yield
if not (_is_interactive(console) and _can_draw_live(console)):
logging.getLogger(LOGGER_NAME).info(message)
yield
return

progress = _STATE.acquire(console)
task_id = progress.add_task(message, total=None, status=True)
try:
yield
finally:
_STATE.release(task_id)
finally:
_STATE.release(task_id)
_IN_OPERATION.reset(token)


def _app_handlers(logger: logging.Logger) -> list[logging.Handler]:
Expand Down
2 changes: 2 additions & 0 deletions mp_api/client/core/_external.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ def _tracked(fn: Callable[..., Any]) -> Callable[..., Any]:

@functools.wraps(fn)
def wrapper(*args: Any, **kwargs: Any) -> Any:
# keep this frame out of tracebacks in IPython, Jupyter and pytest
__tracebackhide__ = True
with capturing():
return fn(*args, **kwargs)

Expand Down
39 changes: 30 additions & 9 deletions mp_api/client/mprester.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
from typing import Any, Literal

import numpy as np
from emmet.core.phonon import PhononBS, PhononDOS
from emmet.core.tasks import CoreTaskDoc
from packaging.version import Version
from pymatgen.analysis.phase_diagram import PDEntry
Expand Down Expand Up @@ -1514,31 +1515,52 @@ def get_dos_by_material_id(
load_projections=load_projections,
)

def get_phonon_dos_by_material_id(self, material_id: str):
def get_phonon_dos_by_material_id(
self,
material_id: str,
phonon_method: Literal["pheasy", "dfpt"] | None = None,
) -> PhononDOS | dict[str, Any]:
"""Get phonon density of states data corresponding to a material_id.

Args:
material_id (str): Materials Project material_id.
phonon_method (str or None): phonon method, i.e. pheasy or dfpt. By default,
the method is chosen from the material's data: pheasy if it has it,
otherwise dfpt. If the pheasy calculation has no DOS, the dfpt one
is used (with a warning). A method passed explicitly is never replaced.

Returns:
CompletePhononDos: A phonon DOS object.

dos (PhononDOS): PhononDOS object
"""
return self.materials.phonon.get_dos_from_material_id(
material_id=material_id, phonon_method="dfpt"
material_id=material_id, phonon_method=phonon_method
)

def get_phonon_bandstructure_by_material_id(self, material_id: str):
def get_phonon_bandstructure_by_material_id(
self,
material_id: str,
phonon_method: Literal["pheasy", "dfpt"] | None = None,
path_type: str | BSPathType = BSPathType.setyawan_curtarolo,
) -> PhononBS | dict[str, Any]:
"""Get phonon dispersion data corresponding to a material_id.

Args:
material_id (str): Materials Project material_id.
phonon_method (str or None): phonon method, i.e. pheasy or dfpt. By default,
the method is chosen from the material's data: pheasy if it has it,
otherwise dfpt. If the pheasy calculation has no band structure,
the dfpt one is used (with a warning). A method passed explicitly
is never replaced.
path_type (BSPathType or str): k-path selection convention for the band structure.
pheasy has all conventions; dfpt only has setyawan_curtarolo.

Returns:
PhononBandStructureSymmLine: phonon band structure.
bandstructure (PhononBS): PhononBS object
"""
return self.materials.phonon.get_bandstructure_from_material_id(
material_id=material_id, phonon_method="dfpt"
material_id=material_id,
phonon_method=phonon_method,
path_type=path_type,
)

def get_wulff_shape(self, material_id: str):
Expand Down Expand Up @@ -1796,8 +1818,7 @@ def get_cohesive_energy(
# Prevent user error
if isinstance(material_ids, str | MPID):
raise MPRestError(
"Input material IDs (even a single ID) as a list: "
f"`[{material_ids}]`"
f"Input material IDs (even a single ID) as a list: `[{material_ids}]`"
)

entry_preference = {
Expand Down
Loading