Debian Codegraph @

shelxfile/fit/quatfit.py

raw symbols SCIP
1 # coding=utf-8
2 from __future__ import print_function
3
4 import copy
5 from math import fabs
6 from math import sqrt
7 ##############################################################################
8 # The program to superimpose atoms of two molecules by quaternion method
9 #
10 # David J. Heisterberg
11 # The Ohio Supercomputer Center
12 # 1224 Kinnear Rd.
13 # Columbus, OH 43212-1163
14 # (614)292-6036
15 # [email protected] [email protected] ohstpy::djh
16 #
17 # Translated to C from fitest.f program and interfaced with Xmol program
18 # by Jan Labanowski, [email protected] [email protected] ohstpy::jkl
19 #
20 # Translated to python from quatfit.c
21 # by Thomas J. L. Mustard, [email protected]
22 #
23 # Copyright: Ohio Supercomputer Center, David J. Heisterberg, 1990.
24 # The program can be copied and distributed freely, provided that
25 # this copyright in not removed. You may acknowledge the use of the
26 # program in published material as:
27 # David J. Heisterberg, 1990, unpublished results.
28 #
29 # This program was heavily modified by Daniel Kratzert
30 from typing import List, Tuple
31
32 from shelxfile.misc.misc import frac_to_cart, cart_to_frac
33
34
35 def matrix_minus_vect(m: List[List[float]], v: Tuple[float, float, float]):
36 """
37 """
38 result = []
39 for coords in m:
40 result.append([coords[0] - v[0], coords[1] - v[1], coords[2] - v[2]])
41 return result
42
43
44 def matrix_plus_vect(m: List[List[float]], v: Tuple[float, float, float]):
45 """
46 """
47 result = []
48 for coords in m:
49 result.append([coords[0] + v[0], coords[1] + v[1], coords[2] + v[2]])
50 return result
51
52
53 def transpose(a):
54 """
55 transposes a matrix
56 """
57 return list(zip(*a))
58
59
60 def rotmol(frag_atoms, rotmat):
61 """
62 ROTMOL
63 rotate a molecule
64 n - number of atoms
65 filelol (x) - input coordinates
66 filelol (y) - rotated coordinates y = u * x
67 rotmat (u) - left rotation matrix
68 """
69 for i in range(len(frag_atoms)):
70 yx = rotmat[0][0] * frag_atoms[i][0] + rotmat[1][0] * frag_atoms[i][1] + rotmat[2][0] * frag_atoms[i][2]
71 yy = rotmat[0][1] * frag_atoms[i][0] + rotmat[1][1] * frag_atoms[i][1] + rotmat[2][1] * frag_atoms[i][2]
72 yz = rotmat[0][2] * frag_atoms[i][0] + rotmat[1][2] * frag_atoms[i][1] + rotmat[2][2] * frag_atoms[i][2]
73 frag_atoms[i][0] = yx # x
74 frag_atoms[i][1] = yy # y
75 frag_atoms[i][2] = yz # z
76 return frag_atoms
77
78
79 def jacobi(matrix, maxsweeps):
80 """
81 JACOBI
82 Jacobi diagonalizer with sorted output. It is only good for 4x4 matrices.
83 (was too lazy to do pointers...)
84 matrix (a) - input: matrix to diagonalize
85 eigenvect (v) - output: eigenvectors
86 eigenval (d) - output: eigenvalues
87 maxsweeps (nrot) - input: maximum number of sweeps
88 """
89 eigenvect = [[float(0.0) for x in range(4)] for x in range(4)]
90 eigenval = [float(0.0) for x in range(4)]
91 m = 0
92 for j in range(4):
93 eigenvect[j][j] = 1.0
94 eigenval[j] = matrix[j][j]
95 for m in range(maxsweeps):
96 dnorm = 0.0
97 onorm = 0.0
98 for j in range(4):
99 dnorm += fabs(eigenval[j])
100 for i in range(j):
101 onorm += fabs(matrix[i][j])
102 if onorm / dnorm <= 1.0e-12:
103 break # goto Exit_now;
104 for j in range(1, 4):
105 for i in range(j):
106 b = matrix[i][j]
107 if fabs(b) > 0.0:
108 dma = eigenval[j] - eigenval[i]
109 if (fabs(dma) + fabs(b)) <= fabs(dma):
110 t = b / dma
111 else:
112 q = 0.5 * dma / b
113 t = 1.0 / (fabs(q) + sqrt(1.0 + q * q))
114 if q < 0.0:
115 t = -t
116 c = 1.0 / sqrt(t * t + 1.0)
117 s = t * c
118 matrix[i][j] = 0.0
119 for k in range(i):
120 atemp = c * matrix[k][i] - s * matrix[k][j]
121 matrix[k][j] = s * matrix[k][i] + c * matrix[k][j]
122 matrix[k][i] = atemp
123 for k in range(i + 1, j):
124 atemp = c * matrix[i][k] - s * matrix[k][j]
125 matrix[k][j] = s * matrix[i][k] + c * matrix[k][j]
126 matrix[i][k] = atemp
127 for k in range(j + 1, 4):
128 atemp = c * matrix[i][k] - s * matrix[j][k]
129 matrix[j][k] = s * matrix[i][k] + c * matrix[j][k]
130 matrix[i][k] = atemp
131 for k in range(4):
132 vtemp = c * eigenvect[k][i] - s * eigenvect[k][j]
133 eigenvect[k][j] = s * eigenvect[k][i] + c * eigenvect[k][j]
134 eigenvect[k][i] = vtemp
135 dtemp = c * c * eigenval[i] + s * s * eigenval[j] - 2.0 * c * s * b
136 eigenval[j] = s * s * eigenval[i] + c * c * eigenval[j] + 2.0 * c * s * b
137 eigenval[i] = dtemp
138 maxsweeps = m
139 for j in range(3):
140 k = j
141 dtemp = eigenval[k]
142 for i in range(j + 1, 4):
143 if eigenval[i] < dtemp:
144 k = i
145 dtemp = eigenval[k]
146 if k > j:
147 eigenval[k] = eigenval[j]
148 eigenval[j] = dtemp
149 for i in range(4):
150 dtemp = eigenvect[i][k]
151 eigenvect[i][k] = eigenvect[i][j]
152 eigenvect[i][j] = dtemp
153 return eigenvect, eigenval, maxsweeps
154
155
156 def q2mat(quaternion):
157 """
158 Q2MAT
159 Generate a left rotation matrix from a normalized quaternion
160
161 INPUT
162 quaternion (q) - normalized quaternion
163
164 OUTPUT
165 rotmat (u) - the rotation matrix
166 """
167 rotmat = [[float(0.0) for _ in range(3)] for _ in range(3)]
168 rotmat[0][0] = quaternion[0] * quaternion[0] + quaternion[1] * quaternion[1] - quaternion[2] * quaternion[2] - \
169 quaternion[3] * quaternion[3]
170 rotmat[1][0] = 2.0 * (quaternion[1] * quaternion[2] - quaternion[0] * quaternion[3])
171 rotmat[2][0] = 2.0 * (quaternion[1] * quaternion[3] + quaternion[0] * quaternion[2])
172 rotmat[0][1] = 2.0 * (quaternion[2] * quaternion[1] + quaternion[0] * quaternion[3])
173 rotmat[1][1] = quaternion[0] * quaternion[0] - quaternion[1] * quaternion[1] + quaternion[2] * quaternion[2] - \
174 quaternion[3] * quaternion[3]
175 rotmat[2][1] = 2.0 * (quaternion[2] * quaternion[3] - quaternion[0] * quaternion[1])
176 rotmat[0][2] = 2.0 * (quaternion[3] * quaternion[1] - quaternion[0] * quaternion[2])
177 rotmat[1][2] = 2.0 * (quaternion[3] * quaternion[2] + quaternion[0] * quaternion[1])
178 rotmat[2][2] = quaternion[0] * quaternion[0] - quaternion[1] * quaternion[1] - quaternion[2] * quaternion[2] + \
179 quaternion[3] * quaternion[3]
180 return rotmat
181
182
183 def qtrfit(source_xyz, target_xyz, maxsweeps):
184 """
185 QTRFIT
186 Find the quaternion, q,[and left rotation matrix, u] that minimizes
187
188 |qTXq - Y| ^ 2 [|uX - Y| ^ 2]
189
190 This is equivalent to maximizing Re (qTXTqY).
191
192 This is equivalent to finding the largest eigenvalue and corresponding
193 eigenvector of the matrix
194
195 [A2 AUx AUy AUz ]
196 [AUx Ux2 UxUy UzUx]
197 [AUy UxUy Uy2 UyUz]
198 [AUz UzUx UyUz Uz2 ]
199
200 where
201
202 A2 = Xx Yx + Xy Yy + Xz Yz
203 Ux2 = Xx Yx - Xy Yy - Xz Yz
204 Uy2 = Xy Yy - Xz Yz - Xx Yx
205 Uz2 = Xz Yz - Xx Yx - Xy Yy
206 AUx = Xz Yy - Xy Yz
207 AUy = Xx Yz - Xz Yx
208 AUz = Xy Yx - Xx Yy
209 UxUy = Xx Yy + Xy Yx
210 UyUz = Xy Yz + Xz Yy
211 UzUx = Xz Yx + Xx Yz
212
213 The left rotation matrix, u, is obtained from q by
214
215 u = qT1q
216
217 INPUT
218 n - number of points
219 fit_xyz (x) - fitted molecule coordinates
220 ref_xyz (y) - reference molecule coordinates
221 weights (w) - weights
222
223 OUTPUT
224 quaternion (q) - the best-fit quaternion
225 rotmat (u) - the best-fit left rotation matrix
226 maxsweeps (nr) - max number of jacobi sweeps
227
228 """
229 # Create variables/lists/matrixes
230 matrix = [[float(0.0) for x in range(4)] for x in range(4)]
231 quaternion = [float(0.0) for x in range(4)]
232 # generate the upper triangle of the quadratic form matrix
233 xxyx = float(0.0)
234 xxyy = float(0.0)
235 xxyz = float(0.0)
236 xyyx = float(0.0)
237 xyyy = float(0.0)
238 xyyz = float(0.0)
239 xzyx = float(0.0)
240 xzyy = float(0.0)
241 xzyz = float(0.0)
242 for i, _ in enumerate(source_xyz):
243 xxyx = xxyx + source_xyz[i][0] * target_xyz[i][0]
244 xxyy = xxyy + source_xyz[i][0] * target_xyz[i][1]
245 xxyz = xxyz + source_xyz[i][0] * target_xyz[i][2]
246 xyyx = xyyx + source_xyz[i][1] * target_xyz[i][0]
247 xyyy = xyyy + source_xyz[i][1] * target_xyz[i][1]
248 xyyz = xyyz + source_xyz[i][1] * target_xyz[i][2]
249 xzyx = xzyx + source_xyz[i][2] * target_xyz[i][0]
250 xzyy = xzyy + source_xyz[i][2] * target_xyz[i][1]
251 xzyz = xzyz + source_xyz[i][2] * target_xyz[i][2]
252
253 matrix[0][0] = xxyx + xyyy + xzyz
254 matrix[0][1] = xzyy - xyyz
255 matrix[1][1] = xxyx - xyyy - xzyz
256 matrix[0][2] = xxyz - xzyx
257 matrix[1][2] = xxyy + xyyx
258 matrix[2][2] = xyyy - xzyz - xxyx
259 matrix[0][3] = xyyx - xxyy
260 matrix[1][3] = xzyx + xxyz
261 matrix[2][3] = xyyz + xzyy
262 matrix[3][3] = xzyz - xxyx - xyyy
263
264 # diagonalize c
265 eigenvect, eigenval, maxsweeps = jacobi(matrix, maxsweeps)
266
267 # extract the desired quaternion
268 quaternion[0] = eigenvect[0][3]
269 quaternion[1] = eigenvect[1][3]
270 quaternion[2] = eigenvect[2][3]
271 quaternion[3] = eigenvect[3][3]
272
273 # generate the rotation matrix
274 rotmat = q2mat(quaternion)
275
276 return quaternion, transpose(rotmat), maxsweeps
277
278
279 def centroid(vectors: List[List[float]]) -> Tuple[float, float, float]:
280 """
281 Calculate the centroid from a vectorset X.
282
283 https://en.wikipedia.org/wiki/Centroid
284 Centroid is the mean position of all the points in all of the coordinate
285 directions.
286
287 C = sum(X)/len(X)
288
289 Parameters
290 ----------
291 vectors : np.array
292 (N,D) matrix, where N is points and D is dimension.
293
294 Returns
295 -------
296 C : float
297 centeroid
298 """
299 s = [0.0, 0.0, 0.0]
300 num = 0
301 for line in vectors:
302 num += 1
303 for n, v in enumerate(line):
304 s[n] += v
305 return (s[0] / num, s[1] / num, s[2] / num)
306
307
308 def rmsd(vect1, vect2):
309 """
310 Calculate Root-mean-square deviation from two sets of vectors V and W.
311
312 Parameters
313 ----------
314 vect1 : np.array
315 (N,D) matrix, where N is points and D is dimension.
316 vect2 : np.array
317 (N,D) matrix, where N is points and D is dimension.
318
319 Returns
320 -------
321 fit : float
322 Root-mean-square deviation
323
324 """
325 D = len(vect1[0])
326 N = len(vect1)
327 rmsd = 0.0
328 for v, w in zip(vect1, vect2):
329 rmsd += sum([(v[i] - w[i]) ** 2.0 for i in range(D)])
330 return sqrt(rmsd / N)
331
332
333 def show_coordinates(atoms, vect):
334 """
335 Print coordinates V with corresponding atoms to stdout in XYZ format.
336
337 Parameters
338 ----------
339 atoms : np.array
340 List of atomic types
341 vect : np.array
342 (N,3) matrix of atomic coordinates
343 """
344 for n, atom in enumerate(atoms):
345 atom = atom[0].upper() + atom[1:]
346 print("{0:2s} 1 {1:15.8f} {2:15.8f} {3:15.8f} 11.0 0.04".format(atom, *vect[n]))
347
348
349 def fit_fragment(fragment_atoms, source_atoms, target_atoms):
350 """
351 Takes a list of fragment atoms and fits them to the position of target atoms. source_atoms are a fraction
352 of the fragment to be fitted on the target_atoms.
353
354 Parameters
355 ----------
356 fragment_atoms: List
357 complete set of atoms of a fragment
358 source_atoms: List
359 subsection of fragment atoms
360 target_atoms: List
361 target position for source_atoms
362
363 Returns
364 -------
365 rotated_fragment: List
366 list of coordinates from the fitted fragment
367 rmsd: float
368 RMSD (root mean square deviation)
369 """
370 p_source = copy.deepcopy(source_atoms)
371 q_target = copy.deepcopy(target_atoms)
372 # Create the centroid of P_source and Q_target which is the geometric center of a
373 # N-dimensional region and translate P_source and Q_target onto that center:
374 # http://en.wikipedia.org/wiki/Centroid
375 pcentroid = centroid(p_source)
376 qcentroid = centroid(q_target)
377 # Move P_source and Q_target to origin:
378 p_source = matrix_minus_vect(p_source, pcentroid)
379 q_target = matrix_minus_vect(q_target, qcentroid)
380 # get the Kabsch rotation matrix:
381 quaternion, U, maxsweeps = qtrfit(p_source, q_target, 30)
382 # translate source_atoms onto center:
383 source_atoms = matrix_minus_vect(source_atoms, pcentroid)
384 # rotate fragment_atoms (instead of source_atoms):
385 rotated_fragment = rotmol(fragment_atoms, U)
386 # move fragment back from zero (be aware that the translation is still wrong!):
387 rotated_fragment = matrix_plus_vect(rotated_fragment, qcentroid)
388 rms = rmsd(q_target, p_source)
389 return list(rotated_fragment), rms
390
391
392 def mytest():
393 """
394 >>> mytest() # DOCTEST: +REPORT_NDIFF +NORMALIZE_WHITESPACE +ELLIPSIS
395 Kabsch RMSD: 0.339
396 C0d 1 0.13342089 0.24130563 0.55100894 11.0 0.04
397 C1d 1 0.17619888 0.17902262 0.56452914 11.0 0.04
398 C2d 1 0.08365746 0.12997794 0.52724057 11.0 0.04
399 C3d 1 -0.02665530 0.12466866 0.55597929 11.0 0.04
400 C4d 1 0.13521359 0.07155518 0.52290434 11.0 0.04
401 C5d 1 0.05529952 0.15222482 0.46565980 11.0 0.04
402 C6d 1 0.31578577 0.17095916 0.54271372 11.0 0.04
403 C7d 1 0.38815031 0.22093469 0.56283111 11.0 0.04
404 C8d 1 0.31213535 0.16969488 0.47643097 11.0 0.04
405 C9d 1 0.37186868 0.11694406 0.56569282 11.0 0.04
406 C10d 1 0.17345616 0.17029947 0.64030933 11.0 0.04
407 C11d 1 0.27028472 0.20219330 0.67212698 11.0 0.04
408 C12d 1 0.18465947 0.10785452 0.65628617 11.0 0.04
409 C13d 1 0.06399788 0.19258933 0.66104906 11.0 0.04
410
411 """
412 cell = [10.5086, 20.9035, 20.5072, 90.0, 94.13, 90.0]
413
414 target_atoms = [[0.156860, 0.210330, 0.529750], # O1
415 [0.198400, 0.149690, 0.543840], # C1
416 [0.1968, 0.1393, 0.6200]] # Q11
417 # F8: [0.297220, 0.093900, 0.636590]
418 # Q11: [0.1968, 0.1393, 0.6200] # Q11
419 target_atoms = [frac_to_cart(x, cell) for x in target_atoms]
420
421 fragment_atoms = [[-0.01453, 1.66590, 0.10966], # O1 *0
422 [-0.00146, 0.26814, 0.06351], # C1 *1
423 [-1.13341, -0.23247, -0.90730], # C2
424 [-2.34661, -0.11273, -0.34544], # F1
425 [-0.96254, -1.50665, -1.29080], # F2
426 [-1.12263, 0.55028, -2.01763], # F3
427 [1.40566, -0.23179, -0.43131], # C3
428 [2.38529, 0.42340, 0.20561], # F4
429 [1.53256, 0.03843, -1.75538], # F5
430 [1.57833, -1.55153, -0.25035], # F6
431 [-0.27813, -0.21605, 1.52795], # C4 *10
432 [0.80602, -0.03759, 2.30431], # F7
433 [-0.58910, -1.52859, 1.53460], # F8
434 [-1.29323, 0.46963, 2.06735]] # F9
435
436 #target_names = ['O1', 'C1', 'Q11']
437 # Structure A rotated and translated onto B (p onto q)
438
439 fragment_atom_names = []
440 for n in range(len(fragment_atoms)):
441 at = "C{}d".format(n)
442 fragment_atom_names.append(at)
443 fragment_atom_names = fragment_atom_names
444 source_atoms = [fragment_atoms[0], fragment_atoms[1], fragment_atoms[10]]
445 rotated_fragment, rmsd = fit_fragment(fragment_atoms, source_atoms, target_atoms)
446 rotated_fragment = [cart_to_frac(x, cell) for x in rotated_fragment] # back to fractional coordinates
447 print('Kabsch RMSD: {0:8.3}'.format(rmsd))
448 show_coordinates(fragment_atom_names, rotated_fragment)
449
450
451 if __name__ == "__main__":
452 mytest()