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.
Files changed (231) hide show
  1. devtools/scripts/build_cookiecutter_json.py +22 -0
  2. docs/conf.py +296 -0
  3. docs/conftest.py +23 -0
  4. examples/conformer_energies/conformer_energies.py +143 -0
  5. examples/deprecated/SMIRNOFF_comparison/compare_molecule_energies.py +48 -0
  6. examples/deprecated/SMIRNOFF_comparison/compare_set_energies.py +58 -0
  7. examples/deprecated/liquid_box/create_mol2_pdb/create_mol2_pdb.py +193 -0
  8. examples/deprecated/liquid_box/openff_simulation.py +72 -0
  9. examples/deprecated/mixedFF_structure/generate_mixedFF_complex.py +56 -0
  10. examples/deprecated/testing/test_impropers/tleap_tools.py +120 -0
  11. examples/examples_helper.py +61 -0
  12. openff/toolkit/__init__.py +101 -0
  13. openff/toolkit/_tests/__init__.py +0 -0
  14. openff/toolkit/_tests/_stale_tests.py +146 -0
  15. openff/toolkit/_tests/conftest.py +108 -0
  16. openff/toolkit/_tests/create_molecules.py +494 -0
  17. openff/toolkit/_tests/mocking.py +145 -0
  18. openff/toolkit/_tests/molecule/__init__.py +1 -0
  19. openff/toolkit/_tests/molecule/test_state_enumeration.py +302 -0
  20. openff/toolkit/_tests/test_energies.py +136 -0
  21. openff/toolkit/_tests/test_examples.py +109 -0
  22. openff/toolkit/_tests/test_forcefield.py +3864 -0
  23. openff/toolkit/_tests/test_interchange.py +19 -0
  24. openff/toolkit/_tests/test_io.py +19 -0
  25. openff/toolkit/_tests/test_links.py +73 -0
  26. openff/toolkit/_tests/test_mm_molecule.py +404 -0
  27. openff/toolkit/_tests/test_molecule.py +4246 -0
  28. openff/toolkit/_tests/test_nagl.py +169 -0
  29. openff/toolkit/_tests/test_parameter_plugins.py +89 -0
  30. openff/toolkit/_tests/test_parameters.py +2898 -0
  31. openff/toolkit/_tests/test_toolkit_io.py +1088 -0
  32. openff/toolkit/_tests/test_toolkits.py +4418 -0
  33. openff/toolkit/_tests/test_topology.py +2485 -0
  34. openff/toolkit/_tests/test_utils.py +101 -0
  35. openff/toolkit/_tests/test_utils_callback.py +178 -0
  36. openff/toolkit/_tests/test_utils_collections.py +263 -0
  37. openff/toolkit/_tests/test_utils_serialization.py +168 -0
  38. openff/toolkit/_tests/utils.py +1747 -0
  39. openff/toolkit/data/README.md +8 -0
  40. openff/toolkit/data/molecules/AlkEthOH_test_filt1_ff.mol2 +2026 -0
  41. openff/toolkit/data/molecules/AlkEthOH_test_filt1_tripos.mol2 +2026 -0
  42. openff/toolkit/data/molecules/AlkEthOH_tripos.tar.gz +0 -0
  43. openff/toolkit/data/molecules/CID20742535_anion.sdf +50 -0
  44. openff/toolkit/data/molecules/CID20742535_neutral.sdf +51 -0
  45. openff/toolkit/data/molecules/FreeSolv.tar.gz +0 -0
  46. openff/toolkit/data/molecules/MiniDrugBank.sdf +33988 -0
  47. openff/toolkit/data/molecules/MiniDrugBank_tripos.mol2 +35462 -0
  48. openff/toolkit/data/molecules/PT2385.sdf +90 -0
  49. openff/toolkit/data/molecules/QL8.sdf +401 -0
  50. openff/toolkit/data/molecules/README.md +21 -0
  51. openff/toolkit/data/molecules/benzene.crd +8 -0
  52. openff/toolkit/data/molecules/benzene.mol2 +34 -0
  53. openff/toolkit/data/molecules/benzene.top +166 -0
  54. openff/toolkit/data/molecules/butane_multi.sdf +231 -0
  55. openff/toolkit/data/molecules/cyclohexane.mol2 +44 -0
  56. openff/toolkit/data/molecules/ethanol.mol2 +25 -0
  57. openff/toolkit/data/molecules/ethanol.sdf +23 -0
  58. openff/toolkit/data/molecules/ethanol_partial_charges.sdf +26 -0
  59. openff/toolkit/data/molecules/ethanol_reordered.mol2 +25 -0
  60. openff/toolkit/data/molecules/ethanol_reordered.sdf +23 -0
  61. openff/toolkit/data/molecules/ethene_rdkit.sdf +17 -0
  62. openff/toolkit/data/molecules/laromustine_ff.mol2 +71 -0
  63. openff/toolkit/data/molecules/laromustine_tripos.mol2 +71 -0
  64. openff/toolkit/data/molecules/methane_multiconformer.sdf +32 -0
  65. openff/toolkit/data/molecules/methane_multiconformer_properties.sdf +45 -0
  66. openff/toolkit/data/molecules/nh4.pdb +7 -0
  67. openff/toolkit/data/molecules/po4_phenylphosphate.pdb +46 -0
  68. openff/toolkit/data/molecules/ruxolitinib_conformers.sdf +910 -0
  69. openff/toolkit/data/molecules/toluene.mol2 +38 -0
  70. openff/toolkit/data/molecules/toluene.mol2.gz +0 -0
  71. openff/toolkit/data/molecules/toluene.pdb +30 -0
  72. openff/toolkit/data/molecules/toluene.sdf +36 -0
  73. openff/toolkit/data/molecules/toluene_charged.mol2 +38 -0
  74. openff/toolkit/data/molecules/z_3_hydroxy_propenal.sdf +23 -0
  75. openff/toolkit/data/proteins/5tbm_complex_solv.pdb +1928 -0
  76. openff/toolkit/data/proteins/5tbm_complex_solv_box.pdb +19563 -0
  77. openff/toolkit/data/proteins/CTerminal_ALA.pdb +20 -0
  78. openff/toolkit/data/proteins/CTerminal_ALA.sdf +43 -0
  79. openff/toolkit/data/proteins/CTerminal_ALA_ALA.pdb +30 -0
  80. openff/toolkit/data/proteins/CTerminal_ALA_ALA_misnamedH.pdb +30 -0
  81. openff/toolkit/data/proteins/CTerminal_ARG.pdb +34 -0
  82. openff/toolkit/data/proteins/CTerminal_TRP.pdb +34 -0
  83. openff/toolkit/data/proteins/MainChain_ALA.pdb +25 -0
  84. openff/toolkit/data/proteins/MainChain_ALA.sdf +52 -0
  85. openff/toolkit/data/proteins/MainChain_ALA_ALA.pdb +35 -0
  86. openff/toolkit/data/proteins/MainChain_ALA_ALA.sdf +69 -0
  87. openff/toolkit/data/proteins/MainChain_ALA_ALA_icodes.pdb +35 -0
  88. openff/toolkit/data/proteins/MainChain_ALA_ALA_no_hydrogens.pdb +17 -0
  89. openff/toolkit/data/proteins/MainChain_ARG.pdb +39 -0
  90. openff/toolkit/data/proteins/MainChain_ARG.sdf +81 -0
  91. openff/toolkit/data/proteins/MainChain_CYM.pdb +25 -0
  92. openff/toolkit/data/proteins/MainChain_CYS.pdb +26 -0
  93. openff/toolkit/data/proteins/MainChain_CYX.pdb +48 -0
  94. openff/toolkit/data/proteins/MainChain_CYX.sdf +96 -0
  95. openff/toolkit/data/proteins/MainChain_GLH.sdf +64 -0
  96. openff/toolkit/data/proteins/MainChain_GLU.sdf +63 -0
  97. openff/toolkit/data/proteins/MainChain_HID.pdb +32 -0
  98. openff/toolkit/data/proteins/MainChain_HIE.pdb +32 -0
  99. openff/toolkit/data/proteins/MainChain_HIE.sdf +67 -0
  100. openff/toolkit/data/proteins/MainChain_HIP.pdb +33 -0
  101. openff/toolkit/data/proteins/MainChain_HIP.sdf +70 -0
  102. openff/toolkit/data/proteins/MainChain_PRO.pdb +29 -0
  103. openff/toolkit/data/proteins/MainChain_TRP.pdb +39 -0
  104. openff/toolkit/data/proteins/NTerminal_ALA.pdb +21 -0
  105. openff/toolkit/data/proteins/NTerminal_ALA.sdf +45 -0
  106. openff/toolkit/data/proteins/NTerminal_ALA_ALA.pdb +31 -0
  107. openff/toolkit/data/proteins/NTerminal_ARG.pdb +35 -0
  108. openff/toolkit/data/proteins/NTerminal_TRP.pdb +35 -0
  109. openff/toolkit/data/proteins/T4-protein-unprocessed-4w51.pdb +1892 -0
  110. openff/toolkit/data/proteins/T4-protein.mol2 +5461 -0
  111. openff/toolkit/data/proteins/T4-protein.pdb +2637 -0
  112. openff/toolkit/data/proteins/T4-protein.sdf +5318 -0
  113. openff/toolkit/data/proteins/T4_protein_waters.pdb +2965 -0
  114. openff/toolkit/data/proteins/TwoMol_SER_CYS.pdb +50 -0
  115. openff/toolkit/data/proteins/aa_residues_substructures_explicit_bond_orders_with_caps.json +6435 -0
  116. openff/toolkit/data/proteins/aa_residues_substructures_explicit_bond_orders_with_caps_explicit_connectivity.json +6675 -0
  117. openff/toolkit/data/proteins/aa_residues_substructures_with_caps.json +6297 -0
  118. openff/toolkit/data/proteins/ace-ZZZ-gly-nme.pdb +78 -0
  119. openff/toolkit/data/proteins/ace-ZZZ-gly-nme.sdf +98 -0
  120. openff/toolkit/data/proteins/ace-a10-nme.sdf +229 -0
  121. openff/toolkit/data/proteins/ace-ala-nh2.pdb +21 -0
  122. openff/toolkit/data/proteins/fluoresceine_dyed_helix_capped.pdb +338 -0
  123. openff/toolkit/data/proteins/neutral_arginine.pdb +31 -0
  124. openff/toolkit/data/proteins/split_chain.pdb +74 -0
  125. openff/toolkit/data/proteins/split_chain_reordered.pdb +74 -0
  126. openff/toolkit/data/reference_energies/README.md +6 -0
  127. openff/toolkit/data/reference_energies/reference_0.8.0.json +1 -0
  128. openff/toolkit/data/reference_energies/reference_0.8.0.json.txt +180 -0
  129. openff/toolkit/data/reference_energies/reference_after_1007.json +1 -0
  130. openff/toolkit/data/reference_energies/reference_after_1007.json.txt +350 -0
  131. openff/toolkit/data/reference_energies/reference_after_802.json +1 -0
  132. openff/toolkit/data/reference_energies/reference_after_802.json.txt +291 -0
  133. openff/toolkit/data/systems/README.md +3 -0
  134. openff/toolkit/data/systems/amber/cyclohexane_ethanol_0.4_0.6.inpcrd +1511 -0
  135. openff/toolkit/data/systems/amber/cyclohexane_ethanol_0.4_0.6.prmtop +13367 -0
  136. openff/toolkit/data/systems/monomers/butanol.mol2 +38 -0
  137. openff/toolkit/data/systems/monomers/butanol.sdf +88 -0
  138. openff/toolkit/data/systems/monomers/cyclohexane.mol2 +45 -0
  139. openff/toolkit/data/systems/monomers/cyclohexane.sdf +105 -0
  140. openff/toolkit/data/systems/monomers/ethanol.mol2 +26 -0
  141. openff/toolkit/data/systems/monomers/ethanol.sdf +58 -0
  142. openff/toolkit/data/systems/monomers/methane.mol2 +18 -0
  143. openff/toolkit/data/systems/monomers/methane.sdf +38 -0
  144. openff/toolkit/data/systems/monomers/propane.mol2 +30 -0
  145. openff/toolkit/data/systems/monomers/propane.sdf +68 -0
  146. openff/toolkit/data/systems/monomers/tip3p_water.mol2 +14 -0
  147. openff/toolkit/data/systems/monomers/water.mol2 +14 -0
  148. openff/toolkit/data/systems/monomers/water.sdf +28 -0
  149. openff/toolkit/data/systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb +6272 -0
  150. openff/toolkit/data/systems/packmol_boxes/cyclohexane_water.pdb +5524 -0
  151. openff/toolkit/data/systems/packmol_boxes/ethanol_water.pdb +5174 -0
  152. openff/toolkit/data/systems/packmol_boxes/propane_methane_butanol_0.2_0.3_0.5.pdb +7959 -0
  153. openff/toolkit/data/systems/test_systems/1_cyclohexane_1_ethanol.pdb +61 -0
  154. openff/toolkit/data/systems/test_systems/1_ethanol.pdb +24 -0
  155. openff/toolkit/data/systems/test_systems/1_ethanol_no_conect.pdb +15 -0
  156. openff/toolkit/data/systems/test_systems/1_ethanol_reordered.pdb +24 -0
  157. openff/toolkit/data/systems/test_systems/PE.pdb +67 -0
  158. openff/toolkit/data/systems/test_systems/README.md +3 -0
  159. openff/toolkit/data/systems/test_systems/T4_lysozyme_water_ions.pdb +29240 -0
  160. openff/toolkit/data/test_forcefields/Frosst_AlkEthOH.offxml +61 -0
  161. openff/toolkit/data/test_forcefields/Frosst_AlkEthOH_GBSA.offxml +78 -0
  162. openff/toolkit/data/test_forcefields/Frosst_AlkEthOH_MDL.offxml +62 -0
  163. openff/toolkit/data/test_forcefields/Frosst_AlkEthOH_parmAtFrosst.offxml +64 -0
  164. openff/toolkit/data/test_forcefields/GBSA_HCT-1.0.offxml +21 -0
  165. openff/toolkit/data/test_forcefields/GBSA_OBC1-1.0.offxml +18 -0
  166. openff/toolkit/data/test_forcefields/GBSA_OBC2-1.0.offxml +18 -0
  167. openff/toolkit/data/test_forcefields/README.md +23 -0
  168. openff/toolkit/data/test_forcefields/ammonia_minimal.offxml +27 -0
  169. openff/toolkit/data/test_forcefields/benzene_minimal.offxml +29 -0
  170. openff/toolkit/data/test_forcefields/chargeincrement-test.offxml +16 -0
  171. openff/toolkit/data/test_forcefields/frcmod.Frosst_AlkEthOH_withIDs +85 -0
  172. openff/toolkit/data/test_forcefields/ion_charges.offxml +18 -0
  173. openff/toolkit/data/test_forcefields/mangled.offxml +9 -0
  174. openff/toolkit/data/test_forcefields/old/README.md +9 -0
  175. openff/toolkit/data/test_forcefields/old/hbonds.offxml +11 -0
  176. openff/toolkit/data/test_forcefields/old/test_ff_0_0_2_spec_0_1.offxml +332 -0
  177. openff/toolkit/data/test_forcefields/old/test_ff_0_0_2_spec_0_2.offxml +338 -0
  178. openff/toolkit/data/test_forcefields/old/test_ff_0_0_2_spec_0_3.offxml +329 -0
  179. openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_fixed_spec_0_1.offxml +342 -0
  180. openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_fixed_spec_0_2.offxml +348 -0
  181. openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_fixed_spec_0_3.offxml +337 -0
  182. openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_spec_0_1.offxml +340 -0
  183. openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_spec_0_2.offxml +346 -0
  184. openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_spec_0_3.offxml +337 -0
  185. openff/toolkit/data/test_forcefields/smirff99Frosst_reference_0_1_spec.offxml +349 -0
  186. openff/toolkit/data/test_forcefields/smirnoff99Frosst_experimental.offxml +343 -0
  187. openff/toolkit/data/test_forcefields/smirnoff99Frosst_reference_0_1_spec.offxml +349 -0
  188. openff/toolkit/data/test_forcefields/smirnoff99Frosst_reference_0_2_spec.offxml +356 -0
  189. openff/toolkit/data/test_forcefields/test_forcefield.offxml +346 -0
  190. openff/toolkit/data/test_forcefields/tip3p.offxml +22 -0
  191. openff/toolkit/data/test_forcefields/unsupported_smirnoff_version.offxml +9 -0
  192. openff/toolkit/topology/__init__.py +43 -0
  193. openff/toolkit/topology/_mm_molecule.py +663 -0
  194. openff/toolkit/topology/molecule.py +6102 -0
  195. openff/toolkit/topology/topology.py +2555 -0
  196. openff/toolkit/typing/__init__.py +1 -0
  197. openff/toolkit/typing/engines/__init__.py +1 -0
  198. openff/toolkit/typing/engines/smirnoff/__init__.py +31 -0
  199. openff/toolkit/typing/engines/smirnoff/forcefield.py +1440 -0
  200. openff/toolkit/typing/engines/smirnoff/io.py +234 -0
  201. openff/toolkit/typing/engines/smirnoff/parameters.py +3839 -0
  202. openff/toolkit/typing/engines/smirnoff/plugins.py +91 -0
  203. openff/toolkit/utils/__init__.py +57 -0
  204. openff/toolkit/utils/_viz.py +104 -0
  205. openff/toolkit/utils/ambertools_wrapper.py +507 -0
  206. openff/toolkit/utils/base_wrapper.py +268 -0
  207. openff/toolkit/utils/builtin_wrapper.py +136 -0
  208. openff/toolkit/utils/callback.py +187 -0
  209. openff/toolkit/utils/collections.py +247 -0
  210. openff/toolkit/utils/constants.py +18 -0
  211. openff/toolkit/utils/exceptions.py +766 -0
  212. openff/toolkit/utils/nagl_wrapper.py +164 -0
  213. openff/toolkit/utils/openeye_wrapper.py +2750 -0
  214. openff/toolkit/utils/rdkit_wrapper.py +3302 -0
  215. openff/toolkit/utils/serialization.py +466 -0
  216. openff/toolkit/utils/toolkit_registry.py +509 -0
  217. openff/toolkit/utils/toolkits.py +217 -0
  218. openff/toolkit/utils/utils.py +805 -0
  219. openff_toolkit-0.18.0.dist-info/METADATA +109 -0
  220. openff_toolkit-0.18.0.dist-info/RECORD +231 -0
  221. openff_toolkit-0.18.0.dist-info/WHEEL +5 -0
  222. openff_toolkit-0.18.0.dist-info/licenses/LICENSE +21 -0
  223. openff_toolkit-0.18.0.dist-info/top_level.txt +5 -0
  224. utilities/deprecated/convert_frosst/convert_frcmod_0.1.py +251 -0
  225. utilities/deprecated/convert_frosst/convert_frcmod_0.2.py +249 -0
  226. utilities/deprecated/convert_frosst/convert_frcmod_0.3.py +249 -0
  227. utilities/make_substructure_dict/_cif_to_substructure_dict.py +955 -0
  228. utilities/make_substructure_dict/_make_chemical_substructures.py +46 -0
  229. utilities/make_substructure_dict/_make_metadata_assignment_substructures.py +35 -0
  230. utilities/test_plugins/custom_plugins/handler_plugins.py +48 -0
  231. utilities/test_plugins/setup.py +19 -0
@@ -0,0 +1,2750 @@
1
+ """
2
+ Wrapper class providing a minimal consistent interface to
3
+ the `OpenEye Toolkit <https://docs.eyesopen.com/toolkits/python/quickstart-python/index.html>`_
4
+ """
5
+
6
+ __all__ = ("OpenEyeToolkitWrapper",)
7
+
8
+
9
+ # See https://github.com/conda-forge/openff-toolkit-feedstock/issues/86
10
+ try:
11
+ import zstandard # noqa
12
+ except ImportError:
13
+ pass
14
+ import importlib
15
+ import logging
16
+ import pathlib
17
+ import re
18
+ import tempfile
19
+ import warnings
20
+ from collections import defaultdict
21
+ from functools import wraps
22
+ from typing import TYPE_CHECKING, Any, TypeAlias
23
+
24
+ import numpy as np
25
+ from cachetools import LRUCache, cached
26
+ from openff.units.elements import SYMBOLS
27
+
28
+ from openff.toolkit import Quantity, unit
29
+ from openff.toolkit.utils.base_wrapper import (
30
+ ToolkitWrapper,
31
+ _ChargeSettings,
32
+ _mol_to_ctab_and_aro_key,
33
+ )
34
+ from openff.toolkit.utils.constants import (
35
+ ALLOWED_AROMATICITY_MODELS,
36
+ DEFAULT_AROMATICITY_MODEL,
37
+ )
38
+ from openff.toolkit.utils.exceptions import (
39
+ ChargeCalculationError,
40
+ ChargeMethodUnavailableError,
41
+ ConformerGenerationError,
42
+ EmptyInChiError,
43
+ GAFFAtomTypeWarning,
44
+ InChIParseError,
45
+ InconsistentStereochemistryError,
46
+ InvalidAromaticityModelError,
47
+ InvalidIUPACNameError,
48
+ LicenseError,
49
+ MultipleComponentsInMoleculeWarning,
50
+ NotAttachedToMoleculeError,
51
+ OpenEyeError,
52
+ OpenEyeImportError,
53
+ RadicalsNotSupportedError,
54
+ SMILESParseError,
55
+ ToolkitUnavailableException,
56
+ UnassignedChemistryInPDBError,
57
+ UndefinedStereochemistryError,
58
+ )
59
+ from openff.toolkit.utils.utils import inherit_docstrings
60
+
61
+ if TYPE_CHECKING:
62
+ import openmm.app
63
+
64
+ from openff.toolkit.topology.molecule import Atom, Bond, FrozenMolecule, Molecule
65
+
66
+
67
+ logger = logging.getLogger(__name__)
68
+
69
+
70
+ TTA: TypeAlias = tuple[tuple[Any, ...], ...]
71
+
72
+
73
+ def get_oeformat(file_format: str) -> str:
74
+ from openeye import oechem
75
+
76
+ file_format = file_format.upper()
77
+ # XXX This is what RDKit does. Should be supported here too?
78
+ if file_format == "MOL":
79
+ file_format = "SDF"
80
+
81
+ oeformat = getattr(oechem, "OEFormat_" + file_format, None)
82
+ if oeformat is None:
83
+ raise ValueError(f"Unsupported file format: {file_format}")
84
+ return oeformat
85
+
86
+
87
+ @inherit_docstrings
88
+ class OpenEyeToolkitWrapper(ToolkitWrapper):
89
+ """
90
+ OpenEye toolkit wrapper
91
+
92
+ .. warning :: This API is experimental and subject to change.
93
+ """
94
+
95
+ _toolkit_name = "OpenEye Toolkit"
96
+ _toolkit_installation_instructions = (
97
+ "The OpenEye Toolkits can be installed via `mamba install openeye-toolkits -c openeye`"
98
+ )
99
+ _toolkit_license_instructions = (
100
+ "The OpenEye Toolkits require a (free for academics) license, see "
101
+ "https://docs.eyesopen.com/toolkits/python/quickstart-python/license.html"
102
+ )
103
+ # This could belong to ToolkitWrapper, although it seems strange
104
+ # to carry that data for open-source toolkits
105
+ _is_licensed: bool | None = None
106
+ # Only for OpenEye is there potentially a difference between
107
+ # being available and installed
108
+ _is_installed: bool | None = None
109
+ _license_functions: dict[str, str] = {
110
+ "oechem": "OEChemIsLicensed",
111
+ "oequacpac": "OEQuacPacIsLicensed",
112
+ "oeiupac": "OEIUPACIsLicensed",
113
+ "oeomega": "OEOmegaIsLicensed",
114
+ }
115
+ _supported_charge_methods = {
116
+ "am1bcc": {
117
+ "oe_charge_method": "OEAM1BCCCharges",
118
+ "min_confs": 1,
119
+ "max_confs": 1,
120
+ "rec_confs": 1,
121
+ },
122
+ "am1-mulliken": {
123
+ "oe_charge_method": "OEAM1Charges",
124
+ "min_confs": 1,
125
+ "max_confs": 1,
126
+ "rec_confs": 1,
127
+ },
128
+ "gasteiger": {
129
+ "oe_charge_method": "OEGasteigerCharges",
130
+ "min_confs": 0,
131
+ "max_confs": 0,
132
+ "rec_confs": 0,
133
+ },
134
+ "mmff94": {
135
+ "oe_charge_method": "OEMMFF94Charges",
136
+ "min_confs": 0,
137
+ "max_confs": 0,
138
+ "rec_confs": 0,
139
+ },
140
+ "am1bccnosymspt": {
141
+ "oe_charge_method": "OEAM1BCCCharges",
142
+ "min_confs": 1,
143
+ "max_confs": 1,
144
+ "rec_confs": 1,
145
+ },
146
+ "am1elf10": {
147
+ "oe_charge_method": "OEELFCharges",
148
+ "min_confs": 1,
149
+ "max_confs": None, # type: ignore[typeddict-item]
150
+ "rec_confs": 500,
151
+ },
152
+ "am1bccelf10": {
153
+ "oe_charge_method": "OEAM1BCCELF10Charges",
154
+ "min_confs": 1,
155
+ "max_confs": None, # type: ignore[typeddict-item]
156
+ "rec_confs": 500,
157
+ },
158
+ }
159
+
160
+ SUPPORTED_CHARGE_METHODS = _supported_charge_methods
161
+
162
+ _toolkit_file_read_formats = [
163
+ "CAN",
164
+ "CDX",
165
+ "CSV",
166
+ "FASTA",
167
+ "INCHI",
168
+ "INCHIKEY",
169
+ "ISM",
170
+ "MDL",
171
+ "MF",
172
+ "MMOD",
173
+ "MOL2",
174
+ "MOL2H",
175
+ "MOPAC",
176
+ "OEB",
177
+ "PDB",
178
+ "RDF",
179
+ "SDF",
180
+ "SKC",
181
+ "SLN",
182
+ "SMI",
183
+ "USM",
184
+ "XYC",
185
+ ]
186
+ _toolkit_file_write_formats = [
187
+ "CAN",
188
+ "CDX",
189
+ "CSV",
190
+ "FASTA",
191
+ "INCHI",
192
+ "INCHIKEY",
193
+ "ISM",
194
+ "MDL",
195
+ "MF",
196
+ "MMOD",
197
+ "MOL2",
198
+ "MOL2H",
199
+ "MOPAC",
200
+ "OEB",
201
+ "PDB",
202
+ "RDF",
203
+ "SDF",
204
+ "SKC",
205
+ "SLN",
206
+ "SMI",
207
+ "USM",
208
+ "XYC",
209
+ ]
210
+
211
+ def __init__(self):
212
+ # check if the toolkit can be loaded
213
+ if not self.is_available():
214
+ if self._is_installed is False:
215
+ raise ToolkitUnavailableException(
216
+ "OpenEye Toolkits are not installed." + self._toolkit_installation_instructions
217
+ )
218
+ if self._is_licensed is False:
219
+ raise LicenseError(
220
+ "The OpenEye Toolkits are found to be installed but not licensed and "
221
+ + "therefore will not be used.\n"
222
+ + self._toolkit_license_instructions
223
+ )
224
+
225
+ from openeye import __version__ as openeye_version
226
+
227
+ self._toolkit_version = openeye_version
228
+
229
+ @classmethod
230
+ def _check_licenses(cls) -> bool:
231
+ """Check license of all known OpenEye tools. Returns True if any are found
232
+ to be licensed, False if all are not."""
233
+ for tool, license_func in cls._license_functions.items():
234
+ try:
235
+ module = importlib.import_module("openeye." + tool)
236
+ except ImportError:
237
+ continue
238
+ else:
239
+ if getattr(module, license_func)():
240
+ return True
241
+ return False
242
+
243
+ @classmethod
244
+ def is_available(cls) -> bool:
245
+ """
246
+ Check if the given OpenEye toolkit components are available.
247
+
248
+ If the OpenEye toolkit is not installed or no license is found
249
+ for at least one the required toolkits , ``False`` is returned.
250
+
251
+ Returns
252
+ -------
253
+ all_installed
254
+ ``True`` if all required OpenEye tools are installed and licensed,
255
+ ``False`` otherwise
256
+
257
+ """
258
+ if cls._is_available is None:
259
+ if cls._is_licensed is None:
260
+ cls._is_licensed = cls._check_licenses()
261
+ if cls._is_installed is None:
262
+ for tool in cls._license_functions.keys():
263
+ cls._is_installed = True
264
+ try:
265
+ importlib.import_module("openeye." + tool)
266
+ except ImportError:
267
+ cls._is_installed = False
268
+ if cls._is_installed:
269
+ if cls._is_licensed:
270
+ cls._is_available = True
271
+ else:
272
+ cls._is_available = False
273
+ cls._is_available = cls._is_installed and cls._is_licensed
274
+ return cls._is_available # type: ignore[return-value]
275
+
276
+ def from_object(
277
+ self,
278
+ obj,
279
+ allow_undefined_stereo: bool = False,
280
+ _cls=None,
281
+ ) -> "FrozenMolecule":
282
+ """
283
+ Convert an OEMol (or OEMol-derived object) into an openff.toolkit.topology.molecule
284
+
285
+ Parameters
286
+ ----------
287
+ obj
288
+ An object to by type-checked.
289
+ allow_undefined_stereo
290
+ Whether to accept molecules with undefined stereocenters. If False,
291
+ an exception will be raised if a molecule with undefined stereochemistry
292
+ is passed into this function.
293
+ _cls
294
+ Molecule constructor
295
+
296
+ Returns
297
+ -------
298
+ Molecule
299
+ An openff.toolkit.topology.molecule Molecule.
300
+
301
+ Raises
302
+ ------
303
+ NotImplementedError
304
+ If the object could not be converted into a Molecule.
305
+ """
306
+ # TODO: Add tests for the from_object functions
307
+ from openeye import oechem
308
+
309
+ if _cls is None:
310
+ from openff.toolkit.topology.molecule import Molecule
311
+
312
+ _cls = Molecule
313
+
314
+ if isinstance(obj, oechem.OEMolBase):
315
+ return self.from_openeye(
316
+ oemol=obj,
317
+ allow_undefined_stereo=allow_undefined_stereo,
318
+ _cls=_cls,
319
+ )
320
+ raise NotImplementedError(f"Cannot create Molecule from {type(obj)} object")
321
+
322
+ def _polymer_openmm_topology_to_offmol(self, mol_class, omm_top, substructure_dictionary):
323
+ oemol = self._polymer_openmm_topology_to_oemol(omm_top, substructure_dictionary)
324
+ offmol = mol_class.from_openeye(oemol, allow_undefined_stereo=True)
325
+ return offmol
326
+
327
+ def _polymer_openmm_topology_to_oemol(
328
+ self,
329
+ omm_top: "openmm.app.Topology",
330
+ substructure_library: dict[str, dict],
331
+ ):
332
+ """
333
+ Parameters
334
+ ----------
335
+ omm_top
336
+ OpenMM Topology loaded from PDB
337
+ substructure_library
338
+ A dictionary of substructures. substructure_library[aa_name] = list[tagged SMARTS, list[atom_names]]
339
+
340
+ Returns
341
+ -------
342
+ oemol
343
+ a new molecule with charges and bond order added
344
+ """
345
+ from openeye import oechem
346
+
347
+ oemol = self._get_connectivity_from_openmm_top(omm_top)
348
+
349
+ already_assigned_nodes = set()
350
+ already_assigned_edges = set()
351
+
352
+ # Keeping track of which atoms are matched where will help us with error
353
+ # messages
354
+ matches = defaultdict(list)
355
+
356
+ for res_name in substructure_library:
357
+ # TODO: This is a hack for the moment since we don't have a more sophisticated way to resolve clashes
358
+ # so it just does the biggest substructures first
359
+ sorted_substructure_smarts = sorted(substructure_library[res_name], key=len, reverse=True)
360
+ for substructure_smarts in sorted_substructure_smarts:
361
+ ss = self._fuzzy_query(substructure_smarts)
362
+ for match in ss.Match(oemol, True):
363
+ match_mol_atom_indices = [at.GetIdx() for at in match.GetTargetAtoms()]
364
+ for i in match_mol_atom_indices:
365
+ matches[i].append(res_name)
366
+
367
+ if any(m in already_assigned_nodes for m in match_mol_atom_indices) and (
368
+ res_name not in ["PEPTIDE_BOND", "DISULFIDE"]
369
+ ):
370
+ continue
371
+
372
+ for substructure_atom, mol_atom in zip(match.GetPatternAtoms(), match.GetTargetAtoms()):
373
+ mol_atom.SetFormalCharge(substructure_atom.GetFormalCharge())
374
+ # Set arbitrary initial stereochemistry to avoid
375
+ # spamming "undefined stereo" warnings. In the from_polymer_pdb
376
+ # code path, the "real stereo" will be assigned later by a
377
+ # call to _assign_aromaticity_and_stereo_from_3d.
378
+ neighs = [n for n in mol_atom.GetAtoms()]
379
+ mol_atom.SetStereo(neighs, oechem.OEAtomStereo_Tetra, oechem.OEAtomStereo_Left)
380
+
381
+ already_assigned_nodes.add(mol_atom.GetIdx())
382
+ for substructure_bond, mol_bond in zip(match.GetPatternBonds(), match.GetTargetBonds()):
383
+ mol_bond.SetOrder(substructure_bond.GetOrder())
384
+ already_assigned_edges.add(tuple(sorted([mol_bond.GetBgnIdx(), mol_bond.GetEndIdx()])))
385
+
386
+ oemol_n_atoms = len([*oemol.GetAtoms()])
387
+ unassigned_atoms = sorted(set(range(oemol_n_atoms)) - already_assigned_nodes)
388
+
389
+ all_bonds = set([tuple(sorted([bond.GetBgnIdx(), bond.GetEndIdx()])) for bond in oemol.GetBonds()])
390
+ unassigned_bonds = sorted(all_bonds - already_assigned_edges)
391
+
392
+ if unassigned_atoms or unassigned_bonds:
393
+ # Some advanced error reporting needs to interpret the substructure smarts to do things like
394
+ # compare atom counts. Since OFFTK doesn't have a native class to hold fragments, we convert
395
+ # the smarts into a sorted list of symbols to help with generating the error message.
396
+ resname_to_symbols_and_atomnames: dict[str, list[tuple]] = {}
397
+ for resname, smarts_to_atom_names in substructure_library.items():
398
+ resname_to_symbols_and_atomnames[resname] = list()
399
+ for smarts, atom_names in smarts_to_atom_names.items():
400
+ qmol = oechem.OEQMol()
401
+ oechem.OEParseSmiles(qmol, smarts)
402
+ symbols = sorted([SYMBOLS[atom.GetAtomicNum()] for atom in qmol.GetAtoms()])
403
+ resname_to_symbols_and_atomnames[resname].append((symbols, atom_names))
404
+
405
+ raise UnassignedChemistryInPDBError(
406
+ substructure_library=resname_to_symbols_and_atomnames,
407
+ omm_top=omm_top,
408
+ unassigned_atoms=unassigned_atoms,
409
+ unassigned_bonds=unassigned_bonds,
410
+ matches=matches,
411
+ )
412
+
413
+ return oemol
414
+
415
+ def _get_connectivity_from_openmm_top(self, omm_top):
416
+ from openeye import oechem
417
+
418
+ oemol = oechem.OEMol()
419
+ # Add atoms
420
+ oemol_atoms = list() # list of corresponding oemol atoms
421
+ for atom in omm_top.atoms():
422
+ oeatom = oemol.NewAtom(atom.element.atomic_number)
423
+ oemol_atoms.append(oeatom)
424
+
425
+ # Add bonds
426
+ oemol_bonds = list() # list of corresponding oemol bonds
427
+ for bond in omm_top.bonds():
428
+ atom1_index = bond[0].index
429
+ atom2_index = bond[1].index
430
+ oebond = oemol.NewBond(oemol_atoms[atom1_index], oemol_atoms[atom2_index])
431
+ oemol_bonds.append(oebond)
432
+ return oemol
433
+
434
+ @staticmethod
435
+ def _fuzzy_query(query):
436
+ """return a copy of Query which is less specific:
437
+ - ignore aromaticity and hybridization of atoms (i.e. [#6] not C)
438
+ - ignore bond orders
439
+ - ignore formal charges
440
+ """
441
+ from openeye import oechem
442
+
443
+ from openff.toolkit.utils.exceptions import SMIRKSParsingError
444
+
445
+ # Jeff wasn't able to get this working with OEQMol and OEParseSmarts,
446
+ # the QMol/SS matching didn't behave correctly when set to AtomicNumber
447
+ qmol = oechem.OEMol()
448
+ status = oechem.OEParseSmiles(
449
+ qmol,
450
+ query,
451
+ )
452
+
453
+ if not status:
454
+ raise SMIRKSParsingError(f"OpenEye Toolkit was unable to parse SMIRKS {query}")
455
+ ss = oechem.OESubSearch(qmol, oechem.OEExprOpts_AtomicNumber, 0)
456
+ return ss
457
+
458
+ def from_file(
459
+ self,
460
+ file_path: str | pathlib.Path,
461
+ file_format: str,
462
+ allow_undefined_stereo: bool = False,
463
+ _cls=None,
464
+ ) -> list["FrozenMolecule"]:
465
+ """
466
+ Return an openff.toolkit.topology.Molecule from a file using this toolkit.
467
+
468
+ Parameters
469
+ ----------
470
+ file_path
471
+ The file to read the molecule from
472
+ file_format
473
+ Format specifier, usually file suffix (eg. 'MOL2', 'SMI')
474
+ Note that not all toolkits support all formats. Check ToolkitWrapper.toolkit_file_read_formats for details.
475
+ allow_undefined_stereo
476
+ If false, raises an exception if oemol contains undefined stereochemistry.
477
+ _cls
478
+ Molecule constructor
479
+
480
+ Returns
481
+ -------
482
+ molecules
483
+ The list of ``Molecule`` objects in the file.
484
+
485
+ Raises
486
+ ------
487
+ GAFFAtomTypeWarning
488
+ If the loaded mol2 file possibly uses GAFF atom types, which
489
+ are not supported.
490
+
491
+ Examples
492
+ --------
493
+
494
+ Load a mol2 file into an OpenFF ``Molecule`` object.
495
+
496
+ >>> from openff.toolkit.utils import get_data_file_path
497
+ >>> mol2_file_path = get_data_file_path('molecules/cyclohexane.mol2')
498
+ >>> toolkit = OpenEyeToolkitWrapper()
499
+ >>> molecule = toolkit.from_file(mol2_file_path, file_format='mol2')
500
+
501
+ """
502
+ from openeye import oechem
503
+
504
+ if isinstance(file_path, pathlib.Path):
505
+ _file_path = file_path.as_posix()
506
+ else:
507
+ _file_path = file_path
508
+
509
+ oeformat = get_oeformat(file_format)
510
+ ifs = oechem.oemolistream(_file_path)
511
+ if not ifs.IsValid():
512
+ # Get Python to report an error message, if possible.
513
+ # This can distinguish between FileNotFound, IsADirectoryError, etc.
514
+ open(_file_path).close()
515
+ # If that worked, then who knows. Fail anyway.
516
+ raise OSError("Unable to open file")
517
+
518
+ ifs.SetFormat(oeformat)
519
+
520
+ return self._read_oemolistream_molecules(ifs, allow_undefined_stereo, file_path=_file_path, _cls=_cls)
521
+
522
+ def from_file_obj(
523
+ self,
524
+ file_obj,
525
+ file_format: str,
526
+ allow_undefined_stereo: bool = False,
527
+ _cls=None,
528
+ ) -> list["Molecule"]:
529
+ """
530
+ Return an openff.toolkit.topology.Molecule from a file-like object (an object with a ".read()" method using
531
+ this toolkit.
532
+
533
+ Parameters
534
+ ----------
535
+ file_obj
536
+ The file-like object to read the molecule from
537
+ file_format
538
+ Format specifier, usually file suffix (eg. 'MOL2', 'SMI')
539
+ Note that not all toolkits support all formats. Check ToolkitWrapper.toolkit_file_read_formats for details.
540
+ allow_undefined_stereo
541
+ If false, raises an exception if oemol contains undefined stereochemistry.
542
+ _cls
543
+ Molecule constructor
544
+
545
+ Returns
546
+ -------
547
+ molecules
548
+ The list of Molecule objects in the file object.
549
+
550
+ Raises
551
+ ------
552
+ GAFFAtomTypeWarning
553
+ If the loaded mol2 file possibly uses GAFF atom types, which
554
+ are not supported.
555
+
556
+ """
557
+ from openeye import oechem
558
+
559
+ # Configure input molecule stream.
560
+ ifs = oechem.oemolistream()
561
+ ifs.openstring(file_obj.read())
562
+ oeformat = get_oeformat(file_format)
563
+ ifs.SetFormat(oeformat)
564
+
565
+ return self._read_oemolistream_molecules(ifs, allow_undefined_stereo, _cls=_cls)
566
+
567
+ def to_file_obj(self, molecule: "Molecule", file_obj, file_format: str):
568
+ """
569
+ Writes an OpenFF Molecule to a file-like object
570
+
571
+ Parameters
572
+ ----------
573
+ molecule
574
+ The molecule to write
575
+ file_obj
576
+ The file-like object to write to
577
+ file_format
578
+ The format for writing the molecule data
579
+
580
+ """
581
+ # This function requires a text-mode file_obj.
582
+ try:
583
+ file_obj.write("")
584
+ except TypeError:
585
+ # Switch to a ValueError and use a more informative exception
586
+ # message to match RDKit.
587
+ raise ValueError("Need a text mode file object like StringIO or a file opened with mode 't'") from None
588
+
589
+ with tempfile.TemporaryDirectory() as tmpdir:
590
+ path = pathlib.Path(tmpdir, f"input.{file_format.lower()}")
591
+ self.to_file(molecule, str(path), file_format)
592
+ file_data = path.read_text()
593
+ file_obj.write(file_data)
594
+
595
+ def to_file(
596
+ self,
597
+ molecule: "Molecule",
598
+ file_path: str | pathlib.Path,
599
+ file_format: str,
600
+ ):
601
+ """
602
+ Writes an OpenFF Molecule to a file-like object
603
+
604
+ Parameters
605
+ ----------
606
+ molecule
607
+ The molecule to write
608
+ file_path
609
+ The file path to write to.
610
+ file_format
611
+ The format for writing the molecule data
612
+
613
+ """
614
+ from openeye import oechem
615
+
616
+ if isinstance(file_path, pathlib.Path):
617
+ file_path = file_path.as_posix()
618
+
619
+ oemol = self.to_openeye(molecule)
620
+ ofs = oechem.oemolostream(file_path)
621
+ if not ofs.IsValid():
622
+ # Get Python to report an error message, if possible.
623
+ # This can distinguish between PermissionError, IsADirectoryError, etc.
624
+ open(file_path, "wb").close()
625
+ # If that worked, then who knows. Fail anyway.
626
+ raise OSError("Unable to open file")
627
+
628
+ openeye_format = get_oeformat(file_format)
629
+ ofs.SetFormat(openeye_format)
630
+
631
+ if openeye_format == oechem.OEFormat_SMI:
632
+ ofs.SetFlavor(
633
+ openeye_format,
634
+ self._get_smiles_flavor(isomeric=True, explicit_hydrogens=True),
635
+ )
636
+
637
+ # OFFTK strictly treats SDF as a single-conformer format.
638
+ # We need to override OETK's behavior here if the user is saving a multiconformer molecule.
639
+
640
+ # Remove all but the first conformer when writing to SDF as we only support single conformer format
641
+ if (file_format.lower() == "sdf") and oemol.NumConfs() > 1:
642
+ conf1 = next(iter(oemol.GetConfs()))
643
+ flat_coords = list()
644
+ for coord in conf1.GetCoords().values():
645
+ flat_coords.extend(coord)
646
+ oemol.DeleteConfs()
647
+ oecoords = oechem.OEFloatArray(flat_coords)
648
+ oemol.NewConf(oecoords)
649
+ # We're standardizing on putting partial charges into SDFs under the `atom.dprop.PartialCharge` property
650
+ if (file_format.lower() == "sdf") and (molecule.partial_charges is not None):
651
+ partial_charges_list = [oeatom.GetPartialCharge() for oeatom in oemol.GetAtoms()]
652
+ partial_charges_str = " ".join([f"{val:f}" for val in partial_charges_list])
653
+ # TODO: "dprop" means "double precision" -- Is there any way to make Python more accurately
654
+ # describe/infer the proper data type?
655
+ oechem.OESetSDData(oemol, "atom.dprop.PartialCharge", partial_charges_str)
656
+
657
+ # If the file format is "pdb" using OEWriteMolecule() rearranges the atoms (hydrogens are pushed to the bottom)
658
+ # Issue #475 (https://github.com/openforcefield/openff-toolkit/issues/475)
659
+ # dfhahn's workaround: Using OEWritePDBFile does not alter the atom arrangement
660
+ if file_format.lower() == "pdb":
661
+ if oemol.NumConfs() > 1:
662
+ for conf in oemol.GetConfs():
663
+ oechem.OEWritePDBFile(ofs, conf, oechem.OEOFlavor_PDB_BONDS)
664
+ else:
665
+ oechem.OEWritePDBFile(ofs, oemol, oechem.OEOFlavor_PDB_BONDS)
666
+ else:
667
+ oechem.OEWriteMolecule(ofs, oemol)
668
+ ofs.close()
669
+
670
+ @staticmethod
671
+ def _turn_oemolbase_sd_charges_into_partial_charges(oemol) -> bool:
672
+ """
673
+ Process an OEMolBase object and check to see whether it has an SD data pair
674
+ where the tag is "atom.dprop.PartialCharge", indicating that it has a list of
675
+ atomic partial charges. If so, apply those charges to the OEAtoms in the OEMolBase,
676
+ and delete the SD data pair.
677
+
678
+ Parameters
679
+ ----------
680
+ oemol
681
+ The molecule to process
682
+
683
+ Returns
684
+ -------
685
+ charges_are_present
686
+ Whether charges are present in the SD file. This is necessary because OEAtoms
687
+ have a default partial charge of 0.0, which makes truly zero-charge molecules
688
+ (eg "N2", "Ar"...) indistinguishable from molecules for which partial charges
689
+ have not been assigned. The OFF Toolkit allows this distinction with
690
+ mol.partial_charges=None. In order to complete roundtrips within the OFFMol
691
+ spec, we must interpret the presence or absence of this tag as a proxy for
692
+ mol.partial_charges=None.
693
+ """
694
+ from openeye import oechem
695
+
696
+ for dp in oechem.OEGetSDDataPairs(oemol):
697
+ if dp.GetTag() == "atom.dprop.PartialCharge":
698
+ charges_str = oechem.OEGetSDData(oemol, "atom.dprop.PartialCharge")
699
+ charges_unitless = [float(i) for i in charges_str.split()]
700
+ assert len(charges_unitless) == oemol.NumAtoms()
701
+ for charge, oeatom in zip(charges_unitless, oemol.GetAtoms()):
702
+ oeatom.SetPartialCharge(charge)
703
+ oechem.OEDeleteSDData(oemol, "atom.dprop.PartialCharge")
704
+ return True
705
+ return False
706
+
707
+ def _read_oemolistream_molecules(
708
+ self,
709
+ oemolistream,
710
+ allow_undefined_stereo: bool,
711
+ file_path: str | None = None,
712
+ _cls=None,
713
+ ):
714
+ """
715
+ Reads and return the Molecules in a OEMol input stream.
716
+
717
+ Parameters
718
+ ----------
719
+ oemolistream
720
+ The OEMol input stream to read from.
721
+ allow_undefined_stereo
722
+ If false, raises an exception if oemol contains undefined stereochemistry.
723
+ file_path
724
+ The path to the mol2 file. This is used exclusively to make
725
+ the error message more meaningful when the mol2 files doesn't
726
+ use Tripos atom types.
727
+ _cls
728
+ Molecule constructor
729
+
730
+ Returns
731
+ -------
732
+ molecules
733
+ The list of Molecule objects in the stream.
734
+
735
+ """
736
+ from openeye import oechem
737
+
738
+ mols = list()
739
+ oemol = oechem.OEMol()
740
+ while oechem.OEReadMolecule(oemolistream, oemol):
741
+ oechem.OEPerceiveChiral(oemol)
742
+ oechem.OEAssignAromaticFlags(oemol, oechem.OEAroModel_MDL)
743
+ oechem.OE3DToInternalStereo(oemol)
744
+
745
+ # If this is either a multi-conformer or multi-molecule SD file, check to see if there are partial charges
746
+ if (oemolistream.GetFormat() == oechem.OEFormat_SDF) and hasattr(oemol, "GetConfs"):
747
+ # The openFF toolkit treats each conformer in a "multiconformer" SDF as
748
+ # a separate molecule.
749
+ # https://github.com/openforcefield/openff-toolkit/issues/202
750
+ # Note that there is ambiguity about how SD data and "multiconformer" SD files should be stored.
751
+ # As a result, we have to do some weird stuff below, as discussed in
752
+ # https://docs.eyesopen.com/toolkits/python/oechemtk/oemol.html#dude-where-s-my-sd-data
753
+
754
+ # Jeff: I was unable to find a way to distinguish whether a SDF was multiconformer or not.
755
+ # The logic below should handle either single- or multi-conformer SDFs.
756
+ for conf in oemol.GetConfIter():
757
+ # First, we turn "conf" into an OEMCMol (OE multiconformer mol), since OTHER file formats
758
+ # really are multiconformer, and we will eventually feed this into the `from_openeye` function,
759
+ # which is made to ingest multiconformer mols.
760
+ this_conf_oemcmol = conf.GetMCMol()
761
+
762
+ # Then, we take any SD data pairs that were on the oemol, and copy them on to "this_conf_oemcmol".
763
+ # These SD pairs will be populated if we're dealing with a single-conformer SDF.
764
+ for dp in oechem.OEGetSDDataPairs(oemol):
765
+ oechem.OESetSDData(this_conf_oemcmol, dp.GetTag(), dp.GetValue())
766
+ # On the other hand, these SD pairs will be populated if we're dealing with a MULTI-conformer SDF.
767
+ for dp in oechem.OEGetSDDataPairs(conf):
768
+ oechem.OESetSDData(this_conf_oemcmol, dp.GetTag(), dp.GetValue())
769
+ # This function fishes out the special SD data tag we use for partial charge
770
+ # ("atom.dprop.PartialCharge"), and applies those as OETK-supported partial charges on the OEAtoms
771
+ has_charges = self._turn_oemolbase_sd_charges_into_partial_charges(this_conf_oemcmol)
772
+
773
+ # Finally, we feed the molecule into `from_openeye`, where it converted into an OFFMol
774
+ mol = self.from_openeye(
775
+ this_conf_oemcmol,
776
+ allow_undefined_stereo=allow_undefined_stereo,
777
+ _cls=_cls,
778
+ )
779
+
780
+ # If the molecule didn't even have the `PartialCharges` tag, we set it from zeroes to None here.
781
+ if not (has_charges):
782
+ mol.partial_charges = None
783
+ mols.append(mol)
784
+
785
+ else:
786
+ # In case this is being read from a SINGLE-molecule SD file, convert the SD field where we
787
+ # stash partial charges into actual per-atom partial charges
788
+ self._turn_oemolbase_sd_charges_into_partial_charges(oemol)
789
+ mol = self.from_openeye(oemol, allow_undefined_stereo=allow_undefined_stereo, _cls=_cls)
790
+ mols.append(mol)
791
+
792
+ # Check if this is an AMBER-produced mol2 file, which we can not load because they use GAFF atom types.
793
+ if oemolistream.GetFormat() == oechem.OEFormat_MOL2:
794
+ self._check_mol2_gaff_atom_type(mol, file_path)
795
+
796
+ return mols
797
+
798
+ def _assign_aromaticity_and_stereo_from_3d(self, offmol):
799
+ from openeye import oechem
800
+
801
+ oemol = offmol.to_openeye()
802
+ oechem.OEPerceiveChiral(oemol)
803
+ oechem.OE3DToInternalStereo(oemol)
804
+
805
+ # Aromaticity is re-perceived in this call
806
+ offmol_w_stereo_and_aro = self.from_openeye(oemol, allow_undefined_stereo=True)
807
+ return offmol_w_stereo_and_aro
808
+
809
+ def enumerate_protomers(
810
+ self,
811
+ molecule: "FrozenMolecule",
812
+ max_states: int = 0,
813
+ ) -> list["FrozenMolecule"]:
814
+ """
815
+ Enumerate the formal charges of a molecule to generate different protomers.
816
+ Note that, in cases where the input molecule has an uncommon protonation state
817
+ (for example ``[NH2-]``), the input molecule may not be included in the output.
818
+
819
+ Parameters
820
+ ----------
821
+ molecule
822
+ The molecule whose state we should enumerate
823
+
824
+ max_states
825
+ The maximum number of protomer states to be returned. If 0, the default,
826
+ attempt to return all protomers.
827
+
828
+ Returns
829
+ ------
830
+ molecules
831
+ A list of the protomers of the input molecules, including the input molecule if found
832
+ by Quacpac and not pruned by `max_states`.
833
+ """
834
+
835
+ from openeye import oequacpac
836
+
837
+ options = oequacpac.OEFormalChargeOptions()
838
+ options.SetMaxCount(max_states)
839
+
840
+ return [
841
+ self.from_openeye(
842
+ protomer,
843
+ allow_undefined_stereo=True,
844
+ _cls=molecule.__class__,
845
+ )
846
+ for protomer in oequacpac.OEEnumerateFormalCharges(
847
+ self.to_openeye(molecule=molecule),
848
+ options,
849
+ )
850
+ ]
851
+
852
+ def enumerate_stereoisomers(
853
+ self,
854
+ molecule: "FrozenMolecule",
855
+ undefined_only: bool = False,
856
+ max_isomers: int = 20,
857
+ rationalise: bool = True,
858
+ ) -> list["FrozenMolecule"]:
859
+ """
860
+ Enumerate the stereocenters and bonds of the current molecule.
861
+
862
+ Parameters
863
+ ----------
864
+ molecule
865
+ The molecule whose state we should enumerate
866
+
867
+ undefined_only
868
+ If we should enumerate all stereocenters and bonds or only those with undefined stereochemistry
869
+
870
+ max_isomers
871
+ The maximum amount of molecules that should be returned
872
+
873
+ rationalise
874
+ If we should try to build and rationalise the molecule to ensure it can exist
875
+
876
+
877
+ Returns
878
+ --------
879
+ molecules
880
+ A list of openff.toolkit.topology.Molecule instances
881
+
882
+ """
883
+ from openeye import oechem, oeomega
884
+
885
+ oemol = self.to_openeye(molecule=molecule)
886
+
887
+ # arguments for this function can be found here
888
+ # <https://docs.eyesopen.com/toolkits/python/omegatk/OEConfGenFunctions/OEFlipper.html?highlight=stereoisomers>
889
+
890
+ molecules = []
891
+ for isomer in oeomega.OEFlipper(oemol, 200, not undefined_only, True, False):
892
+ if rationalise:
893
+ # try and determine if the molecule is reasonable by generating a conformer with
894
+ # strict stereo, like embedding in rdkit
895
+ omega = oeomega.OEOmega()
896
+ omega.SetMaxConfs(1)
897
+ omega.SetCanonOrder(False)
898
+ # Don't generate random stereoisomer if not specified
899
+ omega.SetStrictStereo(True)
900
+ mol = oechem.OEMol(isomer)
901
+ status = omega(mol)
902
+ if status:
903
+ isomol = self.from_openeye(mol, _cls=molecule.__class__)
904
+ if isomol != molecule:
905
+ molecules.append(isomol)
906
+
907
+ else:
908
+ isomol = self.from_openeye(isomer, _cls=molecule.__class__)
909
+ if isomol != molecule:
910
+ molecules.append(isomol)
911
+
912
+ return molecules[:max_isomers]
913
+
914
+ def enumerate_tautomers(self, molecule: "FrozenMolecule", max_states: int = 20) -> list["FrozenMolecule"]:
915
+ """
916
+ Enumerate the possible tautomers of the current molecule
917
+
918
+ Parameters
919
+ ----------
920
+ molecule
921
+ The molecule whose state we should enumerate
922
+
923
+ max_states
924
+ The maximum amount of molecules that should be returned
925
+
926
+ Returns
927
+ -------
928
+ molecules
929
+ A list of openff.toolkit.topology.Molecule instances excluding the input molecule.
930
+ """
931
+ from openeye import oequacpac
932
+
933
+ oemol = self.to_openeye(molecule=molecule)
934
+
935
+ tautomers = []
936
+
937
+ # set the options
938
+ tautomer_options = oequacpac.OETautomerOptions()
939
+ tautomer_options.SetApplyWarts(False)
940
+ tautomer_options.SetMaxTautomersGenerated(max_states + 1)
941
+ tautomer_options.SetSaveStereo(True)
942
+ # this aligns the outputs of rdkit and openeye for the example cases
943
+ tautomer_options.SetCarbonHybridization(False)
944
+
945
+ for tautomer in oequacpac.OEEnumerateTautomers(oemol, tautomer_options):
946
+ # remove the input tautomer from the output
947
+ taut = self.from_openeye(tautomer, allow_undefined_stereo=True, _cls=molecule.__class__)
948
+ if taut != molecule:
949
+ tautomers.append(self.from_openeye(tautomer, allow_undefined_stereo=True, _cls=molecule.__class__))
950
+
951
+ return tautomers
952
+
953
+ @staticmethod
954
+ def _check_mol2_gaff_atom_type(molecule, file_path=None):
955
+ """Attempts to detect the presence of GAFF atom types in a molecule loaded from a mol2 file.
956
+
957
+ For now, this raises a ``GAFFAtomTypeWarning`` if the molecule
958
+ include Osmium and Holmium atoms, which have GAFF types OS and
959
+ HO respectively.
960
+
961
+ Parameters
962
+ ----------
963
+ molecule
964
+ The loaded molecule.
965
+ file_path
966
+ The path to the mol2 file. This is used exclusively to make
967
+ the error message more meaningful.
968
+
969
+ """
970
+ # Handle default.
971
+ if file_path is None:
972
+ file_path = ""
973
+ else:
974
+ # Append a ':' character that will separate the file
975
+ # path from the molecule string representation.
976
+ file_path = file_path + ":"
977
+ # atomic_number: (GAFF_type, element_name)
978
+ warning_atomic_numbers = {76: ("OS", "Osmium"), 67: ("HO", "Holmium")}
979
+
980
+ for atom in molecule.atoms:
981
+ try:
982
+ atom_type, element_name = warning_atomic_numbers[atom.atomic_number]
983
+ except KeyError:
984
+ pass
985
+ else:
986
+ warn_msg = (
987
+ f'OpenEye interpreted the type "{atom_type}" in {file_path}{molecule.name}'
988
+ f" as {element_name}. Does your mol2 file uses Tripos SYBYL atom types?"
989
+ " Other atom types such as GAFF are not supported."
990
+ )
991
+ warnings.warn(warn_msg, GAFFAtomTypeWarning, stacklevel=2)
992
+
993
+ @staticmethod
994
+ def _openeye_cip_atom_stereochemistry(oemol, oeatom):
995
+ """
996
+ Determine CIP stereochemistry (R/S) for the specified atom
997
+
998
+ Parameters
999
+ ----------
1000
+ oemol
1001
+ The molecule of interest
1002
+ oeatom
1003
+ The atom whose stereochemistry is to be computed
1004
+
1005
+ Returns
1006
+ -------
1007
+ stereochemistry
1008
+ 'R', 'S', or None if no stereochemistry is specified or the atom is not a stereocenter
1009
+ """
1010
+ from openeye import oechem
1011
+
1012
+ if not oeatom.HasStereoSpecified():
1013
+ # No stereochemical information has been stored, so this could be unknown stereochemistry
1014
+ # TODO: Should we raise an exception?
1015
+ return None
1016
+
1017
+ cip = oechem.OEPerceiveCIPStereo(oemol, oeatom)
1018
+
1019
+ if cip == oechem.OECIPAtomStereo_S:
1020
+ return "S"
1021
+ elif cip == oechem.OECIPAtomStereo_R:
1022
+ return "R"
1023
+ elif cip == oechem.OECIPAtomStereo_NotStereo:
1024
+ # Not a stereocenter
1025
+ # TODO: Should this be a different case from ``None``?
1026
+ return None
1027
+
1028
+ @staticmethod
1029
+ def _openeye_cip_bond_stereochemistry(oemol, oebond):
1030
+ """
1031
+ Determine CIP stereochemistry (E/Z) for the specified bond
1032
+
1033
+ Parameters
1034
+ ----------
1035
+ oemol
1036
+ The molecule of interest
1037
+ oebond
1038
+ The bond whose stereochemistry is to be computed
1039
+
1040
+ Returns
1041
+ -------
1042
+ stereochemistry
1043
+ 'E', 'Z', or None if stereochemistry is unspecified or the bond is not a stereo bond
1044
+
1045
+ """
1046
+ from openeye import oechem
1047
+
1048
+ if not oebond.HasStereoSpecified():
1049
+ # No stereochemical information has been stored, so this could be unknown stereochemistry
1050
+ # TODO: Should we raise an exception?
1051
+ return None
1052
+
1053
+ cip = oechem.OEPerceiveCIPStereo(oemol, oebond)
1054
+
1055
+ if cip == oechem.OECIPBondStereo_E:
1056
+ return "E"
1057
+ elif cip == oechem.OECIPBondStereo_Z:
1058
+ return "Z"
1059
+ elif cip == oechem.OECIPBondStereo_NotStereo:
1060
+ return None
1061
+
1062
+ @staticmethod
1063
+ def from_openeye(
1064
+ oemol,
1065
+ allow_undefined_stereo: bool = False,
1066
+ _cls=None,
1067
+ ) -> "FrozenMolecule":
1068
+ """
1069
+ Create a Molecule from an OpenEye molecule. If the OpenEye molecule has
1070
+ implicit hydrogens, this function will make them explicit.
1071
+
1072
+ ``OEAtom`` s have a different set of allowed value for partial charges than
1073
+ ``openff.toolkit.topology.Molecule`` s. In the OpenEye toolkits, partial charges
1074
+ are stored on individual ``OEAtom`` s, and their values are initialized to ``0.0``.
1075
+ In the Open Force Field Toolkit, an ``openff.toolkit.topology.Molecule``'s
1076
+ ``partial_charges`` attribute is initialized to ``None`` and can be set to a
1077
+ unit-wrapped numpy array with units of
1078
+ elementary charge. The Open Force
1079
+ Field Toolkit considers an ``OEMol`` where every ``OEAtom`` has a partial
1080
+ charge of ``float('nan')`` to be equivalent to an Open Force Field Toolkit `Molecule`'s
1081
+ ``partial_charges = None``.
1082
+ This assumption is made in both ``to_openeye`` and ``from_openeye``.
1083
+
1084
+ .. warning :: This API is experimental and subject to change.
1085
+
1086
+ Parameters
1087
+ ----------
1088
+ oemol
1089
+ An OpenEye molecule
1090
+ allow_undefined_stereo
1091
+ If false, raises an exception if oemol contains undefined stereochemistry.
1092
+ _cls
1093
+ Molecule constructor
1094
+
1095
+ Returns
1096
+ -------
1097
+ molecule
1098
+ An OpenFF molecule
1099
+
1100
+ Examples
1101
+ --------
1102
+
1103
+ Create a Molecule from an OpenEye OEMol
1104
+
1105
+ >>> from openeye import oechem
1106
+ >>> from openff.toolkit._tests.utils import get_data_file_path
1107
+ >>> ifs = oechem.oemolistream(get_data_file_path('systems/monomers/ethanol.mol2'))
1108
+ >>> oemols = list(ifs.GetOEGraphMols())
1109
+
1110
+ >>> toolkit_wrapper = OpenEyeToolkitWrapper()
1111
+ >>> molecule = toolkit_wrapper.from_openeye(oemols[0])
1112
+
1113
+ """
1114
+ import math
1115
+
1116
+ from openeye import oechem
1117
+
1118
+ # Save the existing SD tags, if any, since they're lost in the cast to
1119
+ # OEMol of the input is OEGraphMol. See issue #1711
1120
+ existing_sd_tags = {pair.GetTag(): pair.GetValue() for pair in oechem.OEGetSDDataIter(oemol)}
1121
+
1122
+ oemol = oechem.OEMol(oemol)
1123
+
1124
+ components = oechem.OEDetermineComponents(oemol)
1125
+ if components[0] > 1:
1126
+ warnings.warn(
1127
+ "OpenEye OEMol passed to from_openeye consists of more than one molecule, consider running "
1128
+ "something like https://docs.eyesopen.com/toolkits/python/oechemtk/oechem_examples/"
1129
+ "oechem_example_parts2mols.html or splitting input SMILES at '.'s to get separate molecules "
1130
+ "and pass them to from_openeye one at a time. While this is supported for "
1131
+ "legacy reasons, OpenFF Molecule objects are not supposed to contain disconnected chemical "
1132
+ "graphs and this may result in undefined behavior later on. The OpenFF ecosystem is built "
1133
+ "to handle multiple molecules, but they should be in a Topology object, ex: "
1134
+ "top = Topology.from_molecules([mol1, mol2])",
1135
+ MultipleComponentsInMoleculeWarning,
1136
+ stacklevel=2,
1137
+ )
1138
+
1139
+ # Add explicit hydrogens if they're implicit
1140
+ if oechem.OEHasImplicitHydrogens(oemol):
1141
+ oechem.OEAddExplicitHydrogens(oemol)
1142
+
1143
+ # TODO: Is there any risk to perceiving aromaticity here instead of later?
1144
+ oechem.OEAssignAromaticFlags(oemol, oechem.OEAroModel_MDL)
1145
+
1146
+ oechem.OEPerceiveChiral(oemol)
1147
+
1148
+ # Check that all stereo is specified
1149
+ # Potentially better OE stereo check: OEFlipper — Toolkits - - Python
1150
+ # https: // docs.eyesopen.com / toolkits / python / omegatk / OEConfGenFunctions / OEFlipper.html
1151
+
1152
+ unspec_chiral = False
1153
+ unspec_db = False
1154
+ problematic_atoms = list()
1155
+ problematic_bonds = list()
1156
+
1157
+ for oeatom in oemol.GetAtoms():
1158
+ if oeatom.IsChiral():
1159
+ if not (oeatom.HasStereoSpecified()):
1160
+ unspec_chiral = True
1161
+ problematic_atoms.append(oeatom)
1162
+ for oebond in oemol.GetBonds():
1163
+ if oebond.IsChiral():
1164
+ if not (oebond.HasStereoSpecified()):
1165
+ unspec_db = True
1166
+ problematic_bonds.append(oebond)
1167
+ if unspec_chiral or unspec_db:
1168
+
1169
+ def oeatom_to_str(oeatom) -> str:
1170
+ return (
1171
+ f"atomic num: {oeatom.GetAtomicNum()}, "
1172
+ f"name: {oeatom.GetName()}, "
1173
+ f"idx: {oeatom.GetIdx()}, "
1174
+ f"aromatic: {oeatom.IsAromatic()}, "
1175
+ f"chiral: {oeatom.IsChiral()}"
1176
+ )
1177
+
1178
+ def oebond_to_str(oebond) -> str:
1179
+ return f"order: {oebond.GetOrder()}, chiral: {oebond.IsChiral()}"
1180
+
1181
+ def describe_oeatom(oeatom) -> str:
1182
+ description = f"Atom {oeatom_to_str(oeatom)} with bonds:"
1183
+ for oebond in oeatom.GetBonds():
1184
+ description += f"\nbond {oebond_to_str(oebond)} to atom {oeatom_to_str(oebond.GetNbr(oeatom))}"
1185
+ return description
1186
+
1187
+ if (len(problematic_atoms) != 0 or len(problematic_bonds) != 0) and not allow_undefined_stereo:
1188
+ msg = f"OEMol has unspecified stereochemistry. {oemol.GetTitle()=}"
1189
+
1190
+ if len(problematic_atoms) != 0:
1191
+ msg += "Problematic atoms are:\n"
1192
+ for problematic_atom in problematic_atoms:
1193
+ msg += describe_oeatom(problematic_atom) + "\n"
1194
+
1195
+ if len(problematic_bonds) != 0:
1196
+ msg += f"Problematic bonds are: {problematic_bonds}\n"
1197
+
1198
+ raise UndefinedStereochemistryError(f"Unable to make OFFMol from OEMol: {msg}")
1199
+
1200
+ if _cls is None:
1201
+ from openff.toolkit.topology.molecule import Molecule
1202
+
1203
+ _cls = Molecule
1204
+
1205
+ molecule = _cls()
1206
+
1207
+ # OEMol.GetTitle() happens to default to an empty string
1208
+ if oemol.GetTitle() != "":
1209
+ molecule.name = oemol.GetTitle()
1210
+
1211
+ # Attach any SD tag information we saved before casting input to new OEMol
1212
+ for key, value in existing_sd_tags.items():
1213
+ molecule._properties[key] = value
1214
+
1215
+ off_to_oe_idx = dict() # {oemol_idx: molecule_idx}
1216
+ atom_mapping = {}
1217
+ for oeatom in oemol.GetAtoms():
1218
+ oe_idx = oeatom.GetIdx()
1219
+ map_id = oeatom.GetMapIdx()
1220
+ atomic_number = oeatom.GetAtomicNum()
1221
+ # Carry with implicit units of elementary charge for faster route through _add_atom
1222
+ formal_charge = oeatom.GetFormalCharge()
1223
+ explicit_valence = oeatom.GetExplicitValence()
1224
+ # Implicit hydrogens are never added to D- and F- block elements,
1225
+ # and the MDL valence is always the explicit valence for these
1226
+ # elements, so this does not count radical electrons in these blocks.
1227
+ mdl_valence = oechem.OEMDLGetValence(atomic_number, formal_charge, explicit_valence)
1228
+ number_radical_electrons = mdl_valence - (oeatom.GetImplicitHCount() + explicit_valence)
1229
+
1230
+ if number_radical_electrons > 0:
1231
+ raise RadicalsNotSupportedError(
1232
+ "The OpenFF Toolkit does not currently support parsing molecules with radicals. "
1233
+ f"Found {number_radical_electrons} radical electrons on molecule "
1234
+ f"{oechem.OECreateSmiString(oemol)}."
1235
+ )
1236
+
1237
+ is_aromatic = oeatom.IsAromatic()
1238
+ stereochemistry = OpenEyeToolkitWrapper._openeye_cip_atom_stereochemistry(oemol, oeatom)
1239
+ # stereochemistry = self._openeye_cip_atom_stereochemistry(oemol, oeatom)
1240
+ name = oeatom.GetName()
1241
+
1242
+ # Transfer in hierarchy metadata
1243
+ metadata_dict = dict()
1244
+ if oechem.OEHasResidues(oemol):
1245
+ metadata_dict["residue_name"] = oechem.OEAtomGetResidue(oeatom).GetName()
1246
+ metadata_dict["residue_number"] = oechem.OEAtomGetResidue(oeatom).GetResidueNumber()
1247
+ metadata_dict["insertion_code"] = oechem.OEAtomGetResidue(oeatom).GetInsertCode()
1248
+ metadata_dict["chain_id"] = oechem.OEAtomGetResidue(oeatom).GetChainID()
1249
+ # print('from', metadata_dict)
1250
+
1251
+ atom_index = molecule._add_atom(
1252
+ atomic_number,
1253
+ formal_charge,
1254
+ is_aromatic,
1255
+ stereochemistry=stereochemistry,
1256
+ name=name,
1257
+ metadata=metadata_dict,
1258
+ invalidate_cache=False,
1259
+ )
1260
+ off_to_oe_idx[oe_idx] = atom_index # store for mapping oeatom to molecule atom indices below
1261
+ atom_mapping[atom_index] = map_id
1262
+
1263
+ molecule._invalidate_cached_properties()
1264
+
1265
+ # If we have a full / partial atom map add it to the molecule. Zeroes 0
1266
+ # indicates no mapping
1267
+ if {*atom_mapping.values()} != {0}:
1268
+ molecule._properties["atom_map"] = {idx: map_idx for idx, map_idx in atom_mapping.items() if map_idx != 0}
1269
+
1270
+ for oebond in oemol.GetBonds():
1271
+ atom1_index = off_to_oe_idx[oebond.GetBgnIdx()]
1272
+ atom2_index = off_to_oe_idx[oebond.GetEndIdx()]
1273
+ bond_order = oebond.GetOrder()
1274
+ is_aromatic = oebond.IsAromatic()
1275
+ stereochemistry = OpenEyeToolkitWrapper._openeye_cip_bond_stereochemistry(oemol, oebond)
1276
+ if oebond.HasData("fractional_bond_order"):
1277
+ fractional_bond_order = oebond.GetData("fractional_bond_order")
1278
+ else:
1279
+ fractional_bond_order = None
1280
+
1281
+ molecule._add_bond(
1282
+ atom1_index,
1283
+ atom2_index,
1284
+ bond_order,
1285
+ is_aromatic=is_aromatic,
1286
+ stereochemistry=stereochemistry,
1287
+ fractional_bond_order=fractional_bond_order,
1288
+ invalidate_cache=False,
1289
+ )
1290
+
1291
+ molecule._invalidate_cached_properties()
1292
+
1293
+ # TODO: Copy conformations, if present
1294
+ # TODO: Come up with some scheme to know when to import coordinates
1295
+ # From SMILES: no
1296
+ # From MOL2: maybe
1297
+ # From other: maybe
1298
+ if hasattr(oemol, "GetConfs"):
1299
+ for conf in oemol.GetConfs():
1300
+ n_atoms = molecule.n_atoms
1301
+ # Store with implicit units until we're sure this conformer exists
1302
+ positions = np.zeros(shape=[n_atoms, 3], dtype=np.float64)
1303
+
1304
+ # store before iterating and then lookup, so GetCoords() is called once per conformer
1305
+ # this maps (OEChem) atom indices to coordinates (implicitly with Angstrom)
1306
+ oe_coords: dict[int, tuple[float, float, float]] = conf.GetCoords()
1307
+
1308
+ for oe_id in oe_coords:
1309
+ off_atom_coords = oe_coords[oe_id]
1310
+ off_atom_index = off_to_oe_idx[oe_id]
1311
+ positions[off_atom_index, :] = off_atom_coords
1312
+
1313
+ all_zeros = not np.any(positions)
1314
+ if all_zeros and n_atoms > 1:
1315
+ continue
1316
+ molecule._add_conformer(Quantity(positions, unit.angstrom))
1317
+
1318
+ # Store charges with implicit units in this scope
1319
+ unitless_charges = np.zeros(shape=molecule.n_atoms, dtype=np.float64)
1320
+
1321
+ # If all OEAtoms have a partial charge of NaN, then the OFFMol should
1322
+ # have its partial_charges attribute set to None
1323
+ any_partial_charge_is_not_nan = False
1324
+ for oe_atom in oemol.GetAtoms():
1325
+ oe_idx = oe_atom.GetIdx()
1326
+ off_idx = off_to_oe_idx[oe_idx]
1327
+ unitless_charge = oe_atom.GetPartialCharge()
1328
+ # Once this is True, skip the isnancheck
1329
+ if not any_partial_charge_is_not_nan:
1330
+ if not math.isnan(unitless_charge):
1331
+ any_partial_charge_is_not_nan = True
1332
+ unitless_charges[off_idx] = unitless_charge
1333
+
1334
+ if any_partial_charge_is_not_nan:
1335
+ molecule.partial_charges = Quantity(unitless_charges, unit.elementary_charge)
1336
+ else:
1337
+ molecule.partial_charges = None
1338
+
1339
+ return molecule
1340
+
1341
+ @cached(LRUCache(maxsize=4096), key=_mol_to_ctab_and_aro_key)
1342
+ def _connection_table_to_openeye(self, molecule, aromaticity_model=DEFAULT_AROMATICITY_MODEL):
1343
+ from openeye import oechem
1344
+
1345
+ if aromaticity_model not in ALLOWED_AROMATICITY_MODELS:
1346
+ raise InvalidAromaticityModelError(
1347
+ f"Given aromaticity model {aromaticity_model} which is not in the set of allowed aromaticity models: "
1348
+ f"{ALLOWED_AROMATICITY_MODELS}"
1349
+ )
1350
+
1351
+ oemol = oechem.OEMol()
1352
+ # Add atoms
1353
+ off_to_oe_idx = {} # {off_idx : oe_idx}
1354
+ oemol_atoms = list() # list of corresponding oemol atoms
1355
+ for atom in molecule.atoms:
1356
+ oeatom = oemol.NewAtom(atom.atomic_number)
1357
+ oeatom.SetFormalCharge(atom.formal_charge.m_as(unit.elementary_charge))
1358
+ # TODO: Do we want to provide _any_ pathway for Atom.is_aromatic to influence the OEMol?
1359
+ # oeatom.SetAromatic(atom.is_aromatic)
1360
+ oemol_atoms.append(oeatom)
1361
+ off_to_oe_idx[atom.molecule_atom_index] = oeatom.GetIdx()
1362
+
1363
+ # Add bonds
1364
+ oemol_bonds = list() # list of corresponding oemol bonds
1365
+ for bond in molecule.bonds:
1366
+ atom1_index = bond.atom1_index
1367
+ atom2_index = bond.atom2_index
1368
+ oebond = oemol.NewBond(oemol_atoms[atom1_index], oemol_atoms[atom2_index])
1369
+ oebond.SetOrder(bond.bond_order)
1370
+ # TODO: Do we want to provide _any_ pathway for Bond.is_aromatic to influence the OEMol?
1371
+ # oebond.SetAromatic(bond.is_aromatic)
1372
+ oemol_bonds.append(oebond)
1373
+
1374
+ if aromaticity_model == "OEAroModel_MDL":
1375
+ oechem.OEAssignAromaticFlags(oemol, oechem.OEAroModelMDL)
1376
+ else:
1377
+ raise InvalidAromaticityModelError(
1378
+ "Aromaticity model {aromaticity_model} is not in the set of allowed aromaticity models: "
1379
+ f"{ALLOWED_AROMATICITY_MODELS}"
1380
+ )
1381
+
1382
+ # Set atom stereochemistry now that all connectivity is in place
1383
+ for atom, oeatom in zip(molecule.atoms, oemol_atoms):
1384
+ if not atom.stereochemistry:
1385
+ continue
1386
+
1387
+ # Set arbitrary initial stereochemistry
1388
+ neighs = [n for n in oeatom.GetAtoms()]
1389
+ oeatom.SetStereo(neighs, oechem.OEAtomStereo_Tetra, oechem.OEAtomStereo_Right)
1390
+
1391
+ # Flip chirality if stereochemistry is incorrect
1392
+ oeatom_stereochemistry = OpenEyeToolkitWrapper._openeye_cip_atom_stereochemistry(oemol, oeatom)
1393
+ if oeatom_stereochemistry != atom.stereochemistry:
1394
+ # Flip the stereochemistry
1395
+ oeatom.SetStereo(neighs, oechem.OEAtomStereo_Tetra, oechem.OEAtomStereo_Left)
1396
+ # Verify it matches now as a sanity check
1397
+ oeatom_stereochemistry = OpenEyeToolkitWrapper._openeye_cip_atom_stereochemistry(oemol, oeatom)
1398
+ if oeatom_stereochemistry != atom.stereochemistry:
1399
+ raise InconsistentStereochemistryError(
1400
+ "Programming error: OpenEye atom stereochemistry assumptions failed. "
1401
+ f"The atom in the oemol has stereochemistry {oeatom_stereochemistry} and "
1402
+ f"the atom in the offmol has stereochemistry {atom.stereochemistry}."
1403
+ )
1404
+
1405
+ # Set bond stereochemistry
1406
+ for bond, oebond in zip(molecule.bonds, oemol_bonds):
1407
+ if not bond.stereochemistry:
1408
+ continue
1409
+
1410
+ atom1_index = bond.molecule.atoms.index(bond.atom1)
1411
+ atom2_index = bond.molecule.atoms.index(bond.atom2)
1412
+ # Set arbitrary initial stereochemistry
1413
+ oeatom1, oeatom2 = oemol_atoms[atom1_index], oemol_atoms[atom2_index]
1414
+ oeatom1_neighbor = next(n for n in oeatom1.GetAtoms() if not n == oeatom2)
1415
+ oeatom2_neighbor = next(n for n in oeatom2.GetAtoms() if not n == oeatom1)
1416
+ # oebond.SetStereo([oeatom1, oeatom2], oechem.OEBondStereo_CisTrans, oechem.OEBondStereo_Cis)
1417
+ oebond.SetStereo(
1418
+ [oeatom1_neighbor, oeatom2_neighbor],
1419
+ oechem.OEBondStereo_CisTrans,
1420
+ oechem.OEBondStereo_Cis,
1421
+ )
1422
+
1423
+ # Flip stereochemistry if incorrect
1424
+ oebond_stereochemistry = OpenEyeToolkitWrapper._openeye_cip_bond_stereochemistry(oemol, oebond)
1425
+ if oebond_stereochemistry != bond.stereochemistry:
1426
+ # Flip the stereochemistry
1427
+ oebond.SetStereo(
1428
+ [oeatom1_neighbor, oeatom2_neighbor],
1429
+ oechem.OEBondStereo_CisTrans,
1430
+ oechem.OEBondStereo_Trans,
1431
+ )
1432
+ # Verify it matches now as a sanity check
1433
+ oebond_stereochemistry = OpenEyeToolkitWrapper._openeye_cip_bond_stereochemistry(oemol, oebond)
1434
+ if oebond_stereochemistry != bond.stereochemistry:
1435
+ raise InconsistentStereochemistryError(
1436
+ "Programming error: OpenEye bond stereochemistry assumptions failed. "
1437
+ f"The bond in the oemol has stereochemistry {oebond_stereochemistry} and "
1438
+ f"the bond in the offmol has stereochemistry {bond.stereochemistry}."
1439
+ )
1440
+
1441
+ # Clean Up phase
1442
+ # The only feature of a molecule that wasn't perceived above seemed to be ring connectivity, better to run it
1443
+ # here then for someone to inquire about ring sizes and get 0 when it shouldn't be
1444
+ oechem.OEFindRingAtomsAndBonds(oemol)
1445
+
1446
+ return oemol, off_to_oe_idx
1447
+
1448
+ def to_openeye(
1449
+ self,
1450
+ molecule: "FrozenMolecule",
1451
+ aromaticity_model: str = DEFAULT_AROMATICITY_MODEL,
1452
+ ):
1453
+ r"""
1454
+ Create an OpenEye molecule using the specified aromaticity model
1455
+
1456
+ ``OEAtom`` s have a different set of allowed value for partial
1457
+ charges than ``openff.toolkit.topology.Molecule``\ s. In the
1458
+ OpenEye toolkits, partial charges are stored on individual
1459
+ ``OEAtom``\ s, and their values are initialized to ``0.0``. In
1460
+ the Open Force Field Toolkit, an``openff.toolkit.topology.Molecule``'s
1461
+ ``partial_charges`` attribute is initialized to ``None`` and can
1462
+ be set to a unit-wrapped numpy array with
1463
+ units of elementary charge. The Open Force Field Toolkit
1464
+ considers an ``OEMol`` where every ``OEAtom`` has a partial
1465
+ charge of ``float('nan')`` to be equivalent to an Open Force
1466
+ Field Toolkit ``Molecule``'s ``partial_charges = None``. This
1467
+ assumption is made in both ``to_openeye`` and ``from_openeye``.
1468
+
1469
+ .. todo ::
1470
+
1471
+ * Should the aromaticity model be specified in some other way?
1472
+
1473
+ .. warning :: This API is experimental and subject to change.
1474
+
1475
+ Parameters
1476
+ ----------
1477
+ molecule
1478
+ The molecule to convert to an OEMol
1479
+ aromaticity_model
1480
+ The aromaticity model to use
1481
+
1482
+ Returns
1483
+ -------
1484
+ oemol
1485
+ An OpenEye molecule
1486
+
1487
+ Examples
1488
+ --------
1489
+
1490
+ Create an OpenEye molecule from a Molecule
1491
+
1492
+ >>> from openff.toolkit import Molecule
1493
+ >>> toolkit_wrapper = OpenEyeToolkitWrapper()
1494
+ >>> molecule = Molecule.from_smiles('CC')
1495
+ >>> oemol = toolkit_wrapper.to_openeye(molecule)
1496
+
1497
+ """
1498
+ from openeye import oechem
1499
+
1500
+ oemol, off_to_oe_idx = self._connection_table_to_openeye(molecule, aromaticity_model=aromaticity_model)
1501
+ oemol = oechem.OEMol(oemol)
1502
+ # if not(molecule.name is None):
1503
+ oe_to_off_idx = dict([(j, i) for i, j in off_to_oe_idx.items()])
1504
+
1505
+ oemol.SetTitle(molecule.name)
1506
+ # Make lists of OE atoms and OE bonds in the same order as the OFF atoms and OFF bonds
1507
+ oemol_atoms = [None] * molecule.n_atoms # list of corresponding oemol atoms
1508
+ for oe_atom in oemol.GetAtoms():
1509
+ oe_idx = oe_atom.GetIdx()
1510
+ oemol_atoms[oe_to_off_idx[oe_idx]] = oe_atom
1511
+ off_atom = molecule.atoms[oe_to_off_idx[oe_idx]]
1512
+ oe_atom.SetName(off_atom.name)
1513
+
1514
+ if off_atom.partial_charge is None:
1515
+ oe_atom.SetPartialCharge(float("nan"))
1516
+ else:
1517
+ charge = off_atom.partial_charge.m_as(unit.elementary_charge)
1518
+ oe_atom.SetPartialCharge(float(charge))
1519
+ res = oechem.OEAtomGetResidue(oe_atom)
1520
+ # If we add residue info without updating the serial number, all of the atom
1521
+ # serial numbers in a written PDB will be 0. Note two things:
1522
+ # 1) the "res" object is specific to this atom, so its serial number
1523
+ # applies only to this atom
1524
+ # 2) we do NOT preserve
1525
+ # PDB serial numbers in our infrastructure, we merely set these to the
1526
+ # atom index in the molecule so that OpenEye-written PDBs have
1527
+ # nonzero atom serial numbers.
1528
+ res.SetSerialNumber(oe_to_off_idx[oe_idx] + 1)
1529
+
1530
+ if "residue_name" in off_atom.metadata:
1531
+ res.SetName(off_atom.metadata["residue_name"])
1532
+ else:
1533
+ res.SetName("UNL")
1534
+
1535
+ if "residue_number" in off_atom.metadata:
1536
+ res.SetResidueNumber(int(off_atom.metadata["residue_number"]))
1537
+ else:
1538
+ res.SetResidueNumber(1)
1539
+
1540
+ if "insertion_code" in off_atom.metadata:
1541
+ # Replace blank string with single character space to avoid OE PDB writing issue
1542
+ # https://github.com/openforcefield/openff-toolkit/issues/1967
1543
+ if off_atom.metadata["insertion_code"] == "":
1544
+ res.SetInsertCode(" ")
1545
+ else:
1546
+ res.SetInsertCode(off_atom.metadata["insertion_code"])
1547
+ else:
1548
+ res.SetInsertCode(" ")
1549
+
1550
+ if "chain_id" in off_atom.metadata:
1551
+ # Replace blank string with single character space to avoid OE PDB writing issue
1552
+ # https://github.com/openforcefield/openff-toolkit/issues/1967
1553
+ if off_atom.metadata["chain_id"] == "":
1554
+ res.SetChainID(" ")
1555
+ else:
1556
+ res.SetChainID(off_atom.metadata["chain_id"])
1557
+ else:
1558
+ res.SetChainID(" ")
1559
+
1560
+ oechem.OEAtomSetResidue(oe_atom, res)
1561
+
1562
+ assert None not in oemol_atoms
1563
+
1564
+ oemol_bonds = [None] * molecule.n_bonds # list of corresponding oemol bonds
1565
+ for oe_bond in oemol.GetBonds():
1566
+ at1_off_idx = oe_to_off_idx[oe_bond.GetBgnIdx()]
1567
+ at2_off_idx = oe_to_off_idx[oe_bond.GetEndIdx()]
1568
+ off_bond = molecule.get_bond_between(at1_off_idx, at2_off_idx)
1569
+ off_bond_idx = off_bond.molecule_bond_index
1570
+ oemol_bonds[off_bond_idx] = oe_bond
1571
+ if off_bond.fractional_bond_order is not None:
1572
+ oe_bond.SetData("fractional_bond_order", off_bond.fractional_bond_order)
1573
+
1574
+ assert None not in oemol_bonds
1575
+
1576
+ # Retain conformations, if present
1577
+ if molecule._conformers is not None:
1578
+ oemol.DeleteConfs()
1579
+ for conf in molecule._conformers:
1580
+ # OE needs a 1 x (3*n_Atoms) double array as input
1581
+ flat_coords = np.zeros(shape=oemol.NumAtoms() * 3, dtype=np.float64)
1582
+ for index, oe_idx in off_to_oe_idx.items():
1583
+ (x, y, z) = conf[index, :].m_as(unit.angstrom) # type: ignore[index]
1584
+ flat_coords[(3 * oe_idx)] = x
1585
+ flat_coords[(3 * oe_idx) + 1] = y
1586
+ flat_coords[(3 * oe_idx) + 2] = z
1587
+
1588
+ oecoords = oechem.OEFloatArray(flat_coords)
1589
+ oemol.NewConf(oecoords)
1590
+
1591
+ # Retain charges, if present. All atoms are initialized above with a partial charge of NaN.
1592
+ if molecule.partial_charges is not None:
1593
+ oe_indexed_charges = np.zeros(shape=molecule.n_atoms, dtype=np.float64)
1594
+ assert hasattr(molecule.partial_charges, "units")
1595
+ for off_idx, charge in enumerate(molecule.partial_charges):
1596
+ oe_idx = off_to_oe_idx[off_idx]
1597
+ charge_unitless = charge.m_as(unit.elementary_charge)
1598
+ oe_indexed_charges[oe_idx] = charge_unitless
1599
+ # TODO: This loop below fails if we try to use an "enumerate"-style loop.
1600
+ # It's worth investigating whether we make this assumption elsewhere in the codebase, since
1601
+ # the OE docs may indicate that this sort of usage is a very bad thing to do.
1602
+ # https://docs.eyesopen.com/toolkits/python/oechemtk/atombondindices.html#indices-for-molecule-lookup-considered-harmful
1603
+ # for oe_idx, oe_atom in enumerate(oemol.GetAtoms()):
1604
+ for oe_atom in oemol.GetAtoms():
1605
+ oe_idx = oe_atom.GetIdx()
1606
+ oe_atom.SetPartialCharge(oe_indexed_charges[oe_idx])
1607
+
1608
+ # Retain properties, if present
1609
+ for key, value in molecule.properties.items():
1610
+ oechem.OESetSDData(oemol, str(key), str(value))
1611
+
1612
+ return oemol
1613
+
1614
+ def atom_is_in_ring(self, atom: "Atom") -> bool:
1615
+ """Return whether or not an atom is in a ring.
1616
+
1617
+ It is assumed that this atom is in molecule.
1618
+
1619
+ Parameters
1620
+ ----------
1621
+ atom
1622
+ The molecule containing the atom of interest
1623
+
1624
+ Returns
1625
+ -------
1626
+ is_in_ring
1627
+ Whether or not the atom is in a ring.
1628
+
1629
+ Raises
1630
+ ------
1631
+ NotAttachedToMoleculeError
1632
+ """
1633
+ if atom.molecule is None:
1634
+ raise NotAttachedToMoleculeError("This Atom does not belong to a Molecule object")
1635
+
1636
+ molecule = atom.molecule
1637
+ atom_index = atom.molecule_atom_index
1638
+
1639
+ oemol = molecule.to_openeye()
1640
+
1641
+ # Molecule.to_openeye() is guaranteed to preserve atom ordering
1642
+ is_in_ring = [*oemol.GetAtoms()][atom_index].IsInRing()
1643
+
1644
+ return is_in_ring
1645
+
1646
+ def bond_is_in_ring(self, bond: "Bond") -> bool:
1647
+ """Return whether or not a bond is in a ring.
1648
+
1649
+ It is assumed that this atom is in molecule.
1650
+
1651
+ Parameters
1652
+ ----------
1653
+ bond
1654
+ The molecule containing the atom of interest
1655
+
1656
+ Returns
1657
+ -------
1658
+ is_in_ring
1659
+ Whether or not the bond of index `bond_index` is in a ring
1660
+
1661
+ Raises
1662
+ ------
1663
+ NotAttachedToMoleculeError
1664
+ """
1665
+ if bond.molecule is None:
1666
+ raise NotAttachedToMoleculeError("This Bond does not belong to a Molecule object")
1667
+
1668
+ molecule = bond.molecule
1669
+
1670
+ oemol = molecule.to_openeye()
1671
+
1672
+ # Molecule.to_openeye() is NOT guaranteed to preserve bond ordering,
1673
+ # so we must look up the corresponding `OEBond` via `OEAtom`s
1674
+ oebond = oemol.GetBond(
1675
+ [*oemol.GetAtoms()][bond.atom1_index],
1676
+ [*oemol.GetAtoms()][bond.atom2_index],
1677
+ )
1678
+
1679
+ is_in_ring = oebond.IsInRing()
1680
+
1681
+ return is_in_ring
1682
+
1683
+ def _get_smiles_flavor(self, isomeric: bool, explicit_hydrogens: bool) -> int:
1684
+ from openeye import oechem
1685
+
1686
+ # this sets up the default settings following the old DEFAULT flag
1687
+ # more information on flags can be found here
1688
+ # <https://docs.eyesopen.com/toolkits/python/oechemtk/OEChemConstants/OESMILESFlag.html#OEChem::OESMILESFlag>
1689
+ smiles_options = oechem.OESMILESFlag_Canonical | oechem.OESMILESFlag_Isotopes | oechem.OESMILESFlag_RGroups
1690
+
1691
+ # check if we want an isomeric smiles
1692
+ if isomeric:
1693
+ # add the atom and bond stereo flags
1694
+ smiles_options |= oechem.OESMILESFlag_AtomStereo | oechem.OESMILESFlag_BondStereo
1695
+
1696
+ if explicit_hydrogens:
1697
+ # add the hydrogen flag
1698
+ smiles_options |= oechem.OESMILESFlag_Hydrogens
1699
+
1700
+ return smiles_options
1701
+
1702
+ def to_smiles(
1703
+ self,
1704
+ molecule: "Molecule",
1705
+ isomeric: bool = True,
1706
+ explicit_hydrogens: bool = True,
1707
+ mapped: bool = False,
1708
+ ) -> str:
1709
+ """
1710
+ Uses the OpenEye toolkit to convert a Molecule into a SMILES string.
1711
+ A partially mapped smiles can also be generated for atoms of interest by supplying an `atom_map` to the
1712
+ properties dictionary.
1713
+
1714
+ Parameters
1715
+ ----------
1716
+ molecule
1717
+ The molecule to convert into a SMILES.
1718
+ isomeric
1719
+ return an isomeric smiles
1720
+ explicit_hydrogens
1721
+ return a smiles string containing all hydrogens explicitly
1722
+ mapped
1723
+ return a explicit hydrogen mapped smiles, the atoms to be mapped can be controlled by supplying an
1724
+ atom map into the properties dictionary. If no mapping is passed all atoms will be mapped in order, else
1725
+ an atom map dictionary from the current atom index to the map id should be supplied with no duplicates.
1726
+ The map ids (values) should start from 0 or 1.
1727
+
1728
+ Returns
1729
+ -------
1730
+ smiles
1731
+ The SMILES of the input molecule.
1732
+ """
1733
+ from openeye import oechem
1734
+
1735
+ oemol = self.to_openeye(molecule)
1736
+
1737
+ smiles_options = self._get_smiles_flavor(isomeric, explicit_hydrogens)
1738
+
1739
+ if mapped:
1740
+ assert explicit_hydrogens is True, (
1741
+ "Mapped smiles require all hydrogens and stereochemsitry to be defined to retain order"
1742
+ )
1743
+
1744
+ # if we only want to map specific atoms check for an atom map
1745
+ atom_map = molecule._properties.get("atom_map", None)
1746
+ if atom_map is not None:
1747
+ # make sure there are no repeated indices
1748
+ map_ids = set(atom_map.values())
1749
+ if len(map_ids) < len(atom_map):
1750
+ atom_map = None
1751
+ elif 0 in atom_map.values():
1752
+ # we need to increment the map index
1753
+ for atom, map in atom_map.items():
1754
+ atom_map[atom] = map + 1
1755
+
1756
+ if atom_map is None:
1757
+ # now we need to add the atom map to the atoms
1758
+ for oeatom in oemol.GetAtoms():
1759
+ oeatom.SetMapIdx(oeatom.GetIdx() + 1)
1760
+ else:
1761
+ for atom in oemol.GetAtoms():
1762
+ try:
1763
+ # try to set the atom map
1764
+ map_idx = atom_map[atom.GetIdx()]
1765
+ atom.SetMapIdx(map_idx)
1766
+ except KeyError:
1767
+ continue
1768
+
1769
+ smiles_options |= oechem.OESMILESFlag_AtomMaps
1770
+
1771
+ smiles = oechem.OECreateSmiString(oemol, smiles_options)
1772
+ return smiles
1773
+
1774
+ def to_inchi(self, molecule: "Molecule", fixed_hydrogens: bool = False) -> str:
1775
+ """
1776
+ Create an InChI string for the molecule using the OpenEye OEChem Toolkit.
1777
+ InChI is a standardised representation that does not capture tautomers
1778
+ unless specified using the fixed hydrogen layer.
1779
+
1780
+ For information on InChi see here https://iupac.org/who-we-are/divisions/division-details/inchi/
1781
+
1782
+ Parameters
1783
+ ----------
1784
+ molecule
1785
+ The molecule to convert into a SMILES.
1786
+
1787
+ fixed_hydrogens
1788
+ If a fixed hydrogen layer should be added to the InChI, if `True` this
1789
+ will produce a non standard specific InChI string of the molecule.
1790
+
1791
+ Returns
1792
+ --------
1793
+ inchi: str
1794
+ The InChI string of the molecule.
1795
+
1796
+ Raises
1797
+ ------
1798
+ EmptyInChiError
1799
+ If OEChem failed to generate an InChI for the molecule
1800
+ """
1801
+
1802
+ from openeye import oechem
1803
+
1804
+ oemol = self.to_openeye(molecule)
1805
+
1806
+ if fixed_hydrogens:
1807
+ opts = oechem.OEInChIOptions()
1808
+ opts.SetFixedHLayer(True)
1809
+ inchi = oechem.OEMolToInChI(oemol)
1810
+
1811
+ else:
1812
+ inchi = oechem.OEMolToSTDInChI(oemol)
1813
+
1814
+ # TODO: Add support for /LargeMolecules switch when OpenEye allows it
1815
+ # (underlying InChI tool does)
1816
+ if len(inchi) == 0:
1817
+ raise EmptyInChiError("OEChem failed to generate an InChI for the molecule.")
1818
+
1819
+ return inchi
1820
+
1821
+ def to_inchikey(self, molecule: "Molecule", fixed_hydrogens: bool = False) -> str:
1822
+ """
1823
+ Create an InChIKey for the molecule using the OpenEye OEChem Toolkit.
1824
+ InChIKey is a standardised representation that does not capture tautomers
1825
+ unless specified using the fixed hydrogen layer.
1826
+
1827
+ For information on InChi see here https://iupac.org/who-we-are/divisions/division-details/inchi/
1828
+
1829
+ Parameters
1830
+ ----------
1831
+ molecule
1832
+ The molecule to convert into a SMILES.
1833
+
1834
+ fixed_hydrogens
1835
+ If a fixed hydrogen layer should be added to the InChI, if `True` this will produce a non standard specific
1836
+ InChI string of the molecule.
1837
+
1838
+ Returns
1839
+ --------
1840
+ inchi_key
1841
+ The InChIKey representation of the molecule.
1842
+
1843
+ Raises
1844
+ ------
1845
+ EmptyInChiError
1846
+ If OEChem failed to generate an InChI for the molecule
1847
+ """
1848
+
1849
+ from openeye import oechem
1850
+
1851
+ oemol = self.to_openeye(molecule)
1852
+
1853
+ if fixed_hydrogens:
1854
+ opts = oechem.OEInChIOptions()
1855
+ opts.SetFixedHLayer(True)
1856
+ inchi_key = oechem.OEMolToInChIKey(oemol)
1857
+
1858
+ else:
1859
+ inchi_key = oechem.OEMolToSTDInChIKey(oemol)
1860
+
1861
+ if len(inchi_key) == 0:
1862
+ raise EmptyInChiError("OEChem failed to generate an InChI key for the molecule.")
1863
+
1864
+ return inchi_key
1865
+
1866
+ def to_iupac(self, molecule: "Molecule") -> str:
1867
+ """Generate IUPAC name from Molecule
1868
+
1869
+ Parameters
1870
+ ----------
1871
+ molecule
1872
+ The molecule to convert into a SMILES.
1873
+
1874
+ Returns
1875
+ -------
1876
+ iupac_name
1877
+ IUPAC name of the molecule
1878
+
1879
+ Examples
1880
+ --------
1881
+
1882
+ >>> from openff.toolkit import Molecule
1883
+ >>> from openff.toolkit.utils import get_data_file_path
1884
+ >>> sdf_filepath = get_data_file_path('molecules/ethanol.sdf')
1885
+ >>> molecule = Molecule(sdf_filepath)
1886
+ >>> toolkit = OpenEyeToolkitWrapper()
1887
+ >>> iupac_name = toolkit.to_iupac(molecule)
1888
+
1889
+ """
1890
+ from openeye import oeiupac
1891
+
1892
+ oemol = self.to_openeye(molecule)
1893
+
1894
+ return oeiupac.OECreateIUPACName(oemol)
1895
+
1896
+ def canonical_order_atoms(self, molecule: "FrozenMolecule") -> "FrozenMolecule":
1897
+ """
1898
+ Canonical order the atoms in the molecule using the OpenEye toolkit.
1899
+
1900
+ Parameters
1901
+ ----------
1902
+ molecule
1903
+ The input molecule
1904
+
1905
+ Returns
1906
+ -------
1907
+ molecule
1908
+ The input molecule, with canonically-indexed atoms and bonds.
1909
+ """
1910
+
1911
+ from openeye import oechem
1912
+
1913
+ oemol = self.to_openeye(molecule)
1914
+
1915
+ oechem.OECanonicalOrderAtoms(oemol)
1916
+ oechem.OECanonicalOrderBonds(oemol)
1917
+
1918
+ # reorder the iterator
1919
+ vatm = []
1920
+ for atom in oemol.GetAtoms():
1921
+ if atom.GetAtomicNum() != oechem.OEElemNo_H:
1922
+ vatm.append(atom)
1923
+ oemol.OrderAtoms(vatm)
1924
+
1925
+ vbnd = []
1926
+ for bond in oemol.GetBonds():
1927
+ if bond.GetBgn().GetAtomicNum() != oechem.OEElemNo_H and bond.GetEnd().GetAtomicNum() != oechem.OEElemNo_H:
1928
+ vbnd.append(bond)
1929
+ oemol.OrderBonds(vbnd)
1930
+
1931
+ oemol.Sweep()
1932
+
1933
+ for bond in oemol.GetBonds():
1934
+ if bond.GetBgnIdx() > bond.GetEndIdx():
1935
+ bond.SwapEnds()
1936
+
1937
+ return self.from_openeye(oemol, allow_undefined_stereo=True, _cls=molecule.__class__)
1938
+
1939
+ def from_smiles(
1940
+ self,
1941
+ smiles: str,
1942
+ hydrogens_are_explicit: bool = False,
1943
+ allow_undefined_stereo: bool = False,
1944
+ _cls=None,
1945
+ name: str = "",
1946
+ ) -> "FrozenMolecule":
1947
+ """
1948
+ Create a Molecule from a SMILES string using the OpenEye toolkit.
1949
+
1950
+ .. warning :: This API is experimental and subject to change.
1951
+
1952
+ Parameters
1953
+ ----------
1954
+ smiles
1955
+ The SMILES string to turn into a molecule
1956
+ hydrogens_are_explicit
1957
+ If False, OE will perform hydrogen addition using OEAddExplicitHydrogens
1958
+ allow_undefined_stereo
1959
+ Whether to accept SMILES with undefined stereochemistry. If False,
1960
+ an exception will be raised if a SMILES with undefined stereochemistry
1961
+ is passed into this function.
1962
+ _cls
1963
+ Molecule constructor
1964
+ name
1965
+ An optional name for the output molecule
1966
+
1967
+ Returns
1968
+ -------
1969
+ molecule
1970
+ An OpenFF style molecule.
1971
+
1972
+ Raises
1973
+ ------
1974
+ RadicalsNotSupportedError
1975
+ """
1976
+ from openeye import oechem
1977
+
1978
+ oemol = oechem.OEGraphMol()
1979
+ if not oechem.OESmilesToMol(oemol, smiles):
1980
+ raise SMILESParseError("Unable to parse the SMILES string")
1981
+ if not (hydrogens_are_explicit):
1982
+ result = oechem.OEAddExplicitHydrogens(oemol)
1983
+ if not result:
1984
+ raise ValueError("Addition of explicit hydrogens failed in from_openeye")
1985
+ elif hydrogens_are_explicit and oechem.OEHasImplicitHydrogens(oemol):
1986
+ raise ValueError(
1987
+ f"'hydrogens_are_explicit' was specified as True, but OpenEye Toolkit interpreted "
1988
+ f"SMILES '{smiles}' as having implicit hydrogen. If this SMILES is intended to "
1989
+ f"express all explicit hydrogens in the molecule, then you should construct the "
1990
+ f"desired molecule as an OEMol (where oechem.OEHasImplicitHydrogens(oemol) returns "
1991
+ f"False), and then use Molecule.from_openeye() to create the desired OFFMol."
1992
+ )
1993
+
1994
+ # Set partial charges to None, since they couldn't have been stored in a SMILES
1995
+ for atom in oemol.GetAtoms():
1996
+ atom.SetPartialCharge(float("nan"))
1997
+
1998
+ molecule = self.from_openeye(
1999
+ oemol,
2000
+ _cls=_cls,
2001
+ allow_undefined_stereo=allow_undefined_stereo,
2002
+ )
2003
+ molecule.name = name
2004
+ return molecule
2005
+
2006
+ def from_inchi(
2007
+ self,
2008
+ inchi: str,
2009
+ allow_undefined_stereo: bool = False,
2010
+ _cls=None,
2011
+ name: str = "",
2012
+ ) -> "FrozenMolecule":
2013
+ """
2014
+ Construct a Molecule from a InChI representation
2015
+
2016
+ Parameters
2017
+ ----------
2018
+ inchi
2019
+ The InChI representation of the molecule.
2020
+ allow_undefined_stereo
2021
+ Whether to accept InChI with undefined stereochemistry. If False,
2022
+ an exception will be raised if a InChI with undefined stereochemistry
2023
+ is passed into this function.
2024
+ _cls
2025
+ Molecule constructor
2026
+ name
2027
+ An optional name for the output molecule
2028
+
2029
+ Returns
2030
+ -------
2031
+ molecule
2032
+ """
2033
+
2034
+ from openeye import oechem
2035
+
2036
+ # This calls the same functions as OESmilesToMol
2037
+ oemol = oechem.OEGraphMol()
2038
+ oechem.OEInChIToMol(oemol, inchi)
2039
+
2040
+ # try and catch InChI parsing fails
2041
+ # if there are no atoms don't build the molecule
2042
+ if oemol.NumAtoms() == 0:
2043
+ raise InChIParseError(
2044
+ f"There was an issue parsing the InChI string ({inchi}), please check and try again."
2045
+ )
2046
+
2047
+ molecule = self.from_openeye(
2048
+ oemol,
2049
+ allow_undefined_stereo=allow_undefined_stereo,
2050
+ _cls=_cls,
2051
+ )
2052
+ molecule.name = name
2053
+
2054
+ return molecule
2055
+
2056
+ def from_iupac(
2057
+ self,
2058
+ iupac_name: str,
2059
+ allow_undefined_stereo: bool = False,
2060
+ _cls=None,
2061
+ **kwargs,
2062
+ ) -> "FrozenMolecule":
2063
+ """
2064
+ Construct a Molecule from an IUPAC name
2065
+
2066
+ Parameters
2067
+ ----------
2068
+ iupac_name
2069
+ The IUPAC or common name of the molecule.
2070
+ allow_undefined_stereo
2071
+ Whether to accept a molecule name with undefined stereochemistry. If False,
2072
+ an exception will be raised if a molecule name with undefined stereochemistry
2073
+ is passed into this function.
2074
+ _cls
2075
+ Molecule constructor
2076
+
2077
+ Returns
2078
+ -------
2079
+ molecule
2080
+
2081
+ """
2082
+ from openeye import oechem, oeiupac
2083
+
2084
+ oemol = oechem.OEMol()
2085
+ parsing_result = oeiupac.OEParseIUPACName(oemol, iupac_name)
2086
+ if not parsing_result:
2087
+ raise InvalidIUPACNameError(f"OpenEye failed to parse {iupac_name} as a IUPAC name")
2088
+ oechem.OETriposAtomNames(oemol)
2089
+ result = oechem.OEAddExplicitHydrogens(oemol)
2090
+ if not result:
2091
+ raise OpenEyeError("Addition of explicit hydrogens failed in from_iupac")
2092
+
2093
+ molecule = self.from_openeye(oemol, allow_undefined_stereo=allow_undefined_stereo, _cls=_cls, **kwargs)
2094
+
2095
+ return molecule
2096
+
2097
+ def generate_conformers(
2098
+ self,
2099
+ molecule: "Molecule",
2100
+ n_conformers: int = 1,
2101
+ rms_cutoff: Quantity | None = None,
2102
+ clear_existing: bool = True,
2103
+ make_carboxylic_acids_cis: bool = False,
2104
+ ):
2105
+ r"""
2106
+ Generate molecule conformers using OpenEye Omega.
2107
+
2108
+ .. warning :: This API is experimental and subject to change.
2109
+
2110
+ .. todo ::
2111
+
2112
+ * which parameters should we expose? (or can we implement a general system with \*\*kwargs?)
2113
+ * will the coordinates be returned in the OpenFF Molecule's own indexing system? Or is there a chance that
2114
+ they'll get reindexed when we convert the input into an OEmol?
2115
+
2116
+ Parameters
2117
+ ----------
2118
+ molecule
2119
+ The molecule to generate conformers for.
2120
+ n_conformers
2121
+ The maximum number of conformers to generate.
2122
+ rms_cutoff
2123
+ The minimum RMS value at which two conformers are considered redundant and one is deleted.
2124
+ If None, the cutoff is set to 1 Angstrom
2125
+ clear_existing
2126
+ Whether to overwrite existing conformers for the molecule
2127
+ make_carboxylic_acids_cis
2128
+ Guarantee all conformers have exclusively cis carboxylic acid groups (COOH)
2129
+ by rotating the proton in any trans carboxylic acids 180 degrees around the C-O bond.
2130
+ """
2131
+ import copy
2132
+
2133
+ from openeye import oeomega
2134
+
2135
+ # Copy the molecule and scrub the conformers so that omega HAS to read stereo from graph mol
2136
+ # See https://github.com/openforcefield/openff-toolkit/issues/1152
2137
+ mol_copy = copy.deepcopy(molecule)
2138
+ mol_copy._conformers = None
2139
+
2140
+ oemol = self.to_openeye(mol_copy)
2141
+ omega = oeomega.OEOmega()
2142
+ omega.SetMaxConfs(n_conformers)
2143
+ omega.SetCanonOrder(False)
2144
+ omega.SetSampleHydrogens(True)
2145
+ omega.SetEnergyWindow(15.0) # unit?
2146
+ if rms_cutoff is None:
2147
+ omega.SetRMSThreshold(1.0)
2148
+ else:
2149
+ omega.SetRMSThreshold(rms_cutoff.m_as(unit.angstrom))
2150
+ # Don't generate random stereoisomer if not specified
2151
+ omega.SetStrictStereo(True)
2152
+ status = omega(oemol)
2153
+
2154
+ if status is False:
2155
+ omega.SetStrictStereo(False)
2156
+ new_status = omega(oemol)
2157
+ if new_status is False:
2158
+ raise ConformerGenerationError("OpenEye Omega conformer generation failed")
2159
+
2160
+ molecule2 = self.from_openeye(oemol, allow_undefined_stereo=True, _cls=molecule.__class__)
2161
+
2162
+ if clear_existing:
2163
+ molecule._conformers = list()
2164
+
2165
+ for conformer in molecule2._conformers: # type: ignore[union-attr]
2166
+ molecule._add_conformer(conformer)
2167
+
2168
+ if make_carboxylic_acids_cis:
2169
+ molecule._make_carboxylic_acids_cis(toolkit_registry=self)
2170
+
2171
+ def apply_elf_conformer_selection(
2172
+ self,
2173
+ molecule: "Molecule",
2174
+ percentage: float = 2.0,
2175
+ limit: int = 10,
2176
+ ):
2177
+ """Applies the `ELF method
2178
+ <https://docs.eyesopen.com/toolkits/python/quacpactk/molchargetheory.html#elf-conformer-selection>`_
2179
+ to select a set of diverse
2180
+ conformers which have minimal electrostatically strongly interacting functional
2181
+ groups from a molecules conformers.
2182
+
2183
+ Notes
2184
+ -----
2185
+ * The input molecule should have a large set of conformers already
2186
+ generated to select the ELF conformers from.
2187
+ * The selected conformers will be retained in the ``molecule.conformers`` list
2188
+ while unselected conformers will be discarded.
2189
+ * Conformers generated with the OpenEye toolkit often include trans
2190
+ carboxylic acids (COOH). These are unphysical and will be rejected by
2191
+ ``apply_elf_conformer_selection``. If no conformers are selected, try
2192
+ re-running ``generate_conformers`` with the ``make_carboxylic_acids_cis``
2193
+ argument set to ``True``
2194
+
2195
+ See Also
2196
+ --------
2197
+ RDKitToolkitWrapper.apply_elf_conformer_selection
2198
+
2199
+ Parameters
2200
+ ----------
2201
+ molecule
2202
+ The molecule which contains the set of conformers to select from.
2203
+ percentage
2204
+ The percentage of conformers with the lowest electrostatic interaction
2205
+ energies to greedily select from.
2206
+ limit
2207
+ The maximum number of conformers to select.
2208
+ """
2209
+
2210
+ from openeye import oechem, oequacpac
2211
+
2212
+ if molecule.n_conformers == 0:
2213
+ return
2214
+
2215
+ oe_molecule = molecule.to_openeye()
2216
+
2217
+ # Select a subset of the OMEGA generated conformers using the ELF10 method.
2218
+ oe_elf_options = oequacpac.OEELFOptions()
2219
+ oe_elf_options.SetElfLimit(limit)
2220
+ oe_elf_options.SetPercent(percentage)
2221
+
2222
+ oe_elf = oequacpac.OEELF(oe_elf_options)
2223
+
2224
+ output_stream = oechem.oeosstream()
2225
+
2226
+ oechem.OEThrow.SetOutputStream(output_stream)
2227
+ oechem.OEThrow.Clear()
2228
+
2229
+ status = oe_elf.Select(oe_molecule)
2230
+
2231
+ oechem.OEThrow.SetOutputStream(oechem.oeerr)
2232
+
2233
+ output_string = output_stream.str().decode("UTF-8")
2234
+ output_string = output_string.replace("Warning: ", "")
2235
+ output_string = re.sub("^: +", "", output_string, flags=re.MULTILINE)
2236
+ output_string = re.sub("\n$", "", output_string)
2237
+
2238
+ # Check to make sure the call to OE was succesful, and re-route any
2239
+ # non-fatal warnings to the correct logger.
2240
+ if output_string and not status:
2241
+ raise RuntimeError("\n" + output_string)
2242
+ elif not status:
2243
+ raise RuntimeError(
2244
+ "OpenEye failed to select conformers, but did not return any output. "
2245
+ "This most commonly occurs when the Molecule does not have enough conformers to "
2246
+ "select from. Try calling Molecule.apply_elf_conformer_selection() again after "
2247
+ "running Molecule.generate_conformers() with a much larger value of n_conformers "
2248
+ "or with make_carboxylic_acids_cis=True."
2249
+ )
2250
+ elif output_string:
2251
+ logger.warning(output_string)
2252
+
2253
+ # Extract and store the ELF conformers on the input molecule.
2254
+ conformers = []
2255
+
2256
+ for oe_conformer in oe_molecule.GetConfs():
2257
+ conformer = np.zeros((oe_molecule.NumAtoms(), 3))
2258
+
2259
+ for atom_index, coordinates in oe_conformer.GetCoords().items():
2260
+ conformer[atom_index, :] = coordinates
2261
+
2262
+ conformers.append(Quantity(conformer, unit.angstrom))
2263
+
2264
+ molecule._conformers = conformers
2265
+
2266
+ def assign_partial_charges(
2267
+ self,
2268
+ molecule: "Molecule",
2269
+ partial_charge_method: str | None = None,
2270
+ use_conformers: list[Quantity] | None = None,
2271
+ strict_n_conformers: bool = False,
2272
+ normalize_partial_charges: bool = True,
2273
+ _cls=None,
2274
+ ):
2275
+ """
2276
+ Compute partial charges with OpenEye quacpac, and assign
2277
+ the new values to the partial_charges attribute.
2278
+
2279
+ .. warning :: This API is experimental and subject to change.
2280
+
2281
+ .. todo ::
2282
+
2283
+ * Should the default be ELF?
2284
+ * Can we expose more charge models?
2285
+
2286
+
2287
+ Parameters
2288
+ ----------
2289
+ molecule
2290
+ Molecule for which partial charges are to be computed
2291
+ partial_charge_method
2292
+ The charge model to use. One of ['amberff94', 'mmff', 'mmff94', 'am1-mulliken', 'am1bcc',
2293
+ 'am1bccnosymspt', 'am1bccelf10', 'gasteiger']
2294
+ If None, 'am1-mulliken' will be used.
2295
+ use_conformers
2296
+ shape (n_atoms, 3) and dimension of distance. Optional, default = None
2297
+ Coordinates to use for partial charge calculation. If None, an appropriate number
2298
+ of conformers will be generated.
2299
+ strict_n_conformers
2300
+ Whether to raise an exception if an invalid number of conformers is provided for the
2301
+ given charge method.
2302
+ If this is False and an invalid number of conformers is found, a warning will be raised.
2303
+ normalize_partial_charges
2304
+ Whether to offset partial charges so that they sum to the total formal charge of the molecule.
2305
+ This is used to prevent accumulation of rounding errors when the partial charge generation method has
2306
+ low precision.
2307
+ _cls
2308
+ Molecule constructor
2309
+
2310
+ Raises
2311
+ ------
2312
+ ChargeMethodUnavailableError if the requested charge method can not be handled by this toolkit
2313
+
2314
+ ChargeCalculationError if the charge method is supported by this toolkit, but fails
2315
+ """
2316
+
2317
+ import numpy as np
2318
+ from openeye import oechem, oequacpac
2319
+
2320
+ from openff.toolkit.topology import Molecule
2321
+
2322
+ if partial_charge_method is None:
2323
+ partial_charge_method = "am1-mulliken"
2324
+
2325
+ partial_charge_method = partial_charge_method.lower()
2326
+
2327
+ if partial_charge_method not in self._supported_charge_methods:
2328
+ raise ChargeMethodUnavailableError(
2329
+ f"partial_charge_method '{partial_charge_method}' is not available from OpenEyeToolkitWrapper. "
2330
+ f"Available charge methods are {self.supported_charge_methods}"
2331
+ )
2332
+
2333
+ charge_method: _ChargeSettings = self._supported_charge_methods[partial_charge_method]
2334
+
2335
+ if _cls is None:
2336
+ _cls = Molecule
2337
+
2338
+ # Make a temporary copy of the molecule, since we'll be messing with its conformers
2339
+ mol_copy = _cls(molecule)
2340
+
2341
+ if use_conformers is None:
2342
+ if charge_method["rec_confs"] == 0:
2343
+ mol_copy._conformers = None
2344
+ else:
2345
+ self.generate_conformers(
2346
+ mol_copy,
2347
+ n_conformers=charge_method["rec_confs"],
2348
+ rms_cutoff=0.25 * unit.angstrom,
2349
+ make_carboxylic_acids_cis=True,
2350
+ )
2351
+ # TODO: What's a "best practice" RMS cutoff to use here?
2352
+ else:
2353
+ mol_copy._conformers = None
2354
+ for conformer in use_conformers:
2355
+ mol_copy._add_conformer(conformer)
2356
+ self._check_n_conformers(
2357
+ mol_copy,
2358
+ partial_charge_method=partial_charge_method,
2359
+ min_confs=charge_method["min_confs"],
2360
+ max_confs=charge_method["max_confs"],
2361
+ strict_n_conformers=strict_n_conformers,
2362
+ )
2363
+
2364
+ oemol = mol_copy.to_openeye()
2365
+
2366
+ errfs = oechem.oeosstream()
2367
+ oechem.OEThrow.SetOutputStream(errfs)
2368
+ oechem.OEThrow.Clear()
2369
+
2370
+ oe_charge_method = getattr(oequacpac, charge_method["oe_charge_method"])
2371
+
2372
+ # The OpenFF toolkit has always supported a version of AM1BCC with no geometry optimization
2373
+ # or symmetry correction. So we include this keyword to provide a special configuration of quacpac
2374
+ # if requested.
2375
+ if partial_charge_method == "am1bccnosymspt":
2376
+ kwargs = {
2377
+ "optimize": False,
2378
+ "symmetrize": False,
2379
+ }
2380
+ elif partial_charge_method in ["gasteiger", "mmff94", "am1bccelf10"]:
2381
+ # symmetrize is implicit in gasteiger and mmff and is already set to True in am1bccelf10
2382
+ kwargs = dict()
2383
+ else:
2384
+ kwargs = {"symmetrize": True}
2385
+
2386
+ if partial_charge_method == "am1elf10":
2387
+ # special case
2388
+ charge_settings = oequacpac.OEELFCharges(
2389
+ oequacpac.OEAM1Charges(
2390
+ optimize=True,
2391
+ symmetrize=True,
2392
+ ),
2393
+ 10,
2394
+ )
2395
+
2396
+ else:
2397
+ charge_settings = oe_charge_method(**kwargs)
2398
+
2399
+ quacpac_status = oequacpac.OEAssignCharges(
2400
+ oemol,
2401
+ charge_settings,
2402
+ )
2403
+
2404
+ oechem.OEThrow.SetOutputStream(oechem.oeerr) # restoring to original state
2405
+ # This logic handles errors encountered in #34, which can occur when using ELF10 conformer selection
2406
+ if not quacpac_status:
2407
+ oe_charge_engine = (
2408
+ oequacpac.OEAM1Charges if partial_charge_method == "am1elf10" else oequacpac.OEAM1BCCCharges
2409
+ )
2410
+
2411
+ if "SelectElfPop: issue with removing trans COOH conformers" in (errfs.str().decode("UTF-8")):
2412
+ logger.warning(
2413
+ f"Warning: charge assignment involving ELF10 conformer selection failed due to a "
2414
+ f"known bug (toolkit issue #346). Downgrading to {oe_charge_engine.__name__} "
2415
+ f"charge assignment for this molecule. More information "
2416
+ f"is available at https://github.com/openforcefield/openff-toolkit/issues/346"
2417
+ )
2418
+ quacpac_status = oequacpac.OEAssignCharges(oemol, oe_charge_engine())
2419
+
2420
+ if quacpac_status is False:
2421
+ raise ChargeCalculationError(f"Unable to assign charges: {errfs.str().decode('UTF-8')}")
2422
+
2423
+ # Extract and return charges
2424
+ # TODO: Make sure atom mapping remains constant
2425
+ # Extract the list of charges, taking into account possible indexing differences
2426
+ charges = Quantity(np.zeros(shape=oemol.NumAtoms(), dtype=np.float64), unit.elementary_charge)
2427
+ for oeatom in oemol.GetAtoms():
2428
+ index = oeatom.GetIdx()
2429
+ charge = oeatom.GetPartialCharge()
2430
+ charge = charge * unit.elementary_charge
2431
+ charges[index] = charge # type: ignore[index]
2432
+
2433
+ molecule.partial_charges = charges
2434
+
2435
+ if normalize_partial_charges:
2436
+ molecule._normalize_partial_charges()
2437
+
2438
+ def assign_fractional_bond_orders(
2439
+ self,
2440
+ molecule: "Molecule",
2441
+ bond_order_model: str | None = None,
2442
+ use_conformers: list[Quantity] | None = None,
2443
+ _cls=None,
2444
+ ):
2445
+ """
2446
+ Update and store list of bond orders this molecule. Bond orders are stored on each
2447
+ bond, in the `bond.fractional_bond_order` attribute.
2448
+
2449
+ .. warning :: This API is experimental and subject to change.
2450
+
2451
+ Parameters
2452
+ ----------
2453
+ molecule
2454
+ The molecule to assign wiberg bond orders to
2455
+ bond_order_model
2456
+ The charge model to use. One of ['am1-wiberg', 'am1-wiberg-elf10',
2457
+ 'pm3-wiberg', 'pm3-wiberg-elf10']. If None, 'am1-wiberg' will be used.
2458
+ use_conformers
2459
+ The conformers to use for fractional bond order calculation. If None, an
2460
+ appropriate number of conformers will be generated by an available
2461
+ ToolkitWrapper. If the chosen ``bond_order_model`` is an ELF variant, the ELF
2462
+ conformer selection method will be applied to the provided conformers.
2463
+ _cls
2464
+ Molecule constructor
2465
+ """
2466
+ from openeye import oechem, oequacpac
2467
+
2468
+ if _cls is None:
2469
+ from openff.toolkit.topology.molecule import Molecule
2470
+
2471
+ _cls = Molecule
2472
+
2473
+ # Make a copy since we'll be messing with this molecule's conformers
2474
+ temp_mol = _cls(molecule)
2475
+
2476
+ if bond_order_model is None:
2477
+ bond_order_model = "am1-wiberg"
2478
+
2479
+ bond_order_model = bond_order_model.lower()
2480
+
2481
+ is_elf_method = bond_order_model in ["am1-wiberg-elf10", "pm3-wiberg-elf10"]
2482
+
2483
+ if use_conformers is None:
2484
+ self.generate_conformers(
2485
+ molecule=temp_mol,
2486
+ n_conformers=1 if not is_elf_method else 500,
2487
+ # 0.05 is the recommended RMS when generating a 'Dense' amount of
2488
+ # conformers using Omega: https://docs.eyesopen.com/toolkits/python/
2489
+ # omegatk/OEConfGenConstants/OEFragBuilderMode.html.
2490
+ rms_cutoff=None if not is_elf_method else 0.05 * unit.angstrom,
2491
+ make_carboxylic_acids_cis=True,
2492
+ )
2493
+ else:
2494
+ temp_mol._conformers = None
2495
+ for conformer in use_conformers:
2496
+ temp_mol._add_conformer(conformer)
2497
+ if temp_mol.n_conformers == 0:
2498
+ raise ValueError(
2499
+ "No conformers present in molecule submitted for fractional bond order calculation. Consider "
2500
+ "loading the molecule from a file with geometry already present or running "
2501
+ "molecule.generate_conformers() before calling molecule.compute_wiberg_bond_orders()"
2502
+ )
2503
+
2504
+ if is_elf_method:
2505
+ # Apply the ELF10 conformer selection method.
2506
+ temp_mol.apply_elf_conformer_selection()
2507
+
2508
+ # Set the options to use when computing the WBOs. This is based on example at
2509
+ # https://docs.eyesopen.com/toolkits/python/quacpactk/examples_summary_wibergbondorders.html
2510
+ am1 = oequacpac.OEAM1()
2511
+
2512
+ am1results = oequacpac.OEAM1Results()
2513
+ am1options = am1.GetOptions()
2514
+
2515
+ if bond_order_model.startswith("am1-wiberg"):
2516
+ am1options.SetSemiMethod(oequacpac.OEMethodType_AM1)
2517
+ elif bond_order_model.startswith("pm3-wiberg"):
2518
+ # TODO: Make sure that modifying am1options actually works
2519
+ am1options.SetSemiMethod(oequacpac.OEMethodType_PM3)
2520
+ else:
2521
+ raise ValueError(
2522
+ f"Bond order model '{bond_order_model}' is not supported by "
2523
+ f"OpenEyeToolkitWrapper. Supported models are ['am1-wiberg', "
2524
+ f"'am1-wiberg-elf10', 'pm3-wiberg', 'pm3-wiberg-elf10']."
2525
+ )
2526
+
2527
+ # Convert the conformers into OE friendly objects to make setting them one
2528
+ # at a time easier.
2529
+ oe_conformers = [
2530
+ oechem.OEFloatArray(conformer.m_as(unit.angstrom).flatten()) for conformer in temp_mol.conformers
2531
+ ]
2532
+
2533
+ oemol = self.to_openeye(temp_mol)
2534
+ bond_orders = defaultdict(list)
2535
+
2536
+ for oe_conformer in oe_conformers:
2537
+ oemol.DeleteConfs()
2538
+ oemol.NewConf(oe_conformer)
2539
+
2540
+ status = am1.CalcAM1(am1results, oemol)
2541
+
2542
+ if status is False:
2543
+ raise OpenEyeError("Unable to assign charges (in the process of calculating fractional bond orders)")
2544
+
2545
+ for bond in oemol.GetBonds():
2546
+ bond_orders[bond.GetIdx()].append(am1results.GetBondOrder(bond.GetBgnIdx(), bond.GetEndIdx()))
2547
+
2548
+ # TODO: Will bonds always map back to the same index? Consider doing a
2549
+ # topology mapping.
2550
+ for bond_idx, conformer_bond_orders in bond_orders.items():
2551
+ # Get bond order
2552
+ order = np.mean(conformer_bond_orders)
2553
+
2554
+ mol_bond = molecule._bonds[bond_idx]
2555
+ mol_bond.fractional_bond_order = order
2556
+
2557
+ def get_tagged_smarts_connectivity(self, smarts: str) -> tuple[TTA, ...]:
2558
+ """
2559
+ Returns a tuple of tuples indicating connectivity between tagged atoms in a SMARTS string. Does not
2560
+ return bond order.
2561
+
2562
+ Parameters
2563
+ ----------
2564
+ smarts
2565
+ The tagged SMARTS to analyze
2566
+
2567
+ Returns
2568
+ -------
2569
+ unique_tags
2570
+ A sorted tuple of all unique tagged atom map indices.
2571
+ tagged_atom_connectivity
2572
+ A tuple of tuples, where each inner tuple is a pair of tagged atoms
2573
+ (tag_idx_1, tag_idx_2) which are bonded. The inner tuples are ordered
2574
+ smallest-to-largest, and the tuple of tuples is ordered lexically. The
2575
+ return value for an improper torsion would be ((1, 2), (2, 3), (2, 4)).
2576
+
2577
+ Raises
2578
+ ------
2579
+ SMIRKSParsingError
2580
+ If OpenEye toolkit was unable to parse the provided smirks/tagged smarts
2581
+ """
2582
+ from openeye import oechem
2583
+
2584
+ from openff.toolkit.utils.exceptions import SMIRKSParsingError
2585
+
2586
+ qmol = oechem.OEQMol()
2587
+ status = oechem.OEParseSmarts(qmol, smarts)
2588
+ if not status:
2589
+ raise SMIRKSParsingError(f"OpenEye Toolkit was unable to parse SMIRKS {smarts}")
2590
+
2591
+ _unique_tags = set()
2592
+ _connections = set()
2593
+ for at1 in qmol.GetAtoms():
2594
+ if at1.GetMapIdx() == 0:
2595
+ continue
2596
+ _unique_tags.add(at1.GetMapIdx())
2597
+ for at2 in at1.GetAtoms():
2598
+ if at2.GetMapIdx() == 0:
2599
+ continue
2600
+ cxn_to_add = sorted([at1.GetMapIdx(), at2.GetMapIdx()])
2601
+ _connections.add(tuple(cxn_to_add))
2602
+ connections: TTA = tuple(sorted(list(_connections)))
2603
+ unique_tags: TTA = tuple(sorted(list(_unique_tags)))
2604
+ return unique_tags, connections
2605
+
2606
+ @staticmethod
2607
+ def _find_smarts_matches(
2608
+ oemol,
2609
+ smarts: str,
2610
+ aromaticity_model=DEFAULT_AROMATICITY_MODEL,
2611
+ unique: bool = False,
2612
+ ) -> list[tuple[int, ...]]:
2613
+ """Find all sets of atoms in the provided OpenEye molecule that match the provided SMARTS string.
2614
+
2615
+ Parameters
2616
+ ----------
2617
+ oemol
2618
+ oemol to process with the SMIRKS in order to find matches
2619
+ smarts
2620
+ SMARTS string with any number of sequentially tagged atoms.
2621
+ If there are N tagged atoms numbered 1..N, the resulting matches will be N-tuples of
2622
+ atoms that match the corresponding tagged atoms.
2623
+ aromaticity_model
2624
+ The aromaticity model to use. Only OEAroModel_MDL is supported.
2625
+ Molecule is prepared with this aromaticity model prior to querying.
2626
+ unique
2627
+ If True, only return unique matches. If False, return all matches. This is passed to
2628
+ OpenEye's ``OESubSearch`` as ``uniquematch``.
2629
+
2630
+ Returns
2631
+ -------
2632
+ matches
2633
+ matches[index] is an N-tuple of atom numbers from the ``oemol``
2634
+ Matches are returned in no guaranteed order.
2635
+ # TODO: What is returned if no matches are found? An empty list, or None?
2636
+ # TODO: Ensure that SMARTS numbers 1, 2, 3... are rendered into order of returned
2637
+ # matches indexed by 0, 1, 2...
2638
+
2639
+ .. notes ::
2640
+
2641
+ * Raises ``LicenseError`` if valid OpenEye tools license is not found, rather than
2642
+ causing program to terminate
2643
+ * Raises ``ChemicalEnvironmentParsingError`` if ``smarts`` query is malformed
2644
+
2645
+ """
2646
+ from openeye import oechem
2647
+ from openeye.oechem import OESubSearch
2648
+
2649
+ from openff.toolkit.utils.exceptions import ChemicalEnvironmentParsingError
2650
+
2651
+ # Make a copy of molecule so we don't influence original (probably safer than deepcopy per C Bayly)
2652
+ mol = oechem.OEMol(oemol)
2653
+ # Set up query
2654
+ qmol = oechem.OEQMol()
2655
+ if not oechem.OEParseSmarts(qmol, smarts):
2656
+ raise ChemicalEnvironmentParsingError(f'OpenEye could not parse the SMARTS/SMIRKS string "{smarts}"')
2657
+
2658
+ # OEPrepareSearch will clobber our desired aromaticity model if we don't sync up mol
2659
+ # and qmol ahead of time.
2660
+
2661
+ oechem.OEClearAromaticFlags(qmol)
2662
+
2663
+ if aromaticity_model == "OEAroModel_MDL":
2664
+ oechem.OEAssignAromaticFlags(qmol, oechem.OEAroModel_MDL)
2665
+ else:
2666
+ raise InvalidAromaticityModelError(
2667
+ f"Given aromaticity model {aromaticity_model} which is not in the set of allowed aromaticity models: "
2668
+ f"{ALLOWED_AROMATICITY_MODELS}"
2669
+ )
2670
+
2671
+ # oechem.OEAssignHybridization(mol)
2672
+ oechem.OEAssignHybridization(qmol)
2673
+
2674
+ # Build list of matches
2675
+ # TODO: The MoleculeImage mapping should preserve ordering of template molecule for equivalent atoms
2676
+ # and speed matching for larger molecules.
2677
+ substructure_search = OESubSearch(qmol)
2678
+ # TODO: max_matches = int(max_matches) if max_matches is not None else 0
2679
+ max_matches = 0
2680
+ substructure_search.SetMaxMatches(max_matches)
2681
+ oechem.OEPrepareSearch(mol, substructure_search)
2682
+ matches = list()
2683
+ for match in substructure_search.Match(mol, unique):
2684
+ # Compile list of atom indices that match the pattern tags
2685
+ atom_indices: dict[int, int] = dict()
2686
+ for matched_atom in match.GetAtoms():
2687
+ if matched_atom.pattern.GetMapIdx() != 0:
2688
+ atom_indices[matched_atom.pattern.GetMapIdx() - 1] = matched_atom.target.GetIdx()
2689
+
2690
+ # Compress into tuple
2691
+ matches.append(tuple(atom_indices[index] for index in range(len(atom_indices))))
2692
+
2693
+ return matches
2694
+
2695
+ def find_smarts_matches(
2696
+ self,
2697
+ molecule: "Molecule",
2698
+ smarts: str,
2699
+ aromaticity_model=DEFAULT_AROMATICITY_MODEL,
2700
+ unique=False,
2701
+ ) -> list[tuple[int, ...]]:
2702
+ """
2703
+ Find all SMARTS matches for the specified molecule, using the specified aromaticity model.
2704
+
2705
+ .. warning :: This API is experimental and subject to change.
2706
+
2707
+ Parameters
2708
+ ----------
2709
+ molecule
2710
+ The molecule for which all specified SMARTS matches are to be located
2711
+ smarts
2712
+ SMARTS string with optional SMIRKS-style atom tagging
2713
+ aromaticity_model
2714
+ The aromaticity model to use. Only OEAroModel_MDL is supported.
2715
+ unique
2716
+ If True, only return unique matches. If False, return all matches.
2717
+
2718
+ .. note :: Currently, the only supported ``aromaticity_model`` is ``OEAroModel_MDL``
2719
+
2720
+ """
2721
+ oemol, _ = self._connection_table_to_openeye(molecule)
2722
+ return self._find_smarts_matches(
2723
+ oemol,
2724
+ smarts,
2725
+ aromaticity_model=aromaticity_model,
2726
+ unique=unique,
2727
+ )
2728
+
2729
+
2730
+ def requires_openeye_module(module_name):
2731
+ def inner_decorator(function):
2732
+ @wraps(function)
2733
+ def wrapper(*args, **kwargs):
2734
+ try:
2735
+ module = importlib.import_module("openeye." + module_name)
2736
+ except ImportError:
2737
+ raise OpenEyeImportError("openeye." + module_name)
2738
+ try:
2739
+ license_func = OpenEyeToolkitWrapper._license_functions[module_name]
2740
+ except KeyError:
2741
+ raise OpenEyeImportError(f"we do not currently use {module_name}")
2742
+
2743
+ # TODO: Custom exception
2744
+ assert getattr(module, license_func)()
2745
+
2746
+ return function(*args, **kwargs)
2747
+
2748
+ return wrapper
2749
+
2750
+ return inner_decorator