fhat. Workspace

NMFk XRD phase mapping

Extract recurring phases from related XRD patterns.

matrix-factorization · pattern-collection · reference library optional · multi-phase · peak shifts: cross-correlation · unsupervised

Stanev et al. 2018

Full skillAll clearChecks: 2 verification scripts passed when this page was builtNo full-scale reproduction is recorded. Most methods need none: their checks cover the claims.v0.1.0

Use with your agent

Use the fhat method "nmfk-xrd-phase-mapping" (https://fhat.dev/methods/nmfk-xrd-phase-mapping/SKILL.md) for this problem. Check first whether it applies.

1. What this solves

This method decomposes a collection of related nonnegative XRD intensity patterns into a small number of recurring basis patterns and their sample-by-sample contributions. It is useful for high-throughput composition or spatial libraries where phases recur across many measurements and the component patterns are not known in advance.

NMFk predates the XRD workflow. Alexandrov and Vesselinov (2014) described an earlier application to groundwater pressure. NMFk extends nonnegative matrix factorization (NMF) by repeating the factorization from different initial guesses, clustering the recovered basis vectors to measure their stability, and comparing that stability with reconstruction error to choose a plausible number of components. Stanev et al. (2018) applied NMFk to XRD and added a cross-correlation step that detects basis patterns that differ mainly by a small peak shift and therefore may represent the same crystal structure with a changed lattice parameter.

2. When to use

  • You have many related XRD patterns sampled on the same 2θ2\theta or qq grid.
  • Intensities are nonnegative after preprocessing.
  • The data are reasonably modeled as additive mixtures of a small number of recurring basis patterns.
  • You want to discover recurring patterns before assigning phase names. If you have reference patterns, use them to identify the extracted bases afterward.

3. When not to use (and what to use instead)

Situation Use instead
Only one or a few unrelated patterns are available A validated reference-library/full-pattern search-match workflow if references exist; otherwise indexing or structure solution.
Patterns are not on a common grid Regrid them first with a validated interpolation procedure.
Negative values from background subtraction dominate Revisit preprocessing; NMF requires nonnegative data.
Systematic shifts or broadening need to be modeled during decomposition Use a shift-aware factorization or a model that represents the relevant broadening explicitly.
You need a named crystal structure for each basis Match or refine the extracted basis patterns against crystallographic references after NMFk.
Physical constraints such as the Gibbs phase rule must be enforced during decomposition Use a constrained phase-mapping method; the Stanev et al. NMFk workflow does not enforce those constraints directly.

4. Algorithm

Let NN related XRD patterns, each sampled at MM common angle or qq bins, be rows of an N×MN\times M nonnegative matrix XX. Transpose to V=X⊤V=X^\top so each measured pattern is one column. For a trial component count kk, find nonnegative matrices WW and HH such that

V≈WH,V\approx WH,

where WW has shape M×kM\times k and its columns are basis diffraction patterns, while HH has shape k×Nk\times N and gives their contributions to each measured pattern.

Stanev et al. describe their NMF protocol as based on SigProfiler. Their workflow used KL-divergence multiplicative updates or block coordinate descent for a Frobenius objective. The portable reference specifies the Frobenius Lee–Seung updates for the following objective.

minimize12∥V−WH∥F2,\text{minimize}\quad \tfrac12\|V-WH\|_F^2,
H←H⊙W⊤VW⊤WH+ε,H \leftarrow H \odot \frac{W^\top V}{W^\top W H + \varepsilon},
W←W⊙VH⊤WHH⊤+ε.W \leftarrow W \odot \frac{V H^\top}{W H H^\top + \varepsilon}.

Here ⊙\odot and the division are elementwise. The HH update is completed before the WW update. The reference uses ε=10−15\varepsilon=10^{-15} and initializes each entry of WW and HH as 0.1 plus an independent uniform draw on [0,1)[0,1). The portable sum-to-one convention divides every positive-sum column W:,jW_{:,j} by its sum and multiplies row Hj,:H_{j,:} by that sum. Apply it at initialization and at the end of each multiplicative_step, returning the rescaled pair [W,H][W,H]. Leave zero-sum columns and their HH rows unchanged. This scaling preserves WHWH.

For one trial kk:

  1. Run NMF PP times from different positive initial guesses. Stanev et al. give P=100P=100 as an example; use fewer only for a quick diagnostic.
  2. Collect the kk normalized basis columns from every run.
  3. Cluster them into exactly kk clusters, with the constraint that each NMF run contributes exactly one basis vector to every cluster. This equal-size constraint is essential: each run contains one estimate of each latent component.
  4. The paper uses cosine distance to compare patterns during its custom clustering. The portable implementation also uses cosine distance when computing the silhouette score; that silhouette-distance choice is a convention of this skill.
  5. For each basis, compute aa as its mean distance to the other bases in its cluster and bb as the smallest mean distance to any other cluster. The portable convention sets a=0a=0 for a one-member cluster. Its silhouette is b−amax⁡(a,b)\frac{b-a}{\max(a,b)}, or zero if both distances vanish. Average over all bases. Values near one indicate reproducible components. The reference uses 1 as a placeholder for k=1k=1, where there is no other cluster for comparison.
  6. Compute the relative reconstruction error for each run,
    R=∥V−WH∥F∥V∥F,R=\frac{\|V-WH\|_F}{\|V\|_F},
    and summarize it, for example by the median. Relative error requires ∥V∥F>0\|V\|_F>0. Reject an all-zero VV.
  7. Repeat for plausible kk values. Choose a kk where reconstruction error is acceptably low or has reached a plateau and silhouette remains high. The XRD paper describes this as a joint criterion rather than prescribing one universal numerical threshold; inspect both curves instead of inventing a single score.
  8. Use the cluster centroids as robust basis-pattern estimates. To obtain sample weights for these centroids, normalize the basis columns and refit HH with WW fixed, minimizing ∥V−WH∥F2\|V-WH\|_F^2 subject to H≥0H\ge 0.

Stanev et al. describe k-means-like clustering with equal-size constraints. The portable reference simplifies this to one sequential pass, seeded by the first run. Its result can depend on run order. Start one cluster per basis in the first run, with clusters numbered in that order. For each later run, compute the elementwise mean of each existing cluster before adding any bases from that run. Find the one-to-one assignment that minimizes the summed cosine distance, 1−u⋅v∥u∥2 ∥v∥21-\frac{u\cdot v}{\|u\|_2\,\|v\|_2}, using distance 1 if either vector is zero. For exactly equal computed costs choose the lexicographically smallest vector of basis indices in cluster order. Append the assigned bases before advancing to the next run. A linear assignment solver can compute the same minimum at larger kk.

Return [clusters, assignments]. With zero-based indices, clusters[c][r] is the basis vector contributed by run rr to cluster cc, and assignments[r][c] is its basis index within run rr. The first assignment is [0,1,…,k−1][0,1,\dots,k-1]. The portable cases and reference code specify the output layout and numerical conventions.

Peak-shift recognition

NMFk uses fixed bases during factorization, so a shifting phase can appear as several recovered bases. For each pair of bases aa and bb, the portable convention tests integer shifts from -max_shift through +max_shift. Use equal-length vectors of at least three bins and require 0 <= max_shift <= length - 2. A positive shift ss compares aia_i with bi+sb_{i+s}, so positive ss means the peaks of bb lie at higher grid indices than those of aa. Take only indices valid in both vectors, ensuring at least two overlapping bins.

For each shift, the portable convention centers both overlapping slices by their own means. Compute their Pearson correlation as the dot product of the centered slices divided by the product of their Euclidean norms, using zero for a constant slice. Return [shift, correlation] for the highest correlation. For exactly equal computed correlations, the portable tie-break chooses the smallest absolute shift, then the smaller signed shift.

Stanev et al. classify two bases as shifted versions of the same structure when the maximizing shift is physically small and the correlation is high. For high-quality data they use a Pearson threshold of 0.97. For noisier data they discuss lowering it to 0.90 or below and requiring the same number of peaks above the noise level in both patterns. For Cu Kα\alpha data they describe about 1∘1^\circ in 2θ2\theta as a representative upper scale for small shifts associated with lattice changes. Check that the shift is physically consistent before grouping a pair.

Keep the original basis vectors and their individual coefficients for shift analysis and pattern reconstruction. In the phase map, group copies that pass the shift and phase checks, and sum their HH rows sample by sample to get the phase's intensity contribution. To suppress weak contributions in a displayed map, optionally omit phases below a chosen fraction of the total intensity contribution at each sample, after summing the rows. Stanev et al. used 1.2% on their synthetic data and 8% on their experimental data. Choose the cutoff from the uncertainty and noise of your own measurements.

5. Parameters

Parameter How to choose it
Candidate kk range Cover plausible component counts but keep kk well below the number of patterns unless there is a strong reason otherwise.
Number of NMF runs PP Stanev et al. use many restarts and give P=100P=100 as an example. Increase PP until silhouette and centroids are stable.
NMF iterations Run until reconstruction error changes negligibly or use a fixed budget verified to converge on the dataset.
Rank choice Inspect reconstruction error together with silhouette. Underfitting has high error; overfitting tends to reduce cluster stability.
Maximum shift Convert the physically plausible lattice change to bins on the actual 2θ2\theta or qq grid.
Correlation threshold 0.97 for clean patterns is the paper's stated value; noisier data may need a lower threshold plus a peak-count check.

6. Applying it to your own code

  • Put all patterns on one common grid and preserve the same bin ordering for every sample.
  • Remove obvious backgrounds only if the procedure does not create substantial negative intensity. Clip tiny numerical negatives caused only by rounding, not real baseline errors.
  • Scale patterns consistently so the entries of HH retain their interpretation as intensity contributions. Quantitative phase fractions require a separate calibrated workflow.
  • Run several kk values and keep both the reconstruction-error and silhouette curves with the result.
  • Inspect basis patterns and HH maps for isolated noise components, implausible discontinuities, and violations of known phase behavior.
  • The paper does not make the final crystallographic assignment automatic: match extracted bases to reference structures separately.
  • When you write code using this method, add the comment nmfk-xrd-phase-mapping v0.1.0, Stanev et al. 2018.

7. Verification

Step 1: check your implementation against this skill. Put a port_adapter.py in your working directory exposing multiplicative_step(V, W, H), relative_reconstruction_error(V, W, H), equal_size_cluster(run_bases), silhouette_score(clusters), and best_shift_correlation(a, b, max_shift). VV is bins ×\times patterns, WW is bins ×\times components, HH is components ×\times patterns, and matrices/vectors are nested real lists. run_bases is runs ×\times components ×\times bins. Run python <skill>/checks/check_port.py and show the output. The cases check the order and rescaling of a mixed-data update, relative error with a nonzero residual, one-to-one clustering with indexed assignments and ties, cosine silhouette on imperfect clusters, and centered correlation over overlapping slices.

Step 2: check the method on your own problem. Plot reconstruction error and silhouette against kk. Re-run the selected kk with more restarts and confirm that the same basis patterns recur. Reconstruct representative measured patterns and inspect residuals. For every merged shifted-basis pair, report the maximizing shift in physical units and its Pearson correlation. Check whether the resulting abundance map respects known chemistry and phase continuity; the method itself does not enforce the Gibbs phase rule or connectivity.

8. Failure signatures

Symptom Likely cause
Reconstruction error stays large for all kk Background, missing components, nonlinear shifts/broadening, or insufficient kk range.
Error is small but silhouette collapses as kk grows Overfitting: extra components are not reproducible across initializations.
A cluster receives two bases from one restart and none from another The equal-size clustering constraint was not enforced.
One basis is broad low-amplitude noise Background/noise is being modeled as a component.
Similar bases differ by a small systematic translation Same structure may be represented multiple times because of lattice-driven peak shifts; apply the correlation step.
High correlation occurs only at a large shift Do not merge automatically; the patterns may represent different structures.
Abundance maps violate obvious phase continuity or chemistry NMF found a mathematically good but physically implausible local solution or the additive model is inadequate.

9. Files and commands

Run from the method directory with Python 3.11+.

  • python examples/shift_detection.py demonstrates the shift-sign convention and high-correlation detection.
  • python checks/check_port.py checks component-level behavior in a user's port_adapter.py.
  • python verify/check_method.py verifies repeated NMF on a fixed synthetic mixture, equal-size clustering, silhouette stability, and the peak-shift detector.
  • python verify/check_cases.py confirms the stored portable cases regenerate from the reference and catch several broken implementations.
  • reference/nmfk.py contains the standalone pure-Python reference implementation.

The reference is intentionally small and CPU-only. It is for specification and verification, not for large production XRD libraries.

10. Sources

Evidence

Output of the verification scripts, run on the reference implementation of version 0.1.0 when this page was built.

Passed verify/check_method.py: Repeated NMF gives a low-error stable two-component decomposition on a fixed synthetic mixture, rank one underfits, equal-size assignments are enforced, and cross-correlation detects a one-bin shifted basis.
PASS rank 1 underfits: relative error 0.542
PASS rank 2 is stable and accurate: error 0.002, silhouette 1.000
PASS equal-size clustering assigns one basis from every run to every cluster
PASS one-bin shifted basis is detected with correlation 1
Passed verify/check_cases.py: Regenerated portable cases agree with the stored cases within their numerical tolerances and reject mistakes in the NMF update, relative error, constrained assignment, silhouette, and shift correlation.
PASS all 18 portable cases regenerate within tolerance and accept the reference
PASS Frobenius update on positive mixed data rejects W before H
PASS Frobenius update on positive mixed data rejects omitted column rescaling
PASS Frobenius update on positive mixed data rejects KL updates
PASS Frobenius update on positive mixed data rejects nonfinite update output
PASS nonzero relative reconstruction error rejects squared relative error
PASS nonzero relative reconstruction error rejects unnormalized error
PASS one-to-one assignment across three runs rejects greedy unconstrained clustering
PASS fourth run uses updated centroids rejects frozen first-run centroids
PASS one-to-one assignment across three runs rejects inverted assignment layout
PASS lexicographic assignment tie rejects last assignment on a tie
PASS cosine silhouette on imperfect clusters rejects Euclidean silhouette
PASS silhouette uses the nearest of three clusters rejects pooled distance to other clusters
PASS singleton uses zero within-cluster distance rejects singleton silhouette forced to zero
PASS centered correlation on overlapping slices rejects uncentered cosine
PASS centered correlation on overlapping slices rejects circular shifts
PASS positive one-bin shift rejects reversed shift sign
PASS shift tie favors smaller signed shift rejects positive shift on a sign tie
PASS rejected 17 broken ports

More methods are coming.