vibe-sketcherDocumentation
Source code for vibesketcher.chem.layered_carbon
"""Honeycomb layers: binary sheets, stacked multilayers and twisted bilayers (#201).
A honeycomb layer has the hexagonal lattice a1 = a (1, 0), a2 = a (1/2, sqrt(3)/2)
(60 degrees apart) with sublattice A at the lattice points and sublattice B at
A + (a1 + a2) / 3, so the A-B distance is a / sqrt(3). Graphene puts carbon on
both sublattices (a = 2.46 angstrom); hexagonal boron nitride puts boron on A and
nitrogen on B (a = 2.504 angstrom); a custom layer names both elements and a.
Stacks
Layer k (0-based) of a stack is shifted in-plane by s_k (a1 + a2) / 3:
AA has s_k = 0 (eclipsed), AB (Bernal) s_k = k mod 2, ABC (rhombohedral)
s_k = k mod 3, so A of layer k + 1 sits over B of layer k. AA' is eclipsed
with the sublattice chemistry swapped on every other layer (B over N, the
h-BN bulk stacking). A periodic (3-D) stack repeats along c = L d and needs a
whole number of stacking periods; a 2-D stack carries a stated vacuum.
Commensurate twisted bilayers
The construction of Lopes dos Santos, Peres and Castro Neto, Phys. Rev.
Lett. 99, 256802 (2007) (also Shallcross, Sharma, Kandelaki and Pankratov,
Phys. Rev. B 81, 165105, 2010): for coprime integers (m, r) the top layer is
the bottom layer turned by theta about a common site, with
cos(theta) = (3m^2 + 3mr + r^2/2) / (3m^2 + 3mr + r^2),
and the superlattice is t1 = m a1 + (m + r) a2, t2 = -(m + r) a1 + (2m + r) a2
holding N = 4 (3m^2 + 3mr + r^2) atoms; when 3 divides r it is
t1 = (m + r/3) a1 + (r/3) a2, t2 = -(r/3) a1 + (m + 2r/3) a2 with
N = 4 (m^2 + mr + r^2/3). Both layers' integer matrices are recorded and
checked: t1 and t2 must be lattice vectors of the turned layer to 1e-9.
A requested angle is matched to such a cell only when it agrees within the
stated tolerance; any other angle is refused with the nearest commensurate
cells, never rounded or strained to fit.
Layers of different lattice constants share one in-plane lattice only with an
explicit ``strain_allocation``; the strain of every layer is recorded. Every
structure is an unrelaxed starting geometry, neutral, with the lowest spin
multiplicity the electron count allows (not a ground-state prediction).
"""
from __future__ import annotations
import math
from collections.abc import Sequence
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,
_check_collisions,
_provenance,
_structure,
neighbour_pairs,
)
from vibesketcher.document.model import PeriodicStructure
from vibesketcher.elements import ATOMIC_NUMBER
from vibesketcher.limits import MAX_ATOMS
__all__ = [
"HoneycombLayer",
"HoneycombStackRecipe",
"TwistedBilayerRecipe",
"build_honeycomb_stack",
"build_twisted_bilayer",
"commensurate_twists",
"twist_cell",
]
_ID = Field(pattern=r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")
_Points = NDArray[np.float64]
#: material -> (sublattice A, sublattice B, lattice constant in angstrom, interlayer spacing).
#: Graphite: a = 2.46, c/2 = 3.35; h-BN: a = 2.504, c/2 = 3.33 angstrom.
PRESETS: dict[str, tuple[str, str, float, float]] = {
"graphene": ("C", "C", 2.46, 3.35),
"hbn": ("B", "N", 2.504, 3.33),
}
#: Largest strain a stated allocation may impose on one layer.
_MAX_STRAIN = 0.10
#: Neighbour cutoff as a multiple of the A-B distance.
_BOND_FACTOR = 1.2
[docs]
class HoneycombLayer(BaseModel):
"""One honeycomb layer: a preset material or explicit sublattice chemistry."""
model_config = ConfigDict(extra="forbid")
material: Literal["graphene", "hbn", "custom"] = "graphene"
#: Elements on sublattices A and B (custom layers only).
a_site: str | None = None
b_site: str | None = None
#: The in-plane lattice constant, angstrom (a preset's default when left out).
a: float | None = Field(default=None, ge=1.5, le=10, allow_inf_nan=False)
@model_validator(mode="after")
def _chemistry(self) -> Self:
if self.material == "custom":
if not self.a_site or not self.b_site or self.a is None:
raise ValueError("a custom honeycomb layer needs a_site, b_site and a")
for symbol in (self.a_site, self.b_site):
if symbol not in ATOMIC_NUMBER:
raise ValueError(f"{symbol!r} is not an element")
elif self.a_site or self.b_site:
raise ValueError(f"{self.material} fixes its sublattices; use material custom")
return self
[docs]
def sublattices(self) -> tuple[str, str]:
if self.material == "custom":
assert self.a_site and self.b_site
return (self.a_site, self.b_site)
a_site, b_site, _, _ = PRESETS[self.material]
return (a_site, b_site)
[docs]
def lattice_constant(self) -> float:
return self.a if self.a is not None else PRESETS[self.material][2]
[docs]
def spacing(self) -> float | None:
return None if self.material == "custom" else PRESETS[self.material][3]
def _graphene() -> list[HoneycombLayer]:
return [HoneycombLayer()]
class _LayeredRecipe(BaseModel):
model_config = ConfigDict(extra="forbid")
identifier: str = _ID
#: Interlayer distance, angstrom; the presets' mean when left out.
interlayer: float | None = Field(default=None, ge=2.5, le=10, allow_inf_nan=False)
periodicity: Literal["2d", "3d"] = "2d"
#: Vacuum along c for a 2-D cell, angstrom.
vacuum: float = Field(default=15.0, ge=3, le=200, allow_inf_nan=False)
#: How layers of different lattice constants share one lattice: refuse (none),
#: strain all to the bottom or top layer, or to their mean.
strain_allocation: Literal["none", "bottom", "top", "mean"] = "none"
[docs]
class HoneycombStackRecipe(_LayeredRecipe):
"""A honeycomb monolayer or AA, AB, ABC or AA' multilayer, 2-D or bulk."""
kind: Literal["honeycomb_stack"] = "honeycomb_stack"
layers: list[HoneycombLayer] = Field(default_factory=_graphene, min_length=1, max_length=24)
stacking: Literal["AA", "AB", "ABC", "AA'"] = "AA"
[docs]
class TwistedBilayerRecipe(_LayeredRecipe):
"""A commensurate twisted bilayer from coprime (m, r), or an exactly matching angle."""
kind: Literal["twisted_bilayer"] = "twisted_bilayer"
m: int | None = Field(default=None, ge=1, le=1000)
r: int | None = Field(default=None, ge=1, le=1000)
angle_deg: float | None = Field(default=None, gt=0, lt=60, allow_inf_nan=False)
#: How close a requested angle must be to a commensurate one to be accepted.
angle_tolerance_deg: float = Field(default=1e-6, gt=0, le=1e-3)
layers: list[HoneycombLayer] = Field(
default_factory=lambda: [HoneycombLayer(), HoneycombLayer()], min_length=2, max_length=2
)
#: Registry before the twist: AA (site over site) or AB (top A over bottom B).
registry: Literal["AA", "AB"] = "AA"
#: The largest cell built; larger commensurate cells are refused.
max_atoms: int = Field(default=2000, ge=4, le=MAX_ATOMS)
@model_validator(mode="after")
def _indices(self) -> Self:
given_indices = self.m is not None or self.r is not None
if given_indices and self.angle_deg is not None:
raise ValueError("give the twist as m and r or as angle_deg, not both")
if given_indices and (self.m is None or self.r is None):
raise ValueError("a twisted bilayer needs both m and r")
if not given_indices and self.angle_deg is None:
raise ValueError("give the twist as m and r, or as angle_deg")
if self.m is not None and self.r is not None and math.gcd(self.m, self.r) != 1:
raise ValueError(
f"m={self.m} and r={self.r} share a factor; the primitive cell of that angle "
"uses coprime indices"
)
return self
# --- commensurate twists (Lopes dos Santos, Peres and Castro Neto 2007) ---
def _cosine_fraction(m: int, r: int) -> tuple[int, int]:
"""cos(theta) as the exact fraction (6m^2 + 6mr + r^2) / (2 (3m^2 + 3mr + r^2))."""
numerator = 6 * m * m + 6 * m * r + r * r
denominator = 2 * (3 * m * m + 3 * m * r + r * r)
g = math.gcd(numerator, denominator)
return numerator // g, denominator // g
[docs]
def twist_cell(m: int, r: int) -> dict[str, Any]:
"""Angle, bottom-layer superlattice matrix and atom count of the (m, r) cell."""
if m < 1 or r < 1 or math.gcd(m, r) != 1:
raise BuildRefused("commensurate twist indices are coprime integers m, r >= 1")
numerator, denominator = _cosine_fraction(m, r)
angle = math.degrees(math.acos(numerator / denominator))
if r % 3:
matrix = [[m, m + r], [-(m + r), 2 * m + r]]
atoms = 4 * (3 * m * m + 3 * m * r + r * r)
else:
k = r // 3
matrix = [[m + k, k], [-k, m + 2 * k]]
atoms = 4 * (m * m + m * r + r * r // 3)
return {
"m": m,
"r": r,
"angle_deg": angle,
"cos_theta": f"{numerator}/{denominator}",
"matrix": matrix,
"atoms": atoms,
}
[docs]
def commensurate_twists(
max_atoms: int = 2000, min_angle: float = 0.0, max_angle: float = 60.0
) -> list[dict[str, Any]]:
"""Every commensurate cell of at most ``max_atoms`` atoms, by angle (one cell per angle)."""
if not 4 <= max_atoms <= MAX_ATOMS:
raise BuildRefused(f"max_atoms must be between 4 and {MAX_ATOMS}")
found: dict[str, dict[str, Any]] = {}
def bound(m: int, r: int) -> float:
# Neither branch's atom count is below 4 (m^2 + mr + r^2 / 3).
return 4 * (m * m + m * r + r * r / 3)
m = 1
while bound(m, 1) <= max_atoms:
r = 1
while bound(m, r) <= max_atoms:
if math.gcd(m, r) == 1:
cell = twist_cell(m, r)
if cell["atoms"] <= max_atoms and min_angle <= cell["angle_deg"] <= max_angle:
key = cell["cos_theta"]
if key not in found or cell["atoms"] < found[key]["atoms"]:
found[key] = cell
r += 1
m += 1
return sorted(found.values(), key=lambda c: (c["angle_deg"], c["atoms"]))
def _resolve_twist(recipe: TwistedBilayerRecipe) -> dict[str, Any]:
if recipe.m is not None and recipe.r is not None:
return twist_cell(recipe.m, recipe.r)
assert recipe.angle_deg is not None
candidates = commensurate_twists(recipe.max_atoms)
exact = [c for c in candidates
if abs(c["angle_deg"] - recipe.angle_deg) <= recipe.angle_tolerance_deg] # fmt: skip
if exact:
return min(exact, key=lambda c: c["atoms"])
nearest = sorted(candidates, key=lambda c: abs(c["angle_deg"] - recipe.angle_deg))[:3]
listed = ", ".join(
f"{c['angle_deg']:.6f} deg (m={c['m']}, r={c['r']}, {c['atoms']} atoms)" for c in nearest
)
raise BuildRefused(
f"{recipe.angle_deg} deg is not a commensurate twist within "
f"{recipe.angle_tolerance_deg} deg for cells up to {recipe.max_atoms} atoms; a "
f"periodic cell would need rounding or strain, which is not applied. Nearest: {listed}"
)
# --- shared layer construction ---
def _basis(a: float, angle_deg: float = 0.0) -> _Points:
"""Rows a1 = a (1, 0), a2 = a (1/2, sqrt(3)/2), turned by angle about z."""
t = math.radians(angle_deg)
rotation = np.array([[math.cos(t), -math.sin(t)], [math.sin(t), math.cos(t)]])
rows = a * np.array([[1.0, 0.0], [0.5, math.sqrt(3) / 2]])
return np.asarray(rows @ rotation.T, dtype=float)
def _shared_constant(layers: Sequence[HoneycombLayer], allocation: str) -> float:
constants = [layer.lattice_constant() for layer in layers]
if max(constants) - min(constants) <= 1e-9 * max(constants):
return constants[0]
if allocation == "none":
raise BuildRefused(
"the layers have different lattice constants ("
+ ", ".join(f"{c:g}" for c in constants)
+ " angstrom); set strain_allocation (bottom, top or mean) to strain them to one "
"lattice, or give equal a"
)
shared = {
"bottom": constants[0],
"top": constants[-1],
"mean": sum(constants) / len(constants),
}[allocation]
worst = max(abs(shared / c - 1) for c in constants)
if worst > _MAX_STRAIN:
raise BuildRefused(
f"sharing a = {shared:g} angstrom strains a layer by {worst:.1%}, more than "
f"{_MAX_STRAIN:.0%}"
)
return shared
def _interlayer(recipe: _LayeredRecipe, layers: Sequence[HoneycombLayer]) -> float:
if recipe.interlayer is not None:
return recipe.interlayer
spacings = [layer.spacing() for layer in layers]
if any(s is None for s in spacings):
raise BuildRefused("a stack with a custom layer needs an explicit interlayer distance")
return sum(s for s in spacings if s is not None) / len(spacings)
class _Sites:
"""Atoms collected layer by layer, with the deterministic site map."""
def __init__(self) -> None:
self.symbols: list[str] = []
self.xy: list[list[float]] = []
self.z: list[float] = []
self.labels: list[str] = []
self.rows: list[list[Any]] = []
def add_layer(
self,
layer: int,
species: tuple[str, str],
basis: _Points,
matrix: _Points,
shift: float,
height: float,
) -> None:
"""Fill the supercell ``matrix @ basis`` with one layer's A and B sites.
``shift`` moves the layer by shift (a1 + a2) in its own basis. Site
fractions are taken in the layer's integer basis, so membership is exact.
"""
inverse = np.linalg.inv(matrix)
corners = np.array([[0, 0], matrix[0], matrix[1], matrix[0] + matrix[1]], dtype=float)
low = np.floor(corners.min(axis=0)).astype(int) - 2
high = np.ceil(corners.max(axis=0)).astype(int) + 2
count = round(abs(float(np.linalg.det(matrix))))
eps = 1e-9
for sub, (label, symbol) in enumerate(zip("AB", species, strict=True)):
offset = shift + sub / 3
found: list[tuple[int, int, NDArray[np.float64]]] = []
for i in range(low[0], high[0] + 1):
for j in range(low[1], high[1] + 1):
fraction = np.array([i + offset, j + offset])
s = fraction @ inverse
if np.all(s >= -eps) and np.all(s < 1 - eps):
found.append((i, j, fraction))
if len(found) != count:
raise AssertionError("a layer lost or duplicated sites in the supercell")
found.sort(key=lambda item: (item[1], item[0]))
for k, (i, j, fraction) in enumerate(found, start=1):
site = f"L{layer}{label}{k}"
self.symbols.append(symbol)
self.xy.append([float(x) for x in fraction @ basis])
self.z.append(height)
self.labels.append(site)
self.rows.append([site, layer, label, i, j])
def cartesian(self) -> _Points:
return np.column_stack([np.array(self.xy), np.array(self.z)])
def _cell(
rows2d: _Points, heights: Sequence[float], spacing: float, recipe: _LayeredRecipe
) -> tuple[_Points, tuple[bool, bool, bool], list[float]]:
"""3-D lattice rows, PBC and the layer heights placed in the cell."""
count = len(heights)
if recipe.periodicity == "3d":
c = count * spacing
placed = [k * spacing for k in range(count)]
pbc = (True, True, True)
else:
c = (count - 1) * spacing + recipe.vacuum
placed = [recipe.vacuum / 2 + k * spacing for k in range(count)]
pbc = (True, True, False)
lattice = np.zeros((3, 3))
lattice[:2, :2] = rows2d
lattice[2, 2] = c
return lattice, pbc, placed
def _multiplicity(symbols: Sequence[str]) -> int:
return 1 if sum(ATOMIC_NUMBER[s] for s in symbols) % 2 == 0 else 2
def _finish(
recipe: _LayeredRecipe,
kind: str,
lattice: _Points,
pbc: tuple[bool, bool, bool],
sites: _Sites,
a: float,
layers: Sequence[HoneycombLayer],
**extra: Any,
) -> PeriodicStructure:
cartesian = sites.cartesian()
cutoff = _BOND_FACTOR * a / math.sqrt(3)
_check_collisions(cartesian, lattice, pbc, minimum=0.7 * a / math.sqrt(3))
pairs = neighbour_pairs(cartesian, lattice, pbc, cutoff)
degree = [0] * len(cartesian)
for i, j, _, _ in pairs:
degree[i] += 1
degree[j] += 1
if any(d != 3 for d in degree):
raise BuildRefused("the layers did not give three in-plane neighbours per site")
symbols = sites.symbols
bonds = [(i, j, 1.5 if symbols[i] == symbols[j] == "C" else 1.0) for i, j, _, _ in pairs]
counts: dict[str, int] = {}
for symbol in symbols:
counts[symbol] = counts.get(symbol, 0) + 1
multiplicity = _multiplicity(symbols)
return _structure(
recipe.identifier,
lattice,
pbc,
symbols,
cartesian,
bonds,
cell_setting="unspecified",
charge=0,
multiplicity=multiplicity,
labels=sites.labels,
provenance=_provenance(
kind,
recipe,
lattice_constant_angstrom=a,
layers=[
{
"layer": k + 1,
"material": layer.material,
"sublattices": {"A": layer.sublattices()[0], "B": layer.sublattices()[1]},
"natural_a_angstrom": layer.lattice_constant(),
"strain": round(a / layer.lattice_constant() - 1, 9),
}
for k, layer in enumerate(layers)
],
stoichiometry=dict(sorted(counts.items())),
site_map={"columns": ["site", "layer", "sublattice", "i", "j"], "rows": sites.rows},
charge_spin="neutral; lowest multiplicity allowed by electron parity, "
"not a ground-state prediction",
**extra,
),
)
# --- stacks ---
_PERIOD = {"AA": 1, "AB": 2, "ABC": 3, "AA'": 2}
[docs]
def build_honeycomb_stack(recipe: HoneycombStackRecipe) -> PeriodicStructure:
"""A monolayer or stacked honeycomb cell, or a refusal with the reason."""
layers = recipe.layers
stacking = recipe.stacking
if stacking == "AA'" and all(len(set(layer.sublattices())) == 1 for layer in layers):
raise BuildRefused(
"AA' differs from AA only by swapping the sublattice chemistry; with one element "
"on both sublattices it is AA"
)
period = _PERIOD[stacking]
if recipe.periodicity == "3d" and len(layers) % period:
raise BuildRefused(
f"a periodic {stacking} stack repeats every {period} layers; {len(layers)} "
"layer(s) do not close the period"
)
a = _shared_constant(layers, recipe.strain_allocation)
spacing = _interlayer(recipe, layers) if len(layers) > 1 or recipe.periodicity == "3d" else 0
basis = _basis(a)
lattice, pbc, heights = _cell(basis, [0.0] * len(layers), spacing, recipe)
sites = _Sites()
identity = np.eye(2)
for k, layer in enumerate(layers):
shift = {"AA": 0, "AB": k % 2, "ABC": k % 3, "AA'": 0}[stacking] / 3
species = layer.sublattices()
if stacking == "AA'" and k % 2:
species = (species[1], species[0])
sites.add_layer(k + 1, species, basis, identity, shift, heights[k])
registry = {
"AA": "eclipsed: every site over the same sublattice",
"AB": "A of each layer over B of the layer below (Bernal)",
"ABC": "A of each layer over B of the layer below, repeating every three layers",
"AA'": "eclipsed with the sublattice chemistry swapped on every other layer",
}[stacking]
return _finish(
recipe,
"honeycomb_stack",
lattice,
pbc,
sites,
a,
layers,
stacking=stacking,
registry=registry,
interlayer_angstrom=spacing,
)
# --- twisted bilayers ---
[docs]
def build_twisted_bilayer(recipe: TwistedBilayerRecipe) -> PeriodicStructure:
"""A commensurate twisted bilayer, or a refusal with the reason (never a rounded angle)."""
cell = _resolve_twist(recipe)
if cell["atoms"] > recipe.max_atoms:
raise BuildRefused(
f"the (m={cell['m']}, r={cell['r']}) cell at {cell['angle_deg']:.6f} deg holds "
f"{cell['atoms']} atoms, more than max_atoms={recipe.max_atoms}"
)
layers = recipe.layers
a = _shared_constant(layers, recipe.strain_allocation)
spacing = _interlayer(recipe, layers)
bottom = _basis(a)
top = _basis(a, cell["angle_deg"])
lower = np.array(cell["matrix"], dtype=float)
rows2d = lower @ bottom
# The same superlattice in the turned layer's own basis must be integer.
upper = rows2d @ np.linalg.inv(top)
if not np.allclose(upper, np.round(upper), atol=1e-9 * max(1, float(np.abs(upper).max()))):
raise AssertionError("the twisted layer is not commensurate with the superlattice")
upper = np.round(upper)
lattice, pbc, heights = _cell(rows2d, [0.0, 0.0], spacing, recipe)
sites = _Sites()
sites.add_layer(1, layers[0].sublattices(), bottom, lower, 0.0, heights[0])
shift = 1 / 3 if recipe.registry == "AB" else 0.0
sites.add_layer(2, layers[1].sublattices(), top, upper, shift, heights[1])
return _finish(
recipe,
"twisted_bilayer",
lattice,
pbc,
sites,
a,
layers,
twist={
"m": cell["m"],
"r": cell["r"],
"angle_deg": cell["angle_deg"],
"cos_theta": cell["cos_theta"],
"construction": "Lopes dos Santos, Peres and Castro Neto 2007",
},
layer_matrices=[
[[int(x) for x in row] for row in lower],
[[int(x) for x in row] for row in upper],
], # fmt: skip
registry=f"{recipe.registry} before the twist, turned about the origin site",
interlayer_angstrom=spacing,
strain="none from the twist; only the stated lattice-constant allocation",
)