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.
- devtools/scripts/build_cookiecutter_json.py +22 -0
- docs/conf.py +296 -0
- docs/conftest.py +23 -0
- examples/conformer_energies/conformer_energies.py +143 -0
- examples/deprecated/SMIRNOFF_comparison/compare_molecule_energies.py +48 -0
- examples/deprecated/SMIRNOFF_comparison/compare_set_energies.py +58 -0
- examples/deprecated/liquid_box/create_mol2_pdb/create_mol2_pdb.py +193 -0
- examples/deprecated/liquid_box/openff_simulation.py +72 -0
- examples/deprecated/mixedFF_structure/generate_mixedFF_complex.py +56 -0
- examples/deprecated/testing/test_impropers/tleap_tools.py +120 -0
- examples/examples_helper.py +61 -0
- openff/toolkit/__init__.py +101 -0
- openff/toolkit/_tests/__init__.py +0 -0
- openff/toolkit/_tests/_stale_tests.py +146 -0
- openff/toolkit/_tests/conftest.py +108 -0
- openff/toolkit/_tests/create_molecules.py +494 -0
- openff/toolkit/_tests/mocking.py +145 -0
- openff/toolkit/_tests/molecule/__init__.py +1 -0
- openff/toolkit/_tests/molecule/test_state_enumeration.py +302 -0
- openff/toolkit/_tests/test_energies.py +136 -0
- openff/toolkit/_tests/test_examples.py +109 -0
- openff/toolkit/_tests/test_forcefield.py +3864 -0
- openff/toolkit/_tests/test_interchange.py +19 -0
- openff/toolkit/_tests/test_io.py +19 -0
- openff/toolkit/_tests/test_links.py +73 -0
- openff/toolkit/_tests/test_mm_molecule.py +404 -0
- openff/toolkit/_tests/test_molecule.py +4246 -0
- openff/toolkit/_tests/test_nagl.py +169 -0
- openff/toolkit/_tests/test_parameter_plugins.py +89 -0
- openff/toolkit/_tests/test_parameters.py +2898 -0
- openff/toolkit/_tests/test_toolkit_io.py +1088 -0
- openff/toolkit/_tests/test_toolkits.py +4418 -0
- openff/toolkit/_tests/test_topology.py +2485 -0
- openff/toolkit/_tests/test_utils.py +101 -0
- openff/toolkit/_tests/test_utils_callback.py +178 -0
- openff/toolkit/_tests/test_utils_collections.py +263 -0
- openff/toolkit/_tests/test_utils_serialization.py +168 -0
- openff/toolkit/_tests/utils.py +1747 -0
- openff/toolkit/data/README.md +8 -0
- openff/toolkit/data/molecules/AlkEthOH_test_filt1_ff.mol2 +2026 -0
- openff/toolkit/data/molecules/AlkEthOH_test_filt1_tripos.mol2 +2026 -0
- openff/toolkit/data/molecules/AlkEthOH_tripos.tar.gz +0 -0
- openff/toolkit/data/molecules/CID20742535_anion.sdf +50 -0
- openff/toolkit/data/molecules/CID20742535_neutral.sdf +51 -0
- openff/toolkit/data/molecules/FreeSolv.tar.gz +0 -0
- openff/toolkit/data/molecules/MiniDrugBank.sdf +33988 -0
- openff/toolkit/data/molecules/MiniDrugBank_tripos.mol2 +35462 -0
- openff/toolkit/data/molecules/PT2385.sdf +90 -0
- openff/toolkit/data/molecules/QL8.sdf +401 -0
- openff/toolkit/data/molecules/README.md +21 -0
- openff/toolkit/data/molecules/benzene.crd +8 -0
- openff/toolkit/data/molecules/benzene.mol2 +34 -0
- openff/toolkit/data/molecules/benzene.top +166 -0
- openff/toolkit/data/molecules/butane_multi.sdf +231 -0
- openff/toolkit/data/molecules/cyclohexane.mol2 +44 -0
- openff/toolkit/data/molecules/ethanol.mol2 +25 -0
- openff/toolkit/data/molecules/ethanol.sdf +23 -0
- openff/toolkit/data/molecules/ethanol_partial_charges.sdf +26 -0
- openff/toolkit/data/molecules/ethanol_reordered.mol2 +25 -0
- openff/toolkit/data/molecules/ethanol_reordered.sdf +23 -0
- openff/toolkit/data/molecules/ethene_rdkit.sdf +17 -0
- openff/toolkit/data/molecules/laromustine_ff.mol2 +71 -0
- openff/toolkit/data/molecules/laromustine_tripos.mol2 +71 -0
- openff/toolkit/data/molecules/methane_multiconformer.sdf +32 -0
- openff/toolkit/data/molecules/methane_multiconformer_properties.sdf +45 -0
- openff/toolkit/data/molecules/nh4.pdb +7 -0
- openff/toolkit/data/molecules/po4_phenylphosphate.pdb +46 -0
- openff/toolkit/data/molecules/ruxolitinib_conformers.sdf +910 -0
- openff/toolkit/data/molecules/toluene.mol2 +38 -0
- openff/toolkit/data/molecules/toluene.mol2.gz +0 -0
- openff/toolkit/data/molecules/toluene.pdb +30 -0
- openff/toolkit/data/molecules/toluene.sdf +36 -0
- openff/toolkit/data/molecules/toluene_charged.mol2 +38 -0
- openff/toolkit/data/molecules/z_3_hydroxy_propenal.sdf +23 -0
- openff/toolkit/data/proteins/5tbm_complex_solv.pdb +1928 -0
- openff/toolkit/data/proteins/5tbm_complex_solv_box.pdb +19563 -0
- openff/toolkit/data/proteins/CTerminal_ALA.pdb +20 -0
- openff/toolkit/data/proteins/CTerminal_ALA.sdf +43 -0
- openff/toolkit/data/proteins/CTerminal_ALA_ALA.pdb +30 -0
- openff/toolkit/data/proteins/CTerminal_ALA_ALA_misnamedH.pdb +30 -0
- openff/toolkit/data/proteins/CTerminal_ARG.pdb +34 -0
- openff/toolkit/data/proteins/CTerminal_TRP.pdb +34 -0
- openff/toolkit/data/proteins/MainChain_ALA.pdb +25 -0
- openff/toolkit/data/proteins/MainChain_ALA.sdf +52 -0
- openff/toolkit/data/proteins/MainChain_ALA_ALA.pdb +35 -0
- openff/toolkit/data/proteins/MainChain_ALA_ALA.sdf +69 -0
- openff/toolkit/data/proteins/MainChain_ALA_ALA_icodes.pdb +35 -0
- openff/toolkit/data/proteins/MainChain_ALA_ALA_no_hydrogens.pdb +17 -0
- openff/toolkit/data/proteins/MainChain_ARG.pdb +39 -0
- openff/toolkit/data/proteins/MainChain_ARG.sdf +81 -0
- openff/toolkit/data/proteins/MainChain_CYM.pdb +25 -0
- openff/toolkit/data/proteins/MainChain_CYS.pdb +26 -0
- openff/toolkit/data/proteins/MainChain_CYX.pdb +48 -0
- openff/toolkit/data/proteins/MainChain_CYX.sdf +96 -0
- openff/toolkit/data/proteins/MainChain_GLH.sdf +64 -0
- openff/toolkit/data/proteins/MainChain_GLU.sdf +63 -0
- openff/toolkit/data/proteins/MainChain_HID.pdb +32 -0
- openff/toolkit/data/proteins/MainChain_HIE.pdb +32 -0
- openff/toolkit/data/proteins/MainChain_HIE.sdf +67 -0
- openff/toolkit/data/proteins/MainChain_HIP.pdb +33 -0
- openff/toolkit/data/proteins/MainChain_HIP.sdf +70 -0
- openff/toolkit/data/proteins/MainChain_PRO.pdb +29 -0
- openff/toolkit/data/proteins/MainChain_TRP.pdb +39 -0
- openff/toolkit/data/proteins/NTerminal_ALA.pdb +21 -0
- openff/toolkit/data/proteins/NTerminal_ALA.sdf +45 -0
- openff/toolkit/data/proteins/NTerminal_ALA_ALA.pdb +31 -0
- openff/toolkit/data/proteins/NTerminal_ARG.pdb +35 -0
- openff/toolkit/data/proteins/NTerminal_TRP.pdb +35 -0
- openff/toolkit/data/proteins/T4-protein-unprocessed-4w51.pdb +1892 -0
- openff/toolkit/data/proteins/T4-protein.mol2 +5461 -0
- openff/toolkit/data/proteins/T4-protein.pdb +2637 -0
- openff/toolkit/data/proteins/T4-protein.sdf +5318 -0
- openff/toolkit/data/proteins/T4_protein_waters.pdb +2965 -0
- openff/toolkit/data/proteins/TwoMol_SER_CYS.pdb +50 -0
- openff/toolkit/data/proteins/aa_residues_substructures_explicit_bond_orders_with_caps.json +6435 -0
- openff/toolkit/data/proteins/aa_residues_substructures_explicit_bond_orders_with_caps_explicit_connectivity.json +6675 -0
- openff/toolkit/data/proteins/aa_residues_substructures_with_caps.json +6297 -0
- openff/toolkit/data/proteins/ace-ZZZ-gly-nme.pdb +78 -0
- openff/toolkit/data/proteins/ace-ZZZ-gly-nme.sdf +98 -0
- openff/toolkit/data/proteins/ace-a10-nme.sdf +229 -0
- openff/toolkit/data/proteins/ace-ala-nh2.pdb +21 -0
- openff/toolkit/data/proteins/fluoresceine_dyed_helix_capped.pdb +338 -0
- openff/toolkit/data/proteins/neutral_arginine.pdb +31 -0
- openff/toolkit/data/proteins/split_chain.pdb +74 -0
- openff/toolkit/data/proteins/split_chain_reordered.pdb +74 -0
- openff/toolkit/data/reference_energies/README.md +6 -0
- openff/toolkit/data/reference_energies/reference_0.8.0.json +1 -0
- openff/toolkit/data/reference_energies/reference_0.8.0.json.txt +180 -0
- openff/toolkit/data/reference_energies/reference_after_1007.json +1 -0
- openff/toolkit/data/reference_energies/reference_after_1007.json.txt +350 -0
- openff/toolkit/data/reference_energies/reference_after_802.json +1 -0
- openff/toolkit/data/reference_energies/reference_after_802.json.txt +291 -0
- openff/toolkit/data/systems/README.md +3 -0
- openff/toolkit/data/systems/amber/cyclohexane_ethanol_0.4_0.6.inpcrd +1511 -0
- openff/toolkit/data/systems/amber/cyclohexane_ethanol_0.4_0.6.prmtop +13367 -0
- openff/toolkit/data/systems/monomers/butanol.mol2 +38 -0
- openff/toolkit/data/systems/monomers/butanol.sdf +88 -0
- openff/toolkit/data/systems/monomers/cyclohexane.mol2 +45 -0
- openff/toolkit/data/systems/monomers/cyclohexane.sdf +105 -0
- openff/toolkit/data/systems/monomers/ethanol.mol2 +26 -0
- openff/toolkit/data/systems/monomers/ethanol.sdf +58 -0
- openff/toolkit/data/systems/monomers/methane.mol2 +18 -0
- openff/toolkit/data/systems/monomers/methane.sdf +38 -0
- openff/toolkit/data/systems/monomers/propane.mol2 +30 -0
- openff/toolkit/data/systems/monomers/propane.sdf +68 -0
- openff/toolkit/data/systems/monomers/tip3p_water.mol2 +14 -0
- openff/toolkit/data/systems/monomers/water.mol2 +14 -0
- openff/toolkit/data/systems/monomers/water.sdf +28 -0
- openff/toolkit/data/systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb +6272 -0
- openff/toolkit/data/systems/packmol_boxes/cyclohexane_water.pdb +5524 -0
- openff/toolkit/data/systems/packmol_boxes/ethanol_water.pdb +5174 -0
- openff/toolkit/data/systems/packmol_boxes/propane_methane_butanol_0.2_0.3_0.5.pdb +7959 -0
- openff/toolkit/data/systems/test_systems/1_cyclohexane_1_ethanol.pdb +61 -0
- openff/toolkit/data/systems/test_systems/1_ethanol.pdb +24 -0
- openff/toolkit/data/systems/test_systems/1_ethanol_no_conect.pdb +15 -0
- openff/toolkit/data/systems/test_systems/1_ethanol_reordered.pdb +24 -0
- openff/toolkit/data/systems/test_systems/PE.pdb +67 -0
- openff/toolkit/data/systems/test_systems/README.md +3 -0
- openff/toolkit/data/systems/test_systems/T4_lysozyme_water_ions.pdb +29240 -0
- openff/toolkit/data/test_forcefields/Frosst_AlkEthOH.offxml +61 -0
- openff/toolkit/data/test_forcefields/Frosst_AlkEthOH_GBSA.offxml +78 -0
- openff/toolkit/data/test_forcefields/Frosst_AlkEthOH_MDL.offxml +62 -0
- openff/toolkit/data/test_forcefields/Frosst_AlkEthOH_parmAtFrosst.offxml +64 -0
- openff/toolkit/data/test_forcefields/GBSA_HCT-1.0.offxml +21 -0
- openff/toolkit/data/test_forcefields/GBSA_OBC1-1.0.offxml +18 -0
- openff/toolkit/data/test_forcefields/GBSA_OBC2-1.0.offxml +18 -0
- openff/toolkit/data/test_forcefields/README.md +23 -0
- openff/toolkit/data/test_forcefields/ammonia_minimal.offxml +27 -0
- openff/toolkit/data/test_forcefields/benzene_minimal.offxml +29 -0
- openff/toolkit/data/test_forcefields/chargeincrement-test.offxml +16 -0
- openff/toolkit/data/test_forcefields/frcmod.Frosst_AlkEthOH_withIDs +85 -0
- openff/toolkit/data/test_forcefields/ion_charges.offxml +18 -0
- openff/toolkit/data/test_forcefields/mangled.offxml +9 -0
- openff/toolkit/data/test_forcefields/old/README.md +9 -0
- openff/toolkit/data/test_forcefields/old/hbonds.offxml +11 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_2_spec_0_1.offxml +332 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_2_spec_0_2.offxml +338 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_2_spec_0_3.offxml +329 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_fixed_spec_0_1.offxml +342 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_fixed_spec_0_2.offxml +348 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_fixed_spec_0_3.offxml +337 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_spec_0_1.offxml +340 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_spec_0_2.offxml +346 -0
- openff/toolkit/data/test_forcefields/old/test_ff_0_0_4_spec_0_3.offxml +337 -0
- openff/toolkit/data/test_forcefields/smirff99Frosst_reference_0_1_spec.offxml +349 -0
- openff/toolkit/data/test_forcefields/smirnoff99Frosst_experimental.offxml +343 -0
- openff/toolkit/data/test_forcefields/smirnoff99Frosst_reference_0_1_spec.offxml +349 -0
- openff/toolkit/data/test_forcefields/smirnoff99Frosst_reference_0_2_spec.offxml +356 -0
- openff/toolkit/data/test_forcefields/test_forcefield.offxml +346 -0
- openff/toolkit/data/test_forcefields/tip3p.offxml +22 -0
- openff/toolkit/data/test_forcefields/unsupported_smirnoff_version.offxml +9 -0
- openff/toolkit/topology/__init__.py +43 -0
- openff/toolkit/topology/_mm_molecule.py +663 -0
- openff/toolkit/topology/molecule.py +6102 -0
- openff/toolkit/topology/topology.py +2555 -0
- openff/toolkit/typing/__init__.py +1 -0
- openff/toolkit/typing/engines/__init__.py +1 -0
- openff/toolkit/typing/engines/smirnoff/__init__.py +31 -0
- openff/toolkit/typing/engines/smirnoff/forcefield.py +1440 -0
- openff/toolkit/typing/engines/smirnoff/io.py +234 -0
- openff/toolkit/typing/engines/smirnoff/parameters.py +3839 -0
- openff/toolkit/typing/engines/smirnoff/plugins.py +91 -0
- openff/toolkit/utils/__init__.py +57 -0
- openff/toolkit/utils/_viz.py +104 -0
- openff/toolkit/utils/ambertools_wrapper.py +507 -0
- openff/toolkit/utils/base_wrapper.py +268 -0
- openff/toolkit/utils/builtin_wrapper.py +136 -0
- openff/toolkit/utils/callback.py +187 -0
- openff/toolkit/utils/collections.py +247 -0
- openff/toolkit/utils/constants.py +18 -0
- openff/toolkit/utils/exceptions.py +766 -0
- openff/toolkit/utils/nagl_wrapper.py +164 -0
- openff/toolkit/utils/openeye_wrapper.py +2750 -0
- openff/toolkit/utils/rdkit_wrapper.py +3302 -0
- openff/toolkit/utils/serialization.py +466 -0
- openff/toolkit/utils/toolkit_registry.py +509 -0
- openff/toolkit/utils/toolkits.py +217 -0
- openff/toolkit/utils/utils.py +805 -0
- openff_toolkit-0.18.0.dist-info/METADATA +109 -0
- openff_toolkit-0.18.0.dist-info/RECORD +231 -0
- openff_toolkit-0.18.0.dist-info/WHEEL +5 -0
- openff_toolkit-0.18.0.dist-info/licenses/LICENSE +21 -0
- openff_toolkit-0.18.0.dist-info/top_level.txt +5 -0
- utilities/deprecated/convert_frosst/convert_frcmod_0.1.py +251 -0
- utilities/deprecated/convert_frosst/convert_frcmod_0.2.py +249 -0
- utilities/deprecated/convert_frosst/convert_frcmod_0.3.py +249 -0
- utilities/make_substructure_dict/_cif_to_substructure_dict.py +955 -0
- utilities/make_substructure_dict/_make_chemical_substructures.py +46 -0
- utilities/make_substructure_dict/_make_metadata_assignment_substructures.py +35 -0
- utilities/test_plugins/custom_plugins/handler_plugins.py +48 -0
- utilities/test_plugins/setup.py +19 -0
|
@@ -0,0 +1,2555 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Class definitions to represent a molecular system and its chemical components
|
|
3
|
+
|
|
4
|
+
.. todo::
|
|
5
|
+
|
|
6
|
+
* Create MoleculeImage, ParticleImage, AtomImage here. (Or ``MoleculeInstance``?)
|
|
7
|
+
* Create ``MoleculeGraph`` to represent fozen set of atom elements and bonds that can used as a key for compression
|
|
8
|
+
* Add hierarchical way of traversing Topology (chains, residues)
|
|
9
|
+
* Make all classes hashable and serializable.
|
|
10
|
+
* JSON/BSON representations of objects?
|
|
11
|
+
* Use `attrs <http://www.attrs.org/>`_ for object setter boilerplate?
|
|
12
|
+
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from collections import defaultdict
|
|
17
|
+
from collections.abc import Generator, Iterable, Iterator, MutableMapping
|
|
18
|
+
from contextlib import nullcontext
|
|
19
|
+
from copy import deepcopy
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import (
|
|
22
|
+
TYPE_CHECKING,
|
|
23
|
+
Literal,
|
|
24
|
+
TextIO,
|
|
25
|
+
TypeAlias,
|
|
26
|
+
Union,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
from numpy.typing import NDArray
|
|
31
|
+
from openff.units import Unit
|
|
32
|
+
|
|
33
|
+
from openff.toolkit import Quantity, unit
|
|
34
|
+
from openff.toolkit.topology import Molecule
|
|
35
|
+
from openff.toolkit.topology._mm_molecule import (
|
|
36
|
+
_SimpleAtom,
|
|
37
|
+
_SimpleBond,
|
|
38
|
+
_SimpleMolecule,
|
|
39
|
+
)
|
|
40
|
+
from openff.toolkit.topology.molecule import FrozenMolecule, HierarchyElement
|
|
41
|
+
from openff.toolkit.utils import quantity_to_string, string_to_quantity
|
|
42
|
+
from openff.toolkit.utils.constants import (
|
|
43
|
+
ALLOWED_AROMATICITY_MODELS,
|
|
44
|
+
DEFAULT_AROMATICITY_MODEL,
|
|
45
|
+
)
|
|
46
|
+
from openff.toolkit.utils.exceptions import (
|
|
47
|
+
AtomNotInTopologyError,
|
|
48
|
+
BondNotInTopologyError,
|
|
49
|
+
ConstraintExsistsError,
|
|
50
|
+
DuplicateUniqueMoleculeError,
|
|
51
|
+
IncompatibleUnitError,
|
|
52
|
+
InvalidAromaticityModelError,
|
|
53
|
+
InvalidBoxVectorsError,
|
|
54
|
+
InvalidPeriodicityError,
|
|
55
|
+
MissingConformersError,
|
|
56
|
+
MissingUniqueMoleculesError,
|
|
57
|
+
MoleculeNotInTopologyError,
|
|
58
|
+
NotBondedError,
|
|
59
|
+
VirtualSitesUnsupportedError,
|
|
60
|
+
WrongShapeError,
|
|
61
|
+
)
|
|
62
|
+
from openff.toolkit.utils.serialization import Serializable
|
|
63
|
+
from openff.toolkit.utils.toolkits import GLOBAL_TOOLKIT_REGISTRY
|
|
64
|
+
from openff.toolkit.utils.utils import get_data_file_path, requires_package
|
|
65
|
+
|
|
66
|
+
if TYPE_CHECKING:
|
|
67
|
+
import mdtraj
|
|
68
|
+
import openmm.app
|
|
69
|
+
from networkx import Graph
|
|
70
|
+
from nglview import NGLWidget
|
|
71
|
+
from openmm.unit import Quantity as OMMQuantity
|
|
72
|
+
|
|
73
|
+
from openff.toolkit.topology.molecule import Atom, Bond
|
|
74
|
+
from openff.toolkit.utils import ToolkitRegistry, ToolkitWrapper
|
|
75
|
+
|
|
76
|
+
TKR: TypeAlias = Union["ToolkitRegistry", "ToolkitWrapper"]
|
|
77
|
+
MoleculeLike: TypeAlias = Union["Molecule", "FrozenMolecule", "_SimpleMolecule"]
|
|
78
|
+
|
|
79
|
+
_DISTANCE_UNITS = set(
|
|
80
|
+
[
|
|
81
|
+
Unit(val)
|
|
82
|
+
for val in [
|
|
83
|
+
"nanometer",
|
|
84
|
+
"angstrom",
|
|
85
|
+
"micron",
|
|
86
|
+
"bohr",
|
|
87
|
+
"meter",
|
|
88
|
+
"fermi",
|
|
89
|
+
]
|
|
90
|
+
]
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class _TransformedDict(MutableMapping):
|
|
95
|
+
"""A dictionary that transform and sort keys.
|
|
96
|
+
|
|
97
|
+
The function __keytransform__ can be inherited to apply an arbitrary
|
|
98
|
+
key-altering function before accessing the keys.
|
|
99
|
+
|
|
100
|
+
The function __sortfunc__ can be inherited to specify a particular
|
|
101
|
+
order over which to iterate over the dictionary.
|
|
102
|
+
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def __init__(self, *args, **kwargs):
|
|
106
|
+
self.store = dict()
|
|
107
|
+
self.update(dict(*args, **kwargs)) # use the free update to set keys
|
|
108
|
+
|
|
109
|
+
def __getitem__(self, key):
|
|
110
|
+
return self.store[self.__keytransform__(key)]
|
|
111
|
+
|
|
112
|
+
def __setitem__(self, key, value):
|
|
113
|
+
self.store[self.__keytransform__(key)] = value
|
|
114
|
+
|
|
115
|
+
def __delitem__(self, key):
|
|
116
|
+
del self.store[self.__keytransform__(key)]
|
|
117
|
+
|
|
118
|
+
def __iter__(self):
|
|
119
|
+
return iter(sorted(self.store, key=self.__sortfunc__))
|
|
120
|
+
|
|
121
|
+
def __len__(self):
|
|
122
|
+
return len(self.store)
|
|
123
|
+
|
|
124
|
+
def __keytransform__(self, key):
|
|
125
|
+
return key
|
|
126
|
+
|
|
127
|
+
@staticmethod
|
|
128
|
+
def __sortfunc__(key):
|
|
129
|
+
return key
|
|
130
|
+
|
|
131
|
+
@classmethod
|
|
132
|
+
def _return_possible_index_of(cls, key, possible, permutations):
|
|
133
|
+
"""
|
|
134
|
+
Returns canonical ordering of ``key``, given a dictionary of ordered
|
|
135
|
+
``permutations`` and a list of allowed orders ``possible``.
|
|
136
|
+
|
|
137
|
+
Parameters
|
|
138
|
+
----------
|
|
139
|
+
key: tuple of int
|
|
140
|
+
A key of indices
|
|
141
|
+
possible: list of tuples of int
|
|
142
|
+
List of possible keys
|
|
143
|
+
permutations: dict[tuple[int, ...], int]
|
|
144
|
+
Dictionary of canonical orders
|
|
145
|
+
"""
|
|
146
|
+
key = tuple(key)
|
|
147
|
+
possible = [tuple(p) for p in possible]
|
|
148
|
+
impossible = [p for p in possible if p not in permutations]
|
|
149
|
+
if impossible:
|
|
150
|
+
raise ValueError(f"Impossible permutations {impossible} for key {key}!")
|
|
151
|
+
possible_permutations = [k for k in permutations if k in possible]
|
|
152
|
+
for i, permutation in enumerate(possible_permutations):
|
|
153
|
+
if key == permutation:
|
|
154
|
+
return i
|
|
155
|
+
raise ValueError(f"key {key} not in possible {possible}")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# TODO: Encapsulate this atom ordering logic directly into Atom/Bond/Angle/Torsion classes?
|
|
159
|
+
class ValenceDict(_TransformedDict):
|
|
160
|
+
"""Enforce uniqueness in atom indices."""
|
|
161
|
+
|
|
162
|
+
@staticmethod
|
|
163
|
+
def key_transform(key):
|
|
164
|
+
"""Reverse tuple if first element is larger than last element."""
|
|
165
|
+
key = tuple(key)
|
|
166
|
+
if key[0] > key[-1]:
|
|
167
|
+
key = tuple(reversed(key))
|
|
168
|
+
return key
|
|
169
|
+
|
|
170
|
+
@classmethod
|
|
171
|
+
def index_of(
|
|
172
|
+
cls,
|
|
173
|
+
key: Iterable[int],
|
|
174
|
+
possible: Iterable[Iterable[int]] | None = None,
|
|
175
|
+
) -> int:
|
|
176
|
+
"""
|
|
177
|
+
Generates a canonical ordering of the equivalent permutations of ``key`` (equivalent rearrangements of indices)
|
|
178
|
+
and identifies which of those possible orderings this particular ordering is. This method is useful when
|
|
179
|
+
multiple SMARTS patterns might match the same atoms, but local molecular symmetry or the use of
|
|
180
|
+
wildcards in the SMARTS could make the matches occur in arbitrary order.
|
|
181
|
+
|
|
182
|
+
This method can be restricted to a subset of the canonical orderings, by providing
|
|
183
|
+
the optional ``possible`` keyword argument. If provided, the index returned by this method will be
|
|
184
|
+
the index of the element in ``possible`` after undergoing the same canonical sorting as above.
|
|
185
|
+
|
|
186
|
+
Parameters
|
|
187
|
+
----------
|
|
188
|
+
key
|
|
189
|
+
A valid key for ValenceDict
|
|
190
|
+
possible
|
|
191
|
+
A subset of the possible orderings that this match might take.
|
|
192
|
+
|
|
193
|
+
Returns
|
|
194
|
+
-------
|
|
195
|
+
index
|
|
196
|
+
"""
|
|
197
|
+
refkey = cls.key_transform(key)
|
|
198
|
+
permutations = {refkey: 0, refkey[::-1]: 1}
|
|
199
|
+
if possible is not None:
|
|
200
|
+
return cls._return_possible_index_of(key, possible=possible, permutations=permutations)
|
|
201
|
+
else:
|
|
202
|
+
return permutations[tuple(key)]
|
|
203
|
+
|
|
204
|
+
def __keytransform__(self, key):
|
|
205
|
+
return self.key_transform(key)
|
|
206
|
+
|
|
207
|
+
def __repr__(self):
|
|
208
|
+
return f"ValenceDict({ {k: v for k, v in self.items()}!r})"
|
|
209
|
+
|
|
210
|
+
def _repr_pretty_(self, p, cycle):
|
|
211
|
+
if cycle:
|
|
212
|
+
p.text("ValenceDict(...)")
|
|
213
|
+
else:
|
|
214
|
+
with p.group(2, "ValenceDict(", ")"):
|
|
215
|
+
p.breakable("")
|
|
216
|
+
p.pretty({k: v for k, v in self.items()})
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class SortedDict(_TransformedDict):
|
|
220
|
+
"""Enforce uniqueness of atom index tuples, without any restrictions on atom reordering."""
|
|
221
|
+
|
|
222
|
+
def __keytransform__(self, key):
|
|
223
|
+
"""Sort tuple from lowest to highest."""
|
|
224
|
+
key = tuple(sorted(key))
|
|
225
|
+
return key
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class UnsortedDict(_TransformedDict):
|
|
229
|
+
pass
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class TagSortedDict(_TransformedDict):
|
|
233
|
+
"""
|
|
234
|
+
A dictionary where keys, consisting of tuples of atom indices, are kept unsorted, but only allows one permutation
|
|
235
|
+
of a key to exist. Certain situations require that atom indices are not transformed in any way, such as when the
|
|
236
|
+
tagged order of a match is needed downstream. For example a parameter using charge increments needs the ordering of
|
|
237
|
+
the tagged match, and so transforming the atom indices in any way will cause that information to be lost.
|
|
238
|
+
|
|
239
|
+
Because deduplication is needed, we still must avoid the expected situation
|
|
240
|
+
where we must not allow two permutations of the same atoms to coexist. For example,
|
|
241
|
+
a parameter may have matched the indices (2, 0, 1), however a parameter with higher
|
|
242
|
+
priority also matches the same indices, but the tagged order is (1, 0, 2). We need
|
|
243
|
+
to make sure both keys don't exist, or else two parameters will apply to
|
|
244
|
+
the same atoms. We allow the ability to query using either permutation and get
|
|
245
|
+
identical behavior. The defining feature here, then, is that the stored indices are
|
|
246
|
+
in tagged order, but one can supply any permutation and it will resolve to the
|
|
247
|
+
stored value/parameter.
|
|
248
|
+
|
|
249
|
+
As a subtle behavior, one must be careful if an external key is used that was not
|
|
250
|
+
supplied from the TagSortedDict object itself. For example:
|
|
251
|
+
|
|
252
|
+
>>> x = TagSortedDict({(2, 5, 0): 100})
|
|
253
|
+
>>> y = x[(5, 0, 2)]
|
|
254
|
+
|
|
255
|
+
The variable y will be 100, but this does not mean the tagged order is (5, 0, 2)
|
|
256
|
+
as it was supplied from the external tuple. One should either use keys only from
|
|
257
|
+
__iter__ (e.g. `for k in x`) or one must transform the key:
|
|
258
|
+
|
|
259
|
+
>>> key = (5, 0, 2)
|
|
260
|
+
>>> y = x[key]
|
|
261
|
+
>>> key = x.key_transform(key)
|
|
262
|
+
|
|
263
|
+
Where `key` will now be `(2, 5, 0)`, as it is the key stored. One can overwrite
|
|
264
|
+
this key with the new one as expected:
|
|
265
|
+
|
|
266
|
+
>>> key = (5, 0, 2)
|
|
267
|
+
>>> x[key] = 50
|
|
268
|
+
|
|
269
|
+
Now the key `(2, 5, 0)` will no longer exist, as it was replaced with `(5, 0, 2)`.
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
def __init__(self, *args, **kwargs):
|
|
273
|
+
# Because keytransform is O(n) due to needing to check the sorted keys,
|
|
274
|
+
# we cache the sorted keys separately to make keytransform O(1) at
|
|
275
|
+
# the expense of storage. This is also better in the long run if the
|
|
276
|
+
# key is long and repeatedly sorting isn't a negligible cost.
|
|
277
|
+
|
|
278
|
+
# Set this before calling super init, since super will call the get/set
|
|
279
|
+
# methods implemented here as it populates self via args/kwargs,
|
|
280
|
+
# which will automatically populate _sorted
|
|
281
|
+
self._sorted = SortedDict()
|
|
282
|
+
|
|
283
|
+
super().__init__(*args, **kwargs)
|
|
284
|
+
|
|
285
|
+
def __setitem__(self, key, value):
|
|
286
|
+
"""
|
|
287
|
+
Set the key to value, but only allow one permutation of key to exist. The
|
|
288
|
+
key argument will replace the old permutation:value if it exists.
|
|
289
|
+
"""
|
|
290
|
+
key = tuple(key)
|
|
291
|
+
tr_key = self.__keytransform__(key)
|
|
292
|
+
if key != tr_key:
|
|
293
|
+
# this means our new key is a permutation of an existing, so we should
|
|
294
|
+
# replace it
|
|
295
|
+
del self.store[tr_key]
|
|
296
|
+
self.store[key] = value
|
|
297
|
+
# save the sorted version for faster keytransform
|
|
298
|
+
self._sorted[key] = key
|
|
299
|
+
|
|
300
|
+
def __keytransform__(self, key):
|
|
301
|
+
"""Give the key permutation that is currently stored"""
|
|
302
|
+
# we check if there is a permutation clash by saving the sorted version of
|
|
303
|
+
# each key. If the sorted version of the key exists, then the return value
|
|
304
|
+
# corresponds to the explicit permutation we are storing in self (the public
|
|
305
|
+
# facing key). This permutation may or may not be the same as the key argument
|
|
306
|
+
# supplied. If the key is not present, then no transformation should be done
|
|
307
|
+
# and we should return the key as is.
|
|
308
|
+
|
|
309
|
+
# As stated in __init__, the alternative is to, on each call, sort the saved
|
|
310
|
+
# permutations and check if it is equal to the sorted supplied key. In this
|
|
311
|
+
# sense, self._sorted is a cache/lookup table.
|
|
312
|
+
key = tuple(key)
|
|
313
|
+
return self._sorted.get(key, key)
|
|
314
|
+
|
|
315
|
+
def key_transform(self, key):
|
|
316
|
+
key = tuple(key)
|
|
317
|
+
return self.__keytransform__(key)
|
|
318
|
+
|
|
319
|
+
def clear(self):
|
|
320
|
+
"""
|
|
321
|
+
Clear the contents
|
|
322
|
+
"""
|
|
323
|
+
self.store.clear()
|
|
324
|
+
self._sorted.clear()
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
class ImproperDict(_TransformedDict):
|
|
328
|
+
"""Symmetrize improper torsions."""
|
|
329
|
+
|
|
330
|
+
@staticmethod
|
|
331
|
+
def key_transform(key):
|
|
332
|
+
"""
|
|
333
|
+
Reorder tuple in numerical order except for element[1] which is the central atom; it retains its position.
|
|
334
|
+
"""
|
|
335
|
+
# Ensure key is a tuple
|
|
336
|
+
key = tuple(key)
|
|
337
|
+
assert len(key) == 4, "Improper keys must be 4 atoms"
|
|
338
|
+
# Retrieve connected atoms
|
|
339
|
+
connectedatoms = [key[0], key[2], key[3]]
|
|
340
|
+
# Sort connected atoms
|
|
341
|
+
connectedatoms.sort()
|
|
342
|
+
# Re-store connected atoms
|
|
343
|
+
key = tuple([connectedatoms[0], key[1], connectedatoms[1], connectedatoms[2]])
|
|
344
|
+
return key
|
|
345
|
+
|
|
346
|
+
@classmethod
|
|
347
|
+
def index_of(cls, key, possible=None):
|
|
348
|
+
"""
|
|
349
|
+
Generates a canonical ordering of the equivalent permutations of ``key`` (equivalent rearrangements of indices)
|
|
350
|
+
and identifies which of those possible orderings this particular ordering is. This method is useful when
|
|
351
|
+
multiple SMARTS patterns might match the same atoms, but local molecular symmetry or the use of wildcards in
|
|
352
|
+
the SMARTS could make the matches occur in arbitrary order.
|
|
353
|
+
|
|
354
|
+
This method can be restricted to a subset of the canonical orderings, by providing the optional ``possible``
|
|
355
|
+
keyword argument. If provided, the index returned by this method will be the index of the element in
|
|
356
|
+
``possible`` after undergoing the same canonical sorting as above.
|
|
357
|
+
|
|
358
|
+
Parameters
|
|
359
|
+
----------
|
|
360
|
+
key
|
|
361
|
+
A valid key for ValenceDict
|
|
362
|
+
possible
|
|
363
|
+
A subset of the possible orderings that this match might take.
|
|
364
|
+
|
|
365
|
+
Returns
|
|
366
|
+
-------
|
|
367
|
+
index
|
|
368
|
+
"""
|
|
369
|
+
key = tuple(key)
|
|
370
|
+
assert len(key) == 4
|
|
371
|
+
refkey = cls.key_transform(key)
|
|
372
|
+
permutations = {
|
|
373
|
+
(refkey[0], refkey[1], refkey[2], refkey[3]): 0,
|
|
374
|
+
(refkey[0], refkey[1], refkey[3], refkey[2]): 1,
|
|
375
|
+
(refkey[2], refkey[1], refkey[0], refkey[3]): 2,
|
|
376
|
+
(refkey[2], refkey[1], refkey[3], refkey[0]): 3,
|
|
377
|
+
(refkey[3], refkey[1], refkey[0], refkey[2]): 4,
|
|
378
|
+
(refkey[3], refkey[1], refkey[2], refkey[0]): 5,
|
|
379
|
+
}
|
|
380
|
+
if possible is not None:
|
|
381
|
+
return cls._return_possible_index_of(key, possible=possible, permutations=permutations)
|
|
382
|
+
else:
|
|
383
|
+
return permutations[key]
|
|
384
|
+
|
|
385
|
+
def __keytransform__(self, key):
|
|
386
|
+
return __class__.key_transform(key)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
class Topology(Serializable):
|
|
390
|
+
"""
|
|
391
|
+
A Topology is a chemical representation of a system containing one or more molecules appearing in a specified
|
|
392
|
+
order.
|
|
393
|
+
|
|
394
|
+
.. warning :: This API is experimental and subject to change.
|
|
395
|
+
|
|
396
|
+
Examples
|
|
397
|
+
--------
|
|
398
|
+
|
|
399
|
+
Import some utilities
|
|
400
|
+
|
|
401
|
+
>>> from openmm import app
|
|
402
|
+
>>> from openff.toolkit._tests.utils import get_data_file_path, get_packmol_pdb_file_path
|
|
403
|
+
>>> pdb_filepath = get_packmol_pdb_file_path('cyclohexane_ethanol_0.4_0.6')
|
|
404
|
+
>>> monomer_names = ('cyclohexane', 'ethanol')
|
|
405
|
+
|
|
406
|
+
Create a Topology object from a PDB file and sdf files defining the molecular contents
|
|
407
|
+
|
|
408
|
+
>>> from openff.toolkit import Molecule, Topology
|
|
409
|
+
>>> pdbfile = app.PDBFile(pdb_filepath)
|
|
410
|
+
>>> sdf_filepaths = [get_data_file_path(f'systems/monomers/{name}.sdf') for name in monomer_names]
|
|
411
|
+
>>> unique_molecules = [Molecule.from_file(sdf_filepath) for sdf_filepath in sdf_filepaths]
|
|
412
|
+
>>> topology = Topology.from_openmm(pdbfile.topology, unique_molecules=unique_molecules)
|
|
413
|
+
|
|
414
|
+
Create a Topology object from a PDB file and IUPAC names of the molecular contents
|
|
415
|
+
|
|
416
|
+
>>> pdbfile = app.PDBFile(pdb_filepath)
|
|
417
|
+
>>> unique_molecules = [Molecule.from_iupac(name) for name in monomer_names]
|
|
418
|
+
>>> topology = Topology.from_openmm(pdbfile.topology, unique_molecules=unique_molecules)
|
|
419
|
+
|
|
420
|
+
Create an empty Topology object and add a few copies of a single benzene molecule
|
|
421
|
+
|
|
422
|
+
>>> topology = Topology()
|
|
423
|
+
>>> molecule = Molecule.from_iupac('benzene')
|
|
424
|
+
>>> molecule_topology_indices = [topology.add_molecule(molecule) for index in range(10)]
|
|
425
|
+
|
|
426
|
+
"""
|
|
427
|
+
|
|
428
|
+
_constrained_atom_pairs: dict[tuple[int, int], Quantity | bool]
|
|
429
|
+
|
|
430
|
+
def __init__(self, other=None):
|
|
431
|
+
"""
|
|
432
|
+
Create a new Topology.
|
|
433
|
+
|
|
434
|
+
Parameters
|
|
435
|
+
----------
|
|
436
|
+
other
|
|
437
|
+
If specified, attempt to construct a copy of the Topology from the specified object.
|
|
438
|
+
This might be a Topology object, or a file that can be used to construct a Topology object
|
|
439
|
+
or serialized Topology object.
|
|
440
|
+
|
|
441
|
+
"""
|
|
442
|
+
# Assign cheminformatics models
|
|
443
|
+
self._aromaticity_model = DEFAULT_AROMATICITY_MODEL
|
|
444
|
+
|
|
445
|
+
# Initialize storage
|
|
446
|
+
self._initialize()
|
|
447
|
+
|
|
448
|
+
# TODO: Try to construct Topology copy from `other` if specified
|
|
449
|
+
if isinstance(other, Topology):
|
|
450
|
+
self.copy_initializer(other)
|
|
451
|
+
elif isinstance(other, FrozenMolecule):
|
|
452
|
+
self.from_molecules([other])
|
|
453
|
+
elif isinstance(other, dict):
|
|
454
|
+
self._initialize_from_dict(other)
|
|
455
|
+
|
|
456
|
+
def _initialize(self):
|
|
457
|
+
"""
|
|
458
|
+
Initializes a blank Topology.
|
|
459
|
+
"""
|
|
460
|
+
self._constrained_atom_pairs = dict()
|
|
461
|
+
self._box_vectors = None
|
|
462
|
+
self._molecules = list()
|
|
463
|
+
self._cached_chemically_identical_molecules = None
|
|
464
|
+
|
|
465
|
+
def __iadd__(self, other):
|
|
466
|
+
"""Add two Topology objects in-place.
|
|
467
|
+
|
|
468
|
+
This method has the following effects:
|
|
469
|
+
* The cache (_cached_chemically_identical_molecules) is reset
|
|
470
|
+
* The constrained atom pairs (Topology.constrained_atom_pairs) is reset
|
|
471
|
+
* Box vectors are **not** updated.
|
|
472
|
+
|
|
473
|
+
"""
|
|
474
|
+
if self.aromaticity_model != other.aromaticity_model:
|
|
475
|
+
raise InvalidAromaticityModelError(
|
|
476
|
+
"Mismatch in aromaticity models. Trying to add a Topology with aromaticity model "
|
|
477
|
+
f"{other.aromaticity_model} to a Topology with aromaticity model "
|
|
478
|
+
f"{self.aromaticity_model}"
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
self._cached_chemically_identical_molecules = None
|
|
482
|
+
|
|
483
|
+
constrained_atom_pairs_to_add = other.constrained_atom_pairs
|
|
484
|
+
atom_index_offset = self.n_atoms
|
|
485
|
+
|
|
486
|
+
for molecule in other.molecules:
|
|
487
|
+
self._add_molecule_keep_cache(molecule)
|
|
488
|
+
self._invalidate_cached_properties()
|
|
489
|
+
|
|
490
|
+
for key, value in constrained_atom_pairs_to_add.items():
|
|
491
|
+
new_key = tuple(index + atom_index_offset for index in key)
|
|
492
|
+
self._constrained_atom_pairs[new_key] = value
|
|
493
|
+
|
|
494
|
+
return self
|
|
495
|
+
|
|
496
|
+
def __add__(self, other):
|
|
497
|
+
"""Add two Topology objects. See Topology.__iadd__ for details."""
|
|
498
|
+
combined = deepcopy(self)
|
|
499
|
+
combined += other
|
|
500
|
+
|
|
501
|
+
return combined
|
|
502
|
+
|
|
503
|
+
@property
|
|
504
|
+
def unique_molecules(self) -> Iterator[Molecule | _SimpleMolecule]:
|
|
505
|
+
"""
|
|
506
|
+
Get a list of chemically unique molecules in this Topology.
|
|
507
|
+
|
|
508
|
+
Molecules are considered unique if they fail an isomorphism check with
|
|
509
|
+
default values (see :meth:`Molecule.is_isomorphic_with`).
|
|
510
|
+
The order of molecules returned by this property is arbitrary.
|
|
511
|
+
"""
|
|
512
|
+
for mol_idx in self.identical_molecule_groups.keys():
|
|
513
|
+
yield deepcopy(self.molecule(mol_idx))
|
|
514
|
+
|
|
515
|
+
@property
|
|
516
|
+
def n_unique_molecules(self) -> int:
|
|
517
|
+
"""Returns the number of unique molecules in this Topology"""
|
|
518
|
+
return len(self.identical_molecule_groups)
|
|
519
|
+
|
|
520
|
+
@classmethod
|
|
521
|
+
def from_molecules(
|
|
522
|
+
cls,
|
|
523
|
+
molecules: MoleculeLike | Iterable[MoleculeLike],
|
|
524
|
+
) -> "Topology":
|
|
525
|
+
"""
|
|
526
|
+
Create a new Topology object containing one copy of each of the specified molecule(s).
|
|
527
|
+
|
|
528
|
+
Parameters
|
|
529
|
+
----------
|
|
530
|
+
molecules
|
|
531
|
+
One or more molecules to be added to the Topology
|
|
532
|
+
|
|
533
|
+
Returns
|
|
534
|
+
-------
|
|
535
|
+
topology
|
|
536
|
+
The Topology created from the specified molecule(s)
|
|
537
|
+
"""
|
|
538
|
+
# Ensure that we are working with an iterable
|
|
539
|
+
if isinstance(molecules, FrozenMolecule | _SimpleMolecule):
|
|
540
|
+
molecules = [molecules]
|
|
541
|
+
|
|
542
|
+
# Create Topology and populate it with specified molecules
|
|
543
|
+
topology = cls()
|
|
544
|
+
for molecule in molecules:
|
|
545
|
+
topology._add_molecule_keep_cache(molecule)
|
|
546
|
+
topology._invalidate_cached_properties()
|
|
547
|
+
|
|
548
|
+
return topology
|
|
549
|
+
|
|
550
|
+
def assert_bonded(self, atom1: Union[int, "Atom"], atom2: Union[int, "Atom"]):
|
|
551
|
+
"""
|
|
552
|
+
Raise an exception if the specified atoms are not bonded in the topology.
|
|
553
|
+
|
|
554
|
+
Parameters
|
|
555
|
+
----------
|
|
556
|
+
atom1, atom2
|
|
557
|
+
The atoms or atom topology indices to check to ensure they are bonded
|
|
558
|
+
|
|
559
|
+
"""
|
|
560
|
+
if isinstance(atom1, int) and isinstance(atom2, int):
|
|
561
|
+
atom1 = self.atom(atom1)
|
|
562
|
+
atom2 = self.atom(atom2)
|
|
563
|
+
|
|
564
|
+
if not (self.is_bonded(atom1, atom2)):
|
|
565
|
+
# TODO: Raise more specific exception.
|
|
566
|
+
raise NotBondedError(f"Atoms {atom1} and {atom2} are not bonded in topology")
|
|
567
|
+
|
|
568
|
+
@property
|
|
569
|
+
def aromaticity_model(self) -> str:
|
|
570
|
+
"""
|
|
571
|
+
Get the aromaticity model applied to all molecules in the topology.
|
|
572
|
+
|
|
573
|
+
Returns
|
|
574
|
+
-------
|
|
575
|
+
aromaticity_model
|
|
576
|
+
Aromaticity model in use.
|
|
577
|
+
"""
|
|
578
|
+
return self._aromaticity_model
|
|
579
|
+
|
|
580
|
+
@aromaticity_model.setter
|
|
581
|
+
def aromaticity_model(self, aromaticity_model):
|
|
582
|
+
"""
|
|
583
|
+
Set the aromaticity model applied to all molecules in the topology.
|
|
584
|
+
|
|
585
|
+
Parameters
|
|
586
|
+
----------
|
|
587
|
+
aromaticity_model
|
|
588
|
+
Aromaticity model to use. One of: ['OEAroModel_MDL']
|
|
589
|
+
"""
|
|
590
|
+
if aromaticity_model not in ALLOWED_AROMATICITY_MODELS:
|
|
591
|
+
raise InvalidAromaticityModelError(
|
|
592
|
+
f"Read aromaticity model {aromaticity_model} which is not in the set of allowed aromaticity models: "
|
|
593
|
+
f"{ALLOWED_AROMATICITY_MODELS}."
|
|
594
|
+
)
|
|
595
|
+
|
|
596
|
+
self._aromaticity_model = aromaticity_model
|
|
597
|
+
|
|
598
|
+
@property
|
|
599
|
+
def box_vectors(self):
|
|
600
|
+
"""Return the box vectors of the topology, if specified
|
|
601
|
+
|
|
602
|
+
Returns
|
|
603
|
+
-------
|
|
604
|
+
box_vectors
|
|
605
|
+
The unit-wrapped box vectors of this topology
|
|
606
|
+
"""
|
|
607
|
+
return self._box_vectors
|
|
608
|
+
|
|
609
|
+
@box_vectors.setter
|
|
610
|
+
def box_vectors(self, box_vectors):
|
|
611
|
+
"""
|
|
612
|
+
Sets the box vectors to be used for this topology.
|
|
613
|
+
|
|
614
|
+
Parameters
|
|
615
|
+
----------
|
|
616
|
+
box_vectors
|
|
617
|
+
The unit-wrapped box vectors
|
|
618
|
+
|
|
619
|
+
"""
|
|
620
|
+
if box_vectors is None:
|
|
621
|
+
self._box_vectors = None
|
|
622
|
+
return
|
|
623
|
+
if not hasattr(box_vectors, "units"):
|
|
624
|
+
if hasattr(box_vectors, "unit"):
|
|
625
|
+
from openff.units import ensure_quantity
|
|
626
|
+
|
|
627
|
+
# this is probably an openmm.unit.Quantity; we should gracefully import OpenMM but
|
|
628
|
+
# the chances of this being an object with the two previous conditions met is low
|
|
629
|
+
box_vectors = ensure_quantity(box_vectors, "openff")
|
|
630
|
+
|
|
631
|
+
else:
|
|
632
|
+
raise InvalidBoxVectorsError("Given unitless box vectors")
|
|
633
|
+
|
|
634
|
+
if box_vectors.units not in _DISTANCE_UNITS:
|
|
635
|
+
raise InvalidBoxVectorsError(f"Cannot set box vectors with quantities with unit {box_vectors.units}")
|
|
636
|
+
|
|
637
|
+
if hasattr(box_vectors, "shape"):
|
|
638
|
+
if box_vectors.shape == (3,):
|
|
639
|
+
# Cannot multiply in-place without ufunc support in Pint
|
|
640
|
+
box_vectors = box_vectors * np.eye(3)
|
|
641
|
+
if box_vectors.shape != (3, 3):
|
|
642
|
+
raise InvalidBoxVectorsError(f"Box vectors must be shape (3, 3). Found shape {box_vectors.shape}")
|
|
643
|
+
else:
|
|
644
|
+
raise InvalidBoxVectorsError(f"Cannot set box vectors with object of type {type(box_vectors)}")
|
|
645
|
+
|
|
646
|
+
self._box_vectors = box_vectors
|
|
647
|
+
|
|
648
|
+
@property
|
|
649
|
+
def is_periodic(self) -> bool:
|
|
650
|
+
"""Return whether or not this Topology is intended to be described with periodic
|
|
651
|
+
boundary conditions."""
|
|
652
|
+
return self.box_vectors is not None
|
|
653
|
+
|
|
654
|
+
@is_periodic.setter
|
|
655
|
+
def is_periodic(self, is_periodic: bool):
|
|
656
|
+
"""
|
|
657
|
+
Set whether or not this topology is periodic.
|
|
658
|
+
|
|
659
|
+
Parameters
|
|
660
|
+
----------
|
|
661
|
+
is_periodic
|
|
662
|
+
Whether or not this Topology is periodici
|
|
663
|
+
|
|
664
|
+
"""
|
|
665
|
+
if is_periodic is True and self.box_vectors is None:
|
|
666
|
+
raise InvalidPeriodicityError(
|
|
667
|
+
"Cannot set is_periodic to True without box vectors. Set box vectors directly instead."
|
|
668
|
+
)
|
|
669
|
+
if is_periodic is False and self.box_vectors is not None:
|
|
670
|
+
raise InvalidPeriodicityError(
|
|
671
|
+
"Cannot set is_periodic to False while box vectors are stored. First set box_vectors to None."
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
@property
|
|
675
|
+
def constrained_atom_pairs(self) -> dict[tuple[int, int], Quantity | bool]:
|
|
676
|
+
"""Returns the constrained atom pairs of the Topology
|
|
677
|
+
|
|
678
|
+
Returns
|
|
679
|
+
-------
|
|
680
|
+
constrained_atom_pairs
|
|
681
|
+
dictionary of the form {(atom1_topology_index, atom2_topology_index): distance}
|
|
682
|
+
"""
|
|
683
|
+
return self._constrained_atom_pairs
|
|
684
|
+
|
|
685
|
+
@property
|
|
686
|
+
def n_molecules(self) -> int:
|
|
687
|
+
"""Returns the number of molecules in this Topology"""
|
|
688
|
+
return len(self._molecules)
|
|
689
|
+
|
|
690
|
+
@property
|
|
691
|
+
def molecules(self) -> Iterator[MoleculeLike]:
|
|
692
|
+
"""Returns an iterator over all the Molecules in this Topology
|
|
693
|
+
|
|
694
|
+
Returns
|
|
695
|
+
-------
|
|
696
|
+
molecules
|
|
697
|
+
"""
|
|
698
|
+
# Yields instead of returning the list itself. This prevents user from modifying the list
|
|
699
|
+
# outside the Topology's knowledge. This is essential to make sure that atom index caches
|
|
700
|
+
# invalidate themselves during appropriate events.
|
|
701
|
+
yield from self._molecules
|
|
702
|
+
|
|
703
|
+
def molecule(self, index: int) -> Molecule | _SimpleMolecule:
|
|
704
|
+
"""
|
|
705
|
+
Returns the molecule with a given index in this Topology.
|
|
706
|
+
|
|
707
|
+
Returns
|
|
708
|
+
-------
|
|
709
|
+
molecule
|
|
710
|
+
"""
|
|
711
|
+
return self._molecules[index]
|
|
712
|
+
|
|
713
|
+
@property
|
|
714
|
+
def n_atoms(self) -> int:
|
|
715
|
+
"""
|
|
716
|
+
Returns the number of atoms in in this Topology.
|
|
717
|
+
|
|
718
|
+
Returns
|
|
719
|
+
-------
|
|
720
|
+
n_atoms
|
|
721
|
+
"""
|
|
722
|
+
n_atoms = 0
|
|
723
|
+
for molecule in self.molecules:
|
|
724
|
+
n_atoms += molecule.n_atoms
|
|
725
|
+
return n_atoms
|
|
726
|
+
|
|
727
|
+
@property
|
|
728
|
+
def atoms(self) -> Generator["Atom", None, None]:
|
|
729
|
+
"""Returns an iterator over the atoms in this Topology. These will be in ascending order of topology index.
|
|
730
|
+
|
|
731
|
+
Returns
|
|
732
|
+
-------
|
|
733
|
+
atoms
|
|
734
|
+
"""
|
|
735
|
+
for molecule in self._molecules:
|
|
736
|
+
yield from molecule.atoms
|
|
737
|
+
|
|
738
|
+
def atom_index(self, atom: "Atom") -> int:
|
|
739
|
+
"""
|
|
740
|
+
Returns the index of a given atom in this topology
|
|
741
|
+
|
|
742
|
+
Parameters
|
|
743
|
+
----------
|
|
744
|
+
atom
|
|
745
|
+
|
|
746
|
+
Returns
|
|
747
|
+
-------
|
|
748
|
+
index
|
|
749
|
+
The index of the given atom in this topology
|
|
750
|
+
|
|
751
|
+
Raises
|
|
752
|
+
------
|
|
753
|
+
AtomNotInTopologyError
|
|
754
|
+
If the given atom is not in this topology
|
|
755
|
+
"""
|
|
756
|
+
# If the atom's topology atom index isn't cached, calculate it for the whole topology
|
|
757
|
+
if "_topology_atom_index" not in atom.__dict__:
|
|
758
|
+
self._build_atom_index_cache()
|
|
759
|
+
# After computing the topology atom indices for all atoms in this topology, if this
|
|
760
|
+
# atom still doesn't have a topology atom index assigned, then it must not be in this topology
|
|
761
|
+
if "_topology_atom_index" not in atom.__dict__:
|
|
762
|
+
raise AtomNotInTopologyError("Atom not found in this Topology")
|
|
763
|
+
|
|
764
|
+
return atom._topology_atom_index # type: ignore[attr-defined]
|
|
765
|
+
|
|
766
|
+
def molecule_index(self, molecule: MoleculeLike) -> int:
|
|
767
|
+
"""
|
|
768
|
+
Returns the index of a given molecule in this topology
|
|
769
|
+
|
|
770
|
+
Parameters
|
|
771
|
+
----------
|
|
772
|
+
molecule
|
|
773
|
+
|
|
774
|
+
Returns
|
|
775
|
+
-------
|
|
776
|
+
index
|
|
777
|
+
The index of the given molecule in this topology
|
|
778
|
+
|
|
779
|
+
Raises
|
|
780
|
+
------
|
|
781
|
+
MoleculeNotInTopologyError
|
|
782
|
+
If the given atom is not in this topology
|
|
783
|
+
"""
|
|
784
|
+
for index, iter_molecule in enumerate(self.molecules):
|
|
785
|
+
if molecule is iter_molecule:
|
|
786
|
+
return index
|
|
787
|
+
|
|
788
|
+
raise MoleculeNotInTopologyError("Molecule not found in this Topology")
|
|
789
|
+
|
|
790
|
+
def molecule_atom_start_index(self, molecule: Molecule) -> int:
|
|
791
|
+
"""
|
|
792
|
+
Returns the index of a molecule's first atom in this topology
|
|
793
|
+
|
|
794
|
+
Parameters
|
|
795
|
+
----------
|
|
796
|
+
molecule
|
|
797
|
+
|
|
798
|
+
Returns
|
|
799
|
+
-------
|
|
800
|
+
index
|
|
801
|
+
"""
|
|
802
|
+
return self.atom_index(molecule.atoms[0])
|
|
803
|
+
|
|
804
|
+
@property
|
|
805
|
+
def n_bonds(self) -> int:
|
|
806
|
+
"""
|
|
807
|
+
Returns the number of Bonds in in this Topology.
|
|
808
|
+
|
|
809
|
+
Returns
|
|
810
|
+
-------
|
|
811
|
+
n_bonds
|
|
812
|
+
"""
|
|
813
|
+
n_bonds = 0
|
|
814
|
+
for molecule in self.molecules:
|
|
815
|
+
n_bonds += molecule.n_bonds
|
|
816
|
+
return n_bonds
|
|
817
|
+
|
|
818
|
+
@property
|
|
819
|
+
def bonds(self) -> Generator["Bond", None, None]:
|
|
820
|
+
"""Returns an iterator over the bonds in this Topology
|
|
821
|
+
|
|
822
|
+
Returns
|
|
823
|
+
-------
|
|
824
|
+
bonds
|
|
825
|
+
"""
|
|
826
|
+
for molecule in self.molecules:
|
|
827
|
+
yield from molecule.bonds
|
|
828
|
+
|
|
829
|
+
@property
|
|
830
|
+
def n_angles(self) -> int:
|
|
831
|
+
"""int: number of angles in this Topology."""
|
|
832
|
+
return sum(mol.n_angles for mol in self._molecules)
|
|
833
|
+
|
|
834
|
+
@property
|
|
835
|
+
def angles(self) -> Generator[tuple["Atom", ...], None, None]:
|
|
836
|
+
"""Iterator over the angles in this Topology. Returns a Generator of tuple[Atom]."""
|
|
837
|
+
for molecule in self._molecules:
|
|
838
|
+
yield from molecule.angles
|
|
839
|
+
|
|
840
|
+
@property
|
|
841
|
+
def n_propers(self) -> int:
|
|
842
|
+
"""The number of proper torsions in this Topology."""
|
|
843
|
+
return sum(mol.n_propers for mol in self._molecules)
|
|
844
|
+
|
|
845
|
+
@property
|
|
846
|
+
def propers(self) -> Generator[tuple[Union["Atom", _SimpleAtom], ...], None, None]:
|
|
847
|
+
"""Iterable of tuple[Atom]: iterator over the proper torsions in this Topology."""
|
|
848
|
+
for molecule in self.molecules:
|
|
849
|
+
yield from molecule.propers
|
|
850
|
+
|
|
851
|
+
@property
|
|
852
|
+
def n_impropers(self) -> int:
|
|
853
|
+
"""The number of possible improper torsions in this Topology."""
|
|
854
|
+
return sum(mol.n_impropers for mol in self._molecules)
|
|
855
|
+
|
|
856
|
+
@property
|
|
857
|
+
def impropers(self) -> Generator[tuple["Atom", ...], None, None]:
|
|
858
|
+
"""Generator of tuple[Atom]: iterator over the possible improper torsions in this Topology."""
|
|
859
|
+
for molecule in self._molecules:
|
|
860
|
+
yield from molecule.impropers
|
|
861
|
+
|
|
862
|
+
@property
|
|
863
|
+
def smirnoff_impropers(
|
|
864
|
+
self,
|
|
865
|
+
) -> Generator[tuple[Union["Atom", _SimpleAtom], ...], None, None]:
|
|
866
|
+
"""
|
|
867
|
+
Iterate over improper torsions in the molecule, but only those with
|
|
868
|
+
trivalent centers, reporting the central atom second in each improper.
|
|
869
|
+
|
|
870
|
+
Note that it's possible that a trivalent center will not have an improper assigned.
|
|
871
|
+
This will depend on the force field that is used.
|
|
872
|
+
|
|
873
|
+
Also note that this will return 6 possible atom orderings around each improper
|
|
874
|
+
center. In current SMIRNOFF parameterization, three of these six
|
|
875
|
+
orderings will be used for the actual assignment of the improper term
|
|
876
|
+
and measurement of the angles. These three orderings capture the three unique
|
|
877
|
+
angles that could be calculated around the improper center, therefore the sum
|
|
878
|
+
of these three terms will always return a consistent energy.
|
|
879
|
+
|
|
880
|
+
For more details on the use of three-fold ('trefoil') impropers, see
|
|
881
|
+
https://openforcefield.github.io/standards/standards/smirnoff/#impropertorsions
|
|
882
|
+
|
|
883
|
+
.. todo:: Offer a way to do the keytransform and get the final 3 orderings in this
|
|
884
|
+
method? How can we keep this logic synced up with the parameterization
|
|
885
|
+
machinery?
|
|
886
|
+
|
|
887
|
+
Returns
|
|
888
|
+
-------
|
|
889
|
+
smirnoff_impropers
|
|
890
|
+
An iterator of tuples, each containing the Atom objects comprising
|
|
891
|
+
up a possible improper torsion. The central atom is listed second in
|
|
892
|
+
each tuple.
|
|
893
|
+
|
|
894
|
+
See Also
|
|
895
|
+
--------
|
|
896
|
+
impropers, amber_impropers
|
|
897
|
+
|
|
898
|
+
"""
|
|
899
|
+
for molecule in self.molecules:
|
|
900
|
+
yield from molecule.smirnoff_impropers
|
|
901
|
+
|
|
902
|
+
@property
|
|
903
|
+
def amber_impropers(
|
|
904
|
+
self,
|
|
905
|
+
) -> Generator[tuple[Union["Atom", _SimpleAtom], ...], None, None]:
|
|
906
|
+
"""
|
|
907
|
+
Iterate over improper torsions in the molecule, but only those with
|
|
908
|
+
trivalent centers, reporting the central atom first in each improper.
|
|
909
|
+
|
|
910
|
+
Note that it's possible that a trivalent center will not have an improper assigned.
|
|
911
|
+
This will depend on the force field that is used.
|
|
912
|
+
|
|
913
|
+
Also note that this will return 6 possible atom orderings around each improper
|
|
914
|
+
center. In current AMBER parameterization, one of these six
|
|
915
|
+
orderings will be used for the actual assignment of the improper term
|
|
916
|
+
and measurement of the angle. This method does not encode the logic to
|
|
917
|
+
determine which of the six orderings AMBER would use.
|
|
918
|
+
|
|
919
|
+
Returns
|
|
920
|
+
-------
|
|
921
|
+
amber_impropers
|
|
922
|
+
An iterator of tuples, each containing the Atom objects comprising
|
|
923
|
+
up a possible improper torsion. The central atom is listed first in
|
|
924
|
+
each tuple.
|
|
925
|
+
|
|
926
|
+
See Also
|
|
927
|
+
--------
|
|
928
|
+
impropers, smirnoff_impropers
|
|
929
|
+
"""
|
|
930
|
+
for molecule in self.molecules:
|
|
931
|
+
yield from molecule.amber_impropers
|
|
932
|
+
|
|
933
|
+
def nth_degree_neighbors(self, n_degrees: int):
|
|
934
|
+
"""
|
|
935
|
+
Return canonicalized pairs of atoms whose shortest separation is `exactly` n bonds.
|
|
936
|
+
Only pairs with increasing atom indices are returned.
|
|
937
|
+
|
|
938
|
+
Parameters
|
|
939
|
+
----------
|
|
940
|
+
n: int
|
|
941
|
+
The number of bonds separating atoms in each pair
|
|
942
|
+
|
|
943
|
+
Returns
|
|
944
|
+
-------
|
|
945
|
+
neighbors: iterator of tuple of Atom
|
|
946
|
+
Tuples (len 2) of atom that are separated by ``n`` bonds.
|
|
947
|
+
|
|
948
|
+
Notes
|
|
949
|
+
-----
|
|
950
|
+
The criteria used here relies on minimum distances; when there are multiple valid
|
|
951
|
+
paths between atoms, such as atoms in rings, the shortest path is considered.
|
|
952
|
+
For example, two atoms in "meta" positions with respect to each other in a benzene
|
|
953
|
+
are separated by two paths, one length 2 bonds and the other length 4 bonds. This
|
|
954
|
+
function would consider them to be 2 apart and would not include them if ``n=4`` was
|
|
955
|
+
passed.
|
|
956
|
+
"""
|
|
957
|
+
for molecule in self.molecules:
|
|
958
|
+
yield from molecule.nth_degree_neighbors(n_degrees=n_degrees)
|
|
959
|
+
|
|
960
|
+
class _ChemicalEnvironmentMatch:
|
|
961
|
+
"""Represents the match of a given chemical environment query, storing
|
|
962
|
+
both the matched topology atom indices and the indices of the corresponding
|
|
963
|
+
reference molecule atoms, as well as a reference to the reference molecule.
|
|
964
|
+
"""
|
|
965
|
+
|
|
966
|
+
@property
|
|
967
|
+
def reference_atom_indices(self):
|
|
968
|
+
"""tuple of int: The indices of the corresponding reference molecule atoms."""
|
|
969
|
+
return self._reference_atom_indices
|
|
970
|
+
|
|
971
|
+
@property
|
|
972
|
+
def reference_molecule(self):
|
|
973
|
+
"""topology.molecule.Molecule: The corresponding reference molecule."""
|
|
974
|
+
return self._reference_molecule
|
|
975
|
+
|
|
976
|
+
@property
|
|
977
|
+
def topology_atom_indices(self):
|
|
978
|
+
"""tuple of int: The matched topology atom indices."""
|
|
979
|
+
return self._topology_atom_indices
|
|
980
|
+
|
|
981
|
+
def __init__(self, reference_atom_indices, reference_molecule, topology_atom_indices):
|
|
982
|
+
"""Constructs a new _ChemicalEnvironmentMatch object
|
|
983
|
+
|
|
984
|
+
Parameters
|
|
985
|
+
----------
|
|
986
|
+
reference_atom_indices: tuple of int
|
|
987
|
+
The indices of the corresponding reference molecule atoms.
|
|
988
|
+
reference_molecule: topology.molecule.Molecule
|
|
989
|
+
The corresponding reference molecule.
|
|
990
|
+
topology_atom_indices: tuple of int
|
|
991
|
+
The matched topology atom indices.
|
|
992
|
+
"""
|
|
993
|
+
|
|
994
|
+
assert len(reference_atom_indices) == len(topology_atom_indices)
|
|
995
|
+
|
|
996
|
+
self._reference_atom_indices = reference_atom_indices
|
|
997
|
+
self._reference_molecule = reference_molecule
|
|
998
|
+
|
|
999
|
+
self._topology_atom_indices = topology_atom_indices
|
|
1000
|
+
|
|
1001
|
+
def chemical_environment_matches(
|
|
1002
|
+
self,
|
|
1003
|
+
query: str,
|
|
1004
|
+
aromaticity_model: str = "MDL",
|
|
1005
|
+
unique: bool = False,
|
|
1006
|
+
toolkit_registry: TKR = GLOBAL_TOOLKIT_REGISTRY,
|
|
1007
|
+
):
|
|
1008
|
+
"""
|
|
1009
|
+
Retrieve all matches for a given chemical environment query.
|
|
1010
|
+
|
|
1011
|
+
TODO:
|
|
1012
|
+
|
|
1013
|
+
* Do we want to generalize this to other kinds of queries too, like mdtraj DSL, pymol selections, atom index
|
|
1014
|
+
slices, etc? We could just call it topology.matches(query)
|
|
1015
|
+
|
|
1016
|
+
Parameters
|
|
1017
|
+
----------
|
|
1018
|
+
query
|
|
1019
|
+
SMARTS string (with one or more tagged atoms)
|
|
1020
|
+
aromaticity_model
|
|
1021
|
+
Override the default aromaticity model for this topology and use the specified aromaticity model instead.
|
|
1022
|
+
Allowed values: ['MDL']
|
|
1023
|
+
|
|
1024
|
+
Returns
|
|
1025
|
+
-------
|
|
1026
|
+
matches
|
|
1027
|
+
A list of tuples, containing the topology indices of the matching atoms.
|
|
1028
|
+
|
|
1029
|
+
"""
|
|
1030
|
+
|
|
1031
|
+
# Render the query to a SMARTS string
|
|
1032
|
+
if isinstance(query, str):
|
|
1033
|
+
smarts = query
|
|
1034
|
+
else:
|
|
1035
|
+
raise ValueError(f"Don't know how to convert query '{query}' into SMARTS string")
|
|
1036
|
+
|
|
1037
|
+
# Perform matching on each unique molecule, unrolling the matches to all matching copies
|
|
1038
|
+
# of that molecule in the Topology object.
|
|
1039
|
+
matches = list()
|
|
1040
|
+
|
|
1041
|
+
groupings = self.identical_molecule_groups
|
|
1042
|
+
|
|
1043
|
+
for unique_mol_idx, group in groupings.items():
|
|
1044
|
+
unique_mol = self.molecule(unique_mol_idx)
|
|
1045
|
+
# Find all atomsets that match this definition in the reference molecule
|
|
1046
|
+
# This will automatically attempt to match chemically identical atoms in
|
|
1047
|
+
# a canonical order within the Topology
|
|
1048
|
+
if isinstance(unique_mol, _SimpleMolecule):
|
|
1049
|
+
raise ValueError("Topologies with simple molecules do not support environment matching")
|
|
1050
|
+
mol_matches = unique_mol.chemical_environment_matches(
|
|
1051
|
+
smarts,
|
|
1052
|
+
unique=unique,
|
|
1053
|
+
toolkit_registry=toolkit_registry,
|
|
1054
|
+
)
|
|
1055
|
+
|
|
1056
|
+
if len(mol_matches) == 0:
|
|
1057
|
+
continue
|
|
1058
|
+
|
|
1059
|
+
for mol_instance_idx, atom_map in group:
|
|
1060
|
+
mol_instance = self.molecule(mol_instance_idx)
|
|
1061
|
+
# Loop over matches
|
|
1062
|
+
for match in mol_matches:
|
|
1063
|
+
# Collect indices of matching `Atom`s
|
|
1064
|
+
topology_atom_indices = []
|
|
1065
|
+
for molecule_atom_index in match:
|
|
1066
|
+
atom = mol_instance.atom(atom_map[molecule_atom_index])
|
|
1067
|
+
topology_atom_indices.append(self.atom_index(atom)) # type: ignore[arg-type]
|
|
1068
|
+
|
|
1069
|
+
environment_match = Topology._ChemicalEnvironmentMatch(
|
|
1070
|
+
tuple(match), unique_mol, tuple(topology_atom_indices)
|
|
1071
|
+
)
|
|
1072
|
+
|
|
1073
|
+
matches.append(environment_match)
|
|
1074
|
+
return matches
|
|
1075
|
+
|
|
1076
|
+
@property
|
|
1077
|
+
def identical_molecule_groups(self) -> dict[int, list[tuple[int, dict[int, int]]]]:
|
|
1078
|
+
"""
|
|
1079
|
+
Returns groups of chemically identical molecules, identified by index and atom map.
|
|
1080
|
+
|
|
1081
|
+
Returns
|
|
1082
|
+
-------
|
|
1083
|
+
identical_molecule_groups
|
|
1084
|
+
A dict of the form ``{unique_mol_idx : [(topology_mol_idx, atom_map), ...].``
|
|
1085
|
+
Each key is the topology molecule index of the first instance of a
|
|
1086
|
+
unique chemical species. Iterating over the keys will yield all of
|
|
1087
|
+
the unique chemical species in the topology. Each value is a list
|
|
1088
|
+
of all instances of that chemical species in the topology. Each
|
|
1089
|
+
element of the list is a 2-tuple where the first element is the
|
|
1090
|
+
molecule index of the instance, and the second element maps the atom
|
|
1091
|
+
topology indices of the key molecule to the instance. The molecule
|
|
1092
|
+
instance corresponding to the key is included in the list, so the
|
|
1093
|
+
list is a complete list of all instances of that chemical species.
|
|
1094
|
+
|
|
1095
|
+
Examples
|
|
1096
|
+
--------
|
|
1097
|
+
|
|
1098
|
+
>>> from openff.toolkit import Molecule, Topology
|
|
1099
|
+
>>> # Create a water ordered as OHH
|
|
1100
|
+
>>> water1 = Molecule()
|
|
1101
|
+
>>> water1.add_atom(8, 0, False)
|
|
1102
|
+
0
|
|
1103
|
+
>>> water1.add_atom(1, 0, False)
|
|
1104
|
+
1
|
|
1105
|
+
>>> water1.add_atom(1, 0, False)
|
|
1106
|
+
2
|
|
1107
|
+
>>> _ = water1.add_bond(0, 1, 1, False)
|
|
1108
|
+
>>> _ = water1.add_bond(0, 2, 1, False)
|
|
1109
|
+
...
|
|
1110
|
+
>>> # Create a different water ordered as HOH
|
|
1111
|
+
>>> water2 = Molecule()
|
|
1112
|
+
>>> water2.add_atom(1, 0, False)
|
|
1113
|
+
0
|
|
1114
|
+
>>> water2.add_atom(8, 0, False)
|
|
1115
|
+
1
|
|
1116
|
+
>>> water2.add_atom(1, 0, False)
|
|
1117
|
+
2
|
|
1118
|
+
>>> _ = water2.add_bond(0, 1, 1, False)
|
|
1119
|
+
>>> _ = water2.add_bond(1, 2, 1, False)
|
|
1120
|
+
...
|
|
1121
|
+
>>> top = Topology.from_molecules([water1, water2])
|
|
1122
|
+
>>> top.identical_molecule_groups
|
|
1123
|
+
{0: [(0, {0: 0, 1: 1, 2: 2}), (1, {0: 1, 1: 0, 2: 2})]}
|
|
1124
|
+
"""
|
|
1125
|
+
# Check whether this was run previously, and a cached result is available.
|
|
1126
|
+
if self._cached_chemically_identical_molecules is not None:
|
|
1127
|
+
return self._cached_chemically_identical_molecules
|
|
1128
|
+
|
|
1129
|
+
# Convert molecule identity maps into groups of identical molecules
|
|
1130
|
+
identity_maps = self._identify_chemically_identical_molecules()
|
|
1131
|
+
groupings: dict[int, list[tuple[int, dict[int, int]]]] = defaultdict(list)
|
|
1132
|
+
for molecule_idx, (unique_mol, atom_map) in identity_maps.items():
|
|
1133
|
+
groupings[unique_mol] += [(molecule_idx, atom_map)]
|
|
1134
|
+
|
|
1135
|
+
self._cached_chemically_identical_molecules = dict(groupings)
|
|
1136
|
+
|
|
1137
|
+
return self._cached_chemically_identical_molecules
|
|
1138
|
+
|
|
1139
|
+
def _identify_chemically_identical_molecules(
|
|
1140
|
+
self,
|
|
1141
|
+
) -> dict[int, tuple[int, dict[int, int]]]:
|
|
1142
|
+
"""
|
|
1143
|
+
Perform an all-by-all isomorphism check over molecules in the Topology.
|
|
1144
|
+
|
|
1145
|
+
Efficiently performs an all-by-all isomorphism check for the molecules in
|
|
1146
|
+
this Topology. This method uses the strictest form of isomorphism
|
|
1147
|
+
checking, which will NOT match distinct kekule structures of multiple
|
|
1148
|
+
resonance forms of the same molecule, or different kekulizations of
|
|
1149
|
+
aromatic systems.
|
|
1150
|
+
|
|
1151
|
+
Returns
|
|
1152
|
+
-------
|
|
1153
|
+
identical_molecules
|
|
1154
|
+
A mapping from the index of each molecule in the topology to (the
|
|
1155
|
+
index of the first appearance of a chemically equivalent molecule in
|
|
1156
|
+
the topology, and a mapping from the atom indices of this molecule
|
|
1157
|
+
to the atom indices of that chemically equivalent molecule).
|
|
1158
|
+
``identical_molecules[molecule_idx] = (
|
|
1159
|
+
unique_molecule_idx, {molecule_atom_idx, unique_molecule_atom_idx}
|
|
1160
|
+
)``
|
|
1161
|
+
"""
|
|
1162
|
+
identity_maps: dict[int, tuple] = dict()
|
|
1163
|
+
already_matched_mols = set()
|
|
1164
|
+
|
|
1165
|
+
for mol1_idx in range(self.n_molecules):
|
|
1166
|
+
if mol1_idx in already_matched_mols:
|
|
1167
|
+
continue
|
|
1168
|
+
mol1 = self.molecule(mol1_idx)
|
|
1169
|
+
identity_maps[mol1_idx] = (
|
|
1170
|
+
mol1_idx,
|
|
1171
|
+
{i: i for i in range(mol1.n_atoms)},
|
|
1172
|
+
)
|
|
1173
|
+
for mol2_idx in range(mol1_idx + 1, self.n_molecules):
|
|
1174
|
+
if mol2_idx in already_matched_mols:
|
|
1175
|
+
continue
|
|
1176
|
+
mol2 = self.molecule(mol2_idx)
|
|
1177
|
+
if isinstance(mol1, type(mol2)) or isinstance(mol2, type(mol1)):
|
|
1178
|
+
are_isomorphic, atom_map = mol1.are_isomorphic(mol1, mol2, return_atom_map=True)
|
|
1179
|
+
else:
|
|
1180
|
+
are_isomorphic = False
|
|
1181
|
+
|
|
1182
|
+
if are_isomorphic:
|
|
1183
|
+
identity_maps[mol2_idx] = (
|
|
1184
|
+
mol1_idx,
|
|
1185
|
+
atom_map,
|
|
1186
|
+
)
|
|
1187
|
+
already_matched_mols.add(mol2_idx)
|
|
1188
|
+
|
|
1189
|
+
return identity_maps
|
|
1190
|
+
|
|
1191
|
+
def _build_atom_index_cache(self):
|
|
1192
|
+
topology_molecule_atom_start_index = 0
|
|
1193
|
+
for molecule in self.molecules:
|
|
1194
|
+
for at in molecule.atoms:
|
|
1195
|
+
at._topology_atom_index = topology_molecule_atom_start_index + at.molecule_atom_index
|
|
1196
|
+
topology_molecule_atom_start_index += molecule.n_atoms
|
|
1197
|
+
|
|
1198
|
+
def _invalidate_cached_properties(self):
|
|
1199
|
+
self._cached_chemically_identical_molecules = None
|
|
1200
|
+
for atom in self.atoms:
|
|
1201
|
+
if "_topology_atom_index" in atom.__dict__:
|
|
1202
|
+
del atom.__dict__["_topology_atom_index"]
|
|
1203
|
+
|
|
1204
|
+
def copy_initializer(self, other):
|
|
1205
|
+
import copy
|
|
1206
|
+
|
|
1207
|
+
self.aromaticity_model = other.aromaticity_model
|
|
1208
|
+
self._constrained_atom_pairs = copy.deepcopy(other._constrained_atom_pairs)
|
|
1209
|
+
self._box_vectors = copy.deepcopy(other._box_vectors)
|
|
1210
|
+
self._molecules = copy.deepcopy(other._molecules)
|
|
1211
|
+
self._invalidate_cached_properties()
|
|
1212
|
+
|
|
1213
|
+
def to_dict(self) -> dict:
|
|
1214
|
+
from openff.toolkit.utils.utils import serialize_numpy
|
|
1215
|
+
|
|
1216
|
+
return_dict: dict[
|
|
1217
|
+
str,
|
|
1218
|
+
None | str | bytes | bool | tuple | list[dict] | dict[tuple[int, int], str],
|
|
1219
|
+
] = dict()
|
|
1220
|
+
|
|
1221
|
+
return_dict["aromaticity_model"] = self._aromaticity_model
|
|
1222
|
+
|
|
1223
|
+
return_dict["constrained_atom_pairs"] = {
|
|
1224
|
+
constrained_atom_pair: quantity_to_string(distance) # type: ignore[arg-type]
|
|
1225
|
+
for constrained_atom_pair, distance in self._constrained_atom_pairs.items()
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
if self._box_vectors is None:
|
|
1229
|
+
return_dict["box_vectors"] = None
|
|
1230
|
+
return_dict["box_vectors_unit"] = None
|
|
1231
|
+
else:
|
|
1232
|
+
box_vectors_unitless = self.box_vectors.m_as(unit.nanometer)
|
|
1233
|
+
box_vectors_serialized, box_vectors_shape = serialize_numpy(box_vectors_unitless)
|
|
1234
|
+
if box_vectors_shape != (3, 3):
|
|
1235
|
+
raise RuntimeError(f"Box vectors are assumed to be (3, 3); found shape {box_vectors_shape}")
|
|
1236
|
+
return_dict["box_vectors"] = box_vectors_serialized
|
|
1237
|
+
return_dict["box_vectors_unit"] = "nanometer"
|
|
1238
|
+
|
|
1239
|
+
return_dict["molecules"] = [mol.to_dict() for mol in self._molecules]
|
|
1240
|
+
|
|
1241
|
+
return return_dict
|
|
1242
|
+
|
|
1243
|
+
@classmethod
|
|
1244
|
+
def from_dict(cls, topology_dict: dict):
|
|
1245
|
+
"""
|
|
1246
|
+
Create a new Topology from a dictionary representation
|
|
1247
|
+
|
|
1248
|
+
The structure of the dict expected by this function is defined by the output of `Topology.to_dict()`.
|
|
1249
|
+
|
|
1250
|
+
Parameters
|
|
1251
|
+
----------
|
|
1252
|
+
topology_dict
|
|
1253
|
+
A dictionary representation of the topology.
|
|
1254
|
+
|
|
1255
|
+
Returns
|
|
1256
|
+
-------
|
|
1257
|
+
topology
|
|
1258
|
+
A Topology created from the dictionary representation
|
|
1259
|
+
|
|
1260
|
+
"""
|
|
1261
|
+
topology = cls()
|
|
1262
|
+
topology._initialize_from_dict(topology_dict)
|
|
1263
|
+
return topology
|
|
1264
|
+
|
|
1265
|
+
def _initialize_from_dict(self, topology_dict):
|
|
1266
|
+
from openff.toolkit.utils.utils import deserialize_numpy
|
|
1267
|
+
|
|
1268
|
+
self._aromaticity_model = topology_dict["aromaticity_model"]
|
|
1269
|
+
for pair, distance in topology_dict["constrained_atom_pairs"]:
|
|
1270
|
+
deserialized_distance = string_to_quantity(distance)
|
|
1271
|
+
self.add_constraint(pair, deserialized_distance)
|
|
1272
|
+
|
|
1273
|
+
if topology_dict["box_vectors"] is None:
|
|
1274
|
+
self._box_vectors = None
|
|
1275
|
+
else:
|
|
1276
|
+
# The box_vectors setters _should_ ensure (3, 3) shape, and
|
|
1277
|
+
# to_dict enforces this at serialization time
|
|
1278
|
+
box_vectors_unitless = deserialize_numpy(
|
|
1279
|
+
topology_dict["box_vectors"],
|
|
1280
|
+
(3, 3),
|
|
1281
|
+
)
|
|
1282
|
+
box_vectors_unit = getattr(unit, topology_dict["box_vectors_unit"])
|
|
1283
|
+
self.box_vectors = Quantity(box_vectors_unitless, box_vectors_unit)
|
|
1284
|
+
|
|
1285
|
+
for molecule_dict in topology_dict["molecules"]:
|
|
1286
|
+
# the serialized representation doesn't store which molecule model
|
|
1287
|
+
# each of these dicts is meant to be deserialized to. Usually it'll
|
|
1288
|
+
# be Molecule, so try that first. If it's supposed to be a
|
|
1289
|
+
# _SimpleMolecule, it'll KeyError because Molecule has more fields.
|
|
1290
|
+
try:
|
|
1291
|
+
new_mol = Molecule.from_dict(molecule_dict)
|
|
1292
|
+
except KeyError:
|
|
1293
|
+
# masks possible other ways KeyErrors could pop up
|
|
1294
|
+
new_mol = _SimpleMolecule.from_dict(molecule_dict)
|
|
1295
|
+
|
|
1296
|
+
self._add_molecule_keep_cache(new_mol)
|
|
1297
|
+
|
|
1298
|
+
self._invalidate_cached_properties()
|
|
1299
|
+
|
|
1300
|
+
@staticmethod
|
|
1301
|
+
@requires_package("openmm")
|
|
1302
|
+
def _openmm_topology_to_networkx(openmm_topology):
|
|
1303
|
+
import networkx as nx
|
|
1304
|
+
|
|
1305
|
+
# Convert all openMM mols to graphs
|
|
1306
|
+
omm_topology_G: nx.classes.graph.Graph = nx.Graph()
|
|
1307
|
+
for atom in openmm_topology.atoms():
|
|
1308
|
+
if atom.element is None:
|
|
1309
|
+
raise VirtualSitesUnsupportedError(
|
|
1310
|
+
f"Atom {atom} has element None and is probably a virtual site. Virtual sites "
|
|
1311
|
+
"cannot be stored in `Topology` objects but can be stored in `Interchange` "
|
|
1312
|
+
"objects produced by `ForceField`s with virtual site parameters."
|
|
1313
|
+
)
|
|
1314
|
+
omm_topology_G.add_node(
|
|
1315
|
+
atom.index,
|
|
1316
|
+
atomic_number=atom.element.atomic_number,
|
|
1317
|
+
atom_name=atom.name,
|
|
1318
|
+
residue_name=atom.residue.name,
|
|
1319
|
+
residue_id=atom.residue.id,
|
|
1320
|
+
insertion_code=atom.residue.insertionCode,
|
|
1321
|
+
chain_id=atom.residue.chain.id,
|
|
1322
|
+
)
|
|
1323
|
+
for bond in openmm_topology.bonds():
|
|
1324
|
+
omm_topology_G.add_edge(bond.atom1.index, bond.atom2.index, bond_order=bond.order)
|
|
1325
|
+
return omm_topology_G
|
|
1326
|
+
|
|
1327
|
+
@classmethod
|
|
1328
|
+
@requires_package("openmm")
|
|
1329
|
+
def from_openmm(
|
|
1330
|
+
cls,
|
|
1331
|
+
openmm_topology: "openmm.app.Topology",
|
|
1332
|
+
unique_molecules: Iterable[FrozenMolecule] | None = None,
|
|
1333
|
+
positions: Union[None, Quantity, "OMMQuantity"] = None,
|
|
1334
|
+
) -> "Topology":
|
|
1335
|
+
"""
|
|
1336
|
+
Construct an OpenFF Topology object from an OpenMM Topology object.
|
|
1337
|
+
|
|
1338
|
+
This method guarantees that the order of atoms in the input OpenMM
|
|
1339
|
+
Topology will be the same as the ordering of atoms in the output OpenFF
|
|
1340
|
+
Topology. However it does not guarantee the order of the bonds will be
|
|
1341
|
+
the same.
|
|
1342
|
+
|
|
1343
|
+
Hierarchy schemes are taken from the OpenMM topology, not from
|
|
1344
|
+
``unique_molecules``.
|
|
1345
|
+
|
|
1346
|
+
If any virtual sites are detected in the OpenMM topology,
|
|
1347
|
+
``VirtualSitesUnsupportedError`` is raised because the ``Topology``
|
|
1348
|
+
object model does not store virtual sites.
|
|
1349
|
+
|
|
1350
|
+
Parameters
|
|
1351
|
+
----------
|
|
1352
|
+
openmm_topology
|
|
1353
|
+
The OpenMM Topology object to convert
|
|
1354
|
+
unique_molecules
|
|
1355
|
+
An iterable containing all the unique molecules in the topology.
|
|
1356
|
+
This is used to identify the molecules in the OpenMM topology and
|
|
1357
|
+
provide any missing chemical information. Each chemical species in
|
|
1358
|
+
the topology must be specified exactly once, though the topology
|
|
1359
|
+
may have any number of copies, including zero. The chemical
|
|
1360
|
+
elements of atoms and their bond connectivity will be used to match
|
|
1361
|
+
these reference molecules to the molecules appearing in the
|
|
1362
|
+
topology. If bond orders are specified in the topology, these will
|
|
1363
|
+
be used in matching as well.
|
|
1364
|
+
positions
|
|
1365
|
+
Positions for the atoms in the new topology.
|
|
1366
|
+
|
|
1367
|
+
Returns
|
|
1368
|
+
-------
|
|
1369
|
+
topology
|
|
1370
|
+
An OpenFF Topology object, constructed from the molecules in
|
|
1371
|
+
``unique_molecules``, with the same atom order as the input topology.
|
|
1372
|
+
|
|
1373
|
+
Raises
|
|
1374
|
+
------
|
|
1375
|
+
MissingUniqueMoleculesError
|
|
1376
|
+
If ``unique_molecules`` is ``None``
|
|
1377
|
+
DuplicateUniqueMoleculeError
|
|
1378
|
+
If the same connectivity graph is represented by two different
|
|
1379
|
+
molecules in ``unique_molecules``
|
|
1380
|
+
ValueError
|
|
1381
|
+
If a chemically impossible molecule is detected in the topology
|
|
1382
|
+
"""
|
|
1383
|
+
import networkx as nx
|
|
1384
|
+
from openff.units.openmm import from_openmm
|
|
1385
|
+
|
|
1386
|
+
from openff.toolkit.topology.molecule import Molecule
|
|
1387
|
+
|
|
1388
|
+
# Check to see if the openMM system has defined bond orders, by looping over all Bonds in the Topology.
|
|
1389
|
+
omm_has_bond_orders = True
|
|
1390
|
+
for omm_bond in openmm_topology.bonds():
|
|
1391
|
+
if omm_bond.order is None:
|
|
1392
|
+
omm_has_bond_orders = False
|
|
1393
|
+
|
|
1394
|
+
if unique_molecules is None:
|
|
1395
|
+
raise MissingUniqueMoleculesError(
|
|
1396
|
+
"Topology.from_openmm requires a list of Molecule objects "
|
|
1397
|
+
"passed as unique_molecules, but None was passed."
|
|
1398
|
+
)
|
|
1399
|
+
|
|
1400
|
+
# Convert all unique mols to graphs
|
|
1401
|
+
topology = cls()
|
|
1402
|
+
graph_to_unq_mol: dict[Graph, FrozenMolecule] = {}
|
|
1403
|
+
for unq_mol in unique_molecules:
|
|
1404
|
+
unq_mol_graph = unq_mol.to_networkx()
|
|
1405
|
+
for existing_graph in graph_to_unq_mol.keys():
|
|
1406
|
+
if Molecule.are_isomorphic(
|
|
1407
|
+
existing_graph,
|
|
1408
|
+
unq_mol_graph,
|
|
1409
|
+
return_atom_map=False,
|
|
1410
|
+
aromatic_matching=False,
|
|
1411
|
+
formal_charge_matching=False,
|
|
1412
|
+
bond_order_matching=omm_has_bond_orders,
|
|
1413
|
+
atom_stereochemistry_matching=False,
|
|
1414
|
+
bond_stereochemistry_matching=False,
|
|
1415
|
+
)[0]:
|
|
1416
|
+
msg = (
|
|
1417
|
+
"Error: Two unique molecules have indistinguishable "
|
|
1418
|
+
f"graphs: {unq_mol} and {graph_to_unq_mol[existing_graph]}"
|
|
1419
|
+
)
|
|
1420
|
+
raise DuplicateUniqueMoleculeError(msg)
|
|
1421
|
+
graph_to_unq_mol[unq_mol_graph] = unq_mol
|
|
1422
|
+
|
|
1423
|
+
omm_topology_G = cls._openmm_topology_to_networkx(openmm_topology)
|
|
1424
|
+
# For each connected subgraph (molecule) in the topology, find its match in unique_molecules
|
|
1425
|
+
topology_molecules_to_add = list()
|
|
1426
|
+
for omm_mol_G in (omm_topology_G.subgraph(c).copy() for c in nx.connected_components(omm_topology_G)):
|
|
1427
|
+
match_found = False
|
|
1428
|
+
for unq_mol_G in graph_to_unq_mol.keys():
|
|
1429
|
+
isomorphic, mapping = Molecule.are_isomorphic(
|
|
1430
|
+
omm_mol_G,
|
|
1431
|
+
unq_mol_G,
|
|
1432
|
+
return_atom_map=True,
|
|
1433
|
+
aromatic_matching=False,
|
|
1434
|
+
formal_charge_matching=False,
|
|
1435
|
+
bond_order_matching=omm_has_bond_orders,
|
|
1436
|
+
atom_stereochemistry_matching=False,
|
|
1437
|
+
bond_stereochemistry_matching=False,
|
|
1438
|
+
)
|
|
1439
|
+
if isomorphic:
|
|
1440
|
+
# Take the first valid atom indexing map
|
|
1441
|
+
first_topology_atom_index = min(mapping.keys()) # type: ignore[union-attr]
|
|
1442
|
+
topology_molecules_to_add.append(
|
|
1443
|
+
(
|
|
1444
|
+
first_topology_atom_index,
|
|
1445
|
+
unq_mol_G,
|
|
1446
|
+
mapping.items(), # type: ignore[union-attr]
|
|
1447
|
+
omm_mol_G,
|
|
1448
|
+
)
|
|
1449
|
+
)
|
|
1450
|
+
match_found = True
|
|
1451
|
+
break
|
|
1452
|
+
if match_found is False:
|
|
1453
|
+
from openff.toolkit.topology.molecule import (
|
|
1454
|
+
_networkx_graph_to_hill_formula,
|
|
1455
|
+
)
|
|
1456
|
+
|
|
1457
|
+
hill_formula = _networkx_graph_to_hill_formula(omm_mol_G)
|
|
1458
|
+
msg = f"No match found for molecule {hill_formula}. "
|
|
1459
|
+
probably_missing_conect = [
|
|
1460
|
+
"C",
|
|
1461
|
+
"H",
|
|
1462
|
+
"O",
|
|
1463
|
+
"N",
|
|
1464
|
+
"P",
|
|
1465
|
+
"S",
|
|
1466
|
+
"F",
|
|
1467
|
+
"Cl",
|
|
1468
|
+
"Br",
|
|
1469
|
+
]
|
|
1470
|
+
if hill_formula in probably_missing_conect:
|
|
1471
|
+
msg += (
|
|
1472
|
+
"This would be a very unusual molecule to try and parameterize, "
|
|
1473
|
+
"and it is likely that the data source it was read from does not "
|
|
1474
|
+
"contain connectivity information. If this molecule is coming from "
|
|
1475
|
+
"PDB, please ensure that the file contains CONECT records. The PDB "
|
|
1476
|
+
"format documentation (https://www.wwpdb.org/documentation/"
|
|
1477
|
+
'file-format-content/format33/sect10.html) states "CONECT records '
|
|
1478
|
+
"are mandatory for HET groups (excluding water) and for other bonds "
|
|
1479
|
+
'not specified in the standard residue connectivity table."'
|
|
1480
|
+
)
|
|
1481
|
+
raise ValueError(msg)
|
|
1482
|
+
|
|
1483
|
+
# The connected_component_subgraph function above may have scrambled the molecule order, so sort molecules
|
|
1484
|
+
# by their first atom's topology index
|
|
1485
|
+
topology_molecules_to_add.sort(key=lambda x: x[0])
|
|
1486
|
+
for (
|
|
1487
|
+
first_index,
|
|
1488
|
+
unq_mol_G,
|
|
1489
|
+
top_to_ref_index,
|
|
1490
|
+
omm_mol_G,
|
|
1491
|
+
) in topology_molecules_to_add:
|
|
1492
|
+
local_top_to_ref_index = dict(
|
|
1493
|
+
[(top_index - first_index, ref_index) for top_index, ref_index in top_to_ref_index]
|
|
1494
|
+
)
|
|
1495
|
+
unq_mol = graph_to_unq_mol[unq_mol_G]
|
|
1496
|
+
remapped_mol = unq_mol.remap(local_top_to_ref_index, current_to_new=False)
|
|
1497
|
+
# Transfer hierarchy metadata from openmm mol graph to offmol metadata
|
|
1498
|
+
for off_atom_idx in range(remapped_mol.n_atoms):
|
|
1499
|
+
off_atom = remapped_mol.atom(off_atom_idx)
|
|
1500
|
+
|
|
1501
|
+
omm_atom_idx = off_atom_idx + first_index
|
|
1502
|
+
|
|
1503
|
+
off_atom.name = omm_mol_G.nodes[omm_atom_idx]["atom_name"]
|
|
1504
|
+
off_atom.metadata["residue_name"] = omm_mol_G.nodes[omm_atom_idx]["residue_name"]
|
|
1505
|
+
off_atom.metadata["residue_number"] = omm_mol_G.nodes[omm_atom_idx]["residue_id"]
|
|
1506
|
+
off_atom.metadata["insertion_code"] = omm_mol_G.nodes[omm_atom_idx]["insertion_code"]
|
|
1507
|
+
|
|
1508
|
+
off_atom.metadata["chain_id"] = omm_mol_G.nodes[omm_atom_idx]["chain_id"]
|
|
1509
|
+
|
|
1510
|
+
remapped_mol.add_default_hierarchy_schemes()
|
|
1511
|
+
topology._add_molecule_keep_cache(remapped_mol)
|
|
1512
|
+
topology._invalidate_cached_properties()
|
|
1513
|
+
|
|
1514
|
+
if openmm_topology.getPeriodicBoxVectors() is not None:
|
|
1515
|
+
topology.box_vectors = from_openmm(openmm_topology.getPeriodicBoxVectors())
|
|
1516
|
+
|
|
1517
|
+
if positions is not None:
|
|
1518
|
+
from openff.units import ensure_quantity
|
|
1519
|
+
|
|
1520
|
+
topology.set_positions(ensure_quantity(positions, "openff"))
|
|
1521
|
+
|
|
1522
|
+
# TODO: How can we preserve metadata from the openMM topology when creating the OFF topology?
|
|
1523
|
+
return topology
|
|
1524
|
+
|
|
1525
|
+
def _ensure_unique_atom_names(self, ensure_unique_atom_names: str | bool):
|
|
1526
|
+
"""See `Topology.to_openmm`"""
|
|
1527
|
+
if not ensure_unique_atom_names:
|
|
1528
|
+
return
|
|
1529
|
+
for molecule in self._molecules:
|
|
1530
|
+
if isinstance(ensure_unique_atom_names, str) and hasattr(molecule, ensure_unique_atom_names):
|
|
1531
|
+
for hier_elem in getattr(molecule, ensure_unique_atom_names):
|
|
1532
|
+
if not hier_elem.has_unique_atom_names:
|
|
1533
|
+
hier_elem.generate_unique_atom_names()
|
|
1534
|
+
elif not molecule.has_unique_atom_names:
|
|
1535
|
+
molecule.generate_unique_atom_names()
|
|
1536
|
+
|
|
1537
|
+
@classmethod
|
|
1538
|
+
@requires_package("openmm")
|
|
1539
|
+
def from_pdb(
|
|
1540
|
+
cls,
|
|
1541
|
+
file_path: str | Path | TextIO,
|
|
1542
|
+
unique_molecules: Iterable[Molecule] | None = None,
|
|
1543
|
+
toolkit_registry=GLOBAL_TOOLKIT_REGISTRY,
|
|
1544
|
+
_custom_substructures: dict[str, list[str]] | None = None,
|
|
1545
|
+
_additional_substructures: Iterable[Molecule] | None = None,
|
|
1546
|
+
):
|
|
1547
|
+
"""
|
|
1548
|
+
Loads supported or user-specified molecules from a PDB file.
|
|
1549
|
+
|
|
1550
|
+
Currently, canonical proteins, waters, and monoatomic ions are supported
|
|
1551
|
+
without CONECT records via residue and atom names, and molecules
|
|
1552
|
+
specified in the ``unique_molecules`` argument are supported when
|
|
1553
|
+
CONECT records are provided.
|
|
1554
|
+
|
|
1555
|
+
.. warning::
|
|
1556
|
+
Molecules in the resulting Topology will adopt
|
|
1557
|
+
the geometric stereochemistry in the PDB, even if this conflicts
|
|
1558
|
+
with the stereochemistry specified in ``unique_molecules``.
|
|
1559
|
+
|
|
1560
|
+
All molecules in the PDB file have the following requirements:
|
|
1561
|
+
|
|
1562
|
+
* Polymer molecules must use the standard atom names described in the
|
|
1563
|
+
`PDB Chemical Component Dictionary <https://www.wwpdb.org/data/ccd>`_
|
|
1564
|
+
(PDB CCD).
|
|
1565
|
+
* There must be no missing atoms (all hydrogens must be explicit).
|
|
1566
|
+
* All particles must correspond to an atomic nucleus (particles in the
|
|
1567
|
+
PDB representing "virtual sites" or "extra points" are not allowed).
|
|
1568
|
+
* All bonds must be specified by either CONECT records, or for
|
|
1569
|
+
polymers and water by the PDB CCD via the residue and atom name.
|
|
1570
|
+
* CONECT records must correspond only to chemical bonds (CONECT records
|
|
1571
|
+
representing an angle constraints are not allowed).
|
|
1572
|
+
* CONECT records may be redundant with connectivity defined by residue
|
|
1573
|
+
templates.
|
|
1574
|
+
|
|
1575
|
+
Currently, the only supported polymers are proteins made of the 20
|
|
1576
|
+
canonical amino acids. For details on the polymer loading used here,
|
|
1577
|
+
see :py:meth:`Molecule.from_polymer_pdb`.
|
|
1578
|
+
|
|
1579
|
+
Waters can be recognized in either of two ways:
|
|
1580
|
+
|
|
1581
|
+
* By the residue name "HOH" and atom names "H1", "H2", and "O".
|
|
1582
|
+
* By ATOM records which include element information and CONECT records.
|
|
1583
|
+
|
|
1584
|
+
Monoatomic ions supported by Sage are recognized (Na+, Li+, K+, Rb+,
|
|
1585
|
+
Cs+, F-, Cl-, Br-, and I-). To load other monoatomic ions, use the
|
|
1586
|
+
``unique_molecules`` keyword argument.
|
|
1587
|
+
|
|
1588
|
+
The ``unique_molecules`` keyword argument can be used to load arbitrary
|
|
1589
|
+
molecules from the PDB file. These molecules match a group of atoms in
|
|
1590
|
+
the PDB file when their atomic elements and connectivity are identical;
|
|
1591
|
+
elements and CONECT records must therefore be explicitly specified in
|
|
1592
|
+
the PDB file. Information missing from the PDB format, such as bond
|
|
1593
|
+
orders and formal charges, is then taken from the matching unique
|
|
1594
|
+
molecule. Unique molecule matches will overwrite bond order and formal
|
|
1595
|
+
charge assignments from other sources. Stereochemistry is assigned
|
|
1596
|
+
based on the geometry in the PDB, even if this differs from the
|
|
1597
|
+
stereochemistry in the unique molecule.
|
|
1598
|
+
|
|
1599
|
+
A user-defined molecule in the PDB file must exactly match a unique
|
|
1600
|
+
molecule to successfully load it - substructures and superstructures
|
|
1601
|
+
will raise :py:exc:`UnassignedChemistryInPDBError`. Unique molecules
|
|
1602
|
+
need not be present in the PDB.
|
|
1603
|
+
|
|
1604
|
+
Metadata such as residues, chains, and atom names are recorded in the
|
|
1605
|
+
``Atom.metadata`` attribute, which is a dictionary mapping from the
|
|
1606
|
+
strings ``"residue_name"``, ``"residue_number"``, ``"insertion_code"``,
|
|
1607
|
+
and ``"chain_id"`` to the appropriate value. The topology returned by
|
|
1608
|
+
this method can expose residue and chain iterators which can be
|
|
1609
|
+
accessed using :py:meth:`Topology.hierarchy_iterator`, such as
|
|
1610
|
+
``top.hierarchy_iterator("residues")`` and ``top.hierarchy_iterator
|
|
1611
|
+
("chains")``.
|
|
1612
|
+
|
|
1613
|
+
A CRYST line in the PDB, if present, will be interpreted as periodic
|
|
1614
|
+
box vectors in Angstroms.
|
|
1615
|
+
|
|
1616
|
+
Parameters
|
|
1617
|
+
----------
|
|
1618
|
+
file_path
|
|
1619
|
+
PDB information to be passed to OpenMM PDBFile object for loading
|
|
1620
|
+
unique_molecules
|
|
1621
|
+
OpenFF Molecule objects corresponding to the molecules in the input
|
|
1622
|
+
PDB. See above for details.
|
|
1623
|
+
toolkit_registry
|
|
1624
|
+
The ToolkitRegistry to use as the cheminformatics backend.
|
|
1625
|
+
_custom_substructures: dict[str, list[str]], Default = {}
|
|
1626
|
+
Experimental and unstable. Dictionary where keys are the names of new substructures
|
|
1627
|
+
(cannot overlap with existing amino acid names) and the values are the new substructure
|
|
1628
|
+
entries that follow the same format as those used in the amino acid substructure library
|
|
1629
|
+
_additional_substructures
|
|
1630
|
+
Experimental and unstable. Molecule with atom.metadata["substructure_atom"] =
|
|
1631
|
+
True or False for all atoms. Currently only stable for independent, standalone
|
|
1632
|
+
molecules not bonded to a larger protein/molecule. (For that use _custom_substructures)
|
|
1633
|
+
|
|
1634
|
+
Returns
|
|
1635
|
+
-------
|
|
1636
|
+
topology
|
|
1637
|
+
|
|
1638
|
+
Raises
|
|
1639
|
+
------
|
|
1640
|
+
|
|
1641
|
+
UnassignedChemistryInPDBError
|
|
1642
|
+
If an atom or bond could not be assigned; the exception will
|
|
1643
|
+
provide a detailed diagnostic of what went wrong.
|
|
1644
|
+
|
|
1645
|
+
Examples
|
|
1646
|
+
--------
|
|
1647
|
+
|
|
1648
|
+
>>> from openff.toolkit import Topology
|
|
1649
|
+
>>> from openff.toolkit.utils import get_data_file_path
|
|
1650
|
+
>>> top = Topology.from_pdb(get_data_file_path("proteins/TwoMol_SER_CYS.pdb"))
|
|
1651
|
+
>>> # The molecules in the loaded topology are full-fledged OpenFF Molecule objects
|
|
1652
|
+
>>> for match in top.chemical_environment_matches('[O:1]=[C:2][N:3][H:4]'): print(match.topology_atom_indices)
|
|
1653
|
+
(1, 0, 6, 13)
|
|
1654
|
+
(9, 8, 17, 19)
|
|
1655
|
+
(24, 23, 29, 36)
|
|
1656
|
+
(32, 31, 40, 42)
|
|
1657
|
+
>>> [*top.hierarchy_iterator("residues")]
|
|
1658
|
+
[HierarchyElement ('A', '1', ' ', 'ACE') of iterator 'residues' containing 6 atom(s), HierarchyElement ('A', '2', ' ', 'SER') of iterator 'residues' containing 11 atom(s), HierarchyElement ('A', '3', ' ', 'NME') of iterator 'residues' containing 6 atom(s), HierarchyElement ('B', '1', ' ', 'ACE') of iterator 'residues' containing 6 atom(s), HierarchyElement ('B', '2', ' ', 'CYS') of iterator 'residues' containing 11 atom(s), HierarchyElement ('B', '3', ' ', 'NME') of iterator 'residues' containing 6 atom(s)]
|
|
1659
|
+
|
|
1660
|
+
Polymer systems can also be supported if ``_custom_substructures`` are
|
|
1661
|
+
given as a ``dict[str, list[str]]``, where the keys are unique atom
|
|
1662
|
+
names and the values are lists of substructure SMARTS. The substructure
|
|
1663
|
+
SMARTS must follow the same format as given in the `residue
|
|
1664
|
+
substructure connectivity library
|
|
1665
|
+
<https://github.com/openforcefield/openff-toolkit/blob/main/openff/toolkit/data/proteins/aa_residues_substructures_explicit_bond_orders_with_caps_explicit_connectivity.json>`_:
|
|
1666
|
+
``"<bond>[#<atomic number>D<degree>+<formal charge>:<id>]<bond>"`` for monomer
|
|
1667
|
+
atoms and ``"<bond>[*:<id>]"`` for adjacent neighboring atoms
|
|
1668
|
+
(NOTE: This functionality is experimental!)
|
|
1669
|
+
|
|
1670
|
+
>>> PE_substructs = {
|
|
1671
|
+
... "PE": [
|
|
1672
|
+
... "[#6D4+0:2](-[#1D1+0:3])(-[#1D1+0:4])(-[#6D4+0:5](-[#1D1+0:6])(-[#1D1+0:7])-[*:8])-[*:1]",
|
|
1673
|
+
... "[#6D4+0:2](-[#1D1+0:3])(-[#1D1+0:4])(-[#6D4+0:5](-[#1D1+0:6])(-[#1D1+0:7])-[#1D1+0:8])-[*:1]",
|
|
1674
|
+
... "[#6D4+0:2](-[#1D1+0:3])(-[#1D1+0:4])(-[#6D4+0:5](-[#1D1+0:6])(-[#1D1+0:7])-[*:8])-[#1D1+0:1]",
|
|
1675
|
+
... ]
|
|
1676
|
+
... }
|
|
1677
|
+
>>> top = Topology.from_pdb(
|
|
1678
|
+
... get_data_file_path("systems/test_systems/PE.pdb"),
|
|
1679
|
+
... _custom_substructures=PE_substructs,
|
|
1680
|
+
... )
|
|
1681
|
+
""" # noqa: E501
|
|
1682
|
+
import io
|
|
1683
|
+
import json
|
|
1684
|
+
|
|
1685
|
+
import openmm.unit as openmm_unit
|
|
1686
|
+
from openmm.app import PDBFile
|
|
1687
|
+
|
|
1688
|
+
if isinstance(file_path, str | io.TextIOBase):
|
|
1689
|
+
pass
|
|
1690
|
+
elif isinstance(file_path, Path):
|
|
1691
|
+
file_path = file_path.as_posix()
|
|
1692
|
+
else:
|
|
1693
|
+
raise ValueError(f"Unexpected type {type(file_path)}")
|
|
1694
|
+
|
|
1695
|
+
if not _custom_substructures:
|
|
1696
|
+
_custom_substructures = dict()
|
|
1697
|
+
|
|
1698
|
+
pdb = PDBFile(file_path)
|
|
1699
|
+
|
|
1700
|
+
substructure_file_path = get_data_file_path(
|
|
1701
|
+
"proteins/aa_residues_substructures_explicit_bond_orders_with_caps_explicit_connectivity.json"
|
|
1702
|
+
)
|
|
1703
|
+
|
|
1704
|
+
with open(substructure_file_path) as subfile:
|
|
1705
|
+
substructure_dictionary = json.load(subfile) # preserving order is useful later when saving metadata
|
|
1706
|
+
substructure_dictionary["HOH"] = {"[H:1][O:2][H:3]": ["H1", "O", "H2"]}
|
|
1707
|
+
substructure_dictionary["Li"] = {"[Li+1:1]": ["Li"]}
|
|
1708
|
+
substructure_dictionary["Na"] = {"[Na+1:1]": ["Na"]}
|
|
1709
|
+
substructure_dictionary["K"] = {"[K+1:1]": ["K"]}
|
|
1710
|
+
substructure_dictionary["Rb"] = {"[Rb+1:1]": ["Rb"]}
|
|
1711
|
+
substructure_dictionary["Cs"] = {"[Cs+1:1]": ["Cs"]}
|
|
1712
|
+
substructure_dictionary["F"] = {"[F-1:1]": ["F"]}
|
|
1713
|
+
substructure_dictionary["Cl"] = {"[Cl-1:1]": ["Cl"]}
|
|
1714
|
+
substructure_dictionary["Br"] = {"[Br-1:1]": ["Br"]}
|
|
1715
|
+
substructure_dictionary["I"] = {"[I-1:1]": ["I"]}
|
|
1716
|
+
|
|
1717
|
+
if not (unique_molecules):
|
|
1718
|
+
unique_molecules = []
|
|
1719
|
+
|
|
1720
|
+
substructure_dictionary["UNIQUE_MOLECULE"] = {}
|
|
1721
|
+
|
|
1722
|
+
for unique_molecule in unique_molecules:
|
|
1723
|
+
mapped_smiles = unique_molecule.to_smiles(mapped=True)
|
|
1724
|
+
substructure_dictionary["UNIQUE_MOLECULE"][mapped_smiles] = [a.name for a in unique_molecule.atoms]
|
|
1725
|
+
|
|
1726
|
+
substructure_dictionary["ADDITIONAL_SUBSTRUCTURE"] = {}
|
|
1727
|
+
|
|
1728
|
+
if _additional_substructures:
|
|
1729
|
+
for mol in _additional_substructures:
|
|
1730
|
+
label_mol = Molecule(mol)
|
|
1731
|
+
c = 0
|
|
1732
|
+
label_mol.properties["atom_map"] = {}
|
|
1733
|
+
for atom in label_mol.atoms:
|
|
1734
|
+
if atom.metadata["substructure_atom"]:
|
|
1735
|
+
label_mol.properties["atom_map"][atom.molecule_atom_index] = c
|
|
1736
|
+
c += 1
|
|
1737
|
+
smi = label_mol.to_smiles(mapped=True)
|
|
1738
|
+
# remove unmapped atoms from mapped smiles. This will catch things like
|
|
1739
|
+
# `[H]` and `[Cl]` but not anything with 3 characters like `[H:1]`
|
|
1740
|
+
smi = re.sub(r"\[[A-Za-z]{1,2}\]", "[*]", smi)
|
|
1741
|
+
# Remove any orphaned () that remain
|
|
1742
|
+
smi = smi.replace("()", "")
|
|
1743
|
+
|
|
1744
|
+
substructure_dictionary["ADDITIONAL_SUBSTRUCTURE"][smi] = []
|
|
1745
|
+
|
|
1746
|
+
substructure_dictionary["ADDITIONAL_SUBSTRUCTURE_OVERLAP"] = {}
|
|
1747
|
+
|
|
1748
|
+
coords_angstrom = np.array([[*vec3.value_in_unit(openmm_unit.angstrom)] for vec3 in pdb.getPositions()])
|
|
1749
|
+
|
|
1750
|
+
topology: Topology = toolkit_registry.call(
|
|
1751
|
+
"_polymer_openmm_pdbfile_to_offtop",
|
|
1752
|
+
cls,
|
|
1753
|
+
pdb,
|
|
1754
|
+
substructure_dictionary,
|
|
1755
|
+
coords_angstrom,
|
|
1756
|
+
_custom_substructures,
|
|
1757
|
+
)
|
|
1758
|
+
|
|
1759
|
+
for off_atom, atom in zip(topology.atoms, pdb.topology.atoms()):
|
|
1760
|
+
off_atom.metadata["residue_name"] = atom.residue.name
|
|
1761
|
+
off_atom.metadata["residue_number"] = atom.residue.id
|
|
1762
|
+
off_atom.metadata["insertion_code"] = atom.residue.insertionCode
|
|
1763
|
+
off_atom.metadata["chain_id"] = atom.residue.chain.id
|
|
1764
|
+
off_atom.name = atom.name
|
|
1765
|
+
|
|
1766
|
+
for offmol in topology.molecules:
|
|
1767
|
+
offmol.add_default_hierarchy_schemes()
|
|
1768
|
+
|
|
1769
|
+
return topology
|
|
1770
|
+
|
|
1771
|
+
@requires_package("openmm")
|
|
1772
|
+
def to_openmm(
|
|
1773
|
+
self,
|
|
1774
|
+
ensure_unique_atom_names: str | bool = "residues",
|
|
1775
|
+
) -> "openmm.app.Topology":
|
|
1776
|
+
"""
|
|
1777
|
+
Create an OpenMM Topology object.
|
|
1778
|
+
|
|
1779
|
+
The atom metadata fields `residue_name`, `residue_number`, `insertion_code`, and `chain_id`
|
|
1780
|
+
are used to group atoms into OpenMM residues and chains.
|
|
1781
|
+
|
|
1782
|
+
Contiguously-indexed atoms with the same `residue_name`, `residue_number`, `insertion_code`,
|
|
1783
|
+
and `chain_id` will be put into the same OpenMM residue.
|
|
1784
|
+
|
|
1785
|
+
Contiguously-indexed residues with with the same `chain_id` will be put
|
|
1786
|
+
into the same OpenMM chain.
|
|
1787
|
+
|
|
1788
|
+
This method will never make an OpenMM chain or residue larger than the
|
|
1789
|
+
OpenFF Molecule that it came from. In other words, no chain or residue
|
|
1790
|
+
will span two OpenFF Molecules.
|
|
1791
|
+
|
|
1792
|
+
This method will **not** populate the OpenMM Topology with virtual sites.
|
|
1793
|
+
|
|
1794
|
+
Parameters
|
|
1795
|
+
----------
|
|
1796
|
+
ensure_unique_atom_names
|
|
1797
|
+
Whether to generate new atom names to ensure uniqueness within a
|
|
1798
|
+
molecule or hierarchy element.
|
|
1799
|
+
|
|
1800
|
+
- If the name of a :class:`HierarchyScheme` is given as a string,
|
|
1801
|
+
new atom names will be generated so that each element of that
|
|
1802
|
+
scheme has unique atom names. Molecules without the given
|
|
1803
|
+
hierarchy scheme will be given unique atom names within that
|
|
1804
|
+
molecule.
|
|
1805
|
+
- If ``True``, new atom names will be generated so that atom names
|
|
1806
|
+
are unique within a molecule.
|
|
1807
|
+
- If ``False``, the existing atom names will be used.
|
|
1808
|
+
|
|
1809
|
+
Returns
|
|
1810
|
+
-------
|
|
1811
|
+
openmm_topology
|
|
1812
|
+
An OpenMM Topology object
|
|
1813
|
+
"""
|
|
1814
|
+
# TODO: MT needs to write a virtual sites section of the Interchange user guide.
|
|
1815
|
+
# Once that exists, the last note in this docstring should link to that.
|
|
1816
|
+
from openmm import app
|
|
1817
|
+
|
|
1818
|
+
from openff.toolkit.topology.molecule import Bond
|
|
1819
|
+
|
|
1820
|
+
off_topology = Topology(self)
|
|
1821
|
+
omm_topology = app.Topology()
|
|
1822
|
+
|
|
1823
|
+
off_topology._ensure_unique_atom_names(ensure_unique_atom_names)
|
|
1824
|
+
|
|
1825
|
+
# Go through atoms in OpenFF to preserve the order.
|
|
1826
|
+
omm_atoms = []
|
|
1827
|
+
|
|
1828
|
+
# For each atom in each molecule, determine which chain/residue it should be a part of
|
|
1829
|
+
for molecule in off_topology.molecules:
|
|
1830
|
+
# No chain or residue can span more than one OFF molecule, so reset these to None for the first
|
|
1831
|
+
# atom in each molecule.
|
|
1832
|
+
last_chain = None
|
|
1833
|
+
last_residue = None
|
|
1834
|
+
for atom in molecule.atoms:
|
|
1835
|
+
# If the residue name is undefined, assume a default of "UNK"
|
|
1836
|
+
if "residue_name" in atom.metadata:
|
|
1837
|
+
atom_residue_name = atom.metadata["residue_name"]
|
|
1838
|
+
else:
|
|
1839
|
+
atom_residue_name = "UNK"
|
|
1840
|
+
|
|
1841
|
+
# If the residue number is undefined, assume a default of "0"
|
|
1842
|
+
if "residue_number" in atom.metadata:
|
|
1843
|
+
atom_residue_number = atom.metadata["residue_number"]
|
|
1844
|
+
else:
|
|
1845
|
+
atom_residue_number = "0"
|
|
1846
|
+
|
|
1847
|
+
# If the insertion code is undefined, assume a default of " "
|
|
1848
|
+
if "insertion_code" in atom.metadata:
|
|
1849
|
+
atom_insertion_code = atom.metadata["insertion_code"]
|
|
1850
|
+
else:
|
|
1851
|
+
atom_insertion_code = " "
|
|
1852
|
+
|
|
1853
|
+
# If the chain ID is undefined, assume a default of "X"
|
|
1854
|
+
if "chain_id" in atom.metadata:
|
|
1855
|
+
atom_chain_id = atom.metadata["chain_id"]
|
|
1856
|
+
else:
|
|
1857
|
+
atom_chain_id = "X"
|
|
1858
|
+
|
|
1859
|
+
# Determine whether this atom should be part of the last atom's chain, or if it
|
|
1860
|
+
# should start a new chain
|
|
1861
|
+
if last_chain is None:
|
|
1862
|
+
chain = omm_topology.addChain(atom_chain_id)
|
|
1863
|
+
elif last_chain.id == atom_chain_id:
|
|
1864
|
+
chain = last_chain
|
|
1865
|
+
else:
|
|
1866
|
+
chain = omm_topology.addChain(atom_chain_id)
|
|
1867
|
+
# Determine whether this atom should be a part of the last atom's residue, or if it
|
|
1868
|
+
# should start a new residue
|
|
1869
|
+
if last_residue is None:
|
|
1870
|
+
residue = omm_topology.addResidue(
|
|
1871
|
+
atom_residue_name,
|
|
1872
|
+
chain,
|
|
1873
|
+
id=atom_residue_number,
|
|
1874
|
+
insertionCode=atom_insertion_code,
|
|
1875
|
+
)
|
|
1876
|
+
elif (
|
|
1877
|
+
(last_residue.name == atom_residue_name)
|
|
1878
|
+
and (int(last_residue.id) == int(atom_residue_number))
|
|
1879
|
+
and (last_residue.insertionCode == atom_insertion_code)
|
|
1880
|
+
and (chain.id == last_chain.id) # type: ignore[union-attr]
|
|
1881
|
+
):
|
|
1882
|
+
residue = last_residue
|
|
1883
|
+
else:
|
|
1884
|
+
residue = omm_topology.addResidue(
|
|
1885
|
+
atom_residue_name,
|
|
1886
|
+
chain,
|
|
1887
|
+
id=atom_residue_number,
|
|
1888
|
+
insertionCode=atom_insertion_code,
|
|
1889
|
+
)
|
|
1890
|
+
|
|
1891
|
+
# Add atom.
|
|
1892
|
+
element = app.Element.getByAtomicNumber(atom.atomic_number)
|
|
1893
|
+
omm_atom = omm_topology.addAtom(atom.name, element, residue)
|
|
1894
|
+
|
|
1895
|
+
# Make sure that OpenFF and OpenMM Topology atoms have the same indices.
|
|
1896
|
+
assert off_topology.atom_index(atom) == int(omm_atom.id) - 1
|
|
1897
|
+
omm_atoms.append(omm_atom)
|
|
1898
|
+
|
|
1899
|
+
last_chain = chain
|
|
1900
|
+
last_residue = residue
|
|
1901
|
+
|
|
1902
|
+
# Add all bonds.
|
|
1903
|
+
bond_types = {1: app.Single, 2: app.Double, 3: app.Triple}
|
|
1904
|
+
for bond in molecule.bonds:
|
|
1905
|
+
atom1, atom2 = bond.atoms
|
|
1906
|
+
atom1_idx, atom2_idx = off_topology.atom_index(atom1), off_topology.atom_index(atom2)
|
|
1907
|
+
if isinstance(bond, Bond):
|
|
1908
|
+
if bond.is_aromatic:
|
|
1909
|
+
bond_type = app.Aromatic
|
|
1910
|
+
else:
|
|
1911
|
+
bond_type = bond_types[bond.bond_order]
|
|
1912
|
+
bond_order = bond.bond_order
|
|
1913
|
+
elif isinstance(bond, _SimpleBond):
|
|
1914
|
+
bond_type = None
|
|
1915
|
+
bond_order = None
|
|
1916
|
+
else:
|
|
1917
|
+
raise RuntimeError(
|
|
1918
|
+
"Unexpected bond type found while iterating over Topology.bonds."
|
|
1919
|
+
f"Found {type(bond)}, allowed are Bond and _SimpleBond."
|
|
1920
|
+
)
|
|
1921
|
+
|
|
1922
|
+
omm_topology.addBond(
|
|
1923
|
+
omm_atoms[atom1_idx],
|
|
1924
|
+
omm_atoms[atom2_idx],
|
|
1925
|
+
type=bond_type,
|
|
1926
|
+
order=bond_order,
|
|
1927
|
+
)
|
|
1928
|
+
|
|
1929
|
+
if off_topology.box_vectors is not None:
|
|
1930
|
+
from openff.units.openmm import to_openmm
|
|
1931
|
+
|
|
1932
|
+
omm_topology.setPeriodicBoxVectors(to_openmm(off_topology.box_vectors))
|
|
1933
|
+
return omm_topology
|
|
1934
|
+
|
|
1935
|
+
@requires_package("openmm")
|
|
1936
|
+
def to_file(
|
|
1937
|
+
self,
|
|
1938
|
+
file: Path | str | TextIO,
|
|
1939
|
+
positions: Union["OMMQuantity", Quantity, NDArray] | None = None,
|
|
1940
|
+
file_format: Literal["PDB"] = "PDB",
|
|
1941
|
+
keep_ids: bool = False,
|
|
1942
|
+
ensure_unique_atom_names: str | bool = "residues",
|
|
1943
|
+
):
|
|
1944
|
+
"""
|
|
1945
|
+
Save coordinates and topology to a PDB file.
|
|
1946
|
+
|
|
1947
|
+
Reference: https://github.com/openforcefield/openff-toolkit/issues/502
|
|
1948
|
+
|
|
1949
|
+
Notes:
|
|
1950
|
+
|
|
1951
|
+
1. Atom numbering may not remain same, for example if the atoms
|
|
1952
|
+
in water are numbered as 1001, 1002, 1003, they would change
|
|
1953
|
+
to 1, 2, 3. This doesn't affect the topology or coordinates or
|
|
1954
|
+
atom-ordering in any way.
|
|
1955
|
+
2. Same issue with the amino acid names in the pdb file, they are
|
|
1956
|
+
not returned.
|
|
1957
|
+
|
|
1958
|
+
Parameters
|
|
1959
|
+
----------
|
|
1960
|
+
file
|
|
1961
|
+
A file-like object to write to, or a path to save the file to.
|
|
1962
|
+
positions
|
|
1963
|
+
May be a...
|
|
1964
|
+
|
|
1965
|
+
- ``openmm.unit.Quantity`` object which has atomic positions as a
|
|
1966
|
+
List of unit-tagged ``Vec3`` objects
|
|
1967
|
+
- ``openff.units.unit.Quantity`` object which wraps a
|
|
1968
|
+
``numpy.ndarray`` with dimensions of length
|
|
1969
|
+
- (unitless) 2D ``numpy.ndarray``, in which it is assumed that the
|
|
1970
|
+
positions are in units of Angstroms.
|
|
1971
|
+
- ``None`` (the default), in which case the first conformer of
|
|
1972
|
+
each molecule in the topology will be used.
|
|
1973
|
+
|
|
1974
|
+
file_format
|
|
1975
|
+
Output file format. Case insensitive. Currently only supported values
|
|
1976
|
+
are ``"PDB"``.
|
|
1977
|
+
keep_ids
|
|
1978
|
+
If ``True``, keep the residue and chain IDs specified in the Topology
|
|
1979
|
+
rather than generating new ones.
|
|
1980
|
+
ensure_unique_atom_names
|
|
1981
|
+
Whether to generate new atom names to ensure uniqueness within a
|
|
1982
|
+
molecule or hierarchy element.
|
|
1983
|
+
|
|
1984
|
+
- If the name of a :class:`HierarchyScheme` is given as a string,
|
|
1985
|
+
new atom names will be generated so that each element of that
|
|
1986
|
+
scheme has unique atom names. Molecules without the given
|
|
1987
|
+
hierarchy scheme will be given unique atom names within that
|
|
1988
|
+
molecule.
|
|
1989
|
+
- If ``True``, new atom names will be generated so that atom names
|
|
1990
|
+
are unique within a molecule.
|
|
1991
|
+
- If ``False``, the existing atom names will be used.
|
|
1992
|
+
|
|
1993
|
+
Note that this option cannot guarantee name uniqueness for formats
|
|
1994
|
+
like PDB that truncate long atom names.
|
|
1995
|
+
|
|
1996
|
+
"""
|
|
1997
|
+
import openmm.app
|
|
1998
|
+
import openmm.unit
|
|
1999
|
+
|
|
2000
|
+
# Convert the topology to OpenMM
|
|
2001
|
+
openmm_top = self.to_openmm(ensure_unique_atom_names=ensure_unique_atom_names)
|
|
2002
|
+
|
|
2003
|
+
# Get positions in OpenMM format
|
|
2004
|
+
if isinstance(positions, openmm.unit.Quantity):
|
|
2005
|
+
openmm_positions: openmm.unit.Quantity = positions
|
|
2006
|
+
elif isinstance(positions, Quantity):
|
|
2007
|
+
openmm_positions = positions.to_openmm() # type: ignore[attr-defined]
|
|
2008
|
+
elif isinstance(positions, np.ndarray):
|
|
2009
|
+
openmm_positions = openmm.unit.Quantity(positions, openmm.unit.angstroms)
|
|
2010
|
+
elif positions is None:
|
|
2011
|
+
openmm_positions = self.get_positions().to_openmm() # type: ignore[union-attr]
|
|
2012
|
+
else:
|
|
2013
|
+
raise ValueError(f"Could not process positions of type {type(positions)}.")
|
|
2014
|
+
|
|
2015
|
+
if file_format.upper() == "PDB":
|
|
2016
|
+
import openmm
|
|
2017
|
+
|
|
2018
|
+
# Convert the topology to OpenMM
|
|
2019
|
+
openmm_top = self.to_openmm(ensure_unique_atom_names=ensure_unique_atom_names)
|
|
2020
|
+
|
|
2021
|
+
# Write PDB file
|
|
2022
|
+
ctx_manager: nullcontext[TextIO] | TextIO # MyPy needs some help here
|
|
2023
|
+
if isinstance(file, str | Path):
|
|
2024
|
+
ctx_manager = open(file, "w")
|
|
2025
|
+
else:
|
|
2026
|
+
ctx_manager = nullcontext(file)
|
|
2027
|
+
with ctx_manager as outfile:
|
|
2028
|
+
openmm.app.PDBFile.writeFile(
|
|
2029
|
+
topology=openmm_top,
|
|
2030
|
+
positions=openmm_positions,
|
|
2031
|
+
file=outfile,
|
|
2032
|
+
keepIds=keep_ids,
|
|
2033
|
+
)
|
|
2034
|
+
|
|
2035
|
+
else:
|
|
2036
|
+
raise NotImplementedError("Topology.to_file supports only PDB")
|
|
2037
|
+
|
|
2038
|
+
def get_positions(self) -> Quantity | None:
|
|
2039
|
+
"""
|
|
2040
|
+
Copy the positions of the topology into a new array.
|
|
2041
|
+
|
|
2042
|
+
Topology positions are stored as the first conformer of each molecule.
|
|
2043
|
+
If any molecule has no conformers, this method returns ``None``. Note
|
|
2044
|
+
that modifying the returned array will not update the positions in the
|
|
2045
|
+
topology. To change the positions, use :meth:`Topology.set_positions`.
|
|
2046
|
+
|
|
2047
|
+
See Also
|
|
2048
|
+
--------
|
|
2049
|
+
set_positions
|
|
2050
|
+
clear_positions
|
|
2051
|
+
"""
|
|
2052
|
+
conformers = []
|
|
2053
|
+
for molecule in self.molecules:
|
|
2054
|
+
try:
|
|
2055
|
+
conformer = molecule.conformers[0] # type: ignore[index]
|
|
2056
|
+
except (IndexError, TypeError):
|
|
2057
|
+
return None
|
|
2058
|
+
|
|
2059
|
+
conformer = conformer.m_as(unit.nanometer)
|
|
2060
|
+
|
|
2061
|
+
conformers.append(conformer)
|
|
2062
|
+
positions = np.concatenate(conformers, axis=0)
|
|
2063
|
+
|
|
2064
|
+
return Quantity(positions, unit.nanometer)
|
|
2065
|
+
|
|
2066
|
+
def clear_positions(self):
|
|
2067
|
+
"""
|
|
2068
|
+
Clear the positions of this topology by removing all conformers from its consituent molecules.
|
|
2069
|
+
|
|
2070
|
+
Note that all conformers will be deleted (in-place) from all molecules. Use `Topology.get_positions()`
|
|
2071
|
+
if you wish to save them before clearing.
|
|
2072
|
+
|
|
2073
|
+
See Also
|
|
2074
|
+
--------
|
|
2075
|
+
get_positions
|
|
2076
|
+
set_positions
|
|
2077
|
+
"""
|
|
2078
|
+
for molecule in self.molecules:
|
|
2079
|
+
molecule._conformers = None
|
|
2080
|
+
|
|
2081
|
+
def set_positions(self, array: Quantity) -> None:
|
|
2082
|
+
"""
|
|
2083
|
+
Set the positions in a topology by copying from a single (n, 3) array.
|
|
2084
|
+
|
|
2085
|
+
Note that modifying the original array will not update the positions
|
|
2086
|
+
in the topology; it must be passed again to ``set_positions()``.
|
|
2087
|
+
|
|
2088
|
+
Parameters
|
|
2089
|
+
----------
|
|
2090
|
+
|
|
2091
|
+
array
|
|
2092
|
+
Positions for the topology. Should be a unit-wrapped array-like
|
|
2093
|
+
object with shape (n_atoms, 3) and dimensions of length.
|
|
2094
|
+
|
|
2095
|
+
See Also
|
|
2096
|
+
--------
|
|
2097
|
+
get_positions
|
|
2098
|
+
clear_positions
|
|
2099
|
+
"""
|
|
2100
|
+
if array is None:
|
|
2101
|
+
raise ValueError("array argument cannot be None, use clear_positions instead.")
|
|
2102
|
+
|
|
2103
|
+
if not isinstance(array, Quantity):
|
|
2104
|
+
raise IncompatibleUnitError("array should be an OpenFF Quantity with dimensions of length")
|
|
2105
|
+
|
|
2106
|
+
# Copy the array in nanometers and make it an OpenFF Quantity
|
|
2107
|
+
array = Quantity(np.asarray(array.to(unit.nanometer).magnitude), unit.nanometer)
|
|
2108
|
+
if array.shape != (self.n_atoms, 3):
|
|
2109
|
+
raise WrongShapeError(f"Array has shape {array.shape} but should have shape {self.n_atoms, 3}")
|
|
2110
|
+
|
|
2111
|
+
start = 0
|
|
2112
|
+
for molecule in self.molecules:
|
|
2113
|
+
stop = start + molecule.n_atoms
|
|
2114
|
+
if molecule.conformers is None:
|
|
2115
|
+
molecule._conformers = [array[start:stop]] # type: ignore[index]
|
|
2116
|
+
else:
|
|
2117
|
+
molecule.conformers[0:1] = [array[start:stop]] # type: ignore[index]
|
|
2118
|
+
start = stop
|
|
2119
|
+
|
|
2120
|
+
@classmethod
|
|
2121
|
+
@requires_package("mdtraj")
|
|
2122
|
+
def from_mdtraj(
|
|
2123
|
+
cls,
|
|
2124
|
+
mdtraj_topology: "mdtraj.Topology",
|
|
2125
|
+
unique_molecules: Iterable[MoleculeLike] | None = None,
|
|
2126
|
+
positions: Union[None, "OMMQuantity", Quantity] = None,
|
|
2127
|
+
):
|
|
2128
|
+
"""
|
|
2129
|
+
Construct an OpenFF ``Topology`` from an MDTraj ``Topology``
|
|
2130
|
+
|
|
2131
|
+
This method guarantees that the order of atoms in the input MDTraj
|
|
2132
|
+
Topology will be the same as the ordering of atoms in the output OpenFF
|
|
2133
|
+
Topology. However it does not guarantee the order of the bonds will be
|
|
2134
|
+
the same.
|
|
2135
|
+
|
|
2136
|
+
Hierarchy schemes are taken from the MDTraj topology, not from
|
|
2137
|
+
``unique_molecules``.
|
|
2138
|
+
|
|
2139
|
+
Parameters
|
|
2140
|
+
----------
|
|
2141
|
+
mdtraj_topology
|
|
2142
|
+
The MDTraj Topology object to convert
|
|
2143
|
+
unique_molecules
|
|
2144
|
+
An iterable containing all the unique molecules in the topology.
|
|
2145
|
+
This is used to identify the molecules in the MDTraj topology and
|
|
2146
|
+
provide any missing chemical information. Each chemical species in
|
|
2147
|
+
the topology must be specified exactly once, though the topology
|
|
2148
|
+
may have any number of copies, including zero. The chemical
|
|
2149
|
+
elements of atoms and their bond connectivity will be used to match
|
|
2150
|
+
these reference molecules to the molecules appearing in the
|
|
2151
|
+
topology. If bond orders are specified in the topology, these will
|
|
2152
|
+
be used in matching as well.
|
|
2153
|
+
positions
|
|
2154
|
+
Positions for the atoms in the new topology.
|
|
2155
|
+
|
|
2156
|
+
Returns
|
|
2157
|
+
-------
|
|
2158
|
+
topology
|
|
2159
|
+
An OpenFF Topology object, constructed from the molecules in
|
|
2160
|
+
``unique_molecules``, with the same atom order as the input topology.
|
|
2161
|
+
|
|
2162
|
+
Raises
|
|
2163
|
+
------
|
|
2164
|
+
MissingUniqueMoleculesError
|
|
2165
|
+
If ``unique_molecules`` is ``None``
|
|
2166
|
+
DuplicateUniqueMoleculeError
|
|
2167
|
+
If the same connectivity graph is represented by two different
|
|
2168
|
+
molecules in ``unique_molecules``
|
|
2169
|
+
ValueError
|
|
2170
|
+
If a chemically impossible molecule is detected in the topology
|
|
2171
|
+
"""
|
|
2172
|
+
return cls.from_openmm(
|
|
2173
|
+
mdtraj_topology.to_openmm(),
|
|
2174
|
+
unique_molecules=unique_molecules,
|
|
2175
|
+
positions=positions,
|
|
2176
|
+
)
|
|
2177
|
+
|
|
2178
|
+
# Avoid removing this method, even though it is private and would not be difficult for most
|
|
2179
|
+
# users to replace. Also avoid making it public as round-trips with MDTraj are likely
|
|
2180
|
+
# to not preserve necessary information.
|
|
2181
|
+
@requires_package("mdtraj")
|
|
2182
|
+
def _to_mdtraj(self):
|
|
2183
|
+
"""
|
|
2184
|
+
Create an MDTraj Topology object.
|
|
2185
|
+
Returns
|
|
2186
|
+
----------
|
|
2187
|
+
mdtraj_topology
|
|
2188
|
+
An MDTraj Topology object
|
|
2189
|
+
"""
|
|
2190
|
+
import mdtraj as md
|
|
2191
|
+
|
|
2192
|
+
return md.Topology.from_openmm(self.to_openmm())
|
|
2193
|
+
|
|
2194
|
+
def get_bond_between(self, i: Union[int, "Atom"], j: Union[int, "Atom"]) -> "Bond":
|
|
2195
|
+
"""Returns the bond between two atoms
|
|
2196
|
+
|
|
2197
|
+
Parameters
|
|
2198
|
+
----------
|
|
2199
|
+
i, j
|
|
2200
|
+
Atoms or atom indices to check
|
|
2201
|
+
|
|
2202
|
+
Returns
|
|
2203
|
+
-------
|
|
2204
|
+
bond
|
|
2205
|
+
The bond between i and j.
|
|
2206
|
+
|
|
2207
|
+
"""
|
|
2208
|
+
from openff.toolkit.topology import Atom
|
|
2209
|
+
|
|
2210
|
+
if (type(i) is int) and (type(j) is int):
|
|
2211
|
+
atomi = self.atom(i)
|
|
2212
|
+
atomj = self.atom(j)
|
|
2213
|
+
elif (type(i) is Atom) and (type(j) is Atom):
|
|
2214
|
+
atomi = i
|
|
2215
|
+
atomj = j
|
|
2216
|
+
else:
|
|
2217
|
+
raise ValueError(
|
|
2218
|
+
f"Invalid input passed to is_bonded(). Expected ints or `Atom`s, got {type(i)} and {type(j)}"
|
|
2219
|
+
)
|
|
2220
|
+
|
|
2221
|
+
for bond in atomi.bonds:
|
|
2222
|
+
for atom in bond.atoms:
|
|
2223
|
+
if atom == atomi:
|
|
2224
|
+
continue
|
|
2225
|
+
if atom == atomj:
|
|
2226
|
+
return bond
|
|
2227
|
+
|
|
2228
|
+
raise NotBondedError(f"No bond between atom {i} and {j}")
|
|
2229
|
+
|
|
2230
|
+
def is_bonded(self, i: Union[int, "Atom"], j: Union[int, "Atom"]) -> bool:
|
|
2231
|
+
"""Returns True if the two atoms are bonded
|
|
2232
|
+
|
|
2233
|
+
Parameters
|
|
2234
|
+
----------
|
|
2235
|
+
i, j
|
|
2236
|
+
Atoms or atom indices to check
|
|
2237
|
+
|
|
2238
|
+
Returns
|
|
2239
|
+
-------
|
|
2240
|
+
is_bonded
|
|
2241
|
+
True if atoms are bonded, False otherwise.
|
|
2242
|
+
|
|
2243
|
+
"""
|
|
2244
|
+
try:
|
|
2245
|
+
self.get_bond_between(i, j)
|
|
2246
|
+
return True
|
|
2247
|
+
except NotBondedError:
|
|
2248
|
+
return False
|
|
2249
|
+
|
|
2250
|
+
def atom(self, atom_topology_index: int) -> "Atom":
|
|
2251
|
+
"""
|
|
2252
|
+
Get the Atom at a given Topology atom index.
|
|
2253
|
+
|
|
2254
|
+
Parameters
|
|
2255
|
+
----------
|
|
2256
|
+
atom_topology_index
|
|
2257
|
+
The index of the Atom in this Topology
|
|
2258
|
+
|
|
2259
|
+
Returns
|
|
2260
|
+
-------
|
|
2261
|
+
An openff.toolkit.topology.Atom
|
|
2262
|
+
"""
|
|
2263
|
+
if not isinstance(atom_topology_index, int):
|
|
2264
|
+
raise ValueError(
|
|
2265
|
+
"Argument passed to `Topology.atom` must be an int. "
|
|
2266
|
+
f"Given argument of type {type(atom_topology_index)}."
|
|
2267
|
+
)
|
|
2268
|
+
|
|
2269
|
+
if not (0 <= atom_topology_index < self.n_atoms):
|
|
2270
|
+
raise AtomNotInTopologyError(
|
|
2271
|
+
f"No atom with index {atom_topology_index} exists in this topology, "
|
|
2272
|
+
f"which contains {self.n_atoms} atoms."
|
|
2273
|
+
)
|
|
2274
|
+
|
|
2275
|
+
this_molecule_start_index = 0
|
|
2276
|
+
next_molecule_start_index = 0
|
|
2277
|
+
for molecule in self.molecules:
|
|
2278
|
+
next_molecule_start_index += molecule.n_atoms
|
|
2279
|
+
if next_molecule_start_index > atom_topology_index:
|
|
2280
|
+
atom_molecule_index = atom_topology_index - this_molecule_start_index
|
|
2281
|
+
# NOTE: the index here should still be in the topology index order, NOT the reference molecule's
|
|
2282
|
+
# can Molecule.atom be a _SimpleAtom?
|
|
2283
|
+
return molecule.atom(atom_molecule_index) # type: ignore[return-value]
|
|
2284
|
+
this_molecule_start_index += molecule.n_atoms
|
|
2285
|
+
|
|
2286
|
+
raise AtomNotInTopologyError(
|
|
2287
|
+
f"No atom with index {atom_topology_index} exists in this topology, which contains {self.n_atoms} atoms."
|
|
2288
|
+
)
|
|
2289
|
+
|
|
2290
|
+
# Potentially more computationally efficient lookup ( O(largest_molecule_natoms)? )
|
|
2291
|
+
# start_index_2_top_mol is an ordered dict of [starting_atom_index] --> [topology_molecule]
|
|
2292
|
+
# search_range = range(atom_topology_index - largest_molecule_natoms, atom_topology_index)
|
|
2293
|
+
# search_index = atom_topology_index
|
|
2294
|
+
# Only efficient if start_index_2_top_mol.keys() is a set (constant time lookups)
|
|
2295
|
+
# while not(search_index in start_index_2_top_mol.keys()):
|
|
2296
|
+
# search_index -= 1
|
|
2297
|
+
# topology_molecule = start_index_2_top_mol(search_index)
|
|
2298
|
+
# atom_molecule_index = atom_topology_index - search_index
|
|
2299
|
+
# return topology_molecule.atom(atom_molecule_index)
|
|
2300
|
+
|
|
2301
|
+
def bond(self, bond_topology_index: int) -> "Bond": # type: ignore[return]
|
|
2302
|
+
"""
|
|
2303
|
+
Get the Bond at a given Topology bond index.
|
|
2304
|
+
|
|
2305
|
+
Parameters
|
|
2306
|
+
----------
|
|
2307
|
+
bond_topology_index
|
|
2308
|
+
The index of the Bond in this Topology
|
|
2309
|
+
|
|
2310
|
+
Returns
|
|
2311
|
+
-------
|
|
2312
|
+
An openff.toolkit.topology.Bond
|
|
2313
|
+
"""
|
|
2314
|
+
if not isinstance(bond_topology_index, int):
|
|
2315
|
+
raise ValueError(
|
|
2316
|
+
"Argument passed to `Topology.bond` must be an int. "
|
|
2317
|
+
f"Given argument of type {type(bond_topology_index)}."
|
|
2318
|
+
)
|
|
2319
|
+
|
|
2320
|
+
if not (0 <= bond_topology_index < self.n_bonds):
|
|
2321
|
+
raise BondNotInTopologyError(
|
|
2322
|
+
f"No bond with index {bond_topology_index} exists in this topology, "
|
|
2323
|
+
f"which contains {self.n_bonds} bonds."
|
|
2324
|
+
)
|
|
2325
|
+
|
|
2326
|
+
this_molecule_start_index = 0
|
|
2327
|
+
next_molecule_start_index = 0
|
|
2328
|
+
for molecule in self._molecules:
|
|
2329
|
+
next_molecule_start_index += molecule.n_bonds
|
|
2330
|
+
if next_molecule_start_index > bond_topology_index:
|
|
2331
|
+
bond_molecule_index = bond_topology_index - this_molecule_start_index
|
|
2332
|
+
return molecule.bond(bond_molecule_index)
|
|
2333
|
+
this_molecule_start_index += molecule.n_bonds
|
|
2334
|
+
|
|
2335
|
+
def add_molecule(
|
|
2336
|
+
self,
|
|
2337
|
+
molecule: MoleculeLike,
|
|
2338
|
+
) -> int:
|
|
2339
|
+
"""
|
|
2340
|
+
Add a molecule to the topology.
|
|
2341
|
+
|
|
2342
|
+
To add multiple molecules, particularly many times, use `add_molecules` for better performance.
|
|
2343
|
+
"""
|
|
2344
|
+
if isinstance(molecule, Molecule | _SimpleMolecule):
|
|
2345
|
+
# Route everything through add_molecules for simplicity; the overhead of
|
|
2346
|
+
# making a list and grabbing the first element should be negligible
|
|
2347
|
+
return self.add_molecules([molecule])[0]
|
|
2348
|
+
|
|
2349
|
+
else:
|
|
2350
|
+
raise ValueError(f"Invalid type {type(molecule)} for Topology.add_molecule")
|
|
2351
|
+
|
|
2352
|
+
def add_molecules(
|
|
2353
|
+
self,
|
|
2354
|
+
molecules: list[MoleculeLike],
|
|
2355
|
+
) -> list[int]:
|
|
2356
|
+
"""
|
|
2357
|
+
Add molecules to the topology.
|
|
2358
|
+
|
|
2359
|
+
To add a single molecule to the topology, use `add_molecule`.
|
|
2360
|
+
"""
|
|
2361
|
+
|
|
2362
|
+
if isinstance(molecules, list):
|
|
2363
|
+
indices = [self._add_molecule_keep_cache(molecule) for molecule in molecules]
|
|
2364
|
+
|
|
2365
|
+
self._invalidate_cached_properties()
|
|
2366
|
+
|
|
2367
|
+
return indices
|
|
2368
|
+
|
|
2369
|
+
else:
|
|
2370
|
+
raise ValueError(f"Invalid type {type(molecules)} for Topology.add_molecules")
|
|
2371
|
+
|
|
2372
|
+
def _add_molecule_keep_cache(self, molecule: MoleculeLike) -> int:
|
|
2373
|
+
self._molecules.append(deepcopy(molecule))
|
|
2374
|
+
|
|
2375
|
+
# Ensure this is 0-indexed
|
|
2376
|
+
return len(self._molecules) - 1
|
|
2377
|
+
|
|
2378
|
+
def add_constraint(self, iatom, jatom, distance=True):
|
|
2379
|
+
"""
|
|
2380
|
+
Mark a pair of atoms as constrained.
|
|
2381
|
+
|
|
2382
|
+
Constraints between atoms that are not bonded (e.g., rigid waters) are permissible.
|
|
2383
|
+
|
|
2384
|
+
Parameters
|
|
2385
|
+
----------
|
|
2386
|
+
iatom, jatom
|
|
2387
|
+
Atoms to mark as constrained
|
|
2388
|
+
These atoms may be bonded or not in the Topology
|
|
2389
|
+
distance
|
|
2390
|
+
Constraint distance
|
|
2391
|
+
``True`` if distance has yet to be determined
|
|
2392
|
+
``False`` if constraint is to be removed
|
|
2393
|
+
|
|
2394
|
+
"""
|
|
2395
|
+
# Check that constraint hasn't already been specified.
|
|
2396
|
+
if (iatom, jatom) in self._constrained_atom_pairs:
|
|
2397
|
+
existing_distance = self._constrained_atom_pairs[(iatom, jatom)]
|
|
2398
|
+
if isinstance(existing_distance, Quantity) and distance is True:
|
|
2399
|
+
raise ConstraintExsistsError(
|
|
2400
|
+
f"Atoms ({iatom},{jatom}) already constrained with distance {existing_distance} "
|
|
2401
|
+
"but attempting to override with unspecified distance"
|
|
2402
|
+
)
|
|
2403
|
+
if (existing_distance is True) and (distance is True):
|
|
2404
|
+
raise ConstraintExsistsError(
|
|
2405
|
+
f"Atoms ({iatom},{jatom}) already constrained with unspecified distance "
|
|
2406
|
+
"but attempting to override with unspecified distance"
|
|
2407
|
+
)
|
|
2408
|
+
if distance is False:
|
|
2409
|
+
del self._constrained_atom_pairs[(iatom, jatom)]
|
|
2410
|
+
del self._constrained_atom_pairs[(jatom, iatom)]
|
|
2411
|
+
return
|
|
2412
|
+
|
|
2413
|
+
self._constrained_atom_pairs[(iatom, jatom)] = distance
|
|
2414
|
+
self._constrained_atom_pairs[(jatom, iatom)] = distance
|
|
2415
|
+
|
|
2416
|
+
def is_constrained(self, iatom, jatom):
|
|
2417
|
+
"""
|
|
2418
|
+
Check if a pair of atoms are marked as constrained.
|
|
2419
|
+
|
|
2420
|
+
Parameters
|
|
2421
|
+
----------
|
|
2422
|
+
iatom, jatom
|
|
2423
|
+
Indices of atoms to mark as constrained.
|
|
2424
|
+
|
|
2425
|
+
Returns
|
|
2426
|
+
-------
|
|
2427
|
+
distance
|
|
2428
|
+
True if constrained but constraints have not yet been applied
|
|
2429
|
+
Distance if constraint has already been added to Topology
|
|
2430
|
+
|
|
2431
|
+
"""
|
|
2432
|
+
if (iatom, jatom) in self._constrained_atom_pairs:
|
|
2433
|
+
return self._constrained_atom_pairs[(iatom, jatom)]
|
|
2434
|
+
else:
|
|
2435
|
+
return False
|
|
2436
|
+
|
|
2437
|
+
@requires_package("nglview")
|
|
2438
|
+
def visualize(self, ensure_correct_connectivity: bool = False) -> "NGLWidget":
|
|
2439
|
+
"""
|
|
2440
|
+
Visualize with NGLView.
|
|
2441
|
+
|
|
2442
|
+
Requires all molecules in this topology have positions.
|
|
2443
|
+
|
|
2444
|
+
NGLView is a 3D molecular visualization library for use in Jupyter
|
|
2445
|
+
notebooks. Note that for performance reasons, by default the
|
|
2446
|
+
visualized connectivity is inferred from positions and may not reflect
|
|
2447
|
+
the connectivity in the ``Topology``.
|
|
2448
|
+
|
|
2449
|
+
Parameters
|
|
2450
|
+
----------
|
|
2451
|
+
|
|
2452
|
+
ensure_correct_connectivity
|
|
2453
|
+
If ``True``, the visualization will be guaranteed to reflect the
|
|
2454
|
+
connectivity in the ``Topology``. Note that this will severely
|
|
2455
|
+
degrade performance, especially for topologies with many atoms.
|
|
2456
|
+
|
|
2457
|
+
Examples
|
|
2458
|
+
--------
|
|
2459
|
+
|
|
2460
|
+
Visualize a complex PDB file
|
|
2461
|
+
|
|
2462
|
+
>>> from openff.toolkit import Topology
|
|
2463
|
+
>>> from openff.toolkit.utils.utils import get_data_file_path
|
|
2464
|
+
>>> pdb_filename = get_data_file_path("systems/test_systems/T4_lysozyme_water_ions.pdb")
|
|
2465
|
+
>>> topology = Topology.from_pdb(pdb_filename)
|
|
2466
|
+
>>> topology.visualize() # doctest: +SKIP
|
|
2467
|
+
|
|
2468
|
+
"""
|
|
2469
|
+
import nglview
|
|
2470
|
+
|
|
2471
|
+
from openff.toolkit.utils._viz import TopologyNGLViewStructure
|
|
2472
|
+
|
|
2473
|
+
if ensure_correct_connectivity:
|
|
2474
|
+
raise ValueError(
|
|
2475
|
+
"`ensure_correct_connectivity` not (yet) implemented "
|
|
2476
|
+
"(requires passing multi-molecule SDF files to NGLview)"
|
|
2477
|
+
)
|
|
2478
|
+
|
|
2479
|
+
if self.get_positions() is None:
|
|
2480
|
+
raise MissingConformersError(
|
|
2481
|
+
"All molecules in this topology must have positions for it to be visualized in a widget."
|
|
2482
|
+
)
|
|
2483
|
+
|
|
2484
|
+
widget = nglview.NGLWidget(
|
|
2485
|
+
TopologyNGLViewStructure(
|
|
2486
|
+
topology=self,
|
|
2487
|
+
ext="pdb",
|
|
2488
|
+
),
|
|
2489
|
+
representations=[
|
|
2490
|
+
dict(type="unitcell", params=dict()),
|
|
2491
|
+
],
|
|
2492
|
+
)
|
|
2493
|
+
|
|
2494
|
+
widget.add_representation("line", sele="water")
|
|
2495
|
+
widget.add_representation("spacefill", sele="ion")
|
|
2496
|
+
widget.add_representation("cartoon", sele="protein")
|
|
2497
|
+
widget.add_representation(
|
|
2498
|
+
"licorice",
|
|
2499
|
+
sele="not water and not ion and not protein",
|
|
2500
|
+
radius=0.25,
|
|
2501
|
+
multipleBond=bool(ensure_correct_connectivity),
|
|
2502
|
+
)
|
|
2503
|
+
|
|
2504
|
+
return widget
|
|
2505
|
+
|
|
2506
|
+
def hierarchy_iterator(
|
|
2507
|
+
self,
|
|
2508
|
+
iter_name: str,
|
|
2509
|
+
) -> Iterator[HierarchyElement]:
|
|
2510
|
+
"""
|
|
2511
|
+
Iterate over all molecules with the given hierarchy scheme.
|
|
2512
|
+
|
|
2513
|
+
Get an iterator over hierarchy elements from all of the molecules in
|
|
2514
|
+
this topology that provide the appropriately named iterator. This
|
|
2515
|
+
iterator will yield hierarchy elements sorted first by the order that
|
|
2516
|
+
molecules are listed in the Topology, and second by the specific
|
|
2517
|
+
sorting of hierarchy elements defined in each molecule. Molecules
|
|
2518
|
+
without the named iterator are not included.
|
|
2519
|
+
|
|
2520
|
+
Parameters
|
|
2521
|
+
----------
|
|
2522
|
+
iter_name
|
|
2523
|
+
The iterator name associated with the HierarchyScheme to retrieve
|
|
2524
|
+
(for example 'residues' or 'chains')
|
|
2525
|
+
|
|
2526
|
+
Returns
|
|
2527
|
+
-------
|
|
2528
|
+
iterator of :class:`HierarchyElement`
|
|
2529
|
+
|
|
2530
|
+
See also
|
|
2531
|
+
--------
|
|
2532
|
+
HierarchyScheme, HierarchyElement, Molecule.hierarchy_schemes
|
|
2533
|
+
"""
|
|
2534
|
+
for molecule in self._molecules:
|
|
2535
|
+
if hasattr(molecule, iter_name):
|
|
2536
|
+
yield from getattr(molecule, iter_name)
|
|
2537
|
+
|
|
2538
|
+
def __getattr__(self, name: str) -> list["HierarchyElement"]:
|
|
2539
|
+
"""If a requested attribute is not found, check the hierarchy schemes"""
|
|
2540
|
+
# Avoid attempting to process dunder methods as hierarchy scheme iterator names
|
|
2541
|
+
if name.startswith("__"):
|
|
2542
|
+
raise AttributeError
|
|
2543
|
+
|
|
2544
|
+
try:
|
|
2545
|
+
return [
|
|
2546
|
+
element
|
|
2547
|
+
for molecule in self.molecules
|
|
2548
|
+
for element in molecule.hierarchy_schemes[name].hierarchy_elements
|
|
2549
|
+
]
|
|
2550
|
+
except (KeyError, AttributeError) as error:
|
|
2551
|
+
raise AttributeError(
|
|
2552
|
+
f"'{self.__class__.__name__}' object has no attribute '{name}'. If looking for a "
|
|
2553
|
+
"`HierarchyScheme` iterator, not all molecules in this topology have an interator "
|
|
2554
|
+
f"name {name} defined."
|
|
2555
|
+
) from error
|