vibe-sketcherDocumentation
Source code for vibesketcher.document.interfaces
"""Periodic interfaces, stacking faults and planned extended defects (#197).
Every model built here is an unrelaxed starting geometry. Construction is not
relaxation, thermodynamic stability, adhesion or validated mechanics; each
record says so and lists the strain and size convergence a calculation on it
still owes.
Heterointerfaces (``kind: "interface"``)
Two parent slabs in the document (any slab-like cell: in-plane rows a, b
with no normal component and c along the normal) are put on one in-plane
lattice. The coincidence search follows A. Zur and T. C. McGill, J. Appl.
Phys. 55, 378 (1984), doi:10.1063/1.333084: every superlattice of index n
of a 2-D lattice is an integer Hermite normal form matrix [[a, b], [0, d]]
with a d = n and 0 <= b < d times the parent rows. Superlattices of the
two phases with equal area within the strain bound are reduced
(Lagrange-Gauss), compared, and the integer basis correspondence with the
smallest principal strain is kept. The map F that takes the top
superlattice onto the bottom one is split by polar decomposition into the
in-plane rotation of the top phase and its stretch; the principal values
of the stretch minus one are the lattice mismatch. Candidates are ranked by
mismatch, then area. Both integer supercell matrices are recorded.
The common cell is C = S_bottom + w (R S_top - S_bottom): w = 0 keeps the
bottom lattice and strains the top, w = 1 the reverse, w = 0.5 shares the
mismatch. ``strain_allocation`` is required for any nonzero mismatch; no
phase is ever strained silently. Each phase's strain is recorded as the
left stretch tensor minus the identity (Biot strain, interface frame); the
normal axis is not strained, so no Poisson response is applied.
Stacking faults (``kind: "stacking_fault"``)
A bulk crystal is oriented on its close-packed plane (the slab surface
transform of W. Sun and G. Ceder, Surf. Sci. 617, 53, 2013) and stacked.
Planes above the fault plane are displaced rigidly in-plane, as in the
generalised stacking-fault construction of V. Vitek, Philos. Mag. 18, 773
(1968). For an ABC close-packed stack the stacking offset delta (the
Shockley partial, a/6 <112> in fcc) is measured from the planes themselves:
an intrinsic fault shifts every plane above the fault by delta (one plane
missing, ABC|BCA), an extrinsic fault shifts the planes above the fault by
delta and those above the next plane by a further delta (one plane
inserted); J. P. Hirth and J. Lothe, Theory of Dislocations, 2nd ed.
(Wiley, 1982), ch. 9-10. A periodic model tilts c by the total
displacement, so each cell holds exactly one fault; a slab model carries
vacuum. The fault is refused when it is closer to its periodic image, or to
a free surface, than the stated minimum.
Grain boundaries and dislocations
Only planned here: :func:`plan_extended_defect` returns a planned record
when the rotation axis, misorientation and boundary plane (grain
boundaries) or Burgers vector, line direction and boundary/elastic
assumptions (dislocations) are all stated, and coded refusals listing what
is missing otherwise. No atoms are placed.
"""
from __future__ import annotations
import itertools
import math
from collections import Counter
from functools import cache
from typing import Any, Literal
import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from vibesketcher.chem.periodic_geometry import BuildRefused, _check_collisions, _provenance
from vibesketcher.chem.periodic_geometry import _structure as _geometry_structure
from vibesketcher.document.model import Document, PeriodicSite, PeriodicStructure
from vibesketcher.limits import MAX_ATOMS
__all__ = [
"InterfaceRecipe",
"StackingFaultRecipe",
"build_interface",
"build_stacking_fault",
"coincidence_cells",
"interface_matches",
"plan_extended_defect",
"preview",
]
_ID = Field(pattern=r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")
_Points = NDArray[np.float64]
#: Largest principal strain any allocation may impose on one phase.
_MAX_STRAIN = 0.15
#: Below this every principal strain counts as an exact match.
_EXACT = 1e-9
#: What a constructed model is not; carried in every record.
NOT_CLAIMED = [
"relaxation (positions, cell or interlayer distance)",
"thermodynamic stability or the lowest-energy registry",
"adhesion, interface or fault energy",
"electronic-structure alignment or charge transfer",
]
class _Recipe(BaseModel):
model_config = ConfigDict(extra="forbid")
# --- integer lattice helpers ---
def _hnf(n: int) -> list[NDArray[np.int64]]:
"""Every index-``n`` superlattice of a 2-D lattice, as row Hermite normal forms."""
found = []
for a in range(1, n + 1):
if n % a:
continue
d = n // a
for b in range(d):
found.append(np.array([[a, b], [0, d]], dtype=np.int64))
return found
def _gauss(matrix: NDArray[np.int64], rows: _Points) -> NDArray[np.int64]:
"""Lagrange-Gauss reduction of the rows ``matrix @ rows``, kept right-handed."""
m = matrix.copy()
for _ in range(200):
u, v = m @ rows
if u @ u > (v @ v) * (1 + 1e-9):
m = m[[1, 0]]
continue
mu = round(float(u @ v) / float(u @ u))
if mu == 0:
break
m[1] = m[1] - mu * m[0]
u, v = m @ rows
if u[0] * v[1] - u[1] * v[0] < 0:
m[1] = -m[1]
return m
@cache
def _unimodular() -> tuple[NDArray[np.int64], ...]:
"""Proper basis changes with entries in -1, 0, 1 (covers 60/120 degree conventions)."""
found = []
for entries in itertools.product((-1, 0, 1), repeat=4):
w = np.array(entries, dtype=np.int64).reshape(2, 2)
if round(float(np.linalg.det(w))) == 1:
found.append(w)
return tuple(found)
def _polar(f: _Points) -> tuple[_Points, _Points, _Points]:
"""F = R U = V R: the rotation, right stretch and left stretch of a 2x2 map."""
w, s, vt = np.linalg.svd(f)
rotation = w @ vt
if np.linalg.det(rotation) < 0: # pragma: no cover - callers pass det F > 0
raise BuildRefused("the coincidence map includes a reflection")
return rotation, vt.T @ np.diag(s) @ vt, w @ np.diag(s) @ w.T
def _angle(rotation: _Points) -> float:
return math.degrees(math.atan2(float(rotation[1, 0]), float(rotation[0, 0])))
def _wrap(angle: float) -> float:
return (angle + 180.0) % 360.0 - 180.0
def _match(s_bottom: _Points, s_top: _Points) -> dict[str, Any]:
"""Rotation and principal strains that take the top superlattice onto the bottom one."""
# Columns: s_bottom.T = F s_top.T, so F = (inv(s_top) s_bottom).T.
f = (np.linalg.inv(s_top) @ s_bottom).T
rotation, right, _ = _polar(f)
principal = np.linalg.eigvalsh(right) - 1.0
return {
"rotation": rotation,
"rotation_deg": _angle(rotation),
"principal": [float(x) for x in principal],
"mismatch": float(np.max(np.abs(principal))),
}
def _point_rotations(rows: _Points) -> list[float]:
"""Proper rotation angles (degrees) that map the 2-D lattice onto itself."""
found = []
inverse = np.linalg.inv(rows)
for w in _unimodular():
r = (inverse @ (w @ rows)).T # columns: rows.T r.T = (w rows).T
if np.allclose(r @ r.T, np.eye(2), atol=1e-6):
found.append(round(_angle(r), 6) % 360)
return sorted(set(found))
def _canonical(angle: float, symmetry: list[float]) -> float:
"""The representative of a rotation modulo the two lattices' point rotations."""
options = [round(_wrap(angle + g), 4) for g in symmetry]
return min(options, key=lambda a: (abs(a), -a))
[docs]
def coincidence_cells(
bottom: _Points,
top: _Points,
*,
max_area: float,
max_strain: float,
twist_deg: float | None = 0.0,
angle_tolerance_deg: float = 0.5,
max_candidates: int = 20,
) -> list[dict[str, Any]]:
"""Commensurate in-plane supercells of two 2-D lattices (rows), best first.
Zur and McGill (1984): superlattices of both phases of at most
``max_area`` square angstrom whose principal mismatch is at most
``max_strain``. With ``twist_deg`` set, only coincidences whose top-phase
rotation lies within ``angle_tolerance_deg`` of it (modulo the lattices'
point rotations) are kept; ``None`` admits every rotation and records it.
Coincidences equal up to those point rotations, and larger cells with the
rotation and mismatch of a smaller one, are listed once.
"""
area_b = abs(float(np.linalg.det(bottom)))
area_t = abs(float(np.linalg.det(top)))
if area_b < 1e-6 or area_t < 1e-6:
raise BuildRefused("an in-plane cell has no area")
if max_area / min(area_b, area_t) > 400:
raise BuildRefused(
f"max_area {max_area:g} square angstrom allows more than 400 parent cells; "
"bound the search more tightly"
)
symmetry = sorted(
{
round((gb + gt) % 360, 6)
for gb in _point_rotations(bottom)
for gt in _point_rotations(top)
}
)
bases = np.array(_unimodular())
def reduced(rows: _Points, n: int) -> tuple[NDArray[np.int64], _Points]:
ms = np.array([_gauss(h, rows) for h in _hnf(n)])
vectors = ms @ rows
return ms, np.linalg.norm(vectors, axis=2)
tops: dict[int, tuple[NDArray[np.int64], _Points]] = {}
found: dict[tuple[float, float], dict[str, Any]] = {}
low, high = 1 - max_strain - 1e-9, 1 + max_strain + 1e-9
for n_b in range(1, int(max_area / area_b + 1e-9) + 1):
target = n_b * area_b
n_lo = max(1, math.ceil(target * (1 - max_strain) ** 2 / area_t - 1e-9))
n_hi = math.floor(target * (1 + max_strain) ** 2 / area_t + 1e-9)
if n_lo > n_hi:
continue
ms_b, lengths_b = reduced(bottom, n_b)
for n_t in range(n_lo, n_hi + 1):
if n_t not in tops:
tops[n_t] = reduced(top, n_t)
ms_t, lengths_t = tops[n_t]
for m_b, (b1, b2) in zip(ms_b, lengths_b, strict=True):
# Successive minima scale with the principal stretches.
r1, r2 = b1 / lengths_t[:, 0], b2 / lengths_t[:, 1]
keep = np.nonzero((r1 >= low) & (r1 <= high) & (r2 >= low) & (r2 <= high))[0]
if not len(keep):
continue
s_b = (m_b @ bottom).astype(float)
m_v = bases[None, :, :, :] @ ms_t[keep][:, None, :, :] # (k, w, 2, 2)
s_v = m_v.astype(float) @ top
f = np.swapaxes(np.linalg.inv(s_v) @ s_b, -1, -2)
u, sv, vt = np.linalg.svd(f)
rotation = u @ vt
mismatch = np.abs(sv - 1).max(axis=-1)
angles = np.degrees(np.arctan2(rotation[..., 1, 0], rotation[..., 0, 0]))
ok = mismatch <= max_strain + 1e-12
if twist_deg is not None:
near = np.zeros_like(ok)
for g in symmetry:
near |= np.abs((angles + g - twist_deg + 180) % 360 - 180) <= (
angle_tolerance_deg
)
ok &= near
for row in range(len(keep)):
choices = np.nonzero(ok[row])[0]
if not len(choices):
continue
# Least strain first, then the smallest turn among equivalent bases.
order = np.lexsort(
(np.abs(angles[row, choices]), np.round(mismatch[row, choices], 9))
)
best = choices[order[0]]
rot = float(angles[row, best])
key = (_canonical(rot, symmetry), round(float(mismatch[row, best]), 7))
if key in found:
continue
principal = np.sort(sv[row, best] - 1.0)
found[key] = {
"bottom_matrix": m_b.tolist(),
"top_matrix": m_v[row, best].tolist(),
"bottom_cells": n_b,
"top_cells": n_t,
"area_angstrom2": n_b * area_b,
"rotation_deg": rot,
"rotation_class_deg": key[0],
"principal_strains": [float(x) for x in principal],
"mismatch": float(mismatch[row, best]),
"lengths_angstrom": [float(b1), float(b2)],
"gamma_deg": math.degrees(
math.acos(max(-1.0, min(1.0, float(s_b[0] @ s_b[1]) / float(b1 * b2))))
),
}
ranked = sorted(
found.values(),
key=lambda c: (
round(c["mismatch"], 7),
c["area_angstrom2"],
abs(c["rotation_class_deg"]),
c["bottom_matrix"],
),
)
return ranked[:max_candidates]
# --- parents ---
def _slab_like(structure: PeriodicStructure, role: str) -> tuple[_Points, float, _Points]:
"""In-plane rows, c length and Cartesian positions of a slab-like parent."""
lattice = np.asarray(structure.lattice_angstrom, dtype=float)
if not (structure.pbc[0] and structure.pbc[1]):
raise BuildRefused(f"the {role} phase {structure.id!r} is not periodic in-plane")
if np.abs(lattice[:2, 2]).max() > 1e-6 or np.abs(lattice[2, :2]).max() > 1e-6:
raise BuildRefused(
f"the {role} phase {structure.id!r} is not slab-like: its a and b must lie in "
"the surface plane and c along the normal (cut it with kind=slab)"
)
if lattice[2, 2] <= 0:
raise BuildRefused(f"the {role} phase {structure.id!r} has c pointing down")
cartesian = np.asarray([structure.cartesian(s) for s in structure.sites], dtype=float)
thickness = float(np.ptp(cartesian[:, 2]))
if structure.pbc[2] and lattice[2, 2] - thickness < 3.0:
raise BuildRefused(
f"the {role} phase {structure.id!r} is periodic along the normal with less than "
"3 angstrom of vacuum; it is bulk, not a slab (cut it with kind=slab)"
)
if structure.pbc[2] and (
cartesian[:, 2].min() < -1e-6 or cartesian[:, 2].max() > lattice[2, 2] + 1e-6
):
raise BuildRefused(f"the {role} phase {structure.id!r} wraps across its c boundary")
return lattice[:2, :2].copy(), float(lattice[2, 2]), cartesian
def _flipped(structure: PeriodicStructure) -> PeriodicStructure:
"""The slab turned 180 degrees about x, so its top termination faces down.
(x, y, z) -> (x, -y, -z) is a proper rotation; a and b swap so the in-plane
basis stays right-handed with c up. Bond images follow the same swap.
"""
lattice = np.asarray(structure.lattice_angstrom, dtype=float)
turn = np.diag([1.0, -1.0, -1.0])
a1, a2 = lattice[0] @ turn, lattice[1] @ turn
rows = np.array([a2, a1, lattice[2]])
cartesian = np.asarray([structure.cartesian(s) for s in structure.sites]) @ turn
cartesian[:, 2] -= cartesian[:, 2].min()
if structure.pbc[2]:
cartesian[:, 2] += (lattice[2, 2] - np.ptp(cartesian[:, 2])) / 2
fractional = cartesian @ np.linalg.inv(rows)
fractional[:, :2] -= np.floor(fractional[:, :2] + 1e-12)
sites = [
site.model_copy(update={"fractional": tuple(float(x) for x in f)})
for site, f in zip(structure.sites, fractional, strict=True)
]
bonds = [
b.model_copy(update={"image": (b.image[1], b.image[0], -b.image[2])})
for b in structure.bonds
]
return structure.model_copy(
update={
"lattice_angstrom": tuple(tuple(float(x) for x in row) for row in rows),
"sites": sites,
"bonds": bonds,
}
)
def _builder(structure: PeriodicStructure) -> dict[str, Any]:
recorded = structure.provenance.get("builder")
return dict(recorded) if isinstance(recorded, dict) else {}
def _faces(structure: PeriodicStructure, flipped: bool, role: str) -> dict[str, Any]:
"""Which recorded termination of a parent slab faces the interface."""
builder = _builder(structure)
bottom, top = builder.get("bottom_composition"), builder.get("top_composition")
facing = (
(top if not flipped else bottom) if role == "bottom" else (bottom if not flipped else top)
)
return {
"structure": structure.id,
"builder": builder.get("kind"),
"miller": builder.get("miller"),
"termination": builder.get("termination"),
"facing_interface": facing,
"flipped": flipped,
"polarity": builder.get("polarity"),
}
# --- interfaces ---
StrainAllocation = Literal["none", "bottom", "top", "mean", "weighted"]
[docs]
class InterfaceRecipe(_Recipe):
"""Two parent slabs on one commensurate in-plane cell, bottom first."""
kind: Literal["interface"] = "interface"
identifier: str = _ID
#: The substrate (lower) slab and the overlayer (upper) slab in the document.
bottom: str = _ID
top: str = _ID
#: Explicit integer supercell matrices (rows of the parents' a and b); without
#: them the ranked coincidence search picks candidate ``match``.
bottom_matrix: list[list[int]] | None = None
top_matrix: list[list[int]] | None = None
match: int = Field(default=0, ge=0, le=99)
max_area: float = Field(default=150.0, gt=0, le=5000, allow_inf_nan=False)
max_strain: float = Field(default=0.05, ge=0, le=_MAX_STRAIN, allow_inf_nan=False)
#: Rotation of the top phase about the normal, degrees; None searches every rotation.
twist_deg: float | None = Field(default=0.0, ge=-180, le=180, allow_inf_nan=False)
angle_tolerance_deg: float = Field(default=0.5, gt=0, le=30, allow_inf_nan=False)
#: Whose lattice is kept: none (refuse any mismatch), bottom (strain the top),
#: top (strain the bottom), mean, or weighted with ``top_weight``.
strain_allocation: StrainAllocation = "none"
#: Fraction of the mismatch the bottom phase takes (weighted only): 0 keeps it unstrained.
top_weight: float | None = Field(default=None, ge=0, le=1, allow_inf_nan=False)
#: In-plane shift of the top phase, fractions of the interface cell.
translation: tuple[float, float] = (0.0, 0.0)
#: Normal distance from the highest bottom atom to the lowest top atom, angstrom.
gap: float = Field(ge=0.5, le=20, allow_inf_nan=False)
#: Turn the top slab over so its recorded top termination faces the interface.
top_flip: bool = False
periodicity: Literal["2d", "3d"] = "2d"
#: Vacuum along the normal for a 2-D model, angstrom.
vacuum: float = Field(default=15.0, ge=3, le=200, allow_inf_nan=False)
#: 3-D models only: the second interface's gap (top phase to the bottom image).
periodic_gap: float | None = Field(default=None, ge=0.5, le=20, allow_inf_nan=False)
#: Closest interphase contact admitted, angstrom.
min_distance: float = Field(default=1.0, gt=0.3, le=5, allow_inf_nan=False)
max_atoms: int = Field(default=2000, ge=2, le=MAX_ATOMS)
def _parents(
recipe: InterfaceRecipe, document: Document
) -> tuple[PeriodicStructure, PeriodicStructure]:
existing = {s.id: s for s in document.periodic_structures}
for name in (recipe.bottom, recipe.top):
if name not in existing:
raise BuildRefused(f"periodic structure {name!r} not found")
top = existing[recipe.top]
return existing[recipe.bottom], _flipped(top) if recipe.top_flip else top
def _search(recipe: InterfaceRecipe, l_b: _Points, l_t: _Points) -> dict[str, Any]:
if (recipe.bottom_matrix is None) != (recipe.top_matrix is None):
raise BuildRefused("give both bottom_matrix and top_matrix, or neither")
if recipe.bottom_matrix is not None and recipe.top_matrix is not None:
m_b = np.array(recipe.bottom_matrix, dtype=np.int64)
m_t = np.array(recipe.top_matrix, dtype=np.int64)
for name, m in (("bottom_matrix", m_b), ("top_matrix", m_t)):
if m.shape != (2, 2) or round(float(np.linalg.det(m))) < 1:
raise BuildRefused(f"{name} must be a 2x2 integer matrix with positive determinant")
s_b = (m_b @ l_b).astype(float)
result = _match(s_b, (m_t @ l_t).astype(float))
if result["mismatch"] > recipe.max_strain + 1e-12:
raise BuildRefused(
f"the given matrices mismatch by {result['mismatch']:.4%}, more than "
f"max_strain {recipe.max_strain:.2%}"
)
if (
recipe.twist_deg is not None
and abs(_wrap(result["rotation_deg"] - recipe.twist_deg)) > recipe.angle_tolerance_deg
):
raise BuildRefused(
f"the given matrices need the top phase turned by {result['rotation_deg']:.4f} "
f"deg, not {recipe.twist_deg} deg; set twist_deg or omit it (null)"
)
return {
"bottom_matrix": m_b.tolist(),
"top_matrix": m_t.tolist(),
"bottom_cells": round(float(np.linalg.det(m_b))),
"top_cells": round(float(np.linalg.det(m_t))),
"area_angstrom2": abs(float(np.linalg.det(s_b))),
"rotation_deg": result["rotation_deg"],
"principal_strains": result["principal"],
"mismatch": result["mismatch"],
"source": "given",
}
candidates = coincidence_cells(
l_b,
l_t,
max_area=recipe.max_area,
max_strain=recipe.max_strain,
twist_deg=recipe.twist_deg,
angle_tolerance_deg=recipe.angle_tolerance_deg,
max_candidates=recipe.match + 1,
)
if len(candidates) <= recipe.match:
twist = "any rotation" if recipe.twist_deg is None else f"twist {recipe.twist_deg} deg"
raise BuildRefused(
f"no coincidence cell (candidate {recipe.match}) within {recipe.max_area:g} square "
f"angstrom and {recipe.max_strain:.2%} strain at {twist}; raise max_area or "
"max_strain, free the twist, or give the matrices"
)
return {**candidates[recipe.match], "source": f"search candidate {recipe.match}"}
def _weight(recipe: InterfaceRecipe, mismatch: float) -> float:
allocation = recipe.strain_allocation
if allocation == "weighted":
if recipe.top_weight is None:
raise BuildRefused("strain_allocation weighted needs top_weight between 0 and 1")
return recipe.top_weight
if recipe.top_weight is not None:
raise BuildRefused("top_weight applies only to strain_allocation weighted")
if allocation == "none":
if mismatch > _EXACT:
raise BuildRefused(
f"the phases mismatch by {mismatch:.4%} on this cell; set strain_allocation "
"(bottom keeps the bottom lattice and strains the top, top the reverse, mean "
"or weighted shares it); no phase is strained without it"
)
return 0.0
return {"bottom": 0.0, "top": 1.0, "mean": 0.5}[allocation]
def _supercell_sites(structure: PeriodicStructure, matrix: list[list[int]]) -> list[PeriodicSite]:
from vibesketcher.document.periodic import supercell
m = [[matrix[0][0], matrix[0][1], 0], [matrix[1][0], matrix[1][1], 0], [0, 0, 1]]
return supercell(structure, m, identifier="interfacephase").sites
def _strain(f: _Points) -> dict[str, Any]:
_, _, left = _polar(f)
tensor = left - np.eye(2)
full = np.zeros((3, 3))
full[:2, :2] = tensor
principal = np.linalg.eigvalsh(tensor)
return {
"tensor": [[round(float(x), 12) for x in row] for row in full],
"principal": [round(float(x), 12) for x in principal],
"max_abs": round(float(np.max(np.abs(principal))), 12),
"area": round(float(np.linalg.det(f)) - 1, 12),
}
[docs]
def build_interface(recipe: InterfaceRecipe, document: Document) -> PeriodicStructure:
"""A heterointerface of two parent slabs, or a refusal with the reason."""
bottom, top = _parents(recipe, document)
l_b, c_b, _ = _slab_like(bottom, "bottom")
l_t, c_t, _ = _slab_like(top, "top")
cell = _search(recipe, l_b, l_t)
weight = _weight(recipe, cell["mismatch"])
m_b = np.array(cell["bottom_matrix"], dtype=float)
m_t = np.array(cell["top_matrix"], dtype=float)
s_b, s_t = m_b @ l_b, m_t @ l_t
rotation = _match(s_b, s_t)["rotation"]
common = s_b + weight * (s_t @ rotation.T - s_b)
atoms = cell["bottom_cells"] * len(bottom.sites) + cell["top_cells"] * len(top.sites)
if atoms > recipe.max_atoms:
raise BuildRefused(
f"the coincidence cell holds {atoms} atoms, more than max_atoms={recipe.max_atoms}"
)
phases = []
for role, parent, matrix, s, c in (
("bottom", bottom, cell["bottom_matrix"], s_b, c_b),
("top", top, cell["top_matrix"], s_t, c_t),
):
sites = _supercell_sites(parent, matrix)
f = np.array([s.fractional for s in sites], dtype=float)
xy = f[:, :2] @ common
z = f[:, 2] * c
deformation = (np.linalg.inv(s) @ common).T
phases.append((role, parent, sites, xy, z - z.min(), float(np.ptp(z)), deformation))
(_, _, _, xy_b, z_b, thick_b, f_b), (_, _, _, xy_t, z_t, thick_t, f_t) = phases
shift = np.asarray(recipe.translation, dtype=float) @ common
xy_t = xy_t + shift
gap2 = recipe.periodic_gap if recipe.periodic_gap is not None else recipe.gap
if recipe.periodicity == "3d":
base = gap2 / 2
length = thick_b + recipe.gap + thick_t + gap2
pbc = (True, True, True)
else:
if recipe.periodic_gap is not None:
raise BuildRefused("periodic_gap applies only to periodicity 3d")
base = recipe.vacuum / 2
length = thick_b + recipe.gap + thick_t + recipe.vacuum
pbc = (True, True, False)
lattice = np.zeros((3, 3))
lattice[:2, :2] = common
lattice[2, 2] = length
bottom_xyz = np.column_stack([xy_b, z_b + base])
top_xyz = np.column_stack([xy_t, z_t + base + thick_b + recipe.gap])
cartesian = np.vstack([bottom_xyz, top_xyz])
contact = _closest(bottom_xyz, top_xyz, lattice, pbc)
if contact < recipe.min_distance:
raise BuildRefused(
f"the closest interphase contact is {contact:.3f} angstrom, below min_distance "
f"{recipe.min_distance} angstrom; increase the gap or change the translation"
)
_check_collisions(cartesian, lattice, pbc, minimum=min(recipe.min_distance, 0.7))
sites_all = [*phases[0][2], *phases[1][2]]
roles = ["bottom"] * len(phases[0][2]) + ["top"] * len(phases[1][2])
parents = [bottom.id] * len(phases[0][2]) + [top.id] * len(phases[1][2])
symbols = [s.symbol for s in sites_all]
rows = []
ids = []
counter: Counter[str] = Counter()
for k, site in enumerate(sites_all):
counter[symbols[k]] += 1
ids.append(f"{symbols[k]}{counter[symbols[k]]}")
rows.append([ids[-1], roles[k], parents[k], site.parent_site, list(site.image)])
charges = [bottom.charge, top.charge]
charge = None if None in charges else sum(c for c in charges if c is not None)
dropped = len(bottom.bonds) + len(top.bonds)
convergence = [
"converge each phase's thickness (add layers until the target property changes "
"less than the stated tolerance); report the layers used",
"converge the vacuum (2-D) or the second interface's separation (3-D)",
f"strain sensitivity: this cell strains the phases by up to "
f"{max(_strain(f_b)['max_abs'], _strain(f_t)['max_abs']):.4%}; repeat on a lower-"
"strain or larger coincidence cell and with another strain_allocation",
"sample in-plane translations (registries) and terminations; this is one choice",
"relax the gap and positions (and the cell, when the allocation is not fixed by a "
"substrate) before reading energies",
"converge in-plane k-point sampling for the supercell",
]
if recipe.periodicity == "3d":
convergence.append("a 3-D cell holds two interfaces; they interact through each phase")
provenance = _provenance(
"interface",
recipe,
coincidence={
**cell,
"method": "Zur and McGill, J. Appl. Phys. 55, 378 (1984)",
},
strain_allocation=recipe.strain_allocation,
top_weight=weight,
strain={
"convention": "left stretch minus identity (Biot), interface frame; normal axis "
"not strained (no Poisson response)",
"bottom": _strain(f_b),
"top": _strain(f_t),
},
top_rotation_deg=_angle(_polar(f_t)[0]),
translation_fractional=list(recipe.translation),
translation_angstrom=[float(x) for x in shift],
gap_angstrom=recipe.gap,
periodic_gap_angstrom=gap2 if recipe.periodicity == "3d" else None,
thickness_angstrom={"bottom": thick_b, "top": thick_t},
closest_interphase_contact_angstrom=contact,
periodicity=recipe.periodicity,
interfaces_per_cell=2 if recipe.periodicity == "3d" else 1,
phases={
"bottom": _faces(bottom, False, "bottom"),
"top": _faces(top, recipe.top_flip, "top"),
},
site_map={
"columns": ["site", "phase", "parent_structure", "parent_site", "image"],
"rows": rows,
},
stoichiometry=dict(sorted(Counter(symbols).items())),
charge_spin="charge is the sum of both parents' stated charges (none when either "
"is unstated); no compensation chosen; spin not chosen",
bonds=f"no bonds authored; {dropped} parent bond(s) not carried (perceive them with "
"the periodic graph tools)",
not_claimed=NOT_CLAIMED,
convergence_requirements=convergence,
)
made = _geometry_structure(
recipe.identifier,
lattice,
pbc,
symbols,
cartesian,
[],
cell_setting="unspecified",
provenance=_jsonable(provenance),
charge=charge,
labels=ids,
)
sites = [
s.model_copy(update={"parent_site": site.parent_site, "image": site.image})
for s, site in zip(made.sites, sites_all, strict=True)
]
return made.model_copy(update={"sites": sites})
def _closest(
first: _Points, second: _Points, lattice: _Points, pbc: tuple[bool, bool, bool]
) -> float:
ranges = [(-1, 0, 1) if periodic else (0,) for periodic in pbc]
best = math.inf
for image in itertools.product(*ranges):
shifted = second + np.asarray(image, dtype=float) @ lattice
for start in range(0, len(first), 256):
block = first[start : start + 256]
d = np.linalg.norm(block[:, None, :] - shifted[None, :, :], axis=2)
best = min(best, float(d.min()))
return best
def _jsonable(value: Any) -> Any:
from vibesketcher.document.crystal import _json
return _json(value)
[docs]
def interface_matches(
document: Document,
bottom: str,
top: str,
*,
max_area: float = 150.0,
max_strain: float = 0.05,
twist_deg: float | None = 0.0,
angle_tolerance_deg: float = 0.5,
top_flip: bool = False,
max_candidates: int = 20,
) -> dict[str, Any]:
"""The ranked coincidence cells of two parent slabs, with atom counts; nothing is built."""
existing = {s.id: s for s in document.periodic_structures}
for name in (bottom, top):
if name not in existing:
raise BuildRefused(f"periodic structure {name!r} not found")
if not 0 <= max_strain <= _MAX_STRAIN:
raise BuildRefused(f"max_strain must be between 0 and {_MAX_STRAIN}")
if not 1 <= max_candidates <= 100:
raise BuildRefused("max_candidates must be between 1 and 100")
lower = existing[bottom]
upper = _flipped(existing[top]) if top_flip else existing[top]
l_b, _, _ = _slab_like(lower, "bottom")
l_t, _, _ = _slab_like(upper, "top")
candidates = coincidence_cells(
l_b,
l_t,
max_area=max_area,
max_strain=max_strain,
twist_deg=twist_deg,
angle_tolerance_deg=angle_tolerance_deg,
max_candidates=max_candidates,
)
for index, c in enumerate(candidates):
c["match"] = index
c["atoms"] = c["bottom_cells"] * len(lower.sites) + c["top_cells"] * len(upper.sites)
return {
"bottom": bottom,
"top": top,
"top_flip": top_flip,
"method": "Zur and McGill, J. Appl. Phys. 55, 378 (1984)",
"mismatch": "largest principal strain of the top phase when strained onto the bottom "
"lattice; the built strain depends on strain_allocation",
"candidates": candidates,
}
# --- stacking faults ---
[docs]
class StackingFaultRecipe(_Recipe):
"""An intrinsic, extrinsic or explicitly shifted fault in a stack of planes."""
kind: Literal["stacking_fault"] = "stacking_fault"
identifier: str = _ID
#: The bulk structure in the document; or give ``template`` (e.g. cu).
source: str | None = Field(default=None, pattern=r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")
template: str | None = None
template_a: float | None = Field(default=None, gt=0, allow_inf_nan=False)
#: The fault plane, in the bulk cell's rows (conventional cell for a template).
miller: tuple[int, int, int] = (1, 1, 1)
#: Atomic planes along the normal; a whole number of oriented bulk repeats.
planes: int = Field(default=12, ge=3, le=240)
fault: Literal["intrinsic", "extrinsic", "shift"]
#: ``shift`` only: the rigid in-plane displacement, fractions of the surface cell.
displacement: tuple[float, float] | None = None
#: Planes with this index and above (0 = bottom) are displaced; the middle by default.
fault_plane: int | None = Field(default=None, ge=1)
model: Literal["periodic", "slab"] = "periodic"
vacuum: float = Field(default=15.0, ge=3, le=200, allow_inf_nan=False)
repeat: tuple[int, int] = (1, 1)
#: The closest a fault may come to its periodic image (or twice to a free surface).
min_image_separation: float = Field(default=10.0, gt=0, le=200, allow_inf_nan=False)
plane_tolerance: float = Field(default=0.05, gt=0, le=0.5, allow_inf_nan=False)
min_distance: float = Field(default=1.0, gt=0.3, le=5, allow_inf_nan=False)
surface_cell: Literal["primitive", "given"] = "primitive"
def _bulk(recipe: StackingFaultRecipe, document: Document | None) -> PeriodicStructure:
if (recipe.source is None) == (recipe.template is None):
raise BuildRefused("give the bulk as source (a document structure) or template")
if recipe.template is not None:
from vibesketcher.document import crystal_templates
return crystal_templates.build(
recipe.template,
identifier=f"{recipe.identifier}-bulk",
cell="conventional",
a=recipe.template_a,
)
if recipe.template_a is not None:
raise BuildRefused("template_a needs a template")
existing = {s.id: s for s in (document.periodic_structures if document else [])}
if recipe.source not in existing:
raise BuildRefused(f"periodic structure {recipe.source!r} not found")
return existing[recipe.source]
def _oriented(
bulk: PeriodicStructure, miller: tuple[int, int, int], surface_cell: str
) -> tuple[_Points, list[tuple[str, str, _Points]], tuple[int, int, int], Any]:
"""Rotated rows (a1, a2 in-plane, c with the normal along z), sites and the transform."""
from vibesketcher.document import crystal, slab
if sum(bulk.pbc) != 3:
raise BuildRefused("a stacking fault is built in a three-dimensional bulk crystal")
reduced = slab._reduced(miller)
bravais = crystal._builder(bulk).get("bravais")
if (
surface_cell == "primitive"
and bulk.cell_setting == "conventional"
and isinstance(bravais, str)
and len(crystal.centring_vectors(bravais)) > 1
):
scaled = np.rint(6 * crystal.primitive_transform(bravais) @ np.asarray(reduced))
reduced = slab._reduced(tuple(int(x) for x in scaled)) # type: ignore[arg-type]
bulk = crystal.primitive_cell(bulk, bravais, identifier=bulk.id)
lattice = crystal.lattice_rows(bulk)
transform = slab.surface_transform(reduced, lattice)
oriented = transform @ lattice
e1 = oriented[0] / np.linalg.norm(oriented[0])
e3 = np.cross(oriented[0], oriented[1])
e3 /= np.linalg.norm(e3)
e2 = np.cross(e3, e1)
rotation = np.asarray([e1, e2, e3]).T
rows = oriented @ rotation
rows[:2, 2] = 0.0
inverse = np.linalg.inv(oriented)
sites = []
for site in bulk.sites:
frac = np.asarray(bulk.cartesian(site)) @ inverse
frac -= np.floor(frac + 1e-9)
sites.append((site.symbol, site.id, frac))
return rows, sites, reduced, transform
def _planes(
sites: list[tuple[str, str, _Points]], spacing: float, tolerance: float
) -> tuple[list[int], int, float]:
"""Plane index of every site in one repeat; the origin sits in the widest gap."""
heights = np.array([float(f[2]) * spacing for _, _, f in sites])
order = np.sort(heights)
gaps = np.diff(np.append(order, order[0] + spacing))
widest = int(np.argmax(gaps))
origin = (order[widest] + gaps[widest] / 2) % spacing
shifted = (heights - origin) % spacing
levels: list[float] = []
for h in np.sort(shifted):
if not levels or h - levels[-1] > tolerance:
levels.append(float(h))
index = [int(np.searchsorted(np.array(levels) + tolerance, h)) for h in shifted]
return index, len(levels), float(origin)
def _stacking_offset(
in_plane: _Points, plane_xy: list[_Points], symbols: list[list[str]]
) -> NDArray[np.float64] | None:
"""The fractional in-plane offset delta of an ABC close-packed stack, or None."""
if len(plane_xy) < 3 or len({tuple(sorted(s)) for s in symbols}) != 1:
return None
inverse = np.linalg.inv(in_plane)
def offset(first: _Points, second: _Points) -> NDArray[np.float64] | None:
f1, f2 = first @ inverse, second @ inverse
for candidate in f2 - f1[0]:
moved = (f1 + candidate) % 1.0
target = f2 % 1.0
d = np.abs(((moved[:, None, :] - target[None, :, :]) + 0.5) % 1.0 - 0.5)
if np.all(d.max(axis=2).min(axis=1) < 1e-4):
return np.asarray((candidate + 0.5) % 1.0 - 0.5)
return None
deltas = [offset(plane_xy[k], plane_xy[k + 1]) for k in range(2)]
if any(d is None for d in deltas):
return None
d0, d1 = deltas
assert d0 is not None and d1 is not None
if np.abs(((d0 - d1) + 0.5) % 1.0 - 0.5).max() > 1e-4:
return None
if np.abs(((3 * d0) + 0.5) % 1.0 - 0.5).max() > 1e-4 or np.abs(d0).max() < 1e-4:
return None
return d0
[docs]
def build_stacking_fault(
recipe: StackingFaultRecipe, document: Document | None = None
) -> PeriodicStructure:
"""A stacking-fault model with one fault per cell (periodic) or between surfaces (slab)."""
bulk = _bulk(recipe, document)
rows, cell_sites, miller_cell, transform = _oriented(bulk, recipe.miller, recipe.surface_cell)
spacing = float(rows[2, 2])
plane_of, per_repeat, origin = _planes(cell_sites, spacing, recipe.plane_tolerance)
if recipe.planes % per_repeat:
raise BuildRefused(
f"this cut repeats every {per_repeat} planes; planes={recipe.planes} is not a "
"whole number of repeats"
)
repeats = recipe.planes // per_repeat
total = recipe.planes
fault_plane = recipe.fault_plane if recipe.fault_plane is not None else total // 2
last = total - (2 if recipe.fault == "extrinsic" else 1)
if not 1 <= fault_plane <= last:
raise BuildRefused(f"fault_plane must be between 1 and {last} for {total} planes")
in_plane = rows[:2, :2]
base = []
for k in range(repeats):
for (symbol, parent, frac), plane in zip(cell_sites, plane_of, strict=True):
# A site below the origin belongs to the repeat above (a lattice translation).
lift = 1.0 if float(frac[2]) * spacing < origin else 0.0
f = frac + np.array([0.0, 0.0, k + lift])
base.append((symbol, parent, k * per_repeat + plane, f @ rows))
planes: dict[int, list[tuple[str, _Points]]] = {}
for symbol, _, plane, xyz in base:
planes.setdefault(plane, []).append((symbol, xyz[:2]))
first_three = [np.array([xy for _, xy in planes[p]]) for p in range(min(3, total))]
delta = _stacking_offset(
in_plane, first_three, [[s for s, _ in planes[p]] for p in range(min(3, total))]
)
if recipe.fault in ("intrinsic", "extrinsic"):
if recipe.displacement is not None:
raise BuildRefused(
"intrinsic and extrinsic faults take their displacement from the stack; "
"use fault shift for an explicit displacement"
)
if delta is None:
raise BuildRefused(
"intrinsic and extrinsic faults need an ABC close-packed stack (equal planes, "
"each the one below moved by one offset delta with 3 delta a lattice vector); "
"this cut is not one. Use fault shift with an explicit displacement"
)
step = delta
shifts = (
{fault_plane: step}
if recipe.fault == "intrinsic"
else {fault_plane: step, fault_plane + 1: step}
)
else:
if recipe.displacement is None:
raise BuildRefused("fault shift needs an explicit displacement (fractions of a, b)")
step = np.asarray(recipe.displacement, dtype=float)
shifts = {fault_plane: step}
total_shift = sum(shifts.values(), np.zeros(2))
displacement_xy = total_shift @ in_plane
xyz_all = []
symbols = []
parents = []
plane_index = []
for symbol, parent, plane, xyz in base:
moved = xyz.copy()
for start, s in shifts.items():
if plane >= start:
moved[:2] += s @ in_plane
xyz_all.append(moved)
symbols.append(symbol)
parents.append(parent)
plane_index.append(plane)
cartesian = np.array(xyz_all)
heights = [
float(np.mean([cartesian[i, 2] for i in range(len(base)) if plane_index[i] == p]))
for p in range(total)
]
fault_height = (heights[fault_plane - 1] + heights[fault_plane]) / 2
if recipe.fault == "extrinsic":
fault_height = heights[fault_plane]
n1, n2 = recipe.repeat
if not (1 <= n1 <= 20 and 1 <= n2 <= 20):
raise BuildRefused("repeat must be two integers between 1 and 20")
if recipe.model == "periodic":
c_row = repeats * rows[2] + np.append(displacement_xy, 0.0)
separation = repeats * spacing
if separation < recipe.min_image_separation:
raise BuildRefused(
f"the fault is {separation:.2f} angstrom from its periodic image, less than "
f"min_image_separation {recipe.min_image_separation} angstrom; add planes"
)
pbc = (True, True, True)
lattice = np.array([n1 * rows[0], n2 * rows[1], c_row])
separations = {"periodic_image_angstrom": separation}
else:
cartesian[:, 2] -= cartesian[:, 2].min()
top = float(cartesian[:, 2].max())
fault_height -= heights[0]
below, above = fault_height, top - fault_height
if min(below, above) < recipe.min_image_separation / 2:
raise BuildRefused(
f"the fault is {min(below, above):.2f} angstrom from a free surface, less than "
f"half of min_image_separation {recipe.min_image_separation} angstrom; add "
"planes or move fault_plane"
)
cartesian[:, 2] += recipe.vacuum / 2
pbc = (True, True, False)
lattice = np.array([n1 * rows[0], n2 * rows[1], [0.0, 0.0, top + recipe.vacuum]])
separations = {"to_bottom_surface_angstrom": below, "to_top_surface_angstrom": above}
# In-plane repeats.
cells = [(i, j) for j in range(n2) for i in range(n1)]
big = np.vstack([cartesian + i * rows[0] + j * rows[1] for i, j in cells])
symbols_all = symbols * len(cells)
parents_all = parents * len(cells)
planes_all = plane_index * len(cells)
if len(symbols_all) > MAX_ATOMS:
raise BuildRefused(f"{len(symbols_all)} sites exceed the {MAX_ATOMS}-atom limit")
_check_collisions(big, lattice, pbc, minimum=recipe.min_distance)
sequence, hc = (None, None)
if delta is not None and recipe.fault != "shift":
sequence, hc = _sequence(in_plane, delta, planes, shifts, total, recipe.model)
convergence = [
"converge the fault energy with the number of planes (fault-image or fault-surface "
"separation) and with in-plane k-point sampling",
"the displacement is rigid: relax positions (at least along the normal) before reading "
"a fault energy; a relaxed fault may also shift in-plane",
"the bulk lattice parameter is the parent's; use the method's own equilibrium lattice",
]
if recipe.model == "slab":
convergence.append("a slab model adds two free surfaces; converge the vacuum too")
provenance = _provenance(
"stacking_fault",
recipe,
source=bulk.id if recipe.source else None,
template=recipe.template,
miller_in_cell=list(miller_cell),
surface_transform=transform,
planes_per_repeat=per_repeat,
planes=total,
plane_spacing_angstrom=spacing / per_repeat,
fault=recipe.fault,
fault_plane=fault_plane,
fault_height_angstrom=fault_height,
stacking_offset_fractional=None if delta is None else [float(x) for x in delta],
stacking_offset_angstrom=None if delta is None else float(np.linalg.norm(delta @ in_plane)),
displacement_fractional=[float(x) for x in total_shift],
displacement_angstrom=[float(x) for x in displacement_xy],
displacement_length_angstrom=float(np.linalg.norm(displacement_xy)),
shifted_planes={str(k): [float(x) for x in v] for k, v in shifts.items()},
stacking_sequence=sequence,
hc_notation=hc,
model=recipe.model,
cell="c tilted by the total displacement: one fault per cell"
if recipe.model == "periodic"
else "slab with vacuum: one fault between free surfaces",
separations=separations,
site_map={"columns": ["site", "parent_site", "plane"], "rows": []},
references=[
"V. Vitek, Philos. Mag. 18, 773 (1968)",
"J. P. Hirth and J. Lothe, Theory of Dislocations, 2nd ed. (Wiley, 1982)",
],
charge_spin="the bulk's stated charge per cell scaled to the model; spin not chosen",
not_claimed=NOT_CLAIMED,
convergence_requirements=convergence,
)
counter: Counter[str] = Counter()
ids = []
for symbol in symbols_all:
counter[symbol] += 1
ids.append(f"{symbol}{counter[symbol]}")
provenance["builder"]["site_map"]["rows"] = [
[i, p, k] for i, p, k in zip(ids, parents_all, planes_all, strict=True)
]
charge = None
if bulk.charge is not None:
charge = bulk.charge * len(symbols_all) // max(1, len(bulk.sites))
made = _geometry_structure(
recipe.identifier,
lattice,
pbc,
symbols_all,
big,
[],
cell_setting="unspecified",
provenance=_jsonable(provenance),
charge=charge,
labels=ids,
)
sites = [
s.model_copy(update={"parent_site": p})
for s, p in zip(made.sites, parents_all, strict=True)
]
return made.model_copy(update={"sites": sites})
def _sequence(
in_plane: _Points,
delta: NDArray[np.float64],
planes: dict[int, list[tuple[str, _Points]]],
shifts: dict[int, NDArray[np.float64]],
total: int,
model: str,
) -> tuple[str, str]:
"""ABC labels of every plane after the fault, and the Frank h/c notation."""
inverse = np.linalg.inv(in_plane)
reference = planes[0][0][1] @ inverse
labels = []
for p in range(total):
position = planes[p][0][1] @ inverse
for start, s in shifts.items():
if p >= start:
position = position + s
for k in range(3):
if np.abs(((position - reference - k * delta) + 0.5) % 1.0 - 0.5).max() < 1e-4:
labels.append("ABC"[k])
break
else: # pragma: no cover - planes of an ABC stack are A, B or C
labels.append("?")
total_label = sum(shifts.values(), np.zeros(2))
image = None
for k in range(3):
if np.abs(((total_label - k * delta) + 0.5) % 1.0 - 0.5).max() < 1e-4:
image = "ABC"[k]
hc = []
for p in range(total):
if model == "periodic":
below = labels[p - 1] if p > 0 else _relabel(labels[-1], image, back=True)
above = labels[p + 1] if p < total - 1 else _relabel(labels[0], image, back=False)
else:
if p in (0, total - 1):
hc.append("-")
continue
below, above = labels[p - 1], labels[p + 1]
hc.append("h" if below == above else "c")
return "".join(labels), "".join(hc)
def _relabel(label: str, image: str | None, *, back: bool) -> str:
"""The label of a plane one tilted period away (shifted by the total displacement)."""
if image is None: # pragma: no cover - named faults shift by multiples of delta
return label
step = "ABC".index(image)
return "ABC"[("ABC".index(label) + (-step if back else step)) % 3]
# --- planned extended defects ---
class _Plan(BaseModel):
model_config = ConfigDict(extra="forbid")
source: str | None = None
template: str | None = None
notes: str | None = Field(default=None, max_length=2000)
class GrainBoundaryPlan(_Plan):
"""A grain boundary to plan: every geometric and boundary assumption is explicit."""
kind: Literal["grain_boundary"] = "grain_boundary"
rotation_axis: tuple[int, int, int] | None = None
misorientation_deg: float | None = Field(default=None, gt=0, lt=180, allow_inf_nan=False)
sigma: int | None = Field(default=None, ge=1, le=999)
boundary_plane: tuple[int, int, int] | None = None
boundary_type: Literal["tilt", "twist", "mixed"] | None = None
#: periodic_bicrystal (two boundaries per cell) or vacuum_bicrystal (free surfaces).
boundary_conditions: Literal["periodic_bicrystal", "vacuum_bicrystal"] | None = None
#: The rigid translation of one grain, fractions of the boundary cell, or "sampled".
translation: tuple[float, float, float] | Literal["sampled"] | None = None
class DislocationPlan(_Plan):
"""A dislocation to plan: Burgers vector, line direction and boundary/elastic model."""
kind: Literal["dislocation"] = "dislocation"
#: In fractions of the bulk cell rows (e.g. [0.5, 0.5, 0] for a/2 [110] in fcc).
burgers_vector: tuple[float, float, float] | None = None
#: Integer direction in the bulk cell rows.
line_direction: tuple[int, int, int] | None = None
glide_plane: tuple[int, int, int] | None = None
boundary_conditions: (
Literal[
"dipole_periodic",
"quadrupole_periodic",
"cylinder_fixed_boundary",
"slab_free_surfaces",
]
| None
) = None
elastic_model: Literal["isotropic", "anisotropic", "none"] | None = None
poisson_ratio: float | None = Field(default=None, gt=-1, lt=0.5, allow_inf_nan=False)
#: Voigt 6x6 elastic constants, GPa (anisotropic only).
elastic_constants_gpa: list[list[float]] | None = None
core_model: Literal["unspecified", "compact", "dissociated"] | None = None
def _refusal(code: str, message: str) -> dict[str, str]:
return {"code": code, "message": message}
[docs]
def plan_extended_defect(data: dict[str, Any], document: Document | None = None) -> dict[str, Any]:
"""A planned-only grain-boundary or dislocation record, or coded refusals.
No atoms are placed. The plan is admitted only when its assumptions are
complete; a missing item is a refusal with a stable code, never a default.
"""
kind = data.get("kind")
model: type[GrainBoundaryPlan] | type[DislocationPlan]
if kind == "grain_boundary":
model = GrainBoundaryPlan
elif kind == "dislocation":
model = DislocationPlan
else:
return {
"planned": False,
"refused": True,
"refusals": [_refusal("plan.kind", "kind must be grain_boundary or dislocation")],
}
try:
plan = model.model_validate(data)
except ValidationError as error:
return {
"planned": False,
"refused": True,
"refusals": [
_refusal("plan.invalid", f"{'.'.join(str(x) for x in e['loc'])}: {e['msg']}")
for e in error.errors()
],
}
refusals: list[dict[str, str]] = []
lattice = None
if (plan.source is None) == (plan.template is None):
refusals.append(_refusal("plan.parent", "name the bulk as source or template"))
elif plan.source is not None:
found = {s.id: s for s in (document.periodic_structures if document else [])}
if plan.source not in found:
refusals.append(
_refusal("plan.parent", f"periodic structure {plan.source!r} not found")
)
else:
lattice = np.asarray(found[plan.source].lattice_angstrom, dtype=float)
else:
from vibesketcher.document import crystal_templates
try:
bulk = crystal_templates.build(
plan.template or "", identifier="planbulk", cell="conventional"
)
lattice = np.asarray(bulk.lattice_angstrom, dtype=float)
except (KeyError, ValueError) as error:
refusals.append(_refusal("plan.parent", str(error)))
record: dict[str, Any] = {"kind": plan.kind, "parent": plan.source or plan.template}
if isinstance(plan, GrainBoundaryPlan):
refusals += _grain_boundary(plan, record)
else:
refusals += _dislocation(plan, record, lattice)
if refusals:
return {"planned": False, "refused": True, "refusals": refusals}
record.update(
{
"status": "planned only: no structure is built",
"not_claimed": NOT_CLAIMED + ["validated mechanics or core structure"],
"convergence_requirements": _plan_convergence(plan),
"references": [
"J. P. Hirth and J. Lothe, Theory of Dislocations, 2nd ed. (Wiley, 1982)"
],
"notes": plan.notes,
}
)
return {"planned": True, "refused": False, "record": record}
def _grain_boundary(plan: GrainBoundaryPlan, record: dict[str, Any]) -> list[dict[str, str]]:
out = []
if plan.rotation_axis is None or not any(plan.rotation_axis):
out.append(_refusal("gb.rotation_axis", "state the misorientation axis [u, v, w]"))
if plan.misorientation_deg is None and plan.sigma is None:
out.append(_refusal("gb.misorientation", "state misorientation_deg or the CSL sigma"))
if plan.boundary_plane is None or not any(plan.boundary_plane):
out.append(_refusal("gb.boundary_plane", "state the boundary plane (h, k, l)"))
if plan.boundary_type is None:
out.append(_refusal("gb.boundary_type", "state tilt, twist or mixed"))
if plan.boundary_conditions is None:
out.append(
_refusal(
"gb.boundary_conditions",
"state periodic_bicrystal (two boundaries per cell) or "
"vacuum_bicrystal (free surfaces)",
)
)
if plan.translation is None:
out.append(_refusal("gb.translation", "state the rigid grain translation or 'sampled'"))
if out:
return out
axis, normal = np.asarray(plan.rotation_axis), np.asarray(plan.boundary_plane)
dot = int(axis @ normal)
implied = (
"tilt" if dot == 0 else "twist" if np.linalg.norm(np.cross(axis, normal)) == 0 else "mixed"
)
record.update(
{
"rotation_axis": list(axis),
"misorientation_deg": plan.misorientation_deg,
"sigma": plan.sigma,
"boundary_plane": list(normal),
"boundary_type": plan.boundary_type,
"index_relation": f"axis . plane = {dot} (index-space check, exact for cubic cells)",
"index_implied_type": implied,
"boundary_conditions": plan.boundary_conditions,
"translation": plan.translation,
"builder": "not implemented: a CSL bicrystal builder is planned, not available",
}
)
return []
def _dislocation(
plan: DislocationPlan, record: dict[str, Any], lattice: _Points | None
) -> list[dict[str, str]]:
out = []
if plan.burgers_vector is None or not any(plan.burgers_vector):
out.append(_refusal("dislocation.burgers_vector", "state the Burgers vector"))
if plan.line_direction is None or not any(plan.line_direction):
out.append(_refusal("dislocation.line_direction", "state the line direction [u, v, w]"))
if plan.boundary_conditions is None:
out.append(
_refusal(
"dislocation.boundary_conditions",
"state dipole_periodic, quadrupole_periodic, "
"cylinder_fixed_boundary or slab_free_surfaces",
)
)
if plan.elastic_model is None:
out.append(
_refusal(
"dislocation.elastic_model",
"state the elastic model for the far field (isotropic, anisotropic or none)",
)
)
elif plan.elastic_model == "isotropic" and plan.poisson_ratio is None:
out.append(_refusal("dislocation.poisson_ratio", "an isotropic field needs poisson_ratio"))
elif plan.elastic_model == "anisotropic":
c = plan.elastic_constants_gpa
if c is None or len(c) != 6 or any(len(row) != 6 for row in c):
out.append(
_refusal(
"dislocation.elastic_constants",
"an anisotropic field needs the 6x6 Voigt elastic constants",
)
)
if plan.core_model is None:
out.append(
_refusal(
"dislocation.core_model",
"state the core assumption (unspecified, compact or dissociated)",
)
)
if out or lattice is None:
return out
assert plan.burgers_vector is not None and plan.line_direction is not None
b = np.asarray(plan.burgers_vector, dtype=float) @ lattice
xi = np.asarray(plan.line_direction, dtype=float) @ lattice
xi /= np.linalg.norm(xi)
screw = float(b @ xi)
edge = float(np.linalg.norm(b - screw * xi))
angle = math.degrees(math.atan2(edge, abs(screw)))
character = "screw" if edge < 1e-6 else "edge" if abs(screw) < 1e-6 else "mixed"
if plan.glide_plane is not None:
normal = np.asarray(plan.glide_plane, dtype=float) @ np.linalg.inv(lattice).T
normal /= np.linalg.norm(normal)
if abs(float(normal @ xi)) > 1e-6 or (edge > 1e-6 and abs(float(normal @ b)) > 1e-6):
out.append(
_refusal(
"dislocation.glide_plane",
"the glide plane must contain both the line direction and the Burgers vector",
)
)
return out
record.update(
{
"burgers_vector_fractional": list(plan.burgers_vector),
"burgers_vector_angstrom": [float(x) for x in b],
"burgers_length_angstrom": float(np.linalg.norm(b)),
"line_direction": list(plan.line_direction),
"glide_plane": plan.glide_plane,
"character": character,
"angle_b_line_deg": angle,
"screw_component_angstrom": abs(screw),
"edge_component_angstrom": edge,
"boundary_conditions": plan.boundary_conditions,
"elastic_model": plan.elastic_model,
"poisson_ratio": plan.poisson_ratio,
"elastic_constants_gpa": plan.elastic_constants_gpa,
"core_model": plan.core_model,
"builder": "not implemented: an elastic-field dislocation builder is planned, not "
"available",
}
)
return out
def _plan_convergence(plan: GrainBoundaryPlan | DislocationPlan) -> list[str]:
if isinstance(plan, GrainBoundaryPlan):
return [
"converge the grain thickness between boundaries (boundary-image separation)",
"sample rigid translations and boundary-plane atom densities",
"relax positions and the cell length normal to the boundary",
]
return [
"converge the dislocation-image separation (cell size) and the boundary region",
"converge the elastic far field against the stated elastic model",
"relax the core; the elastic displacement field is only a starting guess",
]
# --- preview ---
[docs]
def preview(
recipe: InterfaceRecipe | StackingFaultRecipe, document: Document | None
) -> dict[str, Any]:
"""Build without storing: the record and structure, or a refusal with the reason."""
from vibesketcher.document import new_document
try:
if isinstance(recipe, InterfaceRecipe):
made = build_interface(recipe, document or new_document())
else:
made = build_stacking_fault(recipe, document)
except ValueError as error:
return {"refused": True, "reason": str(error)}
return {
"refused": False,
"sites": len(made.sites),
"pbc": list(made.pbc),
"lattice_angstrom": [list(row) for row in made.lattice_angstrom],
"record": made.provenance.get("builder"),
"structure": made.model_dump(mode="json"),
}