-
Notifications
You must be signed in to change notification settings - Fork 87
/
rdkit_wrapper.py
2415 lines (1988 loc) · 91 KB
/
rdkit_wrapper.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
"""
Wrapper class providing a minimal consistent interface to the `RDKit <http://www.rdkit.org/>`.
"""
__all__ = ("RDKitToolkitWrapper",)
import copy
import importlib
import itertools
import logging
import tempfile
from typing import TYPE_CHECKING, List, Optional, Tuple
import numpy as np
try:
from openmm import unit
except ImportError:
from simtk import unit
if TYPE_CHECKING:
from openff.toolkit.topology.molecule import Molecule
from openff.toolkit.utils import base_wrapper
from openff.toolkit.utils.constants import DEFAULT_AROMATICITY_MODEL
from openff.toolkit.utils.exceptions import (
ChargeMethodUnavailableError,
ConformerGenerationError,
SMILESParseError,
ToolkitUnavailableException,
UndefinedStereochemistryError,
)
# =============================================================================================
# CONFIGURE LOGGER
# =============================================================================================
logger = logging.getLogger(__name__)
# =============================================================================================
# IMPLEMENTATION
# =============================================================================================
def normalize_file_format(file_format):
return file_format.upper()
def _require_text_file_obj(file_obj):
try:
file_obj.write("")
except TypeError:
# Switch to a ValueError and use a more informative exception
# message to match RDKit's toolkit writer.
raise ValueError(
"Need a text mode file object like StringIO or a file opened with mode 't'"
) from None
class RDKitToolkitWrapper(base_wrapper.ToolkitWrapper):
"""
RDKit toolkit wrapper
.. warning :: This API is experimental and subject to change.
"""
_toolkit_name = "The RDKit"
_toolkit_installation_instructions = (
"A conda-installable version of the free and open source RDKit cheminformatics "
"toolkit can be found at: https://anaconda.org/rdkit/rdkit"
)
def __init__(self):
super().__init__()
self._toolkit_file_read_formats = ["SDF", "MOL", "SMI"] # TODO: Add TDT support
if not self.is_available():
raise ToolkitUnavailableException(
f"The required toolkit {self._toolkit_name} is not "
f"available. {self._toolkit_installation_instructions}"
)
else:
from rdkit import __version__ as rdkit_version
self._toolkit_version = rdkit_version
from rdkit import Chem
# we have to make sure the toolkit can be loaded before formatting this dict
# Note any new file write formats should be added here only
self._toolkit_file_write_formats = {
"SDF": Chem.SDWriter,
"MOL": Chem.SDWriter,
"SMI": None, # Special support to use to_smiles() instead of RDKit's SmilesWriter
"PDB": Chem.PDBWriter,
"TDT": Chem.TDTWriter,
}
@property
def toolkit_file_write_formats(self):
"""
List of file formats that this toolkit can write.
"""
return list(self._toolkit_file_write_formats.keys())
@classmethod
def is_available(cls):
"""
Check whether the RDKit toolkit can be imported
Returns
-------
is_installed : bool
True if RDKit is installed, False otherwise.
"""
if cls._is_available is None:
try:
importlib.import_module("rdkit", "Chem")
except ImportError:
cls._is_available = False
else:
cls._is_available = True
return cls._is_available
def from_object(self, obj, allow_undefined_stereo=False, _cls=None):
"""
If given an rdchem.Mol (or rdchem.Mol-derived object), this function will load it into an
openff.toolkit.topology.molecule. Otherwise, it will return False.
Parameters
----------
obj : A rdchem.Mol-derived object
An object to be type-checked and converted into a Molecule, if possible.
allow_undefined_stereo : bool, default=False
Whether to accept molecules with undefined stereocenters. If False,
an exception will be raised if a molecule with undefined stereochemistry
is passed into this function.
_cls : class
Molecule constructor
Returns
-------
Molecule or False
An openff.toolkit.topology.molecule Molecule.
Raises
------
NotImplementedError
If the object could not be converted into a Molecule.
"""
# TODO: Add tests for the from_object functions
from rdkit import Chem
if _cls is None:
from openff.toolkit.topology.molecule import Molecule
_cls = Molecule
if isinstance(obj, Chem.rdchem.Mol):
return _cls.from_rdkit(obj, allow_undefined_stereo=allow_undefined_stereo)
raise NotImplementedError(
"Cannot create Molecule from {} object".format(type(obj))
)
def from_pdb_and_smiles(
self, file_path, smiles, allow_undefined_stereo=False, _cls=None
):
"""
Create a Molecule from a pdb file and a SMILES string using RDKit.
Requires RDKit to be installed.
The molecule is created and sanitised based on the SMILES string, we then find a mapping
between this molecule and one from the PDB based only on atomic number and connections.
The SMILES molecule is then reindexed to match the PDB, the conformer is attached, and the
molecule returned.
Note that any stereochemistry in the molecule is set by the SMILES, and not the coordinates
of the PDB.
Parameters
----------
file_path: str
PDB file path
smiles : str
a valid smiles string for the pdb, used for stereochemistry, formal charges, and bond order
allow_undefined_stereo : bool, default=False
If false, raises an exception if SMILES contains undefined stereochemistry.
_cls : class
Molecule constructor
Returns
--------
molecule : openff.toolkit.Molecule (or _cls() type)
An OFFMol instance with ordering the same as used in the PDB file.
Raises
------
InvalidConformerError : if the SMILES and PDB molecules are not isomorphic.
"""
from rdkit import Chem
# Make the molecule from smiles
offmol = self.from_smiles(
smiles, allow_undefined_stereo=allow_undefined_stereo, _cls=_cls
)
# Make another molecule from the PDB. We squelch stereo errors here, since
# RDKit's PDB loader doesn't attempt to perceive stereochemistry, bond order,
# or formal charge (and we don't need those here).
prev_log_level = logger.getEffectiveLevel()
logger.setLevel(logging.ERROR)
pdbmol = self.from_rdkit(
Chem.MolFromPDBFile(file_path, removeHs=False),
allow_undefined_stereo=True,
hydrogens_are_explicit=True,
_cls=_cls,
)
logger.setLevel(prev_log_level)
# check isomorphic and get the mapping if true the mapping will be
# Dict[pdb_index: offmol_index] sorted by pdb_index
isomorphic, mapping = _cls.are_isomorphic(
pdbmol,
offmol,
return_atom_map=True,
aromatic_matching=False,
formal_charge_matching=False,
bond_order_matching=False,
atom_stereochemistry_matching=False,
bond_stereochemistry_matching=False,
)
if mapping is not None:
new_mol = offmol.remap(mapping)
# the pdb conformer is in the correct order so just attach it here
new_mol._add_conformer(pdbmol.conformers[0])
return new_mol
else:
from openff.toolkit.topology.molecule import InvalidConformerError
raise InvalidConformerError("The PDB and SMILES structures do not match.")
def _process_sdf_supplier(self, sdf_supplier, allow_undefined_stereo, _cls):
"Helper function to process RDKit molecules from an SDF input source"
from rdkit import Chem
for rdmol in sdf_supplier:
if rdmol is None:
continue
# Sanitize the molecules (fails on nitro groups)
try:
Chem.SanitizeMol(
rdmol,
Chem.SANITIZE_ALL
^ Chem.SANITIZE_SETAROMATICITY
^ Chem.SANITIZE_ADJUSTHS,
)
Chem.AssignStereochemistryFrom3D(rdmol)
except ValueError as e:
logger.warning(rdmol.GetProp("_Name") + " " + str(e))
continue
Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_MDL)
mol = self.from_rdkit(
rdmol, allow_undefined_stereo=allow_undefined_stereo, _cls=_cls
)
yield mol
def from_file(
self, file_path, file_format, allow_undefined_stereo=False, _cls=None
):
"""
Create an openff.toolkit.topology.Molecule from a file using this toolkit.
Parameters
----------
file_path : str
The file to read the molecule from
file_format : str
Format specifier, usually file suffix (eg. 'MOL2', 'SMI')
Note that not all toolkits support all formats. Check
ToolkitWrapper.toolkit_file_read_formats for details.
allow_undefined_stereo : bool, default=False
If false, raises an exception if oemol contains undefined stereochemistry.
_cls : class
Molecule constructor
Returns
-------
molecules : iterable of Molecules
a list of Molecule objects is returned.
"""
from rdkit import Chem
file_format = normalize_file_format(file_format)
mols = list()
if (file_format == "MOL") or (file_format == "SDF"):
sdf_supplier = Chem.ForwardSDMolSupplier(
file_path, removeHs=False, sanitize=False, strictParsing=True
)
mols.extend(
self._process_sdf_supplier(
sdf_supplier,
allow_undefined_stereo=allow_undefined_stereo,
_cls=_cls,
)
)
elif file_format == "SMI":
# TODO: We have to do some special stuff when we import SMILES (currently
# just adding H's, but could get fancier in the future). It might be
# worthwhile to parse the SMILES file ourselves and pass each SMILES
# through the from_smiles function instead
for rdmol in Chem.SmilesMolSupplier(file_path, titleLine=False):
if rdmol is None:
# Skip any lines that could not be processed.
# This is consistent with the SDF reader and with
# the OpenEye toolkit wrapper.
continue
rdmol = Chem.AddHs(rdmol)
mol = self.from_rdkit(
rdmol, allow_undefined_stereo=allow_undefined_stereo, _cls=_cls
)
mols.append(mol)
elif file_format == "PDB":
raise Exception(
"RDKit can not safely read PDBs on their own. Information about bond order "
"and aromaticity is likely to be lost. To read a PDB using RDKit use "
"Molecule.from_pdb_and_smiles()"
)
# TODO: See if we can implement PDB+mol/smi combinations to get complete bond information.
# testing to see if we can make a molecule from smiles and then use the PDB
# conformer as the geometry and just reorder the molecule
# https://github.com/openforcefield/openff-toolkit/issues/121
# rdmol = Chem.MolFromPDBFile(file_path, removeHs=False)
# mol = Molecule.from_rdkit(rdmol, _cls=_cls)
# mols.append(mol)
# TODO: Add SMI, TDT(?) support
else:
raise ValueError(f"Unsupported file format: {file_format}")
return mols
def from_file_obj(
self, file_obj, file_format, allow_undefined_stereo=False, _cls=None
):
"""
Return an openff.toolkit.topology.Molecule from a file-like object using this toolkit.
A file-like object is an object with a ".read()" method.
.. warning :: This API is experimental and subject to change.
Parameters
----------
file_obj : file-like object
The file-like object to read the molecule from
file_format : str
Format specifier, usually file suffix (eg. 'MOL2', 'SMI')
Note that not all toolkits support all formats. Check
ToolkitWrapper.toolkit_file_read_formats for details.
allow_undefined_stereo : bool, default=False
If false, raises an exception if oemol contains undefined stereochemistry.
_cls : class
Molecule constructor
Returns
-------
molecules : Molecule or list of Molecules
a list of Molecule objects is returned.
"""
from rdkit import Chem
mols = []
file_format = normalize_file_format(file_format)
if (file_format == "MOL") or (file_format == "SDF"):
# TODO: Iterate over all mols in file_data
sdf_supplier = Chem.ForwardSDMolSupplier(
file_obj, removeHs=False, sanitize=False, strictParsing=True
)
mols.extend(
self._process_sdf_supplier(
sdf_supplier,
allow_undefined_stereo=allow_undefined_stereo,
_cls=_cls,
)
)
elif file_format == "SMI":
# There's no good way to create a SmilesMolSuppler from a string
# other than to use a temporary file.
with tempfile.NamedTemporaryFile(suffix=".smi") as tmpfile:
content = file_obj.read()
if isinstance(content, str):
# Backwards compatibility. Older versions of OpenFF supported
# file objects in "t"ext mode, but not file objects
# in "b"inary mode. Now we expect all input file objects
# to handle binary mode, but don't want to break older code.
tmpfile.write(content.encode("utf8"))
else:
tmpfile.write(content)
tmpfile.flush()
return self.from_file(
tmpfile.name,
"SMI",
allow_undefined_stereo=allow_undefined_stereo,
_cls=_cls,
)
elif file_format == "PDB":
raise Exception(
"RDKit can not safely read PDBs on their own. Information about bond order and aromaticity "
"is likely to be lost. To read a PDB using RDKit use Molecule.from_pdb_and_smiles()"
)
# TODO: See if we can implement PDB+mol/smi combinations to get complete bond information.
# https://github.com/openforcefield/openff-toolkit/issues/121
# file_data = file_obj.read()
# rdmol = Chem.MolFromPDBBlock(file_data)
# mol = Molecule.from_rdkit(rdmol, _cls=_cls)
# mols.append(mol)
else:
raise ValueError(f"Unsupported file format: {file_format}")
# TODO: TDT file support
return mols
def to_file_obj(self, molecule, file_obj, file_format):
"""
Writes an OpenFF Molecule to a file-like object
Parameters
----------
molecule : an OpenFF Molecule
The molecule to write
file_obj
The file-like object to write to
file_format
The format for writing the molecule data
Returns
-------
"""
file_format = normalize_file_format(file_format)
_require_text_file_obj(file_obj)
if file_format == "SMI":
# Special case for SMILES
smiles = self.to_smiles(molecule)
name = molecule.name
if name is not None:
output_line = f"{smiles} {name}\n"
else:
output_line = f"{smiles}\n"
file_obj.write(output_line)
else:
try:
writer_func = self._toolkit_file_write_formats[file_format]
except KeyError:
raise ValueError(f"Unsupported file format: {file_format})") from None
rdmol = self.to_rdkit(molecule)
writer = writer_func(file_obj)
try:
writer.write(rdmol)
finally:
writer.close()
def to_file(self, molecule, file_path, file_format):
"""
Writes an OpenFF Molecule to a file-like object
Parameters
----------
molecule : an OpenFF Molecule
The molecule to write
file_path
The file path to write to
file_format
The format for writing the molecule data
Returns
------
"""
# open a file object and pass to the object writer
with open(file_path, "w") as file_obj:
self.to_file_obj(
molecule=molecule, file_obj=file_obj, file_format=file_format
)
def enumerate_stereoisomers(
self, molecule, undefined_only=False, max_isomers=20, rationalise=True
):
"""
Enumerate the stereocenters and bonds of the current molecule.
Parameters
----------
molecule: openff.toolkit.topology.Molecule
The molecule whose state we should enumerate
undefined_only: bool optional, default=False
If we should enumerate all stereocenters and bonds or only those with undefined stereochemistry
max_isomers: int optional, default=20
The maximum amount of molecules that should be returned
rationalise: bool optional, default=True
If we should try to build and rationalise the molecule to ensure it can exist
Returns
--------
molecules: List[openff.toolkit.topology.Molecule]
A list of openff.toolkit.topology.Molecule instances
"""
from rdkit import Chem
from rdkit.Chem.EnumerateStereoisomers import ( # type: ignore[import]
EnumerateStereoisomers,
StereoEnumerationOptions,
)
# create the molecule
rdmol = self.to_rdkit(molecule=molecule)
# in case any bonds/centers are missing stereo chem flag it here
Chem.AssignStereochemistry(
rdmol, cleanIt=True, force=True, flagPossibleStereoCenters=True
)
Chem.FindPotentialStereoBonds(rdmol)
# set up the options
stereo_opts = StereoEnumerationOptions(
tryEmbedding=rationalise,
onlyUnassigned=undefined_only,
maxIsomers=max_isomers,
)
isomers = tuple(EnumerateStereoisomers(rdmol, options=stereo_opts))
molecules = []
for isomer in isomers:
# isomer has CIS/TRANS tags so convert back to E/Z
Chem.SetDoubleBondNeighborDirections(isomer)
Chem.AssignStereochemistry(isomer, force=True, cleanIt=True)
mol = self.from_rdkit(isomer, _cls=molecule.__class__)
if mol != molecule:
molecules.append(mol)
return molecules
def enumerate_tautomers(self, molecule, max_states=20):
"""
Enumerate the possible tautomers of the current molecule.
Parameters
----------
molecule: openff.toolkit.topology.Molecule
The molecule whose state we should enumerate
max_states: int optional, default=20
The maximum amount of molecules that should be returned
Returns
-------
molecules: List[openff.toolkit.topology.Molecule]
A list of openff.toolkit.topology.Molecule instances not including the input molecule.
"""
from rdkit import Chem
from rdkit.Chem.MolStandardize import rdMolStandardize # type: ignore[import]
enumerator = rdMolStandardize.TautomerEnumerator()
enumerator.SetMaxTautomers(max_states)
rdmol = Chem.RemoveHs(molecule.to_rdkit())
tautomers = enumerator.Enumerate(rdmol)
# make a list of OpenFF molecules excluding the input molecule
molecules = []
for taut in tautomers:
taut_hs = Chem.AddHs(taut)
mol = self.from_smiles(
Chem.MolToSmiles(taut_hs), allow_undefined_stereo=True
)
if mol != molecule:
molecules.append(mol)
return molecules[:max_states]
def canonical_order_atoms(self, molecule):
"""
Canonical order the atoms in the molecule using the RDKit.
Parameters
----------
molecule: openff.toolkit.topology.Molecule
The input molecule
Returns
-------
molecule : openff.toolkit.topology.Molecule
The input molecule, with canonically-indexed atoms and bonds.
"""
from rdkit import Chem
rdmol = self.to_rdkit(molecule)
# get the canonical ordering with hydrogens first
# this is the default behaviour of RDKit
atom_order = list(Chem.CanonicalRankAtoms(rdmol, breakTies=True))
heavy_atoms = rdmol.GetNumHeavyAtoms()
hydrogens = rdmol.GetNumAtoms() - heavy_atoms
# now go through and change the rankings to get the heavy atoms first if hydrogens are present
if hydrogens != 0:
for i in range(len(atom_order)):
if rdmol.GetAtomWithIdx(i).GetAtomicNum() != 1:
atom_order[i] -= hydrogens
else:
atom_order[i] += heavy_atoms
# make an atom mapping from the atom_order and remap the molecule
atom_mapping = dict((i, rank) for i, rank in enumerate(atom_order))
return molecule.remap(atom_mapping, current_to_new=True)
def to_smiles(self, molecule, isomeric=True, explicit_hydrogens=True, mapped=False):
"""
Uses the RDKit toolkit to convert a Molecule into a SMILES string.
A partially mapped smiles can also be generated for atoms of interest by supplying
an `atom_map` to the properties dictionary.
Parameters
----------
molecule : An openff.toolkit.topology.Molecule
The molecule to convert into a SMILES.
isomeric: bool optional, default= True
return an isomeric smiles
explicit_hydrogens: bool optional, default=True
return a smiles string containing all hydrogens explicitly
mapped: bool optional, default=False
return a explicit hydrogen mapped smiles, the atoms to be mapped can be controlled by
supplying an atom map into the properties dictionary. If no mapping is passed all
atoms will be mapped in order, else an atom map dictionary from the current atom
index to the map id should be supplied with no duplicates. The map ids (values) should
start from 0 or 1.
Returns
-------
smiles : str
The SMILES of the input molecule.
"""
from rdkit import Chem
rdmol = self.to_rdkit(molecule)
if not explicit_hydrogens:
# remove the hydrogens from the molecule
rdmol = Chem.RemoveHs(rdmol)
if mapped:
assert explicit_hydrogens is True, (
"Mapped smiles require all hydrogens and "
"stereochemistry to be defined to retain order"
)
# if we only want to map specific atoms check for an atom map
atom_map = molecule._properties.get("atom_map", None)
if atom_map is not None:
# make sure there are no repeated indices
map_ids = set(atom_map.values())
if len(map_ids) < len(atom_map):
atom_map = None
elif 0 in atom_map.values():
# we need to increment the map index
for atom, map in atom_map.items():
atom_map[atom] = map + 1
if atom_map is None:
# now we need to add the indexing to the rdmol to get it in the smiles
for atom in rdmol.GetAtoms():
# the mapping must start from 1, as RDKit uses 0 to represent no mapping.
atom.SetAtomMapNum(atom.GetIdx() + 1)
else:
for atom in rdmol.GetAtoms():
try:
# try to set the atom map
map_idx = atom_map[atom.GetIdx()]
atom.SetAtomMapNum(map_idx)
except KeyError:
continue
return Chem.MolToSmiles(
rdmol, isomericSmiles=isomeric, allHsExplicit=explicit_hydrogens
)
def from_smiles(
self,
smiles,
hydrogens_are_explicit=False,
allow_undefined_stereo=False,
_cls=None,
):
"""
Create a Molecule from a SMILES string using the RDKit toolkit.
.. warning :: This API is experimental and subject to change.
Parameters
----------
smiles : str
The SMILES string to turn into a molecule
hydrogens_are_explicit : bool, default=False
If False, RDKit will perform hydrogen addition using Chem.AddHs
allow_undefined_stereo : bool, default=False
Whether to accept SMILES with undefined stereochemistry. If False,
an exception will be raised if a SMILES with undefined stereochemistry
is passed into this function.
_cls : class
Molecule constructor
Returns
-------
molecule : openff.toolkit.topology.Molecule
An OpenFF style molecule.
"""
from rdkit import Chem
rdmol = Chem.MolFromSmiles(smiles, sanitize=False)
if rdmol is None:
raise SMILESParseError("Unable to parse the SMILES string")
# strip the atom map from the molecule if it has one
# so we don't affect the sterochemistry tags
for atom in rdmol.GetAtoms():
if atom.GetAtomMapNum() != 0:
# set the map back to zero but hide the index in the atom prop data
atom.SetProp("_map_idx", str(atom.GetAtomMapNum()))
# set it back to zero
atom.SetAtomMapNum(0)
# Chem.SanitizeMol calls updatePropertyCache so we don't need to call it ourselves
# https://www.rdkit.org/docs/cppapi/namespaceRDKit_1_1MolOps.html#a8d831787aaf2d65d9920c37b25b476f5
Chem.SanitizeMol(
rdmol,
Chem.SANITIZE_ALL ^ Chem.SANITIZE_ADJUSTHS ^ Chem.SANITIZE_SETAROMATICITY,
)
Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_MDL)
# Chem.MolFromSmiles adds bond directions (i.e. ENDDOWNRIGHT/ENDUPRIGHT), but
# doesn't set bond.GetStereo(). We need to call AssignStereochemistry for that.
Chem.AssignStereochemistry(rdmol)
# Throw an exception/warning if there is unspecified stereochemistry.
if not allow_undefined_stereo:
self._detect_undefined_stereo(
rdmol, err_msg_prefix="Unable to make OFFMol from SMILES: "
)
# Add explicit hydrogens if they aren't there already
if not hydrogens_are_explicit:
rdmol = Chem.AddHs(rdmol)
elif hydrogens_are_explicit:
for atom_idx in range(rdmol.GetNumAtoms()):
atom = rdmol.GetAtomWithIdx(atom_idx)
if atom.GetNumImplicitHs() != 0:
raise ValueError(
f"'hydrogens_are_explicit' was specified as True, but RDKit toolkit interpreted "
f"SMILES '{smiles}' as having implicit hydrogen. If this SMILES is intended to "
f"express all explicit hydrogens in the molecule, then you should construct the "
f"desired molecule as an RDMol with no implicit hydrogens, and then use "
f"Molecule.from_rdkit() to create the desired OFFMol."
)
molecule = self.from_rdkit(
rdmol,
_cls=_cls,
allow_undefined_stereo=allow_undefined_stereo,
hydrogens_are_explicit=hydrogens_are_explicit,
)
return molecule
def from_inchi(self, inchi, allow_undefined_stereo=False, _cls=None):
"""
Construct a Molecule from a InChI representation
Parameters
----------
inchi : str
The InChI representation of the molecule.
allow_undefined_stereo : bool, default=False
Whether to accept InChI with undefined stereochemistry. If False,
an exception will be raised if a InChI with undefined stereochemistry
is passed into this function.
_cls : class
Molecule constructor
Returns
-------
molecule : openff.toolkit.topology.Molecule
"""
from rdkit import Chem
# this seems to always remove the hydrogens
rdmol = Chem.MolFromInchi(inchi, sanitize=False, removeHs=False)
# try and catch an InChI parsing error
if rdmol is None:
raise RuntimeError(
"There was an issue parsing the InChI string, please check and try again."
)
# process the molecule
# TODO do we need this with inchi?
rdmol.UpdatePropertyCache(strict=False)
Chem.SanitizeMol(
rdmol,
Chem.SANITIZE_ALL ^ Chem.SANITIZE_ADJUSTHS ^ Chem.SANITIZE_SETAROMATICITY,
)
Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_MDL)
# add hydrogens back here
rdmol = Chem.AddHs(rdmol)
molecule = self.from_rdkit(
rdmol, allow_undefined_stereo=allow_undefined_stereo, _cls=_cls
)
return molecule
def generate_conformers(
self, molecule, n_conformers=1, rms_cutoff=None, clear_existing=True, _cls=None
):
r"""
Generate molecule conformers using RDKit.
.. warning :: This API is experimental and subject to change.
.. todo ::
* which parameters should we expose? (or can we implement a general system with \*\*kwargs?)
* will the coordinates be returned in the OpenFF Molecule's own indexing system?
Or is there a chance that they'll get reindexed when we convert the input into an RDMol?
Parameters
----------
molecule : a :class:`Molecule`
The molecule to generate conformers for.
n_conformers : int, default=1
Maximum number of conformers to generate.
rms_cutoff : openmm.Quantity-wrapped float, in units of distance, optional, default=None
The minimum RMS value at which two conformers are considered redundant and one is deleted.
If None, the cutoff is set to 1 Angstrom
clear_existing : bool, default=True
Whether to overwrite existing conformers for the molecule.
_cls : class
Molecule constructor
"""
from rdkit.Chem import AllChem
if rms_cutoff is None:
rms_cutoff = 1.0 * unit.angstrom
rdmol = self.to_rdkit(molecule)
# TODO: This generates way more conformations than omega, given the same
# nConfs and RMS threshold. Is there some way to set an energy cutoff as well?
conformer_generation_status = AllChem.EmbedMultipleConfs(
rdmol,
numConfs=n_conformers,
pruneRmsThresh=rms_cutoff.value_in_unit(unit.angstrom),
randomSeed=1,
# params=AllChem.ETKDG()
)
if not conformer_generation_status:
raise ConformerGenerationError("RDKit conformer generation failed.")
molecule2 = self.from_rdkit(
rdmol, allow_undefined_stereo=True, _cls=molecule.__class__
)
if clear_existing:
molecule._conformers = list()
for conformer in molecule2._conformers:
molecule._add_conformer(conformer)
def assign_partial_charges(
self,
molecule,
partial_charge_method=None,
use_conformers=None,
strict_n_conformers=False,
normalize_partial_charges=True,
_cls=None,
):
"""
Compute partial charges with RDKit, and assign
the new values to the partial_charges attribute.
.. warning :: This API is experimental and subject to change.
Parameters
----------
molecule : openff.toolkit.topology.Molecule
Molecule for which partial charges are to be computed
partial_charge_method : str, optional, default=None
The charge model to use. One of ['mmff94']. If None, 'mmff94' will be used.
* 'mmff94': Applies partial charges using the Merck Molecular Force Field
(MMFF). This method does not make use of conformers, and hence
``use_conformers`` and ``strict_n_conformers`` will not impact
the partial charges produced.
use_conformers : iterable of openmm.unit.Quantity-wrapped numpy arrays, each with
shape (n_atoms, 3) and dimension of distance. Optional, default = None
Coordinates to use for partial charge calculation. If None, an appropriate number of
conformers will be generated.
strict_n_conformers : bool, default=False
Whether to raise an exception if an invalid number of conformers is provided for
the given charge method.
If this is False and an invalid number of conformers is found, a warning will be raised.
normalize_partial_charges : bool, default=True
Whether to offset partial charges so that they sum to the total formal charge of the molecule.
This is used to prevent accumulation of rounding errors when the partial charge generation method has
low precision.
_cls : class
Molecule constructor
Raises
------
ChargeMethodUnavailableError if the requested charge method can not be handled by this toolkit
ChargeCalculationError if the charge method is supported by this toolkit, but fails
"""
import numpy as np
from rdkit.Chem import AllChem
SUPPORTED_CHARGE_METHODS = {"mmff94"}
if partial_charge_method is None:
partial_charge_method = "mmff94"
partial_charge_method = partial_charge_method.lower()
if partial_charge_method not in SUPPORTED_CHARGE_METHODS:
raise ChargeMethodUnavailableError(
f"partial_charge_method '{partial_charge_method}' is not available from RDKitToolkitWrapper. "
f"Available charge methods are {list(SUPPORTED_CHARGE_METHODS)} "
)
rdkit_molecule = molecule.to_rdkit()
charges = None
if partial_charge_method == "mmff94":
mmff_properties = AllChem.MMFFGetMoleculeProperties(
rdkit_molecule, "MMFF94"
)
charges = np.array(
[
mmff_properties.GetMMFFPartialCharge(i)
for i in range(molecule.n_atoms)
]
)
molecule.partial_charges = charges * unit.elementary_charge
if normalize_partial_charges:
molecule._normalize_partial_charges()
@classmethod
def _elf_is_problematic_conformer(
cls, molecule: "Molecule", conformer: unit.Quantity
) -> Tuple[bool, Optional[str]]:
"""A function which checks if a particular conformer is known to be problematic
when computing ELF partial charges.