vibe-sketcherDocumentation

Source code for vibesketcher.chem.porous_carbon

"""Net-derived porous and negative-curvature carbon models: a plan and one builder (#204).

A *model plan* names everything a net-derived carbon model depends on: the
generating net, the surface that separates its two labyrinths, the cell, the
sheet construction and its parameters, the termination and the seed of any
stochastic step. :func:`model_catalog` lists the constructions; one is built
here, the others are planned and refused by name.

The built construction, ``truncated_mucube``, starts from the primitive cubic
net ``pcu`` (the net of :mod:`vibesketcher.chem.reticular`, written out in
code; no RCSR data). The unit cubes of a period-2 cubic grid are split into
the cubes on the net (a node cube on each net vertex and an arm cube on each
net edge, at most one odd index) and the rest. The squares between the two
sets form the regular skew polyhedron {4,6|4} (the "mucube"; H. S. M.
Coxeter, Proc. London Math. Soc. s2-43, 33 (1937),
doi:10.1112/plms/s2-43.1.33): every grid point is a vertex where six squares
meet, and the polyhedron is a discrete form of Schwarz's P surface around
the net. Truncating it (each six-valent vertex cut to a hexagon, each square
becoming an octagon) gives a 3-connected graph whose every vertex lies on one
6-ring and two 8-rings, the vertex symbol 6.8.8 (vertex symbols: M. O'Keeffe
and S. T. Hyde, Zeolites 19, 370 (1997), doi:10.1016/S0144-2449(97)00133-4).
Carbon schwarzites of this kind, sp2-like sheets of negative Gaussian
curvature on periodic minimal surfaces, were proposed by A. L. Mackay and
H. Terrones, Nature 352, 762 (1991), doi:10.1038/352762a0, and
T. Lenosky, X. Gonze, M. Teter and V. Elser, Nature 355, 333 (1992),
doi:10.1038/355333a0. This builder does not claim to reproduce the
coordinates of any published structure.

Atom placement is explicit and deterministic. The carbon for vertex ``v``
and edge direction ``e`` sits at ``a v + rho u``, where ``u`` is ``e``
projected onto the tangent plane of the P nodal surface
``cos X + cos Y + cos Z = 0`` at ``v`` (H. G. von Schnering and R. Nesper,
Z. Phys. B 83, 407 (1991), doi:10.1007/BF01313411; with ``X = pi (x - 1/2)``
every grid point lies on it and its normal there is
``((-1)^x, (-1)^y, (-1)^z)``). The six projections are 60 degrees apart, so
each hexagon is planar and regular with bond ``rho`` (``bond_length``); the
grid edge ``a`` is chosen so the bond along each mucube edge is
``edge_bond_length``: ``a = edge + 4 rho / sqrt(6)``.

Topology is computed, not assumed. The construction faces (one hexagon per
mucube vertex, one octagon per square) are checked to be closed cycles of the
bond graph with every bond on exactly two faces and a consistent
orientation; then ``chi = V - E + F`` per cell and ``genus = 1 - chi / 2``.
For a 3-connected graph ``3V = 2E`` turns Euler's relation into
``sum over faces of (6 - n) = 6 chi``, the curvature count used for
schwarzites (Mackay and Terrones 1991; Lenosky et al. 1992): with only
hexagons and octagons, ``12 (g - 1) / 2`` octagons per cell. The same genus
is the cycle rank ``E - V + 1`` of the generating net's quotient graph,
since the sheet bounds a tubular neighbourhood of the net. Ring statistics
come independently from the bond graph: the smallest ring at each bond angle
(O'Keeffe and Hyde 1997), searched breadth-first in the periodic lift.

A Stone-Wales defect (A. J. Stone and D. J. Wales, Chem. Phys. Lett. 128,
501 (1986), doi:10.1016/0009-2614(86)80661-3) turns one bond by 90 degrees
about its midpoint, in the sheet's local tangent plane. Atom ``i`` of bond
``i-j`` gives up neighbour ``a`` and takes ``d``; ``j`` gives up ``d`` and
takes ``a``. The two rings that shared the bond lose an atom, and the two
rings at its ends gain one. Graphene's 6,6,6,6 becomes the 5-7-7-5 defect.
On this sheet a mucube-edge bond lies between two octagons, so its rings go
from 8,8,6,6 to 7,7,7,7. A hexagon bond lies between a hexagon and an
octagon, so its rings go from 6,8,8,8 to 5,7,9,9. The rotation is applied to
the construction faces as well as to the bonds. The faces are then checked
again as a closed, orientable surface: the Euler characteristic and genus
must be unchanged, because the transformation preserves V, E and F. The
ring census is recomputed independently from the bond graph. The two atoms
move to the midpoint plus or minus half the bond, along the in-plane
direction that takes each one towards its new neighbours. Nothing else
moves, and nothing is relaxed. The bond-misfit and contact checks apply to
the result unchanged. The bonds to rotate are chosen with
``numpy.random.default_rng([seed, 1])`` among the bonds of the requested kind.
No atom or face is shared between two rotations.

Nothing is relaxed, capped or hybridised: no hydrogen is added, a carbon
with fewer than three neighbours is reported, bond orders are a connectivity
placeholder (1, not a Kekule structure) and sp2 character is not assumed.
The result is a geometric model, unrelaxed, not a stable material; a
relaxation or ML validation is a separately admitted periodic job and not
proof of synthesis or stability. The generating net and the mucube are kept
in the construction record; no site sits on a net vertex, so net edges are
never written as chemical bonds.

None of the papers cited here are in the project's literature library yet.
"""

from __future__ import annotations

import itertools
import math
from collections import Counter, deque
from typing import Annotated, Any, Literal

import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field

from vibesketcher.chem.periodic_geometry import (
    BuildRefused,
    _provenance,
    _structure,
    neighbour_pairs,
)
from vibesketcher.document.model import PeriodicStructure

__all__ = [
    "CONSTRUCTIONS",
    "STATUS",
    "PorousCarbonRecipe",
    "PorousCarbonRefused",
    "analyse_carbon_graph",
    "build_porous_carbon",
    "model_catalog",
    "porosity_handoff_plan",
    "preview",
    "structure_report",
]

_Points = NDArray[np.float64]
Image = tuple[int, int, int]

#: Version of this construction, recorded in provenance.
CONSTRUCTION_VERSION = 1
#: Recorded on every built structure and in every report.
STATUS = "geometric model, unrelaxed, not a stable material"
#: Repeats of the generating cell along one axis.
MAX_REPEAT = 3
#: Vacancies one build may place.
MAX_VACANCIES = 32
#: Stone-Wales rotations one build may place.
MAX_STONE_WALES = 16
#: The largest smallest-ring the ring search looks for.
MAX_RING = 16
#: Carbon atoms in one generating (period-2) cell of the truncated mucube.
ATOMS_PER_CELL = 48
#: Default perception factor for the geometry cross-check, d <= f (r_a + r_b).
PERCEPTION_SCALE = 1.15
_CARBON_RADIUS = 0.76  # Cordero et al., Dalton Trans. 2008, 2832 (sp3 C; a perception scale)
_SQ6 = math.sqrt(6.0)

REFERENCES = [
    "H. S. M. Coxeter, Proc. London Math. Soc. s2-43, 33 (1937), doi:10.1112/plms/s2-43.1.33 "
    "(regular skew polyhedron {4,6|4})",
    "A. L. Mackay, H. Terrones, Nature 352, 762 (1991), doi:10.1038/352762a0 (schwarzites)",
    "T. Lenosky, X. Gonze, M. Teter, V. Elser, Nature 355, 333 (1992), doi:10.1038/355333a0 "
    "(negative-curvature sp2 carbon; ring counts from Euler's relation)",
    "H. G. von Schnering, R. Nesper, Z. Phys. B 83, 407 (1991), doi:10.1007/BF01313411 "
    "(P nodal surface)",
    "M. O'Keeffe, S. T. Hyde, Zeolites 19, 370 (1997), doi:10.1016/S0144-2449(97)00133-4 "
    "(vertex symbols)",
    "A. J. Stone, D. J. Wales, Chem. Phys. Lett. 128, 501 (1986), "
    "doi:10.1016/0009-2614(86)80661-3 (Stone-Wales bond rotation)",
]

#: Constructions in the model plan; only ``built`` ones run.
CONSTRUCTIONS: dict[str, dict[str, Any]] = {
    "truncated_mucube": {
        "state": "built",
        "net": "pcu",
        "surface": "Schwarz P (discrete: regular skew polyhedron {4,6|4}, the mucube)",
        "sheet": "truncation of the mucube: a hexagon per six-valent vertex, an octagon per "
        "square; vertex symbol 6.8.8",
        "cell": "the period-2 cubic grid cell of pcu, cubic, edge 2a",
        "parameters": [
            "bond_length",
            "edge_bond_length",
            "repeat",
            "vacancies",
            "stone_wales",
            "stone_wales_bond",
            "seed",
        ],
        "stochastic": "vacancy placement (numpy default_rng(seed)) and the Stone-Wales "
        "bonds (numpy default_rng([seed, 1]))",
        "defects": {
            "vacancies": "seeded removal; never capped",
            "stone_wales": "90-degree bond rotation (Stone and Wales 1986): an edge bond turns "
            "rings 8,8,6,6 into 7,7,7,7, a ring bond 6,8,8,8 into 5,7,9,9; unrelaxed",
        },
        "termination": "none: no hydrogen is added; undercoordinated carbons are reported",
    },
    "d_surface_on_dia": {
        "state": "planned",
        "net": "dia",
        "surface": "Schwarz D (discrete: regular skew polyhedron {6,6|3})",
        "reason": "the truncation of {6,6|3} gives 12-rings; a 6/7/8-ring D-type sheet needs "
        "a reviewed decoration",
    },
    "tpms_remeshing": {
        "state": "planned",
        "surface": "a triply periodic minimal surface (nodal approximation)",
        "reason": "triangulation/remeshing to a 3-connected carbon graph needs a cited, "
        "bounded remeshing algorithm",
    },
    "zeolite_templated": {
        "state": "planned",
        "net": "a zeolite framework",
        "reason": "needs licensed framework coordinates (IZA database terms not reviewed) and "
        "a cited pore-wall carbon construction",
    },
}

#: Nets the model plan knows, and which construction (if any) builds them.
_NET_ROUTES: dict[str, str] = {"pcu": "truncated_mucube", "dia": "d_surface_on_dia"}


[docs] class PorousCarbonRefused(BuildRefused): """A model the builder will not produce; ``code`` is stable.""" def __init__(self, code: str, message: str) -> None: super().__init__(f"[{code}] {message}") self.code = code self.detail = message
_ID = Annotated[str, Field(pattern=r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")] _Repeat = Annotated[int, Field(ge=1, le=MAX_REPEAT)]
[docs] class PorousCarbonRecipe(BaseModel): """A net-derived carbon model: net, construction, parameters, termination and seed.""" model_config = ConfigDict(extra="forbid") kind: Literal["porous_carbon"] = "porous_carbon" identifier: _ID net: str = Field(default="pcu", min_length=1, max_length=32) construction: str = Field(default="truncated_mucube", min_length=1, max_length=64) #: Hexagon (ring) bond, angstrom; also the hexagon circumradius. bond_length: float = Field(default=1.42, ge=1.2, le=1.7, allow_inf_nan=False) #: Bond along each mucube edge (joins two hexagons); default ``bond_length``. edge_bond_length: float | None = Field(default=None, ge=1.2, le=1.7, allow_inf_nan=False) #: Largest allowed difference between any bond and its target, angstrom. bond_tolerance: float = Field(default=0.15, gt=0, le=0.5, allow_inf_nan=False) repeat: tuple[_Repeat, _Repeat, _Repeat] = (1, 1, 1) vacancies: int = Field(default=0, ge=0, le=MAX_VACANCIES) #: Stone-Wales bond rotations, placed with ``seed``. stone_wales: int = Field(default=0, ge=0, le=MAX_STONE_WALES) #: Which bonds rotate: ``edge`` (between two octagons) or ``ring`` (hexagon-octagon). stone_wales_bond: Literal["edge", "ring"] = "edge" seed: int = Field(default=0, ge=0, lt=2**63) #: Closest allowed contact between carbons that are not bonded, angstrom. min_distance: float = Field(default=1.8, gt=0, le=3, allow_inf_nan=False) max_ring_size: int = Field(default=12, ge=6, le=MAX_RING) #: Only ``none``: the builder never adds hydrogen or other caps. termination: str = Field(default="none", min_length=1, max_length=32)
# --- the mucube -------------------------------------------------------------------------- def _solid(cube: tuple[int, ...]) -> bool: """A cube on the net: a node cube (all indices even) or an arm cube (one odd).""" return sum(c % 2 for c in cube) <= 1 _Direction = tuple[int, int] # (axis, sign) def _mucube(shape: tuple[int, int, int]) -> list[list[tuple[int, int, int]]]: """The squares between net and non-net cubes, corners in cyclic order (unwrapped).""" faces: list[list[tuple[int, int, int]]] = [] for cube in itertools.product(*(range(n) for n in shape)): if not _solid(cube): continue for axis, sign in itertools.product(range(3), (1, -1)): other = list(cube) other[axis] += sign if _solid(tuple(other)): continue a, b = [k for k in range(3) if k != axis] base = list(cube) base[axis] += 1 if sign > 0 else 0 corners = [] for da, db in ((0, 0), (1, 0), (1, 1), (0, 1)): point = list(base) point[a] += da point[b] += db corners.append((point[0], point[1], point[2])) faces.append(corners) return faces def _wrap(point: tuple[int, ...], shape: tuple[int, int, int]) -> tuple[int, int, int]: return (point[0] % shape[0], point[1] % shape[1], point[2] % shape[2]) def _direction(start: tuple[int, ...], end: tuple[int, ...]) -> _Direction: step = [e - s for s, e in zip(start, end, strict=True)] axis = next(k for k in range(3) if step[k]) return (axis, 1 if step[axis] > 0 else -1) def _direction_name(direction: _Direction) -> str: return ("+" if direction[1] > 0 else "-") + "xyz"[direction[0]] def _tangent(vertex: tuple[int, int, int], direction: _Direction) -> _Points: """``e`` projected onto the P nodal surface's tangent plane at ``vertex``, normalised.""" normal = np.array([(-1.0) ** c for c in vertex]) / math.sqrt(3.0) e = np.zeros(3) e[direction[0]] = float(direction[1]) u = e - float(e @ normal) * normal out: _Points = u / np.linalg.norm(u) return out # --- recipe checks ----------------------------------------------------------------------- def _refuse(recipe: PorousCarbonRecipe) -> None: if recipe.termination != "none": raise PorousCarbonRefused( "porous_carbon.termination_unsupported", f"termination {recipe.termination!r} is not built; the model is never capped " "(termination 'none'), undercoordinated carbons are reported instead", ) if recipe.construction not in CONSTRUCTIONS: raise PorousCarbonRefused( "porous_carbon.construction_unknown", f"construction {recipe.construction!r} is not in the model plan " f"({', '.join(CONSTRUCTIONS)})", ) entry = CONSTRUCTIONS[recipe.construction] if entry["state"] != "built": raise PorousCarbonRefused( "porous_carbon.construction_planned", f"construction {recipe.construction!r} is planned, not built: {entry['reason']}", ) from vibesketcher.chem.reticular import NETS if recipe.net not in NETS: raise PorousCarbonRefused( "porous_carbon.net_unknown", f"net {recipe.net!r} is not in the catalogue ({', '.join(NETS)}); RCSR data is " "not bundled", ) if NETS[recipe.net].dimension != 3: raise PorousCarbonRefused( "porous_carbon.net_not_3d", f"net {recipe.net!r} is a layer; a negative-curvature sheet needs a 3-periodic net", ) route = _NET_ROUTES.get(recipe.net) if route != recipe.construction: planned = f" (planned: {route})" if route else "" raise PorousCarbonRefused( "porous_carbon.net_unsupported", f"construction {recipe.construction!r} is defined on {entry['net']}, not on " f"{recipe.net!r}{planned}", ) atoms = ATOMS_PER_CELL * math.prod(recipe.repeat) if recipe.vacancies >= atoms // 4: raise PorousCarbonRefused( "porous_carbon.too_many_vacancies", f"{recipe.vacancies} vacancies in {atoms} carbons; at most {atoms // 4 - 1} keep " "the sheet a perturbed pristine model", ) edge = recipe.edge_bond_length or recipe.bond_length if abs(edge - recipe.bond_length) > recipe.bond_tolerance: raise PorousCarbonRefused( "porous_carbon.bond_misfit", f"edge bond {edge:g} and ring bond {recipe.bond_length:g} angstrom differ by more " f"than bond_tolerance {recipe.bond_tolerance:g}", ) # --- build ------------------------------------------------------------------------------- def _round(values: Any, digits: int = 6) -> Any: return np.round(np.asarray(values, dtype=float), digits).tolist()
[docs] def build_porous_carbon(recipe: PorousCarbonRecipe) -> PeriodicStructure: """Build the model; refuse (``PorousCarbonRefused``) what the plan does not support.""" _refuse(recipe) shape = (2 * recipe.repeat[0], 2 * recipe.repeat[1], 2 * recipe.repeat[2]) rho = recipe.bond_length edge_bond = recipe.edge_bond_length or recipe.bond_length a = edge_bond + 4 * rho / _SQ6 faces = _mucube(shape) # Carbons: one per (vertex, incident edge direction), in sorted order. incident: dict[tuple[int, int, int], set[_Direction]] = {} links: dict[tuple[int, int, int], list[tuple[_Direction, _Direction]]] = {} edge_faces: Counter[tuple[tuple[int, int, int], int]] = Counter() for corners in faces: for k in range(4): here, prev, nxt = corners[k], corners[k - 1], corners[(k + 1) % 4] v = _wrap(here, shape) d_prev, d_next = _direction(here, prev), _direction(here, nxt) incident.setdefault(v, set()).update((d_prev, d_next)) links.setdefault(v, []).append((d_prev, d_next)) low = min(here, nxt, key=lambda p: p[_direction(here, nxt)[0]]) edge_faces[(_wrap(low, shape), _direction(here, nxt)[0])] += 1 if any(n != 2 for n in edge_faces.values()): raise PorousCarbonRefused("porous_carbon.non_manifold", "a mucube edge is not on two faces") atoms: list[tuple[tuple[int, int, int], _Direction]] = sorted( (v, d) for v, ds in incident.items() for d in ds ) index = {key: k for k, key in enumerate(atoms)} cartesian = np.array([a * np.array(v, dtype=float) + rho * _tangent(v, d) for v, d in atoms]) bonds: list[tuple[int, int, str]] = [] hexagons: list[list[int]] = [] for v in sorted(links): pairs = links[v] degree = Counter(d for pair in pairs for d in pair) if len(pairs) != len(incident[v]) or any(n != 2 for n in degree.values()): raise PorousCarbonRefused( "porous_carbon.non_manifold", f"the mucube vertex {v} has no single link cycle" ) neighbours: dict[_Direction, list[_Direction]] = {} for d1, d2 in pairs: neighbours.setdefault(d1, []).append(d2) neighbours.setdefault(d2, []).append(d1) bonds.append((index[(v, d1)], index[(v, d2)], "ring")) start = min(neighbours) cycle, previous = [start], None while True: options = [d for d in neighbours[cycle[-1]] if d != previous] previous = cycle[-1] if options[0] == start: break cycle.append(options[0]) if len(cycle) != len(incident[v]): raise PorousCarbonRefused( "porous_carbon.non_manifold", f"the mucube vertex {v} link splits into cycles" ) hexagons.append([index[(v, d)] for d in cycle]) edges_seen: set[tuple[int, int]] = set() for v, d in atoms: if d[1] > 0: w = list(v) w[d[0]] += 1 far = (_wrap(tuple(w), shape), (d[0], -1)) pair = (index[(v, d)], index[far]) if pair not in edges_seen: edges_seen.add(pair) bonds.append((pair[0], pair[1], "edge")) octagons: list[list[int]] = [] for corners in faces: ring: list[int] = [] for k in range(4): here, prev, nxt = corners[k], corners[k - 1], corners[(k + 1) % 4] v = _wrap(here, shape) ring += [index[(v, _direction(here, prev))], index[(v, _direction(here, nxt))]] octagons.append(ring) construction_faces = [*hexagons, *octagons] pristine = _surface_topology(len(atoms), bonds, construction_faces) net_cells = math.prod(recipe.repeat) from vibesketcher.chem.reticular import NETS net = NETS[recipe.net] cycle_rank = net_cells * (len(net.edges) - len(net.vertices)) + 1 if pristine["genus"] != cycle_rank: raise PorousCarbonRefused( "porous_carbon.genus_mismatch", f"the sheet has genus {pristine['genus']} but the net's quotient graph has cycle " f"rank {cycle_rank}", ) pristine["net_cycle_rank"] = cycle_rank # Stone-Wales rotations act on the pristine sheet, before any vacancy. box = np.array([a * n for n in shape], dtype=float) cartesian, bonds, construction_faces, rotations = _stone_wales( recipe, cartesian, box, bonds, construction_faces ) rotated_topology = None if rotations: rotated_topology = _surface_topology(len(atoms), bonds, construction_faces) if rotated_topology["genus"] != pristine["genus"] or not rotated_topology["orientable"]: raise PorousCarbonRefused( "porous_carbon.genus_mismatch", "the Stone-Wales rotations changed the sheet's topology", ) # Vacancies: a seeded choice over the construction order; never capped. removed: list[int] = [] if recipe.vacancies: rng = np.random.default_rng(recipe.seed) removed = sorted(int(k) for k in rng.choice(len(atoms), recipe.vacancies, replace=False)) keep = [k for k in range(len(atoms)) if k not in set(removed)] renumber = {old: new for new, old in enumerate(keep)} kept_bonds = [ (renumber[i], renumber[j], kind) for i, j, kind in bonds if i in renumber and j in renumber ] lattice = np.diag([a * n for n in shape]).astype(float) structure = _structure( recipe.identifier, lattice, (True, True, True), ["C"] * len(keep), cartesian[keep], [(i, j, 1.0) for i, j, _ in kept_bonds], cell_setting="unspecified", provenance={}, ) rules = { "ring": "porous_carbon hexagon bond; order 1 is a connectivity placeholder", "edge": "porous_carbon mucube-edge bond; order 1 is a connectivity placeholder", "stone_wales": "porous_carbon bond formed by a Stone-Wales rotation; order 1 is a " "connectivity placeholder", } typed_bonds = [ bond.model_copy(update={"rule": rules[kind], "order_source": "builder"}) for bond, (_, _, kind) in zip(structure.bonds, kept_bonds, strict=True) ] structure = structure.model_copy(update={"bonds": typed_bonds}) from vibesketcher.document.periodic_graph import geometry_fingerprint ids = [s.id for s in structure.sites] targets = {"ring": rho, "edge": edge_bond, "stone_wales": rho} report = analyse_carbon_graph( structure, targets=[targets[kind] for _, _, kind in kept_bonds], kinds=[kind for _, _, kind in kept_bonds], max_ring_size=recipe.max_ring_size, ) _check_geometry(report, recipe) contacts = _contacts(structure, recipe) pristine_symbol = "6.8.8" roles = { ids[renumber[k]]: {"vertex": list(atoms[k][0]), "direction": _direction_name(atoms[k][1])} for k in keep } defect_sites = sorted( site for site, entry in report["sites"].items() if entry["coordination"] != 3 or entry["vertex_symbol"] != pristine_symbol ) broken = [ {"ring": len(face), "construction_atoms": [k + 1 for k in face]} for face in construction_faces if any(k in set(removed) for k in face) ] defect_map = { "pristine_vertex_symbol": pristine_symbol, "pristine_sites": len(keep) - len(defect_sites), "defect_sites": defect_sites, "vacancies": [ { "construction_atom": k + 1, "vertex": list(atoms[k][0]), "direction": _direction_name(atoms[k][1]), } for k in removed ], "broken_construction_rings": broken, "stone_wales": rotations, "seed": recipe.seed if recipe.vacancies or rotations else None, "termination": "none: no hydrogen added; undercoordinated carbons are flagged, not capped", } model = { "version": CONSTRUCTION_VERSION, "status": STATUS, "construction": recipe.construction, "plan": CONSTRUCTIONS[recipe.construction], "generating_net": { **net.describe(), "cell_in_grid_units": [2, 2, 2], "vertex_cube_centres_fractional": [[0.25, 0.25, 0.25]], "note": "net vertices sit at node-cube centres, inside one labyrinth; no carbon " "sits on them, so net edges are recorded here and never written as bonds", }, "surface": { "name": "Schwarz P", "discrete": "regular skew polyhedron {4,6|4} (mucube)", "nodal_approximation": "cos(pi (x - 1/2)) + cos(pi (y - 1/2)) + cos(pi (z - 1/2)) " "= 0 in grid units", "grid_shape": list(shape), "vertices": len(incident), "edges": len(edge_faces), "squares": len(faces), }, "parameters": { "bond_length_angstrom": rho, "edge_bond_length_angstrom": edge_bond, "grid_edge_angstrom": round(a, 6), "cell_edge_angstrom": _round([a * n for n in shape]), "repeat": list(recipe.repeat), "vacancies": recipe.vacancies, "stone_wales": recipe.stone_wales, "stone_wales_bond": recipe.stone_wales_bond, "seed": recipe.seed, "placement": "a v + rho u, u the edge direction projected on the nodal surface's " "tangent plane at v", }, "cell": { "setting": "cubic grid cell of the generating net (side-preserving); the " "unoriented sheet also has a body-centring translation that swaps the labyrinths", "net_cells": net_cells, }, "pristine_topology": pristine, "defect_topology": rotated_topology, "graph": {k: v for k, v in report.items() if k != "sites"}, "contacts": contacts, "built_graph": { "sites": len(ids), "chemical_bonds": len(typed_bonds), "geometry_fingerprint": geometry_fingerprint(structure), }, "defect_map": defect_map, "site_roles": roles, "hybridisation": "not assigned: coordination and bond angles are reported; sp2 is " "not assumed", "references": REFERENCES, } provenance = _provenance( "porous_carbon", recipe, net=net.name, model=model, status=STATUS, warnings=[d["message"] for d in report["diagnostics"] if d["severity"] == "warning"], ) return structure.model_copy(update={"provenance": provenance})
def _stone_wales( recipe: PorousCarbonRecipe, cartesian: _Points, box: _Points, bonds: list[tuple[int, int, str]], faces: list[list[int]], ) -> tuple[_Points, list[tuple[int, int, str]], list[list[int]], list[dict[str, Any]]]: """Rotate ``recipe.stone_wales`` bonds by 90 degrees (Stone and Wales 1986). Returns new coordinates, bonds and construction faces, and one record per rotation. ``box`` holds the orthogonal cell edges, for minimum images. """ if not recipe.stone_wales: return cartesian, bonds, faces, [] faces = [list(face) for face in faces] on_bond: dict[tuple[int, int], list[int]] = {} on_atom: dict[int, list[int]] = {} for f, face in enumerate(faces): for k, atom in enumerate(face): nxt = face[(k + 1) % len(face)] on_bond.setdefault((min(atom, nxt), max(atom, nxt)), []).append(f) on_atom.setdefault(atom, []).append(f) def beside(face: list[int], atom: int, other: int) -> int: """``atom``'s neighbour in ``face`` that is not ``other``.""" k = face.index(atom) before, after = face[k - 1], face[(k + 1) % len(face)] return after if before == other else before candidates = sorted( (min(i, j), max(i, j)) for i, j, kind in bonds if kind == recipe.stone_wales_bond ) rng = np.random.default_rng([recipe.seed, 1]) used_atoms: set[int] = set() used_faces: set[int] = set() chosen: list[tuple[int, int, int, int, int, int, int, int, int, int]] = [] for n in rng.permutation(len(candidates)): i, j = candidates[int(n)] f1, f2 = on_bond[(i, j)] (f3,) = [f for f in on_atom[i] if f not in (f1, f2)] (f4,) = [f for f in on_atom[j] if f not in (f1, f2)] a, c = beside(faces[f1], i, j), beside(faces[f1], j, i) b, d = beside(faces[f2], i, j), beside(faces[f2], j, i) atoms, rings = {i, j, a, b, c, d}, {f1, f2, f3, f4} if len(atoms) < 6 or len(rings) < 4 or atoms & used_atoms or rings & used_faces: continue used_atoms |= atoms used_faces |= rings chosen.append((i, j, a, b, c, d, f1, f2, f3, f4)) if len(chosen) == recipe.stone_wales: break if len(chosen) < recipe.stone_wales: raise PorousCarbonRefused( "porous_carbon.stone_wales_crowded", f"only {len(chosen)} {recipe.stone_wales_bond} bonds can rotate without sharing an " f"atom or ring; {recipe.stone_wales} were asked for", ) bond_kind = {(min(i, j), max(i, j)): kind for i, j, kind in bonds} xyz = cartesian.copy() records: list[dict[str, Any]] = [] for i, j, a, b, c, d, f1, f2, f3, f4 in chosen: before = [len(faces[f]) for f in (f1, f2, f3, f4)] def near(point: _Points, ref: _Points) -> _Points: step: _Points = point - ref return ref + step - box * np.round(step / box) ri = xyz[i] rj, ra, rb, rc, rd = (near(xyz[k], ri) for k in (j, a, b, c, d)) points = np.array([ri, rj, ra, rb, rc, rd]) normal = np.linalg.svd(points - points.mean(axis=0))[2][-1] toward = (rb + rd) / 2 - (ra + rc) / 2 # i keeps b and takes d; j keeps c and takes a toward = toward - float(toward @ normal) * normal toward /= np.linalg.norm(toward) middle, half = (ri + rj) / 2, float(np.linalg.norm(rj - ri)) / 2 xyz[i], xyz[j] = middle + half * toward, middle - half * toward del bond_kind[(min(i, a), max(i, a))], bond_kind[(min(j, d), max(j, d))] bond_kind[(min(i, d), max(i, d))] = "stone_wales" bond_kind[(min(j, a), max(j, a))] = "stone_wales" faces[f1].remove(i) faces[f2].remove(j) for target, first, second, inserted in ((f3, a, i, j), (f4, j, d, i)): ring = faces[target] p, q = ring.index(first), ring.index(second) ring.insert(max(p, q) if abs(p - q) == 1 else 0, inserted) records.append( { "bond": [i + 1, j + 1], "kind": recipe.stone_wales_bond, "rings_before": before, "rings_after": [len(faces[f]) for f in (f1, f2, f3, f4)], "bonds_broken": [[i + 1, a + 1], [j + 1, d + 1]], "bonds_formed": [[i + 1, d + 1], [j + 1, a + 1]], } ) rotated = [(i, j, kind) for (i, j), kind in sorted(bond_kind.items())] return xyz, rotated, faces, records def _surface_topology( vertices: int, bonds: list[tuple[int, int, str]], faces: list[list[int]] ) -> dict[str, Any]: """Closed-surface checks and Euler characteristic of the construction faces.""" bond_set = {(min(i, j), max(i, j)) for i, j, _ in bonds} uses: dict[tuple[int, int], list[tuple[int, int]]] = {} for f, face in enumerate(faces): for k in range(len(face)): i, j = face[k], face[(k + 1) % len(face)] key = (min(i, j), max(i, j)) if key not in bond_set: raise PorousCarbonRefused( "porous_carbon.face_not_cycle", f"face {f + 1} steps over a missing bond" ) uses.setdefault(key, []).append((f, 1 if i < j else -1)) if set(uses) != bond_set or any(len(u) != 2 for u in uses.values()): raise PorousCarbonRefused( "porous_carbon.non_manifold", "a bond is not on exactly two construction faces" ) # Orientability: flip faces so each bond is walked once each way (breadth first). sign: dict[int, int] = {0: 1} queue = deque([0]) by_face: dict[int, list[tuple[int, int]]] = {} for (f, s), (g, t) in uses.values(): by_face.setdefault(f, []).append((g, -s * t)) by_face.setdefault(g, []).append((f, -s * t)) orientable = True while queue: f = queue.popleft() for g, relation in by_face.get(f, []): wanted = sign[f] * relation if g not in sign: sign[g] = wanted queue.append(g) elif sign[g] != wanted: orientable = False census = Counter(len(face) for face in faces) chi = vertices - len(bond_set) + len(faces) curvature = sum((6 - n) * c for n, c in census.items()) return { "vertices": vertices, "edges": len(bond_set), "faces": len(faces), "face_census": {str(n): census[n] for n in sorted(census)}, "euler_characteristic": chi, "orientable": orientable, "connected_faces": len(sign) == len(faces), "genus": (2 - chi) // 2 if orientable and chi % 2 == 0 else None, "curvature_sum": curvature, "curvature_check": "sum over faces of (6 - n) = 6 chi for a 3-connected sheet " f"({curvature} = {6 * chi})", "curvature_check_holds": curvature == 6 * chi, "definition": "chi = V - E + F over the construction faces of the cell; genus = " "1 - chi/2 of the orientable closed sheet in the 3-torus", } # --- graph analysis ---------------------------------------------------------------------- def _neg(image: Image) -> Image: return (-image[0], -image[1], -image[2]) def _add(x: Image, y: Image) -> Image: return (x[0] + y[0], x[1] + y[1], x[2] + y[2]) def _sub(x: Image, y: Image) -> Image: return (x[0] - y[0], x[1] - y[1], x[2] - y[2]) def _smallest_ring( adjacency: list[list[tuple[int, Image]]], centre: int, first: tuple[int, Image], second: tuple[int, Image], limit: int, ) -> list[tuple[int, Image]] | None: """The shortest path ``first`` to ``second`` in the lift avoiding ``centre``, as a ring.""" start, goal = first, second parent: dict[tuple[int, Image], tuple[int, Image] | None] = {start: None} frontier = [start] for _ in range(limit - 2): following: list[tuple[int, Image]] = [] for node in frontier: site, image = node for other, step in adjacency[site]: nxt = (other, _add(image, step)) if nxt in parent or nxt == (centre, (0, 0, 0)): continue parent[nxt] = node if nxt == goal: path: list[tuple[int, Image]] = [nxt] back = parent[nxt] while back is not None: path.append(back) back = parent[back] return [(centre, (0, 0, 0)), *reversed(path)] following.append(nxt) frontier = following return None def _canonical(ring: list[tuple[int, Image]]) -> tuple[tuple[int, Image], ...]: low = min(site for site, _ in ring) options = [] for site, image in ring: if site == low: options.append(tuple(sorted((s, _sub(i, image)) for s, i in ring))) return min(options)
[docs] def analyse_carbon_graph( structure: PeriodicStructure, *, targets: list[float] | None = None, kinds: list[str] | None = None, max_ring_size: int = 12, ) -> dict[str, Any]: """Coordination, bond lengths and angles under PBC, vertex symbols and a ring census. Reads the chemical edges (authored and perceived); topology, distance and suppressed edges are ignored. ``targets`` gives each chemical bond's target length in stored order (default 1.42 angstrom). """ if max_ring_size > MAX_RING: raise PorousCarbonRefused("porous_carbon.too_large", f"rings above {MAX_RING} atoms") lattice = np.array(structure.lattice_angstrom, dtype=float) ids = [s.id for s in structure.sites] where = {sid: k for k, sid in enumerate(ids)} xyz = np.array([s.fractional for s in structure.sites], dtype=float) @ lattice chemical = [b for b in structure.bonds if b.kind in ("authored", "perceived")] adjacency: list[list[tuple[int, Image]]] = [[] for _ in ids] lengths: list[dict[str, Any]] = [] for n, bond in enumerate(chemical): i, j = where[bond.a], where[bond.b] adjacency[i].append((j, bond.image)) adjacency[j].append((i, _neg(bond.image))) vector = xyz[j] + np.array(bond.image, dtype=float) @ lattice - xyz[i] target = targets[n] if targets is not None else 1.42 lengths.append( { "kind": kinds[n] if kinds is not None else "bond", "length": float(np.linalg.norm(vector)), "target": target, } ) diagnostics: list[dict[str, Any]] = [] coordination = Counter(len(neighbours) for neighbours in adjacency) flagged = [ids[k] for k, neighbours in enumerate(adjacency) if len(neighbours) != 3] if flagged: diagnostics.append( { "code": "coordination.not_three", "severity": "warning", "message": f"{len(flagged)} carbon(s) are not 3-coordinate " f"({', '.join(flagged[:8])}); no hydrogen is added", "sites": flagged, } ) sites: dict[str, dict[str, Any]] = {} rings: dict[tuple[tuple[int, Image], ...], int] = {} angle_sums: list[float] = [] for k, neighbours in enumerate(adjacency): symbol: list[int | None] = [] angles: list[float] = [] for (p, ip), (q, iq) in itertools.combinations(neighbours, 2): ring = _smallest_ring(adjacency, k, (p, ip), (q, iq), max_ring_size) symbol.append(len(ring) if ring else None) if ring: rings.setdefault(_canonical(ring), len(ring)) u = xyz[p] + np.array(ip, dtype=float) @ lattice - xyz[k] w = xyz[q] + np.array(iq, dtype=float) @ lattice - xyz[k] cosine = float(u @ w / (np.linalg.norm(u) * np.linalg.norm(w))) angles.append(math.degrees(math.acos(max(-1.0, min(1.0, cosine))))) if len(neighbours) == 3: angle_sums.append(sum(angles)) text = ".".join(str(n) if n else "*" for n in sorted(symbol, key=lambda n: n or 99)) sites[ids[k]] = { "coordination": len(neighbours), "vertex_symbol": text, "angles_deg": [round(x, 3) for x in angles], } symbols = Counter(entry["vertex_symbol"] for entry in sites.values()) census = Counter(rings.values()) by_kind: dict[str, dict[str, float]] = {} for kind in sorted({x["kind"] for x in lengths}): values = [x["length"] for x in lengths if x["kind"] == kind] by_kind[kind] = { "count": len(values), "min_angstrom": round(min(values), 4), "max_angstrom": round(max(values), 4), "mean_angstrom": round(sum(values) / len(values), 4), } deviation = max((abs(x["length"] - x["target"]) for x in lengths), default=0.0) return { "sites_total": len(ids), "chemical_bonds": len(chemical), "topology_edges": sum(1 for b in structure.bonds if b.kind == "topology"), "coordination": {str(n): coordination[n] for n in sorted(coordination)}, "not_three_coordinate": flagged, "bond_lengths": by_kind, "max_bond_deviation_angstrom": round(deviation, 4), "bond_angle_sum_deg": ( {"min": round(min(angle_sums), 3), "max": round(max(angle_sums), 3), "planar": 360.0} if angle_sums else None ), "vertex_symbols": dict(sorted(symbols.items())), "ring_census": {str(n): census[n] for n in sorted(census)}, "ring_definition": "smallest ring at each bond angle (vertex symbol), searched up to " f"{max_ring_size} atoms in the periodic lift; distinct rings counted once per cell; " "'*' marks an angle with no ring within the bound", "diagnostics": diagnostics, "sites": sites, }
def _check_geometry(report: dict[str, Any], recipe: PorousCarbonRecipe) -> None: if report["max_bond_deviation_angstrom"] > recipe.bond_tolerance: raise PorousCarbonRefused( "porous_carbon.bond_misfit", f"a bond is {report['max_bond_deviation_angstrom']:.3f} angstrom off its target " f"(bond_tolerance {recipe.bond_tolerance:g})", ) def _contacts(structure: PeriodicStructure, recipe: PorousCarbonRecipe) -> dict[str, Any]: """Non-bonded pairs within the perception range under PBC; refuses clashes.""" lattice = np.array(structure.lattice_angstrom, dtype=float) xyz = np.array([s.fractional for s in structure.sites], dtype=float) @ lattice ids = [s.id for s in structure.sites] where = {sid: k for k, sid in enumerate(ids)} bonded: set[tuple[int, int, Image]] = set() for bond in structure.bonds: i, j = where[bond.a], where[bond.b] bonded.add((i, j, bond.image)) bonded.add((j, i, _neg(bond.image))) perception = PERCEPTION_SCALE * 2 * _CARBON_RADIUS cutoff = max(perception, recipe.min_distance, 2.6) unbonded: list[tuple[int, int, Image, float]] = [] for i, j, image, distance in neighbour_pairs(xyz, lattice, structure.pbc, cutoff): if (i, j, image) not in bonded: unbonded.append((i, j, image, distance)) clashes = [x for x in unbonded if x[3] < recipe.min_distance] if clashes: i, j, _, distance = clashes[0] raise PorousCarbonRefused( "porous_carbon.collision", f"{len(clashes)} non-bonded carbon pair(s) closer than {recipe.min_distance:g} " f"angstrom ({ids[i]}-{ids[j]} at {distance:.3f})", ) closest = min((d for *_, d in unbonded), default=None) return { "perception_cutoff_angstrom": round(perception, 4), "unbonded_within_perception": len([x for x in unbonded if x[3] <= perception]), "closest_unbonded_angstrom": round(closest, 4) if closest is not None else None, "min_distance_angstrom": recipe.min_distance, } # --- plan, preview and porosity handoff --------------------------------------------------
[docs] def model_catalog() -> dict[str, Any]: """The model plan: constructions (built or planned), parameters, bounds and status.""" from vibesketcher.chem.reticular import NETS return { "status": STATUS, "constructions": CONSTRUCTIONS, "nets": {name: _NET_ROUTES.get(name) for name in NETS}, "bounds": { "max_repeat": MAX_REPEAT, "max_vacancies": MAX_VACANCIES, "max_stone_wales": MAX_STONE_WALES, "max_ring_size": MAX_RING, "atoms_per_cell": ATOMS_PER_CELL, }, "checks": [ "construction faces are closed cycles, each bond on two faces, consistently oriented", "chi = V - E + F and genus per cell; genus equals the net's cycle rank", "sum over faces of (6 - n) = 6 chi", "coordination per carbon (non-3-coordinate flagged, never capped)", "bond lengths under PBC against their targets; non-bonded contacts within the " "perception range", "smallest ring at each bond angle and a distinct-ring census", ], "porosity": "planned via vibesketcher.document.porosity (probe-defined plans); see " "porosity_handoff_plan", "references": REFERENCES, }
[docs] def preview(recipe: PorousCarbonRecipe) -> dict[str, Any]: """Build without storing: the model record, contacts and the structure, or the refusal.""" try: structure = build_porous_carbon(recipe) except PorousCarbonRefused as error: return {"refused": True, "refusals": [{"code": error.code, "message": error.detail}]} except BuildRefused as error: return {"refused": True, "refusals": [{"code": "build.refused", "message": str(error)}]} builder = structure.provenance["builder"] assert isinstance(builder, dict) return { "refused": False, "status": STATUS, "model": builder["model"], "warnings": builder.get("warnings", []), "structure": structure.model_dump(mode="json", exclude_none=True), }
[docs] def porosity_handoff_plan( structure: PeriodicStructure, *, probe_species: str = "He", probe_radius: float = 1.3, radius_source: str | None = "user-stated hard-sphere radius", ) -> dict[str, Any]: """A probe-defined porosity plan for a built model, validated but not run. The plan goes to :mod:`vibesketcher.document.porosity` unchanged; this states the assumptions a net-derived sheet adds. Nothing is estimated here. """ from vibesketcher.document.porosity import parse_plan, plan_porosity builder = structure.provenance.get("builder") if not isinstance(builder, dict) or builder.get("kind") != "porous_carbon": raise ValueError(f"{structure.id} is not a porous_carbon model") plan = parse_plan( { "structure": structure.id, "probe": { "species": probe_species, "radius_angstrom": probe_radius, "radius_source": radius_source, }, "radii": {"name": "vdw"}, "surface": "accessible", } ) planning = plan_porosity(structure, plan) return { "status": STATUS, "plan": plan.model_dump(mode="json"), "runnable": planning["runnable"], "refusals": planning["refusals"], "work": planning["work"], "assumptions": [ "the sheet is one atom thick and divides the cell into two congruent labyrinths " "(either side of the P surface); both are void for a geometric analysis", "atoms are hard spheres of RDKit van der Waals radii; no relaxation, thermal " "motion or framework flexibility", "the geometry is a geometric model, unrelaxed; pores of a relaxed or synthesised " "material may differ", "geometric void is not adsorption capacity and an accessible surface is not a BET area", ], "engine": "run with vibesketcher.document.porosity (reference engine) or a reviewed " "external engine; not run here", }
[docs] def structure_report( structure: PeriodicStructure, *, max_ring_size: int = 12, probe_radius: float | None = None, probe_species: str = "He", ) -> dict[str, Any]: """The graph checks of a stored carbon structure, with its model record when it has one. A porous_carbon build's record is compared with the current graph: an edit after the build makes the record ``stale``, and the live checks win. """ others = sorted({s.symbol for s in structure.sites} - {"C"}) if others: raise PorousCarbonRefused( "porous_carbon.not_carbon", f"{structure.id} has {', '.join(others)} sites; the report checks carbon graphs", ) report = analyse_carbon_graph(structure, max_ring_size=max_ring_size) if not report["chemical_bonds"]: report["diagnostics"].append( { "code": "graph.no_chemical_bonds", "severity": "warning", "message": "no chemical bonds are stored; perceive or author them first", } ) builder = structure.provenance.get("builder") model = builder.get("model") if isinstance(builder, dict) else None record: dict[str, Any] | None = None if isinstance(builder, dict) and builder.get("kind") == "porous_carbon": from vibesketcher.document.periodic_graph import geometry_fingerprint built = model.get("built_graph", {}) if isinstance(model, dict) else {} current = { "sites": len(structure.sites), "chemical_bonds": report["chemical_bonds"], "geometry_fingerprint": geometry_fingerprint(structure), } record = { "status": builder.get("status"), "construction": model.get("construction") if isinstance(model, dict) else None, "pristine_topology": model.get("pristine_topology") if isinstance(model, dict) else None, "defect_map": model.get("defect_map") if isinstance(model, dict) else None, "stale": built != current, } result: dict[str, Any] = { "structure": structure.id, "status": STATUS if record else "not a porous_carbon build; graph checks only", "model": record, "graph": report, } if probe_radius is not None: if record is None: raise PorousCarbonRefused( "porous_carbon.not_a_model", f"{structure.id} is not a porous_carbon build; plan porosity directly", ) result["porosity_handoff"] = porosity_handoff_plan( structure, probe_species=probe_species, probe_radius=probe_radius ) return result