vibe-sketcherDocumentation
Source code for vibesketcher.render.porosity_table
"""Publication table of a stored porosity estimate: CSV, SVG and TeX (#206).
The table is drawn from an estimate stored on its structure
(:mod:`vibesketcher.document.porosity_store`), never from a loose result: a stale
estimate (the structure changed since it was stored) is refused. Every table
names the quantity, its symbol, value and unit, and carries the label
"geometric planning estimate, not BET/adsorption capacity", the structure
digest, the probe, the radius table, the grid and the outcome.
"""
from __future__ import annotations
import csv
import html
import io
from typing import Any, Literal
from vibesketcher.document.porosity_store import TABLE_LABEL
TableFormat = Literal["csv", "svg", "tex"]
MEDIA_TYPES: dict[str, str] = {
"csv": "text/csv; charset=utf-8",
"svg": "image/svg+xml",
"tex": "application/x-tex; charset=utf-8",
}
def _cm3_per_g(estimate: dict[str, Any]) -> float:
cell = estimate["cell"]
return float(cell["volume_angstrom3"]) * 1e-24 / float(cell["mass_g"])
def _row(quantity: str, symbol: str, value: Any, unit: str = "") -> dict[str, Any]:
return {"quantity": quantity, "symbol": symbol, "value": value, "unit": unit}
[docs]
def rows(item: dict[str, Any]) -> list[dict[str, Any]]:
"""The table rows of a stored estimate: quantity, symbol, value and unit."""
estimate = item["estimate"]
final = estimate["result"]
per_g = _cm3_per_g(estimate)
out = [
_row("Largest included sphere", "D_i", final["di_angstrom"], "Å"),
_row("Largest free sphere", "D_f", final["df_angstrom"], "Å"),
_row("Channel dimensionality", "dim", final["dimensionality"]),
_row("Outcome", "", estimate["outcome"]["status"]),
_row("Geometric void fraction", "θ_void", final["geometric_void_fraction"]),
_row("Probe-occupiable fraction", "θ_PO", final["probe_occupiable_fraction"]),
_row("Accessible fraction", "θ_acc", final["accessible_fraction"]),
_row("Accessible pore volume", "V_acc", final["accessible_fraction"] * per_g, "cm³/g"),
]
surface = estimate.get("surface") or {}
if surface.get("definition") == "accessible":
name = "Accessible surface area"
out += [
_row(name, "ASA", surface["accessible_area_angstrom2"], "Ų/cell"),
_row(name, "ASA", surface["accessible_area_m2_per_cm3"], "m²/cm³"),
_row(name, "ASA", surface["accessible_area_m2_per_g"], "m²/g"),
]
elif surface.get("definition") == "connolly":
name = "Connolly surface area"
out += [
_row(name, "SES", surface["connolly_area_angstrom2"], "Ų/cell"),
_row(name, "SES", surface["connolly_area_m2_per_cm3"], "m²/cm³"),
_row(name, "SES", surface["connolly_area_m2_per_g"], "m²/g"),
_row(
"Accessible Connolly surface area",
"SES_acc",
surface["accessible_connolly_area_m2_per_g"],
"m²/g",
),
_row(
"Excluded (Connolly) volume fraction", "θ_SE", surface["excluded_volume_fraction"]
),
_row(
"Connolly occupiable pore volume", "V_PO", surface["occupiable_cm3_per_g"], "cm³/g"
),
]
converged = _yes(estimate["convergence"]["converged"])
out += [
_row("Framework density", "ρ", estimate["cell"]["density_g_per_cm3"], "g/cm³"),
_row("Grid ladder converged", "", converged),
]
return out
def _yes(value: Any) -> str:
return {True: "yes", False: "no"}.get(value, "not assessed")
def _value(row: dict[str, Any]) -> str:
value = row["value"]
if isinstance(value, (bool, str, int)):
return str(value)
return f"{float(value):.4g}"
def _header(item: dict[str, Any]) -> list[str]:
estimate = item["estimate"]
plan = estimate["plan"]
final = estimate["result"]
table = estimate["radius_table"]
probe = plan["probe"]
return [
f"{item['structure']} estimate {item['id']}: {TABLE_LABEL}",
f"structure sha256 {item['structure_sha256']}",
f"probe {probe['species']} r = {probe['radius_angstrom']} Å; radii {table['name']} "
f"({table['source']}, {table['version']})",
f"engine {estimate['engine']['name']}; grid {'x'.join(map(str, final['grid_shape']))} "
f"spacing {final['spacing_angstrom']} Å; seed {plan['sampling']['seed']}; "
f"surface {plan['surface']}",
]
def _check(item: dict[str, Any]) -> None:
if item.get("stale") is not False or "estimate" not in item:
raise ValueError("only a current stored estimate makes a publication table; refusing")
[docs]
def table_csv(item: dict[str, Any]) -> str:
"""The table as CSV with '#' provenance lines (full precision values)."""
_check(item)
buffer = io.StringIO()
for line in _header(item):
buffer.write(f"# {line}\n")
writer = csv.writer(buffer, lineterminator="\n")
writer.writerow(["quantity", "symbol", "value", "unit"])
for row in rows(item):
value = row["value"]
text = f"{value:.8g}" if isinstance(value, float) else str(value)
writer.writerow([row["quantity"], row["symbol"], text, row["unit"]])
return buffer.getvalue()
_TEX = {
"&": r"\&",
"%": r"\%",
"$": r"\$",
"#": r"\#",
"_": r"\_",
"{": r"\{",
"}": r"\}",
"~": r"\textasciitilde{}",
"^": r"\textasciicircum{}",
"\\": r"\textbackslash{}",
}
_TEX_UNITS = {
"Å": r"\AA",
"Ų/cell": r"\AA$^{2}$ per cell",
"m²/cm³": r"m$^{2}$\,cm$^{-3}$",
"m²/g": r"m$^{2}$\,g$^{-1}$",
"cm³/g": r"cm$^{3}$\,g$^{-1}$",
"g/cm³": r"g\,cm$^{-3}$",
"": "",
}
_TEX_SYMBOLS = {
"D_i": "$D_\\mathrm{i}$",
"D_f": "$D_\\mathrm{f}$",
"θ_void": "$\\theta_\\mathrm{void}$",
"θ_PO": "$\\theta_\\mathrm{PO}$",
"θ_acc": "$\\theta_\\mathrm{acc}$",
"θ_SE": "$\\theta_\\mathrm{SE}$",
"V_acc": "$V_\\mathrm{acc}$",
"V_PO": "$V_\\mathrm{PO}$",
"SES_acc": "SES$_\\mathrm{acc}$",
"ρ": "$\\rho$",
}
def _tex(text: str) -> str:
out = "".join(_TEX.get(c, c) for c in text)
return out.replace("Å", r"\AA{}")
[docs]
def table_tex(item: dict[str, Any]) -> str:
"""The table as a LaTeX ``table`` float (tabular, booktabs-free, plain LaTeX)."""
_check(item)
header = _header(item)
lines = [f"% {_tex(line)}" for line in header] + [
r"\begin{table}",
r"\centering",
f"\\caption{{{_tex(item['structure'])}: {_tex(TABLE_LABEL)}. Probe "
f"{_tex(item['estimate']['plan']['probe']['species'])}, $r = "
f"{item['estimate']['plan']['probe']['radius_angstrom']}$~\\AA{{}}; structure "
f"SHA-256 \\texttt{{{item['structure_sha256'][:16]}}}.}}",
r"\begin{tabular}{llrl}",
r"\hline",
r"Quantity & Symbol & Value & Unit \\",
r"\hline",
]
for row in rows(item):
symbol = _TEX_SYMBOLS.get(row["symbol"], _tex(row["symbol"]))
lines.append(
f"{_tex(row['quantity'])} & {symbol} & {_tex(_value(row))} & "
f"{_TEX_UNITS.get(row['unit'], _tex(row['unit']))} \\\\"
)
lines += [r"\hline", r"\end{tabular}", r"\end{table}"]
return "\n".join(lines) + "\n"
[docs]
def table_svg(item: dict[str, Any]) -> bytes:
"""The table as standalone SVG (UTF-8) with its provenance lines beneath."""
_check(item)
body = rows(item)
header = _header(item)
font, row_h, pad = 11.0, 18.0, 10.0
columns = [(pad, "start"), (250.0, "start"), (420.0, "end"), (430.0, "start")]
width = 560.0
top = 30.0
height = top + row_h * (len(body) + 1) + 14.0 * len(header) + 3 * pad
title = f"{item['structure']}: porosity ({TABLE_LABEL})"
parts = [
f'<text x="{pad}" y="18" font-size="{font * 1.1:.1f}">{html.escape(title)}</text>',
f'<line x1="{pad}" y1="{top}" x2="{width - pad}" y2="{top}" stroke="#000" '
'stroke-width="0.8"/>',
]
for (x, anchor), text in zip(columns, ("Quantity", "Symbol", "Value", "Unit"), strict=True):
parts.append(
f'<text x="{x}" y="{top + 13}" font-size="{font}" font-weight="bold" '
f'text-anchor="{anchor}">{text}</text>'
)
y = top + row_h
parts.append(
f'<line x1="{pad}" y1="{y}" x2="{width - pad}" y2="{y}" stroke="#000" stroke-width="0.5"/>'
)
for row in body:
cells = (row["quantity"], row["symbol"], _value(row), row["unit"])
for (x, anchor), text in zip(columns, cells, strict=True):
parts.append(
f'<text x="{x}" y="{y + 13}" font-size="{font}" '
f'text-anchor="{anchor}">{html.escape(text)}</text>'
)
y += row_h
parts.append(
f'<line x1="{pad}" y1="{y + 2}" x2="{width - pad}" y2="{y + 2}" stroke="#000" '
'stroke-width="0.8"/>'
)
for i, line in enumerate(header[1:]):
parts.append(
f'<text x="{pad}" y="{y + pad + 12 + 14 * i}" font-size="{font * 0.75:.2f}">'
f"{html.escape(line[:150])}</text>"
)
svg = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width:g}" height="{height:g}" '
f'viewBox="0 0 {width:g} {height:g}" 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 table(item: dict[str, Any], fmt: str) -> bytes:
"""The table in ``fmt`` (csv, svg or tex)."""
if fmt == "csv":
return table_csv(item).encode("utf-8")
if fmt == "tex":
return table_tex(item).encode("utf-8")
if fmt == "svg":
return table_svg(item)
raise ValueError(f"cannot write a table as {fmt!r}; formats: csv, svg, tex")