UP | HOME

Conventions and units

minimage is unit-agnostic: coordinates, lattice vectors, origins, and displacements share one caller-chosen Cartesian length unit, and squared distances and cutoffs use that unit squared. The single exception is from_con_box (minimage_cell_from_con_box), which takes the three cell angles alpha, beta, and gamma in degrees. Fractional coordinates from Cell::fractional are dimensionless in [0, 1).

Internally, Cell stores the three lattice vectors a, b, and c as the columns of the 3x3 matrix H, so Cartesian coordinates are r = H s + origin and fractional coordinates fold via s = Hinv (r - origin). Constructors that take three separate vectors (Cell::from_vectors, minimage_cell_from_vectors) pass columns, whereas ASE, CON, and vesin constructors (from_ase, from_con, from_vesin, PartialCell::from_ase, and their minimage_* C equivalents) accept row-major 3x3 arrays [a, b, c].

Every displacement function computes the wrapped vector from p to q, meaning wrap(q - p). The cell origin cancels in every displacement and squared distance call.

Fractional wrap and triclinic cells

A periodic cell is a parallelepiped whose edges are the columns of H. Cartesian coordinates fold to fractional coordinates s = Hinv (r - origin), wrap each component into the central image, then map back r = H s. Squared engine distance is |H wrap(Hinv (q - p))|^2.

Orthorhombic cells

Orthorhombic boxes are the diagonal case (Allen and Tildesley; Frenkel and Smit). Each axis is d - L floor(d/L + 1/2) for every image, not a single subtraction. The half-box tie keeps -L/2 and maps +L/2 onto -L/2, matching LAMMPS dump relDist in d-SEAMS (Goswami et al., J. Chem. Inf. Model. 60, 2169, 2020, doi:10.1021/acs.jcim.0c00031). wrap_ortho_half_strict is the scalar alternative for a closed interval. It folds the exact remainder fmod(d, L) with at most one addition or subtraction of L, which is exact by Sterbenz's lemma, so it never rounds a quotient: a value one ulp inside L/2 stays put and 1e308 against 0.5 gives 0. An exact binary tie keeps the sign of d, so +L/2 and -L/2 are both reachable.

An edge -L spans the lattice the edge +L spans, so an orthorhombic cell stores each lattice vector with a positive diagonal entry: Cell::ortho(-15, 10, 10) is Cell::ortho(15, 10, 10). The wrap, the fold into fractional coordinates, and a lattice shift all count in those stored vectors, and the integer shifts of filter_shifted and pairs_within_images count them too. Read the vectors back from the cell (Cell::a, b, c, or the mi_cell a minimage_cell_from_* call wrote) before applying an integer shift; a hand-filled mi_cell with a negative diagonal edge is read as the positive one. A sheared cell keeps the vectors it was given, whatever their signs or handedness, because its wrap goes through H and its inverse and has no separate width to disagree with. A zero, infinite, or NaN edge on a periodic axis is Error::BadBox. Two positions folded into the box are less than one length apart on every axis, so the wrap is two selects and the floor runs only past that. A squared distance needs no sign: for |d| < L the wrapped length is min(|d|, L - |d|), the same square bit for bit with a third of the selects.

Baseline x86-64 has no rounding instruction, so f64::round and floor are libm calls. Rounding half away from zero adds the largest double below one half, with the sign of the argument, and truncates toward zero. That is the same integer for every finite double, and the expansion LLVM itself uses when SSE4.1 is present. The same truncation runs on every architecture. Truncation of a negative zero is +0.0, so floor_fast(-0.0) is +0.0 and the fractional part of -0.0 is -0.0. f64::floor(-0.0) keeps the minus sign and is not used. See SIMD paths and dispatch.

Restricted and general triclinic cells

A restricted triclinic box (a along x, b in the xy plane, with upper-triangular tilts xy, xz, yz) uses the triangular lamda step of LAMMPS Domain::minimum_image, HOOMD BoxDim::minImage, OpenMM applyPeriodic, and GROMACS pbc_dx (Tuckerman, Statistical Mechanics: Theory and Molecular Simulation, doi:10.1093/oso/9780198825562.001.0001; Wassenaar). It wraps sz, then sy, then sx using half-away-from-zero rounding (round_away), avoiding a general 3x3 inverse multiply.

A general triclinic orientation (is_restricted() = false=) computes two 3x3 products with Hinv and H. Cell::reduce_tilts applies unimodular GROMACS correct_box reduction so that |xy| < |lx|/2=, |xz| < |lx|/2=, and |yz| < |ly|/2= (tested by tilts_reduced()), preserving the Cartesian lattice. Cell::to_restricted rotates a general parallelepiped into the restricted-triclinic frame (LAMMPS define_general_triclinic).

Batch fusion

dist2_many, dist2_pairs, and wrap_many are one SIMD pass over the packed rows for every cell shape: four rows load as three vectors, subtract while still packed, and transpose once in registers, with no staging buffer (map fusion in the sense of DaCe and Futhark). An orthorhombic wrap is per element and does not transpose at all. Each lane runs the per-pair operations in the per-pair order, so a batch squared distance equals the per-pair call bit for bit and a wrapped vector equals it up to the sign of a zero. dist2_ortho_diffs keeps the Highway BatchPeriodicDistSq shape: precomputed differences, one reciprocal per axis, abs, then round.

Where the processor has AVX-512F and DQ, eight rows go per pass: two-source permutes transpose them, and the last rows load and store under a lane mask, so no batch ends in a scalar tail. The intrinsics are stable from Rust 1.89, which build.rs checks; an older compiler keeps the AVX path. The orthorhombic wrap stays at four rows. It stores as much as it loads, and a 64-byte store splits a cache line on all but one alignment in eight.

Euclidean nearest image and Selling reduction

Smith, CCP5 Newsletter 1989: the engine wrap is the Euclidean nearest image when its length is strictly below half the smallest face altitude. That is the cutoff regime. Linkcell k-NN has no cutoff. A hex-prism body diagonal is an engine wrap that is longer than another image, even when the cell is already tilt-reduced and Minkowski-reduced.

Past that test, displacement_euclidean (minimage_displacement_euclidean in C) finds the closest lattice image from the obtuse superbasis every three-dimensional lattice has (Selling, J. Math. Pures Appl. 1874; Conway and Sloane, Proc. R. Soc. Lond. A 436, 55, 1992, doi:10.1098/rspa.1992.0004). A near-parallel basis makes the one-vector Delone step linear in the reciprocal of the angle, so Lagrange's size reduction (1773; Gauss,

  1. shortens the edges first, keeping the Delone loop within the

1000-step bound used by spglib and Andrews, Bernstein, and Sauter (Acta Cryst. A 75, 115, 2019, doi:10.1107/s2053273318015413). The superbasis is cached on the calling thread, keyed by H, and is built on the first query that fails the Smith test. Constructors do not build it.

The query rounds in three of the four superbasis vectors (Babai, Combinatorica 6, 1, 1986, doi:10.1007/bf02579403), then runs the iterative slicer of Sommer, Feder, and Shalvi (SIAM J. Discrete Math. 23, 715, 2009, doi:10.1137/060676362): while some relevant vector r has 2 |x . r| > |r|^2, step by r. Every Voronoi-relevant vector of an obtuse superbasis is one of seven classes +/- v_S (Conway and Sloane, 1992), so where the walk stops x is the shortest vector of its coset. A restricted cell with its tilts inside half an edge starts from the engine wrap instead of Babai's point. McKilliam, Grant, and Clarkson (SIAM J. Discrete Math. 28, 1405, 2014, doi:10.1137/140952806) search the same subset sums in three rounds of fifteen. A tie keeps the engine vector.

dist2_euclidean_many and dist2_euclidean_pairs look the superbasis up once per call and run the slicer on eight rows per AVX-512 pass: a row's seven dot products are one lane of eight vectors, the select tree runs lane by lane, and a lane's Gram row is one vpermpd of the stored rows. The Smith test becomes a lane mask, so the branch that a single query mispredicts is gone, and a group whose lanes all pass it skips the slicer. Each lane keeps the scalar order, its step choice, and its step count, so a batch equals the per-pair call bit for bit. Without AVX-512 the batch runs the per-pair code with the one lookup.

Across frames a pair seldom leaves its image. dist2_euclidean_pairs_warm keeps each pair's cell-basis shift n from the previous call: subtracting H n and testing the seven relevant vectors replaces the search for a pair still in its Voronoi cell, and the others take the full search and store their new shift. Integer shifts stay right when the cell deforms. While the pairs fit in cache this is 2.2 to 2.8 times faster than the batch; from main memory, where the shifts are one more stream, 1.15 times. The image is the one the search finds, and the distance equals it to rounding, since H n is subtracted directly rather than through the engine wrap.

Nguyen and Stehle (ACM Trans. Algorithms 5, 46, 2009, doi:10.1145/1597036.1597050) Minkowski-reduce a basis (minkowski_reduce and is_minkowski_reduced, supporting the 27-image check displacement_cartesian), though Minkowski reduction alone does not eliminate the hex-prism body diagonal check without searching all 27 combinations. The linked-cell pair itself is Rapaport's shift, |q + shift - p|^2, exposed as dist2_shifted_many. A bin that is an index list rather than a contiguous slice is dist2_shifted_indexed: it gathers a chunk of those positions into the same kernel. The gather copies every point first. On a long index list that copy was slower than the inlined subtract, so the production walk keeps the subtract.

N-dimensional periodic product metric

PeriodicSpace is for feature vectors whose axes are independent: angles, phases, time-of-day coordinates, or any mixture of circular and open values. A descriptor contains Some(period) for a circular axis and None for an open axis. It is not a replacement for Cell: a triclinic lattice couples Cartesian coordinates through H, whereas this metric is the Cartesian product of circles and real lines.

For a periodic axis, the point representative is in [0, L) and a difference is in [-L/2, L/2). Thus an exact +L/2 tie maps to -L/2. This is the usual shortest circular separation described by Mardia and Jupp, Directional Statistics (doi:10.1002/9780470316979). It also matches the toroidal boxsize model in SciPy cKDTree, which requires input data wrapped into [0, L) (SciPy cKDTree). Varilly's periodic kd-tree uses the same image-search model and avoids physically duplicating all periodic images (periodic_kdtree).

The implementation wraps each coordinate independently and sums its squared separation. This separable form is the best fit for a tree inner loop: descriptor validation happens once, scalar queries need no allocation, and batches consume contiguous row-major f64 slices.

Wrapping one given point or difference uses the same select path as the orthorhombic engine for nearby values. More distant finite values use d - L floor_fast(d/L + 1/2) while the quotient is representable with fractional bits, and an exact remainder beyond that range. Corrective selects enforce [-L/2, L/2) after either path. Point wrapping applies the analogous correction to guarantee [0, L) even when division rounds a tiny negative value onto the upper boundary.

A displacement between two coordinates never subtracts first and wraps the rounded difference afterwards, because that rounding can exceed the whole period. With L = 1e-6, 0 - (-10) rounds to 10 and wraps to zero, but the exact image is about 4.5e-16. Instead the displacement is the exact minimum image of q - p, rounded once:

  • If the raw difference is under L/2 in magnitude, the exact difference is inside the central image and the raw difference is already its correctly rounded value.
  • Otherwise a two-sum splits q - p into a head, the raw difference, and a tail. Near f64::MAX an intermediate of the two-sum can overflow even when the head is finite, which leaves a non-finite tail. Only a finite tail holds the exact rounding error of the head.
  • If the tail is non-finite, or the head is beyond 16 periods, each coordinate is reduced with the exact remainder % and folded into [-L/2, L/2), and a two-sum subtracts the residues. This check comes first, so it applies even to a head within one period. With p = f64::MAX, q = 0x1.7ffffffffffffp+1022, and L = f64::MAX, the head is -0x1.4p+1023 but the tail is NaN, and this path returns the exact image q.
  • Otherwise the tail is finite. If the head is within one period, the pair goes straight to the fold.
  • Otherwise the head is within 16 periods, and whole periods come off it in four steps. For k = 8, 4, 2, 1 in turn, kL is subtracted toward zero whenever the head exceeds it in magnitude. Each step starts with the head at most 2kL in magnitude, so a subtraction from a head in (kL, 2kL] is exact by Sterbenz's lemma, and the head ends within one period. A multiple kL that overflows exceeds every finite head, so skipping its step is also exact. The tail may now exceed half an ulp of the smaller head, so a second two-sum renormalizes the pair.

The remaining fold by one period is exact by Sterbenz's lemma, and the half-period comparisons are exact on the unevaluated sum. Only the final addition rounds, so each displacement component is the correctly rounded exact image. That rounding can produce +L/2 when the exact image is less than half an ulp below it. dist2 sums the squared components. The Metric<T = f64> trait also exposes a zero-sized Euclidean implementation. Only f64 implementations exist now; the defaulted scalar parameter leaves room for later Metric<f32> implementations without renaming methods or breaking existing Metric bounds. For an axis-aligned interval, the lower bound is the exact distance to the nearest translated interval, decided with the same exact pairs and rounded toward zero before squaring. The squared box bound is the sum of those one-axis minima, with each square and partial sum rounded down when more than one axis contributes. It never exceeds the correctly rounded exact distance, nor dist2 to any point in the box, so it can prune a kd-tree or ball-tree node without false negatives. An interval at least one period wide covers its whole circle. Unlike a generic callable metric in a tree, the explicit box bound preserves metric-aware pruning; scikit-learn documents that callable metrics are not supported by KDTree because function-call overhead gives poor performance (scikit-learn KDTree).

This orthogonal product rule is deliberately simpler than the general triclinic nearest-image search above. The latter needs a coupled closest-lattice-point algorithm (Conway and Sloane, doi:10.1098/rspa.1992.0004); applying independent periods to a skew cell would be incorrect.

Partial periodicity

PartialCell (mi_pbc_cell in C) handles systems periodic along zero, one, two, or three axes. An open system (zero periodic axes) returns q - p. A wire (one periodic vector a) projects onto a and wraps with s - floor(s + 1/2). A slab (two periodic vectors) Lagrange-reduces its 2D basis and checks the nine neighbouring lattice combinations around the rounded reduced coordinates, preserving the component normal to the periodic plane. With all three axes periodic, PartialCell delegates to Cell and returns the exact same bits.

Fixed-point fractions

Cell::fixed stores a position folded into the cell as three fractions on 64 bits, round(s * 2^52) * 2^12: the low 52 bits of s + 1 are that integer, so a position converts with an add and a mask, no conversion instruction and no branch, and fixed_many does four or eight at once. The engine wrap of a difference is then integer arithmetic: b - a modulo 2^64, read as signed, is the wrapped fraction in [-1/2, 1/2), exactly. The top 52 bits of that difference convert to a double exactly, and one product with H gives the Cartesian vector, for any cell shape, with no Hinv and no rounding step. That is the exact integer split of the Ozaki scheme (Ozaki, Ogita, Oishi, and Rump, Numer. Algorithms 59, 95, 2012, doi:10.1007/s11075-011-9478-1) applied to the periodic wrap, and the fixed-point positions of Anton (Shaw et al., Commun. ACM 51, 91, 2008, doi:10.1145/1364782.1364802). The wrap is the symmetric residue a - m floor(a/m + 1/2) of Ozaki Scheme II (Ozaki, Uchino, and Imamura, arXiv:2504.08009, 2025) with the one modulus m = 2^64; two's complement computes it, so no Chinese remainder step is needed. The orthorhombic wrap above is the same residue with m = L. Scheme II splits a product over several small moduli so that INT8 units compute each part exactly, then rebuilds it by the Chinese remainder theorem; that pays when many products share one rebuild, as along the inner dimension of a matrix product. A wrap has one subtraction per axis and the product with H has three terms, so on a CPU the double-precision units are already the fast path. Convert positions once per frame; a pair list over them then costs a subtraction, a conversion, and a matrix product per pair. A fraction exactly one half apart wraps to -1/2, and the distance agrees with dist2 to a few units in the last place.

Cell::fixed32 and the _fixed32 batches round each fraction to its top 32 bits: 12 bytes a position instead of 24. Past the second-level cache a batch moves more bytes than it computes on, about 56 a pair, so the bytes set the time. On the measured Xeon host the 32-bit batches are 2.7 to 3.5 times faster than the double batches at 64K pairs, 1.8 to 2.0 times at 16M, and 2 times in cache. The wrap is still exact, modulo 2^32, and a displacement is within 2^-32 (|a| + |b| + |c|) of the engine wrap, about 7e-9 in a cell 10 long: a tier for neighbour searches and histograms, beside the double contract.

Arrays and devices

The Python methods take any host DLPack producer (numpy, PyTorch, JAX, or CuPy host memory; see also metatensor and metatomic, doi:10.1063/5.0304911) and read contiguous rows where they lie; the result is a numpy array that owns its buffer through a DLPack 1.0 capsule, so torch.from_dlpack shares it too.

minimage-burn puts the wrap on Burn tensors. Burn 0.22 picks the backend from the device at run time, so one code path serves the CPU, wgpu, Vulkan, Metal, CUDA, and ROCm, and every step is a matrix product or an element-wise map that Burn's fusion joins per batch. Positions folded into [0, 1) on the CPU in double precision wrap exactly on the device in any float width: for |ds| < 1, ds - round(ds) subtracts zero or a neighbour of ds, which is exact by Sterbenz's lemma. A single- or half-precision device then rounds only ds and the product with H. That is the reduced precision of kernel_float (Heldens, Netherlands eScience Center), chosen per call, around an exact wrap. Folding on a single-precision device would lose the digits of a position far from the origin, so the fold stays on the CPU.

Error behaviour

  • Rust: constructors and slice-validated functions return Result<_, Error>. Error::BadBox covers singular (|det(H)| < 1e-18), non-finite, or zero-width cells, non-positive lengths in from_con_box or dist2_ortho_diffs, and collinear or non-finite periodic basis vectors in PartialCell::from_ase, plus non-positive or non-finite PeriodicSpace periods. Error::BufferSize covers mismatched slice lengths or out-of-range atom indices in filter_shifted. Error::Empty covers zero dimensions, zero beads, empty coordinates, or misaligned bead lengths in ring_centroid. Once constructed, per-pair methods on Cell and PartialCell are infallible (dist2_shifted_indexed panics on an out-of-bounds index). wrap_ortho_half_strict returns NaN, without panicking, for a non-finite component or a non-finite or non-positive length.
  • C ABI (minimage_*): every int-returning function returns 0 on success and 1 on failure (null pointer, invalid cell, length/index error, or integer overflow). On failure, a thread-local NUL-terminated UTF-8 error string is stored and returned by minimage_last_error(). The next successful minimage_* call on that thread clears the slot, and minimage_last_error() then returns NULL. minimage_version() neither reads nor modifies the slot.
  • C++ (minimage.hpp): wraps C ABI status codes and throws minimage::Error (carrying status() and what() from minimage_last_error()). Cell::ortho is noexcept and defers validation until a query runs; the other constructors validate immediately. minimage::wrap_ortho_half_strict is noexcept and returns NaN for the same invalid inputs as the Rust function.
  • Python: raises ValueError on invalid cells, length-3 / 3x3 / (N, 3) shape errors, or length mismatches; TypeError on unsupported dtypes, non-CPU DLPack devices, or invalid DLPack objects; and BufferError on unsupported DLPack capsule versions or re-exported buffers.

Dump bounds are not H

LAMMPS ITEM BOX BOUNDS stores bound spans plus tilt xy, xz, yz. Cell::from_lammps_bounds recovers the restricted-triclinic H and origin:

xlo_bound = xlo + min(0, xy, xz, xy+xz)

A CON header may already hold the 3x3 lattice (readcon-core, doi:10.5281/zenodo.22019397), or lengths and angles in the crystallographic convention. ASE and vesin pass rows (a, b, c).

vesin images

vesin enumerates periodic images. A particle can appear as its own neighbour through an image, and one neighbour can arrive through several images. reduce_pairs keeps each ordered pair once and drops the self image.

Consumers

linkcell re-exports minimage::Cell for the fold and the lattice shift. d-SEAMS (doi:10.1021/acs.jcim.0c00031) calls the C ABI from lammpsBoxToLcCell, periodicDistSq / relDist, the ortho batch kernel, and the vesin pair collapse.