习题答案 10 · 第十讲基础习题参考答案(GNN、晶体图与 MLIP)
直接阅读答案的学习效果远低于独立实现。建议至少尝试 20 分钟,卡住时先看习题里的 💡 提示,再展开本页。
展开状态只在当前浏览器标签页有效,关闭标签页后会重新折叠。
import numpy as np
import torch
import torch.nn as nn
from rdkit import Chem
from pymatgen.core import Lattice, Structure
torch.manual_seed(42)
np.random.seed(42)
print("Module 10 exercises environment ready.")
Module 10 exercises environment ready.
习题 1:把分子 SMILES 转成无向分子图(edge_index 与原子特征)
给定噻吩 c1ccsc1,编写函数返回原子序数张量 x 和双向边索引 edge_index(形状 [2, 2*num_bonds]),并验证边数等于化学键数的 2 倍。
def smiles_to_graph(smiles: str):
mol = Chem.MolFromSmiles(smiles)
x = torch.tensor([a.GetAtomicNum() for a in mol.GetAtoms()], dtype=torch.long)
src, dst = [], []
for bond in mol.GetBonds():
u, v = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()
src.extend([u, v])
dst.extend([v, u])
edge_index = torch.tensor([src, dst], dtype=torch.long)
return x, edge_index
x, edge_index = smiles_to_graph("c1ccsc1")
print("Atomic numbers:", x.tolist(), "| edge_index shape:", tuple(edge_index.shape))
assert edge_index.shape == (2, 10)
Atomic numbers: [6, 6, 6, 16, 6] | edge_index shape: (2, 10)
习题 2:验证 index_add_ 消息聚合的置换不变性
对一个 5 原子分子图的节点特征随机打乱原子编号(并同步重映射 edge_index),验证单层求和消息传递 + 全局求和读出的输出完全不变。
x_feat = torch.randn(5, 8)
_, edge_index = smiles_to_graph("c1ccsc1")
W = nn.Linear(8, 8, bias=False)
def gnn_step(h, ei):
msg = W(h[ei[1]])
agg = torch.zeros_like(h)
agg.index_add_(0, ei[0], msg)
return (h + torch.relu(agg)).sum(dim=0)
perm = torch.tensor([3, 0, 4, 1, 2])
inv_perm = torch.argsort(perm)
h_perm = x_feat[perm]
ei_perm = inv_perm[edge_index]
out1 = gnn_step(x_feat, edge_index)
out2 = gnn_step(h_perm, ei_perm)
diff = (out1 - out2).abs().max().item()
print(f"Max diff after atom permutation: {diff:.2e}")
assert diff < 1e-5
Max diff after atom permutation: 1.19e-07
习题 3:求和读出(Sum Readout)vs. 平均读出(Mean Readout)的尺寸外推
比较苯(6 原子)与并五苯(22 原子)在相同每原子特征向量下,Sum Readout 与 Mean Readout 的输出差异,解释为什么预测广延量(如分子总能量、溶解度趋势)往往偏好 Sum Readout。
atom_vec = torch.ones(1, 4) * 0.5
h_benzene = atom_vec.repeat(6, 1)
h_pentacene = atom_vec.repeat(22, 1)
print("Mean readout -> benzene:", h_benzene.mean(0)[0].item(), "| pentacene:", h_pentacene.mean(0)[0].item())
print("Sum readout -> benzene:", h_benzene.sum(0)[0].item(), "| pentacene:", h_pentacene.sum(0)[0].item())
# Mean readout 丢失了分子大小(原子数)信息;Sum readout 保留广延标度!
Mean readout -> benzene: 0.5 | pentacene: 0.5 Sum readout -> benzene: 3.0 | pentacene: 11.0
习题 4:用 pymatgen 构造周期性晶体近邻图并统计配位数
构造金刚石硅(Fd-3m, \(a = 5.431\,\text{\AA}\))和体心立方铁(Im-3m, \(a = 2.866\,\text{\AA}\)),在合适截断半径下统计每个原子的第一近邻配位数(应分别为 4 和 8)。
si = Structure.from_spacegroup("Fd-3m", Lattice.cubic(5.431), ["Si"], [[0, 0, 0]])
fe = Structure.from_spacegroup("Im-3m", Lattice.cubic(2.866), ["Fe"], [[0, 0, 0]])
cn_si = [len(nbrs) for nbrs in si.get_all_neighbors(2.6)]
cn_fe = [len(nbrs) for nbrs in fe.get_all_neighbors(2.6)]
print("Diamond Si coordination numbers:", cn_si)
print("BCC Fe coordination numbers :", cn_fe)
assert all(c == 4 for c in cn_si) and all(c == 8 for c in cn_fe)
Diamond Si coordination numbers: [4, 4, 4, 4, 4, 4, 4, 4] BCC Fe coordination numbers : [8, 8]
习题 5:实现高斯径向基展开(GBF)并检验平滑性
编写 gaussian_basis(dist, dmin=1.5, dmax=5.5, n_bins=16),把距离张量 [2.35, 2.86, 3.61] 展开为形状 [3, 16] 的特征矩阵,并验证每个距离的最大激活中心正好对应其最接近的 \(\mu_k\)。
def gaussian_basis(dist, dmin=1.5, dmax=5.5, n_bins=16):
centers = torch.linspace(dmin, dmax, n_bins)
step = (dmax - dmin) / (n_bins - 1)
return torch.exp(-((dist.unsqueeze(-1) - centers) / step) ** 2), centers
dists = torch.tensor([2.35, 2.86, 3.61])
gbf, centers = gaussian_basis(dists)
peak_centers = centers[gbf.argmax(dim=-1)]
print("GBF shape:", tuple(gbf.shape), "| Peak centers:", [round(v, 2) for v in peak_centers.tolist()])
assert gbf.shape == (3, 16)
GBF shape: (3, 16) | Peak centers: [2.3, 2.83, 3.63]
习题 6:用 PyTorch 自动微分从标量势能计算保守力
给定简谐势能 \(E(r) = \frac{1}{2} k (r - r_0)^2\)(取 \(k = 10.0, r_0 = 2.5\)),用 torch.autograd.grad 计算 \(r = 2.8\) 处的力 \(F = -dE/dr\),并与解析解 \(-k(r - r_0) = -3.0\) 对比。
r = torch.tensor(2.8, requires_grad=True)
k, r0 = 10.0, 2.5
E = 0.5 * k * (r - r0) ** 2
F_auto = -torch.autograd.grad(E, r)[0]
F_exact = -k * (2.8 - r0)
print(f"Autograd F = {F_auto.item():.6f} | Exact F = {F_exact:.6f}")
assert abs(F_auto.item() - F_exact) < 1e-5
Autograd F = -3.000000 | Exact F = -3.000000