-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02-spread-on-mesh.py
201 lines (159 loc) · 6.92 KB
/
02-spread-on-mesh.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
import itertools
from pathlib import Path
import numpy as np
import sys
import argparse
import MDAnalysis as mda
from MDAnalysis.analysis.leaflet import LeafletFinder
from geodesic import ExactGeodesicMixin
import pyvista as pv
from sklearn.neighbors import NearestNeighbors
from tqdm import tqdm
import uuid
def log_samples(start,end,num=50):
""" start: starting point in linspace (cast to int)
end: endpoint in linspace (cast to int)
Casting the samples to 'int' reduces their number,
as 1., 1.2, ... all map to 1. This is solved by
increasing the 'apparent' num until the output has
the desired dimensions.
NOTE: num cannot be larger than the max number of
integers in the range [start, end].
"""
start = int(start)
end = int(end)
if start < 1 or end < 1:
raise ValueError
nmax = end - start + 1
if num >= nmax:
return np.linspace(start,end,num=nmax,dtype=int)
s = np.log10(start)
e = np.log10(end)
n = num
while True:
out = np.unique(np.logspace(s,e, num=n,dtype=int))
if len(out) == num:
return out
n += 1
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter):
pass
desc = """Map particle positions to mesh, based on lagtime displacements.
The program takes a mesh generated by \'01-generate-mesh.py\', and discretizes
the positions so that the particle and its lagtime-shifted version both fall on
the mesh, along with their displacement vector.
"""
parser = argparse.ArgumentParser(description=desc, formatter_class=CustomFormatter)
parser.add_argument('mesh')
parser.add_argument('--logmin' , default=1 , type=int , help="Beginning of log-spaced lagtimes (# of frames)")
parser.add_argument('--logmax' , default=500, type=int , help="End of log-spaced lagtimes (# of frames)")
parser.add_argument('--logstep' , default=50 , type=int , help="Stride of log-spaced lagtimes (# of frames)")
parser.add_argument('--trestart', default=1 , type=int , help="Time between restarting points (# of frames)")
parser.add_argument('--maxd' , default=15 , type=float, help="Max. allowed distance between the continous and discrete positions (angstrom)")
parser.add_argument('--lg' , default=None, type=str , help="Atomtype for leaflet-identification. Preferably the headgroup.")
args = parser.parse_args()
# ##########################################
# # #
# # MAPPING TO MESH #
# # #
# ##########################################
# Load the configuration
mesh = pv.read(args.mesh)
topology = mesh.field_arrays['topology'][0]
trajectory = mesh.field_arrays['trajectory'][0]
if args.lg:
select = args.lg
else:
select = mesh.field_arrays['select'][0]
leaflet = mesh.field_arrays['leaflet'][0]
cutoff = mesh.field_arrays['cutoff'][0]
lx = mesh.field_arrays['lx'][0]
ly = mesh.field_arrays['ly'][0]
universe = mda.Universe(topology, trajectory)
if leaflet != 'both':
lf = LeafletFinder(universe, select, pbc=True, cutoff=cutoff)
assert len(lf.groups()) == 2, f"Could not separate {trajectory} into upper and lower leaflets..."
if leaflet == "upper":
indices = lf.groups(0).indices
if leaflet == "lower":
indices = lf.groups(1).indices
selection = universe.atoms[indices]
else:
selection = universe.select_atoms(select)
print ()
print (f"* Mapping onto mesh {sys.argv[1]}")
print (f" topology: {topology}")
print (f" trajectory: {trajectory}")
print (f" leaflet: \'{leaflet}\' based on group {select}")
print (f" Selected {selection.__repr__()}")
fname = f"indices-{uuid.uuid4()}.dat"
print (f" Saving to binary {fname}")
mesh.field_arrays['indexfile'] = (fname,)
p = Path(fname)
p.unlink(missing_ok=True)
lagtimes = log_samples(args.logmin,args.logmax,args.logstep)
print (f" Log-spaced samples from {lagtimes[0]} to {lagtimes[-1]} -- {len(lagtimes)} steps")
pts = mesh.points
neigh = NearestNeighbors(n_neighbors=1,n_jobs=-1)
neigh.fit(pts)
with open(p, "ab") as f:
for i in tqdm(range(0,universe.trajectory.n_frames,args.trestart)):
# Calling the trajectory updates the positions
universe.trajectory[i]
# Real CoM positions of the particles @lagtime=0
# Acont = np.array([res.atoms.center_of_mass() for res in selection.residues])
Acont = np.array([res.atoms.center_of_geometry() for res in selection.residues])
# Loop over all lagtimes
for dt in lagtimes:
j = dt +i
if j >= universe.trajectory.n_frames:
break
universe.trajectory[j]
# Bcont = np.array([res.atoms.center_of_mass() for res in selection.residues])
Bcont = np.array([res.atoms.center_of_geometry() for res in selection.residues])
M = np.minimum(Acont,Bcont)
shift = np.floor_divide(M,[lx,ly,np.inf])
shift[:,0] *=lx
shift[:,1] *=ly
shift[:,2] = 0
As = Acont - shift
Bs = Bcont - shift
dA, ndx_A = neigh.kneighbors(As)
dB, ndx_B = neigh.kneighbors(Bs)
ndx_A = ndx_A.flatten()
ndx_B = ndx_B.flatten()
# TOO LARGE DEVIATION BETWEEN SURFACE AND MOLECULE
if max(dA.max(),dB.max()) > args.maxd:
if dA.max() > dB.max():
max_diff = dA.max()
max_ndx = dA.argmax()
max_conf = As
max_mesh = ndx_A
max_time = i
else:
max_diff = dB.max()
max_ndx = dB.argmax()
max_conf = Bs
max_mesh = ndx_B
max_time = j
print ()
print ("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print ()
print (f" Largest distance between mesh and trajectory {max_diff} is larger than the prescribed {args.maxd}")
print ()
print (f" Mesh point: {max_mesh[max_ndx]}")
print (f" xyz : {mesh.points[max_mesh[max_ndx]]}")
print ()
print (f" Traj point: {max_ndx}")
print (f" xyz : {max_conf[max_ndx]}")
print (f" frame: {max_time}")
print ()
print ("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print ()
# Save indices to file
indices = np.minimum(ndx_A,ndx_B), np.maximum(ndx_A,ndx_B), np.zeros(ndx_A.shape)+j-i
indices = np.array(indices,dtype=np.int32).T
indices.tofile(f)
print ()
print ("* Updating the mesh metadata")
mesh.field_arrays['lagtimes'] = lagtimes
mesh.save(args.mesh)