openff-toolkit 0.18.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- devtools/scripts/build_cookiecutter_json.py +22 -0
- docs/conf.py +296 -0
- docs/conftest.py +23 -0
- examples/conformer_energies/conformer_energies.py +143 -0
- examples/deprecated/SMIRNOFF_comparison/compare_molecule_energies.py +48 -0
- examples/deprecated/SMIRNOFF_comparison/compare_set_energies.py +58 -0
- examples/deprecated/liquid_box/create_mol2_pdb/create_mol2_pdb.py +193 -0
- examples/deprecated/liquid_box/openff_simulation.py +72 -0
- examples/deprecated/mixedFF_structure/generate_mixedFF_complex.py +56 -0
- examples/deprecated/testing/test_impropers/tleap_tools.py +120 -0
- examples/examples_helper.py +61 -0
- openff/toolkit/__init__.py +101 -0
- openff/toolkit/_tests/__init__.py +0 -0
- openff/toolkit/_tests/_stale_tests.py +146 -0
- openff/toolkit/_tests/conftest.py +108 -0
- openff/toolkit/_tests/create_molecules.py +494 -0
- openff/toolkit/_tests/mocking.py +145 -0
- openff/toolkit/_tests/molecule/__init__.py +1 -0
- openff/toolkit/_tests/molecule/test_state_enumeration.py +302 -0
- openff/toolkit/_tests/test_energies.py +136 -0
- openff/toolkit/_tests/test_examples.py +109 -0
- openff/toolkit/_tests/test_forcefield.py +3864 -0
- openff/toolkit/_tests/test_interchange.py +19 -0
- openff/toolkit/_tests/test_io.py +19 -0
- openff/toolkit/_tests/test_links.py +73 -0
- openff/toolkit/_tests/test_mm_molecule.py +404 -0
- openff/toolkit/_tests/test_molecule.py +4246 -0
- openff/toolkit/_tests/test_nagl.py +169 -0
- openff/toolkit/_tests/test_parameter_plugins.py +89 -0
- openff/toolkit/_tests/test_parameters.py +2898 -0
- openff/toolkit/_tests/test_toolkit_io.py +1088 -0
- openff/toolkit/_tests/test_toolkits.py +4418 -0
- openff/toolkit/_tests/test_topology.py +2485 -0
- openff/toolkit/_tests/test_utils.py +101 -0
- openff/toolkit/_tests/test_utils_callback.py +178 -0
- openff/toolkit/_tests/test_utils_collections.py +263 -0
- openff/toolkit/_tests/test_utils_serialization.py +168 -0
- openff/toolkit/_tests/utils.py +1747 -0
- openff/toolkit/data/README.md +8 -0
- openff/toolkit/data/molecules/AlkEthOH_test_filt1_ff.mol2 +2026 -0
- openff/toolkit/data/molecules/AlkEthOH_test_filt1_tripos.mol2 +2026 -0
- openff/toolkit/data/molecules/AlkEthOH_tripos.tar.gz +0 -0
- openff/toolkit/data/molecules/CID20742535_anion.sdf +50 -0
- openff/toolkit/data/molecules/CID20742535_neutral.sdf +51 -0
- openff/toolkit/data/molecules/FreeSolv.tar.gz +0 -0
- openff/toolkit/data/molecules/MiniDrugBank.sdf +33988 -0
- openff/toolkit/data/molecules/MiniDrugBank_tripos.mol2 +35462 -0
- openff/toolkit/data/molecules/PT2385.sdf +90 -0
- openff/toolkit/data/molecules/QL8.sdf +401 -0
- openff/toolkit/data/molecules/README.md +21 -0
- openff/toolkit/data/molecules/benzene.crd +8 -0
- openff/toolkit/data/molecules/benzene.mol2 +34 -0
- openff/toolkit/data/molecules/benzene.top +166 -0
- openff/toolkit/data/molecules/butane_multi.sdf +231 -0
- openff/toolkit/data/molecules/cyclohexane.mol2 +44 -0
- openff/toolkit/data/molecules/ethanol.mol2 +25 -0
- openff/toolkit/data/molecules/ethanol.sdf +23 -0
- openff/toolkit/data/molecules/ethanol_partial_charges.sdf +26 -0
- openff/toolkit/data/molecules/ethanol_reordered.mol2 +25 -0
- openff/toolkit/data/molecules/ethanol_reordered.sdf +23 -0
- openff/toolkit/data/molecules/ethene_rdkit.sdf +17 -0
- openff/toolkit/data/molecules/laromustine_ff.mol2 +71 -0
- openff/toolkit/data/molecules/laromustine_tripos.mol2 +71 -0
- openff/toolkit/data/molecules/methane_multiconformer.sdf +32 -0
- openff/toolkit/data/molecules/methane_multiconformer_properties.sdf +45 -0
- openff/toolkit/data/molecules/nh4.pdb +7 -0
- openff/toolkit/data/molecules/po4_phenylphosphate.pdb +46 -0
- openff/toolkit/data/molecules/ruxolitinib_conformers.sdf +910 -0
- openff/toolkit/data/molecules/toluene.mol2 +38 -0
- openff/toolkit/data/molecules/toluene.mol2.gz +0 -0
- openff/toolkit/data/molecules/toluene.pdb +30 -0
- openff/toolkit/data/molecules/toluene.sdf +36 -0
- openff/toolkit/data/molecules/toluene_charged.mol2 +38 -0
- openff/toolkit/data/molecules/z_3_hydroxy_propenal.sdf +23 -0
- openff/toolkit/data/proteins/5tbm_complex_solv.pdb +1928 -0
- openff/toolkit/data/proteins/5tbm_complex_solv_box.pdb +19563 -0
- openff/toolkit/data/proteins/CTerminal_ALA.pdb +20 -0
- openff/toolkit/data/proteins/CTerminal_ALA.sdf +43 -0
- openff/toolkit/data/proteins/CTerminal_ALA_ALA.pdb +30 -0
- openff/toolkit/data/proteins/CTerminal_ALA_ALA_misnamedH.pdb +30 -0
- openff/toolkit/data/proteins/CTerminal_ARG.pdb +34 -0
- openff/toolkit/data/proteins/CTerminal_TRP.pdb +34 -0
- openff/toolkit/data/proteins/MainChain_ALA.pdb +25 -0
- openff/toolkit/data/proteins/MainChain_ALA.sdf +52 -0
- openff/toolkit/data/proteins/MainChain_ALA_ALA.pdb +35 -0
- openff/toolkit/data/proteins/MainChain_ALA_ALA.sdf +69 -0
- openff/toolkit/data/proteins/MainChain_ALA_ALA_icodes.pdb +35 -0
- openff/toolkit/data/proteins/MainChain_ALA_ALA_no_hydrogens.pdb +17 -0
- openff/toolkit/data/proteins/MainChain_ARG.pdb +39 -0
- openff/toolkit/data/proteins/MainChain_ARG.sdf +81 -0
- openff/toolkit/data/proteins/MainChain_CYM.pdb +25 -0
- openff/toolkit/data/proteins/MainChain_CYS.pdb +26 -0
- openff/toolkit/data/proteins/MainChain_CYX.pdb +48 -0
- openff/toolkit/data/proteins/MainChain_CYX.sdf +96 -0
- openff/toolkit/data/proteins/MainChain_GLH.sdf +64 -0
- openff/toolkit/data/proteins/MainChain_GLU.sdf +63 -0
- openff/toolkit/data/proteins/MainChain_HID.pdb +32 -0
- openff/toolkit/data/proteins/MainChain_HIE.pdb +32 -0
- openff/toolkit/data/proteins/MainChain_HIE.sdf +67 -0
- openff/toolkit/data/proteins/MainChain_HIP.pdb +33 -0
- openff/toolkit/data/proteins/MainChain_HIP.sdf +70 -0
- openff/toolkit/data/proteins/MainChain_PRO.pdb +29 -0
- openff/toolkit/data/proteins/MainChain_TRP.pdb +39 -0
- openff/toolkit/data/proteins/NTerminal_ALA.pdb +21 -0
- openff/toolkit/data/proteins/NTerminal_ALA.sdf +45 -0
- openff/toolkit/data/proteins/NTerminal_ALA_ALA.pdb +31 -0
- openff/toolkit/data/proteins/NTerminal_ARG.pdb +35 -0
- openff/toolkit/data/proteins/NTerminal_TRP.pdb +35 -0
- openff/toolkit/data/proteins/T4-protein-unprocessed-4w51.pdb +1892 -0
- openff/toolkit/data/proteins/T4-protein.mol2 +5461 -0
- openff/toolkit/data/proteins/T4-protein.pdb +2637 -0
- openff/toolkit/data/proteins/T4-protein.sdf +5318 -0
- openff/toolkit/data/proteins/T4_protein_waters.pdb +2965 -0
- openff/toolkit/data/proteins/TwoMol_SER_CYS.pdb +50 -0
- openff/toolkit/data/proteins/aa_residues_substructures_explicit_bond_orders_with_caps.json +6435 -0
- openff/toolkit/data/proteins/aa_residues_substructures_explicit_bond_orders_with_caps_explicit_connectivity.json +6675 -0
- openff/toolkit/data/proteins/aa_residues_substructures_with_caps.json +6297 -0
- openff/toolkit/data/proteins/ace-ZZZ-gly-nme.pdb +78 -0
- openff/toolkit/data/proteins/ace-ZZZ-gly-nme.sdf +98 -0
- openff/toolkit/data/proteins/ace-a10-nme.sdf +229 -0
- openff/toolkit/data/proteins/ace-ala-nh2.pdb +21 -0
- openff/toolkit/data/proteins/fluoresceine_dyed_helix_capped.pdb +338 -0
- openff/toolkit/data/proteins/neutral_arginine.pdb +31 -0
- openff/toolkit/data/proteins/split_chain.pdb +74 -0
- openff/toolkit/data/proteins/split_chain_reordered.pdb +74 -0
- openff/toolkit/data/reference_energies/README.md +6 -0
- openff/toolkit/data/reference_energies/reference_0.8.0.json +1 -0
- openff/toolkit/data/reference_energies/reference_0.8.0.json.txt +180 -0
- openff/toolkit/data/reference_energies/reference_after_1007.json +1 -0
- openff/toolkit/data/reference_energies/reference_after_1007.json.txt +350 -0
- openff/toolkit/data/reference_energies/reference_after_802.json +1 -0
- openff/toolkit/data/reference_energies/reference_after_802.json.txt +291 -0
- openff/toolkit/data/systems/README.md +3 -0
- openff/toolkit/data/systems/amber/cyclohexane_ethanol_0.4_0.6.inpcrd +1511 -0
- openff/toolkit/data/systems/amber/cyclohexane_ethanol_0.4_0.6.prmtop +13367 -0
- openff/toolkit/data/systems/monomers/butanol.mol2 +38 -0
- openff/toolkit/data/systems/monomers/butanol.sdf +88 -0
- openff/toolkit/data/systems/monomers/cyclohexane.mol2 +45 -0
- openff/toolkit/data/systems/monomers/cyclohexane.sdf +105 -0
- openff/toolkit/data/systems/monomers/ethanol.mol2 +26 -0
- openff/toolkit/data/systems/monomers/ethanol.sdf +58 -0
- openff/toolkit/data/systems/monomers/methane.mol2 +18 -0
- openff/toolkit/data/systems/monomers/methane.sdf +38 -0
- openff/toolkit/data/systems/monomers/propane.mol2 +30 -0
- openff/toolkit/data/systems/monomers/propane.sdf +68 -0
- openff/toolkit/data/systems/monomers/tip3p_water.mol2 +14 -0
- openff/toolkit/data/systems/monomers/water.mol2 +14 -0
- openff/toolkit/data/systems/monomers/water.sdf +28 -0
- openff/toolkit/data/systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb +6272 -0
- openff/toolkit/data/systems/packmol_boxes/cyclohexane_water.pdb +5524 -0
- openff/toolkit/data/systems/packmol_boxes/ethanol_water.pdb +5174 -0
- openff/toolkit/data/systems/packmol_boxes/propane_methane_butanol_0.2_0.3_0.5.pdb +7959 -0
- openff/toolkit/data/systems/test_systems/1_cyclohexane_1_ethanol.pdb +61 -0
- openff/toolkit/data/systems/test_systems/1_ethanol.pdb +24 -0
- openff/toolkit/data/systems/test_systems/1_ethanol_no_conect.pdb +15 -0
- openff/toolkit/data/systems/test_systems/1_ethanol_reordered.pdb +24 -0
- openff/toolkit/data/systems/test_systems/PE.pdb +67 -0
- openff/toolkit/data/systems/test_systems/README.md +3 -0
- openff/toolkit/data/systems/test_systems/T4_lysozyme_water_ions.pdb +29240 -0
- openff/toolkit/data/test_forcefields/Frosst_AlkEthOH.offxml +61 -0
- openff/toolkit/data/test_forcefields/Frosst_AlkEthOH_GBSA.offxml +78 -0
- openff/toolkit/data/test_forcefields/Frosst_AlkEthOH_MDL.offxml +62 -0
- openff/toolkit/data/test_forcefields/Frosst_AlkEthOH_parmAtFrosst.offxml +64 -0
- openff/toolkit/data/test_forcefields/GBSA_HCT-1.0.offxml +21 -0
- openff/toolkit/data/test_forcefields/GBSA_OBC1-1.0.offxml +18 -0
- openff/toolkit/data/test_forcefields/GBSA_OBC2-1.0.offxml +18 -0
- openff/toolkit/data/test_forcefields/README.md +23 -0
- openff/toolkit/data/test_forcefields/ammonia_minimal.offxml +27 -0
- openff/toolkit/data/test_forcefields/benzene_minimal.offxml +29 -0
- openff/toolkit/data/test_forcefields/chargeincrement-test.offxml +16 -0
- openff/toolkit/data/test_forcefields/frcmod.Frosst_AlkEthOH_withIDs +85 -0
- openff/toolkit/data/test_forcefields/ion_charges.offxml +18 -0
- openff/toolkit/data/test_forcefields/mangled.offxml +9 -0
- openff/toolkit/data/test_forcefields/old/README.md +9 -0
- openff/toolkit/data/test_forcefields/old/hbonds.offxml +11 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_2_spec_0_1.offxml +332 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_2_spec_0_2.offxml +338 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_2_spec_0_3.offxml +329 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_fixed_spec_0_1.offxml +342 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_fixed_spec_0_2.offxml +348 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_fixed_spec_0_3.offxml +337 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_spec_0_1.offxml +340 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_spec_0_2.offxml +346 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_spec_0_3.offxml +337 -0
- openff/toolkit/data/test_forcefields/smirff99Frosst_reference_0_1_spec.offxml +349 -0
- openff/toolkit/data/test_forcefields/smirnoff99Frosst_experimental.offxml +343 -0
- openff/toolkit/data/test_forcefields/smirnoff99Frosst_reference_0_1_spec.offxml +349 -0
- openff/toolkit/data/test_forcefields/smirnoff99Frosst_reference_0_2_spec.offxml +356 -0
- openff/toolkit/data/test_forcefields/test_forcefield.offxml +346 -0
- openff/toolkit/data/test_forcefields/tip3p.offxml +22 -0
- openff/toolkit/data/test_forcefields/unsupported_smirnoff_version.offxml +9 -0
- openff/toolkit/topology/__init__.py +43 -0
- openff/toolkit/topology/_mm_molecule.py +663 -0
- openff/toolkit/topology/molecule.py +6102 -0
- openff/toolkit/topology/topology.py +2555 -0
- openff/toolkit/typing/__init__.py +1 -0
- openff/toolkit/typing/engines/__init__.py +1 -0
- openff/toolkit/typing/engines/smirnoff/__init__.py +31 -0
- openff/toolkit/typing/engines/smirnoff/forcefield.py +1440 -0
- openff/toolkit/typing/engines/smirnoff/io.py +234 -0
- openff/toolkit/typing/engines/smirnoff/parameters.py +3839 -0
- openff/toolkit/typing/engines/smirnoff/plugins.py +91 -0
- openff/toolkit/utils/__init__.py +57 -0
- openff/toolkit/utils/_viz.py +104 -0
- openff/toolkit/utils/ambertools_wrapper.py +507 -0
- openff/toolkit/utils/base_wrapper.py +268 -0
- openff/toolkit/utils/builtin_wrapper.py +136 -0
- openff/toolkit/utils/callback.py +187 -0
- openff/toolkit/utils/collections.py +247 -0
- openff/toolkit/utils/constants.py +18 -0
- openff/toolkit/utils/exceptions.py +766 -0
- openff/toolkit/utils/nagl_wrapper.py +164 -0
- openff/toolkit/utils/openeye_wrapper.py +2750 -0
- openff/toolkit/utils/rdkit_wrapper.py +3302 -0
- openff/toolkit/utils/serialization.py +466 -0
- openff/toolkit/utils/toolkit_registry.py +509 -0
- openff/toolkit/utils/toolkits.py +217 -0
- openff/toolkit/utils/utils.py +805 -0
- openff_toolkit-0.18.0.dist-info/METADATA +109 -0
- openff_toolkit-0.18.0.dist-info/RECORD +231 -0
- openff_toolkit-0.18.0.dist-info/WHEEL +5 -0
- openff_toolkit-0.18.0.dist-info/licenses/LICENSE +21 -0
- openff_toolkit-0.18.0.dist-info/top_level.txt +5 -0
- utilities/deprecated/convert_frosst/convert_frcmod_0.1.py +251 -0
- utilities/deprecated/convert_frosst/convert_frcmod_0.2.py +249 -0
- utilities/deprecated/convert_frosst/convert_frcmod_0.3.py +249 -0
- utilities/make_substructure_dict/_cif_to_substructure_dict.py +955 -0
- utilities/make_substructure_dict/_make_chemical_substructures.py +46 -0
- utilities/make_substructure_dict/_make_metadata_assignment_substructures.py +35 -0
- utilities/test_plugins/custom_plugins/handler_plugins.py +48 -0
- utilities/test_plugins/setup.py +19 -0
|
@@ -0,0 +1,3302 @@
|
|
|
1
|
+
# mypy: ignore-errors
|
|
2
|
+
"""
|
|
3
|
+
Wrapper class providing a minimal consistent interface to the `RDKit <http://www.rdkit.org/>`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
__all__ = ("RDKitToolkitWrapper",)
|
|
7
|
+
|
|
8
|
+
import copy
|
|
9
|
+
import functools
|
|
10
|
+
import importlib
|
|
11
|
+
import itertools
|
|
12
|
+
import logging
|
|
13
|
+
import pathlib
|
|
14
|
+
import tempfile
|
|
15
|
+
import warnings
|
|
16
|
+
from collections import defaultdict
|
|
17
|
+
from typing import TYPE_CHECKING, Any
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
from cachetools import LRUCache, cached
|
|
21
|
+
from numpy.typing import NDArray
|
|
22
|
+
from openff.units.elements import SYMBOLS
|
|
23
|
+
|
|
24
|
+
from openff.toolkit import Quantity, unit
|
|
25
|
+
from openff.toolkit.utils import base_wrapper
|
|
26
|
+
from openff.toolkit.utils.constants import (
|
|
27
|
+
ALLOWED_AROMATICITY_MODELS,
|
|
28
|
+
DEFAULT_AROMATICITY_MODEL,
|
|
29
|
+
)
|
|
30
|
+
from openff.toolkit.utils.exceptions import (
|
|
31
|
+
AmbiguousAtomChemicalAssignment,
|
|
32
|
+
AmbiguousBondChemicalAssignment,
|
|
33
|
+
ChargeMethodUnavailableError,
|
|
34
|
+
ConformerGenerationError,
|
|
35
|
+
EmptyInChiError,
|
|
36
|
+
InChIParseError,
|
|
37
|
+
InvalidAromaticityModelError,
|
|
38
|
+
MoleculeParseError,
|
|
39
|
+
MultipleComponentsInMoleculeWarning,
|
|
40
|
+
NonUniqueSubstructureName,
|
|
41
|
+
NotAttachedToMoleculeError,
|
|
42
|
+
PDBMoleculeHasNoncontiguousAtomIndicesError,
|
|
43
|
+
RadicalsNotSupportedError,
|
|
44
|
+
SMILESParseError,
|
|
45
|
+
SubstructureAtomSmartsInvalid,
|
|
46
|
+
SubstructureBondSmartsInvalid,
|
|
47
|
+
SubstructureImproperlySpecified,
|
|
48
|
+
ToolkitUnavailableException,
|
|
49
|
+
UnassignedChemistryInPDBError,
|
|
50
|
+
UndefinedStereochemistryError,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
if TYPE_CHECKING:
|
|
54
|
+
from openff.toolkit.topology.molecule import Atom, Bond, Molecule
|
|
55
|
+
|
|
56
|
+
logger = logging.getLogger(__name__)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def normalize_file_format(file_format: str) -> str:
|
|
60
|
+
return file_format.upper()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _require_text_file_obj(file_obj):
|
|
64
|
+
try:
|
|
65
|
+
file_obj.write("")
|
|
66
|
+
except TypeError:
|
|
67
|
+
# Switch to a ValueError and use a more informative exception
|
|
68
|
+
# message to match RDKit's toolkit writer.
|
|
69
|
+
raise ValueError("Need a text mode file object like StringIO or a file opened with mode 't'") from None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class RDKitToolkitWrapper(base_wrapper.ToolkitWrapper):
|
|
73
|
+
"""
|
|
74
|
+
RDKit toolkit wrapper
|
|
75
|
+
|
|
76
|
+
.. warning :: This API is experimental and subject to change.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
_toolkit_name = "The RDKit"
|
|
80
|
+
_toolkit_installation_instructions = (
|
|
81
|
+
"A conda-installable version of the free and open source RDKit cheminformatics "
|
|
82
|
+
"toolkit can be found at: https://anaconda.org/conda-forge/rdkit"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
_supported_charge_methods = {"mmff94": dict(), "gasteiger": dict()}
|
|
86
|
+
|
|
87
|
+
SUPPORTED_CHARGE_METHODS: set[str] = set(_supported_charge_methods.keys())
|
|
88
|
+
|
|
89
|
+
# TODO: Add TDT support
|
|
90
|
+
_toolkit_file_read_formats = ["SDF", "MOL", "SMI"]
|
|
91
|
+
_toolkit_file_write_formats = ["SDF", "MOL", "SMI", "PDB", "TDT"]
|
|
92
|
+
|
|
93
|
+
def __init__(self):
|
|
94
|
+
super().__init__()
|
|
95
|
+
|
|
96
|
+
if not self.is_available():
|
|
97
|
+
raise ToolkitUnavailableException(
|
|
98
|
+
f"The required toolkit {self._toolkit_name} is not "
|
|
99
|
+
f"available. {self._toolkit_installation_instructions}"
|
|
100
|
+
)
|
|
101
|
+
else:
|
|
102
|
+
from rdkit import __version__ as rdkit_version
|
|
103
|
+
|
|
104
|
+
self._toolkit_version = rdkit_version
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def toolkit_file_write_formats(self) -> list[str]:
|
|
108
|
+
"""
|
|
109
|
+
List of file formats that this toolkit can write.
|
|
110
|
+
"""
|
|
111
|
+
return self._toolkit_file_write_formats
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def is_available(cls) -> bool:
|
|
115
|
+
"""
|
|
116
|
+
Check whether the RDKit toolkit can be imported
|
|
117
|
+
|
|
118
|
+
Returns
|
|
119
|
+
-------
|
|
120
|
+
is_installed
|
|
121
|
+
True if RDKit is installed, False otherwise.
|
|
122
|
+
|
|
123
|
+
"""
|
|
124
|
+
if cls._is_available is None:
|
|
125
|
+
try:
|
|
126
|
+
importlib.import_module("rdkit", "Chem")
|
|
127
|
+
except ImportError:
|
|
128
|
+
cls._is_available = False
|
|
129
|
+
else:
|
|
130
|
+
cls._is_available = True
|
|
131
|
+
return cls._is_available
|
|
132
|
+
|
|
133
|
+
def from_object(
|
|
134
|
+
self,
|
|
135
|
+
obj,
|
|
136
|
+
allow_undefined_stereo: bool = False,
|
|
137
|
+
_cls=None,
|
|
138
|
+
):
|
|
139
|
+
"""
|
|
140
|
+
If given an rdchem.Mol (or rdchem.Mol-derived object), this function will load it into an
|
|
141
|
+
openff.toolkit.topology.molecule. Otherwise, it will return False.
|
|
142
|
+
|
|
143
|
+
Parameters
|
|
144
|
+
----------
|
|
145
|
+
obj
|
|
146
|
+
An object to be type-checked and converted into a Molecule, if possible.
|
|
147
|
+
allow_undefined_stereo
|
|
148
|
+
Whether to accept molecules with undefined stereocenters. If False,
|
|
149
|
+
an exception will be raised if a molecule with undefined stereochemistry
|
|
150
|
+
is passed into this function.
|
|
151
|
+
_cls
|
|
152
|
+
Molecule constructor
|
|
153
|
+
|
|
154
|
+
Returns
|
|
155
|
+
-------
|
|
156
|
+
Molecule or False
|
|
157
|
+
An openff.toolkit.topology.molecule Molecule.
|
|
158
|
+
|
|
159
|
+
Raises
|
|
160
|
+
------
|
|
161
|
+
NotImplementedError
|
|
162
|
+
If the object could not be converted into a Molecule.
|
|
163
|
+
"""
|
|
164
|
+
# TODO: Add tests for the from_object functions
|
|
165
|
+
from rdkit import Chem
|
|
166
|
+
|
|
167
|
+
if _cls is None:
|
|
168
|
+
from openff.toolkit.topology.molecule import Molecule
|
|
169
|
+
|
|
170
|
+
_cls = Molecule
|
|
171
|
+
if isinstance(obj, Chem.rdchem.Mol):
|
|
172
|
+
return _cls.from_rdkit(
|
|
173
|
+
obj,
|
|
174
|
+
allow_undefined_stereo=allow_undefined_stereo,
|
|
175
|
+
)
|
|
176
|
+
raise NotImplementedError(f"Cannot create Molecule from {type(obj)} object")
|
|
177
|
+
|
|
178
|
+
def from_pdb_and_smiles(
|
|
179
|
+
self,
|
|
180
|
+
file_path: str,
|
|
181
|
+
smiles: str,
|
|
182
|
+
allow_undefined_stereo: bool = False,
|
|
183
|
+
_cls=None,
|
|
184
|
+
name: str = "",
|
|
185
|
+
):
|
|
186
|
+
"""
|
|
187
|
+
Create a Molecule from a pdb file and a SMILES string using RDKit.
|
|
188
|
+
|
|
189
|
+
Requires RDKit to be installed.
|
|
190
|
+
|
|
191
|
+
The molecule is created and sanitised based on the SMILES string, we then find a mapping
|
|
192
|
+
between this molecule and one from the PDB based only on atomic number and connections.
|
|
193
|
+
The SMILES molecule is then reindexed to match the PDB, the conformer is attached, and the
|
|
194
|
+
molecule returned.
|
|
195
|
+
|
|
196
|
+
Note that any stereochemistry in the molecule is set by the SMILES, and not the coordinates
|
|
197
|
+
of the PDB.
|
|
198
|
+
|
|
199
|
+
Parameters
|
|
200
|
+
----------
|
|
201
|
+
file_path
|
|
202
|
+
PDB file path
|
|
203
|
+
smiles
|
|
204
|
+
a valid smiles string for the pdb, used for stereochemistry, formal charges, and bond order
|
|
205
|
+
allow_undefined_stereo
|
|
206
|
+
If false, raises an exception if SMILES contains undefined stereochemistry.
|
|
207
|
+
_cls
|
|
208
|
+
Molecule constructor
|
|
209
|
+
name
|
|
210
|
+
An optional name for the output molecule
|
|
211
|
+
|
|
212
|
+
Returns
|
|
213
|
+
--------
|
|
214
|
+
molecule
|
|
215
|
+
An OFFMol instance with ordering the same as used in the PDB file.
|
|
216
|
+
|
|
217
|
+
Raises
|
|
218
|
+
------
|
|
219
|
+
InvalidConformerError
|
|
220
|
+
"""
|
|
221
|
+
from rdkit import Chem
|
|
222
|
+
|
|
223
|
+
warnings.warn(
|
|
224
|
+
"`RDKitToolkitWrapper.from_polymer_pdb` is deprecated in favor of `Topology.from_pdb`, the recommended "
|
|
225
|
+
"method for loading PDB files. (Note the `unique_molecules` argument.) This method will "
|
|
226
|
+
"be removed in a future release of the OpenFF Toolkit.",
|
|
227
|
+
stacklevel=2,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
# Make the molecule from smiles
|
|
231
|
+
offmol = self.from_smiles(
|
|
232
|
+
smiles,
|
|
233
|
+
allow_undefined_stereo=allow_undefined_stereo,
|
|
234
|
+
_cls=_cls,
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
# Make another molecule from the PDB. We squelch stereo errors here, since
|
|
238
|
+
# RDKit's PDB loader doesn't attempt to perceive stereochemistry, bond order,
|
|
239
|
+
# or formal charge (and we don't need those here).
|
|
240
|
+
prev_log_level = logger.getEffectiveLevel()
|
|
241
|
+
logger.setLevel(logging.ERROR)
|
|
242
|
+
pdbmol = self.from_rdkit(
|
|
243
|
+
Chem.MolFromPDBFile(file_path, removeHs=False),
|
|
244
|
+
allow_undefined_stereo=True,
|
|
245
|
+
hydrogens_are_explicit=True,
|
|
246
|
+
_cls=_cls,
|
|
247
|
+
)
|
|
248
|
+
logger.setLevel(prev_log_level)
|
|
249
|
+
|
|
250
|
+
# check isomorphic and get the mapping if true the mapping will be
|
|
251
|
+
# dict[offmol_index, pdbmol_index] sorted by offmol index
|
|
252
|
+
_, mapping = _cls.are_isomorphic(
|
|
253
|
+
offmol,
|
|
254
|
+
pdbmol,
|
|
255
|
+
return_atom_map=True,
|
|
256
|
+
aromatic_matching=False,
|
|
257
|
+
formal_charge_matching=False,
|
|
258
|
+
bond_order_matching=False,
|
|
259
|
+
atom_stereochemistry_matching=False,
|
|
260
|
+
bond_stereochemistry_matching=False,
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
if mapping is None:
|
|
264
|
+
from openff.toolkit.topology.molecule import InvalidConformerError
|
|
265
|
+
|
|
266
|
+
raise InvalidConformerError("The PDB and SMILES structures do not match.")
|
|
267
|
+
|
|
268
|
+
new_mol = offmol.remap(mapping)
|
|
269
|
+
|
|
270
|
+
# the pdb conformer is in the correct order so just attach it here
|
|
271
|
+
new_mol._add_conformer(pdbmol.conformers[0])
|
|
272
|
+
|
|
273
|
+
# Take residue info from PDB
|
|
274
|
+
for pdbatom, newatom in zip(pdbmol.atoms, new_mol.atoms):
|
|
275
|
+
newatom.metadata.update(pdbatom.metadata)
|
|
276
|
+
newatom.name = pdbatom.name
|
|
277
|
+
new_mol.add_default_hierarchy_schemes()
|
|
278
|
+
|
|
279
|
+
new_mol.name = name
|
|
280
|
+
return new_mol
|
|
281
|
+
|
|
282
|
+
def _polymer_openmm_topology_to_offmol(self, molecule_class, omm_top, substructure_dictionary):
|
|
283
|
+
rdkit_mol = self._polymer_openmm_topology_to_rdmol(omm_top, substructure_dictionary)
|
|
284
|
+
offmol = molecule_class.from_rdkit(rdkit_mol, allow_undefined_stereo=True)
|
|
285
|
+
return offmol
|
|
286
|
+
|
|
287
|
+
def _polymer_openmm_pdbfile_to_offtop(
|
|
288
|
+
self,
|
|
289
|
+
topology_class,
|
|
290
|
+
pdbfile,
|
|
291
|
+
substructure_dictionary,
|
|
292
|
+
coords_angstrom,
|
|
293
|
+
_custom_substructures: dict[str, list[str]] | None = None,
|
|
294
|
+
):
|
|
295
|
+
import json
|
|
296
|
+
|
|
297
|
+
from openff.units.openmm import from_openmm
|
|
298
|
+
from rdkit import Chem, Geometry
|
|
299
|
+
from rdkit.DataStructs.cDataStructs import BitVectToBinaryText
|
|
300
|
+
|
|
301
|
+
omm_top = pdbfile.topology
|
|
302
|
+
|
|
303
|
+
if not _custom_substructures:
|
|
304
|
+
_custom_substructures = dict()
|
|
305
|
+
|
|
306
|
+
# if custom substructures exist, validate them and add to the substructure_dictionary
|
|
307
|
+
# (existing amino acid substructures are already validated as part of their creation)
|
|
308
|
+
|
|
309
|
+
self._validate_custom_substructures( # errors if any errors found
|
|
310
|
+
_custom_substructures, forbidden_keys=substructure_dictionary.keys()
|
|
311
|
+
)
|
|
312
|
+
custom_substructure_dictionary = self._prepare_custom_substructures(_custom_substructures)
|
|
313
|
+
substructure_dictionary.update(
|
|
314
|
+
custom_substructure_dictionary
|
|
315
|
+
) # concats both dicts, unique keys are enforced in previous function
|
|
316
|
+
|
|
317
|
+
rdkit_mol = self._polymer_openmm_topology_to_rdmol(omm_top, substructure_dictionary)
|
|
318
|
+
|
|
319
|
+
# If the PDB file contains a single molecule that doesn't have contiguous atom indices,
|
|
320
|
+
# we would need to rearrange the atoms away from the order that the user expects. We could
|
|
321
|
+
# do this with some additional logic, but until a user makes a compelling case for this to
|
|
322
|
+
# be supported, we'll just raise an error.
|
|
323
|
+
sorted_mol_frags = [tuple(sorted(i)) for i in Chem.GetMolFrags(rdkit_mol)]
|
|
324
|
+
|
|
325
|
+
for mol_idx, frag_idxs in enumerate(sorted_mol_frags):
|
|
326
|
+
# frag_idxs is sorted
|
|
327
|
+
min_frag_idx = frag_idxs[0]
|
|
328
|
+
max_frag_idx = frag_idxs[-1]
|
|
329
|
+
if len(frag_idxs) != (max_frag_idx - min_frag_idx) + 1:
|
|
330
|
+
expected_idxs = set(range(min_frag_idx, max_frag_idx + 1))
|
|
331
|
+
missing_idxs = expected_idxs.difference(set(frag_idxs))
|
|
332
|
+
raise PDBMoleculeHasNoncontiguousAtomIndicesError(
|
|
333
|
+
"At least one molecule in the PDB file has noncontiguous atom indices. "
|
|
334
|
+
"This is not currently supported by Topology.from_pdb.\n\n"
|
|
335
|
+
f"Atom indices {min(missing_idxs) + 1} and {max(missing_idxs) + 1} "
|
|
336
|
+
f"are in molecule {mol_idx}, but some or all of the intervening indices are not.\n\n"
|
|
337
|
+
"This can happen when a crosslink is introduced between two molecules, but other "
|
|
338
|
+
"molecules are present between them in the PDB atom ordering. "
|
|
339
|
+
"You may be able to get around this error by rearranging the atom order in your PDB file to "
|
|
340
|
+
"ensure that all the atoms in a single covalently bonded molecule are listed on a contiguous "
|
|
341
|
+
"series of lines (don't change atom/residue/chain naming or numbering or any "
|
|
342
|
+
"CONECT records, just the order of the ATOM/HETATM records). "
|
|
343
|
+
"For more information see https://github.com/openforcefield/openff-toolkit/issues/2093"
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
rdmol_conformer = Chem.Conformer()
|
|
347
|
+
for atom_idx in range(rdkit_mol.GetNumAtoms()):
|
|
348
|
+
x, y, z = coords_angstrom[atom_idx, :]
|
|
349
|
+
rdmol_conformer.SetAtomPosition(atom_idx, Geometry.Point3D(x, y, z))
|
|
350
|
+
rdkit_mol.AddConformer(rdmol_conformer, assignId=True)
|
|
351
|
+
Chem.SanitizeMol(
|
|
352
|
+
rdkit_mol,
|
|
353
|
+
Chem.SANITIZE_ALL ^ Chem.SANITIZE_ADJUSTHS,
|
|
354
|
+
)
|
|
355
|
+
Chem.AssignStereochemistryFrom3D(rdkit_mol)
|
|
356
|
+
Chem.Kekulize(rdkit_mol, clearAromaticFlags=True)
|
|
357
|
+
Chem.SetAromaticity(rdkit_mol, Chem.AromaticityModel.AROMATICITY_MDL)
|
|
358
|
+
|
|
359
|
+
# Don't sanitize or we risk assigning non-MDL aromaticity
|
|
360
|
+
rdmols = Chem.GetMolFrags(rdkit_mol, asMols=True, sanitizeFrags=False)
|
|
361
|
+
top = topology_class()
|
|
362
|
+
|
|
363
|
+
# Identify unique molecules and only run from_rdkit on them once.
|
|
364
|
+
# Note that this identity comparison COULD match two chemically equivalent
|
|
365
|
+
# atoms with different atom names, but that doesn't matter because we do
|
|
366
|
+
# the metadata assignment and coordinate setting outside this method, so
|
|
367
|
+
# as long as a chemically equivalent atom is sitting at the right index
|
|
368
|
+
# in the topology when the metadata is assigned there's no difference.
|
|
369
|
+
smiles2offmol: dict[str, Molecule] = dict()
|
|
370
|
+
for rdmol in rdmols:
|
|
371
|
+
# Make a copy of the molecule to assign atom maps, since
|
|
372
|
+
# otherwise the atom maps will mess with stereo assignment.
|
|
373
|
+
mapped_rdmol = Chem.Mol(rdmol)
|
|
374
|
+
for atom in mapped_rdmol.GetAtoms():
|
|
375
|
+
# the mapping must start from 1, as RDKit uses 0 to represent no mapping.
|
|
376
|
+
atom.SetAtomMapNum(atom.GetIdx() + 1)
|
|
377
|
+
mapped_smi = Chem.MolToSmiles(mapped_rdmol)
|
|
378
|
+
if mapped_smi in smiles2offmol.keys():
|
|
379
|
+
offmol = copy.deepcopy(smiles2offmol[mapped_smi])
|
|
380
|
+
else:
|
|
381
|
+
offmol = self.from_rdkit(rdmol, allow_undefined_stereo=True)
|
|
382
|
+
# assign metadata
|
|
383
|
+
for offatom, rdatom in zip(offmol.atoms, rdmol.GetAtoms()):
|
|
384
|
+
res_ids = np.frombuffer(
|
|
385
|
+
BitVectToBinaryText(rdatom.GetExplicitBitVectProp("res_ids")),
|
|
386
|
+
dtype=np.uint64,
|
|
387
|
+
)
|
|
388
|
+
query_nums = np.frombuffer(
|
|
389
|
+
BitVectToBinaryText(rdatom.GetExplicitBitVectProp("query_nums")),
|
|
390
|
+
dtype=np.uint64,
|
|
391
|
+
)
|
|
392
|
+
query_ids = np.frombuffer(
|
|
393
|
+
BitVectToBinaryText(rdatom.GetExplicitBitVectProp("query_ids")),
|
|
394
|
+
dtype=np.uint64,
|
|
395
|
+
)
|
|
396
|
+
residues = [list(substructure_dictionary.keys())[i] for i in res_ids]
|
|
397
|
+
# query_ids = [int(idx) for idx in list(query_ids)]
|
|
398
|
+
match_info = dict()
|
|
399
|
+
for res_name, query_idx, query_num in zip(residues, query_ids, query_nums):
|
|
400
|
+
match_info[int(query_num)] = (res_name, int(query_idx))
|
|
401
|
+
offatom.metadata["match_info"] = json.dumps(match_info)
|
|
402
|
+
smiles2offmol[mapped_smi] = copy.deepcopy(offmol)
|
|
403
|
+
top._add_molecule_keep_cache(offmol)
|
|
404
|
+
if pdbfile.topology.getPeriodicBoxVectors() is not None:
|
|
405
|
+
top.box_vectors = from_openmm(pdbfile.topology.getPeriodicBoxVectors())
|
|
406
|
+
top.set_positions(coords_angstrom * unit.angstrom)
|
|
407
|
+
|
|
408
|
+
return top
|
|
409
|
+
|
|
410
|
+
def _validate_custom_substructures(self, custom_substructures: dict[str, list[str]], forbidden_keys):
|
|
411
|
+
"""Validates custom substructures to adhere to monomer specifications
|
|
412
|
+
Parameters
|
|
413
|
+
----------
|
|
414
|
+
custom_substructures
|
|
415
|
+
substructures given with unique names as keys and smarts as values
|
|
416
|
+
forbidden_keys
|
|
417
|
+
a list of keys that cannot overlap with the custom substructure keys
|
|
418
|
+
|
|
419
|
+
Returns
|
|
420
|
+
-------
|
|
421
|
+
None: If validation successful. Errors otherwise
|
|
422
|
+
Raises
|
|
423
|
+
------
|
|
424
|
+
NonUniqueSubstructureName
|
|
425
|
+
Raised when any substructures have nonunique names or names that
|
|
426
|
+
conflict with toolkit substructure names (such as protein residue names)
|
|
427
|
+
SubstructureAtomSmartsInvalid
|
|
428
|
+
Raised when any atom smarts are improperly formatted
|
|
429
|
+
SubstructureBondSmartsInvalid
|
|
430
|
+
Raised when any bond smarts are improperly formatted
|
|
431
|
+
SubstructureImproperlySpecified
|
|
432
|
+
Raised when the custom substructure is inadequately specified or
|
|
433
|
+
contains conflicting information
|
|
434
|
+
|
|
435
|
+
"""
|
|
436
|
+
# ensure no duplicate keys
|
|
437
|
+
custom_keys = custom_substructures.keys()
|
|
438
|
+
same_keys = set(forbidden_keys).intersection(set(custom_keys))
|
|
439
|
+
if same_keys:
|
|
440
|
+
raise NonUniqueSubstructureName(list(same_keys))
|
|
441
|
+
for name, smarts_list in custom_substructures.items():
|
|
442
|
+
for smarts in smarts_list:
|
|
443
|
+
self._is_valid_substructure_smarts(name, smarts) # raises error if invalid
|
|
444
|
+
|
|
445
|
+
return # all tests passed without raised exception
|
|
446
|
+
|
|
447
|
+
def _is_valid_substructure_smarts(self, name, smarts):
|
|
448
|
+
from rdkit import Chem
|
|
449
|
+
|
|
450
|
+
def check_is_connected(rdmol):
|
|
451
|
+
if len(Chem.rdmolops.GetMolFrags(rdmol)) > 1:
|
|
452
|
+
error_reason = "Multiple fragments detected. Must be a single and connected substructure."
|
|
453
|
+
raise SubstructureImproperlySpecified(name, error_reason)
|
|
454
|
+
return
|
|
455
|
+
|
|
456
|
+
def check_interior_atom(atom, qmol):
|
|
457
|
+
atom_smarts = atom.GetSmarts()
|
|
458
|
+
# ensure that no unsupported logical operators exist
|
|
459
|
+
operators = r"!,;"
|
|
460
|
+
found_ops = [op in atom_smarts for op in operators]
|
|
461
|
+
if any(found_ops):
|
|
462
|
+
operator_chars = [op for op, b in zip(operators, found_ops) if b]
|
|
463
|
+
error_reason = f"found unsupported logical operator(s): {operator_chars}"
|
|
464
|
+
mol_smarts = Chem.MolToSmarts(qmol)
|
|
465
|
+
raise SubstructureAtomSmartsInvalid(name, atom.GetSmarts(), mol_smarts, error_reason)
|
|
466
|
+
# ensure that no other unsupported atomic primitives are accepted
|
|
467
|
+
unsupported_prims = r"@xXvrRhH*"
|
|
468
|
+
found_prims = [prim in atom_smarts for prim in unsupported_prims]
|
|
469
|
+
if any(found_prims):
|
|
470
|
+
operator_chars = [prim for prim, b in zip(unsupported_prims, found_prims) if b]
|
|
471
|
+
error_reason = f"found unsupported primitive(s): {operator_chars}"
|
|
472
|
+
mol_smarts = Chem.MolToSmarts(qmol)
|
|
473
|
+
raise SubstructureAtomSmartsInvalid(name, atom.GetSmarts(), mol_smarts, error_reason)
|
|
474
|
+
# require that all elements are specified in #<n> format. Because the H primitive can act as either
|
|
475
|
+
# hydrogen atom or the number of implicit hydrogens, it is cleaner to specify atoms by atomic number
|
|
476
|
+
# rather than atomic symbol.
|
|
477
|
+
# Also require explicit connecitivity in D<n> format and explicit charge with either a + or -
|
|
478
|
+
required_prims = r"[]#D:"
|
|
479
|
+
missing_prims = [prim not in atom_smarts for prim in required_prims]
|
|
480
|
+
if any(missing_prims):
|
|
481
|
+
operator_chars = [prim for prim, b in zip(required_prims, missing_prims) if b]
|
|
482
|
+
error_reason = f"required primitive(s) not included: {operator_chars}"
|
|
483
|
+
mol_smarts = Chem.MolToSmarts(qmol)
|
|
484
|
+
raise SubstructureAtomSmartsInvalid(name, atom.GetSmarts(), mol_smarts, error_reason)
|
|
485
|
+
charge_prims = r"-+"
|
|
486
|
+
if not any(prim in atom_smarts for prim in charge_prims):
|
|
487
|
+
error_reason = f"{atom_smarts}: no charge primitive (+ or -) on atom"
|
|
488
|
+
mol_smarts = Chem.MolToSmarts(qmol)
|
|
489
|
+
raise SubstructureAtomSmartsInvalid(name, atom.GetSmarts(), mol_smarts, error_reason)
|
|
490
|
+
if not atom.Match(atom):
|
|
491
|
+
error_reason = (
|
|
492
|
+
"query does not match rdchem.Mol reading of the molecule (likely due to incorrect"
|
|
493
|
+
"/ambiguous connectivity)"
|
|
494
|
+
)
|
|
495
|
+
mol_smarts = Chem.MolToSmarts(qmol)
|
|
496
|
+
raise SubstructureAtomSmartsInvalid(name, atom.GetSmarts(), mol_smarts, error_reason)
|
|
497
|
+
return
|
|
498
|
+
|
|
499
|
+
def check_neighbor_atom(atom, qmol):
|
|
500
|
+
atom_smarts = atom.GetSmarts()
|
|
501
|
+
# ensure that no unsupported logical operators exist
|
|
502
|
+
operators = r"!,;&"
|
|
503
|
+
found_ops = [op in atom_smarts for op in operators]
|
|
504
|
+
if any(found_ops):
|
|
505
|
+
operator_chars = [op for op, b in zip(operators, found_ops) if b]
|
|
506
|
+
error_reason = f"found unsupported logical operator(s): {operator_chars}"
|
|
507
|
+
mol_smarts = Chem.MolToSmarts(qmol)
|
|
508
|
+
raise SubstructureAtomSmartsInvalid(name, atom.GetSmarts(), mol_smarts, error_reason)
|
|
509
|
+
# ensure that no other unsupported atomic primitives are accepted
|
|
510
|
+
unsupported_prims = r"@xXDvrRhH"
|
|
511
|
+
found_prims = [prim in atom_smarts for prim in unsupported_prims]
|
|
512
|
+
if any(found_prims):
|
|
513
|
+
operator_chars = [prim for prim, b in zip(unsupported_prims, found_prims) if b]
|
|
514
|
+
error_reason = f"found unsupported primitive(s): {operator_chars}"
|
|
515
|
+
mol_smarts = Chem.MolToSmarts(qmol)
|
|
516
|
+
raise SubstructureAtomSmartsInvalid(name, atom.GetSmarts(), mol_smarts, error_reason)
|
|
517
|
+
# require that atoms have a wildtype atom and label
|
|
518
|
+
required_prims = r"[]*:"
|
|
519
|
+
missing_prims = [prim not in atom_smarts for prim in required_prims]
|
|
520
|
+
if any(missing_prims):
|
|
521
|
+
operator_chars = [prim for prim, b in zip(required_prims, missing_prims) if b]
|
|
522
|
+
error_reason = f"required primitive(s) not included: {operator_chars}"
|
|
523
|
+
mol_smarts = Chem.MolToSmarts(qmol)
|
|
524
|
+
raise SubstructureAtomSmartsInvalid(name, atom.GetSmarts(), mol_smarts, error_reason)
|
|
525
|
+
return
|
|
526
|
+
|
|
527
|
+
def check_bond(bond):
|
|
528
|
+
valid_bond_types = [
|
|
529
|
+
Chem.BondType.SINGLE,
|
|
530
|
+
Chem.BondType.DOUBLE,
|
|
531
|
+
Chem.BondType.TRIPLE,
|
|
532
|
+
]
|
|
533
|
+
if bond.GetBondType() not in valid_bond_types:
|
|
534
|
+
raise SubstructureBondSmartsInvalid(name, bond, [str(b) for b in valid_bond_types])
|
|
535
|
+
return
|
|
536
|
+
|
|
537
|
+
qmol = Chem.MolFromSmarts(smarts)
|
|
538
|
+
|
|
539
|
+
# check if graph is connected
|
|
540
|
+
check_is_connected(qmol)
|
|
541
|
+
|
|
542
|
+
# check atom strings for required and unsupported primitives
|
|
543
|
+
for atom in qmol.GetAtoms():
|
|
544
|
+
if atom.GetAtomicNum() > 0:
|
|
545
|
+
check_interior_atom(atom, qmol)
|
|
546
|
+
elif atom.GetAtomicNum() == 0 and "#" not in atom.GetSmarts():
|
|
547
|
+
check_neighbor_atom(atom, qmol)
|
|
548
|
+
else:
|
|
549
|
+
mol_smarts = Chem.MolToSmarts(qmol)
|
|
550
|
+
error_reason = "atomic num = 0 but smarts contains # primitive (likely due to conditionals)"
|
|
551
|
+
raise SubstructureAtomSmartsInvalid(name, atom.GetSmarts(), mol_smarts, error_reason)
|
|
552
|
+
for bond in qmol.GetBonds():
|
|
553
|
+
check_bond(bond)
|
|
554
|
+
|
|
555
|
+
# ensure unique atom map numbers for each atom
|
|
556
|
+
map_nums = [atom.GetAtomMapNum() for atom in qmol.GetAtoms()]
|
|
557
|
+
unique_map_nums = set(map_nums)
|
|
558
|
+
if len(map_nums) != len(unique_map_nums):
|
|
559
|
+
reason = "non-unique atom map numbers detected"
|
|
560
|
+
raise SubstructureImproperlySpecified(name, reason)
|
|
561
|
+
|
|
562
|
+
# If all checks pass, continue
|
|
563
|
+
return
|
|
564
|
+
|
|
565
|
+
def _prepare_custom_substructures(self, custom_substructures: dict[str, list[str]]):
|
|
566
|
+
"""Adds general atom names to match the format of the amino acid substructure dict
|
|
567
|
+
Parameters
|
|
568
|
+
----------
|
|
569
|
+
custom_substructures
|
|
570
|
+
substructures given with unique names as keys and smarts as values
|
|
571
|
+
Returns
|
|
572
|
+
-------
|
|
573
|
+
prepared_dict
|
|
574
|
+
a dictionary of the same type and format as the predefined toolkit
|
|
575
|
+
substructures (amino acids, etc). Atom names are given the format
|
|
576
|
+
"CSTM_{symbol}", including wildtypes which show as "CSTM_*"
|
|
577
|
+
"""
|
|
578
|
+
from rdkit import Chem
|
|
579
|
+
|
|
580
|
+
prepared_dict = defaultdict[str, dict[str, list[str]]](lambda: defaultdict(list))
|
|
581
|
+
for name, smarts_list in custom_substructures.items():
|
|
582
|
+
for smarts in smarts_list:
|
|
583
|
+
rdmol = Chem.MolFromSmarts(smarts)
|
|
584
|
+
atom_list = [f"CSTM_{atom.GetSymbol()}" for atom in rdmol.GetAtoms()]
|
|
585
|
+
prepared_dict[name][smarts] = atom_list
|
|
586
|
+
return prepared_dict
|
|
587
|
+
|
|
588
|
+
def _polymer_openmm_topology_to_rdmol(self, omm_top, substructure_library):
|
|
589
|
+
"""
|
|
590
|
+
Parameters
|
|
591
|
+
----------
|
|
592
|
+
rdkit_mol
|
|
593
|
+
Currently invalid (bond orders and charge) Molecule
|
|
594
|
+
substructure_library
|
|
595
|
+
A dictionary of substructures. substructure_library[aa_name] = list[tagged SMARTS, list[atom_names]]
|
|
596
|
+
toolkit_registry
|
|
597
|
+
Either a ToolkitRegistry, ToolkitWrapper
|
|
598
|
+
|
|
599
|
+
Returns
|
|
600
|
+
-------
|
|
601
|
+
rdkit_mol
|
|
602
|
+
a copy of the original molecule with charges and bond order added
|
|
603
|
+
|
|
604
|
+
Raises
|
|
605
|
+
------
|
|
606
|
+
MissingChemistryFromPolymerError
|
|
607
|
+
Raised when bonds or atoms in ``rdkit_mol`` are missing from the
|
|
608
|
+
substructure library
|
|
609
|
+
"""
|
|
610
|
+
from copy import deepcopy
|
|
611
|
+
|
|
612
|
+
from rdkit import Chem
|
|
613
|
+
from rdkit.DataStructs.cDataStructs import CreateFromBinaryText
|
|
614
|
+
|
|
615
|
+
already_assigned_nodes: set = set()
|
|
616
|
+
# TODO: We currently assume all single and modify a few
|
|
617
|
+
# Therefore it's hard to know if we've missed any edges...
|
|
618
|
+
# Notably assumes all bonds *between* fragments are single
|
|
619
|
+
already_assigned_edges = set()
|
|
620
|
+
|
|
621
|
+
# Keeping track of which atoms are matched where will help us with error
|
|
622
|
+
# messages
|
|
623
|
+
matches = defaultdict(list)
|
|
624
|
+
residue_name_ids = defaultdict(list)
|
|
625
|
+
query_nums = defaultdict(list)
|
|
626
|
+
query_ids = defaultdict(list)
|
|
627
|
+
|
|
628
|
+
rdkit_mol = self._get_connectivity_from_openmm_top(omm_top)
|
|
629
|
+
mol = Chem.Mol(rdkit_mol)
|
|
630
|
+
# Get a tuple of tuples of atom indices belonging to separate molecules in this RDMol
|
|
631
|
+
# (note that this rdmol may actually be a solvated protein-ligand system)
|
|
632
|
+
sorted_mol_frags = [tuple(sorted(i)) for i in Chem.GetMolFrags(mol)]
|
|
633
|
+
|
|
634
|
+
query_number = 0
|
|
635
|
+
for res_idx, res_name in enumerate(substructure_library):
|
|
636
|
+
# TODO: This is a hack for the moment since we don't have a more sophisticated way to resolve clashes
|
|
637
|
+
# so it just does the biggest substructures first
|
|
638
|
+
# NOTE: If this changes, MissingChemistryFromPolymerError needs to be updated too
|
|
639
|
+
sorted_substructure_smarts = sorted(substructure_library[res_name], key=len, reverse=True)
|
|
640
|
+
|
|
641
|
+
for substructure_smarts in sorted_substructure_smarts:
|
|
642
|
+
# this is the molecule as defined in template.
|
|
643
|
+
# ref is used to execute queries and find substructures but is difficult to
|
|
644
|
+
# sanitize/calculate valence (has query atoms)
|
|
645
|
+
ref = Chem.MolFromSmarts(substructure_smarts)
|
|
646
|
+
ref_info = deepcopy(ref)
|
|
647
|
+
# ref must be sanitized to calculate aromaticity
|
|
648
|
+
# run sanitization to calculate Implcit H counts to later aromaticity assignment
|
|
649
|
+
Chem.SanitizeMol(
|
|
650
|
+
ref_info,
|
|
651
|
+
Chem.SANITIZE_NONE,
|
|
652
|
+
)
|
|
653
|
+
|
|
654
|
+
# set aromaticity for ref to avoid ambiguous chemical assignments from rotating or
|
|
655
|
+
# flipping aromatic rings.
|
|
656
|
+
# The entire molecule is kekulized after
|
|
657
|
+
Chem.SetAromaticity(ref_info, Chem.AromaticityModel.AROMATICITY_MDL)
|
|
658
|
+
|
|
659
|
+
# then create a looser definition for pattern matching...
|
|
660
|
+
# be lax about double bonds and chirality
|
|
661
|
+
fuzzy, neighbor_idxs = self._fuzzy_query(ref)
|
|
662
|
+
# It's important that we do the substructure search on `rdkit_mol`, but the chemical
|
|
663
|
+
# info is added to `mol`. If we use the same rdkit molecule for search AND info addition,
|
|
664
|
+
# then single bonds may no longer be present for subsequent overlapping matches.
|
|
665
|
+
sym_atoms = []
|
|
666
|
+
sym_bonds = []
|
|
667
|
+
|
|
668
|
+
sym_atoms, sym_bonds = self._get_symmetrical_groups(fuzzy, ref)
|
|
669
|
+
|
|
670
|
+
for full_match in rdkit_mol.GetSubstructMatches(fuzzy, maxMatches=0):
|
|
671
|
+
# Keep track of all residue names that have been assigned to
|
|
672
|
+
# each atom, for use in generating a useful error message later
|
|
673
|
+
match_ids = [
|
|
674
|
+
(query_id, mol_id)
|
|
675
|
+
for query_id, mol_id in enumerate(full_match)
|
|
676
|
+
if query_id not in neighbor_idxs
|
|
677
|
+
]
|
|
678
|
+
match = list(zip(*match_ids))[1] # get the molecule ids without the corresponding query ids.
|
|
679
|
+
# ^^ matches return match ids in the order that they appear in the query.
|
|
680
|
+
# The code above filters neighboring (*) atoms.
|
|
681
|
+
|
|
682
|
+
# Unique molecule matches should only apply if they match entire molecule
|
|
683
|
+
if res_name == "UNIQUE_MOLECULE":
|
|
684
|
+
sorted_match = tuple(sorted(match))
|
|
685
|
+
if sorted_match not in sorted_mol_frags:
|
|
686
|
+
continue
|
|
687
|
+
|
|
688
|
+
# assign chemical info and check all overlapping substructures for ambiguous/conflicting
|
|
689
|
+
# chemical info.
|
|
690
|
+
for atom_i, j in zip(ref_info.GetAtoms(), full_match):
|
|
691
|
+
if atom_i.GetAtomicNum() == 0: # ignore neighboring atoms
|
|
692
|
+
continue
|
|
693
|
+
atom_j = mol.GetAtomWithIdx(j)
|
|
694
|
+
# error checking for overlapping substructures with priority. Enforce that no ambiguous
|
|
695
|
+
# chemical assignments are made.
|
|
696
|
+
if j in already_assigned_nodes: # if overlapping with previous match
|
|
697
|
+
if (
|
|
698
|
+
atom_i.GetFormalCharge() != atom_j.GetFormalCharge()
|
|
699
|
+
and atom_i.GetIdx() not in sym_atoms
|
|
700
|
+
):
|
|
701
|
+
error_reason = (
|
|
702
|
+
f"Formal charge of new query ({atom_i.GetFormalCharge()}) does "
|
|
703
|
+
f"not match the formal charge of previous query "
|
|
704
|
+
f"({atom_j.GetFormalCharge()})"
|
|
705
|
+
)
|
|
706
|
+
raise AmbiguousAtomChemicalAssignment(
|
|
707
|
+
res_name,
|
|
708
|
+
atom_j.GetIdx(),
|
|
709
|
+
atom_i.GetIdx(),
|
|
710
|
+
error_reason,
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
atom_j.SetFormalCharge(atom_i.GetFormalCharge())
|
|
714
|
+
|
|
715
|
+
already_assigned_nodes.update(match)
|
|
716
|
+
|
|
717
|
+
for b in ref_info.GetBonds():
|
|
718
|
+
ref_bond_ids = tuple(sorted([b.GetBeginAtomIdx(), b.GetEndAtomIdx()]))
|
|
719
|
+
x = full_match[b.GetBeginAtomIdx()]
|
|
720
|
+
y = full_match[b.GetEndAtomIdx()]
|
|
721
|
+
b2 = mol.GetBondBetweenAtoms(x, y)
|
|
722
|
+
bond_ids = tuple(sorted([x, y]))
|
|
723
|
+
|
|
724
|
+
# error checking of overlapping bonds. If substructures with priority disagree on the
|
|
725
|
+
# bond order, raise exception
|
|
726
|
+
if bond_ids in already_assigned_edges: # if overlapping with previous match
|
|
727
|
+
if b.GetBondType() != b2.GetBondType() and ref_bond_ids not in sym_bonds:
|
|
728
|
+
error_reason = (
|
|
729
|
+
f"Bond order of new query ({b.GetBondType()}) does not match the "
|
|
730
|
+
f"bond order of previous query ({b2.GetBondType()})"
|
|
731
|
+
)
|
|
732
|
+
query_bond = tuple(sorted([b.GetBeginAtomIdx(), b.GetEndAtomIdx()]))
|
|
733
|
+
raise AmbiguousBondChemicalAssignment(res_name, bond_ids, query_bond, error_reason)
|
|
734
|
+
b2.SetBondType(b.GetBondType())
|
|
735
|
+
already_assigned_edges.add(bond_ids)
|
|
736
|
+
|
|
737
|
+
for query_id, mol_id in match_ids:
|
|
738
|
+
matches[mol_id].append(res_name)
|
|
739
|
+
residue_name_ids[mol_id].append(
|
|
740
|
+
res_idx
|
|
741
|
+
) # save the minimum amount of information between the res_name and query ids
|
|
742
|
+
query_nums[mol_id].append(query_number)
|
|
743
|
+
query_ids[mol_id].append(
|
|
744
|
+
query_id
|
|
745
|
+
) # that may allow someone to reproduce or fully investigate the matches
|
|
746
|
+
query_number += 1
|
|
747
|
+
|
|
748
|
+
unassigned_atoms = sorted(set(range(rdkit_mol.GetNumAtoms())) - already_assigned_nodes)
|
|
749
|
+
all_bonds = set(
|
|
750
|
+
[tuple(sorted([bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()])) for bond in rdkit_mol.GetBonds()]
|
|
751
|
+
)
|
|
752
|
+
unassigned_bonds = sorted(all_bonds - already_assigned_edges)
|
|
753
|
+
|
|
754
|
+
if unassigned_atoms or unassigned_bonds:
|
|
755
|
+
# Some advanced error reporting needs to interpret the substructure smarts to do things like
|
|
756
|
+
# compare atom counts. Since OFFTK doesn't have a native class to hold fragments, we convert
|
|
757
|
+
# the smarts into a sorted list of symbols to help with generating the error message.
|
|
758
|
+
resname_to_symbols_and_atomnames: dict[str, list[tuple]] = dict()
|
|
759
|
+
for resname, smarts_to_atom_names in substructure_library.items():
|
|
760
|
+
resname_to_symbols_and_atomnames[resname] = list()
|
|
761
|
+
for smarts, atom_names in smarts_to_atom_names.items():
|
|
762
|
+
ref = Chem.MolFromSmarts(smarts)
|
|
763
|
+
symbols = sorted(
|
|
764
|
+
[SYMBOLS[atom.GetAtomicNum()] for atom in ref.GetAtoms() if atom.GetAtomicNum() > 0]
|
|
765
|
+
)
|
|
766
|
+
resname_to_symbols_and_atomnames[resname].append((symbols, atom_names))
|
|
767
|
+
|
|
768
|
+
raise UnassignedChemistryInPDBError(
|
|
769
|
+
substructure_library=resname_to_symbols_and_atomnames,
|
|
770
|
+
omm_top=omm_top,
|
|
771
|
+
unassigned_atoms=unassigned_atoms,
|
|
772
|
+
unassigned_bonds=unassigned_bonds,
|
|
773
|
+
matches=matches,
|
|
774
|
+
)
|
|
775
|
+
|
|
776
|
+
# set some properties to later remember what matches were made
|
|
777
|
+
for atom in mol.GetAtoms():
|
|
778
|
+
atom_id = atom.GetIdx()
|
|
779
|
+
res_ids = residue_name_ids[atom_id]
|
|
780
|
+
q_nums = query_nums[atom_id]
|
|
781
|
+
q_ids = query_ids[atom_id]
|
|
782
|
+
atom.SetExplicitBitVectProp(
|
|
783
|
+
"res_ids",
|
|
784
|
+
CreateFromBinaryText(np.array(res_ids, dtype=np.uint64).tobytes()),
|
|
785
|
+
)
|
|
786
|
+
atom.SetExplicitBitVectProp(
|
|
787
|
+
"query_nums",
|
|
788
|
+
CreateFromBinaryText(np.array(q_nums, dtype=np.uint64).tobytes()),
|
|
789
|
+
)
|
|
790
|
+
atom.SetExplicitBitVectProp(
|
|
791
|
+
"query_ids",
|
|
792
|
+
CreateFromBinaryText(np.array(q_ids, dtype=np.uint64).tobytes()),
|
|
793
|
+
)
|
|
794
|
+
|
|
795
|
+
return mol
|
|
796
|
+
|
|
797
|
+
def _get_connectivity_from_openmm_top(self, omm_top):
|
|
798
|
+
from rdkit import Chem
|
|
799
|
+
|
|
800
|
+
# convert openmm topology to rdkit Molecule
|
|
801
|
+
# all bonds initially SINGLE, all charge initially neutral
|
|
802
|
+
rwmol = Chem.RWMol()
|
|
803
|
+
for atom in omm_top.atoms():
|
|
804
|
+
idx = rwmol.AddAtom(Chem.Atom(atom.element.atomic_number))
|
|
805
|
+
res = Chem.AtomPDBResidueInfo()
|
|
806
|
+
res.SetResidueName(atom.residue.name)
|
|
807
|
+
res.SetResidueNumber(int(atom.residue.id))
|
|
808
|
+
res.SetChainId(atom.residue.chain.id)
|
|
809
|
+
rwatom = rwmol.GetAtomWithIdx(idx)
|
|
810
|
+
rwatom.SetPDBResidueInfo(res)
|
|
811
|
+
# we're fully explicit
|
|
812
|
+
for atom in rwmol.GetAtoms():
|
|
813
|
+
atom.SetNoImplicit(True)
|
|
814
|
+
for bond in omm_top.bonds():
|
|
815
|
+
rwmol.AddBond(bond[0].index, bond[1].index, Chem.BondType.SINGLE)
|
|
816
|
+
|
|
817
|
+
return rwmol
|
|
818
|
+
|
|
819
|
+
def _get_symmetrical_groups(self, fuzzy_query, substruct):
|
|
820
|
+
"""Returns those atoms and bonds whose chemical information
|
|
821
|
+
is ambiguous due to resonance forms or symmetrical groups. Conflicts
|
|
822
|
+
in assignment are ignored for these atoms when two queries have the same
|
|
823
|
+
atoms in resonance/symmetry"""
|
|
824
|
+
from copy import deepcopy
|
|
825
|
+
|
|
826
|
+
from rdkit import Chem
|
|
827
|
+
|
|
828
|
+
qmol = deepcopy(fuzzy_query)
|
|
829
|
+
for atom in qmol.GetAtoms(): # reset queries and map numbers
|
|
830
|
+
atom.SetAtomMapNum(atom.GetIdx()) # reorder atom map nums to later recover ids
|
|
831
|
+
|
|
832
|
+
qmol = Chem.RemoveAllHs(qmol, sanitize=False)
|
|
833
|
+
idx_to_map_num = dict([(a.GetIdx(), a.GetAtomMapNum()) for a in qmol.GetAtoms()])
|
|
834
|
+
automorphs = fuzzy_query.GetSubstructMatches(qmol, uniquify=0)
|
|
835
|
+
ambiguous_bonds = []
|
|
836
|
+
ambiguous_atoms = []
|
|
837
|
+
for automorph in automorphs:
|
|
838
|
+
# check for conflicting chemical information
|
|
839
|
+
automorph = dict(
|
|
840
|
+
[(idx_to_map_num[idx], a) for idx, a in enumerate(list(automorph)) if idx_to_map_num[idx] != a]
|
|
841
|
+
) # only care about cases of different matching
|
|
842
|
+
|
|
843
|
+
for atom_iso, new_atom_iso in automorph.items():
|
|
844
|
+
atom = substruct.GetAtomWithIdx(atom_iso)
|
|
845
|
+
new_atom = substruct.GetAtomWithIdx(new_atom_iso)
|
|
846
|
+
# new_atom = substruct.GetAtomWithIdx(automorph[atom.GetIdx()])
|
|
847
|
+
if atom.GetFormalCharge() != new_atom.GetFormalCharge():
|
|
848
|
+
if atom.GetIdx() not in ambiguous_atoms:
|
|
849
|
+
ambiguous_atoms.append(atom.GetIdx())
|
|
850
|
+
|
|
851
|
+
for bond in substruct.GetBonds():
|
|
852
|
+
if (
|
|
853
|
+
bond.GetBeginAtom().GetAtomicNum() == 1 or bond.GetEndAtom().GetAtomicNum() == 1
|
|
854
|
+
): # we remove Hs for matching so must remove here as well
|
|
855
|
+
continue
|
|
856
|
+
if bond.GetBeginAtomIdx() in automorph or bond.GetEndAtomIdx() in automorph:
|
|
857
|
+
new_bond_begin_idx = automorph.get(bond.GetBeginAtomIdx(), bond.GetBeginAtomIdx())
|
|
858
|
+
new_bond_end_idx = automorph.get(bond.GetEndAtomIdx(), bond.GetEndAtomIdx())
|
|
859
|
+
new_bond = substruct.GetBondBetweenAtoms(new_bond_begin_idx, new_bond_end_idx)
|
|
860
|
+
if bond.GetBondType() != new_bond.GetBondType():
|
|
861
|
+
sym_bond_entry = tuple(sorted([bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()]))
|
|
862
|
+
if sym_bond_entry not in ambiguous_bonds:
|
|
863
|
+
ambiguous_bonds.append(tuple(sorted([bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()])))
|
|
864
|
+
if not ambiguous_bonds:
|
|
865
|
+
ambiguous_atoms = [] # if no ambiguous bonds, there cannot be physically valid sets of ambiguous atoms
|
|
866
|
+
# this is because that would imply that two different simple/graph connectivites can give different
|
|
867
|
+
# formal charges, which is not supported in this implementation and likely not possible outside of
|
|
868
|
+
# exotic transition metal groups
|
|
869
|
+
return ambiguous_atoms, ambiguous_bonds
|
|
870
|
+
|
|
871
|
+
@staticmethod
|
|
872
|
+
def _fuzzy_query(query):
|
|
873
|
+
"""return a copy of Query which is less specific:
|
|
874
|
+
- ignore aromaticity and hybridization of atoms (i.e. [#6] not C)
|
|
875
|
+
- ignore bond orders
|
|
876
|
+
- ignore formal charges
|
|
877
|
+
"""
|
|
878
|
+
from rdkit import Chem
|
|
879
|
+
|
|
880
|
+
# it's tricky from the Python API to properly edit queries,
|
|
881
|
+
# but you can do SetQuery on Atoms/Bonds to edit them quite powerfully
|
|
882
|
+
generic = Chem.MolFromSmarts("**")
|
|
883
|
+
generic_bond = generic.GetBondWithIdx(0)
|
|
884
|
+
|
|
885
|
+
fuzzy = Chem.Mol(query)
|
|
886
|
+
neighbor_idxs = []
|
|
887
|
+
for idx, a in enumerate(fuzzy.GetAtoms()):
|
|
888
|
+
a.SetFormalCharge(0)
|
|
889
|
+
if a.GetAtomicNum() > 0:
|
|
890
|
+
a.SetQuery(Chem.AtomFromSmarts(f"[#{a.GetAtomicNum()}D{a.GetDegree()}]"))
|
|
891
|
+
else:
|
|
892
|
+
a.SetQuery(generic.GetAtomWithIdx(0))
|
|
893
|
+
a.SetNoImplicit(True)
|
|
894
|
+
if a.GetAtomicNum() == 0:
|
|
895
|
+
neighbor_idxs.append(idx)
|
|
896
|
+
for b in fuzzy.GetBonds():
|
|
897
|
+
b.SetIsAromatic(False)
|
|
898
|
+
b.SetBondType(Chem.rdchem.BondType.SINGLE)
|
|
899
|
+
b.SetQuery(generic_bond)
|
|
900
|
+
return fuzzy, neighbor_idxs
|
|
901
|
+
|
|
902
|
+
def _assign_aromaticity_and_stereo_from_3d(self, offmol):
|
|
903
|
+
from rdkit import Chem
|
|
904
|
+
|
|
905
|
+
rdmol = offmol.to_rdkit()
|
|
906
|
+
Chem.SanitizeMol(
|
|
907
|
+
rdmol,
|
|
908
|
+
Chem.SANITIZE_ALL ^ Chem.SANITIZE_ADJUSTHS, # ^ Chem.SANITIZE_SETAROMATICITY,
|
|
909
|
+
)
|
|
910
|
+
Chem.AssignStereochemistryFrom3D(rdmol)
|
|
911
|
+
Chem.Kekulize(rdmol, clearAromaticFlags=True)
|
|
912
|
+
Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_MDL)
|
|
913
|
+
# To get HIS//TRP to get recognized as aromatic, we can use a different aromaticity model
|
|
914
|
+
# Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_DEFAULT)
|
|
915
|
+
|
|
916
|
+
offmol_w_stereo_and_aro = offmol.from_rdkit(rdmol, allow_undefined_stereo=True, hydrogens_are_explicit=True)
|
|
917
|
+
return offmol_w_stereo_and_aro
|
|
918
|
+
|
|
919
|
+
def _process_sdf_supplier(self, sdf_supplier, allow_undefined_stereo, _cls):
|
|
920
|
+
"Helper function to process RDKit molecules from an SDF input source"
|
|
921
|
+
from rdkit import Chem
|
|
922
|
+
|
|
923
|
+
for rdmol in sdf_supplier:
|
|
924
|
+
if rdmol is None:
|
|
925
|
+
continue
|
|
926
|
+
|
|
927
|
+
# Sanitize the molecules (fails on nitro groups)
|
|
928
|
+
try:
|
|
929
|
+
Chem.SanitizeMol(
|
|
930
|
+
rdmol,
|
|
931
|
+
Chem.SANITIZE_ALL ^ Chem.SANITIZE_SETAROMATICITY ^ Chem.SANITIZE_ADJUSTHS,
|
|
932
|
+
)
|
|
933
|
+
Chem.AssignStereochemistryFrom3D(rdmol)
|
|
934
|
+
except ValueError as e:
|
|
935
|
+
logger.warning(rdmol.GetProp("_Name") + " " + str(e))
|
|
936
|
+
continue
|
|
937
|
+
Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_MDL)
|
|
938
|
+
mol = self.from_rdkit(rdmol, allow_undefined_stereo=allow_undefined_stereo, _cls=_cls)
|
|
939
|
+
yield mol
|
|
940
|
+
|
|
941
|
+
def from_file(
|
|
942
|
+
self,
|
|
943
|
+
file_path: str,
|
|
944
|
+
file_format: str,
|
|
945
|
+
allow_undefined_stereo: bool = False,
|
|
946
|
+
_cls=None,
|
|
947
|
+
):
|
|
948
|
+
"""
|
|
949
|
+
Create an openff.toolkit.topology.Molecule from a file using this toolkit.
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
Parameters
|
|
954
|
+
----------
|
|
955
|
+
file_path
|
|
956
|
+
The file to read the molecule from
|
|
957
|
+
file_format
|
|
958
|
+
Format specifier, usually file suffix (eg. 'MOL2', 'SMI')
|
|
959
|
+
Note that not all toolkits support all formats. Check
|
|
960
|
+
ToolkitWrapper.toolkit_file_read_formats for details.
|
|
961
|
+
allow_undefined_stereo
|
|
962
|
+
If false, raises an exception if RDMol contains undefined stereochemistry.
|
|
963
|
+
_cls
|
|
964
|
+
Molecule constructor
|
|
965
|
+
Returns
|
|
966
|
+
-------
|
|
967
|
+
molecules
|
|
968
|
+
a list of Molecule objects is returned.
|
|
969
|
+
|
|
970
|
+
"""
|
|
971
|
+
from rdkit import Chem
|
|
972
|
+
|
|
973
|
+
if isinstance(file_path, pathlib.Path):
|
|
974
|
+
file_path: str = file_path.as_posix() # type: ignore[no-redef]
|
|
975
|
+
|
|
976
|
+
file_format = normalize_file_format(file_format)
|
|
977
|
+
|
|
978
|
+
mols = list()
|
|
979
|
+
if (file_format == "MOL") or (file_format == "SDF"):
|
|
980
|
+
sdf_supplier = Chem.ForwardSDMolSupplier(file_path, removeHs=False, sanitize=False, strictParsing=True)
|
|
981
|
+
mols.extend(
|
|
982
|
+
self._process_sdf_supplier(
|
|
983
|
+
sdf_supplier,
|
|
984
|
+
allow_undefined_stereo=allow_undefined_stereo,
|
|
985
|
+
_cls=_cls,
|
|
986
|
+
)
|
|
987
|
+
)
|
|
988
|
+
|
|
989
|
+
elif file_format == "SMI":
|
|
990
|
+
# TODO: We have to do some special stuff when we import SMILES (currently
|
|
991
|
+
# just adding H's, but could get fancier in the future). It might be
|
|
992
|
+
# worthwhile to parse the SMILES file ourselves and pass each SMILES
|
|
993
|
+
# through the from_smiles function instead
|
|
994
|
+
for rdmol in Chem.SmilesMolSupplier(file_path, titleLine=False):
|
|
995
|
+
if rdmol is None:
|
|
996
|
+
# Skip any lines that could not be processed.
|
|
997
|
+
# This is consistent with the SDF reader and with
|
|
998
|
+
# the OpenEye toolkit wrapper.
|
|
999
|
+
continue
|
|
1000
|
+
rdmol = Chem.AddHs(rdmol)
|
|
1001
|
+
mol = self.from_rdkit(rdmol, allow_undefined_stereo=allow_undefined_stereo, _cls=_cls)
|
|
1002
|
+
mols.append(mol)
|
|
1003
|
+
|
|
1004
|
+
elif file_format == "PDB":
|
|
1005
|
+
raise MoleculeParseError(
|
|
1006
|
+
"RDKit can not safely read PDBs on their own. Information about bond order "
|
|
1007
|
+
"and aromaticity is likely to be lost. To read a PDB using RDKit use "
|
|
1008
|
+
"Molecule.from_pdb_and_smiles()"
|
|
1009
|
+
)
|
|
1010
|
+
# TODO: See if we can implement PDB+mol/smi combinations to get complete bond information.
|
|
1011
|
+
# testing to see if we can make a molecule from smiles and then use the PDB
|
|
1012
|
+
# conformer as the geometry and just reorder the molecule
|
|
1013
|
+
# https://github.com/openforcefield/openff-toolkit/issues/121
|
|
1014
|
+
# rdmol = Chem.MolFromPDBFile(file_path, removeHs=False)
|
|
1015
|
+
# mol = Molecule.from_rdkit(rdmol, _cls=_cls)
|
|
1016
|
+
# mols.append(mol)
|
|
1017
|
+
# TODO: Add SMI, TDT(?) support
|
|
1018
|
+
|
|
1019
|
+
else:
|
|
1020
|
+
raise ValueError(f"Unsupported file format: {file_format}")
|
|
1021
|
+
|
|
1022
|
+
return mols
|
|
1023
|
+
|
|
1024
|
+
def from_file_obj(
|
|
1025
|
+
self,
|
|
1026
|
+
file_obj,
|
|
1027
|
+
file_format: str,
|
|
1028
|
+
allow_undefined_stereo: bool = False,
|
|
1029
|
+
_cls=None,
|
|
1030
|
+
):
|
|
1031
|
+
"""
|
|
1032
|
+
Return an openff.toolkit.topology.Molecule from a file-like object using this toolkit.
|
|
1033
|
+
|
|
1034
|
+
A file-like object is an object with a ".read()" method.
|
|
1035
|
+
|
|
1036
|
+
.. warning :: This API is experimental and subject to change.
|
|
1037
|
+
|
|
1038
|
+
Parameters
|
|
1039
|
+
----------
|
|
1040
|
+
file_obj
|
|
1041
|
+
The file-like object to read the molecule from
|
|
1042
|
+
file_format
|
|
1043
|
+
Format specifier, usually file suffix (eg. 'MOL2', 'SMI')
|
|
1044
|
+
Note that not all toolkits support all formats. Check
|
|
1045
|
+
ToolkitWrapper.toolkit_file_read_formats for details.
|
|
1046
|
+
allow_undefined_stereo
|
|
1047
|
+
If false, raises an exception if RDMol contains undefined stereochemistry.
|
|
1048
|
+
_cls
|
|
1049
|
+
Molecule constructor
|
|
1050
|
+
Returns
|
|
1051
|
+
-------
|
|
1052
|
+
molecules
|
|
1053
|
+
a list of Molecule objects is returned.
|
|
1054
|
+
|
|
1055
|
+
"""
|
|
1056
|
+
from rdkit import Chem
|
|
1057
|
+
|
|
1058
|
+
mols = []
|
|
1059
|
+
|
|
1060
|
+
file_format = normalize_file_format(file_format)
|
|
1061
|
+
|
|
1062
|
+
if (file_format == "MOL") or (file_format == "SDF"):
|
|
1063
|
+
# TODO: Iterate over all mols in file_data
|
|
1064
|
+
sdf_supplier = Chem.ForwardSDMolSupplier(file_obj, removeHs=False, sanitize=False, strictParsing=True)
|
|
1065
|
+
mols.extend(
|
|
1066
|
+
self._process_sdf_supplier(
|
|
1067
|
+
sdf_supplier,
|
|
1068
|
+
allow_undefined_stereo=allow_undefined_stereo,
|
|
1069
|
+
_cls=_cls,
|
|
1070
|
+
)
|
|
1071
|
+
)
|
|
1072
|
+
|
|
1073
|
+
elif file_format == "SMI":
|
|
1074
|
+
# There's no good way to create a SmilesMolSuppler from a string
|
|
1075
|
+
# other than to use a temporary file.
|
|
1076
|
+
with tempfile.NamedTemporaryFile(suffix=".smi") as tmpfile:
|
|
1077
|
+
content = file_obj.read()
|
|
1078
|
+
if isinstance(content, str):
|
|
1079
|
+
# Backwards compatibility. Older versions of OpenFF supported
|
|
1080
|
+
# file objects in "t"ext mode, but not file objects
|
|
1081
|
+
# in "b"inary mode. Now we expect all input file objects
|
|
1082
|
+
# to handle binary mode, but don't want to break older code.
|
|
1083
|
+
tmpfile.write(content.encode("utf8"))
|
|
1084
|
+
else:
|
|
1085
|
+
tmpfile.write(content)
|
|
1086
|
+
tmpfile.flush()
|
|
1087
|
+
return self.from_file(
|
|
1088
|
+
tmpfile.name,
|
|
1089
|
+
"SMI",
|
|
1090
|
+
allow_undefined_stereo=allow_undefined_stereo,
|
|
1091
|
+
_cls=_cls,
|
|
1092
|
+
)
|
|
1093
|
+
|
|
1094
|
+
elif file_format == "PDB":
|
|
1095
|
+
raise MoleculeParseError(
|
|
1096
|
+
"RDKit can not safely read PDBs on their own. Information about bond order and aromaticity "
|
|
1097
|
+
"is likely to be lost. To read a PDB using RDKit use Molecule.from_pdb_and_smiles()"
|
|
1098
|
+
)
|
|
1099
|
+
# TODO: See if we can implement PDB+mol/smi combinations to get complete bond information.
|
|
1100
|
+
# https://github.com/openforcefield/openff-toolkit/issues/121
|
|
1101
|
+
# file_data = file_obj.read()
|
|
1102
|
+
# rdmol = Chem.MolFromPDBBlock(file_data)
|
|
1103
|
+
# mol = Molecule.from_rdkit(rdmol, _cls=_cls)
|
|
1104
|
+
# mols.append(mol)
|
|
1105
|
+
|
|
1106
|
+
else:
|
|
1107
|
+
raise ValueError(f"Unsupported file format: {file_format}")
|
|
1108
|
+
# TODO: TDT file support
|
|
1109
|
+
return mols
|
|
1110
|
+
|
|
1111
|
+
def to_file_obj(self, molecule: "Molecule", file_obj, file_format: str):
|
|
1112
|
+
"""
|
|
1113
|
+
Writes an OpenFF Molecule to a file-like object
|
|
1114
|
+
|
|
1115
|
+
Parameters
|
|
1116
|
+
----------
|
|
1117
|
+
molecule
|
|
1118
|
+
The molecule to write
|
|
1119
|
+
file_obj
|
|
1120
|
+
The file-like object to write to
|
|
1121
|
+
file_format
|
|
1122
|
+
The format for writing the molecule data
|
|
1123
|
+
|
|
1124
|
+
Returns
|
|
1125
|
+
-------
|
|
1126
|
+
|
|
1127
|
+
"""
|
|
1128
|
+
from rdkit import Chem
|
|
1129
|
+
|
|
1130
|
+
_TOOLKIT_WRITERS: dict[str, Any] = {
|
|
1131
|
+
"SDF": Chem.SDWriter,
|
|
1132
|
+
"MOL": Chem.SDWriter,
|
|
1133
|
+
"PDB": Chem.PDBWriter,
|
|
1134
|
+
"TDT": Chem.TDTWriter,
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
file_format = normalize_file_format(file_format)
|
|
1138
|
+
_require_text_file_obj(file_obj)
|
|
1139
|
+
|
|
1140
|
+
if file_format == "SMI":
|
|
1141
|
+
# Special case for SMILES
|
|
1142
|
+
smiles = self.to_smiles(molecule)
|
|
1143
|
+
name = molecule.name
|
|
1144
|
+
if name is not None:
|
|
1145
|
+
output_line = f"{smiles} {name}\n"
|
|
1146
|
+
else:
|
|
1147
|
+
output_line = f"{smiles}\n"
|
|
1148
|
+
file_obj.write(output_line)
|
|
1149
|
+
else:
|
|
1150
|
+
try:
|
|
1151
|
+
writer_func = _TOOLKIT_WRITERS[file_format]
|
|
1152
|
+
except KeyError:
|
|
1153
|
+
raise ValueError(f"Unsupported file format: {file_format})") from None
|
|
1154
|
+
rdmol = self.to_rdkit(molecule)
|
|
1155
|
+
writer = writer_func(file_obj)
|
|
1156
|
+
try:
|
|
1157
|
+
writer.write(rdmol)
|
|
1158
|
+
finally:
|
|
1159
|
+
writer.close()
|
|
1160
|
+
|
|
1161
|
+
def to_file(self, molecule: "Molecule", file_path: str, file_format: str):
|
|
1162
|
+
"""
|
|
1163
|
+
Writes an OpenFF Molecule to a file-like object
|
|
1164
|
+
|
|
1165
|
+
Parameters
|
|
1166
|
+
----------
|
|
1167
|
+
molecule
|
|
1168
|
+
The molecule to write
|
|
1169
|
+
file_path
|
|
1170
|
+
The file path to write to
|
|
1171
|
+
file_format
|
|
1172
|
+
The format for writing the molecule data
|
|
1173
|
+
|
|
1174
|
+
Returns
|
|
1175
|
+
------
|
|
1176
|
+
|
|
1177
|
+
"""
|
|
1178
|
+
|
|
1179
|
+
# open a file object and pass to the object writer
|
|
1180
|
+
with open(file_path, "w") as file_obj:
|
|
1181
|
+
self.to_file_obj(molecule=molecule, file_obj=file_obj, file_format=file_format)
|
|
1182
|
+
|
|
1183
|
+
def enumerate_stereoisomers(
|
|
1184
|
+
self,
|
|
1185
|
+
molecule: "Molecule",
|
|
1186
|
+
undefined_only: bool = False,
|
|
1187
|
+
max_isomers: int = 20,
|
|
1188
|
+
rationalise: bool = True,
|
|
1189
|
+
) -> list["Molecule"]:
|
|
1190
|
+
"""
|
|
1191
|
+
Enumerate the stereocenters and bonds of the current molecule.
|
|
1192
|
+
|
|
1193
|
+
Parameters
|
|
1194
|
+
----------
|
|
1195
|
+
molecule
|
|
1196
|
+
The molecule whose state we should enumerate
|
|
1197
|
+
|
|
1198
|
+
undefined_only
|
|
1199
|
+
If we should enumerate all stereocenters and bonds or only those with undefined stereochemistry
|
|
1200
|
+
|
|
1201
|
+
max_isomers
|
|
1202
|
+
The maximum amount of molecules that should be returned
|
|
1203
|
+
|
|
1204
|
+
rationalise
|
|
1205
|
+
If we should try to build and rationalise the molecule to ensure it can exist
|
|
1206
|
+
|
|
1207
|
+
Returns
|
|
1208
|
+
--------
|
|
1209
|
+
molecules
|
|
1210
|
+
A list of openff.toolkit.topology.Molecule instances
|
|
1211
|
+
|
|
1212
|
+
"""
|
|
1213
|
+
from rdkit import Chem
|
|
1214
|
+
from rdkit.Chem.EnumerateStereoisomers import ( # type: ignore[import-untyped]
|
|
1215
|
+
EnumerateStereoisomers,
|
|
1216
|
+
StereoEnumerationOptions,
|
|
1217
|
+
)
|
|
1218
|
+
|
|
1219
|
+
# create the molecule
|
|
1220
|
+
rdmol = self.to_rdkit(molecule=molecule)
|
|
1221
|
+
|
|
1222
|
+
# in case any bonds/centers are missing stereo chem flag it here
|
|
1223
|
+
Chem.AssignStereochemistry(rdmol, cleanIt=True, force=True, flagPossibleStereoCenters=True)
|
|
1224
|
+
Chem.FindPotentialStereoBonds(rdmol)
|
|
1225
|
+
|
|
1226
|
+
# set up the options
|
|
1227
|
+
stereo_opts = StereoEnumerationOptions(
|
|
1228
|
+
tryEmbedding=rationalise,
|
|
1229
|
+
onlyUnassigned=undefined_only,
|
|
1230
|
+
maxIsomers=max_isomers,
|
|
1231
|
+
)
|
|
1232
|
+
|
|
1233
|
+
isomers = tuple(EnumerateStereoisomers(rdmol, options=stereo_opts))
|
|
1234
|
+
|
|
1235
|
+
molecules = []
|
|
1236
|
+
for isomer in isomers:
|
|
1237
|
+
# isomer has CIS/TRANS tags so convert back to E/Z
|
|
1238
|
+
Chem.SetDoubleBondNeighborDirections(isomer)
|
|
1239
|
+
Chem.AssignStereochemistry(isomer, force=True, cleanIt=True)
|
|
1240
|
+
mol = self.from_rdkit(isomer, _cls=molecule.__class__)
|
|
1241
|
+
if mol != molecule:
|
|
1242
|
+
molecules.append(mol)
|
|
1243
|
+
|
|
1244
|
+
return molecules
|
|
1245
|
+
|
|
1246
|
+
def enumerate_tautomers(self, molecule: "Molecule", max_states: int = 20) -> list["Molecule"]:
|
|
1247
|
+
"""
|
|
1248
|
+
Enumerate the possible tautomers of the current molecule.
|
|
1249
|
+
|
|
1250
|
+
Parameters
|
|
1251
|
+
----------
|
|
1252
|
+
molecule
|
|
1253
|
+
The molecule whose state we should enumerate
|
|
1254
|
+
|
|
1255
|
+
max_states
|
|
1256
|
+
The maximum amount of molecules that should be returned
|
|
1257
|
+
|
|
1258
|
+
Returns
|
|
1259
|
+
-------
|
|
1260
|
+
molecules
|
|
1261
|
+
A list of openff.toolkit.topology.Molecule instances not including the input molecule.
|
|
1262
|
+
"""
|
|
1263
|
+
|
|
1264
|
+
from rdkit import Chem
|
|
1265
|
+
from rdkit.Chem.MolStandardize import ( # type: ignore[import-untyped]
|
|
1266
|
+
rdMolStandardize,
|
|
1267
|
+
)
|
|
1268
|
+
|
|
1269
|
+
enumerator = rdMolStandardize.TautomerEnumerator()
|
|
1270
|
+
enumerator.SetMaxTautomers(max_states)
|
|
1271
|
+
rdmol = Chem.RemoveHs(molecule.to_rdkit())
|
|
1272
|
+
|
|
1273
|
+
tautomers = enumerator.Enumerate(rdmol)
|
|
1274
|
+
|
|
1275
|
+
# make a list of OpenFF molecules excluding the input molecule
|
|
1276
|
+
molecules = []
|
|
1277
|
+
for taut in tautomers:
|
|
1278
|
+
taut_hs = Chem.AddHs(taut)
|
|
1279
|
+
mol = self.from_smiles(Chem.MolToSmiles(taut_hs), allow_undefined_stereo=True)
|
|
1280
|
+
if mol != molecule:
|
|
1281
|
+
molecules.append(mol)
|
|
1282
|
+
|
|
1283
|
+
return molecules[:max_states]
|
|
1284
|
+
|
|
1285
|
+
def canonical_order_atoms(self, molecule: "Molecule") -> "Molecule":
|
|
1286
|
+
"""
|
|
1287
|
+
Canonical order the atoms in the molecule using the RDKit.
|
|
1288
|
+
|
|
1289
|
+
Parameters
|
|
1290
|
+
----------
|
|
1291
|
+
molecule
|
|
1292
|
+
The input molecule
|
|
1293
|
+
|
|
1294
|
+
Returns
|
|
1295
|
+
-------
|
|
1296
|
+
molecule
|
|
1297
|
+
The input molecule, with canonically-indexed atoms and bonds.
|
|
1298
|
+
"""
|
|
1299
|
+
|
|
1300
|
+
from rdkit import Chem
|
|
1301
|
+
|
|
1302
|
+
rdmol = self.to_rdkit(molecule)
|
|
1303
|
+
|
|
1304
|
+
# get the canonical ordering with hydrogens first
|
|
1305
|
+
# this is the default behaviour of RDKit
|
|
1306
|
+
atom_order = list(Chem.CanonicalRankAtoms(rdmol, breakTies=True))
|
|
1307
|
+
|
|
1308
|
+
heavy_atoms = rdmol.GetNumHeavyAtoms()
|
|
1309
|
+
hydrogens = rdmol.GetNumAtoms() - heavy_atoms
|
|
1310
|
+
|
|
1311
|
+
# now go through and change the rankings to get the heavy atoms first if hydrogens are present
|
|
1312
|
+
if hydrogens != 0:
|
|
1313
|
+
for i in range(len(atom_order)):
|
|
1314
|
+
if rdmol.GetAtomWithIdx(i).GetAtomicNum() != 1:
|
|
1315
|
+
atom_order[i] -= hydrogens
|
|
1316
|
+
else:
|
|
1317
|
+
atom_order[i] += heavy_atoms
|
|
1318
|
+
|
|
1319
|
+
# make an atom mapping from the atom_order and remap the molecule
|
|
1320
|
+
atom_mapping = dict((i, rank) for i, rank in enumerate(atom_order))
|
|
1321
|
+
|
|
1322
|
+
return molecule.remap(atom_mapping, current_to_new=True)
|
|
1323
|
+
|
|
1324
|
+
def to_smiles(
|
|
1325
|
+
self,
|
|
1326
|
+
molecule: "Molecule",
|
|
1327
|
+
isomeric: bool = True,
|
|
1328
|
+
explicit_hydrogens: bool = True,
|
|
1329
|
+
mapped: bool = False,
|
|
1330
|
+
):
|
|
1331
|
+
"""
|
|
1332
|
+
Uses the RDKit toolkit to convert a Molecule into a SMILES string.
|
|
1333
|
+
A partially mapped smiles can also be generated for atoms of interest by supplying
|
|
1334
|
+
an `atom_map` to the properties dictionary.
|
|
1335
|
+
|
|
1336
|
+
Parameters
|
|
1337
|
+
----------
|
|
1338
|
+
molecule
|
|
1339
|
+
The molecule to convert into a SMILES.
|
|
1340
|
+
isomeric
|
|
1341
|
+
return an isomeric smiles
|
|
1342
|
+
explicit_hydrogens
|
|
1343
|
+
return a smiles string containing all hydrogens explicitly
|
|
1344
|
+
mapped
|
|
1345
|
+
return a explicit hydrogen mapped smiles, the atoms to be mapped can be controlled by
|
|
1346
|
+
supplying an atom map into the properties dictionary. If no mapping is passed all
|
|
1347
|
+
atoms will be mapped in order, else an atom map dictionary from the current atom
|
|
1348
|
+
index to the map id should be supplied with no duplicates. The map ids (values) should
|
|
1349
|
+
start from 0 or 1.
|
|
1350
|
+
|
|
1351
|
+
Returns
|
|
1352
|
+
-------
|
|
1353
|
+
smiles
|
|
1354
|
+
The SMILES of the input molecule.
|
|
1355
|
+
"""
|
|
1356
|
+
from rdkit import Chem
|
|
1357
|
+
|
|
1358
|
+
rdmol = self.to_rdkit(molecule)
|
|
1359
|
+
|
|
1360
|
+
if not explicit_hydrogens:
|
|
1361
|
+
# remove the hydrogens from the molecule
|
|
1362
|
+
rdmol = Chem.RemoveHs(rdmol)
|
|
1363
|
+
|
|
1364
|
+
if mapped:
|
|
1365
|
+
assert explicit_hydrogens is True, (
|
|
1366
|
+
"Mapped smiles require all hydrogens and stereochemistry to be defined to retain order"
|
|
1367
|
+
)
|
|
1368
|
+
|
|
1369
|
+
# if we only want to map specific atoms check for an atom map
|
|
1370
|
+
atom_map = molecule._properties.get("atom_map", None)
|
|
1371
|
+
if atom_map is not None:
|
|
1372
|
+
# make sure there are no repeated indices
|
|
1373
|
+
map_ids = set(atom_map.values())
|
|
1374
|
+
if len(map_ids) < len(atom_map):
|
|
1375
|
+
atom_map = None
|
|
1376
|
+
elif 0 in atom_map.values():
|
|
1377
|
+
# we need to increment the map index
|
|
1378
|
+
for atom, map in atom_map.items():
|
|
1379
|
+
atom_map[atom] = map + 1
|
|
1380
|
+
|
|
1381
|
+
if atom_map is None:
|
|
1382
|
+
# now we need to add the indexing to the rdmol to get it in the smiles
|
|
1383
|
+
for atom in rdmol.GetAtoms():
|
|
1384
|
+
# the mapping must start from 1, as RDKit uses 0 to represent no mapping.
|
|
1385
|
+
atom.SetAtomMapNum(atom.GetIdx() + 1)
|
|
1386
|
+
else:
|
|
1387
|
+
for atom in rdmol.GetAtoms():
|
|
1388
|
+
try:
|
|
1389
|
+
# try to set the atom map
|
|
1390
|
+
map_idx = atom_map[atom.GetIdx()]
|
|
1391
|
+
atom.SetAtomMapNum(map_idx)
|
|
1392
|
+
except KeyError:
|
|
1393
|
+
continue
|
|
1394
|
+
|
|
1395
|
+
return Chem.MolToSmiles(rdmol, isomericSmiles=isomeric, allHsExplicit=explicit_hydrogens)
|
|
1396
|
+
|
|
1397
|
+
def from_smiles(
|
|
1398
|
+
self,
|
|
1399
|
+
smiles: str,
|
|
1400
|
+
hydrogens_are_explicit: bool = False,
|
|
1401
|
+
allow_undefined_stereo: bool = False,
|
|
1402
|
+
_cls=None,
|
|
1403
|
+
name: str = "",
|
|
1404
|
+
):
|
|
1405
|
+
"""
|
|
1406
|
+
Create a Molecule from a SMILES string using the RDKit toolkit.
|
|
1407
|
+
|
|
1408
|
+
.. warning :: This API is experimental and subject to change.
|
|
1409
|
+
|
|
1410
|
+
Parameters
|
|
1411
|
+
----------
|
|
1412
|
+
smiles
|
|
1413
|
+
The SMILES string to turn into a molecule
|
|
1414
|
+
hydrogens_are_explicit
|
|
1415
|
+
If False, RDKit will perform hydrogen addition using Chem.AddHs
|
|
1416
|
+
allow_undefined_stereo
|
|
1417
|
+
Whether to accept SMILES with undefined stereochemistry. If False,
|
|
1418
|
+
an exception will be raised if a SMILES with undefined stereochemistry
|
|
1419
|
+
is passed into this function.
|
|
1420
|
+
_cls
|
|
1421
|
+
Molecule constructor
|
|
1422
|
+
name
|
|
1423
|
+
An optional name to pass to the _cls constructor
|
|
1424
|
+
|
|
1425
|
+
Returns
|
|
1426
|
+
-------
|
|
1427
|
+
molecule
|
|
1428
|
+
An OpenFF style molecule.
|
|
1429
|
+
|
|
1430
|
+
Raises
|
|
1431
|
+
------
|
|
1432
|
+
RadicalsNotSupportedError
|
|
1433
|
+
"""
|
|
1434
|
+
from rdkit import Chem
|
|
1435
|
+
|
|
1436
|
+
rdmol = Chem.MolFromSmiles(smiles, sanitize=False)
|
|
1437
|
+
if rdmol is None:
|
|
1438
|
+
raise SMILESParseError("Unable to parse the SMILES string")
|
|
1439
|
+
|
|
1440
|
+
# strip the atom map from the molecule if it has one
|
|
1441
|
+
# so we don't affect the sterochemistry tags
|
|
1442
|
+
for atom in rdmol.GetAtoms():
|
|
1443
|
+
if atom.GetAtomMapNum() != 0:
|
|
1444
|
+
# set the map back to zero but hide the index in the atom prop data
|
|
1445
|
+
atom.SetProp("_map_idx", str(atom.GetAtomMapNum()))
|
|
1446
|
+
# set it back to zero
|
|
1447
|
+
atom.SetAtomMapNum(0)
|
|
1448
|
+
|
|
1449
|
+
# Chem.SanitizeMol calls updatePropertyCache so we don't need to call it ourselves
|
|
1450
|
+
# https://www.rdkit.org/docs/cppapi/namespaceRDKit_1_1MolOps.html#a8d831787aaf2d65d9920c37b25b476f5
|
|
1451
|
+
Chem.SanitizeMol(
|
|
1452
|
+
rdmol,
|
|
1453
|
+
Chem.SANITIZE_ALL ^ Chem.SANITIZE_ADJUSTHS ^ Chem.SANITIZE_SETAROMATICITY,
|
|
1454
|
+
)
|
|
1455
|
+
Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_MDL)
|
|
1456
|
+
|
|
1457
|
+
# Chem.MolFromSmiles adds bond directions (i.e. ENDDOWNRIGHT/ENDUPRIGHT), but
|
|
1458
|
+
# doesn't set bond.GetStereo(). We need to call AssignStereochemistry for that.
|
|
1459
|
+
Chem.AssignStereochemistry(rdmol)
|
|
1460
|
+
|
|
1461
|
+
# Throw an exception/warning if there is unspecified stereochemistry.
|
|
1462
|
+
if not allow_undefined_stereo:
|
|
1463
|
+
self._detect_undefined_stereo(
|
|
1464
|
+
rdmol,
|
|
1465
|
+
err_msg_prefix="Unable to make OFFMol from SMILES: ",
|
|
1466
|
+
)
|
|
1467
|
+
|
|
1468
|
+
# Add explicit hydrogens if they aren't there already
|
|
1469
|
+
if not hydrogens_are_explicit:
|
|
1470
|
+
rdmol = Chem.AddHs(rdmol)
|
|
1471
|
+
elif hydrogens_are_explicit:
|
|
1472
|
+
for atom_idx in range(rdmol.GetNumAtoms()):
|
|
1473
|
+
atom = rdmol.GetAtomWithIdx(atom_idx)
|
|
1474
|
+
if atom.GetNumImplicitHs() != 0:
|
|
1475
|
+
raise ValueError(
|
|
1476
|
+
f"'hydrogens_are_explicit' was specified as True, but RDKit toolkit interpreted "
|
|
1477
|
+
f"SMILES '{smiles}' as having implicit hydrogen. If this SMILES is intended to "
|
|
1478
|
+
f"express all explicit hydrogens in the molecule, then you should construct the "
|
|
1479
|
+
f"desired molecule as an RDMol with no implicit hydrogens, and then use "
|
|
1480
|
+
f"Molecule.from_rdkit() to create the desired OFFMol."
|
|
1481
|
+
)
|
|
1482
|
+
# Issue #936 and #1696: GetNumExplicitHs() counts the number of hydrogens that are
|
|
1483
|
+
# explicitly in the string but not present in the graph. This criteria would apply to
|
|
1484
|
+
# hydrogens inside the brackets descibing a heavy atom, e.g. [NH+].
|
|
1485
|
+
# https://www.rdkit.org/docs/Cookbook.html#explicit-valence-and-number-of-hydrogens
|
|
1486
|
+
# This method is also used in GetTotalNumHs, which returns
|
|
1487
|
+
# GetNumImplicitHs() + GetNumExplicitHs() + Optionally the number of
|
|
1488
|
+
# neighboring hydrogens in the molecular graph.
|
|
1489
|
+
# (see the cookbook link above for more details)
|
|
1490
|
+
elif atom.GetNumExplicitHs() != 0:
|
|
1491
|
+
raise ValueError(
|
|
1492
|
+
"'hydrogens_are_explicit' was specified as True, but the RDKit wrapper interpreted "
|
|
1493
|
+
f"the following SMILES as having some nonexplicit hydrogens (e.g., [NH+]): '{smiles}'\n"
|
|
1494
|
+
"If this SMILES is intended to express all explicit hydrogens in the molecule, then either: \n"
|
|
1495
|
+
"1) Replace instances of implicit Hs (ex. `[NH+]` with `[N+]([H])` to make "
|
|
1496
|
+
"the hydrogen explicit, or\n"
|
|
1497
|
+
"2) construct the desired molecule as an RDMol with no implicit hydrogens, "
|
|
1498
|
+
"and then use Molecule.from_rdkit() to create the desired OFFMol."
|
|
1499
|
+
)
|
|
1500
|
+
|
|
1501
|
+
molecule = self.from_rdkit(
|
|
1502
|
+
rdmol,
|
|
1503
|
+
_cls=_cls,
|
|
1504
|
+
allow_undefined_stereo=allow_undefined_stereo,
|
|
1505
|
+
hydrogens_are_explicit=hydrogens_are_explicit,
|
|
1506
|
+
)
|
|
1507
|
+
molecule.name = name
|
|
1508
|
+
return molecule
|
|
1509
|
+
|
|
1510
|
+
def from_inchi(
|
|
1511
|
+
self,
|
|
1512
|
+
inchi: str,
|
|
1513
|
+
allow_undefined_stereo: bool = False,
|
|
1514
|
+
_cls=None,
|
|
1515
|
+
name: str = "",
|
|
1516
|
+
):
|
|
1517
|
+
"""
|
|
1518
|
+
Construct a Molecule from a InChI representation
|
|
1519
|
+
|
|
1520
|
+
Parameters
|
|
1521
|
+
----------
|
|
1522
|
+
inchi
|
|
1523
|
+
The InChI representation of the molecule.
|
|
1524
|
+
|
|
1525
|
+
allow_undefined_stereo
|
|
1526
|
+
Whether to accept InChI with undefined stereochemistry. If False,
|
|
1527
|
+
an exception will be raised if a InChI with undefined stereochemistry
|
|
1528
|
+
is passed into this function.
|
|
1529
|
+
|
|
1530
|
+
_cls
|
|
1531
|
+
Molecule constructor
|
|
1532
|
+
|
|
1533
|
+
Returns
|
|
1534
|
+
-------
|
|
1535
|
+
molecule
|
|
1536
|
+
"""
|
|
1537
|
+
|
|
1538
|
+
from rdkit import Chem
|
|
1539
|
+
|
|
1540
|
+
# this seems to always remove the hydrogens
|
|
1541
|
+
rdmol = Chem.MolFromInchi(inchi, sanitize=False, removeHs=False)
|
|
1542
|
+
|
|
1543
|
+
# try and catch an InChI parsing error
|
|
1544
|
+
if rdmol is None:
|
|
1545
|
+
raise InChIParseError(
|
|
1546
|
+
f"There was an issue parsing the InChI string ({inchi}), please check and try again."
|
|
1547
|
+
)
|
|
1548
|
+
|
|
1549
|
+
# process the molecule
|
|
1550
|
+
# TODO do we need this with inchi?
|
|
1551
|
+
rdmol.UpdatePropertyCache(strict=False)
|
|
1552
|
+
Chem.SanitizeMol(
|
|
1553
|
+
rdmol,
|
|
1554
|
+
Chem.SANITIZE_ALL ^ Chem.SANITIZE_ADJUSTHS ^ Chem.SANITIZE_SETAROMATICITY,
|
|
1555
|
+
)
|
|
1556
|
+
Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_MDL)
|
|
1557
|
+
|
|
1558
|
+
# add hydrogens back here
|
|
1559
|
+
rdmol = Chem.AddHs(rdmol)
|
|
1560
|
+
|
|
1561
|
+
molecule = self.from_rdkit(rdmol, allow_undefined_stereo=allow_undefined_stereo, _cls=_cls)
|
|
1562
|
+
molecule.name = name
|
|
1563
|
+
|
|
1564
|
+
return molecule
|
|
1565
|
+
|
|
1566
|
+
def generate_conformers(
|
|
1567
|
+
self,
|
|
1568
|
+
molecule: "Molecule",
|
|
1569
|
+
n_conformers: int = 1,
|
|
1570
|
+
rms_cutoff: Quantity | None = None,
|
|
1571
|
+
clear_existing: bool = True,
|
|
1572
|
+
_cls=None,
|
|
1573
|
+
make_carboxylic_acids_cis: bool = False,
|
|
1574
|
+
):
|
|
1575
|
+
r"""
|
|
1576
|
+
Generate molecule conformers using RDKit.
|
|
1577
|
+
|
|
1578
|
+
.. warning :: This API is experimental and subject to change.
|
|
1579
|
+
|
|
1580
|
+
.. todo ::
|
|
1581
|
+
|
|
1582
|
+
* which parameters should we expose? (or can we implement a general system with \*\*kwargs?)
|
|
1583
|
+
* will the coordinates be returned in the OpenFF Molecule's own indexing system?
|
|
1584
|
+
Or is there a chance that they'll get reindexed when we convert the input into an RDMol?
|
|
1585
|
+
|
|
1586
|
+
Parameters
|
|
1587
|
+
----------
|
|
1588
|
+
molecule
|
|
1589
|
+
The molecule to generate conformers for.
|
|
1590
|
+
n_conformers
|
|
1591
|
+
Maximum number of conformers to generate.
|
|
1592
|
+
rms_cutoff
|
|
1593
|
+
The minimum RMS value at which two conformers are considered redundant and one is deleted.
|
|
1594
|
+
If None, the cutoff is set to 1 Angstrom
|
|
1595
|
+
|
|
1596
|
+
clear_existing
|
|
1597
|
+
Whether to overwrite existing conformers for the molecule.
|
|
1598
|
+
_cls
|
|
1599
|
+
Molecule constructor
|
|
1600
|
+
make_carboxylic_acids_cis
|
|
1601
|
+
Guarantee all conformers have exclusively cis carboxylic acid groups (COOH)
|
|
1602
|
+
by rotating the proton in any trans carboxylic acids 180 degrees around the C-O bond.
|
|
1603
|
+
|
|
1604
|
+
"""
|
|
1605
|
+
from rdkit.Chem import AllChem
|
|
1606
|
+
|
|
1607
|
+
if rms_cutoff is None:
|
|
1608
|
+
rms_cutoff = Quantity(1.0, unit.angstrom)
|
|
1609
|
+
rdmol = self.to_rdkit(molecule)
|
|
1610
|
+
# TODO: This generates way more conformations than omega, given the same
|
|
1611
|
+
# nConfs and RMS threshold. Is there some way to set an energy cutoff as well?
|
|
1612
|
+
first_conformer_generation_status = AllChem.EmbedMultipleConfs(
|
|
1613
|
+
rdmol,
|
|
1614
|
+
numConfs=n_conformers,
|
|
1615
|
+
pruneRmsThresh=rms_cutoff.m_as(unit.angstrom),
|
|
1616
|
+
randomSeed=1,
|
|
1617
|
+
# params=AllChem.ETKDG()
|
|
1618
|
+
)
|
|
1619
|
+
|
|
1620
|
+
if not first_conformer_generation_status:
|
|
1621
|
+
# For some large molecules, conformer generation fails without `useRandomCoords`;
|
|
1622
|
+
# Landrum recommends it https://github.com/rdkit/rdkit/issues/3764#issuecomment-769367489
|
|
1623
|
+
fallback_conformer_generation_status = AllChem.EmbedMultipleConfs(
|
|
1624
|
+
rdmol,
|
|
1625
|
+
numConfs=n_conformers,
|
|
1626
|
+
pruneRmsThresh=rms_cutoff.m_as(unit.angstrom),
|
|
1627
|
+
randomSeed=1,
|
|
1628
|
+
useRandomCoords=True,
|
|
1629
|
+
)
|
|
1630
|
+
|
|
1631
|
+
if not fallback_conformer_generation_status:
|
|
1632
|
+
raise ConformerGenerationError("RDKit conformer generation failed.")
|
|
1633
|
+
|
|
1634
|
+
molecule2 = self.from_rdkit(rdmol, allow_undefined_stereo=True, _cls=molecule.__class__)
|
|
1635
|
+
|
|
1636
|
+
if clear_existing:
|
|
1637
|
+
molecule._conformers = list()
|
|
1638
|
+
|
|
1639
|
+
for conformer in molecule2._conformers:
|
|
1640
|
+
molecule._add_conformer(conformer)
|
|
1641
|
+
|
|
1642
|
+
if make_carboxylic_acids_cis:
|
|
1643
|
+
molecule._make_carboxylic_acids_cis(toolkit_registry=self)
|
|
1644
|
+
|
|
1645
|
+
def assign_partial_charges(
|
|
1646
|
+
self,
|
|
1647
|
+
molecule: "Molecule",
|
|
1648
|
+
partial_charge_method: str | None = None,
|
|
1649
|
+
use_conformers: list[Quantity] | None = None,
|
|
1650
|
+
strict_n_conformers: bool = False,
|
|
1651
|
+
normalize_partial_charges: bool = True,
|
|
1652
|
+
_cls=None,
|
|
1653
|
+
):
|
|
1654
|
+
"""
|
|
1655
|
+
Compute partial charges with RDKit, and assign
|
|
1656
|
+
the new values to the partial_charges attribute.
|
|
1657
|
+
|
|
1658
|
+
.. warning :: This API is experimental and subject to change.
|
|
1659
|
+
|
|
1660
|
+
Parameters
|
|
1661
|
+
----------
|
|
1662
|
+
molecule
|
|
1663
|
+
Molecule for which partial charges are to be computed
|
|
1664
|
+
partial_charge_method
|
|
1665
|
+
The charge model to use. One of ['mmff94', 'gasteiger']. If None, 'mmff94' will be used.
|
|
1666
|
+
|
|
1667
|
+
* 'mmff94': Applies partial charges using the Merck Molecular Force Field
|
|
1668
|
+
(MMFF). This method does not make use of conformers, and hence
|
|
1669
|
+
``use_conformers`` and ``strict_n_conformers`` will not impact
|
|
1670
|
+
the partial charges produced.
|
|
1671
|
+
use_conformers
|
|
1672
|
+
shape (n_atoms, 3) and dimension of distance. Optional, default = None
|
|
1673
|
+
Coordinates to use for partial charge calculation. If None, an appropriate number of
|
|
1674
|
+
conformers will be generated.
|
|
1675
|
+
strict_n_conformers
|
|
1676
|
+
Whether to raise an exception if an invalid number of conformers is provided for
|
|
1677
|
+
the given charge method.
|
|
1678
|
+
If this is False and an invalid number of conformers is found, a warning will be raised.
|
|
1679
|
+
normalize_partial_charges
|
|
1680
|
+
Whether to offset partial charges so that they sum to the total formal charge of the molecule.
|
|
1681
|
+
This is used to prevent accumulation of rounding errors when the partial charge generation method has
|
|
1682
|
+
low precision.
|
|
1683
|
+
_cls
|
|
1684
|
+
Molecule constructor
|
|
1685
|
+
|
|
1686
|
+
Raises
|
|
1687
|
+
------
|
|
1688
|
+
ChargeMethodUnavailableError if the requested charge method can not be handled by this toolkit
|
|
1689
|
+
|
|
1690
|
+
ChargeCalculationError if the charge method is supported by this toolkit, but fails
|
|
1691
|
+
"""
|
|
1692
|
+
|
|
1693
|
+
import numpy as np
|
|
1694
|
+
from rdkit.Chem import AllChem
|
|
1695
|
+
|
|
1696
|
+
if partial_charge_method is None:
|
|
1697
|
+
partial_charge_method = "mmff94"
|
|
1698
|
+
|
|
1699
|
+
partial_charge_method = partial_charge_method.lower()
|
|
1700
|
+
|
|
1701
|
+
if partial_charge_method not in self._supported_charge_methods:
|
|
1702
|
+
raise ChargeMethodUnavailableError(
|
|
1703
|
+
f"partial_charge_method '{partial_charge_method}' is not available from RDKitToolkitWrapper. "
|
|
1704
|
+
f"Available charge methods are {self._supported_charge_methods}"
|
|
1705
|
+
)
|
|
1706
|
+
|
|
1707
|
+
rdkit_molecule = molecule.to_rdkit()
|
|
1708
|
+
charges = None
|
|
1709
|
+
|
|
1710
|
+
if partial_charge_method == "mmff94":
|
|
1711
|
+
mmff_properties = AllChem.MMFFGetMoleculeProperties(rdkit_molecule, "MMFF94")
|
|
1712
|
+
charges = [mmff_properties.GetMMFFPartialCharge(i) for i in range(molecule.n_atoms)]
|
|
1713
|
+
elif partial_charge_method == "gasteiger":
|
|
1714
|
+
AllChem.ComputeGasteigerCharges(rdkit_molecule)
|
|
1715
|
+
charges = [float(rdatom.GetProp("_GasteigerCharge")) for rdatom in rdkit_molecule.GetAtoms()]
|
|
1716
|
+
|
|
1717
|
+
molecule.partial_charges = Quantity(np.asarray(charges), unit.elementary_charge)
|
|
1718
|
+
|
|
1719
|
+
if normalize_partial_charges:
|
|
1720
|
+
molecule._normalize_partial_charges()
|
|
1721
|
+
|
|
1722
|
+
@classmethod
|
|
1723
|
+
def _elf_is_problematic_conformer(
|
|
1724
|
+
cls,
|
|
1725
|
+
molecule: "Molecule",
|
|
1726
|
+
conformer: Quantity,
|
|
1727
|
+
) -> tuple[bool, str | None]:
|
|
1728
|
+
"""A function which checks if a particular conformer is known to be problematic
|
|
1729
|
+
when computing ELF partial charges.
|
|
1730
|
+
|
|
1731
|
+
Currently this includes conformers which:
|
|
1732
|
+
|
|
1733
|
+
* contain a trans-COOH configuration. The trans conformer is discarded because
|
|
1734
|
+
it leads to strong electrostatic interactions when assigning charges, and these
|
|
1735
|
+
result in unreasonable charges. Downstream calculations have observed up to a
|
|
1736
|
+
4 log unit error in water-octanol logP calculations when using charges assigned
|
|
1737
|
+
from trans conformers.
|
|
1738
|
+
|
|
1739
|
+
Returns
|
|
1740
|
+
-------
|
|
1741
|
+
A tuple of a bool stating whether the conformer is problematic and, if it
|
|
1742
|
+
is, a string message explaing why. If the conformer is not problematic, the
|
|
1743
|
+
second return value will be none.
|
|
1744
|
+
"""
|
|
1745
|
+
from rdkit.Chem.rdMolTransforms import ( # type: ignore[import-untyped]
|
|
1746
|
+
GetDihedralRad,
|
|
1747
|
+
)
|
|
1748
|
+
|
|
1749
|
+
# Create a copy of the molecule which contains only this conformer.
|
|
1750
|
+
molecule_copy = copy.deepcopy(molecule)
|
|
1751
|
+
molecule_copy._conformers = [conformer]
|
|
1752
|
+
|
|
1753
|
+
rdkit_molecule = molecule_copy.to_rdkit()
|
|
1754
|
+
|
|
1755
|
+
# Check for trans-COOH configurations
|
|
1756
|
+
carboxylic_acid_matches = cls._find_smarts_matches(rdkit_molecule, "[#6X3:2](=[#8:1])(-[#8X2H1:3]-[#1:4])")
|
|
1757
|
+
|
|
1758
|
+
for match in carboxylic_acid_matches:
|
|
1759
|
+
dihedral_angle = GetDihedralRad(rdkit_molecule.GetConformer(0), *match)
|
|
1760
|
+
|
|
1761
|
+
if dihedral_angle > np.pi / 2.0:
|
|
1762
|
+
# Discard the 'trans' conformer.
|
|
1763
|
+
return (
|
|
1764
|
+
True,
|
|
1765
|
+
"Molecules which contain COOH functional groups in a trans "
|
|
1766
|
+
"configuration are discarded by the ELF method.",
|
|
1767
|
+
)
|
|
1768
|
+
|
|
1769
|
+
return False, None
|
|
1770
|
+
|
|
1771
|
+
@classmethod
|
|
1772
|
+
def _elf_prune_problematic_conformers(cls, molecule: "Molecule") -> list[Quantity]:
|
|
1773
|
+
"""A function which attempts to remove conformers which are known to be
|
|
1774
|
+
problematic when computing ELF partial charges.
|
|
1775
|
+
|
|
1776
|
+
Currently this includes conformers which:
|
|
1777
|
+
|
|
1778
|
+
* contain a trans-COOH configuration. These conformers ... TODO add reason.
|
|
1779
|
+
|
|
1780
|
+
Notes
|
|
1781
|
+
-----
|
|
1782
|
+
* Problematic conformers are flagged by the
|
|
1783
|
+
``RDKitToolkitWrapper._elf_is_problematic_conformer`` function.
|
|
1784
|
+
|
|
1785
|
+
Returns
|
|
1786
|
+
-------
|
|
1787
|
+
The conformers to retain.
|
|
1788
|
+
"""
|
|
1789
|
+
|
|
1790
|
+
valid_conformers = []
|
|
1791
|
+
|
|
1792
|
+
for i, conformer in enumerate(molecule.conformers):
|
|
1793
|
+
is_problematic, reason = cls._elf_is_problematic_conformer(molecule, conformer)
|
|
1794
|
+
|
|
1795
|
+
if is_problematic:
|
|
1796
|
+
logger.warning(f"Discarding conformer {i}: {reason}")
|
|
1797
|
+
else:
|
|
1798
|
+
valid_conformers.append(conformer)
|
|
1799
|
+
|
|
1800
|
+
return valid_conformers
|
|
1801
|
+
|
|
1802
|
+
@classmethod
|
|
1803
|
+
def _elf_compute_electrostatic_energy(
|
|
1804
|
+
cls,
|
|
1805
|
+
molecule: "Molecule",
|
|
1806
|
+
conformer: Quantity,
|
|
1807
|
+
) -> float:
|
|
1808
|
+
"""Computes the 'electrostatic interaction energy' of a particular conformer
|
|
1809
|
+
of a molecule.
|
|
1810
|
+
|
|
1811
|
+
The energy is computed as the sum of ``|q_i * q_j| * r_ij^-1`` over all pairs
|
|
1812
|
+
of atoms (i, j) excluding 1-2 and 1-3 terms, where q_i is the partial charge
|
|
1813
|
+
of atom i and r_ij the Euclidean distance between atoms i and j.
|
|
1814
|
+
|
|
1815
|
+
Notes
|
|
1816
|
+
-----
|
|
1817
|
+
* The partial charges will be taken from the molecule directly.
|
|
1818
|
+
|
|
1819
|
+
Parameters
|
|
1820
|
+
----------
|
|
1821
|
+
molecule
|
|
1822
|
+
The molecule containing the partial charges.
|
|
1823
|
+
conformer
|
|
1824
|
+
The conformer to compute the energy of. This should be a unit wrapped
|
|
1825
|
+
numpy array with shape=(n_atoms, 3) with units compatible with angstroms.
|
|
1826
|
+
|
|
1827
|
+
Returns
|
|
1828
|
+
-------
|
|
1829
|
+
The electrostatic interaction energy in units of [e^2 / Angstrom].
|
|
1830
|
+
"""
|
|
1831
|
+
|
|
1832
|
+
if molecule.partial_charges is None:
|
|
1833
|
+
raise ValueError("The molecule has no partial charges assigned.")
|
|
1834
|
+
|
|
1835
|
+
partial_charges = np.abs(molecule.partial_charges.m_as(unit.elementary_charge)).reshape(-1, 1)
|
|
1836
|
+
|
|
1837
|
+
# Build an exclusion list for 1-2 and 1-3 interactions.
|
|
1838
|
+
excluded_x, excluded_y = zip(
|
|
1839
|
+
*{
|
|
1840
|
+
*[(bond.atom1_index, bond.atom2_index) for bond in molecule.bonds],
|
|
1841
|
+
*[(angle[0].molecule_atom_index, angle[-1].molecule_atom_index) for angle in molecule.angles],
|
|
1842
|
+
}
|
|
1843
|
+
)
|
|
1844
|
+
|
|
1845
|
+
# Build the distance matrix between all pairs of atoms.
|
|
1846
|
+
coordinates = conformer.m_as(unit.angstrom)
|
|
1847
|
+
|
|
1848
|
+
# Equation 1: (a - b)^2 = a^2 - 2ab + b^2
|
|
1849
|
+
# distances_squared will eventually wind up as the squared distances
|
|
1850
|
+
# although it is first computed as the ab portion of Eq 1
|
|
1851
|
+
distances_squared = coordinates.dot(coordinates.T)
|
|
1852
|
+
# np.einsum is both faster than np.diag, and not read-only
|
|
1853
|
+
# we know that a^2 == b^2 == diag(ab)
|
|
1854
|
+
diag = np.einsum("ii->i", distances_squared)
|
|
1855
|
+
# we modify in-place so we can use the `diag` view
|
|
1856
|
+
# to make the diagonals 0
|
|
1857
|
+
distances_squared += distances_squared - diag - diag[..., np.newaxis]
|
|
1858
|
+
# Handle edge cases where the squared distance is slightly negative due to
|
|
1859
|
+
# precision issues
|
|
1860
|
+
diag[:] = -0.0 # this is somewhat faster than np.fill_diagonal
|
|
1861
|
+
distances = np.sqrt(-distances_squared)
|
|
1862
|
+
|
|
1863
|
+
inverse_distances = np.reciprocal(distances, out=np.zeros_like(distances), where=~np.isclose(distances, 0.0))
|
|
1864
|
+
|
|
1865
|
+
# Multiply by the charge products.
|
|
1866
|
+
charge_products = partial_charges @ partial_charges.T
|
|
1867
|
+
|
|
1868
|
+
charge_products[excluded_x, excluded_y] = 0.0
|
|
1869
|
+
charge_products[excluded_y, excluded_x] = 0.0
|
|
1870
|
+
|
|
1871
|
+
interaction_energies = inverse_distances * charge_products
|
|
1872
|
+
|
|
1873
|
+
return 0.5 * interaction_energies.sum()
|
|
1874
|
+
|
|
1875
|
+
@classmethod
|
|
1876
|
+
def _elf_compute_rms_matrix(cls, molecule: "Molecule") -> NDArray:
|
|
1877
|
+
"""Computes the symmetric RMS matrix of all conformers in a molecule taking
|
|
1878
|
+
only heavy atoms into account.
|
|
1879
|
+
|
|
1880
|
+
Parameters
|
|
1881
|
+
----------
|
|
1882
|
+
molecule
|
|
1883
|
+
The molecule containing the conformers.
|
|
1884
|
+
|
|
1885
|
+
Returns
|
|
1886
|
+
-------
|
|
1887
|
+
The RMS matrix with shape=(n_conformers, n_conformers).
|
|
1888
|
+
"""
|
|
1889
|
+
|
|
1890
|
+
from rdkit import Chem
|
|
1891
|
+
from rdkit.Chem import AllChem
|
|
1892
|
+
|
|
1893
|
+
rdkit_molecule: Chem.RWMol = Chem.RemoveHs(molecule.to_rdkit())
|
|
1894
|
+
|
|
1895
|
+
n_conformers = len(molecule.conformers)
|
|
1896
|
+
|
|
1897
|
+
# rdkit does not have conformer indices but conformer "ids"
|
|
1898
|
+
conformer_ids = [conf.GetId() for conf in rdkit_molecule.GetConformers()]
|
|
1899
|
+
|
|
1900
|
+
# Compute the RMS matrix making sure to take into account any automorhism (e.g
|
|
1901
|
+
# a phenyl or nitro substituent flipped 180 degrees.
|
|
1902
|
+
rms_matrix = np.zeros((n_conformers, n_conformers))
|
|
1903
|
+
|
|
1904
|
+
for i, j in itertools.combinations(np.arange(n_conformers), 2):
|
|
1905
|
+
rms_matrix[i, j] = AllChem.GetBestRMS(
|
|
1906
|
+
rdkit_molecule,
|
|
1907
|
+
rdkit_molecule,
|
|
1908
|
+
conformer_ids[i],
|
|
1909
|
+
conformer_ids[j],
|
|
1910
|
+
)
|
|
1911
|
+
|
|
1912
|
+
rms_matrix += rms_matrix.T
|
|
1913
|
+
return rms_matrix
|
|
1914
|
+
|
|
1915
|
+
@classmethod
|
|
1916
|
+
def _elf_select_diverse_conformers(
|
|
1917
|
+
cls,
|
|
1918
|
+
molecule: "Molecule",
|
|
1919
|
+
ranked_conformers: list[Quantity],
|
|
1920
|
+
limit: int,
|
|
1921
|
+
rms_tolerance: Quantity,
|
|
1922
|
+
) -> list[Quantity]:
|
|
1923
|
+
"""Attempt to greedily select a specified number conformers which are maximally
|
|
1924
|
+
diverse.
|
|
1925
|
+
|
|
1926
|
+
The conformer with the lowest electrostatic energy (the first conformer in the
|
|
1927
|
+
``ranked_conformers`` list) is always chosen. After that selection proceeds by:
|
|
1928
|
+
|
|
1929
|
+
a) selecting an un-selected conformer which is the most different from those
|
|
1930
|
+
already selected, and whose RMS compared to each selected conformer is
|
|
1931
|
+
greater than ``rms_tolerance``. Here most different means the conformer
|
|
1932
|
+
which has the largest sum of RMS with the selected conformers.
|
|
1933
|
+
|
|
1934
|
+
b) repeating a) until either ``limit`` number of conformers have been selected,
|
|
1935
|
+
or there are no more distinct conformers to select from.
|
|
1936
|
+
|
|
1937
|
+
Notes
|
|
1938
|
+
-----
|
|
1939
|
+
|
|
1940
|
+
* As the selection is greedy there is no guarantee that the selected conformers
|
|
1941
|
+
will be the optimal distinct i.e. there may be other selections of conformers
|
|
1942
|
+
which are more distinct.
|
|
1943
|
+
|
|
1944
|
+
Parameters
|
|
1945
|
+
----------
|
|
1946
|
+
molecule
|
|
1947
|
+
The molecule object which matches the conformers to select from.
|
|
1948
|
+
ranked_conformers
|
|
1949
|
+
A list of conformers to select from, ranked by their electrostatic
|
|
1950
|
+
interaction energy (see ``_compute_electrostatic_energy``).
|
|
1951
|
+
limit
|
|
1952
|
+
The maximum number of conformers to select.
|
|
1953
|
+
rms_tolerance
|
|
1954
|
+
Conformers whose RMS is within this amount will be treated as identical and
|
|
1955
|
+
the duplicate discarded.
|
|
1956
|
+
|
|
1957
|
+
Returns
|
|
1958
|
+
-------
|
|
1959
|
+
The select list of conformers.
|
|
1960
|
+
"""
|
|
1961
|
+
|
|
1962
|
+
# Compute the RMS between all pairs of conformers
|
|
1963
|
+
molecule = copy.deepcopy(molecule)
|
|
1964
|
+
molecule.conformers.clear()
|
|
1965
|
+
|
|
1966
|
+
for conformer in ranked_conformers:
|
|
1967
|
+
molecule.add_conformer(conformer)
|
|
1968
|
+
|
|
1969
|
+
rms_matrix = cls._elf_compute_rms_matrix(molecule)
|
|
1970
|
+
|
|
1971
|
+
# Apply the greedy selection process.
|
|
1972
|
+
selected_indices = [0]
|
|
1973
|
+
angstrom_tol = rms_tolerance.m_as(unit.angstrom)
|
|
1974
|
+
for _ in range(min(limit, molecule.n_conformers) - 1):
|
|
1975
|
+
selected_rms = rms_matrix[selected_indices]
|
|
1976
|
+
any_too_close = np.any(selected_rms < angstrom_tol, axis=0)
|
|
1977
|
+
if np.all(any_too_close):
|
|
1978
|
+
# stop if all conformers remaining are within RMS
|
|
1979
|
+
# threshold of any selected conformer
|
|
1980
|
+
break
|
|
1981
|
+
|
|
1982
|
+
# add the next conformer with the largest summed RMS distance
|
|
1983
|
+
# to current selected conformers
|
|
1984
|
+
rmsdist = np.where(any_too_close, -np.inf, selected_rms.sum(axis=0))
|
|
1985
|
+
selected_indices.append(int(rmsdist.argmax()))
|
|
1986
|
+
|
|
1987
|
+
return [ranked_conformers[i] for i in selected_indices]
|
|
1988
|
+
|
|
1989
|
+
def apply_elf_conformer_selection(
|
|
1990
|
+
self,
|
|
1991
|
+
molecule: "Molecule",
|
|
1992
|
+
percentage: float = 2.0,
|
|
1993
|
+
limit: int = 10,
|
|
1994
|
+
rms_tolerance: Quantity = 0.05 * unit.angstrom,
|
|
1995
|
+
):
|
|
1996
|
+
"""Applies the `ELF method
|
|
1997
|
+
<https://docs.eyesopen.com/toolkits/python/quacpactk/molchargetheory.html#elf-conformer-selection>`_
|
|
1998
|
+
to select a set of diverse conformers which have minimal electrostatically
|
|
1999
|
+
strongly interacting functional groups from a molecules conformers.
|
|
2000
|
+
|
|
2001
|
+
The diverse conformer selection is performed by the ``_elf_select_diverse_conformers``
|
|
2002
|
+
function, which attempts to greedily select conformers which are most distinct
|
|
2003
|
+
according to their RMS.
|
|
2004
|
+
|
|
2005
|
+
Warnings
|
|
2006
|
+
--------
|
|
2007
|
+
* Although this function is inspired by the OpenEye ELF10 method, this
|
|
2008
|
+
implementation may yield slightly different conformers due to potential
|
|
2009
|
+
differences in this and the OE closed source implementation.
|
|
2010
|
+
|
|
2011
|
+
Notes
|
|
2012
|
+
-----
|
|
2013
|
+
* The input molecule should have a large set of conformers already
|
|
2014
|
+
generated to select the ELF10 conformers from.
|
|
2015
|
+
* The selected conformers will be retained in the `molecule.conformers` list
|
|
2016
|
+
while unselected conformers will be discarded.
|
|
2017
|
+
* Only heavy atoms are included when using the RMS to select diverse conformers.
|
|
2018
|
+
|
|
2019
|
+
See Also
|
|
2020
|
+
--------
|
|
2021
|
+
RDKitToolkitWrapper._elf_select_diverse_conformers
|
|
2022
|
+
|
|
2023
|
+
Parameters
|
|
2024
|
+
----------
|
|
2025
|
+
molecule
|
|
2026
|
+
The molecule which contains the set of conformers to select from.
|
|
2027
|
+
percentage
|
|
2028
|
+
The percentage of conformers with the lowest electrostatic interaction
|
|
2029
|
+
energies to greedily select from.
|
|
2030
|
+
limit
|
|
2031
|
+
The maximum number of conformers to select.
|
|
2032
|
+
rms_tolerance
|
|
2033
|
+
Conformers whose RMS is within this amount will be treated as identical and
|
|
2034
|
+
the duplicate discarded.
|
|
2035
|
+
"""
|
|
2036
|
+
|
|
2037
|
+
if molecule.n_conformers == 0:
|
|
2038
|
+
return
|
|
2039
|
+
|
|
2040
|
+
# Copy the input molecule so we can directly perturb it within the method.
|
|
2041
|
+
molecule_copy = copy.deepcopy(molecule)
|
|
2042
|
+
|
|
2043
|
+
# Prune any problematic conformers, such as trans-COOH configurations.
|
|
2044
|
+
conformers = self._elf_prune_problematic_conformers(molecule_copy)
|
|
2045
|
+
|
|
2046
|
+
if len(conformers) == 0:
|
|
2047
|
+
raise ValueError(
|
|
2048
|
+
"There were no conformers to select from after discarding conformers "
|
|
2049
|
+
"which are known to be problematic when computing ELF partial charges. "
|
|
2050
|
+
"Make sure to generate a diverse array of conformers before calling the "
|
|
2051
|
+
"`RDKitToolkitWrapper.apply_elf_conformer_selection` method."
|
|
2052
|
+
)
|
|
2053
|
+
|
|
2054
|
+
# Generate a set of absolute MMFF94 partial charges for the molecule and use
|
|
2055
|
+
# these to compute the electrostatic interaction energy of each conformer.
|
|
2056
|
+
self.assign_partial_charges(molecule_copy, "mmff94")
|
|
2057
|
+
|
|
2058
|
+
conformer_energies = [
|
|
2059
|
+
(
|
|
2060
|
+
self._elf_compute_electrostatic_energy(molecule_copy, conformer),
|
|
2061
|
+
conformer,
|
|
2062
|
+
)
|
|
2063
|
+
for conformer in conformers
|
|
2064
|
+
]
|
|
2065
|
+
|
|
2066
|
+
# Rank the conformer energies and retain `percentage`% with the lowest energies.
|
|
2067
|
+
conformer_energies = sorted(conformer_energies, key=lambda x: x[0])
|
|
2068
|
+
cutoff_index = max(1, int(len(conformer_energies) * percentage / 100.0))
|
|
2069
|
+
|
|
2070
|
+
low_energy_conformers = [conformer for _, conformer in conformer_energies[:cutoff_index]]
|
|
2071
|
+
|
|
2072
|
+
# Attempt to greedily select `limit` conformers which are maximally diverse.
|
|
2073
|
+
diverse_conformers = self._elf_select_diverse_conformers(
|
|
2074
|
+
molecule_copy, low_energy_conformers, limit, rms_tolerance
|
|
2075
|
+
)
|
|
2076
|
+
|
|
2077
|
+
molecule._conformers = diverse_conformers
|
|
2078
|
+
|
|
2079
|
+
def from_rdkit(
|
|
2080
|
+
self,
|
|
2081
|
+
rdmol,
|
|
2082
|
+
allow_undefined_stereo: bool = False,
|
|
2083
|
+
hydrogens_are_explicit: bool = False,
|
|
2084
|
+
_cls=None,
|
|
2085
|
+
):
|
|
2086
|
+
"""
|
|
2087
|
+
Create a Molecule from an RDKit molecule.
|
|
2088
|
+
|
|
2089
|
+
Requires the RDKit to be installed.
|
|
2090
|
+
|
|
2091
|
+
.. warning :: This API is experimental and subject to change.
|
|
2092
|
+
|
|
2093
|
+
Parameters
|
|
2094
|
+
----------
|
|
2095
|
+
rdmol
|
|
2096
|
+
An RDKit molecule
|
|
2097
|
+
allow_undefined_stereo
|
|
2098
|
+
If false, raises an exception if rdmol contains undefined stereochemistry.
|
|
2099
|
+
hydrogens_are_explicit
|
|
2100
|
+
If False, RDKit will perform hydrogen addition using Chem.AddHs
|
|
2101
|
+
_cls
|
|
2102
|
+
Molecule constructor
|
|
2103
|
+
|
|
2104
|
+
Returns
|
|
2105
|
+
-------
|
|
2106
|
+
molecule
|
|
2107
|
+
An OpenFF molecule
|
|
2108
|
+
|
|
2109
|
+
Examples
|
|
2110
|
+
--------
|
|
2111
|
+
|
|
2112
|
+
Create a molecule from an RDKit molecule
|
|
2113
|
+
|
|
2114
|
+
>>> from rdkit import Chem
|
|
2115
|
+
>>> from openff.toolkit._tests.utils import get_data_file_path
|
|
2116
|
+
>>> rdmol = Chem.MolFromMolFile(get_data_file_path('systems/monomers/ethanol.sdf'))
|
|
2117
|
+
|
|
2118
|
+
>>> toolkit_wrapper = RDKitToolkitWrapper()
|
|
2119
|
+
>>> molecule = toolkit_wrapper.from_rdkit(rdmol)
|
|
2120
|
+
|
|
2121
|
+
"""
|
|
2122
|
+
from rdkit import Chem
|
|
2123
|
+
from rdkit.Chem import AllChem
|
|
2124
|
+
|
|
2125
|
+
if _cls is None:
|
|
2126
|
+
from openff.toolkit.topology.molecule import Molecule
|
|
2127
|
+
|
|
2128
|
+
_cls = Molecule
|
|
2129
|
+
|
|
2130
|
+
# Make a copy of the RDKit Mol as we'll need to change it (e.g. assign stereo).
|
|
2131
|
+
rdmol = Chem.Mol(rdmol)
|
|
2132
|
+
|
|
2133
|
+
frags = AllChem.GetMolFrags(rdmol)
|
|
2134
|
+
if len(frags) > 1:
|
|
2135
|
+
warnings.warn(
|
|
2136
|
+
"RDKit Molecule passed to from_rdkit consists of more than one molecule, consider running "
|
|
2137
|
+
"rdkit.Chem.AllChem.GetMolFrags(rdmol, asMols=True) or splitting input SMILES at '.' to get "
|
|
2138
|
+
"separate molecules and pass them to from_rdkit one at a time. While this is supported for "
|
|
2139
|
+
"legacy reasons, OpenFF Molecule objects are not supposed to contain disconnected chemical "
|
|
2140
|
+
"graphs and this may result in undefined behavior later on. The OpenFF ecosystem is built "
|
|
2141
|
+
"to handle multiple molecules, but they should be in a Topology object, ex: "
|
|
2142
|
+
"top = Topology.from_molecules([mol1, mol2])",
|
|
2143
|
+
MultipleComponentsInMoleculeWarning,
|
|
2144
|
+
stacklevel=2,
|
|
2145
|
+
)
|
|
2146
|
+
|
|
2147
|
+
if not hydrogens_are_explicit:
|
|
2148
|
+
rdmol = Chem.AddHs(rdmol, addCoords=True)
|
|
2149
|
+
|
|
2150
|
+
# Sanitizing the molecule. We handle aromaticity and chirality manually.
|
|
2151
|
+
# This SanitizeMol(...) calls cleanUp, updatePropertyCache, symmetrizeSSSR,
|
|
2152
|
+
# assignRadicals, setConjugation, and setHybridization.
|
|
2153
|
+
Chem.SanitizeMol(
|
|
2154
|
+
rdmol,
|
|
2155
|
+
(
|
|
2156
|
+
Chem.SANITIZE_ALL
|
|
2157
|
+
^ Chem.SANITIZE_SETAROMATICITY
|
|
2158
|
+
^ Chem.SANITIZE_ADJUSTHS
|
|
2159
|
+
^ Chem.SANITIZE_CLEANUPCHIRALITY
|
|
2160
|
+
),
|
|
2161
|
+
)
|
|
2162
|
+
Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_MDL)
|
|
2163
|
+
# SetAromaticity set aromatic bonds to 1.5, but Molecule.bond_order is an
|
|
2164
|
+
# integer (contrarily to fractional_bond_order) so we need the Kekule order.
|
|
2165
|
+
Chem.Kekulize(rdmol)
|
|
2166
|
+
|
|
2167
|
+
# Make sure the bond stereo tags are set before checking for
|
|
2168
|
+
# undefined stereo. RDKit can figure out bond stereo from other
|
|
2169
|
+
# information in the Mol object like bond direction properties.
|
|
2170
|
+
# Do not overwrite eventual chiral tags provided by the user.
|
|
2171
|
+
Chem.AssignStereochemistry(rdmol, cleanIt=False)
|
|
2172
|
+
|
|
2173
|
+
# Check for undefined stereochemistry.
|
|
2174
|
+
if not allow_undefined_stereo:
|
|
2175
|
+
self._detect_undefined_stereo(
|
|
2176
|
+
rdmol,
|
|
2177
|
+
err_msg_prefix="Unable to make OFFMol from RDMol: ",
|
|
2178
|
+
)
|
|
2179
|
+
|
|
2180
|
+
# Create a new OpenFF Molecule
|
|
2181
|
+
offmol = _cls()
|
|
2182
|
+
|
|
2183
|
+
# If RDMol has a title, use it
|
|
2184
|
+
if rdmol.HasProp("_Name"):
|
|
2185
|
+
offmol.name = rdmol.GetProp("_Name")
|
|
2186
|
+
|
|
2187
|
+
# Store all properties
|
|
2188
|
+
# TODO: Should there be an API point for storing properties?
|
|
2189
|
+
properties = rdmol.GetPropsAsDict()
|
|
2190
|
+
offmol._properties = properties
|
|
2191
|
+
|
|
2192
|
+
# setting chirality in openeye requires using neighbor atoms
|
|
2193
|
+
# therefore we can't do it until after the atoms and bonds are all added
|
|
2194
|
+
map_atoms = {}
|
|
2195
|
+
map_bonds = {}
|
|
2196
|
+
# if we are loading from a mapped smiles extract the mapping
|
|
2197
|
+
atom_mapping = {}
|
|
2198
|
+
# We need the elements of the lanthanides, actinides, and transition
|
|
2199
|
+
# metals as we don't want to exclude radicals in these blocks.
|
|
2200
|
+
d_and_f_block_elements = {
|
|
2201
|
+
*range(21, 31),
|
|
2202
|
+
*range(39, 49),
|
|
2203
|
+
*range(57, 81),
|
|
2204
|
+
*range(89, 113),
|
|
2205
|
+
}
|
|
2206
|
+
for rda in rdmol.GetAtoms():
|
|
2207
|
+
# See issues #1075 for some discussion on radicals
|
|
2208
|
+
if rda.GetAtomicNum() not in d_and_f_block_elements and rda.GetNumRadicalElectrons() != 0:
|
|
2209
|
+
raise RadicalsNotSupportedError(
|
|
2210
|
+
"The OpenFF Toolkit does not currently support parsing molecules with S- and P-block radicals. "
|
|
2211
|
+
f"Found {rda.GetNumRadicalElectrons()} radical electrons on molecule {Chem.MolToSmiles(rdmol)}."
|
|
2212
|
+
)
|
|
2213
|
+
|
|
2214
|
+
rd_idx = rda.GetIdx()
|
|
2215
|
+
# if the molecule was made from a mapped smiles this has been hidden
|
|
2216
|
+
# so that it does not affect the sterochemistry tags
|
|
2217
|
+
try:
|
|
2218
|
+
map_id = int(rda.GetProp("_map_idx"))
|
|
2219
|
+
except KeyError:
|
|
2220
|
+
map_id = rda.GetAtomMapNum()
|
|
2221
|
+
|
|
2222
|
+
# create a new atom
|
|
2223
|
+
atomic_number = rda.GetAtomicNum()
|
|
2224
|
+
# implicit units of elementary charge
|
|
2225
|
+
formal_charge = rda.GetFormalCharge()
|
|
2226
|
+
is_aromatic = rda.GetIsAromatic()
|
|
2227
|
+
if rda.HasProp("_Name"):
|
|
2228
|
+
name = rda.GetProp("_Name")
|
|
2229
|
+
else:
|
|
2230
|
+
# check for PDB names
|
|
2231
|
+
try:
|
|
2232
|
+
name = rda.GetMonomerInfo().GetName().strip()
|
|
2233
|
+
except AttributeError:
|
|
2234
|
+
name = ""
|
|
2235
|
+
|
|
2236
|
+
# If chiral, store the chirality to be set later
|
|
2237
|
+
stereochemistry = None
|
|
2238
|
+
# tag = rda.GetChiralTag()
|
|
2239
|
+
if rda.HasProp("_CIPCode"):
|
|
2240
|
+
stereo_code = rda.GetProp("_CIPCode")
|
|
2241
|
+
# if tag == Chem.CHI_TETRAHEDRAL_CCW:
|
|
2242
|
+
if stereo_code == "R":
|
|
2243
|
+
stereochemistry = "R"
|
|
2244
|
+
# if tag == Chem.CHI_TETRAHEDRAL_CW:
|
|
2245
|
+
elif stereo_code == "S":
|
|
2246
|
+
stereochemistry = "S"
|
|
2247
|
+
else:
|
|
2248
|
+
raise UndefinedStereochemistryError(
|
|
2249
|
+
f"In from_rdkit: Expected atom stereochemistry of R or S. Got {stereo_code} instead."
|
|
2250
|
+
)
|
|
2251
|
+
|
|
2252
|
+
res = rda.GetPDBResidueInfo()
|
|
2253
|
+
metadata = dict()
|
|
2254
|
+
if res is not None:
|
|
2255
|
+
metadata["residue_name"] = res.GetResidueName()
|
|
2256
|
+
metadata["residue_number"] = res.GetResidueNumber()
|
|
2257
|
+
metadata["insertion_code"] = res.GetInsertionCode()
|
|
2258
|
+
metadata["chain_id"] = res.GetChainId()
|
|
2259
|
+
|
|
2260
|
+
atom_index = offmol._add_atom(
|
|
2261
|
+
atomic_number,
|
|
2262
|
+
formal_charge,
|
|
2263
|
+
is_aromatic,
|
|
2264
|
+
name=name,
|
|
2265
|
+
stereochemistry=stereochemistry,
|
|
2266
|
+
metadata=metadata,
|
|
2267
|
+
invalidate_cache=False,
|
|
2268
|
+
)
|
|
2269
|
+
map_atoms[rd_idx] = atom_index
|
|
2270
|
+
atom_mapping[atom_index] = map_id
|
|
2271
|
+
|
|
2272
|
+
offmol._invalidate_cached_properties()
|
|
2273
|
+
|
|
2274
|
+
# If we have a full / partial atom map add it to the molecule. Zeroes 0
|
|
2275
|
+
# indicates no mapping
|
|
2276
|
+
if {*atom_mapping.values()} != {0}:
|
|
2277
|
+
offmol._properties["atom_map"] = {idx: map_idx for idx, map_idx in atom_mapping.items() if map_idx != 0}
|
|
2278
|
+
|
|
2279
|
+
# Similar to chirality, stereochemistry of bonds in OE is set relative to their neighbors
|
|
2280
|
+
for rdb in rdmol.GetBonds():
|
|
2281
|
+
rdb_idx = rdb.GetIdx()
|
|
2282
|
+
a1 = rdb.GetBeginAtomIdx()
|
|
2283
|
+
a2 = rdb.GetEndAtomIdx()
|
|
2284
|
+
|
|
2285
|
+
# Determine bond aromaticity and Kekulized bond order
|
|
2286
|
+
is_aromatic = rdb.GetIsAromatic()
|
|
2287
|
+
order = rdb.GetBondTypeAsDouble()
|
|
2288
|
+
# Convert floating-point bond order to integral bond order
|
|
2289
|
+
order = int(order)
|
|
2290
|
+
|
|
2291
|
+
# create a new bond
|
|
2292
|
+
bond_index = offmol._add_bond(
|
|
2293
|
+
map_atoms[a1],
|
|
2294
|
+
map_atoms[a2],
|
|
2295
|
+
order,
|
|
2296
|
+
is_aromatic=is_aromatic,
|
|
2297
|
+
invalidate_cache=False,
|
|
2298
|
+
)
|
|
2299
|
+
map_bonds[rdb_idx] = bond_index
|
|
2300
|
+
|
|
2301
|
+
offmol._invalidate_cached_properties()
|
|
2302
|
+
|
|
2303
|
+
# Now fill in the cached (structure-dependent) properties. We have to have the 2D
|
|
2304
|
+
# structure of the molecule in place first, because each call to add_atom and
|
|
2305
|
+
# add_bond invalidates all cached properties
|
|
2306
|
+
for rdb in rdmol.GetBonds():
|
|
2307
|
+
rdb_idx = rdb.GetIdx()
|
|
2308
|
+
offb_idx = map_bonds[rdb_idx]
|
|
2309
|
+
offb = offmol.bonds[offb_idx]
|
|
2310
|
+
# determine if stereochemistry is needed
|
|
2311
|
+
# Note that RDKit has 6 possible values of bond stereo: CIS, TRANS, E, Z, ANY, or NONE
|
|
2312
|
+
# The logic below assumes that "ANY" and "NONE" mean the same thing.
|
|
2313
|
+
stereochemistry = None
|
|
2314
|
+
tag = rdb.GetStereo()
|
|
2315
|
+
if tag == Chem.BondStereo.STEREOZ:
|
|
2316
|
+
stereochemistry = "Z"
|
|
2317
|
+
elif tag == Chem.BondStereo.STEREOE:
|
|
2318
|
+
stereochemistry = "E"
|
|
2319
|
+
elif tag == Chem.BondStereo.STEREOTRANS or tag == Chem.BondStereo.STEREOCIS:
|
|
2320
|
+
raise ValueError(f"Expected RDKit bond stereochemistry of E or Z, got {tag} instead")
|
|
2321
|
+
offb._stereochemistry = stereochemistry
|
|
2322
|
+
fractional_bond_order = None
|
|
2323
|
+
if rdb.HasProp("fractional_bond_order"):
|
|
2324
|
+
fractional_bond_order = rdb.GetDoubleProp("fractional_bond_order")
|
|
2325
|
+
offb.fractional_bond_order = fractional_bond_order
|
|
2326
|
+
|
|
2327
|
+
# TODO: Save conformer(s), if present
|
|
2328
|
+
# If the rdmol has a conformer, store its coordinates
|
|
2329
|
+
if len(rdmol.GetConformers()) != 0:
|
|
2330
|
+
for conf in rdmol.GetConformers():
|
|
2331
|
+
n_atoms = offmol.n_atoms
|
|
2332
|
+
# Here we assume this always be angstrom
|
|
2333
|
+
positions = np.zeros((n_atoms, 3))
|
|
2334
|
+
for rd_idx, off_idx in map_atoms.items():
|
|
2335
|
+
atom_coords = conf.GetPositions()[rd_idx, :]
|
|
2336
|
+
positions[off_idx, :] = atom_coords
|
|
2337
|
+
offmol._add_conformer(Quantity(positions, unit.angstrom))
|
|
2338
|
+
|
|
2339
|
+
partial_charges = np.zeros(shape=offmol.n_atoms, dtype=np.float64)
|
|
2340
|
+
|
|
2341
|
+
any_atom_has_partial_charge = False
|
|
2342
|
+
for rd_idx, rd_atom in enumerate(rdmol.GetAtoms()):
|
|
2343
|
+
off_idx = map_atoms[rd_idx]
|
|
2344
|
+
if rd_atom.HasProp("PartialCharge"):
|
|
2345
|
+
charge = rd_atom.GetDoubleProp("PartialCharge")
|
|
2346
|
+
partial_charges[off_idx] = charge
|
|
2347
|
+
any_atom_has_partial_charge = True
|
|
2348
|
+
else:
|
|
2349
|
+
# If some other atoms had partial charges but this one doesn't, raise an Exception
|
|
2350
|
+
if any_atom_has_partial_charge:
|
|
2351
|
+
raise ValueError("Some atoms in rdmol have partial charges, but others do not.")
|
|
2352
|
+
if any_atom_has_partial_charge:
|
|
2353
|
+
offmol.partial_charges = Quantity(partial_charges, unit.elementary_charge)
|
|
2354
|
+
else:
|
|
2355
|
+
offmol.partial_charges = None
|
|
2356
|
+
return offmol
|
|
2357
|
+
|
|
2358
|
+
@cached(LRUCache(maxsize=4096), key=base_wrapper._mol_to_ctab_and_aro_key)
|
|
2359
|
+
def _connection_table_to_rdkit(self, molecule, aromaticity_model=DEFAULT_AROMATICITY_MODEL):
|
|
2360
|
+
from rdkit import Chem
|
|
2361
|
+
|
|
2362
|
+
if aromaticity_model not in ALLOWED_AROMATICITY_MODELS:
|
|
2363
|
+
raise InvalidAromaticityModelError(
|
|
2364
|
+
f"Given aromaticity model {aromaticity_model} which is not in the set of allowed aromaticity models: "
|
|
2365
|
+
f"{ALLOWED_AROMATICITY_MODELS}"
|
|
2366
|
+
)
|
|
2367
|
+
|
|
2368
|
+
# Create an editable RDKit molecule
|
|
2369
|
+
rdmol = Chem.RWMol()
|
|
2370
|
+
|
|
2371
|
+
_bondtypes = {
|
|
2372
|
+
1: Chem.BondType.SINGLE,
|
|
2373
|
+
1.5: Chem.BondType.AROMATIC,
|
|
2374
|
+
2: Chem.BondType.DOUBLE,
|
|
2375
|
+
3: Chem.BondType.TRIPLE,
|
|
2376
|
+
4: Chem.BondType.QUADRUPLE,
|
|
2377
|
+
5: Chem.BondType.QUINTUPLE,
|
|
2378
|
+
6: Chem.BondType.HEXTUPLE,
|
|
2379
|
+
7: Chem.BondType.ONEANDAHALF,
|
|
2380
|
+
}
|
|
2381
|
+
|
|
2382
|
+
for index, atom in enumerate(molecule.atoms):
|
|
2383
|
+
rdatom = Chem.Atom(atom.atomic_number)
|
|
2384
|
+
rdatom.SetFormalCharge(atom.formal_charge.m_as(unit.elementary_charge))
|
|
2385
|
+
rdatom.SetIsAromatic(atom.is_aromatic)
|
|
2386
|
+
|
|
2387
|
+
# Stereo handling code moved to after bonds are added
|
|
2388
|
+
if atom.stereochemistry == "S":
|
|
2389
|
+
rdatom.SetChiralTag(Chem.CHI_TETRAHEDRAL_CW)
|
|
2390
|
+
elif atom.stereochemistry == "R":
|
|
2391
|
+
rdatom.SetChiralTag(Chem.CHI_TETRAHEDRAL_CCW)
|
|
2392
|
+
|
|
2393
|
+
# Stop rdkit from adding implicit hydrogens
|
|
2394
|
+
rdatom.SetNoImplicit(True)
|
|
2395
|
+
|
|
2396
|
+
rd_index = rdmol.AddAtom(rdatom)
|
|
2397
|
+
|
|
2398
|
+
# Let's make sure al the atom indices in the two molecules
|
|
2399
|
+
# are the same, otherwise we need to create an atom map.
|
|
2400
|
+
assert index == atom.molecule_atom_index
|
|
2401
|
+
assert index == rd_index
|
|
2402
|
+
|
|
2403
|
+
for bond in molecule.bonds:
|
|
2404
|
+
atom_indices = (
|
|
2405
|
+
bond.atom1.molecule_atom_index,
|
|
2406
|
+
bond.atom2.molecule_atom_index,
|
|
2407
|
+
)
|
|
2408
|
+
rdmol.AddBond(*atom_indices)
|
|
2409
|
+
rdbond = rdmol.GetBondBetweenAtoms(*atom_indices)
|
|
2410
|
+
# Assign bond type, which is based on order unless it is aromatic
|
|
2411
|
+
if bond.is_aromatic:
|
|
2412
|
+
rdbond.SetBondType(_bondtypes[1.5])
|
|
2413
|
+
rdbond.SetIsAromatic(True)
|
|
2414
|
+
else:
|
|
2415
|
+
rdbond.SetBondType(_bondtypes[bond.bond_order])
|
|
2416
|
+
rdbond.SetIsAromatic(False)
|
|
2417
|
+
|
|
2418
|
+
Chem.SanitizeMol(
|
|
2419
|
+
rdmol,
|
|
2420
|
+
Chem.SANITIZE_ALL ^ Chem.SANITIZE_ADJUSTHS ^ Chem.SANITIZE_SETAROMATICITY,
|
|
2421
|
+
)
|
|
2422
|
+
|
|
2423
|
+
if aromaticity_model == "OEAroModel_MDL":
|
|
2424
|
+
Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_MDL)
|
|
2425
|
+
else:
|
|
2426
|
+
raise InvalidAromaticityModelError(
|
|
2427
|
+
f"Given aromaticity model {aromaticity_model} which is not in the set of allowed aromaticity models:"
|
|
2428
|
+
f"{ALLOWED_AROMATICITY_MODELS}"
|
|
2429
|
+
)
|
|
2430
|
+
|
|
2431
|
+
# Assign atom stereochemsitry and collect atoms for which RDKit
|
|
2432
|
+
# can't figure out chirality. The _CIPCode property of these atoms
|
|
2433
|
+
# will be forcefully set to the stereo we want (see #196).
|
|
2434
|
+
undefined_stereo_atoms = {}
|
|
2435
|
+
for index, atom in enumerate(molecule.atoms):
|
|
2436
|
+
rdatom = rdmol.GetAtomWithIdx(index)
|
|
2437
|
+
|
|
2438
|
+
# Skip non-chiral atoms.
|
|
2439
|
+
if atom.stereochemistry is None:
|
|
2440
|
+
continue
|
|
2441
|
+
|
|
2442
|
+
# Let's randomly assign this atom's (local) stereo to CW
|
|
2443
|
+
# and check if this causes the (global) stereo to be set
|
|
2444
|
+
# to the desired one (S or R).
|
|
2445
|
+
rdatom.SetChiralTag(Chem.CHI_TETRAHEDRAL_CW)
|
|
2446
|
+
# We need to do force and cleanIt to recalculate CIP stereo.
|
|
2447
|
+
Chem.AssignStereochemistry(rdmol, force=True, cleanIt=True)
|
|
2448
|
+
# If our random initial assignment worked, then we're set.
|
|
2449
|
+
if rdatom.HasProp("_CIPCode") and rdatom.GetProp("_CIPCode") == atom.stereochemistry:
|
|
2450
|
+
continue
|
|
2451
|
+
|
|
2452
|
+
# Otherwise, set it to CCW.
|
|
2453
|
+
rdatom.SetChiralTag(Chem.CHI_TETRAHEDRAL_CCW)
|
|
2454
|
+
# We need to do force and cleanIt to recalculate CIP stereo.
|
|
2455
|
+
Chem.AssignStereochemistry(rdmol, force=True, cleanIt=True)
|
|
2456
|
+
# Hopefully this worked, otherwise something's wrong
|
|
2457
|
+
if rdatom.HasProp("_CIPCode") and rdatom.GetProp("_CIPCode") == atom.stereochemistry:
|
|
2458
|
+
continue
|
|
2459
|
+
|
|
2460
|
+
# Keep track of undefined stereo atoms. We'll force stereochemistry
|
|
2461
|
+
# at the end to avoid the next AssignStereochemistry to overwrite.
|
|
2462
|
+
if not rdatom.HasProp("_CIPCode"):
|
|
2463
|
+
undefined_stereo_atoms[rdatom] = atom.stereochemistry
|
|
2464
|
+
continue
|
|
2465
|
+
|
|
2466
|
+
# Something is wrong.
|
|
2467
|
+
err_msg = (
|
|
2468
|
+
"Unknown atom stereochemistry encountered in to_rdkit. "
|
|
2469
|
+
f"Desired stereochemistry: {atom.stereochemistry}. "
|
|
2470
|
+
f"Set stereochemistry {rdatom.GetProp('_CIPCode')}"
|
|
2471
|
+
)
|
|
2472
|
+
raise RuntimeError(err_msg)
|
|
2473
|
+
|
|
2474
|
+
# Copy bond stereo info from molecule to rdmol.
|
|
2475
|
+
self._assign_rdmol_bonds_stereo(molecule, rdmol)
|
|
2476
|
+
|
|
2477
|
+
# Cleanup the rdmol
|
|
2478
|
+
rdmol.UpdatePropertyCache(strict=False)
|
|
2479
|
+
Chem.GetSSSR(rdmol)
|
|
2480
|
+
|
|
2481
|
+
# Forcefully assign stereo information on the atoms that RDKit
|
|
2482
|
+
# can't figure out. This must be done last as calling AssignStereochemistry
|
|
2483
|
+
# again will delete these properties (see #196).
|
|
2484
|
+
for rdatom, stereochemistry in undefined_stereo_atoms.items():
|
|
2485
|
+
rdatom.SetProp("_CIPCode", stereochemistry)
|
|
2486
|
+
|
|
2487
|
+
return rdmol
|
|
2488
|
+
|
|
2489
|
+
def to_rdkit(self, molecule: "Molecule", aromaticity_model: str = DEFAULT_AROMATICITY_MODEL):
|
|
2490
|
+
"""
|
|
2491
|
+
Create an RDKit molecule
|
|
2492
|
+
Requires the RDKit to be installed.
|
|
2493
|
+
|
|
2494
|
+
.. warning :: This API is experimental and subject to change.
|
|
2495
|
+
|
|
2496
|
+
Parameters
|
|
2497
|
+
----------
|
|
2498
|
+
|
|
2499
|
+
aromaticity_model
|
|
2500
|
+
The aromaticity model to use. Only OEAroModel_MDL is supported.
|
|
2501
|
+
|
|
2502
|
+
Returns
|
|
2503
|
+
-------
|
|
2504
|
+
|
|
2505
|
+
rdmol
|
|
2506
|
+
An RDKit molecule
|
|
2507
|
+
|
|
2508
|
+
Examples
|
|
2509
|
+
--------
|
|
2510
|
+
|
|
2511
|
+
Convert a molecule to RDKit
|
|
2512
|
+
>>> from openff.toolkit import Molecule
|
|
2513
|
+
>>> ethanol = Molecule.from_smiles('CCO')
|
|
2514
|
+
>>> rdmol = ethanol.to_rdkit()
|
|
2515
|
+
"""
|
|
2516
|
+
from rdkit import Chem, Geometry
|
|
2517
|
+
|
|
2518
|
+
if aromaticity_model not in ALLOWED_AROMATICITY_MODELS:
|
|
2519
|
+
raise InvalidAromaticityModelError(
|
|
2520
|
+
f"Given aromaticity model {aromaticity_model} which is not in the set of allowed aromaticity models: "
|
|
2521
|
+
f"{ALLOWED_AROMATICITY_MODELS}."
|
|
2522
|
+
)
|
|
2523
|
+
|
|
2524
|
+
# Convert the OFF molecule's connectivity table to RDKit, returning a cached rdmol if possible
|
|
2525
|
+
rdmol = self._connection_table_to_rdkit(molecule, aromaticity_model=aromaticity_model)
|
|
2526
|
+
# In case a cached rdmol was returned, make a copy of it
|
|
2527
|
+
rdmol = Chem.RWMol(rdmol)
|
|
2528
|
+
# Set name
|
|
2529
|
+
# TODO: What is the best practice for how this should be named?
|
|
2530
|
+
if molecule.name != "":
|
|
2531
|
+
rdmol.SetProp("_Name", molecule.name)
|
|
2532
|
+
|
|
2533
|
+
# TODO: Set other properties
|
|
2534
|
+
for name, value in molecule.properties.items():
|
|
2535
|
+
if type(value) is str:
|
|
2536
|
+
rdmol.SetProp(name, value)
|
|
2537
|
+
elif type(value) is int:
|
|
2538
|
+
rdmol.SetIntProp(name, value)
|
|
2539
|
+
elif type(value) is float:
|
|
2540
|
+
rdmol.SetDoubleProp(name, value)
|
|
2541
|
+
elif type(value) is bool:
|
|
2542
|
+
rdmol.SetBoolProp(name, value)
|
|
2543
|
+
else:
|
|
2544
|
+
# Shove everything else into a string
|
|
2545
|
+
rdmol.SetProp(name, str(value))
|
|
2546
|
+
|
|
2547
|
+
for index, atom in enumerate(molecule.atoms):
|
|
2548
|
+
rdatom = rdmol.GetAtomWithIdx(index)
|
|
2549
|
+
rdatom.SetProp("_Name", atom.name)
|
|
2550
|
+
|
|
2551
|
+
if rdatom.GetPDBResidueInfo() is None:
|
|
2552
|
+
res = Chem.AtomPDBResidueInfo()
|
|
2553
|
+
else:
|
|
2554
|
+
res = rdatom.GetPDBResidueInfo()
|
|
2555
|
+
|
|
2556
|
+
atom_has_any_metadata = False
|
|
2557
|
+
# RDKit is very naive about PDB atom names - Needs them to be exactly
|
|
2558
|
+
# 4 characters or the columns won't comply with PDB specification
|
|
2559
|
+
res.SetName(atom.name.center(4)[:4])
|
|
2560
|
+
if "residue_name" in atom.metadata:
|
|
2561
|
+
atom_has_any_metadata = True
|
|
2562
|
+
res.SetResidueName(atom.metadata["residue_name"])
|
|
2563
|
+
|
|
2564
|
+
if "residue_number" in atom.metadata:
|
|
2565
|
+
try:
|
|
2566
|
+
residue_number_int = int(atom.metadata["residue_number"])
|
|
2567
|
+
except ValueError:
|
|
2568
|
+
# Residue number is a string that could not be converted to int
|
|
2569
|
+
pass
|
|
2570
|
+
else:
|
|
2571
|
+
atom_has_any_metadata = True
|
|
2572
|
+
res.SetResidueNumber(residue_number_int)
|
|
2573
|
+
|
|
2574
|
+
if "insertion_code" in atom.metadata:
|
|
2575
|
+
atom_has_any_metadata = True
|
|
2576
|
+
res.SetInsertionCode(atom.metadata["insertion_code"])
|
|
2577
|
+
|
|
2578
|
+
if "chain_id" in atom.metadata:
|
|
2579
|
+
atom_has_any_metadata = True
|
|
2580
|
+
res.SetChainId(atom.metadata["chain_id"])
|
|
2581
|
+
|
|
2582
|
+
if atom_has_any_metadata:
|
|
2583
|
+
rdatom.SetPDBResidueInfo(res)
|
|
2584
|
+
|
|
2585
|
+
for bond in molecule.bonds:
|
|
2586
|
+
atom_indices = (
|
|
2587
|
+
bond.atom1.molecule_atom_index,
|
|
2588
|
+
bond.atom2.molecule_atom_index,
|
|
2589
|
+
)
|
|
2590
|
+
rdbond = rdmol.GetBondBetweenAtoms(*atom_indices)
|
|
2591
|
+
if bond.fractional_bond_order is not None:
|
|
2592
|
+
rdbond.SetDoubleProp("fractional_bond_order", bond.fractional_bond_order)
|
|
2593
|
+
|
|
2594
|
+
# Set coordinates if we have them
|
|
2595
|
+
if molecule._conformers:
|
|
2596
|
+
for conformer in molecule._conformers:
|
|
2597
|
+
rdmol_conformer = Chem.Conformer()
|
|
2598
|
+
for atom_idx in range(molecule.n_atoms):
|
|
2599
|
+
x, y, z = conformer[atom_idx, :].m_as(unit.angstrom)
|
|
2600
|
+
rdmol_conformer.SetAtomPosition(atom_idx, Geometry.Point3D(x, y, z))
|
|
2601
|
+
rdmol.AddConformer(rdmol_conformer, assignId=True)
|
|
2602
|
+
|
|
2603
|
+
# Retain charges, if present
|
|
2604
|
+
if molecule._partial_charges is not None:
|
|
2605
|
+
rdk_indexed_charges = np.zeros(shape=molecule.n_atoms, dtype=float)
|
|
2606
|
+
for atom_idx, charge in enumerate(molecule._partial_charges):
|
|
2607
|
+
charge_unitless = charge.m_as(unit.elementary_charge)
|
|
2608
|
+
rdk_indexed_charges[atom_idx] = charge_unitless
|
|
2609
|
+
for atom_idx, rdk_atom in enumerate(rdmol.GetAtoms()):
|
|
2610
|
+
rdk_atom.SetDoubleProp("PartialCharge", rdk_indexed_charges[atom_idx])
|
|
2611
|
+
|
|
2612
|
+
# Note: We could put this outside the "if" statement, which would result in all partial charges in the
|
|
2613
|
+
# resulting file being set to "n/a" if they weren't set in the Open Force Field Toolkit ``Molecule``
|
|
2614
|
+
Chem.CreateAtomDoublePropertyList(rdmol, "PartialCharge")
|
|
2615
|
+
|
|
2616
|
+
# Return non-editable version
|
|
2617
|
+
return Chem.Mol(rdmol)
|
|
2618
|
+
|
|
2619
|
+
def to_inchi(self, molecule: "Molecule", fixed_hydrogens: bool = False):
|
|
2620
|
+
"""
|
|
2621
|
+
Create an InChI string for the molecule using the RDKit Toolkit.
|
|
2622
|
+
InChI is a standardised representation that does not capture tautomers
|
|
2623
|
+
unless specified using the fixed hydrogen layer.
|
|
2624
|
+
|
|
2625
|
+
The /LargeMolecules option is used.
|
|
2626
|
+
|
|
2627
|
+
For information on InChi see here https://iupac.org/who-we-are/divisions/division-details/inchi/
|
|
2628
|
+
|
|
2629
|
+
Parameters
|
|
2630
|
+
----------
|
|
2631
|
+
molecule
|
|
2632
|
+
The molecule to convert into a SMILES.
|
|
2633
|
+
|
|
2634
|
+
fixed_hydrogens
|
|
2635
|
+
If a fixed hydrogen layer should be added to the InChI, if `True` this will produce a
|
|
2636
|
+
non standard specific InChI string of the molecule.
|
|
2637
|
+
|
|
2638
|
+
Returns
|
|
2639
|
+
--------
|
|
2640
|
+
inchi
|
|
2641
|
+
The InChI string of the molecule.
|
|
2642
|
+
|
|
2643
|
+
Raises
|
|
2644
|
+
------
|
|
2645
|
+
EmptyInChiError
|
|
2646
|
+
If RDKit failed to generate an InChI for the molecule
|
|
2647
|
+
"""
|
|
2648
|
+
|
|
2649
|
+
from rdkit import Chem
|
|
2650
|
+
|
|
2651
|
+
rdmol = self.to_rdkit(molecule)
|
|
2652
|
+
|
|
2653
|
+
options = "/LargeMolecules"
|
|
2654
|
+
|
|
2655
|
+
if fixed_hydrogens:
|
|
2656
|
+
options += " /FixedH"
|
|
2657
|
+
|
|
2658
|
+
inchi = Chem.MolToInchi(rdmol, options)
|
|
2659
|
+
|
|
2660
|
+
if len(inchi) == 0:
|
|
2661
|
+
raise EmptyInChiError("RDKit failed to generate an InChI for the molecule.")
|
|
2662
|
+
|
|
2663
|
+
return inchi
|
|
2664
|
+
|
|
2665
|
+
def to_inchikey(self, molecule: "Molecule", fixed_hydrogens: bool = False) -> str:
|
|
2666
|
+
"""
|
|
2667
|
+
Create an InChIKey for the molecule using the RDKit Toolkit.
|
|
2668
|
+
InChIKey is a standardised representation that does not capture tautomers
|
|
2669
|
+
unless specified using the fixed hydrogen layer.
|
|
2670
|
+
|
|
2671
|
+
The /LargeMolecules option is used.
|
|
2672
|
+
|
|
2673
|
+
For information on InChi see here https://iupac.org/who-we-are/divisions/division-details/inchi/
|
|
2674
|
+
|
|
2675
|
+
Parameters
|
|
2676
|
+
----------
|
|
2677
|
+
molecule
|
|
2678
|
+
The molecule to convert into a SMILES.
|
|
2679
|
+
|
|
2680
|
+
fixed_hydrogens
|
|
2681
|
+
If a fixed hydrogen layer should be added to the InChI, if `True` this will
|
|
2682
|
+
produce a non standard specific InChI string of the molecule.
|
|
2683
|
+
|
|
2684
|
+
Returns
|
|
2685
|
+
--------
|
|
2686
|
+
inchi_key
|
|
2687
|
+
The InChIKey representation of the molecule.
|
|
2688
|
+
|
|
2689
|
+
Raises
|
|
2690
|
+
------
|
|
2691
|
+
EmptyInChiError
|
|
2692
|
+
If RDKit failed to generate an InChI for the molecule
|
|
2693
|
+
"""
|
|
2694
|
+
|
|
2695
|
+
from rdkit import Chem
|
|
2696
|
+
|
|
2697
|
+
rdmol = self.to_rdkit(molecule)
|
|
2698
|
+
|
|
2699
|
+
options = "/LargeMolecules"
|
|
2700
|
+
|
|
2701
|
+
if fixed_hydrogens:
|
|
2702
|
+
options += " /FixedH"
|
|
2703
|
+
|
|
2704
|
+
inchi_key = Chem.MolToInchiKey(rdmol, options)
|
|
2705
|
+
|
|
2706
|
+
if len(inchi_key) == 0:
|
|
2707
|
+
raise EmptyInChiError("RDKit failed to generate an InChI key for the molecule.")
|
|
2708
|
+
|
|
2709
|
+
return inchi_key
|
|
2710
|
+
|
|
2711
|
+
def get_tagged_smarts_connectivity(self, smarts: str):
|
|
2712
|
+
"""
|
|
2713
|
+
Returns a tuple of tuples indicating connectivity between tagged atoms in a SMARTS string. Does not
|
|
2714
|
+
return bond order.
|
|
2715
|
+
|
|
2716
|
+
Parameters
|
|
2717
|
+
----------
|
|
2718
|
+
smarts
|
|
2719
|
+
The tagged SMARTS to analyze
|
|
2720
|
+
|
|
2721
|
+
Returns
|
|
2722
|
+
-------
|
|
2723
|
+
unique_tags
|
|
2724
|
+
A sorted tuple of all unique tagged atom map indices.
|
|
2725
|
+
tagged_atom_connectivity
|
|
2726
|
+
A tuple of tuples, where each inner tuple is a pair of tagged atoms (tag_idx_1, tag_idx_2)
|
|
2727
|
+
which are bonded. The inner tuples are ordered smallest-to-largest, and the tuple of
|
|
2728
|
+
tuples is ordered lexically. So the return value for an improper torsion would be
|
|
2729
|
+
((1, 2), (2, 3), (2, 4)).
|
|
2730
|
+
|
|
2731
|
+
Raises
|
|
2732
|
+
------
|
|
2733
|
+
SMIRKSParsingError
|
|
2734
|
+
If RDKit was unable to parse the provided smirks/tagged smarts
|
|
2735
|
+
"""
|
|
2736
|
+
from rdkit import Chem
|
|
2737
|
+
|
|
2738
|
+
from openff.toolkit.utils.exceptions import SMIRKSParsingError
|
|
2739
|
+
|
|
2740
|
+
ss = Chem.MolFromSmarts(smarts)
|
|
2741
|
+
|
|
2742
|
+
if ss is None:
|
|
2743
|
+
# This is a SMIRKS or SMARTS parsing error? The argument and exception disagree
|
|
2744
|
+
raise SMIRKSParsingError(f"RDKit was unable to parse SMIRKS/SMARTS {smarts}")
|
|
2745
|
+
|
|
2746
|
+
_unique_tags = set()
|
|
2747
|
+
_connections = set()
|
|
2748
|
+
for at1 in ss.GetAtoms():
|
|
2749
|
+
if at1.GetAtomMapNum() == 0:
|
|
2750
|
+
continue
|
|
2751
|
+
_unique_tags.add(at1.GetAtomMapNum())
|
|
2752
|
+
for at2 in at1.GetNeighbors():
|
|
2753
|
+
if at2.GetAtomMapNum() == 0:
|
|
2754
|
+
continue
|
|
2755
|
+
cxn_to_add = sorted([at1.GetAtomMapNum(), at2.GetAtomMapNum()])
|
|
2756
|
+
_connections.add(tuple(cxn_to_add))
|
|
2757
|
+
connections = tuple(sorted(list(_connections)))
|
|
2758
|
+
unique_tags = tuple(sorted(list(_unique_tags)))
|
|
2759
|
+
return unique_tags, connections
|
|
2760
|
+
|
|
2761
|
+
@staticmethod
|
|
2762
|
+
def _find_smarts_matches(
|
|
2763
|
+
rdmol,
|
|
2764
|
+
smarts: str,
|
|
2765
|
+
aromaticity_model: str = "OEAroModel_MDL",
|
|
2766
|
+
unique: bool = False,
|
|
2767
|
+
) -> list[tuple[int, ...]]:
|
|
2768
|
+
"""Find all sets of atoms in the provided RDKit molecule that match the provided SMARTS string.
|
|
2769
|
+
|
|
2770
|
+
Parameters
|
|
2771
|
+
----------
|
|
2772
|
+
rdmol
|
|
2773
|
+
rdmol to process with the SMIRKS in order to find matches
|
|
2774
|
+
smarts
|
|
2775
|
+
SMARTS string with any number of sequentially tagged atoms.
|
|
2776
|
+
If there are N tagged atoms numbered 1..N, the resulting matches will be
|
|
2777
|
+
N-tuples of atoms that match the corresponding tagged atoms.
|
|
2778
|
+
aromaticity_model
|
|
2779
|
+
OpenEye aromaticity model designation as a string, such as ``OEAroModel_MDL``.
|
|
2780
|
+
Molecule is prepared with this aromaticity model prior to querying.
|
|
2781
|
+
unique
|
|
2782
|
+
If True, only return unique matches. If False, return all matches. This is passed to
|
|
2783
|
+
RDKit's ``GetSubstructMatches`` as ``uniquify``.
|
|
2784
|
+
|
|
2785
|
+
Returns
|
|
2786
|
+
-------
|
|
2787
|
+
matches
|
|
2788
|
+
matches[index] is an N-tuple of atom numbers from the ``rdmol``
|
|
2789
|
+
Matches are returned in no guaranteed order.
|
|
2790
|
+
# TODO: What is returned if no matches are found? An empty list, or None?
|
|
2791
|
+
# TODO: Ensure that SMARTS numbers 1, 2, 3... are rendered into order of
|
|
2792
|
+
# returned matches indexed by 0, 1, 2...
|
|
2793
|
+
|
|
2794
|
+
.. notes ::
|
|
2795
|
+
|
|
2796
|
+
* Raises ``ChemicalEnvironmentParsingError`` if ``smarts`` query is malformed
|
|
2797
|
+
|
|
2798
|
+
"""
|
|
2799
|
+
from rdkit import Chem
|
|
2800
|
+
|
|
2801
|
+
from openff.toolkit.utils.exceptions import ChemicalEnvironmentParsingError
|
|
2802
|
+
|
|
2803
|
+
# This code is part of a possible performance optimization that hasn't been validated
|
|
2804
|
+
# for production use yet.
|
|
2805
|
+
def _match_smarts_with_heavy_atoms_first(rdmol, qmol, match_kwargs):
|
|
2806
|
+
for i, atom in enumerate(qmol.GetAtoms()):
|
|
2807
|
+
atom.SetIntProp("index", i)
|
|
2808
|
+
|
|
2809
|
+
remove_params = Chem.rdmolops.RemoveHsParameters()
|
|
2810
|
+
remove_params.removeWithQuery = True
|
|
2811
|
+
heavy_query = Chem.RemoveHs(qmol, remove_params, sanitize=False)
|
|
2812
|
+
heavy_to_qmol = [atom.GetIntProp("index") for atom in heavy_query.GetAtoms()]
|
|
2813
|
+
query_atoms = [Chem.Atom(i + 2) for i in range(len(heavy_to_qmol))]
|
|
2814
|
+
|
|
2815
|
+
full_matches = set()
|
|
2816
|
+
|
|
2817
|
+
for heavy_match in rdmol.GetSubstructMatches(heavy_query, **match_kwargs):
|
|
2818
|
+
rdmol_copy = Chem.RWMol(rdmol)
|
|
2819
|
+
qmol_copy = Chem.RWMol(qmol)
|
|
2820
|
+
# pin atoms by atom type
|
|
2821
|
+
for heavy_index, rdmol_index in enumerate(heavy_match):
|
|
2822
|
+
qmol_index = heavy_to_qmol[heavy_index]
|
|
2823
|
+
qmol_copy.ReplaceAtom(qmol_index, query_atoms[heavy_index])
|
|
2824
|
+
rdmol_copy.ReplaceAtom(rdmol_index, query_atoms[heavy_index])
|
|
2825
|
+
|
|
2826
|
+
rdmol_copy.UpdatePropertyCache(strict=False)
|
|
2827
|
+
qmol_copy.UpdatePropertyCache(strict=False)
|
|
2828
|
+
h_matches = rdmol_copy.GetSubstructMatches(qmol_copy, **match_kwargs)
|
|
2829
|
+
full_matches |= set(h_matches)
|
|
2830
|
+
|
|
2831
|
+
return full_matches
|
|
2832
|
+
|
|
2833
|
+
# Set up query.
|
|
2834
|
+
qmol = Chem.MolFromSmarts(smarts) # cannot catch the error
|
|
2835
|
+
if qmol is None:
|
|
2836
|
+
raise ChemicalEnvironmentParsingError(f'RDKit could not parse the SMARTS/SMIRKS string "{smarts}"')
|
|
2837
|
+
|
|
2838
|
+
# Create atom mapping for query molecule
|
|
2839
|
+
idx_map = dict()
|
|
2840
|
+
for atom in qmol.GetAtoms():
|
|
2841
|
+
smirks_index = atom.GetAtomMapNum()
|
|
2842
|
+
if smirks_index != 0:
|
|
2843
|
+
idx_map[smirks_index - 1] = atom.GetIdx()
|
|
2844
|
+
map_list = [idx_map[x] for x in sorted(idx_map)]
|
|
2845
|
+
|
|
2846
|
+
# choose the largest unsigned int without overflow
|
|
2847
|
+
# since the C++ signature is a uint
|
|
2848
|
+
# TODO: max_matches = int(max_matches) if max_matches is not None else np.iinfo(np.uintc).max
|
|
2849
|
+
max_matches = np.iinfo(np.uintc).max
|
|
2850
|
+
match_kwargs = dict(uniquify=unique, maxMatches=max_matches, useChirality=True)
|
|
2851
|
+
# These variables are un-used, do they serve a purpose?
|
|
2852
|
+
# n_heavy = qmol.GetNumHeavyAtoms()
|
|
2853
|
+
# n_h = qmol.GetNumAtoms() - n_heavy
|
|
2854
|
+
# TODO: if match_heavy_first: full_matches = _match_smarts_with_heavy_atoms_first(...)
|
|
2855
|
+
full_matches = rdmol.GetSubstructMatches(qmol, **match_kwargs)
|
|
2856
|
+
|
|
2857
|
+
matches = [tuple(match[x] for x in map_list) for match in full_matches]
|
|
2858
|
+
|
|
2859
|
+
return matches
|
|
2860
|
+
|
|
2861
|
+
def find_smarts_matches(
|
|
2862
|
+
self,
|
|
2863
|
+
molecule: "Molecule",
|
|
2864
|
+
smarts: str,
|
|
2865
|
+
aromaticity_model: str = "OEAroModel_MDL",
|
|
2866
|
+
unique: bool = False,
|
|
2867
|
+
) -> list[tuple[int, ...]]:
|
|
2868
|
+
"""
|
|
2869
|
+
Find all SMARTS matches for the specified molecule, using the specified aromaticity model.
|
|
2870
|
+
|
|
2871
|
+
.. warning :: This API is experimental and subject to change.
|
|
2872
|
+
|
|
2873
|
+
Parameters
|
|
2874
|
+
----------
|
|
2875
|
+
molecule
|
|
2876
|
+
The molecule for which all specified SMARTS matches are to be located
|
|
2877
|
+
smarts
|
|
2878
|
+
SMARTS string with optional SMIRKS-style atom tagging
|
|
2879
|
+
aromaticity_model
|
|
2880
|
+
Molecule is prepared with this aromaticity model prior to querying.
|
|
2881
|
+
unique
|
|
2882
|
+
If True, only return unique matches. If False, return all matches.
|
|
2883
|
+
|
|
2884
|
+
.. note :: Currently, the only supported ``aromaticity_model`` is ``OEAroModel_MDL``
|
|
2885
|
+
|
|
2886
|
+
"""
|
|
2887
|
+
rdmol = self._connection_table_to_rdkit(molecule, aromaticity_model=aromaticity_model)
|
|
2888
|
+
return self._find_smarts_matches(
|
|
2889
|
+
rdmol,
|
|
2890
|
+
smarts,
|
|
2891
|
+
aromaticity_model="OEAroModel_MDL",
|
|
2892
|
+
unique=unique,
|
|
2893
|
+
)
|
|
2894
|
+
|
|
2895
|
+
def atom_is_in_ring(self, atom: "Atom") -> bool:
|
|
2896
|
+
"""Return whether or not an atom is in a ring.
|
|
2897
|
+
|
|
2898
|
+
It is assumed that this atom is in molecule.
|
|
2899
|
+
|
|
2900
|
+
Parameters
|
|
2901
|
+
----------
|
|
2902
|
+
atom
|
|
2903
|
+
The molecule containing the atom of interest
|
|
2904
|
+
|
|
2905
|
+
Returns
|
|
2906
|
+
-------
|
|
2907
|
+
is_in_ring
|
|
2908
|
+
Whether or not the atom is in a ring.
|
|
2909
|
+
|
|
2910
|
+
Raises
|
|
2911
|
+
------
|
|
2912
|
+
NotAttachedToMoleculeError
|
|
2913
|
+
"""
|
|
2914
|
+
if atom.molecule is None:
|
|
2915
|
+
raise NotAttachedToMoleculeError("This Atom does not belong to a Molecule object")
|
|
2916
|
+
|
|
2917
|
+
molecule = atom.molecule
|
|
2918
|
+
atom_index = atom.molecule_atom_index
|
|
2919
|
+
|
|
2920
|
+
rdmol = molecule.to_rdkit()
|
|
2921
|
+
rdatom = rdmol.GetAtomWithIdx(atom_index)
|
|
2922
|
+
|
|
2923
|
+
is_in_ring = rdatom.IsInRing()
|
|
2924
|
+
|
|
2925
|
+
return is_in_ring
|
|
2926
|
+
|
|
2927
|
+
def bond_is_in_ring(self, bond: "Bond") -> bool:
|
|
2928
|
+
"""Return whether or not a bond is in a ring.
|
|
2929
|
+
|
|
2930
|
+
It is assumed that this atom is in molecule.
|
|
2931
|
+
|
|
2932
|
+
Parameters
|
|
2933
|
+
----------
|
|
2934
|
+
bond
|
|
2935
|
+
The molecule containing the atom of interest
|
|
2936
|
+
|
|
2937
|
+
Returns
|
|
2938
|
+
-------
|
|
2939
|
+
is_in_ring
|
|
2940
|
+
Whether or not the bond of index `bond_index` is in a ring
|
|
2941
|
+
|
|
2942
|
+
Raises
|
|
2943
|
+
------
|
|
2944
|
+
NotAttachedToMoleculeError
|
|
2945
|
+
"""
|
|
2946
|
+
if bond.molecule is None:
|
|
2947
|
+
raise NotAttachedToMoleculeError("This Bond does not belong to a Molecule object")
|
|
2948
|
+
|
|
2949
|
+
molecule = bond.molecule
|
|
2950
|
+
rdmol = molecule.to_rdkit()
|
|
2951
|
+
|
|
2952
|
+
# Molecule.to_rdkit() is NOT guaranteed to preserve bond ordering,
|
|
2953
|
+
# so we must look up the corresponding bond via its constituent atom indices
|
|
2954
|
+
rdbond = rdmol.GetBondBetweenAtoms(bond.atom1_index, bond.atom2_index)
|
|
2955
|
+
is_in_ring = rdbond.IsInRing()
|
|
2956
|
+
|
|
2957
|
+
return is_in_ring
|
|
2958
|
+
|
|
2959
|
+
@staticmethod
|
|
2960
|
+
def _find_undefined_stereo_atoms(rdmol, assign_stereo: bool = False) -> list[int]:
|
|
2961
|
+
"""Find the chiral atoms with undefined stereochemsitry in the RDMol.
|
|
2962
|
+
|
|
2963
|
+
Parameters
|
|
2964
|
+
----------
|
|
2965
|
+
rdmol
|
|
2966
|
+
The RDKit molecule.
|
|
2967
|
+
assign_stereo
|
|
2968
|
+
As a side effect, this function calls ``Chem.AssignStereochemistry()``
|
|
2969
|
+
so by default we work on a molecule copy. Set this to ``True`` to avoid
|
|
2970
|
+
making a copy and assigning the stereochemistry to the Mol object.
|
|
2971
|
+
|
|
2972
|
+
Returns
|
|
2973
|
+
-------
|
|
2974
|
+
undefined_atom_indices
|
|
2975
|
+
A list of atom indices that are chiral centers with undefined
|
|
2976
|
+
stereochemistry.
|
|
2977
|
+
|
|
2978
|
+
See Also
|
|
2979
|
+
--------
|
|
2980
|
+
rdkit.Chem.FindMolChiralCenters
|
|
2981
|
+
|
|
2982
|
+
"""
|
|
2983
|
+
from rdkit import Chem
|
|
2984
|
+
|
|
2985
|
+
if not assign_stereo:
|
|
2986
|
+
# Avoid modifying the original molecule.
|
|
2987
|
+
rdmol = copy.deepcopy(rdmol)
|
|
2988
|
+
|
|
2989
|
+
# Flag possible chiral centers with the "_ChiralityPossible".
|
|
2990
|
+
Chem.AssignStereochemistry(rdmol, force=True, flagPossibleStereoCenters=True)
|
|
2991
|
+
|
|
2992
|
+
# Find all atoms with undefined stereo.
|
|
2993
|
+
undefined_atom_indices = []
|
|
2994
|
+
for atom_idx, atom in enumerate(rdmol.GetAtoms()):
|
|
2995
|
+
if atom.GetChiralTag() == Chem.ChiralType.CHI_UNSPECIFIED and atom.HasProp("_ChiralityPossible"):
|
|
2996
|
+
undefined_atom_indices.append(atom_idx)
|
|
2997
|
+
return undefined_atom_indices
|
|
2998
|
+
|
|
2999
|
+
@staticmethod
|
|
3000
|
+
def _find_undefined_stereo_bonds(rdmol):
|
|
3001
|
+
"""Find the chiral atoms with undefined stereochemsitry in the RDMol.
|
|
3002
|
+
|
|
3003
|
+
Parameters
|
|
3004
|
+
----------
|
|
3005
|
+
rdmol
|
|
3006
|
+
The RDKit molecule.
|
|
3007
|
+
|
|
3008
|
+
Returns
|
|
3009
|
+
-------
|
|
3010
|
+
undefined_bond_indices
|
|
3011
|
+
A list of bond indices with undefined stereochemistry.
|
|
3012
|
+
|
|
3013
|
+
See Also
|
|
3014
|
+
--------
|
|
3015
|
+
Chem.EnumerateStereoisomers._getFlippers
|
|
3016
|
+
|
|
3017
|
+
Links
|
|
3018
|
+
-----
|
|
3019
|
+
https://github.com/rdkit/rdkit/blob/master/Code/GraphMol/Chirality.cpp#L1509-L1515
|
|
3020
|
+
This comment in FindPotentialStereoBonds mention that the method
|
|
3021
|
+
ignores ring bonds.
|
|
3022
|
+
https://github.com/DrrDom/rdk/blob/master/gen_stereo_rdkit3.py
|
|
3023
|
+
The function get_unspec_double_bonds() in this module looks like
|
|
3024
|
+
may solve the problem with the rings.
|
|
3025
|
+
|
|
3026
|
+
"""
|
|
3027
|
+
from rdkit import Chem
|
|
3028
|
+
|
|
3029
|
+
# Copy the molecule to avoid side effects. Chem.FindPotentialStereoBonds
|
|
3030
|
+
# assign Bond.STEREOANY to unspecific bond, which make subsequent calls
|
|
3031
|
+
# of Chem.AssignStereochemistry ignore the bond even if there are
|
|
3032
|
+
# ENDDOWNRIGHT/ENDUPRIGHT bond direction indications.
|
|
3033
|
+
rdmol_copy = copy.deepcopy(rdmol)
|
|
3034
|
+
|
|
3035
|
+
# Clear any previous assignments on the bonds, since FindPotentialStereo may not overwrite it
|
|
3036
|
+
for bond in rdmol_copy.GetBonds():
|
|
3037
|
+
bond.SetStereo(Chem.BondStereo.STEREONONE)
|
|
3038
|
+
|
|
3039
|
+
# This function assigns Bond.GetStereo() == Bond.STEREOANY to bonds with
|
|
3040
|
+
# possible stereochemistry.
|
|
3041
|
+
Chem.FindPotentialStereoBonds(rdmol_copy, cleanIt=True)
|
|
3042
|
+
|
|
3043
|
+
# Any TRULY stereogenic bonds in the molecule are now marked as STEREOANY in rdmol_copy.
|
|
3044
|
+
# Iterate through all the bonds, and for the ones where rdmol_copy is marked as STEREOANY,
|
|
3045
|
+
# ensure that they are cis/trans/E/Z (tested here be ensuring that they're NOT either
|
|
3046
|
+
# # of the other possible types (NONE or ANY))
|
|
3047
|
+
undefined_bond_indices = []
|
|
3048
|
+
for bond_idx, (orig_bond, repercieved_bond) in enumerate(zip(rdmol.GetBonds(), rdmol_copy.GetBonds())):
|
|
3049
|
+
# print(repercieved_bond.GetStereo(), orig_bond.GetStereo())
|
|
3050
|
+
if (repercieved_bond.GetStereo() == Chem.BondStereo.STEREOANY) and (
|
|
3051
|
+
(orig_bond.GetStereo() == Chem.BondStereo.STEREOANY)
|
|
3052
|
+
or (orig_bond.GetStereo() == Chem.BondStereo.STEREONONE)
|
|
3053
|
+
):
|
|
3054
|
+
undefined_bond_indices.append(bond_idx)
|
|
3055
|
+
return undefined_bond_indices
|
|
3056
|
+
|
|
3057
|
+
@classmethod
|
|
3058
|
+
def _detect_undefined_stereo(
|
|
3059
|
+
cls,
|
|
3060
|
+
rdmol,
|
|
3061
|
+
err_msg_prefix: str = "",
|
|
3062
|
+
):
|
|
3063
|
+
"""Raise UndefinedStereochemistryError if the RDMol has undefined stereochemistry.
|
|
3064
|
+
|
|
3065
|
+
Parameters
|
|
3066
|
+
----------
|
|
3067
|
+
rdmol
|
|
3068
|
+
The RDKit molecule.
|
|
3069
|
+
err_msg_prefix
|
|
3070
|
+
A string to prepend to the error message (but not the warning).
|
|
3071
|
+
|
|
3072
|
+
Raises
|
|
3073
|
+
------
|
|
3074
|
+
UndefinedStereochemistryError
|
|
3075
|
+
If the RDMol has undefined atom or bond stereochemistry.
|
|
3076
|
+
|
|
3077
|
+
"""
|
|
3078
|
+
# Find undefined atom/bond stereochemistry.
|
|
3079
|
+
undefined_atom_indices = cls._find_undefined_stereo_atoms(rdmol)
|
|
3080
|
+
undefined_bond_indices = cls._find_undefined_stereo_bonds(rdmol)
|
|
3081
|
+
|
|
3082
|
+
if len(undefined_atom_indices) == 0 and len(undefined_bond_indices) == 0:
|
|
3083
|
+
return
|
|
3084
|
+
|
|
3085
|
+
msg = "RDMol has unspecified stereochemistry. "
|
|
3086
|
+
# The "_Name" property is not always assigned.
|
|
3087
|
+
if rdmol.HasProp("_Name"):
|
|
3088
|
+
msg += "RDMol name: " + rdmol.GetProp("_Name")
|
|
3089
|
+
|
|
3090
|
+
# Details about undefined atoms.
|
|
3091
|
+
if len(undefined_atom_indices) > 0:
|
|
3092
|
+
msg += "Undefined chiral centers are:\n"
|
|
3093
|
+
for undefined_atom_idx in undefined_atom_indices:
|
|
3094
|
+
msg += f" - Atom {rdmol.GetAtomWithIdx(undefined_atom_idx).GetSymbol()} (index {undefined_atom_idx})\n"
|
|
3095
|
+
|
|
3096
|
+
# Details about undefined bond.
|
|
3097
|
+
if len(undefined_bond_indices) > 0:
|
|
3098
|
+
msg += "Bonds with undefined stereochemistry are:\n"
|
|
3099
|
+
for undefined_bond_idx in undefined_bond_indices:
|
|
3100
|
+
bond = rdmol.GetBondWithIdx(undefined_bond_idx)
|
|
3101
|
+
atom1, atom2 = bond.GetBeginAtom(), bond.GetEndAtom()
|
|
3102
|
+
msg += (
|
|
3103
|
+
f" - Bond {undefined_bond_idx} (atoms {atom1.GetIdx()}-{atom2.GetIdx()} of element "
|
|
3104
|
+
f"({atom1.GetSymbol()}-{atom2.GetSymbol()})\n"
|
|
3105
|
+
)
|
|
3106
|
+
|
|
3107
|
+
raise UndefinedStereochemistryError(err_msg_prefix + msg)
|
|
3108
|
+
|
|
3109
|
+
@staticmethod
|
|
3110
|
+
def _constrain_end_directions(*values: int, bond_indices: list[int], flip_direction: dict[int, bool]) -> bool:
|
|
3111
|
+
"""A constraint applied when mapping global E/Z stereochemistry into local RDKit
|
|
3112
|
+
bond directions that ensures that the 'left' bonds point in opposite directions
|
|
3113
|
+
(i.e. one has to be up and one has to be down) and likewise for the 'right' bonds
|
|
3114
|
+
"""
|
|
3115
|
+
# Account for bond "direction" using flip_directions dict, see more thorough comment
|
|
3116
|
+
# in _constrain_rank for details.
|
|
3117
|
+
bond_directions = [(value if not flip_direction[i] else 1 - value) for i, value in zip(bond_indices, values)]
|
|
3118
|
+
unique_bond_directions = set(bond_directions)
|
|
3119
|
+
return len(unique_bond_directions) == len(values)
|
|
3120
|
+
|
|
3121
|
+
@staticmethod
|
|
3122
|
+
def _constrain_rank(
|
|
3123
|
+
*values: int,
|
|
3124
|
+
bond_indices: list[int],
|
|
3125
|
+
flip_direction: dict[int, bool],
|
|
3126
|
+
expected_stereo: str,
|
|
3127
|
+
) -> bool:
|
|
3128
|
+
"""A constraint applied when mapping global E/Z stereochemistry into local RDKit
|
|
3129
|
+
bond directions that ensures that the 'left' bond with the highest CIP rank
|
|
3130
|
+
and the 'right' bond with the highest CIP rank point either in the same direction
|
|
3131
|
+
if Z stereo or opposite directions if E.
|
|
3132
|
+
"""
|
|
3133
|
+
# The "value" for each bond is ultimately set to either 0 (down) or 1 (up).
|
|
3134
|
+
# However, we also need to know the "direction" of the bond to make sense
|
|
3135
|
+
# of this - Is it coming FROM, or going TO this double bond while going down or up?
|
|
3136
|
+
# This information is in the flipped_values dict. This code assumes that the
|
|
3137
|
+
# "normal" case is when the neighboring bonds are coming FROM the double bond,
|
|
3138
|
+
# and where that's not true, the following line switches the
|
|
3139
|
+
# meaning of "down" and "up" to give us the desired meaning.
|
|
3140
|
+
bond_directions = [(value if not flip_direction[i] else 1 - value) for i, value in zip(bond_indices, values)]
|
|
3141
|
+
|
|
3142
|
+
# Test for equality of items in flipped_values by turning it into a set and
|
|
3143
|
+
# counting how many values remain.
|
|
3144
|
+
unique_bond_directions = set(bond_directions)
|
|
3145
|
+
if expected_stereo == "E":
|
|
3146
|
+
return len(unique_bond_directions) == min(2, len(bond_indices))
|
|
3147
|
+
elif expected_stereo == "Z":
|
|
3148
|
+
return len(unique_bond_directions) == 1
|
|
3149
|
+
else:
|
|
3150
|
+
raise NotImplementedError()
|
|
3151
|
+
|
|
3152
|
+
@classmethod
|
|
3153
|
+
def _assign_rdmol_bonds_stereo(cls, off_molecule: "Molecule", rd_molecule):
|
|
3154
|
+
"""Copy the info about bonds stereochemistry from the OFF Molecule to RDKit Mol.
|
|
3155
|
+
The method proceeds by formulating mapping global E/Z stereo information onto
|
|
3156
|
+
local 'bond directions' as a constraint satisfaction problem (CSP).
|
|
3157
|
+
In this formalism, the variables correspond to the indices of the bonds
|
|
3158
|
+
neighbouring a stereogenic bond, the domain for each variable is 0 (down)
|
|
3159
|
+
or 1 (up), and the constraints are designed to ensure the correct E/Z stereo
|
|
3160
|
+
is yielded after assignment of the directions.
|
|
3161
|
+
"""
|
|
3162
|
+
from constraint import Problem
|
|
3163
|
+
from rdkit import Chem
|
|
3164
|
+
|
|
3165
|
+
_RD_STEREO_TO_STR = {
|
|
3166
|
+
Chem.BondStereo.STEREOE: "E",
|
|
3167
|
+
Chem.BondStereo.STEREOZ: "Z",
|
|
3168
|
+
}
|
|
3169
|
+
|
|
3170
|
+
stereogenic_bonds = [bond for bond in off_molecule.bonds if bond.stereochemistry]
|
|
3171
|
+
|
|
3172
|
+
if len(stereogenic_bonds) == 0:
|
|
3173
|
+
return
|
|
3174
|
+
|
|
3175
|
+
# Needed to ensure the _CIPRank is present. Note that, despite the kwargs that look like
|
|
3176
|
+
# they could mangle existing stereo, it is actually preserved.
|
|
3177
|
+
Chem.AssignStereochemistry(rd_molecule, cleanIt=True, force=True, flagPossibleStereoCenters=True)
|
|
3178
|
+
|
|
3179
|
+
csp_problem = Problem()
|
|
3180
|
+
csp_variables = set()
|
|
3181
|
+
|
|
3182
|
+
for bond in stereogenic_bonds:
|
|
3183
|
+
# Here we use a notation where atoms 'b' and 'c' are the two atoms involved
|
|
3184
|
+
# in the double bond, while 'a' corresponds to a neighbour of 'b' and 'd' a
|
|
3185
|
+
# neighbour of 'c'.
|
|
3186
|
+
atom_b, atom_c = bond.atom1, bond.atom2
|
|
3187
|
+
index_b, index_c = atom_b.molecule_atom_index, atom_c.molecule_atom_index
|
|
3188
|
+
|
|
3189
|
+
indices_a = [n.molecule_atom_index for n in atom_b.bonded_atoms if n != atom_c]
|
|
3190
|
+
indices_d = [n.molecule_atom_index for n in atom_c.bonded_atoms if n != atom_b]
|
|
3191
|
+
# A stereogenic double bond should either involve atoms with degree 3
|
|
3192
|
+
# (e.g. carbon) or degree 2 (e.g. divalent nitrogen).
|
|
3193
|
+
assert 1 <= len(indices_a) <= 2 and 1 <= len(indices_d) <= 2
|
|
3194
|
+
|
|
3195
|
+
# Identify the highest CIP-ranked bond coming off each side of the double
|
|
3196
|
+
# bond. This lets us later add a constraint to ensure that we have the
|
|
3197
|
+
# correct E/Z stereochemistry
|
|
3198
|
+
ranks_a = [int(rd_molecule.GetAtomWithIdx(i).GetProp("_CIPRank")) for i in indices_a]
|
|
3199
|
+
index_a = indices_a[np.argmax(ranks_a)]
|
|
3200
|
+
ranks_d = [int(rd_molecule.GetAtomWithIdx(i).GetProp("_CIPRank")) for i in indices_d]
|
|
3201
|
+
index_d = indices_d[np.argmax(ranks_d)]
|
|
3202
|
+
|
|
3203
|
+
index_ab = rd_molecule.GetBondBetweenAtoms(index_a, index_b).GetIdx()
|
|
3204
|
+
index_cd = rd_molecule.GetBondBetweenAtoms(index_c, index_d).GetIdx()
|
|
3205
|
+
|
|
3206
|
+
flip_direction = {}
|
|
3207
|
+
|
|
3208
|
+
# Collect lists of the indices of the bonds that appear to the 'left' of
|
|
3209
|
+
# and 'right' of the stereogenic bond so we can constrain their directions
|
|
3210
|
+
# so that all 'left' bonds do not, for example, point up.
|
|
3211
|
+
constraints_ab: list[int] = []
|
|
3212
|
+
constraints_cd: list[int] = []
|
|
3213
|
+
|
|
3214
|
+
for index_pair, constraints_list in [((index_a, index_b), constraints_ab) for index_a in indices_a] + [
|
|
3215
|
+
((index_d, index_c), constraints_cd) for index_d in indices_d
|
|
3216
|
+
]:
|
|
3217
|
+
# Each single bond neighboring a double bond needs to be defined as a
|
|
3218
|
+
# "variable" in the CSP problem. Here, each bond is identified by its
|
|
3219
|
+
# bond index in the RDMol (note: this is not guaranteed to be the same
|
|
3220
|
+
# as the corresponding bond's index in the OFFMol). This also ensures
|
|
3221
|
+
# that we don't define the same bond twice.
|
|
3222
|
+
rd_bond = rd_molecule.GetBondBetweenAtoms(*index_pair)
|
|
3223
|
+
rd_bond_index = rd_bond.GetIdx()
|
|
3224
|
+
|
|
3225
|
+
if rd_bond_index not in csp_variables:
|
|
3226
|
+
csp_problem.addVariable(rd_bond_index, [1, 0]) # 0 = down, 1 = up
|
|
3227
|
+
csp_variables.add(rd_bond_index)
|
|
3228
|
+
|
|
3229
|
+
# The direction of the bond should point from the double bond to its
|
|
3230
|
+
# neighbour. If the bond is pointing from the neighbour to the double
|
|
3231
|
+
# bond instead, we need to flip the direction of the bond. See
|
|
3232
|
+
# rdkit/Code/GraphMol/Chirality.cpp:findAtomNeighborDirHelper for more
|
|
3233
|
+
# details.
|
|
3234
|
+
flip_direction[rd_bond_index] = rd_bond.GetBeginAtomIdx() != index_pair[1]
|
|
3235
|
+
constraints_list.append(rd_bond_index)
|
|
3236
|
+
|
|
3237
|
+
# Add one constraint corresponding to the highest-ranked bond on OPPOSITE
|
|
3238
|
+
# sides of the double bond, to ensure that they are oriented up/down to
|
|
3239
|
+
# achieve the correct E/Z value of the double bond.
|
|
3240
|
+
csp_problem.addConstraint(
|
|
3241
|
+
functools.partial(
|
|
3242
|
+
cls._constrain_rank,
|
|
3243
|
+
bond_indices=[index_ab, index_cd],
|
|
3244
|
+
flip_direction=flip_direction,
|
|
3245
|
+
expected_stereo=bond.stereochemistry,
|
|
3246
|
+
),
|
|
3247
|
+
[index_ab, index_cd],
|
|
3248
|
+
)
|
|
3249
|
+
# Add constraint(s) corresponding ALL bonds on the SAME side of the double
|
|
3250
|
+
# bond, to ensure that they do not all take the same value (if one is "up",
|
|
3251
|
+
# the other can not also be "up").
|
|
3252
|
+
csp_problem.addConstraint(
|
|
3253
|
+
functools.partial(
|
|
3254
|
+
cls._constrain_end_directions,
|
|
3255
|
+
bond_indices=constraints_ab,
|
|
3256
|
+
flip_direction=flip_direction,
|
|
3257
|
+
),
|
|
3258
|
+
constraints_ab,
|
|
3259
|
+
)
|
|
3260
|
+
csp_problem.addConstraint(
|
|
3261
|
+
functools.partial(
|
|
3262
|
+
cls._constrain_end_directions,
|
|
3263
|
+
bond_indices=constraints_cd,
|
|
3264
|
+
flip_direction=flip_direction,
|
|
3265
|
+
),
|
|
3266
|
+
constraints_cd,
|
|
3267
|
+
)
|
|
3268
|
+
|
|
3269
|
+
# Do not assume that every solution found by the solver is valid.
|
|
3270
|
+
# Iterate through the solutions and ensure that the
|
|
3271
|
+
# desired E/Z marks have really been achieved.
|
|
3272
|
+
has_solution = False
|
|
3273
|
+
|
|
3274
|
+
for solution in csp_problem.getSolutionIter():
|
|
3275
|
+
for rd_bond_index, direction in solution.items():
|
|
3276
|
+
rd_bond = rd_molecule.GetBondWithIdx(rd_bond_index)
|
|
3277
|
+
if direction == 0:
|
|
3278
|
+
rd_bond.SetBondDir(Chem.BondDir.ENDDOWNRIGHT)
|
|
3279
|
+
elif direction == 1:
|
|
3280
|
+
rd_bond.SetBondDir(Chem.BondDir.ENDUPRIGHT)
|
|
3281
|
+
else:
|
|
3282
|
+
raise NotImplementedError()
|
|
3283
|
+
|
|
3284
|
+
Chem.AssignStereochemistry(rd_molecule, cleanIt=True, force=True)
|
|
3285
|
+
|
|
3286
|
+
# Verify that there are no stereo mismatches between the original
|
|
3287
|
+
# OFFMol and the newly-assigned RDMol
|
|
3288
|
+
stereo_mismatch = False
|
|
3289
|
+
for off_bond in stereogenic_bonds:
|
|
3290
|
+
rd_bond = rd_molecule.GetBondBetweenAtoms(off_bond.atom1_index, off_bond.atom2_index)
|
|
3291
|
+
rd_stereo_string = _RD_STEREO_TO_STR.get(rd_bond.GetStereo(), None)
|
|
3292
|
+
if off_bond.stereochemistry != rd_stereo_string:
|
|
3293
|
+
stereo_mismatch = True
|
|
3294
|
+
break
|
|
3295
|
+
|
|
3296
|
+
if stereo_mismatch:
|
|
3297
|
+
continue
|
|
3298
|
+
|
|
3299
|
+
has_solution = True
|
|
3300
|
+
break
|
|
3301
|
+
|
|
3302
|
+
assert has_solution, "E/Z stereo could not be converted to local stereo"
|