useful-rdkit-utils 2.0.2__tar.gz → 2.0.3__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.2 → useful_rdkit_utils-2.0.3}/CHANGELOG.md +46 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/PKG-INFO +2 -2
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/pyproject.toml +2 -2
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_audit_fixes.py +50 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_descriptor_preprocessor.py +32 -1
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_geometry.py +12 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_model_comparison.py +21 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_ring_systems.py +24 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_sali.py +24 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_scaffold_finder.py +16 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_split_utils.py +82 -4
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_useful_rdkit_utils.py +7 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/__init__.py +1 -1
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/descriptor_preprocessor.py +35 -28
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/geometry.py +2 -2
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/misc_utils.py +7 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/model_comparison.py +16 -5
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/pandas_utils.py +4 -1
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/reactions.py +2 -1
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/reos.py +16 -11
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/ring_systems.py +14 -3
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/sali.py +14 -2
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/scaffold_finder.py +11 -1
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/split_utils.py +47 -24
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/stat_utils.py +6 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/.gitattributes +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/.github/CONTRIBUTING.md +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/.github/PUBLISHING.md +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/.github/workflows/CI.yaml +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/.github/workflows/publish.yaml +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/.gitignore +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/.readthedocs.yaml +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/CODE_OF_CONDUCT.md +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/LICENSE +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/MANIFEST.in +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/README.md +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/data/chembl_ring_systems.csv +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/data/test.smi +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/Makefile +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/cli.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/conf.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/descriptor_preprocessor.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/descriptors.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/geometry.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/index.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/installation.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/jupyter.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/misc_utils.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/model_comparison.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/optional.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/pandas.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/reactions.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/reos.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/ring_systems.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/sali.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/scaffold_finder.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/seaborn.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/silly_walks.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/split_utils.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/stats.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/docs/source/units.rst +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/nikki.png +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/README.md +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/bootstrap_AUC.ipynb +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/catboost_wrapper.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/compare_mordred_rdkit.ipynb +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/data/biogen_logS.csv +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/demo_REOS.ipynb +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/demo_cross_validate.ipynb +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/demo_descriptors.ipynb +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/demo_ring_systems.ipynb +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/demo_useful_rdkit_utils.ipynb +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/explore_functional_group_filters.ipynb +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/ffnn.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/lgbm_wrapper.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/model_comparison.ipynb +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/parallel_conformer_generation.ipynb +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/sort_and_slice_ecfp_featuriser.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/notebooks/zinc_sample.smi +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/__init__.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test.smi +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_chemreps.txt +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_descriptors.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_reactions.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_reos.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/tests/test_silly_walks.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/build_ring_dictionary.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/descriptors.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/jupyter_utils.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/optional.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/seaborn_utils.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/silly_walks.py +0 -0
- {useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/units.py +0 -0
|
@@ -3,6 +3,52 @@ All notable changes to this project will be documented in this file.
|
|
|
3
3
|
|
|
4
4
|
## [Unreleased]
|
|
5
5
|
|
|
6
|
+
## [2.0.3] - 2026-12-06
|
|
7
|
+
### Changed
|
|
8
|
+
- `DescriptorPreprocessor` validates input with scikit-learn's `validate_data`. When it is fit
|
|
9
|
+
on a DataFrame, `transform` now rejects a DataFrame whose column names or order differ, where
|
|
10
|
+
it previously scaled the values silently against the wrong columns. It sets
|
|
11
|
+
`feature_names_in_`, and `get_feature_names_out()` returns the training column names. The
|
|
12
|
+
error for a wrong number of columns now uses scikit-learn's wording ("... expecting 6
|
|
13
|
+
features"), so code that matched the old "Expected 6 features" message needs updating.
|
|
14
|
+
- `GroupKFoldShuffle.split()`, and through it `cross_validate()`, raise `ValueError` for group
|
|
15
|
+
labels that are missing (NaN/NA), that do not match the number of samples, or that give more
|
|
16
|
+
than one label per sample. Missing labels previously left a row in training in every fold,
|
|
17
|
+
and a short label list silently dropped rows.
|
|
18
|
+
- Excluded rdkit 2026.9.3 from the dependencies as well as 2026.9.2. It still raises
|
|
19
|
+
`RuntimeError: bad any cast` from `MurckoDecompose()` on macOS arm64 (rdkit/rdkit#9836).
|
|
20
|
+
### Fixed
|
|
21
|
+
- `DescriptorPreprocessor` drops columns whose values are all identical even when floating-point
|
|
22
|
+
rounding gives them a tiny positive variance, such as a column of 0.1s.
|
|
23
|
+
- `RingSystemLookup(ignore_stereo=True)` no longer requests a data file that does not exist,
|
|
24
|
+
and it sums counts across stereoisomers instead of reporting 0 for ring systems with
|
|
25
|
+
stereocenters.
|
|
26
|
+
- `get_scaffold()` canonicalizes acyclic molecules, so `"OCC"` and `"CCO"` share a scaffold
|
|
27
|
+
cluster.
|
|
28
|
+
- `audit_split_leakage()`:
|
|
29
|
+
- Treats an empty SMILES as missing.
|
|
30
|
+
- Handles an empty test set without dividing by zero, and gives that empty result boolean
|
|
31
|
+
flag columns so filtering on them works.
|
|
32
|
+
- No longer reports `exact` or `same_connectivity` matches between molecules for which InChI
|
|
33
|
+
could not generate a key, such as fragments with dummy atoms.
|
|
34
|
+
- `REOS.pandas_smiles()` and `pandas_mols()` handle unparseable input, and an invalid rule set
|
|
35
|
+
name now raises an error even when valid names are passed with it.
|
|
36
|
+
- `enumerate_library_sample()` no longer overflows int64 and returns nothing for very large
|
|
37
|
+
combinatorial libraries.
|
|
38
|
+
- `remove_dummy_atoms()` no longer fails to kekulize N-substituted pyrrole-like rings, which
|
|
39
|
+
also affected `align_mols_to_template()`.
|
|
40
|
+
- `get_center()` works after conformer 0 has been removed.
|
|
41
|
+
- `get_performance_stats()` scores each `(group, fold)` pair separately instead of pooling
|
|
42
|
+
folds with the same number from different grouping strategies.
|
|
43
|
+
- `plot_sali_pairs()` accepts the output of `calculate_sali()` when custom SMILES and activity
|
|
44
|
+
column names are used.
|
|
45
|
+
- `calculate_sali()` returns an empty DataFrame with the usual columns when only one molecule
|
|
46
|
+
parses.
|
|
47
|
+
- `find_scaffolds()` returns empty tables with the usual columns for an empty input, instead
|
|
48
|
+
of raising.
|
|
49
|
+
- `add_molecule_and_errors()` adds its columns to an empty DataFrame, instead of raising.
|
|
50
|
+
- `pearson_confidence()` handles r = ±1 instead of raising in `math.atanh`.
|
|
51
|
+
|
|
6
52
|
## [2.0.2] - 2026-11-29
|
|
7
53
|
### Fixed
|
|
8
54
|
- Excluded rdkit 2026.9.2 from the dependencies. Its macOS arm64 PyPI wheels raise
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: useful_rdkit_utils
|
|
3
|
-
Version: 2.0.
|
|
3
|
+
Version: 2.0.3
|
|
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!=2026.9.2
|
|
21
|
+
Requires-Dist: rdkit!=2026.9.2,!=2026.9.3
|
|
22
22
|
Requires-Dist: scikit-learn
|
|
23
23
|
Requires-Dist: scipy
|
|
24
24
|
Requires-Dist: seaborn
|
|
@@ -21,8 +21,8 @@ classifiers = [
|
|
|
21
21
|
]
|
|
22
22
|
dependencies = [
|
|
23
23
|
'numpy',
|
|
24
|
-
# 2026.9.2 macOS arm64 PyPI wheels break MurckoDecompose (rdkit/rdkit#9836)
|
|
25
|
-
'rdkit!=2026.9.2',
|
|
24
|
+
# 2026.9.2 and 2026.9.3 macOS arm64 PyPI wheels break MurckoDecompose (rdkit/rdkit#9836)
|
|
25
|
+
'rdkit!=2026.9.2,!=2026.9.3',
|
|
26
26
|
'pandas',
|
|
27
27
|
'pystow',
|
|
28
28
|
'matplotlib',
|
|
@@ -70,6 +70,14 @@ def test_enumerate_library_sample_stops_when_combinations_are_exhausted(reagent_
|
|
|
70
70
|
assert 0 < len(df) <= 25
|
|
71
71
|
|
|
72
72
|
|
|
73
|
+
def test_enumerate_library_sample_does_not_overflow_int64_on_four_component_pools():
|
|
74
|
+
"""60000^4 exceeds 2^63 - 1, which overflowed np.prod to a negative total."""
|
|
75
|
+
rxn = AllChem.ReactionFromSmarts("[C:1].[C:2].[C:3].[C:4]>>[C:1][C:2][C:3][C:4]")
|
|
76
|
+
mol = _named_mol("C", "m")
|
|
77
|
+
df = uru.enumerate_library_sample(rxn, [[mol] * 60000] * 4, num_to_generate=3)
|
|
78
|
+
assert len(df) == 3
|
|
79
|
+
|
|
80
|
+
|
|
73
81
|
def test_enumerate_library_sample_handles_duplicate_reagent_names():
|
|
74
82
|
"""Reagent names are not unique, so combinations must be tracked by position.
|
|
75
83
|
|
|
@@ -342,6 +350,15 @@ def test_generate_fragments_reports_an_empty_molecule():
|
|
|
342
350
|
uru.generate_fragments(Chem.MolFromSmiles(""))
|
|
343
351
|
|
|
344
352
|
|
|
353
|
+
def test_remove_dummy_atoms_and_align_mols_to_template_handle_aromatic_heteroatoms():
|
|
354
|
+
"""Removing * from [*]n1cccc1 or [*]n1ccnc1 must restore the NH and kekulize."""
|
|
355
|
+
cleaned = uru.remove_dummy_atoms(Chem.MolFromSmiles("[*]n1cccc1"))
|
|
356
|
+
assert Chem.MolToSmiles(cleaned) == "c1cc[nH]c1"
|
|
357
|
+
aligned = uru.align_mols_to_template("[*]n1ccnc1", ["Cn1ccnc1", "CCn1ccnc1"])
|
|
358
|
+
assert len(aligned) == 2
|
|
359
|
+
assert all(m.GetNumConformers() == 1 for m in aligned)
|
|
360
|
+
|
|
361
|
+
|
|
345
362
|
# --------------------------------------------------------------------------
|
|
346
363
|
# model_comparison.py
|
|
347
364
|
# --------------------------------------------------------------------------
|
|
@@ -454,6 +471,16 @@ def test_add_molecule_and_errors_round_trip():
|
|
|
454
471
|
assert df.ROMol[1] is None
|
|
455
472
|
|
|
456
473
|
|
|
474
|
+
def test_add_molecule_and_errors_adds_columns_to_empty_filter_result():
|
|
475
|
+
df = pd.DataFrame({"structure": ["CCO"]}, index=pd.Index(["sample"], name="id"))
|
|
476
|
+
filtered = df.loc[df["structure"] == "CCC"].copy()
|
|
477
|
+
|
|
478
|
+
uru.add_molecule_and_errors(filtered, "structure", "molecule", "diagnostic")
|
|
479
|
+
|
|
480
|
+
assert list(filtered.columns) == ["structure", "molecule", "diagnostic"]
|
|
481
|
+
pd.testing.assert_index_equal(filtered.index, df.index[:0])
|
|
482
|
+
|
|
483
|
+
|
|
457
484
|
# --------------------------------------------------------------------------
|
|
458
485
|
# optional.py
|
|
459
486
|
# --------------------------------------------------------------------------
|
|
@@ -620,3 +647,26 @@ def test_max_possible_correlation():
|
|
|
620
647
|
# a smaller experimental error must permit a higher achievable correlation
|
|
621
648
|
assert uru.max_possible_correlation(values, error=0.1, cycles=20) > \
|
|
622
649
|
uru.max_possible_correlation(values, error=1.0, cycles=20)
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def test_reos_pandas_handles_unparseable_inputs_and_rejects_unknown_rule_sets(tmp_path):
|
|
653
|
+
rules_csv = tmp_path / "rules.csv"
|
|
654
|
+
rules_csv.write_text(
|
|
655
|
+
"rule_id,description,rule_set_name,priority,max,smarts\n"
|
|
656
|
+
"1,acid_chloride,Glaxo,8,0,C(=O)Cl\n"
|
|
657
|
+
)
|
|
658
|
+
reos = uru.REOS.__new__(uru.REOS)
|
|
659
|
+
reos.output_smarts = False
|
|
660
|
+
reos.read_rules(str(rules_csv), active_rules=["Glaxo"])
|
|
661
|
+
|
|
662
|
+
with pytest.raises(ValueError, match="not available"):
|
|
663
|
+
reos.set_active_rule_sets(["Glaxo", "NoSuchRuleSet"])
|
|
664
|
+
|
|
665
|
+
df_bad_only = reos.pandas_smiles(["not_a_smiles"])
|
|
666
|
+
assert list(df_bad_only.columns) == ["rule_set_name", "description"]
|
|
667
|
+
assert df_bad_only.isna().all().all()
|
|
668
|
+
|
|
669
|
+
df_mixed = reos.pandas_mols([None, Chem.MolFromSmiles("CC(=O)Cl"), Chem.MolFromSmiles("CCO")])
|
|
670
|
+
assert df_mixed.loc[0].isna().all()
|
|
671
|
+
assert tuple(df_mixed.loc[1]) == ("Glaxo", "acid_chloride")
|
|
672
|
+
assert tuple(df_mixed.loc[2]) == ("ok", "ok")
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import doctest
|
|
2
2
|
|
|
3
3
|
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
4
5
|
import pytest
|
|
5
6
|
from sklearn.exceptions import NotFittedError
|
|
6
7
|
from sklearn.pipeline import Pipeline
|
|
@@ -50,10 +51,19 @@ def test_transform_applies_the_training_imputation(descriptor_matrix):
|
|
|
50
51
|
|
|
51
52
|
def test_transform_rejects_a_different_column_count(descriptor_matrix):
|
|
52
53
|
pre = DescriptorPreprocessor().fit(descriptor_matrix)
|
|
53
|
-
with pytest.raises(ValueError, match="
|
|
54
|
+
with pytest.raises(ValueError, match="expecting 6 features"):
|
|
54
55
|
pre.transform(np.zeros((3, 5)))
|
|
55
56
|
|
|
56
57
|
|
|
58
|
+
@pytest.mark.parametrize("columns", [["LogP", "MolWt"], ["MolWt", "TPSA"]])
|
|
59
|
+
def test_transform_rejects_changed_dataframe_columns(columns):
|
|
60
|
+
descriptors = pd.DataFrame({"MolWt": [80.0, 120.0], "LogP": [1.0, 3.0]})
|
|
61
|
+
pre = DescriptorPreprocessor().fit(descriptors)
|
|
62
|
+
np.testing.assert_allclose(pre.transform(descriptors), [[-1.0, -1.0], [1.0, 1.0]])
|
|
63
|
+
with pytest.raises(ValueError, match="feature names"):
|
|
64
|
+
pre.transform(pd.DataFrame([[1.0, 80.0]], columns=columns))
|
|
65
|
+
|
|
66
|
+
|
|
57
67
|
def test_transform_before_fit_raises(descriptor_matrix):
|
|
58
68
|
with pytest.raises(NotFittedError):
|
|
59
69
|
DescriptorPreprocessor().transform(descriptor_matrix)
|
|
@@ -100,6 +110,16 @@ def test_variance_threshold_drops_near_constant_columns():
|
|
|
100
110
|
assert list(pre.kept_indices_) == [0]
|
|
101
111
|
|
|
102
112
|
|
|
113
|
+
def test_variance_filter_drops_fractional_constants():
|
|
114
|
+
descriptors = np.column_stack([
|
|
115
|
+
[0.0, 1.0, 2.0, 3.0],
|
|
116
|
+
[0.1, 0.1, 0.1, np.nan],
|
|
117
|
+
[0.1, 0.1, 0.1, 0.1 + 1e-12],
|
|
118
|
+
])
|
|
119
|
+
pre = DescriptorPreprocessor(max_nan_fraction=0.25).fit(descriptors)
|
|
120
|
+
assert list(pre.kept_indices_) == [0, 2]
|
|
121
|
+
|
|
122
|
+
|
|
103
123
|
def test_get_feature_names_out(descriptor_matrix):
|
|
104
124
|
pre = DescriptorPreprocessor().fit(descriptor_matrix)
|
|
105
125
|
assert list(pre.get_feature_names_out()) == ["x0", "x1", "x3", "x5"]
|
|
@@ -107,6 +127,17 @@ def test_get_feature_names_out(descriptor_matrix):
|
|
|
107
127
|
assert list(pre.get_feature_names_out(names)) == ["MolWt", "LogP", "TPSA", "HBD"]
|
|
108
128
|
|
|
109
129
|
|
|
130
|
+
def test_get_feature_names_out_preserves_dataframe_names_after_filtering(descriptor_matrix):
|
|
131
|
+
names = ["MolWt", "LogP", "Const", "TPSA", "Sparse", "HBD"]
|
|
132
|
+
pre = DescriptorPreprocessor().fit(pd.DataFrame(descriptor_matrix, columns=names))
|
|
133
|
+
kept = ["MolWt", "LogP", "TPSA", "HBD"]
|
|
134
|
+
assert list(pre.get_feature_names_out()) == kept
|
|
135
|
+
assert list(pre.get_feature_names_out(names)) == kept
|
|
136
|
+
with pytest.raises(ValueError, match="feature_names_in_"):
|
|
137
|
+
pre.get_feature_names_out(names[::-1])
|
|
138
|
+
assert list(pre.fit(descriptor_matrix).get_feature_names_out()) == ["x0", "x1", "x3", "x5"]
|
|
139
|
+
|
|
140
|
+
|
|
110
141
|
def test_get_feature_names_out_checks_length(descriptor_matrix):
|
|
111
142
|
pre = DescriptorPreprocessor().fit(descriptor_matrix)
|
|
112
143
|
with pytest.raises(ValueError, match="input_features has length"):
|
|
@@ -40,6 +40,18 @@ def test_get_center(benzene):
|
|
|
40
40
|
assert center.shape == (3,)
|
|
41
41
|
|
|
42
42
|
|
|
43
|
+
def test_get_center_after_removing_conformer_zero():
|
|
44
|
+
mol = Chem.MolFromSmiles("CC")
|
|
45
|
+
mol.AddConformer(Chem.Conformer(2), assignId=True)
|
|
46
|
+
conformer = Chem.Conformer(2)
|
|
47
|
+
conformer.SetAtomPosition(0, (1.0, 2.0, 3.0))
|
|
48
|
+
conformer.SetAtomPosition(1, (3.0, 4.0, 5.0))
|
|
49
|
+
mol.AddConformer(conformer, assignId=True)
|
|
50
|
+
mol.RemoveConformer(0)
|
|
51
|
+
|
|
52
|
+
np.testing.assert_allclose(get_center(mol), [2.0, 3.0, 4.0])
|
|
53
|
+
|
|
54
|
+
|
|
43
55
|
def test_get_shape_moments(benzene):
|
|
44
56
|
npr1, npr2 = get_shape_moments(benzene)
|
|
45
57
|
assert isinstance(npr1, float)
|
|
@@ -101,6 +101,27 @@ def test_get_performance_stats(cv_results):
|
|
|
101
101
|
assert (mae_df["mae"] >= 0).all()
|
|
102
102
|
|
|
103
103
|
|
|
104
|
+
def test_get_performance_stats_keeps_groups_with_the_same_fold_separate():
|
|
105
|
+
results = pd.DataFrame({
|
|
106
|
+
"group": ["random", "random", "scaffold", "scaffold"],
|
|
107
|
+
"fold": [0, 0, 0, 0],
|
|
108
|
+
"dset": ["test", "test", "test", "test"],
|
|
109
|
+
"y": [0.0, 2.0, 10.0, 12.0],
|
|
110
|
+
"model": [0.0, 2.0, 12.0, 10.0],
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
r2, mae = uru.get_performance_stats(results, y_col="y", method_list=["model"])
|
|
114
|
+
|
|
115
|
+
assert r2.set_index(["group", "fold", "method"])["r2"].to_dict() == {
|
|
116
|
+
("random", 0, "model"): 1.0,
|
|
117
|
+
("scaffold", 0, "model"): -3.0,
|
|
118
|
+
}
|
|
119
|
+
assert mae.set_index(["group", "fold", "method"])["mae"].to_dict() == {
|
|
120
|
+
("random", 0, "model"): 0.0,
|
|
121
|
+
("scaffold", 0, "model"): 2.0,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
104
125
|
def test_make_tukey_plot_r2(cv_results):
|
|
105
126
|
r2_df, _ = uru.get_performance_stats(
|
|
106
127
|
cv_results, y_col="y", method_list=["method_a", "method_b", "method_c"]
|
|
@@ -57,3 +57,27 @@ def test_ring_system_lookup(tmp_path):
|
|
|
57
57
|
output_filename = os.path.join(tmp_path, "ring_freq_test.csv")
|
|
58
58
|
df.to_csv(output_filename, index=False)
|
|
59
59
|
assert os.path.exists(output_filename)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_ring_system_lookup_ignore_stereo(monkeypatch):
|
|
63
|
+
ring_csv = os.path.join(REPO_DIR, "data", "chembl_ring_systems.csv")
|
|
64
|
+
# Present in chembl_ring_systems.csv only with stereochemistry (no achiral row).
|
|
65
|
+
bicyclic = "C1CO[C@@H]2CCN[C@@H]2C1"
|
|
66
|
+
stereo_lookup = uru.RingSystemLookup(ring_file=ring_csv, ignore_stereo=False)
|
|
67
|
+
nostereo_lookup = uru.RingSystemLookup(ring_file=ring_csv, ignore_stereo=True)
|
|
68
|
+
stereo_count = stereo_lookup.process_smiles(bicyclic)[0][1]
|
|
69
|
+
nostereo_count = nostereo_lookup.process_smiles(bicyclic)[0][1]
|
|
70
|
+
assert stereo_count >= 532
|
|
71
|
+
assert nostereo_count >= stereo_count
|
|
72
|
+
|
|
73
|
+
captured_urls = []
|
|
74
|
+
monkeypatch.setattr(
|
|
75
|
+
uru.ring_systems.pystow,
|
|
76
|
+
"ensure",
|
|
77
|
+
lambda *args, **kwargs: captured_urls.append(kwargs["url"]) or ring_csv,
|
|
78
|
+
)
|
|
79
|
+
default_nostereo = uru.RingSystemLookup(ignore_stereo=True)
|
|
80
|
+
assert captured_urls == [
|
|
81
|
+
"https://raw.githubusercontent.com/PatWalters/useful_rdkit_utils/refs/heads/master/data/chembl_ring_systems.csv"
|
|
82
|
+
]
|
|
83
|
+
assert default_nostereo.process_smiles(bicyclic)[0][1] == nostereo_count
|
|
@@ -45,6 +45,15 @@ def test_calculate_sali_custom_column_names():
|
|
|
45
45
|
assert len(result) == 3
|
|
46
46
|
|
|
47
47
|
|
|
48
|
+
def test_calculate_sali_preserves_columns_with_one_molecule(small_dataset):
|
|
49
|
+
dataset = small_dataset.rename(columns={"SMILES": "smi", "Activity": "value"})
|
|
50
|
+
pairs = uru.calculate_sali(dataset, smiles_col="smi", activity_col="value")
|
|
51
|
+
empty = uru.calculate_sali(dataset.iloc[:1], smiles_col="smi", activity_col="value")
|
|
52
|
+
|
|
53
|
+
assert empty.empty
|
|
54
|
+
assert empty.columns.equals(pairs.columns)
|
|
55
|
+
|
|
56
|
+
|
|
48
57
|
def test_plot_sali_pairs_returns_image(small_dataset):
|
|
49
58
|
sali_df = uru.calculate_sali(small_dataset)
|
|
50
59
|
img = uru.plot_sali_pairs(
|
|
@@ -56,6 +65,21 @@ def test_plot_sali_pairs_returns_image(small_dataset):
|
|
|
56
65
|
assert img is not None
|
|
57
66
|
|
|
58
67
|
|
|
68
|
+
@pytest.mark.parametrize("use_explicit_pair_columns", [False, True])
|
|
69
|
+
def test_plot_sali_pairs_with_custom_smiles_column(small_dataset, use_explicit_pair_columns):
|
|
70
|
+
dataset = small_dataset.rename(columns={"SMILES": "smi", "Activity": "value"})
|
|
71
|
+
pairs = uru.calculate_sali(dataset, smiles_col="smi", activity_col="value")
|
|
72
|
+
if use_explicit_pair_columns:
|
|
73
|
+
pairs = pairs.rename(columns={"SMILES_1": "smi_1", "SMILES_2": "smi_2"})
|
|
74
|
+
pairs["SMILES_1"] = pairs["SMILES_2"] = "invalid"
|
|
75
|
+
|
|
76
|
+
image = uru.plot_sali_pairs(
|
|
77
|
+
pairs, smiles_col="smi", activity_col="value",
|
|
78
|
+
similarity_cutoff=0.0, delta_activity_cutoff=0.0,
|
|
79
|
+
)
|
|
80
|
+
assert image is not None
|
|
81
|
+
|
|
82
|
+
|
|
59
83
|
def test_plot_sali_pairs_with_swap(small_dataset):
|
|
60
84
|
"""Force a swap by including pairs where Activity_2 > Activity_1."""
|
|
61
85
|
sali_df = uru.calculate_sali(small_dataset)
|
|
@@ -47,6 +47,22 @@ def test_find_scaffolds(small_series):
|
|
|
47
47
|
assert scaffold_df.iloc[0]["Count"] >= 2
|
|
48
48
|
|
|
49
49
|
|
|
50
|
+
def test_find_scaffolds_after_filtering_all_rows(small_series):
|
|
51
|
+
series = small_series.rename(columns={"SMILES": "structure", "Name": "label"})
|
|
52
|
+
filtered = series.loc[series["pIC50"] > 10]
|
|
53
|
+
|
|
54
|
+
mol_df, scaffold_df = uru.find_scaffolds(
|
|
55
|
+
filtered, smiles_col="structure", name_col="label", disable_progress=True
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
assert mol_df.empty
|
|
59
|
+
assert mol_df.columns.tolist() == ["Scaffold", "NumAtoms", "NumRgroups", "Name", "SMILES"]
|
|
60
|
+
assert mol_df.select_dtypes("number").columns.tolist() == ["NumAtoms", "NumRgroups"]
|
|
61
|
+
assert scaffold_df.empty
|
|
62
|
+
assert scaffold_df.columns.tolist() == ["Scaffold", "Count", "NumAtoms"]
|
|
63
|
+
assert scaffold_df.select_dtypes("number").columns.tolist() == ["Count", "NumAtoms"]
|
|
64
|
+
|
|
65
|
+
|
|
50
66
|
def test_get_molecules_with_scaffold(small_series):
|
|
51
67
|
mol_df, scaffold_df = uru.find_scaffolds(small_series, disable_progress=True)
|
|
52
68
|
top_scaffold = scaffold_df.iloc[0]["Scaffold"]
|
|
@@ -31,8 +31,32 @@ def small_df():
|
|
|
31
31
|
|
|
32
32
|
def test_group_kfold_shuffle_error_when_too_many_splits():
|
|
33
33
|
kf = GroupKFoldShuffle(n_splits=10, shuffle=True)
|
|
34
|
-
with pytest.raises(ValueError):
|
|
35
|
-
|
|
34
|
+
with pytest.raises(ValueError, match="number of groups"):
|
|
35
|
+
list(kf.split(X=np.zeros(3), groups=[0, 1, 2]))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@pytest.mark.parametrize("groups", [
|
|
39
|
+
[0, 0, 1, 1, np.nan],
|
|
40
|
+
["a", "a", "b", "b", np.nan],
|
|
41
|
+
pd.Series([0, 0, 1, 1, pd.NA], dtype="Int64"),
|
|
42
|
+
])
|
|
43
|
+
def test_group_kfold_shuffle_rejects_missing_labels(groups):
|
|
44
|
+
kf = GroupKFoldShuffle(n_splits=2)
|
|
45
|
+
with pytest.raises(ValueError, match="missing group label"):
|
|
46
|
+
next(kf.split(X=np.zeros(5), groups=groups))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_cross_validate_rejects_missing_group_labels(small_df):
|
|
50
|
+
groups = [f"cluster-{i % 4}" for i in range(len(small_df))]
|
|
51
|
+
groups[0] = np.nan
|
|
52
|
+
|
|
53
|
+
def assign_groups(smiles):
|
|
54
|
+
return [groups[index] for index in smiles.index]
|
|
55
|
+
|
|
56
|
+
with pytest.raises(ValueError, match="missing group label"):
|
|
57
|
+
uru.cross_validate(small_df, [("fake", _FakeModel)], "y",
|
|
58
|
+
[("cluster", assign_groups)],
|
|
59
|
+
n_outer=2, n_inner=2, random_state=1)
|
|
36
60
|
|
|
37
61
|
|
|
38
62
|
def test_cross_validate_nested(small_df):
|
|
@@ -65,8 +89,40 @@ def test_cross_validate_nested(small_df):
|
|
|
65
89
|
assert test_df.groupby("fold").ngroups == n_outer * (n_inner + 1)
|
|
66
90
|
|
|
67
91
|
|
|
92
|
+
@pytest.mark.parametrize("groups", [[0, 1], [0, 1, 2, 3]])
|
|
93
|
+
def test_group_kfold_shuffle_rejects_mismatched_group_count(groups):
|
|
94
|
+
kf = GroupKFoldShuffle(n_splits=2)
|
|
95
|
+
with pytest.raises(ValueError, match="inconsistent numbers of samples"):
|
|
96
|
+
list(kf.split(X=np.zeros((3, 1)), groups=groups))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_group_kfold_shuffle_rejects_multiple_labels_per_sample():
|
|
100
|
+
kf = GroupKFoldShuffle(n_splits=2)
|
|
101
|
+
with pytest.raises(ValueError, match="1d array"):
|
|
102
|
+
list(kf.split(X=np.zeros((3, 1)), groups=[[0, 1], [1, 0], [1, 1]]))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_group_kfold_shuffle_accepts_single_column_of_labels():
|
|
106
|
+
kf = GroupKFoldShuffle(n_splits=2)
|
|
107
|
+
splits = kf.split(X=np.zeros((3, 1)), groups=[[0], [1], [1]])
|
|
108
|
+
train_test = [(train.tolist(), test.tolist()) for train, test in splits]
|
|
109
|
+
assert train_test == [([1, 2], [0]), ([0], [1, 2])]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_cross_validate_rejects_incomplete_group_assignments(small_df):
|
|
113
|
+
def incomplete_groups(smiles):
|
|
114
|
+
return np.arange(len(smiles) - 1)
|
|
115
|
+
|
|
116
|
+
with pytest.raises(ValueError, match="inconsistent numbers of samples"):
|
|
117
|
+
uru.cross_validate(small_df, [("fake", _FakeModel)], "y",
|
|
118
|
+
[("incomplete", incomplete_groups)],
|
|
119
|
+
n_outer=2, n_inner=2, random_state=1)
|
|
120
|
+
|
|
121
|
+
|
|
68
122
|
def test_get_scaffold_acyclic():
|
|
69
123
|
assert uru.get_scaffold("CCCC") == "CCCC"
|
|
124
|
+
assert uru.get_scaffold("OCC") == "CCO"
|
|
125
|
+
assert list(uru.get_bemis_murcko_clusters(["OCC", "CCO"])) == [0, 0]
|
|
70
126
|
|
|
71
127
|
|
|
72
128
|
# A training set and a test set with leakage planted deliberately, one kind per row.
|
|
@@ -87,6 +143,17 @@ def test_audit_split_leakage_finds_an_exact_duplicate():
|
|
|
87
143
|
assert audit.loc[0, "nearest_train_smiles"] == "CC(=O)Oc1ccccc1C(=O)O"
|
|
88
144
|
|
|
89
145
|
|
|
146
|
+
def test_audit_split_leakage_does_not_match_missing_inchikeys():
|
|
147
|
+
train_smiles = "*c1ccccc1"
|
|
148
|
+
test_smiles = "*Cc1ccccc1"
|
|
149
|
+
audit = audit_split_leakage([train_smiles], [test_smiles])
|
|
150
|
+
|
|
151
|
+
assert audit.loc[0, ["exact", "same_connectivity"]].tolist() == [False, False]
|
|
152
|
+
assert bool(audit.loc[0, "same_scaffold"])
|
|
153
|
+
assert audit.loc[0, "nearest_train_smiles"] == train_smiles
|
|
154
|
+
assert 0 < audit.loc[0, "nearest_similarity"] < 1
|
|
155
|
+
|
|
156
|
+
|
|
90
157
|
def test_audit_split_leakage_finds_an_enantiomer():
|
|
91
158
|
"""An enantiomer of a training compound is a different molecule but still leakage.
|
|
92
159
|
|
|
@@ -125,12 +192,15 @@ def test_audit_split_leakage_flags_a_near_duplicate_at_the_cutoff():
|
|
|
125
192
|
|
|
126
193
|
def test_audit_split_leakage_survives_an_unparsable_smiles():
|
|
127
194
|
"""One bad row must not take the audit down with it."""
|
|
128
|
-
audit = audit_split_leakage(LEAKY_TRAIN, ["not a molecule", "c1ccccc1"])
|
|
195
|
+
audit = audit_split_leakage(LEAKY_TRAIN + [""], ["not a molecule", "", "c1ccccc1"])
|
|
129
196
|
assert not bool(audit.loc[0, "exact"])
|
|
130
197
|
assert not bool(audit.loc[0, "same_connectivity"])
|
|
131
198
|
assert np.isnan(audit.loc[0, "nearest_similarity"])
|
|
132
199
|
assert audit.loc[0, "nearest_train_smiles"] is None
|
|
133
|
-
assert bool(audit.loc[1, "exact"])
|
|
200
|
+
assert not bool(audit.loc[1, "exact"])
|
|
201
|
+
assert audit.loc[1, "nearest_train_smiles"] is None
|
|
202
|
+
assert bool(audit.loc[2, "exact"])
|
|
203
|
+
assert len(audit_split_leakage(LEAKY_TRAIN, [])) == 0
|
|
134
204
|
|
|
135
205
|
|
|
136
206
|
def test_audit_split_leakage_tolerates_a_bad_training_smiles():
|
|
@@ -145,6 +215,14 @@ def test_audit_split_leakage_returns_one_row_per_test_molecule():
|
|
|
145
215
|
assert list(audit["test_smiles"]) == test_smiles
|
|
146
216
|
|
|
147
217
|
|
|
218
|
+
def test_audit_split_leakage_empty_test_set_supports_boolean_filtering():
|
|
219
|
+
audit = audit_split_leakage(["CCO"], [])
|
|
220
|
+
|
|
221
|
+
for flag in ("exact", "same_connectivity", "same_scaffold", "near_duplicate"):
|
|
222
|
+
pd.testing.assert_frame_equal(audit[audit[flag]], audit)
|
|
223
|
+
assert pd.api.types.is_float_dtype(audit["nearest_similarity"])
|
|
224
|
+
|
|
225
|
+
|
|
148
226
|
def test_summarize_split_leakage_reports_fractions():
|
|
149
227
|
test_smiles = ["CC(=O)Oc1ccccc1C(=O)O", "C[C@@H](N)C(=O)O", "c1ccc2ccccc2c1", "CCO"]
|
|
150
228
|
summary = summarize_split_leakage(audit_split_leakage(LEAKY_TRAIN, test_smiles))
|
|
@@ -3,6 +3,7 @@ import useful_rdkit_utils as uru
|
|
|
3
3
|
import numpy as np
|
|
4
4
|
from io import StringIO
|
|
5
5
|
import pandas as pd
|
|
6
|
+
import pytest
|
|
6
7
|
|
|
7
8
|
|
|
8
9
|
def generate_3D_mol():
|
|
@@ -197,6 +198,12 @@ def test_pearson_confidence():
|
|
|
197
198
|
assert upper - lower > 0
|
|
198
199
|
|
|
199
200
|
|
|
201
|
+
@pytest.mark.parametrize("r", [-1.0, 1.0])
|
|
202
|
+
def test_pearson_confidence_perfect_correlation(r):
|
|
203
|
+
assert uru.pearson_confidence(r, 5) == (r, r)
|
|
204
|
+
assert uru.pearson_confidence(r, 5, interval=1.0) == (-1.0, 1.0)
|
|
205
|
+
|
|
206
|
+
|
|
200
207
|
def test_bootstrap_confidence_interval():
|
|
201
208
|
from sklearn.metrics import r2_score
|
|
202
209
|
truth = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
|
{useful_rdkit_utils-2.0.2 → useful_rdkit_utils-2.0.3}/useful_rdkit_utils/descriptor_preprocessor.py
RENAMED
|
@@ -4,24 +4,23 @@ import warnings
|
|
|
4
4
|
import numpy as np
|
|
5
5
|
from sklearn.base import BaseEstimator, TransformerMixin
|
|
6
6
|
from sklearn.preprocessing import StandardScaler
|
|
7
|
-
from sklearn.utils.validation import check_array
|
|
8
|
-
|
|
7
|
+
from sklearn.utils.validation import check_array, check_is_fitted
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
from sklearn.utils.validation import validate_data
|
|
11
|
+
except ImportError: # scikit-learn < 1.6
|
|
12
|
+
def validate_data(estimator, X, **kwargs):
|
|
13
|
+
return estimator._validate_data(X, **kwargs)
|
|
9
14
|
|
|
10
15
|
# scikit-learn renamed `force_all_finite` -> `ensure_all_finite` in 1.6 and
|
|
11
16
|
# removed the old name in 1.8. Detect which one the installed version uses.
|
|
12
17
|
_FINITE_KW = (
|
|
13
18
|
"ensure_all_finite"
|
|
14
|
-
if "ensure_all_finite" in inspect.signature(
|
|
19
|
+
if "ensure_all_finite" in inspect.signature(check_array).parameters
|
|
15
20
|
else "force_all_finite"
|
|
16
21
|
)
|
|
17
22
|
|
|
18
23
|
|
|
19
|
-
def _check_array_allow_nan(X, **kwargs):
|
|
20
|
-
"""Version-agnostic ``check_array`` that permits NaN but rejects inf."""
|
|
21
|
-
kwargs[_FINITE_KW] = "allow-nan"
|
|
22
|
-
return _sk_check_array(X, **kwargs)
|
|
23
|
-
|
|
24
|
-
|
|
25
24
|
__all__ = ["DescriptorPreprocessor"]
|
|
26
25
|
|
|
27
26
|
|
|
@@ -58,8 +57,9 @@ class DescriptorPreprocessor(BaseEstimator, TransformerMixin):
|
|
|
58
57
|
descriptor values.
|
|
59
58
|
max_nan_fraction : float, default=0.2
|
|
60
59
|
Columns whose fraction of NaN values strictly exceeds this threshold
|
|
61
|
-
are dropped. Use 1.0 to
|
|
62
|
-
|
|
60
|
+
are dropped. Use 1.0 to disable the NaN-fraction filter and 0.0 to
|
|
61
|
+
drop any column containing a NaN. All-NaN columns have no variance
|
|
62
|
+
and are dropped even when this filter is disabled.
|
|
63
63
|
variance_threshold : float, default=0.0
|
|
64
64
|
Columns with variance ``<= variance_threshold`` (computed ignoring
|
|
65
65
|
NaNs) are dropped. The default removes truly constant descriptors;
|
|
@@ -86,6 +86,9 @@ class DescriptorPreprocessor(BaseEstimator, TransformerMixin):
|
|
|
86
86
|
Fitted scaler applied to the imputed, retained columns.
|
|
87
87
|
n_features_in_ : int
|
|
88
88
|
Number of features seen during ``fit``.
|
|
89
|
+
feature_names_in_ : ndarray of str, shape (n_features,)
|
|
90
|
+
Names of features seen during ``fit``. Defined when the input has
|
|
91
|
+
feature names that are all strings.
|
|
89
92
|
n_features_out_ : int
|
|
90
93
|
Number of features produced by ``transform``.
|
|
91
94
|
|
|
@@ -152,19 +155,21 @@ class DescriptorPreprocessor(BaseEstimator, TransformerMixin):
|
|
|
152
155
|
by the NaN and variance filters.
|
|
153
156
|
"""
|
|
154
157
|
self._validate_params()
|
|
155
|
-
X =
|
|
156
|
-
self.n_features_in_ = X.shape[1]
|
|
158
|
+
X = validate_data(self, X, dtype=np.float64, **{_FINITE_KW: "allow-nan"})
|
|
157
159
|
|
|
158
160
|
# 1. NaN-fraction filter
|
|
159
161
|
nan_fraction = np.isnan(X).mean(axis=0)
|
|
160
162
|
nan_ok = nan_fraction <= self.max_nan_fraction
|
|
161
163
|
|
|
162
|
-
# 2.
|
|
163
|
-
#
|
|
164
|
-
# all-NaN slice and avoid the "Degrees of freedom <= 0" warning.
|
|
164
|
+
# 2. Exclude exact constants before computing variance. Rounding the
|
|
165
|
+
# mean can otherwise give identical finite values a positive variance.
|
|
165
166
|
variances = np.full(self.n_features_in_, np.nan)
|
|
166
167
|
if nan_ok.any():
|
|
167
|
-
|
|
168
|
+
candidates = X[:, nan_ok]
|
|
169
|
+
low = np.nanmin(candidates, axis=0, initial=np.inf)
|
|
170
|
+
high = np.nanmax(candidates, axis=0, initial=-np.inf)
|
|
171
|
+
varying = low < high
|
|
172
|
+
variances[np.flatnonzero(nan_ok)[varying]] = np.nanvar(candidates[:, varying], axis=0)
|
|
168
173
|
var_ok = variances > self.variance_threshold
|
|
169
174
|
|
|
170
175
|
self.kept_columns_ = nan_ok & var_ok
|
|
@@ -211,7 +216,9 @@ class DescriptorPreprocessor(BaseEstimator, TransformerMixin):
|
|
|
211
216
|
----------
|
|
212
217
|
X : array-like of shape (n_samples, n_features)
|
|
213
218
|
Raw descriptor matrix with the same number of columns as the
|
|
214
|
-
matrix seen during ``fit``.
|
|
219
|
+
matrix seen during ``fit``. Named columns must match the training
|
|
220
|
+
names and order when both inputs have names. May contain NaNs
|
|
221
|
+
(but not infs).
|
|
215
222
|
|
|
216
223
|
Returns
|
|
217
224
|
-------
|
|
@@ -223,15 +230,10 @@ class DescriptorPreprocessor(BaseEstimator, TransformerMixin):
|
|
|
223
230
|
sklearn.exceptions.NotFittedError
|
|
224
231
|
If ``fit`` has not been called.
|
|
225
232
|
ValueError
|
|
226
|
-
If the
|
|
227
|
-
matrix.
|
|
233
|
+
If the features in ``X`` do not match the training matrix.
|
|
228
234
|
"""
|
|
229
235
|
check_is_fitted(self, "scaler_")
|
|
230
|
-
X =
|
|
231
|
-
if X.shape[1] != self.n_features_in_:
|
|
232
|
-
raise ValueError(
|
|
233
|
-
f"Expected {self.n_features_in_} features, got {X.shape[1]}"
|
|
234
|
-
)
|
|
236
|
+
X = validate_data(self, X, reset=False, dtype=np.float64, **{_FINITE_KW: "allow-nan"})
|
|
235
237
|
X_kept = X[:, self.kept_columns_]
|
|
236
238
|
X_imputed = self._impute(X_kept)
|
|
237
239
|
return self.scaler_.transform(X_imputed)
|
|
@@ -261,8 +263,8 @@ class DescriptorPreprocessor(BaseEstimator, TransformerMixin):
|
|
|
261
263
|
Parameters
|
|
262
264
|
----------
|
|
263
265
|
input_features : array-like of str, optional
|
|
264
|
-
Names of the input columns. If None,
|
|
265
|
-
``"x0"``, ``"x1"``, ...
|
|
266
|
+
Names of the input columns. If None, use the names seen during
|
|
267
|
+
``fit`` or generate ``"x0"``, ``"x1"``, ... for unnamed inputs.
|
|
266
268
|
|
|
267
269
|
Returns
|
|
268
270
|
-------
|
|
@@ -270,10 +272,15 @@ class DescriptorPreprocessor(BaseEstimator, TransformerMixin):
|
|
|
270
272
|
Names of the features produced by ``transform``, in order.
|
|
271
273
|
"""
|
|
272
274
|
check_is_fitted(self, "kept_indices_")
|
|
275
|
+
fitted_names = getattr(self, "feature_names_in_", None)
|
|
273
276
|
if input_features is None:
|
|
274
|
-
input_features =
|
|
277
|
+
input_features = fitted_names
|
|
278
|
+
if input_features is None:
|
|
279
|
+
input_features = np.array([f"x{i}" for i in range(self.n_features_in_)])
|
|
275
280
|
else:
|
|
276
281
|
input_features = np.asarray(input_features)
|
|
282
|
+
if fitted_names is not None and not np.array_equal(input_features, fitted_names):
|
|
283
|
+
raise ValueError("input_features must match feature_names_in_")
|
|
277
284
|
if input_features.shape[0] != self.n_features_in_:
|
|
278
285
|
raise ValueError(
|
|
279
286
|
f"input_features has length {input_features.shape[0]}, "
|