-
Notifications
You must be signed in to change notification settings - Fork 8
/
geometry.py
7090 lines (6275 loc) · 272 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
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)
@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):
"""
Generates a N x 3 coordinate matrix for atoms
Note: the matrix rows are copies of, not references to, the
Atom.coords objects. Run Geometry.update_geometry(matrix) after
using this method to save changes.
"""
if atoms is None:
atoms = self.atoms
else:
atoms = self.find(atoms)
rv = np.zeros((len(atoms), 3), dtype=float)
for i, a in enumerate(atoms):
rv[i] = a.coords[:]
return rv
@property
def elements(self):
"""
returns list of elements composing the atoms in the geometry
"""
return np.array([a.element for a in self.atoms])
@property
def num_atoms(self):
"""
number of atoms
"""
return len(self.atoms)
@property
def coords(self):
"""
array of coordinates (read only)
"""
return self.coordinates()
@coords.setter
def coords(self, value):
"""
set coordinates
"""
for a, c in zip(self.atoms, value):
a.coords = np.array(c, dtype=float)
def coordinates(self, atoms=None):
"""
:param list(Atom) atoms: atoms to be searched
:return: N x 3 coordinate matrix for requested atoms
(defaults to all atoms)
:rtype: np.ndarray
"""
if atoms is None:
return self._stack_coords()
return self._stack_coords(atoms)
# utilities
def __str__(self):
xyz = self.write(outfile=False)
return xyz
# Duplicate method; __repr__ is the same code
# Remove?
def __repr__(self):
"""string representation"""
xyz = self.write(outfile=False)
return xyz
def __eq__(self, other):
"""
two geometries equal if:
same number of atoms
same numbers of elements
coordinates of atoms similar
"""
if id(self) == id(other):
return True
if len(self.atoms) != len(other.atoms):
return False
self_eles = [atom.element for atom in self.atoms]
other_eles = [atom.element for atom in other.atoms]
self_counts = {ele: self_eles.count(ele) for ele in set(self_eles)}
other_counts = {ele: other_eles.count(ele) for ele in set(other_eles)}
if self_counts != other_counts:
return False
try:
self_atypes = [atom.atomtype for atom in self.atoms]
other_atypes = [atom.atomtype for atom in other.atoms]
self_atcounts = {at: self_atypes.count(at) for at in set(self_atypes)}
other_atcounts = {at: other_atypes.count(at) for at in set(other_atypes)}
if self_atcounts != other_atcounts:
return False
except AttributeError:
pass
rmsd = self.RMSD(other, sort=False)
return rmsd < COORD_THRESHOLD
def __add__(self, other):
"""
adds other or other's atoms to self
"""
if isinstance(other, Atom):
other = [other]
elif not isinstance(other, list):
other = other.atoms
self.atoms += other
return self
def __sub__(self, other):
"""
subtracts other or other's atoms from self
"""
if isinstance(other, Atom):
other = [other]
elif not isinstance(other, list):
other = other.atoms
for o in other:
self.atoms.remove(o)
for a in self.atoms:
if a.connected & set(other):
a.connected = a.connected - set(other)
return self
def __iter__(self):
"""
resets the iterator of self
"""
self._iter_idx = -1
return self
def __next__(self):
"""
iterates to the next atom of self
"""
if self._iter_idx + 1 < len(self.atoms):
self._iter_idx += 1
return self.atoms[self._iter_idx]
raise StopIteration
def __len__(self):
"""
returns the number of atoms in self
"""
return len(self.atoms)
def __setattr__(self, attr, val):
if attr == "_hashed" and not val:
raise RuntimeError("can only set %s to True" % attr)
if not self._hashed or (self._hashed and attr != "atoms"):
super().__setattr__(attr, val)
else:
raise RuntimeError(
"cannot change atoms attribute of HashableGeometry"
)
def __hash__(self):
# hash depends on atom elements, connectivity, order, and coordinates
# reorient using principle axes
coords = self.coords
coords -= self.COM()
mat = np.matmul(coords.T, coords)
vals = np.linalg.svd(mat, compute_uv=False)
t = [int(v * 3) for v in vals]
for atom, coord in zip(self.atoms, coords):
# only use the first 3 decimal places of coordinates b/c numerical issues
t.append(int(atom.get_neighbor_id()))
if not atom._hashed:
atom.connected = frozenset(atom.connected)
atom.coords.setflags(write=False)
atom._hashed = True
# make sure atoms don't move
# if atoms move, te hash value could change making it impossible to access
# items in a dictionary with this instance as the key
if not self._hashed:
self.LOG.warning(
"Geometry `%s` has been hashed and will no longer be editable.\n"
"Use Geometry.copy to get an editable duplicate of this instance",
self.name,
)
self.atoms = tuple(self.atoms)
self._hashed = True
return hash(tuple(t))
def tag(self, tag, targets=None):
"""
Adds a tag to atoms within a Geometry object
:param str tag: tag to be added to the targets
:param list(Atom) targets: atoms to be given the tag, defaults to all atoms
"""
if targets is None:
targets = self.atoms
else:
targets = self.find(targets)
for atom in targets:
atom.tags.add(tag)
def write(self, name=None, *args, **kwargs):
"""
Write geometry to a file
:param str name: name for geometry defaults to self.name
:param args: passed to FileWriter.write
:param kwargs: passed to FileWriter.write
"""
tmp = self.name
if name is not None:
self.name = name
out = FileWriter.write_file(self, *args, **kwargs)
self.name = tmp
if out is not None:
return out
def display(self, style="stick", colorscheme="Jmol"):
"""
Display py3Dmol viewer from Geometry
:param str style: stick, sphere, or line (or other style supported by 3Dmol.js)
:param str colorscheme: 3Dmol.js color scheme (see https://3dmol.org/doc/global.html#builtinColorSchemes)
"""
def is_notebook():
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
if is_notebook():
try:
import py3Dmol
view = py3Dmol.view(
data=self.write(outfile=False),
style={style: {'colorscheme': colorscheme}},
)
#display labels on mouse hover using js
view.setHoverable({},True,'''function(atom,viewer,event,container) {
if(!atom.label) {
var ndx = atom.index + 1;
atom.label = viewer.addLabel(
atom.atom + ":" + ndx,
{position: atom, backgroundColor: 'white', fontColor:'black'}
);
}}''',
'''function(atom,viewer) {
if(atom.label) {
viewer.removeLabel(atom.label);
delete atom.label;
}
}''')
view.show()
except ImportError:
print("py3Dmol required to display 3D representations")
else:
print(self.write(outfile=False))
# Simple function to convert Geometry to basic Psi4 molecule. Expand later to
# pass multiple fragments, etc.
def convert_to_Psi4(self, charge=0, mult=1, fix_com=True, fix_orientation=True):
"""
converts Geometry into Psi4 Molecule object (requires Psi4)
:param int charge: total molecular charge
:param int mult: multiplicity
:param bool fix_com: whether to fix center of mass in Psi4 Molecule
:param bool fix_coordinates: whether to fix coordinates in Psi4 Molecule
:returns: activated Psi4 Molecule (or None if Psi4 not available)
"""
try:
import psi4
import psi4.core as p4c
except:
return None