Worked solutions to the three exercises of Lecture 1. 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: Cubic & Hexagonal Unit-Cell Construction and Ideal vs Real HCP c/a")
for st in ["sc", "bcc", "fcc", "diamond"]:
c = lattices.cubic_unit_cell(st, a_A=4.0)
assert np.allclose(c["cartesian_coords"], c["fractional_coords"] @ c["lattice_vectors"])
print(f"Cubic {st:8s} | n_atoms = {c['n_atoms']:2d} | basis[0..1] frac = {c['fractional_coords'][:2].tolist()}")
hcp_ideal = lattices.hcp_unit_cell(a_A=3.0)
ti_meta = constants.ELEMENTS_DB["Ti"]
mg_meta = constants.ELEMENTS_DB["Mg"]
hcp_ti = lattices.hcp_unit_cell(ti_meta["a_A"], ti_meta["c_A"])
hcp_mg = lattices.hcp_unit_cell(mg_meta["a_A"], mg_meta["c_A"])
print(f"\nIdeal HCP c/a = {hcp_ideal['c_over_a']:.6f} (sqrt(8/3) = {np.sqrt(8.0 / 3.0):.6f})")
print(f"Ti HCP c/a = {hcp_ti['c_over_a']:.6f} (deviation = {100.0 * (hcp_ti['c_over_a'] / np.sqrt(8.0 / 3.0) - 1.0):+.2f}%)")
print(f"Mg HCP c/a = {hcp_mg['c_over_a']:.6f} (deviation = {100.0 * (hcp_mg['c_over_a'] / np.sqrt(8.0 / 3.0) - 1.0):+.2f}%)")
assert np.isclose(hcp_ideal["c_over_a"], np.sqrt(8.0 / 3.0), rtol=1e-15)
assert hcp_ti["c_over_a"] < hcp_mg["c_over_a"] < hcp_ideal["c_over_a"]
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify for Ti and Mg HCP cells that with matches element_crystal_summary(sym)['d_nn_A'] and to rounding error.
heading("Exercise 1: Metric-Tensor Bond Length Verification in Non-Orthogonal HCP Coordinates")
df = np.array([1.0 / 3.0, 2.0 / 3.0, 0.5])
for sym in ["Ti", "Mg"]:
meta = constants.ELEMENTS_DB[sym]
cell = lattices.hcp_unit_cell(meta["a_A"], meta["c_A"])
mt = lattices.metric_tensor(cell["lattice_vectors"])
d_metric = float(np.sqrt(df @ mt["G"] @ df))
d_analytic = float(np.sqrt((meta["a_A"] ** 2) / 3.0 + 0.25 * (meta["c_A"] ** 2)))
d_lib = lattices.element_crystal_summary(sym)["d_nn_A"]
print(f"{sym}: d_metric = {d_metric:.8f} A | d_analytic = {d_analytic:.8f} A | d_lib = {d_lib:.8f} A")
assert np.isclose(d_metric, d_analytic, rtol=1e-15)
assert np.isclose(d_metric, d_lib, rtol=1e-14)
Exercise 1: Metric-Tensor Bond Length Verification in Non-Orthogonal HCP Coordinates
====================================================================================
Ti: d_metric = 2.89670234 A | d_analytic = 2.89670234 A | d_lib = 2.89670234 A
Mg: d_metric = 3.19711202 A | d_analytic = 3.19711202 A | d_lib = 3.19711202 A
Explanation. Expanding shows how automatically accounts for the hexagonal basis angle without Cartesian projection.
Exercise 2¶
Problem. Demonstrate how transposing non-orthogonal HCP Ti basis vectors (A.T instead of A) corrupts metric_tensor lengths and angles, and verify ValueError guards on coplanar lattice vectors and negative lattice constants.
heading("Exercise 2: Diagnostic Audit of Column-Stacked Basis Bug & Coplanar Lattice Guard")
ti_cell = lattices.hcp_unit_cell(constants.ELEMENTS_DB["Ti"]["a_A"], constants.ELEMENTS_DB["Ti"]["c_A"])
mt_correct = lattices.metric_tensor(ti_cell["lattice_vectors"])
mt_transposed_bug = lattices.metric_tensor(ti_cell["lattice_vectors"].T)
print(f"Correct row-basis lengths = {np.round(mt_correct['lengths_A'], 4)}, angles = {np.round(mt_correct['angles_deg'], 2)}")
print(f"Buggy column-stacked lengths = {np.round(mt_transposed_bug['lengths_A'], 4)}, angles = {np.round(mt_transposed_bug['angles_deg'], 2)}")
assert not np.allclose(mt_correct["lengths_A"], mt_transposed_bug["lengths_A"])
assert not np.allclose(mt_correct["angles_deg"], mt_transposed_bug["angles_deg"])
coplanar = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]])
raised_dep, raised_neg = False, False
try:
lattices.metric_tensor(coplanar)
except ValueError:
raised_dep = True
try:
lattices.cubic_unit_cell("bcc", -2.86)
except ValueError:
raised_neg = True
assert raised_dep and raised_neg
Exercise 2: Diagnostic Audit of Column-Stacked Basis Bug & Coplanar Lattice Guard
=================================================================================
Correct row-basis lengths = [2.9508 2.9508 4.6855], angles = [ 90. 90. 120.]
Buggy column-stacked lengths = [3.2991 2.5555 4.6855], angles = [ 90. 90. 116.57]
Explanation. When is not symmetric, computes dot products of Cartesian coordinate columns across the three vectors rather than dot products of the basis vectors themselves, which gives the wrong lengths and the angle instead of .
Exercise 3¶
Problem. Implement interstitial_void_radius_ratio(structure, void_frac) via supercell nearest-atom distance and verify the 4 metallurgy ratios: FCC octahedral (), FCC tetrahedral (), BCC octahedral (), and BCC tetrahedral ().
heading("Exercise 3: Implement It Yourself — Octahedral & Tetrahedral Interstitial Void Ratios")
def interstitial_void_radius_ratio(structure: str, void_frac: list[float]) -> float:
"""Compute r_void / R_host for an interstitial fractional site in a unit cell."""
cell = lattices.cubic_unit_cell(structure, a_A=1.0)
r_host = 0.5 * lattices.coordination_shells(structure, a_A=1.0, max_shells=1)[0]["radius_A"]
rng = np.arange(-2, 3, dtype=float)
ii, jj, kk = np.meshgrid(rng, rng, rng, indexing="ij")
shifts = np.column_stack([ii.ravel(), jj.ravel(), kk.ravel()]) @ cell["lattice_vectors"]
atoms = (shifts[:, None, :] + cell["cartesian_coords"][None, :, :]).reshape(-1, 3)
void_cart = np.asarray(void_frac, dtype=float) @ cell["lattice_vectors"]
d_min = float(np.min(np.linalg.norm(atoms - void_cart[None, :], axis=1)))
return d_min / r_host - 1.0
cases = [
("FCC Octahedral", "fcc", [0.5, 0.5, 0.5], np.sqrt(2.0) - 1.0),
("FCC Tetrahedral", "fcc", [0.25, 0.25, 0.25], np.sqrt(1.5) - 1.0),
("BCC Octahedral", "bcc", [0.5, 0.5, 0.0], 2.0 / np.sqrt(3.0) - 1.0),
("BCC Tetrahedral", "bcc", [0.5, 0.25, 0.0], np.sqrt(5.0 / 3.0) - 1.0),
]
for name, st, vf, exact in cases:
val = interstitial_void_radius_ratio(st, vf)
print(f"{name:16s} | r_void / R_host = {val:.6f} vs exact = {exact:.6f}")
assert np.isclose(val, exact, rtol=1e-14)
Exercise 3: Implement It Yourself — Octahedral & Tetrahedral Interstitial Void Ratios
=====================================================================================
FCC Octahedral | r_void / R_host = 0.414214 vs exact = 0.414214
FCC Tetrahedral | r_void / R_host = 0.224745 vs exact = 0.224745
BCC Octahedral | r_void / R_host = 0.154701 vs exact = 0.154701
BCC Tetrahedral | r_void / R_host = 0.290994 vs exact = 0.290994
Summary. Even though FCC is more densely packed overall than BCC (0.7405 vs. 0.6802), FCC concentrates its free volume into generous octahedral voids () whereas BCC disperses free volume into cramped octahedral (0.1547) and tetrahedral (0.2910) sites, explaining why FCC austenite dissolves up to carbon while BCC ferrite dissolves barely .