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,1440 @@
1
+ """
2
+ Parameter assignment tools for the SMIRNOFF (SMIRKS Native Open Force Field) format.
3
+
4
+ .. codeauthor:: John D. Chodera <john.chodera@choderalab.org>
5
+ .. codeauthor:: David L. Mobley <dmobley@mobleylab.org>
6
+ .. codeauthor:: Peter K. Eastman <peastman@stanford.edu>
7
+
8
+ .. todo ::
9
+
10
+ * Speed up overall import time by putting non-global imports only where they are needed
11
+
12
+ """
13
+
14
+ import logging
15
+ import os
16
+ import pathlib
17
+ from importlib.metadata import entry_points
18
+ from typing import IO, TYPE_CHECKING, Any, Union
19
+
20
+ from packaging.version import Version
21
+
22
+ from openff.toolkit import Quantity
23
+ from openff.toolkit.typing.engines.smirnoff.io import ParameterIOHandler
24
+ from openff.toolkit.typing.engines.smirnoff.parameters import ParameterHandler
25
+ from openff.toolkit.typing.engines.smirnoff.plugins import load_handler_plugins
26
+ from openff.toolkit.utils.constants import (
27
+ ALLOWED_AROMATICITY_MODELS,
28
+ DEFAULT_AROMATICITY_MODEL,
29
+ )
30
+ from openff.toolkit.utils.exceptions import (
31
+ ParameterHandlerRegistrationError,
32
+ PartialChargeVirtualSitesError,
33
+ SMIRNOFFAromaticityError,
34
+ SMIRNOFFParseError,
35
+ SMIRNOFFVersionError,
36
+ )
37
+ from openff.toolkit.utils.utils import (
38
+ all_subclasses,
39
+ convert_0_1_smirnoff_to_0_2,
40
+ convert_0_2_smirnoff_to_0_3,
41
+ convert_all_quantities_to_string,
42
+ convert_all_strings_to_quantity,
43
+ requires_package,
44
+ )
45
+
46
+ if TYPE_CHECKING:
47
+ import openmm
48
+ from openff.interchange import Interchange
49
+
50
+ from openff.toolkit import Molecule
51
+ from openff.toolkit.topology.topology import Topology, ValenceDict
52
+ from openff.toolkit.utils.base_wrapper import ToolkitWrapper
53
+ from openff.toolkit.utils.toolkit_registry import ToolkitRegistry
54
+
55
+
56
+ __all__ = [
57
+ "MAX_SUPPORTED_VERSION",
58
+ "ForceField",
59
+ "ParameterHandlerRegistrationError",
60
+ "PartialChargeVirtualSitesError",
61
+ "SMIRNOFFAromaticityError",
62
+ "SMIRNOFFParseError",
63
+ "SMIRNOFFVersionError",
64
+ "get_available_force_fields",
65
+ ]
66
+
67
+ logger = logging.getLogger(__name__)
68
+
69
+ # Directory paths used by ForceField to discover offxml files.
70
+ _installed_offxml_dir_paths: list[str] = []
71
+
72
+
73
+ def _get_installed_offxml_dir_paths() -> list[str]:
74
+ """Return the list of directory paths where to search for offxml files.
75
+
76
+ This function load the information by calling all the entry points
77
+ registered in the "openff.forcefielddirs" group. Each entry point
78
+ (i.e. a function) should return a list of paths to directories
79
+ containing the offxml files.
80
+
81
+ Returns
82
+ -------
83
+ installed_offxml_dir_paths :list[str]
84
+ All the installed directory paths where ``ForceField`` will
85
+ look for offxml files.
86
+
87
+ """
88
+ global _installed_offxml_dir_paths
89
+ if len(_installed_offxml_dir_paths) == 0:
90
+ # Find all registered entry points that should return a list of
91
+ # paths to directories where to search for offxml files.
92
+ for entry_point in entry_points().select(group="openforcefield.smirnoff_forcefield_directory"):
93
+ _installed_offxml_dir_paths.extend(entry_point.load()())
94
+ return _installed_offxml_dir_paths
95
+
96
+
97
+ def get_available_force_fields(full_paths=False):
98
+ r"""
99
+ Get the filenames of all available .offxml force field files.
100
+
101
+ Availability is determined by what is discovered through the
102
+ ``openforcefield.smirnoff_forcefield_directory`` entry point. If the
103
+ ``openff-forcefields`` package is installed, this should include several
104
+ .offxml files such as ``openff-1.0.0.offxml``.
105
+
106
+ Parameters
107
+ ----------
108
+ full_paths
109
+ If False, return the name of each available \*.offxml file.
110
+ If True, return the full path to each available \*.offxml file.
111
+
112
+ Returns
113
+ -------
114
+ available_force_fields
115
+ List of available force field files
116
+
117
+ """
118
+ installed_paths = _get_installed_offxml_dir_paths()
119
+ available_force_fields = []
120
+ for installed_path in installed_paths:
121
+ for globbed in pathlib.Path(installed_path).rglob("*.offxml"):
122
+ if full_paths:
123
+ available_force_fields.append(globbed.as_posix())
124
+ else:
125
+ available_force_fields.append(globbed.name)
126
+ return available_force_fields
127
+
128
+
129
+ # TODO: Instead of having a global version number, alow each Force to have a separate version number
130
+ MAX_SUPPORTED_VERSION = "1.0" # maximum version of the SMIRNOFF spec supported by this SMIRNOFF force field
131
+
132
+
133
+ class ForceField:
134
+ """
135
+ A factory that assigns SMIRNOFF parameters to a molecular system
136
+
137
+ :class:`ForceField` is a factory that constructs an
138
+ OpenMM :class:`System <openmm.openmm.System>` object from a
139
+ :class:`Topology <openff.toolkit.topology.Topology>` object defining a
140
+ (bio)molecular system containing one or more molecules.
141
+
142
+ When a :class:`ForceField` object is created from one or more specified
143
+ SMIRNOFF serialized representations, all :class:`ParameterHandler
144
+ <openff.toolkit.typing.engines.smirnoff.parameters.ParameterHandler>`
145
+ subclasses currently imported are identified and registered to handle
146
+ different sections of the SMIRNOFF force field definition file(s).
147
+
148
+ All :class:`ParameterIOHandler` subclasses currently imported are identified
149
+ and registered to handle different serialization formats (such as XML).
150
+
151
+ The force field definition is processed by these handlers to populate the
152
+ ``ForceField`` object model data structures that can easily be manipulated
153
+ via the API:
154
+
155
+ Processing a :class:`Topology` object defining a chemical system will then
156
+ call all :class:`ParameterHandler` objects in an order guaranteed to
157
+ satisfy the declared processing order constraints of each
158
+ :class:`ParameterHandler`.
159
+
160
+ Examples
161
+ --------
162
+
163
+ Create a new ForceField object from the distributed OpenFF 2.0 ("Sage") file:
164
+
165
+ >>> from openff.toolkit import ForceField
166
+ >>> force_field = ForceField('openff-2.0.0.offxml')
167
+
168
+ Create an OpenMM system from a :class:`openff.toolkit.topology.Topology` object:
169
+
170
+ >>> from openff.toolkit import Molecule, Topology
171
+ >>> ethanol = Molecule.from_smiles('CCO')
172
+ >>> topology = Topology.from_molecules(molecules=[ethanol])
173
+ >>> system = force_field.create_openmm_system(topology)
174
+
175
+ Modify the long-range electrostatics method:
176
+
177
+ >>> force_field.get_parameter_handler('Electrostatics').periodic_potential = 'PME'
178
+
179
+ Inspect the first few vdW parameters:
180
+
181
+ >>> low_precedence_parameters = force_field.get_parameter_handler('vdW').parameters[0:3]
182
+
183
+ Retrieve the vdW parameters by SMIRKS string and manipulate it:
184
+
185
+ >>> from openff.toolkit import unit
186
+ >>> parameter = force_field.get_parameter_handler('vdW').parameters['[#1:1]-[#7]']
187
+ >>> parameter.rmin_half += 0.1 * unit.angstroms
188
+ >>> parameter.epsilon *= 1.02
189
+
190
+ Make a child vdW type more specific (checking modified SMIRKS for validity):
191
+
192
+ >>> force_field.get_parameter_handler('vdW').parameters[-1].smirks += '~[#53]'
193
+
194
+ .. warning ::
195
+
196
+ While we check whether the modified SMIRKS is still valid and has the appropriate valence type,
197
+ we currently don't check whether the typing remains hierarchical, which could result in some types
198
+ no longer being assignable because more general types now come *below* them and preferentially match.
199
+
200
+ Delete a parameter:
201
+
202
+ >>> del force_field.get_parameter_handler('vdW').parameters['[#1:1]-[#6X4]']
203
+
204
+ Insert a parameter at a specific point in the parameter tree:
205
+
206
+ >>> from openff.toolkit.typing.engines.smirnoff import vdWHandler
207
+ >>> new_parameter = vdWHandler.vdWType(
208
+ ... smirks='[*:1]',
209
+ ... epsilon=0.0157*unit.kilocalories_per_mole,
210
+ ... rmin_half=0.6000*unit.angstroms,
211
+ ... )
212
+ >>> force_field.get_parameter_handler('vdW').parameters.insert(0, new_parameter)
213
+
214
+ .. warning ::
215
+
216
+ We currently don't check whether removing a parameter could accidentally remove the root type, so it's possible
217
+ to no longer type all molecules this way.
218
+
219
+ """
220
+
221
+ def __init__(
222
+ self,
223
+ *sources,
224
+ aromaticity_model: str = DEFAULT_AROMATICITY_MODEL,
225
+ parameter_handler_classes: list[type[ParameterHandler]] | None = None,
226
+ parameter_io_handler_classes: list[type[ParameterIOHandler]] | None = None,
227
+ disable_version_check: bool = False,
228
+ allow_cosmetic_attributes: bool = False,
229
+ load_plugins: bool = False,
230
+ ):
231
+ """Create a new :class:`ForceField` object from one or more SMIRNOFF parameter definition files.
232
+
233
+ Parameters
234
+ ----------
235
+ sources
236
+ A list of files defining the SMIRNOFF force field to be loaded.
237
+ Currently, only `the SMIRNOFF XML format <https://openforcefield.github.io/standards/standards/smirnoff/>`_
238
+ is supported. Each entry may be an absolute file path, a path relative to the current working directory, a
239
+ path relative to this module's data subdirectory (for built in force fields), or an open file-like object
240
+ with a ``read()`` method from which the force field XML data can be loaded. If multiple files are
241
+ specified, any top-level tags that are repeated will be merged if they are compatible, with files appearing
242
+ later in the sequence resulting in parameters that have higher precedence. Support for multiple files is
243
+ primarily intended to allow solvent parameters to be specified by listing them last in the sequence.
244
+ aromaticity_model
245
+ The aromaticity model to use. Only OEAroModel_MDL is supported.
246
+ parameter_handler_classes
247
+ If not None, the specified set of ParameterHandler classes will be instantiated to create the parameter
248
+ object model. By default, all imported subclasses of ParameterHandler not loaded as plugins are
249
+ automatically registered.
250
+ parameter_io_handler_classes
251
+ If not None, the specified set of ParameterIOHandler classes will be used to parse/generate serialized
252
+ parameter sets. By default, all imported subclasses of ParameterIOHandler are automatically registered.
253
+ disable_version_check
254
+ If True, will disable checks against the current highest supported force field version.
255
+ This option is primarily intended for force field development.
256
+ allow_cosmetic_attributes
257
+ Whether to retain non-spec kwargs from data sources.
258
+ load_plugins
259
+ Whether to load ``ParameterHandler`` classes which have been registered
260
+ by installed plugins.
261
+
262
+ Examples
263
+ --------
264
+
265
+ Load one SMIRNOFF parameter set in XML format (searching the package data directory by default, which includes
266
+ some standard parameter sets):
267
+
268
+ >>> forcefield = ForceField('openff-2.0.0.offxml')
269
+
270
+ Load multiple SMIRNOFF parameter sets:
271
+
272
+ >>> from openff.toolkit._tests.utils import get_data_file_path
273
+ >>> forcefield = ForceField('openff-2.0.0.offxml', get_data_file_path('test_forcefields/tip3p.offxml'))
274
+
275
+ Load a parameter set from a string:
276
+
277
+ >>> offxml = '<SMIRNOFF version="0.2" aromaticity_model="OEAroModel_MDL"/>'
278
+ >>> forcefield = ForceField(offxml)
279
+
280
+ See Also
281
+ --------
282
+ parse_sources
283
+
284
+ Notes
285
+ -----
286
+ No effort is made to de-duplicate redundant parameters or parameters with identical SMIRKS patterns.
287
+
288
+ """
289
+ # Clear all object fields
290
+ self._initialize()
291
+
292
+ self.aromaticity_model = aromaticity_model
293
+ # Store initialization options
294
+ self.disable_version_check = disable_version_check
295
+ # if True, we won't check which SMIRNOFF version number we're parsing
296
+
297
+ # Register all ParameterHandler objects that will process SMIRNOFF force definitions
298
+ # TODO: We need to change this to just find all ParameterHandler objects in this file;
299
+ # otherwise, we can't define two different ParameterHandler subclasses to compare for a new type of energy term
300
+ # since both will try to register themselves for the same XML tag and an Exception will be raised.
301
+ if parameter_handler_classes is None:
302
+ # TODO: What is the point of this argument? The default behavior includes a lot of logic.
303
+ # Unaware of cases in which the argument is used.
304
+
305
+ internal_module = "openff.toolkit.typing.engines.smirnoff.parameters"
306
+
307
+ # Plugins, if already loaded, are also subclasses of ParameterHandler and therefore
308
+ # show up in all_subclasses, but we don't want them included here. Checking the
309
+ # module each come from is the safest way to know which are plugins; another
310
+ # option is explicitly defining a set of default handlers
311
+
312
+ default_handlers: list[type[ParameterHandler]] = [
313
+ handler for handler in all_subclasses(ParameterHandler) if handler.__module__ == internal_module
314
+ ]
315
+
316
+ # We could also track a list of the plugins that were already loaded, but that's not necessary here
317
+ # since we're only cleaning out the handlers that were already registered.
318
+ parameter_handler_classes = default_handlers
319
+
320
+ if load_plugins:
321
+ plugin_classes = load_handler_plugins()
322
+
323
+ for plugin_class in plugin_classes:
324
+ parameter_handler_classes.append(plugin_class)
325
+ self._plugin_parameter_handler_classes.append(plugin_class)
326
+
327
+ self._register_parameter_handler_classes(parameter_handler_classes)
328
+
329
+ # Register all ParameterIOHandler objects that will process serialized parameter representations
330
+ if parameter_io_handler_classes is None:
331
+ parameter_io_handler_classes = all_subclasses(ParameterIOHandler)
332
+
333
+ self._register_parameter_io_handler_classes(parameter_io_handler_classes)
334
+
335
+ # Parse all sources containing SMIRNOFF parameter definitions
336
+ self.parse_sources(sources, allow_cosmetic_attributes=allow_cosmetic_attributes)
337
+
338
+ def _initialize(self):
339
+ """
340
+ Initialize all object fields.
341
+ """
342
+ self._MIN_SUPPORTED_SMIRNOFF_VERSION = Version("0.1")
343
+ self._MAX_SUPPORTED_SMIRNOFF_VERSION = Version("0.3")
344
+ # if True, will disable checking compatibility version
345
+ self._disable_version_check = False
346
+ self._aromaticity_model = DEFAULT_AROMATICITY_MODEL
347
+ # Parameter handler classes that _can_ be initialized if needed
348
+ self._parameter_handler_classes: dict[str, type[ParameterHandler]] = dict()
349
+ # ParameterHandler classes to be instantiated for each parameter type
350
+ self._parameter_handlers: dict[str, ParameterHandler] = dict()
351
+ # classes of ParameterHandlers that were registered via the plugin interface
352
+ self._plugin_parameter_handler_classes: list[type[ParameterHandler]] = list()
353
+ # ParameterIOHandler classes that _can_ be initialiazed if needed
354
+ self._parameter_io_handler_classes: dict[str, type[ParameterIOHandler]] = dict()
355
+ # ParameterIO classes to be used for each file type
356
+ self._parameter_io_handlers: dict[str, ParameterIOHandler] = dict()
357
+ # It'd be much more convenient for these to only be str, and just default to the empty string
358
+ self._author: str | None = None
359
+ self._date: str | None = None
360
+
361
+ def _check_smirnoff_version_compatibility(self, version: str):
362
+ """
363
+ Raise a parsing exception if the given file version is incompatible with this ForceField class.
364
+
365
+ Parameters
366
+ ----------
367
+ version
368
+ The SMIRNOFF version being read.
369
+
370
+ Raises
371
+ ------
372
+ SMIRNOFFVersionError
373
+ If an incompatible version is passed in.
374
+
375
+ """
376
+ from packaging.version import parse
377
+
378
+ # Use PEP-440 compliant version number comparison, if requested
379
+ if self.disable_version_check:
380
+ pass
381
+ else:
382
+ if (parse(str(version)) > parse(str(self._MAX_SUPPORTED_SMIRNOFF_VERSION))) or (
383
+ parse(str(version)) < parse(str(self._MIN_SUPPORTED_SMIRNOFF_VERSION))
384
+ ):
385
+ raise SMIRNOFFVersionError(
386
+ f"SMIRNOFF offxml file was written with version {version}, but this version of "
387
+ f"ForceField only supports version {self._MIN_SUPPORTED_SMIRNOFF_VERSION} to "
388
+ f"version {self._MAX_SUPPORTED_SMIRNOFF_VERSION}"
389
+ )
390
+
391
+ @property
392
+ def aromaticity_model(self) -> str:
393
+ """Returns the aromaticity model for this ForceField object.
394
+
395
+ Returns
396
+ -------
397
+ aromaticity_model
398
+ The aromaticity model for this force field.
399
+ """
400
+ return self._aromaticity_model
401
+
402
+ @aromaticity_model.setter
403
+ def aromaticity_model(self, aromaticity_model: str):
404
+ """
405
+ Register that this force field is using an aromaticity model. Will check for
406
+ compatibility with other aromaticity model(s) already in use.
407
+
408
+ Parameters
409
+ ----------
410
+ aromaticity_model
411
+ The aromaticity model to register.
412
+
413
+ Raises
414
+ ------
415
+ SMIRNOFFAromaticityError
416
+ If an incompatible aromaticity model is passed in.
417
+
418
+ Notes
419
+ -----
420
+ * Currently, the only supported aromaticity model is 'OEAroModel_MDL'.
421
+
422
+ """
423
+ # Implement better logic here if we ever support another aromaticity model
424
+ if aromaticity_model not in ALLOWED_AROMATICITY_MODELS:
425
+ raise SMIRNOFFAromaticityError(
426
+ f"Read aromaticity model {aromaticity_model} which is not in the set of allowed aromaticity models: "
427
+ f"{ALLOWED_AROMATICITY_MODELS}"
428
+ )
429
+
430
+ self._aromaticity_model = aromaticity_model
431
+
432
+ def _add_author(self, author: str):
433
+ """
434
+ Add an author to this force field. If this functional is called multiple times, all provided authors
435
+ will be concatenated with the string " AND ". No redundancy checking is performed by this function.
436
+
437
+ Parameters
438
+ ----------
439
+ author
440
+ The author to add to this ForceField object
441
+ """
442
+ if self._author is None:
443
+ self._author = author
444
+ else:
445
+ self._author += " AND " + author
446
+
447
+ def _add_date(self, date: str):
448
+ """
449
+ Add an date to this force field. If this functional is called multiple times, all provided dates
450
+ will be concatenated with the string " AND ". No redundancy checking is performed by this function.
451
+
452
+ Parameters
453
+ ----------
454
+ date
455
+ The author to add to this ForceField object
456
+ """
457
+ if self._date is None:
458
+ self._date = date
459
+ else:
460
+ self._date += " AND " + date
461
+
462
+ @property
463
+ def author(self) -> str | None:
464
+ """Returns the author data for this ForceField object. If not defined in any loaded files, this will be None.
465
+
466
+ Returns
467
+ -------
468
+ author
469
+ The author data for this force field.
470
+ """
471
+ return self._author
472
+
473
+ @author.setter
474
+ def author(self, author: str | None):
475
+ """Set the author data for this ForceField object. If not defined in any loaded files, this will be None.
476
+
477
+ Parameters
478
+ ----------
479
+ author
480
+ The author data to set for this force field.
481
+ """
482
+ self._author = author
483
+
484
+ @property
485
+ def date(self) -> str | None:
486
+ """Returns the date data for this ForceField object. If not defined in any loaded files, this will be None.
487
+
488
+ Returns
489
+ -------
490
+ date
491
+ The date data for this force field.
492
+ """
493
+ return self._date
494
+
495
+ @date.setter
496
+ def date(self, date: str | None):
497
+ """Set the author data for this ForceField object. If not defined in any loaded files, this will be None.
498
+
499
+ Parameters
500
+ ----------
501
+ date
502
+ The date data to set for this force field.
503
+ """
504
+ self._date = date
505
+
506
+ def _register_parameter_handler_classes(
507
+ self,
508
+ parameter_handler_classes: list[type[ParameterHandler]],
509
+ ):
510
+ """
511
+ Register multiple ParameterHandler classes, ensuring they specify unique tags to process
512
+
513
+ .. warning :: This API is experimental and subject to change.
514
+
515
+ Parameters
516
+ ----------
517
+ parameter_handler_classes
518
+ List of ParameterHandler classes to register for this ForceField.
519
+ """
520
+ for parameter_handler_class in parameter_handler_classes:
521
+ tagname = parameter_handler_class._TAGNAME
522
+ if tagname is not None:
523
+ if tagname in self._parameter_handler_classes:
524
+ raise ParameterHandlerRegistrationError(
525
+ f"Attempting to register ParameterHandler {parameter_handler_class}, which provides a parser "
526
+ "for tag '{tagname}', but ParameterHandler {self._parameter_handler_classes[tagname]} has "
527
+ "already been registered to handle that tag."
528
+ )
529
+ self._parameter_handler_classes[tagname] = parameter_handler_class
530
+
531
+ def _register_parameter_io_handler_classes(
532
+ self,
533
+ parameter_io_handler_classes: list[type[ParameterIOHandler]],
534
+ ):
535
+ """
536
+ Register multiple ParameterIOHandler classes, ensuring they specify unique suffixes
537
+
538
+ .. warning :: This API is experimental and subject to change.
539
+
540
+ Parameters
541
+ ----------
542
+ parameter_io_handler_classes
543
+ All specified ParameterIOHandler classes will be registered as ways to translate to/from the object model
544
+ to serialized parameter sets.
545
+
546
+ Raises
547
+ ------
548
+ Exception
549
+ If two ParameterIOHandlers are attempted to be registered for the same file format.
550
+
551
+ """
552
+ for parameter_io_handler_class in parameter_io_handler_classes:
553
+ serialization_format = parameter_io_handler_class._FORMAT
554
+ if serialization_format is not None:
555
+ if serialization_format in self._parameter_io_handler_classes.keys():
556
+ raise ParameterHandlerRegistrationError(
557
+ f"Attempting to register ParameterIOHandler {parameter_io_handler_class}, which provides a IO "
558
+ "parser for format '{serialization_format}', but ParameterIOHandler "
559
+ "{self._parameter_io_handler_classes[serialization_format]} has already been registered to "
560
+ "handle that tag."
561
+ )
562
+ self._parameter_io_handler_classes[serialization_format] = parameter_io_handler_class
563
+
564
+ def register_parameter_handler(self, parameter_handler: ParameterHandler):
565
+ """
566
+ Register a new ParameterHandler for a specific tag, making it
567
+ available for lookup in the ForceField.
568
+
569
+ .. warning :: This API is experimental and subject to change.
570
+
571
+ Parameters
572
+ ----------
573
+ parameter_handler
574
+ The ParameterHandler to register. The TAGNAME attribute of this object will be used as the key for
575
+ registration.
576
+
577
+ """
578
+ if not parameter_handler._TAGNAME:
579
+ raise ValueError("Handler's `_TAGNAME` must not be `None`.")
580
+
581
+ tagname = parameter_handler._TAGNAME
582
+ if tagname in self._parameter_handlers.keys():
583
+ raise ParameterHandlerRegistrationError(
584
+ f"Tried to register parameter handler '{parameter_handler}' for tag '{tagname}', but "
585
+ f"tag is already registered to {self._parameter_handlers[tagname]}"
586
+ )
587
+
588
+ self._parameter_handlers[parameter_handler._TAGNAME] = parameter_handler
589
+ self._parameter_handler_classes[parameter_handler._TAGNAME] = type(parameter_handler)
590
+
591
+ def register_parameter_io_handler(self, parameter_io_handler: ParameterIOHandler):
592
+ """
593
+ Register a new ParameterIOHandler, making it available for lookup in the ForceField.
594
+
595
+ .. warning :: This API is experimental and subject to change.
596
+
597
+ Parameters
598
+ ----------
599
+ parameter_io_handler
600
+ The ParameterIOHandler to register. The FORMAT attribute of this object will be used
601
+ to associate it to a file format/suffix.
602
+
603
+ """
604
+ io_format = parameter_io_handler._FORMAT
605
+ if io_format in self._parameter_io_handlers.keys():
606
+ raise ParameterHandlerRegistrationError(
607
+ f"Tried to register parameter IO handler '{parameter_io_handler}' for tag '{io_format}', but "
608
+ f"tag is already registered to {self._parameter_io_handlers[io_format]}"
609
+ )
610
+ self._parameter_io_handlers[io_format] = parameter_io_handler
611
+
612
+ @property
613
+ def registered_parameter_handlers(self) -> list[str]:
614
+ """
615
+ Return the list of registered parameter handlers by name
616
+
617
+ .. warning :: This API is experimental and subject to change.
618
+
619
+ Returns
620
+ -------
621
+ registered_parameter_handlers
622
+
623
+ """
624
+ return [*self._parameter_handlers.keys()]
625
+
626
+ def get_parameter_handler(
627
+ self,
628
+ tagname: str,
629
+ handler_kwargs: dict | None = None,
630
+ allow_cosmetic_attributes: bool = False,
631
+ ) -> ParameterHandler:
632
+ """Retrieve the parameter handlers associated with the provided tagname.
633
+
634
+ If the parameter handler has not yet been instantiated, it will be created and returned.
635
+ If a parameter handler object already exists, it will be checked for compatibility
636
+ and an Exception raised if it is incompatible with the provided kwargs. If compatible, the
637
+ existing ParameterHandler will be returned.
638
+
639
+ Parameters
640
+ ----------
641
+ tagname
642
+ The name of the parameter to be handled.
643
+ handler_kwargs
644
+ Dict to be passed to the handler for construction or checking compatibility. If this is None and no
645
+ existing ParameterHandler exists for the desired tag, a handler will be initialized with all default
646
+ values. If this is None and a handler for the desired tag exists, the existing ParameterHandler will
647
+ be returned.
648
+ allow_cosmetic_attributes
649
+ Whether to permit non-spec kwargs in smirnoff_data.
650
+
651
+ Returns
652
+ -------
653
+ handler
654
+
655
+ Raises
656
+ ------
657
+ KeyError
658
+ If there is no ParameterHandler for the given tagname
659
+ """
660
+ # If there are no kwargs for the handler, initialize handler_kwargs as an empty dict
661
+ skip_version_check = False
662
+ if handler_kwargs is None:
663
+ handler_kwargs = dict()
664
+ skip_version_check = True
665
+
666
+ # Ensure that the ForceField has a ParameterHandler class registered that can handle this tag
667
+ ph_class = self._get_parameter_handler_class(tagname)
668
+
669
+ if tagname in self._parameter_handlers:
670
+ # If a handler of this class already exists, ensure that the two handlers encode compatible science
671
+ old_handler = self._parameter_handlers[tagname]
672
+ # If no handler kwargs were provided, skip the compatibility check
673
+ if handler_kwargs != {}:
674
+ # Initialize a new instance of this parameter handler class with the given kwargs
675
+ new_handler = ph_class(
676
+ **handler_kwargs,
677
+ allow_cosmetic_attributes=allow_cosmetic_attributes,
678
+ skip_version_check=skip_version_check,
679
+ )
680
+ old_handler.check_handler_compatibility(new_handler)
681
+ return_handler = old_handler
682
+ elif tagname in self._parameter_handler_classes:
683
+ # Otherwise, register this handler in the force field
684
+ # Initialize a new instance of this parameter handler class with the given kwargs
685
+ new_handler = ph_class(
686
+ **handler_kwargs,
687
+ allow_cosmetic_attributes=allow_cosmetic_attributes,
688
+ skip_version_check=skip_version_check,
689
+ )
690
+ self.register_parameter_handler(new_handler)
691
+ return_handler = new_handler
692
+
693
+ return return_handler
694
+
695
+ def get_parameter_io_handler(self, io_format: str) -> ParameterIOHandler:
696
+ """Retrieve the parameter handlers associated with the provided tagname.
697
+ If the parameter IO handler has not yet been instantiated, it will be created.
698
+
699
+ Parameters
700
+ ----------
701
+ io_format
702
+ The name of the io format to be handled.
703
+
704
+ Returns
705
+ -------
706
+ io_handler
707
+
708
+ Raises
709
+ ------
710
+ KeyError
711
+ If there is no ParameterIOHandler for the given tagname
712
+ """
713
+ # Uppercase the format string to avoid case mismatches
714
+ io_format = io_format.upper()
715
+
716
+ # Remove "." (ParameterIOHandler tags do not include it)
717
+ io_format = io_format.strip(".")
718
+
719
+ # Find or initialize ParameterIOHandler for this format
720
+ if io_format in self._parameter_io_handlers.keys():
721
+ return self._parameter_io_handlers[io_format]
722
+ elif io_format in self._parameter_io_handler_classes.keys():
723
+ new_handler_class = self._parameter_io_handler_classes[io_format]
724
+ io_handler = new_handler_class()
725
+ self.register_parameter_io_handler(io_handler)
726
+ return io_handler
727
+ else:
728
+ raise KeyError(
729
+ f"Cannot find a registered parameter IO handler for format '{io_format}'\n"
730
+ f"Registered parameter IO handlers: {self._parameter_io_handlers.keys()}\n"
731
+ )
732
+
733
+ def deregister_parameter_handler(
734
+ self,
735
+ handler: str | ParameterHandler,
736
+ ):
737
+ """
738
+ Deregister a parameter handler specified by tag name, class, or instance.
739
+
740
+ Parameters
741
+ ----------
742
+ handler
743
+ The handler to deregister.
744
+ """
745
+ if isinstance(handler, ParameterHandler):
746
+ tagname = handler.TAGNAME
747
+ elif isinstance(handler, str): # Catch case of name (as str) before checking subclass
748
+ tagname = handler
749
+ elif issubclass(handler, ParameterHandler):
750
+ tagname = handler._TAGNAME
751
+ else:
752
+ tagname = handler
753
+ del self._parameter_handlers[tagname]
754
+
755
+ def parse_sources(self, sources, allow_cosmetic_attributes: bool = True):
756
+ """Parse a SMIRNOFF force field definition.
757
+
758
+ Parameters
759
+ ----------
760
+ sources
761
+ An iterable of files defining the SMIRNOFF force field to be loaded.
762
+ Currently, only `the SMIRNOFF XML format <https://openforcefield.github.io/standards/standards/smirnoff/>`_
763
+ is supported. Each entry may be an absolute file path, a path relative to the current working directory, a
764
+ path relative to this module's data subdirectory (for built in force fields), or an open file-like object
765
+ with a ``read()`` method from which the force field XML data can be loaded. If multiple files are
766
+ specified, any top-level tags that are repeated will be merged if they are compatible, with files appearing
767
+ later in the sequence resulting in parameters that have higher precedence. Support for multiple files is
768
+ primarily intended to allow solvent parameters to be specified by listing them last in the sequence.
769
+ allow_cosmetic_attributes
770
+ Whether to permit non-spec kwargs present in the source.
771
+
772
+ Notes
773
+ -----
774
+
775
+ * New SMIRNOFF sections are handled independently, as if they were specified in the same file.
776
+ * If a SMIRNOFF section that has already been read appears again, its definitions are appended to the end
777
+ of the previously-read definitions if the sections are configured with compatible attributes;
778
+ otherwise, an ``IncompatibleTagException`` is raised.
779
+
780
+ """
781
+ # Ensure that we are working with an iterable
782
+ try:
783
+ sources = iter(sources)
784
+ except TypeError:
785
+ # Make iterable object
786
+ sources = [sources]
787
+
788
+ # TODO: If a non-first source fails here, the force field might be partially modified
789
+ for source in sources:
790
+ smirnoff_data = self.parse_smirnoff_from_source(source)
791
+ self._load_smirnoff_data(smirnoff_data, allow_cosmetic_attributes=allow_cosmetic_attributes)
792
+
793
+ def _to_smirnoff_data(self, discard_cosmetic_attributes: bool = False) -> dict:
794
+ """
795
+ Convert this ForceField and all related ParameterHandlers to a dict representing a SMIRNOFF
796
+ data object.
797
+
798
+ Parameters
799
+ ----------
800
+ discard_cosmetic_attributes
801
+ Whether to discard any non-spec attributes stored in the ForceField.
802
+
803
+ Returns
804
+ -------
805
+ smirnoff_data
806
+ A nested dict representing this ForceField as a SMIRNOFF data object.
807
+
808
+ """
809
+ l1_dict: dict[str, str | dict] = dict()
810
+
811
+ # Assume we will write out SMIRNOFF data in compliance with the max supported spec version
812
+ l1_dict["version"] = str(self._MAX_SUPPORTED_SMIRNOFF_VERSION)
813
+
814
+ # Write out the aromaticity model used
815
+ l1_dict["aromaticity_model"] = self._aromaticity_model
816
+
817
+ # Write out author and date (if they have been set)
818
+ if self._author is not None:
819
+ l1_dict["Author"] = self._author
820
+
821
+ # Write out author and date (if they have been set)
822
+ if self._date is not None:
823
+ l1_dict["Date"] = self._date
824
+
825
+ for parameter_handler in self._parameter_handlers.values():
826
+ # If _TAGNAME is None, the default value, an error should have been
827
+ # thrown upon registering it, so assume it is str here
828
+ handler_tag: str = parameter_handler._TAGNAME # type: ignore[assignment]
829
+ l1_dict[handler_tag] = parameter_handler.to_dict(discard_cosmetic_attributes=discard_cosmetic_attributes)
830
+
831
+ smirnoff_data: dict[str, dict] = dict()
832
+ smirnoff_data["SMIRNOFF"] = l1_dict
833
+
834
+ return convert_all_quantities_to_string(smirnoff_data)
835
+
836
+ # TODO: Should we call this "from_dict"?
837
+ def _load_smirnoff_data(
838
+ self,
839
+ smirnoff_data: dict,
840
+ allow_cosmetic_attributes: bool = False,
841
+ ):
842
+ """
843
+ Add parameters from a SMIRNOFF-format data structure to this ForceField.
844
+
845
+ Parameters
846
+ ----------
847
+ smirnoff_data
848
+ A representation of a SMIRNOFF-format data structure. Begins at top-level 'SMIRNOFF' key.
849
+ allow_cosmetic_attributes
850
+ Whether to permit non-spec kwargs in smirnoff_data.
851
+ """
852
+ import packaging.version
853
+
854
+ # Check that the SMIRNOFF version of this data structure is supported by this ForceField implementation
855
+
856
+ if "SMIRNOFF" in smirnoff_data:
857
+ version = smirnoff_data["SMIRNOFF"]["version"]
858
+ elif "SMIRFF" in smirnoff_data:
859
+ version = smirnoff_data["SMIRFF"]["version"]
860
+ else:
861
+ raise SMIRNOFFParseError("'version' attribute must be specified in SMIRNOFF tag")
862
+
863
+ self._check_smirnoff_version_compatibility(str(version))
864
+
865
+ # Convert 0.1 spec files to 0.3 SMIRNOFF data format by converting
866
+ # from 0.1 spec to 0.2, then 0.2 to 0.3
867
+ if packaging.version.parse(str(version)) == packaging.version.parse("0.1"):
868
+ # NOTE: This will convert the top-level "SMIRFF" tag to "SMIRNOFF"
869
+ smirnoff_data = convert_0_1_smirnoff_to_0_2(smirnoff_data)
870
+ smirnoff_data = convert_0_2_smirnoff_to_0_3(smirnoff_data)
871
+
872
+ # Convert 0.2 spec files to 0.3 SMIRNOFF data format by removing units
873
+ # from section headers and adding them to quantity strings at all levels.
874
+ elif packaging.version.parse(str(version)) == packaging.version.parse("0.2"):
875
+ smirnoff_data = convert_0_2_smirnoff_to_0_3(smirnoff_data)
876
+
877
+ # Ensure that SMIRNOFF is a top-level key of the dict
878
+ if "SMIRNOFF" not in smirnoff_data:
879
+ raise SMIRNOFFParseError("'SMIRNOFF' must be a top-level key in the SMIRNOFF object model")
880
+
881
+ # Check that the aromaticity model required by this parameter set is compatible with
882
+ # others loaded by this ForceField
883
+ if "aromaticity_model" in smirnoff_data["SMIRNOFF"]:
884
+ aromaticity_model = smirnoff_data["SMIRNOFF"]["aromaticity_model"]
885
+ self.aromaticity_model = aromaticity_model
886
+
887
+ elif self._aromaticity_model is None:
888
+ raise SMIRNOFFParseError(
889
+ "'aromaticity_model' attribute must be specified in SMIRNOFF "
890
+ "tag, or contained in a previously-loaded SMIRNOFF data source"
891
+ )
892
+
893
+ if "Author" in smirnoff_data["SMIRNOFF"]:
894
+ self._add_author(smirnoff_data["SMIRNOFF"]["Author"])
895
+
896
+ if "Date" in smirnoff_data["SMIRNOFF"]:
897
+ self._add_date(smirnoff_data["SMIRNOFF"]["Date"])
898
+
899
+ # Go through the whole SMIRNOFF data structure, trying to convert all strings to Quantity
900
+ smirnoff_data = convert_all_strings_to_quantity(
901
+ smirnoff_data,
902
+ ignore_keys=["smirks", "name", "id", "parent_id"],
903
+ )
904
+
905
+ # Go through the subsections, delegating each to the proper ParameterHandler
906
+
907
+ # Define keys which are expected from the spec, but are not parameter sections
908
+ l1_spec_keys = ["Author", "Date", "version", "aromaticity_model"]
909
+ # TODO: Throw SMIRNOFFSpecError for unrecognized keywords
910
+
911
+ for parameter_name in smirnoff_data["SMIRNOFF"]:
912
+ # Skip (for now) cosmetic l1 items. They're handled above
913
+ if parameter_name in l1_spec_keys:
914
+ continue
915
+ # Handle cases where a parameter name has no info (eg. ToolkitAM1BCC)
916
+ if smirnoff_data["SMIRNOFF"][parameter_name] is None:
917
+ # "get"ting the parameter handler here will also initialize it.
918
+ _ = self.get_parameter_handler(parameter_name, {})
919
+ continue
920
+
921
+ # Otherwise, we expect this l1_key to correspond to a ParameterHandler
922
+ section_dict = smirnoff_data["SMIRNOFF"][parameter_name]
923
+
924
+ # TODO: Implement a ParameterHandler.from_dict() that knows how to deserialize itself for extensibility.
925
+ # We could let it load the ParameterTypes from the dict and append them to the existing handler
926
+ # after verifying that they are compatible.
927
+
928
+ # Get the parameter types serialization that is not passed to the ParameterHandler constructor.
929
+ ph_class = self._get_parameter_handler_class(parameter_name)
930
+ try:
931
+ infotype = ph_class._INFOTYPE
932
+ parameter_list_tagname = infotype._ELEMENT_NAME # type: ignore[union-attr]
933
+ except AttributeError:
934
+ # The ParameterHandler doesn't have ParameterTypes (e.g. ToolkitAM1BCCHandler).
935
+ parameter_list_dict = {}
936
+ else:
937
+ parameter_list_dict = section_dict.pop(parameter_list_tagname, {})
938
+
939
+ # Must be wrapped into its own tag.
940
+ # Assumes that parameter_list_dict is always a list
941
+
942
+ # If the parameter list isn't empty, it must be transferred into its own tag.
943
+ # This is necessary for deserializing SMIRNOFF force field sections which may or may
944
+ # not have any smirks-based elements (like an empty ChargeIncrementModel section)
945
+ if parameter_list_dict != {}:
946
+ parameter_list_dict = {parameter_list_tagname: parameter_list_dict}
947
+
948
+ # Retrieve or create parameter handler, passing in section_dict to check for
949
+ # compatibility if a handler for this parameter name already exists
950
+ handler = self.get_parameter_handler(
951
+ parameter_name,
952
+ section_dict,
953
+ allow_cosmetic_attributes=allow_cosmetic_attributes,
954
+ )
955
+ handler._add_parameters(parameter_list_dict, allow_cosmetic_attributes=allow_cosmetic_attributes)
956
+
957
+ def parse_smirnoff_from_source(self, source: str | IO) -> dict:
958
+ """
959
+ Reads a SMIRNOFF data structure from a source, which can be one of many types.
960
+
961
+ Parameters
962
+ ----------
963
+ source
964
+ File defining the SMIRNOFF force field to be loaded Currently, only `the SMIRNOFF XML format
965
+ <https://openforcefield.github.io/standards/standards/smirnoff/>`_ is supported. The file may be an
966
+ absolute file path, a path relative to the current working directory, a path relative to this module's data
967
+ subdirectory (for built in force fields), or an open file-like object with a ``read()`` method from which
968
+ the force field XML data can be loaded.
969
+
970
+ Returns
971
+ -------
972
+ smirnoff_data
973
+ A representation of a SMIRNOFF-format data structure. Begins at top-level 'SMIRNOFF' key.
974
+
975
+ """
976
+ # First, see if a file exists with a name `source` in the current directory or in directories known to the
977
+ # plugin system. It could also be a raw XML-like string ...
978
+ if isinstance(source, str):
979
+ # Try first the simple path.
980
+ searched_dirs_paths: list[str] = [os.getcwd()]
981
+ # Then try a relative file path w.r.t. an installed directory.
982
+ searched_dirs_paths.extend(_get_installed_offxml_dir_paths())
983
+
984
+ # Determine the actual path of the file.
985
+ # TODO: What is desired toolkit behavior if two files with the desired name are available?
986
+ for dir_path in searched_dirs_paths:
987
+ for file_path in pathlib.Path(dir_path).glob("*.offxml"):
988
+ if str(file_path).lower().endswith(source.lower()):
989
+ source = str(file_path.absolute())
990
+ break
991
+
992
+ else:
993
+ # ... or a file-like object, in which case we shouldn't look through the plugin system.
994
+ # if it's raw bytes, no need to search for paths, either.
995
+ searched_dirs_paths = list()
996
+
997
+ # Process all SMIRNOFF definition files or objects
998
+ # QUESTION: Allow users to specify force field URLs so they can pull force field definitions from the web too?
999
+ io_formats_to_try = self._parameter_io_handler_classes.keys()
1000
+
1001
+ # Parse content depending on type
1002
+ for parameter_io_format in io_formats_to_try:
1003
+ parameter_io_handler = self.get_parameter_io_handler(parameter_io_format)
1004
+
1005
+ # Try parsing as a force field file or file-like object
1006
+ try:
1007
+ smirnoff_data = parameter_io_handler.parse_file(source)
1008
+ return smirnoff_data
1009
+ except SMIRNOFFParseError as e:
1010
+ exception_type = type(e)
1011
+ exception_context = "while trying to parse source as an object"
1012
+ exception_msg = e.msg
1013
+ except OSError:
1014
+ # If this is not a file path or a file handle, attempt parsing as a string.
1015
+ # TODO: Do we actually support parsing bytes?
1016
+ try:
1017
+ smirnoff_data = parameter_io_handler.parse_string(source)
1018
+ return smirnoff_data
1019
+ except SMIRNOFFParseError as e:
1020
+ exception_type = type(e)
1021
+ exception_context = "while trying to parse source as a file"
1022
+ exception_msg = e.args[0]
1023
+
1024
+ # If we haven't returned by now, the parsing was unsuccessful
1025
+ # There is different parsing behavior for str and file-like objects, so raise errors separately
1026
+ if isinstance(source, str):
1027
+ pretty_searched_paths = "\n ".join(searched_dirs_paths)
1028
+ msg = (
1029
+ f"Source '{source}' could not be read. If this is a file, ensure that the path is correct.\n"
1030
+ f"Looked in the following paths and found no files named '{source}':"
1031
+ f"\n {pretty_searched_paths}\n"
1032
+ f"If '{source}' is present as a file, ensure it is in a known SMIRNOFF encoding.\n"
1033
+ f"Valid formats are: {[*self._parameter_io_handler_classes.keys()]}\n"
1034
+ f"Parsing failed {exception_context} with the following exception and "
1035
+ f"message:\n{exception_type}\n{exception_msg}\n"
1036
+ )
1037
+
1038
+ else:
1039
+ msg = (
1040
+ f"Source '{source}' could not be read.\n"
1041
+ f"Parsing failed {exception_context} with the following exception and message:\n"
1042
+ f"{exception_type}\n{exception_msg}\n"
1043
+ )
1044
+
1045
+ raise OSError(msg)
1046
+
1047
+ def to_string(
1048
+ self,
1049
+ io_format: str | ParameterIOHandler = "XML",
1050
+ discard_cosmetic_attributes: bool = False,
1051
+ ) -> str:
1052
+ """
1053
+ Write this Forcefield and all its associated parameters to a string in a given format which
1054
+ complies with the SMIRNOFF spec.
1055
+
1056
+
1057
+ Parameters
1058
+ ----------
1059
+ io_format
1060
+ The serialization format to write to
1061
+ discard_cosmetic_attributes
1062
+ Whether to discard any non-spec attributes stored in the ForceField.
1063
+
1064
+ Returns
1065
+ -------
1066
+ forcefield_string
1067
+ The string representation of the serialized force field
1068
+ """
1069
+ # Resolve which IO handler to use
1070
+ if isinstance(io_format, ParameterIOHandler):
1071
+ io_handler = io_format
1072
+ else:
1073
+ io_handler = self.get_parameter_io_handler(io_format)
1074
+
1075
+ smirnoff_data = self._to_smirnoff_data(discard_cosmetic_attributes=discard_cosmetic_attributes)
1076
+ string_data = io_handler.to_string(smirnoff_data)
1077
+ return string_data
1078
+
1079
+ def to_file(
1080
+ self,
1081
+ filename: str,
1082
+ io_format: str | ParameterIOHandler | None = None,
1083
+ discard_cosmetic_attributes: bool = False,
1084
+ ) -> None:
1085
+ """
1086
+ Write this Forcefield and all its associated parameters to a string in a given format which
1087
+ complies with the SMIRNOFF spec.
1088
+
1089
+ Parameters
1090
+ ----------
1091
+ filename
1092
+ The filename to write to
1093
+ io_format
1094
+ The serialization format to write out. If None, will attempt to be inferred from the filename.
1095
+ discard_cosmetic_attributes
1096
+ Whether to discard any non-spec attributes stored in the ForceField.
1097
+
1098
+ """
1099
+ if io_format is None:
1100
+ _, io_format = os.path.splitext(filename)
1101
+
1102
+ # Resolve which IO handler to use
1103
+ if isinstance(io_format, ParameterIOHandler):
1104
+ io_handler = io_format
1105
+ else:
1106
+ # Handle the fact that .offxml is the same as .xml
1107
+ if io_format.lower() == "offxml" or io_format.lower() == ".offxml":
1108
+ io_format = "xml"
1109
+ io_handler = self.get_parameter_io_handler(io_format)
1110
+
1111
+ # Write out the SMIRNOFF data to the IOHandler
1112
+ smirnoff_data = self._to_smirnoff_data(discard_cosmetic_attributes=discard_cosmetic_attributes)
1113
+ io_handler.to_file(filename, smirnoff_data)
1114
+
1115
+ def combine(
1116
+ self,
1117
+ other: "ForceField",
1118
+ ) -> "ForceField":
1119
+ """
1120
+ Combine this `ForceField` with another `ForceField`, returning a new `ForceField`.
1121
+
1122
+ The same rules as `ForceField.__init__` are followed.
1123
+ """
1124
+ import copy
1125
+
1126
+ combined = copy.deepcopy(self)
1127
+
1128
+ combined._load_smirnoff_data(
1129
+ smirnoff_data=other._to_smirnoff_data(
1130
+ discard_cosmetic_attributes=False,
1131
+ ),
1132
+ allow_cosmetic_attributes=True,
1133
+ )
1134
+
1135
+ return combined
1136
+
1137
+ # TODO: Should we also accept a Molecule as an alternative to a Topology?
1138
+ @requires_package("openmm")
1139
+ def create_openmm_system(
1140
+ self,
1141
+ topology: "Topology",
1142
+ *,
1143
+ toolkit_registry: Union["ToolkitRegistry", "ToolkitWrapper"] | None = None,
1144
+ charge_from_molecules: list["Molecule"] | None = None,
1145
+ partial_bond_orders_from_molecules: list["Molecule"] | None = None,
1146
+ allow_nonintegral_charges: bool = False,
1147
+ ) -> "openmm.System":
1148
+ """Create an OpenMM System from this ForceField and a Topology.
1149
+
1150
+ Note that most force fields specify their own partial charges, and any
1151
+ partial charges defined on the ``Molecule`` objects in the topology are
1152
+ ignored. To use custom partial charges, see the
1153
+ ``charge_from_molecules`` argument.
1154
+
1155
+ Parameters
1156
+ ----------
1157
+ topology
1158
+ The ``Topology`` which is to be parameterized with this
1159
+ ``ForceField``.
1160
+ toolkit_registry
1161
+ The toolkit registry to use for parametrization (eg, for calculating
1162
+ partial charges and partial bond orders)
1163
+ charge_from_molecules
1164
+ Take partial charges from the input topology rather than calculating
1165
+ them. This may be useful for avoiding recalculating charges, but
1166
+ take care to ensure that your charges are appropriate for the force
1167
+ field.
1168
+ partial_bond_orders_from_molecules
1169
+ Take partial bond orders from the input topology rather than
1170
+ calculating them. This may be useful for avoiding recalculating
1171
+ PBOs, but take to ensure that they are appropriate for the
1172
+ force field.
1173
+ allow_nonintegral_charges
1174
+ Allow charges that do not sum to an integer.
1175
+ """
1176
+ return self.create_interchange(
1177
+ topology,
1178
+ toolkit_registry,
1179
+ charge_from_molecules=charge_from_molecules,
1180
+ partial_bond_orders_from_molecules=partial_bond_orders_from_molecules,
1181
+ allow_nonintegral_charges=allow_nonintegral_charges,
1182
+ ).to_openmm(combine_nonbonded_forces=True)
1183
+
1184
+ @requires_package("openff.interchange")
1185
+ def create_interchange(
1186
+ self,
1187
+ topology: "Topology",
1188
+ toolkit_registry: Union["ToolkitRegistry", "ToolkitWrapper"] | None = None,
1189
+ charge_from_molecules: list["Molecule"] | None = None,
1190
+ partial_bond_orders_from_molecules: list["Molecule"] | None = None,
1191
+ allow_nonintegral_charges: bool = False,
1192
+ ) -> "Interchange":
1193
+ """
1194
+ Create an Interchange object from a ForceField, Topology, and (optionally) box vectors.
1195
+
1196
+ WARNING: This API and functionality are experimental and not suitable for production.
1197
+
1198
+ Parameters
1199
+ ----------
1200
+ topology
1201
+ The topology to create this `Interchange` object from.
1202
+ toolkit_registry
1203
+ The toolkit registry to use for parametrization (eg, for calculating
1204
+ partial charges and partial bond orders)
1205
+ charge_from_molecules
1206
+ Take charges from the input topology rather than calculating them.
1207
+ This may be useful for avoiding recalculating charges, but take care
1208
+ to ensure that your charges are appropriate for the force field.
1209
+ partial_bond_orders_from_molecules
1210
+ Take partial bond orders from the input topology rather than
1211
+ calculating them. This may be useful for avoiding recalculating
1212
+ PBOs, but take to ensure that they are appropriate for the
1213
+ force field.
1214
+ allow_nonintegral_charges
1215
+ Allow charges that do not sum to an integer.
1216
+
1217
+ Returns
1218
+ -------
1219
+ interchange
1220
+ An `Interchange` object resulting from applying this `ForceField` to a `Topology`.
1221
+
1222
+ """
1223
+ from openff.interchange import Interchange
1224
+
1225
+ from openff.toolkit.utils.toolkit_registry import toolkit_registry_manager
1226
+
1227
+ if toolkit_registry is not None:
1228
+ used_registry = toolkit_registry
1229
+ else:
1230
+ from openff.toolkit.utils.toolkits import GLOBAL_TOOLKIT_REGISTRY
1231
+
1232
+ used_registry = GLOBAL_TOOLKIT_REGISTRY
1233
+
1234
+ with toolkit_registry_manager(used_registry):
1235
+ return Interchange.from_smirnoff(
1236
+ force_field=self,
1237
+ topology=topology,
1238
+ charge_from_molecules=charge_from_molecules,
1239
+ partial_bond_orders_from_molecules=partial_bond_orders_from_molecules,
1240
+ allow_nonintegral_charges=allow_nonintegral_charges,
1241
+ )
1242
+
1243
+ def label_molecules(self, topology: "Topology") -> list[dict[str, "ValenceDict"]]:
1244
+ """
1245
+ Return labels for a list of molecules corresponding to parameters from this force field.
1246
+
1247
+ For each molecule, a dictionary of force types is returned, and for each force type,
1248
+ each force term is provided with the atoms involved, the parameter id assigned, and the corresponding SMIRKS.
1249
+
1250
+ .. todo::
1251
+ What is the most useful API for this method?
1252
+
1253
+ - Should we instead accept :class:`Molecule` objects as input and
1254
+ individually return labels?
1255
+ - Should we attach the labels to the :class:`Molecule` object?
1256
+ - Or should we label all interactions in a :class:`Topology` instead
1257
+ of just labeling its ``unique_molecules``?
1258
+
1259
+ Parameters
1260
+ ----------
1261
+ topology
1262
+ A Topology object containing one or more unique molecules to be labeled
1263
+
1264
+ Returns
1265
+ -------
1266
+ molecule_labels
1267
+ List of labels for unique molecules. Each entry in the list
1268
+ corresponds to one unique molecule in the Topology and is a
1269
+ dictionary keyed by force type, i.e., ``molecule_labels[0]
1270
+ ['HarmonicBondForce']`` gives details for the harmonic bond
1271
+ parameters for the first molecule. Each element is a list of the
1272
+ form: ``[ ( [ atom1, ..., atomN], parameter_id, SMIRKS), ... ]``.
1273
+ """
1274
+ from openff.toolkit.typing.engines.smirnoff.parameters import VirtualSiteHandler
1275
+
1276
+ # Loop over molecules and label
1277
+ molecule_labels = list()
1278
+
1279
+ # TODO: This was previously ... enumerate(topology.reference_molecules). It's currently
1280
+ # unclear if this should be topology.unique_molecules instead, since that might be faster
1281
+ # (if also modifying this to label _all_ duplicates of each unique molecule)
1282
+ for molecule in topology.molecules:
1283
+ current_molecule_labels = dict()
1284
+ for tag, parameter_handler in self._parameter_handlers.items():
1285
+ param_is_list = False
1286
+
1287
+ if type(parameter_handler) is VirtualSiteHandler:
1288
+ param_is_list = True
1289
+
1290
+ matches = parameter_handler.find_matches(molecule.to_topology())
1291
+
1292
+ # Remove the chemical environment matches from the
1293
+ # matched results.
1294
+
1295
+ # Because we sometimes need to enforce atom ordering,
1296
+ # `matches` here is not a normal `dict`, but rather
1297
+ # one that transforms keys in arbitrary ways. Thus,
1298
+ # we need to make a copy of its specific class here.
1299
+
1300
+ parameter_matches = matches.__class__()
1301
+
1302
+ # Now make parameter_matches into a dict mapping
1303
+ # match objects to ParameterTypes
1304
+
1305
+ if param_is_list:
1306
+ for match in matches:
1307
+ parameter_matches[match] = [m.parameter_type for m in matches[match]]
1308
+ else:
1309
+ for match in matches:
1310
+ parameter_matches[match] = matches[match].parameter_type
1311
+
1312
+ current_molecule_labels[tag] = parameter_matches
1313
+
1314
+ molecule_labels.append(current_molecule_labels)
1315
+ return molecule_labels
1316
+
1317
+ def _get_parameter_handler_class(self, tagname: str) -> type[ParameterHandler]:
1318
+ """Retrieve the ParameterHandler class associated to the tagname and throw a custom error if not found."""
1319
+ try:
1320
+ ph_class = self._parameter_handler_classes[tagname]
1321
+ except KeyError:
1322
+ msg = f"Cannot find a registered parameter handler class for tag '{tagname}'\n"
1323
+ msg += f"Known parameter handler class tags are {self._parameter_handler_classes.keys()}"
1324
+ raise KeyError(msg)
1325
+ return ph_class
1326
+
1327
+ @requires_package("openff.interchange")
1328
+ def get_partial_charges(self, molecule: "Molecule", **kwargs: Any) -> Quantity:
1329
+ """Generate the partial charges for the given molecule in this force field.
1330
+
1331
+ Parameters
1332
+ ----------
1333
+ molecule
1334
+ The ``Molecule`` corresponding to the system to be parameterized
1335
+ toolkit_registry
1336
+ The toolkit registry to use for operations like conformer generation and
1337
+ partial charge assignment.
1338
+
1339
+ Returns
1340
+ -------
1341
+ charges
1342
+ The partial charges of the provided molecule in this force field.
1343
+
1344
+ Raises
1345
+ ------
1346
+ PartialChargeVirtualSitesError
1347
+ If the ``ForceField`` applies virtual sites to the ``Molecule``.
1348
+ ``get_partial_charges`` cannot identify which virtual site charges
1349
+ may belong to which atoms in this case.
1350
+
1351
+ Other exceptions
1352
+ As any ``ParameterHandler`` may in principle modify charges, the entire
1353
+ force field must be applied to the molecule to produce the charges.
1354
+ Calls to this method from incorrectly or incompletely specified ``ForceField``
1355
+ objects thus may raise an exception.
1356
+
1357
+ Examples
1358
+ --------
1359
+
1360
+ >>> from openff.toolkit import ForceField, Molecule
1361
+ >>> ethanol = Molecule.from_smiles('CCO')
1362
+ >>> force_field = ForceField('openff-2.0.0.offxml')
1363
+
1364
+ Assign partial charges to the molecule according to the force field:
1365
+
1366
+ >>> ethanol.partial_charges = force_field.get_partial_charges(ethanol)
1367
+
1368
+ Use the assigned partial charges when creating an OpenMM ``System``:
1369
+
1370
+ >>> topology = ethanol.to_topology()
1371
+ >>> system = force_field.create_openmm_system(
1372
+ ... topology,
1373
+ ... charge_from_molecules=[ethanol]
1374
+ ... )
1375
+
1376
+ This is especially useful when you want to create multiple systems
1377
+ with the same molecule or molecules, as it allows the expensive
1378
+ charge calculation to be cached.
1379
+
1380
+ """
1381
+ from openff.toolkit import Molecule, unit
1382
+
1383
+ if not isinstance(molecule, Molecule):
1384
+ raise ValueError(
1385
+ f"`molecule` argument must be a `Molecule` or subclass object. Found type {type(molecule)}"
1386
+ )
1387
+
1388
+ return Quantity(
1389
+ [
1390
+ c.m
1391
+ for c in self.create_interchange(
1392
+ topology=molecule.to_topology(),
1393
+ **kwargs,
1394
+ )["Electrostatics"].charges.values()
1395
+ ],
1396
+ unit.elementary_charge,
1397
+ )
1398
+
1399
+ def __getitem__(self, val: str | ParameterHandler) -> ParameterHandler:
1400
+ """
1401
+ Syntax sugar for lookikng up a ParameterHandler. Note that only
1402
+ string-based lookups are currently supported.
1403
+ """
1404
+ if isinstance(val, str):
1405
+ if val in self._parameter_handlers:
1406
+ return self.get_parameter_handler(val)
1407
+ else:
1408
+ raise KeyError(f"Parameter handler with name '{val}' not found.")
1409
+ elif isinstance(val, ParameterHandler) or issubclass(val, ParameterHandler):
1410
+ raise NotImplementedError
1411
+
1412
+ def __hash__(self) -> int:
1413
+ """Deterministically hash a ForceField object
1414
+
1415
+ Notable behavior:
1416
+ * `author` and `date` are stripped from the ForceField
1417
+ * `id` and `parent_id` are stripped from each ParameterType"""
1418
+ import copy
1419
+
1420
+ # Completely re-constructing the force field may be overkill
1421
+ # compared to deepcopying and modifying, but is not currently slow
1422
+ ff_copy = ForceField()
1423
+ ff_copy.date = ""
1424
+ ff_copy.author = ""
1425
+
1426
+ param_attrs_to_strip = ["_id", "_parent_id"]
1427
+
1428
+ for handler_name in self.registered_parameter_handlers:
1429
+ handler = copy.deepcopy(self.get_parameter_handler(handler_name))
1430
+
1431
+ for param in handler._parameters:
1432
+ for attr in param_attrs_to_strip:
1433
+ # param.__dict__.pop(attr, None) may be faster
1434
+ # https://stackoverflow.com/a/42303681/4248961
1435
+ if hasattr(param, attr):
1436
+ delattr(param, attr)
1437
+
1438
+ ff_copy.register_parameter_handler(handler)
1439
+
1440
+ return hash(ff_copy.to_string(discard_cosmetic_attributes=True))