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,2485 @@
1
+ """
2
+ Tests for Topology
3
+
4
+ """
5
+
6
+ import itertools
7
+ import re
8
+ from copy import deepcopy
9
+
10
+ import numpy as np
11
+ import pytest
12
+ from openff.units.openmm import from_openmm
13
+ from openff.utilities import skip_if_missing
14
+ from openmm import app
15
+
16
+ from openff.toolkit import Quantity, unit
17
+ from openff.toolkit._tests.create_molecules import (
18
+ create_ammonia,
19
+ create_cyclohexane,
20
+ create_ethanol,
21
+ create_reversed_ethanol,
22
+ create_water,
23
+ cyx_hierarchy_added,
24
+ dipeptide,
25
+ dipeptide_hierarchy_added,
26
+ dipeptide_residues_perceived,
27
+ ethane_from_smiles,
28
+ ethene_from_smiles,
29
+ propane_from_smiles,
30
+ toluene_from_sdf,
31
+ topology_with_metadata,
32
+ )
33
+ from openff.toolkit._tests.utils import (
34
+ get_data_file_path,
35
+ requires_openeye,
36
+ requires_pkg,
37
+ requires_rdkit,
38
+ )
39
+ from openff.toolkit.topology import (
40
+ Atom,
41
+ ImproperDict,
42
+ Molecule,
43
+ TagSortedDict,
44
+ Topology,
45
+ ValenceDict,
46
+ )
47
+ from openff.toolkit.topology._mm_molecule import _SimpleMolecule
48
+ from openff.toolkit.utils import (
49
+ BASIC_CHEMINFORMATICS_TOOLKITS,
50
+ OPENEYE_AVAILABLE,
51
+ RDKIT_AVAILABLE,
52
+ OpenEyeToolkitWrapper,
53
+ RDKitToolkitWrapper,
54
+ )
55
+ from openff.toolkit.utils.exceptions import (
56
+ AmbiguousAtomChemicalAssignment,
57
+ AmbiguousBondChemicalAssignment,
58
+ AtomNotInTopologyError,
59
+ BondNotInTopologyError,
60
+ DuplicateUniqueMoleculeError,
61
+ HierarchyIteratorNameConflictError,
62
+ IncompatibleUnitError,
63
+ InvalidBoxVectorsError,
64
+ InvalidPeriodicityError,
65
+ MissingConformersError,
66
+ MissingUniqueMoleculesError,
67
+ MoleculeNotInTopologyError,
68
+ NonUniqueSubstructureName,
69
+ PDBMoleculeHasNoncontiguousAtomIndicesError,
70
+ SubstructureAtomSmartsInvalid,
71
+ SubstructureBondSmartsInvalid,
72
+ UnassignedChemistryInPDBError,
73
+ VirtualSitesUnsupportedError,
74
+ WrongShapeError,
75
+ )
76
+
77
+
78
+ def assert_tuple_of_atoms_equal(atom_tuples1, atom_tuples2, transformed_dict_cls=ValenceDict):
79
+ """Check that two lists of atoms are the same.
80
+
81
+ The function compares that the parent molecules are isomorphic and
82
+ that the molecule index is the same.
83
+ """
84
+ assert len(atom_tuples1) == len(atom_tuples2)
85
+
86
+ # They are atoms of isomorphic molecules. We assume here that all
87
+ # atoms in the same list of tuples belong to the same molecule so
88
+ # that we can perform the check only once.
89
+ molecule1 = atom_tuples1[0][0]._molecule
90
+ molecule2 = atom_tuples2[0][0]._molecule
91
+ assert molecule1 == molecule2
92
+ for atom_tuple in atom_tuples1:
93
+ for a in atom_tuple:
94
+ assert a._molecule is molecule1
95
+ for atom_tuple in atom_tuples2:
96
+ for a in atom_tuple:
97
+ assert a._molecule is molecule2
98
+
99
+ # All atoms are equal. Use ValenceDict for this
100
+ atom_indices = []
101
+ for atom_tuples in [atom_tuples1, atom_tuples2]:
102
+ valence_dict = transformed_dict_cls()
103
+ for atom_tuple in atom_tuples:
104
+ key = tuple(a.molecule_atom_index for a in atom_tuple)
105
+ valence_dict[key] = atom_tuple
106
+ atom_indices.append(valence_dict)
107
+ assert set(atom_indices[0]) == set(atom_indices[1])
108
+
109
+
110
+ # IF we've done our jobs right, it shouldn't matter which toolkit the tests for Topology run using (both's behaviors
111
+ # should be indistinguishable)
112
+ def test_cheminformatics_toolkit_is_installed():
113
+ """Ensure that at least one supported cheminformatics toolkit is installed."""
114
+ if not (RDKIT_AVAILABLE) and not (OPENEYE_AVAILABLE):
115
+ msg = "No supported cheminformatics toolkits are installed. Please install a supported toolkit:\n"
116
+ msg += str(BASIC_CHEMINFORMATICS_TOOLKITS)
117
+ raise Exception(msg)
118
+
119
+
120
+ @pytest.fixture()
121
+ def mixed_topology():
122
+ return Topology.from_molecules(
123
+ [
124
+ create_ethanol(),
125
+ create_ethanol(),
126
+ _SimpleMolecule.from_molecule(create_ethanol()),
127
+ _SimpleMolecule.from_molecule(create_ethanol()),
128
+ ]
129
+ )
130
+
131
+
132
+ # TODO: Refactor this to pytest
133
+ class TestTopology:
134
+ def test_empty(self):
135
+ """Test creation of empty topology"""
136
+ topology = Topology()
137
+ assert topology.n_molecules == 0
138
+ assert topology.n_unique_molecules == 0
139
+ assert topology.n_atoms == 0
140
+ assert topology.n_bonds == 0
141
+ assert topology.box_vectors is None
142
+ assert not topology.is_periodic
143
+ assert len(topology.constrained_atom_pairs.items()) == 0
144
+
145
+ def test_add_molecule_index(self):
146
+ """Ensure the index of added molecules is 0-indexed."""
147
+ topology = Topology()
148
+
149
+ index = topology.add_molecule(create_ammonia())
150
+
151
+ assert index == 0 == topology.n_molecules - 1
152
+
153
+ # Ensure that same index can immediately be used as a lookup
154
+ topology.molecule(index)
155
+
156
+ next_index = topology.add_molecule(create_ethanol())
157
+
158
+ assert next_index == 1 == topology.n_molecules - 1
159
+
160
+ def test_from_molecule_bad_argument(self):
161
+ with pytest.raises(
162
+ ValueError,
163
+ match=r"Invalid type.*Topology",
164
+ ):
165
+ topology = Topology()
166
+
167
+ topology.add_molecule(create_water().to_topology())
168
+
169
+ @pytest.mark.timeout(10)
170
+ def test_add_molecules(self):
171
+ water = create_water()
172
+
173
+ topology = Topology()
174
+
175
+ indices = topology.add_molecules(10_000 * [water])
176
+
177
+ assert topology.n_molecules == 10_000
178
+
179
+ assert indices == [*range(10_000)]
180
+
181
+ def test_from_molecule_nonlist(self):
182
+ topology = Topology()
183
+
184
+ with pytest.raises(
185
+ ValueError,
186
+ match=r"Invalid type.*set.*molecules",
187
+ ):
188
+ topology.add_molecules({create_water(), create_ammonia()})
189
+
190
+ with pytest.raises(
191
+ ValueError,
192
+ match=r"Invalid type.*str.*molecules",
193
+ ):
194
+ topology.add_molecules("CC.CCO")
195
+
196
+ def test_add_simple_molecule_atom_names(self):
197
+ """Reproduce issue #1927"""
198
+ simple = _SimpleMolecule.from_molecule(Molecule.from_smiles("C"))
199
+
200
+ for index, letter in enumerate("BLAHB"):
201
+ simple.atom(index).name = letter
202
+
203
+ topology = Topology()
204
+ topology.add_molecule(simple)
205
+
206
+ assert topology.atom(0).name == "B"
207
+ assert topology.atom(1).name == "L"
208
+ assert topology.atom(2).name == "A"
209
+ assert topology.atom(3).name == "H"
210
+ assert topology.atom(4).name == "B"
211
+
212
+ def test_reinitialization_box_vectors(self):
213
+ topology = Topology()
214
+ assert Topology(topology).box_vectors is None
215
+
216
+ topology.box_vectors = [1, 2, 3] * unit.nanometer
217
+ topology_copy = Topology(topology)
218
+
219
+ assert (topology.box_vectors == topology_copy.box_vectors).all()
220
+
221
+ def test_box_vectors(self):
222
+ """Test the getter and setter for box_vectors"""
223
+ topology = Topology()
224
+ good_box_vectors = unit.Quantity(np.eye(3) * 20, unit.angstrom)
225
+ one_dim_vectors = unit.Quantity(np.ones(3) * 20, unit.angstrom)
226
+ list_vectors = unit.Quantity([20, 20, 20], unit.angstrom)
227
+ list_list_vectors = unit.Quantity([[20, 0, 0], [0, 20, 0], [0, 0, 20]], unit.angstrom)
228
+ bad_shape_vectors = unit.Quantity(np.ones(2) * 20, unit.angstrom)
229
+ bad_units_vectors = unit.Quantity(np.ones(3) * 20, unit.year)
230
+ bad_type_vectors = unit.Quantity(1.0, unit.nanometer)
231
+ unitless_vectors = np.array([10, 20, 30])
232
+
233
+ assert topology.box_vectors is None
234
+
235
+ for bad_vectors in [
236
+ bad_shape_vectors,
237
+ bad_units_vectors,
238
+ bad_type_vectors,
239
+ unitless_vectors,
240
+ ]:
241
+ with pytest.raises(InvalidBoxVectorsError):
242
+ topology.box_vectors = bad_vectors
243
+ assert topology.box_vectors is None
244
+
245
+ for good_vectors in [
246
+ good_box_vectors,
247
+ one_dim_vectors,
248
+ list_vectors,
249
+ list_list_vectors,
250
+ ]:
251
+ topology.box_vectors = good_vectors
252
+ assert (topology.box_vectors == good_vectors * np.eye(3)).all()
253
+
254
+ def test_issue_1527(self):
255
+ """Test the error handling of setting box vectors with an OpenMM quantity."""
256
+ import numpy
257
+ import openmm.unit
258
+
259
+ topology = Topology()
260
+ topology.box_vectors = numpy.ones(3) * openmm.unit.nanometer
261
+
262
+ assert isinstance(topology.box_vectors, unit.Quantity)
263
+
264
+ def test_is_periodic(self):
265
+ """Test the getter and setter for is_periodic"""
266
+ vacuum_top = Topology()
267
+ assert vacuum_top.is_periodic is False
268
+
269
+ with pytest.raises(InvalidPeriodicityError):
270
+ vacuum_top.is_periodic = True
271
+
272
+ solvent_box = Topology()
273
+ solvent_box.box_vectors = np.eye(3) * 4 * unit.nanometer
274
+ assert solvent_box.is_periodic is True
275
+
276
+ with pytest.raises(InvalidPeriodicityError):
277
+ solvent_box.is_periodic = False
278
+ solvent_box.box_vectors = None
279
+ assert solvent_box.is_periodic is False
280
+
281
+ def test_from_smiles(self):
282
+ """Test creation of a OpenFF Topology object from a SMILES string"""
283
+ topology = Topology.from_molecules(ethane_from_smiles())
284
+
285
+ assert topology.n_molecules == 1
286
+ assert topology.n_unique_molecules == 1
287
+ assert topology.n_atoms == 8
288
+ assert topology.n_bonds == 7
289
+ assert topology.box_vectors is None
290
+ assert len(topology.constrained_atom_pairs.items()) == 0
291
+
292
+ topology.add_molecule(ethane_from_smiles())
293
+ assert topology.n_molecules == 2
294
+ assert topology.n_unique_molecules == 1
295
+ assert topology.n_atoms == 16
296
+ assert topology.n_bonds == 14
297
+ assert topology.box_vectors is None
298
+ assert len(topology.constrained_atom_pairs.items()) == 0
299
+
300
+ def test_from_smiles_unique_mols(self):
301
+ """Test the addition of two different molecules to a topology"""
302
+ topology = Topology.from_molecules([ethane_from_smiles(), propane_from_smiles()])
303
+ assert topology.n_molecules == 2
304
+ assert topology.n_unique_molecules == 2
305
+
306
+ def test_n_atoms(self):
307
+ """Test n_atoms function"""
308
+ topology = Topology()
309
+ assert topology.n_atoms == 0
310
+ assert topology.n_bonds == 0
311
+ topology.add_molecule(ethane_from_smiles())
312
+ assert topology.n_atoms == 8
313
+ assert topology.n_bonds == 7
314
+
315
+ def test_get_atom(self):
316
+ """Test Topology.atom function (atom lookup from index)"""
317
+ topology = Topology()
318
+ topology.add_molecule(ethane_from_smiles())
319
+
320
+ # Make sure we get 2 carbons and 8 hydrogens
321
+ n_carbons = 0
322
+ n_hydrogens = 0
323
+ for index in range(8):
324
+ if topology.atom(index).atomic_number == 6:
325
+ n_carbons += 1
326
+ if topology.atom(index).atomic_number == 1:
327
+ n_hydrogens += 1
328
+ assert n_carbons == 2
329
+ assert n_hydrogens == 6
330
+
331
+ with pytest.raises(ValueError, match=r"must be an int.*'str'"):
332
+ topology.atom("one")
333
+
334
+ with pytest.raises(AtomNotInTopologyError):
335
+ topology.atom(-1)
336
+
337
+ with pytest.raises(AtomNotInTopologyError):
338
+ topology.atom(8)
339
+
340
+ def test_atom_index(self):
341
+ topology = create_ethanol().to_topology()
342
+
343
+ for index in range(topology.n_atoms):
344
+ atom = topology.atom(index)
345
+ assert topology.atom_index(atom) == index
346
+
347
+ ghost_atom = Atom(atomic_number=1, formal_charge=0, is_aromatic=False)
348
+
349
+ with pytest.raises(AtomNotInTopologyError):
350
+ topology.atom_index(ghost_atom)
351
+
352
+ def test_molecule_index(self):
353
+ molecules = [Molecule.from_smiles("CCO"), Molecule.from_smiles("O")]
354
+
355
+ topology = Topology.from_molecules(molecules)
356
+
357
+ for index in range(topology.n_molecules):
358
+ molecule = topology.molecule(index)
359
+ assert topology.molecule_index(molecule) == index
360
+
361
+ ghost_molecule = Molecule.from_smiles("N")
362
+
363
+ with pytest.raises(MoleculeNotInTopologyError):
364
+ topology.molecule_index(ghost_molecule)
365
+
366
+ def test_atom_element_properties(self):
367
+ """
368
+ Test element-like getters of `Atom`. In 0.11.0, Atom.element
369
+ was removed and replaced with Atom.atomic_number and Atom.symbol.
370
+ """
371
+ topology = Topology()
372
+ topology.add_molecule(toluene_from_sdf())
373
+
374
+ first_atom = topology.atom(0)
375
+ eighth_atom = topology.atom(7)
376
+
377
+ # These atoms are expected to be hydrogen and carbon, respectively
378
+ assert first_atom.symbol == "C"
379
+ assert first_atom.atomic_number == 6
380
+ assert eighth_atom.symbol == "H"
381
+ assert eighth_atom.atomic_number == 1
382
+
383
+ def test_get_bond(self):
384
+ """Test Topology.bond function (bond lookup from index)"""
385
+ topology = Topology()
386
+ topology.add_molecule(ethane_from_smiles())
387
+ topology.add_molecule(ethene_from_smiles())
388
+
389
+ n_single_bonds = 0
390
+ n_double_bonds = 0
391
+ n_ch_bonds = 0
392
+ n_cc_bonds = 0
393
+ for index in range(12): # 7 from ethane, 5 from ethene
394
+ bond = topology.bond(index)
395
+ if bond.bond_order == 1:
396
+ n_single_bonds += 1
397
+ if bond.bond_order == 2:
398
+ n_double_bonds += 1
399
+ n_bond_carbons = 0
400
+ n_bond_hydrogens = 0
401
+ for atom in bond.atoms:
402
+ if atom.atomic_number == 6:
403
+ n_bond_carbons += 1
404
+ if atom.atomic_number == 1:
405
+ n_bond_hydrogens += 1
406
+ if n_bond_carbons == 2:
407
+ n_cc_bonds += 1
408
+ if n_bond_carbons == 1 and n_bond_hydrogens == 1:
409
+ n_ch_bonds += 1
410
+
411
+ assert n_single_bonds == 11
412
+ assert n_double_bonds == 1
413
+ assert n_cc_bonds == 2
414
+ assert n_ch_bonds == 10
415
+
416
+ with pytest.raises(ValueError, match=r"must be an int.*'str'"):
417
+ topology.bond("one")
418
+
419
+ with pytest.raises(BondNotInTopologyError, match="No bond with index -1"):
420
+ topology.bond(-1)
421
+
422
+ with pytest.raises(BondNotInTopologyError, match="No bond with index 12"):
423
+ topology.bond(12)
424
+
425
+ def test_angles(self):
426
+ """Topology.angles should return image angles of all topology molecules."""
427
+ molecule1 = ethane_from_smiles()
428
+ molecule2 = propane_from_smiles()
429
+
430
+ # Create topology.
431
+ topology = Topology()
432
+ topology.add_molecule(molecule1)
433
+ topology.add_molecule(molecule1)
434
+ topology.add_molecule(molecule2)
435
+
436
+ # The topology should have the correct number of angles.
437
+ topology_angles = list(topology.angles)
438
+ assert len(topology_angles) == topology.n_angles
439
+ assert topology.n_angles == 2 * molecule1.n_angles + molecule2.n_angles
440
+
441
+ # Check that the topology angles are the correct ones.
442
+ mol_angle_atoms1 = list(molecule1.angles)
443
+ mol_angle_atoms2 = list(molecule2.angles)
444
+ top_angle_atoms1 = [tuple(a for a in atoms) for atoms in topology_angles[: molecule1.n_angles]]
445
+ top_angle_atoms2 = [
446
+ tuple(a for a in atoms) for atoms in topology_angles[molecule1.n_angles : 2 * molecule1.n_angles]
447
+ ]
448
+ top_angle_atoms3 = [tuple(a for a in atoms) for atoms in topology_angles[2 * molecule1.n_angles :]]
449
+
450
+ assert_tuple_of_atoms_equal(top_angle_atoms1, mol_angle_atoms1)
451
+ assert_tuple_of_atoms_equal(top_angle_atoms2, mol_angle_atoms1)
452
+ assert_tuple_of_atoms_equal(top_angle_atoms3, mol_angle_atoms2)
453
+
454
+ def test_propers(self):
455
+ """Topology.propers should return image propers torsions of all topology molecules."""
456
+ molecule1 = ethane_from_smiles()
457
+ molecule2 = propane_from_smiles()
458
+
459
+ # Create topology.
460
+ topology = Topology()
461
+ topology.add_molecule(molecule1)
462
+ topology.add_molecule(molecule1)
463
+ topology.add_molecule(molecule2)
464
+
465
+ # The topology should have the correct number of propers.
466
+ topology_propers = list(topology.propers)
467
+ assert len(topology_propers) == topology.n_propers
468
+ assert topology.n_propers == 2 * molecule1.n_propers + molecule2.n_propers
469
+
470
+ # Check that the topology propers are the correct ones.
471
+ mol_proper_atoms1 = list(molecule1.propers)
472
+ mol_proper_atoms2 = list(molecule2.propers)
473
+ top_proper_atoms1 = [tuple(a for a in atoms) for atoms in topology_propers[: molecule1.n_propers]]
474
+ top_proper_atoms2 = [
475
+ tuple(a for a in atoms) for atoms in topology_propers[molecule1.n_propers : 2 * molecule1.n_propers]
476
+ ]
477
+ top_proper_atoms3 = [tuple(a for a in atoms) for atoms in topology_propers[2 * molecule1.n_propers :]]
478
+
479
+ assert_tuple_of_atoms_equal(top_proper_atoms1, mol_proper_atoms1)
480
+ assert_tuple_of_atoms_equal(top_proper_atoms2, mol_proper_atoms1)
481
+ assert_tuple_of_atoms_equal(top_proper_atoms3, mol_proper_atoms2)
482
+
483
+ def test_impropers(self):
484
+ """Topology.impropers should return image impropers torsions of all topology molecules."""
485
+ molecule1 = ethane_from_smiles()
486
+ molecule2 = propane_from_smiles()
487
+
488
+ # Create topology.
489
+ topology = Topology()
490
+ topology.add_molecule(molecule1)
491
+ topology.add_molecule(molecule1)
492
+ topology.add_molecule(molecule2)
493
+
494
+ # The topology should have the correct number of impropers.
495
+ topology_impropers = list(topology.impropers)
496
+ assert len(topology_impropers) == topology.n_impropers
497
+ assert topology.n_impropers == 2 * molecule1.n_impropers + molecule2.n_impropers
498
+
499
+ # Check that the topology impropers are the correct ones.
500
+ mol_improper_atoms1 = list(molecule1.impropers)
501
+ mol_improper_atoms2 = list(molecule2.impropers)
502
+ top_improper_atoms1 = [tuple(a for a in atoms) for atoms in topology_impropers[: molecule1.n_impropers]]
503
+ top_improper_atoms2 = [
504
+ tuple(a for a in atoms) for atoms in topology_impropers[molecule1.n_impropers : 2 * molecule1.n_impropers]
505
+ ]
506
+ top_improper_atoms3 = [tuple(a for a in atoms) for atoms in topology_impropers[2 * molecule1.n_impropers :]]
507
+
508
+ assert_tuple_of_atoms_equal(top_improper_atoms1, mol_improper_atoms1, transformed_dict_cls=ImproperDict)
509
+ assert_tuple_of_atoms_equal(top_improper_atoms2, mol_improper_atoms1, transformed_dict_cls=ImproperDict)
510
+ assert_tuple_of_atoms_equal(top_improper_atoms3, mol_improper_atoms2, transformed_dict_cls=ImproperDict)
511
+
512
+ def test_pruned_impropers(self):
513
+ """Test {smirnoff|amber}_impropers from the Topology API"""
514
+ top = Topology.from_molecules([Molecule.from_smiles(smi) for smi in ["N", "C=C"]])
515
+
516
+ assert len([*top.smirnoff_impropers]) == 18
517
+ assert len([*top.amber_impropers]) == 18
518
+
519
+ # Order not guaranteed, so cannot zip and compare directly
520
+ for smirnoff_imp in top.smirnoff_impropers:
521
+ # Convert SMIRNOFF-style improper into AMBER-style
522
+ mod_imp = (
523
+ smirnoff_imp[1],
524
+ smirnoff_imp[0],
525
+ smirnoff_imp[2],
526
+ smirnoff_imp[3],
527
+ )
528
+ assert mod_imp in top.amber_impropers
529
+
530
+ # test_two_of_same_molecule
531
+ # test_two_different_molecules
532
+ # test_get_molecule
533
+ # test_is_bonded
534
+ # TODO: Test serialization
535
+
536
+ def test_from_openmm(self):
537
+ """Test creation of an OpenFF Topology object from an OpenMM Topology and component molecules"""
538
+ pdbfile = app.PDBFile(get_data_file_path("systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb"))
539
+
540
+ with pytest.raises(MissingUniqueMoleculesError, match="requires a list of Molecule objects"):
541
+ Topology.from_openmm(pdbfile.topology)
542
+
543
+ molecules = [create_ethanol(), create_cyclohexane()]
544
+
545
+ topology = Topology.from_openmm(
546
+ pdbfile.topology,
547
+ unique_molecules=molecules,
548
+ positions=pdbfile.positions,
549
+ )
550
+ assert topology.n_molecules == 239
551
+ assert topology.n_unique_molecules == 2
552
+ assert np.all(topology.get_positions() == from_openmm(pdbfile.positions))
553
+ # Ensure that hierarchy iterators are initialized
554
+ assert all(all([molecule.residues, molecule.chains]) for molecule in topology.molecules)
555
+ for omm_atom, off_atom in zip(pdbfile.topology.atoms(), topology.atoms):
556
+ assert omm_atom.name == off_atom.name
557
+
558
+ def test_from_openmm_virtual_sites(self, opc):
559
+ water = Molecule.from_mapped_smiles("[O:1]([H:2])[H:3]")
560
+
561
+ openmm_topology = opc.create_interchange([water]).to_openmm_topology()
562
+
563
+ with pytest.raises(
564
+ VirtualSitesUnsupportedError,
565
+ match=r"Atom <Atom 3 .*EP.*a virtual site",
566
+ ):
567
+ Topology.from_openmm(
568
+ openmm_topology,
569
+ unique_molecules=[water],
570
+ )
571
+
572
+ def test_from_openmm_missing_reference(self):
573
+ """Test creation of an OpenFF Topology object from an OpenMM Topology when missing a unique molecule"""
574
+ pdbfile = app.PDBFile(get_data_file_path("systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb"))
575
+
576
+ molecules = [create_ethanol()]
577
+ with pytest.raises(ValueError, match="No match found for molecule C6H12"):
578
+ Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
579
+
580
+ def test_from_openmm_missing_conect(self):
581
+ """
582
+ Test creation of an OpenFF Topology object from an OpenMM Topology
583
+ when the origin PDB lacks CONECT records
584
+ """
585
+ pdbfile = app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol_no_conect.pdb"))
586
+
587
+ molecules = []
588
+ molecules.append(Molecule.from_smiles("CCO"))
589
+ with pytest.raises(
590
+ ValueError,
591
+ match=r"No match found for molecule C. This would be a "
592
+ r"very unusual molecule to try and parameterize, "
593
+ r"and it is likely that the data source it was "
594
+ r"read from does not contain connectivity "
595
+ r"information. If this molecule is coming from "
596
+ r"PDB, please ensure that the file contains CONECT "
597
+ r"records.",
598
+ ):
599
+ Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
600
+
601
+ def test_to_from_openmm(self):
602
+ """Test a round-trip OpenFF -> OpenMM -> OpenFF Topology."""
603
+ # Create OpenFF topology with 1 ethanol and 2 benzenes.
604
+ ethanol = Molecule.from_smiles("CCO")
605
+ benzene = Molecule.from_smiles("c1ccccc1")
606
+ off_topology = Topology.from_molecules(molecules=[ethanol, benzene, benzene])
607
+
608
+ # Convert to OpenMM Topology.
609
+ omm_topology = off_topology.to_openmm()
610
+
611
+ # Check that bond orders are preserved.
612
+ n_double_bonds = sum([b.order == 2 for b in omm_topology.bonds()])
613
+ n_aromatic_bonds = sum([b.type is app.Aromatic for b in omm_topology.bonds()])
614
+ assert n_double_bonds == 6
615
+ assert n_aromatic_bonds == 12
616
+
617
+ # Check that there is one residue and chain for each molecule.
618
+ assert omm_topology.getNumResidues() == 3
619
+ assert omm_topology.getNumChains() == 3
620
+
621
+ # Convert back to OpenFF Topology.
622
+ off_topology_copy = Topology.from_openmm(omm_topology, unique_molecules=[ethanol, benzene])
623
+
624
+ # The round-trip OpenFF Topology is identical to the original.
625
+ # The reference molecules are the same.
626
+ assert off_topology.n_molecules == off_topology_copy.n_molecules
627
+ assert off_topology.n_unique_molecules == off_topology_copy.n_unique_molecules
628
+ molecules_copy = list(off_topology_copy.molecules)
629
+ for mol_idx, mol in enumerate(off_topology.molecules):
630
+ assert mol == molecules_copy[mol_idx]
631
+
632
+ # The number of topology molecules is the same.
633
+ assert off_topology.n_molecules == off_topology_copy.n_molecules
634
+
635
+ # Check atoms.
636
+ assert off_topology.n_atoms == off_topology_copy.n_atoms
637
+ for atom_idx, atom in enumerate(off_topology.atoms):
638
+ atom_copy = off_topology_copy.atom(atom_idx)
639
+ assert atom.atomic_number == atom_copy.atomic_number
640
+
641
+ # Check bonds.
642
+ for bond in off_topology.bonds:
643
+ bond_copy = off_topology_copy.get_bond_between(
644
+ off_topology.atom_index(bond.atoms[0]),
645
+ off_topology.atom_index(bond.atoms[1]),
646
+ )
647
+ bond_atoms = [a.atomic_number for a in bond.atoms]
648
+ bond_atoms_copy = [a.atomic_number for a in bond_copy.atoms]
649
+ assert bond_atoms == bond_atoms_copy
650
+ assert bond.bond_order == bond_copy.bond_order
651
+ assert bond.is_aromatic == bond_copy.is_aromatic
652
+
653
+ def test_to_from_openmm_hierarchy_metadata(self):
654
+ """
655
+ Test roundtripping to/from ``OpenEyeToolkitWrapper`` for molecules with PDB hierarchy metadata
656
+ """
657
+ top = topology_with_metadata()
658
+ omm_top = top.to_openmm()
659
+
660
+ # Make a list of the unique molecules in the topology for the return from roundtripping to OpenMM
661
+ unique_mols = []
662
+ for mol in top.molecules:
663
+ if mol.to_smiles() not in [m.to_smiles() for m in unique_mols]:
664
+ unique_mols.append(mol)
665
+
666
+ roundtrip_top = Topology.from_openmm(omm_top, unique_molecules=unique_mols)
667
+
668
+ # Check OMM Atom
669
+ for orig_atom, omm_atom in zip(top.atoms, omm_top.atoms()):
670
+ if "residue_name" in orig_atom.metadata:
671
+ assert orig_atom.metadata["residue_name"] == omm_atom.residue.name
672
+ else:
673
+ assert omm_atom.residue.name == "UNK"
674
+
675
+ if "residue_number" in orig_atom.metadata:
676
+ assert orig_atom.metadata["residue_number"] == int(omm_atom.residue.id)
677
+ else:
678
+ assert omm_atom.residue.id == "0"
679
+
680
+ if "insertion_code" in orig_atom.metadata:
681
+ assert orig_atom.metadata["insertion_code"] == omm_atom.residue.insertionCode
682
+ else:
683
+ assert omm_atom.residue.insertionCode == " "
684
+
685
+ if "chain_id" in orig_atom.metadata:
686
+ assert orig_atom.metadata["chain_id"] == omm_atom.residue.chain.id
687
+ else:
688
+ assert omm_atom.residue.chain.id == "X"
689
+
690
+ # Check roundtripped OFFMol
691
+ for orig_atom, roundtrip_atom in zip(top.atoms, roundtrip_top.atoms):
692
+ if "residue_name" in orig_atom.metadata:
693
+ original = orig_atom.metadata["residue_name"]
694
+ roundtrip = roundtrip_atom.metadata["residue_name"]
695
+ assert original == roundtrip
696
+ else:
697
+ assert roundtrip_atom.metadata["residue_name"] == "UNK"
698
+
699
+ if "residue_number" in orig_atom.metadata:
700
+ original = orig_atom.metadata["residue_number"]
701
+ roundtrip = roundtrip_atom.metadata["residue_number"]
702
+ assert original == roundtrip
703
+ else:
704
+ assert roundtrip_atom.metadata["residue_number"] == "0"
705
+
706
+ if "insertion_code" in orig_atom.metadata:
707
+ original = orig_atom.metadata["insertion_code"]
708
+ roundtrip = roundtrip_atom.metadata["insertion_code"]
709
+ assert original == roundtrip
710
+ else:
711
+ assert roundtrip_atom.metadata["insertion_code"] == " "
712
+
713
+ if "chain_id" in orig_atom.metadata:
714
+ original = orig_atom.metadata["chain_id"]
715
+ roundtrip = roundtrip_atom.metadata["chain_id"]
716
+ assert original == roundtrip
717
+ else:
718
+ assert roundtrip_atom.metadata["chain_id"] == "X"
719
+
720
+ @requires_rdkit
721
+ def test_from_to_openmm_hierarchy_metadata(self):
722
+ """Reproduce issue #1953"""
723
+ import openmm.app
724
+
725
+ openmm_topology = openmm.app.PDBFile(get_data_file_path("proteins/MainChain_ALA_ALA.pdb")).topology
726
+ openff_molecule = Topology.from_pdb(get_data_file_path("proteins/MainChain_ALA_ALA.pdb")).molecule(0)
727
+
728
+ roundtripped = Topology.from_openmm(
729
+ openmm_topology,
730
+ unique_molecules=[openff_molecule],
731
+ ).to_openmm()
732
+
733
+ assert {type(residue.id) for residue in roundtripped.residues()} == {str}, (
734
+ "type mistmatch in residue id in OpenMM residues"
735
+ )
736
+
737
+ @requires_rdkit
738
+ def test_from_pdb(self):
739
+ with pytest.raises(UnassignedChemistryInPDBError) as exc_info:
740
+ Topology.from_pdb(get_data_file_path("proteins/5tbm_complex_solv.pdb"))
741
+ # Make sure that the error message above doesn't contain the "multiple chains" hint
742
+ assert "input has multiple chain identifiers" not in exc_info.value.args[0].join("")
743
+
744
+ ligand = Molecule.from_file(get_data_file_path("molecules/PT2385.sdf"))
745
+ stereoisomer1 = Molecule.from_smiles("[C@H](Cl)(F)/C=C/F")
746
+ stereoisomer2 = Molecule.from_smiles(r"[C@@H](Cl)(F)/C=C\F")
747
+
748
+ top = Topology.from_pdb(
749
+ get_data_file_path("proteins/5tbm_complex_solv.pdb"),
750
+ unique_molecules=[
751
+ ligand,
752
+ Molecule.from_smiles("[H]S[H]"),
753
+ # Unlike bond order and formal charge, the stereo is
754
+ # assigned by 3D geometry, so providing stereoisomer1 should allow
755
+ # us to load stereoisomers 1 and 2 correctly
756
+ stereoisomer1,
757
+ ],
758
+ )
759
+
760
+ assert top.box_vectors is None
761
+
762
+ res_iter = top.hierarchy_iterator("residues")
763
+ assert len([*res_iter]) == 130
764
+ chain_iter = top.hierarchy_iterator("chains")
765
+ assert len([*chain_iter]) == 19
766
+
767
+ assert top.molecule(1).is_isomorphic_with(ligand)
768
+ water = Molecule.from_smiles("O")
769
+ assert top.molecule(2).is_isomorphic_with(water)
770
+ assert top.molecule(3).is_isomorphic_with(water)
771
+ assert top.molecule(4).is_isomorphic_with(water)
772
+ assert top.molecule(5).is_isomorphic_with(water)
773
+
774
+ # Ensure the stereo twins were loaded correctly
775
+ assert top.molecule(6).is_isomorphic_with(stereoisomer1)
776
+ assert not (top.molecule(6).is_isomorphic_with(stereoisomer2))
777
+ assert top.molecule(7).is_isomorphic_with(stereoisomer2)
778
+ assert not (top.molecule(7).is_isomorphic_with(stereoisomer1))
779
+
780
+ # Test loading monoatomic ions added by pdbfixer
781
+ cl_minus = Molecule.from_smiles("[Cl-]")
782
+ assert top.molecule(8).is_isomorphic_with(cl_minus)
783
+ assert top.molecule(9).is_isomorphic_with(cl_minus)
784
+
785
+ na_plus = Molecule.from_smiles("[Na+]")
786
+ assert top.molecule(10).is_isomorphic_with(na_plus)
787
+ assert top.molecule(11).is_isomorphic_with(na_plus)
788
+
789
+ # Test loading monoatomic ions added as SMILES
790
+ assert top.molecule(12).is_isomorphic_with(Molecule.from_smiles("[Li+]"))
791
+ assert top.molecule(13).is_isomorphic_with(Molecule.from_smiles("[K+]"))
792
+ assert top.molecule(14).is_isomorphic_with(Molecule.from_smiles("[Rb+]"))
793
+ assert top.molecule(15).is_isomorphic_with(Molecule.from_smiles("[Cs+]"))
794
+ assert top.molecule(16).is_isomorphic_with(Molecule.from_smiles("[F-]"))
795
+ assert top.molecule(17).is_isomorphic_with(Molecule.from_smiles("[Br-]"))
796
+ assert top.molecule(18).is_isomorphic_with(Molecule.from_smiles("[I-]"))
797
+
798
+ @requires_rdkit
799
+ def test_from_pdb_input_types(self):
800
+ import pathlib
801
+ from io import StringIO
802
+
803
+ import openmm.app
804
+
805
+ protein_path = get_data_file_path("proteins/ace-ala-nh2.pdb")
806
+
807
+ Topology.from_pdb(protein_path)
808
+
809
+ Topology.from_pdb(pathlib.Path(protein_path))
810
+
811
+ with open(protein_path) as f:
812
+ Topology.from_pdb(f)
813
+
814
+ pdb_string = pathlib.Path(protein_path).read_text()
815
+ with StringIO(pdb_string) as f:
816
+ Topology.from_pdb(f)
817
+
818
+ with pytest.raises(ValueError, match=r"Unexpected type.*PDBFile"):
819
+ Topology.from_pdb(openmm.app.PDBFile(protein_path))
820
+
821
+ @requires_rdkit
822
+ def test_from_pdb_two_polymers_metadata(self):
823
+ """Test that a PDB with two capped polymers is loaded correctly"""
824
+ top = Topology.from_pdb(get_data_file_path("proteins/TwoMol_SER_CYS.pdb"))
825
+ assert top.molecule(0).is_isomorphic_with(
826
+ Molecule.from_smiles(
827
+ "[H][O][C]([H])([H])[C@@]([H])([C](=[O])[N]([H])[C]([H])([H])[H])[N]([H])[C](=[O])[C]([H])([H])[H]"
828
+ )
829
+ )
830
+ assert top.molecule(1).is_isomorphic_with(
831
+ Molecule.from_smiles(
832
+ "[H][S][C]([H])([H])[C@@]([H])([C](=[O])[N]([H])[C]([H])([H])[H])[N]([H])[C](=[O])[C]([H])([H])[H]"
833
+ )
834
+ )
835
+
836
+ expected_residues = (
837
+ (6, ("A", "1", " ", "ACE")),
838
+ (11, ("A", "2", " ", "SER")),
839
+ (6, ("A", "3", " ", "NME")),
840
+ (6, ("B", "1", " ", "ACE")),
841
+ (11, ("B", "2", " ", "CYS")),
842
+ (6, ("B", "3", " ", "NME")),
843
+ )
844
+ res_iter = top.hierarchy_iterator("residues")
845
+ for (n_atoms, identifier), residue in zip(expected_residues, res_iter):
846
+ assert residue.n_atoms == n_atoms
847
+ assert residue.identifier == identifier
848
+
849
+ assert ((abs(top.box_vectors - (np.eye(3, 3) * 48 * unit.angstrom)) / unit.angstrom) < 1e-10).all()
850
+
851
+ @requires_rdkit
852
+ def test_from_pdb_overlapping_unique_mols(self):
853
+ """Test that even overlapping unique molecules can be loaded using from_pdb"""
854
+ po4 = Molecule.from_smiles("P(=O)([O-])([O-])([O-])")
855
+ phenylphosphate = Molecule.from_smiles("c1ccccc1OP(=O)([O-1])([O-1])")
856
+
857
+ # Load the topology with po4 listed as the first unique mol
858
+ top1 = Topology.from_pdb(
859
+ get_data_file_path("molecules/po4_phenylphosphate.pdb"),
860
+ unique_molecules=[po4, phenylphosphate],
861
+ )
862
+ assert po4.is_isomorphic_with(top1.molecule(0))
863
+ assert phenylphosphate.is_isomorphic_with(top1.molecule(1))
864
+
865
+ # Load the topology with phenylphosphate listed as the first unique mol
866
+ top2 = Topology.from_pdb(
867
+ get_data_file_path("molecules/po4_phenylphosphate.pdb"),
868
+ unique_molecules=[phenylphosphate, po4],
869
+ )
870
+ assert po4.is_isomorphic_with(top2.molecule(0))
871
+ assert phenylphosphate.is_isomorphic_with(top2.molecule(1))
872
+
873
+ @requires_rdkit
874
+ def test_from_pdb_unique_mol_ammonium(self):
875
+ """
876
+ Test that Topology.from_pdb can load ammonium unique mol.
877
+ See https://github.com/openforcefield/openff-toolkit/issues/2051
878
+ """
879
+ nh4 = Molecule.from_smiles("[NH4+]")
880
+ offtop = Topology.from_pdb(get_data_file_path("molecules/nh4.pdb"), unique_molecules=[nh4])
881
+ assert nh4.is_isomorphic_with(offtop.molecule(0))
882
+
883
+ @requires_rdkit
884
+ def test_from_pdb_additional_substructures(self):
885
+ """Test that the _additional_substructures arg is wired up correctly"""
886
+ with pytest.raises(UnassignedChemistryInPDBError):
887
+ Topology.from_pdb(get_data_file_path("proteins/ace-ZZZ-gly-nme.pdb"))
888
+
889
+ # Make unnatural AA
890
+ # TODO: Should this be able to support defined stereo?
891
+ mol = Molecule.from_smiles("N[CH]([CH](C)O[P@](=O)(OCNCO)[O-])C(=O)", allow_undefined_stereo=True)
892
+ # Get the indices of an N term and C term hydrogen for removal
893
+ leaving_atoms = mol.chemical_environment_matches("[H:1]N([H])CC(=O)[H:2]")[0]
894
+
895
+ # Label the atoms with whether they're leaving
896
+ for atom in mol.atoms:
897
+ if atom.molecule_atom_index not in leaving_atoms:
898
+ atom.metadata["substructure_atom"] = True
899
+ else:
900
+ atom.metadata["substructure_atom"] = False
901
+
902
+ top = Topology.from_pdb(
903
+ get_data_file_path("proteins/ace-ZZZ-gly-nme.pdb"),
904
+ _additional_substructures=[mol],
905
+ )
906
+
907
+ expected_mol = Molecule.from_file(get_data_file_path("proteins/ace-ZZZ-gly-nme.sdf"))
908
+ assert top.molecule(0).is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
909
+
910
+ @requires_rdkit
911
+ def test_from_pdb_molecule_atom_ordering_noncontiguous(self):
912
+ """
913
+ Test that from_pdb correctly raises an error when the PDB atom ordering has atoms
914
+ in the same molecule on noncontiguous lines.
915
+ See https://github.com/openforcefield/openff-toolkit/issues/2093
916
+ """
917
+ with pytest.raises(
918
+ PDBMoleculeHasNoncontiguousAtomIndicesError, match="Atom indices 23 and 48 are in molecule 0"
919
+ ):
920
+ Topology.from_pdb(get_data_file_path("proteins/split_chain.pdb"))
921
+
922
+ # Ensure that following the prior error message's advice and naively reordering the PDB lines works
923
+ top = Topology.from_pdb(get_data_file_path("proteins/split_chain_reordered.pdb"))
924
+
925
+ # Check for sanity by ensuring that no bonds have unreasonable geometry
926
+ for mol in top.molecules:
927
+ for bond in mol.bonds:
928
+ length = np.linalg.norm(mol.conformers[0][bond.atom1_index] - mol.conformers[0][bond.atom2_index])
929
+ assert 0.4 < length.m_as(unit.angstrom) < 2.5
930
+
931
+ @requires_pkg("mdtraj")
932
+ def test_from_mdtraj(self):
933
+ """Test construction of an OpenFF Topology from an MDTraj Topology object"""
934
+ import mdtraj as md
935
+
936
+ pdb_path = get_data_file_path("systems/test_systems/1_cyclohexane_1_ethanol.pdb")
937
+ trj = md.load(pdb_path)
938
+
939
+ with pytest.raises(MissingUniqueMoleculesError, match="requires a list of Molecule objects"):
940
+ Topology.from_mdtraj(trj.top)
941
+
942
+ unique_molecules = [Molecule.from_smiles(mol_name) for mol_name in ["C1CCCCC1", "CCO"]]
943
+ top = Topology.from_mdtraj(trj.top, unique_molecules=unique_molecules)
944
+
945
+ assert top.n_molecules == 2
946
+ assert top.n_bonds == 26
947
+
948
+ @requires_rdkit
949
+ def test_to_file_units_check(self):
950
+ """
951
+ Checks that writing a PDB file with different coordinate representations results in the same output.
952
+ - Angstrom "openff units" (default behavior if using Molecule.conformers[0])
953
+ - nanometer "openff units"
954
+ - unitless NumPy array
955
+ - converted OpenMM quantity
956
+ """
957
+ from tempfile import NamedTemporaryFile
958
+
959
+ from openff.units.openmm import to_openmm
960
+
961
+ from openff.toolkit.topology import Molecule, Topology
962
+
963
+ topology = Topology()
964
+ mol = Molecule.from_pdb_and_smiles(get_data_file_path("systems/test_systems/1_ethanol.pdb"), "CCO")
965
+ topology.add_molecule(mol)
966
+ positions_angstrom = mol.conformers[0]
967
+
968
+ def _check_file(topology, coordinates):
969
+ # Write the molecule to PDB and ensure that the X coordinate of the first atom is 10.172
970
+ count = 1
971
+ with NamedTemporaryFile(suffix=".pdb") as iofile:
972
+ topology.to_file(iofile.name, coordinates)
973
+ data = open(iofile.name).readlines()
974
+ for line in data:
975
+ if line.startswith("HETATM") and count == 1:
976
+ count = count + 1
977
+ coord = line.split()[-6]
978
+ assert coord == "10.172"
979
+
980
+ _check_file(topology, coordinates=positions_angstrom)
981
+ _check_file(topology, coordinates=positions_angstrom.to(unit.nanometer))
982
+ _check_file(topology, coordinates=positions_angstrom.m)
983
+ _check_file(topology, coordinates=to_openmm(positions_angstrom))
984
+
985
+ with pytest.raises(ValueError, match=r"Could not process.*list.*"):
986
+ _check_file(topology, coordinates=positions_angstrom.m.tolist())
987
+
988
+ @requires_rdkit
989
+ def test_to_file_fileformat_lettercase(self):
990
+ """
991
+ Checks if fileformat specifier is indpendent of upper/lowercase
992
+ """
993
+ from tempfile import NamedTemporaryFile
994
+
995
+ from openff.toolkit.topology import Molecule, Topology
996
+
997
+ topology = Topology()
998
+ mol = Molecule.from_pdb_and_smiles(get_data_file_path("systems/test_systems/1_ethanol.pdb"), "CCO")
999
+ topology.add_molecule(mol)
1000
+ positions = mol.conformers[0]
1001
+ count = 1
1002
+ with NamedTemporaryFile(suffix=".pdb") as iofile:
1003
+ topology.to_file(iofile.name, positions, file_format="pDb")
1004
+ data = open(iofile.name).readlines()
1005
+ for line in data:
1006
+ if line.startswith("HETATM") and count == 1:
1007
+ count = count + 1
1008
+ coord = line.split()[-6]
1009
+ assert coord == "10.172"
1010
+
1011
+ @requires_rdkit
1012
+ def test_to_file_fileformat_invalid(self):
1013
+ """
1014
+ Checks for invalid file format
1015
+ """
1016
+ from openff.toolkit.topology import Molecule, Topology
1017
+
1018
+ topology = Topology()
1019
+ mol = Molecule.from_pdb_and_smiles(get_data_file_path("systems/test_systems/1_ethanol.pdb"), "CCO")
1020
+ topology.add_molecule(mol)
1021
+ positions = mol.conformers[0]
1022
+ fname = "ethanol_file.pdb"
1023
+ with pytest.raises(NotImplementedError):
1024
+ topology.to_file(fname, positions, file_format="AbC")
1025
+
1026
+ def test_to_file_no_molecules(self):
1027
+ """
1028
+ Checks if Topology.to_file() writes a file with no topology and no coordinates
1029
+ """
1030
+ from tempfile import NamedTemporaryFile
1031
+
1032
+ from openff.toolkit.topology import Topology
1033
+
1034
+ topology = Topology()
1035
+ lines = []
1036
+ with NamedTemporaryFile(suffix=".pdb") as iofile:
1037
+ topology.to_file(iofile.name, [] * unit.nanometer)
1038
+ data = open(iofile.name).readlines()
1039
+ for line in data:
1040
+ lines.append(line.split())
1041
+ assert lines[1] == ["END"]
1042
+
1043
+ @requires_rdkit
1044
+ def test_to_file_multi_molecule_different_order(self):
1045
+ """
1046
+ Checks for the following if Topology.to_write maintains the order of atoms
1047
+ for the same molecule with different indexing
1048
+ """
1049
+ from tempfile import NamedTemporaryFile
1050
+
1051
+ from openff.toolkit.topology import Molecule, Topology
1052
+
1053
+ topology = Topology()
1054
+ topology.add_molecule(create_ethanol())
1055
+ topology.add_molecule(create_reversed_ethanol())
1056
+ mol = Molecule.from_pdb_and_smiles(get_data_file_path("systems/test_systems/1_ethanol.pdb"), "CCO")
1057
+ positions = mol.conformers[0]
1058
+ # Make up coordinates for the second ethanol by translating the first by 10 angstroms (note that this will
1059
+ # still be a gibberish conformation, since the atom order in the second molecule is different)
1060
+ positions = np.concatenate([positions, positions + 10.0 * unit.angstrom])
1061
+ element_order = []
1062
+
1063
+ with NamedTemporaryFile(suffix=".pdb") as iofile:
1064
+ topology.to_file(iofile.name, positions)
1065
+ data = open(iofile.name).readlines()
1066
+ for line in data:
1067
+ if line.startswith("HETATM"):
1068
+ element_order.append(line.strip()[-1])
1069
+ assert element_order == [
1070
+ "C",
1071
+ "C",
1072
+ "O",
1073
+ "H",
1074
+ "H",
1075
+ "H",
1076
+ "H",
1077
+ "H",
1078
+ "H",
1079
+ "H",
1080
+ "H",
1081
+ "H",
1082
+ "H",
1083
+ "H",
1084
+ "H",
1085
+ "O",
1086
+ "C",
1087
+ "C",
1088
+ ]
1089
+
1090
+ @requires_rdkit
1091
+ def test_to_file_object(self):
1092
+ """
1093
+ Checks that a file-like object can be written to (vs a path or str)
1094
+ """
1095
+ from io import StringIO
1096
+ from tempfile import NamedTemporaryFile
1097
+
1098
+ from openff.toolkit.topology import Molecule, Topology
1099
+
1100
+ topology = Topology()
1101
+ mol = Molecule.from_pdb_and_smiles(get_data_file_path("systems/test_systems/1_ethanol.pdb"), "CCO")
1102
+ topology.add_molecule(mol)
1103
+ positions = mol.conformers[0]
1104
+
1105
+ # Check a file-like wrapper around a str
1106
+ with StringIO() as iofile:
1107
+ topology.to_file(iofile, positions)
1108
+ data1 = [line + "\n" for line in iofile.getvalue().splitlines()]
1109
+
1110
+ # Check an actual real file object
1111
+ with NamedTemporaryFile(mode="w+", suffix=".pdb") as iofile:
1112
+ topology.to_file(iofile, positions)
1113
+ iofile.seek(0)
1114
+ data2 = iofile.readlines()
1115
+
1116
+ # Do it the old fashioned way for comparison
1117
+ with NamedTemporaryFile(mode="w+", suffix=".pdb") as iofile:
1118
+ topology.to_file(iofile.name, positions)
1119
+ data3 = iofile.readlines()
1120
+
1121
+ assert data1 == data3
1122
+ assert data2 == data3
1123
+
1124
+ @requires_rdkit
1125
+ def test_to_file_automatic_positions(self):
1126
+ """
1127
+ Checks that to_file can take positions from the topology
1128
+ """
1129
+ from io import StringIO
1130
+
1131
+ from openff.toolkit.topology import Molecule, Topology
1132
+
1133
+ topology = Topology()
1134
+ mol = Molecule.from_pdb_and_smiles(get_data_file_path("systems/test_systems/1_ethanol.pdb"), "CCO")
1135
+ topology.add_molecule(mol)
1136
+
1137
+ count = 1
1138
+ with StringIO() as iofile:
1139
+ topology.to_file(iofile)
1140
+ data = iofile.getvalue().splitlines()
1141
+ for line in data:
1142
+ if line.startswith("HETATM") and count == 1:
1143
+ count = count + 1
1144
+ coord = line.split()[-6]
1145
+ assert coord == "10.172"
1146
+
1147
+ def test_to_file_ensure_uniqueness_true(self):
1148
+ """
1149
+ Checks that ensure_unique_atom_names=True provides per-molecule unique atom names
1150
+ """
1151
+ from io import StringIO
1152
+
1153
+ from openff.toolkit.topology import Molecule, Topology
1154
+
1155
+ mol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA_ALA.pdb"))
1156
+ topology = Topology.from_molecules([mol])
1157
+
1158
+ with StringIO() as iofile:
1159
+ topology.to_file(iofile, ensure_unique_atom_names=True)
1160
+ data = iofile.getvalue().splitlines()
1161
+
1162
+ atom_names = []
1163
+ for line in data:
1164
+ if line.startswith("ATOM") or line.startswith("HETATM"):
1165
+ atom_name = line[12:16].strip()
1166
+ atom_names.append(atom_name)
1167
+ assert len(atom_names) == len(set(atom_names))
1168
+
1169
+ def test_to_file_ensure_uniqueness_false(self):
1170
+ """
1171
+ Checks that ensure_unique_atom_names=False preserves atom names
1172
+ """
1173
+ from io import StringIO
1174
+
1175
+ from openff.toolkit.topology import Molecule, Topology
1176
+
1177
+ mol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA_ALA.pdb"))
1178
+ topology = Topology.from_molecules([mol])
1179
+ atom_names = set([atom.name for atom in topology.atoms])
1180
+ assert None not in atom_names, "All input atoms must be named"
1181
+
1182
+ with StringIO() as iofile:
1183
+ topology.to_file(iofile, ensure_unique_atom_names=False)
1184
+ data = iofile.getvalue().splitlines()
1185
+
1186
+ for line in data:
1187
+ if line.startswith("ATOM") or line.startswith("HETATM"):
1188
+ atom_name = line[12:16].strip()
1189
+ assert atom_name in atom_names
1190
+
1191
+ def test_to_file_ensure_uniqueness_residues(self):
1192
+ """
1193
+ Checks that ensure_unique_atom_names="residues" provides per-residue unique atom names
1194
+ """
1195
+ from io import StringIO
1196
+
1197
+ from openff.toolkit.topology import Molecule, Topology
1198
+
1199
+ mol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA_ALA.pdb"))
1200
+ topology = Topology.from_molecules([mol])
1201
+
1202
+ with StringIO() as iofile:
1203
+ topology.to_file(iofile, ensure_unique_atom_names="residues")
1204
+ data = iofile.getvalue().splitlines()
1205
+
1206
+ from collections import defaultdict
1207
+
1208
+ residues = defaultdict(list)
1209
+ for line in data:
1210
+ if line.startswith("ATOM") or line.startswith("HETATM"):
1211
+ atom_name = line[12:16].strip()
1212
+ res_name = line[17:20].strip()
1213
+ res_number = line[22:26].strip()
1214
+ res_icode = line[26].strip()
1215
+ residues[(res_name, res_number, res_icode)].append(atom_name)
1216
+
1217
+ for residue_atom_names in residues.values():
1218
+ assert len(residue_atom_names) == len(set(residue_atom_names))
1219
+
1220
+ @requires_openeye
1221
+ def test_from_openmm_duplicate_unique_mol(self):
1222
+ """
1223
+ Check that a DuplicateUniqueMoleculeError is raised if we try to pass in two indistinguishably unique mols
1224
+ """
1225
+ pdbfile = app.PDBFile(get_data_file_path("systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb"))
1226
+ molecules = [
1227
+ Molecule.from_file(get_data_file_path(name))
1228
+ for name in (
1229
+ "molecules/ethanol.mol2",
1230
+ "molecules/ethanol_reordered.mol2",
1231
+ "molecules/cyclohexane.mol2",
1232
+ )
1233
+ ]
1234
+ with pytest.raises(DuplicateUniqueMoleculeError):
1235
+ Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
1236
+
1237
+ @pytest.mark.skip
1238
+ def test_from_openmm_distinguish_using_stereochemistry(self):
1239
+ """Test creation of an OpenFF Topology object from an OpenMM topology with stereoisomers"""
1240
+ # From Jeff: The graph representation created from OMM molecules during the matching
1241
+ # process doesn't encode stereochemistry.
1242
+ raise NotImplementedError
1243
+
1244
+ @pytest.mark.parametrize("ensure_unique_atom_names", [True, "residues", "chains"])
1245
+ def test_to_openmm_assign_unique_atom_names(self, ensure_unique_atom_names):
1246
+ """
1247
+ Ensure that OFF topologies with no pre-existing atom names have unique
1248
+ atom names applied when being converted to openmm
1249
+ """
1250
+ # Create OpenFF topology with 1 ethanol and 2 benzenes.
1251
+ ethanol = Molecule.from_smiles("CCO")
1252
+ benzene = Molecule.from_smiles("c1ccccc1")
1253
+ off_topology = Topology.from_molecules(molecules=[ethanol, benzene, benzene])
1254
+
1255
+ # This test uses molecules with no hierarchy schemes, so the parametrized
1256
+ # ensure_unique_atom_names values should behave identically.
1257
+ assert not any([mol._hierarchy_schemes for mol in off_topology.molecules]), "Test assumes no hierarchy schemes"
1258
+
1259
+ omm_topology = off_topology.to_openmm(ensure_unique_atom_names=ensure_unique_atom_names)
1260
+ atom_names = set()
1261
+ for atom in omm_topology.atoms():
1262
+ atom_names.add(atom.name)
1263
+ # There should be 6 unique Cs, 6 unique Hs, and 1 unique O, for a total of 13 unique atom names
1264
+ assert len(atom_names) == 13
1265
+
1266
+ @pytest.mark.parametrize("ensure_unique_atom_names", [True, "residues", "chains"])
1267
+ def test_to_openmm_assign_some_unique_atom_names(self, ensure_unique_atom_names):
1268
+ """
1269
+ Ensure that OFF topologies with some pre-existing atom names have unique
1270
+ atom names applied to the other atoms when being converted to openmm
1271
+ """
1272
+ # Create OpenFF topology with 1 ethanol and 2 benzenes.
1273
+ ethanol = Molecule.from_smiles("CCO")
1274
+ for atom in ethanol.atoms:
1275
+ atom.name = f"AT{atom.molecule_atom_index}"
1276
+ benzene = Molecule.from_smiles("c1ccccc1")
1277
+ off_topology = Topology.from_molecules(molecules=[ethanol, benzene, benzene])
1278
+
1279
+ # This test uses molecules with no hierarchy schemes, so the parametrized
1280
+ # ensure_unique_atom_names values should behave identically.
1281
+ assert not any([mol._hierarchy_schemes for mol in off_topology.molecules]), "Test assumes no hierarchy schemes"
1282
+
1283
+ omm_topology = off_topology.to_openmm(ensure_unique_atom_names=ensure_unique_atom_names)
1284
+ atom_names = set()
1285
+ for atom in omm_topology.atoms():
1286
+ atom_names.add(atom.name)
1287
+ # There should be 9 "ATOM#"-labeled atoms, 6 unique Cs, and 6 unique Hs,
1288
+ # for a total of 21 unique atom names
1289
+ assert len(atom_names) == 21
1290
+
1291
+ @pytest.mark.parametrize("ensure_unique_atom_names", [True, "residues", "chains"])
1292
+ def test_to_openmm_assign_unique_atom_names_some_duplicates(self, ensure_unique_atom_names):
1293
+ """
1294
+ Ensure that OFF topologies where some molecules have invalid/duplicate
1295
+ atom names have unique atom names applied while the other molecules are unaffected.
1296
+ """
1297
+ # Create OpenFF topology with 1 ethanol and 2 benzenes.
1298
+ ethanol = Molecule.from_smiles("CCO")
1299
+
1300
+ # Assign duplicate atom names in ethanol (two AT0s)
1301
+ ethanol_atom_names_with_duplicates = [f"AT{i}" for i in range(ethanol.n_atoms)]
1302
+ ethanol_atom_names_with_duplicates[1] = "AT0"
1303
+ for atom, atom_name in zip(ethanol.atoms, ethanol_atom_names_with_duplicates):
1304
+ atom.name = atom_name
1305
+
1306
+ # Assign unique atom names in benzene
1307
+ benzene = Molecule.from_smiles("c1ccccc1")
1308
+ benzene_atom_names = [f"AT{i}" for i in range(benzene.n_atoms)]
1309
+ for atom, atom_name in zip(benzene.atoms, benzene_atom_names):
1310
+ atom.name = atom_name
1311
+
1312
+ off_topology = Topology.from_molecules(molecules=[ethanol, benzene, benzene])
1313
+
1314
+ # This test uses molecules with no hierarchy schemes, so the parametrized
1315
+ # ensure_unique_atom_names values should behave identically.
1316
+ assert not any([mol._hierarchy_schemes for mol in off_topology.molecules]), "Test assumes no hierarchy schemes"
1317
+
1318
+ omm_topology = off_topology.to_openmm(ensure_unique_atom_names=ensure_unique_atom_names)
1319
+ atom_names = set()
1320
+ for atom in omm_topology.atoms():
1321
+ atom_names.add(atom.name)
1322
+
1323
+ # There should be 12 "AT#"-labeled atoms (from benzene), 2 unique Cs,
1324
+ # 1 unique O, and 6 unique Hs, for a total of 21 unique atom names
1325
+ assert len(atom_names) == 21
1326
+
1327
+ def test_to_openmm_do_not_assign_unique_atom_names(self):
1328
+ """
1329
+ Test disabling unique atom name assignment in Topology.to_openmm
1330
+ """
1331
+ # Create OpenFF topology with 1 ethanol and 2 benzenes.
1332
+ ethanol = Molecule.from_smiles("CCO")
1333
+ for atom in ethanol.atoms:
1334
+ atom.name = "eth_test"
1335
+ benzene = Molecule.from_smiles("c1ccccc1")
1336
+ benzene.atoms[0].name = "bzn_test"
1337
+ off_topology = Topology.from_molecules(molecules=[ethanol, benzene, benzene])
1338
+ omm_topology = off_topology.to_openmm(ensure_unique_atom_names=False)
1339
+ atom_names = set()
1340
+ for atom in omm_topology.atoms():
1341
+ atom_names.add(atom.name)
1342
+ # There should be 9 atom named "eth_test", 1 atom named "bzn_test",
1343
+ # and 12 atoms named "", for a total of 3 unique atom names
1344
+ assert len(atom_names) == 3
1345
+
1346
+ @pytest.mark.parametrize("explicit_arg", [True, False])
1347
+ def test_to_openmm_preserve_per_residue_unique_atom_names(self, explicit_arg):
1348
+ """
1349
+ Test that to_openmm preserves atom names that are unique per-residue by default
1350
+ """
1351
+ # Create a topology from a capped dialanine
1352
+ peptide = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA_ALA.pdb"))
1353
+ off_topology = Topology.from_molecules([peptide])
1354
+
1355
+ # Assert the test's assumptions
1356
+ _ace, ala1, ala2, _nme = off_topology.hierarchy_iterator("residues")
1357
+ assert [a.name for a in ala1.atoms] == [a.name for a in ala2.atoms], (
1358
+ "Test assumes both alanines have same atom names"
1359
+ )
1360
+
1361
+ for res in off_topology.hierarchy_iterator("residues"):
1362
+ res_atomnames = [atom.name for atom in res.atoms]
1363
+ assert len(set(res_atomnames)) == len(res_atomnames), (
1364
+ f"Test assumes atom names are already unique per-residue in {res}"
1365
+ )
1366
+
1367
+ # Record the initial atom names
1368
+ init_atomnames = [str(atom.name) for atom in off_topology.atoms]
1369
+
1370
+ # Perform the test
1371
+ if explicit_arg:
1372
+ omm_topology = off_topology.to_openmm(ensure_unique_atom_names="residues")
1373
+ else:
1374
+ omm_topology = off_topology.to_openmm()
1375
+
1376
+ # Check that the atom names were preserved
1377
+ final_atomnames = [str(atom.name) for atom in omm_topology.atoms()]
1378
+ assert final_atomnames == init_atomnames
1379
+
1380
+ @pytest.mark.parametrize("explicit_arg", [True, False])
1381
+ def test_to_openmm_generate_per_residue_unique_atom_names(self, explicit_arg):
1382
+ """
1383
+ Test that to_openmm preserves atom names that are unique per-residue by default
1384
+ """
1385
+ # Create a topology from a capped dialanine
1386
+ peptide = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA_ALA.pdb"))
1387
+ off_topology = Topology.from_molecules([peptide])
1388
+
1389
+ # Remove atom names from some residues, make others have duplicate atom names
1390
+ ace, ala1, ala2, nme = off_topology.hierarchy_iterator("residues")
1391
+ for atom in ace.atoms:
1392
+ atom._name = None
1393
+ for atom in ala1.atoms:
1394
+ atom.name = ""
1395
+ for atom in ala2.atoms:
1396
+ atom.name = "ATX2"
1397
+ for atom in nme.atoms:
1398
+ if atom.name == "H2":
1399
+ atom.name = "H1"
1400
+ break
1401
+
1402
+ # Assert assumptions
1403
+ for res in off_topology.hierarchy_iterator("residues"):
1404
+ res_atomnames = [atom.name for atom in res.atoms]
1405
+ assert len(set(res_atomnames)) != len(res_atomnames), (
1406
+ f"Test assumes atom names are not unique per-residue in {res}"
1407
+ )
1408
+ assert off_topology.n_atoms == 32, "Test assumes topology has 32 atoms"
1409
+
1410
+ # Perform the test
1411
+ if explicit_arg:
1412
+ omm_topology = off_topology.to_openmm(ensure_unique_atom_names="residues")
1413
+ else:
1414
+ omm_topology = off_topology.to_openmm()
1415
+
1416
+ # Check that the atom names are now unique per-residue but not per-molecule
1417
+ for res in omm_topology.residues():
1418
+ res_atomnames = [atom.name for atom in res.atoms()]
1419
+ assert len(set(res_atomnames)) == len(res_atomnames), f"Final atom names are not unique in residue {res}"
1420
+
1421
+ atom_names = set()
1422
+ for atom in omm_topology.atoms():
1423
+ atom_names.add(atom.name)
1424
+ assert len(atom_names) < 32, "There should be duplicate atom names in this output topology"
1425
+
1426
+ @pytest.mark.parametrize("ensure_unique_atom_names", ["chains", True])
1427
+ def test_to_openmm_generate_per_molecule_unique_atom_names_with_residues(self, ensure_unique_atom_names):
1428
+ """
1429
+ Test that to_openmm preserves atom names that are unique per-residue by default
1430
+ """
1431
+ # Create a topology from a capped dialanine
1432
+ peptide = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA_ALA.pdb"))
1433
+ off_topology = Topology.from_molecules([peptide])
1434
+
1435
+ # Remove atom names from some residues, make others have duplicate atom names
1436
+ ace, ala1, ala2, nme = off_topology.hierarchy_iterator("residues")
1437
+ for atom in ace.atoms:
1438
+ atom._name = None
1439
+ for atom in ala1.atoms:
1440
+ atom.name = ""
1441
+ for atom in ala2.atoms:
1442
+ atom.name = "ATX2"
1443
+ for atom in nme.atoms:
1444
+ if atom.name == "H2":
1445
+ atom.name = "H1"
1446
+ break
1447
+
1448
+ # Assert assumptions
1449
+ for res in off_topology.hierarchy_iterator("residues"):
1450
+ res_atomnames = [atom.name for atom in res.atoms]
1451
+ assert len(set(res_atomnames)) != len(res_atomnames), (
1452
+ f"Test assumes atom names are not unique per-residue in {res}"
1453
+ )
1454
+ assert off_topology.n_atoms == 32, "Test assumes topology has 32 atoms"
1455
+
1456
+ # Perform the test
1457
+ omm_topology = off_topology.to_openmm(ensure_unique_atom_names=ensure_unique_atom_names)
1458
+
1459
+ # Check that the atom names are now unique across the topology (of 1 molecule)
1460
+ atom_names = set()
1461
+ for atom in omm_topology.atoms():
1462
+ atom_names.add(atom.name)
1463
+ assert len(atom_names) == 32, "There should not be duplicate atom names in this output topology"
1464
+
1465
+ @pytest.mark.parametrize("ensure_unique_atom_names", [True, "residues", "chains", False])
1466
+ def test_to_openmm_copies_molecules(self, ensure_unique_atom_names):
1467
+ """
1468
+ Check that generating new atom names doesn't affect the input topology
1469
+ """
1470
+ # Create OpenFF topology with 1 ethanol and 2 benzenes.
1471
+ ethanol = Molecule.from_smiles("CCO")
1472
+ for atom in ethanol.atoms:
1473
+ atom.name = f"AT{atom.molecule_atom_index}"
1474
+ benzene = Molecule.from_smiles("c1ccccc1")
1475
+ off_topology = Topology.from_molecules(molecules=[ethanol, benzene, benzene])
1476
+ # Record the initial atom names to compare to later
1477
+ init_atomnames = [str(atom.name) for atom in off_topology.atoms]
1478
+
1479
+ # This test uses molecules with no hierarchy schemes, so the parametrized
1480
+ # ensure_unique_atom_names values should behave identically (except False).
1481
+ assert not any([mol._hierarchy_schemes for mol in off_topology.molecules]), "Test assumes no hierarchy schemes"
1482
+
1483
+ omm_topology = off_topology.to_openmm(ensure_unique_atom_names=ensure_unique_atom_names)
1484
+
1485
+ # Get the atom names back from the initial molecules after calling to_openmm
1486
+ final_atomnames_mols = [atom.name for atom in [*ethanol.atoms, *benzene.atoms, *benzene.atoms]]
1487
+ # Get the atom names back from the initial topology after calling to_openmm
1488
+ final_atomnames_offtop = [atom.name for atom in off_topology.atoms]
1489
+ # Get the atom names back from the new OpenMM topology
1490
+ final_atomnames_ommtop = [atom.name for atom in omm_topology.atoms()]
1491
+
1492
+ # Check the appropriate properties!
1493
+ assert init_atomnames == final_atomnames_mols, "Molecules' atom names were changed"
1494
+ assert init_atomnames == final_atomnames_offtop, "Topology's atom names were changed"
1495
+ if ensure_unique_atom_names:
1496
+ assert init_atomnames != final_atomnames_ommtop, "New atom names should've been generated but weren't"
1497
+
1498
+ def test_group_chemically_identical_molecules(self):
1499
+ """Test behavior and caching of Topology.group_chemically_identical_molecules"""
1500
+ top = Topology()
1501
+
1502
+ # Test for correct behavior with empty topology
1503
+ assert top._identify_chemically_identical_molecules() == {}
1504
+
1505
+ # Test for correct behavior with topology of one ethanol
1506
+ top.add_molecule(create_ethanol())
1507
+ groupings = top.identical_molecule_groups
1508
+
1509
+ def assert_first_ethanol_is_grouped_correctly(groupings):
1510
+ assert groupings[0][0] == (0, {i: i for i in range(9)})
1511
+
1512
+ assert_first_ethanol_is_grouped_correctly(groupings)
1513
+
1514
+ # Add an ethanol in reversed order
1515
+ top.add_molecule(create_reversed_ethanol())
1516
+ groupings = top.identical_molecule_groups
1517
+
1518
+ def assert_reversed_ethanol_is_grouped_correctly(groupings):
1519
+ # Ensure that the second ethanol knows it's the same chemical species as the first ethanol
1520
+ assert groupings[0][1][0] == 1
1521
+ # Ensure that the second ethanol has the heavy atoms reversed
1522
+ assert groupings[0][1][1][0] == 8 # C
1523
+ assert groupings[0][1][1][1] == 7 # C
1524
+ assert groupings[0][1][1][2] == 6 # O
1525
+ # (we only check the hydroxyl H, since the other Hs have multiple valid matches)
1526
+ assert groupings[0][1][1][8] == 0 # HO
1527
+
1528
+ assert_first_ethanol_is_grouped_correctly(groupings)
1529
+ assert_reversed_ethanol_is_grouped_correctly(groupings)
1530
+
1531
+ # Add a cyclohexane, which should be unique from all the other molecules
1532
+ top.add_molecule(create_cyclohexane())
1533
+
1534
+ def assert_cyclohexane_is_grouped_correctly(groupings):
1535
+ assert len(groupings[2]) == 1
1536
+ assert groupings[2][0] == (2, {i: i for i in range(18)})
1537
+
1538
+ groupings = top.identical_molecule_groups
1539
+ assert_first_ethanol_is_grouped_correctly(groupings)
1540
+ assert_reversed_ethanol_is_grouped_correctly(groupings)
1541
+ assert_cyclohexane_is_grouped_correctly(groupings)
1542
+
1543
+ # Add a third ethanol, in the same order as the first
1544
+ top.add_molecule(create_ethanol())
1545
+
1546
+ def assert_last_ethanol_is_grouped_correctly(groupings):
1547
+ # Ensure that the last ethanol knows it's the same chemical species as the first ethanol
1548
+ assert groupings[0][2][0] == 3
1549
+ # Ensure that the second ethanol has the heavy atoms matched correctly
1550
+ assert groupings[0][2][1][0] == 0
1551
+ assert groupings[0][2][1][1] == 1
1552
+ assert groupings[0][2][1][2] == 2
1553
+ # Ensure that the second ethanol has the hydroxyl hydrogen matched correctly
1554
+ assert groupings[0][2][1][8] == 8
1555
+
1556
+ groupings = top.identical_molecule_groups
1557
+ assert_first_ethanol_is_grouped_correctly(groupings)
1558
+ assert_reversed_ethanol_is_grouped_correctly(groupings)
1559
+ assert_cyclohexane_is_grouped_correctly(groupings)
1560
+ assert_last_ethanol_is_grouped_correctly(groupings)
1561
+
1562
+ def test_identical_molecule_groups_mixed_topology(self, mixed_topology):
1563
+ assert len(mixed_topology.identical_molecule_groups) == 2
1564
+
1565
+ @requires_openeye
1566
+ def test_chemical_environments_matches_OE(self):
1567
+ """Test Topology.chemical_environment_matches"""
1568
+ toolkit_wrapper = OpenEyeToolkitWrapper()
1569
+ pdbfile = app.PDBFile(get_data_file_path("systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb"))
1570
+ # toolkit_wrapper = RDKitToolkitWrapper()
1571
+ molecules = [
1572
+ Molecule.from_file(get_data_file_path(name))
1573
+ for name in ("molecules/ethanol.mol2", "molecules/cyclohexane.mol2")
1574
+ ]
1575
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
1576
+ # Test for substructure match
1577
+ matches = topology.chemical_environment_matches("[C:1]-[C:2]-[O:3]", toolkit_registry=toolkit_wrapper)
1578
+ assert len(matches) == 143
1579
+ assert matches[0].topology_atom_indices == (1728, 1729, 1730)
1580
+ # Test for whole-molecule match
1581
+ matches = topology.chemical_environment_matches(
1582
+ "[H][C:1]([H])([H])-[C:2]([H])([H])-[O:3][H]",
1583
+ toolkit_registry=toolkit_wrapper,
1584
+ )
1585
+ assert len(matches) == 1716 # 143 * 12 (there are 12 possible hydrogen mappings)
1586
+ assert matches[0].topology_atom_indices == (1728, 1729, 1730)
1587
+ # Search for a substructure that isn't there
1588
+ matches = topology.chemical_environment_matches("[C][C:1]-[C:2]-[O:3]", toolkit_registry=toolkit_wrapper)
1589
+ assert len(matches) == 0
1590
+
1591
+ @requires_rdkit
1592
+ def test_chemical_environments_matches_RDK(self):
1593
+ """Test Topology.chemical_environment_matches"""
1594
+ toolkit_wrapper = RDKitToolkitWrapper()
1595
+ pdbfile = app.PDBFile(get_data_file_path("systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb"))
1596
+ # toolkit_wrapper = RDKitToolkitWrapper()
1597
+ # molecules = [Molecule.from_file(get_data_file_path(name)) for name in ('molecules/ethanol.mol2',
1598
+ # 'molecules/cyclohexane.mol2')]
1599
+ molecules = []
1600
+ molecules.append(Molecule.from_smiles("CCO"))
1601
+ molecules.append(Molecule.from_smiles("C1CCCCC1"))
1602
+ topology = Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
1603
+ # Count CCO matches
1604
+ matches = topology.chemical_environment_matches("[C:1]-[C:2]-[O:3]", toolkit_registry=toolkit_wrapper)
1605
+ assert len(matches) == 143
1606
+ assert matches[0].topology_atom_indices == (1728, 1729, 1730)
1607
+ matches = topology.chemical_environment_matches(
1608
+ "[H][C:1]([H])([H])-[C:2]([H])([H])-[O:3][H]",
1609
+ toolkit_registry=toolkit_wrapper,
1610
+ )
1611
+ assert len(matches) == 1716 # 143 * 12 (there are 12 possible hydrogen mappings)
1612
+ assert matches[0].topology_atom_indices == (1728, 1729, 1730)
1613
+ # Search for a substructure that isn't there
1614
+ matches = topology.chemical_environment_matches("[C][C:1]-[C:2]-[O:3]", toolkit_registry=toolkit_wrapper)
1615
+ assert len(matches) == 0
1616
+
1617
+ def test_topology_hierarchy_iterators(
1618
+ self,
1619
+ ):
1620
+ top = Topology()
1621
+ # Ensure that an empty topology has no residues defined
1622
+ residues = list(top.hierarchy_iterator("residues"))
1623
+ assert residues == []
1624
+ # Ensure that a topology with no metadata has no residues defined
1625
+ top.add_molecule(dipeptide())
1626
+ residues = list(top.hierarchy_iterator("residues"))
1627
+ assert residues == []
1628
+ # Ensure that a topology with residues perceived has residues but not chains
1629
+ top.add_molecule(dipeptide_residues_perceived())
1630
+ residues = list(top.hierarchy_iterator("residues"))
1631
+ chains = list(top.hierarchy_iterator("chains"))
1632
+ assert chains == []
1633
+ assert [res.identifier for res in residues] == [
1634
+ ("None", "1", " ", "ACE"),
1635
+ ("None", "2", " ", "ALA"),
1636
+ ]
1637
+ # Ensure that adding molecules WITH hierarchy perceived DOES give the
1638
+ # topology residues and chains to iterate over
1639
+ top.add_molecule(dipeptide_hierarchy_added())
1640
+ top.add_molecule(cyx_hierarchy_added())
1641
+ residues = list(top.hierarchy_iterator("residues"))
1642
+ chains = list(top.hierarchy_iterator("chains"))
1643
+ assert [res.identifier for res in residues] == [
1644
+ ("None", "1", " ", "ACE"),
1645
+ ("None", "2", " ", "ALA"),
1646
+ ("None", "1", " ", "ACE"),
1647
+ ("None", "2", " ", "ALA"),
1648
+ ("None", "1", " ", "ACE"),
1649
+ ("None", "2", " ", "CYS"),
1650
+ ("None", "3", " ", "NME"),
1651
+ ("None", "4", " ", "ACE"),
1652
+ ("None", "5", " ", "CYS"),
1653
+ ("None", "6", " ", "NME"),
1654
+ ]
1655
+ # First chain hierarchy element is from dipeptide_hierarchy_added,
1656
+ # second is from cyx_hierarchy_added. Both have the same uniqueness
1657
+ # identifier; unclear that this behaviour is desired --- Perhaps
1658
+ # Topology.hierarchy_iterator should consolidate hierarchy elements from
1659
+ # different molecules?
1660
+ assert len(chains) == 2
1661
+ # Haven't changed anything, so updating hierarchy schemes should give
1662
+ # same results
1663
+ top.molecule(3).update_hierarchy_schemes()
1664
+ residues = list(top.hierarchy_iterator("residues"))
1665
+ chains = list(top.hierarchy_iterator("chains"))
1666
+ assert [res.identifier for res in residues] == [
1667
+ ("None", "1", " ", "ACE"),
1668
+ ("None", "2", " ", "ALA"),
1669
+ ("None", "1", " ", "ACE"),
1670
+ ("None", "2", " ", "ALA"),
1671
+ ("None", "1", " ", "ACE"),
1672
+ ("None", "2", " ", "CYS"),
1673
+ ("None", "3", " ", "NME"),
1674
+ ("None", "4", " ", "ACE"),
1675
+ ("None", "5", " ", "CYS"),
1676
+ ("None", "6", " ", "NME"),
1677
+ ]
1678
+ assert len(chains) == 2
1679
+
1680
+
1681
+ @skip_if_missing("nglview")
1682
+ class TestTopologyVisaulization:
1683
+ @pytest.mark.slow
1684
+ @requires_rdkit
1685
+ def test_visualize_basic(self):
1686
+ import nglview
1687
+
1688
+ topology = Topology.from_pdb(
1689
+ get_data_file_path(
1690
+ "systems/test_systems/T4_lysozyme_water_ions.pdb",
1691
+ )
1692
+ )
1693
+
1694
+ assert isinstance(topology.visualize(), nglview.NGLWidget)
1695
+
1696
+ @requires_rdkit
1697
+ @skip_if_missing("nglview")
1698
+ def test_missing_positions(self):
1699
+ import nglview
1700
+
1701
+ water = create_water()
1702
+ ammonia = create_ammonia()
1703
+
1704
+ with pytest.raises(MissingConformersError):
1705
+ water.to_topology().visualize()
1706
+
1707
+ with pytest.raises(MissingConformersError):
1708
+ Topology.from_molecules([water, ammonia]).visualize()
1709
+
1710
+ water.generate_conformers()
1711
+
1712
+ with pytest.raises(MissingConformersError):
1713
+ Topology.from_molecules([water, ammonia]).visualize()
1714
+
1715
+ ammonia.generate_conformers()
1716
+
1717
+ assert isinstance(
1718
+ Topology.from_molecules([water, ammonia]).visualize(),
1719
+ nglview.NGLWidget,
1720
+ )
1721
+
1722
+
1723
+ class TestAddTopology:
1724
+ def test_add_basic(self):
1725
+ topology1 = Molecule.from_smiles("O").to_topology()
1726
+ topology2 = Molecule.from_smiles("CO").to_topology()
1727
+
1728
+ topology3 = topology1 + topology2
1729
+
1730
+ assert topology3.n_atoms == 9
1731
+ assert topology3.n_bonds == 7
1732
+ assert topology3.n_molecules == 2
1733
+
1734
+ def test_add_inplace(self):
1735
+ topology1 = Molecule.from_smiles("O").to_topology()
1736
+ topology2 = Molecule.from_smiles("CO").to_topology()
1737
+
1738
+ topology3 = topology1 + topology2
1739
+ topology1 += topology2
1740
+
1741
+ for attr in ["n_atoms", "n_bonds", "n_molecules"]:
1742
+ assert getattr(topology1, attr) == getattr(topology3, attr)
1743
+
1744
+ def test_add_invalidate_cache(self):
1745
+ topology1 = Molecule.from_smiles("O").to_topology()
1746
+ topology2 = Molecule.from_smiles("CO").to_topology()
1747
+
1748
+ topology1.add_constraint(0, 1, 1.01 * unit.angstrom)
1749
+ topology2.identical_molecule_groups
1750
+
1751
+ assert topology1.constrained_atom_pairs[(0, 1)] == 1.01 * unit.angstrom
1752
+ assert len(topology2._cached_chemically_identical_molecules) == 1
1753
+ # Do a basic test of topology.atom_index which forces topology2
1754
+ # to build its atom index cache
1755
+ assert topology2.atom_index(topology2.atom(2)) == 2
1756
+
1757
+ topology3 = topology1 + topology2
1758
+
1759
+ assert topology3._cached_chemically_identical_molecules is None
1760
+ # Query the same atom as above, but in topology 3. If the cache isn't invalidated
1761
+ # then this will still have the old atom index (2), but if it's correctly
1762
+ # invalidated and rebuilt, it will have an index of 5.
1763
+ assert topology3.atom_index(topology3.atom(5)) == 5
1764
+
1765
+ # Constrained atom pairs are intentionally not removed
1766
+ assert topology3.constrained_atom_pairs[(0, 1)] == 1.01 * unit.angstrom
1767
+
1768
+ def test_add_with_constraints(self):
1769
+ # See https://github.com/openforcefield/openff-toolkit/pull/1194#discussion_r834768068
1770
+ methane = Molecule.from_mapped_smiles("[H:2][C:1]([H:3])([H:4])[H:5]").to_topology()
1771
+ water = Molecule.from_mapped_smiles("[H:2][O:1][H:3]").to_topology()
1772
+
1773
+ # Constrain one C-H bond in methane and H-H in water (0-indexed)
1774
+ methane.add_constraint(0, 1)
1775
+ water.add_constraint(1, 2, unit.Quantity(1.234, unit.angstrom))
1776
+
1777
+ combined_topology = methane + water
1778
+
1779
+ # Constraints are tracked i-j and j-i, so this dict is length 4
1780
+ assert len(combined_topology.constrained_atom_pairs) == 4
1781
+
1782
+ # Methane is the first molecule, so (0, 1) is conserved. The atoms in the constrained
1783
+ # pair in water are offset by the number of atoms in methane (5)
1784
+ assert ((0, 1)) in combined_topology.constrained_atom_pairs
1785
+ assert ((1, 0)) in combined_topology.constrained_atom_pairs
1786
+ assert ((6, 7)) in combined_topology.constrained_atom_pairs
1787
+ assert ((7, 6)) in combined_topology.constrained_atom_pairs
1788
+
1789
+ assert combined_topology.constrained_atom_pairs[(0, 1)]
1790
+ assert combined_topology.constrained_atom_pairs[(1, 0)]
1791
+ assert combined_topology.constrained_atom_pairs[(6, 7)] == unit.Quantity(1.234, unit.angstrom)
1792
+ assert combined_topology.constrained_atom_pairs[(7, 6)] == unit.Quantity(1.234, unit.angstrom)
1793
+
1794
+
1795
+ def residue_equality_check(residue1, residue2):
1796
+ """Hack to work around #1659."""
1797
+ assert residue1.n_atoms == residue2.n_atoms
1798
+ assert residue1.residue_number == residue2.residue_number
1799
+ assert residue1.residue_name == residue2.residue_name
1800
+ assert residue1.chain_id == residue2.chain_id
1801
+ assert residue1.insertion_code == residue2.insertion_code
1802
+
1803
+
1804
+ class TestTopologyHierarchyIterators:
1805
+ @requires_rdkit
1806
+ def test_single_small_peptide(
1807
+ self,
1808
+ ):
1809
+ protein_path = get_data_file_path("proteins/ace-ala-nh2.pdb")
1810
+
1811
+ topology = Topology.from_pdb(protein_path)
1812
+ molecule = Molecule.from_polymer_pdb(protein_path)
1813
+
1814
+ assert hasattr(topology, "residues")
1815
+
1816
+ assert len(topology.residues) == len(molecule.residues)
1817
+
1818
+ for topology_residue, molecule_residue in zip(
1819
+ topology.residues,
1820
+ molecule.residues,
1821
+ ):
1822
+ residue_equality_check(
1823
+ topology_residue,
1824
+ molecule_residue,
1825
+ )
1826
+
1827
+ def test_no_iterators(self):
1828
+ topology = Molecule.from_smiles("CCO").to_topology()
1829
+
1830
+ with pytest.raises(
1831
+ AttributeError,
1832
+ match="'Topology' object has no attribute 'residues'",
1833
+ ):
1834
+ topology.residues
1835
+
1836
+ @requires_rdkit
1837
+ def test_error_when_mixed_iterators(
1838
+ self,
1839
+ ):
1840
+ """Test that an error is raised when a topology has molecules with and without an iterator."""
1841
+ protein_path = get_data_file_path("proteins/ace-ala-nh2.pdb")
1842
+
1843
+ topology = Topology.from_pdb(protein_path)
1844
+ topology.add_molecule(Molecule.from_smiles("CCO"))
1845
+
1846
+ with pytest.raises(
1847
+ AttributeError,
1848
+ match="'Topology' object has no attribute 'residues'",
1849
+ ):
1850
+ topology.residues
1851
+
1852
+ def test_molecule_order_wins_over_residue_order(
1853
+ self,
1854
+ ):
1855
+ """Test that no effort is made to sort residues by residue number across molecules."""
1856
+ protein_path = get_data_file_path("proteins/ace-ala-nh2.pdb")
1857
+
1858
+ topology = Topology.from_molecules(
1859
+ [
1860
+ Molecule.from_polymer_pdb(protein_path),
1861
+ Molecule.from_polymer_pdb(protein_path),
1862
+ ]
1863
+ )
1864
+
1865
+ assert topology.residues[0].residue_number == topology.residues[3].residue_number
1866
+ assert topology.residues[1].residue_number == topology.residues[4].residue_number
1867
+ assert topology.residues[2].residue_number == topology.residues[5].residue_number
1868
+
1869
+ assert int(topology.residues[2].residue_number) > int(topology.residues[3].residue_number)
1870
+
1871
+ @pytest.mark.skip(reason="Undefined behavior upstream, see #1660")
1872
+ def test_clashing_hierarchy_scheme_iterator_name(
1873
+ self,
1874
+ ):
1875
+ molecule = Molecule.from_smiles("CCO")
1876
+ molecule.add_hierarchy_scheme(
1877
+ uniqueness_criteria=("magic",),
1878
+ iterator_name="atoms",
1879
+ )
1880
+
1881
+ topology = molecule.to_topology()
1882
+
1883
+ with pytest.raises(HierarchyIteratorNameConflictError):
1884
+ topology.atoms
1885
+
1886
+
1887
+ class TestTopologySerialization:
1888
+ @pytest.fixture
1889
+ def oleic_acid(self):
1890
+ """Simple floppy molecule that can be assured to have multiple conformers"""
1891
+ return Molecule.from_smiles(r"CCCCCCCC\C=C/CCCCCCCC(O)=O")
1892
+
1893
+ @pytest.mark.parametrize(("with_conformers"), [True, False])
1894
+ @pytest.mark.parametrize(("n_molecules"), [1, 2])
1895
+ @pytest.mark.parametrize(("format"), ["dict", "json"])
1896
+ def test_roundtrip(self, oleic_acid, with_conformers, n_molecules, format):
1897
+ if with_conformers:
1898
+ n_conformers = 2
1899
+ oleic_acid.generate_conformers(n_conformers=n_conformers)
1900
+ else:
1901
+ n_conformers = 0
1902
+
1903
+ if format == "dict":
1904
+ roundtrip = Topology.from_dict(Topology.from_molecules(n_molecules * [oleic_acid]).to_dict())
1905
+ elif format == "json":
1906
+ roundtrip = Topology.from_json(Topology.from_molecules(n_molecules * [oleic_acid]).to_json())
1907
+
1908
+ assert roundtrip.n_molecules == n_molecules
1909
+ assert roundtrip.n_atoms == oleic_acid.n_atoms * n_molecules
1910
+ assert next(iter(roundtrip.molecules)).n_conformers == n_conformers
1911
+
1912
+ @pytest.mark.parametrize("format", ["dict", "json"])
1913
+ def test_roundtrip_simple_molecules(self, mixed_topology, format):
1914
+ if format == "dict":
1915
+ roundtrip = Topology.from_dict(mixed_topology.to_dict())
1916
+ elif format == "json":
1917
+ roundtrip = Topology.from_json(mixed_topology.to_json())
1918
+
1919
+ assert roundtrip.n_molecules == mixed_topology.n_molecules
1920
+ assert roundtrip.n_atoms == mixed_topology.n_atoms
1921
+
1922
+
1923
+ @pytest.mark.parametrize(
1924
+ ("n_degrees", "num_pairs"),
1925
+ [
1926
+ (6, 0),
1927
+ (5, 3),
1928
+ (4, 14),
1929
+ (3, 28),
1930
+ ],
1931
+ )
1932
+ def test_nth_degree_neighbors(n_degrees, num_pairs):
1933
+ smiles = ["c1ccccc1", "N1ONON1"]
1934
+ topology = Topology.from_molecules([Molecule.from_smiles(smi) for smi in smiles])
1935
+
1936
+ # See test_molecule.TestMolecule.test_nth_degree_neighbors_rings for values
1937
+ num_pairs_found = len([*topology.nth_degree_neighbors(n_degrees=n_degrees)])
1938
+ assert num_pairs_found == num_pairs
1939
+
1940
+
1941
+ def _tagsorted_dict_init_ref_key(tsd):
1942
+ if tsd is None:
1943
+ tsd = TagSortedDict()
1944
+
1945
+ ref_key = (0, 1, 2)
1946
+ tsd[ref_key] = 5
1947
+ else:
1948
+ ref_key = next(x for x in tsd)
1949
+
1950
+ return tsd, ref_key
1951
+
1952
+
1953
+ @pytest.mark.parametrize("tsd", [None, TagSortedDict({(0, 1, 2): 5})])
1954
+ def test_tagsorted_dict_deduplication(tsd):
1955
+ """Test that all permutations of a key are present if one permutation is stored"""
1956
+ tsd, ref_key = _tagsorted_dict_init_ref_key(tsd)
1957
+
1958
+ # only has one key, but all permutations match
1959
+ for key in itertools.permutations(ref_key):
1960
+ assert key in tsd
1961
+
1962
+ assert len(tsd) == 1
1963
+
1964
+
1965
+ @pytest.mark.parametrize("tsd", [None, TagSortedDict({(0, 1, 2): 5})])
1966
+ def test_tagsorted_dict_permutation_equivalence(tsd):
1967
+ """Test that all permutations of a key would return the same result"""
1968
+ tsd, ref_key = _tagsorted_dict_init_ref_key(tsd)
1969
+
1970
+ # lookups using any permutation will give the same return
1971
+ for key in itertools.permutations(ref_key):
1972
+ assert tsd[key] == 5
1973
+
1974
+ assert len(tsd) == 1
1975
+
1976
+
1977
+ @pytest.mark.parametrize("tsd", [None, TagSortedDict({(0, 1, 2): 5})])
1978
+ def test_tagsorted_dict_key_transform(tsd):
1979
+ """Test that all key permutations transform to the same stored single key
1980
+ permutation"""
1981
+ tsd, ref_key = _tagsorted_dict_init_ref_key(tsd)
1982
+
1983
+ # all permutations should resolve to ref_key
1984
+ for key in itertools.permutations(ref_key):
1985
+ tr_key = tsd.key_transform(key)
1986
+ assert tr_key == ref_key
1987
+
1988
+ assert len(tsd) == 1
1989
+
1990
+
1991
+ @pytest.mark.parametrize("tsd", [None, TagSortedDict({(0, 1, 2): 5})])
1992
+ def test_tagsorted_dict_modify(tsd):
1993
+ """Test that modifying a key with another permutation replaces the original key"""
1994
+ tsd, ref_key = _tagsorted_dict_init_ref_key(tsd)
1995
+
1996
+ # replace the ref_key since this is a permutation of it
1997
+ mod_key = (1, 0, 2)
1998
+ tsd[mod_key] = 6
1999
+
2000
+ keys = list(tsd)
2001
+ assert ref_key not in keys
2002
+
2003
+ for key in itertools.permutations(ref_key):
2004
+ assert key in tsd
2005
+
2006
+ assert len(tsd) == 1 # should not be 2
2007
+
2008
+
2009
+ @pytest.mark.parametrize("tsd", [TagSortedDict({(0, 1, 2): 5, (1, 2): 4})])
2010
+ def test_tagsorted_dict_multiple_keys(tsd):
2011
+ """Test the use of multiple keys with similar values but different length"""
2012
+ tsd, ref_key = _tagsorted_dict_init_ref_key(tsd)
2013
+
2014
+ # replace the ref_key since this is a permutation of it
2015
+ mod_key = (1, 0, 2)
2016
+ tsd[mod_key] = 6
2017
+
2018
+ keys = list(tsd)
2019
+ assert ref_key not in keys # ensure original key is gone
2020
+
2021
+ for key in itertools.permutations(ref_key):
2022
+ assert key in tsd
2023
+
2024
+ assert tsd[(2, 1)] == 4 # should be unchanged
2025
+ assert len(tsd) == 2 # should not be 3
2026
+
2027
+
2028
+ @pytest.mark.parametrize("tsd", [TagSortedDict({(0, 1, 2): 5, (1, 2): 4})])
2029
+ def test_tagsorted_dict_clear(tsd):
2030
+ """Test the clear method"""
2031
+ tsd, _ = _tagsorted_dict_init_ref_key(tsd)
2032
+
2033
+ tsd.clear()
2034
+
2035
+ assert len(tsd) == 0
2036
+
2037
+
2038
+ class TestValenceDictKeyIndex:
2039
+ @pytest.mark.parametrize(
2040
+ "inkey, outkey",
2041
+ [
2042
+ [[0, 1], (0, 1)],
2043
+ [[1, 0], (0, 1)],
2044
+ [(1, 3, 2, 4), (1, 3, 2, 4)],
2045
+ [(4, 2, 3, 1), (1, 3, 2, 4)],
2046
+ [(1, 8, 3, 4, 2, 5), (1, 8, 3, 4, 2, 5)],
2047
+ [(5, 2, 4, 3, 8, 1), (1, 8, 3, 4, 2, 5)],
2048
+ ],
2049
+ )
2050
+ def test_key_transform(self, inkey, outkey):
2051
+ assert ValenceDict.key_transform(inkey) == outkey
2052
+
2053
+ @pytest.mark.parametrize(
2054
+ "key, possible, index",
2055
+ [
2056
+ [[0, 1], None, 0],
2057
+ [[1, 0], None, 1],
2058
+ [(1, 3, 2, 4), None, 0],
2059
+ [(4, 2, 3, 1), None, 1],
2060
+ [(4, 2, 3, 1), [(4, 2, 3, 1)], 0],
2061
+ [(1, 8, 3, 4, 2, 5), None, 0],
2062
+ [(5, 2, 4, 3, 8, 1), None, 1],
2063
+ [(5, 2, 4, 3, 8, 1), [(5, 2, 4, 3, 8, 1)], 0],
2064
+ ],
2065
+ )
2066
+ def test_index_of(self, key, possible, index):
2067
+ assert ValenceDict.index_of(key, possible) == index
2068
+
2069
+ def test_impossible_error(self):
2070
+ with pytest.raises(ValueError, match="Impossible permutations"):
2071
+ ValenceDict.index_of([0, 1, 2, 4], possible=[(1, 2, 3, 4)])
2072
+
2073
+ def test_no_key(self):
2074
+ with pytest.raises(ValueError, match="not in possible"):
2075
+ ValenceDict.index_of([0, 1, 2, 4], possible=[(4, 2, 1, 0)])
2076
+
2077
+ def test_construct(self):
2078
+ v = ValenceDict()
2079
+ v[(4, 2, 3, 1)] = 0
2080
+ assert (1, 3, 2, 4) in v
2081
+ assert (4, 2, 3, 1) in v
2082
+ assert v[(1, 3, 2, 4)] == 0
2083
+
2084
+
2085
+ class TestImproperDictKeyIndex:
2086
+ @pytest.mark.parametrize(
2087
+ "inkey, outkey",
2088
+ [
2089
+ [(0, 1, 2, 3), (0, 1, 2, 3)],
2090
+ [(0, 1, 3, 2), (0, 1, 2, 3)],
2091
+ [(2, 1, 0, 3), (0, 1, 2, 3)],
2092
+ [(2, 1, 3, 0), (0, 1, 2, 3)],
2093
+ [(3, 1, 2, 0), (0, 1, 2, 3)],
2094
+ [(3, 1, 0, 2), (0, 1, 2, 3)],
2095
+ ],
2096
+ )
2097
+ def test_key_transform(self, inkey, outkey):
2098
+ assert ImproperDict.key_transform(inkey) == outkey
2099
+
2100
+ @pytest.mark.parametrize(
2101
+ "key, index",
2102
+ [
2103
+ [(0, 1, 2, 3), 0],
2104
+ [(0, 1, 3, 2), 1],
2105
+ [(2, 1, 0, 3), 2],
2106
+ [(2, 1, 3, 0), 3],
2107
+ [(3, 1, 0, 2), 4],
2108
+ [(3, 1, 2, 0), 5],
2109
+ ],
2110
+ )
2111
+ def test_index_of_no_possible(self, key, index):
2112
+ assert ImproperDict.index_of(key) == index
2113
+
2114
+ @pytest.mark.parametrize(
2115
+ "possible, index",
2116
+ [
2117
+ [[(3, 1, 0, 2)], 0],
2118
+ [[(3, 1, 0, 2), (3, 1, 0, 2)], 0],
2119
+ [[(0, 1, 2, 3), (3, 1, 0, 2)], 1],
2120
+ [[(2, 1, 3, 0), (3, 1, 0, 2)], 1],
2121
+ [[(0, 1, 3, 2), (3, 1, 0, 2), (3, 1, 2, 0)], 1],
2122
+ [[(0, 1, 3, 2), (0, 1, 2, 3), (3, 1, 0, 2)], 2],
2123
+ ],
2124
+ )
2125
+ def test_index_of_possible(self, possible, index):
2126
+ assert ImproperDict.index_of((3, 1, 0, 2), possible) == index
2127
+
2128
+ def test_impossible_error(self):
2129
+ with pytest.raises(ValueError, match="Impossible permutations"):
2130
+ ImproperDict.index_of([0, 1, 2, 4], possible=[(1, 2, 3, 4)])
2131
+
2132
+ def test_no_key(self):
2133
+ with pytest.raises(ValueError, match="not in possible"):
2134
+ ImproperDict.index_of([0, 1, 2, 4], possible=[(4, 1, 2, 0)])
2135
+
2136
+
2137
+ class TestTopologyPositions:
2138
+ @pytest.mark.parametrize(
2139
+ "generate_positions",
2140
+ [
2141
+ # Test an array
2142
+ lambda n: np.arange(n * 3).reshape(n, 3),
2143
+ # Test a list of lists
2144
+ lambda n: [[i * 3, i * 3 + 1, i * 3 + 2] for i in range(n)],
2145
+ # Test a list of tuples
2146
+ lambda n: [(i * 3, i * 3 + 1, i * 3 + 2) for i in range(n)],
2147
+ ],
2148
+ )
2149
+ def test_set_positions(self, generate_positions):
2150
+ # Methane molecule with initial conformers
2151
+ methane = Molecule.from_mapped_smiles("[H:2][C:1]([H:3])([H:4])[H:5]")
2152
+ methane.generate_conformers()
2153
+ init_conformers = deepcopy(methane.conformers)
2154
+
2155
+ # Water molecules without initial conformers
2156
+ water = Molecule.from_mapped_smiles("[H:2][O:1][H:3]")
2157
+ assert water._conformers is None
2158
+
2159
+ # Water molecules with empty list of conformers
2160
+ water_emptyconfs = Molecule.from_mapped_smiles("[H:2][O:1][H:3]")
2161
+ water_emptyconfs._conformers = []
2162
+
2163
+ # Compile topology
2164
+ topology = Topology.from_molecules(
2165
+ [
2166
+ methane,
2167
+ *[water] * 2,
2168
+ *[water_emptyconfs] * 2,
2169
+ ]
2170
+ )
2171
+
2172
+ # Generate positions deterministically
2173
+ positions = Quantity(generate_positions(topology.n_atoms), unit.nanometer)
2174
+
2175
+ # Run the method under test
2176
+ topology.set_positions(positions)
2177
+
2178
+ # Make sure the input molecules haven't changed
2179
+ # (because adding them to the topology copies them)
2180
+ assert all(np.all(a == b) for a, b in zip(methane.conformers, init_conformers))
2181
+ assert not water.conformers
2182
+
2183
+ # Now we're going to check all the molecules
2184
+ mol_iter = topology.molecules
2185
+
2186
+ # Make sure the methane's first conformation is changed, but the others are left
2187
+ first_mol = next(mol_iter)
2188
+ assert np.all(first_mol.conformers[0] == positions[0:5, :])
2189
+ assert np.all(first_mol.conformers[1:] == init_conformers[1:])
2190
+
2191
+ # Check the other molecules in the topology.
2192
+ # Reusing the iterator to skip the methane
2193
+ for i, mol in enumerate(mol_iter):
2194
+ # Methane is indices 0-4, so the first water we want to iterate
2195
+ # over (i==0) is indices 5, 6, 7, ie slice [5:8].
2196
+ start = i * 3 + 5
2197
+ stop = i * 3 + 8
2198
+ assert np.all(mol.conformers[0] == positions[start:stop, :])
2199
+
2200
+ def test_set_positions_simple_molecule(self):
2201
+ """Reproduce issue #1867"""
2202
+ simple = _SimpleMolecule.from_molecule(Molecule.from_smiles("C=O"))
2203
+
2204
+ topology = Topology.from_molecules([simple, simple])
2205
+
2206
+ topology.set_positions(Quantity(np.zeros((topology.n_atoms, 3)), "nanometer"))
2207
+
2208
+ positions = topology.get_positions()
2209
+
2210
+ assert positions.shape == (topology.n_atoms, 3)
2211
+ assert positions.units == "nanometer"
2212
+
2213
+ def test_set_positions_mixed_topology(self):
2214
+ """Reproduce issue #1867"""
2215
+ molecule = Molecule.from_smiles("C=O")
2216
+ simple = _SimpleMolecule.from_molecule(molecule)
2217
+
2218
+ topology = Topology.from_molecules([molecule, simple])
2219
+
2220
+ topology.set_positions(Quantity(np.zeros((topology.n_atoms, 3)), "nanometer"))
2221
+
2222
+ positions = topology.get_positions()
2223
+
2224
+ assert positions.shape == (topology.n_atoms, 3)
2225
+ assert positions.units == "nanometer"
2226
+
2227
+ @pytest.fixture()
2228
+ def topology(self) -> Topology:
2229
+ methane = Molecule.from_mapped_smiles("[H:2][C:1]([H:3])([H:4])[H:5]")
2230
+ water = Molecule.from_mapped_smiles("[H:2][O:1][H:3]")
2231
+ topology = Topology.from_molecules([methane] + [water] * 4)
2232
+
2233
+ return topology
2234
+
2235
+ @pytest.fixture()
2236
+ def topology_with_positions(self, topology) -> Topology:
2237
+ # These conformers will obviously overlap, but they'll be the right data type
2238
+ for molecule in topology.molecules:
2239
+ molecule.generate_conformers(n_conformers=1)
2240
+
2241
+ return topology
2242
+
2243
+ def test_set_positions_fails_without_units(self, topology):
2244
+ # Generate positions without units deterministically
2245
+ positions_no_units = np.arange(topology.n_atoms * 3).reshape(-1, 3)
2246
+
2247
+ with pytest.raises(
2248
+ IncompatibleUnitError,
2249
+ match=re.escape("array should be an OpenFF Quantity with dimensions of length"),
2250
+ ):
2251
+ topology.set_positions(positions_no_units)
2252
+
2253
+ @pytest.mark.parametrize(
2254
+ "generate_shape",
2255
+ [
2256
+ lambda n: (3, n), # right size, backwards
2257
+ lambda n: (n, 1, 3), # right size, one extra dimension
2258
+ lambda n: (n * 3,), # right size, 1D array
2259
+ lambda _: (0,), # No positions
2260
+ lambda n: (n + 1, 3), # Right shape, one too many atoms
2261
+ lambda n: (n - 1, 3), # Right shape, one too few atoms
2262
+ lambda n: (n * 3, 3), # Right shape, 3 times too many atoms
2263
+ lambda n: (n, 1), # 1D chemistry is not real
2264
+ ],
2265
+ )
2266
+ def test_set_positions_fails_with_wrong_shape(
2267
+ self,
2268
+ topology,
2269
+ generate_shape,
2270
+ ):
2271
+ # Generate positions without units deterministically
2272
+ n_atoms = topology.n_atoms
2273
+ shape = generate_shape(n_atoms)
2274
+ size = np.prod(shape)
2275
+ positions_wrong_shape = Quantity(
2276
+ np.arange(size).reshape(*shape),
2277
+ unit.nanometer,
2278
+ )
2279
+
2280
+ with pytest.raises(
2281
+ WrongShapeError,
2282
+ match=re.escape(f"Array has shape {shape} but should have shape {(n_atoms, 3)}"),
2283
+ ):
2284
+ topology.set_positions(positions_wrong_shape)
2285
+
2286
+ def test_get_positions(self, topology):
2287
+ # Generate positions deterministically
2288
+ positions = Quantity(np.arange(topology.n_atoms * 3).reshape(-1, 3), unit.nanometer)
2289
+ topology.set_positions(positions)
2290
+
2291
+ # Check that the positions match
2292
+ positions_out = topology.get_positions()
2293
+ assert np.all(positions_out == positions)
2294
+ assert positions_out is not positions
2295
+
2296
+ # Set a position in positions_out and check that it does not alter the
2297
+ # underlying conformer
2298
+ positions_out[0, 0] = -1.0 * unit.nanometer # Negative positions cannot be generated
2299
+ assert np.all(next(topology.molecules).conformers[0] != -1.0 * unit.nanometer)
2300
+
2301
+ def test_get_positions_none(self, topology):
2302
+ # No positions when conformers are None
2303
+ assert topology.get_positions() is None
2304
+
2305
+ # No positions when conformer is empty
2306
+ topology._molecules[0]._conformers = []
2307
+ assert topology.get_positions() is None
2308
+
2309
+ # Positions for everything but first molecule
2310
+ positions = Quantity(
2311
+ np.arange(topology.n_atoms * 3).reshape(-1, 3),
2312
+ unit.nanometer,
2313
+ )
2314
+ topology.set_positions(positions)
2315
+ topology._molecules[0]._conformers = None
2316
+ assert topology.get_positions() is None
2317
+
2318
+ def test_clear_and_re_set_positions(self, topology_with_positions):
2319
+ initial_positions = topology_with_positions.get_positions()
2320
+ assert initial_positions is not None
2321
+ assert initial_positions.shape == (topology_with_positions.n_atoms, 3)
2322
+
2323
+ with pytest.raises(
2324
+ ValueError,
2325
+ match=r"cannot be None.*use clear_positions",
2326
+ ):
2327
+ topology_with_positions.set_positions(None)
2328
+
2329
+ topology_with_positions.clear_positions()
2330
+
2331
+ assert topology_with_positions.get_positions() is None
2332
+
2333
+ for molecule in topology_with_positions.molecules:
2334
+ assert molecule.conformers is None
2335
+
2336
+ # re-set positions back to their original values
2337
+ topology_with_positions.set_positions(initial_positions)
2338
+
2339
+ assert initial_positions is not None
2340
+ assert initial_positions.shape == (topology_with_positions.n_atoms, 3)
2341
+
2342
+
2343
+ @requires_rdkit
2344
+ class TestTopologyFromPdbCustomSubstructures:
2345
+ def test_atomic_num_spec(self):
2346
+ with pytest.raises(SubstructureAtomSmartsInvalid):
2347
+ PE_substructs = {
2348
+ "PE": ["[CD4+0:9](-[#1D1+0:10])(-[#1D1+0:11])(-[#6D4+0:12](-[#1D1+0:13])(-[#1D1+0:14])-[*:15])-[*:16]"]
2349
+ }
2350
+ Topology.from_pdb(
2351
+ get_data_file_path("systems/test_systems/PE.pdb"),
2352
+ _custom_substructures=PE_substructs,
2353
+ )
2354
+
2355
+ def test_monomer_connectivity(self):
2356
+ with pytest.raises(SubstructureAtomSmartsInvalid):
2357
+ PE_substructs = {
2358
+ "PE": [
2359
+ "[#6D3+0:9](-[#1D1+0:10])(-[#1D1+0:11])(-[#6D4+0:12](-[#1D1+0:13])(-[#1D1+0:14])-[*:15])-[*:16]"
2360
+ ]
2361
+ }
2362
+ Topology.from_pdb(
2363
+ get_data_file_path("systems/test_systems/PE.pdb"),
2364
+ _custom_substructures=PE_substructs,
2365
+ )
2366
+
2367
+ def test_formal_charge_spec(self):
2368
+ with pytest.raises(SubstructureAtomSmartsInvalid):
2369
+ PE_substructs = {
2370
+ "PE": ["[#6D4+0:9](-[#1D1+0:10])(-[#1D1+0:11])(-[#6D4:12](-[#1D1+0:13])(-[#1D1+0:14])-[*:15])-[*:16]"]
2371
+ }
2372
+ Topology.from_pdb(
2373
+ get_data_file_path("systems/test_systems/PE.pdb"),
2374
+ _custom_substructures=PE_substructs,
2375
+ )
2376
+
2377
+ def test_bond_type_spec(self):
2378
+ with pytest.raises(SubstructureBondSmartsInvalid):
2379
+ PE_substructs = {
2380
+ "PE": [
2381
+ "[#6D4+0:9](~[#1D1+0:10])(-[#1D1+0:11])(-[#6D4+0:12](-[#1D1+0:13])(-[#1D1+0:14])-[*:15])-[*:16]"
2382
+ ]
2383
+ }
2384
+ Topology.from_pdb(
2385
+ get_data_file_path("systems/test_systems/PE.pdb"),
2386
+ _custom_substructures=PE_substructs,
2387
+ )
2388
+
2389
+ def test_duplicate_monomers(self):
2390
+ with pytest.raises(NonUniqueSubstructureName):
2391
+ PE_substructs = {
2392
+ "LEU": [
2393
+ "[#6D4+0:9](-[#1D1+0:10])(-[#1D1+0:11])(-[#6D4+0:12](-[#1D1+0:13])(-[#1D1+0:14])-[*:15])-[*:16]"
2394
+ ]
2395
+ }
2396
+ Topology.from_pdb(
2397
+ get_data_file_path("systems/test_systems/PE.pdb"),
2398
+ _custom_substructures=PE_substructs,
2399
+ )
2400
+
2401
+ def test_ambiguous_bond_info_check(self):
2402
+ with pytest.raises(AmbiguousBondChemicalAssignment):
2403
+ PE_substructs = {
2404
+ "PE": [
2405
+ "[#6D4+0:9](-[#1D1+0:10])(-[#1D1+0:11])(-[#6D4+0:12](-[#1D1+0:13])(-[#1D1+0:14])-[*:15])-[*:16]",
2406
+ "[#6D4+0:9](-[#1D1+0:10])(-[#1D1+0:11])(=[#6D4+0:12](-[#1D1+0:13])(-[#1D1+0:14])-[*:15])-[*:16]",
2407
+ ]
2408
+ }
2409
+ Topology.from_pdb(
2410
+ get_data_file_path("systems/test_systems/PE.pdb"),
2411
+ _custom_substructures=PE_substructs,
2412
+ )
2413
+
2414
+ def test_ambiguous_formal_charge_check(self):
2415
+ with pytest.raises(AmbiguousAtomChemicalAssignment):
2416
+ PE_substructs = {
2417
+ "PE": [
2418
+ "[#6D4+0:9](-[#1D1+0:10])(-[#1D1+0:11])(-[#6D4+0:12](-[#1D1+0:13])(-[#1D1+0:14])-[*:15])-[*:16]",
2419
+ "[#6D4+0:9](-[#1D1+0:10])(-[#1D1+0:11])(-[#6D4+1:12](-[#1D1+0:13])(-[#1D1+0:14])-[*:15])-[*:16]",
2420
+ ]
2421
+ }
2422
+ Topology.from_pdb(
2423
+ get_data_file_path("systems/test_systems/PE.pdb"),
2424
+ _custom_substructures=PE_substructs,
2425
+ )
2426
+
2427
+ def test_successful_PE_loading(self):
2428
+ PE_substructs = {
2429
+ "PE": [
2430
+ "[#6D4+0:2](-[#1D1+0:3])(-[#1D1+0:4])(-[#6D4+0:5](-[#1D1+0:6])(-[#1D1+0:7])-[*:8])-[*:1]",
2431
+ "[#6D4+0:2](-[#1D1+0:3])(-[#1D1+0:4])(-[#6D4+0:5](-[#1D1+0:6])(-[#1D1+0:7])-[#1D1+0:8])-[*:1]",
2432
+ "[#6D4+0:2](-[#1D1+0:3])(-[#1D1+0:4])(-[#6D4+0:5](-[#1D1+0:6])(-[#1D1+0:7])-[*:8])-[#1D1+0:1]",
2433
+ ]
2434
+ }
2435
+ Topology.from_pdb(
2436
+ get_data_file_path("systems/test_systems/PE.pdb"),
2437
+ _custom_substructures=PE_substructs,
2438
+ )
2439
+
2440
+ def test_symmetrical_group_COO(self):
2441
+ from rdkit import Chem
2442
+
2443
+ substructure_smarts = (
2444
+ "[#7D4+:1](-[#6D4+0:2](-[#6D3+0:3](=[#8D1+0:4])-[#8D1-:6])(-[#6D4+0:5](-[#1D1+0:8])(-"
2445
+ "[#1D1+0:9])-[#1D1+0:10])-[#1D1+0:7])(-[#1D1+0:11])(-[#1D1+0:12])-[#1D1+0:13]"
2446
+ )
2447
+ ref = Chem.MolFromSmarts(substructure_smarts)
2448
+ rdkit_wrapper = RDKitToolkitWrapper()
2449
+ fuzzy, _ = rdkit_wrapper._fuzzy_query(ref)
2450
+ sym_atoms, sym_bonds = rdkit_wrapper._get_symmetrical_groups(fuzzy, ref)
2451
+
2452
+ assert sorted(sym_atoms) == [3, 4]
2453
+ assert sorted(sym_bonds) == [(2, 3), (2, 4)]
2454
+
2455
+ def test_symmetrical_group_ARG(self):
2456
+ from rdkit import Chem
2457
+
2458
+ substructure_smarts = (
2459
+ "[#7D4+:1](-[#6D4+0:2](-[#6D3+0:3](=[#8D1+0:4])-[#8D1-:12])(-[#6D4+0:5](-[#6D4+0:6](-"
2460
+ "[#6D4+0:7](-[#7D3+0:8](-[#6D3+0:9](-[#7D3+0:10](-[#1D1+0:21])-[#1D1+0:22])=[#7D3+:11"
2461
+ "](-[#1D1+0:23])-[#1D1+0:24])-[#1D1+0:20])(-[#1D1+0:18])-[#1D1+0:19])(-[#1D1+0:16])-["
2462
+ "#1D1+0:17])(-[#1D1+0:14])-[#1D1+0:15])-[#1D1+0:13])(-[#1D1+0:25])(-[#1D1+0:26])-[#1D"
2463
+ "1+0:27]"
2464
+ )
2465
+ ref = Chem.MolFromSmarts(substructure_smarts)
2466
+ rdkit_wrapper = RDKitToolkitWrapper()
2467
+ fuzzy, _ = rdkit_wrapper._fuzzy_query(ref)
2468
+ sym_atoms, sym_bonds = rdkit_wrapper._get_symmetrical_groups(fuzzy, ref)
2469
+
2470
+ assert sorted(sym_atoms) == [3, 4, 10, 13]
2471
+ assert sorted(sym_bonds) == [(2, 3), (2, 4), (9, 10), (9, 13)]
2472
+
2473
+
2474
+ class TestMixedTopology:
2475
+ def test_reinitialized_mixed_topology(self, mixed_topology):
2476
+ copied = Topology(mixed_topology)
2477
+
2478
+ assert copied.n_atoms == mixed_topology.n_atoms
2479
+ assert copied.n_bonds == mixed_topology.n_bonds
2480
+ assert copied.n_molecules == mixed_topology.n_molecules
2481
+
2482
+ assert (
2483
+ copied.atom(int(copied.n_atoms / 2)).atomic_number
2484
+ == mixed_topology.atom(int(mixed_topology.n_atoms / 2)).atomic_number
2485
+ )