vibe-sketcherDocumentation
Source code for vibesketcher.chem.reticular
"""Reticular frameworks from drawn building blocks with explicit connection points (#202).
A building block is a molecule whose connection points are marked by dummy
atoms: ``*`` in SMILES (``[*:1]``, ``[1*]``), the R-group and attachment atoms
of a drawn generic structure (``_R1``, ``_AP1``), or ``X`` in an explicit atom
list. Each marker is bonded to exactly one anchor atom; the anchor-to-marker
direction is the attachment direction. Markers are never physical atoms: they
are removed before assembly, the anchors are bonded to their partners across
a net edge, and the assembly record says how many markers were consumed.
The net is chosen explicitly from a small catalogue defined here from the
geometry of the lattice itself (simple cubic, diamond, square and honeycomb
graphs; vertex and edge lists written out by hand). Their three-letter names
follow the RCSR convention (O'Keeffe, Peskov, Ramsden and Yaghi, Acc. Chem.
Res. 41, 1782 (2008), doi:10.1021/ar800124u); no RCSR or PORMAKE data is
bundled or read. Construction is the reticular one (Yaghi, O'Keeffe, Ockwig,
Chae, Eddaoudi and Kim, Nature 423, 705 (2003), doi:10.1038/nature01650): a
node block on every vertex, a ditopic linker block on every edge, or the
nodes joined directly when no linker is given.
Each node is rotated onto its vertex by the proper rotation that best maps
its centre-to-marker directions onto the vertex's edge directions over every
assignment of markers to edges (W. Kabsch, Acta Cryst. A32, 922 (1976),
doi:10.1107/S0567739476001873; ties keep the first assignment in
lexicographic order). A linker's anchor-to-anchor axis is laid along its
edge and its widest perpendicular direction along a fixed reference turned
by ``linker_rotation``. The edge length is the longest one any edge needs for
bonds of the covalent-radius sum (Cordero et al., Dalton Trans. 2008, 2832,
doi:10.1039/b801115j). Blocks drawn without coordinates are embedded with
RDKit's ETKDG v3 and MMFF94 (or UFF) under a fixed seed, markers standing in
as hydrogen. Nothing is relaxed: the coordinates are an unrelaxed starting
geometry, and misfits are reported (or refused), never smoothed away.
Interpenetration, rod nodes, merged nets, partitioned pores and
supertetrahedral units are gated extensions, refused by name.
"""
from __future__ import annotations
import itertools
import math
from collections import Counter
from dataclasses import dataclass, field
from typing import Annotated, Any, Literal, Self
import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field, model_validator
from vibesketcher.chem.periodic_geometry import BuildRefused, _provenance, _structure
from vibesketcher.document.model import Document, PeriodicBond, PeriodicStructure
from vibesketcher.elements import ATOMIC_NUMBER
__all__ = [
"GATED_EXTENSIONS",
"NETS",
"AssemblyRefused",
"BlockSpec",
"ReticularRecipe",
"assembly_refusals",
"build_reticular",
"net_catalog",
"preview",
]
_Points = NDArray[np.float64]
Image = tuple[int, int, int]
#: Version of this construction, recorded in provenance.
ASSEMBLY_VERSION = 1
#: Connection points one block may carry.
MAX_MARKERS = 12
#: Explicit atoms one block may list.
MAX_BLOCK_ATOMS = 500
#: Extensions a topology name does not imply; each is refused until designed.
GATED_EXTENSIONS = (
"interpenetration",
"rod_nodes",
"merged_nets",
"partitioned_pores",
"supertetrahedral_units",
)
[docs]
class AssemblyRefused(BuildRefused):
"""A reticular assembly 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
# --- nets ------------------------------------------------------------------------
@dataclass(frozen=True)
class NetEdge:
"""From vertex ``tail`` in the home cell to vertex ``head`` in cell ``image``."""
id: str
tail: str
head: str
image: Image
@dataclass(frozen=True)
class Net:
"""A periodic net with unit edge length; rows of ``lattice`` are cell vectors."""
name: str
description: str
dimension: Literal[2, 3]
lattice: tuple[tuple[float, float, float], ...]
vertices: dict[str, tuple[float, float, float]]
edges: tuple[NetEdge, ...]
vertex_figure: str
construction: str
def rows(self) -> _Points:
return np.array(self.lattice, dtype=float)
def directions(self, vertex: str) -> list[tuple[str, str, _Points]]:
"""``(edge, end, unit direction)`` leaving ``vertex``, in edge order."""
rows = self.rows()
out: list[tuple[str, str, _Points]] = []
for edge in self.edges:
span = (
np.array(self.vertices[edge.head])
+ np.array(edge.image, dtype=float)
- np.array(self.vertices[edge.tail])
) @ rows
unit = span / np.linalg.norm(span)
if edge.tail == vertex:
out.append((edge.id, "tail", unit))
if edge.head == vertex:
out.append((edge.id, "head", -unit))
return out
def describe(self) -> dict[str, Any]:
return {
"name": self.name,
"description": self.description,
"dimension": self.dimension,
"vertices": {v: list(f) for v, f in self.vertices.items()},
"edges": [
{"id": e.id, "tail": e.tail, "head": e.head, "image": list(e.image)}
for e in self.edges
],
"coordination": {v: len(self.directions(v)) for v in self.vertices},
"vertex_figure": self.vertex_figure,
"unit_edge_lattice": [list(row) for row in self.lattice],
"construction": self.construction,
"source": "defined in vibe-sketcher from the lattice geometry; no RCSR data",
}
_SQ3 = math.sqrt(3.0)
_DIA_A = 4 / _SQ3 # the cubic constant whose nearest-neighbour distance is 1
NETS: dict[str, Net] = {
"pcu": Net(
name="pcu",
description="primitive cubic: 6-c octahedral vertex, one vertex per cell",
dimension=3,
lattice=((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)),
vertices={"V1": (0.0, 0.0, 0.0)},
edges=(
NetEdge("E1", "V1", "V1", (1, 0, 0)),
NetEdge("E2", "V1", "V1", (0, 1, 0)),
NetEdge("E3", "V1", "V1", (0, 0, 1)),
),
vertex_figure="octahedron",
construction="vertices of the simple cubic lattice, edges along the cell vectors",
),
"dia": Net(
name="dia",
description="diamond: 4-c tetrahedral vertices, two per primitive fcc cell",
dimension=3,
lattice=(
(0.0, _DIA_A / 2, _DIA_A / 2),
(_DIA_A / 2, 0.0, _DIA_A / 2),
(_DIA_A / 2, _DIA_A / 2, 0.0),
),
vertices={"V1": (0.0, 0.0, 0.0), "V2": (0.25, 0.25, 0.25)},
edges=(
NetEdge("E1", "V1", "V2", (0, 0, 0)),
NetEdge("E2", "V1", "V2", (-1, 0, 0)),
NetEdge("E3", "V1", "V2", (0, -1, 0)),
NetEdge("E4", "V1", "V2", (0, 0, -1)),
),
vertex_figure="tetrahedron",
construction="fcc lattice with a two-point basis at 0 and (1/4, 1/4, 1/4)",
),
"sql": Net(
name="sql",
description="square grid layer: 4-c square-planar vertex, one per cell",
dimension=2,
lattice=((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)),
vertices={"V1": (0.0, 0.0, 0.0)},
edges=(NetEdge("E1", "V1", "V1", (1, 0, 0)), NetEdge("E2", "V1", "V1", (0, 1, 0))),
vertex_figure="square",
construction="vertices of the square lattice, edges along a and b",
),
"hcb": Net(
name="hcb",
description="honeycomb layer: 3-c trigonal vertices, two per hexagonal cell",
dimension=2,
lattice=((_SQ3, 0.0, 0.0), (-_SQ3 / 2, 1.5, 0.0), (0.0, 0.0, 1.0)),
vertices={"V1": (1 / 3, 2 / 3, 0.0), "V2": (2 / 3, 1 / 3, 0.0)},
edges=(
NetEdge("E1", "V1", "V2", (0, 0, 0)),
NetEdge("E2", "V1", "V2", (-1, 0, 0)),
NetEdge("E3", "V1", "V2", (0, 1, 0)),
),
vertex_figure="triangle",
construction="hexagonal lattice with vertices at (1/3, 2/3) and (2/3, 1/3)",
),
}
[docs]
def net_catalog() -> dict[str, Any]:
"""The nets and gated extensions, for clients that present choices."""
return {
"nets": {name: net.describe() for name, net in NETS.items()},
"gated_extensions": list(GATED_EXTENSIONS),
"markers": "dummy atoms: * in SMILES, R-group/attachment atoms of a drawn generic, "
"or X in an atom list; each bonded to exactly one anchor atom",
}
# --- recipe ------------------------------------------------------------------------
class _Spec(BaseModel):
model_config = ConfigDict(extra="forbid")
class BlockAtom(_Spec):
"""One explicit atom; ``X`` marks a connection point."""
symbol: str
xyz: tuple[float, float, float]
[docs]
class BlockSpec(_Spec):
"""A building block: SMILES, a drawn generic structure, or explicit atoms."""
smiles: str | None = Field(default=None, min_length=1, max_length=2000)
generic: str | None = Field(default=None, description="A generic structure id in the document.")
atoms: list[BlockAtom] = Field(default_factory=list, max_length=MAX_BLOCK_ATOMS)
bonds: list[tuple[int, int, float]] = Field(
default_factory=list, max_length=4 * MAX_BLOCK_ATOMS
)
@model_validator(mode="after")
def _one_source(self) -> Self:
given = [x for x in (self.smiles, self.generic, self.atoms or None) if x]
if len(given) != 1:
raise ValueError("a block needs exactly one of smiles, generic or atoms")
if self.bonds and not self.atoms:
raise ValueError("bonds go with an explicit atom list")
return self
_ID = Annotated[str, Field(pattern=r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")]
[docs]
class ReticularRecipe(_Spec):
"""A framework from a node block, an optional linker block and an explicit net."""
kind: Literal["reticular"] = "reticular"
identifier: _ID
net: str = Field(min_length=1, max_length=32)
node: BlockSpec
#: A second node block for the second vertex of a two-vertex net (dia, hcb).
second_node: BlockSpec | None = None
#: A ditopic linker on every edge; without one, node anchors bond directly.
linker: BlockSpec | None = None
linker_rotation: float = Field(default=0.0, ge=-360, le=360, allow_inf_nan=False)
angle_tolerance: float = Field(default=20.0, gt=0, le=60, allow_inf_nan=False)
closure_tolerance: float = Field(default=0.3, gt=0, le=2, allow_inf_nan=False)
min_distance: float = Field(default=1.0, gt=0, le=3, allow_inf_nan=False)
vacuum: float = Field(default=15.0, ge=5, le=200, allow_inf_nan=False)
interpenetration: int = Field(default=1, ge=1, le=8)
extensions: list[str] = Field(default_factory=list, max_length=8)
# --- blocks ------------------------------------------------------------------------
@dataclass
class _Point:
label: str
anchor: int
marker: _Points
@dataclass
class _Block:
name: str
source: dict[str, Any]
symbols: list[str]
positions: _Points
bonds: list[tuple[int, int, float]]
points: list[_Point]
notes: list[str] = field(default_factory=list)
def formula(self) -> str:
return _hill(Counter(self.symbols))
def describe(self) -> dict[str, Any]:
return {
"source": self.source,
"formula": self.formula(),
"atoms": len(self.symbols),
"connection_points": [
{"label": p.label, "anchor": p.anchor, "anchor_symbol": self.symbols[p.anchor]}
for p in self.points
],
"markers_removed": len(self.points),
}
def _hill(counts: Counter[str]) -> str:
order = (["C", "H"] if "C" in counts else []) + sorted(
s for s in counts if "C" not in counts or s not in ("C", "H")
)
return "".join(f"{s}{counts[s] if counts[s] > 1 else ''}" for s in order)
def _marker_label(atom: Any, position: int) -> str:
for prop in ("atomLabel", "dummyLabel"):
if atom.HasProp(prop):
text = str(atom.GetProp(prop)).strip()
if text and text != "*":
return text
if atom.GetAtomMapNum():
return f"*{atom.GetAtomMapNum()}"
if atom.GetIsotope():
return f"*{atom.GetIsotope()}"
return f"*{position}"
def _smiles_block(name: str, smiles: str, source: dict[str, Any]) -> _Block:
from rdkit import Chem
from vibesketcher.chem.frameworks import _embed_mol, _rdkit_version
mol = Chem.MolFromSmiles(smiles) # reads CXSMILES atom labels ($_R1$) too
if mol is None:
raise AssemblyRefused("block.unreadable", f"cannot read the {name} SMILES {smiles!r}")
markers = [a.GetIdx() for a in mol.GetAtoms() if a.GetAtomicNum() == 0]
_check_marker_count(name, len(markers))
labels: dict[int, str] = {}
anchors: dict[int, int] = {}
for position, index in enumerate(markers, start=1):
atom = mol.GetAtomWithIdx(index)
neighbours = list(atom.GetNeighbors())
if len(neighbours) != 1 or neighbours[0].GetAtomicNum() == 0:
raise AssemblyRefused(
"block.marker_valence",
f"connection point {position} of the {name} must bond to exactly one real atom",
)
bond = mol.GetBondBetweenAtoms(index, neighbours[0].GetIdx())
if bond.GetBondTypeAsDouble() != 1.0:
raise AssemblyRefused(
"block.marker_valence",
f"connection point {position} of the {name} must be singly bonded",
)
labels[index] = _marker_label(atom, position)
anchors[index] = neighbours[0].GetIdx()
_check_unique_labels(name, list(labels.values()))
# Markers stand in as hydrogen for the embedding only; the anchor-to-H
# direction is the attachment direction.
editable = Chem.RWMol(mol)
for index in markers:
atom = editable.GetAtomWithIdx(index)
atom.SetAtomicNum(1)
atom.SetIsotope(0)
atom.SetAtomMapNum(0)
atom.SetNoImplicit(True)
atom.SetFormalCharge(0)
for prop in ("atomLabel", "dummyLabel", "molFileAlias"):
if atom.HasProp(prop):
atom.ClearProp(prop)
stand_in = editable.GetMol()
try:
Chem.SanitizeMol(stand_in)
except Exception as error: # RDKit raises several sanitisation types
raise AssemblyRefused(
"block.unreadable", f"the {name} does not sanitise: {error}"
) from None
embedded = _embed_mol(stand_in, name)
xyz = np.asarray(embedded.GetConformer().GetPositions(), dtype=float)
keep = [a.GetIdx() for a in embedded.GetAtoms() if a.GetIdx() not in labels]
order = {old: new for new, old in enumerate(keep)}
bonds = [
(order[b.GetBeginAtomIdx()], order[b.GetEndAtomIdx()], float(b.GetBondTypeAsDouble()))
for b in embedded.GetBonds()
if b.GetBeginAtomIdx() in order and b.GetEndAtomIdx() in order
]
points = [_Point(labels[m], order[anchors[m]], xyz[m]) for m in markers]
return _Block(
name,
source,
[embedded.GetAtomWithIdx(i).GetSymbol() for i in keep],
xyz[keep],
bonds,
points,
[f"{name} embedded with RDKit {_rdkit_version()} (ETKDGv3, MMFF94/UFF, fixed seed)"],
)
def _atoms_block(name: str, spec: BlockSpec) -> _Block:
markers = [i for i, a in enumerate(spec.atoms) if a.symbol in ("X", "*")]
_check_marker_count(name, len(markers))
real = [i for i, a in enumerate(spec.atoms) if a.symbol not in ("X", "*")]
if not real:
raise AssemblyRefused("block.empty", f"the {name} has no real atoms")
for i in real:
if spec.atoms[i].symbol not in ATOMIC_NUMBER:
raise AssemblyRefused(
"block.unknown_element",
f"the {name} has an unknown element {spec.atoms[i].symbol!r}",
)
xyz = np.array([a.xyz for a in spec.atoms], dtype=float)
if not np.all(np.isfinite(xyz)):
raise AssemblyRefused("block.unreadable", f"the {name} has non-finite coordinates")
order = {old: new for new, old in enumerate(real)}
bonds = []
for i, j, bond_order in spec.bonds:
if not (0 <= i < len(spec.atoms) and 0 <= j < len(spec.atoms)) or i == j:
raise AssemblyRefused("block.bad_bond", f"the {name} bond {i}-{j} names no atom pair")
if i not in order or j not in order:
raise AssemblyRefused(
"block.bad_bond", f"the {name} bond {i}-{j} joins a marker; markers bond implicitly"
)
if not (math.isfinite(bond_order) and bond_order > 0):
raise AssemblyRefused("block.bad_bond", f"the {name} bond {i}-{j} has no order")
bonds.append((order[i], order[j], float(bond_order)))
points = []
for position, m in enumerate(markers, start=1):
distances = [(float(np.linalg.norm(xyz[r] - xyz[m])), r) for r in real]
distance, anchor = min(distances)
if distance > 3.0 or distance < 0.3:
raise AssemblyRefused(
"block.marker_valence",
f"marker {position} of the {name} has no anchor atom between 0.3 and 3 angstrom",
)
points.append(_Point(f"X{position}", order[anchor], xyz[m]))
return _Block(
name,
{"atoms": len(spec.atoms)},
[spec.atoms[i].symbol for i in real],
xyz[real],
bonds,
points,
)
def _check_marker_count(name: str, count: int) -> None:
if count == 0:
raise AssemblyRefused(
"block.no_connection_points",
f"the {name} has no connection points; mark them with * (or R/attachment atoms)",
)
if count > MAX_MARKERS:
raise AssemblyRefused(
"block.too_many_points", f"the {name} has {count} connection points (> {MAX_MARKERS})"
)
def _check_unique_labels(name: str, labels: list[str]) -> None:
repeated = sorted(k for k, n in Counter(labels).items() if n > 1)
if repeated:
raise AssemblyRefused(
"block.duplicate_label",
f"the {name} repeats connection-point labels {', '.join(repeated)}",
)
def _block(name: str, spec: BlockSpec, document: Document | None) -> _Block:
if spec.atoms:
return _atoms_block(name, spec)
if spec.generic is not None:
found = {g.id: g for g in document.generics} if document is not None else {}
if spec.generic not in found:
raise AssemblyRefused("block.missing_generic", f"generic {spec.generic!r} not found")
text = found[spec.generic].cxsmiles
return _smiles_block(name, text, {"generic": spec.generic, "cxsmiles": text})
assert spec.smiles is not None
return _smiles_block(name, spec.smiles, {"smiles": spec.smiles})
# --- geometry ----------------------------------------------------------------------
def _kabsch(source: _Points, target: _Points) -> _Points:
"""The proper rotation R minimising sum |R s_i - t_i|^2 (Kabsch 1976)."""
h = source.T @ target
u, _, vt = np.linalg.svd(h)
d = 1.0 if np.linalg.det(vt.T @ u.T) >= 0 else -1.0
rotation: _Points = vt.T @ np.diag([1.0, 1.0, d]) @ u.T
return rotation
def _angle(a: _Points, b: _Points) -> float:
cosine = float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
return math.degrees(math.acos(max(-1.0, min(1.0, cosine))))
@dataclass
class _Placed:
vertex: str
rotation: _Points
centre: _Points
#: Connection-point index of the block for each (edge, end).
ports: dict[tuple[str, str], int]
angles: list[float]
def _align(block: _Block, vertex: str, net: Net, tolerance: float) -> _Placed:
ends = net.directions(vertex)
if len(ends) != len(block.points):
raise AssemblyRefused(
"site.coordination_mismatch",
f"vertex {vertex} of {net.name} is {len(ends)}-connected but the {block.name} "
f"has {len(block.points)} connection points",
)
centre = np.mean([block.positions[p.anchor] for p in block.points], axis=0)
spokes = np.array([p.marker - centre for p in block.points])
lengths = np.linalg.norm(spokes, axis=1)
if np.any(lengths < 1e-6):
raise AssemblyRefused(
"block.degenerate", f"a connection point of the {block.name} sits on its centre"
)
unit = spokes / lengths[:, None]
targets = np.array([d for _, _, d in ends])
best: tuple[float, tuple[int, ...], _Points] | None = None
for perm in itertools.permutations(range(len(ends))):
wanted = targets[list(perm)]
rotation = _kabsch(unit, wanted)
residual = float(np.sum((unit @ rotation.T - wanted) ** 2))
if best is None or residual < best[0] - 1e-9:
best = (residual, perm, rotation)
assert best is not None
_, perm, rotation = best
angles = [_angle(rotation @ unit[i], targets[perm[i]]) for i in range(len(ends))]
if max(angles) > tolerance:
raise AssemblyRefused(
"site.direction_mismatch",
f"the {block.name}'s connection directions miss the {net.vertex_figure} of "
f"vertex {vertex} by up to {max(angles):.1f} degrees (tolerance {tolerance:g})",
)
ports = {(ends[perm[i]][0], ends[perm[i]][1]): i for i in range(len(ends))}
return _Placed(vertex, rotation, centre, ports, angles)
def _reference(direction: _Points, dimension: int) -> _Points:
"""A fixed unit vector perpendicular to an edge: in-plane for layers."""
candidates = [np.array([0.0, 0.0, 1.0]), np.array([1.0, 0.0, 0.0]), np.array([0.0, 1.0, 0.0])]
if dimension == 2:
perpendicular = np.cross(np.array([0.0, 0.0, 1.0]), direction)
return perpendicular / np.linalg.norm(perpendicular)
for candidate in candidates:
if abs(float(candidate @ direction)) < 0.9:
part = candidate - (candidate @ direction) * direction
return part / np.linalg.norm(part)
raise AssertionError("no reference direction")
@dataclass
class _Linker:
block: _Block
first: int
second: int
#: Local frame: anchor midpoint at the origin, axis x, widest direction y.
local: _Points
markers: _Points
span: float
def _linker_frame(block: _Block, tolerance: float) -> _Linker:
if len(block.points) != 2:
raise AssemblyRefused(
"linker.not_ditopic",
f"a linker needs exactly two connection points; the linker has {len(block.points)}",
)
first, second = sorted(range(2), key=lambda k: (block.points[k].label, k))
a1 = block.positions[block.points[first].anchor]
a2 = block.positions[block.points[second].anchor]
axis = a2 - a1
span = float(np.linalg.norm(axis))
if span < 1e-6:
# One anchor carries both points (a single-atom linker): use the marker axis.
axis = block.points[second].marker - block.points[first].marker
if float(np.linalg.norm(axis)) < 1e-6:
raise AssemblyRefused("block.degenerate", "the linker's connection points coincide")
ex = axis / np.linalg.norm(axis)
for k, outward in ((first, -ex), (second, ex)):
point = block.points[k]
direction = point.marker - block.positions[point.anchor]
bend = _angle(direction, outward)
if bend > tolerance:
raise AssemblyRefused(
"linker.not_linear",
f"linker connection point {point.label} leaves {bend:.1f} degrees off its "
f"anchor-to-anchor axis (tolerance {tolerance:g})",
)
middle = (a1 + a2) / 2
relative = block.positions - middle
across = relative - np.outer(relative @ ex, ex)
if float(np.max(np.linalg.norm(across, axis=1))) < 1e-3:
trial = np.array([0.0, 0.0, 1.0]) if abs(ex[2]) < 0.9 else np.array([1.0, 0.0, 0.0])
ey = trial - (trial @ ex) * ex
else:
values, vectors = np.linalg.eigh(across.T @ across)
ey = vectors[:, int(np.argmax(values))]
projections = across @ ey
lead = next(p for p in projections if abs(p) > 1e-3)
if lead < 0:
ey = -ey
ey = ey / np.linalg.norm(ey)
ez = np.cross(ex, ey)
frame = np.array([ex, ey, ez])
return _Linker(
block,
first,
second,
relative @ frame.T,
np.array([p.marker - middle for p in block.points]) @ frame.T,
span,
)
def _covalent(symbol: str) -> float:
from vibesketcher.document.periodic_graph import covalent_radius
return covalent_radius(symbol)
def _rotate_about(vector: _Points, axis: _Points, degrees: float) -> _Points:
"""Rodrigues' rotation of ``vector`` about the unit ``axis``."""
t = math.radians(degrees)
rotated: _Points = (
vector * math.cos(t)
+ np.cross(axis, vector) * math.sin(t)
+ axis * float(axis @ vector) * (1 - math.cos(t))
)
return rotated
# --- assembly ------------------------------------------------------------------------
def _round(values: Any, digits: int = 6) -> Any:
return np.round(np.asarray(values, dtype=float), digits).tolist()
def _refuse_gated(recipe: ReticularRecipe) -> None:
if recipe.interpenetration > 1:
raise AssemblyRefused(
"gated.interpenetration",
"interpenetrated frameworks are a gated extension; build one net (interpenetration 1)",
)
for name in recipe.extensions:
if name in GATED_EXTENSIONS:
raise AssemblyRefused(
f"gated.{name}", f"{name.replace('_', ' ')} is a gated extension, not built yet"
)
raise AssemblyRefused("gated.unknown", f"unknown extension {name!r}")
def _net(name: str) -> Net:
if name not in NETS:
raise AssemblyRefused(
"net.unknown",
f"net {name!r} is not in the catalogue ({', '.join(NETS)}); RCSR and PORMAKE data "
"are not bundled",
)
return NETS[name]
[docs]
def build_reticular(recipe: ReticularRecipe, document: Document | None = None) -> PeriodicStructure:
"""Assemble the framework; refuse (``AssemblyRefused``) what cannot close cleanly."""
_refuse_gated(recipe)
net = _net(recipe.net)
vertices = list(net.vertices)
if recipe.second_node is not None and len(vertices) != 2:
raise AssemblyRefused(
"assignment.second_node", f"{net.name} has one vertex; second_node needs two"
)
node = _block("node", recipe.node, document)
second = _block("second_node", recipe.second_node, document) if recipe.second_node else None
linker = (
_linker_frame(_block("linker", recipe.linker, document), recipe.angle_tolerance)
if recipe.linker is not None
else None
)
blocks = {
v: (second if (second is not None and k == 1) else node) for k, v in enumerate(vertices)
}
assignment: dict[str, str] = {v: blocks[v].name for v in vertices}
for edge in net.edges:
assignment[edge.id] = "linker" if linker is not None else "direct bond"
placed = {v: _align(blocks[v], v, net, recipe.angle_tolerance) for v in vertices}
unit_rows = net.rows()
def anchor_vector(v: str, end: tuple[str, str]) -> tuple[_Points, str]:
block, where = blocks[v], placed[v]
point = block.points[where.ports[end]]
offset = where.rotation @ (block.positions[point.anchor] - where.centre)
return offset, block.symbols[point.anchor]
# The edge length each edge needs; the longest sets the cell.
needs: list[float] = []
for edge in net.edges:
span = (
np.array(net.vertices[edge.head])
+ np.array(edge.image, dtype=float)
- np.array(net.vertices[edge.tail])
) @ unit_rows
d = span / np.linalg.norm(span)
tail, tail_symbol = anchor_vector(edge.tail, (edge.id, "tail"))
head, head_symbol = anchor_vector(edge.head, (edge.id, "head"))
reach = float(tail @ d) - float(head @ d)
if linker is None:
needs.append(reach + _covalent(tail_symbol) + _covalent(head_symbol))
else:
lb = linker.block
first_symbol = lb.symbols[lb.points[linker.first].anchor]
second_symbol = lb.symbols[lb.points[linker.second].anchor]
needs.append(
reach
+ linker.span
+ _covalent(tail_symbol)
+ _covalent(first_symbol)
+ _covalent(head_symbol)
+ _covalent(second_symbol)
)
edge_length = max(needs)
if edge_length <= 0.5:
raise AssemblyRefused("assembly.collision", "the blocks overlap at any edge length")
lattice = unit_rows * edge_length
if net.dimension == 2:
lattice[2] = np.array([0.0, 0.0, 1.0])
symbols: list[str] = []
points: list[_Points] = []
bonds: list[tuple[int, int, float]] = []
placements: list[dict[str, Any]] = []
offsets: dict[str, int] = {}
representative: dict[str, int] = {}
for v in vertices:
block, where = blocks[v], placed[v]
position = np.array(net.vertices[v]) @ lattice
offsets[v] = len(symbols)
moved = (block.positions - where.centre) @ where.rotation.T + position
symbols += block.symbols
points += list(moved)
bonds += [(i + offsets[v], j + offsets[v], o) for i, j, o in block.bonds]
nearest = int(np.argmin(np.linalg.norm(moved - position, axis=1)))
representative[v] = offsets[v] + nearest
translation = position - where.rotation @ where.centre
placements.append(
{
"block": block.name,
"vertex": v,
"rotation": _round(where.rotation, 9),
"translation_angstrom": _round(translation),
"ports": {
f"{edge}:{end}": block.points[k].label for (edge, end), k in where.ports.items()
},
"direction_misfit_deg": {
block.points[k].label: round(where.angles[k], 3)
for k in range(len(where.angles))
},
}
)
joins: list[dict[str, Any]] = []
join_pairs: list[tuple[int, int, Image, str, str]] = []
for edge in net.edges:
tail_block, head_block = blocks[edge.tail], blocks[edge.head]
tail_atom = (
offsets[edge.tail]
+ tail_block.points[placed[edge.tail].ports[(edge.id, "tail")]].anchor
)
head_atom = (
offsets[edge.head]
+ head_block.points[placed[edge.head].ports[(edge.id, "head")]].anchor
)
shift = np.array(edge.image, dtype=float) @ lattice
tail_xyz = points[tail_atom]
head_xyz = points[head_atom] + shift
span = (
np.array(net.vertices[edge.head])
+ np.array(edge.image, dtype=float)
- np.array(net.vertices[edge.tail])
) @ lattice
d = span / np.linalg.norm(span)
if linker is None:
bonds.append((tail_atom, head_atom, 1.0))
join_pairs.append((tail_atom, head_atom, edge.image, edge.id, "direct"))
continue
reference = _rotate_about(_reference(d, net.dimension), d, recipe.linker_rotation)
frame = np.array([d, reference, np.cross(d, reference)])
middle = (tail_xyz + head_xyz) / 2
start = len(symbols)
lb = linker.block
symbols += lb.symbols
points += list(linker.local @ frame + middle)
bonds += [(i + start, j + start, o) for i, j, o in lb.bonds]
first_atom = start + lb.points[linker.first].anchor
second_atom = start + lb.points[linker.second].anchor
bonds.append((tail_atom, first_atom, 1.0))
bonds.append((second_atom, head_atom, 1.0))
join_pairs.append((tail_atom, first_atom, (0, 0, 0), edge.id, "tail"))
join_pairs.append((second_atom, head_atom, edge.image, edge.id, "head"))
placements.append(
{
"block": "linker",
"edge": edge.id,
"rotation": _round(frame.T, 9),
"translation_angstrom": _round(middle),
"toward_tail": lb.points[linker.first].label,
"toward_head": lb.points[linker.second].label,
"rotation_about_edge_deg": recipe.linker_rotation,
}
)
cartesian = np.array(points)
pbc: tuple[bool, bool, bool] = (True, True, net.dimension == 3)
if net.dimension == 2:
z = cartesian[:, 2]
height = float(z.max() - z.min()) + recipe.vacuum
cartesian[:, 2] += recipe.vacuum / 2 - float(z.min())
lattice[2] = np.array([0.0, 0.0, height])
diagnostics: list[dict[str, Any]] = []
# Closure: every join as a bond of the covalent-radius sum.
for i, j, image, edge_id, end in join_pairs:
shift = np.array(image, dtype=float) @ lattice
distance = float(np.linalg.norm(cartesian[j] + shift - cartesian[i]))
target = _covalent(symbols[i]) + _covalent(symbols[j])
deviation = distance - target
joins.append(
{
"edge": edge_id,
"end": end,
"atoms": [i, j],
"distance_angstrom": round(distance, 4),
"target_angstrom": round(target, 4),
"deviation_angstrom": round(deviation, 4),
}
)
if abs(deviation) > recipe.closure_tolerance:
raise AssemblyRefused(
"assembly.closure",
f"edge {edge_id} ({end}) closes at {distance:.2f} angstrom against a "
f"{target:.2f} angstrom bond (tolerance {recipe.closure_tolerance:g}); the "
"blocks do not fit this net at one edge length",
)
if abs(deviation) > 0.05:
diagnostics.append(
{
"code": "assembly.bond_strain",
"severity": "warning",
"message": f"edge {edge_id} ({end}) bond is {deviation:+.2f} angstrom off "
f"the covalent-radius sum",
}
)
_collisions(cartesian, lattice, pbc, symbols, bonds, recipe.min_distance)
structure = _structure(
recipe.identifier,
lattice,
pbc,
symbols,
cartesian,
bonds,
cell_setting="primitive",
provenance={},
)
ids = [s.id for s in structure.sites]
for join in joins:
join["sites"] = [ids[k] for k in join.pop("atoms")]
topology = _topology_edges(net, cartesian, lattice, pbc, representative, ids, linker)
node_points = sum(len(net.directions(v)) for v in vertices)
expected_connections = node_points if linker else node_points // 2
expected_atoms = sum(len(blocks[v].symbols) for v in vertices) + (
len(net.edges) * len(linker.block.symbols) if linker else 0
)
markers = sum(len(blocks[v].points) for v in vertices) + (2 * len(net.edges) if linker else 0)
counts = {
"vertices": len(vertices),
"edges": len(net.edges),
"expected_connections": expected_connections,
"actual_connections": len(joins),
"expected_atoms": expected_atoms,
"actual_atoms": len(structure.sites),
"markers_removed": markers,
"markers_in_structure": 0,
"unmapped_connection_points": markers - 2 * len(joins),
"topology_edges": len(topology),
"chemical_bonds": len(structure.bonds),
}
if (
counts["expected_connections"] != counts["actual_connections"]
or (counts["expected_atoms"] != counts["actual_atoms"])
or counts["unmapped_connection_points"] != 0
):
raise AssemblyRefused(
"assembly.count_mismatch",
f"expected {expected_connections} connections and {expected_atoms} atoms, made "
f"{len(joins)} and {len(structure.sites)}",
)
spread = max(needs) - min(needs)
if spread > 0.05:
diagnostics.append(
{
"code": "assembly.edge_spread",
"severity": "warning",
"message": f"edges need lengths {min(needs):.2f}-{max(needs):.2f} angstrom; "
"the longest is used, so shorter ones carry stretched bonds",
}
)
notes = [
*node.notes,
*(second.notes if second else []),
*(linker.block.notes if linker else []),
]
assembly = {
"version": ASSEMBLY_VERSION,
"net": net.describe(),
"assignment": assignment,
"blocks": {
b.name: b.describe()
for b in [node, *([second] if second else []), *([linker.block] if linker else [])]
},
"placements": placements,
"joins": joins,
"counts": counts,
"stoichiometry": {
"cell": _hill(Counter(symbols)),
"vertex_blocks": {v: blocks[v].formula() for v in vertices},
"linkers_per_vertex": (len(net.edges) / len(vertices)) if linker else 0,
},
"edge_angstrom": round(edge_length, 6),
"edge_needs_angstrom": [round(x, 6) for x in needs],
"diagnostics": diagnostics,
"gated_extensions": list(GATED_EXTENSIONS),
}
provenance = _provenance(
"reticular",
recipe,
net=net.name,
assembly=assembly,
warnings=notes,
)
return structure.model_copy(
update={"bonds": [*structure.bonds, *topology], "provenance": provenance}
)
def _collisions(
cartesian: _Points,
lattice: _Points,
pbc: tuple[bool, bool, bool],
symbols: list[str],
bonds: list[tuple[int, int, float]],
minimum: float,
) -> None:
from vibesketcher.chem.periodic_geometry import neighbour_pairs
radii = {s: _covalent(s) for s in set(symbols)}
cutoff = max(minimum, 0.75 * 2 * max(radii.values()))
bonded = {(min(i, j), max(i, j)) for i, j, _ in bonds}
clashes = []
for i, j, _, distance in neighbour_pairs(cartesian, lattice, pbc, cutoff):
limit = max(minimum, 0.75 * (radii[symbols[i]] + radii[symbols[j]]))
if distance < limit and (min(i, j), max(i, j)) not in bonded:
clashes.append((i, j, distance))
if clashes:
i, j, distance = clashes[0]
raise AssemblyRefused(
"assembly.collision",
f"{len(clashes)} non-bonded atom pair(s) overlap (atoms {i + 1} {symbols[i]} and "
f"{j + 1} {symbols[j]} at {distance:.2f} angstrom); try linker_rotation or a "
"different block",
)
def _wrap_shift(fractional: _Points, pbc: tuple[bool, bool, bool]) -> NDArray[np.int64]:
"""The integer cell each site was moved out of by ``_structure``'s wrapping."""
shift = np.zeros_like(fractional)
for axis in range(3):
if pbc[axis]:
floor = np.floor(fractional[:, axis])
rest = fractional[:, axis] - floor
shift[:, axis] = floor + np.where(rest >= 1 - 1e-12, 1, 0)
return shift.astype(np.int64)
def _topology_edges(
net: Net,
cartesian: _Points,
lattice: _Points,
pbc: tuple[bool, bool, bool],
representative: dict[str, int],
ids: list[str],
linker: _Linker | None,
) -> list[PeriodicBond]:
"""One ``topology`` edge per net edge between the vertex blocks' central sites."""
shift = _wrap_shift(cartesian @ np.linalg.inv(lattice), pbc)
edges = []
for edge in net.edges:
a, b = representative[edge.tail], representative[edge.head]
image = np.array(edge.image) + shift[b] - shift[a]
edges.append(
PeriodicBond(
a=ids[a],
b=ids[b],
image=(int(image[0]), int(image[1]), int(image[2])),
kind="topology",
order=1,
rule=f"net {net.name} edge {edge.id}" + ("; linker" if linker else "; direct"),
)
)
return edges
# --- preview and writer guard -------------------------------------------------------------
[docs]
def preview(recipe: ReticularRecipe, document: Document | None = None) -> dict[str, Any]:
"""Build without storing: the structure and its assembly record, or the refusal."""
try:
structure = build_reticular(recipe, document)
except AssemblyRefused 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,
"assembly": builder["assembly"],
"warnings": builder.get("warnings", []),
"structure": structure.model_dump(mode="json", exclude_none=True),
}
[docs]
def assembly_refusals(structure: PeriodicStructure) -> list[str]:
"""Why a writer must not export this structure's atoms; empty when it may.
A reticular structure's sites must hold no connection markers and leave no
connection point unmapped. The record is checked rather than trusted to
be absent: a structure that claims a reticular build without the record
is refused too.
"""
builder = structure.provenance.get("builder")
if not isinstance(builder, dict) or builder.get("kind") != "reticular":
return []
assembly = builder.get("assembly")
counts = assembly.get("counts") if isinstance(assembly, dict) else None
if not isinstance(counts, dict):
return ["the reticular structure has no assembly record; rebuild it"]
reasons = []
if counts.get("markers_in_structure") != 0:
reasons.append("connection markers would be written as atoms")
if counts.get("unmapped_connection_points") != 0:
reasons.append(
f"{counts.get('unmapped_connection_points')} connection point(s) are not joined"
)
return reasons