-
Notifications
You must be signed in to change notification settings - Fork 5
/
selectors.py
528 lines (465 loc) · 18.6 KB
/
selectors.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
import numpy as np
from chimerax.atomic import AtomicStructure, Atoms, selected_atoms, selected_bonds
from chimerax.core.commands import register_selector
from AaronTools.atoms import BondOrder
from AaronTools.finders import ChiralCenters, VSEPR, Bridgehead, SpiroCenters
from AaronTools.substituent import Substituent
from AaronTools.const import TMETAL
from AaronTools.utils.prime_numbers import Primes
from SEQCROW.residue_collection import ResidueCollection
from collections import deque
from warnings import warn
Primes()
BondOrder()
def register_selectors(logger, name):
logger.info(name)
if name == "tm":
register_selector("tm", tm_selector, logger, desc="transition metals")
elif any(name == sub for sub in Substituent.list()):
register_selector(
name,
lambda sess, models, results, sub_name=name: substituent_selection(
sess,
sub_name,
models,
results
),
logger,
desc="substituent %s" % name
)
elif name == "connected":
register_selector("connected", all_connected_selector, logger, desc="fragment connected to selected atoms")
elif any(name == vsepr for vsepr in [
"t-shaped",
"trigonal-planar",
"tetrahedral",
"sawhorse",
"seesaw",
"square-planar",
"trigonal-pyramidal",
"trigonal-bipyramidal",
"square-pyramidal",
"pentagonal",
"octahedral",
"hexagonal",
"trigonal-prismatic",
"pentagonal-pyramidal",
"capped-octahedral",
"capped-trigonal-prismatic",
"heptagonal",
"hexagonal-pyramidal",
"pentagonal-bipyramidal",
"biaugmented-trigonal-prismatic",
"cubic",
"elongated-trigonal-bipyramidal",
"hexagonal-bipyramidal",
"heptagonal-pyramidal",
"octagonal",
"square-antiprismatic",
"trigonal-dodecahedral",
"capped-cube",
"capped-square-antiprismatic",
"enneagonal",
"heptagonal-bipyramidal",
"hula-hoop",
"triangular-cupola",
"tridiminished-icosahedral",
"muffin",
"octagonal-pyramidal",
"tricapped-trigonal-prismatic",
]):
print("vsepr")
new_name = name
if name != "hula-hoop":
new_name = name.replace("-", " ")
register_selector(
name,
lambda sess, models, results, vsepr_name=new_name: vsepr_selection(
sess,
vsepr_name,
models,
results
),
logger,
desc="%s shape" % name
)
elif any(name == vsepr for vsepr in [
"linear",
"bent",
"planar",
]):
print("vsepr")
name_map = {
"linear": ["linear 1", "linear 2"],
"bent": [
"bent 2 planar",
"bent 2 tetrahedral",
"bent 3 tetrahedral",
],
"planar": [
"trigonal planar",
"square planar",
],
}
finders = name_map[name]
register_selector(
name,
lambda sess, models, results, vsepr_name=finders: vsepr_selection(
sess,
vsepr_name,
models,
results
),
logger,
desc="%s shape" % name
)
elif name == "bridgehead":
register_selector(
name,
lambda sess, models, results, finder=Bridgehead(): finder_selection(
sess,
finder,
models,
results
),
logger,
desc="%s atoms" % name.replace("-", " ")
)
elif name == "spiro-centers":
register_selector(
name,
lambda sess, models, results, finder=SpiroCenters(): finder_selection(
sess,
finder,
models,
results
),
logger,
desc="%s" % name.replace("-", " ")
)
elif name == "chiral-centers":
register_selector(
name,
lambda sess, models, results, finder=ChiralCenters(): finder_selection(
sess,
finder,
models,
results
),
logger,
desc="%s" % name.replace("-", " ")
)
def tm_selector(session, models, results):
"""select transition metals using AaronTools' TMETAL dictionary"""
atoms = []
for model in models:
if isinstance(model, AtomicStructure):
for atom in model.atoms:
if atom.element.name in TMETAL:
atoms.append(atom)
#need to add a Collection, not just a list of atoms
results.add_atoms(Atoms(atoms))
def vsepr_selection(session, vsepr_name, models, results):
atoms = []
if isinstance(vsepr_name, str):
finders = VSEPR(vsepr_name)
else:
finders = [VSEPR(name) for name in vsepr_name]
for model in models:
if isinstance(model, AtomicStructure):
rescol = ResidueCollection(model)
try:
rescol_atoms = rescol.find(finders)
atoms.extend([atom.chix_atom for atom in rescol_atoms])
except LookupError:
continue
#need to add a Collection, not just a list of atoms
results.add_atoms(Atoms(atoms))
def finder_selection(self, finder, models, results):
atoms = []
for model in models:
if isinstance(model, AtomicStructure):
rescol = ResidueCollection(
model, refresh_ranks=False,
)
try:
rescol_atoms = rescol.find(finder)
atoms.extend([atom.chix_atom for atom in rescol_atoms])
except LookupError:
continue
#need to add a Collection, not just a list of atoms
results.add_atoms(Atoms(atoms))
#reimplemented some AaronTools but with chimerax stuff because of
#performace reasons
def substituent_selection(session, sub_name, models, results):
#TODO: optimize - or cheat and use cython or something
#TODO: make it so it doesn't select things with just an H bonded to them
# e.g. sel OH should not select water molecules
# probably do a get_all_connected for each fragment and
# check if all_connected.subtract(Atoms[atom]).subtract(frag) leave just an H
atoms = Atoms()
sub = Substituent(sub_name)
chix_sub = ResidueCollection(sub).get_chimera(session)
sub_elements = sorted(chix_sub.atoms.elements.names)
sub_ranks = canonical_rank(Atoms(chix_sub.atoms))
sorted_sub_atoms = [x for _, x in sorted(zip(sub_ranks, chix_sub.atoms), key = lambda pair: pair[0])]
length = len(sub.atoms)
#rank_time = 0
#frag_time = 0
for model in models:
if isinstance(model, AtomicStructure):
for atom in model.atoms:
#session.logger.info("checking groups on %s" % atom.atomspec)
for bonded_atom in atom.neighbors:
if bonded_atom.element.name != sub.atoms[0].element:
continue
#session.logger.info("fragment for %s" % bonded_atom.atomspec)
#frag_start = perf_counter()
frag = get_fragment(bonded_atom, atom, length)
#frag_stop = perf_counter()
#frag_time += frag_stop - frag_start
if frag.intersects(atoms):
continue
frag = frag.subtract(Atoms([atom]))
if len(frag) != length:
continue
elements = sorted(frag.elements.names)
if sub_elements != elements:
#session.logger.info("wrong elements")
continue
#rank_start = perf_counter()
frag_ranks = canonical_rank(frag)
#rank_stop = perf_counter()
#rank_time += rank_stop - rank_start
#session.logger.warning(", ".join(sub_elements))
#session.logger.warning("%s;\n%s" % (", ".join(str(x) for x in sorted(frag_ranks)), ", ".join(str(x) for x in sorted(sub_ranks))))
sorted_frag_atoms = [x for _, x in sorted(zip(frag_ranks, frag.instances()), key = lambda pair: pair[0])]
#session.logger.warning("%s;\n%s" % (", ".join(x.atomspec for x in sorted_frag_atoms), ", ".join(x.name for x in sorted_sub_atoms)))
for a, b in zip(sorted_frag_atoms, sorted_sub_atoms):
#session.logger.info("%s %s" % (a.atomspec, b.name))
if a.element.name != b.element.name:
#session.logger.info("different elements")
break
#session.logger.info("bonded: %s; other: %s" % (bonded_atom.atomspec, atom.atomspec))
if a is not bonded_atom and len(a.neighbors) != len(b.neighbors):
#session.logger.info("different num neighbors")
#session.logger.info("%s and %s" % (a.atomspec, b.name))
#session.logger.info("%i vs %i" % (len(a.neighbors), len(b.neighbors)))
break
elif a is bonded_atom and (len(a.neighbors) - 1) != len(b.neighbors):
#session.logger.info("first atom, different num neighbors")
#session.logger.info("%s and %s" % (a.atomspec, b.name))
#session.logger.info("%i vs %i" % (len(a.neighbors) - 1, len(b.neighbors)))
break
failed = False
for i, j, k in zip(
sorted([aa.element.name for aa in a.neighbors if ((aa is not atom and a is bonded_atom) or a is not bonded_atom)]),
sorted([bb.element.name for bb in b.neighbors]),
sorted([aa for aa in a.neighbors if ((aa is not atom and a is bonded_atom) or a is not bonded_atom)]),
):
if i != j:
#session.logger.info("failed %s %s, %s" % (i, j, k.atomspec))
failed = True
break
if failed:
break
else:
atoms = atoms.merge(frag)
#session.logger.info("spent %f time fragmenting" % frag_time)
#session.logger.info("spent %f time ranking atoms" % rank_time)
results.add_atoms(atoms)
def all_connected_selector(session, models, results):
"""select all atoms connected to the current selection"""
# TODO: right mouse mode for this
cur_sel = selected_atoms(session)
bond_sel = selected_bonds(session)
for bond in bond_sel:
cur_sel = cur_sel.merge(Atoms(bond.atoms))
atoms = Atoms()
for atom in cur_sel:
if atom in atoms:
continue
elif atom.structure not in models:
continue
connected_atoms = get_fragment(atom, max_len=len(atom.structure.atoms))
atoms = atoms.merge(connected_atoms)
results.add_atoms(atoms)
def get_fragment(start, stop=None, max_len=100000):
"""
see AaronTools.geometry.Geometry.get_fragment
"""
stack = deque([start])
frag = deque([start])
if stop is not None:
stop = set([stop])
while len(stack) > 0 and len(frag) <= max_len:
connected = stack.popleft()
connected = set(connected.neighbors) - stop - set(frag)
stack.extend(connected)
frag.extend(connected)
else:
while len(stack) > 0 and len(frag) <= max_len:
connected = stack.popleft()
connected = set(connected.neighbors) - set(frag)
stack.extend(connected)
frag.extend(connected)
return Atoms(frag)
def get_invariant(atom, atoms):
"""
gets initial invariant based on self's element and the element of
the atoms connected to self
same as AaronTools.Atom.get_neighbor_id
"""
# atomic number
z = atom.element.number
s = "%03i" % z
#atom is chimerax atom
heavy = [x.element.number for x in atom.neighbors if x.element.name != "H" and x in atoms]
# number of non-hydrogen connections:
s += "%02i" % len(heavy)
# number of bonds with heavy atoms
for h in sorted(set(heavy)):
s += "%03i" % h
s += "%02i" % heavy.count(h)
# number of connected hydrogens
nH = len([x for x in atom.neighbors if x in atoms]) - len(heavy)
s += "%02i" % nH
return s
def canonical_rank(structure, heavy_only=False, break_ties=True):
"""
see AaronTools.geometry.Geometry.canonical_rank
structure is Atoms collection
"""
primes = Primes.list(len(structure.instances()))
atoms = []
ranks = []
def neighbors_rank(ranks):
# partitions key is product of rank and neighbors' rank
# use prime numbers for product so products are distinct
# eg: primes[2]*primes[2] != primes[1]*primes[4]
partitions = {}
for i, a in enumerate(atoms):
key = primes[ranks[i]]
for b in a.neighbors:
if b in atoms:
key *= primes[ranks[atoms.index(b)]]
partitions.setdefault(ranks[i], {})
partitions[ranks[i]].setdefault(key, [])
partitions[ranks[i]][key] += [i]
return update_ranks(ranks, partitions)
def update_ranks(ranks, partitions):
new_ranks = ranks.copy()
for rank, key_dict in partitions.items():
if len(key_dict) == 1:
continue
for key in sorted(key_dict.keys()):
for idx in key_dict[key]:
new_ranks[idx] = rank
rank += len(key_dict[key])
return new_ranks
def tie_break(ranks):
"""
Uses atom angles around COM -> shared_atom axis to break ties[
Does not break symmetry (eg: pentane carbons still [0, 2, 4, 2, 0]
because C2 and C4 are ~180 deg apart relative to COM-C5 axis)
"""
def get_angle(vi, vj, norm):
dot = np.dot(vi, vj)
cross = np.cross(vi, vj)
det = np.dot(norm, cross)
rv = np.arctan2(det, dot)
return round(rv, 1)
partitions = {}
for i, rank in enumerate(ranks):
partitions.setdefault(rank, {})
partitions[rank].setdefault(rank, [])
partitions[rank][rank] += [i]
new_partitions = partitions.copy()
for rank, rank_dict in partitions.items():
idx_list = rank_dict[rank]
if len(idx_list) == 1:
continue
# split ties into groups connected to same atom
groups = {}
for i in idx_list[:-1]:
a = atoms[i]
for j in idx_list[1:]:
b = atoms[j]
connected = [x for x in a.neighbors if x in b.neighbors]
#connected = sorted(connected, key=lambda x, atoms=atoms: get_invariant(x, atoms))
if len(connected) == 1:
k = connected.pop()
if k in atoms:
k = atoms.index(k)
else:
continue
groups.setdefault(k, set([i]))
groups[k] |= set([j])
# atoms in each group sorted in counter clockwise order
# around axis between shared atom and COM
for shared_idx, connected in groups.items():
shared = atoms[shared_idx]
connected = sorted(connected)
center = np.mean(structure.coords, axis=0)
norm = shared.coord - center
start_idx = None
min_dist = None
for c in connected:
this = np.linalg.norm(atoms[c].coord - center)
if min_dist is None or this < min_dist:
min_dist = this
start_idx = c
start = atoms[start_idx].coord - shared.coord
angles = {0: [start_idx]}
for c in connected:
if c == start_idx:
continue
this = atoms[c].coord - shared.coord
angle = get_angle(start, this, norm)
angles.setdefault(angle, [])
angles[angle] += [c]
for i, angle in enumerate(sorted(angles.keys())):
new_partitions[rank].setdefault(rank + i, [])
new_partitions[rank][rank + i] += angles[angle]
for idx in angles[angle]:
new_partitions[rank][rank].remove(idx)
break
return update_ranks(ranks, new_partitions)
# rank all atoms the same initially
for a in structure:
if heavy_only and a.element.name == "H":
continue
atoms += [a]
ranks += [0]
# partition and re-rank using invariants
partitions = {}
for i, a in enumerate(atoms):
invariant = get_invariant(a, atoms)
partitions.setdefault(invariant, [])
partitions[invariant] += [i]
new_rank = 0
for key in sorted(partitions.keys()):
idx_list = partitions[key]
for idx in idx_list:
ranks[idx] = new_rank
new_rank += len(idx_list)
# re-rank using neighbors until no change
for i in range(500):
new_ranks = neighbors_rank(ranks)
if ranks == new_ranks:
break
ranks = new_ranks
else:
warn("Max cycles reached in canonical sorting (neighbor-ranks)")
# break ties using spatial positions
# AND update neighbors until no change
if break_ties:
for i in range(500):
new_ranks = tie_break(ranks)
new_ranks = neighbors_rank(new_ranks)
if ranks == new_ranks:
break
ranks = new_ranks
else:
warn("Max cycles reached in canonical sorting (tie-breaking)")
return ranks