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,805 @@
1
+ """
2
+ Utility subroutines
3
+
4
+ """
5
+
6
+ __all__ = [
7
+ "all_subclasses",
8
+ "convert_0_1_smirnoff_to_0_2",
9
+ "convert_0_2_smirnoff_to_0_3",
10
+ "convert_all_quantities_to_string",
11
+ "convert_all_strings_to_quantity",
12
+ "deserialize_numpy",
13
+ "get_data_file_path",
14
+ "get_molecule_parameterIDs",
15
+ "inherit_docstrings",
16
+ "object_to_quantity",
17
+ "quantity_to_string",
18
+ "requires_package",
19
+ "serialize_numpy",
20
+ "string_to_quantity",
21
+ "string_to_unit",
22
+ "temporary_cd",
23
+ "unit_to_string",
24
+ ]
25
+
26
+ import contextlib
27
+ import functools
28
+ import logging
29
+ from collections.abc import Iterable
30
+ from typing import TYPE_CHECKING, Any, TypeVar, overload
31
+
32
+ import numpy as np
33
+ import pint
34
+ from numpy.typing import NDArray
35
+ from openff.units import Quantity, Unit
36
+ from openff.utilities import requires_package
37
+
38
+ if TYPE_CHECKING:
39
+ from openff.toolkit import ForceField, Molecule
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+
44
+ # Pre-create an instance of the dimensionless unit to speed up comparisons later
45
+ _DIMENSIONLESS = Unit("dimensionless")
46
+
47
+
48
+ def inherit_docstrings(cls):
49
+ """Inherit docstrings from parent class"""
50
+ from inspect import getmembers, isfunction
51
+
52
+ for name, func in getmembers(cls, isfunction):
53
+ if func.__doc__:
54
+ continue
55
+ for parent in cls.__mro__[1:]:
56
+ if hasattr(parent, name):
57
+ func.__doc__ = getattr(parent, name).__doc__
58
+ return cls
59
+
60
+
61
+ T = TypeVar("T")
62
+
63
+
64
+ def all_subclasses(cls: type[T]) -> list[type[T]]:
65
+ """Recursively retrieve all subclasses of the specified class"""
66
+ return cls.__subclasses__() + [g for s in cls.__subclasses__() for g in all_subclasses(s)]
67
+
68
+
69
+ @contextlib.contextmanager
70
+ def temporary_cd(dir_path):
71
+ """Context to temporary change the working directory.
72
+
73
+ Parameters
74
+ ----------
75
+
76
+ dir_path
77
+ The directory path to enter within the context
78
+
79
+ Examples
80
+ --------
81
+
82
+ >>> dir_path = '/tmp'
83
+ >>> with temporary_cd(dir_path):
84
+ ... pass # do something in dir_path
85
+
86
+ """
87
+ import os
88
+
89
+ prev_dir = os.getcwd()
90
+ os.chdir(os.path.abspath(dir_path))
91
+ try:
92
+ yield
93
+ finally:
94
+ os.chdir(prev_dir)
95
+
96
+
97
+ def get_data_file_path(relative_path: str) -> str:
98
+ """Get the full path to one of the reference files in testsystems.
99
+ In the source distribution, these files are in ``openff/toolkit/data/``,
100
+ but on installation, they're moved to somewhere in the user's python
101
+ site-packages directory.
102
+
103
+ Parameters
104
+ ----------
105
+
106
+ relative_path
107
+ Name of the file to load (with respect to `openff/toolkit/data/`)
108
+
109
+ """
110
+ from importlib.resources import files
111
+
112
+ _DATA_ROOT = files("openff.toolkit") / "data"
113
+
114
+ file_path = _DATA_ROOT / relative_path
115
+
116
+ if not file_path.exists(): # type: ignore[attr-defined]
117
+ raise ValueError(f"Sorry! {file_path} does not exist. If you just added it, you'll have to re-install")
118
+
119
+ return str(file_path)
120
+
121
+
122
+ @pint.register_unit_format("simple")
123
+ def format_unit_simple(unit, registry, **options):
124
+ return " * ".join(f"{u} ** {p}" for u, p in unit.items())
125
+
126
+
127
+ def unit_to_string(input_unit: Unit) -> str:
128
+ return f"{input_unit:simple}"
129
+
130
+
131
+ def quantity_to_dict(input_quantity):
132
+ value = input_quantity.magnitude
133
+ if isinstance(value, np.ndarray):
134
+ value = value.tolist()
135
+
136
+ return {
137
+ "value": value,
138
+ "unit": str(input_quantity.units),
139
+ }
140
+
141
+
142
+ def dict_to_quantity(input_dict):
143
+ return input_dict["value"] * Unit(input_dict["unit"])
144
+
145
+
146
+ def quantity_to_string(input_quantity: Quantity) -> str:
147
+ """
148
+ Serialize a ``openff.units.Quantity`` to a string representation that is backwards-compatible
149
+ with older versions of the OpenFF Toolkit. This includes a " * " between numerical values and
150
+ their units and "A" being used in place of the unicode Å ("\N{ANGSTROM SIGN}").
151
+
152
+ Parameters
153
+ ----------
154
+ input_quantity
155
+ The quantity to serialize
156
+
157
+ Returns
158
+ -------
159
+ output_string
160
+ The serialized quantity
161
+
162
+ """
163
+ unitless_value: float | int | NDArray | list = input_quantity.m
164
+ # The string representation of a numpy array doesn't have commas and breaks the
165
+ # parser, thus we convert any arrays to list here
166
+ if isinstance(unitless_value, np.ndarray):
167
+ unitless_value = list(unitless_value)
168
+
169
+ unit_string = unit_to_string(input_quantity.units)
170
+
171
+ return f"{unitless_value} * {unit_string}"
172
+
173
+
174
+ @functools.lru_cache
175
+ def string_to_unit(unit_string) -> Unit:
176
+ """
177
+ Deserializes a ``openff.units.Quantity`` from a string representation, for
178
+ example: "kilocalories_per_mole / angstrom ** 2"
179
+
180
+
181
+ Parameters
182
+ ----------
183
+ unit_string
184
+ Serialized representation of a ``openff.units.Quantity``.
185
+
186
+ Returns
187
+ -------
188
+ output_unit
189
+ The deserialized unit from the string
190
+ """
191
+ return Unit(unit_string)
192
+
193
+
194
+ @functools.lru_cache
195
+ def string_to_quantity(quantity_string: str) -> int | float | Quantity:
196
+ """Attempt to parse a string into a ``Quantity``.
197
+
198
+ Note that strings representing dimensionless floats or ints are returned as floats or ints, not
199
+ `Quantity` objects. For example, "1.0" is returned as `1.0` (a float) not
200
+ `Quantity(1.0, "dimensionless")`. (This quirk can't be captured by type annotations because the
201
+ input type remains str.)
202
+
203
+ This function is cached, keyed by the stringified quantity, to avoid re-parsing the same strings,
204
+ and re-creating `Quantity` objects, for identical inputs.
205
+ """
206
+
207
+ from tokenize import TokenError
208
+
209
+ from pint import UndefinedUnitError
210
+
211
+ try:
212
+ quantity = Quantity(quantity_string)
213
+ except (TokenError, UndefinedUnitError):
214
+ return quantity_string # type: ignore[return-value]
215
+
216
+ # TODO: Should intentionally unitless array-likes be Quantity objects
217
+ # or their raw representation?
218
+ if quantity.units == _DIMENSIONLESS and isinstance(quantity.m, int | float):
219
+ return quantity.m
220
+ else:
221
+ return quantity
222
+
223
+
224
+ def convert_all_strings_to_quantity(
225
+ smirnoff_data: dict,
226
+ ignore_keys: Iterable[str] = tuple(),
227
+ ) -> dict:
228
+ """
229
+ Traverses a SMIRNOFF data structure, attempting to convert all
230
+ quantity-defining strings into ``openff.units.Quantity`` objects.
231
+
232
+ Integers and floats are ignored and not converted into a dimensionless
233
+ ``openff.units.Quantity`` object.
234
+
235
+ Some good keys to ignore include `ignore_keys=["smirks", "name", "id", "parent_id"]`
236
+ since these are commonly used in SMIRNOFF force fields in ways that are meant to
237
+ remain strings. For more context, see `Issue #1635`_.
238
+
239
+ .. _Issue #1635: https://github.com/openforcefield/openff-toolkit/issues/1635.
240
+
241
+ Parameters
242
+ ----------
243
+ smirnoff_data
244
+ A hierarchical dict structured in compliance with the SMIRNOFF spec
245
+ ignore_keys
246
+ A list of keys to skip when converting strings to quantities
247
+
248
+ Returns
249
+ -------
250
+ converted_smirnoff_data
251
+ A hierarchical dict structured in compliance with the SMIRNOFF spec,
252
+ with quantity-defining strings converted to ``openff.units.Quantity`` objects
253
+ """
254
+ from pint import DefinitionSyntaxError
255
+
256
+ if isinstance(smirnoff_data, dict):
257
+ for key, value in smirnoff_data.items():
258
+ if key in ignore_keys:
259
+ smirnoff_data[key] = value
260
+ else:
261
+ smirnoff_data[key] = convert_all_strings_to_quantity(
262
+ value,
263
+ ignore_keys=ignore_keys,
264
+ )
265
+ obj_to_return = smirnoff_data
266
+
267
+ elif isinstance(smirnoff_data, list):
268
+ for index, item in enumerate(smirnoff_data):
269
+ smirnoff_data[index] = convert_all_strings_to_quantity(
270
+ item,
271
+ ignore_keys=ignore_keys,
272
+ )
273
+ obj_to_return = smirnoff_data
274
+
275
+ elif isinstance(smirnoff_data, int) or isinstance(smirnoff_data, float):
276
+ obj_to_return = smirnoff_data
277
+
278
+ else:
279
+ try:
280
+ obj_to_return = object_to_quantity(smirnoff_data)
281
+ except (TypeError, DefinitionSyntaxError):
282
+ obj_to_return = smirnoff_data
283
+
284
+ return obj_to_return
285
+
286
+
287
+ @overload
288
+ def convert_all_quantities_to_string(
289
+ smirnoff_data: list[Quantity],
290
+ ) -> list[str]: ...
291
+
292
+
293
+ @overload
294
+ def convert_all_quantities_to_string(
295
+ smirnoff_data: dict,
296
+ ) -> dict[str, Any]: ...
297
+
298
+
299
+ @overload
300
+ def convert_all_quantities_to_string(
301
+ smirnoff_data: "Quantity",
302
+ ) -> str | list[str] | dict[str, Any]: ...
303
+
304
+
305
+ def convert_all_quantities_to_string(
306
+ smirnoff_data: dict | str | Quantity | list,
307
+ ) -> str | dict[str, Any] | list[str]:
308
+ """
309
+ Traverses a SMIRNOFF data structure, attempting to convert all
310
+ quantities into strings.
311
+
312
+ Parameters
313
+ ----------
314
+ smirnoff_data
315
+ A hierarchical dict structured in compliance with the SMIRNOFF spec
316
+
317
+ Returns
318
+ -------
319
+ converted_smirnoff_data
320
+ A hierarchical dict structured in compliance with the SMIRNOFF spec,
321
+ with ``openff.units.Quantity``s converted to string
322
+ """
323
+
324
+ if isinstance(smirnoff_data, dict):
325
+ for key, value in smirnoff_data.items():
326
+ smirnoff_data[key] = convert_all_quantities_to_string(value)
327
+ return smirnoff_data
328
+ elif isinstance(smirnoff_data, list):
329
+ for index, item in enumerate(smirnoff_data):
330
+ smirnoff_data[index] = convert_all_quantities_to_string(item)
331
+ return smirnoff_data
332
+ elif isinstance(smirnoff_data, Quantity):
333
+ return quantity_to_string(smirnoff_data)
334
+ else:
335
+ return smirnoff_data
336
+
337
+
338
+ @functools.singledispatch
339
+ def object_to_quantity(object):
340
+ """
341
+ Attempts to turn the provided object into `openff.units.Quantity`s.
342
+
343
+ Can handle float, int, str, `Quantity`, `openmm.unit.Quantity`, or iterators over
344
+ the same. Raises an exception if unable to convert all inputs.
345
+
346
+ Parameters
347
+ ----------
348
+ object
349
+ The object to convert to a ``Quantity`` object(s).
350
+
351
+ Returns
352
+ -------
353
+ converted_object
354
+
355
+ """
356
+ # If we can't find a custom type, we treat this as a generic iterator.
357
+ return [object_to_quantity(sub_obj) for sub_obj in object]
358
+
359
+
360
+ @object_to_quantity.register(Quantity)
361
+ def _(obj):
362
+ return obj
363
+
364
+
365
+ @object_to_quantity.register(str)
366
+ def _(obj):
367
+ import pint
368
+
369
+ try:
370
+ return string_to_quantity(obj)
371
+ except pint.errors.UndefinedUnitError:
372
+ raise ValueError
373
+
374
+
375
+ @object_to_quantity.register(int)
376
+ @object_to_quantity.register(float)
377
+ def _(obj):
378
+ return Quantity(obj)
379
+
380
+
381
+ try:
382
+ import openmm.unit
383
+ from openff.units.openmm import from_openmm
384
+
385
+ @object_to_quantity.register(openmm.unit.Quantity)
386
+ def _(obj):
387
+ return from_openmm(obj)
388
+
389
+ except ImportError:
390
+ pass # pragma: nocover
391
+
392
+
393
+ def serialize_numpy(np_array) -> tuple[bytes, tuple[int]]:
394
+ """
395
+ Serializes a numpy array into a big-endian bytestring and tuple representing its shape.
396
+
397
+ Parameters
398
+ ----------
399
+ np_array
400
+ Input numpy array
401
+
402
+ Returns
403
+ -------
404
+ serialized
405
+ A big-endian bytestring of the NumPy array.
406
+ shape
407
+ The shape of the serialized array
408
+ """
409
+ bigendian_float = np.dtype(float).newbyteorder(">")
410
+ bigendian_array = np_array.astype(bigendian_float)
411
+ serialized = bigendian_array.tobytes()
412
+ shape = np_array.shape
413
+ return serialized, shape
414
+
415
+
416
+ def deserialize_numpy(
417
+ serialized_np: bytes | list,
418
+ shape: tuple[int, ...],
419
+ ) -> NDArray:
420
+ """
421
+ Deserializes a numpy array from a bytestring or list. The input, if a bytestring, is
422
+ assumed to be in big-endian byte order.
423
+
424
+ Parameters
425
+ ----------
426
+ serialized_np
427
+ A byte or list serialized representation of a numpy array
428
+ shape
429
+ The shape of the serialized array
430
+
431
+ Returns
432
+ -------
433
+ np_array
434
+ The deserialized numpy array
435
+ """
436
+ if isinstance(serialized_np, list):
437
+ np_array = np.array(serialized_np)
438
+ if isinstance(serialized_np, bytes):
439
+ dt = np.dtype("float").newbyteorder(">")
440
+ np_array = np.frombuffer(serialized_np, dtype=dt)
441
+ np_array = np_array.reshape(shape)
442
+ return np_array
443
+
444
+
445
+ def convert_0_2_smirnoff_to_0_3(smirnoff_data_0_2):
446
+ """
447
+ Convert an 0.2-compliant SMIRNOFF dict to an 0.3-compliant one.
448
+ This involves removing units from header tags and adding them
449
+ to attributes of child elements.
450
+ It also requires converting ProperTorsions and ImproperTorsions
451
+ potentials from "charmm" to "fourier".
452
+
453
+ Parameters
454
+ ----------
455
+ smirnoff_data_0_2
456
+ Hierarchical dict representing a SMIRNOFF data structure according the the 0.2 spec
457
+
458
+ Returns
459
+ -------
460
+ smirnoff_data_0_3
461
+ Hierarchical dict representing a SMIRNOFF data structure according the the 0.3 spec
462
+ """
463
+ # Legacy force fields sometimes specify the NonbondedForce's sigma_unit value, but then provide
464
+ # atom size as rmin_half. Here we correct for this behavior by explicitly defining both as
465
+ # the same unit if either one is defined.
466
+ if "vdW" in smirnoff_data_0_2["SMIRNOFF"].keys():
467
+ rmh_unit = smirnoff_data_0_2["SMIRNOFF"]["vdW"].get("rmin_half_unit", None)
468
+ sig_unit = smirnoff_data_0_2["SMIRNOFF"]["vdW"].get("sigma_unit", None)
469
+ if (rmh_unit is not None) and (sig_unit is None):
470
+ smirnoff_data_0_2["SMIRNOFF"]["vdW"]["sigma_unit"] = rmh_unit
471
+ elif (sig_unit is not None) and (rmh_unit is None):
472
+ smirnoff_data_0_2["SMIRNOFF"]["vdW"]["rmin_half_unit"] = sig_unit
473
+ # If both are None, or both are defined, don't overwrite anything
474
+ else:
475
+ pass
476
+
477
+ # Recursively attach unit strings
478
+ smirnoff_data = recursive_attach_unit_strings(smirnoff_data_0_2, {})
479
+
480
+ # Change TorsionHandler potential from "charmm" to "k*(1+cos(periodicity*theta-phase))". Note that, scientifically,
481
+ # we should have used "k*(1+cos(periodicity*theta-phase))" all along, since "charmm" technically
482
+ # implies that we would support a harmonic potential for torsion terms with periodicity 0
483
+ # More at: https://github.com/openforcefield/openff-toolkit/issues/303#issuecomment-490156779
484
+ if "ProperTorsions" in smirnoff_data["SMIRNOFF"]:
485
+ if "potential" in smirnoff_data["SMIRNOFF"]["ProperTorsions"]:
486
+ if smirnoff_data["SMIRNOFF"]["ProperTorsions"]["potential"] == "charmm":
487
+ smirnoff_data["SMIRNOFF"]["ProperTorsions"]["potential"] = "k*(1+cos(periodicity*theta-phase))"
488
+ if "ImproperTorsions" in smirnoff_data["SMIRNOFF"]:
489
+ if "potential" in smirnoff_data["SMIRNOFF"]["ImproperTorsions"]:
490
+ if smirnoff_data["SMIRNOFF"]["ImproperTorsions"]["potential"] == "charmm":
491
+ smirnoff_data["SMIRNOFF"]["ImproperTorsions"]["potential"] = "k*(1+cos(periodicity*theta-phase))"
492
+
493
+ # Add per-section tag
494
+ sections_not_to_version_0_3 = ["Author", "Date", "version", "aromaticity_model"]
495
+ for l1_tag in smirnoff_data["SMIRNOFF"].keys():
496
+ if l1_tag not in sections_not_to_version_0_3:
497
+ if smirnoff_data["SMIRNOFF"][l1_tag] is None:
498
+ # Handle empty entries, such as the ToolkitAM1BCC handler.
499
+ smirnoff_data["SMIRNOFF"][l1_tag] = {}
500
+
501
+ smirnoff_data["SMIRNOFF"][l1_tag]["version"] = 0.3
502
+
503
+ # Update top-level tag
504
+ smirnoff_data["SMIRNOFF"]["version"] = 0.3
505
+
506
+ return smirnoff_data
507
+
508
+
509
+ def convert_0_1_smirnoff_to_0_2(smirnoff_data_0_1):
510
+ """
511
+ Convert an 0.1-compliant SMIRNOFF dict to an 0.2-compliant one.
512
+ This involves renaming several tags, adding Electrostatics and ToolkitAM1BCC tags, and
513
+ separating improper torsions into their own section.
514
+
515
+ Parameters
516
+ ----------
517
+ smirnoff_data_0_1
518
+ Hierarchical dict representing a SMIRNOFF data structure according the the 0.1 spec
519
+
520
+ Returns
521
+ -------
522
+ smirnoff_data_0_2
523
+ Hierarchical dict representing a SMIRNOFF data structure according the the 0.2 spec
524
+ """
525
+ smirnoff_data = smirnoff_data_0_1.copy()
526
+
527
+ l0_replacement_dict = {"SMIRFF": "SMIRNOFF"}
528
+ l1_replacement_dict = {
529
+ "HarmonicBondForce": "Bonds",
530
+ "HarmonicAngleForce": "Angles",
531
+ "PeriodicTorsionForce": "ProperTorsions",
532
+ "NonbondedForce": "vdW",
533
+ }
534
+ for old_l0_tag, new_l0_tag in l0_replacement_dict.items():
535
+ # Convert first-level smirnoff_data tags.
536
+ # Right now this just changes the SMIRFF tag to SMIRNOFF
537
+ if old_l0_tag in smirnoff_data.keys():
538
+ smirnoff_data[new_l0_tag] = smirnoff_data[old_l0_tag]
539
+ del smirnoff_data[old_l0_tag]
540
+
541
+ # SMIRFF tag will have been converted to SMIRNOFF here
542
+ # Convert second-level tags here
543
+ for old_l1_tag, new_l1_tag in l1_replacement_dict.items():
544
+ if old_l1_tag in smirnoff_data["SMIRNOFF"].keys():
545
+ smirnoff_data["SMIRNOFF"][new_l1_tag] = smirnoff_data["SMIRNOFF"][old_l1_tag]
546
+ del smirnoff_data["SMIRNOFF"][old_l1_tag]
547
+
548
+ # Add 'potential' field to each l1 tag
549
+ default_potential = {
550
+ "Bonds": "harmonic",
551
+ "Angles": "harmonic",
552
+ "ProperTorsions": "charmm",
553
+ # Note that "charmm" isn't actually correct, and was later changed
554
+ # in the 0.3 spec. More info at
555
+ # https://github.com/openforcefield/openff-toolkit/pull/311#commitcomment-33494506
556
+ "vdW": "Lennard-Jones-12-6",
557
+ }
558
+ for l1_tag in smirnoff_data["SMIRNOFF"].keys():
559
+ if l1_tag in default_potential.keys():
560
+ # Ensure that it isn't there already (shouldn't happen, but better to be safe)
561
+ if "potential" in smirnoff_data["SMIRNOFF"][l1_tag].keys():
562
+ assert smirnoff_data[l1_tag].keys == default_potential[l1_tag]
563
+ continue
564
+ # Issue an informative warning about assumptions made during conversion.
565
+ logger.warning(
566
+ f"0.1 SMIRNOFF spec file does not contain 'potential' attribute for '{l1_tag}' tag. "
567
+ f"The SMIRNOFF spec converter is assuming it has a value of '{default_potential[l1_tag]}'"
568
+ )
569
+ smirnoff_data["SMIRNOFF"][l1_tag]["potential"] = default_potential[l1_tag]
570
+
571
+ # Separate improper torsions from propers
572
+ if "ProperTorsions" in smirnoff_data["SMIRNOFF"]:
573
+ if "Improper" in smirnoff_data["SMIRNOFF"]["ProperTorsions"]:
574
+ # First generate an ImproperTorsions header, taking the relevant values from the ProperTorsions header
575
+ improper_section = {
576
+ "k_unit": smirnoff_data["SMIRNOFF"]["ProperTorsions"]["k_unit"],
577
+ "phase_unit": smirnoff_data["SMIRNOFF"]["ProperTorsions"]["phase_unit"],
578
+ "potential": smirnoff_data["SMIRNOFF"]["ProperTorsions"]["potential"],
579
+ "Improper": smirnoff_data["SMIRNOFF"]["ProperTorsions"]["Improper"],
580
+ }
581
+
582
+ # Then, attach the newly-made ImproperTorsions section
583
+ smirnoff_data["SMIRNOFF"]["ImproperTorsions"] = improper_section
584
+ del smirnoff_data["SMIRNOFF"]["ProperTorsions"]["Improper"]
585
+
586
+ # Add Electrostatics tag, setting several values to their defaults and
587
+ # warning about assumptions that are being made
588
+ electrostatics_section = {
589
+ "method": "PME",
590
+ "scale12": 0.0,
591
+ "scale13": 0.0,
592
+ "scale15": 1.0,
593
+ "cutoff": 9.0,
594
+ "cutoff_unit": "angstrom",
595
+ }
596
+ logger.warning(
597
+ "0.1 SMIRNOFF spec did not allow the 'Electrostatics' tag. Adding it in 0.2 spec conversion, and "
598
+ "assuming the following values:"
599
+ )
600
+ for key, val in electrostatics_section.items():
601
+ logger.warning(f"\t{key}: {val}")
602
+
603
+ # Take electrostatics 1-4 scaling term from 0.1 spec's NonBondedForce tag
604
+ electrostatics_section["scale14"] = smirnoff_data["SMIRNOFF"]["vdW"]["coulomb14scale"]
605
+ del smirnoff_data["SMIRNOFF"]["vdW"]["coulomb14scale"]
606
+ smirnoff_data["SMIRNOFF"]["Electrostatics"] = electrostatics_section
607
+
608
+ # Change vdW's lj14scale to 14scale, add other scaling terms
609
+ vdw_section_additions = {
610
+ "method": "cutoff",
611
+ "combining_rules": "Lorentz-Berthelot",
612
+ "scale12": "0.0",
613
+ "scale13": "0.0",
614
+ "scale15": "1",
615
+ "switch_width": "1.0",
616
+ "switch_width_unit": "angstrom",
617
+ "cutoff": "9.0",
618
+ "cutoff_unit": "angstrom",
619
+ }
620
+ for key, val in vdw_section_additions.items():
621
+ if key not in smirnoff_data["SMIRNOFF"]["vdW"].keys():
622
+ logger.warning(
623
+ f"0.1 SMIRNOFF spec file does not contain '{key}' attribute for 'NonBondedMethod/vdW'' tag. "
624
+ f"The SMIRNOFF spec converter is assuming it has a value of '{val}'"
625
+ )
626
+ smirnoff_data["SMIRNOFF"]["vdW"][key] = val
627
+
628
+ # Rename L-J 1-4 scaling term from 0.1 spec's NonBondedForce tag to vdW's scale14
629
+ smirnoff_data["SMIRNOFF"]["vdW"]["scale14"] = smirnoff_data["SMIRNOFF"]["vdW"]["lj14scale"]
630
+ del smirnoff_data["SMIRNOFF"]["vdW"]["lj14scale"]
631
+
632
+ # Add <ToolkitAM1BCC/> tag
633
+ smirnoff_data["SMIRNOFF"]["ToolkitAM1BCC"] = {}
634
+
635
+ # Update top-level tag
636
+ smirnoff_data["SMIRNOFF"]["version"] = 0.2
637
+
638
+ return smirnoff_data
639
+
640
+
641
+ def recursive_attach_unit_strings(smirnoff_data, units_to_attach):
642
+ """
643
+ Recursively traverse a SMIRNOFF data structure, appending "* {unit}" to values in key:value pairs
644
+ where "key_unit":"unit_string" is present at a higher level in the hierarchy.
645
+ This function expects all items in smirnoff_data to be formatted as strings.
646
+
647
+ Parameters
648
+ ----------
649
+ smirnoff_data
650
+ Any level of hierarchy that is part of a SMIRNOFF dict, with all data members
651
+ formatted as string.
652
+ units_to_attach
653
+ Dict of the form {key:unit_string}
654
+
655
+ Returns
656
+ -------
657
+ unit_appended_smirnoff_data: dict
658
+ """
659
+ import re
660
+
661
+ # Make a copy of units_to_attach so we don't modify the original (otherwise things like k_unit could
662
+ # leak between sections)
663
+ units_to_attach = units_to_attach.copy()
664
+ # smirnoff_data = smirnoff_data.copy()
665
+
666
+ # If we're working with a dict, see if there are any new unit entries and store them,
667
+ # then operate recursively on the values in the dict.
668
+ if isinstance(smirnoff_data, dict):
669
+ # Go over all key:value pairs once to see if there are new units to attach.
670
+ # Note that units to be attached can be defined in the same dict as the
671
+ # key:value pair they will be attached to, so we need to complete this check
672
+ # before we are able to check other items in the dict.
673
+ for key, value in list(smirnoff_data.items()):
674
+ if key[-5:] == "_unit":
675
+ units_to_attach[key[:-5]] = value
676
+ del smirnoff_data[key]
677
+
678
+ # Go through once more to attach units as appropriate
679
+ for key in smirnoff_data.keys():
680
+ # We use regular expressions to catch possible indexed attributes
681
+ attach_unit = None
682
+ for unit_key, unit_string in units_to_attach.items():
683
+ if re.match(f"{unit_key}[0-9]*", key):
684
+ attach_unit = unit_string
685
+
686
+ if attach_unit is not None:
687
+ smirnoff_data[key] = str(smirnoff_data[key]) + " * " + attach_unit
688
+
689
+ # And recursively act on value, in case it's a deeper level of hierarchy
690
+ smirnoff_data[key] = recursive_attach_unit_strings(smirnoff_data[key], units_to_attach)
691
+
692
+ # If it's a list, operate on each member of the list
693
+ elif isinstance(smirnoff_data, list):
694
+ for index, value in enumerate(smirnoff_data):
695
+ smirnoff_data[index] = recursive_attach_unit_strings(value, units_to_attach)
696
+
697
+ # Otherwise, just return smirnoff_data unchanged
698
+ else:
699
+ pass
700
+
701
+ return smirnoff_data
702
+
703
+
704
+ def get_molecule_parameterIDs(molecules: list["Molecule"], forcefield: "ForceField") -> tuple[dict, dict]:
705
+ """Process a list of molecules with a specified SMIRNOFF ffxml file and determine which parameters are used by
706
+ which molecules, returning collated results.
707
+
708
+ Parameters
709
+ ----------
710
+ molecules
711
+ List of molecules (with explicit hydrogens) to parse
712
+ forcefield
713
+ The ForceField to apply
714
+
715
+ Returns
716
+ -------
717
+ parameters_by_molecule
718
+ Parameter IDs used in each molecule, keyed by isomeric SMILES
719
+ generated from provided OEMols. Each entry in the dict is a list
720
+ which does not necessarily have unique entries; i.e. parameter IDs
721
+ which are used more than once will occur multiple times.
722
+
723
+ parameters_by_ID
724
+ Molecules in which each parameter ID occur, keyed by parameter ID.
725
+ Each entry in the dict is a set of isomeric SMILES for molecules
726
+ in which that parameter occurs. No frequency information is stored.
727
+
728
+ """
729
+
730
+ from openff.toolkit.topology import Topology
731
+
732
+ # Create storage
733
+ parameters_by_molecule: dict[str, list] = dict()
734
+ parameters_by_ID: dict[str, set[str]] = dict()
735
+
736
+ # Generate isomeric SMILES for each molecule, ensuring all molecules are unique
737
+ isosmiles = [molecule.to_smiles() for molecule in molecules]
738
+ already_seen = set()
739
+ duplicates = set(
740
+ smiles
741
+ for smiles in isosmiles
742
+ if smiles in already_seen or already_seen.add(smiles) # type: ignore[func-returns-value]
743
+ )
744
+ if len(duplicates) > 0:
745
+ raise ValueError(
746
+ "Error: get_molecule_parameterIDs has been provided a list of oemols which contains some duplicates: "
747
+ f"{duplicates}"
748
+ )
749
+
750
+ # Assemble molecules into a Topology
751
+ topology = Topology()
752
+ for molecule in molecules:
753
+ topology.add_molecule(molecule)
754
+
755
+ # Label molecules
756
+ labels = forcefield.label_molecules(topology)
757
+
758
+ # Organize labels into output dictionary by looping over all molecules/smiles
759
+ for idx in range(len(isosmiles)):
760
+ # Pull smiles, initialize storage
761
+ smi = isosmiles[idx]
762
+ parameters_by_molecule[smi] = []
763
+
764
+ # Organize data for this molecule
765
+ data = labels[idx]
766
+ for force_type in data.keys():
767
+ for parameter_type in data[force_type].values():
768
+ pid = parameter_type.id
769
+ # Store pid to molecule
770
+ parameters_by_molecule[smi].append(pid)
771
+
772
+ # Store which molecule this pid occurred in
773
+ if pid not in parameters_by_ID:
774
+ parameters_by_ID[pid] = set()
775
+ parameters_by_ID[pid].add(smi)
776
+ else:
777
+ parameters_by_ID[pid].add(smi)
778
+
779
+ return parameters_by_molecule, parameters_by_ID
780
+
781
+
782
+ def sort_smirnoff_dict(data):
783
+ """
784
+ Recursively sort the keys in a dict of SMIRNOFF data.
785
+
786
+ Adapted from https://stackoverflow.com/a/47882384/4248961
787
+
788
+ TODO: Should this live elsewhere?
789
+ """
790
+ sorted_dict = dict()
791
+ for key, val in sorted(data.items()):
792
+ if isinstance(val, dict):
793
+ # This should hit each ParameterHandler and dicts within them
794
+ sorted_dict[key] = sort_smirnoff_dict(val)
795
+ elif isinstance(val, list):
796
+ # Handle case of ParameterLists, which show up in
797
+ # the smirnoff dicts as lists of dicts
798
+ new_parameter_list = list()
799
+ for param in val:
800
+ new_parameter_list.append(sort_smirnoff_dict(param))
801
+ sorted_dict[key] = new_parameter_list
802
+ else:
803
+ # Handle metadata or the bottom of a recursive dict
804
+ sorted_dict[key] = val
805
+ return sorted_dict