Bends in the Path: Per-Grain Trajectory Geometry for Early Yield Detection in In Situ X-Ray Diffraction

In in situ synchrotron X-ray diffraction, a sample is squeezed, stretched or heated while an intense X-ray beam records how its crystal lattice scatters light, frame after frame. The events scientists most want to catch are the first slip of a grain, a lattice collapse, or the onset of a new phase. These events are rare and brief. The standard analysis, which fits a curve to every diffraction spot, takes minutes, so experimenters often learn too late that the interesting moment has passed. The current fast detector compares each new frame to a fixed snapshot of the sample at zero load, called the Rare Event Indicator (Rapid detection of rare events from in situ X-ray diffraction data using machine learning). It reports a single global alarm. It cannot say which grain moved first, and normal elastic straining and beam drift steadily push it away from its reference.

Video forensics has a different habit. Detectors of synthetic video look at the shape of a sequence's path through a learned feature space, and they flag places where the path bends or jumps instead of continuing smoothly (AI-Generated Video Detection via Perceptual Straightening). We propose to give every diffraction spot its own path. Under elastic loading a spot drifts steadily, so its feature trajectory should be close to a straight line traveled at constant speed. When that grain begins to slip plastically, the path should bend. A detector built on this "straight-line null model" should fire earlier than a zero-load comparison, should not be fooled by slow drifts, and should say which grain yielded first.

Core Claim

Treat each tracked Bragg peak (the bright diffraction spot produced by one grain's set of lattice planes) as a short time series of embeddings from a self-supervised peak encoder. Normal deformation follows a locally linear trajectory in this space. Departures from local linearity, measured relative to the peak's own recent motion and not relative to the zero-load state, mark the onset of plasticity grain by grain. The new ingredient is not the encoder, which we reuse, and not curvature as a statistic, which we borrow. It is the change of reference from a static initial baseline to each peak's own extrapolated past, combined with per-peak tracking that turns a global alarm into a ranked list of grains.

Concretely, let $z_{g,t}$ be the embedding of peak $g$ at load step $t$. The straight-line forecast is $\hat z_{g,t} = 2z_{g,t-1} - z_{g,t-2}$. The bend score is

$$ b_{g,t} = \frac{\lVert z_{g,t} - \hat z_{g,t} \rVert}{\operatorname{median}_{k \le W}\lVert z_{g,t-k} - z_{g,t-k-1}\rVert + \epsilon}, $$

where $W$ is a short window of recent steps and $\epsilon$ prevents division by zero. The score is the forecast miss expressed in units of the peak's own typical step size. Any drift that is linear in time cancels in the numerator, and any smooth overall scaling of the steps cancels in the ratio. That is why we expect it to be insensitive to slow flux decay and steady elastic peak shifts, while still responding to the abrupt peak smearing that crystallographic slip produces. Sample-level onset is declared when the fraction of peaks whose $b_{g,t}$ exceeds a threshold calibrated on elastic steps rises above a chance level. Per-grain onset is the first step at which a peak exceeds the threshold.

Where This Sits

The Rare Event Indicator supplies our method and is our main competitor. It trains a modified BraggNN encoder with BYOL (a self-supervised method that learns features by matching two noisy views of the same input) on peak patches. It clusters zero-load embeddings with K-means and raises an alarm when new peaks fall far from those clusters. It reports a speedup from roughly 500 seconds to roughly 2 seconds, and transfer from stainless steel to titanium alloys, with sand as a brittle negative control. We keep its encoder and its data. We change what each peak is compared against, and we keep per-peak identity instead of pooling. BraggNN: Fast X-ray Bragg Peak Analysis Using Deep Learning supplies the sub-pixel peak centers (under 0.29 pixels error for 75% of peaks) that make frame-to-frame peak association feasible. On its own, BraggNN treats each patch in isolation and has no notion of a sequence.

From video forensics, ReStraV supplies the geometric statistics: step sizes and the angles between consecutive steps in a frozen DINOv2 feature space. It reports 97.17% accuracy and 98.63% AUROC on VidProM, but only on RGB video. Two of its acknowledged weaknesses shape our design. First, curvature produces false alarms at legitimate scene cuts. In our setting a legitimate discontinuity is the signal, so this weakness becomes the detection mechanism. Second, curvature is blind to the direction of time. We address that only in a secondary loading–unloading check. FInfer (FInfer: Frame Inference-Based Deepfake Detection for High-Visual-Quality Videos) motivates the predict-then-compare structure, since it forecasts latent frames with a recurrent network. We deliberately start with a parameter-free linear forecaster, because learned forecasters trained on elastic data may silently extrapolate through the onset.

Two papers constrain the design. Machine Learning Automated Analysis of Enormous Synchrotron X-ray Diffraction Datasets shows models trained only on simulated patterns fall to 64% accuracy, and to 0.50 AUROC for rhenium, on real data. We therefore train only self-supervised on experimental patches. The Loss Landscape of XRD-Based Structure Optimization Is Too Rough for Gradient Descent argues against inverting patterns to structures online. We therefore stay in embedding space and leave structure solution offline.

Research Program

We first build a peak tracker. BraggNN centers from consecutive load steps are linked by nearest-neighbor matching in detector position and rotation angle, with gating by expected elastic shift. Where HEDM grain indexing exists, it supplies ground-truth grain identity for the tracked peaks. Each tracked patch is embedded with the REI's BYOL-BraggNN encoder: first frozen as released, then retrained on our splits to rule out leakage. We then compute bend scores, curvature angles and step sizes per peak. We calibrate thresholds only on the first elastic steps of each run, never on the onset region.

The analysis has three layers. At the sample level, we ask whether onset is detected earlier and with fewer false alarms than the REI. At the grain level, we ask whether the earliest-flagged peaks agree with the peaks that offline per-peak width fitting identifies as broadening first. For robustness, we create semi-synthetic sequences by multiplying real elastic frames by smooth intensity decays and beam-size changes of controlled magnitude. Because these perturbations are known to be non-structural, they let us measure false-alarm rates directly.

Baselines

The naive reference is raw frame differencing. We compute the mean squared pixel difference between consecutive detector frames, globally and per peak patch, and threshold it on the same elastic calibration steps. Beating it means lower false-alarm rates on the semi-synthetic drift sequences and on sand at equal detection delay.

The strongest existing method is the Rare Event Indicator, run with its published encoder, zero-load K-means reference and thresholding. It runs on the same Argonne runs (304L steel, Ti-6Al-4V, Ti-7Al continuous loading, sand control) and the same 40° rotation subsets it reports as sufficient. The file reports its speed (about 2 s versus about 500 s for peak fitting) and its data efficiency. No reported result was found on Lacuna for REI onset-detection error in load steps or for its false-alarm rate, so we will measure both ourselves under identical calibration. Our method beats it if it detects onset at least one load step earlier on the median run, or matches it with fewer false alarms on sand and on the drift sequences, and adds grain-level ranking that the REI cannot provide.

The obvious cross-domain transfer is ReStraV applied off the shelf. This means frozen DINOv2 features of whole detector frames, its curvature and step statistics, and its MLP replaced by threshold calibration, since we have no labeled training set of onsets. This baseline tests whether a generic vision backbone suffices or whether a diffraction-specific peak encoder is needed.

A physics baseline tracks BraggNN peak centers plus a fast width estimate per peak and applies CUSUM change-point detection (a running-sum test for a shift in a signal's mean) to their second differences. It uses the same tracker and calibration.

Two ablations isolate the key ingredient. The first is a rolling-reference REI, which re-fits K-means on the previous $W$ steps instead of zero load. It separates "moving reference" from "trajectory geometry." The second is a pooled bend score, which averages embeddings over all peaks before computing $b_t$. It separates per-peak tracking from the geometry. All methods share the encoder where applicable, the same calibration steps, and an equal threshold-tuning budget: one threshold per method, chosen on steel and frozen for the titanium alloys and sand.

Why not just…?

Why not just update the REI baseline with a rolling window? This is the most serious threat. A rolling reference also cancels slow drift, and it may capture most of the benefit. We include it as an ablation precisely so the experiment decides. If rolling REI matches our bend score at the sample level, we will report that the gain comes from the moving reference and not the geometry. The remaining contribution would then be per-grain localization, which we would evaluate on its own. The bend score has one principled advantage: a linear trend in the embedding cancels exactly in the forecast. A rolling mean lags a trend, so under steady elastic shift it accumulates offset in proportion to $W$. The drift sequences test that difference directly.

Why not just fit peak positions and widths and run change-point detection? Peak broadening is the textbook signature of slip, and BraggNN makes position tracking fast, so this is a credible competitor. Its weaknesses are that BraggNN discards overlapping peaks and does not estimate width. Width fitting is the slow step the REI paper measured at about 500 seconds, and fitted widths become ill-defined as peaks smear. The CUSUM baseline uses the same tracker, so any advantage must come from embeddings capturing shape changes, such as asymmetry, streaking or splitting, that a two-parameter summary misses. If CUSUM ties, the honest conclusion is that the learned representation is unnecessary for yield onset. That would still be a useful result.

Why not just run ReStraV on detector images? It is the direct transfer and costs nothing to try. However, DINOv2 was trained on natural photographs. A diffraction frame is mostly empty background with a few hundred small spots, and whole-frame features will be dominated by background and global intensity. The comparison against the per-peak BraggNN encoder shows whether domain-specific, per-spot features matter. We expect the off-the-shelf transfer to respond to flux drift. That expectation is falsifiable on the drift sequences.

Proposed Experiments

The primary benchmark is the Argonne HEDM rare-event collection from the REI paper. The reference onset for each run is the yield step determined offline by per-peak pseudo-Voigt width fitting and the macroscopic stress–strain knee. The primary metrics are onset delay in load steps (signed, so early detection counts as negative), false-alarm rate per hundred elastic steps, and false alarms on the full sand run, where no plastic onset exists. Grain-level evaluation uses the BraggNN gold bi-crystal and Ti-7Al data for tracker accuracy. On the titanium runs we use precision of the top-$k$ earliest-flagged peaks against the top-$k$ earliest-broadening peaks from offline fitting. Latency per frame is reported against the REI's 2-second figure.

The first decisive check is lead time. Yield begins in favorably oriented grains before the aggregate knee, so if per-peak bend scores are real, the earliest-flagged grains should precede the global REI alarm on most runs. They should also be the grains that offline fitting shows broadening first. If flagged grains are random relative to offline broadening, the localization claim fails. The second decisive check is drift immunity. On semi-synthetic sequences with flux decays up to the scale observed in real runs, the bend score's false-alarm rate should remain at its elastic-calibration level while static-baseline REI's rises. The third is transfer: thresholds frozen on steel must work on Ti-6Al-4V and Ti-7Al without retuning, mirroring the REI's own transfer claim.

As a secondary test of the arrow-of-time gap that ReStraV leaves open, runs with an unloading segment let us ask whether elastic peak trajectories retrace their loading path while post-yield trajectories do not. We would measure this as the distance between loading and unloading embeddings at matched load. High-pressure diamond-anvil-cell series are the long-term target, with published transition pressures such as the plane-to-chain collapse in CaMn2Bi2 or the isostructural transition in Na1-xFeAs. These are only feasible if raw frame sequences can be obtained. Their sparse pressure steps (tens per run) also strain a three-point linear forecast, so we treat them as a later validation and not as evidence for the core claim.