vibe-sketcherDocumentation
Source code for vibesketcher.chem.porous_carbon_d
"""The Mackay-Terrones D-type carbon sheet: octagons and hexagons on the D surface (#204).
A. L. Mackay and H. Terrones, Nature 352, 762 (1991), doi:10.1038/352762a0
(library: ``incoming/352762a0.pdf``), cover Schwarz's diamond D surface with a
graphite-like sheet: "8 tetrahedral units per cell, so that there are 768
carbon atoms per face centred cubic unit cell ... each consisting of six
octagons and 40 hexagons". The sheet is made from plane 30-60-90 degree
triangles of the graphite net, "curved so that 60 degree vertices become 45
degree and eight fit together to give an octagon"; they add that "the
triangle can be chosen in several ways". This module builds one choice and
names it.
**The map on the surface.** The D surface contains straight lines. Schwarz's
generating patch is the skew quadrilateral formed by four edges of a regular
tetrahedron, and the surface is the union of its images under 180-degree
rotations about those edges (H. A. Schwarz, Gesammelte Mathematische
Abhandlungen, Springer, Berlin, 1890; not in the library, and the
construction is checked here rather than taken on trust). With tetrahedron
vertices at alternate corners of a unit cube, the first quadrilateral is
``(0,0,0) (1,1,0) (0,1,1) (1,0,1)``. Six quadrilaterals meet at every vertex,
each with a 60-degree corner, so the patches form a {4,6} map. The
translations that keep the two sides of the sheet apart form an fcc lattice
of conventional edge 4 (primitive vectors ``(0,2,2) (2,0,2) (2,2,0)``). The
simple cubic lattice of edge 2, the translations that swap the sides, is
the Pn-3m description of the unoriented surface. A primitive cell has 8
vertices, 24 edges and 12 quadrilaterals: chi = -4, genus 3. That is the
cycle rank of the diamond net ``dia`` (2 vertices and 4 edges per primitive
cell), which the sheet surrounds.
**The decoration.** Each quadrilateral is cut into eight flag triangles
(vertex ``v``, edge midpoint ``m``, centre ``c``). Their angles are 30
degrees at ``v`` (12 flags meet), 45 at ``c`` (8 meet) and 90 at ``m`` (4
meet): Mackay and Terrones' triangle. Each flag is filled with a plane
graphite triangle whose 30-degree corner ``H`` and 60-degree corner ``O``
are hexagon centres ``K`` hexagon spacings apart along an armchair line. The
90-degree corner ``M`` is then a bond midpoint, and all three sides are
mirror lines of graphite. ``TRIANGLE = 2`` gives 2 carbons per flag, so 192
per primitive cell and 768 per conventional cubic cell. That is the paper's
count: 12 octagons (one per quadrilateral centre) and 80 hexagons per
primitive cell, or 6 octagons and 40 hexagons per tetrahedral unit. It is
the only triangle on this armchair line with that count (``K = 1`` gives
the 48-carbon sheet, ``K = 3`` 432). A plane atom is carried into a flag by
its barycentric coordinates in ``(H, O, M)``. Atoms on a side, which is a
mirror line, get the same position from both flags. A bond leaving the
triangle is followed by reflecting the far atom across the side it crosses,
into the neighbouring flag, until it lands inside. Bonds therefore come
from the plane net, not from distances.
**Placement.** The mapped atoms lie on the flat flag triangles. They are
projected onto the D nodal surface
``sin X sin Y sin Z + sin X cos Y cos Z - cos X sin Y cos Z - cos X cos Y sin Z = 0``
with ``X = pi x / 2`` in cube units (H. G. von Schnering and R. Nesper, Z.
Phys. B 83, 407 (1991), doi:10.1007/BF01313411). In this form it contains
every quadrilateral edge. A fixed, deterministic bond-length equalisation
then follows: each step moves every atom along the summed misfit of its
bonds against their mean, then projects back onto the nodal surface,
stopping when the largest relative misfit is below ``EQUALISE_TOLERANCE`` or
after ``EQUALISE_STEPS``. This is a geometric placement on a fixed surface.
It has no angle, bending or pi terms, no fitted potential and no forces from
any energy model, so it is not a relaxation. The cell is then scaled so the
common bond is ``bond_length``. Topology is untouched: the graph comes from
the decoration alone.
The sheet does not divide space into two congruent labyrinths, as T.
Lenosky, X. Gonze, M. Teter and V. Elser note for their D sheet (Nature 355,
333 (1992), doi:10.1038/355333a0; library ``incoming/lenosky1992.pdf``). It
is a carbon net on a nodal approximation of the D surface, not the minimal
surface itself. Their heptagon D sheet (24 heptagons and 80 hexagons per
cell) is a different decoration and is not built here.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
import numpy as np
from numpy.typing import NDArray
__all__ = [
"ATOMS_PER_CELL",
"EQUALISE_STEPS",
"EQUALISE_TOLERANCE",
"LATTICE_UNITS",
"TRIANGLE",
"DSheet",
"d_sheet",
"nodal_d",
"schwarz_d_quadrilaterals",
]
_Points = NDArray[np.float64]
Image = tuple[int, int, int]
#: Hexagon spacings between the triangle's 30- and 60-degree corners.
TRIANGLE = 2
#: Carbons per primitive cell for ``TRIANGLE`` (2 K^2 per flag, 96 flags).
ATOMS_PER_CELL = 2 * TRIANGLE**2 * 96
#: Primitive fcc vectors in cube units (conventional edge 4).
LATTICE_UNITS: _Points = np.array([[0.0, 2.0, 2.0], [2.0, 0.0, 2.0], [2.0, 2.0, 0.0]])
#: The equalisation stops once every bond is within this fraction of the mean.
EQUALISE_TOLERANCE = 1e-9
#: The most equalisation steps one build takes.
EQUALISE_STEPS = 4000
_STEP = 0.2
_FIRST: tuple[tuple[int, int, int], ...] = ((0, 0, 0), (1, 1, 0), (0, 1, 1), (1, 0, 1))
_INVERSE: _Points = np.linalg.inv(LATTICE_UNITS)
_H = math.pi / 2
def _fractional(points: _Points) -> _Points:
out: _Points = np.asarray(points, dtype=float) @ _INVERSE
return out
def _rotate(p: _Points, q: _Points, x: _Points) -> _Points:
"""``x`` turned 180 degrees about the line through ``p`` and ``q``."""
d = (q - p) / np.linalg.norm(q - p)
foot = p + float((x - p) @ d) * d
out: _Points = 2 * foot - x
return out
def _cyclic_key(quad: _Points) -> tuple[tuple[int, int, int], ...]:
corners = [(int(round(a)), int(round(b)), int(round(c))) for a, b, c in quad]
options = []
for start in range(4):
for step in (1, -1):
options.append(tuple(corners[(start + step * k) % 4] for k in range(4)))
return min(options)
def _into_cell(quad: _Points) -> _Points:
"""``quad`` translated so its centre has fractional coordinates in [0, 1)."""
shift = np.floor(_fractional(quad.mean(axis=0)) + 1e-9)
out: _Points = quad - shift @ LATTICE_UNITS
return out
[docs]
def schwarz_d_quadrilaterals() -> list[_Points]:
"""The 12 skew quadrilaterals of one primitive cell, corners in cyclic order.
Generated from the first quadrilateral by 180-degree rotations about the
edges, each image translated into the cell, until no new one appears.
"""
first = np.array(_FIRST, dtype=float)
seen = {_cyclic_key(first): first}
frontier = [first]
while frontier:
found = []
for quad in frontier:
for k in range(4):
p, q = quad[k], quad[(k + 1) % 4]
image = _into_cell(np.array([_rotate(p, q, x) for x in quad]))
key = _cyclic_key(image)
if key not in seen:
seen[key] = image
found.append(image)
frontier = found
return [seen[key] for key in sorted(seen)]
[docs]
def nodal_d(points: _Points) -> tuple[_Points, _Points]:
"""The D nodal function and its gradient at ``points`` (cube units)."""
x, y, z = (_H * np.asarray(points, dtype=float)).T
sx, sy, sz, cx, cy, cz = np.sin(x), np.sin(y), np.sin(z), np.cos(x), np.cos(y), np.cos(z)
value = sx * sy * sz + sx * cy * cz - cx * sy * cz - cx * cy * sz
gx = cx * sy * sz + cx * cy * cz + sx * sy * cz + sx * cy * sz
gy = sx * cy * sz - sx * sy * cz - cx * cy * cz + cx * sy * sz
gz = sx * sy * cz - sx * cy * sz + cx * sy * sz - cx * cy * cz
gradient: _Points = _H * np.stack([gx, gy, gz], axis=1)
return value, gradient
def _project(points: _Points) -> _Points:
"""Newton steps along the gradient onto the nodal surface."""
for _ in range(25):
value, gradient = nodal_d(points)
points = points - (value / np.sum(gradient * gradient, axis=1))[:, None] * gradient
return points
# --- the plane graphite triangle -----------------------------------------------------------
def _triangle(k: int) -> tuple[_Points, _Points, list[list[_Points]]]:
"""Corners ``H, O, M``, the carbons in or on the triangle and each one's 3 neighbours."""
length = k * math.sqrt(3.0)
corners = np.array(
[[0.0, 0.0], [length, 0.0], [0.75 * length, math.sqrt(3.0) / 4 * length]], dtype=float
)
a1 = math.sqrt(3.0) * np.array([1.0, 0.0])
a2 = math.sqrt(3.0) * np.array([0.5, math.sqrt(3.0) / 2])
net: list[_Points] = []
for i in range(-2, 2 * k + 3):
for j in range(-2, 2 * k + 3):
centre = i * a1 + j * a2
for t in range(6):
angle = math.radians(30 + 60 * t)
point = centre + np.array([math.cos(angle), math.sin(angle)])
if all(np.linalg.norm(point - other) > 1e-6 for other in net):
net.append(point)
inside = [p for p in net if np.all(_barycentric(corners, p) > -1e-9)]
neighbours = [[q for q in net if abs(np.linalg.norm(q - p) - 1.0) < 1e-6] for p in inside]
if any(len(n) != 3 for n in neighbours):
raise ValueError("the plane net around the triangle is too small")
return corners, np.array(inside), neighbours
def _barycentric(corners: _Points, point: _Points) -> _Points:
matrix = np.vstack([corners.T, np.ones(3)])
out: _Points = np.linalg.solve(matrix, np.array([point[0], point[1], 1.0]))
return out
def _reflect(corners: _Points, point: _Points, side: int) -> _Points:
"""``point`` mirrored across the side opposite corner ``side``."""
p, q = (corners[(side + 1) % 3], corners[(side + 2) % 3])
d = (q - p) / np.linalg.norm(q - p)
r = point - p
out: _Points = p + 2 * float(r @ d) * d - r
return out
# --- the sheet ---------------------------------------------------------------------------
[docs]
@dataclass(frozen=True)
class DSheet:
"""One primitive cell of the decorated sheet, in cube units before scaling."""
positions: _Points
bonds: list[tuple[int, int, Image]]
quadrilaterals: int
flags: int
equalise_steps: int
equalise_misfit: float
mean_bond_units: float
def _key(point: _Points) -> tuple[float, float, float]:
f = np.round(_fractional(point) % 1.0, 6) % 1.0
return (float(f[0]), float(f[1]), float(f[2]))
[docs]
def d_sheet(k: int = TRIANGLE) -> DSheet:
"""Decorate the Schwarz D map with the ``k`` triangle and place it on the nodal surface."""
quads = schwarz_d_quadrilaterals()
flags: list[tuple[_Points, _Points, _Points]] = [] # (v, c, m): the H, O, M corners
for quad in quads:
centre = quad.mean(axis=0)
for side in range(4):
v, w = quad[side], quad[(side + 1) % 4]
middle = (v + w) / 2
flags += [(v, centre, middle), (w, centre, middle)]
# Neighbouring flag across the side opposite corner H (0), O (1) or M (2).
sides: dict[tuple[int, tuple[tuple[float, float, float], ...]], list[int]] = {}
for n, corners in enumerate(flags):
for opposite in range(3):
pair = tuple(_key(corners[s]) for s in range(3) if s != opposite)
sides.setdefault((opposite, pair), []).append(n)
if any(len(v) != 2 for v in sides.values()):
raise ValueError("a flag side is not shared by exactly two flags")
def across(n: int, opposite: int) -> tuple[int, _Points]:
"""The neighbour flag and the translation from its frame into flag ``n``'s."""
pair = tuple(_key(flags[n][s]) for s in range(3) if s != opposite)
first, second = sides[(opposite, pair)]
other = second if first == n else first
shared = (opposite + 1) % 3
shift: _Points = flags[n][shared] - flags[other][shared]
return other, shift
plane, inside, neighbours = _triangle(k)
def place(n: int, point: _Points) -> _Points:
weights = _barycentric(plane, point)
h, o, m = flags[n]
out: _Points = weights[0] * h + weights[1] * o + weights[2] * m
return out
canonical: list[_Points] = []
index: dict[tuple[float, float, float], int] = {}
def identify(point: _Points) -> tuple[int, NDArray[np.int64]]:
key = _key(point)
if key not in index:
index[key] = len(canonical)
canonical.append(point)
atom = index[key]
offset = np.rint(_fractional(point) - _fractional(canonical[atom])).astype(np.int64)
return atom, offset
bonds: dict[tuple[int, int, Image], None] = {}
for n in range(len(flags)):
for p, near in zip(inside, neighbours, strict=True):
i, offset_i = identify(place(n, p))
for q in near:
flag, point, moved = n, q.copy(), np.zeros(3)
for _ in range(8):
weights = _barycentric(plane, point)
if np.all(weights > -1e-9):
break
side = int(np.argmin(weights))
flag, shift = across(flag, side)
point, moved = _reflect(plane, point, side), moved + shift
else:
raise ValueError("a bond walk left the flag neighbourhood")
j, offset_j = identify(place(flag, point) + moved)
cells = offset_j - offset_i
image = (int(cells[0]), int(cells[1]), int(cells[2]))
if (i, image) == (j, (0, 0, 0)):
raise ValueError("a bond closes on its own atom")
if i > j or (i == j and _neg(image) < image):
i_, j_, image = j, i, _neg(image)
else:
i_, j_ = i, j
bonds[(i_, j_, image)] = None
bond_list = sorted(bonds)
positions = _project(np.array(canonical))
edges = np.array([(i, j) for i, j, _ in bond_list])
shifts = np.array([image for *_, image in bond_list], dtype=float) @ LATTICE_UNITS
misfit, steps = math.inf, 0
while steps < EQUALISE_STEPS:
vectors = positions[edges[:, 1]] + shifts - positions[edges[:, 0]]
lengths = np.linalg.norm(vectors, axis=1)
mean = float(lengths.mean())
misfit = float(np.abs(lengths - mean).max() / mean)
if misfit < EQUALISE_TOLERANCE:
break
pull = ((lengths - mean) / lengths)[:, None] * vectors
move = np.zeros_like(positions)
np.add.at(move, edges[:, 0], pull)
np.add.at(move, edges[:, 1], -pull)
positions = _project(positions + _STEP * move)
steps += 1
vectors = positions[edges[:, 1]] + shifts - positions[edges[:, 0]]
return DSheet(
positions=positions,
bonds=bond_list,
quadrilaterals=len(quads),
flags=len(flags),
equalise_steps=steps,
equalise_misfit=misfit,
mean_bond_units=float(np.linalg.norm(vectors, axis=1).mean()),
)
def _neg(image: Image) -> Image:
return (-image[0], -image[1], -image[2])