vibe-sketcherDocumentation
Source code for vibesketcher.server.diffraction
"""REST routes for powder diffraction planning and overlays (#207).
Every route reads; none changes a document. A calculated pattern comes from
a document's periodic structure or from posted CIF text; a measured pattern
is posted as text or base64 bytes with its file name and stated axis, and
its provenance (SHA-256 of the posted bytes, axis, wavelength, instrument
fields as given) is returned with the points and printed on the overlay.
"""
from __future__ import annotations
import base64
import binascii
from typing import Any, Literal
from fastapi import APIRouter, HTTPException, Response
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from vibesketcher.server.store import Entry, NotFound, Store
[docs]
class PatternRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
structure: str
settings: dict[str, Any] = Field(default_factory=dict)
[docs]
class CifPatternRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
cif: str = Field(max_length=67108864)
settings: dict[str, Any] = Field(default_factory=dict)
block: str | None = None
setting: str | None = None
[docs]
class MeasuredRequest(BaseModel):
"""A measured file: ``text`` or ``data_base64`` (the original bytes), and its name."""
model_config = ConfigDict(extra="forbid")
filename: str = Field(max_length=500)
text: str | None = None
data_base64: str | None = None
settings: dict[str, Any]
points: bool = True
[docs]
class FigureRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
structure: str | None = None
cif: str | None = Field(default=None, max_length=67108864)
block: str | None = None
setting: str | None = None
settings: dict[str, Any] = Field(default_factory=dict)
measured: MeasuredRequest | None = None
options: dict[str, Any] = Field(default_factory=dict)
format: Literal["svg", "pdf", "png"] = "svg"
dpi: int = Field(default=300, ge=36, le=1200)
def _errors(error: ValidationError) -> list[str]:
return [f"{'.'.join(str(x) for x in e['loc'])}: {e['msg']}" for e in error.errors()]
def _measured(request: MeasuredRequest) -> dict[str, Any]:
from vibesketcher.document.measured_patterns import MeasuredSettings, read_measured
if (request.text is None) == (request.data_base64 is None):
raise HTTPException(422, {"errors": ["give the measured file as text or data_base64"]})
if request.text is not None:
data = request.text.encode("utf-8")
else:
try:
data = base64.b64decode(request.data_base64 or "", validate=True)
except (binascii.Error, ValueError):
raise HTTPException(422, {"errors": ["data_base64 is not valid base64"]}) from None
try:
settings = MeasuredSettings.model_validate(request.settings)
return read_measured(data, request.filename, settings)
except ValidationError as error:
raise HTTPException(422, {"errors": _errors(error)}) from None
except ValueError as error:
raise HTTPException(422, {"errors": [str(error)]}) from None
[docs]
def router(store: Store) -> APIRouter:
routes = APIRouter(prefix="/api", tags=["powder diffraction"])
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_pattern(identifier: str, structure: str, settings: dict[str, Any]) -> Any:
from vibesketcher.document.diffraction import calculate, parse_settings
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")
try:
return calculate(found[structure], parse_settings(settings))
except ValidationError as error:
raise HTTPException(422, {"errors": _errors(error)}) from None
except ValueError as error:
raise HTTPException(422, {"errors": [str(error)]}) from None
def cif_pattern(
cif: str, settings: dict[str, Any], block: str | None, setting: str | None
) -> Any:
from vibesketcher.document.diffraction import calculate_from_cif, parse_settings
try:
return calculate_from_cif(cif, parse_settings(settings), block=block, setting=setting)
except ValidationError as error:
raise HTTPException(422, {"errors": _errors(error)}) from None
except ValueError as error:
raise HTTPException(422, {"errors": [str(error)]}) from None
@routes.post("/documents/{identifier}/diffraction/pattern")
def powder_pattern(identifier: str, request: PatternRequest) -> dict[str, Any]:
"""Reflections, intensities, assumptions and the structure digest; no change."""
result: dict[str, Any] = structure_pattern(identifier, request.structure, request.settings)
return result
@routes.post("/diffraction/cif-pattern")
def powder_pattern_cif(request: CifPatternRequest) -> dict[str, Any]:
"""The pattern of posted CIF text, with its occupancies and U_iso/B_iso."""
result: dict[str, Any] = cif_pattern(request.cif, request.settings, request.block,
request.setting) # fmt: skip
return result
@routes.post("/diffraction/measured")
def measured_pattern(request: MeasuredRequest) -> dict[str, Any]:
"""Points and provenance of a measured XY/CSV pattern with a stated axis."""
result = _measured(request)
if not request.points:
result = {"kind": result["kind"], "provenance": result["provenance"]}
return result
@routes.post("/documents/{identifier}/diffraction/figure")
def powder_figure(identifier: str, request: FigureRequest) -> Response:
"""Measured against calculated (SVG, PDF or PNG) with ticks and provenance."""
from vibesketcher.render import RenderRefused, RenderUnavailable
from vibesketcher.render.diffraction import OverlayOptions, overlay_figure
if (request.structure is None) == (request.cif is None):
raise HTTPException(422, {"errors": ["give structure or cif, not both"]})
if request.structure is not None:
calculated = structure_pattern(identifier, request.structure, request.settings)
else:
entry_or_404(identifier)
assert request.cif is not None
calculated = cif_pattern(request.cif, request.settings, request.block,
request.setting) # fmt: skip
measured = _measured(request.measured) if request.measured is not None else None
try:
options = OverlayOptions.model_validate(request.options)
data = overlay_figure(calculated, measured, options, request.format, dpi=request.dpi)
except ValidationError as error:
raise HTTPException(422, {"errors": _errors(error)}) 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])
return routes