Worked solutions to the three exercises of Lecture 15. 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: Interstitial C vs Substitutional Fe Diffusion in Austenite & erfc Carburizing")
# Classical metallurgical parameters in FCC austenite (gamma-Fe):
D0_C, Q_C = 2.0e-5, 142_000.0 # Interstitial C in gamma-Fe [m^2/s, J/mol]
D0_Fe, Q_Fe = 4.9e-5, 284_000.0 # Substitutional Fe self-diffusion in gamma-Fe [m^2/s, J/mol]
T_range = np.array([1150.0, 1200.0, 1250.0, 1300.0]) # [K] (877 C to 1027 C)
D_C_vals = kinetics_selection.arrhenius_diffusivity(T_range, D0_C, Q_C)
D_Fe_vals = kinetics_selection.arrhenius_diffusivity(T_range, D0_Fe, Q_Fe)
print(f"{'T [K]':>7s} | {'T [C]':>7s} | {'D_C (interstitial) [m^2/s]':>27s} | {'D_Fe (substitutional) [m^2/s]':>30s} | {'Ratio D_C / D_Fe':>16s}")
print("-" * 98)
for tk, dc, dfe in zip(T_range, D_C_vals, D_Fe_vals):
print(f"{tk:7.0f} | {tk - 273.15:7.1f} | {dc:27.3e} | {dfe:30.3e} | {dc / dfe:16.1e}")
assert np.all(D_C_vals / D_Fe_vals > 1e5)
# Carburizing AISI 1020 steel (c0 = 0.20 wt% C) at T = 1200 K (927 C), cs = 1.00 wt% C:
D_1200 = float(kinetics_selection.arrhenius_diffusivity(1200.0, D0_C, Q_C))
x_mm = np.linspace(0.0, 4.0, 201)
x_m = x_mm * 1e-3
c_2h = kinetics_selection.carburization_erfc(x_m, t_s=2.0 * 3600.0, D_m2_s=D_1200, c_s=1.00, c_0=0.20)
c_8h = kinetics_selection.carburization_erfc(x_m, t_s=8.0 * 3600.0, D_m2_s=D_1200, c_s=1.00, c_0=0.20)
# Exact sqrt(t) scaling check: c(x = 0.8 mm, t = 2 h) == c(x = 1.6 mm, t = 8 h)
c_2h_08 = kinetics_selection.carburization_erfc(0.8e-3, t_s=2.0 * 3600.0, D_m2_s=D_1200, c_s=1.00, c_0=0.20)
c_8h_16 = kinetics_selection.carburization_erfc(1.6e-3, t_s=8.0 * 3600.0, D_m2_s=D_1200, c_s=1.00, c_0=0.20)
print(f"\nSimilarity check: c(0.8 mm, 2 h) = {c_2h_08:.8f} wt% vs c(1.6 mm, 8 h) = {c_8h_16:.8f} wt% C")
assert np.isclose(c_2h_08, c_8h_16, rtol=1e-14)
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Construct the analytical constant- couple with , , and on (), and verify that boltzmann_matano_diffusivity recovers to and everywhere within .
heading("Exercise 1: Analytical Constant-D Diffusion Couple Verification of Boltzmann-Matano")
import math
x_grid = np.linspace(-4.0e-3, 4.0e-3, 401)
D0_true = 2.5e-11
x0_true = -0.25e-3
t_anneal = 3600.0
erfc_vec = np.vectorize(math.erfc)
c_prof = 0.10 + 0.35 * erfc_vec((x_grid - x0_true) / (2.0 * np.sqrt(D0_true * t_anneal)))
bm = kinetics_selection.boltzmann_matano_diffusivity(x_grid, c_prof, t_s=t_anneal, grad_rel_threshold=0.08)
max_rel_err = float(np.max(np.abs(bm["D_est"] - D0_true) / D0_true))
print(f"Recovered Matano plane x_M = {bm['x_matano']*1e3:.6f} mm vs true x0 = {x0_true*1e3:.6f} mm")
print(f"Recovered D_est range = [{bm['D_est'].min():.4e}, {bm['D_est'].max():.4e}] m^2/s (max rel err = {max_rel_err:.3%})")
assert np.isclose(bm["x_matano"], x0_true, atol=1e-7)
assert max_rel_err < 0.005
Exercise 1: Analytical Constant-D Diffusion Couple Verification of Boltzmann-Matano
===================================================================================
Recovered Matano plane x_M = -0.250000 mm vs true x0 = -0.250000 mm
Recovered D_est range = [2.4968e-11, 2.5014e-11] m^2/s (max rel err = 0.130%)
Explanation. boltzmann_matano_diffusivity rewrites the cumulative integral via integration by parts. Integrating with respect to rather than with respect to handles arbitrary grid spacing cleanly and recovers across the couple to .
Exercise 2¶
Problem. Verify ValueError guards for x_m < 0 in carburization_erfc and equal endpoints c[0] == c[-1] in boltzmann_matano_diffusivity, and quantify on a noisy EPMA couple () how grad_rel_threshold=0.12 eliminates catastrophic tail amplification compared to grad_rel_threshold=1e-6.
heading("Exercise 2: Domain Guards & EPMA Tail-Gradient Division-by-Zero Audit")
import math
caught_neg_x = False
try:
kinetics_selection.carburization_erfc(-1e-4, t_s=100.0, D_m2_s=1e-11, c_s=1.0, c_0=0.2)
except ValueError:
caught_neg_x = True
assert caught_neg_x is True
caught_flat_c = False
try:
kinetics_selection.boltzmann_matano_diffusivity(np.linspace(0.0, 1.0, 20), np.full(20, 0.5), t_s=100.0)
except ValueError:
caught_flat_c = True
assert caught_flat_c is True
rng_epma = np.random.default_rng(1502)
xg = np.linspace(-3.0e-3, 3.0e-3, 201)
D_ref = 2.0e-11
c_clean = 0.5 * np.vectorize(math.erfc)(xg / (2.0 * np.sqrt(D_ref * 3600.0)))
c_noisy = c_clean + rng_epma.normal(0.0, 5e-4, size=xg.size)
c_noisy[0], c_noisy[-1] = 1.0, 0.0
bm_unfiltered = kinetics_selection.boltzmann_matano_diffusivity(xg, c_noisy, t_s=3600.0, grad_rel_threshold=1e-6)
bm_filtered = kinetics_selection.boltzmann_matano_diffusivity(xg, c_noisy, t_s=3600.0, grad_rel_threshold=0.15)
err_unfilt = float(np.max(np.abs(bm_unfiltered["D_est"] - D_ref) / D_ref))
err_filt = float(np.max(np.abs(bm_filtered["D_est"] - D_ref) / D_ref))
print(f"Noisy EPMA max relative error: unfiltered (thresh=1e-6) = {err_unfilt:.1%} vs filtered (thresh=0.15) = {err_filt:.2%}")
assert err_unfilt > 1.0 and err_filt < 0.15
Exercise 2: Domain Guards & EPMA Tail-Gradient Division-by-Zero Audit
=====================================================================
Noisy EPMA max relative error: unfiltered (thresh=1e-6) = 1343.3% vs filtered (thresh=0.15) = 8.46%
Explanation. Far from the Matano interface (), the true concentration gradient exponentially while finite-difference microprobe noise stays , causing to divide by random noise (including negative ). Masking restricts inversion to the physically informative core of the diffusion zone.
Exercise 3¶
Problem. Implement two_stage_boost_diffuse(x_grid, D, t_boost, c_boost, t_diff, c_diff, c_core, dt=60.0) chaining two sequential fick_1d_crank_nicolson stages at (): boost at + diffuse at , and verify it achieves deeper case depth than single-stage carburizing at while holding surface carbon at .
heading("Exercise 3: Implement It Yourself — Industrial Two-Stage Boost-Diffuse Carburizing Schedule")
def two_stage_boost_diffuse(
x_grid: np.ndarray, D: float, t_boost: float, c_boost: float, t_diff: float, c_diff: float, c_core: float, dt: float = 60.0
) -> np.ndarray:
"""Simulate two-stage boost-diffuse gas carburizing via sequential Crank-Nicolson integrations."""
dx = float(x_grid[1] - x_grid[0])
n1 = int(round(t_boost / dt))
n2 = int(round(t_diff / dt))
c0 = np.full(x_grid.size, c_core, dtype=float)
c_after_boost = kinetics_selection.fick_1d_crank_nicolson(c0, dx=dx, dt=dt, n_steps=n1, D=D, bc_left=c_boost, bc_right=c_core)
c_final = kinetics_selection.fick_1d_crank_nicolson(c_after_boost, dx=dx, dt=dt, n_steps=n2, D=D, bc_left=c_diff, bc_right=c_core)
return c_final
D_carb = float(kinetics_selection.arrhenius_diffusivity(1200.0, 2.0e-5, 142_000.0))
xg_carb = np.linspace(0.0, 5.0e-3, 251)
c_bd = two_stage_boost_diffuse(xg_carb, D=D_carb, t_boost=7200.0, c_boost=1.10, t_diff=7200.0, c_diff=0.80, c_core=0.20)
c_single = kinetics_selection.fick_1d_crank_nicolson(
np.full(xg_carb.size, 0.20), dx=float(xg_carb[1] - xg_carb[0]), dt=60.0, n_steps=240, D=D_carb, bc_left=0.80, bc_right=0.20
)
depth_bd_mm = float(np.interp(0.50, c_bd[::-1], xg_carb[::-1]) * 1e3)
depth_single_mm = float(np.interp(0.50, c_single[::-1], xg_carb[::-1]) * 1e3)
print(f"4 h Single-stage (cs=0.80 wt%): surface c = {c_single[0]:.2f} wt%, 0.50 wt% case depth = {depth_single_mm:.3f} mm")
print(f"2h+2h Boost-Diffuse (1.10->0.80): surface c = {c_bd[0]:.2f} wt%, 0.50 wt% case depth = {depth_bd_mm:.3f} mm (+{(depth_bd_mm/depth_single_mm - 1)*100:.1f}% deeper)")
assert np.isclose(c_bd[0], 0.80, atol=1e-12) and depth_bd_mm > 1.15 * depth_single_mm
Exercise 3: Implement It Yourself — Industrial Two-Stage Boost-Diffuse Carburizing Schedule
===========================================================================================
4 h Single-stage (cs=0.80 wt%): surface c = 0.80 wt%, 0.50 wt% case depth = 0.416 mm
2h+2h Boost-Diffuse (1.10->0.80): surface c = 0.80 wt%, 0.50 wt% case depth = 0.500 mm (+20.3% deeper)
Summary. Whereas analytical requires constant boundary conditions and uniform initial state, fick_1d_crank_nicolson handles arbitrary piecewise furnace schedules, demonstrating why industrial boost–diffuse carburizing achieves an deeper hardened case in the same furnace time without brittle surface cementite networks.