vibe-sketcherDocumentation

Source code for vibesketcher.server.periodic_graph

"""REST routes for periodic bond graphs and crystal preparation (#200).

Every mutation is checked against the document revision and recorded as an
edit; graph edits and applied preparations have their own undo routes, which
refuse when the structure changed since.
"""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, ConfigDict, Field, ValidationError

from vibesketcher.document.model import Document, PeriodicStructure
from vibesketcher.server.documents import (
    DocumentResponse,
    RevisionRequest,
    _response,
    _with_edit,
)
from vibesketcher.server.store import Conflict, Entry, NotFound, Store


[docs] class GraphEditRequest(RevisionRequest): operations: list[dict[str, Any]] = Field(min_length=1, max_length=1000)
[docs] class PreparationPreviewRequest(BaseModel): """A preview reads the current document; the answer names its revision.""" model_config = ConfigDict(extra="forbid") preparation: dict[str, Any]
[docs] class PreparationRequest(RevisionRequest): preparation: dict[str, Any] source_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
[docs] class PreparationUndoRequest(RevisionRequest): structure: str
def _errors(error: ValidationError) -> list[str]: return [f"{'.'.join(str(x) for x in e['loc'])}: {e['msg']}" for e in error.errors()]
[docs] def router(store: Store) -> APIRouter: routes = APIRouter(prefix="/api/documents/{identifier}/periodic", tags=["periodic graph"]) def entry_or_404(identifier: str) -> Entry: try: return store.get(identifier) except NotFound: raise HTTPException(404, f"no document {identifier!r}") from None def structure_or_404(entry: Entry, structure: str) -> PeriodicStructure: found = {s.id: s for s in entry.document.periodic_structures} if structure not in found: raise HTTPException(404, "periodic structure not found") return found[structure] def check(entry: Entry, revision: int) -> None: if revision != entry.document.revision: raise HTTPException(409, {"revision": entry.document.revision}) def commit(entry: Entry, document: Document, request: RevisionRequest, summary: str) -> Any: try: replaced = store.replace( entry.id, _with_edit(document, request, summary), expected=request.revision, warnings=entry.warnings, ) except Conflict as error: raise HTTPException(409, {"message": str(error), "revision": error.current}) from None return _response(replaced) @routes.get("/{structure}/graph") def graph_report(identifier: str, structure: str) -> dict[str, Any]: """Edge counts by kind, fragments, coordination and coded diagnostics.""" from vibesketcher.document.periodic_graph import report entry = entry_or_404(identifier) try: result = report(structure_or_404(entry, structure)) except ValueError as error: raise HTTPException(422, {"errors": [str(error)]}) from None return {"revision": entry.document.revision, **result} @routes.post("/{structure}/graph") def graph_edit(identifier: str, structure: str, request: GraphEditRequest) -> DocumentResponse: """Add, remove, suppress, perceive, accept or reorder edges as one undoable step.""" from vibesketcher.document.periodic import with_periodic from vibesketcher.document.periodic_graph import apply_graph_edit, parse_graph_edit entry = entry_or_404(identifier) check(entry, request.revision) source = structure_or_404(entry, structure) try: edit = parse_graph_edit({"structure": structure, "operations": request.operations}) edited = apply_graph_edit(source, edit) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None except ValueError as error: raise HTTPException(422, {"errors": [str(error)]}) from None names = ", ".join(dict.fromkeys(o.op for o in edit.operations)) document = with_periodic(entry.document, edited) response: DocumentResponse = commit( entry, document, request, f"Edited the bond graph of {structure} ({names})" ) return response @routes.post("/{structure}/graph/undo") def graph_undo(identifier: str, structure: str, request: RevisionRequest) -> DocumentResponse: from vibesketcher.document.periodic import with_periodic from vibesketcher.document.periodic_graph import undo_graph_edit entry = entry_or_404(identifier) check(entry, request.revision) try: restored = undo_graph_edit(structure_or_404(entry, structure)) except ValueError as error: raise HTTPException(409, {"errors": [str(error)]}) from None document = with_periodic(entry.document, restored) response: DocumentResponse = commit( entry, document, request, f"Undid a bond-graph edit of {structure}" ) return response @routes.post("/preparation/preview") def preparation_preview(identifier: str, request: PreparationPreviewRequest) -> dict[str, Any]: """The derived model, deltas, refusals and provenance; the document is unchanged.""" from vibesketcher.document.periodic_prepare import parse_preparation, preview entry = entry_or_404(identifier) try: preparation = parse_preparation(request.preparation) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None source = structure_or_404(entry, preparation.source) try: result = preview(source, preparation) except ValueError as error: raise HTTPException(422, {"errors": [str(error)]}) from None return {"revision": entry.document.revision, **result} @routes.post("/preparation") def preparation_apply(identifier: str, request: PreparationRequest) -> DocumentResponse: """Add the previewed derived model; refused while any choice is ambiguous.""" from vibesketcher.document.periodic_prepare import apply, parse_preparation entry = entry_or_404(identifier) check(entry, request.revision) try: preparation = parse_preparation(request.preparation) document = apply(entry.document, preparation, source_sha256=request.source_sha256) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None except ValueError as error: raise HTTPException(422, {"errors": [str(error)]}) from None made = document.periodic_structures[-1].id response: DocumentResponse = commit( entry, document, request, f"Prepared {made} from {preparation.source} ({preparation.step.operation})", ) return response @routes.post("/preparation/undo") def preparation_undo(identifier: str, request: PreparationUndoRequest) -> DocumentResponse: """Remove a prepared model again while it is unchanged.""" from vibesketcher.document.periodic_prepare import undo entry = entry_or_404(identifier) check(entry, request.revision) try: document = undo(entry.document, request.structure) except ValueError as error: raise HTTPException(409, {"errors": [str(error)]}) from None response: DocumentResponse = commit( entry, document, request, f"Undid the preparation of {request.structure}" ) return response return routes