vibe-sketcherDocumentation

Source code for vibesketcher.server.polymer_packing

"""REST routes for amorphous polymer boxes and membranes (#205).

A preview reads the current document and changes nothing; applying is
checked against the document revision and recorded as an edit; an applied
packing has an undo route that refuses when the packed model changed since.
Refusals in a preview are returned with ``applicable: false`` and stable codes.
"""

from __future__ import annotations

from typing import Any

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

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


[docs] class PackingPreviewRequest(BaseModel): model_config = ConfigDict(extra="forbid") packing: dict[str, Any]
[docs] class PackingRequest(RevisionRequest): packing: dict[str, Any]
[docs] class PackingUndoRequest(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/polymer", tags=["periodic polymer"] ) 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 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.post("/preview") def packing_preview(identifier: str, request: PackingPreviewRequest) -> dict[str, Any]: """Chains, checks, rejections, refusals and the packed model; no change.""" from vibesketcher.document.polymer_packing import parse_packing, preview entry = entry_or_404(identifier) try: packing = parse_packing(request.packing) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None result = preview(packing, entry.document) return {"revision": entry.document.revision, **result} @routes.post("") def packing_apply(identifier: str, request: PackingRequest) -> DocumentResponse: """Add the packed model; refused while the preview has refusals.""" from vibesketcher.document.polymer_packing import apply, parse_packing entry = entry_or_404(identifier) check(entry, request.revision) try: packing = parse_packing(request.packing) document = apply(entry.document, packing) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None except ValueError as error: raise HTTPException(422, {"errors": [str(error)]}) from None response: DocumentResponse = commit( entry, document, request, f"Packed polymer chains into {packing.identifier}" ) return response @routes.post("/undo") def packing_undo(identifier: str, request: PackingUndoRequest) -> DocumentResponse: """Remove a packed model again while it is unchanged.""" from vibesketcher.document.polymer_packing 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 polymer packing of {request.structure}" ) return response return routes