vibe-sketcherDocumentation

Source code for vibesketcher.render.diffraction

"""Publication figures of powder patterns: measured against calculated (#207).

The figure is drawn from the calculated result of
:mod:`vibesketcher.document.diffraction` and, optionally, a measured pattern
read by :mod:`vibesketcher.document.measured_patterns`: the measured curve,
the calculated profile (or sticks when no profile was asked for), a row of
reflection tick marks under the curves, and provenance lines naming both
sources by their SHA-256 digests, the wavelengths and the instrument fields
as given. The calculated curve is scaled to the measured maximum *for
display*; the factor is printed and nothing is fitted.

The x axis is 2theta (degrees), d (angstrom) or Q = 2 pi / d (1/angstrom).
A measured 2theta axis is compared in 2theta only at the calculated
wavelength, and converted to d or Q only with its stated wavelength; other
combinations are refused rather than shifted. Styling follows the periodic
figures: white background, Arial/Helvetica, SVG with PDF/PNG through the
publication extra.
"""

from __future__ import annotations

import html
import math
from typing import Any, Literal

from pydantic import BaseModel, ConfigDict, Field

from vibesketcher.document.measured_patterns import MeasuredPatternRefused, convert_axis

PlotAxis = Literal["two_theta_deg", "d_angstrom", "q_inv_angstrom"]

_LABELS = {
    "two_theta_deg": "2θ (degrees)",
    "d_angstrom": "d (Å)",
    "q_inv_angstrom": "Q (1/Å)",
}
_UNITS = {"counts": "counts", "counts_per_second": "counts/s", "arbitrary": "arb. units"}
_MEASURED, _CALCULATED, _TICKS = "#000000", "#c0392b", "#1f5fbf"


[docs] class OverlayOptions(BaseModel): """What the overlay shows; every choice is stated.""" model_config = ConfigDict(extra="forbid") axis: PlotAxis = "two_theta_deg" x_range: tuple[float, float] | None = None ticks: bool = True #: Label the hkl of the n strongest reflections above their ticks. label_reflections: int = Field(default=0, ge=0, le=50) 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
[docs] class OverlayRefused(ValueError): """The two patterns cannot be put on one axis faithfully."""
def _n(value: float) -> str: return f"{value:.2f}" def _nice_ticks(lo: float, hi: float, target: int = 6) -> list[float]: span = hi - lo if span <= 0: return [lo] raw = span / target power = 10 ** math.floor(math.log10(raw)) step = min((m * power for m in (1, 2, 2.5, 5, 10) if m * power >= raw), default=10 * power) first = math.ceil(lo / step - 1e-9) * step out, value = [], first while value <= hi + 1e-9 * step: out.append(round(value, 10)) value += step return out def _fmt(value: float) -> str: text = f"{value:.6g}" return text if "e" not in text else f"{value:.2e}" def _nearest(points: list[tuple[float, float]], x: float) -> float: return min(points, key=lambda p: abs(p[0] - x))[1] def _hkl_label(hkl: list[int]) -> str: """(hkl) with a minus sign for negative indices, spaced when ambiguous.""" parts = [f"\u2212{-v}" if v < 0 else str(v) for v in hkl] spaced = any(v < 0 or v > 9 for v in hkl) return "(" + (" ".join(parts) if spaced else "".join(parts)) + ")" def _short(digest: str | None) -> str: return f"sha256 {digest[:12]}" if digest else "no digest" def _measured_x(measured: dict[str, Any], axis: str, calc_wavelength: float) -> list[float]: prov = measured["provenance"] source, wavelength = prov["axis"], prov.get("wavelength_angstrom") if source == "two_theta_deg" and axis == "two_theta_deg": if wavelength is None: raise OverlayRefused( "the measured 2theta pattern has no stated wavelength; state it, or plot in d or Q" ) if abs(wavelength - calc_wavelength) > 1e-5: raise OverlayRefused( f"the measured wavelength {wavelength:g} A differs from the calculated " f"{calc_wavelength:g} A; recalculate at the measured wavelength or plot in d or Q" ) if source != "two_theta_deg" and axis == "two_theta_deg": wavelength = calc_wavelength # d and Q do not depend on the wavelength try: return convert_axis(list(measured["x"]), source, axis, wavelength) except MeasuredPatternRefused as error: raise OverlayRefused(str(error)) from None
[docs] def overlay_svg( calculated: dict[str, Any], measured: dict[str, Any] | None = None, options: OverlayOptions | None = None, ) -> bytes: """The overlay as standalone SVG (UTF-8).""" options = options or OverlayOptions() axis = options.axis wavelength = float(calculated["wavelength_angstrom"]) reflections = calculated["reflections"] key = {"two_theta_deg": "two_theta_deg", "d_angstrom": "d_angstrom", "q_inv_angstrom": "q_inv_angstrom"}[axis] # fmt: skip ref_x = [float(r[key]) for r in reflections] calc_curve: list[tuple[float, float]] = [] profile = calculated.get("profile") if profile: xs = convert_axis(profile["two_theta_deg"], "two_theta_deg", axis, wavelength) calc_curve = list(zip(xs, profile["intensity"], strict=True)) meas_curve: list[tuple[float, float]] = [] if measured is not None: mx = _measured_x(measured, axis, wavelength) meas_curve = list(zip(mx, measured["intensity"], strict=True)) # Range: stated, else the union of what is drawn. if options.x_range is not None: lo, hi = sorted(options.x_range) else: candidates = [x for x, _ in meas_curve] + [x for x, _ in calc_curve] + ref_x if not candidates: raise OverlayRefused("nothing to draw: no reflections and no measured pattern") if axis == "two_theta_deg": span = calculated["two_theta_range_deg"] candidates += [float(span[0]), float(span[1])] if not meas_curve else [] lo, hi = min(candidates), max(candidates) if hi <= lo: raise OverlayRefused("the x range is empty") def inside(points: list[tuple[float, float]]) -> list[tuple[float, float]]: return sorted(p for p in points if lo <= p[0] <= hi) meas_curve, calc_curve = inside(meas_curve), inside(calc_curve) shown = [(x, r) for x, r in zip(ref_x, reflections, strict=True) if lo <= x <= hi] # Display scaling of the calculated curve to the measured maximum (no fit). meas_max = max((y for _x, y in meas_curve), default=0.0) meas_min = min((y for _x, y in meas_curve), default=0.0) calc_values = [y for _x, y in calc_curve] or [float(r["relative_intensity"]) for _x, r in shown] calc_max = max(calc_values, default=0.0) if meas_curve: scale = (meas_max - min(meas_min, 0.0)) / calc_max if calc_max > 0 else 1.0 y_lo, y_hi = min(meas_min, 0.0), meas_max y_label = f"Intensity ({_UNITS[measured['provenance']['intensity_unit']]})" # type: ignore[index] else: scale, y_lo, y_hi, y_label = 1.0, 0.0, 100.0, "Relative intensity" if y_hi <= y_lo: y_hi = y_lo + 1.0 y_hi_plot = y_hi + 0.05 * (y_hi - y_lo) footer = _provenance(calculated, measured, scale) if options.provenance else [] font = 11.0 left, right = 64.0, 16.0 top = 30.0 tick_band = 22.0 if options.ticks and shown else 0.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 - tick_band - axis_band - foot_h if plot_h < 60: raise OverlayRefused("the figure is too short for its provenance lines; raise height") def px(x: float) -> float: return left + (x - lo) / (hi - lo) * plot_w def py(y: float) -> float: return top + plot_h - (y - y_lo) / (y_hi_plot - y_lo) * plot_h parts: list[str] = [] parts.append(f'<rect x="{_n(left)}" y="{_n(top)}" width="{_n(plot_w)}" height="{_n(plot_h)}" ' 'fill="none" stroke="#000" stroke-width="0.8"/>') # fmt: skip clip = (f'<clipPath id="plot"><rect x="{_n(left)}" y="{_n(top)}" width="{_n(plot_w)}" ' f'height="{_n(plot_h)}"/></clipPath>') # fmt: skip if meas_curve: points = " ".join(f"{_n(px(x))},{_n(py(y))}" for x, y in meas_curve) parts.append(f'<polyline clip-path="url(#plot)" points="{points}" fill="none" ' f'stroke="{_MEASURED}" stroke-width="0.9"/>') # fmt: skip if calc_curve: base = y_lo if meas_curve else 0.0 points = " ".join(f"{_n(px(x))},{_n(py(base + scale * y))}" for x, y in calc_curve) parts.append(f'<polyline clip-path="url(#plot)" points="{points}" fill="none" ' f'stroke="{_CALCULATED}" stroke-width="0.9"/>') # fmt: skip elif shown: base = y_lo if meas_curve else 0.0 for x, r in shown: parts.append( f'<line x1="{_n(px(x))}" y1="{_n(py(base))}" x2="{_n(px(x))}" ' f'y2="{_n(py(base + scale * float(r["relative_intensity"])))}" ' f'stroke="{_CALCULATED}" stroke-width="1"/>' ) # Reflection tick marks below the plot. tick_y = top + plot_h + 4.0 if tick_band: for x, _r in shown: parts.append(f'<line x1="{_n(px(x))}" y1="{_n(tick_y)}" x2="{_n(px(x))}" ' f'y2="{_n(tick_y + 12)}" stroke="{_TICKS}" ' 'stroke-width="0.9"/>') # fmt: skip if options.label_reflections: strongest = sorted(shown, key=lambda item: -float(item[1]["intensity"])) for x, r in strongest[: options.label_reflections]: label = _hkl_label(r["hkl"]) base = y_lo if meas_curve else 0.0 near = _nearest(calc_curve, x) if calc_curve else r["relative_intensity"] y = py(base + scale * near) - 4 parts.append(f'<text x="{_n(px(x))}" y="{_n(max(y, top + 10))}" ' f'font-size="{_n(font * 0.8)}" text-anchor="middle">' f"{html.escape(label)}</text>") # fmt: skip # Axes. x_base = top + plot_h + tick_band for value in _nice_ticks(lo, hi): x = px(value) parts.append(f'<line x1="{_n(x)}" y1="{_n(top + plot_h)}" x2="{_n(x)}" ' f'y2="{_n(top + plot_h - 4)}" stroke="#000" stroke-width="0.8"/>' f'<text x="{_n(x)}" y="{_n(x_base + 13)}" font-size="{_n(font * 0.9)}" ' f'text-anchor="middle">{_fmt(value)}</text>') # fmt: skip parts.append(f'<text x="{_n(left + plot_w / 2)}" y="{_n(x_base + 30)}" font-size="{_n(font)}" ' f'text-anchor="middle">{html.escape(_LABELS[axis])}</text>') # fmt: skip for value in _nice_ticks(y_lo, y_hi_plot, 5): y = py(value) if y < top - 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>") # fmt: skip cy = top + 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>') # fmt: skip # Legend and title. legend = [] if meas_curve: legend.append(("measured", _MEASURED)) if calc_curve or shown: legend.append(("calculated" + (f" × {scale:.3g}" if meas_curve else ""), _CALCULATED)) if tick_band: legend.append(("reflections", _TICKS)) lx = left + plot_w - 8 for i, (text, colour) in enumerate(legend): y = top + 14 + 14 * i parts.append(f'<line x1="{_n(lx - 18)}" y1="{_n(y - 4)}" x2="{_n(lx)}" y2="{_n(y - 4)}" ' f'stroke="{colour}" stroke-width="1.5"/><text x="{_n(lx - 22)}" y="{_n(y)}" ' f'font-size="{_n(font * 0.85)}" text-anchor="end">' f"{html.escape(text)}</text>") # fmt: skip source = calculated.get("source", {}) title = options.title or str(source.get("structure") or source.get("block") or "pattern") parts.append(f'<text x="{_n(left)}" y="{_n(top - 10)}" font-size="{_n(font * 1.1)}">' f"{html.escape(title)}</text>") # fmt: skip fy = x_base + axis_band for i, line in enumerate(footer): parts.append(f'<text x="{_n(8)}" y="{_n(fy + 13 * i + 10)}" font-size="{_n(font * 0.75)}">' f"{html.escape(line)}</text>") # fmt: skip w, h = options.width, options.height svg = ( '<?xml version="1.0" encoding="UTF-8"?>\n' # Print size in pt (SVG px are 0.75 pt) so PNG follows dpi; Roboto is the # publication font, the only one PDF and PNG converters load (#251). f'<svg xmlns="http://www.w3.org/2000/svg" width="{_n(0.75 * w)}pt" ' f'height="{_n(0.75 * h)}pt" ' f'viewBox="0 0 {_n(w)} {_n(h)}" font-family="Roboto, Arial, sans-serif">' f"<title>{html.escape(title)}</title><defs>{clip}</defs>" f'<rect width="100%" height="100%" fill="#fff"/>{"".join(parts)}</svg>' ) return svg.encode("utf-8")
def _provenance( calculated: dict[str, Any], measured: dict[str, Any] | None, scale: float ) -> list[str]: source = calculated.get("source", {}) digest = source.get("structure_sha256") or source.get("cif_sha256") name = source.get("structure") or source.get("block") or "model" texture = (calculated.get("settings") or {}).get("preferred_orientation") oriented = ( f"March-Dollase ({' '.join(str(i) for i in texture['hkl'])})*, r = {texture['r']:g}" if isinstance(texture, dict) else "no preferred orientation" ) lines = [ f"Calculated: {name} ({_short(digest)}); λ = {calculated['wavelength_angstrom']:.7f} " f"Å ({calculated['wavelength_source']}); {calculated['polarisation']}; " f"Waasmaier-Kirfel f0; kinematic, no absorption; {oriented}" ] if measured is not None: prov = measured["provenance"] wl = prov.get("wavelength_angstrom") instrument = "; ".join(f"{k}: {v}" for k, v in prov.get("instrument", {}).items()) lines.append( f"Measured: {prov['file_name']} ({_short(prov['sha256'])}); x as " f"{prov['axis']}; λ = {wl if wl is not None else 'not stated'}" + (f" Å; {instrument}" if instrument else (" Å" if wl is not None else "")) ) lines.append(f"Calculated curve scaled by {scale:.4g} for display; no fit or refinement.") return [line[:180] for line in lines]
[docs] def overlay_figure( calculated: dict[str, Any], measured: dict[str, Any] | None = None, options: OverlayOptions | None = None, fmt: str = "svg", *, dpi: int = 300, ) -> bytes: """SVG, or PDF/PNG through the publication extra.""" svg = overlay_svg(calculated, measured, options) if fmt == "svg": return svg if fmt not in ("pdf", "png"): raise OverlayRefused(f"cannot write {fmt!r}; formats: svg, pdf, png") from vibesketcher.render.publication import convert return bytes(convert(svg, fmt, dpi=dpi))