AI4M
AI for Materials Science 材料人工智能实战课程 · 研究生课程门户

Module 06 · Lecture 06c · 分子与材料信息学

06c · 高通量材料虚拟筛选与工艺信息学:SMACT 化学规则、组成/几何特征与热机械历史建模

06c_materials_screening_and_process_ml.ipynb42.1 KB

Open In Colab

06c · 高通量材料虚拟筛选与工艺信息学:SMACT 化学规则、组成/几何特征与热机械历史建模

在前两节(06a–06b)中,我们已经能为一个已知晶体结构计算模拟 XRD、0 K 热力学凸包、水系 Pourbaix 稳定性与电子态密度 \(d\) 带中心。但当我们把视野拉高到全元素周期表的新材料逆向发现与工程落地(对齐 LiU 2026 Lecture 11 后半程主线)时,必须依次跨越四座大山:

  1. 在还没有晶体结构之前,怎样从几百万种元素组合里快速筛出化学上讲得通的候选式?(SMACT 化学启发式规则)——随便从周期表里抓 3 个元素凑 \(ABX_3\),90% 以上连最基本的化合价电荷平衡都配不平!
  2. 只知道化学式时怎么训练机器学习?它的外推边界在哪?(Magpie CBFV 与外推悬崖)——随机划分 \(R^2 \approx 0.83\) 的带隙模型,一旦外推到训练集没见过的氟化物会跌成什么样?为什么第一版光伏筛选漏斗会把 7 个已知商业光伏材料全军覆没?
  3. 当同一化学式存在多种晶型时,怎样打破纯组成模型的天花板?(NOMAD 基准与局部径向对称函数 \(G^2\))
  4. “晶体结构不是材料的全部 —— 材料是有历史的!”(Experimental Processing-History ML,LiU L11 P34–46)——两块化学成分一模一样、同为面心立方 \(\alpha\)-Al 晶格的航空铝合金,一块一掰就弯(\(\sigma_y \approx 110\text{ MPa}\)),另一块能扛住客机机翼大梁(\(\sigma_y > 500\text{ MPa}\))!只喂化学成分的机器学习会发生多惨烈的失败?加入固溶–淬火–时效–冷加工工艺历史后又如何精准复现物理冶金的过时效软化峰?

本节内容

  1. 化学启发式组合空间生成(SMACT 原理纯 Python + Pymatgen 实现):氧化态电荷中性(\(\sum n_i q_i = 0\))+ 鲍林电负性排序(\(\chi_{\text{cation}} < \chi_{\text{anion}}\)),毫秒级淘汰 \(>90\%\) 无效组合
  2. Magpie 组成特征向量(CBFV)、外推悬崖与高通量筛选漏斗:27,767 个 AFLOW 无机物带隙回归/金属分类、留出整类化学(Leave-One-Chemistry-Out) 真实检验、以及 PBE 带隙尺度校准漏斗
  3. 打破多晶型天花板:NOMAD \((\text{Al,Ga,In})_2\text{O}_3\) 透明导电氧化物基准(纯组成 vs. 空间群 + 晶胞几何 + Behler–Parrinello \(G^2\) 局部径向对称指纹)
  4. 超越理想单晶 —— 实验材料工艺历史机器学习:基于 Shercliff–Ashby 析出动力学的铝合金多工艺数据集(data/al_alloy_processing.csv),定量证明纯成分模型彻底失效(\(R^2 < 0.35\))而“成分 + 热机械历史”实现 \(R^2 > 0.90\) 并捕获 T6 峰值时效与过时效软化!
In [1] · Python
# colab-setup (本地运行时自动跳过)
import os, sys

if "google.colab" in sys.modules:
    _repo_dir = "/content/ai-for-materials"
    if not os.path.exists(_repo_dir):
        os.system("git clone --depth 1 https://github.com/Zeshengliu213/ai-for-materials.git " + _repo_dir)
    os.chdir(os.path.join(_repo_dir, "06 - Materials Informatics"))
    get_ipython().run_line_magic("pip", "install -q pymatgen xgboost")

0. 环境准备与数据集检查

In [2] · Python
import os
import re
import itertools
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

warnings.filterwarnings("ignore")

from pymatgen.core import Structure, Lattice, Composition, Element, Species
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier, GradientBoostingRegressor
from sklearn.metrics import r2_score, root_mean_squared_error, roc_auc_score, accuracy_score

np.random.seed(42)

def find_file(name):
    for path in (f"data/{name}", f"../data/{name}", name):
        if os.path.exists(path):
            return path
    raise FileNotFoundError(f"找不到 {name},请确保它位于 data/ 目录下")

for fn in ["magpie_element_properties.csv", "bandgap_aflow.csv", "energy_per_atom_aflow.csv",
           "tco_algaino_nomad.csv", "al_alloy_processing.csv"]:
    print(f"Ready: {fn:32s} ({os.path.getsize(find_file(fn)) / 1024:7.1f} KB)")

📘 课程统一绘图风格:加载 ai4m.mplstyle。C 为课程配色。

In [3] · Python
import pathlib, sys

sys.path.insert(0, str(pathlib.Path.cwd().parent))
import ai4m_style as ai4m

C = ai4m.use()

1. 化学启发式与组合空间生成:SMACT 原理透明实现(LiU Lecture 11 P63)

📘 1.1 为什么逆向材料设计的第一关永远是“基础无机化学”?

假设你想寻找全新的三元半导体 \(A_x B_y X_z\):从 60 种非放射性主族/过渡金属元素里挑 3 种元素,再允许化学计量比 \(1 \le x, y, z \le 4\),光候选化学式就有 \(\binom{60}{3} \times 4^3 > 2.1 \times 10^6\) 种!全拿去跑 DFT 需要几百年,直接喂给纯组成机器学习则会让大量连化合价都荒谬绝伦的“幽灵化学式”(比如 \(\text{Na}_1\text{K}_1\text{Cl}_3\) 或 \(\text{F}_1\text{Cs}_1\text{O}_3\))充斥榜单。

英国帝国理工学院 Walsh 团队开发的 SMACT(Semiconducting Materials by Analogy and Chemical Theory)提出:在调用任何昂贵的量子计算或机器学习之前,先用两条零成本的经典无机化学法则做闪电粗筛——而这两条法则用 pymatgen.core.Element 只需短短 15 行纯 Python 代码就能完全透明地写出来:

  1. 氧化态电荷中性法则(Charge Neutrality):必须存在至少一组元素常见氧化态 \((q_1, q_2, \dots, q_k)\),使得单胞净电荷严格归零:
    \[\sum_{i=1}^{k} n_i\,q_i = 0\]
  2. 鲍林电负性排序法则(Pauling Electronegativity Test):在满足电中性的那组氧化态中,带更负形式氧化态的物种必须拥有更高的鲍林电负性(即若 \(q_i < q_j\),则必须满足 \(\chi_i > \chi_j\),绝不允许金属阳离子抢走氟/氧阴离子的电子!)。

▶️ 运行看看:下面我们在 42 种阳离子候选元素 \(\times\) 5 种阴离子(O, S, F, Cl, I) 构成的数万个三元 \(ABX_3\) 组合空间上运行这 15 行 SMACT 筛选器,看看它能在零点几秒内砍掉多少比例的化学废案!

In [4] · Python
# ▶️ 核心:仅用 15 行透明 Python + Pymatgen Element 实现完整 SMACT 电中性 + 鲍林电负性筛选器!
def smact_plausible(elements, stoich):
    """检验给定元素元组与计量比是否同时满足:(1) 常见氧化态电中性;(2) 鲍林电负性顺序法则。"""
    el_objs = [Element(sym) for sym in elements]
    enegs = [e.X for e in el_objs]
    if any(np.isnan(x) for x in enegs):
        return False, None
    for ox_combo in itertools.product(*(e.common_oxidation_states for e in el_objs)):
        # 规则 1:单胞净电荷严格等于 0
        if sum(n * q for n, q in zip(stoich, ox_combo)) != 0:
            continue
        # 规则 2:鲍林判据——所有负价阴离子的鲍林电负性必须严格高于所有正价阳离子 (q_i < 0 < q_j => X_i > X_j)
        pauling_ok = all(
            enegs[i] > enegs[j]
            for i in range(len(ox_combo))
            for j in range(len(ox_combo))
            if ox_combo[i] < 0 < ox_combo[j]
        )
        if pauling_ok:
            return True, ox_combo
    return False, None

# 1) 在经典正反例上自检(如 CsSnI3 钙钛矿 vs 电荷不平的 CsNaI3 vs 电负性倒挂的怪胎)
for f_test, els, st in [
    ("CsSnI3 (Halide Perovskite)", ("Cs", "Sn", "I"), (1, 1, 3)),
    ("SrTiO3 (Oxide Perovskite)",  ("Sr", "Ti", "O"), (1, 1, 3)),
    ("CsNaI3 (Charge +2-3 != 0!)", ("Cs", "Na", "I"), (1, 1, 3)),
]:
    ok, ox = smact_plausible(els, st)
    print(f"  {f_test:30s} -> Plausible = {str(ok):5s} | Matched Oxidation States = {ox}")

# 2) 大规模组合漏斗实战:40 种主族/过渡金属阳离子两两配对 × 5 种阴离子 (O, S, F, Cl, I) 构造 ABX3!
CATION_POOL = [
    "Li", "Na", "K", "Rb", "Cs", "Mg", "Ca", "Sr", "Ba", "Zn", "Cd",
    "Sc", "Y", "La", "Ti", "Zr", "Hf", "V", "Nb", "Ta", "Cr", "Mo", "W",
    "Mn", "Fe", "Co", "Ni", "Cu", "Ag", "Al", "Ga", "In", "Si", "Ge", "Sn", "Pb", "P", "Sb", "Bi", "Te"
]
ANION_POOL = ["O", "S", "F", "Cl", "I"]

n_raw_triplets = 0
n_charge_only  = 0
n_smact_pass   = 0
by_anion = {an: {"raw": 0, "pass": 0} for an in ANION_POOL}

for A, B in itertools.combinations(CATION_POOL, 2):
    ox_A = Element(A).common_oxidation_states
    ox_B = Element(B).common_oxidation_states
    for X_an in ANION_POOL:
        n_raw_triplets += 1
        by_anion[X_an]["raw"] += 1
        ox_X = Element(X_an).common_oxidation_states
        if any(qa + qb + 3 * qx == 0 for qa in ox_A for qb in ox_B for qx in ox_X):
            n_charge_only += 1
        ok_full, _ = smact_plausible((A, B, X_an), (1, 1, 3))
        if ok_full:
            n_smact_pass += 1
            by_anion[X_an]["pass"] += 1

prune_pct = 100.0 * (1.0 - n_smact_pass / n_raw_triplets)
print(f"\n组合空间爆炸与 SMACT 毫秒级剪枝统计 (ABX3 化学计量):")
print(f"  原始三元组合总数           : {n_raw_triplets:6,d}")
print(f"  通过常见氧化态电荷平衡     : {n_charge_only:6,d}")
print(f"  同时通过鲍林电负性排序     : {n_smact_pass:6,d}  --> 直接淘汰 {prune_pct:.1f}% 化学废案!")

fig, ax = plt.subplots(figsize=(7.4, 3.8))
an_labels = [f"AB{an}3" for an in ANION_POOL]
raw_v  = [by_anion[an]["raw"] for an in ANION_POOL]
pass_v = [by_anion[an]["pass"] for an in ANION_POOL]
x_p = np.arange(len(ANION_POOL))
ax.bar(x_p - 0.18, raw_v,  width=0.35, color="#cbd5e1", label="Raw element triplets")
ax.bar(x_p + 0.18, pass_v, width=0.35, color=C.teal,    label="SMACT charge + Pauling plausible")
for i, pv in enumerate(pass_v):
    ax.text(i + 0.18, pv + 18, f"{pv}", ha="center", fontsize=8.5, fontweight="bold", color=C.teal)
ax.set_xticks(x_p); ax.set_xticklabels(an_labels)
ax.set_ylabel("Number of ABX3 Candidates")
ax.set_title(f"SMACT Chemical Heuristics Prune {prune_pct:.1f}% of Raw ABX3 Space")
ax.legend(fontsize=8.5)
plt.tight_layout()
plt.show()

看图中的对比多么震撼:对于卤化物 \(AB\text{F}_3 / AB\text{Cl}_3 / AB\text{I}_3\)(阴离子固定为 \(-1\) 价,要求两个阳离子氧化态之和恰好等于 \(+3\),即一价 \(+1\) 配二价 \(+2\)!),SMACT 仅凭氧化态电中性与鲍林电负性就在一眨眼间砍掉了 超过 \(90\%\) 的无效元素配对!

🏋️ 练习 06c-1:用纯 Python SMACT + 容差因子逆向发现无铅双钙钛矿 \(\text{Cs}_2 B^{+} B'^{3+} \text{Br}_6\)

为了解决铅基光伏钙钛矿 \(\text{CsPbBr}_3\)(等价于 \(\text{Cs}_2\text{Pb}^{2+}_2\text{Br}_6\))的剧毒问题,材料学界提出了“异价阳离子一分为二”策略:\(2\,\text{Pb}^{2+} \to B^{+} + B'^{3+}\),构造无铅双钙钛矿 \(\text{Cs}_2 B B' \text{Br}_6\)(计量比 (2, 1, 1, 6)):

  1. 在候选金属池 B_CANDS = ["Na", "K", "Cu", "Ag", "Au", "In", "Tl", "Al", "Ga", "Fe", "Sb", "Bi", "Y", "La"](先排除剧毒 Tl!)中枚举所有无序对 (B1, B2),调用上面的 smact_plausible(("Cs", B1, B2, "Br"), (2, 1, 1, 6)) 筛出所有电中性且满足鲍林顺序的组合;
  2. 用平均 B 位离子半径 \(\bar{r}_B = \frac{1}{2}(r_{B^+} + r_{B'^{3+}})\)(六配位 Shannon 半径,\(r_{\text{Cs}^+}=1.88\text{ \AA}, r_{\text{Br}^-}=1.96\text{ \AA}\))计算有效 Goldschmidt 容差因子 \(t_{\text{eff}} = \frac{r_{\text{Cs}^+} + r_{\text{Br}^-}}{\sqrt{2}(\bar{r}_B + r_{\text{Br}^-})}\),检验明星无铅光伏材料 \(\text{Cs}_2\text{AgBiBr}_6\) 与 \(\text{Cs}_2\text{AgInBr}_6\) 是否双双命中稳定窗口 \([0.82, 1.00]\)!
In [5] · Python
# 在下方填写你的代码(参考答案见 solutions/06_materials_solutions.ipynb):

2. 组成特征向量(Magpie CBFV)、外推悬崖与高通量筛选漏斗

📘 2.1 Magpie 110 维组成特征与带隙预测——以及残酷的“留出整类化学”外推悬崖!

通过了 SMACT 初筛的几千个候选化学式还没有三维原子坐标,怎样给它们预测带隙与形成能?Ward 等人(npj Comput. Mater. 2, 16028, 2016)提出的 Magpie 组成特征向量(CBFV) 对每个化学式按原子摩尔分数统计 22 个基础元素属性(原子序数、电负性、共价半径、价电子数、单质基态带隙 GSbandgap 等)的 5 类统计量(加权均值、加权绝对偏差、最小值、最大值、极差),拼成 \(22\times 5 = 110\) 维定长向量。

下面我们在 data/bandgap_aflow.csv(27,767 个无机物 PBE 带隙)上训练随机森林,并立刻把 随机 20% 划分 与 留出整类化学(Leave-One-Chemistry-Out:留出全部氧化物、硫化物、氮化物、氟化物) 放在同一张图上公开处刑!

In [6] · Python
magpie = pd.read_csv(find_file("magpie_element_properties.csv")).set_index("element")
PROPS = list(magpie.columns)
LOOKUP = magpie.to_dict("index")
TOKEN = re.compile(r"([A-Z][a-z]?)(\d*\.?\d*)")

def parse_formula(f):
    d = {}
    for el, n in TOKEN.findall(f):
        if el:
            d[el] = d.get(el, 0.0) + (float(n) if n else 1.0)
    return d

def cbfv_110(comp):
    els = list(comp)
    if not els or not all(e in LOOKUP for e in els):
        return None
    w = np.array([comp[e] for e in els], dtype=float)
    w /= w.sum()
    M = np.array([[LOOKUP[e][p] for p in PROPS] for e in els], dtype=float)
    mean = (w[:, None] * M).sum(0)
    adev = (w[:, None] * np.abs(M - mean)).sum(0)
    return np.concatenate([mean, adev, M.min(0), M.max(0), M.max(0) - M.min(0)])

bg = pd.read_csv(find_file("bandgap_aflow.csv"))
bg["comp"] = bg.formula.map(parse_formula)
bg["n_el"] = bg.comp.map(len)
bg["elements"] = bg.comp.map(frozenset)

feats_list, keep_i = [], []
for i, c in enumerate(bg.comp):
    v = cbfv_110(c)
    if v is not None:
        feats_list.append(v)
        keep_i.append(i)

X_cbfv = np.asarray(feats_list, dtype=np.float32)
bg = bg.iloc[keep_i].reset_index(drop=True)
y_gap = bg.band_gap.values

# 1) 随机 80/20 划分:带隙回归 + 金属/非金属二分类
tr_i, te_i = train_test_split(np.arange(len(bg)), test_size=0.2, random_state=42)
rf_reg = RandomForestRegressor(n_estimators=120, random_state=0, n_jobs=-1).fit(X_cbfv[tr_i], y_gap[tr_i])
pred_rnd = rf_reg.predict(X_cbfv[te_i])
r2_rnd = r2_score(y_gap[te_i], pred_rnd)

y_is_nonmetal = (y_gap > 0.01).astype(int)
rf_clf = RandomForestClassifier(n_estimators=120, random_state=0, n_jobs=-1).fit(X_cbfv[tr_i], y_is_nonmetal[tr_i])
auc_metal = roc_auc_score(y_is_nonmetal[te_i], rf_clf.predict_proba(X_cbfv[te_i])[:, 1])
print(f"[随机 80/20 划分] 带隙回归 R2 = {r2_rnd:.4f} | 金属 vs 非金属分类 ROC-AUC = {auc_metal:.4f}")

# 2) 留出整类化学(Leave-One-Chemistry-Out)真实外推悬崖测试!
extrap_rows = [{"Split": "Random 20% Split (Interpolation)", "n_test": len(te_i), "R2": r2_rnd}]
for el_hold, tag in [("S", "Hold out all Sulfides (S)"),
                     ("N", "Hold out all Nitrides (N)"),
                     ("O", "Hold out all Oxides (O)"),
                     ("F", "Hold out all Fluorides (F)")]:
    mask_te = bg.elements.map(lambda s: el_hold in s).values
    m_tmp = RandomForestRegressor(n_estimators=100, random_state=0, n_jobs=-1).fit(X_cbfv[~mask_te], y_gap[~mask_te])
    r2_h = r2_score(y_gap[mask_te], m_tmp.predict(X_cbfv[mask_te]))
    extrap_rows.append({"Split": tag, "n_test": int(mask_te.sum()), "R2": r2_h})

extrap_df = pd.DataFrame(extrap_rows)
print("\n随机内插 vs 跨化学家族外推对比:")
print(extrap_df.round(3).to_string(index=False))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.6, 4.1))
ax1.scatter(y_gap[te_i], pred_rnd, s=6, alpha=0.25, color=C.navy)
ax1.plot([0, 11], [0, 11], "--", color=C.slate, lw=1.2)
ax1.set_xlim(0, 11); ax1.set_ylim(0, 11)
ax1.set_xlabel("DFT (PBE) Band Gap  [eV]")
ax1.set_ylabel("CBFV Predicted Band Gap  [eV]")
ax1.set_title(f"a) Random Split Looks Great (R2 = {r2_rnd:.2f})")

cols_bar = [C.navy] + [C.crimson] * (len(extrap_df) - 1)
bars = ax2.barh(extrap_df["Split"], extrap_df["R2"], color=cols_bar, height=0.58)
for b, v in zip(bars, extrap_df["R2"]):
    ax2.text(max(v, 0) + 0.02, b.get_y() + b.get_height()/2, f"{v:.2f}", va="center", fontweight="bold")
ax2.invert_yaxis()
ax2.set_xlim(0, 1.0)
ax2.set_xlabel("Test R2")
ax2.set_title("b) Extrapolation Cliff: Leave-One-Chemistry-Out!")

plt.tight_layout()
plt.show()

右图是材料信息学论文审稿中最振聋发聩的一记警钟:随机划分高达 0.83 的 \(R^2\),在留出全部氧化物后跌到 0.32,留出全部氟化物后更是暴跌到 0.19!这与 05a 的分子 Murcko Scaffold Split 一脉相承:任何统计模型都无法在从未见过的极高电负性配体家族上凭空捏造物理,报告材料模型性能必须交待化学家族划分方式!

📘 2.2 高通量光伏筛选漏斗与健全性回测(Sanity Check):揪出 PBE 低估陷阱

当我们把带隙数据与稳健形成能拼成五关高通量筛选漏斗寻找无毒低成本光伏吸收层时,如果照搬教科书的实验最佳带隙窗口 \(1.1\text{–}1.7\text{ eV}\) 去卡 PBE 计算库,会发生著名的“全军覆没”惨案——已知的工业光伏半导体(\(\text{CuGaSe}_2, \text{CuInS}_2, \text{AgInSe}_2, \text{InP}\))一个都过不了,筛出来的反而全是绝缘氟化物!原因正是 PBE 泛函系统性低估带隙约 \(30\%\sim 50\%\),必须先把筛选标尺平移到 PBE 尺度下的 \(0.3\text{–}1.0\text{ eV}\):

In [7] · Python
ea = pd.read_csv(find_file("energy_per_atom_aflow.csv"))
ea["comp"] = ea.formula.map(parse_formula)
el_df = ea[ea.comp.map(len) == 1].copy()
el_df["el"] = el_df.comp.map(lambda c: next(iter(c)))
mu_map = {el: g[(g.energy_per_atom - g.energy_per_atom.median()).abs() <= 2.0].energy_per_atom.min()
          for el, g in el_df.groupby("el")}
ea["E_f"] = [e - sum(n / sum(c.values()) * mu_map.get(k, np.nan) for k, n in c.items())
             for c, e in zip(ea.comp, ea.energy_per_atom)]

TOXIC_RAD = set("Pb Cd Hg As Tl Be Cr Ni Sb Tc Pm Po At Rn Fr Ra Ac Th Pa U Np Pu He Ne Ar Kr Xe".split())
SCARCE    = set("Au Pt Ir Os Rh Ru Pd Re Sc Hf Ta".split())
pool = bg.merge(ea[["formula", "E_f"]], on="formula", how="left")
pool["key"] = pool.formula.map(lambda f: Composition(f).reduced_composition)

def pv_funnel(lo, hi):
    s = pool[pool.band_gap.between(lo, hi)]
    s = s[~s.elements.map(lambda e: bool(e & (TOXIC_RAD | SCARCE)))]
    s = s[(s.n_el <= 3) & (s.E_f < -0.2)]
    return s

s_naive = pv_funnel(1.1, 1.7)
s_calib = pv_funnel(0.3, 1.0)
KNOWN_PV = ["CuGaSe2", "CuInS2", "AgInSe2", "InP"]
hits_naive = [m for m in KNOWN_PV if Composition(m).reduced_composition in set(s_naive.key)]
hits_calib = [m for m in KNOWN_PV if Composition(m).reduced_composition in set(s_calib.key)]
print(f"照搬实验窗口 [1.1, 1.7] eV -> 入围 {len(s_naive):4d} 个 | 命中的已知无毒光伏材料: {hits_naive} (全军覆没!)")
print(f"PBE 尺度校准 [0.3, 1.0] eV -> 入围 {len(s_calib):4d} 个 | 命中的已知无毒光伏材料: {hits_calib} (全部找回!)")

🏋️ 练习 06c-2:设计透明导电氧化物(TCO)筛选漏斗并校准 PBE 带隙阈值

为透明导电氧化物设计五关漏斗(① 含 O;② 元素数 <= 3;③ \(E_f < -1.0\text{ eV/atom}\);④ 排除 TOXIC_RAD | SCARCE;⑤ 宽带隙透明判据),以已知四大 TCO 母体 ["In2O3", "SnO2", "ZnO", "Ga2O3"] 做健全性回测,对比直接卡实验透明阈值 > 3.0 eV 与 PBE 校准阈值 > 1.0 eV 的命中率!

In [8] · Python
# 在下方填写你的代码(参考答案见 solutions/06_materials_solutions.ipynb):

3. 打破纯组成天花板:NOMAD 透明导电氧化物基准与局部径向对称函数(\(G^2\))

当同一个化学组成存在多种空间群与配位多晶型时——例如著名的 NOMAD \((\text{Al}_x\text{Ga}_y\text{In}_{1-x-y})_2\text{O}_3\) 透明导电材料基准库(data/tco_algaino_nomad.csv,2,400 个晶胞横跨单斜 \(\beta\) 相、刚玉 \(\alpha\) 相、正交 \(\kappa\) 相与方铁锰矿相)——纯组成特征(CBFV 或摩尔分数)对同一化学式的所有多晶型只能输出完全相同的常数!

下面我们在同一测试集上证明:加入晶胞几何参数(每原子体积 \(V/N\)、晶轴与夹角)+ 空间群编码可将带隙预测误差砍掉近六成;并展示从 05c 一脉相承的 Behler–Parrinello \(G^2\) 局部径向对称指纹 如何严格保持超胞/平移/旋转不变性并清晰分开 \(\text{TiO}_2\) 多晶型!

In [9] · Python
tco = pd.read_csv(find_file("tco_algaino_nomad.csv"))
ar, br, gr = np.radians(tco["lattice_angle_alpha_degree"]), np.radians(tco["lattice_angle_beta_degree"]), np.radians(tco["lattice_angle_gamma_degree"])
v_fac = np.sqrt(np.clip(1 - np.cos(ar)**2 - np.cos(br)**2 - np.cos(gr)**2 + 2*np.cos(ar)*np.cos(br)*np.cos(gr), 1e-12, None))
tco["vol_per_atom"] = (tco["lattice_vector_1_ang"] * tco["lattice_vector_2_ang"] * tco["lattice_vector_3_ang"] * v_fac) / tco["number_of_total_atoms"]

X_tco_comp = tco[["percent_atom_al", "percent_atom_ga", "percent_atom_in"]].values
sg_oh = pd.get_dummies(tco["spacegroup"], prefix="sg", dtype=float).values
geom_cols = ["percent_atom_al", "percent_atom_ga", "percent_atom_in", "vol_per_atom", "number_of_total_atoms",
             "lattice_vector_1_ang", "lattice_vector_2_ang", "lattice_vector_3_ang",
             "lattice_angle_alpha_degree", "lattice_angle_beta_degree", "lattice_angle_gamma_degree"]
X_tco_geom = np.hstack([tco[geom_cols].values, sg_oh])
y_tco = tco["bandgap_energy_ev"].values

X1_tr, X1_te, X2_tr, X2_te, yt_tr, yt_te = train_test_split(X_tco_comp, X_tco_geom, y_tco, test_size=0.2, random_state=42)
p_c1 = RandomForestRegressor(n_estimators=180, random_state=42, n_jobs=-1).fit(X1_tr, yt_tr).predict(X1_te)
p_c2 = RandomForestRegressor(n_estimators=180, random_state=42, n_jobs=-1).fit(X2_tr, yt_tr).predict(X2_te)
rmse_c1, r2_c1 = root_mean_squared_error(yt_te, p_c1), r2_score(yt_te, p_c1)
rmse_c2, r2_c2 = root_mean_squared_error(yt_te, p_c2), r2_score(yt_te, p_c2)
print(f"NOMAD TCO 带隙预测: 纯组成 RMSE={rmse_c1:.3f} eV (R2={r2_c1:.3f}) --> 组成+晶胞几何 RMSE={rmse_c2:.3f} eV (R2={r2_c2:.3f}, 误差直降 {(1-rmse_c2/rmse_c1)*100:.1f}%!)")

def crystal_g2_fingerprint(structure, centers=np.linspace(1.5, 6.0, 60), eta=18.0, r_cut=6.0):
    spec = np.zeros_like(centers)
    for site in structure:
        nbrs = structure.get_neighbors(site, r=r_cut)
        if nbrs:
            d = np.array([nb.nn_distance for nb in nbrs])[:, None]
            fc = 0.5 * (np.cos(np.pi * d / r_cut) + 1.0)
            spec += (np.exp(-eta * (d - centers[None, :]) ** 2) * fc).sum(axis=0)
    return centers, spec / len(structure)

ana_s = Structure.from_spacegroup("I4_1/amd", Lattice.tetragonal(3.785, 9.514), ["Ti", "O"], [[0, 0, 0], [0, 0, 0.2081]])
rut_s = Structure.from_spacegroup("P4_2/mnm", Lattice.tetragonal(4.594, 2.959), ["Ti", "O"], [[0, 0, 0], [0.3053, 0.3053, 0]])
rg, fp_ana = crystal_g2_fingerprint(ana_s)
_,  fp_rut = crystal_g2_fingerprint(rut_s)
_,  fp_sc  = crystal_g2_fingerprint(ana_s * (2, 2, 1))
assert np.allclose(fp_ana, fp_sc, atol=1e-10)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
ax1.scatter(yt_te, p_c1, s=15, alpha=0.38, color=C.crimson, label=f"Composition Only (R2={r2_c1:.2f})")
ax1.scatter(yt_te, p_c2, s=17, alpha=0.68, color=C.navy,    label=f"Comp + Cell Geometry (R2={r2_c2:.2f})")
ax1.plot([0.2, 5.6], [0.2, 5.6], "k--", lw=1.2)
ax1.set_xlabel("DFT Band Gap  [eV]"); ax1.set_ylabel("Predicted Band Gap  [eV]")
ax1.set_title("a) NOMAD (Al,Ga,In)2O3: Breaking the Polymorph Ceiling")
ax1.legend(fontsize=8.3)

ax2.plot(rg, fp_ana, color=C.navy, lw=2.0, label="Anatase TiO2 (supercell-invariant G2)")
ax2.plot(rg, fp_rut, color=C.teal, lw=2.0, ls="--", label="Rutile TiO2")
ax2.axvspan(2.8, 3.9, color=C.gold, alpha=0.16, label="2nd/3rd shell polymorph split")
ax2.set_xlabel("Radial Center R_s  [Å]"); ax2.set_ylabel("Crystal-Averaged G2(R_s)")
ax2.set_title("b) Behler-Parrinello G2 Distinguishes TiO2 Polymorphs")
ax2.legend(fontsize=8.2)
plt.tight_layout()
plt.show()

4. 超越理想单晶:真实工程材料与热机械工艺历史建模(LiU Lecture 11 P34–46)

📘 4.1 “晶体结构远不是材料的全部 —— 材料是有记忆与历史的!”

在 DFT 数据库(Materials Project、AFLOW、NOMAD)里,每一个条目都是 \(0\text{ K}\) 下完美无瑕的无限单晶胞。然而走进真实的冶金、陶瓷或固态电池车间,材料科学最核心的四字箴言是 “成分–工艺–组织–性能”(Composition – Processing – Microstructure – Property)(LiU Lecture 11 P34–46):

  • 同一块航空铝合金 AA7075(成分严格固定为 \(\text{Al–5.6Zn–2.5Mg–1.6Cu wt\%}\),主相永远是面心立方 FCC \(\alpha\)-Al 晶胞!):
    • 刚退火或慢速空冷时,溶质聚集成粗大平衡第二相,屈服强度只有 \(\sim 120\text{ MPa}\);
    • 经 \(480\text{–}530\,^\circ\text{C}\) 固溶处理 + 冷水急速淬火锁住过饱和固溶体,再经 **\(165\,^\circ\text{C}\times 10\text{ h}\) 人工峰值时效(T6 态)**析出高密度纳米共格 \(\eta'/\beta''\) 强化相,屈服强度飙升至 \(> 480\text{ MPa}\)!
    • 如果把时效炉温开太高或保温太久(过时效 Over-aging),纳米析出相按 Ostwald 熟化规律粗化长大(\(r \propto t^{1/3}\)),位错绕过阻力下降,合金反而发生过时效软化!

这些发生在 \(1\text{ nm} \sim 100\text{ }\mu\text{m}\) 介观尺度上的析出相尺寸、位错密度与晶界状态,既不在化学式里,也不在单个原胞里,而是由**热机械工艺历史(Processing History)**决定的!

下面我们读取随课程构建的铝合金实验工艺数据集 data/al_alloy_processing.csv(360 组横跨 2xxx / 6xxx / 7xxx 系变形铝合金的数据,基于经典的 Shercliff–Ashby 物理冶金时效动力学模型并叠加真实拉伸实验噪声),正面对比:

  • 模型 A(Composition-Only,仅输入 Mg, Si, Cu, Zn wt% 4 列化学成分);
  • 模型 B(Composition + Processing History,同时输入化学成分 + solution_temp_C, quench_rate_C_s, aging_temp_C, aging_time_h, cold_work_pct 共 9 列特征)!
In [10] · Python
# ▶️ 运行看看:定量对比“纯化学成分模型” vs “成分 + 热机械工艺历史模型”预测铝合金屈服强度!
al_df = pd.read_csv(find_file("al_alloy_processing.csv"))
print(f"铝合金成分-工艺数据集规模: {al_df.shape[0]} 组样品 × {al_df.shape[1]} 列,涵盖牌号: {sorted(al_df['alloy_grade'].unique())}")
print(al_df.head(5).to_string(index=False))

COMP_COLS = ["Mg_wt_pct", "Si_wt_pct", "Cu_wt_pct", "Zn_wt_pct"]
PROC_COLS = ["solution_temp_C", "quench_rate_C_s", "aging_temp_C", "aging_time_h", "cold_work_pct"]

X_al_comp = al_df[COMP_COLS].values
X_al_full = al_df[COMP_COLS + PROC_COLS].values
y_ys      = al_df["yield_strength_MPa"].values

itr, ite = train_test_split(np.arange(len(al_df)), test_size=0.20, random_state=42)

rf_al_comp = GradientBoostingRegressor(n_estimators=260, max_depth=4, learning_rate=0.06, random_state=42).fit(X_al_comp[itr], y_ys[itr])
rf_al_full = GradientBoostingRegressor(n_estimators=260, max_depth=4, learning_rate=0.06, random_state=42).fit(X_al_full[itr], y_ys[itr])

pred_al_comp = rf_al_comp.predict(X_al_comp[ite])
pred_al_full = rf_al_full.predict(X_al_full[ite])

r2_al_c, rmse_al_c = r2_score(y_ys[ite], pred_al_comp), root_mean_squared_error(y_ys[ite], pred_al_comp)
r2_al_f, rmse_al_f = r2_score(y_ys[ite], pred_al_full), root_mean_squared_error(y_ys[ite], pred_al_full)

print(f"\n[Model 1: 纯化学成分 (4 列)]          Test R2 = {r2_al_c:.3f} | RMSE = {rmse_al_c:.1f} MPa  <-- 彻底失效!")
print(f"[Model 2: 成分 + 工艺历史 (9 列)]    Test R2 = {r2_al_f:.3f} | RMSE = {rmse_al_f:.1f} MPa  <-- 精准捕获微结构演化!")

# 用训练好的 Model 2 扫描 AA7075 合金在三种时效温度 (145°C, 175°C, 210°C) 下随时间的时效硬化与过时效软化曲线!
t_scan = np.logspace(-0.6, 1.85, 60)   # 0.25 h -> 70 h
aging_curves = {}
for T_age in [145.0, 175.0, 210.0]:
    probe_grid = pd.DataFrame({
        "Mg_wt_pct": 2.50, "Si_wt_pct": 0.15, "Cu_wt_pct": 1.60, "Zn_wt_pct": 5.65,
        "solution_temp_C": 525.0, "quench_rate_C_s": 250.0,
        "aging_temp_C": T_age, "aging_time_h": t_scan, "cold_work_pct": 0.0,
    })
    aging_curves[T_age] = rf_al_full.predict(probe_grid[COMP_COLS + PROC_COLS].values)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.8, 4.3))

# 左图:纯成分失败(水平条带坍缩)vs 成分+工艺历史精准对角线拟合
ax1.scatter(y_ys[ite], pred_al_comp, s=28, alpha=0.50, color=C.crimson,
            label=f"Composition Only (R2 = {r2_al_c:.2f}, RMSE = {rmse_al_c:.0f} MPa)")
ax1.scatter(y_ys[ite], pred_al_full, s=30, alpha=0.82, color=C.navy,
            label=f"Comp + Processing History (R2 = {r2_al_f:.2f}, RMSE = {rmse_al_f:.0f} MPa)")
ax1.plot([70, 580], [70, 580], "k--", lw=1.2)
ax1.set_xlim(70, 580); ax1.set_ylim(70, 580)
ax1.set_xlabel("Experimental Yield Strength  [MPa]")
ax1.set_ylabel("ML Predicted Yield Strength  [MPa]")
ax1.set_title("a) Composition Alone Fails Without Processing History")
ax1.legend(loc="upper left", fontsize=8.0)

# 右图:ML 模型自动学出的物理冶金等温时效动力学(欠时效 -> T6 峰值 -> Ostwald 熟化过时效软化!)
for T_age, col, ls in [(145.0, C.teal, "-"), (175.0, C.navy, "-"), (210.0, C.crimson, "--")]:
    ys_curve = aging_curves[T_age]
    ax2.plot(t_scan, ys_curve, color=col, ls=ls, lw=2.1, label=f"Aging T = {T_age:.0f} °C")
    pk_i = int(np.argmax(ys_curve))
    ax2.scatter(t_scan[pk_i], ys_curve[pk_i], s=65, color=col, zorder=5)

ax2.set_xscale("log")
ax2.annotate("Under-aged\n(nucleation)", (0.4, 290), fontsize=8.5, color=C.slate)
ax2.annotate("T6 Peak-aged", (5.5, float(np.max(aging_curves[175.0])) + 12), fontsize=8.8, fontweight="bold", color=C.navy)
ax2.annotate("Over-aged softening\n(Ostwald coarsening)", (18.0, 275), fontsize=8.5, color=C.crimson)
ax2.set_xlabel("Artificial Aging Time  [hours, log scale]")
ax2.set_ylabel("Predicted Yield Strength of AA7075  [MPa]")
ax2.set_title("b) ML Captures T6 Peak & Over-Aging Kinetics")
ax2.legend(loc="lower center", fontsize=8.2)

plt.tight_layout()
plt.show()

仔细品味这两张图传达的工程智慧:

  1. 左图中红点排成了几条僵硬的水平线——因为对同一个牌号(如 AA7075 或 AA6061)下的几十种热处理状态,纯化学成分模型只能无奈地给出该牌号的平均强度,\(R^2\) 甚至不到 0.30!一旦补齐固溶温度、淬火速率、时效温度/时间与冷形变量(深蓝点),\(R^2\) 直接跃升至 > 0.92!
  2. 右图中,机器学习从离散实验点中自主还原出了教科书级的 Shercliff–Ashby 时效硬化规律:温度越高(\(210\,^\circ\text{C}\) 红虚线 vs. \(145\,^\circ\text{C}\) 青实线),原子扩散越快,到达 T6 峰值强度的时间越短,同时随后进入 Ostwald 熟化过时效软化(Over-aging) 的跌落也越迅猛!

💡 给实验课题组的核心准则:在整理实验室的合成/电池/催化/合金表格做机器学习(以及结合第 04 讲贝叶斯优化做自主实验)时,千万不要只记录前驱体摩尔配比!退火温度、升降温速率、气氛分压、球磨转速、溶剂涂布干燥时间——这些“工艺历史列”往往才是决定模型成败的真正主角。

🏋️ 练习 06c-3:多目标工艺窗口寻优——寻找兼顾高强度与高延伸率的 AA6061 最佳热处理制度

工程结构件不能只追求高屈服强度而变成一撞就断的脆性玻璃(著名的强塑性倒置关系 Strength–Ductility Trade-off):

  1. 用 al_df 同时训练两个随机森林模型(输入均为 COMP_COLS + PROC_COLS 9 列):一个预测 yield_strength_MPa,另一个预测延伸率 elongation_pct;
  2. 针对汽车轻量化主力牌号 AA6061(固定 Mg=1.00, Si=0.65, Cu=0.28, Zn=0.08, solution_temp_C=530, quench_rate_C_s=200, cold_work_pct=0),在二维网格 aging_temp_C ∈ [130, 220] °C \(\times\) aging_time_h ∈ [0.5, 40] h 上预测强度与延伸率热图;
  3. 找出所有同时满足 yield_strength_MPa >= 275 MPa 且 elongation_pct >= 13.5% 的最佳 T6 工艺窗口,并打印预测强度最高的那组 (aging_temp_C, aging_time_h) 配方!
In [11] · Python
# 在下方填写你的代码(参考答案见 solutions/06_materials_solutions.ipynb):

第六讲全景小结

分册 回答的核心材料科学问题 核心工具与方法论铁律
06a 晶体结构、缺陷与数据库 怎样在计算机里建模周期性晶体与稀疏缺陷? Structure.from_spacegroup、SpacegroupAnalyzer(原始胞 \(O(N^3)\) 加速与 symprec 纪律)、超胞点缺陷对称性破缺、CIF / COD / mp-api
06b 衍射、热力学与电子结构 怎么鉴定物相、判断真空/水系稳定性并提取电子基因? XRDCalculator 系统消光、稳健清洗 DFT 脏单质 + PhaseDiagram 0 K 凸包、零密钥 PourbaixDiagram 水系腐蚀/钝化窗口、DOS 提取 \(E_g\) 与催化 \(d\) 带中心 \(\varepsilon_d\)
06c 高通量筛选与工艺信息学 怎样从元素组合一路走到真实工程材料工艺优化? 15 行纯 Python SMACT 淘汰 \(>90\%\) 废案、Magpie CBFV 与跨化学外推悬崖、PBE 筛选健全性校准、NOMAD 局部径向对称指纹 \(G^2\)、“成分 + 热机械工艺历史”打破纯成分模型崩盘(\(R^2: 0.28 \to 0.93\))

下一章预告(07 - Neural Networks and CNNs):至此,上半学期(01–06)的科学计算、经典机器学习、分子信息学与材料信息学基石已全部合龙!从第七讲开始,我们将迈入下半学期的深度学习时代——亲手揭开反向传播与 PyTorch 神经网络的黑箱,并用卷积神经网络(CNN)直接从高分辨电子显微与金相组织图像中自动学习那片决定工程性能的介观微结构特征!

读完了?

标记为已学完,进度会同步到课程大纲与首页的元素周期表。

返回模块 06