useful-rdkit-utils 2.0.1__tar.gz → 2.0.2__tar.gz
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.
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/CHANGELOG.md +45 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/PKG-INFO +2 -2
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/pyproject.toml +2 -1
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_geometry.py +180 -0
- useful_rdkit_utils-2.0.2/tests/test_split_utils.py +154 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_useful_rdkit_utils.py +1 -1
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/__init__.py +1 -1
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/geometry.py +69 -10
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/ring_systems.py +5 -4
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/split_utils.py +129 -2
- useful_rdkit_utils-2.0.1/tests/test_split_utils.py +0 -65
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/.gitattributes +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/.github/CONTRIBUTING.md +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/.github/PUBLISHING.md +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/.github/workflows/CI.yaml +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/.github/workflows/publish.yaml +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/.gitignore +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/.readthedocs.yaml +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/CODE_OF_CONDUCT.md +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/LICENSE +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/MANIFEST.in +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/README.md +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/data/chembl_ring_systems.csv +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/data/test.smi +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/Makefile +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/cli.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/conf.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/descriptor_preprocessor.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/descriptors.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/geometry.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/index.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/installation.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/jupyter.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/misc_utils.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/model_comparison.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/optional.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/pandas.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/reactions.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/reos.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/ring_systems.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/sali.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/scaffold_finder.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/seaborn.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/silly_walks.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/split_utils.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/stats.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/units.rst +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/nikki.png +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/README.md +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/bootstrap_AUC.ipynb +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/catboost_wrapper.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/compare_mordred_rdkit.ipynb +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/data/biogen_logS.csv +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/demo_REOS.ipynb +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/demo_cross_validate.ipynb +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/demo_descriptors.ipynb +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/demo_ring_systems.ipynb +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/demo_useful_rdkit_utils.ipynb +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/explore_functional_group_filters.ipynb +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/ffnn.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/lgbm_wrapper.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/model_comparison.ipynb +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/parallel_conformer_generation.ipynb +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/sort_and_slice_ecfp_featuriser.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/zinc_sample.smi +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/__init__.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test.smi +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_audit_fixes.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_chemreps.txt +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_descriptor_preprocessor.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_descriptors.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_model_comparison.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_reactions.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_reos.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_ring_systems.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_sali.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_scaffold_finder.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/tests/test_silly_walks.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/build_ring_dictionary.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/descriptor_preprocessor.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/descriptors.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/jupyter_utils.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/misc_utils.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/model_comparison.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/optional.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/pandas_utils.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/reactions.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/reos.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/sali.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/scaffold_finder.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/seaborn_utils.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/silly_walks.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/stat_utils.py +0 -0
- {useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/units.py +0 -0
|
@@ -3,6 +3,51 @@ All notable changes to this project will be documented in this file.
|
|
|
3
3
|
|
|
4
4
|
## [Unreleased]
|
|
5
5
|
|
|
6
|
+
## [2.0.2] - 2026-11-29
|
|
7
|
+
### Fixed
|
|
8
|
+
- Excluded rdkit 2026.9.2 from the dependencies. Its macOS arm64 PyPI wheels raise
|
|
9
|
+
`RuntimeError: bad any cast` from `MurckoDecompose()` on every molecule
|
|
10
|
+
(rdkit/rdkit#9836), which broke `get_scaffold()` and the scaffold-based splits and clustering
|
|
11
|
+
on Apple Silicon. The Linux wheels and the conda-forge build are unaffected, but one exclusion
|
|
12
|
+
keeps the requirement simple. Lift it once a fixed release is out.
|
|
13
|
+
- `mcs_rmsd()` is symmetry corrected, which it was documented and named for but did not do.
|
|
14
|
+
It minimizes the RMSD over every way the MCS maps onto each molecule, but called
|
|
15
|
+
`GetSubstructMatches()` without `uniquify=False`. That default keeps one representative per
|
|
16
|
+
symmetry class, which is exactly the set the minimum was meant to be taken over, so there was
|
|
17
|
+
nothing left to minimize and the comparison was symmetry blind. On pose pairs that differ only
|
|
18
|
+
by a symmetric relabeling, such as a carboxylate's two oxygens swapped, a para-ring flipped or
|
|
19
|
+
two methyls exchanged, it reported 1.40 to 1.70 A where the answer is 0. That straddles the 1.5 A
|
|
20
|
+
threshold conventionally used to call a predicted pose correct, so the error changed verdicts.
|
|
21
|
+
`refine_conformers(use_symmetry=True)` already treats such pairs as identical, so the two
|
|
22
|
+
functions disagreed about what counts as the same arrangement.
|
|
23
|
+
### Added
|
|
24
|
+
- `mcs_rmsd(align=...)`. The default compares the conformers in the frame they arrive in, which
|
|
25
|
+
is what scoring docked or co-folded poses against a crystal structure needs, since the receptor
|
|
26
|
+
fixes a common frame and a pose in the wrong place must score as wrong. `align=True` superposes
|
|
27
|
+
the MCS atoms first, which is what comparing free conformers needs. The docstring had not said
|
|
28
|
+
which of the two it did, and the two answers differ by however far apart the inputs sit.
|
|
29
|
+
- `mcs_rmsd(timeout=...)`, passed through to `FindMCS()`. The MCS search was unbounded, and it is
|
|
30
|
+
the expensive half of the call on large or highly symmetric pairs.
|
|
31
|
+
- `mcs_rmsd(max_matches=...)`, replacing the inherited `GetSubstructMatches()` default of 1000.
|
|
32
|
+
Enumerating all mappings rather than one per symmetry class raises the count a long way, and a
|
|
33
|
+
tetraphenyl scaffold returns 1000 of its 4608 mappings at the old default, silently, so the
|
|
34
|
+
minimum was taken over an arbitrary subset. The cap is now explicit, documented and raisable.
|
|
35
|
+
- `audit_split_leakage()` and `summarize_split_leakage()` in split_utils. The module builds
|
|
36
|
+
splits four ways but had no way to check one it was handed, which is the case whenever a split
|
|
37
|
+
arrives with a public benchmark or from a collaborator. Each test molecule is checked against
|
|
38
|
+
the training set from strictest to loosest: identical InChIKey, identical first InChIKey block,
|
|
39
|
+
identical Bemis-Murcko scaffold, and nearest-neighbor Morgan Tanimoto with the training
|
|
40
|
+
molecule that produced it.
|
|
41
|
+
The first block carries constitution only, so it catches a training molecule that differs just
|
|
42
|
+
in stereochemistry or protonation state. Enantiomers, diastereomers, E/Z isomers and an acid
|
|
43
|
+
against its conjugate base all collapse onto it, and each of those is leakage that an InChIKey
|
|
44
|
+
comparison alone reports as a clean split. It does not see through every tautomer and does not
|
|
45
|
+
see through salts at all, so `strip_salts`, on by default, reduces each molecule to its largest
|
|
46
|
+
fragment first; without it a mesylate of a training compound reads as a new molecule.
|
|
47
|
+
The two strict checks are leakage outright, since a model can score on them without
|
|
48
|
+
generalizing. The scaffold and similarity columns are degrees of optimism rather than errors
|
|
49
|
+
and depend on what the split was built to measure, so they are reported and not judged.
|
|
50
|
+
|
|
6
51
|
## [2.0.1] - 2026-08-27
|
|
7
52
|
### Added
|
|
8
53
|
- Documentation pages for the three modules that had none: silly_walks, optional, and a Command Line
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: useful_rdkit_utils
|
|
3
|
-
Version: 2.0.
|
|
3
|
+
Version: 2.0.2
|
|
4
4
|
Summary: A collection of useful RDKit functions
|
|
5
5
|
Project-URL: Homepage, https://github.com/PatWalters/useful_rdkit_utils
|
|
6
6
|
Project-URL: Bug Tracker, https://github.com/PatWalters/useful_rdkit_utils/issues
|
|
@@ -18,7 +18,7 @@ Requires-Dist: numpy
|
|
|
18
18
|
Requires-Dist: pandas
|
|
19
19
|
Requires-Dist: py3dmol
|
|
20
20
|
Requires-Dist: pystow
|
|
21
|
-
Requires-Dist: rdkit
|
|
21
|
+
Requires-Dist: rdkit!=2026.9.2
|
|
22
22
|
Requires-Dist: scikit-learn
|
|
23
23
|
Requires-Dist: scipy
|
|
24
24
|
Requires-Dist: seaborn
|
|
@@ -269,3 +269,183 @@ def test_use_symmetry_preserves_the_filtering_invariants():
|
|
|
269
269
|
assert lookup(i, j) >= rms_threshold
|
|
270
270
|
for d in dropped:
|
|
271
271
|
assert any(lookup(d, k) < rms_threshold for k in kept)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _symmetry_swapped_pair(smiles, seed=0xC0FFEE):
|
|
275
|
+
"""Two poses of one molecule that differ only by a symmetric relabeling.
|
|
276
|
+
|
|
277
|
+
The second pose is the first with the coordinates permuted by a non-identity
|
|
278
|
+
automorphism of the molecular graph, so the two are the same physical
|
|
279
|
+
arrangement of atoms and a symmetry-corrected RMSD between them must be zero.
|
|
280
|
+
A symmetry-blind RMSD compares atom i to atom i and reports them as far apart.
|
|
281
|
+
"""
|
|
282
|
+
mol = Chem.AddHs(Chem.MolFromSmiles(smiles))
|
|
283
|
+
assert AllChem.EmbedMolecule(mol, randomSeed=seed) == 0
|
|
284
|
+
AllChem.MMFFOptimizeMolecule(mol)
|
|
285
|
+
first = Chem.RemoveHs(mol)
|
|
286
|
+
second = Chem.Mol(first)
|
|
287
|
+
self_pattern = Chem.MolFromSmarts(Chem.MolToSmarts(first))
|
|
288
|
+
identity = tuple(range(first.GetNumAtoms()))
|
|
289
|
+
automorphisms = first.GetSubstructMatches(self_pattern, uniquify=False)
|
|
290
|
+
permutation = next(p for p in automorphisms if p != identity)
|
|
291
|
+
positions = first.GetConformer().GetPositions()
|
|
292
|
+
conformer = second.GetConformer()
|
|
293
|
+
for target, source in enumerate(permutation):
|
|
294
|
+
conformer.SetAtomPosition(target, positions[source].tolist())
|
|
295
|
+
return first, second
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
# para-disubstituted rings, a carboxylate and a trityl group: the automorphism
|
|
299
|
+
# groups a symmetry-corrected RMSD has to factor out.
|
|
300
|
+
SYMMETRIC_SMILES = [
|
|
301
|
+
"c1ccc(cc1)C(=O)[O-]",
|
|
302
|
+
"OC(=O)c1ccc(C(=O)O)cc1",
|
|
303
|
+
"Cc1ccc(C)cc1",
|
|
304
|
+
"C(c1ccccc1)(c1ccccc1)c1ccccc1",
|
|
305
|
+
]
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
@pytest.mark.parametrize("smiles", SYMMETRIC_SMILES)
|
|
309
|
+
def test_mcs_rmsd_is_symmetry_corrected(smiles):
|
|
310
|
+
"""A pose pair that is identical up to symmetry must score zero."""
|
|
311
|
+
first, second = _symmetry_swapped_pair(smiles)
|
|
312
|
+
num_mcs_atoms, rmsd = mcs_rmsd(first, second)
|
|
313
|
+
assert num_mcs_atoms == first.GetNumAtoms()
|
|
314
|
+
assert rmsd == pytest.approx(0.0, abs=1e-6)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
@pytest.mark.parametrize("smiles", SYMMETRIC_SMILES)
|
|
318
|
+
def test_mcs_rmsd_matches_rdkit_on_symmetric_pairs(smiles):
|
|
319
|
+
"""RDKit's own symmetry-corrected RMSD agrees, which pins the convention."""
|
|
320
|
+
first, second = _symmetry_swapped_pair(smiles)
|
|
321
|
+
_, rmsd = mcs_rmsd(first, second)
|
|
322
|
+
assert rmsd == pytest.approx(rdMolAlign.CalcRMS(Chem.Mol(second), Chem.Mol(first)), abs=1e-6)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def test_mcs_rmsd_uniquified_mappings_would_miss_the_symmetry():
|
|
326
|
+
"""Guards the actual defect: uniquify keeps one mapping per symmetry class.
|
|
327
|
+
|
|
328
|
+
With the mappings uniquified there is nothing left to minimize over, and the
|
|
329
|
+
symmetry-equivalent pose above scores well over an angstrom. This test fails
|
|
330
|
+
if the implementation ever reverts to the uniquified mappings.
|
|
331
|
+
"""
|
|
332
|
+
first, second = _symmetry_swapped_pair("Cc1ccc(C)cc1")
|
|
333
|
+
pattern = Chem.MolFromSmarts(Chem.MolToSmarts(first))
|
|
334
|
+
uniquified = first.GetSubstructMatches(pattern)
|
|
335
|
+
everything = first.GetSubstructMatches(pattern, uniquify=False)
|
|
336
|
+
assert len(uniquified) == 1
|
|
337
|
+
assert len(everything) > 1
|
|
338
|
+
|
|
339
|
+
positions_1 = first.GetConformer().GetPositions()
|
|
340
|
+
positions_2 = second.GetConformer().GetPositions()
|
|
341
|
+
uniquified_rmsd = min(
|
|
342
|
+
float(np.sqrt(np.mean(np.sum((positions_1[list(m1)] - positions_2[list(m2)]) ** 2, axis=1))))
|
|
343
|
+
for m1 in uniquified
|
|
344
|
+
for m2 in first.GetSubstructMatches(pattern)
|
|
345
|
+
)
|
|
346
|
+
assert uniquified_rmsd > 1.0
|
|
347
|
+
assert mcs_rmsd(first, second)[1] == pytest.approx(0.0, abs=1e-6)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _two_conformer_pair(smiles, seed=7):
|
|
351
|
+
mol = Chem.AddHs(Chem.MolFromSmiles(smiles))
|
|
352
|
+
assert len(AllChem.EmbedMultipleConfs(mol, numConfs=2, randomSeed=seed)) == 2
|
|
353
|
+
AllChem.MMFFOptimizeMoleculeConfs(mol)
|
|
354
|
+
mol = Chem.RemoveHs(mol)
|
|
355
|
+
first = Chem.Mol(mol)
|
|
356
|
+
first.RemoveAllConformers()
|
|
357
|
+
first.AddConformer(mol.GetConformer(0), assignId=True)
|
|
358
|
+
second = Chem.Mol(mol)
|
|
359
|
+
second.RemoveAllConformers()
|
|
360
|
+
second.AddConformer(mol.GetConformer(1), assignId=True)
|
|
361
|
+
return first, second
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def test_mcs_rmsd_default_keeps_the_frame():
|
|
365
|
+
"""Translating one conformer must change the default, unaligned comparison.
|
|
366
|
+
|
|
367
|
+
Poses of a ligand in one receptor share a frame, and a pose in the wrong place
|
|
368
|
+
has to score as wrong, so the default must not superpose.
|
|
369
|
+
"""
|
|
370
|
+
first, second = _two_conformer_pair("c1ccccc1C(=O)O")
|
|
371
|
+
_, before = mcs_rmsd(first, second)
|
|
372
|
+
shifted = Chem.Mol(second)
|
|
373
|
+
conformer = shifted.GetConformer()
|
|
374
|
+
for idx in range(shifted.GetNumAtoms()):
|
|
375
|
+
position = conformer.GetAtomPosition(idx)
|
|
376
|
+
conformer.SetAtomPosition(idx, (position.x + 10.0, position.y, position.z))
|
|
377
|
+
_, after = mcs_rmsd(first, shifted)
|
|
378
|
+
assert after > before + 5.0
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def test_mcs_rmsd_align_discards_the_frame():
|
|
382
|
+
"""align=True must be blind to where the probe sits."""
|
|
383
|
+
first, second = _two_conformer_pair("c1ccccc1C(=O)O")
|
|
384
|
+
_, before = mcs_rmsd(first, second, align=True)
|
|
385
|
+
shifted = Chem.Mol(second)
|
|
386
|
+
conformer = shifted.GetConformer()
|
|
387
|
+
for idx in range(shifted.GetNumAtoms()):
|
|
388
|
+
position = conformer.GetAtomPosition(idx)
|
|
389
|
+
conformer.SetAtomPosition(idx, (position.x + 13.0, position.y - 4.0, position.z + 2.5))
|
|
390
|
+
_, after = mcs_rmsd(first, shifted, align=True)
|
|
391
|
+
assert after == pytest.approx(before, abs=1e-6)
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
@pytest.mark.parametrize("smiles", ["CCO", "c1ccccc1C(=O)O", "CC(C)Cc1ccc(cc1)C(C)C(=O)O",
|
|
395
|
+
"CC(=O)Nc1ccc(O)cc1", "CN1C=NC2=C1C(=O)N(C)C(=O)N2C"])
|
|
396
|
+
def test_mcs_rmsd_align_matches_get_best_rms(smiles):
|
|
397
|
+
"""On one graph, align=True is GetBestRMS without terminal-group symmetrization.
|
|
398
|
+
|
|
399
|
+
That symmetrization is not reachable from Python outside GetBestRMS, so the
|
|
400
|
+
docstring points at GetBestRMS for the same-molecule case and this pins the
|
|
401
|
+
relationship between the two.
|
|
402
|
+
"""
|
|
403
|
+
first, second = _two_conformer_pair(smiles)
|
|
404
|
+
_, rmsd = mcs_rmsd(first, second, align=True)
|
|
405
|
+
expected = rdMolAlign.GetBestRMS(Chem.Mol(second), Chem.Mol(first),
|
|
406
|
+
symmetrizeConjugatedTerminalGroups=False)
|
|
407
|
+
assert rmsd == pytest.approx(expected, abs=1e-4)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def test_mcs_rmsd_no_common_substructure_is_infinite(benzene):
|
|
411
|
+
"""Nothing in common means no RMSD to report."""
|
|
412
|
+
neon = Chem.AddHs(Chem.MolFromSmiles("[Ne]"))
|
|
413
|
+
AllChem.EmbedMolecule(neon, randomSeed=1)
|
|
414
|
+
num_mcs_atoms, rmsd = mcs_rmsd(benzene, neon)
|
|
415
|
+
assert num_mcs_atoms == 0
|
|
416
|
+
assert rmsd == float("inf")
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def test_mcs_rmsd_max_matches_bounds_the_enumeration(benzene):
|
|
420
|
+
"""max_matches caps the mappings, replacing a silent 1000-match default.
|
|
421
|
+
|
|
422
|
+
Benzene admits twelve mappings onto itself. Capping below that has to leave a
|
|
423
|
+
usable, non-negative answer rather than raising.
|
|
424
|
+
"""
|
|
425
|
+
second = Chem.Mol(benzene)
|
|
426
|
+
_, full = mcs_rmsd(benzene, second)
|
|
427
|
+
_, capped = mcs_rmsd(benzene, second, max_matches=1)
|
|
428
|
+
assert full == pytest.approx(0.0, abs=1e-6)
|
|
429
|
+
assert capped >= full
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def test_mcs_rmsd_timeout_is_accepted(benzene, ethanol):
|
|
433
|
+
"""A timeout yields a smaller MCS, never an exception."""
|
|
434
|
+
num_mcs_atoms, rmsd = mcs_rmsd(benzene, ethanol, timeout=5)
|
|
435
|
+
assert num_mcs_atoms >= 0
|
|
436
|
+
assert rmsd >= 0
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def test_kabsch_rmsd_rejects_a_mirror_image():
|
|
440
|
+
"""Superposition must not fold a structure onto its own mirror image."""
|
|
441
|
+
from useful_rdkit_utils.geometry import _kabsch_rmsd
|
|
442
|
+
|
|
443
|
+
mol = Chem.AddHs(Chem.MolFromSmiles("C[C@H](N)C(=O)O"))
|
|
444
|
+
assert AllChem.EmbedMolecule(mol, randomSeed=5) == 0
|
|
445
|
+
AllChem.MMFFOptimizeMolecule(mol)
|
|
446
|
+
mol = Chem.RemoveHs(mol)
|
|
447
|
+
positions = mol.GetConformer().GetPositions()
|
|
448
|
+
mirrored = positions.copy()
|
|
449
|
+
mirrored[:, 0] *= -1.0
|
|
450
|
+
assert _kabsch_rmsd(positions, positions) == pytest.approx(0.0, abs=1e-9)
|
|
451
|
+
assert _kabsch_rmsd(positions, mirrored) > 0.1
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
import useful_rdkit_utils as uru
|
|
6
|
+
from useful_rdkit_utils.split_utils import (
|
|
7
|
+
GroupKFoldShuffle,
|
|
8
|
+
audit_split_leakage,
|
|
9
|
+
summarize_split_leakage,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class _FakeModel:
|
|
14
|
+
"""Minimal stand-in for the WrapperFactory-created models."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, y_col):
|
|
17
|
+
self.y_col = y_col
|
|
18
|
+
|
|
19
|
+
def validate(self, train, test):
|
|
20
|
+
return np.full(len(test), train[self.y_col].mean())
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@pytest.fixture
|
|
24
|
+
def small_df():
|
|
25
|
+
rng = np.random.default_rng(0)
|
|
26
|
+
smiles = ["c1ccccc1", "CCO", "CCN", "CCOC", "c1ccc(O)cc1", "c1ccc(N)cc1",
|
|
27
|
+
"Cc1ccccc1", "NCc1ccccc1", "OCC1=CC=CC=C1", "CC(C)O"] * 4
|
|
28
|
+
n = len(smiles)
|
|
29
|
+
return pd.DataFrame({"SMILES": smiles, "row_id": np.arange(n), "y": rng.normal(size=n)})
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_group_kfold_shuffle_error_when_too_many_splits():
|
|
33
|
+
kf = GroupKFoldShuffle(n_splits=10, shuffle=True)
|
|
34
|
+
with pytest.raises(ValueError):
|
|
35
|
+
_ = list(kf.split(X=np.zeros(5), groups=[0, 1, 2]))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_cross_validate_nested(small_df):
|
|
39
|
+
n_outer, n_inner = 3, 2
|
|
40
|
+
model_list = [("fake", _FakeModel)]
|
|
41
|
+
group_list = [("random", uru.get_random_clusters)]
|
|
42
|
+
res = uru.cross_validate(small_df, model_list, "y", group_list,
|
|
43
|
+
n_outer=n_outer, n_inner=n_inner, random_state=1)
|
|
44
|
+
|
|
45
|
+
assert "fake" in res.columns
|
|
46
|
+
assert {"dset", "group", "fold"} <= set(res.columns)
|
|
47
|
+
|
|
48
|
+
test_df = res.query("dset == 'test'")
|
|
49
|
+
folds_seen = set(test_df["fold"].unique())
|
|
50
|
+
# per outer round: n_inner inner folds plus the outer test evaluation
|
|
51
|
+
expected = {i * (n_inner + 1) + k for i in range(n_outer) for k in range(n_inner + 1)}
|
|
52
|
+
assert folds_seen == expected
|
|
53
|
+
|
|
54
|
+
# no leakage: the outer test rows must not appear in the inner training rows of the same round
|
|
55
|
+
for i in range(n_outer):
|
|
56
|
+
inner_folds = set(range(i * (n_inner + 1), i * (n_inner + 1) + n_inner))
|
|
57
|
+
train_rows = res.query("dset == 'train'")
|
|
58
|
+
train_rows = train_rows[train_rows["fold"].isin(inner_folds)]
|
|
59
|
+
outer_test_folds = {i * (n_inner + 1) + n_inner}
|
|
60
|
+
outer_rows = test_df[test_df["fold"].isin(outer_test_folds)]
|
|
61
|
+
assert not set(train_rows["row_id"]) & set(outer_rows["row_id"])
|
|
62
|
+
|
|
63
|
+
# every test row has a model prediction, and each fold label has at least one test row
|
|
64
|
+
assert test_df["fake"].notna().all()
|
|
65
|
+
assert test_df.groupby("fold").ngroups == n_outer * (n_inner + 1)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_get_scaffold_acyclic():
|
|
69
|
+
assert uru.get_scaffold("CCCC") == "CCCC"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# A training set and a test set with leakage planted deliberately, one kind per row.
|
|
73
|
+
LEAKY_TRAIN = [
|
|
74
|
+
"CC(=O)Oc1ccccc1C(=O)O", # aspirin
|
|
75
|
+
"CC(C)Cc1ccc(cc1)C(C)C(=O)O", # ibuprofen
|
|
76
|
+
"C[C@H](N)C(=O)O", # L-alanine
|
|
77
|
+
"CCN", # ethylamine, as the free base
|
|
78
|
+
"c1ccccc1",
|
|
79
|
+
"CN1C=NC2=C1C(=O)N(C)C(=O)N2C", # caffeine
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_audit_split_leakage_finds_an_exact_duplicate():
|
|
84
|
+
audit = audit_split_leakage(LEAKY_TRAIN, ["CC(=O)Oc1ccccc1C(=O)O"])
|
|
85
|
+
assert bool(audit.loc[0, "exact"])
|
|
86
|
+
assert audit.loc[0, "nearest_similarity"] == pytest.approx(1.0)
|
|
87
|
+
assert audit.loc[0, "nearest_train_smiles"] == "CC(=O)Oc1ccccc1C(=O)O"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_audit_split_leakage_finds_an_enantiomer():
|
|
91
|
+
"""An enantiomer of a training compound is a different molecule but still leakage.
|
|
92
|
+
|
|
93
|
+
The InChIKey differs, so the exact check misses it; the first block is
|
|
94
|
+
constitution only, so the connectivity check catches it.
|
|
95
|
+
"""
|
|
96
|
+
audit = audit_split_leakage(LEAKY_TRAIN, ["C[C@@H](N)C(=O)O"])
|
|
97
|
+
assert not bool(audit.loc[0, "exact"])
|
|
98
|
+
assert bool(audit.loc[0, "same_connectivity"])
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_audit_split_leakage_sees_through_a_salt():
|
|
102
|
+
"""A salt of a training compound counts, and only once the counter ion is gone."""
|
|
103
|
+
stripped = audit_split_leakage(LEAKY_TRAIN, ["CCN.Cl"], strip_salts=True)
|
|
104
|
+
intact = audit_split_leakage(LEAKY_TRAIN, ["CCN.Cl"], strip_salts=False)
|
|
105
|
+
assert bool(stripped.loc[0, "same_connectivity"])
|
|
106
|
+
assert not bool(intact.loc[0, "same_connectivity"])
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_audit_split_leakage_leaves_a_genuinely_new_molecule_alone():
|
|
110
|
+
audit = audit_split_leakage(LEAKY_TRAIN, ["c1ccc2ccccc2c1", "O=C(O)CCCCCCCCCCCCCCCCC"])
|
|
111
|
+
assert not audit["exact"].any()
|
|
112
|
+
assert not audit["same_connectivity"].any()
|
|
113
|
+
assert (audit["nearest_similarity"] < 0.5).all()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def test_audit_split_leakage_flags_a_near_duplicate_at_the_cutoff():
|
|
117
|
+
"""The methyl ester of a training acid is not the same molecule, but it is close."""
|
|
118
|
+
ester = "CC(C)Cc1ccc(cc1)C(C)C(=O)OC"
|
|
119
|
+
audit = audit_split_leakage(LEAKY_TRAIN, [ester], similarity_cutoff=0.6)
|
|
120
|
+
assert not bool(audit.loc[0, "same_connectivity"])
|
|
121
|
+
assert bool(audit.loc[0, "near_duplicate"])
|
|
122
|
+
strict = audit_split_leakage(LEAKY_TRAIN, [ester], similarity_cutoff=0.95)
|
|
123
|
+
assert not bool(strict.loc[0, "near_duplicate"])
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_audit_split_leakage_survives_an_unparsable_smiles():
|
|
127
|
+
"""One bad row must not take the audit down with it."""
|
|
128
|
+
audit = audit_split_leakage(LEAKY_TRAIN, ["not a molecule", "c1ccccc1"])
|
|
129
|
+
assert not bool(audit.loc[0, "exact"])
|
|
130
|
+
assert not bool(audit.loc[0, "same_connectivity"])
|
|
131
|
+
assert np.isnan(audit.loc[0, "nearest_similarity"])
|
|
132
|
+
assert audit.loc[0, "nearest_train_smiles"] is None
|
|
133
|
+
assert bool(audit.loc[1, "exact"])
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_audit_split_leakage_tolerates_a_bad_training_smiles():
|
|
137
|
+
audit = audit_split_leakage(["not a molecule"] + LEAKY_TRAIN, ["c1ccccc1"])
|
|
138
|
+
assert bool(audit.loc[0, "exact"])
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_audit_split_leakage_returns_one_row_per_test_molecule():
|
|
142
|
+
test_smiles = ["c1ccccc1", "CCO", "CC(=O)Oc1ccccc1C(=O)O"]
|
|
143
|
+
audit = audit_split_leakage(LEAKY_TRAIN, test_smiles)
|
|
144
|
+
assert len(audit) == len(test_smiles)
|
|
145
|
+
assert list(audit["test_smiles"]) == test_smiles
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def test_summarize_split_leakage_reports_fractions():
|
|
149
|
+
test_smiles = ["CC(=O)Oc1ccccc1C(=O)O", "C[C@@H](N)C(=O)O", "c1ccc2ccccc2c1", "CCO"]
|
|
150
|
+
summary = summarize_split_leakage(audit_split_leakage(LEAKY_TRAIN, test_smiles))
|
|
151
|
+
assert summary["n_test"] == 4
|
|
152
|
+
assert summary["exact"] == pytest.approx(0.25)
|
|
153
|
+
assert summary["same_connectivity"] == pytest.approx(0.5)
|
|
154
|
+
assert 0.0 <= summary["median_nearest_similarity"] <= 1.0
|
|
@@ -154,7 +154,7 @@ def test_gen_3d():
|
|
|
154
154
|
def test_get_spiro_atoms():
|
|
155
155
|
mol = Chem.MolFromSmiles("C1CC2(C1)CCC1(CCCC1)CC2")
|
|
156
156
|
spiro_atoms = uru.get_spiro_atoms(mol)
|
|
157
|
-
assert
|
|
157
|
+
assert spiro_atoms == [2, 6]
|
|
158
158
|
|
|
159
159
|
|
|
160
160
|
def test_max_ring_size():
|
|
@@ -184,31 +184,90 @@ def get_conformer_energies(mol: Mol) -> List[float]:
|
|
|
184
184
|
return [float(conf.GetProp("Energy")) for conf in mol.GetConformers()]
|
|
185
185
|
|
|
186
186
|
|
|
187
|
-
def
|
|
187
|
+
def _kabsch_rmsd(crd_1: np.ndarray, crd_2: np.ndarray) -> float:
|
|
188
|
+
"""RMSD between two equal-length coordinate sets after optimal superposition.
|
|
189
|
+
|
|
190
|
+
:param crd_1: (N, 3) reference coordinates
|
|
191
|
+
:param crd_2: (N, 3) probe coordinates, in the same atom order
|
|
192
|
+
:return: the RMSD after the probe has been rigidly superposed on the reference
|
|
193
|
+
"""
|
|
194
|
+
ref = crd_1 - crd_1.mean(axis=0)
|
|
195
|
+
prb = crd_2 - crd_2.mean(axis=0)
|
|
196
|
+
v, _, wt = np.linalg.svd(prb.T @ ref)
|
|
197
|
+
# Flip the least significant axis when the naive rotation is a reflection,
|
|
198
|
+
# which would otherwise superpose a structure onto its mirror image.
|
|
199
|
+
if np.linalg.det(v @ wt) < 0.0:
|
|
200
|
+
v[:, -1] *= -1.0
|
|
201
|
+
prb = prb @ (v @ wt)
|
|
202
|
+
return float(np.sqrt(np.mean(np.sum((ref - prb) ** 2, axis=1))))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def mcs_rmsd(mol_1: Mol, mol_2: Mol, id_1: int = 0, id_2: int = 0, align: bool = False,
|
|
206
|
+
timeout: Optional[int] = None, max_matches: int = 10000) -> Tuple[int, float]:
|
|
188
207
|
"""
|
|
189
208
|
Calculate the RMSD (Root Mean Square Deviation) between the MCS (Maximum Common Substructure) of two molecules.
|
|
190
209
|
|
|
210
|
+
The RMSD is symmetry corrected: every way the MCS can be mapped onto each molecule is
|
|
211
|
+
enumerated and the smallest RMSD is returned, so two poses that differ only by a symmetric
|
|
212
|
+
relabeling, such as a flipped phenyl, a rotated methyl, or the two oxygens of a
|
|
213
|
+
carboxylate, are recognized as the same arrangement rather than reported as far apart.
|
|
214
|
+
|
|
215
|
+
By default the two conformers are compared in the frame they arrive in, which is what
|
|
216
|
+
comparing docked or co-folded poses against a crystal structure requires: the receptor
|
|
217
|
+
defines a common frame and a pose that sits in the wrong place should score as wrong.
|
|
218
|
+
Pass ``align=True`` to superpose the MCS atoms first, which is what comparing free
|
|
219
|
+
conformers requires, where absolute position carries no meaning.
|
|
220
|
+
|
|
221
|
+
When both molecules have the same graph, ``align=True`` reproduces
|
|
222
|
+
``rdMolAlign.GetBestRMS(prb, ref, symmetrizeConjugatedTerminalGroups=False)``. RDKit's
|
|
223
|
+
conjugated-terminal-group symmetrization is not applied, and is not reachable from Python
|
|
224
|
+
outside ``GetBestRMS``, so the two oxygens of a carboxylic acid stay distinct here unless
|
|
225
|
+
the MCS itself makes them equivalent. Prefer ``GetBestRMS`` when the two molecules are the
|
|
226
|
+
same and that symmetrization is wanted; this function exists for the case ``GetBestRMS``
|
|
227
|
+
cannot handle, where the molecules differ and only a common substructure can be compared.
|
|
228
|
+
|
|
191
229
|
:param mol_1: First RDKit molecule
|
|
192
230
|
:param mol_2: Second RDKit molecule
|
|
193
231
|
:param id_1: Conformer ID for the first molecule
|
|
194
232
|
:param id_2: Conformer ID for the second molecule
|
|
233
|
+
:param align: If True, rigidly superpose the MCS atoms before measuring, discarding any
|
|
234
|
+
difference in absolute position and orientation. If False (the default) the
|
|
235
|
+
coordinates are compared as given.
|
|
236
|
+
:param timeout: Seconds to allow for the MCS search. ``None``, the default, lets it run to
|
|
237
|
+
completion. On timeout RDKit returns the largest substructure it found so
|
|
238
|
+
far, so a timeout yields a smaller MCS rather than an error.
|
|
239
|
+
:param max_matches: Cap on the number of MCS mappings enumerated per molecule. Highly
|
|
240
|
+
symmetric structures admit a great many, and the RMSD is minimized over
|
|
241
|
+
every pair, so the work grows as the product of the two counts. The cap
|
|
242
|
+
bounds that; raising it makes the search exhaustive on such structures.
|
|
195
243
|
:return: A tuple containing the number of MCS atoms and the RMSD value.
|
|
196
244
|
If the molecules share no common substructure, the RMSD is float("inf").
|
|
197
245
|
"""
|
|
198
|
-
mcs_res = FindMCS([mol_1, mol_2])
|
|
246
|
+
mcs_res = FindMCS([mol_1, mol_2]) if timeout is None else FindMCS([mol_1, mol_2], timeout=timeout)
|
|
199
247
|
num_mcs_atoms = mcs_res.numAtoms
|
|
248
|
+
if not num_mcs_atoms:
|
|
249
|
+
return 0, float("inf")
|
|
200
250
|
pat = Chem.MolFromSmarts(mcs_res.smartsString)
|
|
201
|
-
|
|
202
|
-
|
|
251
|
+
if pat is None:
|
|
252
|
+
return num_mcs_atoms, float("inf")
|
|
253
|
+
# uniquify must be off. It keeps one representative per symmetry class, which collapses
|
|
254
|
+
# exactly the mappings this minimum is taken over and leaves a symmetry-blind comparison.
|
|
255
|
+
match_1 = mol_1.GetSubstructMatches(pat, uniquify=False, maxMatches=max_matches)
|
|
256
|
+
match_2 = mol_2.GetSubstructMatches(pat, uniquify=False, maxMatches=max_matches)
|
|
257
|
+
if not match_1 or not match_2:
|
|
258
|
+
return num_mcs_atoms, float("inf")
|
|
259
|
+
crd_1 = mol_1.GetConformer(id_1).GetPositions()
|
|
260
|
+
crd_2 = mol_2.GetConformer(id_2).GetPositions()
|
|
203
261
|
min_rmsd = float("inf")
|
|
204
262
|
for m1 in match_1:
|
|
263
|
+
ref = crd_1[list(m1)]
|
|
205
264
|
for m2 in match_2:
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
265
|
+
prb = crd_2[list(m2)]
|
|
266
|
+
if align:
|
|
267
|
+
rmsd = _kabsch_rmsd(ref, prb)
|
|
268
|
+
else:
|
|
269
|
+
diff = ref - prb
|
|
270
|
+
rmsd = float(np.sqrt(np.mean(np.sum(diff ** 2, axis=1))))
|
|
212
271
|
min_rmsd = min(min_rmsd, rmsd)
|
|
213
272
|
return num_mcs_atoms, float(min_rmsd)
|
|
214
273
|
|
|
@@ -296,16 +296,17 @@ def get_spiro_atoms(mol):
|
|
|
296
296
|
"""Get atoms that are part of a spiro fusion
|
|
297
297
|
|
|
298
298
|
:param mol: input RDKit molecule
|
|
299
|
-
:return: a list of atom numbers for atoms that are the centers of spiro fusions
|
|
299
|
+
:return: a sorted list of atom numbers for atoms that are the centers of spiro fusions
|
|
300
300
|
"""
|
|
301
301
|
info = mol.GetRingInfo()
|
|
302
302
|
ring_sets = [set(x) for x in info.AtomRings()]
|
|
303
|
-
spiro_atoms =
|
|
303
|
+
spiro_atoms = set()
|
|
304
304
|
for i, j in itertools.combinations(ring_sets, 2):
|
|
305
305
|
i_and_j = (i.intersection(j))
|
|
306
306
|
if len(i_and_j) == 1:
|
|
307
|
-
spiro_atoms
|
|
308
|
-
|
|
307
|
+
spiro_atoms.update(i_and_j)
|
|
308
|
+
# AtomRings() order varies across RDKit versions, so sort for a stable result
|
|
309
|
+
return sorted(spiro_atoms)
|
|
309
310
|
|
|
310
311
|
|
|
311
312
|
def max_ring_size(mol):
|
|
@@ -2,7 +2,7 @@ from typing import Callable, List, Optional, Tuple, Union
|
|
|
2
2
|
|
|
3
3
|
import numpy as np
|
|
4
4
|
import pandas as pd
|
|
5
|
-
from rdkit import Chem
|
|
5
|
+
from rdkit import Chem, DataStructs
|
|
6
6
|
from rdkit.Chem import rdFingerprintGenerator
|
|
7
7
|
from rdkit.Chem.Scaffolds.MurckoScaffold import MurckoScaffoldSmiles
|
|
8
8
|
from rdkit.Chem.rdchem import Mol
|
|
@@ -10,7 +10,7 @@ from sklearn.cluster import KMeans
|
|
|
10
10
|
from sklearn.model_selection._split import _BaseKFold
|
|
11
11
|
from tqdm.auto import tqdm
|
|
12
12
|
from .descriptors import smi2numpy_fp
|
|
13
|
-
from .misc_utils import taylor_butina_clustering
|
|
13
|
+
from .misc_utils import get_largest_fragment, taylor_butina_clustering
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
class GroupKFoldShuffle(_BaseKFold):
|
|
@@ -210,6 +210,131 @@ def cross_validate(df: pd.DataFrame,
|
|
|
210
210
|
return pd.concat(fold_df_list)[output_cols]
|
|
211
211
|
|
|
212
212
|
|
|
213
|
+
def _leakage_keys(smiles_list: List[str], strip_salts: bool,
|
|
214
|
+
progress: bool) -> Tuple[List[Optional[str]], List[Optional[str]], List[Optional[Mol]]]:
|
|
215
|
+
"""InChIKey, Bemis-Murcko scaffold and parsed molecule for each input SMILES.
|
|
216
|
+
|
|
217
|
+
:param smiles_list: SMILES to key
|
|
218
|
+
:param strip_salts: keep only the largest fragment before keying
|
|
219
|
+
:param progress: show a progress bar
|
|
220
|
+
:return: a list of InChIKeys, a list of scaffolds and a list of molecules,
|
|
221
|
+
each holding None where the SMILES would not parse
|
|
222
|
+
"""
|
|
223
|
+
keys, scaffolds, mols = [], [], []
|
|
224
|
+
for smi in tqdm(smiles_list, disable=not progress, desc="keying molecules"):
|
|
225
|
+
mol = Chem.MolFromSmiles(smi)
|
|
226
|
+
if mol is None:
|
|
227
|
+
keys.append(None)
|
|
228
|
+
scaffolds.append(None)
|
|
229
|
+
mols.append(None)
|
|
230
|
+
continue
|
|
231
|
+
if strip_salts:
|
|
232
|
+
mol = get_largest_fragment(mol)
|
|
233
|
+
keys.append(Chem.MolToInchiKey(mol))
|
|
234
|
+
scaffolds.append(get_scaffold(mol))
|
|
235
|
+
mols.append(mol)
|
|
236
|
+
return keys, scaffolds, mols
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def audit_split_leakage(train_smiles: List[str], test_smiles: List[str],
|
|
240
|
+
similarity_cutoff: float = 0.9, strip_salts: bool = True,
|
|
241
|
+
radius: int = 2, n_bits: int = 2048,
|
|
242
|
+
progress: bool = False) -> pd.DataFrame:
|
|
243
|
+
"""
|
|
244
|
+
Check an existing train/test split for test molecules that are already in the training set.
|
|
245
|
+
|
|
246
|
+
This module builds splits; this function audits one it is handed, which is the case when the
|
|
247
|
+
split arrives with a public benchmark or from a collaborator. Each test molecule is checked
|
|
248
|
+
against the training set four ways, from strictest to loosest:
|
|
249
|
+
|
|
250
|
+
* ``exact``, an identical InChIKey. The same molecule on both sides.
|
|
251
|
+
* ``same_connectivity``, an identical first InChIKey block. That block encodes constitution
|
|
252
|
+
only, so it also catches a training molecule that differs just in stereochemistry or
|
|
253
|
+
protonation state: enantiomers, diastereomers, E/Z isomers and an acid against its
|
|
254
|
+
conjugate base all collapse onto it. It does not see through every tautomer, and it does
|
|
255
|
+
not see through salts and mixtures at all, which is what ``strip_salts`` is for.
|
|
256
|
+
* ``same_scaffold``, an identical Bemis-Murcko scaffold, via :func:`get_scaffold`.
|
|
257
|
+
* ``nearest_similarity``, the largest Morgan fingerprint Tanimoto to any training molecule,
|
|
258
|
+
with the training molecule that produced it. ``near_duplicate`` flags the ones at or above
|
|
259
|
+
``similarity_cutoff``. The fingerprint carries no chirality, so a pair of enantiomers
|
|
260
|
+
scores 1.0 here; that pair is already reported by ``same_connectivity``.
|
|
261
|
+
|
|
262
|
+
The first two are leakage outright: a model can score well on them without generalizing at
|
|
263
|
+
all. The last two are degrees of optimism rather than errors, and whether they matter depends
|
|
264
|
+
on what the split was built to measure, so they are reported rather than judged.
|
|
265
|
+
|
|
266
|
+
:param train_smiles: SMILES of the training set
|
|
267
|
+
:param test_smiles: SMILES of the test set, one row of output per entry
|
|
268
|
+
:param similarity_cutoff: Tanimoto at or above which a test molecule is flagged a near
|
|
269
|
+
duplicate of a training molecule
|
|
270
|
+
:param strip_salts: Reduce every molecule to its largest fragment before comparing, so a
|
|
271
|
+
salt of a training compound is recognized rather than missed. Counter
|
|
272
|
+
ions and solvates otherwise change the InChIKey outright.
|
|
273
|
+
:param radius: Morgan fingerprint radius used for the similarity column
|
|
274
|
+
:param n_bits: Morgan fingerprint length used for the similarity column
|
|
275
|
+
:param progress: Show progress bars, which is worth it on large training sets
|
|
276
|
+
:return: One row per test molecule, with columns ``test_smiles``, ``exact``,
|
|
277
|
+
``same_connectivity``, ``same_scaffold``, ``nearest_similarity``, ``nearest_train_smiles``
|
|
278
|
+
and ``near_duplicate``. A test SMILES that will not parse yields False flags, a NaN
|
|
279
|
+
similarity and None for the nearest training molecule.
|
|
280
|
+
"""
|
|
281
|
+
train_keys, train_scaffolds, train_mols = _leakage_keys(list(train_smiles), strip_salts, progress)
|
|
282
|
+
test_keys, test_scaffolds, test_mols = _leakage_keys(list(test_smiles), strip_salts, progress)
|
|
283
|
+
|
|
284
|
+
exact_lookup, connectivity_lookup, scaffold_set = {}, {}, set()
|
|
285
|
+
for smi, key, scaffold in zip(train_smiles, train_keys, train_scaffolds):
|
|
286
|
+
if key is None:
|
|
287
|
+
continue
|
|
288
|
+
exact_lookup.setdefault(key, smi)
|
|
289
|
+
connectivity_lookup.setdefault(key.split("-")[0], smi)
|
|
290
|
+
scaffold_set.add(scaffold)
|
|
291
|
+
|
|
292
|
+
generator = rdFingerprintGenerator.GetMorganGenerator(radius=radius, fpSize=n_bits)
|
|
293
|
+
train_fp_list = [generator.GetFingerprint(mol) for mol in train_mols if mol is not None]
|
|
294
|
+
train_fp_smiles = [smi for smi, mol in zip(train_smiles, train_mols) if mol is not None]
|
|
295
|
+
|
|
296
|
+
rows = []
|
|
297
|
+
for smi, key, scaffold, mol in tqdm(list(zip(test_smiles, test_keys, test_scaffolds, test_mols)),
|
|
298
|
+
disable=not progress, desc="auditing test set"):
|
|
299
|
+
nearest_similarity, nearest_smiles = np.nan, None
|
|
300
|
+
if mol is not None and train_fp_list:
|
|
301
|
+
similarity = np.array(DataStructs.BulkTanimotoSimilarity(generator.GetFingerprint(mol),
|
|
302
|
+
train_fp_list))
|
|
303
|
+
best = int(similarity.argmax())
|
|
304
|
+
nearest_similarity, nearest_smiles = float(similarity[best]), train_fp_smiles[best]
|
|
305
|
+
rows.append({
|
|
306
|
+
"test_smiles": smi,
|
|
307
|
+
"exact": key is not None and key in exact_lookup,
|
|
308
|
+
"same_connectivity": key is not None and key.split("-")[0] in connectivity_lookup,
|
|
309
|
+
"same_scaffold": scaffold is not None and scaffold in scaffold_set,
|
|
310
|
+
"nearest_similarity": nearest_similarity,
|
|
311
|
+
"nearest_train_smiles": nearest_smiles,
|
|
312
|
+
"near_duplicate": bool(nearest_similarity >= similarity_cutoff)
|
|
313
|
+
if nearest_similarity == nearest_similarity else False,
|
|
314
|
+
})
|
|
315
|
+
audit_df = pd.DataFrame(rows)
|
|
316
|
+
# A column of strings with a gap in it becomes NaN on construction. Put the None back so
|
|
317
|
+
# the absence of a nearest neighbor reads the same whatever else the column holds.
|
|
318
|
+
nearest = audit_df["nearest_train_smiles"]
|
|
319
|
+
audit_df["nearest_train_smiles"] = nearest.astype(object).where(nearest.notna(), None)
|
|
320
|
+
return audit_df
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def summarize_split_leakage(audit_df: pd.DataFrame) -> pd.Series:
|
|
324
|
+
"""
|
|
325
|
+
Reduce the output of :func:`audit_split_leakage` to the fraction of the test set each check hit.
|
|
326
|
+
|
|
327
|
+
:param audit_df: the DataFrame returned by :func:`audit_split_leakage`
|
|
328
|
+
:return: a Series indexed by check name, holding the fraction of test rows each one flagged,
|
|
329
|
+
plus ``n_test`` and the median nearest-neighbor similarity
|
|
330
|
+
"""
|
|
331
|
+
checks = ["exact", "same_connectivity", "same_scaffold", "near_duplicate"]
|
|
332
|
+
summary = {name: float(audit_df[name].mean()) for name in checks}
|
|
333
|
+
summary["median_nearest_similarity"] = float(audit_df["nearest_similarity"].median())
|
|
334
|
+
summary["n_test"] = int(len(audit_df))
|
|
335
|
+
return pd.Series(summary)
|
|
336
|
+
|
|
337
|
+
|
|
213
338
|
__all__ = [
|
|
214
339
|
"GroupKFoldShuffle",
|
|
215
340
|
"get_scaffold",
|
|
@@ -218,4 +343,6 @@ __all__ = [
|
|
|
218
343
|
"get_bemis_murcko_clusters",
|
|
219
344
|
"get_kmeans_clusters",
|
|
220
345
|
"cross_validate",
|
|
346
|
+
"audit_split_leakage",
|
|
347
|
+
"summarize_split_leakage",
|
|
221
348
|
]
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import numpy as np
|
|
2
|
-
import pandas as pd
|
|
3
|
-
import pytest
|
|
4
|
-
|
|
5
|
-
import useful_rdkit_utils as uru
|
|
6
|
-
from useful_rdkit_utils.split_utils import GroupKFoldShuffle
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
class _FakeModel:
|
|
10
|
-
"""Minimal stand-in for the WrapperFactory-created models."""
|
|
11
|
-
|
|
12
|
-
def __init__(self, y_col):
|
|
13
|
-
self.y_col = y_col
|
|
14
|
-
|
|
15
|
-
def validate(self, train, test):
|
|
16
|
-
return np.full(len(test), train[self.y_col].mean())
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
@pytest.fixture
|
|
20
|
-
def small_df():
|
|
21
|
-
rng = np.random.default_rng(0)
|
|
22
|
-
smiles = ["c1ccccc1", "CCO", "CCN", "CCOC", "c1ccc(O)cc1", "c1ccc(N)cc1",
|
|
23
|
-
"Cc1ccccc1", "NCc1ccccc1", "OCC1=CC=CC=C1", "CC(C)O"] * 4
|
|
24
|
-
n = len(smiles)
|
|
25
|
-
return pd.DataFrame({"SMILES": smiles, "row_id": np.arange(n), "y": rng.normal(size=n)})
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
def test_group_kfold_shuffle_error_when_too_many_splits():
|
|
29
|
-
kf = GroupKFoldShuffle(n_splits=10, shuffle=True)
|
|
30
|
-
with pytest.raises(ValueError):
|
|
31
|
-
_ = list(kf.split(X=np.zeros(5), groups=[0, 1, 2]))
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
def test_cross_validate_nested(small_df):
|
|
35
|
-
n_outer, n_inner = 3, 2
|
|
36
|
-
model_list = [("fake", _FakeModel)]
|
|
37
|
-
group_list = [("random", uru.get_random_clusters)]
|
|
38
|
-
res = uru.cross_validate(small_df, model_list, "y", group_list,
|
|
39
|
-
n_outer=n_outer, n_inner=n_inner, random_state=1)
|
|
40
|
-
|
|
41
|
-
assert "fake" in res.columns
|
|
42
|
-
assert {"dset", "group", "fold"} <= set(res.columns)
|
|
43
|
-
|
|
44
|
-
test_df = res.query("dset == 'test'")
|
|
45
|
-
folds_seen = set(test_df["fold"].unique())
|
|
46
|
-
# per outer round: n_inner inner folds plus the outer test evaluation
|
|
47
|
-
expected = {i * (n_inner + 1) + k for i in range(n_outer) for k in range(n_inner + 1)}
|
|
48
|
-
assert folds_seen == expected
|
|
49
|
-
|
|
50
|
-
# no leakage: the outer test rows must not appear in the inner training rows of the same round
|
|
51
|
-
for i in range(n_outer):
|
|
52
|
-
inner_folds = set(range(i * (n_inner + 1), i * (n_inner + 1) + n_inner))
|
|
53
|
-
train_rows = res.query("dset == 'train'")
|
|
54
|
-
train_rows = train_rows[train_rows["fold"].isin(inner_folds)]
|
|
55
|
-
outer_test_folds = {i * (n_inner + 1) + n_inner}
|
|
56
|
-
outer_rows = test_df[test_df["fold"].isin(outer_test_folds)]
|
|
57
|
-
assert not set(train_rows["row_id"]) & set(outer_rows["row_id"])
|
|
58
|
-
|
|
59
|
-
# every test row has a model prediction, and each fold label has at least one test row
|
|
60
|
-
assert test_df["fake"].notna().all()
|
|
61
|
-
assert test_df.groupby("fold").ngroups == n_outer * (n_inner + 1)
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
def test_get_scaffold_acyclic():
|
|
65
|
-
assert uru.get_scaffold("CCCC") == "CCCC"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/docs/source/descriptor_preprocessor.rst
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/demo_useful_rdkit_utils.ipynb
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/parallel_conformer_generation.ipynb
RENAMED
|
File without changes
|
{useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/notebooks/sort_and_slice_ecfp_featuriser.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/build_ring_dictionary.py
RENAMED
|
File without changes
|
{useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/descriptor_preprocessor.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{useful_rdkit_utils-2.0.1 → useful_rdkit_utils-2.0.2}/useful_rdkit_utils/model_comparison.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|