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,4246 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Tests for molecular topology representations
|
|
3
|
+
|
|
4
|
+
At least one supported cheminformatics toolkit must be installed to run these tests.
|
|
5
|
+
Only the tests applicable to that toolkit will be run.
|
|
6
|
+
|
|
7
|
+
TODO:
|
|
8
|
+
- Will the ToolkitWrapper allow us to pare down importing each wrapper directly?
|
|
9
|
+
- Add tests comparing RDKit and OpenEye aromaticity perception
|
|
10
|
+
- Right now, the test database of TestMolecule is read from mol2, requiring the OE
|
|
11
|
+
toolkit. Find a different test set that RDKit can read, or make a database of
|
|
12
|
+
serialized OFFMols.
|
|
13
|
+
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import copy
|
|
17
|
+
import os
|
|
18
|
+
import pathlib
|
|
19
|
+
import pickle
|
|
20
|
+
import re
|
|
21
|
+
import warnings
|
|
22
|
+
from tempfile import NamedTemporaryFile
|
|
23
|
+
from unittest.mock import Mock
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
import pytest
|
|
27
|
+
from openff.units.elements import MASSES, SYMBOLS
|
|
28
|
+
|
|
29
|
+
from openff.toolkit import unit
|
|
30
|
+
from openff.toolkit._tests.create_molecules import (
|
|
31
|
+
create_acetaldehyde,
|
|
32
|
+
create_benzene_no_aromatic,
|
|
33
|
+
create_cis_1_2_dichloroethene,
|
|
34
|
+
create_cyclohexane,
|
|
35
|
+
create_ethanol,
|
|
36
|
+
create_reversed_ethanol,
|
|
37
|
+
)
|
|
38
|
+
from openff.toolkit._tests.utils import (
|
|
39
|
+
has_pkg,
|
|
40
|
+
requires_ambertools,
|
|
41
|
+
requires_openeye,
|
|
42
|
+
requires_pkg,
|
|
43
|
+
requires_rdkit,
|
|
44
|
+
)
|
|
45
|
+
from openff.toolkit.topology.molecule import (
|
|
46
|
+
Atom,
|
|
47
|
+
Bond,
|
|
48
|
+
BondExistsError,
|
|
49
|
+
FrozenMolecule,
|
|
50
|
+
HierarchyElement,
|
|
51
|
+
HierarchyScheme,
|
|
52
|
+
HierarchySchemeNotFoundException,
|
|
53
|
+
HierarchySchemeWithIteratorNameAlreadyRegisteredException,
|
|
54
|
+
InvalidAtomMetadataError,
|
|
55
|
+
Molecule,
|
|
56
|
+
SmilesParsingError,
|
|
57
|
+
_networkx_graph_to_hill_formula,
|
|
58
|
+
)
|
|
59
|
+
from openff.toolkit.utils import get_data_file_path
|
|
60
|
+
from openff.toolkit.utils.exceptions import (
|
|
61
|
+
AtomMappingWarning,
|
|
62
|
+
BadMoleculeAssumptionError,
|
|
63
|
+
HierarchyIteratorNameConflictError,
|
|
64
|
+
IncompatibleShapeError,
|
|
65
|
+
IncompatibleTypeError,
|
|
66
|
+
IncompatibleUnitError,
|
|
67
|
+
InvalidBondOrderError,
|
|
68
|
+
InvalidConformerError,
|
|
69
|
+
InvalidQCInputError,
|
|
70
|
+
MissingCMILESError,
|
|
71
|
+
MissingConformersError,
|
|
72
|
+
MissingPartialChargesError,
|
|
73
|
+
MultipleMoleculesInPDBError,
|
|
74
|
+
NotBondedError,
|
|
75
|
+
RemapIndexError,
|
|
76
|
+
UnassignedChemistryInPDBError,
|
|
77
|
+
UnsupportedFileTypeError,
|
|
78
|
+
)
|
|
79
|
+
from openff.toolkit.utils.toolkits import (
|
|
80
|
+
AmberToolsToolkitWrapper,
|
|
81
|
+
BuiltInToolkitWrapper,
|
|
82
|
+
OpenEyeToolkitWrapper,
|
|
83
|
+
RDKitToolkitWrapper,
|
|
84
|
+
ToolkitRegistry,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def assert_molecule_is_equal(molecule1, molecule2, msg):
|
|
89
|
+
"""Compare whether two Molecule objects are equal
|
|
90
|
+
|
|
91
|
+
Parameters
|
|
92
|
+
----------
|
|
93
|
+
molecule1, molecule2 : openff.toolkit.topology.Molecule
|
|
94
|
+
Molecules to be compared
|
|
95
|
+
msg : str
|
|
96
|
+
Message to include if molecules fail to match.
|
|
97
|
+
|
|
98
|
+
"""
|
|
99
|
+
if not (molecule1.is_isomorphic_with(molecule2)):
|
|
100
|
+
raise AssertionError(msg)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def is_four_membered_ring_torsion(torsion):
|
|
104
|
+
"""Check that three atoms in the given torsion form a four-membered ring."""
|
|
105
|
+
# Push a copy of the first and second atom in the end to make the code simpler.
|
|
106
|
+
torsion = [*list(torsion), torsion[0], torsion[1]]
|
|
107
|
+
|
|
108
|
+
is_four_membered_ring = True
|
|
109
|
+
for i in range(4):
|
|
110
|
+
# The atom is bonded to the next one.
|
|
111
|
+
is_four_membered_ring &= torsion[i].is_bonded_to(torsion[i + 1])
|
|
112
|
+
# The atom is not bonded to the atom on its diagonal.
|
|
113
|
+
is_four_membered_ring &= not torsion[i].is_bonded_to(torsion[i + 2])
|
|
114
|
+
|
|
115
|
+
return is_four_membered_ring
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def is_three_membered_ring_torsion(torsion):
|
|
119
|
+
"""Check that three atoms in the given torsion form a three-membered ring.
|
|
120
|
+
|
|
121
|
+
In order to be 4 atoms with a three-membered ring, there must be
|
|
122
|
+
1) A central atom connected to all other atoms.
|
|
123
|
+
2) An atom outside the ring connected exclusively to the central atom.
|
|
124
|
+
3) Two atoms in the ring connected to the central atom and to each other.
|
|
125
|
+
|
|
126
|
+
"""
|
|
127
|
+
# A set of atom indices for the atoms in the torsion.
|
|
128
|
+
torsion_atom_indices = set(a.molecule_atom_index for a in torsion)
|
|
129
|
+
|
|
130
|
+
# Collect all the bonds involving exclusively atoms in the torsion.
|
|
131
|
+
bonds_by_atom_idx = {i: set() for i in torsion_atom_indices}
|
|
132
|
+
for atom in torsion:
|
|
133
|
+
for bond in atom.bonds:
|
|
134
|
+
# Consider the bond only if both atoms are in the torsion.
|
|
135
|
+
if bond.atom1_index in torsion_atom_indices and bond.atom2_index in torsion_atom_indices:
|
|
136
|
+
bonds_by_atom_idx[bond.atom1_index].add(bond.atom2_index)
|
|
137
|
+
bonds_by_atom_idx[bond.atom2_index].add(bond.atom1_index)
|
|
138
|
+
|
|
139
|
+
# Find the central atom, which is connected to all other atoms.
|
|
140
|
+
atom_indices = [i for i in torsion_atom_indices if len(bonds_by_atom_idx[i]) == 3]
|
|
141
|
+
if len(atom_indices) != 1:
|
|
142
|
+
return False
|
|
143
|
+
central_atom_idx = atom_indices[0]
|
|
144
|
+
|
|
145
|
+
# Find the atom outside the ring.
|
|
146
|
+
atom_indices = [i for i in torsion_atom_indices if len(bonds_by_atom_idx[i]) == 1]
|
|
147
|
+
if len(atom_indices) != 1 or central_atom_idx not in bonds_by_atom_idx[atom_indices[0]]:
|
|
148
|
+
return False
|
|
149
|
+
outside_atom_idx = atom_indices[0]
|
|
150
|
+
|
|
151
|
+
# Check that the remaining two atoms are non-central atoms in the membered ring.
|
|
152
|
+
atom1, atom2 = (i for i in torsion_atom_indices if i not in [central_atom_idx, outside_atom_idx])
|
|
153
|
+
# The two atoms are bonded to each other.
|
|
154
|
+
if atom2 not in bonds_by_atom_idx[atom1] or atom1 not in bonds_by_atom_idx[atom2]:
|
|
155
|
+
return False
|
|
156
|
+
# Check that they are both bonded to the central atom and none other.
|
|
157
|
+
for atom_idx in [atom1, atom2]:
|
|
158
|
+
if central_atom_idx not in bonds_by_atom_idx[atom_idx] or len(bonds_by_atom_idx[atom_idx]) != 2:
|
|
159
|
+
return False
|
|
160
|
+
|
|
161
|
+
# This is a torsion including a three-membered ring.
|
|
162
|
+
return True
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def mini_drug_bank(xfail_mols=None, wip_mols=None):
|
|
166
|
+
"""Load the full MiniDrugBank into Molecule objects.
|
|
167
|
+
|
|
168
|
+
Parameters
|
|
169
|
+
----------
|
|
170
|
+
xfail_mols : dict[str, str or None]
|
|
171
|
+
Dictionary mapping the molecule names that are allowed to
|
|
172
|
+
failed to the failure reason.
|
|
173
|
+
wip_mols : dict[str, str or None]
|
|
174
|
+
Dictionary mapping the molecule names that are work in progress
|
|
175
|
+
to the failure reason.
|
|
176
|
+
|
|
177
|
+
"""
|
|
178
|
+
# If we have already loaded the data set, return the cached one.
|
|
179
|
+
if mini_drug_bank.molecules is not None:
|
|
180
|
+
molecules = mini_drug_bank.molecules
|
|
181
|
+
else:
|
|
182
|
+
# Load the dataset.
|
|
183
|
+
file_path = get_data_file_path("molecules/MiniDrugBank_tripos.mol2")
|
|
184
|
+
try:
|
|
185
|
+
# We need OpenEye to parse the molecules, but pytest execute this
|
|
186
|
+
# whether or not the test class is skipped so if OE is not available
|
|
187
|
+
# we just return an empty list of test cases as a workaround.
|
|
188
|
+
molecules = Molecule.from_file(file_path, allow_undefined_stereo=True)
|
|
189
|
+
except NotImplementedError as e:
|
|
190
|
+
assert "No toolkits in registry can read file" in str(e)
|
|
191
|
+
mini_drug_bank.molecules = []
|
|
192
|
+
return []
|
|
193
|
+
else:
|
|
194
|
+
mini_drug_bank.molecules = molecules
|
|
195
|
+
|
|
196
|
+
# Check if we need to mark anything.
|
|
197
|
+
if xfail_mols is None and wip_mols is None:
|
|
198
|
+
return molecules
|
|
199
|
+
|
|
200
|
+
# Handle mutable default.
|
|
201
|
+
if xfail_mols is None:
|
|
202
|
+
xfail_mols = {}
|
|
203
|
+
if wip_mols is None:
|
|
204
|
+
wip_mols = {}
|
|
205
|
+
# There should be no molecule in both dictionaries.
|
|
206
|
+
assert len(set(xfail_mols).intersection(set(wip_mols))) == 0
|
|
207
|
+
|
|
208
|
+
# Don't modify the cached molecules.
|
|
209
|
+
molecules = copy.deepcopy(molecules)
|
|
210
|
+
for i, mol in enumerate(molecules):
|
|
211
|
+
if mol.name in xfail_mols:
|
|
212
|
+
marker = pytest.mark.xfail(reason=xfail_mols[mol.name])
|
|
213
|
+
elif mol.name in wip_mols:
|
|
214
|
+
marker = pytest.mark.wip(reason=wip_mols[mol.name])
|
|
215
|
+
else:
|
|
216
|
+
marker = None
|
|
217
|
+
|
|
218
|
+
if marker is not None:
|
|
219
|
+
molecules[i] = pytest.param(mol, marks=marker)
|
|
220
|
+
|
|
221
|
+
return molecules
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# Use a "static" variable as a workaround as fixtures cannot be
|
|
225
|
+
# used inside pytest.mark.parametrize (see issue #349 in pytest).
|
|
226
|
+
mini_drug_bank.molecules = None # type: ignore
|
|
227
|
+
|
|
228
|
+
# All the molecules that raise UndefinedStereochemistryError when read by OETK()
|
|
229
|
+
openeye_drugbank_undefined_stereo_mols = {
|
|
230
|
+
"DrugBank_1634",
|
|
231
|
+
"DrugBank_1700",
|
|
232
|
+
"DrugBank_1962",
|
|
233
|
+
"DrugBank_2519",
|
|
234
|
+
"DrugBank_2987",
|
|
235
|
+
"DrugBank_3502",
|
|
236
|
+
"DrugBank_3930",
|
|
237
|
+
"DrugBank_4161",
|
|
238
|
+
"DrugBank_4162",
|
|
239
|
+
"DrugBank_5043",
|
|
240
|
+
"DrugBank_5418",
|
|
241
|
+
"DrugBank_6531",
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
# All the molecules that raise UndefinedStereochemistryError when read by RDKTKW().
|
|
245
|
+
# Note that this list is different from that for OEMol,
|
|
246
|
+
# since the toolkits have different definitions of "stereogenic"
|
|
247
|
+
rdkit_drugbank_undefined_stereo_mols = {
|
|
248
|
+
"DrugBank_1634",
|
|
249
|
+
"DrugBank_1962",
|
|
250
|
+
"DrugBank_2519",
|
|
251
|
+
"DrugBank_3930",
|
|
252
|
+
"DrugBank_5043",
|
|
253
|
+
"DrugBank_5418",
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# Missing stereo in OE but not RDK: 'DrugBank_2987', 'DrugBank_3502', 'DrugBank_4161',
|
|
258
|
+
# 'DrugBank_4162', 'DrugBank_6531', 'DrugBank_1700',
|
|
259
|
+
drugbank_stereogenic_in_rdkit_but_not_openeye = {
|
|
260
|
+
"DrugBank_5329",
|
|
261
|
+
"DrugBank_7124",
|
|
262
|
+
"DrugBank_6865",
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
# Some molecules are _valid_ in both OETK and RDKit, but will fail if you try
|
|
266
|
+
# to convert from one to the other, since OE adds stereo that RDKit doesn't
|
|
267
|
+
drugbank_stereogenic_in_oe_but_not_rdkit = {
|
|
268
|
+
"DrugBank_1598",
|
|
269
|
+
"DrugBank_4346",
|
|
270
|
+
"DrugBank_1849",
|
|
271
|
+
"DrugBank_2141",
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class TestAtom:
|
|
276
|
+
"""Test Atom class."""
|
|
277
|
+
|
|
278
|
+
def test_atom_constructor(self):
|
|
279
|
+
"""Test Atom creation"""
|
|
280
|
+
# Create a non-aromatic carbon atom
|
|
281
|
+
atom1 = Atom(6, 0, False)
|
|
282
|
+
assert atom1.atomic_number == 6
|
|
283
|
+
assert atom1.formal_charge == 0 * unit.elementary_charge
|
|
284
|
+
|
|
285
|
+
# Create a chiral carbon atom
|
|
286
|
+
atom2 = Atom(6, 0, False, stereochemistry="R", name="CT")
|
|
287
|
+
assert atom1.stereochemistry != atom2.stereochemistry
|
|
288
|
+
|
|
289
|
+
# Ensure that formal charge can also be set as a Quantity
|
|
290
|
+
atom1 = Atom(6, 1 * unit.elementary_charge, False)
|
|
291
|
+
assert atom1.formal_charge == 1 * unit.elementary_charge
|
|
292
|
+
|
|
293
|
+
def test_init_invalid_atoms(self):
|
|
294
|
+
with pytest.raises(ValueError, match="must be int"):
|
|
295
|
+
Atom(0.5, 0, False)
|
|
296
|
+
|
|
297
|
+
with pytest.raises(ValueError, match="must be int"):
|
|
298
|
+
Atom(1 / 2, 0, False)
|
|
299
|
+
|
|
300
|
+
with pytest.raises(ValueError, match="must be positive"):
|
|
301
|
+
Atom(0, 0, False)
|
|
302
|
+
|
|
303
|
+
with pytest.raises(ValueError, match="must be positive"):
|
|
304
|
+
Atom(-1, 0, False)
|
|
305
|
+
|
|
306
|
+
@pytest.mark.parametrize("atomic_number", range(1, 117))
|
|
307
|
+
def test_atom_properties(self, atomic_number):
|
|
308
|
+
"""Test that atom properties are correctly populated and gettable"""
|
|
309
|
+
formal_charge = 0 * unit.elementary_charge
|
|
310
|
+
is_aromatic = False
|
|
311
|
+
|
|
312
|
+
expected_mass = MASSES[atomic_number]
|
|
313
|
+
expected_symbol = SYMBOLS[atomic_number]
|
|
314
|
+
|
|
315
|
+
atom = Atom(
|
|
316
|
+
atomic_number,
|
|
317
|
+
formal_charge,
|
|
318
|
+
is_aromatic,
|
|
319
|
+
name="fOO",
|
|
320
|
+
)
|
|
321
|
+
assert atom.atomic_number == atomic_number
|
|
322
|
+
assert atom.formal_charge == formal_charge
|
|
323
|
+
assert atom.is_aromatic == is_aromatic
|
|
324
|
+
assert atom.symbol == expected_symbol
|
|
325
|
+
assert atom.mass == expected_mass
|
|
326
|
+
assert atom.mass.units == unit.dalton
|
|
327
|
+
assert atom.name == "fOO"
|
|
328
|
+
|
|
329
|
+
def test_atom_metadata(self):
|
|
330
|
+
"""Test that atom metadata behaves as expected"""
|
|
331
|
+
metadata = {"resname": "ALA", "resnum": 1, "chain": "3"}
|
|
332
|
+
# Create an atom with metadata
|
|
333
|
+
|
|
334
|
+
atom = Atom(6, 0, False, metadata=metadata)
|
|
335
|
+
|
|
336
|
+
assert atom.metadata == metadata
|
|
337
|
+
|
|
338
|
+
# Roundtrip that atom to/from dict
|
|
339
|
+
atom2 = Atom.from_dict(atom.to_dict())
|
|
340
|
+
assert atom.metadata == atom2.metadata
|
|
341
|
+
|
|
342
|
+
# Make an atom that initially has no metadata, then add the metadata and ensure that
|
|
343
|
+
# it's equivalent to the atom constructed with the same metadata initially
|
|
344
|
+
atom3 = Atom(6, 0, False)
|
|
345
|
+
assert atom3.metadata == {}
|
|
346
|
+
|
|
347
|
+
for key, val in metadata.items():
|
|
348
|
+
atom3.metadata[key] = val
|
|
349
|
+
|
|
350
|
+
assert atom3.metadata == metadata
|
|
351
|
+
assert atom3.to_dict() == atom.to_dict()
|
|
352
|
+
|
|
353
|
+
# Ensure that invalid types raise appropriate errors
|
|
354
|
+
with pytest.raises(InvalidAtomMetadataError, match="non-string key"):
|
|
355
|
+
atom3.metadata[1] = "one"
|
|
356
|
+
with pytest.raises(InvalidAtomMetadataError, match="non-string or integer value"):
|
|
357
|
+
atom3.metadata["length"] = 3.0 * unit.angstrom
|
|
358
|
+
|
|
359
|
+
def test_set_molecule(self):
|
|
360
|
+
"""Test appropriately setting a molecule with no errors"""
|
|
361
|
+
mol = Molecule.from_smiles("CCO")
|
|
362
|
+
atom = Atom(6, 0, False)
|
|
363
|
+
atom.molecule = mol
|
|
364
|
+
|
|
365
|
+
def test_set_molecule_error(self):
|
|
366
|
+
"""Test setting molecule for atom with molecule raises error"""
|
|
367
|
+
mol = Molecule.from_smiles("CCO")
|
|
368
|
+
atom = Atom(6, 0, False)
|
|
369
|
+
atom.molecule = mol
|
|
370
|
+
with pytest.raises(AssertionError, match="already has an associated molecule"):
|
|
371
|
+
atom.molecule = mol
|
|
372
|
+
|
|
373
|
+
@pytest.fixture()
|
|
374
|
+
def water_without_charges(self):
|
|
375
|
+
return Molecule.from_mapped_smiles("[H:2][O:1][H:3]")
|
|
376
|
+
|
|
377
|
+
@pytest.fixture()
|
|
378
|
+
def water(self, water_without_charges):
|
|
379
|
+
water_without_charges.assign_partial_charges("formal_charge")
|
|
380
|
+
water = water_without_charges
|
|
381
|
+
return water
|
|
382
|
+
|
|
383
|
+
def test_set_partial_charge(self, water):
|
|
384
|
+
water.atoms[0].partial_charge = 12.0 * unit.elementary_charge
|
|
385
|
+
water.atoms[1].partial_charge = -4.0
|
|
386
|
+
water.atoms[2].partial_charge = -8.0
|
|
387
|
+
|
|
388
|
+
assert np.allclose(
|
|
389
|
+
water.partial_charges,
|
|
390
|
+
unit.Quantity([12, -4, -8], unit.elementary_charge),
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
assert np.allclose(
|
|
394
|
+
[atom.partial_charge.m for atom in water.atoms],
|
|
395
|
+
[12, -4, -8],
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
def test_set_partial_charges_no_charges(self, water_without_charges):
|
|
399
|
+
with pytest.raises(MissingPartialChargesError, match="in a molecule with no partial charges"):
|
|
400
|
+
water_without_charges.atoms[2].partial_charge = 0.0 * unit.elementary_charge
|
|
401
|
+
|
|
402
|
+
def test_set_partial_charges_int(self, water):
|
|
403
|
+
with pytest.raises(ValueError, match=r"Cannot set.*'int'"):
|
|
404
|
+
water.atoms[2].partial_charge = 4
|
|
405
|
+
|
|
406
|
+
@requires_pkg("openmm")
|
|
407
|
+
def test_set_partial_charges_openmm_quantity(self, water):
|
|
408
|
+
import openmm.unit
|
|
409
|
+
|
|
410
|
+
with pytest.raises(ValueError, match=r"Cannot set.*openmm.unit"):
|
|
411
|
+
water.atoms[2].partial_charge = 0.0 * openmm.unit.elementary_charge
|
|
412
|
+
|
|
413
|
+
def test_set_partial_charges_array(self, water):
|
|
414
|
+
with pytest.raises(ValueError, match=r"unit-wrapped.*numpy.ndarray"):
|
|
415
|
+
water.atoms[2].partial_charge = unit.Quantity([0.0, 0.0], unit.elementary_charge)
|
|
416
|
+
|
|
417
|
+
def test_set_partial_charges_bogus(self, water):
|
|
418
|
+
with pytest.raises(ValueError, match=r"Cannot set.*class 'str'"):
|
|
419
|
+
water.atoms[2].partial_charge = "the right charge"
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
class TestBond:
|
|
423
|
+
@pytest.fixture()
|
|
424
|
+
def bond(self):
|
|
425
|
+
return create_ethanol().bond(0)
|
|
426
|
+
|
|
427
|
+
def test_cannot_change_molecule(self, bond):
|
|
428
|
+
with pytest.raises(
|
|
429
|
+
AssertionError,
|
|
430
|
+
match=r"Bond.molecule is already set and can only be set once",
|
|
431
|
+
):
|
|
432
|
+
bond.molecule = create_reversed_ethanol()
|
|
433
|
+
|
|
434
|
+
def test_initialize_from_dict(self):
|
|
435
|
+
molecule = create_ethanol()
|
|
436
|
+
|
|
437
|
+
bond = Bond.from_dict(molecule=molecule, d=molecule.bond(0).to_dict())
|
|
438
|
+
|
|
439
|
+
assert bond.atom1_index == 0
|
|
440
|
+
assert bond.atom2_index == 1
|
|
441
|
+
assert bond.atom1.atomic_number == 6
|
|
442
|
+
assert bond.atom2.atomic_number == 6
|
|
443
|
+
|
|
444
|
+
def test_set_bond_order(self, bond):
|
|
445
|
+
bond.bond_order = 2
|
|
446
|
+
|
|
447
|
+
def test_float_bond_order(self, bond):
|
|
448
|
+
with pytest.raises(InvalidBondOrderError):
|
|
449
|
+
bond.bond_order = 1.2
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
class TestMolecule:
|
|
453
|
+
"""Test Molecule class."""
|
|
454
|
+
|
|
455
|
+
# TODO: Test getstate/setstate
|
|
456
|
+
|
|
457
|
+
# Test serialization {to|from}_{dict|yaml|toml|json|bson|xml|messagepack|pickle}
|
|
458
|
+
|
|
459
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
460
|
+
def test_dict_serialization(self, molecule):
|
|
461
|
+
"""Test serialization of a molecule object to and from dict."""
|
|
462
|
+
serialized = molecule.to_dict()
|
|
463
|
+
molecule_copy = Molecule.from_dict(serialized)
|
|
464
|
+
assert molecule == molecule_copy
|
|
465
|
+
assert molecule_copy.n_conformers == molecule.n_conformers
|
|
466
|
+
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
|
|
467
|
+
|
|
468
|
+
@requires_pkg("yaml")
|
|
469
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
470
|
+
def test_yaml_serialization(self, molecule):
|
|
471
|
+
"""Test serialization of a molecule object to and from YAML."""
|
|
472
|
+
serialized = molecule.to_yaml()
|
|
473
|
+
molecule_copy = Molecule.from_yaml(serialized)
|
|
474
|
+
assert molecule == molecule_copy
|
|
475
|
+
assert molecule_copy.n_conformers == molecule.n_conformers
|
|
476
|
+
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
|
|
477
|
+
|
|
478
|
+
@requires_pkg("toml")
|
|
479
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
480
|
+
def test_toml_serialization(self, molecule):
|
|
481
|
+
"""Test serialization of a molecule object to and from TOML."""
|
|
482
|
+
# TODO: Test round-trip, on mini_drug_bank, when implemented
|
|
483
|
+
mol = Molecule.from_smiles("CCO")
|
|
484
|
+
with pytest.raises(NotImplementedError):
|
|
485
|
+
mol.to_toml()
|
|
486
|
+
|
|
487
|
+
@requires_pkg("bson")
|
|
488
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
489
|
+
def test_bson_serialization(self, molecule):
|
|
490
|
+
"""Test serialization of a molecule object to and from BSON."""
|
|
491
|
+
serialized = molecule.to_bson()
|
|
492
|
+
molecule_copy = Molecule.from_bson(serialized)
|
|
493
|
+
assert molecule == molecule_copy
|
|
494
|
+
assert molecule_copy.n_conformers == molecule.n_conformers
|
|
495
|
+
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
|
|
496
|
+
|
|
497
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
498
|
+
def test_json_serialization(self, molecule):
|
|
499
|
+
"""Test serialization of a molecule object to and from JSON."""
|
|
500
|
+
molecule_copy = Molecule.from_json(molecule.to_json())
|
|
501
|
+
assert molecule_copy == molecule
|
|
502
|
+
assert molecule_copy.n_conformers == molecule.n_conformers
|
|
503
|
+
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
|
|
504
|
+
|
|
505
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
506
|
+
def test_xml_serialization(self, molecule):
|
|
507
|
+
"""Test serialization of a molecule object to and from XML."""
|
|
508
|
+
# TODO: Test round-trip, on mini_drug_bank, when from_xml is implemented
|
|
509
|
+
mol = Molecule.from_smiles("CCO")
|
|
510
|
+
serialized = mol.to_xml()
|
|
511
|
+
with pytest.raises(NotImplementedError):
|
|
512
|
+
Molecule.from_xml(serialized)
|
|
513
|
+
|
|
514
|
+
@requires_pkg("msgpack")
|
|
515
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
516
|
+
def test_messagepack_serialization(self, molecule):
|
|
517
|
+
"""Test serialization of a molecule object to and from messagepack."""
|
|
518
|
+
serialized = molecule.to_messagepack()
|
|
519
|
+
molecule_copy = Molecule.from_messagepack(serialized)
|
|
520
|
+
assert molecule == molecule_copy
|
|
521
|
+
assert molecule_copy.n_conformers == molecule.n_conformers
|
|
522
|
+
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
|
|
523
|
+
|
|
524
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
525
|
+
def test_pickle_serialization(self, molecule):
|
|
526
|
+
"""Test round-trip pickling of a molecule object."""
|
|
527
|
+
serialized = pickle.dumps(molecule)
|
|
528
|
+
molecule_copy = pickle.loads(serialized)
|
|
529
|
+
assert molecule == molecule_copy
|
|
530
|
+
assert molecule_copy.n_conformers == molecule.n_conformers
|
|
531
|
+
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
|
|
532
|
+
|
|
533
|
+
@requires_pkg("yaml")
|
|
534
|
+
@requires_pkg("toml")
|
|
535
|
+
@requires_pkg("msgpack")
|
|
536
|
+
def test_serialization_no_conformers(self):
|
|
537
|
+
"""Test round-trip serialization when molecules have no conformers or partial charges."""
|
|
538
|
+
mol = Molecule.from_smiles("CCO")
|
|
539
|
+
|
|
540
|
+
dict_copy = Molecule.from_dict(mol.to_dict())
|
|
541
|
+
assert mol == dict_copy
|
|
542
|
+
|
|
543
|
+
# TODO: yaml_copy = Molecule.from_yaml(mol.to_yaml())
|
|
544
|
+
with pytest.raises(NotImplementedError):
|
|
545
|
+
mol.to_toml()
|
|
546
|
+
|
|
547
|
+
bson_copy = Molecule.from_bson(mol.to_bson())
|
|
548
|
+
assert mol == bson_copy
|
|
549
|
+
|
|
550
|
+
json_copy = Molecule.from_json(mol.to_json())
|
|
551
|
+
assert mol == json_copy
|
|
552
|
+
|
|
553
|
+
# TODO: round-trip when from_xml is implemented
|
|
554
|
+
mol_as_xml = mol.to_xml()
|
|
555
|
+
with pytest.raises(NotImplementedError):
|
|
556
|
+
Molecule.from_xml(mol_as_xml)
|
|
557
|
+
|
|
558
|
+
messagepack_copy = Molecule.from_messagepack(mol.to_messagepack())
|
|
559
|
+
assert mol == messagepack_copy
|
|
560
|
+
|
|
561
|
+
pickle_copy = pickle.loads(pickle.dumps(mol))
|
|
562
|
+
assert mol == pickle_copy
|
|
563
|
+
|
|
564
|
+
def test_json_numpy_roundtrips(self):
|
|
565
|
+
"""Ensure that array data survives several round-trips through JSON,
|
|
566
|
+
which depends on list serialization instead of bytes."""
|
|
567
|
+
mol = Molecule.from_smiles("CCO")
|
|
568
|
+
mol.generate_conformers(n_conformers=1)
|
|
569
|
+
initial_conformer = mol.conformers[0]
|
|
570
|
+
|
|
571
|
+
for _ in range(10):
|
|
572
|
+
mol = Molecule.from_json(mol.to_json())
|
|
573
|
+
|
|
574
|
+
assert np.allclose(initial_conformer, mol.conformers[0])
|
|
575
|
+
|
|
576
|
+
def test_create_empty(self):
|
|
577
|
+
"""Test empty constructor."""
|
|
578
|
+
molecule = Molecule()
|
|
579
|
+
assert len(molecule.atoms) == 0
|
|
580
|
+
assert len(molecule.bonds) == 0
|
|
581
|
+
|
|
582
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
583
|
+
def test_create_copy(self, molecule):
|
|
584
|
+
"""Test copy constructor."""
|
|
585
|
+
molecule_copy = Molecule(molecule)
|
|
586
|
+
assert molecule_copy == molecule
|
|
587
|
+
|
|
588
|
+
# Test that the "properties" dict of both molecules is unique
|
|
589
|
+
# (see https://github.com/openforcefield/openff-toolkit/pull/786)
|
|
590
|
+
molecule_copy.properties["aaa"] = "bbb"
|
|
591
|
+
assert "aaa" not in molecule.properties
|
|
592
|
+
|
|
593
|
+
@pytest.mark.skipif(
|
|
594
|
+
not (has_pkg("rdkit") and not (has_pkg("openeye"))),
|
|
595
|
+
reason="Test requires that RDKit is installed, but OpenEye is not installed",
|
|
596
|
+
)
|
|
597
|
+
def test_repr_bad_smiles(self):
|
|
598
|
+
"""Test that the repr falls back to Hill formula if to_smiles fails."""
|
|
599
|
+
|
|
600
|
+
assert "bad" not in Molecule.from_smiles("CC").__repr__()
|
|
601
|
+
|
|
602
|
+
# OpenEye will report a smiles of ClCl(Cl)C without error, so only test with RDKit unless we
|
|
603
|
+
# can come up with a molecule that OpenEyeToolkitWrapper.to_smiles() will reliably fail on
|
|
604
|
+
|
|
605
|
+
molecule = Molecule()
|
|
606
|
+
molecule.add_atom(17, 0, False)
|
|
607
|
+
molecule.add_atom(17, 0, False)
|
|
608
|
+
molecule.add_atom(17, 0, False)
|
|
609
|
+
|
|
610
|
+
molecule.add_bond(0, 1, 1, False)
|
|
611
|
+
molecule.add_bond(0, 2, 1, False)
|
|
612
|
+
|
|
613
|
+
expected_repr = "Molecule with name '' with bad SMILES and Hill formula 'Cl3'"
|
|
614
|
+
assert molecule.__repr__() == expected_repr
|
|
615
|
+
|
|
616
|
+
def test_repr_large_molecule(self):
|
|
617
|
+
large_molecule = Molecule.from_smiles("CNC" * 100)
|
|
618
|
+
|
|
619
|
+
this_repr = repr(large_molecule)
|
|
620
|
+
|
|
621
|
+
assert "Hill formula" in this_repr
|
|
622
|
+
assert "SMILES" not in this_repr
|
|
623
|
+
assert "C200H502N100" in this_repr
|
|
624
|
+
|
|
625
|
+
# can be displayed on one line
|
|
626
|
+
assert len(this_repr) < 100
|
|
627
|
+
|
|
628
|
+
@pytest.mark.parametrize("toolkit", [OpenEyeToolkitWrapper, RDKitToolkitWrapper])
|
|
629
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
630
|
+
def test_to_from_smiles(self, molecule, toolkit):
|
|
631
|
+
"""Test round-trip creation from SMILES"""
|
|
632
|
+
if not toolkit.is_available():
|
|
633
|
+
pytest.skip("Required toolkit is unavailable")
|
|
634
|
+
|
|
635
|
+
if toolkit == RDKitToolkitWrapper:
|
|
636
|
+
# Skip the test if OpenEye assigns stereochemistry but RDKit doesn't (since then, the
|
|
637
|
+
# OFF molecule will be loaded, but fail to convert in to_rdkit)
|
|
638
|
+
if molecule.name in drugbank_stereogenic_in_oe_but_not_rdkit:
|
|
639
|
+
pytest.skip(
|
|
640
|
+
"Molecule is stereogenic in OpenEye (which loaded this dataset), but not RDKit, so it "
|
|
641
|
+
"is impossible to make a valid RDMol in this test"
|
|
642
|
+
)
|
|
643
|
+
undefined_stereo_mols = rdkit_drugbank_undefined_stereo_mols
|
|
644
|
+
elif toolkit == OpenEyeToolkitWrapper:
|
|
645
|
+
undefined_stereo_mols = openeye_drugbank_undefined_stereo_mols
|
|
646
|
+
|
|
647
|
+
toolkit_wrapper = toolkit()
|
|
648
|
+
|
|
649
|
+
undefined_stereo = molecule.name in undefined_stereo_mols
|
|
650
|
+
# Since OpenEye did the original reading of MiniDrugBank, if OPENEYE doesn't
|
|
651
|
+
# think a feature is stereogenic, then "molecule" won't have stereochemistry defined
|
|
652
|
+
stereogenic_in_rdk_but_not_openeye = molecule.name in drugbank_stereogenic_in_rdkit_but_not_openeye
|
|
653
|
+
|
|
654
|
+
smiles1 = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
|
|
655
|
+
if undefined_stereo or ((toolkit is RDKitToolkitWrapper) and stereogenic_in_rdk_but_not_openeye):
|
|
656
|
+
molecule2 = Molecule.from_smiles(smiles1, allow_undefined_stereo=True, toolkit_registry=toolkit_wrapper)
|
|
657
|
+
else:
|
|
658
|
+
molecule2 = Molecule.from_smiles(smiles1, toolkit_registry=toolkit_wrapper)
|
|
659
|
+
|
|
660
|
+
smiles2 = molecule2.to_smiles(toolkit_registry=toolkit_wrapper)
|
|
661
|
+
assert smiles1 == smiles2
|
|
662
|
+
|
|
663
|
+
def test_from_smiles_name(self):
|
|
664
|
+
"""Test name kwarg to from_smiles"""
|
|
665
|
+
mol = Molecule.from_smiles("C")
|
|
666
|
+
assert mol.name == ""
|
|
667
|
+
|
|
668
|
+
mol = Molecule.from_smiles("C", name="bob")
|
|
669
|
+
assert mol.name == "bob"
|
|
670
|
+
|
|
671
|
+
@pytest.mark.parametrize("smiles, expected", [("[Cl:1]Cl", {0: 1}), ("[Cl:1][Cl:2]", {0: 1, 1: 2})])
|
|
672
|
+
@pytest.mark.parametrize("toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper])
|
|
673
|
+
def test_from_smiles_with_map(self, smiles, expected, toolkit_class):
|
|
674
|
+
if not (toolkit_class.is_available()):
|
|
675
|
+
pytest.skip(f"Required toolkit {toolkit_class} is unavailable")
|
|
676
|
+
molecule = Molecule.from_smiles(smiles, toolkit_registry=toolkit_class())
|
|
677
|
+
assert molecule.properties["atom_map"] == expected
|
|
678
|
+
|
|
679
|
+
smiles_types = [
|
|
680
|
+
{"isomeric": True, "explicit_hydrogens": True, "mapped": True, "error": None},
|
|
681
|
+
{"isomeric": False, "explicit_hydrogens": True, "mapped": True, "error": None},
|
|
682
|
+
{
|
|
683
|
+
"isomeric": True,
|
|
684
|
+
"explicit_hydrogens": False,
|
|
685
|
+
"mapped": True,
|
|
686
|
+
"error": AssertionError,
|
|
687
|
+
},
|
|
688
|
+
{"isomeric": True, "explicit_hydrogens": True, "mapped": False, "error": None},
|
|
689
|
+
{"isomeric": True, "explicit_hydrogens": False, "mapped": False, "error": None},
|
|
690
|
+
{"isomeric": False, "explicit_hydrogens": True, "mapped": False, "error": None},
|
|
691
|
+
{
|
|
692
|
+
"isomeric": False,
|
|
693
|
+
"explicit_hydrogens": False,
|
|
694
|
+
"mapped": True,
|
|
695
|
+
"error": AssertionError,
|
|
696
|
+
},
|
|
697
|
+
{
|
|
698
|
+
"isomeric": False,
|
|
699
|
+
"explicit_hydrogens": False,
|
|
700
|
+
"mapped": False,
|
|
701
|
+
"error": None,
|
|
702
|
+
},
|
|
703
|
+
]
|
|
704
|
+
|
|
705
|
+
@pytest.mark.parametrize("toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper])
|
|
706
|
+
@pytest.mark.parametrize("data", smiles_types)
|
|
707
|
+
def test_smiles_types(self, data, toolkit_class):
|
|
708
|
+
"""Test that the toolkit is passing the correct args to the toolkit backends across different combinations."""
|
|
709
|
+
|
|
710
|
+
if toolkit_class.is_available():
|
|
711
|
+
toolkit = toolkit_class()
|
|
712
|
+
mol = create_cis_1_2_dichloroethene()
|
|
713
|
+
isomeric, explicit_hs, mapped = (
|
|
714
|
+
data["isomeric"],
|
|
715
|
+
data["explicit_hydrogens"],
|
|
716
|
+
data["mapped"],
|
|
717
|
+
)
|
|
718
|
+
if data["error"] is not None:
|
|
719
|
+
with pytest.raises(data["error"]):
|
|
720
|
+
mol.to_smiles(
|
|
721
|
+
isomeric=isomeric,
|
|
722
|
+
explicit_hydrogens=explicit_hs,
|
|
723
|
+
mapped=mapped,
|
|
724
|
+
toolkit_registry=toolkit,
|
|
725
|
+
)
|
|
726
|
+
|
|
727
|
+
else:
|
|
728
|
+
# make the smiles then do some checks on it
|
|
729
|
+
output_smiles = mol.to_smiles(
|
|
730
|
+
isomeric=isomeric,
|
|
731
|
+
explicit_hydrogens=explicit_hs,
|
|
732
|
+
mapped=mapped,
|
|
733
|
+
toolkit_registry=toolkit,
|
|
734
|
+
)
|
|
735
|
+
if isomeric:
|
|
736
|
+
assert "\\" in output_smiles
|
|
737
|
+
if explicit_hs:
|
|
738
|
+
assert "H" in output_smiles
|
|
739
|
+
if mapped:
|
|
740
|
+
for i in range(1, 7):
|
|
741
|
+
assert f":{i}" in output_smiles
|
|
742
|
+
# if the molecule is mapped make it using the mapping
|
|
743
|
+
mol2 = Molecule.from_mapped_smiles(
|
|
744
|
+
mapped_smiles=output_smiles,
|
|
745
|
+
toolkit_registry=toolkit,
|
|
746
|
+
allow_undefined_stereo=not isomeric,
|
|
747
|
+
)
|
|
748
|
+
else:
|
|
749
|
+
# make a molecule from a standard smiles
|
|
750
|
+
mol2 = Molecule.from_smiles(
|
|
751
|
+
smiles=output_smiles,
|
|
752
|
+
allow_undefined_stereo=not isomeric,
|
|
753
|
+
toolkit_registry=toolkit,
|
|
754
|
+
)
|
|
755
|
+
|
|
756
|
+
isomorphic, atom_map = Molecule.are_isomorphic(
|
|
757
|
+
mol,
|
|
758
|
+
mol2,
|
|
759
|
+
return_atom_map=True,
|
|
760
|
+
aromatic_matching=True,
|
|
761
|
+
formal_charge_matching=True,
|
|
762
|
+
bond_order_matching=True,
|
|
763
|
+
atom_stereochemistry_matching=isomeric,
|
|
764
|
+
bond_stereochemistry_matching=isomeric,
|
|
765
|
+
)
|
|
766
|
+
|
|
767
|
+
assert isomorphic is True
|
|
768
|
+
if mapped:
|
|
769
|
+
assert {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5} == atom_map
|
|
770
|
+
|
|
771
|
+
else:
|
|
772
|
+
pytest.skip(f"The required toolkit ({toolkit_class.toolkit_name}) is not available.")
|
|
773
|
+
|
|
774
|
+
@pytest.mark.parametrize("toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper])
|
|
775
|
+
def test_smiles_cache(self, toolkit_class):
|
|
776
|
+
"""Make sure that the smiles cache is being used correctly."""
|
|
777
|
+
|
|
778
|
+
if toolkit_class.is_available():
|
|
779
|
+
toolkit = toolkit_class()
|
|
780
|
+
# this uses no toolkit back end so no smiles should be saved
|
|
781
|
+
mol = create_ethanol()
|
|
782
|
+
|
|
783
|
+
# now lets populate the cache with a test result
|
|
784
|
+
# first we need to make the cache key for the default input
|
|
785
|
+
isomeric, explicit_hydrogens, mapped = True, True, False
|
|
786
|
+
cache_key = toolkit.to_smiles.__qualname__ + str(isomeric) + str(explicit_hydrogens) + str(mapped)
|
|
787
|
+
cache_key += str(mol._properties.get("atom_map", None))
|
|
788
|
+
mol._cached_smiles = {cache_key: None}
|
|
789
|
+
assert (
|
|
790
|
+
mol.to_smiles(
|
|
791
|
+
isomeric=isomeric,
|
|
792
|
+
toolkit_registry=toolkit,
|
|
793
|
+
explicit_hydrogens=explicit_hydrogens,
|
|
794
|
+
mapped=mapped,
|
|
795
|
+
)
|
|
796
|
+
is None
|
|
797
|
+
)
|
|
798
|
+
|
|
799
|
+
# now make sure the cache is not used if we change an input arg
|
|
800
|
+
assert (
|
|
801
|
+
mol.to_smiles(
|
|
802
|
+
isomeric=True,
|
|
803
|
+
explicit_hydrogens=True,
|
|
804
|
+
mapped=True,
|
|
805
|
+
toolkit_registry=toolkit,
|
|
806
|
+
)
|
|
807
|
+
is not None
|
|
808
|
+
)
|
|
809
|
+
|
|
810
|
+
# now make sure the cache was updated
|
|
811
|
+
assert mol._cached_smiles != {cache_key: None}
|
|
812
|
+
assert len(mol._cached_smiles) == 2
|
|
813
|
+
|
|
814
|
+
else:
|
|
815
|
+
pytest.skip(f"The required toolkit ({toolkit_class.toolkit_name}) is not available.")
|
|
816
|
+
|
|
817
|
+
def test_atom_index_cache(self):
|
|
818
|
+
"""Test that the atom index cache is invalidated when a molecule is modified"""
|
|
819
|
+
# First make OH-
|
|
820
|
+
mol = Molecule()
|
|
821
|
+
mol.add_atom(8, -1, False, None)
|
|
822
|
+
mol.add_atom(1, 0, False, None)
|
|
823
|
+
mol.add_bond(0, 1, 1, False)
|
|
824
|
+
assert mol.atom(0).molecule_atom_index == 0
|
|
825
|
+
assert mol.atom(1).molecule_atom_index == 1
|
|
826
|
+
|
|
827
|
+
# Now convert it to H2O and ask for atom indices again
|
|
828
|
+
mol.add_atom(1, 0, False, None)
|
|
829
|
+
mol.add_bond(1, 2, 1, False)
|
|
830
|
+
mol.atom(0).formal_charge = 0
|
|
831
|
+
assert mol.atom(0).molecule_atom_index == 0
|
|
832
|
+
assert mol.atom(1).molecule_atom_index == 1
|
|
833
|
+
assert mol.atom(2).molecule_atom_index == 2
|
|
834
|
+
|
|
835
|
+
mapped_types = [
|
|
836
|
+
{"atom_map": None},
|
|
837
|
+
{"atom_map": {0: 0}},
|
|
838
|
+
{"atom_map": {0: 0, 1: 0, 2: 0, 3: 0}},
|
|
839
|
+
{"atom_map": {0: 0, 1: 1, 2: 2, 3: 3}},
|
|
840
|
+
{"atom_map": {0: 1, 1: 2, 2: 3, 3: 4}},
|
|
841
|
+
]
|
|
842
|
+
|
|
843
|
+
@pytest.mark.parametrize("toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper])
|
|
844
|
+
@pytest.mark.parametrize("data", mapped_types)
|
|
845
|
+
def test_partial_mapped_smiles(self, toolkit_class, data):
|
|
846
|
+
if toolkit_class.is_available():
|
|
847
|
+
toolkit = toolkit_class()
|
|
848
|
+
mol = create_cis_1_2_dichloroethene()
|
|
849
|
+
mol._properties["atom_map"] = data["atom_map"]
|
|
850
|
+
|
|
851
|
+
smiles = mol.to_smiles(
|
|
852
|
+
isomeric=True,
|
|
853
|
+
explicit_hydrogens=True,
|
|
854
|
+
mapped=True,
|
|
855
|
+
toolkit_registry=toolkit,
|
|
856
|
+
)
|
|
857
|
+
|
|
858
|
+
# now we just need to check the smiles generated
|
|
859
|
+
if data["atom_map"] is None:
|
|
860
|
+
for i, atom in enumerate(mol.atoms, 1):
|
|
861
|
+
assert f"[{atom.symbol}:{i}]" in smiles
|
|
862
|
+
else:
|
|
863
|
+
if 0 in data["atom_map"].values():
|
|
864
|
+
increment = True
|
|
865
|
+
else:
|
|
866
|
+
increment = False
|
|
867
|
+
|
|
868
|
+
for atom, index in data["atom_map"].items():
|
|
869
|
+
assert f"[{mol.atoms[atom].symbol}:{index + 1 if increment else index}]"
|
|
870
|
+
|
|
871
|
+
else:
|
|
872
|
+
pytest.skip(f"The required toolkit ({toolkit_class.toolkit_name}) is not available.")
|
|
873
|
+
|
|
874
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
875
|
+
def test_unique_atom_names(self, molecule):
|
|
876
|
+
"""Test molecules have unique atom names"""
|
|
877
|
+
# The dataset we load in has atom names, so let's strip them first
|
|
878
|
+
# to ensure that we can fail the uniqueness check
|
|
879
|
+
for atom in molecule.atoms:
|
|
880
|
+
atom.name = ""
|
|
881
|
+
assert not (molecule.has_unique_atom_names)
|
|
882
|
+
# Then genreate unique atom names using the built in algorithm
|
|
883
|
+
molecule.generate_unique_atom_names()
|
|
884
|
+
# Check that the molecule has unique atom names
|
|
885
|
+
assert molecule.has_unique_atom_names
|
|
886
|
+
# Check molecule.has_unique_atom_names is working correctly
|
|
887
|
+
assert (len(set([atom.name for atom in molecule.atoms])) == molecule.n_atoms) == molecule.has_unique_atom_names
|
|
888
|
+
molecule.atoms[1].name = molecule.atoms[0].name # no longer unique
|
|
889
|
+
assert (len(set([atom.name for atom in molecule.atoms])) == molecule.n_atoms) == molecule.has_unique_atom_names
|
|
890
|
+
assert all(a.name.endswith("x") for a in molecule.atoms)
|
|
891
|
+
|
|
892
|
+
def test_generate_unique_atom_names(self):
|
|
893
|
+
# Create test atoms as opposed to testing with the 'drug_bank'
|
|
894
|
+
# Check that the default works correctly
|
|
895
|
+
molecule = create_ethanol()
|
|
896
|
+
molecule.generate_unique_atom_names()
|
|
897
|
+
assert molecule.atoms[0].name == "C1x"
|
|
898
|
+
assert molecule.atoms[1].name == "C2x"
|
|
899
|
+
assert molecule.atoms[2].name == "O1x"
|
|
900
|
+
assert molecule.atoms[3].name == "H1x"
|
|
901
|
+
assert molecule.atoms[4].name == "H2x"
|
|
902
|
+
|
|
903
|
+
# Check that a non-default string works correctly
|
|
904
|
+
molecule = create_ethanol()
|
|
905
|
+
molecule.generate_unique_atom_names(suffix="y")
|
|
906
|
+
assert molecule.atoms[0].name == "C1y"
|
|
907
|
+
assert molecule.atoms[1].name == "C2y"
|
|
908
|
+
assert molecule.atoms[2].name == "O1y"
|
|
909
|
+
assert molecule.atoms[3].name == "H1y"
|
|
910
|
+
assert molecule.atoms[4].name == "H2y"
|
|
911
|
+
|
|
912
|
+
# Check that an empty string works correctly
|
|
913
|
+
molecule = create_ethanol()
|
|
914
|
+
molecule.generate_unique_atom_names(suffix="")
|
|
915
|
+
assert molecule.atoms[0].name == "C1"
|
|
916
|
+
assert molecule.atoms[1].name == "C2"
|
|
917
|
+
assert molecule.atoms[2].name == "O1"
|
|
918
|
+
assert molecule.atoms[3].name == "H1"
|
|
919
|
+
assert molecule.atoms[4].name == "H2"
|
|
920
|
+
|
|
921
|
+
inchi_data = [
|
|
922
|
+
{
|
|
923
|
+
"molecule": create_ethanol(),
|
|
924
|
+
"standard_inchi": "InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3",
|
|
925
|
+
"fixed_hydrogen_inchi": "InChI=1/C2H6O/c1-2-3/h3H,2H2,1H3",
|
|
926
|
+
},
|
|
927
|
+
{
|
|
928
|
+
"molecule": create_reversed_ethanol(),
|
|
929
|
+
"standard_inchi": "InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3",
|
|
930
|
+
"fixed_hydrogen_inchi": "InChI=1/C2H6O/c1-2-3/h3H,2H2,1H3",
|
|
931
|
+
},
|
|
932
|
+
{
|
|
933
|
+
"molecule": create_acetaldehyde(),
|
|
934
|
+
"standard_inchi": "InChI=1S/C2H4O/c1-2-3/h2H,1H3",
|
|
935
|
+
"fixed_hydrogen_inchi": "InChI=1/C2H4O/c1-2-3/h2H,1H3",
|
|
936
|
+
},
|
|
937
|
+
{
|
|
938
|
+
"molecule": create_cyclohexane(),
|
|
939
|
+
"standard_inchi": "InChI=1S/C6H12/c1-2-4-6-5-3-1/h1-6H2",
|
|
940
|
+
"fixed_hydrogen_inchi": "InChI=1/C6H12/c1-2-4-6-5-3-1/h1-6H2",
|
|
941
|
+
},
|
|
942
|
+
]
|
|
943
|
+
|
|
944
|
+
@requires_openeye
|
|
945
|
+
@pytest.mark.parametrize("data", inchi_data)
|
|
946
|
+
def test_from_inchi(self, data):
|
|
947
|
+
"""Test building a molecule from standard and non-standard InChI strings."""
|
|
948
|
+
|
|
949
|
+
toolkit = OpenEyeToolkitWrapper()
|
|
950
|
+
ref_mol = data["molecule"]
|
|
951
|
+
# make a molecule from inchi
|
|
952
|
+
inchi_mol = Molecule.from_inchi(data["standard_inchi"], toolkit_registry=toolkit)
|
|
953
|
+
assert inchi_mol.to_inchi(toolkit_registry=toolkit) == data["standard_inchi"]
|
|
954
|
+
|
|
955
|
+
def compare_mols(ref_mol, inchi_mol):
|
|
956
|
+
assert ref_mol.n_atoms == inchi_mol.n_atoms
|
|
957
|
+
assert ref_mol.n_bonds == inchi_mol.n_bonds
|
|
958
|
+
assert ref_mol.n_angles == inchi_mol.n_angles
|
|
959
|
+
assert ref_mol.n_propers == inchi_mol.n_propers
|
|
960
|
+
assert ref_mol.is_isomorphic_with(inchi_mol) is True
|
|
961
|
+
|
|
962
|
+
compare_mols(ref_mol, inchi_mol)
|
|
963
|
+
|
|
964
|
+
# now make the molecule from the non-standard inchi and compare
|
|
965
|
+
nonstandard_inchi_mol = Molecule.from_inchi(data["fixed_hydrogen_inchi"], toolkit_registry=toolkit)
|
|
966
|
+
assert (
|
|
967
|
+
nonstandard_inchi_mol.to_inchi(fixed_hydrogens=True, toolkit_registry=toolkit)
|
|
968
|
+
== data["fixed_hydrogen_inchi"]
|
|
969
|
+
)
|
|
970
|
+
|
|
971
|
+
compare_mols(ref_mol, nonstandard_inchi_mol)
|
|
972
|
+
|
|
973
|
+
def test_from_inchi_name(self):
|
|
974
|
+
"""Test name kwarg to from_inchi"""
|
|
975
|
+
mol = Molecule.from_inchi("InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3")
|
|
976
|
+
assert mol.name == ""
|
|
977
|
+
mol = Molecule.from_inchi("InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3", name="bob")
|
|
978
|
+
assert mol.name == "bob"
|
|
979
|
+
|
|
980
|
+
# TODO: Should there be an equivalent toolkit test and leave this as an integration test?
|
|
981
|
+
@requires_openeye
|
|
982
|
+
def test_create_from_file(self):
|
|
983
|
+
"""Test standard constructor taking a filename or file-like object."""
|
|
984
|
+
# TODO: Expand test to both openeye and rdkit toolkits
|
|
985
|
+
filename = get_data_file_path("molecules/toluene.mol2")
|
|
986
|
+
|
|
987
|
+
molecule1 = Molecule(filename, allow_undefined_stereo=True)
|
|
988
|
+
with open(filename) as infile:
|
|
989
|
+
molecule2 = Molecule(infile, file_format="MOL2", allow_undefined_stereo=True)
|
|
990
|
+
assert molecule1 == molecule2
|
|
991
|
+
|
|
992
|
+
import gzip
|
|
993
|
+
|
|
994
|
+
with gzip.GzipFile(filename + ".gz", "r") as infile:
|
|
995
|
+
molecule3 = Molecule(infile, file_format="MOL2", allow_undefined_stereo=True)
|
|
996
|
+
assert molecule3 == molecule1
|
|
997
|
+
|
|
998
|
+
# Ensure that attempting to initialize a single Molecule from a file
|
|
999
|
+
# containing multiple molecules raises a ValueError
|
|
1000
|
+
filename = get_data_file_path("molecules/butane_multi.sdf")
|
|
1001
|
+
|
|
1002
|
+
with pytest.raises(
|
|
1003
|
+
ValueError,
|
|
1004
|
+
match=r"Specified file or file-like.*exactly one molecule",
|
|
1005
|
+
):
|
|
1006
|
+
Molecule(filename, allow_undefined_stereo=True)
|
|
1007
|
+
|
|
1008
|
+
def test_from_pathlib_path(self):
|
|
1009
|
+
ethanol = create_ethanol()
|
|
1010
|
+
with NamedTemporaryFile(suffix=".sdf") as outfile:
|
|
1011
|
+
filename = str(outfile.name)
|
|
1012
|
+
ethanol.to_file(filename, file_format="sdf")
|
|
1013
|
+
|
|
1014
|
+
# there is different logic when file_format is None, so test both cases
|
|
1015
|
+
Molecule.from_file(pathlib.Path(filename))
|
|
1016
|
+
|
|
1017
|
+
Molecule.from_file(pathlib.Path(filename), file_format="sdf")
|
|
1018
|
+
|
|
1019
|
+
@pytest.mark.parametrize("toolkit", [OpenEyeToolkitWrapper, RDKitToolkitWrapper])
|
|
1020
|
+
def test_to_pathlib_path(self, tmp_path, toolkit):
|
|
1021
|
+
if toolkit == OpenEyeToolkitWrapper:
|
|
1022
|
+
pytest.importorskip("openeye")
|
|
1023
|
+
elif toolkit == RDKitToolkitWrapper:
|
|
1024
|
+
pytest.importorskip("rdkit")
|
|
1025
|
+
|
|
1026
|
+
ethanol = create_ethanol()
|
|
1027
|
+
|
|
1028
|
+
filename = tmp_path / "tmp.sdf"
|
|
1029
|
+
ethanol.to_file(filename, file_format="sdf", toolkit_registry=toolkit())
|
|
1030
|
+
|
|
1031
|
+
Molecule.from_file(filename.as_posix())
|
|
1032
|
+
|
|
1033
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
1034
|
+
def test_create_from_serialized(self, molecule):
|
|
1035
|
+
"""Test standard constructor taking the output of Molecule.to_dict()."""
|
|
1036
|
+
serialized_molecule = molecule.to_dict()
|
|
1037
|
+
molecule_copy = Molecule(serialized_molecule)
|
|
1038
|
+
assert molecule == molecule_copy
|
|
1039
|
+
|
|
1040
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
1041
|
+
def test_to_from_dict(self, molecule):
|
|
1042
|
+
"""Test that conversion/creation of a molecule to and from a dict is consistent."""
|
|
1043
|
+
serialized = molecule.to_dict()
|
|
1044
|
+
molecule_copy = Molecule.from_dict(serialized)
|
|
1045
|
+
assert molecule == molecule_copy
|
|
1046
|
+
|
|
1047
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
1048
|
+
def test_to_networkx(self, molecule):
|
|
1049
|
+
"""Test conversion to NetworkX graph."""
|
|
1050
|
+
graph = molecule.to_networkx()
|
|
1051
|
+
|
|
1052
|
+
assert graph.number_of_nodes() == molecule.n_atoms
|
|
1053
|
+
assert graph.number_of_edges() == molecule.n_bonds
|
|
1054
|
+
|
|
1055
|
+
for bond in molecule.bonds:
|
|
1056
|
+
edge = graph.get_edge_data(bond.atom1_index, bond.atom2_index)
|
|
1057
|
+
|
|
1058
|
+
for attr in ["stereochemistry", "bond_order", "is_aromatic"]:
|
|
1059
|
+
assert edge[attr] == getattr(bond, attr)
|
|
1060
|
+
|
|
1061
|
+
for node_index, node in graph.nodes(data=True):
|
|
1062
|
+
atom = molecule.atom(node_index)
|
|
1063
|
+
|
|
1064
|
+
for attr in [
|
|
1065
|
+
"atomic_number",
|
|
1066
|
+
"is_aromatic",
|
|
1067
|
+
"stereochemistry",
|
|
1068
|
+
"formal_charge",
|
|
1069
|
+
]:
|
|
1070
|
+
assert node[attr] == getattr(atom, attr)
|
|
1071
|
+
|
|
1072
|
+
@requires_rdkit
|
|
1073
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
1074
|
+
def test_to_from_rdkit(self, molecule):
|
|
1075
|
+
"""Test that conversion/creation of a molecule to and from an RDKit rdmol is consistent."""
|
|
1076
|
+
# import pickle
|
|
1077
|
+
from openff.toolkit.utils.toolkits import UndefinedStereochemistryError
|
|
1078
|
+
|
|
1079
|
+
undefined_stereo = molecule.name in rdkit_drugbank_undefined_stereo_mols
|
|
1080
|
+
|
|
1081
|
+
toolkit_wrapper = RDKitToolkitWrapper()
|
|
1082
|
+
|
|
1083
|
+
rdmol = molecule.to_rdkit()
|
|
1084
|
+
molecule_smiles = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
|
|
1085
|
+
|
|
1086
|
+
# First test making a molecule using the Molecule(oemol) method
|
|
1087
|
+
|
|
1088
|
+
# If this is a known failure, check that it raises UndefinedStereochemistryError
|
|
1089
|
+
# and proceed with the test ignoring it.
|
|
1090
|
+
test_mol = None
|
|
1091
|
+
if undefined_stereo:
|
|
1092
|
+
with pytest.raises(UndefinedStereochemistryError):
|
|
1093
|
+
Molecule(rdmol)
|
|
1094
|
+
test_mol = Molecule(rdmol, allow_undefined_stereo=True)
|
|
1095
|
+
else:
|
|
1096
|
+
test_mol = Molecule(rdmol)
|
|
1097
|
+
|
|
1098
|
+
test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)
|
|
1099
|
+
assert molecule_smiles == test_mol_smiles
|
|
1100
|
+
|
|
1101
|
+
# Check that the two topologies are isomorphic.
|
|
1102
|
+
assert_molecule_is_equal(molecule, test_mol, "Molecule.to_rdkit()/Molecule(rdmol) round trip failed")
|
|
1103
|
+
|
|
1104
|
+
# Second, test making a molecule using the Molecule.from_openeye(oemol) method
|
|
1105
|
+
|
|
1106
|
+
# If this is a known failure, check that it raises UndefinedStereochemistryError
|
|
1107
|
+
# and proceed with the test.
|
|
1108
|
+
if undefined_stereo:
|
|
1109
|
+
with pytest.raises(UndefinedStereochemistryError):
|
|
1110
|
+
Molecule.from_rdkit(rdmol)
|
|
1111
|
+
test_mol = Molecule.from_rdkit(rdmol, allow_undefined_stereo=True)
|
|
1112
|
+
else:
|
|
1113
|
+
test_mol = Molecule.from_rdkit(rdmol)
|
|
1114
|
+
|
|
1115
|
+
test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)
|
|
1116
|
+
assert molecule_smiles == test_mol_smiles
|
|
1117
|
+
|
|
1118
|
+
# Check that the two topologies are isomorphic.
|
|
1119
|
+
assert_molecule_is_equal(molecule, test_mol, "Molecule.to_rdkit()/from_rdkit() round trip failed")
|
|
1120
|
+
|
|
1121
|
+
@requires_openeye
|
|
1122
|
+
def test_to_from_iupac(self):
|
|
1123
|
+
"""
|
|
1124
|
+
Test basic behavior of the IUPAC conversion functions. More rigorous
|
|
1125
|
+
testing of the toolkity wrapper behavior is in test_toolkits.py
|
|
1126
|
+
"""
|
|
1127
|
+
from openff.toolkit.utils.toolkits import (
|
|
1128
|
+
InvalidIUPACNameError,
|
|
1129
|
+
UndefinedStereochemistryError,
|
|
1130
|
+
)
|
|
1131
|
+
|
|
1132
|
+
with pytest.raises(InvalidIUPACNameError):
|
|
1133
|
+
Molecule.from_iupac(".BETA.-PINENE")
|
|
1134
|
+
|
|
1135
|
+
# DrugBank_977, tagged as a problem molecule in earlier tests
|
|
1136
|
+
bad_stereo_iupac = (
|
|
1137
|
+
"(~{E},3~{R},5~{S})-7-[4-(4-fluorophenyl)-6-isopropyl-2-"
|
|
1138
|
+
"[methyl(methylsulfonyl)amino]pyrimidin-5-yl]-3,5-"
|
|
1139
|
+
"dihydroxy-hept-6-enoic acid"
|
|
1140
|
+
)
|
|
1141
|
+
with pytest.raises(UndefinedStereochemistryError):
|
|
1142
|
+
Molecule.from_iupac(bad_stereo_iupac)
|
|
1143
|
+
|
|
1144
|
+
cholesterol = Molecule.from_smiles(
|
|
1145
|
+
"C[C@H](CCCC(C)C)[C@H]1CC[C@@H]2[C@@]1(CC[C@H]3[C@H]2CC=C4[C@@]3(CC[C@@H](C4)O)C)C"
|
|
1146
|
+
)
|
|
1147
|
+
|
|
1148
|
+
cholesterol_iupac = cholesterol.to_iupac()
|
|
1149
|
+
|
|
1150
|
+
assert Molecule.are_isomorphic(cholesterol, Molecule.from_iupac(cholesterol_iupac))
|
|
1151
|
+
|
|
1152
|
+
@requires_openeye
|
|
1153
|
+
def test_to_from_iupac_wrapper(self):
|
|
1154
|
+
"""Test that IUPAC methods work if passed just `OpenEyeToolkitWrapper`."""
|
|
1155
|
+
from openff.toolkit.utils import OpenEyeToolkitWrapper
|
|
1156
|
+
|
|
1157
|
+
assert (
|
|
1158
|
+
Molecule.from_iupac("benzene", toolkit_registry=OpenEyeToolkitWrapper()).to_iupac(
|
|
1159
|
+
toolkit_registry=OpenEyeToolkitWrapper()
|
|
1160
|
+
)
|
|
1161
|
+
== "benzene"
|
|
1162
|
+
)
|
|
1163
|
+
|
|
1164
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
1165
|
+
def test_to_from_topology(self, molecule):
|
|
1166
|
+
"""Test that conversion/creation of a molecule to and from a Topology is consistent."""
|
|
1167
|
+
topology = molecule.to_topology()
|
|
1168
|
+
molecule_copy = Molecule.from_topology(topology)
|
|
1169
|
+
assert molecule == molecule_copy
|
|
1170
|
+
|
|
1171
|
+
@requires_openeye
|
|
1172
|
+
def test_to_multiframe_xyz_openeye(self):
|
|
1173
|
+
"""
|
|
1174
|
+
Test writing out a molecule with multiple conformations to an xyz file
|
|
1175
|
+
|
|
1176
|
+
This test is backend-specific because of precision/rounding differences between RDKit and OpenEye
|
|
1177
|
+
"""
|
|
1178
|
+
from openff.toolkit.utils import OpenEyeToolkitWrapper
|
|
1179
|
+
|
|
1180
|
+
tkw = OpenEyeToolkitWrapper()
|
|
1181
|
+
# load in an SDF of butane with multiple conformers in it
|
|
1182
|
+
molecules = Molecule.from_file(
|
|
1183
|
+
get_data_file_path("molecules/butane_multi.sdf"),
|
|
1184
|
+
"sdf",
|
|
1185
|
+
toolkit_registry=tkw,
|
|
1186
|
+
)
|
|
1187
|
+
# now we want to combine the conformers to one molecule
|
|
1188
|
+
butane = molecules[0]
|
|
1189
|
+
for mol in molecules[1:]:
|
|
1190
|
+
butane.add_conformer(mol._conformers[0])
|
|
1191
|
+
|
|
1192
|
+
# make sure we have the 7 conformers
|
|
1193
|
+
assert butane.n_conformers == 7
|
|
1194
|
+
with NamedTemporaryFile(suffix=".xyz") as iofile:
|
|
1195
|
+
# try and write out the xyz file
|
|
1196
|
+
butane.to_file(iofile.name, "xyz", toolkit_registry=tkw)
|
|
1197
|
+
|
|
1198
|
+
# now lets check whats in the file
|
|
1199
|
+
with open(iofile.name) as xyz_data:
|
|
1200
|
+
data = xyz_data.readlines()
|
|
1201
|
+
# make sure we have the correct amount of lines writen
|
|
1202
|
+
assert len(data) == 112
|
|
1203
|
+
# make sure all headers and frame data was writen
|
|
1204
|
+
assert data.count("14\n") == 7
|
|
1205
|
+
for i in range(1, 8):
|
|
1206
|
+
assert f"C4H10 Frame {i}\n" in data
|
|
1207
|
+
|
|
1208
|
+
# now make sure the first line of the coordinates are correct in every frame
|
|
1209
|
+
coords = [
|
|
1210
|
+
"C 1.8902000189 0.0425999984 0.2431000024\n",
|
|
1211
|
+
"C 1.8976000547 -0.0232999995 0.2845999897\n",
|
|
1212
|
+
"C -1.8794000149 -0.1792999953 -0.2565000057\n",
|
|
1213
|
+
"C -1.5205999613 -0.0164999999 0.2786999941\n",
|
|
1214
|
+
"C -1.4889999628 -0.2619000077 0.4871000051\n",
|
|
1215
|
+
"C -1.4940999746 -0.2249000072 -0.0957999974\n",
|
|
1216
|
+
"C -1.8826999664 -0.0372000001 0.1937000006\n",
|
|
1217
|
+
]
|
|
1218
|
+
for coord in coords:
|
|
1219
|
+
assert coord in data
|
|
1220
|
+
|
|
1221
|
+
@requires_openeye
|
|
1222
|
+
def test_to_single_xyz_openeye(self):
|
|
1223
|
+
"""
|
|
1224
|
+
Test writing to a single frame xyz file
|
|
1225
|
+
|
|
1226
|
+
This test is backend-specific because of precision/rounding differences between RDKit and OpenEye
|
|
1227
|
+
"""
|
|
1228
|
+
from openff.toolkit.utils import OpenEyeToolkitWrapper
|
|
1229
|
+
|
|
1230
|
+
tkw = OpenEyeToolkitWrapper()
|
|
1231
|
+
|
|
1232
|
+
# load a molecule with a single conformation
|
|
1233
|
+
toluene = Molecule.from_file(get_data_file_path("molecules/toluene.sdf"), "sdf", toolkit_registry=tkw)
|
|
1234
|
+
# make sure it has one conformer
|
|
1235
|
+
assert toluene.n_conformers == 1
|
|
1236
|
+
|
|
1237
|
+
with NamedTemporaryFile(suffix=".xyz") as iofile:
|
|
1238
|
+
# try and write out the xyz file
|
|
1239
|
+
toluene.to_file(iofile.name, "xyz", toolkit_registry=tkw)
|
|
1240
|
+
|
|
1241
|
+
# now lets check the file contents
|
|
1242
|
+
with open(iofile.name) as xyz_data:
|
|
1243
|
+
data = xyz_data.readlines()
|
|
1244
|
+
# make sure we have the correct amount of lines writen
|
|
1245
|
+
assert len(data) == 17
|
|
1246
|
+
# make sure all headers and frame data was writen
|
|
1247
|
+
assert data.count("15\n") == 1
|
|
1248
|
+
assert data.count("C7H8\n") == 1
|
|
1249
|
+
# now check that we can find the first and last coords
|
|
1250
|
+
coords = [
|
|
1251
|
+
"C 22.3700008392 21.6800003052 29.7700004578\n",
|
|
1252
|
+
"H 26.7900009155 23.1900005341 28.7199993134\n",
|
|
1253
|
+
]
|
|
1254
|
+
for coord in coords:
|
|
1255
|
+
assert coord in data
|
|
1256
|
+
|
|
1257
|
+
@requires_rdkit
|
|
1258
|
+
def test_to_multiframe_xyz_rdkit(self):
|
|
1259
|
+
"""
|
|
1260
|
+
Test writing out a molecule with multiple conformations to an xyz file
|
|
1261
|
+
|
|
1262
|
+
This test is backend-specific because of precision/rounding differences between RDKit and OpenEye
|
|
1263
|
+
"""
|
|
1264
|
+
from openff.toolkit.utils import RDKitToolkitWrapper
|
|
1265
|
+
|
|
1266
|
+
tkw = RDKitToolkitWrapper()
|
|
1267
|
+
# load in an SDF of butane with multiple conformers in it
|
|
1268
|
+
molecules = Molecule.from_file(
|
|
1269
|
+
get_data_file_path("molecules/butane_multi.sdf"),
|
|
1270
|
+
"sdf",
|
|
1271
|
+
toolkit_registry=tkw,
|
|
1272
|
+
)
|
|
1273
|
+
# now we want to combine the conformers to one molecule
|
|
1274
|
+
butane = molecules[0]
|
|
1275
|
+
for mol in molecules[1:]:
|
|
1276
|
+
butane.add_conformer(mol._conformers[0])
|
|
1277
|
+
|
|
1278
|
+
# make sure we have the 7 conformers
|
|
1279
|
+
assert butane.n_conformers == 7
|
|
1280
|
+
with NamedTemporaryFile(suffix=".xyz") as iofile:
|
|
1281
|
+
# try and write out the xyz file
|
|
1282
|
+
butane.to_file(iofile.name, "xyz", toolkit_registry=tkw)
|
|
1283
|
+
|
|
1284
|
+
# now lets check whats in the file
|
|
1285
|
+
with open(iofile.name) as xyz_data:
|
|
1286
|
+
data = xyz_data.readlines()
|
|
1287
|
+
# make sure we have the correct amount of lines writen
|
|
1288
|
+
assert len(data) == 112
|
|
1289
|
+
# make sure all headers and frame data was writen
|
|
1290
|
+
assert data.count("14\n") == 7
|
|
1291
|
+
for i in range(1, 8):
|
|
1292
|
+
assert f"C4H10 Frame {i}\n" in data
|
|
1293
|
+
|
|
1294
|
+
# now make sure the first line of the coordinates are correct in every frame
|
|
1295
|
+
coords = [
|
|
1296
|
+
"C 1.8902000000 0.0426000000 0.2431000000\n",
|
|
1297
|
+
"C 1.8976000000 -0.0233000000 0.2846000000\n",
|
|
1298
|
+
"C -1.8794000000 -0.1793000000 -0.2565000000\n",
|
|
1299
|
+
"C -1.5206000000 -0.0165000000 0.2787000000\n",
|
|
1300
|
+
"C -1.4890000000 -0.2619000000 0.4871000000\n",
|
|
1301
|
+
"C -1.4941000000 -0.2249000000 -0.0958000000\n",
|
|
1302
|
+
"C -1.8827000000 -0.0372000000 0.1937000000\n",
|
|
1303
|
+
]
|
|
1304
|
+
for coord in coords:
|
|
1305
|
+
assert coord in data
|
|
1306
|
+
|
|
1307
|
+
@requires_rdkit
|
|
1308
|
+
def test_to_single_xyz_rdkit(self):
|
|
1309
|
+
"""
|
|
1310
|
+
Test writing to a single frame xyz file
|
|
1311
|
+
|
|
1312
|
+
This test is backend-specific because of precision/rounding differences between RDKit and OpenEye
|
|
1313
|
+
"""
|
|
1314
|
+
from openff.toolkit.utils import RDKitToolkitWrapper
|
|
1315
|
+
|
|
1316
|
+
tkw = RDKitToolkitWrapper()
|
|
1317
|
+
|
|
1318
|
+
# load a molecule with a single conformation
|
|
1319
|
+
toluene = Molecule.from_file(get_data_file_path("molecules/toluene.sdf"), "sdf", toolkit_registry=tkw)
|
|
1320
|
+
# make sure it has one conformer
|
|
1321
|
+
assert toluene.n_conformers == 1
|
|
1322
|
+
|
|
1323
|
+
with NamedTemporaryFile(suffix=".xyz") as iofile:
|
|
1324
|
+
# try and write out the xyz file
|
|
1325
|
+
toluene.to_file(iofile.name, "xyz", toolkit_registry=tkw)
|
|
1326
|
+
|
|
1327
|
+
# now lets check the file contents
|
|
1328
|
+
with open(iofile.name) as xyz_data:
|
|
1329
|
+
data = xyz_data.readlines()
|
|
1330
|
+
# make sure we have the correct amount of lines writen
|
|
1331
|
+
assert len(data) == 17
|
|
1332
|
+
# make sure all headers and frame data was writen
|
|
1333
|
+
assert data.count("15\n") == 1
|
|
1334
|
+
assert data.count("C7H8\n") == 1
|
|
1335
|
+
# now check that we can find the first and last coords
|
|
1336
|
+
coords = [
|
|
1337
|
+
"C 22.3700000000 21.6800000000 29.7700000000\n",
|
|
1338
|
+
"H 26.7900000000 23.1900000000 28.7200000000\n",
|
|
1339
|
+
]
|
|
1340
|
+
for coord in coords:
|
|
1341
|
+
assert coord in data
|
|
1342
|
+
|
|
1343
|
+
def test_to_xyz_no_conformers(self):
|
|
1344
|
+
"""Test writing a molecule out when it has no conformers here all coords should be 0."""
|
|
1345
|
+
|
|
1346
|
+
# here we want to make a molecule with no coordinates
|
|
1347
|
+
ethanol = create_ethanol()
|
|
1348
|
+
assert ethanol.n_conformers == 0
|
|
1349
|
+
|
|
1350
|
+
with NamedTemporaryFile(suffix=".xyz") as iofile:
|
|
1351
|
+
# try and write out the xyz file
|
|
1352
|
+
ethanol.to_file(iofile.name, "xyz")
|
|
1353
|
+
|
|
1354
|
+
# now lets check the file contents
|
|
1355
|
+
with open(iofile.name) as xyz_data:
|
|
1356
|
+
data = xyz_data.readlines()
|
|
1357
|
+
# make sure we have the correct amount of lines writen
|
|
1358
|
+
assert len(data) == 11
|
|
1359
|
+
# make sure all headers and frame data was writen
|
|
1360
|
+
assert data.count("9\n") == 1
|
|
1361
|
+
assert data.count("C2H6O\n") == 1
|
|
1362
|
+
# now check that all coords are 0
|
|
1363
|
+
coords = ["0.0000000000", "0.0000000000", "0.0000000000"]
|
|
1364
|
+
for atom_coords in data[2:]:
|
|
1365
|
+
assert atom_coords.split()[1:] == coords
|
|
1366
|
+
|
|
1367
|
+
# TODO: Should there be an equivalent toolkit test and leave this as an integration test?
|
|
1368
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
1369
|
+
@pytest.mark.parametrize(
|
|
1370
|
+
"format",
|
|
1371
|
+
[
|
|
1372
|
+
"mol2",
|
|
1373
|
+
"sdf",
|
|
1374
|
+
pytest.param(
|
|
1375
|
+
"pdb",
|
|
1376
|
+
marks=pytest.mark.wip(reason="Read from pdb has not been implemented properly yet"),
|
|
1377
|
+
),
|
|
1378
|
+
],
|
|
1379
|
+
)
|
|
1380
|
+
def test_to_from_file(self, molecule, format):
|
|
1381
|
+
"""Test that conversion/creation of a molecule to and from a file is consistent."""
|
|
1382
|
+
from openff.toolkit.utils.toolkits import UndefinedStereochemistryError
|
|
1383
|
+
|
|
1384
|
+
# TODO: Test all file capabilities; the current test is minimal
|
|
1385
|
+
# TODO: This is only for OE. Expand to both OE and RDKit toolkits.
|
|
1386
|
+
# Molecules that are known to raise UndefinedStereochemistryError.
|
|
1387
|
+
undefined_stereo_mols = {
|
|
1388
|
+
"DrugBank_1700",
|
|
1389
|
+
"DrugBank_2987",
|
|
1390
|
+
"DrugBank_3502",
|
|
1391
|
+
"DrugBank_4161",
|
|
1392
|
+
"DrugBank_4162",
|
|
1393
|
+
"DrugBank_6531",
|
|
1394
|
+
}
|
|
1395
|
+
undefined_stereo = molecule.name in undefined_stereo_mols
|
|
1396
|
+
|
|
1397
|
+
# The file is automatically deleted outside the with-clause.
|
|
1398
|
+
with NamedTemporaryFile(suffix="." + format) as iofile:
|
|
1399
|
+
# If this has undefined stereo, check that the exception is raised.
|
|
1400
|
+
extension = os.path.splitext(iofile.name)[1][1:]
|
|
1401
|
+
molecule.to_file(iofile.name, extension)
|
|
1402
|
+
if undefined_stereo:
|
|
1403
|
+
with pytest.raises(UndefinedStereochemistryError):
|
|
1404
|
+
Molecule.from_file(iofile.name)
|
|
1405
|
+
molecule2 = Molecule.from_file(iofile.name, allow_undefined_stereo=undefined_stereo)
|
|
1406
|
+
assert molecule == molecule2
|
|
1407
|
+
# TODO: Test to make sure properties are preserved?
|
|
1408
|
+
# NOTE: We can't read pdb files and expect chemical information to be preserved
|
|
1409
|
+
|
|
1410
|
+
@requires_openeye
|
|
1411
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
1412
|
+
def test_to_from_oemol(self, molecule):
|
|
1413
|
+
"""Test that conversion/creation of a molecule to and from a OEMol is consistent."""
|
|
1414
|
+
from openff.toolkit.utils.toolkits import UndefinedStereochemistryError
|
|
1415
|
+
|
|
1416
|
+
# Known failures raise an UndefinedStereochemistryError, but
|
|
1417
|
+
# the round-trip SMILES representation with the OpenEyeToolkit
|
|
1418
|
+
# doesn't seem to be affected.
|
|
1419
|
+
# ZINC test set known failures.
|
|
1420
|
+
# known_failures = {'ZINC05964684', 'ZINC05885163', 'ZINC05543156', 'ZINC17211981',
|
|
1421
|
+
# 'ZINC17312986', 'ZINC06424847', 'ZINC04963126'}
|
|
1422
|
+
|
|
1423
|
+
undefined_stereo = molecule.name in openeye_drugbank_undefined_stereo_mols
|
|
1424
|
+
|
|
1425
|
+
toolkit_wrapper = OpenEyeToolkitWrapper()
|
|
1426
|
+
|
|
1427
|
+
oemol = molecule.to_openeye()
|
|
1428
|
+
molecule_smiles = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
|
|
1429
|
+
|
|
1430
|
+
# First test making a molecule using the Molecule(oemol) method
|
|
1431
|
+
|
|
1432
|
+
# If this is a known failure, check that it raises UndefinedStereochemistryError
|
|
1433
|
+
# and proceed with the test ignoring it.
|
|
1434
|
+
test_mol = None
|
|
1435
|
+
if undefined_stereo:
|
|
1436
|
+
with pytest.raises(UndefinedStereochemistryError):
|
|
1437
|
+
Molecule(oemol)
|
|
1438
|
+
test_mol = Molecule(oemol, allow_undefined_stereo=True)
|
|
1439
|
+
else:
|
|
1440
|
+
test_mol = Molecule(oemol)
|
|
1441
|
+
|
|
1442
|
+
test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)
|
|
1443
|
+
assert molecule_smiles == test_mol_smiles
|
|
1444
|
+
|
|
1445
|
+
# Check that the two topologies are isomorphic.
|
|
1446
|
+
assert_molecule_is_equal(
|
|
1447
|
+
molecule,
|
|
1448
|
+
test_mol,
|
|
1449
|
+
"Molecule.to_openeye()/Molecule(oemol) round trip failed",
|
|
1450
|
+
)
|
|
1451
|
+
|
|
1452
|
+
# Second, test making a molecule using the Molecule.from_openeye(oemol) method
|
|
1453
|
+
|
|
1454
|
+
# If this is a known failure, check that it raises UndefinedStereochemistryError
|
|
1455
|
+
# and proceed with the test.
|
|
1456
|
+
if undefined_stereo:
|
|
1457
|
+
with pytest.raises(UndefinedStereochemistryError):
|
|
1458
|
+
Molecule.from_openeye(oemol)
|
|
1459
|
+
test_mol = Molecule.from_openeye(oemol, allow_undefined_stereo=True)
|
|
1460
|
+
else:
|
|
1461
|
+
test_mol = Molecule.from_openeye(oemol)
|
|
1462
|
+
|
|
1463
|
+
test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)
|
|
1464
|
+
assert molecule_smiles == test_mol_smiles
|
|
1465
|
+
|
|
1466
|
+
# Check that the two topologies are isomorphic.
|
|
1467
|
+
assert_molecule_is_equal(molecule, test_mol, "Molecule.to_openeye()/from_openeye() round trip failed")
|
|
1468
|
+
|
|
1469
|
+
def test_name(self):
|
|
1470
|
+
"""Test Molecule name property"""
|
|
1471
|
+
molecule1 = Molecule()
|
|
1472
|
+
molecule1.name = None
|
|
1473
|
+
|
|
1474
|
+
molecule2 = Molecule()
|
|
1475
|
+
molecule2.name = ""
|
|
1476
|
+
assert molecule1.name == molecule2.name
|
|
1477
|
+
|
|
1478
|
+
name = "benzene"
|
|
1479
|
+
molecule = Molecule()
|
|
1480
|
+
molecule.name = name
|
|
1481
|
+
assert molecule.name == name
|
|
1482
|
+
|
|
1483
|
+
def test_hill_formula(self):
|
|
1484
|
+
"""Test that making the hill formula is consistent between input methods and ordering"""
|
|
1485
|
+
# make sure smiles match reference
|
|
1486
|
+
molecule = create_ethanol()
|
|
1487
|
+
assert molecule.hill_formula == "C2H6O"
|
|
1488
|
+
|
|
1489
|
+
# make sure is not order dependent
|
|
1490
|
+
molecule_reverse = create_reversed_ethanol()
|
|
1491
|
+
assert molecule.hill_formula == molecule_reverse.hill_formula
|
|
1492
|
+
|
|
1493
|
+
# make sure single element names are put first
|
|
1494
|
+
order_mol = Molecule.from_smiles("C(Br)CB")
|
|
1495
|
+
assert order_mol.hill_formula == "C2H6BBr"
|
|
1496
|
+
|
|
1497
|
+
# test molecule with no carbon
|
|
1498
|
+
no_carb_mol = Molecule.from_smiles("OS(=O)(=O)O")
|
|
1499
|
+
assert no_carb_mol.hill_formula == "H2O4S"
|
|
1500
|
+
|
|
1501
|
+
# test no carbon and hydrogen
|
|
1502
|
+
br_i = Molecule.from_smiles("BrI")
|
|
1503
|
+
assert br_i.hill_formula == "BrI"
|
|
1504
|
+
|
|
1505
|
+
# make sure files and smiles match
|
|
1506
|
+
molecule_file = Molecule.from_file(get_data_file_path("molecules/ethanol.sdf"))
|
|
1507
|
+
assert molecule.hill_formula == molecule_file.hill_formula
|
|
1508
|
+
|
|
1509
|
+
# make sure the topology molecule gives the same formula
|
|
1510
|
+
assert molecule.hill_formula == Molecule._object_to_hill_formula(molecule.to_networkx())
|
|
1511
|
+
|
|
1512
|
+
assert molecule.hill_formula == _networkx_graph_to_hill_formula(molecule.to_networkx())
|
|
1513
|
+
|
|
1514
|
+
def test_isomorphic_general(self):
|
|
1515
|
+
"""Test the matching using different input types"""
|
|
1516
|
+
# check that hill formula fails are caught
|
|
1517
|
+
ethanol = create_ethanol()
|
|
1518
|
+
acetaldehyde = create_acetaldehyde()
|
|
1519
|
+
assert ethanol.is_isomorphic_with(acetaldehyde) is False
|
|
1520
|
+
assert acetaldehyde.is_isomorphic_with(ethanol) is False
|
|
1521
|
+
# check that different orderings work with full matching
|
|
1522
|
+
ethanol_reverse = create_reversed_ethanol()
|
|
1523
|
+
assert ethanol.is_isomorphic_with(ethanol_reverse) is True
|
|
1524
|
+
# check a reference mapping between ethanol and ethanol_reverse matches that calculated
|
|
1525
|
+
ref_mapping = {0: 8, 1: 7, 2: 6, 3: 5, 4: 4, 5: 3, 6: 2, 7: 1, 8: 0}
|
|
1526
|
+
assert Molecule.are_isomorphic(ethanol, ethanol_reverse, return_atom_map=True)[1] == ref_mapping
|
|
1527
|
+
# check matching with nx.Graph atomic numbers and connectivity only
|
|
1528
|
+
assert (
|
|
1529
|
+
Molecule.are_isomorphic(
|
|
1530
|
+
ethanol,
|
|
1531
|
+
ethanol_reverse.to_networkx(),
|
|
1532
|
+
aromatic_matching=False,
|
|
1533
|
+
formal_charge_matching=False,
|
|
1534
|
+
bond_order_matching=False,
|
|
1535
|
+
atom_stereochemistry_matching=False,
|
|
1536
|
+
bond_stereochemistry_matching=False,
|
|
1537
|
+
)[0]
|
|
1538
|
+
is True
|
|
1539
|
+
)
|
|
1540
|
+
# check matching with nx.Graph with full matching
|
|
1541
|
+
assert ethanol.is_isomorphic_with(ethanol_reverse.to_networkx()) is True
|
|
1542
|
+
|
|
1543
|
+
from openff.toolkit.topology.topology import Topology
|
|
1544
|
+
|
|
1545
|
+
topology = Topology.from_molecules(ethanol)
|
|
1546
|
+
assert (
|
|
1547
|
+
Molecule.are_isomorphic(
|
|
1548
|
+
ethanol,
|
|
1549
|
+
next(iter(topology.molecules)),
|
|
1550
|
+
aromatic_matching=False,
|
|
1551
|
+
formal_charge_matching=False,
|
|
1552
|
+
bond_order_matching=False,
|
|
1553
|
+
atom_stereochemistry_matching=False,
|
|
1554
|
+
bond_stereochemistry_matching=False,
|
|
1555
|
+
)[0]
|
|
1556
|
+
is True
|
|
1557
|
+
)
|
|
1558
|
+
# test hill formula passes but isomorphic fails
|
|
1559
|
+
mol1 = Molecule.from_smiles("Fc1ccc(F)cc1")
|
|
1560
|
+
mol2 = Molecule.from_smiles("Fc1ccccc1F")
|
|
1561
|
+
assert mol1.is_isomorphic_with(mol2) is False
|
|
1562
|
+
assert mol2.is_isomorphic_with(mol1) is False
|
|
1563
|
+
|
|
1564
|
+
isomorphic_permutations = [
|
|
1565
|
+
{
|
|
1566
|
+
"aromatic_matching": True,
|
|
1567
|
+
"formal_charge_matching": True,
|
|
1568
|
+
"bond_order_matching": True,
|
|
1569
|
+
"atom_stereochemistry_matching": True,
|
|
1570
|
+
"bond_stereochemistry_matching": True,
|
|
1571
|
+
"result": False,
|
|
1572
|
+
},
|
|
1573
|
+
{
|
|
1574
|
+
"aromatic_matching": False,
|
|
1575
|
+
"formal_charge_matching": True,
|
|
1576
|
+
"bond_order_matching": True,
|
|
1577
|
+
"atom_stereochemistry_matching": True,
|
|
1578
|
+
"bond_stereochemistry_matching": True,
|
|
1579
|
+
"result": False,
|
|
1580
|
+
},
|
|
1581
|
+
{
|
|
1582
|
+
"aromatic_matching": True,
|
|
1583
|
+
"formal_charge_matching": False,
|
|
1584
|
+
"bond_order_matching": True,
|
|
1585
|
+
"atom_stereochemistry_matching": True,
|
|
1586
|
+
"bond_stereochemistry_matching": True,
|
|
1587
|
+
"result": False,
|
|
1588
|
+
},
|
|
1589
|
+
{
|
|
1590
|
+
"aromatic_matching": True,
|
|
1591
|
+
"formal_charge_matching": True,
|
|
1592
|
+
"bond_order_matching": False,
|
|
1593
|
+
"atom_stereochemistry_matching": True,
|
|
1594
|
+
"bond_stereochemistry_matching": True,
|
|
1595
|
+
"result": False,
|
|
1596
|
+
},
|
|
1597
|
+
{
|
|
1598
|
+
"aromatic_matching": True,
|
|
1599
|
+
"formal_charge_matching": True,
|
|
1600
|
+
"bond_order_matching": True,
|
|
1601
|
+
"atom_stereochemistry_matching": False,
|
|
1602
|
+
"bond_stereochemistry_matching": True,
|
|
1603
|
+
"result": False,
|
|
1604
|
+
},
|
|
1605
|
+
{
|
|
1606
|
+
"aromatic_matching": True,
|
|
1607
|
+
"formal_charge_matching": True,
|
|
1608
|
+
"bond_order_matching": True,
|
|
1609
|
+
"atom_stereochemistry_matching": True,
|
|
1610
|
+
"bond_stereochemistry_matching": False,
|
|
1611
|
+
"result": False,
|
|
1612
|
+
},
|
|
1613
|
+
{
|
|
1614
|
+
"aromatic_matching": False,
|
|
1615
|
+
"formal_charge_matching": False,
|
|
1616
|
+
"bond_order_matching": False,
|
|
1617
|
+
"atom_stereochemistry_matching": False,
|
|
1618
|
+
"bond_stereochemistry_matching": False,
|
|
1619
|
+
"result": True,
|
|
1620
|
+
},
|
|
1621
|
+
{
|
|
1622
|
+
"aromatic_matching": False,
|
|
1623
|
+
"formal_charge_matching": True,
|
|
1624
|
+
"bond_order_matching": False,
|
|
1625
|
+
"atom_stereochemistry_matching": True,
|
|
1626
|
+
"bond_stereochemistry_matching": True,
|
|
1627
|
+
"result": True,
|
|
1628
|
+
},
|
|
1629
|
+
{
|
|
1630
|
+
"aromatic_matching": False,
|
|
1631
|
+
"formal_charge_matching": False,
|
|
1632
|
+
"bond_order_matching": False,
|
|
1633
|
+
"atom_stereochemistry_matching": True,
|
|
1634
|
+
"bond_stereochemistry_matching": True,
|
|
1635
|
+
"result": True,
|
|
1636
|
+
},
|
|
1637
|
+
]
|
|
1638
|
+
|
|
1639
|
+
@pytest.mark.parametrize("inputs", isomorphic_permutations)
|
|
1640
|
+
def test_isomorphic_perumtations(self, inputs):
|
|
1641
|
+
"""Test all of the different combinations of matching levels between benzene with and without the aromatic bonds
|
|
1642
|
+
defined"""
|
|
1643
|
+
# get benzene with all aromatic atoms/bonds labeled
|
|
1644
|
+
benzene = Molecule.from_smiles("c1ccccc1")
|
|
1645
|
+
# get benzene with no aromatic labels
|
|
1646
|
+
benzene_no_aromatic = create_benzene_no_aromatic()
|
|
1647
|
+
# now test all of the variations
|
|
1648
|
+
assert (
|
|
1649
|
+
Molecule.are_isomorphic(
|
|
1650
|
+
benzene,
|
|
1651
|
+
benzene_no_aromatic,
|
|
1652
|
+
aromatic_matching=inputs["aromatic_matching"],
|
|
1653
|
+
formal_charge_matching=inputs["formal_charge_matching"],
|
|
1654
|
+
bond_order_matching=inputs["bond_order_matching"],
|
|
1655
|
+
atom_stereochemistry_matching=inputs["atom_stereochemistry_matching"],
|
|
1656
|
+
bond_stereochemistry_matching=inputs["bond_stereochemistry_matching"],
|
|
1657
|
+
)[0]
|
|
1658
|
+
is inputs["result"]
|
|
1659
|
+
)
|
|
1660
|
+
|
|
1661
|
+
assert (
|
|
1662
|
+
benzene.is_isomorphic_with(
|
|
1663
|
+
benzene_no_aromatic,
|
|
1664
|
+
aromatic_matching=inputs["aromatic_matching"],
|
|
1665
|
+
formal_charge_matching=inputs["formal_charge_matching"],
|
|
1666
|
+
bond_order_matching=inputs["bond_order_matching"],
|
|
1667
|
+
atom_stereochemistry_matching=inputs["atom_stereochemistry_matching"],
|
|
1668
|
+
bond_stereochemistry_matching=inputs["bond_stereochemistry_matching"],
|
|
1669
|
+
)
|
|
1670
|
+
is inputs["result"]
|
|
1671
|
+
)
|
|
1672
|
+
|
|
1673
|
+
def test_isomorphic_speedup_assumptions(self):
|
|
1674
|
+
"""
|
|
1675
|
+
This test ensures that the assumptions needed by the isomorphism checking speedup in
|
|
1676
|
+
https://github.com/openforcefield/openff-toolkit/pull/2114 are policed
|
|
1677
|
+
"""
|
|
1678
|
+
mol1 = Molecule.from_mapped_smiles("[F:1][H-:2][H-:3][Cl:4]")
|
|
1679
|
+
mol2 = Molecule.from_mapped_smiles("[Cl:1][H-:2][H-:3][F:4]")
|
|
1680
|
+
with pytest.raises(BadMoleculeAssumptionError):
|
|
1681
|
+
assert mol1.is_isomorphic_with(mol2)
|
|
1682
|
+
|
|
1683
|
+
@requires_openeye
|
|
1684
|
+
def test_strip_atom_stereochemistry(self):
|
|
1685
|
+
"""Test the basic behavior of strip_atom_stereochemistry"""
|
|
1686
|
+
mol = Molecule.from_smiles("CCC[N@@](C)CC")
|
|
1687
|
+
|
|
1688
|
+
nitrogen_idx = next(atom.molecule_atom_index for atom in mol.atoms if atom.symbol == "N")
|
|
1689
|
+
|
|
1690
|
+
# TODO: This fails with RDKitToolkitWrapper because it perceives
|
|
1691
|
+
# the stereochemistry of this nitrogen as None
|
|
1692
|
+
assert mol.atoms[nitrogen_idx].stereochemistry == "S"
|
|
1693
|
+
mol.strip_atom_stereochemistry(smarts="[N+0X3:1](-[*])(-[*])(-[*])")
|
|
1694
|
+
assert mol.atoms[nitrogen_idx].stereochemistry is None
|
|
1695
|
+
|
|
1696
|
+
mol = Molecule.from_smiles("CCC[N@@](C)CC")
|
|
1697
|
+
|
|
1698
|
+
assert mol.atoms[nitrogen_idx].stereochemistry == "S"
|
|
1699
|
+
mol.strip_atom_stereochemistry(smarts="[N+0X3:1](-[*])(-[*])(-[*])")
|
|
1700
|
+
assert mol.atoms[nitrogen_idx].stereochemistry is None
|
|
1701
|
+
|
|
1702
|
+
@pytest.mark.parametrize("mol_smiles", [("C[N+](CC)(CC)CC"), ("c1cnc[nH]1")])
|
|
1703
|
+
def test_do_not_strip_atom_stereochemsitry(self, mol_smiles):
|
|
1704
|
+
"""
|
|
1705
|
+
Test special cases in which we do not want nitrogen stereochemistry stripped:
|
|
1706
|
+
NH in planar rings and tetra-coordinatined N+
|
|
1707
|
+
"""
|
|
1708
|
+
mol = Molecule.from_smiles(mol_smiles)
|
|
1709
|
+
mol_mod = copy.deepcopy(mol)
|
|
1710
|
+
mol_mod.strip_atom_stereochemistry("[N+0X3:1](-[*])(-[*])(-[*])")
|
|
1711
|
+
|
|
1712
|
+
# Inspect each atom's stereochemistry instead of relying on __eq__
|
|
1713
|
+
for before, after in zip(mol.atoms, mol_mod.atoms):
|
|
1714
|
+
assert before.stereochemistry == after.stereochemistry
|
|
1715
|
+
|
|
1716
|
+
def test_isomorphic_stripped_stereochemistry(self):
|
|
1717
|
+
"""Test that the equality operator disregards an edge case of nitrogen stereocenters"""
|
|
1718
|
+
mol1 = Molecule.from_smiles("CCC[N@](C)CC")
|
|
1719
|
+
mol2 = Molecule.from_smiles("CCC[N@@](C)CC")
|
|
1720
|
+
|
|
1721
|
+
# Ensure default value is respected and order does not matter
|
|
1722
|
+
assert Molecule.are_isomorphic(mol1, mol2, strip_pyrimidal_n_atom_stereo=True)
|
|
1723
|
+
assert Molecule.are_isomorphic(mol1, mol2)
|
|
1724
|
+
assert Molecule.are_isomorphic(mol2, mol1)
|
|
1725
|
+
|
|
1726
|
+
assert mol1 == mol2
|
|
1727
|
+
assert Molecule.from_smiles("CCC[N@](C)CC") == Molecule.from_smiles("CCC[N@@](C)CC")
|
|
1728
|
+
|
|
1729
|
+
def test_short_circuit_heterogeneous_input(self):
|
|
1730
|
+
from openff.toolkit.topology._mm_molecule import _SimpleMolecule
|
|
1731
|
+
|
|
1732
|
+
assert not Molecule.are_isomorphic(
|
|
1733
|
+
create_ethanol(),
|
|
1734
|
+
_SimpleMolecule.from_molecule(create_ethanol()),
|
|
1735
|
+
)[0]
|
|
1736
|
+
|
|
1737
|
+
assert not Molecule.are_isomorphic(
|
|
1738
|
+
_SimpleMolecule.from_molecule(create_ethanol()),
|
|
1739
|
+
create_ethanol(),
|
|
1740
|
+
)[0]
|
|
1741
|
+
|
|
1742
|
+
def test_exactly_the_same_short_circuit_return_atom_map(self):
|
|
1743
|
+
SMILES = "c1ncccc1COCC"
|
|
1744
|
+
ISOMORPHIC_SMILES = "CCOCc1cccnc1"
|
|
1745
|
+
|
|
1746
|
+
molecule = Molecule.from_smiles(SMILES)
|
|
1747
|
+
exactly_the_same = Molecule.from_smiles(SMILES)
|
|
1748
|
+
not_exactly_the_same = Molecule.from_smiles(ISOMORPHIC_SMILES)
|
|
1749
|
+
|
|
1750
|
+
atom_map = {index: index for index in range(molecule.n_atoms)}
|
|
1751
|
+
|
|
1752
|
+
# If not returning the map, isomorphic inputs should always return (True, None)
|
|
1753
|
+
assert Molecule.are_isomorphic(molecule, exactly_the_same, return_atom_map=False) == (True, None)
|
|
1754
|
+
assert Molecule.are_isomorphic(molecule, not_exactly_the_same, return_atom_map=False) == (True, None)
|
|
1755
|
+
|
|
1756
|
+
# If returning the mapping, isomorphic inputs should always return True and some mapping ...
|
|
1757
|
+
assert Molecule.are_isomorphic(molecule, exactly_the_same, return_atom_map=True) == (True, atom_map)
|
|
1758
|
+
|
|
1759
|
+
# but the ordering is not guaranteed, so just check that the map is a dict of the right length
|
|
1760
|
+
result, mapping = Molecule.are_isomorphic(molecule, not_exactly_the_same, return_atom_map=True)
|
|
1761
|
+
assert result
|
|
1762
|
+
assert isinstance(mapping, dict)
|
|
1763
|
+
assert len(mapping) == molecule.n_atoms
|
|
1764
|
+
|
|
1765
|
+
def test_graph_and_molecule_inputs(self):
|
|
1766
|
+
molecule = create_ethanol()
|
|
1767
|
+
graph = molecule.to_networkx()
|
|
1768
|
+
|
|
1769
|
+
assert Molecule.are_isomorphic(molecule, graph)[0]
|
|
1770
|
+
assert Molecule.are_isomorphic(graph, molecule)[0]
|
|
1771
|
+
|
|
1772
|
+
class TestRemap:
|
|
1773
|
+
"""Tests for the ``Molecule.remap()`` method"""
|
|
1774
|
+
|
|
1775
|
+
def assert_molecules_match_after_remap(self, mol1, mol2):
|
|
1776
|
+
"""Check all of the attributes in a molecule match after being remapped"""
|
|
1777
|
+
for atoms in zip(mol1.atoms, mol2.atoms):
|
|
1778
|
+
assert atoms[0].to_dict() == atoms[1].to_dict()
|
|
1779
|
+
# bonds will not be in the same order in the molecule and the atom1 and atom2 indecies could be out of
|
|
1780
|
+
# order make a dict to compare them both
|
|
1781
|
+
remapped_bonds = dict(((bond.atom1_index, bond.atom2_index), bond) for bond in mol2.bonds)
|
|
1782
|
+
for bond in mol1.bonds:
|
|
1783
|
+
key = (bond.atom1_index, bond.atom2_index)
|
|
1784
|
+
if key not in remapped_bonds:
|
|
1785
|
+
key = tuple(reversed(key))
|
|
1786
|
+
assert key in remapped_bonds
|
|
1787
|
+
# now compare each attribute of the bond except the atom indexes
|
|
1788
|
+
bond_dict = bond.to_dict()
|
|
1789
|
+
del bond_dict["atom1"]
|
|
1790
|
+
del bond_dict["atom2"]
|
|
1791
|
+
remapped_bond_dict = remapped_bonds[key].to_dict()
|
|
1792
|
+
del remapped_bond_dict["atom1"]
|
|
1793
|
+
del remapped_bond_dict["atom2"]
|
|
1794
|
+
assert mol1.n_bonds == mol2.n_bonds
|
|
1795
|
+
assert mol1.n_angles == mol2.n_angles
|
|
1796
|
+
assert mol1.n_propers == mol2.n_propers
|
|
1797
|
+
assert mol1.n_impropers == mol2.n_impropers
|
|
1798
|
+
assert mol1.total_charge == mol2.total_charge
|
|
1799
|
+
assert mol1.partial_charges.all() == mol2.partial_charges.all()
|
|
1800
|
+
|
|
1801
|
+
def test_remap(self):
|
|
1802
|
+
"""Test the remap function which should return a new molecule in the requested ordering"""
|
|
1803
|
+
# the order here is CCO
|
|
1804
|
+
ethanol = create_ethanol()
|
|
1805
|
+
# get ethanol in reverse order OCC
|
|
1806
|
+
ethanol_reverse = create_reversed_ethanol()
|
|
1807
|
+
# get the mapping between the molecules
|
|
1808
|
+
mapping = Molecule.are_isomorphic(ethanol, ethanol_reverse, True)[1]
|
|
1809
|
+
|
|
1810
|
+
new_ethanol = ethanol.remap(mapping, current_to_new=True)
|
|
1811
|
+
|
|
1812
|
+
# check all of the properties match as well, torsions and impropers will be in a different order
|
|
1813
|
+
# due to the bonds being out of order
|
|
1814
|
+
self.assert_molecules_match_after_remap(new_ethanol, ethanol_reverse)
|
|
1815
|
+
|
|
1816
|
+
# test round trip (double remapping a molecule)
|
|
1817
|
+
new_ethanol = ethanol.remap(mapping, current_to_new=True)
|
|
1818
|
+
isomorphic, round_trip_mapping = Molecule.are_isomorphic(new_ethanol, ethanol, return_atom_map=True)
|
|
1819
|
+
assert isomorphic is True
|
|
1820
|
+
round_trip_ethanol = new_ethanol.remap(round_trip_mapping, current_to_new=True)
|
|
1821
|
+
self.assert_molecules_match_after_remap(round_trip_ethanol, ethanol)
|
|
1822
|
+
|
|
1823
|
+
@pytest.mark.parametrize("current_to_new", [True, False])
|
|
1824
|
+
@pytest.mark.parametrize("partial", [True, False])
|
|
1825
|
+
def test_remap_fails_with_duplicate_indices(
|
|
1826
|
+
self,
|
|
1827
|
+
current_to_new,
|
|
1828
|
+
partial,
|
|
1829
|
+
):
|
|
1830
|
+
ethanol = create_ethanol()
|
|
1831
|
+
# get a mapping with duplicate atoms
|
|
1832
|
+
mapping = {i: i for i in range(ethanol.n_atoms)}
|
|
1833
|
+
# Make the first and second maps duplicates
|
|
1834
|
+
mapping[1] = mapping[0]
|
|
1835
|
+
|
|
1836
|
+
with pytest.raises(
|
|
1837
|
+
RemapIndexError,
|
|
1838
|
+
match="There must be no duplicate source or destination indices",
|
|
1839
|
+
):
|
|
1840
|
+
ethanol.remap(
|
|
1841
|
+
mapping,
|
|
1842
|
+
current_to_new=current_to_new,
|
|
1843
|
+
partial=partial,
|
|
1844
|
+
)
|
|
1845
|
+
|
|
1846
|
+
@pytest.mark.parametrize(
|
|
1847
|
+
"mapping",
|
|
1848
|
+
[
|
|
1849
|
+
{10: 2, 11: 1, 12: 0, 13: 6, 14: 7, 15: 8, 16: 4, 17: 5, 18: 3},
|
|
1850
|
+
{0: 2, 1: 1, 2: 0, 3: 6, 4: 7, 5: 8, 6: 4, 7: 5, 8: 999999},
|
|
1851
|
+
{0: 2, 1: 1, 2: 0, 3: 6, 4: "not an integer", 5: 8, 6: 4, 7: 5, 8: 3},
|
|
1852
|
+
],
|
|
1853
|
+
)
|
|
1854
|
+
@pytest.mark.parametrize("current_to_new", [True, False])
|
|
1855
|
+
@pytest.mark.parametrize("partial", [True, False])
|
|
1856
|
+
def test_remap_fails_with_out_of_range_indices(self, mapping, current_to_new, partial):
|
|
1857
|
+
"""Make sure the remap fails when indices are out of range
|
|
1858
|
+
|
|
1859
|
+
This tests current_to_new in both directions and ensures the
|
|
1860
|
+
same behavior with partial maps (as all total maps should work in
|
|
1861
|
+
partial mode).
|
|
1862
|
+
"""
|
|
1863
|
+
ethanol = Molecule.from_file(get_data_file_path("molecules/ethanol.sdf"))
|
|
1864
|
+
mapping = {0: 2, 1: 1, 2: 0, 3: 6, 4: 7, 5: 8, 6: 4, 7: 5, 8: 3}
|
|
1865
|
+
wrong_index_mapping = dict((i + 10, new_id) for i, new_id in enumerate(mapping.values()))
|
|
1866
|
+
with pytest.raises(
|
|
1867
|
+
RemapIndexError,
|
|
1868
|
+
match=re.escape(
|
|
1869
|
+
"All indices in a mapping_dict for a molecule with 9 atoms" + " must be integers between 0 and 8"
|
|
1870
|
+
),
|
|
1871
|
+
):
|
|
1872
|
+
ethanol.remap(wrong_index_mapping, current_to_new=current_to_new, partial=partial)
|
|
1873
|
+
|
|
1874
|
+
def test_remap_fails_with_missing_indices(self):
|
|
1875
|
+
ethanol = create_ethanol()
|
|
1876
|
+
# get a mapping with duplicate atoms
|
|
1877
|
+
mapping = {i: i for i in range(ethanol.n_atoms)}
|
|
1878
|
+
# Remove one of the mappings
|
|
1879
|
+
del mapping[0]
|
|
1880
|
+
|
|
1881
|
+
with pytest.raises(
|
|
1882
|
+
RemapIndexError,
|
|
1883
|
+
match=re.escape(
|
|
1884
|
+
f"The number of mapping indices ({len(mapping)}) does not "
|
|
1885
|
+
+ f"match the number of atoms in this molecule ({ethanol.n_atoms})"
|
|
1886
|
+
),
|
|
1887
|
+
):
|
|
1888
|
+
ethanol.remap(mapping, current_to_new=True)
|
|
1889
|
+
|
|
1890
|
+
def test_remap_updates_atom_map(self):
|
|
1891
|
+
# get ethanol and a reverse mapping
|
|
1892
|
+
ethanol = create_ethanol()
|
|
1893
|
+
ethanol_reverse = create_reversed_ethanol()
|
|
1894
|
+
mapping = Molecule.are_isomorphic(ethanol, ethanol_reverse, True)[1]
|
|
1895
|
+
# Set up an atom_map to update
|
|
1896
|
+
ethanol.properties["atom_map"] = {
|
|
1897
|
+
0: 1, # Check uncomplicated entries are remapped
|
|
1898
|
+
1: "foo", # Check non-integer values are remapped
|
|
1899
|
+
2: 2, # Check duplicate values are remapped
|
|
1900
|
+
3: 2,
|
|
1901
|
+
"hello": 3, # Check non-integer keys are preserved
|
|
1902
|
+
1000: 1000, # Check out-of-range keys are preserved
|
|
1903
|
+
}
|
|
1904
|
+
# Name all atoms so we can tell them apart later
|
|
1905
|
+
for atom, name in zip(ethanol.atoms, range(ethanol.n_atoms)):
|
|
1906
|
+
atom.name = "atom_" + str(name)
|
|
1907
|
+
# Run the remap
|
|
1908
|
+
new_ethanol = ethanol.remap(mapping, current_to_new=True)
|
|
1909
|
+
|
|
1910
|
+
def atom_name_or(default, molecule, index):
|
|
1911
|
+
"""Get the atom name at the given index, or the default"""
|
|
1912
|
+
try:
|
|
1913
|
+
return molecule.atom(index).name
|
|
1914
|
+
except (TypeError, IndexError):
|
|
1915
|
+
return default
|
|
1916
|
+
|
|
1917
|
+
# Check the updated atom map
|
|
1918
|
+
expected_atom_map_with_names = {
|
|
1919
|
+
atom_name_or(k, ethanol, k): v for k, v in ethanol.properties["atom_map"].items()
|
|
1920
|
+
}
|
|
1921
|
+
actual_atom_map_with_names = {
|
|
1922
|
+
atom_name_or(k, new_ethanol, k): v for k, v in new_ethanol.properties["atom_map"].items()
|
|
1923
|
+
}
|
|
1924
|
+
assert expected_atom_map_with_names == actual_atom_map_with_names
|
|
1925
|
+
|
|
1926
|
+
def test_remap_partial(self):
|
|
1927
|
+
"""Test the remap function which should return a new molecule in the requested ordering"""
|
|
1928
|
+
# the order here is CCO
|
|
1929
|
+
ethanol = create_ethanol()
|
|
1930
|
+
# Create partial map to swap first two atoms
|
|
1931
|
+
partial_map = {0: 1, 1: 0}
|
|
1932
|
+
# Create equivalent total map
|
|
1933
|
+
total_map = {0: 1, 1: 0, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}
|
|
1934
|
+
|
|
1935
|
+
remapped_ethanol_partial = ethanol.remap(
|
|
1936
|
+
partial_map,
|
|
1937
|
+
current_to_new=True,
|
|
1938
|
+
partial=True,
|
|
1939
|
+
)
|
|
1940
|
+
remapped_ethanol_total = ethanol.remap(
|
|
1941
|
+
total_map,
|
|
1942
|
+
current_to_new=True,
|
|
1943
|
+
partial=False,
|
|
1944
|
+
)
|
|
1945
|
+
|
|
1946
|
+
# check all of the properties match as well, torsions and impropers will be in a different order
|
|
1947
|
+
# due to the bonds being out of order
|
|
1948
|
+
self.assert_molecules_match_after_remap(
|
|
1949
|
+
remapped_ethanol_partial,
|
|
1950
|
+
remapped_ethanol_total,
|
|
1951
|
+
)
|
|
1952
|
+
|
|
1953
|
+
@pytest.mark.parametrize(
|
|
1954
|
+
"mapping",
|
|
1955
|
+
[
|
|
1956
|
+
{0: 0, 1: 0, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6},
|
|
1957
|
+
{0: 0, 1: 0},
|
|
1958
|
+
],
|
|
1959
|
+
)
|
|
1960
|
+
@pytest.mark.parametrize("current_to_new", [True, False])
|
|
1961
|
+
def test_remap_partial_fails_with_duplicate_indices(
|
|
1962
|
+
self,
|
|
1963
|
+
mapping,
|
|
1964
|
+
current_to_new,
|
|
1965
|
+
):
|
|
1966
|
+
ethanol = create_ethanol()
|
|
1967
|
+
|
|
1968
|
+
with pytest.raises(
|
|
1969
|
+
RemapIndexError,
|
|
1970
|
+
match="There must be no duplicate source or destination indices",
|
|
1971
|
+
):
|
|
1972
|
+
ethanol.remap(
|
|
1973
|
+
mapping,
|
|
1974
|
+
current_to_new=current_to_new,
|
|
1975
|
+
partial=True,
|
|
1976
|
+
)
|
|
1977
|
+
|
|
1978
|
+
@pytest.mark.parametrize(
|
|
1979
|
+
"mapping",
|
|
1980
|
+
[
|
|
1981
|
+
{10: 0, 11: 1, 12: 2, 13: 3, 14: 4, 15: 5, 16: 6},
|
|
1982
|
+
{10: 2, 11: 1, 12: 0, 13: 6, 14: 7, 15: 8, 16: 4},
|
|
1983
|
+
{0: 9999999},
|
|
1984
|
+
{"not_an_integer": 0},
|
|
1985
|
+
],
|
|
1986
|
+
)
|
|
1987
|
+
@pytest.mark.parametrize("current_to_new", [True, False])
|
|
1988
|
+
def test_remap_partial_fails_with_out_of_range_indices(self, mapping, current_to_new):
|
|
1989
|
+
"""Make sure the remap fails when the indexing starts from the wrong value"""
|
|
1990
|
+
ethanol = Molecule.from_file(get_data_file_path("molecules/ethanol.sdf"))
|
|
1991
|
+
|
|
1992
|
+
with pytest.raises(
|
|
1993
|
+
RemapIndexError,
|
|
1994
|
+
match=re.escape(
|
|
1995
|
+
"All indices in a mapping_dict for a molecule with 9 atoms" + " must be integers between 0 and 8"
|
|
1996
|
+
),
|
|
1997
|
+
):
|
|
1998
|
+
ethanol.remap(
|
|
1999
|
+
mapping,
|
|
2000
|
+
current_to_new=current_to_new,
|
|
2001
|
+
partial=True,
|
|
2002
|
+
)
|
|
2003
|
+
|
|
2004
|
+
@requires_openeye
|
|
2005
|
+
def test_canonical_ordering_openeye(self):
|
|
2006
|
+
"""Make sure molecules are returned in canonical ordering of openeye"""
|
|
2007
|
+
from openff.toolkit.utils.toolkits import OpenEyeToolkitWrapper
|
|
2008
|
+
|
|
2009
|
+
openeye = OpenEyeToolkitWrapper()
|
|
2010
|
+
# get ethanol in canonical order
|
|
2011
|
+
ethanol = create_ethanol()
|
|
2012
|
+
# get reversed non canonical ethanol
|
|
2013
|
+
reversed_ethanol = create_reversed_ethanol()
|
|
2014
|
+
# get the canonical ordering
|
|
2015
|
+
canonical_ethanol = reversed_ethanol.canonical_order_atoms(openeye)
|
|
2016
|
+
# make sure the mapping between the ethanol and the openeye ref canonical form is the same
|
|
2017
|
+
assert (
|
|
2018
|
+
True,
|
|
2019
|
+
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
|
|
2020
|
+
) == Molecule.are_isomorphic(canonical_ethanol, ethanol, True)
|
|
2021
|
+
|
|
2022
|
+
@requires_rdkit
|
|
2023
|
+
def test_canonical_ordering_rdkit(self):
|
|
2024
|
+
"""Make sure molecules are returned in canonical ordering of the RDKit"""
|
|
2025
|
+
from openff.toolkit.utils.toolkits import RDKitToolkitWrapper
|
|
2026
|
+
|
|
2027
|
+
rdkit = RDKitToolkitWrapper()
|
|
2028
|
+
# get ethanol in canonical order
|
|
2029
|
+
ethanol = create_ethanol()
|
|
2030
|
+
# get reversed non canonical ethanol
|
|
2031
|
+
reversed_ethanol = create_reversed_ethanol()
|
|
2032
|
+
# get the canonical ordering
|
|
2033
|
+
canonical_ethanol = reversed_ethanol.canonical_order_atoms(rdkit)
|
|
2034
|
+
# make sure the mapping between the ethanol and the rdkit ref canonical form is the same
|
|
2035
|
+
assert (
|
|
2036
|
+
True,
|
|
2037
|
+
{0: 2, 1: 0, 2: 1, 3: 8, 4: 3, 5: 4, 6: 5, 7: 6, 8: 7},
|
|
2038
|
+
) == Molecule.are_isomorphic(canonical_ethanol, ethanol, True)
|
|
2039
|
+
|
|
2040
|
+
def test_from_xyz_unsupported(self):
|
|
2041
|
+
with pytest.raises(UnsupportedFileTypeError):
|
|
2042
|
+
Molecule.from_file("foo.xyz", file_format="xyz")
|
|
2043
|
+
|
|
2044
|
+
@requires_rdkit
|
|
2045
|
+
@pytest.mark.parametrize(
|
|
2046
|
+
"pdb_path,smiles,sdf_path",
|
|
2047
|
+
[
|
|
2048
|
+
(
|
|
2049
|
+
"proteins/MainChain_ALA_ALA.pdb",
|
|
2050
|
+
"C[C@@H](C(=O)N[C@@H](C)C(=O)NC)NC(=O)C",
|
|
2051
|
+
"proteins/MainChain_ALA_ALA.sdf",
|
|
2052
|
+
),
|
|
2053
|
+
(
|
|
2054
|
+
"molecules/toluene.pdb",
|
|
2055
|
+
"CC1=CC=CC=C1",
|
|
2056
|
+
"molecules/toluene.sdf",
|
|
2057
|
+
),
|
|
2058
|
+
],
|
|
2059
|
+
)
|
|
2060
|
+
class TestFromPDBAndSmiles:
|
|
2061
|
+
"""
|
|
2062
|
+
Tests for the ``Molecule.from_pdb_and_smiles()`` method
|
|
2063
|
+
|
|
2064
|
+
Parametrized with different molecules to test on. Each molecule should
|
|
2065
|
+
be a single-molecule PDB, the corresponding SMILES, and a matching SDF
|
|
2066
|
+
with identical coordinates and atom ordering to the PDB.
|
|
2067
|
+
"""
|
|
2068
|
+
|
|
2069
|
+
def test_wrong_smiles_fails(self, pdb_path, smiles, sdf_path):
|
|
2070
|
+
"""Providing an incorrect SMILES should raise an ``InvalidConformerError``"""
|
|
2071
|
+
pdb_path = get_data_file_path(pdb_path)
|
|
2072
|
+
|
|
2073
|
+
# Guarantee wrong_smiles is wrong, even if more parameter options
|
|
2074
|
+
# are added in future
|
|
2075
|
+
wrong_smiles = "CC"
|
|
2076
|
+
if Molecule.from_smiles(wrong_smiles).is_isomorphic_with(Molecule.from_smiles(smiles)):
|
|
2077
|
+
wrong_smiles = "CCC"
|
|
2078
|
+
|
|
2079
|
+
# Run the test
|
|
2080
|
+
with pytest.raises(InvalidConformerError):
|
|
2081
|
+
Molecule.from_pdb_and_smiles(pdb_path, wrong_smiles)
|
|
2082
|
+
|
|
2083
|
+
@requires_pkg("mdtraj")
|
|
2084
|
+
def test_atom_order_matches_pdb(self, pdb_path, smiles, sdf_path):
|
|
2085
|
+
"""The produced Molecule's atom order should match the PDB
|
|
2086
|
+
|
|
2087
|
+
This test uses MDTraj as an alternative PDB parser to check atom
|
|
2088
|
+
ordering. However, it can only check that the elements and atom
|
|
2089
|
+
names are correct, not connectivity."""
|
|
2090
|
+
import mdtraj
|
|
2091
|
+
|
|
2092
|
+
pdb_path = get_data_file_path(pdb_path)
|
|
2093
|
+
mol = Molecule.from_pdb_and_smiles(pdb_path, smiles)
|
|
2094
|
+
|
|
2095
|
+
pdb_mdtraj = mdtraj.load_pdb(pdb_path, standard_names=False)
|
|
2096
|
+
|
|
2097
|
+
assert pdb_mdtraj.n_atoms == mol.n_atoms
|
|
2098
|
+
for mdtraj_atom, off_atom in zip(pdb_mdtraj.topology.atoms, mol.atoms):
|
|
2099
|
+
assert mdtraj_atom.element.number == off_atom.atomic_number
|
|
2100
|
+
assert mdtraj_atom.name == off_atom.name
|
|
2101
|
+
|
|
2102
|
+
@requires_pkg("mdtraj")
|
|
2103
|
+
def test_conformers_match_pdb(self, pdb_path, smiles, sdf_path):
|
|
2104
|
+
"""The produced conformers should match the coordinates in the PDB
|
|
2105
|
+
|
|
2106
|
+
This test uses MDTraj as an alternative PDB parser to check
|
|
2107
|
+
coordinates."""
|
|
2108
|
+
import mdtraj
|
|
2109
|
+
|
|
2110
|
+
pdb_path = get_data_file_path(pdb_path)
|
|
2111
|
+
mol = Molecule.from_pdb_and_smiles(pdb_path, smiles)
|
|
2112
|
+
|
|
2113
|
+
pdb_mdtraj = mdtraj.load_pdb(pdb_path)
|
|
2114
|
+
|
|
2115
|
+
mdtraj_coordinates = pdb_mdtraj.xyz
|
|
2116
|
+
pdb_coordinates = np.asarray([conformer.m_as(unit.nanometer) for conformer in mol.conformers])
|
|
2117
|
+
|
|
2118
|
+
assert np.all(np.abs(mdtraj_coordinates - pdb_coordinates) < 1e-3)
|
|
2119
|
+
|
|
2120
|
+
@requires_pkg("openmm")
|
|
2121
|
+
def test_metadata_matches_pdb(self, pdb_path, smiles, sdf_path):
|
|
2122
|
+
"""The produced conformers should match the coordinates in the PDB
|
|
2123
|
+
|
|
2124
|
+
This test uses OpenMM as an alternative PDB parser to check
|
|
2125
|
+
metadata."""
|
|
2126
|
+
from openmm.app import PDBFile
|
|
2127
|
+
|
|
2128
|
+
pdb_path = get_data_file_path(pdb_path)
|
|
2129
|
+
mol = Molecule.from_pdb_and_smiles(pdb_path, smiles)
|
|
2130
|
+
|
|
2131
|
+
pdb_omm = PDBFile(pdb_path)
|
|
2132
|
+
|
|
2133
|
+
for omm_atom, off_atom in zip(pdb_omm.getTopology().atoms(), mol.atoms):
|
|
2134
|
+
omm_metadata = {
|
|
2135
|
+
"residue_name": omm_atom.residue.name,
|
|
2136
|
+
"residue_number": int(omm_atom.residue.id),
|
|
2137
|
+
"insertion_code": omm_atom.residue.insertionCode,
|
|
2138
|
+
"chain_id": omm_atom.residue.chain.id,
|
|
2139
|
+
}
|
|
2140
|
+
assert omm_metadata == off_atom.metadata
|
|
2141
|
+
|
|
2142
|
+
@requires_rdkit
|
|
2143
|
+
def test_connectivity_matches_pdb(self, pdb_path, smiles, sdf_path):
|
|
2144
|
+
"""
|
|
2145
|
+
The produced Molecule's connectivity should match RDKit's interpretation
|
|
2146
|
+
|
|
2147
|
+
This test is essential to check for jumbling of atom orders that do
|
|
2148
|
+
not alter element order. RDKit is used as a PDB parser to minimise
|
|
2149
|
+
differences in bond perception between parsers.
|
|
2150
|
+
"""
|
|
2151
|
+
pdb_path = get_data_file_path(pdb_path)
|
|
2152
|
+
mol = Molecule.from_pdb_and_smiles(pdb_path, smiles)
|
|
2153
|
+
from rdkit import Chem
|
|
2154
|
+
|
|
2155
|
+
rdkit_mol = Molecule.from_rdkit(
|
|
2156
|
+
Chem.MolFromPDBFile(pdb_path, removeHs=False),
|
|
2157
|
+
allow_undefined_stereo=True,
|
|
2158
|
+
hydrogens_are_explicit=True,
|
|
2159
|
+
)
|
|
2160
|
+
|
|
2161
|
+
expected_connectivity = sorted(sorted([bond.atom1_index, bond.atom2_index]) for bond in rdkit_mol.bonds)
|
|
2162
|
+
actual_connectivity = sorted(sorted([bond.atom1_index, bond.atom2_index]) for bond in mol.bonds)
|
|
2163
|
+
|
|
2164
|
+
assert expected_connectivity == actual_connectivity
|
|
2165
|
+
|
|
2166
|
+
def test_is_isomorphic_to_smiles(self, pdb_path, smiles, sdf_path):
|
|
2167
|
+
"""The produced Molecule should be isomorphic to the SMILES string"""
|
|
2168
|
+
pdb_path = get_data_file_path(pdb_path)
|
|
2169
|
+
pdb_mol = Molecule.from_pdb_and_smiles(pdb_path, smiles)
|
|
2170
|
+
|
|
2171
|
+
smiles_mol = Molecule.from_smiles(smiles)
|
|
2172
|
+
|
|
2173
|
+
assert pdb_mol.is_isomorphic_with(smiles_mol)
|
|
2174
|
+
|
|
2175
|
+
def test_name_kwarg(self, pdb_path, smiles, sdf_path):
|
|
2176
|
+
"""Ensure the name kwarg is wired up correctly"""
|
|
2177
|
+
pdb_path = get_data_file_path(pdb_path)
|
|
2178
|
+
pdb_mol = Molecule.from_pdb_and_smiles(pdb_path, smiles)
|
|
2179
|
+
assert pdb_mol.name == ""
|
|
2180
|
+
|
|
2181
|
+
pdb_mol = Molecule.from_pdb_and_smiles(pdb_path, smiles, name="bob")
|
|
2182
|
+
assert pdb_mol.name == "bob"
|
|
2183
|
+
|
|
2184
|
+
def test_matches_sdf(self, pdb_path, smiles, sdf_path):
|
|
2185
|
+
"""The produced Molecule should exactly match the corresponding SDF
|
|
2186
|
+
|
|
2187
|
+
This test is designed to catch anything missed by the above
|
|
2188
|
+
property tests."""
|
|
2189
|
+
pdb_path = get_data_file_path(pdb_path)
|
|
2190
|
+
pdb_mol = Molecule.from_pdb_and_smiles(pdb_path, smiles)
|
|
2191
|
+
|
|
2192
|
+
sdf_path = get_data_file_path(sdf_path)
|
|
2193
|
+
sdf_mol = Molecule.from_file(sdf_path)
|
|
2194
|
+
|
|
2195
|
+
# Check that the SDF and PDB are isomorphic with identical atom ordering
|
|
2196
|
+
isomorphic, atom_map = Molecule.are_isomorphic(pdb_mol, sdf_mol, return_atom_map=True)
|
|
2197
|
+
assert isomorphic, "SDF and PDB must be the same molecule"
|
|
2198
|
+
assert atom_map == {i: i for i in range(pdb_mol.n_atoms)}, "SDF and PDB must have same atom ordering"
|
|
2199
|
+
|
|
2200
|
+
# Check that the coordinates are identical
|
|
2201
|
+
np.testing.assert_allclose(
|
|
2202
|
+
np.asarray(sdf_mol.conformers[0].m),
|
|
2203
|
+
np.asarray(pdb_mol.conformers[0].m),
|
|
2204
|
+
atol=1e-4,
|
|
2205
|
+
err_msg="SDF and PDB must have identical conformers",
|
|
2206
|
+
)
|
|
2207
|
+
|
|
2208
|
+
# Not sure that the following are necessary given are_isomorphic,
|
|
2209
|
+
# but keeping them from previous test implementations
|
|
2210
|
+
|
|
2211
|
+
# Check that the atom properties are identical (except metadata)
|
|
2212
|
+
for pdb_atom, sdf_atom in zip(pdb_mol.atoms, sdf_mol.atoms):
|
|
2213
|
+
pdb_atom_dict = pdb_atom.to_dict()
|
|
2214
|
+
del pdb_atom_dict["metadata"]
|
|
2215
|
+
del pdb_atom_dict["name"]
|
|
2216
|
+
|
|
2217
|
+
sdf_atom_dict = sdf_atom.to_dict()
|
|
2218
|
+
del sdf_atom_dict["metadata"]
|
|
2219
|
+
del sdf_atom_dict["name"]
|
|
2220
|
+
assert sdf_atom_dict == pdb_atom_dict
|
|
2221
|
+
|
|
2222
|
+
# Check that the bonds match, though possibly in a different order
|
|
2223
|
+
sdf_bonds = {tuple(sorted([bond.atom1_index, bond.atom2_index])): bond for bond in sdf_mol.bonds}
|
|
2224
|
+
|
|
2225
|
+
for pdb_bond in pdb_mol.bonds:
|
|
2226
|
+
key = tuple(sorted([pdb_bond.atom1_index, pdb_bond.atom2_index]))
|
|
2227
|
+
assert key in sdf_bonds
|
|
2228
|
+
assert pdb_bond.is_aromatic == sdf_bonds[key].is_aromatic
|
|
2229
|
+
assert pdb_bond.stereochemistry == sdf_bonds[key].stereochemistry
|
|
2230
|
+
|
|
2231
|
+
def test_from_mapped_smiles(self):
|
|
2232
|
+
"""Test making the molecule from issue #412 using both toolkits to ensure the issue
|
|
2233
|
+
is fixed."""
|
|
2234
|
+
|
|
2235
|
+
# there should be no undefined sterochmeistry error when making the molecule
|
|
2236
|
+
mol = Molecule.from_mapped_smiles(
|
|
2237
|
+
"[H:14][c:1]1[c:3]([c:7]([c:11]([c:8]([c:4]1[H:17])[H:21])[C:13]([H:24])"
|
|
2238
|
+
"([H:25])[c:12]2[c:9]([c:5]([c:2]([c:6]([c:10]2[H:23])[H:19])[H:15])[H:18])[H:22])[H:20])[H:16]"
|
|
2239
|
+
)
|
|
2240
|
+
assert mol.n_atoms == 25
|
|
2241
|
+
# make sure the atom map is not exposed
|
|
2242
|
+
with pytest.raises(KeyError):
|
|
2243
|
+
mol._properties["atom_map"]
|
|
2244
|
+
|
|
2245
|
+
@pytest.mark.parametrize("toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper])
|
|
2246
|
+
def test_from_mapped_smiles_partial(self, toolkit_class):
|
|
2247
|
+
"""Test that creating a molecule from a partially mapped SMILES raises an
|
|
2248
|
+
exception."""
|
|
2249
|
+
if not (toolkit_class.is_available()):
|
|
2250
|
+
pytest.skip(f"Required toolkit {toolkit_class} is unavailable")
|
|
2251
|
+
with pytest.raises(
|
|
2252
|
+
SmilesParsingError,
|
|
2253
|
+
match="The mapped smiles does not contain enough indexes",
|
|
2254
|
+
):
|
|
2255
|
+
Molecule.from_mapped_smiles("[Cl:1][Cl]", toolkit_registry=toolkit_class())
|
|
2256
|
+
|
|
2257
|
+
def test_smiles_with_full_map_warning(
|
|
2258
|
+
self,
|
|
2259
|
+
):
|
|
2260
|
+
with pytest.warns(AtomMappingWarning):
|
|
2261
|
+
Molecule.from_smiles("[H:2][O:1][H:3]")
|
|
2262
|
+
|
|
2263
|
+
@requires_openeye
|
|
2264
|
+
def test_smiles_with_partial_map_no_warning(
|
|
2265
|
+
self,
|
|
2266
|
+
):
|
|
2267
|
+
"""Ensure the 'do you mean from_mapped_smiles?' warning is not emitted with a partial map"""
|
|
2268
|
+
with warnings.catch_warnings():
|
|
2269
|
+
# This turns warnings into exceptions - one way of implementing
|
|
2270
|
+
# "ensure there is not a warning raised"
|
|
2271
|
+
warnings.simplefilter("error")
|
|
2272
|
+
|
|
2273
|
+
Molecule.from_smiles("H[O:1]H")
|
|
2274
|
+
|
|
2275
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
2276
|
+
def test_n_atoms(self, molecule):
|
|
2277
|
+
"""Test n_atoms property"""
|
|
2278
|
+
n_atoms = sum([1 for atom in molecule.atoms])
|
|
2279
|
+
assert n_atoms == molecule.n_atoms
|
|
2280
|
+
|
|
2281
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
2282
|
+
def test_n_bonds(self, molecule):
|
|
2283
|
+
"""Test n_bonds property"""
|
|
2284
|
+
n_bonds = sum([1 for bond in molecule.bonds])
|
|
2285
|
+
assert n_bonds == molecule.n_bonds
|
|
2286
|
+
|
|
2287
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
2288
|
+
def test_angles(self, molecule):
|
|
2289
|
+
"""Test angles property"""
|
|
2290
|
+
for angle in molecule.angles:
|
|
2291
|
+
assert angle[0].is_bonded_to(angle[1])
|
|
2292
|
+
assert angle[1].is_bonded_to(angle[2])
|
|
2293
|
+
|
|
2294
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
2295
|
+
def test_propers(self, molecule):
|
|
2296
|
+
"""Test propers property"""
|
|
2297
|
+
for proper in molecule.propers:
|
|
2298
|
+
# The bonds should be in order 0-1-2-3 unless the
|
|
2299
|
+
# atoms form a three- or four-membered ring.
|
|
2300
|
+
is_chain = proper[0].is_bonded_to(proper[1])
|
|
2301
|
+
is_chain &= proper[1].is_bonded_to(proper[2])
|
|
2302
|
+
is_chain &= proper[2].is_bonded_to(proper[3])
|
|
2303
|
+
is_chain &= not proper[0].is_bonded_to(proper[2])
|
|
2304
|
+
is_chain &= not proper[0].is_bonded_to(proper[3])
|
|
2305
|
+
is_chain &= not proper[1].is_bonded_to(proper[3])
|
|
2306
|
+
|
|
2307
|
+
assert is_chain or is_three_membered_ring_torsion(proper) or is_four_membered_ring_torsion(proper)
|
|
2308
|
+
|
|
2309
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
2310
|
+
def test_impropers(self, molecule):
|
|
2311
|
+
"""Test impropers property"""
|
|
2312
|
+
for improper in molecule.impropers:
|
|
2313
|
+
assert improper[0].is_bonded_to(improper[1])
|
|
2314
|
+
assert improper[1].is_bonded_to(improper[2])
|
|
2315
|
+
assert improper[1].is_bonded_to(improper[3])
|
|
2316
|
+
|
|
2317
|
+
# The non-central atoms can be connected only if
|
|
2318
|
+
# the improper atoms form a three-membered ring.
|
|
2319
|
+
is_not_cyclic = not (
|
|
2320
|
+
(improper[0].is_bonded_to(improper[2]))
|
|
2321
|
+
or (improper[0].is_bonded_to(improper[3]))
|
|
2322
|
+
or (improper[2].is_bonded_to(improper[3]))
|
|
2323
|
+
)
|
|
2324
|
+
assert is_not_cyclic or is_three_membered_ring_torsion(improper)
|
|
2325
|
+
|
|
2326
|
+
@pytest.mark.parametrize(
|
|
2327
|
+
("molecule", "n_impropers", "n_pruned"),
|
|
2328
|
+
[
|
|
2329
|
+
("C", 24, 0),
|
|
2330
|
+
("CC", 48, 0),
|
|
2331
|
+
("N", 6, 6),
|
|
2332
|
+
],
|
|
2333
|
+
)
|
|
2334
|
+
def test_pruned_impropers(self, molecule, n_impropers, n_pruned):
|
|
2335
|
+
"""Test the amber_impropers and smirnoff_impropers properties"""
|
|
2336
|
+
mol = Molecule.from_smiles(molecule)
|
|
2337
|
+
assert mol.n_impropers == n_impropers
|
|
2338
|
+
assert len(mol.smirnoff_impropers) == n_pruned
|
|
2339
|
+
assert len(mol.amber_impropers) == n_pruned
|
|
2340
|
+
|
|
2341
|
+
# Order not guaranteed, so cannot zip and compare directly
|
|
2342
|
+
for smirnoff_imp in mol.smirnoff_impropers:
|
|
2343
|
+
# Convert SMIRNOFF-style improper into AMBER-style
|
|
2344
|
+
mod_imp = (
|
|
2345
|
+
smirnoff_imp[1],
|
|
2346
|
+
smirnoff_imp[0],
|
|
2347
|
+
smirnoff_imp[2],
|
|
2348
|
+
smirnoff_imp[3],
|
|
2349
|
+
)
|
|
2350
|
+
assert mod_imp in mol.amber_impropers
|
|
2351
|
+
|
|
2352
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
2353
|
+
def test_torsions(self, molecule):
|
|
2354
|
+
"""Test torsions property"""
|
|
2355
|
+
# molecule.torsions should be exactly equal to the union of propers and impropers.
|
|
2356
|
+
assert set(molecule.torsions) == set(molecule.propers) | set(molecule.impropers)
|
|
2357
|
+
|
|
2358
|
+
# The intersection of molecule.propers and molecule.impropers should be largely null.
|
|
2359
|
+
# The only exception is for molecules containing 3-membered rings (e.g., DrugBank_5514).
|
|
2360
|
+
common_torsions = molecule.propers & molecule.impropers
|
|
2361
|
+
if len(common_torsions) > 0:
|
|
2362
|
+
for torsion in common_torsions:
|
|
2363
|
+
assert is_three_membered_ring_torsion(torsion)
|
|
2364
|
+
|
|
2365
|
+
def test_nth_degree_neighbors_basic(self):
|
|
2366
|
+
benzene = Molecule.from_smiles("c1ccccc1")
|
|
2367
|
+
|
|
2368
|
+
with pytest.raises(ValueError, match="0 or fewer atoms"):
|
|
2369
|
+
benzene.nth_degree_neighbors(n_degrees=0)
|
|
2370
|
+
|
|
2371
|
+
with pytest.raises(ValueError, match="0 or fewer atoms"):
|
|
2372
|
+
benzene.nth_degree_neighbors(n_degrees=-1)
|
|
2373
|
+
|
|
2374
|
+
# 3 proper torsions have 1-4 pairs that are duplicates of other torsions, i.e.
|
|
2375
|
+
# torsions 0-1-2-3 0-5-4-3 where #s are the indices of carbons in the ring
|
|
2376
|
+
n_14_pairs = len([*benzene.nth_degree_neighbors(n_degrees=3)])
|
|
2377
|
+
assert n_14_pairs == benzene.n_propers - 3
|
|
2378
|
+
|
|
2379
|
+
for pair in benzene.nth_degree_neighbors(n_degrees=3):
|
|
2380
|
+
assert pair[0].molecule_atom_index < pair[1].molecule_atom_index
|
|
2381
|
+
|
|
2382
|
+
@pytest.mark.parametrize(
|
|
2383
|
+
("smiles", "n_degrees", "num_pairs"),
|
|
2384
|
+
[
|
|
2385
|
+
("c1ccccc1", 6, 0),
|
|
2386
|
+
("c1ccccc1", 5, 3),
|
|
2387
|
+
("c1ccccc1", 4, 12),
|
|
2388
|
+
("c1ccccc1", 3, 21),
|
|
2389
|
+
("N1ONON1", 4, 2),
|
|
2390
|
+
("N1ONON1", 3, 7),
|
|
2391
|
+
("C1#CO1", 2, 0),
|
|
2392
|
+
("C1#CO1", 1, 3),
|
|
2393
|
+
("C1CO1", 4, 0),
|
|
2394
|
+
("C1CO1", 2, 10),
|
|
2395
|
+
("C1=C=C=C=1", 4, 0),
|
|
2396
|
+
("C1=C=C=C=1", 3, 0),
|
|
2397
|
+
("C1=C=C=C=1", 2, 2),
|
|
2398
|
+
],
|
|
2399
|
+
)
|
|
2400
|
+
def test_nth_degree_neighbors_rings(self, smiles, n_degrees, num_pairs):
|
|
2401
|
+
molecule = Molecule.from_smiles(smiles)
|
|
2402
|
+
|
|
2403
|
+
num_pairs_found = len([*molecule.nth_degree_neighbors(n_degrees=n_degrees)])
|
|
2404
|
+
assert num_pairs_found == num_pairs
|
|
2405
|
+
|
|
2406
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
2407
|
+
def test_total_charge(self, molecule):
|
|
2408
|
+
"""Test total charge"""
|
|
2409
|
+
charge_sum = 0 * unit.elementary_charge
|
|
2410
|
+
for atom in molecule.atoms:
|
|
2411
|
+
charge_sum += atom.formal_charge
|
|
2412
|
+
assert charge_sum == molecule.total_charge
|
|
2413
|
+
|
|
2414
|
+
def test_equality(self):
|
|
2415
|
+
"""Test equality operator"""
|
|
2416
|
+
molecules = mini_drug_bank()
|
|
2417
|
+
nmolecules = len(molecules)
|
|
2418
|
+
# TODO: Performance improvements should let us un-restrict this test
|
|
2419
|
+
for i in range(nmolecules):
|
|
2420
|
+
for j in range(i, min(i + 3, nmolecules)):
|
|
2421
|
+
assert (molecules[i] == molecules[j]) == (i == j)
|
|
2422
|
+
|
|
2423
|
+
@requires_pkg("openmm")
|
|
2424
|
+
def test_add_conformers(self):
|
|
2425
|
+
"""Test addition of conformers to a molecule"""
|
|
2426
|
+
from openmm import unit as openmm_unit
|
|
2427
|
+
|
|
2428
|
+
# Define a methane molecule
|
|
2429
|
+
molecule = Molecule()
|
|
2430
|
+
molecule.name = "methane"
|
|
2431
|
+
C = molecule.add_atom(6, 0, False)
|
|
2432
|
+
H1 = molecule.add_atom(1, 0, False)
|
|
2433
|
+
H2 = molecule.add_atom(1, 0, False)
|
|
2434
|
+
H3 = molecule.add_atom(1, 0, False)
|
|
2435
|
+
H4 = molecule.add_atom(1, 0, False)
|
|
2436
|
+
molecule.add_bond(C, H1, 1, False)
|
|
2437
|
+
molecule.add_bond(C, H2, 1, False)
|
|
2438
|
+
molecule.add_bond(C, H3, 1, False)
|
|
2439
|
+
molecule.add_bond(C, H4, 1, False)
|
|
2440
|
+
|
|
2441
|
+
assert molecule.n_conformers == 0
|
|
2442
|
+
# Add a conformer that should work
|
|
2443
|
+
conf1 = unit.Quantity(
|
|
2444
|
+
np.array(
|
|
2445
|
+
[
|
|
2446
|
+
[1.0, 2.0, 3.0],
|
|
2447
|
+
[4.0, 5.0, 6.0],
|
|
2448
|
+
[7.0, 8.0, 9.0],
|
|
2449
|
+
[10.0, 11.0, 12.0],
|
|
2450
|
+
[13.0, 14.0, 15],
|
|
2451
|
+
]
|
|
2452
|
+
),
|
|
2453
|
+
unit.angstrom,
|
|
2454
|
+
)
|
|
2455
|
+
molecule.add_conformer(conf1)
|
|
2456
|
+
assert molecule.n_conformers == 1
|
|
2457
|
+
|
|
2458
|
+
conf2 = unit.Quantity(
|
|
2459
|
+
np.array(
|
|
2460
|
+
[
|
|
2461
|
+
[101.0, 102.0, 103.0],
|
|
2462
|
+
[104.0, 105.0, 106.0],
|
|
2463
|
+
[107.0, 108.0, 109.0],
|
|
2464
|
+
[110.0, 111.0, 112.0],
|
|
2465
|
+
[113.0, 114.0, 115],
|
|
2466
|
+
]
|
|
2467
|
+
),
|
|
2468
|
+
unit.angstrom,
|
|
2469
|
+
)
|
|
2470
|
+
molecule.add_conformer(conf2)
|
|
2471
|
+
assert molecule.n_conformers == 2
|
|
2472
|
+
|
|
2473
|
+
conf_too_few_atoms = unit.Quantity(
|
|
2474
|
+
np.array(
|
|
2475
|
+
[
|
|
2476
|
+
[101.0, 102.0, 103.0],
|
|
2477
|
+
[104.0, 105.0, 106.0],
|
|
2478
|
+
[107.0, 108.0, 109.0],
|
|
2479
|
+
[110.0, 111.0, 112.0],
|
|
2480
|
+
]
|
|
2481
|
+
),
|
|
2482
|
+
unit.angstrom,
|
|
2483
|
+
)
|
|
2484
|
+
with pytest.raises(InvalidConformerError):
|
|
2485
|
+
molecule.add_conformer(conf_too_few_atoms)
|
|
2486
|
+
|
|
2487
|
+
# Add a conformer with too many coordinates
|
|
2488
|
+
conf_too_many_atoms = unit.Quantity(
|
|
2489
|
+
np.array(
|
|
2490
|
+
[
|
|
2491
|
+
[101.0, 102.0, 103.0],
|
|
2492
|
+
[104.0, 105.0, 106.0],
|
|
2493
|
+
[107.0, 108.0, 109.0],
|
|
2494
|
+
[110.0, 111.0, 112.0],
|
|
2495
|
+
[113.0, 114.0, 115.0],
|
|
2496
|
+
[116.0, 117.0, 118.0],
|
|
2497
|
+
]
|
|
2498
|
+
),
|
|
2499
|
+
unit.angstrom,
|
|
2500
|
+
)
|
|
2501
|
+
with pytest.raises(InvalidConformerError):
|
|
2502
|
+
molecule.add_conformer(conf_too_many_atoms)
|
|
2503
|
+
|
|
2504
|
+
# Add a conformer with no coordinates
|
|
2505
|
+
conf_no_coordinates = unit.Quantity(np.array([]), unit.angstrom)
|
|
2506
|
+
with pytest.raises(InvalidConformerError):
|
|
2507
|
+
molecule.add_conformer(conf_no_coordinates)
|
|
2508
|
+
|
|
2509
|
+
# Add a conforer with units of nanometers
|
|
2510
|
+
conf3 = unit.Quantity(
|
|
2511
|
+
np.array(
|
|
2512
|
+
[
|
|
2513
|
+
[1.0, 2.0, 3.0],
|
|
2514
|
+
[4.0, 5.0, 6.0],
|
|
2515
|
+
[7.0, 8.0, 9.0],
|
|
2516
|
+
[10.0, 11.0, 12.0],
|
|
2517
|
+
[13.0, 14.0, 15],
|
|
2518
|
+
]
|
|
2519
|
+
),
|
|
2520
|
+
unit.nanometer,
|
|
2521
|
+
)
|
|
2522
|
+
molecule.add_conformer(conf3)
|
|
2523
|
+
assert molecule.n_conformers == 3
|
|
2524
|
+
assert molecule.conformers[2][0][0] == 10.0 * unit.angstrom
|
|
2525
|
+
|
|
2526
|
+
conf_nonsense_units = unit.Quantity(
|
|
2527
|
+
np.array(
|
|
2528
|
+
[
|
|
2529
|
+
[1.0, 2.0, 3.0],
|
|
2530
|
+
[4.0, 5.0, 6.0],
|
|
2531
|
+
[7.0, 8.0, 9.0],
|
|
2532
|
+
[10.0, 11.0, 12.0],
|
|
2533
|
+
[13.0, 14.0, 15],
|
|
2534
|
+
]
|
|
2535
|
+
),
|
|
2536
|
+
unit.joule,
|
|
2537
|
+
)
|
|
2538
|
+
with pytest.raises(IncompatibleUnitError):
|
|
2539
|
+
molecule.add_conformer(conf_nonsense_units)
|
|
2540
|
+
|
|
2541
|
+
conf_openmm_units = openmm_unit.Quantity(
|
|
2542
|
+
np.array(
|
|
2543
|
+
[
|
|
2544
|
+
[1.0, 2.0, 3.0],
|
|
2545
|
+
[4.0, 5.0, 6.0],
|
|
2546
|
+
[7.0, 8.0, 9.0],
|
|
2547
|
+
[10.0, 11.0, 12.0],
|
|
2548
|
+
[13.0, 14.0, 15],
|
|
2549
|
+
]
|
|
2550
|
+
),
|
|
2551
|
+
openmm_unit.angstrom,
|
|
2552
|
+
)
|
|
2553
|
+
molecule.add_conformer(conf_openmm_units)
|
|
2554
|
+
|
|
2555
|
+
assert molecule.conformers[-1][0][0].m_as(unit.angstrom) == 1.0
|
|
2556
|
+
assert molecule.conformers[-1][-1][-1].m_as(unit.angstrom) == 15.0
|
|
2557
|
+
|
|
2558
|
+
# Add a conformer with no units
|
|
2559
|
+
conf_unitless = np.array(
|
|
2560
|
+
[
|
|
2561
|
+
[1.0, 2.0, 3.0],
|
|
2562
|
+
[4.0, 5.0, 6.0],
|
|
2563
|
+
[7.0, 8.0, 9.0],
|
|
2564
|
+
[10.0, 11.0, 12.0],
|
|
2565
|
+
[13.0, 14.0, 15],
|
|
2566
|
+
]
|
|
2567
|
+
)
|
|
2568
|
+
with pytest.raises(IncompatibleUnitError):
|
|
2569
|
+
molecule.add_conformer(conf_unitless)
|
|
2570
|
+
|
|
2571
|
+
def test_clear_conformers(self):
|
|
2572
|
+
# simpler molecules don't always like to have many (> 1) conformers
|
|
2573
|
+
# https://greglandrum.github.io/rdkit-blog/posts/2023-02-04-working-with-conformers.html
|
|
2574
|
+
molecule = Molecule.from_smiles("CCCCCCNCNCNCCCCN")
|
|
2575
|
+
molecule.generate_conformers(n_conformers=10)
|
|
2576
|
+
|
|
2577
|
+
assert molecule.n_conformers > 0
|
|
2578
|
+
|
|
2579
|
+
molecule.clear_conformers()
|
|
2580
|
+
|
|
2581
|
+
assert molecule.n_conformers == 0
|
|
2582
|
+
|
|
2583
|
+
def test_clear_conformers_none(self):
|
|
2584
|
+
"""
|
|
2585
|
+
Ensure nothing weird happens when calling clear_conformers() on a molecule that already has no conformers.
|
|
2586
|
+
"""
|
|
2587
|
+
molecule = create_ethanol()
|
|
2588
|
+
|
|
2589
|
+
assert molecule.n_conformers == 0
|
|
2590
|
+
|
|
2591
|
+
molecule.clear_conformers()
|
|
2592
|
+
|
|
2593
|
+
assert molecule.n_conformers == 0
|
|
2594
|
+
|
|
2595
|
+
@pytest.mark.parametrize("molecule", mini_drug_bank())
|
|
2596
|
+
def test_add_atoms_and_bonds(self, molecule):
|
|
2597
|
+
"""Test the creation of a molecule from the addition of atoms and bonds"""
|
|
2598
|
+
molecule_copy = Molecule()
|
|
2599
|
+
for atom in molecule.atoms:
|
|
2600
|
+
molecule_copy.add_atom(
|
|
2601
|
+
atom.atomic_number,
|
|
2602
|
+
atom.formal_charge,
|
|
2603
|
+
atom.is_aromatic,
|
|
2604
|
+
stereochemistry=atom.stereochemistry,
|
|
2605
|
+
)
|
|
2606
|
+
for bond in molecule.bonds:
|
|
2607
|
+
molecule_copy.add_bond(
|
|
2608
|
+
bond.atom1_index,
|
|
2609
|
+
bond.atom2_index,
|
|
2610
|
+
bond.bond_order,
|
|
2611
|
+
bond.is_aromatic,
|
|
2612
|
+
stereochemistry=bond.stereochemistry,
|
|
2613
|
+
fractional_bond_order=bond.fractional_bond_order,
|
|
2614
|
+
)
|
|
2615
|
+
# Try to add the final bond twice, which should raise an Exception
|
|
2616
|
+
with pytest.raises(BondExistsError):
|
|
2617
|
+
molecule_copy.add_bond(
|
|
2618
|
+
bond.atom1_index,
|
|
2619
|
+
bond.atom2_index,
|
|
2620
|
+
bond.bond_order,
|
|
2621
|
+
bond.is_aromatic,
|
|
2622
|
+
stereochemistry=bond.stereochemistry,
|
|
2623
|
+
fractional_bond_order=bond.fractional_bond_order,
|
|
2624
|
+
)
|
|
2625
|
+
|
|
2626
|
+
assert molecule == molecule_copy
|
|
2627
|
+
|
|
2628
|
+
@requires_openeye
|
|
2629
|
+
def test_chemical_environment_matches_OE(self):
|
|
2630
|
+
"""Test chemical environment matches"""
|
|
2631
|
+
# TODO: Move this to test_toolkits, test all available toolkits
|
|
2632
|
+
# Create chiral molecule
|
|
2633
|
+
toolkit_wrapper = OpenEyeToolkitWrapper()
|
|
2634
|
+
molecule = Molecule()
|
|
2635
|
+
atom_C = molecule.add_atom(6, 0, False, stereochemistry="R", name="C")
|
|
2636
|
+
atom_H = molecule.add_atom(1, 0, False, name="H")
|
|
2637
|
+
atom_Cl = molecule.add_atom(17, 0, False, name="Cl")
|
|
2638
|
+
atom_Br = molecule.add_atom(35, 0, False, name="Br")
|
|
2639
|
+
atom_F = molecule.add_atom(9, 0, False, name="F")
|
|
2640
|
+
molecule.add_bond(atom_C, atom_H, 1, False)
|
|
2641
|
+
molecule.add_bond(atom_C, atom_Cl, 1, False)
|
|
2642
|
+
molecule.add_bond(atom_C, atom_Br, 1, False)
|
|
2643
|
+
molecule.add_bond(atom_C, atom_F, 1, False)
|
|
2644
|
+
# Test known cases
|
|
2645
|
+
matches = molecule.chemical_environment_matches("[#6:1]", toolkit_registry=toolkit_wrapper)
|
|
2646
|
+
assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned
|
|
2647
|
+
assert len(matches[0]) == 1 # it should have one tagged atom
|
|
2648
|
+
assert set(matches[0]) == set([atom_C])
|
|
2649
|
+
matches = molecule.chemical_environment_matches("[#6:1]~[#1:2]", toolkit_registry=toolkit_wrapper)
|
|
2650
|
+
assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned
|
|
2651
|
+
assert len(matches[0]) == 2 # it should have two tagged atoms
|
|
2652
|
+
assert set(matches[0]) == set([atom_C, atom_H])
|
|
2653
|
+
matches = molecule.chemical_environment_matches("[Cl:1]-[C:2]-[H:3]", toolkit_registry=toolkit_wrapper)
|
|
2654
|
+
assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned
|
|
2655
|
+
assert len(matches[0]) == 3 # it should have three tagged atoms
|
|
2656
|
+
assert set(matches[0]) == set([atom_Cl, atom_C, atom_H])
|
|
2657
|
+
matches = molecule.chemical_environment_matches("[#6:1]~[*:2]", toolkit_registry=toolkit_wrapper)
|
|
2658
|
+
assert len(matches) == 4 # there should be four matches
|
|
2659
|
+
for match in matches:
|
|
2660
|
+
assert len(match) == 2 # each match should have two tagged atoms
|
|
2661
|
+
# Test searching for stereo-specific SMARTS
|
|
2662
|
+
matches = molecule.chemical_environment_matches(
|
|
2663
|
+
"[#6@:1](-[F:2])(-[Cl])(-[Br])(-[H])", toolkit_registry=toolkit_wrapper
|
|
2664
|
+
)
|
|
2665
|
+
assert len(matches) == 1 # there should be one match
|
|
2666
|
+
for match in matches:
|
|
2667
|
+
assert len(match) == 2 # each match should have two tagged atoms
|
|
2668
|
+
matches = molecule.chemical_environment_matches(
|
|
2669
|
+
"[#6@@:1](-[F:2])(-[Cl])(-[Br])(-[H])", toolkit_registry=toolkit_wrapper
|
|
2670
|
+
)
|
|
2671
|
+
assert len(matches) == 0 # this is the wrong stereochemistry, so there shouldn't be any matches
|
|
2672
|
+
|
|
2673
|
+
# TODO: Test forgive undef amide enol stereo
|
|
2674
|
+
# TODO: test forgive undef phospho linker stereo
|
|
2675
|
+
# TODO: test forgive undef C=NH stereo
|
|
2676
|
+
# TODO: test forgive undef phospho stereo
|
|
2677
|
+
# Potentially better OE stereo check: OEFlipper — Toolkits - - Python
|
|
2678
|
+
# https: // docs.eyesopen.com / toolkits / python / omegatk / OEConfGenFunctions / OEFlipper.html
|
|
2679
|
+
|
|
2680
|
+
@requires_rdkit
|
|
2681
|
+
def test_chemical_environment_matches_RDKit(self):
|
|
2682
|
+
"""Test chemical environment matches"""
|
|
2683
|
+
# Create chiral molecule
|
|
2684
|
+
toolkit_wrapper = RDKitToolkitWrapper()
|
|
2685
|
+
molecule = Molecule()
|
|
2686
|
+
atom_C = molecule.add_atom(6, 0, False, stereochemistry="R", name="C")
|
|
2687
|
+
atom_H = molecule.add_atom(1, 0, False, name="H")
|
|
2688
|
+
atom_Cl = molecule.add_atom(17, 0, False, name="Cl")
|
|
2689
|
+
atom_Br = molecule.add_atom(35, 0, False, name="Br")
|
|
2690
|
+
atom_F = molecule.add_atom(9, 0, False, name="F")
|
|
2691
|
+
molecule.add_bond(atom_C, atom_H, 1, False)
|
|
2692
|
+
molecule.add_bond(atom_C, atom_Cl, 1, False)
|
|
2693
|
+
molecule.add_bond(atom_C, atom_Br, 1, False)
|
|
2694
|
+
molecule.add_bond(atom_C, atom_F, 1, False)
|
|
2695
|
+
# Test known cases
|
|
2696
|
+
matches = molecule.chemical_environment_matches("[#6:1]", toolkit_registry=toolkit_wrapper)
|
|
2697
|
+
assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned
|
|
2698
|
+
assert len(matches[0]) == 1 # it should have one tagged atom
|
|
2699
|
+
assert set(matches[0]) == set([atom_C])
|
|
2700
|
+
matches = molecule.chemical_environment_matches("[#6:1]~[#1:2]", toolkit_registry=toolkit_wrapper)
|
|
2701
|
+
assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned
|
|
2702
|
+
assert len(matches[0]) == 2 # it should have two tagged atoms
|
|
2703
|
+
assert set(matches[0]) == set([atom_C, atom_H])
|
|
2704
|
+
matches = molecule.chemical_environment_matches("[Cl:1]-[C:2]-[H:3]", toolkit_registry=toolkit_wrapper)
|
|
2705
|
+
assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned
|
|
2706
|
+
assert len(matches[0]) == 3 # it should have three tagged atoms
|
|
2707
|
+
assert set(matches[0]) == set([atom_Cl, atom_C, atom_H])
|
|
2708
|
+
matches = molecule.chemical_environment_matches("[#6:1]~[*:2]", toolkit_registry=toolkit_wrapper)
|
|
2709
|
+
assert len(matches) == 4 # there should be four matches
|
|
2710
|
+
for match in matches:
|
|
2711
|
+
assert len(match) == 2 # each match should have two tagged atoms
|
|
2712
|
+
# Test searching for stereo-specific SMARTS
|
|
2713
|
+
matches = molecule.chemical_environment_matches(
|
|
2714
|
+
"[#6@:1](-[F:2])(-[Cl])(-[Br])(-[H])", toolkit_registry=toolkit_wrapper
|
|
2715
|
+
)
|
|
2716
|
+
assert len(matches) == 1 # there should be one match
|
|
2717
|
+
for match in matches:
|
|
2718
|
+
assert len(match) == 2 # each match should have two tagged atoms
|
|
2719
|
+
matches = molecule.chemical_environment_matches(
|
|
2720
|
+
"[#6@@:1](-[F:2])(-[Cl])(-[Br])(-[H])", toolkit_registry=toolkit_wrapper
|
|
2721
|
+
)
|
|
2722
|
+
assert len(matches) == 0 # this is the wrong stereochemistry, so there shouldn't be any matches
|
|
2723
|
+
|
|
2724
|
+
@requires_rdkit
|
|
2725
|
+
@requires_openeye
|
|
2726
|
+
@pytest.mark.slow
|
|
2727
|
+
@pytest.mark.parametrize(
|
|
2728
|
+
("toolkit", "method"),
|
|
2729
|
+
[
|
|
2730
|
+
("openeye", "mmff94"),
|
|
2731
|
+
("openeye", "am1bcc"),
|
|
2732
|
+
("openeye", "am1-mulliken"),
|
|
2733
|
+
("openeye", "gasteiger"),
|
|
2734
|
+
("openeye", "am1bccnosymspt"),
|
|
2735
|
+
("openeye", "am1elf10"),
|
|
2736
|
+
("openeye", "am1bccelf10"),
|
|
2737
|
+
("ambertools", "am1bcc"),
|
|
2738
|
+
("ambertools", "gasteiger"),
|
|
2739
|
+
("ambertools", "am1-mulliken"),
|
|
2740
|
+
("rdkit", "gasteiger"),
|
|
2741
|
+
],
|
|
2742
|
+
)
|
|
2743
|
+
def test_assign_partial_charges(self, toolkit, method):
|
|
2744
|
+
"""Test computation/retrieval of partial charges"""
|
|
2745
|
+
# TODO: Test only one molecule for speed?
|
|
2746
|
+
# TODO: Do we need to deepcopy each molecule, or is setUp called separately for each test method?
|
|
2747
|
+
# Do not modify original molecules.
|
|
2748
|
+
# molecules = copy.deepcopy(mini_drug_bank())
|
|
2749
|
+
# In principle, testing for charge assignment over a wide set of molecules is important, but
|
|
2750
|
+
# I think that's covered in test_toolkits.py. Here, we should only be concerned with testing the
|
|
2751
|
+
# Molecule API, and therefore a single molecule should be sufficient
|
|
2752
|
+
molecule = Molecule.from_smiles("CN1C=NC2=C1C(=O)N(C(=O)N2C)C")
|
|
2753
|
+
|
|
2754
|
+
_TOOLKITS = {
|
|
2755
|
+
"openeye": OpenEyeToolkitWrapper,
|
|
2756
|
+
"ambertools": AmberToolsToolkitWrapper,
|
|
2757
|
+
"rdkit": RDKitToolkitWrapper,
|
|
2758
|
+
}
|
|
2759
|
+
|
|
2760
|
+
toolkit_registry = ToolkitRegistry(toolkit_precedence=[_TOOLKITS[toolkit]])
|
|
2761
|
+
|
|
2762
|
+
molecule.assign_partial_charges(
|
|
2763
|
+
partial_charge_method=method,
|
|
2764
|
+
toolkit_registry=toolkit_registry,
|
|
2765
|
+
)
|
|
2766
|
+
initial_charges = molecule._partial_charges
|
|
2767
|
+
|
|
2768
|
+
# Make sure everything isn't 0s
|
|
2769
|
+
assert (abs(initial_charges.m_as(unit.elementary_charge)) > 0.01).any()
|
|
2770
|
+
# Check total charge
|
|
2771
|
+
charges_sum_unitless = initial_charges.sum().m_as(unit.elementary_charge)
|
|
2772
|
+
total_charge_unitless = molecule.total_charge.m_as(unit.elementary_charge)
|
|
2773
|
+
|
|
2774
|
+
np.testing.assert_allclose(charges_sum_unitless, total_charge_unitless, atol=0.002)
|
|
2775
|
+
|
|
2776
|
+
# Call should be faster second time due to caching
|
|
2777
|
+
# TODO: Implement caching
|
|
2778
|
+
molecule.assign_partial_charges(partial_charge_method=method, toolkit_registry=toolkit_registry)
|
|
2779
|
+
recomputed_charges = molecule._partial_charges
|
|
2780
|
+
np.testing.assert_allclose(initial_charges, recomputed_charges, atol=0.002)
|
|
2781
|
+
|
|
2782
|
+
def test_partial_charges_setter_type_conversion(self):
|
|
2783
|
+
molecule = Molecule.from_smiles("C")
|
|
2784
|
+
int_charges = np.zeros(molecule.n_atoms, dtype=int)
|
|
2785
|
+
molecule.partial_charges = int_charges * unit.elementary_charge
|
|
2786
|
+
assert molecule.partial_charges.dtype == float
|
|
2787
|
+
|
|
2788
|
+
@pytest.mark.parametrize(
|
|
2789
|
+
"value, error",
|
|
2790
|
+
[
|
|
2791
|
+
(3, IncompatibleTypeError),
|
|
2792
|
+
(np.zeros(5), IncompatibleTypeError),
|
|
2793
|
+
(np.zeros(2), IncompatibleShapeError),
|
|
2794
|
+
(np.zeros(2) * unit.elementary_charge, IncompatibleShapeError),
|
|
2795
|
+
(np.zeros(5) * unit.angstrom, IncompatibleUnitError),
|
|
2796
|
+
(Mock(shape=(5,), unit=None), IncompatibleUnitError),
|
|
2797
|
+
],
|
|
2798
|
+
)
|
|
2799
|
+
def test_partial_charges_setter_errors(self, value, error):
|
|
2800
|
+
molecule = Molecule.from_smiles("C")
|
|
2801
|
+
with pytest.raises(error):
|
|
2802
|
+
molecule.partial_charges = value
|
|
2803
|
+
|
|
2804
|
+
@requires_pkg("openmm")
|
|
2805
|
+
def test_partial_charges_set_openmm_units(self):
|
|
2806
|
+
import openmm.unit
|
|
2807
|
+
|
|
2808
|
+
molecule = Molecule.from_smiles("C")
|
|
2809
|
+
molecule.partial_charges = np.zeros(5) * openmm.unit.elementary_charge
|
|
2810
|
+
assert molecule.partial_charges.units == unit.elementary_charge
|
|
2811
|
+
with pytest.raises(IncompatibleUnitError):
|
|
2812
|
+
molecule.partial_charges = np.zeros(5) * openmm.unit.angstrom
|
|
2813
|
+
|
|
2814
|
+
@pytest.mark.parametrize("toolkit_wrapper", [OpenEyeToolkitWrapper, RDKitToolkitWrapper])
|
|
2815
|
+
@pytest.mark.parametrize("use_registry", [True, False])
|
|
2816
|
+
def test_apply_elf_conformer_selection(self, toolkit_wrapper, use_registry):
|
|
2817
|
+
"""Test applying the ELF10 method."""
|
|
2818
|
+
|
|
2819
|
+
if toolkit_wrapper == OpenEyeToolkitWrapper:
|
|
2820
|
+
pytest.importorskip("openeye")
|
|
2821
|
+
elif toolkit_wrapper == RDKitToolkitWrapper:
|
|
2822
|
+
pytest.importorskip("rdkit")
|
|
2823
|
+
|
|
2824
|
+
if use_registry:
|
|
2825
|
+
toolkit = toolkit_wrapper()
|
|
2826
|
+
else:
|
|
2827
|
+
toolkit = ToolkitRegistry(toolkit_precedence=[toolkit_wrapper])
|
|
2828
|
+
|
|
2829
|
+
molecule = Molecule.from_file(
|
|
2830
|
+
get_data_file_path(os.path.join("molecules", "z_3_hydroxy_propenal.sdf")),
|
|
2831
|
+
"SDF",
|
|
2832
|
+
)
|
|
2833
|
+
|
|
2834
|
+
initial_conformers = [
|
|
2835
|
+
# Add a conformer with an internal H-bond.
|
|
2836
|
+
unit.Quantity(
|
|
2837
|
+
np.array(
|
|
2838
|
+
[
|
|
2839
|
+
[0.5477, 0.3297, -0.0621],
|
|
2840
|
+
[-0.1168, -0.7881, 0.2329],
|
|
2841
|
+
[-1.4803, -0.8771, 0.1667],
|
|
2842
|
+
[-0.2158, 1.5206, -0.4772],
|
|
2843
|
+
[-1.4382, 1.5111, -0.5580],
|
|
2844
|
+
[1.6274, 0.3962, -0.0089],
|
|
2845
|
+
[0.3388, -1.7170, 0.5467],
|
|
2846
|
+
[-1.8612, -0.0347, -0.1160],
|
|
2847
|
+
[0.3747, 2.4222, -0.7115],
|
|
2848
|
+
]
|
|
2849
|
+
),
|
|
2850
|
+
unit.angstrom,
|
|
2851
|
+
),
|
|
2852
|
+
# Add a conformer without an internal H-bond.
|
|
2853
|
+
unit.Quantity(
|
|
2854
|
+
np.array(
|
|
2855
|
+
[
|
|
2856
|
+
[0.5477, 0.3297, -0.0621],
|
|
2857
|
+
[-0.1168, -0.7881, 0.2329],
|
|
2858
|
+
[-1.4803, -0.8771, 0.1667],
|
|
2859
|
+
[-0.2158, 1.5206, -0.4772],
|
|
2860
|
+
[0.3353, 2.5772, -0.7614],
|
|
2861
|
+
[1.6274, 0.3962, -0.0089],
|
|
2862
|
+
[0.3388, -1.7170, 0.5467],
|
|
2863
|
+
[-1.7743, -1.7634, 0.4166],
|
|
2864
|
+
[-1.3122, 1.4082, -0.5180],
|
|
2865
|
+
]
|
|
2866
|
+
),
|
|
2867
|
+
unit.angstrom,
|
|
2868
|
+
),
|
|
2869
|
+
]
|
|
2870
|
+
|
|
2871
|
+
molecule._conformers = [*initial_conformers]
|
|
2872
|
+
|
|
2873
|
+
# Apply ELF10
|
|
2874
|
+
molecule.apply_elf_conformer_selection(toolkit_registry=toolkit)
|
|
2875
|
+
elf10_conformers = molecule.conformers
|
|
2876
|
+
|
|
2877
|
+
assert len(elf10_conformers) == 1
|
|
2878
|
+
|
|
2879
|
+
assert np.allclose(
|
|
2880
|
+
elf10_conformers[0].m_as(unit.angstrom),
|
|
2881
|
+
initial_conformers[1].m_as(unit.angstrom),
|
|
2882
|
+
)
|
|
2883
|
+
|
|
2884
|
+
def test_make_carboxylic_acids_cis(self):
|
|
2885
|
+
# First, check that we get exactly the right coords for cis and trans methanoic acid
|
|
2886
|
+
offmol = Molecule.from_mapped_smiles("[H:1][C:2](=[O:3])[O:4][H:5]")
|
|
2887
|
+
# cis methanoic (formic) acid
|
|
2888
|
+
cis_xyz = unit.Quantity(
|
|
2889
|
+
np.array(
|
|
2890
|
+
[
|
|
2891
|
+
[-1.0, -1.0, 0.0], # HC
|
|
2892
|
+
[+0.0, +0.0, 0.0], # C
|
|
2893
|
+
[-1.0, +1.0, 0.0], # =O
|
|
2894
|
+
[+1.0, +0.0, 0.0], # -O
|
|
2895
|
+
[+2.0, +1.0, 0.0], # HO
|
|
2896
|
+
]
|
|
2897
|
+
),
|
|
2898
|
+
unit.angstrom,
|
|
2899
|
+
)
|
|
2900
|
+
trans_xyz = unit.Quantity(
|
|
2901
|
+
np.array(
|
|
2902
|
+
[
|
|
2903
|
+
[-1.0, -1.0, 0.0], # HC
|
|
2904
|
+
[+0.0, +0.0, 0.0], # C
|
|
2905
|
+
[-1.0, +1.0, 0.0], # =O
|
|
2906
|
+
[+1.0, +0.0, 0.0], # -O
|
|
2907
|
+
[+2.0, -1.0, 0.0], # HO
|
|
2908
|
+
]
|
|
2909
|
+
),
|
|
2910
|
+
unit.angstrom,
|
|
2911
|
+
)
|
|
2912
|
+
|
|
2913
|
+
offmol._conformers = [trans_xyz, cis_xyz]
|
|
2914
|
+
expected_conformers = [cis_xyz, cis_xyz]
|
|
2915
|
+
|
|
2916
|
+
offmol._make_carboxylic_acids_cis()
|
|
2917
|
+
|
|
2918
|
+
for index in [0, 1]:
|
|
2919
|
+
np.testing.assert_allclose(
|
|
2920
|
+
offmol.conformers[index].m_as(unit.angstrom),
|
|
2921
|
+
expected_conformers[index].m_as(unit.angstrom),
|
|
2922
|
+
atol=1e-5,
|
|
2923
|
+
)
|
|
2924
|
+
|
|
2925
|
+
@requires_openeye
|
|
2926
|
+
def test_assign_fractional_bond_orders(self):
|
|
2927
|
+
"""Test assignment of fractional bond orders"""
|
|
2928
|
+
# TODO: Test only one molecule for speed?
|
|
2929
|
+
# TODO: Do we need to deepcopy each molecule, or is setUp called separately for each test method?
|
|
2930
|
+
|
|
2931
|
+
# Do not modify the original molecules.
|
|
2932
|
+
molecules = copy.deepcopy(mini_drug_bank())
|
|
2933
|
+
|
|
2934
|
+
toolkits_to_bondorder_method = {(OpenEyeToolkitWrapper,): ["am1-wiberg", "pm3-wiberg"]}
|
|
2935
|
+
# Don't test AmberTools here since it takes too long
|
|
2936
|
+
# (AmberToolsToolkitWrapper, RDKitToolkitWrapper):['am1-wiberg']}
|
|
2937
|
+
for toolkits in list(toolkits_to_bondorder_method.keys()):
|
|
2938
|
+
toolkit_registry = ToolkitRegistry(toolkit_precedence=toolkits)
|
|
2939
|
+
for bond_order_model in toolkits_to_bondorder_method[toolkits]:
|
|
2940
|
+
for molecule in molecules[:5]: # Just test first five molecules for speed
|
|
2941
|
+
molecule.generate_conformers(toolkit_registry=toolkit_registry)
|
|
2942
|
+
molecule.assign_fractional_bond_orders(
|
|
2943
|
+
bond_order_model=bond_order_model,
|
|
2944
|
+
toolkit_registry=toolkit_registry,
|
|
2945
|
+
use_conformers=molecule.conformers,
|
|
2946
|
+
)
|
|
2947
|
+
# fbo1 = [bond.fractional_bond_order for bond in molecule.bonds]
|
|
2948
|
+
# TODO: Now that the assign_fractional_bond_orders function takes more kwargs,
|
|
2949
|
+
# how can we meaningfully cache its results?
|
|
2950
|
+
# # Call should be faster the second time due to caching
|
|
2951
|
+
# molecule.assign_fractional_bond_orders(bond_order_model=bond_order_model,
|
|
2952
|
+
# toolkit_registry=toolkit_registry)
|
|
2953
|
+
# fbo2 = [bond.fractional_bond_order for bond in molecule.bonds]
|
|
2954
|
+
# np.testing.assert_allclose(fbo1, fbo2, atol=1.e-4)
|
|
2955
|
+
|
|
2956
|
+
@requires_ambertools
|
|
2957
|
+
@requires_openeye
|
|
2958
|
+
@pytest.mark.slow
|
|
2959
|
+
@pytest.mark.parametrize("model", ["AM1-Wiberg", "am1-wiberg"])
|
|
2960
|
+
@pytest.mark.parametrize("toolkit", [OpenEyeToolkitWrapper, AmberToolsToolkitWrapper])
|
|
2961
|
+
def test_bond_order_method_passing(self, model, toolkit):
|
|
2962
|
+
"""Test that different calls to Molecule.assign_fractional_bond_orders do not
|
|
2963
|
+
produce unexpected errors, but do not asses validity of results"""
|
|
2964
|
+
mol = Molecule.from_smiles("CCO")
|
|
2965
|
+
|
|
2966
|
+
# Test that default model works
|
|
2967
|
+
mol.assign_fractional_bond_orders()
|
|
2968
|
+
|
|
2969
|
+
mol.assign_fractional_bond_orders(
|
|
2970
|
+
bond_order_model=model,
|
|
2971
|
+
)
|
|
2972
|
+
|
|
2973
|
+
mol.assign_fractional_bond_orders(
|
|
2974
|
+
bond_order_model=model,
|
|
2975
|
+
toolkit_registry=toolkit(),
|
|
2976
|
+
)
|
|
2977
|
+
|
|
2978
|
+
mol.assign_fractional_bond_orders(
|
|
2979
|
+
bond_order_model=model,
|
|
2980
|
+
toolkit_registry=ToolkitRegistry([toolkit()]),
|
|
2981
|
+
)
|
|
2982
|
+
|
|
2983
|
+
def test_get_bond_between(self):
|
|
2984
|
+
"""Test Molecule.get_bond_between"""
|
|
2985
|
+
mol = Molecule.from_smiles("C#C")
|
|
2986
|
+
|
|
2987
|
+
# Dynamically get atoms in case from_smiles produces different atom order
|
|
2988
|
+
hydrogens = [a for a in mol.atoms if a.atomic_number == 1]
|
|
2989
|
+
carbons = [a for a in mol.atoms if a.atomic_number == 6]
|
|
2990
|
+
|
|
2991
|
+
bond_from_atoms = mol.get_bond_between(carbons[0], carbons[1])
|
|
2992
|
+
bond_from_idx = mol.get_bond_between(carbons[0].molecule_atom_index, carbons[1].molecule_atom_index)
|
|
2993
|
+
assert bond_from_idx == bond_from_atoms
|
|
2994
|
+
|
|
2995
|
+
with pytest.raises(NotBondedError):
|
|
2996
|
+
mol.get_bond_between(hydrogens[0], hydrogens[1])
|
|
2997
|
+
|
|
2998
|
+
def test_is_in_ring(self):
|
|
2999
|
+
"""
|
|
3000
|
+
Test basic behavior of Atom.is_in_ring and Bond.is_in_ring API.
|
|
3001
|
+
More extensive behavior testing is done in test_toolkits.py
|
|
3002
|
+
"""
|
|
3003
|
+
molecule = Molecule.from_smiles("c1ccccc1")
|
|
3004
|
+
|
|
3005
|
+
for atom in molecule.atoms:
|
|
3006
|
+
if atom.atomic_number == 6:
|
|
3007
|
+
assert atom.is_in_ring()
|
|
3008
|
+
|
|
3009
|
+
for bond in molecule.bonds:
|
|
3010
|
+
if 1 in (bond.atom1.atomic_number, bond.atom2.atomic_number):
|
|
3011
|
+
continue
|
|
3012
|
+
assert bond.is_in_ring()
|
|
3013
|
+
|
|
3014
|
+
def test_deepcopy_not_shallow(self):
|
|
3015
|
+
"""
|
|
3016
|
+
Check that deep copies don't re-use any mutable data structures
|
|
3017
|
+
|
|
3018
|
+
Mutable attributes set in ``Molecule._initialize_from_dict()`` and their
|
|
3019
|
+
mutable values should be tested here. Other attributes are either not
|
|
3020
|
+
copied by ``deepcopy``, or else are immutable, so copies may be the same
|
|
3021
|
+
object (eg, ``deepcopy(None)``).
|
|
3022
|
+
"""
|
|
3023
|
+
mol_source = create_ethanol()
|
|
3024
|
+
mol_source.generate_conformers()
|
|
3025
|
+
|
|
3026
|
+
mol_copy = copy.deepcopy(mol_source)
|
|
3027
|
+
|
|
3028
|
+
assert mol_source._conformers is not mol_copy._conformers
|
|
3029
|
+
assert all(a is not b for a, b in zip(mol_source._conformers, mol_copy._conformers))
|
|
3030
|
+
|
|
3031
|
+
assert mol_source._atoms is not mol_copy._atoms
|
|
3032
|
+
assert all(a is not b for a, b in zip(mol_source._atoms, mol_copy._atoms))
|
|
3033
|
+
|
|
3034
|
+
assert mol_source._bonds is not mol_copy._bonds
|
|
3035
|
+
assert all(a is not b for a, b in zip(mol_source._bonds, mol_copy._bonds))
|
|
3036
|
+
|
|
3037
|
+
assert mol_source._hierarchy_schemes is not mol_copy._hierarchy_schemes
|
|
3038
|
+
assert all(a is not b for a, b in zip(mol_source._hierarchy_schemes, mol_copy._hierarchy_schemes))
|
|
3039
|
+
|
|
3040
|
+
assert mol_source._properties is not mol_copy._properties
|
|
3041
|
+
assert mol_source._partial_charges is not mol_copy._partial_charges
|
|
3042
|
+
|
|
3043
|
+
|
|
3044
|
+
@requires_pkg("qcportal")
|
|
3045
|
+
class TestQCArchiveInterface:
|
|
3046
|
+
def test_to_qcschema(self):
|
|
3047
|
+
"""Test the ability to make and validate qcschema with extras"""
|
|
3048
|
+
# the molecule has no coordinates so this should fail
|
|
3049
|
+
ethanol = Molecule.from_smiles("CCO")
|
|
3050
|
+
with pytest.raises(InvalidConformerError):
|
|
3051
|
+
qcschema = ethanol.to_qcschema()
|
|
3052
|
+
|
|
3053
|
+
# now remake the molecule from the sdf
|
|
3054
|
+
ethanol = Molecule.from_file(get_data_file_path("molecules/ethanol.sdf"))
|
|
3055
|
+
# make sure that requests to missing conformers are caught
|
|
3056
|
+
with pytest.raises(InvalidConformerError):
|
|
3057
|
+
qcschema = ethanol.to_qcschema(conformer=1)
|
|
3058
|
+
# now make a valid qcschema and check its properties
|
|
3059
|
+
qcschema = ethanol.to_qcschema(extras={"test_tag": "test"})
|
|
3060
|
+
# make sure the properties match
|
|
3061
|
+
charge = 0
|
|
3062
|
+
connectivity = [
|
|
3063
|
+
(0, 1, 1.0),
|
|
3064
|
+
(0, 4, 1.0),
|
|
3065
|
+
(0, 5, 1.0),
|
|
3066
|
+
(0, 6, 1.0),
|
|
3067
|
+
(1, 2, 1.0),
|
|
3068
|
+
(1, 7, 1.0),
|
|
3069
|
+
(1, 8, 1.0),
|
|
3070
|
+
(2, 3, 1.0),
|
|
3071
|
+
]
|
|
3072
|
+
symbols = ["C", "C", "O", "H", "H", "H", "H", "H", "H"]
|
|
3073
|
+
|
|
3074
|
+
def assert_check():
|
|
3075
|
+
assert charge == qcschema.molecular_charge
|
|
3076
|
+
assert connectivity == qcschema.connectivity
|
|
3077
|
+
assert symbols == qcschema.symbols.tolist()
|
|
3078
|
+
assert qcschema.geometry.all() == ethanol.conformers[0].m_as(unit.bohr).all()
|
|
3079
|
+
|
|
3080
|
+
assert_check()
|
|
3081
|
+
assert qcschema.extras["test_tag"] == "test"
|
|
3082
|
+
assert qcschema.extras["canonical_isomeric_explicit_hydrogen_mapped_smiles"] == ethanol.to_smiles(mapped=True)
|
|
3083
|
+
# # now run again with no extras passed, only cmiles entry will be present with fix-720
|
|
3084
|
+
qcschema = ethanol.to_qcschema()
|
|
3085
|
+
assert_check()
|
|
3086
|
+
assert qcschema.extras["canonical_isomeric_explicit_hydrogen_mapped_smiles"] == ethanol.to_smiles(mapped=True)
|
|
3087
|
+
|
|
3088
|
+
def test_to_qcschema_no_connections(self):
|
|
3089
|
+
mol = Molecule.from_mapped_smiles("[Br-:1].[K+:2]")
|
|
3090
|
+
mol.add_conformer(
|
|
3091
|
+
unit.Quantity(
|
|
3092
|
+
np.array([[0.188518, 0.015684, 0.001562], [0.148794, 0.21268, 0.11992]]),
|
|
3093
|
+
unit.nanometers,
|
|
3094
|
+
)
|
|
3095
|
+
)
|
|
3096
|
+
qcschema = mol.to_qcschema()
|
|
3097
|
+
assert qcschema.connectivity is None
|
|
3098
|
+
|
|
3099
|
+
def test_from_qcschema_no_client(self):
|
|
3100
|
+
"""Test the ability to make molecules from QCArchive record instances and dicts"""
|
|
3101
|
+
|
|
3102
|
+
# As the method can take a record instance or a dict with JSON encoding test both
|
|
3103
|
+
# test incomplete dict
|
|
3104
|
+
example_dict = {"name": "CH4"}
|
|
3105
|
+
with pytest.raises(InvalidQCInputError):
|
|
3106
|
+
Molecule.from_qcschema(example_dict)
|
|
3107
|
+
|
|
3108
|
+
# test an object that is not a record
|
|
3109
|
+
wrong_object = "CH4"
|
|
3110
|
+
# This actualy raises InvalidQCInputError, but this check ensures that it's a subclass of AttributeError
|
|
3111
|
+
with pytest.raises(AttributeError):
|
|
3112
|
+
Molecule.from_qcschema(wrong_object)
|
|
3113
|
+
|
|
3114
|
+
client_examples = [
|
|
3115
|
+
{
|
|
3116
|
+
"dataset": "torsiondrive",
|
|
3117
|
+
"name": "Fragment Stability Benchmark",
|
|
3118
|
+
"index": "CC(=O)Nc1cc2c(cc1OC)nc[n:4][c:3]2[NH:2][c:1]3ccc(c(c3)Cl)F",
|
|
3119
|
+
},
|
|
3120
|
+
{
|
|
3121
|
+
"dataset": "torsiondrive",
|
|
3122
|
+
"name": "OpenFF Fragmenter Phenyl Benchmark",
|
|
3123
|
+
"index": "c1c[ch:1][c:2](cc1)[c:3](=[o:4])o",
|
|
3124
|
+
},
|
|
3125
|
+
{
|
|
3126
|
+
"dataset": "torsiondrive",
|
|
3127
|
+
"name": "OpenFF Full TorsionDrive Benchmark 1",
|
|
3128
|
+
"index": "0",
|
|
3129
|
+
},
|
|
3130
|
+
{
|
|
3131
|
+
"dataset": "torsiondrive",
|
|
3132
|
+
"name": "OpenFF Group1 Torsions",
|
|
3133
|
+
"index": "c1c[ch:1][c:2](cc1)[ch2:3][c:4]2ccccc2",
|
|
3134
|
+
},
|
|
3135
|
+
{
|
|
3136
|
+
"dataset": "optimization",
|
|
3137
|
+
"name": "Kinase Inhibitors: WBO Distributions",
|
|
3138
|
+
"index": "cc1ccc(cc1nc2nccc(n2)c3cccnc3)nc(=o)c4ccc(cc4)cn5ccn(cc5)c-0",
|
|
3139
|
+
},
|
|
3140
|
+
{
|
|
3141
|
+
"dataset": "optimization",
|
|
3142
|
+
"name": "SMIRNOFF Coverage Set 1",
|
|
3143
|
+
"index": "coc(o)oc-0",
|
|
3144
|
+
},
|
|
3145
|
+
{
|
|
3146
|
+
"dataset": "gridoptimization",
|
|
3147
|
+
"name": "OpenFF Trivalent Nitrogen Set 1",
|
|
3148
|
+
"index": "b1(c2c(ccs2)-c3ccsc3n1)c4c(c(c(c(c4f)f)f)f)f",
|
|
3149
|
+
},
|
|
3150
|
+
{
|
|
3151
|
+
"dataset": "gridoptimization",
|
|
3152
|
+
"name": "OpenFF Trivalent Nitrogen Set 1",
|
|
3153
|
+
"index": "C(#N)N",
|
|
3154
|
+
},
|
|
3155
|
+
{
|
|
3156
|
+
"dataset": "singlepoint",
|
|
3157
|
+
"name": "OpenFF multi-Br ESP Fragment Conformers v1.1",
|
|
3158
|
+
"index": "c1c(cc(cc1Br)Br)Br",
|
|
3159
|
+
},
|
|
3160
|
+
]
|
|
3161
|
+
|
|
3162
|
+
@pytest.mark.flaky(reruns=5)
|
|
3163
|
+
@pytest.mark.parametrize("input_data", client_examples)
|
|
3164
|
+
def test_from_qcschema_with_client(self, input_data):
|
|
3165
|
+
"""For each of the examples try and make a offmol using the instance and dict and check they match"""
|
|
3166
|
+
import qcportal
|
|
3167
|
+
from qcportal import PortalRequestError
|
|
3168
|
+
|
|
3169
|
+
client = qcportal.PortalClient("https://api.qcarchive.molssi.org:443")
|
|
3170
|
+
|
|
3171
|
+
ds = client.get_dataset(input_data["dataset"], input_data["name"])
|
|
3172
|
+
try:
|
|
3173
|
+
entry = ds.get_entry(input_data["index"])
|
|
3174
|
+
except PortalRequestError:
|
|
3175
|
+
entry = ds.get_entry(input_data["index"].lower())
|
|
3176
|
+
# now make the molecule from the record instance with and without the geometry
|
|
3177
|
+
mol_from_dict = Molecule.from_qcschema(entry)
|
|
3178
|
+
# make the molecule again with the geometries attached
|
|
3179
|
+
mol_from_instance = Molecule.from_qcschema(entry) # , client)
|
|
3180
|
+
if hasattr(entry, "initial_molecules"):
|
|
3181
|
+
assert mol_from_instance.n_conformers == len(entry.initial_molecules)
|
|
3182
|
+
else:
|
|
3183
|
+
# opt records have one initial molecule
|
|
3184
|
+
assert mol_from_instance.n_conformers == 1
|
|
3185
|
+
|
|
3186
|
+
# now make a molecule from the smiles and make sure they are isomorphic
|
|
3187
|
+
mol_from_smiles = Molecule.from_smiles(entry.attributes["canonical_explicit_hydrogen_smiles"], True)
|
|
3188
|
+
|
|
3189
|
+
assert mol_from_dict.is_isomorphic_with(mol_from_smiles) is True
|
|
3190
|
+
|
|
3191
|
+
def test_qcschema_round_trip(self):
|
|
3192
|
+
"""Test making a molecule from qcschema then converting back
|
|
3193
|
+
Checking whether qca_mol and mol created from/to qcschema are the same or not"""
|
|
3194
|
+
|
|
3195
|
+
# get a molecule qcschema
|
|
3196
|
+
import qcportal
|
|
3197
|
+
|
|
3198
|
+
client = qcportal.PortalClient("https://api.qcarchive.molssi.org:443")
|
|
3199
|
+
|
|
3200
|
+
ds = client.get_dataset("optimization", "SMIRNOFF Coverage Set 1")
|
|
3201
|
+
|
|
3202
|
+
# grab an entry from the optimization data set
|
|
3203
|
+
entry = ds.get_entry("coc(o)oc-0")
|
|
3204
|
+
|
|
3205
|
+
# now make the molecule from the record instance with the geometry
|
|
3206
|
+
mol = Molecule.from_qcschema(entry) # , client)
|
|
3207
|
+
|
|
3208
|
+
# find and grab the initial molecule record
|
|
3209
|
+
iterator = client.query_molecules(molecule_hash=entry.initial_molecule.identifiers.molecule_hash)
|
|
3210
|
+
|
|
3211
|
+
qca_mol = next(iter(iterator))
|
|
3212
|
+
|
|
3213
|
+
# mow make sure the majority of the qcschema attributes are the same
|
|
3214
|
+
# note we can not compare the full dict due to qcelemental differences
|
|
3215
|
+
qcschema = mol.to_qcschema()
|
|
3216
|
+
assert qcschema.atom_labels.tolist() == qca_mol.atom_labels.tolist()
|
|
3217
|
+
assert qcschema.symbols.tolist() == qca_mol.symbols.tolist()
|
|
3218
|
+
# due to conversion using different programs there is a slight difference here
|
|
3219
|
+
assert qcschema.geometry.flatten().tolist() == pytest.approx(qca_mol.geometry.flatten().tolist(), rel=1.0e-5)
|
|
3220
|
+
assert qcschema.connectivity == qca_mol.connectivity
|
|
3221
|
+
assert qcschema.atomic_numbers.tolist() == qca_mol.atomic_numbers.tolist()
|
|
3222
|
+
assert qcschema.fragment_charges == qca_mol.fragment_charges
|
|
3223
|
+
assert qcschema.fragment_multiplicities == qca_mol.fragment_multiplicities
|
|
3224
|
+
assert qcschema.fragments[0].tolist() == qca_mol.fragments[0].tolist()
|
|
3225
|
+
assert qcschema.mass_numbers.tolist() == qca_mol.mass_numbers.tolist()
|
|
3226
|
+
assert qcschema.name == qca_mol.name
|
|
3227
|
+
assert qcschema.masses.all() == qca_mol.masses.all()
|
|
3228
|
+
assert qcschema.molecular_charge == qca_mol.molecular_charge
|
|
3229
|
+
assert qcschema.molecular_multiplicity == qca_mol.molecular_multiplicity
|
|
3230
|
+
assert qcschema.real.all() == qca_mol.real.all()
|
|
3231
|
+
|
|
3232
|
+
def test_qcschema_round_trip_from_to_from(self):
|
|
3233
|
+
"""Test making a molecule from qca record using from_qcschema,
|
|
3234
|
+
then converting back to qcschema using to_qcschema,
|
|
3235
|
+
and then reading that again using from_qcschema"""
|
|
3236
|
+
|
|
3237
|
+
# get a molecule qcschema
|
|
3238
|
+
import qcportal
|
|
3239
|
+
|
|
3240
|
+
client = qcportal.PortalClient("https://api.qcarchive.molssi.org:443")
|
|
3241
|
+
|
|
3242
|
+
ds = client.get_dataset("torsiondrive", "OpenFF-benchmark-ligand-fragments-v1.0")
|
|
3243
|
+
# grab an entry from the torsiondrive data set
|
|
3244
|
+
entry = ds.get_entry(
|
|
3245
|
+
"[H]c1[c:1]([c:2](c(c(c1[H])N([H])C(=O)[H])[H])[C:3]2=C(C(=C([S:4]2)[H])OC([H])([H])[H])Br)[H]".lower()
|
|
3246
|
+
)
|
|
3247
|
+
# now make the molecule from the record instance with the geometry
|
|
3248
|
+
mol_qca_record = Molecule.from_qcschema(entry) # , client)
|
|
3249
|
+
off_qcschema = mol_qca_record.to_qcschema()
|
|
3250
|
+
mol_using_from_off_qcschema = Molecule.from_qcschema(off_qcschema)
|
|
3251
|
+
assert_molecule_is_equal(
|
|
3252
|
+
mol_qca_record,
|
|
3253
|
+
mol_using_from_off_qcschema,
|
|
3254
|
+
"Molecule roundtrip to/from_qcschema failed",
|
|
3255
|
+
)
|
|
3256
|
+
|
|
3257
|
+
def test_qcschema_round_trip_raise_error(self):
|
|
3258
|
+
"""Test making a molecule from qcschema,
|
|
3259
|
+
reaching inner except block where everything fails"""
|
|
3260
|
+
import qcportal
|
|
3261
|
+
|
|
3262
|
+
client = qcportal.PortalClient("https://api.qcarchive.molssi.org:443")
|
|
3263
|
+
|
|
3264
|
+
ds = client.get_dataset("torsiondrive", "OpenFF-benchmark-ligand-fragments-v1.0")
|
|
3265
|
+
# grab an entry from the torsiondrive data set
|
|
3266
|
+
entry = ds.get_entry(
|
|
3267
|
+
"[H]c1[c:1]([c:2](c(c(c1[H])N([H])C(=O)[H])[H])[C:3]2=C(C(=C([S:4]2)[H])OC([H])([H])[H])Br)[H]".lower()
|
|
3268
|
+
)
|
|
3269
|
+
del entry.attributes["canonical_isomeric_explicit_hydrogen_mapped_smiles"]
|
|
3270
|
+
# now make the molecule from the record instance with the geometry
|
|
3271
|
+
# We can handle this now - The code recurses down to the mols and gets their CMILESes.
|
|
3272
|
+
# with pytest.raises(KeyError):
|
|
3273
|
+
# Molecule.from_qcschema(entry) #, client)
|
|
3274
|
+
|
|
3275
|
+
@pytest.mark.flaky(reruns=10)
|
|
3276
|
+
def test_qcschema_molecule_record_round_trip_from_to_from(self):
|
|
3277
|
+
"""Test making a molecule from qca record using from_qcschema,
|
|
3278
|
+
then converting back to qcschema using to_qcschema,
|
|
3279
|
+
and then reading that again using from_qcschema"""
|
|
3280
|
+
|
|
3281
|
+
# get a molecule qcschema
|
|
3282
|
+
import qcportal
|
|
3283
|
+
|
|
3284
|
+
client = qcportal.PortalClient("https://api.qcarchive.molssi.org:443")
|
|
3285
|
+
|
|
3286
|
+
record = [*client.query_molecules(molecular_formula="C16H20N3O5")][-1]
|
|
3287
|
+
|
|
3288
|
+
# now make the molecule from the record instance with the geometry
|
|
3289
|
+
mol_qca_record = Molecule.from_qcschema(record) # , client)
|
|
3290
|
+
off_qcschema = mol_qca_record.to_qcschema()
|
|
3291
|
+
mol_using_from_off_qcschema = Molecule.from_qcschema(off_qcschema)
|
|
3292
|
+
|
|
3293
|
+
assert_molecule_is_equal(
|
|
3294
|
+
mol_qca_record,
|
|
3295
|
+
mol_using_from_off_qcschema,
|
|
3296
|
+
"Molecule roundtrip to/from_qcschema failed",
|
|
3297
|
+
)
|
|
3298
|
+
|
|
3299
|
+
mol_dict = off_qcschema.dict()
|
|
3300
|
+
del mol_dict["extras"]["canonical_isomeric_explicit_hydrogen_mapped_smiles"]
|
|
3301
|
+
del mol_dict["identifiers"]["canonical_isomeric_explicit_hydrogen_mapped_smiles"]
|
|
3302
|
+
with pytest.raises(MissingCMILESError):
|
|
3303
|
+
Molecule.from_qcschema(mol_dict)
|
|
3304
|
+
|
|
3305
|
+
|
|
3306
|
+
class TestGetAvailableChargeMethods:
|
|
3307
|
+
def test_with_global_toolkit_registry(self):
|
|
3308
|
+
"""Test the get_available_charge_methods method"""
|
|
3309
|
+
from openff.toolkit.utils.toolkits import OPENEYE_AVAILABLE
|
|
3310
|
+
|
|
3311
|
+
available_methods = create_ethanol().get_available_charge_methods()
|
|
3312
|
+
|
|
3313
|
+
for method in available_methods:
|
|
3314
|
+
assert isinstance(method, str)
|
|
3315
|
+
|
|
3316
|
+
# The toolkit should always have (basic) AM1-BCC available
|
|
3317
|
+
assert "am1bcc" in available_methods
|
|
3318
|
+
|
|
3319
|
+
# These are provided by both RDKit and OpenEye
|
|
3320
|
+
assert "mmff94" in available_methods
|
|
3321
|
+
assert "gasteiger" in available_methods
|
|
3322
|
+
|
|
3323
|
+
assert ("am1elf10" in available_methods) == OPENEYE_AVAILABLE
|
|
3324
|
+
assert ("am1bccelf10" in available_methods) == OPENEYE_AVAILABLE
|
|
3325
|
+
|
|
3326
|
+
def test_with_explicit_registry(self):
|
|
3327
|
+
assert "zeros" in create_ethanol().get_available_charge_methods(
|
|
3328
|
+
toolkit_registry=ToolkitRegistry([BuiltInToolkitWrapper])
|
|
3329
|
+
)
|
|
3330
|
+
|
|
3331
|
+
def test_with_explicit_wrapper(self):
|
|
3332
|
+
assert "zeros" in create_ethanol().get_available_charge_methods(toolkit_registry=BuiltInToolkitWrapper())
|
|
3333
|
+
|
|
3334
|
+
def test_error_with_type(self):
|
|
3335
|
+
from openff.toolkit.utils.exceptions import InvalidToolkitRegistryError
|
|
3336
|
+
|
|
3337
|
+
with pytest.raises(InvalidToolkitRegistryError):
|
|
3338
|
+
create_ethanol().get_available_charge_methods(toolkit_registry=BuiltInToolkitWrapper)
|
|
3339
|
+
|
|
3340
|
+
|
|
3341
|
+
class TestMoleculeVisualization:
|
|
3342
|
+
@requires_pkg("IPython")
|
|
3343
|
+
@requires_rdkit
|
|
3344
|
+
def test_visualize_rdkit(self):
|
|
3345
|
+
"""
|
|
3346
|
+
Test that the visualize method returns an expected object when using RDKit to generate a 2-D representation
|
|
3347
|
+
"""
|
|
3348
|
+
import IPython
|
|
3349
|
+
|
|
3350
|
+
mol = Molecule().from_smiles("CCO")
|
|
3351
|
+
|
|
3352
|
+
assert isinstance(mol.visualize(backend="rdkit"), IPython.core.display.SVG)
|
|
3353
|
+
|
|
3354
|
+
@pytest.mark.skipif(
|
|
3355
|
+
has_pkg("rdkit"),
|
|
3356
|
+
reason="Test requires that RDKit is not installed",
|
|
3357
|
+
)
|
|
3358
|
+
def test_visualize_fallback(self):
|
|
3359
|
+
"""Test falling back from RDKit to OpenEye if RDKit is specified but not installed"""
|
|
3360
|
+
mol = Molecule().from_smiles("CCO")
|
|
3361
|
+
with pytest.warns(UserWarning):
|
|
3362
|
+
mol.visualize(backend="rdkit")
|
|
3363
|
+
|
|
3364
|
+
@requires_pkg("nglview")
|
|
3365
|
+
def test_visualize_nglview(self):
|
|
3366
|
+
import nglview
|
|
3367
|
+
|
|
3368
|
+
mol = Molecule().from_smiles("CCO")
|
|
3369
|
+
|
|
3370
|
+
with pytest.raises(MissingConformersError):
|
|
3371
|
+
mol.visualize(backend="nglview")
|
|
3372
|
+
|
|
3373
|
+
mol.generate_conformers()
|
|
3374
|
+
|
|
3375
|
+
assert isinstance(mol.visualize(backend="nglview"), nglview.NGLWidget)
|
|
3376
|
+
|
|
3377
|
+
with pytest.warns(UserWarning, match="ignored.*nglview.*111"):
|
|
3378
|
+
mol.visualize(backend="nglview", width=111)
|
|
3379
|
+
with pytest.warns(UserWarning, match="ignored.*nglview.*222"):
|
|
3380
|
+
mol.visualize(backend="nglview", height=222)
|
|
3381
|
+
|
|
3382
|
+
@requires_pkg("IPython")
|
|
3383
|
+
@requires_openeye
|
|
3384
|
+
def test_visualize_openeye(self):
|
|
3385
|
+
"""
|
|
3386
|
+
Test that the visualize method returns an expected object when using OpenEye to generate a 2-D representation.
|
|
3387
|
+
"""
|
|
3388
|
+
import IPython
|
|
3389
|
+
|
|
3390
|
+
mol = Molecule().from_smiles("CCO")
|
|
3391
|
+
|
|
3392
|
+
assert isinstance(mol.visualize(backend="openeye"), IPython.core.display.Image)
|
|
3393
|
+
|
|
3394
|
+
@pytest.mark.skipif(
|
|
3395
|
+
has_pkg("nglview"),
|
|
3396
|
+
reason="Test requires that NGLview is not installed",
|
|
3397
|
+
)
|
|
3398
|
+
def test_ipython_repr_no_nglview(self):
|
|
3399
|
+
"""Test that the default Molecule repr does not break when nglview is not installed"""
|
|
3400
|
+
molecule = Molecule().from_smiles("CCO")
|
|
3401
|
+
molecule._ipython_display_()
|
|
3402
|
+
|
|
3403
|
+
def test_get_coordinates(self):
|
|
3404
|
+
from openff.toolkit.utils._viz import MoleculeNGLViewTrajectory
|
|
3405
|
+
|
|
3406
|
+
molecule = Molecule.from_smiles("C1CC2=C3C(=CC=C2)C(=CN3C1)[C@H]4[C@@H](C(=O)NC4=O)C5=CNC6=CC=CC=C65")
|
|
3407
|
+
molecule.generate_conformers(n_conformers=3)
|
|
3408
|
+
|
|
3409
|
+
trajectory = MoleculeNGLViewTrajectory(molecule)
|
|
3410
|
+
|
|
3411
|
+
# _OFFTrajectoryNGLView.get_coordinates returns a unitless array implicitly in Angstroms
|
|
3412
|
+
np.testing.assert_allclose(trajectory.get_coordinates(), molecule.conformers[0].m)
|
|
3413
|
+
np.testing.assert_allclose(trajectory.get_coordinates(0), molecule.conformers[0].m)
|
|
3414
|
+
np.testing.assert_allclose(trajectory.get_coordinates(1), molecule.conformers[1].m)
|
|
3415
|
+
|
|
3416
|
+
with pytest.raises(IndexError, match="out of range"):
|
|
3417
|
+
trajectory.get_coordinates(100000)
|
|
3418
|
+
|
|
3419
|
+
|
|
3420
|
+
@pytest.mark.parametrize("strict_chirality", (True, False))
|
|
3421
|
+
class TestMoleculeResiduePerception:
|
|
3422
|
+
"""Test residue perception of Molecule class."""
|
|
3423
|
+
|
|
3424
|
+
def test_perceive_residues_natoms_nterminal_alanine(self, strict_chirality):
|
|
3425
|
+
"""Test number of matches atoms in residue perception with NTerminal form of Alanine."""
|
|
3426
|
+
offmol = Molecule.from_file(get_data_file_path("proteins/NTerminal_ALA.sdf"))
|
|
3427
|
+
# Perceive residue substructures
|
|
3428
|
+
offmol.perceive_residues(strict_chirality=strict_chirality)
|
|
3429
|
+
counter = 0 # matched atom counter
|
|
3430
|
+
for atom in offmol.atoms:
|
|
3431
|
+
if atom.metadata:
|
|
3432
|
+
counter += 1
|
|
3433
|
+
assert counter == offmol.n_atoms
|
|
3434
|
+
|
|
3435
|
+
def test_perceive_residues_natoms_cterminal_alanine(self, strict_chirality):
|
|
3436
|
+
"""Test number of matches atoms in residue perception with CTerminal form of Alanine."""
|
|
3437
|
+
offmol = Molecule.from_file(get_data_file_path("proteins/CTerminal_ALA.sdf"))
|
|
3438
|
+
# Perceive residue substructures
|
|
3439
|
+
offmol.perceive_residues(strict_chirality=strict_chirality)
|
|
3440
|
+
counter = 0 # matched atom counter
|
|
3441
|
+
for atom in offmol.atoms:
|
|
3442
|
+
if atom.metadata:
|
|
3443
|
+
counter += 1
|
|
3444
|
+
assert counter == offmol.n_atoms
|
|
3445
|
+
|
|
3446
|
+
def test_perceive_residues_natoms_mainchain_alanine(self, strict_chirality):
|
|
3447
|
+
"""Test number of matches atoms in residue perception with MainChain form of Alanine."""
|
|
3448
|
+
offmol = Molecule.from_file(get_data_file_path("proteins/MainChain_ALA.sdf"))
|
|
3449
|
+
# Perceive residue substructures
|
|
3450
|
+
offmol.perceive_residues(strict_chirality=strict_chirality)
|
|
3451
|
+
counter = 0 # matched atom counter
|
|
3452
|
+
for atom in offmol.atoms:
|
|
3453
|
+
if atom.metadata:
|
|
3454
|
+
counter += 1
|
|
3455
|
+
assert counter == offmol.n_atoms
|
|
3456
|
+
|
|
3457
|
+
def test_perceive_residues_natoms_mainchain_glutamic_acid(self, strict_chirality):
|
|
3458
|
+
"""Test number of matches atoms in residue perception with MainChain form of Glutamic acid."""
|
|
3459
|
+
offmol = Molecule.from_file(get_data_file_path("proteins/MainChain_GLU.sdf"))
|
|
3460
|
+
# Perceive residue substructures
|
|
3461
|
+
offmol.perceive_residues(strict_chirality=strict_chirality)
|
|
3462
|
+
counter = 0 # matched atom counter
|
|
3463
|
+
for atom in offmol.atoms:
|
|
3464
|
+
if atom.metadata:
|
|
3465
|
+
counter += 1
|
|
3466
|
+
assert counter == offmol.n_atoms
|
|
3467
|
+
|
|
3468
|
+
def test_perceive_residues_natoms_mainchain_charged_glutamic_acid(self, strict_chirality):
|
|
3469
|
+
"""Test number of matches atoms in residue perception with MainChain form of charged
|
|
3470
|
+
Glutamic acid."""
|
|
3471
|
+
offmol = Molecule.from_file(get_data_file_path("proteins/MainChain_GLH.sdf"))
|
|
3472
|
+
# Perceive residue substructures
|
|
3473
|
+
offmol.perceive_residues(strict_chirality=strict_chirality)
|
|
3474
|
+
counter = 0 # matched atom counter
|
|
3475
|
+
for atom in offmol.atoms:
|
|
3476
|
+
if atom.metadata:
|
|
3477
|
+
counter += 1
|
|
3478
|
+
assert counter == offmol.n_atoms
|
|
3479
|
+
|
|
3480
|
+
def test_perceive_residues_natoms_mainchain_arginine(self, strict_chirality):
|
|
3481
|
+
"""Test number of matches atoms in residue perception with MainChain form of Alanine."""
|
|
3482
|
+
offmol = Molecule.from_file(get_data_file_path("proteins/MainChain_ARG.sdf"))
|
|
3483
|
+
# Perceive residue substructures
|
|
3484
|
+
offmol.perceive_residues(strict_chirality=strict_chirality)
|
|
3485
|
+
counter = 0 # matched atom counter
|
|
3486
|
+
for atom in offmol.atoms:
|
|
3487
|
+
if atom.metadata:
|
|
3488
|
+
counter += 1
|
|
3489
|
+
assert counter == offmol.n_atoms
|
|
3490
|
+
|
|
3491
|
+
def test_perceive_residues_natoms_mainchain_histidine(self, strict_chirality):
|
|
3492
|
+
"""Test number of matches atoms in residue perception with MainChain form of protonated
|
|
3493
|
+
state of Histidine."""
|
|
3494
|
+
offmol = Molecule.from_file(get_data_file_path("proteins/MainChain_HIP.sdf"))
|
|
3495
|
+
# Perceive residue substructures
|
|
3496
|
+
offmol.perceive_residues(strict_chirality=strict_chirality)
|
|
3497
|
+
counter = 0 # matched atom counter
|
|
3498
|
+
for atom in offmol.atoms:
|
|
3499
|
+
if atom.metadata:
|
|
3500
|
+
counter += 1
|
|
3501
|
+
assert counter == offmol.n_atoms
|
|
3502
|
+
|
|
3503
|
+
def test_perceive_residues_natoms_cyxteine(self, strict_chirality):
|
|
3504
|
+
"""Test number of atoms matched for residue perception of disulfide bond form
|
|
3505
|
+
of cysteine."""
|
|
3506
|
+
offmol = Molecule.from_file(get_data_file_path("proteins/MainChain_CYX.sdf"))
|
|
3507
|
+
# Perceive residue substructures
|
|
3508
|
+
offmol.perceive_residues(strict_chirality=strict_chirality)
|
|
3509
|
+
counter = 0 # matched atom counter
|
|
3510
|
+
for atom in offmol.atoms:
|
|
3511
|
+
if atom.metadata:
|
|
3512
|
+
counter += 1
|
|
3513
|
+
assert counter == offmol.n_atoms
|
|
3514
|
+
|
|
3515
|
+
def test_perceive_residues_cyclic_peptide_chirality(self, strict_chirality):
|
|
3516
|
+
"""Test residue perception failing in cyclic peptide with different chiralities."""
|
|
3517
|
+
smiles = (
|
|
3518
|
+
"[H]c1c(c(c(c(c1[H])[H])C([H])([H])[C@]2(C(=O)N([C@](C(=O)N([C@@](C(=O)N3[C@@](C(=O)N2[H])"
|
|
3519
|
+
"(C(C(C3([H])[H])([H])[H])([H])[H])[H])([H])C([H])([H])[H])[H])([H])C([H])([H])C4=C(N(c5c4c(c(c(c5[H])"
|
|
3520
|
+
"[H])[H])[H])[H])[H])[H])[H])[H])[H]"
|
|
3521
|
+
)
|
|
3522
|
+
offmol = Molecule.from_smiles(smiles)
|
|
3523
|
+
# perceive residues
|
|
3524
|
+
offmol.perceive_residues(strict_chirality=strict_chirality)
|
|
3525
|
+
counter = 0 # matched atom counter
|
|
3526
|
+
for atom in offmol.atoms:
|
|
3527
|
+
if atom.metadata:
|
|
3528
|
+
counter += 1
|
|
3529
|
+
if strict_chirality:
|
|
3530
|
+
# Make sure it fails if strict_chirality=True
|
|
3531
|
+
with pytest.raises(AssertionError):
|
|
3532
|
+
assert counter == offmol.n_atoms
|
|
3533
|
+
else:
|
|
3534
|
+
assert counter == offmol.n_atoms
|
|
3535
|
+
|
|
3536
|
+
@pytest.mark.slow
|
|
3537
|
+
def test_perceive_residues_natoms_t4(self, strict_chirality):
|
|
3538
|
+
"""Test number of atoms matched for residue perception of free from of
|
|
3539
|
+
T4 lysozyme."""
|
|
3540
|
+
offmol = Molecule.from_file(get_data_file_path("proteins/T4-protein.sdf"))
|
|
3541
|
+
# Perceive residue substructures
|
|
3542
|
+
offmol.perceive_residues(strict_chirality=strict_chirality)
|
|
3543
|
+
counter = 0 # matched atom counter
|
|
3544
|
+
for atom in offmol.atoms:
|
|
3545
|
+
if atom.metadata:
|
|
3546
|
+
counter += 1
|
|
3547
|
+
assert counter == offmol.n_atoms
|
|
3548
|
+
|
|
3549
|
+
def test_perceive_residues_sorting(self, strict_chirality):
|
|
3550
|
+
"""Ensure residues are sorted consecutively when `Molecule.perceive_residues` is used. See issue #1461."""
|
|
3551
|
+
molecule = Molecule.from_file(get_data_file_path("proteins/ace-a10-nme.sdf"))
|
|
3552
|
+
|
|
3553
|
+
molecule.perceive_residues(strict_chirality=strict_chirality)
|
|
3554
|
+
|
|
3555
|
+
for index, residue in enumerate(molecule.residues):
|
|
3556
|
+
found = residue.residue_number
|
|
3557
|
+
expected = str(index + 1)
|
|
3558
|
+
|
|
3559
|
+
assert isinstance(found, str)
|
|
3560
|
+
assert found == expected
|
|
3561
|
+
|
|
3562
|
+
|
|
3563
|
+
class TestMoleculeFromPDB:
|
|
3564
|
+
"""
|
|
3565
|
+
Test creation of cheminformatics-rich openff Molecule from PDB files.
|
|
3566
|
+
"""
|
|
3567
|
+
|
|
3568
|
+
def test_from_pdb_input_types(self):
|
|
3569
|
+
import pathlib
|
|
3570
|
+
|
|
3571
|
+
import openmm.app
|
|
3572
|
+
|
|
3573
|
+
protein_path = get_data_file_path("proteins/ace-ala-nh2.pdb")
|
|
3574
|
+
|
|
3575
|
+
Molecule.from_polymer_pdb(protein_path)
|
|
3576
|
+
|
|
3577
|
+
Molecule.from_polymer_pdb(pathlib.Path(protein_path))
|
|
3578
|
+
|
|
3579
|
+
with open(protein_path) as f:
|
|
3580
|
+
Molecule.from_polymer_pdb(f)
|
|
3581
|
+
|
|
3582
|
+
with pytest.raises(ValueError, match=r"Unexpected type.*PDBFile"):
|
|
3583
|
+
Molecule.from_polymer_pdb(openmm.app.PDBFile(protein_path))
|
|
3584
|
+
|
|
3585
|
+
# TODO: Implement all the tests
|
|
3586
|
+
def test_from_pdb_t4_n_atoms(self):
|
|
3587
|
+
"""Test off Molecule contains expected number of atoms from T4 pdb."""
|
|
3588
|
+
# We expect/know the molecule contains this number of atoms
|
|
3589
|
+
expected_n_atoms = 2634
|
|
3590
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/T4-protein.pdb"))
|
|
3591
|
+
assert offmol.n_atoms == expected_n_atoms
|
|
3592
|
+
|
|
3593
|
+
def test_from_pdb_metadata(self):
|
|
3594
|
+
"""Test that metadata is correctly loaded from PDB."""
|
|
3595
|
+
expected_metadata = (
|
|
3596
|
+
[(" ", "1", " ", "ACE")] * 6
|
|
3597
|
+
+ [(" ", "2", " ", "ALA")] * 10
|
|
3598
|
+
+ [(" ", "2", "X", "ALA")] * 10
|
|
3599
|
+
+ [(" ", "3", " ", "NME")] * 6
|
|
3600
|
+
)
|
|
3601
|
+
|
|
3602
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA_ALA_icodes.pdb"))
|
|
3603
|
+
for atom, metadata_tuple in zip(offmol.atoms, expected_metadata):
|
|
3604
|
+
metadata_dict = {
|
|
3605
|
+
"chain_id": metadata_tuple[0],
|
|
3606
|
+
"residue_number": metadata_tuple[1],
|
|
3607
|
+
"insertion_code": metadata_tuple[2],
|
|
3608
|
+
"residue_name": metadata_tuple[3],
|
|
3609
|
+
}
|
|
3610
|
+
assert atom.metadata == metadata_dict
|
|
3611
|
+
|
|
3612
|
+
def test_molecule_from_pdb_mainchain_ala_dipeptide(self):
|
|
3613
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA.pdb"))
|
|
3614
|
+
assert offmol.n_atoms == 22
|
|
3615
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](C)C(=O)NC")
|
|
3616
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3617
|
+
|
|
3618
|
+
with NamedTemporaryFile(suffix="pdb") as iofile:
|
|
3619
|
+
offmol.to_file(iofile.name, file_format="pdb")
|
|
3620
|
+
offmol2 = Molecule.from_polymer_pdb(iofile.name)
|
|
3621
|
+
assert offmol.is_isomorphic_with(offmol2)
|
|
3622
|
+
assert np.allclose(
|
|
3623
|
+
offmol2.conformers[0].m_as(unit.angstrom),
|
|
3624
|
+
offmol2.conformers[0].m_as(unit.angstrom),
|
|
3625
|
+
atol=0.01,
|
|
3626
|
+
)
|
|
3627
|
+
|
|
3628
|
+
def test_molecule_from_pdb_name(self):
|
|
3629
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA.pdb"))
|
|
3630
|
+
assert offmol.name == ""
|
|
3631
|
+
|
|
3632
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA.pdb"), name="bob")
|
|
3633
|
+
assert offmol.name == "bob"
|
|
3634
|
+
|
|
3635
|
+
def test_molecule_from_pdb_ace_ala_nh2(self):
|
|
3636
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/ace-ala-nh2.pdb"))
|
|
3637
|
+
assert offmol.n_atoms == 19
|
|
3638
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](C)C(=O)N")
|
|
3639
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3640
|
+
|
|
3641
|
+
def test_molecule_from_pdb_mainchain_ala_tripeptide(self):
|
|
3642
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA_ALA.pdb"))
|
|
3643
|
+
assert offmol.n_atoms == 32
|
|
3644
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](C)C(=O)N[C@H](C)C(=O)NC")
|
|
3645
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3646
|
+
|
|
3647
|
+
def test_molecule_from_pdb_cterm_ala_dipeptide(self):
|
|
3648
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/CTerminal_ALA.pdb"))
|
|
3649
|
+
assert offmol.n_atoms == 17
|
|
3650
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](C)C(=O)[O-]")
|
|
3651
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3652
|
+
|
|
3653
|
+
def test_molecule_from_pdb_cterm_ala_tripeptide(self):
|
|
3654
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/CTerminal_ALA_ALA.pdb"))
|
|
3655
|
+
assert offmol.n_atoms == 27
|
|
3656
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](C)C(=O)N[C@H](C)C(=O)[O-]")
|
|
3657
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3658
|
+
|
|
3659
|
+
def test_molecule_from_pdb_nterm_ala_dipeptide(self):
|
|
3660
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/NTerminal_ALA.pdb"))
|
|
3661
|
+
assert offmol.n_atoms == 18
|
|
3662
|
+
expected_mol = Molecule.from_smiles("[N+]([H])([H])([H])[C@H](C)C(=O)NC")
|
|
3663
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3664
|
+
|
|
3665
|
+
def test_molecule_from_pdb_mainchain_arg_dipeptide(self):
|
|
3666
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ARG.pdb"))
|
|
3667
|
+
assert offmol.n_atoms == 36
|
|
3668
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](CCCNC(N)=[N+]([H])[H])C(=O)NC")
|
|
3669
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3670
|
+
|
|
3671
|
+
def test_molecule_from_pdb_cterm_arg_dipeptide(self):
|
|
3672
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/CTerminal_ARG.pdb"))
|
|
3673
|
+
assert offmol.n_atoms == 31
|
|
3674
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](CCCNC(N)=[N+]([H])([H]))C(=O)[O-]")
|
|
3675
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3676
|
+
|
|
3677
|
+
def test_molecule_from_pdb_mainchain_cys_dipeptide(self):
|
|
3678
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_CYS.pdb"))
|
|
3679
|
+
assert offmol.n_atoms == 23
|
|
3680
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](CS)C(=O)NC")
|
|
3681
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3682
|
+
|
|
3683
|
+
def test_molecule_from_pdb_mainchain_cym_dipeptide(self):
|
|
3684
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_CYM.pdb"))
|
|
3685
|
+
assert offmol.n_atoms == 22
|
|
3686
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](C[S-])C(=O)NC")
|
|
3687
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3688
|
+
|
|
3689
|
+
def test_molecule_from_pdb_mainchain_cyx_dipeptide(self):
|
|
3690
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_CYX.pdb"))
|
|
3691
|
+
assert offmol.n_atoms == 44
|
|
3692
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](CSSC[C@H](NC(=O)C)C(=O)NC)C(=O)NC")
|
|
3693
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3694
|
+
|
|
3695
|
+
def test_molecule_from_pdb_mainchain_hid_dipeptide(self):
|
|
3696
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_HID.pdb"))
|
|
3697
|
+
assert offmol.n_atoms == 29
|
|
3698
|
+
assert offmol.total_charge == 0 * unit.elementary_charge
|
|
3699
|
+
assert sum([1 for atom in offmol.atoms if atom.is_aromatic]) == 0
|
|
3700
|
+
assert sum([1 for bond in offmol.bonds if bond.is_aromatic]) == 0
|
|
3701
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](CC1NC=NC=1)C(=O)NC")
|
|
3702
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False, aromatic_matching=False)
|
|
3703
|
+
|
|
3704
|
+
def test_molecule_from_pdb_mainchain_hie_dipeptide(self):
|
|
3705
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_HIE.pdb"))
|
|
3706
|
+
assert offmol.n_atoms == 29
|
|
3707
|
+
assert offmol.total_charge == 0 * unit.elementary_charge
|
|
3708
|
+
assert sum([1 for atom in offmol.atoms if atom.is_aromatic]) == 0
|
|
3709
|
+
assert sum([1 for bond in offmol.bonds if bond.is_aromatic]) == 0
|
|
3710
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](CC1N=C[NH]C=1)C(=O)NC")
|
|
3711
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False, aromatic_matching=False)
|
|
3712
|
+
|
|
3713
|
+
def test_molecule_from_pdb_mainchain_hip_dipeptide(self):
|
|
3714
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_HIP.pdb"))
|
|
3715
|
+
assert offmol.n_atoms == 30
|
|
3716
|
+
assert offmol.total_charge == 1 * unit.elementary_charge
|
|
3717
|
+
assert sum([1 for atom in offmol.atoms if atom.is_aromatic]) == 0
|
|
3718
|
+
assert sum([1 for bond in offmol.bonds if bond.is_aromatic]) == 0
|
|
3719
|
+
|
|
3720
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](CC1[N+]([H])=CNC=1)C(=O)NC")
|
|
3721
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False, aromatic_matching=False)
|
|
3722
|
+
|
|
3723
|
+
def test_molecule_from_pdb_mainchain_trp_dipeptide(self):
|
|
3724
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_TRP.pdb"))
|
|
3725
|
+
assert offmol.n_atoms == 36
|
|
3726
|
+
assert offmol.total_charge == 0 * unit.elementary_charge
|
|
3727
|
+
assert sum([1 for atom in offmol.atoms if atom.is_aromatic]) == 6
|
|
3728
|
+
assert sum([1 for bond in offmol.bonds if bond.is_aromatic]) == 6
|
|
3729
|
+
|
|
3730
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](CC1C2=CC=CC=C2NC=1)C(=O)NC")
|
|
3731
|
+
assert offmol.is_isomorphic_with(
|
|
3732
|
+
expected_mol,
|
|
3733
|
+
atom_stereochemistry_matching=False,
|
|
3734
|
+
aromatic_matching=False,
|
|
3735
|
+
bond_order_matching=False,
|
|
3736
|
+
)
|
|
3737
|
+
|
|
3738
|
+
def test_molecule_from_pdb_cterminal_trp_dipeptide(self):
|
|
3739
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/CTerminal_TRP.pdb"))
|
|
3740
|
+
assert offmol.n_atoms == 31
|
|
3741
|
+
assert offmol.total_charge == -1 * unit.elementary_charge
|
|
3742
|
+
assert sum([1 for atom in offmol.atoms if atom.is_aromatic]) == 6
|
|
3743
|
+
assert sum([1 for bond in offmol.bonds if bond.is_aromatic]) == 6
|
|
3744
|
+
|
|
3745
|
+
expected_mol = Molecule.from_smiles("CC(=O)N[C@H](CC1C2=CC=CC=C2NC=1)C(=O)[O-]")
|
|
3746
|
+
assert offmol.is_isomorphic_with(
|
|
3747
|
+
expected_mol,
|
|
3748
|
+
atom_stereochemistry_matching=False,
|
|
3749
|
+
aromatic_matching=False,
|
|
3750
|
+
bond_order_matching=False,
|
|
3751
|
+
)
|
|
3752
|
+
|
|
3753
|
+
def test_molecule_from_pdb_nterminal_trp_dipeptide(self):
|
|
3754
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/NTerminal_TRP.pdb"))
|
|
3755
|
+
assert offmol.n_atoms == 32
|
|
3756
|
+
assert offmol.total_charge == 1 * unit.elementary_charge
|
|
3757
|
+
assert sum([1 for atom in offmol.atoms if atom.is_aromatic]) == 6
|
|
3758
|
+
assert sum([1 for bond in offmol.bonds if bond.is_aromatic]) == 6
|
|
3759
|
+
|
|
3760
|
+
expected_mol = Molecule.from_smiles("[N+]([H])([H])([H])[C@H](CC1C2=CC=CC=C2NC=1)C(=O)NC")
|
|
3761
|
+
assert offmol.is_isomorphic_with(
|
|
3762
|
+
expected_mol,
|
|
3763
|
+
atom_stereochemistry_matching=False,
|
|
3764
|
+
aromatic_matching=False,
|
|
3765
|
+
bond_order_matching=False,
|
|
3766
|
+
)
|
|
3767
|
+
|
|
3768
|
+
def test_molecule_from_pdb_mainchain_pro_dipeptide(self):
|
|
3769
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_PRO.pdb"))
|
|
3770
|
+
assert offmol.n_atoms == 26
|
|
3771
|
+
assert offmol.total_charge == 0 * unit.elementary_charge
|
|
3772
|
+
expected_mol = Molecule.from_smiles("CC(=O)N1[C@H](CCC1)C(=O)NC")
|
|
3773
|
+
assert offmol.is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
|
|
3774
|
+
|
|
3775
|
+
def test_molecule_from_pdb_neutral_arg_dipeptide(self):
|
|
3776
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/neutral_arginine.pdb"))
|
|
3777
|
+
assert offmol.n_atoms == 26
|
|
3778
|
+
assert offmol.total_charge == 0 * unit.elementary_charge
|
|
3779
|
+
expected_mol = Molecule.from_smiles("[NH3+][C@H](CCCNC(N)(=N))C(=O)[O-]", allow_undefined_stereo=True)
|
|
3780
|
+
assert offmol.is_isomorphic_with(
|
|
3781
|
+
expected_mol,
|
|
3782
|
+
atom_stereochemistry_matching=False,
|
|
3783
|
+
bond_stereochemistry_matching=False,
|
|
3784
|
+
)
|
|
3785
|
+
|
|
3786
|
+
def test_molecule_from_pdb_error_no_hydrogens(self):
|
|
3787
|
+
"""Test that a PDB without hydrogens raises a descriptive error"""
|
|
3788
|
+
with pytest.raises(
|
|
3789
|
+
UnassignedChemistryInPDBError,
|
|
3790
|
+
match=(
|
|
3791
|
+
r"There are no hydrogens in the input\. The OpenFF Toolkit "
|
|
3792
|
+
+ r"requires explicit hydrogens to avoid ambiguities in "
|
|
3793
|
+
+ r"protonation state or bond order\. Try generating hydrogens "
|
|
3794
|
+
+ r"with another package and trying again\."
|
|
3795
|
+
),
|
|
3796
|
+
):
|
|
3797
|
+
Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA_ALA_no_hydrogens.pdb"))
|
|
3798
|
+
|
|
3799
|
+
def test_molecule_from_pdb_error_non_canonical_aa(self):
|
|
3800
|
+
"""Test that a PDB with an NCAA raises a descriptive error"""
|
|
3801
|
+
with pytest.raises(
|
|
3802
|
+
UnassignedChemistryInPDBError,
|
|
3803
|
+
match=(
|
|
3804
|
+
r"The following residue names with unassigned atoms were "
|
|
3805
|
+
+ r"not found in the substructure library. While the OpenFF "
|
|
3806
|
+
+ r"Toolkit identifies residues by matching chemical "
|
|
3807
|
+
+ r"substructures rather than by residue name, it currently "
|
|
3808
|
+
+ r"only supports the 20 'canonical' amino acids\.\n\s*DYE"
|
|
3809
|
+
),
|
|
3810
|
+
):
|
|
3811
|
+
Molecule.from_polymer_pdb(get_data_file_path("proteins/fluoresceine_dyed_helix_capped.pdb"))
|
|
3812
|
+
|
|
3813
|
+
def test_molecule_from_pdb_error_misnamed_hydrogens(self):
|
|
3814
|
+
"""Test that a PDB with two chains raises a clear error"""
|
|
3815
|
+
with pytest.raises(
|
|
3816
|
+
UnassignedChemistryInPDBError,
|
|
3817
|
+
match=(
|
|
3818
|
+
r"Hint: The following residues have the right numbers of the "
|
|
3819
|
+
+ r"right elements to match a substructure with the same name "
|
|
3820
|
+
+ r"as the input residue, but did not match\. This most likely "
|
|
3821
|
+
+ r"suggests that their atom names do not match those in the "
|
|
3822
|
+
+ r"substructure library\. Try renaming misnamed atoms "
|
|
3823
|
+
+ r"according to the PDB Chemical Component Dictionary\.\n"
|
|
3824
|
+
+ r" Input residue ALA#0003 has misnamed atoms H01, H02, H03"
|
|
3825
|
+
),
|
|
3826
|
+
):
|
|
3827
|
+
Molecule.from_polymer_pdb(get_data_file_path("proteins/CTerminal_ALA_ALA_misnamedH.pdb"))
|
|
3828
|
+
|
|
3829
|
+
def test_molecule_from_pdb_error_crystal_waters(self):
|
|
3830
|
+
"""Test that a PDB with two chains raises a clear error"""
|
|
3831
|
+
with pytest.raises(
|
|
3832
|
+
UnassignedChemistryInPDBError,
|
|
3833
|
+
match=(
|
|
3834
|
+
r"Note: 'HOH' is a residue code for water. You may have "
|
|
3835
|
+
+ r"crystallographic waters in your PDB file. Please remove "
|
|
3836
|
+
+ r"these before proceeding, or use Topology.from_pdb\."
|
|
3837
|
+
),
|
|
3838
|
+
):
|
|
3839
|
+
Molecule.from_polymer_pdb(get_data_file_path("proteins/T4_protein_waters.pdb"))
|
|
3840
|
+
|
|
3841
|
+
def test_molecule_from_pdb_error_two_polymers(self):
|
|
3842
|
+
"""Test that a PDB with two capped polymers but no chain IDs raises a clear error"""
|
|
3843
|
+
with pytest.raises(
|
|
3844
|
+
MultipleMoleculesInPDBError,
|
|
3845
|
+
match=(
|
|
3846
|
+
r"This PDB has multiple molecules\. The OpenFF Toolkit "
|
|
3847
|
+
+ r"requires that only one molecule is present in a "
|
|
3848
|
+
+ r"PDB\. Try splitting each molecule into its own PDB "
|
|
3849
|
+
+ r"with another tool, and load any small molecules "
|
|
3850
|
+
+ r"with Molecule\.from_pdb_and_smiles\."
|
|
3851
|
+
),
|
|
3852
|
+
):
|
|
3853
|
+
Molecule.from_polymer_pdb(get_data_file_path("proteins/TwoMol_SER_CYS.pdb"))
|
|
3854
|
+
|
|
3855
|
+
def test_unproc_pdb_4w51_errors(self):
|
|
3856
|
+
"""Test that a file fresh from the PDB gives all the right hints when it fails to load"""
|
|
3857
|
+
with pytest.raises(
|
|
3858
|
+
UnassignedChemistryInPDBError,
|
|
3859
|
+
match=(
|
|
3860
|
+
r"Some bonds or atoms in the input could not be identified\."
|
|
3861
|
+
+ r"\n\n"
|
|
3862
|
+
+ r"Hint: There are no hydrogens in the input\. The OpenFF "
|
|
3863
|
+
+ r"Toolkit requires explicit hydrogens to avoid ambiguities "
|
|
3864
|
+
+ r"in protonation state or bond order\. Try generating "
|
|
3865
|
+
+ r"hydrogens with another package and trying again\."
|
|
3866
|
+
+ r"\n\n"
|
|
3867
|
+
+ r"Hint: The input has multiple chain identifiers\. The OpenFF "
|
|
3868
|
+
+ r"Toolkit Molecule.from_polymer_pdb method only supports "
|
|
3869
|
+
+ r"single-molecule PDB files\. Please use Topology.from\_pdb "
|
|
3870
|
+
+ r"or split the file into individual chains and load each "
|
|
3871
|
+
+ r"separately\.\n\n"
|
|
3872
|
+
+ r"Hint: The following residue names with unassigned atoms "
|
|
3873
|
+
+ r"were not found in the substructure library\. While the "
|
|
3874
|
+
+ r"OpenFF Toolkit identifies residues by matching chemical "
|
|
3875
|
+
+ r"substructures rather than by residue name, it currently "
|
|
3876
|
+
+ r"only supports the 20 'canonical' amino acids\.\n"
|
|
3877
|
+
+ r" EPE\n HOH\n"
|
|
3878
|
+
+ r"Note: 'HOH' is a residue code for water\. You may have "
|
|
3879
|
+
+ r"crystallographic waters in your PDB file\. Please remove "
|
|
3880
|
+
+ r"these before proceeding, or use Topology.from_pdb\."
|
|
3881
|
+
),
|
|
3882
|
+
):
|
|
3883
|
+
Molecule.from_polymer_pdb(get_data_file_path("proteins/T4-protein-unprocessed-4w51.pdb"))
|
|
3884
|
+
|
|
3885
|
+
@pytest.mark.xfail()
|
|
3886
|
+
def test_from_pdb_t4_n_residues(self):
|
|
3887
|
+
"""Test number of residues when creating Molecule from T4 PDB"""
|
|
3888
|
+
expected_n_residues = 164 # noqa
|
|
3889
|
+
raise NotImplementedError
|
|
3890
|
+
|
|
3891
|
+
@pytest.mark.xfail()
|
|
3892
|
+
def test_from_pdb_t4_atom_metadata(self):
|
|
3893
|
+
"""Test to check the metadata from T4 pdb is filled correctly."""
|
|
3894
|
+
raise NotImplementedError
|
|
3895
|
+
|
|
3896
|
+
# TODO: Remove decorator when OpenEye implementation is back online
|
|
3897
|
+
@pytest.mark.slow
|
|
3898
|
+
@requires_rdkit
|
|
3899
|
+
def test_from_t4_to_topology(self):
|
|
3900
|
+
"""Ensure a large protein can be converted into a `Topology`. See #1319."""
|
|
3901
|
+
Molecule.from_polymer_pdb(get_data_file_path("proteins/T4-protein.pdb")).to_topology()
|
|
3902
|
+
|
|
3903
|
+
|
|
3904
|
+
class MyMol(FrozenMolecule):
|
|
3905
|
+
"""
|
|
3906
|
+
Lightweight FrozenMolecule subclass for molecule-subclass tests below
|
|
3907
|
+
"""
|
|
3908
|
+
|
|
3909
|
+
|
|
3910
|
+
class TestMoleculeSubclass:
|
|
3911
|
+
"""
|
|
3912
|
+
Test that the FrozenMolecule class is subclass-able, by ensuring that Molecule.from_X constructors
|
|
3913
|
+
return objects of the correct types
|
|
3914
|
+
"""
|
|
3915
|
+
|
|
3916
|
+
def test_molecule_subclass_from_smiles(self):
|
|
3917
|
+
"""Ensure that the right type of object is returned when running MyMol.from_smiles"""
|
|
3918
|
+
mol = MyMol.from_smiles("CCO")
|
|
3919
|
+
assert isinstance(mol, MyMol)
|
|
3920
|
+
|
|
3921
|
+
def test_molecule_subclass_from_inchi(self):
|
|
3922
|
+
"""Ensure that the right type of object is returned when running MyMol.from_inchi"""
|
|
3923
|
+
mol = MyMol.from_inchi("InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3")
|
|
3924
|
+
assert isinstance(mol, MyMol)
|
|
3925
|
+
|
|
3926
|
+
@requires_openeye
|
|
3927
|
+
def test_molecule_subclass_from_iupac(self):
|
|
3928
|
+
"""Ensure that the right type of object is returned when running MyMol.from_iupac"""
|
|
3929
|
+
mol = MyMol.from_iupac("benzene")
|
|
3930
|
+
assert isinstance(mol, MyMol)
|
|
3931
|
+
|
|
3932
|
+
def test_molecule_subclass_from_file(self):
|
|
3933
|
+
"""Ensure that the right type of object is returned when running MyMol.from_file"""
|
|
3934
|
+
mol = MyMol.from_file(get_data_file_path("molecules/ethanol.sdf"))
|
|
3935
|
+
assert isinstance(mol, MyMol)
|
|
3936
|
+
|
|
3937
|
+
def test_molecule_subclass_from_mapped_smiles(self):
|
|
3938
|
+
"""Ensure that the right type of object is returned when running MyMol.from_mapped_smiles"""
|
|
3939
|
+
mol = MyMol.from_mapped_smiles("[H:1][C:2]([H:3])([H:4])([H:5])")
|
|
3940
|
+
assert isinstance(mol, MyMol)
|
|
3941
|
+
|
|
3942
|
+
@requires_pkg("qcelemental")
|
|
3943
|
+
@pytest.mark.flaky(reruns=5)
|
|
3944
|
+
def test_molecule_subclass_from_qcschema(self):
|
|
3945
|
+
"""Ensure that the right type of object is returned when running MyMol.from_qcschema"""
|
|
3946
|
+
import qcportal
|
|
3947
|
+
|
|
3948
|
+
client = qcportal.PortalClient("https://api.qcarchive.molssi.org:443")
|
|
3949
|
+
|
|
3950
|
+
ds = client.get_dataset(
|
|
3951
|
+
"torsiondrive",
|
|
3952
|
+
"Fragment Stability Benchmark",
|
|
3953
|
+
)
|
|
3954
|
+
|
|
3955
|
+
entry = ds.get_entry("CC(=O)Nc1cc2c(cc1OC)nc[n:4][c:3]2[NH:2][c:1]3ccc(c(c3)Cl)F".lower())
|
|
3956
|
+
|
|
3957
|
+
# now make the molecule from the record instance with and without the geometry
|
|
3958
|
+
mol = MyMol.from_qcschema(entry)
|
|
3959
|
+
|
|
3960
|
+
assert isinstance(mol, MyMol)
|
|
3961
|
+
|
|
3962
|
+
assert mol.n_conformers > 0
|
|
3963
|
+
|
|
3964
|
+
def test_molecule_subclass_from_topology(self):
|
|
3965
|
+
"""Ensure that the right type of object is returned when running MyMol.from_topology"""
|
|
3966
|
+
top = Molecule.from_smiles("CCO").to_topology()
|
|
3967
|
+
mol = MyMol.from_topology(top)
|
|
3968
|
+
assert isinstance(mol, MyMol)
|
|
3969
|
+
|
|
3970
|
+
@requires_rdkit
|
|
3971
|
+
def test_molecule_subclass_from_pdb_and_smiles(self):
|
|
3972
|
+
"""Ensure that the right type of object is returned when running MyMol.from_pdb_and_smiles"""
|
|
3973
|
+
mol = MyMol.from_pdb_and_smiles(get_data_file_path("molecules/toluene.pdb"), "Cc1ccccc1")
|
|
3974
|
+
assert isinstance(mol, MyMol)
|
|
3975
|
+
|
|
3976
|
+
def test_molecule_copy_constructor_from_other_subclass(self):
|
|
3977
|
+
"""Ensure that the right type of object is returned when running the MyMol copy constructor"""
|
|
3978
|
+
normal_mol = MyMol.from_smiles("CCO")
|
|
3979
|
+
mol = MyMol(normal_mol)
|
|
3980
|
+
assert isinstance(mol, MyMol)
|
|
3981
|
+
|
|
3982
|
+
def test_molecule_subclass_from_dict(self):
|
|
3983
|
+
"""Ensure that the right type of object is returned when running MyMol.from_dict"""
|
|
3984
|
+
orig_mol = Molecule.from_smiles("CCO")
|
|
3985
|
+
mol = MyMol.from_dict(orig_mol.to_dict())
|
|
3986
|
+
assert isinstance(mol, MyMol)
|
|
3987
|
+
|
|
3988
|
+
|
|
3989
|
+
class TestHierarchies:
|
|
3990
|
+
def test_nothing_perceived_dipeptide(self):
|
|
3991
|
+
"""Test that loading a "vanilla" molecule from SDF does not assign atom metadata"""
|
|
3992
|
+
from openff.toolkit._tests.create_molecules import dipeptide as create_dipeptide
|
|
3993
|
+
|
|
3994
|
+
dipeptide = create_dipeptide()
|
|
3995
|
+
|
|
3996
|
+
with pytest.raises(KeyError):
|
|
3997
|
+
assert dipeptide.atoms[0].metadata["residue_name"] is None
|
|
3998
|
+
with pytest.raises(KeyError):
|
|
3999
|
+
assert "ALA" == dipeptide.atoms[10].metadata["residue_name"]
|
|
4000
|
+
with pytest.raises(KeyError):
|
|
4001
|
+
assert 1 == dipeptide.atoms[10].metadata["residue_number"]
|
|
4002
|
+
with pytest.raises(KeyError):
|
|
4003
|
+
assert " " == dipeptide.atoms[10].metadata["insertion_code"]
|
|
4004
|
+
with pytest.raises(AttributeError):
|
|
4005
|
+
dipeptide.residues[0]
|
|
4006
|
+
|
|
4007
|
+
def test_residues_perceived_dipeptide(self):
|
|
4008
|
+
"""Test that perceiving residues on a residue-containing molecule correctly populates atom metadata"""
|
|
4009
|
+
from openff.toolkit._tests.create_molecules import (
|
|
4010
|
+
dipeptide_residues_perceived as create_dipeptide,
|
|
4011
|
+
)
|
|
4012
|
+
|
|
4013
|
+
dipeptide_residues_perceived = create_dipeptide()
|
|
4014
|
+
|
|
4015
|
+
assert "ACE" == dipeptide_residues_perceived.atoms[0].metadata["residue_name"]
|
|
4016
|
+
assert "1" == dipeptide_residues_perceived.atoms[0].metadata["residue_number"]
|
|
4017
|
+
assert " " == dipeptide_residues_perceived.atoms[0].metadata["insertion_code"]
|
|
4018
|
+
|
|
4019
|
+
assert "ALA" == dipeptide_residues_perceived.atoms[10].metadata["residue_name"]
|
|
4020
|
+
assert "2" == dipeptide_residues_perceived.atoms[10].metadata["residue_number"]
|
|
4021
|
+
assert " " == dipeptide_residues_perceived.atoms[10].metadata["insertion_code"]
|
|
4022
|
+
|
|
4023
|
+
assert isinstance(dipeptide_residues_perceived.residues[0], HierarchyElement)
|
|
4024
|
+
with pytest.raises(AttributeError):
|
|
4025
|
+
type(dipeptide_residues_perceived.chains[0])
|
|
4026
|
+
|
|
4027
|
+
def test_add_delete_hierarchy_scheme(self):
|
|
4028
|
+
"""Test adding and removing HierarchySchemes to/from molecules"""
|
|
4029
|
+
from openff.toolkit._tests.create_molecules import (
|
|
4030
|
+
dipeptide_residues_perceived as create_dipeptide,
|
|
4031
|
+
)
|
|
4032
|
+
|
|
4033
|
+
dipeptide_residues_perceived = create_dipeptide()
|
|
4034
|
+
|
|
4035
|
+
assert len(dipeptide_residues_perceived.hierarchy_schemes) == 1
|
|
4036
|
+
dipeptide_residues_perceived.add_hierarchy_scheme(("residue_number",), "res_by_num")
|
|
4037
|
+
assert len(dipeptide_residues_perceived.hierarchy_schemes) == 2
|
|
4038
|
+
|
|
4039
|
+
# Redundant hier schemes are OK as long as their iter name is different
|
|
4040
|
+
dipeptide_residues_perceived.add_hierarchy_scheme(("residue_number",), "res_by_num2")
|
|
4041
|
+
assert len(dipeptide_residues_perceived.hierarchy_schemes) == 3
|
|
4042
|
+
|
|
4043
|
+
# Redundant hier schemes are NOT OK if their iter name is already used
|
|
4044
|
+
with pytest.raises(
|
|
4045
|
+
HierarchySchemeWithIteratorNameAlreadyRegisteredException,
|
|
4046
|
+
match=r'Can not add iterator with name "res_by_num" to this molecule',
|
|
4047
|
+
):
|
|
4048
|
+
dipeptide_residues_perceived.add_hierarchy_scheme(("residue_number",), "res_by_num")
|
|
4049
|
+
assert len(dipeptide_residues_perceived.hierarchy_schemes) == 3
|
|
4050
|
+
|
|
4051
|
+
# update_hierarchy_schemes() was called by add_hierarchy_scheme
|
|
4052
|
+
assert dipeptide_residues_perceived.res_by_num[0].residue_number == "1"
|
|
4053
|
+
# Delete the hierarchyscheme and ensure that the iterators are no longer available
|
|
4054
|
+
dipeptide_residues_perceived.delete_hierarchy_scheme("res_by_num")
|
|
4055
|
+
assert len(dipeptide_residues_perceived.hierarchy_schemes) == 2
|
|
4056
|
+
with pytest.raises(AttributeError):
|
|
4057
|
+
dipeptide_residues_perceived.res_by_num[0]
|
|
4058
|
+
with pytest.raises(
|
|
4059
|
+
HierarchySchemeNotFoundException,
|
|
4060
|
+
match=r'Can not delete HierarchyScheme with name "res_by_num" because no HierarchyScheme '
|
|
4061
|
+
"with that iterator name exists",
|
|
4062
|
+
):
|
|
4063
|
+
dipeptide_residues_perceived.delete_hierarchy_scheme("res_by_num")
|
|
4064
|
+
|
|
4065
|
+
def test_add_hierarchy_scheme(self):
|
|
4066
|
+
"""Test all behaviors of Molecule.add_hierarchy_scheme"""
|
|
4067
|
+
offmol = Molecule()
|
|
4068
|
+
|
|
4069
|
+
# Raise an error if iterator name isn't a string, even if it's hashable
|
|
4070
|
+
with pytest.raises(TypeError, match=r"'iterator_name' kwarg must be a string, received 1"):
|
|
4071
|
+
offmol.add_hierarchy_scheme(("chain", "residue_number", "insertion_code", "residue_name"), 1)
|
|
4072
|
+
|
|
4073
|
+
# Ensure that the uniqueness criteria kwarg is some sort of iterable
|
|
4074
|
+
with pytest.raises(
|
|
4075
|
+
TypeError,
|
|
4076
|
+
match=r"'uniqueness_criteria' kwarg must be a list or a tuple of strings, received 'residue_number'",
|
|
4077
|
+
):
|
|
4078
|
+
offmol.add_hierarchy_scheme("residue_number", "residues")
|
|
4079
|
+
# Providing uniqueness_criteria as a list is OK
|
|
4080
|
+
offmol.add_hierarchy_scheme(["chain", "residue_number", "insertion_code", "residue_name"], "residues")
|
|
4081
|
+
|
|
4082
|
+
# Ensure that the items in the uniqueness_criteria are strings
|
|
4083
|
+
with pytest.raises(
|
|
4084
|
+
TypeError,
|
|
4085
|
+
match=r"Each item in the 'uniqueness_criteria' kwarg must be a string, received [(]'chain_id',[)]",
|
|
4086
|
+
):
|
|
4087
|
+
offmol.add_hierarchy_scheme([("chain_id",)], "chains")
|
|
4088
|
+
|
|
4089
|
+
def test_add_hierarchy_scheme_name_conflict(self):
|
|
4090
|
+
molecule = Molecule()
|
|
4091
|
+
|
|
4092
|
+
with pytest.raises(
|
|
4093
|
+
HierarchyIteratorNameConflictError,
|
|
4094
|
+
match="with that name already exists",
|
|
4095
|
+
):
|
|
4096
|
+
molecule.add_hierarchy_scheme(
|
|
4097
|
+
uniqueness_criteria=("foo"),
|
|
4098
|
+
iterator_name="atoms",
|
|
4099
|
+
)
|
|
4100
|
+
|
|
4101
|
+
def test_add_default_hierarchy_schemes(self):
|
|
4102
|
+
"""Test add_default_hierarchy_schemes and its kwargs"""
|
|
4103
|
+
offmol = Molecule.from_polymer_pdb(get_data_file_path("proteins/MainChain_ALA.pdb"))
|
|
4104
|
+
offmol.delete_hierarchy_scheme("residues")
|
|
4105
|
+
offmol.delete_hierarchy_scheme("chains")
|
|
4106
|
+
offmol.add_hierarchy_scheme(("residue_number", "insertion_code", "residue_name"), "residues")
|
|
4107
|
+
# Make sure that the non-default "residues" iterator that we just added
|
|
4108
|
+
# doesn't have "chain_id" as a uniqueness criterion
|
|
4109
|
+
assert "chain_id" not in offmol.hierarchy_schemes["residues"].uniqueness_criteria
|
|
4110
|
+
# Test that the overwrite_existing kwarg has the right behavior
|
|
4111
|
+
with pytest.raises(HierarchySchemeWithIteratorNameAlreadyRegisteredException):
|
|
4112
|
+
offmol.add_default_hierarchy_schemes(overwrite_existing=False)
|
|
4113
|
+
|
|
4114
|
+
# Run add_default_hierarchy_schemes with overwrite_existing set to its default value,
|
|
4115
|
+
# which should overwrite the "residues" iterator we just defined
|
|
4116
|
+
offmol.add_default_hierarchy_schemes()
|
|
4117
|
+
# Ensure that the new residues iterator DOES have the correct uniqueness criterion
|
|
4118
|
+
assert "residue_name" in offmol.hierarchy_schemes["residues"].uniqueness_criteria
|
|
4119
|
+
assert "residue_number" in offmol.hierarchy_schemes["residues"].uniqueness_criteria
|
|
4120
|
+
assert "insertion_code" in offmol.hierarchy_schemes["residues"].uniqueness_criteria
|
|
4121
|
+
assert "chain_id" in offmol.hierarchy_schemes["residues"].uniqueness_criteria
|
|
4122
|
+
assert next(iter(offmol.residues)).residue_name == "ACE"
|
|
4123
|
+
assert next(iter(offmol.residues)).residue_number == "1"
|
|
4124
|
+
assert next(iter(offmol.residues)).insertion_code == " "
|
|
4125
|
+
assert next(iter(offmol.residues)).chain_id == " "
|
|
4126
|
+
|
|
4127
|
+
assert "chain_id" in offmol.hierarchy_schemes["chains"].uniqueness_criteria
|
|
4128
|
+
assert next(iter(offmol.chains)).chain_id == " "
|
|
4129
|
+
|
|
4130
|
+
def test_hierarchy_perceived_dipeptide(self):
|
|
4131
|
+
"""Test populating and accessing HierarchyElements"""
|
|
4132
|
+
from openff.toolkit._tests.create_molecules import (
|
|
4133
|
+
dipeptide_hierarchy_added as create_dipeptide,
|
|
4134
|
+
)
|
|
4135
|
+
|
|
4136
|
+
dipeptide_hierarchy_perceived = create_dipeptide()
|
|
4137
|
+
|
|
4138
|
+
assert (
|
|
4139
|
+
str(dipeptide_hierarchy_perceived.residues[0])
|
|
4140
|
+
== "HierarchyElement ('None', '1', ' ', 'ACE') of iterator 'residues' containing 6 atom(s)"
|
|
4141
|
+
)
|
|
4142
|
+
assert dipeptide_hierarchy_perceived.residues[0].chain_id == "None"
|
|
4143
|
+
assert dipeptide_hierarchy_perceived.residues[0].residue_name == "ACE"
|
|
4144
|
+
assert dipeptide_hierarchy_perceived.residues[0].insertion_code == " "
|
|
4145
|
+
assert dipeptide_hierarchy_perceived.residues[0].residue_number == "1"
|
|
4146
|
+
assert set(dipeptide_hierarchy_perceived.residues[0].atom_indices) == set(range(6))
|
|
4147
|
+
|
|
4148
|
+
assert (
|
|
4149
|
+
str(dipeptide_hierarchy_perceived.residues[1])
|
|
4150
|
+
== "HierarchyElement ('None', '2', ' ', 'ALA') of iterator 'residues' containing 11 atom(s)"
|
|
4151
|
+
)
|
|
4152
|
+
assert dipeptide_hierarchy_perceived.residues[1].chain_id == "None"
|
|
4153
|
+
assert dipeptide_hierarchy_perceived.residues[1].residue_name == "ALA"
|
|
4154
|
+
assert dipeptide_hierarchy_perceived.residues[1].insertion_code == " "
|
|
4155
|
+
assert dipeptide_hierarchy_perceived.residues[1].residue_number == "2"
|
|
4156
|
+
assert set(dipeptide_hierarchy_perceived.residues[1].atom_indices) == set(range(6, 17))
|
|
4157
|
+
|
|
4158
|
+
for residue in dipeptide_hierarchy_perceived.residues:
|
|
4159
|
+
for atom in residue.atoms:
|
|
4160
|
+
assert atom.metadata["residue_name"] == residue.residue_name
|
|
4161
|
+
assert atom.metadata["residue_number"] == residue.residue_number
|
|
4162
|
+
assert atom.metadata["insertion_code"] == residue.insertion_code
|
|
4163
|
+
|
|
4164
|
+
def test_hierarchy_perceived_information_propagation(self):
|
|
4165
|
+
"""Ensure that updating atom metadata doesn't update the iterators until the hierarchy is re-perceived"""
|
|
4166
|
+
from openff.toolkit._tests.create_molecules import (
|
|
4167
|
+
dipeptide_hierarchy_added as create_dipeptide,
|
|
4168
|
+
)
|
|
4169
|
+
|
|
4170
|
+
dipeptide_hierarchy_perceived = create_dipeptide()
|
|
4171
|
+
|
|
4172
|
+
for atom in dipeptide_hierarchy_perceived.atoms:
|
|
4173
|
+
atom.metadata["chain_id"] = "A"
|
|
4174
|
+
assert ("A", "1", " ", "ACE") != dipeptide_hierarchy_perceived.residues[0].identifier
|
|
4175
|
+
dipeptide_hierarchy_perceived.update_hierarchy_schemes()
|
|
4176
|
+
assert ("A", "1", " ", "ACE") == dipeptide_hierarchy_perceived.residues[0].identifier
|
|
4177
|
+
|
|
4178
|
+
def test_hierarchy_element_generation(self):
|
|
4179
|
+
"""Ensure that hierarchy elements are generated correctly from atom metadata"""
|
|
4180
|
+
from openff.toolkit._tests.create_molecules import create_ethanol
|
|
4181
|
+
|
|
4182
|
+
ethanol = create_ethanol()
|
|
4183
|
+
|
|
4184
|
+
for atom in ethanol.atoms:
|
|
4185
|
+
atom.metadata["residue_name"] = "AAA"
|
|
4186
|
+
atom.metadata["residue_number"] = 1
|
|
4187
|
+
atom.metadata["chain_id"] = "A"
|
|
4188
|
+
|
|
4189
|
+
ethanol.atoms[1].metadata["chain_id"] = "Z"
|
|
4190
|
+
del ethanol.atoms[2].metadata["chain_id"]
|
|
4191
|
+
ethanol.atoms[3].metadata["chain_id"] = 1
|
|
4192
|
+
ethanol.atoms[4].metadata["residue_number"] = "1"
|
|
4193
|
+
ethanol.atoms[5].metadata["residue_name"] = "ZZZ"
|
|
4194
|
+
del ethanol.atoms[6].metadata["residue_name"]
|
|
4195
|
+
ethanol.atoms[7].metadata["residue_number"] = 2
|
|
4196
|
+
ethanol.add_default_hierarchy_schemes()
|
|
4197
|
+
|
|
4198
|
+
expected_chains = [(("A",), 6), (("None",), 1), (("Z",), 1), ((1,), 1)]
|
|
4199
|
+
|
|
4200
|
+
assert len(ethanol.chains) == len(expected_chains)
|
|
4201
|
+
for chain, exp_chain in zip(ethanol.chains, expected_chains):
|
|
4202
|
+
assert chain.identifier == exp_chain[0]
|
|
4203
|
+
assert len(chain.atom_indices) == exp_chain[1]
|
|
4204
|
+
|
|
4205
|
+
expected_residues = [
|
|
4206
|
+
(("A", 1, "None", "AAA"), 2),
|
|
4207
|
+
(("A", "1", "None", "AAA"), 1),
|
|
4208
|
+
(("A", 1, "None", "None"), 1),
|
|
4209
|
+
(("A", 1, "None", "ZZZ"), 1),
|
|
4210
|
+
(("A", 2, "None", "AAA"), 1),
|
|
4211
|
+
(("None", 1, "None", "AAA"), 1),
|
|
4212
|
+
(("Z", 1, "None", "AAA"), 1),
|
|
4213
|
+
((1, 1, "None", "AAA"), 1),
|
|
4214
|
+
]
|
|
4215
|
+
|
|
4216
|
+
assert len(ethanol.residues) == len(expected_residues)
|
|
4217
|
+
for residue, exp_residue in zip(ethanol.residues, expected_residues):
|
|
4218
|
+
assert residue.identifier == exp_residue[0]
|
|
4219
|
+
assert len(residue.atom_indices) == exp_residue[1]
|
|
4220
|
+
|
|
4221
|
+
def test_hierarchy_element_sorting(self):
|
|
4222
|
+
"""Ensure that hierarchy elements are sorted correctly"""
|
|
4223
|
+
hs = HierarchyScheme(None, ("foo", "bar"), "foobar")
|
|
4224
|
+
# Atom lists are used here to indicate the positions
|
|
4225
|
+
# that this element may have in the "proper" sorting.
|
|
4226
|
+
hs.add_hierarchy_element(("Z", 10), [13])
|
|
4227
|
+
hs.add_hierarchy_element(("Z", 5), [12])
|
|
4228
|
+
# Switch two values so the list isn't just reversed from the correct sorting
|
|
4229
|
+
hs.add_hierarchy_element(("None", "10"), [10])
|
|
4230
|
+
hs.add_hierarchy_element(("Y", 10), [11])
|
|
4231
|
+
hs.add_hierarchy_element(("A", 10), [8, 9])
|
|
4232
|
+
hs.add_hierarchy_element(("A", "10"), [8, 9])
|
|
4233
|
+
hs.add_hierarchy_element(("A", 1), [5, 6, 7])
|
|
4234
|
+
hs.add_hierarchy_element(("A", "1"), [5, 6, 7])
|
|
4235
|
+
hs.add_hierarchy_element(("A", " 1"), [5, 6, 7])
|
|
4236
|
+
hs.add_hierarchy_element(("A", "None"), [4])
|
|
4237
|
+
hs.add_hierarchy_element(("A", " "), [2, 3])
|
|
4238
|
+
hs.add_hierarchy_element(("A", ""), [2, 3])
|
|
4239
|
+
hs.add_hierarchy_element((" ", "10"), [0, 1])
|
|
4240
|
+
hs.add_hierarchy_element(("", "10"), [0, 1])
|
|
4241
|
+
hs.sort_hierarchy_elements()
|
|
4242
|
+
|
|
4243
|
+
# Compare the sorted hierarchyelements to their expected sortings
|
|
4244
|
+
# (assuming that the atom indices indicate valid positions for the resulting elements in the proper sorting)
|
|
4245
|
+
for idx, ele in enumerate(hs.hierarchy_elements):
|
|
4246
|
+
assert idx in ele.atom_indices
|