vibe-sketcherDocumentation

Source code for vibesketcher.render.cyclic_topology

"""Cyclic-topology schematics: a ring for one periodic dimension, a torus for two (#247).

A cyclic cluster (and the AICCM torus of :mod:`vibesketcher.inputs.aiccm`)
is the input cell repeated ``N1 x N2 x N3`` times with Born-von Karman
boundary conditions: cell ``N`` along an axis *is* cell ``0``. This module
draws that identification from the unchanged model, in two panels:

- the **unrolled sheet**: the ``N1`` (x ``N2``) cells laid flat in the true
  lattice geometry, every atom at its fractional position, bonds found across
  the cells, and the identified edges marked with matching arrows (one arrow
  for the edges parallel to the first drawn axis, two for the second), the
  usual notation for gluing a square into a torus;
- the **cyclic shape**: a ring (one drawn axis) or a 2-D projection of the
  parametric torus ``((R + r cos t) cos p, (R + r cos t) sin p, r sin t)``
  with ``p = 2 pi u`` along the first axis and ``t = 2 pi v`` along the
  second, where ``u = (n1 + f1) / N1`` and ``v = (n2 + f2) / N2``. The cells
  are a grid on the surface, the seams ``u = 0`` and ``v = 0`` (where the
  identification happens) are drawn in the accent colour with the same arrow
  marks as the sheet, and every bond that crosses a seam, a *wrap-around
  bond*, is drawn in the accent colour in both panels.

The torus surface is shaded with a Lambert term and drawn back to front
(painter's algorithm) from its front-facing facets; a closed surface hides
every facet that faces away. The torus is a schematic: its radii are chosen
for legibility, not to scale, and the figure says so. The sheet is to scale.

Bonds are the structure's stored bonds (``suppressed`` ones excluded) when it
has any, otherwise pairs closer than 1.15 times the sum of RDKit's covalent
radii (Cordero et al., Dalton Trans. 2832 (2008)), as in the periodic
figures. Nothing here changes the structure; a figure drawn twice from the
same model and options is byte-identical.
"""

from __future__ import annotations

import html
import itertools
import math
from collections.abc import Sequence
from typing import Any, Literal

import numpy as np
from pydantic import BaseModel, ConfigDict, Field

from vibesketcher.document import crystal
from vibesketcher.document.model import PeriodicSite, PeriodicStructure
from vibesketcher.render import mathtext

__all__ = [
    "TopologyOptions",
    "TopologyRefused",
    "structure_from_record",
    "topology_figure",
    "topology_figure_from_record",
    "topology_svg",
]

_ACCENT = "#c0392b"
_GRID = "#3d4852"
_BOND = "#555555"
_SURFACE = (222, 229, 238)
_MAX_ATOMS = 3000
_MAX_CELLS = 48


[docs] class TopologyOptions(BaseModel): """What the cyclic-topology schematic shows; every choice is stated.""" model_config = ConfigDict(extra="forbid") #: The periodic axes drawn (0 = a, 1 = b, 2 = c): one gives a ring, two a #: torus. Default: every periodic axis of the structure, which must be one #: or two; a 3-D structure names two. axes: tuple[int] | tuple[int, int] | None = None atoms: bool = True bonds: bool = True #: Seams and wrap-around bonds in the accent colour, with identification arrows. seams: bool = True #: The unrolled sheet beside the ring or torus. unrolled: bool = True #: Cell indices in the sheet (and around a ring); None: when there are at most 36 cells. cell_labels: bool | None = None #: Torus view: the camera's elevation above the torus plane, in degrees. elevation_deg: float = Field(default=32.0, ge=10.0, le=80.0) #: Torus major radius over tube radius. aspect: float = Field(default=2.4, ge=1.5, le=6.0) atom_scale: float = Field(default=1.0, gt=0, le=3.0) #: Figure width and text size in points (72 per inch). width: float = Field(default=504.0, ge=120.0, le=4000.0) font_size: float = Field(default=9.0, ge=4.0, le=36.0) #: Figure title; ``$...$`` math is allowed (:mod:`vibesketcher.render.mathtext`). title: str | None = Field(default=None, max_length=300) #: Provenance lines under the panels. caption: bool = True
[docs] class TopologyRefused(ValueError): """The structure, repeats or options cannot be drawn as a cyclic topology."""
def _n(value: float) -> str: text = f"{value:.3f}".rstrip("0").rstrip(".") return "0" if text in ("-0", "") else text # ── The model: sites, images and bonds on the torus ───────────────────── def _resolve( structure: PeriodicStructure, repeats: Sequence[int], options: TopologyOptions ) -> tuple[tuple[int, int, int], list[int]]: if len(repeats) != 3 or any( isinstance(n, bool) or not isinstance(n, int) or n < 1 for n in repeats ): raise TopologyRefused("repeats are three integers of at least 1, e.g. (3, 2, 1)") reps = (int(repeats[0]), int(repeats[1]), int(repeats[2])) periodic = [a for a in range(3) if structure.pbc[a]] if any(reps[a] != 1 for a in range(3) if not structure.pbc[a]): raise TopologyRefused("repeats are 1 along non-periodic axes") if options.axes is None: if len(periodic) == 3: raise TopologyRefused( "a three-dimensional torus cannot be drawn; name the two axes to draw (axes)" ) axes = periodic else: axes = list(options.axes) if len(set(axes)) != len(axes) or any(a not in periodic for a in axes): raise TopologyRefused("axes are distinct periodic axes of the structure (0, 1, 2)") if any(reps[a] > _MAX_CELLS for a in axes): raise TopologyRefused(f"at most {_MAX_CELLS} cells along a drawn axis") cells = math.prod(reps[a] for a in axes) if cells * len(structure.sites) > _MAX_ATOMS: raise TopologyRefused(f"the schematic would draw more than {_MAX_ATOMS} atoms") return reps, axes def _radius(symbol: str) -> float: from vibesketcher.render.periodic import _radius as covalent try: return covalent(symbol) except KeyError: raise TopologyRefused(f"unknown element {symbol!r}") from None def _colour(symbol: str) -> str: from vibesketcher.render.periodic import _COLOURS return _COLOURS.get(symbol, "#B0B0B0") def _cell_bonds(structure: PeriodicStructure) -> tuple[list[tuple[int, int, np.ndarray]], str]: """Bonds of the input cell as (site i, site j, cell image of j).""" index = {s.id: i for i, s in enumerate(structure.sites)} stored = [b for b in structure.bonds if b.kind != "suppressed"] if stored: out = [ (index[b.a], index[b.b], np.asarray(b.image, dtype=float)) for b in stored if b.a in index and b.b in index ] return out, f"{len(out)} stored bonds per cell" rows = crystal.lattice_rows(structure) frac = np.asarray([s.fractional for s in structure.sites], dtype=float) radii = [_radius(s.symbol) for s in structure.sites] shifts = list(itertools.product(*((-1, 0, 1) if p else (0,) for p in structure.pbc))) found: list[tuple[int, int, np.ndarray]] = [] for i, j in itertools.product(range(len(frac)), repeat=2): for shift in shifts: image = np.asarray(shift, dtype=float) if j < i or (j == i and tuple(shift) <= (0, 0, 0)): continue distance = float(np.linalg.norm((frac[j] + image - frac[i]) @ rows)) if 0.4 < distance < 1.15 * (radii[i] + radii[j]): found.append((i, j, image)) return found, "bonds from covalent radii (1.15 x sum)" class _Torus: """Sites and bonds in torus coordinates: u along the first drawn axis, v the second.""" def __init__( self, structure: PeriodicStructure, reps: tuple[int, int, int], axes: list[int] ) -> None: self.structure, self.reps, self.axes = structure, reps, axes self.n = [reps[a] for a in axes] + [1] * (2 - len(axes)) frac = np.asarray([s.fractional for s in structure.sites], dtype=float) self.frac = frac cells = list(itertools.product(*(range(n) for n in self.n))) self.cells = cells # Atoms: (site index, cell, u, v) self.atoms: list[tuple[int, tuple[int, ...], float, float]] = [] for cell in cells: for i in range(len(frac)): self.atoms.append((i, cell, *self._uv(i, cell, np.zeros(3)))) bonds, self.bond_source = _cell_bonds(structure) # Bonds: (i, j, u1, v1, u2, v2, wraps) with continuous (unwrapped) ends; a # bond wraps around when its far end lies outside the torus' home range. self.bonds: list[tuple[int, int, float, float, float, float, bool]] = [] for cell in cells: for i, j, image in bonds: u1, v1 = self._uv(i, cell, np.zeros(3)) u2, v2 = self._uv(j, cell, image) wraps = not (-1e-9 <= u2 < 1 - 1e-9 and -1e-9 <= v2 < 1 - 1e-9) self.bonds.append((i, j, u1, v1, u2, v2, wraps)) def _uv(self, i: int, cell: tuple[int, ...], image: np.ndarray) -> tuple[float, float]: f = self.frac[i] + image out = [] for k in range(2): if k < len(self.axes): a = self.axes[k] out.append((cell[k] + float(f[a])) / self.n[k]) else: out.append(0.0) return out[0], out[1] # ── Text and arrow helpers ────────────────────────────────────────────── def _text( text: str, x: float, y: float, size: float, anchor: mathtext.Anchor = "start", fill: str = "#000", ) -> str: return mathtext.svg_text(text, x, y, size, anchor=anchor, fill=fill) def _arrowhead(x: float, y: float, dx: float, dy: float, size: float, colour: str) -> str: """A filled arrowhead with its tip at (x, y) pointing along (dx, dy).""" length = math.hypot(dx, dy) or 1.0 ux, uy = dx / length, dy / length bx, by = x - size * ux, y - size * uy px, py = -uy * 0.45 * size, ux * 0.45 * size return ( f'<polygon points="{_n(x)},{_n(y)} {_n(bx + px)},{_n(by + py)} ' f'{_n(bx - px)},{_n(by - py)}" fill="{colour}"/>' ) def _marks(x: float, y: float, dx: float, dy: float, count: int, size: float) -> str: """One or two identification arrowheads centred at (x, y) along (dx, dy).""" length = math.hypot(dx, dy) or 1.0 ux, uy = dx / length, dy / length out = [] for k in range(count): offset = (k - (count - 1) / 2) * 0.8 * size + 0.5 * size out.append(_arrowhead(x + ux * offset, y + uy * offset, ux, uy, size, _ACCENT)) return "".join(out) # ── The unrolled sheet ────────────────────────────────────────────────── def _sheet( model: _Torus, options: TopologyOptions, width: float, height: float, labels: bool ) -> list[str]: """The flat sheet, fitted into width x height (y down, origin top left).""" rows = crystal.lattice_rows(model.structure) font = options.font_size parts: list[str] = [] a1 = rows[model.axes[0]] if len(model.axes) == 2: a2 = rows[model.axes[1]] gamma = math.acos(float(np.clip(a1 @ a2 / np.linalg.norm(a1) / np.linalg.norm(a2), -1, 1))) e1 = np.asarray([float(np.linalg.norm(a1)), 0.0]) e2 = float(np.linalg.norm(a2)) * np.asarray([math.cos(gamma), math.sin(gamma)]) perp = None else: # A 1-D sheet: the second direction is the largest spread perpendicular to a. along = a1 / np.linalg.norm(a1) cart = model.frac @ rows perp_vecs = cart - np.outer(cart @ along, along) perp_vecs -= perp_vecs.mean(axis=0) if float(np.abs(perp_vecs).max(initial=0.0)) > 1e-6: _, _, vt = np.linalg.svd(perp_vecs) direction = vt[0] if float(vt[0] @ np.ones(3)) >= 0 else -vt[0] perp = perp_vecs @ direction else: perp = np.zeros(len(cart)) e1 = np.asarray([float(np.linalg.norm(a1)), 0.0]) e2 = np.asarray([0.0, max(2.0, 2 * float(np.abs(perp).max(initial=0.0)) + 2.0)]) n1, n2 = model.n corners = [np.zeros(2), n1 * e1, n1 * e1 + n2 * e2, n2 * e2] xs = [c[0] for c in corners] ys = [c[1] for c in corners] margin = 1.6 * font scale = min( (width - 2 * margin) / (max(xs) - min(xs)), (height - 2 * margin) / (max(ys) - min(ys)) ) ox = margin - min(xs) * scale + (width - 2 * margin - (max(xs) - min(xs)) * scale) / 2 oy = height - margin + min(ys) * scale - (height - 2 * margin - (max(ys) - min(ys)) * scale) / 2 def at(f1: float, f2: float) -> tuple[float, float]: p = f1 * e1 + f2 * e2 return ox + float(p[0]) * scale, oy - float(p[1]) * scale def site_xy( i: int, cell: tuple[int, ...], shift: Sequence[float] = (0.0, 0.0) ) -> tuple[float, float]: f = model.frac[i] if perp is not None: x, _ = at(cell[0] + float(f[model.axes[0]]) + shift[0], 0.0) _, y0 = at(0.0, 0.5) return x, y0 - float(perp[i]) * scale return at( cell[0] + float(f[model.axes[0]]) + shift[0], cell[1] + float(f[model.axes[1]]) + shift[1], ) outline = " ".join(f"{_n(x)},{_n(y)}" for x, y in (at(0, 0), at(n1, 0), at(n1, n2), at(0, n2))) parts.append(f'<clipPath id="vtopo-sheet"><polygon points="{outline}"/></clipPath>') parts.append(f'<polygon points="{outline}" fill="#f7f9fb" stroke="none"/>') for k in range(1, n1): (x1, y1), (x2, y2) = at(k, 0), at(k, n2) parts.append( f'<line x1="{_n(x1)}" y1="{_n(y1)}" x2="{_n(x2)}" y2="{_n(y2)}" ' f'stroke="{_GRID}" stroke-width="0.5"/>' ) for k in range(1, n2): (x1, y1), (x2, y2) = at(0, k), at(n1, k) parts.append( f'<line x1="{_n(x1)}" y1="{_n(y1)}" x2="{_n(x2)}" y2="{_n(y2)}" ' f'stroke="{_GRID}" stroke-width="0.5"/>' ) seam = _ACCENT if options.seams else _GRID seam_w = 1.0 if options.seams else 0.6 edges = [(at(0, 0), at(n1, 0), 1), (at(0, n2), at(n1, n2), 1)] if len(model.axes) == 2 else [] edges += [(at(0, 0), at(0, n2), len(model.axes)), (at(n1, 0), at(n1, n2), len(model.axes))] for (x1, y1), (x2, y2), _count in edges: parts.append( f'<line x1="{_n(x1)}" y1="{_n(y1)}" x2="{_n(x2)}" y2="{_n(y2)}" ' f'stroke="{seam}" stroke-width="{_n(seam_w)}"/>' ) if len(model.axes) == 1: for (x1, y1), (x2, y2) in ((at(0, 0), at(n1, 0)), (at(0, n2), at(n1, n2))): parts.append( f'<line x1="{_n(x1)}" y1="{_n(y1)}" x2="{_n(x2)}" y2="{_n(y2)}" ' f'stroke="{_GRID}" stroke-width="0.5" stroke-dasharray="2 2"/>' ) # Bonds, clipped to the sheet; a wrap-around bond leaves one edge and re-enters # through the identified opposite edge. if options.bonds: bonds, _ = _cell_bonds(model.structure) for cell in model.cells: for i, j, image in bonds: shift = [float(image[a]) for a in model.axes] + [0.0] * (2 - len(model.axes)) x1, y1 = site_xy(i, cell) x2, y2 = site_xy(j, cell, shift) target = [ cell[k] + shift[k] + float(model.frac[j][model.axes[k]]) for k in range(len(model.axes)) ] wraps = any(not (0 <= t < model.n[k]) for k, t in enumerate(target)) colour = _ACCENT if wraps and options.seams else _BOND dash = ' stroke-dasharray="2.5 1.5"' if wraps else "" segments = [((x1, y1), (x2, y2))] if wraps: # The same bond drawn from the far atom's image inside the sheet. home = tuple( int(math.floor(t)) % model.n[k] - int(math.floor(t)) for k, t in enumerate(target) ) back = [shift[k] + home[k] for k in range(len(model.axes))] back += [0.0] * (2 - len(back)) bx2, by2 = site_xy(j, cell, back) dx, dy = x2 - x1, y2 - y1 segments.append(((bx2 - dx, by2 - dy), (bx2, by2))) for (sx, sy), (tx, ty) in segments: parts.append( f'<line clip-path="url(#vtopo-sheet)" x1="{_n(sx)}" ' f'y1="{_n(sy)}" x2="{_n(tx)}" y2="{_n(ty)}" stroke="{colour}" ' f'stroke-width="0.9"{dash}/>' ) if options.atoms: cell_size = min( float(np.linalg.norm(e1)) * scale, float(np.linalg.norm(e2)) * scale if len(model.axes) == 2 else 1e9, ) for site_index, cell, _u, _v in model.atoms: site = model.structure.sites[site_index] x, y = site_xy(site_index, cell) r = _atom_radius(site, cell_size, options) parts.append( f'<circle cx="{_n(x)}" cy="{_n(y)}" r="{_n(r)}" ' f'fill="{_colour(site.symbol)}" stroke="#000" ' 'stroke-width="0.3"/>' ) if labels: for cell in model.cells: if len(model.axes) == 2: x, y = at(cell[0] + 0.12, cell[1] + 0.12) label = f"{cell[0]},{cell[1]}" parts.append(_text(label, x, y, 0.7 * font, "start", _GRID)) else: x, y = at(cell[0] + 0.5, 0) parts.append(_text(str(cell[0]), x, y + 1.1 * font, 0.8 * font, "middle", _GRID)) if options.seams: size = 0.55 * font for (x1, y1), (x2, y2), count in edges: parts.append(_marks((x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1, count, size)) return parts def _atom_radius(site: PeriodicSite, cell_size: float, options: TopologyOptions) -> float: base = 0.16 * cell_size * math.sqrt(_radius(site.symbol) / 0.76) return max(0.8, min(base, 0.3 * cell_size)) * options.atom_scale # ── The ring ──────────────────────────────────────────────────────────── def _ring(model: _Torus, options: TopologyOptions, size: float, labels: bool) -> list[str]: """A ring of N cells in a size x size box: cell 0 starts at the top, clockwise.""" font = options.font_size cx = cy = size / 2 radius = 0.34 * size n = model.n[0] rows = crystal.lattice_rows(model.structure) a = rows[model.axes[0]] along = a / np.linalg.norm(a) cart = model.frac @ rows perp_vecs = cart - np.outer(cart @ along, along) perp_vecs -= perp_vecs.mean(axis=0) if float(np.abs(perp_vecs).max(initial=0.0)) > 1e-6: _, _, vt = np.linalg.svd(perp_vecs) direction = vt[0] if float(vt[0] @ np.ones(3)) >= 0 else -vt[0] offsets = perp_vecs @ direction else: offsets = np.zeros(len(cart)) per_angstrom = 2 * math.pi * radius / (n * float(np.linalg.norm(a))) radial = offsets * per_angstrom limit = 0.22 * radius compressed = float(np.abs(radial).max(initial=0.0)) > limit if compressed: radial *= limit / float(np.abs(radial).max()) def point(t: float, dr: float = 0.0) -> tuple[float, float]: angle = math.pi / 2 - 2 * math.pi * t return cx + (radius + dr) * math.cos(angle), cy - (radius + dr) * math.sin(angle) parts = [ f'<circle cx="{_n(cx)}" cy="{_n(cy)}" r="{_n(radius)}" fill="none" ' f'stroke="{_GRID}" stroke-width="0.5"/>' ] tick = 0.3 * radius for k in range(n): (x1, y1), (x2, y2) = point(k / n, -tick), point(k / n, tick) seam = k == 0 and options.seams parts.append( f'<line x1="{_n(x1)}" y1="{_n(y1)}" x2="{_n(x2)}" y2="{_n(y2)}" ' f'stroke="{_ACCENT if seam else _GRID}" ' f'stroke-width="{1.0 if seam else 0.5}"/>' ) if options.bonds: for i1, i2, u1, _v1, u2, _v2, wraps in model.bonds: steps = 8 points = [] for s in range(steps + 1): f = s / steps dr = (1 - f) * float(radial[i1]) + f * float(radial[i2]) points.append(point(u1 + f * (u2 - u1), dr)) colour = _ACCENT if wraps and options.seams else _BOND dash = ' stroke-dasharray="2.5 1.5"' if wraps else "" path = " ".join(f"{_n(x)},{_n(y)}" for x, y in points) parts.append( f'<polyline points="{path}" fill="none" stroke="{colour}" ' f'stroke-width="0.9"{dash}/>' ) if options.atoms: cell_size = 2 * math.pi * radius / n for site_index, _cell, u, _v in model.atoms: site = model.structure.sites[site_index] x, y = point(u, float(radial[site_index])) r = _atom_radius(site, min(cell_size, 0.5 * radius), options) parts.append( f'<circle cx="{_n(x)}" cy="{_n(y)}" r="{_n(r)}" ' f'fill="{_colour(site.symbol)}" stroke="#000" ' 'stroke-width="0.3"/>' ) if labels: for k in range(n): x, y = point((k + 0.5) / n, tick + 0.9 * font) parts.append(_text(str(k), x, y + 0.35 * font, 0.8 * font, "middle", _GRID)) if options.seams: x, y = point(0.0) parts.append(_marks(x, y, 0, -1, 1, 0.55 * font)) sx, sy = point(0.0, tick + 0.4 * font) parts.append( _text( "$n = N$ is $n = 0$", sx + 0.3 * font, sy - 0.3 * font, 0.8 * font, "start", _ACCENT ) ) label = f"$N = {n}$" parts.append(_text(label, cx, cy - 0.2 * font, font, "middle")) length = n * float(np.linalg.norm(a)) parts.append(_text(f"$L = {length:.2f}$ Å", cx, cy + 1.1 * font, 0.85 * font, "middle")) if compressed: parts.append( _text("radial offsets compressed", cx, cy + 2.3 * font, 0.7 * font, "middle", _GRID) ) return parts # ── The torus ─────────────────────────────────────────────────────────── def _torus(model: _Torus, options: TopologyOptions, width: float) -> tuple[list[str], float]: """The projected torus fitted to ``width``; returns the parts and the height used.""" font = options.font_size elevation = math.radians(options.elevation_deg) ce, se = math.cos(elevation), math.sin(elevation) view = np.asarray([0.0, -ce, se]) light = np.asarray([-0.45, -0.55, 0.7]) light /= np.linalg.norm(light) n1, n2 = model.n big, tube = options.aspect, 1.0 margin = 1.2 * font scale = (width - 2 * margin) / (2 * (big + tube)) proj_h = 2 * (big + tube) * se + 2 * tube * ce height = proj_h * scale + 2 * margin ox, oy = width / 2, height / 2 def surface(u: float, v: float, lift: float = 0.0) -> tuple[np.ndarray, np.ndarray]: p, t = 2 * math.pi * u, 2 * math.pi * v normal = np.asarray([math.cos(t) * math.cos(p), math.cos(t) * math.sin(p), math.sin(t)]) centre = np.asarray([big * math.cos(p), big * math.sin(p), 0.0]) return centre + (tube + lift) * normal, normal def screen(x: np.ndarray) -> tuple[float, float, float]: sx = ox + float(x[0]) * scale sy = oy - (float(x[1]) * se + float(x[2]) * ce) * scale return sx, sy, float(x @ view) mp = max(2, math.ceil(72 / n1)) mt = max(2, math.ceil(40 / n2)) nu, nv = n1 * mp, n2 * mt depth = np.zeros((nu, nv)) items: list[tuple[float, int, str]] = [] serial = itertools.count() for i, j in itertools.product(range(nu), range(nv)): corners = [ surface((i + di) / nu, (j + dj) / nv)[0] for di, dj in ((0, 0), (1, 0), (1, 1), (0, 1)) ] centre, normal = surface((i + 0.5) / nu, (j + 0.5) / nv) depth[i, j] = float(centre @ view) if float(normal @ view) <= 0: continue shade = 0.62 + 0.38 * max(0.0, float(normal @ light)) fill = "#{:02x}{:02x}{:02x}".format(*(min(255, round(c * shade + 18)) for c in _SURFACE)) points = " ".join(f"{_n(screen(c)[0])},{_n(screen(c)[1])}" for c in corners) items.append( ( depth[i, j], next(serial), f'<polygon points="{points}" fill="{fill}" stroke="{fill}" stroke-width="0.35"/>', ) ) def front(u: float, v: float) -> bool: return float(surface(u, v)[1] @ view) > 0 def local_depth(u: float, v: float, reach: int = 1) -> float: i, j = math.floor((u % 1) * nu), math.floor((v % 1) * nv) return max( float(depth[(i + di) % nu, (j + dj) % nv]) for di in range(-reach, reach + 1) for dj in range(-reach, reach + 1) ) def segment( u1: float, v1: float, u2: float, v2: float, colour: str, stroke: float, dash: str = "" ) -> None: um, vm = (u1 + u2) / 2, (v1 + v2) / 2 if not front(um, vm): return a, b = screen(surface(u1, v1, 0.01)[0]), screen(surface(u2, v2, 0.01)[0]) items.append( ( local_depth(um, vm) + 1e-4, next(serial), f'<line x1="{_n(a[0])}" y1="{_n(a[1])}" x2="{_n(b[0])}" y2="{_n(b[1])}" ' f'stroke="{colour}" stroke-width="{_n(stroke)}" stroke-linecap="round"' f"{dash}/>", ) ) for k in range(n1): seam = k == 0 and options.seams for j in range(nv): segment( k / n1, j / nv, k / n1, (j + 1) / nv, _ACCENT if seam else _GRID, 1.0 if seam else 0.5, ) for k in range(n2): seam = k == 0 and options.seams for i in range(nu): segment( i / nu, k / n2, (i + 1) / nu, k / n2, _ACCENT if seam else _GRID, 1.0 if seam else 0.5, ) if options.bonds: for _i, _j, u1, v1, u2, v2, wraps in model.bonds: colour = _ACCENT if wraps and options.seams else _BOND steps = 6 for s in range(steps): f1, f2 = s / steps, (s + 1) / steps segment( u1 + f1 * (u2 - u1), v1 + f1 * (v2 - v1), u1 + f2 * (u2 - u1), v1 + f2 * (v2 - v1), colour, 0.9, ' stroke-dasharray="2.5 1.5"' if wraps else "", ) if options.atoms: cell_size = 0.45 * scale * min(2 * math.pi * (big - tube) / n1, 2 * math.pi * tube / n2) cell_size /= math.sqrt(max(1, len(model.frac)) / 2) quad = scale * 2 * math.pi * tube / nv for site_index, _cell, u, v in model.atoms: if not front(u, v): continue site = model.structure.sites[site_index] x, y, _ = screen(surface(u, v, 0.02)[0]) r = _atom_radius(site, cell_size, options) reach = 1 + math.ceil(r / quad) items.append( ( local_depth(u, v, reach) + 2e-4, next(serial), f'<circle cx="{_n(x)}" cy="{_n(y)}" r="{_n(r)}" ' f'fill="{_colour(site.symbol)}" stroke="#000" ' 'stroke-width="0.3"/>', ) ) if options.seams: size = 0.55 * font # Two arrows on the u = 0 seam (along v) at the top of the tube, one on the # v = 0 seam (along u) on the near side: the sheet's edge marks. for u, v, du, dv, count in ((0.0, 0.25, 0.0, 0.02, 2), (0.75, 0.0, 0.02, 0.0, 1)): a = screen(surface(u, v, 0.02)[0]) b = screen(surface(u + du, v + dv, 0.02)[0]) items.append( ( local_depth(u, v) + 3e-4, next(serial), _marks(a[0], a[1], b[0] - a[0], b[1] - a[1], count, size), ) ) items.sort(key=lambda item: (item[0], item[1])) return [svg for _d, _k, svg in items], height # ── The figure ────────────────────────────────────────────────────────── def _wrap(lines: Sequence[str], width: float, size: float) -> list[str]: """Break caption lines at spaces so each fits ``width`` in the publication font.""" from vibesketcher.render.fonts import advance out: list[str] = [] for line in lines: current = "" for word in line.split(" "): trial = f"{current} {word}" if current else word if current and advance(trial) * size > width: out.append(current) current = word else: current = trial out.append(current) return out def _axis_name(axis: int) -> str: return "abc"[axis]
[docs] def topology_svg( structure: PeriodicStructure, repeats: Sequence[int], options: TopologyOptions | None = None, *, provenance: Sequence[str] = (), ) -> bytes: """The schematic as standalone SVG (UTF-8), sized in points.""" options = options or TopologyOptions() reps, axes = _resolve(structure, repeats, options) model = _Torus(structure, reps, axes) font = options.font_size cells = math.prod(model.n) labels = options.cell_labels if options.cell_labels is not None else cells <= 36 width = options.width gap = 1.5 * font shape_w = width * (0.56 if options.unrolled else 1.0) sheet_w = width - shape_w - gap if options.unrolled else 0.0 if len(axes) == 1: shape_h = shape_w shape = _ring(model, options, shape_w, labels) else: shape, shape_h = _torus(model, options, shape_w) body_h = shape_h if options.unrolled: sheet = _sheet(model, options, sheet_w, body_h, labels) n_text = " \\times ".join(str(n) for n in model.n[: len(axes)]) kind = "ring" if len(axes) == 1 else "torus" title = options.title if title is None: count = "N_c" if len(axes) == 2 else "N" title = f"{structure.id}: {kind} of ${n_text}$ cells (${count} = {cells}$)" mathtext.validate(title) top = 2.0 * font sub = 1.6 * font lines: list[str] = [] if options.caption: named = " x ".join(f"{model.n[k]} along {_axis_name(a)}" for k, a in enumerate(axes)) lines.append( f"Cyclic cluster: {named}; repeats {tuple(reps)}; " f"{len(structure.sites)} sites per cell, {len(model.atoms)} drawn." ) hidden = [a for a in range(3) if a not in axes and reps[a] > 1] if hidden: lines.append( "Not drawn: " + ", ".join(f"{reps[a]} images along {_axis_name(a)}" for a in hidden) + " (they coincide here)." ) lines.append( f"Seams (accent) are the identified boundaries, cell N = cell 0; " f"wrap-around bonds dashed in the accent colour; {model.bond_source}." ) lines.append( ("Sheet to scale; " if options.unrolled else "") + f"{kind} schematic, not to scale; drawn from the unchanged model." ) lines.extend(provenance) lines = _wrap(lines, width - 0.4 * font, 0.78 * font) foot = (1.25 * 0.78 * font * len(lines) + 0.6 * font) if lines else 0.0 height = top + sub + body_h + foot parts = [_text(title, 0.0 + font * 0.2, 1.3 * font, 1.1 * font)] y0 = top + sub if options.unrolled: heading = "unrolled: opposite edges identified" # Centred over the sheet, but never past the left edge of a narrow figure. half = mathtext.measure(heading, 0.85 * font)[0] / 2 parts.append( _text( heading, max(sheet_w / 2, half + 0.2 * font), top + 0.9 * font, 0.85 * font, "middle", _GRID, ) ) parts.append(f'<g transform="translate(0 {_n(y0)})">{"".join(sheet)}</g>') sx = sheet_w + gap if options.unrolled else 0.0 parts.append( _text(f"cyclic: {kind}", sx + shape_w / 2, top + 0.9 * font, 0.85 * font, "middle", _GRID) ) parts.append(f'<g transform="translate({_n(sx)} {_n(y0)})">{"".join(shape)}</g>') for k, line in enumerate(lines): parts.append( f'<text x="{_n(0.2 * font)}" y="{_n(y0 + body_h + 1.25 * 0.78 * font * (k + 1))}" ' f'font-size="{_n(0.78 * font)}" fill="{_GRID}">{html.escape(line)}</text>' ) 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"<title>{html.escape(mathtext.plain_text(title))}</title>" f'<rect width="100%" height="100%" fill="#fff"/>{"".join(parts)}</svg>' ) return svg.encode("utf-8")
[docs] def structure_from_record(record: dict[str, Any]) -> tuple[PeriodicStructure, tuple[int, int, int]]: """The input cell and torus repeats stored in an AICCM convention record. The record is the ``vibesketcher.aiccm-record/1`` file written beside every AICCM input (:func:`vibesketcher.inputs.aiccm.torus_record`); its Hamiltonian identity carries the cell and its sites. """ from vibesketcher.inputs.aiccm import RECORD_SCHEMA if not isinstance(record, dict) or record.get("schema") != RECORD_SCHEMA: raise TopologyRefused(f"not an AICCM convention record ({RECORD_SCHEMA})") try: cell = record["hamiltonian_identity"]["cell"] repeats = tuple(int(n) for n in record["torus"]["repeats"]) images = (record.get("site_mapping") or {}).get("images") or {} names = list(images) if len(images) == len(cell["sites"]) else [] sites = [ { "id": names[k] if names else f"s{k + 1}", "symbol": row[0], "fractional": [float(x) for x in row[1:4]], } for k, row in enumerate(cell["sites"]) ] structure = PeriodicStructure.model_validate( { "id": "torus", "lattice_angstrom": cell["lattice_angstrom"], "pbc": cell["pbc"], "sites": sites, } ) except (KeyError, TypeError, ValueError, IndexError) as error: raise TopologyRefused(f"the AICCM record has no usable cell: {error}") from None if len(repeats) != 3: raise TopologyRefused("the AICCM record's torus repeats are not three integers") return structure, (repeats[0], repeats[1], repeats[2])
def _record_provenance(record: dict[str, Any]) -> list[str]: digest = str(record.get("hamiltonian_digest") or "")[:12] return [ f"AICCM record: variant {record.get('variant')}, {record.get('scf_reference')}, " f"Hamiltonian digest {digest}; {record.get('status', '')}." ] Format = Literal["svg", "pdf", "png"] def _convert(svg: bytes, fmt: str, dpi: int) -> bytes: if fmt == "svg": return svg if fmt not in ("pdf", "png"): raise TopologyRefused(f"cannot write {fmt!r}; formats: svg, pdf, png") from vibesketcher.render.publication import convert return bytes(convert(svg, fmt, dpi=dpi))
[docs] def topology_figure( structure: PeriodicStructure, repeats: Sequence[int], options: TopologyOptions | None = None, fmt: str = "svg", *, dpi: int = 300, ) -> bytes: """SVG, or PDF/PNG through the publication extra, of a structure on its torus.""" return _convert(topology_svg(structure, repeats, options), fmt, dpi)
[docs] def topology_figure_from_record( record: dict[str, Any], options: TopologyOptions | None = None, fmt: str = "svg", *, dpi: int = 300, ) -> bytes: """The schematic of the torus an AICCM convention record describes.""" structure, repeats = structure_from_record(record) svg = topology_svg(structure, repeats, options, provenance=_record_provenance(record)) return _convert(svg, fmt, dpi)