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,3864 @@
1
+ """
2
+ Tests for forcefield class
3
+
4
+ """
5
+
6
+ import copy
7
+ import itertools
8
+ import os
9
+ from tempfile import NamedTemporaryFile
10
+
11
+ import numpy as np
12
+ import openmm
13
+ import pytest
14
+ from numpy.testing import assert_almost_equal
15
+ from openff.units.openmm import from_openmm, to_openmm
16
+ from openmm import NonbondedForce, Platform, XmlSerializer, app
17
+ from openmm import unit as openmm_unit
18
+ from pydantic import ValidationError
19
+
20
+ from openff.toolkit import unit
21
+ from openff.toolkit._tests.create_molecules import (
22
+ create_acetate,
23
+ create_cyclohexane,
24
+ create_ethanol,
25
+ create_reversed_ethanol,
26
+ create_water,
27
+ )
28
+ from openff.toolkit._tests.utils import (
29
+ compare_partial_charges,
30
+ get_14_scaling_factors,
31
+ requires_openeye,
32
+ requires_openeye_mol2,
33
+ requires_rdkit,
34
+ )
35
+ from openff.toolkit.topology import Molecule, Topology
36
+ from openff.toolkit.typing.engines.smirnoff import (
37
+ ElectrostaticsHandler,
38
+ ForceField,
39
+ LibraryChargeHandler,
40
+ ParameterHandler,
41
+ ToolkitAM1BCCHandler,
42
+ XMLParameterIOHandler,
43
+ get_available_force_fields,
44
+ vdWHandler,
45
+ )
46
+ from openff.toolkit.utils import (
47
+ AmberToolsToolkitWrapper,
48
+ BuiltInToolkitWrapper,
49
+ OpenEyeToolkitWrapper,
50
+ RDKitToolkitWrapper,
51
+ ToolkitRegistry,
52
+ get_data_file_path,
53
+ )
54
+ from openff.toolkit.utils.exceptions import (
55
+ ChargeMethodUnavailableError,
56
+ IncompatibleParameterError,
57
+ ParameterLookupError,
58
+ SMIRNOFFAromaticityError,
59
+ SMIRNOFFSpecError,
60
+ SMIRNOFFSpecUnimplementedError,
61
+ SMIRNOFFVersionError,
62
+ )
63
+
64
+ XML_FF_GENERICS = """<?xml version='1.0' encoding='ASCII'?>
65
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
66
+ <Bonds version="0.4" potential="harmonic" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
67
+ <Bond smirks="[*:1]~[*:2]" id="b1" k="680.0 * kilocalories_per_mole/angstrom**2" length="1.09 * angstrom"/>
68
+ </Bonds>
69
+ <Angles version="0.3">
70
+ <Angle smirks="[*:1]~[*:2]~[*:3]" angle="109.5 * degree" id="a1" k="100.0 * kilocalories_per_mole/radian**2"/>
71
+ </Angles>
72
+ <ProperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))">
73
+ <Proper smirks="[*:1]~[*:2]~[*:3]-[*:4]" id="t1" idivf1="1" k1="0.156 * kilocalories_per_mole" periodicity1="3" phase1="0.0 * degree"/>
74
+ </ProperTorsions>
75
+ <ImproperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))">
76
+ <Improper smirks="[*:1]~[*:2](~[*:3])~[*:4]" id="i1" k1="1.1 * kilocalories_per_mole" periodicity1="2" phase1="180. * degree"/>
77
+ </ImproperTorsions>
78
+ <vdW version="0.3" potential="Lennard-Jones-12-6" combining_rules="Lorentz-Berthelot" scale12="0.0" scale13="0.0" scale14="0.5" scale15="1" switch_width="1.0 * angstrom" cutoff="9.0 * angstrom" method="cutoff">
79
+ <Atom smirks="[*:1]" epsilon="0.0157 * kilocalories_per_mole" id="n1" rmin_half="0.6000 * angstrom"/>
80
+ </vdW>
81
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
82
+ <ToolkitAM1BCC version="0.3"/>
83
+ </SMIRNOFF>
84
+ """
85
+
86
+ xml_without_section_version = """<?xml version="1.0" encoding="ASCII"?>
87
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
88
+ <ToolkitAM1BCC/>
89
+ </SMIRNOFF>
90
+ """
91
+
92
+ xml_simple_ff = """<?xml version='1.0' encoding='ASCII'?>
93
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
94
+ <Bonds version="0.3">
95
+ <Bond smirks="[#6X4:1]-[#6X4:2]" id="b1" k="620.0 * kilocalories_per_mole/angstrom**2" length="1.526 * angstrom"/>
96
+ <Bond smirks="[#6X4:1]-[#6X3:2]" id="b2" k="634.0 * kilocalories_per_mole/angstrom**2" length="1.51 * angstrom"/>
97
+ <Bond smirks="[#6X3:1]-[#6X3:2]" id="b3" k_bondorder1="100.0*kilocalories_per_mole/angstrom**2" k_bondorder2="4000.0*kilocalories_per_mole/angstrom**2" length="1.5 * angstrom"/>
98
+ </Bonds>
99
+ <Angles version="0.3">
100
+ <Angle smirks="[*:1]~[#6X4:2]-[*:3]" angle="109.5 * degree" id="a1" k="100.0 * kilocalories_per_mole/radian**2"/>
101
+ <Angle smirks="[#1:1]-[#6X4:2]-[#1:3]" angle="109.5 * degree" id="a2" k="70.0 * kilocalories_per_mole/radian**2"/>
102
+ </Angles>
103
+ <ProperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
104
+ <Proper smirks="[*:1]-[#6X4:2]-[#6X4:3]-[*:4]" id="t1" idivf1="1" k1="0.156 * kilocalories_per_mole" periodicity1="3" phase1="0.0 * degree"/>
105
+ <Proper smirks="[#6X4:1]-[#6X4:2]-[#6X4:3]-[#6X4:4]" id="t2" idivf1="1" k1="0.180 * kilocalories_per_mole" periodicity1="3" phase1="0.0 * degree" periodicity2="2" phase2="180.0 * degree" idivf2="1" k2="0.250 * kilocalories_per_mole" periodicity3="1" phase3="180.0 * degree" idivf3="1" k3="0.200 * kilocalories_per_mole"/>
106
+ <Proper smirks="[*:1]:[#6X4:2]~[#6X4:3]:[*:4]" periodicity1="2" phase1="0.0 * degree" k1_bondorder1="1.00*kilocalories_per_mole" k1_bondorder2="1.80*kilocalories_per_mole" idivf1="1.0"/>
107
+ </ProperTorsions>
108
+ <ImproperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))">
109
+ <Improper smirks="[*:1]~[#6X3:2](~[*:3])~[*:4]" id="i1" k1="1.1 * kilocalories_per_mole" periodicity1="2" phase1="180. * degree"/>
110
+ <Improper smirks="[*:1]~[#6X3:2](~[#8X1:3])~[#8:4]" id="i2" k1="10.5 * kilocalories_per_mole" periodicity1="2" phase1="180. * degree"/>
111
+ </ImproperTorsions>
112
+ <vdW version="0.3" potential="Lennard-Jones-12-6" combining_rules="Lorentz-Berthelot" scale12="0.0" scale13="0.0" scale14="0.5" scale15="1" switch_width="1.0 * angstrom" cutoff="9.0 * angstrom" method="cutoff">
113
+ <Atom smirks="[#1:1]" epsilon="0.0157 * kilocalories_per_mole" id="n1" rmin_half="0.6000 * angstrom"/>
114
+ <Atom smirks="[#1:1]-[#6X4]" epsilon="0.0157 * kilocalories_per_mole" id="n2" rmin_half="1.4870 * angstrom"/>
115
+ </vdW>
116
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
117
+ <ToolkitAM1BCC version="0.3"/>
118
+ </SMIRNOFF>
119
+ """
120
+
121
+ xml_ff_w_comments = """<?xml version='1.0' encoding='ASCII'?>
122
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
123
+ <!-- SMIRNOFF (SMIRKS Native Open Force Field) template file -->
124
+ <Date>2018-07-14</Date>
125
+ <Author>C. I. Bayly, OpenEye/UC Irvine; C. C. Bannan, UC Irvine; D. L. Mobley, UC Irvine</Author>
126
+ <!-- This file is meant for processing via openff.toolkit.typing.engines.smirnoff -->
127
+ <!-- WARNING: AMBER functional forms drop the factor of 2 in the bond energy term, so cross-comparing this file with a corresponding .frcmod file, it will appear that the values here are twice as large as they should be. -->
128
+ <Bonds version="0.3">
129
+ <Bond smirks="[#6X4:1]-[#6X4:2]" id="b1" k="620.0 * kilocalories_per_mole/angstrom**2" length="1.526 * angstrom" />
130
+ <Bond smirks="[#6X4:1]-[#6X3:2]" id="b2" k="634.0 * kilocalories_per_mole/angstrom**2" length="1.51 * angstrom"/>
131
+ </Bonds>
132
+ <!-- WARNING: AMBER functional forms drop the factor of 2 in the angle energy term, so cross-comparing this file with a corresponding .frcmod file, it will appear that the values here are twice as large as they should be. -->
133
+ <Angles version="0.3">
134
+ <Angle smirks="[*:1]~[#6X4:2]-[*:3]" angle="109.5 * degree" id="a1" k="100.0 * kilocalories_per_mole/radian**2"/>
135
+ <Angle smirks="[#1:1]-[#6X4:2]-[#1:3]" angle="109.5 * degree" id="a2" k="70.0 * kilocalories_per_mole/radian**2"/>
136
+ </Angles>
137
+ <ProperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))">
138
+ <Proper smirks="[*:1]-[#6X4:2]-[#6X4:3]-[*:4]" id="t1" idivf1="1" k1="0.156 * kilocalories_per_mole" periodicity1="3" phase1="0.0 * degree"/>
139
+ <Proper smirks="[#6X4:1]-[#6X4:2]-[#6X4:3]-[#6X4:4]" id="t2" idivf1="1" k1="0.180 * kilocalories_per_mole" periodicity1="3" phase1="0.0 * degree" periodicity2="2" phase2="180.0 * degree" idivf2="1" k2="0.250 * kilocalories_per_mole" periodicity3="1" phase3="180.0 * degree" idivf3="1" k3="0.200 * kilocalories_per_mole"/>
140
+ </ProperTorsions>
141
+ <ImproperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))">
142
+ <Improper smirks="[*:1]~[#6X3:2](~[*:3])~[*:4]" id="i1" k1="1.1 * kilocalories_per_mole" periodicity1="2" phase1="180. * degree"/>
143
+ <Improper smirks="[*:1]~[#6X3:2](~[#8X1:3])~[#8:4]" id="i2" k1="10.5 * kilocalories_per_mole" periodicity1="2" phase1="180. * degree"/>
144
+ </ImproperTorsions>
145
+ <vdW version="0.3" potential="Lennard-Jones-12-6" combining_rules="Lorentz-Berthelot" scale12="0.0" scale13="0.0" scale14="0.5" scale15="1" switch_width="1.0 * angstrom" cutoff="9.0 * angstrom" method="cutoff">
146
+ <Atom smirks="[#1:1]" epsilon="0.0157 * kilocalories_per_mole" id="n1" rmin_half="0.6000 * angstrom"/>
147
+ <Atom smirks="[#1:1]-[#6X4]" epsilon="0.0157 * kilocalories_per_mole" id="n2" rmin_half="1.4870 * angstrom"/>
148
+ </vdW>
149
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" scale15="1" cutoff="9.0 * angstrom" pme_tolerance="0.00001"/>
150
+ <ToolkitAM1BCC version="0.3"/>
151
+ </SMIRNOFF>
152
+ """
153
+
154
+ xml_missing_torsion = """
155
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
156
+ <ProperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))">
157
+ <Proper smirks="[#99:1]-[#99X4:2]-[#99:3]-[#99:4]" id="t1" idivf1="1" k1="0.156 * kilocalories_per_mole" periodicity1="3" phase1="0.0 * degree"/>
158
+ </ProperTorsions>
159
+ </SMIRNOFF>
160
+ """
161
+
162
+ xml_ff_w_cosmetic_elements = """<?xml version='1.0' encoding='ASCII'?>
163
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
164
+ <!-- SMIRNOFF (SMIRKS Native Open Force Field) template file -->
165
+ <Date>MMXVIII-VII-XIV</Date>
166
+ <Author>Alice and Bob</Author>
167
+ <!-- This file is meant for processing via openff.toolkit.typing.engines.smirnoff -->
168
+ <!-- WARNING: AMBER functional forms drop the factor of 2 in the bond energy term, so cross-comparing this file with a corresponding .frcmod file, it will appear that the values here are twice as large as they should be. -->
169
+ <Bonds version="0.3">
170
+ <Bond smirks="[#6X4:1]-[#6X4:2]" id="b1" k="620.0 * kilocalories_per_mole/angstrom**2" length="1.526 * angstrom" parameters="k, length" parameterize_eval="blah=blah2"/>
171
+ <Bond smirks="[#6X4:1]-[#6X3:2]" id="b2" k="634.0 * kilocalories_per_mole/angstrom**2" length="1.51 * angstrom"/>
172
+ </Bonds>
173
+ <!-- WARNING: AMBER functional forms drop the factor of 2 in the angle energy term, so cross-comparing this file with a corresponding .frcmod file, it will appear that the values here are twice as large as they should be. -->
174
+ <Angles version="0.3" cosmetic_element="why not?">
175
+ <Angle smirks="[*:1]~[#6X4:2]-[*:3]" angle="109.5 * degree" id="a1" k="100.0 * kilocalories_per_mole/radian**2"/>
176
+ <Angle smirks="[#1:1]-[#6X4:2]-[#1:3]" angle="109.5 * degree" id="a2" k="70.0 * kilocalories_per_mole/radian**2"/>
177
+ </Angles>
178
+ <ProperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
179
+ <Proper smirks="[*:1]-[#6X4:2]-[#6X4:3]-[*:4]" id="t1" idivf1="1" k1="0.156 * kilocalories_per_mole" periodicity1="3" phase1="0.0 * degree"/>
180
+ <Proper smirks="[#6X4:1]-[#6X4:2]-[#6X4:3]-[#6X4:4]" id="t2" idivf1="1" k1="0.180 * kilocalories_per_mole" periodicity1="3" phase1="0.0 * degree" periodicity2="2" phase2="180.0 * degree" idivf2="1" k2="0.250 * kilocalories_per_mole" periodicity3="1" phase3="180.0 * degree" idivf3="1" k3="0.200 * kilocalories_per_mole"/>
181
+ <Proper smirks="[*:1]:[#6X4:2]~[#6X4:3]:[*:4]" periodicity1="2" phase1="0.0 * degree" k1_bondorder1="1.00*kilocalories_per_mole" k1_bondorder2="1.80*kilocalories_per_mole" idivf1="1.0"/>
182
+ </ProperTorsions>
183
+ <ImproperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))">
184
+ <Improper smirks="[*:1]~[#6X3:2](~[*:3])~[*:4]" id="i1" k1="1.1 * kilocalories_per_mole" periodicity1="2" phase1="180. * degree"/>
185
+ <Improper smirks="[*:1]~[#6X3:2](~[#8X1:3])~[#8:4]" id="i2" k1="10.5 * kilocalories_per_mole" periodicity1="2" phase1="180. * degree"/>
186
+ </ImproperTorsions>
187
+ <vdW version="0.3" potential="Lennard-Jones-12-6" combining_rules="Lorentz-Berthelot" scale12="0.0" scale13="0.0" scale14="0.5" scale15="1" switch_width="1.0 * angstrom" cutoff="9.0 * angstrom" method="cutoff">
188
+ <Atom smirks="[#1:1]" epsilon="0.0157 * kilocalories_per_mole" id="n1" rmin_half="0.6000 * angstrom"/>
189
+ <Atom smirks="[#1:1]-[#6X4]" epsilon="0.0157 * kilocalories_per_mole" id="n2" rmin_half="1.4870 * angstrom"/>
190
+ </vdW>
191
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" scale15="1" cutoff="9.0 * angstrom" pme_tolerance="0.00001"/>
192
+ <ToolkitAM1BCC version="0.3"/>
193
+ </SMIRNOFF>
194
+ """
195
+
196
+ xml_toolkitam1bcc_ff = """
197
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
198
+ <ToolkitAM1BCC version="0.3"/>
199
+ </SMIRNOFF>
200
+ """
201
+
202
+ xml_ethanol_library_charges_ff = """
203
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
204
+ <LibraryCharges version="0.3">
205
+ <LibraryCharge smirks="[#1:1]-[#6:2](-[#1:3])(-[#1:4])-[#6:5](-[#1:6])(-[#1:7])-[#8:8]-[#1:9]" charge1="-0.02*elementary_charge" charge2="-0.2*elementary_charge" charge3="-0.02*elementary_charge" charge4="-0.02*elementary_charge" charge5="-0.1*elementary_charge" charge6="-0.01*elementary_charge" charge7="-0.01*elementary_charge" charge8="0.3*elementary_charge" charge9="0.08*elementary_charge" />
206
+ </LibraryCharges>
207
+ </SMIRNOFF>
208
+ """
209
+
210
+ xml_ethanol_library_charges_in_parts_ff = """
211
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
212
+ <LibraryCharges version="0.3">
213
+ <!-- Note that the oxygen is covered twice here. The correct behavior should be to take the charge from the SECOND LibraryCharge, as it should overwrite the first -->
214
+ <LibraryCharge smirks="[#1:1]-[#6:2](-[#1:3])(-[#1:4])-[#6:5](-[#1:6])(-[#1:7])-[#8:8]" charge1="-0.02*elementary_charge" charge2="-0.2*elementary_charge" charge3="-0.02*elementary_charge" charge4="-0.02*elementary_charge" charge5="-0.1*elementary_charge" charge6="-0.01*elementary_charge" charge7="-0.01*elementary_charge" charge8="-999*elementary_charge" />
215
+ <LibraryCharge smirks="[#8:1]-[#1:2]" charge1="0.3*elementary_charge" charge2="0.08*elementary_charge" />
216
+ </LibraryCharges>
217
+ </SMIRNOFF>
218
+ """
219
+
220
+ xml_ethanol_library_charges_by_atom_ff = """
221
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
222
+ <LibraryCharges version="0.3">
223
+ <LibraryCharge smirks="[#1:1]-[#6]" charge1="-0.02*elementary_charge" />
224
+ <LibraryCharge smirks="[#6X4:1]" charge1="-0.2*elementary_charge" />
225
+ <LibraryCharge smirks="[#1:1]-[#6]-[#8]" charge1="-0.01*elementary_charge" />
226
+ <LibraryCharge smirks="[#6X4:1]-[#8]" charge1="-0.1*elementary_charge" />
227
+ <LibraryCharge smirks="[#8X2:1]" charge1="0.3*elementary_charge" />
228
+ <LibraryCharge smirks="[#1:1]-[#8]" charge1="0.08*elementary_charge" />
229
+ </LibraryCharges>
230
+ </SMIRNOFF>
231
+ """
232
+
233
+ xml_OH_library_charges_xml = """
234
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
235
+ <LibraryCharges version="0.3">
236
+ <LibraryCharge smirks="[#1:1]" charge1="1.*elementary_charge" />
237
+ <LibraryCharge smirks="[#8:1]" charge1="-2.*elementary_charge" />
238
+ </LibraryCharges>
239
+ </SMIRNOFF>
240
+ """
241
+
242
+ xml_CH_zeroes_library_charges_xml = """
243
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
244
+ <LibraryCharges version="0.3">
245
+ <LibraryCharge smirks="[#1:1]" charge1="0.*elementary_charge" />
246
+ <LibraryCharge smirks="[#6:1]" charge1="0.*elementary_charge" />
247
+ </LibraryCharges>
248
+ </SMIRNOFF>
249
+ """
250
+
251
+ xml_spec_docs_ala_library_charges_xml = """
252
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
253
+ <LibraryCharges version="0.3">
254
+ <LibraryCharge name="ALA" smirks="[NX3:1]([#1:2])([#6])[#6H1:3]([#1:4])([#6:5]([#1:6])([#1:7])[#1:8])[#6:9](=[#8:10])[#7]" charge1="-0.4157*elementary_charge" charge2="0.2719*elementary_charge" charge3="0.0337*elementary_charge" charge4="0.0823*elementary_charge" charge5="-0.1825*elementary_charge" charge6="0.0603*elementary_charge" charge7="0.0603*elementary_charge" charge8="0.0603*elementary_charge" charge9="0.5973*elementary_charge" charge10="-0.5679*elementary_charge"/>
255
+ </LibraryCharges>
256
+ </SMIRNOFF>
257
+ """
258
+
259
+ xml_spec_docs_tip3p_library_charges_xml = """
260
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
261
+ <LibraryCharges version="0.3">
262
+ <LibraryCharge name="TIP3P" smirks="[#1:1]-[#8X2H2+0:2]-[#1:3]" charge1="0.417*elementary_charge" charge2="-0.834*elementary_charge" charge3="0.417*elementary_charge"/>
263
+ </LibraryCharges>
264
+ </SMIRNOFF>
265
+ """
266
+
267
+ xml_spec_docs_charge_increment_model_xml = """
268
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
269
+ <ChargeIncrementModel version="0.4" number_of_conformers="1" partial_charge_method="AM1-Mulliken">
270
+ <!-- A fractional charge can be moved along a single bond -->
271
+ <ChargeIncrement smirks="[#6X4:1]-[#6X3a:2]" charge_increment1="-0.0073*elementary_charge" charge_increment2="0.0073*elementary_charge"/>
272
+ <ChargeIncrement smirks="[#6X4:1]-[#6X3a:2]-[#7]" charge_increment1="0.0943*elementary_charge" charge_increment2="-0.0943*elementary_charge"/>
273
+ <!--- Alternatively, fractional charges can be redistributed among any number of bonded atoms -->
274
+ <ChargeIncrement smirks="[N:1]([H:2])([H:3])" charge_increment1="0.02*elementary_charge" charge_increment2="-0.01*elementary_charge" charge_increment3="-0.01*elementary_charge"/>
275
+ <!-- As of version 0.4 of the ChargeIncrementModel tag, it is possible to define one less charge_increment attribute than there are tagged atoms -->
276
+ <!-- The final, undefined charge_increment will be calculated as to make the sum of the charge_increments equal 0 -->
277
+ <ChargeIncrement smirks="[#6X4:1]-[#8:2]" charge_increment1="-0.0718*elementary_charge"/>
278
+ <ChargeIncrement smirks="[N]-[C:1]-[C:2]-[Cl:3]" charge_increment1="-0.123*elementary_charge" charge_increment2="0.456*elementary_charge" />
279
+ </ChargeIncrementModel>
280
+ </SMIRNOFF>
281
+ """
282
+
283
+ xml_charge_increment_model_formal_charges = """
284
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
285
+ <ChargeIncrementModel version="0.3" number_of_conformers="0" partial_charge_method="formal_charge"/>
286
+ </SMIRNOFF>
287
+ """
288
+
289
+ xml_ff_bo = """<?xml version='1.0' encoding='ASCII'?>
290
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
291
+ <Bonds version="0.3" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
292
+ <Bond smirks="[#6X4:1]~[#8X2:2]" id="bbo1" k_bondorder1="101.0 * kilocalories_per_mole/angstrom**2" k_bondorder2="123.0 * kilocalories_per_mole/angstrom**2" length_bondorder1="1.4 * angstrom" length_bondorder2="1.3 * angstrom"/>
293
+ </Bonds>
294
+ <ProperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))">
295
+ <Proper smirks="[*:1]~[#6X3:2]~[#6X3:3]~[*:4]" id="tbo1" periodicity1="2" phase1="0.0 * degree" k1_bondorder1="1.00*kilocalories_per_mole" k1_bondorder2="1.80*kilocalories_per_mole" idivf1="1.0"/>
296
+ <Proper smirks="[*:1]~[#6X4:2]~[#8X2:3]~[*:4]" id="tbo2" periodicity1="2" phase1="0.0 * degree" k1_bondorder1="1.00*kilocalories_per_mole" k1_bondorder2="1.80*kilocalories_per_mole" idivf1="1.0"/>
297
+ </ProperTorsions>
298
+ </SMIRNOFF>
299
+ """
300
+
301
+ xml_ff_torsion_bo_standard_supersede = """<?xml version='1.0' encoding='ASCII'?>
302
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
303
+ <ProperTorsions version="0.3" potential="k*(1+cos(periodicity*theta-phase))">
304
+ <Proper smirks="[*:1]~[#6X3:2]~[#6X3:3]~[*:4]" id="tbo1" periodicity1="2" phase1="0.0 * degree" k1_bondorder1="1.00*kilocalories_per_mole" k1_bondorder2="1.80*kilocalories_per_mole" idivf1="1.0"/>
305
+ <Proper smirks="[*:1]~[#6X4:2]~[#8X2:3]~[*:4]" id="tbo2" periodicity1="2" phase1="0.0 * degree" k1_bondorder1="1.00*kilocalories_per_mole" k1_bondorder2="1.80*kilocalories_per_mole" idivf1="1.0"/>
306
+ <Proper smirks="[*:1]~[#6X4:2]-[#8X2:3]~[#1:4]" id="t1" periodicity1="2" phase1="0.0 * degree" k1="1.20*kilocalories_per_mole" idivf1="1.0"/>
307
+ </ProperTorsions>
308
+ </SMIRNOFF>
309
+ """
310
+
311
+ xml_tip5p = """<?xml version="1.0" encoding="utf-8"?>
312
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
313
+ <LibraryCharges version="0.3">
314
+ <LibraryCharge name="tip5p" smirks="[#1:1]-[#8X2H2+0:2]-[#1:3]" charge1="0.*elementary_charge" charge2="0.*elementary_charge" charge3="0.*elementary_charge"/>
315
+ </LibraryCharges>
316
+ <vdW version="0.3" potential="Lennard-Jones-12-6" combining_rules="Lorentz-Berthelot" scale12="0.0" scale13="0.0" scale14="0.5" scale15="1.0" switch_width="1.0 * angstrom" cutoff="9.0 * angstrom" method="cutoff">
317
+ <Atom smirks="[#1:1]-[#8X2H2+0]-[#1]" epsilon="0. * mole**-1 * kilojoule" id="n35" sigma="1 * nanometer"/>
318
+ <Atom smirks="[#1]-[#8X2H2+0:1]-[#1]" epsilon="0.66944 * mole**-1 * kilojoule" id="n35" sigma="0.312 * nanometer"/>
319
+ </vdW>
320
+ <Bonds version="0.3" potential="harmonic" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
321
+ <Bond smirks="[#1:1]-[#8X2H2+0:2]-[#1]" length="0.9572 * angstrom" k="462750.4 * nanometer**-2 * mole**-1 * kilojoule" id="b1" />
322
+ </Bonds>
323
+ <Angles version="0.3" potential="harmonic">
324
+ <Angle smirks="[#1:1]-[#8X2H2+0:2]-[#1:3]" angle="1.82421813418 * radian" k="836.8 * mole**-1 * radian**-2 * kilojoule" id="a1" />
325
+ </Angles>
326
+ <VirtualSites version="0.3" exclusion_policy="parents">
327
+ <VirtualSite
328
+ type="DivalentLonePair"
329
+ name="EP"
330
+ smirks="[#1:2]-[#8X2H2+0:1]-[#1:3]"
331
+ distance="0.70 * angstrom"
332
+ charge_increment2="0.1205*elementary_charge"
333
+ charge_increment1="0.0*elementary_charge"
334
+ charge_increment3="0.1205*elementary_charge"
335
+ sigma="1.0*angstrom"
336
+ epsilon="0.0*kilocalories_per_mole"
337
+ outOfPlaneAngle="54.71384225*degree"
338
+ match="all_permutations" >
339
+ </VirtualSite>
340
+ </VirtualSites>
341
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" scale15="1.0" switch_width="0.0 * angstrom" cutoff="9.0 * angstrom"/>
342
+ <Constraints version="0.3">
343
+ <Constraint smirks="[#1:1]-[#8X2H2+0:2]-[#1]" id="c1" distance="0.9572 * angstrom"/>
344
+ <Constraint smirks="[#1:1]-[#8X2H2+0]-[#1:2]" id="c2" distance="1.5139006545247014 * angstrom"/>
345
+ </Constraints>
346
+ </SMIRNOFF>
347
+ """
348
+
349
+ xml_gbsa_ff = """<?xml version='1.0' encoding='ASCII'?>
350
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
351
+ <GBSA version="0.3" gb_model="HCT" solvent_dielectric="78.5" solute_dielectric="1" sa_model="None" surface_area_penalty="5.4*calories/mole/angstroms**2" solvent_radius="1.4*angstroms">
352
+ <Atom smirks="[*:1]" radius="0.15*nanometer" scale="0.8"/>
353
+ </GBSA>
354
+ </SMIRNOFF>
355
+ """
356
+
357
+ xml_charge_increment_model_ff_no_missing_cis = """
358
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
359
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
360
+ <ChargeIncrementModel version="0.3" number_of_conformers="1" partial_charge_method="formal_charge">
361
+ <ChargeIncrement smirks="[#6X4:1]-[#8:2]" charge_increment1="-0.06*elementary_charge" charge_increment2="0.06*elementary_charge"/>
362
+ <ChargeIncrement smirks="[#6X4:1]-[#1:2]" charge_increment1="-0.01*elementary_charge" charge_increment2="0.01*elementary_charge"/>
363
+ <ChargeIncrement smirks="[C:1][C:2][O:3]" charge_increment1="0.2*elementary_charge" charge_increment2="-0.1*elementary_charge" charge_increment3="-0.1*elementary_charge"/>
364
+ </ChargeIncrementModel>
365
+ </SMIRNOFF>"""
366
+
367
+ xml_charge_increment_model_ff_one_less_ci = """
368
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
369
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
370
+ <ChargeIncrementModel version="0.3" number_of_conformers="1" partial_charge_method="formal_charge">
371
+ <ChargeIncrement smirks="[#6X4:1]-[#8:2]" charge_increment1="-0.06*elementary_charge" charge_increment2="0.06*elementary_charge"/>
372
+ <ChargeIncrement smirks="[#6X4:1]-[#1:2]" charge_increment1="-0.01*elementary_charge"/>
373
+ <ChargeIncrement smirks="[C:1][C:2][O:3]" charge_increment1="0.2*elementary_charge" charge_increment2="-0.1*elementary_charge"/>
374
+ </ChargeIncrementModel>
375
+ </SMIRNOFF>"""
376
+
377
+ xml_charge_increment_model_ff_ethanol = """
378
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
379
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
380
+ <ChargeIncrementModel version="0.3" number_of_conformers="1" partial_charge_method="formal_charge">
381
+ <ChargeIncrement smirks="[#6X4:1]-[#8:2]" charge_increment1="-0.05*elementary_charge" charge_increment2="0.05*elementary_charge"/>
382
+ <ChargeIncrement smirks="[C:1][C:2][O:3]" charge_increment1="0.2*elementary_charge" charge_increment2="-0.1*elementary_charge" charge_increment3="-0.1*elementary_charge"/>
383
+ </ChargeIncrementModel>
384
+ </SMIRNOFF>"""
385
+
386
+ xml_charge_increment_model_ff_net_charge = """
387
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
388
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
389
+ <ChargeIncrementModel version="0.3" number_of_conformers="1" partial_charge_method="formal_charge">
390
+ <ChargeIncrement smirks="[#6X3:1]-[#8X1-1:2]" charge_increment1="-0.05*elementary_charge" charge_increment2="0.05*elementary_charge"/>
391
+ <ChargeIncrement smirks="[#6X3:1]=[#8X1:2]" charge_increment1="0.2*elementary_charge" charge_increment2="-0.2*elementary_charge"/>
392
+ </ChargeIncrementModel>
393
+ </SMIRNOFF>"""
394
+
395
+ xml_charge_increment_model_ff_override = """
396
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
397
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
398
+ <ChargeIncrementModel version="0.3" number_of_conformers="1" partial_charge_method="formal_charge">
399
+ <ChargeIncrement smirks="[#1:1]-[#6:2]([#1:3])([#1:4])" charge_increment1="0.123*elementary_charge" charge_increment2="0.369*elementary_charge" charge_increment3="-0.123*elementary_charge" charge_increment4="0.123*elementary_charge"/>
400
+ <ChargeIncrement smirks="[#6X4:1]([#1:2])([#1:3])([#1:4])" charge_increment1="0.3*elementary_charge" charge_increment2="-0.1*elementary_charge" charge_increment3="-0.1*elementary_charge" charge_increment4="-0.1*elementary_charge"/>
401
+ </ChargeIncrementModel>
402
+ </SMIRNOFF>"""
403
+
404
+ xml_charge_increment_model_ff_both_apply = """
405
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
406
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
407
+ <ChargeIncrementModel version="0.3" number_of_conformers="0" partial_charge_method="formal_charge">
408
+ <ChargeIncrement smirks="[#6X4:1]([#1:2])([#1:3])([#1:4])" charge_increment1="0.3*elementary_charge" charge_increment2="-0.1*elementary_charge" charge_increment3="-0.1*elementary_charge" charge_increment4="-0.1*elementary_charge"/>
409
+ <ChargeIncrement smirks="[#6X4:1][#6X4:2][#8]" charge_increment1="0.05*elementary_charge" charge_increment2="-0.05*elementary_charge"/>
410
+ </ChargeIncrementModel>
411
+ </SMIRNOFF>"""
412
+
413
+ xml_charge_increment_model_ff_match_once = """
414
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
415
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
416
+ <ChargeIncrementModel version="0.3" number_of_conformers="1" partial_charge_method="formal_charge">
417
+ <ChargeIncrement smirks="[#6X4:1]([#1:2])[#6][#8]" charge_increment1="0.1*elementary_charge" charge_increment2="-0.1*elementary_charge"/>
418
+ </ChargeIncrementModel>
419
+ </SMIRNOFF>"""
420
+
421
+ xml_charge_increment_model_ff_match_two = """
422
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
423
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
424
+ <ChargeIncrementModel version="0.3" number_of_conformers="1" partial_charge_method="formal_charge">
425
+ <ChargeIncrement smirks="[#6X4:1]([#1:2])([#1:3])[#6][#8]" charge_increment1="0.1*elementary_charge" charge_increment2="-0.05*elementary_charge" charge_increment3="-0.05*elementary_charge"/>
426
+ </ChargeIncrementModel>
427
+ </SMIRNOFF>"""
428
+
429
+ xml_charge_increment_model_ff_match_all = """
430
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
431
+ <Electrostatics version="0.3" method="PME" scale12="0.0" scale13="0.0" scale14="0.833333" cutoff="9.0 * angstrom"/>
432
+ <ChargeIncrementModel version="0.3" number_of_conformers="1" partial_charge_method="formal_charge">
433
+ <ChargeIncrement smirks="[#6X4:1]([#1:2])([#1:3])([#1:4])" charge_increment1="0.3*elementary_charge" charge_increment2="-0.1*elementary_charge" charge_increment3="-0.1*elementary_charge" charge_increment4="-0.1*elementary_charge"/>
434
+ </ChargeIncrementModel>
435
+ </SMIRNOFF>"""
436
+
437
+ xml_ff_virtual_sites_bondcharge_match_once = """<?xml version="1.0" encoding="utf-8"?>
438
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
439
+ <Bonds version="0.3" potential="harmonic" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
440
+ <Bond smirks="[*:1]~[*:2]" id="b999" k="500.0 * kilocalories_per_mole/angstrom**2" length="1.1 * angstrom"/>
441
+ </Bonds>
442
+ <VirtualSites version="0.3">
443
+ <VirtualSite
444
+ type="BondCharge"
445
+ name="EP"
446
+ smirks="[*:1]~[*:2]"
447
+ distance="0.1*angstrom"
448
+ charge_increment1="0.1*elementary_charge"
449
+ charge_increment2="0.1*elementary_charge"
450
+ sigma="0.1*angstrom"
451
+ epsilon="0.1*kilocalories_per_mole"
452
+ match="once" >
453
+ </VirtualSite>
454
+ <VirtualSite
455
+ type="BondCharge"
456
+ name="EP"
457
+ smirks="[#7:1]~[#7:2]"
458
+ distance="0.2*angstrom"
459
+ charge_increment1="0.2*elementary_charge"
460
+ charge_increment2="0.2*elementary_charge"
461
+ sigma="0.2*angstrom"
462
+ epsilon="0.2*kilocalories_per_mole"
463
+ match="all_permutations" >
464
+ </VirtualSite>
465
+ <VirtualSite
466
+ type="BondCharge"
467
+ name="EP"
468
+ smirks="[#7:1]~[#7:2]"
469
+ distance="0.2*nanometers"
470
+ charge_increment1="0.2*elementary_charge"
471
+ charge_increment2="0.2*elementary_charge"
472
+ sigma="0.2*angstrom"
473
+ epsilon="0.2*kilocalories_per_mole"
474
+ match="once" >
475
+ </VirtualSite>
476
+ </VirtualSites>
477
+ </SMIRNOFF>
478
+ """
479
+
480
+ xml_ff_virtual_sites_bondcharge_match_all = """<?xml version="1.0" encoding="utf-8"?>
481
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
482
+ <Bonds version="0.3" potential="harmonic" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
483
+ <Bond smirks="[*:1]~[*:2]" id="b999" k="500.0 * kilocalories_per_mole/angstrom**2" length="1.1 * angstrom"/>
484
+ </Bonds>
485
+ <VirtualSites version="0.3">
486
+ <VirtualSite
487
+ type="BondCharge"
488
+ name="EP"
489
+ smirks="[*:1]~[*:2]"
490
+ distance="0.1*angstrom"
491
+ charge_increment1="0.1*elementary_charge"
492
+ charge_increment2="0.1*elementary_charge"
493
+ sigma="0.1*angstrom"
494
+ epsilon="0.1*kilocalories_per_mole"
495
+ match="once" >
496
+ </VirtualSite>
497
+ <VirtualSite
498
+ type="BondCharge"
499
+ name="EP"
500
+ smirks="[#7:1]~[#7:2]"
501
+ distance="0.2*angstrom"
502
+ charge_increment1="0.2*elementary_charge"
503
+ charge_increment2="0.2*elementary_charge"
504
+ sigma="0.2*angstrom"
505
+ epsilon="0.2*kilocalories_per_mole"
506
+ match="once" >
507
+ </VirtualSite>
508
+ <VirtualSite
509
+ type="BondCharge"
510
+ name="EP"
511
+ smirks="[#7:1]~[#7:2]"
512
+ distance="0.2*angstrom"
513
+ charge_increment1="0.2*elementary_charge"
514
+ charge_increment2="0.2*elementary_charge"
515
+ sigma="0.2*angstrom"
516
+ epsilon="0.2*kilocalories_per_mole"
517
+ match="all_permutations" >
518
+ </VirtualSite>
519
+ </VirtualSites>
520
+ </SMIRNOFF>
521
+ """
522
+
523
+ xml_ff_virtual_sites_bondcharge_match_once_two_names = """<?xml version="1.0" encoding="utf-8"?>
524
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
525
+ <Bonds version="0.3" potential="harmonic" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
526
+ <Bond smirks="[*:1]~[*:2]" id="b999" k="500.0 * kilocalories_per_mole/angstrom**2" length="1.1 * angstrom"/>
527
+ </Bonds>
528
+ <VirtualSites version="0.3">
529
+ <VirtualSite
530
+ type="BondCharge"
531
+ name="EP1"
532
+ smirks="[*:1]~[*:2]"
533
+ distance="0.1*angstrom"
534
+ charge_increment1="0.1*elementary_charge"
535
+ charge_increment2="0.1*elementary_charge"
536
+ sigma="0.1*angstrom"
537
+ epsilon="0.1*kilocalories_per_mole"
538
+ match="once" >
539
+ </VirtualSite>
540
+ <VirtualSite
541
+ type="BondCharge"
542
+ name="EP2"
543
+ smirks="[*:1]~[*:2]"
544
+ distance="0.2*angstrom"
545
+ charge_increment1="0.2*elementary_charge"
546
+ charge_increment2="0.2*elementary_charge"
547
+ sigma="0.2*angstrom"
548
+ epsilon="0.2*kilocalories_per_mole"
549
+ match="once" >
550
+ </VirtualSite>
551
+ </VirtualSites>
552
+ </SMIRNOFF>
553
+ """
554
+
555
+ xml_ff_virtual_sites_monovalent = """<?xml version="1.0" encoding="utf-8"?>
556
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
557
+ <Bonds version="0.3" potential="harmonic" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
558
+ <Bond smirks="[*:1]~[*:2]" id="b999" k="500.0 * kilocalories_per_mole/angstrom**2" length="1.1 * angstrom"/>
559
+ </Bonds>
560
+ <VirtualSites version="0.3">
561
+ <VirtualSite
562
+ type="MonovalentLonePair"
563
+ name="EP"
564
+ smirks="[#8:1]~[#6:2]~[#6:3]"
565
+ distance="0.1*angstrom"
566
+ charge_increment1="0.1*elementary_charge"
567
+ charge_increment2="0.1*elementary_charge"
568
+ charge_increment3="0.1*elementary_charge"
569
+ sigma="0.1*angstrom"
570
+ epsilon="0.1*kilocalories_per_mole"
571
+ inPlaneAngle="110.*degree"
572
+ outOfPlaneAngle="41*degree"
573
+ match="all_permutations" >
574
+ </VirtualSite>
575
+ <VirtualSite
576
+ type="MonovalentLonePair"
577
+ name="EP"
578
+ smirks="[#8:1]=[#6:2]-[#6:3]"
579
+ distance="0.2*angstrom"
580
+ charge_increment1="0.2*elementary_charge"
581
+ charge_increment2="0.2*elementary_charge"
582
+ charge_increment3="0.2*elementary_charge"
583
+ sigma="0.2*angstrom"
584
+ epsilon="0.2*kilocalories_per_mole"
585
+ inPlaneAngle="120.*degree"
586
+ outOfPlaneAngle="42*degree"
587
+ match="all_permutations" >
588
+ </VirtualSite>
589
+ </VirtualSites>
590
+ </SMIRNOFF>
591
+ """
592
+
593
+ xml_ff_virtual_sites_divalent_match_all = """<?xml version="1.0" encoding="ASCII"?>
594
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
595
+ <Bonds version="0.3" potential="harmonic" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
596
+ <Bond smirks="[*:1]~[*:2]" id="b999" k="500.0 * kilocalories_per_mole/angstrom**2" length="1.1 * angstrom"/>
597
+ </Bonds>
598
+ <VirtualSites version="0.3">
599
+ <VirtualSite
600
+ type="DivalentLonePair"
601
+ name="EP"
602
+ smirks="[#1:1]-[#8X2H2+0:2]-[#1:3]"
603
+ distance="0.70 * angstrom"
604
+ charge_increment1="0.241*elementary_charge"
605
+ charge_increment2="0.0*elementary_charge"
606
+ charge_increment3="0.241*elementary_charge"
607
+ sigma="3.12*angstrom"
608
+ epsilon="0.16*kilocalories_per_mole"
609
+ outOfPlaneAngle="54.71384225*degree"
610
+ match="all_permutations" >
611
+ </VirtualSite>
612
+ </VirtualSites>
613
+ </SMIRNOFF>
614
+ """
615
+
616
+ xml_ff_virtual_sites_trivalent_match_once = """<?xml version="1.0" encoding="ASCII"?>
617
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
618
+ <Bonds version="0.3" potential="harmonic" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
619
+ <Bond smirks="[*:1]~[*:2]" id="b999" k="500.0 * kilocalories_per_mole/angstrom**2" length="1.1 * angstrom"/>
620
+ </Bonds>
621
+ <VirtualSites version="0.3">
622
+ <VirtualSite
623
+ type="TrivalentLonePair"
624
+ name="EP"
625
+ smirks="[*:1]-[#7X3:2](-[*:3])-[*:4]"
626
+ distance="0.50 * angstrom"
627
+ charge_increment1="0.0*elementary_charge"
628
+ charge_increment2="1.0*elementary_charge"
629
+ charge_increment3="0.0*elementary_charge"
630
+ charge_increment4="0.0*elementary_charge"
631
+ sigma="0.0*angstrom"
632
+ epsilon="0.0*kilocalories_per_mole"
633
+ match="once" >
634
+ </VirtualSite>
635
+ </VirtualSites>
636
+ </SMIRNOFF>
637
+ """
638
+
639
+ xml_ff_virtual_sites_trivalent_match_all = """
640
+ <?xml version="1.0" encoding="ASCII"?>
641
+ <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL">
642
+ <Bonds version="0.3" potential="harmonic" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear">
643
+ <Bond smirks="[*:1]~[*:2]" id="b999" k="500.0 * kilocalories_per_mole/angstrom**2" length="1.1 * angstrom"/>
644
+ </Bonds>
645
+ <VirtualSites version="0.3">
646
+ <VirtualSite
647
+ type="TrivalentLonePair"
648
+ name="EP"
649
+ smirks="[*:1]-[#7X3:2]-([*:3])-[*:4]"
650
+ distance="0.70 * angstrom"
651
+ charge_increment1="0.1*elementary_charge"
652
+ charge_increment2="0.1*elementary_charge"
653
+ charge_increment3="0.1*elementary_charge"
654
+ charge_increment4="0.1*elementary_charge"
655
+ sigma="0.1*angstrom"
656
+ epsilon="0.1*kilocalories_per_mole"
657
+ match="once" >
658
+ </VirtualSite>
659
+ </VirtualSites>
660
+ </SMIRNOFF>
661
+ """
662
+
663
+
664
+ def round_charge(xml):
665
+ """Round charge fields in a serialized OpenMM system to 2 decimal places"""
666
+ # Example Particle line: <Particle eps=".4577296" q="-.09709000587463379" sig=".1908"/>
667
+ xmlsp = xml.split(' q="')
668
+ for index, chunk in enumerate(xmlsp):
669
+ # Skip file before first q=
670
+ if index == 0:
671
+ continue
672
+ chunksp = chunk.split('" sig')
673
+ chunksp[0] = f"{float(chunksp[0]):.2f}"
674
+ chunk = '" sig'.join(chunksp)
675
+ xmlsp[index] = chunk
676
+ return ' q="'.join(xmlsp)
677
+
678
+
679
+ def generate_monatomic_ions():
680
+ return (
681
+ ("Li+", +1 * openmm_unit.elementary_charge),
682
+ ("Na+", +1 * openmm_unit.elementary_charge),
683
+ ("K+", +1 * openmm_unit.elementary_charge),
684
+ ("Rb+", +1 * openmm_unit.elementary_charge),
685
+ ("Cs+", +1 * openmm_unit.elementary_charge),
686
+ ("F-", -1 * openmm_unit.elementary_charge),
687
+ ("Cl-", -1 * openmm_unit.elementary_charge),
688
+ ("Br-", -1 * openmm_unit.elementary_charge),
689
+ ("I-", -1 * openmm_unit.elementary_charge),
690
+ )
691
+
692
+
693
+ partial_charge_method_resolution_matrix = [
694
+ {
695
+ "toolkit": AmberToolsToolkitWrapper,
696
+ "partial_charge_method": "AM1-Mulliken",
697
+ "exception": None,
698
+ "exception_match": "",
699
+ },
700
+ {
701
+ "toolkit": AmberToolsToolkitWrapper,
702
+ "partial_charge_method": "Gasteiger",
703
+ "exception": None,
704
+ "exception_match": "",
705
+ },
706
+ {
707
+ "toolkit": AmberToolsToolkitWrapper,
708
+ "partial_charge_method": "Madeup-ChargeMethod",
709
+ "exception": ChargeMethodUnavailableError,
710
+ "exception_match": "",
711
+ },
712
+ {
713
+ "toolkit": OpenEyeToolkitWrapper,
714
+ "partial_charge_method": "AM1-Mulliken",
715
+ "exception": None,
716
+ "exception_match": "",
717
+ },
718
+ {
719
+ "toolkit": OpenEyeToolkitWrapper,
720
+ "partial_charge_method": "Gasteiger",
721
+ "exception": None,
722
+ "exception_match": "",
723
+ },
724
+ {
725
+ "toolkit": OpenEyeToolkitWrapper,
726
+ "partial_charge_method": "MMFF94",
727
+ "exception": None,
728
+ "exception_match": "",
729
+ },
730
+ {
731
+ "toolkit": OpenEyeToolkitWrapper,
732
+ "partial_charge_method": "am1bcc",
733
+ "exception": None,
734
+ "exception_match": "",
735
+ },
736
+ {
737
+ "toolkit": OpenEyeToolkitWrapper,
738
+ "partial_charge_method": "am1bccnosymspt",
739
+ "exception": None,
740
+ "exception_match": "",
741
+ },
742
+ {
743
+ "toolkit": OpenEyeToolkitWrapper,
744
+ "partial_charge_method": "am1bccelf10",
745
+ "exception": None,
746
+ "exception_match": "",
747
+ },
748
+ {
749
+ "toolkit": OpenEyeToolkitWrapper,
750
+ "partial_charge_method": "Madeup-ChargeMethod",
751
+ "exception": ChargeMethodUnavailableError,
752
+ "exception_match": "",
753
+ },
754
+ ]
755
+
756
+
757
+ toolkit_registries = []
758
+ if OpenEyeToolkitWrapper.is_available():
759
+ toolkit_registries.append(
760
+ ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper]),
761
+ )
762
+ if RDKitToolkitWrapper.is_available() and AmberToolsToolkitWrapper.is_available():
763
+ toolkit_registries.append(ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper, AmberToolsToolkitWrapper]))
764
+
765
+
766
+ class _ForceFieldFixtures:
767
+ @pytest.fixture()
768
+ def alkethoh_forcefield(self):
769
+ return ForceField(get_data_file_path("test_forcefields/Frosst_AlkEthOH_parmAtFrosst.offxml"))
770
+
771
+ @pytest.fixture()
772
+ def force_field(self):
773
+ return ForceField(get_data_file_path("test_forcefields/test_forcefield.offxml"))
774
+
775
+
776
+ class TestForceField(_ForceFieldFixtures):
777
+ """Test the ForceField class"""
778
+
779
+ def test_get_available_force_fields(self):
780
+ """Ensure get_available_force_fields returns some expected data"""
781
+ available_force_fields = get_available_force_fields(full_paths=False)
782
+
783
+ # Incomplete list of some expected force fields
784
+ expected_force_fields = [
785
+ "openff-1.0.0.offxml",
786
+ "openff_unconstrained-1.0.0.offxml",
787
+ "openff-1.3.0.offxml",
788
+ "openff-2.0.0.offxml",
789
+ "openff-2.1.0.offxml",
790
+ "ff14sb_off_impropers_0.0.3.offxml",
791
+ ]
792
+
793
+ for ff in expected_force_fields:
794
+ assert ff in available_force_fields
795
+
796
+ @pytest.mark.parametrize("full_path", [(True, False)])
797
+ @pytest.mark.parametrize("force_field_file", [*get_available_force_fields()])
798
+ def test_get_available_force_fields_loadable(self, full_path, force_field_file):
799
+ """Ensure get_available_force_fields returns load-able files"""
800
+ if "ff14sb" in force_field_file and "off_imp" not in force_field_file:
801
+ pytest.skip(
802
+ "Only the variants of the ff14SB port with SMIRNOFF-style impropers "
803
+ "can be loaded by the toolkit by default. Those with Amber-style impropers"
804
+ "require AmberImproperTorsionHandler."
805
+ )
806
+ ForceField(force_field_file)
807
+
808
+ def test_force_field_case(self):
809
+ """Ensure forcefield paths are loaded in a case-insensitive manner"""
810
+ default_case = ForceField("openff-2.0.0.offxml")
811
+ lower_case = ForceField("oPeNFF-2.0.0.offxml")
812
+
813
+ assert hash(default_case) == hash(lower_case)
814
+
815
+ def test_do_not_load_in_child_dir(self, tmp_path):
816
+ """Ensure force field XML files in nested subdirectories are not loaded
817
+ when not explicitly pointed to."""
818
+ nested_directory = tmp_path / os.path.join("a", "b", "c")
819
+ os.makedirs(nested_directory, exist_ok=True)
820
+
821
+ # Create a FF in a nested directory
822
+ ForceField("openff-1.0.0.offxml").to_file(os.path.join(nested_directory, "force-field.offxml"))
823
+
824
+ # Check that the file does not exist in the current working directory.
825
+ assert not os.path.isfile("force-field.offxml")
826
+
827
+ with pytest.raises(OSError, match=r"Source 'force-field.offxml' could not be read."):
828
+ ForceField("force-field.offxml")
829
+
830
+ def test_load_bad_version(self):
831
+ with pytest.raises(SMIRNOFFVersionError, match=r"99.3"):
832
+ ForceField(
833
+ get_data_file_path("test_forcefields/unsupported_smirnoff_version.offxml"),
834
+ disable_version_check=False,
835
+ )
836
+
837
+ ForceField(
838
+ get_data_file_path("test_forcefields/unsupported_smirnoff_version.offxml"),
839
+ disable_version_check=True,
840
+ )
841
+
842
+ def test_create_forcefield_no_args(self):
843
+ """Test empty constructor"""
844
+ forcefield = ForceField()
845
+
846
+ # Should find BondHandler and AngleHandler, since they're default classes
847
+ forcefield.get_parameter_handler("Bonds")
848
+ forcefield.get_parameter_handler("Angles")
849
+
850
+ # Shouldn't find InvalidKey handler, since it doesn't exist
851
+ with pytest.raises(KeyError):
852
+ forcefield.get_parameter_handler("InvalidKey")
853
+
854
+ # Verify the aromatocitiy model is not None
855
+ assert forcefield.aromaticity_model == "OEAroModel_MDL"
856
+
857
+ def test_create_forcefield_aromaticity_model(self):
858
+ """Test the aromaticiy_model argument of the constructor"""
859
+ mdl = "OEAroModel_MDL"
860
+
861
+ assert ForceField(aromaticity_model=mdl).aromaticity_model == mdl
862
+
863
+ with pytest.raises(SMIRNOFFAromaticityError):
864
+ ForceField(aromaticity_model="foobar")
865
+
866
+ def test_create_forcefield_custom_handler_classes(self):
867
+ """Test constructor given specific classes to register"""
868
+ from openff.toolkit.typing.engines.smirnoff import BondHandler
869
+
870
+ forcefield = ForceField(parameter_handler_classes=[BondHandler])
871
+
872
+ # Should find BondHandler, since we registered it
873
+ forcefield.get_parameter_handler("Bonds")
874
+
875
+ # Shouldn't find AngleHandler, since we didn't allow that to be registered
876
+ with pytest.raises(KeyError):
877
+ forcefield.get_parameter_handler("Angles")
878
+
879
+ def test_create_forcefield_from_file(self, force_field):
880
+ """Test basic file loading in constructor"""
881
+ assert len(force_field._parameter_handlers["Bonds"]._parameters) == 87
882
+ assert len(force_field._parameter_handlers["Angles"]._parameters) == 38
883
+ assert len(force_field._parameter_handlers["ProperTorsions"]._parameters) == 158
884
+ assert len(force_field._parameter_handlers["ImproperTorsions"]._parameters) == 4
885
+ assert len(force_field._parameter_handlers["vdW"]._parameters) == 35
886
+ assert force_field.aromaticity_model == "OEAroModel_MDL"
887
+
888
+ def test_load_bad_string(self):
889
+ with pytest.raises(IOError) as exception_info:
890
+ ForceField("1234")
891
+
892
+ # This may need to be updated if the `openforcefields` package changes name;
893
+ # searching through `site-packages/` and other paths is probably unrelaiable
894
+ for match in [
895
+ "Source '1234' could not be read",
896
+ "SMIRNOFFParseError",
897
+ "syntax error",
898
+ "openforcefields",
899
+ ]:
900
+ assert match in str(exception_info.value)
901
+
902
+ def test_load_bad_bytes(self):
903
+ with pytest.raises(IOError) as exception_info:
904
+ ForceField(b"the holy grail of computational chemistry")
905
+
906
+ for match in [
907
+ "Source 'b'the holy grail",
908
+ "could not be read",
909
+ "SMIRNOFFParseError",
910
+ "syntax error",
911
+ ]:
912
+ assert match in str(exception_info.value)
913
+
914
+ # See note in test_load_bad_string
915
+ assert "openforcefields" not in str(exception_info.value)
916
+
917
+ def test_load_filelike_object(self):
918
+ with open(get_data_file_path("test_forcefields/test_forcefield.offxml")) as f:
919
+ ForceField(f)
920
+
921
+ def test_load_bad_filelike_object(self):
922
+ with open(get_data_file_path("test_forcefields/mangled.offxml")) as f:
923
+ with pytest.raises(IOError) as exception_info:
924
+ ForceField(f)
925
+
926
+ assert "while trying to parse source as an object" in str(exception_info.value)
927
+
928
+ def test_create_forcefield_from_xml_string(self):
929
+ forcefield = ForceField(xml_simple_ff)
930
+ assert len(forcefield._parameter_handlers["Bonds"]._parameters) == 3
931
+ assert len(forcefield._parameter_handlers["Angles"]._parameters) == 2
932
+ assert len(forcefield._parameter_handlers["ProperTorsions"]._parameters) == 3
933
+ assert len(forcefield._parameter_handlers["ImproperTorsions"]._parameters) == 2
934
+ assert len(forcefield._parameter_handlers["vdW"]._parameters) == 2
935
+
936
+ def test_load_do_not_convert_non_quantity_strings(self):
937
+ """Reproduce part of #1493"""
938
+ sage = ForceField("openff-2.0.0.offxml")
939
+
940
+ for parameter_handler_name in sage.registered_parameter_handlers:
941
+ parameter_handler = sage.get_parameter_handler(parameter_handler_name)
942
+
943
+ for parameter in parameter_handler.parameters:
944
+ assert isinstance(parameter.smirks, str)
945
+ assert not isinstance(parameter.smirks, unit.Quantity)
946
+
947
+ # Ensure that, for example, F isn't converted to Farad
948
+ if parameter_handler_name == "LibraryCharges" and parameter.name is not None:
949
+ assert isinstance(parameter.name, str)
950
+ assert not isinstance(parameter.name, unit.Quantity)
951
+
952
+ def test_load_do_not_convert_id_to_quantities(self):
953
+ ff = ForceField("openff-2.1.0.offxml")
954
+ handler = ff.get_parameter_handler("LibraryCharges")
955
+ assert handler.parameters[2].id == "K+"
956
+
957
+ def test_pickle(self):
958
+ """
959
+ Test pickling and unpickling a force field
960
+ """
961
+ import pickle
962
+
963
+ forcefield_1 = ForceField(xml_simple_ff)
964
+ pickled = pickle.dumps(forcefield_1)
965
+ forcefield_2 = pickle.loads(pickled)
966
+ assert forcefield_1.to_string() == forcefield_2.to_string()
967
+
968
+ def test_pickle_with_cosmetic_attributes(self):
969
+ """
970
+ Test pickling and unpickling a force field with cosmetic attributes
971
+ """
972
+ import pickle
973
+
974
+ forcefield_1 = ForceField(xml_ff_w_cosmetic_elements, allow_cosmetic_attributes=True)
975
+ pickled = pickle.dumps(forcefield_1)
976
+ forcefield_2 = pickle.loads(pickled)
977
+ assert forcefield_1.to_string() == forcefield_2.to_string()
978
+ # Ensure that the cosmetic attributes stuck around
979
+ assert "blah=blah2" in forcefield_2.to_string()
980
+
981
+ def test_xml_string_roundtrip(self):
982
+ """
983
+ Test writing a ForceField to an XML string
984
+ """
985
+ forcefield_1 = ForceField(xml_simple_ff)
986
+ string_1 = forcefield_1.to_string("XML")
987
+ # Ensure that we have spaces instead of tabs
988
+ assert " " in string_1
989
+ assert "\t" not in string_1
990
+ forcefield_2 = ForceField(string_1)
991
+ string_2 = forcefield_2.to_string("XML")
992
+ assert string_1 == string_2
993
+
994
+ def test_xml_string_roundtrip_keep_cosmetic(self):
995
+ """
996
+ Test roundtripping a force field to an XML string with and without retaining cosmetic elements
997
+ """
998
+ # Ensure an exception is raised if we try to read the XML string with cosmetic attributes
999
+ with pytest.raises(
1000
+ SMIRNOFFSpecError,
1001
+ match=r"Unexpected kwarg [(]parameters: k, length[)] passed",
1002
+ ):
1003
+ ForceField(xml_ff_w_cosmetic_elements)
1004
+
1005
+ # Create a force field from XML successfully, by explicitly permitting cosmetic attributes
1006
+ forcefield_1 = ForceField(xml_ff_w_cosmetic_elements, allow_cosmetic_attributes=True)
1007
+
1008
+ # Convert the force field back to XML
1009
+ string_1 = forcefield_1.to_string("XML", discard_cosmetic_attributes=False)
1010
+
1011
+ # Ensure that the new XML string has cosmetic attributes in it
1012
+ assert 'cosmetic_element="why not?"' in string_1
1013
+ assert 'parameterize_eval="blah=blah2"' in string_1
1014
+ with pytest.raises(
1015
+ SMIRNOFFSpecError,
1016
+ match=r"Unexpected kwarg [(]parameters: k, length[)] passed",
1017
+ ):
1018
+ ForceField(string_1, allow_cosmetic_attributes=False)
1019
+
1020
+ # Complete the forcefield_1 --> string --> forcefield_2 roundtrip
1021
+ forcefield_2 = ForceField(string_1, allow_cosmetic_attributes=True)
1022
+
1023
+ # Ensure that the force field remains the same after the roundtrip
1024
+ string_2 = forcefield_2.to_string("XML", discard_cosmetic_attributes=False)
1025
+ assert string_1 == string_2
1026
+
1027
+ # Discard the cosmetic attributes and ensure that the string is different
1028
+ string_3 = forcefield_2.to_string("XML", discard_cosmetic_attributes=True)
1029
+ assert string_1 != string_3
1030
+ # Ensure that the new XML string does NOT have cosmetic attributes in it
1031
+ assert 'cosmetic_element="why not?"' not in string_3
1032
+ assert 'parameterize_eval="blah=blah2"' not in string_3
1033
+
1034
+ def test_combine_order_dependent(self):
1035
+ assert hash(ForceField("openff-1.3.0.offxml").combine(ForceField("openff-2.2.0.offxml"))) != hash(
1036
+ ForceField("openff-2.2.0.offxml").combine(ForceField("openff-1.3.0.offxml"))
1037
+ )
1038
+
1039
+ def test_combine_same_force_field(self, force_field):
1040
+ combined = force_field.combine(force_field)
1041
+
1042
+ for handler_name in force_field.registered_parameter_handlers:
1043
+ n_parameters = len(force_field[handler_name].parameters)
1044
+ assert len(combined[handler_name].parameters) == 2 * n_parameters
1045
+
1046
+ for parameter_index, parameter in enumerate(force_field[handler_name].parameters):
1047
+ # __eq__ is undefined, comparing dicts should be close enough
1048
+ assert (
1049
+ combined[handler_name].parameters[parameter_index + n_parameters].to_dict() == parameter.to_dict()
1050
+ )
1051
+
1052
+ assert hash(force_field) != hash(combined)
1053
+
1054
+ def test_combine_same_results_as_loading(self):
1055
+ assert hash(ForceField("openff-1.3.0.offxml").combine(ForceField("openff-2.2.0.offxml"))) == hash(
1056
+ ForceField("openff-1.3.0.offxml", "openff-2.2.0.offxml")
1057
+ )
1058
+
1059
+ def test_combine_chain_calls(self, force_field):
1060
+ """Just test that nothing weird happens if squishing together twice."""
1061
+ tripled = force_field.combine(force_field.combine(force_field))
1062
+
1063
+ assert len(tripled["vdW"].parameters) == 3 * len(force_field["vdW"].parameters)
1064
+
1065
+ def test_read_0_1_smirnoff(self):
1066
+ """Test reading an 0.1 spec OFFXML file"""
1067
+ ForceField(get_data_file_path("test_forcefields/smirnoff99Frosst_reference_0_1_spec.offxml"))
1068
+
1069
+ def test_read_0_1_smirff(self):
1070
+ """Test reading an 0.1 spec OFFXML file, enclosed by the legacy "SMIRFF" tag"""
1071
+ ForceField(get_data_file_path("test_forcefields/smirff99Frosst_reference_0_1_spec.offxml"))
1072
+
1073
+ def test_read_0_2_smirnoff(self):
1074
+ """Test reading an 0.2 spec OFFXML file"""
1075
+ ForceField(get_data_file_path("test_forcefields/smirnoff99Frosst_reference_0_2_spec.offxml"))
1076
+
1077
+ @pytest.mark.parametrize("file_path_extension", ["xml", "XML", "offxml", "OFFXML"])
1078
+ @pytest.mark.parametrize(
1079
+ "specified_format",
1080
+ [
1081
+ None,
1082
+ "xml",
1083
+ "XML",
1084
+ ".xml",
1085
+ ".XML",
1086
+ "offxml",
1087
+ "OFFXML",
1088
+ ".offxml",
1089
+ ".OFFXML",
1090
+ XMLParameterIOHandler(),
1091
+ ],
1092
+ )
1093
+ def test_xml_file_roundtrip(self, file_path_extension, specified_format):
1094
+ """
1095
+ Test roundtripping a ForceField to and from an XML file
1096
+ """
1097
+ # These files will be deleted once garbage collection runs (end of this function)
1098
+ iofile1 = NamedTemporaryFile(suffix="." + file_path_extension)
1099
+ iofile2 = NamedTemporaryFile(suffix="." + file_path_extension)
1100
+ forcefield_1 = ForceField(xml_simple_ff)
1101
+ forcefield_1.to_file(iofile1.name, io_format=specified_format)
1102
+ forcefield_2 = ForceField(iofile1.name)
1103
+ forcefield_2.to_file(iofile2.name, io_format=specified_format)
1104
+ assert open(iofile1.name).read() == open(iofile2.name).read()
1105
+
1106
+ @pytest.mark.parametrize("file_path_extension", ["xml", "XML", "offxml", "OFFXML"])
1107
+ @pytest.mark.parametrize(
1108
+ "specified_format",
1109
+ [
1110
+ None,
1111
+ "xml",
1112
+ "XML",
1113
+ ".xml",
1114
+ ".XML",
1115
+ "offxml",
1116
+ "OFFXML",
1117
+ ".offxml",
1118
+ ".OFFXML",
1119
+ XMLParameterIOHandler(),
1120
+ ],
1121
+ )
1122
+ def test_xml_file_roundtrip_keep_cosmetic(self, file_path_extension, specified_format):
1123
+ """
1124
+ Test roundtripping a force field to an XML file with and without retaining cosmetic elements
1125
+ """
1126
+ # These files will be deleted once garbage collection runs (end of this function)
1127
+ iofile1 = NamedTemporaryFile(suffix="." + file_path_extension)
1128
+ iofile2 = NamedTemporaryFile(suffix="." + file_path_extension)
1129
+ iofile3 = NamedTemporaryFile(suffix="." + file_path_extension)
1130
+
1131
+ # Ensure an exception is raised if we try to read the XML string with cosmetic attributes
1132
+ with pytest.raises(
1133
+ SMIRNOFFSpecError,
1134
+ match=r"Unexpected kwarg [(]parameters: k, length[)] passed",
1135
+ ):
1136
+ ForceField(xml_ff_w_cosmetic_elements)
1137
+
1138
+ # Create a force field from XML successfully
1139
+ forcefield_1 = ForceField(xml_ff_w_cosmetic_elements, allow_cosmetic_attributes=True)
1140
+
1141
+ # Convert the force field back to XML, keeping cosmetic attributes
1142
+ forcefield_1.to_file(iofile1.name, discard_cosmetic_attributes=False, io_format=specified_format)
1143
+
1144
+ # Ensure that the new XML string has cosmetic attributes in it
1145
+ assert 'cosmetic_element="why not?"' in open(iofile1.name).read()
1146
+ assert 'parameterize_eval="blah=blah2"' in open(iofile1.name).read()
1147
+ with pytest.raises(
1148
+ SMIRNOFFSpecError,
1149
+ match=r"Unexpected kwarg [(]parameters: k, length[)] passed",
1150
+ ):
1151
+ ForceField(iofile1.name, allow_cosmetic_attributes=False)
1152
+
1153
+ # Complete the forcefield_1 --> file --> forcefield_2 roundtrip
1154
+ forcefield_2 = ForceField(iofile1.name, allow_cosmetic_attributes=True)
1155
+
1156
+ # Ensure that the force field remains the same after the roundtrip
1157
+ forcefield_2.to_file(iofile2.name, discard_cosmetic_attributes=False, io_format=specified_format)
1158
+ assert open(iofile1.name).read() == open(iofile2.name).read()
1159
+
1160
+ # Discard the cosmetic attributes and ensure that the string is different
1161
+ forcefield_2.to_file(iofile3.name, discard_cosmetic_attributes=True, io_format=specified_format)
1162
+ assert open(iofile1.name).read() != open(iofile3.name).read()
1163
+
1164
+ # Ensure that the new XML string does NOT have cosmetic attributes in it
1165
+ assert 'cosmetic_element="why not?"' not in open(iofile3.name).read()
1166
+ assert 'parameterize_eval="blah=blah2"' not in open(iofile3.name).read()
1167
+
1168
+ def test_load_section_without_section_version(self):
1169
+ """Ensure that a SMIRNOFFSpecError is raised if we try to load a SMIRNOFF section without a version.
1170
+ Section versions are a requirement added in the 0.3 spec."""
1171
+ with pytest.raises(
1172
+ SMIRNOFFSpecError,
1173
+ match=r"Missing version while trying to construct "
1174
+ r"<class 'openff.toolkit.typing.engines."
1175
+ r"smirnoff.parameters.ToolkitAM1BCCHandler'>.",
1176
+ ):
1177
+ ForceField(xml_without_section_version)
1178
+
1179
+ def test_load_two_sources(self):
1180
+ """Test loading data from two SMIRNOFF data sources"""
1181
+ ff = ForceField(xml_simple_ff, xml_ff_w_cosmetic_elements, allow_cosmetic_attributes=True)
1182
+ assert len(ff.get_parameter_handler("Bonds").parameters) == 5
1183
+
1184
+ def test_load_two_sources_authors_dates(self):
1185
+ """Test that authors and dates are handled properly"""
1186
+ ff = ForceField(
1187
+ xml_ff_w_cosmetic_elements,
1188
+ xml_ff_w_comments,
1189
+ allow_cosmetic_attributes=True,
1190
+ )
1191
+ xml_str = ff.to_string("XML")
1192
+ assert (
1193
+ "<Author>Alice and Bob AND C. I. Bayly, OpenEye/UC Irvine; C. C. Bannan, "
1194
+ "UC Irvine; D. L. Mobley, UC Irvine</Author>" in xml_str
1195
+ )
1196
+ assert "<Date>MMXVIII-VII-XIV AND 2018-07-14</Date>" in xml_str
1197
+
1198
+ # Test property getters
1199
+ assert (
1200
+ "Alice and Bob AND C. I. Bayly, OpenEye/UC Irvine; C. C. Bannan, "
1201
+ "UC Irvine; D. L. Mobley, UC Irvine" == ff.author
1202
+ )
1203
+ assert "MMXVIII-VII-XIV AND 2018-07-14" == ff.date
1204
+
1205
+ # Test property setters
1206
+ ff.author = "Me"
1207
+ ff.date = "yesteryear"
1208
+ xml_str = ff.to_string("XML")
1209
+ assert "<Author>Me</Author>" in xml_str
1210
+ assert "<Date>yesteryear</Date>" in xml_str
1211
+
1212
+ # Unset both author and date and ensure they don't get written out.
1213
+ ff.author = None
1214
+ ff.date = None
1215
+ xml_str = ff.to_string("XML")
1216
+ assert "<Author>" not in xml_str
1217
+ assert "<Date>" not in xml_str
1218
+
1219
+ def test_load_two_sources_incompatible_tags(self):
1220
+ """Test loading data from two SMIRNOFF data sources which have incompatible physics"""
1221
+ # Make an XML force field with a modified vdW 1-4 scaling factor
1222
+ nonstandard_xml_ff = xml_ff_w_comments.replace('scale14="0.5"', 'scale14="1.0"')
1223
+ with pytest.raises(
1224
+ IncompatibleParameterError,
1225
+ match=r"handler value: 0.5, incompatible value: 1.0",
1226
+ ):
1227
+ ForceField(xml_simple_ff, nonstandard_xml_ff)
1228
+
1229
+ def test_gbsahandler_sa_model_none(self):
1230
+ """
1231
+ Ensure that string values of "None" are correctly interpreted in the GBSAHandler's sa_model field
1232
+ """
1233
+ ForceField(xml_gbsa_ff)
1234
+
1235
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
1236
+ def test_parameterize_ethanol(self, toolkit_registry, force_field):
1237
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol.pdb"))
1238
+ molecules = [create_ethanol()]
1239
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
1240
+
1241
+ force_field.create_openmm_system(
1242
+ topology,
1243
+ toolkit_registry=toolkit_registry,
1244
+ )
1245
+
1246
+ def test_parameterize_ethanol_missing_torsion(self):
1247
+ from openff.interchange.exceptions import UnassignedTorsionError
1248
+
1249
+ forcefield = ForceField(xml_missing_torsion)
1250
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol.pdb"))
1251
+ molecules = [create_ethanol()]
1252
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
1253
+ with pytest.raises(
1254
+ UnassignedTorsionError,
1255
+ match="- Topology indices [(]5, 0, 1, 6[)]: "
1256
+ r"names and elements [(](H\d+)? H[)], [(](C\d+)? C[)], [(](C\d+)? C[)], [(](H\d+)? H[)],",
1257
+ ):
1258
+ forcefield.create_openmm_system(topology)
1259
+
1260
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
1261
+ def test_parameterize_1_cyclohexane_1_ethanol(
1262
+ self,
1263
+ toolkit_registry,
1264
+ force_field,
1265
+ ):
1266
+ """Test parameterizing a periodic system of two distinct molecules"""
1267
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_cyclohexane_1_ethanol.pdb"))
1268
+ # toolkit_wrapper = RDKitToolkitWrapper()
1269
+ molecules = [create_ethanol(), create_cyclohexane()]
1270
+ # molecules = [Molecule.from_file(get_data_file_path(name)) for name in ('molecules/ethanol.mol2',
1271
+ # 'molecules/cyclohexane.mol2')]
1272
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
1273
+
1274
+ force_field.create_openmm_system(topology)
1275
+
1276
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
1277
+ def test_parameterize_1_cyclohexane_1_ethanol_vacuum(
1278
+ self,
1279
+ toolkit_registry,
1280
+ force_field,
1281
+ ):
1282
+ """Test parametrizing a nonperiodic system of two distinct molecules"""
1283
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_cyclohexane_1_ethanol.pdb"))
1284
+ molecules = [create_ethanol(), create_cyclohexane()]
1285
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
1286
+ topology.box_vectors = None
1287
+
1288
+ force_field.create_openmm_system(topology)
1289
+
1290
+ @pytest.mark.slow
1291
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
1292
+ @pytest.mark.parametrize(
1293
+ "box",
1294
+ [
1295
+ "ethanol_water.pdb",
1296
+ "cyclohexane_water.pdb",
1297
+ "cyclohexane_ethanol_0.4_0.6.pdb",
1298
+ "propane_methane_butanol_0.2_0.3_0.5.pdb",
1299
+ ],
1300
+ )
1301
+ def test_parameterize_large_system(
1302
+ self,
1303
+ toolkit_registry,
1304
+ box,
1305
+ force_field,
1306
+ ):
1307
+ """Test parameterizing a large system of several distinct molecules.
1308
+ This test is very slow, so it is only run if the slow marker option is provided to pytest.
1309
+ """
1310
+ box_file_path = get_data_file_path(os.path.join("systems", "packmol_boxes", box))
1311
+ pdbfile = app.PDBFile(box_file_path)
1312
+ mol_names = ["water", "cyclohexane", "ethanol", "propane", "methane", "butanol"]
1313
+ sdf_files = [get_data_file_path(os.path.join("systems", "monomers", name + ".sdf")) for name in mol_names]
1314
+ molecules = [Molecule.from_file(sdf_file) for sdf_file in sdf_files]
1315
+ topology = Topology.from_openmm(
1316
+ pdbfile.topology,
1317
+ unique_molecules=molecules,
1318
+ )
1319
+
1320
+ force_field.create_openmm_system(
1321
+ topology,
1322
+ toolkit_registry=toolkit_registry,
1323
+ )
1324
+ # TODO: Add check to ensure system energy is finite
1325
+
1326
+ @requires_openeye
1327
+ def test_parameterize_ethanol_different_reference_ordering_openeye(self, force_field):
1328
+ """
1329
+ Test parameterizing the same PDB, using reference mol2s that have different atom orderings.
1330
+ The results of both should be identical.
1331
+ """
1332
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1333
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol.pdb"))
1334
+ # Load the unique molecules with one atom ordering
1335
+ molecules1 = [Molecule.from_file(get_data_file_path("molecules/ethanol.sdf"))]
1336
+ topology1 = Topology.from_openmm(
1337
+ pdbfile.topology,
1338
+ unique_molecules=molecules1,
1339
+ )
1340
+
1341
+ omm_system1 = force_field.create_openmm_system(
1342
+ topology1,
1343
+ toolkit_registry=toolkit_registry,
1344
+ )
1345
+ # Load the unique molecules with a different atom ordering
1346
+ molecules2 = [Molecule.from_file(get_data_file_path("molecules/ethanol_reordered.sdf"))]
1347
+ topology2 = Topology.from_openmm(
1348
+ pdbfile.topology,
1349
+ unique_molecules=molecules2,
1350
+ )
1351
+ omm_system2 = force_field.create_openmm_system(
1352
+ topology2,
1353
+ toolkit_registry=toolkit_registry,
1354
+ )
1355
+
1356
+ serialized_1 = XmlSerializer.serialize(omm_system1)
1357
+ serialized_2 = XmlSerializer.serialize(omm_system2)
1358
+
1359
+ serialized_1 = round_charge(serialized_1)
1360
+ serialized_2 = round_charge(serialized_2)
1361
+
1362
+ assert serialized_1 == serialized_2
1363
+
1364
+ @requires_rdkit
1365
+ def test_parameterize_ethanol_different_reference_ordering_rdkit(self, force_field):
1366
+ """
1367
+ Test parameterizing the same PDB, using reference sdfs that have different atom orderings.
1368
+ The results of both should be identical.
1369
+ """
1370
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper, AmberToolsToolkitWrapper])
1371
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol.pdb"))
1372
+
1373
+ # Load the unique molecules with one atom ordering
1374
+ molecules1 = [Molecule.from_file(get_data_file_path("molecules/ethanol.sdf"))]
1375
+ topology1 = Topology.from_openmm(
1376
+ pdbfile.topology,
1377
+ unique_molecules=molecules1,
1378
+ )
1379
+
1380
+ omm_system1 = force_field.create_openmm_system(
1381
+ topology1,
1382
+ toolkit_registry=toolkit_registry,
1383
+ )
1384
+
1385
+ # Load the unique molecules with a different atom ordering
1386
+ molecules2 = [Molecule.from_file(get_data_file_path("molecules/ethanol_reordered.sdf"))]
1387
+ topology2 = Topology.from_openmm(
1388
+ pdbfile.topology,
1389
+ unique_molecules=molecules2,
1390
+ )
1391
+ omm_system2 = force_field.create_openmm_system(
1392
+ topology2,
1393
+ toolkit_registry=toolkit_registry,
1394
+ )
1395
+
1396
+ serialized_1 = XmlSerializer.serialize(omm_system1)
1397
+ serialized_2 = XmlSerializer.serialize(omm_system2)
1398
+
1399
+ serialized_1 = round_charge(serialized_1)
1400
+ serialized_2 = round_charge(serialized_2)
1401
+
1402
+ assert serialized_1 == serialized_2
1403
+
1404
+ @requires_rdkit
1405
+ def test_parameterize_mol_missing_stereo_rdkit(self, force_field):
1406
+ """
1407
+ Test parameterizing a molecule with undefined stereochemsity using the RDKit/AmberTools backend.
1408
+ """
1409
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper, AmberToolsToolkitWrapper])
1410
+
1411
+ molecule = Molecule.from_smiles("CC1CCC(=O)O1", allow_undefined_stereo=True)
1412
+ topology = Topology.from_molecules([molecule])
1413
+
1414
+ force_field.create_openmm_system(
1415
+ topology,
1416
+ toolkit_registry=toolkit_registry,
1417
+ )
1418
+
1419
+ @requires_openeye
1420
+ def test_parameterize_mol_missing_stereo_openeye(self, force_field):
1421
+ """
1422
+ Test parameterizing a molecule with undefined stereochemsity using the OpenEye backend.
1423
+ """
1424
+ toolkit_registry = ToolkitRegistry(toolkit_precedence=[OpenEyeToolkitWrapper])
1425
+
1426
+ molecule = Molecule.from_smiles("CC1CCC(=O)O1", allow_undefined_stereo=True)
1427
+ topology = Topology.from_molecules([molecule])
1428
+
1429
+ force_field.create_openmm_system(
1430
+ topology,
1431
+ toolkit_registry=toolkit_registry,
1432
+ )
1433
+
1434
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
1435
+ def test_pass_invalid_kwarg_to_create_openmm_system(self, toolkit_registry, force_field):
1436
+ """Test to ensure an exception is raised when an unrecognized kwarg is passed"""
1437
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol.pdb"))
1438
+ molecules = []
1439
+ molecules.append(Molecule.from_smiles("CCO"))
1440
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
1441
+
1442
+ with pytest.raises(
1443
+ TypeError,
1444
+ match=r"got an unexpected keyword argument .*invalid_kwarg.*",
1445
+ ):
1446
+ # TODO: specify desired toolkit_registry behavior in Interchange
1447
+ force_field.create_openmm_system(
1448
+ topology,
1449
+ invalid_kwarg="aaa",
1450
+ toolkit_registry=toolkit_registry,
1451
+ )
1452
+
1453
+ def test_electrostatics_switch_width_unsupported(self):
1454
+ handler = ElectrostaticsHandler(version=0.4)
1455
+ with pytest.raises(
1456
+ SMIRNOFFSpecUnimplementedError,
1457
+ match="not support an electrostatic switch width",
1458
+ ):
1459
+ handler.switch_width = 1.234 * unit.nanometer
1460
+
1461
+ @pytest.mark.parametrize("mod_cuoff", [True, False])
1462
+ def test_nonbonded_cutoff_no_box_vectors(self, mod_cuoff, force_field):
1463
+ """Ensure that the NonbondedForce objects use the cutoff specified in the
1464
+ ParameterHandler, not the OpenMM defaults"""
1465
+ top = Topology.from_molecules(create_ethanol())
1466
+ assert top.box_vectors is None
1467
+
1468
+ if mod_cuoff:
1469
+ # Ensure a modified, non-default cutoff will be propogated through
1470
+ force_field["vdW"].cutoff = 0.777 * unit.nanometer
1471
+ force_field["Electrostatics"].cutoff = 0.777 * unit.nanometer
1472
+
1473
+ omm_sys = force_field.create_openmm_system(top)
1474
+
1475
+ for f in omm_sys.getForces():
1476
+ if isinstance(f, openmm.NonbondedForce):
1477
+ nonbonded_force = f
1478
+
1479
+ found_cutoff = from_openmm(nonbonded_force.getCutoffDistance())
1480
+ vdw_cutoff = force_field["vdW"].cutoff
1481
+ e_cutoff = force_field["Electrostatics"].cutoff
1482
+ assert (found_cutoff - vdw_cutoff).m_as(unit.nanometer) < 1e-6
1483
+ assert (found_cutoff - e_cutoff).m_as(unit.nanometer) < 1e-6
1484
+
1485
+ @pytest.mark.skip(reason="periodic_potential='Coulomb' not supported by Interchange")
1486
+ def test_vdw_cutoff_overrides_electrostatics(self):
1487
+ topology = Molecule.from_smiles("[#18]").to_topology()
1488
+ topology.box_vectors = [3, 3, 3] * unit.nanometer
1489
+
1490
+ force_field = ForceField()
1491
+
1492
+ vdw_handler = vdWHandler(version=0.4)
1493
+ vdw_handler.cutoff = 6.0 * unit.angstrom
1494
+ vdw_handler.scale14 = 1.0
1495
+
1496
+ vdw_handler.add_parameter(
1497
+ {
1498
+ "smirks": "[#18:1]",
1499
+ "epsilon": 1.0 * unit.kilojoules_per_mole,
1500
+ "sigma": 1.0 * unit.angstrom,
1501
+ }
1502
+ )
1503
+ force_field.register_parameter_handler(vdw_handler)
1504
+
1505
+ electrostatics_handler = ElectrostaticsHandler(version=0.3)
1506
+ electrostatics_handler.cutoff = 7.0 * unit.angstrom
1507
+ electrostatics_handler.periodic_potential = "PME"
1508
+ force_field.register_parameter_handler(electrostatics_handler)
1509
+
1510
+ library_charges = LibraryChargeHandler(version=0.3)
1511
+ library_charges.add_parameter(
1512
+ {
1513
+ "smirks": "[#18:1]",
1514
+ "charge1": 0.0 * unit.elementary_charge,
1515
+ }
1516
+ )
1517
+ force_field.register_parameter_handler(library_charges)
1518
+
1519
+ system = force_field.create_openmm_system(topology)
1520
+
1521
+ assert np.isclose(
1522
+ system.getForce(0).getCutoffDistance().value_in_unit(openmm_unit.angstrom),
1523
+ 6.0,
1524
+ )
1525
+
1526
+ # Ensure an exception is raised when the electrostatics cutoff is meaningful
1527
+ # and mismatched
1528
+ force_field.deregister_parameter_handler(force_field["Electrostatics"])
1529
+
1530
+ # TODO: Don't change the box vectors once this case is supported
1531
+ topology.box_vectors = None
1532
+ electrostatics_handler.periodic_potential = "Coulomb"
1533
+ force_field.register_parameter_handler(electrostatics_handler)
1534
+
1535
+ with pytest.raises(IncompatibleParameterError, match="cutoff must equal"):
1536
+ force_field.create_openmm_system(topology)
1537
+
1538
+ def test_nondefault_nonbonded_cutoff(self):
1539
+ """Test that the cutoff of the NonbondedForce is set properly when vdW and Electrostatics cutoffs
1540
+ are identical but not the psuedo-default value of 9.0 A."""
1541
+ topology = Molecule.from_smiles("[#18]").to_topology()
1542
+ topology.box_vectors = [3, 3, 3] * unit.nanometer
1543
+
1544
+ force_field = ForceField()
1545
+
1546
+ vdw_handler = vdWHandler(version=0.4)
1547
+ vdw_handler.cutoff = 7.89 * unit.angstrom
1548
+ vdw_handler.scale14 = 1.0
1549
+
1550
+ vdw_handler.add_parameter(
1551
+ {
1552
+ "smirks": "[#18:1]",
1553
+ "epsilon": 1.0 * unit.kilojoules_per_mole,
1554
+ "sigma": 1.0 * unit.angstrom,
1555
+ }
1556
+ )
1557
+ force_field.register_parameter_handler(vdw_handler)
1558
+
1559
+ electrostatics_handler = ElectrostaticsHandler(version=0.3)
1560
+ electrostatics_handler.cutoff = 7.89 * unit.angstrom
1561
+ electrostatics_handler.periodic_potential = "PME"
1562
+ force_field.register_parameter_handler(electrostatics_handler)
1563
+
1564
+ library_charges = LibraryChargeHandler(version=0.3)
1565
+ library_charges.add_parameter(
1566
+ {
1567
+ "smirks": "[#18:1]",
1568
+ "charge1": 0.0 * unit.elementary_charge,
1569
+ }
1570
+ )
1571
+ force_field.register_parameter_handler(library_charges)
1572
+
1573
+ system = force_field.create_openmm_system(topology)
1574
+
1575
+ found_cutoff = system.getForce(0).getCutoffDistance().value_in_unit(openmm_unit.angstrom)
1576
+
1577
+ assert abs(found_cutoff - 7.89) < 1e-6
1578
+
1579
+ def test_registered_parameter_handlers(self, force_field):
1580
+ """Test registered_parameter_handlers property"""
1581
+ registered_handlers = force_field.registered_parameter_handlers
1582
+
1583
+ expected_handlers = [
1584
+ "Bonds",
1585
+ "Angles",
1586
+ "ProperTorsions",
1587
+ "ImproperTorsions",
1588
+ "vdW",
1589
+ "Electrostatics",
1590
+ "ToolkitAM1BCC",
1591
+ ]
1592
+
1593
+ for expected_handler in expected_handlers:
1594
+ assert expected_handler in registered_handlers
1595
+
1596
+ assert "LibraryChrages" not in registered_handlers
1597
+
1598
+ def test_parameter_handler_lookup(self, force_field):
1599
+ """Ensure __getitem__ lookups work"""
1600
+
1601
+ handlers_before = sorted(force_field._parameter_handlers)
1602
+
1603
+ for val in handlers_before:
1604
+ looked_up_handler = force_field[val]
1605
+ assert isinstance(looked_up_handler, ParameterHandler)
1606
+
1607
+ handlers_after = sorted(force_field._parameter_handlers)
1608
+
1609
+ assert handlers_before == handlers_after
1610
+
1611
+ @pytest.mark.parametrize("unregistered_handler", ["LibraryCharges", "foobar"])
1612
+ def test_unregistered_parameter_handler_lookup(self, unregistered_handler, force_field):
1613
+ """Ensure ForceField.__getitem__ lookups do not register new handlers"""
1614
+ assert unregistered_handler not in force_field._parameter_handlers
1615
+ with pytest.raises(KeyError, match=unregistered_handler):
1616
+ force_field[unregistered_handler]
1617
+ assert unregistered_handler not in force_field._parameter_handlers
1618
+
1619
+ def test_lookup_parameter_handler_object(self, force_field):
1620
+ """Ensure ForceField.__getitem__ raises NotImplemented when passed a ParameterHandler object"""
1621
+ bonds = force_field["Bonds"]
1622
+ with pytest.raises(NotImplementedError):
1623
+ force_field[bonds]
1624
+ with pytest.raises(NotImplementedError):
1625
+ force_field[type(bonds)]
1626
+
1627
+ def test_lookup_parameter_type(self, force_field):
1628
+ """Test both ForceField and ParameterHandler __getitem__ methods"""
1629
+ smirks = "[#6X4:1]-[#6X3:2]=[#8X1+0]"
1630
+
1631
+ param = force_field["Bonds"][smirks]
1632
+ assert param.smirks == smirks
1633
+
1634
+ # Look up the same param by its index in the ParameterList
1635
+ param_idx = 2
1636
+ assert param == force_field["Bonds"][param_idx]
1637
+
1638
+ with pytest.raises(
1639
+ ParameterLookupError,
1640
+ match="Lookup by instance is not supported",
1641
+ ):
1642
+ force_field["Bonds"][param]
1643
+ with pytest.raises(
1644
+ ParameterLookupError,
1645
+ match=r" not found in ParameterList",
1646
+ ):
1647
+ force_field["vdW"][smirks]
1648
+
1649
+ def test_lookup_duplicate_parameter_type(self, force_field):
1650
+ """Test that if a parameter SMIRKS appears twice, lookups will yield the second copy"""
1651
+ first_bond = force_field["Bonds"][0]
1652
+ force_field["Bonds"].add_parameter(
1653
+ {
1654
+ "smirks": first_bond.smirks,
1655
+ "k": first_bond.k / 2,
1656
+ "length": first_bond.length / 2,
1657
+ "id": first_bond.id + "2",
1658
+ },
1659
+ allow_duplicate_smirks=True,
1660
+ )
1661
+ result = force_field["Bonds"][first_bond.smirks]
1662
+ assert result == force_field["Bonds"].parameters[first_bond.smirks]
1663
+ assert result.id == force_field["Bonds"][0].id + "2"
1664
+ assert result.k == first_bond.k / 2
1665
+ assert result.length == first_bond.length / 2
1666
+
1667
+ @pytest.mark.parametrize(
1668
+ "to_deregister",
1669
+ [
1670
+ "ToolkitAM1BCC",
1671
+ ToolkitAM1BCCHandler,
1672
+ ToolkitAM1BCCHandler(skip_version_check=True),
1673
+ ],
1674
+ )
1675
+ def test_deregister_parameter_handler(self, to_deregister):
1676
+ """Ensure that ForceField.deregister_parameter_handler behaves correctly"""
1677
+ ff = ForceField(xml_simple_ff)
1678
+ # Make sure the handler is present in the test force field
1679
+ handler_found = False
1680
+ for handler in ff._parameter_handlers.values():
1681
+ if isinstance(handler, ToolkitAM1BCCHandler):
1682
+ handler_found = True
1683
+ assert handler_found
1684
+ ff.deregister_parameter_handler(to_deregister)
1685
+ # Make sure the handler is absent after deletion
1686
+ handler_found = False
1687
+ for handler in ff._parameter_handlers.values():
1688
+ if isinstance(handler, ToolkitAM1BCCHandler):
1689
+ handler_found = True
1690
+ assert not (handler_found)
1691
+
1692
+ with pytest.raises(KeyError):
1693
+ ff.deregister_parameter_handler(to_deregister)
1694
+
1695
+ def test_hash(self):
1696
+ """Test hashes on all available force fields"""
1697
+ ffs = get_available_force_fields()
1698
+
1699
+ for ff1, ff2 in itertools.combinations(ffs, 2):
1700
+ assert hash(ff1) != hash(ff2)
1701
+
1702
+ def test_hash_cosmetic(self, force_field):
1703
+ """Test that adding a cosmetic attribute does not change the hash"""
1704
+ hash_without_cosmetic = hash(force_field)
1705
+
1706
+ force_field.get_parameter_handler("Bonds").add_cosmetic_attribute("foo", 4)
1707
+ assert "foo" in force_field["Bonds"]._cosmetic_attribs
1708
+
1709
+ hash_with_cosmetic = hash(force_field)
1710
+
1711
+ assert hash_with_cosmetic == hash_without_cosmetic
1712
+
1713
+ def test_hash_strip_author_date(self):
1714
+ """Ensure that author and date are ignored in hashing"""
1715
+ ff_no_data = ForceField()
1716
+ ff_with_author_date = ForceField()
1717
+ ff_with_author_date.author = "John Doe"
1718
+ ff_with_author_date.date = "2020-01-01"
1719
+
1720
+ assert hash(ff_no_data) == hash(ff_with_author_date)
1721
+
1722
+ def test_hash_strip_ids(self):
1723
+ """Test the behavior of strip_ids arg to __hash__()"""
1724
+ from openff.toolkit.typing.engines.smirnoff import BondHandler
1725
+
1726
+ length = 1 * unit.angstrom
1727
+ k = 10 * unit.kilocalorie_per_mole / unit.angstrom**2
1728
+
1729
+ param_with_id = {
1730
+ "smirks": "[*:1]-[*:2]",
1731
+ "length": length,
1732
+ "k": k,
1733
+ "id": "b1",
1734
+ }
1735
+
1736
+ param_without_id = {
1737
+ "smirks": "[*:1]-[*:2]",
1738
+ "length": length,
1739
+ "k": k,
1740
+ }
1741
+
1742
+ ff_with_id = ForceField()
1743
+ ff_without_id = ForceField()
1744
+
1745
+ ff_with_id.register_parameter_handler(BondHandler(version=0.3))
1746
+ ff_without_id.register_parameter_handler(BondHandler(version=0.3))
1747
+
1748
+ ff_with_id.get_parameter_handler("Bonds").add_parameter(param_with_id)
1749
+ ff_without_id.get_parameter_handler("Bonds").add_parameter(param_without_id)
1750
+
1751
+ assert hash(ff_with_id) == hash(ff_without_id)
1752
+
1753
+ def test_issue_1216(self):
1754
+ """Test that the conflict between vsitehandler and librarychargehandler
1755
+ identified in issue #1216 remains resolved.
1756
+
1757
+ https://github.com/openforcefield/openff-toolkit/issues/1216
1758
+ """
1759
+ from openff.toolkit.typing.engines.smirnoff.parameters import VirtualSiteHandler
1760
+
1761
+ force_field = ForceField()
1762
+ force_field.get_parameter_handler("Electrostatics")
1763
+
1764
+ vsite_handler: VirtualSiteHandler = force_field.get_parameter_handler("VirtualSites")
1765
+ vsite_handler.add_parameter(
1766
+ {
1767
+ "smirks": "[#6:1][#9:2]",
1768
+ "name": "EP",
1769
+ "type": "BondCharge",
1770
+ "distance": 1.0 * unit.angstrom,
1771
+ "match": "all_permutations",
1772
+ "charge_increment1": 0.2 * unit.elementary_charge,
1773
+ "charge_increment2": 0.1 * unit.elementary_charge,
1774
+ "sigma": 1.0 * unit.angstrom,
1775
+ "epsilon": 0.0 * unit.kilocalorie_per_mole,
1776
+ }
1777
+ )
1778
+
1779
+ library_handler: LibraryChargeHandler = force_field.get_parameter_handler("LibraryCharges")
1780
+ library_handler.add_parameter(
1781
+ {
1782
+ "smirks": "[F:2][C:1]([H:3])([H:4])([H:5])",
1783
+ "charge": [
1784
+ 0.3 * unit.elementary_charge,
1785
+ -0.15 * unit.elementary_charge,
1786
+ -0.05 * unit.elementary_charge,
1787
+ -0.05 * unit.elementary_charge,
1788
+ -0.05 * unit.elementary_charge,
1789
+ ],
1790
+ }
1791
+ )
1792
+ force_field.label_molecules(Molecule.from_smiles("CF").to_topology())
1793
+
1794
+ def test_issue_1475(self):
1795
+ """Reproduce issue #1475."""
1796
+ force_field = ForceField("openff-2.0.0.offxml")
1797
+
1798
+ class BogusHandler(ParameterHandler):
1799
+ _TAGNAME = "bogus"
1800
+
1801
+ bogus_handler = BogusHandler(version=0.3)
1802
+
1803
+ force_field.register_parameter_handler(bogus_handler)
1804
+
1805
+ assert "bogus" in force_field._parameter_handlers.keys()
1806
+ assert bogus_handler in force_field._parameter_handlers.values()
1807
+
1808
+ assert "bogus" in force_field._parameter_handler_classes.keys()
1809
+ assert BogusHandler in force_field._parameter_handler_classes.values()
1810
+
1811
+ assert force_field["bogus"] is not None
1812
+
1813
+ def test_handy_handler_creation(self):
1814
+ """See issue #1757"""
1815
+ for key in [
1816
+ "vdW",
1817
+ "Electrostatics",
1818
+ "ToolkitAM1BCC",
1819
+ "LibraryCharges",
1820
+ "ChargeIncrementModel",
1821
+ "Bonds",
1822
+ "Angles",
1823
+ "ProperTorsions",
1824
+ "ImproperTorsions",
1825
+ "VirtualSites",
1826
+ "GBSA",
1827
+ ]:
1828
+ ForceField().get_parameter_handler(key)
1829
+
1830
+
1831
+ class TestForceFieldPluginLoading:
1832
+ def test_handlers_tracked_if_already_loaded(self):
1833
+ """Reproduce issue #1542."""
1834
+ from openff.toolkit.typing.engines.smirnoff.plugins import load_handler_plugins
1835
+
1836
+ plugins = load_handler_plugins()
1837
+
1838
+ if len(plugins) == 0:
1839
+ pytest.skip("Test assumes that some ParameterHandler plugins are available")
1840
+
1841
+ assert ForceField(load_plugins=False)._plugin_parameter_handler_classes == []
1842
+ assert ForceField(load_plugins=True)._plugin_parameter_handler_classes == [*plugins]
1843
+
1844
+
1845
+ class TestForceFieldSerializaiton(_ForceFieldFixtures):
1846
+ def test_json_dump(self, force_field):
1847
+ """Test that at a ForceField can at least be dumped to JSON without error."""
1848
+ import json
1849
+
1850
+ json.dumps(force_field._to_smirnoff_data())
1851
+
1852
+
1853
+ class TestForceFieldChargeAssignment(_ForceFieldFixtures):
1854
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
1855
+ def test_charges_from_molecule(self, toolkit_registry, force_field):
1856
+ """Test skipping charge generation and instead getting charges from the original Molecule"""
1857
+ # Create an ethanol molecule without using a toolkit
1858
+ molecules = [create_ethanol()]
1859
+
1860
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol.pdb"))
1861
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
1862
+ omm_system = force_field.create_openmm_system(
1863
+ topology, charge_from_molecules=molecules, toolkit_registry=toolkit_registry
1864
+ )
1865
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
1866
+ expected_charges = (
1867
+ (0, -0.4 * openmm_unit.elementary_charge),
1868
+ (1, -0.3 * openmm_unit.elementary_charge),
1869
+ (2, -0.2 * openmm_unit.elementary_charge),
1870
+ )
1871
+ for particle_index, expected_charge in expected_charges:
1872
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
1873
+ assert q == expected_charge
1874
+
1875
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
1876
+ def test_charges_from_molecule_reordered(self, toolkit_registry, force_field):
1877
+ """A copy of test_charges_from_molecule but with the same molecule in a different atom order."""
1878
+ molecules = [create_ethanol()]
1879
+
1880
+ # In 1_ethanol_reordered.pdb, the first three atoms go O-C-C instead of C-C-O. This part of the test ensures
1881
+ # that the charges are correctly mapped according to this PDB in the resulting system.
1882
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol_reordered.pdb"))
1883
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
1884
+
1885
+ omm_system = force_field.create_openmm_system(
1886
+ topology,
1887
+ charge_from_molecules=molecules,
1888
+ toolkit_registry=toolkit_registry,
1889
+ )
1890
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
1891
+ expected_charges = (
1892
+ (0, -0.2 * openmm_unit.elementary_charge),
1893
+ (1, -0.4 * openmm_unit.elementary_charge),
1894
+ (2, -0.3 * openmm_unit.elementary_charge),
1895
+ )
1896
+ for particle_index, expected_charge in expected_charges:
1897
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
1898
+ assert q == expected_charge
1899
+
1900
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
1901
+ def test_nonintegral_charge_exception(self, toolkit_registry, force_field):
1902
+ # Create an ethanol molecule without using a toolkit
1903
+ from openff.interchange.exceptions import NonIntegralMoleculeChargeError
1904
+
1905
+ ethanol = create_ethanol()
1906
+ ethanol.partial_charges[0] = 1.0 * unit.elementary_charge
1907
+
1908
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol.pdb"))
1909
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=[ethanol])
1910
+
1911
+ with pytest.raises(NonIntegralMoleculeChargeError, match=r"Molecule .* has a net charge"):
1912
+ force_field.create_openmm_system(
1913
+ topology,
1914
+ charge_from_molecules=[ethanol],
1915
+ toolkit_registry=toolkit_registry,
1916
+ )
1917
+
1918
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
1919
+ def test_nonintegral_charge_override(self, toolkit_registry, force_field):
1920
+ ethanol = create_ethanol()
1921
+ ethanol.partial_charges[0] = 1.0 * unit.elementary_charge
1922
+
1923
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol.pdb"))
1924
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=[ethanol])
1925
+
1926
+ # Pass when the `allow_nonintegral_charges` keyword is included
1927
+ force_field.create_openmm_system(
1928
+ topology,
1929
+ charge_from_molecules=[ethanol],
1930
+ toolkit_registry=toolkit_registry,
1931
+ allow_nonintegral_charges=True,
1932
+ )
1933
+
1934
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
1935
+ def test_some_charges_from_molecule(self, toolkit_registry, force_field):
1936
+ """
1937
+ Test creating an OpenMM system where some charges come from a Molecule, but others come from toolkit
1938
+ calculation
1939
+ """
1940
+ ethanol = create_ethanol()
1941
+ cyclohexane = create_cyclohexane()
1942
+ molecules = [ethanol, cyclohexane]
1943
+
1944
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_cyclohexane_1_ethanol.pdb"))
1945
+ topology = Topology.from_openmm(
1946
+ pdbfile.topology,
1947
+ unique_molecules=molecules,
1948
+ )
1949
+
1950
+ omm_system = force_field.create_openmm_system(
1951
+ topology, charge_from_molecules=[ethanol], toolkit_registry=toolkit_registry
1952
+ )
1953
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
1954
+ expected_charges = (
1955
+ (18, -0.4 * openmm_unit.elementary_charge),
1956
+ (19, -0.3 * openmm_unit.elementary_charge),
1957
+ (20, -0.2 * openmm_unit.elementary_charge),
1958
+ )
1959
+ for particle_index, expected_charge in expected_charges:
1960
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
1961
+ assert q == expected_charge
1962
+ for atom_index in range(topology.n_atoms):
1963
+ q, _, _ = nonbondedForce.getParticleParameters(atom_index)
1964
+ assert q != (0.0 * unit.elementary_charge)
1965
+
1966
+ @pytest.mark.parametrize(
1967
+ "ff_inputs",
1968
+ [
1969
+ [
1970
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
1971
+ get_data_file_path("test_forcefields/tip3p.offxml"),
1972
+ ],
1973
+ ["openff-2.0.0.offxml"],
1974
+ ],
1975
+ )
1976
+ def test_library_charges_to_single_water(self, ff_inputs):
1977
+ """Test assigning charges to one water molecule using library charges"""
1978
+ ff = ForceField(*ff_inputs)
1979
+ mol = Molecule.from_file(get_data_file_path(os.path.join("systems", "monomers", "water.sdf")))
1980
+ omm_system = ff.create_openmm_system(mol.to_topology())
1981
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
1982
+ expected_charges = [-0.834, 0.417, 0.417] * openmm_unit.elementary_charge
1983
+ for particle_index, expected_charge in enumerate(expected_charges):
1984
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
1985
+ assert q == expected_charge
1986
+
1987
+ def test_parse_library_charges_from_spec_docs(self):
1988
+ """Ensure that the examples for librarycharges in the SMIRNOFF spec page are still valid"""
1989
+ # TODO: This test is practically useless while the XML strings are hard-coded at the top of this file.
1990
+ # We should implement something like doctests for the XML snippets on the SMIRNOFF spec page.
1991
+ ForceField(xml_spec_docs_ala_library_charges_xml)
1992
+ ForceField(xml_spec_docs_tip3p_library_charges_xml)
1993
+
1994
+ def test_parse_charge_increment_model_from_spec_docs(self):
1995
+ """Ensure that the examples for librarycharges in the SMIRNOFF spec page are still valid"""
1996
+ # TODO: This test is practically useless while the XML strings are hard-coded at the top of this file.
1997
+ # We should implement something like doctests for the XML snippets on the SMIRNOFF spec page.
1998
+ ForceField(xml_spec_docs_charge_increment_model_xml)
1999
+
2000
+ def test_charge_increment_model_forward_and_reverse_ethanol(self):
2001
+ """Test application of ChargeIncrements to the same molecule with different orderings in the topology"""
2002
+ file_path = get_data_file_path("test_forcefields/test_forcefield.offxml")
2003
+ ff = ForceField(file_path, xml_charge_increment_model_ff_ethanol)
2004
+ del ff._parameter_handlers["ToolkitAM1BCC"]
2005
+ top = Topology.from_molecules([create_ethanol(), create_reversed_ethanol()])
2006
+ sys = ff.create_openmm_system(top)
2007
+ nonbonded_force = next(force for force in sys.getForces() if isinstance(force, openmm.NonbondedForce))
2008
+ expected_charges = [
2009
+ 0.2,
2010
+ -0.15,
2011
+ -0.05,
2012
+ 0.0,
2013
+ 0.0,
2014
+ 0.0,
2015
+ 0.0,
2016
+ 0.0,
2017
+ 0.0,
2018
+ 0.0,
2019
+ 0.0,
2020
+ 0.0,
2021
+ 0.0,
2022
+ 0.0,
2023
+ 0.0,
2024
+ -0.05,
2025
+ -0.15,
2026
+ 0.2,
2027
+ ] * openmm_unit.elementary_charge
2028
+ for idx, expected_charge in enumerate(expected_charges):
2029
+ charge, _, _ = nonbonded_force.getParticleParameters(idx)
2030
+ assert abs(charge - expected_charge) < 1.0e-6 * openmm_unit.elementary_charge
2031
+
2032
+ def test_charge_increment_model_one_less_ci_than_tagged_atom(self):
2033
+ """
2034
+ Ensure that we support the behavior where a ChargeIncrement is initialized with one less chargeincrement value
2035
+ than tagged atom. We test this by making two equivalent (one with fully explicit CIs, the other with some
2036
+ implicit CIa) FFs and ensuring that both perform the same parameterization.
2037
+ """
2038
+ # Make a FF from each OFFXML string
2039
+ file_path = get_data_file_path("test_forcefields/test_forcefield.offxml")
2040
+ ff1 = ForceField(file_path, xml_charge_increment_model_ff_one_less_ci)
2041
+ del ff1._parameter_handlers["ToolkitAM1BCC"]
2042
+ ff2 = ForceField(file_path, xml_charge_increment_model_ff_no_missing_cis)
2043
+ del ff2._parameter_handlers["ToolkitAM1BCC"]
2044
+ top = Topology.from_molecules([create_ethanol()])
2045
+ # Make a system from each FF
2046
+ sys1 = ff2.create_openmm_system(top)
2047
+ sys2 = ff2.create_openmm_system(top)
2048
+ # Extract the nonbonded force from each system
2049
+ nonbonded_force1 = next(force for force in sys1.getForces() if isinstance(force, openmm.NonbondedForce))
2050
+ nonbonded_force2 = next(force for force in sys2.getForces() if isinstance(force, openmm.NonbondedForce))
2051
+
2052
+ # Ensure that the systems both have the correct charges assigned
2053
+ expected_charges = [
2054
+ 0.17,
2055
+ -0.18,
2056
+ -0.04,
2057
+ 0.01,
2058
+ 0.01,
2059
+ 0.01,
2060
+ 0.01,
2061
+ 0.01,
2062
+ 0.0,
2063
+ ] * openmm_unit.elementary_charge
2064
+ for idx, expected_charge in enumerate(expected_charges):
2065
+ charge1, _, _ = nonbonded_force1.getParticleParameters(idx)
2066
+ charge2, _, _ = nonbonded_force2.getParticleParameters(idx)
2067
+ assert abs(charge1 - expected_charge) < 1.0e-6 * openmm_unit.elementary_charge
2068
+ assert charge1 == charge2
2069
+
2070
+ def test_charge_increment_model_invalid_number_of_cis(self, force_field):
2071
+ """
2072
+ Ensure that we support the behavior where a ChargeIncrement with an incorrect number of tagged atoms
2073
+ and chargeincrementX values riases an error
2074
+ """
2075
+ del force_field._parameter_handlers["ToolkitAM1BCC"]
2076
+ cimh = force_field.get_parameter_handler(
2077
+ "ChargeIncrementModel",
2078
+ handler_kwargs={"version": "0.3", "partial_charge_method": "formal_charge"},
2079
+ )
2080
+ cimh.add_parameter(
2081
+ {
2082
+ "smirks": "[C:1][C:2][O:3]",
2083
+ "charge_increment1": 0.3 * unit.elementary_charge,
2084
+ "charge_increment2": -0.2 * unit.elementary_charge,
2085
+ "charge_increment3": -0.1 * unit.elementary_charge,
2086
+ }
2087
+ )
2088
+
2089
+ # Add ONE MORE chargeincrement parameter than there are tagged atoms and ensure an exception is raised
2090
+ cimh.parameters[0].charge_increment.append(0.01 * unit.elementary_charge)
2091
+ top = Topology.from_molecules([create_ethanol()])
2092
+ with pytest.raises(
2093
+ SMIRNOFFSpecError,
2094
+ match="number of chargeincrements must be either the same",
2095
+ ):
2096
+ force_field.create_openmm_system(top)
2097
+
2098
+ # Ensure that parameterization with the correct number of increments DOES NOT raise an exception
2099
+ cimh.parameters[0].charge_increment = cimh.parameters[0].charge_increment[:2]
2100
+ force_field.create_openmm_system(top)
2101
+
2102
+ # Add TWO LESS chargeincrement parameters than there are tagged atoms and ensure an exception is raised
2103
+ cimh.parameters[0].charge_increment = cimh.parameters[0].charge_increment[:1]
2104
+ with pytest.raises(
2105
+ SMIRNOFFSpecError,
2106
+ match="number of chargeincrements must be either the same",
2107
+ ):
2108
+ force_field.create_openmm_system(top)
2109
+
2110
+ def test_charge_increment_model_initialize_with_no_elements(self):
2111
+ """Ensure that we can initialize a ForceField object from an OFFXML with a ChargeIncrementModel header, but no
2112
+ ChargeIncrement elements"""
2113
+ ForceField(xml_charge_increment_model_formal_charges)
2114
+
2115
+ def test_charge_increment_model_net_charge(self):
2116
+ """Test application of charge increments on a molecule with a net charge"""
2117
+ file_path = get_data_file_path("test_forcefields/test_forcefield.offxml")
2118
+ ff = ForceField(file_path, xml_charge_increment_model_ff_net_charge)
2119
+ del ff._parameter_handlers["ToolkitAM1BCC"]
2120
+
2121
+ acetate = create_acetate()
2122
+ top = acetate.to_topology()
2123
+
2124
+ sys = ff.create_openmm_system(top)
2125
+ nonbonded_force = next(force for force in sys.getForces() if isinstance(force, openmm.NonbondedForce))
2126
+ expected_charges = [
2127
+ 0,
2128
+ 0.15,
2129
+ -0.2,
2130
+ -0.95,
2131
+ 0,
2132
+ 0,
2133
+ 0,
2134
+ ] * openmm_unit.elementary_charge
2135
+ for idx, expected_charge in enumerate(expected_charges):
2136
+ charge, _, _ = nonbonded_force.getParticleParameters(idx)
2137
+ assert abs(charge - expected_charge) < 1.0e-6 * openmm_unit.elementary_charge
2138
+
2139
+ def test_charge_increment_model_deduplicate_symmetric_matches(self):
2140
+ """Test that chargeincrementmodelhandler deduplicates symmetric matches"""
2141
+ ethanol = create_ethanol()
2142
+ top = ethanol.to_topology()
2143
+
2144
+ file_path = get_data_file_path("test_forcefields/test_forcefield.offxml")
2145
+ # Test a charge increment that matches all C-H bonds at once
2146
+ # (this should be applied once: C0-H3-H4-H5)
2147
+ ff = ForceField(file_path, xml_charge_increment_model_ff_match_all)
2148
+ del ff._parameter_handlers["ToolkitAM1BCC"]
2149
+
2150
+ sys = ff.create_openmm_system(top)
2151
+ nonbonded_force = next(force for force in sys.getForces() if isinstance(force, openmm.NonbondedForce))
2152
+ expected_charges = [
2153
+ 0.3,
2154
+ 0,
2155
+ 0,
2156
+ -0.1,
2157
+ -0.1,
2158
+ -0.1,
2159
+ 0.0,
2160
+ 0.0,
2161
+ 0.0,
2162
+ ] * openmm_unit.elementary_charge
2163
+ for idx, expected_charge in enumerate(expected_charges):
2164
+ charge, _, _ = nonbonded_force.getParticleParameters(idx)
2165
+ assert abs(charge - expected_charge) < 1.0e-6 * openmm_unit.elementary_charge
2166
+
2167
+ # Test a charge increment that matches two C-H bonds at a time
2168
+ # (this should be applied 3 times: C0-H3-H4, C0-H3-H5, C0-H4-H5)
2169
+ ff = ForceField(file_path, xml_charge_increment_model_ff_match_two)
2170
+ del ff._parameter_handlers["ToolkitAM1BCC"]
2171
+
2172
+ sys = ff.create_openmm_system(top)
2173
+ nonbonded_force = next(force for force in sys.getForces() if isinstance(force, openmm.NonbondedForce))
2174
+ expected_charges = [
2175
+ 0.3,
2176
+ 0,
2177
+ 0,
2178
+ -0.1,
2179
+ -0.1,
2180
+ -0.1,
2181
+ 0.0,
2182
+ 0.0,
2183
+ 0.0,
2184
+ ] * openmm_unit.elementary_charge
2185
+ for idx, expected_charge in enumerate(expected_charges):
2186
+ charge, _, _ = nonbonded_force.getParticleParameters(idx)
2187
+ assert abs(charge - expected_charge) < 1.0e-6 * openmm_unit.elementary_charge
2188
+
2189
+ # Test a charge increment that matches ONE C-H bond at a time
2190
+ # (this should be applied three times: C0-H3, C0-H4, C0-H5)
2191
+ ff = ForceField(file_path, xml_charge_increment_model_ff_match_once)
2192
+ del ff._parameter_handlers["ToolkitAM1BCC"]
2193
+
2194
+ sys = ff.create_openmm_system(top)
2195
+ nonbonded_force = next(force for force in sys.getForces() if isinstance(force, openmm.NonbondedForce))
2196
+ expected_charges = [
2197
+ 0.3,
2198
+ 0,
2199
+ 0,
2200
+ -0.1,
2201
+ -0.1,
2202
+ -0.1,
2203
+ 0.0,
2204
+ 0.0,
2205
+ 0.0,
2206
+ ] * openmm_unit.elementary_charge
2207
+ for idx, expected_charge in enumerate(expected_charges):
2208
+ charge, _, _ = nonbonded_force.getParticleParameters(idx)
2209
+ assert abs(charge - expected_charge) < 1.0e-6 * openmm_unit.elementary_charge
2210
+
2211
+ def test_charge_increment_model_completely_overlapping_matches_override(self):
2212
+ """Ensure that DIFFERENT chargeincrements override one another if they apply to the
2213
+ same atoms, regardless of order"""
2214
+ file_path = get_data_file_path("test_forcefields/test_forcefield.offxml")
2215
+ ff = ForceField(file_path, xml_charge_increment_model_ff_override)
2216
+ del ff._parameter_handlers["ToolkitAM1BCC"]
2217
+
2218
+ ethanol = create_ethanol()
2219
+ top = ethanol.to_topology()
2220
+ sys = ff.create_openmm_system(top)
2221
+ nonbonded_force = next(force for force in sys.getForces() if isinstance(force, openmm.NonbondedForce))
2222
+ expected_charges = [
2223
+ 0.3,
2224
+ 0,
2225
+ 0,
2226
+ -0.1,
2227
+ -0.1,
2228
+ -0.1,
2229
+ 0.0,
2230
+ 0.0,
2231
+ 0.0,
2232
+ ] * openmm_unit.elementary_charge
2233
+ for idx, expected_charge in enumerate(expected_charges):
2234
+ charge, _, _ = nonbonded_force.getParticleParameters(idx)
2235
+ assert abs(charge - expected_charge) < 1.0e-6 * openmm_unit.elementary_charge
2236
+
2237
+ def test_charge_increment_model_partially_overlapping_matches_both_apply(self):
2238
+ """Ensure that DIFFERENT chargeincrements BOTH get applied if they match
2239
+ a partially-overlapping set of atoms"""
2240
+ file_path = get_data_file_path("test_forcefields/test_forcefield.offxml")
2241
+ ff = ForceField(file_path, xml_charge_increment_model_ff_both_apply)
2242
+ del ff._parameter_handlers["ToolkitAM1BCC"]
2243
+
2244
+ ethanol = create_ethanol()
2245
+ top = ethanol.to_topology()
2246
+ sys = ff.create_openmm_system(top)
2247
+ nonbonded_force = next(force for force in sys.getForces() if isinstance(force, openmm.NonbondedForce))
2248
+ expected_charges = [
2249
+ 0.35,
2250
+ -0.05,
2251
+ 0,
2252
+ -0.1,
2253
+ -0.1,
2254
+ -0.1,
2255
+ 0.0,
2256
+ 0.0,
2257
+ 0.0,
2258
+ ] * openmm_unit.elementary_charge
2259
+ for idx, expected_charge in enumerate(expected_charges):
2260
+ charge, _, _ = nonbonded_force.getParticleParameters(idx)
2261
+ assert abs(charge - expected_charge) < 1.0e-6 * openmm_unit.elementary_charge
2262
+
2263
+ @pytest.mark.parametrize("inputs", partial_charge_method_resolution_matrix)
2264
+ def test_partial_charge_resolution(self, inputs):
2265
+ """Check that the proper partial charge methods are available, and that unavailable partial charge methods
2266
+ raise an exception.
2267
+ """
2268
+ toolkit_wrapper_class = inputs["toolkit"]
2269
+ if not (toolkit_wrapper_class.is_available()):
2270
+ pytest.skip(f"{toolkit_wrapper_class} is not available.")
2271
+ toolkit_wrapper = toolkit_wrapper_class()
2272
+ partial_charge_method = inputs["partial_charge_method"]
2273
+ expected_exception = inputs["exception"]
2274
+ expected_exception_match = inputs["exception_match"]
2275
+ ethanol = create_ethanol()
2276
+ ethanol.generate_conformers()
2277
+ if expected_exception is None:
2278
+ ethanol.assign_partial_charges(
2279
+ partial_charge_method=partial_charge_method,
2280
+ toolkit_registry=toolkit_wrapper,
2281
+ )
2282
+ abs_charge_sum = 0.0 * unit.elementary_charge
2283
+
2284
+ # Ensure that nonzero charges were assigned
2285
+ for pc in ethanol.partial_charges:
2286
+ abs_charge_sum += abs(pc)
2287
+ assert abs_charge_sum > 0.5 * unit.elementary_charge
2288
+
2289
+ else:
2290
+ with pytest.raises(expected_exception, match=expected_exception_match):
2291
+ ethanol.assign_partial_charges(
2292
+ partial_charge_method=partial_charge_method,
2293
+ toolkit_registry=toolkit_wrapper,
2294
+ )
2295
+
2296
+ def test_library_charge_hierarchy(self):
2297
+ """Test assigning charges to one water molecule using library charges, where two LCs match and the
2298
+ assignment is determined by order they are added to the force field"""
2299
+ # Test with xml_OH_library_charges_xml loaded last, which should assign dummy partial charges
2300
+ ff = ForceField(
2301
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
2302
+ get_data_file_path("test_forcefields/tip3p.offxml"),
2303
+ xml_OH_library_charges_xml,
2304
+ )
2305
+ mol = Molecule.from_file(get_data_file_path(os.path.join("systems", "monomers", "water.sdf")))
2306
+ omm_system = ff.create_openmm_system(mol.to_topology())
2307
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
2308
+ expected_charges = [-2.0, 1.0, 1.0] * openmm_unit.elementary_charge
2309
+ for particle_index, expected_charge in enumerate(expected_charges):
2310
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
2311
+ assert q == expected_charge
2312
+
2313
+ # Test again, but with tip3p.offxml loaded last (loading the correct partial charges)
2314
+ ff = ForceField(
2315
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
2316
+ xml_OH_library_charges_xml,
2317
+ get_data_file_path("test_forcefields/tip3p.offxml"),
2318
+ )
2319
+ omm_system = ff.create_openmm_system(mol.to_topology())
2320
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
2321
+ expected_charges = [-0.834, 0.417, 0.417] * openmm_unit.elementary_charge
2322
+ for particle_index, expected_charge in enumerate(expected_charges):
2323
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
2324
+ assert q == expected_charge
2325
+
2326
+ def test_library_charges_to_two_waters(self):
2327
+ """Test assigning charges to two water molecules using library charges"""
2328
+ ff = ForceField(
2329
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
2330
+ get_data_file_path("test_forcefields/tip3p.offxml"),
2331
+ )
2332
+ mol = Molecule.from_file(get_data_file_path(os.path.join("systems", "monomers", "water.sdf")))
2333
+ top = Topology.from_molecules([mol, mol])
2334
+ omm_system = ff.create_openmm_system(top)
2335
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
2336
+ expected_charges = [
2337
+ -0.834,
2338
+ 0.417,
2339
+ 0.417,
2340
+ -0.834,
2341
+ 0.417,
2342
+ 0.417,
2343
+ ] * openmm_unit.elementary_charge
2344
+ for particle_index, expected_charge in enumerate(expected_charges):
2345
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
2346
+ assert q == expected_charge
2347
+
2348
+ def test_library_charges_to_three_ethanols_different_atom_ordering(self):
2349
+ """Test assigning charges to three ethanols with different atom orderings"""
2350
+ # Define a library charge parameter for ethanol (C1-C2-O3) where C1 has charge -0.2, and its Hs have -0.02,
2351
+ # C2 has charge -0.1 and its Hs have -0.01, and O3 has charge 0.3, and its H has charge 0.08
2352
+
2353
+ ff = ForceField(
2354
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
2355
+ xml_ethanol_library_charges_ff,
2356
+ )
2357
+
2358
+ # ethanol.sdf
2359
+ # H5 H8
2360
+ # | |
2361
+ # H6 - C1 - C2 - O3 - H4
2362
+ # | |
2363
+ # H7 H9
2364
+ #
2365
+ # ethanol_reordered.sdf (The middle C and O switch indices)
2366
+ # H5 H8
2367
+ # | |
2368
+ # H6 - C1 - C3 - O2 - H4
2369
+ # | |
2370
+ # H7 H9
2371
+ #
2372
+ # create_reversed_ethanol()
2373
+ # H5 H2
2374
+ # | |
2375
+ # H4 - C8 - C7 - O6 - H0
2376
+ # | |
2377
+ # H3 H1
2378
+
2379
+ molecules = [
2380
+ Molecule.from_file(get_data_file_path("molecules/ethanol.sdf")),
2381
+ Molecule.from_file(get_data_file_path("molecules/ethanol_reordered.sdf")),
2382
+ create_reversed_ethanol(),
2383
+ ]
2384
+ top = Topology.from_molecules(molecules)
2385
+ omm_system = ff.create_openmm_system(top)
2386
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
2387
+ expected_charges = [
2388
+ -0.2,
2389
+ -0.1,
2390
+ 0.3,
2391
+ 0.08,
2392
+ -0.02,
2393
+ -0.02,
2394
+ -0.02,
2395
+ -0.01,
2396
+ -0.01,
2397
+ -0.2,
2398
+ 0.3,
2399
+ -0.1,
2400
+ 0.08,
2401
+ -0.02,
2402
+ -0.02,
2403
+ -0.02,
2404
+ -0.01,
2405
+ -0.01,
2406
+ 0.08,
2407
+ -0.01,
2408
+ -0.01,
2409
+ -0.02,
2410
+ -0.02,
2411
+ -0.02,
2412
+ 0.3,
2413
+ -0.1,
2414
+ -0.2,
2415
+ ] * openmm_unit.elementary_charge
2416
+ for particle_index, expected_charge in enumerate(expected_charges):
2417
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
2418
+ assert q == expected_charge
2419
+
2420
+ @pytest.mark.parametrize("monatomic_ion,formal_charge", generate_monatomic_ions())
2421
+ def test_library_charges_monatomic_ions(self, monatomic_ion, formal_charge):
2422
+ """Test assigning library charges to each of the monatomic ions in openff-1.1.0.xml"""
2423
+ ff = ForceField(
2424
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
2425
+ get_data_file_path("test_forcefields/ion_charges.offxml"),
2426
+ )
2427
+ mol = Molecule.from_smiles(f"[{monatomic_ion}]")
2428
+ omm_system = ff.create_openmm_system(mol.to_topology())
2429
+
2430
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
2431
+ q, _, _ = nonbondedForce.getParticleParameters(0)
2432
+ assert q == formal_charge
2433
+
2434
+ def test_charge_method_hierarchy(self):
2435
+ """Ensure that molecules are parameterized by charge_from_molecules first, then library charges
2436
+ if not applicable, then AM1BCC otherwise"""
2437
+ ff = ForceField(
2438
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
2439
+ xml_CH_zeroes_library_charges_xml,
2440
+ get_data_file_path("test_forcefields/tip3p.offxml"),
2441
+ xml_charge_increment_model_formal_charges,
2442
+ )
2443
+ # Cyclohexane will be assigned nonzero charges based on `charge_from_molecules` kwarg
2444
+ cyclohexane = Molecule.from_file(get_data_file_path(os.path.join("systems", "monomers", "cyclohexane.sdf")))
2445
+ # Butanol will be assigned zero-valued charges based on `charge_from_molecules` kwarg
2446
+ butanol = Molecule.from_file(get_data_file_path(os.path.join("systems", "monomers", "butanol.sdf")))
2447
+ # Propane will be assigned charges from AM1BCC
2448
+ propane = Molecule.from_file(get_data_file_path(os.path.join("systems", "monomers", "propane.sdf")))
2449
+ # Water will be assigned TIP3P librarycharges
2450
+ water = Molecule.from_file(get_data_file_path(os.path.join("systems", "monomers", "water.sdf")))
2451
+ # Ethanol should be caught by ToolkitAM1BCC
2452
+ ethanol = Molecule.from_file(get_data_file_path(os.path.join("systems", "monomers", "ethanol.sdf")))
2453
+ # iodide should fail to be assigned charges by AM1-BCC, and instead be caught by ChargeIncrementHandler
2454
+ # (and assigned formal charge by dummy charge method)
2455
+ iodide = Molecule.from_smiles("[I-1]")
2456
+
2457
+ # Assign dummy partial charges to cyclohexane, which we expect to find in the final system since it
2458
+ # is included in the charge_from_molecules kwarg to create_openmm_system
2459
+ cyclohexane.partial_charges = unit.Quantity(
2460
+ np.array(
2461
+ [
2462
+ -0.2,
2463
+ -0.2,
2464
+ -0.2,
2465
+ -0.2,
2466
+ -0.2,
2467
+ -0.2,
2468
+ 0.1,
2469
+ 0.1,
2470
+ 0.1,
2471
+ 0.1,
2472
+ 0.1,
2473
+ 0.1,
2474
+ 0.1,
2475
+ 0.1,
2476
+ 0.1,
2477
+ 0.1,
2478
+ 0.1,
2479
+ 0.1,
2480
+ ]
2481
+ ),
2482
+ unit.elementary_charge,
2483
+ )
2484
+
2485
+ # There were previously known issues when parameterizing molecules with all zero charges,
2486
+ # so test this explicitly with butanol. Since butanol will be in the charge_from_molecules kwarg,
2487
+ # we expect to find these charges in the final system.
2488
+ butanol.partial_charges = np.array([0.0] * 15) * unit.elementary_charge
2489
+
2490
+ # Add dummy partial charges to propane, which should be IGNORED since it
2491
+ # isn't in the charge_from_molecules kwarg
2492
+ propane.partial_charges = np.array([99.0] * 11) * unit.elementary_charge
2493
+
2494
+ # Add dummy partial charges to water, which should be IGNORED since it
2495
+ # isn't in the charge_from_molecules kwarg
2496
+ water.partial_charges = np.array([99.0] * 3) * unit.elementary_charge
2497
+
2498
+ # molecule correct charge method
2499
+ molecules = [
2500
+ cyclohexane, # charge_from_molecules kwarg
2501
+ butanol, # charge_from_molecules kwarg
2502
+ propane, # library charges
2503
+ water, # library charges
2504
+ ethanol, # AM1-BCC
2505
+ iodide,
2506
+ ] # charge increment model (formal charge)
2507
+ top = Topology.from_molecules(molecules)
2508
+ omm_system = ff.create_openmm_system(top, charge_from_molecules=[cyclohexane, butanol])
2509
+ existing = [f for f in omm_system.getForces() if type(f) is NonbondedForce]
2510
+
2511
+ # Ensure that the handlers do not make multiple NonbondedForce objects
2512
+ assert len(existing) == 1
2513
+ nonbondedForce = existing[0]
2514
+ expected_charges = [ # cyclohexane (18 atoms) should have the following values from charge_from_mols
2515
+ -0.2,
2516
+ -0.2,
2517
+ -0.2,
2518
+ -0.2,
2519
+ -0.2,
2520
+ -0.2,
2521
+ 0.1,
2522
+ 0.1,
2523
+ 0.1,
2524
+ 0.1,
2525
+ 0.1,
2526
+ 0.1,
2527
+ 0.1,
2528
+ 0.1,
2529
+ 0.1,
2530
+ 0.1,
2531
+ 0.1,
2532
+ 0.1,
2533
+ # butanol (15 atoms) should have the following values from charge_from_mols
2534
+ 0.0,
2535
+ 0.0,
2536
+ 0.0,
2537
+ 0.0,
2538
+ 0.0,
2539
+ 0.0,
2540
+ 0.0,
2541
+ 0.0,
2542
+ 0.0,
2543
+ 0.0,
2544
+ 0.0,
2545
+ 0.0,
2546
+ 0.0,
2547
+ 0.0,
2548
+ 0.0,
2549
+ # propane (11 atoms) should have the following values from xml_CH_zeroes_library_charges_xml
2550
+ 0.0,
2551
+ 0.0,
2552
+ 0.0,
2553
+ 0.0,
2554
+ 0.0,
2555
+ 0.0,
2556
+ 0.0,
2557
+ 0.0,
2558
+ 0.0,
2559
+ 0.0,
2560
+ 0.0,
2561
+ # water (3 atoms) should have the following charges from tip3p.offxml
2562
+ -0.834,
2563
+ 0.417,
2564
+ 0.417,
2565
+ ] * openmm_unit.elementary_charge
2566
+
2567
+ # Ensure that the first four molecules have exactly the charges we intended
2568
+ for particle_index, expected_charge in enumerate(expected_charges):
2569
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
2570
+ assert q == expected_charge
2571
+
2572
+ # Ensure the last molecule (ethanol) had _some_ nonzero charge assigned by an AM1BCC implementation
2573
+ for particle_index in range(len(expected_charges), top.n_atoms - 1):
2574
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
2575
+ assert q != 0 * unit.elementary_charge
2576
+
2577
+ # Ensure that iodine has a charge of -1, specified by charge increment model charge_method="formal charge"
2578
+ q, _, _ = nonbondedForce.getParticleParameters(top.n_atoms - 1)
2579
+ assert q == -1.0 * openmm_unit.elementary_charge
2580
+
2581
+ def test_assign_charges_to_molecule_in_parts_using_multiple_library_charges(self):
2582
+ """Test assigning charges to parts of a molecule using two library charge lines. Note that these LibraryCharge
2583
+ SMIRKS have partial overlap, so this also tests that the hierarchy is correctly obeyed.
2584
+ """
2585
+ ff = ForceField(
2586
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
2587
+ xml_ethanol_library_charges_in_parts_ff,
2588
+ )
2589
+
2590
+ molecules = [
2591
+ Molecule.from_file(get_data_file_path("molecules/ethanol.sdf")),
2592
+ Molecule.from_file(get_data_file_path("molecules/ethanol_reordered.sdf")),
2593
+ ]
2594
+ top = Topology.from_molecules(molecules)
2595
+ omm_system = ff.create_openmm_system(top)
2596
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
2597
+ expected_charges = [
2598
+ -0.2,
2599
+ -0.1,
2600
+ 0.3,
2601
+ 0.08,
2602
+ -0.02,
2603
+ -0.02,
2604
+ -0.02,
2605
+ -0.01,
2606
+ -0.01,
2607
+ -0.2,
2608
+ 0.3,
2609
+ -0.1,
2610
+ 0.08,
2611
+ -0.02,
2612
+ -0.02,
2613
+ -0.02,
2614
+ -0.01,
2615
+ -0.01,
2616
+ ] * openmm_unit.elementary_charge
2617
+ for particle_index, expected_charge in enumerate(expected_charges):
2618
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
2619
+ assert q == expected_charge
2620
+
2621
+ def test_assign_charges_using_library_charges_by_single_atoms(self):
2622
+ """Test assigning charges to parts of a molecule using per-atom library charges. Note that these LibraryCharge
2623
+ SMIRKS will match multiple atoms, so this is also a test of correct usage of the parameter hierarchy..
2624
+ """
2625
+ ff = ForceField(
2626
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
2627
+ xml_ethanol_library_charges_by_atom_ff,
2628
+ )
2629
+
2630
+ molecules = [
2631
+ Molecule.from_file(get_data_file_path("molecules/ethanol.sdf")),
2632
+ Molecule.from_file(get_data_file_path("molecules/ethanol_reordered.sdf")),
2633
+ ]
2634
+ top = Topology.from_molecules(molecules)
2635
+ omm_system = ff.create_openmm_system(top)
2636
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
2637
+ expected_charges = [
2638
+ -0.2,
2639
+ -0.1,
2640
+ 0.3,
2641
+ 0.08,
2642
+ -0.02,
2643
+ -0.02,
2644
+ -0.02,
2645
+ -0.01,
2646
+ -0.01,
2647
+ -0.2,
2648
+ 0.3,
2649
+ -0.1,
2650
+ 0.08,
2651
+ -0.02,
2652
+ -0.02,
2653
+ -0.02,
2654
+ -0.01,
2655
+ -0.01,
2656
+ ] * openmm_unit.elementary_charge
2657
+ for particle_index, expected_charge in enumerate(expected_charges):
2658
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
2659
+ assert q == expected_charge
2660
+
2661
+ def test_library_charges_dont_parameterize_molecule_because_of_incomplete_coverage(
2662
+ self,
2663
+ ):
2664
+ """Fail to assign charges to a molecule because not all atoms can be assigned"""
2665
+ molecules = [Molecule.from_file(get_data_file_path("molecules/toluene.sdf"))]
2666
+ top = Topology.from_molecules(molecules)
2667
+
2668
+ # The library charges in the FF should not be able to fully cover toluene
2669
+ ff = ForceField(
2670
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
2671
+ xml_ethanol_library_charges_by_atom_ff,
2672
+ )
2673
+ # Delete the ToolkitAM1BCCHandler so the molecule won't get charges from anywhere
2674
+ del ff._parameter_handlers["ToolkitAM1BCC"]
2675
+ with pytest.raises(RuntimeError, match="Cc1ccccc1 could not be fully assigned charges"):
2676
+ omm_system = ff.create_openmm_system(top)
2677
+
2678
+ # If we do NOT delete the ToolkiAM1BCCHandler, then toluene should be assigned some nonzero partial charges.
2679
+ # The exact value will vary by toolkit, so we don't test that here.
2680
+ ff = ForceField(
2681
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
2682
+ xml_ethanol_library_charges_by_atom_ff,
2683
+ )
2684
+ omm_system = ff.create_openmm_system(top)
2685
+ nonbondedForce = next(f for f in omm_system.getForces() if type(f) is NonbondedForce)
2686
+ for particle_index in range(top.n_atoms):
2687
+ q, _, _ = nonbondedForce.getParticleParameters(particle_index)
2688
+ assert q != 0 * unit.elementary_charge
2689
+
2690
+ def test_library_charges_from_molecule_manual(self, force_field):
2691
+ """Test that constructing a LibraryChargeHandler from partial charges on Molecule objects
2692
+ produces the same result as using the `charge_from_molecules` kwarg. while manually
2693
+ setting the molecule's partial charges to arbitrary non-physical values"""
2694
+ # TODO: Remove this test if `charge_from_molecules` is depcreated (#806)
2695
+ mol = Molecule.from_mapped_smiles("[Cl:1][C:2]#[C:3][F:4]")
2696
+ mol.partial_charges = np.linspace(-0.3, 0.3, 4) * unit.elementary_charge
2697
+
2698
+ using_kwarg = force_field.create_openmm_system(topology=mol.to_topology(), charge_from_molecules=[mol])
2699
+
2700
+ library_charges = LibraryChargeHandler.LibraryChargeType.from_molecule(mol)
2701
+ force_field.register_parameter_handler(LibraryChargeHandler(version=0.3))
2702
+ force_field["LibraryCharges"].add_parameter(parameter=library_charges)
2703
+ using_library_charges = force_field.create_openmm_system(topology=mol.to_topology())
2704
+
2705
+ compare_partial_charges(using_kwarg, using_library_charges)
2706
+
2707
+ def test_library_charges_from_molecule_assigned(self, force_field):
2708
+ """Test that constructing a LibraryChargeHandler from partial charges on Molecule objects
2709
+ produces the same result as using the `charge_from_molecules` kwarg. while manually
2710
+ setting the molecule's partial charges to arbitrary non-physical values"""
2711
+ mol = Molecule.from_smiles("CCO")
2712
+ mol.assign_partial_charges(partial_charge_method="mmff94")
2713
+
2714
+ using_kwarg = force_field.create_openmm_system(topology=mol.to_topology(), charge_from_molecules=[mol])
2715
+
2716
+ library_charges = LibraryChargeHandler.LibraryChargeType.from_molecule(mol)
2717
+ force_field.register_parameter_handler(LibraryChargeHandler(version=0.3))
2718
+ force_field["LibraryCharges"].add_parameter(parameter=library_charges)
2719
+ using_library_charges = force_field.create_openmm_system(topology=mol.to_topology())
2720
+
2721
+ compare_partial_charges(using_kwarg, using_library_charges)
2722
+
2723
+ @requires_openeye
2724
+ def test_toolkit_am1bcc_uses_elf10_if_oe_is_available(self, force_field):
2725
+ """Ensure that the ToolkitAM1BCCHandler assigns ELF10 charges if OpenEye is available."""
2726
+ # Can't just use CCO - Molecule needs to be big enough to realistically
2727
+ # result in more than one conformer when ELF10 is requested
2728
+ mol = Molecule.from_smiles("OCCCCCCO")
2729
+
2730
+ # The test forcefield "out of the box" just uses ToolkitAM1BCC, so this
2731
+ # should produce ELF10 charges
2732
+ sys = force_field.create_openmm_system(topology=mol.to_topology())
2733
+
2734
+ # Make another system with a force field that has the ToolkitAM1BCCHandler
2735
+ # removed, and is explicitly told to use a ChargeIncrementModelHandler
2736
+ # with AM1BCCELF10 charges. Ensure that the resulting charges are identical.
2737
+ force_field.deregister_parameter_handler("ToolkitAM1BCC")
2738
+ cimh = force_field.get_parameter_handler(
2739
+ "ChargeIncrementModel",
2740
+ {"version": 0.3, "partial_charge_method": "am1bccelf10"},
2741
+ )
2742
+
2743
+ sys_a1b_elf10 = force_field.create_openmm_system(topology=mol.to_topology())
2744
+
2745
+ compare_partial_charges(sys, sys_a1b_elf10)
2746
+
2747
+ # Now modify the ChargeIncrementModelHandler to specifically use single-conformer
2748
+ # AM1BCC and ensure that the resulting charges are different from the first system.
2749
+ cimh.partial_charge_method = "am1bcc"
2750
+ assert force_field["ChargeIncrementModel"].partial_charge_method == "am1bcc"
2751
+
2752
+ sys_a1b_single_conf = force_field.create_openmm_system(topology=mol.to_topology())
2753
+ # Ensure that we get different results with AM1BCC ELF10 and single conf AM1BCC
2754
+ with pytest.raises(AssertionError):
2755
+ compare_partial_charges(sys_a1b_elf10, sys_a1b_single_conf)
2756
+
2757
+
2758
+ class TestForceFieldConstraints:
2759
+ """Tests that constraints are correctly applied and behave correctly."""
2760
+
2761
+ @classmethod
2762
+ def check_molecule_constraints(cls, molecule, system, bond_elements, bond_length):
2763
+ """Check that the bonds in the molecule is correctly constrained."""
2764
+ for constraint_idx in range(system.getNumConstraints()):
2765
+ atom1_idx, atom2_idx, distance = system.getConstraintParameters(constraint_idx)
2766
+ atom_elements = {
2767
+ molecule.atoms[atom1_idx].symbol,
2768
+ molecule.atoms[atom2_idx].symbol,
2769
+ }
2770
+ assert atom_elements == bond_elements
2771
+ assert np.isclose(
2772
+ distance.value_in_unit(openmm_unit.angstrom),
2773
+ bond_length.m_as(unit.angstrom),
2774
+ )
2775
+
2776
+ def test_constraints_hbonds(self):
2777
+ """Test that hydrogen bonds constraints are applied correctly to a ethane molecule."""
2778
+ # Parametrize an ethane molecule.
2779
+ ethane = Molecule.from_smiles("CC")
2780
+ topology = Topology.from_molecules([ethane])
2781
+ ff = ForceField(XML_FF_GENERICS, get_data_file_path("test_forcefields/old/hbonds.offxml"))
2782
+ system = ff.create_openmm_system(topology)
2783
+
2784
+ # Check that all C-H bonds have been constrained to the FF bond length.
2785
+ self.check_molecule_constraints(ethane, system, bond_elements={"C", "H"}, bond_length=1.09 * unit.angstrom)
2786
+
2787
+
2788
+ def generate_alkethoh_parameters_assignment_cases():
2789
+ """Create dynamically all test cases that should be ran for the AlkEthOH set."""
2790
+ # These AlkEthOH molecules are always run by test_alkethoh_parameters_assignment.
2791
+ fast_test_cases = ["r0", "r12", "r118", "c38", "c100", "c1161", "c1266"]
2792
+
2793
+ def extract_id(file_path):
2794
+ """Extract the AlkEthOH molecule ID from the file path."""
2795
+ # An example of file path is AlkEthOH_tripos/AlkEthOH_chain_filt1/AlkEthOH_c555.crd
2796
+ return os.path.splitext(os.path.basename(file_path))[0][9:]
2797
+
2798
+ # Get all the molecules ids from the tarfiles. The tarball is extracted
2799
+ # in conftest.py if slow tests are activated.
2800
+ import tarfile
2801
+
2802
+ alkethoh_tar_file_path = get_data_file_path(os.path.join("molecules", "AlkEthOH_tripos.tar.gz"))
2803
+ with tarfile.open(alkethoh_tar_file_path, "r:gz") as tar:
2804
+ # Collect all the files discarding the duplicates in the test_filt1 folder.
2805
+ slow_test_cases = {
2806
+ extract_id(m.name) for m in tar.getmembers() if "crd" in m.name and "test_filt1" not in m.name
2807
+ }
2808
+
2809
+ # Remove fast test cases from slow ones to avoid duplicate tests.
2810
+ # Remove also water (c1302), which was reparameterized in AlkEthOH
2811
+ # to be TIP3P (not covered by Frosst_AlkEthOH_parmAtFrosst.
2812
+ for fast_test_case in [*fast_test_cases, "c1302"]:
2813
+ slow_test_cases.remove(fast_test_case)
2814
+
2815
+ # Mark all slow cases as slow.
2816
+ slow_test_cases = [pytest.param(case, marks=pytest.mark.slow) for case in sorted(slow_test_cases)]
2817
+
2818
+ # Isolate the AlkEthOH ID.
2819
+ return fast_test_cases + slow_test_cases
2820
+
2821
+
2822
+ def generate_freesolv_parameters_assignment_cases():
2823
+ """Create dynamically all test cases that should be ran for the FreeSolv set."""
2824
+ import tarfile
2825
+
2826
+ # For these tests, UndefinedStereochemistryError is ignored.
2827
+ # The chirality was manually checked (see issue #175).
2828
+ ignore_undefined_stereo = {"2501588", "3266352", "7829570"}
2829
+
2830
+ # These molecules are always tested by test_freesolv_parameters_assignment().
2831
+ # Each test case is (freesolv_id, force_field_version, allow_undefined_stereo).
2832
+ fast_test_cases = [
2833
+ ("1019269", "0_0_4_fixed", False),
2834
+ (
2835
+ "63712",
2836
+ "0_0_2",
2837
+ False,
2838
+ ), # The XML was regenerated after fixing the issue described in #179.
2839
+ ("1723043", "0_0_2", False),
2840
+ ("2501588", "0_0_2", True), # Test impropers and undefined stereochemistry.
2841
+ (
2842
+ "3323117",
2843
+ "0_0_2",
2844
+ False,
2845
+ ), # The XML was regenerated after fixing the issue described in #179.
2846
+ ("1107178", "0_0_2", False), # Molecule with iodine
2847
+ ("1036761", "0_0_2", False), # Molecule with primary amine
2848
+ ]
2849
+
2850
+ def extract_id(file_path):
2851
+ """Extract the FreeSolv ID and force field version from the file subpath."""
2852
+ # An example of file path is FreeSolv/xml_0_0_4_fixed/mobley_7913234_vacuum.xml
2853
+ freesolv_id = os.path.basename(file_path).split("_")[1]
2854
+ force_field_version = os.path.basename(os.path.dirname(file_path))[4:]
2855
+ allow_undefined_stereo = freesolv_id in ignore_undefined_stereo
2856
+ return (freesolv_id, force_field_version, allow_undefined_stereo)
2857
+
2858
+ # Get all the tarball XML files available. The tarball is extracted
2859
+ # in conftest.py if slow tests are activated.
2860
+ freesolv_tar_file_path = get_data_file_path(os.path.join("molecules", "FreeSolv.tar.gz"))
2861
+ with tarfile.open(freesolv_tar_file_path, "r:gz") as tar:
2862
+ slow_test_cases = {extract_id(m.name) for m in tar.getmembers() if ".xml" in m.name}
2863
+
2864
+ # Remove fast test cases from slow ones to avoid duplicate tests.
2865
+ for fast_test_case in fast_test_cases:
2866
+ slow_test_cases.remove(fast_test_case)
2867
+
2868
+ # Mark all slow cases as slow.
2869
+ slow_test_cases = [pytest.param(*case, marks=pytest.mark.slow) for case in sorted(slow_test_cases)]
2870
+
2871
+ return fast_test_cases + slow_test_cases
2872
+
2873
+
2874
+ class TestForceFieldParameterAssignment(_ForceFieldFixtures):
2875
+ """Regression tests checking that parameters are assigned correctly."""
2876
+
2877
+ @requires_openeye_mol2
2878
+ @pytest.mark.parametrize("alkethoh_id", generate_alkethoh_parameters_assignment_cases())
2879
+ def test_alkethoh_parameters_assignment(self, alkethoh_id, alkethoh_forcefield):
2880
+ """Test that ForceField assign parameters correctly in the AlkEthOH set.
2881
+ The test compares the System parameters of a AlkEthOH molecule
2882
+ parameterized with AMBER and Frosst_AlkEthOH_parmAtFrosst.offxml.
2883
+
2884
+ The AMBER files were prepared following the pipeline described here:
2885
+ https://github.com/openforcefield/open-forcefield-data/tree/master/Model-Systems/AlkEthOH_distrib/
2886
+ They were built for the SMIRNOFF parametrization to yield exact same
2887
+ parameters.
2888
+
2889
+ The AlkEthOH set, however, does not have impropers, which should be
2890
+ tested separately. Currently, test_freesolv_parameters_assignment
2891
+ does the job.
2892
+
2893
+ """
2894
+ from openff.toolkit._tests.utils import (
2895
+ compare_amber_smirnoff,
2896
+ get_alkethoh_file_path,
2897
+ )
2898
+
2899
+ # Obtain the path to the input files.
2900
+ alkethoh_name = "AlkEthOH_" + alkethoh_id
2901
+ mol2_filepath, top_filepath, crd_filepath = get_alkethoh_file_path(alkethoh_name, get_amber=True)
2902
+
2903
+ # Load molecule.
2904
+ molecule = Molecule.from_file(mol2_filepath)
2905
+
2906
+ # Compare parameters. Skip the energy checks as the parameter check should be
2907
+ # sufficient. We test both energies and parameters in the slow test.
2908
+ # We ignore the charges for now as they are not included in the force field.
2909
+ # TODO: Reactivate the charge check when we'll be able to load charges from files.
2910
+ compare_amber_smirnoff(
2911
+ top_filepath,
2912
+ crd_filepath,
2913
+ alkethoh_forcefield,
2914
+ molecule,
2915
+ check_energies=False,
2916
+ ignore_charges=True,
2917
+ )
2918
+
2919
+ @requires_openeye_mol2
2920
+ def test_multi_alkethoh_parameters_assignment(self, alkethoh_forcefield):
2921
+ """Test that systems with multiple reference molecules are parametrized correctly.
2922
+
2923
+ The test relies on the fact that we have already verified we can
2924
+ parametrize correctly single AlkEthOH molecules in
2925
+ test_alkethoh_parameters_assignment(). We use ParmEd to merge
2926
+ the AMBER files to be used as reference parameters.
2927
+
2928
+ """
2929
+ import parmed
2930
+
2931
+ from openff.toolkit._tests.utils import (
2932
+ compare_system_energies,
2933
+ compare_system_parameters,
2934
+ get_alkethoh_file_path,
2935
+ )
2936
+
2937
+ # The AlkEthOH molecule ids to mix in the systems.
2938
+ alketoh_ids = ["r0", "c38", "c1161"]
2939
+
2940
+ # Load molecules and structures.
2941
+ molecules = []
2942
+ structures = []
2943
+ for alkethoh_id in alketoh_ids:
2944
+ mol2_filepath, top_filepath, crd_filepath = get_alkethoh_file_path(
2945
+ "AlkEthOH_" + alkethoh_id, get_amber=True
2946
+ )
2947
+ molecules.append(Molecule.from_file(mol2_filepath))
2948
+ amber_parm = parmed.load_file(top_filepath, crd_filepath)
2949
+ # Convert this into a real structure as mixing AmberParm objects is bugged (see ParmEd#1045).
2950
+ structures.append(amber_parm.copy(parmed.Structure))
2951
+
2952
+ # Merge the structures into a single system with two copies of the last molecule.
2953
+ structure_mixture = structures[0] + structures[1] + structures[2] + structures[-1]
2954
+ amber_system = structure_mixture.createSystem(nonbondedMethod=openmm.app.NoCutoff)
2955
+
2956
+ # Create the OpenFF System through ForceField.
2957
+ topology = Topology.from_openmm(structure_mixture.topology, unique_molecules=molecules)
2958
+ topology.box_vectors = None
2959
+ off_system = alkethoh_forcefield.create_openmm_system(topology)
2960
+
2961
+ # Translate the molecules a little to avoid overlapping atoms.
2962
+ positions = copy.deepcopy(structure_mixture.positions)
2963
+ translate_vectors = [
2964
+ np.array([1.0, 0.0, 0.0]) * openmm_unit.nanometer,
2965
+ np.array([0.0, 1.0, 0.0]) * openmm_unit.nanometer,
2966
+ np.array([0.0, 0.0, 1.0]) * openmm_unit.nanometer,
2967
+ # Leave the fourth molecule where it is.
2968
+ ]
2969
+ current_atom_idx = 0
2970
+ for translate_vector, mol in zip(translate_vectors, molecules):
2971
+ n_mol_atoms = len(mol.atoms)
2972
+ positions[current_atom_idx : current_atom_idx + n_mol_atoms] += translate_vector
2973
+ current_atom_idx += n_mol_atoms
2974
+
2975
+ # Compare parameters and systems.
2976
+ # TODO: Reactivate charges comparison when we'll be able to read them from the file.
2977
+ compare_system_parameters(
2978
+ amber_system,
2979
+ off_system,
2980
+ systems_labels=("AMBER", "SMIRNOFF"),
2981
+ ignore_charges=True,
2982
+ )
2983
+ compare_system_energies(amber_system, off_system, positions, ignore_charges=True)
2984
+
2985
+ @requires_openeye_mol2
2986
+ @pytest.mark.parametrize(
2987
+ ("freesolv_id", "forcefield_version", "allow_undefined_stereo"),
2988
+ generate_freesolv_parameters_assignment_cases(),
2989
+ )
2990
+ def test_freesolv_parameters_assignment(self, freesolv_id, forcefield_version, allow_undefined_stereo):
2991
+ """Regression test on parameters assignment based on the FreeSolv set used in the 0.1 paper.
2992
+
2993
+ This, contrarily to the similar AlkEthOH test, checks also constraints
2994
+ and improper torsions.
2995
+
2996
+ """
2997
+ from openff.toolkit._tests.utils import (
2998
+ compare_system_parameters,
2999
+ get_freesolv_file_path,
3000
+ )
3001
+
3002
+ mol2_file_path, xml_file_path = get_freesolv_file_path(freesolv_id, forcefield_version)
3003
+
3004
+ # Load molecules.
3005
+ molecule = Molecule.from_file(mol2_file_path, allow_undefined_stereo=allow_undefined_stereo)
3006
+
3007
+ # Create OpenFF System with the current toolkit.
3008
+ forcefield_file_path = get_data_file_path(
3009
+ "test_forcefields/old/test_ff_" + forcefield_version + "_spec_0_2.offxml"
3010
+ )
3011
+ ff = ForceField(
3012
+ forcefield_file_path,
3013
+ get_data_file_path("test_forcefields/old/hbonds.offxml"),
3014
+ )
3015
+ ff_system = ff.create_openmm_system(molecule.to_topology())
3016
+
3017
+ # Load OpenMM System created with the 0.1 version of the toolkit.
3018
+ with open(xml_file_path) as f:
3019
+ xml_system = openmm.XmlSerializer.deserialize(f.read())
3020
+
3021
+ # Compare parameters. We ignore the improper folds as in 0.0.3 we
3022
+ # used a six-fold implementation while we now use a three-fold way.
3023
+ # TODO: Reactivate charge comparison once we'll be able to read them from file.
3024
+ compare_system_parameters(
3025
+ ff_system,
3026
+ xml_system,
3027
+ systems_labels=("current OpenFF", "SMIRNOFF 0.0.4"),
3028
+ ignore_charges=True,
3029
+ ignore_improper_folds=True,
3030
+ )
3031
+
3032
+ @requires_openeye_mol2
3033
+ @pytest.mark.parametrize(("is_periodic"), (False, True))
3034
+ @pytest.mark.parametrize(("gbsa_model"), ["HCT", "OBC1", "OBC2"])
3035
+ @pytest.mark.parametrize(
3036
+ ("freesolv_id", "forcefield_version", "allow_undefined_stereo"),
3037
+ generate_freesolv_parameters_assignment_cases(),
3038
+ )
3039
+ def test_freesolv_gbsa_energies(
3040
+ self,
3041
+ gbsa_model,
3042
+ is_periodic,
3043
+ freesolv_id,
3044
+ forcefield_version,
3045
+ allow_undefined_stereo,
3046
+ ):
3047
+ """
3048
+ Regression test on HCT, OBC1, and OBC2 GBSA models. This test ensures that the
3049
+ SMIRNOFF-based GBSA models match the equivalent OpenMM implementations.
3050
+ """
3051
+ import parmed as pmd
3052
+
3053
+ from openff.toolkit._tests.utils import (
3054
+ compare_system_energies,
3055
+ create_system_from_amber,
3056
+ get_context_potential_energy,
3057
+ get_freesolv_file_path,
3058
+ )
3059
+
3060
+ mol2_file_path, _ = get_freesolv_file_path(freesolv_id, forcefield_version)
3061
+
3062
+ # Load molecules.
3063
+ molecule = Molecule.from_file(mol2_file_path, allow_undefined_stereo=allow_undefined_stereo)
3064
+
3065
+ # Give each atom a unique name, otherwise OpenMM will complain
3066
+ for idx, atom in enumerate(molecule.atoms):
3067
+ atom.name = f"{atom.symbol}{idx}"
3068
+ positions = to_openmm(molecule.conformers[0])
3069
+
3070
+ off_gbsas = {
3071
+ "HCT": "test_forcefields/GBSA_HCT-1.0.offxml",
3072
+ "OBC1": "test_forcefields/GBSA_OBC1-1.0.offxml",
3073
+ "OBC2": "test_forcefields/GBSA_OBC2-1.0.offxml",
3074
+ }
3075
+ # Create OpenFF System with the current toolkit.
3076
+ ff = ForceField(
3077
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
3078
+ get_data_file_path(off_gbsas[gbsa_model]),
3079
+ )
3080
+
3081
+ # OpenMM 7.7 and older don't properly handle parsing prmtop files with a GBSA model and
3082
+ # a switching function; this bug may be fixed but for testing purposes, simply turn off
3083
+ # the switching function
3084
+ ff["vdW"].switch_width = 0.0 * unit.angstrom
3085
+
3086
+ off_top = molecule.to_topology()
3087
+ if is_periodic:
3088
+ off_top.box_vectors = (
3089
+ (30.0, 0, 0),
3090
+ (0, 30.0, 0),
3091
+ (0, 0, 30.0),
3092
+ ) * unit.angstrom
3093
+
3094
+ else:
3095
+ off_top.box_vectors = None
3096
+
3097
+ off_omm_system = ff.create_openmm_system(off_top, charge_from_molecules=[molecule])
3098
+
3099
+ off_nonbonded_force = next(
3100
+ force for force in off_omm_system.getForces() if isinstance(force, openmm.NonbondedForce)
3101
+ )
3102
+
3103
+ omm_top = off_top.to_openmm()
3104
+ pmd_struct = pmd.openmm.load_topology(omm_top, off_omm_system, positions)
3105
+ prmtop_file = NamedTemporaryFile(suffix=".prmtop")
3106
+ inpcrd_file = NamedTemporaryFile(suffix=".inpcrd")
3107
+ pmd_struct.save(prmtop_file.name, overwrite=True)
3108
+ pmd_struct.save(inpcrd_file.name, overwrite=True)
3109
+
3110
+ openmm_gbsas = {
3111
+ "HCT": openmm.app.HCT,
3112
+ "OBC1": openmm.app.OBC1,
3113
+ "OBC2": openmm.app.OBC2,
3114
+ }
3115
+
3116
+ # The functional form of the nonbonded force will change depending on whether the cutoff
3117
+ # is None during initialization. Therefore, we need to figure that out here.
3118
+
3119
+ # WARNING: The NonbondedMethod enums at openmm.app.forcefield and openmm.CustomGBForce
3120
+ # aren't necessarily the same, and could be misinterpreted if the wrong one is used. For
3121
+ # create_system_from_amber, we must provide the app.forcefield version.
3122
+
3123
+ if is_periodic:
3124
+ amber_nb_method = openmm.app.forcefield.CutoffPeriodic
3125
+ amber_cutoff = off_nonbonded_force.getCutoffDistance()
3126
+ else:
3127
+ amber_nb_method = openmm.app.forcefield.NoCutoff
3128
+ amber_cutoff = None
3129
+
3130
+ # OpenMM will process False to mean "don't use one" and a quantity as "use with this distance"
3131
+ switching_distance = off_nonbonded_force.getUseSwitchingFunction()
3132
+ if switching_distance:
3133
+ switching_distance = off_nonbonded_force.getSwitchingDistance()
3134
+
3135
+ (
3136
+ amber_omm_system,
3137
+ _,
3138
+ _,
3139
+ ) = create_system_from_amber(
3140
+ prmtop_file.name,
3141
+ inpcrd_file.name,
3142
+ implicitSolvent=openmm_gbsas[gbsa_model],
3143
+ nonbondedMethod=amber_nb_method,
3144
+ nonbondedCutoff=amber_cutoff,
3145
+ gbsaModel="ACE",
3146
+ implicitSolventKappa=0.0,
3147
+ switchDistance=switching_distance,
3148
+ )
3149
+
3150
+ # Retrieve the GBSAForce from both the AMBER and OpenForceField systems
3151
+ off_gbsa_forces = list()
3152
+ for force in off_omm_system.getForces():
3153
+ if isinstance(force, openmm.GBSAOBCForce) or isinstance(force, openmm.openmm.CustomGBForce):
3154
+ off_gbsa_forces.append(force)
3155
+
3156
+ amber_gbsa_forces = list()
3157
+ for force in amber_omm_system.getForces():
3158
+ if isinstance(force, openmm.GBSAOBCForce) or isinstance(force, openmm.openmm.CustomGBForce):
3159
+ amber_gbsa_forces.append(force)
3160
+
3161
+ assert len(amber_gbsa_forces) == len(off_gbsa_forces) == 1
3162
+
3163
+ off_gbsa_force = off_gbsa_forces[0]
3164
+ amber_gbsa_force = amber_gbsa_forces[0]
3165
+
3166
+ # We get radius and screen values from each model's getStandardParameters method
3167
+ if gbsa_model == "HCT":
3168
+ gb_params = openmm.app.internal.customgbforces.GBSAHCTForce.getStandardParameters(omm_top)
3169
+ elif gbsa_model == "OBC1":
3170
+ gb_params = openmm.app.internal.customgbforces.GBSAOBC1Force.getStandardParameters(omm_top)
3171
+ elif gbsa_model == "OBC2":
3172
+ gb_params = openmm.app.internal.customgbforces.GBSAOBC2Force.getStandardParameters(omm_top)
3173
+
3174
+ # Use GB params from OpenMM GBSA classes to populate parameters
3175
+ for idx, (radius, screen) in enumerate(gb_params):
3176
+ # Keep the charge, but throw out the old radius and screen values
3177
+ q, _, _ = amber_gbsa_force.getParticleParameters(idx)
3178
+ if isinstance(amber_gbsa_force, openmm.GBSAOBCForce):
3179
+ # Note that in GBSAOBCForce, the per-particle parameters are separate
3180
+ # arguments, while in CustomGBForce they're a single iterable
3181
+ amber_gbsa_force.setParticleParameters(idx, q, radius, screen)
3182
+
3183
+ elif isinstance(amber_gbsa_force, openmm.CustomGBForce):
3184
+ # !!! WARNING: CustomAmberGBForceBase expects different per-particle parameters
3185
+ # depending on whether you use addParticle or setParticleParameters. In
3186
+ # setParticleParameters, we have to apply the offset and scale BEFORE setting
3187
+ # parameters, whereas in addParticle, it is applied afterwards, and the particle
3188
+ # parameters are not set until an auxillary finalize() method is called. !!!
3189
+ amber_gbsa_force.setParticleParameters(idx, (q, radius - 0.009, screen * (radius - 0.009)))
3190
+
3191
+ # Put the GBSA force into a separate group so we can specifically compare GBSA energies
3192
+ amber_gbsa_force.setForceGroup(1)
3193
+ off_gbsa_force.setForceGroup(1)
3194
+
3195
+ # Some manual overrides to get the OFF system's NonbondedForce matched up with the AMBER system
3196
+ if is_periodic:
3197
+ off_nonbonded_force.setNonbondedMethod(openmm.NonbondedForce.CutoffPeriodic)
3198
+ else:
3199
+ off_nonbonded_force.setNonbondedMethod(openmm.NonbondedForce.NoCutoff)
3200
+
3201
+ off_nonbonded_force.setReactionFieldDielectric(1.0)
3202
+
3203
+ # Create Contexts
3204
+ integrator = openmm.VerletIntegrator(1.0 * openmm_unit.femtoseconds)
3205
+ platform = Platform.getPlatformByName("Reference")
3206
+ amber_context = openmm.Context(amber_omm_system, integrator, platform)
3207
+ off_context = openmm.Context(off_omm_system, copy.deepcopy(integrator), platform)
3208
+
3209
+ # Get context energies
3210
+ amber_energy = get_context_potential_energy(amber_context, positions)
3211
+ off_energy = get_context_potential_energy(off_context, positions)
3212
+ # Very handy for debugging
3213
+ # print(openmm.XmlSerializer.serialize(off_gbsa_force))
3214
+ # print(openmm.XmlSerializer.serialize(amber_gbsa_force))
3215
+ # Ensure that the GBSA energies (which we put into ForceGroup 1) are identical
3216
+ # For Platform=OpenCL, we do get "=="-level identical numbers, but for "Reference", we don't.
3217
+ # assert amber_energy[1] == off_energy[1]
3218
+ assert abs(amber_energy[1] - off_energy[1]) < 1e-5 * openmm_unit.kilojoule_per_mole
3219
+
3220
+ # Ensure that all system energies are the same
3221
+ compare_system_energies(
3222
+ off_omm_system,
3223
+ amber_omm_system,
3224
+ positions,
3225
+ by_force_type=False,
3226
+ atol=1.0e-4,
3227
+ )
3228
+
3229
+ def test_tip5p_dimer_energy(self):
3230
+ pytest.skip("fails until migration to openff-interchange")
3231
+
3232
+ from openff.toolkit._tests.utils import evaluate_molecules_off
3233
+
3234
+ off_ff = ForceField("test_forcefields/test_forcefield.offxml", xml_tip5p)
3235
+
3236
+ molecule1 = create_water()
3237
+ molecule1.atoms[1].name = "O"
3238
+ molecule1.atoms[0].name = "H1"
3239
+ molecule1.atoms[2].name = "H2"
3240
+ molecule1.generate_conformers(n_conformers=1)
3241
+
3242
+ molecule1.conformers[0] = unit.Quantity(
3243
+ np.array(
3244
+ [
3245
+ [-0.78900161, -0.19816432, -0.0],
3246
+ [-0.00612716, 0.39173634, -0.0],
3247
+ [0.79512877, -0.19357202, 0.0],
3248
+ ]
3249
+ ),
3250
+ unit.angstrom,
3251
+ )
3252
+
3253
+ molecule2 = create_water()
3254
+ molecule2.atoms[1].name = "O"
3255
+ molecule2.atoms[0].name = "H1"
3256
+ molecule2.atoms[2].name = "H2"
3257
+ molecule2.generate_conformers(n_conformers=1)
3258
+
3259
+ # This is mol1 + 10 angstrom
3260
+ molecule2.conformers[0] = unit.Quantity(
3261
+ np.array(
3262
+ [
3263
+ [9.21099839, 9.80183568, 10.0],
3264
+ [9.99387284, 10.39173634, 10.0],
3265
+ [10.79512877, 9.80642798, 10.0],
3266
+ ]
3267
+ ),
3268
+ unit.angstrom,
3269
+ )
3270
+
3271
+ off_crds, off_ene = evaluate_molecules_off([molecule1, molecule2], off_ff, minimize=False)
3272
+
3273
+ ref_crds_with_vsite = unit.Quantity(
3274
+ np.array(
3275
+ [
3276
+ [-0.0789001605855, -0.0198164316973, -0.0],
3277
+ [-0.0006127160367, 0.0391736336129, -0.0],
3278
+ [0.0795128766222, -0.0193572019156, 0.0],
3279
+ [0.9210998394144, 0.9801835683026, 1.0],
3280
+ [0.9993872839632, 1.0391736336129, 1.0],
3281
+ [1.0795128766222, 0.9806427980843, 1.0],
3282
+ [-0.0012451030403, 0.0796049187395, -0.0571394020767],
3283
+ [-0.0012451030403, 0.0796049187395, 0.0571394020767],
3284
+ [0.9987548969596, 1.0796049187395, 0.9428605979232],
3285
+ [0.9987548969596, 1.0796049187395, 1.0571394020767],
3286
+ ]
3287
+ ),
3288
+ unit.nanometer,
3289
+ )
3290
+
3291
+ ref_ene = 0.0011797690240 * openmm_unit.kilojoule_per_mole
3292
+
3293
+ assert np.allclose(
3294
+ off_crds.m_as(unit.angstrom),
3295
+ ref_crds_with_vsite.m_as(unit.angstrom),
3296
+ )
3297
+ # allow 1% error in energy difference (default is .001%)
3298
+ assert np.allclose(
3299
+ off_ene.value_in_unit(openmm_unit.kilocalorie_per_mole),
3300
+ ref_ene.value_in_unit(openmm_unit.kilocalorie_per_mole),
3301
+ rtol=0.05,
3302
+ )
3303
+
3304
+ # skip direct comparison for now because of particle creation and atom
3305
+ # ordering complications
3306
+
3307
+ # # Create the oMM paramterized system
3308
+ # omm_ff = app.ForceField("tip5p.xml")
3309
+
3310
+ # omm_top = off_top.to_openmm()
3311
+ # omm_modeller = app.Modeller(omm_top, positions)
3312
+ # omm_modeller.addExtraParticles(omm_ff)
3313
+ # omm_top = omm_modeller.getTopology()
3314
+
3315
+ # omm_omm_system = omm_ff.createSystem(omm_top, nonbondedMethod=app.NoCutoff)
3316
+
3317
+ # compare_system_energies(
3318
+ # off_omm_system,
3319
+ # omm_omm_system,
3320
+ # positions,
3321
+ # by_force_type=False,
3322
+ # modify_system=False,
3323
+ # )
3324
+
3325
+ @pytest.mark.slow
3326
+ @requires_openeye_mol2
3327
+ @pytest.mark.parametrize("zero_charges", [True, False])
3328
+ @pytest.mark.parametrize(("gbsa_model"), ["HCT", "OBC1", "OBC2"])
3329
+ def test_molecule_energy_gb_no_sa(self, zero_charges, gbsa_model):
3330
+ """Test creating a GBSA system without a surface energy term, and validate its energy
3331
+ against the same system made using OpenMM's AMBER GBSA functionality"""
3332
+ import parmed as pmd
3333
+
3334
+ from openff.toolkit._tests.utils import (
3335
+ compare_system_energies,
3336
+ create_system_from_amber,
3337
+ get_context_potential_energy,
3338
+ )
3339
+
3340
+ # Load an arbitrary molecule from the freesolv set
3341
+ molecule = Molecule.from_file(get_data_file_path("molecules/FreeSolv/mol2files_sybyl/mobley_1036761.mol2"))
3342
+
3343
+ molecule.name = "mobley_1036761" # Name the molecule, otherwise OpenMM will complain
3344
+ if zero_charges:
3345
+ molecule.partial_charges = np.zeros(molecule.n_atoms) * unit.elementary_charge
3346
+
3347
+ # Give each atom a unique name, otherwise OpenMM will complain
3348
+ for idx, atom in enumerate(molecule.atoms):
3349
+ atom.name = f"{atom.symbol}{idx}"
3350
+
3351
+ positions = np.concatenate((molecule.conformers[0], molecule.conformers[0] + (10 * unit.angstrom)))
3352
+ # Create OpenFF System with the current toolkit.
3353
+
3354
+ off_gbsas = {
3355
+ "HCT": "test_forcefields/GBSA_HCT-1.0.offxml",
3356
+ "OBC1": "test_forcefields/GBSA_OBC1-1.0.offxml",
3357
+ "OBC2": "test_forcefields/GBSA_OBC2-1.0.offxml",
3358
+ }
3359
+
3360
+ ff = ForceField(
3361
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
3362
+ get_data_file_path(off_gbsas[gbsa_model]),
3363
+ )
3364
+ ff.get_parameter_handler("GBSA").sa_model = None
3365
+ off_top = Topology.from_molecules([molecule, molecule])
3366
+ off_omm_system = ff.create_openmm_system(off_top, charge_from_molecules=[molecule])
3367
+
3368
+ omm_top = off_top.to_openmm()
3369
+ pmd_struct = pmd.openmm.load_topology(omm_top, off_omm_system, positions)
3370
+ prmtop_file = NamedTemporaryFile(suffix=".prmtop")
3371
+ inpcrd_file = NamedTemporaryFile(suffix=".inpcrd")
3372
+ pmd_struct.save(prmtop_file.name, overwrite=True)
3373
+ pmd_struct.save(inpcrd_file.name, overwrite=True)
3374
+
3375
+ openmm_gbsas = {
3376
+ "HCT": openmm.app.HCT,
3377
+ "OBC1": openmm.app.OBC1,
3378
+ "OBC2": openmm.app.OBC2,
3379
+ }
3380
+
3381
+ (
3382
+ amber_omm_system,
3383
+ _,
3384
+ _,
3385
+ ) = create_system_from_amber(
3386
+ prmtop_file.name,
3387
+ inpcrd_file.name,
3388
+ implicitSolvent=openmm_gbsas[gbsa_model],
3389
+ nonbondedMethod=openmm.app.forcefield.NoCutoff,
3390
+ nonbondedCutoff=None,
3391
+ gbsaModel=None,
3392
+ implicitSolventKappa=0.0,
3393
+ )
3394
+
3395
+ # Retrieve the GBSAForce from both the AMBER and OpenForceField systems
3396
+ off_gbsa_forces = list()
3397
+ for force in off_omm_system.getForces():
3398
+ if isinstance(force, openmm.GBSAOBCForce) or isinstance(force, openmm.openmm.CustomGBForce):
3399
+ off_gbsa_forces.append(force)
3400
+
3401
+ amber_gbsa_forces = list()
3402
+ for force in amber_omm_system.getForces():
3403
+ if isinstance(force, openmm.GBSAOBCForce) or isinstance(force, openmm.openmm.CustomGBForce):
3404
+ amber_gbsa_forces.append(force)
3405
+
3406
+ assert len(amber_gbsa_forces) == len(off_gbsa_forces) == 1
3407
+
3408
+ off_gbsa_force = off_gbsa_forces[0]
3409
+ amber_gbsa_force = amber_gbsa_forces[0]
3410
+
3411
+ # We get radius and screen values from each model's getStandardParameters method
3412
+ if gbsa_model == "HCT":
3413
+ gb_params = openmm.app.internal.customgbforces.GBSAHCTForce.getStandardParameters(omm_top)
3414
+ elif gbsa_model == "OBC1":
3415
+ gb_params = openmm.app.internal.customgbforces.GBSAOBC1Force.getStandardParameters(omm_top)
3416
+ elif gbsa_model == "OBC2":
3417
+ gb_params = openmm.app.internal.customgbforces.GBSAOBC2Force.getStandardParameters(omm_top)
3418
+ # This is only necessary until https://github.com/openmm/openmm/pull/2362 is bundled into a conda release
3419
+ amber_gbsa_force.setSurfaceAreaEnergy(0)
3420
+
3421
+ # Use GB params from OpenMM GBSA classes to populate parameters
3422
+ for idx, (radius, screen) in enumerate(gb_params):
3423
+ # Keep the charge, but throw out the old radius and screen values
3424
+ q, _, _ = amber_gbsa_force.getParticleParameters(idx)
3425
+
3426
+ if isinstance(amber_gbsa_force, openmm.GBSAOBCForce):
3427
+ # Note that in GBSAOBCForce, the per-particle parameters are separate
3428
+ # arguments, while in CustomGBForce they're a single iterable
3429
+ amber_gbsa_force.setParticleParameters(idx, q, radius, screen)
3430
+
3431
+ elif isinstance(amber_gbsa_force, openmm.CustomGBForce):
3432
+ # !!! WARNING: CustomAmberGBForceBase expects different per-particle parameters
3433
+ # depending on whether you use addParticle or setParticleParameters. In
3434
+ # setParticleParameters, we have to apply the offset and scale BEFORE setting
3435
+ # parameters, whereas in addParticle, it is applied afterwards, and the particle
3436
+ # parameters are not set until an auxillary finalize() method is called. !!!
3437
+ amber_gbsa_force.setParticleParameters(idx, (q, radius - 0.009, screen * (radius - 0.009)))
3438
+
3439
+ # Put the GBSA force into a separate group so we can specifically compare GBSA energies
3440
+ amber_gbsa_force.setForceGroup(1)
3441
+ off_gbsa_force.setForceGroup(1)
3442
+
3443
+ # Create Contexts
3444
+ integrator = openmm.VerletIntegrator(1.0 * openmm_unit.femtoseconds)
3445
+ platform = Platform.getPlatformByName("Reference")
3446
+ amber_context = openmm.Context(amber_omm_system, integrator, platform)
3447
+ off_context = openmm.Context(off_omm_system, copy.deepcopy(integrator), platform)
3448
+
3449
+ # Get context energies
3450
+ amber_energy = get_context_potential_energy(amber_context, to_openmm(positions))
3451
+ off_energy = get_context_potential_energy(off_context, to_openmm(positions))
3452
+
3453
+ # Very handy for debugging
3454
+ # print(openmm.XmlSerializer.serialize(off_gbsa_force))
3455
+ # print(openmm.XmlSerializer.serialize(amber_gbsa_force))
3456
+
3457
+ # Ensure that the GBSA energies (which we put into ForceGroup 1) are identical
3458
+ # For Platform=OpenCL, we do get "=="-level identical numbers, but for "Reference", we don't.
3459
+ # assert amber_energy[1] == off_energy[1]
3460
+ assert abs(amber_energy[1] - off_energy[1]) < 1e-5 * openmm_unit.kilojoule_per_mole
3461
+
3462
+ # If charges are zero, the GB energy component should be 0, so the total GBSA energy should be 0
3463
+ if zero_charges:
3464
+ assert amber_energy[1]._value == 0.0
3465
+ else:
3466
+ assert amber_energy[1]._value != 0.0
3467
+
3468
+ # Ensure that all system energies are the same
3469
+ if zero_charges or gbsa_model in ["HCT", "OBC1"]:
3470
+ compare_system_energies(
3471
+ off_omm_system,
3472
+ amber_omm_system,
3473
+ to_openmm(positions),
3474
+ by_force_type=False,
3475
+ )
3476
+ else:
3477
+ compare_system_energies(
3478
+ off_omm_system,
3479
+ amber_omm_system,
3480
+ to_openmm(positions),
3481
+ by_force_type=False,
3482
+ atol=1e-4,
3483
+ )
3484
+
3485
+ @pytest.mark.slow
3486
+ @requires_openeye_mol2
3487
+ @pytest.mark.parametrize("toolkit_registry", toolkit_registries)
3488
+ def test_parameterize_protein(
3489
+ self,
3490
+ toolkit_registry,
3491
+ force_field,
3492
+ ):
3493
+ """Test that ForceField assigns parameters correctly for a protein"""
3494
+
3495
+ mol_path = get_data_file_path("proteins/T4-protein.mol2")
3496
+ molecule = Molecule.from_file(mol_path, allow_undefined_stereo=False)
3497
+ topology = Topology.from_molecules(molecule)
3498
+
3499
+ labels = force_field.label_molecules(topology)[0]
3500
+
3501
+ assert len(labels["Bonds"]) == 2654
3502
+ assert len(labels["Angles"]) == 4789
3503
+ assert len(labels["ProperTorsions"]) == 6973
3504
+ assert len(labels["ImproperTorsions"]) == 528
3505
+
3506
+ force_field.create_openmm_system(
3507
+ topology,
3508
+ charge_from_molecules=[molecule],
3509
+ toolkit_registry=toolkit_registry,
3510
+ )
3511
+
3512
+ def test_modified_14_factors(self, force_field):
3513
+ """Test that the 1-4 scaling factors for electrostatics and vdW handlers matche,
3514
+ to a tight precision, the values specified in the force field."""
3515
+ top = Molecule.from_smiles("CCCC").to_topology()
3516
+ default_14 = copy.deepcopy(force_field)
3517
+ e_mod_14 = copy.deepcopy(force_field)
3518
+ vdw_mod_14 = copy.deepcopy(force_field)
3519
+
3520
+ e_mod_14["Electrostatics"].scale14 = 0.66
3521
+ assert e_mod_14["Electrostatics"].scale14 == 0.66
3522
+
3523
+ vdw_mod_14["vdW"].scale14 = 0.777
3524
+ assert vdw_mod_14["vdW"].scale14 == 0.777
3525
+
3526
+ default_omm_sys = default_14.create_openmm_system(top)
3527
+ e_mod_omm_sys = e_mod_14.create_openmm_system(top)
3528
+ vdw_mod_omm_sys = vdw_mod_14.create_openmm_system(top)
3529
+
3530
+ for omm_sys, expected_vdw_14, expected_coul_14 in [
3531
+ [default_omm_sys, 0.5, 0.833333],
3532
+ [e_mod_omm_sys, 0.5, 0.66],
3533
+ [vdw_mod_omm_sys, 0.777, 0.833333],
3534
+ ]:
3535
+ found_coul_14, found_vdw_14 = get_14_scaling_factors(omm_sys)
3536
+
3537
+ np.testing.assert_almost_equal(
3538
+ actual=found_vdw_14,
3539
+ desired=expected_vdw_14,
3540
+ decimal=10,
3541
+ err_msg="vdW 1-4 scaling factors do not match",
3542
+ )
3543
+
3544
+ np.testing.assert_almost_equal(
3545
+ actual=found_coul_14,
3546
+ desired=expected_coul_14,
3547
+ decimal=10,
3548
+ err_msg="Electrostatics 1-4 scaling factors do not match",
3549
+ )
3550
+
3551
+ def test_14_missing_nonbonded_handler(self, force_field):
3552
+ """Test that something sane happens with 1-4 scaling factors if a
3553
+ ForceField is missing a vdWHandler and/or ElectrostaticsHandler"""
3554
+ top = Molecule.from_smiles("CCCC").to_topology()
3555
+
3556
+ ff_no_vdw = copy.deepcopy(force_field)
3557
+ ff_no_electrostatics = copy.deepcopy(force_field)
3558
+
3559
+ ff_no_vdw.deregister_parameter_handler("vdW")
3560
+
3561
+ ff_no_electrostatics.deregister_parameter_handler("Electrostatics")
3562
+ ff_no_electrostatics.deregister_parameter_handler("ToolkitAM1BCC")
3563
+
3564
+ sys_no_electrostatics = ff_no_electrostatics.create_openmm_system(top)
3565
+
3566
+ np.testing.assert_almost_equal(
3567
+ actual=get_14_scaling_factors(sys_no_electrostatics)[1],
3568
+ desired=ff_no_electrostatics["vdW"].scale14,
3569
+ decimal=8,
3570
+ )
3571
+
3572
+ sys_no_vdw = ff_no_vdw.create_openmm_system(top)
3573
+ np.testing.assert_almost_equal(
3574
+ actual=get_14_scaling_factors(sys_no_vdw)[0],
3575
+ desired=ff_no_vdw["Electrostatics"].scale14,
3576
+ decimal=8,
3577
+ )
3578
+
3579
+ @pytest.mark.parametrize(
3580
+ (
3581
+ "get_molecule",
3582
+ "k_torsion_interpolated",
3583
+ "k_bond_interpolated",
3584
+ "length_bond_interpolated",
3585
+ "central_atoms",
3586
+ ),
3587
+ [
3588
+ (create_ethanol, 4.953856, 44375.504, 0.13770, (1, 2)),
3589
+ (create_reversed_ethanol, 4.953856, 44375.504, 0.13770, (7, 6)),
3590
+ ],
3591
+ )
3592
+ def test_fractional_bondorder_from_molecule(
3593
+ self,
3594
+ get_molecule,
3595
+ k_torsion_interpolated,
3596
+ k_bond_interpolated,
3597
+ length_bond_interpolated,
3598
+ central_atoms,
3599
+ ):
3600
+ """Test the fractional bond orders are used to interpolate k and length values as we expect
3601
+
3602
+ Values for bond and torsion parameters are inferred from the bond order specified in the input molecule (1.23)
3603
+
3604
+ Parameter | SMIRNOFF unit | OpenMM unit | param values at bond orders 1, 2 | used bond order | value in OpenMM force
3605
+ bond k kcal/mol/A**2 kJ/mol/nm**2 101, 123 1.23 44375.504
3606
+ bond length A nm 1.4, 1.3 1.23 0.1377
3607
+ torsion k kcal kj 1, 1.8 1.23 4.953856
3608
+
3609
+ See test_fractional_bondorder_calculated_openeye test_fractional_bondorder_calculated_rdkit for
3610
+ how the bond orders are obtained.
3611
+ """
3612
+ mol = get_molecule()
3613
+ forcefield = ForceField(get_data_file_path("test_forcefields/test_forcefield.offxml"), xml_ff_bo)
3614
+ topology = Topology.from_molecules(mol)
3615
+
3616
+ omm_system = forcefield.create_openmm_system(
3617
+ topology,
3618
+ charge_from_molecules=[mol],
3619
+ partial_bond_orders_from_molecules=[mol],
3620
+ )
3621
+
3622
+ # Verify that the assigned bond parameters were correctly interpolated
3623
+ off_bond_force = next(force for force in omm_system.getForces() if isinstance(force, openmm.HarmonicBondForce))
3624
+
3625
+ for idx in range(off_bond_force.getNumBonds()):
3626
+ params = off_bond_force.getBondParameters(idx)
3627
+
3628
+ atom1, atom2 = params[0], params[1]
3629
+ atom1_mol, atom2_mol = central_atoms
3630
+
3631
+ if ((atom1 == atom1_mol) and (atom2 == atom2_mol)) or ((atom1 == atom2_mol) and (atom2 == atom1_mol)):
3632
+ k = params[-1]
3633
+ length = params[-2]
3634
+ assert_almost_equal(k / k.unit, k_bond_interpolated)
3635
+ assert_almost_equal(length / length.unit, length_bond_interpolated)
3636
+
3637
+ # Verify that the assigned torsion parameters were correctly interpolated
3638
+ off_torsion_force = next(
3639
+ force for force in omm_system.getForces() if isinstance(force, openmm.PeriodicTorsionForce)
3640
+ )
3641
+
3642
+ for idx in range(off_torsion_force.getNumTorsions()):
3643
+ params = off_torsion_force.getTorsionParameters(idx)
3644
+
3645
+ atom2, atom3 = params[1], params[2]
3646
+ atom2_mol, atom3_mol = central_atoms
3647
+
3648
+ if ((atom2 == atom2_mol) and (atom3 == atom3_mol)) or ((atom2 == atom3_mol) and (atom3 == atom2_mol)):
3649
+ k = params[-1]
3650
+ assert_almost_equal(k / k.unit, k_torsion_interpolated)
3651
+
3652
+ def test_fractional_bondorder_multiple_same_mol(self):
3653
+ """Check that an error is thrown when essentially the same molecule is entered more than once
3654
+ for partial_bond_orders_from_molecules"""
3655
+
3656
+ mol = create_ethanol()
3657
+ mol2 = create_reversed_ethanol()
3658
+
3659
+ forcefield = ForceField(
3660
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
3661
+ xml_ff_bo,
3662
+ )
3663
+ topology = Topology.from_molecules([mol, mol2])
3664
+
3665
+ with pytest.raises(ValueError):
3666
+ forcefield.create_openmm_system(
3667
+ topology,
3668
+ charge_from_molecules=[mol],
3669
+ partial_bond_orders_from_molecules=[mol, mol2],
3670
+ )
3671
+
3672
+ @pytest.mark.parametrize(
3673
+ ("get_molecule", "central_atoms"),
3674
+ [(create_ethanol, (1, 2)), (create_reversed_ethanol, (7, 6))],
3675
+ )
3676
+ def test_fractional_bondorder_superseded_by_standard_torsion(self, get_molecule, central_atoms):
3677
+ """Test that matching rules are still respected with fractional bondorder parameters.
3678
+
3679
+ We check here that a standard torsion parameter can still get priority on a match
3680
+ if it is further down the list.
3681
+ """
3682
+
3683
+ mol = get_molecule()
3684
+
3685
+ forcefield = ForceField(
3686
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
3687
+ xml_ff_torsion_bo_standard_supersede,
3688
+ )
3689
+ topology = Topology.from_molecules([mol])
3690
+
3691
+ omm_system = forcefield.create_openmm_system(
3692
+ topology,
3693
+ charge_from_molecules=[mol],
3694
+ partial_bond_orders_from_molecules=[mol],
3695
+ )
3696
+
3697
+ off_torsion_force = next(
3698
+ force for force in omm_system.getForces() if isinstance(force, openmm.PeriodicTorsionForce)
3699
+ )
3700
+
3701
+ for idx in range(off_torsion_force.getNumTorsions()):
3702
+ params = off_torsion_force.getTorsionParameters(idx)
3703
+
3704
+ atom2, atom3 = params[1], params[2]
3705
+ atom2_mol, atom3_mol = central_atoms
3706
+
3707
+ if ((atom2 == atom2_mol) and (atom3 == atom3_mol)) or ((atom2 == atom3_mol) and (atom3 == atom2_mol)):
3708
+ k = params[-1]
3709
+ assert_almost_equal(k / k.unit, 5.0208)
3710
+
3711
+ def test_fractional_bondorder_invalid_interpolation_method(self):
3712
+ """
3713
+ Ensure that requesting an invalid interpolation method leads to a
3714
+ FractionalBondOrderInterpolationMethodUnsupportedError
3715
+ """
3716
+
3717
+ mol = create_ethanol()
3718
+
3719
+ forcefield = ForceField(get_data_file_path("test_forcefields/test_forcefield.offxml"), xml_ff_bo)
3720
+ forcefield.get_parameter_handler("ProperTorsions")._fractional_bondorder_interpolation = "invalid method name"
3721
+ topology = Topology.from_molecules([mol])
3722
+
3723
+ # If important, this can be a custom exception instead of a verbose ValidationError
3724
+ with pytest.raises(
3725
+ ValidationError,
3726
+ match=r"Input should be 'linear'.*input_value='invalid method name'",
3727
+ ):
3728
+ forcefield.create_openmm_system(
3729
+ topology,
3730
+ charge_from_molecules=[mol],
3731
+ )
3732
+
3733
+
3734
+ class TestForceFieldWithToolkits(_ForceFieldFixtures):
3735
+ """Test interactions between ``ForceField`` methods and wrapped toolkits."""
3736
+
3737
+ # TODO: Many of these tests could leverage toolkit_registry_manager
3738
+
3739
+ def test_toolkit_registry_bogus_argument(self, force_field):
3740
+ topology = create_ethanol().to_topology()
3741
+ with pytest.raises(
3742
+ NotImplementedError,
3743
+ match=r"Only .*ToolkitRegistry.*ToolkitWrapper.* are supported",
3744
+ ):
3745
+ force_field.create_openmm_system(
3746
+ topology,
3747
+ toolkit_registry="rdkit",
3748
+ )
3749
+
3750
+ def test_toolkit_registry_no_charge_methods(self, force_field):
3751
+ topology = create_ethanol().to_topology()
3752
+ with pytest.raises(ValueError, match=r"No registered toolkits can provide .*find_smarts_matches"):
3753
+ force_field.create_openmm_system(topology, toolkit_registry=BuiltInToolkitWrapper())
3754
+
3755
+ @pytest.mark.skip(reason="Broken until Interchange supports Electrostatics 0.4")
3756
+ @requires_rdkit
3757
+ def test_toolkit_registry_bad_charge_method(self):
3758
+ topology = create_ethanol().to_topology()
3759
+ force_field = ForceField(
3760
+ get_data_file_path("test_forcefields/test_forcefield.offxml"),
3761
+ xml_charge_increment_model_ff_ethanol,
3762
+ )
3763
+ force_field.deregister_parameter_handler("ToolkitAM1BCC")
3764
+ force_field["ChargeIncrementModel"].partial_charge_method = "am1bccelf10"
3765
+
3766
+ with pytest.raises(ValueError, match=r"No registered toolkits can provide .*elf10"):
3767
+ force_field.create_openmm_system(
3768
+ topology,
3769
+ toolkit_registry=ToolkitRegistry([RDKitToolkitWrapper(), AmberToolsToolkitWrapper()]),
3770
+ )
3771
+
3772
+
3773
+ class TestSmirnoffVersionConverter:
3774
+ @requires_openeye_mol2
3775
+ @pytest.mark.slow
3776
+ @pytest.mark.parametrize(
3777
+ ("freesolv_id", "forcefield_version", "allow_undefined_stereo"),
3778
+ generate_freesolv_parameters_assignment_cases(),
3779
+ )
3780
+ @pytest.mark.parametrize(("spec"), ["0_1", "0_2", "0_3"])
3781
+ def test_read_smirnoff_spec_freesolv(self, freesolv_id, forcefield_version, allow_undefined_stereo, spec):
3782
+ """
3783
+ Test reading an 0.2 smirnoff spec file, by reading an 0.1 spec representation of a set of parameters,
3784
+ and ensuring that it parameterizes molecules identically to the same FF in the most recent spec
3785
+
3786
+ Regression test on parameters assignment based on the FreeSolv set used in the 0.1 paper.
3787
+
3788
+ This, contrarily to the similar AlkEthOH test, checks also constraints
3789
+ and improper torsions.
3790
+
3791
+ The AlkEthOH set, however, does not have impropers, which should be
3792
+ tested separately. Currently, test_freesolv_parameters_assignment
3793
+ does the job.
3794
+ """
3795
+ from openff.toolkit._tests.utils import (
3796
+ compare_system_parameters,
3797
+ get_freesolv_file_path,
3798
+ )
3799
+
3800
+ mol2_file_path, xml_file_path = get_freesolv_file_path(freesolv_id, forcefield_version)
3801
+
3802
+ # Load molecules.
3803
+ molecule = Molecule.from_file(mol2_file_path, allow_undefined_stereo=allow_undefined_stereo)
3804
+
3805
+ # Create OpenFF System with the current toolkit.
3806
+ # forcefield_file_path = 'test_forcefields/old/smirnoff99Frosst_1_0_8_spec_0_2.offxml'
3807
+ forcefield_file_path = get_data_file_path(
3808
+ f"test_forcefields/old/test_ff_{forcefield_version}_spec_{spec}.offxml"
3809
+ )
3810
+ ff = ForceField(
3811
+ forcefield_file_path,
3812
+ get_data_file_path("test_forcefields/old/hbonds.offxml"),
3813
+ )
3814
+ ff_system = ff.create_openmm_system(molecule.to_topology())
3815
+
3816
+ # Load OpenMM System created with the 0.1 version of the toolkit.
3817
+ with open(xml_file_path) as f:
3818
+ xml_system = openmm.XmlSerializer.deserialize(f.read())
3819
+
3820
+ # Compare parameters. We ignore the improper folds as in 0.0.3 we
3821
+ # used a six-fold implementation while we now use a three-fold way.
3822
+ # TODO: Reactivate charge comparison once we'll be able to read them from file.
3823
+ compare_system_parameters(
3824
+ ff_system,
3825
+ xml_system,
3826
+ systems_labels=("current OpenFF", "SMIRNOFF 0.0.4"),
3827
+ ignore_charges=True,
3828
+ ignore_improper_folds=True,
3829
+ )
3830
+
3831
+
3832
+ class TestForceFieldGetPartialCharges(_ForceFieldFixtures):
3833
+ """Tests for the ForceField.get_partial_charges method."""
3834
+
3835
+ @staticmethod
3836
+ def get_partial_charges_from_create_openmm_system(mol, force_field):
3837
+ """Helper method to compute partial charges from a generated openmm System."""
3838
+ system = force_field.create_openmm_system(mol.to_topology())
3839
+ nbforce = next(f for f in system.getForces() if isinstance(f, openmm.openmm.NonbondedForce))
3840
+
3841
+ n_particles = nbforce.getNumParticles()
3842
+ charges = [nbforce.getParticleParameters(i)[0] for i in range(n_particles)]
3843
+
3844
+ return openmm_unit.Quantity(charges)
3845
+
3846
+ def test_get_partial_charges(self, force_field):
3847
+ """Test that ethanol charges are computed correctly."""
3848
+ ethanol: Molecule = create_ethanol()
3849
+
3850
+ ethanol_partial_charges = from_openmm(self.get_partial_charges_from_create_openmm_system(ethanol, force_field))
3851
+
3852
+ partial_charges = force_field.get_partial_charges(ethanol)
3853
+
3854
+ assert (ethanol_partial_charges - partial_charges < 1.0e-6 * unit.elementary_charge).all()
3855
+ assert partial_charges.shape == (ethanol.n_atoms,)
3856
+
3857
+
3858
+ # TODO: test_store_cosmetic_attribs
3859
+ # TODO: test_write_cosmetic_attribs
3860
+ # TODO: test_store_cosmetic_elements (eg. Author)
3861
+ # TODO: test_write_cosmetic_elements (eg. Author)
3862
+ # TODO: add_handler_with_incompatible_kwargs (for example different scale14 vals)
3863
+ # TODO: test_invalid_file_version
3864
+ # TODO: test_create_gbsa