Source code for eon.amsel_records

"""Search records of ``[amsel] displacement = direction_cover``.

Every start amsel hands out, and what the search made of it, is a record in a
readcon-db corpus in the state directory, ``states/N/searches.db``. The corpus
is the only account of what was searched: the next start is planned from it,
the score of the state is computed from it, and nothing about either is kept
anywhere else.

A search is two trajectories of one frame. Trajectory ``2 * wuid`` is written
when the job is created and trajectory ``2 * wuid + 1`` when its result is
registered. A search with the first and without the second was handed out and
has not come back. The fields of a record are the JSON object under
``eon_search`` in the metadata of its frame, written and read by readcon.

A record does not hold a second copy of a structure eOn keeps. The frame of a
start holds the atoms its push moves, as they were sent, and the record holds
the push itself: ``mode`` lists those atoms with the three components of the
unit vector on each, ``magnitude`` its length, and ``atoms`` their rows in the
state. The numbers read back bit for bit, so the structure the client was
sent is the reactant of the state plus the push. The frame of a result holds
the active atoms of the structure the search ended on. A search that landed
on a process names it by ``process_id``; its saddle and its far minimum are in
``states/N/procdata``. eOn keeps no file of a search that ended on no process
unless ``[Debug] keep_bad_saddles`` is set, and the record then names the
directory.

A search can find a connected saddle that eOn leaves off the table, as it
does above the thermal window. It is a connected search all the same: the
direction led to a saddle. Its record has ``off_table`` set, the barrier and
the two energies, no process and no rate, and since eOn keeps no file of it
the active atoms of the saddle and of the far minimum are its two frames.

A state amsel has no start for has one more trajectory, with a record of kind
``fallback`` that gives the reason. The state info file holds nothing of
this.

The corpus needs the ``readcon_db`` module. Without it there is no place to
keep a record, so ``direction_cover`` is refused when the configuration is
read; it is never run without records. It is an LMDB directory and belongs on
a local filesystem; it follows ``[Paths] states``.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

_KEY = "eon_search"
_NAME = "searches.db"
# Trajectory of the fallback record. Odd, so it is no start, and above any
# work-unit id.
_FALLBACK_TRAJ = (1 << 62) + 1

#: What a search made of its start, in the vocabulary of the direction cover.
CONNECTED = "connected"
RETURNED = "returned"
NON_CONVERGED = "non_converged"
FAILED = "failed"
KINDS = (CONNECTED, RETURNED, NON_CONVERGED, FAILED)

# eOn termination reasons of a search whose budget ran out before a saddle.
_BUDGET_TERMINATIONS = frozenset({3, 4, 5, 9, 15})


[docs] def corpus_error() -> str | None: """Why the record corpus cannot be used, or None when it can.""" try: import readcon_db # noqa: F401 except (ImportError, OSError) as exc: return str(exc) or type(exc).__name__ return None
[docs] def outcome_kind(termination_reason: int, connected: bool) -> str: """Record kind of an eOn result. ``connected`` is true when eOn accepted the saddle as a process of the state, new or repeated. A search that stopped on an energy, iteration or trajectory budget did not converge. Every other ending failed. """ if connected: return CONNECTED if int(termination_reason) in _BUDGET_TERMINATIONS: return NON_CONVERGED return FAILED
[docs] def subset_text(structure: Any, rows: list[int], record: dict[str, Any]) -> str: """A frame of the atoms in ``rows`` of ``structure`` that carries ``record``. The atoms keep their positions, species, masses, per-axis fixed flags and ids. readcon builds and writes the frame. Taking the rows is ``readcon.subframe(frame, rows)``. The readcon that eOn pins predates it, so the rows are copied here first; this function becomes that one call when the pin carries it. """ import readcon from eon.structure import Structure part = Structure(len(rows)) part.box = structure.box.copy() for slot, row in enumerate(rows): part.r[slot] = structure.r[row] part.names[slot] = structure.names[row] part.mass[slot] = structure.mass[row] part.free = structure.free[rows] part.atom_ids = structure.ids_or_sequential()[rows] frame = part.to_conframe() frame.set_string_metadata(_KEY, json.dumps(record, sort_keys=True)) return readcon.write_con_string([frame])
def _record_of(text: str) -> dict[str, Any]: """The record a frame carries, read from its metadata by readcon.""" import readcon metadata = readcon.read_con_string(text)[0].metadata if _KEY not in metadata: raise ValueError("frame without a search record") return json.loads(metadata[_KEY]) # A corpus directory can be open once in a process, and the explorer that # reads a state's records is rebuilt on every pass of the server. The open # corpora are kept here, the most recently used last, and the oldest is let # go when a run has moved on through more states than this. _OPEN: dict[str, Any] = {} _OPEN_LIMIT = 8 # Records already read, by corpus path and trajectory. A trajectory is # written once, and reading its record parses the whole frame. _READ: dict[tuple[str, int], dict[str, Any]] = {} def _open(path: Path): key = str(path) db = _OPEN.pop(key, None) if db is None: reason = corpus_error() if reason is not None: raise RuntimeError( "[amsel] displacement = direction_cover keeps its search " f"records in a readcon-db corpus, and readcon_db does not load: {reason}" ) from readcon_db import ConCorpus path.mkdir(parents=True, exist_ok=True) while len(_OPEN) >= _OPEN_LIMIT: del _OPEN[next(iter(_OPEN))] db = ConCorpus(key) _OPEN[key] = db return db
[docs] class SearchRecords: """The searches of one state, in work-unit order.""" def __init__(self, state: Any): self.state = state self.path = Path(state.path).resolve() / _NAME def _corpus(self): return _open(self.path) def _keys(self) -> set[int]: if not self.path.is_dir(): return set() return {int(traj) for traj, frame in self._corpus().select() if int(frame) == 0} def _record(self, traj: int) -> dict[str, Any]: key = (str(self.path), int(traj)) record = _READ.get(key) if record is None: record = _record_of(self._corpus().get_frame_text(int(traj), 0)) _READ[key] = record return dict(record)
[docs] def handed_out(self) -> int: """Number of starts handed out, returned or not.""" return sum(1 for traj in self._keys() if traj % 2 == 0)
[docs] def fallback(self) -> str | None: """Why amsel has no start for the state, or None when it has.""" if _FALLBACK_TRAJ not in self._keys(): return None return str(self._record(_FALLBACK_TRAJ)["reason"])
[docs] def set_fallback(self, reason: str, structure: Any) -> None: """Record once that the state takes no start from amsel, and why. The record needs a frame to ride on. It is the first atom of the state, which says nothing; the reason is the content. """ if _FALLBACK_TRAJ in self._keys(): return record = {"state": int(self.state.number), "kind": "fallback", "reason": str(reason)} self._corpus().append_trajectory_str( _FALLBACK_TRAJ, subset_text(structure, [0], record), source="fallback" )
[docs] def pending_start(self, wuid: int) -> dict[str, Any] | None: """The start on record for ``wuid`` when no result is, else None.""" keys = self._keys() if 2 * int(wuid) not in keys or 2 * int(wuid) + 1 in keys: return None return self._record(2 * int(wuid))
[docs] def hand_out(self, wuid: int, start: Any, rows: list[int], **fields: Any) -> None: """Record the start sent to the client for work unit ``wuid``. ``start`` is the structure sent and ``rows`` the atoms its push moves; only those go into the frame. """ rows = [int(row) for row in rows] record = {"state": int(self.state.number), "wuid": int(wuid), "atoms": rows, **fields} self._corpus().append_trajectory_str( 2 * int(wuid), subset_text(start, rows, record), source=f"start {wuid}" )
[docs] def register( self, wuid: int, kind: str, end: Any, rows: list[int], beyond: Any = None, **fields: Any, ) -> bool: """Record what the search of ``wuid`` ended on. ``end`` is the structure it ended on and ``rows`` the atoms of it to keep, in ascending order. ``beyond`` is the minimum on the far side of a saddle eOn keeps no file of; the same atoms of it follow as a second frame. False when ``wuid`` has no start here: a search of another state, or one that was not started by amsel. """ if kind not in KINDS: raise ValueError(f"unknown search record kind {kind!r}") keys = self._keys() if 2 * int(wuid) not in keys or 2 * int(wuid) + 1 in keys: return False rows = sorted(int(row) for row in rows) record = { "state": int(self.state.number), "wuid": int(wuid), "kind": kind, "atoms": rows, "frames": ["end"] if beyond is None else ["saddle", "far minimum"], **fields, } text = subset_text(end, rows, record) if beyond is not None: text += subset_text(beyond, rows, {"frame": "far minimum"}) self._corpus().append_trajectory_str(2 * int(wuid) + 1, text, source=f"end {wuid}") return True
[docs] def frame_text(self, wuid: int, end: bool = False, frame: int = 0) -> str: """The frame of the start of ``wuid``, or a frame of its result.""" return self._corpus().get_frame_text(2 * int(wuid) + int(end), int(frame))
[docs] def records(self) -> list[dict[str, Any]]: """One row per start in work-unit order: ``start`` and ``end`` or None.""" keys = self._keys() rows = [] for traj in sorted(k for k in keys if k % 2 == 0 and k < _FALLBACK_TRAJ): end = self._record(traj + 1) if traj + 1 in keys else None rows.append({"wuid": traj // 2, "start": self._record(traj), "end": end}) return rows