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,1747 @@
1
+ """
2
+ Utilities for testing.
3
+
4
+ """
5
+
6
+ import collections
7
+ import copy
8
+ import functools
9
+ import importlib
10
+ import itertools
11
+ import os
12
+ import pathlib
13
+ import pprint
14
+ import textwrap
15
+ from contextlib import contextmanager
16
+
17
+ import numpy as np
18
+ import openmm
19
+ import pytest
20
+ from openff.units.openmm import to_openmm
21
+ from openmm import unit as openmm_unit
22
+
23
+ from openff.toolkit import unit
24
+ from openff.toolkit.utils import (
25
+ AmberToolsToolkitWrapper,
26
+ OpenEyeToolkitWrapper,
27
+ RDKitToolkitWrapper,
28
+ get_data_file_path,
29
+ )
30
+
31
+ requires_ambertools = pytest.mark.skipif(
32
+ not AmberToolsToolkitWrapper.is_available(),
33
+ reason="Test requires AmberTools",
34
+ )
35
+ requires_rdkit = pytest.mark.skipif(
36
+ not RDKitToolkitWrapper.is_available(),
37
+ reason="Test requires RDKit",
38
+ )
39
+ requires_openeye = pytest.mark.skipif(
40
+ not OpenEyeToolkitWrapper.is_available(),
41
+ reason="Test requires OE toolkit",
42
+ )
43
+ requires_openeye_mol2 = pytest.mark.skipif(
44
+ not OpenEyeToolkitWrapper.is_available(),
45
+ reason="Test requires OE toolkit to read mol2 files",
46
+ )
47
+
48
+
49
+ def _get_readme_path() -> pathlib.Path | None:
50
+ """
51
+ Return a path to the README file or None if it cannot be assured to be the toolkit's README.
52
+ """
53
+ if "site-packages" in __file__:
54
+ # This test file is being collected from the installed package, which
55
+ # does not provide the README file.
56
+ # Note that there will likely be a mis-bundled file
57
+ # $CONDA_PREFIX/lib/python3.x/site-packages/README.md, but this is not
58
+ # the toolkit's README file!
59
+ return None
60
+
61
+ else:
62
+ return pathlib.Path(__file__).parents[3] / "README.md"
63
+
64
+
65
+ def has_pkg(pkg_name):
66
+ """
67
+ Helper function to generically check if a package is installed. Intended
68
+ to be used to check for optional dependencies.
69
+
70
+ Parameters
71
+ ----------
72
+ pkg_name : str
73
+ The name of the package to check the availability of
74
+
75
+ Returns
76
+ -------
77
+ pkg_available : bool
78
+ Boolean indicator if the package is available or not
79
+
80
+ Examples
81
+ --------
82
+ >>> has_numpy = has_pkg('numpy')
83
+ >>> has_numpy
84
+ True
85
+ >>> has_foo = has_pkg('other_non_installed_pkg')
86
+ >>> has_foo
87
+ False
88
+ """
89
+ try:
90
+ importlib.import_module(pkg_name)
91
+ except ModuleNotFoundError:
92
+ return False
93
+ return True
94
+
95
+
96
+ def requires_pkg(pkg_name, reason=None):
97
+ """
98
+ Helper function to generate a pytest.mark.skipif decorator
99
+ for any package. This allows tests to be skipped if some
100
+ optional dependency is not found.
101
+
102
+ Parameters
103
+ ----------
104
+ pkg_name : str
105
+ The name of the package that is required for a test(s)
106
+ reason : str, optional
107
+ Explanation of why the skipped it to be tested
108
+
109
+ Returns
110
+ -------
111
+ requires_pkg : _pytest.mark.structures.MarkDecorator
112
+ A pytest decorator that will skip tests if the package is not available
113
+ """
114
+ if not reason:
115
+ reason = f"Package {pkg_name} is required, but was not found."
116
+ requires_pkg = pytest.mark.skipif(not has_pkg(pkg_name), reason=reason)
117
+ return requires_pkg
118
+
119
+
120
+ @contextmanager
121
+ def does_not_raise():
122
+ """A helpful context manager to use inplace of a pytest raise statement
123
+ when no exception is expected."""
124
+ yield
125
+
126
+
127
+ def get_amber_file_path(prefix):
128
+ """Get AMBER prmtop and inpcrd test data filepaths.
129
+
130
+ Parameters
131
+ ----------
132
+ prefix : str
133
+ The file name without extension of .prmtop and .inpcrd
134
+ files to retrieve from testdata/systems/amber.
135
+
136
+ Returns
137
+ -------
138
+ prmtop_filepath : str
139
+ Absolute path to the AMBER prmtop filepath in testdata/systems/amber
140
+ inpcrd_filepath : str
141
+ Absolute path to the AMBER inpcrd filepath in testdata/systems/amber
142
+
143
+ """
144
+ prefix = os.path.join("systems", "amber", prefix)
145
+ prmtop_filepath = get_data_file_path(prefix + ".prmtop")
146
+ inpcrd_filepath = get_data_file_path(prefix + ".inpcrd")
147
+ return prmtop_filepath, inpcrd_filepath
148
+
149
+
150
+ def get_packmol_pdb_file_path(prefix="cyclohexane_ethanol_0.4_0.6"):
151
+ """Get PDB filename for a packmol-generated box
152
+
153
+ Parameters
154
+ ----------
155
+ prefix : str, optional, default='cyclohexane_ethanol_0.4_0.6'
156
+ The prefix of .pdb file to retrieve from testdata/systems/packmol_boxes
157
+
158
+ Returns
159
+ -------
160
+ pdb_filename : str
161
+ Absolute path to the PDB file
162
+ """
163
+ prefix = os.path.join("systems", "packmol_boxes", prefix)
164
+ pdb_filename = get_data_file_path(prefix + ".pdb")
165
+ return pdb_filename
166
+
167
+
168
+ def get_monomer_mol2_file_path(prefix="ethanol"):
169
+ """Get absolute filepath for a mol2 file denoting a small molecule monomer in testdata
170
+
171
+ Parameters
172
+ ----------
173
+ prefix : str, optional, default='ethanol'
174
+ The prefix of .mol2 file to retrieve from systems/monomers/
175
+
176
+ Returns
177
+ -------
178
+ mol2_filename : str
179
+ Absolute path to the mol2 file
180
+ """
181
+ # TODO: The mol2 files in this folder are not tripos mol2 files. Delete or convert them.
182
+ prefix = os.path.join("systems", "monomers", prefix)
183
+ mol2_filename = get_data_file_path(prefix + ".mol2")
184
+ return mol2_filename
185
+
186
+
187
+ def extract_compressed_molecules(tar_file_name, file_subpaths=None, filter_func=None):
188
+ if (file_subpaths is None) == (filter_func is None):
189
+ raise ValueError("Only one between file_subpaths and filter_func must be specified.")
190
+
191
+ # Find the path of the tarfile with respect to the data/molecules/ folder.
192
+ molecules_dir_path = get_data_file_path("molecules")
193
+ tar_file_path = os.path.join(molecules_dir_path, tar_file_name)
194
+ tar_root_dir_name = tar_file_name.split(".")[0]
195
+
196
+ # Return value: Paths to the extracted molecules.
197
+ extracted_file_paths = None
198
+
199
+ # Handle subpaths search.
200
+ if file_subpaths is not None:
201
+ # We can already check the paths of the extracted files
202
+ # and skipping opening the tarball if not necessary.
203
+ extracted_file_paths = [
204
+ os.path.join(molecules_dir_path, tar_root_dir_name, file_subpath) for file_subpath in file_subpaths
205
+ ]
206
+
207
+ # Remove files that we have already extracted.
208
+ # Also, we augument the subpath with its root directory.
209
+ file_subpaths_set = {
210
+ os.path.join(tar_root_dir_name, subpath)
211
+ for subpath, fullpath in zip(file_subpaths, extracted_file_paths)
212
+ if not os.path.isfile(fullpath)
213
+ }
214
+
215
+ # If everything was already extracted, we don't need to open the tarball.
216
+ if len(file_subpaths_set) == 0:
217
+ return extracted_file_paths
218
+
219
+ # Otherwise, create a filter matching only the subpaths.
220
+ def filter_func(x):
221
+ return x in file_subpaths_set
222
+
223
+ # If no filter was specified, just create one matching everything.
224
+ if filter_func is None:
225
+
226
+ def filter_func(x):
227
+ return True
228
+
229
+ # Determine opening mode.
230
+ if ".gz" in tar_file_name:
231
+ mode = "r:gz"
232
+ else:
233
+ mode = "r"
234
+
235
+ # Extract required files.
236
+ import tarfile
237
+
238
+ with tarfile.open(tar_file_path, mode) as tar_file:
239
+ # Gather the paths to extract. Remove the
240
+ members = [m for m in tar_file.getmembers() if filter_func(m.name)]
241
+
242
+ # Built the paths to the extracted molecules we didn't already.
243
+ if extracted_file_paths is None:
244
+ extracted_file_paths = [os.path.join(molecules_dir_path, m.name) for m in members]
245
+
246
+ # Extract only the members that we haven't already extracted.
247
+ members = [member for member, fullpath in zip(members, extracted_file_paths) if not os.path.isfile(fullpath)]
248
+ tar_file.extractall(path=molecules_dir_path, members=members)
249
+
250
+ return extracted_file_paths
251
+
252
+
253
+ def get_alkethoh_file_path(alkethoh_name, get_amber=False):
254
+ """Retrieve the mol2, top and crd files of a molecule in the AlkEthOH set.
255
+
256
+ Parameters
257
+ ----------
258
+ alkethoh_name : str
259
+ The name of the AlkEthOH molecule (e.g. "AlkEthOH_r0", "AlkEthOH_c1266").
260
+ get_amber : bool, optional
261
+ If True, the paths to the top and crd files are returned.
262
+
263
+ Returns
264
+ -------
265
+ molecule_file_paths : str or list[str]
266
+ All the requested paths. If ``get_amber`` is False, only a single string
267
+ pointing to the path of the mol2 file is returned, otherwise this is a
268
+ list ``[mol2_path, top_path, crd_path]``.
269
+
270
+ """
271
+ # Determine if this is a ring or a chain molecule and the subfolder name.
272
+ is_ring = alkethoh_name[9] == "r"
273
+ alkethoh_subdir_name = "rings" if is_ring else "chain"
274
+ alkethoh_subdir_name = "AlkEthOH_" + alkethoh_subdir_name + "_filt1"
275
+
276
+ # Determine which paths have to be returned.
277
+ file_base_subpath = os.path.join(alkethoh_subdir_name, alkethoh_name)
278
+ # We always return the mol2 file.
279
+ file_subpaths = [file_base_subpath + "_tripos.mol2"]
280
+ # Check if we need to return also Amber files.
281
+ if get_amber:
282
+ file_subpaths.append(file_base_subpath + ".top")
283
+ file_subpaths.append(file_base_subpath + ".crd")
284
+
285
+ return extract_compressed_molecules("AlkEthOH_tripos.tar.gz", file_subpaths=file_subpaths)
286
+
287
+
288
+ def get_freesolv_file_path(freesolv_id, ff_version):
289
+ file_base_name = "mobley_" + freesolv_id
290
+ mol2_file_subpath = os.path.join("mol2files_sybyl", file_base_name + ".mol2")
291
+ xml_dir = "xml_" + ff_version.replace(".", "_")
292
+ xml_file_subpath = os.path.join(xml_dir, file_base_name + "_vacuum.xml")
293
+
294
+ # Extract the files if needed.
295
+ file_subpaths = [mol2_file_subpath, xml_file_subpath]
296
+ return extract_compressed_molecules("FreeSolv.tar.gz", file_subpaths=file_subpaths)
297
+
298
+
299
+ def create_system_from_amber(prmtop_file_path, inpcrd_file_path, *args, **kwargs):
300
+ """Create an OpenMM System and Topology from the AMBER files.
301
+
302
+ Parameters
303
+ ----------
304
+ prmtop_file_path : str
305
+ Path to the topology/parameter file in AMBER prmtop format.
306
+ inpcrd_file_path : str
307
+ Path to the coordinates file in AMBER inpcrd or rst7 format.
308
+ *args
309
+ **kwargs
310
+ Other parameters to pass to ``openmm.app.AmberPrmtopFile.createSystem``.
311
+
312
+ Returns
313
+ -------
314
+ system : openmm.System
315
+ The OpenMM ``System`` object with the parameters.
316
+ topology : openmm.app.Topology
317
+ The OpenMM ``Topology`` object loaded from the AMBER files.
318
+ positions : openmm.unit.Quantity
319
+ Initial positions loaded from the inpcrd or restart file.
320
+
321
+ """
322
+ prmtop_file = openmm.app.AmberPrmtopFile(prmtop_file_path)
323
+ # AmberInpcrdFile parses also rst7 files.
324
+ inpcrd_file = openmm.app.AmberInpcrdFile(inpcrd_file_path)
325
+ # Create system and update box vectors (if needed)
326
+ system = prmtop_file.createSystem(*args, **kwargs)
327
+ if inpcrd_file.boxVectors is not None:
328
+ system.setDefaultPeriodicBoxVectors(*inpcrd_file.boxVectors)
329
+ # Store numpy positions.
330
+ positions = inpcrd_file.getPositions(asNumpy=True)
331
+ return system, prmtop_file.topology, positions
332
+
333
+
334
+ def quantities_allclose(quantity1, quantity2, **kwargs):
335
+ """Check if two Quantity objects are close.
336
+
337
+ If the quantities are arrays, all their elements must be close.
338
+ If the given arguments are unitless, this simply calls numpy.allclose().
339
+
340
+ Parameters
341
+ ----------
342
+ quantity1 : openmm.unit.Quantity
343
+ The first unit to compare.
344
+ quantity2 : openmm.unit.Quantity
345
+ The second unit to compare.
346
+ **kwargs
347
+ Other parameters passed to ``numpy.allclose()``.
348
+
349
+ Returns
350
+ -------
351
+ is_close : bool
352
+ True if the two quantities are close, False otherwise.
353
+
354
+ """
355
+ if isinstance(quantity1, openmm_unit.Quantity):
356
+ # Check that the two Quantities have compatible units.
357
+ if not quantity1.unit.is_compatible(quantity2.unit):
358
+ raise ValueError(f"The two quantities don't have compatible units: {quantity1.unit} and {quantity2.unit}")
359
+ # Compare the values stripped of the units.
360
+ quantity1 = quantity1.value_in_unit_system(openmm_unit.md_unit_system)
361
+ quantity2 = quantity2.value_in_unit_system(openmm_unit.md_unit_system)
362
+ return np.allclose(quantity1, quantity2, **kwargs)
363
+
364
+
365
+ def get_context_potential_energy(context, positions, box_vectors=None, by_force_group=True):
366
+ """Compute the potential energy of a System in a Context object.
367
+
368
+ This is simply a shortcut that takes care of setting
369
+ box vectors and positions before computing the energy.
370
+
371
+ Parameters
372
+ ----------
373
+ context : openmm.Context
374
+ The Context object containing the system.
375
+ positions : openmm.unit.Quantity
376
+ A n_atoms x 3 arrays of coordinates with units of length.
377
+ box_vectors : openmm.unit.Quantity, optional
378
+ If specified, this should be a 3 x 3 array. Each row should
379
+ be a box vector.
380
+ by_force_group : bool, optional
381
+ If True, it returns a dictionary mapping force groups to
382
+ their potential energies. Default is True.
383
+
384
+ Returns
385
+ -------
386
+ potential_energy : openmm.unit.Quantity or dict[type, Quantity]
387
+ The potential energy of the system at the given coordinates.
388
+ If ``by_force_group`` is True, then this is a dictionary
389
+ mapping force groups to their potential energy.
390
+
391
+ """
392
+ # Box vectors must be updated before positions are set.
393
+ if box_vectors is not None:
394
+ context.setPeriodicBoxVectors(*box_vectors)
395
+ context.setPositions(positions)
396
+
397
+ # If we don't have energies by force group,
398
+ # just return the energy of the full System.
399
+ if not by_force_group:
400
+ return context.getState(getEnergy=True).getPotentialEnergy()
401
+
402
+ # Determine how many force groups we need to compute.
403
+ force_groups = {f.getForceGroup() for f in context.getSystem().getForces()}
404
+
405
+ # Compute potential energies of all groups.
406
+ potential_energies = {}
407
+ for force_group in force_groups:
408
+ state = context.getState(getEnergy=True, groups={force_group})
409
+ potential_energies[force_group] = state.getPotentialEnergy()
410
+ return potential_energies
411
+
412
+
413
+ class FailedEnergyComparisonError(AssertionError):
414
+ """Error raised when the energy comparison between two system fails.
415
+
416
+ Attributes
417
+ ----------
418
+ potential_energy1
419
+ potential_energy2
420
+
421
+ """
422
+
423
+ def __init__(self, err_msg, potential_energy1, potential_energy2):
424
+ super().__init__(err_msg)
425
+ self.potential_energy1 = potential_energy1
426
+ self.potential_energy2 = potential_energy2
427
+
428
+
429
+ def compare_context_energies(context1, context2, *args, rtol=1.0e-5, atol=1.0e-8, **kwargs):
430
+ """Compare energies of two Contexts given the same positions.
431
+
432
+ Parameters
433
+ ----------
434
+ context1 : openmm.Context
435
+ The first Context object to compare containing the system.
436
+ context2 : openmm.Context
437
+ The second Context object to compare containing the system.
438
+ positions : openmm.unit.Quantity
439
+ A n_atoms x 3 arrays of coordinates with units of length.
440
+ rtol : float, optional, default=1e-5
441
+ The relative tolerance parameter used for the energy comparisons.
442
+ atol : float, optional, default=1e-8
443
+ The absolute tolerance parameter used for the energy comparisons.
444
+ box_vectors : openmm.unit.Quantity, optional
445
+ If specified, this should be a 3 x 3 array. Each row should
446
+ be a box vector.
447
+ by_force_group : bool, optional
448
+ If True, the energies of each force groups are compared.
449
+ Default is True.
450
+
451
+ Returns
452
+ -------
453
+ potential_energy1 : openmm.unit.Quantity or dict[int, Quantity]
454
+ The potential energy of context1 at the given coordinates.
455
+ If ``by_force_group`` is True, then this is a dictionary
456
+ mapping force groups to their potential energy.
457
+ potential_energy2 : openmm.unit.Quantity or dict[int, Quantity]
458
+ The potential energy of context2 at the given coordinates.
459
+ If ``by_force_group`` is True, then this is a dictionary
460
+ mapping force groups to their potential energy.
461
+
462
+ Raises
463
+ ------
464
+ FailedEnergyComparisonError
465
+ If the potential energies of the two contexts are different
466
+ or if the two Systems in the contexts have forces divided into
467
+ different force groups. The potential energies of context1 and
468
+ context2 can be accessed in the Exception through the attributes
469
+ potential_energy1 and potential_energy2 respectively.
470
+
471
+ """
472
+ potential_energy1 = get_context_potential_energy(context1, *args, **kwargs)
473
+ potential_energy2 = get_context_potential_energy(context2, *args, **kwargs)
474
+
475
+ def raise_assert(assertion, err_msg, format_args):
476
+ """Shortcut to raise a custom error and format the error message."""
477
+ if not assertion:
478
+ raise FailedEnergyComparisonError(err_msg.format(*format_args), potential_energy1, potential_energy2)
479
+
480
+ # If by_force_group is True, then the return value will be a
481
+ # dictionary and we need to compare force group by force group.
482
+ if isinstance(potential_energy1, openmm_unit.Quantity):
483
+ raise_assert(
484
+ assertion=quantities_allclose(potential_energy1, potential_energy2, rtol=rtol, atol=atol),
485
+ err_msg="potential energy 1 {}, potential energy 2: {}",
486
+ format_args=(potential_energy1, potential_energy2),
487
+ )
488
+ else: # potential_energy1 is a dict.
489
+ # If the two context expose different force groups raise an error.
490
+ raise_assert(
491
+ assertion=set(potential_energy1) == set(potential_energy2),
492
+ err_msg="The two contexts have different force groups: context1 {}, context2 {}",
493
+ format_args=(sorted(potential_energy1), sorted(potential_energy2)),
494
+ )
495
+
496
+ # Check the potential energies of all force groups.
497
+ for force_group in potential_energy1:
498
+ energy1 = potential_energy1[force_group]
499
+ energy2 = potential_energy2[force_group]
500
+ raise_assert(
501
+ assertion=quantities_allclose(energy1, energy2, rtol=rtol, atol=atol),
502
+ err_msg="Force group {} do not have the same energies: context1 {}, context2 {}",
503
+ format_args=(force_group, energy1, energy2),
504
+ )
505
+
506
+ return potential_energy1, potential_energy2
507
+
508
+
509
+ def compare_system_energies(
510
+ system1,
511
+ system2,
512
+ positions,
513
+ box_vectors=None,
514
+ by_force_type=True,
515
+ ignore_charges=False,
516
+ modify_system=False,
517
+ rtol=1.0e-5,
518
+ atol=1.0e-8,
519
+ ):
520
+ """Compare energies of two Systems given the same positions.
521
+
522
+ Parameters
523
+ ----------
524
+ system1 : openmm.System
525
+ The first Context object to compare containing the system.
526
+ system2 : openmm.System
527
+ The second Context object to compare containing the system.
528
+ positions : openmm.unit.Quantity
529
+ A n_atoms x 3 arrays of coordinates with units of length.
530
+ box_vectors : openmm.unit.Quantity, optional
531
+ If specified, this should be a 3 x 3 array. Each row should
532
+ be a box vector.
533
+ by_force_type : bool, optional
534
+ If True, the contribution to the energy of each force type
535
+ is compared instead of just the overall potential energy.
536
+ Default is True.
537
+ ignore_charges : bool, optional
538
+ If True, particle and exception charges are ignored during
539
+ the comparison. Default is False.
540
+ modify_system : bool, optional
541
+ If either ``by_force_type`` or ``ignore_charges`` are True,
542
+ the function will change the force groups of two ``Systems``
543
+ to compute the separate contributions. Set this to False to
544
+ work on a copy and avoid modifying the original objects.
545
+ Default is False.
546
+ rtol : float, optional, default=1e-5
547
+ The relative tolerance parameter used for the energy comparisons.
548
+ atol : float, optional, default=1e-8
549
+ The absolute tolerance parameter used for the energy comparisons.
550
+
551
+ Returns
552
+ -------
553
+ potential_energy1 : openmm.unit.Quantity or dict[str, Quantity]
554
+ The potential energy of context1 at the given coordinates.
555
+ If ``by_force_type`` is True, then this is a dictionary
556
+ mapping force names to their potential energy.
557
+ potential_energy2 : openmm.unit.Quantity or dict[str, Quantity]
558
+ The potential energy of context2 at the given coordinates.
559
+ If ``by_force_type`` is True, then this is a dictionary
560
+ mapping force names to their potential energy.
561
+
562
+ Raises
563
+ ------
564
+ FailedEnergyComparisonError
565
+ If the potential energies of the two contexts are different
566
+ or if the two Systems in the contexts have forces divided into
567
+ different force groups. The potential energies of context1 and
568
+ context2 can be accessed in the Exception through the attributes
569
+ potential_energy1 and potential_energy2 respectively.
570
+
571
+ """
572
+ # Make a copy of the systems if requested.
573
+ if not modify_system and (by_force_type or ignore_charges):
574
+ system1 = copy.deepcopy(system1)
575
+ system2 = copy.deepcopy(system2)
576
+
577
+ # Group force types into OpenMM force groups.
578
+ if by_force_type:
579
+ # Remove eventual CMMotionRemover forces that do not affect energies.
580
+ for system in [system1, system2]:
581
+ for force_idx, force in enumerate(system.getForces()):
582
+ if isinstance(force, openmm.CMMotionRemover):
583
+ system.removeForce(force_idx)
584
+ break
585
+
586
+ # First check that the two systems have the same force types.
587
+ force_names1 = {f.__class__.__name__ for f in system1.getForces()}
588
+ force_names2 = {f.__class__.__name__ for f in system2.getForces()}
589
+ if set(force_names1) != set(force_names2):
590
+ err_msg = "The two Systems have different forces to compare:\n - system1 {}\n - system2 {}"
591
+ raise ValueError(err_msg.format(sorted(force_names1), sorted(force_names2)))
592
+
593
+ # Create a map from force group to force class and viceversa.
594
+ group_to_force = {i: force_name for i, force_name in enumerate(force_names1)}
595
+ force_to_group = {force_name: i for i, force_name in group_to_force.items()}
596
+
597
+ # Assign force groups.
598
+ for system in [system1, system2]:
599
+ for force in system.getForces():
600
+ force.setForceGroup(force_to_group[force.__class__.__name__])
601
+
602
+ # If we need to ignore the charges, turn off particle and exceptions charges.
603
+ if ignore_charges:
604
+ for system in [system1, system2]:
605
+ # Find the NonbondedForce.
606
+ nonbonded_force = None
607
+ for force in system.getForces():
608
+ if isinstance(force, openmm.NonbondedForce):
609
+ nonbonded_force = force
610
+
611
+ # We checked before that the two systems have the same force
612
+ # types so we can break the loop if there are no NonbondedForces.
613
+ if nonbonded_force is None:
614
+ break
615
+
616
+ # Set particle charges to 0.0.
617
+ for particle_idx in range(nonbonded_force.getNumParticles()):
618
+ _, sigma, epsilon = nonbonded_force.getParticleParameters(particle_idx)
619
+ nonbonded_force.setParticleParameters(particle_idx, 0.0, sigma, epsilon)
620
+
621
+ # Set particle exceptions charge products to 0.0.
622
+ for exception_idx in range(nonbonded_force.getNumExceptions()):
623
+ (
624
+ atom1,
625
+ atom2,
626
+ _,
627
+ sigma,
628
+ epsilon,
629
+ ) = nonbonded_force.getExceptionParameters(exception_idx)
630
+ nonbonded_force.setExceptionParameters(exception_idx, atom1, atom2, 0.0, sigma, epsilon)
631
+
632
+ # Create Contexts and compare the energies.
633
+ integrator = openmm.VerletIntegrator(1.0 * openmm_unit.femtoseconds)
634
+
635
+ context1 = openmm.Context(system1, integrator, openmm.Platform.getPlatformByName("Reference"))
636
+ context2 = openmm.Context(system2, copy.deepcopy(integrator), openmm.Platform.getPlatformByName("Reference"))
637
+
638
+ def map_energies_by_force_type(potential_energy1, potential_energy2):
639
+ """Convert dictionary force_group -> energy to force_type -> energy."""
640
+ potential_energy1 = {group_to_force[group]: energy for group, energy in potential_energy1.items()}
641
+ potential_energy2 = {group_to_force[group]: energy for group, energy in potential_energy2.items()}
642
+ return potential_energy1, potential_energy2
643
+
644
+ # Catch the exception and log table force type -> energy.
645
+ try:
646
+ potential_energy1, potential_energy2 = compare_context_energies(
647
+ context1,
648
+ context2,
649
+ positions,
650
+ box_vectors,
651
+ by_force_group=by_force_type,
652
+ rtol=rtol,
653
+ atol=atol,
654
+ )
655
+ except FailedEnergyComparisonError as e:
656
+ # We don't need to convert force groups into force types
657
+ if not by_force_type:
658
+ raise
659
+ # Add to the error message the table of energies by force type.
660
+ potential_energy1, potential_energy2 = map_energies_by_force_type(e.potential_energy1, e.potential_energy2)
661
+ # Pretty-print the dictionaries.
662
+ table = "\n\npotential energy system1:\n" + pprint.pformat(potential_energy1)
663
+ table += "\n\npotential energy system2:\n" + pprint.pformat(potential_energy2)
664
+ raise type(e)(str(e) + table, e.potential_energy1, e.potential_energy2)
665
+
666
+ if by_force_type:
667
+ return map_energies_by_force_type(potential_energy1, potential_energy2)
668
+ return potential_energy1, potential_energy2
669
+
670
+
671
+ class _ParametersComparer:
672
+ """This is just a convenience class to compare and print parameters.
673
+
674
+ Parameters
675
+ ----------
676
+ **kwargs
677
+ All the parameters to compare.
678
+
679
+ Attributes
680
+ ----------
681
+ parameters : dict
682
+ The dictionary of parameters.
683
+
684
+ Examples
685
+ --------
686
+ >>> import copy
687
+ >>> from openmm import unit
688
+ >>> par1 = _ParametersComparer(charge=1.0*unit.elementary_charge,
689
+ ... rmin_half=1.5*unit.angstrom)
690
+ >>> par2 = copy.deepcopy(par1)
691
+ >>> par3 = _ParametersComparer(charge=-1.0*unit.elementary_charge,
692
+ ... rmin_half=0.15*unit.nanometers)
693
+ >>> par1 == par2
694
+ True
695
+ >>> par1 == par3
696
+ False
697
+ >>> str(par1)
698
+ '(charge: 1.0 e, rmin_half: 1.5 A)'
699
+
700
+ """
701
+
702
+ def __init__(self, **parameters):
703
+ self.parameters = parameters
704
+
705
+ def remove_parameters(self, parameter_names):
706
+ for parameter_name in parameter_names:
707
+ try:
708
+ del self.parameters[parameter_name]
709
+ except KeyError:
710
+ pass
711
+
712
+ def pretty_format_diff(self, other, new_line=True, indent=True):
713
+ """Return a pretty-formatted string describing the differences between parameters.
714
+
715
+ Parameters
716
+ ----------
717
+ other : _ParametersComparer
718
+ new_line : bool, optional
719
+ Separate different parameters with new lines.
720
+ indent : bool, optional
721
+ Indent the formatting.
722
+
723
+ Returns
724
+ -------
725
+ diff_str : str
726
+
727
+ """
728
+ diff = self._get_diff(other)
729
+ diff_list = []
730
+ for par_name in sorted(diff.keys()):
731
+ par1, par2 = diff[par_name]
732
+ diff_list.append(f"{par_name}: {par1} != {par2}")
733
+ separator = "\n" if new_line else ""
734
+ diff_str = separator.join(diff_list)
735
+ if indent:
736
+ diff_str = textwrap.indent(diff_str, prefix=" ")
737
+ return diff_str
738
+
739
+ def _get_diff(self, other):
740
+ """Build a 'diff' including only the parameters that are different."""
741
+ assert set(self.parameters.keys()) == set(other.parameters.keys())
742
+ diff = {}
743
+ for par_name, par1_value in self.parameters.items():
744
+ par2_value = other.parameters[par_name]
745
+ # Determine whether this parameter is close or not.
746
+ if not quantities_allclose(par1_value, par2_value):
747
+ diff[par_name] = (par1_value, par2_value)
748
+ return diff
749
+
750
+ def __eq__(self, other):
751
+ return len(self._get_diff(other)) == 0
752
+
753
+ def __str__(self):
754
+ # Reorder the parameters to print in deterministic order.
755
+ parameter_order = sorted(self.parameters)
756
+ # Quantities in a dictionary are normally printed in the
757
+ # format "Quantity(value, unit=unit)" so we make it prettier.
758
+ par_str = ", ".join(f"{p}: {self.parameters[p]}" for p in parameter_order)
759
+ return "(" + par_str + ")"
760
+
761
+
762
+ class _TorsionParametersComparer:
763
+ """A ParametersComparer class for torsions.
764
+
765
+ Torsions require a different comparison because multiple set of
766
+ (periodicity, phase, k) parameters can be associated to the same
767
+ four atoms.
768
+
769
+ Parameters
770
+ ----------
771
+ *parameters
772
+ Variable length arguments. Each is a _ParametersComparer instance.
773
+
774
+ Attributes
775
+ ----------
776
+ parameters : list[_ParametersComparer]
777
+ The list of _ParametersComparer instances.
778
+
779
+ Examples
780
+ --------
781
+ >>> from openmm import unit
782
+ >>> par1 = _ParametersComparer(periodicity=2, phase=0.0*unit.degrees)
783
+ >>> par2 = _ParametersComparer(periodicity=4, phase=180.0*unit.degrees)
784
+ >>> torsion_par = _TorsionParametersComparer(par1, par2)
785
+
786
+ """
787
+
788
+ def __init__(self, *parameters):
789
+ # *args is a tuple. Convert it to a list to make it appendable.
790
+ self.parameters = list(parameters)
791
+
792
+ def pretty_format_diff(self, other, new_line=True, indent=True):
793
+ """Return a pretty-formatted string describing the differences between parameters.
794
+
795
+ Parameters
796
+ ----------
797
+ other : _TorsionParametersComparer
798
+ new_line : bool, optional
799
+ Separate different parameters with new lines.
800
+ indent : bool, optional
801
+ Indent the formatting.
802
+
803
+ Returns
804
+ -------
805
+ diff_str : str
806
+
807
+ """
808
+ diff_str = "Parameters in first system:\n"
809
+ diff_str += self._pretty_format_parameters(self.parameters, new_line=new_line)
810
+ diff_str += "\nParameters in second system:\n"
811
+ diff_str += self._pretty_format_parameters(other.parameters, new_line=new_line)
812
+ if indent:
813
+ diff_str = textwrap.indent(diff_str, " ")
814
+ return diff_str
815
+
816
+ def _pretty_format_parameters(self, parameters, new_line=True, indent=True):
817
+ # Reorder the parameters by periodicity and then phase to print in deterministic order.
818
+ def sort_key(x):
819
+ return x.parameters["periodicity"], x.parameters["phase"]
820
+
821
+ parameters = sorted(parameters, key=sort_key)
822
+ # Quantities in a dictionary are normally printed in the
823
+ # format "Quantity(value, unit=unit)" so we make it prettier.
824
+ separator = "\n" if new_line else ", "
825
+ prefix = "["
826
+ if indent and new_line:
827
+ separator += " "
828
+ elif indent:
829
+ prefix += " "
830
+ return prefix + separator.join(str(pars) for pars in parameters) + "]"
831
+
832
+ def __eq__(self, other):
833
+ # Look for self.parameters that don't match any other.parameters.
834
+ for parameters1 in self.parameters:
835
+ # Find at least 1 set of parameters in the list that are equal.
836
+ if all(parameters1 != parameters2 for parameters2 in other.parameters):
837
+ return False
838
+
839
+ # Look for other.parameters that don't match any other self.parameters.
840
+ for parameters2 in other.parameters:
841
+ # Find at least 1 set of parameters in the list that are equal.
842
+ if all(parameters1 != parameters2 for parameters1 in self.parameters):
843
+ return False
844
+ return True
845
+
846
+ def __str__(self):
847
+ return self._pretty_format_parameters(self.parameters, new_line=False, indent=False)
848
+
849
+
850
+ class FailedParameterComparisonError(AssertionError):
851
+ """Error raised when the parameter comparison between two forces fails.
852
+
853
+ Attributes
854
+ ----------
855
+ different_parameters : dict[Hashable, tuple[_ParameterComparer]]
856
+ All the parameters for which a differences was detected.
857
+ different_parameters[atom_indices] is a tuple
858
+ (parameter_force1, parameter_force2).
859
+
860
+ """
861
+
862
+ def __init__(self, err_msg, different_parameters):
863
+ super().__init__(err_msg)
864
+ self.different_parameters = different_parameters
865
+
866
+
867
+ def _compare_parameters(
868
+ parameters_force1,
869
+ parameters_force2,
870
+ interaction_type,
871
+ force_name="",
872
+ systems_labels=None,
873
+ ):
874
+ """Compare the parameters of 2 forces and raises an exception if they are different.
875
+
876
+ Parameters
877
+ ----------
878
+ parameters_force1 : dict[Hashable, _ParametersComparer]
879
+ A dictionary associating a _ParametersComparer entry to a key
880
+ that is usually a set of atom indices (e.g., the atom index
881
+ for nonbonded interactions, two atom indices for bonds and
882
+ 1-4 exceptions, 3 indices for angles, and 4 for torsions).
883
+ parameters_force2 : dict[Hashable, _ParametersComparer]
884
+ The parameters of the force to compare.
885
+ interaction_type : str
886
+ A string describing the type of interactions (e.g., "bond",
887
+ "particle exception", "proper torsion"). This is only used to
888
+ improve the error message where differences between the two
889
+ forces are detected.
890
+ force_name : str, optional
891
+ The name of the force to optionally include in the eventual
892
+ error message.
893
+ systems_labels : tuple[str], optional
894
+ A pair of strings with a meaningful name for the system. If
895
+ specified, this will be included in the error message to
896
+ improve its readability.
897
+
898
+ Raises
899
+ ------
900
+ FailedParameterComparisonError
901
+ If there are differences in the parameters of the two forces.
902
+ The exceptions exposes an attribute ``different_parameters``
903
+ with the different parameters.
904
+
905
+ """
906
+ diff_msg = ""
907
+
908
+ # First check the parameters that are unique to only one of the forces.
909
+ unique_keys1 = set(parameters_force1) - set(parameters_force2)
910
+ unique_keys2 = set(parameters_force2) - set(parameters_force1)
911
+ err_msg = "\n\n{} force has the following unique " + interaction_type + "s: {}\n"
912
+ if len(unique_keys1) != 0:
913
+ force_label = systems_labels[0] if systems_labels is not None else "First"
914
+ diff_msg += err_msg.format(force_label, sorted(unique_keys1))
915
+ if len(unique_keys2) != 0:
916
+ force_label = systems_labels[1] if systems_labels is not None else "Second"
917
+ diff_msg += err_msg.format(force_label, sorted(unique_keys2))
918
+
919
+ # Create a diff for entries that have same keys but different parameters.
920
+ different_parameters = {}
921
+ for key in set(parameters_force1).intersection(set(parameters_force2)):
922
+ if parameters_force1[key] != parameters_force2[key]:
923
+ different_parameters[key] = (parameters_force1[key], parameters_force2[key])
924
+
925
+ # Handle force and systems labels default arguments.
926
+ if force_name != "":
927
+ force_name += " " # Add space after.
928
+ if systems_labels is not None:
929
+ systems_labels = " for the {} and {} systems respectively".format(*systems_labels)
930
+ else:
931
+ systems_labels = ""
932
+
933
+ # Print error.
934
+ if len(different_parameters) > 0:
935
+ diff_msg += (
936
+ f"\n\nThe following {interaction_type}s have different parameters "
937
+ f"in the two {force_name}forces{systems_labels}:"
938
+ )
939
+ for key in sorted(different_parameters.keys()):
940
+ param1, param2 = different_parameters[key]
941
+ parameters_diff = param1.pretty_format_diff(param2)
942
+ diff_msg += f"\n{interaction_type} {key}:\n{parameters_diff}"
943
+
944
+ if diff_msg != "":
945
+ diff_msg = (f"A difference between {interaction_type} was detected. Details follow.") + diff_msg
946
+ raise FailedParameterComparisonError(diff_msg + "\n", different_parameters)
947
+
948
+
949
+ @functools.singledispatch
950
+ def _get_force_parameters(force, system, ignored_parameters):
951
+ """This function builds a _ParameterComparer representation of the
952
+ force parameters that can be used for comparison to other forces
953
+ with _compare_parameters.
954
+
955
+ Each _ParameterComparer must be associated to a key, which is usually
956
+ a tuple of atom indices (e.g., the atom index for nonbonded interactions,
957
+ two atom indices for bonds and 1-4 exceptions, 3 indices for angles,
958
+ and 4 for torsions).
959
+
960
+ A single force can generate multiple representations (e.g., a NonbondedForce
961
+ can generate one representations for particle parameters and one for
962
+ parameter exceptions.
963
+
964
+ Parameters
965
+ ----------
966
+ force
967
+ The OpenMM Force object.
968
+ system : openmm.System
969
+ The System to which this force belongs to.
970
+ ignored_parameters : Iterable[str]
971
+ The parameters to ignore in the comparison.
972
+
973
+ Returns
974
+ -------
975
+ force_parameters : dict[str, dict[Hashable, _ParameterComparer]]
976
+ The parameter representation. force_parameters[interaction_type]
977
+ is a dictionary mapping a tuple of atom indices to the
978
+ associated parameters. interaction_type can be any string
979
+ identifying the type of parameters (e.g. "particle exception",
980
+ "proper torsion", "bond").
981
+
982
+ """
983
+ raise NotImplementedError(f"Comparison between {type(force)}s is not currently supported.")
984
+
985
+
986
+ @_get_force_parameters.register(openmm.HarmonicBondForce)
987
+ def _get_bond_force_parameters(force, _, ignored_parameters):
988
+ """Implementation of _get_force_parameters for HarmonicBondForces."""
989
+ # Build the dictionary of the parameters of a single force.
990
+ force_parameters = {}
991
+ for bond_idx in range(force.getNumBonds()):
992
+ atom1, atom2, r0, k = force.getBondParameters(bond_idx)
993
+
994
+ # Ignore bonds with 0.0 spring constant that don't affect the energy.
995
+ if k._value == 0.0:
996
+ continue
997
+
998
+ # Reorder the bond to have a canonical key.
999
+ bond_key = tuple(sorted([atom1, atom2]))
1000
+ force_parameters[bond_key] = _ParametersComparer(r0=r0, k=k)
1001
+ force_parameters[bond_key].remove_parameters(ignored_parameters)
1002
+
1003
+ return {"bond": force_parameters}
1004
+
1005
+
1006
+ @_get_force_parameters.register(openmm.HarmonicAngleForce)
1007
+ def _get_angle_force_parameters(force, _, ignored_parameters):
1008
+ """Implementation of _get_force_parameters for HarmonicAngleForces."""
1009
+ # Build the dictionary of the parameters of a single force.
1010
+ force_parameters = {}
1011
+ for angle_idx in range(force.getNumAngles()):
1012
+ atom1, atom2, atom3, theta0, k = force.getAngleParameters(angle_idx)
1013
+
1014
+ # Ignore angles with 0.0 spring constant that don't affect the energy.
1015
+ if k._value == 0.00:
1016
+ continue
1017
+
1018
+ # Reorder the bond to have a canonical key.
1019
+ angle_key = min(atom1, atom3), atom2, max(atom1, atom3)
1020
+ force_parameters[angle_key] = _ParametersComparer(theta0=theta0, k=k)
1021
+ force_parameters[angle_key].remove_parameters(ignored_parameters)
1022
+
1023
+ return {"angle": force_parameters}
1024
+
1025
+
1026
+ @_get_force_parameters.register(openmm.NonbondedForce)
1027
+ def _get_nonbonded_force_parameters(force, _, ignored_parameters):
1028
+ """Implementation of _get_force_parameters for NonbondedForces."""
1029
+ # Build the dictionary of the particle parameters of the force.
1030
+ particle_parameters = {}
1031
+ for particle_idx in range(force.getNumParticles()):
1032
+ charge, sigma, epsilon = force.getParticleParameters(particle_idx)
1033
+
1034
+ # Ignore sigma parameter if epsilon is 0.0.
1035
+ particle_parameters[particle_idx] = _ParametersComparer(charge=charge, epsilon=epsilon)
1036
+ if epsilon._value != 0.0:
1037
+ particle_parameters[particle_idx].parameters["sigma"] = sigma
1038
+ particle_parameters[particle_idx].remove_parameters(ignored_parameters)
1039
+
1040
+ # Build the dictionary representation of the particle exceptions.
1041
+ exception_parameters = {}
1042
+ for exception_idx in range(force.getNumExceptions()):
1043
+ atom1, atom2, chargeprod, sigma, epsilon = force.getExceptionParameters(exception_idx)
1044
+
1045
+ # Reorder the atom indices to have a canonical key.
1046
+ exception_key = tuple(sorted([atom1, atom2]))
1047
+ # Ignore sigma parameter if epsilon is 0.0.
1048
+ exception_parameters[exception_key] = _ParametersComparer(charge=chargeprod, epsilon=epsilon)
1049
+ if epsilon._value != 0.0:
1050
+ exception_parameters[exception_key].parameters["sigma"] = sigma
1051
+ exception_parameters[exception_key].remove_parameters(ignored_parameters)
1052
+
1053
+ return {"particle": particle_parameters, "particle exception": exception_parameters}
1054
+
1055
+
1056
+ def _merge_impropers_folds(improper_parameters):
1057
+ """Merge impropers with same periodicities and phases into a single folds.
1058
+
1059
+ See _get_torsion_force_parameters.
1060
+
1061
+ """
1062
+ for improper_comparer in improper_parameters.values():
1063
+ # Group parameters by periodicity and phase and sum force constants.
1064
+ for comparer2_idx in reversed(range(1, len(improper_comparer.parameters))):
1065
+ parameter_comparer2 = improper_comparer.parameters[comparer2_idx]
1066
+ parameters2 = parameter_comparer2.parameters
1067
+
1068
+ # parameter_comparer1 comes before parameter_comparer2 in the list.
1069
+ for parameter_comparer1 in improper_comparer.parameters[:comparer2_idx]:
1070
+ parameters1 = parameter_comparer1.parameters
1071
+
1072
+ # If phase and periodicity match, sum the force constants
1073
+ # and remove one _ParametersComparer object from the list.
1074
+ if (parameters1["phase"] == parameters2["phase"]) and (
1075
+ parameters1["periodicity"] == parameters2["periodicity"]
1076
+ ):
1077
+ # Update the force constant of the first parameter.
1078
+ parameters1["k"] += parameters2["k"]
1079
+ # Remove the second parameter from the list.
1080
+ del improper_comparer.parameters[comparer2_idx]
1081
+ break
1082
+
1083
+
1084
+ @_get_force_parameters.register(openmm.PeriodicTorsionForce)
1085
+ def _get_torsion_force_parameters(force, system, ignored_parameters):
1086
+ """Implementation of _get_force_parameters for NonbondedForces.
1087
+
1088
+ If the special attribute 'n_improper_folds' is in ignored_parameters,
1089
+ then impropers with same periodicity and phases are merged into a
1090
+ single set of parameters having the sum of the force constants as k.
1091
+ This allows to compare parameters before and after the 0.1 version of
1092
+ the toolkit, in which the six-fold implementation was changed into
1093
+ the current three-fold.
1094
+
1095
+ """
1096
+ if "n_improper_folds" not in ignored_parameters:
1097
+ ignore_n_folds = False
1098
+ else:
1099
+ ignore_n_folds = True
1100
+ # Create a copy of ignored_parameters without n_improper_folds
1101
+ # that must be removed later from the _ParametersComparer object.
1102
+ ignored_parameters = copy.deepcopy(ignored_parameters)
1103
+ ignored_parameters.remove("n_improper_folds")
1104
+
1105
+ # Find all bonds. We'll use this to distinguish
1106
+ # between proper and improper torsions.
1107
+ bond_set = _find_all_bonds(system)
1108
+
1109
+ proper_parameters = {}
1110
+ improper_parameters = {}
1111
+ for torsion_idx in range(force.getNumTorsions()):
1112
+ atom1, atom2, atom3, atom4, periodicity, phase, k = force.getTorsionParameters(torsion_idx)
1113
+
1114
+ # Ignore torsions that don't contribute to the energy.
1115
+ if k._value == 0.0:
1116
+ continue
1117
+
1118
+ torsion_key = [atom1, atom2, atom3, atom4]
1119
+ if len(set(torsion_key)) != 4:
1120
+ raise ValueError(f"Torsion {torsion_idx} is defined on less than 4 atoms: {torsion_key}")
1121
+
1122
+ # Check if this is proper or not.
1123
+ torsion_bonds = [(torsion_key[i], torsion_key[i + 1]) for i in range(3)]
1124
+ is_proper = all(bond in bond_set for bond in torsion_bonds)
1125
+
1126
+ # Determine the canonical order of the torsion key.
1127
+ if is_proper:
1128
+ torsion_key = _get_proper_torsion_canonical_order(*torsion_key)
1129
+ force_parameters = proper_parameters
1130
+ else:
1131
+ torsion_key = _get_improper_torsion_canonical_order(bond_set, *torsion_key)
1132
+ force_parameters = improper_parameters
1133
+
1134
+ # Update the dictionary representation.
1135
+ parameters = _ParametersComparer(periodicity=periodicity, phase=phase, k=k)
1136
+ parameters.remove_parameters(ignored_parameters)
1137
+ # Each set of 4 atoms can have multiple torsion terms.
1138
+ try:
1139
+ force_parameters[torsion_key].parameters.append(parameters)
1140
+ except KeyError:
1141
+ force_parameters[torsion_key] = _TorsionParametersComparer(parameters)
1142
+
1143
+ # Sum the force constants of all the improper torsion folds. This
1144
+ # is fundamental to compare parameters with versions of the toolkit
1145
+ # previous to 0.1, where the trefoil improper was six-fold rather
1146
+ # than three-fold as in the current version.
1147
+ if ignore_n_folds:
1148
+ _merge_impropers_folds(improper_parameters)
1149
+
1150
+ return {
1151
+ "proper torsion": proper_parameters,
1152
+ "improper torsion": improper_parameters,
1153
+ }
1154
+
1155
+
1156
+ def _find_all_bonds(system):
1157
+ """Find all bonds in the given system
1158
+
1159
+ Parameters
1160
+ ----------
1161
+ system : openmm.System
1162
+ A System object containing a HarmonicBondForce from which the
1163
+ bonds are inferred.
1164
+
1165
+ Returns
1166
+ -------
1167
+ bond_set : set[tuple[int]]
1168
+ A set of pairs (atom_index1, atom_index2) associated to bonds.
1169
+ For each bond two pairs are created with the atom indices in
1170
+ inverse order.
1171
+
1172
+ """
1173
+ # Find the force with information on the bonds.
1174
+ bond_force = [f for f in system.getForces() if isinstance(f, openmm.HarmonicBondForce)]
1175
+ assert len(bond_force) == 1
1176
+ bond_force = bond_force[0]
1177
+
1178
+ # Create a set of all bonds.
1179
+ bond_set = set()
1180
+ for bond_idx in range(bond_force.getNumBonds()):
1181
+ atom1, atom2, _, _ = bond_force.getBondParameters(bond_idx)
1182
+ bond_set.add((atom1, atom2))
1183
+ bond_set.add((atom2, atom1))
1184
+
1185
+ # Find all the constrained bonds, which do not have a HarmonicBondForce term.
1186
+ for constraint_idx in range(system.getNumConstraints()):
1187
+ atom1, atom2, _ = system.getConstraintParameters(constraint_idx)
1188
+ bond_set.add((atom1, atom2))
1189
+ bond_set.add((atom2, atom1))
1190
+
1191
+ return bond_set
1192
+
1193
+
1194
+ def _get_proper_torsion_canonical_order(i0, i1, i2, i3):
1195
+ """Create a unique order of the 4 atom indices of a proper torsion.
1196
+
1197
+ The atom indices of a proper torsion are reordered so that the
1198
+ first atom is the smallest index.
1199
+
1200
+ Parameters
1201
+ ----------
1202
+ i0, i1, i2, i3 : int
1203
+ Atom indices of the proper torsion.
1204
+
1205
+ Returns
1206
+ -------
1207
+ j0, j1, j2, j3 : int
1208
+ Reordered atom indices of the proper torsion.
1209
+
1210
+ """
1211
+ if i0 < i3:
1212
+ return i0, i1, i2, i3
1213
+ else:
1214
+ return i3, i2, i1, i0
1215
+
1216
+
1217
+ def _get_improper_torsion_canonical_order(bond_set, i0, i1, i2, i3):
1218
+ """Create a unique order of the 4 atom indices of an improper torsion.
1219
+
1220
+ Return j0, j1, j2, j3, where j0 is the central index and j1, j2, j3
1221
+ are in sorted() order. The centrality is determined by the maximum
1222
+ counts in the adjacency matrix.
1223
+
1224
+ Parameters
1225
+ ----------
1226
+ bond_set : set
1227
+ The set of all bonds as determined by _find_all_bonds.
1228
+ i0, i1, i2, i3 : int,
1229
+ Atom indices of the improper torsion.
1230
+
1231
+ Returns
1232
+ -------
1233
+ j0, j1, j2, j3 : int
1234
+ Reordered atom indices of the improper torsion, with j0 being
1235
+ the central index.
1236
+
1237
+ """
1238
+ connections = np.zeros((4, 4))
1239
+
1240
+ mapping = {i0: 0, i1: 1, i2: 2, i3: 3}
1241
+ inv_mapping = dict([(val, key) for key, val in mapping.items()])
1242
+
1243
+ for a, b in itertools.combinations([i0, i1, i2, i3], 2):
1244
+ if (a, b) in bond_set:
1245
+ i, j = mapping[a], mapping[b]
1246
+ connections[i, j] += 1.0
1247
+ connections[j, i] += 1.0
1248
+
1249
+ central_ind = connections.sum(0).argmax()
1250
+ central_ind = inv_mapping[central_ind]
1251
+ other_ind = sorted([i0, i1, i2, i3])
1252
+ other_ind.remove(central_ind)
1253
+
1254
+ return central_ind, other_ind[0], other_ind[1], other_ind[2]
1255
+
1256
+
1257
+ def compare_system_parameters(
1258
+ system1,
1259
+ system2,
1260
+ systems_labels=None,
1261
+ ignore_charges=False,
1262
+ ignore_improper_folds=False,
1263
+ ):
1264
+ """Check that two OpenMM systems have the same parameters.
1265
+
1266
+ Parameters
1267
+ ----------
1268
+ system1 : openmm.System
1269
+ The first system to compare.
1270
+ system2 : openmm.System
1271
+ The second system to compare.
1272
+ systems_labels : tuple[str], optional
1273
+ A pair of strings with a meaningful name for the system. If
1274
+ specified, this will be included in the error message to
1275
+ improve its readability.
1276
+ ignore_charges : bool, optional
1277
+ If True, particle and exception charges are ignored during
1278
+ the comparison. Default is False.
1279
+ ignore_improper_folds : bool, optional
1280
+ If True, all the folds of the same impropers are merged into
1281
+ a single one for the purpose of parameter comparison. Default
1282
+ is False.
1283
+
1284
+ Raises
1285
+ ------
1286
+ FailedParameterComparisonError
1287
+ If there are differences in the parameters of the two forces.
1288
+ The exceptions exposes an attribute ``different_parameters``
1289
+ with the different parameters.
1290
+
1291
+ """
1292
+ # Determine parameters to ignore.
1293
+ ignored_parameters_by_force = {}
1294
+ if ignore_charges:
1295
+ ignored_parameters_by_force["NonbondedForce"] = ["charge", "chargeprod"]
1296
+ if ignore_improper_folds:
1297
+ ignored_parameters_by_force["PeriodicTorsionForce"] = ["n_improper_folds"]
1298
+
1299
+ # We need to perform some checks on the type and number of forces in the Systems.
1300
+ force_names1 = collections.Counter(f.__class__.__name__ for f in system1.getForces())
1301
+ force_names2 = collections.Counter(f.__class__.__name__ for f in system2.getForces())
1302
+ err_msg = "Only systems having 1 force per type are supported."
1303
+ assert set(force_names1.values()) == {1}, err_msg
1304
+ assert set(force_names2.values()) == {1}, err_msg
1305
+
1306
+ # Remove the center-of-mass motion remover force from comparison.
1307
+ for force_names in [force_names1, force_names2]:
1308
+ if "CMMotionRemover" in force_names:
1309
+ del force_names["CMMotionRemover"]
1310
+
1311
+ # Check that the two systems have the same forces.
1312
+ if set(force_names1) != set(force_names2):
1313
+ err_msg = "The two Systems have different forces to compare:\n - system1 {}\n - system2 {}"
1314
+ raise ValueError(err_msg.format(sorted(force_names1), sorted(force_names2)))
1315
+
1316
+ # Find all the pair of forces to compare.
1317
+ force_pairs = {force_name: [] for force_name in force_names1}
1318
+ for system in [system1, system2]:
1319
+ for force in system.getForces():
1320
+ # Skip CMMotionRemover.
1321
+ if force.__class__.__name__ == "CMMotionRemover":
1322
+ continue
1323
+ force_pairs[force.__class__.__name__].append(force)
1324
+
1325
+ # TODO: ParmEd-derived system representations separate out vdW from ES (putting ES in NonbondedForce
1326
+ # and vdW in CustomNonbondedForce with precomputed mixing parameters). We'll need to update this to
1327
+ # somehow account for the difference.
1328
+
1329
+ # Compare all pairs of forces
1330
+ for force_name, (force1, force2) in force_pairs.items():
1331
+ # Select the parameters to ignore.
1332
+ try:
1333
+ ignored_parameters = ignored_parameters_by_force[force_name]
1334
+ except KeyError:
1335
+ ignored_parameters = ()
1336
+
1337
+ # Get a dictionary representation of the parameters.
1338
+ parameters_force1 = _get_force_parameters(force1, system1, ignored_parameters)
1339
+ parameters_force2 = _get_force_parameters(force2, system2, ignored_parameters)
1340
+
1341
+ # Compare the forces and raise an error if a difference is detected.
1342
+ for parameter_type, parameters1 in parameters_force1.items():
1343
+ parameters2 = parameters_force2[parameter_type]
1344
+ _compare_parameters(
1345
+ parameters1,
1346
+ parameters2,
1347
+ interaction_type=parameter_type,
1348
+ force_name=force_name,
1349
+ systems_labels=systems_labels,
1350
+ )
1351
+
1352
+
1353
+ def compare_amber_smirnoff(
1354
+ prmtop_file_path,
1355
+ inpcrd_file_path,
1356
+ forcefield,
1357
+ molecule,
1358
+ check_parameters=True,
1359
+ check_energies=True,
1360
+ **kwargs,
1361
+ ):
1362
+ """
1363
+ Compare energies and parameters for OpenMM Systems/topologies created
1364
+ from an AMBER prmtop and crd versus from a SMIRNOFF force field file which
1365
+ should parameterize the same system with same parameters.
1366
+
1367
+ Parameters
1368
+ ----------
1369
+ prmtop_file_path : str
1370
+ Path to the topology/parameter file in AMBER prmtop format
1371
+ inpcrd_file_path : str
1372
+ Path to the coordinates file in AMBER inpcrd or rst7 format
1373
+ forcefield : ForceField
1374
+ Force field instance used to create the system to compare.
1375
+ molecule : topology.molecule.Molecule
1376
+ The molecule object to test.
1377
+ check_parameters : bool, optional
1378
+ If False, parameters are not compared. Energies are still comapred
1379
+ if ``check_energies`` is ``True`` (default is ``True``).
1380
+ check_parameters : bool, optional
1381
+ If False, energies are not compared and they are not returned.
1382
+ Parameters are not compared if ``check_energies`` is ``True``
1383
+ (default is ``True``).
1384
+ ignore_charges : bool, optional
1385
+ If True, particle and exception charges are ignored during
1386
+ the comparison. Default is False.
1387
+
1388
+ Returns
1389
+ -------
1390
+ energies : dict[str, dict[str, openmm.unit.Quantity]] or None
1391
+ If ``check_energies`` is ``False``, nothing is returned. Otherwise,
1392
+ this is a dictionary with two keys: 'AMBER' and 'SMIRNOFF', each
1393
+ pointing to another dictionary mapping forces to their total
1394
+ contribution to the potential energy.
1395
+
1396
+ Raises
1397
+ ------
1398
+ FailedEnergyComparisonError
1399
+ If the potential energies of the two systems are different
1400
+ or if the two Systems in the contexts have forces divided into
1401
+ different force groups. The potential energies of the AMBER and
1402
+ ForceField systems can be accessed in the Exception through the
1403
+ attributes potential_energy1 and potential_energy2 respectively.
1404
+ FailedParameterComparisonError
1405
+ If there are differences in the parameters of the two systems.
1406
+ The exceptions exposes an attribute ``different_parameters``
1407
+ with the different parameters.
1408
+
1409
+ """
1410
+ from openff.toolkit.topology import Topology
1411
+
1412
+ # Create System from AMBER files. By default, contrarily to ForceField,
1413
+ # systems from AMBER files are created with removeCMMotion=True
1414
+ amber_system, openmm_topology, positions = create_system_from_amber(
1415
+ prmtop_file_path, inpcrd_file_path, removeCMMotion=False
1416
+ )
1417
+ box_vectors = amber_system.getDefaultPeriodicBoxVectors()
1418
+
1419
+ # Create System from force field.
1420
+ openff_topology = Topology.from_openmm(openmm_topology, unique_molecules=[molecule])
1421
+ ff_system = forcefield.create_openmm_system(openff_topology)
1422
+
1423
+ # Test energies and parameters.
1424
+ if check_parameters:
1425
+ compare_system_parameters(amber_system, ff_system, systems_labels=("AMBER", "SMIRNOFF"), **kwargs)
1426
+
1427
+ if check_energies:
1428
+ amber_energies, forcefield_energies = compare_system_energies(
1429
+ amber_system, ff_system, positions, box_vectors, **kwargs
1430
+ )
1431
+
1432
+ return {"AMBER": amber_energies, "SMIRNOFF": forcefield_energies}
1433
+ return None
1434
+
1435
+
1436
+ def reorder_openff_to_openmm(xyz, n_atoms_per_mol, n_vptls_per_mol):
1437
+ """
1438
+ Rearrange the coordinates of an OpenFF-created system to an order
1439
+ that OpenMM uses/used.
1440
+
1441
+ This function is mainly used to compare with a system that was created with
1442
+ OpenMM, where the ordering is AAABBAAABB and was created elsewhere. This will
1443
+ reorder the OpenFF particles such that they match with this ordering.
1444
+
1445
+ xyz : list[list[float]]
1446
+ The atom and virtual positions
1447
+ n_atoms_per_mol : int
1448
+ The number of atoms per molecule. All molecules are assumed to have the
1449
+ same number of atoms.
1450
+ n_vptls_per_mol : int
1451
+ The number of virtual particles per molecule. All molecules are assumed
1452
+ to have the same number of virtual particles
1453
+
1454
+ Returns:
1455
+ xyz : list[list[float]]
1456
+ The atom and virtual particle positions in OpenFF order
1457
+ """
1458
+
1459
+ n_particles_per_mol = n_atoms_per_mol + n_vptls_per_mol
1460
+ n_mols = xyz.shape[0] // n_particles_per_mol
1461
+
1462
+ atom_base_indices = np.arange(n_atoms_per_mol)
1463
+ vsite_base_indices = np.arange(n_vptls_per_mol) + n_atoms_per_mol * n_mols
1464
+
1465
+ mask = np.hstack(
1466
+ [
1467
+ np.hstack(
1468
+ [
1469
+ atom_base_indices + (i * n_atoms_per_mol),
1470
+ vsite_base_indices + (i * n_vptls_per_mol),
1471
+ ]
1472
+ )
1473
+ for i in range(n_mols)
1474
+ ]
1475
+ )
1476
+
1477
+ return xyz[mask]
1478
+
1479
+
1480
+ def reorder_openmm_to_openff(xyz, n_atoms_per_mol, n_vptls_per_mol):
1481
+ """
1482
+ Rearrange the coordinates of an OpenMM-created system to an order
1483
+ that OpenFF uses.
1484
+
1485
+ For example, since OpenMM creates virtual sites in-place, they are interleaved
1486
+ with the atoms. This means that, if atoms are labeled as A and virtual sites
1487
+ as B, then the ordering will be AAABBAAABB, and the index is 0 to 9.
1488
+ This function will reorder the coordinates to be AAAAAABBBB, which is the order
1489
+ OpenFF expects/uses.
1490
+
1491
+ xyz : list[list[float]]
1492
+ The atom and virtual positions
1493
+ n_atoms_per_mol : int
1494
+ The number of atoms per molecule. All molecules are assumed to have the
1495
+ same number of atoms.
1496
+ n_vptls_per_mol : int
1497
+ The number of virtual particles per molecule. All molecules are assumed
1498
+ to have the same number of virtual particles
1499
+
1500
+ Returns:
1501
+ xyz : list[list[float]]
1502
+ The atom and virtual particle positions in OpenFF order
1503
+ """
1504
+
1505
+ # constants for simplicity
1506
+ n_particles_per_mol = n_atoms_per_mol + n_vptls_per_mol
1507
+ n_mols = xyz.shape[0] // n_particles_per_mol
1508
+
1509
+ atom_base_indices = np.arange(n_atoms_per_mol)
1510
+ atom_indices = np.hstack([atom_base_indices + (i * n_particles_per_mol) for i in range(n_mols)])
1511
+
1512
+ vsite_base_indices = np.arange(n_vptls_per_mol) + n_atoms_per_mol
1513
+ vsite_indices = np.hstack([vsite_base_indices + (i * n_particles_per_mol) for i in range(n_mols)])
1514
+
1515
+ mask = np.hstack([atom_indices, vsite_indices])
1516
+
1517
+ return xyz[mask]
1518
+
1519
+
1520
+ def openmm_evaluate_vsites_and_energy(omm_top, omm_sys, atom_xyz_in_nm, minimize=False):
1521
+ """
1522
+ Calculate the Virtual Site positions and potential energy
1523
+ of the given system
1524
+
1525
+ Parameters
1526
+ ----------
1527
+ omm_top: OpenMM Topology
1528
+ omm_sys: OpenMM System
1529
+ atom_xyz_in_nm: list[list[float]]
1530
+ An N,3 array of floats interpreted as nanometers of the atom positions
1531
+ minimize: bool
1532
+ Perform a minimization before calculating energy
1533
+
1534
+ Returns
1535
+ -------
1536
+ pos: list[list[float]]
1537
+ The coordinates of all particles in the system (OpenMM ordering)
1538
+ ene: float
1539
+ The potential energy
1540
+ """
1541
+
1542
+ integ = openmm.VerletIntegrator(1.0 * openmm_unit.femtoseconds)
1543
+
1544
+ sim = openmm.app.Simulation(omm_top, omm_sys, integ)
1545
+ pos = sim.context.getState(getPositions=True).getPositions()
1546
+
1547
+ sim.context.setPositions(atom_xyz_in_nm)
1548
+
1549
+ # Once the atom positions are known, virtual sites can
1550
+ # be determined.
1551
+ sim.context.computeVirtualSites()
1552
+
1553
+ if minimize:
1554
+ sim.minimizeEnergy()
1555
+
1556
+ state = sim.context.getState(getEnergy=True, getPositions=True)
1557
+ ene = state.getPotentialEnergy()
1558
+ pos = [list(xyz) for xyz in state.getPositions().value_in_unit(openmm_unit.nanometer)] * unit.nanometer
1559
+ return pos, ene
1560
+
1561
+
1562
+ def insert_vsite_padding(xyz, n_mol, n_vptl, order="OpenFF"):
1563
+ """
1564
+ Given a set of atomic coordinates, insert dummy coordinates in indices
1565
+ expected for either OpenFF or OpenMM. OpenFF places the dummy coordinates
1566
+ at the end, whereas OpenMM expects virtual sites to be next to their owning
1567
+ molecule.
1568
+
1569
+ Parameters
1570
+ ----------
1571
+ xyz: list[list[float]]
1572
+ An Nx3 set of coordinates of atoms only
1573
+ n_mol: int
1574
+ The number of molecules
1575
+ n_vptl: int
1576
+ The number of virtual site particle dummy positions to insert
1577
+
1578
+ Returns
1579
+ -------
1580
+ xyz : list[list[float]]
1581
+ The coordinates of shape (N+n_vsite,3) with all particles in the expected order
1582
+ """
1583
+
1584
+ # heuristic that vsites come at the end; applies to OpenFF
1585
+ vsite_pad = np.arange(n_vptl * 3).reshape(n_vptl, 3)
1586
+ xyz = np.vstack([xyz, vsite_pad])
1587
+
1588
+ # but does not apply to OpenMM. Need to interleave vsite coordinates
1589
+ if order == "OpenMM":
1590
+ n_vptls_per_mol = n_vptl // n_mol
1591
+ n_atoms_per_mol = len(xyz) // n_mol - n_vptls_per_mol
1592
+ xyz = reorder_openff_to_openmm(xyz, n_atoms_per_mol, n_vptls_per_mol)
1593
+
1594
+ return xyz
1595
+
1596
+
1597
+ def coords_from_off_mols(mols, conformer_id=0, unit=unit.angstrom):
1598
+ """
1599
+ Small utility to extract the coordinates from the molecule conformers,
1600
+ with optional unit conversion
1601
+
1602
+ Parameters
1603
+ ----------
1604
+ mols : list[openff.toolkit.topology.molecule.Molecule]
1605
+ The system/list of molecules
1606
+ conformer_id : int, default=0
1607
+ The conformer to use for retreiving the coordinates from each molcule
1608
+ unit : openmm.unit, default=unit.angstrom
1609
+ The units to convert the coordinates to
1610
+ """
1611
+ xyz = np.vstack([mol.conformers[conformer_id].m_as(unit) for mol in mols])
1612
+ return xyz * unit
1613
+
1614
+
1615
+ def evaluate_molecules_omm(water, ff, minimize=False):
1616
+ """
1617
+ Given a list of molecules and a force field definition, calculate the
1618
+ positions and energy.
1619
+
1620
+ Parameters
1621
+ ----------
1622
+ molecules: list[openff.toolkit.topology.molecule.Molecule]
1623
+ A list of molecules with a 3D conformation
1624
+ forcefield: openff.toolkit.typing.engines.smirnoff.forcefield.ForceField
1625
+ The force field object to parameterize with
1626
+ minimize: bool
1627
+ Whether the structure should be minimized
1628
+
1629
+ Returns
1630
+ -------
1631
+ xyz: list[list[float]]
1632
+ The coordinates of all particles in the system (OpenMM ordering)
1633
+ ene: float
1634
+ The potential energy
1635
+ """
1636
+
1637
+ from openff.toolkit.topology import Topology
1638
+
1639
+ top = Topology.from_molecules(water).to_openmm()
1640
+
1641
+ # get the oFF topology and the positions
1642
+ atom_xyz = to_openmm(coords_from_off_mols(water, unit=unit.nanometer))
1643
+
1644
+ # first pass; no virtual sites
1645
+ omm_modeller = openmm.app.Modeller(top, atom_xyz)
1646
+ omm_modeller.addExtraParticles(ff)
1647
+
1648
+ # second pass: virtual sites now present (according to oMM FF)
1649
+ top = omm_modeller.getTopology()
1650
+
1651
+ sys = ff.createSystem(top, nonbondedMethod=openmm.app.NoCutoff)
1652
+ n_vptl = sys.getNumParticles() - len(atom_xyz)
1653
+ n_mol = len(water)
1654
+
1655
+ # need to insert dummy positions into coordinates, since OpenMM
1656
+ # systems create virtual site particles in place, i.e. OHHMMOHHMM etc.
1657
+ atom_xyz = insert_vsite_padding(atom_xyz, n_mol, n_vptl, order="OpenMM")
1658
+
1659
+ # Need an openMM topology, an openMM system, and a set of positions
1660
+ # to calculate the energy. Also returns the vsite positions based
1661
+ # on supplied atom coordinates
1662
+ xyz, ene = openmm_evaluate_vsites_and_energy(top, sys, atom_xyz, minimize=minimize)
1663
+
1664
+ return xyz, ene
1665
+
1666
+
1667
+ def evaluate_molecules_off(molecules, forcefield, minimize=False):
1668
+ """
1669
+ Given a list of molecules and a force field definition, calculate the
1670
+ positions and energy.
1671
+
1672
+ Parameters
1673
+ ----------
1674
+ molecules: list[openff.toolkit.topology.molecule.Molecule]
1675
+ A list of molecules with a 3D conformation
1676
+ forcefield: openff.toolkit.typing.engines.smirnoff.forcefield.ForceField
1677
+ The force field object to parameterize with
1678
+ minimize: bool
1679
+ Whether the structure should be minimized
1680
+
1681
+ Returns
1682
+ -------
1683
+ xyz: list[list[float]]
1684
+ The coordinates of all particles in the system (OpenMM ordering)
1685
+ ene: float
1686
+ The potential energy
1687
+ """
1688
+
1689
+ from openff.toolkit.topology import Topology
1690
+
1691
+ # get the oFF topology and the positions
1692
+ top = Topology.from_molecules(molecules)
1693
+ atom_xyz = to_openmm(coords_from_off_mols(molecules, unit=unit.nanometer))
1694
+
1695
+ # IMPORTANT! The new system has the virtual sites, but the oFF top does not as there is no API yet to do so
1696
+ sys = forcefield.create_openmm_system(top, allow_nonintegral_charges=True)
1697
+
1698
+ n_vptl = sys.getNumParticles() - len(atom_xyz)
1699
+ n_mol = len(molecules)
1700
+ atom_xyz = insert_vsite_padding(atom_xyz, n_mol, n_vptl, order="OpenFF")
1701
+
1702
+ # Need an openMM topology, an openMM system, and a set of positions
1703
+ # to calculate the energy. Also returns the vsite positions based
1704
+ # on supplied atom coordinates
1705
+ xyz, ene = openmm_evaluate_vsites_and_energy(top.to_openmm(), sys, atom_xyz, minimize=minimize)
1706
+
1707
+ return xyz, ene
1708
+
1709
+
1710
+ def get_14_scaling_factors(omm_sys: openmm.System) -> tuple[list, list]:
1711
+ """Find the 1-4 scaling factors as they are applied to an OpenMM System"""
1712
+ nonbond_force = next(f for f in omm_sys.getForces() if type(f) is openmm.NonbondedForce)
1713
+
1714
+ vdw_14 = list()
1715
+ coul_14 = list()
1716
+
1717
+ for exception_idx in range(nonbond_force.getNumExceptions()):
1718
+ i, j, q, _, eps = nonbond_force.getExceptionParameters(exception_idx)
1719
+
1720
+ # Trust that q == 0 covers the cases of 1-2, 1-3, and truly being 0
1721
+ if q._value != 0:
1722
+ q_i = nonbond_force.getParticleParameters(i)[0]
1723
+ q_j = nonbond_force.getParticleParameters(j)[0]
1724
+ coul_14.append(q / (q_i * q_j))
1725
+
1726
+ if eps._value != 0:
1727
+ eps_i = nonbond_force.getParticleParameters(i)[2]
1728
+ eps_j = nonbond_force.getParticleParameters(j)[2]
1729
+ vdw_14.append(eps / (eps_i * eps_j) ** 0.5)
1730
+
1731
+ return coul_14, vdw_14
1732
+
1733
+
1734
+ def compare_partial_charges(system1, system2):
1735
+ assert system1.getNumParticles() == system2.getNumParticles(), "Systems do not have the same number of particles"
1736
+
1737
+ n_particles = system1.getNumParticles()
1738
+
1739
+ for force1 in system1.getForces():
1740
+ if type(force1) is openmm.NonbondedForce:
1741
+ charges1 = [force1.getParticleParameters(i)[0] for i in range(n_particles)]
1742
+
1743
+ for force2 in system2.getForces():
1744
+ if type(force2) is openmm.NonbondedForce:
1745
+ charges2 = [force2.getParticleParameters(i)[0] for i in range(n_particles)]
1746
+
1747
+ assert charges1 == charges2, [(x - y) for x, y in zip(charges1, charges2)]