vibe-sketcherDocumentation
Source code for vibesketcher.document.diffraction_model
"""Powder patterns stored in a document: the ``diffraction_patterns`` records (#207).
A *measured* record keeps what :func:`vibesketcher.document.measured_patterns.read_measured`
read: the SHA-256 and size of the original bytes, the stated axis, intensity unit and
wavelength, the instrument fields and header lines exactly as given, and the points.
The original bytes themselves are not kept; the digest names them.
A *calculated* record keeps a :func:`vibesketcher.document.diffraction.calculate` result
of one periodic structure with that structure's digest (``structure_sha256``). It is
*stale* once the structure changes or is removed; stale records are listed as such and
refused by the overlay and export writers (:mod:`vibesketcher.document.diffraction_store`).
The structure reference is deliberately not required to resolve: removing a structure
leaves its patterns stale rather than making the document invalid.
The records are additive: a document without patterns serialises as before.
"""
from __future__ import annotations
from typing import Annotated, Literal, Self
from pydantic import BaseModel, ConfigDict, Field, JsonValue, StringConstraints, model_validator
#: Stored patterns one document may hold.
MAX_PATTERNS = 32
#: Points one stored pattern may hold (the reader accepts more; storing refuses).
MAX_STORED_POINTS = 200_000
#: Points all stored patterns of a document may hold together.
MAX_DOCUMENT_POINTS = 1_000_000
#: Reflections one stored calculated pattern may hold.
MAX_STORED_REFLECTIONS = 20_000
_Identifier = Annotated[str, StringConstraints(pattern=r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")]
_Sha256 = Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")]
_Line = Annotated[str, StringConstraints(max_length=500)]
_Finite = Annotated[float, Field(allow_inf_nan=False)]
PatternAxis = Literal["two_theta_deg", "d_angstrom", "q_inv_angstrom"]
class _Strict(BaseModel):
model_config = ConfigDict(extra="forbid", populate_by_name=True, validate_assignment=True)
[docs]
class MeasuredSource(_Strict):
"""Provenance of a measured import, as read; nothing is inferred."""
file_name: Annotated[str, StringConstraints(min_length=1, max_length=255)]
sha256: _Sha256 = Field(description="SHA-256 of the original file bytes.")
bytes: int = Field(ge=0, description="Size of the original file in bytes.")
encoding: Literal["utf-8", "latin-1"]
format: Literal["xy", "csv"]
instrument: dict[str, Annotated[str, StringConstraints(max_length=500)]] = Field(
default_factory=dict, max_length=64, description="Instrument fields exactly as given."
)
sample: _Line | None = None
header: list[_Line] = Field(
default_factory=list, max_length=200, description="The file's own comment lines."
)
columns: list[Annotated[str, StringConstraints(max_length=80)]] | None = Field(
default=None, max_length=8, description="A column-name row, when the file had one."
)
[docs]
class DiffractionPattern(_Strict):
"""A measured or calculated powder pattern stored in the document."""
id: _Identifier
kind: Literal["measured", "calculated"]
label: _Line | None = None
axis: PatternAxis = Field(description="The x axis of ``x``; a calculated curve is 2theta.")
intensity_unit: Literal["counts", "counts_per_second", "arbitrary", "relative"]
wavelength_angstrom: float | None = Field(
default=None, gt=0.01, le=100, allow_inf_nan=False, description="Absent when not stated."
)
x: list[_Finite] = Field(default_factory=list, max_length=MAX_STORED_POINTS)
intensity: list[_Finite] = Field(default_factory=list, max_length=MAX_STORED_POINTS)
esd: list[_Finite] | None = Field(default=None, max_length=MAX_STORED_POINTS)
measured: MeasuredSource | None = Field(
default=None, description="The measured file's provenance (measured records only)."
)
structure: _Identifier | None = Field(
default=None, description="The periodic structure a calculated record belongs to."
)
structure_sha256: _Sha256 | None = Field(
default=None, description="That structure's digest when the pattern was calculated."
)
result: dict[str, JsonValue] | None = Field(
default=None,
description="The calculated result (reflections, settings, assumptions) without its "
"profile curve, which is ``x``/``intensity``.",
)
stored_at_revision: int = Field(ge=0)
@model_validator(mode="after")
def _consistent(self) -> Self:
if len(self.x) != len(self.intensity):
raise ValueError(f"pattern {self.id}: x and intensity differ in length")
if self.esd is not None and len(self.esd) != len(self.x):
raise ValueError(f"pattern {self.id}: esd and x differ in length")
if self.kind == "measured":
if self.measured is None or len(self.x) < 2:
raise ValueError(f"measured pattern {self.id} needs its source and points")
if self.structure is not None or self.result is not None:
raise ValueError(f"measured pattern {self.id} cannot name a calculation")
else:
if self.structure is None or self.structure_sha256 is None or self.result is None:
raise ValueError(
f"calculated pattern {self.id} needs its structure, digest and result"
)
if self.measured is not None or self.esd is not None:
raise ValueError(f"calculated pattern {self.id} cannot carry a measured source")
if self.wavelength_angstrom is None:
raise ValueError(f"calculated pattern {self.id} needs its wavelength")
reflections = self.result.get("reflections")
if not isinstance(reflections, list) or len(reflections) > MAX_STORED_REFLECTIONS:
raise ValueError(
f"calculated pattern {self.id} needs at most {MAX_STORED_REFLECTIONS} "
"reflections"
)
return self
[docs]
def check_patterns(patterns: list[DiffractionPattern]) -> None:
"""Refuse duplicate ids and more points than :data:`MAX_DOCUMENT_POINTS` in all."""
ids = [p.id for p in patterns]
twice = sorted({i for i in ids if ids.count(i) > 1})
if twice:
raise ValueError(f"diffraction pattern ids used more than once: {', '.join(twice)}")
total = sum(len(p.x) for p in patterns)
if total > MAX_DOCUMENT_POINTS:
raise ValueError(
f"the stored diffraction patterns hold {total} points; at most {MAX_DOCUMENT_POINTS}"
)