-
Notifications
You must be signed in to change notification settings - Fork 93
/
openeye_wrapper.py
2881 lines (2416 loc) · 105 KB
/
openeye_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 `OpenEye Toolkit <https://docs.eyesopen.com/toolkits/python/quickstart-python/index.html>`_
"""
__all__ = ("OpenEyeToolkitWrapper",)
import importlib
import logging
import pathlib
import re
import tempfile
from collections import defaultdict
from functools import wraps
from typing import TYPE_CHECKING, Any, Optional, Union
import numpy as np
from cachetools import LRUCache, cached
from typing_extensions import TypeAlias
from openff.toolkit import Quantity, unit
if TYPE_CHECKING:
from openff.toolkit.topology.molecule import FrozenMolecule, Molecule, Bond, Atom
from openff.units.elements import SYMBOLS
from openff.toolkit.utils.base_wrapper import (
ToolkitWrapper,
_ChargeSettings,
_mol_to_ctab_and_aro_key,
)
from openff.toolkit.utils.constants import (
ALLOWED_AROMATICITY_MODELS,
DEFAULT_AROMATICITY_MODEL,
)
from openff.toolkit.utils.exceptions import (
ChargeCalculationError,
ChargeMethodUnavailableError,
ConformerGenerationError,
GAFFAtomTypeWarning,
InChIParseError,
InconsistentStereochemistryError,
InvalidAromaticityModelError,
InvalidIUPACNameError,
LicenseError,
NotAttachedToMoleculeError,
OpenEyeError,
OpenEyeImportError,
RadicalsNotSupportedError,
SMILESParseError,
ToolkitUnavailableException,
UnassignedChemistryInPDBError,
UndefinedStereochemistryError,
)
from openff.toolkit.utils.utils import inherit_docstrings
logger = logging.getLogger(__name__)
TTA: TypeAlias = tuple[tuple[Any, ...], ...]
def get_oeformat(file_format: str) -> str:
from openeye import oechem
file_format = file_format.upper()
# XXX This is what RDKit does. Should be supported here too?
if file_format == "MOL":
file_format = "SDF"
oeformat = getattr(oechem, "OEFormat_" + file_format, None)
if oeformat is None:
raise ValueError(f"Unsupported file format: {file_format}")
return oeformat
@inherit_docstrings
class OpenEyeToolkitWrapper(ToolkitWrapper):
"""
OpenEye toolkit wrapper
.. warning :: This API is experimental and subject to change.
"""
_toolkit_name = "OpenEye Toolkit"
_toolkit_installation_instructions = (
"The OpenEye Toolkits can be installed via "
"`mamba install openeye-toolkits -c openeye`"
)
_toolkit_license_instructions = (
"The OpenEye Toolkits require a (free for academics) license, see "
"https://docs.eyesopen.com/toolkits/python/quickstart-python/license.html"
)
# This could belong to ToolkitWrapper, although it seems strange
# to carry that data for open-source toolkits
_is_licensed: Optional[bool] = None
# Only for OpenEye is there potentially a difference between
# being available and installed
_is_installed: Optional[bool] = None
_license_functions: dict[str, str] = {
"oechem": "OEChemIsLicensed",
"oequacpac": "OEQuacPacIsLicensed",
"oeiupac": "OEIUPACIsLicensed",
"oeomega": "OEOmegaIsLicensed",
}
_supported_charge_methods = {
"am1bcc": {
"oe_charge_method": "OEAM1BCCCharges",
"min_confs": 1,
"max_confs": 1,
"rec_confs": 1,
},
"am1-mulliken": {
"oe_charge_method": "OEAM1Charges",
"min_confs": 1,
"max_confs": 1,
"rec_confs": 1,
},
"gasteiger": {
"oe_charge_method": "OEGasteigerCharges",
"min_confs": 0,
"max_confs": 0,
"rec_confs": 0,
},
"mmff94": {
"oe_charge_method": "OEMMFF94Charges",
"min_confs": 0,
"max_confs": 0,
"rec_confs": 0,
},
"am1bccnosymspt": {
"oe_charge_method": "OEAM1BCCCharges",
"min_confs": 1,
"max_confs": 1,
"rec_confs": 1,
},
"am1elf10": {
"oe_charge_method": "OEELFCharges",
"min_confs": 1,
"max_confs": None, # type: ignore[typeddict-item]
"rec_confs": 500,
},
"am1bccelf10": {
"oe_charge_method": "OEAM1BCCELF10Charges",
"min_confs": 1,
"max_confs": None, # type: ignore[typeddict-item]
"rec_confs": 500,
},
}
SUPPORTED_CHARGE_METHODS = _supported_charge_methods
_toolkit_file_read_formats = [
"CAN",
"CDX",
"CSV",
"FASTA",
"INCHI",
"INCHIKEY",
"ISM",
"MDL",
"MF",
"MMOD",
"MOL2",
"MOL2H",
"MOPAC",
"OEB",
"PDB",
"RDF",
"SDF",
"SKC",
"SLN",
"SMI",
"USM",
"XYC",
]
_toolkit_file_write_formats = [
"CAN",
"CDX",
"CSV",
"FASTA",
"INCHI",
"INCHIKEY",
"ISM",
"MDL",
"MF",
"MMOD",
"MOL2",
"MOL2H",
"MOPAC",
"OEB",
"PDB",
"RDF",
"SDF",
"SKC",
"SLN",
"SMI",
"USM",
"XYC",
]
def __init__(self):
# check if the toolkit can be loaded
if not self.is_available():
if self._is_installed is False:
raise ToolkitUnavailableException(
"OpenEye Toolkits are not installed."
+ self._toolkit_installation_instructions
)
if self._is_licensed is False:
raise LicenseError(
"The OpenEye Toolkits are found to be installed but not licensed and "
+ "therefore will not be used.\n"
+ self._toolkit_license_instructions
)
from openeye import __version__ as openeye_version
self._toolkit_version = openeye_version
@classmethod
def _check_licenses(cls) -> bool:
"""Check license of all known OpenEye tools. Returns True if any are found
to be licensed, False if all are not."""
for tool, license_func in cls._license_functions.items():
try:
module = importlib.import_module("openeye." + tool)
except ImportError:
continue
else:
if getattr(module, license_func)():
return True
return False
@classmethod
def is_available(cls) -> bool:
"""
Check if the given OpenEye toolkit components are available.
If the OpenEye toolkit is not installed or no license is found
for at least one the required toolkits , ``False`` is returned.
Returns
-------
all_installed
``True`` if all required OpenEye tools are installed and licensed,
``False`` otherwise
"""
if cls._is_available is None:
if cls._is_licensed is None:
cls._is_licensed = cls._check_licenses()
if cls._is_installed is None:
for tool in cls._license_functions.keys():
cls._is_installed = True
try:
importlib.import_module("openeye." + tool)
except ImportError:
cls._is_installed = False
if cls._is_installed:
if cls._is_licensed:
cls._is_available = True
else:
cls._is_available = False
cls._is_available = cls._is_installed and cls._is_licensed
return cls._is_available # type: ignore[return-value]
def from_object(
self,
obj,
allow_undefined_stereo: bool = False,
_cls=None,
) -> "FrozenMolecule":
"""
Convert an OEMol (or OEMol-derived object) into an openff.toolkit.topology.molecule
Parameters
----------
obj
An object to by type-checked.
allow_undefined_stereo
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
Molecule constructor
Returns
-------
Molecule
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 openeye import oechem
if _cls is None:
from openff.toolkit.topology.molecule import Molecule
_cls = Molecule
if isinstance(obj, oechem.OEMolBase):
return self.from_openeye(
oemol=obj,
allow_undefined_stereo=allow_undefined_stereo,
_cls=_cls,
)
raise NotImplementedError(
"Cannot create Molecule from {} object".format(type(obj))
)
def _polymer_openmm_topology_to_offmol(
self, mol_class, omm_top, substructure_dictionary
):
oemol = self._polymer_openmm_topology_to_oemol(omm_top, substructure_dictionary)
offmol = mol_class.from_openeye(oemol, allow_undefined_stereo=True)
return offmol
def _polymer_openmm_topology_to_oemol(
self,
omm_top,
substructure_library,
):
"""
Parameters
----------
omm_top
OpenMM Topology loaded from PDB
substructure_library
A dictionary of substructures. substructure_library[aa_name] = list[tagged SMARTS, list[atom_names]]
Returns
-------
oemol
a new molecule with charges and bond order added
"""
from openeye import oechem
oemol = self._get_connectivity_from_openmm_top(omm_top)
already_assigned_nodes = set()
already_assigned_edges = set()
# Keeping track of which atoms are matched where will help us with error
# messages
matches = defaultdict(list)
for res_name in substructure_library:
# TODO: This is a hack for the moment since we don't have a more sophisticated way to resolve clashes
# so it just does the biggest substructures first
sorted_substructure_smarts = sorted(
substructure_library[res_name], key=len, reverse=True
)
for substructure_smarts in sorted_substructure_smarts:
ss = self._fuzzy_query(substructure_smarts)
for match in ss.Match(oemol, True):
match_mol_atom_indices = [
at.GetIdx() for at in match.GetTargetAtoms()
]
for i in match_mol_atom_indices:
matches[i].append(res_name)
if any(
m in already_assigned_nodes for m in match_mol_atom_indices
) and (res_name not in ["PEPTIDE_BOND", "DISULFIDE"]):
continue
for substructure_atom, mol_atom in zip(
match.GetPatternAtoms(), match.GetTargetAtoms()
):
mol_atom.SetFormalCharge(substructure_atom.GetFormalCharge())
# Set arbitrary initial stereochemistry to avoid
# spamming "undefined stereo" warnings. In the from_polymer_pdb
# code path, the "real stereo" will be assigned later by a
# call to _assign_aromaticity_and_stereo_from_3d.
neighs = [n for n in mol_atom.GetAtoms()]
mol_atom.SetStereo(
neighs, oechem.OEAtomStereo_Tetra, oechem.OEAtomStereo_Left
)
already_assigned_nodes.add(mol_atom.GetIdx())
for substructure_bond, mol_bond in zip(
match.GetPatternBonds(), match.GetTargetBonds()
):
mol_bond.SetOrder(substructure_bond.GetOrder())
already_assigned_edges.add(
tuple(sorted([mol_bond.GetBgnIdx(), mol_bond.GetEndIdx()]))
)
oemol_n_atoms = len([*oemol.GetAtoms()])
unassigned_atoms = sorted(set(range(oemol_n_atoms)) - already_assigned_nodes)
all_bonds = set(
[
tuple(sorted([bond.GetBgnIdx(), bond.GetEndIdx()]))
for bond in oemol.GetBonds()
]
)
unassigned_bonds = sorted(all_bonds - already_assigned_edges)
if unassigned_atoms or unassigned_bonds:
# Some advanced error reporting needs to interpret the substructure smarts to do things like
# compare atom counts. Since OFFTK doesn't have a native class to hold fragments, we convert
# the smarts into a sorted list of symbols to help with generating the error message.
resname_to_symbols_and_atomnames: dict[str, list[tuple]] = {}
for resname, smarts_to_atom_names in substructure_library.items():
resname_to_symbols_and_atomnames[resname] = list()
for smarts, atom_names in smarts_to_atom_names.items():
qmol = oechem.OEQMol()
oechem.OEParseSmiles(qmol, smarts)
symbols = sorted(
[SYMBOLS[atom.GetAtomicNum()] for atom in qmol.GetAtoms()]
)
resname_to_symbols_and_atomnames[resname].append(
(symbols, atom_names)
)
raise UnassignedChemistryInPDBError(
substructure_library=resname_to_symbols_and_atomnames,
omm_top=omm_top,
unassigned_atoms=unassigned_atoms,
unassigned_bonds=unassigned_bonds,
matches=matches,
)
return oemol
def _get_connectivity_from_openmm_top(self, omm_top):
from openeye import oechem
oemol = oechem.OEMol()
# Add atoms
oemol_atoms = list() # list of corresponding oemol atoms
for atom in omm_top.atoms():
oeatom = oemol.NewAtom(atom.element.atomic_number)
oemol_atoms.append(oeatom)
# Add bonds
oemol_bonds = list() # list of corresponding oemol bonds
for bond in omm_top.bonds():
atom1_index = bond[0].index
atom2_index = bond[1].index
oebond = oemol.NewBond(oemol_atoms[atom1_index], oemol_atoms[atom2_index])
oemol_bonds.append(oebond)
return oemol
@staticmethod
def _fuzzy_query(query):
"""return a copy of Query which is less specific:
- ignore aromaticity and hybridization of atoms (i.e. [#6] not C)
- ignore bond orders
- ignore formal charges
"""
from openeye import oechem
from openff.toolkit.utils.exceptions import SMIRKSParsingError
# Jeff wasn't able to get this working with OEQMol and OEParseSmarts,
# the QMol/SS matching didn't behave correctly when set to AtomicNumber
qmol = oechem.OEMol()
status = oechem.OEParseSmiles(
qmol,
query,
)
if not status:
raise SMIRKSParsingError(
f"OpenEye Toolkit was unable to parse SMIRKS {query}"
)
ss = oechem.OESubSearch(qmol, oechem.OEExprOpts_AtomicNumber, 0)
return ss
def from_file(
self,
file_path: Union[str, pathlib.Path],
file_format: str,
allow_undefined_stereo: bool = False,
_cls=None,
) -> list["FrozenMolecule"]:
"""
Return an openff.toolkit.topology.Molecule from a file using this toolkit.
Parameters
----------
file_path
The file to read the molecule from
file_format
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
If false, raises an exception if oemol contains undefined stereochemistry.
_cls
Molecule constructor
Returns
-------
molecules
The list of ``Molecule`` objects in the file.
Raises
------
GAFFAtomTypeWarning
If the loaded mol2 file possibly uses GAFF atom types, which
are not supported.
Examples
--------
Load a mol2 file into an OpenFF ``Molecule`` object.
>>> from openff.toolkit.utils import get_data_file_path
>>> mol2_file_path = get_data_file_path('molecules/cyclohexane.mol2')
>>> toolkit = OpenEyeToolkitWrapper()
>>> molecule = toolkit.from_file(mol2_file_path, file_format='mol2')
"""
from openeye import oechem
if isinstance(file_path, pathlib.Path):
_file_path = file_path.as_posix()
else:
_file_path = file_path
oeformat = get_oeformat(file_format)
ifs = oechem.oemolistream(_file_path)
if not ifs.IsValid():
# Get Python to report an error message, if possible.
# This can distinguish between FileNotFound, IsADirectoryError, etc.
open(_file_path).close()
# If that worked, then who knows. Fail anyway.
raise OSError("Unable to open file")
ifs.SetFormat(oeformat)
return self._read_oemolistream_molecules(
ifs, allow_undefined_stereo, file_path=_file_path, _cls=_cls
)
def from_file_obj(
self,
file_obj,
file_format: str,
allow_undefined_stereo: bool = False,
_cls=None,
) -> list["Molecule"]:
"""
Return an openff.toolkit.topology.Molecule from a file-like object (an object with a ".read()" method using
this toolkit.
Parameters
----------
file_obj
The file-like object to read the molecule from
file_format
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
If false, raises an exception if oemol contains undefined stereochemistry.
_cls
Molecule constructor
Returns
-------
molecules
The list of Molecule objects in the file object.
Raises
------
GAFFAtomTypeWarning
If the loaded mol2 file possibly uses GAFF atom types, which
are not supported.
"""
from openeye import oechem
# Configure input molecule stream.
ifs = oechem.oemolistream()
ifs.openstring(file_obj.read())
oeformat = get_oeformat(file_format)
ifs.SetFormat(oeformat)
return self._read_oemolistream_molecules(ifs, allow_undefined_stereo, _cls=_cls)
def to_file_obj(self, molecule: "Molecule", file_obj, file_format: str):
"""
Writes an OpenFF Molecule to a file-like object
Parameters
----------
molecule
The molecule to write
file_obj
The file-like object to write to
file_format
The format for writing the molecule data
"""
# This function requires a text-mode file_obj.
try:
file_obj.write("")
except TypeError:
# Switch to a ValueError and use a more informative exception
# message to match RDKit.
raise ValueError(
"Need a text mode file object like StringIO or a file opened with mode 't'"
) from None
with tempfile.TemporaryDirectory() as tmpdir:
path = pathlib.Path(tmpdir, f"input.{file_format.lower()}")
self.to_file(molecule, str(path), file_format)
file_data = path.read_text()
file_obj.write(file_data)
def to_file(
self,
molecule: "Molecule",
file_path: Union[str, pathlib.Path],
file_format: str,
):
"""
Writes an OpenFF Molecule to a file-like object
Parameters
----------
molecule
The molecule to write
file_path
The file path to write to.
file_format
The format for writing the molecule data
"""
from openeye import oechem
if isinstance(file_path, pathlib.Path):
file_path = file_path.as_posix()
oemol = self.to_openeye(molecule)
ofs = oechem.oemolostream(file_path)
if not ofs.IsValid():
# Get Python to report an error message, if possible.
# This can distinguish between PermissionError, IsADirectoryError, etc.
open(file_path, "wb").close()
# If that worked, then who knows. Fail anyway.
raise OSError("Unable to open file")
openeye_format = get_oeformat(file_format)
ofs.SetFormat(openeye_format)
if openeye_format == oechem.OEFormat_SMI:
ofs.SetFlavor(
openeye_format,
self._get_smiles_flavor(isomeric=True, explicit_hydrogens=True),
)
# OFFTK strictly treats SDF as a single-conformer format.
# We need to override OETK's behavior here if the user is saving a multiconformer molecule.
# Remove all but the first conformer when writing to SDF as we only support single conformer format
if (file_format.lower() == "sdf") and oemol.NumConfs() > 1:
conf1 = [conf for conf in oemol.GetConfs()][0]
flat_coords = list()
for coord in conf1.GetCoords().values():
flat_coords.extend(coord)
oemol.DeleteConfs()
oecoords = oechem.OEFloatArray(flat_coords)
oemol.NewConf(oecoords)
# We're standardizing on putting partial charges into SDFs under the `atom.dprop.PartialCharge` property
if (file_format.lower() == "sdf") and (molecule.partial_charges is not None):
partial_charges_list = [
oeatom.GetPartialCharge() for oeatom in oemol.GetAtoms()
]
partial_charges_str = " ".join([f"{val:f}" for val in partial_charges_list])
# TODO: "dprop" means "double precision" -- Is there any way to make Python more accurately
# describe/infer the proper data type?
oechem.OESetSDData(oemol, "atom.dprop.PartialCharge", partial_charges_str)
# If the file format is "pdb" using OEWriteMolecule() rearranges the atoms (hydrogens are pushed to the bottom)
# Issue #475 (https://github.com/openforcefield/openff-toolkit/issues/475)
# dfhahn's workaround: Using OEWritePDBFile does not alter the atom arrangement
if file_format.lower() == "pdb":
if oemol.NumConfs() > 1:
for conf in oemol.GetConfs():
oechem.OEWritePDBFile(ofs, conf, oechem.OEOFlavor_PDB_BONDS)
else:
oechem.OEWritePDBFile(ofs, oemol, oechem.OEOFlavor_PDB_BONDS)
else:
oechem.OEWriteMolecule(ofs, oemol)
ofs.close()
@staticmethod
def _turn_oemolbase_sd_charges_into_partial_charges(oemol) -> bool:
"""
Process an OEMolBase object and check to see whether it has an SD data pair
where the tag is "atom.dprop.PartialCharge", indicating that it has a list of
atomic partial charges. If so, apply those charges to the OEAtoms in the OEMolBase,
and delete the SD data pair.
Parameters
----------
oemol
The molecule to process
Returns
-------
charges_are_present
Whether charges are present in the SD file. This is necessary because OEAtoms
have a default partial charge of 0.0, which makes truly zero-charge molecules
(eg "N2", "Ar"...) indistinguishable from molecules for which partial charges
have not been assigned. The OFF Toolkit allows this distinction with
mol.partial_charges=None. In order to complete roundtrips within the OFFMol
spec, we must interpret the presence or absence of this tag as a proxy for
mol.partial_charges=None.
"""
from openeye import oechem
for dp in oechem.OEGetSDDataPairs(oemol):
if dp.GetTag() == "atom.dprop.PartialCharge":
charges_str = oechem.OEGetSDData(oemol, "atom.dprop.PartialCharge")
charges_unitless = [float(i) for i in charges_str.split()]
assert len(charges_unitless) == oemol.NumAtoms()
for charge, oeatom in zip(charges_unitless, oemol.GetAtoms()):
oeatom.SetPartialCharge(charge)
oechem.OEDeleteSDData(oemol, "atom.dprop.PartialCharge")
return True
return False
def _read_oemolistream_molecules(
self,
oemolistream,
allow_undefined_stereo: bool,
file_path: Optional[str] = None,
_cls=None,
):
"""
Reads and return the Molecules in a OEMol input stream.
Parameters
----------
oemolistream
The OEMol input stream to read from.
allow_undefined_stereo
If false, raises an exception if oemol contains undefined stereochemistry.
file_path
The path to the mol2 file. This is used exclusively to make
the error message more meaningful when the mol2 files doesn't
use Tripos atom types.
_cls
Molecule constructor
Returns
-------
molecules
The list of Molecule objects in the stream.
"""
from openeye import oechem
mols = list()
oemol = oechem.OEMol()
while oechem.OEReadMolecule(oemolistream, oemol):
oechem.OEPerceiveChiral(oemol)
oechem.OEAssignAromaticFlags(oemol, oechem.OEAroModel_MDL)
oechem.OE3DToInternalStereo(oemol)
# If this is either a multi-conformer or multi-molecule SD file, check to see if there are partial charges
if (oemolistream.GetFormat() == oechem.OEFormat_SDF) and hasattr(
oemol, "GetConfs"
):
# The openFF toolkit treats each conformer in a "multiconformer" SDF as
# a separate molecule.
# https://github.com/openforcefield/openff-toolkit/issues/202
# Note that there is ambiguity about how SD data and "multiconformer" SD files should be stored.
# As a result, we have to do some weird stuff below, as discussed in
# https://docs.eyesopen.com/toolkits/python/oechemtk/oemol.html#dude-where-s-my-sd-data
# Jeff: I was unable to find a way to distinguish whether a SDF was multiconformer or not.
# The logic below should handle either single- or multi-conformer SDFs.
for conf in oemol.GetConfIter():
# First, we turn "conf" into an OEMCMol (OE multiconformer mol), since OTHER file formats
# really are multiconformer, and we will eventually feed this into the `from_openeye` function,
# which is made to ingest multiconformer mols.
this_conf_oemcmol = conf.GetMCMol()
# Then, we take any SD data pairs that were on the oemol, and copy them on to "this_conf_oemcmol".
# These SD pairs will be populated if we're dealing with a single-conformer SDF.
for dp in oechem.OEGetSDDataPairs(oemol):
oechem.OESetSDData(
this_conf_oemcmol, dp.GetTag(), dp.GetValue()
)
# On the other hand, these SD pairs will be populated if we're dealing with a MULTI-conformer SDF.
for dp in oechem.OEGetSDDataPairs(conf):
oechem.OESetSDData(
this_conf_oemcmol, dp.GetTag(), dp.GetValue()
)
# This function fishes out the special SD data tag we use for partial charge
# ("atom.dprop.PartialCharge"), and applies those as OETK-supported partial charges on the OEAtoms
has_charges = self._turn_oemolbase_sd_charges_into_partial_charges(
this_conf_oemcmol
)
# Finally, we feed the molecule into `from_openeye`, where it converted into an OFFMol
mol = self.from_openeye(
this_conf_oemcmol,
allow_undefined_stereo=allow_undefined_stereo,
_cls=_cls,
)
# If the molecule didn't even have the `PartialCharges` tag, we set it from zeroes to None here.
if not (has_charges):
mol.partial_charges = None
mols.append(mol)
else:
# In case this is being read from a SINGLE-molecule SD file, convert the SD field where we
# stash partial charges into actual per-atom partial charges
self._turn_oemolbase_sd_charges_into_partial_charges(oemol)
mol = self.from_openeye(
oemol, allow_undefined_stereo=allow_undefined_stereo, _cls=_cls
)
mols.append(mol)
# Check if this is an AMBER-produced mol2 file, which we can not load because they use GAFF atom types.
if oemolistream.GetFormat() == oechem.OEFormat_MOL2:
self._check_mol2_gaff_atom_type(mol, file_path)
return mols
def _smarts_to_networkx(self, substructure_smarts):
import networkx as nx
from openeye import oechem
qmol = oechem.OEQMol()
if not oechem.OEParseSmiles(qmol, substructure_smarts):
raise SMILESParseError(f"Error parsing SMARTS '{substructure_smarts}'")
oechem.OEAssignHybridization(qmol)
graph: nx.classes.graph.Graph = nx.Graph()
for atom in qmol.GetAtoms():
atomic_number = atom.GetAtomicNum()
graph.add_node(
atom.GetIdx(),
atomic_number=atomic_number,
formal_charge=atom.GetFormalCharge(),
map_index=atom.GetMapIdx(),
)
for bond in qmol.GetBonds():
bond_order = bond.GetOrder()
if bond_order == 0:
raise SMILESParseError(f"A bond in '{substructure_smarts} has order 0")
graph.add_edge(
bond.GetBgnIdx(),
bond.GetEndIdx(),
bond_order=bond_order,
)
return graph
def _assign_aromaticity_and_stereo_from_3d(self, offmol):
from openeye import oechem
oemol = offmol.to_openeye()
oechem.OEPerceiveChiral(oemol)
oechem.OE3DToInternalStereo(oemol)
# Aromaticity is re-perceived in this call
offmol_w_stereo_and_aro = self.from_openeye(oemol, allow_undefined_stereo=True)
return offmol_w_stereo_and_aro
def enumerate_protomers(
self,
molecule: "FrozenMolecule",
max_states: int = 0,
) -> list["FrozenMolecule"]:
"""
Enumerate the formal charges of a molecule to generate different protomers.
Note that, in cases where the input molecule has an uncommon protonation state
(for example ``[NH2-]``), the input molecule may not be included in the output.
Parameters
----------
molecule
The molecule whose state we should enumerate
max_states
The maximum number of protomer states to be returned. If 0, the default,
attempt to return all protomers.
Returns
------
molecules
A list of the protomers of the input molecules, including the input molecule if found
by Quacpac and not pruned by `max_states`.
"""
from openeye import oequacpac
options = oequacpac.OEFormalChargeOptions()
options.SetMaxCount(max_states)
return [
self.from_openeye(
protomer,
allow_undefined_stereo=True,
_cls=molecule.__class__,
)
for protomer in oequacpac.OEEnumerateFormalCharges(
self.to_openeye(molecule=molecule),
options,
)
]
def enumerate_stereoisomers(
self,
molecule: "FrozenMolecule",
undefined_only: bool = False,
max_isomers: int = 20,
rationalise: bool = True,
) -> list["FrozenMolecule"]:
"""
Enumerate the stereocenters and bonds of the current molecule.
Parameters
----------
molecule
The molecule whose state we should enumerate
undefined_only
If we should enumerate all stereocenters and bonds or only those with undefined stereochemistry
max_isomers
The maximum amount of molecules that should be returned
rationalise
If we should try to build and rationalise the molecule to ensure it can exist
Returns
--------
molecules
A list of openff.toolkit.topology.Molecule instances
"""
from openeye import oechem, oeomega
oemol = self.to_openeye(molecule=molecule)
# arguments for this function can be found here
# <https://docs.eyesopen.com/toolkits/python/omegatk/OEConfGenFunctions/OEFlipper.html?highlight=stereoisomers>
molecules = []
for isomer in oeomega.OEFlipper(oemol, 200, not undefined_only, True, False):
if rationalise:
# try and determine if the molecule is reasonable by generating a conformer with
# strict stereo, like embedding in rdkit
omega = oeomega.OEOmega()
omega.SetMaxConfs(1)
omega.SetCanonOrder(False)
# Don't generate random stereoisomer if not specified
omega.SetStrictStereo(True)
mol = oechem.OEMol(isomer)
status = omega(mol)
if status:
isomol = self.from_openeye(mol, _cls=molecule.__class__)
if isomol != molecule:
molecules.append(isomol)
else:
isomol = self.from_openeye(isomer, _cls=molecule.__class__)
if isomol != molecule:
molecules.append(isomol)
return molecules[:max_isomers]
def enumerate_tautomers(
self, molecule: "FrozenMolecule", max_states: int = 20
) -> list["FrozenMolecule"]:
"""
Enumerate the possible tautomers of the current molecule
Parameters
----------
molecule
The molecule whose state we should enumerate
max_states
The maximum amount of molecules that should be returned
Returns
-------
molecules
A list of openff.toolkit.topology.Molecule instances excluding the input molecule.