vibe-sketcherDocumentation
Source code for vibesketcher.server.symmetry_ops
"""REST routes for adopting symmetry, enantiomorphs and subgroup descent (#199).
Previews read the current document and name its revision; every mutation
names the revision it read (409 when stale) and is recorded as an edit.
``.../symmetry/undo`` reverts the last adoption of a structure, or removes an
enantiomorph or subgroup structure that is unchanged since it was derived.
``.../symmetry/drop-displacements`` drops measured displacement tensors with a
recorded reason, which edits that cannot transform them require.
"""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, ConfigDict, Field
from vibesketcher.document.model import Document, PeriodicStructure
from vibesketcher.server.documents import (
DocumentResponse,
RevisionRequest,
_response,
_with_edit,
)
from vibesketcher.server.store import Conflict, Entry, NotFound, Store
_ID = r"^[A-Za-z][A-Za-z0-9_-]{0,63}$"
[docs]
class AdoptOptions(BaseModel):
model_config = ConfigDict(extra="forbid")
symprec: float = Field(default=1e-3, gt=0, le=1)
idealize: bool = False
diagnostic_symprec: float = Field(default=0.1, gt=0, le=1)
[docs]
class AdoptRequest(RevisionRequest):
symprec: float = Field(default=1e-3, gt=0, le=1)
idealize: bool = False
diagnostic_symprec: float = Field(default=0.1, gt=0, le=1)
#: The preview's ``source_sha256``: refuses when the structure changed since.
source_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
[docs]
class EnantiomorphOptions(BaseModel):
model_config = ConfigDict(extra="forbid")
symprec: float = Field(default=1e-3, gt=0, le=1)
diagnostic_symprec: float = Field(default=0.1, gt=0, le=1)
[docs]
class EnantiomorphRequest(RevisionRequest):
identifier: str = Field(pattern=_ID)
symprec: float = Field(default=1e-3, gt=0, le=1)
diagnostic_symprec: float = Field(default=0.1, gt=0, le=1)
[docs]
class DescendOptions(BaseModel):
model_config = ConfigDict(extra="forbid")
transformation: str = Field(min_length=5, max_length=200)
subgroup: str = Field(min_length=1, max_length=40)
symprec: float = Field(default=1e-3, gt=0, le=1)
[docs]
class DescendRequest(RevisionRequest):
identifier: str = Field(pattern=_ID)
transformation: str = Field(min_length=5, max_length=200)
subgroup: str = Field(min_length=1, max_length=40)
symprec: float = Field(default=1e-3, gt=0, le=1)
[docs]
class DropDisplacementsRequest(RevisionRequest):
#: Recorded in ``provenance["displacement_parameters_dropped"]``.
reason: str = Field(min_length=1, max_length=500)
[docs]
def router(store: Store) -> APIRouter:
routes = APIRouter(
prefix="/api/documents/{identifier}/periodic/{structure}/symmetry",
tags=["periodic symmetry"],
)
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_or_404(entry: Entry, structure: str) -> PeriodicStructure:
found = {s.id: s for s in entry.document.periodic_structures}
if structure not in found:
raise HTTPException(404, "periodic structure not found")
return found[structure]
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)
def refused(error: Exception) -> HTTPException:
from vibesketcher.document.symmetry import SymmetryUnavailable
status = 503 if isinstance(error, SymmetryUnavailable) else 422
return HTTPException(status, {"errors": [str(error)]})
@routes.post("/adopt/preview")
def adopt_preview(identifier: str, structure: str, request: AdoptOptions) -> dict[str, Any]:
"""Detected group, displacements, orbit merges/splits and near-special sites."""
from vibesketcher.document.symmetry import SymmetryUnavailable
from vibesketcher.document.symmetry_ops import preview_adopt
entry = entry_or_404(identifier)
try:
result = preview_adopt(structure_or_404(entry, structure), **request.model_dump())
except (ValueError, SymmetryUnavailable) as error:
raise refused(error) from None
return {"revision": entry.document.revision, **result}
@routes.post("/adopt")
def adopt(identifier: str, structure: str, request: AdoptRequest) -> DocumentResponse:
"""Record the detected group as adopted (positions move only with idealize)."""
from vibesketcher.document.periodic import with_periodic
from vibesketcher.document.symmetry import SymmetryUnavailable
from vibesketcher.document.symmetry_ops import adopt as adopt_symmetry
entry = entry_or_404(identifier)
check(entry, request.revision)
try:
adopted = adopt_symmetry(
structure_or_404(entry, structure),
symprec=request.symprec,
idealize=request.idealize,
diagnostic_symprec=request.diagnostic_symprec,
source_sha256=request.source_sha256,
)
except (ValueError, SymmetryUnavailable) as error:
raise refused(error) from None
record: Any = adopted.provenance["symmetry_edit"]
group = record["space_group"]
how = "idealised" if request.idealize else "positions kept"
response: DocumentResponse = commit(
entry,
with_periodic(entry.document, adopted),
request,
f"Adopted {group['international']} for {structure} ({how})",
)
return response
@routes.post("/enantiomorph/preview")
def enantiomorph_preview(
identifier: str, structure: str, request: EnantiomorphOptions
) -> dict[str, Any]:
from vibesketcher.document.symmetry import SymmetryUnavailable
from vibesketcher.document.symmetry_ops import preview_enantiomorph
entry = entry_or_404(identifier)
try:
result = preview_enantiomorph(
structure_or_404(entry, structure), **request.model_dump()
)
except (ValueError, SymmetryUnavailable) as error:
raise refused(error) from None
return {"revision": entry.document.revision, **result}
@routes.post("/enantiomorph")
def enantiomorph(
identifier: str, structure: str, request: EnantiomorphRequest
) -> DocumentResponse:
"""Add the inverted structure with its group transformed to the enantiomorph."""
from vibesketcher.document.symmetry import SymmetryUnavailable
from vibesketcher.document.symmetry_ops import add_derived
from vibesketcher.document.symmetry_ops import enantiomorph as invert
entry = entry_or_404(identifier)
check(entry, request.revision)
try:
made = invert(
structure_or_404(entry, structure),
identifier=request.identifier,
symprec=request.symprec,
diagnostic_symprec=request.diagnostic_symprec,
)
document = add_derived(entry.document, made)
except (ValueError, SymmetryUnavailable) as error:
raise refused(error) from None
response: DocumentResponse = commit(
entry, document, request, f"Added {request.identifier}, the enantiomorph of {structure}"
)
return response
@routes.post("/descend/preview")
def descend_preview(identifier: str, structure: str, request: DescendOptions) -> dict[str, Any]:
from vibesketcher.document.symmetry import SymmetryUnavailable
from vibesketcher.document.symmetry_ops import preview_descend
entry = entry_or_404(identifier)
try:
result = preview_descend(structure_or_404(entry, structure), **request.model_dump())
except (ValueError, SymmetryUnavailable) as error:
raise refused(error) from None
return {"revision": entry.document.revision, **result}
@routes.post("/descend")
def descend(identifier: str, structure: str, request: DescendRequest) -> DocumentResponse:
"""Add the structure described in a subgroup, given (P, p) and its Hall symbol."""
from vibesketcher.document.symmetry import SymmetryUnavailable
from vibesketcher.document.symmetry_ops import add_derived
from vibesketcher.document.symmetry_ops import descend as descend_to
entry = entry_or_404(identifier)
check(entry, request.revision)
try:
made = descend_to(
structure_or_404(entry, structure),
transformation=request.transformation,
subgroup=request.subgroup,
identifier=request.identifier,
symprec=request.symprec,
)
document = add_derived(entry.document, made)
except (ValueError, SymmetryUnavailable) as error:
raise refused(error) from None
response: DocumentResponse = commit(
entry,
document,
request,
f"Added {request.identifier}, {structure} in subgroup {request.subgroup}",
)
return response
@routes.post("/undo")
def undo(identifier: str, structure: str, request: RevisionRequest) -> DocumentResponse:
from vibesketcher.document.symmetry_ops import undo as undo_edit
entry = entry_or_404(identifier)
check(entry, request.revision)
structure_or_404(entry, structure)
try:
document = undo_edit(entry.document, structure)
except ValueError as error:
raise HTTPException(409, {"errors": [str(error)]}) from None
response: DocumentResponse = commit(
entry, document, request, f"Undid the symmetry edit of {structure}"
)
return response
@routes.post("/drop-displacements")
def drop_displacements(
identifier: str, structure: str, request: DropDisplacementsRequest
) -> DocumentResponse:
"""Drop measured displacement tensors explicitly; the reason and record are kept."""
from vibesketcher.document.displacements import drop_in_document
entry = entry_or_404(identifier)
check(entry, request.revision)
structure_or_404(entry, structure)
try:
document = drop_in_document(entry.document, structure, request.reason)
except ValueError as error:
raise HTTPException(422, {"errors": [str(error)]}) from None
response: DocumentResponse = commit(
entry, document, request, f"Dropped the displacement tensors of {structure}"
)
return response
return routes