使用MDAnalysis遍历LAMMPS dumpfile分子的选择语法报错问题
解决MDAnalysis中按分子ID选择原子的问题
你遇到的SelectionError是因为MDAnalysis的选择语法中没有mol这个内置关键字,直接用mol {i}会被识别为未知令牌。以下是两种正确的按分子ID选择原子的方法:
方法1:使用resid关键字
当你从LAMMPS Dump文件加载数据时,MDAnalysis会自动将mol列的值映射为原子的残基ID(resid)。因此可以直接用resid关键字来选择对应分子的原子:
N_Molecules = 4 for ts in u.trajectory: Rgyr = 0 for i in range(1, N_Molecules + 1): # 使用resid替代mol选择分子 molecule = u.select_atoms(f"resid {i}") Rgyr += molecule.radius_of_gyration() Rgyr /= N_Molecules print(f"Rgyr {Rgyr:.2f}")
方法2:直接引用mol属性
如果需要明确使用mol字段,可以通过属性比较的方式选择原子(MDAnalysis支持直接基于原子属性进行筛选):
N_Molecules = 4 for ts in u.trajectory: Rgyr = 0 for i in range(1, N_Molecules + 1): # 使用属性比较语法选择mol等于i的原子 molecule = u.select_atoms(f"mol == {i}") Rgyr += molecule.radius_of_gyration() Rgyr /= N_Molecules print(f"Rgyr {Rgyr:.2f}")
验证映射关系(可选)
你可以通过以下代码确认resid和mol是否一致:
print(u.atoms[0].resid) # 输出第一个原子的残基ID print(u.atoms[0].mol) # 输出第一个原子的分子ID
内容的提问来源于stack exchange,提问作者ludwig_boltzplatz
相关产品推荐
相关产品推荐

