vibe-sketcherDocumentation

Source code for vibesketcher.document.solid_balance

"""Atom, charge and site balances of solid reaction steps; periodic site hops (#192).

The data model is :mod:`vibesketcher.document.solid_reaction_model`. Counting
sites per site type follows Kröger-Vink notation (Kröger and Vink, Solid
State Phys. 3, 307 (1956)): a vacancy still occupies its lattice site.
"""

from __future__ import annotations

import math
from collections.abc import Mapping, Sequence
from fractions import Fraction
from typing import Any

from vibesketcher.document.model import PeriodicStructure
from vibesketcher.document.solid_reaction_model import (
    SolidParticipant,
    SolidStep,
)
from vibesketcher.elements import ATOMIC_NUMBER

__all__ = [
    "balance",
    "check_scheme",
    "participant_charge",
    "participant_formula",
    "participant_sites",
    "site_hops",
]

_SITE_KINDS = ("empty_site", "surface_vacancy")
_BULK_KINDS = ("bulk_phase", "gas", "solution")
_FREE_KINDS = ("gas", "solution")
_SURFACE_HELD = ("adsorbate", "surface_vacancy")


# -- resolution against the document ----------------------------------------------


def _structure_formula(structure: PeriodicStructure, atoms: Sequence[str]) -> dict[str, int]:
    chosen = set(atoms)
    sites = [s for s in structure.sites if not chosen or s.id in chosen]
    if chosen and len(sites) != len(chosen):
        missing = sorted(chosen - {s.id for s in structure.sites})
        raise ValueError(f"structure {structure.id} has no sites {', '.join(missing)}")
    if any(s.occupancy != 1 for s in sites):
        raise ValueError(
            f"structure {structure.id}: partial occupancy has no integer formula; state one"
        )
    counts: dict[str, int] = {}
    for site in sites:
        counts[site.symbol] = counts.get(site.symbol, 0) + 1
    return dict(sorted(counts.items()))


[docs] def participant_formula( participant: SolidParticipant, structures: Mapping[str, PeriodicStructure] ) -> dict[str, int]: """Atoms per formula unit, derived from the structure when not stated. A stated formula of a structure-backed participant without ``atoms`` is a formula unit: the structure's composition must be a whole multiple of it. """ if participant.kind in (*_SITE_KINDS, "electron"): return {} structure = structures.get(participant.structure) if participant.structure else None if participant.structure is not None and structure is None: raise ValueError( f"participant {participant.id} names a missing structure {participant.structure}" ) if structure is None: if not participant.formula: raise ValueError(f"participant {participant.id} needs a formula or a structure") return dict(sorted(participant.formula.items())) derived = _structure_formula(structure, participant.atoms) if participant.formula is None: return derived stated = dict(sorted(participant.formula.items())) if participant.atoms: if stated != derived: raise ValueError( f"participant {participant.id}: formula {stated} differs from its atoms {derived}" ) return stated multiples = {derived.get(k, 0) / v for k, v in stated.items()} whole = len(multiples) == 1 and set(derived) == set(stated) factor = next(iter(multiples)) if whole else 0.0 if not whole or factor < 1 or abs(factor - round(factor)) > 1e-9: raise ValueError( f"participant {participant.id}: structure {structure.id} ({derived}) is not a whole " f"number of formula units {stated}" ) return stated
[docs] def participant_charge( participant: SolidParticipant, structures: Mapping[str, PeriodicStructure] ) -> int: if participant.kind == "electron": return -1 if participant.charge is not None: return participant.charge structure = structures.get(participant.structure) if participant.structure else None if structure is not None and not participant.atoms and participant.formula is None: return structure.charge or 0 return 0
[docs] def participant_sites(participant: SolidParticipant) -> dict[str, int]: if participant.sites is not None: return dict(participant.sites) if participant.kind in ("empty_site", "adsorbate"): return {"*": 1} return {}
def _exact(value: float) -> Fraction: return Fraction(value).limit_denominator(100000) def _text(value: Fraction) -> str: return str(value.numerator) if value.denominator == 1 else f"{value}"
[docs] def balance( step: SolidStep, participants: Mapping[str, SolidParticipant], structures: Mapping[str, PeriodicStructure], ) -> dict[str, Any]: """Atom, charge and site balances of a step and the reservoirs that close them. Imbalance is products minus reactants. ``balanced`` is true when every quantity balances or has a stated reservoir; ``refusals`` say why not. """ totals: dict[str, Fraction] = {} for sign, terms in ((-1, step.reactants), (1, step.products)): for term in terms: found = participants.get(term.participant) if found is None: raise ValueError(f"step {step.id} names a missing participant {term.participant}") c = _exact(term.coefficient) * sign for element, n in participant_formula(found, structures).items(): totals[element] = totals.get(element, Fraction(0)) + c * n totals["charge"] = totals.get("charge", Fraction(0)) + c * participant_charge( found, structures ) for kind, n in participant_sites(found).items(): key = f"site:{kind}" totals[key] = totals.get(key, Fraction(0)) + c * n imbalances = {k: v for k, v in totals.items() if v != 0} stated = {r.quantity: r for r in step.reservoirs} open_ = {k: stated[k].description for k in imbalances if k in stated} refusals = [ f"step {step.id}: {k} does not balance (products - reactants = {_text(v)}); balance it " f"or state an open reservoir for {k}" for k, v in sorted(imbalances.items()) if k not in stated ] unused = sorted(k for k in stated if k not in imbalances) return { "step": step.id, "atoms": {k: _text(v) for k, v in sorted(totals.items()) if k in ATOMIC_NUMBER}, "charge": _text(totals.get("charge", Fraction(0))), "sites": {k.removeprefix("site:"): _text(v) for k, v in sorted(totals.items()) if ":" in k}, "imbalances": {k: _text(v) for k, v in sorted(imbalances.items())}, "open_reservoirs": open_, "unused_reservoirs": unused, "balanced": not refusals, "refusals": refusals, }
def _kind_refusals(step: SolidStep, participants: Mapping[str, SolidParticipant]) -> list[str]: left = [participants[t.participant].kind for t in step.reactants] right = [participants[t.participant].kind for t in step.products] reasons: list[str] = [] if step.kind == "bulk_synthesis": odd = sorted({k for k in (*left, *right) if k not in _BULK_KINDS}) if odd: reasons.append(f"a bulk synthesis has bulk phases, gases and solutes, not {odd}") elif step.kind == "adsorption": if not any(k in _FREE_KINDS for k in left) or "adsorbate" not in right: reasons.append("an adsorption takes a gas or solute to an adsorbate") elif step.kind == "desorption": if "adsorbate" not in left or not any(k in _FREE_KINDS for k in right): reasons.append("a desorption takes an adsorbate to a gas or solute") elif step.kind == "dissociation": held = [k for k in right if k == "adsorbate"] if len(step.products) < 2 or not held: reasons.append("a dissociation gives two or more products, adsorbates among them") elif step.kind == "diffusion": if not any(k in _SURFACE_HELD for k in left) or not any(k in _SURFACE_HELD for k in right): reasons.append("a diffusion moves an adsorbate or a vacancy between sites") return [f"step {step.id}: {r}" for r in reasons] def _cartesian(structure: PeriodicStructure, fractional: Sequence[float]) -> list[float]: rows = structure.lattice_angstrom return [sum(fractional[i] * rows[i][j] for i in range(3)) for j in range(3)]
[docs] def site_hops( step: SolidStep, participants: Mapping[str, SolidParticipant], structures: Mapping[str, PeriodicStructure], ) -> list[dict[str, Any]]: """Each site-map entry resolved: start and end sites, image and hop vector (angstrom). ``minimum_image`` says whether the stated image is the shortest of the translations to the end site; a longer one is kept as stated, never wrapped. """ hops: list[dict[str, Any]] = [] reactants = {t.participant for t in step.reactants} products = {t.participant for t in step.products} for entry in step.site_map: if entry.start.participant not in reactants or entry.end.participant not in products: raise ValueError( f"step {step.id}: a site map runs from a reactant's site to a product's site" ) ends: list[Any] = [] for ref in (entry.start, entry.end): owner = participants[ref.participant] if owner.structure is None: raise ValueError( f"step {step.id}: site {ref.site} needs participant {ref.participant} to " "name a periodic structure" ) structure = structures[owner.structure] site = next((s for s in structure.sites if s.id == ref.site), None) if site is None: raise ValueError(f"step {step.id}: structure {structure.id} has no site {ref.site}") if owner.atoms and ref.site not in owner.atoms: raise ValueError( f"step {step.id}: site {ref.site} is not an atom of participant {owner.id}" ) ends.append((structure, site)) (first, a), (second, b) = ends if ( any( abs(x - y) > 1e-6 for row, other in zip(first.lattice_angstrom, second.lattice_angstrom, strict=True) for x, y in zip(row, other, strict=True) ) or first.pbc != second.pbc ): raise ValueError( f"step {step.id}: the endpoints of a site map need the same cell and periodicity" ) if any(i and not p for i, p in zip(entry.image, first.pbc, strict=True)): raise ValueError(f"step {step.id}: a site-map image crosses a nonperiodic direction") start = _cartesian(first, a.fractional) end_frac = [b.fractional[i] + entry.image[i] for i in range(3)] vector = [e - s for e, s in zip(_cartesian(first, end_frac), start, strict=True)] length = math.sqrt(sum(x * x for x in vector)) shortest = length ranges = [range(-2, 3) if p else range(0, 1) for p in first.pbc] for i in ranges[0]: for j in ranges[1]: for k in ranges[2]: f = [b.fractional[0] + i, b.fractional[1] + j, b.fractional[2] + k] v = [e - s for e, s in zip(_cartesian(first, f), start, strict=True)] shortest = min(shortest, math.sqrt(sum(x * x for x in v))) hops.append( { "from": {"participant": entry.start.participant, "site": a.id}, "to": {"participant": entry.end.participant, "site": b.id}, "image": list(entry.image), "vector_angstrom": [round(x, 6) for x in vector], "length_angstrom": round(length, 6), "minimum_image": length <= shortest + 1e-6, } ) return hops
def _map_refusals( step: SolidStep, participants: Mapping[str, SolidParticipant], structures: Mapping[str, PeriodicStructure], ) -> list[str]: reasons: list[str] = [] present = set(step.participant_ids()) for name in step.coverages: if name not in present: reasons.append(f"step {step.id}: coverage for {name}, which is not in the step") elif participants[name].kind != "adsorbate": reasons.append(f"step {step.id}: coverage is stated for adsorbates only, not {name}") try: site_hops(step, participants, structures) except ValueError as error: reasons.append(str(error)) reactants = {t.participant for t in step.reactants} products = {t.participant for t in step.products} for entry in step.atom_map: if entry.start.participant not in reactants or entry.end.participant not in products: reasons.append(f"step {step.id}: an atom map runs from a reactant to a product") continue for ref in (entry.start, entry.end): owner = participants[ref.participant] if owner.structure is None or (owner.atoms and ref.site not in owner.atoms): reasons.append( f"step {step.id}: atom {ref.site} is not a mapped atom of {ref.participant}" ) return reasons
[docs] def check_scheme( participants: Sequence[SolidParticipant], steps: Sequence[SolidStep], structures: Mapping[str, PeriodicStructure], species: Mapping[str, int], ) -> list[str]: """Every reason the scheme cannot be held; empty when it can. ``species`` maps molecular species IDs to their charges. """ reasons: list[str] = [] by_id = {p.id: p for p in participants} for p in participants: for name, what in ((p.structure, "structure"), (p.parent, "parent structure")): if name is not None and name not in structures: reasons.append(f"participant {p.id} names a missing {what} {name}") if p.species is not None: if p.species not in species: reasons.append(f"participant {p.id} names a missing species {p.species}") elif p.charge is not None and p.charge != species[p.species]: reasons.append(f"participant {p.id}: charge differs from species {p.species}") if not reasons: try: participant_formula(p, structures) except ValueError as error: reasons.append(str(error)) if reasons: return reasons for step in steps: missing = [i for i in step.participant_ids() if i not in by_id] if missing: reasons.append(f"step {step.id} names missing participants: {', '.join(missing)}") continue reasons += _kind_refusals(step, by_id) reasons += balance(step, by_id, structures)["refusals"] reasons += _map_refusals(step, by_id, structures) if step.schematic: reasons += [ f"step {step.id}: a schematic step keeps the paper scheme; {i} names a " "structure, so the step is not schematic" for i in step.participant_ids() if by_id[i].structure is not None ] return reasons