Ideal infinite crystals produce sharp Dirac-delta Bragg peaks, yet real engineering alloys (ball-milled nanopowders, electrodeposited thin films, cold-rolled steels) exhibit noticeably broadened diffraction peaks. Crucially, two different microstructural features broaden XRD peaks: nanoscale crystallite size and dislocation-induced heterogeneous lattice microstrain . Applying the single-peak Scherrer formula blindly to a cold-worked metal mistakes microstrain for ultra-fine grains, an error we diagnose and cure via linear Williamson–Hall deconvolution.
Learning objectives¶
Compute coherent crystallite domain sizes from peak FWHM via
diffraction.scherrer_crystallite_size_nm.Contrast the angular dependence of size broadening against the dependence of nonuniform lattice microstrain.
Demonstrate why naive single-peak Scherrer sizing systematically underestimates grain size in cold-worked alloys.
Deconvolve crystallite size and microstrain simultaneously via linear regression in
diffraction.williamson_hall_fit.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engmaterials
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engmaterials" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engmaterials.git"], check=True)
import engmaterials
import inspect
import numpy as np
import matplotlib.pyplot as plt
from engmaterials import (atomistics, constants, diffraction, elasticity, kinetics_selection,
lattices, phase_field, phase_thermodynamics)
from engmaterials.plotting import label_panels, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. Principles and governing equations¶
1.1 Finite-Size (Scherrer) vs. Microstrain (Stokes–Wilson) Broadening¶
Finite Coherent Domain Size : Incomplete destructive interference just off the Bragg angle across a crystallite of thickness broadens the peak with full-width at half-maximum (FWHM, in radians):
where is the dimensionless Scherrer shape factor (note unit scaling: ).
Heterogeneous Microstrain : Differentiating Bragg’s law at fixed gives . Since and root-mean-square strain spans , Stokes & Wilson obtain:
1.2 Additive Williamson–Hall Linear Law¶
Under Lorentzian (Cauchy) profile convolution, FWHMs add linearly (). Multiplying through by yields a straight line in :
heading("Demonstration 1: Angular Scaling of Size Broadening (sec theta) vs Microstrain (tan theta)")
tt_grid = np.array([30.0, 50.0, 75.0, 100.0, 125.0])
th_rad = 0.5 * np.radians(tt_grid)
d_true_nm = 35.0
eps_true = 0.0025
beta_size_rad = (0.9 * constants.CU_K_ALPHA_A) / ((d_true_nm * 10.0) * np.cos(th_rad))
beta_strain_rad = 4.0 * eps_true * np.tan(th_rad)
print(f"{'2theta [deg]':>12s} | {'beta_size [deg]':>15s} | {'beta_strain [deg]':>17s} | {'Strain/Size Ratio':>17s} | {'Scherrer D [nm]':>15s}")
print("-" * 88)
for tt, bs, be in zip(tt_grid, beta_size_rad, beta_strain_rad):
d_rec = diffraction.scherrer_crystallite_size_nm(bs, tt)
print(f"{tt:12.1f} | {np.degrees(bs):15.4f} | {np.degrees(be):17.4f} | {be/bs:17.3f} | {d_rec:15.4f}")
assert np.isclose(d_rec, d_true_nm, rtol=1e-13)
assert (beta_strain_rad[-1] / beta_size_rad[-1]) > 2.5 * (beta_strain_rad[0] / beta_size_rad[0])
Demonstration 1: Angular Scaling of Size Broadening (sec theta) vs Microstrain (tan theta)
==========================================================================================
2theta [deg] | beta_size [deg] | beta_strain [deg] | Strain/Size Ratio | Scherrer D [nm]
----------------------------------------------------------------------------------------
30.0 | 0.2350 | 0.1535 | 0.653 | 35.0000
50.0 | 0.2504 | 0.2672 | 1.067 | 35.0000
75.0 | 0.2861 | 0.4396 | 1.537 | 35.0000
100.0 | 0.3531 | 0.6828 | 1.934 | 35.0000
125.0 | 0.4916 | 1.1006 | 2.239 | 35.0000
What Demonstration 1 shows. Because grows faster than by an extra factor of , microstrain broadening is modest at low () but dominates at high (). When , scherrer_crystallite_size_nm recovers across every single peak.
2. Why Single-Peak Scherrer Underestimates Grain Size in Cold-Worked Alloys¶
We simulate a cold-rolled nanocrystalline Cu alloy with true domain size and dislocation microstrain across all five FCC reflections (111), (200), (220), (311), (222) and inspect the biased apparent sizes returned by naive single-peak Scherrer.
heading("Demonstration 2: Apparent Scherrer Bias Across Reflections of Cold-Worked FCC Copper")
pks_cu = diffraction.simulate_powder_xrd("fcc", constants.ELEMENTS_DB["Cu"]["a_A"], max_hkl=4, two_theta_max=105.0)
tt_cu = np.array([p["two_theta_deg"] for p in pks_cu])
th_cu = 0.5 * np.radians(tt_cu)
D_true_nm = 45.0
eps_cw = 0.0022
beta_tot_cu = (0.9 * constants.CU_K_ALPHA_A) / (D_true_nm * 10.0 * np.cos(th_cu)) + 4.0 * eps_cw * np.tan(th_cu)
D_app_nm = diffraction.scherrer_crystallite_size_nm(beta_tot_cu, tt_cu)
print(f"{'Cu (hkl)':10s} | {'2theta [deg]':>12s} | {'FWHM_tot [deg]':>14s} | {'Naive Scherrer D_app [nm]':>25s} | {'Bias [%]':>10s}")
print("-" * 82)
for p, bt, da in zip(pks_cu, beta_tot_cu, D_app_nm):
bias_pct = 100.0 * (da - D_true_nm) / D_true_nm
print(f"{str(p['hkl']):10s} | {p['two_theta_deg']:12.3f} | {np.degrees(bt):14.4f} | {da:25.3f} | {bias_pct:+10.2f}%")
assert np.all(D_app_nm < D_true_nm)
assert np.all(np.diff(D_app_nm) < 0.0)
Demonstration 2: Apparent Scherrer Bias Across Reflections of Cold-Worked FCC Copper
====================================================================================
Cu (hkl) | 2theta [deg] | FWHM_tot [deg] | Naive Scherrer D_app [nm] | Bias [%]
----------------------------------------------------------------------------------
(1, 1, 1) | 43.318 | 0.3902 | 21.907 | -51.32%
(2, 0, 0) | 50.451 | 0.4327 | 20.296 | -54.90%
(2, 2, 0) | 74.128 | 0.6021 | 16.536 | -63.25%
(3, 1, 1) | 89.941 | 0.7532 | 14.908 | -66.87%
(2, 2, 2) | 95.151 | 0.8134 | 14.478 | -67.83%
fig, ax = plt.subplots(figsize=(6.4, 4.0))
ax.plot(tt_cu, D_app_nm, "o-", label="single-peak Scherrer estimate")
ax.axhline(D_true_nm, color="k", ls="--", lw=1.0, label="size used to generate the widths")
for p_lab, da_lab in zip(pks_cu, D_app_nm):
ax.annotate("(%d%d%d)" % tuple(p_lab["hkl"]), (p_lab["two_theta_deg"], da_lab), textcoords="offset points", xytext=(0, 8), ha="center", fontsize=9)
ax.set_ylim(0.0, 50.0); ax.set_xlabel(r"$2\theta$ [deg]"); ax.set_ylabel("crystallite size [nm]"); ax.legend(loc="lower left")
plt.show()
Figure 4.1. Synthetic data. Crystallite size from the Scherrer equation applied to single peaks of strained copper. Because the strain broadening is counted as size broadening, every estimate is below the true 45 nm, and the error grows with angle.
What Demonstration 2 shows. The single-peak Scherrer estimate is below the true crystallite size on every peak: on (111) () and on (222) (). Whenever apparent Scherrer size shrinks systematically with , significant microstrain is present.
3. Williamson–Hall Deconvolution & Broadened Profile Comparison¶
We pass (beta_tot_cu, tt_cu) into diffraction.williamson_hall_fit, both noise-free and with realistic experimental FWHM measurement noise, and plot the Williamson–Hall diagram alongside the annealed vs. nanocrystalline cold-worked diffractograms.
heading("Demonstration 3: Williamson-Hall Linear Deconvolution (Annealed vs Cold-Worked vs Noisy)")
wh_clean = diffraction.williamson_hall_fit(beta_tot_cu, tt_cu)
rng = np.random.default_rng(104)
beta_noisy = beta_tot_cu * (1.0 + rng.normal(0.0, 0.018, size=beta_tot_cu.size))
wh_noisy = diffraction.williamson_hall_fit(beta_noisy, tt_cu)
beta_annealed = (0.9 * constants.CU_K_ALPHA_A) / (D_true_nm * 10.0 * np.cos(th_cu))
wh_annealed = diffraction.williamson_hall_fit(beta_annealed, tt_cu)
print(f"Clean Cold-Worked Fit : D = {wh_clean['crystallite_size_nm']:.4f} nm, eps = {wh_clean['microstrain']:.6f}, R^2 = {wh_clean['r2']:.6f}")
print(f"Noisy Cold-Worked Fit : D = {wh_noisy['crystallite_size_nm']:.2f} nm, eps = {wh_noisy['microstrain']:.5f}, R^2 = {wh_noisy['r2']:.4f}")
print(f"Annealed (eps=0) Fit : D = {wh_annealed['crystallite_size_nm']:.4f} nm, eps = {wh_annealed['microstrain']:.2e}")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.0, 4.3))
x_wh = 4.0 * np.sin(th_cu)
x_line = np.linspace(0.0, 3.4, 100)
ax1.scatter(x_wh, beta_annealed * np.cos(th_cu) * 1e3, color="#2ca02c", marker="s", s=55, label="Annealed ($\\varepsilon=0$)")
ax1.plot(x_line, (wh_annealed["intercept"] + wh_annealed["slope"] * x_line) * 1e3, "--", color="#2ca02c")
ax1.scatter(x_wh, beta_noisy * np.cos(th_cu) * 1e3, color="#d62728", marker="o", s=55, label="Cold-Worked (Noisy)")
ax1.plot(x_line, (wh_clean["intercept"] + wh_clean["slope"] * x_line) * 1e3, "-", color="#1f77b4", lw=2.0,
label=f"W–H Fit ($D={wh_clean['crystallite_size_nm']:.0f}$ nm, $\\varepsilon={wh_clean['microstrain']*1e3:.2f}\\times 10^{{-3}}$)")
ax1.set_xlabel("$4\\sin\\theta$ [-]")
ax1.set_ylabel("$\\beta\\cos\\theta$ [$10^{-3}$ rad]")
ax1.set_title("Williamson–Hall Size–Strain Plot (FCC Cu)")
ax1.set_xlim(0.0, 3.4)
ax1.set_ylim(0.0, 11.5)
ax1.legend(frameon=False, fontsize=8)
grid_zoom = np.linspace(40.0, 54.0, 701)
prof_coarse = diffraction.broadened_xrd_profile(pks_cu[:2], grid_zoom, fwhm_deg=0.12)
prof_nano = diffraction.broadened_xrd_profile(pks_cu[:2], grid_zoom, fwhm_deg=float(np.degrees(np.mean(beta_tot_cu[:2]))))
ax2.plot(grid_zoom, prof_coarse, color="#2ca02c", lw=1.8, label="Coarse Annealed (FWHM $0.12^\\circ$)")
ax2.plot(grid_zoom, prof_nano, color="#d62728", lw=2.0, ls="--", label="Cold-Worked Nano-Cu")
ax2.set_xlabel("Diffraction Angle $2\\theta$ [deg]")
ax2.set_ylabel("Relative Intensity [a.u.]")
ax2.set_title("Cu (111) & (200) Peak Broadening")
ax2.legend(frameon=False, fontsize=8.5)
label_panels(fig)
plt.show()
assert np.isclose(wh_clean["crystallite_size_nm"], D_true_nm, rtol=1e-12)
assert np.isclose(wh_clean["microstrain"], eps_cw, rtol=1e-12)
assert abs(wh_noisy["crystallite_size_nm"] - D_true_nm) < 5.0
Demonstration 3: Williamson-Hall Linear Deconvolution (Annealed vs Cold-Worked vs Noisy)
========================================================================================
Clean Cold-Worked Fit : D = 45.0000 nm, eps = 0.002200, R^2 = 1.000000
Noisy Cold-Worked Fit : D = 43.00 nm, eps = 0.00214, R^2 = 0.9986
Annealed (eps=0) Fit : D = 45.0000 nm, eps = 7.73e-19

Figure 4.2. Synthetic data. (a) Williamson–Hall plot for annealed and cold-worked copper: the intercept gives the crystallite size and the slope the microstrain. (b) The (111) and (200) peaks of the two samples.
What Demonstration 3 shows. Extrapolating the Williamson–Hall line back to removes of the microstrain contribution, recovering the exact intercept and slope .
4. Sensitivity: Instrumental Broadening Subtraction¶
Every real diffractometer contributes an instrumental width (typically , measured using a strain-free NIST standard) that must be subtracted before Scherrer or Williamson–Hall analysis:
Lorentzian deconvolution:
Gaussian deconvolution:
We test how uncorrected distorts size estimates across true grain sizes .
heading("Demonstration 4: Instrumental Broadening Sensitivity Across True Grain Sizes")
beta_inst_rad = np.radians(0.08)
tt_ref = 43.30 # Cu (111)
th_ref = 0.5 * np.radians(tt_ref)
print(f"{'D_true [nm]':>11s} | {'FWHM_sample [deg]':>17s} | {'FWHM_obs_L [deg]':>16s} | {'Uncorrected D [nm]':>18s} | {'Error [%]':>10s}")
print("-" * 84)
for d_nm in [10.0, 30.0, 80.0, 200.0]:
b_samp = (0.9 * constants.CU_K_ALPHA_A) / (d_nm * 10.0 * np.cos(th_ref))
b_obs = b_samp + beta_inst_rad
d_uncorr = diffraction.scherrer_crystallite_size_nm(b_obs, tt_ref)
err_pct = 100.0 * (d_uncorr - d_nm) / d_nm
print(f"{d_nm:11.1f} | {np.degrees(b_samp):17.4f} | {np.degrees(b_obs):16.4f} | {d_uncorr:18.2f} | {err_pct:+10.2f}%")
# Defensive input checks:
caught_neg, caught_short = False, False
try:
diffraction.scherrer_crystallite_size_nm(-0.01, 43.3)
except ValueError:
caught_neg = True
try:
diffraction.williamson_hall_fit(np.array([0.01]), np.array([43.3]))
except ValueError:
caught_short = True
assert caught_neg and caught_short
assert diffraction.scherrer_crystallite_size_nm(
(0.9 * constants.CU_K_ALPHA_A) / (2000.0 * np.cos(th_ref)) + beta_inst_rad, tt_ref
) < 90.0
Demonstration 4: Instrumental Broadening Sensitivity Across True Grain Sizes
============================================================================
D_true [nm] | FWHM_sample [deg] | FWHM_obs_L [deg] | Uncorrected D [nm] | Error [%]
------------------------------------------------------------------------------------
10.0 | 0.8547 | 0.9347 | 9.14 | -8.56%
30.0 | 0.2849 | 0.3649 | 23.42 | -21.92%
80.0 | 0.1068 | 0.1868 | 45.75 | -42.82%
200.0 | 0.0427 | 0.1227 | 69.64 | -65.18%
Inside the algorithm¶
At , sample broadening () swamps the instrument width ( bias), whereas at , exceeds (), capping uncorrected Scherrer estimates below ( error, why XRD line broadening has a practical upper ceiling around ). Below we inspect diffraction.williamson_hall_fit and verify ordinary least squares in pure NumPy.
Check against the library¶
heading("Inside the Algorithm: NumPy Vandermonde OLS vs diffraction.williamson_hall_fit")
print(show_source(diffraction.williamson_hall_fit))
x_vec = 4.0 * np.sin(th_cu)
y_vec = beta_noisy * np.cos(th_cu)
x_mean, y_mean = np.mean(x_vec), np.mean(y_vec)
slope_np = float(np.sum((x_vec - x_mean) * (y_vec - y_mean)) / np.sum((x_vec - x_mean) ** 2))
intercept_np = float(y_mean - slope_np * x_mean)
d_np = 0.1 * (0.9 * constants.CU_K_ALPHA_A) / intercept_np
print(f"NumPy: D = {d_np:.8f} nm, eps = {slope_np:.10f}")
print(f"Library : D = {wh_noisy['crystallite_size_nm']:.8f} nm, eps = {wh_noisy['microstrain']:.10f}")
assert np.isclose(d_np, wh_noisy["crystallite_size_nm"], rtol=1e-13)
assert np.isclose(slope_np, wh_noisy["microstrain"], rtol=1e-13)
Inside the Algorithm: NumPy Vandermonde OLS vs diffraction.williamson_hall_fit
==============================================================================
def williamson_hall_fit(
beta_fwhm_rad: np.ndarray,
two_theta_deg: np.ndarray,
wavelength_A: float = CU_K_ALPHA_A,
shape_factor: float = 0.9,
) -> dict:
"""Separate size and microstrain broadening via Williamson-Hall fit beta*cos(theta) = K*lam/D + 4*eps*sin(theta)."""
beta = np.asarray(beta_fwhm_rad, dtype=float).ravel()
theta = 0.5 * np.radians(np.asarray(two_theta_deg, dtype=float).ravel())
if beta.size < 2 or beta.size != theta.size:
raise ValueError("Provide at least two matching (beta_fwhm_rad, two_theta_deg) reflections.")
x = 4.0 * np.sin(theta)
y = beta * np.cos(theta)
a_mat = np.column_stack([x, np.ones_like(x)])
coeffs, _, _, _ = np.linalg.lstsq(a_mat, y, rcond=None)
slope = float(coeffs[0])
intercept = float(coeffs[1])
y_pred = a_mat @ coeffs
ss_res = float(np.sum((y - y_pred) ** 2))
ss_tot = float(np.sum((y - np.mean(y)) ** 2))
r2 = 1.0 - ss_res / ss_tot if ss_tot > 0.0 else 1.0
d_nm = 0.1 * (shape_factor * wavelength_A) / intercept if intercept > 0.0 else np.inf
return {
"crystallite_size_nm": float(d_nm),
"microstrain": slope,
"slope": slope,
"intercept": intercept,
"r2": r2,
}
NumPy: D = 43.00399777 nm, eps = 0.0021404098
Library : D = 43.00399777 nm, eps = 0.0021404098
Exercises¶
Worked solutions are in 04_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify across five reflections of strained
Si(, ) that naive single-peak Scherrer size satisfies to rounding error.Find how it fails. Quantify the exact error factor when is passed into
scherrer_crystallite_size_nmwithout converting degrees to radians, and compare the erroneous size to copper’s lattice constant .Implement it yourself. Implement
gaussian_size_strain_fit(beta_fwhm_rad, two_theta_deg, wavelength_A, shape_factor=0.9)for quadrature-broadened Gaussian peaks and compare against Lorentzianwilliamson_hall_fit.
heading("Self-check for the exercises")
tt_si = np.array([28.44, 47.30, 56.12, 69.13, 76.38])
th_si = 0.5 * np.radians(tt_si)
d_si_true, eps_si = 60.0, 0.0018
beta_si = (0.9 * constants.CU_K_ALPHA_A) / (d_si_true * 10.0 * np.cos(th_si)) + 4.0 * eps_si * np.tan(th_si)
d_si_app = diffraction.scherrer_crystallite_size_nm(beta_si, tt_si)
inv_d_exact = (1.0 / d_si_true) + (4.0 * eps_si * np.sin(th_si)) / (0.1 * 0.9 * constants.CU_K_ALPHA_A)
assert np.allclose(1.0 / d_si_app, inv_d_exact, rtol=1e-14)
print("Reciprocal Scherrer bias identity verified to machine precision across all 5 Si peaks")
print("All checks passed.")
Self-check for the exercises
============================
Reciprocal Scherrer bias identity verified to machine precision across all 5 Si peaks
All checks passed.