vibe-sketcherDocumentation

Source code for vibesketcher.render.solid_reactions

"""Editable SVG figures of solid-state and surface reaction schemes (#192).

One row per step: reactants, an arrow with the conditions above and below
it, the products, and the step kind at the right. Every participant label
is its own ``<text>`` element carrying the participant ID
(``data-participant``) and every step its own ``<g>`` (``data-step``), so a
vector editor can move and retype them. The text sizes and line widths come
from the document's figure style preset, as in the molecular reaction
figures; nothing is drawn from a geometry, so schematic paper schemes need
none.

Labels print digits after a letter or a closing bracket as subscripts
(``H2O`` -> H₂O), and ``^`` starts a superscript that runs to the next space
or ``_`` (``e^-``, ``O^2-``).
"""

from __future__ import annotations

from collections.abc import Iterable, Sequence
from xml.sax.saxutils import escape

from vibesketcher.document.model import Document
from vibesketcher.document.solid_reaction_model import SolidParticipant, SolidStep, Term
from vibesketcher.render.styles import resolve

__all__ = ["label_spans", "scheme_svg"]

_KIND_TEXT = {
    "adsorption": "adsorption",
    "desorption": "desorption",
    "dissociation": "dissociation",
    "diffusion": "diffusion",
    "surface_transformation": "surface transformation",
    "bulk_synthesis": "bulk synthesis",
}


[docs] def label_spans(label: str) -> list[tuple[str, str]]: """``label`` as runs of (``base`` | ``sub`` | ``sup``, text).""" runs: list[tuple[str, str]] = [] def put(kind: str, char: str) -> None: if runs and runs[-1][0] == kind: runs[-1] = (kind, runs[-1][1] + char) else: runs.append((kind, char)) superscript = False previous = "" for char in label: if char == "^": superscript = True elif superscript and char in " _": superscript = False if char == " ": put("base", char) elif superscript: put("sup", "−" if char == "-" else char) elif ( char.isdigit() and previous and ( previous.isalpha() or previous in ")]" or (runs[-1][0] == "sub" and previous.isdigit()) ) ): put("sub", char) else: put("base", char) previous = char return runs
#: Approximate advance widths of a sans-serif face, in ems; others count 0.56. _NARROW = dict.fromkeys("il|.,:;'!", 0.25) | dict.fromkeys("()[]*fjrt ", 0.33) _WIDE = dict.fromkeys("MW", 0.85) | dict.fromkeys("mw", 0.8) | dict.fromkeys("ABCDGHKNOQRUV", 0.7) def _width(label: str, size: float) -> float: total = 0.0 for kind, text in label_spans(label): scale = 1.0 if kind == "base" else 0.7 total += sum(_NARROW.get(c, _WIDE.get(c, 0.56)) for c in text) * size * scale return total def _text(label: str, x: float, y: float, size: float, font: str, extra: str = "") -> str: spans = [] for kind, text in label_spans(label): if kind == "base": spans.append(f"<tspan>{escape(text)}</tspan>") else: spans.append( f'<tspan baseline-shift="{"sub" if kind == "sub" else "super"}" ' f'font-size="{size * 0.7:.2f}">{escape(text)}</tspan>' ) return ( f'<text xml:space="preserve" x="{x:.2f}" y="{y:.2f}" ' f'font-family="{escape(font)}" font-size="{size}"' f"{extra}>{''.join(spans)}</text>" ) def _conditions(step: SolidStep) -> tuple[list[str], list[str]]: c = step.conditions above = [c.facet] if c.facet else [] above += [f"p({p.of}) = {p.value:g} {p.unit}" if p.of else f"p = {p.value:g} {p.unit}" for p in c.pressures] # fmt: skip below = [f"{c.temperature_k:g} K"] if c.temperature_k is not None else [] if c.potential is not None: below.append(f"U = {c.potential.value_v:g} V vs {c.potential.reference}") below += list(c.notes) below += [f"open {r.quantity}: {r.description}" for r in step.reservoirs] return above, below def _coefficient(term: Term) -> str: c = term.coefficient if c == 1: return "" if c == int(c): return f"{int(c)} " from fractions import Fraction exact = Fraction(c).limit_denominator(12) return f"{exact} " if abs(float(exact) - c) < 1e-9 else f"{c:g} " def _side( parts: list[str], step: SolidStep, terms: Sequence[Term], by_id: dict[str, SolidParticipant], x: float, base: float, size: float, font: str, ) -> float: """Draw one side of a step from ``x``; returns where it ends.""" for i, term in enumerate(terms): if i: parts.append(_text("+", x + size * 0.4, base, size, font)) x += size * 1.4 p = by_id[term.participant] text = _coefficient(term) + p.label extra = ( f' class="participant" data-participant="{escape(p.id)}"' f' id="{escape(step.id)}-{escape(p.id)}"' ) parts.append(_text(text, x, base, size, font, extra)) x += _width(text, size) return x
[docs] def scheme_svg( document: Document, steps: Sequence[str] | None = None, *, style: str | None = None ) -> str: """The scheme's steps (all, or those named) as one editable SVG.""" preset = resolve(style if style is not None else document.style.preset) size = float(preset.size) * 1.4 small = size * 0.72 by_id: dict[str, SolidParticipant] = {p.id: p for p in document.solid_participants} chosen: Iterable[SolidStep] if steps is None: chosen = document.solid_steps else: known = {s.id: s for s in document.solid_steps} missing = [s for s in steps if s not in known] if missing: raise ValueError(f"no solid steps {', '.join(missing)}") chosen = [known[s] for s in steps] chosen = list(chosen) if not chosen: raise ValueError("the document has no solid reaction steps to draw") margin = size rows: list[str] = [] y = margin widest = 0.0 line = max(preset.line * 1.4, 0.8) for number, step in enumerate(chosen, start=1): above, below = _conditions(step) top = y + len(above) * small * 1.2 base = top + size x = margin parts: list[str] = [f'<g data-step="{escape(step.id)}" id="step-{escape(step.id)}">'] parts.append(f"<title>{escape(step.label or step.id)} ({_KIND_TEXT[step.kind]})</title>") x = _side(parts, step, step.reactants, by_id, x, base, size, preset.font) + size * 0.6 labels = [*above, *below] length = max([size * 3.0, *(_width(t, small) + size for t in labels)]) mid = base - size * 0.32 end = x + length head = size * 0.45 if step.arrow == "equilibrium": gap = size * 0.12 parts.append( f'<path d="M{x:.2f},{mid - gap:.2f} H{end:.2f} l{-head:.2f},{-head * 0.5:.2f}" ' f'fill="none" stroke="black" stroke-width="{line:.2f}" class="arrow"/>' f'<path d="M{end:.2f},{mid + gap:.2f} H{x:.2f} l{head:.2f},{head * 0.5:.2f}" ' f'fill="none" stroke="black" stroke-width="{line:.2f}" class="arrow"/>' ) else: parts.append( f'<path d="M{x:.2f},{mid:.2f} H{end:.2f}" stroke="black" ' f'stroke-width="{line:.2f}" class="arrow"/>' f'<path d="M{end:.2f},{mid:.2f} l{-head:.2f},{-head * 0.4:.2f} ' f'v{head * 0.8:.2f} z" fill="black" class="arrow"/>' ) for i, text in enumerate(reversed(above)): ty = mid - size * 0.5 - i * small * 1.2 parts.append(_text(text, x + (length - _width(text, small)) / 2, ty, small, preset.font, ' class="condition"')) # fmt: skip for i, text in enumerate(below): ty = mid + small * 1.3 + i * small * 1.2 parts.append(_text(text, x + (length - _width(text, small)) / 2, ty, small, preset.font, ' class="condition"')) # fmt: skip x = _side(parts, step, step.products, by_id, end + size * 0.6, base, size, preset.font) caption = f"({number}) {_KIND_TEXT[step.kind]}" parts.append(_text(caption, x + size * 1.5, base, small, preset.font, ' class="step-kind" fill="#555"')) # fmt: skip x += size * 1.5 + _width(caption, small) parts.append("</g>") rows.append("".join(parts)) widest = max(widest, x) y = mid + small * 1.3 + max(len(below), 0) * small * 1.2 + size * 0.8 width = widest + margin height = y + margin * 0.5 return ( '<?xml version="1.0" encoding="UTF-8"?>\n' f'<svg xmlns="http://www.w3.org/2000/svg" width="{width:.0f}pt" height="{height:.0f}pt" ' f'viewBox="0 0 {width:.2f} {height:.2f}" data-figure="solid-reaction-scheme">' f'<rect width="100%" height="100%" fill="white"/>{"".join(rows)}</svg>\n' )