首页 > 解决方案 > 用python成对计算两个文件之间的原子距离

问题描述

到目前为止,我已经使用 bash 生成了两个文件:

File one包含蛋白质的 C 原子坐标除以空间:

C2[0]  C2[1]  C2[2]

13.717 10.109 8.591
13.306 9.421 7.294
12.004 8.673 7.519
13.163 10.412 6.155
15.876 11.528 12.222
17.300 11.385 12.712
14.936 10.789 13.182
13.481 10.875 12.771
12.703 11.969 13.122
12.890 9.875 12.010
11.376 12.078 12.725
11.556 9.961 11.612
10.803 11.067 11.970
19.044 12.341 14.078
19.906 12.922 12.973

File two包含配体的 C 原子坐标:

C1[0] C1[1]  C1[2]

0.510 -3.329 3.463
1.664 -2.694 4.189
1.864 -6.031 5.380
2.956 -6.810 4.984
4.038 -7.028 5.832
1.887 -5.446 6.650
2.974 -5.663 7.501
4.066 -6.436 7.093
5.204 -6.724 8.010
6.532 -6.775 7.600
7.539 -7.095 8.513
7.222 -7.396 9.831
5.894 -7.377 10.238
4.894 -7.058 9.331

我如何在python中使用foreach循环来计算第一行file two到每一行的距离file one(这将生成15个数字,因为文件一中有15行);

然后file two, 的第二行到file one.

要计算我需要使用的距离:

import math
def distance(c1, c2):
    x_dist = (c1[0] - c2[0])**2
    y_dist = (c1[1] - c2[1])**2
    z_dist = (c1[2] - c2[2])**2
    return math.sqrt(x_dist + y_dist + z_dist)

现在如何将公式放入 foreach 循环中?

标签: python

解决方案


您可以通过访问矩阵中的文件 1 和 fil2 2pands并计算距离numpy。例如:

import pandas as pd
import numpy as np
file1='your_file1.txt'
file2='your_file2.txt'
f1=pd.read_csv(file1,sep='\t')
f2=pd.read_csv(file2,sep='\t')
f1=f1.apply(pd.to_numeric) #make sure f1 is numeric
f2=f2.apply(pd.to_numeric) #make sure f1 is numeric
f1=f1.T.values
f2=f2.T.values
print (f1.shape, f2.shape)

wheref1f2应该是 15 行 3 列的矩阵。

def distance(a,b):
    return np.sqrt(sum((a-b)**2))
DD=[distance(i,j) for i,j in zip(f1, f2)]
print (DD)

您可以使用函数 计算距离,该函数distance (a,b)将两个矩阵作为输入。DD应该返回一个列表,其中包含由您显示的公式计算的 15 个距离。


推荐阅读