Worked solutions to the three exercises of Lecture 3. 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: 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
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify the exact first-5 allowed sequences for Cu (fcc), Fe (bcc), and Si (diamond) via simulate_powder_xrd, and recover from across all peaks to rounding error.
heading("Exercise 1: Cubic sin^2(theta) Integer Signatures & Exact Lattice-Parameter Inversion")
expected = {"Cu": [3, 4, 8, 11, 12], "Fe": [2, 4, 6, 8, 10], "Si": [3, 8, 11, 16, 19]}
for sym, exp_n in expected.items():
meta = constants.ELEMENTS_DB[sym]
pks = diffraction.simulate_powder_xrd(meta["structure"], meta["a_A"], max_hkl=5, two_theta_max=145.0)
n_obs = [sum(x * x for x in p["hkl"]) for p in pks[:5]]
a_recovered = [
constants.CU_K_ALPHA_A * np.sqrt(sum(x * x for x in p["hkl"])) / (2.0 * np.sin(0.5 * np.radians(p["two_theta_deg"])))
for p in pks[:5]
]
print(f"{sym} ({meta['structure']:7s}) | N_seq = {n_obs} | mean recovered a = {np.mean(a_recovered):.6f} A (true = {meta['a_A']:.6f} A)")
assert n_obs == exp_n
assert np.allclose(a_recovered, meta["a_A"], rtol=1e-13)
Exercise 1: Cubic sin^2(theta) Integer Signatures & Exact Lattice-Parameter Inversion
=====================================================================================
Cu (fcc ) | N_seq = [3, 4, 8, 11, 12] | mean recovered a = 3.614900 A (true = 3.614900 A)
Fe (bcc ) | N_seq = [2, 4, 6, 8, 10] | mean recovered a = 2.866500 A (true = 2.866500 A)
Si (diamond) | N_seq = [3, 8, 11, 16, 19] | mean recovered a = 5.430900 A (true = 5.430900 A)
Explanation. FCC produces , BCC produces , and Diamond produces , so the ratio of the first two peaks already separates the three structures.
Exercise 2¶
Problem. Compare (100) superlattice and (110) fundamental structure factors in ordered B2 FeAl (form_factors=[26.0, 13.0]) versus disordered A2 ([19.5, 19.5]) using diffraction.structure_factor_hkl.
heading("Exercise 2: Diagnostic Audit — B2 Superlattice Ordering vs Disordered BCC Extinction")
b2_frac = np.array([[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]])
sf_100_dis = diffraction.structure_factor_hkl((1, 0, 0), b2_frac, form_factors=[19.5, 19.5])
sf_100_ord = diffraction.structure_factor_hkl((1, 0, 0), b2_frac, form_factors=[26.0, 13.0])
sf_110_ord = diffraction.structure_factor_hkl((1, 1, 0), b2_frac, form_factors=[26.0, 13.0])
print(f"Disordered A2 (100): allowed = {sf_100_dis['allowed']}, |F|^2 = {sf_100_dis['intensity_F2']:.2f}")
print(f"Ordered B2 (100): allowed = {sf_100_ord['allowed']}, |F|^2 = {sf_100_ord['intensity_F2']:.2f} == (f_Fe - f_Al)^2")
print(f"Ordered B2 (110): allowed = {sf_110_ord['allowed']}, |F|^2 = {sf_110_ord['intensity_F2']:.2f} == (f_Fe + f_Al)^2")
assert not sf_100_dis["allowed"]
assert sf_100_ord["allowed"] and np.isclose(sf_100_ord["intensity_F2"], (26.0 - 13.0) ** 2, rtol=1e-14)
assert np.isclose(sf_110_ord["intensity_F2"], (26.0 + 13.0) ** 2, rtol=1e-14)
Exercise 2: Diagnostic Audit — B2 Superlattice Ordering vs Disordered BCC Extinction
====================================================================================
Disordered A2 (100): allowed = False, |F|^2 = 0.00
Ordered B2 (100): allowed = True, |F|^2 = 169.00 == (f_Fe - f_Al)^2
Ordered B2 (110): allowed = True, |F|^2 = 1521.00 == (f_Fe + f_Al)^2
Explanation. Breaking body-centering translational symmetry by chemical ordering () reduces the Bravais lattice from BCC to simple cubic with a 2-atom basis, lighting up superlattice peaks ( odd) with intensity proportional to chemical contrast (the basis of long-range order parameter measurement in intermetallics).
Exercise 3¶
Problem. Implement index_unknown_cubic_xrd(two_theta_deg_list, wavelength_A) using 7 reflections under to break the 6-peak SC/BCC degeneracy ( vs. 7) and verify exact classification and recovery on SC, Fe (bcc), Cu (fcc), and Si (diamond).
heading("Exercise 3: Implement It Yourself — 7-Peak Cubic XRD Indexer (Breaking SC vs BCC Degeneracy)")
def index_unknown_cubic_xrd(two_theta_deg_list: list[float], wavelength_A: float = constants.MO_K_ALPHA_A) -> dict:
"""Classify cubic Bravais/basis type (including SC vs BCC at peak 7) and extract a_A [A]."""
sin2 = np.sin(0.5 * np.radians(np.asarray(two_theta_deg_list[:7], dtype=float))) ** 2
ratios = sin2 / sin2[0]
templates = {
"sc": np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 8.0]),
"bcc": np.array([2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0]),
"fcc": np.array([3.0, 4.0, 8.0, 11.0, 12.0, 16.0, 19.0]),
"diamond": np.array([3.0, 8.0, 11.0, 16.0, 19.0, 24.0, 27.0]),
}
best_st, best_err = None, np.inf
for st, n_vec in templates.items():
err = float(np.max(np.abs(ratios - n_vec / n_vec[0])))
if err < best_err:
best_st, best_err = st, err
n_matched = templates[best_st]
a_vals = wavelength_A * np.sqrt(n_matched) / (2.0 * np.sqrt(sin2))
return {"structure": best_st, "a_A": float(np.mean(a_vals)), "max_ratio_residual": best_err}
samples = [
("Po-alpha (SC)", "sc", 3.3590),
("Fe (BCC)", "bcc", constants.ELEMENTS_DB["Fe"]["a_A"]),
("Cu (FCC)", "fcc", constants.ELEMENTS_DB["Cu"]["a_A"]),
("Si (Diamond)", "diamond", constants.ELEMENTS_DB["Si"]["a_A"]),
]
for label, st_true, a_true in samples:
pks = diffraction.simulate_powder_xrd(st_true, a_true, wavelength_A=constants.MO_K_ALPHA_A, max_hkl=6)
tt_list = [p["two_theta_deg"] for p in pks[:7]]
res = index_unknown_cubic_xrd(tt_list, wavelength_A=constants.MO_K_ALPHA_A)
print(f"{label:15s} -> classified = {res['structure']:8s}, extracted a = {res['a_A']:.5f} A (true = {a_true:.5f} A)")
assert res["structure"] == st_true
assert np.isclose(res["a_A"], a_true, rtol=1e-12)
Exercise 3: Implement It Yourself — 7-Peak Cubic XRD Indexer (Breaking SC vs BCC Degeneracy)
============================================================================================
Po-alpha (SC) -> classified = sc , extracted a = 3.35900 A (true = 3.35900 A)
Fe (BCC) -> classified = bcc , extracted a = 2.86650 A (true = 2.86650 A)
Cu (FCC) -> classified = fcc , extracted a = 3.61490 A (true = 3.61490 A)
Si (Diamond) -> classified = diamond , extracted a = 5.43090 A (true = 5.43090 A)
Summary. Because no three integers satisfy , SC skips 7 ([1,2,3,4,5,6,8]) while BCC hits via (321), a crystallographic pitfall where inspecting fewer than 7 reflections misindexes a BCC metal of edge as an SC crystal of edge .