2017-12-02 10 views
-1

나는 이와 같은 데이터 파일이 있습니다.euclidean 파이썬 xyz 좌표에서 거리

HETATM 1 H10 XSHQ 0  10.139 2.231 0.091 1.00 0.00   H 
HETATM 2 N1 XSHQ 0  9.641 1.386 -0.104 1.00 0.00   N 
HETATM 3 H9 XSHQ 0  9.773 1.133 -1.063 1.00 0.00   H 
HETATM 4 C1 XSHQ 0  8.245 1.531 0.230 1.00 0.00   H 

여기서 XYZ 좌표는 6,7,8 열이며, 포인트와 연관된 문자는 마지막 열에 있습니다. 마지막 열에 문자 H가있는 점 사이의 거리를 식별하고 싶습니다. 어떻게해야합니까? 이 코드는 작업을 수행하는 데 필요한 코드라는 것을 알고 있지만 마지막 열이 H 인 경우에만 6,7 및 8 열의 값을 사용하는 방법과 혼동 스럽습니다.

from scipy.spatial import distance  
dst = distance.euclidean(a,b) 
+0

데이터 파일 형식이란 무엇입니까? –

답변

0

, @ 소음기의 대답은 이미 정확하고 OrderedDict 같은 데이터 구조의 사용은 좋은 생각,하지만 당신은 표준 사용하려는 경우 방법은, 당신은 시도 할 수 있습니다 :

from scipy.spatial import distance 

# Load data from file 
with open('datafile.txt') as datafile: 
    contents = [line.split() for line in datafile] 

# Extract the xyz coordiantes, if there is an H in the last column 
coords = [] 
for i, item in enumerate(contents): 
    if item[-1] == 'H': 
     coords.append([[float(x) for x in item[5:8]], i+1]) 

# Show results 
for i in range(len(coords)): 
    for j in range(i+1, len(coords)): 
     dist = distance.euclidean(coords[i][0], coords[j][0]) 
     print('({}, {}): {:.5f}'.format(coords[i][1], coords[j][1], dist)) 
+0

해답을 주셔서 감사합니다. 이것은 실제로 첫 번째 거리를 제공합니다! 유일한 것은 모든 파일을 검사하여 모든 거리를 검사하지 않는다는 것입니다. – mrsphd

+0

'itertools'의'combination' 대신에 가능한 모든 결과를 보여주기 위해 double sum을 더했습니다. 또한 다른 형식의 문자열 서식을 사용했는데 구문 오류가 해결되었습니다. – TheIdealis

+0

고마워요, 당신은 스타입니다, 그것은 매력처럼 작동하고 매우 명확합니다! 도와 주셔서 정말 고맙습니다. – mrsphd

0

정규 표현식을 사용하여 날짜를 추출한 다음 규칙에 따라 필터링합니다.

데모 코드는 다음과 같다 :

물론

enter image description here

0

생성기를 사용하는 간단한 솔루션은

From PEP 289 -- Generator Expressions
Rationale
Experience with list comprehensions has shown their widespread utility throughout Python. However, many of the use cases do not need to have a full list created in memory. Instead, they only need to iterate over the elements one at a time.

를 연산 식 617,451,515,

  • 가능성이 큰 데이터가 itertools 표준 라이브러리 모듈에서

    combinations을 설정해야

    1. 당신이 중간 결과를 저장 할 필요가 없습니다, 당신이 계산하는 원하기 때문에 때문에 두 세트의 거리가 흥미로운 데이터 세트의 포인트입니다.

      $ cat euclid.py 
      from scipy.spatial.distance import euclidean 
      from itertools import combinations 
      
      lines = ['HETATM 1 H10 XSHQ 0 10.139 2.231 0.091 1.00 0.00 H', 
           'HETATM 2 N1 XSHQ 0 9.641 1.386 -0.104 1.00 0.00 N', 
           'HETATM 3 H9 XSHQ 0 9.773 1.133 -1.063 1.00 0.00 H', 
           'HETATM 4 C1 XSHQ 0 8.245 1.531 0.230 1.00 0.00 H'] 
      
      H_lines = (line for line in lines if line[-1]=='H') 
      H_lists = (line.split() for line in H_lines) 
      H_data = ((int(tok[1]), [float(x) for x in tok[5:8]]) for tok in H_lists) 
      H_dist = {(i[0], j[0]):euclidean(i[1], j[1]) 
            for i, j in combinations(H_data, 2)} 
      
      for m, n in H_dist: 
          print('Distance between points %d and %d is %.6f'%(
            m, n, H_dist[m, n])) 
      $ python3 euclid.py 
      Distance between points 1 and 3 is 1.634404 
      Distance between points 1 and 4 is 2.023995 
      Distance between points 3 and 4 is 2.040842 
      $ 
      
    +0

    고마워요. 별도의 줄에 각 거리를 인쇄하는 방법이 있습니까? 나는 어디에서나 시도했지만 시도가 안된다. print ({(i [0], j [0]) : i, j의 조합을위한 euclidean (i [1], j [1]) (H_v, 2)}) – mrsphd

    +0

    제네레이터에 문제가 있다고 생각합니다 ... 사전을 반환하는 함수 측면에서 답을 다시 작성하려고합니다. 계속 지켜봐. – gboffi

    +0

    print ('포인트 % d와 % d 사이의 거리는 % .6f'% (* points, distance [points])입니다. ^ SyntaxError : 구문이 잘못되었습니다. "" "감사합니다. 그러나 어떤 이유로이 오류가 발생합니다. .. "" " – mrsphd