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,3839 @@
1
+ """
2
+ Parameter handlers for the SMIRNOFF force field engine
3
+
4
+ This file contains standard parameter handlers for the SMIRNOFF force field engine.
5
+ These classes implement the object model for self-contained parameter assignment.
6
+ New pluggable handlers can be created by creating subclasses of :class:`ParameterHandler`.
7
+
8
+ """
9
+
10
+ __all__ = [
11
+ "AngleHandler",
12
+ "AngleType",
13
+ "BondHandler",
14
+ "BondType",
15
+ "ChargeIncrementType",
16
+ "ConstraintHandler",
17
+ "ConstraintType",
18
+ "DuplicateParameterError",
19
+ "DuplicateVirtualSiteTypeException",
20
+ "ElectrostaticsHandler",
21
+ "FractionalBondOrderInterpolationMethodUnsupportedError",
22
+ "GBSAHandler",
23
+ "GBSAType",
24
+ "ImproperTorsionHandler",
25
+ "ImproperTorsionType",
26
+ "IncompatibleParameterError",
27
+ "IndexedMappedParameterAttribute",
28
+ "IndexedParameterAttribute",
29
+ "LibraryChargeHandler",
30
+ "LibraryChargeType",
31
+ "MappedParameterAttribute",
32
+ "NAGLChargesHandler",
33
+ "NotEnoughPointsForInterpolationError",
34
+ "ParameterAttribute",
35
+ "ParameterHandler",
36
+ "ParameterList",
37
+ "ParameterLookupError",
38
+ "ParameterType",
39
+ "ParameterType",
40
+ "ProperTorsionHandler",
41
+ "ProperTorsionType",
42
+ "SMIRNOFFSpecError",
43
+ "SMIRNOFFSpecUnimplementedError",
44
+ "ToolkitAM1BCCHandler",
45
+ "UnassignedAngleParameterException",
46
+ "UnassignedBondParameterException",
47
+ "UnassignedMoleculeChargeException",
48
+ "UnassignedProperTorsionParameterException",
49
+ "UnassignedValenceParameterException",
50
+ "VirtualSiteHandler",
51
+ "VirtualSiteType",
52
+ "vdWHandler",
53
+ "vdWType",
54
+ ]
55
+
56
+ import copy
57
+ import functools
58
+ import inspect
59
+ import logging
60
+ import re
61
+ from collections import defaultdict
62
+ from collections.abc import Callable
63
+ from typing import Any, Literal, Union, cast, get_args
64
+
65
+ import numpy
66
+ from openff.units.units import Unit
67
+ from packaging.version import Version
68
+
69
+ from openff.toolkit import Quantity, unit
70
+ from openff.toolkit.topology import ImproperDict, TagSortedDict, Topology, ValenceDict
71
+ from openff.toolkit.topology.molecule import Molecule
72
+ from openff.toolkit.utils.collections import ValidatedDict, ValidatedList
73
+ from openff.toolkit.utils.exceptions import (
74
+ DuplicateParameterError,
75
+ DuplicateVirtualSiteTypeException,
76
+ FractionalBondOrderInterpolationMethodUnsupportedError,
77
+ IncompatibleParameterError,
78
+ IncompatibleUnitError,
79
+ MissingIndexedAttributeError,
80
+ MissingPartialChargesError,
81
+ NotEnoughPointsForInterpolationError,
82
+ ParameterLookupError,
83
+ SMIRNOFFSpecError,
84
+ SMIRNOFFSpecUnimplementedError,
85
+ UnassignedAngleParameterException,
86
+ UnassignedBondParameterException,
87
+ UnassignedMoleculeChargeException,
88
+ UnassignedProperTorsionParameterException,
89
+ UnassignedValenceParameterException,
90
+ )
91
+ from openff.toolkit.utils.toolkits import GLOBAL_TOOLKIT_REGISTRY
92
+ from openff.toolkit.utils.utils import object_to_quantity
93
+
94
+ logger = logging.getLogger(__name__)
95
+
96
+
97
+ _cal_mol_a2 = unit.calorie / unit.mole / unit.angstrom**2
98
+
99
+
100
+ # Hack to make Sphinx happy without breaking changes
101
+ class _UNDEFINED:
102
+ """
103
+ Marker type for an undeclared default parameter.
104
+
105
+ Custom type used by ``ParameterAttribute`` to differentiate between ``None``
106
+ and undeclared default.
107
+ """
108
+
109
+ pass
110
+
111
+
112
+ UNDEFINED = _UNDEFINED
113
+
114
+
115
+ def _linear_inter_or_extrapolate(points_dict, x_query):
116
+ """
117
+ Linearly interpolate or extrapolate based on a piecewise linear function
118
+ defined by a set of points. This function is designed to work with
119
+ key:value pairs where the value may be a ``openff.units.Quantity``.
120
+
121
+ Parameters
122
+ ----------
123
+ points_dict
124
+ A dictionary with each item representing a point, where the key is the X value and the value is the Y value.
125
+ x_query
126
+ The X value of the point to interpolate or extrapolate.
127
+
128
+ Returns
129
+ -------
130
+ y_value
131
+ The result of interpolation/extrapolation.
132
+ """
133
+
134
+ # pre-empt case where no interpolation is necessary
135
+ if x_query in points_dict:
136
+ return points_dict[x_query]
137
+
138
+ if len(points_dict) < 2:
139
+ raise NotEnoughPointsForInterpolationError(
140
+ f"Unable to perform interpolation with less than two points. "
141
+ f"points_dict: {points_dict} x_query: {x_query}"
142
+ )
143
+ # TODO: error out for nonsensical fractional bond orders
144
+
145
+ # find the nearest point beneath our queried x value
146
+ try:
147
+ below = max(bo for bo in points_dict if bo < x_query)
148
+ except ValueError:
149
+ below = None
150
+ # find the nearest point above our queried x value
151
+ try:
152
+ above = min(bo for bo in points_dict if bo > x_query)
153
+ except ValueError:
154
+ above = None
155
+
156
+ # handle case where we can clearly interpolate
157
+ if (above is not None) and (below is not None):
158
+ return points_dict[below] + (points_dict[above] - points_dict[below]) * ((x_query - below) / (above - below))
159
+
160
+ # error if we can't hope to interpolate at all
161
+ elif (above is None) and (below is None):
162
+ raise NotImplementedError(
163
+ f"Failed to find interpolation references for `x_query` '{x_query}', with `points_dict` '{points_dict}'"
164
+ )
165
+
166
+ # extrapolate for fractional bond orders below our lowest defined bond order
167
+ elif below is None:
168
+ bond_orders = sorted(points_dict)
169
+ k = points_dict[bond_orders[0]] - (
170
+ (points_dict[bond_orders[1]] - points_dict[bond_orders[0]]) / (bond_orders[1] - bond_orders[0])
171
+ ) * (bond_orders[0] - x_query)
172
+ return k
173
+
174
+ # extrapolate for fractional bond orders above our highest defined bond order
175
+ elif above is None:
176
+ bond_orders = sorted(points_dict)
177
+ k = points_dict[bond_orders[-1]] + (
178
+ (points_dict[bond_orders[-1]] - points_dict[bond_orders[-2]]) / (bond_orders[-1] - bond_orders[-2])
179
+ ) * (x_query - bond_orders[-1])
180
+ return k
181
+
182
+
183
+ # TODO: This is technically a validator, not a converter, but ParameterAttribute doesn't support them yet
184
+ # (it'll be easy if we switch to use the attrs library).
185
+ def _allow_only(allowed_values):
186
+ """A converter that checks the new value is only in a set."""
187
+ allowed_values = frozenset(allowed_values)
188
+
189
+ def _value_checker(instance, attr, new_value):
190
+ # This statement means that, in the "SMIRNOFF Data dict" format, the string "None"
191
+ # and the Python None are the same thing
192
+ if new_value == "None":
193
+ new_value = None
194
+
195
+ # Ensure that the new value is in the list of allowed values
196
+ if new_value not in allowed_values:
197
+ err_msg = (
198
+ f"Attempted to set {instance.__class__.__name__}.{attr.name} "
199
+ f"to {new_value}. Currently, only the following values "
200
+ f"are supported: {sorted(allowed_values)}."
201
+ )
202
+ raise SMIRNOFFSpecError(err_msg)
203
+ return new_value
204
+
205
+ return _value_checker
206
+
207
+
208
+ def _validate_units(attr, value: str | Quantity, units: Unit):
209
+ value = object_to_quantity(value)
210
+
211
+ try:
212
+ if not units.is_compatible_with(value.units): # type: ignore
213
+ raise IncompatibleUnitError(f"{attr.name}={value} should have units of {units}")
214
+ except AttributeError:
215
+ raise IncompatibleUnitError(f"{attr.name}={value} should have units of {units}")
216
+ return value
217
+
218
+
219
+ class ParameterAttribute:
220
+ """A descriptor for ``ParameterType`` attributes.
221
+
222
+ The descriptors allows associating to the parameter a default value,
223
+ which makes the attribute optional, a unit, and a custom converter.
224
+
225
+ Because we may want to have ``None`` as a default value, required
226
+ attributes have the ``default`` set to the special type ``UNDEFINED``.
227
+
228
+ Converters can be both static or instance functions/methods with
229
+ respective signatures::
230
+
231
+ converter(value): -> converted_value
232
+ converter(instance, parameter_attribute, value): -> converted_value
233
+
234
+ A decorator syntax is available (see example below).
235
+
236
+ Parameters
237
+ ----------
238
+ default
239
+ When specified, the descriptor makes this attribute optional by
240
+ attaching a default value to it.
241
+ unit
242
+ When specified, only quantities with compatible units are allowed
243
+ to be set, and string expressions are automatically parsed into a
244
+ ``Quantity``.
245
+ converter
246
+ An optional function that can be used to convert values before
247
+ setting the attribute.
248
+
249
+ See Also
250
+ --------
251
+ IndexedParameterAttribute
252
+ A parameter attribute with multiple terms.
253
+
254
+ Examples
255
+ --------
256
+
257
+ Create a parameter type with an optional and a required attribute.
258
+
259
+ >>> class MyParameter:
260
+ ... attr_required = ParameterAttribute()
261
+ ... attr_optional = ParameterAttribute(default=2)
262
+ ...
263
+ >>> my_par = MyParameter()
264
+
265
+ Even without explicit assignment, the default value is returned.
266
+
267
+ >>> my_par.attr_optional
268
+ 2
269
+
270
+ If you try to access an attribute without setting it first, an
271
+ exception is raised.
272
+
273
+ >>> my_par.attr_required
274
+ Traceback (most recent call last):
275
+ ...
276
+ AttributeError: 'MyParameter' object has no attribute '_attr_required'. Did you mean: 'attr_required'?
277
+
278
+ The attribute allow automatic conversion and validation of units.
279
+
280
+ >>> from openff.toolkit import unit
281
+ >>> class MyParameter:
282
+ ... attr_quantity = ParameterAttribute(unit=unit.angstrom)
283
+ ...
284
+ >>> my_par = MyParameter()
285
+ >>> my_par.attr_quantity = '1.0 * nanometer'
286
+ >>> my_par.attr_quantity
287
+ <Quantity(1.0, 'nanometer')>
288
+ >>> my_par.attr_quantity = 3.0 # doctest: +ELLIPSIS
289
+ Traceback (most recent call last):
290
+ ...
291
+ openff.toolkit.utils.exceptions.IncompatibleUnitError: attr_quantity=3.0 dimensionless should have units of angstrom
292
+
293
+ You can attach a custom converter to an attribute.
294
+
295
+ >>> class MyParameter:
296
+ ... # Both strings and integers convert nicely to floats with float().
297
+ ... attr_all_to_float = ParameterAttribute(converter=float)
298
+ ... attr_int_to_float = ParameterAttribute()
299
+ ... @attr_int_to_float.converter
300
+ ... def attr_int_to_float(self, attr, value):
301
+ ... # This converter converts only integers to float
302
+ ... # and raise an exception for the other types.
303
+ ... if isinstance(value, int):
304
+ ... return float(value)
305
+ ... elif not isinstance(value, float):
306
+ ... raise TypeError(f"Cannot convert '{value}' to float")
307
+ ... return value
308
+ ...
309
+ >>> my_par = MyParameter()
310
+
311
+ attr_all_to_float accepts and convert to float both strings and integers
312
+
313
+ >>> my_par.attr_all_to_float = 1
314
+ >>> my_par.attr_all_to_float
315
+ 1.0
316
+ >>> my_par.attr_all_to_float = '2.0'
317
+ >>> my_par.attr_all_to_float
318
+ 2.0
319
+
320
+ The custom converter associated to attr_int_to_float converts only integers instead.
321
+
322
+ >>> my_par.attr_int_to_float = 3
323
+ >>> my_par.attr_int_to_float
324
+ 3.0
325
+ >>> my_par.attr_int_to_float = '4.0'
326
+ Traceback (most recent call last):
327
+ ...
328
+ TypeError: Cannot convert '4.0' to float
329
+
330
+ """ # noqa: E501
331
+
332
+ UNDEFINED = UNDEFINED
333
+ """Marker type for an undeclared default parameter."""
334
+
335
+ def __init__(
336
+ self,
337
+ default: Any = UNDEFINED,
338
+ unit: Unit | str | None = None,
339
+ converter: Callable | None = None,
340
+ docstring: str = "",
341
+ ):
342
+ if isinstance(unit, str):
343
+ # be careful with module & variable names
344
+ unit = Unit(unit)
345
+
346
+ self.default = default
347
+ self._unit = unit
348
+ self._converter = converter
349
+ self.__doc__ = docstring
350
+
351
+ def __set_name__(self, owner, name):
352
+ self._name = "_" + name
353
+
354
+ @property
355
+ def name(self):
356
+ # Get rid of the initial underscore.
357
+ return self._name[1:]
358
+
359
+ def __get__(self, instance, owner):
360
+ if instance is None:
361
+ # This is called from the class. Return the descriptor object.
362
+ return self
363
+
364
+ try:
365
+ return getattr(instance, self._name)
366
+ except AttributeError:
367
+ # The attribute has not initialized. Check if there's a default.
368
+ if self.default is ParameterAttribute.UNDEFINED:
369
+ raise
370
+ return self.default
371
+
372
+ def __set__(self, instance, value):
373
+ # Convert and validate the value.
374
+ value = self._convert_and_validate(instance, value)
375
+ setattr(instance, self._name, value)
376
+
377
+ def converter(self, converter):
378
+ """Create a new ParameterAttribute with an associated converter.
379
+
380
+ This is meant to be used as a decorator (see main examples).
381
+ """
382
+ return self.__class__(default=self.default, converter=converter)
383
+
384
+ def _convert_and_validate(self, instance, value):
385
+ """Convert to Quantity, validate units, and call custom converter."""
386
+ # The default value is always allowed.
387
+ if self._is_valid_default(value):
388
+ return value
389
+ # Convert and validate units.
390
+ value = self._validate_units(value)
391
+ # Call the custom converter before setting the value.
392
+ value = self._call_converter(value, instance)
393
+ return value
394
+
395
+ def _is_valid_default(self, value):
396
+ """Return True if this is a defined default value."""
397
+ return self.default is not ParameterAttribute.UNDEFINED and value == self.default
398
+
399
+ def _validate_units(self, value):
400
+ """Convert strings expressions to Quantity and validate the units if requested."""
401
+ if self._unit is not None:
402
+ # Convert eventual strings to Quantity objects.
403
+ value = object_to_quantity(value)
404
+
405
+ # Check if units are compatible.
406
+ try:
407
+ if not self._unit.is_compatible_with(value.units):
408
+ raise IncompatibleUnitError(f"{self.name}={value} should have units of {self._unit}")
409
+ except AttributeError:
410
+ # This is not a Quantity object.
411
+ raise IncompatibleUnitError(f"{self.name}={value} should have units of {self._unit}")
412
+ return value
413
+
414
+ def _call_converter(self, value, instance):
415
+ """Correctly calls static and instance converters."""
416
+ if self._converter is not None:
417
+ try:
418
+ # Static function.
419
+ return self._converter(value)
420
+ except TypeError:
421
+ # Instance method.
422
+ return self._converter(instance, self, value)
423
+ return value
424
+
425
+
426
+ class IndexedParameterAttribute(ParameterAttribute):
427
+ """The attribute of a parameter with an unspecified number of terms.
428
+
429
+ Some parameters can be associated to multiple terms, For example,
430
+ torsions have parameters such as k1, k2, ..., and ``IndexedParameterAttribute``
431
+ can be used to encapsulate the sequence of terms.
432
+
433
+ The only substantial difference with ``ParameterAttribute`` is that
434
+ only sequences are supported as values and converters and units are
435
+ checked on each element of the sequence.
436
+
437
+ Currently, the descriptor makes the sequence immutable. This is to
438
+ avoid that an element of the sequence could be set without being
439
+ properly validated. In the future, the data could be wrapped in a
440
+ safe list that would safely allow mutability.
441
+
442
+ Parameters
443
+ ----------
444
+ default
445
+ When specified, the descriptor makes this attribute optional by
446
+ attaching a default value to it.
447
+ unit
448
+ When specified, only sequences of quantities with compatible units
449
+ are allowed to be set.
450
+ converter
451
+ An optional function that can be used to validate and cast each
452
+ element of the sequence before setting the attribute.
453
+
454
+ See Also
455
+ --------
456
+ ParameterAttribute
457
+ A simple parameter attribute.
458
+ MappedParameterAttribute
459
+ A parameter attribute representing a mapping.
460
+ IndexedMappedParameterAttribute
461
+ A parameter attribute representing a sequence, each term of which is a mapping.
462
+
463
+ Examples
464
+ --------
465
+
466
+ Create an optional indexed attribute with unit of angstrom.
467
+
468
+ >>> from openff.toolkit import unit
469
+ >>> class MyParameter:
470
+ ... length = IndexedParameterAttribute(default=None, unit=unit.angstrom)
471
+ ...
472
+ >>> my_par = MyParameter()
473
+ >>> my_par.length is None
474
+ True
475
+
476
+ Strings are parsed into Quantity objects.
477
+
478
+ >>> my_par.length = ['1 * angstrom', 0.5 * unit.nanometer]
479
+ >>> my_par.length[0]
480
+ <Quantity(1, 'angstrom')>
481
+
482
+ Similarly, custom converters work as with ``ParameterAttribute``, but
483
+ they are used to validate each value in the sequence.
484
+
485
+ >>> class MyParameter:
486
+ ... attr_indexed = IndexedParameterAttribute(converter=float)
487
+ ...
488
+ >>> my_par = MyParameter()
489
+ >>> my_par.attr_indexed = [1, '1.0', '1e-2', 4.0]
490
+ >>> my_par.attr_indexed
491
+ [1.0, 1.0, 0.01, 4.0]
492
+
493
+ """
494
+
495
+ def _convert_and_validate(self, instance, value):
496
+ """Overwrite ParameterAttribute._convert_and_validate to make the value a ValidatedList."""
497
+ # The default value is always allowed.
498
+ if self._is_valid_default(value):
499
+ return value
500
+
501
+ # We push the converters into a ValidatedList so that we can make
502
+ # sure that elements are validated correctly when they are modified
503
+ # after their initialization.
504
+ # ValidatedList expects converters that take the value as a single
505
+ # argument so we create a partial function with the instance assigned.
506
+ static_converter = functools.partial(self._call_converter, instance=instance)
507
+ value = ValidatedList(value, converter=[self._validate_units, static_converter])
508
+
509
+ return value
510
+
511
+
512
+ class MappedParameterAttribute(ParameterAttribute):
513
+ """The attribute of a parameter in which each term is a mapping.
514
+
515
+ The substantial difference with ``IndexedParameterAttribute`` is that, unlike
516
+ indexing, the mapping can be based on artbitrary references, like indices but
517
+ can starting at non-zero values and include non-adjacent keys.
518
+
519
+ Parameters
520
+ ----------
521
+ default
522
+ When specified, the descriptor makes this attribute optional by
523
+ attaching a default value to it.
524
+ unit
525
+ When specified, only sequences of mappings where values are quantities with
526
+ compatible units are allowed to be set.
527
+ converter
528
+ An optional function that can be used to validate and cast each
529
+ component of each element of the sequence before setting the attribute.
530
+
531
+ See Also
532
+ --------
533
+ IndexedParameterAttribute
534
+ A parameter attribute representing a sequence.
535
+ IndexedMappedParameterAttribute
536
+ A parameter attribute representing a sequence, each term of which is a mapping.
537
+
538
+ Examples
539
+ --------
540
+
541
+ Create an optional indexed attribute with unit of angstrom.
542
+
543
+ >>> from openff.toolkit import unit
544
+ >>> class MyParameter:
545
+ ... length = MappedParameterAttribute(default=None, unit=unit.angstrom)
546
+ ...
547
+ >>> my_par = MyParameter()
548
+ >>> my_par.length is None
549
+ True
550
+
551
+ Like other ParameterAttribute objects, strings are parsed into Quantity objects.
552
+
553
+ >>> my_par.length = {1:'1.5 * angstrom', 2: '1.4 * angstrom'}
554
+ >>> my_par.length[1]
555
+ <Quantity(1.5, 'angstrom')>
556
+
557
+ Unlike other ParameterAttribute objects, the reference points can do not need ot be
558
+ zero-indexed, non-adjancent, such as interpolating defining a bond parameter for
559
+ interpolation by defining references values and bond orders 2 and 3:
560
+
561
+ >>> my_par.length = {2:'1.42 * angstrom', 3: '1.35 * angstrom'}
562
+ >>> my_par.length[2]
563
+ <Quantity(1.42, 'angstrom')>
564
+
565
+ """
566
+
567
+ def _convert_and_validate(self, instance, value):
568
+ if self._is_valid_default(value):
569
+ return value
570
+ static_converter = functools.partial(self._call_converter, instance=instance)
571
+ value = ValidatedDict(value, converter=[self._validate_units, static_converter])
572
+ return value
573
+
574
+
575
+ class IndexedMappedParameterAttribute(ParameterAttribute):
576
+ r"""The attribute of a parameter with an unspecified number of terms, where
577
+ each term is a mapping.
578
+
579
+ Some parameters can be associated to multiple terms,
580
+ where those terms have multiple components.
581
+ For example, torsions with fractional bond orders have parameters such as
582
+ k1_bondorder1, k1_bondorder2, k2_bondorder1, k2_bondorder2, ..., and
583
+ ``IndexedMappedParameterAttribute`` can be used to encapsulate the sequence of
584
+ terms as mappings (typically, ``dict``\ s) of their components.
585
+
586
+ The only substantial difference with ``IndexedParameterAttribute`` is that
587
+ only sequences of mappings are supported as values and converters and units are
588
+ checked on each component of each element in the sequence.
589
+
590
+ Currently, the descriptor makes the sequence immutable. This is to
591
+ avoid that an element of the sequence could be set without being
592
+ properly validated. In the future, the data could be wrapped in a
593
+ safe list that would safely allow mutability.
594
+
595
+ Parameters
596
+ ----------
597
+ default
598
+ When specified, the descriptor makes this attribute optional by
599
+ attaching a default value to it.
600
+ unit
601
+ When specified, only sequences of mappings where values are quantities with
602
+ compatible units are allowed to be set.
603
+ converter
604
+ An optional function that can be used to validate and cast each
605
+ component of each element of the sequence before setting the attribute.
606
+
607
+ See Also
608
+ --------
609
+ IndexedParameterAttribute
610
+ A parameter attribute representing a sequence.
611
+ MappedParameterAttribute
612
+ A parameter attribute representing a mapping.
613
+
614
+ Examples
615
+ --------
616
+
617
+ Create an optional indexed attribute with unit of angstrom.
618
+
619
+ >>> from openff.toolkit import unit
620
+ >>> class MyParameter:
621
+ ... length = IndexedMappedParameterAttribute(default=None, unit=unit.angstrom)
622
+ ...
623
+ >>> my_par = MyParameter()
624
+ >>> my_par.length is None
625
+ True
626
+
627
+ Strings are parsed into Quantity objects.
628
+
629
+ >>> my_par.length = [{1:'1 * angstrom'}, {1: 0.5 * unit.nanometer}]
630
+ >>> my_par.length[0]
631
+ {1: <Quantity(1, 'angstrom')>}
632
+
633
+ Similarly, custom converters work as with ``ParameterAttribute``, but
634
+ they are used to validate each value in the sequence.
635
+
636
+ >>> class MyParameter:
637
+ ... attr_indexed = IndexedMappedParameterAttribute(converter=float)
638
+ ...
639
+ >>> my_par = MyParameter()
640
+ >>> my_par.attr_indexed = [{1: 1}, {2: '1.0', 3: '1e-2'}, {4: 4.0}]
641
+ >>> my_par.attr_indexed
642
+ [{1: 1.0}, {2: 1.0, 3: 0.01}, {4: 4.0}]
643
+
644
+ """
645
+
646
+ def _convert_and_validate(self, instance, value):
647
+ """Overwrite ParameterAttribute._convert_and_validate to make the value a ValidatedList."""
648
+ # The default value is always allowed.
649
+ if self._is_valid_default(value):
650
+ return value
651
+
652
+ # We push the converters into a ValidatedListMapping so that we can make
653
+ # sure that elements are validated correctly when they are modified
654
+ # after their initialization.
655
+ # ValidatedListMapping expects converters that take the value as a single
656
+ # argument so we create a partial function with the instance assigned.
657
+ static_converter = functools.partial(self._call_converter, instance=instance)
658
+
659
+ value = ValidatedList(
660
+ [ValidatedDict(element, converter=[self._validate_units, static_converter]) for element in value],
661
+ converter=self._index_converter,
662
+ )
663
+
664
+ return value
665
+
666
+ @staticmethod
667
+ def _index_converter(x):
668
+ return ValidatedDict(x)
669
+
670
+
671
+ class _ParameterAttributeHandler:
672
+ """A base class for ``ParameterType`` and ``ParameterHandler`` objects.
673
+
674
+ Encapsulate shared code of ``ParameterType`` and ``ParameterHandler``.
675
+ In particular, this base class provides an ``__init__`` method that
676
+ automatically initialize the attributes defined through the ``ParameterAttribute``
677
+ and ``IndexedParameterAttribute`` descriptors, as well as handling
678
+ cosmetic attributes.
679
+
680
+ See Also
681
+ --------
682
+ ParameterAttribute
683
+ A simple parameter attribute.
684
+ IndexedParameterAttribute
685
+ A parameter attribute with multiple terms.
686
+
687
+ Examples
688
+ --------
689
+
690
+ This base class was design to encapsulate shared code between ``ParameterType``
691
+ and ``ParameterHandler``, which both need to deal with parameter and cosmetic
692
+ attributes.
693
+
694
+ To create a new type/handler, you can use the ``ParameterAttribute`` descriptors.
695
+
696
+ >>> class ParameterTypeOrHandler(_ParameterAttributeHandler):
697
+ ... length = ParameterAttribute(unit=unit.angstrom)
698
+ ... k = ParameterAttribute(unit=unit.kilocalorie / unit.mole / unit.angstrom**2)
699
+ ...
700
+
701
+ ``_ParameterAttributeHandler`` and the descriptors take care of performing
702
+ sanity checks on initialization and assignment of the single attributes. Because
703
+ we attached units to the parameters, we need to pass them with compatible units.
704
+
705
+ >>> my_par = ParameterTypeOrHandler(
706
+ ... length='1.01 * angstrom',
707
+ ... k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2
708
+ ... )
709
+
710
+ Note that ``_ParameterAttributeHandler`` took care of implementing
711
+ a constructor, and that unit parameters support string assignments.
712
+ These are automatically converted to ``Quantity`` objects.
713
+
714
+ >>> my_par.length
715
+ <Quantity(1.01, 'angstrom')>
716
+
717
+ While assigning incompatible units is forbidden.
718
+
719
+ >>> my_par.k = 3.0 * unit.gram # doctest: +ELLIPSIS
720
+ Traceback (most recent call last):
721
+ ...
722
+ openff.toolkit.utils.exceptions.IncompatibleUnitError: k=3.0 gram should have units of kilocalorie / angstrom ** 2 / mole
723
+
724
+ On top of type checking, the constructor implemented in ``_ParameterAttributeHandler``
725
+ checks if some required parameters are not given.
726
+
727
+ >>> ParameterTypeOrHandler(length=3.0*unit.nanometer) # doctest: +ELLIPSIS
728
+ Traceback (most recent call last):
729
+ ...
730
+ openff.toolkit.utils.exceptions.SMIRNOFFSpecError: <class '...ParameterTypeOrHandler'> require the following missing parameters: ['k']. Defined kwargs are ['length']
731
+
732
+ Each attribute can be made optional by specifying a default value,
733
+ and you can attach a converter function by passing a callable as an
734
+ argument or through the decorator syntax.
735
+
736
+ >>> class ParameterTypeOrHandler(_ParameterAttributeHandler):
737
+ ... attr_optional = ParameterAttribute(default=2)
738
+ ... attr_all_to_float = ParameterAttribute(converter=float)
739
+ ... attr_int_to_float = ParameterAttribute()
740
+ ...
741
+ ... @attr_int_to_float.converter
742
+ ... def attr_int_to_float(self, attr, value):
743
+ ... # This converter converts only integers to floats
744
+ ... # and raise an exception for the other types.
745
+ ... if isinstance(value, int):
746
+ ... return float(value)
747
+ ... elif not isinstance(value, float):
748
+ ... raise TypeError(f"Cannot convert '{value}' to float")
749
+ ... return value
750
+ ...
751
+ >>> my_par = ParameterTypeOrHandler(attr_all_to_float='3.0', attr_int_to_float=1)
752
+ >>> my_par.attr_optional
753
+ 2
754
+ >>> my_par.attr_all_to_float
755
+ 3.0
756
+ >>> my_par.attr_int_to_float
757
+ 1.0
758
+
759
+ The float() function can convert strings to integers, but our custom
760
+ converter forbids it
761
+
762
+ >>> my_par.attr_all_to_float = '2.0'
763
+ >>> my_par.attr_int_to_float = '4.0'
764
+ Traceback (most recent call last):
765
+ ...
766
+ TypeError: Cannot convert '4.0' to float
767
+
768
+ Parameter attributes that can be indexed can be handled with the
769
+ ``IndexedParameterAttribute``. These support unit validation and
770
+ converters exactly as ``ParameterAttribute``s, but the validation/conversion
771
+ is performed for each indexed attribute.
772
+
773
+ >>> class MyTorsionType(_ParameterAttributeHandler):
774
+ ... periodicity = IndexedParameterAttribute(converter=int)
775
+ ... k = IndexedParameterAttribute(unit=unit.kilocalorie / unit.mole)
776
+ ...
777
+ >>> my_par = MyTorsionType(
778
+ ... periodicity1=2,
779
+ ... k1=5 * unit.kilocalorie / unit.mole,
780
+ ... periodicity2='3',
781
+ ... k2=6 * unit.kilocalorie / unit.mole,
782
+ ... )
783
+ >>> my_par.periodicity
784
+ [2, 3]
785
+
786
+ Indexed attributes, can be accessed both as a list or as their indexed
787
+ parameter name.
788
+
789
+ >>> my_par.periodicity2 = 6
790
+ >>> my_par.periodicity[0] = 1
791
+ >>> my_par.periodicity
792
+ [1, 6]
793
+
794
+ """ # noqa: E501
795
+
796
+ def __init__(self, allow_cosmetic_attributes=False, **kwargs):
797
+ """
798
+ Initialize parameter and cosmetic attributes.
799
+
800
+ Parameters
801
+ ----------
802
+ allow_cosmetic_attributes
803
+ Whether to permit non-spec kwargs ("cosmetic attributes").
804
+ If True, non-spec kwargs will be stored as an attribute of
805
+ this parameter which can be accessed and written out. Otherwise,
806
+ an exception will be raised.
807
+
808
+ """
809
+ # A list that may be populated to record the cosmetic attributes
810
+ # read from a SMIRNOFF data source.
811
+ self._cosmetic_attribs = []
812
+
813
+ # Do not modify the original data.
814
+ smirnoff_data = copy.deepcopy(kwargs)
815
+
816
+ (
817
+ smirnoff_data,
818
+ indexed_mapped_attr_lengths,
819
+ ) = self._process_indexed_mapped_attributes(smirnoff_data)
820
+ smirnoff_data = self._process_indexed_attributes(smirnoff_data, indexed_mapped_attr_lengths)
821
+
822
+ smirnoff_data = self._process_mapped_attributes(smirnoff_data)
823
+
824
+ # Check for missing required arguments.
825
+ given_attributes = set(smirnoff_data.keys())
826
+ required_attributes = set(self._get_required_parameter_attributes().keys())
827
+ missing_attributes = required_attributes.difference(given_attributes)
828
+ if len(missing_attributes) != 0:
829
+ msg = (
830
+ f"{self.__class__} require the following missing parameters: {sorted(missing_attributes)}."
831
+ f" Defined kwargs are {sorted(smirnoff_data.keys())}"
832
+ )
833
+ raise SMIRNOFFSpecError(msg)
834
+
835
+ # Finally, set attributes of this ParameterType and handle cosmetic attributes.
836
+ allowed_attributes = set(self._get_parameter_attributes().keys())
837
+ for key, val in smirnoff_data.items():
838
+ if key in allowed_attributes:
839
+ setattr(self, key, val)
840
+ # Handle all unknown kwargs as cosmetic so we can write them back out
841
+ elif allow_cosmetic_attributes:
842
+ self.add_cosmetic_attribute(key, val)
843
+ else:
844
+ msg = (
845
+ f"Unexpected kwarg ({key}: {val}) passed to {self.__class__} constructor. "
846
+ "If this is a desired cosmetic attribute, consider setting "
847
+ "'allow_cosmetic_attributes=True'"
848
+ )
849
+ raise SMIRNOFFSpecError(msg)
850
+
851
+ def _process_mapped_attributes(self, smirnoff_data: dict) -> dict:
852
+ kwargs = list(smirnoff_data.keys())
853
+ for kwarg in kwargs:
854
+ attr_name, key = self._split_attribute_mapping(kwarg)
855
+
856
+ # Check if this is a mapped attribute
857
+ if key is not None and attr_name in self._get_mapped_parameter_attributes():
858
+ if attr_name not in smirnoff_data:
859
+ smirnoff_data[attr_name] = dict()
860
+
861
+ smirnoff_data[attr_name][key] = smirnoff_data[kwarg]
862
+ del smirnoff_data[kwarg]
863
+
864
+ return smirnoff_data
865
+
866
+ def _process_indexed_mapped_attributes(self, smirnoff_data: dict) -> tuple[dict, dict[str, int]]:
867
+ # TODO: construct data structure for holding indexed_mapped attrs, which
868
+ # will get fed into setattr
869
+ indexed_mapped_attr_lengths = {}
870
+ reindex = set()
871
+ reverse: defaultdict = defaultdict(dict)
872
+
873
+ kwargs = list(smirnoff_data.keys())
874
+ for kwarg in kwargs:
875
+ attr_name, index, key = self._split_attribute_index_mapping(kwarg)
876
+
877
+ # Check if this is an indexed_mapped attribute.
878
+ if (
879
+ (key is not None)
880
+ and (index is not None)
881
+ and attr_name in self._get_indexed_mapped_parameter_attributes()
882
+ ):
883
+ # we start with a dict because have no guarantee of order
884
+ # in which we will see each kwarg
885
+ # we'll switch this to a list later
886
+ if attr_name not in smirnoff_data:
887
+ smirnoff_data[attr_name] = dict()
888
+ reindex.add(attr_name)
889
+
890
+ if index not in smirnoff_data[attr_name]:
891
+ smirnoff_data[attr_name][index] = dict()
892
+
893
+ smirnoff_data[attr_name][index][key] = smirnoff_data[kwarg]
894
+ del smirnoff_data[kwarg]
895
+
896
+ # build reverse mapping; needed for contiguity check below
897
+ if index not in reverse[attr_name]:
898
+ reverse[attr_name][index] = dict()
899
+ reverse[attr_name][index][key] = kwarg
900
+
901
+ # turn all our top-level dicts into lists
902
+ # catch cases where we skip an index,
903
+ # e.g. k1_bondorder*, k3_bondorder* defined, but not k2_bondorder*
904
+ for attr_name in reindex:
905
+ indexed_mapping = []
906
+ j = 0
907
+ for i in sorted(smirnoff_data[attr_name].keys()):
908
+ if int(i) == j:
909
+ indexed_mapping.append(smirnoff_data[attr_name][i])
910
+ j += 1
911
+ else:
912
+ # any key will do; we are sensitive only to top-level index
913
+ key = sorted(reverse[attr_name][i].keys())[0]
914
+ kwarg = reverse[attr_name][i][key]
915
+ val = smirnoff_data[attr_name][i][key]
916
+
917
+ msg = (
918
+ f"Unexpected kwarg ({kwarg}: {val}) passed to {self.__class__} constructor. "
919
+ "If this is a desired cosmetic attribute, consider setting "
920
+ "'allow_cosmetic_attributes=True'"
921
+ )
922
+ raise SMIRNOFFSpecError(msg)
923
+
924
+ smirnoff_data[attr_name] = indexed_mapping
925
+
926
+ # keep track of lengths; used downstream for checking against other
927
+ # indexed attributes
928
+ indexed_mapped_attr_lengths[attr_name] = len(smirnoff_data[attr_name])
929
+
930
+ return smirnoff_data, indexed_mapped_attr_lengths
931
+
932
+ def _process_indexed_attributes(self, smirnoff_data: dict, indexed_attr_lengths: dict | None = None) -> dict:
933
+ # Check for indexed attributes and stack them into a list.
934
+ # Keep track of how many indexed attribute we find to make sure they all have the same length.
935
+
936
+ # TODO: REFACTOR ME; try looping over contents of `smirnoff_data`, using
937
+ # `split_attribute_index` to extract values
938
+
939
+ if indexed_attr_lengths is None:
940
+ indexed_attr_lengths = {}
941
+
942
+ for attrib_basename in self._get_indexed_parameter_attributes().keys():
943
+ index = 1
944
+ while True:
945
+ attrib_w_index = f"{attrib_basename}{index}"
946
+
947
+ # Exit the while loop if the indexed attribute is not given.
948
+ # this is the stop condition
949
+ try:
950
+ attrib_w_index_value = smirnoff_data[attrib_w_index]
951
+ except KeyError:
952
+ break
953
+
954
+ # Check if this is the first iteration.
955
+ if index == 1:
956
+ # Check if this attribute has been specified with and without index.
957
+ if attrib_basename in smirnoff_data:
958
+ err_msg = (
959
+ f"The attribute '{attrib_basename}' has been specified "
960
+ f"with and without index: '{attrib_w_index}'"
961
+ )
962
+ raise TypeError(err_msg)
963
+
964
+ # Otherwise create the list object.
965
+ smirnoff_data[attrib_basename] = list()
966
+
967
+ # Append the new value to the list.
968
+ smirnoff_data[attrib_basename].append(attrib_w_index_value)
969
+
970
+ # Remove the indexed attribute from the kwargs as it will
971
+ # be exposed only as an element of the list.
972
+ del smirnoff_data[attrib_w_index]
973
+ index += 1
974
+
975
+ # Update the lengths with this attribute (if it was found).
976
+ if index > 1:
977
+ indexed_attr_lengths[attrib_basename] = len(smirnoff_data[attrib_basename])
978
+
979
+ # Raise an error if we there are different indexed
980
+ # attributes with a different number of terms.
981
+ if len(set(indexed_attr_lengths.values())) > 1:
982
+ raise TypeError(f"The following indexed attributes have different lengths: {indexed_attr_lengths}")
983
+
984
+ return smirnoff_data
985
+
986
+ def to_dict(
987
+ self,
988
+ discard_cosmetic_attributes: bool = False,
989
+ duplicate_attributes: list[str] | None = None,
990
+ ) -> dict[str, dict | list | str]:
991
+ """
992
+ Convert this object to dict format.
993
+
994
+ The returning dictionary contains all the ``ParameterAttribute``
995
+ and ``IndexedParameterAttribute`` as well as cosmetic attributes
996
+ if ``discard_cosmetic_attributes`` is ``False``.
997
+
998
+ Parameters
999
+ ----------
1000
+ discard_cosmetic_attributes
1001
+ Whether to discard non-spec attributes of this object
1002
+ duplicate_attributes
1003
+ A list of names of attributes that redundantly decsribe
1004
+ data and should be discarded during serializaiton
1005
+
1006
+ Returns
1007
+ -------
1008
+ smirnoff_dict
1009
+ The SMIRNOFF-compliant dict representation of this object.
1010
+
1011
+ """
1012
+ # Make a list of all attribs that should be included in the
1013
+ # returned dict (call list() to make a copy). We discard
1014
+ # optional attributes that are set to None defaults.
1015
+ attribs_to_return = list(self._get_defined_parameter_attributes().keys())
1016
+
1017
+ if duplicate_attributes is not None:
1018
+ for duplicate in duplicate_attributes:
1019
+ try:
1020
+ attribs_to_return.pop(attribs_to_return.index(duplicate))
1021
+ except ValueError:
1022
+ # The attribute was not in the list
1023
+ continue
1024
+
1025
+ # Start populating a dict of the attribs.
1026
+ indexed_attribs = set(self._get_indexed_parameter_attributes().keys())
1027
+ mapped_attribs = set(self._get_mapped_parameter_attributes().keys())
1028
+ indexed_mapped_attribs = set(self._get_indexed_mapped_parameter_attributes().keys())
1029
+ smirnoff_dict = dict()
1030
+
1031
+ # If attribs_to_return is ordered here, that will effectively be an informal output ordering
1032
+ for attrib_name in attribs_to_return:
1033
+ attrib_value = getattr(self, attrib_name)
1034
+
1035
+ if attrib_name in indexed_mapped_attribs:
1036
+ for idx, mapping in enumerate(attrib_value):
1037
+ for key, val in mapping.items():
1038
+ attrib_name_indexed, attrib_name_mapped = attrib_name.split("_")
1039
+ smirnoff_dict[f"{attrib_name_indexed}{idx + 1!s}_{attrib_name_mapped}{key}"] = val
1040
+ elif attrib_name in indexed_attribs:
1041
+ for idx, val in enumerate(attrib_value):
1042
+ smirnoff_dict[attrib_name + str(idx + 1)] = val
1043
+ elif attrib_name in mapped_attribs:
1044
+ for key, val in attrib_value.items():
1045
+ smirnoff_dict[f"{attrib_name}{key!s}"] = val
1046
+ elif attrib_name == "version":
1047
+ smirnoff_dict[attrib_name] = str(attrib_value)
1048
+ else:
1049
+ smirnoff_dict[attrib_name] = attrib_value
1050
+
1051
+ # Serialize cosmetic attributes.
1052
+ if not (discard_cosmetic_attributes):
1053
+ for cosmetic_attrib in self._cosmetic_attribs:
1054
+ smirnoff_dict[cosmetic_attrib] = getattr(self, "_" + cosmetic_attrib)
1055
+
1056
+ return smirnoff_dict
1057
+
1058
+ def __getattr__(self, item):
1059
+ """Take care of mapping indexed attributes to their respective list elements."""
1060
+
1061
+ # Try matching the case where there are two indices
1062
+ # this indicates a index_mapped parameter
1063
+ attr_name, index, key = self._split_attribute_index_mapping(item)
1064
+
1065
+ # Check if this is an indexed_mapped attribute.
1066
+ if key is not None and index is not None and attr_name in self._get_indexed_mapped_parameter_attributes():
1067
+ indexed_mapped_attr_value = getattr(self, attr_name)
1068
+ try:
1069
+ return indexed_mapped_attr_value[index][key]
1070
+ except (IndexError, KeyError) as err:
1071
+ raise MissingIndexedAttributeError(
1072
+ f"{err!s} '{item}' is out of bounds for indexed attribute '{attr_name}'"
1073
+ )
1074
+
1075
+ # Otherwise, try indexed attribute
1076
+ # Separate the indexed attribute name from the list index.
1077
+ attr_name, index = self._split_attribute_index(item)
1078
+
1079
+ # Check if this is an indexed attribute.
1080
+ if index is not None and attr_name in self._get_indexed_parameter_attributes():
1081
+ indexed_attr_value = getattr(self, attr_name)
1082
+ try:
1083
+ return indexed_attr_value[index]
1084
+ except IndexError:
1085
+ raise MissingIndexedAttributeError(f"'{item}' is out of bounds for indexed attribute '{attr_name}'")
1086
+
1087
+ # Otherwise, forward the search to the next class in the MRO.
1088
+ try:
1089
+ return super().__getattr__(item)
1090
+ except AttributeError as e:
1091
+ # If this fails because the next classes in the MRO do not
1092
+ # implement __getattr__(), then raise the standard Attribute error.
1093
+ if "__getattr__" in str(e):
1094
+ raise AttributeError(f"{self.__class__} object has no attribute '{item}'")
1095
+ # Otherwise, re-raise the error from the class in the MRO.
1096
+ raise
1097
+
1098
+ def __setattr__(self, key, value):
1099
+ """Take care of mapping indexed attributes to their respective list elements."""
1100
+
1101
+ # Try matching the case where there are two indices
1102
+ # this indicates a index_mapped parameter
1103
+ attr_name, index, mapkey = self._split_attribute_index_mapping(key)
1104
+
1105
+ # Check if this is an index_mapped attribute. avoiding an infinite
1106
+ # recursion by calling getattr() with non-existing keys.
1107
+ if (
1108
+ (mapkey is not None)
1109
+ and (index is not None)
1110
+ and attr_name in self._get_indexed_mapped_parameter_attributes()
1111
+ ):
1112
+ indexed_mapped_attr_value = getattr(self, attr_name)
1113
+ try:
1114
+ indexed_mapped_attr_value[index][mapkey] = value
1115
+ return
1116
+ except (IndexError, KeyError) as err:
1117
+ raise MissingIndexedAttributeError(
1118
+ f"{err!s} '{key}' is out of bounds for indexed attribute '{attr_name}'"
1119
+ )
1120
+
1121
+ # Otherwise, try indexed attribute
1122
+ # Separate the indexed attribute name from the list index.
1123
+ attr_name, index = self._split_attribute_index(key)
1124
+
1125
+ # Check if this is an indexed attribute. avoiding an infinite
1126
+ # recursion by calling getattr() with non-existing keys.
1127
+ if (index is not None) and (attr_name in self._get_indexed_parameter_attributes()):
1128
+ indexed_attr_value = getattr(self, attr_name)
1129
+ try:
1130
+ indexed_attr_value[index] = value
1131
+ return
1132
+ except IndexError:
1133
+ raise MissingIndexedAttributeError(f"'{key}' is out of bounds for indexed attribute '{attr_name}'")
1134
+
1135
+ # Forward the request to the next class in the MRO.
1136
+ super().__setattr__(key, value)
1137
+
1138
+ def add_cosmetic_attribute(self, attr_name, attr_value):
1139
+ """
1140
+ Add a cosmetic attribute to this object.
1141
+
1142
+ This attribute will not have a functional effect on the object
1143
+ in the OpenFF Toolkit, but can be written out during
1144
+ output.
1145
+
1146
+ .. warning :: The API for modifying cosmetic attributes is experimental
1147
+ and may change in the future (see issue #338).
1148
+
1149
+ Parameters
1150
+ ----------
1151
+ attr_name
1152
+ Name of the attribute to define for this object.
1153
+ attr_value
1154
+ The value of the attribute to define for this object.
1155
+
1156
+ """
1157
+ setattr(self, "_" + attr_name, attr_value)
1158
+ self._cosmetic_attribs.append(attr_name)
1159
+
1160
+ def delete_cosmetic_attribute(self, attr_name):
1161
+ """
1162
+ Delete a cosmetic attribute from this object.
1163
+
1164
+ .. warning :: The API for modifying cosmetic attributes is experimental
1165
+ and may change in the future (see issue #338).
1166
+
1167
+ Parameters
1168
+ ----------
1169
+ attr_name
1170
+ Name of the cosmetic attribute to delete.
1171
+ """
1172
+ # TODO: Can we handle this by overriding __delattr__ instead?
1173
+ # Would we also need to override __del__ as well to cover both deletation methods?
1174
+ delattr(self, "_" + attr_name)
1175
+ self._cosmetic_attribs.remove(attr_name)
1176
+
1177
+ def attribute_is_cosmetic(self, attr_name):
1178
+ """
1179
+ Determine whether an attribute of this object is cosmetic.
1180
+
1181
+ .. warning :: The API for modifying cosmetic attributes is experimental
1182
+ and may change in the future (see issue #338).
1183
+
1184
+ Parameters
1185
+ ----------
1186
+ attr_name
1187
+ The attribute name to check
1188
+
1189
+ Returns
1190
+ -------
1191
+ is_cosmetic
1192
+ Returns True if the attribute is defined and is cosmetic. Returns False otherwise.
1193
+ """
1194
+ return attr_name in self._cosmetic_attribs
1195
+
1196
+ @staticmethod
1197
+ def _split_attribute_index(item: str) -> tuple[str, int | None]:
1198
+ """Split the attribute name from the final index.
1199
+
1200
+ For example, the method takes 'k2' and returns the tuple ('k', 1).
1201
+ If attribute_name doesn't end with an integer, it returns (item, None).
1202
+ """
1203
+
1204
+ # Match any number (\d+) at the end of the string ($).
1205
+ match = re.search(r"\d+$", item)
1206
+ if match is None:
1207
+ return item, None
1208
+
1209
+ _index: str = match.group() # This is a str.
1210
+ attr_name = item[: -len(_index)]
1211
+ index = int(match.group()) - 1
1212
+ return attr_name, index
1213
+
1214
+ @staticmethod
1215
+ def _split_attribute_index_mapping(
1216
+ item: str,
1217
+ ) -> tuple[str, int | None, int | None]:
1218
+ """Split the attribute name from the final index.
1219
+
1220
+ For example, the method takes 'k1_bondorder2' and returns the tuple ('k_bondorder', 0, 2).
1221
+ If attribute_name doesn't end with an integer, it returns (item, None, None).
1222
+ """
1223
+ # Match items of the form <item><index>_<mapping><key>
1224
+ # where <index> and <key> always integers
1225
+ match = re.search(r"\d+_[A-z]+\d+$", item)
1226
+ if match is None:
1227
+ return item, None, None
1228
+
1229
+ # Match any number (\d+) at the end of the string ($).
1230
+ i_match = r"\d+$"
1231
+
1232
+ indexed, mapped = item.split("_")
1233
+
1234
+ # process indexed component
1235
+ match_indexed = re.search(i_match, indexed)
1236
+ assert match_indexed is not None
1237
+ _index: str = match_indexed.group()
1238
+ attr_name = indexed[: -len(_index)]
1239
+ index = int(_index) - 1
1240
+
1241
+ # process mapped component
1242
+ match_mapping = re.search(i_match, mapped)
1243
+ assert match_mapping is not None
1244
+ _key: str = match_mapping.group()
1245
+ attr_name = f"{attr_name}_{mapped[: -len(_key)]}"
1246
+ # we don't subtract 1 here, because these are keys, not indices
1247
+ key = int(_key)
1248
+
1249
+ return attr_name, index, key
1250
+
1251
+ @staticmethod
1252
+ def _split_attribute_mapping(item: str) -> tuple[str, int | None]:
1253
+ """Split the attribute name from the and its mapping.
1254
+
1255
+ For example, the method takes 'k_foo2' and returns the tuple ('k_foo', 2).
1256
+ If attribute_name doesn't end with an integer, it returns (item, None).
1257
+
1258
+ """
1259
+ # TODO: Can these three splitting functions be collapsed down into one?
1260
+ # Match any number (\d+) at the end of the string ($).
1261
+ map_match = r"\d+$"
1262
+
1263
+ match_mapping = re.search(map_match, item)
1264
+ if match_mapping is None:
1265
+ return item, None
1266
+
1267
+ _key = match_mapping.group()
1268
+ attr_name = item[: -len(_key)]
1269
+ key = int(_key)
1270
+
1271
+ return attr_name, key
1272
+
1273
+ @classmethod
1274
+ def _get_parameter_attributes(cls, filter=None):
1275
+ """Return all the attributes of the parameters.
1276
+
1277
+ This is constructed dynamically by introspection gathering all
1278
+ the descriptors that are instances of the ParameterAttribute class.
1279
+ Parent classes of the parameter types are inspected as well.
1280
+
1281
+ Note that since Python 3.6 the order of the class attribute definition
1282
+ is preserved (see PEP 520) so this function will return the attribute
1283
+ in their declaration order.
1284
+
1285
+ Parameters
1286
+ ----------
1287
+ filter
1288
+ An optional function with signature filter(ParameterAttribute) -> bool.
1289
+ If specified, only attributes for which this functions returns
1290
+ True are returned.
1291
+
1292
+ Returns
1293
+ -------
1294
+ parameter_attributes[str, ParameterAttribute]
1295
+ A map from the name of the controlled parameter to the
1296
+ ParameterAttribute descriptor handling it.
1297
+
1298
+ Examples
1299
+ --------
1300
+ >>> parameter_attributes = ParameterType._get_parameter_attributes()
1301
+ >>> sorted(parameter_attributes.keys())
1302
+ ['id', 'parent_id', 'smirks']
1303
+ >>> isinstance(parameter_attributes['id'], ParameterAttribute)
1304
+ True
1305
+
1306
+ """
1307
+ # If no filter is specified, get all the parameters.
1308
+ if filter is None:
1309
+
1310
+ def filter(x):
1311
+ return True
1312
+
1313
+ # Go through MRO and retrieve also parents descriptors. The function
1314
+ # inspect.getmembers() automatically resolves the MRO, but it also
1315
+ # sorts the attribute alphabetically by name. Here we want the order
1316
+ # to be the same as the declaration order, which is guaranteed by PEP 520,
1317
+ # starting from the parent class.
1318
+ parameter_attributes = dict(
1319
+ (name, descriptor)
1320
+ for c in reversed(inspect.getmro(cls))
1321
+ for name, descriptor in c.__dict__.items()
1322
+ if isinstance(descriptor, ParameterAttribute) and filter(descriptor)
1323
+ )
1324
+ return parameter_attributes
1325
+
1326
+ @classmethod
1327
+ def _get_indexed_mapped_parameter_attributes(cls):
1328
+ """Shortcut to retrieve only IndexedMappedParameterAttributes."""
1329
+ return cls._get_parameter_attributes(filter=lambda x: isinstance(x, IndexedMappedParameterAttribute))
1330
+
1331
+ @classmethod
1332
+ def _get_indexed_parameter_attributes(cls):
1333
+ """Shortcut to retrieve only IndexedParameterAttributes."""
1334
+ return cls._get_parameter_attributes(filter=lambda x: isinstance(x, IndexedParameterAttribute))
1335
+
1336
+ @classmethod
1337
+ def _get_mapped_parameter_attributes(cls):
1338
+ """Shortcut to retrieve only IndexedParameterAttributes."""
1339
+ return cls._get_parameter_attributes(filter=lambda x: isinstance(x, MappedParameterAttribute))
1340
+
1341
+ @classmethod
1342
+ def _get_required_parameter_attributes(cls):
1343
+ """Shortcut to retrieve only required ParameterAttributes."""
1344
+ return cls._get_parameter_attributes(filter=lambda x: x.default is x.UNDEFINED)
1345
+
1346
+ @classmethod
1347
+ def _get_optional_parameter_attributes(cls):
1348
+ """Shortcut to retrieve only required ParameterAttributes."""
1349
+ return cls._get_parameter_attributes(filter=lambda x: x.default is not x.UNDEFINED)
1350
+
1351
+ def _get_defined_parameter_attributes(self):
1352
+ """Returns all the attributes except for the optional attributes that have None default value.
1353
+
1354
+ This returns first the required attributes and then the defined optional
1355
+ attribute in their respective declaration order.
1356
+ """
1357
+ required = self._get_required_parameter_attributes()
1358
+ optional = self._get_optional_parameter_attributes()
1359
+ # Filter the optional parameters that are set to their default.
1360
+ optional = dict(
1361
+ (name, descriptor)
1362
+ for name, descriptor in optional.items()
1363
+ if not (descriptor.default is None and getattr(self, name) == descriptor.default)
1364
+ )
1365
+ required.update(optional)
1366
+ return required
1367
+
1368
+
1369
+ # We can't actually make this derive from dict, because it's possible for the user to change SMIRKS
1370
+ # of parameters already in the list, which would cause the ParameterType object's SMIRKS and
1371
+ # the dictionary key's SMIRKS to be out of sync.
1372
+ class ParameterList(list):
1373
+ """
1374
+ Parameter list that also supports accessing items by SMARTS string.
1375
+
1376
+ .. warning :: This API is experimental and subject to change.
1377
+
1378
+ """
1379
+
1380
+ # TODO: Make this faster by caching SMARTS -> index lookup?
1381
+
1382
+ # TODO: Override __del__ to make sure we don't remove root atom type
1383
+
1384
+ # TODO: Allow retrieval by `id` as well
1385
+
1386
+ def __init__(
1387
+ self,
1388
+ input_parameter_list: list["ParameterType"] | None = None,
1389
+ ):
1390
+ """
1391
+ Initialize a new ParameterList, optionally providing a list of ParameterType objects
1392
+ to initially populate it.
1393
+
1394
+ Parameters
1395
+ ----------
1396
+ input_parameter_list
1397
+ A pre-existing list of ParameterType-based objects. If None, this ParameterList
1398
+ will be initialized empty.
1399
+ """
1400
+ super().__init__()
1401
+
1402
+ input_parameter_list = input_parameter_list or []
1403
+ # TODO: Should a ParameterList only contain a single kind of ParameterType?
1404
+ for input_parameter in input_parameter_list:
1405
+ self.append(input_parameter)
1406
+
1407
+ def append(self, parameter):
1408
+ """
1409
+ Add a ParameterType object to the end of the ParameterList
1410
+
1411
+ Parameters
1412
+ ----------
1413
+ parameter
1414
+
1415
+ """
1416
+ # TODO: Ensure that newly added parameter is the same type as existing?
1417
+ super().append(parameter)
1418
+
1419
+ def extend(self, other):
1420
+ """
1421
+ Add a ParameterList object to the end of the ParameterList
1422
+
1423
+ Parameters
1424
+ ----------
1425
+ other
1426
+
1427
+ """
1428
+ if not isinstance(other, ParameterList):
1429
+ msg = (
1430
+ "ParameterList.extend(other) expected instance of ParameterList, "
1431
+ f"but received {other} (type {type(other)}) instead"
1432
+ )
1433
+ raise TypeError(msg)
1434
+ # TODO: Check if other ParameterList contains the same ParameterTypes?
1435
+ super().extend(other)
1436
+
1437
+ def index(self, item, start=None, stop=None):
1438
+ """
1439
+ Get the numerical index of a ParameterType object or SMIRKS in this ParameterList.
1440
+ Raises ParameterLookupError if the item is not found.
1441
+
1442
+ Parameters
1443
+ ----------
1444
+ item
1445
+ The parameter or SMIRKS to look up in this ParameterList
1446
+ start
1447
+ Unsupported, added to align method signature with list.index
1448
+ stop
1449
+ Unsupported, added to align method signature with list.index
1450
+
1451
+ Returns
1452
+ -------
1453
+ index
1454
+ The index of the found item
1455
+
1456
+ Raises
1457
+ ------
1458
+ ParameterLookupError if SMIRKS pattern is passed in but not found
1459
+
1460
+ """
1461
+ if start is not None:
1462
+ raise TypeError("ParameterList.index does not support non-None values for start.")
1463
+ if stop is not None:
1464
+ raise TypeError("ParameterList.index does not support non-None values for stop.")
1465
+ if isinstance(item, ParameterType):
1466
+ return super().index(item)
1467
+ else:
1468
+ for parameter in self[::-1]:
1469
+ if parameter.smirks == item:
1470
+ return self.index(parameter)
1471
+ raise ParameterLookupError(f"SMIRKS {item} not found in ParameterList")
1472
+
1473
+ def insert(self, index, parameter):
1474
+ """
1475
+ Add a ParameterType object as if this were a list
1476
+
1477
+ Parameters
1478
+ ----------
1479
+ index
1480
+ The numerical position to insert the parameter at
1481
+ parameter
1482
+ The parameter to insert
1483
+ """
1484
+ # TODO: Ensure that newly added parameter is the same type as existing?
1485
+ super().insert(index, parameter)
1486
+
1487
+ def __delitem__(self, item):
1488
+ """
1489
+ Delete item by index or SMIRKS.
1490
+
1491
+ Parameters
1492
+ ----------
1493
+ item
1494
+ SMIRKS or numerical index of item in this ParameterList
1495
+ """
1496
+ if type(item) is int:
1497
+ index = item
1498
+ else:
1499
+ # Try to find by SMIRKS
1500
+ index = self.index(item)
1501
+ super().__delitem__(index)
1502
+
1503
+ def __getitem__(self, item: Union[int, slice, str, "ParameterType"]): # type: ignore[override]
1504
+ """
1505
+ Retrieve item by index or SMIRKS. If multiple parameters have the same
1506
+ SMIRKS, this returns the last one.
1507
+
1508
+ Parameters
1509
+ ----------
1510
+ item
1511
+ SMIRKS or numerical index of item in this ParameterList
1512
+ """
1513
+ if type(item) in (int, slice):
1514
+ indexable_item: int | slice = item # type: ignore[assignment]
1515
+ elif isinstance(item, str):
1516
+ indexable_item = self.index(item)
1517
+ elif isinstance(item, ParameterType) or issubclass(type(item), ParameterType):
1518
+ raise ParameterLookupError("Lookup by instance is not supported")
1519
+ return super().__getitem__(indexable_item)
1520
+
1521
+ # TODO: Override __setitem__ and __del__ to ensure we can slice by SMIRKS as well
1522
+ # This is needed for pickling. See https://github.com/openforcefield/openff-toolkit/issues/411
1523
+ # for more details.
1524
+ # TODO: Is there a cleaner way (getstate/setstate perhaps?) to allow FFs to be
1525
+ # pickled?
1526
+ def __reduce__(self):
1527
+ return (__class__, (list(self),), self.__dict__)
1528
+
1529
+ def __contains__(self, item):
1530
+ """Check to see if either Parameter or SMIRKS is contained in parameter list.
1531
+
1532
+ Parameters
1533
+ ----------
1534
+ item
1535
+ SMIRKS of item in this ParameterList
1536
+ """
1537
+ if isinstance(item, str):
1538
+ # Special case for SMIRKS strings
1539
+ if item in [result.smirks for result in self]:
1540
+ return True
1541
+ # Fall back to traditional access
1542
+ return list.__contains__(self, item)
1543
+
1544
+ def to_list(self, discard_cosmetic_attributes=True):
1545
+ """
1546
+ Render this ParameterList to a normal list, serializing each ParameterType object in it to dict.
1547
+
1548
+ Parameters
1549
+ ----------
1550
+
1551
+ discard_cosmetic_attributes
1552
+ Whether to discard non-spec attributes of each ParameterType object.
1553
+
1554
+ Returns
1555
+ -------
1556
+ parameter_list :list[dict]
1557
+ A serialized representation of a ParameterList, with each ParameterType it contains converted to dict.
1558
+ """
1559
+ parameter_list = list()
1560
+
1561
+ for parameter in self:
1562
+ parameter_dict = parameter.to_dict(discard_cosmetic_attributes=discard_cosmetic_attributes)
1563
+ parameter_list.append(parameter_dict)
1564
+
1565
+ return parameter_list
1566
+
1567
+
1568
+ class VirtualSiteParameterList(ParameterList):
1569
+ def __getitem__(self, val: Union[int, slice, str, "ParameterType"]): # type: ignore[override]
1570
+ indexable_item: int | slice
1571
+
1572
+ if isinstance(val, int):
1573
+ indexable_item = val
1574
+ elif isinstance(val, slice):
1575
+ assert type(val.start) is int and type(val.stop) is int, "slices must be based on ints"
1576
+ indexable_item = val
1577
+ else:
1578
+ raise NotImplementedError(
1579
+ "VirtualSiteHandler does not support __getitem__ lookups "
1580
+ f"of this type ({type(val)=}) due to the "
1581
+ "number of values required to uniquely identify a specific parameter."
1582
+ )
1583
+
1584
+ return super().__getitem__(indexable_item)
1585
+
1586
+
1587
+ # TODO: Rename to better reflect role as parameter base class?
1588
+ class ParameterType(_ParameterAttributeHandler):
1589
+ r"""
1590
+ Base class for SMIRNOFF parameter types.
1591
+
1592
+ This base class provides utilities to create new parameter types. See
1593
+ the below for examples of how to do this.
1594
+
1595
+ .. warning :: This API is experimental and subject to change.
1596
+
1597
+ Attributes
1598
+ ----------
1599
+ smirks
1600
+ The SMIRKS pattern that this parameter matches.
1601
+ id
1602
+ An optional identifier for the parameter.
1603
+ parent_id
1604
+ Optionally, the identifier of the parameter of which this parameter
1605
+ is a specialization.
1606
+
1607
+ See Also
1608
+ --------
1609
+ ParameterAttribute
1610
+ IndexedParameterAttribute
1611
+
1612
+ Examples
1613
+ --------
1614
+
1615
+ This class allows to define new parameter types by just listing its
1616
+ attributes. In the example below, ``_ELEMENT_NAME`` is used to
1617
+ describe the SMIRNOFF parameter being defined, and is used during
1618
+ automatic serialization/deserialization into a ``dict``.
1619
+
1620
+ >>> class MyBondParameter(ParameterType):
1621
+ ... _ELEMENT_NAME = 'Bond'
1622
+ ... length = ParameterAttribute(unit=unit.angstrom)
1623
+ ... k = ParameterAttribute(unit=unit.kilocalorie / unit.mole / unit.angstrom**2)
1624
+ ...
1625
+
1626
+ The parameter automatically inherits the required smirks attribute
1627
+ from ``ParameterType``. Associating a ``unit`` to a ``ParameterAttribute``
1628
+ cause the attribute to accept only values in compatible units and to
1629
+ parse string expressions.
1630
+
1631
+ >>> my_par = MyBondParameter(
1632
+ ... smirks='[*:1]-[*:2]',
1633
+ ... length='1.01 * angstrom',
1634
+ ... k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2
1635
+ ... )
1636
+ >>> my_par.length
1637
+ <Quantity(1.01, 'angstrom')>
1638
+ >>> my_par.k = 3.0 * unit.gram # doctest: +ELLIPSIS
1639
+ Traceback (most recent call last):
1640
+ ...
1641
+ openff.toolkit.utils.exceptions.IncompatibleUnitError: k=3.0 gram should have units of kilocalorie / angstrom ** 2 / mole
1642
+
1643
+ Each attribute can be made optional by specifying a default value,
1644
+ and you can attach a converter function by passing a callable as an
1645
+ argument or through the decorator syntax.
1646
+
1647
+ >>> class MyParameterType(ParameterType):
1648
+ ... _ELEMENT_NAME = 'Atom'
1649
+ ...
1650
+ ... attr_optional = ParameterAttribute(default=2)
1651
+ ... attr_all_to_float = ParameterAttribute(converter=float)
1652
+ ... attr_int_to_float = ParameterAttribute()
1653
+ ...
1654
+ ... @attr_int_to_float.converter
1655
+ ... def attr_int_to_float(self, attr, value):
1656
+ ... # This converter converts only integers to floats
1657
+ ... # and raise an exception for the other types.
1658
+ ... if isinstance(value, int):
1659
+ ... return float(value)
1660
+ ... elif not isinstance(value, float):
1661
+ ... raise TypeError(f"Cannot convert '{value}' to float")
1662
+ ... return value
1663
+ ...
1664
+ >>> my_par = MyParameterType(smirks='[*:1]', attr_all_to_float='3.0', attr_int_to_float=1)
1665
+ >>> my_par.attr_optional
1666
+ 2
1667
+ >>> my_par.attr_all_to_float
1668
+ 3.0
1669
+ >>> my_par.attr_int_to_float
1670
+ 1.0
1671
+
1672
+ The float() function can convert strings to integers, but our custom
1673
+ converter forbids it
1674
+
1675
+ >>> my_par.attr_all_to_float = '2.0'
1676
+ >>> my_par.attr_int_to_float = '4.0'
1677
+ Traceback (most recent call last):
1678
+ ...
1679
+ TypeError: Cannot convert '4.0' to float
1680
+
1681
+ Parameter attributes that can be indexed can be handled with the
1682
+ ``IndexedParameterAttribute``. These support unit validation and
1683
+ converters exactly as ``ParameterAttribute``\ s, but the validation/conversion
1684
+ is performed for each indexed attribute.
1685
+
1686
+ >>> class MyTorsionType(ParameterType):
1687
+ ... _ELEMENT_NAME = 'Proper'
1688
+ ... periodicity = IndexedParameterAttribute(converter=int)
1689
+ ... k = IndexedParameterAttribute(unit=unit.kilocalorie / unit.mole)
1690
+ ...
1691
+ >>> my_par = MyTorsionType(
1692
+ ... smirks='[*:1]-[*:2]-[*:3]-[*:4]',
1693
+ ... periodicity1=2,
1694
+ ... k1=5 * unit.kilocalorie / unit.mole,
1695
+ ... periodicity2='3',
1696
+ ... k2=6 * unit.kilocalorie / unit.mole,
1697
+ ... )
1698
+ >>> my_par.periodicity
1699
+ [2, 3]
1700
+
1701
+ Indexed attributes, can be accessed both as a list or as their indexed
1702
+ parameter name.
1703
+
1704
+ >>> my_par.periodicity2 = 6
1705
+ >>> my_par.periodicity[0] = 1
1706
+ >>> my_par.periodicity
1707
+ [1, 6]
1708
+
1709
+ """ # noqa: E501
1710
+
1711
+ # The string mapping to this ParameterType in a SMIRNOFF data source
1712
+ _ELEMENT_NAME: str | None = None
1713
+
1714
+ # Parameter attributes shared among all parameter types.
1715
+ smirks = ParameterAttribute()
1716
+ id = ParameterAttribute(default=None)
1717
+ parent_id = ParameterAttribute(default=None)
1718
+
1719
+ def __init__(self, smirks, allow_cosmetic_attributes=False, **kwargs):
1720
+ """
1721
+ Create a ParameterType.
1722
+
1723
+ Parameters
1724
+ ----------
1725
+ smirks
1726
+ The SMIRKS match for the provided parameter type.
1727
+ allow_cosmetic_attributes
1728
+ Whether to permit non-spec kwargs ("cosmetic attributes"). If True, non-spec kwargs will be stored as
1729
+ an attribute of this parameter which can be accessed and written out. Otherwise an exception will
1730
+ be raised.
1731
+
1732
+ """
1733
+ # This is just to make smirks a required positional argument.
1734
+ kwargs["smirks"] = smirks
1735
+ super().__init__(allow_cosmetic_attributes=allow_cosmetic_attributes, **kwargs)
1736
+
1737
+ def __repr__(self):
1738
+ ret_str = f"<{self.__class__.__name__} with "
1739
+ for attr, val in self.to_dict().items():
1740
+ ret_str += f"{attr}: {val} "
1741
+ ret_str += ">"
1742
+ return ret_str
1743
+
1744
+
1745
+ # TODO: Should we have a parameter handler registry?
1746
+
1747
+
1748
+ class ParameterHandler(_ParameterAttributeHandler):
1749
+ """Base class for parameter handlers.
1750
+
1751
+ Parameter handlers are configured with some global parameters for a
1752
+ given section. They may also contain a :class:`ParameterList` populated
1753
+ with :class:`ParameterType` objects if they are responsible for assigning
1754
+ SMIRKS-based parameters.
1755
+
1756
+ .. warning
1757
+
1758
+ Parameter handler objects can only belong to a single :class:`ForceField` object.
1759
+ If you need to create a copy to attach to a different :class:`ForceField` object,
1760
+ use ``create_copy()``.
1761
+
1762
+ .. warning :: This API is experimental and subject to change.
1763
+
1764
+ """
1765
+
1766
+ # str of section type handled by this ParameterHandler (XML element name for SMIRNOFF XML representation)
1767
+ _TAGNAME: str | None = None
1768
+ # container class with type information that will be stored in self._parameters
1769
+ _INFOTYPE: Any | None = None
1770
+ # list of ParameterHandler classes that must precede this, or None
1771
+ _DEPENDENCIES: Any | None = None
1772
+
1773
+ # Kwargs to catch when create_force is called
1774
+ _KWARGS: list[str] = []
1775
+ # the earliest version of SMIRNOFF spec that supports this ParameterHandler
1776
+ _SMIRNOFF_VERSION_INTRODUCED = 0.0
1777
+ _SMIRNOFF_VERSION_DEPRECATED = None
1778
+ # if deprecated, the first SMIRNOFF version number it is no longer used
1779
+ _MIN_SUPPORTED_SECTION_VERSION = Version("0.3")
1780
+ _MAX_SUPPORTED_SECTION_VERSION = Version("0.3")
1781
+
1782
+ version = ParameterAttribute()
1783
+
1784
+ @version.converter # type: ignore[no-redef]
1785
+ def version(self, attr, new_version):
1786
+ """
1787
+ Raise a parsing exception if the given section version is unsupported.
1788
+
1789
+ Raises
1790
+ ------
1791
+ SMIRNOFFVersionError if an incompatible version is passed in.
1792
+
1793
+ """
1794
+ from openff.toolkit.utils.exceptions import SMIRNOFFVersionError
1795
+
1796
+ if isinstance(new_version, Version):
1797
+ pass
1798
+ elif isinstance(new_version, str):
1799
+ new_version = Version(new_version)
1800
+ elif isinstance(new_version, float | int):
1801
+ new_version = Version(str(new_version))
1802
+ else:
1803
+ raise ValueError(f"Could not convert type {type(new_version)}")
1804
+
1805
+ # Use PEP-440 compliant version number comparison, if requested
1806
+ if (new_version > self._MAX_SUPPORTED_SECTION_VERSION) or (new_version < self._MIN_SUPPORTED_SECTION_VERSION):
1807
+ raise SMIRNOFFVersionError(
1808
+ f"SMIRNOFF offxml file was written with version {new_version}, but this version "
1809
+ f"of ForceField only supports version {self._MIN_SUPPORTED_SECTION_VERSION} "
1810
+ f"to version {self._MAX_SUPPORTED_SECTION_VERSION}"
1811
+ )
1812
+ return new_version
1813
+
1814
+ def __init__(self, allow_cosmetic_attributes=False, skip_version_check=False, **kwargs):
1815
+ """
1816
+ Initialize a ParameterHandler, optionally with a list of parameters and other kwargs.
1817
+
1818
+ Parameters
1819
+ ----------
1820
+ allow_cosmetic_attributes
1821
+ Whether to permit non-spec kwargs. If True, non-spec kwargs will be stored as attributes of this object
1822
+ and can be accessed and modified. Otherwise an exception will be raised if a non-spec kwarg is encountered.
1823
+ skip_version_check: bool, optional. Default = False
1824
+ If False, the SMIRNOFF section version will not be checked, and the ParameterHandler will be initialized
1825
+ with version set to _MAX_SUPPORTED_SECTION_VERSION.
1826
+ **kwargs
1827
+ The dict representation of the SMIRNOFF data source
1828
+
1829
+ """
1830
+ # Skip version check if requested.
1831
+ if "version" not in kwargs:
1832
+ if skip_version_check:
1833
+ kwargs["version"] = self._MAX_SUPPORTED_SECTION_VERSION
1834
+ else:
1835
+ raise SMIRNOFFSpecError(
1836
+ f"Missing version while trying to construct {self.__class__}. "
1837
+ f"0.3 SMIRNOFF spec requires each parameter section to have its own version."
1838
+ )
1839
+
1840
+ # List of ParameterType objects (also behaves like a dict where keys are SMARTS).
1841
+ self._parameters = ParameterList()
1842
+
1843
+ # Initialize ParameterAttributes and cosmetic attributes.
1844
+ super().__init__(allow_cosmetic_attributes=allow_cosmetic_attributes, **kwargs)
1845
+
1846
+ def _add_parameters(self, section_dict, allow_cosmetic_attributes=False):
1847
+ """
1848
+ Extend the ParameterList in this ParameterHandler using a SMIRNOFF data source.
1849
+
1850
+ Parameters
1851
+ ----------
1852
+ section_dict
1853
+ The dict representation of a SMIRNOFF data source containing parameters to att to this ParameterHandler
1854
+ allow_cosmetic_attributes
1855
+ Whether to allow non-spec fields in section_dict. If True, non-spec kwargs will be stored as an
1856
+ attribute of the parameter. If False, non-spec kwargs will raise an exception.
1857
+
1858
+ """
1859
+ for key, val in section_dict.items():
1860
+ if self._INFOTYPE is not None:
1861
+ element_name = self._INFOTYPE._ELEMENT_NAME
1862
+ # Skip sections that aren't the parameter list
1863
+ if key != element_name:
1864
+ break
1865
+ # If there are multiple parameters, this will be a list. If there's just one, make it a list
1866
+ if not (isinstance(val, list)):
1867
+ val = [val]
1868
+
1869
+ # If we're reading the parameter list, iterate through and attach units to
1870
+ # each parameter_dict, then use it to initialize a ParameterType
1871
+ for param_dict in val:
1872
+ new_parameter = self._INFOTYPE(**param_dict, allow_cosmetic_attributes=allow_cosmetic_attributes)
1873
+ self._parameters.append(new_parameter)
1874
+
1875
+ @property
1876
+ def parameters(self):
1877
+ """The ParameterList that holds this ParameterHandler's parameter objects"""
1878
+ return self._parameters
1879
+
1880
+ @property
1881
+ def TAGNAME(self):
1882
+ """
1883
+ The name of this ParameterHandler corresponding to the SMIRNOFF tag name
1884
+
1885
+ Returns
1886
+ -------
1887
+ handler_name
1888
+ The name of this parameter handler
1889
+
1890
+ """
1891
+ return self._TAGNAME
1892
+
1893
+ # TODO: Do we need to return these, or can we handle this internally
1894
+ @property
1895
+ def known_kwargs(self):
1896
+ """List of kwargs that can be parsed by the function."""
1897
+ # TODO: Should we use introspection to inspect the function signature instead?
1898
+ return set(self._KWARGS)
1899
+
1900
+ def check_handler_compatibility(self, handler_kwargs):
1901
+ """
1902
+ Checks if a set of kwargs used to create a ParameterHandler are compatible with this ParameterHandler. This is
1903
+ called if a second handler is attempted to be initialized for the same tag.
1904
+
1905
+ Parameters
1906
+ ----------
1907
+ handler_kwargs
1908
+ The kwargs that would be used to construct
1909
+
1910
+ Raises
1911
+ ------
1912
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
1913
+ """
1914
+ pass
1915
+
1916
+ def _index_of_parameter(self, parameter: ParameterType | None = None, key: Any | None = None) -> int | None:
1917
+ """Attempts to find the index of a parameter in the parameters list.
1918
+
1919
+ By default, two parameters are considered 'the same' if they have the same
1920
+ SMIRKS pattern.
1921
+
1922
+ Parameters
1923
+ ----------
1924
+ parameter
1925
+ The parameter to find the index of. This argument is mutually exclusive with
1926
+ ``key``.
1927
+ key
1928
+ The SMIRKS pattern associated with the parameter to find the index
1929
+ of. This argument is mutually exclusive with ``parameter``.
1930
+
1931
+ Returns
1932
+ -------
1933
+ The index of the parameter if found, otherwise ``None``.
1934
+ """
1935
+
1936
+ if (key is None and parameter is None) or (key is not None and parameter is not None):
1937
+ raise ValueError("`key` and `parameter` are mutually exclusive arguments")
1938
+
1939
+ key = key if parameter is None else parameter.smirks
1940
+
1941
+ for index, existing_parameter in enumerate(self._parameters):
1942
+ if existing_parameter.smirks != key:
1943
+ continue
1944
+
1945
+ return index
1946
+
1947
+ return None
1948
+
1949
+ # TODO: Can we ensure SMIRKS and other parameters remain valid after manipulation?
1950
+ def add_parameter(
1951
+ self,
1952
+ parameter_kwargs: dict | None = None,
1953
+ parameter: ParameterType | None = None,
1954
+ after: int | str | None = None,
1955
+ before: int | str | None = None,
1956
+ allow_duplicate_smirks: bool = False,
1957
+ ):
1958
+ """Add a parameter to the force field, ensuring all parameters are valid.
1959
+
1960
+ Parameters
1961
+ ----------
1962
+ parameter_kwargs
1963
+ The kwargs to pass to the ParameterHandler.INFOTYPE (a ParameterType) constructor
1964
+ parameter
1965
+ A ParameterType to add to the ParameterHandler
1966
+ after
1967
+ The SMIRKS pattern (if str) or index (if int) of the parameter directly before where
1968
+ the new parameter will be added
1969
+ before
1970
+ The SMIRKS pattern (if str) or index (if int) of the parameter directly after where
1971
+ the new parameter will be added
1972
+ allow_duplicate_smirks
1973
+ If False, a DuplicateParameterError will be raised if the parameter being added has
1974
+ a SMIRKS that already appears in another parameter owned by this ParameterHandler.
1975
+
1976
+ Note the following behavior:
1977
+ * Either `parameter_kwargs` or `parameter` must be specified.
1978
+ * When `before` and `after` are both `None`, the new parameter will be appended
1979
+ to the **END** of the parameter list.
1980
+ * When `before` and `after` are both specified, the new parameter will be added immediately
1981
+ after the parameter matching the `after` pattern or index.
1982
+ * The order of parameters in a parameter list can have significant impacts on parameter assignment. For
1983
+ details, see the SMIRNOFF specification:
1984
+ https://openforcefield.github.io/standards/standards/smirnoff/#smirnoff-parameter-specification-is-hierarchical
1985
+
1986
+ Examples
1987
+ --------
1988
+
1989
+ Add a ParameterType to an existing ParameterList at a specified position.
1990
+
1991
+ Given an existing parameter handler and a new parameter to add to it:
1992
+
1993
+ >>> from openff.toolkit import unit
1994
+ >>> bh = BondHandler(skip_version_check=True)
1995
+ >>> length = 1.5 * unit.angstrom
1996
+ >>> k = 100 * unit.kilocalorie / unit.mole / unit.angstrom ** 2
1997
+ >>> bh.add_parameter({'smirks': '[*:1]-[*:2]', 'length': length, 'k': k, 'id': 'b1'})
1998
+ >>> bh.add_parameter({'smirks': '[*:1]=[*:2]', 'length': length, 'k': k, 'id': 'b2'})
1999
+ >>> bh.add_parameter({'smirks': '[*:1]#[*:2]', 'length': length, 'k': k, 'id': 'b3'})
2000
+ >>> [p.id for p in bh.parameters]
2001
+ ['b1', 'b2', 'b3']
2002
+
2003
+ >>> param = {'smirks': '[#1:1]-[#6:2]', 'length': length, 'k': k, 'id': 'b4'}
2004
+
2005
+ Add a new parameter immediately after the parameter with the smirks '[*:1]=[*:2]'
2006
+
2007
+ >>> bh.add_parameter(param, after='[*:1]=[*:2]')
2008
+ >>> [p.id for p in bh.parameters]
2009
+ ['b1', 'b2', 'b4', 'b3']
2010
+ """
2011
+ for val in [before, after]:
2012
+ if val and not isinstance(val, str | int):
2013
+ raise TypeError
2014
+
2015
+ # If a dict was passed, construct it; if a ParameterType was passed, do nothing
2016
+ if parameter_kwargs:
2017
+ # here we are using the INFOTYPE to construct a new parameter
2018
+ # and at this poitn we expect parameter_kwargs to be a dict
2019
+ new_parameter = self._INFOTYPE(**parameter_kwargs) # type: ignore[misc]
2020
+ elif parameter:
2021
+ new_parameter = parameter
2022
+ else:
2023
+ raise ValueError("One of (parameter, parameter_kwargs) must be specified")
2024
+
2025
+ if not allow_duplicate_smirks:
2026
+ if self._index_of_parameter(new_parameter) is not None:
2027
+ msg = f"A parameter SMIRKS pattern {new_parameter.smirks} already exists."
2028
+ raise DuplicateParameterError(msg)
2029
+
2030
+ before_index, after_index = None, None
2031
+
2032
+ if before is not None:
2033
+ if isinstance(before, int):
2034
+ before_index = before
2035
+ else:
2036
+ before_index = self._index_of_parameter(key=before)
2037
+
2038
+ if after is not None:
2039
+ if isinstance(after, int):
2040
+ after_index = after
2041
+ else:
2042
+ after_index = self._index_of_parameter(key=after)
2043
+
2044
+ if None not in (before, after):
2045
+ if after_index > before_index: # type: ignore[operator]
2046
+ raise ValueError("before arg must be before after arg")
2047
+
2048
+ if after is not None:
2049
+ self._parameters.insert(after_index + 1, new_parameter) # type: ignore[operator]
2050
+ elif before is not None:
2051
+ self._parameters.insert(before_index, new_parameter)
2052
+ else:
2053
+ self._parameters.append(new_parameter)
2054
+
2055
+ def get_parameter(self, parameter_attrs):
2056
+ """
2057
+ Return the parameters in this ParameterHandler that match the parameter_attrs argument.
2058
+ When multiple attrs are passed, parameters that have any (not all) matching attributes
2059
+ are returned.
2060
+
2061
+ Parameters
2062
+ ----------
2063
+ parameter_attrs
2064
+ The attrs mapped to desired values (for example {"smirks": "[*:1]~[#16:2]=,:[#6:3]~[*:4]", "id": "t105"} )
2065
+
2066
+ Returns
2067
+ -------
2068
+ params
2069
+ A list of matching ParameterType objects
2070
+
2071
+ Examples
2072
+ --------
2073
+
2074
+ Create a parameter handler and populate it with some data.
2075
+
2076
+ >>> from openff.toolkit import unit
2077
+ >>> handler = BondHandler(skip_version_check=True)
2078
+ >>> handler.add_parameter(
2079
+ ... {
2080
+ ... 'smirks': '[*:1]-[*:2]',
2081
+ ... 'length': 1*unit.angstrom,
2082
+ ... 'k': 10*unit.kilocalorie / unit.mole/unit.angstrom**2,
2083
+ ... }
2084
+ ... )
2085
+
2086
+ Look up, from this handler, all parameters matching some SMIRKS pattern
2087
+
2088
+ >>> handler.get_parameter({'smirks': '[*:1]-[*:2]'})
2089
+ [<BondType with smirks: [*:1]-[*:2] length: 1 angstrom k: 10.0 kilocalorie / angstrom ** 2 / mole >]
2090
+
2091
+ """
2092
+ params = list()
2093
+ for attr, value in parameter_attrs.items():
2094
+ for param in self.parameters:
2095
+ if param in params:
2096
+ continue
2097
+ # TODO: Cleaner accessing of cosmetic attributes
2098
+ # See issue #338
2099
+ if param.attribute_is_cosmetic(attr):
2100
+ attr = "_" + attr
2101
+ if hasattr(param, attr):
2102
+ if getattr(param, attr) == value:
2103
+ params.append(param)
2104
+ return params
2105
+
2106
+ class _Match:
2107
+ """Represents a ParameterType which has been matched to
2108
+ a given chemical environment.
2109
+ """
2110
+
2111
+ @property
2112
+ def parameter_type(self):
2113
+ """ParameterType: The matched parameter type."""
2114
+ return self._parameter_type
2115
+
2116
+ @property
2117
+ def environment_match(self):
2118
+ """Topology._ChemicalEnvironmentMatch: The environment which matched the type."""
2119
+ return self._environment_match
2120
+
2121
+ def __init__(self, parameter_type: ParameterType, environment_match):
2122
+ """Constructs a new ParameterHandlerMatch object.
2123
+
2124
+ Parameters
2125
+ ----------
2126
+ parameter_type: ParameterType
2127
+ The matched parameter type.
2128
+ environment_match: Topology._ChemicalEnvironmentMatch
2129
+ The environment which matched the type.
2130
+ """
2131
+ self._parameter_type = parameter_type
2132
+ self._environment_match = environment_match
2133
+
2134
+ def find_matches(self, entity: Topology, unique: bool = False) -> ValenceDict:
2135
+ """Find the elements of the topology/molecule matched by a parameter type.
2136
+
2137
+ Parameters
2138
+ ----------
2139
+ entity
2140
+ Topology to search.
2141
+ unique
2142
+ If False, SMARTS matching will enumerate every valid permutation of matching atoms.
2143
+ If True, only one order of each unique match will be returned.
2144
+
2145
+ Returns
2146
+ ---------
2147
+ matches
2148
+ ``matches[atom_indices]`` is the ``ParameterType`` object
2149
+ matching the tuple of atom indices in ``entity``.
2150
+ """
2151
+
2152
+ return self._find_matches(entity, unique=unique)
2153
+
2154
+ def _find_matches(
2155
+ self,
2156
+ entity: Topology,
2157
+ transformed_dict_cls: type = ValenceDict,
2158
+ unique=False,
2159
+ ):
2160
+ """Implement find_matches() and allow using a difference valence dictionary.
2161
+ Parameters
2162
+ ----------
2163
+ entity
2164
+ Topology to search.
2165
+ transformed_dict_cls: class
2166
+ The type of dictionary to store the matches in. This
2167
+ will determine how groups of atom indices are stored
2168
+ and accessed (e.g for angles indices should be 0-1-2
2169
+ and not 2-1-0).
2170
+ unique
2171
+ If False, SMARTS matching will enumerate every valid permutation of matching atoms.
2172
+ If True, only one order of each unique match will be returned.
2173
+
2174
+ Returns
2175
+ ---------
2176
+ matches
2177
+ ``matches[atom_indices]`` is the ``ParameterType`` object
2178
+ matching the tuple of atom indices in ``entity``.
2179
+ """
2180
+ logger.debug(f"Finding matches for {self.__class__.__name__}")
2181
+
2182
+ matches = transformed_dict_cls()
2183
+
2184
+ # TODO: There are probably performance gains to be had here
2185
+ # by performing this loop in reverse order, and breaking early once
2186
+ # all environments have been matched.
2187
+ for parameter_type in self._parameters:
2188
+ matches_for_this_type = {}
2189
+
2190
+ for environment_match in entity.chemical_environment_matches(
2191
+ parameter_type.smirks,
2192
+ unique=unique,
2193
+ ):
2194
+ # Update the matches for this parameter type.
2195
+ handler_match = self._Match(parameter_type, environment_match)
2196
+ matches_for_this_type[environment_match.topology_atom_indices] = handler_match
2197
+
2198
+ # Update matches of all parameter types.
2199
+ matches.update(matches_for_this_type)
2200
+
2201
+ logger.debug(f"{parameter_type.smirks:64} : {len(matches_for_this_type):8} matches")
2202
+
2203
+ logger.debug(f"{len(matches)} matches identified")
2204
+ return matches
2205
+
2206
+ @staticmethod
2207
+ def _assert_correct_connectivity(match, expected_connectivity=None):
2208
+ """A more performant version of the `topology.assert_bonded` method
2209
+ to ensure that the results of `_find_matches` are valid.
2210
+ Raises
2211
+ ------
2212
+ ValueError
2213
+ Raise an exception when the atoms in the match don't have
2214
+ the correct connectivity.
2215
+ Parameters
2216
+ ----------
2217
+ match: ParameterHandler._Match
2218
+ The match found by `_find_matches`
2219
+ connectivity: list of tuple of int, optional
2220
+ The expected connectivity of the match (e.g. for a torsion
2221
+ expected_connectivity=[(0, 1), (1, 2), (2, 3)]). If `None`,
2222
+ a connectivity of [(0, 1), ... (n - 1, n)] is assumed.
2223
+ """
2224
+
2225
+ # I'm not 100% sure this is really necessary... but this should do
2226
+ # the same checks as the more costly assert_bonded method in the
2227
+ # ParameterHandler.create_force methods.
2228
+ if expected_connectivity is None:
2229
+ return
2230
+
2231
+ reference_molecule = match.environment_match.reference_molecule
2232
+
2233
+ for connectivity in expected_connectivity:
2234
+ atom_i = match.environment_match.reference_atom_indices[connectivity[0]]
2235
+ atom_j = match.environment_match.reference_atom_indices[connectivity[1]]
2236
+
2237
+ reference_molecule.get_bond_between(atom_i, atom_j)
2238
+
2239
+ def create_force(self, *args, **kwarsg):
2240
+ """
2241
+ .. deprecated:: 0.11.0
2242
+
2243
+ This method was deprecated in v0.11.0, no longer has any
2244
+ functionality, and will soon be removed. Use the `OpenFF Interchange
2245
+ <https://docs.openforcefield.org/interchange>`_ package instead.
2246
+ """
2247
+ raise NotImplementedError(
2248
+ "`ParameterHandler`s no longer create OpenMM forces. Use `openff-interchange` instead."
2249
+ )
2250
+
2251
+ def to_dict(
2252
+ self,
2253
+ discard_cosmetic_attributes: bool = False,
2254
+ duplciate_attributes: list[str] | None = None,
2255
+ ) -> dict[str, dict | list | str]:
2256
+ """
2257
+ Convert this ParameterHandler to a dict, compliant with the SMIRNOFF data spec.
2258
+
2259
+ Parameters
2260
+ ----------
2261
+ discard_cosmetic_attributes
2262
+ Whether to discard non-spec parameter and header attributes in this ParameterHandler.
2263
+
2264
+ Returns
2265
+ -------
2266
+ smirnoff_data
2267
+ SMIRNOFF-spec compliant representation of this ParameterHandler and its internal ParameterList.
2268
+
2269
+ """
2270
+ parameter_dict: dict[str, dict | list | str] = dict()
2271
+
2272
+ # Populate parameter list
2273
+ parameter_list = self._parameters.to_list(discard_cosmetic_attributes=discard_cosmetic_attributes)
2274
+
2275
+ # NOTE: This assumes that a ParameterHandler will have just one homogenous ParameterList under it
2276
+ if self._INFOTYPE is not None:
2277
+ # smirnoff_data[self._INFOTYPE._ELEMENT_NAME] = unitless_parameter_list
2278
+ parameter_dict[self._INFOTYPE._ELEMENT_NAME] = parameter_list
2279
+
2280
+ # Collect parameter and cosmetic attributes.
2281
+ header_attribute_dict: dict[str, dict | list | str] = super().to_dict(
2282
+ discard_cosmetic_attributes=discard_cosmetic_attributes
2283
+ )
2284
+ # import ipdb; ipdb.set_trace()
2285
+ parameter_dict.update(header_attribute_dict)
2286
+
2287
+ return parameter_dict
2288
+
2289
+ def _check_attributes_are_equal(
2290
+ self,
2291
+ other: "ParameterHandler",
2292
+ identical_attrs: tuple[str, ...] = tuple(),
2293
+ tolerance_attrs: tuple[str, ...] = tuple(),
2294
+ tolerance: float = 1e-6,
2295
+ ):
2296
+ """Utility function to check that the given attributes of the two handlers are equal.
2297
+
2298
+ Parameters
2299
+ ----------
2300
+ other
2301
+ The other handler
2302
+ identical_attrs
2303
+ Names of the parameters that must be checked with the equality operator.
2304
+ tolerance_attrs
2305
+ Names of the parameters that must be equal up to a tolerance.
2306
+ tolerance
2307
+ The absolute tolerance used to compare the parameters.
2308
+ """
2309
+
2310
+ def get_unitless_values(attr):
2311
+ this_val = getattr(self, attr)
2312
+ other_val = getattr(other, attr)
2313
+ # Strip quantities of their units before comparison.
2314
+ try:
2315
+ this_val.units
2316
+ except AttributeError:
2317
+ return this_val, other_val
2318
+ assert this_val.units == other_val.units
2319
+ return this_val.m, other_val.m
2320
+
2321
+ for attr in identical_attrs:
2322
+ this_val, other_val = get_unitless_values(attr)
2323
+
2324
+ if this_val != other_val:
2325
+ msg = (
2326
+ f"{attr} values are not identical. (handler value: '{this_val}', "
2327
+ f"incompatible value: '{other_val}').\n"
2328
+ )
2329
+ if "AM1-Wiberg" in (this_val, other_val) and "none" in (
2330
+ this_val,
2331
+ other_val,
2332
+ ):
2333
+ msg += (
2334
+ "This likely results from mixing bond handlers with different versions "
2335
+ "(0.3 and 0.4). Consider upgrading bond handlers to version 0.4 or "
2336
+ "manually setting `fractional_bondorder_method='AM1-Wiberg'`."
2337
+ )
2338
+ raise IncompatibleParameterError(msg)
2339
+
2340
+ for attr in tolerance_attrs:
2341
+ try:
2342
+ this_val, other_val = get_unitless_values(attr)
2343
+ except AttributeError:
2344
+ raise AttributeError(f"Mismatch found with attr={attr}, this_val={this_val}, other_val={other_val}")
2345
+ if abs(this_val - other_val) > tolerance:
2346
+ raise IncompatibleParameterError(
2347
+ f"Difference between '{attr}' values is beyond allowed tolerance {tolerance}. "
2348
+ f"(handler value: {this_val}, incompatible value: {other_val}"
2349
+ )
2350
+
2351
+ def __getitem__(self, val):
2352
+ """
2353
+ Syntax sugar for looking up a ParameterType in a ParameterHandler
2354
+ based on its SMIRKS.
2355
+ """
2356
+ return self.parameters[val]
2357
+
2358
+
2359
+ class ConstraintHandler(ParameterHandler):
2360
+ """Handle SMIRNOFF ``<Constraints>`` tags
2361
+
2362
+ ``ConstraintHandler`` must be applied before ``BondHandler`` and ``AngleHandler``,
2363
+ since those classes add constraints for which equilibrium geometries are needed from those tags.
2364
+
2365
+ .. warning :: This API is experimental and subject to change.
2366
+ """
2367
+
2368
+ class ConstraintType(ParameterType):
2369
+ """A SMIRNOFF constraint type
2370
+
2371
+ .. warning :: This API is experimental and subject to change.
2372
+ """
2373
+
2374
+ _ELEMENT_NAME = "Constraint"
2375
+
2376
+ distance = ParameterAttribute(default=None, unit=unit.angstrom)
2377
+
2378
+ _TAGNAME = "Constraints"
2379
+ _INFOTYPE = ConstraintType
2380
+
2381
+
2382
+ class BondHandler(ParameterHandler):
2383
+ """Handle SMIRNOFF ``<Bonds>`` tags
2384
+
2385
+ .. warning :: This API is experimental and subject to change.
2386
+ """
2387
+
2388
+ class BondType(ParameterType):
2389
+ """A SMIRNOFF bond type
2390
+
2391
+ .. warning :: This API is experimental and subject to change.
2392
+ """
2393
+
2394
+ _ELEMENT_NAME = "Bond"
2395
+
2396
+ length = ParameterAttribute(default=None, unit=unit.angstrom)
2397
+ k = ParameterAttribute(default=None, unit=unit.kilocalorie / unit.mole / unit.angstrom**2)
2398
+
2399
+ # fractional bond order params
2400
+ length_bondorder = MappedParameterAttribute(default=None, unit=unit.angstrom)
2401
+ k_bondorder = MappedParameterAttribute(default=None, unit=unit.kilocalorie / unit.mole / unit.angstrom**2)
2402
+
2403
+ def __init__(self, **kwargs):
2404
+ # these checks enforce mutually-exclusive parameterattribute specifications
2405
+ has_k = "k" in kwargs.keys()
2406
+ has_k_bondorder = any(["k_bondorder" in key for key in kwargs.keys()])
2407
+ has_length = "length" in kwargs.keys()
2408
+ has_length_bondorder = any(["length_bondorder" in key for key in kwargs.keys()])
2409
+
2410
+ # Are these errors too general? What about ParametersMissingError/ParametersOverspecifiedError?
2411
+ if has_k:
2412
+ if has_k_bondorder:
2413
+ raise SMIRNOFFSpecError("BOTH k and k_bondorder* cannot be specified simultaneously.")
2414
+ else:
2415
+ if not has_k_bondorder:
2416
+ raise SMIRNOFFSpecError("Either k or k_bondorder* must be specified.")
2417
+ if has_length:
2418
+ if has_length_bondorder:
2419
+ raise SMIRNOFFSpecError("BOTH length and length_bondorder* cannot be specified simultaneously.")
2420
+ else:
2421
+ if not has_length_bondorder:
2422
+ raise SMIRNOFFSpecError("Either length or length_bondorder* must be specified.")
2423
+
2424
+ super().__init__(**kwargs)
2425
+
2426
+ _TAGNAME = "Bonds" # SMIRNOFF tag name to process
2427
+ _INFOTYPE = BondType # class to hold force type info
2428
+ _DEPENDENCIES = [ConstraintHandler] # ConstraintHandler must be executed first
2429
+ _MAX_SUPPORTED_SECTION_VERSION = Version("0.4")
2430
+
2431
+ # Use the _allow_only filter here because this class's implementation contains all the information about supported
2432
+ # potentials for this handler.
2433
+ potential = ParameterAttribute(
2434
+ default="overridden in init",
2435
+ converter=_allow_only(["harmonic", "(k/2)*(r-length)^2"]),
2436
+ )
2437
+ # The default value for fractional_bondorder_method depends on the section version and is overwritten in __init__.
2438
+ # Do not use the allow_only filter here since ToolkitWrappers may be imported that support additional fractional
2439
+ # bondorder methods.
2440
+ fractional_bondorder_method = ParameterAttribute(default="overridden in init")
2441
+ # Use the _allow_only filter here because this class's implementation contains all the information about supported
2442
+ # interpolation types.
2443
+ fractional_bondorder_interpolation = ParameterAttribute(default="linear", converter=_allow_only(["linear"]))
2444
+
2445
+ def __init__(self, **kwargs):
2446
+ super().__init__(**kwargs)
2447
+ # Default value for fractional_bondorder_interpolation depends on section version
2448
+ if self.version == Version("0.3") and "fractional_bondorder_method" not in kwargs:
2449
+ self.fractional_bondorder_method = "none"
2450
+ elif self.version == Version("0.4") and "fractional_bondorder_method" not in kwargs:
2451
+ self.fractional_bondorder_method = "AM1-Wiberg"
2452
+
2453
+ # Default value for potential depends on section version
2454
+ if self.version == Version("0.3") and "potential" not in kwargs:
2455
+ self.potential = "harmonic"
2456
+ elif self.version == Version("0.4") and "potential" not in kwargs:
2457
+ self.potential = "(k/2)*(r-length)^2"
2458
+
2459
+ def check_handler_compatibility(self, other_handler: "BondHandler"):
2460
+ """
2461
+ Checks whether this ParameterHandler encodes compatible physics as another ParameterHandler. This is
2462
+ called if a second handler is attempted to be initialized for the same tag.
2463
+
2464
+ Parameters
2465
+ ----------
2466
+ other_handler
2467
+ The handler to compare to.
2468
+
2469
+ Raises
2470
+ ------
2471
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
2472
+ """
2473
+ string_attrs_to_compare = (
2474
+ "fractional_bondorder_method",
2475
+ "fractional_bondorder_interpolation",
2476
+ )
2477
+ self._check_attributes_are_equal(other_handler, identical_attrs=string_attrs_to_compare)
2478
+
2479
+ # potential="harmonic" and potential="(k/2)*(r-length)^2" should be considered identical
2480
+ self_has_harmonic_potential = self.potential == "harmonic" or self.potential == "(k/2)*(r-length)^2"
2481
+ other_has_harmonic_potential = (
2482
+ other_handler.potential == "harmonic" or other_handler.potential == "(k/2)*(r-length)^2"
2483
+ )
2484
+ if not (self_has_harmonic_potential and other_has_harmonic_potential):
2485
+ if self.potential != other_handler.potential:
2486
+ raise IncompatibleParameterError(
2487
+ f"potential values are not identical. "
2488
+ f"(handler value: {self.potential}, incompatible value: {other_handler.potential}"
2489
+ )
2490
+
2491
+
2492
+ class AngleHandler(ParameterHandler):
2493
+ """Handle SMIRNOFF ``<AngleForce>`` tags
2494
+
2495
+ .. warning :: This API is experimental and subject to change.
2496
+ """
2497
+
2498
+ class AngleType(ParameterType):
2499
+ """A SMIRNOFF angle type.
2500
+
2501
+ .. warning :: This API is experimental and subject to change.
2502
+ """
2503
+
2504
+ _ELEMENT_NAME = "Angle"
2505
+
2506
+ angle = ParameterAttribute(unit=unit.degree)
2507
+ k = ParameterAttribute(unit=unit.kilocalorie / unit.mole / unit.degree**2)
2508
+
2509
+ _TAGNAME = "Angles" # SMIRNOFF tag name to process
2510
+ _INFOTYPE = AngleType # class to hold force type info
2511
+ _DEPENDENCIES = [ConstraintHandler] # ConstraintHandler must be executed first
2512
+
2513
+ potential = ParameterAttribute(default="harmonic")
2514
+
2515
+ def check_handler_compatibility(self, other_handler: "AngleHandler"):
2516
+ """
2517
+ Checks whether this ParameterHandler encodes compatible physics as another ParameterHandler. This is
2518
+ called if a second handler is attempted to be initialized for the same tag.
2519
+
2520
+ Parameters
2521
+ ----------
2522
+ other_handler
2523
+ The handler to compare to.
2524
+
2525
+ Raises
2526
+ ------
2527
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
2528
+ """
2529
+ string_attrs_to_compare = ("potential",)
2530
+ self._check_attributes_are_equal(other_handler, identical_attrs=string_attrs_to_compare)
2531
+
2532
+
2533
+ # TODO: There's a lot of duplicated code in ProperTorsionHandler and ImproperTorsionHandler
2534
+ class ProperTorsionHandler(ParameterHandler):
2535
+ """Handle SMIRNOFF ``<ProperTorsionForce>`` tags
2536
+
2537
+ .. warning :: This API is experimental and subject to change.
2538
+ """
2539
+
2540
+ class ProperTorsionType(ParameterType):
2541
+ """A SMIRNOFF torsion type for proper torsions.
2542
+
2543
+ .. warning :: This API is experimental and subject to change.
2544
+ """
2545
+
2546
+ _ELEMENT_NAME = "Proper"
2547
+
2548
+ periodicity = IndexedParameterAttribute(converter=int)
2549
+ phase = IndexedParameterAttribute(unit=unit.degree)
2550
+ k = IndexedParameterAttribute(default=None, unit=unit.kilocalorie / unit.mole)
2551
+ idivf = IndexedParameterAttribute(default=None, converter=float)
2552
+
2553
+ # fractional bond order params
2554
+ k_bondorder = IndexedMappedParameterAttribute(default=None, unit=unit.kilocalorie / unit.mole)
2555
+
2556
+ _TAGNAME = "ProperTorsions" # SMIRNOFF tag name to process
2557
+ _KWARGS = ["partial_bond_orders_from_molecules"]
2558
+ _INFOTYPE = ProperTorsionType # info type to store
2559
+ _MAX_SUPPORTED_SECTION_VERSION = Version("0.4")
2560
+
2561
+ potential = ParameterAttribute(
2562
+ default="k*(1+cos(periodicity*theta-phase))",
2563
+ converter=_allow_only(["k*(1+cos(periodicity*theta-phase))"]),
2564
+ )
2565
+ default_idivf = ParameterAttribute(default="auto")
2566
+ fractional_bondorder_method = ParameterAttribute(default="AM1-Wiberg")
2567
+ fractional_bondorder_interpolation = ParameterAttribute(default="linear", converter=_allow_only(["linear"]))
2568
+
2569
+ def check_handler_compatibility(self, other_handler: "ProperTorsionHandler"):
2570
+ """
2571
+ Checks whether this ParameterHandler encodes compatible physics as another ParameterHandler. This is
2572
+ called if a second handler is attempted to be initialized for the same tag.
2573
+
2574
+ Parameters
2575
+ ----------
2576
+ other_handler
2577
+ The handler to compare to.
2578
+
2579
+ Raises
2580
+ ------
2581
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
2582
+ """
2583
+ float_attrs_to_compare = list()
2584
+ string_attrs_to_compare = [
2585
+ "potential",
2586
+ "fractional_bondorder_method",
2587
+ "fractional_bondorder_interpolation",
2588
+ ]
2589
+
2590
+ if self.default_idivf == "auto":
2591
+ string_attrs_to_compare.append("default_idivf")
2592
+ else:
2593
+ float_attrs_to_compare.append("default_idivf")
2594
+
2595
+ self._check_attributes_are_equal(
2596
+ other_handler,
2597
+ identical_attrs=tuple(string_attrs_to_compare),
2598
+ tolerance_attrs=tuple(float_attrs_to_compare),
2599
+ )
2600
+
2601
+
2602
+ # TODO: There's a lot of duplicated code in ProperTorsionHandler and ImproperTorsionHandler
2603
+ class ImproperTorsionHandler(ParameterHandler):
2604
+ """Handle SMIRNOFF ``<ImproperTorsionForce>`` tags
2605
+
2606
+ .. warning :: This API is experimental and subject to change.
2607
+ """
2608
+
2609
+ class ImproperTorsionType(ParameterType):
2610
+ """A SMIRNOFF torsion type for improper torsions.
2611
+
2612
+ .. warning :: This API is experimental and subject to change.
2613
+ """
2614
+
2615
+ _ELEMENT_NAME = "Improper"
2616
+
2617
+ periodicity = IndexedParameterAttribute(converter=int)
2618
+ phase = IndexedParameterAttribute(unit=unit.degree)
2619
+ k = IndexedParameterAttribute(unit=unit.kilocalorie / unit.mole)
2620
+ idivf = IndexedParameterAttribute(default=None, converter=float)
2621
+
2622
+ _TAGNAME = "ImproperTorsions" # SMIRNOFF tag name to process
2623
+ _INFOTYPE = ImproperTorsionType # info type to store
2624
+
2625
+ potential = ParameterAttribute(
2626
+ default="k*(1+cos(periodicity*theta-phase))",
2627
+ converter=_allow_only(["k*(1+cos(periodicity*theta-phase))"]),
2628
+ )
2629
+ default_idivf = ParameterAttribute(default="auto")
2630
+
2631
+ def check_handler_compatibility(self, other_handler: "ImproperTorsionHandler"):
2632
+ """
2633
+ Checks whether this ParameterHandler encodes compatible physics as another ParameterHandler. This is
2634
+ called if a second handler is attempted to be initialized for the same tag.
2635
+
2636
+ Parameters
2637
+ ----------
2638
+ other_handler
2639
+ The handler to compare to.
2640
+
2641
+ Raises
2642
+ ------
2643
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
2644
+ """
2645
+ float_attrs_to_compare = list()
2646
+ string_attrs_to_compare = ["potential"]
2647
+
2648
+ if self.default_idivf == "auto":
2649
+ string_attrs_to_compare.append("default_idivf")
2650
+ else:
2651
+ float_attrs_to_compare.append("default_idivf")
2652
+
2653
+ self._check_attributes_are_equal(
2654
+ other_handler,
2655
+ identical_attrs=tuple(string_attrs_to_compare),
2656
+ tolerance_attrs=tuple(float_attrs_to_compare),
2657
+ )
2658
+
2659
+ def find_matches(self, entity, unique=False):
2660
+ """Find the improper torsions in the topology/molecule matched by a parameter type.
2661
+
2662
+ Parameters
2663
+ ----------
2664
+ entity
2665
+ Topology to search.
2666
+
2667
+ Returns
2668
+ ---------
2669
+ matches
2670
+ ``matches[atom_indices]`` is the ``ParameterType`` object
2671
+ matching the 4-tuple of atom indices in ``entity``.
2672
+
2673
+ """
2674
+ return self._find_matches(entity, transformed_dict_cls=ImproperDict, unique=unique)
2675
+
2676
+
2677
+ class _NonbondedHandler(ParameterHandler):
2678
+ """Base class for ParameterHandlers that deal with OpenMM NonbondedForce objects."""
2679
+
2680
+
2681
+ class vdWHandler(_NonbondedHandler):
2682
+ """Handle SMIRNOFF ``<vdW>`` tags
2683
+
2684
+ .. warning :: This API is experimental and subject to change.
2685
+ """
2686
+
2687
+ class vdWType(ParameterType):
2688
+ """A SMIRNOFF vdWForce type.
2689
+
2690
+ .. warning :: This API is experimental and subject to change.
2691
+ """
2692
+
2693
+ _ELEMENT_NAME = "Atom"
2694
+
2695
+ epsilon = ParameterAttribute(unit=unit.kilocalorie / unit.mole)
2696
+ sigma = ParameterAttribute(default=None, unit=unit.angstrom)
2697
+ rmin_half = ParameterAttribute(default=None, unit=unit.angstrom)
2698
+
2699
+ def __init__(self, **kwargs):
2700
+ sigma = kwargs.get("sigma", None)
2701
+ rmin_half = kwargs.get("rmin_half", None)
2702
+ if (sigma is None) and (rmin_half is None):
2703
+ raise SMIRNOFFSpecError("Either sigma or rmin_half must be specified.")
2704
+ if (sigma is not None) and (rmin_half is not None):
2705
+ raise SMIRNOFFSpecError("BOTH sigma and rmin_half cannot be specified simultaneously.")
2706
+
2707
+ super().__init__(**kwargs)
2708
+
2709
+ if sigma:
2710
+ self._extra_nb_var = "rmin_half"
2711
+ if rmin_half:
2712
+ self._extra_nb_var = "sigma"
2713
+
2714
+ def __setattr__(self, name, value):
2715
+ super().__setattr__(key=name, value=value)
2716
+ if name == "rmin_half":
2717
+ if type(value) is str:
2718
+ value = object_to_quantity(value)
2719
+ super().__setattr__("sigma", 2.0 * value / 2 ** (1 / 6))
2720
+ self._extra_nb_var = "sigma"
2721
+
2722
+ if name == "sigma":
2723
+ if type(value) is str:
2724
+ value = object_to_quantity(value)
2725
+ super().__setattr__("rmin_half", value * 2 ** (1 / 6) / 2.0)
2726
+ self._extra_nb_var = "rmin_half"
2727
+
2728
+ def to_dict(
2729
+ self,
2730
+ discard_cosmetic_attributes=False,
2731
+ duplicate_attributes=None,
2732
+ ):
2733
+ return super().to_dict(
2734
+ discard_cosmetic_attributes=discard_cosmetic_attributes,
2735
+ duplicate_attributes=[
2736
+ *([] if duplicate_attributes is None else duplicate_attributes),
2737
+ self._extra_nb_var,
2738
+ ],
2739
+ )
2740
+
2741
+ _TAGNAME = "vdW" # SMIRNOFF tag name to process
2742
+ _INFOTYPE = vdWType # info type to store
2743
+ _MAX_SUPPORTED_SECTION_VERSION = Version("0.5")
2744
+
2745
+ potential = ParameterAttribute(default="Lennard-Jones-12-6", converter=_allow_only(["Lennard-Jones-12-6"]))
2746
+ combining_rules = ParameterAttribute(default="Lorentz-Berthelot", converter=_allow_only(["Lorentz-Berthelot"]))
2747
+
2748
+ scale12 = ParameterAttribute(default=0.0, converter=float)
2749
+ scale13 = ParameterAttribute(default=0.0, converter=float)
2750
+ scale14 = ParameterAttribute(default=0.5, converter=float)
2751
+ scale15 = ParameterAttribute(default=1.0, converter=float)
2752
+
2753
+ cutoff = ParameterAttribute(default=9.0 * unit.angstroms, unit=unit.angstrom)
2754
+ switch_width = ParameterAttribute(default=1.0 * unit.angstroms, unit=unit.angstrom)
2755
+ periodic_method = ParameterAttribute(default="cutoff", converter=_allow_only(["cutoff", "no-cutoff", "Ewald3D"]))
2756
+ nonperiodic_method = ParameterAttribute(default="no-cutoff", converter=_allow_only(["cutoff", "no-cutoff"]))
2757
+
2758
+ def __init__(self, **kwargs):
2759
+ if kwargs.get("version") is None:
2760
+ kwargs["version"] = 0.5
2761
+ elif Version(str(kwargs.get("version"))) > Version("0.3"):
2762
+ if "method" in kwargs:
2763
+ raise SMIRNOFFSpecError(
2764
+ "`method` attribute has been removed in version 0.4 of the vdW tag. Use "
2765
+ "`periodic_method` and `nonperiodic_method` instead. "
2766
+ "See https://openforcefield.github.io/standards/standards/smirnoff/#electrostatics"
2767
+ )
2768
+
2769
+ if kwargs.get("version") == 0.3:
2770
+ logger.info("Attempting to up-convert vdW section from 0.3 to 0.4")
2771
+
2772
+ # This is the only supported value of "method" is version 0.3
2773
+ if kwargs.get("method") in ("cutoff", None):
2774
+ kwargs["periodic_method"] = "cutoff"
2775
+ kwargs["nonperiodic_method"] = "no-cutoff"
2776
+ kwargs["version"] = 0.4
2777
+ kwargs.pop("method", None)
2778
+
2779
+ logger.info(
2780
+ 'Successfully up-converted vdW section from 0.3 to 0.4. `method="cutoff"` '
2781
+ 'is now split into `periodic_method="cutoff"` '
2782
+ 'and `nonperiodic_method="no-cutoff"`.'
2783
+ )
2784
+
2785
+ else:
2786
+ raise NotImplementedError(
2787
+ "Failed to up-convert vdW section from 0.3 to 0.4. Did not know "
2788
+ f'how to up-convert `method="{kwargs["method"]}"`.'
2789
+ )
2790
+ super().__init__(**kwargs)
2791
+
2792
+ # TODO: Use _allow_only when ParameterAttribute will support multiple converters
2793
+ # (it'll be easy when we switch to use the attrs library)
2794
+ @scale12.converter # type: ignore[no-redef]
2795
+ def scale12(self, attrs, new_scale12):
2796
+ if new_scale12 != 0.0:
2797
+ raise SMIRNOFFSpecError(
2798
+ "Current OpenFF toolkit is unable to handle scale12 values other than 0.0. "
2799
+ f"Specified 1-2 scaling was {new_scale12}."
2800
+ )
2801
+ return new_scale12
2802
+
2803
+ @scale13.converter # type: ignore[no-redef]
2804
+ def scale13(self, attrs, new_scale13):
2805
+ if new_scale13 != 0.0:
2806
+ raise SMIRNOFFSpecError(
2807
+ "Current OpenFF toolkit is unable to handle scale13 values other than 0.0. "
2808
+ f"Specified 1-3 scaling was {new_scale13}."
2809
+ )
2810
+ return new_scale13
2811
+
2812
+ @scale15.converter # type: ignore[no-redef]
2813
+ def scale15(self, attrs, new_scale15):
2814
+ if new_scale15 != 1.0:
2815
+ raise SMIRNOFFSpecError(
2816
+ "Current OpenFF toolkit is unable to handle scale15 values other than 1.0. "
2817
+ f"Specified 1-5 scaling was {new_scale15}."
2818
+ )
2819
+ return new_scale15
2820
+
2821
+ # Tolerance when comparing float attributes for handler compatibility.
2822
+ _SCALETOL = 1e-5
2823
+
2824
+ def check_handler_compatibility(self, other_handler: "vdWHandler"):
2825
+ """
2826
+ Checks whether this ParameterHandler encodes compatible physics as another ParameterHandler. This is
2827
+ called if a second handler is attempted to be initialized for the same tag.
2828
+
2829
+ Parameters
2830
+ ----------
2831
+ other_handler
2832
+ The handler to compare to.
2833
+
2834
+ Raises
2835
+ ------
2836
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
2837
+ """
2838
+ float_attrs_to_compare = ("scale12", "scale13", "scale14", "scale15")
2839
+ string_attrs_to_compare = (
2840
+ "potential",
2841
+ "combining_rules",
2842
+ "periodic_method",
2843
+ "nonperiodic_method",
2844
+ )
2845
+ unit_attrs_to_compare = ("cutoff", "switch_width")
2846
+
2847
+ self._check_attributes_are_equal(
2848
+ other_handler,
2849
+ identical_attrs=string_attrs_to_compare,
2850
+ tolerance_attrs=float_attrs_to_compare + unit_attrs_to_compare,
2851
+ tolerance=self._SCALETOL,
2852
+ )
2853
+
2854
+
2855
+ class ElectrostaticsHandler(_NonbondedHandler):
2856
+ """Handles SMIRNOFF ``<Electrostatics>`` tags.
2857
+
2858
+ .. warning :: This API is experimental and subject to change.
2859
+ """
2860
+
2861
+ _TAGNAME = "Electrostatics"
2862
+ _DEPENDENCIES = [vdWHandler]
2863
+ _KWARGS = ["charge_from_molecules"]
2864
+ _MAX_SUPPORTED_SECTION_VERSION = Version("0.4")
2865
+
2866
+ # Tolerance when comparing float attributes for handler compatibility.
2867
+ _SCALETOL = 1e-5
2868
+ _DEFAULT_REACTION_FIELD_EXPRESSION = (
2869
+ "charge1*charge2/(4*pi*epsilon0)*(1/r + k_rf*r^2 - c_rf);"
2870
+ "k_rf=(cutoff^(-3))*(solvent_dielectric-1)/(2*solvent_dielectric+1);"
2871
+ "c_rf=cutoff^(-1)*(3*solvent_dielectric)/(2*solvent_dielectric+1)"
2872
+ )
2873
+
2874
+ scale12 = ParameterAttribute(default=0.0, converter=float)
2875
+ scale13 = ParameterAttribute(default=0.0, converter=float)
2876
+ scale14 = ParameterAttribute(default=0.833333, converter=float)
2877
+ scale15 = ParameterAttribute(default=1.0, converter=float)
2878
+ cutoff = ParameterAttribute(default=9.0 * unit.angstrom, unit=unit.angstrom)
2879
+ switch_width = ParameterAttribute(default=0.0 * unit.angstrom, unit=unit.angstrom)
2880
+ solvent_dielectric = ParameterAttribute(default=None)
2881
+
2882
+ # TODO: How to validate arbitrary algebra in a converter?
2883
+ periodic_potential = ParameterAttribute(
2884
+ default="Ewald3D-ConductingBoundary",
2885
+ converter=_allow_only(
2886
+ [
2887
+ "Ewald3D-ConductingBoundary",
2888
+ "Coulomb",
2889
+ _DEFAULT_REACTION_FIELD_EXPRESSION,
2890
+ ]
2891
+ ),
2892
+ )
2893
+ nonperiodic_potential = ParameterAttribute(default="Coulomb", converter=_allow_only(["Coulomb"]))
2894
+ exception_potential = ParameterAttribute(default="Coulomb", converter=_allow_only(["Coulomb"]))
2895
+
2896
+ # TODO: Use _allow_only when ParameterAttribute will support multiple converters
2897
+ # (it'll be easy when we switch to use the attrs library)
2898
+ @scale12.converter # type: ignore[no-redef]
2899
+ def scale12(self, attrs, new_scale12):
2900
+ if new_scale12 != 0.0:
2901
+ raise SMIRNOFFSpecError(
2902
+ "Current OpenFF toolkit is unable to handle scale12 values other than 0.0. "
2903
+ f"Specified 1-2 scaling was {new_scale12}."
2904
+ )
2905
+ return new_scale12
2906
+
2907
+ @scale13.converter # type: ignore[no-redef]
2908
+ def scale13(self, attrs, new_scale13):
2909
+ if new_scale13 != 0.0:
2910
+ raise SMIRNOFFSpecError(
2911
+ "Current OpenFF toolkit is unable to handle scale13 values other than 0.0. "
2912
+ f"Specified 1-3 scaling was {new_scale13}."
2913
+ )
2914
+ return new_scale13
2915
+
2916
+ @scale15.converter # type: ignore[no-redef]
2917
+ def scale15(self, attrs, new_scale15):
2918
+ if new_scale15 != 1.0:
2919
+ raise SMIRNOFFSpecError(
2920
+ "Current OpenFF toolkit is unable to handle scale15 values other than 1.0. "
2921
+ f"Specified 1-5 scaling was {new_scale15}."
2922
+ )
2923
+ return new_scale15
2924
+
2925
+ @switch_width.converter # type: ignore[no-redef]
2926
+ def switch_width(self, attr, new_switch_width):
2927
+ if new_switch_width not in [0.0 * unit.angstrom, None, "None", "none"]:
2928
+ raise SMIRNOFFSpecUnimplementedError(
2929
+ "The current implementation of the OpenFF Toolkit does not support an electrostatic "
2930
+ f"switch width (passed a value of {new_switch_width}). Currently only `0.0 angstroms` is supported "
2931
+ "and no switching function will be applied to the resulting `NonbondedForce`. If this behavior is "
2932
+ "important to you, please raise an issue at https://github.com/openforcefield/openff-toolkit/issues."
2933
+ )
2934
+
2935
+ @periodic_potential.converter # type: ignore[no-redef]
2936
+ def periodic_potential(self, attr, new_value):
2937
+ if new_value in ["PME", "Ewald3D-ConductingBoundary"]:
2938
+ return "Ewald3D-ConductingBoundary"
2939
+ elif new_value in ["reaction-field", self._DEFAULT_REACTION_FIELD_EXPRESSION]:
2940
+ return self._DEFAULT_REACTION_FIELD_EXPRESSION
2941
+ elif new_value.lower() == "coulomb":
2942
+ return "Coulomb"
2943
+ else:
2944
+ raise NotImplementedError("Failed to process unexpected periodic potential value: {new_value}")
2945
+
2946
+ @solvent_dielectric.converter # type: ignore[no-redef]
2947
+ def solvent_dielectric(self, attr, new_value):
2948
+ if new_value is not None:
2949
+ raise SMIRNOFFSpecUnimplementedError(
2950
+ "The current implementation of the OpenFF Toolkit does not support any electrostatic "
2951
+ "functions that make use of `solvent_dielectric`. If this behavior is important to you, please raise"
2952
+ "raise an issue at https://github.com/openforcefield/openff-toolkit/issues."
2953
+ )
2954
+
2955
+ def __init__(self, **kwargs):
2956
+ if kwargs.get("version") == 0.4:
2957
+ if "method" in kwargs:
2958
+ raise SMIRNOFFSpecError(
2959
+ "`method` attribute has been removed in version 0.4 of the Electrostatics tag. Use "
2960
+ "`periodic_potential`, `nonperiodic_potential`, and `exception_potential` instead. "
2961
+ "See https://openforcefield.github.io/standards/standards/smirnoff/#electrostatics"
2962
+ )
2963
+ if kwargs.get("version") == 0.3:
2964
+ logger.info("Attempting to up-convert Electrostatics section from 0.3 to 0.4")
2965
+ # Default value in 0.3 is "PME", so we have to handle these cases identically
2966
+ if kwargs.get("method") in ["PME", None]:
2967
+ kwargs["periodic_potential"] = "Ewald3D-ConductingBoundary"
2968
+ kwargs["nonperiodic_potential"] = "Coulomb"
2969
+ kwargs["exception_potential"] = "Coulomb"
2970
+ kwargs["version"] = 0.4
2971
+ kwargs.pop("method", None)
2972
+ logger.info(
2973
+ 'Successfully up-converted Electrostatics section from 0.3 to 0.4. `method="PME"` '
2974
+ 'is now split into `periodic_potential="Ewald3D-ConductingBoundary"`, '
2975
+ '`nonperiodic_potential="Coulomb"`, and `exception_potential="Coulomb"`.'
2976
+ )
2977
+ elif kwargs["method"] == "Coulomb":
2978
+ kwargs["periodic_potential"] = "Coulomb"
2979
+ kwargs["nonperiodic_potential"] = "Coulomb"
2980
+ kwargs["exception_potential"] = "Coulomb"
2981
+ kwargs["version"] = 0.4
2982
+ kwargs.pop("method", None)
2983
+ logger.info(
2984
+ 'Successfully up-converted Electrostatics section from 0.3 to 0.4. `method="Coulomb"` '
2985
+ 'is now split into `periodic_potential="Coulob"`, '
2986
+ '`nonperiodic_potential="Coulomb"`, and `exception_potential="Coulomb"`.'
2987
+ )
2988
+ elif kwargs["method"] == "reaction-field":
2989
+ kwargs["periodic_potential"] = self._DEFAULT_REACTION_FIELD_EXPRESSION
2990
+ kwargs["nonperiodic_potential"] = "Coulomb"
2991
+ kwargs["exception_potential"] = "Coulomb"
2992
+ kwargs["version"] = 0.4
2993
+ kwargs.pop("method", None)
2994
+ logger.info(
2995
+ 'Successfully up-converted Electrostatics section from 0.3 to 0.4. `method="Coulomb"` '
2996
+ f'is now split into `periodic_potential="{self._DEFAULT_REACTION_FIELD_EXPRESSION}"` '
2997
+ '`nonperiodic_potential="Coulomb"`, and `exception_potential="Coulomb"`.'
2998
+ )
2999
+ else:
3000
+ raise NotImplementedError(
3001
+ "Failed to up-convert Electrostatics section from 0.3 to 0.4. Did not know "
3002
+ f"how to up-convert `method={kwargs['method']}`."
3003
+ )
3004
+ super().__init__(**kwargs)
3005
+
3006
+ def check_handler_compatibility(self, other_handler: "ElectrostaticsHandler"):
3007
+ """
3008
+ Checks whether this ParameterHandler encodes compatible physics as another ParameterHandler. This is
3009
+ called if a second handler is attempted to be initialized for the same tag.
3010
+
3011
+ Parameters
3012
+ ----------
3013
+ other_handler
3014
+ The handler to compare to.
3015
+
3016
+ Raises
3017
+ ------
3018
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
3019
+ """
3020
+ float_attrs_to_compare = (
3021
+ "scale12",
3022
+ "scale13",
3023
+ "scale14",
3024
+ "scale15",
3025
+ )
3026
+ string_attrs_to_compare = (
3027
+ "periodic_potential",
3028
+ "nonperiodic_potential",
3029
+ "exception_potential",
3030
+ )
3031
+ unit_attrs_to_compare = ("cutoff", "switch_width")
3032
+
3033
+ self._check_attributes_are_equal(
3034
+ other_handler,
3035
+ identical_attrs=string_attrs_to_compare,
3036
+ tolerance_attrs=float_attrs_to_compare + unit_attrs_to_compare,
3037
+ tolerance=self._SCALETOL,
3038
+ )
3039
+
3040
+
3041
+ class LibraryChargeHandler(_NonbondedHandler):
3042
+ """Handle SMIRNOFF ``<LibraryCharges>`` tags
3043
+
3044
+ .. warning :: This API is experimental and subject to change.
3045
+ """
3046
+
3047
+ class LibraryChargeType(ParameterType):
3048
+ """A SMIRNOFF Library Charge type.
3049
+
3050
+ .. warning :: This API is experimental and subject to change.
3051
+ """
3052
+
3053
+ _ELEMENT_NAME = "LibraryCharge"
3054
+
3055
+ name = ParameterAttribute(default=None)
3056
+ charge = IndexedParameterAttribute(unit=unit.elementary_charge)
3057
+
3058
+ def __init__(self, **kwargs):
3059
+ super().__init__(**kwargs)
3060
+ unique_tags, _ = GLOBAL_TOOLKIT_REGISTRY.call("get_tagged_smarts_connectivity", self.smirks)
3061
+ if len(self.charge) != len(unique_tags):
3062
+ raise SMIRNOFFSpecError(
3063
+ f"LibraryCharge {self} was initialized with unequal number of tagged atoms and charges"
3064
+ )
3065
+
3066
+ @classmethod
3067
+ def from_molecule(cls, molecule: Molecule):
3068
+ """
3069
+ Construct a LibraryChargeType from a molecule with existing partial charges.
3070
+
3071
+ Parameters
3072
+ ----------
3073
+ molecule
3074
+ The molecule to create the LibraryChargeType from. The molecule must have partial charges.
3075
+
3076
+ Returns
3077
+ -------
3078
+ library_charge_type
3079
+ A LibraryChargeType that is expected to match this molecule and its partial charges.
3080
+
3081
+ Raises
3082
+ ------
3083
+
3084
+ MissingPartialChargesError
3085
+ """
3086
+ if molecule.partial_charges is None:
3087
+ raise MissingPartialChargesError("Input molecule is missing partial charges.")
3088
+
3089
+ smirks = molecule.to_smiles(mapped=True)
3090
+ charges = molecule.partial_charges
3091
+
3092
+ library_charge_type = cls(smirks=smirks, charge=charges)
3093
+
3094
+ return library_charge_type
3095
+
3096
+ _TAGNAME = "LibraryCharges" # SMIRNOFF tag name to process
3097
+ _INFOTYPE = LibraryChargeType # info type to store
3098
+ _DEPENDENCIES = [vdWHandler, ElectrostaticsHandler]
3099
+
3100
+ def find_matches(self, entity, unique=False):
3101
+ """Find the elements of the topology/molecule matched by a parameter type.
3102
+
3103
+ Parameters
3104
+ ----------
3105
+ entity
3106
+ Topology to search.
3107
+
3108
+ Returns
3109
+ ---------
3110
+ matches
3111
+ ``matches[atom_indices]`` is the ``ParameterType`` object
3112
+ matching the tuple of atom indices in ``entity``.
3113
+ """
3114
+
3115
+ return self._find_matches(
3116
+ entity,
3117
+ transformed_dict_cls=dict,
3118
+ unique=unique,
3119
+ )
3120
+
3121
+
3122
+ class NAGLChargesHandler(_NonbondedHandler):
3123
+ """ParameterHandler for applying partial charges from a pretrained NAGL model.
3124
+
3125
+ This handler processes the NAGLCharges section of SMIRNOFF force fields, which
3126
+ specifies a pre-trained NAGL model for computing
3127
+ partial charges on molecules.
3128
+
3129
+ Parameters
3130
+ ----------
3131
+ model_file : str
3132
+ Path to the PyTorch model file (e.g., "openff-gnn-am1bcc-0.1.0-rc.3.pt").
3133
+ This is the model that will be used for charge assignment.
3134
+ model_file_hash : str, optional
3135
+ SHA-256 hash of the model file for integrity verification. When provided,
3136
+ the hash will be validated against the actual model file.
3137
+ digital_object_identifier : str, optional
3138
+ Zenodo DOI that can be used to retrieve the model file if it's not found
3139
+ locally. Must point to a Zenodo record with an attached file matching
3140
+ the model_file name.
3141
+ version : str, optional
3142
+ The version of the NAGLCharges section specification.
3143
+ skip_version_check : bool, optional, default=False
3144
+ If True, skips validation of the version parameter and sets it to the highest
3145
+ supported version.
3146
+ allow_cosmetic_attributes : bool, optional, default=False
3147
+ If True, allows non-specification attributes to be present.
3148
+
3149
+ Examples
3150
+ --------
3151
+ Create a handler with just the model file:
3152
+
3153
+ >>> handler = NAGLChargesHandler(
3154
+ ... model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
3155
+ ... skip_version_check=True
3156
+ ... )
3157
+
3158
+ Create a handler with hash verification:
3159
+
3160
+ >>> handler = NAGLChargesHandler(
3161
+ ... model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
3162
+ ... model_file_hash="144ed56e46c5b3ad80157b342c8c0f8f7340e4d382a678e30dd300c811646bd0",
3163
+ ... skip_version_check=True
3164
+ ... )
3165
+
3166
+ Create a handler with DOI for model retrieval:
3167
+
3168
+ >>> handler = NAGLChargesHandler(
3169
+ ... model_file="openff-gnn-am1bcc-0.1.0-rc.3.pt",
3170
+ ... digital_object_identifier="10.5072/zenodo.203601",
3171
+ ... skip_version_check=True
3172
+ ... )
3173
+
3174
+ Notes
3175
+ -----
3176
+ NAGLChargesHandler compatibility is determined solely by the model_file parameter. Two
3177
+ handlers are compatible if and only if they specify the same model_file,
3178
+ regardless of the values of model_file_hash or digital_object_identifier.
3179
+
3180
+ The actual model loading, hash verification, and DOI-based retrieval are
3181
+ handled by the openff-nagl-models package, not by this handler directly.
3182
+ """
3183
+
3184
+ _TAGNAME = "NAGLCharges"
3185
+ _DEPENDENCIES = [vdWHandler, ElectrostaticsHandler, LibraryChargeHandler]
3186
+ _INFOTYPE = None # No separate parameter types; just a model path
3187
+ _MAX_SUPPORTED_SECTION_VERSION = Version("0.3")
3188
+ model_file = ParameterAttribute(converter=str)
3189
+ model_file_hash = ParameterAttribute(default=None, converter=str)
3190
+ digital_object_identifier = ParameterAttribute(default=None, converter=str)
3191
+
3192
+ def check_handler_compatibility(
3193
+ self,
3194
+ other_handler: "NAGLChargesHandler",
3195
+ assume_missing_is_default: bool = True,
3196
+ ):
3197
+ """
3198
+ Checks whether this ParameterHandler encodes compatible physics as another ParameterHandler. This is
3199
+ called if a second handler is attempted to be initialized for the same tag.
3200
+
3201
+ Parameters
3202
+ ----------
3203
+ other_handler
3204
+ The handler to compare to.
3205
+ assume_missing_is_default
3206
+
3207
+ Raises
3208
+ ------
3209
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
3210
+ """
3211
+ if self.model_file != other_handler.model_file:
3212
+ raise IncompatibleParameterError(
3213
+ "Attempted to initialize two NAGLCharges sections with different "
3214
+ "model_files: "
3215
+ f"{self.model_file=} is not identical to {other_handler.model_file=}"
3216
+ )
3217
+
3218
+ # If both handlers have model_file_hashes defined, ensure they're identical
3219
+ if (
3220
+ self.model_file_hash
3221
+ and other_handler.model_file_hash
3222
+ and self.model_file_hash != other_handler.model_file_hash
3223
+ ):
3224
+ raise IncompatibleParameterError(
3225
+ "Attempted to initialize two NAGLCharges sections with different "
3226
+ "model_file_hash values: "
3227
+ f"{self.model_file_hash=} is not identical to "
3228
+ f"{other_handler.model_file_hash=}"
3229
+ )
3230
+
3231
+ # If both handlers have digital_object_identifiers defined, ensure they're identical
3232
+ if (
3233
+ self.digital_object_identifier
3234
+ and other_handler.digital_object_identifier
3235
+ and self.digital_object_identifier != other_handler.digital_object_identifier
3236
+ ):
3237
+ raise IncompatibleParameterError(
3238
+ "Attempted to initialize two NAGLCharges sections with different "
3239
+ "digital_object_identifier values: "
3240
+ f"{self.digital_object_identifier=} is not identical to "
3241
+ f"{other_handler.digital_object_identifier=}"
3242
+ )
3243
+
3244
+
3245
+ class ToolkitAM1BCCHandler(_NonbondedHandler):
3246
+ """Handle SMIRNOFF ``<ToolkitAM1BCC>`` tags
3247
+
3248
+ .. warning :: This API is experimental and subject to change.
3249
+ """
3250
+
3251
+ _TAGNAME = "ToolkitAM1BCC" # SMIRNOFF tag name to process
3252
+ _DEPENDENCIES = [vdWHandler, ElectrostaticsHandler, LibraryChargeHandler, NAGLChargesHandler]
3253
+ _KWARGS = ["toolkit_registry"] # Kwargs to catch when create_force is called
3254
+
3255
+ def check_handler_compatibility(
3256
+ self,
3257
+ other_handler: "ToolkitAM1BCCHandler",
3258
+ assume_missing_is_default: bool = True,
3259
+ ):
3260
+ """
3261
+ Checks whether this ParameterHandler encodes compatible physics as another ParameterHandler. This is
3262
+ called if a second handler is attempted to be initialized for the same tag.
3263
+
3264
+ Parameters
3265
+ ----------
3266
+ other_handler
3267
+ The handler to compare to.
3268
+ assume_missing_is_default
3269
+
3270
+ Raises
3271
+ ------
3272
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
3273
+ """
3274
+ pass
3275
+
3276
+
3277
+ class ChargeIncrementModelHandler(_NonbondedHandler):
3278
+ """Handle SMIRNOFF ``<ChargeIncrementModel>`` tags
3279
+
3280
+ .. warning :: This API is experimental and subject to change.
3281
+ """
3282
+
3283
+ class ChargeIncrementType(ParameterType):
3284
+ """A SMIRNOFF bond charge correction type.
3285
+
3286
+ .. warning :: This API is experimental and subject to change.
3287
+ """
3288
+
3289
+ _ELEMENT_NAME = "ChargeIncrement"
3290
+
3291
+ charge_increment = IndexedParameterAttribute(unit=unit.elementary_charge)
3292
+
3293
+ def __init__(self, **kwargs):
3294
+ super().__init__(**kwargs)
3295
+ unique_tags, _ = GLOBAL_TOOLKIT_REGISTRY.call("get_tagged_smarts_connectivity", self.smirks)
3296
+
3297
+ n_tags = len(unique_tags)
3298
+ n_increments = len(self.charge_increment)
3299
+ diff = n_tags - n_increments
3300
+
3301
+ if diff < 0 or diff > 1:
3302
+ # TODO: Consider dealing with diff > 2 by smearing charges across
3303
+ # all un-specified increments
3304
+ raise SMIRNOFFSpecError(
3305
+ f"ChargeIncrement {self} was initialized with an invalid combination "
3306
+ f"of tagged atoms and charge increments"
3307
+ )
3308
+
3309
+ _TAGNAME = "ChargeIncrementModel" # SMIRNOFF tag name to process
3310
+ _INFOTYPE = ChargeIncrementType # info type to store
3311
+ _DEPENDENCIES = [
3312
+ vdWHandler,
3313
+ ElectrostaticsHandler,
3314
+ LibraryChargeHandler,
3315
+ ToolkitAM1BCCHandler,
3316
+ ]
3317
+ _MAX_SUPPORTED_SECTION_VERSION = Version("0.4")
3318
+
3319
+ number_of_conformers = ParameterAttribute(default=1, converter=int)
3320
+
3321
+ partial_charge_method = ParameterAttribute(default="AM1-Mulliken", converter=str)
3322
+
3323
+ def check_handler_compatibility(
3324
+ self,
3325
+ other_handler: "ChargeIncrementModelHandler",
3326
+ assume_missing_is_default: bool = True,
3327
+ ):
3328
+ """
3329
+ Checks whether this ParameterHandler encodes compatible physics as another ParameterHandler. This is
3330
+ called if a second handler is attempted to be initialized for the same tag.
3331
+
3332
+ Parameters
3333
+ ----------
3334
+ other_handler
3335
+ The handler to compare to.
3336
+ assume_missing_is_default
3337
+
3338
+ Raises
3339
+ ------
3340
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
3341
+ """
3342
+
3343
+ int_attrs_to_compare = ("number_of_conformers",)
3344
+ string_attrs_to_compare = ("partial_charge_method",)
3345
+
3346
+ self._check_attributes_are_equal(
3347
+ other_handler,
3348
+ identical_attrs=string_attrs_to_compare + int_attrs_to_compare,
3349
+ )
3350
+
3351
+ def find_matches(self, entity, unique=False):
3352
+ """Find the elements of the topology/molecule matched by a parameter type.
3353
+
3354
+ Parameters
3355
+ ----------
3356
+ entity
3357
+ Topology to search.
3358
+
3359
+ Returns
3360
+ ---------
3361
+ matches
3362
+ ``matches[atom_indices]`` is the ``ParameterType`` object
3363
+ matching the tuple of atom indices in ``entity``.
3364
+ """
3365
+ matches = self._find_matches(entity, transformed_dict_cls=TagSortedDict, unique=unique)
3366
+ return matches
3367
+
3368
+
3369
+ class GBSAHandler(ParameterHandler):
3370
+ """Handle SMIRNOFF ``<GBSA>`` tags
3371
+
3372
+ .. warning :: This API is experimental and subject to change.
3373
+ """
3374
+
3375
+ class GBSAType(ParameterType):
3376
+ """A SMIRNOFF GBSA type.
3377
+
3378
+ .. warning :: This API is experimental and subject to change.
3379
+ """
3380
+
3381
+ _ELEMENT_NAME = "Atom"
3382
+
3383
+ radius = ParameterAttribute(unit=unit.angstrom)
3384
+ scale = ParameterAttribute(converter=float)
3385
+
3386
+ _TAGNAME = "GBSA"
3387
+ _INFOTYPE = GBSAType
3388
+ # It's important that this runs AFTER partial charges are assigned to all particles, since this will need to
3389
+ # collect and assign them to the GBSA particles
3390
+ _DEPENDENCIES = [
3391
+ vdWHandler,
3392
+ ElectrostaticsHandler,
3393
+ ToolkitAM1BCCHandler,
3394
+ ChargeIncrementModelHandler,
3395
+ LibraryChargeHandler,
3396
+ ]
3397
+
3398
+ gb_model = ParameterAttribute(default="OBC1", converter=_allow_only(["HCT", "OBC1", "OBC2"]))
3399
+ solvent_dielectric = ParameterAttribute(default=78.5, converter=float)
3400
+ solute_dielectric = ParameterAttribute(default=1, converter=float)
3401
+ sa_model = ParameterAttribute(default="ACE", converter=_allow_only(["ACE", None]))
3402
+ surface_area_penalty = ParameterAttribute(
3403
+ default=Quantity(5.4, _cal_mol_a2),
3404
+ unit=_cal_mol_a2,
3405
+ )
3406
+ solvent_radius = ParameterAttribute(default=1.4 * unit.angstrom, unit=unit.angstrom)
3407
+
3408
+ # Tolerance when comparing float attributes for handler compatibility.
3409
+ _SCALETOL = 1e-5
3410
+
3411
+ def check_handler_compatibility(self, other_handler: "GBSAHandler"):
3412
+ """
3413
+ Checks whether this ParameterHandler encodes compatible physics as another ParameterHandler. This is
3414
+ called if a second handler is attempted to be initialized for the same tag.
3415
+
3416
+ Parameters
3417
+ ----------
3418
+ other_handler
3419
+ The handler to compare to.
3420
+
3421
+ Raises
3422
+ ------
3423
+ IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
3424
+ """
3425
+ float_attrs_to_compare = ("solvent_dielectric", "solute_dielectric")
3426
+ string_attrs_to_compare = ("gb_model", "sa_model")
3427
+ unit_attrs_to_compare = ("surface_area_penalty", "solvent_radius")
3428
+
3429
+ self._check_attributes_are_equal(
3430
+ other_handler,
3431
+ identical_attrs=string_attrs_to_compare,
3432
+ tolerance_attrs=float_attrs_to_compare + unit_attrs_to_compare,
3433
+ tolerance=self._SCALETOL,
3434
+ )
3435
+
3436
+
3437
+ _VirtualSiteType = Literal[
3438
+ "BondCharge",
3439
+ "MonovalentLonePair",
3440
+ "DivalentLonePair",
3441
+ "TrivalentLonePair",
3442
+ ]
3443
+
3444
+
3445
+ class _BaseVirtualSiteType(ParameterType):
3446
+ """
3447
+ Handle virtual site parameters, including geometry and electrostatics, but not vdW interactions.
3448
+
3449
+ .. warning :: This API is experimental and subject to change.
3450
+ """
3451
+
3452
+ _ELEMENT_NAME = "VirtualSite"
3453
+
3454
+ name = ParameterAttribute(default="EP", converter=str)
3455
+ type = ParameterAttribute(converter=str)
3456
+
3457
+ match = ParameterAttribute(converter=str)
3458
+
3459
+ distance = ParameterAttribute(unit=unit.angstrom)
3460
+ outOfPlaneAngle = ParameterAttribute(unit=unit.degree)
3461
+ inPlaneAngle = ParameterAttribute(unit=unit.degree)
3462
+
3463
+ charge_increment = IndexedParameterAttribute(unit=unit.elementary_charge)
3464
+
3465
+ @property
3466
+ def parent_index(self) -> int:
3467
+ """Returns the index of the atom matched by the SMIRKS pattern that should
3468
+ be considered the 'parent' to the virtual site.
3469
+ A value of ``0`` corresponds to the atom matched by the ``:1`` selector in
3470
+ the SMIRKS pattern, a value ``2`` the atom matched by ``:2`` and so on.
3471
+ """
3472
+ return self.type_to_parent_index(self.type)
3473
+
3474
+ @classmethod
3475
+ def type_to_parent_index(cls, type_: _VirtualSiteType) -> int:
3476
+ """Returns the index of the atom matched by the SMIRKS pattern that should
3477
+ be considered the 'parent' to a given type of virtual site.
3478
+ A value of ``0`` corresponds to the atom matched by the ``:1`` selector in
3479
+ the SMIRKS pattern, a value ``2`` the atom matched by ``:2`` and so on.
3480
+ """
3481
+
3482
+ if type_.replace("VirtualSite", "") in get_args(_VirtualSiteType):
3483
+ return 0
3484
+
3485
+ raise NotImplementedError()
3486
+
3487
+ @outOfPlaneAngle.converter # type: ignore[no-redef]
3488
+ def outOfPlaneAngle(self, attr, value):
3489
+ if value == "None":
3490
+ return
3491
+
3492
+ supports_out_of_plane_angle = self._supports_out_of_plane_angle(self.type)
3493
+
3494
+ if not supports_out_of_plane_angle and value is not None:
3495
+ raise SMIRNOFFSpecError(f"'{self.type}' sites do not support `outOfPlaneAngle`")
3496
+ elif supports_out_of_plane_angle:
3497
+ return _validate_units(attr, value, unit.degrees)
3498
+
3499
+ return value
3500
+
3501
+ @inPlaneAngle.converter # type: ignore[no-redef]
3502
+ def inPlaneAngle(self, attr, value):
3503
+ if value == "None":
3504
+ return
3505
+
3506
+ supports_in_plane_angle = self._supports_in_plane_angle(self.type)
3507
+
3508
+ if not supports_in_plane_angle and value is not None:
3509
+ raise SMIRNOFFSpecError(f"'{self.type}' sites do not support `inPlaneAngle`")
3510
+ elif supports_in_plane_angle:
3511
+ return _validate_units(attr, value, unit.degrees)
3512
+
3513
+ return value
3514
+
3515
+ def __init__(self, **kwargs):
3516
+ self._add_default_init_kwargs(kwargs)
3517
+ super().__init__(**kwargs)
3518
+
3519
+ @classmethod
3520
+ def _add_default_init_kwargs(cls, kwargs):
3521
+ """Adds any missing default values to the ``kwargs`` dictionary, and
3522
+ partially validates any provided values that aren't easily validated with
3523
+ converters.
3524
+ """
3525
+
3526
+ type_ = kwargs.get("type", None)
3527
+
3528
+ if type_ is None:
3529
+ raise SMIRNOFFSpecError("the `type` keyword is missing")
3530
+ if type_ not in get_args(_VirtualSiteType):
3531
+ raise SMIRNOFFSpecError(f"'{type_}' is not a supported virtual site type")
3532
+
3533
+ if "charge_increment" in kwargs:
3534
+ expected_num_charge_increments = cls._expected_num_charge_increments(type_)
3535
+ num_charge_increments = len(kwargs["charge_increment"])
3536
+ if num_charge_increments != expected_num_charge_increments:
3537
+ raise SMIRNOFFSpecError(
3538
+ f"'{type_}' virtual sites expect exactly {expected_num_charge_increments} "
3539
+ f"charge increments, but got {kwargs['charge_increment']} "
3540
+ f"(length {num_charge_increments}) instead."
3541
+ )
3542
+
3543
+ supports_in_plane_angle = cls._supports_in_plane_angle(type_)
3544
+ supports_out_of_plane_angle = cls._supports_out_of_plane_angle(type_)
3545
+
3546
+ if not supports_out_of_plane_angle:
3547
+ kwargs["outOfPlaneAngle"] = kwargs.get("outOfPlaneAngle", None)
3548
+ if not supports_in_plane_angle:
3549
+ kwargs["inPlaneAngle"] = kwargs.get("inPlaneAngle", None)
3550
+
3551
+ match = kwargs.get("match", None)
3552
+
3553
+ if match is None:
3554
+ raise SMIRNOFFSpecError("the `match` keyword is missing")
3555
+
3556
+ out_of_plane_angle = kwargs.get("outOfPlaneAngle", 0.0 * unit.degree)
3557
+ is_in_plane = (
3558
+ None if not supports_out_of_plane_angle else numpy.isclose(out_of_plane_angle.m_as(unit.degree), 0.0)
3559
+ )
3560
+
3561
+ if not cls._supports_match(type_, match, is_in_plane):
3562
+ raise SMIRNOFFSpecError(
3563
+ f"match='{match}' not supported with type='{type_}'"
3564
+ + ("" if is_in_plane is None else f" and is_in_plane={is_in_plane}")
3565
+ )
3566
+
3567
+ @classmethod
3568
+ def _supports_in_plane_angle(cls, type_: _VirtualSiteType) -> bool:
3569
+ return type_ in {"MonovalentLonePair"}
3570
+
3571
+ @classmethod
3572
+ def _supports_out_of_plane_angle(cls, type_: _VirtualSiteType) -> bool:
3573
+ return type_ in {"MonovalentLonePair", "DivalentLonePair"}
3574
+
3575
+ @classmethod
3576
+ def _expected_num_charge_increments(cls, type_: _VirtualSiteType) -> int:
3577
+ if type_ == "BondCharge":
3578
+ return 2
3579
+ elif (type_ == "MonovalentLonePair") or (type_ == "DivalentLonePair"):
3580
+ return 3
3581
+ elif type_ == "TrivalentLonePair":
3582
+ return 4
3583
+ raise NotImplementedError()
3584
+
3585
+ @classmethod
3586
+ def _supports_match(cls, type_: _VirtualSiteType, match: str, is_in_plane: bool | None = None) -> bool:
3587
+ is_in_plane = True if is_in_plane is None else is_in_plane
3588
+
3589
+ if match == "once":
3590
+ return type_ == "TrivalentLonePair" or (type_ == "DivalentLonePair" and is_in_plane)
3591
+ elif match == "all_permutations":
3592
+ return type_ in {"BondCharge", "MonovalentLonePair", "DivalentLonePair"}
3593
+
3594
+ raise NotImplementedError()
3595
+
3596
+
3597
+ class VirtualSiteHandler(_NonbondedHandler):
3598
+ """Handle SMIRNOFF ``<VirtualSites>`` tags
3599
+ TODO: Add example usage/documentation
3600
+ .. warning :: This API is experimental and subject to change.
3601
+ """
3602
+
3603
+ class VirtualSiteType(_BaseVirtualSiteType, vdWHandler.vdWType):
3604
+ """Store virtual site parameters (geometry and electrostatics) and vdW interactions."""
3605
+
3606
+ epsilon = ParameterAttribute(default=0.0 * unit.kilocalorie_per_mole, unit=unit.kilocalorie_per_mole)
3607
+ sigma = ParameterAttribute(default=1.0 * unit.angstrom, unit=unit.angstrom)
3608
+ rmin_half = ParameterAttribute(default=None, unit=unit.angstrom)
3609
+
3610
+ def __init__(self, **kwargs):
3611
+ if "rmin_half" not in kwargs:
3612
+ kwargs["sigma"] = kwargs.get("sigma", 0.0 * unit.angstrom)
3613
+
3614
+ kwargs["epsilon"] = kwargs.get("epsilon", 0.0 * unit.kilocalorie_per_mole)
3615
+
3616
+ self._add_default_init_kwargs(kwargs)
3617
+
3618
+ super().__init__(**kwargs)
3619
+
3620
+ _TAGNAME = "VirtualSites"
3621
+ _INFOTYPE = VirtualSiteType
3622
+ _DEPENDENCIES = [
3623
+ ElectrostaticsHandler,
3624
+ LibraryChargeHandler,
3625
+ ChargeIncrementModelHandler,
3626
+ ToolkitAM1BCCHandler,
3627
+ vdWHandler,
3628
+ ]
3629
+
3630
+ exclusion_policy = ParameterAttribute(default="parents")
3631
+
3632
+ @classmethod
3633
+ def _validate_found_match(
3634
+ cls,
3635
+ atoms_by_index: dict,
3636
+ matched_indices: tuple[int, ...],
3637
+ parameter: VirtualSiteType,
3638
+ ):
3639
+ """
3640
+ We place limitations on the chemical environments that certain types of v-site
3641
+ can be applied to, e.g. we enforce that divalent lone pairs can only be applied
3642
+ to environments that look like a carboxyl group.
3643
+ These somewhat artificial restrictions limit the number of potential edge
3644
+ cases that need to be thought through, and significantly reduces the number
3645
+ of test cases / problematic choices that need to be made. If users meet a not
3646
+ supported exception, they should open an issue on GitHub explaining their exact
3647
+ use case so that we can ensure that exactly what they need is both supported
3648
+ and works as expected through expansion of the unit tests.
3649
+
3650
+ This validation can be disabled by assigning the environment variable
3651
+ `OPENFF_UNSAFE_VSITES=1`.
3652
+ """
3653
+ import os
3654
+
3655
+ if os.environ.get("OPENFF_UNSAFE_VSITES", "0") != "0":
3656
+ return
3657
+ supported_connectivity = {
3658
+ # We currently expect monovalent lone pairs to be applied to something
3659
+ # like a carboxyl group, where the parent of the lone pair has a
3660
+ # connectivity of 1, while it neighbour has a connectivity of 3
3661
+ ("MonovalentLonePair", 0): 1,
3662
+ ("MonovalentLonePair", 1): 3,
3663
+ # We currently expect divalent lone pairs to be applied to something
3664
+ # like an sp2 nitrogen, or a hydroxyl oxygen
3665
+ ("DivalentLonePair", 0): 2,
3666
+ # We currently expect trivalent lone pairs to be applied to something
3667
+ # like an sp3 nitrogen
3668
+ ("TrivalentLonePair", 0): 3,
3669
+ }
3670
+
3671
+ for smirks_index, atom_index in enumerate(matched_indices):
3672
+ if (parameter.type, smirks_index) not in supported_connectivity:
3673
+ # No restrictions placed on this matched atom.
3674
+ continue
3675
+
3676
+ matched_atom = atoms_by_index[atom_index]
3677
+ connectivity = len(matched_atom.bonds)
3678
+ expected_connectivity = supported_connectivity[(parameter.type, smirks_index)]
3679
+ if expected_connectivity == connectivity:
3680
+ continue
3681
+
3682
+ raise NotImplementedError(
3683
+ f"{parameter.smirks} matched chemical environment that is currently "
3684
+ f"unsupported by virtual sites of type {parameter.type}. Atom with "
3685
+ f"smirks index={smirks_index} matched topology atom {atom_index} with "
3686
+ f"connectivity={connectivity}, but it was expected to have connectivity "
3687
+ f"{expected_connectivity}. If you are getting this error and aren't "
3688
+ f"developing your own force field, it indicates that the FF you're "
3689
+ f"using never expected to see a molecule like this. If you ARE developing "
3690
+ f"a force field and know that you want to squelch this error, set the "
3691
+ f"environment variable `OPENFF_UNSAFE_VSITES=1`."
3692
+ )
3693
+
3694
+ def check_handler_compatibility(self, other_handler: "VirtualSiteHandler"):
3695
+ self._check_attributes_are_equal(
3696
+ other_handler,
3697
+ identical_attrs=("exclusion_policy",),
3698
+ )
3699
+
3700
+ def _index_of_parameter(
3701
+ self,
3702
+ parameter: ParameterType | None = None,
3703
+ key: Any | None = None,
3704
+ ) -> int | None:
3705
+ """Attempts to find the index of a parameter in the parameters list.
3706
+ By default, two parameters are considered 'the same' if they have the same
3707
+ SMIRKS pattern, type, and name.
3708
+ Parameters
3709
+ ----------
3710
+ parameter
3711
+ The parameter to find the index of. This argument is mutually exclusive with
3712
+ ``key``.
3713
+ key
3714
+ A tuple of the type, SMIRKS, and name of the parameter to find the index
3715
+ of. This argument is mutually exclusive with ``parameter``.
3716
+ Returns
3717
+ -------
3718
+ The index of the parameter if found, otherwise ``None``.
3719
+ """
3720
+
3721
+ if (key is None and parameter is None) or (key is not None and parameter is not None):
3722
+ raise ValueError("`key` and `parameter` are mutually exclusive arguments")
3723
+
3724
+ key = cast(
3725
+ tuple[str, str, str],
3726
+ (key if parameter is None else (parameter.type, parameter.smirks, parameter.name)),
3727
+ )
3728
+ expected_type, expected_smirks, expected_name = key
3729
+
3730
+ for i, existing_parameter in enumerate(self.parameters):
3731
+ if (
3732
+ existing_parameter.type != expected_type
3733
+ or existing_parameter.smirks != expected_smirks
3734
+ or existing_parameter.name != expected_name
3735
+ ):
3736
+ continue
3737
+
3738
+ return i
3739
+
3740
+ return None
3741
+
3742
+ def _find_matches_by_parent(self, entity: Topology) -> dict[int, list]:
3743
+ from collections import defaultdict
3744
+
3745
+ topology_atoms = {i: topology_atom for i, topology_atom in enumerate(entity.atoms)}
3746
+
3747
+ # We need to find all the parameters that would lead to a v-site being placed
3748
+ # onto a given 'parent atom'. We only allow each parent atom to be assigned one
3749
+ # v-site with a given 'name', whereby the last parameter to be matched wins.
3750
+ matches_by_parent: dict = defaultdict(lambda: defaultdict(list))
3751
+
3752
+ for parameter in self._parameters:
3753
+ # Filter for redundant matches caused by non-tagged atoms
3754
+ # See https://github.com/openforcefield/openff-toolkit/issues/1739
3755
+ seen_topology_atom_indices = set()
3756
+ for match in entity.chemical_environment_matches(parameter.smirks):
3757
+ if match.topology_atom_indices in seen_topology_atom_indices:
3758
+ continue
3759
+ else:
3760
+ seen_topology_atom_indices.add(match.topology_atom_indices)
3761
+
3762
+ parent_index = match.topology_atom_indices[parameter.parent_index]
3763
+
3764
+ matches_by_parent[parent_index][parameter.name].append((parameter, match))
3765
+
3766
+ # we then need to find which parameter was the last one to be assigned to each
3767
+ # given 'parent' atom, and all the ways that that parameter matches the atoms
3768
+ # surrounding the parent. Whether we keep the different orientations or not
3769
+ # depends on the 'match' setting of the parameter.
3770
+ assigned_matches_by_parent = defaultdict(list)
3771
+
3772
+ for parent_index, matches_by_name in matches_by_parent.items():
3773
+ for matches in matches_by_name.values():
3774
+ assigned_parameter, _ = matches[-1] # last match wins
3775
+
3776
+ match_orientations = [
3777
+ match for parameter_index, match in matches if parameter_index == assigned_parameter
3778
+ ]
3779
+
3780
+ if assigned_parameter.match == "once":
3781
+ # the v-site types were designed such that we should be safe
3782
+ # choosing an arbitrary ordering of the non-parent matched atoms.
3783
+ match_orientations = [match_orientations[0]]
3784
+ elif assigned_parameter.match == "all_permutations":
3785
+ pass
3786
+ else:
3787
+ raise SMIRNOFFSpecError(f"{assigned_parameter.match} match keyword is not supported")
3788
+
3789
+ assigned_matches_by_parent[parent_index].append((assigned_parameter, match_orientations))
3790
+
3791
+ for match in match_orientations:
3792
+ # make sure the match does not look like a weird edge case that we
3793
+ # haven't tested to ensure 'sensible' behaviour in most cases.
3794
+ self._validate_found_match(topology_atoms, match.topology_atom_indices, assigned_parameter)
3795
+
3796
+ return assigned_matches_by_parent
3797
+
3798
+ def _find_matches(
3799
+ self,
3800
+ entity: Topology,
3801
+ transformed_dict_cls=dict,
3802
+ unique=False,
3803
+ ) -> dict[tuple[int], list[ParameterHandler._Match]]:
3804
+ assigned_matches_by_parent = self._find_matches_by_parent(entity)
3805
+ return_dict = {}
3806
+ for parent_index, assigned_parameters in assigned_matches_by_parent.items():
3807
+ assigned_matches = []
3808
+ for assigned_parameter, match_orientations in assigned_parameters:
3809
+ for match in match_orientations:
3810
+ assigned_matches.append(ParameterHandler._Match(assigned_parameter, match))
3811
+ return_dict[(parent_index,)] = assigned_matches
3812
+
3813
+ return return_dict
3814
+
3815
+ def __init__(self, **kwargs):
3816
+ super().__init__(**kwargs)
3817
+ self._parameters = VirtualSiteParameterList()
3818
+
3819
+ def __getitem__(self, val):
3820
+ return self.parameters.__getitem__(val)
3821
+
3822
+
3823
+ ConstraintType = ConstraintHandler.ConstraintType
3824
+ BondType = BondHandler.BondType
3825
+ AngleType = AngleHandler.AngleType
3826
+ ProperTorsionType = ProperTorsionHandler.ProperTorsionType
3827
+ ImproperTorsionType = ImproperTorsionHandler.ImproperTorsionType
3828
+ vdWType = vdWHandler.vdWType
3829
+ LibraryChargeType = LibraryChargeHandler.LibraryChargeType
3830
+ GBSAType = GBSAHandler.GBSAType
3831
+ ChargeIncrementType = ChargeIncrementModelHandler.ChargeIncrementType
3832
+ VirtualSiteType = VirtualSiteHandler.VirtualSiteType
3833
+
3834
+
3835
+ if __name__ == "__main__":
3836
+ import doctest
3837
+
3838
+ doctest.testmod()
3839
+ # doctest.run_docstring_examples(_ParameterAttributeHandler, globals())