vibe-sketcherDocumentation

Source code for vibesketcher.server.periodic_recipes

"""REST routes for periodic scan, phonon and free-energy recipes and EOS analysis (#208).

Planning reads a document and changes nothing: the answer is the plan, the
generated inputs (one per point plus ``run_all.py``) and the document revision
it was planned against, or the refusal. Analysis is stateless.
"""

from __future__ import annotations

import base64
import binascii
from typing import Any

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

from vibesketcher.server.store import NotFound, Store


[docs] class RecipePlanRequest(BaseModel): model_config = ConfigDict(extra="forbid") #: volume_scan, coordinate_scan, phonons or free_energy recipe. recipe: dict[str, Any]
[docs] class EosAnalyseRequest(BaseModel): """A vibe-eos-table/1 table, or a volume-scan plan with its results.""" model_config = ConfigDict(extra="forbid") table: dict[str, Any] | None = None plan: dict[str, Any] | None = None #: scan-results.json written by the plan's run_all.py. results: dict[str, Any] | None = None #: Point label to a base64 result QVF. qvfs: dict[str, str] = Field(default_factory=dict, max_length=100) drop_unconverged: bool = False #: Include the E(V) plot as SVG text. svg: bool = False title: str | None = Field(default=None, max_length=200)
[docs] class FrequencyRequest(BaseModel): """Explicit frequencies for an independent harmonic free-energy check.""" model_config = ConfigDict(extra="forbid") frequencies_cm1: list[float] = Field(min_length=1, max_length=100000) weights: list[float] | None = None temperatures_k: list[float] = Field(default_factory=lambda: [300.0], max_length=500)
[docs] def router(store: Store) -> APIRouter: routes = APIRouter(prefix="/api", tags=["periodic recipes"]) @routes.get("/periodic/recipes/capabilities") def capabilities() -> dict[str, Any]: """The pinned engine's periodic capability table.""" from vibesketcher.document.periodic_capabilities import table return table() @routes.post("/documents/{identifier}/periodic/recipes/plan") def plan(identifier: str, request: RecipePlanRequest) -> dict[str, Any]: """Plan a recipe: inputs and plan, or a plan with its engine refusal, or a refusal.""" from vibesketcher.document.periodic_recipes import plan_or_refusal try: entry = store.get(identifier) except NotFound: raise HTTPException(404, f"no document {identifier!r}") from None try: result = plan_or_refusal(entry.document, request.recipe) except ValidationError as error: raise HTTPException(422, {"errors": [e["msg"] for e in error.errors()]}) from None except ValueError as error: raise HTTPException(422, {"errors": [str(error)]}) from None return {"revision": entry.document.revision, **result} @routes.post("/periodic/recipes/eos") def analyse(request: EosAnalyseRequest) -> dict[str, Any]: """Birch-Murnaghan and Vinet fits with flags, optionally with the SVG plot.""" from vibesketcher.document import eos from vibesketcher.document.periodic_recipes import RecipePlan, eos_table try: if request.table is not None: data = dict(request.table) if request.drop_unconverged: data["drop_unconverged"] = True table = eos.EosTable.model_validate(data) elif request.plan is not None: blobs = {k: base64.b64decode(v, validate=True) for k, v in request.qvfs.items()} table = eos_table( RecipePlan.model_validate(request.plan), request.results, blobs, drop_unconverged=request.drop_unconverged, ) else: raise ValueError("give a table, or a plan with results or qvfs") report = eos.analyse(table) except ValidationError as error: raise HTTPException(422, {"errors": [e["msg"] for e in error.errors()]}) from None except (ValueError, binascii.Error) as error: raise HTTPException(422, {"errors": [str(error)]}) from None if request.svg: report["svg"] = eos.plot_svg(report, title=request.title) return report @routes.post("/periodic/recipes/harmonic") def harmonic(request: FrequencyRequest) -> dict[str, Any]: """Harmonic ZPE, F, S and C_V from given frequencies; imaginary modes are refused.""" from vibesketcher.document.periodic_recipes import harmonic_free_energy try: rows = [ harmonic_free_energy(request.frequencies_cm1, t, request.weights) for t in request.temperatures_k ] except ValueError as error: raise HTTPException(422, {"errors": [str(error)]}) from None return {"units": {"energy": "eV per cell of the frequencies", "entropy": "eV/K"}, "temperatures": rows} # fmt: skip return routes