vibe-sketcherDocumentation

Source code for vibesketcher.document.solid_reaction_model

"""Solid-state and surface reaction schemes: participants, steps and balances (#192).

A *participant* is one physical state that takes part in a step: a bulk
phase, a clean or adsorbed slab, an empty surface site ``*``, a surface
vacancy, an adsorbate, a gas or solution species, or an electron. Several
participants may draw on the same periodic structure (``structure``) or name
the same parent (``parent``), but every participant has its own ID, so CO*
on a slab and the clean slab it came from never share one.

A *step* states formula coefficients for its reactants and products. Each
step is checked for three conserved quantities:

- atoms, element by element, from each participant's formula;
- charge, from each participant's charge (an electron carries -1);
- sites, per site type: ``*`` for an adsorption site, or any named lattice
  site such as ``O_site``, counted the way Kröger-Vink notation counts them
  (Kröger and Vink, Solid State Phys. 3, 307 (1956)): a vacancy still
  occupies its lattice site.

A quantity that does not balance is refused unless the step names an open
reservoir for it: an explicit statement that this quantity is exchanged with
something outside the scheme (O with an O2 gas reservoir, charge with the
electrode at the stated potential, ``*`` with a surface of many sites).
Bulk synthesis steps never take a reservoir; they balance or are refused.

Atom maps, lattice-site maps, formula coefficients and coverages are separate
fields: a coefficient never implies a coverage, and a site map never implies
an atom map. Conditions (facet, temperature, pressures, potential) annotate a
step; they state no rate, barrier or equilibrium constant.

This module holds the data model only. The balances are computed in
:mod:`vibesketcher.document.solid_balance`, which the document validator
calls, so a document cannot hold an unbalanced step without a stated
reservoir.
"""

from __future__ import annotations

import math
import re
from typing import Annotated, Literal, Self

from pydantic import BaseModel, ConfigDict, Field, StringConstraints, model_validator

from vibesketcher.elements import ATOMIC_NUMBER

__all__ = [
    "PARTICIPANT_KINDS",
    "STEP_KINDS",
    "AtomMapEntry",
    "OpenReservoir",
    "Potential",
    "Pressure",
    "SiteMapEntry",
    "SiteRef",
    "SolidParticipant",
    "SolidStep",
    "StepConditions",
    "Term",
]

_Identifier = Annotated[str, StringConstraints(pattern=r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")]
_Text = Annotated[str, StringConstraints(min_length=1, max_length=500)]
#: A site type: ``*`` for an adsorption site, or a lattice-site name such as ``O_site``.
_SiteType = Annotated[str, StringConstraints(pattern=r"^(\*|[A-Za-z][A-Za-z0-9_()*-]{0,31})$")]

ParticipantKind = Literal[
    "bulk_phase",
    "slab",
    "adsorbed_slab",
    "empty_site",
    "surface_vacancy",
    "adsorbate",
    "gas",
    "solution",
    "electron",
]
PARTICIPANT_KINDS: tuple[str, ...] = (
    "bulk_phase",
    "slab",
    "adsorbed_slab",
    "empty_site",
    "surface_vacancy",
    "adsorbate",
    "gas",
    "solution",
    "electron",
)

StepKind = Literal[
    "adsorption",
    "desorption",
    "dissociation",
    "diffusion",
    "surface_transformation",
    "bulk_synthesis",
]
STEP_KINDS: tuple[str, ...] = (
    "adsorption",
    "desorption",
    "dissociation",
    "diffusion",
    "surface_transformation",
    "bulk_synthesis",
)

#: Participants that stand for a surface location and carry no atoms.
_SITE_KINDS = ("empty_site", "surface_vacancy")
_FREE_KINDS = ("gas", "solution")


class _Strict(BaseModel):
    model_config = ConfigDict(extra="forbid", populate_by_name=True, validate_assignment=True)


[docs] class SolidParticipant(_Strict): """One physical state in a solid-state or surface reaction scheme.""" id: _Identifier kind: ParticipantKind label: _Text = Field( description="As printed: CO*, CuO(s), H2O(g), *, V_O, e^-. Digits after a letter " "print as subscripts; ^ starts a superscript." ) formula: dict[str, int] | None = Field( default=None, description="Atoms per formula unit. Derived from structure (and atoms) when left out; " "empty for sites, vacancies and electrons.", ) charge: int | None = Field( default=None, description="Net charge per formula unit; -1 for an electron, else 0." ) sites: dict[_SiteType, int] | None = Field( default=None, description="Surface or lattice sites held per formula unit, by site type. Defaults: " "{'*': 1} for empty sites and adsorbates, none otherwise.", ) structure: _Identifier | None = Field( default=None, description="A periodic structure this participant is drawn from." ) atoms: list[_Identifier] = Field( default_factory=list, max_length=25000, description="Site IDs of the structure that belong to this participant (an adsorbate " "on a slab model); its formula is then theirs.", ) parent: _Identifier | None = Field( default=None, description="The bulk or slab structure this state belongs to; shared by several " "participants without sharing their IDs.", ) species: _Identifier | None = Field( default=None, description="A molecular species of the document for a gas or solute." ) state: _Text | None = Field( default=None, description="Phase or medium, e.g. 'aq', '0.1 M KOH'." ) note: _Text | None = None @model_validator(mode="after") def _kind_rules(self) -> Self: if self.formula is not None: bad = sorted(k for k in self.formula if k not in ATOMIC_NUMBER) if bad: raise ValueError(f"participant {self.id}: unknown elements {', '.join(bad)}") if any(v <= 0 for v in self.formula.values()): raise ValueError(f"participant {self.id}: formula counts must be positive") if self.sites is not None and any(v <= 0 for v in self.sites.values()): raise ValueError(f"participant {self.id}: site counts must be positive") atomless = self.kind in (*_SITE_KINDS, "electron") if atomless and (self.formula or self.atoms or self.species): raise ValueError(f"participant {self.id}: a {self.kind} carries no atoms") if self.kind == "electron" and ( self.charge not in (None, -1) or self.sites or self.structure ): raise ValueError(f"participant {self.id}: an electron has charge -1 and no sites") if self.kind == "surface_vacancy" and not self.sites: raise ValueError( f"participant {self.id}: a surface vacancy names the lattice site it leaves " "empty, e.g. sites {'O_site': 1}" ) if self.kind in _FREE_KINDS and self.sites: raise ValueError(f"participant {self.id}: a {self.kind} species holds no surface site") if self.atoms and self.structure is None: raise ValueError(f"participant {self.id}: atoms need the structure they belong to") if len(self.atoms) != len(set(self.atoms)): raise ValueError(f"participant {self.id}: an atom is listed twice") if self.species is not None and self.kind not in (*_FREE_KINDS, "adsorbate"): raise ValueError(f"participant {self.id}: only gas, solution or adsorbate species") return self
[docs] class Term(_Strict): """A participant with its formula coefficient in a step.""" participant: _Identifier coefficient: float = Field(default=1, gt=0, le=1000, allow_inf_nan=False)
[docs] class OpenReservoir(_Strict): """An explicit statement that a quantity is exchanged outside the scheme.""" quantity: Annotated[str, StringConstraints(min_length=1, max_length=40)] = Field( description="An element symbol, 'charge', or 'site:<type>' such as 'site:*'." ) @model_validator(mode="after") def _known_quantity(self) -> Self: site = self.quantity.removeprefix("site:") if self.quantity.startswith("site:"): if not re.fullmatch(r"\*|[A-Za-z][A-Za-z0-9_()*-]{0,31}", site): raise ValueError(f"reservoir for an unknown site type {site!r}") elif self.quantity != "charge" and self.quantity not in ATOMIC_NUMBER: raise ValueError( f"reservoir quantity {self.quantity!r} is not an element, 'charge' or 'site:<type>'" ) return self description: _Text = Field( description="What the reservoir is, e.g. 'O2(g) at the stated pressure' or " "'the electrode at the stated potential'." ) participant: _Identifier | None = Field( default=None, description="A participant that stands for the reservoir, if drawn." )
[docs] class Pressure(_Strict): value: float = Field(gt=0, allow_inf_nan=False) unit: Literal["Pa", "kPa", "bar", "mbar", "atm", "Torr"] of: _Text | None = Field(default=None, description="Whose partial pressure, e.g. 'CO'.")
[docs] class Potential(_Strict): value_v: float = Field(allow_inf_nan=False) reference: Annotated[str, StringConstraints(min_length=1, max_length=40)] = Field( description="The reference electrode, e.g. RHE, SHE, Ag/AgCl." )
[docs] class StepConditions(_Strict): """Annotations of a step; none of them implies a rate or a balanced kinetics.""" facet: Annotated[str, StringConstraints(min_length=1, max_length=40)] | None = Field( default=None, description="As printed, e.g. 'Pt(111)' or '(110)'." ) temperature_k: float | None = Field(default=None, gt=0, le=1e5, allow_inf_nan=False) pressures: list[Pressure] = Field(default_factory=list, max_length=20) potential: Potential | None = None notes: list[_Text] = Field(default_factory=list, max_length=20)
[docs] class SiteRef(_Strict): participant: _Identifier site: _Identifier
[docs] class SiteMapEntry(_Strict): """A lattice-site map: a site of a reactant goes to a site of a product in cell ``image``. For a diffusion hop the image is the lattice translation of the end site relative to the home cell of the start site; it is never inferred. """ start: SiteRef = Field(alias="from") end: SiteRef = Field(alias="to") image: tuple[int, int, int] = (0, 0, 0)
[docs] class AtomMapEntry(_Strict): """An atom map: atom ``start`` of a reactant is atom ``end`` of a product.""" start: SiteRef = Field(alias="from") end: SiteRef = Field(alias="to")
[docs] class SolidStep(_Strict): """One step of a solid-state or surface scheme.""" id: _Identifier kind: StepKind reactants: list[Term] = Field(min_length=1, max_length=50) products: list[Term] = Field(min_length=1, max_length=50) arrow: Literal["forward", "equilibrium"] = "forward" reservoirs: list[OpenReservoir] = Field(default_factory=list, max_length=20) conditions: StepConditions = Field(default_factory=StepConditions) coverages: dict[_Identifier, float] = Field( default_factory=dict, description="Coverage in monolayers per adsorbate participant; never a coefficient.", ) site_map: list[SiteMapEntry] = Field(default_factory=list, max_length=1000) atom_map: list[AtomMapEntry] = Field(default_factory=list, max_length=25000) schematic: bool = Field( default=False, description="A paper scheme kept as drawn: no participant needs a computed geometry.", ) label: _Text | None = None @model_validator(mode="after") def _shape(self) -> Self: for role in ("reactants", "products"): named = [t.participant for t in getattr(self, role)] if len(named) != len(set(named)): raise ValueError(f"step {self.id}: a participant appears twice among the {role}") quantities = [r.quantity for r in self.reservoirs] if len(quantities) != len(set(quantities)): raise ValueError(f"step {self.id}: a quantity has more than one reservoir") for quantity in quantities: if ( quantity != "charge" and not quantity.startswith("site:") and quantity not in ATOMIC_NUMBER ): raise ValueError(f"step {self.id}: reservoir for unknown element {quantity}") if self.kind == "bulk_synthesis" and self.reservoirs: raise ValueError(f"step {self.id}: a bulk synthesis balances without reservoirs") if any(not (0 < v <= 1000) or not math.isfinite(v) for v in self.coverages.values()): raise ValueError(f"step {self.id}: coverages are positive monolayer fractions") if self.kind == "diffusion" and not self.site_map: raise ValueError( f"step {self.id}: a diffusion step needs a site map from the start site to " "the end site, with its lattice image" ) return self
[docs] def participant_ids(self) -> list[str]: return [t.participant for t in (*self.reactants, *self.products)]