vibe-sketcherDocumentation

Source code for vibesketcher.render.porosity

"""Publication figure of a geometric pore-size distribution (#206).

Drawn from a :mod:`vibesketcher.document.porosity` estimate: the PSD as bars
(the stated normalisation per bin), the cumulative curve on the right axis,
and provenance lines naming the structure digest, probe, radius table, grid,
outcome and the label "geometric planning estimate". Styling follows the
powder overlays: white background, Arial/Helvetica, SVG with PDF/PNG through
the publication extra. A distribution without volume is refused, never drawn
empty.
"""

from __future__ import annotations

import html
from typing import Any, Literal

from pydantic import BaseModel, ConfigDict, Field

from vibesketcher.document.porosity import PorosityRefused, _check_result
from vibesketcher.render.diffraction import _fmt, _n, _nice_ticks

_BARS, _CUMULATIVE = "#1f5fbf", "#c0392b"


[docs] class PsdFigureOptions(BaseModel): """What the figure shows; every choice is stated.""" model_config = ConfigDict(extra="forbid") #: Bars as the bin fraction or as the density per angstrom of diameter. quantity: Literal["fraction", "density_per_angstrom"] = "fraction" cumulative: bool = True width: float = Field(default=640, ge=200, le=4000) height: float = Field(default=400, ge=150, le=3000) title: str | None = Field(default=None, max_length=200) provenance: bool = True
def _provenance(result: dict[str, Any]) -> list[str]: plan, final, table = result["plan"], result["result"], result["radius_table"] source = result["source"] psd = result["psd"] return [ line[:180] for line in ( f"{source['structure']} (sha256 {source['structure_sha256'][:12]}); probe " f"{plan['probe']['species']} r = {plan['probe']['radius_angstrom']} Å; radii " f"{table['name']} ({table['version']})", f"Grid {'x'.join(map(str, final['grid_shape']))}, spacing {final['spacing_angstrom']} " f"Å, resolution {final['resolution_angstrom']:.3f} Å; outcome " f"{result['outcome']['status']}; region {psd['region']}, {psd['normalisation']}", "Geometric planning estimate (Gelb-Gubbins PSD); not adsorption capacity or BET area.", ) ]
[docs] def psd_svg(result: dict[str, Any], options: PsdFigureOptions | None = None) -> bytes: """The PSD figure as standalone SVG (UTF-8).""" _check_result(result) options = options or PsdFigureOptions() psd = result["psd"] bins = psd["bins"] if not bins or not any(row["fraction"] > 0 for row in bins): raise PorosityRefused( [ { "code": "porosity.empty_distribution", "message": "the pore-size distribution has no volume " f"(outcome {result['outcome']['status']}); nothing to draw", } ] ) key = options.quantity lo = float(bins[0]["diameter_lo_angstrom"]) hi = float(bins[-1]["diameter_hi_angstrom"]) top = max(float(row[key]) for row in bins) cum_top = max(float(row["cumulative_fraction"]) for row in bins) or 1.0 footer = _provenance(result) if options.provenance else [] font = 11.0 left, right, top_pad = 64.0, 60.0 if options.cumulative else 16.0, 30.0 axis_band = 38.0 foot_h = 13.0 * len(footer) + (6.0 if footer else 0.0) plot_w = options.width - left - right plot_h = options.height - top_pad - axis_band - foot_h if plot_h < 60: raise ValueError("the figure is too short for its provenance lines; raise height") y_hi = top * 1.05 def px(x: float) -> float: return left + (x - lo) / (hi - lo) * plot_w def py(y: float, scale: float = y_hi) -> float: return top_pad + plot_h - y / scale * plot_h parts = [ f'<rect x="{_n(left)}" y="{_n(top_pad)}" width="{_n(plot_w)}" ' f'height="{_n(plot_h)}" fill="none" stroke="#000" stroke-width="0.8"/>' ] for row in bins: x0, x1 = px(float(row["diameter_lo_angstrom"])), px(float(row["diameter_hi_angstrom"])) y = py(float(row[key])) parts.append( f'<rect x="{_n(x0)}" y="{_n(y)}" width="{_n(max(x1 - x0 - 0.5, 0.5))}" ' f'height="{_n(top_pad + plot_h - y)}" fill="{_BARS}" ' 'fill-opacity="0.75"/>' ) if options.cumulative: points = " ".join( f"{_n(px(float(r['diameter_lo_angstrom'])))}," f"{_n(py(float(r['cumulative_fraction']), cum_top * 1.05))}" for r in bins ) parts.append( f'<polyline points="{points}" fill="none" stroke="{_CUMULATIVE}" stroke-width="1.2"/>' ) for value in _nice_ticks(0.0, cum_top * 1.05, 5): y = py(value, cum_top * 1.05) if y < top_pad - 0.5: continue parts.append( f'<line x1="{_n(left + plot_w - 4)}" y1="{_n(y)}" ' f'x2="{_n(left + plot_w)}" y2="{_n(y)}" stroke="{_CUMULATIVE}" ' f'stroke-width="0.8"/><text x="{_n(left + plot_w + 4)}" ' f'y="{_n(y + 3.5)}" font-size="{_n(font * 0.9)}" ' f'fill="{_CUMULATIVE}">{_fmt(value)}</text>' ) cy = top_pad + plot_h / 2 rx = options.width - 12 parts.append( f'<text x="{_n(rx)}" y="{_n(cy)}" font-size="{_n(font)}" ' f'text-anchor="middle" fill="{_CUMULATIVE}" ' f'transform="rotate(90 {_n(rx)} {_n(cy)})">Cumulative (this size or larger)</text>' ) base = top_pad + plot_h for value in _nice_ticks(lo, hi): x = px(value) parts.append( f'<line x1="{_n(x)}" y1="{_n(base)}" x2="{_n(x)}" y2="{_n(base - 4)}" ' f'stroke="#000" stroke-width="0.8"/><text x="{_n(x)}" ' f'y="{_n(base + 13)}" font-size="{_n(font * 0.9)}" ' f'text-anchor="middle">{_fmt(value)}</text>' ) parts.append( f'<text x="{_n(left + plot_w / 2)}" y="{_n(base + 30)}" ' f'font-size="{_n(font)}" text-anchor="middle">Pore diameter (Å)</text>' ) for value in _nice_ticks(0.0, y_hi, 5): y = py(value) if y < top_pad - 0.5: continue parts.append( f'<line x1="{_n(left)}" y1="{_n(y)}" x2="{_n(left + 4)}" y2="{_n(y)}" ' f'stroke="#000" stroke-width="0.8"/><text x="{_n(left - 4)}" ' f'y="{_n(y + 3.5)}" font-size="{_n(font * 0.9)}" text-anchor="end">' f"{_fmt(value)}</text>" ) region = "region" if psd["normalisation"] == "region_fraction" else "cell" y_label = ( f"Fraction of {region} volume" if key == "fraction" else f"Fraction of {region} volume per Å" ) cy = top_pad + plot_h / 2 parts.append( f'<text x="14" y="{_n(cy)}" font-size="{_n(font)}" text-anchor="middle" ' f'transform="rotate(-90 14 {_n(cy)})">{html.escape(y_label)}</text>' ) title = options.title or f"{result['source']['structure']}: geometric pore-size distribution" parts.append( f'<text x="{_n(left)}" y="{_n(top_pad - 10)}" font-size="{_n(font * 1.1)}">' f"{html.escape(title)}</text>" ) fy = base + axis_band for i, line in enumerate(footer): parts.append( f'<text x="8" y="{_n(fy + 13 * i + 10)}" font-size="{_n(font * 0.75)}">' f"{html.escape(line)}</text>" ) w, h = options.width, options.height svg = ( '<?xml version="1.0" encoding="UTF-8"?>\n' f'<svg xmlns="http://www.w3.org/2000/svg" width="{_n(w)}" height="{_n(h)}" ' f'viewBox="0 0 {_n(w)} {_n(h)}" font-family="Arial, Helvetica, sans-serif">' f"<title>{html.escape(title)}</title>" f'<rect width="100%" height="100%" fill="#fff"/>{"".join(parts)}</svg>' ) return svg.encode("utf-8")
[docs] def psd_figure( result: dict[str, Any], options: PsdFigureOptions | None = None, fmt: str = "svg", *, dpi: int = 300, ) -> bytes: """SVG, or PDF/PNG through the publication extra.""" svg = psd_svg(result, options) if fmt == "svg": return svg if fmt not in ("pdf", "png"): raise ValueError(f"cannot write {fmt!r}; formats: svg, pdf, png") from vibesketcher.render.publication import convert return bytes(convert(svg, fmt, dpi=dpi))