vibe-sketcherDocumentation

Source code for vibesketcher.document.grain_boundaries

"""Symmetric tilt grain boundaries in cubic crystals: CSL bicrystals (#197).

A symmetric tilt boundary on the plane (hkl), tilted about an axis [uvw] in
that plane (u h + v k + w l = 0), is built as a bicrystal whose second grain
is the mirror image of the first in the boundary plane. In a centrosymmetric
crystal the mirror image is the first grain rotated by 180 degrees about the
boundary normal, so both grains are the same crystal and the boundary is a
coincidence-site-lattice (CSL) boundary. Its Sigma is the least common
denominator of the rotation in the cubic basis (Grimmer, Acta Cryst. A30, 685
(1974), doi:10.1107/S0567739474001719); for the 180 degree rotation about
[hkl], ``R = 2 n n^T / N - I`` with ``N = h^2 + k^2 + l^2``, which gives the
odd part of N. The same misorientation is the tilt by theta about [uvw]
found among the 24 cubic rotations; theta agrees with Ranganathan's
``Sigma = m^2 + N_axis n^2``, ``theta = 2 atan(n sqrt(N_axis) / m)``
(Acta Cryst. 21, 197 (1966), doi:10.1107/S0365110X66002615). A plane
whose mirror is a symmetry of the cubic lattice (Sigma 1, such as (100) or
(110)) makes no boundary and is refused, as are polar crystals, whose
mirror image is not a rotated copy (it would invert the polarity).

Construction (Sutton and Balluffi, Interfaces in Crystalline Materials,
Oxford 1995, ch. 1-4):

- The boundary frame has x along [uvw], z along the boundary normal [hkl] and
  y = z x x. Each is spanned by the shortest lattice vector along that
  direction (centring included), so the orthogonal box is a supercell of the
  crystal.
- Grain A fills ``0 <= z <= L``, with ``L`` a whole number of lattice periods
  along [hkl]. The atoms on the boundary planes (z = 0 and z = L) are grain
  A's; grain B is their mirror image, without those planes.
- ``periodic``: grain B fills ``L < z < 2L``, so the cell holds two
  equivalent boundaries, at z = 0 and z = L. ``slab``: grain B fills
  ``-L <= z < 0`` and the bicrystal has free surfaces and vacuum.
- ``translation`` shifts grain B rigidly in the boundary plane (fractions of
  the boundary cell). Atoms closer than ``min_distance`` are refused, never
  merged or removed silently.

The model is an unrelaxed starting geometry. Neither the boundary's
translation state, its atomic density nor its energy is optimised, and the
record says so.
"""

from __future__ import annotations

import itertools
import math
from collections import Counter
from fractions import Fraction
from functools import reduce
from typing import Any, Literal

import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field

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, PeriodicStructure
from vibesketcher.limits import MAX_ATOMS

__all__ = ["GrainBoundaryRecipe", "build_grain_boundary", "csl_tilt"]

_Points = NDArray[np.float64]
_TOL = 1e-6

#: The centrings a conventional cubic cell may carry, as fractions of its rows.
_CENTRINGS = {
    "cP": [(0.0, 0.0, 0.0)],
    "cI": [(0.0, 0.0, 0.0), (0.5, 0.5, 0.5)],
    "cF": [(0.0, 0.0, 0.0), (0.0, 0.5, 0.5), (0.5, 0.0, 0.5), (0.5, 0.5, 0.0)],
}

NOT_CLAIMED = [
    "relaxation (positions, or the cell length normal to the boundary)",
    "the boundary's lowest-energy rigid translation or atomic density",
    "grain-boundary energy, segregation or mobility",
]

REFERENCES = [
    "H. Grimmer, Acta Cryst. A30, 685 (1974), doi:10.1107/S0567739474001719",
    "S. Ranganathan, Acta Cryst. 21, 197 (1966), doi:10.1107/S0365110X66002615",
    "A. P. Sutton and R. W. Balluffi, Interfaces in Crystalline Materials (Oxford, 1995)",
]


[docs] class GrainBoundaryRecipe(BaseModel): """A symmetric tilt CSL boundary of a cubic crystal; every choice is stated.""" model_config = ConfigDict(extra="forbid") kind: Literal["grain_boundary"] = "grain_boundary" identifier: str = Field(pattern=r"^[A-Za-z][A-Za-z0-9_-]{0,63}$") #: The cubic bulk in the document (conventional cell); or give ``template``. 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 tilt axis [uvw], in the conventional cubic cell; it lies in the boundary plane. rotation_axis: tuple[int, int, int] #: The boundary plane (hkl) of grain A (and, mirrored, of grain B). boundary_plane: tuple[int, int, int] #: If stated, checked against the construction: the CSL Sigma ... sigma: int | None = Field(default=None, ge=3, le=999) #: ... and the tilt angle about the axis, in degrees. misorientation_deg: float | None = Field(default=None, gt=0, lt=180, allow_inf_nan=False) #: Lattice periods along the normal in each grain; by default the fewest #: that keep boundaries (or a boundary and a surface) min_image_separation apart. repeats: int | None = Field(default=None, ge=1, le=200) model: Literal["periodic", "slab"] = "periodic" vacuum: float = Field(default=15.0, ge=3, le=200, allow_inf_nan=False) #: Rigid in-plane shift of grain B: fractions of the boundary cell along x (the axis) and y. translation: tuple[float, float] = (0.0, 0.0) #: In-plane repeats of the boundary cell along x (the axis) and y. repeat: tuple[int, int] = (1, 1) min_image_separation: float = Field(default=10.0, gt=0, le=200, allow_inf_nan=False) #: The closest two atoms may come; by default 0.6 of the bulk nearest-neighbour distance. min_distance: float | None = Field(default=None, gt=0.3, le=5, allow_inf_nan=False)
def _gcd(values: tuple[int, ...] | list[int]) -> int: return reduce(math.gcd, (abs(v) for v in values)) def _reduced(direction: tuple[int, int, int], name: str) -> tuple[int, int, int]: g = _gcd(direction) if g == 0: raise BuildRefused(f"the {name} needs a nonzero index") return (direction[0] // g, direction[1] // g, direction[2] // g) def _cubic_rotations() -> list[NDArray[np.int64]]: """The 24 proper rotations of the cube as integer matrices.""" out = [] for perm in itertools.permutations(range(3)): for signs in itertools.product((1, -1), repeat=3): m = np.zeros((3, 3), dtype=np.int64) for row, (col, sign) in enumerate(zip(perm, signs, strict=True)): m[row, col] = sign if round(np.linalg.det(m)) == 1: out.append(m) return out def _angle_axis(rotation: _Points) -> tuple[float, _Points]: cosine = max(-1.0, min(1.0, (float(np.trace(rotation)) - 1) / 2)) angle = math.degrees(math.acos(cosine)) skew = np.asarray( [ rotation[2, 1] - rotation[1, 2], rotation[0, 2] - rotation[2, 0], rotation[1, 0] - rotation[0, 1], ] ) if np.linalg.norm(skew) > 1e-9: return angle, skew / np.linalg.norm(skew) # 0 or 180 degrees: the axis is an eigenvector with eigenvalue 1. values, vectors = np.linalg.eigh((rotation + rotation.T) / 2) return angle, np.real(vectors[:, int(np.argmax(values))])
[docs] def csl_tilt( rotation_axis: tuple[int, int, int], boundary_plane: tuple[int, int, int] ) -> dict[str, Any]: """Sigma, tilt angle and disorientation of the symmetric tilt boundary (hkl)[uvw]. Pure lattice geometry for a cubic crystal; raises :class:`BuildRefused` when the axis is not in the plane or the plane makes no boundary. """ axis = _reduced(rotation_axis, "rotation axis") plane = _reduced(boundary_plane, "boundary plane") if sum(a * p for a, p in zip(axis, plane, strict=True)) != 0: raise BuildRefused( f"a symmetric tilt boundary needs the axis in the boundary plane: " f"[{' '.join(map(str, axis))}] . ({' '.join(map(str, plane))}) is not 0; twist and " "mixed boundaries are planned only (plan_extended_defect)" ) n_squared = sum(p * p for p in plane) # 180 degrees about the plane normal, exactly, in the cubic basis. exact = [ [Fraction(2 * plane[i] * plane[j], n_squared) - (1 if i == j else 0) for j in range(3)] for i in range(3) ] sigma = reduce(math.lcm, (entry.denominator for row in exact for entry in row)) odd = n_squared while odd % 2 == 0: odd //= 2 if sigma == 1: raise BuildRefused( f"({' '.join(map(str, plane))}) is a mirror plane of the cubic lattice (Sigma 1): " "the two grains would be the same crystal, with no boundary" ) rotation = np.asarray([[float(x) for x in row] for row in exact]) u = np.asarray(axis, dtype=float) / math.sqrt(sum(a * a for a in axis)) tilts = [] angles = [] for symmetry in _cubic_rotations(): equivalent = rotation @ symmetry angle, about = _angle_axis(equivalent) angles.append((angle, about)) if np.allclose(equivalent @ u, u, atol=1e-9) and angle > 1e-6: sign = 1.0 if about @ u > 0 else -1.0 tilts.append(angle if sign > 0 else 360.0 - angle) if not tilts: # pragma: no cover - the 180 degree rotation itself fixes no axis in the plane raise BuildRefused("no rotation about the stated axis relates the two grains") # One misorientation, several tilt angles about the axis that cubic # symmetry makes equivalent (e.g. 36.87 and 53.13 degrees for Sigma 5 # about [001]); tables quote whichever their convention picks. tilt_angles = sorted({round(min(t, 360.0 - t), 9) for t in tilts}) smallest, about = min(angles, key=lambda item: item[0]) return { "rotation_axis": list(axis), "boundary_plane": list(plane), "sigma": sigma, "sigma_check": f"odd part of h^2 + k^2 + l^2 = {n_squared}: {odd}", "tilt_deg": tilt_angles[0], "tilt_angles_deg": tilt_angles, "disorientation_deg": smallest, "disorientation_axis": [float(x) for x in about], "rotation_exact": [[str(x) for x in row] for row in exact], }
def _bulk(recipe: GrainBoundaryRecipe, 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 _sites(bulk: PeriodicStructure) -> list[tuple[str, str, _Points]]: out = [] for site in bulk.sites: if site.occupancy < 1: raise BuildRefused(f"site {site.id} is partly occupied; resolve the disorder first") frac = np.asarray(site.fractional, dtype=float) out.append((site.symbol, site.id, frac - np.floor(frac + 1e-9))) return out def _maps_onto( sites: list[tuple[str, str, _Points]], moved: list[_Points], centrings: list[_Points] ) -> bool: """Whether the moved positions are the sites again, species kept, modulo the lattice.""" for (symbol, _, _), position in zip(sites, moved, strict=True): if not any( other == symbol and any( np.allclose(((position - frac - c + 0.5) % 1.0) - 0.5, 0, atol=1e-4) for c in centrings ) for other, _, frac in sites ): return False return True def _cubic(bulk: PeriodicStructure) -> tuple[float, list[_Points]]: """The cubic cell length and its centring translations (fractions).""" from vibesketcher.document import crystal if sum(bulk.pbc) != 3: raise BuildRefused("a grain boundary is built in a three-dimensional bulk crystal") rows = crystal.lattice_rows(bulk) a = float(np.linalg.norm(rows[0])) if not np.allclose(rows, a * np.eye(3), atol=1e-6 * a): raise BuildRefused( "a symmetric tilt boundary is built from a cubic crystal in its conventional cell, " "rows a(1,0,0), a(0,1,0), a(0,0,1) (cell: conventional)" ) sites = _sites(bulk) candidates = [np.asarray(c) for c in _CENTRINGS["cF"] + _CENTRINGS["cI"][1:]] centrings = [ c for c in candidates if _maps_onto(sites, [f + c for _, _, f in sites], [np.zeros(3)]) ] return a, centrings def _centrosymmetric(sites: list[tuple[str, str, _Points]], centrings: list[_Points]) -> bool: first = sites[0][2] for _, _, other in sites: centre = (first + other) / 2 for c in centrings: # Inversion through centre (+ half a centring: those are centres too). point = centre + c / 2 if _maps_onto(sites, [2 * point - f for _, _, f in sites], centrings): return True return False def _period(direction: tuple[int, int, int], centrings: list[_Points]) -> _Points: """The shortest lattice vector along an integer direction, as conventional fractions.""" d = np.asarray(direction, dtype=float) for scale in (0.5, 1.0): v = scale * d if any(np.allclose(v - c, np.rint(v - c), atol=1e-9) for c in centrings): return v return d # pragma: no cover - an integer vector is always a lattice vector def _closest(cartesian: _Points, lattice: _Points, pbc: tuple[bool, bool, bool]) -> float: """The shortest interatomic distance in the (orthogonal) cell, periodic images included.""" shifts = [ np.asarray(n, dtype=float) @ lattice for n in itertools.product(*((-1, 0, 1) if p else (0,) for p in pbc)) ] best = math.inf for shift in shifts: delta = cartesian[None, :, :] + shift - cartesian[:, None, :] distance = np.linalg.norm(delta, axis=-1) if not np.any(shift): np.fill_diagonal(distance, math.inf) best = min(best, float(distance.min())) return best
[docs] def build_grain_boundary( recipe: GrainBoundaryRecipe, document: Document | None = None ) -> PeriodicStructure: """The bicrystal with its CSL record; raises :class:`BuildRefused` with the reason.""" geometry = csl_tilt(recipe.rotation_axis, recipe.boundary_plane) if recipe.sigma is not None and recipe.sigma != geometry["sigma"]: raise BuildRefused( f"the ({' '.join(map(str, geometry['boundary_plane']))}) symmetric tilt boundary is " f"Sigma {geometry['sigma']}, not Sigma {recipe.sigma}" ) stated = recipe.misorientation_deg if stated is not None and all(abs(stated - t) > 0.01 for t in geometry["tilt_angles_deg"]): angles = ", ".join(f"{t:.4f}" for t in geometry["tilt_angles_deg"]) raise BuildRefused( f"this boundary is a tilt of {angles} degrees (equivalent by cubic symmetry) about " f"the axis, not {stated:g}" ) bulk = _bulk(recipe, document) a, centrings = _cubic(bulk) sites = _sites(bulk) if not _centrosymmetric(sites, centrings): raise BuildRefused( f"{bulk.id} is not centrosymmetric: its mirror image is not a rotated copy of it, " "so the mirror bicrystal would invert the polarity; polar boundaries are not built" ) axis = tuple(geometry["rotation_axis"]) plane = tuple(geometry["boundary_plane"]) third = np.cross(np.asarray(plane), np.asarray(axis)) y_direction = _reduced((int(third[0]), int(third[1]), int(third[2])), "in-plane direction") tx, ty, tz = (_period(d, centrings) * a for d in (axis, y_direction, plane)) # Cartesian lx, ly, period = (float(np.linalg.norm(v)) for v in (tx, ty, tz)) frame = np.asarray([tx / lx, ty / ly, tz / period]) # rows: x, y, z # Two boundaries L apart (periodic), or a boundary L from each surface (slab). repeats = recipe.repeats or max(1, math.ceil(recipe.min_image_separation / period - 1e-9)) thickness = repeats * period if thickness < recipe.min_image_separation - 1e-9: raise BuildRefused( f"{repeats} period(s) of {period:.3f} angstrom put the boundary {thickness:.3f} " f"angstrom from its image, below min_image_separation " f"{recipe.min_image_separation:g}; raise repeats" ) box = np.asarray([tx, ty, repeats * tz]) expected = len(sites) * abs(np.linalg.det(box)) / a**3 if ( abs(expected - round(expected)) > 1e-6 ): # pragma: no cover - lattice vectors span a supercell raise BuildRefused("the boundary cell is not a supercell of the crystal") # Grain A: every atom of the crystal in 0 <= x < lx, 0 <= y < ly, 0 <= z <= L. corners = np.asarray(list(itertools.product((0, 1), repeat=3)), dtype=float) @ box / a low = np.floor(corners.min(axis=0)) - 1 high = np.ceil(corners.max(axis=0)) + 1 if np.prod(high - low + 1) * len(sites) > 4 * MAX_ATOMS: raise BuildRefused("the boundary cell is too large; lower repeats") shifts = np.asarray( list( itertools.product( *(range(int(lo), int(hi) + 1) for lo, hi in zip(low, high, strict=True)) ) ), dtype=float, ) grain: list[tuple[str, str, _Points]] = [] seen: set[tuple[int, int, int]] = set() for symbol, parent, frac in sites: points = (frac + shifts) * a @ frame.T # x, y, z in the boundary frame for x, y, z in points: if z < -_TOL or z > thickness + _TOL: continue fx, fy = (x / lx) % 1.0, (y / ly) % 1.0 fx, fy = (0.0 if abs(f - 1) < 1e-9 else f for f in (fx, fy)) key = (round(fx * 1e6), round(fy * 1e6), round(z * 1e6)) if key in seen: continue seen.add(key) grain.append( (symbol, parent, np.asarray([fx * lx, fy * ly, min(max(z, 0.0), thickness)])) ) inside = sum(1 for _, _, p in grain if p[2] < thickness - _TOL) if inside != round(expected): # pragma: no cover - a self-check of the enumeration raise BuildRefused(f"internal: {inside} atoms in the grain, {round(expected)} expected") if recipe.model == "periodic": pbc = (True, True, True) height = 2 * thickness boundaries = [0.0, thickness] separations = {"boundary_to_image_angstrom": thickness} else: pbc = (True, True, False) height = 2 * thickness + recipe.vacuum boundaries = [thickness + recipe.vacuum / 2] separations = {"boundary_to_surface_angstrom": thickness} cell = np.asarray([[lx, 0, 0], [0, ly, 0], [0, 0, height]], dtype=float) def place(translation: tuple[float, float]) -> tuple[list[str], list[str], list[str], _Points]: shift = np.asarray([translation[0] * lx, translation[1] * ly, 0.0]) symbols, parents, grains, positions = [], [], [], [] for symbol, parent, p in grain: symbols.append(symbol) parents.append(parent) grains.append("A") positions.append(p.copy()) for symbol, parent, p in grain: on_a_boundary = p[2] < _TOL or p[2] > thickness - _TOL if recipe.model == "periodic" and on_a_boundary: continue # boundary planes are grain A's if recipe.model == "slab" and p[2] < _TOL: continue # the boundary plane; B keeps its own surface plane at z = -L z = 2 * thickness - p[2] if recipe.model == "periodic" else -p[2] mirrored = np.asarray([(p[0] + shift[0]) % lx, (p[1] + shift[1]) % ly, z]) symbols.append(symbol) parents.append(parent) grains.append("B") positions.append(mirrored) cartesian = np.asarray(positions) if recipe.model == "slab": cartesian[:, 2] += thickness + recipe.vacuum / 2 return symbols, parents, grains, cartesian bulk_cart = np.asarray([f * a for _, _, f in sites]) nearest = _closest(bulk_cart, a * np.eye(3), (True, True, True)) minimum = recipe.min_distance if recipe.min_distance is not None else 0.6 * nearest symbols, parents, grains, cartesian = place(recipe.translation) closest = _closest(cartesian, cell, pbc) if closest < minimum: grid = [(i / 4, j / 4) for i in range(4) for j in range(4)] clear = sorted( ((_closest(place(t)[3], cell, pbc), t) for t in grid), key=lambda item: -item[0] ) hints = [f"({t[0]:g}, {t[1]:g}): {d:.3f} angstrom" for d, t in clear[:3] if d >= minimum] raise BuildRefused( f"two atoms across the boundary are {closest:.3f} angstrom apart, below " f"{minimum:.3f} (min_distance; the bulk nearest neighbour is {nearest:.3f}); state " "a rigid translation of grain B" + (f", for example {'; '.join(hints)}" if hints else "") + ". Atoms are never removed or merged silently" ) shift = np.asarray([recipe.translation[0] * lx, recipe.translation[1] * ly, 0.0]) lattice = cell.copy() n1, n2 = recipe.repeat cells = [(i, j) for j in range(n2) for i in range(n1)] big = np.vstack([cartesian + i * lattice[0] + j * lattice[1] for i, j in cells]) lattice[0] *= n1 lattice[1] *= n2 symbols_all, parents_all, grains_all = (v * len(cells) for v in (symbols, parents, grains)) 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=minimum) counter: Counter[str] = Counter() ids = [] for symbol in symbols_all: counter[symbol] += 1 ids.append(f"{symbol}{counter[symbol]}") provenance = _provenance( "grain_boundary", recipe, source=bulk.id if recipe.source else None, template=recipe.template, boundary_type="symmetric tilt", **{ k: geometry[k] for k in ( "rotation_axis", "boundary_plane", "sigma", "sigma_check", "tilt_deg", "tilt_angles_deg", "disorientation_deg", "disorientation_axis", ) }, closest_pair_angstrom=closest, bulk_nearest_neighbour_angstrom=nearest, min_distance_angstrom=minimum, frame={ "x": {"direction": list(axis), "period_angstrom": lx}, "y": {"direction": list(y_direction), "period_angstrom": ly}, "z": {"direction": list(plane), "period_angstrom": period}, }, construction="grain B is the mirror image of grain A in the boundary plane; in a " "centrosymmetric crystal that is grain A rotated 180 degrees about the boundary normal " "(the Sigma misorientation). Atoms on the boundary planes are grain A's.", repeats=repeats, grain_thickness_angstrom=thickness, boundary_heights_angstrom=boundaries, translation_fractional=list(recipe.translation), translation_angstrom=[float(shift[0]), float(shift[1])], model=recipe.model, cell="two equivalent boundaries per cell" if recipe.model == "periodic" else "one boundary between free surfaces, with vacuum", separations=separations, lattice_parameter_angstrom=a, site_map={ "columns": ["site", "parent_site", "grain"], "rows": [[i, p, g] for i, p, g in zip(ids, parents_all, grains_all, strict=True)], }, references=REFERENCES, charge_spin="the bulk's stated charge per cell scaled to the model; spin not chosen", not_claimed=NOT_CLAIMED, convergence_requirements=[ "converge the grain thickness (boundary-image or boundary-surface separation)", "sample the rigid translation of grain B and the boundary-plane atom density", "relax positions and the cell length normal to the boundary", "the lattice parameter is the parent's; use the method's own equilibrium lattice", ], ) charge = None if bulk.charge is not None: charge = bulk.charge * len(symbols_all) // max(1, len(sites)) made = _geometry_structure( recipe.identifier, lattice, pbc, symbols_all, big, [], cell_setting="unspecified", provenance=provenance, charge=charge, labels=ids, ) return made.model_copy( update={ "sites": [ s.model_copy(update={"parent_site": p}) for s, p in zip(made.sites, parents_all, strict=True) ] } )