vibe-sketcherDocumentation

Source code for vibesketcher.server.porosity

"""REST routes for probe-defined porosity plans and the reference estimate (#206).

``plan`` validates a plan and returns the planning record with its refusals;
``estimate`` runs the bounded reference geometric estimate; ``psd-csv``,
``psd-figure`` and ``handoff`` write the source-linked CSV, the PSD figure and
the Viewer handoff record. These read; none changes a document.

``store`` runs the estimate and attaches it to its structure as one edit
checked against the document revision; ``undo`` removes the last stored
estimate while the structure is unchanged. ``stored/{structure}`` lists the
stored estimates marked stale or current, and ``table/{structure}`` writes the
publication table (CSV, SVG or TeX) of a current stored estimate.
Refusals are 422 with ``errors`` and stable ``codes``; a revision conflict or a
stale estimate is 409, a structure without stored estimates 404.
"""

from __future__ import annotations

from typing import Any, Literal

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

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


[docs] class PlanRequest(BaseModel): model_config = ConfigDict(extra="forbid") plan: dict[str, Any]
[docs] class FigureRequest(BaseModel): model_config = ConfigDict(extra="forbid") plan: dict[str, Any] options: dict[str, Any] = Field(default_factory=dict) format: Literal["svg", "pdf", "png"] = "svg" dpi: int = Field(default=300, ge=36, le=1200)
[docs] class HandoffRequest(BaseModel): model_config = ConfigDict(extra="forbid") plan: dict[str, Any] #: Written file names and their SHA-256, recorded in the handoff as given. files: dict[str, str] = Field(default_factory=dict, max_length=20)
[docs] class StoreRequest(RevisionRequest): plan: dict[str, Any] #: The stored estimate's id; ``porosity-N`` when left out. estimate_id: str | None = Field(default=None, max_length=40)
[docs] class UndoRequest(RevisionRequest): structure: str = Field(min_length=1, max_length=64)
def _refused(error: Any) -> HTTPException: codes = [r["code"] for r in error.refusals] status = 422 if {"porosity.revision_conflict", "porosity.stale_estimate"} & set(codes): status = 409 elif codes == ["porosity.no_estimate"]: status = 404 return HTTPException(status, {"errors": [r["message"] for r in error.refusals], "codes": codes}) 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}/porosity", tags=["porosity"]) 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_plan(identifier: str, data: dict[str, Any]) -> tuple[Any, Any]: from vibesketcher.document.porosity import parse_plan try: plan = parse_plan(data) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None found = {s.id: s for s in entry_or_404(identifier).document.periodic_structures} if plan.structure not in found: raise HTTPException(404, "periodic structure not found") return found[plan.structure], plan def estimate(identifier: str, data: dict[str, Any]) -> tuple[Any, dict[str, Any]]: from vibesketcher.document.porosity import PorosityRefused, analyse structure, plan = structure_plan(identifier, data) try: return structure, analyse(structure, plan) except PorosityRefused as error: raise HTTPException( 422, { "errors": [r["message"] for r in error.refusals], "codes": [r["code"] for r in error.refusals], }, ) from None @routes.post("/plan") def porosity_plan(identifier: str, request: PlanRequest) -> dict[str, Any]: """The planning record: plan, radius table, grid ladder, work, refusals; no change.""" from vibesketcher.document.porosity import plan_porosity structure, plan = structure_plan(identifier, request.plan) return plan_porosity(structure, plan) @routes.post("/estimate") def porosity_estimate(identifier: str, request: PlanRequest) -> dict[str, Any]: """The reference geometric estimate (a planning estimate, not adsorption).""" return estimate(identifier, request.plan)[1] @routes.post("/psd-csv") def porosity_psd_csv(identifier: str, request: PlanRequest) -> Response: """PSD and cumulative data as CSV with the structure digest.""" from vibesketcher.document.porosity import psd_csv text = psd_csv(estimate(identifier, request.plan)[1]) return Response(text, media_type="text/csv; charset=utf-8") @routes.post("/psd-figure") def porosity_psd_figure(identifier: str, request: FigureRequest) -> Response: """The PSD figure (SVG, PDF or PNG) with provenance lines.""" from vibesketcher.document.porosity import PorosityRefused from vibesketcher.render import RenderRefused, RenderUnavailable from vibesketcher.render.porosity import PsdFigureOptions, psd_figure _structure, result = estimate(identifier, request.plan) try: options = PsdFigureOptions.model_validate(request.options) data = psd_figure(result, options, request.format, dpi=request.dpi) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None except PorosityRefused as error: raise HTTPException( 422, { "errors": [r["message"] for r in error.refusals], "codes": [r["code"] for r in error.refusals], }, ) from None except (ValueError, RenderRefused) as error: raise HTTPException(422, {"errors": [str(error)]}) from None except RenderUnavailable as error: raise HTTPException(503, {"errors": [str(error)]}) from None media = {"svg": "image/svg+xml", "pdf": "application/pdf", "png": "image/png"} return Response(data, media_type=media[request.format]) @routes.post("/handoff") def porosity_handoff(identifier: str, request: HandoffRequest) -> dict[str, Any]: """The Viewer handoff sidecar: grid parameters, results and digests.""" from vibesketcher.document.porosity import handoff_record structure, result = estimate(identifier, request.plan) return handoff_record(structure, result, request.files) def commit(entry: Entry, document: Any, 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) def structure_of(identifier: str, structure: str) -> Any: found = {s.id: s for s in entry_or_404(identifier).document.periodic_structures} if structure not in found: raise HTTPException(404, "periodic structure not found") return found[structure] @routes.post("/store") def porosity_store(identifier: str, request: StoreRequest) -> DocumentResponse: """Run the estimate and store it on its structure (one revision-checked edit).""" from vibesketcher.document import porosity_store as ps from vibesketcher.document.porosity import PorosityRefused entry = entry_or_404(identifier) if request.revision != entry.document.revision: raise HTTPException(409, {"revision": entry.document.revision}) _structure, result = estimate(identifier, request.plan) try: document, item = ps.store( entry.document, result, revision=request.revision, identifier=request.estimate_id ) except PorosityRefused as error: raise _refused(error) from None except ValueError as error: raise HTTPException(422, {"errors": [str(error)]}) from None response: DocumentResponse = commit( entry, document, request, f"Stored porosity estimate {item['id']} on {item['structure']}", ) return response @routes.post("/undo") def porosity_undo(identifier: str, request: UndoRequest) -> DocumentResponse: """Remove the last stored estimate; refused once the structure changed.""" from vibesketcher.document import porosity_store as ps from vibesketcher.document.porosity import PorosityRefused entry = entry_or_404(identifier) structure_of(identifier, request.structure) try: document = ps.undo(entry.document, request.structure, revision=request.revision) except PorosityRefused as error: raise _refused(error) from None response: DocumentResponse = commit( entry, document, request, f"Removed the last porosity estimate of {request.structure}" ) return response @routes.get("/stored/{structure}") def porosity_stored(identifier: str, structure: str) -> dict[str, Any]: """The stored estimates of a structure (without payloads), each marked stale or not.""" from vibesketcher.document import porosity_store as ps entry = entry_or_404(identifier) found = structure_of(identifier, structure) return {"revision": entry.document.revision, "estimates": ps.summaries(found)} @routes.get("/stored/{structure}/{estimate}") def porosity_stored_one(identifier: str, structure: str, estimate: str) -> dict[str, Any]: """One stored estimate with its full payload, marked stale or not.""" from vibesketcher.document import porosity_store as ps from vibesketcher.document.porosity import PorosityRefused try: return ps.entry(structure_of(identifier, structure), estimate) except PorosityRefused as error: raise _refused(error) from None except KeyError as error: raise HTTPException(404, str(error)) from None @routes.get("/table/{structure}") def porosity_table( identifier: str, structure: str, estimate: str | None = None, format: Literal["csv", "svg", "tex"] = "csv", ) -> Response: """The publication table of a current stored estimate (the latest by default).""" from vibesketcher.document import porosity_store as ps from vibesketcher.document.porosity import PorosityRefused from vibesketcher.render.porosity_table import MEDIA_TYPES, table try: item = ps.fresh(structure_of(identifier, structure), estimate) except PorosityRefused as error: raise _refused(error) from None except KeyError as error: raise HTTPException(404, str(error)) from None return Response(table(item, format), media_type=MEDIA_TYPES[format]) return routes