/
geometry_utils.py
257 lines (208 loc) · 7.6 KB
/
geometry_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""
Geometric utility functions for 3D geometry.
"""
import numpy as np
from scipy.spatial.distance import cdist
from copy import deepcopy
def unit_vector(vector: np.ndarray) -> np.ndarray:
""" Returns the unit vector of the vector.
Parameters
----------
vector: np.ndarray
A numpy array of shape `(3,)`, where `3` is (x,y,z).
Returns
----------
np.ndarray
A numpy array of shape `(3,)`. The unit vector of the input vector.
"""
return vector / np.linalg.norm(vector)
def angle_between(vector_i: np.ndarray, vector_j: np.ndarray) -> float:
"""Returns the angle in radians between vectors "vector_i" and "vector_j"
Note that this function always returns the smaller of the two angles between
the vectors (value between 0 and pi).
Parameters
----------
vector_i: np.ndarray
A numpy array of shape `(3,)`, where `3` is (x,y,z).
vector_j: np.ndarray
A numpy array of shape `(3,)`, where `3` is (x,y,z).
Returns
----------
np.ndarray
The angle in radians between the two vectors.
Examples
--------
>>> print("%0.06f" % angle_between((1, 0, 0), (0, 1, 0)))
1.570796
>>> print("%0.06f" % angle_between((1, 0, 0), (1, 0, 0)))
0.000000
>>> print("%0.06f" % angle_between((1, 0, 0), (-1, 0, 0)))
3.141593
"""
vector_i_u = unit_vector(vector_i)
vector_j_u = unit_vector(vector_j)
angle = np.arccos(np.dot(vector_i_u, vector_j_u))
if np.isnan(angle):
if np.allclose(vector_i_u, vector_j_u):
return 0.0
else:
return np.pi
return angle
def generate_random_unit_vector() -> np.ndarray:
r"""Generate a random unit vector on the sphere S^2.
Citation: http://mathworld.wolfram.com/SpherePointPicking.html
Pseudocode:
a. Choose random theta \element [0, 2*pi]
b. Choose random z \element [-1, 1]
c. Compute output vector u: (x,y,z) = (sqrt(1-z^2)*cos(theta), sqrt(1-z^2)*sin(theta),z)
Returns
-------
u: np.ndarray
A numpy array of shape `(3,)`. u is an unit vector
"""
theta = np.random.uniform(low=0.0, high=2 * np.pi)
z = np.random.uniform(low=-1.0, high=1.0)
u = np.array(
[np.sqrt(1 - z**2) * np.cos(theta),
np.sqrt(1 - z**2) * np.sin(theta), z])
return u
def generate_random_rotation_matrix() -> np.ndarray:
r"""Generates a random rotation matrix.
1. Generate a random unit vector u, randomly sampled from the
unit sphere (see function generate_random_unit_vector()
for details)
2. Generate a second random unit vector v
a. If absolute value of u \dot v > 0.99, repeat.
(This is important for numerical stability. Intuition: we
want them to be as linearly independent as possible or
else the orthogonalized version of v will be much shorter
in magnitude compared to u. I assume in Stack they took
this from Gram-Schmidt orthogonalization?)
b. v" = v - (u \dot v)*u, i.e. subtract out the component of
v that's in u's direction
c. normalize v" (this isn"t in Stack but I assume it must be
done)
3. find w = u \cross v"
4. u, v", and w will form the columns of a rotation matrix, R.
The intuition is that u, v" and w are, respectively, what
the standard basis vectors e1, e2, and e3 will be mapped
to under the transformation.
Returns
-------
R: np.ndarray
A numpy array of shape `(3, 3)`. R is a rotation matrix.
"""
u = generate_random_unit_vector()
v = generate_random_unit_vector()
while np.abs(np.dot(u, v)) >= 0.99:
v = generate_random_unit_vector()
vp = v - (np.dot(u, v) * u)
vp /= np.linalg.norm(vp)
w = np.cross(u, vp)
R = np.column_stack((u, vp, w))
return R
def rotate_molecules(mol_coordinates_list):
"""Rotates provided molecular coordinates.
Pseudocode:
1. Generate random rotation matrix. This matrix applies a random
transformation to any 3-vector such that, were the random transformation
repeatedly applied, it would randomly sample along the surface of a sphere
with radius equal to the norm of the given 3-vector cf.
_generate_random_rotation_matrix() for details
2. Apply R to all atomic coordinatse.
3. Return rotated molecule
"""
R = generate_random_rotation_matrix()
rotated_coordinates_list = []
for mol_coordinates in mol_coordinates_list:
coordinates = deepcopy(mol_coordinates)
rotated_coordinates = np.transpose(np.dot(R, np.transpose(coordinates)))
rotated_coordinates_list.append(rotated_coordinates)
return (rotated_coordinates_list)
def is_angle_within_cutoff(vector_i: np.ndarray, vector_j: np.ndarray,
angle_cutoff: float) -> bool:
"""A utility function to compute whether two vectors are within a cutoff from 180 degrees apart.
Parameters
----------
vector_i: np.ndarray
A numpy array of shape (3,)`, where `3` is (x,y,z).
vector_j: np.ndarray
A numpy array of shape `(3,)`, where `3` is (x,y,z).
cutoff: float
The deviation from 180 (in degrees)
Returns
-------
bool
Whether two vectors are within a cutoff from 180 degrees apart
"""
angle = angle_between(vector_i, vector_j) * 180. / np.pi
return (angle > (180 - angle_cutoff) and angle < (180. + angle_cutoff))
def compute_centroid(coordinates: np.ndarray) -> np.ndarray:
"""Compute the (x,y,z) centroid of provided coordinates
Parameters
----------
coordinates: np.ndarray
A numpy array of shape `(N, 3)`, where `N` is the number of atoms.
Returns
-------
centroid: np.ndarray
A numpy array of shape `(3,)`, where `3` is (x,y,z).
"""
centroid = np.mean(coordinates, axis=0)
return centroid
def compute_protein_range(coordinates: np.ndarray) -> np.ndarray:
"""Compute the protein range of provided coordinates
Parameters
----------
coordinates: np.ndarray
A numpy array of shape `(N, 3)`, where `N` is the number of atoms.
Returns
-------
protein_range: np.ndarray
A numpy array of shape `(3,)`, where `3` is (x,y,z).
"""
protein_max = np.max(coordinates, axis=0)
protein_min = np.min(coordinates, axis=0)
protein_range = protein_max - protein_min
return protein_range
def subtract_centroid(coordinates: np.ndarray,
centroid: np.ndarray) -> np.ndarray:
"""Subtracts centroid from each coordinate.
Subtracts the centroid, a numpy array of dim 3, from all coordinates
of all atoms in the molecule
Note that this update is made in place to the array it's applied to.
Parameters
----------
coordinates: np.ndarray
A numpy array of shape `(N, 3)`, where `N` is the number of atoms.
centroid: np.ndarray
A numpy array of shape `(3,)`
Returns
-------
coordinates: np.ndarray
A numpy array of shape `(3,)`, where `3` is (x,y,z).
"""
coordinates -= np.transpose(centroid)
return coordinates
def compute_pairwise_distances(first_coordinate: np.ndarray,
second_coordinate: np.ndarray) -> np.ndarray:
"""Computes pairwise distances between two molecules.
Takes an input (m, 3) and (n, 3) numpy arrays of 3D coords of
two molecules respectively, and outputs an m x n numpy
array of pairwise distances in Angstroms between the first and
second molecule. entry (i,j) is dist between the i"th
atom of first molecule and the j"th atom of second molecule.
Parameters
----------
first_coordinate: np.ndarray
A numpy array of shape `(m, 3)`, where `m` is the number of atoms.
second_coordinate: np.ndarray
A numpy array of shape `(n, 3)`, where `n` is the number of atoms.
Returns
-------
pairwise_distances: np.ndarray
A numpy array of shape `(m, n)`
"""
pairwise_distances = cdist(
first_coordinate, second_coordinate, metric='euclidean')
return pairwise_distances