Eve library

phase-117.md

Tracker

Revision 1

On this page

Historical task source. The Eve task board holds current task state.

<!-- prettier-ignore-start -->

Phase 117: Kalika Crystallography & Solid-State Physics — Space Groups, Symmetry Operations, Crystal Structure Analysis, Reciprocal Space & Diffraction#

Crystallography is the structural foundation upon which all materials science computation is built. Every density functional theory calculation begins with a crystal structure described by a lattice and basis; every phonon dispersion requires a Brillouin zone path determined by space group symmetry; every electronic band structure depends on irreducible k-point sampling that exploits the 230 space groups; every surface energy calculation requires slab models constructed from Miller indices. Without a rigorous, production-grade crystallography library, no downstream materials science module — electronic structure, thermodynamics, mechanical properties, phase diagrams — can function. This phase implements the complete crystallographic stack: from Bravais lattices and space group theory through structure representation, file I/O, reciprocal space construction, diffraction simulation, crystal chemistry analysis, surface and interface modeling, and symmetry-adapted tensor properties. The Rust kernel handles performance-critical symmetry detection, group enumeration, and neighbor-finding algorithms, while TypeScript provides the structural manipulation API, file parsers, and integration surface. The result is a self-contained crystallography platform comparable in capability to pymatgen, ASE, and spglib combined, serving as the bedrock for all subsequent Kalika materials science phases.


117.1 Project Scaffolding (@kalika/crystallography)#

117.1.1 Directory Structure & Build Configuration#

  • 117.1.1.1 Create libs/kalika/crystallography/ directory structure: src/, src/lattice/, src/space-group/, src/structure/, src/io/, src/reciprocal/, src/diffraction/, src/chemistry/, src/surface/, src/interface/, src/tensor/, src/types/, src/constants/, src/utils/, __tests__/ — with index.ts barrel exports at each level
  • 117.1.1.2 Create project.json with Nx targets: build (esbuild), test (vitest), lint (eslint), type-check (tsc --noEmit) — configure dependencies on @kalika/cas-engine, @kalika/numerical, @kalika/linear-algebra
  • 117.1.1.3 Create package.json with name @kalika/crystallography, dependencies using pnpm catalog refs, peer dependencies on core Kalika libs
  • 117.1.1.4 Create tsconfig.json extending root tsconfig.base.json, add path mapping @kalika/crystallography to tsconfig.base.json
  • 117.1.1.5 Create Rust workspace for symmetry kernel: rust/ directory with Cargo.toml, src/lib.rs, modules for space_group/, point_group/, symmetry_detection/, neighbor/ — configured for napi-rs bindings to expose functions to TypeScript

117.1.2 Core Types & Foundational Interfaces#

  • 117.1.2.1 Implement Element and Species types: Element enum for all 118 elements with atomic number, symbol, name, atomic mass (IUPAC 2021 standard atomic weights), covalent radius (Cordero et al. 2008), van der Waals radius (Alvarez 2013), electronegativity (Pauling scale); Species type extending Element with oxidation state, spin state, and arbitrary properties
  • 117.1.2.2 Implement PeriodicSite type: fractional coordinates (Vector3), Cartesian coordinates (Vector3, lazily computed from lattice), species (Species | Species[] for disordered sites), occupancy (number, default 1.0), site properties (magnetic moment, selective dynamics flags, velocity), label (string), and methods distanceTo(other, lattice), isPeriodicImage(other, tolerance)
  • 117.1.2.3 Implement Molecule type (non-periodic): list of CartesianSite (Cartesian coordinates + species), charge, spin multiplicity, point group detection, center of mass, moment of inertia tensor, principal axes — for molecular crystal and gas-phase calculations
  • 117.1.2.4 Implement Vector3 and Matrix3 utility types with full arithmetic: add, subtract, dot product, cross product, scalar multiply, matrix-vector multiply, matrix-matrix multiply, determinant, inverse, transpose, eigenvalues/eigenvectors (3x3 analytical formulas), Frobenius norm — all immutable, all with almostEqual(other, tol) comparators
  • 117.1.2.5 Implement elemental data constants: Shannon ionic radii table (for all common oxidation states and coordination numbers), Cordero covalent radii, Alvarez van der Waals radii, Pauling electronegativity scale, Allen electronegativity scale, electron configuration strings, common oxidation states per element — sourced from peer-reviewed tabulations with full citation
  • 117.1.2.6 Implement Composition class: represent chemical composition as a map of Element -> fractional amount, with methods reducedFormula(), anonymizedFormula(), weight() (molecular weight), getAtomicFraction(element), isSameComposition(other), getOxidationStateDecorated(), and Pettifor/Mendeleev number ordering for structure map positioning
  • 117.1.2.7 Implement unit conversion utilities: Angstrom <-> Bohr <-> nanometer, eV <-> Hartree <-> Rydberg <-> kJ/mol <-> kcal/mol, GPa <-> kbar <-> eV/A^3, Kelvin <-> meV (k_B T), degrees <-> radians — all physical constants from CODATA 2018

117.2 Lattice & Unit Cell (@kalika/crystallography)#

117.2.1 Lattice Representation & Construction#

  • 117.2.1.1 Implement Lattice class from lattice vectors: constructor takes 3x3 matrix (rows = lattice vectors a, b, c), compute and cache lattice parameters (a, b, c, alpha, beta, gamma), volume (triple product |a . (b x c)|), metric tensor G_ij = a_i . a_j, inverse metric tensor
  • 117.2.1.2 Implement Lattice.fromParameters(a, b, c, alpha, beta, gamma): construct lattice vectors from lengths and angles using the standard convention (a along x, b in xy-plane), validate angles satisfy triangle inequality, reject degenerate lattices (volume < epsilon)
  • 117.2.1.3 Implement all 14 Bravais lattice constructors: Lattice.cubic(a), Lattice.tetragonal(a, c), Lattice.orthorhombic(a, b, c), Lattice.hexagonal(a, c), Lattice.rhombohedral(a, alpha), Lattice.monoclinic(a, b, c, beta), Lattice.triclinic(a, b, c, alpha, beta, gamma) — each with body-centered (I), face-centered (F), base-centered (A/B/C), and rhombohedral (R) variants where applicable
  • 117.2.1.4 Implement Bravais lattice type detection: given a lattice, determine its Bravais type (aP, mP, mS, oP, oS, oI, oF, tP, tI, hP, hR, cP, cI, cF) by analyzing metric tensor eigenvalues and relationships between lattice parameters within tolerance
  • 117.2.1.5 Implement Lattice.isEquivalent(other, tolerance): test whether two lattices are equivalent under a unimodular transformation (integer matrix with determinant +/-1), considering all valid lattice vector choices
  • 117.2.1.6 Implement lattice serialization/deserialization: toJSON() and fromJSON() for lattice persistence, toString() with formatted lattice parameters and vectors, toFortranString() for direct embedding in DFT input files (Bohr units with appropriate precision)
  • 117.2.1.7 Implement Lattice.getWignerSeitzCell(): construct the Wigner-Seitz cell of the direct lattice by computing the perpendicular bisector planes of lattice vectors to all neighboring lattice points, return as a convex polyhedron (vertices, edges, faces) — the primitive cell with full point group symmetry

117.2.2 Lattice Vector Operations#

  • 117.2.2.1 Implement reciprocal lattice computation: b1 = 2pi(a2 x a3)/V, b2 = 2pi(a3 x a1)/V, b3 = 2pi(a1 x a2)/V — return a new Lattice instance representing the reciprocal lattice, verify a_i . b_j = 2pi * delta_ij
  • 117.2.2.2 Implement metric tensor operations: metricTensor() returns G_ij, dStar(hkl) computes d-spacing d* = sqrt(h^2 a*^2 + k^2 b*^2 + l^2 c*^2 + 2hk abcos(gamma*) + ...) using the reciprocal metric tensor, dSpacing(hkl) returns 1/d*
  • 117.2.2.3 Implement Lattice.getCartesianCoords(fractional) and Lattice.getFractionalCoords(cartesian): convert between fractional and Cartesian coordinates using the lattice matrix and its inverse, handle wrapping of fractional coordinates to [0, 1) range
  • 117.2.2.4 Implement Lattice.getDistanceAndImage(frac1, frac2): compute minimum-image distance between two fractional coordinate vectors under periodic boundary conditions, return both the distance and the periodic image vector (integer translations) — using the algorithm that checks 27 images for general triclinic cells
  • 117.2.2.5 Implement Lattice.getAllDistancesAndImages(frac1, frac2, cutoff): return all periodic images of frac2 within a distance cutoff from frac1, with associated translation vectors — essential for neighbor lists

117.2.3 Cell Reduction Algorithms#

  • 117.2.3.1 Implement Niggli reduction algorithm (Krivy & Gruber 1976, refined by Grosse-Kunstleve et al. 2004): reduce any lattice to its unique Niggli-reduced form by iterating the 8 conditions on the metric tensor elements (A, B, C, D, E, F), with numerical tolerance handling for near-degenerate cases — the standard canonical cell representation
  • 117.2.3.2 Implement Delaunay (Selling) reduction: reduce lattice to Delaunay-reduced form using the four-vector (a, b, c, d = -(a+b+c)) representation, iterating scalar products until all are non-positive — alternative canonical form used for lattice comparison
  • 117.2.3.3 Implement Minkowski reduction (LLL algorithm adapted for 3D): find shortest three linearly independent lattice vectors using the Lenstra-Lenstra-Lovász algorithm specialized to dimension 3, with exact arithmetic where possible
  • 117.2.3.4 Implement conventional cell to primitive cell transformation: for each centering type (P, I, F, A, B, C, R), apply the standard transformation matrix (e.g., F-centered: rows (0,1/2,1/2), (1/2,0,1/2), (1/2,1/2,0)) to obtain the primitive lattice vectors, transform all fractional coordinates accordingly
  • 117.2.3.5 Implement primitive cell to conventional cell finder: given a primitive cell, determine the conventional cell by analyzing the Niggli- reduced form, identifying the Bravais lattice type, and applying the inverse centering transformation

117.2.4 Supercell & Strain Operations#

  • 117.2.4.1 Implement diagonal supercell generation: Lattice.supercell(na, nb, nc) creates a supercell by replicating the unit cell na x nb x nc times along each lattice vector, computing new lattice vectors and generating all replicated site positions
  • 117.2.4.2 Implement general (non-diagonal) supercell transformation: Lattice.transform(P) where P is a 3x3 integer matrix, new lattice vectors = P * old lattice vectors, enumerate all sites in the new cell by finding all integer combinations mapping old fractional coords into the new cell — handles arbitrary supercell shapes including rotated cells
  • 117.2.4.3 Implement strain tensor computation: given two lattices (reference and deformed), compute the deformation gradient tensor F = L_deformed * L_reference^(-1), the Green-Lagrange strain tensor E = (F^T F - I)/2, the infinitesimal strain tensor epsilon = (F + F^T)/2 - I, and the rotation tensor R (polar decomposition)
  • 117.2.4.4 Implement Lattice.applyStrain(strainTensor): apply a 3x3 symmetric strain tensor (Voigt notation input: [e_xx, e_yy, e_zz, e_yz, e_xz, e_xy]) to the lattice, returning the deformed lattice — used for elastic constant calculation workflows
  • 117.2.4.5 Implement lattice parameter refinement: given noisy lattice parameters, refine to the nearest ideal Bravais lattice by constraining parameters according to crystal system (e.g., for cubic: a=b=c, alpha=beta=gamma=90), using least-squares fitting of the metric tensor
  • 117.2.4.6 Implement strain set generation for elastic constant calculation: generate the set of strained lattices needed to compute all independent elastic constants for a given crystal system — 6 deformations for cubic (sufficient to determine C11, C12, C44), 9 for hexagonal, 21 for triclinic — each at multiple strain magnitudes (e.g., +/- 0.5%, 1%, 1.5%) for polynomial fitting of energy vs strain
  • 117.2.4.7 Implement equation of state fitting: given a set of (volume, energy) data points from uniform compression/expansion, fit to Birch-Murnaghan EOS: E(V) = E0 + (9/16)B0V0*{[(V0/V)^(2/3)-1]^3B0' + [(V0/V)^(2/3)-1]^2[6-4*(V0/V)^(2/3)]} — extract equilibrium volume V0, bulk modulus B0, pressure derivative B0', and equilibrium energy E0 via nonlinear least-squares; also support Murnaghan, Vinet, and Rose-Vinet EOS forms

117.3 Space Group Theory (@kalika/crystallography — Rust Kernel)#

117.3.1 Symmetry Operations#

  • 117.3.1.1 Implement SymmetryOperation type in Rust: 3x3 integer rotation matrix W plus translation vector w (rational, stored as numerator/denominator pairs with denominator dividing 12), with composition (W1,w1)(W2,w2) = (W1W2, W1w2 + w1), inverse (W,w)^(-1) = (W^(-1), -W^(-1)*w), and equality testing (mod integer translations for w)
  • 117.3.1.2 Implement symmetry operation classification: given (W, w), determine operation type by analyzing the rotation matrix — identity (det=1, tr=3), inversion (det=-1, tr=-3), rotation (det=1: 2-fold tr=-1, 3-fold tr=0, 4-fold tr=1, 6-fold tr=2), rotoinversion (det=-1), mirror (det=-1, tr=1) — plus axis/plane direction and screw/glide component extraction (intrinsic translation)
  • 117.3.1.3 Implement screw axis identification: decompose translation w into intrinsic part w_intrinsic (parallel to rotation axis, determined by order and axis direction: w_int = (w . n_axis / n) * n_axis for n-fold) and location part w_location, classify as 2_1, 3_1, 3_2, 4_1, 4_2, 4_3, 6_1, 6_2, 6_3, 6_4, 6_5 screw axes
  • 117.3.1.4 Implement glide plane identification: decompose translation w for mirror/rotoinversion operations into intrinsic glide component (parallel to mirror plane) and location shift, classify as axial glide (a, b, c), diagonal glide (n), diamond glide (d), or no glide (m)
  • 117.3.1.5 Implement Seitz notation rendering: format symmetry operation as {W|w} Seitz symbol, Jones faithful representation (e.g., -y,x,z for 4-fold rotation), and x,y,z notation with translational components (e.g., -y+1/2,x+1/2,z for 4_1 screw)

117.3.2 Point Groups (32 Crystallographic)#

  • 117.3.2.1 Implement all 32 crystallographic point groups as sets of rotation matrices: triclinic (1, -1), monoclinic (2, m, 2/m), orthorhombic (222, mm2, mmm), tetragonal (4, -4, 4/m, 422, 4mm, -42m, 4/mmm), trigonal (3, -3, 32, 3m, -3m), hexagonal (6, -6, 6/m, 622, 6mm, -6m2, 6/mmm), cubic (23, m-3, 432, -43m, m-3m) — store as canonical generator sets and full element lists
  • 117.3.2.2 Implement point group detection from a set of symmetry operations: extract rotation parts {W} from a list of (W,w) pairs, identify the point group by matching against the 32 known groups — classify by Schoenflies symbol (C1, Ci, C2, Cs, C2h, D2, C2v, D2h, C4, S4, C4h, D4, C4v, D2d, D4h, C3, S6, D3, C3v, D3d, C6, C3h, C6h, D6, C6v, D3h, D6h, T, Th, O, Td, Oh) and Hermann-Mauguin symbol
  • 117.3.2.3 Implement point group multiplication table generation and subgroup lattice: for each of the 32 groups, compute the full multiplication table, list all subgroups, determine normal subgroups, compute factor groups, build the subgroup Hasse diagram
  • 117.3.2.4 Implement Laue class determination: given a point group, return its Laue class (the point group obtained by adding inversion symmetry), one of the 11 Laue classes: -1, 2/m, mmm, 4/m, 4/mmm, -3, -3m, 6/m, 6/mmm, m-3, m-3m — determines diffraction symmetry
  • 117.3.2.5 Implement crystal system determination: map point group to crystal system (triclinic, monoclinic, orthorhombic, tetragonal, trigonal, hexagonal, cubic) and crystal family

117.3.3 Space Groups (230)#

  • 117.3.3.1 Implement the complete space group database in Rust: all 230 space group types stored as generator sets {(W_i, w_i)}, indexed by ITA number (1-230), with Hermann-Mauguin symbol (full, short, extended), Schoenflies symbol, Hall symbol, crystal system, crystal class (point group), Bravais lattice type, and centering translations
  • 117.3.3.2 Implement space group element generation: from generator set, compute the full list of symmetry operations by iterating all products of generators until closure (modulo lattice translations), verify group axioms (closure, associativity, identity, inverse) — handle centering translations by expanding with centering vectors
  • 117.3.3.3 Implement symmorphic vs non-symmorphic classification: identify the 73 symmorphic space groups (those where all operations can be written as point group operation + lattice translation, i.e., no screw axes or glide planes of non-trivial intrinsic translation) and the 157 non-symmorphic groups
  • 117.3.3.4 Implement space group setting transformations: transform between different settings of the same space group (e.g., unique axis b vs c for monoclinic, hexagonal vs rhombohedral axes for trigonal, origin choice 1 vs 2) using the transformation matrices from ITA
  • 117.3.3.5 Implement space group lookup by any identifier: given an ITA number, Hermann-Mauguin symbol (any variant), Schoenflies symbol, or Hall symbol, return the canonical space group data — handle ambiguities with setting specifications
  • 117.3.3.6 Implement napi-rs bindings: expose all Rust space group functions to TypeScript via napi-rs — getSpaceGroup(id), generateOperations(generators), classifyOperation(W, w), detectPointGroup(operations) — with proper TypeScript type definitions
  • 117.3.3.7 Implement space group arithmetic: compute the intersection of two space groups (common subgroup), determine if one is a subgroup of another, compute the index [G:H] of a subgroup H in G — needed for group-subgroup analysis of phase transitions
  • 117.3.3.8 Implement space group orbit computation: given a space group and a general position (x, y, z), compute the full orbit (set of all symmetry-equivalent positions), determine the orbit size (= |G| / |G_x| where G_x is the stabilizer), list all equivalent positions with their generating symmetry operation

117.3.4 Wyckoff Positions#

  • 117.3.4.1 Implement the complete Wyckoff position database: for all 230 space groups, store all Wyckoff positions with multiplicity, Wyckoff letter, site symmetry group (as Hermann-Mauguin symbol), coordinate triplets (with free parameters x, y, z), and special conditions on parameters — sourced from ITA Tables
  • 117.3.4.2 Implement Wyckoff position lookup and coordinate generation: given a space group and Wyckoff letter, generate all equivalent positions by applying the symmetry operations of the site symmetry group, substitute free parameters with given values
  • 117.3.4.3 Implement site symmetry group computation: given a space group and a point in the unit cell (fractional coordinates), determine which symmetry operations leave that point invariant (modulo lattice translations) — the stabilizer subgroup, returned as a list of (W, w) pairs and its point group classification
  • 117.3.4.4 Implement Wyckoff position assignment: given a structure with known space group, assign each site to its Wyckoff position by computing the site symmetry group and matching against the database, determine free parameter values from the actual coordinates
  • 117.3.4.5 Implement Wyckoff position splitting: for a group-subgroup pair, determine how each Wyckoff position of the supergroup splits into Wyckoff positions of the subgroup — essential for phase transition analysis

117.3.5 Space Group Detection#

  • 117.3.5.1 Implement symmetry detection algorithm (Togo & Tanaka, spglib-equivalent) in Rust: given atomic coordinates and lattice, find all symmetry operations (W, w) that map the structure onto itself within a configurable tolerance — (1) lattice point symmetry detection via metric tensor analysis, (2) candidate operation generation from lattice symmetries, (3) atomic mapping verification for each candidate using distance-based matching
  • 117.3.5.2 Implement tolerance-based symmetry finding: adaptive tolerance strategy that starts with a user-specified tolerance (default 0.01 Angstrom) and refines — if a symmetry operation maps atoms with residuals just above tolerance, report it as a near-miss; support separate tolerances for positions and angles
  • 117.3.5.3 Implement space group identification from detected operations: given the full set of detected symmetry operations, identify the space group number by (1) determining the point group from rotation parts, (2) analyzing translation parts to identify centering and screw/glide components, (3) matching against the 230 known types with appropriate origin shift
  • 117.3.5.4 Implement structure symmetrization: given a structure and its detected space group, idealize the structure by averaging over symmetry- related atoms — project each atom to its Wyckoff position, average lattice parameters according to crystal system constraints, report the maximum displacement from idealization
  • 117.3.5.5 Implement primitive cell standardization (Togo convention): given any cell, find the standardized conventional cell (ITA setting) and the corresponding primitive cell, return the transformation matrix relating input to standardized cell
  • 117.3.5.6 Implement symmetry precision analysis: given a structure, compute the symmetry operations at multiple tolerance levels, plot the number of detected operations vs tolerance to identify the natural symmetry breaking scale — useful for slightly distorted structures
  • 117.3.5.7 Implement Hall symbol parser: parse the Hall space group symbol notation (compact encoding of generators using rotation matrices and translation symbols N^A_T), expand into the full set of generators {(W_i, w_i)} — Hall symbols unambiguously specify space group setting and origin, making them the preferred internal representation
  • 117.3.5.8 Implement international tables coordinate triplet parser: parse symmetry operations in x,y,z string notation (e.g., "-x+1/2,y,-z", "y,-x+y,z+1/3"), convert to matrix/vector representation (W, w), and vice versa — with full validation of the resulting operation (det(W) = +/-1, W is integer, translation components are rational with denominator | 12)

117.3.6 Magnetic & Subperiodic Groups#

  • 117.3.6.1 Implement the 1651 magnetic space group types (Shubnikov groups): store as generator sets with time-reversal flags on each operation (W, w, theta where theta = +1 or -1), classify into Type I (230, no time reversal), Type II (230, all ops doubled with time reversal), Type III (674, half ops have time reversal — equitranslational), Type IV (517, magnetic lattice has doubled period)
  • 117.3.6.2 Implement magnetic symmetry detection: given a structure with magnetic moments on each site (vector or scalar), detect the magnetic space group by finding operations that preserve both atomic positions and magnetic moment orientations (considering time reversal flips moments)
  • 117.3.6.3 Implement the 80 layer groups for 2D materials: symmetry groups for systems periodic in two dimensions, non-periodic in the third — store generators, Wyckoff positions, and systematic absences for each
  • 117.3.6.4 Implement the 75 rod groups for 1D materials: symmetry groups for systems periodic in one dimension (nanowires, nanotubes) — with full symmetry operation enumeration
  • 117.3.6.5 Implement the 7 frieze groups for quasi-1D surface patterns: with pattern generation and symmetry detection

117.3.7 Group Relationships & Representations#

  • 117.3.7.1 Implement subgroup enumeration: for a given space group, find all maximal subgroups (translationengleiche: same translations, fewer rotations; klassengleiche: same rotations, enlarged translations; and isomorphic subgroups of prime index) — data from Bilbao Crystallographic Server tables
  • 117.3.7.2 Implement supergroup enumeration: for a given space group, find all minimal supergroups — the inverse relationship of subgroup enumeration
  • 117.3.7.3 Implement Bärnighausen tree construction: build the complete group-subgroup graph connecting two space groups (supergroup and subgroup), showing the chain of maximal subgroup steps with index and transformation matrix at each level — essential for phase transition crystallography
  • 117.3.7.4 Implement irreducible representations of space groups: construct the irreps at each k-point using the little group method — determine the little group G_k (subgroup of operations leaving k invariant or mapping to k + G), compute its irreps (small representations), induce to get the full space group irreps — compatible with Bilbao REPRESENTATIONS tables
  • 117.3.7.5 Implement compatibility relations: for irreps at different k-points along a high-symmetry path, determine how irreps at a high- symmetry point decompose into irreps at nearby general k-points — needed for band structure labeling
  • 117.3.7.6 Implement corepresentations for magnetic space groups: extend the irrep machinery to handle time-reversal symmetry, construct corepresentations following the Wigner classification (Type a, b, c depending on Herring criterion)

117.4 Crystal Structure Representation (@kalika/crystallography)#

117.4.1 Structure Class#

  • 117.4.1.1 Implement Structure class: immutable container holding a Lattice and an array of PeriodicSite, with getters for numSites, species, fractionalCoords, cartesianCoords, volume, density (g/cm^3), composition (element counts and formula), reducedFormula, anonymizedFormula (for structure type comparison)
  • 117.4.1.2 Implement Structure.builder() pattern: fluent API for constructing structures — Structure.builder().lattice(l).addSite(species, coords).addSite(...).build(), with validation (no overlapping sites within tolerance, all coordinates valid)
  • 117.4.1.3 Implement coordinate system operations: Structure.getFractionalCoords(), Structure.getCartesianCoords(), Structure.translateSites(indices, vector), Structure.perturbSites(distance) (random displacement for phonon calculations), Structure.wrapToUnitCell() (ensure all fractional coords in [0, 1))
  • 117.4.1.4 Implement periodic boundary condition handling: Structure.getDistance(i, j) using minimum image convention, Structure.getAllDistances() returning the full distance matrix, Structure.getSitesInSphere(center, radius) returning all periodic images of all sites within radius of a point
  • 117.4.1.5 Implement structure manipulation: Structure.removeSites(indices), Structure.replaceSite(index, species), Structure.insertSite(index, species, coords), Structure.applyOperation(symmOp), Structure.makeSuperCell(scaling) — all returning new Structure instances (immutable)
  • 117.4.1.6 Implement structure sorting and canonicalization: Structure.getSortedStructure() sorts sites by electronegativity then fractional coordinates (matching pymatgen convention), Structure.getReducedStructure() returns structure with primitive cell, Structure.getConventionalStructure() returns conventional cell form
  • 117.4.1.7 Implement structure property accessors: Structure.spaceGroup (lazily detected), Structure.symmetryOperations, Structure.wyckoffSites, Structure.latticeType, Structure.crystalSystem — cached after first computation, invalidated on any structural modification
  • 117.4.1.8 Implement structure merge and concatenation: Structure.merge(other) combines two structures sharing the same lattice (for adding interstitial atoms or combining sublattices), Structure.replicate(na, nb, nc) creates a supercell with all site properties preserved, Structure.freeze(indices) marks atoms as fixed for selective dynamics in relaxation calculations

117.4.2 Neighbor Finding#

  • 117.4.2.1 Implement KD-tree based neighbor finding with periodic images (Rust kernel): build a KD-tree over all sites including sufficient periodic images (determined by cutoff radius and lattice geometry), support range queries neighborsWithinRadius(site, r) and k-nearest queries kNearestNeighbors(site, k) — O(N log N) construction, O(log N) queries
  • 117.4.2.2 Implement Voronoi-based coordination analysis: compute the Voronoi tessellation of the crystal (accounting for periodicity via replicated images), identify nearest neighbors as sites sharing a Voronoi face, weight neighbors by solid angle subtended by shared face — provides coordination environment without arbitrary cutoff
  • 117.4.2.3 Implement coordination number computation with multiple methods: (1) distance cutoff method (sum of covalent radii * factor), (2) Voronoi method (count faces above weight threshold), (3) effective coordination number ECoN (Hoppe 1979: weighted by exp(-6((d_i/d_min)^6 - 1))), (4) minimum distance method (O'Keeffe) — return coordination number and list of coordinating atoms
  • 117.4.2.4 Implement neighbor list class: NeighborList storing all neighbor pairs within a cutoff, with methods to query neighbors of a specific atom, update incrementally when a single atom moves, and compute pair distribution function from the list
  • 117.4.2.5 Implement napi-rs bindings for neighbor-finding: expose the Rust KD-tree and Voronoi neighbor finder to TypeScript with efficient data marshaling (Float64Array for coordinates, Int32Array for indices)

117.4.3 Structure Matching & Comparison#

  • 117.4.3.1 Implement StructureMatcher class (pymatgen algorithm): determine if two structures are equivalent by (1) comparing composition, (2) reducing both to Niggli cells, (3) generating all possible lattice mappings between the reduced cells (considering volume ratio tolerance and length/angle tolerances), (4) for each lattice mapping, finding the best atomic assignment using the Hungarian algorithm on a cost matrix of distances — configurable tolerances for lattice and atomic positions
  • 117.4.3.2 Implement RMS displacement computation: given two structures with matched atoms, compute the root-mean-square displacement between corresponding atomic positions (minimum image convention), with optional rigid-body alignment (translation + rotation to minimize RMSD using Kabsch algorithm)
  • 117.4.3.3 Implement structure interpolation (for NEB): given two endpoint structures with matched atoms, generate N intermediate images by linear interpolation of fractional coordinates, with geodesic interpolation option (interpolate along great circle on unit cell surface for large displacements), adjust images to avoid atom-atom clashes using IDPP (Image Dependent Pair Potential) method
  • 117.4.3.4 Implement structure fingerprinting: compute a fixed-length numerical fingerprint for each structure (e.g., partial radial distribution function up to cutoff, discretized into bins; or OFM — Orbital-Field Matrix — fingerprint) for fast approximate structure comparison without full matching
  • 117.4.3.5 Implement structure deduplication: given a list of structures, identify duplicates using a two-stage approach — (1) fast pre-screening by composition, volume, and fingerprint distance, (2) full StructureMatcher comparison for candidates passing pre-screening

117.4.4 Disordered & Complex Structures#

  • 117.4.4.1 Implement disordered site representation: sites with multiple species and partial occupancies (e.g., 0.7 Fe + 0.3 Mn on one site), with methods isOrdered(), totalOccupancy(), and getOrderedApproximation() that generates the closest ordered structure
  • 117.4.4.2 Implement SQS (Special Quasirandom Structures) generation: for substitutional alloys (e.g., A_{1-x}B_x on a given sublattice), generate the supercell configuration that best mimics the pair (and optionally triplet) correlation functions of a random alloy — using the stochastic approach of Zunger et al. (1990) with simulated annealing optimization of the objective function Sigma_m w_m |Pi_m^SQS - Pi_m^random|^2
  • 117.4.4.3 Implement oxidation state assignment: (1) bond valence method (Brown & Altermatt 1985): sum BV_ij = exp((R0 - r_ij)/b) over neighbors, constrain sum of oxidation states to total charge, solve as integer linear program; (2) ICSD statistics-based: assign most common oxidation states from database frequencies; (3) electronegativity-based: assign based on Pauling electronegativity ordering
  • 117.4.4.4 Implement molecular fragment detection in crystals: identify connected molecular units within a crystal structure using periodic boundary conditions — compute connected components of the bonding graph (edges defined by distance < sum of covalent radii * 1.2), handle molecules spanning cell boundaries, return each fragment as a Molecule with its Cartesian coordinates
  • 117.4.4.5 Implement structure editing utilities: Structure.substituteSpecies(mapping) (e.g., {Fe: Co} replaces all Fe with Co), Structure.removeOxidationStates(), Structure.addOxidationStates(mapping), Structure.scaleVolume(factor) (uniform scaling), Structure.applyStrainToCoords(strainTensor) (internal coordinate response to strain, for elastic calculations)

117.5 Structure File I/O (@kalika/crystallography)#

117.5.1 CIF Reader/Writer#

  • 117.5.1.1 Implement CIF (Crystallographic Information Framework) lexer: tokenize CIF files into data blocks, data names, data values (numbers, strings, text fields delimited by semicolons), loop constructs — handle CIF 1.1 syntax including single-quoted, double-quoted, and semicolon- delimited text fields
  • 117.5.1.2 Implement CIF parser: parse tokenized CIF into structured data — extract cell parameters (_cell_length_a, _cell_angle_alpha, etc.), space group (_symmetry_space_group_name_H-M or _space_group_name_H-M_alt), atom sites (_atom_site_fract_x/y/z, _atom_site_type_symbol, _atom_site_label), symmetry operations (_symmetry_equiv_pos_as_xyz or _space_group_symop_operation_xyz), anisotropic displacement parameters (_atom_site_aniso_U_11, etc.)
  • 117.5.1.3 Implement CIF structure builder: from parsed CIF data, construct a Structure by (1) building the Lattice from cell parameters, (2) applying symmetry operations to the asymmetric unit atoms to generate all symmetry-equivalent positions, (3) removing duplicates (atoms mapping to same position within tolerance), (4) assigning oxidation states if present in CIF
  • 117.5.1.4 Implement CIF writer: serialize a Structure to CIF format — write cell parameters, space group (if known), atom site loop with fractional coordinates, labels, occupancies, and isotropic displacement parameters — produce valid CIF that can be read by Mercury, VESTA, and other visualization tools
  • 117.5.1.5 Implement multi-block CIF handling: parse CIF files containing multiple data blocks (common for multi-phase refinements and CIF dictionaries), return a list of structures, support writing multi-block CIF files

117.5.2 VASP Format Reader/Writer#

  • 117.5.2.1 Implement POSCAR/CONTCAR reader: parse VASP structure files — title line, scaling factor (including negative = volume), lattice vectors (3 lines), species names (VASP 5+ format), species counts, selective dynamics flags (T/F per atom per direction), coordinate type (Direct/Cartesian), atomic positions, optional velocities — handle both VASP 4 (no species names) and VASP 5+ formats
  • 117.5.2.2 Implement POSCAR/CONTCAR writer: serialize Structure to POSCAR format — proper species ordering, lattice vector formatting (16 decimal places for accuracy), Direct coordinates, optional selective dynamics flags, VASP 5 format with element symbols
  • 117.5.2.3 Implement VASP CHGCAR/LOCPOT volumetric data reader: parse header (same as POSCAR), then read the 3D volumetric data grid (charge density, local potential, etc.) — handle augmentation charges in PAW, support spin-polarized files (two grids), return as 3D typed array with associated structure

117.5.3 Other Format Readers/Writers#

  • 117.5.3.1 Implement XSF (XCrySDen) reader/writer: parse/write CRYSTAL, PRIMVEC, PRIMCOORD, and ATOMS blocks — support both periodic (CRYSTAL) and molecular (ATOMS) formats, handle animated XSF (AXSF) with multiple frames for molecular dynamics trajectories
  • 117.5.3.2 Implement PDB (Protein Data Bank) reader/writer: parse CRYST1 (cell parameters and space group), ATOM/HETATM records (name, residue, chain, coordinates, occupancy, B-factor), CONECT records (bonding) — write valid PDB files for visualization in PyMOL, VMD
  • 117.5.3.3 Implement extended XYZ reader/writer: parse comment line for lattice vectors (Lattice="ax ay az bx by bz cx cy cz"), properties specification (Properties=species:S:1:pos:R:3:forces:R:3), per-atom properties — the ASE extended XYZ convention; write with full property preservation
  • 117.5.3.4 Implement Quantum ESPRESSO input (.pwi/.in) reader/writer: parse CELL_PARAMETERS, ATOMIC_SPECIES (with pseudopotential filenames), ATOMIC_POSITIONS (crystal/angstrom/bohr), K_POINTS blocks — write valid QE input files with sensible defaults for &CONTROL, &SYSTEM, &ELECTRONS namelists
  • 117.5.3.5 Implement ABINIT input reader/writer: parse acell, rprim, natom, ntypat, typat, znucl, xred/xcart/xangst, and k-point grid variables — write valid ABINIT input with structure variables
  • 117.5.3.6 Implement FHI-aims geometry.in reader/writer: parse lattice_vector lines, atom lines (x y z species), with optional initial_moment, constrain_relaxation — write valid geometry.in files
  • 117.5.3.7 Implement LAMMPS data file reader/writer: parse Masses, Atoms (atom-id mol-id type charge x y z), Bonds, Angles sections, box dimensions with tilt factors (for triclinic cells) — write valid LAMMPS data files for molecular dynamics
  • 117.5.3.8 Implement SHELX (.res/.ins) reader/writer: parse CELL, LATT, SYMM, SFAC, UNIT, atom lines with coordinates and Uiso/Uaniso — the standard format for single-crystal X-ray refinement results
  • 117.5.3.9 Implement Gaussian (.gjf/.com) reader/writer: parse route section, charge/multiplicity, Cartesian or Z-matrix coordinates, basis set specification — write valid Gaussian input files
  • 117.5.3.10 Implement JSON structure format (Materials Project compatible): serialize/deserialize structures to/from JSON matching the pymatgen Structure.as_dict() format — enabling direct data exchange with Materials Project API responses
  • 117.5.3.11 Implement WIEN2k struct file reader/writer: parse the case.struct format with lattice parameters, atom positions in local coordinate systems, RMT values (muffin-tin radii), symmetry operations — required for LAPW calculations
  • 117.5.3.12 Implement trajectory/animation file support: read and write multi-frame structure files (VASP XDATCAR, XYZ trajectory, AXSF animation), return as Trajectory object (ordered list of Structure instances sharing species but with varying coordinates/lattice), support frame slicing, interpolation, and RMSD-vs-frame analysis
  • 117.5.3.13 Implement structure format validation: for each output format, validate that the written file conforms to the format specification — check for required fields, valid ranges (e.g., fractional coords in [0,1) for Direct POSCAR), consistent atom counts, and syntactic correctness — return detailed error messages for invalid files

117.5.4 Structure Database Integration#

  • 117.5.4.1 Implement Materials Project API client: query structures by formula, elements, band gap range, space group, etc. using the MP REST API v2 (with API key management), parse responses into Structure objects, cache results locally — support pagination for large result sets
  • 117.5.4.2 Implement COD (Crystallography Open Database) query client: search by formula, cell parameters, space group, author, journal via the COD RESTful API, download CIF files and parse into structures
  • 117.5.4.3 Implement automatic format detection: given a file path or string content, detect the format (CIF, POSCAR, XYZ, PDB, QE, etc.) by examining file extension and content heuristics (e.g., presence of _cell_length_a for CIF, CRYST1 for PDB), dispatch to the appropriate reader — Structure.fromFile(path) convenience method

117.6 Reciprocal Space & Brillouin Zones (@kalika/crystallography)#

117.6.1 Reciprocal Lattice#

  • 117.6.1.1 Implement reciprocal lattice construction: given a direct lattice, compute the reciprocal lattice vectors b1, b2, b3 using b_i = 2pi _ (a_j x a_k) / (a_i . (a_j x a_k)), return as a Lattice instance, verify orthonormality relations a_i . b_j = 2pi _ delta_ij
  • 117.6.1.2 Implement reciprocal space distance/angle computations: reciprocalDistance(hkl1, hkl2) in inverse Angstroms, interplanarAngle (hkl1, hkl2) between reciprocal lattice planes, dSpacing(hkl) via d = 1/|G_hkl| where G_hkl = hb1 + kb2 + l*b3

117.6.2 Brillouin Zone Construction#

  • 117.6.2.1 Implement first Brillouin zone (BZ) as Wigner-Seitz cell in reciprocal space: construct by finding the perpendicular bisector planes of reciprocal lattice vectors to nearby points (enumerate sufficient shells), compute the intersection polyhedron using half-space intersection (e.g., incremental convex hull or vertex enumeration algorithm), return as a list of vertices, edges, and faces
  • 117.6.2.2 Implement BZ face classification: for each face of the BZ polyhedron, identify the reciprocal lattice vector it bisects, determine which faces are related by point group symmetry, compute face areas and the BZ volume (should equal (2pi)^3 / V_cell)
  • 117.6.2.3 Implement irreducible Brillouin zone (IBZ) construction: reduce the full BZ by the point group symmetry, represent the IBZ as a polyhedron with its bounding faces labeled by symmetry operations

117.6.3 High-Symmetry Points & Paths#

  • 117.6.3.1 Implement high-symmetry k-point identification (Setyawan & Curtarolo 2010 conventions): for each of the 14 Bravais lattice types, define the standard high-symmetry points (Gamma, X, M, K, L, W, U, etc.) with their fractional coordinates in reciprocal space and conventional labels — handle the lattice parameter-dependent positions (e.g., for body-centered tetragonal, the location of N depends on c/a ratio)
  • 117.6.3.2 Implement Hinuma et al. (2017) conventions as alternative: support the k-path conventions from Hinuma, Pizzi, Kumagai, Oba, Tanaka that handle all special cases including monoclinic and triclinic cells with different relationships between lattice parameters — selectable as an option alongside Setyawan-Curtarolo
  • 117.6.3.3 Implement SeeK-path algorithm: automatic high-symmetry path determination that (1) reduces the input cell to the standardized conventional cell, (2) identifies the Bravais lattice type, (3) looks up the appropriate high-symmetry points, (4) connects them in the conventional order with line segments — handling all edge cases for the 14 Bravais lattice types
  • 117.6.3.4 Implement k-path segment generation: KPath.getKPoints(numPointsPerSegment) generates the list of k-points along the high-symmetry path with specified density, with segment boundaries marked, k-point distances computed for x-axis plotting of band structures, and labels at high-symmetry points
  • 117.6.3.5 Implement k-path label rendering: generate LaTeX-formatted labels for high-symmetry points (e.g., $\Gamma$, $\mathrm{X}$, $\mathrm{M}|\mathrm{K}$) with proper handling of path discontinuities (vertical bar separator) — for band structure plot annotations

117.6.4 K-Point Grid Generation#

  • 117.6.4.1 Implement Monkhorst-Pack grid generation: generate a uniform k-point mesh with N1 x N2 x N3 points using the formula k_p = (2p - N - 1)/(2N) for p = 1..N along each direction, with optional shift vector (commonly Gamma-centered shift = (1/2N, 1/2N, 1/2N) for even grids) — return k-points in fractional reciprocal coordinates
  • 117.6.4.2 Implement Gamma-centered grid generation: generate k-point mesh that always includes the Gamma point (0,0,0), with N1 x N2 x N3 points uniformly distributed — preferred for hexagonal systems and when Gamma-point values are needed
  • 117.6.4.3 Implement irreducible k-point reduction: given a full k-point grid and the space group symmetry operations, identify symmetry-equivalent k-points, reduce to the irreducible set, compute the weight of each irreducible k-point (proportional to the number of equivalent points in the full grid) — optionally exploit time-reversal symmetry (k ~ -k if no spin-orbit coupling or magnetic ordering)
  • 117.6.4.4 Implement k-point density specification: given a target k-point density (e.g., k-points per reciprocal Angstrom), automatically determine the grid dimensions N1, N2, N3 proportional to the reciprocal lattice vector lengths, ensuring the density is at least the target value along each direction
  • 117.6.4.5 Implement k-point convergence testing workflow: generate a series of k-grids with increasing density, define a convergence criterion (e.g., energy difference < threshold between successive grids), return the converged grid parameters — helper for computational setup
  • 117.6.4.6 Implement special k-point sets for phonon calculations: generate commensurate k-point meshes for supercell phonon calculations (the k-points that fold back to Gamma in the supercell), and q-point meshes for density functional perturbation theory (DFPT) — considering the relationship between q-mesh and supercell size
  • 117.6.4.7 Implement Baldereschi mean-value point computation: determine the single k-point that best approximates the Brillouin zone average of any smooth periodic function — for each Bravais lattice type, compute the mean-value point using the Chadi-Cohen or Baldereschi scheme, useful for rapid estimates of electronic properties
  • 117.6.4.8 Implement k-point path with line density: generate k-points along a high-symmetry path with uniform reciprocal-space distance between consecutive points (not uniform in fractional coordinates), ensuring equal point spacing regardless of segment length — resolving the common issue of different segment densities in naive implementations

117.7 Diffraction Simulation (@kalika/crystallography)#

117.7.1 Structure Factor Computation#

  • 117.7.1.1 Implement atomic form factor database: store Cromer-Mann coefficients (a1-a4, b1-b4, c) for all elements and common ions, computing f(s) = sum_i a_i _ exp(-b_i _ s^2) + c where s = sin(theta)/ lambda — 9-parameter analytical approximation valid for 0 <= s <= 6 A^-1
  • 117.7.1.2 Implement anomalous scattering factor database: store dispersion corrections f'(E) and f''(E) for all elements at common X-ray energies (Henke tables for 10 eV - 30 keV, Sasaki tables above 30 keV), with interpolation for arbitrary energies — essential for resonant/anomalous diffraction and absolute structure determination
  • 117.7.1.3 Implement structure factor calculation: F(hkl) = sum_j f_j(s) _ T_j(s) _ o_j * exp(2pii*(hx_j + ky_j + l*z_j)) where f_j is the atomic form factor (including anomalous corrections), T_j is the temperature factor, o_j is the occupancy — return complex F(hkl), |F(hkl)|^2, and phase angle phi(hkl)
  • 117.7.1.4 Implement Debye-Waller temperature factor computation: isotropic Tj = exp(-B_j * s^2) where B = 8pi^2 * <u^2>, and anisotropic T_j = exp(-2pi^2 * sum{ij} U_ij _ h_i _ h_j _ a__i _ a__j) with the 6-parameter anisotropic displacement tensor U_ij — convert between B_iso, U_iso, U_ij, and beta_ij conventions
  • 117.7.1.5 Implement systematic absence determination: given a space group, determine all reflection conditions (integral, zonal, serial absence conditions) from the centering translations, glide planes, and screw axes — return a function isSystematicallyAbsent(h, k, l): boolean

117.7.2 X-ray Powder Diffraction Simulation#

  • 117.7.2.1 Implement kinematic X-ray powder diffraction pattern simulation: for a given structure and wavelength (default Cu Kalpha1 = 1.5406 A), compute 2-theta positions from Bragg's law 2dsin(theta) = n*lambda for all non-absent reflections up to a maximum 2-theta, intensities from |F(hkl)|^2 * multiplicity * Lp factor, simulate the full pattern as intensity vs 2-theta
  • 117.7.2.2 Implement Lorentz-polarization correction: Lp = (1 + cos^2(2theta)) / (sin^2(theta) * cos(theta)) for unpolarized source, with monochromator correction Lp = (1 + K * cos^2(2theta)) / (sin^2(theta) * cos(theta)) where K = cos^2(2*theta_m) for a monochromator angle theta_m
  • 117.7.2.3 Implement peak profile functions: Gaussian G(x) = sqrt(ln2/pi)/H * exp(-4ln2 * x^2/H^2), Lorentzian L(x) = 2/(piH) * 1/(1 + 4x^2/H^2), pseudo-Voigt pV(x) = etaL(x) + (1-eta)G(x), Thompson-Cox-Hastings pseudo-Voigt (FWHM varies with 2-theta: Utan^2(theta) + V*tan(theta) + W for Gaussian, X/cos(theta) + Y*tan(theta) for Lorentzian — the Caglioti formula)
  • 117.7.2.4 Implement full powder pattern generation: convolve each reflection with the peak profile function, sum all contributions over the 2-theta range, add optional background (polynomial or Chebyshev), return as arrays of 2-theta and intensity values — support multiple wavelengths (Kalpha1 + Kalpha2 with intensity ratio 0.5)
  • 117.7.2.5 Implement preferred orientation correction: March-Dollase model P(alpha) = (r^2*cos^2(alpha) + sin^2(alpha)/r)^(-3/2) where alpha is the angle between the scattering vector and the preferred orientation direction, r is the refinable parameter (r=1 for random, r<1 for plate, r>1 for needle morphology)
  • 117.7.2.6 Implement reflection multiplicity calculation: given a space group and reflection (h,k,l), compute the number of symmetry-equivalent reflections in the Laue group — this factor directly scales the integrated intensity in a powder pattern

117.7.3 Neutron & Electron Diffraction#

  • 117.7.3.1 Implement neutron scattering length database: store coherent neutron scattering lengths (b in fm) and absorption cross sections for all stable isotopes and natural-abundance elements — data from NIST neutron scattering length table, sign-aware (b can be negative)
  • 117.7.3.2 Implement neutron powder diffraction simulation: same framework as X-ray but using neutron scattering lengths instead of atomic form factors (no angular dependence for nuclear scattering), neutron wavelength specification, magnetic scattering contribution for ordered magnetic structures (using magnetic form factors and spin arrangement)
  • 117.7.3.3 Implement electron diffraction structure factor: use Mott-Bethe formula f_e(s) = (Z - f_X(s)) / (4piepsilon_0 * s^2) to convert X-ray atomic form factors to electron scattering factors, where Z is the atomic number — or use Doyle-Turner parametrization directly
  • 117.7.3.4 Implement selected area electron diffraction (SAED) pattern simulation: given a structure and zone axis [uvw], compute the reciprocal lattice section perpendicular to [uvw] (the zero-order Laue zone, ZOLZ), plot spots at positions of allowed reflections with radii proportional to |F(hkl)|, apply systematic absence rules, include first-order Laue zone (FOLZ) spots as a ring of weaker reflections
  • 117.7.3.5 Implement convergent beam electron diffraction (CBED) simulation: for a zone axis, compute the intensity distribution within each diffraction disk using the two-beam dynamical theory approximation — disk size determined by beam convergence angle, intensity varies within disk as function of excitation error, show HOLZ lines as sharp features within the central disk

117.7.4 Pattern Analysis & Refinement#

  • 117.7.4.1 Implement space group determination from systematic absences: given a list of observed and absent reflections, test against the systematic absence conditions of each space group, rank candidate space groups by consistency — report the most likely space group(s) with confidence level, flag ambiguous cases (e.g., same absences for multiple space groups)
  • 117.7.4.2 Implement Rietveld refinement engine: refine structural parameters (atom positions, occupancies, displacement parameters), profile parameters (U, V, W, X, Y, eta), lattice parameters, scale factor, background coefficients, and zero-shift against an observed powder diffraction pattern — minimize R_wp = sqrt(sum w_i(y_obs - y_calc)^2 / sum w_i * y_obs^2) using Levenberg-Marquardt nonlinear least-squares, compute GOF, R_p, R_wp, R_exp, chi^2 figures of merit
  • 117.7.4.3 Implement Le Bail whole-pattern fitting: extract integrated intensities |F(hkl)|^2 from a powder pattern without a structural model — iteratively partition overlapping peaks using the current best estimates of individual reflection intensities, refine profile and lattice parameters — used as a precursor to Rietveld refinement or for lattice parameter determination
  • 117.7.4.4 Implement pair distribution function (PDF) computation: G(r) = 4pir*(rho(r) - rho_0) from total scattering data — compute via Fourier transform G(r) = (2/pi) * integral Q[S(Q)-1]sin(Qr) dQ where S(Q) is the structure function obtained from the corrected diffraction pattern, apply Lorch modification function to reduce termination ripples, handle Qmax truncation effects
  • 117.7.4.5 Implement PDF computation from a structural model: G_calc(r) = (1/r) * sum_ij [(b_ib_j)/<b>^2] * delta(r - r_ij) - 4pir rho_0 — computed from the pair distances in the structure, broadened with thermal displacement parameters, for comparison against experimental PDF data
  • 117.7.4.6 Implement peak indexing from powder diffraction data: given a list of observed d-spacings or 2-theta positions, determine the Miller indices (hkl) and lattice parameters using the iterative singular value decomposition (ITO) method or the dichotomy method (DICVOL) — test all crystal systems from highest to lowest symmetry, rank solutions by figure of merit M_N (de Wolff) or F_N
  • 117.7.4.7 Implement Williamson-Hall analysis: from peak positions and FWHM values, plot betacos(theta) vs sin(theta) to separate crystallite size broadening (intercept = Klambda/D) from microstrain broadening (slope = 4*epsilon) — distinguish between isotropic and anisotropic broadening by analyzing hkl-dependent deviations
  • 117.7.4.8 Implement Scherrer equation: compute average crystallite size D = Klambda / (betacos(theta)) from integral breadth or FWHM of individual peaks, with shape factor K appropriate for the crystallite morphology (K=0.94 for spherical, 0.89 for cubic), correct for instrumental broadening by deconvolution or quadratic subtraction

117.8 Crystal Chemistry & Structure Analysis (@kalika/crystallography)#

117.8.1 Geometric Analysis#

  • 117.8.1.1 Implement bond length computation: given two atoms (indices or species), compute the bond length using minimum image convention, return all bond lengths of a given type (e.g., all Si-O distances) sorted by length — compare against tabulated values (Shannon ionic radii, Cordero covalent radii)
  • 117.8.1.2 Implement bond angle computation: for a triplet of atoms (A-B-C where B is central), compute the angle using minimum image convention for the BA and BC vectors, enumerate all angles of a given type (e.g., all O-Si-O angles in a silicate)
  • 117.8.1.3 Implement torsion (dihedral) angle computation: for a quadruplet (A-B-C-D), compute the torsion angle as the angle between the ABC and BCD planes, handling periodic boundary conditions — essential for organic crystal analysis and conformational studies
  • 117.8.1.4 Implement automatic bond detection: given a structure, identify all bonds using the sum-of-covalent-radii criterion with a tolerance factor (default 1.2), return as a bond graph (adjacency list) — handle metallic bonds with separate metallic radius table
  • 117.8.1.5 Implement bond valence sum computation: for each cation site, compute s_ij = exp((R_0 - r_ij) / b) for each cation-anion pair using Brown-Altermatt bond valence parameters (R_0, b=0.37 A from Brese & O'Keeffe 1991), sum over coordinating anions to get the bond valence sum V_i — deviation from formal valence indicates over/under-bonding (Global Instability Index GII = sqrt(sum (V_i - q_i)^2 / N))
  • 117.8.1.6 Implement interatomic distance histogram: compute all pairwise distances up to a cutoff, bin into a histogram (partial and total radial distribution functions g_AB(r)), identify peaks corresponding to coordination shells — useful for amorphous and disordered structures

117.8.2 Polyhedral Analysis#

  • 117.8.2.1 Implement coordination polyhedra identification: given a central atom and its coordinating atoms, identify the polyhedron type (tetrahedron, octahedron, cube, trigonal prism, square antiprism, tricapped trigonal prism, cuboctahedron, icosahedron, etc.) by comparing the arrangement against ideal polyhedra using continuous symmetry measures (CSM)
  • 117.8.2.2 Implement polyhedral distortion indices: compute quadratic elongation <lambda> = (1/n) _ sum (l_i/l_0)^2, bond angle variance sigma^2 = (1/(m-1)) _ sum (phi_i - phi_0)^2 (Robinson et al. 1971), effective coordination number (ECoN), volume of coordination polyhedron, and comparison to ideal polyhedron volumes
  • 117.8.2.3 Implement continuous symmetry measures (CSM): for a set of coordinating atoms, compute S(G) = min sum |P_i - P_i_ideal|^2 / sum |P_i - P_centroid|^2 * 100 over all orientations and scale factors of the ideal polyhedron with symmetry G — using the Pinsky-Avnir algorithm, values 0 (perfect) to 100 (no symmetry)
  • 117.8.2.4 Implement polyhedral connectivity analysis: determine how coordination polyhedra are connected — corner-sharing (one shared atom), edge-sharing (two shared atoms), face-sharing (three+ shared atoms) — classify the connectivity pattern (e.g., isolated, chain, layer, 3D framework) — critical for understanding structure topology

117.8.3 Tolerance Factors & Structure Prediction#

  • 117.8.3.1 Implement Goldschmidt tolerance factor for perovskites: t = (r_A + r_O) / (sqrt(2) * (r_B + r_O)) using Shannon ionic radii — predict stability: 0.9 < t < 1.0 cubic, 0.71 < t < 0.9 orthorhombic distortion, t > 1 hexagonal polytypes; also implement the octahedral factor mu = r_B / r_O
  • 117.8.3.2 Implement generalized tolerance factors: radius ratio rules (r+/r- ranges for CN 3, 4, 6, 8, 12), Madelung energy-based stability analysis, Villars structure maps (electronegativity difference vs radius ratio), Pettifor chemical scale maps (Mendeleev number ordering)
  • 117.8.3.3 Implement Pauling's rules as structure validators: (1) radius ratio determines coordination, (2) electrostatic valence principle (bond strength sum = charge), (3) edge/face sharing destabilizes, (4) cations with high valence and small CN tend not to share polyhedra, (5) number of structurally distinct sites is small — quantitative checks against a given structure

117.8.4 Prototype Structure Library#

  • 117.8.4.1 Implement prototype structure database with at least 50 common structure types, each with: structure type name, Strukturbericht designation (where applicable), prototype compound, Pearson symbol, space group, Wyckoff positions, lattice parameter ratios — including: rock salt (B1, Fm-3m), zinc blende (B3, F-43m), wurtzite (B4, P6_3mc), cesium chloride (B2, Pm-3m), fluorite (C1, Fm-3m), antifluorite, rutile (C4, P4_2/mnm), corundum (D5_1, R-3c), perovskite (E2_1, Pm-3m), spinel (H1_1, Fd-3m), inverse spinel, garnet (Ia-3d), diamond (A4, Fd-3m), FCC (A1, Fm-3m), BCC (A2, Im-3m), HCP (A3, P6_3/mmc), beta-tin (A5), graphite (A9), NiAs (B8_1), pyrite (C2, Pa-3), ilmenite (R-3), scheelite (I4_1/a), zircon (I4_1/amd), calcite (R-3c), aragonite (Pmcn), olivine (Pnma), sodalite (Im-3m), cristobalite (Fd-3m), quartz (P3_121), delafossite (R-3m), chalcopyrite (I-42d), layered (CdI2/CdCl2), Heusler (Fm-3m), half-Heusler (F-43m), skutterudite (Im-3), clathrate, Laves (MgCu2/MgZn2/MgNi2), sigma phase, A15 (Pm-3n), Th3P4, Mn5Si3, CaCu5 (P6/mmm), ThCr2Si2 (I4/mmm), NaFeAs (P4/nmm), TiAl3 (I4/mmm), Cu3Au (L1_2, Pm-3m), CuAu (L1_0, P4/mmm), NaTl (Fd-3m)
  • 117.8.4.2 Implement prototype instantiation: given a prototype name and list of species + lattice parameters, generate the corresponding Structure — e.g., Prototypes.perovskite("Ba", "Ti", "O", a=3.99) creates BaTiO3 in cubic perovskite structure
  • 117.8.4.3 Implement structure type classification: given an unknown structure, determine its structure type by comparing against all prototypes using anonymous formula matching, space group matching, and Wyckoff position matching (with tolerance for small distortions) — return ranked list of matching prototypes with similarity scores

117.8.5 Topological Analysis#

  • 117.8.5.1 Implement net topology analysis (TOPOS-style): represent the crystal structure as a periodic net (graph embedded in the torus), determine the underlying topology by simplification (removing 2- connected nodes, identifying clusters as single nodes), classify using the RCSR (Reticular Chemistry Structure Resource) three-letter codes (e.g., dia for diamond, pcu for primitive cubic, sod for sodalite)
  • 117.8.5.2 Implement void analysis for porous materials: compute the probe-accessible void volume and surface area using a spherical probe (default r = 1.2 A for N2-accessible), determine the largest included sphere (Di), largest free sphere (Df, the largest sphere that can traverse the structure), and largest included sphere along free path (Dif) — using Voronoi network analysis (similar to Zeo++ algorithm)
  • 117.8.5.3 Implement channel detection: identify connected void pathways through the crystal along each crystallographic direction ([100], [010], [001] and combinations), determine channel dimensionality (0D cage, 1D channel, 2D layer, 3D pore network), compute channel diameter profile along the path — essential for zeolites, MOFs, and ion conductors

117.9 Surface & Slab Models (@kalika/crystallography)#

117.9.1 Surface Generation#

  • 117.9.1.1 Implement Miller index surface construction: given a bulk structure and Miller indices (hkl), find the lattice vectors of the surface unit cell by (1) computing the normal direction n = ha + kb + lc (reciprocal lattice), (2) finding two lattice vectors perpendicular to n (shortest ones using the extended GCD / HNF approach), (3) orienting the cell with the surface normal along z
  • 117.9.1.2 Implement slab model construction: from the surface unit cell, create a slab of specified thickness (in number of layers or Angstroms) by stacking layers, add a vacuum layer of specified thickness along the z-direction, return as a Structure with the slab centered in the cell
  • 117.9.1.3 Implement surface termination enumeration: for a given (hkl) surface, identify all inequivalent surface terminations by scanning the z-position of the cutting plane through one repeat unit, group terminations by symmetry equivalence, report the composition of each termination and whether it is stoichiometric
  • 117.9.1.4 Implement Tasker classification: for ionic surfaces, classify as Type I (each layer is charge-neutral and has no dipole), Type II (charged layers but the repeat unit has no dipole), or Type III (charged layers with net dipole — polar, unstable without reconstruction) — analyze the layer-by-layer charge and cumulative dipole
  • 117.9.1.5 Implement non-polar surface selection: given a structure, enumerate low-index surfaces (up to max Miller index), classify each by Tasker type, return only non-polar (Type I and II) surfaces sorted by surface density (lower density ~ higher surface energy) — for efficient surface energy screening

117.9.2 Slab Properties & Manipulation#

  • 117.9.2.1 Implement symmetric slab generation: given a surface termination, construct a slab that is symmetric with respect to a mirror plane or inversion center at its midpoint — required for correct surface energy calculations (no net dipole), may require odd or even numbers of layers depending on the space group
  • 117.9.2.2 Implement dipole correction for polar slabs: for Type III surfaces, implement the compensating charge method — add a uniform electric field in the vacuum region to cancel the slab dipole, compute the required field strength from the slab dipole moment per unit area
  • 117.9.2.3 Implement surface energy computation workflow: given bulk and slab structures, compute surface energy gamma = (E_slab - nE_bulk) / (2A) for symmetric slabs — handle convergence with respect to slab thickness and vacuum thickness, cleavage energy for stoichiometric surfaces, generalized surface energy for non-stoichiometric surfaces using chemical potentials
  • 117.9.2.4 Implement Wulff construction: given surface energies gamma(hkl) for multiple facets, construct the equilibrium crystal shape (Wulff shape) — compute the convex hull of the inner envelope of planes at distance gamma(hkl) from the origin along each normal direction, return vertices, faces, face areas, and the fraction of each facet on the surface
  • 117.9.2.5 Implement slab convergence analysis: generate a series of slabs with increasing thickness, compute layer-resolved properties (interlayer spacing, Bader charges if available), determine the minimum number of layers for bulk-like interior behavior
  • 117.9.2.6 Implement surface reconstruction representation: support reconstructed surfaces with non-(1x1) surface unit cells — e.g., Si(100)-(2x1), Si(111)-(7x7), Au(110)-(1x2) missing row — by applying a surface supercell transformation and modifying the top-layer atom positions according to known reconstruction patterns
  • 117.9.2.7 Implement selective dynamics assignment for slabs: automatically set fixed/free flags for each atom based on distance from the surface — atoms in the interior (below a specified depth threshold) are fixed to mimic bulk behavior, surface and near-surface atoms are free to relax — write the flags in VASP selective dynamics format

117.9.3 Adsorption Site Analysis#

  • 117.9.3.1 Implement adsorption site enumeration: given a slab model, automatically identify high-symmetry adsorption sites on the surface — atop (directly above a surface atom), bridge (midpoint between two surface atoms), hollow (center of three or more surface atoms: fcc hollow, hcp hollow for FCC surfaces) — using the Delaunay triangulation of surface atoms projected onto the surface plane
  • 117.9.3.2 Implement adsorbate placement: given a slab and an adsorption site, place a molecular adsorbate (atom or molecule) at a specified height above the surface, with controllable orientation (tilt angle, rotation about surface normal), return the combined slab+adsorbate structure
  • 117.9.3.3 Implement substrate-adsorbate strain matching: for epitaxial interfaces, find the best substrate-adsorbate orientation relationship by scanning rotation angles and supercell sizes, minimizing the lattice mismatch — return the strain tensor, the supercell transformation matrices for both substrate and adsorbate, and the residual strain

117.10 Interface & Heterostructure Construction (@kalika/crystallography)#

117.10.1 Grain Boundary Models#

  • 117.10.1.1 Implement coincidence site lattice (CSL) computation: given a crystal structure and a rotation axis+angle, compute the CSL — the sublattice of points common to both the original and rotated lattices — using the analytical formulas for cubic systems (Grimmer, Bollmann) and numerical methods for lower symmetry, determine the Sigma value (ratio of unit cell volume to CSL cell volume, always odd for cubic)
  • 117.10.1.2 Implement Sigma value enumeration: for a given crystal system and rotation axis, enumerate all CSL rotations with Sigma <= Sigma_max (sorted by Sigma value), compute the misorientation angle for each — provide the standard Sigma rotation table for cubic systems (Sigma 3 = 60 degree <111>, Sigma 5 = 36.87 degree <100>, etc.)
  • 117.10.1.3 Implement tilt grain boundary construction: given a rotation axis perpendicular to the grain boundary plane, a tilt angle (from the CSL table), and the grain boundary plane orientation, construct a bicrystal model — two half-crystals joined at the boundary with appropriate periodic boundary conditions, rigid body translations for finding the minimum energy configuration
  • 117.10.1.4 Implement twist grain boundary construction: given a rotation axis normal to the grain boundary plane and a twist angle, construct the bicrystal model — the in-plane CSL determines the supercell size, stack the two rotated grains along the twist axis with vacuum or periodic boundary conditions

117.10.2 Heterojunction & Heterostructure Models#

  • 117.10.2.1 Implement lattice matching for heterojunction construction: given two different crystal structures, find the optimal interface orientation by scanning surface Miller indices of both materials, computing the strain tensor for each combination, ranking by total strain energy — use the algorithm of Zur & McGill (1984) that finds the smallest supercells with strain below a threshold
  • 117.10.2.2 Implement heterojunction model construction: given two matched surfaces (from lattice matching), construct the interface model by stacking the two slabs along the interface normal, adjusting interlayer spacing, and applying the appropriate supercell transformation to both slabs to achieve commensurability
  • 117.10.2.3 Implement strain analysis for interfaces: given an interface model, decompose the total strain into biaxial in-plane strain and uniaxial out-of-plane strain (Poisson response), compute the elastic strain energy density from the elastic constants of each material, determine the critical thickness for misfit dislocation formation (Matthews-Blakeslee model: h_c = b/(2pif) * (ln(h_c/b) + 1) where b is the Burgers vector and f is the misfit)

117.10.3 2D Heterostructures & Moire Patterns#

  • 117.10.3.1 Implement Moire pattern analysis: given two 2D layers with different lattice constants or a relative twist angle theta, compute the Moire superlattice vectors using the formula a_M = a / (2*sin(theta/2)) for commensurate angles (or the approximate supercell for incommensurate angles), determine the Moire wavelength and real-space pattern
  • 117.10.3.2 Implement commensurate twist angle enumeration: for two identical 2D lattices, find all commensurate twist angles (where the Moire pattern is periodic) by enumerating pairs of lattice vectors (m1, m2) and (n1, n2) related by the rotation — list angles, supercell sizes, and number of atoms for each, filter by maximum supercell size
  • 117.10.3.3 Implement twisted bilayer/multilayer construction: given a 2D material structure and a twist angle, construct the twisted bilayer by (1) finding the commensurate Moire cell, (2) populating both layers with atoms from the original structure, (3) adjusting interlayer spacing, (4) registering stacking type (AA, AB, SP) at each point — support arbitrary layer numbers (trilayer, etc.)
  • 117.10.3.4 Implement superlattice generation: construct periodic superlattices by alternating layers of two different materials with specified thicknesses (in number of unit cells), apply strain matching at each interface, compute the superlattice period and mini-zone boundaries
  • 117.10.3.5 Implement stacking sequence enumeration for layered materials: for materials with multiple possible stacking orders (e.g., graphite AB vs ABC, TMDs 2H vs 1T vs 1T'), enumerate all distinct stacking sequences up to a specified number of layers, classify by resulting space group symmetry, and generate the corresponding Structure for each
  • 117.10.3.6 Implement interlayer binding analysis: for van der Waals heterostructures, compute the registry-dependent interlayer potential energy surface by rigid sliding of one layer over another (generating a 2D energy landscape as a function of lateral shift), identify energy minima corresponding to favorable stacking configurations (AB, AA', etc.)

117.11 Symmetry-Adapted Properties (@kalika/crystallography)#

117.11.1 Tensor Symmetry Constraints#

  • 117.11.1.1 Implement Neumann's principle enforcement: given a crystal point group and a property tensor of specified rank and symmetry, compute the independent tensor elements by requiring T = R^T _ T _ R for all point group operations R — return the number of independent elements and the constraint equations relating dependent elements to independent ones
  • 117.11.1.2 Implement symmetry-allowed tensor elements for all 32 crystal classes: precompute and store the independent element patterns for rank-2 symmetric tensors (dielectric, thermal conductivity, thermal expansion: triclinic 6, monoclinic 4, orthorhombic 3, tetragonal 2, trigonal 2, hexagonal 2, cubic 1 independent), rank-3 tensors (piezoelectric: 18 independent for triclinic down to 1 for some cubic classes), rank-4 symmetric tensors (elastic: 21 independent for triclinic down to 3 for cubic)
  • 117.11.1.3 Implement Voigt notation conversion: convert between full tensor notation and Voigt notation for rank-2 (3x3 -> 6-vector), rank-3 (3x3x3 -> 3x6 matrix), and rank-4 (3x3x3x3 -> 6x6 matrix) tensors, applying the correct factors of 2 for shear components — essential for elastic constant representation (C_ijkl -> C_mn in Voigt)

117.11.2 Property Tensor Computation#

  • 117.11.2.1 Implement dielectric tensor symmetry (rank 2): given the crystal class, return the form of the dielectric tensor epsilon_ij with constraints applied — diagonal for orthorhombic and higher, epsilon_11 = epsilon_22 for tetragonal/hexagonal/trigonal, isotropic for cubic
  • 117.11.2.2 Implement piezoelectric tensor symmetry (rank 3): given the crystal class, return the form of the piezoelectric tensor d_ijk in Voigt notation (d_in, 3x6 matrix) with zero and equal elements marked — non-zero only for non-centrosymmetric classes (21 of the 32 classes, with further restriction: 20 piezoelectric classes excluding point group 432)
  • 117.11.2.3 Implement elastic stiffness tensor symmetry (rank 4): given the crystal class, return the form of the elastic stiffness tensor C_ijkl in Voigt notation (C_mn, 6x6 matrix) with the specific constraint pattern — from 21 independent elements (triclinic) down to 3 (cubic: C11, C12, C44), including the special relationships (e.g., hexagonal C66 = (C11 - C12)/2, isotropic: only 2 independent)
  • 117.11.2.4 Implement elastic compliance tensor: compute the compliance tensor Smn = C_mn^(-1) (matrix inverse of the 6x6 Voigt stiffness matrix), compute engineering moduli from compliance: Young's modulus E_i = 1/S_ii, Poisson's ratio nu_ij = -S_ji/S_ii, shear modulus G_ij = 1/S(i+3)(i+3)
  • 117.11.2.5 Implement Voigt-Reuss-Hill averaging: for polycrystalline aggregates, compute Voigt upper bound (uniform strain assumption, arithmetic mean of C_ij), Reuss lower bound (uniform stress assumption, harmonic mean via S_ij), and Hill average (arithmetic mean of Voigt and Reuss) for bulk modulus K, shear modulus G, Young's modulus E, and Poisson's ratio nu — the standard polycrystalline elastic property estimates
  • 117.11.2.6 Implement elastic anisotropy measures: compute Zener anisotropy ratio A = 2C44/(C11-C12) for cubic crystals (A=1 for isotropic), universal anisotropy index A_U = 5G_V/G_R + K_V/K_R - 6 (Ranganathan & Ostoja-Starzewski), and directional Young's modulus E(n) = 1/(S_ijkl _ n_i _ n_j _ n_k _ n_l) as a function of direction — generate the 3D anisotropy surface for visualization
  • 117.11.2.7 Implement thermal expansion tensor symmetry (rank 2): analogous to dielectric tensor, determine the independent components of the thermal expansion coefficient tensor alpha_ij for each crystal class, convert between linear and volumetric expansion coefficients

117.11.3 Symmetry Breaking Analysis#

  • 117.11.3.1 Implement symmetry breaking analysis for phase transitions: given a high-symmetry parent structure and a lower-symmetry child structure, identify the symmetry elements lost in the transition, determine the order parameter symmetry (which irreducible representation of the parent space group describes the distortion), classify as ferroelectric (polar distortion), ferroelastic (strain distortion), or other
  • 117.11.3.2 Implement distortion mode analysis: decompose the structural distortion (difference between parent and child structures) into symmetry-adapted modes — project the displacement pattern onto the basis functions of each irreducible representation of the parent space group (AMPLIMODES algorithm from Bilbao), report the amplitude of each mode
  • 117.11.3.3 Implement Landau theory connection: given the order parameter symmetry (irrep), construct the Landau free energy expansion F = F_0 + aQ^2 + bQ^3 + c*Q^4 + ... (with terms constrained by the irrep symmetry — odd-order terms vanish if the order parameter cannot form a scalar), determine if the transition is first-order (b != 0) or second-order (b = 0), identify coupling terms between multiple order parameters
  • 117.11.3.4 Implement Curie's principle application: given a crystal under an external perturbation (electric field, magnetic field, uniaxial stress), determine the resulting symmetry as the intersection of the crystal point group with the symmetry group of the perturbation — predict which symmetry elements survive and what new property tensors become non-zero

117.12 Comprehensive Test Suite (@kalika/crystallography)#

117.12.1 Lattice Tests#

  • 117.12.1.1 Test all 14 Bravais lattice constructors: verify lattice parameters, volume, reciprocal lattice vectors, metric tensor for each type — test with known crystal data (e.g., Si: Fd-3m, a=5.431 A, V=160.18 A^3; alpha-quartz: P3_121, a=4.916 A, c=5.405 A)
  • 117.12.1.2 Test Niggli reduction: verify convergence for challenging cases (nearly degenerate cells, very oblique angles), test roundtrip (reduce, then verify Niggli conditions are satisfied), compare against spglib reference output for a set of benchmark cells
  • 117.12.1.3 Test Delaunay and Minkowski reduction: verify against known reduced forms, test that equivalent lattices produce the same reduced cell, test numerical stability with near-degenerate inputs
  • 117.12.1.4 Test supercell generation: verify atom count (N_supercell = det(P) * N_original), verify all original lattice vectors are expressible as integer combinations of supercell vectors, test both diagonal and non-diagonal transformations
  • 117.12.1.5 Test strain tensor computation: apply a known strain to a lattice, recompute the strain tensor from original and deformed, verify roundtrip consistency — test Green-Lagrange vs infinitesimal for small strains (should agree to O(epsilon^2))

117.12.2 Space Group Tests#

  • 117.12.2.1 Test all 230 space groups: verify that generator sets produce the correct number of general position operations (accounting for centering multiplicity), verify group closure, verify that Hermann- Mauguin, Schoenflies, and Hall symbols are consistent
  • 117.12.2.2 Test symmetry operation classification: for known operations in each space group, verify correct identification as rotation, screw, mirror, glide, rotoinversion — test all screw axis types (2_1, 3_1, 3_2, 4_1, 4_2, 4_3, 6_1...6_5) and glide types (a, b, c, n, d)
  • 117.12.2.3 Test Wyckoff positions: for selected space groups (at least Fm-3m, Pm-3m, P6_3/mmc, Pnma, I4/mmm, R-3c, Fd-3m, P2_1/c), verify that generating all Wyckoff positions produces the correct multiplicity and site symmetry
  • 117.12.2.4 Test space group detection: for known crystal structures (Si, NaCl, GaAs, BaTiO3, alpha-Fe, alpha-quartz, corundum, spinel), detect the space group and verify it matches the known space group — test with different tolerance values
  • 117.12.2.5 Test structure symmetrization: distort a known structure by adding random noise, detect symmetry, symmetrize, verify the symmetrized structure has the correct space group and atoms are at Wyckoff positions

117.12.3 Structure & I/O Tests#

  • 117.12.3.1 Test Structure class operations: create structures, verify distance calculations against hand-computed values (e.g., nearest- neighbor distance in FCC = a/sqrt(2)), test neighbor finding with known coordination numbers (FCC CN=12, BCC CN=8, diamond CN=4)
  • 117.12.3.2 Test StructureMatcher: verify that equivalent structures (same structure in different settings, with different atom orderings, or with small perturbations) are correctly matched, and non-equivalent structures are correctly distinguished
  • 117.12.3.3 Test CIF roundtrip: write a structure to CIF, read it back, verify the structure is identical (within numerical precision) — test with structures containing symmetry operations, anisotropic displacement parameters, disordered sites
  • 117.12.3.4 Test POSCAR roundtrip: write a structure to POSCAR, read it back, verify identical — test with selective dynamics flags, multiple species, large supercells
  • 117.12.3.5 Test all other format roundtrips (XYZ, PDB, QE, ABINIT, FHI-aims, LAMMPS, SHELX, Gaussian, JSON): write and read back representative structures, verify consistency within format limitations (some formats lose space group or occupancy information)

117.12.4 Reciprocal Space & Diffraction Tests#

  • 117.12.4.1 Test reciprocal lattice: verify a_i . b_j = 2pidelta_ij for all 14 Bravais lattice types, verify reciprocal lattice volume = (2*pi)^3 / V_direct
  • 117.12.4.2 Test high-symmetry k-point paths: for FCC, BCC, HCP, and simple cubic lattices, verify that the standard k-points (Gamma, X, L, W, K, U, etc.) are at the correct fractional coordinates and lie on the Brillouin zone boundary (verified by d-spacing)
  • 117.12.4.3 Test Monkhorst-Pack grid generation: verify grid dimensions, verify Gamma-centering, verify irreducible k-point count matches expectations (e.g., 8x8x8 grid for FCC with time reversal: 60 irreducible k-points)
  • 117.12.4.4 Test X-ray diffraction simulation: for Si (Fd-3m, a=5.431 A), verify that (111), (220), (311) peaks appear at correct 2-theta positions for Cu Kalpha, verify that (200) is systematically absent (F-centering), verify relative intensities match ICDD reference patterns within 10%
  • 117.12.4.5 Test structure factor magnitudes: compute |F(hkl)|^2 for NaCl at (200), (111), (220) — verify (111) intensity proportional to (f_Na - f_Cl)^2 and (200) proportional to (f_Na + f_Cl)^2 as expected from the FCC structure with two-atom basis

117.12.5 Surface & Interface Tests#

  • 117.12.5.1 Test surface generation: for FCC Al, generate (111), (100), (110) surfaces, verify surface atom positions match known configurations (FCC(111) is close-packed with ABC stacking), verify surface unit cell areas: A(111) = a^2*sqrt(3)/2, A(100) = a^2/2, A(110) = a^2/sqrt(2)
  • 117.12.5.2 Test slab model: verify slab has correct number of atoms (layers _ atoms_per_layer _ surface_cell_multiplicity), verify vacuum gap is correct, verify symmetric slab is actually symmetric (inversion or mirror at midpoint)
  • 117.12.5.3 Test Wulff construction: for a cube (all {100} faces equal energy), verify the Wulff shape is a cube; for FCC metals with gamma(111) < gamma(100) < gamma(110), verify the truncated octahedron shape appears
  • 117.12.5.4 Test CSL and grain boundary construction: for FCC Sigma 3 twin boundary (60 degree about <111>), verify the CSL has 3x the unit cell volume, verify the twin boundary structure matches the known coherent twin configuration
  • 117.12.5.5 Test Moire pattern computation: for graphene twisted by theta = 21.79 degrees (commensurate angle with 28 atoms), verify the supercell vectors, atom count, and Moire wavelength match the known values

117.12.6 Symmetry-Adapted Property Tests#

  • 117.12.6.1 Test tensor symmetry constraints: for cubic system (Oh), verify that the elastic tensor has exactly 3 independent elements (C11, C12, C44); for hexagonal (6/mmm), verify 5 independent elements with C66 = (C11-C12)/2; for isotropic, verify 2 independent with C44 = (C11-C12)/2
  • 117.12.6.2 Test piezoelectric tensor constraints: verify that centrosymmetric crystal classes have identically zero piezoelectric tensor (11 of 32 classes), verify specific non-zero patterns for known piezoelectric materials (e.g., wurtzite class 6mm has d31=d32, d33, d15 non-zero only)
  • 117.12.6.3 Test distortion mode analysis: for BaTiO3 cubic-to- tetragonal transition (Pm-3m -> P4mm), verify the primary distortion mode is the Gamma_4- (T1u) polar mode, verify the amplitude is consistent with the atomic displacement magnitude

117.12.7 Integration Tests#

  • 117.12.7.1 End-to-end test: read a CIF file (e.g., BaTiO3 from COD), detect space group, find Wyckoff positions, generate reciprocal lattice, compute high-symmetry k-path, generate XRD pattern, write POSCAR — verify consistency at each step
  • 117.12.7.2 End-to-end test: read a POSCAR (Si supercell), find the primitive cell, detect space group (should recover Fd-3m), generate (111) surface slab, enumerate adsorption sites, write CIF — verify all operations preserve physical consistency
  • 117.12.7.3 End-to-end test: create a perovskite from prototype library, compute tolerance factor, generate all low-index surfaces, classify by Tasker type, compute Wulff shape from assumed surface energies — verify the workflow produces physically reasonable results
  • 117.12.7.4 Performance benchmark: Niggli reduction of 10,000 random lattices (< 5 seconds), space group detection for 1,000 structures with 100 atoms each (< 30 seconds), neighbor list construction for a 10,000- atom supercell (< 2 seconds) — verify Rust kernel provides adequate performance

<!-- prettier-ignore-end -->