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,4418 @@
1
+ """
2
+ Tests for cheminformatics toolkit wrappers
3
+
4
+ """
5
+
6
+ import logging
7
+ import os
8
+ import pathlib
9
+ from tempfile import NamedTemporaryFile
10
+
11
+ import numpy as np
12
+ import pytest
13
+ from numpy.testing import assert_almost_equal
14
+
15
+ from openff.toolkit import Quantity, unit
16
+ from openff.toolkit._tests.create_molecules import (
17
+ create_acetaldehyde,
18
+ create_acetate,
19
+ create_cyclic_n3h3,
20
+ create_cyclohexane,
21
+ create_ethanol,
22
+ create_reversed_ethanol,
23
+ topology_with_metadata,
24
+ )
25
+ from openff.toolkit._tests.utils import (
26
+ requires_ambertools,
27
+ requires_openeye,
28
+ requires_rdkit,
29
+ )
30
+ from openff.toolkit.topology.molecule import Atom, Molecule
31
+ from openff.toolkit.utils import get_data_file_path
32
+ from openff.toolkit.utils.exceptions import (
33
+ ChargeMethodUnavailableError,
34
+ ChemicalEnvironmentParsingError,
35
+ ConformerGenerationError,
36
+ EmptyInChiError,
37
+ InChIParseError,
38
+ IncorrectNumConformersError,
39
+ IncorrectNumConformersWarning,
40
+ InvalidIUPACNameError,
41
+ InvalidToolkitError,
42
+ MultipleComponentsInMoleculeWarning,
43
+ NotAttachedToMoleculeError,
44
+ RadicalsNotSupportedError,
45
+ ToolkitUnavailableException,
46
+ UndefinedStereochemistryError,
47
+ )
48
+ from openff.toolkit.utils.toolkits import (
49
+ GLOBAL_TOOLKIT_REGISTRY,
50
+ AmberToolsToolkitWrapper,
51
+ BuiltInToolkitWrapper,
52
+ GAFFAtomTypeWarning,
53
+ OpenEyeToolkitWrapper,
54
+ RDKitToolkitWrapper,
55
+ ToolkitRegistry,
56
+ ToolkitWrapper,
57
+ )
58
+
59
+ _rng = np.random.default_rng()
60
+
61
+
62
+ def get_mini_drug_bank(toolkit_class, xfail_mols=None):
63
+ """Read the mini drug bank sdf file with the toolkit and return the molecules"""
64
+ # This is a work around a weird error where even though the test is skipped due to a missing toolkit
65
+ # we still try and read the file with the toolkit
66
+ if toolkit_class.is_available():
67
+ toolkit = toolkit_class()
68
+ molecules = Molecule.from_file(
69
+ get_data_file_path("molecules/MiniDrugBank.sdf"),
70
+ "sdf",
71
+ toolkit_registry=toolkit,
72
+ allow_undefined_stereo=True,
73
+ )
74
+ else:
75
+ molecules = []
76
+
77
+ if xfail_mols is None:
78
+ return molecules
79
+
80
+ for i, mol in enumerate(molecules):
81
+ if mol.name in xfail_mols:
82
+ marker = pytest.mark.xfail(reason=xfail_mols[mol.name])
83
+ molecules[i] = pytest.param(mol, marks=marker)
84
+
85
+ return molecules
86
+
87
+
88
+ openeye_inchi_stereochemistry_lost = [
89
+ "DrugBank_2799",
90
+ "DrugBank_5414",
91
+ "DrugBank_5415",
92
+ "DrugBank_5418",
93
+ "DrugBank_2955",
94
+ "DrugBank_2987",
95
+ "DrugBank_5555",
96
+ "DrugBank_472",
97
+ "DrugBank_5737",
98
+ "DrugBank_3332",
99
+ "DrugBank_3461",
100
+ "DrugBank_794",
101
+ "DrugBank_3502",
102
+ "DrugBank_6026",
103
+ "DrugBank_3622",
104
+ "DrugBank_977",
105
+ "DrugBank_3693",
106
+ "DrugBank_3726",
107
+ "DrugBank_3739",
108
+ "DrugBank_6222",
109
+ "DrugBank_6232",
110
+ "DrugBank_3844",
111
+ "DrugBank_6295",
112
+ "DrugBank_6304",
113
+ "DrugBank_6305",
114
+ "DrugBank_3930",
115
+ "DrugBank_6329",
116
+ "DrugBank_6353",
117
+ "DrugBank_6355",
118
+ "DrugBank_6401",
119
+ "DrugBank_4161",
120
+ "DrugBank_4162",
121
+ "DrugBank_6509",
122
+ "DrugBank_6531",
123
+ "DrugBank_1570",
124
+ "DrugBank_4249",
125
+ "DrugBank_1634",
126
+ "DrugBank_1659",
127
+ "DrugBank_6647",
128
+ "DrugBank_1700",
129
+ "DrugBank_1721",
130
+ "DrugBank_1742",
131
+ "DrugBank_1802",
132
+ "DrugBank_6775",
133
+ "DrugBank_1849",
134
+ "DrugBank_1864",
135
+ "DrugBank_6875",
136
+ "DrugBank_1897",
137
+ "DrugBank_4593",
138
+ "DrugBank_1962",
139
+ "DrugBank_4662",
140
+ "DrugBank_7049",
141
+ "DrugBank_4702",
142
+ "DrugBank_2095",
143
+ "DrugBank_4778",
144
+ "DrugBank_2141",
145
+ "DrugBank_2148",
146
+ "DrugBank_2178",
147
+ "DrugBank_4865",
148
+ "DrugBank_2208",
149
+ "DrugBank_2210",
150
+ "DrugBank_2276",
151
+ "DrugBank_4959",
152
+ "DrugBank_4964",
153
+ "DrugBank_5043",
154
+ "DrugBank_2429",
155
+ "DrugBank_5076",
156
+ "DrugBank_2465",
157
+ "DrugBank_2519",
158
+ "DrugBank_2538",
159
+ "DrugBank_5158",
160
+ "DrugBank_5176",
161
+ "DrugBank_2592",
162
+ ]
163
+
164
+ openeye_inchi_isomorphic_fails = ["DrugBank_1661", "DrugBank_4346", "DrugBank_2467"]
165
+
166
+ rdkit_inchi_stereochemistry_lost = [
167
+ "DrugBank_5414",
168
+ "DrugBank_2955",
169
+ "DrugBank_5737",
170
+ "DrugBank_3332",
171
+ "DrugBank_3461",
172
+ "DrugBank_6026",
173
+ "DrugBank_3622",
174
+ "DrugBank_3726",
175
+ "DrugBank_6222",
176
+ "DrugBank_3844",
177
+ "DrugBank_6304",
178
+ "DrugBank_6305",
179
+ "DrugBank_6329",
180
+ "DrugBank_6509",
181
+ "DrugBank_6647",
182
+ "DrugBank_1897",
183
+ "DrugBank_4778",
184
+ "DrugBank_2148",
185
+ "DrugBank_2178",
186
+ "DrugBank_2538",
187
+ "DrugBank_2592",
188
+ "DrugBank_4249",
189
+ "DrugBank_5076",
190
+ "DrugBank_5418",
191
+ "DrugBank_3930",
192
+ "DrugBank_1634",
193
+ "DrugBank_1962",
194
+ "DrugBank_5043",
195
+ "DrugBank_2519",
196
+ ]
197
+
198
+ openeye_iupac_bad_stereo = [
199
+ "DrugBank_977",
200
+ "DrugBank_1634",
201
+ "DrugBank_1700",
202
+ "DrugBank_1962",
203
+ "DrugBank_2148",
204
+ "DrugBank_2178",
205
+ "DrugBank_2186",
206
+ "DrugBank_2208",
207
+ "DrugBank_2519",
208
+ "DrugBank_2538",
209
+ "DrugBank_2592",
210
+ "DrugBank_2651",
211
+ "DrugBank_2987",
212
+ "DrugBank_3332",
213
+ "DrugBank_3502",
214
+ "DrugBank_3622",
215
+ "DrugBank_3726",
216
+ "DrugBank_3844",
217
+ "DrugBank_3930",
218
+ "DrugBank_4161",
219
+ "DrugBank_4162",
220
+ "DrugBank_4778",
221
+ "DrugBank_4593",
222
+ "DrugBank_4959",
223
+ "DrugBank_5043",
224
+ "DrugBank_5076",
225
+ "DrugBank_5176",
226
+ "DrugBank_5418",
227
+ "DrugBank_5737",
228
+ "DrugBank_5902",
229
+ "DrugBank_6295",
230
+ "DrugBank_6304",
231
+ "DrugBank_6305",
232
+ "DrugBank_6329",
233
+ "DrugBank_6355",
234
+ "DrugBank_6401",
235
+ "DrugBank_6509",
236
+ "DrugBank_6531",
237
+ "DrugBank_6647",
238
+ "DrugBank_390",
239
+ "DrugBank_810",
240
+ "DrugBank_4316",
241
+ "DrugBank_4346",
242
+ "DrugBank_7124",
243
+ "DrugBank_2799",
244
+ "DrugBank_4662",
245
+ "DrugBank_4865",
246
+ "DrugBank_2465",
247
+ ]
248
+
249
+
250
+ @pytest.fixture()
251
+ def formic_acid_molecule() -> Molecule:
252
+ formic_acid = Molecule()
253
+ formic_acid.add_atom(8, 0, False) # O1
254
+ formic_acid.add_atom(6, 0, False) # C1
255
+ formic_acid.add_atom(8, 0, False) # O2
256
+ formic_acid.add_atom(1, 0, False) # H1
257
+ formic_acid.add_atom(1, 0, False) # H2
258
+ formic_acid.add_bond(0, 1, 2, False) # O1 - C1
259
+ formic_acid.add_bond(1, 2, 1, False) # C1 - O2
260
+ formic_acid.add_bond(1, 3, 1, False) # C1 - H1
261
+ formic_acid.add_bond(2, 4, 1, False) # O2 - H2
262
+
263
+ return formic_acid
264
+
265
+
266
+ @pytest.fixture()
267
+ def formic_acid_conformers() -> dict[str, Quantity]:
268
+ return {
269
+ "cis": Quantity(
270
+ np.array(
271
+ [
272
+ [-0.95927322, -0.91789997, 0.36333418],
273
+ [-0.34727824, 0.12828046, 0.22784603],
274
+ [0.82766682, 0.26871252, -0.42284882],
275
+ [-0.67153811, 1.10376000, 0.61921501],
276
+ [1.15035689, -0.58282924, -0.78766006],
277
+ ]
278
+ ),
279
+ unit.angstrom,
280
+ ),
281
+ "trans": Quantity(
282
+ np.array(
283
+ [
284
+ [-0.95927322, -0.91789997, 0.36333418],
285
+ [-0.34727824, 0.12828046, 0.22784603],
286
+ [0.82766682, 0.26871252, -0.42284882],
287
+ [-0.67153811, 1.10376000, 0.61921501],
288
+ [1.14532626, 1.19679034, -0.41266876],
289
+ ]
290
+ ),
291
+ unit.angstrom,
292
+ ),
293
+ }
294
+
295
+
296
+ @requires_openeye
297
+ class TestOpenEyeToolkitWrapper:
298
+ """Test the OpenEyeToolkitWrapper"""
299
+
300
+ # TODO: Make separate smiles_add_H and smiles_explicit_H tests
301
+
302
+ def test_supported_charge_methods(self):
303
+ methods = OpenEyeToolkitWrapper().supported_charge_methods
304
+
305
+ assert "am1-mulliken" in methods
306
+ assert "am1bcc" in methods
307
+ assert "am1bccelf10" in methods
308
+ assert "am1elf10" in methods
309
+ assert "am1bccnosymspt" in methods
310
+ assert "mmff94" in methods
311
+ assert "gasteiger" in methods
312
+
313
+ assert "zeros" not in methods
314
+ assert "formal_charge" not in methods
315
+
316
+ def test_smiles(self):
317
+ """Test OpenEyeToolkitWrapper to_smiles() and from_smiles()"""
318
+ toolkit_wrapper = OpenEyeToolkitWrapper()
319
+
320
+ # This differs from RDKit's SMILES due to different canonicalization schemes
321
+
322
+ smiles = "[H]C([H])([H])C([H])([H])[H]"
323
+ molecule = Molecule.from_smiles(smiles, toolkit_registry=toolkit_wrapper)
324
+ # When creating an OFFMol from SMILES, partial charges should be initialized to None
325
+ assert molecule.partial_charges is None
326
+ smiles2 = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
327
+ assert smiles == smiles2
328
+
329
+ def test_smiles_missing_stereochemistry(self):
330
+ """Test OpenEyeToolkitWrapper to_smiles() and from_smiles()"""
331
+ toolkit_wrapper = OpenEyeToolkitWrapper()
332
+
333
+ unspec_chiral_smiles = r"C\C(F)=C(/F)CC(C)(Cl)Br"
334
+ spec_chiral_smiles = r"C\C(F)=C(/F)C[C@@](C)(Cl)Br"
335
+ unspec_db_smiles = r"CC(F)=C(F)C[C@@](C)(Cl)Br"
336
+ spec_db_smiles = r"C\C(F)=C(/F)C[C@@](C)(Cl)Br"
337
+
338
+ for smiles, raises_exception in [
339
+ (unspec_chiral_smiles, True),
340
+ (spec_chiral_smiles, False),
341
+ (unspec_db_smiles, True),
342
+ (spec_db_smiles, False),
343
+ ]:
344
+ if raises_exception:
345
+ with pytest.raises(UndefinedStereochemistryError):
346
+ Molecule.from_smiles(smiles, toolkit_registry=toolkit_wrapper)
347
+ Molecule.from_smiles(
348
+ smiles,
349
+ toolkit_registry=toolkit_wrapper,
350
+ allow_undefined_stereo=True,
351
+ )
352
+ else:
353
+ Molecule.from_smiles(smiles, toolkit_registry=toolkit_wrapper)
354
+
355
+ def test_openeye_from_smiles_radical(self):
356
+ """Test that parsing an SMILES with a radical raises RadicalsNotSupportedError."""
357
+ with pytest.raises(RadicalsNotSupportedError):
358
+ OpenEyeToolkitWrapper().from_smiles("[CH3]")
359
+
360
+ def test_openeye_from_smiles_transition_metal_radical(self):
361
+ """Test that parsing an SMILES with a transition metal radical works."""
362
+ OpenEyeToolkitWrapper().from_smiles("[Zn+2]")
363
+
364
+ # TODO: test_smiles_round_trip
365
+
366
+ def test_smiles_add_H(self):
367
+ """Test OpenEyeToolkitWrapper for adding explicit hydrogens"""
368
+ toolkit_wrapper = OpenEyeToolkitWrapper()
369
+ # This differs from RDKit's SMILES due to different canonicalization schemes
370
+ input_smiles = "CC"
371
+ expected_output_smiles = "[H]C([H])([H])C([H])([H])[H]"
372
+ molecule = Molecule.from_smiles(input_smiles, toolkit_registry=toolkit_wrapper)
373
+ smiles2 = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
374
+ assert expected_output_smiles == smiles2
375
+
376
+ def test_smiles_charged(self):
377
+ """Test OpenEyeToolkitWrapper functions for reading/writing charged SMILES"""
378
+ toolkit_wrapper = OpenEyeToolkitWrapper()
379
+ # This differs from RDKit's expected output due to different canonicalization schemes
380
+ smiles = "[H]C([H])([H])[N+]([H])([H])[H]"
381
+ molecule = Molecule.from_smiles(smiles, toolkit_registry=toolkit_wrapper)
382
+ smiles2 = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
383
+ assert smiles == smiles2
384
+
385
+ def test_to_from_openeye_core_props_filled(self):
386
+ """Test OpenEyeToolkitWrapper to_openeye() and from_openeye()"""
387
+ toolkit_wrapper = OpenEyeToolkitWrapper()
388
+
389
+ # Replacing with a simple molecule with stereochemistry
390
+ input_smiles = r"C\C(F)=C(/F)C[C@@](C)(Cl)Br"
391
+ expected_output_smiles = r"[H]C([H])([H])/C(=C(/C([H])([H])[C@@](C([H])([H])[H])(Cl)Br)\F)/F"
392
+ molecule = Molecule.from_smiles(input_smiles, toolkit_registry=toolkit_wrapper)
393
+ assert molecule.to_smiles(toolkit_registry=toolkit_wrapper) == expected_output_smiles
394
+
395
+ # Populate core molecule property fields
396
+ molecule.name = "Alice"
397
+ partial_charges = Quantity(
398
+ np.array(
399
+ [
400
+ -0.9,
401
+ -0.8,
402
+ -0.7,
403
+ -0.6,
404
+ -0.5,
405
+ -0.4,
406
+ -0.3,
407
+ -0.2,
408
+ -0.1,
409
+ 0.0,
410
+ 0.1,
411
+ 0.2,
412
+ 0.3,
413
+ 0.4,
414
+ 0.5,
415
+ 0.6,
416
+ 0.7,
417
+ 0.8,
418
+ ]
419
+ ),
420
+ unit.elementary_charge,
421
+ )
422
+ molecule.partial_charges = partial_charges
423
+ coords = Quantity(
424
+ np.array(
425
+ [
426
+ ["0.0", "1.0", "2.0"],
427
+ ["3.0", "4.0", "5.0"],
428
+ ["6.0", "7.0", "8.0"],
429
+ ["9.0", "10.0", "11.0"],
430
+ ["12.0", "13.0", "14.0"],
431
+ ["15.0", "16.0", "17.0"],
432
+ ["18.0", "19.0", "20.0"],
433
+ ["21.0", "22.0", "23.0"],
434
+ ["24.0", "25.0", "26.0"],
435
+ ["27.0", "28.0", "29.0"],
436
+ ["30.0", "31.0", "32.0"],
437
+ ["33.0", "34.0", "35.0"],
438
+ ["36.0", "37.0", "38.0"],
439
+ ["39.0", "40.0", "41.0"],
440
+ ["42.0", "43.0", "44.0"],
441
+ ["45.0", "46.0", "47.0"],
442
+ ["48.0", "49.0", "50.0"],
443
+ ["51.0", "52.0", "53.0"],
444
+ ]
445
+ ),
446
+ unit.angstrom,
447
+ )
448
+ molecule.add_conformer(coords)
449
+ # Populate core atom property fields
450
+ molecule.atoms[2].name = "Bob"
451
+ # Ensure one atom has its stereochemistry specified
452
+ central_carbon_stereo_specified = False
453
+ for atom in molecule.atoms:
454
+ if (atom.atomic_number == 6) and atom.stereochemistry == "S":
455
+ central_carbon_stereo_specified = True
456
+ assert central_carbon_stereo_specified
457
+
458
+ # Populate bond core property fields
459
+ fractional_bond_orders = [float(val) for val in range(1, 19)]
460
+ for fbo, bond in zip(fractional_bond_orders, molecule.bonds):
461
+ bond.fractional_bond_order = fbo
462
+
463
+ # Do a first conversion to/from oemol
464
+ oemol = molecule.to_openeye()
465
+ molecule2 = Molecule.from_openeye(oemol)
466
+
467
+ # Test that properties survived first conversion
468
+ # assert molecule.to_dict() == molecule2.to_dict()
469
+ assert molecule.name == molecule2.name
470
+ # NOTE: This expects the same indexing scheme in the original and new molecule
471
+
472
+ central_carbon_stereo_specified = False
473
+ for atom in molecule2.atoms:
474
+ if (atom.atomic_number == 6) and atom.stereochemistry == "S":
475
+ central_carbon_stereo_specified = True
476
+ assert central_carbon_stereo_specified
477
+ for atom1, atom2 in zip(molecule.atoms, molecule2.atoms):
478
+ # OpenEye wrapper always adds hierarchy metadata (residue name + num) info, so account for that
479
+ atom1_dict = atom1.to_dict()
480
+ atom1_dict["metadata"].update(
481
+ {
482
+ "residue_name": "UNL",
483
+ "residue_number": 1,
484
+ "insertion_code": " ",
485
+ "chain_id": " ",
486
+ }
487
+ )
488
+ assert atom1_dict == atom2.to_dict()
489
+ for bond1, bond2 in zip(molecule.bonds, molecule2.bonds):
490
+ assert bond1.to_dict() == bond2.to_dict()
491
+ assert (molecule.conformers[0] == molecule2.conformers[0]).all()
492
+ for pc1, pc2 in zip(molecule._partial_charges, molecule2._partial_charges):
493
+ pc1_ul = pc1.m_as(unit.elementary_charge)
494
+ pc2_ul = pc2.m_as(unit.elementary_charge)
495
+ assert_almost_equal(pc1_ul, pc2_ul, decimal=6)
496
+ assert molecule2.to_smiles(toolkit_registry=toolkit_wrapper) == expected_output_smiles
497
+
498
+ def test_to_from_openeye_core_props_unset(self):
499
+ """Test OpenEyeToolkitWrapper to_openeye() and from_openeye() when given empty core property fields"""
500
+ toolkit_wrapper = OpenEyeToolkitWrapper()
501
+
502
+ # Using a simple molecule with tetrahedral and bond stereochemistry
503
+ input_smiles = r"C\C(F)=C(/F)C[C@](C)(Cl)Br"
504
+
505
+ expected_output_smiles = r"[H]C([H])([H])/C(=C(/C([H])([H])[C@](C([H])([H])[H])(Cl)Br)\F)/F"
506
+ molecule = Molecule.from_smiles(input_smiles, toolkit_registry=toolkit_wrapper)
507
+ assert molecule.to_smiles(toolkit_registry=toolkit_wrapper) == expected_output_smiles
508
+
509
+ # Ensure one atom has its stereochemistry specified
510
+ central_carbon_stereo_specified = False
511
+ for atom in molecule.atoms:
512
+ if (atom.atomic_number == 6) and atom.stereochemistry == "R":
513
+ central_carbon_stereo_specified = True
514
+ assert central_carbon_stereo_specified
515
+
516
+ # Do a first conversion to/from oemol
517
+ oemol = molecule.to_openeye()
518
+ molecule2 = Molecule.from_openeye(oemol)
519
+
520
+ # Test that properties survived first conversion
521
+ assert molecule.name == molecule2.name
522
+ # NOTE: This expects the same indexing scheme in the original and new molecule
523
+
524
+ central_carbon_stereo_specified = False
525
+ for atom in molecule2.atoms:
526
+ if (atom.atomic_number == 6) and atom.stereochemistry == "R":
527
+ central_carbon_stereo_specified = True
528
+ assert central_carbon_stereo_specified
529
+ for atom1, atom2 in zip(molecule.atoms, molecule2.atoms):
530
+ # OpenEye wrapper always adds hierarchy metadata (residue name + num) info, so account for that
531
+ atom1_dict = atom1.to_dict()
532
+ atom1_dict["metadata"].update(
533
+ {
534
+ "residue_name": "UNL",
535
+ "residue_number": 1,
536
+ "insertion_code": " ",
537
+ "chain_id": " ",
538
+ }
539
+ )
540
+ assert atom1_dict == atom2.to_dict()
541
+ for bond1, bond2 in zip(molecule.bonds, molecule2.bonds):
542
+ assert bond1.to_dict() == bond2.to_dict()
543
+ # The molecule was initialized from SMILES, so mol.conformers arrays should be None for both
544
+ assert molecule.conformers is None
545
+ assert molecule2.conformers is None
546
+ # The molecule was initialized from SMILES, so mol.partial_charges arrays should be None for both
547
+ assert molecule.partial_charges is None
548
+ assert molecule2.partial_charges is None
549
+
550
+ assert molecule2.to_smiles(toolkit_registry=toolkit_wrapper) == expected_output_smiles
551
+
552
+ def test_sd_tags_in_graph_mol_preserved(self):
553
+ from openeye import oechem
554
+
555
+ graph = oechem.OEGraphMol()
556
+
557
+ oechem.OEParseSmiles(graph, "CCO")
558
+
559
+ oechem.OEAddSDData(graph, "cat", "meow")
560
+
561
+ assert Molecule.from_openeye(graph).properties["cat"] == "meow"
562
+
563
+ def test_to_from_openeye_none_partial_charges(self):
564
+ """Test to ensure that to_openeye and from_openeye correctly handle None partial charges"""
565
+ import math
566
+
567
+ # Create ethanol, which has partial charges defined with float values
568
+ ethanol = create_ethanol()
569
+ assert ethanol.partial_charges is not None
570
+ # Convert to OEMol, which should populate the partial charges on
571
+ # the OEAtoms with the same partial charges
572
+ oemol = ethanol.to_openeye()
573
+ for oeatom in oemol.GetAtoms():
574
+ assert not math.isnan(oeatom.GetPartialCharge())
575
+ # Change the first OEAtom's partial charge to nan, and ensure that it comes
576
+ # back to OFFMol with only the first atom as nan
577
+ for oeatom in oemol.GetAtoms():
578
+ oeatom.SetPartialCharge(float("nan"))
579
+ break
580
+ eth_from_oe = Molecule.from_openeye(oemol)
581
+ assert math.isnan(eth_from_oe.partial_charges[0].m_as(unit.elementary_charge))
582
+ for pc in eth_from_oe.partial_charges[1:]:
583
+ assert not math.isnan(pc.m_as(unit.elementary_charge))
584
+ # Then, set all the OEMol's partial charges to nan, and ensure that
585
+ # from_openeye produces an OFFMol with partial_charges = None
586
+ for oeatom in oemol.GetAtoms():
587
+ oeatom.SetPartialCharge(float("nan"))
588
+ eth_from_oe = Molecule.from_openeye(oemol)
589
+ assert eth_from_oe.partial_charges is None
590
+
591
+ # Send the OFFMol with partial_charges = None back to OEMol, and
592
+ # ensure that all its charges are nan
593
+ oemol2 = eth_from_oe.to_openeye()
594
+ for oeatom in oemol2.GetAtoms():
595
+ assert math.isnan(oeatom.GetPartialCharge())
596
+
597
+ def test_to_openeye_typed_partial_charges(self):
598
+ ethanol = create_ethanol()
599
+ ethanol.partial_charges = Quantity(np.zeros(ethanol.n_atoms, dtype=int), unit.elementary_charge)
600
+ oemol = ethanol.to_openeye()
601
+ for oeatom in oemol.GetAtoms():
602
+ assert np.isclose(oeatom.GetPartialCharge(), 0)
603
+
604
+ def test_to_from_openeye_hierarchy_metadata(self):
605
+ """
606
+ Test roundtripping to/from ``OpenEyeToolkitWrapper`` for molecules with PDB hierarchy metadata
607
+ """
608
+ from openeye import oechem
609
+
610
+ for molecule in topology_with_metadata().molecules:
611
+ oemol = molecule.to_openeye()
612
+ roundtrip_mol = Molecule.from_openeye(oemol)
613
+
614
+ # Check OEMol
615
+ for orig_atom, oe_atom in zip(molecule.atoms, oemol.GetAtoms()):
616
+ if "residue_name" in orig_atom.metadata:
617
+ assert orig_atom.metadata["residue_name"] == oechem.OEAtomGetResidue(oe_atom).GetName()
618
+
619
+ if "residue_number" in orig_atom.metadata:
620
+ assert orig_atom.metadata["residue_number"] == oechem.OEAtomGetResidue(oe_atom).GetResidueNumber()
621
+
622
+ if "insertion_code" in orig_atom.metadata:
623
+ assert orig_atom.metadata["insertion_code"] == oechem.OEAtomGetResidue(oe_atom).GetInsertCode()
624
+
625
+ if "chain_id" in orig_atom.metadata:
626
+ assert orig_atom.metadata["chain_id"] == oechem.OEAtomGetResidue(oe_atom).GetChainID()
627
+
628
+ # Check roundtripped OFFMol
629
+ for orig_atom, roundtrip_atom in zip(molecule.atoms, roundtrip_mol.atoms):
630
+ # If ANY atom in the OEMol has any hierarchy metadata set, then the ENTIRE molecule is considered
631
+ # to have metadata. Anything that wasn't set defaults to ("UNK", 1, " ").
632
+ if oechem.OEHasResidues(oemol):
633
+ if "residue_name" in orig_atom.metadata:
634
+ assert orig_atom.metadata["residue_name"] == roundtrip_atom.metadata["residue_name"]
635
+
636
+ if "residue_number" in orig_atom.metadata:
637
+ assert orig_atom.metadata["residue_number"] == roundtrip_atom.metadata["residue_number"]
638
+
639
+ if "insertion_code" in orig_atom.metadata:
640
+ assert orig_atom.metadata["insertion_code"] == roundtrip_atom.metadata["insertion_code"]
641
+
642
+ if "chain_id" in orig_atom.metadata:
643
+ assert orig_atom.metadata["chain_id"] == roundtrip_atom.metadata["chain_id"]
644
+
645
+ else:
646
+ assert "residue_name" not in roundtrip_atom.metadata
647
+ assert "residue_number" not in roundtrip_atom.metadata
648
+ assert "insertion_code" not in roundtrip_atom.metadata
649
+ assert "chain_id" not in roundtrip_atom.metadata
650
+
651
+ def test_from_openeye_mutable_input(self):
652
+ """
653
+ Test ``OpenEyeToolkitWrapper.from_openeye`` does not mutate the input molecule.
654
+ """
655
+ from openeye import oechem
656
+
657
+ oe_molecule = oechem.OEMol()
658
+ oechem.OESmilesToMol(oe_molecule, "C")
659
+
660
+ assert oechem.OEHasImplicitHydrogens(oe_molecule)
661
+ Molecule.from_openeye(oe_molecule)
662
+ assert oechem.OEHasImplicitHydrogens(oe_molecule)
663
+
664
+ def test_from_openeye_radical(self):
665
+ """Test that parsing an oemol with a radical raises RadicalsNotSupportedError."""
666
+ from openeye import oechem
667
+
668
+ smiles = "[H][C]([H])[H]"
669
+ oemol = oechem.OEGraphMol()
670
+ oechem.OESmilesToMol(oemol, smiles)
671
+
672
+ with pytest.raises(RadicalsNotSupportedError):
673
+ OpenEyeToolkitWrapper().from_openeye(oemol)
674
+
675
+ def test_from_openeye_transition_metal_radical(self):
676
+ """Test that parsing an oemol with a transition metal radical works."""
677
+ from openeye import oechem
678
+
679
+ smiles = "[Zn+2]"
680
+ oemol = oechem.OEGraphMol()
681
+ oechem.OESmilesToMol(oemol, smiles)
682
+
683
+ OpenEyeToolkitWrapper().from_openeye(oemol)
684
+
685
+ def test_from_openeye_multiple_molecule(self):
686
+ """Test that parsing a OEMol that is actually multiple disconnected molecules raises a warning"""
687
+ from openeye import oechem
688
+
689
+ oemol = oechem.OEMol()
690
+ oechem.OESmilesToMol(oemol, "C.N")
691
+ with pytest.warns(
692
+ MultipleComponentsInMoleculeWarning,
693
+ match="more than one molecule",
694
+ ):
695
+ OpenEyeToolkitWrapper().from_openeye(oemol)
696
+
697
+ def test_from_openeye_implicit_hydrogen(self):
698
+ """
699
+ Test OpenEyeToolkitWrapper for loading a molecule with implicit
700
+ hydrogens (correct behavior is to add them explicitly)
701
+ """
702
+ from openeye import oechem
703
+
704
+ smiles_impl = "C#C"
705
+ oemol_impl = oechem.OEMol()
706
+ oechem.OESmilesToMol(oemol_impl, smiles_impl)
707
+ molecule_from_impl = Molecule.from_openeye(oemol_impl)
708
+
709
+ assert molecule_from_impl.n_atoms == 4
710
+
711
+ smiles_expl = "HC#CH"
712
+ oemol_expl = oechem.OEMol()
713
+ oechem.OESmilesToMol(oemol_expl, smiles_expl)
714
+ molecule_from_expl = Molecule.from_openeye(oemol_expl)
715
+ assert molecule_from_expl.to_smiles() == molecule_from_impl.to_smiles()
716
+
717
+ def test_openeye_from_smiles_name(self):
718
+ """
719
+ Test to ensure that the `name` kwarg to from_smiles behaves correctly
720
+ """
721
+ toolkit_wrapper = OpenEyeToolkitWrapper()
722
+ mol = toolkit_wrapper.from_smiles("C")
723
+ assert mol.name == ""
724
+ mol = toolkit_wrapper.from_smiles("C", name="bob")
725
+ assert mol.name == "bob"
726
+
727
+ def test_openeye_from_smiles_hydrogens_are_explicit(self):
728
+ """
729
+ Test to ensure that OpenEyeToolkitWrapper.from_smiles has the proper behavior with
730
+ respect to its hydrogens_are_explicit kwarg
731
+ """
732
+ toolkit_wrapper = OpenEyeToolkitWrapper()
733
+ smiles_impl = "C#C"
734
+ with pytest.raises(
735
+ ValueError,
736
+ match=r"but OpenEye Toolkit interpreted SMILES 'C#C' as having implicit hydrogen",
737
+ ):
738
+ offmol = Molecule.from_smiles(
739
+ smiles_impl,
740
+ toolkit_registry=toolkit_wrapper,
741
+ hydrogens_are_explicit=True,
742
+ )
743
+ offmol = Molecule.from_smiles(smiles_impl, toolkit_registry=toolkit_wrapper, hydrogens_are_explicit=False)
744
+ assert offmol.n_atoms == 4
745
+
746
+ smiles_expl = "HC#CH"
747
+ offmol = Molecule.from_smiles(smiles_expl, toolkit_registry=toolkit_wrapper, hydrogens_are_explicit=True)
748
+ assert offmol.n_atoms == 4
749
+ # It's debatable whether this next function should pass. Strictly speaking, the hydrogens in this SMILES
750
+ # _are_ explicit, so allowing "hydrogens_are_explicit=False" through here is allowing a contradiction.
751
+ # We might rethink the name of this kwarg.
752
+
753
+ offmol = Molecule.from_smiles(smiles_expl, toolkit_registry=toolkit_wrapper, hydrogens_are_explicit=False)
754
+ assert offmol.n_atoms == 4
755
+
756
+ @pytest.mark.parametrize("smiles, expected_map", [("[Cl:1][H]", {0: 1}), ("[Cl:1][H:2]", {0: 1, 1: 2})])
757
+ def test_from_openeye_atom_map(self, smiles, expected_map):
758
+ """
759
+ Test OpenEyeToolkitWrapper for loading a molecule with implicit
760
+ hydrogens (correct behavior is to add them explicitly)
761
+ """
762
+ from openeye import oechem
763
+
764
+ oemol = oechem.OEMol()
765
+ oechem.OESmilesToMol(oemol, smiles)
766
+
767
+ off_molecule = Molecule.from_openeye(oemol)
768
+ assert off_molecule.properties["atom_map"] == expected_map
769
+
770
+ @pytest.mark.parametrize("molecule", get_mini_drug_bank(OpenEyeToolkitWrapper))
771
+ def test_to_inchi(self, molecule):
772
+ """Test, but do not validate, conversion to standard and non-standard InChI"""
773
+
774
+ toolkit = OpenEyeToolkitWrapper()
775
+ molecule.to_inchi(toolkit_registry=toolkit)
776
+ molecule.to_inchi(True, toolkit_registry=toolkit)
777
+
778
+ @pytest.mark.parametrize("molecule", get_mini_drug_bank(OpenEyeToolkitWrapper))
779
+ def test_to_inchikey(self, molecule):
780
+ """Test, but do not validate, the conversion to standard and non-standard InChIKey"""
781
+
782
+ toolkit = OpenEyeToolkitWrapper()
783
+ molecule.to_inchikey(toolkit_registry=toolkit)
784
+ molecule.to_inchikey(True, toolkit_registry=toolkit)
785
+
786
+ def test_openeye_from_inchi_name(self):
787
+ """
788
+ Test to ensure that the `name` kwarg to from_inchi behaves correctly
789
+ """
790
+ toolkit_wrapper = OpenEyeToolkitWrapper()
791
+ mol = toolkit_wrapper.from_inchi("InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3")
792
+ assert mol.name == ""
793
+ mol = toolkit_wrapper.from_inchi("InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3", name="bob")
794
+ assert mol.name == "bob"
795
+
796
+ def test_from_bad_inchi(self):
797
+ """Test building a molecule from a bad InChI string"""
798
+
799
+ toolkit = OpenEyeToolkitWrapper()
800
+ inchi = "InChI=1S/ksbfksfksfksbfks"
801
+
802
+ with pytest.raises(InChIParseError, match="ksbfksfksfksbfks"):
803
+ Molecule.from_inchi(inchi, toolkit_registry=toolkit)
804
+
805
+ @pytest.mark.parametrize("method", ["to_inchi", "to_inchikey"])
806
+ def test_empty_inchi(self, method):
807
+ """Reproduce Issue #1897"""
808
+ with pytest.raises(
809
+ EmptyInChiError,
810
+ match="failed to generate" + (r".*key" if method == "to_inchikey" else ""),
811
+ ):
812
+ # call either .to_inchi or .to_inchikey
813
+ getattr(
814
+ Molecule.from_mapped_smiles("[H:5][S:3]#[N+:2][S:1][H:4]"),
815
+ method,
816
+ )(toolkit_registry=OpenEyeToolkitWrapper())
817
+
818
+ @pytest.mark.parametrize(
819
+ "molecule",
820
+ get_mini_drug_bank(
821
+ OpenEyeToolkitWrapper,
822
+ xfail_mols={
823
+ "DrugBank_3046": "Molecule is corrupted and is interpreted as a radical",
824
+ "DrugBank_3655": "Molecule is corrupted and is interpreted as a radical",
825
+ "DrugBank_1594": "Molecule is corrupted and is interpreted as a radical",
826
+ "DrugBank_4346": "Molecule is corrupted and is interpreted as a radical",
827
+ "DrugBank_6947": "Molecule is corrupted and is interpreted as a radical",
828
+ },
829
+ ),
830
+ )
831
+ def test_non_standard_inchi_round_trip(self, molecule):
832
+ """Test if a molecule can survive an InChi round trip test in some cases the standard InChI
833
+ will not enough to ensure information is preserved so we test the non-standard inchi here.
834
+ """
835
+
836
+ from openff.toolkit.utils.toolkits import UndefinedStereochemistryError
837
+
838
+ toolkit = OpenEyeToolkitWrapper()
839
+ inchi = molecule.to_inchi(fixed_hydrogens=True, toolkit_registry=toolkit)
840
+ # make a copy of the molecule from the inchi string
841
+ if molecule.name in openeye_inchi_stereochemistry_lost:
842
+ # some molecules lose sterorchemsitry so they are skipped
843
+ # if we fail here the molecule may of been fixed
844
+ with pytest.raises(UndefinedStereochemistryError):
845
+ mol2 = molecule.from_inchi(inchi, toolkit_registry=toolkit)
846
+
847
+ else:
848
+ mol2 = molecule.from_inchi(inchi, toolkit_registry=toolkit)
849
+ # compare the full molecule excluding the properties dictionary
850
+ # turn of the bond order matching as this could move in the aromatic rings
851
+ if molecule.name in openeye_inchi_isomorphic_fails:
852
+ # Some molecules graphs change during the round trip testing
853
+ # we test quite strict isomorphism here
854
+ with pytest.raises(AssertionError):
855
+ assert molecule.is_isomorphic_with(mol2, bond_order_matching=False, toolkit_registry=toolkit)
856
+ else:
857
+ assert molecule.is_isomorphic_with(mol2, bond_order_matching=False, toolkit_registry=toolkit)
858
+
859
+ @pytest.mark.parametrize(
860
+ "molecule",
861
+ get_mini_drug_bank(
862
+ OpenEyeToolkitWrapper,
863
+ xfail_mols={
864
+ "DrugBank_2397": 'OpenEye cannot generate a correct IUPAC name and raises a "Warning: Incorrect name:" or simply return "BLAH".',
865
+ "DrugBank_2543": 'OpenEye cannot generate a correct IUPAC name and raises a "Warning: Incorrect name:" or simply return "BLAH".',
866
+ "DrugBank_2642": 'OpenEye cannot generate a correct IUPAC name and raises a "Warning: Incorrect name:" or simply return "BLAH".',
867
+ "DrugBank_1212": "the roundtrip generates molecules with very different IUPAC/SMILES!",
868
+ "DrugBank_2210": "the roundtrip generates molecules with very different IUPAC/SMILES!",
869
+ "DrugBank_4584": "the roundtrip generates molecules with very different IUPAC/SMILES!",
870
+ "DrugBank_390": 'raises warning "Unable to make OFFMol from OEMol: OEMol has unspecified stereochemistry."',
871
+ "DrugBank_810": 'raises warning "Unable to make OFFMol from OEMol: OEMol has unspecified stereochemistry."',
872
+ "DrugBank_4316": 'raises warning "Unable to make OFFMol from OEMol: OEMol has unspecified stereochemistry."',
873
+ "DrugBank_7124": 'raises warning "Unable to make OFFMol from OEMol: OEMol has unspecified stereochemistry."',
874
+ "DrugBank_3739": 'raises warning "Failed to parse name:"',
875
+ "DrugBank_4346": 'raises warning "Failed to parse name:"',
876
+ "DrugBank_5415": 'raises warning "Failed to parse name:"',
877
+ "DrugBank_1661": "fails roundtrip test",
878
+ "DrugBank_6353": "fails roundtrip test",
879
+ "DrugBank_2799": "from_iupac fails to read what to_iupac returns",
880
+ "DrugBank_4865": "from_iupac fails to read what to_iupac returns",
881
+ "DrugBank_2465": "from_iupac fails to read what to_iupac returns",
882
+ },
883
+ ),
884
+ )
885
+ def test_iupac_round_trip(self, molecule):
886
+ """Test round-trips with IUPAC names"""
887
+ undefined_stereo = molecule.name in openeye_iupac_bad_stereo
888
+
889
+ iupac = molecule.to_iupac()
890
+
891
+ if undefined_stereo:
892
+ with pytest.raises(UndefinedStereochemistryError):
893
+ Molecule.from_iupac(iupac)
894
+
895
+ molecule_copy = Molecule.from_iupac(iupac, allow_undefined_stereo=undefined_stereo)
896
+ if not undefined_stereo:
897
+ assert molecule.is_isomorphic_with(molecule_copy, atom_stereochemistry_matching=not undefined_stereo)
898
+
899
+ def test_from_iupac_failure(self):
900
+ """Test that invalid IUPAC names are handled properly"""
901
+ toolkit = OpenEyeToolkitWrapper()
902
+
903
+ with pytest.raises(InvalidIUPACNameError):
904
+ toolkit.from_iupac(".BETA.-PINENE")
905
+
906
+ def test_atom_names_round_trip(self):
907
+ """Test that atom names are correctly preserved in a round trip"""
908
+ # Create a molecule with unique atom names
909
+ molecule = Molecule.from_smiles("c1ccccc1")
910
+ molecule.generate_unique_atom_names()
911
+ # Convert it to an OEMol
912
+ oemol = molecule.to_openeye()
913
+ # Compare atom names
914
+ for oeatom, atom in zip(oemol.GetAtoms(), molecule.atoms):
915
+ assert oeatom.GetName() == atom.name
916
+ # Change the OEMol atom names
917
+ for index, oeatom in enumerate(oemol.GetAtoms()):
918
+ oeatom.SetName(f"X{index}")
919
+ # Round trip back to molecule
920
+ molecule2 = molecule.from_openeye(oemol)
921
+ # Compare atom names
922
+ for oeatom, atom2 in zip(oemol.GetAtoms(), molecule2.atoms):
923
+ assert oeatom.GetName() == atom2.name
924
+
925
+ def test_from_pathlib_path(self):
926
+ ethanol = create_ethanol()
927
+ with NamedTemporaryFile(suffix=".sdf") as outfile:
928
+ filename = str(outfile.name)
929
+ ethanol.to_file(filename, file_format="sdf")
930
+
931
+ toolkit = OpenEyeToolkitWrapper()
932
+ toolkit.from_file(pathlib.Path(filename), file_format="sdf")
933
+
934
+ def test_write_multiconformer_pdb(self):
935
+ """
936
+ Make sure OpenEye can write multi conformer PDB files.
937
+ """
938
+ from io import StringIO
939
+
940
+ toolkit = OpenEyeToolkitWrapper()
941
+ # load up a multiconformer sdf file and condense down the conformers
942
+ molecules = Molecule.from_file(get_data_file_path("molecules/butane_multi.sdf"), toolkit_registry=toolkit)
943
+ butane = molecules.pop(0)
944
+ for mol in molecules:
945
+ butane.add_conformer(mol.conformers[0])
946
+ assert butane.n_conformers == 7
947
+ sio = StringIO()
948
+ butane.to_file(sio, "pdb", toolkit_registry=toolkit)
949
+ # we need to make sure each conformer is wrote to the file
950
+ pdb = sio.getvalue()
951
+ assert pdb.count("END") == 7
952
+
953
+ def test_write_pdb_preserving_atom_order(self):
954
+ """
955
+ Make sure OpenEye does not rearrange hydrogens when writing PDBs
956
+ (reference: https://github.com/openforcefield/openff-toolkit/issues/475).
957
+ """
958
+ from io import StringIO
959
+
960
+ toolkit = OpenEyeToolkitWrapper()
961
+ water = Molecule()
962
+ water.add_atom(1, 0, False)
963
+ water.add_atom(8, 0, False)
964
+ water.add_atom(1, 0, False)
965
+ water.add_bond(0, 1, 1, False)
966
+ water.add_bond(1, 2, 1, False)
967
+ water.add_conformer(
968
+ Quantity(
969
+ np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]),
970
+ unit.angstrom,
971
+ )
972
+ )
973
+ sio = StringIO()
974
+ water.to_file(sio, "pdb", toolkit_registry=toolkit)
975
+ water_from_pdb = sio.getvalue()
976
+ water_from_pdb_split = water_from_pdb.split("\n")
977
+ # Check serial number
978
+ assert water_from_pdb_split[0].split()[1].rstrip() == "1"
979
+ assert water_from_pdb_split[1].split()[1].rstrip() == "2"
980
+ assert water_from_pdb_split[2].split()[1].rstrip() == "3"
981
+ # Check atom name
982
+ assert water_from_pdb_split[0].split()[2].rstrip() == "H"
983
+ assert water_from_pdb_split[1].split()[2].rstrip() == "O"
984
+ assert water_from_pdb_split[2].split()[2].rstrip() == "H"
985
+
986
+ def test_write_pdb_blank_chain_id_insertion_code(self):
987
+ """
988
+ Ensure PDB files are written with coords by OE when chain ID or insertion code is blank string.
989
+ (reference: https://github.com/openforcefield/openff-toolkit/issues/1967).
990
+ """
991
+ toolkit = OpenEyeToolkitWrapper()
992
+ water = Molecule()
993
+ water.add_atom(1, 0, False)
994
+ water.add_atom(8, 0, False)
995
+ water.add_atom(1, 0, False)
996
+ water.add_bond(0, 1, 1, False)
997
+ water.add_bond(1, 2, 1, False)
998
+ water.add_conformer(
999
+ Quantity(
1000
+ np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]),
1001
+ unit.angstrom,
1002
+ )
1003
+ )
1004
+ water.atoms[0].metadata["insertion_code"] = ""
1005
+ water.atoms[1].metadata["chain_id"] = ""
1006
+ with NamedTemporaryFile(suffix=".pdb") as of:
1007
+ water.to_file(of.name, "pdb", toolkit_registry=toolkit)
1008
+ roundtripped = toolkit.from_file(of.name, file_format="pdb")
1009
+ np.testing.assert_allclose(
1010
+ water.conformers[0].m_as(unit.angstrom), roundtripped[0].conformers[0].m_as(unit.angstrom)
1011
+ )
1012
+
1013
+ def test_get_sdf_coordinates(self):
1014
+ """Test OpenEyeToolkitWrapper for importing a single set of coordinates from a sdf file"""
1015
+
1016
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1017
+ filename = get_data_file_path("molecules/toluene.sdf")
1018
+ molecule = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
1019
+ assert len(molecule.conformers) == 1
1020
+ assert molecule.conformers[0].shape == (15, 3)
1021
+
1022
+ def test_load_multiconformer_sdf_as_separate_molecules(self):
1023
+ """
1024
+ Test OpenEyeToolkitWrapper for reading a "multiconformer" SDF, which the OFF
1025
+ Toolkit should treat as separate molecules
1026
+ """
1027
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1028
+ filename = get_data_file_path("molecules/methane_multiconformer.sdf")
1029
+ molecules = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
1030
+ assert len(molecules) == 2
1031
+ assert len(molecules[0].conformers) == 1
1032
+ assert len(molecules[1].conformers) == 1
1033
+ assert molecules[0].conformers[0].shape == (5, 3)
1034
+
1035
+ def test_load_multiconformer_sdf_as_separate_molecules_properties(self):
1036
+ """
1037
+ Test OpenEyeToolkitWrapper for reading a "multiconformer" SDF, which the OFF
1038
+ Toolkit should treat as separate molecules, and it should load their SD properties
1039
+ and partial charges separately
1040
+ """
1041
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1042
+ filename = get_data_file_path("molecules/methane_multiconformer_properties.sdf")
1043
+ molecules = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
1044
+ assert len(molecules) == 2
1045
+ assert len(molecules[0].conformers) == 1
1046
+ assert len(molecules[1].conformers) == 1
1047
+ assert molecules[0].conformers[0].shape == (5, 3)
1048
+ # The first molecule in the SDF has the following properties and charges:
1049
+ assert molecules[0].properties["test_property_key"] == "test_property_value"
1050
+ np.testing.assert_allclose(
1051
+ molecules[0].partial_charges.m_as(unit.elementary_charge),
1052
+ [-0.108680, 0.027170, 0.027170, 0.027170, 0.027170],
1053
+ )
1054
+ # The second molecule in the SDF has the following properties and charges:
1055
+ assert molecules[1].properties["test_property_key"] == "test_property_value2"
1056
+ assert molecules[1].properties["another_test_property_key"] == "another_test_property_value"
1057
+ np.testing.assert_allclose(
1058
+ molecules[1].partial_charges.m_as(unit.elementary_charge),
1059
+ [0.027170, 0.027170, 0.027170, 0.027170, -0.108680],
1060
+ )
1061
+
1062
+ def test_file_extension_case(self):
1063
+ """
1064
+ Test round-trips of some file extensions when called directly from the toolkit wrappers,
1065
+ including lower- and uppercase file extensions. Note that this test does not ensure
1066
+ accuracy, it only tests that reading/writing without raising an exception.
1067
+ """
1068
+ mols_in = OpenEyeToolkitWrapper().from_file(
1069
+ file_path=get_data_file_path("molecules/ethanol.sdf"), file_format="sdf"
1070
+ )
1071
+
1072
+ assert len(mols_in) > 0
1073
+
1074
+ mols_in = OpenEyeToolkitWrapper().from_file(
1075
+ file_path=get_data_file_path("molecules/ethanol.sdf"), file_format="SDF"
1076
+ )
1077
+
1078
+ assert len(mols_in) > 0
1079
+
1080
+ def test_write_sdf_charges(self):
1081
+ """Test OpenEyeToolkitWrapper for writing partial charges to a sdf file"""
1082
+ from io import StringIO
1083
+
1084
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1085
+ ethanol = create_ethanol()
1086
+ sio = StringIO()
1087
+ ethanol.to_file(sio, "SDF", toolkit_registry=toolkit_wrapper)
1088
+ sdf_text = sio.getvalue()
1089
+ # The output lines of interest here will look like
1090
+ # > <atom.dprop.PartialCharge>
1091
+ # -0.400000 -0.300000 -0.200000 -0.100000 0.000010 0.100000 0.200000 0.300000 0.400000
1092
+ # Parse the SDF text, grabbing the numeric line above
1093
+ sdf_split = sdf_text.split("\n")
1094
+ charge_line_found = False
1095
+ for line in sdf_split:
1096
+ if charge_line_found:
1097
+ charges = [float(i) for i in line.split()]
1098
+ break
1099
+ if "> <atom.dprop.PartialCharge>" in line:
1100
+ charge_line_found = True
1101
+
1102
+ # Make sure that a charge line was ever found
1103
+ assert charge_line_found
1104
+
1105
+ # Make sure that the charges found were correct
1106
+ assert_almost_equal(charges, [-0.4, -0.3, -0.2, -0.1, 0.00001, 0.1, 0.2, 0.3, 0.4])
1107
+
1108
+ def test_write_sdf_no_charges(self):
1109
+ """Test OpenEyeToolkitWrapper for writing an SDF file without charges"""
1110
+ from io import StringIO
1111
+
1112
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1113
+ ethanol = create_ethanol()
1114
+ ethanol.partial_charges = None
1115
+ sio = StringIO()
1116
+ ethanol.to_file(sio, "SDF", toolkit_registry=toolkit_wrapper)
1117
+ sdf_text = sio.getvalue()
1118
+ # In our current configuration, if the OFFMol doesn't have partial charges, we DO NOT want a partial charge
1119
+ # block to be written. For reference, it's possible to indicate that a partial charge is not known by writing
1120
+ # out "n/a" (or another placeholder) in the partial charge block atoms without charges.
1121
+ assert "<atom.dprop.PartialCharge>" not in sdf_text
1122
+
1123
+ def test_sdf_properties_roundtrip(self):
1124
+ """Test OpenEyeToolkitWrapper for performing a round trip of a molecule with defined partial charges
1125
+ and entries in the properties dict to and from a sdf file"""
1126
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1127
+ ethanol = create_ethanol()
1128
+ ethanol.properties["test_property"] = "test_value"
1129
+ # Write ethanol to a temporary file, and then immediately read it.
1130
+ with NamedTemporaryFile(suffix=".sdf") as iofile:
1131
+ ethanol.to_file(iofile.name, file_format="SDF", toolkit_registry=toolkit_wrapper)
1132
+ ethanol2 = Molecule.from_file(iofile.name, file_format="SDF", toolkit_registry=toolkit_wrapper)
1133
+ np.testing.assert_allclose(
1134
+ ethanol.partial_charges.m_as(unit.elementary_charge),
1135
+ ethanol2.partial_charges.m_as(unit.elementary_charge),
1136
+ )
1137
+ assert ethanol2.properties["test_property"] == "test_value"
1138
+
1139
+ # Now test with no properties or charges
1140
+ ethanol = create_ethanol()
1141
+ ethanol.partial_charges = None
1142
+ # Write ethanol to a temporary file, and then immediately read it.
1143
+ with NamedTemporaryFile(suffix=".sdf") as iofile:
1144
+ ethanol.to_file(iofile.name, file_format="SDF", toolkit_registry=toolkit_wrapper)
1145
+ ethanol2 = Molecule.from_file(iofile.name, file_format="SDF", toolkit_registry=toolkit_wrapper)
1146
+ assert ethanol2.partial_charges is None
1147
+ assert ethanol2.properties == {}
1148
+
1149
+ def test_write_multiconformer_mol_as_sdf(self):
1150
+ """
1151
+ Test OpenEyeToolkitWrapper for writing a multiconformer molecule to SDF. The OFF toolkit should only
1152
+ save the first conformer.
1153
+ """
1154
+ from io import StringIO
1155
+
1156
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1157
+ filename = get_data_file_path("molecules/ethanol.sdf")
1158
+ ethanol = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
1159
+ ethanol.partial_charges = Quantity(
1160
+ np.array([-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0]),
1161
+ unit.elementary_charge,
1162
+ )
1163
+ ethanol.properties["test_prop"] = "test_value"
1164
+ new_conf = ethanol.conformers[0] + (np.ones(ethanol.conformers[0].shape) * unit.angstrom)
1165
+ ethanol.add_conformer(new_conf)
1166
+ sio = StringIO()
1167
+ ethanol.to_file(sio, "sdf", toolkit_registry=toolkit_wrapper)
1168
+ data = sio.getvalue()
1169
+ # In SD format, each molecule ends with "$$$$"
1170
+ assert data.count("$$$$") == 1
1171
+ # A basic SDF for ethanol would be 27 lines, though the properties add three more
1172
+ assert len(data.split("\n")) == 30
1173
+ assert "test_prop" in data
1174
+ assert "<atom.dprop.PartialCharge>" in data
1175
+ # Ensure the first conformer's first atom's X coordinate is in the file
1176
+ assert str(ethanol.conformers[0][0][0].to(unit.angstrom))[:5] in data
1177
+ # Ensure the SECOND conformer's first atom's X coordinate is NOT in the file
1178
+ assert str(ethanol.conformers[1][0][0].to(unit.angstrom))[:5] not in data
1179
+
1180
+ def test_get_mol2_coordinates(self):
1181
+ """Test OpenEyeToolkitWrapper for importing a single set of molecule coordinates"""
1182
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1183
+ filename = get_data_file_path("molecules/toluene.mol2")
1184
+ molecule1 = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
1185
+ assert len(molecule1.conformers) == 1
1186
+ assert molecule1.conformers[0].shape == (15, 3)
1187
+ assert_almost_equal(molecule1.conformers[0][5][1].m_as(unit.angstrom), 22.98, decimal=2)
1188
+
1189
+ # Test loading from file-like object
1190
+ with open(filename) as infile:
1191
+ molecule2 = Molecule(infile, file_format="MOL2", toolkit_registry=toolkit_wrapper)
1192
+ assert molecule1.is_isomorphic_with(molecule2)
1193
+ assert len(molecule2.conformers) == 1
1194
+ assert molecule2.conformers[0].shape == (15, 3)
1195
+ assert_almost_equal(molecule2.conformers[0][5][1].m_as(unit.angstrom), 22.98, decimal=2)
1196
+
1197
+ # Test loading from gzipped mol2
1198
+ import gzip
1199
+
1200
+ with gzip.GzipFile(filename + ".gz", "r") as infile:
1201
+ molecule3 = Molecule(infile, file_format="MOL2", toolkit_registry=toolkit_wrapper)
1202
+ assert molecule1.is_isomorphic_with(molecule3)
1203
+ assert len(molecule3.conformers) == 1
1204
+ assert molecule3.conformers[0].shape == (15, 3)
1205
+ assert_almost_equal(molecule3.conformers[0][5][1].m_as(unit.angstrom), 22.98, decimal=2)
1206
+
1207
+ def test_get_mol2_charges(self):
1208
+ """Test OpenEyeToolkitWrapper for importing a mol2 file specifying partial charges"""
1209
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1210
+ filename = get_data_file_path("molecules/toluene_charged.mol2")
1211
+ molecule = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
1212
+ assert len(molecule.conformers) == 1
1213
+ assert molecule.conformers[0].shape == (15, 3)
1214
+ target_charges = Quantity(
1215
+ np.array(
1216
+ [
1217
+ -0.1342,
1218
+ -0.1271,
1219
+ -0.1271,
1220
+ -0.1310,
1221
+ -0.1310,
1222
+ -0.0765,
1223
+ -0.0541,
1224
+ 0.1314,
1225
+ 0.1286,
1226
+ 0.1286,
1227
+ 0.1303,
1228
+ 0.1303,
1229
+ 0.0440,
1230
+ 0.0440,
1231
+ 0.0440,
1232
+ ]
1233
+ ),
1234
+ unit.elementary_charge,
1235
+ )
1236
+ for pc1, pc2 in zip(molecule._partial_charges, target_charges):
1237
+ pc1_ul = pc1.m_as(unit.elementary_charge)
1238
+ pc2_ul = pc2.m_as(unit.elementary_charge)
1239
+ assert_almost_equal(pc1_ul, pc2_ul, decimal=4)
1240
+
1241
+ def test_mol2_charges_roundtrip(self):
1242
+ """Test OpenEyeToolkitWrapper for performing a round trip of a molecule with partial charge to and from
1243
+ a mol2 file"""
1244
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1245
+ ethanol = create_ethanol()
1246
+ # we increase the magnitude of the partial charges here, since mol2 is only
1247
+ # written to 4 digits of precision, and the default middle charge for our test ethanol is 1e-5
1248
+ ethanol.partial_charges *= 100
1249
+ # Write ethanol to a temporary file, and then immediately read it.
1250
+ with NamedTemporaryFile(suffix=".mol2") as iofile:
1251
+ ethanol.to_file(iofile.name, file_format="mol2", toolkit_registry=toolkit_wrapper)
1252
+ ethanol2 = Molecule.from_file(iofile.name, file_format="mol2", toolkit_registry=toolkit_wrapper)
1253
+ np.testing.assert_allclose(
1254
+ ethanol.partial_charges.m_as(unit.elementary_charge),
1255
+ ethanol2.partial_charges.m_as(unit.elementary_charge),
1256
+ )
1257
+
1258
+ # Now test with no properties or charges
1259
+ ethanol = create_ethanol()
1260
+ ethanol.partial_charges = None
1261
+ # Write ethanol to a temporary file, and then immediately read it.
1262
+ with NamedTemporaryFile(suffix=".mol2") as iofile:
1263
+ ethanol.to_file(iofile.name, file_format="mol2", toolkit_registry=toolkit_wrapper)
1264
+ ethanol2 = Molecule.from_file(iofile.name, file_format="mol2", toolkit_registry=toolkit_wrapper)
1265
+ assert ethanol2.partial_charges is None
1266
+ assert ethanol2.properties == {}
1267
+
1268
+ def test_get_mol2_gaff_atom_types(self):
1269
+ """Test that a warning is raised OpenEyeToolkitWrapper when it detects GAFF atom types in a mol2 file."""
1270
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1271
+ mol2_file_path = get_data_file_path("molecules/AlkEthOH_test_filt1_ff.mol2")
1272
+ with pytest.warns(GAFFAtomTypeWarning, match="SYBYL"):
1273
+ Molecule.from_file(mol2_file_path, toolkit_registry=toolkit_wrapper)
1274
+
1275
+ def test_generate_conformers(self):
1276
+ """Test OpenEyeToolkitWrapper generate_conformers()"""
1277
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1278
+ smiles = "[H]C([H])([H])C([H])([H])[H]"
1279
+ molecule = toolkit_wrapper.from_smiles(smiles)
1280
+ molecule.generate_conformers()
1281
+ assert molecule.n_conformers != 0
1282
+ assert not (molecule.conformers[0] == (0.0 * unit.angstrom)).all()
1283
+
1284
+ def test_generate_multiple_conformers(self):
1285
+ """Test OpenEyeToolkitWrapper generate_conformers() for generating multiple conformers"""
1286
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1287
+ smiles = "CCCCCCCCCN"
1288
+ molecule = toolkit_wrapper.from_smiles(smiles)
1289
+ molecule.generate_conformers(
1290
+ rms_cutoff=1 * unit.angstrom,
1291
+ n_conformers=100,
1292
+ toolkit_registry=toolkit_wrapper,
1293
+ )
1294
+ assert molecule.n_conformers > 1
1295
+ assert not (molecule.conformers[0] == (0.0 * unit.angstrom)).all()
1296
+
1297
+ # Ensure rms_cutoff kwarg is working
1298
+ molecule2 = toolkit_wrapper.from_smiles(smiles)
1299
+ molecule2.generate_conformers(
1300
+ rms_cutoff=0.1 * unit.angstrom,
1301
+ n_conformers=100,
1302
+ toolkit_registry=toolkit_wrapper,
1303
+ )
1304
+ assert molecule2.n_conformers > molecule.n_conformers
1305
+
1306
+ # Ensure n_conformers kwarg is working
1307
+ molecule2 = toolkit_wrapper.from_smiles(smiles)
1308
+ molecule2.generate_conformers(
1309
+ rms_cutoff=0.1 * unit.angstrom,
1310
+ n_conformers=10,
1311
+ toolkit_registry=toolkit_wrapper,
1312
+ )
1313
+ assert molecule2.n_conformers == 10
1314
+
1315
+ def test_generate_conformers_failure(self):
1316
+ toolkit = OpenEyeToolkitWrapper()
1317
+
1318
+ molecule = Molecule.from_smiles("C(C2)(C3)1CC23C1")
1319
+
1320
+ with pytest.raises(ConformerGenerationError, match=r"Omega conf.*fail"):
1321
+ toolkit.generate_conformers(molecule, n_conformers=1)
1322
+
1323
+ def test_apply_elf_conformer_selection(self):
1324
+ """Test applying the ELF10 method."""
1325
+
1326
+ toolkit = OpenEyeToolkitWrapper()
1327
+
1328
+ molecule = Molecule.from_file(
1329
+ get_data_file_path(os.path.join("molecules", "z_3_hydroxy_propenal.sdf")),
1330
+ "SDF",
1331
+ )
1332
+
1333
+ # Test that the simple case of no conformers does not yield an exception.
1334
+ toolkit.apply_elf_conformer_selection(molecule)
1335
+
1336
+ initial_conformers = [
1337
+ # Add a conformer with an internal H-bond.
1338
+ Quantity(
1339
+ np.array(
1340
+ [
1341
+ [0.5477, 0.3297, -0.0621],
1342
+ [-0.1168, -0.7881, 0.2329],
1343
+ [-1.4803, -0.8771, 0.1667],
1344
+ [-0.2158, 1.5206, -0.4772],
1345
+ [-1.4382, 1.5111, -0.5580],
1346
+ [1.6274, 0.3962, -0.0089],
1347
+ [0.3388, -1.7170, 0.5467],
1348
+ [-1.8612, -0.0347, -0.1160],
1349
+ [0.3747, 2.4222, -0.7115],
1350
+ ]
1351
+ ),
1352
+ unit.angstrom,
1353
+ ),
1354
+ # Add a conformer without an internal H-bond.
1355
+ Quantity(
1356
+ np.array(
1357
+ [
1358
+ [0.5477, 0.3297, -0.0621],
1359
+ [-0.1168, -0.7881, 0.2329],
1360
+ [-1.4803, -0.8771, 0.1667],
1361
+ [-0.2158, 1.5206, -0.4772],
1362
+ [0.3353, 2.5772, -0.7614],
1363
+ [1.6274, 0.3962, -0.0089],
1364
+ [0.3388, -1.7170, 0.5467],
1365
+ [-1.7743, -1.7634, 0.4166],
1366
+ [-1.3122, 1.4082, -0.5180],
1367
+ ]
1368
+ ),
1369
+ unit.angstrom,
1370
+ ),
1371
+ ]
1372
+
1373
+ molecule._conformers = [*initial_conformers]
1374
+
1375
+ # Apply ELF10
1376
+ toolkit.apply_elf_conformer_selection(molecule)
1377
+ elf10_conformers = molecule.conformers
1378
+
1379
+ assert len(elf10_conformers) == 1
1380
+
1381
+ assert np.allclose(
1382
+ elf10_conformers[0].m_as(unit.angstrom),
1383
+ initial_conformers[1].m_as(unit.angstrom),
1384
+ )
1385
+
1386
+ def test_assign_partial_charges_am1bcc(self):
1387
+ """Test OpenEyeToolkitWrapper assign_partial_charges() with am1bcc"""
1388
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1389
+ molecule = create_ethanol()
1390
+ molecule.assign_partial_charges(partial_charge_method="am1bcc", toolkit_registry=toolkit_registry)
1391
+ charge_sum = np.sum(molecule.partial_charges)
1392
+ abs_charge_sum = np.sum(abs(molecule.partial_charges))
1393
+
1394
+ assert abs(charge_sum) < 1e-10 * unit.elementary_charge
1395
+ assert abs_charge_sum > 0.25 * unit.elementary_charge
1396
+
1397
+ def test_assign_partial_charges_am1bcc_no_normalization(self):
1398
+ """Test OpenEyeToolkitWrapper assign_partial_charges() with am1bcc, with
1399
+ normalize_partial_charges=False"""
1400
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1401
+ # Use a cyclic N3H3 molecule, since the threefold symmetry makes it likely to expose rounding
1402
+ # errors. (can we find a cyclic molecule with exactly 3 atoms?)
1403
+ molecule = create_cyclic_n3h3()
1404
+ molecule.assign_partial_charges(
1405
+ partial_charge_method="am1bcc",
1406
+ toolkit_registry=toolkit_registry,
1407
+ normalize_partial_charges=False,
1408
+ )
1409
+ charge_sum = np.sum(molecule.partial_charges)
1410
+ abs_charge_sum = np.sum(abs(molecule.partial_charges))
1411
+ # Rounding error should be on the order of 1e-3
1412
+
1413
+ assert 1e-7 > abs(charge_sum.m_as(unit.elementary_charge)) > 1e-8
1414
+ assert abs_charge_sum > 0.25 * unit.elementary_charge
1415
+
1416
+ def test_assign_partial_charges_am1bcc_net_charge(self):
1417
+ """Test OpenEyeToolkitWrapper assign_partial_charges() on a molecule with a net +1 charge"""
1418
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1419
+ molecule = create_acetate()
1420
+ molecule.assign_partial_charges(partial_charge_method="am1bcc", toolkit_registry=toolkit_registry)
1421
+ charge_sum = np.sum(molecule.partial_charges)
1422
+ assert 1e-10 > abs((charge_sum - molecule.total_charge).m_as(unit.elementary_charge))
1423
+
1424
+ def test_assign_partial_charges_am1bcc_wrong_n_confs(self):
1425
+ """
1426
+ Test OpenEyeToolkitWrapper assign_partial_charges() with am1bcc when requesting to use an incorrect number of
1427
+ conformers. This test is a bit shorter than that for AmberToolsToolkitWrapper because OETK uses the
1428
+ ELF10 multiconformer method of AM1BCC, which doesn't have a maximum number of conformers.
1429
+ """
1430
+
1431
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1432
+ molecule = create_ethanol()
1433
+ molecule.generate_conformers(
1434
+ n_conformers=2,
1435
+ rms_cutoff=0.1 * unit.angstrom,
1436
+ toolkit_registry=toolkit_registry,
1437
+ )
1438
+
1439
+ # Try again, with strict_n_confs as true, but not including use_confs, so the
1440
+ # recommended number of confs will be generated
1441
+ molecule.assign_partial_charges(
1442
+ partial_charge_method="am1bcc",
1443
+ toolkit_registry=toolkit_registry,
1444
+ strict_n_conformers=True,
1445
+ )
1446
+
1447
+ @pytest.mark.parametrize("partial_charge_method", ["am1bcc", "am1elf10", "am1-mulliken", "gasteiger"])
1448
+ def test_assign_partial_charges_neutral(self, partial_charge_method):
1449
+ """Test OpenEyeToolkitWrapper assign_partial_charges()"""
1450
+
1451
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1452
+ molecule = create_ethanol()
1453
+ molecule.assign_partial_charges(
1454
+ toolkit_registry=toolkit_registry,
1455
+ partial_charge_method=partial_charge_method,
1456
+ )
1457
+ charge_sum = np.sum(molecule.partial_charges)
1458
+ assert 1.0e-10 > abs(charge_sum.m_as(unit.elementary_charge))
1459
+
1460
+ # Atoms 6 and 7 are hydrogens on the central C. If we don't symmetrize charges they'll have slight differences
1461
+ assert 1.0e-10 > abs(molecule.partial_charges[6] - molecule.partial_charges[7]).m_as(unit.elementary_charge)
1462
+
1463
+ @pytest.mark.parametrize("partial_charge_method", ["am1bcc", "am1-mulliken"])
1464
+ def test_assign_partial_charges_conformer_dependence(self, partial_charge_method):
1465
+ """Test OpenEyeToolkitWrapper assign_partial_charges()'s use_conformers kwarg
1466
+ to ensure charges are really conformer dependent. Skip Gasteiger because it isn't
1467
+ conformer dependent."""
1468
+ import copy
1469
+
1470
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1471
+ molecule = create_ethanol()
1472
+ molecule.generate_conformers(n_conformers=1)
1473
+ molecule.assign_partial_charges(
1474
+ toolkit_registry=toolkit_registry,
1475
+ partial_charge_method=partial_charge_method,
1476
+ use_conformers=molecule.conformers,
1477
+ )
1478
+ pcs1 = copy.deepcopy(molecule.partial_charges)
1479
+ molecule._conformers[0][0][0] += 0.2 * unit.angstrom
1480
+ molecule._conformers[0][1][1] -= 0.2 * unit.angstrom
1481
+ molecule._conformers[0][2][1] += 0.2 * unit.angstrom
1482
+ molecule.assign_partial_charges(
1483
+ toolkit_registry=toolkit_registry,
1484
+ partial_charge_method=partial_charge_method,
1485
+ use_conformers=molecule.conformers,
1486
+ )
1487
+ for pc1, pc2 in zip(pcs1, molecule.partial_charges):
1488
+ assert abs(pc1 - pc2) > 1.0e-5 * unit.elementary_charge
1489
+
1490
+ @pytest.mark.parametrize("partial_charge_method", ["am1bcc", "am1elf10", "am1-mulliken", "gasteiger"])
1491
+ def test_assign_partial_charges_net_charge(self, partial_charge_method):
1492
+ """
1493
+ Test OpenEyeToolkitWrapper assign_partial_charges() on a molecule with net charge.
1494
+ """
1495
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1496
+ molecule = create_acetate()
1497
+ molecule.assign_partial_charges(
1498
+ toolkit_registry=toolkit_registry,
1499
+ partial_charge_method=partial_charge_method,
1500
+ )
1501
+ charge_sum = np.sum(molecule.partial_charges)
1502
+ assert -1.0e-10 < abs(charge_sum.m_as(unit.elementary_charge) + 1.0)
1503
+
1504
+ def test_assign_partial_charges_bad_charge_method(self):
1505
+ """Test OpenEyeToolkitWrapper assign_partial_charges() for a nonexistent charge method"""
1506
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1507
+ molecule = create_ethanol()
1508
+
1509
+ # Molecule.assign_partial_charges calls the ToolkitRegistry with raise_exception_types = [],
1510
+ # which means it will only ever return ValueError
1511
+ with pytest.raises(ValueError, match="is not available from OpenEyeToolkitWrapper"):
1512
+ molecule.assign_partial_charges(
1513
+ toolkit_registry=toolkit_registry,
1514
+ partial_charge_method="NotARealChargeMethod",
1515
+ )
1516
+
1517
+ # ToolkitWrappers raise a specific exception class, so we test that here
1518
+ with pytest.raises(
1519
+ ChargeMethodUnavailableError,
1520
+ match="is not available from OpenEyeToolkitWrapper",
1521
+ ):
1522
+ OETKW = OpenEyeToolkitWrapper()
1523
+ OETKW.assign_partial_charges(molecule=molecule, partial_charge_method="NotARealChargeMethod")
1524
+
1525
+ @pytest.mark.parametrize(
1526
+ "partial_charge_method,expected_n_confs",
1527
+ [("am1bcc", 1), ("am1-mulliken", 1), ("gasteiger", 0)],
1528
+ )
1529
+ def test_assign_partial_charges_wrong_n_confs(self, partial_charge_method, expected_n_confs):
1530
+ """
1531
+ Test OpenEyeToolkitWrapper assign_partial_charges() when requesting to use an incorrect number of
1532
+ conformers
1533
+ """
1534
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1535
+ molecule = create_ethanol()
1536
+ molecule.generate_conformers(n_conformers=2, rms_cutoff=0.01 * unit.angstrom)
1537
+
1538
+ # Try passing in the incorrect number of confs, but without specifying strict_n_conformers,
1539
+ # which should produce a warning
1540
+ with pytest.warns(
1541
+ IncorrectNumConformersWarning,
1542
+ match=f"has 2 conformers, but charge method '{partial_charge_method}' expects exactly {expected_n_confs}.",
1543
+ ):
1544
+ molecule.assign_partial_charges(
1545
+ toolkit_registry=toolkit_registry,
1546
+ partial_charge_method=partial_charge_method,
1547
+ use_conformers=molecule.conformers,
1548
+ strict_n_conformers=False,
1549
+ )
1550
+
1551
+ # Try again, with strict_n_confs as true, but not including use_confs, so the
1552
+ # recommended number of confs will be generated
1553
+ molecule.assign_partial_charges(
1554
+ toolkit_registry=toolkit_registry,
1555
+ partial_charge_method=partial_charge_method,
1556
+ strict_n_conformers=True,
1557
+ )
1558
+
1559
+ # Test calling the ToolkitWrapper _indirectly_, though a ToolkitRegistry,
1560
+ # which should aggregate any exceptions and bundle all of the messages
1561
+ # in a failed task together in a single ValueError.
1562
+ with pytest.raises(
1563
+ ValueError,
1564
+ match=rf"has 2 conformers, but charge method '{partial_charge_method}' expects exactly {expected_n_confs}.",
1565
+ ):
1566
+ molecule.assign_partial_charges(
1567
+ toolkit_registry=toolkit_registry,
1568
+ partial_charge_method=partial_charge_method,
1569
+ use_conformers=molecule.conformers,
1570
+ strict_n_conformers=True,
1571
+ )
1572
+
1573
+ # Test calling the ToolkitWrapper _directly_, passing in the incorrect number of
1574
+ # confs, and specify strict_n_conformers, which should produce an IncorrectNumConformersError
1575
+ with pytest.raises(
1576
+ IncorrectNumConformersError,
1577
+ match=rf"has 2 conformers, but charge method '{partial_charge_method}' expects exactly {expected_n_confs}.",
1578
+ ):
1579
+ OETKW = OpenEyeToolkitWrapper()
1580
+ OETKW.assign_partial_charges(
1581
+ molecule=molecule,
1582
+ partial_charge_method=partial_charge_method,
1583
+ use_conformers=molecule.conformers,
1584
+ strict_n_conformers=True,
1585
+ )
1586
+
1587
+ def test_assign_partial_charges_failure(self):
1588
+ """Test OpenEyeToolkitWrapper assign_partial_charges() on a molecule it cannot assign charges to"""
1589
+
1590
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1591
+ smiles = "[Li+1]"
1592
+ molecule = toolkit_wrapper.from_smiles(smiles)
1593
+ molecule.generate_conformers(toolkit_registry=toolkit_wrapper)
1594
+
1595
+ # For now, I'm just testing AM1-BCC (will test more when the SMIRNOFF spec for other charges is finalized)
1596
+ with pytest.raises(Exception) as excinfo:
1597
+ molecule.assign_partial_charges(partial_charge_method="am1-bcc", toolkit_registry=toolkit_wrapper)
1598
+ assert "Unable to assign charges" in str(excinfo)
1599
+ assert "OE Error: " in str(excinfo)
1600
+
1601
+ def test_assign_partial_charges_trans_cooh_am1bcc(self):
1602
+ """Test OpenEyeToolkitWrapper for computing partial charges for problematic molecules, as exemplified by
1603
+ Issue 346 (https://github.com/openforcefield/openff-toolkit/issues/346)"""
1604
+
1605
+ lysine = Molecule.from_smiles("C(CC[NH3+])C[C@@H](C(=O)O)N")
1606
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1607
+ lysine.generate_conformers(toolkit_registry=toolkit_wrapper)
1608
+ lysine.assign_partial_charges(partial_charge_method="am1bcc", toolkit_registry=toolkit_wrapper)
1609
+
1610
+ @pytest.mark.parametrize(
1611
+ "bond_order_model",
1612
+ ["am1-wiberg", "am1-wiberg-elf10", "pm3-wiberg", "pm3-wiberg-elf10"],
1613
+ )
1614
+ @pytest.mark.parametrize(
1615
+ "smiles",
1616
+ [
1617
+ "[H]C([H])([H])C([H])([H])[H]",
1618
+ "[H]C([H])([H])[N+]([H])([H])[H]",
1619
+ r"C\C(F)=C(/F)C[C@@](C)(Cl)Br",
1620
+ ],
1621
+ )
1622
+ def test_assign_fractional_bond_orders(self, bond_order_model, smiles):
1623
+ """Test OpenEyeToolkitWrapper assign_fractional_bond_orders()"""
1624
+
1625
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1626
+ molecule = toolkit_wrapper.from_smiles(smiles)
1627
+ molecule.assign_fractional_bond_orders(toolkit_registry=toolkit_wrapper, bond_order_model=bond_order_model)
1628
+ # TODO: Add test for equivalent Wiberg orders for equivalent bonds
1629
+
1630
+ # Sanity check single bonds.
1631
+ assert all(0.75 < bond.fractional_bond_order < 1.25 for bond in molecule.bonds if bond.bond_order == 1)
1632
+ # Sanity check double bonds.
1633
+ assert all(1.75 < bond.fractional_bond_order < 2.25 for bond in molecule.bonds if bond.bond_order == 2)
1634
+
1635
+ def test_assign_fractional_bond_orders_multi_conf(self, formic_acid_molecule, formic_acid_conformers):
1636
+ """Test that the OpenEyeToolkitWrapper assign_fractional_bond_orders()
1637
+ function correctly averages over all conformers."""
1638
+
1639
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1640
+
1641
+ # Compute the WBO from a single conformer.
1642
+ formic_acid_molecule.assign_fractional_bond_orders(
1643
+ toolkit_registry=toolkit_wrapper,
1644
+ bond_order_model="am1-wiberg",
1645
+ use_conformers=[formic_acid_conformers["cis"]],
1646
+ )
1647
+ cis_bond_orders = [bond.fractional_bond_order for bond in formic_acid_molecule.bonds]
1648
+ formic_acid_molecule.assign_fractional_bond_orders(
1649
+ toolkit_registry=toolkit_wrapper,
1650
+ bond_order_model="am1-wiberg",
1651
+ use_conformers=[formic_acid_conformers["trans"]],
1652
+ )
1653
+ trans_bond_orders = [bond.fractional_bond_order for bond in formic_acid_molecule.bonds]
1654
+
1655
+ # Use the method to average the conformers.
1656
+ formic_acid_molecule.assign_fractional_bond_orders(
1657
+ toolkit_registry=toolkit_wrapper,
1658
+ bond_order_model="am1-wiberg",
1659
+ use_conformers=[
1660
+ formic_acid_conformers["cis"],
1661
+ formic_acid_conformers["trans"],
1662
+ ],
1663
+ )
1664
+ avg_bond_orders = [bond.fractional_bond_order for bond in formic_acid_molecule.bonds]
1665
+
1666
+ # The average should be distinct from the WBO from either conformer.
1667
+ assert not np.allclose(cis_bond_orders, avg_bond_orders)
1668
+ assert not np.allclose(trans_bond_orders, avg_bond_orders)
1669
+
1670
+ assert np.allclose(np.mean([trans_bond_orders, cis_bond_orders], axis=0), avg_bond_orders)
1671
+
1672
+ def test_assign_fractional_bond_orders_conformer_dependence(self):
1673
+ """
1674
+ Test that OpenEyeToolkitWrapper assign_fractional_bond_orders() provides different results when using
1675
+ different conformers
1676
+ """
1677
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1678
+ # Get the WBOs using one conformer
1679
+ molecule = create_ethanol()
1680
+ molecule.generate_conformers(toolkit_registry=toolkit_wrapper)
1681
+ molecule.assign_fractional_bond_orders(
1682
+ toolkit_registry=toolkit_wrapper,
1683
+ use_conformers=molecule.conformers,
1684
+ bond_order_model="am1-wiberg",
1685
+ )
1686
+
1687
+ # Do the same again, but change the conformer to yield a different result
1688
+ molecule_diff_coords = create_ethanol()
1689
+ molecule_diff_coords.generate_conformers(toolkit_registry=toolkit_wrapper)
1690
+ molecule_diff_coords._conformers[0][0][0] = molecule_diff_coords._conformers[0][0][0] + 1.0 * unit.angstrom
1691
+ molecule_diff_coords._conformers[0][1][0] = molecule_diff_coords._conformers[0][1][0] - 1.0 * unit.angstrom
1692
+ molecule_diff_coords._conformers[0][2][0] = molecule_diff_coords._conformers[0][2][0] + 1.0 * unit.angstrom
1693
+ molecule_diff_coords.assign_fractional_bond_orders(
1694
+ toolkit_registry=toolkit_wrapper,
1695
+ use_conformers=molecule_diff_coords.conformers,
1696
+ bond_order_model="am1-wiberg",
1697
+ )
1698
+
1699
+ for bond1, bond2 in zip(molecule.bonds, molecule_diff_coords.bonds):
1700
+ assert abs(bond1.fractional_bond_order - bond2.fractional_bond_order) > 1e-3
1701
+
1702
+ @pytest.mark.parametrize(
1703
+ "bond_order_model",
1704
+ ["am1-wiberg", "am1-wiberg-elf10", "pm3-wiberg", "pm3-wiberg-elf10"],
1705
+ )
1706
+ def test_assign_fractional_bond_orders_neutral_charge_mol(self, bond_order_model):
1707
+ """Test OpenEyeToolkitWrapper assign_fractional_bond_orders() for neutral and
1708
+ charged molecule"""
1709
+
1710
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1711
+ # Reading neutral molecule from file
1712
+ filename = get_data_file_path("molecules/CID20742535_neutral.sdf")
1713
+ molecule1 = Molecule.from_file(filename)
1714
+ # Reading negative molecule from file
1715
+ filename = get_data_file_path("molecules/CID20742535_anion.sdf")
1716
+ molecule2 = Molecule.from_file(filename)
1717
+
1718
+ # Checking that only one additional bond is present in the neutral molecule
1719
+ assert len(molecule1.bonds) == len(molecule2.bonds) + 1
1720
+
1721
+ molecule1.assign_fractional_bond_orders(
1722
+ toolkit_registry=toolkit_wrapper,
1723
+ bond_order_model=bond_order_model,
1724
+ use_conformers=molecule1.conformers,
1725
+ )
1726
+
1727
+ for i in molecule1.bonds:
1728
+ if i.is_aromatic:
1729
+ # Checking aromatic bonds
1730
+ assert 1.05 < i.fractional_bond_order < 1.65
1731
+ elif i.atom1.atomic_number == 1 or i.atom2.atomic_number == 1:
1732
+ # Checking bond order of C-H or O-H bonds are around 1
1733
+ assert 0.85 < i.fractional_bond_order < 1.05
1734
+ elif i.atom1.atomic_number == 8 or i.atom2.atomic_number == 8:
1735
+ # Checking C-O single bond
1736
+ wbo_C_O_neutral = i.fractional_bond_order
1737
+ assert 1.0 < wbo_C_O_neutral < 1.5
1738
+ else:
1739
+ # Should be C-C single bond
1740
+ assert (i.atom1_index == 4 and i.atom2_index == 6) or (i.atom1_index == 6 and i.atom2_index == 4)
1741
+ wbo_C_C_neutral = i.fractional_bond_order
1742
+ assert 1.0 < wbo_C_C_neutral < 1.3
1743
+
1744
+ molecule2.assign_fractional_bond_orders(
1745
+ toolkit_registry=toolkit_wrapper,
1746
+ bond_order_model=bond_order_model,
1747
+ use_conformers=molecule2.conformers,
1748
+ )
1749
+ for i in molecule2.bonds:
1750
+ if i.is_aromatic:
1751
+ # Checking aromatic bonds
1752
+ assert 1.05 < i.fractional_bond_order < 1.65
1753
+ elif i.atom1.atomic_number == 1 or i.atom2.atomic_number == 1:
1754
+ # Checking bond order of C-H or O-H bonds are around 1
1755
+ assert 0.85 < i.fractional_bond_order < 1.05
1756
+ elif i.atom1.atomic_number == 8 or i.atom2.atomic_number == 8:
1757
+ # Checking C-O single bond
1758
+ wbo_C_O_anion = i.fractional_bond_order
1759
+ assert 1.3 < wbo_C_O_anion < 1.8
1760
+ else:
1761
+ # Should be C-C single bond
1762
+ assert (i.atom1_index == 4 and i.atom2_index == 6) or (i.atom1_index == 6 and i.atom2_index == 4)
1763
+ wbo_C_C_anion = i.fractional_bond_order
1764
+ assert 1.0 < wbo_C_C_anion < 1.3
1765
+
1766
+ # Wiberg bond order of C-C single bond is higher in the anion
1767
+ assert wbo_C_C_anion > wbo_C_C_neutral
1768
+ # Wiberg bond order of C-O bond is higher in the anion
1769
+ assert wbo_C_O_anion > wbo_C_O_neutral
1770
+
1771
+ def test_assign_fractional_bond_orders_invalid_method(self):
1772
+ """
1773
+ Test that OpenEyeToolkitWrapper assign_fractional_bond_orders() raises the
1774
+ correct error if an invalid charge model is provided
1775
+ """
1776
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1777
+
1778
+ molecule = toolkit_wrapper.from_smiles("C")
1779
+
1780
+ expected_error = (
1781
+ r"Bond order model 'not a real bond order model' is not supported by "
1782
+ "OpenEyeToolkitWrapper. Supported models are "
1783
+ r"\['am1-wiberg', 'am1-wiberg-elf10', 'pm3-wiberg', 'pm3-wiberg-elf10'\]"
1784
+ )
1785
+
1786
+ with pytest.raises(ValueError, match=expected_error):
1787
+ molecule.assign_fractional_bond_orders(
1788
+ toolkit_registry=toolkit_wrapper,
1789
+ bond_order_model="not a real bond order model",
1790
+ )
1791
+
1792
+ @pytest.mark.slow
1793
+ def test_max_substructure_matches_can_handle_large_molecule(self):
1794
+ """Test OpenEyeToolkitWrapper substructure search handles more than the default of MaxMatches = 1024
1795
+ See https://github.com/openforcefield/openff-toolkit/pull/509 .
1796
+ """
1797
+
1798
+ tk = OpenEyeToolkitWrapper()
1799
+ smiles = "C" * 600
1800
+ molecule = tk.from_smiles(smiles)
1801
+ query = "[C:1]~[C:2]"
1802
+ ret = molecule.chemical_environment_matches(query, toolkit_registry=tk)
1803
+ assert len(ret) == 1198
1804
+ assert len(ret[0]) == 2
1805
+
1806
+ def test_find_rotatable_bonds(self):
1807
+ """Test finding rotatable bonds while ignoring some groups"""
1808
+
1809
+ # test a simple molecule
1810
+ ethanol = create_ethanol()
1811
+ bonds = ethanol.find_rotatable_bonds()
1812
+ assert len(bonds) == 2
1813
+ for bond in bonds:
1814
+ assert ethanol.atoms[bond.atom1_index].atomic_number != 1
1815
+ assert ethanol.atoms[bond.atom2_index].atomic_number != 1
1816
+
1817
+ # now ignore the C-O bond, forwards
1818
+ bonds = ethanol.find_rotatable_bonds(ignore_functional_groups="[#6:1]-[#8:2]")
1819
+ assert len(bonds) == 1
1820
+ assert ethanol.atoms[bonds[0].atom1_index].atomic_number == 6
1821
+ assert ethanol.atoms[bonds[0].atom2_index].atomic_number == 6
1822
+
1823
+ # now ignore the O-C bond, backwards
1824
+ bonds = ethanol.find_rotatable_bonds(ignore_functional_groups="[#8:1]-[#6:2]")
1825
+ assert len(bonds) == 1
1826
+ assert ethanol.atoms[bonds[0].atom1_index].atomic_number == 6
1827
+ assert ethanol.atoms[bonds[0].atom2_index].atomic_number == 6
1828
+
1829
+ # now ignore the C-C bond
1830
+ bonds = ethanol.find_rotatable_bonds(ignore_functional_groups="[#6:1]-[#6:2]")
1831
+ assert len(bonds) == 1
1832
+ assert ethanol.atoms[bonds[0].atom1_index].atomic_number == 6
1833
+ assert ethanol.atoms[bonds[0].atom2_index].atomic_number == 8
1834
+
1835
+ # ignore a list of searches, forward
1836
+ bonds = ethanol.find_rotatable_bonds(ignore_functional_groups=["[#6:1]-[#8:2]", "[#6:1]-[#6:2]"])
1837
+ assert bonds == []
1838
+
1839
+ # ignore a list of searches, backwards
1840
+ bonds = ethanol.find_rotatable_bonds(ignore_functional_groups=["[#6:1]-[#6:2]", "[#8:1]-[#6:2]"])
1841
+ assert bonds == []
1842
+
1843
+ # test molecules that should have no rotatable bonds
1844
+ cyclohexane = create_cyclohexane()
1845
+ bonds = cyclohexane.find_rotatable_bonds()
1846
+ assert bonds == []
1847
+
1848
+ methane = Molecule.from_smiles("C")
1849
+ bonds = methane.find_rotatable_bonds()
1850
+ assert bonds == []
1851
+
1852
+ ethene = Molecule.from_smiles("C=C")
1853
+ bonds = ethene.find_rotatable_bonds()
1854
+ assert bonds == []
1855
+
1856
+ terminal_forwards = "[*]~[*:1]-[X2H1,X3H2,X4H3:2]-[#1]"
1857
+ terminal_backwards = "[#1]-[X2H1,X3H2,X4H3:1]-[*:2]~[*]"
1858
+ # test removing terminal rotors
1859
+ toluene = Molecule.from_file(get_data_file_path("molecules/toluene.sdf"))
1860
+ bonds = toluene.find_rotatable_bonds()
1861
+ assert len(bonds) == 1
1862
+ assert toluene.atoms[bonds[0].atom1_index].atomic_number == 6
1863
+ assert toluene.atoms[bonds[0].atom2_index].atomic_number == 6
1864
+
1865
+ # find terminal bonds forward
1866
+ bonds = toluene.find_rotatable_bonds(ignore_functional_groups=terminal_forwards)
1867
+ assert bonds == []
1868
+
1869
+ # find terminal bonds backwards
1870
+ bonds = toluene.find_rotatable_bonds(ignore_functional_groups=terminal_backwards)
1871
+ assert bonds == []
1872
+
1873
+ # TODO: Check partial charge invariants (total charge, charge equivalence)
1874
+
1875
+ # TODO: Add test for aromaticity
1876
+ # TODO: Add test and molecule functionality for isotopes
1877
+
1878
+ @pytest.mark.parametrize(
1879
+ ("smiles", "n_atom_rings", "n_bond_rings"),
1880
+ [
1881
+ ("c1ccc2ccccc2c1", 10, 11),
1882
+ ("c1ccc(cc1)c2ccccc2", 12, 12),
1883
+ ("Cc1ccc(cc1Nc2nccc(n2)c3cccnc3)NC(=O)c4ccc(cc4)CN5CCN(CC5)C", 30, 30),
1884
+ ],
1885
+ )
1886
+ def test_is_in_ring(self, smiles, n_atom_rings, n_bond_rings):
1887
+ """Test Atom.is_in_ring and Bond.is_in_ring"""
1888
+ mol = Molecule.from_smiles(smiles)
1889
+
1890
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper()])
1891
+
1892
+ atoms_in_ring = [atom for atom in mol.atoms if atom.is_in_ring(toolkit_registry=toolkit_registry)]
1893
+
1894
+ bonds_in_ring = [bond for bond in mol.bonds if bond.is_in_ring(toolkit_registry=toolkit_registry)]
1895
+
1896
+ assert len(atoms_in_ring) == n_atom_rings
1897
+ assert len(bonds_in_ring) == n_bond_rings
1898
+
1899
+ def test_central_biphenyl_bond(self):
1900
+ """Test that `Bond.is_in_ring` is False for the central bond in a phenyl"""
1901
+ # Use a mapped smiles to ensure atom order while looking up central bond
1902
+ # Generated via Molecule.from_smiles("c1ccc(cc1)c2ccccc2").to_smiles(mapped=True)
1903
+
1904
+ biphenyl = Molecule.from_mapped_smiles(
1905
+ "[H:13][c:1]1[c:2]([c:3]([c:4]([c:5]([c:6]1[H:17])[H:16])[c:7]2[c:8]([c:9]([c:10]"
1906
+ "([c:11]([c:12]2[H:22])[H:21])[H:20])[H:19])[H:18])[H:15])[H:14]"
1907
+ )
1908
+
1909
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1910
+
1911
+ this_bond = biphenyl.get_bond_between(3, 6)
1912
+ assert this_bond.is_in_ring(toolkit_registry=toolkit_registry) is False
1913
+
1914
+ ring_bonds = [b for b in biphenyl.bonds if b.is_in_ring(toolkit_registry=toolkit_registry)]
1915
+ assert len(ring_bonds) == 12
1916
+
1917
+ def test_unattached_is_in_ring(self):
1918
+ toolkit = OpenEyeToolkitWrapper()
1919
+ dummy_atom = Atom(1, 0, False)
1920
+
1921
+ with pytest.raises(NotAttachedToMoleculeError, match="Atom"):
1922
+ toolkit.atom_is_in_ring(dummy_atom)
1923
+
1924
+ # The Bond constructor checks to see that the atoms are in a molecule,
1925
+ # so not so straightforward to make one from the constructor
1926
+ dummy_bond = Molecule.from_smiles("O").bonds[0]
1927
+ dummy_bond._molecule = None
1928
+
1929
+ with pytest.raises(NotAttachedToMoleculeError, match="Bond"):
1930
+ toolkit.bond_is_in_ring(dummy_bond)
1931
+
1932
+ def test_find_matches_unique(self):
1933
+ """Test the expected behavior of the `unique` argument in find_matches"""
1934
+ smirks = "[C:1]~[C:2]~[C:3]"
1935
+ tk = OpenEyeToolkitWrapper()
1936
+
1937
+ mol = Molecule.from_smiles("CCC")
1938
+
1939
+ assert len(tk.find_smarts_matches(mol, smirks, unique=True)) == 1
1940
+ assert len(tk.find_smarts_matches(mol, smirks, unique=False)) == 2
1941
+
1942
+ def test_find_matches_bad_smarts(self):
1943
+ with pytest.raises(
1944
+ ChemicalEnvironmentParsingError,
1945
+ match="foobar",
1946
+ ):
1947
+ OpenEyeToolkitWrapper().find_smarts_matches(
1948
+ create_ethanol(),
1949
+ smarts="foobar",
1950
+ )
1951
+
1952
+ def test_charge_method_api_continuity(self):
1953
+ """Test rough continuity of OpenEyeToolkitWrapper.SUPPORTED_CHARGE_METHODS"""
1954
+
1955
+ assert OpenEyeToolkitWrapper.SUPPORTED_CHARGE_METHODS["gasteiger"] == {
1956
+ "oe_charge_method": "OEGasteigerCharges",
1957
+ "min_confs": 0,
1958
+ "max_confs": 0,
1959
+ "rec_confs": 0,
1960
+ }
1961
+ assert OpenEyeToolkitWrapper.SUPPORTED_CHARGE_METHODS["am1bcc"] == {
1962
+ "oe_charge_method": "OEAM1BCCCharges",
1963
+ "min_confs": 1,
1964
+ "max_confs": 1,
1965
+ "rec_confs": 1,
1966
+ }
1967
+
1968
+ assert OpenEyeToolkitWrapper.SUPPORTED_CHARGE_METHODS["am1bccelf10"] == {
1969
+ "oe_charge_method": "OEAM1BCCELF10Charges",
1970
+ "min_confs": 1,
1971
+ "max_confs": None,
1972
+ "rec_confs": 500,
1973
+ }
1974
+
1975
+
1976
+ @requires_rdkit
1977
+ class TestRDKitToolkitWrapper:
1978
+ """Test the RDKitToolkitWrapper"""
1979
+
1980
+ def test_supported_charge_methods(self):
1981
+ methods = RDKitToolkitWrapper().supported_charge_methods
1982
+
1983
+ assert "mmff94" in methods
1984
+ assert "gasteiger" in methods
1985
+
1986
+ assert "zeros" not in methods
1987
+ assert "formal_charge" not in methods
1988
+ assert "am1bcc" not in methods
1989
+ assert "am1bccelf10" not in methods
1990
+
1991
+ def test_smiles(self):
1992
+ """Test RDKitToolkitWrapper to_smiles() and from_smiles()"""
1993
+ toolkit_wrapper = RDKitToolkitWrapper()
1994
+ # This differs from OE's expected output due to different canonicalization schemes
1995
+ smiles = "[H][C]([H])([H])[C]([H])([H])[H]"
1996
+ molecule = Molecule.from_smiles(smiles, toolkit_registry=toolkit_wrapper)
1997
+ # When making a molecule from SMILES, partial charges should be initialized to None
1998
+ assert molecule.partial_charges is None
1999
+ smiles2 = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
2000
+ # print(smiles, smiles2)
2001
+ assert smiles == smiles2
2002
+
2003
+ @pytest.mark.parametrize(
2004
+ "smiles,exception_regex",
2005
+ [
2006
+ (r"C\C(F)=C(/F)CC(C)(Cl)Br", "Undefined chiral centers"),
2007
+ (r"C\C(F)=C(/F)C[C@@](C)(Cl)Br", None),
2008
+ (r"CC(F)=C(F)C[C@@](C)(Cl)Br", "Bonds with undefined stereochemistry"),
2009
+ ],
2010
+ )
2011
+ def test_smiles_missing_stereochemistry(self, smiles, exception_regex):
2012
+ """Test RDKitToolkitWrapper to_smiles() and from_smiles() when given ambiguous stereochemistry"""
2013
+ toolkit_wrapper = RDKitToolkitWrapper()
2014
+
2015
+ if exception_regex is not None:
2016
+ with pytest.raises(UndefinedStereochemistryError, match=exception_regex):
2017
+ Molecule.from_smiles(smiles, toolkit_registry=toolkit_wrapper)
2018
+ Molecule.from_smiles(smiles, toolkit_registry=toolkit_wrapper, allow_undefined_stereo=True)
2019
+ else:
2020
+ Molecule.from_smiles(smiles, toolkit_registry=toolkit_wrapper)
2021
+
2022
+ # TODO: test_smiles_round_trip
2023
+
2024
+ def test_smiles_add_H(self):
2025
+ """Test RDKitToolkitWrapper to_smiles() and from_smiles()"""
2026
+ toolkit_wrapper = RDKitToolkitWrapper()
2027
+ input_smiles = "CC"
2028
+ # This differs from OE's expected output due to different canonicalization schemes
2029
+ expected_output_smiles = "[H][C]([H])([H])[C]([H])([H])[H]"
2030
+ molecule = Molecule.from_smiles(input_smiles, toolkit_registry=toolkit_wrapper)
2031
+ smiles2 = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
2032
+ assert smiles2 == expected_output_smiles
2033
+
2034
+ def test_rdkit_from_smiles_name(self):
2035
+ """
2036
+ Test to ensure that the `name` kwarg to from_smiles behaves correctly
2037
+ """
2038
+ toolkit_wrapper = RDKitToolkitWrapper()
2039
+ mol = toolkit_wrapper.from_smiles("C")
2040
+ assert mol.name == ""
2041
+ mol = toolkit_wrapper.from_smiles("C", name="bob")
2042
+ assert mol.name == "bob"
2043
+
2044
+ def test_rdkit_from_smiles_radical(self):
2045
+ """Test that parsing an SMILES with a radical raises RadicalsNotSupportedError."""
2046
+ with pytest.raises(RadicalsNotSupportedError):
2047
+ RDKitToolkitWrapper().from_smiles("[CH3]")
2048
+
2049
+ def test_rdkit_from_smiles_transition_metal_radical(self):
2050
+ """Test that parsing an SMILES with a transition metal radical works."""
2051
+ RDKitToolkitWrapper().from_smiles("[Zn+2]")
2052
+
2053
+ def test_rdkit_from_smiles_hydrogens_are_explicit(self):
2054
+ """
2055
+ Test to ensure that RDKitToolkitWrapper.from_smiles has the proper behavior with
2056
+ respect to its hydrogens_are_explicit kwarg
2057
+ """
2058
+ toolkit_wrapper = RDKitToolkitWrapper()
2059
+ smiles_impl = "C#C"
2060
+ with pytest.raises(
2061
+ ValueError,
2062
+ match=r"but RDKit toolkit interpreted SMILES 'C#C' as having implicit hydrogen",
2063
+ ):
2064
+ offmol = Molecule.from_smiles(
2065
+ smiles_impl,
2066
+ toolkit_registry=toolkit_wrapper,
2067
+ hydrogens_are_explicit=True,
2068
+ )
2069
+ offmol = Molecule.from_smiles(smiles_impl, toolkit_registry=toolkit_wrapper, hydrogens_are_explicit=False)
2070
+ assert offmol.n_atoms == 4
2071
+
2072
+ smiles_expl = "[H][C]#[C][H]"
2073
+ offmol = Molecule.from_smiles(smiles_expl, toolkit_registry=toolkit_wrapper, hydrogens_are_explicit=True)
2074
+ assert offmol.n_atoms == 4
2075
+ # It's debatable whether this next function should pass. Strictly speaking, the hydrogens in this SMILES
2076
+ # _are_ explicit, so allowing "hydrogens_are_explicit=False" through here is allowing a contradiction.
2077
+ # We might rethink the name of this kwarg.
2078
+
2079
+ offmol = Molecule.from_smiles(smiles_expl, toolkit_registry=toolkit_wrapper, hydrogens_are_explicit=False)
2080
+ assert offmol.n_atoms == 4
2081
+
2082
+ def test_rdkit_from_smiles_hydrogens_are_explicit_and_in_graph(self):
2083
+ """
2084
+ Test to ensure that RDKitToolkitWrapper.from_smiles has the proper behavior with
2085
+ respect to its hydrogens_are_explicit kwarg and that a CMILES entry has all hydrogens
2086
+ in the graph.
2087
+
2088
+ `Issue #936 <https://github.com/openforcefield/openff-toolkit/issues/936>`,
2089
+ `Issue #1696 <https://github.com/openforcefield/openff-toolkit/issues/1696>`,
2090
+ """
2091
+ toolkit_wrapper = RDKitToolkitWrapper()
2092
+ smiles_impl = "[H][C]([H])([H])[NH+]([H])[C]([H])([H])[H]"
2093
+ with pytest.raises(
2094
+ ValueError,
2095
+ match="the following SMILES as having some nonexplicit hydrogens",
2096
+ ):
2097
+ _ = Molecule.from_smiles(
2098
+ smiles_impl,
2099
+ toolkit_registry=toolkit_wrapper,
2100
+ hydrogens_are_explicit=True,
2101
+ )
2102
+
2103
+ @pytest.mark.parametrize("molecule", get_mini_drug_bank(RDKitToolkitWrapper))
2104
+ def test_to_inchi(self, molecule):
2105
+ """Test, but do not validate, conversion to standard and non-standard InChI"""
2106
+
2107
+ toolkit = RDKitToolkitWrapper()
2108
+ molecule.to_inchi(toolkit_registry=toolkit)
2109
+ molecule.to_inchi(fixed_hydrogens=True, toolkit_registry=toolkit)
2110
+
2111
+ @pytest.mark.parametrize("molecule", get_mini_drug_bank(RDKitToolkitWrapper))
2112
+ def test_to_inchikey(self, molecule):
2113
+ """Test, but do not validate, the conversion to standard and non-standard InChIKey"""
2114
+
2115
+ toolkit = RDKitToolkitWrapper()
2116
+ molecule.to_inchikey(toolkit_registry=toolkit)
2117
+ molecule.to_inchikey(fixed_hydrogens=True, toolkit_registry=toolkit)
2118
+
2119
+ def test_from_bad_inchi(self):
2120
+ """Test building a molecule from a bad InChI string"""
2121
+
2122
+ toolkit = RDKitToolkitWrapper()
2123
+ inchi = "InChI=1S/ksbfksfksfksbfks"
2124
+
2125
+ with pytest.raises(InChIParseError, match="ksbfksfksfksbfks"):
2126
+ Molecule.from_inchi(inchi, toolkit_registry=toolkit)
2127
+
2128
+ inchi_data = [
2129
+ {
2130
+ "molecule": create_ethanol(),
2131
+ "standard_inchi": "InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3",
2132
+ "fixed_hydrogen_inchi": "InChI=1/C2H6O/c1-2-3/h3H,2H2,1H3",
2133
+ },
2134
+ {
2135
+ "molecule": create_reversed_ethanol(),
2136
+ "standard_inchi": "InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3",
2137
+ "fixed_hydrogen_inchi": "InChI=1/C2H6O/c1-2-3/h3H,2H2,1H3",
2138
+ },
2139
+ {
2140
+ "molecule": create_acetaldehyde(),
2141
+ "standard_inchi": "InChI=1S/C2H4O/c1-2-3/h2H,1H3",
2142
+ "fixed_hydrogen_inchi": "InChI=1/C2H4O/c1-2-3/h2H,1H3",
2143
+ },
2144
+ {
2145
+ "molecule": create_cyclohexane(),
2146
+ "standard_inchi": "InChI=1S/C6H12/c1-2-4-6-5-3-1/h1-6H2",
2147
+ "fixed_hydrogen_inchi": "InChI=1/C6H12/c1-2-4-6-5-3-1/h1-6H2",
2148
+ },
2149
+ ]
2150
+
2151
+ @pytest.mark.parametrize("data", inchi_data)
2152
+ def test_from_inchi(self, data):
2153
+ """Test building a molecule from standard and non-standard InChI strings."""
2154
+
2155
+ toolkit = RDKitToolkitWrapper()
2156
+
2157
+ ref_mol = data["molecule"]
2158
+ # make a molecule from inchi
2159
+ inchi_mol = Molecule.from_inchi(data["standard_inchi"], toolkit_registry=toolkit)
2160
+ assert inchi_mol.to_inchi(toolkit_registry=toolkit) == data["standard_inchi"]
2161
+
2162
+ def compare_mols(ref_mol, inchi_mol):
2163
+ assert ref_mol.n_atoms == inchi_mol.n_atoms
2164
+ assert ref_mol.n_bonds == inchi_mol.n_bonds
2165
+ assert ref_mol.n_angles == inchi_mol.n_angles
2166
+ assert ref_mol.n_propers == inchi_mol.n_propers
2167
+ assert ref_mol.is_isomorphic_with(inchi_mol) is True
2168
+
2169
+ compare_mols(ref_mol, inchi_mol)
2170
+
2171
+ # now make the molecule from the non-standard inchi and compare
2172
+ nonstandard_inchi_mol = Molecule.from_inchi(data["fixed_hydrogen_inchi"])
2173
+ assert (
2174
+ nonstandard_inchi_mol.to_inchi(fixed_hydrogens=True, toolkit_registry=toolkit)
2175
+ == data["fixed_hydrogen_inchi"]
2176
+ )
2177
+
2178
+ compare_mols(ref_mol, nonstandard_inchi_mol)
2179
+
2180
+ def test_rdkit_from_inchi_name(self):
2181
+ """
2182
+ Test to ensure that the `name` kwarg to from_inchi behaves correctly
2183
+ """
2184
+ toolkit_wrapper = RDKitToolkitWrapper()
2185
+ mol = toolkit_wrapper.from_inchi("InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3")
2186
+ assert mol.name == ""
2187
+ mol = toolkit_wrapper.from_inchi("InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3", name="bob")
2188
+ assert mol.name == "bob"
2189
+
2190
+ @pytest.mark.parametrize("molecule", get_mini_drug_bank(RDKitToolkitWrapper))
2191
+ def test_non_standard_inchi_round_trip(self, molecule):
2192
+ """Test if a molecule can survive an InChi round trip test in some cases the standard InChI
2193
+ will not be enough to ensure information is preserved so we test the non-standard inchi here.
2194
+ """
2195
+
2196
+ from openff.toolkit.utils.toolkits import UndefinedStereochemistryError
2197
+
2198
+ toolkit = RDKitToolkitWrapper()
2199
+ inchi = molecule.to_inchi(fixed_hydrogens=True, toolkit_registry=toolkit)
2200
+ # make a copy of the molecule from the inchi string
2201
+ if molecule.name in rdkit_inchi_stereochemistry_lost:
2202
+ # some molecules lose stereochemsitry so they are skipped
2203
+ # if we fail here the molecule may of been fixed
2204
+ with pytest.raises(UndefinedStereochemistryError):
2205
+ mol2 = molecule.from_inchi(inchi, toolkit_registry=toolkit)
2206
+
2207
+ else:
2208
+ print(molecule.name)
2209
+ mol2 = molecule.from_inchi(inchi, toolkit_registry=toolkit)
2210
+
2211
+ # compare the full molecule excluding the properties dictionary
2212
+ # turn of the bond order matching as this could move in the aromatic rings
2213
+ assert molecule.is_isomorphic_with(mol2, bond_order_matching=False, toolkit_registry=toolkit)
2214
+
2215
+ @pytest.mark.parametrize("method", ["to_inchi", "to_inchikey"])
2216
+ def test_empty_inchi(self, method):
2217
+ """Reproduce Issue #1897"""
2218
+ with pytest.raises(
2219
+ EmptyInChiError,
2220
+ match="failed to generate" + (".*key" if method == "to_inchikey" else ""),
2221
+ ):
2222
+ # call either .to_inchi or .to_inchikey
2223
+ getattr(
2224
+ Molecule.from_mapped_smiles("[H:5][S:3]#[N+:2][S:1][H:4]"),
2225
+ method,
2226
+ )(toolkit_registry=RDKitToolkitWrapper())
2227
+
2228
+ @pytest.mark.parametrize("method", ["to_inchi", "to_inchikey"])
2229
+ def test_large_molecule(self, method):
2230
+ getattr(
2231
+ Molecule.from_smiles(342 * "C"),
2232
+ method,
2233
+ )(toolkit_registry=RDKitToolkitWrapper())
2234
+
2235
+ def test_smiles_charged(self):
2236
+ """Test RDKitWrapper functions for reading/writing charged SMILES"""
2237
+ toolkit_wrapper = RDKitToolkitWrapper()
2238
+ # This differs from OE's expected output due to different canonicalization schemes
2239
+ smiles = "[H][C]([H])([H])[N+]([H])([H])[H]"
2240
+ molecule = Molecule.from_smiles(smiles, toolkit_registry=toolkit_wrapper)
2241
+ smiles2 = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
2242
+ assert smiles == smiles2
2243
+
2244
+ def test_to_from_rdkit_core_props_filled(self):
2245
+ """Test RDKitToolkitWrapper to_rdkit() and from_rdkit() when given populated core property fields"""
2246
+ toolkit_wrapper = RDKitToolkitWrapper()
2247
+
2248
+ # Replacing with a simple molecule with stereochemistry
2249
+ input_smiles = r"C\C(F)=C(/F)C[C@@](C)(Cl)Br"
2250
+ expected_output_smiles = r"[H][C]([H])([H])/[C]([F])=[C](\[F])[C]([H])([H])[C@@]([Cl])([Br])[C]([H])([H])[H]"
2251
+ molecule = Molecule.from_smiles(input_smiles, toolkit_registry=toolkit_wrapper)
2252
+ assert molecule.to_smiles(toolkit_registry=toolkit_wrapper) == expected_output_smiles
2253
+
2254
+ # Populate core molecule property fields
2255
+ molecule.name = "Alice"
2256
+ partial_charges = Quantity(
2257
+ np.array(
2258
+ [
2259
+ -0.9,
2260
+ -0.8,
2261
+ -0.7,
2262
+ -0.6,
2263
+ -0.5,
2264
+ -0.4,
2265
+ -0.3,
2266
+ -0.2,
2267
+ -0.1,
2268
+ 0.0,
2269
+ 0.1,
2270
+ 0.2,
2271
+ 0.3,
2272
+ 0.4,
2273
+ 0.5,
2274
+ 0.6,
2275
+ 0.7,
2276
+ 0.8,
2277
+ ]
2278
+ ),
2279
+ unit.elementary_charge,
2280
+ )
2281
+ molecule.partial_charges = partial_charges
2282
+ coords = Quantity(
2283
+ np.array(
2284
+ [
2285
+ ["0.0", "1.0", "2.0"],
2286
+ ["3.0", "4.0", "5.0"],
2287
+ ["6.0", "7.0", "8.0"],
2288
+ ["9.0", "10.0", "11.0"],
2289
+ ["12.0", "13.0", "14.0"],
2290
+ ["15.0", "16.0", "17.0"],
2291
+ ["18.0", "19.0", "20.0"],
2292
+ ["21.0", "22.0", "23.0"],
2293
+ ["24.0", "25.0", "26.0"],
2294
+ ["27.0", "28.0", "29.0"],
2295
+ ["30.0", "31.0", "32.0"],
2296
+ ["33.0", "34.0", "35.0"],
2297
+ ["36.0", "37.0", "38.0"],
2298
+ ["39.0", "40.0", "41.0"],
2299
+ ["42.0", "43.0", "44.0"],
2300
+ ["45.0", "46.0", "47.0"],
2301
+ ["48.0", "49.0", "50.0"],
2302
+ ["51.0", "52.0", "53.0"],
2303
+ ]
2304
+ ),
2305
+ unit.angstrom,
2306
+ )
2307
+ molecule.add_conformer(coords)
2308
+ # Populate core atom property fields
2309
+ molecule.atoms[2].name = "Bob"
2310
+ # Ensure one atom has its stereochemistry specified
2311
+ central_carbon_stereo_specified = False
2312
+ for atom in molecule.atoms:
2313
+ if (atom.atomic_number == 6) and atom.stereochemistry == "S":
2314
+ central_carbon_stereo_specified = True
2315
+ assert central_carbon_stereo_specified
2316
+
2317
+ # Populate bond core property fields
2318
+ fractional_bond_orders = [float(val) for val in range(18)]
2319
+ for fbo, bond in zip(fractional_bond_orders, molecule.bonds):
2320
+ bond.fractional_bond_order = fbo
2321
+
2322
+ # Do a first conversion to/from rdmol
2323
+ rdmol = molecule.to_rdkit()
2324
+ molecule2 = Molecule.from_rdkit(rdmol)
2325
+
2326
+ # Test that properties survived first conversion
2327
+ # assert molecule.to_dict() == molecule2.to_dict()
2328
+ assert molecule.name == molecule2.name
2329
+ # NOTE: This expects the same indexing scheme in the original and new molecule
2330
+
2331
+ central_carbon_stereo_specified = False
2332
+ for atom in molecule2.atoms:
2333
+ if (atom.atomic_number == 6) and atom.stereochemistry == "S":
2334
+ central_carbon_stereo_specified = True
2335
+ assert central_carbon_stereo_specified
2336
+ for atom1, atom2 in zip(molecule.atoms, molecule2.atoms):
2337
+ assert atom1.to_dict() == atom2.to_dict()
2338
+ for bond1, bond2 in zip(molecule.bonds, molecule2.bonds):
2339
+ assert bond1.to_dict() == bond2.to_dict()
2340
+ assert (molecule.conformers[0] == molecule2.conformers[0]).all()
2341
+ for pc1, pc2 in zip(molecule._partial_charges, molecule2._partial_charges):
2342
+ pc1_ul = pc1.m_as(unit.elementary_charge)
2343
+ pc2_ul = pc2.m_as(unit.elementary_charge)
2344
+ assert_almost_equal(pc1_ul, pc2_ul, decimal=6)
2345
+ assert molecule2.to_smiles(toolkit_registry=toolkit_wrapper) == expected_output_smiles
2346
+ # TODO: This should be its own test
2347
+
2348
+ def test_to_from_rdkit_core_props_unset(self):
2349
+ """Test RDKitToolkitWrapper to_rdkit() and from_rdkit() when given empty core property fields"""
2350
+ toolkit_wrapper = RDKitToolkitWrapper()
2351
+
2352
+ # Replacing with a simple molecule with stereochemistry
2353
+ input_smiles = r"C\C(F)=C(/F)C[C@](C)(Cl)Br"
2354
+ expected_output_smiles = r"[H][C]([H])([H])/[C]([F])=[C](\[F])[C]([H])([H])[C@]([Cl])([Br])[C]([H])([H])[H]"
2355
+ molecule = Molecule.from_smiles(input_smiles, toolkit_registry=toolkit_wrapper)
2356
+ assert molecule.to_smiles(toolkit_registry=toolkit_wrapper) == expected_output_smiles
2357
+
2358
+ # Ensure one atom has its stereochemistry specified
2359
+ central_carbon_stereo_specified = False
2360
+ for atom in molecule.atoms:
2361
+ if (atom.atomic_number == 6) and atom.stereochemistry == "R":
2362
+ central_carbon_stereo_specified = True
2363
+ assert central_carbon_stereo_specified
2364
+
2365
+ # Do a first conversion to/from rdmol
2366
+ rdmol = molecule.to_rdkit()
2367
+ molecule2 = Molecule.from_rdkit(rdmol)
2368
+
2369
+ # Test that properties survived first conversion
2370
+ assert molecule.name == molecule2.name
2371
+ # NOTE: This expects the same indexing scheme in the original and new molecule
2372
+
2373
+ central_carbon_stereo_specified = False
2374
+ for atom in molecule2.atoms:
2375
+ if (atom.atomic_number == 6) and atom.stereochemistry == "R":
2376
+ central_carbon_stereo_specified = True
2377
+ assert central_carbon_stereo_specified
2378
+ for atom1, atom2 in zip(molecule.atoms, molecule2.atoms):
2379
+ assert atom1.to_dict() == atom2.to_dict()
2380
+ for bond1, bond2 in zip(molecule.bonds, molecule2.bonds):
2381
+ assert bond1.to_dict() == bond2.to_dict()
2382
+ # The molecule was initialized from SMILES, so mol.conformers arrays should be None for both
2383
+ assert molecule.conformers is None
2384
+ assert molecule2.conformers is None
2385
+ # The molecule was initialized from SMILES, so mol.partial_charges arrays should be None for both
2386
+ assert molecule.partial_charges is None
2387
+ assert molecule2.partial_charges is None
2388
+
2389
+ assert molecule2.to_smiles(toolkit_registry=toolkit_wrapper) == expected_output_smiles
2390
+
2391
+ def test_to_from_rdkit_hierarchy_metadata(self):
2392
+ """
2393
+ Test roundtripping to/from ``OpenEyeToolkitWrapper`` for molecules with PDB hierarchy metadata
2394
+ """
2395
+ for molecule in topology_with_metadata().molecules:
2396
+ rdmol = molecule.to_rdkit()
2397
+ roundtrip_mol = Molecule.from_rdkit(rdmol)
2398
+
2399
+ # Check RDMol
2400
+ for orig_atom, rd_atom in zip(molecule.atoms, rdmol.GetAtoms()):
2401
+ atom_has_any_metadata = (
2402
+ ("residue_name" in orig_atom.metadata)
2403
+ or ("residue_number" in orig_atom.metadata)
2404
+ or ("insertion_code" in orig_atom.metadata)
2405
+ or ("chain_id" in orig_atom.metadata)
2406
+ )
2407
+
2408
+ if not (atom_has_any_metadata):
2409
+ assert rd_atom.GetPDBResidueInfo() is None
2410
+ continue
2411
+
2412
+ if "residue_name" in orig_atom.metadata:
2413
+ assert orig_atom.metadata["residue_name"] == rd_atom.GetPDBResidueInfo().GetResidueName()
2414
+ else:
2415
+ assert rd_atom.GetPDBResidueInfo().GetResidueName() == ""
2416
+
2417
+ if "residue_number" in orig_atom.metadata:
2418
+ assert orig_atom.metadata["residue_number"] == rd_atom.GetPDBResidueInfo().GetResidueNumber()
2419
+ else:
2420
+ assert rd_atom.GetPDBResidueInfo().GetResidueNumber() == 0
2421
+
2422
+ if "insertion_code" in orig_atom.metadata:
2423
+ assert orig_atom.metadata["insertion_code"] == rd_atom.GetPDBResidueInfo().GetInsertionCode()
2424
+ else:
2425
+ assert rd_atom.GetPDBResidueInfo().GetInsertionCode() == " "
2426
+
2427
+ if "chain_id" in orig_atom.metadata:
2428
+ assert orig_atom.metadata["chain_id"] == rd_atom.GetPDBResidueInfo().GetChainId()
2429
+ else:
2430
+ assert rd_atom.GetPDBResidueInfo().GetChainId() == ""
2431
+
2432
+ # Check roundtripped OFFMol
2433
+ for orig_atom, roundtrip_atom in zip(molecule.atoms, roundtrip_mol.atoms):
2434
+ atom_has_any_metadata = (
2435
+ ("residue_name" in orig_atom.metadata)
2436
+ or ("residue_number" in orig_atom.metadata)
2437
+ or ("insertion_code" in orig_atom.metadata)
2438
+ or ("chain_id" in orig_atom.metadata)
2439
+ )
2440
+ if not (atom_has_any_metadata):
2441
+ assert roundtrip_atom.metadata == {}
2442
+ continue
2443
+
2444
+ if "residue_name" in orig_atom.metadata:
2445
+ assert orig_atom.metadata["residue_name"] == roundtrip_atom.metadata["residue_name"]
2446
+ else:
2447
+ assert roundtrip_atom.metadata["residue_name"] == ""
2448
+
2449
+ if "residue_number" in orig_atom.metadata:
2450
+ assert orig_atom.metadata["residue_number"] == roundtrip_atom.metadata["residue_number"]
2451
+ else:
2452
+ assert roundtrip_atom.metadata["residue_number"] == 0
2453
+
2454
+ if "insertion_code" in orig_atom.metadata:
2455
+ assert orig_atom.metadata["insertion_code"] == roundtrip_atom.metadata["insertion_code"]
2456
+ else:
2457
+ assert roundtrip_atom.metadata["insertion_code"] == 0
2458
+
2459
+ if "chain_id" in orig_atom.metadata:
2460
+ assert orig_atom.metadata["chain_id"] == roundtrip_atom.metadata["chain_id"]
2461
+ else:
2462
+ assert roundtrip_atom.metadata["chain_id"] == ""
2463
+
2464
+ def test_from_rdkit_implicit_hydrogens(self):
2465
+ """
2466
+ Test that hydrogens are inferred from hydrogen-less RDKit molecules,
2467
+ unless the option is turned off.
2468
+ """
2469
+ from rdkit import Chem
2470
+
2471
+ rdmol = Chem.MolFromSmiles("CC")
2472
+ offmol = Molecule.from_rdkit(rdmol)
2473
+
2474
+ assert any([a.atomic_number == 1 for a in offmol.atoms])
2475
+
2476
+ offmol_no_h = Molecule.from_rdkit(rdmol, hydrogens_are_explicit=True)
2477
+ assert not any([a.atomic_number == 1 for a in offmol_no_h.atoms])
2478
+
2479
+ def test_from_rdkit_radical(self):
2480
+ """Test that parsing an rdmol with a radical raises RadicalsNotSupportedError."""
2481
+ from rdkit import Chem
2482
+
2483
+ rdmol = Chem.MolFromSmiles("[CH3]")
2484
+
2485
+ with pytest.raises(RadicalsNotSupportedError):
2486
+ RDKitToolkitWrapper().from_rdkit(rdmol)
2487
+
2488
+ def test_from_rdkit_incompatible_aromaticity(self):
2489
+ """Test loading an rdmol where the aromaticity was set by a model that disagrees with MDL"""
2490
+ from rdkit import Chem
2491
+
2492
+ smi = "c2scnc2C"
2493
+ rdmol = Chem.MolFromSmiles(smi)
2494
+ Chem.SetAromaticity(rdmol, Chem.AromaticityModel.AROMATICITY_RDKIT)
2495
+ Molecule.from_rdkit(rdmol)
2496
+
2497
+ def test_from_rdkit_transition_metal_radical(self):
2498
+ """Test that parsing an rdmol with a transition metal radical works."""
2499
+ from rdkit import Chem
2500
+
2501
+ rdmol = Chem.MolFromSmiles("[Zn+2]")
2502
+
2503
+ RDKitToolkitWrapper().from_rdkit(rdmol)
2504
+
2505
+ def test_from_rdkit_multiple_molecule(self):
2506
+ """Test that parsing a rdmol that is actually multiple disconnected molecules raises a warning"""
2507
+ from rdkit import Chem
2508
+
2509
+ rdmol = Chem.MolFromSmiles("C.N")
2510
+ with pytest.warns(MultipleComponentsInMoleculeWarning, match="more than one molecule"):
2511
+ RDKitToolkitWrapper().from_rdkit(rdmol)
2512
+
2513
+ @pytest.mark.parametrize("smiles, expected_map", [("[Cl:1][Cl]", {0: 1}), ("[Cl:1][Cl:2]", {0: 1, 1: 2})])
2514
+ def test_from_rdkit_atom_map(self, smiles, expected_map):
2515
+ """
2516
+ Test OpenEyeToolkitWrapper for loading a molecule with implicit
2517
+ hydrogens (correct behavior is to add them explicitly)
2518
+ """
2519
+ from rdkit import Chem
2520
+
2521
+ off_molecule = Molecule.from_rdkit(Chem.MolFromSmiles(smiles))
2522
+ assert off_molecule.properties["atom_map"] == expected_map
2523
+
2524
+ def test_from_pathlib_path(self):
2525
+ ethanol = create_ethanol()
2526
+ with NamedTemporaryFile(suffix=".sdf") as outfile:
2527
+ filename = str(outfile.name)
2528
+ ethanol.to_file(filename, file_format="sdf")
2529
+
2530
+ toolkit = RDKitToolkitWrapper()
2531
+ toolkit.from_file(pathlib.Path(filename), file_format="sdf")
2532
+
2533
+ def test_file_extension_case(self):
2534
+ """
2535
+ Test round-trips of some file extensions when called directly from the toolkit wrappers,
2536
+ including lower- and uppercase file extensions. Note that this test does not ensure
2537
+ accuracy, it only tests that reading/writing without raising an exception.
2538
+ """
2539
+ mols_in = RDKitToolkitWrapper().from_file(
2540
+ file_path=get_data_file_path("molecules/ethanol.sdf"), file_format="sdf"
2541
+ )
2542
+
2543
+ assert len(mols_in) > 0
2544
+
2545
+ mols_in = RDKitToolkitWrapper().from_file(
2546
+ file_path=get_data_file_path("molecules/ethanol.sdf"), file_format="SDF"
2547
+ )
2548
+
2549
+ assert len(mols_in) > 0
2550
+
2551
+ def test_get_sdf_coordinates(self):
2552
+ """Test RDKitToolkitWrapper for importing a single set of coordinates from a sdf file"""
2553
+ toolkit_wrapper = RDKitToolkitWrapper()
2554
+ filename = get_data_file_path("molecules/toluene.sdf")
2555
+ molecule = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
2556
+ assert len(molecule.conformers) == 1
2557
+ assert molecule.conformers[0].shape == (15, 3)
2558
+ assert_almost_equal(molecule.conformers[0][5][1].m_as(unit.angstrom), 22.9800, decimal=4)
2559
+
2560
+ def test_read_sdf_charges(self):
2561
+ """Test RDKitToolkitWrapper for importing a charges from a sdf file"""
2562
+ toolkit_wrapper = RDKitToolkitWrapper()
2563
+ filename = get_data_file_path("molecules/ethanol_partial_charges.sdf")
2564
+ molecule = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
2565
+ assert molecule.partial_charges is not None
2566
+ assert molecule.partial_charges[0] == -0.4 * unit.elementary_charge
2567
+ assert molecule.partial_charges[-1] == 0.4 * unit.elementary_charge
2568
+
2569
+ def test_write_sdf_charges(self):
2570
+ """Test RDKitToolkitWrapper for writing partial charges to a sdf file"""
2571
+ from io import StringIO
2572
+
2573
+ toolkit_wrapper = RDKitToolkitWrapper()
2574
+ ethanol = create_ethanol()
2575
+ sio = StringIO()
2576
+ ethanol.to_file(sio, "SDF", toolkit_registry=toolkit_wrapper)
2577
+ sdf_text = sio.getvalue()
2578
+ # The output lines of interest here will look like
2579
+ # > <atom.dprop.PartialCharge> (1)
2580
+ # -0.40000000000000002 -0.29999999999999999 -0.20000000000000001 -0.10000000000000001 0.01 0.10000000000000001 0.20000000000000001 0.29999999999999999 0.40000000000000002
2581
+
2582
+ # Parse the SDF text, grabbing the numeric line above
2583
+ sdf_split = sdf_text.split("\n")
2584
+ charge_line_found = False
2585
+ for line in sdf_split:
2586
+ if charge_line_found:
2587
+ charges = [float(i) for i in line.split()]
2588
+ break
2589
+ if "> <atom.dprop.PartialCharge>" in line:
2590
+ charge_line_found = True
2591
+
2592
+ # Make sure that a charge line was ever found
2593
+ assert charge_line_found
2594
+
2595
+ # Make sure that the charges found were correct
2596
+ assert_almost_equal(charges, [-0.4, -0.3, -0.2, -0.1, 0.00001, 0.1, 0.2, 0.3, 0.4])
2597
+
2598
+ def test_sdf_properties_roundtrip(self):
2599
+ """Test RDKitToolkitWrapper for performing a round trip of a molecule with defined partial charges
2600
+ and entries in the properties dict to and from a sdf file"""
2601
+ toolkit_wrapper = RDKitToolkitWrapper()
2602
+ ethanol = create_ethanol()
2603
+ # Write ethanol to a temporary file, and then immediately read it.
2604
+ with NamedTemporaryFile(suffix=".sdf") as iofile:
2605
+ ethanol.to_file(iofile.name, file_format="SDF", toolkit_registry=toolkit_wrapper)
2606
+ ethanol2 = Molecule.from_file(iofile.name, file_format="SDF", toolkit_registry=toolkit_wrapper)
2607
+ assert (ethanol.partial_charges == ethanol2.partial_charges).all()
2608
+
2609
+ # Now test with no properties or charges
2610
+ ethanol = create_ethanol()
2611
+ ethanol.partial_charges = None
2612
+ # Write ethanol to a temporary file, and then immediately read it.
2613
+ with NamedTemporaryFile(suffix=".sdf") as iofile:
2614
+ ethanol.to_file(iofile.name, file_format="SDF", toolkit_registry=toolkit_wrapper)
2615
+ ethanol2 = Molecule.from_file(iofile.name, file_format="SDF", toolkit_registry=toolkit_wrapper)
2616
+ assert ethanol2.partial_charges is None
2617
+ assert ethanol2.properties == {}
2618
+
2619
+ def test_write_sdf_no_charges(self):
2620
+ """Test RDKitToolkitWrapper for writing an SDF file with no charges"""
2621
+ from io import StringIO
2622
+
2623
+ toolkit_wrapper = RDKitToolkitWrapper()
2624
+ ethanol = create_ethanol()
2625
+ ethanol.partial_charges = None
2626
+ sio = StringIO()
2627
+ ethanol.to_file(sio, "SDF", toolkit_registry=toolkit_wrapper)
2628
+ sdf_text = sio.getvalue()
2629
+ # In our current configuration, if the OFFMol doesn't have partial charges, we DO NOT want a partial charge
2630
+ # block to be written. For reference, it's possible to indicate that a partial charge is not known by writing
2631
+ # out "n/a" (or another placeholder) in the partial charge block atoms without charges.
2632
+ assert "> <atom.dprop.PartialCharge>" not in sdf_text
2633
+
2634
+ def test_read_ethene_sdf(self):
2635
+ """
2636
+ Test that RDKitToolkitWrapper can load an ethene molecule without complaining about bond stereo.
2637
+ See https://github.com/openforcefield/openff-toolkit/issues/785
2638
+ """
2639
+ ethene_file_path = get_data_file_path("molecules/ethene_rdkit.sdf")
2640
+ toolkit_wrapper = RDKitToolkitWrapper()
2641
+ toolkit_wrapper.from_file(ethene_file_path, file_format="sdf")
2642
+
2643
+ def test_load_multiconformer_sdf_as_separate_molecules(self):
2644
+ """
2645
+ Test RDKitToolkitWrapper for reading a "multiconformer" SDF, which the OFF
2646
+ Toolkit should treat as separate molecules
2647
+ """
2648
+ toolkit_wrapper = RDKitToolkitWrapper()
2649
+ filename = get_data_file_path("molecules/methane_multiconformer.sdf")
2650
+ molecules = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
2651
+ assert len(molecules) == 2
2652
+ assert len(molecules[0].conformers) == 1
2653
+ assert len(molecules[1].conformers) == 1
2654
+ assert molecules[0].conformers[0].shape == (5, 3)
2655
+
2656
+ def test_load_multiconformer_sdf_as_separate_molecules_properties(self):
2657
+ """
2658
+ Test RDKitToolkitWrapper for reading a "multiconformer" SDF, which the OFF
2659
+ Toolkit should treat as separate molecules
2660
+ """
2661
+ toolkit_wrapper = RDKitToolkitWrapper()
2662
+ filename = get_data_file_path("molecules/methane_multiconformer_properties.sdf")
2663
+ molecules = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
2664
+ assert len(molecules) == 2
2665
+ assert len(molecules[0].conformers) == 1
2666
+ assert len(molecules[1].conformers) == 1
2667
+ assert molecules[0].conformers[0].shape == (5, 3)
2668
+ # The first molecule in the SDF has the following properties and charges:
2669
+ assert molecules[0].properties["test_property_key"] == "test_property_value"
2670
+ np.testing.assert_allclose(
2671
+ molecules[0].partial_charges.m_as(unit.elementary_charge),
2672
+ [-0.108680, 0.027170, 0.027170, 0.027170, 0.027170],
2673
+ )
2674
+ # The second molecule in the SDF has the following properties and charges:
2675
+ assert molecules[1].properties["test_property_key"] == "test_property_value2"
2676
+ assert molecules[1].properties["another_test_property_key"] == "another_test_property_value"
2677
+ np.testing.assert_allclose(
2678
+ molecules[1].partial_charges.m_as(unit.elementary_charge),
2679
+ [0.027170, 0.027170, 0.027170, 0.027170, -0.108680],
2680
+ )
2681
+
2682
+ def test_write_multiconformer_mol_as_sdf(self):
2683
+ """
2684
+ Test RDKitToolkitWrapper for writing a multiconformer molecule to SDF. The OFF toolkit should only
2685
+ save the first conformer
2686
+ """
2687
+ from io import StringIO
2688
+
2689
+ toolkit_wrapper = RDKitToolkitWrapper()
2690
+ filename = get_data_file_path("molecules/ethanol.sdf")
2691
+ ethanol = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
2692
+ ethanol.partial_charges = Quantity(
2693
+ np.array([-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0]),
2694
+ unit.elementary_charge,
2695
+ )
2696
+ ethanol.properties["test_prop"] = "test_value"
2697
+ new_conf = ethanol.conformers[0] + (np.ones(ethanol.conformers[0].shape) * unit.angstrom)
2698
+ ethanol.add_conformer(new_conf)
2699
+ sio = StringIO()
2700
+ ethanol.to_file(sio, "sdf", toolkit_registry=toolkit_wrapper)
2701
+ data = sio.getvalue()
2702
+ # In SD format, each molecule ends with "$$$$"
2703
+ assert data.count("$$$$") == 1
2704
+ # A basic SDF for ethanol would be 27 lines, though the properties add three more
2705
+ assert len(data.split("\n")) == 30
2706
+ assert "test_prop" in data
2707
+ assert "<atom.dprop.PartialCharge>" in data
2708
+ # Ensure the first conformer's first atom's X coordinate is in the file
2709
+ assert str(ethanol.conformers[0][0][0].m_as(unit.angstrom))[:5] in data
2710
+ # Ensure the SECOND conformer's first atom's X coordinate is NOT in the file
2711
+ assert str(ethanol.conformers[1][0][0].m_as(unit.angstrom))[:5] not in data
2712
+
2713
+ def test_write_multiconformer_pdb(self):
2714
+ """
2715
+ Make sure RDKit can write multi conformer PDB files.
2716
+ """
2717
+ from io import StringIO
2718
+
2719
+ toolkit = RDKitToolkitWrapper()
2720
+ # load up a multiconformer pdb file and condense down the conformers
2721
+ molecules = Molecule.from_file(get_data_file_path("molecules/butane_multi.sdf"), toolkit_registry=toolkit)
2722
+ butane = molecules.pop(0)
2723
+ for mol in molecules:
2724
+ butane.add_conformer(mol.conformers[0])
2725
+ assert butane.n_conformers == 7
2726
+ sio = StringIO()
2727
+ butane.to_file(sio, "pdb", toolkit_registry=toolkit)
2728
+ # we need to make sure each conformer is wrote to the file
2729
+ pdb = sio.getvalue()
2730
+ for i in range(1, 8):
2731
+ assert f"MODEL {i}" in pdb
2732
+
2733
+ # Unskip this when we implement PDB-reading support for RDKitToolkitWrapper
2734
+ @pytest.mark.skip
2735
+ def test_get_pdb_coordinates(self):
2736
+ """Test RDKitToolkitWrapper for importing a single set of coordinates from a pdb file"""
2737
+ toolkit_wrapper = RDKitToolkitWrapper()
2738
+ filename = get_data_file_path("molecules/toluene.pdb")
2739
+ molecule = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
2740
+ assert len(molecule.conformers) == 1
2741
+ assert molecule.conformers[0].shape == (15, 3)
2742
+
2743
+ # Unskip this when we implement PDB-reading support for RDKitToolkitWrapper
2744
+ @pytest.mark.skip
2745
+ def test_load_aromatic_pdb(self):
2746
+ """Test OpenEyeToolkitWrapper for importing molecule conformers"""
2747
+ toolkit_wrapper = RDKitToolkitWrapper()
2748
+ filename = get_data_file_path("molecules/toluene.pdb")
2749
+ molecule = Molecule.from_file(filename, toolkit_registry=toolkit_wrapper)
2750
+ assert len(molecule.conformers) == 1
2751
+ assert molecule.conformers[0].shape == (15, 3)
2752
+
2753
+ def test_generate_conformers(self):
2754
+ """Test RDKitToolkitWrapper generate_conformers()"""
2755
+ toolkit_wrapper = RDKitToolkitWrapper()
2756
+ smiles = "[H]C([H])([H])C([H])([H])[H]"
2757
+ molecule = toolkit_wrapper.from_smiles(smiles)
2758
+ molecule.generate_conformers()
2759
+ # TODO: Make this test more robust
2760
+
2761
+ def test_generate_multiple_conformers(self):
2762
+ """Test RDKitToolkitWrapper generate_conformers() for generating multiple conformers"""
2763
+ toolkit_wrapper = RDKitToolkitWrapper()
2764
+ smiles = "CCCCCCCCCN"
2765
+ molecule = toolkit_wrapper.from_smiles(smiles)
2766
+ molecule.generate_conformers(
2767
+ rms_cutoff=1 * unit.angstrom,
2768
+ n_conformers=100,
2769
+ toolkit_registry=toolkit_wrapper,
2770
+ )
2771
+ assert molecule.n_conformers > 1
2772
+ assert not (molecule.conformers[0] == (0.0 * unit.angstrom)).all()
2773
+
2774
+ # Ensure rms_cutoff kwarg is working
2775
+ molecule2 = toolkit_wrapper.from_smiles(smiles)
2776
+ molecule2.generate_conformers(
2777
+ rms_cutoff=0.1 * unit.angstrom,
2778
+ n_conformers=100,
2779
+ toolkit_registry=toolkit_wrapper,
2780
+ )
2781
+ assert molecule2.n_conformers > molecule.n_conformers
2782
+
2783
+ # Ensure n_conformers kwarg is working
2784
+ molecule2 = toolkit_wrapper.from_smiles(smiles)
2785
+ molecule2.generate_conformers(
2786
+ rms_cutoff=0.1 * unit.angstrom,
2787
+ n_conformers=10,
2788
+ toolkit_registry=toolkit_wrapper,
2789
+ )
2790
+ assert molecule2.n_conformers == 10
2791
+
2792
+ def test_generate_conformers_failure(self):
2793
+ toolkit = RDKitToolkitWrapper()
2794
+
2795
+ molecule = Molecule.from_smiles("C(C2)(C3)1CC23C1")
2796
+
2797
+ with pytest.raises(ConformerGenerationError, match=r"RDKit conf.*fail"):
2798
+ toolkit.generate_conformers(molecule, n_conformers=1)
2799
+
2800
+ def test_generate_conformers_large_molecule(self):
2801
+ """Ensure that we don't get error caused by this molecule being too big for conf gen. See issue #882 / OpenMM #3550."""
2802
+ ql8 = Molecule.from_file(get_data_file_path("molecules/QL8.sdf"))
2803
+
2804
+ ql8.generate_conformers(
2805
+ n_conformers=1,
2806
+ toolkit_registry=RDKitToolkitWrapper(),
2807
+ )
2808
+
2809
+ @pytest.mark.parametrize("partial_charge_method", ["mmff94", "gasteiger"])
2810
+ def test_assign_partial_charges_neutral(self, partial_charge_method):
2811
+ """Test RDKitToolkitWrapper assign_partial_charges()"""
2812
+
2813
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper])
2814
+ # TODO: create_ethanol should be replaced by a function scope fixture.
2815
+ molecule = create_ethanol()
2816
+ molecule.assign_partial_charges(
2817
+ toolkit_registry=toolkit_registry,
2818
+ partial_charge_method=partial_charge_method,
2819
+ # the partial charges returned by this method already have no rounding errors that require normalization
2820
+ # so this is just testing that the kwarg remains accessible
2821
+ normalize_partial_charges=False,
2822
+ )
2823
+ charge_sum = np.sum(molecule.partial_charges)
2824
+ assert 1.0e-10 > abs(charge_sum.m_as(unit.elementary_charge))
2825
+
2826
+ @pytest.mark.parametrize("partial_charge_method", ["mmff94", "gasteiger"])
2827
+ def test_assign_partial_charges_net_charge(self, partial_charge_method):
2828
+ """
2829
+ Test RDKitToolkitWrapper assign_partial_charges() on a molecule with net charge.
2830
+ """
2831
+
2832
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper])
2833
+ # TODO: create_acetate should be replaced by a function scope fixture.
2834
+ molecule = create_acetate()
2835
+ molecule.assign_partial_charges(
2836
+ toolkit_registry=toolkit_registry,
2837
+ partial_charge_method=partial_charge_method,
2838
+ )
2839
+ charge_sum = np.sum(molecule.partial_charges)
2840
+ assert 1.0e-10 > abs(charge_sum.m_as(unit.elementary_charge) + 1.0)
2841
+
2842
+ def test_assign_partial_charges_bad_charge_method(self):
2843
+ """Test RDKitToolkitWrapper assign_partial_charges() for a nonexistent charge method"""
2844
+
2845
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper])
2846
+ molecule = create_ethanol()
2847
+
2848
+ # Molecule.assign_partial_charges calls the ToolkitRegistry with raise_exception_types = [],
2849
+ # which means it will only ever return ValueError
2850
+ with pytest.raises(ValueError, match="is not available from RDKitToolkitWrapper"):
2851
+ molecule.assign_partial_charges(
2852
+ toolkit_registry=toolkit_registry,
2853
+ partial_charge_method="NotARealChargeMethod",
2854
+ )
2855
+
2856
+ # ToolkitWrappers raise a specific exception class, so we test that here
2857
+ with pytest.raises(
2858
+ ChargeMethodUnavailableError,
2859
+ match="is not available from RDKitToolkitWrapper",
2860
+ ):
2861
+ RDTKW = RDKitToolkitWrapper()
2862
+ RDTKW.assign_partial_charges(molecule=molecule, partial_charge_method="NotARealChargeMethod")
2863
+
2864
+ def test_elf_is_problematic_conformer_acid(self, formic_acid_molecule, formic_acid_conformers):
2865
+ problematic, reason = RDKitToolkitWrapper._elf_is_problematic_conformer(
2866
+ formic_acid_molecule, formic_acid_conformers["cis"]
2867
+ )
2868
+ assert not problematic
2869
+ assert reason is None
2870
+
2871
+ problematic, reason = RDKitToolkitWrapper._elf_is_problematic_conformer(
2872
+ formic_acid_molecule, formic_acid_conformers["trans"]
2873
+ )
2874
+ assert problematic
2875
+ assert reason is not None
2876
+
2877
+ def test_elf_prune_problematic_conformers_acid(self, formic_acid_molecule, formic_acid_conformers):
2878
+ formic_acid_molecule._conformers = [*formic_acid_conformers.values()]
2879
+
2880
+ pruned_conformers = RDKitToolkitWrapper._elf_prune_problematic_conformers(formic_acid_molecule)
2881
+
2882
+ assert len(pruned_conformers) == 1
2883
+ assert np.allclose(
2884
+ formic_acid_conformers["cis"].m_as(unit.angstrom),
2885
+ pruned_conformers[0].m_as(unit.angstrom),
2886
+ )
2887
+
2888
+ def test_elf_compute_electrostatic_energy(self, formic_acid_molecule: Molecule):
2889
+ """Test the computation of the ELF electrostatic energy function."""
2890
+
2891
+ # Set some partial charges and a dummy conformer with values which make
2892
+ # computing the expected energy by hand easier.
2893
+ formic_acid_molecule.partial_charges = np.ones(formic_acid_molecule.n_atoms) * 1.0 * unit.elementary_charge
2894
+
2895
+ formic_acid_molecule.partial_charges[0] *= 2.0
2896
+ formic_acid_molecule.partial_charges[4] *= 3.0
2897
+
2898
+ conformer = np.array(
2899
+ [
2900
+ [1.0, 0.0, 0.0],
2901
+ [0.0, 0.0, 0.0],
2902
+ [-1.0, 0.0, 0.0],
2903
+ [0.0, 1.0, 0.0],
2904
+ [0.0, -1.0, 0.0],
2905
+ ]
2906
+ )
2907
+
2908
+ # Compute the conformers electrostatic energy.
2909
+ computed_energy = RDKitToolkitWrapper._elf_compute_electrostatic_energy(
2910
+ formic_acid_molecule, conformer * unit.angstrom
2911
+ )
2912
+ # q_O1 * q_H2 / d_O1,H2 + q_H1 * q_H2 / d_H1,H2
2913
+ expected_energy = 2.0 * 3.0 / np.sqrt(2.0) + 1.0 * 3.0 / 2.0
2914
+
2915
+ assert np.isclose(computed_energy, expected_energy)
2916
+
2917
+ def test_elf_compute_rms_matrix(self, formic_acid_molecule: Molecule):
2918
+ """Test the computation of the ELF conformer RMS matrix."""
2919
+ formic_acid_molecule.add_conformer(_rng.random((5, 3)) * unit.angstrom)
2920
+ formic_acid_molecule.add_conformer(_rng.random((5, 3)) * unit.angstrom)
2921
+
2922
+ rms_matrix = RDKitToolkitWrapper._elf_compute_rms_matrix(formic_acid_molecule)
2923
+
2924
+ assert rms_matrix.shape == (2, 2)
2925
+
2926
+ assert np.isclose(rms_matrix[0, 0], 0.0)
2927
+ assert np.isclose(rms_matrix[1, 1], 0.0)
2928
+
2929
+ assert np.isclose(rms_matrix[0, 1], rms_matrix[1, 0])
2930
+ assert not np.isclose(rms_matrix[0, 1], 0.0)
2931
+
2932
+ def test_elf_compute_rms_matrix_symmetry(self):
2933
+ """Test the computation of the ELF conformer RMS matrix for matrices which
2934
+ contain symmetry."""
2935
+
2936
+ # Create a molecule which can have two different automorphs.
2937
+ n_methyl_aniline: Molecule = Molecule.from_smiles("CNc1ccccc1")
2938
+ n_methyl_aniline.generate_conformers(n_conformers=1)
2939
+
2940
+ # Add a second conformer with the benzene ring flipped 180
2941
+ original_conformer = n_methyl_aniline.conformers[0].m_as(unit.angstrom)
2942
+
2943
+ ring_atoms = RDKitToolkitWrapper().find_smarts_matches(
2944
+ n_methyl_aniline,
2945
+ "[#6]-[#7](-[#6]1:[#6:1](-[#1:2]):[#6:3](-[#1:4]):[#6]:[#6:6](-[#1:5]):[#6:8](-[#1:7])1)",
2946
+ )[0]
2947
+
2948
+ flipped_conformer = np.copy(original_conformer)
2949
+
2950
+ for i in range(8):
2951
+ flipped_conformer[ring_atoms[i], :] = original_conformer[ring_atoms[7 - i]]
2952
+
2953
+ n_methyl_aniline.add_conformer(flipped_conformer * unit.angstrom)
2954
+
2955
+ # Compute the RMS matrix.
2956
+ rms_matrix = RDKitToolkitWrapper._elf_compute_rms_matrix(n_methyl_aniline)
2957
+
2958
+ assert rms_matrix.shape == (2, 2)
2959
+ assert np.allclose(rms_matrix, 0.0, atol=1e-7)
2960
+
2961
+ @pytest.mark.parametrize(
2962
+ "expected_conformer_map, rms_tolerance",
2963
+ [({0: 0, 1: 2}, 0.001 * unit.angstrom), ({0: 0}, 100.0 * unit.angstrom)],
2964
+ )
2965
+ def test_elf_select_diverse_conformers(
2966
+ self,
2967
+ formic_acid_molecule: Molecule,
2968
+ expected_conformer_map: dict[int, int],
2969
+ rms_tolerance: Quantity,
2970
+ ):
2971
+ """Test the greedy selection of 'diverse' ELF conformers."""
2972
+
2973
+ formic_acid_molecule.add_conformer(_rng.random((5, 3)) * unit.angstrom)
2974
+ formic_acid_molecule.add_conformer(formic_acid_molecule.conformers[0] * 1.1)
2975
+ formic_acid_molecule.add_conformer(formic_acid_molecule.conformers[0] * 1.2)
2976
+
2977
+ conformers = RDKitToolkitWrapper._elf_select_diverse_conformers(
2978
+ formic_acid_molecule, formic_acid_molecule.conformers, 2, rms_tolerance
2979
+ )
2980
+
2981
+ assert len(conformers) == len(expected_conformer_map)
2982
+
2983
+ for elf_index, original_index in expected_conformer_map.items():
2984
+ assert np.allclose(
2985
+ conformers[elf_index].m_as(unit.angstrom),
2986
+ formic_acid_molecule.conformers[original_index].m_as(unit.angstrom),
2987
+ )
2988
+
2989
+ def test_apply_elf_conformer_selection(self):
2990
+ """Test applying the ELF10 method."""
2991
+
2992
+ toolkit = RDKitToolkitWrapper()
2993
+
2994
+ molecule = Molecule.from_file(
2995
+ get_data_file_path(os.path.join("molecules", "z_3_hydroxy_propenal.sdf")),
2996
+ "SDF",
2997
+ )
2998
+
2999
+ # Test that the simple case of no conformers does not yield an exception.
3000
+ toolkit.apply_elf_conformer_selection(molecule)
3001
+
3002
+ initial_conformers = [
3003
+ # Add a conformer with an internal H-bond.
3004
+ Quantity(
3005
+ np.array(
3006
+ [
3007
+ [0.5477, 0.3297, -0.0621],
3008
+ [-0.1168, -0.7881, 0.2329],
3009
+ [-1.4803, -0.8771, 0.1667],
3010
+ [-0.2158, 1.5206, -0.4772],
3011
+ [-1.4382, 1.5111, -0.5580],
3012
+ [1.6274, 0.3962, -0.0089],
3013
+ [0.3388, -1.7170, 0.5467],
3014
+ [-1.8612, -0.0347, -0.1160],
3015
+ [0.3747, 2.4222, -0.7115],
3016
+ ]
3017
+ ),
3018
+ unit.angstrom,
3019
+ ),
3020
+ # Add a conformer without an internal H-bond.
3021
+ Quantity(
3022
+ np.array(
3023
+ [
3024
+ [0.5477, 0.3297, -0.0621],
3025
+ [-0.1168, -0.7881, 0.2329],
3026
+ [-1.4803, -0.8771, 0.1667],
3027
+ [-0.2158, 1.5206, -0.4772],
3028
+ [0.3353, 2.5772, -0.7614],
3029
+ [1.6274, 0.3962, -0.0089],
3030
+ [0.3388, -1.7170, 0.5467],
3031
+ [-1.7743, -1.7634, 0.4166],
3032
+ [-1.3122, 1.4082, -0.5180],
3033
+ ]
3034
+ ),
3035
+ unit.angstrom,
3036
+ ),
3037
+ ]
3038
+
3039
+ molecule._conformers = [*initial_conformers]
3040
+
3041
+ # Apply ELF10
3042
+ toolkit.apply_elf_conformer_selection(molecule)
3043
+ elf10_conformers = molecule.conformers
3044
+
3045
+ assert len(elf10_conformers) == 1
3046
+
3047
+ assert np.allclose(
3048
+ elf10_conformers[0].m_as(unit.angstrom),
3049
+ initial_conformers[1].m_as(unit.angstrom),
3050
+ )
3051
+
3052
+ def test_apply_elf_conformer_selection_acid(self, formic_acid_molecule, formic_acid_conformers, caplog):
3053
+ """Test applying the ELF10 method."""
3054
+
3055
+ toolkit = RDKitToolkitWrapper()
3056
+
3057
+ # Add the conformers to the molecule and apply ELF.
3058
+ formic_acid_molecule._conformers = [
3059
+ formic_acid_conformers["trans"],
3060
+ formic_acid_conformers["cis"],
3061
+ ]
3062
+
3063
+ # Only the CIS conformer should remain after pruning and a warning raised to
3064
+ # explain why the conformer was discarded.
3065
+ with caplog.at_level(logging.WARNING):
3066
+ toolkit.apply_elf_conformer_selection(formic_acid_molecule)
3067
+
3068
+ assert formic_acid_molecule.n_conformers == 1
3069
+ assert "Discarding conformer 0" in caplog.text
3070
+ assert "Molecules which contain COOH functional groups in a" in caplog.text
3071
+
3072
+ assert np.allclose(
3073
+ formic_acid_molecule.conformers[0].m_as(unit.angstrom),
3074
+ formic_acid_conformers["cis"].m_as(unit.angstrom),
3075
+ )
3076
+
3077
+ # Check that an exception is raised if no conformers remain after removing the
3078
+ # trans conformer.
3079
+ formic_acid_molecule._conformers = [formic_acid_conformers["trans"]]
3080
+
3081
+ with pytest.raises(ValueError) as error_info:
3082
+ toolkit.apply_elf_conformer_selection(formic_acid_molecule)
3083
+
3084
+ assert "There were no conformers to select from after discarding conformers" in str(error_info.value)
3085
+
3086
+ def test_find_rotatable_bonds(self):
3087
+ """Test finding rotatable bonds while ignoring some groups"""
3088
+
3089
+ # test a simple molecule
3090
+ ethanol = create_ethanol()
3091
+ bonds = ethanol.find_rotatable_bonds()
3092
+ assert len(bonds) == 2
3093
+ for bond in bonds:
3094
+ assert ethanol.atoms[bond.atom1_index].atomic_number != 1
3095
+ assert ethanol.atoms[bond.atom2_index].atomic_number != 1
3096
+
3097
+ # now ignore the C-O bond, forwards
3098
+ bonds = ethanol.find_rotatable_bonds(ignore_functional_groups="[#6:1]-[#8:2]")
3099
+ assert len(bonds) == 1
3100
+ assert ethanol.atoms[bonds[0].atom1_index].atomic_number == 6
3101
+ assert ethanol.atoms[bonds[0].atom2_index].atomic_number == 6
3102
+
3103
+ # now ignore the O-C bond, backwards
3104
+ bonds = ethanol.find_rotatable_bonds(ignore_functional_groups="[#8:1]-[#6:2]")
3105
+ assert len(bonds) == 1
3106
+ assert ethanol.atoms[bonds[0].atom1_index].atomic_number == 6
3107
+ assert ethanol.atoms[bonds[0].atom2_index].atomic_number == 6
3108
+
3109
+ # now ignore the C-C bond
3110
+ bonds = ethanol.find_rotatable_bonds(ignore_functional_groups="[#6:1]-[#6:2]")
3111
+ assert len(bonds) == 1
3112
+ assert ethanol.atoms[bonds[0].atom1_index].atomic_number == 6
3113
+ assert ethanol.atoms[bonds[0].atom2_index].atomic_number == 8
3114
+
3115
+ # ignore a list of searches, forward
3116
+ bonds = ethanol.find_rotatable_bonds(ignore_functional_groups=["[#6:1]-[#8:2]", "[#6:1]-[#6:2]"])
3117
+ assert bonds == []
3118
+
3119
+ # ignore a list of searches, backwards
3120
+ bonds = ethanol.find_rotatable_bonds(ignore_functional_groups=["[#6:1]-[#6:2]", "[#8:1]-[#6:2]"])
3121
+ assert bonds == []
3122
+
3123
+ # test molecules that should have no rotatable bonds
3124
+ cyclohexane = create_cyclohexane()
3125
+ bonds = cyclohexane.find_rotatable_bonds()
3126
+ assert bonds == []
3127
+
3128
+ methane = Molecule.from_smiles("C")
3129
+ bonds = methane.find_rotatable_bonds()
3130
+ assert bonds == []
3131
+
3132
+ ethene = Molecule.from_smiles("C=C")
3133
+ bonds = ethene.find_rotatable_bonds()
3134
+ assert bonds == []
3135
+
3136
+ terminal_forwards = "[*]~[*:1]-[X2H1,X3H2,X4H3:2]-[#1]"
3137
+ terminal_backwards = "[#1]-[X2H1,X3H2,X4H3:1]-[*:2]~[*]"
3138
+ # test removing terminal rotors
3139
+ toluene = Molecule.from_file(get_data_file_path("molecules/toluene.sdf"))
3140
+ bonds = toluene.find_rotatable_bonds()
3141
+ assert len(bonds) == 1
3142
+ assert toluene.atoms[bonds[0].atom1_index].atomic_number == 6
3143
+ assert toluene.atoms[bonds[0].atom2_index].atomic_number == 6
3144
+
3145
+ # find terminal bonds forward
3146
+ bonds = toluene.find_rotatable_bonds(ignore_functional_groups=terminal_forwards)
3147
+ assert bonds == []
3148
+
3149
+ # find terminal bonds backwards
3150
+ bonds = toluene.find_rotatable_bonds(ignore_functional_groups=terminal_backwards)
3151
+ assert bonds == []
3152
+
3153
+ @pytest.mark.parametrize(
3154
+ ("smiles", "n_atom_rings", "n_bond_rings"),
3155
+ [
3156
+ ("c1ccc2ccccc2c1", 10, 11),
3157
+ ("c1ccc(cc1)c2ccccc2", 12, 12),
3158
+ ("Cc1ccc(cc1Nc2nccc(n2)c3cccnc3)NC(=O)c4ccc(cc4)CN5CCN(CC5)C", 30, 30),
3159
+ ],
3160
+ )
3161
+ def test_is_in_ring(self, smiles, n_atom_rings, n_bond_rings):
3162
+ """Test Atom.is_in_ring and Bond.is_in_ring"""
3163
+ mol = Molecule.from_smiles(smiles)
3164
+
3165
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper()])
3166
+
3167
+ atoms_in_ring = [atom for atom in mol.atoms if atom.is_in_ring(toolkit_registry=toolkit_registry)]
3168
+
3169
+ bonds_in_ring = [bond for bond in mol.bonds if bond.is_in_ring(toolkit_registry=toolkit_registry)]
3170
+
3171
+ assert len(atoms_in_ring) == n_atom_rings
3172
+ assert len(bonds_in_ring) == n_bond_rings
3173
+
3174
+ def test_central_biphenyl_bond(self):
3175
+ """Test that `Bond.is_in_ring` is False for the central bond in a phenyl"""
3176
+ # Use a mapped smiles to ensure atom order while looking up central bond
3177
+ # Generated via Molecule.from_smiles("c1ccc(cc1)c2ccccc2").to_smiles(mapped=True)
3178
+
3179
+ biphenyl = Molecule.from_mapped_smiles(
3180
+ "[H:13][c:1]1[c:2]([c:3]([c:4]([c:5]([c:6]1[H:17])[H:16])[c:7]2[c:8]([c:9]([c:10]"
3181
+ "([c:11]([c:12]2[H:22])[H:21])[H:20])[H:19])[H:18])[H:15])[H:14]"
3182
+ )
3183
+
3184
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper()])
3185
+
3186
+ this_bond = biphenyl.get_bond_between(3, 6)
3187
+ assert this_bond.is_in_ring(toolkit_registry=toolkit_registry) is False
3188
+
3189
+ ring_bonds = [b for b in biphenyl.bonds if b.is_in_ring(toolkit_registry=toolkit_registry)]
3190
+ assert len(ring_bonds) == 12
3191
+
3192
+ def test_unattached_is_in_ring(self):
3193
+ toolkit = RDKitToolkitWrapper()
3194
+ dummy_atom = Atom(1, 0, False)
3195
+
3196
+ with pytest.raises(NotAttachedToMoleculeError, match="Atom"):
3197
+ toolkit.atom_is_in_ring(dummy_atom)
3198
+
3199
+ # The Bond constructor checks to see that the atoms are in a molecule,
3200
+ # so not so straightforward to make one from the constructor
3201
+ dummy_bond = Molecule.from_smiles("O").bonds[0]
3202
+ dummy_bond._molecule = None
3203
+
3204
+ with pytest.raises(NotAttachedToMoleculeError, match="Bond"):
3205
+ toolkit.bond_is_in_ring(dummy_bond)
3206
+
3207
+ def test_find_matches_unique(self):
3208
+ """Test the expected behavior of the `unique` argument in find_matches"""
3209
+ smirks = "[C:1]~[C:2]~[C:3]"
3210
+ tk = RDKitToolkitWrapper()
3211
+
3212
+ mol = Molecule.from_smiles("CCC")
3213
+
3214
+ assert len(tk.find_smarts_matches(mol, smirks, unique=True)) == 1
3215
+ assert len(tk.find_smarts_matches(mol, smirks, unique=False)) == 2
3216
+
3217
+ def test_find_matches_bad_smarts(self):
3218
+ with pytest.raises(
3219
+ ChemicalEnvironmentParsingError,
3220
+ match="foobar",
3221
+ ):
3222
+ RDKitToolkitWrapper().find_smarts_matches(
3223
+ create_ethanol(),
3224
+ smarts="foobar",
3225
+ )
3226
+
3227
+ def test_to_rdkit_losing_aromaticity_(self):
3228
+ # test the example given in issue #513
3229
+ # <https://github.com/openforcefield/openff-toolkit/issues/513>
3230
+ smiles = (
3231
+ "[H]c1c(c(c(c(c1OC2=C(C(=C(N3C2=C(C(=C3[H])C#N)[H])[H])F)[H])OC([H])([H])C([H])([H])"
3232
+ "N4C(=C(C(=O)N(C4=O)[H])[H])[H])[H])F)[H]"
3233
+ )
3234
+
3235
+ mol = Molecule.from_smiles(smiles)
3236
+ rdmol = mol.to_rdkit()
3237
+
3238
+ # now make sure the aromaticity matches for each atom
3239
+ for offatom, rdatom in zip(mol.atoms, rdmol.GetAtoms()):
3240
+ assert offatom.is_aromatic is rdatom.GetIsAromatic()
3241
+
3242
+ def test_to_rdkit_str_resnum(self):
3243
+ smiles = "O"
3244
+
3245
+ mol = Molecule.from_smiles(smiles)
3246
+
3247
+ # Test an int, a string that can convert to an int, and a non-intable str
3248
+ atom_resnums = [9998, "9999", "A000"]
3249
+ # RDKit's default residue number is 0
3250
+ expected_atom_resnums = [9998, 9999, 0]
3251
+
3252
+ for atom, resnum in zip(mol.atoms, atom_resnums):
3253
+ atom.metadata["residue_number"] = resnum
3254
+ atom.metadata["residue_name"] = "HOH"
3255
+
3256
+ rdmol = mol.to_rdkit()
3257
+
3258
+ # now make sure the residue number matches for each atom
3259
+ for resnum, rdatom in zip(expected_atom_resnums, rdmol.GetAtoms()):
3260
+ assert rdatom.GetPDBResidueInfo().GetResidueNumber() == resnum
3261
+
3262
+ @pytest.mark.slow
3263
+ def test_max_substructure_matches_can_handle_large_molecule(self):
3264
+ """Test RDKitToolkitWrapper substructure search handles more than the default of maxMatches = 1000
3265
+ See https://github.com/openforcefield/openff-toolkit/pull/509 .
3266
+ """
3267
+ tk = RDKitToolkitWrapper()
3268
+ smiles = "C" * 3000
3269
+ molecule = tk.from_smiles(smiles)
3270
+ query = "[C:1]~[C:2]"
3271
+ ret = molecule.chemical_environment_matches(query, toolkit_registry=tk)
3272
+ assert len(ret) == 5998
3273
+ assert len(ret[0]) == 2
3274
+
3275
+ # TODO: Add test for higher bonds orders
3276
+ # TODO: Add test for aromaticity
3277
+ # TODO: Add test and molecule functionality for isotopes
3278
+ # TODO: Add read tests for MOL/SDF, SMI
3279
+ # TODO: Add read tests fpr multi-SMI files
3280
+ # TODO: Add read tests for both files and file-like objects
3281
+ # TODO: Add read/write tests for gzipped files
3282
+ # TODO: Add write tests for all formats
3283
+
3284
+ def test_charge_method_api_continuity(self):
3285
+ """Test rough continuity of RDKitToolkitWrapper.SUPPORTED_CHARGE_METHODS"""
3286
+ assert isinstance(RDKitToolkitWrapper.SUPPORTED_CHARGE_METHODS, set)
3287
+
3288
+ assert "mmff94" in RDKitToolkitWrapper.SUPPORTED_CHARGE_METHODS
3289
+ assert "gasteiger" in RDKitToolkitWrapper.SUPPORTED_CHARGE_METHODS
3290
+
3291
+
3292
+ @requires_ambertools
3293
+ @requires_rdkit
3294
+ class TestAmberToolsToolkitWrapper:
3295
+ """Test the AmberToolsToolkitWrapper"""
3296
+
3297
+ def test_supported_charge_methods(self):
3298
+ methods = AmberToolsToolkitWrapper().supported_charge_methods
3299
+
3300
+ assert "gasteiger" in methods
3301
+ assert "am1bcc" in methods
3302
+ assert "am1-mulliken" in methods
3303
+
3304
+ assert "zeros" not in methods
3305
+ assert "formal_charge" not in methods
3306
+ assert "mmff94" not in methods
3307
+ assert "am1bccelf10" not in methods
3308
+
3309
+ def test_assign_partial_charges_am1bcc(self):
3310
+ """Test AmberToolsToolkitWrapper assign_partial_charges() with am1bcc"""
3311
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3312
+ molecule = create_ethanol()
3313
+ molecule.assign_partial_charges(partial_charge_method="am1bcc", toolkit_registry=toolkit_registry)
3314
+ charge_sum = np.sum(molecule.partial_charges)
3315
+ abs_charge_sum = np.sum(abs(molecule.partial_charges))
3316
+
3317
+ assert abs(charge_sum) < 1e-10 * unit.elementary_charge
3318
+ assert abs_charge_sum > 0.25 * unit.elementary_charge
3319
+
3320
+ def test_assign_partial_charges_am1bcc_no_normalization(self):
3321
+ """Test AmberToolsToolkitWrapper assign_partial_charges() with am1bcc, with
3322
+ normalize_partial_charges=False"""
3323
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3324
+ # Use a cyclic N3H3 molecule since this is likely to produce a rounding error
3325
+ # Antechamber outputs 6 digits after the decimal in charges.txt, so I (Jeff) don't know
3326
+ # why this N3H3 molecule ends up with an error of 1e-3, but it's the smallest reproducing
3327
+ # case of this that I could find.
3328
+ molecule = create_cyclic_n3h3()
3329
+ molecule.assign_partial_charges(
3330
+ partial_charge_method="am1bcc",
3331
+ toolkit_registry=toolkit_registry,
3332
+ normalize_partial_charges=False,
3333
+ )
3334
+
3335
+ charge_sum = np.sum(molecule.partial_charges)
3336
+ abs_charge_sum = np.sum(abs(molecule.partial_charges))
3337
+
3338
+ # Rounding error should be on the order of 1e-3
3339
+ assert 1e-2 > abs(charge_sum.m_as(unit.elementary_charge)) > 1e-4
3340
+ assert abs_charge_sum > 0.25 * unit.elementary_charge
3341
+
3342
+ def test_assign_partial_charges_am1bcc_net_charge(self):
3343
+ """Test AmberToolsToolkitWrapper assign_partial_charges() on a molecule with a net -1 charge"""
3344
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3345
+ molecule = create_acetate()
3346
+ molecule.assign_partial_charges(partial_charge_method="am1bcc", toolkit_registry=toolkit_registry)
3347
+ charge_sum = np.sum(molecule.partial_charges)
3348
+ assert 1e-10 > abs(charge_sum.m_as(unit.elementary_charge) + 1)
3349
+
3350
+ def test_assign_partial_charges_am1bcc_thread_safe(self):
3351
+ """
3352
+ Test that AmberToolsToolkitWrapper assign_partial_charges() is thread-safe
3353
+ See https://github.com/openforcefield/openff-toolkit/issues/1642
3354
+ """
3355
+ from concurrent.futures import ThreadPoolExecutor
3356
+
3357
+ def charge_func(run_num=-1):
3358
+ from openff.toolkit import AmberToolsToolkitWrapper, Molecule
3359
+
3360
+ AmberToolsToolkitWrapper().assign_partial_charges(Molecule.from_smiles("CCO"))
3361
+
3362
+ futures = list()
3363
+ with ThreadPoolExecutor() as executor:
3364
+ for i in range(5):
3365
+ futures.append(executor.submit(charge_func, i))
3366
+ for future in futures:
3367
+ future.result()
3368
+
3369
+ def test_assign_partial_charges_am1bcc_wrong_n_confs(self):
3370
+ """
3371
+ Test AmberToolsToolkitWrapper assign_partial_charges() with am1bcc when requesting to use an incorrect number
3372
+ of conformers
3373
+ """
3374
+
3375
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3376
+ molecule = create_ethanol()
3377
+ molecule.generate_conformers(n_conformers=2, rms_cutoff=0.01 * unit.angstrom)
3378
+
3379
+ # Try passing in the incorrect number of confs, but without specifying strict_n_conformers,
3380
+ # which should produce a warning
3381
+ with pytest.warns(
3382
+ IncorrectNumConformersWarning,
3383
+ match=r"has 2 conformers, but charge method 'am1bcc' expects exactly 1.",
3384
+ ):
3385
+ molecule.assign_partial_charges(
3386
+ partial_charge_method="am1bcc",
3387
+ toolkit_registry=toolkit_registry,
3388
+ use_conformers=molecule.conformers,
3389
+ strict_n_conformers=False,
3390
+ )
3391
+
3392
+ # Try again, with strict_n_confs as true, but not including use_confs, so the
3393
+ # recommended number of confs will be generated
3394
+ molecule.assign_partial_charges(
3395
+ partial_charge_method="am1bcc",
3396
+ toolkit_registry=toolkit_registry,
3397
+ strict_n_conformers=True,
3398
+ )
3399
+
3400
+ # Test calling the ToolkitWrapper _indirectly_, though the Molecule API,
3401
+ # which should raise the first error encountered
3402
+ with pytest.raises(
3403
+ ValueError,
3404
+ match=r"has 2 conformers, but charge method 'am1bcc' expects exactly 1.",
3405
+ ):
3406
+ molecule.assign_partial_charges(
3407
+ partial_charge_method="am1bcc",
3408
+ toolkit_registry=toolkit_registry,
3409
+ use_conformers=molecule.conformers,
3410
+ strict_n_conformers=True,
3411
+ )
3412
+
3413
+ # Test calling the ToolkitWrapper _indirectly_, though a ToolkitRegistry,
3414
+ # specifying raise_exception_types=[]
3415
+ # which should aggregate any exceptions and bundle all of the messages
3416
+ # in a failed task together in a single ValueError.
3417
+ with pytest.raises(
3418
+ ValueError,
3419
+ match=r"has 2 conformers, but charge method 'am1bcc' expects exactly 1.",
3420
+ ):
3421
+ toolkit_registry.call(
3422
+ "assign_partial_charges",
3423
+ partial_charge_method="am1bcc",
3424
+ molecule=molecule,
3425
+ use_conformers=molecule.conformers,
3426
+ strict_n_conformers=True,
3427
+ raise_exception_types=[],
3428
+ )
3429
+
3430
+ # Test calling the ToolkitWrapper _directly_, passing in the incorrect number of
3431
+ # confs, and specify strict_n_conformers, which should produce an IncorrectNumConformersError
3432
+ with pytest.raises(
3433
+ IncorrectNumConformersError,
3434
+ match=r"has 2 conformers, but charge method 'am1bcc' expects exactly 1.",
3435
+ ):
3436
+ ATTKW = AmberToolsToolkitWrapper()
3437
+ ATTKW.assign_partial_charges(
3438
+ partial_charge_method="am1bcc",
3439
+ molecule=molecule,
3440
+ use_conformers=molecule.conformers,
3441
+ strict_n_conformers=True,
3442
+ )
3443
+
3444
+ @pytest.mark.parametrize("partial_charge_method", ["am1bcc", "am1-mulliken", "gasteiger"])
3445
+ def test_assign_partial_charges_neutral(self, partial_charge_method):
3446
+ """Test AmberToolsToolkitWrapper assign_partial_charges()"""
3447
+
3448
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3449
+ molecule = create_ethanol()
3450
+ molecule.assign_partial_charges(
3451
+ toolkit_registry=toolkit_registry,
3452
+ partial_charge_method=partial_charge_method,
3453
+ )
3454
+ charge_sum = np.sum(molecule.partial_charges)
3455
+ assert 1e-10 > charge_sum.m_as(unit.elementary_charge)
3456
+
3457
+ @pytest.mark.xfail(strict=False)
3458
+ @pytest.mark.parametrize("partial_charge_method", ["am1bcc", "am1-mulliken"])
3459
+ def test_assign_partial_charges_conformer_dependence(self, partial_charge_method):
3460
+ """Test AmberToolsToolkitWrapper assign_partial_charges()'s use_conformers kwarg
3461
+ to ensure charges are really conformer dependent. Skip Gasteiger because it isn't
3462
+ conformer dependent."""
3463
+ import copy
3464
+
3465
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3466
+ molecule = create_ethanol()
3467
+ molecule.generate_conformers(n_conformers=1)
3468
+ molecule.assign_partial_charges(
3469
+ toolkit_registry=toolkit_registry,
3470
+ partial_charge_method=partial_charge_method,
3471
+ use_conformers=molecule.conformers,
3472
+ )
3473
+ pcs1 = copy.deepcopy(molecule.partial_charges)
3474
+ # This test case needs a pretty extreme coordinate change since ambertools only
3475
+ # stores partial charges to 1e-3
3476
+ molecule._conformers[0][0][0] += 3.0 * unit.angstrom
3477
+ molecule._conformers[0][1][1] += 3.0 * unit.angstrom
3478
+ molecule.assign_partial_charges(
3479
+ toolkit_registry=toolkit_registry,
3480
+ partial_charge_method=partial_charge_method,
3481
+ use_conformers=molecule.conformers,
3482
+ )
3483
+ for pc1, pc2 in zip(pcs1, molecule.partial_charges):
3484
+ assert abs(pc1 - pc2) > 1.0e-3 * unit.elementary_charge
3485
+
3486
+ @pytest.mark.parametrize("partial_charge_method", ["am1bcc", "am1-mulliken", "gasteiger"])
3487
+ def test_assign_partial_charges_net_charge(self, partial_charge_method):
3488
+ """
3489
+ Test AmberToolsToolkitWrapper assign_partial_charges().
3490
+ """
3491
+
3492
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3493
+ molecule = create_acetate()
3494
+ molecule.assign_partial_charges(
3495
+ toolkit_registry=toolkit_registry,
3496
+ partial_charge_method=partial_charge_method,
3497
+ )
3498
+ charge_sum = np.sum(molecule.partial_charges)
3499
+ assert 1e-10 > abs(charge_sum.m_as(unit.elementary_charge) + 1)
3500
+
3501
+ def test_assign_partial_charges_bad_charge_method(self):
3502
+ """Test AmberToolsToolkitWrapper assign_partial_charges() for a nonexistent charge method"""
3503
+
3504
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3505
+ molecule = create_ethanol()
3506
+
3507
+ # For now, ToolkitRegistries lose track of what exception type
3508
+ # was thrown inside them, so we just check for a ValueError here
3509
+ with pytest.raises(ValueError, match="is not available from AmberToolsToolkitWrapper"):
3510
+ molecule.assign_partial_charges(
3511
+ toolkit_registry=toolkit_registry,
3512
+ partial_charge_method="NotARealChargeMethod",
3513
+ )
3514
+
3515
+ # ToolkitWrappers raise a specific exception class, so we test that here
3516
+ with pytest.raises(
3517
+ ChargeMethodUnavailableError,
3518
+ match="is not available from AmberToolsToolkitWrapper",
3519
+ ):
3520
+ ATTKW = AmberToolsToolkitWrapper()
3521
+ ATTKW.assign_partial_charges(molecule=molecule, partial_charge_method="NotARealChargeMethod")
3522
+
3523
+ @pytest.mark.parametrize(
3524
+ "partial_charge_method, expected_n_confs, toolkit_wrappers",
3525
+ [
3526
+ ("am1bcc", 1, [AmberToolsToolkitWrapper, RDKitToolkitWrapper]),
3527
+ ("am1-mulliken", 1, [AmberToolsToolkitWrapper, RDKitToolkitWrapper]),
3528
+ ("gasteiger", 0, [AmberToolsToolkitWrapper]),
3529
+ ],
3530
+ )
3531
+ def test_assign_partial_charges_wrong_n_confs(self, partial_charge_method, expected_n_confs, toolkit_wrappers):
3532
+ """
3533
+ Test AmberToolsToolkitWrapper assign_partial_charges() when requesting to use an incorrect number of
3534
+ conformers
3535
+ """
3536
+
3537
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=toolkit_wrappers)
3538
+ molecule = create_ethanol()
3539
+ molecule.generate_conformers(n_conformers=2, rms_cutoff=0.01 * unit.angstrom)
3540
+
3541
+ # Try passing in the incorrect number of confs, but without specifying strict_n_conformers,
3542
+ # which should produce a warning
3543
+ with pytest.warns(
3544
+ IncorrectNumConformersWarning,
3545
+ match=f"has 2 conformers, but charge method '{partial_charge_method}' expects exactly {expected_n_confs}.",
3546
+ ):
3547
+ molecule.assign_partial_charges(
3548
+ toolkit_registry=toolkit_registry,
3549
+ partial_charge_method=partial_charge_method,
3550
+ use_conformers=molecule.conformers,
3551
+ strict_n_conformers=False,
3552
+ )
3553
+
3554
+ # Try again, with strict_n_confs as true, but not including use_confs, so the
3555
+ # recommended number of confs will be generated
3556
+ molecule.assign_partial_charges(
3557
+ toolkit_registry=toolkit_registry,
3558
+ partial_charge_method=partial_charge_method,
3559
+ strict_n_conformers=True,
3560
+ )
3561
+
3562
+ # Test calling the ToolkitWrapper _indirectly_, though the Molecule API
3563
+ # which should aggregate any exceptions and bundle all of the messages
3564
+ # in a failed task together in a single ValueError.
3565
+ with pytest.raises(
3566
+ ValueError,
3567
+ match=f"has 2 conformers, but charge method '{partial_charge_method}' expects exactly {expected_n_confs}.",
3568
+ ):
3569
+ molecule.assign_partial_charges(
3570
+ toolkit_registry=toolkit_registry,
3571
+ partial_charge_method=partial_charge_method,
3572
+ use_conformers=molecule.conformers,
3573
+ strict_n_conformers=True,
3574
+ )
3575
+
3576
+ # Test calling the ToolkitWrapper _directly_, passing in the incorrect number of
3577
+ # confs, and specify strict_n_conformers, which should produce an IncorrectNumConformersError
3578
+ with pytest.raises(
3579
+ IncorrectNumConformersError,
3580
+ match=f"has 2 conformers, but charge method '{partial_charge_method}' expects exactly {expected_n_confs}.",
3581
+ ):
3582
+ ATTKW = AmberToolsToolkitWrapper()
3583
+ ATTKW.assign_partial_charges(
3584
+ molecule=molecule,
3585
+ partial_charge_method=partial_charge_method,
3586
+ use_conformers=molecule.conformers,
3587
+ strict_n_conformers=True,
3588
+ )
3589
+
3590
+ @pytest.mark.parametrize("bond_order_model", ["am1-wiberg"])
3591
+ @pytest.mark.parametrize(
3592
+ "smiles",
3593
+ [
3594
+ "[H]C([H])([H])C([H])([H])[H]",
3595
+ "[H]C([H])([H])[N+]([H])([H])[H]",
3596
+ r"C\C(F)=C(/F)C[C@@](C)(Cl)Br",
3597
+ ],
3598
+ )
3599
+ def test_assign_fractional_bond_orders(self, bond_order_model, smiles):
3600
+ """Test AmbetToolsToolkitWrapper assign_fractional_bond_orders()"""
3601
+
3602
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3603
+
3604
+ molecule = toolkit_registry.call("from_smiles", smiles)
3605
+ molecule.assign_fractional_bond_orders(toolkit_registry=toolkit_registry, bond_order_model=bond_order_model)
3606
+ # TODO: Add test for equivalent Wiberg orders for equivalent bonds
3607
+
3608
+ # Sanity check single bonds.
3609
+ assert all(0.75 < bond.fractional_bond_order < 1.25 for bond in molecule.bonds if bond.bond_order == 1)
3610
+ # Sanity check double bonds.
3611
+ assert all(1.75 < bond.fractional_bond_order < 2.25 for bond in molecule.bonds if bond.bond_order == 2)
3612
+
3613
+ def test_assign_fractional_bond_orders_conformer_dependence(self):
3614
+ """
3615
+ Test that RDKitToolkitWrapper assign_fractional_bond_orders() provides different results when using
3616
+ different conformers
3617
+ """
3618
+
3619
+ toolkit_wrapper = ToolkitRegistry([RDKitToolkitWrapper, AmberToolsToolkitWrapper])
3620
+ # Get the WBOs using one conformer
3621
+ molecule = create_ethanol()
3622
+ molecule.generate_conformers(toolkit_registry=toolkit_wrapper)
3623
+ molecule.assign_fractional_bond_orders(
3624
+ toolkit_registry=toolkit_wrapper,
3625
+ use_conformers=molecule.conformers,
3626
+ bond_order_model="am1-wiberg",
3627
+ )
3628
+
3629
+ # Do the same again, but change the conformer to yield a different result
3630
+ molecule_diff_coords = create_ethanol()
3631
+ molecule_diff_coords.generate_conformers(toolkit_registry=toolkit_wrapper)
3632
+ molecule_diff_coords._conformers[0][0][0] = molecule_diff_coords._conformers[0][0][0] + 1.0 * unit.angstrom
3633
+ molecule_diff_coords._conformers[0][1][0] = molecule_diff_coords._conformers[0][1][0] - 1.0 * unit.angstrom
3634
+ molecule_diff_coords._conformers[0][2][0] = molecule_diff_coords._conformers[0][2][0] + 1.0 * unit.angstrom
3635
+ molecule_diff_coords.assign_fractional_bond_orders(
3636
+ toolkit_registry=toolkit_wrapper,
3637
+ use_conformers=molecule_diff_coords.conformers,
3638
+ bond_order_model="am1-wiberg",
3639
+ )
3640
+
3641
+ for bond1, bond2 in zip(molecule.bonds, molecule_diff_coords.bonds):
3642
+ assert abs(bond1.fractional_bond_order - bond2.fractional_bond_order) > 1e-3
3643
+
3644
+ @pytest.mark.parametrize("bond_order_model", ["am1-wiberg"])
3645
+ def test_assign_fractional_bond_orders_neutral_charge_mol(self, bond_order_model):
3646
+ """Test AmberToolsToolkitWrapper assign_fractional_bond_orders() for neutral and charged molecule.
3647
+ Also tests using existing conformers"""
3648
+
3649
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3650
+ # Reading neutral molecule from file
3651
+ filename = get_data_file_path("molecules/CID20742535_neutral.sdf")
3652
+ molecule1 = Molecule.from_file(filename)
3653
+ # Reading negative molecule from file
3654
+ filename = get_data_file_path("molecules/CID20742535_anion.sdf")
3655
+ molecule2 = Molecule.from_file(filename)
3656
+
3657
+ # Checking that only one additional bond is present in the neutral molecule
3658
+ assert len(molecule1.bonds) == len(molecule2.bonds) + 1
3659
+
3660
+ molecule1.assign_fractional_bond_orders(
3661
+ toolkit_registry=toolkit_registry,
3662
+ bond_order_model=bond_order_model,
3663
+ use_conformers=molecule1.conformers,
3664
+ )
3665
+
3666
+ for i in molecule1.bonds:
3667
+ if i.is_aromatic:
3668
+ # Checking aromatic bonds
3669
+ assert 1.05 < i.fractional_bond_order < 1.65
3670
+ elif i.atom1.atomic_number == 1 or i.atom2.atomic_number == 1:
3671
+ # Checking bond order of C-H or O-H bonds are around 1
3672
+ assert 0.85 < i.fractional_bond_order < 1.05
3673
+ elif i.atom1.atomic_number == 8 or i.atom2.atomic_number == 8:
3674
+ # Checking C-O single bond
3675
+ wbo_C_O_neutral = i.fractional_bond_order
3676
+ assert 1.0 < wbo_C_O_neutral < 1.5
3677
+ else:
3678
+ # Should be C-C single bond
3679
+ assert (i.atom1_index == 4 and i.atom2_index == 6) or (i.atom1_index == 6 and i.atom2_index == 4)
3680
+ wbo_C_C_neutral = i.fractional_bond_order
3681
+ assert 1.0 < wbo_C_C_neutral < 1.3
3682
+
3683
+ molecule2.assign_fractional_bond_orders(
3684
+ toolkit_registry=toolkit_registry,
3685
+ bond_order_model=bond_order_model,
3686
+ use_conformers=molecule2.conformers,
3687
+ )
3688
+ for i in molecule2.bonds:
3689
+ if i.is_aromatic:
3690
+ # Checking aromatic bonds
3691
+ assert 1.05 < i.fractional_bond_order < 1.65
3692
+
3693
+ elif i.atom1.atomic_number == 1 or i.atom2.atomic_number == 1:
3694
+ # Checking bond order of C-H or O-H bonds are around 1
3695
+ assert 0.85 < i.fractional_bond_order < 1.05
3696
+ elif i.atom1.atomic_number == 8 or i.atom2.atomic_number == 8:
3697
+ # Checking C-O single bond
3698
+ wbo_C_O_anion = i.fractional_bond_order
3699
+ assert 1.3 < wbo_C_O_anion < 1.8
3700
+ else:
3701
+ # Should be C-C single bond
3702
+ assert (i.atom1_index == 4 and i.atom2_index == 6) or (i.atom1_index == 6 and i.atom2_index == 4)
3703
+ wbo_C_C_anion = i.fractional_bond_order
3704
+ assert 1.0 < wbo_C_C_anion < 1.3
3705
+
3706
+ # Wiberg bond order of C-C single bond is higher in the anion
3707
+ assert wbo_C_C_anion > wbo_C_C_neutral
3708
+ # Wiberg bond order of C-O bond is higher in the anion
3709
+ assert wbo_C_O_anion > wbo_C_O_neutral
3710
+
3711
+ def test_assign_fractional_bond_orders_invalid_method(self):
3712
+ """
3713
+ Test that AmberToolsToolkitWrapper.assign_fractional_bond_orders() raises the
3714
+ correct error if an invalid charge model is provided
3715
+ """
3716
+
3717
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
3718
+ molecule = toolkit_registry.call("from_smiles", "C")
3719
+
3720
+ expected_error = (
3721
+ "Bond order model 'not a real charge model' is not supported by "
3722
+ "AmberToolsToolkitWrapper. Supported models are ([[]'am1-wiberg'[]])"
3723
+ )
3724
+ with pytest.raises(ValueError, match=expected_error):
3725
+ molecule.assign_fractional_bond_orders(
3726
+ toolkit_registry=AmberToolsToolkitWrapper(),
3727
+ bond_order_model="not a real charge model",
3728
+ )
3729
+
3730
+ def test_assign_fractional_bond_orders_thread_safe(self):
3731
+ """
3732
+ Test that AmberToolsToolkitWrapper assign_fractional_bond_orders() is thread-safe
3733
+ See https://github.com/openforcefield/openff-toolkit/issues/1642
3734
+ """
3735
+ from concurrent.futures import ThreadPoolExecutor
3736
+
3737
+ def charge_func(run_num=-1):
3738
+ from openff.toolkit import AmberToolsToolkitWrapper, Molecule
3739
+
3740
+ AmberToolsToolkitWrapper().assign_fractional_bond_orders(Molecule.from_smiles("CCO"))
3741
+
3742
+ futures = list()
3743
+ with ThreadPoolExecutor() as executor:
3744
+ for i in range(5):
3745
+ futures.append(executor.submit(charge_func, i))
3746
+ for future in futures:
3747
+ future.result()
3748
+
3749
+ @requires_openeye
3750
+ def test_assign_fractional_bond_orders_openeye_installed(self):
3751
+ """Test that assign_fractional_bond_orders produces the same result
3752
+ with and without OpenEye toolkits installed"""
3753
+ mol = Molecule.from_smiles("CCO")
3754
+ AmberToolsToolkitWrapper().assign_fractional_bond_orders(mol)
3755
+ with_oe = [b.fractional_bond_order for b in mol.bonds]
3756
+ GLOBAL_TOOLKIT_REGISTRY.deregister_toolkit(OpenEyeToolkitWrapper)
3757
+ AmberToolsToolkitWrapper().assign_fractional_bond_orders(mol)
3758
+ without_oe = [b.fractional_bond_order for b in mol.bonds]
3759
+ GLOBAL_TOOLKIT_REGISTRY.register_toolkit(OpenEyeToolkitWrapper)
3760
+
3761
+ assert with_oe == pytest.approx(without_oe, abs=1e-5)
3762
+
3763
+
3764
+ class TestBuiltInToolkitWrapper:
3765
+ """Test the BuiltInToolkitWrapper"""
3766
+
3767
+ def test_supported_charge_methods(self):
3768
+ methods = BuiltInToolkitWrapper().supported_charge_methods
3769
+
3770
+ assert "am1-mulliken" not in methods
3771
+ assert "am1bcc" not in methods
3772
+ assert "am1bccelf10" not in methods
3773
+ assert "am1elf10" not in methods
3774
+ assert "am1bccnosymspt" not in methods
3775
+ assert "mmff94" not in methods
3776
+ assert "gasteiger" not in methods
3777
+
3778
+ assert "zeros" in methods
3779
+ assert "formal_charge" in methods
3780
+
3781
+ @pytest.mark.parametrize("partial_charge_method", ["zeros", "formal_charge"])
3782
+ def test_assign_partial_charges_neutral(self, partial_charge_method):
3783
+ """Test BuiltInToolkitWrapper assign_partial_charges()"""
3784
+
3785
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[BuiltInToolkitWrapper])
3786
+ molecule = create_ethanol()
3787
+ molecule.assign_partial_charges(
3788
+ toolkit_registry=toolkit_registry,
3789
+ partial_charge_method=partial_charge_method,
3790
+ # The normalize_partial_charges kwarg won't cause a measurable effect here, this just
3791
+ # tests that the kwarg remains accepted.
3792
+ normalize_partial_charges=False,
3793
+ )
3794
+ charge_sum = np.sum(molecule.partial_charges)
3795
+ assert 1.0e-10 > abs(charge_sum.m_as(unit.elementary_charge))
3796
+
3797
+ @pytest.mark.parametrize("partial_charge_method", ["formal_charge"])
3798
+ def test_assign_partial_charges_net_charge(self, partial_charge_method):
3799
+ """
3800
+ Test BuiltInToolkitWrapper assign_partial_charges(). Only formal_charge is tested, since zeros will not
3801
+ sum up to the proper number
3802
+ """
3803
+
3804
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[BuiltInToolkitWrapper])
3805
+ molecule = create_acetate()
3806
+ molecule.assign_partial_charges(
3807
+ toolkit_registry=toolkit_registry,
3808
+ partial_charge_method=partial_charge_method,
3809
+ )
3810
+ charge_sum = np.sum(molecule.partial_charges)
3811
+ assert 1.0e-10 > abs(charge_sum.m_as(unit.elementary_charge) + 1.0)
3812
+
3813
+ def test_assign_partial_charges_bad_charge_method(self):
3814
+ """Test BuiltInToolkitWrapper assign_partial_charges() for a nonexistent charge method"""
3815
+
3816
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[BuiltInToolkitWrapper])
3817
+ molecule = create_ethanol()
3818
+
3819
+ # For now, the Molecule API passes raise_exception_types=[] to ToolkitRegistry.call,
3820
+ # which loses track of what exception type
3821
+ # was thrown inside them, so we just check for a ValueError here
3822
+ with pytest.raises(ValueError, match="is not supported by the Built-in toolkit"):
3823
+ molecule.assign_partial_charges(
3824
+ toolkit_registry=toolkit_registry,
3825
+ partial_charge_method="NotARealChargeMethod",
3826
+ )
3827
+
3828
+ # ToolkitWrappers raise a specific exception class, so we test that here
3829
+ with pytest.raises(
3830
+ ChargeMethodUnavailableError,
3831
+ match="is not supported by the Built-in toolkit",
3832
+ ):
3833
+ BITKW = BuiltInToolkitWrapper()
3834
+ BITKW.assign_partial_charges(molecule=molecule, partial_charge_method="NotARealChargeMethod")
3835
+
3836
+ def test_assign_partial_charges_wrong_n_confs(self):
3837
+ """
3838
+ Test BuiltInToolkitWrapper assign_partial_charges() when requesting to use an incorrect number of
3839
+ conformers
3840
+ """
3841
+
3842
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[BuiltInToolkitWrapper])
3843
+ molecule = create_ethanol()
3844
+ molecule.generate_conformers(n_conformers=1)
3845
+ with pytest.warns(
3846
+ IncorrectNumConformersWarning,
3847
+ match=r"has 1 conformers, but charge method 'zeros' expects exactly 0.",
3848
+ ):
3849
+ molecule.assign_partial_charges(
3850
+ toolkit_registry=toolkit_registry,
3851
+ partial_charge_method="zeros",
3852
+ use_conformers=molecule.conformers,
3853
+ strict_n_conformers=False,
3854
+ )
3855
+
3856
+ # Specify strict_n_conformers=True, but not use_conformers, so a recommended number of
3857
+ # conformers will be generated internally
3858
+ molecule.assign_partial_charges(
3859
+ toolkit_registry=toolkit_registry,
3860
+ partial_charge_method="zeros",
3861
+ strict_n_conformers=True,
3862
+ )
3863
+
3864
+ # For now, the Molecule API passes raise_exception_types=[] to ToolkitRegistry.call,
3865
+ # which loses track of what exception type
3866
+ # was thrown inside them, so we just check for a ValueError here
3867
+ with pytest.raises(
3868
+ ValueError,
3869
+ match=r"has 1 conformers, but charge method 'zeros' expects exactly 0.",
3870
+ ):
3871
+ molecule.assign_partial_charges(
3872
+ toolkit_registry=toolkit_registry,
3873
+ partial_charge_method="zeros",
3874
+ use_conformers=molecule.conformers,
3875
+ strict_n_conformers=True,
3876
+ )
3877
+
3878
+ # Test calling the ToolkitWrapper _directly_, passing in the incorrect number of
3879
+ # confs, and specify strict_n_conformers, which should produce an IncorrectNumConformersError
3880
+ with pytest.raises(
3881
+ IncorrectNumConformersError,
3882
+ match=r"has 1 conformers, but charge method 'zeros' expects exactly 0.",
3883
+ ):
3884
+ BITKW = BuiltInToolkitWrapper()
3885
+ BITKW.assign_partial_charges(
3886
+ molecule=molecule,
3887
+ partial_charge_method="zeros",
3888
+ use_conformers=molecule.conformers,
3889
+ strict_n_conformers=True,
3890
+ )
3891
+
3892
+ def test_charge_method_api_continuity(self):
3893
+ """Test rough continuity of BuiltinToolkitWrapper.PARTIAL_CHARGE_METHODS"""
3894
+ assert isinstance(BuiltInToolkitWrapper.PARTIAL_CHARGE_METHODS, dict)
3895
+
3896
+ assert BuiltInToolkitWrapper.PARTIAL_CHARGE_METHODS["zeros"] == {
3897
+ "rec_confs": 0,
3898
+ "min_confs": 0,
3899
+ "max_confs": 0,
3900
+ }
3901
+ assert BuiltInToolkitWrapper.PARTIAL_CHARGE_METHODS["formal_charge"] == {
3902
+ "rec_confs": 0,
3903
+ "min_confs": 0,
3904
+ "max_confs": 0,
3905
+ }
3906
+
3907
+
3908
+ class TestToolkitWrapper:
3909
+ """Test the ToolkitWrapper class"""
3910
+
3911
+ def test_check_n_conformers(self):
3912
+ """Ensure that _check_n_conformers is working properly"""
3913
+ tkw = ToolkitWrapper()
3914
+ mol = create_ethanol()
3915
+
3916
+ # Test molecule with no conformers
3917
+ # Check with no min or max should pass
3918
+ tkw._check_n_conformers(mol, "nocharge")
3919
+ # Check with min=1 should warn
3920
+ with pytest.warns(
3921
+ IncorrectNumConformersWarning,
3922
+ match=r"has 0 conformers, but charge method 'nocharge' expects at least 1",
3923
+ ):
3924
+ tkw._check_n_conformers(mol, "nocharge", min_confs=1)
3925
+ # Check with min=1 and strict_n_conformers should raise an error
3926
+ with pytest.raises(
3927
+ IncorrectNumConformersError,
3928
+ match=r"has 0 conformers, but charge method 'nocharge' expects at least 1",
3929
+ ):
3930
+ tkw._check_n_conformers(mol, "nocharge", min_confs=1, strict_n_conformers=True)
3931
+ # Check with min=1, max=1 and strict_n_conformers should raise an error
3932
+ with pytest.raises(
3933
+ IncorrectNumConformersError,
3934
+ match=r"has 0 conformers, but charge method 'nocharge' expects exactly 1",
3935
+ ):
3936
+ tkw._check_n_conformers(mol, "nocharge", min_confs=1, max_confs=1, strict_n_conformers=True)
3937
+ # Check with min=1, max=2 and strict_n_conformers should raise an error
3938
+ with pytest.raises(
3939
+ IncorrectNumConformersError,
3940
+ match=r"has 0 conformers, but charge method 'nocharge' expects between 1 and 2",
3941
+ ):
3942
+ tkw._check_n_conformers(mol, "nocharge", min_confs=1, max_confs=2, strict_n_conformers=True)
3943
+ # Check with max=1 should pass
3944
+ tkw._check_n_conformers(mol, "nocharge", max_confs=1, strict_n_conformers=True)
3945
+
3946
+ # Test molecule with conformers
3947
+ # Add some conformers
3948
+ mol.generate_conformers(n_conformers=1)
3949
+ for _ in range(9):
3950
+ mol.add_conformer(mol.conformers[0])
3951
+
3952
+ # Check with no min or max should pass
3953
+ tkw._check_n_conformers(mol, "nocharge")
3954
+
3955
+ # min_confs checks
3956
+ # Check with min=1 should be fine
3957
+ tkw._check_n_conformers(mol, "nocharge", min_confs=1)
3958
+ # Check with min=10 should be fine
3959
+ tkw._check_n_conformers(mol, "nocharge", min_confs=10)
3960
+ # Check with min=11 should warn
3961
+ with pytest.warns(
3962
+ IncorrectNumConformersWarning,
3963
+ match="has 10 conformers, but charge method 'nocharge' expects at least 11",
3964
+ ):
3965
+ tkw._check_n_conformers(mol, "nocharge", min_confs=11)
3966
+ # Check with min=11 and strict_n_conformers should raise an error
3967
+ with pytest.raises(
3968
+ IncorrectNumConformersError,
3969
+ match="has 10 conformers, but charge method 'nocharge' expects at least 11",
3970
+ ):
3971
+ tkw._check_n_conformers(mol, "nocharge", min_confs=11, strict_n_conformers=True)
3972
+
3973
+ # max_confs checks
3974
+ # Check with max=1 and strict_n_conformers should raise an error
3975
+ with pytest.raises(
3976
+ IncorrectNumConformersError,
3977
+ match="has 10 conformers, but charge method 'nocharge' expects at most 1",
3978
+ ):
3979
+ tkw._check_n_conformers(mol, "nocharge", max_confs=1, strict_n_conformers=True)
3980
+ # Check with max=10 and strict_n_conformers should be OK
3981
+ tkw._check_n_conformers(mol, "nocharge", max_confs=10, strict_n_conformers=True)
3982
+ # Check with max=11 and strict_n_conformers should be OK
3983
+ tkw._check_n_conformers(mol, "nocharge", max_confs=11, strict_n_conformers=True)
3984
+
3985
+ # min_confs and max_confs checks
3986
+ # Check with max=10 and min=10 and strict_n_conformers should be OK
3987
+ tkw._check_n_conformers(mol, "nocharge", min_confs=10, max_confs=10, strict_n_conformers=True)
3988
+ # Check with max=10 and min=9 and strict_n_conformers should be OK
3989
+ tkw._check_n_conformers(mol, "nocharge", min_confs=9, max_confs=10, strict_n_conformers=True)
3990
+ # Check with max=11 and min=10 and strict_n_conformers should be OK
3991
+ tkw._check_n_conformers(mol, "nocharge", min_confs=10, max_confs=11, strict_n_conformers=True)
3992
+ # Check with max=11 and min=9 and strict_n_conformers should be OK
3993
+ tkw._check_n_conformers(mol, "nocharge", min_confs=9, max_confs=11, strict_n_conformers=True)
3994
+ # Check with min=9 and max=9 and strict_n_conformers should raise an error
3995
+ with pytest.raises(
3996
+ IncorrectNumConformersError,
3997
+ match="has 10 conformers, but charge method 'nocharge' expects exactly 9",
3998
+ ):
3999
+ tkw._check_n_conformers(mol, "nocharge", min_confs=9, max_confs=9, strict_n_conformers=True)
4000
+ # Check with min=1 and max=9 and strict_n_conformers should raise an error
4001
+ with pytest.raises(
4002
+ IncorrectNumConformersError,
4003
+ match="has 10 conformers, but charge method 'nocharge' expects between 1 and 9",
4004
+ ):
4005
+ tkw._check_n_conformers(mol, "nocharge", min_confs=1, max_confs=9, strict_n_conformers=True)
4006
+ # Check with min=11 and max=12 and strict_n_conformers should raise an error
4007
+ with pytest.raises(
4008
+ IncorrectNumConformersError,
4009
+ match="has 10 conformers, but charge method 'nocharge' expects between 11 and 12",
4010
+ ):
4011
+ tkw._check_n_conformers(mol, "nocharge", min_confs=11, max_confs=12, strict_n_conformers=True)
4012
+
4013
+
4014
+ class TestToolkitRegistry:
4015
+ """Test the ToolkitRegistry class"""
4016
+
4017
+ def test_register_empty_toolkit(self):
4018
+ """Ensure the default ToolkitRegistry init returns an empty registry"""
4019
+ empty_registry = ToolkitRegistry()
4020
+
4021
+ assert empty_registry.registered_toolkits == []
4022
+ assert empty_registry.registered_toolkit_versions == {}
4023
+
4024
+ @requires_openeye
4025
+ @requires_rdkit
4026
+ def test_register_imported_toolkit_wrappers(self):
4027
+ """Test that imported toolkits are registered, and in the expected order"""
4028
+ no_precedence = ToolkitRegistry(_register_imported_toolkit_wrappers=True)
4029
+
4030
+ assert len(no_precedence.registered_toolkits) == 4
4031
+
4032
+ # Ensure a specified order is respected
4033
+ default_registry = ToolkitRegistry(
4034
+ toolkit_precedence=[
4035
+ OpenEyeToolkitWrapper,
4036
+ RDKitToolkitWrapper,
4037
+ AmberToolsToolkitWrapper,
4038
+ BuiltInToolkitWrapper,
4039
+ ],
4040
+ _register_imported_toolkit_wrappers=True,
4041
+ )
4042
+
4043
+ assert len(default_registry.registered_toolkits) == 4
4044
+
4045
+ expected_toolkits = [
4046
+ OpenEyeToolkitWrapper,
4047
+ RDKitToolkitWrapper,
4048
+ AmberToolsToolkitWrapper,
4049
+ BuiltInToolkitWrapper,
4050
+ ]
4051
+ for found, expected in zip(default_registry.registered_toolkits, expected_toolkits):
4052
+ assert isinstance(found, expected)
4053
+
4054
+ # Test forcing a non-default order
4055
+ non_default_registry = ToolkitRegistry(
4056
+ toolkit_precedence=[BuiltInToolkitWrapper, RDKitToolkitWrapper],
4057
+ _register_imported_toolkit_wrappers=True,
4058
+ )
4059
+
4060
+ assert len(non_default_registry.registered_toolkits) == 2
4061
+
4062
+ expected_toolkits = [BuiltInToolkitWrapper, RDKitToolkitWrapper]
4063
+ for found, expected in zip(non_default_registry.registered_toolkits, expected_toolkits):
4064
+ assert isinstance(found, expected)
4065
+
4066
+ @requires_rdkit
4067
+ def test_add_bad_toolkit(self):
4068
+ registry = ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper])
4069
+ with pytest.raises(InvalidToolkitError):
4070
+ registry.add_toolkit("rdkit as a string")
4071
+
4072
+ @requires_rdkit
4073
+ @pytest.mark.skipif(
4074
+ OpenEyeToolkitWrapper.is_available(),
4075
+ reason="Skipping while OpenEye is available",
4076
+ )
4077
+ def test_register_unavailable_toolkit(self):
4078
+ registry = ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper])
4079
+ with pytest.raises(ToolkitUnavailableException):
4080
+ registry.register_toolkit(toolkit_wrapper=OpenEyeToolkitWrapper, exception_if_unavailable=True)
4081
+
4082
+ @pytest.mark.skipif(
4083
+ RDKitToolkitWrapper.is_available(),
4084
+ reason="Skipping while The RDKit is available",
4085
+ )
4086
+ def test_requires_toolkit_exception(self):
4087
+ """Test that ToolkitUnavailableException, not LicenseError, is raised
4088
+ when RDKitToolkitWrapper is unavailable"""
4089
+ registry = ToolkitRegistry()
4090
+ with pytest.raises(ToolkitUnavailableException):
4091
+ registry.register_toolkit(toolkit_wrapper=RDKitToolkitWrapper, exception_if_unavailable=True)
4092
+
4093
+ @requires_openeye
4094
+ def test_register_openeye(self):
4095
+ """Test creation of toolkit registry with OpenEye toolkit"""
4096
+ # Test registration of OpenEyeToolkitWrapper
4097
+ toolkit_precedence = [OpenEyeToolkitWrapper]
4098
+ registry = ToolkitRegistry(
4099
+ toolkit_precedence=toolkit_precedence,
4100
+ )
4101
+
4102
+ assert set(type(c) for c in registry.registered_toolkits) == set([OpenEyeToolkitWrapper])
4103
+
4104
+ # Test ToolkitRegistry.resolve()
4105
+ assert registry.resolve("to_smiles") == registry.registered_toolkits[0].to_smiles
4106
+
4107
+ # Test ToolkitRegistry.call()
4108
+ smiles = "[H]C([H])([H])C([H])([H])[H]"
4109
+ molecule = registry.call("from_smiles", smiles)
4110
+ smiles2 = registry.call("to_smiles", molecule)
4111
+ assert smiles == smiles2
4112
+
4113
+ @requires_rdkit
4114
+ def test_register_rdkit(self):
4115
+ """Test creation of toolkit registry with RDKit toolkit"""
4116
+ # Test registration of RDKitToolkitWrapper
4117
+ toolkit_precedence = [RDKitToolkitWrapper]
4118
+ registry = ToolkitRegistry(
4119
+ toolkit_precedence=toolkit_precedence,
4120
+ )
4121
+
4122
+ assert set([type(c) for c in registry.registered_toolkits]) == set([RDKitToolkitWrapper])
4123
+
4124
+ # Test ToolkitRegistry.resolve()
4125
+ assert registry.resolve("to_smiles") == registry.registered_toolkits[0].to_smiles
4126
+
4127
+ # Test ToolkitRegistry.call()
4128
+ smiles = "[H][C]([H])([H])[C]([H])([H])[H]"
4129
+ molecule = registry.call("from_smiles", smiles)
4130
+ smiles2 = registry.call("to_smiles", molecule)
4131
+ assert smiles == smiles2
4132
+
4133
+ @requires_ambertools
4134
+ def test_register_ambertools(self):
4135
+ """Test creation of toolkit registry with AmberToolsToolkitWrapper"""
4136
+ # Test registration of AmberToolsToolkitWrapper
4137
+ toolkit_precedence = [AmberToolsToolkitWrapper]
4138
+ registry = ToolkitRegistry(
4139
+ toolkit_precedence=toolkit_precedence,
4140
+ )
4141
+
4142
+ assert set([type(c) for c in registry.registered_toolkits]) == set([AmberToolsToolkitWrapper])
4143
+
4144
+ # Test ToolkitRegistry.resolve()
4145
+ registry.resolve("assign_partial_charges")
4146
+ assert registry.resolve("assign_partial_charges") == registry.registered_toolkits[0].assign_partial_charges
4147
+
4148
+ # Test ToolkitRegistry.call()
4149
+ molecule = RDKitToolkitWrapper().from_file(
4150
+ file_path=get_data_file_path("molecules/ethanol.sdf"), file_format="SDF"
4151
+ )[0]
4152
+ registry.call("assign_partial_charges", molecule)
4153
+ charges_from_registry = molecule.partial_charges
4154
+ AmberToolsToolkitWrapper().assign_partial_charges(molecule)
4155
+ charges_from_toolkit = molecule.partial_charges
4156
+
4157
+ assert np.allclose(charges_from_registry, charges_from_toolkit)
4158
+
4159
+ @requires_ambertools
4160
+ def test_register_rdkit_and_ambertools(self):
4161
+ """Test creation of toolkit registry with RDKitToolkitWrapper and
4162
+ AmberToolsToolkitWrapper and test ToolkitRegistry.resolve()"""
4163
+ toolkit_precedence = [RDKitToolkitWrapper, AmberToolsToolkitWrapper]
4164
+ registry = ToolkitRegistry(
4165
+ toolkit_precedence=toolkit_precedence,
4166
+ )
4167
+
4168
+ assert set([type(c) for c in registry.registered_toolkits]) == set(
4169
+ [RDKitToolkitWrapper, AmberToolsToolkitWrapper]
4170
+ )
4171
+
4172
+ # Resolve to a method that is supported by AmberToolsToolkitWrapper
4173
+ # but _not_ RDKitToolkitWrapper. Note that this may change as more
4174
+ # functionality is added to to toolkit wrappers
4175
+ assert (
4176
+ registry.resolve("assign_fractional_bond_orders")
4177
+ == registry.registered_toolkits[1].assign_fractional_bond_orders
4178
+ )
4179
+ # Resolve a method supported by both to the highest-priority wrapper
4180
+ assert registry.resolve("from_smiles") == registry.registered_toolkits[0].from_smiles
4181
+
4182
+ # Test ToolkitRegistry.call() for each toolkit
4183
+ smiles = "[H][C]([H])([H])[C]([H])([H])[H]"
4184
+ molecule = registry.call("from_smiles", smiles)
4185
+ smiles2 = registry.call("to_smiles", molecule)
4186
+
4187
+ # Round-tripping SMILES is not 100% reliable, so just ensure it returned something
4188
+ assert isinstance(smiles2, str)
4189
+
4190
+ # This method is available in AmberToolsToolkitWrapper, but not RDKitToolkitWrapper
4191
+ registry.call("assign_partial_charges", molecule)
4192
+
4193
+ @requires_ambertools
4194
+ def test_deregister_toolkit(self):
4195
+ """Test removing an instantiated toolkit from the registry"""
4196
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
4197
+
4198
+ assert any([isinstance(tk, AmberToolsToolkitWrapper) for tk in toolkit_registry._toolkits])
4199
+ assert any([isinstance(tk, RDKitToolkitWrapper) for tk in toolkit_registry._toolkits])
4200
+
4201
+ toolkit_registry.deregister_toolkit(toolkit_registry._toolkits[-1])
4202
+ assert any([isinstance(tk, AmberToolsToolkitWrapper) for tk in toolkit_registry._toolkits])
4203
+ assert not any([isinstance(tk, RDKitToolkitWrapper) for tk in toolkit_registry._toolkits])
4204
+
4205
+ toolkit_registry.deregister_toolkit(toolkit_registry._toolkits[-1])
4206
+ assert not any([isinstance(tk, AmberToolsToolkitWrapper) for tk in toolkit_registry._toolkits])
4207
+ assert not any([isinstance(tk, RDKitToolkitWrapper) for tk in toolkit_registry._toolkits])
4208
+
4209
+ @requires_ambertools
4210
+ def test_deregister_toolkit_by_class(self):
4211
+ """Test removing a toolkit from the registry by matching class types"""
4212
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper, RDKitToolkitWrapper])
4213
+
4214
+ assert any([isinstance(tk, AmberToolsToolkitWrapper) for tk in toolkit_registry._toolkits])
4215
+ assert any([isinstance(tk, RDKitToolkitWrapper) for tk in toolkit_registry._toolkits])
4216
+
4217
+ toolkit_registry.deregister_toolkit(RDKitToolkitWrapper)
4218
+ assert any([isinstance(tk, AmberToolsToolkitWrapper) for tk in toolkit_registry._toolkits])
4219
+ assert not any([isinstance(tk, RDKitToolkitWrapper) for tk in toolkit_registry._toolkits])
4220
+
4221
+ toolkit_registry.deregister_toolkit(AmberToolsToolkitWrapper)
4222
+ assert not any([isinstance(tk, AmberToolsToolkitWrapper) for tk in toolkit_registry._toolkits])
4223
+ assert not any([isinstance(tk, RDKitToolkitWrapper) for tk in toolkit_registry._toolkits])
4224
+
4225
+ @requires_ambertools
4226
+ def test_deregister_toolkit_bad_inputs(self):
4227
+ """Test bad inputs to deregister_toolkit"""
4228
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[AmberToolsToolkitWrapper])
4229
+
4230
+ with pytest.raises(InvalidToolkitError):
4231
+ toolkit_registry.deregister_toolkit("rdkit as a string")
4232
+
4233
+ # Attempt to deregister a toolkit that is not registered
4234
+ with pytest.raises(ToolkitUnavailableException):
4235
+ toolkit_registry.deregister_toolkit(RDKitToolkitWrapper)
4236
+
4237
+ def deregister_from_global_registry(self):
4238
+ # TODO: Update this, or move into a separate TestClass, pending GLOBAL_TOOLKIT_REGISTRY rewor
4239
+ # See issue #493
4240
+ # Whatever the first tookit it, de-register it and verify it's de-registered
4241
+
4242
+ # Keep a copy of the original registry since this is a "global" variable accessible to other modules
4243
+ from copy import deepcopy
4244
+
4245
+ global_registry_copy = deepcopy(GLOBAL_TOOLKIT_REGISTRY) # noqa: F823
4246
+ first_toolkit = type(GLOBAL_TOOLKIT_REGISTRY.registered_toolkits[0])
4247
+ num_toolkits = len(GLOBAL_TOOLKIT_REGISTRY.registered_toolkits)
4248
+
4249
+ GLOBAL_TOOLKIT_REGISTRY.deregister_toolkit(first_toolkit)
4250
+
4251
+ assert first_toolkit not in [type(tk) for tk in GLOBAL_TOOLKIT_REGISTRY.registered_toolkits]
4252
+ assert len(GLOBAL_TOOLKIT_REGISTRY.registered_toolkits) == num_toolkits - 1
4253
+
4254
+ GLOBAL_TOOLKIT_REGISTRY = deepcopy(global_registry_copy) # noqa
4255
+
4256
+ def test_register_builtintoolkit(self):
4257
+ """Test creation of toolkit registry with Built-in toolkit"""
4258
+ # Test registration of BuiltInToolkitWrapper
4259
+ toolkit_precedence = [BuiltInToolkitWrapper]
4260
+ registry = ToolkitRegistry(
4261
+ toolkit_precedence=toolkit_precedence,
4262
+ )
4263
+ # registry.register_toolkit(BuiltInToolkitWrapper)
4264
+ assert set([type(c) for c in registry.registered_toolkits]) == set([BuiltInToolkitWrapper])
4265
+
4266
+ # Test ToolkitRegistry.resolve()
4267
+ resolved = registry.resolve("assign_partial_charges")
4268
+ assert resolved == registry.registered_toolkits[0].assign_partial_charges
4269
+
4270
+ @requires_rdkit
4271
+ @requires_openeye
4272
+ def test_toolkit_versions(self):
4273
+ """Test behavior of ToolkitRegistry.registered_toolkit_versions"""
4274
+ toolkit_precedence = [
4275
+ OpenEyeToolkitWrapper,
4276
+ RDKitToolkitWrapper,
4277
+ AmberToolsToolkitWrapper,
4278
+ BuiltInToolkitWrapper,
4279
+ ]
4280
+ all_toolkits = ToolkitRegistry(toolkit_precedence=toolkit_precedence)
4281
+ versions = all_toolkits.registered_toolkit_versions
4282
+
4283
+ import openeye
4284
+ import rdkit
4285
+
4286
+ assert versions["OpenEye Toolkit"] == openeye.__version__
4287
+ assert versions["The RDKit"] == rdkit.__version__
4288
+ assert versions["AmberTools"].startswith("2") # TODO: Safer way of checking AmberTools version
4289
+ assert versions["Built-in Toolkit"] is None
4290
+
4291
+ toolkit_precedence = [
4292
+ RDKitToolkitWrapper,
4293
+ AmberToolsToolkitWrapper,
4294
+ BuiltInToolkitWrapper,
4295
+ ]
4296
+ no_openeye = ToolkitRegistry(toolkit_precedence=toolkit_precedence)
4297
+
4298
+ assert "OpenEye Toolkit" not in no_openeye.registered_toolkit_versions.keys()
4299
+
4300
+ @requires_ambertools
4301
+ def test_call_raise_first_error(self):
4302
+ """Test to ensure proper behavior of raise_first_error kwarg to ToolkitRegistry.call"""
4303
+ toolkit_precedence = [
4304
+ BuiltInToolkitWrapper,
4305
+ RDKitToolkitWrapper,
4306
+ AmberToolsToolkitWrapper,
4307
+ ]
4308
+ registry = ToolkitRegistry(
4309
+ toolkit_precedence=toolkit_precedence,
4310
+ )
4311
+ mol = registry.call("from_smiles", "C")
4312
+ # Specify that the ToolkitRegistry should raise the first ChargeMethodUnavailableError it encounters
4313
+ with pytest.raises(
4314
+ ChargeMethodUnavailableError,
4315
+ match=r'"notarealchargemethod"" is not supported by the Built-in toolkit.',
4316
+ ):
4317
+ registry.call(
4318
+ "assign_partial_charges",
4319
+ molecule=mol,
4320
+ partial_charge_method="NotARealChargeMethod",
4321
+ raise_exception_types=[ChargeMethodUnavailableError],
4322
+ )
4323
+ # Specify that the ToolkitRegistry should collect all the errors it encounters and
4324
+ # ensure it raises a single ValueError when no ToolkitWrappers succeed
4325
+ with pytest.raises(
4326
+ ValueError,
4327
+ match=r"partial_charge_method 'notarealchargemethod' is not available from AmberToolsToolkitWrapper",
4328
+ ):
4329
+ registry.call(
4330
+ "assign_partial_charges",
4331
+ molecule=mol,
4332
+ partial_charge_method="NotARealChargeMethod",
4333
+ raise_exception_types=[],
4334
+ )
4335
+
4336
+
4337
+ @requires_openeye
4338
+ @requires_ambertools
4339
+ @requires_rdkit
4340
+ class TestToolkitRegistryManager:
4341
+ def test_openeye_registry(self):
4342
+ from openff.toolkit.utils.toolkit_registry import toolkit_registry_manager
4343
+
4344
+ openeye_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
4345
+
4346
+ with toolkit_registry_manager(openeye_registry):
4347
+ assert "OpenEye" in str(GLOBAL_TOOLKIT_REGISTRY)
4348
+ assert "RDKit" not in str(GLOBAL_TOOLKIT_REGISTRY)
4349
+
4350
+ create_ethanol().assign_partial_charges(
4351
+ partial_charge_method="am1bccelf10",
4352
+ )
4353
+
4354
+ def test_no_openeye_registry(self):
4355
+ from openff.toolkit.utils.toolkit_registry import toolkit_registry_manager
4356
+
4357
+ no_openeye_registry = ToolkitRegistry(
4358
+ toolkit_precedence=[
4359
+ RDKitToolkitWrapper,
4360
+ AmberToolsToolkitWrapper,
4361
+ ]
4362
+ )
4363
+
4364
+ with toolkit_registry_manager(no_openeye_registry):
4365
+ assert "OpenEye" not in str(GLOBAL_TOOLKIT_REGISTRY)
4366
+ assert "RDKit" in str(GLOBAL_TOOLKIT_REGISTRY)
4367
+
4368
+ with pytest.raises(
4369
+ ValueError,
4370
+ match="No registered toolkits",
4371
+ ):
4372
+ create_ethanol().assign_partial_charges(
4373
+ partial_charge_method="am1bccelf10",
4374
+ )
4375
+
4376
+ create_ethanol().assign_partial_charges(
4377
+ partial_charge_method="am1bcc",
4378
+ )
4379
+
4380
+
4381
+ @requires_openeye
4382
+ def test_license_check(monkeypatch):
4383
+ def MockIsLicensed():
4384
+ return False
4385
+
4386
+ from openeye import oeiupac
4387
+
4388
+ assert oeiupac.OEIUPACIsLicensed()
4389
+
4390
+ from openff.toolkit.utils.toolkits import OpenEyeToolkitWrapper
4391
+
4392
+ assert OpenEyeToolkitWrapper.is_available()
4393
+
4394
+ # Mock OEIUPACIsLicensed to return False ...
4395
+ monkeypatch.setattr(oeiupac, "OEIUPACIsLicensed", MockIsLicensed)
4396
+
4397
+ # ... ensure that the oeiupac module reflects this
4398
+ assert not oeiupac.OEIUPACIsLicensed()
4399
+
4400
+ # ... and ensure that the toolkit wrapper is **still** available
4401
+ assert OpenEyeToolkitWrapper()._check_licenses()
4402
+ assert OpenEyeToolkitWrapper().is_available()
4403
+
4404
+ from openff.toolkit.utils.openeye_wrapper import requires_openeye_module
4405
+
4406
+ @requires_openeye_module("oeszybki")
4407
+ def func_using_extraneous_openeye_module():
4408
+ pass
4409
+
4410
+ with pytest.raises(Exception, match="currently use oeszybki"):
4411
+ func_using_extraneous_openeye_module()
4412
+
4413
+ @requires_openeye_module("oeiupac")
4414
+ def func_using_unlicsensed_openeye_module():
4415
+ pass
4416
+
4417
+ with pytest.raises(AssertionError):
4418
+ func_using_unlicsensed_openeye_module()