hddflyzer 0.1.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. hddflyzer/__init__.py +25 -0
  2. hddflyzer/chem/__init__.py +105 -0
  3. hddflyzer/chem/feature_curation.py +212 -0
  4. hddflyzer/chem/feature_engineering.py +736 -0
  5. hddflyzer/chem/npclassifier.py +327 -0
  6. hddflyzer/chem/pruning.py +218 -0
  7. hddflyzer/chem/reference_catalog.py +69 -0
  8. hddflyzer/chem/stats.py +356 -0
  9. hddflyzer/chem/tanimoto.py +272 -0
  10. hddflyzer/chem/tanimoto_sampling.py +291 -0
  11. hddflyzer/cli.py +422 -0
  12. hddflyzer/config/__init__.py +124 -0
  13. hddflyzer/config/descriptor_config.json +179 -0
  14. hddflyzer/config/settings.py +91 -0
  15. hddflyzer/data/__init__.py +25 -0
  16. hddflyzer/data/registry.py +226 -0
  17. hddflyzer/dimred/__init__.py +37 -0
  18. hddflyzer/dimred/pca.py +294 -0
  19. hddflyzer/dimred/pca_joint.py +221 -0
  20. hddflyzer/dimred/pca_utils.py +42 -0
  21. hddflyzer/dimred/tsne.py +664 -0
  22. hddflyzer/dimred/umap.py +690 -0
  23. hddflyzer/io/__init__.py +36 -0
  24. hddflyzer/io/paths.py +7 -0
  25. hddflyzer/io/readers.py +205 -0
  26. hddflyzer/io/writers.py +249 -0
  27. hddflyzer/pipeline/__init__.py +21 -0
  28. hddflyzer/pipeline/contracts.py +79 -0
  29. hddflyzer/pipeline/orchestrator.py +232 -0
  30. hddflyzer/pipeline/stages.py +140 -0
  31. hddflyzer/results/__init__.py +36 -0
  32. hddflyzer/results/artifacts.py +283 -0
  33. hddflyzer/results/workflow_run.py +602 -0
  34. hddflyzer/science/__init__.py +47 -0
  35. hddflyzer/science/metrics.py +650 -0
  36. hddflyzer/science/spaces.py +423 -0
  37. hddflyzer/utils/__init__.py +33 -0
  38. hddflyzer/utils/columns.py +37 -0
  39. hddflyzer/utils/descriptors.py +228 -0
  40. hddflyzer/utils/naming.py +33 -0
  41. hddflyzer/version.py +3 -0
  42. hddflyzer/viz/__init__.py +48 -0
  43. hddflyzer/viz/colors.py +61 -0
  44. hddflyzer/viz/correlations.py +194 -0
  45. hddflyzer/viz/distributions.py +354 -0
  46. hddflyzer/viz/inputs.py +134 -0
  47. hddflyzer/viz/npclassifier_plots.py +328 -0
  48. hddflyzer/viz/pca_plots.py +298 -0
  49. hddflyzer/viz/similarity.py +309 -0
  50. hddflyzer/viz/tsne_plots.py +415 -0
  51. hddflyzer/viz/umap_plots.py +387 -0
  52. hddflyzer-0.1.5.dist-info/METADATA +696 -0
  53. hddflyzer-0.1.5.dist-info/RECORD +58 -0
  54. hddflyzer-0.1.5.dist-info/WHEEL +4 -0
  55. hddflyzer-0.1.5.dist-info/entry_points.txt +2 -0
  56. hddflyzer-0.1.5.dist-info/licenses/COPYING +674 -0
  57. hddflyzer-0.1.5.dist-info/licenses/COPYING.LESSER +165 -0
  58. hddflyzer-0.1.5.dist-info/licenses/LICENSE +8 -0
hddflyzer/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ # SPDX-License-Identifier: LGPL-3.0-or-later
2
+
3
+ """
4
+ HDDFlyzer
5
+ =========
6
+ High-Dimensional Descriptor-based Feature Space Analyzer.
7
+
8
+ A scientific toolkit for molecular descriptor analysis,
9
+ chemical space visualization, and pharmacological similarity
10
+ of organic compound collections.
11
+
12
+ Modules
13
+ -------
14
+ data : Local molecule registry
15
+ annotate : External annotations
16
+ chem : Feature engineering, statistics, similarity
17
+ dimred : Dimensionality reduction (PCA, t-SNE, UMAP)
18
+ viz : Visualization and plotting
19
+ utils : Shared utilities (I/O, colors, descriptors)
20
+ config : Static configuration (descriptor definitions)
21
+ """
22
+
23
+ from hddflyzer.version import __version__
24
+
25
+ __author__ = "Flavio F. Contreras-Torres"
@@ -0,0 +1,105 @@
1
+ # SPDX-License-Identifier: LGPL-3.0-or-later
2
+
3
+ """
4
+ Chemistry module for HDDFlyzer.
5
+
6
+ Submodules
7
+ ----------
8
+ feature_engineering : Intrinsic descriptors and reference similarity features
9
+ feature_curation : ML-ready curated descriptor tables
10
+ stats : Pearson/Spearman correlations (BASE and HDDF modes)
11
+ pruning : Remove redundant descriptors via correlation graph
12
+ npclassifier : Optional NPClassifier annotation via external API
13
+ tanimoto : Compute Morgan fingerprint Tanimoto matrices
14
+ tanimoto_sampling : Stratified sampling from Tanimoto matrices
15
+
16
+ Note: feature_engineering and tanimoto require RDKit.
17
+ All other submodules are RDKit-independent.
18
+ """
19
+
20
+ # RDKit-independent imports (always available)
21
+ from .stats import (
22
+ HDDF_COLUMNS,
23
+ HDDF_NAMES,
24
+ NONCORR_THRESHOLD,
25
+ run_base_stats,
26
+ run_hddf_stats,
27
+ )
28
+
29
+ from .pruning import (
30
+ DEFAULT_THRESHOLD,
31
+ run as run_pruning,
32
+ )
33
+
34
+ from .npclassifier import (
35
+ NPClassifierClient,
36
+ run as run_npclassifier,
37
+ )
38
+
39
+ from .tanimoto_sampling import (
40
+ DEFAULTS as TANIMOTO_SAMPLING_DEFAULTS,
41
+ stratify,
42
+ balanced_sample,
43
+ run as run_tanimoto_sampling,
44
+ )
45
+
46
+ from .feature_curation import (
47
+ curate_features,
48
+ run as run_feature_curation,
49
+ )
50
+
51
+ _LAZY_EXPORTS = {
52
+ "REFERENCE_MOLECULES": ("hddflyzer.chem.reference_catalog", "REFERENCE_MOLECULES"),
53
+ "calculate_molecular_descriptors": (
54
+ "hddflyzer.chem.feature_engineering",
55
+ "calculate_molecular_descriptors",
56
+ ),
57
+ "calculate_fingerprint_similarities": (
58
+ "hddflyzer.chem.feature_engineering",
59
+ "calculate_fingerprint_similarities",
60
+ ),
61
+ "calculate_mcs_features": (
62
+ "hddflyzer.chem.feature_engineering",
63
+ "calculate_mcs_features",
64
+ ),
65
+ "run_feature_engineering": ("hddflyzer.chem.feature_engineering", "run"),
66
+ "run_reference_features": (
67
+ "hddflyzer.chem.feature_engineering",
68
+ "run_reference_features",
69
+ ),
70
+ "build_morgan_fps": ("hddflyzer.chem.tanimoto", "build_morgan_fps"),
71
+ "compute_tanimoto_matrix": ("hddflyzer.chem.tanimoto", "compute_tanimoto_matrix"),
72
+ "stats_from_matrix": ("hddflyzer.chem.tanimoto", "stats_from_matrix"),
73
+ "run_tanimoto": ("hddflyzer.chem.tanimoto", "run"),
74
+ }
75
+
76
+ __all__ = [
77
+ "HDDF_COLUMNS",
78
+ "HDDF_NAMES",
79
+ "NONCORR_THRESHOLD",
80
+ "run_base_stats",
81
+ "run_hddf_stats",
82
+ "DEFAULT_THRESHOLD",
83
+ "run_pruning",
84
+ "NPClassifierClient",
85
+ "run_npclassifier",
86
+ "TANIMOTO_SAMPLING_DEFAULTS",
87
+ "stratify",
88
+ "balanced_sample",
89
+ "run_tanimoto_sampling",
90
+ "curate_features",
91
+ "run_feature_curation",
92
+ *_LAZY_EXPORTS,
93
+ ]
94
+
95
+
96
+ def __getattr__(name):
97
+ if name not in _LAZY_EXPORTS:
98
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
99
+
100
+ from importlib import import_module
101
+
102
+ module_name, attr_name = _LAZY_EXPORTS[name]
103
+ value = getattr(import_module(module_name), attr_name)
104
+ globals()[name] = value
105
+ return value
@@ -0,0 +1,212 @@
1
+ # SPDX-License-Identifier: LGPL-3.0-or-later
2
+
3
+ """Create ML-ready feature tables from intrinsic molecular descriptors."""
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ from typing import Dict, List, Tuple
9
+
10
+ import pandas as pd
11
+
12
+ from hddflyzer.config import get_path
13
+ from hddflyzer.io import load_features_table, update_manifest
14
+ from hddflyzer.utils.descriptors import HYBRID_BASE
15
+ from hddflyzer.utils.naming import sanitize_tag
16
+
17
+ try:
18
+ from rdkit import Chem, rdBase
19
+ _RDKIT_AVAILABLE = True
20
+ except ImportError:
21
+ rdBase = None
22
+ _RDKIT_AVAILABLE = False
23
+
24
+ ID_COLUMNS = ["identifier", "SMILES"]
25
+
26
+ REDUNDANT_COLUMNS = [
27
+ "HeavyAtomMolWt",
28
+ "NHOHCount",
29
+ "NOCount",
30
+ ]
31
+
32
+ HIGH_ORDER_CONNECTIVITY_COLUMNS = [
33
+ "Chi4",
34
+ "Chi4v",
35
+ ]
36
+
37
+ DERIVED_COLUMNS = list(HYBRID_BASE)
38
+
39
+ ATOM_COUNT_COLUMNS = [
40
+ "NumCarbonAtoms",
41
+ "NumNitrogenAtoms",
42
+ "NumOxygenAtoms",
43
+ ]
44
+
45
+
46
+ def _remove_columns(df: pd.DataFrame, columns: List[str]) -> Tuple[pd.DataFrame, List[str]]:
47
+ present = [c for c in columns if c in df.columns and c not in ID_COLUMNS]
48
+ return df.drop(columns=present), present
49
+
50
+
51
+ def _zero_variance_columns(df: pd.DataFrame) -> List[str]:
52
+ numeric = df.select_dtypes(include="number")
53
+ return [
54
+ col for col in numeric.columns
55
+ if col not in ID_COLUMNS and numeric[col].nunique(dropna=False) <= 1
56
+ ]
57
+
58
+
59
+ def _atom_counts(smiles: object) -> Dict[str, int]:
60
+ counts = {col: 0 for col in ATOM_COUNT_COLUMNS}
61
+ if not _RDKIT_AVAILABLE:
62
+ return counts
63
+ mol = Chem.MolFromSmiles("" if pd.isna(smiles) else str(smiles))
64
+ if mol is None:
65
+ return counts
66
+ for atom in mol.GetAtoms():
67
+ atomic_num = atom.GetAtomicNum()
68
+ if atomic_num == 6:
69
+ counts["NumCarbonAtoms"] += 1
70
+ elif atomic_num == 7:
71
+ counts["NumNitrogenAtoms"] += 1
72
+ elif atomic_num == 8:
73
+ counts["NumOxygenAtoms"] += 1
74
+ return counts
75
+
76
+
77
+ def add_atom_counts(df: pd.DataFrame) -> Tuple[pd.DataFrame, List[str]]:
78
+ """Add simple atom-count descriptors when SMILES are available."""
79
+ if "SMILES" not in df.columns:
80
+ return df, []
81
+ out = df.copy()
82
+ counts = pd.DataFrame([_atom_counts(smi) for smi in out["SMILES"]])
83
+ for col in ATOM_COUNT_COLUMNS:
84
+ out[col] = counts[col].values
85
+ return out, ATOM_COUNT_COLUMNS.copy()
86
+
87
+
88
+ def curate_features(
89
+ df: pd.DataFrame,
90
+ drop_redundant: bool = True,
91
+ drop_derived: bool = True,
92
+ drop_high_order_connectivity: bool = True,
93
+ drop_zero_variance: bool = True,
94
+ add_atoms: bool = True,
95
+ ) -> Tuple[pd.DataFrame, Dict]:
96
+ """Return an ML-ready feature table and curation metadata."""
97
+ curated = df.copy()
98
+ removed = {}
99
+ added = []
100
+
101
+ if add_atoms:
102
+ curated, added = add_atom_counts(curated)
103
+
104
+ if drop_redundant:
105
+ curated, removed["redundant"] = _remove_columns(curated, REDUNDANT_COLUMNS)
106
+
107
+ if drop_derived:
108
+ curated, removed["derived_ratios"] = _remove_columns(curated, DERIVED_COLUMNS)
109
+
110
+ if drop_high_order_connectivity:
111
+ curated, removed["high_order_connectivity"] = _remove_columns(
112
+ curated, HIGH_ORDER_CONNECTIVITY_COLUMNS)
113
+
114
+ if drop_zero_variance:
115
+ zero_cols = _zero_variance_columns(curated)
116
+ curated, removed["zero_variance"] = _remove_columns(curated, zero_cols)
117
+
118
+ metadata = {
119
+ "input_shape": {
120
+ "rows": int(len(df)),
121
+ "columns": int(len(df.columns)),
122
+ },
123
+ "output_shape": {
124
+ "rows": int(len(curated)),
125
+ "columns": int(len(curated.columns)),
126
+ },
127
+ "added_features": added,
128
+ "removed_features": removed,
129
+ "rules": {
130
+ "drop_redundant": bool(drop_redundant),
131
+ "drop_derived": bool(drop_derived),
132
+ "drop_high_order_connectivity": bool(drop_high_order_connectivity),
133
+ "drop_zero_variance": bool(drop_zero_variance),
134
+ "add_atom_counts": bool(add_atoms),
135
+ },
136
+ "chemistry_backend": {
137
+ "rdkit_available": bool(_RDKIT_AVAILABLE),
138
+ "rdkit_version": rdBase.rdkitVersion if _RDKIT_AVAILABLE else None,
139
+ },
140
+ "descriptor_parameters": {
141
+ "atom_counts": {
142
+ "enabled": bool(add_atoms),
143
+ "source": "RDKit MolFromSmiles atomic numbers",
144
+ "elements": ["C", "N", "O"],
145
+ },
146
+ "morgan_fingerprint": {
147
+ "applies": False,
148
+ "reason": (
149
+ "features_ml.csv is curated from intrinsic molecular "
150
+ "descriptors and does not include reference or pairwise "
151
+ "fingerprint similarities."
152
+ ),
153
+ },
154
+ "reference_similarity": {
155
+ "applies": False,
156
+ "reason": (
157
+ "Reference-dependent Tanimoto and MCS features are stored "
158
+ "separately under features/reference/."
159
+ ),
160
+ },
161
+ },
162
+ "notes": (
163
+ "Curated table for ML workflows. The canonical chemistry table "
164
+ "remains results/{tag}/features/full/features.csv."
165
+ ),
166
+ }
167
+ return curated, metadata
168
+
169
+
170
+ def run(tag: str) -> bool:
171
+ """Create results/{tag}/features/curated/features_ml.csv."""
172
+ try:
173
+ df, input_path = load_features_table(tag)
174
+ except FileNotFoundError as e:
175
+ print(f"[ERROR] {e}")
176
+ return False
177
+
178
+ curated, metadata = curate_features(df)
179
+ metadata["tag"] = tag
180
+ metadata["source_features"] = input_path
181
+
182
+ out_dir = get_path("features_curated", tag)
183
+ os.makedirs(out_dir, exist_ok=True)
184
+ out_csv = os.path.join(out_dir, "features_ml.csv")
185
+ meta_path = os.path.join(out_dir, "feature_curation_metadata.json")
186
+
187
+ curated.to_csv(out_csv, index=False)
188
+ with open(meta_path, "w", encoding="utf-8") as f:
189
+ json.dump(metadata, f, ensure_ascii=False, indent=2)
190
+
191
+ update_manifest(tag, "chem.curate_features", [out_csv, meta_path], metadata)
192
+
193
+ removed_total = sum(len(v) for v in metadata["removed_features"].values())
194
+ print(f"[OK] Curated ML features: {out_csv}")
195
+ print(f" Input columns : {metadata['input_shape']['columns']}")
196
+ print(f" Output columns : {metadata['output_shape']['columns']}")
197
+ print(f" Removed : {removed_total}")
198
+ return True
199
+
200
+
201
+ def main():
202
+ if len(sys.argv) < 2:
203
+ print("Usage: python -m hddflyzer.chem.feature_curation <tag>")
204
+ print("Example: python -m hddflyzer.chem.feature_curation aocd")
205
+ sys.exit(1)
206
+ tag = sanitize_tag(sys.argv[1])
207
+ if not run(tag):
208
+ sys.exit(1)
209
+
210
+
211
+ if __name__ == "__main__":
212
+ main()