vibe-sketcherDocumentation
Source code for vibesketcher.server.interfaces
"""REST routes for interfaces, stacking faults and planned extended defects (#197).
Building goes through ``POST /api/documents/{id}/periodic/build`` with a
``kind: interface`` or ``kind: stacking_fault`` recipe (revision-checked,
recorded as an edit and undone like any build). These routes rank coincidence
cells, preview a build and plan grain boundaries or dislocations without
changing the document.
"""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError
from vibesketcher.server.store import NotFound, Store
[docs]
class InterfaceMatchesRequest(BaseModel):
"""Two parent slabs of the document and the search bounds."""
model_config = ConfigDict(extra="forbid")
bottom: str
top: str
max_area: float = Field(default=150.0, gt=0, le=5000)
max_strain: float = Field(default=0.05, ge=0, le=0.15)
#: Rotation of the top phase in degrees; null searches every rotation.
twist_deg: float | None = 0.0
angle_tolerance_deg: float = Field(default=0.5, gt=0, le=30)
top_flip: bool = False
max_candidates: int = Field(default=20, ge=1, le=100)
[docs]
class ExtendedPreviewRequest(BaseModel):
"""A preview reads the current document; the answer names its revision."""
model_config = ConfigDict(extra="forbid")
recipe: dict[str, Any]
#: Include the built structure in the answer (it can be large).
structure: bool = False
[docs]
class DefectPlanRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
plan: dict[str, Any]
#: Optional document holding the plan's source bulk structure.
document: str | None = None
[docs]
def router(store: Store) -> APIRouter:
routes = APIRouter(prefix="/api", tags=["interfaces"])
def _document(identifier: str) -> Any:
try:
return store.get(identifier)
except NotFound:
raise HTTPException(404, f"no document {identifier!r}") from None
@routes.post("/documents/{identifier}/periodic/interface/matches")
def interface_matches(identifier: str, request: InterfaceMatchesRequest) -> dict[str, Any]:
"""Ranked commensurate coincidence cells (Zur and McGill 1984); nothing is built."""
from vibesketcher.document.interfaces import interface_matches as matches
entry = _document(identifier)
try:
result = matches(entry.document, **request.model_dump())
except ValueError as error:
raise HTTPException(422, {"errors": [str(error)]}) from None
return {"revision": entry.document.revision, **result}
@routes.post("/documents/{identifier}/periodic/extended/preview")
def extended_preview(identifier: str, request: ExtendedPreviewRequest) -> dict[str, Any]:
"""Interface or stacking-fault record and diagnostics, or the refusal, unstored."""
from vibesketcher.document.interfaces import (
InterfaceRecipe,
StackingFaultRecipe,
preview,
)
entry = _document(identifier)
adapter: TypeAdapter[InterfaceRecipe | StackingFaultRecipe] = TypeAdapter(
InterfaceRecipe | StackingFaultRecipe
)
try:
recipe = adapter.validate_python(request.recipe)
except ValidationError as error:
raise HTTPException(422, {"errors": [e["msg"] for e in error.errors()]}) from None
if recipe.identifier in {s.id for s in entry.document.periodic_structures}:
raise HTTPException(422, {"errors": [f"{recipe.identifier!r} already exists"]})
result = preview(recipe, entry.document)
if not request.structure:
result.pop("structure", None)
return {"revision": entry.document.revision, **result}
@routes.post("/periodic/extended-defects/plan")
def plan_defect(request: DefectPlanRequest) -> dict[str, Any]:
"""A planned-only grain-boundary or dislocation record, or coded refusals."""
from vibesketcher.document.interfaces import plan_extended_defect
document = _document(request.document).document if request.document else None
return plan_extended_defect(request.plan, document)
return routes