When monochromatic X-rays strike a crystalline powder, Bragg’s law predicts where diffraction cones could appear, yet in practice, entire families of reflections vanish completely. Copper shows (111) and (200) but never (100) or (110); iron shows (110) and (200) but never (111); and diamond-cubic silicon extinguishes (200) and (222) via destructive interference across its glide basis. In this lecture, we compute complex kinematic structure factors and synthesize full Bragg–Brentano powder diffractograms.
Learning objectives¶
Apply Bragg’s law (
diffraction.bragg_two_theta_deg,diffraction.bragg_d_spacing_A) for () vs. ().Evaluate complex kinematic structure factors (
diffraction.structure_factor_hkl) and verify FCC, BCC, Diamond, and HCP selection rules.Combine multiplicity and the Lorentz–polarization factor (
diffraction.lorentz_polarization_factor) to simulate powder patterns (diffraction.simulate_powder_xrd).Synthesize continuous pseudo-Voigt diffractograms (
diffraction.broadened_xrd_profile) and analyze Ewald-sphere wavelength cutoffs.
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 Bragg’s Law & Ewald Resolution Cutoff¶
Constructive interference between X-rays of wavelength scattered elastically by parallel planes of spacing occurs at glancing Bragg angle (diffractometer detector angle ):
Because , diffraction is physically observable only for plane spacings satisfying (the diameter of the Ewald sphere in reciprocal space is ).
1.2 Kinematic Structure Factor ¶
Within each unit cell, basis atoms at fractional coordinates with atomic scattering factors interfere with phase shifts :
heading("Demonstration 1: Bragg Angle Comparison (Cu K-alpha1 vs Mo K-alpha1) & Round-Trip Closure")
si_lat = lattices.cubic_unit_cell("diamond", constants.ELEMENTS_DB["Si"]["a_A"])["lattice_vectors"]
print(f"{'Si (hkl)':10s} | {'d_hkl [A]':>10s} | {'2theta Cu-Ka1 [deg]':>19s} | {'2theta Mo-Ka1 [deg]':>19s} | {'Round-trip d [A]':>16s}")
print("-" * 86)
for hkl in [(1, 1, 1), (2, 2, 0), (3, 1, 1), (4, 0, 0), (3, 3, 1)]:
d_val = lattices.interplanar_spacing(hkl, si_lat)
tt_cu = diffraction.bragg_two_theta_deg(d_val, wavelength_A=constants.CU_K_ALPHA_A)
tt_mo = diffraction.bragg_two_theta_deg(d_val, wavelength_A=constants.MO_K_ALPHA_A)
d_back = diffraction.bragg_d_spacing_A(tt_cu, wavelength_A=constants.CU_K_ALPHA_A)
print(f"{str(hkl):10s} | {d_val:10.5f} | {tt_cu:19.4f} | {tt_mo:19.4f} | {d_back:16.5f}")
assert np.isclose(d_back, d_val, rtol=1e-14)
assert tt_mo < tt_cu
Demonstration 1: Bragg Angle Comparison (Cu K-alpha1 vs Mo K-alpha1) & Round-Trip Closure
=========================================================================================
Si (hkl) | d_hkl [A] | 2theta Cu-Ka1 [deg] | 2theta Mo-Ka1 [deg] | Round-trip d [A]
--------------------------------------------------------------------------------------
(1, 1, 1) | 3.13553 | 28.4426 | 12.9892 | 3.13553
(2, 2, 0) | 1.92011 | 47.3032 | 21.2882 | 1.92011
(3, 1, 1) | 1.63748 | 56.1229 | 25.0175 | 1.63748
(4, 0, 0) | 1.35773 | 69.1306 | 30.2845 | 1.35773
(3, 3, 1) | 1.24593 | 76.3769 | 33.0763 | 1.24593
What Demonstration 1 shows. Silicon’s primary (111) reflection () appears at under (), but compresses down to under harder radiation (), with bragg_d_spacing_A inverting bragg_two_theta_deg to rounding error.
2. Systematic Absences Across FCC, BCC, Diamond & HCP Crystals¶
Evaluating Equation (1.2) on unit-form-factor () fractional coordinates yields exact crystallographic extinction rules:
BCC: if is even, 0 if odd.
FCC: if have unmixed parity (all even or all odd), 0 otherwise.
Diamond: (
h,k,lall odd), (h,k,lall even and ), and forbidden (0) when such as(200)and(222).HCP: Forbidden whenever and is odd, extinguishing basal
(001)and(003).
heading("Demonstration 2: Kinematic Structure Factors |F_hkl|^2 & Systematic Absences")
cells = {
"BCC": lattices.cubic_unit_cell("bcc", 1.0)["fractional_coords"],
"FCC": lattices.cubic_unit_cell("fcc", 1.0)["fractional_coords"],
"Diamond": lattices.cubic_unit_cell("diamond", 1.0)["fractional_coords"],
"HCP": lattices.hcp_unit_cell(1.0)["fractional_coords"],
}
test_hkls = [(1, 0, 0), (0, 0, 1), (0, 0, 2), (1, 0, 1), (1, 1, 0), (1, 1, 1), (2, 0, 0), (2, 2, 0), (2, 2, 2), (4, 0, 0)]
print(f"{'(hkl)':10s} | {'BCC |F|^2':>10s} | {'FCC |F|^2':>10s} | {'Diam |F|^2':>11s} | {'HCP |F|^2':>10s}")
print("-" * 64)
for hkl in test_hkls:
vals = {k: diffraction.structure_factor_hkl(hkl, fc)["intensity_F2"] for k, fc in cells.items()}
print(f"{str(hkl):10s} | {vals['BCC']:10.2f} | {vals['FCC']:10.2f} | {vals['Diamond']:11.2f} | {vals['HCP']:10.2f}")
# Assert signature selection rules:
assert not diffraction.structure_factor_hkl((1, 0, 0), cells["FCC"])["allowed"]
assert not diffraction.structure_factor_hkl((1, 1, 1), cells["BCC"])["allowed"]
assert not diffraction.structure_factor_hkl((2, 0, 0), cells["Diamond"])["allowed"]
assert not diffraction.structure_factor_hkl((2, 2, 2), cells["Diamond"])["allowed"]
assert np.isclose(diffraction.structure_factor_hkl((1, 1, 1), cells["Diamond"])["intensity_F2"], 32.0)
assert np.isclose(diffraction.structure_factor_hkl((2, 2, 0), cells["Diamond"])["intensity_F2"], 64.0)
assert not diffraction.structure_factor_hkl((0, 0, 1), cells["HCP"])["allowed"]
assert np.isclose(diffraction.structure_factor_hkl((1, 0, 1), cells["HCP"])["intensity_F2"], 3.0)
Demonstration 2: Kinematic Structure Factors |F_hkl|^2 & Systematic Absences
============================================================================
(hkl) | BCC |F|^2 | FCC |F|^2 | Diam |F|^2 | HCP |F|^2
----------------------------------------------------------------
(1, 0, 0) | 0.00 | 0.00 | 0.00 | 1.00
(0, 0, 1) | 0.00 | 0.00 | 0.00 | 0.00
(0, 0, 2) | 4.00 | 16.00 | 0.00 | 4.00
(1, 0, 1) | 4.00 | 0.00 | 0.00 | 3.00
(1, 1, 0) | 4.00 | 0.00 | 0.00 | 4.00
(1, 1, 1) | 0.00 | 16.00 | 32.00 | 0.00
(2, 0, 0) | 4.00 | 16.00 | 0.00 | 1.00
(2, 2, 0) | 4.00 | 16.00 | 64.00 | 4.00
(2, 2, 2) | 4.00 | 16.00 | 0.00 | 4.00
(4, 0, 0) | 4.00 | 16.00 | 64.00 | 1.00
fig, ax = plt.subplots(figsize=(7.4, 3.8))
rows = [("sc", "SC"), ("bcc", "BCC"), ("fcc", "FCC"), ("diamond", "diamond")]
for row, (struct_name, label_name) in enumerate(rows):
frac_plot = lattices.cubic_unit_cell(struct_name, 1.0)["fractional_coords"]
allowed_n = set()
for h in range(0, 5):
for k in range(0, h + 1):
for l in range(0, k + 1):
n_sum = h * h + k * k + l * l
if 0 < n_sum <= 24 and diffraction.structure_factor_hkl((h, k, l), frac_plot)["allowed"]:
allowed_n.add(n_sum)
ax.vlines(sorted(allowed_n), row - 0.35, row + 0.35, color=f"C{row}", lw=2.0)
ax.set_yticks(range(len(rows))); ax.set_yticklabels([name for _, name in rows]); ax.minorticks_off()
ax.set_xticks(range(0, 25, 2)); ax.set_xlim(0, 25); ax.set_ylim(-0.7, len(rows) - 0.3)
ax.set_xlabel(r"$h^2 + k^2 + l^2$")
plt.show()
Figure 3.1. Allowed reflections of four cubic structures up to , from the structure factor. Since for a cubic crystal, the sequence of lines identifies the structure.
What Demonstration 2 shows. Rows (2, 0, 0) and (2, 2, 2) are allowed in FCC (), yet extinguished in Diamond () because the second interpenetrating FCC sublattice shifted by scatters out of phase (). Similarly, in HCP, (001) vanishes while (100) (), (101) (), and (002) () survive in a structure-factor ratio.
3. Simulating Full Powder Diffractograms (Cu, Fe, Si, Ti)¶
In an unpolarized Bragg–Brentano powder diffractometer, raw peak intensity combines plane multiplicity , , and the geometric Lorentz–polarization factor:
We simulate and plot continuous pseudo-Voigt powder XRD patterns (simulate_powder_xrd + broadened_xrd_profile) for Cu, Fe, Si, and Ti.
heading("Demonstration 3: Simulated Cu K-alpha1 Powder Diffractograms for Cu, Fe, Si & Ti")
grid_2theta = np.linspace(20.0, 100.0, 1601)
targets = [("Cu (FCC)", "Cu"), ("Fe (BCC)", "Fe"), ("Si (Diamond)", "Si"), ("Ti (HCP)", "Ti")]
fig, ax = plt.subplots(figsize=(9.5, 5.2))
colors = ["#1f77b4", "#d62728", "#2ca02c", "#9467bd"]
for idx, (lbl, sym) in enumerate(targets):
meta = constants.ELEMENTS_DB[sym]
pks = diffraction.simulate_powder_xrd(
meta["structure"], meta["a_A"], c_A=meta["c_A"], two_theta_max=100.0, atomic_Z=meta["Z"]
)
prof = diffraction.broadened_xrd_profile(pks, grid_2theta, fwhm_deg=0.35, eta_pseudo_voigt=0.5)
offset = idx * 115.0
ax.plot(grid_2theta, prof + offset, color=colors[idx], lw=1.5, label=lbl)
top3 = sorted(pks, key=lambda p: p["intensity_rel"], reverse=True)[:3]
for p in pks[:4]:
ax.annotate(f"{p['hkl']}", (p["two_theta_deg"], p["intensity_rel"] + offset + 3.0),
fontsize=7.5, ha="center", va="bottom", rotation=90, color=colors[idx])
print(f"{lbl:13s} | {len(pks):2d} peaks in [20, 100] deg | strongest = {top3[0]['hkl']} at 2theta = {top3[0]['two_theta_deg']:.2f} deg")
assert len(pks) >= 3
assert np.isclose(max(p["intensity_rel"] for p in pks), 100.0, rtol=1e-12)
ax.set_xlabel("Diffraction Angle $2\\theta$ [deg] (Cu $K\\alpha_1$, $\\lambda = 1.5406$ Å)")
ax.set_ylabel("Normalized Intensity + Waterfall Offset [a.u.]")
ax.set_title("Simulated Bragg–Brentano Powder XRD Fingerprints Across Crystal Classes")
ax.set_ylim(-5, 485)
ax.set_ylim(top=500.0)
ax.legend(loc="upper right", frameon=False)
plt.show()
Demonstration 3: Simulated Cu K-alpha1 Powder Diffractograms for Cu, Fe, Si & Ti
================================================================================
Cu (FCC) | 5 peaks in [20, 100] deg | strongest = (1, 1, 1) at 2theta = 43.32 deg
Fe (BCC) | 4 peaks in [20, 100] deg | strongest = (1, 1, 0) at 2theta = 44.67 deg
Si (Diamond) | 7 peaks in [20, 100] deg | strongest = (1, 1, 1) at 2theta = 28.44 deg
Ti (HCP) | 12 peaks in [20, 100] deg | strongest = (1, 0, 1) at 2theta = 40.16 deg

Figure 3.2. Computed powder patterns of Cu, Fe, Si and Ti for Cu K radiation, offset vertically. All atoms are given the same form factor, so only the positions and the absences are quantitative; the peak width is chosen for display.
What Demonstration 3 shows. Each structure has its own pattern: FCC Cu opens with the closely spaced (111)/(200) doublet (); BCC Fe shows evenly spaced (110), (200), (211); Diamond Si shows wide gaps where (200) and (222) are missing; and lower-symmetry HCP Ti splits into the (100), (002), (101) triplet between and .
4. Sensitivity: Radiation Wavelength & Ewald Cutoff¶
How many reflections can simulate_powder_xrd observe in Cu (, max_hkl=6, two_theta_max=150.0) when switching X-ray anode from () to () to ()?
heading("Demonstration 4: Anode Wavelength Sweep & Ewald Sphere Cutoff (d_min = lambda / 2)")
anodes = [("Cr K-alpha", 2.28970), ("Cu K-alpha1", constants.CU_K_ALPHA_A), ("Mo K-alpha1", constants.MO_K_ALPHA_A)]
cu_a = constants.ELEMENTS_DB["Cu"]["a_A"]
counts = []
for name, wl in anodes:
pks = diffraction.simulate_powder_xrd("fcc", cu_a, wavelength_A=wl, max_hkl=6, two_theta_max=150.0)
counts.append(len(pks))
d_min = 0.5 * wl
print(f"{name:12s} (lambda = {wl:.5f} A, d_min = {d_min:.4f} A) -> {len(pks):2d} observable FCC peaks <= 150 deg")
# Verify ValueError when wavelength > 2*d (outside Ewald sphere):
caught_ewald = False
try:
diffraction.bragg_two_theta_deg(d_A=0.60, wavelength_A=constants.CU_K_ALPHA_A)
except ValueError:
caught_ewald = True
assert caught_ewald
assert counts[0] < counts[1] < counts[2]
Demonstration 4: Anode Wavelength Sweep & Ewald Sphere Cutoff (d_min = lambda / 2)
==================================================================================
Cr K-alpha (lambda = 2.28970 A, d_min = 1.1448 A) -> 3 observable FCC peaks <= 150 deg
Cu K-alpha1 (lambda = 1.54060 A, d_min = 0.7703 A) -> 8 observable FCC peaks <= 150 deg
Mo K-alpha1 (lambda = 0.70932 A, d_min = 0.3547 A) -> 26 observable FCC peaks <= 150 deg
Inside the algorithm¶
Halving X-ray wavelength doubles the radius of the Ewald sphere, so the number of Cu reflections below grows from 3 () to 8 () to 26 (). Below we inspect diffraction.structure_factor_hkl and verify a vectorized NumPy structure-factor matrix across 20 reflections simultaneously.
Check against the library¶
heading("Inside the Algorithm: Vectorized NumPy Complex Phase Matrix vs structure_factor_hkl")
print(show_source(diffraction.structure_factor_hkl))
frac_si = lattices.cubic_unit_cell("diamond", 5.4309)["fractional_coords"]
hkl_batch = np.array([[1, 1, 1], [2, 0, 0], [2, 2, 0], [3, 1, 1], [2, 2, 2], [4, 0, 0], [3, 3, 1], [4, 2, 2]], dtype=float)
# NumPy batch evaluation: shape (M_reflections, N_atoms)
phases = 2.0 * np.pi * (hkl_batch @ frac_si.T)
f_complex_np = np.sum(28.0 * np.exp(1j * phases), axis=1)
f2_np = np.abs(f_complex_np) ** 2
f2_lib = np.array([diffraction.structure_factor_hkl(h, frac_si, form_factors=28.0)["intensity_F2"] for h in hkl_batch])
print("NumPy |F|^2:", np.round(f2_np, 2))
print("Library |F|^2:", np.round(f2_lib, 2))
assert np.allclose(f2_np, f2_lib, rtol=1e-13, atol=1e-12)
Inside the Algorithm: Vectorized NumPy Complex Phase Matrix vs structure_factor_hkl
===================================================================================
def structure_factor_hkl(
hkl: tuple | list | np.ndarray,
fractional_coords: np.ndarray,
form_factors: np.ndarray | float | None = None,
) -> dict:
"""Evaluate complex kinematic structure factor F_hkl = sum_j f_j exp(2*pi*i*(h*x_j + k*y_j + l*z_j))."""
idx = np.asarray(hkl, dtype=float).reshape(3)
frac = np.asarray(fractional_coords, dtype=float)
if frac.ndim != 2 or frac.shape[1] != 3:
raise ValueError("fractional_coords must have shape (N, 3).")
n_atoms = frac.shape[0]
if form_factors is None:
f_arr = np.ones(n_atoms, dtype=float)
elif np.ndim(form_factors) == 0:
f_arr = np.full(n_atoms, float(form_factors), dtype=float)
else:
f_arr = np.asarray(form_factors, dtype=float).reshape(n_atoms)
phases = 2.0 * np.pi * (frac @ idx)
f_complex = np.sum(f_arr * np.exp(1j * phases))
f2 = float(np.abs(f_complex) ** 2)
return {
"F_complex": complex(f_complex),
"F_real": float(np.real(f_complex)),
"F_imag": float(np.imag(f_complex)),
"intensity_F2": f2,
"allowed": bool(f2 > 1e-10),
}
NumPy |F|^2: [25088. 0. 50176. 25088. 0. 50176. 25088. 50176.]
Library |F|^2: [25088. 0. 50176. 25088. 0. 50176. 25088. 50176.]
Exercises¶
Worked solutions are in 03_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify the exact first-5 allowed sequences for
Cu(fcc),Fe(bcc), andSi(diamond) viasimulate_powder_xrd, and recover from across all peaks to rounding error.Find how it fails. Compare
(100)superlattice and(110)fundamental structure factors in orderedB2FeAl (form_factors=[26.0, 13.0]) versus disorderedA2([19.5, 19.5]) usingdiffraction.structure_factor_hkl.Implement it yourself. Implement
index_unknown_cubic_xrd(two_theta_deg_list, wavelength_A)using 7 reflections under to break the 6-peakSC/BCCdegeneracy ( vs. 7) and verify exact classification and recovery onSC,Fe(bcc),Cu(fcc), andSi(diamond).
heading("Self-check for the exercises")
for st, a_val, expected_N in [("fcc", 3.6149, [3, 4, 8, 11, 12]),
("bcc", 2.8665, [2, 4, 6, 8, 10]),
("diamond", 5.4309, [3, 8, 11, 16, 19])]:
pks = diffraction.simulate_powder_xrd(st, a_val, max_hkl=5, two_theta_max=145.0)
n_seq = [sum(x * x for x in p["hkl"]) for p in pks[:5]]
print(f"{st:8s} first 5 allowed N = h^2+k^2+l^2: {n_seq}")
assert n_seq == expected_N
print("All checks passed.")
Self-check for the exercises
============================
fcc first 5 allowed N = h^2+k^2+l^2: [3, 4, 8, 11, 12]
bcc first 5 allowed N = h^2+k^2+l^2: [2, 4, 6, 8, 10]
diamond first 5 allowed N = h^2+k^2+l^2: [3, 8, 11, 16, 19]
All checks passed.