You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MDTraj计算原子间距离:筛选特定距离及对应帧报错求助

解决MDTraj计算原子距离时报TypeError的问题

你的代码存在几个明显问题,导致了TypeError,以下是问题分析和修正后的代码:

问题点说明

  • 存在未定义的变量pairs_traj,且对应的循环块完全多余,既没用到也会引发报错
  • 错误地将数组传入range()函数:md.compute_distances返回的是形状为(n_frames, 1)的二维数组,range()只接受整数参数,不能直接传入数组
  • 帧索引与距离值的对应逻辑混乱,无法正确关联到目标帧

修正后的代码

import numpy as np
import mdtraj as md

top_file = input("Topology file path: ")
traj_file = input("Trajectory file path: ")
index1 = int(input("VMD index of atom 1: "))
index2 = int(input("VMD index of atom 2: "))

traj = md.load(traj_file, top=top_file)
# 计算指定原子对在所有帧中的距离,结果为(n_frames, 1)的二维数组
atom_distances = md.compute_distances(traj, atom_pairs=[[index1, index2]])

# 遍历每帧的距离,同时获取对应的帧索引
for frame_idx, distance in enumerate(atom_distances.flatten()):
    if distance < 0.15:
        print(f"Frame {frame_idx}: Distance = {distance:.4f} nm")

修正细节

  1. 删除了无用的pairs_traj相关代码,该变量未定义且与需求无关
  2. 使用flatten()将二维的距离数组转为一维,配合enumerate()同时获取帧索引和对应的距离值
  3. 直接比较距离值与0.15的大小,打印符合条件的帧编号和距离值

内容的提问来源于stack exchange,提问作者jaospadeto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:05:36