Worked solutions to the three exercises of Lecture 4. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
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))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
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])
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify across five reflections of strained Si (, ) that naive single-peak Scherrer size satisfies to rounding error.
heading("Exercise 1: Exact Reciprocal-Size Bias Law for Naive Single-Peak Scherrer")
pks_si = diffraction.simulate_powder_xrd("diamond", constants.ELEMENTS_DB["Si"]["a_A"], max_hkl=4, two_theta_max=85.0)
tt_si = np.array([p["two_theta_deg"] for p in pks_si])
th_si = 0.5 * np.radians(tt_si)
D_nm, eps = 60.0, 0.0018
beta_si = (0.9 * constants.CU_K_ALPHA_A) / (D_nm * 10.0 * np.cos(th_si)) + 4.0 * eps * np.tan(th_si)
D_app = diffraction.scherrer_crystallite_size_nm(beta_si, tt_si)
lhs = 1.0 / D_app
rhs = (1.0 / D_nm) + (4.0 * eps * np.sin(th_si)) / (0.1 * 0.9 * constants.CU_K_ALPHA_A)
for p, da, l_v, r_v in zip(pks_si, D_app, lhs, rhs):
print(f"Si {str(p['hkl']):10s} | D_app = {da:6.2f} nm | 1/D_app = {l_v:.6f} nm^-1 vs formula = {r_v:.6f} nm^-1")
assert np.allclose(lhs, rhs, rtol=1e-14)
Exercise 1: Exact Reciprocal-Size Bias Law for Naive Single-Peak Scherrer
=========================================================================
Si (1, 1, 1) | D_app = 33.99 nm | 1/D_app = 0.029424 nm^-1 vs formula = 0.029424 nm^-1
Si (2, 2, 0) | D_app = 26.67 nm | 1/D_app = 0.037499 nm^-1 vs formula = 0.037499 nm^-1
Si (3, 1, 1) | D_app = 24.33 nm | 1/D_app = 0.041094 nm^-1 vs formula = 0.041094 nm^-1
Si (4, 0, 0) | D_app = 21.68 nm | 1/D_app = 0.046128 nm^-1 vs formula = 0.046128 nm^-1
Si (3, 3, 1) | D_app = 20.50 nm | 1/D_app = 0.048771 nm^-1 vs formula = 0.048771 nm^-1
Explanation. Dividing by shows immediately that is the Williamson–Hall ordinate rescaled into .
Exercise 2¶
Problem. Quantify the exact error factor when is passed into scherrer_crystallite_size_nm without converting degrees to radians, and compare the erroneous size to copper’s lattice constant .
heading("Exercise 2: Diagnostic Audit — Passing FWHM in Degrees Instead of Radians")
fwhm_deg = 0.45
tt_cu111 = 43.30
d_correct_nm = diffraction.scherrer_crystallite_size_nm(np.radians(fwhm_deg), tt_cu111)
d_deg_bug_nm = diffraction.scherrer_crystallite_size_nm(fwhm_deg, tt_cu111)
a_cu_nm = 0.1 * constants.ELEMENTS_DB["Cu"]["a_A"]
print(f"Correct radian Scherrer D = {d_correct_nm:.3f} nm")
print(f"Unconverted degree-bug D = {d_deg_bug_nm:.4f} nm (< 1 Cu unit cell a = {a_cu_nm:.4f} nm)")
print(f"Exact error ratio = {d_correct_nm / d_deg_bug_nm:.6f} == 180 / pi")
assert np.isclose(d_correct_nm / d_deg_bug_nm, 180.0 / np.pi, rtol=1e-14)
assert d_deg_bug_nm < a_cu_nm
Exercise 2: Diagnostic Audit — Passing FWHM in Degrees Instead of Radians
=========================================================================
Correct radian Scherrer D = 18.994 nm
Unconverted degree-bug D = 0.3315 nm (< 1 Cu unit cell a = 0.3615 nm)
Exact error ratio = 57.295780 == 180 / pi
Explanation. Omitting np.radians(..) divides by , which turns into , less than one unit cell of copper. A size below the lattice constant is a sign of this unit error.
Exercise 3¶
Problem. 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 Lorentzian williamson_hall_fit.
heading("Exercise 3: Implement It Yourself — Quadratic Gaussian Size-Strain Deconvolution")
def gaussian_size_strain_fit(
beta_fwhm_rad: np.ndarray,
two_theta_deg: np.ndarray,
wavelength_A: float = constants.CU_K_ALPHA_A,
shape_factor: float = 0.9,
) -> dict:
"""Separate Gaussian size and microstrain broadening via (beta*cos(th))^2 = (K*lam/D)^2 + 16*eps^2*sin^2(th)."""
beta = np.asarray(beta_fwhm_rad, dtype=float).ravel()
th = 0.5 * np.radians(np.asarray(two_theta_deg, dtype=float).ravel())
x_quad = (4.0 * np.sin(th)) ** 2
y_quad = (beta * np.cos(th)) ** 2
a_mat = np.column_stack([x_quad, np.ones_like(x_quad)])
coeffs, _, _, _ = np.linalg.lstsq(a_mat, y_quad, rcond=None)
eps_est = float(np.sqrt(max(coeffs[0], 0.0)))
d_nm = 0.1 * (shape_factor * wavelength_A) / np.sqrt(coeffs[1])
return {"crystallite_size_nm": float(d_nm), "microstrain": eps_est}
tt_test = np.array([43.30, 50.43, 74.13, 89.93, 95.14])
th_test = 0.5 * np.radians(tt_test)
D_true, eps_true = 40.0, 0.0020
b_size = (0.9 * constants.CU_K_ALPHA_A) / (D_true * 10.0 * np.cos(th_test))
b_str = 4.0 * eps_true * np.tan(th_test)
beta_gauss = np.sqrt(b_size ** 2 + b_str ** 2)
g_fit = gaussian_size_strain_fit(beta_gauss, tt_test)
l_fit = diffraction.williamson_hall_fit(beta_gauss, tt_test)
print(f"Quadratic Gaussian Fit: D = {g_fit['crystallite_size_nm']:.4f} nm, eps = {g_fit['microstrain']:.6f} (EXACT)")
print(f"Linear Lorentzian Fit : D = {l_fit['crystallite_size_nm']:.2f} nm, eps = {l_fit['microstrain']:.6f} (model-mismatch bias)")
assert np.isclose(g_fit["crystallite_size_nm"], D_true, rtol=1e-12)
assert np.isclose(g_fit["microstrain"], eps_true, rtol=1e-12)
assert abs(l_fit["crystallite_size_nm"] - D_true) > 5.0
Exercise 3: Implement It Yourself — Quadratic Gaussian Size-Strain Deconvolution
================================================================================
Quadratic Gaussian Fit: D = 40.0000 nm, eps = 0.002000 (EXACT)
Linear Lorentzian Fit : D = 62.31 nm, eps = 0.001557 (model-mismatch bias)
Summary. Because , applying linear Lorentzian Williamson–Hall to purely Gaussian peaks overestimates ( against ), motivating quadratic Gaussian or Halder–Wagner plots for pseudo-Voigt profiles.