---
name: nmfk-xrd-phase-mapping
description: "Extract recurring phase patterns and their intensity contributions from related powder XRD measurements. Use NMFk when many composition, spatial, temperature, or process-series patterns share a small set of additive components; repeated NMF and equal-size clustering assess component stability, and cross-correlation identifies small peak-shifted copies."
---

# NMFk XRD phase mapping

## 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\theta$ or $q$ 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 $N$ related XRD patterns, each sampled at $M$ common angle or $q$ bins, be rows of an $N\times M$ nonnegative matrix $X$. Transpose to $V=X^\top$ so each measured pattern is one column. For a trial component count $k$, find nonnegative matrices $W$ and $H$ such that

$$V\approx WH,$$

where $W$ has shape $M\times k$ and its columns are basis diffraction patterns, while $H$ has shape $k\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.

$$\text{minimize}\quad \tfrac12\|V-WH\|_F^2,$$

$$H \leftarrow H \odot \frac{W^\top V}{W^\top W H + \varepsilon},$$

$$W \leftarrow W \odot \frac{V H^\top}{W H H^\top + \varepsilon}.$$

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

For one trial $k$:

1. Run NMF $P$ times from different positive initial guesses. Stanev et al. give $P=100$ as an example; use fewer only for a quick diagnostic.
2. Collect the $k$ normalized basis columns from every run.
3. Cluster them into exactly $k$ 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 $a$ as its mean distance to the other bases in its cluster and $b$ as the smallest mean distance to any other cluster. The portable convention sets $a=0$ for a one-member cluster. Its silhouette is $\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=1$, where there is no other cluster for comparison.
6. Compute the relative reconstruction error for each run,
   $$R=\frac{\|V-WH\|_F}{\|V\|_F},$$
   and summarize it, for example by the median. Relative error requires $\|V\|_F>0$. Reject an all-zero $V$.
7. Repeat for plausible $k$ values. Choose a $k$ 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 $H$ with $W$ fixed, minimizing $\|V-WH\|_F^2$ subject to $H\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-\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 $k$.

Return [clusters, assignments]. With zero-based indices, `clusters[c][r]` is the basis vector contributed by run $r$ to cluster $c$, and `assignments[r][c]` is its basis index within run $r$. The first assignment is $[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 $a$ and $b$, 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 $s$ compares $a_i$ with $b_{i+s}$, so positive $s$ means the peaks of $b$ lie at higher grid indices than those of $a$. 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^\circ$ in $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 $H$ 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 $k$ range | Cover plausible component counts but keep $k$ well below the number of patterns unless there is a strong reason otherwise. |
| Number of NMF runs $P$ | Stanev et al. use many restarts and give $P=100$ as an example. Increase $P$ 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\theta$ or $q$ 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 $H$ retain their interpretation as intensity contributions. Quantitative phase fractions require a separate calibrated workflow.
- Run several $k$ values and keep both the reconstruction-error and silhouette curves with the result.
- Inspect basis patterns and $H$ 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)`. $V$ is bins $\times$ patterns, $W$ is bins $\times$ components, $H$ 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 $k$. Re-run the selected $k$ 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 $k$ | Background, missing components, nonlinear shifts/broadening, or insufficient $k$ range. |
| Error is small but silhouette collapses as $k$ 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

- Stanev et al. define the XRD workflow: repeated NMF, equal-size clustering, stability plus reconstruction error for component-count selection, and cross-correlation for peak-shifted bases. They identify SigProfiler MATLAB source as the basis of their NMF protocol. https://doi.org/10.1038/s41524-018-0099-2
- Lee and Seung give multiplicative-update algorithms for NMF; this skill uses their Frobenius update as a portable convention rather than claiming it was the update used in the Stanev XRD implementation. https://proceedings.neurips.cc/paper/2000/hash/f9d1152547c0bde01830b7e8bd60024c-Abstract.html
- Alexandrov and Vesselinov describe an earlier use of repeated NMF with semi-supervised clustering. https://doi.org/10.1002/2013WR015037
- Stanev et al. cite the SigProfiler work of Alexandrov et al., published in Nature in 2013. https://doi.org/10.1038/nature12477
- The historical SigProfiler MATLAB release is linked in the XRD paper. https://www.mathworks.com/matlabcentral/fileexchange/38724-sigprofiler
