vibe-sketcherDocumentation

Source code for vibesketcher.document.refinement_records

"""Refinement intents and verified report associations of measured patterns (#275).

vibe-sketcher runs no refinement and depends on no refinement engine. It keeps two
kinds of record on a stored *measured* pattern:

- an **intent**: which parameters an external engine is meant to refine or hold
  (scale, zero shift, background, lattice parameters, U_iso groups, occupancies,
  positions, profile, preferred orientation) and the constraints between them
  (``equal`` ties, ``sum`` such as occupancies summing to 1, ``fixed`` values), for
  a named periodic structure whose digest is recorded. Starting values may be
  stated. Refined values and agreement indices may not: an intent is not a result.
- a **report association**: an external report file read here, so its SHA-256 and
  size are computed rather than stated, with the engine, the version as given and
  the agreement indices exactly as the report gives them. Agreement measures the
  fit of one model to one pattern. It does not establish that the structure is
  unique, and it is not the instrument's uncertainty; every record says so.

An agreement claim without its report bytes is refused, and so is an intent that
carries results. Every edit is checked against the document revision. An intent
whose structure changed or is gone is *stale*, and so is a report whose intent is
stale. Undo removes the pattern's last record while it is current; removing an
intent that a report answers is refused.
"""

from __future__ import annotations

import hashlib
from typing import Any

from pydantic import ValidationError

from vibesketcher.document.diffraction import structure_digest
from vibesketcher.document.diffraction_model import (
    LATTICE_PARAMETERS,
    MAX_REFINEMENT_RECORDS,
    SITE_PARAMETERS,
    DiffractionPattern,
    RefinementIntent,
    RefinementReport,
)
from vibesketcher.document.model import Document

#: Printed with every record and on every output that shows agreement indices.
AGREEMENT_NOTE = (
    "Agreement indices are as reported by the external engine for this model and this "
    "pattern. They measure the fit; they do not establish that the structure is unique, "
    "and they are not the instrument's uncertainty."
)
#: The largest report file read for its digest (bytes).
MAX_REPORT_BYTES = 64 * 1024 * 1024
#: Keys that would turn an intent into a claim of results.
_RESULT_KEYS = (
    "agreement",
    "rwp",
    "Rwp",
    "chi2",
    "gof",
    "GOF",
    "results",
    "refined",
    "refined_values",
    "converged",
)


[docs] class RefinementRefused(ValueError): """A refinement record cannot be stored or changed faithfully; ``code`` says why.""" def __init__(self, code: str, message: str) -> None: super().__init__(message) self.code = code
def _check_revision(document: Document, revision: int | None) -> None: if revision is not None and revision != document.revision: raise RefinementRefused( "refinement.revision_conflict", f"the edit is based on revision {revision}; the document is at {document.revision}", ) def _measured(document: Document, pattern: str) -> DiffractionPattern: for stored in document.diffraction_patterns: if stored.id == pattern: if stored.kind != "measured": raise RefinementRefused( "refinement.not_measured", f"pattern {pattern} is calculated; refinement records belong to a measured " "pattern", ) return stored raise RefinementRefused("refinement.unknown_pattern", f"no stored pattern {pattern!r}") def _replace(document: Document, pattern: DiffractionPattern) -> Document: data = document.to_json_data() data["diffraction_patterns"] = [ (pattern if p.id == pattern.id else p).model_dump(mode="json", exclude_none=True) for p in document.diffraction_patterns ] return Document.model_validate(data) def _with_records(pattern: DiffractionPattern, records: list[Any]) -> DiffractionPattern: data = pattern.model_dump(mode="json", exclude_none=True) data["refinement"] = [r.model_dump(mode="json", exclude_none=True) for r in records] or None if data["refinement"] is None: del data["refinement"] return DiffractionPattern.model_validate(data) def _new_id(pattern: DiffractionPattern, identifier: str | None, prefix: str) -> str: taken = {r.id for r in pattern.refinement or []} if len(taken) >= MAX_REFINEMENT_RECORDS: raise RefinementRefused( "refinement.too_many", f"pattern {pattern.id} already holds {MAX_REFINEMENT_RECORDS} refinement records", ) if identifier is not None: if identifier in taken: raise RefinementRefused( "refinement.duplicate_id", f"pattern {pattern.id} already holds a record {identifier!r}", ) return identifier k = 1 while f"{prefix}-{k}" in taken: k += 1 return f"{prefix}-{k}" def _invalid(error: ValidationError) -> RefinementRefused: parts = [] for e in error.errors(): where = ".".join(str(x) for x in e["loc"]) or "record" parts.append(f"{where}: {e['msg'].removeprefix('Value error, ')}") detail = "; ".join(parts) return RefinementRefused("refinement.invalid", detail) def _targets(document: Document, intent: RefinementIntent) -> None: """Refuse parameters whose targets are not in the structure, by kind.""" found = {s.id: s for s in document.periodic_structures} structure = found.get(intent.structure) if structure is None: raise RefinementRefused( "refinement.unknown_structure", f"no periodic structure {intent.structure!r}" ) sites = {site.id for site in structure.sites} for parameter in intent.parameters: if parameter.kind in SITE_PARAMETERS: allowed: set[str] | tuple[str, ...] = sites elif parameter.kind == "lattice": allowed = LATTICE_PARAMETERS else: allowed = () if parameter.kind in (*SITE_PARAMETERS, "lattice") and not parameter.targets: raise RefinementRefused( "refinement.unknown_target", f"a {parameter.kind} parameter names its targets" ) stray = [t for t in parameter.targets if t not in allowed] if stray: what = ( "sites of " + intent.structure if parameter.kind in SITE_PARAMETERS else ( "lattice parameters a, b, c, alpha, beta, gamma" if parameter.kind == "lattice" else "no targets" ) ) raise RefinementRefused( "refinement.unknown_target", f"{parameter.kind} targets {', '.join(stray[:8])} are not {what}", )
[docs] def store_intent( document: Document, pattern: str, intent: dict[str, Any], *, revision: int | None = None, identifier: str | None = None, ) -> tuple[Document, dict[str, Any]]: """Keep a refinement intent on a measured pattern; returns (document, summary).""" _check_revision(document, revision) claimed = sorted(k for k in intent if k in _RESULT_KEYS) if claimed: raise RefinementRefused( "refinement.claim_without_report", f"an intent states what is to be refined, not results ({', '.join(claimed)}); " "associate the external report, whose bytes are digested, to record agreement", ) stored = _measured(document, pattern) structure = {s.id: s for s in document.periodic_structures}.get(str(intent.get("structure"))) if structure is None: raise RefinementRefused( "refinement.unknown_structure", f"no periodic structure {intent.get('structure')!r}" ) try: record = RefinementIntent.model_validate( { **intent, "kind": "intent", "id": _new_id(stored, identifier, "intent"), "structure_sha256": structure_digest(structure), "stored_at_revision": document.revision, } ) except ValidationError as error: raise _invalid(error) from None _targets(document, record) made = _replace(document, _with_records(stored, [*(stored.refinement or []), record])) return made, summary(made, pattern, record.id)
[docs] def associate_report( document: Document, pattern: str, report: bytes | None, file_name: str, *, engine: str, engine_version: str | None = None, agreement: dict[str, float] | None = None, intent: str | None = None, notes: str | None = None, revision: int | None = None, identifier: str | None = None, ) -> tuple[Document, dict[str, Any]]: """Associate an external refinement report (its bytes) with a measured pattern.""" _check_revision(document, revision) if not report: raise RefinementRefused( "refinement.claim_without_report", "a refinement claim needs the report itself: its bytes are read for the SHA-256 " "the association keeps; agreement indices are never recorded on their own", ) if len(report) > MAX_REPORT_BYTES: raise RefinementRefused( "refinement.too_large", f"the report has {len(report)} bytes; at most {MAX_REPORT_BYTES}", ) stored = _measured(document, pattern) if intent is not None and not any( r.id == intent and r.kind == "intent" for r in stored.refinement or [] ): raise RefinementRefused( "refinement.unknown_intent", f"pattern {pattern} holds no intent {intent!r}" ) name = file_name.replace("\\", "/").rsplit("/", 1)[-1] or "report" try: record = RefinementReport.model_validate( { "id": _new_id(stored, identifier, "report"), "intent": intent, "engine": engine, "engine_version": engine_version, "file_name": name, "sha256": hashlib.sha256(report).hexdigest(), "bytes": len(report), "agreement": dict(agreement or {}), "notes": notes, "stored_at_revision": document.revision, } ) except ValidationError as error: raise _invalid(error) from None made = _replace(document, _with_records(stored, [*(stored.refinement or []), record])) return made, summary(made, pattern, record.id)
def _stale(document: Document, pattern: DiffractionPattern, record: Any) -> str | None: """Why a record is stale, or None while it is current.""" if record.kind == "intent": found = {s.id: s for s in document.periodic_structures}.get(record.structure) if found is None: return f"structure {record.structure} no longer exists" if structure_digest(found) != record.structure_sha256: return f"structure {record.structure} changed since the intent was stored" return None if record.intent is None: return None answered = next(r for r in pattern.refinement or [] if r.id == record.intent) reason = _stale(document, pattern, answered) return f"its intent {record.intent} is stale ({reason})" if reason else None
[docs] def summary(document: Document, pattern: str, record_id: str) -> dict[str, Any]: """One record with its pattern, marked stale or current, with the agreement note.""" stored = _measured(document, pattern) record = next((r for r in stored.refinement or [] if r.id == record_id), None) if record is None: raise RefinementRefused( "refinement.unknown_record", f"pattern {pattern} holds no refinement record {record_id!r}", ) reason = _stale(document, stored, record) out = { "pattern": stored.id, "pattern_sha256": stored.measured.sha256 if stored.measured else None, **record.model_dump(mode="json", exclude_none=True), "stale": reason is not None, "stale_reason": reason, } if record.kind == "report": out["note"] = AGREEMENT_NOTE else: out["note"] = "an intent for an external engine; nothing was refined here" return out
[docs] def records(document: Document, pattern: str) -> list[dict[str, Any]]: """The pattern's refinement records, oldest first, each marked stale or current.""" stored = _measured(document, pattern) return [summary(document, pattern, r.id) for r in stored.refinement or []]
[docs] def undo(document: Document, pattern: str, *, revision: int | None = None) -> Document: """Remove the pattern's last refinement record; refused once it is stale.""" _check_revision(document, revision) stored = _measured(document, pattern) held = list(stored.refinement or []) if not held: raise RefinementRefused( "refinement.nothing_to_undo", f"pattern {pattern} holds no refinement record" ) reason = _stale(document, stored, held[-1]) if reason: raise RefinementRefused( "refinement.stale_record", f"record {held[-1].id} is stale ({reason}); undo refused (remove it by id instead)", ) return _replace(document, _with_records(stored, held[:-1]))
[docs] def remove( document: Document, pattern: str, record_id: str, *, revision: int | None = None ) -> Document: """Remove one refinement record by id, stale or not; an answered intent is refused.""" _check_revision(document, revision) stored = _measured(document, pattern) held = list(stored.refinement or []) if not any(r.id == record_id for r in held): raise RefinementRefused( "refinement.unknown_record", f"pattern {pattern} holds no refinement record {record_id!r}", ) answering = [r.id for r in held if r.kind == "report" and r.intent == record_id] if answering: raise RefinementRefused( "refinement.referenced_intent", f"intent {record_id} is answered by {', '.join(answering)}; remove those first", ) return _replace(document, _with_records(stored, [r for r in held if r.id != record_id]))