-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgeometry.py
7618 lines (6742 loc) · 295 KB
/
geometry.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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""For storing, manipulating, and measuring molecular structures"""
import itertools
import os
import re
import ssl
from collections import deque
from copy import deepcopy
import concurrent.futures
import numpy as np
from scipy.spatial import distance_matrix, distance
import AaronTools
from AaronTools import default_config as DEFAULT_CONFIG
import AaronTools.utils.utils as utils
from AaronTools import addlogger
from AaronTools.atoms import Atom, BondOrder
from AaronTools.config import Config
from AaronTools.const import AARONLIB, AARONTOOLS, BONDI_RADII, D_CUTOFF, ELEMENTS, TMETAL, VDW_RADII, RADII
from AaronTools.fileIO import FileReader, FileWriter, read_types
from AaronTools.finders import Finder, OfType, WithinRadiusFromPoint, WithinRadiusFromAtom, WithinBondsOf
from AaronTools.utils.prime_numbers import Primes
from AaronTools.oniomatoms import OniomAtom
COORD_THRESHOLD = 0.2
CACTUS_HOST = "https://cactus.nci.nih.gov"
OPSIN_HOST = "https://opsin.ch.cam.ac.uk"
if not DEFAULT_CONFIG["DEFAULT"].getboolean("local_only"):
import urllib.parse
from urllib.error import HTTPError
from urllib.request import urlopen
@addlogger
class Geometry:
"""
Attributes:
* name
* comment
* atoms
* other
* _iter_idx
"""
# AaronTools.addlogger decorator will add logger to this class attribute
LOG = None
# decorator uses this to set log level (defaults to WARNING if None)
# LOGLEVEL = "INFO"
# add to this dict to override log level for specific functions
# keys are log level, values are lists of function names
# LOGLEVEL_OVERRIDE = {"DEBUG": "find"}
Primes()
def __init__(
self,
structure="",
name="",
comment="",
components=None,
refresh_connected=True,
refresh_ranks=True,
):
"""
:param structure: can be a Geometry(), a FileReader(), a file name, or a
list of atoms
:param str name: name
:param str comment: comment
:param list(AaronTools.component.Component())|None components: components list or None
:param bool refresh_connected: usually True - determine connectivity
can save time for methods that only need coordinates by using
`refresh_connected=False`
:param bool refresh_ranks: usually True - rank atoms, False when loading from database
can save time for methods that only don't rely on ranks by using
`refresh_ranks=False`
"""
super().__setattr__("_hashed", False)
self.name = name
self.comment = comment
self.atoms = []
self.center = None
self.components = components
self.other = {}
self._iter_idx = None
self._sigmat = None
self._epsmat = None
if isinstance(structure, Geometry):
# new from geometry
self.atoms = structure.atoms
if not name:
self.name = structure.name
if not comment:
self.comment = structure.comment
return
elif isinstance(structure, FileReader):
# get info from FileReader object
from_file = structure
elif isinstance(structure, str) and structure:
# parse file
from_file = FileReader(structure)
elif hasattr(structure, "__iter__") and structure:
for a in structure:
if not isinstance(a, Atom):
raise TypeError
else:
# list of atoms supplied
self.atoms = structure
if refresh_connected:
# SEQCROW sometimes uses refresh_connected=False to keep
# the connectivity the same as what's on screen
self.refresh_connected()
if refresh_ranks:
self.refresh_ranks()
return
else:
return
# only get here if we were given a file reader object or a file name
self.name = from_file.name
self.comment = from_file.comment
self.atoms = from_file.atoms
self.other = self.parse_comment()
if refresh_connected:
# some file types contain connectivity info (e.g. sd) - might not want
# to overwrite that
self.refresh_connected()
if refresh_ranks:
self.refresh_ranks()
return
# class methods
@staticmethod
def iupac2smiles(name):
"""
convert IUPAC name to SMILES using the OPSIN web API
:param str name: IUPAC name of a molecule
:return: SMILES name of a molecule
"""
if DEFAULT_CONFIG["DEFAULT"].getboolean("local_only"):
raise PermissionError(
"Converting IUPAC to SMILES failed. External network lookup disallowed."
)
# opsin seems to be better at iupac names with radicals
url_smi = "{}/opsin/{}.smi".format(
OPSIN_HOST, urllib.parse.quote(name)
)
try:
smiles = (
urlopen(url_smi, context=ssl.SSLContext())
.read()
.decode("utf8")
)
except HTTPError:
raise RuntimeError(
"%s is not a valid IUPAC name or https://opsin.ch.cam.ac.uk is down"
% name
)
return smiles
@classmethod
def from_string(cls, name, form="smiles", strict_use_rdkit=False):
"""
Converts a string input into a Geometry object
:param str name: either an IUPAC name or a SMILES for a molecule
:param str form: * "smiles" - structure from cactvs API/RDKit
* "iupac" - iupac to smiles from opsin API, then the same as form=smiles
:param bool strict_use_rdkit: force use of RDKit and never use cactvs
:return: Geometry object that matches the input name
:rtype: Geometry
"""
# CC and HOH are special-cased because they are used in
# the automated testing and we don't want that to fail
# b/c cactus is down and the user doesn't have rdkit
# these structures are from NIST
if name == "CC":
return cls([
Atom("C", coords=[0.0, 0.0, 0.7680], name="1"),
Atom("C", coords=[0.0, 0.0, -0.7680], name="2"),
Atom("H", coords=[-1.0192, 0.0, 1.1573], name="3"),
Atom("H", coords=[0.5096, 0.8826, 1.1573], name="4"),
Atom("H", coords=[0.5096, -0.8826, 1.1573], name="5"),
Atom("H", coords=[1.0192, 0.0, -1.1573], name="6"),
Atom("H", coords=[-0.5096, -0.8826, -1.1573], name="7"),
Atom("H", coords=[-0.5096, 0.8826, -1.1573], name="8"),
])
elif name == "HOH":
return cls([
Atom("H", coords=[0.0, 0.7572, -0.4692], name="1"),
Atom("O", coords=[0.0, 0.0, 0.0], name="2"),
Atom("H", coords=[0.0, -0.7572, -0.4692], name="3"),
])
elif name == "ClC(Cl)Cl":
return cls([
Atom("Cl", coords=[-0.59020, 1.58610, -0.40730], name="1"),
Atom("C", coords=[ 0.00140, -0.00160, 0.12250], name="2"),
Atom("Cl", coords=[-1.05120, -1.30360, -0.49820], name="3"),
Atom("Cl", coords=[ 1.66160, -0.20470, -0.44580], name="4"),
Atom("H", coords=[-0.02170, -0.07610, 1.22880], name="5"),
])
def get_cactus_sd(smiles):
if DEFAULT_CONFIG["DEFAULT"].getboolean("local_only"):
raise PermissionError(
"Cannot retrieve structure from {}. External network lookup disallowed.".format(
CACTUS_HOST
)
)
url_sd = "{}/cgi-bin/translate.tcl?smiles={}&format=sdf&astyle=kekule&dim=3D&file=".format(
CACTUS_HOST, urllib.parse.quote(smiles)
)
s_sd_get = urlopen(url_sd, context=ssl.SSLContext())
msg, status = s_sd_get.msg, s_sd_get.status
if msg != "OK":
cls.LOG.error(
"Issue contacting %s for SMILES lookup (status: %s)",
CACTUS_HOST,
status,
)
raise IOError
s_sd_get = s_sd_get.read().decode("utf8")
try:
tmp_url = re.search(
'User-defined exchange format file: <a href="(.*)"',
s_sd_get,
).group(1)
except AttributeError as err:
if re.search("You entered an invalid SMILES", s_sd_get):
cls.LOG.error(
"Invalid SMILES encountered: %s (consult %s for syntax help)",
smiles,
"https://cactus.nci.nih.gov/translate/smiles.html",
)
exit(1)
raise IOError(err)
new_url = "{}{}".format(CACTUS_HOST, tmp_url)
s_sd = (
urlopen(new_url, context=ssl.SSLContext())
.read()
.decode("utf8")
)
return s_sd
if DEFAULT_CONFIG["DEFAULT"].getboolean("local_only"):
strict_use_rdkit = True
accepted_forms = ["iupac", "smiles"]
if form not in accepted_forms:
raise NotImplementedError(
"cannot create substituent given %s; use one of %s" % form,
str(accepted_forms),
)
if form == "smiles":
smiles = name
elif form == "iupac":
smiles = cls.iupac2smiles(name)
try:
import rdkit.Chem.AllChem as rdk
m = rdk.MolFromSmiles(smiles)
if m is None and not strict_use_rdkit:
s_sd = get_cactus_sd(smiles)
elif m:
mh = rdk.AddHs(m)
rdk.EmbedMolecule(mh, randomSeed=0x421C52)
s_sd = rdk.MolToMolBlock(mh)
else:
raise RuntimeError(
"Could not load {} with RDKit".format(smiles)
)
except ImportError:
s_sd = get_cactus_sd(smiles)
try:
f = FileReader((name, "sd", s_sd))
is_sdf = True
except ValueError:
# for some reason, CACTUS is giving xyz files instead of sdf...
is_sdf = False
try:
f = FileReader((name, "xyz", s_sd))
except ValueError:
cls.LOG.error("Error loading geometry:\n %s", s_sd)
raise
return cls(f, refresh_connected=not is_sdf)
@classmethod
def get_coordination_complexes(
cls,
center,
ligands,
shape,
c2_symmetric=None,
minimize=False,
session=None, # This parameter is unused in the method; possibly should be removed?
):
"""
get all unique coordination complexes
uses templates from Inorg. Chem. 2018, 57, 17, 10557–10567
:param str center: - element of center atom
:param list(str) ligands: - list of ligand names in the ligand library
:param str shape: coordination geometry (e.g. octahedral) - see Atom.get_shape
:param list(bool) c2_symmetric: specify which of the bidentate ligands are C2-symmetric
if this list is as long as the ligands list, the nth item corresponds
to the nth ligand
otherwise, the nth item indicate the symmetry of the nth bidentate ligand
:param bool minimize: passed to cls.map_ligand when adding ligands
:return: a list of cls containing all unique coordination complexes and the
general formula of the complexes
:rtype: list(Geometry)
"""
import os.path
from AaronTools.atoms import BondOrder
from AaronTools.component import Component
from AaronTools.const import AARONTOOLS
if c2_symmetric is None:
c2_symmetric = []
for lig in ligands:
comp = Component(lig)
if not len(comp.key_atoms) == 2:
c2_symmetric.append(False)
continue
c2_symmetric.append(comp.c2_symmetric())
bo = BondOrder()
# create a geometry with the specified shape
# change the elements from dummy atoms to something else
start_shape = Atom.get_shape(shape)
start_atoms = [
Atom(element="B", coords=coords, name="%i" % i) for i, coords in
enumerate(start_shape)
]
n_coord = len(start_atoms) - 1
start_atoms[0].element = center
start_atoms[0].reset()
for atom in start_atoms[1:]:
start_atoms[0].connected.add(atom)
atom.connected.add(start_atoms[0])
atom.reset()
geom = cls(start_atoms, refresh_connected=False, refresh_ranks=False)
# we'll need to determine the formula of the requested complex
# monodentate ligands are a, b, etc
# symmetric bidentate are AA, BB, etc
# asymmetric bidentate are AB, CD, etc
# ligands are sorted monodentate, followed by symmetric bidentate, followed by
# asymmetric bidentate, then by decreasing count
# e.g., Ca(CO)2(ACN)4 is Ma4b2
alphabet = "abcdefghi"
symmbet = ["AA", "BB", "CC", "DD"]
asymmbet = ["AB", "CD", "EF", "GH"]
monodentate_names = []
symm_bidentate_names = []
asymm_bidentate_names = []
n_bidentate = 0
# determine types of ligands
for i, lig in enumerate(ligands):
comp = Component(lig)
if len(comp.key_atoms) == 1:
monodentate_names.append(lig)
elif len(comp.key_atoms) == 2:
if len(ligands) == len(c2_symmetric):
c2 = c2_symmetric[i]
else:
c2 = c2_symmetric[n_bidentate]
n_bidentate += 1
if c2:
symm_bidentate_names.append(lig)
else:
asymm_bidentate_names.append(lig)
else:
# tridentate or something
raise NotImplementedError(
"can only attach mono- and bidentate ligands: %s (%i)"
% (lig, len(comp.key_atoms))
)
coord_num = len(monodentate_names) + 2 * (
len(symm_bidentate_names) + len(asymm_bidentate_names)
)
if coord_num != n_coord:
raise RuntimeError(
"coordination number (%i) does not match sum of ligand denticity (%i)"
% (n_coord, coord_num)
)
# start putting formula together
cc_type = "M"
this_name = center
# sorted by name count is insufficient when there's multiple monodentate ligands
# with the same count (e.g. Ma3b3)
# add the index in the library to offset this
monodentate_names = sorted(
monodentate_names,
key=lambda x: 10000 * monodentate_names.count(x)
+ Component.list().index(x),
reverse=True,
)
for i, mono_lig in enumerate(
sorted(
set(monodentate_names),
key=lambda x: 10000 * monodentate_names.count(x)
+ Component.list().index(x),
reverse=True,
)
):
cc_type += alphabet[i]
this_name += "(%s)" % mono_lig
if monodentate_names.count(mono_lig) > 1:
cc_type += "%i" % monodentate_names.count(mono_lig)
this_name += "%i" % monodentate_names.count(mono_lig)
symm_bidentate_names = sorted(
symm_bidentate_names,
key=lambda x: 10000 * symm_bidentate_names.count(x)
+ Component.list().index(x),
reverse=True,
)
for i, symbi_lig in enumerate(
sorted(
set(symm_bidentate_names),
key=lambda x: 10000 * symm_bidentate_names.count(x)
+ Component.list().index(x),
reverse=True,
)
):
cc_type += "(%s)" % symmbet[i]
this_name += "(%s)" % symbi_lig
if symm_bidentate_names.count(symbi_lig) > 1:
cc_type += "%i" % symm_bidentate_names.count(symbi_lig)
this_name += "%i" % symm_bidentate_names.count(symbi_lig)
asymm_bidentate_names = sorted(
asymm_bidentate_names,
key=lambda x: 10000 * asymm_bidentate_names.count(x)
+ Component.list().index(x),
reverse=True,
)
for i, asymbi_lig in enumerate(
sorted(
set(asymm_bidentate_names),
key=lambda x: 10000 * asymm_bidentate_names.count(x)
+ Component.list().index(x),
reverse=True,
)
):
cc_type += "(%s)" % asymmbet[i]
this_name += "(%s)" % asymbi_lig
if asymm_bidentate_names.count(asymbi_lig) > 1:
cc_type += "%i" % asymm_bidentate_names.count(asymbi_lig)
this_name += "%i" % asymm_bidentate_names.count(asymbi_lig)
# load the key atoms for ligand mapping from the template file
libdir = os.path.join(
AARONTOOLS, "coordination_complex", shape, cc_type
)
if not os.path.exists(libdir):
raise RuntimeError("no templates for %s %s" % (cc_type, shape))
geoms = []
for f in os.listdir(libdir):
mappings = np.loadtxt(
os.path.join(libdir, f), dtype=str, delimiter=",", ndmin=2
)
point_group, subset = f.rstrip(".csv").split("_")[:2]
# for each possible structure, create a copy of the original template shape
# attach ligands in the order they would appear in the formula
for i, mapping in enumerate(mappings):
geom_copy = geom.copy()
geom_copy.center = [geom_copy.atoms[0]]
geom_copy.components = [
Component([atom]) for atom in geom_copy.atoms[1:]
]
start = 0
for lig in monodentate_names:
key = mapping[start]
start += 1
comp = Component(lig)
d = 2.5
# adjust distance to key atoms to what they should be for the new ligand
try:
d = bo.bonds[bo.key(center, comp.key_atoms[0])]["1.0"]
except KeyError:
pass
geom_copy.change_distance(
geom_copy.atoms[0], key, dist=d, fix=1
)
# attach ligand
geom_copy.map_ligand(comp, key, minimize=minimize)
for key in comp.key_atoms:
geom_copy.atoms[0].connected.add(key)
key.connected.add(geom_copy.atoms[0])
for lig in symm_bidentate_names:
keys = mapping[start : start + 2]
start += 2
comp = Component(lig)
for old_key, new_key in zip(keys, comp.key_atoms):
d = 2.5
try:
d = bo.bonds[bo.key(center, new_key)]["1.0"]
except KeyError:
pass
geom_copy.change_distance(
geom_copy.atoms[0],
old_key,
dist=d,
fix=1,
as_group=False,
)
geom_copy.map_ligand(comp, keys, minimize=minimize)
for key in comp.key_atoms:
geom_copy.atoms[0].connected.add(key)
key.connected.add(geom_copy.atoms[0])
for lig in asymm_bidentate_names:
keys = mapping[start : start + 2]
start += 2
comp = Component(lig)
for old_key, new_key in zip(keys, comp.key_atoms):
d = 2.5
try:
d = bo.bonds[bo.key(center, new_key)]["1.0"]
except KeyError:
pass
geom_copy.change_distance(
geom_copy.atoms[0],
old_key,
dist=d,
fix=1,
as_group=False,
)
geom_copy.map_ligand(comp, keys, minimize=minimize)
for key in comp.key_atoms:
geom_copy.atoms[0].connected.add(key)
key.connected.add(geom_copy.atoms[0])
geom_copy.name = "%s-%i_%s_%s" % (
this_name,
i + 1,
point_group,
subset,
)
geoms.append(geom_copy)
return geoms, cc_type
@classmethod
def get_diastereomers(cls, geometry, minimize=True):
"""
Generate diastereomers of Geometry
:param Geometry geometry: chiral structure
:param bool minimize: performs minimize_sub_torsion on each diastereomer
:return: list of all diastereomer_countastereomers for detected chiral centers
:rtype: list(Geometry)
"""
from AaronTools.finders import ChiralCenters, Bridgehead, NotAny, SpiroCenters
from AaronTools.ring import Ring
from AaronTools.substituent import Substituent
if not isinstance(geometry, Geometry):
geometry = Geometry(geometry)
updating_diastereomer = geometry.copy()
if not getattr(updating_diastereomer, "substituents", False):
updating_diastereomer.substituents = []
# we can invert any chiral center that isn't part of a
# fused ring unless it's a spiro center
chiral_centers = updating_diastereomer.find(ChiralCenters())
spiro_chiral = updating_diastereomer.find(SpiroCenters(), chiral_centers)
ring_centers = updating_diastereomer.find(
chiral_centers, Bridgehead(), NotAny(spiro_chiral)
)
chiral_centers = [c for c in chiral_centers if c not in ring_centers]
diastereomer_count = [2 for c in chiral_centers]
mod_array = []
for i in range(0, len(diastereomer_count)):
mod_array.append(1)
for j in range(i + 1, len(diastereomer_count)):
mod_array[i] *= diastereomer_count[j]
diastereomers = [updating_diastereomer.copy()]
previous_diastereomer = 0
for d in range(1, int(np.prod(diastereomer_count))):
for i, center in enumerate(chiral_centers):
flip = int(d / mod_array[i]) % diastereomer_count[i]
flip -= int(previous_diastereomer / mod_array[i]) % diastereomer_count[i]
if flip == 0:
continue
updating_diastereomer.change_chirality(center)
diastereomers.append(updating_diastereomer.copy())
previous_diastereomer = d
if minimize:
for diastereomer in diastereomers:
diastereomer.minimize_sub_torsion(increment=15)
return diastereomers
@staticmethod
def weighted_percent_buried_volume(
geometries, energies, temperature, *args, **kwargs
):
"""
Boltzmann-averaged percent buried volume
:param list(Geometry) geometries: structures to calculate buried volume for
:param np.ndarray energies: energy in kcal/mol; ith energy corresponds to ith substituent
:param temperature: temperature in K
:param float args: passed to Geometry.percent_buried_volume()
:param kwargs: passed to Geometry.percent_buried_volume()
:return: Boltzmann-weighted percent buried volume
"""
values = []
for geom in geometries:
values.append(geom.percent_buried_volume(*args, **kwargs))
rv = utils.boltzmann_average(
energies,
np.array(values),
temperature,
)
return rv
@classmethod
def get_solvent(cls, solvent):
"""
Converts the name of a solvent into a Geometry representation
based on solvents within AaronTools libraries
Note: list_solvents provides a str array of solvents within the libraries
:param str solvent: name of the solvent to be converted
:return: converted solvent
:rtype: Geometry
:raises LookupError: when input solvent is not present in libraries
"""
BUILTIN = os.path.join(AARONTOOLS, "Solvents")
AARON_LIBS = os.path.join(AARONLIB, "Solvents")
for lib in [AARON_LIBS, BUILTIN]:
if not os.path.exists(lib):
continue
for f in os.listdir(lib):
name, ext = os.path.splitext(os.path.basename(f))
if not any(".%s" % x == ext for x in read_types):
continue
if name == solvent:
return cls(os.path.join(lib, f), name=solvent)
raise LookupError("solvent %s not found in library" % solvent)
@classmethod
def ring_conformers(cls, geometry, targets=None):
"""
returns a list of Geometry objects with varying ring conformations
:param Geometry geometry: structure to look for conformers of
:param Atom targets: atoms in rings to search for conformers of (default is all rings)
"""
import json
from AaronTools.internal_coordinates import InternalCoordinateSet
from AaronTools.utils.utils import shortest_path
# from cProfile import Profile
#
# profile = Profile()
# profile.enable()
normal_vseprs = {
"linear 2": "linear",
"bent 2 tetrahedral": "tetrahedral",
# TODO: have a way to distiguish whether the ring is
# in the axial-equitorial or equitorial-equitorial
"bent 2 planar": "trigonal bipyramidal",
"trigonal planar": "trigonal bipyramidal",
"bent 3 tetrahedral": "tetrahedral",
"t shaped": "octahedral",
"tetrahedral": "tetrahedral",
"sawhorse": "trigonal bipyramidal",
"seesaw": "octahedral",
"square planar": "octahedral",
"trigonal pyramidal": "trigonal bipyramidal",
"trigonal bipyramidal": "trigonal bipyramidal",
"square pyramidal": "octahedral",
"octahedral": "octahedral",
}
ring_types = dict()
for fname in [
os.path.join(AARONTOOLS, "ring_conformers.json"),
os.path.join(AARONLIB, "ring_conformers.json"),
]:
if not os.path.exists(fname):
continue
with open(fname, "r") as f:
these_types = json.load(f)
ring_types.update(these_types)
#XXX: remember to fix this when oop_type options mean anything
ric = InternalCoordinateSet(geometry, torsion_type="all", oop_type="yes")
if targets is None:
targets = geometry.atoms
else:
targets = geometry.find(targets)
# identify rings
rings = []
ring_atoms = set()
graph = []
ndx = {a: i for i, a in enumerate(geometry.atoms) if a in targets}
for a in geometry.atoms:
if a in targets:
graph.append([ndx[n] for n in a.connected if n in targets])
else:
graph.append([])
utils.prune_branches(graph)
for a in range(0, len(graph)):
# skip atoms with no valid neighbors
if not graph[a]:
continue
# skip atoms we've already found
if a in ring_atoms:
continue
found_ring = False
# look for a path to each pair of neighbors
for a2 in graph[a]:
if found_ring and a2 in ring_atoms:
continue
# copy the graph, but remove the node for this atom
graph[a].remove(a2)
path = shortest_path(graph, a, a2)
if path is not None:
ring_atoms.update(path)
rings.append(path)
found_ring = True
graph[a].append(a2)
else:
# this pair of atoms is not in a ring
# we will not need to revisit
graph[a2].remove(a)
# if this atom is not in a ring, we will not
# need to visit it again - remove it's connections
# from the graph
if not found_ring:
for a2 in graph[a]:
graph[a2].remove(a)
graph[a] = []
utils.prune_branches(graph)
# need to figure out reasonable torsion values
# depending on the type of ring it is
flexible_torsions = []
ring_torsions = []
torsion_options = []
for ring in rings:
vseprs = []
ring_torsions.append([])
for i in range(0, len(ring)):
atom1 = i
atom2 = i + 1
if atom2 >= len(ring):
atom2 -= len(ring)
group1 = i - 1
if group1 < 0:
group1 += len(ring)
group2 = atom2 + 1
if group2 >= len(ring):
group2 -= len(ring)
for torsion in ric.coordinates["torsions"]:
if (
torsion.atom1 == ring[atom1] and
torsion.atom2 == ring[atom2] and
torsion.group1[0] == ring[group1] and
torsion.group2[0] == ring[group2]
):
vsepr, err = geometry.atoms[atom1].get_vsepr()
try:
vseprs.append(normal_vseprs[vsepr])
except KeyError:
vseprs.append(vsepr)
flexible_torsions.append(torsion)
ring_torsions[-1].append(torsion)
if (
torsion.atom1 == ring[atom2] and
torsion.atom2 == ring[atom1] and
torsion.group1[0] == ring[group2] and
torsion.group2[0] == ring[group1]
):
vsepr, err = geometry.atoms[atom2].get_vsepr()
try:
vseprs.append(normal_vseprs[vsepr])
except KeyError:
vseprs.append(vsepr)
flexible_torsions.append(torsion)
ring_torsions[-1].append(torsion)
# this could probably only happen if there's a linear angle
# in a ring
# torsions skip linear atoms
# e.g. allene will have H-C1-C3-H torsions
if len(vseprs) != len(ring):
cls.LOG.warning("ring atoms and vseprs don't match!")
# continue
for i in range(0, len(vseprs)):
vseprs = np.roll(vseprs, 1)
ring_torsions[-1] = np.roll(ring_torsions[-1], 1)
ring_type = ", ".join(vseprs)
try:
torsion_options.append(ring_types[str(len(ring))][ring_type])
ring_torsions[-1] = ring_torsions[-1].tolist()
break
except KeyError:
continue
else:
cls.LOG.debug(
"unknown ring type with %i atoms and %s VSEPR pattern" % (
len(ring), ring_type
)
)
# need to remove torsions that connect to these
# rings, but that are not part of the ring
# otherwise the changes we try to make to the
# internal coordinates will suck, or we will
# have to figure out how to change these torsion
# in a way that corresponds to the changes we
# are making to the ring torsions
remove_torsions = []
for t in ric.coordinates["torsions"]:
if t in flexible_torsions:
continue
if (
t.group1[0] in ring_atoms or
t.atom1 in ring_atoms or
t.atom2 in ring_atoms or
t.group2[0] in ring_atoms
):
remove_torsions.append(t)
ric.coordinates["torsions"] = [t for t in ric.coordinates["torsions"] if t not in remove_torsions]
unique_geoms = [geometry.copy()]
if not torsion_options:
cls.LOG.debug("no ring conformers could be found")
return unique_geoms
# try each 'reasonable' combination of torsions for every ring
coords = geometry.coords
current_q = ric.values(coords)
combos = itertools.product(*torsion_options)
i = 1
for combo in combos:
i += 1
probably_useless = False
#TODO: make finding the indices of a coordinate easier
dq = np.zeros(ric.n_dimensions)
visited = set()
for j, (ring, torsions) in enumerate(zip(rings, ring_torsions)):
for k, torsion in enumerate(torsions):
n = 0
for coord_type in ric.coordinates:
for coord in ric.coordinates[coord_type]:
if coord is torsion:
# if there are fused rings, there will be at least one
# pair of torsions with the same two middle atoms
# if the conformer we're trying doesn't have the same
# change in both of these torsions, it probably won't
# produce a reasonable structure
# so if we've seen a torsion with these middle atoms
# before, but the targeted change in torsional angle
# is different from before, we will skip
if (
(torsion.atom1, torsion.atom2) in visited and
not np.isclose(dq[n] - np.deg2rad(combo[j][k]) + coord.value(coords), 0, atol=1e-4)
):
probably_useless = True
dq[n : n + coord.n_values] = (
np.deg2rad(combo[j][k]) - coord.value(coords)
)
visited.add((torsion.atom1, torsion.atom2))
# print("changing", torsion, "by %.0f" % np.rad2deg(dq[n]))
n += coord.n_values
# there will be at least one combination with basically no changes
if np.linalg.norm(dq) < 1e-3:
continue
if probably_useless:
continue
# try setting the torsions
new_coords, err = ric.apply_change_2(coords, dq, convergence=1e-7)
if err > 1e-2:
cls.LOG.debug("significant deviation from expected torsions: %.2f" % err)
continue
# do RMSD to make sure it's actually unique
#XXX: RMSD sucks at this in simple test cases - consider
# adding a variant RMSD function that checks all permutations
# of equivalent atoms or something
# mirroring can sometimes trick it
ref = geometry.copy()
ref.coords = new_coords
ref_mirror = ref.copy()
ref_mirror.mirror()
for geom in unique_geoms:
rmsd = geom.RMSD(ref, sort=True, align=True)
if rmsd < 1e-2:
break
rmsd = geom.RMSD(ref_mirror, sort=True, align=True)
if rmsd < 1e-2:
break
else:
unique_geoms.append(ref)
# profile.disable()
# profile.print_stats()
return unique_geoms
@staticmethod
def list_solvents(include_ext=False):
"""
Retrieves a list of solvents stored in AaronTools
:param bool include_ext: Includes file extensions (.xyz) on
each solvent when true.
:return: string array with the names of all solvents in the libraries
"""
names = []
solvents = []
BUILTIN = os.path.join(AARONTOOLS, "Solvents")
AARON_LIBS = os.path.join(AARONLIB, "Solvents")
for lib in [AARON_LIBS, BUILTIN]:
if not os.path.exists(lib):
continue
for f in os.listdir(lib):
name, ext = os.path.splitext(os.path.basename(f))
if not any(".%s" % x == ext for x in read_types):
continue
if name in names:
continue
names.append(name)
if include_ext:
solvents.append(name + ext)
else:
solvents.append(name)
return solvents
# attribute access
def _stack_coords(self, atoms=None):
"""