Worked solutions to the three exercises of Lecture 0. 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: CODATA Unit Bridges & Theoretical Crystal Density Benchmarks")
ev_to_kj_mol = constants.EV_TO_J * constants.N_A * 1.0e-3
r_from_kb_na = constants.K_B * constants.N_A
print(f"1 eV/atom = {ev_to_kj_mol:.6f} kJ/mol | k_B * N_A = {r_from_kb_na:.9f} J/(mol*K) vs R = {constants.R:.9f}")
# Representative elements across all 4 crystal classes (FCC Cu, BCC Fe, Diamond Si, HCP Ti):
benchmarks = [
("Cu", "fcc", 4, constants.ELEMENTS_DB["Cu"]["Mw"], constants.ELEMENTS_DB["Cu"]["a_A"] ** 3),
("Fe", "bcc", 2, constants.ELEMENTS_DB["Fe"]["Mw"], constants.ELEMENTS_DB["Fe"]["a_A"] ** 3),
("Si", "diamond", 8, constants.ELEMENTS_DB["Si"]["Mw"], constants.ELEMENTS_DB["Si"]["a_A"] ** 3),
("Ti", "hcp", 2, constants.ELEMENTS_DB["Ti"]["Mw"],
(np.sqrt(3.0) / 2.0) * (constants.ELEMENTS_DB["Ti"]["a_A"] ** 2) * constants.ELEMENTS_DB["Ti"]["c_A"]),
]
print(f"\n{'Elem':4s} | {'Struct':8s} | {'n_cell':>6s} | {'V_cell [A^3]':>12s} | {'rho [g/cm^3]':>12s} | {'Vm [cm^3/mol]':>13s}")
print("-" * 70)
for sym, st, n_at, mw, vol_A3 in benchmarks:
rho = lattices.theoretical_density_g_cm3(mw, n_at, vol_A3)
vm = mw / rho
print(f"{sym:4s} | {st:8s} | {n_at:6d} | {vol_A3:12.4f} | {rho:12.4f} | {vm:13.4f}")
assert np.isclose(r_from_kb_na, constants.R, rtol=1e-10)
assert np.isclose(ev_to_kj_mol, 96.48533212, rtol=1e-8)
assert np.isclose(lattices.theoretical_density_g_cm3(63.546, 4, 3.6149 ** 3), 8.9353, atol=1e-3)
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. For all 14 elements in constants.ELEMENTS_DB, compute and verify to rounding error, identifying the minimum and maximum elements.
heading("Exercise 1: Avogadro Atomic-Volume Closure Across 14 Elements")
omega_map = {}
max_rel_err = 0.0
for sym, meta in constants.ELEMENTS_DB.items():
s = lattices.element_crystal_summary(sym)
omega_A3 = s["volume_A3"] / s["n_atoms_cell"]
vm_lhs = meta["Mw"] / s["density_g_cm3"]
vm_rhs = constants.N_A * omega_A3 * 1.0e-24
rel_err = abs(vm_lhs - vm_rhs) / vm_rhs
max_rel_err = max(max_rel_err, rel_err)
omega_map[sym] = omega_A3
print(f"{sym:9s} | Omega = {omega_A3:7.4f} A^3/atom | Vm = {vm_lhs:7.4f} cm^3/mol | rel_err = {rel_err:.2e}")
min_el = min(omega_map, key=omega_map.get)
max_el = max(omega_map, key=omega_map.get)
print(f"\nMin Omega = {min_el} ({omega_map[min_el]:.4f} A^3/atom), Max Omega = {max_el} ({omega_map[max_el]:.4f} A^3/atom)")
assert max_rel_err < 1e-14
assert min_el == "C-diamond" and max_el == "Mg"
Exercise 1: Avogadro Atomic-Volume Closure Across 14 Elements
=============================================================
Cu | Omega = 11.8094 A^3/atom | Vm = 7.1118 cm^3/mol | rel_err = 0.00e+00
Al | Omega = 16.6014 A^3/atom | Vm = 9.9976 cm^3/mol | rel_err = 0.00e+00
Ni | Omega = 10.9408 A^3/atom | Vm = 6.5887 cm^3/mol | rel_err = 0.00e+00
Au | Omega = 16.9569 A^3/atom | Vm = 10.2117 cm^3/mol | rel_err = 1.74e-16
Ag | Omega = 17.0456 A^3/atom | Vm = 10.2651 cm^3/mol | rel_err = 0.00e+00
Fe | Omega = 11.7768 A^3/atom | Vm = 7.0921 cm^3/mol | rel_err = 1.25e-16
W | Omega = 15.8553 A^3/atom | Vm = 9.5483 cm^3/mol | rel_err = 0.00e+00
Mo | Omega = 15.5833 A^3/atom | Vm = 9.3845 cm^3/mol | rel_err = 0.00e+00
Cr | Omega = 12.3211 A^3/atom | Vm = 7.4199 cm^3/mol | rel_err = 1.20e-16
Si | Omega = 20.0228 A^3/atom | Vm = 12.0580 cm^3/mol | rel_err = 0.00e+00
Ge | Omega = 22.6400 A^3/atom | Vm = 13.6341 cm^3/mol | rel_err = 1.30e-16
C-diamond | Omega = 5.6721 A^3/atom | Vm = 3.4158 cm^3/mol | rel_err = 0.00e+00
Ti | Omega = 17.6659 A^3/atom | Vm = 10.6387 cm^3/mol | rel_err = 1.67e-16
Mg | Omega = 23.2409 A^3/atom | Vm = 13.9960 cm^3/mol | rel_err = 0.00e+00
Min Omega = C-diamond (5.6721 A^3/atom), Max Omega = Mg (23.2409 A^3/atom)
Explanation. Dividing by cancels identically, showing that molar volume depends strictly on per-atom geometric volume . C-diamond () and Mg () bound the database.
Exercise 2¶
Problem. Quantify on FCC Cu the exact error factors from (a) converting with 10-30 instead of and (b) passing with conventional volume , and verify ValueError guards on invalid inputs to lattices.theoretical_density_g_cm3.
heading("Exercise 2: Diagnostic Audit of Unit-Exponent and Basis-Count Bugs")
cu_meta = constants.ELEMENTS_DB["Cu"]
vol_cu = cu_meta["a_A"] ** 3
rho_true = lattices.theoretical_density_g_cm3(cu_meta["Mw"], 4, vol_cu)
rho_m3_bug = (4 * cu_meta["Mw"]) / (constants.N_A * vol_cu * 1.0e-30)
rho_n1_bug = lattices.theoretical_density_g_cm3(cu_meta["Mw"], 1, vol_cu)
print(f"True Cu density = {rho_true:.4f} g/cm^3")
print(f"10^-30 unit-bug density = {rho_m3_bug:.1f} (off by {rho_m3_bug / rho_true:,.0f}x)")
print(f"n_cell=1 basis-bug result = {rho_n1_bug:.4f} g/cm^3 (off by {rho_n1_bug / rho_true:.2f}x)")
assert np.isclose(rho_m3_bug / rho_true, 1.0e6, rtol=1e-14)
assert np.isclose(rho_n1_bug / rho_true, 0.25, rtol=1e-14)
for bad_args in [(0.0, 4, vol_cu), (63.546, 0, vol_cu), (63.546, 4, -1.0)]:
raised = False
try:
lattices.theoretical_density_g_cm3(*bad_args)
except ValueError:
raised = True
assert raised, f"Expected ValueError for {bad_args}"
Exercise 2: Diagnostic Audit of Unit-Exponent and Basis-Count Bugs
==================================================================
True Cu density = 8.9353 g/cm^3
10^-30 unit-bug density = 8935285.7 (off by 1,000,000x)
n_cell=1 basis-bug result = 2.2338 g/cm^3 (off by 0.25x)
Explanation. Using without converting inflates by (it actually computes ), while pairing the 1-atom primitive count with the 4-atom conventional cube underpredicts by an exact factor of 4 ().
Exercise 3¶
Problem. Implement allotropic_density_shift(symbol, target_structure) assuming constant nearest-neighbor bond length , and verify on Fe (bcc fcc) that volume contracts by .
heading("Exercise 3: Implement It Yourself — Allotropic BCC -> FCC Volume Contraction in Iron")
def allotropic_density_shift(symbol: str, target_structure: str) -> dict:
"""Predict lattice constant, density, and volume change at fixed nearest-neighbor bond length d_nn."""
orig = lattices.element_crystal_summary(symbol)
mw = constants.ELEMENTS_DB[symbol]["Mw"]
d_nn = orig["d_nn_A"]
unit_d_nn = lattices.coordination_shells(target_structure, a_A=1.0, max_shells=1)[0]["radius_A"]
a_new = d_nn / unit_d_nn
cell_new = lattices.build_unit_cell(target_structure, a_A=a_new)
vol_new = lattices.metric_tensor(cell_new["lattice_vectors"])["volume_A3"]
rho_new = lattices.theoretical_density_g_cm3(mw, cell_new["n_atoms"], vol_new)
omega_orig = orig["volume_A3"] / orig["n_atoms_cell"]
omega_new = vol_new / cell_new["n_atoms"]
return {
"a_new_A": a_new,
"rho_orig_g_cm3": orig["density_g_cm3"],
"rho_new_g_cm3": rho_new,
"volume_change_pct": 100.0 * (omega_new - omega_orig) / omega_orig,
}
fe_shift = allotropic_density_shift("Fe", "fcc")
exact_vol_pct = 100.0 * (lattices.atomic_packing_fraction("bcc") / lattices.atomic_packing_fraction("fcc") - 1.0)
print(f"Predicted gamma-Fe FCC a = {fe_shift['a_new_A']:.4f} A (d_nn conserved)")
print(f"alpha-Fe rho = {fe_shift['rho_orig_g_cm3']:.4f} g/cm^3 -> gamma-Fe rho = {fe_shift['rho_new_g_cm3']:.4f} g/cm^3")
print(f"Atomic volume change = {fe_shift['volume_change_pct']:.4f}% vs exact APF ratio = {exact_vol_pct:.4f}%")
assert np.isclose(fe_shift["volume_change_pct"], exact_vol_pct, rtol=1e-13)
assert np.isclose(fe_shift["volume_change_pct"], -8.144, atol=1e-2)
Exercise 3: Implement It Yourself — Allotropic BCC -> FCC Volume Contraction in Iron
====================================================================================
Predicted gamma-Fe FCC a = 3.5107 A (d_nn conserved)
alpha-Fe rho = 7.8742 g/cm^3 -> gamma-Fe rho = 8.5724 g/cm^3
Atomic volume change = -8.1441% vs exact APF ratio = -8.1441%
Summary. Repacking hard spheres of fixed atomic radius from BCC () into close-packed FCC () shrinks atomic volume by , the fundamental crystallographic origin of transformation strains during steel heat treatment (in real iron the measured contraction at is only about , because the atomic diameter is not the same in the two structures).