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,2898 @@
1
+ """
2
+ Test classes and function in module openff.toolkit.typing.engines.smirnoff.parameters.
3
+
4
+ """
5
+
6
+ from collections import defaultdict
7
+ from inspect import isabstract, isclass
8
+
9
+ import numpy
10
+ import pytest
11
+ from numpy.testing import assert_almost_equal
12
+ from packaging.version import Version
13
+
14
+ from openff.toolkit import ForceField, Molecule, Quantity, Topology, unit
15
+ from openff.toolkit._tests.mocking import VirtualSiteMocking
16
+ from openff.toolkit._tests.utils import does_not_raise
17
+ from openff.toolkit.typing.engines.smirnoff import NAGLChargesHandler
18
+ from openff.toolkit.typing.engines.smirnoff.parameters import (
19
+ AngleHandler,
20
+ BondHandler,
21
+ ChargeIncrementModelHandler,
22
+ ConstraintHandler,
23
+ ElectrostaticsHandler,
24
+ GBSAHandler,
25
+ ImproperTorsionHandler,
26
+ IndexedParameterAttribute,
27
+ LibraryChargeHandler,
28
+ ParameterAttribute,
29
+ ParameterHandler,
30
+ ParameterList,
31
+ ParameterType,
32
+ ProperTorsionHandler,
33
+ VirtualSiteHandler,
34
+ _cal_mol_a2,
35
+ _linear_inter_or_extrapolate,
36
+ _ParameterAttributeHandler,
37
+ vdWHandler,
38
+ )
39
+ from openff.toolkit.utils.collections import ValidatedList
40
+ from openff.toolkit.utils.exceptions import (
41
+ DuplicateParameterError,
42
+ IncompatibleParameterError,
43
+ IncompatibleUnitError,
44
+ MissingIndexedAttributeError,
45
+ NotEnoughPointsForInterpolationError,
46
+ ParameterLookupError,
47
+ SMIRNOFFSpecError,
48
+ SMIRNOFFSpecUnimplementedError,
49
+ SMIRNOFFVersionError,
50
+ )
51
+
52
+
53
+ class TestParameterAttribute:
54
+ """Test cases for the descriptor ParameterAttribute."""
55
+
56
+ def test_default_value(self):
57
+ """Default values are assigned correctly on initialization."""
58
+
59
+ class MyParameter:
60
+ attr_optional = ParameterAttribute(default=2)
61
+
62
+ my_par = MyParameter()
63
+ assert my_par.attr_optional == 2
64
+
65
+ def test_none_default_value(self):
66
+ """None is a valid default value for ParameterAttribute."""
67
+
68
+ class MyParameter:
69
+ attr_optional = ParameterAttribute(default=None)
70
+
71
+ my_par = MyParameter()
72
+ assert my_par.attr_optional is None
73
+
74
+ def test_required_value(self):
75
+ """AttributeError is raised if a required attribute is accessed before being initialized."""
76
+
77
+ class MyParameter:
78
+ attr_required = ParameterAttribute()
79
+
80
+ my_par = MyParameter()
81
+ with pytest.raises(AttributeError):
82
+ my_par.attr_required
83
+
84
+ def test_unit_validation(self):
85
+ """ParameterAttributes attached to a unit are validated correctly."""
86
+
87
+ class MyParameter:
88
+ attr_unit = ParameterAttribute(unit=unit.kilocalorie / unit.mole / unit.angstrom**2)
89
+
90
+ my_par = MyParameter()
91
+
92
+ # TypeError is raised when setting a unit-less value.
93
+ with pytest.raises(IncompatibleUnitError, match="should have units of"):
94
+ my_par.attr_unit = 3.0
95
+ # TypeError is raised when setting a value with incorrect units.
96
+ with pytest.raises(IncompatibleUnitError, match="should have units of"):
97
+ my_par.attr_unit = 3.0 * unit.kilocalorie / unit.mole
98
+ # Otherwise the attribute is assigned correctly.
99
+ value = 3.0 * unit.kilocalorie / unit.mole / unit.angstrom**2
100
+ my_par.attr_unit = value
101
+ assert my_par.attr_unit == value
102
+ assert my_par.attr_unit.units == value.units
103
+
104
+ def test_quantity_string_parsing(self):
105
+ """ParameterAttributes attached to units convert strings into Quantity objects."""
106
+
107
+ class MyParameter:
108
+ attr_unit = ParameterAttribute(unit=unit.meter / unit.second**2)
109
+
110
+ my_par = MyParameter()
111
+
112
+ my_par.attr_unit = "3.0*meter/second**2"
113
+ assert my_par.attr_unit == 3.0 * unit.meter / unit.second**2
114
+ assert my_par.attr_unit.units == unit.meter / unit.second**2
115
+
116
+ # Assigning incorrect units still raises an error.
117
+ with pytest.raises(IncompatibleUnitError, match="should have units of"):
118
+ my_par.attr_unit = "3.0"
119
+ with pytest.raises(IncompatibleUnitError, match="should have units of"):
120
+ my_par.attr_unit = "3.0*meter/second"
121
+
122
+ def test_custom_converter(self):
123
+ """Custom converters of ParameterAttributes are executed correctly."""
124
+
125
+ class MyParameter:
126
+ attr_all_to_float = ParameterAttribute(converter=float)
127
+ attr_int_to_float = ParameterAttribute()
128
+
129
+ @attr_int_to_float.converter
130
+ def attr_int_to_float(self, attr, value):
131
+ """Convert only integers to float"""
132
+ if isinstance(value, int):
133
+ return float(value)
134
+ elif not isinstance(value, float):
135
+ raise TypeError()
136
+ return value
137
+
138
+ my_par = MyParameter()
139
+
140
+ # Both strings and integers are converted to floats when casted with float().
141
+ my_par.attr_all_to_float = "1.0"
142
+ assert isinstance(my_par.attr_all_to_float, float) and my_par.attr_all_to_float == 1.0
143
+ my_par.attr_all_to_float = 2
144
+ assert isinstance(my_par.attr_all_to_float, float) and my_par.attr_all_to_float == 2.0
145
+
146
+ # Only integers are converted with the custom converter function.
147
+ with pytest.raises(TypeError):
148
+ my_par.attr_int_to_float = "1.0"
149
+ my_par.attr_int_to_float = 2
150
+ assert isinstance(my_par.attr_int_to_float, float) and my_par.attr_int_to_float == 2.0
151
+
152
+ def test_default_pass_validation(self):
153
+ """The default value of ParameterAttribute is always allowed regardless of the validator/converter."""
154
+
155
+ class MyParameter:
156
+ attr = ParameterAttribute(default=None, unit=unit.angstrom, converter=unit.Quantity)
157
+
158
+ my_par = MyParameter()
159
+ my_par.attr = 3.0 * unit.nanometer
160
+ my_par.attr = None
161
+ assert my_par.attr is None
162
+
163
+ def test_get_descriptor_object(self):
164
+ """When the descriptor is called from the class, the ParameterAttribute descriptor is returned."""
165
+
166
+ class MyParameter:
167
+ attr = ParameterAttribute()
168
+
169
+ assert isinstance(MyParameter.attr, ParameterAttribute)
170
+
171
+
172
+ class TestIndexedParameterAttribute:
173
+ """Tests for the IndexedParameterAttribute descriptor."""
174
+
175
+ def test_tuple_conversion(self):
176
+ """IndexedParameterAttribute converts internally sequences to ValidatedList."""
177
+
178
+ class MyParameter:
179
+ attr_indexed = IndexedParameterAttribute()
180
+
181
+ my_par = MyParameter()
182
+ my_par.attr_indexed = [1, 2, 3]
183
+ assert isinstance(my_par.attr_indexed, ValidatedList)
184
+
185
+ def test_indexed_default(self):
186
+ """IndexedParameterAttribute handles default values correctly."""
187
+
188
+ class MyParameter:
189
+ attr_indexed_optional = IndexedParameterAttribute(default=None)
190
+
191
+ my_par = MyParameter()
192
+ assert my_par.attr_indexed_optional is None
193
+
194
+ # Assigning the default is allowed.
195
+ my_par.attr_indexed_optional = None
196
+ assert my_par.attr_indexed_optional is None
197
+
198
+ def test_units_on_all_elements(self):
199
+ """IndexedParameterAttribute validates every single element of the sequence."""
200
+
201
+ class MyParameter:
202
+ attr_indexed_unit = IndexedParameterAttribute(unit=unit.gram)
203
+
204
+ my_par = MyParameter()
205
+
206
+ # Strings are correctly converted.
207
+ my_par.attr_indexed_unit = ["1.0*gram", 2 * unit.gram]
208
+ assert my_par.attr_indexed_unit == [1.0 * unit.gram, 2 * unit.gram]
209
+
210
+ # Incompatible units on a single elements are correctly caught.
211
+ with pytest.raises(IncompatibleUnitError, match="should have units of"):
212
+ my_par.attr_indexed_unit = [3.0, 2 * unit.gram]
213
+ with pytest.raises(IncompatibleUnitError, match="should have units of"):
214
+ my_par.attr_indexed_unit = [2 * unit.gram, 4.0 * unit.meter]
215
+
216
+ def test_converter_on_all_elements(self):
217
+ """IndexedParameterAttribute calls custom converters on every single element of the sequence."""
218
+
219
+ class MyParameter:
220
+ attr_indexed_converter = IndexedParameterAttribute(converter=float)
221
+
222
+ my_par = MyParameter()
223
+
224
+ my_par.attr_indexed_converter = [1, "2.0", "1e-3", 4.0]
225
+ assert my_par.attr_indexed_converter == [1.0, 2.0, 1e-3, 4.0]
226
+
227
+ def test_validate_new_elements(self):
228
+ """New elements set in the list are correctly validated."""
229
+
230
+ class MyParameter:
231
+ attr_indexed = IndexedParameterAttribute(converter=int)
232
+
233
+ my_par = MyParameter()
234
+ my_par.attr_indexed = (1, 2, 3)
235
+
236
+ # Modifying one or more elements of the list should validate them.
237
+ my_par.attr_indexed[2] = "4"
238
+ assert my_par.attr_indexed[2] == 4
239
+ my_par.attr_indexed[0:3] = ["2", "3", 4]
240
+ assert my_par.attr_indexed == [2, 3, 4]
241
+
242
+ # Same for append().
243
+ my_par.attr_indexed.append("5")
244
+ assert my_par.attr_indexed[3] == 5
245
+
246
+ # And extend.
247
+ my_par.attr_indexed.extend([6, "7"])
248
+ assert my_par.attr_indexed[5] == 7
249
+ my_par.attr_indexed += ["8", 9]
250
+ assert my_par.attr_indexed[6] == 8
251
+
252
+ # And insert.
253
+ my_par.attr_indexed.insert(5, "10")
254
+ assert my_par.attr_indexed[5] == 10
255
+
256
+
257
+ class TestInterpolation:
258
+ """Test method(s) that are used for functionality like fractional bond order-dependent parameter interpolation"""
259
+
260
+ @pytest.mark.parametrize(
261
+ ("fractional_bond_order", "k_interpolated"),
262
+ [(1.6, 1.48), (0.7, 0.76), (2.3, 2.04)],
263
+ )
264
+ def test_linear_inter_or_extrapolate(self, fractional_bond_order, k_interpolated):
265
+ """Test that linear interpolation works as expected"""
266
+ k_bondorder = {
267
+ 1: 1 * unit.kilocalorie / unit.mole,
268
+ 2: 1.8 * unit.kilocalorie / unit.mole,
269
+ }
270
+
271
+ k = _linear_inter_or_extrapolate(k_bondorder, fractional_bond_order)
272
+ assert_almost_equal(k.m, k_interpolated)
273
+
274
+ def test_linear_inter_or_extrapolate_one_point(self):
275
+ """Test that linear interpolation raises an error if attempted with just one point"""
276
+ k_bondorder = {
277
+ 2: 1.8 * unit.kilocalorie / unit.mole,
278
+ }
279
+ with pytest.raises(NotEnoughPointsForInterpolationError):
280
+ _linear_inter_or_extrapolate(k_bondorder, 1)
281
+
282
+ @pytest.mark.parametrize(
283
+ ("fractional_bond_order", "k_interpolated"),
284
+ [(1.6, 1.48), (0.7, 0.76), (2.3, 2.01), (3.1, 2.57)],
285
+ )
286
+ def test_linear_inter_or_extrapolate_3_terms(self, fractional_bond_order, k_interpolated):
287
+ """Test that linear interpolation works as expected for three terms"""
288
+ k_bondorder = {
289
+ 1: 1 * unit.kilocalorie / unit.mole,
290
+ 2: 1.8 * unit.kilocalorie / unit.mole,
291
+ 3: 2.5 * unit.kilocalorie / unit.mole,
292
+ }
293
+
294
+ k = _linear_inter_or_extrapolate(k_bondorder, fractional_bond_order)
295
+ assert_almost_equal(k.m, k_interpolated)
296
+
297
+ def test_linear_inter_or_extrapolate_below_zero(self):
298
+ """Test that linear interpolation does not error if resulting k less than 0"""
299
+ k_bondorder = {
300
+ 1: 1 * unit.kilocalorie / unit.mole,
301
+ 2: 2.3 * unit.kilocalorie / unit.mole,
302
+ }
303
+
304
+ fractional_bond_order = 0.2
305
+ k = _linear_inter_or_extrapolate(k_bondorder, fractional_bond_order)
306
+
307
+ assert k.m < 0
308
+
309
+
310
+ class TestParameterAttributeHandler:
311
+ """Test suite for the base class _ParameterAttributeHandler."""
312
+
313
+ def test_access_get_set_single_indexed_attribute_legacy(self):
314
+ """Single indexed attributes such as k1 can be accessed through normal attribute syntax."""
315
+
316
+ class MyParameterType(_ParameterAttributeHandler):
317
+ k = IndexedParameterAttribute()
318
+
319
+ my_parameter = MyParameterType(k=[1, 2, 3])
320
+
321
+ # Getting the attribute works.
322
+ assert my_parameter.k1 == 1
323
+ assert my_parameter.k2 == 2
324
+ assert my_parameter.k3 == 3
325
+
326
+ # So does setting it.
327
+ my_parameter.k2 = 5
328
+ assert my_parameter.k2 == 5
329
+ assert my_parameter.k == [1, 5, 3]
330
+
331
+ # Accessing k4 raises an index error.
332
+ with pytest.raises(IndexError, match="'k4' is out of bounds for indexed attribute 'k'"):
333
+ my_parameter.k4
334
+ with pytest.raises(IndexError, match="'k4' is out of bounds for indexed attribute 'k'"):
335
+ my_parameter.k4 = 2
336
+
337
+ # For other attributes, the behavior is normal.
338
+ with pytest.raises(AttributeError, match="has no attribute 'x'"):
339
+ my_parameter.x
340
+ # Monkey-patching.
341
+ my_parameter.x = 3
342
+
343
+ def test_access_get_set_single_indexed_attribute(self):
344
+ """Single indexed attributes such as k1 can be accessed through normal attribute syntax."""
345
+
346
+ class MyParameterType(_ParameterAttributeHandler):
347
+ k = IndexedParameterAttribute()
348
+
349
+ my_parameter = MyParameterType(k=[1, 2, 3])
350
+
351
+ # Getting the attribute works.
352
+ assert my_parameter.k1 == 1
353
+ assert my_parameter.k2 == 2
354
+ assert my_parameter.k3 == 3
355
+
356
+ # So does setting it.
357
+ my_parameter.k2 = 5
358
+ assert my_parameter.k2 == 5
359
+ assert my_parameter.k == [1, 5, 3]
360
+
361
+ # Accessing k4 raises an index error.
362
+ with pytest.raises(
363
+ MissingIndexedAttributeError,
364
+ match="'k4' is out of bounds for indexed attribute 'k'",
365
+ ):
366
+ my_parameter.k4
367
+ with pytest.raises(
368
+ MissingIndexedAttributeError,
369
+ match="'k4' is out of bounds for indexed attribute 'k'",
370
+ ):
371
+ my_parameter.k4 = 2
372
+
373
+ # For other attributes, the behavior is normal.
374
+ with pytest.raises(AttributeError, match="has no attribute 'x'"):
375
+ my_parameter.x
376
+ # Monkey-patching.
377
+ my_parameter.x = 3
378
+
379
+ def test_hasattr(self):
380
+ """Single indexed attributes such as k1 can be accessed through normal attribute syntax."""
381
+
382
+ class MyParameterType(_ParameterAttributeHandler):
383
+ k = IndexedParameterAttribute()
384
+
385
+ my_parameter = MyParameterType(k=[1, 2, 3])
386
+ assert hasattr(my_parameter, "k3")
387
+ assert not hasattr(my_parameter, "k4")
388
+
389
+ def test_mro_access_get_set_single_indexed_attribute(self):
390
+ """Attribute access is forwarded correctly to the next MRO classes."""
391
+
392
+ class MixIn:
393
+ """Utility class to keep track of whether __get/setattr__ are called."""
394
+
395
+ data = {}
396
+
397
+ def __getattr__(self, item):
398
+ self.getattr_flag = True
399
+ try:
400
+ return self.data[item]
401
+ except KeyError:
402
+ raise AttributeError()
403
+
404
+ def __setattr__(self, key, value):
405
+ self.data[key] = value
406
+ super().__setattr__("setattr_flag", True)
407
+
408
+ def assert_getattr(self):
409
+ assert self.getattr_flag is True
410
+ self.getattr_flag = False
411
+
412
+ def assert_setattr(self):
413
+ assert self.setattr_flag is True
414
+ super().__setattr__("setattr_flag", False)
415
+
416
+ class MyParameterType(_ParameterAttributeHandler, MixIn):
417
+ k = IndexedParameterAttribute()
418
+
419
+ my_parameter = MyParameterType(k=[1, 2, 3])
420
+
421
+ # Non-existing parameters.
422
+ my_parameter.a = 2
423
+ my_parameter.assert_setattr()
424
+ my_parameter.a1 = 4
425
+ my_parameter.assert_setattr()
426
+
427
+ my_parameter.a
428
+ my_parameter.assert_getattr()
429
+ my_parameter.a1
430
+ my_parameter.assert_getattr()
431
+
432
+
433
+ class TestParameterHandler:
434
+ length = 1 * unit.angstrom
435
+ k = 10 * unit.kilocalorie / unit.mole / unit.angstrom**2
436
+
437
+ def test_tagname(self):
438
+ """Test the TAGNAME getter and default behavior"""
439
+ ph = ParameterHandler(skip_version_check=True)
440
+ assert ph.TAGNAME is None
441
+
442
+ bh = BondHandler(skip_version_check=True)
443
+ assert bh.TAGNAME == "Bonds"
444
+
445
+ def test_add_parameter(self):
446
+ """Test the behavior of add_parameter"""
447
+ bh = BondHandler(skip_version_check=True)
448
+ param1 = {
449
+ "smirks": "[*:1]-[*:2]",
450
+ "length": self.length,
451
+ "k": self.k,
452
+ "id": "b1",
453
+ }
454
+ param2 = {
455
+ "smirks": "[*:1]=[*:2]",
456
+ "length": self.length,
457
+ "k": self.k,
458
+ "id": "b2",
459
+ }
460
+ param3 = {
461
+ "smirks": "[*:1]#[*:2]",
462
+ "length": self.length,
463
+ "k": self.k,
464
+ "id": "b3",
465
+ }
466
+
467
+ bh.add_parameter(param1)
468
+ bh.add_parameter(param2)
469
+ bh.add_parameter(param3)
470
+
471
+ assert [p.id for p in bh._parameters] == ["b1", "b2", "b3"]
472
+
473
+ param_duplicate_smirks = {
474
+ "smirks": param2["smirks"],
475
+ "length": 2 * self.length,
476
+ "k": 2 * self.k,
477
+ "id": "b4",
478
+ }
479
+
480
+ # Ensure a duplicate parameter cannot be added under default conditions
481
+ with pytest.raises(DuplicateParameterError):
482
+ bh.add_parameter(param_duplicate_smirks)
483
+ # Ensure a duplicate parameter CAN be added if `allow_duplicate_smirks=True`
484
+ bh.add_parameter(param_duplicate_smirks, allow_duplicate_smirks=True)
485
+
486
+ dict_to_add_by_smirks = {
487
+ "smirks": "[#1:1]-[#6:2]",
488
+ "length": self.length,
489
+ "k": self.k,
490
+ "id": "d1",
491
+ }
492
+ dict_to_add_by_index = {
493
+ "smirks": "[#1:1]-[#8:2]",
494
+ "length": self.length,
495
+ "k": self.k,
496
+ "id": "d2",
497
+ }
498
+
499
+ param_to_add_by_smirks = BondHandler.BondType(
500
+ **{
501
+ "smirks": "[#6:1]-[#6:2]",
502
+ "length": self.length,
503
+ "k": self.k,
504
+ "id": "p1",
505
+ }
506
+ )
507
+ param_to_add_by_index = BondHandler.BondType(
508
+ **{
509
+ "smirks": "[#6:1]=[#8:2]",
510
+ "length": self.length,
511
+ "k": self.k,
512
+ "id": "p2",
513
+ }
514
+ )
515
+
516
+ param_several_apart = {
517
+ "smirks": "[#1:1]-[#7:2]",
518
+ "length": self.length,
519
+ "k": self.k,
520
+ "id": "s0",
521
+ }
522
+
523
+ # The `before` parameter should come after the `after` parameter
524
+ # in the parameter list; i.e. in this list of ['-', '=', '#'], it is
525
+ # impossible to add a new parameter after '=' *and* before '-'
526
+ with pytest.raises(ValueError):
527
+ # Test invalid parameter order by SMIRKS
528
+ bh.add_parameter(dict_to_add_by_smirks, after="[*:1]=[*:2]", before="[*:1]-[*:2]")
529
+
530
+ with pytest.raises(ValueError):
531
+ # Test invalid parameter order by index
532
+ bh.add_parameter(dict_to_add_by_index, after=1, before=0)
533
+
534
+ # Add d1 before param b2
535
+ bh.add_parameter(dict_to_add_by_smirks, before="[*:1]=[*:2]")
536
+
537
+ assert [p.id for p in bh._parameters] == ["b1", "d1", "b2", "b3", "b4"]
538
+
539
+ # Add d2 after index 2 (which is also param b2)
540
+ bh.add_parameter(dict_to_add_by_index, after=2)
541
+
542
+ assert [p.id for p in bh._parameters] == ["b1", "d1", "b2", "d2", "b3", "b4"]
543
+
544
+ # Add p1 before param b3
545
+ bh.add_parameter(parameter=param_to_add_by_smirks, before="[*:1]=[*:2]")
546
+
547
+ assert [p.id for p in bh._parameters] == [
548
+ "b1",
549
+ "d1",
550
+ "p1",
551
+ "b2",
552
+ "d2",
553
+ "b3",
554
+ "b4",
555
+ ]
556
+
557
+ # Add p2 after index 2 (which is param p1)
558
+ bh.add_parameter(parameter=param_to_add_by_index, after=2)
559
+
560
+ assert [p.id for p in bh._parameters] == [
561
+ "b1",
562
+ "d1",
563
+ "p1",
564
+ "p2",
565
+ "b2",
566
+ "d2",
567
+ "b3",
568
+ "b4",
569
+ ]
570
+
571
+ # Add s0 between params that are several positions apart
572
+ bh.add_parameter(param_several_apart, after=1, before=6)
573
+
574
+ assert [p.id for p in bh._parameters] == [
575
+ "b1",
576
+ "d1",
577
+ "s0",
578
+ "p1",
579
+ "p2",
580
+ "b2",
581
+ "d2",
582
+ "b3",
583
+ "b4",
584
+ ]
585
+
586
+ def test_different_units_to_dict(self):
587
+ """Test ParameterHandler.to_dict() function when some parameters are in
588
+ different units (proper behavior is to convert all quantities to the last-
589
+ read unit)
590
+ """
591
+ bh = BondHandler(skip_version_check=True)
592
+ bh.add_parameter(
593
+ {
594
+ "smirks": "[*:1]-[*:2]",
595
+ "length": 1 * unit.angstrom,
596
+ "k": 10 * unit.kilocalorie / unit.mole / unit.angstrom**2,
597
+ }
598
+ )
599
+ bh.add_parameter(
600
+ {
601
+ "smirks": "[*:1]=[*:2]",
602
+ "length": 0.2 * unit.nanometer,
603
+ "k": 0.4 * unit.kilojoule / unit.mole / unit.nanometer**2,
604
+ }
605
+ )
606
+ bh_dict = bh.to_dict()
607
+ assert bh_dict["Bond"][0]["length"] == unit.Quantity(value=1, units=unit.angstrom)
608
+ assert bh_dict["Bond"][1]["length"] == unit.Quantity(value=2, units=unit.angstrom)
609
+
610
+ def test_to_dict_maintain_units(self):
611
+ """Test ParameterHandler.to_dict() function when parameters were provided in different units"""
612
+ bh = BondHandler(skip_version_check=True)
613
+ bh.add_parameter(
614
+ {
615
+ "smirks": "[*:1]-[*:2]",
616
+ "length": 1 * unit.angstrom,
617
+ "k": 10 * unit.kilocalorie / unit.mole / unit.angstrom**2,
618
+ }
619
+ )
620
+ bh.add_parameter(
621
+ {
622
+ "smirks": "[*:1]=[*:2]",
623
+ "length": 0.2 * unit.nanometer,
624
+ "k": 0.4 * unit.kilojoule / unit.mole / unit.nanometer**2,
625
+ }
626
+ )
627
+ bh_dict = bh.to_dict()
628
+ assert bh_dict["Bond"][0]["length"] == unit.Quantity(1.0, unit.angstrom)
629
+ assert bh_dict["Bond"][0]["length"].units == unit.angstrom
630
+ assert bh_dict["Bond"][1]["length"] == unit.Quantity(0.2, unit.nanometer)
631
+ assert bh_dict["Bond"][1]["length"].units == unit.nanometer
632
+
633
+ def test_missing_section_version(self):
634
+ """Test that exceptions are raised if invalid or improper section versions are provided during intialization"""
635
+ # Generate a SMIRNOFFSpecError by not providing a section version
636
+ with pytest.raises(SMIRNOFFSpecError, match="Missing version while trying to construct"):
637
+ ParameterHandler()
638
+
639
+ # Successfully create ParameterHandler by skipping version check
640
+ ParameterHandler(skip_version_check=True)
641
+
642
+ # Successfully create ParameterHandler by providing max supported version
643
+ ParameterHandler(version=ParameterHandler._MAX_SUPPORTED_SECTION_VERSION)
644
+
645
+ # Successfully create ParameterHandler by providing min supported version
646
+ ParameterHandler(version=ParameterHandler._MIN_SUPPORTED_SECTION_VERSION)
647
+
648
+ # Generate a SMIRNOFFSpecError by providing a value higher than the max supported
649
+ with pytest.raises(
650
+ SMIRNOFFVersionError,
651
+ match=r"SMIRNOFF offxml file was written with version 1000.0, but this version of ForceField only supports version",
652
+ ):
653
+ ParameterHandler(version="1000.0")
654
+
655
+ # Generate a SMIRNOFFSpecError by providing a value lower than the min supported
656
+ with pytest.raises(
657
+ SMIRNOFFVersionError,
658
+ match=r"SMIRNOFF offxml file was written with version 0.1, but this version of ForceField only supports version",
659
+ ):
660
+ ParameterHandler(version="0.1")
661
+
662
+ def test_supported_version_range(self):
663
+ """
664
+ Ensure that version values in various formats can be correctly parsed and validated
665
+ """
666
+
667
+ class MyPHSubclass(ParameterHandler):
668
+ _MIN_SUPPORTED_SECTION_VERSION = Version("0.3")
669
+ _MAX_SUPPORTED_SECTION_VERSION = Version("2")
670
+
671
+ with pytest.raises(SMIRNOFFVersionError):
672
+ MyPHSubclass(version=0.1)
673
+ with pytest.raises(Exception, match=r"Could not convert .*list"):
674
+ MyPHSubclass(version=[0])
675
+ MyPHSubclass(version=0.3)
676
+ MyPHSubclass(version=1)
677
+ MyPHSubclass(version="1.9")
678
+ MyPHSubclass(version=2.0)
679
+ with pytest.raises(SMIRNOFFVersionError):
680
+ MyPHSubclass(version=2.1)
681
+
682
+ def test_write_same_version_as_was_set(self):
683
+ """Ensure that a ParameterHandler remembers the version that was set when it was initialized."""
684
+
685
+ class MyPHSubclass(ParameterHandler):
686
+ _MIN_SUPPORTED_SECTION_VERSION = Version("0.3")
687
+ _MAX_SUPPORTED_SECTION_VERSION = Version("2")
688
+
689
+ my_ph = MyPHSubclass(version=1.234)
690
+ assert my_ph.to_dict()["version"] == str(Version("1.234"))
691
+
692
+ def test_add_delete_cosmetic_attributes(self):
693
+ """Test ParameterHandler.to_dict() function when some parameters are in
694
+ different units (proper behavior is to convert all quantities to the last-
695
+ read unit)
696
+ """
697
+ bh = BondHandler(skip_version_check=True)
698
+ bh.add_parameter(
699
+ {
700
+ "smirks": "[*:1]-[*:2]",
701
+ "length": 1 * unit.angstrom,
702
+ "k": 10 * unit.kilocalorie / unit.mole / unit.angstrom**2,
703
+ }
704
+ )
705
+ bh.add_parameter(
706
+ {
707
+ "smirks": "[*:1]=[*:2]",
708
+ "length": 0.2 * unit.nanometer,
709
+ "k": 0.4 * unit.kilojoule / unit.mole / unit.nanometer**2,
710
+ }
711
+ )
712
+
713
+ assert not (bh.attribute_is_cosmetic("pilot"))
714
+
715
+ # Ensure the cosmetic attribute is present by default during output
716
+ bh.add_cosmetic_attribute("pilot", "alice")
717
+ param_dict = bh.to_dict()
718
+ assert ("pilot", "alice") in param_dict.items()
719
+ assert bh.attribute_is_cosmetic("pilot")
720
+
721
+ # Ensure the cosmetic attribute isn't present if we request that it be discarded
722
+ param_dict = bh.to_dict(discard_cosmetic_attributes=True)
723
+ assert "pilot" not in param_dict
724
+
725
+ # Manually delete the cosmetic attribute and ensure it doesn't get written out
726
+ bh.delete_cosmetic_attribute("pilot")
727
+ param_dict = bh.to_dict()
728
+ assert "pilot" not in param_dict
729
+ assert not (bh.attribute_is_cosmetic("pilot"))
730
+
731
+ def test_get_parameter(self):
732
+ """Test that ParameterHandler.get_parameter can lookup function"""
733
+ bh = BondHandler(skip_version_check=True, allow_cosmetic_attributes=True)
734
+
735
+ bh.add_parameter(
736
+ {
737
+ "smirks": "[*:1]-[*:2]",
738
+ "length": 1 * unit.angstrom,
739
+ "k": 10 * unit.kilocalorie / unit.mole / unit.angstrom**2,
740
+ "id": "b0",
741
+ }
742
+ )
743
+ bh.parameters[0].add_cosmetic_attribute("foo", "bar")
744
+
745
+ # Check base behavior
746
+ params = bh.get_parameter({"smirks": "[*:1]-[*:2]"})
747
+
748
+ assert params[0].length == unit.Quantity(1.0, unit.angstrom)
749
+ assert params[0].k == unit.Quantity(10.0, unit.kilocalorie / unit.mole / unit.angstrom**2)
750
+
751
+ # Ensure a query with no matches returns an empty list
752
+ assert not bh.get_parameter({"smirks": "xyz"})
753
+
754
+ # Ensure searching for a nonexistent attr does not raise an exception
755
+ assert not bh.get_parameter({"bAdAttR": "0"})
756
+
757
+ # Check for optional and cosmetic attrs
758
+ optional_params = bh.get_parameter({"id": "b0"})
759
+ cosmetic_params = bh.get_parameter({"foo": "bar"})
760
+
761
+ assert optional_params[0].id == "b0"
762
+ assert cosmetic_params[0]._foo == "bar"
763
+
764
+ # Ensure selection behaves a "OR" not "AND"
765
+ bh.add_parameter(
766
+ {
767
+ "smirks": "[#1:1]-[#6:2]",
768
+ "length": 1 * unit.angstrom,
769
+ "k": 10 * unit.kilocalorie / unit.mole / unit.angstrom**2,
770
+ "id": "b1",
771
+ }
772
+ )
773
+
774
+ params = bh.get_parameter({"id": "b0", "smirks": "[#1:1]-[#6:2]"})
775
+
776
+ assert "b0" in [param.id for param in params]
777
+ assert "[*:1]-[*:2]" in [param.smirks for param in params]
778
+
779
+ # Ensure selection does not return duplicates if multiple matches
780
+ params = bh.get_parameter({"id": "b1", "smirks": "[#1:1]-[#6:2]"})
781
+
782
+ assert len(params) == 1
783
+
784
+ def test_create_force(self):
785
+ class MyParameterHandler(ParameterHandler):
786
+ pass
787
+
788
+ handler = MyParameterHandler(version=0.3)
789
+
790
+ with pytest.raises(NotImplementedError, match=r"no longer create OpenMM forces."):
791
+ handler.create_force()
792
+
793
+
794
+ class TestParameterList:
795
+ """Test capabilities of ParameterList for accessing and manipulating SMIRNOFF parameter definitions."""
796
+
797
+ def test_create(self):
798
+ """Test creation of a parameter list."""
799
+ p1 = ParameterType(smirks="[*:1]")
800
+ p2 = ParameterType(smirks="[#1:1]")
801
+ ParameterList([p1, p2])
802
+
803
+ def test_index(self):
804
+ """
805
+ Tests the ParameterList.index() function by attempting lookups by SMIRKS and by ParameterType equivalence.
806
+
807
+ """
808
+ p1 = ParameterType(smirks="[*:1]")
809
+ p2 = ParameterType(smirks="[#1:1]")
810
+ p3 = ParameterType(smirks="[#7:1]")
811
+ parameters = ParameterList([p1, p2, p3])
812
+ assert parameters.index(p1) == 0
813
+ assert parameters.index(p2) == 1
814
+ assert parameters.index(p3) == 2
815
+ assert parameters.index("[*:1]") == 0
816
+ assert parameters.index("[#1:1]") == 1
817
+ assert parameters.index("[#7:1]") == 2
818
+ with pytest.raises(ParameterLookupError, match=r"SMIRKS \[#2:1\] not found in ParameterList"):
819
+ parameters.index("[#2:1]")
820
+
821
+ p4 = ParameterType(smirks="[#2:1]")
822
+ with pytest.raises(ValueError, match="is not in list"):
823
+ parameters.index(p4)
824
+
825
+ with pytest.raises(TypeError, match="non-None values for start"):
826
+ parameters.index("[*:1]", start=1)
827
+ with pytest.raises(TypeError, match="non-None values for stop"):
828
+ parameters.index("[*:1]", stop=-1)
829
+
830
+ def test_index_duplicates(self):
831
+ """Test ParameterList.index when multiple parameters have identical SMIRKS"""
832
+ p1 = ParameterType(smirks="[*:1]")
833
+ p2 = ParameterType(smirks="[*:1]")
834
+ parameters = ParameterList([p1, p2])
835
+ assert parameters.index("[*:1]") == 1
836
+
837
+ def test_contains(self):
838
+ """Test ParameterList __contains__ overloading."""
839
+ p1 = ParameterType(smirks="[*:1]")
840
+ p2 = ParameterType(smirks="[#1:1]")
841
+ p3 = ParameterType(smirks="[#7:1]")
842
+ parameters = ParameterList([p1, p2])
843
+ assert p1 in parameters
844
+ assert p2 in parameters
845
+ assert p3 not in parameters
846
+ assert p1.smirks in parameters
847
+ assert p2.smirks in parameters
848
+ assert p3.smirks not in parameters
849
+
850
+ def test_del(self):
851
+ """
852
+ Test ParameterList __del__ overloading.
853
+ """
854
+ p1 = ParameterType(smirks="[*:1]")
855
+ p2 = ParameterType(smirks="[#1:1]")
856
+ p3 = ParameterType(smirks="[#7:1]")
857
+ parameters = ParameterList([p1, p2, p3])
858
+
859
+ with pytest.raises(IndexError, match="list assignment index out of range"):
860
+ del parameters[4]
861
+ with pytest.raises(
862
+ ParameterLookupError,
863
+ match=r"SMIRKS \[#6:1\] not found in ParameterList",
864
+ ):
865
+ del parameters["[#6:1]"]
866
+
867
+ # Test that original list deletion behavior is preserved.
868
+ del parameters[2]
869
+ assert len(parameters) == 2
870
+ assert p1 in parameters
871
+ assert p2 in parameters
872
+ assert p3 not in parameters
873
+
874
+ # Test that we can delete elements by their smirks.
875
+ del parameters["[#1:1]"]
876
+ assert len(parameters) == 1
877
+ assert p1 in parameters
878
+ assert p2 not in parameters
879
+
880
+ def test_append(self):
881
+ """
882
+ Test ParameterList.append, ensuring that the new parameter was added to the bottom of the list
883
+ and that it is properly recorded as the most recently-added.
884
+ """
885
+ p1 = ParameterType(smirks="[*:1]-[*:2]")
886
+ p2 = ParameterType(smirks="[*:1]=[*:2]")
887
+ param_list = ParameterList()
888
+ param_list.append(p1)
889
+ assert len(param_list) == 1
890
+ assert "[*:1]-[*:2]" in param_list
891
+ param_list.append(p2)
892
+ assert len(param_list) == 2
893
+ assert "[*:1]=[*:2]" in param_list
894
+ assert param_list[-1] == p2
895
+
896
+ def test_insert(self):
897
+ """
898
+ Test ParameterList.insert, ensuring that the new parameter was added to the proper spot in
899
+ the list and that it is propertly recorded as the most recently added.
900
+ """
901
+ p1 = ParameterType(smirks="[*:1]-[*:2]")
902
+ p2 = ParameterType(smirks="[*:1]=[*:2]")
903
+ p3 = ParameterType(smirks="[*:1]#[*:2]")
904
+ param_list = ParameterList([p1, p2])
905
+ param_list.insert(1, p3)
906
+ assert param_list[1] == p3
907
+
908
+ def test_extend(self):
909
+ """
910
+ Test ParameterList.extend, ensuring that the new parameter was added to the proper spot in
911
+ the list and that it is propertly recorded as the most recently added.
912
+ """
913
+ p1 = ParameterType(smirks="[*:1]-[*:2]")
914
+ p2 = ParameterType(smirks="[*:1]=[*:2]")
915
+ param_list1 = ParameterList()
916
+ param_list2 = ParameterList([p1, p2])
917
+
918
+ param_list1.extend(param_list2)
919
+ assert len(param_list1) == 2
920
+ assert "[*:1]-[*:2]" in param_list1
921
+ assert "[*:1]=[*:2]" in param_list1
922
+ assert param_list1[-1] == p2
923
+
924
+ def test_to_list(self):
925
+ """Test basic ParameterList.to_list() function, ensuring units are preserved"""
926
+ p1 = BondHandler.BondType(
927
+ smirks="[*:1]-[*:2]",
928
+ length=1.01 * unit.angstrom,
929
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
930
+ )
931
+ p2 = BondHandler.BondType(
932
+ smirks="[*:1]=[*:2]",
933
+ length=1.02 * unit.angstrom,
934
+ k=6 * unit.kilocalorie / unit.mole / unit.angstrom**2,
935
+ )
936
+ p3 = BondHandler.BondType(
937
+ smirks="[*:1]#[*:3]",
938
+ length=1.03 * unit.angstrom,
939
+ k=7 * unit.kilocalorie / unit.mole / unit.angstrom**2,
940
+ )
941
+ parameter_list = ParameterList([p1, p2, p3])
942
+ ser_param_list = parameter_list.to_list()
943
+ assert len(ser_param_list) == 3
944
+ assert ser_param_list[0]["length"] == 1.01 * unit.angstrom
945
+
946
+ def test_round_trip(self):
947
+ """Test basic ParameterList.to_list() function and constructor"""
948
+ p1 = BondHandler.BondType(
949
+ smirks="[*:1]-[*:2]",
950
+ length=1.01 * unit.angstrom,
951
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
952
+ )
953
+ p2 = BondHandler.BondType(
954
+ smirks="[*:1]=[*:2]",
955
+ length=1.02 * unit.angstrom,
956
+ k=6 * unit.kilocalorie / unit.mole / unit.angstrom**2,
957
+ )
958
+ p3 = BondHandler.BondType(
959
+ smirks="[*:1]#[*:3]",
960
+ length=1.03 * unit.angstrom,
961
+ k=7 * unit.kilocalorie / unit.mole / unit.angstrom**2,
962
+ )
963
+ parameter_list = ParameterList([p1, p2, p3])
964
+ param_dict_list = parameter_list.to_list()
965
+ parameter_list_2 = ParameterList()
966
+ for param_dict in param_dict_list:
967
+ new_parameter = BondHandler.BondType(**param_dict)
968
+ parameter_list_2.append(new_parameter)
969
+ assert parameter_list.to_list() == parameter_list_2.to_list()
970
+
971
+
972
+ class TestParameterType:
973
+ def test_find_all_parameter_attrs(self):
974
+ """ParameterType find all ParameterAttributes in the declared order."""
975
+
976
+ class MyParameter(ParameterType):
977
+ attr = ParameterAttribute()
978
+ indexed = IndexedParameterAttribute()
979
+
980
+ parameter_attributes = MyParameter._get_parameter_attributes()
981
+
982
+ # The function should find also the parent's attributes and in the correct order.
983
+ expected_attributes = ["smirks", "id", "parent_id", "attr", "indexed"]
984
+ assert list(parameter_attributes.keys()) == expected_attributes
985
+
986
+ # The keys map to the descriptor instances.
987
+ assert type(parameter_attributes["attr"]) is ParameterAttribute
988
+ assert type(parameter_attributes["indexed"]) is IndexedParameterAttribute
989
+
990
+ def test_find_all_indexed_parameter_attrs(self):
991
+ """ParameterType find all IndexedParameterAttributes."""
992
+
993
+ class MyParameter(ParameterType):
994
+ attr = ParameterAttribute()
995
+ indexed = IndexedParameterAttribute()
996
+ attr2 = ParameterAttribute()
997
+ indexed2 = IndexedParameterAttribute(default=None)
998
+
999
+ expected_names = ["indexed", "indexed2"]
1000
+ parameter_attributes = MyParameter._get_indexed_parameter_attributes()
1001
+ assert list(parameter_attributes.keys()) == expected_names
1002
+ assert all(isinstance(parameter_attributes[name], IndexedParameterAttribute) for name in expected_names)
1003
+
1004
+ def test_find_all_required_and_optional_parameter_attrs(self):
1005
+ """ParameterType distinguish between required and optional ParameterAttributes."""
1006
+
1007
+ class MyParameter(ParameterType):
1008
+ required = ParameterAttribute()
1009
+ optional = ParameterAttribute(default=1)
1010
+ required_indexed = IndexedParameterAttribute()
1011
+ optional_indexed2 = IndexedParameterAttribute(default=None)
1012
+
1013
+ expected_names = ["smirks", "required", "required_indexed"]
1014
+ parameter_attributes = MyParameter._get_required_parameter_attributes()
1015
+ assert list(parameter_attributes.keys()) == expected_names
1016
+
1017
+ expected_names = ["id", "parent_id", "optional", "optional_indexed2"]
1018
+ parameter_attributes = MyParameter._get_optional_parameter_attributes()
1019
+ assert list(parameter_attributes.keys()) == expected_names
1020
+
1021
+ def test_required_attribute_on_init(self):
1022
+ """ParameterType raises TypeError if a required attribute is not specified on construction."""
1023
+
1024
+ class MyParameter(ParameterType):
1025
+ required = ParameterAttribute()
1026
+ optional = ParameterAttribute(default=None)
1027
+
1028
+ with pytest.raises(SMIRNOFFSpecError, match="require the following missing parameters"):
1029
+ MyParameter(smirks="[*:1]", optional=1)
1030
+
1031
+ def test_add_delete_cosmetic_attributes(self):
1032
+ """
1033
+ Test ParameterType.add_cosmetic_attribute, delete_cosmetic_attribute,
1034
+ attribute_is_cosmetic, and to_dict() functions for proper behavior
1035
+ """
1036
+
1037
+ class MyParameter(ParameterType):
1038
+ required = ParameterAttribute()
1039
+
1040
+ my_par = MyParameter(smirks="[*:1]", required="aaa")
1041
+ assert not (my_par.attribute_is_cosmetic("pilot"))
1042
+
1043
+ # Ensure the cosmetic attribute is present by default during output
1044
+ my_par.add_cosmetic_attribute("pilot", "alice")
1045
+ param_dict = my_par.to_dict()
1046
+ assert ("pilot", "alice") in param_dict.items()
1047
+ assert my_par.attribute_is_cosmetic("pilot")
1048
+
1049
+ # Ensure the cosmetic attribute isn't present if we request that it be discarded
1050
+ param_dict = my_par.to_dict(discard_cosmetic_attributes=True)
1051
+ assert "pilot" not in param_dict
1052
+
1053
+ # Manually delete the cosmetic attribute and ensure it doesn't get written out
1054
+ my_par.delete_cosmetic_attribute("pilot")
1055
+ param_dict = my_par.to_dict()
1056
+ assert "pilot" not in param_dict
1057
+ assert not (my_par.attribute_is_cosmetic("pilot"))
1058
+
1059
+ def test_indexed_attrs(self):
1060
+ """ParameterType handles indexed attributes correctly."""
1061
+
1062
+ class MyParameter(ParameterType):
1063
+ a = IndexedParameterAttribute()
1064
+ b = IndexedParameterAttribute()
1065
+
1066
+ my_par = MyParameter(smirks="[*:1]", a1=1, a3=3, a2=2, b1=4, b2=5, b3=6)
1067
+ assert my_par.a == [1, 2, 3]
1068
+ assert my_par.b == [4, 5, 6]
1069
+
1070
+ def test_sequence_init_indexed_attr(self):
1071
+ """ParameterType handle indexed attributes initialized with sequences correctly."""
1072
+
1073
+ class MyParameter(ParameterType):
1074
+ a = IndexedParameterAttribute()
1075
+
1076
+ my_par = MyParameter(smirks="[*:1]", a=(1, 2))
1077
+ assert my_par.a == [1, 2]
1078
+
1079
+ def test_same_length_indexed_attrs(self):
1080
+ """ParameterType raises TypeError if indexed attributes of different lengths are given."""
1081
+
1082
+ class MyParameter(ParameterType):
1083
+ a = IndexedParameterAttribute()
1084
+ b = IndexedParameterAttribute()
1085
+
1086
+ with pytest.raises(TypeError, match="indexed attributes have different lengths"):
1087
+ MyParameter(smirks="[*:1]", a1=1, a2=2, a3=3, b1=1, b2=2)
1088
+
1089
+ def test_error_single_value_plus_index(self):
1090
+ """ParameterType raises an error if an indexed attribute is specified with and without index."""
1091
+
1092
+ class MyParameter(ParameterType):
1093
+ a = IndexedParameterAttribute()
1094
+
1095
+ with pytest.raises(TypeError, match="'a' has been specified with and without index"):
1096
+ MyParameter(smirks="[*:1]", a=[1], a1=2)
1097
+
1098
+ def test_find_all_defined_parameter_attrs(self):
1099
+ """ParameterType._get_defined_attributes() discards None default-value attributes."""
1100
+
1101
+ class MyParameter(ParameterType):
1102
+ required1 = ParameterAttribute()
1103
+ optional1 = ParameterAttribute(default=None)
1104
+ optional2 = IndexedParameterAttribute(default=None)
1105
+ optional3 = ParameterAttribute(default=5)
1106
+ required2 = IndexedParameterAttribute()
1107
+ optional4 = ParameterAttribute(default=2)
1108
+
1109
+ my_par = MyParameter(smirks="[*:1]", required1=0, optional1=10, required2=[0])
1110
+
1111
+ # _get_defined_parameter_attributes discards only the attribute
1112
+ # that are set to None as a default value.
1113
+ expected_names = [
1114
+ "smirks",
1115
+ "required1",
1116
+ "required2",
1117
+ "optional1",
1118
+ "optional3",
1119
+ "optional4",
1120
+ ]
1121
+ parameter_attributes = my_par._get_defined_parameter_attributes()
1122
+ assert list(parameter_attributes.keys()) == expected_names
1123
+
1124
+ def test_base_parametertype_to_dict(self):
1125
+ """
1126
+ Test ParameterType to_dict.
1127
+ """
1128
+ p1 = ParameterType(smirks="[*:1]")
1129
+ param_dict = p1.to_dict()
1130
+ assert param_dict["smirks"] == "[*:1]"
1131
+ assert len(param_dict.keys()) == 1
1132
+
1133
+ def test_repr(self):
1134
+ class NamedType(ParameterType):
1135
+ pass
1136
+
1137
+ assert NamedType(smirks="[*:1]").__repr__().startswith("<NamedType")
1138
+
1139
+
1140
+ class TestElementName:
1141
+ @pytest.mark.parametrize(
1142
+ ("_class", "expected_name"),
1143
+ [
1144
+ (ConstraintHandler, "Constraint"),
1145
+ (BondHandler, "Bond"),
1146
+ (AngleHandler, "Angle"),
1147
+ (ProperTorsionHandler, "Proper"),
1148
+ (ImproperTorsionHandler, "Improper"),
1149
+ (vdWHandler, "Atom"),
1150
+ (LibraryChargeHandler, "LibraryCharge"),
1151
+ (ChargeIncrementModelHandler, "ChargeIncrement"),
1152
+ (VirtualSiteHandler, "VirtualSite"),
1153
+ (GBSAHandler, "Atom"),
1154
+ ],
1155
+ )
1156
+ def test_element_names(self, _class, expected_name):
1157
+ assert _class._INFOTYPE._ELEMENT_NAME == expected_name
1158
+
1159
+
1160
+ class TestBondType:
1161
+ """Tests for the BondType class."""
1162
+
1163
+ def test_bondtype_to_dict(self):
1164
+ """
1165
+ Test BondType to_dict.
1166
+ """
1167
+ p1 = BondHandler.BondType(
1168
+ smirks="[*:1]-[*:2]",
1169
+ length=1.02 * unit.angstrom,
1170
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1171
+ )
1172
+ param_dict = p1.to_dict()
1173
+
1174
+ assert param_dict == {
1175
+ "smirks": "[*:1]-[*:2]",
1176
+ "length": unit.Quantity(1.02, unit.angstrom),
1177
+ "k": unit.Quantity(5, unit.kilocalorie_per_mole / unit.angstrom**2),
1178
+ }
1179
+
1180
+ def test_bondtype_partial_bondorders(self):
1181
+ """
1182
+ Test the parsing of a BondType with k_bondorder1/2/3 definitions
1183
+ """
1184
+ length = 1.4 * unit.angstrom
1185
+ k1 = 101 * unit.kilocalorie / unit.mole / unit.angstrom**2
1186
+ k2 = 202 * unit.kilocalorie / unit.mole / unit.angstrom**2
1187
+ k3 = 303 * unit.kilocalorie / unit.mole / unit.angstrom**2
1188
+
1189
+ param = BondHandler.BondType(
1190
+ smirks="[*:1]-[*:2]",
1191
+ length=length,
1192
+ k_bondorder1=k1,
1193
+ k_bondorder2=k2,
1194
+ k_bondorder3=k3,
1195
+ )
1196
+
1197
+ assert param.k_bondorder == {1: k1, 2: k2, 3: k3}
1198
+
1199
+ def test_bondtype_bad_params(self):
1200
+ """
1201
+ Test the over/underspecification of k/k_bondorderN are caught
1202
+ """
1203
+ length = 1.4 * unit.angstrom
1204
+ length1 = 1.5 * unit.angstrom
1205
+ length2 = 1.3 * unit.angstrom
1206
+ k = 50 * unit.kilocalorie / unit.mole / unit.angstrom**2
1207
+ k1 = 101 * unit.kilocalorie / unit.mole / unit.angstrom**2
1208
+ k2 = 202 * unit.kilocalorie / unit.mole / unit.angstrom**2
1209
+
1210
+ with pytest.raises(SMIRNOFFSpecError, match="Either k or k_bondorder"):
1211
+ BondHandler.BondType(
1212
+ smirks="[*:1]-[*:2]",
1213
+ length=length,
1214
+ )
1215
+
1216
+ with pytest.raises(SMIRNOFFSpecError, match="BOTH k and k_bondorder"):
1217
+ BondHandler.BondType(
1218
+ smirks="[*:1]-[*:2]",
1219
+ length=length,
1220
+ k=k,
1221
+ k_bondorder1=k1,
1222
+ k_bondorder2=k2,
1223
+ )
1224
+
1225
+ with pytest.raises(SMIRNOFFSpecError, match="Either length or length_bondorder"):
1226
+ BondHandler.BondType(
1227
+ smirks="[*:1]-[*:2]",
1228
+ k=k,
1229
+ )
1230
+
1231
+ with pytest.raises(SMIRNOFFSpecError, match="BOTH length and length_bondorder"):
1232
+ BondHandler.BondType(
1233
+ smirks="[*:1]-[*:2]",
1234
+ length=length,
1235
+ k=k,
1236
+ length_bondorder1=length1,
1237
+ length_bondorder2=length2,
1238
+ )
1239
+
1240
+ def test_bondtype_to_dict_custom_output_units(self):
1241
+ """
1242
+ Test BondType to_dict with custom output units.
1243
+ """
1244
+ p1 = BondHandler.BondType(
1245
+ smirks="[*:1]-[*:2]",
1246
+ length=1.02 * unit.angstrom,
1247
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1248
+ )
1249
+
1250
+ param_dict = p1.to_dict()
1251
+
1252
+ assert abs(param_dict["length"].m_as(unit.nanometer) - 0.102) < 1e-10
1253
+
1254
+ def test_read_write_optional_parameter_attribute(self):
1255
+ """
1256
+ Test ParameterTypes' ability to store and write out optional attributes passed to __init__()
1257
+ """
1258
+ p1 = BondHandler.BondType(
1259
+ smirks="[*:1]-[*:2]",
1260
+ length=1.02 * unit.angstrom,
1261
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1262
+ id="b1",
1263
+ )
1264
+ param_dict = p1.to_dict()
1265
+ assert ("id", "b1") in param_dict.items()
1266
+
1267
+ def test_read_write_cosmetic_parameter_attribute(self):
1268
+ """
1269
+ Test ParameterTypes' ability to store and write out cosmetic attributes passed to __init__()
1270
+ """
1271
+ p1 = BondHandler.BondType(
1272
+ smirks="[*:1]-[*:2]",
1273
+ length=1.02 * unit.angstrom,
1274
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1275
+ pilot="alice",
1276
+ allow_cosmetic_attributes=True,
1277
+ )
1278
+ param_dict = p1.to_dict(discard_cosmetic_attributes=False)
1279
+ assert ("pilot", "alice") in param_dict.items()
1280
+
1281
+ def test_read_but_dont_write_cosmetic_parameter_attribute(self):
1282
+ """
1283
+ Test ParameterTypes' ability to ignore cosmetic attributes passed to __init__() if instructed
1284
+ """
1285
+ p1 = BondHandler.BondType(
1286
+ smirks="[*:1]-[*:2]",
1287
+ length=1.02 * unit.angstrom,
1288
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1289
+ pilot="alice",
1290
+ allow_cosmetic_attributes=True,
1291
+ )
1292
+ param_dict = p1.to_dict(discard_cosmetic_attributes=True)
1293
+ assert ("pilot", "alice") not in param_dict.items()
1294
+
1295
+ def test_error_cosmetic_parameter_attribute(self):
1296
+ """
1297
+ Test that ParameterTypes raise an error on receiving unexpected attributes passed to __init__()
1298
+ """
1299
+ with pytest.raises(SMIRNOFFSpecError, match=r"Unexpected kwarg \(pilot: alice\)"):
1300
+ BondHandler.BondType(
1301
+ smirks="[*:1]-[*:2]",
1302
+ length=1.02 * unit.angstrom,
1303
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1304
+ pilot="alice",
1305
+ allow_cosmetic_attributes=False,
1306
+ )
1307
+
1308
+ def test_add_delete_cosmetic_attrib(self):
1309
+ """
1310
+ Test adding and deleting cosmetic attributes for already-initialized ParameterType objects
1311
+ """
1312
+ p1 = BondHandler.BondType(
1313
+ smirks="[*:1]-[*:2]",
1314
+ length=1.02 * unit.angstrom,
1315
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1316
+ )
1317
+ # Ensure the cosmetic attribute is present by default during output
1318
+ p1.add_cosmetic_attribute("pilot", "alice")
1319
+ param_dict = p1.to_dict()
1320
+ assert ("pilot", "alice") in param_dict.items()
1321
+
1322
+ # Ensure the cosmetic attribute isn't present if we request that it be discarded
1323
+ param_dict = p1.to_dict(discard_cosmetic_attributes=True)
1324
+ assert ("pilot", "alice") not in param_dict.items()
1325
+
1326
+ # Manually delete the cosmetic attribute and ensure it doesn't get written out
1327
+ p1.delete_cosmetic_attribute("pilot")
1328
+ param_dict = p1.to_dict()
1329
+ assert ("pilot", "alice") not in param_dict.items()
1330
+
1331
+
1332
+ class TestBondHandler:
1333
+ @pytest.mark.parametrize(
1334
+ ("fractional_bond_order", "k_interpolated", "length_interpolated"),
1335
+ [
1336
+ (1.0, 101, 1.4),
1337
+ (1.5, 112.0, 1.35),
1338
+ (1.99, 122.78, 1.301),
1339
+ (2.1, 125.2, 1.29),
1340
+ ],
1341
+ )
1342
+ def test_linear_interpolate(self, fractional_bond_order, k_interpolated, length_interpolated):
1343
+ """Test that linear interpolation works as expected"""
1344
+ k_bondorder = {
1345
+ 1: 101 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1346
+ 2: 123 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1347
+ }
1348
+
1349
+ length_bondorder = {
1350
+ 1: 1.4 * unit.angstrom,
1351
+ 2: 1.3 * unit.angstrom,
1352
+ }
1353
+
1354
+ k = _linear_inter_or_extrapolate(k_bondorder, fractional_bond_order)
1355
+ length = _linear_inter_or_extrapolate(length_bondorder, fractional_bond_order)
1356
+ assert_almost_equal(k.m, k_interpolated, 1)
1357
+ assert_almost_equal(length.m, length_interpolated, 2)
1358
+
1359
+ def test_different_defaults_03_04(self):
1360
+ """Ensure that the 0.3 and 0.4 versions' defaults are correctly set"""
1361
+ bh = BondHandler(version=0.3)
1362
+ assert bh.fractional_bondorder_method == "none"
1363
+ assert bh.potential == "harmonic"
1364
+ bh2 = BondHandler(version=0.4)
1365
+ assert bh2.fractional_bondorder_method == "AM1-Wiberg"
1366
+ assert bh2.potential == "(k/2)*(r-length)^2"
1367
+ bh3 = BondHandler(version=0.3, fractional_bondorder_method="AM1-Wiberg")
1368
+ assert bh3.fractional_bondorder_method == "AM1-Wiberg"
1369
+ assert bh3.fractional_bondorder_interpolation == "linear"
1370
+ assert bh3.potential == "harmonic"
1371
+
1372
+ def test_harmonic_potentials_are_compatible(self):
1373
+ """
1374
+ Ensure that handlers with `potential="harmonic"` evaluate as compatible with handlers with
1375
+ potential="(k/2)*(r-length)^2"
1376
+ """
1377
+ bh1 = BondHandler(skip_version_check=True)
1378
+ bh2 = BondHandler(skip_version_check=True)
1379
+ bh1.potential = "harmonic"
1380
+ bh2.potential = "(k/2)*(r-length)^2"
1381
+ # This comparison should pass, since the potentials defined above are compatible
1382
+ bh1.check_handler_compatibility(bh2)
1383
+
1384
+ def test_am1_wiberg_combine_error(self):
1385
+ """Reproduce issue #719 and a suggested fix."""
1386
+ v3 = BondHandler(version=0.3)
1387
+ v4 = BondHandler(version=0.4)
1388
+
1389
+ v3.add_parameter(
1390
+ parameter=BondHandler.BondType(
1391
+ smirks="[#6:1]-[*:2]",
1392
+ length=1.0 * unit.angstrom,
1393
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1394
+ )
1395
+ )
1396
+
1397
+ v4.add_parameter(
1398
+ parameter=BondHandler.BondType(
1399
+ smirks="[#8:1]-[*:2]",
1400
+ length=2.0 * unit.angstrom,
1401
+ k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
1402
+ )
1403
+ )
1404
+
1405
+ ff_v3 = ForceField()
1406
+ ff_v4 = ForceField()
1407
+
1408
+ ff_v3.register_parameter_handler(v3)
1409
+ ff_v4.register_parameter_handler(v4)
1410
+
1411
+ with pytest.raises(
1412
+ IncompatibleParameterError,
1413
+ match="This likely results from mixing bond handlers",
1414
+ ):
1415
+ ff_v3._load_smirnoff_data(ff_v4._to_smirnoff_data())
1416
+
1417
+ # Simulate a user following the recommendation to switch a
1418
+ # version 0.3 BondHandler to use 'AM1-Wiberg'
1419
+ ff_v3["Bonds"].fractional_bondorder_method = "AM1-Wiberg"
1420
+
1421
+ ff_v3._load_smirnoff_data(ff_v4._to_smirnoff_data())
1422
+
1423
+
1424
+ class TestProperTorsionType:
1425
+ """Tests for the ProperTorsionType class."""
1426
+
1427
+ def test_single_term_proper_torsion(self):
1428
+ """
1429
+ Test creation and serialization of a single-term proper torsion
1430
+ """
1431
+ p1 = ProperTorsionHandler.ProperTorsionType(
1432
+ smirks="[*:1]-[*:2]-[*:3]-[*:4]",
1433
+ phase1=30 * unit.degree,
1434
+ periodicity1=2,
1435
+ k1=5 * unit.kilocalorie / unit.mole,
1436
+ )
1437
+ param_dict = p1.to_dict()
1438
+ assert ("k1", 5 * unit.kilocalorie / unit.mole) in param_dict.items()
1439
+ assert ("phase1", 30 * unit.degree) in param_dict.items()
1440
+ assert ("periodicity1", 2) in param_dict.items()
1441
+ assert "idivf" not in param_dict
1442
+
1443
+ def test_single_term_proper_torsion_w_idivf(self):
1444
+ """
1445
+ Test creation and serialization of a single-term proper torsion
1446
+ """
1447
+ p1 = ProperTorsionHandler.ProperTorsionType(
1448
+ smirks="[*:1]-[*:2]-[*:3]-[*:4]",
1449
+ phase1=30 * unit.degree,
1450
+ periodicity1=2,
1451
+ k1=5 * unit.kilocalorie / unit.mole,
1452
+ idivf1=4,
1453
+ )
1454
+
1455
+ param_dict = p1.to_dict()
1456
+ assert ("k1", 5 * unit.kilocalorie / unit.mole) in param_dict.items()
1457
+ assert ("phase1", 30 * unit.degree) in param_dict.items()
1458
+ assert ("periodicity1", 2) in param_dict.items()
1459
+ assert ("idivf1", 4) in param_dict.items()
1460
+
1461
+ def test_multi_term_proper_torsion(self):
1462
+ """
1463
+ Test creation and serialization of a multi-term proper torsion
1464
+ """
1465
+ p1 = ProperTorsionHandler.ProperTorsionType(
1466
+ smirks="[*:1]-[*:2]-[*:3]-[*:4]",
1467
+ phase1=30 * unit.degree,
1468
+ periodicity1=2,
1469
+ k1=5 * unit.kilocalorie / unit.mole,
1470
+ phase2=31 * unit.degree,
1471
+ periodicity2=3,
1472
+ k2=6 * unit.kilocalorie / unit.mole,
1473
+ )
1474
+ param_dict = p1.to_dict()
1475
+ assert param_dict["k1"] == 5 * unit.kilocalorie / unit.mole
1476
+ assert param_dict["phase1"] == 30 * unit.degree
1477
+ assert param_dict["periodicity1"] == 2
1478
+ assert param_dict["k2"] == 6 * unit.kilocalorie / unit.mole
1479
+ assert param_dict["phase2"] == 31 * unit.degree
1480
+ assert param_dict["periodicity2"] == 3
1481
+
1482
+ def test_multi_term_proper_torsion_skip_index(self):
1483
+ """
1484
+ Test creation and serialization of a multi-term proper torsion where
1485
+ the indices are not consecutive and a SMIRNOFFSpecError is raised
1486
+ """
1487
+ with pytest.raises(SMIRNOFFSpecError, match=r"Unexpected kwarg \(phase3: 31 deg\)*."):
1488
+ ProperTorsionHandler.ProperTorsionType(
1489
+ smirks="[*:1]-[*:2]-[*:3]-[*:4]",
1490
+ phase1=30 * unit.degree,
1491
+ periodicity1=2,
1492
+ k1=5 * unit.kilocalorie / unit.mole,
1493
+ phase3=31 * unit.degree,
1494
+ periodicity3=3,
1495
+ k3=6 * unit.kilocalorie / unit.mole,
1496
+ )
1497
+
1498
+ def test_multi_term_proper_torsion_bad_units(self):
1499
+ """
1500
+ Test creation and serialization of a multi-term proper torsion where
1501
+ one of the terms has incorrect units
1502
+ """
1503
+ with pytest.raises(IncompatibleUnitError, match="should have units of"):
1504
+ ProperTorsionHandler.ProperTorsionType(
1505
+ smirks="[*:1]-[*:2]-[*:3]-[*:4]",
1506
+ phase1=30 * unit.degree,
1507
+ periodicity1=2,
1508
+ k1=5 * unit.kilocalorie / unit.mole,
1509
+ phase2=31 * unit.angstrom, # This should be caught
1510
+ periodicity2=3,
1511
+ k2=6 * unit.kilocalorie / unit.mole,
1512
+ )
1513
+
1514
+ def test_single_term_proper_torsion_bo(self):
1515
+ """
1516
+ Test creation and serialization of a single-term proper torsion with bond order interpolation.
1517
+ """
1518
+ p1 = ProperTorsionHandler.ProperTorsionType(
1519
+ smirks="[*:1]-[*:2]~[*:3]-[*:4]",
1520
+ phase1=30 * unit.degree,
1521
+ periodicity1=2,
1522
+ k1_bondorder1=1 * unit.kilocalorie / unit.mole,
1523
+ k1_bondorder2=1.8 * unit.kilocalorie / unit.mole,
1524
+ )
1525
+ param_dict = p1.to_dict()
1526
+ assert ("k1_bondorder1", 1 * unit.kilocalorie / unit.mole) in param_dict.items()
1527
+ assert (
1528
+ "k1_bondorder2",
1529
+ 1.8 * unit.kilocalorie / unit.mole,
1530
+ ) in param_dict.items()
1531
+ assert ("phase1", 30 * unit.degree) in param_dict.items()
1532
+ assert ("periodicity1", 2) in param_dict.items()
1533
+ assert "idivf" not in param_dict
1534
+
1535
+ assert len(p1.k_bondorder) == 1
1536
+ assert len(p1.k_bondorder[0]) == 2
1537
+ assert {1, 2} == set(p1.k_bondorder[0].keys())
1538
+
1539
+ def test_single_term_proper_torsion_bo_w_idivf(self):
1540
+ """
1541
+ Test creation and serialization of a single-term proper torsion with bond order interpolation.
1542
+
1543
+ With `idivf1` specified.
1544
+
1545
+ """
1546
+ p1 = ProperTorsionHandler.ProperTorsionType(
1547
+ smirks="[*:1]-[*:2]-[*:3]-[*:4]",
1548
+ phase1=30 * unit.degree,
1549
+ periodicity1=2,
1550
+ k1_bondorder1=1 * unit.kilocalorie / unit.mole,
1551
+ k1_bondorder2=1.8 * unit.kilocalorie / unit.mole,
1552
+ idivf1=4,
1553
+ )
1554
+
1555
+ param_dict = p1.to_dict()
1556
+ assert ("k1_bondorder1", 1 * unit.kilocalorie / unit.mole) in param_dict.items()
1557
+ assert (
1558
+ "k1_bondorder2",
1559
+ 1.8 * unit.kilocalorie / unit.mole,
1560
+ ) in param_dict.items()
1561
+ assert ("phase1", 30 * unit.degree) in param_dict.items()
1562
+ assert ("periodicity1", 2) in param_dict.items()
1563
+ assert ("idivf1", 4) in param_dict.items()
1564
+
1565
+ def test_multi_term_proper_torsion_bo(self):
1566
+ """
1567
+ Test creation and serialization of a multi-term proper torsion with bond order interpolation.
1568
+ """
1569
+ p1 = ProperTorsionHandler.ProperTorsionType(
1570
+ smirks="[*:1]-[*:2]-[*:3]-[*:4]",
1571
+ phase1=30 * unit.degree,
1572
+ periodicity1=2,
1573
+ k1_bondorder1=1 * unit.kilocalorie / unit.mole,
1574
+ k1_bondorder2=1.8 * unit.kilocalorie / unit.mole,
1575
+ phase2=31 * unit.degree,
1576
+ periodicity2=3,
1577
+ k2_bondorder1=1.2 * unit.kilocalorie / unit.mole,
1578
+ k2_bondorder2=1.9 * unit.kilocalorie / unit.mole,
1579
+ )
1580
+ param_dict = p1.to_dict()
1581
+ assert param_dict["k1_bondorder1"] == 1 * unit.kilocalorie / unit.mole
1582
+ assert param_dict["k1_bondorder2"] == 1.8 * unit.kilocalorie / unit.mole
1583
+ assert param_dict["phase1"] == 30 * unit.degree
1584
+ assert param_dict["periodicity1"] == 2
1585
+ assert param_dict["k2_bondorder1"] == 1.2 * unit.kilocalorie / unit.mole
1586
+ assert param_dict["k2_bondorder2"] == 1.9 * unit.kilocalorie / unit.mole
1587
+ assert param_dict["phase2"] == 31 * unit.degree
1588
+ assert param_dict["periodicity2"] == 3
1589
+
1590
+ def test_multi_term_proper_torsion_bo_getters_setters(self):
1591
+ """
1592
+ Test getters and setters of a multi-term proper torsion with bond order interpolation.
1593
+ """
1594
+ p1 = ProperTorsionHandler.ProperTorsionType(
1595
+ smirks="[*:1]-[*:2]-[*:3]-[*:4]",
1596
+ phase1=30 * unit.degree,
1597
+ periodicity1=2,
1598
+ k1_bondorder1=1 * unit.kilocalorie / unit.mole,
1599
+ k1_bondorder2=1.8 * unit.kilocalorie / unit.mole,
1600
+ phase2=31 * unit.degree,
1601
+ periodicity2=3,
1602
+ k2_bondorder1=1.2 * unit.kilocalorie / unit.mole,
1603
+ k2_bondorder2=1.9 * unit.kilocalorie / unit.mole,
1604
+ )
1605
+
1606
+ assert p1.k1_bondorder1 == 1.0 * unit.kilocalorie / unit.mole
1607
+ p1.k1_bondorder1 = 2.0 * unit.kilocalorie / unit.mole
1608
+ assert p1.k1_bondorder1 == 2.0 * unit.kilocalorie / unit.mole
1609
+
1610
+ assert p1.k2_bondorder2 == 1.9 * unit.kilocalorie / unit.mole
1611
+ p1.k2_bondorder2 = 2.9 * unit.kilocalorie / unit.mole
1612
+ assert p1.k2_bondorder2 == 2.9 * unit.kilocalorie / unit.mole
1613
+
1614
+ def test_multi_term_proper_torsion_bo_skip_index(self):
1615
+ """
1616
+ Test creation and serialization of a multi-term proper torsion where
1617
+ the indices are not consecutive and a SMIRNOFFSpecError is raised
1618
+ AND we are doing bond order interpolation
1619
+ """
1620
+ with pytest.raises(SMIRNOFFSpecError, match=r"Unexpected kwarg \(k3_bondorder1*."):
1621
+ ProperTorsionHandler.ProperTorsionType(
1622
+ smirks="[*:1]-[*:2]-[*:3]-[*:4]",
1623
+ phase1=30 * unit.degree,
1624
+ periodicity1=2,
1625
+ k1_bondorder1=1 * unit.kilocalorie / unit.mole,
1626
+ k1_bondorder2=1.8 * unit.kilocalorie / unit.mole,
1627
+ phase3=31 * unit.degree,
1628
+ periodicity3=3,
1629
+ k3_bondorder1=1.2 * unit.kilocalorie / unit.mole,
1630
+ k3_bondorder2=1.9 * unit.kilocalorie / unit.mole,
1631
+ )
1632
+
1633
+ def test_single_term_single_bo_exception(self):
1634
+ """Test behavior where a single bond order term is specified for a single k"""
1635
+ # raises no error, as checks are handled at parameterization
1636
+ # we may add a `validate` method later that is called manually by user when they want it
1637
+ ProperTorsionHandler.ProperTorsionType(
1638
+ smirks="[*:1]-[*:2]~[*:3]-[*:4]",
1639
+ phase1=30 * unit.degree,
1640
+ periodicity1=2,
1641
+ k1_bondorder1=1 * unit.kilocalorie / unit.mole,
1642
+ )
1643
+
1644
+ def test_multi_term_single_bo_exception(self):
1645
+ """Test behavior where a single bond order term is specified for each of multiple k"""
1646
+ # TODO : currently raises no error, as checks are handled at parameterization
1647
+ # is this a spec thing that we should be checking?
1648
+ # if so, it will be painful to implement
1649
+ ProperTorsionHandler.ProperTorsionType(
1650
+ smirks="[*:1]-[*:2]-[*:3]-[*:4]",
1651
+ phase1=30 * unit.degree,
1652
+ periodicity1=2,
1653
+ k1_bondorder1=1 * unit.kilocalorie / unit.mole,
1654
+ phase2=31 * unit.degree,
1655
+ periodicity2=3,
1656
+ k2_bondorder1=1.2 * unit.kilocalorie / unit.mole,
1657
+ )
1658
+
1659
+
1660
+ class TestProperTorsionHandler:
1661
+ def test_torsion_handler_charmm_potential(self):
1662
+ """
1663
+ Test creation of TorsionHandlers with the deprecated 0.2 potential value "charmm" instead of the current
1664
+ supported potential value "fourier".
1665
+ """
1666
+ import re
1667
+
1668
+ # Test creating ProperTorsionHandlers
1669
+ err_msg = re.escape(
1670
+ "Attempted to set ProperTorsionHandler.potential to charmm. Currently, "
1671
+ "only the following values are supported: ['k*(1+cos(periodicity*theta-phase))']."
1672
+ )
1673
+ with pytest.raises(SMIRNOFFSpecError, match=err_msg):
1674
+ ProperTorsionHandler(potential="charmm", skip_version_check=True)
1675
+ ProperTorsionHandler(potential="k*(1+cos(periodicity*theta-phase))", skip_version_check=True)
1676
+
1677
+ # Same test, but with ImproperTorsionHandler
1678
+ err_msg = re.escape(
1679
+ "Attempted to set ImproperTorsionHandler.potential to charmm. Currently, "
1680
+ "only the following values are supported: ['k*(1+cos(periodicity*theta-phase))']."
1681
+ )
1682
+ with pytest.raises(SMIRNOFFSpecError, match=err_msg):
1683
+ ImproperTorsionHandler(potential="charmm", skip_version_check=True)
1684
+ ImproperTorsionHandler(potential="k*(1+cos(periodicity*theta-phase))", skip_version_check=True)
1685
+
1686
+
1687
+ class TestvdWHandler:
1688
+ def test_add_param_str(self):
1689
+ """
1690
+ Ensure that string input is supported, given the added complication that the
1691
+ sigma/rmin_half setters silently set each other's value.
1692
+ See https://github.com/openforcefield/openff-toolkit/issues/788
1693
+ """
1694
+ vdw_handler = vdWHandler(version=0.4)
1695
+ param1 = {
1696
+ "epsilon": "0.5 * kilocalorie/mole",
1697
+ "rmin_half": "1.2 * angstrom",
1698
+ "smirks": "[*:1]",
1699
+ "id": "n99",
1700
+ }
1701
+ param2 = {
1702
+ "epsilon": "0.1 * kilocalorie/mole",
1703
+ "sigma": "0.8 * angstrom",
1704
+ "smirks": "[#1:1]",
1705
+ "id": "n00",
1706
+ }
1707
+ vdw_handler.add_parameter(param1)
1708
+ vdw_handler.add_parameter(param2)
1709
+
1710
+ assert vdw_handler.get_parameter({"smirks": "[*:1]"})[0].id == "n99"
1711
+ assert vdw_handler.get_parameter({"smirks": "[#1:1]"})[0].id == "n00"
1712
+
1713
+ def test_set_invalid_scale_factor(self):
1714
+ import random
1715
+
1716
+ factors = {index: random.random() for index in (2, 3, 5)}
1717
+
1718
+ handler = vdWHandler(version=0.4)
1719
+
1720
+ for factor, value in factors.items():
1721
+ with pytest.raises(
1722
+ SMIRNOFFSpecError,
1723
+ match=f"unable to handle scale1{factor}.*1-{factor} scaling was {value}",
1724
+ ):
1725
+ setattr(handler, f"scale1{factor}", value)
1726
+
1727
+ def test_initialize_ewald3d(self):
1728
+ handler = vdWHandler(version=0.5, periodic_method="Ewald3D")
1729
+ assert handler.periodic_method == "Ewald3D"
1730
+
1731
+ def test_unsupported_method(self):
1732
+ with pytest.raises(
1733
+ SMIRNOFFSpecError,
1734
+ match=r"LJPME.*following values are supported.*(?!LJPME.)",
1735
+ ):
1736
+ vdWHandler(version=0.5, periodic_method="LJPME")
1737
+
1738
+
1739
+ class TestvdWHandlerUpConversion:
1740
+ """
1741
+ Test the implementation of OFF-EP-0008:
1742
+
1743
+ https://openforcefield.github.io/standards/enhancement-proposals/off-ep-0008/
1744
+ """
1745
+
1746
+ def test_upconversion(self):
1747
+ converted = vdWHandler(version=0.3, method="cutoff")
1748
+
1749
+ new = vdWHandler(version=0.4)
1750
+
1751
+ assert converted.version == new.version == Version("0.4")
1752
+
1753
+ # Up-conversion from default (only) value of .method in 0.3 happens
1754
+ # happens to match default values of new attributes version 0.4
1755
+ assert converted.periodic_method == new.periodic_method == "cutoff"
1756
+ assert converted.nonperiodic_method == new.nonperiodic_method == "no-cutoff"
1757
+
1758
+ try:
1759
+ assert not hasattr(converted, "method")
1760
+ except AttributeError:
1761
+ # https://github.com/openforcefield/openff-toolkit/issues/1680
1762
+ pytest.skip("ParameterAttribute.__delete__ not implemented")
1763
+
1764
+ def test_issue_1668(self):
1765
+ """Reproduce https://github.com/openforcefield/openff-toolkit/issues/1688"""
1766
+ handler1 = vdWHandler(version=0.3)
1767
+ handler2 = vdWHandler(version=0.3, method="cutoff")
1768
+
1769
+ assert handler1.version == handler2.version
1770
+ assert handler1.periodic_method == handler2.periodic_method
1771
+ assert handler1.nonperiodic_method == handler2.nonperiodic_method
1772
+
1773
+ def test_upconversion_unknown_kwarg(self):
1774
+ with pytest.raises(
1775
+ NotImplementedError,
1776
+ match=r"Did not know.*`method=\"no-cutoff",
1777
+ ):
1778
+ vdWHandler(
1779
+ version=0.3,
1780
+ method="no-cutoff",
1781
+ )
1782
+
1783
+ def test_invalid_0_4_kwargs(self):
1784
+ with pytest.raises(
1785
+ SMIRNOFFSpecError,
1786
+ match=r"removed in version 0.4 of the vdW",
1787
+ ):
1788
+ vdWHandler(version=0.4, method="cutoff")
1789
+
1790
+
1791
+ class TestvdWType:
1792
+ """
1793
+ Test the behavior of vdWType
1794
+ """
1795
+
1796
+ def test_sigma_rmin_half(self):
1797
+ """Test the setter/getter behavior or sigma and rmin_half"""
1798
+
1799
+ data = {
1800
+ "smirks": "[*:1]",
1801
+ "rmin_half": 0.5 * unit.angstrom,
1802
+ "epsilon": 0.5 * unit.kilocalorie / unit.mole,
1803
+ }
1804
+ param = vdWHandler.vdWType(**data)
1805
+
1806
+ assert param.sigma is not None
1807
+ assert param.rmin_half is not None
1808
+ assert numpy.isclose(
1809
+ param.sigma.m_as(unit.angstrom),
1810
+ (2.0 * param.rmin_half / 2 ** (1 / 6)).m_as(unit.angstrom),
1811
+ )
1812
+ assert "sigma" not in param.to_dict()
1813
+ assert "rmin_half" in param.to_dict()
1814
+
1815
+ param.sigma = param.sigma
1816
+
1817
+ assert numpy.isclose(param.rmin_half.m_as(unit.angstrom), 0.5)
1818
+ assert "sigma" in param.to_dict()
1819
+ assert "rmin_half" not in param.to_dict()
1820
+
1821
+ param.rmin_half = param.rmin_half
1822
+
1823
+ assert numpy.isclose(
1824
+ param.sigma.m_as(unit.angstrom),
1825
+ (2.0 * param.rmin_half / 2 ** (1 / 6)).m_as(unit.angstrom),
1826
+ )
1827
+ assert "sigma" not in param.to_dict()
1828
+ assert "rmin_half" in param.to_dict()
1829
+
1830
+
1831
+ class TestElectrostaticsHandler:
1832
+ def test_solvent_dielectric(self):
1833
+ with pytest.raises(
1834
+ SMIRNOFFSpecUnimplementedError,
1835
+ match="make use of `solvent_d",
1836
+ ):
1837
+ ElectrostaticsHandler(version=0.3, method="PME", solvent_dielectric=4)
1838
+
1839
+ handler = ElectrostaticsHandler(version=0.4)
1840
+ assert handler.solvent_dielectric is None
1841
+
1842
+ handler.solvent_dielectric = None
1843
+
1844
+ with pytest.raises(
1845
+ SMIRNOFFSpecUnimplementedError,
1846
+ match="make use of `solvent_d",
1847
+ ):
1848
+ handler.solvent_dielectric = 78.3
1849
+
1850
+ def test_unknown_periodic_potential(self):
1851
+ handler = ElectrostaticsHandler(version=0.4)
1852
+
1853
+ with pytest.raises(
1854
+ NotImplementedError,
1855
+ match="unexpected periodic potential",
1856
+ ):
1857
+ handler.periodic_potential = "PPPM"
1858
+
1859
+ def test_set_invalid_scale_factor(self):
1860
+ handler = ElectrostaticsHandler(version=0.4)
1861
+
1862
+ with pytest.raises(SMIRNOFFSpecError, match="unable to handle scale12"):
1863
+ handler.scale12 = 0.1
1864
+
1865
+ with pytest.raises(SMIRNOFFSpecError, match="unable to handle scale13"):
1866
+ handler.scale13 = 0.1
1867
+
1868
+ with pytest.raises(SMIRNOFFSpecError, match="unable to handle scale15"):
1869
+ handler.scale15 = 0.1
1870
+
1871
+
1872
+ class TestElectrostaticsHandlerUpconversion:
1873
+ """
1874
+ Test the implementation of OFF-EP-0005:
1875
+
1876
+ https://openforcefield.github.io/standards/enhancement-proposals/off-ep-0005/
1877
+ """
1878
+
1879
+ default_reaction_field_expression = (
1880
+ "charge1*charge2/(4*pi*epsilon0)*(1/r + k_rf*r^2 - c_rf);"
1881
+ "k_rf=(cutoff^(-3))*(solvent_dielectric-1)/(2*solvent_dielectric+1);"
1882
+ "c_rf=cutoff^(-1)*(3*solvent_dielectric)/(2*solvent_dielectric+1)"
1883
+ )
1884
+
1885
+ @pytest.mark.parametrize(
1886
+ ("old_method", "new_method"),
1887
+ [
1888
+ ("PME", "Ewald3D-ConductingBoundary"),
1889
+ ("Coulomb", "Coulomb"),
1890
+ ("reaction-field", default_reaction_field_expression),
1891
+ ],
1892
+ )
1893
+ def test_upconversion(self, old_method, new_method):
1894
+ handler = ElectrostaticsHandler(version=0.3, method=old_method)
1895
+ assert handler.version == Version("0.4")
1896
+
1897
+ # Only `periodic_potential` is a function of the values in a version 0.3 handler ...
1898
+ assert handler.periodic_potential == new_method
1899
+
1900
+ # ... for everything else, it's the same
1901
+ assert handler.nonperiodic_potential == "Coulomb"
1902
+ assert handler.exception_potential == "Coulomb"
1903
+
1904
+ def test_invalid_0_4_kwargs(self):
1905
+ with pytest.raises(SMIRNOFFSpecError, match=r"removed in version 0.4 of the E"):
1906
+ ElectrostaticsHandler(version=0.4, method="PME")
1907
+
1908
+
1909
+ class TestVirtualSiteHandler:
1910
+ """
1911
+ Test the creation of a VirtualSiteHandler and the implemented VirtualSiteTypes
1912
+ """
1913
+
1914
+ def test_int_getitem_okay(self, opc):
1915
+ """Test that ints can be used to lookup virtual site types."""
1916
+ parameter = opc["VirtualSites"].parameters[0]
1917
+
1918
+ assert isinstance(parameter, VirtualSiteHandler.VirtualSiteType)
1919
+ assert parameter.epsilon.m == 0.0
1920
+ assert parameter.type == "DivalentLonePair"
1921
+
1922
+ assert opc["VirtualSites"][0] == parameter
1923
+
1924
+ def test_slice(self, opc):
1925
+ assert len(opc["VirtualSites"].parameters[0:1:2]) == 1
1926
+
1927
+ with pytest.raises(
1928
+ AssertionError,
1929
+ match="must be based on int",
1930
+ ):
1931
+ opc["VirtualSites"].parameters["first":"second"]
1932
+
1933
+ def test_smirks_getitem_forbidden(self, opc):
1934
+ """Test that SMIRKS/ParameterType can NOT be used to lookup virtual site types."""
1935
+ smirks = next(iter(opc["VirtualSites"]._parameters)).smirks
1936
+
1937
+ with pytest.raises(
1938
+ NotImplementedError,
1939
+ match="uniquely identify",
1940
+ ):
1941
+ opc["VirtualSites"][smirks]
1942
+
1943
+ with pytest.raises(
1944
+ NotImplementedError,
1945
+ match="uniquely identify",
1946
+ ):
1947
+ opc["VirtualSites"].parameters[smirks]
1948
+
1949
+ @pytest.mark.parametrize(
1950
+ "parameter, expected_index",
1951
+ [
1952
+ (VirtualSiteMocking.bond_charge_parameter("[*:1][*:2]"), 0),
1953
+ (VirtualSiteMocking.monovalent_parameter("[*:1][*:2][*:3]"), 0),
1954
+ (VirtualSiteMocking.divalent_parameter("[*:2][*:1][*:3]", "once"), 0),
1955
+ (VirtualSiteMocking.trivalent_parameter("[*:1][*:2][*:3][*:4]"), 0),
1956
+ ],
1957
+ )
1958
+ def test_parent_index(self, parameter, expected_index):
1959
+ assert parameter.parent_index == expected_index
1960
+ assert VirtualSiteHandler.VirtualSiteType.type_to_parent_index(parameter.type) == expected_index
1961
+
1962
+ @pytest.mark.parametrize(
1963
+ "kwargs, expected_raises",
1964
+ [
1965
+ (
1966
+ VirtualSiteMocking.bond_charge_parameter("[*:1][*:2]").to_dict(),
1967
+ does_not_raise(),
1968
+ ),
1969
+ (
1970
+ VirtualSiteMocking.monovalent_parameter("[*:1][*:2][*:3]").to_dict(),
1971
+ does_not_raise(),
1972
+ ),
1973
+ (
1974
+ VirtualSiteMocking.divalent_parameter(
1975
+ "[*:1][*:2][*:3]", match="once", angle=0.0 * unit.degrees
1976
+ ).to_dict(),
1977
+ does_not_raise(),
1978
+ ),
1979
+ (
1980
+ VirtualSiteMocking.divalent_parameter(
1981
+ "[*:1][*:2][*:3]",
1982
+ match="all_permutations",
1983
+ angle=2.0 * unit.degrees,
1984
+ ).to_dict(),
1985
+ does_not_raise(),
1986
+ ),
1987
+ (
1988
+ VirtualSiteMocking.trivalent_parameter("[*:1][*:2][*:3][*:4]").to_dict(),
1989
+ does_not_raise(),
1990
+ ),
1991
+ # Validate `type`
1992
+ (
1993
+ {},
1994
+ pytest.raises(SMIRNOFFSpecError, match="the `type` keyword is missing"),
1995
+ ),
1996
+ (
1997
+ {"type": "InvalidType"},
1998
+ pytest.raises(
1999
+ SMIRNOFFSpecError,
2000
+ match="'InvalidType' is not a supported virtual site type",
2001
+ ),
2002
+ ),
2003
+ # Validate `match`
2004
+ (
2005
+ {"type": "BondCharge"},
2006
+ pytest.raises(SMIRNOFFSpecError, match="the `match` keyword is missing"),
2007
+ ),
2008
+ (
2009
+ {"type": "BondCharge", "match": "once"},
2010
+ pytest.raises(
2011
+ SMIRNOFFSpecError,
2012
+ match="match='once' not supported with type='BondCharge'",
2013
+ ),
2014
+ ),
2015
+ (
2016
+ {"type": "BondCharge", "match": "once"},
2017
+ pytest.raises(
2018
+ SMIRNOFFSpecError,
2019
+ match="match='once' not supported with type='BondCharge'",
2020
+ ),
2021
+ ),
2022
+ (
2023
+ {"type": "MonovalentLonePair", "match": "once"},
2024
+ pytest.raises(
2025
+ SMIRNOFFSpecError,
2026
+ match="match='once' not supported with type='MonovalentLonePair'",
2027
+ ),
2028
+ ),
2029
+ (
2030
+ {
2031
+ "type": "DivalentLonePair",
2032
+ "match": "once",
2033
+ "outOfPlaneAngle": 2.0 * unit.degrees,
2034
+ },
2035
+ pytest.raises(
2036
+ SMIRNOFFSpecError,
2037
+ match="match='once' not supported with type='DivalentLonePair' and is_in_plane=False",
2038
+ ),
2039
+ ),
2040
+ (
2041
+ {"type": "TrivalentLonePair", "match": "all_permutations"},
2042
+ pytest.raises(
2043
+ SMIRNOFFSpecError,
2044
+ match="match='all_permutations' not supported with type='TrivalentLonePair'",
2045
+ ),
2046
+ ),
2047
+ ],
2048
+ )
2049
+ def test_add_default_init_kwargs_validation(self, kwargs, expected_raises):
2050
+ with expected_raises:
2051
+ VirtualSiteHandler.VirtualSiteType._add_default_init_kwargs(kwargs)
2052
+
2053
+ @pytest.mark.parametrize(
2054
+ "kwargs, expected_kwargs",
2055
+ [
2056
+ (
2057
+ {
2058
+ "type": "BondCharge",
2059
+ "match": "all_permutations",
2060
+ },
2061
+ {
2062
+ "type": "BondCharge",
2063
+ "match": "all_permutations",
2064
+ "outOfPlaneAngle": None,
2065
+ "inPlaneAngle": None,
2066
+ },
2067
+ ),
2068
+ ],
2069
+ )
2070
+ def test_add_default_init_kwargs_values(self, kwargs, expected_kwargs):
2071
+ assert kwargs != expected_kwargs
2072
+ VirtualSiteHandler.VirtualSiteType._add_default_init_kwargs(kwargs)
2073
+ assert kwargs == expected_kwargs
2074
+
2075
+ def test_vdw_defaults(self):
2076
+ """Test initializing without vdW parameters specified."""
2077
+ defaults = VirtualSiteHandler.VirtualSiteType(
2078
+ type="BondCharge",
2079
+ smirks="",
2080
+ match="all_permutations",
2081
+ distance=0.0 * unit.angstrom,
2082
+ charge_increment=2 * [0.0 * unit.elementary_charge],
2083
+ )
2084
+
2085
+ assert defaults.rmin_half == 0.0 * unit.angstrom
2086
+ assert defaults.sigma == 0.0 * unit.angstrom
2087
+ assert defaults.epsilon == 0.0 * unit.kilojoule_per_mole
2088
+
2089
+ @pytest.mark.parametrize(
2090
+ "parameter, in_plane_angle, expected_raises",
2091
+ [
2092
+ (
2093
+ VirtualSiteMocking.bond_charge_parameter("[*:1][*:2]"),
2094
+ 0.0 * unit.degrees,
2095
+ pytest.raises(
2096
+ SMIRNOFFSpecError,
2097
+ match="'BondCharge' sites do not support `inPlaneAngle`",
2098
+ ),
2099
+ ),
2100
+ (
2101
+ VirtualSiteMocking.bond_charge_parameter("[*:1][*:2]"),
2102
+ None,
2103
+ does_not_raise(),
2104
+ ),
2105
+ (
2106
+ VirtualSiteMocking.monovalent_parameter("[*:1][*:2][*:3]"),
2107
+ 1.0 * unit.angstrom,
2108
+ pytest.raises(IncompatibleUnitError),
2109
+ ),
2110
+ (
2111
+ VirtualSiteMocking.monovalent_parameter("[*:1][*:2][*:3]"),
2112
+ 130.0 * unit.degrees,
2113
+ does_not_raise(),
2114
+ ),
2115
+ ],
2116
+ )
2117
+ def test_in_plane_angle_converter(self, parameter, in_plane_angle, expected_raises):
2118
+ parameter_dict = parameter.to_dict()
2119
+ parameter_dict["inPlaneAngle"] = in_plane_angle
2120
+
2121
+ with expected_raises:
2122
+ new_parameter = VirtualSiteHandler.VirtualSiteType(**parameter_dict)
2123
+ assert new_parameter.inPlaneAngle == in_plane_angle
2124
+
2125
+ @pytest.mark.parametrize(
2126
+ "parameter, out_of_plane_angle, expected_raises",
2127
+ [
2128
+ (
2129
+ VirtualSiteMocking.bond_charge_parameter("[*:1][*:2]"),
2130
+ 0.0 * unit.degrees,
2131
+ pytest.raises(
2132
+ SMIRNOFFSpecError,
2133
+ match="'BondCharge' sites do not support `outOfPlaneAngle`",
2134
+ ),
2135
+ ),
2136
+ (
2137
+ VirtualSiteMocking.bond_charge_parameter("[*:1][*:2]"),
2138
+ None,
2139
+ does_not_raise(),
2140
+ ),
2141
+ (
2142
+ VirtualSiteMocking.monovalent_parameter("[*:1][*:2][*:3]"),
2143
+ 130.0 * unit.degrees,
2144
+ does_not_raise(),
2145
+ ),
2146
+ ],
2147
+ )
2148
+ def test_out_of_plane_angle_converter(self, parameter, out_of_plane_angle, expected_raises):
2149
+ parameter_dict = parameter.to_dict()
2150
+ parameter_dict["outOfPlaneAngle"] = out_of_plane_angle
2151
+
2152
+ with expected_raises:
2153
+ new_parameter = VirtualSiteHandler.VirtualSiteType(**parameter_dict)
2154
+ assert new_parameter.outOfPlaneAngle == out_of_plane_angle
2155
+
2156
+ def test_serialize_roundtrip(self):
2157
+ force_field = ForceField()
2158
+
2159
+ handler = force_field.get_parameter_handler("VirtualSites")
2160
+ handler.add_parameter(parameter=VirtualSiteMocking.bond_charge_parameter("[*:1][*:2]"))
2161
+ handler.add_parameter(parameter=VirtualSiteMocking.monovalent_parameter("[*:1][*:2][*:3]"))
2162
+ handler.add_parameter(parameter=VirtualSiteMocking.divalent_parameter("[*:2][*:1][*:3]", "once"))
2163
+ handler.add_parameter(parameter=VirtualSiteMocking.trivalent_parameter("[*:1][*:2][*:3][*:4]"))
2164
+ offxml_string = force_field.to_string()
2165
+ roundtripped_force_field = ForceField(offxml_string)
2166
+ assert offxml_string == roundtripped_force_field.to_string()
2167
+
2168
+ @pytest.mark.parametrize(
2169
+ "smiles, matched_indices, parameter, expected_raises, unsafe_vsites",
2170
+ [
2171
+ (
2172
+ "[Cl:1][H:2]",
2173
+ (1, 2),
2174
+ VirtualSiteMocking.bond_charge_parameter("[Cl:1][H:2]"),
2175
+ does_not_raise(),
2176
+ False,
2177
+ ),
2178
+ (
2179
+ "[N:1]([H:2])([H:3])[H:4]",
2180
+ (1, 2, 3),
2181
+ VirtualSiteMocking.monovalent_parameter("[*:2][N:1][*:3]"),
2182
+ pytest.raises(NotImplementedError, match="currently unsupported by virtual sites"),
2183
+ False,
2184
+ ),
2185
+ (
2186
+ "[N:1]([H:2])([H:3])[H:4]",
2187
+ (1, 2, 3),
2188
+ VirtualSiteMocking.monovalent_parameter("[*:2][N:1][*:3]"),
2189
+ does_not_raise(),
2190
+ True,
2191
+ ),
2192
+ ],
2193
+ )
2194
+ def test_validate_found_match(
2195
+ self,
2196
+ monkeypatch,
2197
+ smiles,
2198
+ matched_indices,
2199
+ parameter,
2200
+ expected_raises,
2201
+ unsafe_vsites,
2202
+ ):
2203
+ if unsafe_vsites:
2204
+ monkeypatch.setenv("OPENFF_UNSAFE_VSITES", "1")
2205
+ molecule = Molecule.from_smiles(smiles, allow_undefined_stereo=True)
2206
+ topology: Topology = molecule.to_topology()
2207
+
2208
+ atoms = {i: atom for i, atom in enumerate(topology.atoms)}
2209
+
2210
+ with expected_raises:
2211
+ VirtualSiteHandler._validate_found_match(atoms, matched_indices, parameter)
2212
+
2213
+ @pytest.mark.parametrize(
2214
+ "handler_a, handler_b, expected_raises",
2215
+ [
2216
+ # Currently, no other test cases as only one `exclusion_policy` is supported
2217
+ (
2218
+ VirtualSiteHandler(version="0.3"),
2219
+ VirtualSiteHandler(version="0.3"),
2220
+ does_not_raise(),
2221
+ )
2222
+ ],
2223
+ )
2224
+ def test_check_handler_compatability(self, handler_a, handler_b, expected_raises):
2225
+ with expected_raises:
2226
+ handler_a.check_handler_compatibility(handler_b)
2227
+
2228
+ @pytest.mark.parametrize(
2229
+ "parameters, smiles, expected_matches",
2230
+ [
2231
+ # Check that a basic BondCharge virtual site can be applied
2232
+ (
2233
+ [VirtualSiteMocking.bond_charge_parameter("[Cl:1]-[C:2]")],
2234
+ "[Cl:2][C:1]([H:3])([H:4])[H:5]",
2235
+ {(1, 0): {("[Cl:1]-[C:2]", "EP")}},
2236
+ ),
2237
+ # Check that two bond charge vsites with different names can be applied
2238
+ # to the same atoms
2239
+ (
2240
+ [
2241
+ VirtualSiteMocking.bond_charge_parameter("[Cl:1]-[C:2]", name="EP"),
2242
+ VirtualSiteMocking.bond_charge_parameter("[Cl:1]-[C:2]", name="LP"),
2243
+ ],
2244
+ "[Cl:1][C:2]([H:3])([H:4])[H:5]",
2245
+ {(0, 1): {("[Cl:1]-[C:2]", "EP"), ("[Cl:1]-[C:2]", "LP")}},
2246
+ ),
2247
+ # Check that a bond charge vsite can be applied to a symmetric moiety
2248
+ (
2249
+ [VirtualSiteMocking.bond_charge_parameter("[C:1]#[C:2]")],
2250
+ "[H:1][C:2]#[C:3][Cl:4]",
2251
+ {(1, 2): {("[C:1]#[C:2]", "EP")}, (2, 1): {("[C:1]#[C:2]", "EP")}},
2252
+ ),
2253
+ # Check that a monovalent lone pair vsite can be applied to a relatively symmetric moiety
2254
+ (
2255
+ [VirtualSiteMocking.monovalent_parameter("[O:1]=[C:2]-[*:3]")],
2256
+ "[O:2]=[C:1]([H:3])[Cl:4]",
2257
+ {
2258
+ (1, 0, 2): {("[O:1]=[C:2]-[*:3]", "EP")},
2259
+ (1, 0, 3): {("[O:1]=[C:2]-[*:3]", "EP")},
2260
+ },
2261
+ ),
2262
+ # Check that monovalent lone pair vsites override correctly
2263
+ (
2264
+ [
2265
+ VirtualSiteMocking.monovalent_parameter("[O:1]=[C:2]-[*:3]"),
2266
+ VirtualSiteMocking.monovalent_parameter("[O:1]=[C:2]-[Cl:3]"),
2267
+ ],
2268
+ "[O:2]=[C:1]([H:3])[Cl:4]",
2269
+ {(1, 0, 3): {("[O:1]=[C:2]-[Cl:3]", "EP")}},
2270
+ ),
2271
+ # Check that a single-particle in-plane divalent lone pair vsite
2272
+ # can be applied
2273
+ (
2274
+ [VirtualSiteMocking.divalent_parameter("[H:2][O:1][H:3]", match="once", angle=0.0 * unit.degree)],
2275
+ "[H:1][O:2][H:3]",
2276
+ {(1, 0, 2): {("[H:2][O:1][H:3]", "EP")}},
2277
+ ),
2278
+ # Check that a two-particle out-of-plane divalent lone pair vsite can be applied
2279
+ (
2280
+ [
2281
+ VirtualSiteMocking.divalent_parameter(
2282
+ "[H:2][O:1][H:3]",
2283
+ match="all_permutations",
2284
+ angle=30.0 * unit.degree,
2285
+ )
2286
+ ],
2287
+ "[H:1][O:2][H:3]",
2288
+ {
2289
+ (1, 0, 2): {("[H:2][O:1][H:3]", "EP")},
2290
+ (1, 2, 0): {("[H:2][O:1][H:3]", "EP")},
2291
+ },
2292
+ ),
2293
+ # Check that a single-particle in-plane divalent lone pair site can
2294
+ # be applied to a symmetric molecule
2295
+ (
2296
+ [VirtualSiteMocking.divalent_parameter("[*:2]-[N:1]~[*:3]", match="once", angle=0.0 * unit.degree)],
2297
+ "[H:1][N:2]=[N:3][H:4]",
2298
+ {
2299
+ (1, 0, 2): {("[*:2]-[N:1]~[*:3]", "EP")},
2300
+ (2, 3, 1): {("[*:2]-[N:1]~[*:3]", "EP")},
2301
+ },
2302
+ ),
2303
+ # Check that a two-particle out-of-plane divalent lone pair vsite
2304
+ # can be applied to a symmetric molecule
2305
+ (
2306
+ [
2307
+ VirtualSiteMocking.divalent_parameter(
2308
+ "[*:2]~[N:1]~[*:3]",
2309
+ match="all_permutations",
2310
+ angle=30.0 * unit.degree,
2311
+ )
2312
+ ],
2313
+ "[H:1][N:2]=[N:3][H:4]",
2314
+ {
2315
+ (1, 0, 2): {("[*:2]~[N:1]~[*:3]", "EP")},
2316
+ (1, 2, 0): {("[*:2]~[N:1]~[*:3]", "EP")},
2317
+ (2, 1, 3): {("[*:2]~[N:1]~[*:3]", "EP")},
2318
+ (2, 3, 1): {("[*:2]~[N:1]~[*:3]", "EP")},
2319
+ },
2320
+ ),
2321
+ # Check that a trivalent lone pair vsite can be applied to a simple molecule
2322
+ (
2323
+ [VirtualSiteMocking.trivalent_parameter("[N:1]([H:2])([H:3])[H:4]")],
2324
+ "[N:2]([H:1])([H:3])[H:4]",
2325
+ {(1, 0, 2, 3): {("[N:1]([H:2])([H:3])[H:4]", "EP")}},
2326
+ ),
2327
+ ],
2328
+ )
2329
+ def test_find_matches(
2330
+ self,
2331
+ parameters: list[VirtualSiteHandler.VirtualSiteType],
2332
+ smiles: str,
2333
+ expected_matches: dict[tuple[int, ...], list[tuple[str, str]]],
2334
+ ):
2335
+ molecule = Molecule.from_mapped_smiles(smiles, allow_undefined_stereo=True)
2336
+
2337
+ handler = VirtualSiteHandler(version="0.3")
2338
+
2339
+ for parameter in parameters:
2340
+ handler.add_parameter(parameter=parameter)
2341
+
2342
+ matches = handler.find_matches(molecule.to_topology(), unique=False)
2343
+
2344
+ matched_smirks = defaultdict(set)
2345
+
2346
+ for match_list in matches.values():
2347
+ for match in match_list:
2348
+ matched_smirks[match.environment_match.topology_atom_indices].add(
2349
+ (match.parameter_type.smirks, match.parameter_type.name)
2350
+ )
2351
+
2352
+ assert {**matched_smirks} == expected_matches
2353
+
2354
+ def test_find_matches_multiple_molecules(self):
2355
+ topology = Topology.from_molecules(
2356
+ [
2357
+ Molecule.from_mapped_smiles("[Cl:2][C:1]([H:3])([H:4])[H:5]"),
2358
+ Molecule.from_mapped_smiles("[O:2]=[C:1]([H:3])[F:4]"),
2359
+ ]
2360
+ )
2361
+
2362
+ handler = VirtualSiteHandler(version="0.3")
2363
+
2364
+ handler.add_parameter(parameter=VirtualSiteMocking.bond_charge_parameter("[Cl:1]-[C:2]"))
2365
+ handler.add_parameter(parameter=VirtualSiteMocking.monovalent_parameter("[O:1]=[C:2]-[*:3]"))
2366
+
2367
+ matches = handler.find_matches(topology, unique=False)
2368
+
2369
+ matched_smirks = defaultdict(set)
2370
+
2371
+ for match_key in matches:
2372
+ match_list: list = matches[match_key]
2373
+
2374
+ for match in match_list:
2375
+ matched_smirks[match.environment_match.topology_atom_indices].add(
2376
+ (match.parameter_type.smirks, match.parameter_type.name)
2377
+ )
2378
+
2379
+ expected_matches = {
2380
+ (1, 0): {("[Cl:1]-[C:2]", "EP")},
2381
+ (6, 5, 7): {("[O:1]=[C:2]-[*:3]", "EP")},
2382
+ (6, 5, 8): {("[O:1]=[C:2]-[*:3]", "EP")},
2383
+ }
2384
+ assert {**matched_smirks} == expected_matches
2385
+
2386
+ @pytest.mark.parametrize(
2387
+ "query_parameter, query_key, expected_index",
2388
+ [
2389
+ (
2390
+ VirtualSiteMocking.monovalent_parameter("[*:1][*:2][*:3]", name="LP"),
2391
+ None,
2392
+ 2,
2393
+ ),
2394
+ (None, ("BondCharge", "[*:1][*:2]", "EP"), 3),
2395
+ (None, ("BondCharge", "[*:1][*:2]", "LP"), 1),
2396
+ (None, ("MonovalentLonePair", "[*:1][*:2][*:3]", "EP"), 0),
2397
+ (None, ("MonovalentLonePair", "[*:1][*:2][*:3]", "LP"), 2),
2398
+ (None, ("DivalentLonePair", "[*:1][*:2][*:3]", "LP"), None),
2399
+ ],
2400
+ )
2401
+ def test_index_of_parameter(self, query_parameter, query_key, expected_index):
2402
+ handler = VirtualSiteHandler(version="0.3")
2403
+
2404
+ for parameter in [
2405
+ VirtualSiteMocking.monovalent_parameter("[*:1][*:2][*:3]", name="EP"),
2406
+ VirtualSiteMocking.bond_charge_parameter("[*:1][*:2]", name="LP"),
2407
+ VirtualSiteMocking.monovalent_parameter("[*:1][*:2][*:3]", name="LP"),
2408
+ VirtualSiteMocking.bond_charge_parameter("[*:1][*:2]", name="EP"),
2409
+ ]:
2410
+ handler.add_parameter(parameter=parameter)
2411
+
2412
+ assert handler._index_of_parameter(query_parameter, query_key) == expected_index
2413
+
2414
+ def test_invalid_num_charge_increments(self):
2415
+ with pytest.raises(
2416
+ SMIRNOFFSpecError,
2417
+ match="'BondCharge' virtual sites expect exactly 2 charge increments,",
2418
+ ):
2419
+ VirtualSiteHandler.VirtualSiteType(
2420
+ type="BondCharge",
2421
+ smirks="[*]-[*]",
2422
+ name="EP",
2423
+ charge_increment=[0.1, 0.2, 0.3] * unit.elementary_charge,
2424
+ match="all_permutations",
2425
+ distance=2.0 * unit.angstrom,
2426
+ )
2427
+
2428
+ def test_deduplicate_symmetric_matches_in_noncapturing_atoms(self):
2429
+ """
2430
+ Make sure we don't double-assign vsites based on symmetries in non-tagged atoms in the SMIRKS.
2431
+ See https://github.com/openforcefield/openff-toolkit/issues/1739
2432
+ """
2433
+ vsite_handler = VirtualSiteHandler(skip_version_check=True)
2434
+ vsite_handler.add_parameter(
2435
+ parameter_kwargs={
2436
+ "smirks": "[H][#6:2]([H])=[#8:1]",
2437
+ "name": "EP",
2438
+ "type": "BondCharge",
2439
+ "distance": Quantity(7.0, "angstrom"),
2440
+ "match": "all_permutations",
2441
+ "charge_increment1": Quantity(0.2, "elementary_charge"),
2442
+ "charge_increment2": Quantity(0.1, "elementary_charge"),
2443
+ "sigma": Quantity(1.0, "angstrom"),
2444
+ "epsilon": Quantity(2.0, "kilocalorie_per_mole"),
2445
+ }
2446
+ )
2447
+ molecule = Molecule.from_mapped_smiles("[H:3][C:2]([H:4])=[O:1]")
2448
+ matches = vsite_handler.find_matches(molecule.to_topology())
2449
+ assert len(matches) == 1
2450
+
2451
+
2452
+ class TestLibraryChargeHandler:
2453
+ def test_create_library_charge_handler(self):
2454
+ """Test creation of an empty LibraryChargeHandler"""
2455
+ LibraryChargeHandler(skip_version_check=True)
2456
+
2457
+ def test_library_charge_type_wrong_num_charges(self):
2458
+ """Ensure that an error is raised if a LibraryChargeType is initialized with a different number of
2459
+ tagged atoms and charges"""
2460
+ LibraryChargeHandler.LibraryChargeType(
2461
+ smirks="[#6:1]-[#7:2]",
2462
+ charge1=0.1 * unit.elementary_charge,
2463
+ charge2=-0.1 * unit.elementary_charge,
2464
+ )
2465
+
2466
+ LibraryChargeHandler.LibraryChargeType(
2467
+ smirks="[#6:1]-[#7:2]-[#6]",
2468
+ charge1=0.1 * unit.elementary_charge,
2469
+ charge2=-0.1 * unit.elementary_charge,
2470
+ )
2471
+
2472
+ with pytest.raises(
2473
+ SMIRNOFFSpecError,
2474
+ match="initialized with unequal number of tagged atoms and charges",
2475
+ ):
2476
+ LibraryChargeHandler.LibraryChargeType(
2477
+ smirks="[#6:1]-[#7:2]",
2478
+ charge1=0.05 * unit.elementary_charge,
2479
+ charge2=0.05 * unit.elementary_charge,
2480
+ charge3=-0.1 * unit.elementary_charge,
2481
+ )
2482
+
2483
+ with pytest.raises(
2484
+ SMIRNOFFSpecError,
2485
+ match="initialized with unequal number of tagged atoms and charges",
2486
+ ):
2487
+ LibraryChargeHandler.LibraryChargeType(
2488
+ smirks="[#6:1]-[#7:2]-[#6]",
2489
+ charge1=0.05 * unit.elementary_charge,
2490
+ charge2=0.05 * unit.elementary_charge,
2491
+ charge3=-0.1 * unit.elementary_charge,
2492
+ )
2493
+
2494
+ with pytest.raises(
2495
+ SMIRNOFFSpecError,
2496
+ match="initialized with unequal number of tagged atoms and charges",
2497
+ ):
2498
+ LibraryChargeHandler.LibraryChargeType(smirks="[#6:1]-[#7:2]-[#6]", charge1=0.05 * unit.elementary_charge)
2499
+
2500
+ def test_library_charge_type_from_molecule(self):
2501
+ mol = Molecule.from_smiles("CCO")
2502
+
2503
+ with pytest.raises(ValueError, match="missing partial"):
2504
+ LibraryChargeHandler.LibraryChargeType.from_molecule(mol)
2505
+
2506
+ mol.partial_charges = numpy.linspace(-0.4, 0.4, 9) * unit.elementary_charge
2507
+
2508
+ library_charges = LibraryChargeHandler.LibraryChargeType.from_molecule(mol)
2509
+
2510
+ assert isinstance(library_charges, LibraryChargeHandler.LibraryChargeType)
2511
+ assert library_charges.smirks == mol.to_smiles(mapped=True)
2512
+ assert library_charges.charge == [*mol.partial_charges]
2513
+
2514
+
2515
+ class TestChargeIncrementModelHandler:
2516
+ def test_create_charge_increment_model_handler(self):
2517
+ """Test creation of ChargeIncrementModelHandlers"""
2518
+ handler = ChargeIncrementModelHandler(skip_version_check=True)
2519
+ assert handler.number_of_conformers == 1
2520
+ assert handler.partial_charge_method == "AM1-Mulliken"
2521
+ handler = ChargeIncrementModelHandler(skip_version_check=True, number_of_conformers=10)
2522
+ handler = ChargeIncrementModelHandler(skip_version_check=True, number_of_conformers=1)
2523
+ handler = ChargeIncrementModelHandler(skip_version_check=True, number_of_conformers="10")
2524
+ handler = ChargeIncrementModelHandler(skip_version_check=True, number_of_conformers=0)
2525
+ handler = ChargeIncrementModelHandler(skip_version_check=True, number_of_conformers="0")
2526
+ with pytest.raises(TypeError):
2527
+ handler = ChargeIncrementModelHandler(skip_version_check=True, number_of_conformers=None)
2528
+ with pytest.raises(SMIRNOFFSpecError):
2529
+ handler = ChargeIncrementModelHandler(skip_version_check=True, n_conformers=[10])
2530
+ handler = ChargeIncrementModelHandler(skip_version_check=True, partial_charge_method="AM1-Mulliken")
2531
+ handler = ChargeIncrementModelHandler(skip_version_check=True, partial_charge_method="Gasteiger")
2532
+ handler = ChargeIncrementModelHandler(skip_version_check=True, partial_charge_method=None)
2533
+
2534
+ def test_charge_increment_model_handler_getters_setters(self):
2535
+ """Test ChargeIncrementModelHandler getters and setters"""
2536
+ handler = ChargeIncrementModelHandler(skip_version_check=True)
2537
+ assert handler.number_of_conformers == 1
2538
+ assert handler.partial_charge_method == "AM1-Mulliken"
2539
+ handler.number_of_conformers = 2
2540
+ assert handler.number_of_conformers == 2
2541
+ handler.number_of_conformers = "3"
2542
+ assert handler.number_of_conformers == 3
2543
+ with pytest.raises(ValueError):
2544
+ handler.number_of_conformers = "string that can't be cast to int"
2545
+
2546
+ def test_charge_increment_model_handlers_are_compatible(self):
2547
+ """Test creation of ChargeIncrementModelHandlers"""
2548
+ handler1 = ChargeIncrementModelHandler(skip_version_check=True)
2549
+ handler2 = ChargeIncrementModelHandler(skip_version_check=True)
2550
+ handler1.check_handler_compatibility(handler2)
2551
+
2552
+ handler3 = ChargeIncrementModelHandler(skip_version_check=True, number_of_conformers="9")
2553
+ with pytest.raises(IncompatibleParameterError):
2554
+ handler1.check_handler_compatibility(handler3)
2555
+
2556
+ def test_charge_increment_type_wrong_num_increments(self):
2557
+ """Ensure that an error is raised if a ChargeIncrementType is initialized with a different number of
2558
+ tagged atoms and chargeincrements"""
2559
+ ChargeIncrementModelHandler.ChargeIncrementType(
2560
+ smirks="[#6:1]-[#7:2]",
2561
+ charge_increment1=0.1 * unit.elementary_charge,
2562
+ charge_increment2=-0.1 * unit.elementary_charge,
2563
+ )
2564
+
2565
+ ChargeIncrementModelHandler.ChargeIncrementType(
2566
+ smirks="[#6:1]-[#7:2]-[#6]",
2567
+ charge_increment1=0.1 * unit.elementary_charge,
2568
+ charge_increment2=-0.1 * unit.elementary_charge,
2569
+ )
2570
+
2571
+ with pytest.raises(
2572
+ SMIRNOFFSpecError,
2573
+ match="an invalid combination of tagged atoms and charge increments",
2574
+ ):
2575
+ ChargeIncrementModelHandler.ChargeIncrementType(
2576
+ smirks="[#6:1]-[#7:2]",
2577
+ charge_increment1=0.05 * unit.elementary_charge,
2578
+ charge_increment2=0.05 * unit.elementary_charge,
2579
+ charge_increment3=-0.1 * unit.elementary_charge,
2580
+ )
2581
+
2582
+ with pytest.raises(
2583
+ SMIRNOFFSpecError,
2584
+ match="an invalid combination of tagged atoms and charge increments",
2585
+ ):
2586
+ ChargeIncrementModelHandler.ChargeIncrementType(
2587
+ smirks="[#6:1]-[#7:2]-[#6]",
2588
+ charge_increment1=0.05 * unit.elementary_charge,
2589
+ charge_increment2=0.05 * unit.elementary_charge,
2590
+ charge_increment3=-0.1 * unit.elementary_charge,
2591
+ )
2592
+
2593
+ ChargeIncrementModelHandler.ChargeIncrementType(
2594
+ smirks="[#6:1]-[#7:2]-[#6]",
2595
+ charge_increment1=0.05 * unit.elementary_charge,
2596
+ )
2597
+
2598
+ def test_charge_increment_one_ci_missing(self):
2599
+ """Test creating a chargeincrement parameter with a missing value"""
2600
+ ChargeIncrementModelHandler.ChargeIncrementType(
2601
+ smirks="[*:1]-[*:2]",
2602
+ charge_increment=[0.1 * unit.elementary_charge],
2603
+ )
2604
+
2605
+ ChargeIncrementModelHandler.ChargeIncrementType(
2606
+ smirks="[*:1]-[*:2]",
2607
+ charge_increment=[
2608
+ 0.1 * unit.elementary_charge,
2609
+ -0.1 * unit.elementary_charge,
2610
+ ],
2611
+ )
2612
+
2613
+
2614
+ class TestNAGLChargesHandler:
2615
+ def test_nagl_charges_handler_serialization(self):
2616
+ handler = NAGLChargesHandler(model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt", skip_version_check=True)
2617
+ assert handler.model_file == "openff-gnn-am1bcc-0.1.0-rc.3.pt"
2618
+ handler_dict = handler.to_dict()
2619
+ assert handler_dict["model_file"] == "openff-gnn-am1bcc-0.1.0-rc.3.pt"
2620
+
2621
+ def test_nagl_charges_handler_with_optional_fields(self):
2622
+ # Test with model_file_hash
2623
+ handler = NAGLChargesHandler(
2624
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2625
+ model_file_hash="144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0",
2626
+ skip_version_check=True,
2627
+ )
2628
+ assert handler.model_file == "openff-gnn-am1bcc-0.1.0-rc.3.pt"
2629
+ assert handler.model_file_hash == "144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0"
2630
+ assert handler.digital_object_identifier is None
2631
+
2632
+ # Test with digital_object_identifier
2633
+ handler = NAGLChargesHandler(
2634
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2635
+ digital_object_identifier="10.5072/zenodo.203601",
2636
+ skip_version_check=True,
2637
+ )
2638
+ assert handler.model_file == "openff-gnn-am1bcc-0.1.0-rc.3.pt"
2639
+ assert handler.model_file_hash is None
2640
+ assert handler.digital_object_identifier == "10.5072/zenodo.203601"
2641
+
2642
+ # Test with both optional fields
2643
+ handler = NAGLChargesHandler(
2644
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2645
+ model_file_hash="144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0",
2646
+ digital_object_identifier="10.5072/zenodo.203601",
2647
+ skip_version_check=True,
2648
+ )
2649
+ assert handler.model_file == "openff-gnn-am1bcc-0.1.0-rc.3.pt"
2650
+ assert handler.model_file_hash == "144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0"
2651
+ assert handler.digital_object_identifier == "10.5072/zenodo.203601"
2652
+
2653
+ def test_nagl_charges_handler_serialization_with_optional_fields(self):
2654
+ # Test serialization with all fields
2655
+ handler = NAGLChargesHandler(
2656
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2657
+ model_file_hash="144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0",
2658
+ digital_object_identifier="10.5072/zenodo.203601",
2659
+ skip_version_check=True,
2660
+ )
2661
+ handler_dict = handler.to_dict()
2662
+ assert handler_dict["model_file"] == "openff-gnn-am1bcc-0.1.0-rc.3.pt"
2663
+ assert handler_dict["model_file_hash"] == "144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0"
2664
+ assert handler_dict["digital_object_identifier"] == "10.5072/zenodo.203601"
2665
+
2666
+ # Test deserialization via constructor
2667
+ handler_from_dict = NAGLChargesHandler(**handler_dict)
2668
+ assert handler_from_dict.model_file == "openff-gnn-am1bcc-0.1.0-rc.3.pt"
2669
+ assert handler_from_dict.model_file_hash == "144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0"
2670
+ assert handler_from_dict.digital_object_identifier == "10.5072/zenodo.203601"
2671
+
2672
+ def test_nagl_charges_handler_compatibility(self):
2673
+ # Test compatible handlers (same model_file)
2674
+ handler1 = NAGLChargesHandler(model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt", skip_version_check=True)
2675
+ handler2 = NAGLChargesHandler(
2676
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2677
+ model_file_hash="144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0",
2678
+ skip_version_check=True,
2679
+ )
2680
+ # Should not raise exception
2681
+ handler1.check_handler_compatibility(handler2)
2682
+
2683
+ # Test incompatible handlers (different model_file)
2684
+ handler3 = NAGLChargesHandler(model_file="different-model-file.pt", skip_version_check=True)
2685
+ with pytest.raises(IncompatibleParameterError, match="different model_files"):
2686
+ handler1.check_handler_compatibility(handler3)
2687
+
2688
+ def test_nagl_charges_handler_defaults(self):
2689
+ # Test that optional fields default to None
2690
+ handler = NAGLChargesHandler(model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt", skip_version_check=True)
2691
+ assert handler.model_file_hash is None
2692
+ assert handler.digital_object_identifier is None
2693
+
2694
+ def test_nagl_charges_handler_hash_compatibility(self):
2695
+ """Test compatibility checks for model_file_hash"""
2696
+ # Test compatible handlers with same hash
2697
+ handler1 = NAGLChargesHandler(
2698
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2699
+ model_file_hash="144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0",
2700
+ skip_version_check=True,
2701
+ )
2702
+ handler2 = NAGLChargesHandler(
2703
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2704
+ model_file_hash="144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0",
2705
+ skip_version_check=True,
2706
+ )
2707
+ # Should not raise exception
2708
+ handler1.check_handler_compatibility(handler2)
2709
+
2710
+ # Test incompatible handlers with different hashes
2711
+ handler3 = NAGLChargesHandler(
2712
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2713
+ model_file_hash="different_hash_value",
2714
+ skip_version_check=True,
2715
+ )
2716
+ with pytest.raises(IncompatibleParameterError, match="different model_file_hash values"):
2717
+ handler1.check_handler_compatibility(handler3)
2718
+
2719
+ # Test compatibility when only one handler has hash (should be compatible)
2720
+ handler4 = NAGLChargesHandler(model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt", skip_version_check=True)
2721
+ # Should not raise exception
2722
+ handler1.check_handler_compatibility(handler4)
2723
+ handler4.check_handler_compatibility(handler1)
2724
+
2725
+ def test_nagl_charges_handler_doi_compatibility(self):
2726
+ """Test compatibility checks for digital_object_identifier"""
2727
+ # Test compatible handlers with same DOI
2728
+ handler1 = NAGLChargesHandler(
2729
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2730
+ digital_object_identifier="10.5072/zenodo.203601",
2731
+ skip_version_check=True,
2732
+ )
2733
+ handler2 = NAGLChargesHandler(
2734
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2735
+ digital_object_identifier="10.5072/zenodo.203601",
2736
+ skip_version_check=True,
2737
+ )
2738
+ # Should not raise exception
2739
+ handler1.check_handler_compatibility(handler2)
2740
+
2741
+ # Test incompatible handlers with different DOIs
2742
+ handler3 = NAGLChargesHandler(
2743
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2744
+ digital_object_identifier="10.5072/zenodo.999999",
2745
+ skip_version_check=True,
2746
+ )
2747
+ with pytest.raises(IncompatibleParameterError, match="different digital_object_identifier values"):
2748
+ handler1.check_handler_compatibility(handler3)
2749
+
2750
+ # Test compatibility when only one handler has DOI (should be compatible)
2751
+ handler4 = NAGLChargesHandler(model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt", skip_version_check=True)
2752
+ # Should not raise exception
2753
+ handler1.check_handler_compatibility(handler4)
2754
+ handler4.check_handler_compatibility(handler1)
2755
+
2756
+ def test_nagl_charges_handler_combined_compatibility(self):
2757
+ """Test compatibility checks with both hash and DOI"""
2758
+ # Test compatible handlers with same hash and DOI
2759
+ handler1 = NAGLChargesHandler(
2760
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2761
+ model_file_hash="144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0",
2762
+ digital_object_identifier="10.5072/zenodo.203601",
2763
+ skip_version_check=True,
2764
+ )
2765
+ handler2 = NAGLChargesHandler(
2766
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2767
+ model_file_hash="144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0",
2768
+ digital_object_identifier="10.5072/zenodo.203601",
2769
+ skip_version_check=True,
2770
+ )
2771
+ # Should not raise exception
2772
+ handler1.check_handler_compatibility(handler2)
2773
+
2774
+ # Test incompatible with same hash but different DOI
2775
+ handler3 = NAGLChargesHandler(
2776
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2777
+ model_file_hash="144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0",
2778
+ digital_object_identifier="10.5072/zenodo.999999",
2779
+ skip_version_check=True,
2780
+ )
2781
+ with pytest.raises(IncompatibleParameterError, match="different digital_object_identifier values"):
2782
+ handler1.check_handler_compatibility(handler3)
2783
+
2784
+ # Test incompatible with different hash but same DOI
2785
+ handler4 = NAGLChargesHandler(
2786
+ model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
2787
+ model_file_hash="different_hash_value",
2788
+ digital_object_identifier="10.5072/zenodo.203601",
2789
+ skip_version_check=True,
2790
+ )
2791
+ with pytest.raises(IncompatibleParameterError, match="different model_file_hash values"):
2792
+ handler1.check_handler_compatibility(handler4)
2793
+
2794
+
2795
+ class TestGBSAHandler:
2796
+ def test_create_default_gbsahandler(self):
2797
+ """Test creation of an empty GBSAHandler, with all default attributes"""
2798
+ gbsa_handler = GBSAHandler(skip_version_check=True)
2799
+ assert gbsa_handler.gb_model == "OBC1"
2800
+ assert gbsa_handler.solvent_dielectric == 78.5
2801
+ assert gbsa_handler.solute_dielectric == 1
2802
+ assert gbsa_handler.sa_model == "ACE"
2803
+ assert gbsa_handler.surface_area_penalty == 5.4 * _cal_mol_a2
2804
+ assert gbsa_handler.solvent_radius == 1.4 * unit.angstrom
2805
+
2806
+ def test_gbsahandler_setters(self):
2807
+ """Test creation of an empty GBSAHandler, with all default attributes"""
2808
+ gbsa_handler = GBSAHandler(skip_version_check=True)
2809
+
2810
+ gbsa_handler.gb_model = "OBC2"
2811
+ gbsa_handler.gb_model = "HCT"
2812
+ gbsa_handler.gb_model = "OBC1"
2813
+ with pytest.raises(SMIRNOFFSpecError):
2814
+ gbsa_handler.gb_model = "Something invalid"
2815
+
2816
+ gbsa_handler.solvent_dielectric = 50.0
2817
+ gbsa_handler.solvent_dielectric = "50.0"
2818
+ with pytest.raises(ValueError):
2819
+ gbsa_handler.solvent_dielectric = "string that can not be cast to float"
2820
+
2821
+ gbsa_handler.solute_dielectric = 2.5
2822
+ gbsa_handler.solute_dielectric = "3.5"
2823
+ with pytest.raises(ValueError):
2824
+ gbsa_handler.solute_dielectric = "string that can not be cast to float"
2825
+
2826
+ gbsa_handler.sa_model = "ACE"
2827
+
2828
+ # NOTE -- Right now, the SMIRNOFF spec will implicitly assume these are the same.
2829
+ gbsa_handler.sa_model = None
2830
+ gbsa_handler.sa_model = "None"
2831
+
2832
+ with pytest.raises(TypeError):
2833
+ gbsa_handler.sa_model = "Invalid SA option"
2834
+
2835
+ gbsa_handler.surface_area_penalty = 1.23 * unit.kilocalorie / unit.mole / unit.nanometer**2
2836
+ with pytest.raises(IncompatibleUnitError):
2837
+ gbsa_handler.surface_area_penalty = 1.23 * unit.degree / unit.mole / unit.nanometer**2
2838
+
2839
+ gbsa_handler.solvent_radius = 300 * unit.femtometer
2840
+ with pytest.raises(IncompatibleUnitError):
2841
+ gbsa_handler.solvent_radius = 3000 * unit.radian
2842
+
2843
+ def test_gbsahandlers_are_compatible(self):
2844
+ """
2845
+ Test the check_handler_compatibility function of GBSAHandler
2846
+ """
2847
+ gbsa_handler_1 = GBSAHandler(skip_version_check=True)
2848
+ gbsa_handler_2 = GBSAHandler(skip_version_check=True)
2849
+
2850
+ # Perform a check which should pass
2851
+ gbsa_handler_1.check_handler_compatibility(gbsa_handler_2)
2852
+
2853
+ # Perform a check which should fail
2854
+ gbsa_handler_3 = GBSAHandler(skip_version_check=True, solvent_radius=1.3 * unit.angstrom)
2855
+ with pytest.raises(IncompatibleParameterError, match="Difference between 'solvent_radius' "):
2856
+ gbsa_handler_1.check_handler_compatibility(gbsa_handler_3)
2857
+
2858
+
2859
+ class TestParameterTypeReExports:
2860
+ def test_parametertype_reexports(self):
2861
+ import openff.toolkit.typing.engines.smirnoff.parameters
2862
+
2863
+ params_module = openff.toolkit.typing.engines.smirnoff.parameters
2864
+
2865
+ def subclass_attrs(obj, classinfo):
2866
+ """Iterate over members of ``obj`` that are concrete, public subclasses of ``classinfo``"""
2867
+ return filter(
2868
+ lambda nv: ( # (name, value)
2869
+ isclass(nv[1])
2870
+ and issubclass(nv[1], classinfo)
2871
+ and not isabstract(nv[1])
2872
+ and not nv[0].startswith("_")
2873
+ ),
2874
+ vars(obj).items(),
2875
+ )
2876
+
2877
+ for _, paramhandler in subclass_attrs(params_module, ParameterHandler):
2878
+ for paramtype_name, paramtype in subclass_attrs(paramhandler, ParameterType):
2879
+ assert paramtype_name in vars(params_module), (
2880
+ f"ParameterType {paramtype_name!r} is not re-exported from parameters module"
2881
+ )
2882
+ assert vars(params_module)[paramtype_name] is paramtype, (
2883
+ f"Exported attribute parameters.{paramtype_name} does not match ParameterType {paramtype_name!r}"
2884
+ )
2885
+ assert paramtype_name in params_module.__all__, (
2886
+ f"ParameterType {paramtype_name!r} missing from parameters.__all__"
2887
+ )
2888
+
2889
+
2890
+ # TODO: test_(all attributes of all ParameterTypes)
2891
+ # TODO: test_add_parameter_fractional_bondorder
2892
+ # TODO: test_get_indexed_attrib
2893
+ # TODO: test_set_unitbearing_attrib (requires implementing __getattr__ and __setattr__)
2894
+ # TODO: test_parametertype_unit_getattr
2895
+ # TODO: test_parametertype_unit_setattr
2896
+ # TODO: test_optional_attribs
2897
+ # TODO: test_optional_indexed_attribs
2898
+ # TODO: test_(X)handler_compatibility, where X is all handlers