Automotive transmission gears must combine a wear-resistant, high-carbon martensitic surface () with a tough, fracture-resistant low-carbon core (). Metallurgists achieve this graded architecture by gas carburizing austenite (-Fe) at , a solid-state Fickian diffusion process. Yet in real alloys and welded diffusion couples, the interdiffusion coefficient is rarely constant: carbon in -Fe diffuses up to faster at than in dilute iron. In this lecture we cover thermally activated arrhenius_diffusivity, analytical carburization_erfc case-depth design, unconditionally stable fick_1d_crank_nicolson with the NumPy Thomas tridiagonal solver, and inverse boltzmann_matano_diffusivity extraction of directly from a single concentration profile.
Learning objectives¶
Compute thermally activated interstitial vs. substitutional diffusivities using
kinetics_selection.arrhenius_diffusivity.Design gas-carburizing heat treatments via the exact semi-infinite similarity solution in
kinetics_selection.carburization_erfc.Solve 1-D transient diffusion with Dirichlet boundary conditions via the unconditionally stable Crank–Nicolson + Thomas tridiagonal algorithm in
kinetics_selection.fick_1d_crank_nicolson.Invert an experimental diffusion-couple profile to locate the mass-conserving Matano plane and recover concentration-dependent via
kinetics_selection.boltzmann_matano_diffusivity.
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¶
Atomic jumps in crystalline solids require surmounting a saddle-point activation enthalpy , giving the Arrhenius diffusivity (kinetics_selection.arrhenius_diffusivity):
Interstitial solutes (C, N, H squeezing between octahedral sites without needing a vacant host lattice site) have far smaller activation barriers than substitutional host atoms (which must wait for thermal vacancies).
1.1 Semi-Infinite Gas Carburization & Similarity Scaling¶
For a thick steel component () initially at uniform core carbon exposed at to a constant surface carbon potential , Fick’s second law collapses via the Boltzmann similarity variable onto the exact complementary error-function solution (kinetics_selection.carburization_erfc):
In particular, since , the effective case depth where obeys the rule-of-thumb : doubling case depth requires quadrupling furnace soak time , or raising temperature modestly.
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)
Demonstration 1: Interstitial C vs Substitutional Fe Diffusion in Austenite & erfc Carburizing
==============================================================================================
T [K] | T [C] | D_C (interstitial) [m^2/s] | D_Fe (substitutional) [m^2/s] | Ratio D_C / D_Fe
--------------------------------------------------------------------------------------------------
1150 | 876.9 | 7.101e-12 | 6.177e-18 | 1.1e+06
1200 | 926.9 | 1.318e-11 | 2.129e-17 | 6.2e+05
1250 | 976.9 | 2.330e-11 | 6.648e-17 | 3.5e+05
1300 | 1026.8 | 3.940e-11 | 1.902e-16 | 2.1e+05
Similarity check: c(0.8 mm, 2 h) = 0.25308100 wt% vs c(1.6 mm, 8 h) = 0.25308100 wt% C
What Demonstration 1 shows. At (), interstitial carbon diffuses times faster than iron host atoms ( vs. ). And because is invariant when and , carbon concentration at after equals that at after () to rounding error.
2. Crank–Nicolson & Thomas Tridiagonal Algorithm¶
On finite slabs, multi-stage boost-diffuse furnace schedules, or fine surface meshes where explicit Forward-Time Central-Space (FTCS) violates , the Crank–Nicolson method (kinetics_selection.fick_1d_crank_nicolson) averages spatial second derivatives equally at time levels and ():
Instead of forming a dense matrix (), the Thomas tridiagonal algorithm solves Eq. (2.1) by a single forward sweep and back-substitution in strictly operations. We benchmark fick_1d_crank_nicolson at Fourier number (nearly above the explicit FTCS blow-up limit) against carburization_erfc.
heading("Demonstration 2: Crank-Nicolson + Thomas Solver vs Analytical erfc at Fourier Number r = 1.90")
L_slab = 6.0e-3 # 6 mm slab (>> 2*sqrt(D*t) = 1.38 mm for 4 h at 1200 K, so right boundary stays at c0)
N_cn = 241
x_cn = np.linspace(0.0, L_slab, N_cn)
dx_cn = float(x_cn[1] - x_cn[0]) # 25 um
t_total = 4.0 * 3600.0 # 4 hours = 14,400 s
n_steps_cn = 160
dt_cn = t_total / n_steps_cn # 90 s
fourier_r = D_1200 * dt_cn / (dx_cn ** 2)
c_init_cn = np.full(N_cn, 0.20)
c_init_cn[0] = 1.00
c_cn_4h = kinetics_selection.fick_1d_crank_nicolson(
c_init_cn, dx=dx_cn, dt=dt_cn, n_steps=n_steps_cn, D=D_1200, bc_left=1.00, bc_right=0.20
)
c_erfc_4h = kinetics_selection.carburization_erfc(x_cn, t_s=t_total, D_m2_s=D_1200, c_s=1.00, c_0=0.20)
# Compare interior accuracy (and verify explicit FTCS at the same dt blows up):
c_ftcs = c_init_cn.copy()
with np.errstate(over="ignore", invalid="ignore"):
for _ in range(n_steps_cn):
c_ftcs[1:-1] = c_ftcs[1:-1] + fourier_r * (c_ftcs[:-2] - 2.0 * c_ftcs[1:-1] + c_ftcs[2:])
rmse_cn = float(np.sqrt(np.mean((c_cn_4h - c_erfc_4h) ** 2)))
max_err_cn = float(np.max(np.abs(c_cn_4h - c_erfc_4h)))
print(f"Mesh Fourier number r = D*dt/dx^2 = {fourier_r:.3f} (Explicit FTCS limit = 0.500 -> FTCS blew up: {not np.all(np.isfinite(c_ftcs)) or np.max(np.abs(c_ftcs)) > 1e6})")
print(f"Crank-Nicolson 4 h carburizing RMSE vs analytical erfc = {rmse_cn:.4e} wt% C (max diff = {max_err_cn:.4e} wt% C)")
assert fourier_r > 1.5
assert max_err_cn < 2e-3
fig, ax = plt.subplots(figsize=(7.5, 4.0))
ax.plot(x_mm, c_2h, "--", lw=1.9, label="Analytical erfc ($t = 2\\ \\mathrm{h}$)")
ax.plot(x_cn * 1e3, c_erfc_4h, "k-", lw=2.2, label="Analytical erfc ($t = 4\\ \\mathrm{h}$)")
ax.plot(x_cn[::6] * 1e3, c_cn_4h[::6], "ro", ms=4.5, label=f"Crank–Nicolson ($t = 4\\ \\mathrm{{h}}$, $r = {fourier_r:.2f}$)")
ax.plot(x_mm, c_8h, "-.", lw=1.9, label="Analytical erfc ($t = 8\\ \\mathrm{h}$)")
ax.axhline(0.50, color="gray", ls=":", label="Target case hardness $c^* = 0.50\\ \\mathrm{wt\\%}$")
ax.set_xlim(0.0, 4.0)
ax.set_xlabel("Depth below gear surface $x$ [mm]")
ax.set_ylabel("Carbon concentration $c(x,t)$ [wt% C]")
ax.set_title("Gas Carburization of $\\gamma$-Fe at $927\\ ^\\circ\\mathrm{C}$ ($1200\\ \\mathrm{K}$)")
ax.legend(fontsize=8)
plt.show()
Demonstration 2: Crank-Nicolson + Thomas Solver vs Analytical erfc at Fourier Number r = 1.90
=============================================================================================
Mesh Fourier number r = D*dt/dx^2 = 1.899 (Explicit FTCS limit = 0.500 -> FTCS blew up: True)
Crank-Nicolson 4 h carburizing RMSE vs analytical erfc = 1.2099e-05 wt% C (max diff = 3.5093e-05 wt% C)

Figure 15.1. Carbon profiles in austenite at 1200 K for a fixed surface concentration: the error-function solution at three times and the Crank–Nicolson solution at 4 h. The dotted line is the concentration that defines the case depth.
What Demonstration 2 shows. At , explicit FTCS explodes exponentially to , whereas Crank–Nicolson with the Thomas solver tracks the exact analytical profile to RMSE = 1.5e-4 wt% C across the entire gear tooth.
3. Concentration-Dependent Interdiffusion & Boltzmann–Matano Inversion¶
In real binary diffusion couples (welding pure at to alloy at and annealing for time ), diffusivity varies strongly with composition:
In 1933, Chujiro Matano applied Ludwig Boltzmann’s similarity transformation to invert a single measured profile directly for (kinetics_selection.boltzmann_matano_diffusivity):
Locate the Matano interface by global solute conservation: equal areas on both sides of .
Evaluate at each interior composition :
We simulate a forward nonlinear diffusion couple where ( faster at than at , creating an asymmetric profile), and then pass into boltzmann_matano_diffusivity to see if it recovers without knowing the PDE parameters.
heading("Demonstration 3: Forward Nonlinear Diffusion Couple & Inverse Boltzmann-Matano Recovery of D(c)")
# Forward conservative finite-volume simulation of dc/dt = d/dx [D(c) dc/dx] on [-4 mm, +4 mm]:
N_bm = 321
x_bm = np.linspace(-4.0e-3, 4.0e-3, N_bm)
dx_bm = float(x_bm[1] - x_bm[0])
D_base = 1.0e-11 # [m^2/s]
D_true_fn = lambda c_arr: D_base * (1.0 + 2.0 * c_arr)
# Smooth initial weld step centered at x0 = +0.35e-3 m (off-center weld to test Matano-plane recovery):
x_weld = 0.35e-3
c_couple = 0.5 * (1.0 + np.tanh((x_bm - x_weld) / (1.5 * dx_bm)))
dt_bm = 2.0 # s (max D = 3e-11 -> max r = 3e-11 * 2 / (2.5e-5)^2 = 0.096 < 0.5, ultra-accurate)
n_bm_steps = 3600 # t_s = 7200 s (2 h)
for _ in range(n_bm_steps):
c_mid = 0.5 * (c_couple[:-1] + c_couple[1:])
flux = -D_true_fn(c_mid) * np.diff(c_couple) / dx_bm
c_couple[1:-1] -= (dt_bm / dx_bm) * np.diff(flux)
bm_res = kinetics_selection.boltzmann_matano_diffusivity(x_bm, c_couple, t_s=n_bm_steps * dt_bm, grad_rel_threshold=0.08)
D_recovered = bm_res["D_est"]
D_exact_valid = D_true_fn(bm_res["c_valid"])
rel_err_bm = float(np.mean(np.abs(D_recovered - D_exact_valid) / D_exact_valid))
print(f"True initial weld plane x_weld = {x_weld * 1e3:.4f} mm | Recovered Matano plane x_M = {bm_res['x_matano'] * 1e3:.4f} mm")
print(f"Mean relative error of Boltzmann-Matano D(c) across {len(D_recovered)} interior points = {rel_err_bm:.2%}")
assert np.isclose(bm_res["x_matano"], x_weld, atol=5e-6)
assert rel_err_bm < 0.02
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
ax1.plot(x_bm * 1e3, c_couple, lw=2.2, label="Nonlinear couple $c(x, t)$")
ax1.axvline(bm_res["x_matano"] * 1e3, color="tab:red", ls="--", lw=1.8, label=f"Matano plane $x_M = {bm_res['x_matano']*1e3:.2f}\\ \\mathrm{{mm}}$")
ax1.set_xlim(-2.5, 3.0)
ax1.set_xlabel("Position $x$ [mm]")
ax1.set_ylabel("Composition $c$ [-]")
ax1.set_title("Asymmetric Diffusion-Couple Profile ($D$ Higher at High $c$)")
ax1.legend(fontsize=8)
c_line = np.linspace(0.0, 1.0, 100)
ax2.plot(c_line, D_true_fn(c_line) * 1e11, "k-", lw=2.2, label=r"True $D(c) = D_0(1 + 2c)$")
ax2.plot(bm_res["c_valid"][::3], D_recovered[::3] * 1e11, "ro", ms=5, label="Boltzmann–Matano $D_{\\mathrm{est}}(c)$")
ax2.set_xlabel("Composition $c$ [-]")
ax2.set_ylabel("Interdiffusivity $D(c)$ [$10^{-11}\\ \\mathrm{m^2/s}$]")
ax2.set_title("Inverse Recovery of Concentration-Dependent $D(c)$")
ax2.legend(fontsize=8)
label_panels(fig)
plt.show()
Demonstration 3: Forward Nonlinear Diffusion Couple & Inverse Boltzmann-Matano Recovery of D(c)
===============================================================================================
True initial weld plane x_weld = 0.3500 mm | Recovered Matano plane x_M = 0.3500 mm
Mean relative error of Boltzmann-Matano D(c) across 94 interior points = 0.42%

Figure 15.2. Synthetic data. (a) Diffusion-couple profile computed with and the Matano plane. (b) Diffusivity recovered by Boltzmann–Matano analysis (points) and the law used to generate the profile (line).
What Demonstration 3 shows. Panel (a) shows the effect of a concentration-dependent : on the right side (, where ), the composition profile penetrates much farther and has a gentler slope than on the left side (, where ). Yet global mass conservation still locks the Matano plane right onto the original weld interface, and boltzmann_matano_diffusivity reconstructs the linear ramp across the interdiffusion zone to mean relative error.
4. Sensitivity to the parameters¶
In industrial heat treatment, furnace energy and cycle time are expensive. Suppose an automotive specification requires (). How strongly does raising the carburizing furnace temperature from to cut the required furnace soak time ?
heading("Demonstration 4: Carburizing Temperature Tradeoff — How +100 C Shortens the Furnace Time")
# Target: (c* - c0)/(cs - c0) = (0.50 - 0.20)/(1.00 - 0.20) = 0.375 = erfc(eta*)
# Find exact eta* by bisection using carburization_erfc at D=1, t=0.25 (so 2*sqrt(D*t) = 1 -> x = eta):
lo_e, hi_e = 0.0, 2.0
for _ in range(80):
mid_e = 0.5 * (lo_e + hi_e)
if kinetics_selection.carburization_erfc(mid_e, t_s=0.25, D_m2_s=1.0, c_s=1.0, c_0=0.20) > 0.50:
lo_e = mid_e
else:
hi_e = mid_e
eta_star = 0.5 * (lo_e + hi_e)
x_spec = 1.0e-3 # 1.0 mm
print(f"Exact similarity root eta* where erfc(eta*) = 0.375 : {eta_star:.6f}")
print(f"{'Temp [C]':>9s} | {'Temp [K]':>9s} | {'D_C(T) [m^2/s]':>16s} | {'Required Soak Time [h]':>23s} | {'Check c(1 mm, t_req)':>21s}")
print("-" * 90)
soak_hours = []
for T_C in [875.0, 900.0, 925.0, 950.0, 975.0]:
T_K_val = T_C + 273.15
D_val = float(kinetics_selection.arrhenius_diffusivity(T_K_val, D0_C, Q_C))
t_req_s = (x_spec / (2.0 * eta_star)) ** 2 / D_val
soak_hours.append(t_req_s / 3600.0)
c_chk = kinetics_selection.carburization_erfc(x_spec, t_s=t_req_s, D_m2_s=D_val, c_s=1.00, c_0=0.20)
print(f"{T_C:9.1f} | {T_K_val:9.2f} | {D_val:16.3e} | {t_req_s / 3600.0:23.2f} | {c_chk:21.6f}")
assert np.isclose(c_chk, 0.50, atol=1e-12)
assert soak_hours[0] > 3.2 * soak_hours[-1]
Demonstration 4: Carburizing Temperature Tradeoff — How +100 C Shortens the Furnace Time
========================================================================================
Exact similarity root eta* where erfc(eta*) = 0.375 : 0.627307
Temp [C] | Temp [K] | D_C(T) [m^2/s] | Required Soak Time [h] | Check c(1 mm, t_req)
------------------------------------------------------------------------------------------
875.0 | 1148.15 | 6.933e-12 | 25.45 | 0.500000
900.0 | 1173.15 | 9.519e-12 | 18.54 | 0.500000
925.0 | 1198.15 | 1.290e-11 | 13.68 | 0.500000
950.0 | 1223.15 | 1.726e-11 | 10.22 | 0.500000
975.0 | 1248.15 | 2.283e-11 | 7.73 | 0.500000
Inside the algorithm¶
What Demonstration 4 shows. Raising the furnace temperature by () boosts exponentially and reduces the required carburizing time from to ( faster throughput), though metallurgists cap in conventional steels to prevent abnormal austenite grain growth.
Below we inspect kinetics_selection._solve_tridiagonal and kinetics_selection.boltzmann_matano_diffusivity, and verify the Thomas solver against np.linalg.solve to rounding error.
Check against the library¶
heading("Inside the Algorithm: Thomas Tridiagonal Solver & Boltzmann-Matano Integration by Parts")
print(show_source(kinetics_selection._solve_tridiagonal))
print(show_source(kinetics_selection.boltzmann_matano_diffusivity))
rng_tri = np.random.default_rng(1505)
n_sys = 40
lo_v = -0.8 * np.ones(n_sys - 1)
di_v = 2.6 * np.ones(n_sys)
up_v = -0.8 * np.ones(n_sys - 1)
rhs_v = rng_tri.standard_normal(n_sys)
A_dense = np.diag(di_v) + np.diag(lo_v, k=-1) + np.diag(up_v, k=1)
sol_thomas = kinetics_selection._solve_tridiagonal(lo_v, di_v, up_v, rhs_v)
sol_dense = np.linalg.solve(A_dense, rhs_v)
print("Thomas vs np.linalg.solve max |diff|:", float(np.max(np.abs(sol_thomas - sol_dense))))
assert np.allclose(sol_thomas, sol_dense, rtol=1e-14, atol=1e-14)
Inside the Algorithm: Thomas Tridiagonal Solver & Boltzmann-Matano Integration by Parts
=======================================================================================
def _solve_tridiagonal(lower: np.ndarray, diag: np.ndarray, upper: np.ndarray, rhs: np.ndarray) -> np.ndarray:
"""Pure-NumPy Thomas algorithm for an N x N tridiagonal linear system."""
n = diag.size
cp = np.zeros(n - 1, dtype=float)
dp = np.zeros(n, dtype=float)
cp[0] = upper[0] / diag[0]
dp[0] = rhs[0] / diag[0]
for i in range(1, n):
denom = diag[i] - lower[i - 1] * cp[i - 1]
if i < n - 1:
cp[i] = upper[i] / denom
dp[i] = (rhs[i] - lower[i - 1] * dp[i - 1]) / denom
sol = np.zeros(n, dtype=float)
sol[-1] = dp[-1]
for i in range(n - 2, -1, -1):
sol[i] = dp[i] - cp[i] * sol[i + 1]
return sol
def boltzmann_matano_diffusivity(
x: np.ndarray,
c: np.ndarray,
t_s: float,
grad_rel_threshold: float = 0.05,
) -> dict:
"""Invert a 1-D diffusion-couple profile c(x, t) for concentration-dependent D(c) via Boltzmann-Matano analysis."""
if t_s <= 0.0:
raise ValueError("Diffusion anneal time t_s must be strictly positive.")
xg = np.asarray(x, dtype=float).ravel()
cg = np.asarray(c, dtype=float).ravel()
if xg.size != cg.size or xg.size < 9:
raise ValueError("x and c must be matching 1-D arrays with at least 9 points.")
c_left, c_right = float(cg[0]), float(cg[-1])
if abs(c_right - c_left) < 1e-12:
raise ValueError("Diffusion couple requires distinct terminal compositions c[0] != c[-1].")
dx_seg = np.diff(xg)
cum_int_c = np.concatenate([[0.0], np.cumsum(0.5 * (cg[:-1] + cg[1:]) * dx_seg)])
total_int_c = float(cum_int_c[-1])
x_matano = (xg[-1] * c_right - xg[0] * c_left - total_int_c) / (c_right - c_left)
dc_dx = np.gradient(cg, xg)
int_x_dc = (xg - x_matano) * cg - (xg[0] - x_matano) * c_left - cum_int_c
max_grad = float(np.max(np.abs(dc_dx)))
valid = np.abs(dc_dx) >= grad_rel_threshold * max_grad
valid[0] = False
valid[-1] = False
d_est = -int_x_dc[valid] / (2.0 * t_s * dc_dx[valid])
return {
"x_matano": float(x_matano),
"x_valid": xg[valid],
"c_valid": cg[valid],
"D_est": d_est,
}
Thomas vs np.linalg.solve max |diff|: 2.220446049250313e-16
Exercises¶
Worked solutions are in 15_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Construct the analytical constant- couple with , , and on (), and verify that
boltzmann_matano_diffusivityrecovers to and everywhere within .Find how it fails. Verify
ValueErrorguards forx_m < 0incarburization_erfcand equal endpointsc[0] == c[-1]inboltzmann_matano_diffusivity, and quantify on a noisy EPMA couple () howgrad_rel_threshold=0.12eliminates catastrophic tail amplification compared tograd_rel_threshold=1e-6.Implement it yourself. Implement
two_stage_boost_diffuse(x_grid, D, t_boost, c_boost, t_diff, c_diff, c_core, dt=60.0)chaining two sequentialfick_1d_crank_nicolsonstages at (): boost at + diffuse at , and verify it achieves deeper case depth than single-stage carburizing at while holding surface carbon at .
heading("Self-check for the exercises")
x_c15 = np.linspace(-4.0e-3, 4.0e-3, 401)
D_ref15, x0_ref15, t_ref15 = 2.5e-11, -0.25e-3, 3600.0
# Use carburization_erfc on |x - x0| via symmetry of erfc: erfc(-z) = 2 - erfc(z)
z_15 = (x_c15 - x0_ref15) / (2.0 * np.sqrt(D_ref15 * t_ref15))
erfc_15 = np.where(
z_15 >= 0.0,
kinetics_selection.carburization_erfc(np.abs(z_15), t_s=0.25, D_m2_s=1.0, c_s=1.0, c_0=0.0),
2.0 - kinetics_selection.carburization_erfc(np.abs(z_15), t_s=0.25, D_m2_s=1.0, c_s=1.0, c_0=0.0),
)
c_c15 = 0.10 + 0.5 * (0.80 - 0.10) * erfc_15
bm_15 = kinetics_selection.boltzmann_matano_diffusivity(x_c15, c_c15, t_s=t_ref15, grad_rel_threshold=0.08)
print(f"Constant-D Boltzmann-Matano: x_M = {bm_15['x_matano']*1e3:.5f} mm (exact -0.25000 mm), mean D = {np.mean(bm_15['D_est']):.4e} m^2/s")
assert np.isclose(bm_15["x_matano"], x0_ref15, atol=1e-7) and np.allclose(bm_15["D_est"], D_ref15, rtol=5e-3)
print("All checks passed.")
Self-check for the exercises
============================
Constant-D Boltzmann-Matano: x_M = -0.25000 mm (exact -0.25000 mm), mean D = 2.4998e-11 m^2/s
All checks passed.