Why does aluminum deform ductily on twelve close-packed slip systems while silicon cleaves brittlely along tetrahedral bonds, and why do titanium and magnesium require non-orthogonal basis vectors? Every geometric property of a crystal, bond lengths, interaxial angles, unit-cell volumes, neighbor coordination shells, and sphere packing fractions, is encoded in a lattice matrix and its covariant metric tensor . In this lecture, we build cubic and hexagonal close-packed unit cells, show metric rotational invariance, and verify Kepler’s close-packing limit.
Learning objectives¶
Construct
sc,bcc,fcc,diamond, andhcpunit cells (lattices.cubic_unit_cell,lattices.hcp_unit_cell) and map fractional to Cartesian coordinates .Evaluate the covariant metric tensor , cell volume , and interaxial angles via
lattices.metric_tensor.Enumerate neighbor coordination shells (
lattices.coordination_shells) and verify exact hard-sphere APFs (lattices.atomic_packing_fraction).Analyze how non-ideal HCP axial ratios in Ti and Mg split the first coordination shell into basal and pyramidal bonds.
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 Direct Lattice Basis & Fractional Coordinates¶
Stacking the three primitive or conventional basis vectors as rows of , any basis atom with fractional coordinates sits at Cartesian position:
For the 2-atom primitive hexagonal close-packed (HCP) lattice with basal constant and height , lattices.hcp_unit_cell uses , , with basis and . Hard spheres touching both in the basal plane () and between ABAB planes require the ideal axial ratio:
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"]
Demonstration 1: Cubic & Hexagonal Unit-Cell Construction and Ideal vs Real HCP c/a
===================================================================================
Cubic sc | n_atoms = 1 | basis[0..1] frac = [[0.0, 0.0, 0.0]]
Cubic bcc | n_atoms = 2 | basis[0..1] frac = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]]
Cubic fcc | n_atoms = 4 | basis[0..1] frac = [[0.0, 0.0, 0.0], [0.0, 0.5, 0.5]]
Cubic diamond | n_atoms = 8 | basis[0..1] frac = [[0.0, 0.0, 0.0], [0.0, 0.5, 0.5]]
Ideal HCP c/a = 1.632993 (sqrt(8/3) = 1.632993)
Ti HCP c/a = 1.587874 (deviation = -2.76%)
Mg HCP c/a = 1.623606 (deviation = -0.57%)
What Demonstration 1 shows. Magnesium (, from ideal) behaves almost like an ideal hard-sphere close-packed crystal, whereas titanium (, axial compression) is noticeably compressed along due to directional -electron metallic bonding, activating prismatic slip in -Ti.
2. Covariant Metric Tensor , Cell Volume & Rotational Invariance¶
In any curvilinear or non-orthogonal crystal frame, dot products and squared bond lengths between fractional displacements are governed by the covariant metric tensor:
Crucially, rotating a crystal in 3-D space by any proper orthogonal matrix () leaves strictly invariant.
heading("Demonstration 2: Metric Tensor Geometry of HCP Ti & Exact SO(3) Rotational Invariance")
mt_ti = lattices.metric_tensor(hcp_ti["lattice_vectors"])
print("Ti covariant metric tensor G [A^2]:\n", np.round(mt_ti["G"], 5))
print(f"Lengths [A] = {np.round(mt_ti['lengths_A'], 5)}")
print(f"Angles [deg] = {np.round(mt_ti['angles_deg'], 4)} (expected: [90, 90, 120])")
print(f"Volume [A^3] = {mt_ti['volume_A3']:.6f} vs (sqrt(3)/2)*a^2*c = {(np.sqrt(3.0)/2.0)*(ti_meta['a_A']**2)*ti_meta['c_A']:.6f}")
# Construct an exact SO(3) rotation via QR decomposition and verify G invariance:
rng = np.random.default_rng(42)
q_rot, _ = np.linalg.qr(rng.normal(size=(3, 3)))
if np.linalg.det(q_rot) < 0:
q_rot[:, 0] *= -1.0
mt_rot = lattices.metric_tensor(hcp_ti["lattice_vectors"] @ q_rot)
print(f"Max ||G_rotated - G||_inf under arbitrary 3-D rotation = {np.max(np.abs(mt_rot['G'] - mt_ti['G'])):.2e}")
assert np.allclose(mt_ti["angles_deg"], [90.0, 90.0, 120.0], atol=1e-12)
assert np.isclose(mt_ti["volume_A3"], (np.sqrt(3.0) / 2.0) * (ti_meta["a_A"] ** 2) * ti_meta["c_A"], rtol=1e-14)
assert np.allclose(mt_rot["G"], mt_ti["G"], atol=1e-13)
Demonstration 2: Metric Tensor Geometry of HCP Ti & Exact SO(3) Rotational Invariance
=====================================================================================
Ti covariant metric tensor G [A^2]:
[[ 8.70722 -4.35361 0. ]
[-4.35361 8.70722 0. ]
[ 0. 0. 21.95391]]
Lengths [A] = [2.9508 2.9508 4.6855]
Angles [deg] = [ 90. 90. 120.] (expected: [90, 90, 120])
Volume [A^3] = 35.331829 vs (sqrt(3)/2)*a^2*c = 35.331829
Max ||G_rotated - G||_inf under arbitrary 3-D rotation = 3.55e-15
What Demonstration 2 shows. The off-diagonal metric entry , encoding . Even after an arbitrary 3-D rigid rotation , every component of , all cell angles, and remain identical to 10-15.
3. Coordination Shells & Hard-Sphere Atomic Packing Fractions¶
If identical hard spheres of radius sit on every basis site and touch along nearest-neighbor bonds, the atomic packing fraction (APF) is:
heading("Demonstration 3: Coordination Shells (Z1, Z2, Z3) & Kepler Sphere-Packing Verification")
exact_apfs = {
"sc": np.pi / 6.0,
"bcc": np.sqrt(3.0) * np.pi / 8.0,
"fcc": np.sqrt(2.0) * np.pi / 6.0,
"hcp": np.sqrt(2.0) * np.pi / 6.0,
"diamond": np.sqrt(3.0) * np.pi / 16.0,
}
structs = ["diamond", "sc", "bcc", "fcc", "hcp"]
apf_computed = []
z1_list = []
print(f"{'Structure':9s} | {'Z1 (r1/a)':>16s} | {'Z2 (r2/a)':>16s} | {'Z3 (r3/a)':>16s} | {'APF_num':>8s} | {'APF_exact':>9s}")
print("-" * 88)
for st in structs:
sh = lattices.coordination_shells(st, a_A=1.0, max_shells=3)
apf_val = lattices.atomic_packing_fraction(st)
apf_computed.append(apf_val)
z1_list.append(sh[0]["coordination_number"])
assert np.isclose(apf_val, exact_apfs[st], rtol=1e-13)
print(
f"{st:9s} | {sh[0]['coordination_number']:2d} ({sh[0]['r_over_a']:.4f}) | "
f"{sh[1]['coordination_number']:2d} ({sh[1]['r_over_a']:.4f}) | "
f"{sh[2]['coordination_number']:2d} ({sh[2]['r_over_a']:.4f}) | "
f"{apf_val:8.5f} | {exact_apfs[st]:9.5f}"
)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 4.0))
colors = ["#2ca02c", "#7f7f7f", "#d62728", "#1f77b4", "#9467bd"]
ax1.bar([s.upper() for s in structs], apf_computed, color=colors, width=0.55)
ax1.axhline(np.sqrt(2.0) * np.pi / 6.0, color="k", ls="--", lw=1.1, label="Kepler Limit $\\sqrt{2}\\pi/6 \\approx 0.7405$")
ax1.set_ylabel("Atomic Packing Fraction (APF) [-]")
ax1.set_title("Hard-Sphere Packing Across Crystal Classes")
ax1.set_ylim(0, 0.85)
ax1.legend(frameon=False, fontsize=8.5)
for st, col in zip(["bcc", "fcc", "diamond"], ["#d62728", "#1f77b4", "#2ca02c"]):
sh = lattices.coordination_shells(st, a_A=1.0, max_shells=3)
ax2.stem([x["r_over_a"] for x in sh], [x["coordination_number"] for x in sh],
linefmt=col, markerfmt="o", basefmt=" ", label=st.upper())
ax2.set_xlabel("Normalized Shell Radius $r_s / a$ [-]")
ax2.set_ylabel("Shell Coordination Number $Z_s$ [-]")
ax2.set_title("Radial Neighbor Shells ($a = 1$)")
ax2.legend(frameon=False)
label_panels(fig)
plt.show()
assert z1_list == [4, 6, 8, 12, 12]
Demonstration 3: Coordination Shells (Z1, Z2, Z3) & Kepler Sphere-Packing Verification
======================================================================================
Structure | Z1 (r1/a) | Z2 (r2/a) | Z3 (r3/a) | APF_num | APF_exact
----------------------------------------------------------------------------------------
diamond | 4 (0.4330) | 12 (0.7071) | 12 (0.8292) | 0.34009 | 0.34009
sc | 6 (1.0000) | 12 (1.4142) | 8 (1.7321) | 0.52360 | 0.52360
bcc | 8 (0.8660) | 6 (1.0000) | 12 (1.4142) | 0.68017 | 0.68017
fcc | 12 (0.7071) | 6 (1.0000) | 24 (1.2247) | 0.74048 | 0.74048
hcp | 12 (1.0000) | 6 (1.4142) | 2 (1.6330) | 0.74048 | 0.74048

Figure 1.1. (a) Packing fraction of hard spheres in five structures; the dashed line is the close-packing value . (b) Number of neighbours in the first three shells of BCC, FCC and diamond against the shell radius in units of .
What Demonstration 3 shows. In BCC the first two neighbor shells are close together, which is why interatomic potentials for BCC metals must treat both: in BCC, the 8 first neighbors at and 6 second neighbors at are separated by only in distance, whereas in FCC (, ) the second shell sits farther away.
4. Sensitivity: Splitting the HCP Shell When ¶
In an HCP crystal, every atom has 6 in-plane basal neighbors at and 6 out-of-plane pyramidal neighbors (3 above, 3 below) at . Only at do these coincide (). We sweep and observe the shell splitting.
heading("Demonstration 4: HCP Shell Splitting Across c/a Sweep (Ti, Mg, Ideal, Zn-like)")
ca_grid = np.linspace(1.50, 1.88, 150)
d_basal_over_a = np.ones_like(ca_grid)
d_pyr_over_a = np.sqrt(1.0 / 3.0 + 0.25 * (ca_grid ** 2))
fig, ax = plt.subplots(figsize=(7.5, 4.2))
ax.plot(ca_grid, d_basal_over_a, lw=2.2, color="#1f77b4", label="6 Basal Neighbors ($d_{\\mathrm{basal}}/a = 1$)")
ax.plot(ca_grid, d_pyr_over_a, lw=2.2, color="#d62728", ls="--", label="6 Out-of-Plane Neighbors ($\\sqrt{1/3 + c^2/(4a^2)}$)")
for label, ca_val, col in [("Ti (1.588)", hcp_ti["c_over_a"], "#2ca02c"),
("Mg (1.624)", hcp_mg["c_over_a"], "#ff7f0e"),
("Ideal (1.633)", np.sqrt(8.0 / 3.0), "k"),
("Zn (1.856)", 1.856, "#9467bd")]:
ax.axvline(ca_val, color=col, ls=":", lw=1.3, label=label)
ax.set_xlabel("HCP Axial Ratio $c / a$ [-]")
ax.set_ylabel("Normalized Bond Distance $d / a$ [-]")
ax.set_title("Degeneracy Lifting of the 12-Fold HCP Shell Away from $c/a = \\sqrt{8/3}$")
ax.legend(frameon=False, fontsize=8.5)
plt.show()
sh_ti = lattices.coordination_shells("hcp", a_A=1.0, max_shells=2, c_A=hcp_ti["c_over_a"])
sh_zn = lattices.coordination_shells("hcp", a_A=1.0, max_shells=2, c_A=1.856)
print(f"Ti (c/a < ideal): Shell 1 has Z1={sh_ti[0]['coordination_number']} at r/a={sh_ti[0]['r_over_a']:.4f} (pyramidal), Shell 2 has Z2={sh_ti[1]['coordination_number']} at r/a={sh_ti[1]['r_over_a']:.4f} (basal)")
print(f"Zn (c/a > ideal): Shell 1 has Z1={sh_zn[0]['coordination_number']} at r/a={sh_zn[0]['r_over_a']:.4f} (basal), Shell 2 has Z2={sh_zn[1]['coordination_number']} at r/a={sh_zn[1]['r_over_a']:.4f} (pyramidal)")
assert sh_ti[0]["coordination_number"] == 6 and np.isclose(sh_ti[0]["r_over_a"], np.sqrt(1.0 / 3.0 + 0.25 * hcp_ti["c_over_a"] ** 2))
assert sh_zn[0]["coordination_number"] == 6 and np.isclose(sh_zn[0]["r_over_a"], 1.0)
Demonstration 4: HCP Shell Splitting Across c/a Sweep (Ti, Mg, Ideal, Zn-like)
==============================================================================

Ti (c/a < ideal): Shell 1 has Z1=6 at r/a=0.9817 (pyramidal), Shell 2 has Z2=6 at r/a=1.0000 (basal)
Zn (c/a > ideal): Shell 1 has Z1=6 at r/a=1.0000 (basal), Shell 2 has Z2=6 at r/a=1.0929 (pyramidal)
Figure 1.2. Distances to the six in-plane and the six out-of-plane neighbours of an HCP atom against the axial ratio . The two are equal only at the ideal ratio ; the vertical lines mark Ti, Mg, the ideal ratio and a ratio typical of Zn.
Inside the algorithm¶
When (Ti), the 6 out-of-plane bonds become shorter than , whereas for (Zn), the 6 basal bonds are shortest. Below we inspect lattices.metric_tensor and lattices.atomic_packing_fraction and verify a NumPy supercell shell counter.
Check against the library¶
heading("Inside the Algorithm: NumPy Supercell Shell Counter vs lattices.coordination_shells")
print(show_source(lattices.atomic_packing_fraction))
cell_fcc = lattices.cubic_unit_cell("fcc", a_A=3.6149)
rng_sc = np.arange(-3, 4, dtype=float)
ii, jj, kk = np.meshgrid(rng_sc, rng_sc, rng_sc, indexing="ij")
shifts = np.column_stack([ii.ravel(), jj.ravel(), kk.ravel()]) @ cell_fcc["lattice_vectors"]
cloud = (shifts[:, None, :] + cell_fcc["cartesian_coords"][None, :, :]).reshape(-1, 3)
dists = np.sort(np.linalg.norm(cloud - cell_fcc["cartesian_coords"][0], axis=1))
dists = dists[dists > 1e-8]
unique_r, counts = np.unique(np.round(dists, 8), return_counts=True)
lib_shells = lattices.coordination_shells("fcc", a_A=3.6149, max_shells=3)
for idx_s, sh in enumerate(lib_shells):
print(f"Shell {idx_s+1}: NumPy (r={unique_r[idx_s]:.5f} A, Z={counts[idx_s]:2d}) vs library (r={sh['radius_A']:.5f} A, Z={sh['coordination_number']:2d})")
assert np.isclose(unique_r[idx_s], sh["radius_A"], rtol=1e-10)
assert int(counts[idx_s]) == sh["coordination_number"]
Inside the Algorithm: NumPy Supercell Shell Counter vs lattices.coordination_shells
===================================================================================
def atomic_packing_fraction(structure: str) -> float:
"""Compute hard-sphere atomic packing fraction (APF) directly from unit-cell volume and nearest-neighbor contact."""
cell = build_unit_cell(structure, a_A=1.0, c_A=None)
vol = metric_tensor(cell["lattice_vectors"])["volume_A3"]
d_nn = coordination_shells(structure, a_A=1.0, max_shells=1)[0]["radius_A"]
r_sphere = 0.5 * d_nn
sphere_vol = (4.0 / 3.0) * np.pi * (r_sphere**3)
return float(cell["n_atoms"] * sphere_vol / vol)
Shell 1: NumPy (r=2.55612 A, Z=12) vs library (r=2.55612 A, Z=12)
Shell 2: NumPy (r=3.61490 A, Z= 6) vs library (r=3.61490 A, Z= 6)
Shell 3: NumPy (r=4.42733 A, Z=24) vs library (r=4.42733 A, Z=24)
Exercises¶
Worked solutions are in 01_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify for
TiandMgHCP cells that with matcheselement_crystal_summary(sym)['d_nn_A']and to rounding error.Find how it fails. Demonstrate how transposing non-orthogonal HCP
Tibasis vectors (A.Tinstead ofA) corruptsmetric_tensorlengths and angles, and verifyValueErrorguards on coplanar lattice vectors and negative lattice constants.Implement it yourself. 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("Self-check for the exercises")
df_hcp = 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"])
G_mat = lattices.metric_tensor(cell["lattice_vectors"])["G"]
d_metric = float(np.sqrt(df_hcp @ G_mat @ df_hcp))
d_summary = lattices.element_crystal_summary(sym)["d_nn_A"]
print(f"{sym}: sqrt(df @ G @ df) = {d_metric:.6f} A vs summary d_nn = {d_summary:.6f} A")
assert np.isclose(d_metric, d_summary, rtol=1e-14)
print("All checks passed.")
Self-check for the exercises
============================
Ti: sqrt(df @ G @ df) = 2.896702 A vs summary d_nn = 2.896702 A
Mg: sqrt(df @ G @ df) = 3.197112 A vs summary d_nn = 3.197112 A
All checks passed.