vibe-sketcherDocumentation

Source code for vibesketcher.document.solid_reactions

"""Authoring solid-state and surface reaction schemes in a document (#192).

The data model and the balance arithmetic are in
:mod:`vibesketcher.document.solid_reaction_model`; this module edits a
:class:`~vibesketcher.document.model.Document` with them and reports on it.
Every edit returns a new, validated document: a step whose atoms, charge or
sites do not balance is refused unless it states an open reservoir for each
quantity that does not.

A participant may come from a periodic structure (a bulk phase, a slab, the
atoms of an adsorbate on a slab), from a molecular species (a gas or solute),
or from a formula alone. A scheme copied from a paper can stay schematic:
participants without structures, and steps marked ``schematic``, so no
computational geometry is made up for them.

Molecular formats (MOL, SDF, RXN, SMILES, InChI, CDXML, KET, chemfig) cannot
carry these participants; :func:`export_refusal` gives the reason the
exporters refuse with, so nothing is dropped silently. VSK and QVF keep them.
"""

from __future__ import annotations

from collections.abc import Iterable, Mapping
from typing import Any

from vibesketcher.document.model import Document, PeriodicStructure
from vibesketcher.document.solid_balance import (
    balance,
    check_scheme,
    participant_charge,
    participant_formula,
    participant_sites,
    site_hops,
)
from vibesketcher.document.solid_reaction_model import SolidParticipant, SolidStep

__all__ = [
    "EXAMPLES",
    "KINETICS_NOTE",
    "add",
    "apply_example",
    "check_step",
    "example",
    "export_refusal",
    "remove",
    "report",
]

#: What condition annotations do not say; repeated in every report.
KINETICS_NOTE = (
    "Conditions annotate a step; they state no rate, barrier, equilibrium constant or "
    "reaction order, and the scheme does not imply a balanced kinetics."
)


def _structures(document: Document) -> dict[str, PeriodicStructure]:
    return {s.id: s for s in document.periodic_structures}


def _species_formula(document: Document, identifier: str) -> dict[str, int] | None:
    """The formula of a molecular species from its SMILES, hydrogens included."""
    species = next((s for s in document.species if s.id == identifier), None)
    if species is None or species.smiles is None:
        return None
    try:
        from rdkit import Chem
    except ImportError:  # pragma: no cover - RDKit is a core dependency
        return None
    mol = Chem.MolFromSmiles(species.smiles)
    if mol is None:
        return None
    counts: dict[str, int] = {}
    for atom in Chem.AddHs(mol).GetAtoms():
        counts[atom.GetSymbol()] = counts.get(atom.GetSymbol(), 0) + 1
    return dict(sorted(counts.items()))


def _participant(
    document: Document, data: SolidParticipant | Mapping[str, Any]
) -> SolidParticipant:
    participant = (
        data if isinstance(data, SolidParticipant) else SolidParticipant.model_validate(data)
    )
    if participant.species is None:
        return participant
    derived = _species_formula(document, participant.species)
    if derived is None:
        if participant.formula is None:
            raise ValueError(
                f"participant {participant.id}: species {participant.species} has no SMILES; "
                "state the formula"
            )
        return participant
    if participant.formula is not None and dict(sorted(participant.formula.items())) != derived:
        raise ValueError(
            f"participant {participant.id}: formula {participant.formula} differs from species "
            f"{participant.species} ({derived})"
        )
    charge = next(s.charge for s in document.species if s.id == participant.species)
    return participant.model_copy(
        update={
            "formula": derived,
            "charge": participant.charge if participant.charge is not None else charge,
        }  # fmt: skip
    )


def _rebuilt(
    document: Document, participants: list[SolidParticipant], steps: list[SolidStep]
) -> Document:
    reasons = check_scheme(
        participants,
        steps,
        _structures(document),
        {s.id: s.charge for s in document.species},
    )
    if reasons:
        raise ValueError("; ".join(reasons))
    data = document.to_json_data()
    data["solid_participants"] = [
        p.model_dump(mode="json", by_alias=True, exclude_none=True) for p in participants
    ]
    data["solid_steps"] = [
        s.model_dump(mode="json", by_alias=True, exclude_none=True) for s in steps
    ]
    return Document.model_validate(data)


def _merged[T: (SolidParticipant, SolidStep)](
    kept: list[T], items: list[T], replace: bool
) -> list[T]:
    for item in items:
        at = next((i for i, old in enumerate(kept) if old.id == item.id), None)
        if at is None:
            kept.append(item)
        elif replace:
            kept[at] = item
        else:
            raise ValueError(f"{item.id} exists already; pass replace to change it")
    return kept


[docs] def add( document: Document, *, participants: Iterable[SolidParticipant | Mapping[str, Any]] = (), steps: Iterable[SolidStep | Mapping[str, Any]] = (), replace: bool = False, ) -> Document: """``document`` with participants and steps added, as one checked edit. An ID that exists already is refused unless ``replace`` is true, which swaps the entry in place. A species-backed participant takes its formula and charge from the species. """ new_participants = [_participant(document, p) for p in participants] new_steps = [s if isinstance(s, SolidStep) else SolidStep.model_validate(s) for s in steps] kept_p = _merged(list(document.solid_participants), new_participants, replace) kept_s = _merged(list(document.solid_steps), new_steps, replace) return _rebuilt(document, kept_p, kept_s)
[docs] def remove(document: Document, identifiers: Iterable[str]) -> Document: """``document`` without these participants and steps. A participant still used by a step that stays is refused. """ gone = set(identifiers) known = {p.id for p in document.solid_participants} | {s.id for s in document.solid_steps} unknown = sorted(gone - known) if unknown: raise ValueError(f"no solid participants or steps {', '.join(unknown)}") steps = [s for s in document.solid_steps if s.id not in gone] used = sorted({i for s in steps for i in s.participant_ids()} & gone) if used: raise ValueError(f"participants still used by a step: {', '.join(used)}") participants = [p for p in document.solid_participants if p.id not in gone] return _rebuilt(document, participants, steps)
def _participant_row(p: SolidParticipant, structures: Mapping[str, PeriodicStructure]) -> Any: return { "id": p.id, "kind": p.kind, "label": p.label, "formula": participant_formula(p, structures), "charge": participant_charge(p, structures), "sites": participant_sites(p), "structure": p.structure, "parent": p.parent, "species": p.species, "atoms": len(p.atoms), "geometry": "structure" if p.structure else ("species" if p.species else "none (schematic)"), } def _step_row( step: SolidStep, participants: Mapping[str, SolidParticipant], structures: Mapping[str, PeriodicStructure], ) -> dict[str, Any]: return { "id": step.id, "kind": step.kind, "arrow": step.arrow, "equation": equation(step, participants), "balance": balance(step, participants, structures), "conditions": step.conditions.model_dump(mode="json", exclude_none=True), "coverages": dict(step.coverages), "site_map": site_hops(step, participants, structures), "atom_map": len(step.atom_map), "schematic": step.schematic, } def equation(step: SolidStep, participants: Mapping[str, SolidParticipant]) -> str: """The step as one line of text: ``CO(g) + * -> CO*``.""" def side(terms: Any) -> str: parts = [] for t in terms: c = t.coefficient prefix = "" if c == 1 else (f"{c:g} " if c != int(c) else f"{int(c)} ") parts.append(prefix + participants[t.participant].label) return " + ".join(parts) arrow = " <=> " if step.arrow == "equilibrium" else " -> " return side(step.reactants) + arrow + side(step.products)
[docs] def report(document: Document) -> dict[str, Any]: """Participants with resolved formula, charge and sites; steps with their balances. ``parents`` groups participants that share a bulk or slab parent (or structure) while keeping their own IDs. """ structures = _structures(document) by_id = {p.id: p for p in document.solid_participants} parents: dict[str, list[str]] = {} for p in document.solid_participants: for name in dict.fromkeys(x for x in (p.parent, p.structure) if x): parents.setdefault(name, []).append(p.id) return { "participants": [_participant_row(p, structures) for p in document.solid_participants], "steps": [_step_row(s, by_id, structures) for s in document.solid_steps], "parents": {k: v for k, v in parents.items() if len(v) > 1}, "kinetics": KINETICS_NOTE, }
[docs] def check_step( document: Document, step: SolidStep | Mapping[str, Any], participants: Iterable[SolidParticipant | Mapping[str, Any]] = (), ) -> dict[str, Any]: """A dry run: the balance and every refusal of ``step``; the document is unchanged. ``participants`` are considered beside the document's own, as if added. """ parsed = step if isinstance(step, SolidStep) else SolidStep.model_validate(step) extra = [_participant(document, p) for p in participants] known = {p.id: p for p in document.solid_participants} | {p.id: p for p in extra} structures = _structures(document) reasons = check_scheme( list(known.values()), [parsed], structures, {s.id: s.charge for s in document.species} ) missing = [i for i in parsed.participant_ids() if i not in known] row: dict[str, Any] = {"id": parsed.id, "applicable": not reasons, "refusals": reasons} if not missing and not any("participant" in r and "missing" in r for r in reasons): try: row.update(_step_row(parsed, known, structures)) except ValueError as error: row["refusals"] = [*reasons, str(error)] row["applicable"] = False row["refusals"] = list(dict.fromkeys(row["refusals"])) return row
#: Worked schemes; each a dict of participants and steps for :func:`add`. EXAMPLES: dict[str, dict[str, Any]] = { "co-adsorption": { "description": "CO(g) + * -> CO* on Pt(111), a schematic paper scheme.", "participants": [ {"id": "CO_g", "kind": "gas", "label": "CO(g)", "formula": {"C": 1, "O": 1}}, {"id": "site", "kind": "empty_site", "label": "*"}, {"id": "CO_ads", "kind": "adsorbate", "label": "CO*", "formula": {"C": 1, "O": 1}}, ], "steps": [ { "id": "co_adsorption", "kind": "adsorption", "reactants": [{"participant": "CO_g"}, {"participant": "site"}], "products": [{"participant": "CO_ads"}], "arrow": "equilibrium", "schematic": True, "conditions": { "facet": "Pt(111)", "temperature_k": 300, "pressures": [{"value": 1, "unit": "mbar", "of": "CO"}], }, } ], }, "cuo-reduction": { "description": "CuO(s) + H2(g) -> Cu(s) + H2O(g), a balanced bulk reduction.", "participants": [ {"id": "CuO_s", "kind": "bulk_phase", "label": "CuO(s)", "formula": {"Cu": 1, "O": 1}}, {"id": "H2_g", "kind": "gas", "label": "H2(g)", "formula": {"H": 2}}, {"id": "Cu_s", "kind": "bulk_phase", "label": "Cu(s)", "formula": {"Cu": 1}}, {"id": "H2O_g", "kind": "gas", "label": "H2O(g)", "formula": {"H": 2, "O": 1}}, ], "steps": [ { "id": "cuo_reduction", "kind": "bulk_synthesis", "reactants": [{"participant": "CuO_s"}, {"participant": "H2_g"}], "products": [{"participant": "Cu_s"}, {"participant": "H2O_g"}], "schematic": True, "conditions": {"temperature_k": 573, "notes": ["H2 flow"]}, } ], }, }
[docs] def example(name: str) -> dict[str, Any]: """A copy of a worked scheme from :data:`EXAMPLES`.""" import copy if name not in EXAMPLES: raise ValueError(f"no example {name!r}; known: {', '.join(EXAMPLES)}") return copy.deepcopy(EXAMPLES[name])
[docs] def apply_example(document: Document, name: str) -> Document: """``document`` with a worked scheme added.""" found = example(name) return add(document, participants=found["participants"], steps=found["steps"])
#: Formats that keep solid reaction schemes whole. KEEPING_FORMATS = ("vsk", "qvf")
[docs] def export_refusal(document: Document, fmt: str) -> str | None: """Why ``fmt`` cannot carry the document's solid reaction scheme; ``None`` if it can.""" if fmt in KEEPING_FORMATS or not (document.solid_participants or document.solid_steps): return None shown = [p.id for p in document.solid_participants][:5] more = len(document.solid_participants) - len(shown) names = ", ".join(shown) + (f" and {more} more" if more > 0 else "") return ( f"{fmt} cannot express solid-state or surface reaction participants ({names}); " "export VSK or QVF, or draw the scheme with 'solid reaction figure'" )