vibe-sketcherDocumentation

Source code for vibesketcher.document.cnt_junctions

"""Explicit CNT-linker-metal junction models (#240).

A junction is assembled from three explicitly chosen parts by explicit graph
and geometry edits; nothing is perceived or guessed:

* a finite single-walled carbon nanotube segment, hydrogen-capped at both
  rims, with the attachment carbon chosen by index: ``end_on`` takes a rim
  carbon of the open lower end (its free valence goes to the linker instead of
  a hydrogen cap), ``sidewall`` takes a wall carbon of the central period and
  converts it from sp2 to sp3 (its three tube bonds become single bonds; the
  edit is recorded);
* a linker given as SMILES with two connection markers, ``[*:1]`` towards the
  tube and ``[*:2]`` towards the metal, embedded with RDKit (fixed seed) and
  placed by the marker vectors (the connection-point convention of #202);
* a metal slab cut from the Cu or Au template (#190/#232) with one surface site
  chosen explicitly: ``top``, ``bridge`` (``short``/``long`` on fcc(110)) or
  ``hollow`` (``fcc``/``hcp`` on fcc(111), four-fold on (100) and (110)).

Every bond the assembly adds is listed with its rationale. The structure is
an unrelaxed construction: it is not a relaxed geometry, a binding energy, a
conductance or transport result, nor a validated atomistic junction.

Source reconstruction (primary acceptance source)
    C. P. Nawarathne, A. Hoque, G. R. Dangel and N. T. Alvarez, Nanoscale Adv.
    6, 428 (2024), doi:10.1039/d3na00500c, main text section 2.2 and Tables
    1-2 (the ESI is not in the literature library, so nothing here comes from
    it). The paper states: open-ended semiconducting (8,0) SWCNTs 15 angstrom
    long carrying COOH groups; an aminophenyl linker grafted on Cu from the
    p-phenylenediamine-derived diazonium salt; CNT attachment by amide
    formation between the CNT carboxyl and the linker amine, releasing water;
    the aminophenyl para carbon bonded to Cu(100), (110) or (111). From top or
    hollow ("hole") starting sites the optimised Cu-C geometry is a bridge
    (two Cu-C bonds) on every facet except Cu(111) top, which stays a single
    Cu-C bond (Table 1). The Table 1 Cu-C distances of the final geometries are
    used as placement distances below and nothing else is taken from the
    paper's optimised structures. Sidewall bonding of carboxylated aligned CNTs
    to aminophenyl-grafted Cu and Au (C. P. Nawarathne et al., ACS Appl. Nano
    Mater. 6, 22001 (2023), doi:10.1021/acsanm.3c04137) and to Au films (ACS
    Appl. Mater. Interfaces (2025), doi:10.1021/acsami.4c19859) is reported
    experimentally, with the same amide chemistry and no atomistic model; any
    Au-C or hollow-site distance is therefore illustrative (the sum of RDKit
    covalent radii, Cordero et al., Dalton Trans. 2008, 2832) and labelled so.

Geometry
    Surface sites are the points above the top layer equidistant from one
    (top), two (bridge), three (hollow, fcc(111)) or four (hollow, fcc(100)
    and (110)) top-layer atoms; an fcc(111) hollow is hcp when a second-layer
    atom lies beneath it and fcc otherwise. The bonded linker carbon sits at
    height sqrt(d^2 - rho^2) above the site, where d is the metal-carbon
    distance and rho the site's in-plane radius; d <= rho is refused. Vector
    alignment uses Rodrigues rotations; the tube's rotation about the
    linker-tube bond is the 5-degree grid value with the largest closest
    contact (smallest angle on ties), or the stated ``cnt_rotation_deg``.
"""

from __future__ import annotations

import itertools
import math
from collections import Counter
from typing import 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, neighbour_pairs
from vibesketcher.chem.periodic_geometry import _structure as _geometry_structure
from vibesketcher.document.model import Chirality, Document, PeriodicStructure
from vibesketcher.elements import ATOMIC_NUMBER
from vibesketcher.limits import MAX_ATOMS

__all__ = [
    "DEFAULT_LINKER",
    "NOT_CLAIMED",
    "SOURCE",
    "CntJunctionRecipe",
    "JunctionRefused",
    "attachment_candidates",
    "build_cnt_junction",
    "preview",
    "surface_sites",
]

_ID = Field(pattern=r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")
_Points = NDArray[np.float64]

#: The amide-aminophenyl linker of the source: CNT-C(=O)-NH-C6H4-metal.
DEFAULT_LINKER = "[*:1]C(=O)Nc1ccc([*:2])cc1"

#: Metal and Miller index pairs this builder places sites on.
FACETS: dict[tuple[str, tuple[int, int, int]], str] = {
    ("Cu", (1, 0, 0)): "Cu(100)",
    ("Cu", (1, 1, 0)): "Cu(110)",
    ("Cu", (1, 1, 1)): "Cu(111)",
    ("Au", (1, 1, 1)): "Au(111)",
}
_TEMPLATE = {"Cu": "cu", "Au": "au"}

SOURCE: dict[str, Any] = {
    "doi": "10.1039/d3na00500c",
    "key": "nawarathne2024creating",
    "citation": "C. P. Nawarathne, A. Hoque, G. R. Dangel and N. T. Alvarez, "
    "Nanoscale Adv. 6, 428-442 (2024)",
    "sections": ["2.2 Computational details", "3 Results, Table 1", "Table 2"],
    "esi": "not in the literature library; no ESI value is used",
    "stated": [
        "open-ended semiconducting (8,0) SWCNT, 15 angstrom long, carrying COOH",
        "aminophenyl linker grafted on Cu from the p-phenylenediamine diazonium salt",
        "amide formation CNT-COOH + H2N-C6H4-Cu -> CNT-C(=O)NH-C6H4-Cu + H2O",
        "para carbon of the aminophenyl bonded to Cu(100), Cu(110) or Cu(111)",
        "top and hollow starting sites optimise to bridge (two Cu-C bonds), except "
        "Cu(111) top, which keeps one Cu-C bond",
        "PBE/PAW periodic slabs (Quantum ESPRESSO, 50 Ry) and a B3PW91 Cu-cluster model",
    ],
    "extended_by": [
        {
            "doi": "10.1021/acsanm.3c04137",
            "key": "nawarathne2023sidewall",
            "use": "sidewall amide bonding of carboxylated aligned CNTs to aminophenyl-"
            "grafted Cu, Au and other metals (experimental; no atomistic model)",
        },
        {
            "doi": "10.1021/acsami.4c19859",
            "key": "nawarathne2025chemically",
            "use": "VACNT-linker-Au bonding from aminobenzene diazonium on Au films "
            "(experimental; no atomistic model)",
        },
    ],
}

#: Table 1 of the source: Cu-C distance (angstrom) of the optimised geometry for
#: each final site, keyed by the facet; the value of the most stable starting
#: configuration ending in that site (lowest E_total).
_TABLE1: dict[tuple[str, str], dict[str, Any]] = {
    ("Cu(100)", "bridge"): {"distance": 2.08, "row": "100 hole -> bridge, 2 Cu-C bonds"},
    ("Cu(110)", "bridge"): {"distance": 2.05, "row": "110 top -> bridge, 2 Cu-C bonds"},
    ("Cu(111)", "bridge"): {"distance": 2.02, "row": "111 hole -> bridge, 2 Cu-C bonds"},
    ("Cu(111)", "top"): {"distance": 1.97, "row": "111 top -> top, 1 Cu-C bond"},
}

#: What a junction model is not; carried in every record.
NOT_CLAIMED = [
    "relaxation (positions, linker conformation, metal-carbon distance or cell)",
    "the stable or lowest-energy site (the source reports hollow and most top starts "
    "relaxing to bridge)",
    "binding, adsorption or reaction energy",
    "conductance, interface resistance or electron transport",
    "a validated atomistic CNT-metal junction",
]

STATUS = (
    "unrelaxed construction: explicit graph and geometry edits only; not a conductance "
    "or transport result and not a validated atomistic junction"
)

#: Typical single-bond length between the tube carbon and the linker atom (angstrom);
#: illustrative, not from the source.
_TUBE_LINKER_BOND = 1.50
_CH = 1.09


[docs] class JunctionRefused(BuildRefused): """A junction the builder will not construct; ``code`` names the rule.""" def __init__(self, code: str, message: str) -> None: super().__init__(f"{code}: {message}") self.code = code
[docs] class CntJunctionRecipe(BaseModel): """A CNT-linker-metal junction; every choice explicit (#240).""" model_config = ConfigDict(extra="forbid") kind: Literal["cnt_junction"] = "cnt_junction" identifier: str = _ID # --- metal slab and site --- metal: Literal["Cu", "Au"] miller: tuple[int, int, int] layers: int = Field(default=3, ge=2, le=12) repeat: tuple[int, int] = (6, 6) vacuum: float = Field(default=15.0, ge=5, le=200, allow_inf_nan=False) site: Literal["top", "bridge", "hollow"] #: short/long bridge on fcc(110); fcc/hcp hollow on fcc(111); none elsewhere. site_variant: Literal["short", "long", "fcc", "hcp"] | None = None #: The top-layer reference atom (a slab site id); None: nearest the cell centre. surface_atom: str | None = None #: Which of the equivalent sites around the reference atom (sorted by azimuth). site_index: int = Field(default=0, ge=0, le=11) #: Metal-carbon placement distance (angstrom); None: Table 1 or illustrative. metal_carbon_distance: float | None = Field(default=None, ge=1.5, le=3.0) # --- tube --- n: int = Field(default=8, ge=3, le=20) m: int = Field(default=0, ge=0, le=20) periods: int = Field(default=4, ge=1, le=12) attachment: Literal["end_on", "sidewall"] #: Index into :func:`attachment_candidates` for this tube and attachment mode. attachment_carbon: int = Field(ge=0) cnt_rotation_deg: float | None = Field(default=None, ge=-360, le=360, allow_inf_nan=False) # --- linker --- linker_smiles: str = Field(default=DEFAULT_LINKER, min_length=3, max_length=500) linker_rotation_deg: float = Field(default=0.0, ge=-360, le=360, allow_inf_nan=False) tube_linker_distance: float = Field(default=_TUBE_LINKER_BOND, ge=1.2, le=2.0) # --- boundary, checks and electrons --- boundary: Literal["slab_2d", "slab_3d", "cluster"] = "slab_2d" clash_fraction: float = Field(default=0.75, ge=0.3, le=1.0) min_image_separation: float = Field(default=3.0, ge=1.0, le=50.0) max_atoms: int = Field(default=1500, ge=10, le=MAX_ATOMS) charge: int | None = None multiplicity: int | None = Field(default=None, ge=1) charge_spin_source: str | None = Field(default=None, max_length=500) @model_validator(mode="after") def _indices(self) -> Self: if self.m > self.n: raise ValueError(f"({self.n},{self.m}): write the indices with m <= n") return self
[docs] def facet(self) -> str: key = (self.metal, tuple(self.miller)) if key not in FACETS: supported = ", ".join(FACETS.values()) raise JunctionRefused( "junction.facet", f"{self.metal}{tuple(self.miller)} has no site model here; supported: {supported}", ) return FACETS[key]
# --- vector helpers --- def _unit(v: _Points) -> _Points: norm = float(np.linalg.norm(v)) if norm < 1e-12: raise JunctionRefused("junction.geometry", "a direction vector vanished") return v / norm def _rotation_between(a: _Points, b: _Points) -> _Points: """The rotation taking unit vector a onto unit vector b (Rodrigues).""" a, b = _unit(a), _unit(b) v = np.cross(a, b) c = float(a @ b) if c > 1 - 1e-12: return np.eye(3) if c < -1 + 1e-12: axis = _unit(np.cross(a, [1.0, 0, 0] if abs(a[0]) < 0.9 else [0, 1.0, 0])) return _about(axis, math.pi) k = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) rotation: _Points = np.eye(3) + k + k @ k / (1 + c) return rotation def _about(axis: _Points, angle: float) -> _Points: x, y, z = _unit(axis) k = np.array([[0, -z, y], [z, 0, -x], [-y, x, 0]]) rotation: _Points = np.eye(3) + math.sin(angle) * k + (1 - math.cos(angle)) * k @ k return rotation def _azimuth(v: _Points) -> float: return round(math.degrees(math.atan2(float(v[1]), float(v[0]))) % 360.0, 3) % 360.0 # --- metal slab and sites --- def _slab(recipe: CntJunctionRecipe) -> PeriodicStructure: from vibesketcher.document.solid_build import SlabRecipe, _template_slab slab = SlabRecipe( identifier=f"{recipe.identifier}-slab", template=_TEMPLATE[recipe.metal], miller=recipe.miller, layers=recipe.layers, layer_unit="plane", repeat=list(recipe.repeat), vacuum=recipe.vacuum, periodicity="2d", ) return _template_slab(slab) def _surface(slab: PeriodicStructure) -> dict[str, Any]: from vibesketcher.document import crystal lattice = crystal.lattice_rows(slab) xyz = crystal.cartesian(slab) z_top = float(xyz[:, 2].max()) top = [i for i in range(len(xyz)) if xyz[i, 2] > z_top - 0.3] below = sorted({round(float(z), 2) for z in xyz[:, 2] if z < z_top - 0.3}, reverse=True) second = [i for i in range(len(xyz)) if below and abs(xyz[i, 2] - below[0]) < 0.3] images = [(i, j) for i in (-1, 0, 1) for j in (-1, 0, 1)] points: list[tuple[int, tuple[int, int], _Points]] = [] for index in top: for image in images: shift = image[0] * lattice[0] + image[1] * lattice[1] points.append((index, image, xyz[index] + shift)) under = np.array( [xyz[i, :2] + a * lattice[0, :2] + b * lattice[1, :2] for i in second for a, b in images] ) return { "lattice": lattice, "xyz": xyz, "z_top": z_top, "top": top, "points": points, "under": under, } def _reference(slab: PeriodicStructure, surface: dict[str, Any], atom: str | None) -> int: ids = [s.id for s in slab.sites] if atom is not None: if atom not in ids or ids.index(atom) not in surface["top"]: raise JunctionRefused( "junction.surface_atom", f"{atom!r} is not a top-layer atom of the slab" ) return ids.index(atom) lattice = surface["lattice"] centre = (lattice[0] + lattice[1]) / 2 top: list[int] = surface["top"] xyz = surface["xyz"] return min(top, key=lambda i: (round(float(np.linalg.norm(xyz[i, :2] - centre[:2])), 6), i)) def _sites_around( slab: PeriodicStructure, surface: dict[str, Any], reference: int, facet: str ) -> list[dict[str, Any]]: """Every top, bridge and hollow point whose coordinating atoms include ``reference``.""" points = surface["points"] xy = np.array([p[2][:2] for p in points]) r0 = surface["xyz"][reference, :2] distances = np.linalg.norm(xy - r0, axis=1) d1 = float(np.min(distances[distances > 1e-6])) near = [k for k in range(len(points)) if 1e-6 < distances[k] < 1.8 * d1] home = next(k for k, p in enumerate(points) if p[0] == reference and p[1] == (0, 0)) candidates: list[_Points] = [r0] candidates += [(r0 + xy[k]) / 2 for k in near] candidates += [(r0 + xy[a] + xy[b]) / 3 for a, b in itertools.combinations(near, 2)] found: dict[tuple[float, float], dict[str, Any]] = {} for point in candidates: d = np.linalg.norm(xy - point, axis=1) rho = float(d.min()) shell = [k for k in range(len(points)) if d[k] < rho + 0.02] if home not in shell or len(shell) > 4 or (len(shell) == 1 and rho > 1e-6): continue if len(shell) > 1 and float(np.linalg.norm(xy[shell].mean(axis=0) - point)) > 0.05: continue key = (round(float(point[0]), 3), round(float(point[1]), 3)) if key in found: continue count = len(shell) kind = {1: "top", 2: "bridge"}.get(count, "hollow") variant: str | None = None if kind == "bridge" and facet.endswith("(110)"): pair = float(np.linalg.norm(xy[shell[0]] - xy[shell[1]])) variant = "short" if pair < 1.2 * d1 else "long" elif kind == "bridge": pair = float(np.linalg.norm(xy[shell[0]] - xy[shell[1]])) if pair > 1.2 * d1: continue if kind == "hollow" and count == 3: beneath = surface["under"] covered = len(beneath) and float(np.min(np.linalg.norm(beneath - point, axis=1))) < 0.3 variant = "hcp" if covered else "fcc" ids = [slab.sites[points[k][0]].id for k in shell] images = [list(points[k][1]) for k in shell] label = { "top": f"{facet} top", "bridge": f"{facet} {variant + ' ' if variant else ''}bridge", "hollow": f"{facet} {variant or 'four-fold'} hollow", }[kind] found[key] = { "kind": kind, "variant": variant, "label": label, "coordination": count, "metal_atoms": ids, "metal_images": images, "point_xy": [float(point[0]), float(point[1])], "radius_angstrom": round(rho, 6), "azimuth_deg": _azimuth(np.append(point - r0, 0.0)) if kind != "top" else 0.0, "_shell": shell, } order = {"top": 0, "bridge": 1, "hollow": 2} ranked = sorted( found.values(), key=lambda s: (order[s["kind"]], s["variant"] or "", s["azimuth_deg"]) ) counters: Counter[tuple[str, str | None]] = Counter() for entry in ranked: entry["index"] = counters[(entry["kind"], entry["variant"])] counters[(entry["kind"], entry["variant"])] += 1 return ranked def _distance(recipe: CntJunctionRecipe, facet: str, site: dict[str, Any]) -> dict[str, Any]: from vibesketcher.document.periodic_graph import covalent_radius if recipe.metal_carbon_distance is not None: return {"value": recipe.metal_carbon_distance, "source": "stated in the recipe"} row = _TABLE1.get((facet, site["kind"])) if row is not None: return { "value": row["distance"], "source": f"{SOURCE['doi']} Table 1 ({row['row']}); the optimised distance, " "used here only as a placement distance", } value = round(covalent_radius(recipe.metal) + covalent_radius("C"), 3) reason = ( "the source reports this starting site relaxing to bridge" if facet.startswith("Cu") else "no source reports an Au-C junction geometry" ) return { "value": value, "source": f"illustrative: sum of RDKit covalent radii (Cordero et al. 2008); {reason}", "illustrative": True, } def _validate_variant(recipe: CntJunctionRecipe, facet: str) -> None: wanted = recipe.site_variant if recipe.site == "bridge" and facet.endswith("(110)"): if wanted not in ("short", "long"): raise JunctionRefused( "junction.site_variant", f"a {facet} bridge is short (along [1-10]) or long (along [001]); state " "site_variant", ) return if recipe.site == "hollow" and facet.endswith("(111)"): if wanted not in ("fcc", "hcp"): raise JunctionRefused( "junction.site_variant", f"a {facet} hollow is fcc or hcp (second-layer atom beneath); state site_variant", ) return if wanted is not None: raise JunctionRefused( "junction.site_variant", f"a {facet} {recipe.site} site takes no site_variant" )
[docs] def surface_sites( metal: str, miller: tuple[int, int, int], *, layers: int = 3, repeat: tuple[int, int] = (6, 6), surface_atom: str | None = None, ) -> dict[str, Any]: """The explicit site catalogue around one top-layer atom of a template slab.""" recipe = CntJunctionRecipe.model_validate( { "identifier": "sites", "metal": metal, "miller": miller, "layers": layers, "repeat": repeat, "site": "top", "attachment": "end_on", "attachment_carbon": 0, "surface_atom": surface_atom, } ) facet = recipe.facet() slab = _slab(recipe) surface = _surface(slab) reference = _reference(slab, surface, surface_atom) sites = _sites_around(slab, surface, reference, facet) for site in sites: site.pop("_shell") return { "facet": facet, "surface_atom": slab.sites[reference].id, "top_layer_atoms": len(surface["top"]), "sites": sites, "source_final_sites": { f"{f} {k}": v["distance"] for (f, k), v in _TABLE1.items() if f == facet }, "note": "sites are geometric; the source (doi:10.1039/d3na00500c, Table 1) reports top " "and hollow starts relaxing to bridge except Cu(111) top", }
# --- tube --- def _tube(recipe: CntJunctionRecipe) -> tuple[_Points, list[tuple[int, int]]]: from vibesketcher.chem import nanostructures as nano chirality = Chirality(n=recipe.n, m=recipe.m) if nano.diameter_nm(chirality) < nano._MIN_DIAMETER_NM: raise JunctionRefused( "junction.tube", f"({recipe.n},{recipe.m}) is thinner than the generator allows" ) points = nano._wall(chirality, recipe.periods) pairs = nano._bonds_within(points) points, pairs = nano._prune(points, pairs) return points, pairs def _degrees(count: int, pairs: list[tuple[int, int]]) -> list[list[int]]: around: list[list[int]] = [[] for _ in range(count)] for i, j in pairs: around[i].append(j) around[j].append(i) return around def _candidates(points: _Points, around: list[list[int]], attachment: str) -> list[int]: z = points[:, 2] middle = (float(z.min()) + float(z.max())) / 2 if attachment == "end_on": chosen = [i for i in range(len(points)) if len(around[i]) == 2 and z[i] < middle] return sorted(chosen, key=lambda i: (_azimuth(points[i]), i)) span = float(z.max() - z.min()) chosen = [ i for i in range(len(points)) if len(around[i]) == 3 and abs(z[i] - middle) <= max(span / 6, 1.5) ] return sorted(chosen, key=lambda i: (round(float(z[i]), 3), _azimuth(points[i]), i))
[docs] def attachment_candidates( n: int = 8, m: int = 0, periods: int = 4, attachment: str = "end_on" ) -> dict[str, Any]: """The explicit list ``attachment_carbon`` indexes, in the tube's own frame.""" recipe = CntJunctionRecipe.model_validate( { "identifier": "tube", "metal": "Cu", "miller": (1, 1, 1), "site": "top", "n": n, "m": m, "periods": periods, "attachment": attachment, "attachment_carbon": 0, } ) points, pairs = _tube(recipe) around = _degrees(len(points), pairs) chosen = _candidates(points, around, recipe.attachment) return { "tube": f"({n},{m})", "periods": periods, "attachment": attachment, "carbons": len(points), "candidates": [ { "index": k, "neighbours": len(around[i]), "z_angstrom": round(float(points[i, 2]), 4), "azimuth_deg": _azimuth(points[i]), } for k, i in enumerate(chosen) ], "rule": "end_on: two-coordinate rim carbons of the lower open end by azimuth; " "sidewall: three-coordinate carbons near the middle by height, then azimuth", }
# --- assembly --- def _clashes( cartesian: _Points, lattice: _Points, pbc: tuple[bool, bool, bool], symbols: list[str], bonded: set[tuple[int, int]], fraction: float, ) -> list[tuple[int, int, float, float]]: from vibesketcher.document.periodic_graph import covalent_radius radii = {s: covalent_radius(s) for s in set(symbols)} cutoff = 2 * max(radii.values()) * fraction found = [] for i, j, _, d in neighbour_pairs(cartesian, lattice, pbc, cutoff): limit = fraction * (radii[symbols[i]] + radii[symbols[j]]) if d < limit and (min(i, j), max(i, j)) not in bonded: found.append((i, j, d, limit)) return found def _image_separation(cartesian: _Points, lattice: _Points, rows: list[int]) -> float: """Closest distance between the non-slab atoms and their in-plane images.""" block = cartesian[rows] best = math.inf for a, b in ((1, 0), (0, 1), (1, 1), (1, -1)): shift = a * lattice[0] + b * lattice[1] d = np.linalg.norm(block[:, None, :] - (block + shift)[None, :, :], axis=2) best = min(best, float(d.min())) return best def _electrons(recipe: CntJunctionRecipe, symbols: list[str]) -> dict[str, Any]: missing = [ name for name in ("charge", "multiplicity", "charge_spin_source") if getattr(recipe, name) in (None, "") ] if missing: raise JunctionRefused( "junction.charge_spin", f"state {', '.join(missing)}: a junction's charge, multiplicity and their " "provenance are never defaulted", ) assert recipe.charge is not None and recipe.multiplicity is not None electrons = sum(ATOMIC_NUMBER[s] for s in symbols) - recipe.charge if electrons < 0 or (electrons + recipe.multiplicity) % 2 == 0: raise JunctionRefused( "junction.charge_spin", f"{electrons} electrons cannot have multiplicity {recipe.multiplicity}", ) return { "charge": recipe.charge, "multiplicity": recipe.multiplicity, "electrons": electrons, "source": recipe.charge_spin_source, "note": "stated by the user; not derived, compensated or checked against a calculation", }
[docs] def build_cnt_junction( recipe: CntJunctionRecipe, document: Document | None = None ) -> PeriodicStructure: """Assemble the junction the recipe states, or refuse with a coded reason.""" del document # every part is built from the recipe; the document is not read facet = recipe.facet() if recipe.boundary == "cluster": raise JunctionRefused( "junction.boundary", "a finite metal cluster is not cut in this version (its shape, size and " "termination would have to be stated); use slab_2d or slab_3d, where the tube " "and linker are finite and hydrogen-capped and the slab is periodic in-plane", ) _validate_variant(recipe, facet) # Metal slab and the chosen site. slab = _slab(recipe) surface = _surface(slab) reference = _reference(slab, surface, recipe.surface_atom) sites = [ s for s in _sites_around(slab, surface, reference, facet) if s["kind"] == recipe.site and s["variant"] == recipe.site_variant ] if not sites: raise JunctionRefused( "junction.site", f"no {recipe.site} site with variant {recipe.site_variant} on {facet}" ) if recipe.site_index >= len(sites): raise JunctionRefused( "junction.site_index", f"site_index {recipe.site_index}: the reference atom has {len(sites)} such sites", ) site = sites[recipe.site_index] distance = _distance(recipe, facet, site) d_mc = float(distance["value"]) if d_mc <= site["radius_angstrom"] + 0.1: raise JunctionRefused( "junction.site_height", f"a {d_mc:.3f} angstrom metal-carbon distance cannot reach the " f"{site['radius_angstrom']:.3f} angstrom {site['label']}; state a longer " "metal_carbon_distance or another site", ) height = math.sqrt(d_mc**2 - site["radius_angstrom"] ** 2) anchor_metal = np.array([*site["point_xy"], surface["z_top"] + height]) # Linker from SMILES with two markers. from vibesketcher.chem.reticular import AssemblyRefused, _smiles_block try: block = _smiles_block("linker", recipe.linker_smiles, {"smiles": recipe.linker_smiles}) except AssemblyRefused as error: raise JunctionRefused("junction.linker", str(error)) from None labels = sorted(p.label for p in block.points) if labels != ["*1", "*2"]: raise JunctionRefused( "junction.linker", "the linker needs exactly two markers, [*:1] towards the tube and [*:2] towards " f"the metal; found {labels}", ) to_tube = next(p for p in block.points if p.label == "*1") to_metal = next(p for p in block.points if p.label == "*2") xyz = block.positions - block.positions[to_metal.anchor] rotate = _rotation_between( to_metal.marker - block.positions[to_metal.anchor], np.array([0.0, 0.0, -1.0]) ) xyz = xyz @ rotate.T marker_tube = (to_tube.marker - block.positions[to_metal.anchor]) @ rotate.T heavy = xyz[[k for k, s in enumerate(block.symbols) if s != "H"]] normal = np.linalg.svd(heavy - heavy.mean(axis=0))[2][2] spin = -math.atan2(float(normal[0]), float(normal[1])) if math.hypot(*normal[:2]) > 1e-3 else 0 twist = _about(np.array([0.0, 0.0, 1.0]), spin + math.radians(recipe.linker_rotation_deg)) xyz = xyz @ twist.T + anchor_metal marker_tube = marker_tube @ twist.T + anchor_metal linker_anchor = xyz[to_tube.anchor] u1 = _unit(marker_tube - linker_anchor) # Tube, capped, oriented on the linker. tube_xyz, pairs = _tube(recipe) around = _degrees(len(tube_xyz), pairs) candidates = _candidates(tube_xyz, around, recipe.attachment) if recipe.attachment_carbon >= len(candidates): raise JunctionRefused( "junction.attachment_carbon", f"attachment_carbon {recipe.attachment_carbon}: the ({recipe.n},{recipe.m}) tube " f"has {len(candidates)} {recipe.attachment} candidates (see attachment_candidates)", ) carbon = candidates[recipe.attachment_carbon] rim = [i for i in range(len(tube_xyz)) if len(around[i]) == 2 and i != carbon] caps = [tube_xyz[i] + _CH * _unit(tube_xyz[i] - tube_xyz[around[i]].mean(axis=0)) for i in rim] tube_all = np.vstack([tube_xyz, np.array(caps)]) if caps else tube_xyz outward = _unit(tube_xyz[carbon] - tube_xyz[around[carbon]].mean(axis=0)) align = _rotation_between(outward, -u1) base = (tube_all - tube_xyz[carbon]) @ align.T target = linker_anchor + recipe.tube_linker_distance * u1 lattice = surface["lattice"] slab_xyz = surface["xyz"] shifts = [a * lattice[0] + b * lattice[1] for a in (-1, 0, 1) for b in (-1, 0, 1)] environment = np.vstack([slab_xyz + s for s in shifts] + [np.delete(xyz, to_tube.anchor, 0)]) def placed(angle: float) -> _Points: moved: _Points = base @ _about(u1, math.radians(angle)).T + target return moved def contact(angle: float) -> float: moved = placed(angle) others = np.delete(moved, carbon, 0) return float(np.min(np.linalg.norm(others[:, None] - environment[None], axis=2))) if recipe.cnt_rotation_deg is not None: angle = recipe.cnt_rotation_deg rotation_rule = "stated in the recipe" else: clear = 3.0 def score(a: int) -> tuple[float, float, float, int]: moved = placed(a) images = _image_separation(moved, lattice, list(range(len(moved)))) return (round(min(contact(a), clear), 4), round(min(images, clear), 4), round(float(moved[:, 2].mean()), 3), -a) # fmt: skip angle = max(range(0, 360, 5), key=score) rotation_rule = ( "5-degree grid: closest contact to slab and linker, then to the tube's in-plane " "images (each counted up to 3 angstrom), then the highest tube centroid, then the " "smallest angle" ) tube_placed = placed(float(angle)) # Assemble symbols, positions, roles and bonds. n_slab, n_link, n_tube = len(slab.sites), len(block.symbols), len(tube_xyz) symbols = [s.symbol for s in slab.sites] + block.symbols + ["C"] * n_tube + ["H"] * len(caps) if len(symbols) > recipe.max_atoms: raise JunctionRefused( "junction.atom_budget", f"the junction holds {len(symbols)} atoms, more than max_atoms={recipe.max_atoms}", ) roles = ["metal"] * n_slab + ["linker"] * n_link + ["cnt"] * n_tube + ["cap"] * len(caps) cartesian = np.vstack([slab_xyz, xyz, tube_placed]) o_link, o_tube = n_slab, n_slab + n_link o_cap = o_tube + n_tube tube_carbon = o_tube + carbon linker_metal_atom = o_link + to_metal.anchor linker_tube_atom = o_link + to_tube.anchor sp3 = recipe.attachment == "sidewall" tube_order = {(min(i, j), max(i, j)): 1.5 for i, j in pairs} reordered = [] if sp3: for j in around[carbon]: tube_order[(min(carbon, j), max(carbon, j))] = 1.0 reordered.append(j) bonds: list[tuple[int, int, float]] = [] bonds += [(o_link + i, o_link + j, order) for i, j, order in block.bonds] bonds += [(o_tube + i, o_tube + j, order) for (i, j), order in sorted(tube_order.items())] bonds += [(o_tube + i, o_cap + k, 1.0) for k, i in enumerate(rim)] added: list[tuple[int, int, float, str]] = [ ( tube_carbon, linker_tube_atom, 1.0, "tube carbon to the linker's [*:1] atom: the amide carbonyl from the CNT carboxyl " f"(CNT-COOH + H2N-aryl -> CNT-C(=O)NH-aryl + H2O; {SOURCE['doi']} section 3)" if recipe.linker_smiles == DEFAULT_LINKER else "tube carbon to the linker's [*:1] atom, as stated by the linker SMILES", ) ] metal_ids = site["metal_atoms"] for k in site["_shell"]: index = surface["points"][k][0] added.append( ( index, linker_metal_atom, 1.0, f"{site['label']}: metal-carbon bond to the linker's [*:2] atom (the aryl " f"carbon of the grafted diazonium-derived aminophenyl); placement distance " f"{d_mc:.3f} angstrom ({distance['source']})", ) ) bonds += [(i, j, order) for i, j, order, _ in added] bonded = {(min(i, j), max(i, j)) for i, j, _ in bonds} pbc = (True, True, recipe.boundary == "slab_3d") # Stack along the normal with vacuum, then check images, clashes and electrons. low, high = float(cartesian[:, 2].min()), float(cartesian[:, 2].max()) cartesian[:, 2] += recipe.vacuum / 2 - low lattice = lattice.copy() lattice[2] = [0.0, 0.0, high - low + recipe.vacuum] finite = list(range(o_link, len(symbols))) separation = _image_separation(cartesian, lattice, finite) if separation < recipe.min_image_separation: raise JunctionRefused( "junction.image_separation", f"the finite tube and linker come {separation:.3f} angstrom from their in-plane " f"images (min_image_separation {recipe.min_image_separation}); enlarge repeat", ) clashes = _clashes(cartesian, lattice, pbc, symbols, bonded, recipe.clash_fraction) if clashes: i, j, d, limit = clashes[0] raise JunctionRefused( "junction.clash", f"{len(clashes)} unbonded pair(s) closer than {recipe.clash_fraction} x the " f"covalent radius sum: {roles[i]} {symbols[i]}{i + 1} and {roles[j]} " f"{symbols[j]}{j + 1} at {d:.3f} angstrom (limit {limit:.3f}); change the site, " "rotations or attachment carbon", ) electrons = _electrons(recipe, symbols) counter: Counter[str] = Counter() ids: list[str] = [] for symbol in symbols: counter[symbol] += 1 ids.append(f"{symbol}{counter[symbol]}") local = [*range(n_slab), *range(n_link), *range(n_tube), *range(len(caps))] edits: list[dict[str, Any]] = [ {"op": "add_bond", "a": ids[i], "b": ids[j], "order": order, "rationale": why} for i, j, order, why in added ] if sp3: edits.append( { "op": "rehybridise", "site": ids[tube_carbon], "from": "sp2", "to": "sp3", "set_order": [[ids[tube_carbon], ids[o_tube + j], 1.0] for j in reordered], "rationale": "sidewall attachment: the tube carbon gains a fourth bond, so its " "three tube bonds become single bonds (aromatic 1.5 before)", } ) else: edits.append( { "op": "complete_valence", "site": ids[tube_carbon], "rationale": "end-on attachment: the open-end rim carbon's free valence goes to " "the linker instead of a hydrogen cap", } ) edits.append( { "op": "cap_hydrogen", "bonds": [[ids[o_tube + i], ids[o_cap + k]] for k, i in enumerate(rim)], "rationale": f"every other two-coordinate rim carbon gets one H at {_CH} angstrom " "along the in-surface bisector (finite tube termination)", } ) record = { "status": STATUS, "facet": facet, "site": {k: v for k, v in site.items() if k != "_shell"}, "surface_atom": slab.sites[reference].id, "metal_carbon_distance": distance, "site_height_angstrom": round(height, 6), "linker": { **block.describe(), "smiles": recipe.linker_smiles, "rotation_deg": recipe.linker_rotation_deg, "default": recipe.linker_smiles == DEFAULT_LINKER, }, "tube": { "chirality": [recipe.n, recipe.m], "periods": recipe.periods, "length_angstrom": round(float(np.ptp(tube_xyz[:, 2])), 4), "source_length_angstrom": 15.0, "attachment": recipe.attachment, "attachment_carbon": recipe.attachment_carbon, "attachment_site": ids[tube_carbon], "caps": len(caps), "rotation_deg": float(angle), "rotation_rule": rotation_rule, "tube_linker_distance": { "value": recipe.tube_linker_distance, "source": "stated in the recipe" if recipe.tube_linker_distance != _TUBE_LINKER_BOND else "illustrative typical C-C single bond", }, }, "graph_edits": edits, "metal_metal_bonds": "not authored (perceive them with the periodic graph tools)", "boundary": { "policy": recipe.boundary, "metal": "periodic in-plane slab" + (", padded 3-D cell" if pbc[2] else ""), "tube_and_linker": "finite, hydrogen-capped; sees its in-plane periodic images", "closest_image_angstrom": round(separation, 6), }, "checks": { "clash_fraction": recipe.clash_fraction, "atoms": len(symbols), "max_atoms": recipe.max_atoms, }, "charge_spin": electrons, "source": SOURCE, "not_claimed": NOT_CLAIMED, "site_map": { "columns": ["site", "role", "index_in_part"], "rows": [[ids[k], roles[k], local[k]] for k in range(len(symbols))], }, "stoichiometry": dict(sorted(Counter(symbols).items())), "metal_atoms_bonded": metal_ids, "slab": slab.provenance.get("builder"), } made = _geometry_structure( recipe.identifier, lattice, pbc, symbols, cartesian, bonds, cell_setting="unspecified", provenance=_provenance("cnt_junction", recipe, junction=record), charge=recipe.charge, multiplicity=recipe.multiplicity, labels=ids, ) return made
[docs] def preview(recipe: CntJunctionRecipe, document: Document | None = None) -> dict[str, Any]: """Build without storing: the record and structure, or the coded refusal.""" try: made = build_cnt_junction(recipe, document) except JunctionRefused as error: return {"refused": True, "code": error.code, "reason": str(error)} except ValueError as error: return {"refused": True, "code": "junction.invalid", "reason": str(error)} builder = made.provenance.get("builder") return { "refused": False, "sites": len(made.sites), "bonds": len(made.bonds), "pbc": list(made.pbc), "lattice_angstrom": [list(row) for row in made.lattice_angstrom], "record": builder.get("junction") if isinstance(builder, dict) else None, "structure": made.model_dump(mode="json"), }