vibe-sketcherDocumentation
Source code for vibesketcher.document.build_review
"""Preview, revision-checked apply and undo for periodic build recipes (#201).
:func:`vibesketcher.document.solid_build.build` adds a structure directly.
This module puts the same recipes (every kind in ``AnyRecipe``) behind the
preview -> apply -> undo contract of the other reviewed features
(:mod:`vibesketcher.document.guest_loading`,
:mod:`vibesketcher.document.periodic_prepare`):
* :func:`preview_build` runs the recipe against a document and returns what
would be added (formula, site count, cell, builder warnings), refusals with
stable codes, the recipe digest and the digests of the document structures
and species the recipe reads. The document is not changed.
* :func:`apply_build` adds the structure only when the document revision, the
recipe digest and (optionally) the input digest still match the preview. The
structure equals :func:`~vibesketcher.document.solid_build.build`'s except for
a ``provenance["build_review"]`` record that makes it undoable.
* :func:`undo_build` removes such a structure again while it is unchanged
since the build and nothing else in the document refers to it.
The document schema does not change: the record lives in the provenance.
"""
from __future__ import annotations
import hashlib
import json
from collections.abc import Iterator
from typing import Any
from vibesketcher.chem.nanostructures import hill_formula
from vibesketcher.document.model import Document, PeriodicStructure
from vibesketcher.document.periodic_prepare import content_digest
from vibesketcher.document.solid_build import AnyRecipe
#: The provenance key of the record an applied build carries.
RECORD = "build_review"
#: Stable refusal and notice codes of build preview, apply and undo.
CODES: dict[str, str] = {
"build.identifier_exists": "a periodic structure with the new ID already exists",
"build.source_not_found": "the recipe names a periodic structure the document does not have",
"build.refused": "the builder refused these parameters; the message says why",
"build.invalid": "the recipe cannot be built as given; the message says why",
"build.unavailable": "the recipe needs an optional extra that is not installed",
"build.warning": "the builder recorded a warning for the result",
"build.stale_revision": "the document changed since the preview",
"build.recipe_changed": "the recipe differs from the previewed one",
"build.inputs_changed": "a structure or species the recipe reads changed since the preview",
"build.undo.not_found": "no periodic structure with that ID",
"build.undo.not_reviewed": "the structure was not added through a reviewed build",
"build.undo.changed": "the structure changed after it was built",
"build.undo.dependents": "other parts of the document refer to the structure",
}
#: Recipe fields that name an existing periodic structure the recipe reads.
_SOURCE_FIELDS = ("source", "bottom", "top")
[docs]
class BuildReviewRefused(ValueError):
"""A preview, apply or undo the build review refuses; ``code`` is stable."""
def __init__(self, code: str, message: str) -> None:
super().__init__(f"[{code}] {message}")
self.code = code
self.detail = message
def _digest(data: Any) -> str:
text = json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
return hashlib.sha256(text.encode()).hexdigest()
[docs]
def recipe_digest(recipe: AnyRecipe) -> str:
"""SHA-256 of the parsed recipe with every default filled in.
Two requests that parse to the same recipe have the same digest, so a
client may omit defaults in one and spell them out in the other.
"""
return _digest(recipe.model_dump(mode="json"))
def _strings(value: Any, *, keys: bool = False) -> Iterator[str]:
"""Every string value in a JSON value, and with ``keys`` every mapping key."""
if isinstance(value, str):
yield value
elif isinstance(value, dict):
for key, item in value.items():
if keys:
yield str(key)
yield from _strings(item, keys=keys)
elif isinstance(value, list | tuple):
for item in value:
yield from _strings(item, keys=keys)
[docs]
def inputs(document: Document, recipe: AnyRecipe) -> dict[str, dict[str, str]]:
"""Digests of the document structures and species the recipe names.
Every string in the recipe (other than its own ``identifier``) that is the
ID of a periodic structure or a species counts as an input; naming one
more than the builder reads only makes the check stricter.
"""
named = set(_strings(recipe.model_dump(mode="json", exclude={"identifier"})))
structures = {s.id: content_digest(s) for s in document.periodic_structures if s.id in named}
species = {s.id: _digest(s.model_dump(mode="json")) for s in document.species if s.id in named}
return {
"structures": dict(sorted(structures.items())),
"species": dict(sorted(species.items())),
}
def _cell(structure: PeriodicStructure) -> dict[str, Any]:
import numpy as np
lattice = np.array(structure.lattice_angstrom, dtype=float)
lengths = np.linalg.norm(lattice, axis=1)
def angle(i: int, j: int) -> float:
cosine = float(lattice[i] @ lattice[j] / (lengths[i] * lengths[j]))
return round(float(np.degrees(np.arccos(np.clip(cosine, -1.0, 1.0)))), 6)
return {
"lattice_angstrom": [[round(float(x), 8) for x in row] for row in lattice],
"lengths_angstrom": [round(float(x), 6) for x in lengths],
"angles_deg": [angle(1, 2), angle(0, 2), angle(0, 1)],
"volume_angstrom3": round(float(abs(np.linalg.det(lattice))), 6),
"pbc": list(structure.pbc),
"dimension": sum(structure.pbc),
"cell_setting": structure.cell_setting,
}
[docs]
def summary(structure: PeriodicStructure) -> dict[str, Any]:
"""What a reviewer reads before adding a structure."""
return {
"identifier": structure.id,
"formula": hill_formula(s.symbol for s in structure.sites),
"sites": len(structure.sites),
"bonds": len(structure.bonds),
"charge": structure.charge,
"multiplicity": structure.multiplicity,
"cell": _cell(structure),
}
def _warnings(value: Any) -> Iterator[str]:
"""Every entry of a ``warnings`` list anywhere in a provenance record."""
if isinstance(value, dict):
for key, item in value.items():
if key == "warnings" and isinstance(item, list):
for entry in item:
yield entry if isinstance(entry, str) else json.dumps(entry, sort_keys=True)
else:
yield from _warnings(item)
elif isinstance(value, list):
for item in value:
yield from _warnings(item)
def _coded(code: str, message: str) -> dict[str, Any]:
return {"code": code, "message": message, "sites": []}
def _classify(error: Exception) -> dict[str, Any]:
from vibesketcher.chem.periodic_geometry import BuildRefused
from vibesketcher.document.symmetry import SymmetryUnavailable
code = getattr(error, "code", None)
if isinstance(code, str) and code:
return _coded(code, str(getattr(error, "detail", None) or error))
if isinstance(error, SymmetryUnavailable | ImportError):
return _coded("build.unavailable", str(error))
if isinstance(error, BuildRefused):
return _coded("build.refused", str(error))
return _coded("build.invalid", str(error))
def _build(document: Document, recipe: AnyRecipe) -> tuple[PeriodicStructure | None, list[Any]]:
from vibesketcher.document.solid_build import apply_recipe
from vibesketcher.document.symmetry import SymmetryUnavailable
existing = {s.id for s in document.periodic_structures}
refusals: list[dict[str, Any]] = []
if recipe.identifier in existing:
refusals.append(
_coded(
"build.identifier_exists",
f"periodic structure {recipe.identifier!r} already exists",
)
)
for name in _SOURCE_FIELDS:
value = getattr(recipe, name, None)
if isinstance(value, str) and value not in existing:
refusals.append(
_coded("build.source_not_found", f"periodic structure {value!r} not found")
)
if refusals:
return None, refusals
try:
return apply_recipe(document, recipe), []
except (ValueError, SymmetryUnavailable, ImportError) as error:
return None, [_classify(error)]
[docs]
def preview_build(
document: Document, recipe: AnyRecipe, *, structure: bool = False
) -> dict[str, Any]:
"""The would-be structure's summary, refusals and digests; ``document`` is unchanged.
``structure=True`` adds the full derived structure as ``derived`` (the
browser draws it); the summary is always there when the build succeeds.
"""
made, refusals = _build(document, recipe)
used = inputs(document, recipe)
notices = [] if made is None else [
_coded("build.warning", text) for text in dict.fromkeys(_warnings(made.provenance))
] # fmt: skip
return {
"revision": document.revision,
"kind": recipe.kind,
"identifier": recipe.identifier,
"applicable": made is not None,
"refusals": refusals,
"notices": notices,
"summary": None if made is None else summary(made),
"recipe_sha256": recipe_digest(recipe),
"inputs": used,
"inputs_sha256": _digest(used),
"derived_sha256": None if made is None else content_digest(made),
"derived": (
made.model_dump(mode="json", exclude_none=True)
if made is not None and structure
else None
), # fmt: skip
"codes": CODES,
}
[docs]
def apply_build(
document: Document,
recipe: AnyRecipe,
*,
recipe_sha256: str,
revision: int | None = None,
inputs_sha256: str | None = None,
) -> Document:
"""Add a previewed build to a copy of ``document``.
Refused (:class:`BuildReviewRefused`) when ``revision`` is given and is not
the document's, when the recipe's digest is not ``recipe_sha256``, when
``inputs_sha256`` is given and the inputs changed, or when the preview
would refuse. The added structure is the plain build's plus the record
:func:`undo_build` checks.
"""
from vibesketcher.document.periodic import with_periodic
if revision is not None and revision != document.revision:
raise BuildReviewRefused(
"build.stale_revision",
f"the document is at revision {document.revision}, the preview at {revision}",
)
digest = recipe_digest(recipe)
if digest != recipe_sha256:
raise BuildReviewRefused("build.recipe_changed", "the recipe differs from the preview")
used = inputs(document, recipe)
if inputs_sha256 is not None and _digest(used) != inputs_sha256:
raise BuildReviewRefused(
"build.inputs_changed", "a structure or species the recipe reads changed"
)
made, refusals = _build(document, recipe)
if made is None:
first = refusals[0]
raise BuildReviewRefused(first["code"], first["message"])
record = {
"kind": recipe.kind,
"recipe_sha256": digest,
"inputs": used,
"derived_sha256": content_digest(made),
}
provenance = {**made.provenance, RECORD: record}
return with_periodic(document, made.model_copy(update={"provenance": provenance}))
[docs]
def dependents(document: Document, identifier: str) -> list[str]:
"""Where else the document names periodic structure ``identifier``.
Other structures' ``parent`` and provenance (derived cells, slabs,
preparations, loadings, interfaces), surfaces and the solid-state
reaction scheme. Each entry is a readable location.
"""
found: list[str] = []
for other in document.periodic_structures:
if other.id == identifier:
continue
if other.parent == identifier or identifier in set(_strings(other.provenance, keys=True)):
found.append(f"periodic structure {other.id}")
for name in ("surfaces", "solid_participants", "solid_steps"):
for item in getattr(document, name):
if identifier in set(_strings(item.model_dump(mode="json"))):
found.append(f"{name[:-1].replace('_', ' ')} {getattr(item, 'id', '?')}")
return found
[docs]
def undo_build(document: Document, identifier: str) -> Document:
"""Remove a reviewed build again, while it is unchanged and nothing depends on it."""
found = {s.id: s for s in document.periodic_structures}
structure = found.get(identifier)
if structure is None:
raise BuildReviewRefused("build.undo.not_found", f"no periodic structure {identifier!r}")
record = structure.provenance.get(RECORD)
if not isinstance(record, dict) or not isinstance(record.get("derived_sha256"), str):
raise BuildReviewRefused(
"build.undo.not_reviewed", f"{identifier} was not added through a reviewed build"
)
if record["derived_sha256"] != content_digest(structure):
raise BuildReviewRefused(
"build.undo.changed", f"{identifier} changed after it was built; undo refused"
)
users = dependents(document, identifier)
if users:
raise BuildReviewRefused(
"build.undo.dependents", f"{identifier} is used by {', '.join(users)}; undo refused"
)
data = document.to_json_data()
data["periodic_structures"] = [
s.model_dump(mode="json", exclude_none=True)
for s in document.periodic_structures
if s.id != identifier
]
return Document.model_validate(data)