Worked solutions to the three exercises of Lecture 9. 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: Enthalpy-Entropy Competition Above and Below Tc = Omega / (2R)")
omega_demo = 18000.0 # [J/mol], representative of Au-Ni / Cu-Co positive-enthalpy FCC solid solutions
Tc_demo = phase_thermodynamics.regular_solution_critical_temp(omega_demo)
x_grid = np.linspace(0.002, 0.998, 400)
res_low = phase_thermodynamics.regular_solution_free_energy(x_grid, T_K=750.0, omega_J_mol=omega_demo)
res_high = phase_thermodynamics.regular_solution_free_energy(x_grid, T_K=1300.0, omega_J_mol=omega_demo)
mid_low = phase_thermodynamics.regular_solution_free_energy(0.5, T_K=750.0, omega_J_mol=omega_demo)
mid_high = phase_thermodynamics.regular_solution_free_energy(0.5, T_K=1300.0, omega_J_mol=omega_demo)
print(f"Omega = {omega_demo:.0f} J/mol -> Consolute Critical Temperature Tc = {Tc_demo:.2f} K")
print(f"At T = 750 K (< Tc): dG_mix(0.5) = {mid_low['dG_mix']:+8.1f} J/mol | d2G/dx2(0.5) = {mid_low['d2G_dx2']:+9.1f} J/mol (UNSTABLE < 0)")
print(f"At T = 1300 K (> Tc): dG_mix(0.5) = {mid_high['dG_mix']:+8.1f} J/mol | d2G/dx2(0.5) = {mid_high['d2G_dx2']:+9.1f} J/mol (STABLE > 0)")
assert mid_low["d2G_dx2"] < 0.0 and mid_high["d2G_dx2"] > 0.0
assert float(np.min(res_low["dG_mix"])) < 0.0 # Entropy guarantees negative dG_mix wells near x->0 and x->1
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.4, 3.9))
ax1.plot(x_grid, res_low["dH_mix"] / 1e3, "--", lw=1.7, label=r"$\Delta H_{\mathrm{mix}}$")
ax1.plot(x_grid, -750.0 * res_low["dS_mix"] / 1e3, ":", lw=1.7, label=r"$-T \Delta S_{\mathrm{mix}}$ ($750$ K)")
ax1.plot(x_grid, res_low["dG_mix"] / 1e3, lw=2.2, color="#c0392b", label=r"$\Delta G_{\mathrm{mix}}$ ($750$ K $< T_c$, double well)")
ax1.plot(x_grid, res_high["dG_mix"] / 1e3, lw=2.0, color="#1f4e79", label=r"$\Delta G_{\mathrm{mix}}$ ($1300$ K $> T_c$, convex)")
ax1.set_xlabel(r"Solute Mole Fraction $x_B$ [-]")
ax1.set_ylabel(r"Molar Energy [$\mathrm{kJ/mol}$]")
ax1.set_title("Enthalpy vs. Configurational Entropy")
ax1.set_ylim(-5.0, 8.5)
ax1.legend(fontsize=7.8, loc="upper center", ncol=2)
ax2.plot(x_grid, res_low["d2G_dx2"] / 1e3, lw=2.0, color="#c0392b", label=r"$750$ K ($< T_c$)")
ax2.plot(x_grid, res_high["d2G_dx2"] / 1e3, lw=2.0, color="#1f4e79", label=r"$1300$ K ($> T_c$)")
ax2.axhline(0.0, color="black", ls="--", lw=1.2)
ax2.set_ylim(-20.0, 80.0)
ax2.set_xlabel(r"Solute Mole Fraction $x_B$ [-]")
ax2.set_ylabel(r"Curvature $\partial^2 \Delta G_{\mathrm{mix}} / \partial x^2$ [$\mathrm{kJ/mol}$]")
ax2.set_title("Spinodal Instability Window ($\\partial^2 G / \\partial x^2 < 0$)")
ax2.legend()
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Evaluate and from redlich_kister_free_energy with at , verifying Raoult’s law ( as ) and Henry’s infinite-dilution enthalpies () and ().
heading("Exercise 1: Raoult's Law & Henry's Infinite-Dilution Limits of Redlich-Kister Activity Coefficients")
L0, L1, L2, T = 21000.0, -5500.0, 2400.0, 1000.0
x_dil_A = 1e-8
x_dil_B = 1.0 - 1e-8
rk_lo = phase_thermodynamics.redlich_kister_free_energy(x_dil_A, T, L0, L1, L2)
rk_hi = phase_thermodynamics.redlich_kister_free_energy(x_dil_B, T, L0, L1, L2)
rt_lngA_0 = rk_lo["dmu_A"] - constants.R * T * np.log(1.0 - x_dil_A)
rt_lngB_inf = rk_lo["dmu_B"] - constants.R * T * np.log(x_dil_A)
rt_lngA_inf = rk_hi["dmu_A"] - constants.R * T * np.log(1.0 - x_dil_B)
rt_lngB_1 = rk_hi["dmu_B"] - constants.R * T * np.log(x_dil_B)
print(f"x -> 0+ : RT ln(gamma_A) = {rt_lngA_0:.3e} J/mol (Raoult = 0) | RT ln(gamma_B^inf) = {rt_lngB_inf:.2f} vs L0+L1+L2 = {L0+L1+L2:.2f}")
print(f"x -> 1- : RT ln(gamma_B) = {rt_lngB_1:.3e} J/mol (Raoult = 0) | RT ln(gamma_A^inf) = {rt_lngA_inf:.2f} vs L0-L1+L2 = {L0-L1+L2:.2f}")
assert abs(rt_lngA_0) < 1e-6 and abs(rt_lngB_1) < 1e-6
assert np.isclose(rt_lngB_inf, L0 + L1 + L2, rtol=1e-6)
assert np.isclose(rt_lngA_inf, L0 - L1 + L2, rtol=1e-6)
Exercise 1: Raoult's Law & Henry's Infinite-Dilution Limits of Redlich-Kister Activity Coefficients
===================================================================================================
x -> 0+ : RT ln(gamma_A) = 1.650e-12 J/mol (Raoult = 0) | RT ln(gamma_B^inf) = 17900.00 vs L0+L1+L2 = 17900.00
x -> 1- : RT ln(gamma_B) = 4.950e-12 J/mol (Raoult = 0) | RT ln(gamma_A^inf) = 28900.00 vs L0-L1+L2 = 28900.00
Explanation. Near , , so while near , , so . The direct physical meaning of : when , the partial molar enthalpy of dissolving trace B into pure A () differs from dissolving trace A into pure B () by .
Exercise 2¶
Problem. Verify that pure-component endpoints return exact zero mixing energy (dG_mix == 0.0) without 0 * (-inf) = NaN corruption in both regular_solution_free_energy and redlich_kister_free_energy, and confirm that invalid compositions () or raise ValueError.
heading("Exercise 2: Pure-Component Endpoint Limit Check (0 * log(0) == 0) & Input Validation Guards")
reg_ends = phase_thermodynamics.regular_solution_free_energy(np.array([0.0, 1.0]), 800.0, 15000.0)
rk_ends = phase_thermodynamics.redlich_kister_free_energy(np.array([0.0, 1.0]), 800.0, 15000.0, -4000.0, 1200.0)
print("Regular dG_mix([0, 1]) :", reg_ends["dG_mix"], "| dS_mix([0, 1]):", reg_ends["dS_mix"])
print("Redlich-Kister dG_mix([0, 1]) :", rk_ends["dG_mix"], "| G_ex([0, 1]) :", rk_ends["G_excess"])
assert np.allclose(reg_ends["dG_mix"], 0.0, atol=1e-15) and not np.any(np.isnan(reg_ends["dmu_A"]))
assert np.allclose(rk_ends["dG_mix"], 0.0, atol=1e-15) and not np.any(np.isnan(rk_ends["dmu_B"]))
for bad_call in [
lambda: phase_thermodynamics.regular_solution_free_energy(-0.01, 800.0, 10000.0),
lambda: phase_thermodynamics.redlich_kister_free_energy(1.02, 800.0, 10000.0),
lambda: phase_thermodynamics.redlich_kister_free_energy(0.5, 0.0, 10000.0),
]:
caught = False
try:
bad_call()
except ValueError:
caught = True
assert caught is True
print("All endpoint limits and out-of-domain ValueError guards verified")
Exercise 2: Pure-Component Endpoint Limit Check (0 * log(0) == 0) & Input Validation Guards
===========================================================================================
Regular dG_mix([0, 1]) : [0. 0.] | dS_mix([0, 1]): [0. 0.]
Redlich-Kister dG_mix([0, 1]) : [0. 0.] | G_ex([0, 1]) : [0. 0.]
All endpoint limits and out-of-domain ValueError guards verified
Explanation. Evaluating x * np.log(x) directly at x = 0.0 in IEEE-754 floating point produces 0.0 * (-inf) = nan (plus RuntimeWarning), even though . Guarding pure endpoints with np.where((x > 0) & (x < 1), ..) preserves exact when building full convex-hull phase diagrams.
Exercise 3¶
Problem. Implement subregular_spinodal_roots(T_K, L0, L1, L2=0.0) to find the spinodal compositions where redlich_kister_free_energy(..., L0, L1, L2)['d2G_dx2'] == 0 via sign-change bracketing and 60-step bisection. Verify exact match with regular_solution_spinodal when , and compute the skewed spinodal roots for at .
heading("Exercise 3: Implement It Yourself — Asymmetric Subregular Spinodal Solver via Bisection")
def subregular_spinodal_roots(T_K: float, L0: float, L1: float = 0.0, L2: float = 0.0) -> tuple[float, float] | None:
"""Locate spinodal roots (x_s1, x_s2) where d2G_dx2 == 0 for a Redlich-Kister binary solution."""
x_scan = np.linspace(1e-6, 1.0 - 1e-6, 4000)
d2_scan = phase_thermodynamics.redlich_kister_free_energy(x_scan, T_K, L0, L1, L2)["d2G_dx2"]
brackets = []
for i in range(x_scan.size - 1):
if d2_scan[i] * d2_scan[i + 1] <= 0.0:
lo, hi = float(x_scan[i]), float(x_scan[i + 1])
flo = float(d2_scan[i])
for _ in range(60):
mid = 0.5 * (lo + hi)
fmid = phase_thermodynamics.redlich_kister_free_energy(mid, T_K, L0, L1, L2)["d2G_dx2"]
if flo * fmid <= 0.0:
hi = mid
else:
lo, flo = mid, fmid
brackets.append(0.5 * (lo + hi))
return (brackets[0], brackets[-1]) if len(brackets) >= 2 else None
# Benchmark 1: Symmetric limit L1 = L2 = 0 against closed-form regular_solution_spinodal
sym_num = subregular_spinodal_roots(850.0, 18500.0, 0.0, 0.0)
sym_exact = phase_thermodynamics.regular_solution_spinodal(850.0, 18500.0)
assert sym_num is not None and sym_exact is not None
assert np.allclose(sym_num, sym_exact, rtol=1e-12, atol=1e-12)
# Benchmark 2: Au-Ni-like skewed subregular solution (L1 = -6000 J/mol shifts spinodal toward x > 0.5)
skew_roots = subregular_spinodal_roots(850.0, 18500.0, -6000.0, 0.0)
assert skew_roots is not None
d2_check = phase_thermodynamics.redlich_kister_free_energy(np.array(skew_roots), 850.0, 18500.0, -6000.0, 0.0)["d2G_dx2"]
print(f"Symmetric (L1=0) roots : ({sym_num[0]:.6f}, {sym_num[1]:.6f}) -> midpoint = {0.5*(sym_num[0]+sym_num[1]):.4f}")
print(f"Skewed (L1=-6000) roots : ({skew_roots[0]:.6f}, {skew_roots[1]:.6f}) -> midpoint = {0.5*(skew_roots[0]+skew_roots[1]):.4f}")
print(f"Curvature |d2G/dx2| at roots: {np.max(np.abs(d2_check)):.3e} J/mol")
assert np.max(np.abs(d2_check)) < 1e-8 and 0.5 * (skew_roots[0] + skew_roots[1]) > 0.58
Exercise 3: Implement It Yourself — Asymmetric Subregular Spinodal Solver via Bisection
=======================================================================================
Symmetric (L1=0) roots : (0.257117, 0.742883) -> midpoint = 0.5000
Skewed (L1=-6000) roots : (0.396364, 0.873315) -> midpoint = 0.6348
Curvature |d2G/dx2| at roots: 7.276e-12 J/mol
Summary. A negative (an assumed value) shifts the midpoint of the spinodal from to , so that spinodal decomposition is centred on the B-rich side.