Materials science bridges twelve orders of magnitude, from X-ray lattice spacings measured in Ångströms () and bond energies in electron-volts () to continuum structural densities in and elastic moduli in . A single misplaced power-of-ten when converting to (10-24) versus (10-30) corrupts predicted alloy densities by a factor of a million. In this opening lecture, we establish strict atomic-to-continuum unit discipline, audit the 14-element crystallographic benchmark database constants.ELEMENTS_DB, and predict macroscopic X-ray crystal densities directly from unit-cell geometry.
Learning objectives¶
Convert between atomic and continuum units (, , and ) with explicit unit-suffixed Python variables.
Query and classify all 14 crystalline elements in
constants.ELEMENTS_DBacross FCC, BCC, Diamond, and HCP crystal classes.Compute theoretical X-ray crystal densities and molar volumes using
lattices.theoretical_density_g_cm3andlattices.element_crystal_summary.Visualize periodic trends of crystal density and molar volume versus atomic number , and quantify thermal-expansion sensitivity.
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 Atomic-to-Continuum Unit Conversions¶
Crystallographic unit cells are naturally measured in Ångströms (), while atomistic defect and cohesive energies are reported in electron-volts (). Bridging to macroscopic continuum thermodynamics requires three identities between constants whose values are fixed by the 2019 definition of the SI:
1.2 Theoretical X-Ray Crystal Density & Molar Volume¶
Given a crystal unit cell of volume containing basis atoms of molar mass , the theoretical X-ray density and molar volume are:
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)
Demonstration 1: CODATA Unit Bridges & Theoretical Crystal Density Benchmarks
=============================================================================
1 eV/atom = 96.485332 kJ/mol | k_B * N_A = 8.314462618 J/(mol*K) vs R = 8.314462618
Elem | Struct | n_cell | V_cell [A^3] | rho [g/cm^3] | Vm [cm^3/mol]
----------------------------------------------------------------------
Cu | fcc | 4 | 47.2377 | 8.9353 | 7.1118
Fe | bcc | 2 | 23.5535 | 7.8742 | 7.0921
Si | diamond | 8 | 160.1826 | 2.3292 | 12.0580
Ti | hcp | 2 | 35.3318 | 4.4993 | 10.6387
What Demonstration 1 shows. Converting yields (about at , which is why a vacancy formation energy near keeps the equilibrium vacancy fraction very small at room temperature). From lattice constants alone, Equation (1.4) predicts , , , and . These follow from the lattice constants and molar masses stored in ELEMENTS_DB alone; measured densities of real samples differ slightly because of vacancies, impurities and porosity.
2. Auditing ELEMENTS_DB & element_crystal_summary¶
constants.ELEMENTS_DB curates 14 benchmark crystalline elements spanning four Bravais/basis crystal classes:
FCC (, ):
Cu,Al,Ni,Au,AgBCC (, ):
Fe,W,Mo,CrDiamond cubic (, ):
Si,Ge,C-diamondHCP (, ):
Ti,Mg
Calling lattices.element_crystal_summary(symbol) builds the unit cell, evaluates its metric-tensor volume , finds the nearest-neighbor bond distance , and computes and ideal hard-sphere packing fraction.
heading("Demonstration 2: Complete 14-Element Crystallographic Audit of ELEMENTS_DB")
print(f"{'Sym':9s} | {'Z':>3s} | {'Struct':7s} | {'n':>2s} | {'V_cell [A^3]':>12s} | {'d_nn [A]':>8s} | {'Z1':>3s} | {'APF*':>6s} | {'rho [g/cm^3]':>12s}")
print("-" * 82)
summaries = {}
struct_counts = {}
for sym, meta in constants.ELEMENTS_DB.items():
s = lattices.element_crystal_summary(sym)
summaries[sym] = s
struct_counts[s["structure"]] = struct_counts.get(s["structure"], 0) + 1
print(
f"{sym:9s} | {meta['Z']:3d} | {s['structure']:7s} | {s['n_atoms_cell']:2d} | "
f"{s['volume_A3']:12.4f} | {s['d_nn_A']:8.4f} | {s['coordination_number']:3d} | "
f"{s['ideal_apf']:6.4f} | {s['density_g_cm3']:12.4f}"
)
print("\nElement counts by crystal class:", struct_counts)
assert len(constants.ELEMENTS_DB) == 14
assert struct_counts == {"fcc": 5, "bcc": 4, "diamond": 3, "hcp": 2}
assert summaries["Au"]["density_g_cm3"] > 19.2 and summaries["W"]["density_g_cm3"] > 19.2
assert summaries["Mg"]["density_g_cm3"] < 1.75
Demonstration 2: Complete 14-Element Crystallographic Audit of ELEMENTS_DB
==========================================================================
Sym | Z | Struct | n | V_cell [A^3] | d_nn [A] | Z1 | APF* | rho [g/cm^3]
----------------------------------------------------------------------------------
Cu | 29 | fcc | 4 | 47.2377 | 2.5561 | 12 | 0.7405 | 8.9353
Al | 13 | fcc | 4 | 66.4055 | 2.8634 | 12 | 0.7405 | 2.6988
Ni | 28 | fcc | 4 | 43.7631 | 2.4918 | 12 | 0.7405 | 8.9082
Au | 79 | fcc | 4 | 67.8275 | 2.8837 | 12 | 0.7405 | 19.2884
Ag | 47 | fcc | 4 | 68.1823 | 2.8887 | 12 | 0.7405 | 10.5083
Fe | 26 | bcc | 2 | 23.5535 | 2.4825 | 8 | 0.6802 | 7.8742
W | 74 | bcc | 2 | 31.7105 | 2.7411 | 8 | 0.6802 | 19.2538
Mo | 42 | bcc | 2 | 31.1667 | 2.7254 | 8 | 0.6802 | 10.2243
Cr | 24 | bcc | 2 | 24.6422 | 2.5201 | 8 | 0.6802 | 7.0076
Si | 14 | diamond | 8 | 160.1826 | 2.3516 | 4 | 0.3401 | 2.3292
Ge | 32 | diamond | 8 | 181.1197 | 2.4499 | 4 | 0.3401 | 5.3271
C-diamond | 6 | diamond | 8 | 45.3771 | 1.5445 | 4 | 0.3401 | 3.5163
Ti | 22 | hcp | 2 | 35.3318 | 2.8967 | 6 | 0.7405 | 4.4993
Mg | 12 | hcp | 2 | 46.4818 | 3.1971 | 6 | 0.7405 | 1.7366
Element counts by crystal class: {'fcc': 5, 'bcc': 4, 'diamond': 3, 'hcp': 2}
What Demonstration 2 shows. Tungsten (W, BCC, , ) and gold (Au, FCC, , ) have nearly the same density: gold packs spheres more densely ( vs. 0.6802) and has slightly higher , whereas tungsten compensates with a shorter metallic bond ( vs. ). Also, non-ideal HCP Ti and Mg show in element_crystal_summary because slightly splits their 12 ideal neighbors into 6 closer out-of-plane bonds and 6 basal bonds, which Lecture 1 examines. The column APF* is the packing fraction of the ideal structure (ideal for HCP), not of the real cell.
3. Molar Volume Scaling & Density vs. Atomic Number ¶
While mass density generally rises with atomic number due to heavier nuclei, the molar volume (where is the per-atom volume) reflects directional bonding and valence-shell contraction (Lothar Meyer’s atomic-volume curve). We plot both and across all 14 elements.
heading("Demonstration 3: Visualizing Crystal Density and Molar Volume vs Atomic Number Z")
palette = {"fcc": "#1f77b4", "bcc": "#d62728", "diamond": "#2ca02c", "hcp": "#9467bd"}
markers = {"fcc": "o", "bcc": "s", "diamond": "D", "hcp": "^"}
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.3))
for st in ["fcc", "bcc", "diamond", "hcp"]:
syms = [k for k, v in constants.ELEMENTS_DB.items() if v["structure"] == st]
z_vals = [constants.ELEMENTS_DB[k]["Z"] for k in syms]
rhos = [summaries[k]["density_g_cm3"] for k in syms]
vms = [constants.ELEMENTS_DB[k]["Mw"] / summaries[k]["density_g_cm3"] for k in syms]
ax1.scatter(z_vals, rhos, c=palette[st], marker=markers[st], s=65, label=st.upper(), zorder=3)
ax2.scatter(z_vals, vms, c=palette[st], marker=markers[st], s=65, label=st.upper(), zorder=3)
for k, zv, rv, vmv in zip(syms, z_vals, rhos, vms):
ax1.annotate(k, (zv, rv), xytext={"Ni": (-14, 4), "Cu": (5, 4), "Cr": (3, -11), "Al": (-12, 5), "Si": (6, -2), "Mg": (5, -11)}.get(k, (4, 3)), textcoords="offset points", fontsize=8)
ax2.annotate(k, (zv, vmv), xytext={"Cr": (-6, 6), "Fe": (-6, -13), "Cu": (5, 3), "Ni": (5, -11)}.get(k, (4, 3)), textcoords="offset points", fontsize=8)
ax1.set_xlabel("Atomic Number $Z$ [-]")
ax1.set_ylabel("Theoretical Density $\\rho$ [g/cm$^3$]")
ax1.set_title("X-Ray Crystal Density vs. $Z$")
ax1.legend(frameon=False)
ax2.set_xlabel("Atomic Number $Z$ [-]")
ax2.set_ylabel("Molar Volume $V_m$ [cm$^3$/mol]")
ax2.set_title("Crystalline Molar Volume vs. $Z$")
ax2.legend(frameon=False)
label_panels(fig)
plt.show()
vm_cdiam = constants.ELEMENTS_DB["C-diamond"]["Mw"] / summaries["C-diamond"]["density_g_cm3"]
vm_si = constants.ELEMENTS_DB["Si"]["Mw"] / summaries["Si"]["density_g_cm3"]
print(f"C-diamond Vm = {vm_cdiam:.4f} cm^3/mol (rho = {summaries['C-diamond']['density_g_cm3']:.4f} g/cm^3) vs Si Vm = {vm_si:.4f} cm^3/mol")
assert vm_cdiam < 3.5 and vm_si > 12.0
Demonstration 3: Visualizing Crystal Density and Molar Volume vs Atomic Number Z
================================================================================

C-diamond Vm = 3.4158 cm^3/mol (rho = 3.5163 g/cm^3) vs Si Vm = 12.0580 cm^3/mol
Figure 0.1. The 14 elements of ELEMENTS_DB. (a) Density computed from the unit cell against atomic number. (b) Molar volume against atomic number. The symbols mark the crystal structure.
What Demonstration 3 shows. Despite sharing the open tetrahedral diamond structure (), C-diamond exhibits the smallest molar volume in the entire database (, ) due to short covalent bonds, giving , over denser than Si () even though silicon atoms are heavier.
4. Sensitivity to the parameters¶
How sensitive is X-ray crystal density to isotropic thermal expansion when heating copper (assumed constant ) from to ()? We compare exact cubic volume dilation against the linearized continuum approximation , and verify defensive input guards.
heading("Demonstration 4: Thermal Expansion Sensitivity of Cu Density & Defensive Guards")
a0_cu = constants.ELEMENTS_DB["Cu"]["a_A"]
mw_cu = constants.ELEMENTS_DB["Cu"]["Mw"]
alpha_cu = 16.5e-6 # [1/K]
dT_grid = np.array([0.0, 250.0, 500.0, 750.0, 1000.0])
rho_0 = lattices.theoretical_density_g_cm3(mw_cu, 4, a0_cu ** 3)
print(f"{'dT [K]':>8s} | {'a(T) [A]':>10s} | {'rho_exact [g/cm^3]':>18s} | {'rho_linear [g/cm^3]':>19s} | {'Drop [%]':>9s}")
print("-" * 76)
for dT in dT_grid:
a_T = a0_cu * (1.0 + alpha_cu * dT)
rho_ex = lattices.theoretical_density_g_cm3(mw_cu, 4, a_T ** 3)
rho_lin = rho_0 * (1.0 - 3.0 * alpha_cu * dT)
drop_pct = 100.0 * (rho_0 - rho_ex) / rho_0
print(f"{dT:8.1f} | {a_T:10.5f} | {rho_ex:18.5f} | {rho_lin:19.5f} | {drop_pct:9.3f}")
# Verify defensive guards on non-positive inputs and unknown element symbols:
caught_val, caught_key = False, False
try:
lattices.theoretical_density_g_cm3(mw_cu, 4, -10.0)
except ValueError:
caught_val = True
try:
lattices.element_crystal_summary("Unobtainium")
except KeyError:
caught_key = True
assert caught_val and caught_key
assert np.isclose(lattices.theoretical_density_g_cm3(mw_cu, 4, (a0_cu * (1.0 + alpha_cu * 1000.0)) ** 3),
rho_0 / ((1.0 + alpha_cu * 1000.0) ** 3), rtol=1e-14)
Demonstration 4: Thermal Expansion Sensitivity of Cu Density & Defensive Guards
===============================================================================
dT [K] | a(T) [A] | rho_exact [g/cm^3] | rho_linear [g/cm^3] | Drop [%]
----------------------------------------------------------------------------
0.0 | 3.61490 | 8.93529 | 8.93529 | 0.000
250.0 | 3.62981 | 8.82562 | 8.82471 | 1.227
500.0 | 3.64472 | 8.71774 | 8.71414 | 2.435
750.0 | 3.65963 | 8.61161 | 8.60356 | 3.622
1000.0 | 3.67455 | 8.50719 | 8.49299 | 4.791
dT_line = np.linspace(0.0, 1000.0, 101)
rho_exact_line = rho_0 / (1.0 + alpha_cu * dT_line) ** 3
rho_lin_line = rho_0 * (1.0 - 3.0 * alpha_cu * dT_line)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.6, 3.8))
ax1.plot(dT_line, rho_exact_line, "-", label=r"$\rho_0(1+\alpha_L\Delta T)^{-3}$")
ax1.plot(dT_line, rho_lin_line, "--", label=r"$\rho_0(1-3\alpha_L\Delta T)$")
ax1.set_xlabel(r"temperature rise $\Delta T$ [K]"); ax1.set_ylabel(r"density of Cu [g/cm$^3$]"); ax1.legend()
ax2.plot(dT_line, 1000.0 * (rho_exact_line - rho_lin_line), "-")
ax2.set_xlabel(r"temperature rise $\Delta T$ [K]"); ax2.set_ylabel(r"difference [mg/cm$^3$]")
label_panels(fig)
plt.show()
Figure 0.2. Density of copper against temperature rise for an assumed constant expansion coefficient. (a) The cubic law and its linearization. (b) Their difference, which grows as .
Inside the algorithm¶
Heating copper by expands by and lowers its theoretical density by (), with the linearized rule agreeing within . Below we inspect lattices.theoretical_density_g_cm3 and verify a NumPy implementation across all 14 elements in ELEMENTS_DB.
Check against the library¶
heading("Inside the Algorithm: NumPy vs lattices.theoretical_density_g_cm3")
print(show_source(lattices.theoretical_density_g_cm3))
syms = list(constants.ELEMENTS_DB.keys())
n_map = {"sc": 1, "bcc": 2, "fcc": 4, "diamond": 8, "hcp": 2}
mw_vec = np.array([constants.ELEMENTS_DB[s]["Mw"] for s in syms])
n_vec = np.array([n_map[constants.ELEMENTS_DB[s]["structure"]] for s in syms])
vol_vec = np.array([
(np.sqrt(3.0) / 2.0) * (constants.ELEMENTS_DB[s]["a_A"] ** 2) * constants.ELEMENTS_DB[s]["c_A"]
if constants.ELEMENTS_DB[s]["structure"] == "hcp"
else constants.ELEMENTS_DB[s]["a_A"] ** 3
for s in syms
])
rho_numpy = (n_vec * mw_vec) / (constants.N_A * vol_vec * 1.0e-24)
rho_lib = np.array([lattices.element_crystal_summary(s)["density_g_cm3"] for s in syms])
max_err = float(np.max(np.abs(rho_numpy - rho_lib)))
print(f"Max discrepancy across all 14 ELEMENTS_DB entries = {max_err:.2e} g/cm^3")
assert np.allclose(rho_numpy, rho_lib, rtol=1e-14, atol=1e-14)
Inside the Algorithm: NumPy vs lattices.theoretical_density_g_cm3
=================================================================
def theoretical_density_g_cm3(Mw: float, n_atoms: int, volume_A3: float) -> float:
"""Compute theoretical crystal density [g/cm^3] from molar mass Mw [g/mol], cell atoms, and cell volume [A^3]."""
if volume_A3 <= 0.0 or Mw <= 0.0 or n_atoms <= 0:
raise ValueError("Mw, n_atoms, and volume_A3 must be strictly positive.")
volume_cm3 = float(volume_A3) * 1.0e-24
return float((n_atoms * Mw) / (N_A * volume_cm3))
Max discrepancy across all 14 ELEMENTS_DB entries = 3.55e-15 g/cm^3
Exercises¶
Worked solutions are in 00_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. For all 14 elements in
constants.ELEMENTS_DB, compute and verify to rounding error, identifying the minimum and maximum elements.Find how it fails. Quantify on FCC
Cuthe exact error factors from (a) converting with 10-30 instead of and (b) passing with conventional volume , and verifyValueErrorguards on invalid inputs tolattices.theoretical_density_g_cm3.Implement it yourself. Implement
allotropic_density_shift(symbol, target_structure)assuming constant nearest-neighbor bond length , and verify onFe(bccfcc) that volume contracts by .
heading("Self-check for the exercises")
omega_vals = {}
for sym, meta in constants.ELEMENTS_DB.items():
s = lattices.element_crystal_summary(sym)
omega_A3 = s["volume_A3"] / s["n_atoms_cell"]
vm_from_rho = meta["Mw"] / s["density_g_cm3"]
vm_from_omega = constants.N_A * omega_A3 * 1.0e-24
assert np.isclose(vm_from_rho, vm_from_omega, rtol=1e-14)
omega_vals[sym] = omega_A3
min_sym = min(omega_vals, key=omega_vals.get)
max_sym = max(omega_vals, key=omega_vals.get)
print(f"Smallest atomic volume: {min_sym} ({omega_vals[min_sym]:.3f} A^3/atom) | Largest: {max_sym} ({omega_vals[max_sym]:.3f} A^3/atom)")
assert min_sym == "C-diamond" and max_sym == "Mg"
print("All checks passed.")
Self-check for the exercises
============================
Smallest atomic volume: C-diamond (5.672 A^3/atom) | Largest: Mg (23.241 A^3/atom)
All checks passed.