"""Saddle-search starts from amsel for ``[amsel] displacement = direction_cover``.
``amsel.select_active_atoms`` picks the atoms. ``amsel.next_search_start``
plans each start from the state's search records (:mod:`eon.amsel_records`):
it rebuilds the direction cover of the state from what every earlier search
ended on and returns the best free arm with its push over all atoms. The
records are a readcon-db corpus in the state directory and the only thing the
plan depends on besides the state and the seed, so a server that stops and
starts again plans the same starts, and so do several clients whose results
are registered in work-unit order.
A state with no free active atom has no start from amsel and is searched with
the ``[Saddle Search]`` displacement like any other. A cell without a defect
is one, such as the crystal a vacancy and an interstitial leave when they
recombine. The reason is written once as a record of the state, and the
state does not ask amsel again.
So is a state whose cover has no arm left: every arm is recorded or out.
"""
from __future__ import annotations
import logging
from typing import Any
import numpy as np
from eon import fileio as io
from eon.amsel_records import SearchRecords, outcome_kind
logger = logging.getLogger("amsel")
# Active mask of each state by state directory, and the last confidence of
# each by its records. Both follow from the state alone, and both are asked
# for several times in one pass of the server.
_MASKS: dict[str, list[bool] | None] = {}
_CONFIDENCE: dict[str, tuple[tuple, float]] = {}
# Saddle and far minimum of each process a search landed on, by corpus path
# and process. A process does not change once it is registered, and the
# explorer that replays the records is rebuilt on every pass of the server.
_GEOMETRY: dict[tuple[str, int], tuple[list, list]] = {}
[docs]
class AmselSearch:
"""The ordered (atom, direction) starts of one state."""
def __init__(self, state: Any, reactant: Any, config: Any):
self.state = state
self.reactant = reactant
self.config = config
self._mask: list[bool] | None = None
self.records = SearchRecords(state)
self._arm: dict[str, Any] | None = None
self._resumed: int | None = None
[docs]
def fallback_reason(self) -> str | None:
"""Why this state takes the eOn displacement, or None when it does not."""
return self.records.fallback()
def _fall_back(self, reason: str) -> None:
logger.warning(
"amsel direction_cover: state %s uses the eOn displacement from here on: %s",
self.state.number,
reason,
)
self.records.set_fallback(reason, self.reactant)
def _active_mask(self) -> list[bool] | None:
if self._mask is not None:
return self._mask
key = str(self.records.path)
if key in _MASKS:
self._mask = _MASKS[key]
return self._mask
import amsel
rule = self.config.amsel_active_atoms
box = np.asarray(self.reactant.box, dtype=float)
names: dict[str, int] = {}
species = [names.setdefault(str(n), len(names)) for n in self.reactant.names]
selection = amsel.select_active_atoms(
np.asarray(self.reactant.r, dtype=float).tolist(),
np.linalg.norm(box, axis=1).tolist(),
rule=rule,
species=species,
cell_matrix=box.tolist(),
)
free = self.reactant.atom_is_free()
mask = [bool(m) and bool(f) for m, f in zip(selection.mask, free)]
if not any(mask):
self._fall_back(
f"{rule} found no free active atom (status {selection.status})"
)
_MASKS[key] = None
return None
logger.info(
"amsel %s: %d active atoms in state %s (%s, %s)",
rule,
sum(mask),
self.state.number,
selection.status,
selection.cluster_method,
)
self._mask = mask
_MASKS[key] = mask
return mask
def _cover_records(self) -> list:
"""The state's search records as amsel reads them, in work-unit order."""
import amsel
rows = []
for row in self.records.records():
start, end = row["start"], row["end"]
if start.get("point") is None:
raise RuntimeError(
f"search record {row['wuid']} of state {self.state.number} names "
"no cover point; it was written before starts were planned from "
"the records and cannot be replayed"
)
arm = (int(start["atom"]), int(start["point"]))
if end is None:
rows.append(amsel.SearchRecord(*arm, "pending"))
continue
calls = int(end.get("force_calls_saddle", 0)) + int(
end.get("force_calls_minimization", 0)
)
kind = end["kind"]
if kind != "connected":
rows.append(
amsel.SearchRecord(
*arm,
kind,
force_calls=max(calls, 1),
reason=f"eOn termination reason {end.get('termination_reason')}",
)
)
continue
if end.get("process_id") is not None:
saddle, product = self._geometry(end["process_id"])
else:
saddle, product = self._off_table_geometry(row["wuid"], end)
rows.append(
amsel.SearchRecord(
*arm,
"connected",
saddle=saddle,
saddle_energy=float(end["saddle_energy"]),
product=product,
product_energy=float(end["product_energy"]),
force_calls=max(calls, 1),
rate=end.get("rate"),
)
)
return rows
[docs]
def confidence(self) -> float | None:
"""Confidence of the state from its search records, or None.
``amsel.search_confidence`` rebuilds the direction cover from the
records and returns one minus the largest posterior probability,
over the active atoms, that a missed exit carries more than
``[amsel] relevant_rate_share`` of the escape rate. A state with no
search scores close to zero from the estimator itself.
None when amsel has no cover for the state: no free atom of it is
active, so it has no search record to score.
"""
mask = self._active_mask()
if mask is None:
return None
rows = self.records.records()
key = str(self.records.path)
stamp = tuple((row["wuid"], row["end"] is not None) for row in rows)
cached = _CONFIDENCE.get(key)
if cached is not None and cached[0] == stamp:
return cached[1]
import amsel
if not hasattr(amsel, "search_confidence"):
raise RuntimeError(
"[amsel] state_confidence = coverage needs an amsel that scores "
"a state from search records (amsel.search_confidence)"
)
energy = self.state.get_energy()
result = amsel.search_confidence(
np.asarray(self.reactant.r, dtype=float).tolist(),
self._cover_records(),
active_mask=mask,
cell_matrix=np.asarray(self.reactant.box, dtype=float).tolist(),
seed=int(self.config.amsel_direction_seed) + int(self.state.number),
energy=0.0 if energy is None else float(energy),
eps=float(self.config.amsel_relevant_rate_share),
alpha=float(self.config.amsel_category_alpha),
)
logger.info(
"amsel coverage: state %s confidence %.6f, missed-exit probability "
"worst atom %.6f mean %.6f, %d of %d starts returned",
self.state.number,
result.confidence,
result.worst_p_missed,
result.mean_p_missed,
sum(1 for row in rows if row["end"] is not None),
len(rows),
)
_CONFIDENCE[key] = (stamp, float(result.confidence))
return float(result.confidence)
def _geometry(self, process: int) -> tuple[list, list]:
"""Saddle and far minimum of the process a search landed on.
eOn keeps both with the process, in the state's ``procdata``. The
records name the process and hold no copy.
"""
key = (str(self.records.path), int(process))
cached = _GEOMETRY.get(key)
if cached is None:
cached = (
self.state.get_process_saddle(int(process)).r.tolist(),
self.state.get_process_product(int(process)).r.tolist(),
)
_GEOMETRY[key] = cached
return cached
def _off_table_geometry(self, wuid: int, end: dict) -> tuple[list, list]:
"""Saddle and far minimum of a connected search eOn kept no file of.
The record holds the active atoms of both. Every other atom is taken
where the state has it, which is where the direction cover compares
structures: on its centres.
"""
key = (str(self.records.path), -1 - int(wuid))
cached = _GEOMETRY.get(key)
if cached is None:
rows = [int(row) for row in end["atoms"]]
pair = []
for frame in (0, 1):
part = io.loadcon(io.StringIO(self.records.frame_text(wuid, end=True, frame=frame)))
full = np.asarray(self.reactant.r, dtype=float).copy()
full[rows] = part.r
pair.append(full.tolist())
cached = (pair[0], pair[1])
_GEOMETRY[key] = cached
return cached
def _resume(self, wuid: int) -> tuple[Any, np.ndarray] | None:
"""The start already on record for ``wuid``, when its job never left.
A server that stops after recording a start and before it has the
work-unit counter on disk comes back with the same ``wuid``. The
start is then sent as recorded: planning again would take a second
arm and leave the first one out for ever.
"""
start = self.records.pending_start(wuid)
if start is None:
return None
mode = np.zeros(np.asarray(self.reactant.r).shape)
for atom, x, y, z in start["mode"]:
mode[int(atom)] = (x, y, z)
displaced = self.reactant.copy()
displaced.r += float(start["magnitude"]) * mode
logger.warning(
"amsel direction_cover: work unit %s of state %s was recorded and not "
"sent; sending the recorded start",
wuid,
self.state.number,
)
self._arm = None
self._resumed = int(wuid)
return displaced, mode
[docs]
def make_displacement(self, wuid: int | None = None) -> tuple[Any, np.ndarray] | None:
"""The displaced structure and the unit mode of the next start.
``wuid`` is the work unit the start is for. When that work unit
already has a start on record and no result, the recorded start is
returned in place of a new one.
None when amsel has no start for this state. amsel plans the start
from the state's search records: the direction cover is rebuilt from
them in work-unit order and asked for its best free arm. A start is
taken when it is handed out, so a search that fails or is lost has
used its arm. The push is the seed of the arm over all atoms, scaled
to ``displace_magnitude``. :meth:`hand_out` records the start once
the job has a work-unit id.
"""
if self.fallback_reason() is not None:
return None
if wuid is not None:
resumed = self._resume(wuid)
if resumed is not None:
return resumed
mask = self._active_mask()
if mask is None:
return None
import amsel
if not hasattr(amsel, "next_search_start"):
raise RuntimeError(
"[amsel] displacement = direction_cover needs an amsel that "
"plans a start from search records (amsel.next_search_start)"
)
records = self._cover_records()
energy = self.state.get_energy()
start = amsel.next_search_start(
np.asarray(self.reactant.r, dtype=float).tolist(),
records,
active_mask=mask,
cell_matrix=np.asarray(self.reactant.box, dtype=float).tolist(),
seed=int(self.config.amsel_direction_seed) + int(self.state.number),
energy=0.0 if energy is None else float(energy),
)
if start is None:
# Every arm of the cover is recorded or out. Asking again would
# hand out nothing, so the state leaves the cover.
self._fall_back(
f"the direction cover has no arm left after {len(records)} starts "
f"on {sum(mask)} active atoms"
)
return None
mode = np.asarray(start.mode, dtype=float)
mode = mode / np.linalg.norm(mode)
displaced = self.reactant.copy()
displaced.r += float(self.config.disp_magnitude) * mode
self._arm = {
"atom": int(start.atom),
"point": int(start.point),
"direction": [float(x) for x in start.direction],
# The push as applied: each atom it moves and its unit vector
# there. JSON keeps a float so that it reads back the same.
"mode": [
[int(i), float(row[0]), float(row[1]), float(row[2])]
for i, row in enumerate(mode)
if np.any(row != 0.0)
],
"magnitude": float(self.config.disp_magnitude),
}
self._resumed = None
return displaced, mode
[docs]
def hand_out(self, wuid: int, start: Any) -> None:
"""Record the start of :meth:`make_displacement` as sent for ``wuid``.
``start`` is the displaced structure. The record keeps the atoms the
push moves and the push; the rest of the structure is the reactant.
"""
if self._arm is None and self._resumed == int(wuid):
# Already on record: this is the start that was read back.
self._resumed = None
return
if self._arm is None:
raise RuntimeError("no amsel start is waiting for a work-unit id")
rows = [int(row[0]) for row in self._arm["mode"]]
self.records.hand_out(wuid, start, rows, **self._arm)
self._arm = None
[docs]
def register_search(state: Any, result: Any, finds_before: dict) -> bool:
"""Record what an amsel search of ``state`` ended on.
``finds_before`` is ``state.get_proc_own_search_count()`` taken before
the result was registered. The process whose count the result raised is
the one the search landed on, and the search is ``connected``. A result
that raised none landed on no process of the state: its budget ran out,
or it failed, or the client found a connected saddle that eOn left off
the table. That last one is ``connected`` too, with ``off_table`` set, no
process and no rate: the direction led to a saddle, and the saddle is no
exit of the table. The record keeps the active atoms of the structure
the search ended on, and names the directory of its files when eOn was
told to keep them. False when the work unit has no start in the state's
records.
"""
finds = state.get_proc_own_search_count()
raised = [i for i, n in finds.items() if n > finds_before.get(i, 0)]
found = raised[0] if raised else None
records = SearchRecords(state)
wuid = int(result["wuid"])
start = records.pending_start(wuid)
if start is None:
return False
data = result["results"]
termination = int(data.get("termination_reason", 0))
fields: dict[str, Any] = {
"termination_reason": termination,
"process_id": None if found is None else int(found),
}
if found is not None:
proc = state.procs[found]
fields.update(
barrier=float(proc["barrier"]),
rate=float(proc["rate"]),
product=int(proc["product"]),
saddle_energy=float(proc["saddle_energy"]),
product_energy=float(proc["product_energy"]),
)
elif getattr(state.config, "debug_keep_bad_saddles", False):
fields["retained"] = str(state.bad_procdata_path)
saddle = result.get("saddle.con")
product = result.get("product.con")
energy = state.get_energy()
off_table = (
found is None
and termination == 0
and saddle is not None
and product is not None
and energy is not None
)
if off_table:
fields.update(
off_table=True,
saddle_energy=float(data["potential_energy_saddle"]),
product_energy=float(data["potential_energy_product"]),
barrier=float(data["potential_energy_saddle"]) - float(energy),
)
for key in ("force_calls_saddle", "force_calls_minimization"):
if key in data:
fields[key] = int(data[key])
# The atoms worth keeping of the end structure: the active ones when the
# mask of the state is at hand, else the ones the push moved.
mask = _MASKS.get(str(records.path))
rows = [i for i, m in enumerate(mask) if m] if mask else list(start["atoms"])
beyond = None
if saddle is not None:
end = io.loadcon(io.StringIO(saddle.getvalue()))
if off_table:
beyond = io.loadcon(io.StringIO(product.getvalue()))
else:
end = state.get_reactant()
fields["no_end_structure"] = True
kind = outcome_kind(termination, found is not None or off_table)
return records.register(wuid, kind, end, rows, beyond=beyond, **fields)