vibe-sketcherDocumentation

Source code for vibesketcher.render.panels

"""Labelled multi-panel figures at a stated physical width (#247).

:func:`compose_panels` lays existing figure SVGs (periodic figures, the
cyclic-topology schematic, powder overlays, scheme renders or any SVG that
passes the checks below) out in a grid, row by row in the order given, labels
them (a), (b), ... in that order and writes one SVG, or PDF/PNG through the
publication extra. The physical width is stated: a single column (85 mm), a
double column (178 mm), or ``width_mm`` for a journal's own measure. One SVG
unit is one point (1/72 in), as in every vibe-sketcher figure, so the PDF has
exactly that width.

Each panel keeps its own drawing: it is embedded as a nested ``<svg>`` with
its viewBox, scaled by one factor, and nothing in it is redrawn. Its ``id``
attributes are prefixed per panel so two panels never share a clip path.
Panel scaling is stated, not guessed:

- ``fit``: every panel fills its column width;
- ``uniform``: one factor for every panel, so relative sizes are kept;
- ``angstrom``: every panel shows one angstrom at the same length, from the
  panel's stated ``angstrom_per_unit`` (or its root attribute
  ``data-vibe-angstrom-per-unit``); a panel without one is refused, and an
  optional common scale bar is drawn.

Panel SVG is untrusted input and fails closed: a DOCTYPE or entity, an
element outside the drawing subset (no script, foreignObject, image or
animation), an event attribute, an external reference (``href`` or
``url(...)`` not starting with ``#``) or a style sheet other than an
``@font-face`` block (which is dropped; the publication font is supplied at
conversion) is refused. Captions and the title may hold ``$...$`` math
(:mod:`vibesketcher.render.mathtext`).
"""

from __future__ import annotations

import html
import math
import re
import xml.etree.ElementTree as ET
from collections.abc import Sequence
from typing import Literal

from pydantic import BaseModel, ConfigDict, Field

from vibesketcher.render import RenderRefused, mathtext

__all__ = [
    "COLUMN_WIDTH_MM",
    "Panel",
    "PanelOptions",
    "PanelRefused",
    "compose_panels",
    "compose_panels_svg",
    "cell_width_pt",
    "panel_labels",
]

_SVG = "http://www.w3.org/2000/svg"
_NS = f"{{{_SVG}}}"
_XLINK = "{http://www.w3.org/1999/xlink}href"

#: Generic single- and double-column widths; give ``width_mm`` for a journal's own.
COLUMN_WIDTH_MM = {"single": 85.0, "double": 178.0}
_PT_PER_MM = 72 / 25.4
_MAX_PANELS = 26

_ALLOWED = {
    "svg",
    "g",
    "title",
    "desc",
    "defs",
    "rect",
    "circle",
    "ellipse",
    "line",
    "polyline",
    "polygon",
    "path",
    "text",
    "tspan",
    "clipPath",
    "mask",
    "linearGradient",
    "radialGradient",
    "stop",
    "marker",
    "pattern",
    "use",
    "symbol",
    "style",
}
_UNITS = {"": 1.0, "pt": 1.0, "px": 1.0, "mm": _PT_PER_MM, "cm": 10 * _PT_PER_MM, "in": 72.0}
_URL = re.compile(r"url\(\s*(['\"]?)([^)'\"]*)\1\s*\)")

LabelStyle = Literal["(a)", "a", "a)", "(A)", "A", "none"]


[docs] class PanelRefused(RenderRefused): """A panel or the layout cannot be composed as asked."""
[docs] class Panel(BaseModel): """One panel: its SVG and what is stated about it.""" model_config = ConfigDict(extra="forbid") svg: str = Field(min_length=1) #: A caption under the panel; ``$...$`` math is allowed. caption: str | None = Field(default=None, max_length=300) #: Angstrom per SVG unit of this panel, for ``scale="angstrom"``. angstrom_per_unit: float | None = Field(default=None, gt=0, allow_inf_nan=False)
[docs] class PanelOptions(BaseModel): """The grid, the physical width and the labels; every choice is stated.""" model_config = ConfigDict(extra="forbid") columns: int = Field(default=2, ge=1, le=6) column: Literal["single", "double"] = "double" #: Overrides ``column`` with an exact width. width_mm: float | None = Field(default=None, ge=20.0, le=500.0) gap_mm: float = Field(default=3.0, ge=0.0, le=30.0) labels: LabelStyle = "(a)" label_size_pt: float = Field(default=9.0, ge=4.0, le=24.0) label_bold: bool = True caption_size_pt: float = Field(default=8.0, ge=4.0, le=24.0) scale: Literal["fit", "uniform", "angstrom"] = "fit" #: With ``scale="angstrom"``: a scale bar of this many angstrom under the grid. scale_bar_angstrom: float | None = Field(default=None, gt=0, le=10000) #: The tallest a panel may be drawn; with ``fit`` and ``uniform`` a taller #: panel is scaled down to it (``angstrom`` refuses instead, to keep the scale). max_height_mm: float | None = Field(default=None, ge=10.0, le=500.0) title: str | None = Field(default=None, max_length=300)
[docs] def cell_width_pt(options: PanelOptions | None = None, panels: int | None = None) -> float: """The width of one grid column in points: draw a panel at this width for true-size text.""" options = options or PanelOptions() width = (options.width_mm or COLUMN_WIDTH_MM[options.column]) * _PT_PER_MM cols = min(options.columns, panels) if panels else options.columns return (width - options.gap_mm * _PT_PER_MM * (cols - 1)) / cols
[docs] def panel_labels(count: int, style: LabelStyle = "(a)") -> list[str]: """The labels of ``count`` panels in reading order: (a), (b), ...""" if not 0 <= count <= _MAX_PANELS: raise PanelRefused(f"at most {_MAX_PANELS} panels") if style == "none": return [""] * count letters = [chr(ord("a") + k) for k in range(count)] if style in ("(A)", "A"): letters = [c.upper() for c in letters] return [style.replace("a", c).replace("A", c) for c in letters]
def _length(text: str | None, what: str) -> float | None: if text is None: return None match = re.fullmatch(r"\s*([0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?)\s*([a-z]*)\s*", text) if not match or match.group(2) not in _UNITS: raise PanelRefused(f"panel {what} {text!r} is not a length in pt, px, mm, cm or in") value = float(match.group(1)) * _UNITS[match.group(2)] if not (0 < value <= 14400): raise PanelRefused(f"panel {what} must be positive and at most 14400 pt") return value class _Prepared: def __init__(self, root: ET.Element, width: float, height: float, scale: float | None): self.root, self.width, self.height, self.angstrom_per_unit = root, width, height, scale def _check_reference(value: str, where: str) -> None: for _q, target in _URL.findall(value): if not target.startswith("#"): raise PanelRefused(f"{where}: external reference url({target}) is refused") if "javascript:" in value.lower(): raise PanelRefused(f"{where}: script URLs are refused") def _prepare(panel: Panel, index: int) -> _Prepared: where = f"panel {index + 1}" data = panel.svg if "<!DOCTYPE" in data or "<!ENTITY" in data: raise PanelRefused(f"{where}: DOCTYPE and entity declarations are refused") try: root = ET.fromstring(data) except ET.ParseError as error: raise PanelRefused(f"{where}: not well-formed SVG ({error})") from None if root.tag != f"{_NS}svg": raise PanelRefused(f"{where}: the root element is not an SVG <svg>") prefix = f"p{index + 1}-" ids: dict[str, str] = {} for node in root.iter(): if not isinstance(node.tag, str) or not node.tag.startswith(_NS): raise PanelRefused(f"{where}: element {node.tag!r} is outside the SVG namespace") name = node.tag[len(_NS) :] if name not in _ALLOWED: raise PanelRefused(f"{where}: <{name}> is not allowed in a panel") if name == "style": css = (node.text or "").strip() if css and not re.fullmatch(r"(@font-face\s*\{[^{}]*\}\s*)+", css): raise PanelRefused(f"{where}: style sheets other than @font-face are refused") for key, value in node.attrib.items(): local = key.rsplit("}", 1)[-1] if local.lower().startswith("on"): raise PanelRefused(f"{where}: event attribute {local!r} is refused") if local == "href" and not value.startswith("#"): raise PanelRefused(f"{where}: external reference {value!r} is refused") _check_reference(value, where) if local == "id": ids[value] = prefix + value # Drop the panel's own title and style sheets; they are not part of the drawing. for parent in list(root.iter()): for child in list(parent): if child.tag in (f"{_NS}style", f"{_NS}title") or ( parent is root and child.tag == f"{_NS}desc" ): parent.remove(child) def rename(value: str) -> str: def swap(match: re.Match[str]) -> str: target = match.group(2)[1:] return f"url(#{ids.get(target, target)})" return _URL.sub(swap, value) for node in root.iter(): for key, value in list(node.attrib.items()): local = key.rsplit("}", 1)[-1] if local == "id": node.set(key, ids[value]) elif local == "href": node.set(key, "#" + ids.get(value[1:], value[1:])) elif local == "font-family" and "roboto" not in value.lower(): # PDF and PNG have the publication font only; name it first. node.set(key, "Roboto, " + value) elif "url(" in value: node.set(key, rename(value)) view = root.get("viewBox") width = _length(root.get("width"), "width") height = _length(root.get("height"), "height") box: list[float] | None = None if view is not None: try: box = [float(x) for x in view.replace(",", " ").split()] except ValueError: box = None if box is None or len(box) != 4 or box[2] <= 0 or box[3] <= 0: raise PanelRefused(f"{where}: the viewBox is not four numbers with a positive size") if width is None or height is None: if box is None: raise PanelRefused(f"{where}: give the SVG a width and height or a viewBox") if width is None and height is None: width, height = box[2], box[3] elif width is None: assert height is not None width = height * box[2] / box[3] else: height = width * box[3] / box[2] if box is None: root.set("viewBox", f"0 0 {width:g} {height:g}") stated = panel.angstrom_per_unit if stated is None and root.get("data-vibe-angstrom-per-unit") is not None: try: stated = float(root.get("data-vibe-angstrom-per-unit", "")) except ValueError: stated = None if stated is not None and not (math.isfinite(stated) and stated > 0): stated = None if stated is not None and box is not None: stated = stated * box[2] / width # per point of the panel's own size return _Prepared(root, width, height, stated) def _n(value: float) -> str: text = f"{value:.3f}".rstrip("0").rstrip(".") return "0" if text in ("-0", "") else text def _nested(prepared: _Prepared, x: float, y: float, k: float) -> str: root = prepared.root keep = { key: value for key, value in root.attrib.items() if key.rsplit("}", 1)[-1] not in ("width", "height", "x", "y", "version", "preserveAspectRatio") } attrs = "".join(f' {_attr(key)}="{html.escape(value)}"' for key, value in sorted(keep.items())) inner = "".join(ET.tostring(child, encoding="unicode") for child in root) return ( f'<svg x="{_n(x)}" y="{_n(y)}" width="{_n(prepared.width * k)}" ' f'height="{_n(prepared.height * k)}" preserveAspectRatio="xMidYMid meet"' f'{attrs} overflow="hidden">{inner}</svg>' ) def _attr(key: str) -> str: if key == _XLINK: return "href" if key.startswith("{"): raise PanelRefused(f"namespaced attribute {key!r} is not allowed on a panel root") return key
[docs] def compose_panels_svg(panels: Sequence[Panel], options: PanelOptions | None = None) -> bytes: """The labelled grid as standalone SVG (UTF-8), one unit per point.""" options = options or PanelOptions() if not panels: raise PanelRefused("give at least one panel") if len(panels) > _MAX_PANELS: raise PanelRefused(f"at most {_MAX_PANELS} panels (labels a to z)") if options.scale_bar_angstrom is not None and options.scale != "angstrom": raise PanelRefused("a common scale bar needs scale='angstrom'") ET.register_namespace("", _SVG) prepared = [_prepare(p, i) for i, p in enumerate(panels)] labels = panel_labels(len(panels), options.labels) for text in [*(p.caption for p in panels if p.caption), options.title or ""]: if text: mathtext.validate(text) width_mm = options.width_mm or COLUMN_WIDTH_MM[options.column] width = width_mm * _PT_PER_MM gap = options.gap_mm * _PT_PER_MM cols = min(options.columns, len(panels)) cell = cell_width_pt(options, len(panels)) tallest = options.max_height_mm * _PT_PER_MM if options.max_height_mm else math.inf if cell < 20: raise PanelRefused("the columns are narrower than 20 pt; use fewer columns") if options.scale == "fit": factors = [min(cell / p.width, tallest / p.height) for p in prepared] elif options.scale == "uniform": common = min(min(cell / p.width, tallest / p.height) for p in prepared) factors = [common] * len(prepared) else: missing = [str(i + 1) for i, p in enumerate(prepared) if p.angstrom_per_unit is None] if missing: raise PanelRefused( "scale='angstrom' needs every panel's angstrom_per_unit; missing for panel(s) " + ", ".join(missing) ) # One angstrom spans 1 / apu panel points; equal for all: k_i = c * apu_i. c = min(cell / (p.width * (p.angstrom_per_unit or 1.0)) for p in prepared) factors = [c * (p.angstrom_per_unit or 1.0) for p in prepared] if any(p.height * k > tallest + 1e-9 for p, k in zip(prepared, factors, strict=True)): raise PanelRefused("at the common angstrom scale a panel exceeds max_height_mm") label_h = 1.35 * options.label_size_pt if options.labels != "none" else 0.0 caption_h = 1.5 * options.caption_size_pt title_h = 1.8 * options.label_size_pt if options.title else 0.0 parts: list[str] = [] if options.title: parts.append( mathtext.svg_text( options.title, 0.0, 1.2 * options.label_size_pt, options.label_size_pt * 1.05 ) ) y = title_h for start in range(0, len(panels), cols): row = list(range(start, min(start + cols, len(panels)))) body = max(prepared[i].height * factors[i] for i in row) has_caption = any(panels[i].caption for i in row) for slot, i in enumerate(row): w = prepared[i].width * factors[i] x = slot * (cell + gap) + (cell - w) / 2 top = y + label_h parts.append(_nested(prepared[i], x, top, factors[i])) if labels[i]: parts.append( mathtext.svg_text( labels[i], x, y + 1.0 * options.label_size_pt, options.label_size_pt, weight="bold" if options.label_bold else "normal", ) ) caption = panels[i].caption if caption: parts.append( mathtext.svg_text( caption, x + w / 2, top + body + 1.1 * options.caption_size_pt, options.caption_size_pt, anchor="middle", ) ) y += label_h + body + (caption_h if has_caption else 0.0) + gap y -= gap if options.scale_bar_angstrom is not None: length = options.scale_bar_angstrom k = factors[0] / (prepared[0].angstrom_per_unit or 1.0) bar = length * k # points per angstrom times length if bar > width: raise PanelRefused("the scale bar is wider than the figure") y += 0.8 * options.caption_size_pt parts.append( f'<line x1="0" y1="{_n(y)}" x2="{_n(bar)}" y2="{_n(y)}" stroke="#000" ' 'stroke-width="1.2"/>' ) parts.append( mathtext.svg_text( f"{length:g} Å", bar + 0.4 * options.caption_size_pt, y + 0.35 * options.caption_size_pt, options.caption_size_pt, ) ) y += 0.8 * options.caption_size_pt height = y title = mathtext.plain_text(options.title) if options.title else "figure panels" svg = ( '<?xml version="1.0" encoding="UTF-8"?>\n' f'<svg xmlns="http://www.w3.org/2000/svg" width="{_n(width)}pt" height="{_n(height)}pt" ' f'viewBox="0 0 {_n(width)} {_n(height)}" font-family="Roboto, Arial, sans-serif" ' f'data-vibe-width-mm="{_n(width_mm)}">' f"<title>{html.escape(title)}</title>" f'<rect width="100%" height="100%" fill="#fff"/>{"".join(parts)}</svg>' ) return svg.encode("utf-8")
[docs] def compose_panels( panels: Sequence[Panel], options: PanelOptions | None = None, fmt: str = "svg", *, dpi: int = 300, ) -> bytes: """The labelled grid as SVG, or PDF/PNG through the publication extra.""" svg = compose_panels_svg(panels, options) if fmt == "svg": return svg if fmt not in ("pdf", "png"): raise PanelRefused(f"cannot write {fmt!r}; formats: svg, pdf, png") from vibesketcher.render.publication import convert return bytes(convert(svg, fmt, dpi=dpi))