10c · 晶体图神经网络(CGCNN)与机器学习原子间势函数(MLIP)
本节定位:全课程的收官之战!在
10a和10b中,我们学会了用分子图神经网络(GNN / D-MPNN)直接从原子和化学键预测有机分子性质。但在材料科学中,无机晶体、金属合金、电池电极、钙钛矿不是孤立分子,而是三维周期性无限晶格;而且我们不仅想预测静态性质(如带隙、形成能),还想以接近 DFT 的精度、快 10,000 倍的速度跑分子动力学(MD)模拟!学习目标:
- 理解**晶体多图(Crystal Multi-Graph)**如何处理周期性边界条件(PBC)与高斯径向基展开(GBF);
- 用约 40 行纯 PyTorch 手写 CGCNN 门控晶体图卷积层,并实测验证其平移、旋转与原子编号置换不变性;
- 在 CPU 上训练迷你 CGCNN,预测不同晶体结构与应变下的势能;
- 亲手实现能量守恒的机器学习势函数(MLIP):通过 PyTorch 自动微分求力 \(\mathbf{F}_i = -\nabla_{\mathbf{R}_i} E\),并运行微正则系综(NVE)分子动力学验证能量守恒;
- 了解现代通用等变势函数(MACE / NequIP / CHGNet)如何通过 \(E(3)\) 等变性统治当今计算材料学。
0. 环境准备与统一样式
import pathlib, sys, warnings
warnings.filterwarnings("ignore")
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from pymatgen.core import Lattice, Structure
# 加载课程统一绘图风格
sys.path.insert(0, str(pathlib.Path.cwd().parent))
import ai4m_style as ai4m
C = ai4m.use()
def set_seed(seed=42):
np.random.seed(seed)
torch.manual_seed(seed)
set_seed(42)
print(f"PyTorch {torch.__version__} | Device: CPU")
PyTorch 2.8.0+cpu | Device: CPU
1. 📘 从分子图到晶体图:为什么普通 GNN 不够用?
在 06a 我们学过,晶体由**晶胞(Unit Cell)和周期性边界条件(PBC)**定义。把分子 GNN(10a)搬到晶体上,会立刻遇到三个新物理挑战:
- 没有明确的“共价键”:金属 Cu 或离子晶体 NaCl 中没有单键/双键概念,原子通过截断半径 \(r_{\text{cut}}\)(例如 \(5\text{–}6\,\text{\AA}\))内的近邻距离相互作用。
- 多图结构(Multi-Graph):在周期性晶胞中,原子 \(i\) 可能同时与原子 \(j\) 的多个周期性镜像相邻!因此同一对原子 \((i, j)\) 之间可以存在多条不同距离的边。
- 连续距离编码(高斯径向基 GBF):不能只传一个标量距离 \(d_{ij}\),而要把它展开成 \(K\) 维平滑的高斯径向基向量:
\[e_{ij}^{(k)} = \exp\!\left(-\gamma (d_{ij} - \mu_k)^2\right), \quad k = 1, \dots, K\]这样神经网络可以像“多通道测距仪”一样精确分辨键长微小变化(哪怕 \(0.02\,\text{\AA}\) 的应变!)。
▶️ 下面我们用 pymatgen 构造 FCC Cu 和 Rock-salt NaCl 晶体,并可视化周期性近邻图与高斯径向基展开。
# 构造 FCC Cu 与 Rock-salt NaCl 原胞
cu_struct = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.615), ["Cu"], [[0, 0, 0]])
nacl_struct = Structure.from_spacegroup("Fm-3m", Lattice.cubic(5.640), ["Na", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]])
def build_crystal_graph(struct: Structure, r_cut: float = 4.5, max_nbrs: int = 12):
"""将 pymatgen Structure 转换为周期性晶体图 (z_nums, edge_src, edge_dst, edge_dist)."""
z_nums = np.array([site.specie.Z for site in struct], dtype=np.int64)
all_nbrs = struct.get_all_neighbors(r_cut)
src, dst, dist = [], [], []
for i, nbrs in enumerate(all_nbrs):
nbrs_sorted = sorted(nbrs, key=lambda n: n.nn_distance)[:max_nbrs]
for nbr in nbrs_sorted:
src.append(i)
dst.append(nbr.index)
dist.append(nbr.nn_distance)
return (
torch.tensor(z_nums, dtype=torch.long),
torch.tensor(src, dtype=torch.long),
torch.tensor(dst, dtype=torch.long),
torch.tensor(dist, dtype=torch.float32),
)
z_cu, src_cu, dst_cu, dist_cu = build_crystal_graph(cu_struct, r_cut=4.0, max_nbrs=12)
print(f"FCC Cu unit cell: {len(z_cu)} atoms, {len(dist_cu)} periodic edges (12 nearest neighbors per atom!)")
print(f"Nearest-neighbor distance: {dist_cu.min():.3f} Å (theoretical a/√2 = {3.615/np.sqrt(2):.3f} Å)")
# 可视化高斯径向基函数 (GBF)
d_grid = np.linspace(1.5, 5.5, 400)
centers = np.linspace(1.8, 5.2, 8)
gamma = 4.0
fig, ax = plt.subplots(figsize=(7.5, 3.4))
for k, mu in enumerate(centers):
ax.plot(d_grid, np.exp(-gamma * (d_grid - mu) ** 2), lw=1.8, alpha=0.85,
color=C.navy if k % 2 == 0 else C.teal)
ax.axvline(dist_cu.min().item(), color=C.crimson, ls="--", lw=1.8, label=f"Cu–Cu 1st shell ({dist_cu.min():.2f} Å)")
ax.set_xlabel("Interatomic Distance d_ij (Å)")
ax.set_ylabel("Gaussian Basis Activation")
ax.set_title("Gaussian Basis Function (GBF) Expansion of Interatomic Distances")
ax.legend()
plt.show()
FCC Cu unit cell: 4 atoms, 48 periodic edges (12 nearest neighbors per atom!) Nearest-neighbor distance: 2.556 Å (theoretical a/√2 = 2.556 Å)
2. 📘 40 行纯 PyTorch 手写 CGCNN(Crystal Graph Convolutional Neural Network)
Xie & Grossman (Phys. Rev. Lett. 2018) 提出的 CGCNN 是无机晶体深度学习的里程碑。它的核心消息传递公式非常优雅——引入了门控机制(Gated Convolution),让网络自动学习哪些近邻键更重要:
- \(\sigma\) 是 Sigmoid 函数(控制“通透率”:近距离强键权重接近 1,远距离弱键权重接近 0);
- \(g\) 是 Softplus 激活函数;
- 残差连接 \(+\mathbf{v}_i^{(t)}\) 让多层消息传递更稳定;
- 最后对所有原子的隐向量取平均池化(Mean Pooling),得到每原子能量(eV/atom)——这天然满足超胞尺度不变性(2×2×2 超胞的每原子能量与原胞完全一致!)。
▶️ 下面我们用纯 PyTorch 写出完整的 MiniCGCNN,并立刻做物理对称性体检!
class GaussianDistance(nn.Module):
def __init__(self, dmin=1.5, dmax=5.5, n_bins=24):
super().__init__()
centers = torch.linspace(dmin, dmax, n_bins)
step = (dmax - dmin) / (n_bins - 1)
self.register_buffer("centers", centers)
self.gamma = 1.0 / (step ** 2)
def forward(self, dist):
return torch.exp(-self.gamma * (dist.unsqueeze(-1) - self.centers) ** 2)
class CGCNNLayer(nn.Module):
def __init__(self, node_dim: int, edge_dim: int):
super().__init__()
self.fc_full = nn.Linear(2 * node_dim + edge_dim, 2 * node_dim)
self.bn = nn.BatchNorm1d(node_dim)
def forward(self, v, edge_src, edge_dst, e_feat):
z_ij = torch.cat([v[edge_src], v[edge_dst], e_feat], dim=-1)
gate_and_core = self.fc_full(z_ij)
gate, core = gate_and_core.chunk(2, dim=-1)
msg = torch.sigmoid(gate) * nn.functional.softplus(core)
agg = torch.zeros_like(v)
agg.index_add_(0, edge_src, msg)
return v + self.bn(agg) if v.size(0) > 1 else v + agg
class MiniCGCNN(nn.Module):
def __init__(self, max_z=100, node_dim=32, edge_bins=24, n_layers=2):
super().__init__()
self.embed = nn.Embedding(max_z, node_dim)
self.gbf = GaussianDistance(1.5, 5.5, edge_bins)
self.layers = nn.ModuleList([CGCNNLayer(node_dim, edge_bins) for _ in range(n_layers)])
self.head = nn.Sequential(nn.Linear(node_dim, node_dim), nn.SiLU(), nn.Linear(node_dim, 1))
def forward(self, z, edge_src, edge_dst, edge_dist, batch_idx=None):
v = self.embed(z)
e = self.gbf(edge_dist)
for layer in self.layers:
v = layer(v, edge_src, edge_dst, e)
if batch_idx is None:
return self.head(v.mean(dim=0, keepdim=True)).squeeze()
n_graphs = int(batch_idx.max().item()) + 1
pooled = torch.zeros((n_graphs, v.size(1)), device=v.device)
counts = torch.zeros((n_graphs, 1), device=v.device)
pooled.index_add_(0, batch_idx, v)
counts.index_add_(0, batch_idx, torch.ones((v.size(0), 1), device=v.device))
return self.head(pooled / counts.clamp(min=1.0)).squeeze(-1)
# === 物理对称性体检:平移、旋转、超胞扩展不变性 ===
set_seed(0)
model_test = MiniCGCNN().eval()
# 1. 原胞
e_orig = model_test(*build_crystal_graph(nacl_struct)).item()
# 2. 整体平移 +0.37 分数坐标
s_shift = nacl_struct.copy()
s_shift.translate_sites(range(len(s_shift)), [0.37, -0.21, 0.55], frac_coords=True)
e_shift = model_test(*build_crystal_graph(s_shift)).item()
# 3. 刚体旋转 (35° around [1, 1, 1])
s_rot = nacl_struct.copy()
from pymatgen.transformations.standard_transformations import RotationTransformation
s_rot = RotationTransformation([1, 1, 1], 35.0).apply_transformation(s_rot)
e_rot = model_test(*build_crystal_graph(s_rot)).item()
# 4. 2x2x2 超胞 (原子数扩大 8 倍!)
s_super = nacl_struct.copy()
s_super.make_supercell([2, 2, 2])
e_super = model_test(*build_crystal_graph(s_super)).item()
print(f"Original NaCl (8 atoms) : {e_orig:.6f}")
print(f"Translated (+0.37,-0.21) : {e_shift:.6f} (diff = {abs(e_orig - e_shift):.2e})")
print(f"Rotated 35° around [111] : {e_rot:.6f} (diff = {abs(e_orig - e_rot):.2e})")
print(f"2x2x2 Supercell (64 atoms): {e_super:.6f} (diff = {abs(e_orig - e_super):.2e})")
Original NaCl (8 atoms) : -3.731780 Translated (+0.37,-0.21) : -3.731780 (diff = 0.00e+00) Rotated 35° around [111] : -3.731780 (diff = 0.00e+00) 2x2x2 Supercell (64 atoms): -3.731779 (diff = 7.15e-07)
🤔 思考一下:为什么上面的平移、旋转、超胞误差全都在 \(10^{-6}\) 量级(纯浮点误差)?
- 因为 CGCNN 的边特征只依赖原子间欧氏距离 \(d_{ij}\)(天然具有 \(E(3)\) 平移和旋转不变性);
- 节点特征只依赖元素序数 \(Z\),聚合用
index_add_(天然具有原子编号置换不变性); - 图读出用平均池化,所以 \(2\times 2\times 2\) 超胞与原胞给出完全相同的每原子性质!
3. ▶️ 实战训练迷你 CGCNN:学习晶体的状态方程(能量–体积曲线)
为了在纯 CPU 上 15 秒内跑通真实物理训练,我们构造一个包含 4 种经典金属晶体(Cu, Al, Ni, Ag)在不同晶格应变(\(-8\%\) 到 \(+12\%\))与双元素合金替代下的晶体数据集(共 120 个晶体),使用物理 Morse 势函数作为精确能量标签(单位:eV/atom),然后用我们手写的 MiniCGCNN 从零学习晶体能量!
# Morse 势参数 (D_e [eV], alpha [1/Å], r0 [Å]) — 贴近真实 FCC 金属量级
MORSE_PARAMS = {
29: (0.343, 1.359, 2.866), # Cu
13: (0.270, 1.165, 3.253), # Al
28: (0.420, 1.420, 2.780), # Ni
47: (0.332, 1.369, 3.115), # Ag
}
EQ_A = {29: 3.615, 13: 4.050, 28: 3.524, 47: 4.085}
Z_TO_SYM = {29: "Cu", 13: "Al", 28: "Ni", 47: "Ag"}
def morse_energy_per_atom(struct: Structure, r_cut: float = 5.2) -> float:
all_nbrs = struct.get_all_neighbors(r_cut)
total_e = 0.0
for i, nbrs in enumerate(all_nbrs):
zi = struct[i].specie.Z
di, ai, r0i = MORSE_PARAMS[zi]
for nbr in nbrs:
zj = nbr.specie.Z
dj, aj, r0j = MORSE_PARAMS[zj]
# Lorentz-Berthelot 混合规则
D = np.sqrt(di * dj)
alpha = 0.5 * (ai + aj)
r0 = 0.5 * (r0i + r0j)
r = nbr.nn_distance
exp_term = np.exp(-alpha * (r - r0))
total_e += 0.5 * D * (exp_term ** 2 - 2.0 * exp_term)
return total_e / len(struct)
# 生成 120 个不同晶格常数与组成的晶体图
rng = np.random.default_rng(42)
dataset = []
for z_el, a0 in EQ_A.items():
for strain in np.linspace(-0.08, 0.14, 22):
s = Structure.from_spacegroup("Fm-3m", Lattice.cubic(a0 * (1 + strain)), [Z_TO_SYM[z_el]], [[0, 0, 0]])
g = build_crystal_graph(s, r_cut=5.2, max_nbrs=18)
dataset.append((g, morse_energy_per_atom(s), Z_TO_SYM[z_el]))
# 加入 32 个二元有序合金 (L1_2 / L1_0 型)
pairs = [(29, 28), (29, 47), (13, 28), (13, 29)]
for z1, z2 in pairs:
a_mix = 0.5 * (EQ_A[z1] + EQ_A[z2])
for strain in np.linspace(-0.06, 0.10, 8):
s = Structure(
Lattice.cubic(a_mix * (1 + strain)),
[Z_TO_SYM[z1], Z_TO_SYM[z2], Z_TO_SYM[z1], Z_TO_SYM[z2]],
[[0, 0, 0], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]],
)
g = build_crystal_graph(s, r_cut=5.2, max_nbrs=18)
dataset.append((g, morse_energy_per_atom(s), f"{Z_TO_SYM[z1]}-{Z_TO_SYM[z2]}"))
perm = rng.permutation(len(dataset))
train_data = [dataset[i] for i in perm[:96]]
test_data = [dataset[i] for i in perm[96:]]
def collate_graphs(batch):
zs, srcs, dsts, dists, bidx, ys = [], [], [], [], [], []
offset = 0
for gi, ((z, s, d, r), y, _) in enumerate(batch):
zs.append(z); srcs.append(s + offset); dsts.append(d + offset); dists.append(r)
bidx.append(torch.full((len(z),), gi, dtype=torch.long))
ys.append(y)
offset += len(z)
return (
torch.cat(zs), torch.cat(srcs), torch.cat(dsts), torch.cat(dists),
torch.cat(bidx), torch.tensor(ys, dtype=torch.float32)
)
set_seed(42)
cgcnn = MiniCGCNN(node_dim=32, edge_bins=24, n_layers=2)
opt = torch.optim.Adam(cgcnn.parameters(), lr=8e-3)
loss_hist = []
tr_pack = collate_graphs(train_data)
te_pack = collate_graphs(test_data)
for ep in range(180):
cgcnn.train()
opt.zero_grad()
pred = cgcnn(*tr_pack[:5])
loss = nn.functional.mse_loss(pred, tr_pack[5])
loss.backward()
opt.step()
loss_hist.append(np.sqrt(loss.item()))
cgcnn.eval()
with torch.no_grad():
te_pred = cgcnn(*te_pack[:5]).numpy()
te_true = te_pack[5].numpy()
mae_mev = np.mean(np.abs(te_pred - te_true)) * 1000
print(f"MiniCGCNN Test MAE = {mae_mev:.1f} meV/atom (Chemical accuracy benchmark ≈ 43 meV/atom)")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.2, 3.8))
ax1.plot(loss_hist, color=C.navy, lw=2.0)
ax1.set_xlabel("Epoch"); ax1.set_ylabel("Train RMSE (eV/atom)")
ax1.set_title("(a) MiniCGCNN Training Curve")
ax2.scatter(te_true, te_pred, color=C.teal, s=42, alpha=0.88, edgecolors="white", lw=0.4)
lo, hi = min(te_true.min(), te_pred.min()) - 0.1, max(te_true.max(), te_pred.max()) + 0.1
ax2.plot([lo, hi], [lo, hi], "k--", lw=1.1)
ax2.set_xlabel("True Energy (eV/atom)"); ax2.set_ylabel("CGCNN Predicted Energy (eV/atom)")
ax2.set_title(f"(b) Test Parity Plot (MAE = {mae_mev:.1f} meV/atom)")
plt.tight_layout()
plt.show()
MiniCGCNN Test MAE = 75.0 meV/atom (Chemical accuracy benchmark ≈ 43 meV/atom)
4. 📘 机器学习原子间势函数(MLIP):用自动微分保证能量守恒!
前面我们用 CGCNN 预测了静态能量 \(E\)。但如果想让原子“动起来”——做结构弛豫(Relaxation)、扩散系数模拟或相变分子动力学(MD)——我们需要每个原子 \(i\) 上的受力 \(\mathbf{F}_i\)。
🤔 先猜一猜:为什么现代 MLIP(Behler–Parrinello、SchNet、NequIP、MACE)从不直接用神经网络输出三维力向量,而是坚持先预测标量总能量 \(E(\mathbf{R})\),再对坐标求负梯度?
- 物理原因:只有梯度场才满足旋度为零(\(\nabla \times \mathbf{F} = 0\)),即保守力场!如果直接预测力,原子绕一圈回来可能会凭空产生能量,跑几百步 MD 系统就会热爆炸!
- 工程红利:在 PyTorch 中,只需把原子坐标设成
requires_grad=True,然后调用一次torch.autograd.grad(E, R),即可免费、解析地拿到严格守恒的力!
▶️ 下面我们训练一个 1D/双原子可微 MLIP(拟合真实 Morse 势能面),并用 Velocity-Verlet 算法运行 400 步 NVE 分子动力学,亲眼验证总能量 \(E_{\text{tot}} = E_{\text{kin}} + E_{\text{pot}}\) 的守恒性!
# 训练一个可微分的神经网络原子间势函数 (MLIP: r -> E, F = -dE/dr)
r_train = torch.linspace(2.2, 5.2, 60).unsqueeze(1)
D_cu, a_cu, r0_cu = 0.343, 1.359, 2.866
def true_morse(r):
e = torch.exp(-a_cu * (r - r0_cu))
return D_cu * (e ** 2 - 2.0 * e)
def true_force(r):
# 解析力 F = -dE/dr
e = torch.exp(-a_cu * (r - r0_cu))
return 2.0 * D_cu * a_cu * (e ** 2 - e)
E_ref = true_morse(r_train)
F_ref = true_force(r_train)
set_seed(42)
# 关键:必须用平滑激活函数 (SiLU / Tanh),不能用 ReLU(ReLU 二阶导不连续会导致 MD 能量漂移!)
mlip = nn.Sequential(
nn.Linear(1, 32), nn.SiLU(),
nn.Linear(32, 32), nn.SiLU(),
nn.Linear(32, 1),
)
opt_m = torch.optim.Adam(mlip.parameters(), lr=1e-2)
# 联合能量 + 力训练 (Force Matching — MACE/NequIP 的核心训练秘诀!)
for ep in range(600):
opt_m.zero_grad()
r_in = r_train.clone().detach().requires_grad_(True)
E_pred = mlip(r_in)
F_pred = -torch.autograd.grad(E_pred.sum(), r_in, create_graph=True)[0]
loss = nn.functional.mse_loss(E_pred, E_ref) + 0.2 * nn.functional.mse_loss(F_pred, F_ref)
loss.backward()
opt_m.step()
# Velocity-Verlet NVE 分子动力学 (400 步)
def mlip_ef(r_val):
rt = torch.tensor([[r_val]], dtype=torch.float32, requires_grad=True)
e = mlip(rt)
f = -torch.autograd.grad(e, rt)[0]
return float(e.item()), float(f.item())
dt = 0.08
mass = 1.0
r_cur = 2.55 # 从压缩键长释放,发生谐振/非谐振动
v_cur = 0.0
e_cur, f_cur = mlip_ef(r_cur)
rs, epots, ekins, etots = [], [], [], []
for _ in range(400):
v_half = v_cur + 0.5 * (f_cur / mass) * dt
r_cur = r_cur + v_half * dt
e_cur, f_cur = mlip_ef(r_cur)
v_cur = v_half + 0.5 * (f_cur / mass) * dt
ek = 0.5 * mass * v_cur ** 2
rs.append(r_cur); epots.append(e_cur); ekins.append(ek); etots.append(e_cur + ek)
r_grid = torch.linspace(2.2, 5.2, 200).unsqueeze(1).requires_grad_(True)
e_g = mlip(r_grid)
f_g = -torch.autograd.grad(e_g.sum(), r_grid)[0].detach().numpy()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.4, 3.8))
ax1.plot(r_grid.detach().numpy(), true_morse(r_grid).detach().numpy(), "k--", lw=1.6, label="True Morse E(r)")
ax1.plot(r_grid.detach().numpy(), e_g.detach().numpy(), color=C.navy, lw=2.2, label="MLIP Predicted E(r)")
ax1.set_xlabel("Interatomic Distance r (Å)"); ax1.set_ylabel("Potential Energy E (eV)")
ax1.set_title("(a) Force-Matched MLIP Potential Energy Surface")
ax1.legend()
steps = np.arange(len(etots))
ax2.plot(steps, epots, color=C.navy, lw=1.5, alpha=0.8, label="Potential E_pot")
ax2.plot(steps, ekins, color=C.teal, lw=1.5, alpha=0.8, label="Kinetic E_kin")
ax2.plot(steps, etots, color=C.crimson, lw=2.2, label=f"Total E (drift = {np.std(etots):.2e} eV)")
ax2.set_xlabel("Velocity-Verlet MD Step"); ax2.set_ylabel("Energy (eV)")
ax2.set_title("(b) NVE MD: Autograd Forces Conserve Total Energy!")
ax2.legend(loc="center right")
plt.tight_layout()
plt.show()
💡 小贴士:注意上面 mlip 用的是平滑激活函数 nn.SiLU() 而不是 nn.ReLU()!如果换成 ReLU,能量曲线是分段折线,求导后的力会出现阶跃跳变,跑 MD 时总能量就会剧烈漂移。
5. 📘 前沿视野:从 CGCNN 到通用等变势函数(MACE / CHGNet / MatterSim)
我们手写的 MiniCGCNN 只用到了两体距离 \(d_{ij}\)(标量,\(l=0\) 旋转不变特征)。过去五年,计算材料学最激动人心的突破是 \(E(3)\) 等变图神经网络与全元素周期表通用势函数(Universal MLIPs):
| 架构代际 | 代表模型 | 几何信息 | 典型优势与定位 |
|---|---|---|---|
| 第 1 代:描述符势 | Behler–Parrinello (HDNNP), GAP | 手工对称函数 / SOAP | 开创了 \(O(N)\) 线性标度 MLIP,但多元素组合爆炸 |
| 第 2 代:不变图网络 | CGCNN, SchNet, MEGNet | 两体距离 \(d_{ij}\) | 端到端学习化学嵌入,适合全周期表性质预测 |
| 第 3 代:多体 / 等变 GNN | NequIP, MACE, CHGNet, MatterSim | 球谐函数 \(Y_l^m(\hat{\mathbf{r}}_{ij})\) + 高阶多体交互 | 旋转等变(方向信息在消息传递中无损保留),样本效率提升 10–100× |
在实际科研中,你不再需要从零训练势函数——开源的 MACE-MP-0(在 Materials Project 15 万个晶体轨迹上预训练)已经可以直接作为 ASE Calculator 即插即用:
# 在安装 mace-torch 后的真实科研用法(仅需 4 行代码即可弛豫任意晶体!)
# from mace.calculators import mace_mp
# from ase.optimize import BFGS
# atoms.calc = mace_mp(model="medium", device="cpu")
# BFGS(atoms).run(fmax=0.02)
🏋️ 练习
- 练习 10c-1(激活函数对 MD 能量守恒的影响):把第 4 节
mlip里的nn.SiLU()改成nn.ReLU(),重新训练并运行 400 步 NVE MD,比较总能量标准差np.std(etots)的变化。 - 练习 10c-2(CGCNN 感受野深度):把
MiniCGCNN的n_layers分别设为1、2、3,比较测试集 MAE 与训练时间。 - 练习 10c-3(截断半径灵敏度):把
build_crystal_graph的r_cut从5.2 Å降到3.0 Å(仅保留第一近邻壳层),观察测试 MAE 如何变化并解释物理原因。
小结
- 晶体图必须处理周期性边界条件(PBC)与多图结构,并用**高斯径向基(GBF)**编码连续原子间距;
- CGCNN 通过门控消息传递与平均池化天然满足平移、旋转、置换与超胞尺度不变性;
- MLIP 通过对标量能量求自动微分 \(\mathbf{F}_i = -\nabla_{\mathbf{R}_i} E\) 严格保证保守力场与 MD 能量守恒,并结合 Force Matching(同时拟合能量与力)大幅提升数据效率;
- 现代 \(E(3)\) 等变通用势函数(如 MACE) 正在成为计算材料学的“新 DFT 加速器”。