QPromaQ commited on
Commit
c289d87
·
verified ·
1 Parent(s): bb95297

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README_SERVER.md +112 -0
  2. check_environment.sh +21 -0
  3. configs/known_good_pdb_complexes.yaml +137 -0
  4. configs/multifidelity_defaults.yaml +14 -0
  5. data/examples/example_pdb_dataset_config.yaml +9 -0
  6. data/examples/example_smiles.smi +50 -0
  7. data/examples/example_smiles_1000.smi +1000 -0
  8. docking_pipeline/__init__.py +5 -0
  9. docking_pipeline/__main__.py +197 -0
  10. docking_pipeline/__pycache__/__init__.cpython-313.pyc +0 -0
  11. docking_pipeline/__pycache__/config_io.cpython-313.pyc +0 -0
  12. docking_pipeline/__pycache__/dataset.cpython-313.pyc +0 -0
  13. docking_pipeline/__pycache__/provenance.cpython-313.pyc +0 -0
  14. docking_pipeline/__pycache__/rdock.cpython-313.pyc +0 -0
  15. docking_pipeline/__pycache__/sdf.cpython-313.pyc +0 -0
  16. docking_pipeline/adaptive.py +177 -0
  17. docking_pipeline/benchmark_adaptive.py +900 -0
  18. docking_pipeline/config_io.py +32 -0
  19. docking_pipeline/dataset.py +433 -0
  20. docking_pipeline/metrics.py +83 -0
  21. docking_pipeline/provenance.py +156 -0
  22. docking_pipeline/rdock.py +561 -0
  23. docking_pipeline/reports/__init__.py +1 -0
  24. docking_pipeline/reports/plots.py +644 -0
  25. docking_pipeline/sdf.py +157 -0
  26. docking_pipeline/validation.py +708 -0
  27. environment.yml +12 -0
  28. libs/__init__.py +1 -0
  29. libs/adaptive/__init__.py +19 -0
  30. libs/adaptive/clustering.py +47 -0
  31. libs/adaptive/diversity.py +24 -0
  32. libs/adaptive/epsilon_regret.py +160 -0
  33. libs/adaptive/features.py +408 -0
  34. libs/adaptive/hyperclustering.py +28 -0
  35. libs/adaptive/metrics.py +48 -0
  36. libs/adaptive/policies.py +12 -0
  37. libs/adaptive/prioritization.py +26 -0
  38. libs/adaptive/queue_manager.py +31 -0
  39. libs/adaptive/scheduler.py +253 -0
  40. libs/adaptive/state.py +50 -0
  41. libs/adaptive/surrogate_model.py +208 -0
  42. libs/adaptive/thresholding.py +120 -0
  43. libs/adaptive/weight_schedule.py +48 -0
  44. libs/analysis/__init__.py +0 -0
  45. libs/analysis/backend_diagnostic.py +179 -0
  46. libs/analysis/ranking.py +43 -0
  47. libs/benchmark/__init__.py +108 -0
  48. libs/benchmark/budget_efficiency.py +123 -0
  49. libs/benchmark/cleanup.py +59 -0
  50. libs/benchmark/disk_guard.py +233 -0
README_SERVER.md ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Portable rDock Pipeline
2
+
3
+ ## List known-good PDB complexes
4
+ ```bash
5
+ python scripts/prepare_pdb_ligand_dataset.py --list-known-good
6
+ ```
7
+
8
+ ## Inspect hetero ligands for a PDB
9
+ ```bash
10
+ python scripts/prepare_pdb_ligand_dataset.py \
11
+ --list-hetero \
12
+ --pdb-id 1A52
13
+ ```
14
+
15
+ For `1A52`, the parser should confirm that the correct reference ligand is `EST`, not `MK1`. `AU` is treated as an ion/metal and ignored as a docking reference ligand.
16
+
17
+ ## Prepare a dataset for one PDB complex
18
+ ```bash
19
+ python scripts/prepare_pdb_ligand_dataset.py \
20
+ --pdb-id 4HG7 \
21
+ --receptor-chain A \
22
+ --reference-ligand-resname NUT \
23
+ --reference-ligand-chain A \
24
+ --n-ligands 1000 \
25
+ --ligand-source smiles_file \
26
+ --smiles-file data/examples/example_smiles_1000.smi \
27
+ --out /data/datasets/rdock_4hg7_1000 \
28
+ --force
29
+ ```
30
+
31
+ ## Auto-detect the reference ligand
32
+ ```bash
33
+ python scripts/prepare_pdb_ligand_dataset.py \
34
+ --pdb-id 1A52 \
35
+ --receptor-chain A \
36
+ --auto-reference-ligand \
37
+ --n-ligands 1000 \
38
+ --ligand-source smiles_file \
39
+ --smiles-file data/examples/example_smiles_1000.smi \
40
+ --out /data/datasets/rdock_1a52_1000 \
41
+ --force
42
+ ```
43
+
44
+ ## Validate an existing dataset directory
45
+ ```bash
46
+ python scripts/prepare_pdb_ligand_dataset.py \
47
+ --validate-only \
48
+ --out /data/datasets/rdock_4hg7_1000
49
+ ```
50
+
51
+ or
52
+
53
+ ```bash
54
+ python -m docking_pipeline validate-dataset \
55
+ --dataset-dir /data/datasets/rdock_4hg7_1000
56
+ ```
57
+
58
+ ## Prepare a real 1000-SMILES example file
59
+ ```bash
60
+ python scripts/download_example_smiles.py \
61
+ --n 1000 \
62
+ --out data/examples/example_smiles_1000.smi
63
+ ```
64
+
65
+ This file contains real compounds derived from the benchmark ligand library already present in this repository. It is not a synthetic or random SMILES set.
66
+
67
+ ## Large libraries
68
+ For large libraries such as `50000` ligands, use a real SMILES file:
69
+
70
+ ```bash
71
+ python scripts/prepare_pdb_ligand_dataset.py \
72
+ --pdb-id 1A52 \
73
+ --receptor-chain A \
74
+ --auto-reference-ligand \
75
+ --n-ligands 50000 \
76
+ --ligand-source smiles_file \
77
+ --smiles-file /data/libraries/real_50k_library.smi \
78
+ --out /data/datasets/rdock_1a52_50k \
79
+ --force
80
+ ```
81
+
82
+ `PubChem similarity` may fail to collect 1000 analogs for some reference ligands. When that happens, the generator writes `logs/pubchem_diagnostics.json` and you should switch to `--ligand-source smiles_file`.
83
+
84
+ ## Run multi-fidelity docking
85
+ ```bash
86
+ python -m docking_pipeline benchmark-adaptive \
87
+ --dataset-dir /data/datasets/rdock_1a52_50k \
88
+ --strategy multifidelity_adaptive_rdock \
89
+ --fidelity-levels 5,10,15,30,50 \
90
+ --cost-budget-runs 250000 \
91
+ --jobs auto \
92
+ --cpu-fraction 0.85 \
93
+ --out /data/results/rdock_1a52_50k_mf \
94
+ --resume
95
+ ```
96
+
97
+ ## Results layout
98
+ - `target/`, `ligands/`, `rdock/`, `poses/`, `tables/`, `metrics/`, `plots/`, `checkpoints/`
99
+ - `report.md`, `manifest.json`, `config.yaml`, `commands.log`
100
+
101
+ ## Resume
102
+ - Re-run the same `benchmark-adaptive` command with `--resume`.
103
+ - Checkpoints are written under `checkpoints/`.
104
+
105
+ ## Output interpretation
106
+ - `full_docking_scores.csv`: exhaustive final-fidelity docking reference.
107
+ - `random_baseline_scores.csv`: random baseline at matched cost budget.
108
+ - `single_fidelity_adaptive_scores.csv`: direct final-fidelity model-priority comparator.
109
+ - `multifidelity_trace.csv`: per-ligand trace across fidelity levels.
110
+ - `promotion_decisions.csv`: promotion and rejection reasons.
111
+ - `final_hits.csv`: hit table after multi-fidelity promotion logic.
112
+ - `adaptive_benchmark_metrics.json`: aggregate benchmark metrics and cost accounting.
check_environment.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ echo "python: $(command -v python || true)"
5
+ echo "rbdock: $(command -v rbdock || true)"
6
+ echo "rbcavity: $(command -v rbcavity || true)"
7
+ echo "obabel: $(command -v obabel || true)"
8
+
9
+ python - <<'PY'
10
+ import importlib
11
+ import importlib.util
12
+
13
+ mods = ["yaml", "pandas", "matplotlib", "rdkit"]
14
+ for name in mods:
15
+ print(f"{name}: {'ok' if importlib.util.find_spec(name) else 'missing'}")
16
+ PY
17
+
18
+ python -m docking_pipeline --help >/dev/null
19
+ python scripts/prepare_pdb_ligand_dataset.py --help >/dev/null
20
+
21
+ echo "Environment check completed."
configs/known_good_pdb_complexes.yaml ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "complexes": [
3
+ {
4
+ "pdb_id": "4HG7",
5
+ "target_name": "MDM2",
6
+ "receptor_chain": "A",
7
+ "reference_ligand_resname": "NUT",
8
+ "reference_ligand_chain": "A",
9
+ "available_hetero_ligands": [
10
+ {"resname": "NUT", "chain": "A", "residue_id": "201", "atom_count": 40, "candidate_ligand": true}
11
+ ],
12
+ "checked_download": true,
13
+ "checked_parse": true,
14
+ "checked_reference_ligand": true,
15
+ "notes": "Local parser check confirmed NUT chain A as the reference ligand."
16
+ },
17
+ {
18
+ "pdb_id": "4WKQ",
19
+ "target_name": "EGFR",
20
+ "receptor_chain": "A",
21
+ "reference_ligand_resname": "IRE",
22
+ "reference_ligand_chain": "A",
23
+ "available_hetero_ligands": [
24
+ {"resname": "IRE", "chain": "A", "residue_id": "1101", "atom_count": 31, "candidate_ligand": true}
25
+ ],
26
+ "checked_download": true,
27
+ "checked_parse": true,
28
+ "checked_reference_ligand": true,
29
+ "notes": "Local parser check confirmed IRE chain A."
30
+ },
31
+ {
32
+ "pdb_id": "1IEP",
33
+ "target_name": "ABL1",
34
+ "receptor_chain": "A",
35
+ "reference_ligand_resname": "STI",
36
+ "reference_ligand_chain": "A",
37
+ "available_hetero_ligands": [
38
+ {"resname": "STI", "chain": "A", "residue_id": "201", "atom_count": 37, "candidate_ligand": true},
39
+ {"resname": "STI", "chain": "B", "residue_id": "202", "atom_count": 37, "candidate_ligand": true}
40
+ ],
41
+ "checked_download": true,
42
+ "checked_parse": true,
43
+ "checked_reference_ligand": true,
44
+ "notes": "Use chain A unless the alternate biological assembly is explicitly desired."
45
+ },
46
+ {
47
+ "pdb_id": "1A52",
48
+ "target_name": "Estrogen receptor alpha",
49
+ "receptor_chain": "A",
50
+ "reference_ligand_resname": "EST",
51
+ "reference_ligand_chain": "A",
52
+ "available_hetero_ligands": [
53
+ {"resname": "EST", "chain": "A", "residue_id": "1", "atom_count": 20, "candidate_ligand": true},
54
+ {"resname": "EST", "chain": "B", "residue_id": "2", "atom_count": 20, "candidate_ligand": true},
55
+ {"resname": "AU", "chain": "A", "residue_id": "265", "atom_count": 3, "candidate_ligand": false},
56
+ {"resname": "AU", "chain": "B", "residue_id": "266", "atom_count": 3, "candidate_ligand": false}
57
+ ],
58
+ "checked_download": true,
59
+ "checked_parse": true,
60
+ "checked_reference_ligand": true,
61
+ "notes": "Correct reference ligand is EST, not MK1. AU entries are ignored as ions/metals."
62
+ },
63
+ {
64
+ "pdb_id": "1T46",
65
+ "target_name": "ABL1 alternative complex",
66
+ "receptor_chain": "A",
67
+ "reference_ligand_resname": "STI",
68
+ "reference_ligand_chain": "A",
69
+ "available_hetero_ligands": [
70
+ {"resname": "STI", "chain": "A", "residue_id": "3", "atom_count": 37, "candidate_ligand": true}
71
+ ],
72
+ "checked_download": true,
73
+ "checked_parse": true,
74
+ "checked_reference_ligand": true,
75
+ "notes": "Single clear STI ligand in chain A."
76
+ },
77
+ {
78
+ "pdb_id": "3PTB",
79
+ "target_name": "Trypsin",
80
+ "receptor_chain": "A",
81
+ "reference_ligand_resname": "BEN",
82
+ "reference_ligand_chain": "A",
83
+ "available_hetero_ligands": [
84
+ {"resname": "BEN", "chain": "A", "residue_id": "1", "atom_count": 9, "candidate_ligand": true}
85
+ ],
86
+ "checked_download": true,
87
+ "checked_parse": true,
88
+ "checked_reference_ligand": true,
89
+ "notes": "Compact benchmark target with benzamidine."
90
+ },
91
+ {
92
+ "pdb_id": "2HYY",
93
+ "target_name": "ABL1 tetrameric assembly",
94
+ "receptor_chain": "A",
95
+ "reference_ligand_resname": "STI",
96
+ "reference_ligand_chain": "A",
97
+ "available_hetero_ligands": [
98
+ {"resname": "STI", "chain": "A", "residue_id": "600", "atom_count": 37, "candidate_ligand": true},
99
+ {"resname": "STI", "chain": "B", "residue_id": "600", "atom_count": 37, "candidate_ligand": true},
100
+ {"resname": "STI", "chain": "C", "residue_id": "600", "atom_count": 37, "candidate_ligand": true},
101
+ {"resname": "STI", "chain": "D", "residue_id": "600", "atom_count": 37, "candidate_ligand": true}
102
+ ],
103
+ "checked_download": true,
104
+ "checked_parse": true,
105
+ "checked_reference_ligand": true,
106
+ "notes": "Tetrameric structure; chain A is the default receptor chain for the portable pipeline."
107
+ },
108
+ {
109
+ "pdb_id": "1HSG",
110
+ "target_name": "HIV protease",
111
+ "receptor_chain": "A,B",
112
+ "reference_ligand_resname": "MK1",
113
+ "reference_ligand_chain": "B",
114
+ "available_hetero_ligands": [
115
+ {"resname": "MK1", "chain": "B", "residue_id": "902", "atom_count": 45, "candidate_ligand": true}
116
+ ],
117
+ "checked_download": true,
118
+ "checked_parse": true,
119
+ "checked_reference_ligand": true,
120
+ "notes": "Validated locally as a multi-chain receptor target with one clear ligand."
121
+ },
122
+ {
123
+ "pdb_id": "1HVR",
124
+ "target_name": "HIV reverse transcriptase",
125
+ "receptor_chain": "A",
126
+ "reference_ligand_resname": "XK2",
127
+ "reference_ligand_chain": "A",
128
+ "available_hetero_ligands": [
129
+ {"resname": "XK2", "chain": "A", "residue_id": "263", "atom_count": 46, "candidate_ligand": true}
130
+ ],
131
+ "checked_download": true,
132
+ "checked_parse": true,
133
+ "checked_reference_ligand": true,
134
+ "notes": "Validated locally as a single-chain receptor with one clear organic ligand."
135
+ }
136
+ ]
137
+ }
configs/multifidelity_defaults.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "strategy": "multifidelity_adaptive_rdock",
3
+ "fidelity_levels": [5, 10, 15, 30, 50],
4
+ "cost_budget_runs": 12500,
5
+ "promotion_fraction": 0.5,
6
+ "min_per_cluster": 1,
7
+ "max_per_cluster": 50,
8
+ "outlier_intra_z_threshold": 3.0,
9
+ "score_component_filter": "warn",
10
+ "final_fidelity_only_hits": true,
11
+ "jobs": "auto",
12
+ "cpu_fraction": 0.85,
13
+ "checkpoint_every": 1
14
+ }
data/examples/example_pdb_dataset_config.yaml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "pdb_id": "4HG7",
3
+ "receptor_chain": "A",
4
+ "reference_ligand_resname": "NUT",
5
+ "reference_ligand_chain": "A",
6
+ "n_ligands": 50,
7
+ "smiles_file": "data/examples/example_smiles.smi",
8
+ "ligand_source": "bundled_or_remote"
9
+ }
data/examples/example_smiles.smi ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CCO ethanol
2
+ CCN ethylamine
3
+ CCC propane
4
+ CCCO propanol
5
+ CCCC butane
6
+ CC(=O)O acetic_acid
7
+ CCOC ethoxyethane
8
+ c1ccccc1 benzene
9
+ Cc1ccccc1 toluene
10
+ Oc1ccccc1 phenol
11
+ Nc1ccccc1 aniline
12
+ CC(=O)N acetamide
13
+ CC(C)O isopropanol
14
+ CC(C)N isopropylamine
15
+ C1CCCCC1 cyclohexane
16
+ C1CCNCC1 piperidine
17
+ c1ccncc1 pyridine
18
+ c1ccoc1 furan
19
+ c1ccsc1 thiophene
20
+ CCS ethanethiol
21
+ COC dimethyl_ether
22
+ CCCl chloroethane
23
+ CCBr bromoethane
24
+ CC#N acetonitrile
25
+ CC(=O)OC methyl_acetate
26
+ CC(C)(C)O tert_butanol
27
+ CC(C)(C)N tert_butylamine
28
+ CC(C)C isobutane
29
+ CC(C)CO isobutanol
30
+ CC(C)C(=O)O isobutyric_acid
31
+ c1ccc(F)cc1 fluorobenzene
32
+ c1ccc(Cl)cc1 chlorobenzene
33
+ c1ccc(Br)cc1 bromobenzene
34
+ COc1ccccc1 anisole
35
+ CCOc1ccccc1 ethoxybenzene
36
+ CCc1ccccc1 ethylbenzene
37
+ CC(=O)c1ccccc1 acetophenone
38
+ O=C(O)c1ccccc1 benzoic_acid
39
+ NC(=O)c1ccccc1 benzamide
40
+ CCN(CC)CC triethylamine
41
+ CCOCCO diethylene_glycol
42
+ NCCO ethanolamine
43
+ OCCO ethylene_glycol
44
+ CC(C)COC isobutyl_methyl_ether
45
+ CC(C)CC isoamyl
46
+ CC(C)(C)C neopentane
47
+ CNC methylamine
48
+ CN(C)C trimethylamine
49
+ CC(C)=O acetone
50
+ CCOC(=O)C ethyl_acetate
data/examples/example_smiles_1000.smi ADDED
@@ -0,0 +1,1000 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Cc1nc2ccccc2n1CC(C)(C)c1cc(C(F)(F)F)cc(C(F)(F)F)c1 ref_nutlin3a_prelim
2
+ Cc1nc2ccccc2n1CC(F)(F)F lb_00001
3
+ Cc1nc2ccccc2n1Cc1cccc(C(F)(F)F)c1 lb_00002
4
+ Cc1nc2ccccc2n1-c1cc(C(F)(F)F)cc(C(F)(F)F)c1 lb_00003
5
+ Cc1nc2ccccc2n1Cc1ccccc1C(F)(F)F lb_00004
6
+ FC(F)(F)c1cc(-c2nc3ccccc3n2Cc2ccccc2)cc(C(F)(F)F)c1 lb_00005
7
+ Cn1c(-c2cc(C(F)(F)F)cc(C(F)(F)F)c2)nc2ccccc21 lb_00006
8
+ Cc1nc2ccc(C(F)(F)F)cc2n1CCc1ccccc1 lb_00007
9
+ Cc1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00008
10
+ CCCn1c(-c2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00009
11
+ CCn1c(-c2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00010
12
+ CCn1c(C)nc2cc(C(F)(F)F)ccc21 lb_00011
13
+ Cc1nc2ccccc2n1CCC(=O)Nc1cccc(C(F)(F)F)c1 lb_00012
14
+ CCCCn1c(-c2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00013
15
+ CC(C)n1c(-c2cc(C(F)(F)F)cc(C(F)(F)F)c2)nc2ccccc21 lb_00014
16
+ Cc1nc2ccccc2n1CCCCN1CCN(c2cccc(C(F)(F)F)c2)CC1 lb_00015
17
+ Cc1nc2ccccc2n1Cc1cccc(CC(C)(C)C)c1 lb_00016
18
+ Cc1nc2ccccc2n1-c1ccc(C(F)(F)F)cc1C(F)(F)F lb_00017
19
+ Cc1nc2ccccc2n1Cc1ccccc1 lb_00018
20
+ Cc1nc2ccccc2n1CCCCN1CCN(c2cccc(C(F)(F)F)c2)CC1.Cl lb_00019
21
+ Cc1nc2ccccc2n1CC1CCN(Cc2cccc(C(F)(F)F)c2)CC1 lb_00020
22
+ Cc1nc2ccccc2n1CC1CCN(Cc2ccc(C(F)(F)F)cc2)CC1 lb_00021
23
+ CCCCCCn1c(-c2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00022
24
+ Cc1ccc(-c2nc3ccccc3n2CCc2cccc(C(F)(F)F)c2)cc1 lb_00023
25
+ Cc1cc(Cn2c(C(F)(F)F)nc3ccccc32)c(C)cc1Cn1c(C(F)(F)F)nc2ccccc21 lb_00024
26
+ Cc1nc2ccccc2n1Cc1cccc(F)c1 lb_00025
27
+ Cc1nc2ccccc2n1Cc1c(F)cccc1F lb_00026
28
+ Cc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00027
29
+ Cc1nc2ccccc2n1Cc1ccccc1F lb_00028
30
+ Cc1cc(C)c(C)c(Cn2c(C)nc3ccccc32)c1C lb_00029
31
+ Cc1nc2ccccc2n1CCc1ccccc1 lb_00030
32
+ CCCCn1c(C)nc2ccccc21 lb_00031
33
+ CCn1c(C(F)(F)F)nc2ccccc21 lb_00032
34
+ Cc1cc(C)c(-c2nc3ccccc3n2CC(F)(F)F)c(C)c1 lb_00033
35
+ FC(F)(F)c1ccc(Cn2c(-c3ccc(C(F)(F)F)cc3)nc3ccccc32)cc1 lb_00034
36
+ CNc1nc2ccccc2n1-c1cc(C(F)(F)F)cc(C(F)(F)F)c1 lb_00035
37
+ CC(C)c1nc2ccccc2n1-c1cc(C(F)(F)F)cc(C(F)(F)F)c1 lb_00036
38
+ Cc1nc2ccccc2n1Cc1ccc2ccccc2c1 lb_00037
39
+ Cc1cccc(Cn2c(C)nc3ccccc32)c1 lb_00038
40
+ Cc1ccccc1Cn1c(C)nc2ccccc21 lb_00039
41
+ Cc1ccc(Cn2c(C)nc3ccccc32)cc1 lb_00040
42
+ Cc1nc2ccccc2n1CCC(C)C lb_00041
43
+ Cc1ccc(Cn2c(-c3cccc(C(F)(F)F)c3)nc3ccccc32)cc1 lb_00042
44
+ Cc1ccc(Cn2c(-c3ccc(C(F)(F)F)cc3)nc3ccccc32)cc1 lb_00043
45
+ CC(C)(C)c1ccc(Cn2c(C(F)(F)F)nc3ccccc32)cc1 lb_00044
46
+ Cc1cc(C)c(C)c(Cn2c(C(F)(F)F)nc3ccccc32)c1C lb_00045
47
+ Cc1cc(C)c(Cn2c(C(F)(F)F)nc3ccccc32)c(C)c1 lb_00046
48
+ FC(F)(F)c1cccc(Cn2c(C(F)(F)F)nc3ccccc32)c1 lb_00047
49
+ FC(F)(F)c1ccc(Cn2c(-c3ccccc3)nc3ccccc32)cc1 lb_00048
50
+ FC(F)(F)c1ccc(-c2nc3ccccc3n2Cc2ccccc2)cc1 lb_00049
51
+ CC(C)(C)c1cc(Cn2c(-c3cc(C(C)(C)C)cc(C(C)(C)C)c3)nc3ccccc32)cc(C(C)(C)C)c1 lb_00050
52
+ Cn1c(N=Nc2cc(C(F)(F)F)cc(C(F)(F)F)c2)nc2ccccc21 lb_00051
53
+ CCc1nc2ccccc2n1CC(F)(F)c1ccccc1 lb_00052
54
+ Cc1ccc(C)c(Cn2c(C)nc3ccccc32)c1 lb_00053
55
+ Cc1nc2ccc(C(F)(F)F)cc2n1-c1ccccc1 lb_00054
56
+ CCC(C)Cn1c(C)nc2ccccc21 lb_00055
57
+ CCCCCCCCCCCCn1c(C)nc2ccccc21 lb_00056
58
+ CCCCCCCCCCn1c(C)nc2ccccc21 lb_00057
59
+ CCCn1c(C(F)(F)F)nc2ccccc21 lb_00058
60
+ CCCCCCCCn1c(C)nc2ccccc21 lb_00059
61
+ CCCCCCCCCn1c(C)nc2ccccc21 lb_00060
62
+ FC(F)(F)c1cccc(-c2nc3ccccc3n2CCCc2ccccc2)c1 lb_00061
63
+ FC(F)(F)c1cc(CN2CCN(Cc3nc4ccccc4n3Cc3ccccc3)CC2)cc(C(F)(F)F)c1 lb_00062
64
+ C=CCn1c(-c2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00063
65
+ Cc1cccc(Cn2c(C(F)(F)F)nc3ccccc32)c1 lb_00064
66
+ Nc1nc2ccccc2n1Cc1cccc(C(F)(F)F)c1 lb_00065
67
+ FC(F)(F)c1cccc(Cn2c(Cl)nc3ccccc32)c1 lb_00066
68
+ C=CCn1c(-c2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00067
69
+ N#CCn1c(-c2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00068
70
+ FC(F)(F)c1ccc(-c2ccc(-c3nc4ccccc4n3Cc3ccccc3)cc2)cc1 lb_00069
71
+ Cn1c(-c2cc(N)cc(C(F)(F)F)c2)nc2ccccc21 lb_00070
72
+ Cc1ccccc1Cn1c(C(F)(F)F)nc2ccccc21 lb_00071
73
+ Cn1c(-c2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00072
74
+ Cc1ccc(Cn2c(C(F)(F)F)nc3ccccc32)cc1 lb_00073
75
+ Cn1c(-c2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00074
76
+ Br.CCCCCCCCCCCCn1c(C)nc2ccccc21 lb_00075
77
+ CCCCCCCCCn1c(C)nc2ccccc21.Cl lb_00076
78
+ Fc1cc(F)cc(Cn2c(-c3ccc(-c4ccc(C(F)(F)F)cc4)cc3)nc3ccccc32)c1 lb_00077
79
+ Cc1ccc(C)c(Cn2c(C(F)(F)F)nc3ccccc32)c1 lb_00078
80
+ Cc1nc2ccccc2n1Cc1ccc(-c2ccccc2)cc1F lb_00079
81
+ CCn1c(NCc2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00080
82
+ CCCn1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00081
83
+ Cc1nc2ccccc2n1Cc1ccc(F)cc1CN lb_00082
84
+ Cc1nc2ccccc2n1Cc1cc(F)ccc1CN lb_00083
85
+ FC(F)(F)c1cc(Cn2c3ccccc3c3nc4ccccc4nc32)cc(C(F)(F)F)c1 lb_00084
86
+ CC(C)(C)c1ccc(-c2nc3ccccc3n2CCF)cc1 lb_00085
87
+ Cc1nc2ccccc2n1Cc1cccc2ccccc12 lb_00086
88
+ Cc1nc2ccccc2n1C/C=C/c1ccccc1 lb_00087
89
+ CCCn1c(Nc2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00088
90
+ CCNc1nc2ccccc2n1Cc1cccc(C(F)(F)F)c1 lb_00089
91
+ CCCCn1c(C(F)(F)F)nc2ccccc21 lb_00090
92
+ Cc1nc2ccccc2n1Cc1ccc(CN)cc1F lb_00091
93
+ Cc1nc2ccccc2n1CC(N)c1cccc(F)c1 lb_00092
94
+ Cc1nc2ccccc2n1Cc1cc(CN)ccc1F lb_00093
95
+ Cc1nc2ccccc2n1CC(N)c1ccc(F)c(F)c1 lb_00094
96
+ Cc1nc2ccccc2n1C(F)(F)C(F)F lb_00095
97
+ FC(F)(F)c1nc2ccccc2n1CC#CCn1c(C(F)(F)F)nc2ccccc21 lb_00096
98
+ Fc1ccc(Cn2c(CN3CCN(Cc4cc(C(F)(F)F)cc(C(F)(F)F)c4)CC3)nc3ccccc32)cc1 lb_00097
99
+ CCn1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00098
100
+ FC(F)(F)c1ccc(Cn2c(CBr)nc3ccccc32)cc1 lb_00099
101
+ Cn1c(-c2ccc(C(F)(F)F)cc2C(F)(F)F)nc2ccccc21 lb_00100
102
+ Cc1nc2ccccc2n1CC(N)c1ccccc1F lb_00101
103
+ Cc1nc2ccccc2n1CC(N)c1ccc(F)cc1 lb_00102
104
+ Cc1nc2ccccc2n1CC(N)c1c(F)cccc1F lb_00103
105
+ Nc1cccc(-c2nc3ccccc3n2Cc2ccc(C(F)(F)F)cc2)c1 lb_00104
106
+ CCn1c(C)nc2cc(C(C(F)(F)F)(C(F)(F)F)C(F)(F)F)ccc21 lb_00105
107
+ Cc1nc2cc(C(F)(F)F)ccc2n1-c1ccccc1 lb_00106
108
+ Cc1nc2ccccc2n1CC(N)c1ccc(F)cc1F lb_00107
109
+ Cc1nc2ccccc2n1CC(N)c1cc(F)ccc1F lb_00108
110
+ Cc1nc2ccccc2n1Cc1cc(C#N)ccc1F lb_00109
111
+ CCN(CC)CCCn1c(C)nc2cc(C(F)(F)F)ccc21 lb_00110
112
+ CCCn1c(-c2ccccc2C)nc2cc(C(F)(F)F)ccc21 lb_00111
113
+ Fc1ccc(Cn2c(-c3ccc(-c4ccc(C(F)(F)F)cc4)cc3)nc3ccccc32)cc1 lb_00112
114
+ FC(F)(F)c1nc2ccccc2n1Cc1ccccc1 lb_00113
115
+ FC(F)(F)c1cc(-n2cnc3ccccc32)cc(C(F)(F)F)c1 lb_00114
116
+ Cc1ccc(C=Cc2nc3ccccc3n2Cc2cccc(C(F)(F)F)c2)cc1 lb_00115
117
+ Cc1ccc(/C=C/c2nc3ccccc3n2Cc2cccc(C(F)(F)F)c2)cc1 lb_00116
118
+ Nc1cccc(-c2nc3ccccc3n2CC(F)(F)F)c1 lb_00117
119
+ Cn1c(-c2cc(C(F)(F)F)ccc2N)nc2ccccc21 lb_00118
120
+ CCCCn1c(C)nc2cc(C(F)(F)F)cc(N)c21 lb_00119
121
+ CCCCn1c(Nc2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00120
122
+ CCn1c(C(C)(C)C)nc2ccccc21 lb_00121
123
+ Nc1ccc(-c2nc3ccccc3n2CC(F)(F)F)cc1 lb_00122
124
+ Cn1c(Cn2c(C(F)(F)F)nc3ccccc32)nc2ccccc21 lb_00123
125
+ CCCCCCn1c(C(F)(F)F)nc2ccccc21 lb_00124
126
+ Nc1nc2ccccc2n1CCCc1cccc(C(F)(F)F)c1 lb_00125
127
+ FC(F)(F)c1cc(CNCc2nc3ccccc3n2-c2ccccc2)cc(C(F)(F)F)c1 lb_00126
128
+ FC(F)(F)c1ccc(Cn2c(CBr)nc3ccccc32)c(C(F)(F)F)c1 lb_00127
129
+ CN(C)CCn1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00128
130
+ Cc1nc2ccccc2n1CCNCc1cccc(F)c1 lb_00129
131
+ CCCCN(CCCC)CCCn1c(C)nc2cc(C(F)(F)F)ccc21 lb_00130
132
+ Fc1ccc(Cn2c(CNc3cc(C(F)(F)F)cc(C(F)(F)F)c3)nc3ccccc32)c(F)c1 lb_00131
133
+ CCn1c(C(C)NCc2cc(F)cc(C(F)(F)F)c2)nc2ccccc21 lb_00132
134
+ FC(F)(F)c1nc2ccccc2n1CCc1ccccc1 lb_00133
135
+ C=CCn1c(C(F)(F)F)nc2ccccc21 lb_00134
136
+ Cc1cc(C(F)(F)F)ccc1-c1nc2ccccc2n1-c1c(C)cccc1C lb_00135
137
+ Cc1ccc(NCCn2c(C(F)(F)F)nc3ccccc32)cc1 lb_00136
138
+ Cc1nc2ccccc2n1CCNCc1ccc(F)cc1 lb_00137
139
+ Cc1nc2ccccc2n1CCNCc1ccccc1F lb_00138
140
+ CCn1c(-c2ccccc2C)nc2cc(C(F)(F)F)ccc21 lb_00139
141
+ CC(C)(C)c1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00140
142
+ CCCCCn1c(Nc2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00141
143
+ Cc1nc2cc(C(F)(F)F)ccc2n1C lb_00142
144
+ CC(C)(C)c1ccc(Cn2c(-c3ccc(C(C)(C)C)cc3)nc3ccccc32)cc1 lb_00143
145
+ FC(F)(F)c1nc2ccccc2n1Cc1ccc2ccccc2c1 lb_00144
146
+ I.Nc1nc2ccccc2n1CCCc1cccc(C(F)(F)F)c1 lb_00145
147
+ FC(F)(F)c1cccc(CNc2nc3ccccc3n2Cc2ccccc2)c1 lb_00146
148
+ CC1=CN=C(n2c(C)nc3ccccc32)N(c2ccc(C(F)(F)F)cc2)C1 lb_00147
149
+ Cc1cc(-c2nc3ccccc3n2C2CCC2)cc(C(F)(F)F)c1 lb_00148
150
+ CC(C)(CNc1nc2ccccc2[nH]1)c1cc(F)cc(C(F)(F)F)c1 lb_00149
151
+ Cc1nc2ccccc2n1Cc1cc(C(N)=S)ccc1F lb_00150
152
+ Cc1nc2ccccc2n1Cc1ccc(F)cc1C(=N)N lb_00151
153
+ Cl.Fc1ccc(Cn2c(CNc3cc(C(F)(F)F)cc(C(F)(F)F)c3)nc3ccccc32)c(F)c1 lb_00152
154
+ CC(C)=CCCC(C)CCn1c(-c2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00153
155
+ CC(C)(CC(=O)O)Cc1nc2ccccc2n1Cc1cccc(C(F)(F)F)c1 lb_00154
156
+ CC(C)n1c(-c2ccc(C(F)(F)F)cc2C(F)(F)F)nc2ccccc21 lb_00155
157
+ CCc1nc2ccccc2n1CCCCNc1cccc(C(F)(F)F)c1 lb_00156
158
+ CC.OB(O)Cc1nc2ccccc2n1Cc1ccc(C(F)(F)F)cc1C(F)(F)F lb_00157
159
+ CCCCCCn1c(Nc2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00158
160
+ CC(C)Cn1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00159
161
+ Cn1c(C(F)(F)F)nc2ccccc21 lb_00160
162
+ Cc1nc2ccccc2n1C(F)F lb_00161
163
+ FC(F)(F)c1cc(C2SCc3nc4ccccc4n32)cc(C(F)(F)F)c1 lb_00162
164
+ CCN(CC)CCn1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00163
165
+ CN(C)CCCn1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00164
166
+ Cc1cc(C)cc(NC(=O)Cn2c(C(F)(F)F)nc3ccccc32)c1 lb_00165
167
+ FC(F)(F)c1cccc(-c2nc3ccccc3n2-c2ccccc2)c1 lb_00166
168
+ FC(F)(F)c1ccccc1Cn1c(-c2ccccc2C(F)(F)F)nc2ccccc21 lb_00167
169
+ Cc1cccc(C)c1-n1c(-c2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00168
170
+ CC(C)(C)c1ccc(-c2nc3ccccc3n2Cc2ccccc2)cc1 lb_00169
171
+ Fc1cccc(Cn2c(C(F)(F)F)nc3ccccc32)c1 lb_00170
172
+ CCCn1c(-c2ccc(F)c(F)c2)nc2ccccc21 lb_00171
173
+ CCCn1c(-c2cccc(Br)c2)nc2ccccc21 lb_00172
174
+ CC(C)=CCC/C(C)=C/Cn1c(C)nc2ccccc21 lb_00173
175
+ Cn1c(Nc2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00174
176
+ CCCn1c(-c2ccccc2)nc2ccccc21 lb_00175
177
+ CN(C)CCn1c(NCc2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00176
178
+ Nc1nonc1-c1nc2ccccc2n1Cc1cccc(C(F)(F)F)c1 lb_00177
179
+ FC(F)(F)c1ccc(Cn2c(CN3CCCC3)nc3ccccc32)cc1 lb_00178
180
+ Cc1ccccc1N1CCN(c2nc3ccccc3n2CC(F)(F)F)CC1 lb_00179
181
+ CC(C)(C)c1ccc(Cn2c(-c3ccc(F)cc3)nc3ccccc32)cc1 lb_00180
182
+ CC(C)(C)c1ccc(Cn2c(-c3ccccc3F)nc3ccccc32)cc1 lb_00181
183
+ CCCn1c(-c2cccc(C)c2)nc2cc(C(F)(F)F)ccc21 lb_00182
184
+ CCCn1c(-c2ccccc2F)nc2ccccc21 lb_00183
185
+ CCCn1c(-c2cccc(C)c2)nc2ccccc21 lb_00184
186
+ Cc1ccc(Cn2c(C(C)(C)C)nc3ccccc32)cc1 lb_00185
187
+ Fc1ccc(Cn2c(C(F)(F)F)nc3ccccc32)cc1 lb_00186
188
+ CCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00187
189
+ Fc1ccccc1Cn1c(C(F)(F)F)nc2ccccc21 lb_00188
190
+ CCn1c(C(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00189
191
+ FC(F)(F)c1nc2ccccc2n1Cc1ccc(Cl)cc1 lb_00190
192
+ FC(F)(F)c1ccc(-c2nc3ccccc3n2-c2ccccc2)cc1 lb_00191
193
+ CCCn1c(Cn2ccnc2-c2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00192
194
+ CN(Cc1cc(F)cc(C(F)(F)F)c1)Cc1nc2ccccc2n1C lb_00193
195
+ Cn1c(CN2CCC(c3ccc(C(F)(F)F)cc3)CC2)nc2ccccc21 lb_00194
196
+ CC1=CN(c2ccc(C(F)(F)F)cc2)C(n2c(C)nc3ccccc32)N=C1 lb_00195
197
+ OB(O)Cc1nc2ccccc2n1Cc1ccc(C(F)(F)F)cc1C(F)(F)F lb_00196
198
+ Cc1nc2ccccc2n1C1N=CC=CN1c1ccc(C(F)(F)F)cc1 lb_00197
199
+ FC(F)(F)c1cccc(CN2CCN(Cc3nc4ccccc4n3Cc3ccccc3)CC2)c1 lb_00198
200
+ Cc1nc2ccccc2n1CC1CCN(Cc2cc(F)cc(F)c2)CC1 lb_00199
201
+ FC(F)(F)c1ccc2c(c1)nc(-c1ccccn1)n2CCc1ccccc1 lb_00200
202
+ Cc1nc2ccccc2n1CCCN(C)Cc1ccccc1 lb_00201
203
+ FC(F)(F)c1ccc2c(c1)nc(-c1ccccc1)n2Cc1ccccc1 lb_00202
204
+ CC(C)c1ccc(Cn2c(C(F)(F)F)nc3ccccc32)cc1 lb_00203
205
+ CC(C)(C)c1nc2ccccc2n1Cc1ccccc1 lb_00204
206
+ CC.OB(O)CCc1nc2ccccc2n1Cc1ccc(C(F)(F)F)cc1C(F)(F)F lb_00205
207
+ Cl.Cl.FC(F)(F)c1ccc(Cn2c(CN3CCCC3)nc3ccccc32)cc1 lb_00206
208
+ Cc1ccccc1-c1nc2cc(C(F)(F)F)ccc2n1CC(C)C lb_00207
209
+ Cc1ccccc1-c1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00208
210
+ Cc1ccc(-c2nc3cc(C(F)(F)F)ccc3n2Cc2ccccc2)cc1 lb_00209
211
+ CN(CCN(C)c1nc2ccccc2n1Cc1ccc(F)cc1)C(=O)NCc1cc(C(F)(F)F)cc(C(F)(F)F)c1 lb_00210
212
+ CC(C)(C)c1ccc(Cn2c(N)nc3ccccc32)cc1 lb_00211
213
+ Nc1nc2ccccc2n1Cc1ccccc1C(F)(F)F lb_00212
214
+ Nc1ccc(Cn2c(C(F)(F)F)nc3ccccc32)cc1 lb_00213
215
+ FC(F)(F)Cn1c(C#Cc2ccccc2)nc2ccccc21 lb_00214
216
+ FC(F)(F)c1nc2ccccc2n1Cc1cccc2ccccc12 lb_00215
217
+ CC(C)(C)c1nc2ccccc2n1Cc1ccc(F)cc1 lb_00216
218
+ CC(C)(C)c1nc2ccccc2n1Cc1ccccc1F lb_00217
219
+ FC(F)(F)c1nc2ccccc2n1CCCc1ccccc1 lb_00218
220
+ FC(F)(F)c1nc2ccccc2n1Cc1ccccc1Cl lb_00219
221
+ CC(C)Cc1ccc(C(C)c2nc3ccccc3n2Cc2ccc(C(F)(F)F)cc2)cc1 lb_00220
222
+ Cc1nc2ccccc2n1C1N=CC(F)=CN1c1ccc(C(F)(F)F)cc1 lb_00221
223
+ CCN(CC)CCCn1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00222
224
+ Cc1ccccc1-c1nc2cc(C(F)(F)F)ccc2n1CCCN(C)C lb_00223
225
+ CCN(CC)CCn1c(-c2ccccc2C)nc2cc(C(F)(F)F)ccc21 lb_00224
226
+ CC(C)(C)c1cc(NC(=O)Cn2c(-c3ccccc3)nc3ccccc32)cc(C(C)(C)C)c1 lb_00225
227
+ Cc1ccc(NC(=O)Cn2c(C(F)(F)F)nc3ccccc32)cc1C lb_00226
228
+ CCn1c(-c2ccccc2)nc2ccccc21 lb_00227
229
+ Cc1cccc(Cn2c(CC(C)(C)C)nc3ccccc32)c1 lb_00228
230
+ Cc1cccc(Cn2c(C(C)(C)N)nc3ccccc32)c1 lb_00229
231
+ Cc1ccc(C(F)(F)F)cc1Cn1cnc2ccccc21 lb_00230
232
+ CCn1c(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00231
233
+ CCn1c(-c2cccc(C)c2)nc2cc(C(F)(F)F)ccc21 lb_00232
234
+ CCCn1c(-c2ccc(C)cc2)nc2cc(C(F)(F)F)ccc21 lb_00233
235
+ CCc1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00234
236
+ CCCn1c(-c2cccc(C(F)(F)F)c2)nc2cc3nc(-c4cccc(C(F)(F)F)c4)n(CCC)c3cc21 lb_00235
237
+ CCCCn1c(-c2cccc(Br)c2)nc2ccccc21 lb_00236
238
+ CCCCn1c(-c2ccccc2)nc2ccccc21 lb_00237
239
+ CCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00238
240
+ Cn1c(-c2ccccc2C(F)(F)F)nc2ccccc21 lb_00239
241
+ CCn1c(C)nc2cc(-c3ccccc3)ccc21 lb_00240
242
+ Cn1c(-c2cc(-c3nc4ccccc4n3C)cc(C(C)(C)C)c2)nc2ccccc21 lb_00241
243
+ CCn1c(-c2ccccc2F)nc2ccccc21 lb_00242
244
+ C=CCn1c(C(C)(C)C)nc2ccccc21 lb_00243
245
+ Nc1nc2ccccc2n1-c1ccc(C(F)(F)F)cc1 lb_00244
246
+ CC(F)(F)c1ccc(Cn2c(CN3CCCC3)nc3ccccc32)cc1 lb_00245
247
+ Cc1cccc(-c2nc3cc(C(F)(F)F)ccc3n2Cc2ccccc2)c1 lb_00246
248
+ Cc1nc2ccccc2n1Cc1ccc2c(c1)CCc1ccccc1N2 lb_00247
249
+ Cn1c(/C=C/c2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00248
250
+ Cc1ccccc1Cn1c(CC(C)(C)C)nc2ccccc21 lb_00249
251
+ Cn1c(C=Cc2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00250
252
+ Cn1c(C#Cc2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00251
253
+ CCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00252
254
+ CC(F)(F)c1ccc(-c2nc3ccccc3n2-c2ccccc2)cc1 lb_00253
255
+ Cc1cccc(-c2nc3ccccc3n2CCc2ccccc2)c1 lb_00254
256
+ CCCCn1c(-c2c(F)cccc2F)nc2ccccc21 lb_00255
257
+ FC(F)(F)c1nc2ccccc2n1C/C=C/c1ccccc1 lb_00256
258
+ CCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00257
259
+ CCCn1c(C(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00258
260
+ CCCn1c(-c2ccc(C(F)(F)F)cc2)nc2cc3nc(-c4ccc(C(F)(F)F)cc4)n(CCC)c3cc21 lb_00259
261
+ Cc1nc2ccccc2n1CC1CCN(Cc2ccc(F)c(F)c2)CC1 lb_00260
262
+ CC(C)(C)c1ccc(N2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)cc1 lb_00261
263
+ Cc1nc2ccccc2n1CC1CCN(Cc2cccc(F)c2)CC1 lb_00262
264
+ CCCCN(CCCC)CCCn1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00263
265
+ Cc1nc2cc(C(F)(F)F)ccc2n1C[C@@H]1CCCN2CCCC[C@H]12 lb_00264
266
+ CC(C)(N)c1nc2ccccc2n1Cc1cccc(F)c1 lb_00265
267
+ Cn1c(C(F)(F)c2ccccc2)nc2ccccc21 lb_00266
268
+ Nc1nc2ccccc2n1Cc1ccc(F)cc1C(F)(F)F lb_00267
269
+ CN1CCC(n2c(C(N)Cc3cc(C(F)(F)F)cc(C(F)(F)F)c3)nc3ccccc32)CC1 lb_00268
270
+ CC(C)c1nc2ccccc2n1-c1ccc(C(F)(F)F)cc1C(F)(F)F lb_00269
271
+ CCCn1c(Nc2ccccc2C(F)(F)F)nc2ccccc21 lb_00270
272
+ CCCn1c(-c2ccc(F)cc2)nc2cc(C(F)(F)F)ccc21 lb_00271
273
+ CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1CC lb_00272
274
+ CC(C)c1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00273
275
+ CCCn1c(-c2ccc(F)c(N)c2)nc2ccccc21 lb_00274
276
+ CCCn1c(-c2cc(N)ccc2F)nc2ccccc21 lb_00275
277
+ CCCn1c(-c2cc(N)c(F)cc2F)nc2ccccc21 lb_00276
278
+ CCCn1c(-c2ccc(N)c(F)c2)nc2ccccc21 lb_00277
279
+ CCC(c1ccccc1)c1nc2ccccc2n1-c1ccc(C(F)(F)F)cc1 lb_00278
280
+ CC(C)n1c(C(F)(F)F)nc2ccccc21 lb_00279
281
+ CN(CCN(C)C(=O)NCc1cc(C(F)(F)F)cc(C(F)(F)F)c1)Cc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00280
282
+ Cc1nc2ccccc2n1Cc1ccc(B2OC(C)(C)C(C)(C)O2)cc1 lb_00281
283
+ Cn1c(CN2CCN(Cc3cccc(C(F)(F)F)c3)CC2)nc2ccccc21 lb_00282
284
+ Cc1nc2ccccc2n1CC1CCN(Cc2ccc(F)cc2)CC1 lb_00283
285
+ Cc1nc2ccccc2n1CC1CCN(Cc2ccccc2F)CC1 lb_00284
286
+ CCCCCn1c(-c2ccccc2)nc2ccccc21 lb_00285
287
+ CC(c1ccccc1)n1c(C(F)(F)F)nc2ccccc21 lb_00286
288
+ CC(C)CCn1c(-c2ccccc2)nc2ccccc21 lb_00287
289
+ CC(C)(C)Cc1nc2ccccc2n1Cc1ccccc1 lb_00288
290
+ C[C@@H](c1ccccc1)n1c(C(F)(F)F)nc2ccccc21 lb_00289
291
+ C[C@H](c1ccccc1)n1c(C(F)(F)F)nc2ccccc21 lb_00290
292
+ COCCn1c(-c2ccccc2)nc2ccccc21 lb_00291
293
+ CCn1c(N)nc2cc(C(F)(F)F)ccc21 lb_00292
294
+ Cn1c(CN2CCC(c3cccc(C(F)(F)F)c3)CC2)nc2ccccc21 lb_00293
295
+ Cc1nc2ccccc2n1CC1CCN(Cc2cc(F)ccc2F)CC1 lb_00294
296
+ CCN(CC)CCCn1c(-c2ccccc2C)nc2cc(C(F)(F)F)ccc21 lb_00295
297
+ O[B-](O)(O)CSc1nc2ccccc2n1Cc1ccc(C(F)(F)F)cc1C(F)(F)F lb_00296
298
+ CCCCCn1c(-c2cccc(C)c2)nc2ccccc21 lb_00297
299
+ Cc1cccc(-c2nc3ccccc3n2CCC(C)C)c1 lb_00298
300
+ FC(F)(F)c1nc2ccccc2n1CCC1CCCCC1 lb_00299
301
+ CC(C)(C)Cc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00300
302
+ CC(C)CCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00301
303
+ CN(C)c1ccc(-c2nc3ccccc3n2CCF)cc1 lb_00302
304
+ CCCCCn1c(-c2c(F)cccc2F)nc2ccccc21 lb_00303
305
+ Cc1ccc2c(c1)nc(C(F)(F)F)n2Cc1ccccc1 lb_00304
306
+ CCc1ccc(-c2ccc(-c3nc4ccccc4n3CCF)cc2)cc1 lb_00305
307
+ CCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00306
308
+ CCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00307
309
+ CC(C)CCn1c(-c2ccccc2F)nc2ccccc21 lb_00308
310
+ CCn1c(-c2ccc(C)cc2)nc2cc(C(F)(F)F)ccc21 lb_00309
311
+ CC(C)Cn1c(C(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00310
312
+ CC(C)(O)c1nc2ccccc2n1Cc1ccccc1F lb_00311
313
+ CC(C)(O)c1nc2ccccc2n1Cc1ccc(F)cc1 lb_00312
314
+ CC(F)(F)c1nc2ccccc2n1CC1CCC(F)(F)CC1 lb_00313
315
+ CC(C)c1cccc(C(C)C)c1-n1c(-c2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00314
316
+ CCC(C)c1ccc(Cn2c(C(F)(F)F)nc3ccccc32)cc1 lb_00315
317
+ N#Cc1cccc(Cn2c(C(F)(F)F)nc3ccccc32)c1 lb_00316
318
+ Cn1c(CN2CCN(Cc3ccc(C(F)(F)F)cc3)CC2)nc2ccccc21 lb_00317
319
+ CCCn1c(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00318
320
+ CCCc1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00319
321
+ FC(F)(F)c1cccc(Cn2c3ccccc3c3nc4ccccc4nc32)c1 lb_00320
322
+ CCn1c(-c2ccc(C)cc2)nc2ccccc21 lb_00321
323
+ c1ccc(CCn2c(-c3ccccc3)nc3ccccc32)cc1 lb_00322
324
+ Cc1cccc(Cn2c(C(C)(C)N)nc3cc(C(F)(F)F)ccc32)c1 lb_00323
325
+ Cc1ccc(-c2nc3cc(C(F)(F)F)ccc3n2Cc2ccccc2)c(C)c1 lb_00324
326
+ Cc1nc2ccccc2n1CCNCc1cccc(C#N)c1 lb_00325
327
+ CN(C)CCn1c(Cn2nc3ccccc3n2)nc2cc(C(F)(F)F)ccc21 lb_00326
328
+ Cn1c(-c2cccc(C(C)(C)C)c2)nc2ccccc21 lb_00327
329
+ CC(C)(C)Cc1nc2ccccc2n1CCc1ccccc1 lb_00328
330
+ CCCCCCCn1c(-c2ccccc2)nc2ccccc21 lb_00329
331
+ CCCCCCn1c(-c2ccccc2)nc2ccccc21 lb_00330
332
+ CCCCn1c(-c2ccc(C)cc2)nc2ccccc21 lb_00331
333
+ CCCCCCCCCCCCn1c(-c2ccccc2)nc2ccccc21 lb_00332
334
+ CCCCn1c(-c2ccccc2C)nc2ccccc21 lb_00333
335
+ Cn1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00334
336
+ C=CCn1c(CC(C)(C)C)nc2ccccc21 lb_00335
337
+ CCCn1c(-c2ccc(N)cc2)nc2ccccc21 lb_00336
338
+ CC1(CC(F)F)Cn2c(nc3ccccc32)-c2ccc(C(F)(F)F)cc21 lb_00337
339
+ CCCCN(CCCC)CCCn1c(-c2ccccc2C)nc2cc(C(F)(F)F)ccc21 lb_00338
340
+ CC(C)(C)c1ccc(Cn2c(Cc3ccccc3)nc3ccccc32)cc1 lb_00339
341
+ FC(F)(F)c1ccc([C@H]2Cc3nc4ccccc4n3C2)cc1 lb_00340
342
+ CN(C)c1ccc(-c2ccc(-c3nc4ccccc4n3CCF)cc2)cc1 lb_00341
343
+ CC(C)(C)c1nc2ccccc2n1CC1CCC(F)CC1 lb_00342
344
+ CCCCCCCCCCCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00343
345
+ CCCCCCCCCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00344
346
+ CCCCCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00345
347
+ CCCCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00346
348
+ CCCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00347
349
+ CCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00348
350
+ CCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00349
351
+ CCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00350
352
+ CCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00351
353
+ CCCCCCCCCCCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00352
354
+ CCCCCCCCCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00353
355
+ CCCCCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00354
356
+ CCCCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00355
357
+ CCCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00356
358
+ CCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00357
359
+ CCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00358
360
+ CCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00359
361
+ CCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00360
362
+ N#Cc1ccccc1Cn1c(C(F)(F)F)nc2ccccc21 lb_00361
363
+ FC(F)(F)c1ccc2c(c1)nc(Cc1ccccc1)n2Cc1ccccc1 lb_00362
364
+ CC(C)Cn1c(-c2cccc(Br)c2)nc2ccccc21 lb_00363
365
+ CC(C)(C)c1ccc(CCn2c(N)nc3ccccc32)cc1F lb_00364
366
+ CCCCn1c(Nc2ccccc2C(F)(F)F)nc2ccccc21 lb_00365
367
+ CCCCn1c(-c2ccc(F)cc2)nc2cc(C(F)(F)F)ccc21 lb_00366
368
+ N#Cc1ccc(F)c(Cn2c(C(F)(F)F)nc3ccccc32)c1 lb_00367
369
+ CCCn1c(C(CC)c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00368
370
+ CCCn1c(-c2ccc(C)cc2C)nc2cc(C(F)(F)F)ccc21 lb_00369
371
+ CC(C)Cn1c(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00370
372
+ Cc1cccc(-c2nc3cc(C(F)(F)F)ccc3n2CC(C)C)c1 lb_00371
373
+ CNCc1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00372
374
+ Cc1nc2ccccc2n1CCCCN1CCN(C(c2ccccc2)c2ccccc2)CC1 lb_00373
375
+ FC(F)(F)n1c(-c2ccccc2)nc2ccccc21 lb_00374
376
+ Cc1ccccc1-n1c(C)nc2ccccc21 lb_00375
377
+ COCCCn1c(-c2cccc(C)c2)nc2cc(C(F)(F)F)ccc21 lb_00376
378
+ Cc1cccc(-c2nc3cc(C(F)(F)F)ccc3n2CCCN(C)C)c1 lb_00377
379
+ CCN(CC)CCn1c(-c2cccc(C)c2)nc2cc(C(F)(F)F)ccc21 lb_00378
380
+ Cn1c([C@H]2CCN(Cc3ccc(C(F)(F)F)cc3)C2)nc2ccccc21 lb_00379
381
+ Cn1c(C2CCN(Cc3ccc(C(F)(F)F)cc3)C2)nc2ccccc21 lb_00380
382
+ Cc1cccc(NC(=O)Cn2c(C(F)(F)F)nc3ccccc32)c1C lb_00381
383
+ CC(C)Cn1c(-c2ccccc2)nc2ccccc21 lb_00382
384
+ Cc1cc2nc(C)n(Cc3ccccc3)c2cc1C lb_00383
385
+ COCn1c(-c2ccccc2)nc2ccccc21 lb_00384
386
+ FC(F)(F)c1cc(-c2nc3ccccc3[nH]2)cc(C(F)(F)F)c1 lb_00385
387
+ Cc1cccc(CN2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)c1 lb_00386
388
+ CC(C)(C)c1ccc(-c2nc3ccccc3n2C(F)F)cc1 lb_00387
389
+ Cc1cccc(-c2nc3ccccc3n2Cc2ccccc2)c1 lb_00388
390
+ Cc1cccc(Cn2c(N)nc3ccccc32)c1 lb_00389
391
+ Cc1cccc(Cn2c(-c3cccc(C)c3)nc3ccccc32)c1 lb_00390
392
+ Cc1cc2nc(C)n(Cc3ccccc3F)c2cc1C lb_00391
393
+ FC(c1nc2ccccc2n1Cc1ccccc1)C(F)(F)F lb_00392
394
+ Cc1cc(C)c(Cn2c(-c3ccccc3)nc3ccccc32)c(C)c1 lb_00393
395
+ Fc1ccc(-c2nc3ccccc3n2CCc2ccccc2)cc1 lb_00394
396
+ Fc1ccccc1-c1nc2ccccc2n1CCc1ccccc1 lb_00395
397
+ CC(C)Cn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00396
398
+ CC(C)Cn1c(-c2ccccc2F)nc2ccccc21 lb_00397
399
+ CCOCCn1c(-c2ccccc2)nc2ccccc21 lb_00398
400
+ CCN(CC)CCn1c(C(C)(C)C)nc2ccccc21 lb_00399
401
+ Cc1nc2cc(N)ccc2n1Cc1ccccc1.Cl lb_00400
402
+ FC(F)(F)c1ccc2nc(-c3ccccc3)n(-c3ccccc3)c2c1 lb_00401
403
+ CC(C)CCn1c(CC(C)(C)C)nc2ccccc21 lb_00402
404
+ CCn1c(-c2ccccc2-c2ccc(F)cc2F)nc2ccccc21 lb_00403
405
+ Cc1cccc(-c2nc3ccccc3n2Cc2ccccc2F)c1 lb_00404
406
+ Cc1cccc(-c2nc3ccccc3n2Cc2ccc(F)cc2)c1 lb_00405
407
+ Cc1cc(C)c(Cn2c(-c3ccc(F)cc3)nc3ccccc32)c(C)c1 lb_00406
408
+ Cc1cc(C)c(Cn2c(-c3ccccc3F)nc3ccccc32)c(C)c1 lb_00407
409
+ Cc1cc(C)c(C)c(Cn2c(-c3ccc(F)cc3)nc3ccccc32)c1C lb_00408
410
+ Cc1cc(C)c(C)c(Cn2c(-c3ccccc3F)nc3ccccc32)c1C lb_00409
411
+ Cc1nc2ccccc2n1C(CN)c1cccc(F)c1 lb_00410
412
+ COCc1nc2ccccc2n1Cc1ccc(C(C)(C)C)cc1 lb_00411
413
+ CN(CCCN(C)c1nc2ccccc2n1Cc1ccc(F)cc1)C(=O)NCc1cc(C(F)(F)F)cc(C(F)(F)F)c1 lb_00412
414
+ Cn1c(CN2CCN(c3ccc(C(F)(F)F)cc3)CC2)nc2ccccc21 lb_00413
415
+ FC(F)(F)c1ccc2c(c1)nc(C1CC1)n2CCc1ccccc1 lb_00414
416
+ CN(C)c1cccc(-c2ccc(-c3nc4ccccc4n3CCF)cc2)c1 lb_00415
417
+ CCCCCn1c(Nc2ccccc2C(F)(F)F)nc2ccccc21 lb_00416
418
+ CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1CC(C)C lb_00417
419
+ CCC(C)c1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00418
420
+ CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00419
421
+ Cc1nc2ccccc2n1CCCCN1CC=C(c2ccc(F)cc2)CC1 lb_00420
422
+ Cn1c(CCN2CCN(c3cccc(C(F)(F)F)c3)CC2)nc2ccccc21 lb_00421
423
+ Cc1ccccc1CN1CCC(Cn2c(C(F)(F)F)nc3ccccc32)CC1 lb_00422
424
+ Cc1ccc(CN2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)cc1 lb_00423
425
+ CCCn1c(CC)nc2ccccc21 lb_00424
426
+ Cn1c(C(F)(F)C(F)(F)F)nc2ccccc21 lb_00425
427
+ Cn1c(CC(C)(C)C)nc2ccccc21 lb_00426
428
+ FC(F)(F)c1nc2ccccc2n1-c1ccccc1 lb_00427
429
+ Cc1ccc(C)c(CN2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)c1 lb_00428
430
+ Cc1ccc(Cn2c(N)nc3ccccc32)cc1 lb_00429
431
+ Cc1ccc(Cn2c(-c3ccc(C)cc3)nc3ccccc32)cc1 lb_00430
432
+ CCn1c(-c2ccc(N)cc2)nc2ccccc21 lb_00431
433
+ Cc1cccc(Cn2c(-c3ccccc3)nc3ccccc32)c1 lb_00432
434
+ CCCn1c(-c2ccc(N(C)C)cc2)nc2ccccc21 lb_00433
435
+ C=CCn1c(-c2cccc(C)c2)nc2ccccc21 lb_00434
436
+ FC(F)(F)c1cccc(Cn2cnc3ccccc32)c1 lb_00435
437
+ CCc1nc2ccccc2n1Cc1cccc(C)c1 lb_00436
438
+ Cc1ccccc1-c1nc2cc(C(F)(F)F)ccc2n1C lb_00437
439
+ Cc1cc(C)c(C)c(Cn2c(CO)nc3ccccc32)c1C lb_00438
440
+ CCCCn1c(-c2ccc(Br)cc2)nc2ccccc21 lb_00439
441
+ CCCCn1c(-c2ccc(N)cc2)nc2ccccc21 lb_00440
442
+ FC(F)(F)c1cc(-c2cnc(-c3cc(C(F)(F)F)cc(C(F)(F)F)c3)n2Cc2ccccc2)cc(C(F)(F)F)c1 lb_00441
443
+ CC(C)(C)c1nc2ccccc2n1CC1CCC(F)(F)CC1 lb_00442
444
+ Cc1cccc(Cn2c(-c3ccc(F)cc3)nc3ccccc32)c1 lb_00443
445
+ Cc1cccc(Cn2c(-c3ccccc3F)nc3ccccc32)c1 lb_00444
446
+ CCn1c(-c2ccc(C)cc2C)nc2cc(C(F)(F)F)ccc21 lb_00445
447
+ Cc1ccc(-c2nc3cc(C(F)(F)F)ccc3n2CC(C)C)cc1 lb_00446
448
+ Cc1cccc(Cn2c(-c3cccc(Br)c3)nc3ccccc32)c1 lb_00447
449
+ Cc1ccc2nc(-c3ccc(C(F)(F)F)cc3)n(Cc3cccc(C(F)(F)F)c3)c2c1 lb_00448
450
+ CCN(CC)CCCn1c(-c2cccc(C)c2F)nc2ccccc21 lb_00449
451
+ CCN(CC)CCCn1c(-c2cccc(F)c2)nc2ccccc21 lb_00450
452
+ CCCCCCn1c(Nc2ccccc2C(F)(F)F)nc2ccccc21 lb_00451
453
+ CCCCn1c(-c2ccc(F)c(F)c2)nc2cc(C(F)(F)F)ccc21 lb_00452
454
+ Cc1ccc(-c2nc3cc(C(F)(F)F)ccc3n2CCCN(C)C)cc1 lb_00453
455
+ CCN(CC)CCn1c(-c2ccc(C)cc2)nc2cc(C(F)(F)F)ccc21 lb_00454
456
+ CCn1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00455
457
+ CCN(CC)CCCn1c(-c2cccc(C)c2)nc2cc(C(F)(F)F)ccc21 lb_00456
458
+ CC(C)(C)c1cc(NC(=O)Cn2c(Cc3ccccc3)nc3ccccc32)cc(C(C)(C)C)c1 lb_00457
459
+ NCc1ccc(-c2nc3ccccc3n2CCCN2CCCCC2)cc1C(F)(F)F lb_00458
460
+ NCc1ccc(-c2nc3ccccc3n2CCCN2CCCCC2)c(C(F)(F)F)c1 lb_00459
461
+ CCN(CC)CCn1c(Cn2nnc3ccccc32)nc2cc(C(F)(F)F)ccc21 lb_00460
462
+ Cn1c(-c2cc(-c3nc4ccccc4n3C)cc(-c3nc4ccccc4n3C)c2)nc2ccccc21 lb_00461
463
+ c1ccc(Cn2c(-c3ccccc3)nc3ccccc32)cc1 lb_00462
464
+ Cc1nc2ccccc2n1C(C)c1ccccc1 lb_00463
465
+ FC(F)(F)c1ccc(-n2cnc3ccccc32)cc1 lb_00464
466
+ CN(CCCN(C)C(=O)NCc1cc(C(F)(F)F)cc(C(F)(F)F)c1)Cc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00465
467
+ Fc1cccc(F)c1Cn1c(-c2c(F)cccc2F)nc2ccccc21 lb_00466
468
+ C=C(C)Cn1c(-c2ccccc2)nc2ccccc21 lb_00467
469
+ Fc1ccc(Cn2c(-c3ccc(F)cc3)nc3ccccc32)cc1 lb_00468
470
+ Cc1ccccc1Cn1c(-c2ccccc2C)nc2ccccc21 lb_00469
471
+ CCc1nc2ccccc2n1Cc1ccccc1C lb_00470
472
+ CCc1nc2ccccc2n1Cc1ccc(C)cc1 lb_00471
473
+ CCc1nc2ccccc2n1Cc1c(F)c(F)c(F)c(F)c1F lb_00472
474
+ Cc1ccc(Cn2c(-c3ccccc3)nc3ccccc32)cc1 lb_00473
475
+ FC(F)(F)c1ccc(Cn2cnc3ccccc32)cc1 lb_00474
476
+ Cc1ccccc1Cn1c(N)nc2ccccc21.Cl lb_00475
477
+ Cc1nc2ccccc2n1-c1ccc(CN)cc1.Cl lb_00476
478
+ CCc1cccc(C(C)(C)c2nc3ccccc3n2C)c1 lb_00477
479
+ Cc1ccccc1-c1nc2ccccc2n1Cc1c(F)cccc1F lb_00478
480
+ Cc1cccc(Cn2c(Cc3ccccc3)nc3ccccc32)c1 lb_00479
481
+ Fc1cccc(Cn2c(-c3cccc(F)c3)nc3ccccc32)c1 lb_00480
482
+ CCc1nc2ccccc2n1Cc1cccc(F)c1 lb_00481
483
+ Cc1ccc(Cn2c(-c3ccc(F)cc3)nc3ccccc32)cc1 lb_00482
484
+ Cc1ccccc1-c1nc2ccccc2n1Cc1ccccc1F lb_00483
485
+ Cc1ccccc1-c1nc2ccccc2n1Cc1ccc(F)cc1 lb_00484
486
+ Cc1ccc(-c2nc3ccccc3n2Cc2ccccc2F)cc1 lb_00485
487
+ Cc1ccc(-c2nc3ccccc3n2Cc2ccc(F)cc2)cc1 lb_00486
488
+ C=C(C)Cn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00487
489
+ Cc1ccccc1Cn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00488
490
+ C=C(C)Cn1c(-c2ccccc2F)nc2ccccc21 lb_00489
491
+ Cc1ccccc1Cn1c(-c2ccccc2F)nc2ccccc21 lb_00490
492
+ Cc1ccc(Cn2c(-c3ccccc3F)nc3ccccc32)cc1 lb_00491
493
+ Cn1c(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00492
494
+ CC(C)n1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00493
495
+ Cc1nc2ccccc2n1C(CN)c1ccc(F)cc1 lb_00494
496
+ Cc1nc2ccccc2n1C(CN)c1ccccc1F lb_00495
497
+ CCCn1c(-c2ccc(C#Cc3ccccc3)cc2)nc2ccccc21 lb_00496
498
+ FC(F)(F)c1cc(NCc2nc3ccccc3[nH]2)cc(C(F)(F)F)c1 lb_00497
499
+ CC(C)CCn1c(-c2ccc(N)cc2)nc2ccccc21 lb_00498
500
+ CCN(CC)CCCn1c(-c2ccccc2F)nc2ccccc21 lb_00499
501
+ Cc1ccc(-c2nc3ccccc3n2Cc2ccccc2F)c(C)c1 lb_00500
502
+ Cc1ccc(-c2nc3ccccc3n2Cc2ccc(F)cc2)c(C)c1 lb_00501
503
+ Cc1ccc(C)c(Cn2c(-c3ccc(F)cc3)nc3ccccc32)c1 lb_00502
504
+ Fc1ccc(-c2nc3ccccc3n2CCC2CCCCC2)cc1 lb_00503
505
+ Fc1ccccc1-c1nc2ccccc2n1CCC1CCCCC1 lb_00504
506
+ Cc1ccc(C)c(Cn2c(-c3ccccc3F)nc3ccccc32)c1 lb_00505
507
+ CN(C)CCCn1c(C(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00506
508
+ CCN(CC)CCn1c(C(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00507
509
+ CCC(C)n1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00508
510
+ FC(F)(F)c1cccc(C2SCc3nc4ccccc4n32)c1 lb_00509
511
+ CC(C)(N)c1nc2cc(C(F)(F)F)ccc2n1Cc1cccc(F)c1 lb_00510
512
+ CCN(CC)CCCn1c(-c2cc(C)ccc2F)nc2ccccc21 lb_00511
513
+ Cc1cccc(-c2nc3ccccc3n2CCCN2CCC(F)CC2)c1 lb_00512
514
+ CCCn1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00513
515
+ CC(C)(C)c1ccc(Cn2c(-c3nonc3N)nc3ccccc32)cc1 lb_00514
516
+ Cn1c(CCCN2CCN(c3cccc(C(F)(F)F)c3)CC2)nc2ccccc21 lb_00515
517
+ Cc1nc2ccccc2n1C1N=CC=CN1c1ccc(C(F)(F)F)c(F)c1 lb_00516
518
+ CCc1nc2ccccc2n1C1=C(F)C=NCN1c1ccc(C(F)(F)F)cc1 lb_00517
519
+ CCCCN(CCCC)CCCn1c(-c2cccc(C)c2)nc2cc(C(F)(F)F)ccc21 lb_00518
520
+ Cn1c(NCCN2CCN(c3cccc(C(F)(F)F)c3)CC2)nc2ccccc21 lb_00519
521
+ FC(F)(F)c1cc(Cc2nc3ccccc3n2C(CCc2ccccc2)c2nc3ccccc3[nH]2)cc(C(F)(F)F)c1 lb_00520
522
+ CC(=O)Nc1cccc(C2CCN(CCCn3c(-c4cccc(C(F)(F)F)c4)nc4ccccc43)CC2)c1 lb_00521
523
+ CCc1nc2ccccc2n1Cc1ccccc1 lb_00522
524
+ Fc1ccc(Cn2c(F)nc3ccccc32)cc1 lb_00523
525
+ CCn1c(Cc2ccccc2)nc2ccccc21 lb_00524
526
+ Cc1nc2ccccc2n1/C=C\c1ccccc1 lb_00525
527
+ Cn1c(Cl)nc2cc(C(F)(F)F)ccc21 lb_00526
528
+ Cc1nc2ccccc2n1C1CCCCC1 lb_00527
529
+ CCc1nc2ccccc2n1CC(C)C lb_00528
530
+ CCCCn1c(CC)nc2ccccc21 lb_00529
531
+ Fc1cccc(F)c1Cn1c(-c2ccccc2)nc2ccccc21 lb_00530
532
+ CCn1c(-c2ccc(N(C)C)cc2)nc2ccccc21 lb_00531
533
+ C=CCn1c(-c2ccc(C)cc2)nc2ccccc21 lb_00532
534
+ CCc1nc2ccccc2n1Cc1ccccc1F lb_00533
535
+ CCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00534
536
+ Fc1ccccc1Cn1c(-c2ccccc2)nc2ccccc21 lb_00535
537
+ Fc1cccc(F)c1-c1nc2ccccc2n1Cc1ccccc1 lb_00536
538
+ Fc1ccccc1Cn1c(-c2ccccc2F)nc2ccccc21 lb_00537
539
+ Fc1ccc(-c2nc3ccccc3n2Cc2ccccc2)cc1 lb_00538
540
+ CCn1c(-c2ccc(C(C)C)cc2)nc2ccccc21 lb_00539
541
+ Cn1c(CC(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00540
542
+ Cc1ccc(Cn2c(C(C)C)nc3ccccc32)cc1 lb_00541
543
+ CC(C)=CCn1c(-c2ccccc2)nc2ccccc21 lb_00542
544
+ Fc1ccc(Cn2c(-c3ccccc3)nc3ccccc32)cc1 lb_00543
545
+ Fc1ccccc1-c1nc2ccccc2n1Cc1ccccc1 lb_00544
546
+ Cc1ccc(Cn2c(CO)nc3ccccc32)cc1 lb_00545
547
+ Cn1c(Nc2ccccc2C(F)(F)F)nc2ccccc21 lb_00546
548
+ CSc1nc2ccccc2n1Cc1ccc(C)cc1 lb_00547
549
+ Cc1ccccc1Cn1c(CO)nc2ccccc21 lb_00548
550
+ Fc1ccc(Cn2c(-c3ccc(F)cc3F)nc3ccccc32)c(F)c1 lb_00549
551
+ CC(C)(C)n1c(Cc2cccc(F)c2)nc2ccccc21 lb_00550
552
+ CCC1CCC(n2c(C(F)(F)F)nc3ccccc32)CC1 lb_00551
553
+ Cc1ccccc1Cc1nc2ccccc2n1Cc1ccccc1F lb_00552
554
+ Fc1ccc(-c2nc3ccccc3n2CCCc2ccccc2)cc1 lb_00553
555
+ Fc1ccccc1-c1nc2ccccc2n1CCCc1ccccc1 lb_00554
556
+ CCC(C)Cn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00555
557
+ CCC(C)Cn1c(-c2ccccc2F)nc2ccccc21 lb_00556
558
+ N#CCn1c(-c2ccc(F)c(F)c2)nc2ccccc21 lb_00557
559
+ Cc1ccc(C)c(Cn2c(CO)nc3ccccc32)c1 lb_00558
560
+ CSc1nc2ccccc2n1Cc1cccc(F)c1 lb_00559
561
+ CCCCCc1nc2ccc(C(F)(F)F)cc2n1CC lb_00560
562
+ Cn1c(NCc2ccc(F)c(C(F)(F)F)c2)nc2ccccc21 lb_00561
563
+ CCN(CC)CCCn1c(C(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00562
564
+ CCN(CC)CCn1c(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00563
565
+ CCn1c(/C(C#N)=C/c2ccccc2C(F)(F)F)nc2ccccc21 lb_00564
566
+ Cc1cccc(Cn2c([C@H](C)N)nc3cc(C(F)(F)F)ccc32)c1 lb_00565
567
+ N#Cc1cc(Cn2c(C(F)(F)F)nc3ccccc32)ccc1-c1ccccc1 lb_00566
568
+ CN(C)CCCn1c(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00567
569
+ FC(F)(F)c1cccc(CN2CCCn3c(nc4ccccc43)C2)c1 lb_00568
570
+ Cn1c(-c2cccc(N3CCN(CC(F)(F)F)CC3)c2)nc2ccccc21 lb_00569
571
+ N#Cc1ccc(Cn2c(C(F)(F)F)nc3ccccc32)cc1-c1ccccc1 lb_00570
572
+ Cc1cccc(-c2nc3ccccc3n2CCCN2CCC(F)(F)CC2)c1 lb_00571
573
+ CCn1c(C(C#N)=Cc2ccccc2C(F)(F)F)nc2ccccc21 lb_00572
574
+ Cn1c(C(C#N)=Cc2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00573
575
+ Cn1c(/C(C#N)=C/c2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00574
576
+ CC(c1ccccc1)N1CCC(Cn2c(C(F)(F)F)nc3ccccc32)CC1 lb_00575
577
+ CCN(CC)CCCn1c(-c2ccc(C)cc2)nc2cc(C(F)(F)F)ccc21 lb_00576
578
+ CNc1nc2ccccc2n2c(-c3cccc(C(F)(F)F)c3)cnc12 lb_00577
579
+ CCc1cccc(CC)c1N(COC)C(=O)Cn1c(C)nc2ccccc21 lb_00578
580
+ CCCCn1c(-c2cc(-c3ccc(F)cc3)nc(N)n2)nc2ccccc21 lb_00579
581
+ C[C@@H]1C[C@H](n2c(Cc3ccc(C(F)(F)F)cc3)nc3ccccc32)CC(C)(C)C1 lb_00580
582
+ CC1CC(n2c(Cc3ccc(C(F)(F)F)cc3)nc3ccccc32)CC(C)(C)C1 lb_00581
583
+ CCN(CC)CCCn1c(-c2ccc([C@@H](NC)C(F)(F)F)cc2)nc2ccccc21 lb_00582
584
+ CCN(CC)CCCn1c(-c2ccc(C(NC)C(F)(F)F)cc2)nc2ccccc21 lb_00583
585
+ C=Cc1ccc2c(c1)nc(C)n2Cc1ccccc1CC(C)(F)F.CCc1ccc(C)cc1 lb_00584
586
+ CCN(CC)CCCn1c(Cn2nnc3ccccc32)nc2cc(C(F)(F)F)ccc21 lb_00585
587
+ Cn1c(CN2CCC(CCCc3cc(F)cc(C(F)(F)F)c3)CC2)nc2ccccc21 lb_00586
588
+ Cc1ccc(Cn2c(Cc3ccccc3)nc3ccccc32)cc1 lb_00587
589
+ Cn1c(/C(C#N)=C/c2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00588
590
+ Cc1cccc(Cn2c([C@H](C)N)nc3ccccc32)c1 lb_00589
591
+ CCc1nc2ccccc2n1CCc1ccccc1 lb_00590
592
+ Cc1cccc(Cn2c(CC(C)C)nc3ccccc32)c1 lb_00591
593
+ CCn1c(CCc2ccccc2)nc2ccccc21 lb_00592
594
+ C=CCn1c(-c2ccccc2)nc2ccccc21 lb_00593
595
+ CC(C)c1nc2ccccc2n1Cc1ccccc1 lb_00594
596
+ CC(C)c1nc2ccccc2n1Cc1ccc(F)cc1 lb_00595
597
+ CC(C)c1nc2ccccc2n1Cc1ccccc1F lb_00596
598
+ C=CCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00597
599
+ CN(C)c1nc2ccccc2n1Cc1ccc(F)cc1 lb_00598
600
+ CC(C)n1c(-c2ccc(N(C)C)c(C(F)(F)F)c2)nc2ccccc21 lb_00599
601
+ Cc1nc2ccccc2n1CCCCC1CC(c2ccc(F)cc2)=CCN1 lb_00600
602
+ COCn1c(C(F)(F)F)nc2ccc(-c3ccccc3)cc21 lb_00601
603
+ COCn1c(C(F)(F)F)nc2cc(-c3ccccc3)ccc21 lb_00602
604
+ FC(F)c1nc2ccccc2n1Cc1ccccc1 lb_00603
605
+ Cc1nc2cc(C(C)(C)C)c(C(F)(F)F)cc2n1C lb_00604
606
+ CC(c1nc2ccccc2n1C)N1CCN(c2cccc(C(F)(F)F)c2)CC1 lb_00605
607
+ Cn1cnc2ccccc21.Fc1cc(CN2CCCCC2)cc(C(F)(F)F)c1 lb_00606
608
+ CN1CCN(Cc2cc(F)cc(C(F)(F)F)c2)CC1.Cn1cnc2ccccc21 lb_00607
609
+ Cn1c(C(C#N)=Cc2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00608
610
+ Fc1cccc(F)c1-c1nc2ccccc2n1Cc1c(F)c(F)c(F)c(F)c1F lb_00609
611
+ C=CCn1c(-c2ccccc2F)nc2ccccc21 lb_00610
612
+ FC(F)(F)c1nc2ccccc2n1CC1CCN(Cc2ccccc2)CC1 lb_00611
613
+ Fc1cc(F)cc(CN2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)c1 lb_00612
614
+ CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1CCCN(C)C lb_00613
615
+ Cc1ccc(-c2nc3cc(C(F)(F)F)ccc3n2CCCN(C)C)c(C)c1 lb_00614
616
+ CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1CCN(CC)CC lb_00615
617
+ CCN(CC)CCn1c(-c2ccc(C)cc2C)nc2cc(C(F)(F)F)ccc21 lb_00616
618
+ CCCCN(CCCC)CCCn1c(C(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00617
619
+ CCCCN(CCCC)CCCn1c(-c2ccc(C)cc2)nc2cc(C(F)(F)F)ccc21 lb_00618
620
+ CCC(C)n1c(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00619
621
+ CCC(C)n1c(-c2ccccc2C)nc2cc(C(F)(F)F)ccc21 lb_00620
622
+ CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1C lb_00621
623
+ Cc1ccccc1-c1nc2cc(C(F)(F)F)ccc2n1C(C)C lb_00622
624
+ CCC(C)c1nc2cc(C(F)(F)F)ccc2n1CC(C)C lb_00623
625
+ CC(C)Cn1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00624
626
+ Cc1ccc(-c2nc3cc(C(F)(F)F)ccc3n2CC(C)C)c(C)c1 lb_00625
627
+ FC(F)(F)c1ccc2c(c1)nc(C1CCCCC1)n2Cc1ccccc1 lb_00626
628
+ FC(F)(F)c1nc2ccccc2n1C(c1ccccc1)c1ccccc1 lb_00627
629
+ Cc1nc2ccccc2n1C(c1cccc(F)c1)C(C)N lb_00628
630
+ Cc1nc2ccc(-c3cc(N)nc(N)c3)nc2n1CC(F)(F)F lb_00629
631
+ Fc1ccc(Cn2c(Cl)nc3ccccc32)cc1 lb_00630
632
+ COCc1nc2ccccc2n1Cc1cccc(C)c1 lb_00631
633
+ O=C(C1CC1)N1CCN(Cc2nc3ccccc3n2Cc2cccc(C(F)(F)F)c2)CC1 lb_00632
634
+ Cc1cccc(Cn2c(C(C)O)nc3ccccc32)c1 lb_00633
635
+ CC(C)Cn1c(-c2ccccc2Cl)nc2ccccc21 lb_00634
636
+ FC(F)(F)c1cc(-c2ccccc2)n2c(n1)nc1ccccc12 lb_00635
637
+ CCn1c(-c2ccc(C#Cc3ccccc3)cc2)nc2ccccc21 lb_00636
638
+ CCCCn1c(-c2ccc(C#Cc3ccccc3)cc2)nc2ccccc21 lb_00637
639
+ CSc1nc2ccccc2n1Cc1ccccc1F lb_00638
640
+ C=CCn1c(C(C)C)nc2ccccc21 lb_00639
641
+ Cn1c(-c2cccc(-c3nc4ccccc4n3C)c2)nc2ccccc21 lb_00640
642
+ FC(F)(F)c1cccc(CCN2CCC(Nc3nc4ccccc4n3Cc3ccccc3)CC2)c1 lb_00641
643
+ COCCn1c(-c2ccc(C(C)C)cc2)nc2ccccc21 lb_00642
644
+ CCCCn1c(CCC)nc2ccccc21 lb_00643
645
+ Nc1nc2ccccc2n1Cc1cccc(F)c1 lb_00644
646
+ Cn1c(CCc2ccc(NC(=O)Nc3cccc(C(F)(F)F)c3)cc2)nc2ccccc21 lb_00645
647
+ CC(C)Cc1ccc(C(C)c2nc3ccccc3n2Cc2ccccc2C(F)(F)F)cc1 lb_00646
648
+ Cc1cccc(Cn2c([C@@H](N)C(C)C)nc3cc(C(F)(F)F)ccc32)c1 lb_00647
649
+ CC(C)c1ccc(N2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)cc1 lb_00648
650
+ CCc1nc2ccccc2n1C1N=CC=CN1c1ccc(C(F)(F)F)cc1 lb_00649
651
+ CC(C)(C)c1ccc(CN2CCC(n3c(C(F)(F)F)nc4ccccc43)CC2)cc1.Cl lb_00650
652
+ CCN(CC)CCCn1c(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00651
653
+ CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1CCCN(CC)CC lb_00652
654
+ CCCCCCCCn1c(-c2cc(-c3ccc(F)cc3)nc(N)n2)nc2ccccc21 lb_00653
655
+ CCCCCCn1c(-c2cc(-c3ccc(F)cc3)nc(N)n2)nc2ccccc21 lb_00654
656
+ CCCCCCCn1c(-c2cc(-c3ccc(F)cc3)nc(N)n2)nc2ccccc21 lb_00655
657
+ FC(F)(F)c1ccc2c(c1)nc(N1CCc3ccccc3C1)n2Cc1ccccc1 lb_00656
658
+ NC1=NC(c2cccc(C(F)(F)F)c2)n2c(nc3ccccc32)N1 lb_00657
659
+ CCCn1c(NCc2ccc(C(C)(C)C)cc2)nc2cc(C(F)(F)F)ccc21 lb_00658
660
+ CC(C)c1ccc(-c2nc3ccccc3n2Cc2cccc(F)c2)cc1 lb_00659
661
+ CCCCn1c(-c2cc(-c3ccc(C)cc3)nc(N)n2)nc2ccccc21 lb_00660
662
+ C[C@H](N)c1nc2ccccc2n1Cc1cccc(F)c1 lb_00661
663
+ Cc1ccccc1Cc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00662
664
+ CCc1nc2cc(C(F)(F)F)ccc2n1CCN(CC)CC lb_00663
665
+ CCn1c(C2CCCCC2)nc2cc(C(F)(F)F)ccc21 lb_00664
666
+ CC(C)n1c(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00665
667
+ CCn1c(C(C)(N)c2ccccc2)nc2cc(F)ccc21 lb_00666
668
+ CCn1c(C(C)(N)c2ccccc2)nc2ccc(F)cc21 lb_00667
669
+ CCc1nc2ccccc2n1Cc1ccc(N)cc1F lb_00668
670
+ Cc1ccc(C)c(Cn2c(C(C)O)nc3ccccc32)c1 lb_00669
671
+ CN(CCCn1c(N)nc2cc(C(F)(F)F)ccc21)CCCn1c(N)nc2cc(C(F)(F)F)ccc21 lb_00670
672
+ Cc1ccc(Cn2c(-c3cccc(N)c3)nc3ccccc32)cc1 lb_00671
673
+ Cc1cc(C)c(C)c(Cn2c(CCCO)nc3ccccc32)c1C lb_00672
674
+ Cc1ccccc1Cn1c(Cc2ccccc2)nc2ccccc21 lb_00673
675
+ CCCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00674
676
+ CCn1c(/C=C/c2ccc(F)cc2)nc2ccccc21 lb_00675
677
+ CCCc1nc2ccccc2n1Cc1ccccc1F lb_00676
678
+ Fc1ccc(Cc2nc3ccccc3n2Cc2ccc(F)c(F)c2)cc1F lb_00677
679
+ CC(C)(C)Cc1nc2cc(F)ccc2n1CC(F)(F)F lb_00678
680
+ FC(F)(F)c1ccc(-c2ccc(Cn3cnc4ccccc43)cc2)cc1 lb_00679
681
+ CC(C)(C)c1ccc2c(c1)nc(C(F)(F)F)n2-c1ccccc1 lb_00680
682
+ CC(C)c1ccc(Cn2c(-c3ccc(C(C)C)cc3)nc3ccccc32)cc1 lb_00681
683
+ CCn1c(C=Cc2ccc(F)cc2)nc2ccccc21 lb_00682
684
+ Fc1ccc(-c2nc3ccccc3n2Cc2ccccc2F)cc1 lb_00683
685
+ Fc1ccc(Cn2c(-c3ccccc3F)nc3ccccc32)cc1 lb_00684
686
+ Cc1cccc(-c2nc3cc(C(F)(F)F)ccc3n2C)c1 lb_00685
687
+ Cc1nc2ccccc2n1C(c1ccc(F)cc1)C(C)N lb_00686
688
+ Cc1nc2ccccc2n1C(c1ccccc1F)C(C)N lb_00687
689
+ CCCn1c(Nc2ccccc2C)nc2ccccc21 lb_00688
690
+ CN1CCN(c2nc3ccccc3n2CCc2ccccc2)CC1 lb_00689
691
+ COCc1nc2ccccc2n1Cc1ccccc1C lb_00690
692
+ Cc1ccccc1Cn1c(C(C)O)nc2ccccc21 lb_00691
693
+ Cn1cccc1-c1nc2ccccc2n1Cc1ccccc1 lb_00692
694
+ CN(C)c1ccc(Cn2c(-c3ccc(N(C)C)cc3)nc3ccccc32)cc1 lb_00693
695
+ CCn1c(CCc2ccccc2)nc2ccccc21.Cl lb_00694
696
+ CCn1c(/C=C/c2ccccc2)nc2ccccc21 lb_00695
697
+ CCCc1nc2ccccc2n1CCc1ccccc1 lb_00696
698
+ CCc1nc2ccccc2n1CCc1ccccc1.Cl lb_00697
699
+ CCCc1nc2ccccc2n1Cc1ccccc1 lb_00698
700
+ CC(C)c1nc2ccccc2n1CCc1ccccc1 lb_00699
701
+ Cn1c(-c2cccc(F)c2)nc2ccccc21 lb_00700
702
+ CCCn1c(Cc2ccccc2)nc2ccccc21 lb_00701
703
+ Nc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00702
704
+ CCc1nc2ccccc2n1CCC(C)C lb_00703
705
+ Nc1nc2ccccc2n1Cc1ccccc1F lb_00704
706
+ CCn1c(NCc2ccccc2)nc2ccccc21 lb_00705
707
+ CCC(C)Cn1c(C(C)C)nc2ccccc21 lb_00706
708
+ Nc1nc2ccccc2n1Cc1ccccc1 lb_00707
709
+ CC1(N2CCC(n3c(-c4cccc(C(F)(F)F)c4)nc4ccccc43)CC2)CCCCCCC1 lb_00708
710
+ CN1CCN(c2cc(-c3ccc(C(F)(F)F)cc3)c(C#N)c3nc4ccccc4n23)CC1 lb_00709
711
+ FC(F)(F)c1nc2ccccc2n1CC1CCN(c2ccc(C3CCCCC3)cc2)CC1 lb_00710
712
+ CCc1nc2ccccc2n1C1N=CC(F)=CN1c1ccc(C(F)(F)F)cc1 lb_00711
713
+ Cc1nc2cc(C(F)(F)F)ccc2n1C1CCN(Cc2ccc(C(C)(C)C)cc2)CC1.Cl lb_00712
714
+ Fc1cccc(CN2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)c1 lb_00713
715
+ Fc1ccc(F)c(CN2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)c1 lb_00714
716
+ Fc1ccc(CN2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)cc1F lb_00715
717
+ CCN(CC)CCCn1c(-c2ccc(C)cc2C)nc2cc(C(F)(F)F)ccc21 lb_00716
718
+ CCCCN(CCCC)CCCn1c(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00717
719
+ CCCCN(CCCC)CCCn1c(C(CC)c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00718
720
+ CC(c1nc2ccccc2n1C(F)F)N1CCN(c2cccc(C(F)(F)F)c2)CC1 lb_00719
721
+ Cn1c(CN2CCC(c3ccccc3C(F)(F)F)CC2)nc2ccccc21 lb_00720
722
+ CC(C)Cc1ccc(C(C)c2nc3ccccc3n2Cc2ccc(C(C)(C)C)cc2)cc1 lb_00721
723
+ Cc1nc2cc(F)ccc2n1CCCN1CCN(Cc2ccccc2)CC1 lb_00722
724
+ FC(F)(F)c1nc2ccccc2n1CC1CCCN1Cc1ccccc1 lb_00723
725
+ FC(F)(F)c1nc2ccccc2n1CC1CCN(Cc2ccccc2)C1 lb_00724
726
+ Cc1cccc(Cn2c([C@@H](N)C(C)C)nc3ccccc32)c1 lb_00725
727
+ Cc1ccc2c(c1)nc(-c1ccc(F)cc1)n2CCc1ccccc1 lb_00726
728
+ CC1(CC(F)(F)F)Cn2c(nc3ccccc32)-c2ccccc21 lb_00727
729
+ CC(C)c1ccc(Cn2c(-c3ccc(F)cc3)nc3ccccc32)cc1 lb_00728
730
+ CC(C)c1ccc(Cn2c(-c3ccccc3F)nc3ccccc32)cc1 lb_00729
731
+ CC(C)c1ccc(-c2nc3ccccc3n2Cc2ccc(F)cc2)cc1 lb_00730
732
+ Cc1cccc(Cn2c(CN3CCCC3)nc3ccccc32)c1 lb_00731
733
+ CC(Cl)c1nc2ccccc2n1CCc1cccc(F)c1 lb_00732
734
+ Cn1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00733
735
+ CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1C(C)C lb_00734
736
+ CCn1c(CNCc2cccc(F)c2)nc2ccccc21 lb_00735
737
+ CCc1nc2ccccc2n1Cc1ccc(F)cc1CN lb_00736
738
+ CCc1nc2ccccc2n1Cc1cc(F)ccc1CN lb_00737
739
+ CN(Cc1nc2cc(C(F)(F)F)ccc2n1C)c1ccccc1 lb_00738
740
+ CC(C)Cn1c(-c2ccc(N(C)C)cc2)nc2ccccc21 lb_00739
741
+ CC(C)Cc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00740
742
+ CC(C)Cc1nc2ccccc2n1Cc1ccccc1F lb_00741
743
+ FC(F)(F)c1cccc(-c2cccc(-n3cnc4ccccc43)c2)c1 lb_00742
744
+ CCCCn1c(C(=S)c2ccccc2)nc2ccccc21 lb_00743
745
+ Fc1cccc(F)c1-c1nc2ccccc2n1CC1C=CC=C1 lb_00744
746
+ CCN(CC)c1nc2ccccc2n1Cc1ccc(F)cc1 lb_00745
747
+ Cc1nc2ccccc2n1C(C)C(N)c1ccc(F)cc1 lb_00746
748
+ CCn1c(C(N)c2ccc(F)cc2)nc2ccccc21 lb_00747
749
+ CCn1c(C(N)c2ccccc2F)nc2ccccc21 lb_00748
750
+ CCSc1nc2ccccc2n1Cc1ccccc1F lb_00749
751
+ CC(O)c1nc2ccccc2n1Cc1ccc(F)cc1 lb_00750
752
+ CN(C)c1ccc(-c2nc3ccccc3n2Cc2ccccc2)cc1 lb_00751
753
+ C=C(C)Cn1c(-c2ccc(N)cc2)nc2ccccc21 lb_00752
754
+ COCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00753
755
+ CC(O)c1nc2ccccc2n1Cc1ccccc1F lb_00754
756
+ CC(C)Cn1c(Cc2ccccc2)nc2ccccc21 lb_00755
757
+ CC(C)Cc1nc2ccccc2n1Cc1ccccc1 lb_00756
758
+ CC(C)c1ccc(Cn2c(Cl)nc3ccccc32)cc1 lb_00757
759
+ Cc1cc2nc(C)n(Cc3ccc(F)cc3)c2cc1C lb_00758
760
+ Cn1c(-c2ccc(F)cc2F)nc2ccccc21 lb_00759
761
+ Fc1cccc(F)c1Cc1nc2ccccc2n1Cc1c(F)cccc1F lb_00760
762
+ FC(F)=C(F)c1nc2ccccc2n1Cc1ccccc1 lb_00761
763
+ CCCn1c(CCc2ccccc2)nc2ccccc21 lb_00762
764
+ CC(O)c1nc2ccccc2n1Cc1ccccc1 lb_00763
765
+ CC(=O)c1nc2ccccc2n1Cc1ccccc1 lb_00764
766
+ C=CCn1c(CCC)nc2ccccc21 lb_00765
767
+ COCc1nc2ccccc2n1Cc1ccccc1 lb_00766
768
+ FC(F)(F)c1cc(-c2cn3ccccc3n2)cc(C(F)(F)F)c1 lb_00767
769
+ CCCCCCCn1c(CCCCCC)nc2ccccc21 lb_00768
770
+ c1ccc(Cc2nc3ccccc3n2Cc2ccccc2)cc1 lb_00769
771
+ Cn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00770
772
+ Cn1c(-c2ccccc2F)nc2ccccc21 lb_00771
773
+ Cn1c(-c2c(F)cccc2F)nc2ccccc21 lb_00772
774
+ Cc1cccc(-c2nc3ccccc3n2C)c1 lb_00773
775
+ ClCc1nc2ccccc2n1Cc1ccccc1 lb_00774
776
+ Nc1nc2ccccc2n1CCc1ccccc1 lb_00775
777
+ Cn1c(-c2ccccc2)nc2ccccc21 lb_00776
778
+ Cc1nc2cc3ccccc3cc2n1C lb_00777
779
+ CC1(N2CCC(n3c(-c4cccc(C(F)(F)F)c4)nc4ccccc43)CC2)CCCCCCC1.Cl.Cl lb_00778
780
+ Cc1cccc(Cn2c([C@@H](N)CC(C)C)nc3cc(C(F)(F)F)ccc32)c1 lb_00779
781
+ CCC[C@H](N)c1nc2cc(C(F)(F)F)ccc2n1Cc1cccc(C)c1 lb_00780
782
+ Cn1cnc2ccccc21.Fc1cc(CN2CCC(F)(F)CC2)cc(C(F)(F)F)c1 lb_00781
783
+ CN(C)CCCn1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00782
784
+ CCN(CC)CCn1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00783
785
+ CCCCN(CCCC)CCCn1c(-c2ccc(C)cc2C)nc2cc(C(F)(F)F)ccc21 lb_00784
786
+ CCc1nc2ccc(C)cc2n1CCCCNc1cccc(C(F)(F)F)c1 lb_00785
787
+ FC(F)(F)c1cccc(-c2nc3ccccc3n2C(c2ccccc2)c2nc3ccccc3[nH]2)c1 lb_00786
788
+ CC(C)(C)c1nc2ccccc2n1Cc1cc(=O)[nH]c2c(F)c(F)ccc12 lb_00787
789
+ Cn1c(NC(=S)N2CCN(c3cccc(C(F)(F)F)c3)CC2)nc2ccccc21 lb_00788
790
+ FC(F)(F)c1nc2ccccc2n1Cc1ccc(-c2ccccc2)c(-c2nn[nH]n2)c1 lb_00789
791
+ Fc1ccc(CN2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)cc1 lb_00790
792
+ Fc1ccccc1CN1CCC(Cn2c(C(F)(F)F)nc3ccccc32)CC1 lb_00791
793
+ FC(F)(F)c1nc2ccccc2n1CC1CCCCN1Cc1ccccc1 lb_00792
794
+ CCN1CCC(N2CCC(n3c(C)nc4cc(C(F)(F)F)ccc43)CC2)CC1 lb_00793
795
+ C[C@H](N)c1nc2cc(C(F)(F)F)ccc2n1Cc1cccc(F)c1 lb_00794
796
+ CCCCCCCn1c(-c2cc(-c3ccc(C)cc3)nc(N)n2)nc2ccccc21 lb_00795
797
+ CCCCCCCCn1c(-c2cc(-c3ccc(C)cc3)nc(N)n2)nc2ccccc21 lb_00796
798
+ CCCCCCn1c(-c2cc(-c3ccc(C)cc3)nc(N)n2)nc2ccccc21 lb_00797
799
+ Cc1cccc(Cn2c(CN3CCCCC3)nc3ccccc32)c1 lb_00798
800
+ Cc1cccc(Cn2c(CN3CCCC3)nc3ccccc32)c1.Cl.Cl lb_00799
801
+ Cc1ccc(Cn2c(/C=C/c3ccc(F)cc3)nc3ccccc32)cc1 lb_00800
802
+ Cc1ccc(Cn2c(C=Cc3ccc(F)cc3)nc3ccccc32)cc1 lb_00801
803
+ CN(C)CCn1c(Cc2cccc(F)c2)nc2ccccc21 lb_00802
804
+ Cc1ccc(/C=C/c2nc3ccccc3n2Cc2ccccc2F)cc1 lb_00803
805
+ CCc1nc2cc(C(F)(F)F)ccc2n1CCCN(CC)CC lb_00804
806
+ CCN(CC)CCn1c(C(C)C)nc2cc(C(F)(F)F)ccc21 lb_00805
807
+ CCCc1nc2cc(C(F)(F)F)ccc2n1CCN(CC)CC lb_00806
808
+ CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1C(C)CC lb_00807
809
+ CCCn1c(C2CCCCC2)nc2cc(C(F)(F)F)ccc21 lb_00808
810
+ CCc1nc2ccccc2n1Cc1cc(CN)ccc1F lb_00809
811
+ CCc1nc2ccccc2n1Cc1ccc(CN)cc1F lb_00810
812
+ Cc1cccc(NCc2nc3ccccc3n2Cc2ccccc2)c1 lb_00811
813
+ FC(F)(F)c1cc(-c2nc3cccnc3n2C2CCCC2)cc(C(F)(F)F)c1 lb_00812
814
+ CCC(O)c1nc2ccccc2n1Cc1cc(C)ccc1C lb_00813
815
+ CC(C)[C@H](N)c1nc2ccccc2n1Cc1cccc(F)c1 lb_00814
816
+ Cc1ccc(C)c(Cn2c(CCCO)nc3ccccc32)c1 lb_00815
817
+ C=CCn1c(-c2ccc(N(C)C)cc2)nc2ccccc21 lb_00816
818
+ C=C(Cn1cnc2ccccc21)c1ccc(C(F)(F)F)cc1 lb_00817
819
+ CCCCc1nc2ccccc2n1Cc1ccccc1F lb_00818
820
+ CCc1ccc(Cn2c(C(F)(F)F)nc3cc(C)ccc32)cc1 lb_00819
821
+ Cc1n(Cc2ccccc2)c2cc(C(F)(F)F)ccc2[n+]1C lb_00820
822
+ CCCCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00821
823
+ CCCn1c(C=Cc2ccc(F)cc2)nc2ccccc21 lb_00822
824
+ CCCn1c(/C=C/c2ccc(F)cc2)nc2ccccc21 lb_00823
825
+ CC(Cl)c1nc2ccccc2n1CCc1ccc(F)cc1 lb_00824
826
+ CC(Cl)c1nc2ccccc2n1CCc1ccccc1F lb_00825
827
+ CCC(C)n1c(C(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00826
828
+ CCn1c(CNCc2ccccc2F)nc2ccccc21 lb_00827
829
+ CCn1c(CNCc2ccc(F)cc2)nc2ccccc21 lb_00828
830
+ Cc1ccccc1Cn1c(CN2CCCC2)nc2ccccc21 lb_00829
831
+ Cc1ccc(Cn2c(CCCO)nc3ccccc32)cc1 lb_00830
832
+ CCc1nc2ccccc2n1CCCCNc1ccccc1 lb_00831
833
+ CCCn1c(NCc2ccccc2C)nc2ccccc21 lb_00832
834
+ Cc1ccccc1Cn1c(CCCO)nc2ccccc21 lb_00833
835
+ Fc1ccc(Cn2c(-c3ccccn3)nc3ccccc32)cc1 lb_00834
836
+ CCCn1c(/C=C/c2ccccc2)nc2ccccc21 lb_00835
837
+ CC(C)Cc1nc2ccccc2n1CCc1ccccc1 lb_00836
838
+ CCCCc1nc2ccccc2n1Cc1ccccc1 lb_00837
839
+ CCCCn1c(Cc2ccccc2)nc2ccccc21 lb_00838
840
+ CC(C)(C)c1ccc(-n2c(C(F)(F)F)nc3ccc(C(C)(C)C)cc32)cc1 lb_00839
841
+ Cn1c(-c2ccc(C(F)(F)F)cc2)nc2cc(F)c(F)cc21 lb_00840
842
+ FCCn1c(C#Cc2ccccc2)nc2ccccc21 lb_00841
843
+ Cc1ccc(-c2nc3cc(C(F)(F)F)ccc3n2C)cc1 lb_00842
844
+ CC(C)n1c(C(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00843
845
+ CC(=O)c1nc2ccccc2n1CCc1ccccc1 lb_00844
846
+ OCc1nc2ccccc2n1Cc1ccccc1F lb_00845
847
+ C=CCn1c(C(CC)CC)nc2ccccc21 lb_00846
848
+ COCc1nc2ccccc2n1CCc1ccccc1 lb_00847
849
+ CCn1c(CN(C)c2ccccc2)nc2ccccc21 lb_00848
850
+ OCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00849
851
+ CC(C)(C)c1ccc2nc(-c3ccccc3)n(O)c2c1 lb_00850
852
+ NCc1cccc(Cn2c(N)nc3ccccc32)c1 lb_00851
853
+ CC(O)c1nc2ccccc2n1CCc1ccccc1 lb_00852
854
+ NCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00853
855
+ c1ccc(CCn2c(Cc3ccccc3)nc3ccccc32)cc1 lb_00854
856
+ NCc1nc2ccccc2n1Cc1ccccc1 lb_00855
857
+ Fc1cc(C(F)(F)F)ccc1CCCCN1CCn2c(nc3ccccc32)C1 lb_00856
858
+ CCC(C)[C@H](N)c1nc2cc(C(F)(F)F)ccc2n1Cc1cccc(C)c1 lb_00857
859
+ CCc1ccc2nc(C)n(C3=NC=CCN3c3ccc(C(F)(F)F)cc3)c2c1 lb_00858
860
+ CCc1ccc2nc(C)n(C3N=CC=CN3c3ccc(C(F)(F)F)cc3)c2c1 lb_00859
861
+ Fc1cccc(Cn2c(N3CCC(c4ccccc4C(F)(F)F)CC3)nc3ccccc32)c1 lb_00860
862
+ CC[C@H](C)[C@H](N)c1nc2cc(C(F)(F)F)ccc2n1Cc1cccc(C)c1 lb_00861
863
+ FC(F)(F)c1ccc2c(c1)nc(-c1ccccc1)n2C[C@@H]1CCCN2CCCC[C@H]12 lb_00862
864
+ CC(C)=CCCC(C)CCn1c(-c2ccccc2F)nc2ccccc21 lb_00863
865
+ C=C[C@@H]1CN(Cc2ccc(C(F)(F)F)cc2)Cc2nc3ccccc3n21 lb_00864
866
+ CCn1c(-c2ccccc2-c2ccc(C)cc2C)nc2cc(C(F)(F)CC)ccc21 lb_00865
867
+ FC(F)(F)c1nc2ccccc2n1CC1CCCN(Cc2ccccc2)C1 lb_00866
868
+ CC(C)Cc1ccc(C(C)(C)c2nc3ccccc3n2Cc2ccccc2Cl)cc1 lb_00867
869
+ Cc1cccc(C(C)(C)C)c1NC(=O)Cn1c(-c2ccccc2)nc2ccccc21 lb_00868
870
+ Cn1c(C(F)F)nc2ccccc21 lb_00869
871
+ Cc1ccc(NCc2nc3ccccc3n2Cc2ccc(F)cc2F)cc1 lb_00870
872
+ Cn1c(CN2CCN(c3ccccc3C(F)(F)F)CC2)nc2ccccc21 lb_00871
873
+ CCC[C@H](N)c1nc2ccccc2n1Cc1cccc(C)c1 lb_00872
874
+ Cc1cccc(Cn2c([C@@H](N)CC(C)C)nc3ccccc32)c1 lb_00873
875
+ CCCn1c(CNCc2cccc(F)c2)nc2ccccc21 lb_00874
876
+ CCc1nc2ccc(CCCc3cccc(C(F)(F)F)c3)cc2n1C lb_00875
877
+ CN1CCC(c2nc3ccccc3n2Cc2cccc(F)c2)CC1 lb_00876
878
+ Cc1ccc(Cn2c(CN3CCC(F)(F)CC3)nc3ccccc32)cc1 lb_00877
879
+ CC(c1nc2ccccc2n1Cc1ccccc1F)N1CCCCCC1 lb_00878
880
+ CC(c1nc2ccccc2n1Cc1ccc(F)cc1)N1CCCCCC1 lb_00879
881
+ CCCc1nc2cc(C(F)(F)F)ccc2n1CCCN(C)C lb_00880
882
+ CCC(C)n1c(-c2cccc(C)c2)nc2cc(C(F)(F)F)ccc21 lb_00881
883
+ CC(C)Cn1c(C2CCCCC2)nc2cc(C(F)(F)F)ccc21 lb_00882
884
+ CCc1nc2ccccc2n1Cc1cc(C#N)ccc1F lb_00883
885
+ Cc1ccc(Cn2c(N3CCC(N(C)C)CC3)nc3ccccc32)cc1 lb_00884
886
+ CC(C)(CC#N)Cc1nc2ccccc2n1Cc1ccc(Cl)cc1 lb_00885
887
+ Cc1ccc(Cn2c(-c3cccc(C#N)c3)nc3ccccc32)cc1 lb_00886
888
+ CC(C)Cn1c(/C=C/c2ccc(F)cc2)nc2ccccc21 lb_00887
889
+ C=C(C)Cn1c(-c2ccc(N(C)C)cc2)nc2ccccc21 lb_00888
890
+ CCCCCc1nc2ccccc2n1Cc1ccccc1F lb_00889
891
+ Cc1n(Cc2ccccc2)c2cc(C(F)(F)F)ccc2[n+]1C.[Br-] lb_00890
892
+ CCn1c(C(N)Cc2ccc(F)cc2)nc2ccccc21 lb_00891
893
+ CCCCCc1nc2ccccc2n1Cc1c(F)cccc1F lb_00892
894
+ Cc1cc(F)cc(C)c1CNCc1nc2ccccc2n1C lb_00893
895
+ FC(F)(F)CC1Cn2c(nc3ccccc32)-c2ccccc21 lb_00894
896
+ CCCCCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00895
897
+ CC(C)Cn1c(C=Cc2ccc(F)cc2)nc2ccccc21 lb_00896
898
+ Fc1ccc(-c2nc3ccccc3n2C/C=C/c2ccccc2)cc1 lb_00897
899
+ Fc1ccccc1-c1nc2ccccc2n1C/C=C/c1ccccc1 lb_00898
900
+ Fc1ccc(-c2nc3ccccc3n2Cc2cccc3ccccc23)cc1 lb_00899
901
+ Fc1ccccc1-c1nc2ccccc2n1Cc1cccc2ccccc12 lb_00900
902
+ Cc1cccc(-c2nc3cc(C(F)(F)F)ccc3n2C(C)C)c1 lb_00901
903
+ CC(c1nc2ccccc2n1Cc1ccccc1)N1CCCCC1 lb_00902
904
+ Cc1ccccc1Cn1c(CN2CCCC2)nc2ccccc21.Cl.Cl lb_00903
905
+ Cc1ccc(Cn2c(CN3CCCC3)nc3ccccc32)cc1.Cl.Cl lb_00904
906
+ CCCn1c(NCc2ccccc2F)nc2ccccc21 lb_00905
907
+ CCc1ccc(-c2nc3ccccc3n2Cc2ccccc2)nc1 lb_00906
908
+ Cc1ccccc1NCc1nc2ccccc2n1Cc1ccccc1 lb_00907
909
+ CC(C)Cn1c(/C=C/c2ccccc2)nc2ccccc21 lb_00908
910
+ Fc1ccc(Cn2c(Cc3ccccc3)nc3ccccc32)cc1 lb_00909
911
+ C=C(C)Cn1c(Cc2ccccc2)nc2ccccc21 lb_00910
912
+ CCCCCc1nc2ccccc2n1Cc1ccccc1 lb_00911
913
+ Cn1c(-c2ccc(C(F)(F)F)cc2F)nc2cc(C(F)(F)F)ccc21 lb_00912
914
+ Cn1c(Cc2ccc(F)cc2F)nc2ccccc21 lb_00913
915
+ CC(C)c1ccc(Cn2c(N)nc3ccccc32)cc1 lb_00914
916
+ Cc1cccc(CCc2nc3ccccc3n2C)c1 lb_00915
917
+ CC(c1ccc(C(C)(C)C)cc1)c1nc2ccccc2n1C lb_00916
918
+ C=CCn1c(-c2ccc(N)cc2)nc2ccccc21 lb_00917
919
+ CCc1ccccc1Nc1nc2ccccc2n1CC lb_00918
920
+ Fc1ccccc1Cn1c(C2CC2)nc2ccccc21 lb_00919
921
+ CCCn1c(-c2ccccc2F)nc2cc3nc(-c4ccccc4F)n(CCC)c3cc21 lb_00920
922
+ CC(C)c1nc2ccccc2n1Cc1ccccc1Cl lb_00921
923
+ FC(F)(F)c1ccc2c(c1)ncn2Cc1ccccc1 lb_00922
924
+ CCCCn1c(-c2cc(C(F)(F)F)cc(C(F)(F)F)c2)cnc1-c1cc(C(F)(F)F)cc(C(F)(F)F)c1 lb_00923
925
+ CCN(CC)CCCn1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00924
926
+ Cl.FC(F)(F)c1ccc2c(c1)nc(-c1ccccc1)n2CC1CCCN2CCCCC12 lb_00925
927
+ Cc1ccc(-c2nc3ccccc3n2C(F)F)cc1 lb_00926
928
+ Cn1c(-c2ccccc2-c2ccccc2F)nc2ccccc21 lb_00927
929
+ Cc1cccc2nc(CN3CCC(c4ccc(C(F)(F)F)cc4)CC3)n(C)c12 lb_00928
930
+ Cn1c(C(F)(F)F)nc2cc(C(C)(C)C)ccc21 lb_00929
931
+ CC(C)c1nc2ccccc2n1C1=NC=CCN1c1ccc(C(F)(F)F)cc1 lb_00930
932
+ CC(C)c1nc2ccccc2n1C1N=CC=CN1c1ccc(C(F)(F)F)cc1 lb_00931
933
+ Cc1nc2ccc(F)cc2n1C1N=CC(F)=CN1c1ccc(C(F)(F)F)cc1 lb_00932
934
+ Cc1nc2ccc(F)cc2n1C1N=CC=CN1c1ccc(C(F)(F)F)cc1 lb_00933
935
+ C=Cc1nc2ccccc2n1Cc1ccccc1 lb_00934
936
+ Cc1ccc(-c2nc3ccccc3n2C)c(C)c1 lb_00935
937
+ CCC(c1ccccc1)c1nc2ccccc2n1C lb_00936
938
+ FC(F)(F)c1nc2ccccc2n1CC1CCN(C/C=C/c2ccccc2)CC1 lb_00937
939
+ CCC(C)n1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00938
940
+ OCc1nc2ccccc2n1CCc1ccccc1 lb_00939
941
+ c1ccc(CNc2nc3ccccc3n2Cc2ccccc2)cc1 lb_00940
942
+ Cl.Cl.NCc1nc2ccccc2n1Cc1ccccc1 lb_00941
943
+ CC(C)[C@H](N)c1nc2cc(C(F)(F)F)ccc2n1Cc1cccc(F)c1 lb_00942
944
+ c1ccc(Cn2c(C3CC3)nc3ccccc32)cc1 lb_00943
945
+ FC(F)(F)c1nc2ccccc2n1Cc1ccc(-c2ccccc2-c2nn[nH]n2)cc1 lb_00944
946
+ CCC[C@H](N)c1nc2ccccc2n1Cc1cccc(F)c1 lb_00945
947
+ CCC(C)[C@H](N)c1nc2ccccc2n1Cc1cccc(C)c1 lb_00946
948
+ Cc1nc2cc(F)ccc2n1CCCN1CCC(c2ccc(F)cc2)CC1 lb_00947
949
+ Cc1ccc(Cn2c(CN3CC[C@@H](F)C3)nc3ccccc32)cc1 lb_00948
950
+ Cc1ccc(Cn2c(CN3CC[C@H](F)C3)nc3ccccc32)cc1 lb_00949
951
+ CCC(C)(c1ccccc1-c1nc2ccccc2n1-c1ccccc1)[C@@H](C)F lb_00950
952
+ CCC(C)c1ccc(Cn2c(-c3ccc(F)cc3)nc3ccccc32)cc1 lb_00951
953
+ CCC(C)c1ccc(Cn2c(-c3ccccc3F)nc3ccccc32)cc1 lb_00952
954
+ CCCc1nc2cc(C(F)(F)F)ccc2n1CCCN(CC)CC lb_00953
955
+ CCC(C)c1nc2cc(C(F)(F)F)ccc2n1CCN(CC)CC lb_00954
956
+ CC[C@@H](CN(C)Cc1ccccc1)n1c(C(F)(F)F)nc2ccccc21 lb_00955
957
+ CC[C@H](CN(C)Cc1ccccc1)n1c(C(F)(F)F)nc2ccccc21 lb_00956
958
+ CCC(CN(C)Cc1ccccc1)n1c(C(F)(F)F)nc2ccccc21 lb_00957
959
+ CN(C)C1CCN(c2nc3ccccc3n2Cc2ccc(F)cc2)CC1 lb_00958
960
+ CC(C)C[C@H](N)c1nc2ccccc2n1Cc1cccc(F)c1 lb_00959
961
+ Cc1ccccc1-c1nc2ccccc2n1C lb_00960
962
+ Cn1c(-c2ccc(-c3ccccc3)cc2)nc2ccccc21 lb_00961
963
+ Cc1ccc(-c2nc3ccccc3n2C)cc1 lb_00962
964
+ CCCCn1c(/C=C/c2ccc(F)cc2)nc2ccccc21 lb_00963
965
+ Cc1cccc(/C(=N\C(F)(F)F)n2cnc3ccccc32)c1 lb_00964
966
+ Cn1c(NCc2ccc(C(C)(C)C)cc2)nc2cc(C(F)(F)F)ccc21 lb_00965
967
+ CCn1c(C)[n+](Cc2ccccc2)c2ccc(C(F)(F)F)cc21 lb_00966
968
+ CCN(CC)Cn1c(C=Cc2ccc(C)cc2)nc2ccccc21 lb_00967
969
+ CCCCn1c(C=Cc2ccc(F)cc2)nc2ccccc21 lb_00968
970
+ CN(Cc1ccccc1)c1nc2ccccc2n1Cc1ccc(F)cc1 lb_00969
971
+ N#CCc1nc2ccccc2n1Cc1cccc(F)c1F lb_00970
972
+ Cc1ccc(Cn2c(CC3CCCC3)nc3ccccc32)cc1 lb_00971
973
+ Cn1cc(-c2nc3ccccc3n2Cc2ccccc2)ccc1=O lb_00972
974
+ FC(F)(F)c1cccc(Cn2c(C(F)(F)F)nc3cc(Cl)c(Cl)cc32)c1 lb_00973
975
+ Cc1ccc(Cn2c(-c3ccc(C#N)cc3)nc3ccccc32)cc1 lb_00974
976
+ Fc1ccc(-c2nc3ccccc3n2CN2CCOCC2)cc1 lb_00975
977
+ CCCn1c(-c2ccc(F)c(C(F)(F)F)c2)nc2cc3nc(-c4ccc(F)c(C(F)(F)F)c4)n(CCC)c3cc21 lb_00976
978
+ CN1CCN(c2nc3ccccc3n2Cc2ccc(F)cc2)CC1 lb_00977
979
+ CCCCN(CCCC)CCCn1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00978
980
+ CC(C)c1nc2ccccc2n1Cc1cccc2ccccc12 lb_00979
981
+ Fc1ccccc1Cn1c(Cc2ccccc2)nc2ccccc21 lb_00980
982
+ Cn1c(-c2ccccc2-c2cccc(F)c2)nc2ccccc21 lb_00981
983
+ CCCCCCCCCCCCCCCCCc1nc2ccccc2n1Cc1ccccc1 lb_00982
984
+ CCCCCCCn1c(Cc2ccccc2)nc2ccccc21 lb_00983
985
+ CCCCn1c(/C=C/c2ccccc2)nc2ccccc21 lb_00984
986
+ Fc1ccc(Cn2c(CCc3ccccc3)nc3ccccc32)cc1 lb_00985
987
+ NCCn1c(Cc2ccc(F)cc2)nc2ccccc21 lb_00986
988
+ CCC(O)c1nc2ccccc2n1CCc1ccccc1 lb_00987
989
+ CN1CCN(c2nc3ccccc3n2Cc2ccccc2)CC1 lb_00988
990
+ Cn1c(-c2ccc(N)cc2)nc2cc(C(F)(F)F)ccc21 lb_00989
991
+ CCn1c(/C=C/c2ccc(Cl)cc2)nc2ccccc21 lb_00990
992
+ FC(F)(F)c1cccc(C2CCN(CCCCn3cnc4ccccc43)CC2)c1 lb_00991
993
+ Cn1c(-c2ccccc2-c2ccc(F)cc2)nc2ccccc21 lb_00992
994
+ CC(C)n1c(-c2ccc(F)cc2)nc2ccccc21 lb_00993
995
+ Cn1c(-c2ccccc2)nc2c(C(F)(F)F)cccc21 lb_00994
996
+ Cc1ccccc1CCc1nc2ccccc2n1C lb_00995
997
+ CC(C)n1c(-c2ccccc2F)nc2ccccc21 lb_00996
998
+ CCn1c(-c2ccccc2)nc2cc(C)ccc21 lb_00997
999
+ OCCn1c(Cc2ccccc2)nc2ccccc21 lb_00998
1000
+ Cn1c(-c2cccc(N)c2)nc2ccccc21 lb_00999
docking_pipeline/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Strict rDock-first docking pipeline."""
2
+
3
+ __all__ = ["__version__"]
4
+
5
+ __version__ = "0.1.0"
docking_pipeline/__main__.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+
8
+ def _engine_from_args(args: argparse.Namespace, validation: bool = False) -> RDockEngine:
9
+ from .rdock import RDockEngine, RDockRunConfig
10
+
11
+ return RDockEngine(
12
+ RDockRunConfig(
13
+ n_runs=int(getattr(args, "n_runs", 100 if validation else 50)),
14
+ jobs=getattr(args, "jobs", "auto"),
15
+ cpu_fraction=float(getattr(args, "cpu_fraction", 0.85)),
16
+ dock_prm=getattr(args, "dock_prm", None),
17
+ rbt_root=getattr(args, "rbt_root", None),
18
+ require_reporting_tools=validation,
19
+ )
20
+ )
21
+
22
+
23
+ def main() -> int:
24
+ parser = argparse.ArgumentParser(prog="python -m docking_pipeline", description="Strict rDock-first docking pipeline")
25
+ sub = parser.add_subparsers(dest="cmd", required=True)
26
+
27
+ p = sub.add_parser("prepare-target")
28
+ p.add_argument("--receptor", required=True)
29
+ p.add_argument("--ref-ligand", required=True)
30
+ p.add_argument("--out", required=True)
31
+ p.add_argument("--rbt-root")
32
+ p.add_argument("--dock-prm")
33
+
34
+ p = sub.add_parser("dock-rdock")
35
+ p.add_argument("--target-config", required=True)
36
+ p.add_argument("--ligands", required=True)
37
+ p.add_argument("--out", required=True)
38
+ p.add_argument("--n-runs", type=int, default=50)
39
+ p.add_argument("--jobs", default="auto")
40
+ p.add_argument("--cpu-fraction", type=float, default=0.85)
41
+ p.add_argument("--dock-prm")
42
+ p.add_argument("--rbt-root")
43
+ p.add_argument("--dry-run", action="store_true")
44
+ p.add_argument("--plan-only", action="store_true")
45
+
46
+ p = sub.add_parser("validate-rdock")
47
+ p.add_argument("--set", choices=["astex", "dud", "rna"], required=True)
48
+ p.add_argument("--system")
49
+ p.add_argument("--system-list")
50
+ p.add_argument("--max-systems", type=int)
51
+ p.add_argument("--list-systems", action="store_true")
52
+ p.add_argument("--data-dir", required=True)
53
+ p.add_argument("--out", default="results/rdock_validation")
54
+ p.add_argument("--n-runs", type=int, default=100)
55
+ p.add_argument("--jobs", default="auto")
56
+ p.add_argument("--cpu-fraction", type=float, default=0.85)
57
+ p.add_argument("--download-url")
58
+ p.add_argument("--download-if-missing", action="store_true")
59
+ p.add_argument("--keep-work", action="store_true")
60
+ p.add_argument("--force", action="store_true")
61
+ p.add_argument("--dry-run", action="store_true")
62
+ p.add_argument("--plan-only", action="store_true")
63
+
64
+ p = sub.add_parser("run-adaptive")
65
+ p.add_argument("--target-config", required=True)
66
+ p.add_argument("--ligands", required=True, help="CSV with ligand_id,smiles and optional model_score")
67
+ p.add_argument("--out", required=True)
68
+ p.add_argument("--budget", type=int, required=True)
69
+ p.add_argument("--batch-size", type=int, default=16)
70
+ p.add_argument("--n-runs", type=int, default=50)
71
+ p.add_argument("--jobs", default="auto")
72
+ p.add_argument("--cpu-fraction", type=float, default=0.85)
73
+ p.add_argument("--dock-prm")
74
+ p.add_argument("--rbt-root")
75
+ p.add_argument("--dry-run", action="store_true")
76
+ p.add_argument("--plan-only", action="store_true")
77
+
78
+ p = sub.add_parser("benchmark-adaptive")
79
+ p.add_argument("--dataset-dir", required=True)
80
+ p.add_argument("--strategy", default="multifidelity_adaptive_rdock")
81
+ p.add_argument("--fidelity-levels", default="5,10,15,30,50")
82
+ p.add_argument("--cost-budget-runs", type=int, required=True)
83
+ p.add_argument("--adaptive-budget-ligands", type=int)
84
+ p.add_argument("--promotion-fraction", type=float, default=0.5)
85
+ p.add_argument("--min-per-cluster", type=int, default=1)
86
+ p.add_argument("--max-per-cluster", type=int, default=50)
87
+ p.add_argument("--outlier-intra-z-threshold", type=float, default=3.0)
88
+ p.add_argument("--score-component-filter", default="warn")
89
+ p.add_argument("--final-fidelity-only-hits", default="true")
90
+ p.add_argument("--resume", action="store_true")
91
+ p.add_argument("--checkpoint-every", type=int, default=1)
92
+ p.add_argument("--jobs", default="auto")
93
+ p.add_argument("--cpu-fraction", type=float, default=0.85)
94
+ p.add_argument("--out", required=True)
95
+ p.add_argument("--dry-run", action="store_true")
96
+ p.add_argument("--plan-only", action="store_true")
97
+
98
+ p = sub.add_parser("validate-dataset")
99
+ p.add_argument("--dataset-dir", required=True)
100
+ p.add_argument("--check-rdock-tools", action="store_true")
101
+
102
+ args = parser.parse_args()
103
+ if args.cmd == "prepare-target":
104
+ engine = _engine_from_args(args)
105
+ target = engine.prepare_target(args.receptor, args.ref_ligand, args.out)
106
+ print(json.dumps({"target_config": str(Path(args.out) / "target_config.yaml"), "target": target.__dict__}, indent=2))
107
+ elif args.cmd == "dock-rdock":
108
+ from .rdock import load_target_config
109
+
110
+ engine = _engine_from_args(args)
111
+ if args.dry_run or args.plan_only:
112
+ plan = {
113
+ "target_config": args.target_config,
114
+ "ligands": args.ligands,
115
+ "out": args.out,
116
+ "n_runs": args.n_runs,
117
+ "jobs": args.jobs,
118
+ "cpu_fraction": args.cpu_fraction,
119
+ "commands": ["rbcavity was already run during prepare-target", "rbdock chunks will be launched by --jobs"],
120
+ }
121
+ Path(args.out).mkdir(parents=True, exist_ok=True)
122
+ (Path(args.out) / "dock_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8")
123
+ print(json.dumps(plan, indent=2))
124
+ return 0
125
+ artifacts = engine.dock_sdf(load_target_config(args.target_config), args.ligands, args.out, n_runs=args.n_runs, jobs=args.jobs)
126
+ print(json.dumps(artifacts.__dict__, indent=2))
127
+ elif args.cmd == "validate-rdock":
128
+ from .validation import discover_validation_systems, ensure_validation_data, validate_many
129
+
130
+ if args.set == "rna":
131
+ raise SystemExit("RNA rDock validation is not implemented yet; supported sets are astex and dud.")
132
+ data_root = ensure_validation_data(args.data_dir, args.set, args.download_url, args.download_if_missing, force=args.force)
133
+ if args.list_systems:
134
+ systems = discover_validation_systems(data_root, args.set)
135
+ print(json.dumps([s.__dict__ for s in systems], indent=2))
136
+ return 0
137
+ result = validate_many(
138
+ args.set,
139
+ data_root,
140
+ args.out,
141
+ system=args.system,
142
+ system_list=args.system_list,
143
+ max_systems=args.max_systems,
144
+ n_runs=args.n_runs,
145
+ jobs=args.jobs,
146
+ cpu_fraction=args.cpu_fraction,
147
+ download_url=args.download_url,
148
+ download_if_missing=args.download_if_missing,
149
+ force=args.force,
150
+ dry_run=args.dry_run,
151
+ plan_only=args.plan_only,
152
+ )
153
+ print(json.dumps(result, indent=2))
154
+ metrics = result.get("metrics", {}) if isinstance(result, dict) else {}
155
+ if metrics.get("failures"):
156
+ return 1
157
+ elif args.cmd == "run-adaptive":
158
+ from .adaptive import run_adaptive
159
+ from .rdock import load_target_config
160
+
161
+ engine = _engine_from_args(args)
162
+ if args.dry_run or args.plan_only:
163
+ plan = {
164
+ "target_config": args.target_config,
165
+ "ligands": args.ligands,
166
+ "out": args.out,
167
+ "budget": args.budget,
168
+ "batch_size": args.batch_size,
169
+ "n_runs": args.n_runs,
170
+ "jobs": args.jobs,
171
+ }
172
+ Path(args.out).mkdir(parents=True, exist_ok=True)
173
+ (Path(args.out) / "adaptive_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8")
174
+ print(json.dumps(plan, indent=2))
175
+ return 0
176
+ run_dir = run_adaptive(load_target_config(args.target_config), args.ligands, args.out, args.budget, args.batch_size, engine, n_runs=args.n_runs)
177
+ print(json.dumps({"run_dir": str(run_dir)}, indent=2))
178
+ elif args.cmd == "benchmark-adaptive":
179
+ from .benchmark_adaptive import run_from_args
180
+
181
+ print(json.dumps(run_from_args(args), indent=2))
182
+ elif args.cmd == "validate-dataset":
183
+ from .dataset import validate_dataset_dir
184
+
185
+ print(json.dumps(validate_dataset_dir(args.dataset_dir, check_rdock_tools=args.check_rdock_tools), indent=2))
186
+ return 0
187
+
188
+
189
+ if __name__ == "__main__":
190
+ try:
191
+ raise SystemExit(main())
192
+ except Exception as exc:
193
+ from .provenance import RDockPipelineError
194
+
195
+ if isinstance(exc, RDockPipelineError):
196
+ raise SystemExit(str(exc))
197
+ raise
docking_pipeline/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (296 Bytes). View file
 
docking_pipeline/__pycache__/config_io.cpython-313.pyc ADDED
Binary file (1.89 kB). View file
 
docking_pipeline/__pycache__/dataset.cpython-313.pyc ADDED
Binary file (21.3 kB). View file
 
docking_pipeline/__pycache__/provenance.cpython-313.pyc ADDED
Binary file (9.28 kB). View file
 
docking_pipeline/__pycache__/rdock.cpython-313.pyc ADDED
Binary file (31.6 kB). View file
 
docking_pipeline/__pycache__/sdf.cpython-313.pyc ADDED
Binary file (9.18 kB). View file
 
docking_pipeline/adaptive.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import shutil
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from .provenance import RDockPipelineError, require_file
9
+ from .rdock import RDockEngine, TargetConfig
10
+ from .sdf import best_per_ligand, parse_rdock_sdf_records, records_to_rows, split_sdf_file, write_rows_csv, write_sdf_blocks, write_sdf_records
11
+
12
+
13
+ @dataclass
14
+ class ScheduledBatch:
15
+ batch_index: int
16
+ ligand_ids: list[str]
17
+
18
+
19
+ class RealDockingScheduler:
20
+ """Simple explicit scheduler: model ranks candidates, rDock produces ground truth."""
21
+
22
+ def __init__(self, ligands: object, budget: int, batch_size: int) -> None:
23
+ if hasattr(ligands, "to_dict"):
24
+ rows = ligands.to_dict(orient="records") # type: ignore[call-arg]
25
+ else:
26
+ rows = list(ligands) # type: ignore[arg-type]
27
+ if not rows or "ligand_id" not in rows[0] or "smiles" not in rows[0]:
28
+ raise RDockPipelineError("Adaptive ligand CSV must contain ligand_id and smiles columns")
29
+ self.rows: list[dict[str, object]] = [dict(r) for r in rows]
30
+ self.budget = int(budget)
31
+ self.batch_size = int(batch_size)
32
+ self.completed: set[str] = set()
33
+ for row in self.rows:
34
+ model_score = _float_or_zero(row.get("model_score", 0.0))
35
+ row["model_score"] = model_score
36
+ row["adaptive_priority"] = -model_score
37
+ row["actually_docked"] = False
38
+
39
+ def next_batch(self) -> ScheduledBatch | None:
40
+ remaining_budget = self.budget - len(self.completed)
41
+ if remaining_budget <= 0:
42
+ return None
43
+ active = [row for row in self.rows if str(row["ligand_id"]) not in self.completed]
44
+ if not active:
45
+ return None
46
+ active = sorted(active, key=lambda r: (-float(r["adaptive_priority"]), str(r["ligand_id"])))
47
+ ids = [str(row["ligand_id"]) for row in active[: min(self.batch_size, remaining_budget)]]
48
+ return ScheduledBatch(batch_index=len(self.completed) // max(1, self.batch_size), ligand_ids=ids)
49
+
50
+ def update(self, docked_scores: object) -> None:
51
+ if hasattr(docked_scores, "to_dict"):
52
+ score_rows = docked_scores.to_dict(orient="records") # type: ignore[call-arg]
53
+ else:
54
+ score_rows = list(docked_scores) # type: ignore[arg-type]
55
+ for ligand_id in [str(row["ligand_id"]) for row in score_rows]:
56
+ self.completed.add(ligand_id)
57
+ for row in self.rows:
58
+ if str(row["ligand_id"]) == ligand_id:
59
+ row["actually_docked"] = True
60
+ if not score_rows:
61
+ return
62
+ scores = sorted(_float_or_zero(row.get("SCORE", 0.0)) for row in score_rows)
63
+ median_score = scores[len(scores) // 2]
64
+ for row in self.rows:
65
+ if str(row["ligand_id"]) not in self.completed:
66
+ row["adaptive_priority"] = float(row["adaptive_priority"]) + (0.001 * -median_score)
67
+
68
+ def to_dataframe(self):
69
+ import pandas as pd
70
+
71
+ return pd.DataFrame(self.rows)
72
+
73
+
74
+ def _float_or_zero(value: object) -> float:
75
+ try:
76
+ return float(value)
77
+ except Exception:
78
+ return 0.0
79
+
80
+
81
+ def _prepare_batch_sdf(ligands: pd.DataFrame, ligand_ids: list[str], out_sdf: Path) -> Path:
82
+ from libs.docking.prep import prepare_ligand_sdf
83
+
84
+ tmp = out_sdf.parent / "prepared"
85
+ tmp.mkdir(parents=True, exist_ok=True)
86
+ blocks: list[str] = []
87
+ by_id = ligands.set_index("ligand_id")
88
+ for ligand_id in ligand_ids:
89
+ smiles = str(by_id.loc[ligand_id, "smiles"])
90
+ sdf = prepare_ligand_sdf(ligand_id, smiles, tmp / f"{ligand_id}.sdf")
91
+ blocks.extend(split_sdf_file(sdf))
92
+ write_sdf_blocks(blocks, out_sdf)
93
+ return out_sdf
94
+
95
+
96
+ def run_adaptive(
97
+ target_config: TargetConfig,
98
+ ligands_csv: str | Path,
99
+ out_dir: str | Path,
100
+ budget: int,
101
+ batch_size: int,
102
+ engine: RDockEngine,
103
+ n_runs: int | None = None,
104
+ ) -> Path:
105
+ import pandas as pd
106
+
107
+ ligands = pd.read_csv(require_file(ligands_csv, "adaptive ligand CSV"))
108
+ scheduler = RealDockingScheduler(ligands, budget=budget, batch_size=batch_size)
109
+ root = Path(out_dir)
110
+ for name in ("target", "ligands", "rdock", "poses", "tables", "metrics"):
111
+ (root / name).mkdir(parents=True, exist_ok=True)
112
+ shutil.copy2(target_config.receptor, root / "target" / Path(target_config.receptor).name)
113
+ shutil.copy2(target_config.reference_ligand, root / "target" / Path(target_config.reference_ligand).name)
114
+
115
+ batch_records = []
116
+ all_blocks: list[str] = []
117
+ while True:
118
+ batch = scheduler.next_batch()
119
+ if batch is None:
120
+ break
121
+ batch_dir = root / "rdock" / f"batch_{batch.batch_index:03d}"
122
+ batch_sdf = _prepare_batch_sdf(ligands, batch.ligand_ids, root / "ligands" / f"batch_{batch.batch_index:03d}.sdf")
123
+ artifacts = engine.dock_sdf(target_config, batch_sdf, batch_dir, n_runs=n_runs, jobs=engine.config.jobs, run_id=f"{root.name}_batch_{batch.batch_index:03d}")
124
+ best_df = pd.read_csv(artifacts.best_per_ligand_csv)
125
+ scheduler.update(best_df)
126
+ all_blocks.extend(split_sdf_file(artifacts.all_poses_sdf))
127
+ for ligand_id in batch.ligand_ids:
128
+ batch_records.append({"batch": batch.batch_index, "ligand_id": ligand_id})
129
+
130
+ all_poses = root / "poses" / "all_poses.sdf"
131
+ write_sdf_blocks(all_blocks, all_poses)
132
+ if all_blocks:
133
+ records = parse_rdock_sdf_records(all_poses)
134
+ best = best_per_ligand(records)
135
+ write_sdf_records(best, root / "poses" / "best_per_ligand.sdf")
136
+ score_rows = records_to_rows(records)
137
+ best_rows = records_to_rows(best)
138
+ else:
139
+ score_rows = []
140
+ best_rows = []
141
+ (root / "poses" / "best_per_ligand.sdf").write_text("", encoding="utf-8")
142
+ scheduler_df = scheduler.to_dataframe()
143
+ model_cols = scheduler_df[["ligand_id", "model_score", "adaptive_priority", "actually_docked"]]
144
+ if best_rows:
145
+ model_map = model_cols.set_index("ligand_id").to_dict(orient="index")
146
+ for row in best_rows:
147
+ row.update(model_map.get(str(row["ligand_id"]), {}))
148
+ write_rows_csv(score_rows, root / "tables" / "scores_long.csv")
149
+ write_rows_csv(best_rows, root / "tables" / "best_per_ligand.csv")
150
+ scheduler_df.to_csv(root / "tables" / "scheduler_all_ligands.csv", index=False)
151
+ pd.DataFrame(batch_records).to_csv(root / "tables" / "adaptive_batches.csv", index=False)
152
+ (root / "metrics" / "validation_metrics.json").write_text("{}", encoding="utf-8")
153
+ pd.DataFrame().to_csv(root / "metrics" / "enrichment.csv", index=False)
154
+ manifest = {
155
+ "engine": "real-rdock-adaptive",
156
+ "budget": int(budget),
157
+ "batch_size": int(batch_size),
158
+ "docked_ligand_count": int(scheduler_df["actually_docked"].sum()),
159
+ "undocked_ligands_are_hits": False,
160
+ "artifacts": {
161
+ "all_poses_sdf": str(all_poses),
162
+ "best_per_ligand_csv": str(root / "tables" / "best_per_ligand.csv"),
163
+ "scheduler_all_ligands_csv": str(root / "tables" / "scheduler_all_ligands.csv"),
164
+ },
165
+ }
166
+ (root / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
167
+ (root / "config.yaml").write_text(f"budget: {budget}\nbatch_size: {batch_size}\n", encoding="utf-8")
168
+ (root / "commands.log").write_text("", encoding="utf-8")
169
+ for batch_log in sorted((root / "rdock").glob("batch_*/commands.log")):
170
+ with (root / "commands.log").open("a", encoding="utf-8") as dst:
171
+ dst.write(batch_log.read_text(encoding="utf-8"))
172
+ (root / "report.md").write_text(
173
+ "# Adaptive rDock Run\n\n"
174
+ "Model scores only schedule ligands. `best_per_ligand.csv` is built exclusively from real rDock SDF records with SCORE fields.\n",
175
+ encoding="utf-8",
176
+ )
177
+ return root
docking_pipeline/benchmark_adaptive.py ADDED
@@ -0,0 +1,900 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import csv
5
+ import json
6
+ import math
7
+ import random
8
+ import shutil
9
+ import time
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from .dataset import read_ligand_metadata, validate_dataset_dir
15
+ from .provenance import RDockPipelineError, probe_version, require_executable, require_file
16
+ from .rdock import RDockEngine, RDockRunConfig, TargetConfig, load_target_config
17
+ from .reports.plots import plot_multifidelity_outputs, plot_score_outputs
18
+ from .sdf import ligand_id_from_block, parse_tags, split_sdf_file, write_rows_csv, write_sdf_blocks
19
+
20
+
21
+ def _read_rows(path: str | Path) -> list[dict[str, str]]:
22
+ with Path(path).open("r", encoding="utf-8", newline="") as handle:
23
+ return list(csv.DictReader(handle))
24
+
25
+
26
+ def _write_json(path: str | Path, payload: dict[str, Any]) -> Path:
27
+ target = Path(path)
28
+ target.parent.mkdir(parents=True, exist_ok=True)
29
+ target.write_text(json.dumps(payload, indent=2), encoding="utf-8")
30
+ return target
31
+
32
+
33
+ def _float(value: object, default: float = 0.0) -> float:
34
+ try:
35
+ text = str(value).strip()
36
+ if not text:
37
+ return default
38
+ return float(text)
39
+ except Exception:
40
+ return default
41
+
42
+
43
+ def _bool_text(value: bool) -> str:
44
+ return "true" if value else "false"
45
+
46
+
47
+ def _parse_levels(text: str) -> list[int]:
48
+ try:
49
+ levels = [int(part.strip()) for part in text.split(",") if part.strip()]
50
+ except Exception as exc:
51
+ raise RDockPipelineError(f"Invalid --fidelity-levels value {text!r}: {exc}") from exc
52
+ if not levels or sorted(levels) != levels or min(levels) <= 0:
53
+ raise RDockPipelineError(f"Invalid fidelity levels: {levels}")
54
+ return levels
55
+
56
+
57
+ def _write_yaml_like(path: Path, payload: dict[str, Any]) -> None:
58
+ try:
59
+ import yaml
60
+
61
+ text = yaml.safe_dump(payload, sort_keys=False)
62
+ except Exception:
63
+ text = json.dumps(payload, indent=2)
64
+ path.write_text(text, encoding="utf-8")
65
+
66
+
67
+ def _count_sdf(path: Path) -> int:
68
+ return len(split_sdf_file(path))
69
+
70
+
71
+ def _load_input_block_map(sdf_path: Path) -> dict[str, str]:
72
+ block_map: dict[str, str] = {}
73
+ for idx, block in enumerate(split_sdf_file(sdf_path)):
74
+ tags = parse_tags(block)
75
+ ligand_id = ligand_id_from_block(block, tags, idx)
76
+ block_map[ligand_id] = block
77
+ return block_map
78
+
79
+
80
+ def _write_selected_sdf(block_map: dict[str, str], ligand_ids: list[str], out_path: Path) -> Path:
81
+ missing = [ligand_id for ligand_id in ligand_ids if ligand_id not in block_map]
82
+ if missing:
83
+ raise RDockPipelineError(f"Missing {len(missing)} ligand IDs in prepared SDF: {missing[:10]}")
84
+ write_sdf_blocks([block_map[ligand_id] for ligand_id in ligand_ids], out_path)
85
+ return out_path
86
+
87
+
88
+ def _mean(values: list[float]) -> float:
89
+ return sum(values) / len(values) if values else 0.0
90
+
91
+
92
+ def _stdev(values: list[float], center: float) -> float:
93
+ if not values:
94
+ return 1.0
95
+ var = sum((value - center) ** 2 for value in values) / max(1, len(values))
96
+ return math.sqrt(var) or 1.0
97
+
98
+
99
+ def _augment_full_rows(rows: list[dict[str, str]]) -> list[dict[str, Any]]:
100
+ ordered = sorted(rows, key=lambda row: (_float(row.get("SCORE"), float("inf")), str(row.get("ligand_id", ""))))
101
+ total = max(1, len(ordered))
102
+ enriched: list[dict[str, Any]] = []
103
+ for idx, row in enumerate(ordered, start=1):
104
+ item: dict[str, Any] = dict(row)
105
+ item["full_rank"] = idx
106
+ item["full_percentile"] = 100.0 if total == 1 else 100.0 * (1.0 - ((idx - 1) / (total - 1)))
107
+ enriched.append(item)
108
+ return enriched
109
+
110
+
111
+ def _percentile_from_rank(rank: int, total: int) -> float:
112
+ if total <= 1:
113
+ return 100.0
114
+ return 100.0 * (1.0 - ((rank - 1) / (total - 1)))
115
+
116
+
117
+ def _append_rank_metrics(rows: list[dict[str, Any]], full_rank_map: dict[str, int], total: int) -> list[dict[str, Any]]:
118
+ enriched: list[dict[str, Any]] = []
119
+ for row in rows:
120
+ item = dict(row)
121
+ ligand_id = str(item["ligand_id"])
122
+ rank = full_rank_map.get(ligand_id)
123
+ item["full_rank"] = rank if rank is not None else ""
124
+ item["full_percentile"] = _percentile_from_rank(rank, total) if rank is not None else ""
125
+ enriched.append(item)
126
+ return enriched
127
+
128
+
129
+ def _top_overlap(full_rows: list[dict[str, Any]], sample_rows: list[dict[str, Any]], n: int) -> int:
130
+ full_top = {str(row["ligand_id"]) for row in full_rows[:n]}
131
+ ranked = sorted(sample_rows, key=lambda row: _float(row.get("final_score", row.get("SCORE")), float("inf")))
132
+ sample_top = {str(row["ligand_id"]) for row in ranked[:n] if str(row.get("is_final_fidelity", "")).lower() in {"true", "1"}}
133
+ return len(full_top & sample_top)
134
+
135
+
136
+ def _infer_cluster_id(row: dict[str, str], index: int) -> str:
137
+ for key in ("cluster_id", "scaffold_id", "series_id"):
138
+ value = str(row.get(key, "")).strip()
139
+ if value:
140
+ return value
141
+ smiles = str(row.get("smiles", "")).strip()
142
+ if smiles:
143
+ return smiles[:12]
144
+ return f"cluster_{index:05d}"
145
+
146
+
147
+ def _build_model_rows(rows: list[dict[str, str]]) -> list[dict[str, Any]]:
148
+ numeric_keys = [
149
+ "reference_similarity",
150
+ "molecular_weight",
151
+ "xlogp",
152
+ "tpsa",
153
+ "hbd",
154
+ "hba",
155
+ "rotatable_bonds",
156
+ "heavy_atom_count",
157
+ ]
158
+ features: dict[str, list[float]] = {key: [] for key in numeric_keys}
159
+ parsed: list[dict[str, Any]] = []
160
+ for idx, row in enumerate(rows):
161
+ item: dict[str, Any] = dict(row)
162
+ item["cluster_id"] = _infer_cluster_id(row, idx)
163
+ scaffold_match = str(row.get("scaffold_match", "")).strip().lower() in {"1", "true", "yes", "y"}
164
+ is_reference = str(row.get("is_reference", "")).strip().lower() in {"1", "true", "yes", "y"}
165
+ item["scaffold_match_num"] = 1.0 if scaffold_match else 0.0
166
+ item["is_reference_num"] = 1.0 if is_reference else 0.0
167
+ sim = _float(row.get("reference_similarity"), 0.0)
168
+ model_score = _float(row.get("model_score"), sim + 0.1 * item["scaffold_match_num"] + 0.05 * item["is_reference_num"])
169
+ item["model_score"] = model_score
170
+ for key in numeric_keys:
171
+ value = _float(row.get(key), 0.0)
172
+ item[key] = value
173
+ features[key].append(value)
174
+ parsed.append(item)
175
+ means = {key: _mean(values) for key, values in features.items()}
176
+ stdevs = {key: _stdev(values, means[key]) for key, values in features.items()}
177
+ for item in parsed:
178
+ item["feature_vector"] = [
179
+ (_float(item[key]) - means[key]) / stdevs[key]
180
+ for key in numeric_keys
181
+ ] + [float(item["scaffold_match_num"]), float(item["is_reference_num"])]
182
+ return parsed
183
+
184
+
185
+ def _distance(a: list[float], b: list[float]) -> float:
186
+ return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))
187
+
188
+
189
+ def _plan_level_counts(library_size: int, levels: list[int], budget_runs: int, promotion_fraction: float) -> list[int]:
190
+ if not 0.0 < promotion_fraction <= 1.0:
191
+ raise RDockPipelineError(f"promotion_fraction must be in (0, 1], got {promotion_fraction}")
192
+ if library_size <= 0:
193
+ return [0 for _ in levels]
194
+ best_counts = [0 for _ in levels]
195
+ for final_count in range(1, library_size + 1):
196
+ counts = [0 for _ in levels]
197
+ counts[-1] = final_count
198
+ for idx in range(len(levels) - 2, -1, -1):
199
+ counts[idx] = min(library_size, max(counts[idx + 1], int(math.ceil(counts[idx + 1] / promotion_fraction))))
200
+ cost = sum(count * level for count, level in zip(counts, levels))
201
+ if cost <= budget_runs:
202
+ best_counts = counts
203
+ else:
204
+ break
205
+ if not any(best_counts):
206
+ base = min(library_size, max(1, budget_runs // levels[0]))
207
+ best_counts[0] = base
208
+ for idx in range(1, len(levels)):
209
+ best_counts[idx] = 0
210
+ return best_counts
211
+
212
+
213
+ def _select_diverse(rows: list[dict[str, Any]], target_count: int, min_per_cluster: int, max_per_cluster: int) -> list[dict[str, Any]]:
214
+ if target_count <= 0 or not rows:
215
+ return []
216
+ cluster_counts: dict[str, int] = {}
217
+ selected: list[dict[str, Any]] = []
218
+ cluster_buckets: dict[str, list[dict[str, Any]]] = {}
219
+ for row in rows:
220
+ cluster_buckets.setdefault(str(row["cluster_id"]), []).append(row)
221
+ for cluster_id in sorted(cluster_buckets):
222
+ bucket = cluster_buckets[cluster_id]
223
+ take = min(len(bucket), min_per_cluster, max_per_cluster, target_count - len(selected))
224
+ selected.extend(bucket[:take])
225
+ cluster_counts[cluster_id] = take
226
+ if len(selected) >= target_count:
227
+ return selected[:target_count]
228
+ for row in rows:
229
+ cluster_id = str(row["cluster_id"])
230
+ current = cluster_counts.get(cluster_id, 0)
231
+ if current >= max_per_cluster:
232
+ continue
233
+ if any(str(existing["ligand_id"]) == str(row["ligand_id"]) for existing in selected):
234
+ continue
235
+ selected.append(row)
236
+ cluster_counts[cluster_id] = current + 1
237
+ if len(selected) >= target_count:
238
+ break
239
+ return selected[:target_count]
240
+
241
+
242
+ @dataclass
243
+ class MultiFidelityConfig:
244
+ strategy: str
245
+ fidelity_levels: list[int]
246
+ cost_budget_runs: int
247
+ adaptive_budget_ligands: int | None
248
+ promotion_fraction: float
249
+ min_per_cluster: int
250
+ max_per_cluster: int
251
+ outlier_intra_z_threshold: float
252
+ score_component_filter: str
253
+ final_fidelity_only_hits: bool
254
+ checkpoint_every: int
255
+ jobs: int | str
256
+ cpu_fraction: float
257
+ resume: bool
258
+
259
+
260
+ class MultiFidelityAdaptiveRunner:
261
+ def __init__(
262
+ self,
263
+ dataset_dir: str | Path,
264
+ out_dir: str | Path,
265
+ engine: RDockEngine,
266
+ config: MultiFidelityConfig,
267
+ ) -> None:
268
+ self.dataset_dir = Path(dataset_dir)
269
+ self.out_dir = Path(out_dir)
270
+ self.engine = engine
271
+ self.config = config
272
+ self.dataset_validation = validate_dataset_dir(self.dataset_dir, check_rdock_tools=False)
273
+ self.manifest = self.dataset_validation["manifest"]
274
+ self.target_config = load_target_config(self.dataset_dir / "target" / "rdock_prm" / "target_config.yaml")
275
+ self.ligands_sdf = require_file(self.dataset_dir / "ligands" / "all_ligands.sdf", "dataset ligand library")
276
+ metadata_path = self.dataset_dir / "ligands" / "ligand_metadata.csv"
277
+ if metadata_path.exists():
278
+ metadata_rows = read_ligand_metadata(metadata_path)
279
+ else:
280
+ metadata_rows = [{"ligand_id": ligand_id, "smiles": ""} for ligand_id in self._load_block_map()]
281
+ self.model_rows = _build_model_rows(metadata_rows)
282
+ self.model_by_id = {str(row["ligand_id"]): row for row in self.model_rows}
283
+ self.block_map = self._load_block_map()
284
+ self.final_level = self.config.fidelity_levels[-1]
285
+ self.trace_rows: list[dict[str, Any]] = []
286
+ self.promotion_rows: list[dict[str, Any]] = []
287
+ self.state_by_id: dict[str, dict[str, Any]] = {}
288
+ self.training_time_total = 0.0
289
+ self.docking_time_total = 0.0
290
+ self.overhead_time_total = 0.0
291
+ self._init_state()
292
+
293
+ def _load_block_map(self) -> dict[str, str]:
294
+ return _load_input_block_map(Path(self.ligands_sdf))
295
+
296
+ def _init_state(self) -> None:
297
+ for row in self.model_rows:
298
+ ligand_id = str(row["ligand_id"])
299
+ self.state_by_id[ligand_id] = {
300
+ "ligand_id": ligand_id,
301
+ "cluster_id": str(row["cluster_id"]),
302
+ "model_score": float(row["model_score"]),
303
+ "surrogate_score": float(row["model_score"]),
304
+ "selected_fidelity_runs": 0,
305
+ "current_best_score": "",
306
+ "current_best_score_level": "",
307
+ "final_score": "",
308
+ "is_final_fidelity": False,
309
+ "n_rdock_runs_total_spent": 0,
310
+ "promoted_from_level": "",
311
+ "promoted_to_level": "",
312
+ "promotion_reason": "",
313
+ "batch_id": "",
314
+ "rdock_success": False,
315
+ "failed_reason": "",
316
+ "timing_docking_seconds": 0.0,
317
+ "timing_training_seconds": 0.0,
318
+ "intra_outlier": False,
319
+ "score_outlier": False,
320
+ "component_warning": "",
321
+ }
322
+
323
+ def _write_checkpoint(self, name: str, payload: dict[str, Any]) -> None:
324
+ checkpoint_dir = self.out_dir / "checkpoints"
325
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
326
+ _write_json(checkpoint_dir / f"{name}.json", payload)
327
+
328
+ def _prepare_output_layout(self) -> None:
329
+ for name in ("target", "ligands", "rdock", "poses", "tables", "metrics", "plots", "checkpoints"):
330
+ (self.out_dir / name).mkdir(parents=True, exist_ok=True)
331
+ target_dir = self.out_dir / "target"
332
+ shutil.copy2(require_file(self.dataset_dir / "target" / "target.mol2", "dataset target.mol2"), target_dir / "target.mol2")
333
+ shutil.copy2(require_file(self.dataset_dir / "target" / "reference_ligand.sdf", "dataset reference_ligand.sdf"), target_dir / "reference_ligand.sdf")
334
+ prm_dir = target_dir / "rdock_prm"
335
+ prm_dir.mkdir(parents=True, exist_ok=True)
336
+ for path in (self.dataset_dir / "target" / "rdock_prm").iterdir():
337
+ if path.is_file():
338
+ shutil.copy2(path, prm_dir / path.name)
339
+ shutil.copy2(self.ligands_sdf, self.out_dir / "ligands" / "all_ligands.sdf")
340
+
341
+ def _run_full_docking(self) -> tuple[list[dict[str, Any]], dict[str, Any]]:
342
+ full_dir = self.out_dir / "full_docking"
343
+ full_dir.mkdir(parents=True, exist_ok=True)
344
+ start = time.time()
345
+ artifacts = self.engine.dock_sdf(
346
+ self.target_config,
347
+ self.ligands_sdf,
348
+ full_dir,
349
+ n_runs=self.final_level,
350
+ jobs=self.config.jobs,
351
+ run_id=f"{self.out_dir.name}_full",
352
+ resume=self.config.resume,
353
+ )
354
+ elapsed = time.time() - start
355
+ rows = _augment_full_rows(_read_rows(artifacts.best_per_ligand_csv))
356
+ write_rows_csv(rows, self.out_dir / "tables" / "full_docking_scores.csv")
357
+ metrics = {
358
+ "library_size": _count_sdf(Path(self.ligands_sdf)),
359
+ "successful_ligands": len(rows),
360
+ "failed_ligands": max(0, _count_sdf(Path(self.ligands_sdf)) - len(rows)),
361
+ "pose_count": _count_sdf(Path(artifacts.all_poses_sdf)),
362
+ "best_SCORE": _float(rows[0]["SCORE"]) if rows else None,
363
+ "full_docking_seconds": elapsed,
364
+ "n_runs": self.final_level,
365
+ "best_ligand_id": rows[0]["ligand_id"] if rows else None,
366
+ }
367
+ _write_json(self.out_dir / "metrics" / "rdock_metrics.json", metrics)
368
+ return rows, metrics
369
+
370
+ def _run_single_fidelity_adaptive(self, count: int) -> tuple[list[dict[str, Any]], float]:
371
+ if count <= 0:
372
+ return [], 0.0
373
+ ordered = sorted(
374
+ self.model_rows,
375
+ key=lambda row: (-float(row["model_score"]), str(row["cluster_id"]), str(row["ligand_id"])),
376
+ )
377
+ selected = _select_diverse(ordered, count, self.config.min_per_cluster, self.config.max_per_cluster)
378
+ selected_ids = [str(row["ligand_id"]) for row in selected]
379
+ run_dir = self.out_dir / "single_fidelity_adaptive"
380
+ run_dir.mkdir(parents=True, exist_ok=True)
381
+ sdf_path = self.out_dir / "ligands" / "single_fidelity_adaptive.sdf"
382
+ _write_selected_sdf(self.block_map, selected_ids, sdf_path)
383
+ start = time.time()
384
+ self.engine.dock_sdf(
385
+ self.target_config,
386
+ sdf_path,
387
+ run_dir,
388
+ n_runs=self.final_level,
389
+ jobs=self.config.jobs,
390
+ run_id=f"{self.out_dir.name}_single",
391
+ resume=self.config.resume,
392
+ )
393
+ elapsed = time.time() - start
394
+ rows = [dict(row) for row in _read_rows(run_dir / "tables" / "best_per_ligand.csv")]
395
+ for row in rows:
396
+ row["is_final_fidelity"] = True
397
+ row["final_score"] = row.get("SCORE", "")
398
+ write_rows_csv(rows, self.out_dir / "tables" / "single_fidelity_adaptive_scores.csv")
399
+ return rows, elapsed
400
+
401
+ def _run_random_baseline(self, cost_budget_runs: int) -> tuple[list[dict[str, Any]], float]:
402
+ count = max(1, cost_budget_runs // self.final_level)
403
+ population = [str(row["ligand_id"]) for row in self.model_rows]
404
+ selected_ids = random.Random(42).sample(population, min(len(population), count))
405
+ run_dir = self.out_dir / "random_baseline"
406
+ run_dir.mkdir(parents=True, exist_ok=True)
407
+ sdf_path = self.out_dir / "ligands" / "random_baseline.sdf"
408
+ _write_selected_sdf(self.block_map, selected_ids, sdf_path)
409
+ start = time.time()
410
+ self.engine.dock_sdf(
411
+ self.target_config,
412
+ sdf_path,
413
+ run_dir,
414
+ n_runs=self.final_level,
415
+ jobs=self.config.jobs,
416
+ run_id=f"{self.out_dir.name}_random",
417
+ resume=self.config.resume,
418
+ )
419
+ elapsed = time.time() - start
420
+ rows = [dict(row) for row in _read_rows(run_dir / "tables" / "best_per_ligand.csv")]
421
+ for row in rows:
422
+ row["is_final_fidelity"] = True
423
+ row["final_score"] = row.get("SCORE", "")
424
+ row["n_rdock_runs_total_spent"] = self.final_level
425
+ write_rows_csv(rows, self.out_dir / "tables" / "random_baseline_scores.csv")
426
+ return rows, elapsed
427
+
428
+ def _penalize_rows(self, rows: list[dict[str, Any]], level: int) -> list[dict[str, Any]]:
429
+ score_values = [_float(row.get("SCORE"), float("nan")) for row in rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}]
430
+ intra_values = [_float(row.get("SCORE.INTRA"), float("nan")) for row in rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}]
431
+ score_mean = _mean(score_values)
432
+ intra_mean = _mean(intra_values)
433
+ score_sd = _stdev(score_values, score_mean)
434
+ intra_sd = _stdev(intra_values, intra_mean)
435
+ output: list[dict[str, Any]] = []
436
+ for row in rows:
437
+ item = dict(row)
438
+ score = _float(item.get("SCORE"), float("inf"))
439
+ intra = _float(item.get("SCORE.INTRA"), 0.0)
440
+ score_z = (score - score_mean) / score_sd if math.isfinite(score) else 0.0
441
+ intra_z = (intra - intra_mean) / intra_sd if math.isfinite(intra) else 0.0
442
+ dominant_intra = abs(intra) > max(10.0, abs(score) * 1.5)
443
+ intra_outlier = intra_z < (-abs(self.config.outlier_intra_z_threshold)) or dominant_intra
444
+ score_outlier = score_z < -4.0
445
+ penalty = 0.0
446
+ warnings: list[str] = []
447
+ if intra_outlier:
448
+ penalty += min(25.0, abs(intra_z) * 2.0 if math.isfinite(intra_z) else 10.0)
449
+ warnings.append("intra_outlier")
450
+ if score_outlier:
451
+ penalty += 5.0
452
+ warnings.append("score_outlier")
453
+ item["intra_outlier"] = intra_outlier
454
+ item["score_outlier"] = score_outlier
455
+ item["component_warning"] = ",".join(warnings)
456
+ item["ranking_score"] = score + penalty
457
+ item["selected_fidelity_runs"] = level
458
+ output.append(item)
459
+ return output
460
+
461
+ def _promotion_priority(self, row: dict[str, Any]) -> float:
462
+ ranking_score = _float(row.get("ranking_score"), float("inf"))
463
+ model_score = _float(row.get("model_score"), 0.0)
464
+ surrogate_score = _float(row.get("surrogate_score"), 0.0)
465
+ return ranking_score - (0.5 * surrogate_score) - (0.25 * model_score)
466
+
467
+ def _update_surrogate(self, observed_rows: list[dict[str, Any]]) -> float:
468
+ start = time.time()
469
+ observed = [(str(row["ligand_id"]), _float(row.get("ranking_score"), float("inf"))) for row in observed_rows]
470
+ if not observed:
471
+ return 0.0
472
+ observed_ids = [ligand_id for ligand_id, _ in observed]
473
+ for row in self.model_rows:
474
+ ligand_id = str(row["ligand_id"])
475
+ if ligand_id in observed_ids:
476
+ row["surrogate_score"] = -_float(next(item[1] for item in observed if item[0] == ligand_id))
477
+ continue
478
+ neighbors: list[tuple[float, float]] = []
479
+ for observed_id, ranking_score in observed:
480
+ ref = self.model_by_id[observed_id]
481
+ dist = _distance(row["feature_vector"], ref["feature_vector"])
482
+ neighbors.append((dist, ranking_score))
483
+ neighbors.sort(key=lambda item: item[0])
484
+ top = neighbors[: min(16, len(neighbors))]
485
+ weights = [1.0 / (1.0 + dist) for dist, _ in top]
486
+ total_weight = sum(weights) or 1.0
487
+ predicted = sum(weight * score for weight, (_, score) in zip(weights, top)) / total_weight
488
+ row["surrogate_score"] = -predicted
489
+ return time.time() - start
490
+
491
+ def _record_level_rows(self, level: int, batch_id: int, rows: list[dict[str, Any]], level_seconds: float, training_seconds: float) -> None:
492
+ level_rows: list[dict[str, Any]] = []
493
+ for row in rows:
494
+ ligand_id = str(row["ligand_id"])
495
+ state = self.state_by_id[ligand_id]
496
+ raw_score = row.get("SCORE", "")
497
+ current_best = state["current_best_score"]
498
+ if current_best == "" or _float(raw_score, float("inf")) < _float(current_best, float("inf")):
499
+ state["current_best_score"] = raw_score
500
+ state["current_best_score_level"] = level
501
+ state["selected_fidelity_runs"] = level
502
+ state["surrogate_score"] = self.model_by_id[ligand_id].get("surrogate_score", state["surrogate_score"])
503
+ state["n_rdock_runs_total_spent"] = int(state["n_rdock_runs_total_spent"]) + level
504
+ state["batch_id"] = batch_id
505
+ state["rdock_success"] = str(row.get("rdock_success", True)).lower() in {"true", "1"}
506
+ state["failed_reason"] = row.get("failed_reason", "")
507
+ state["timing_docking_seconds"] = _float(state["timing_docking_seconds"]) + level_seconds / max(1, len(rows))
508
+ state["timing_training_seconds"] = _float(state["timing_training_seconds"]) + training_seconds / max(1, len(rows))
509
+ state["intra_outlier"] = row.get("intra_outlier", False)
510
+ state["score_outlier"] = row.get("score_outlier", False)
511
+ state["component_warning"] = row.get("component_warning", "")
512
+ if level == self.final_level and state["rdock_success"]:
513
+ state["final_score"] = raw_score
514
+ state["is_final_fidelity"] = True
515
+ merged = dict(state)
516
+ merged.update({key: value for key, value in row.items() if key not in merged})
517
+ self.trace_rows.append(merged)
518
+ level_rows.append(merged)
519
+ write_rows_csv(level_rows, self.out_dir / "tables" / f"fidelity_level_{level}_scores.csv")
520
+
521
+ def _run_level(self, level: int, level_index: int, selected_ids: list[str]) -> list[dict[str, Any]]:
522
+ level_dir = self.out_dir / "rdock" / f"fidelity_{level:03d}"
523
+ selection_path = level_dir / "selection.json"
524
+ level_dir.mkdir(parents=True, exist_ok=True)
525
+ if not (self.config.resume and selection_path.exists()):
526
+ _write_json(
527
+ selection_path,
528
+ {
529
+ "level": level,
530
+ "level_index": level_index,
531
+ "ligand_ids": selected_ids,
532
+ },
533
+ )
534
+ sdf_path = self.out_dir / "ligands" / f"fidelity_{level:03d}.sdf"
535
+ if not (self.config.resume and sdf_path.exists() and _count_sdf(sdf_path) == len(selected_ids)):
536
+ _write_selected_sdf(self.block_map, selected_ids, sdf_path)
537
+ start = time.time()
538
+ self.engine.dock_sdf(
539
+ self.target_config,
540
+ sdf_path,
541
+ level_dir,
542
+ n_runs=level,
543
+ jobs=self.config.jobs,
544
+ run_id=f"{self.out_dir.name}_fidelity_{level:03d}",
545
+ resume=self.config.resume,
546
+ )
547
+ level_seconds = time.time() - start
548
+ self.docking_time_total += level_seconds
549
+ best_rows = []
550
+ success_rows = {str(row["ligand_id"]): dict(row) for row in _read_rows(level_dir / "tables" / "best_per_ligand.csv")}
551
+ for ligand_id in selected_ids:
552
+ row = success_rows.get(ligand_id, {"ligand_id": ligand_id, "rdock_success": False, "failed_reason": "missing_best_pose"})
553
+ row.setdefault("model_score", self.model_by_id[ligand_id]["model_score"])
554
+ row.setdefault("cluster_id", self.model_by_id[ligand_id]["cluster_id"])
555
+ row.setdefault("surrogate_score", self.model_by_id[ligand_id].get("surrogate_score", self.model_by_id[ligand_id]["model_score"]))
556
+ row["rdock_success"] = bool(success_rows.get(ligand_id))
557
+ best_rows.append(row)
558
+ penalized = self._penalize_rows(best_rows, level)
559
+ training_seconds = self._update_surrogate(penalized)
560
+ self.training_time_total += training_seconds
561
+ self._record_level_rows(level, level_index, penalized, level_seconds, training_seconds)
562
+ return penalized
563
+
564
+ def _promotion_reason(self, row: dict[str, Any]) -> str:
565
+ reasons = [f"ranking_score={row.get('ranking_score')}", f"cluster={row.get('cluster_id')}"]
566
+ if row.get("component_warning"):
567
+ reasons.append(str(row["component_warning"]))
568
+ return ";".join(reasons)
569
+
570
+ def _promote(
571
+ self,
572
+ rows: list[dict[str, Any]],
573
+ current_level: int,
574
+ next_level: int,
575
+ target_count: int,
576
+ ) -> list[str]:
577
+ successful = [row for row in rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}]
578
+ ordered = sorted(
579
+ successful,
580
+ key=lambda row: (
581
+ self._promotion_priority(row),
582
+ -_float(row.get("model_score"), 0.0),
583
+ str(row.get("cluster_id", "")),
584
+ str(row.get("ligand_id", "")),
585
+ ),
586
+ )
587
+ chosen_rows = _select_diverse(ordered, target_count, self.config.min_per_cluster, self.config.max_per_cluster)
588
+ promoted_ids = [str(row["ligand_id"]) for row in chosen_rows]
589
+ for row in ordered:
590
+ ligand_id = str(row["ligand_id"])
591
+ decision = {
592
+ "ligand_id": ligand_id,
593
+ "cluster_id": row.get("cluster_id", ""),
594
+ "from_level": current_level,
595
+ "to_level": next_level if ligand_id in promoted_ids else "",
596
+ "promoted": ligand_id in promoted_ids,
597
+ "promotion_reason": self._promotion_reason(row) if ligand_id in promoted_ids else "not selected",
598
+ "ranking_score": row.get("ranking_score", ""),
599
+ "SCORE": row.get("SCORE", ""),
600
+ "SCORE.INTER": row.get("SCORE.INTER", ""),
601
+ "SCORE.INTRA": row.get("SCORE.INTRA", ""),
602
+ "component_warning": row.get("component_warning", ""),
603
+ }
604
+ self.promotion_rows.append(decision)
605
+ state = self.state_by_id[ligand_id]
606
+ if ligand_id in promoted_ids:
607
+ state["promoted_from_level"] = current_level
608
+ state["promoted_to_level"] = next_level
609
+ state["promotion_reason"] = decision["promotion_reason"]
610
+ return promoted_ids
611
+
612
+ def _initial_selection(self, target_count: int) -> list[str]:
613
+ ordered = sorted(
614
+ self.model_rows,
615
+ key=lambda row: (-float(row["model_score"]), str(row["cluster_id"]), str(row["ligand_id"])),
616
+ )
617
+ selected = _select_diverse(ordered, target_count, self.config.min_per_cluster, self.config.max_per_cluster)
618
+ return [str(row["ligand_id"]) for row in selected]
619
+
620
+ def run_multifidelity(self) -> dict[str, Any]:
621
+ self._prepare_output_layout()
622
+ full_rows, full_metrics = self._run_full_docking()
623
+ single_count = max(1, self.config.cost_budget_runs // self.final_level)
624
+ single_rows, single_seconds = self._run_single_fidelity_adaptive(single_count)
625
+ random_rows, random_seconds = self._run_random_baseline(self.config.cost_budget_runs)
626
+
627
+ level_counts = _plan_level_counts(
628
+ library_size=_count_sdf(Path(self.ligands_sdf)),
629
+ levels=self.config.fidelity_levels,
630
+ budget_runs=self.config.cost_budget_runs,
631
+ promotion_fraction=self.config.promotion_fraction,
632
+ )
633
+ if self.config.adaptive_budget_ligands is not None and level_counts:
634
+ level_counts[0] = min(level_counts[0], int(self.config.adaptive_budget_ligands))
635
+ selected_ids = self._initial_selection(level_counts[0] if level_counts else 0)
636
+ observed_rows: list[dict[str, Any]] = []
637
+ per_level_summary: list[dict[str, Any]] = []
638
+ for idx, level in enumerate(self.config.fidelity_levels):
639
+ if not selected_ids:
640
+ break
641
+ level_rows = self._run_level(level, idx, selected_ids)
642
+ observed_rows.extend(level_rows)
643
+ outlier_count = sum(1 for row in level_rows if str(row.get("intra_outlier", "")).lower() in {"true", "1"})
644
+ successful_count = sum(1 for row in level_rows if str(row.get("rdock_success", "")).lower() in {"true", "1"})
645
+ per_level_summary.append(
646
+ {
647
+ "fidelity_level": level,
648
+ "screened_ligands": len(selected_ids),
649
+ "successful_ligands": successful_count,
650
+ "failed_ligands": len(selected_ids) - successful_count,
651
+ "outlier_count": outlier_count,
652
+ }
653
+ )
654
+ if idx + 1 < len(self.config.fidelity_levels):
655
+ selected_ids = self._promote(level_rows, level, self.config.fidelity_levels[idx + 1], level_counts[idx + 1])
656
+ if idx % max(1, self.config.checkpoint_every) == 0:
657
+ self._write_checkpoint(
658
+ f"level_{level:03d}",
659
+ {
660
+ "level": level,
661
+ "selected_ids": selected_ids,
662
+ "summary": per_level_summary[-1],
663
+ },
664
+ )
665
+ else:
666
+ selected_ids = []
667
+
668
+ write_rows_csv(self.trace_rows, self.out_dir / "tables" / "multifidelity_trace.csv")
669
+ write_rows_csv(self.promotion_rows, self.out_dir / "tables" / "promotion_decisions.csv")
670
+
671
+ final_rows = [dict(state) for state in self.state_by_id.values() if not self.config.final_fidelity_only_hits or bool(state["is_final_fidelity"])]
672
+ final_rows = [row for row in final_rows if row.get("final_score", "") != "" or not self.config.final_fidelity_only_hits]
673
+ final_rows.sort(key=lambda row: (_float(row.get("final_score", row.get("current_best_score")), float("inf")), str(row.get("ligand_id", ""))))
674
+ write_rows_csv(final_rows, self.out_dir / "tables" / "final_hits.csv")
675
+
676
+ full_rank_map = {str(row["ligand_id"]): int(row["full_rank"]) for row in full_rows}
677
+ random_ranked = _append_rank_metrics(random_rows, full_rank_map, len(full_rows))
678
+ single_ranked = _append_rank_metrics(single_rows, full_rank_map, len(full_rows))
679
+ final_ranked = _append_rank_metrics(final_rows, full_rank_map, len(full_rows))
680
+ write_rows_csv(random_ranked, self.out_dir / "tables" / "random_baseline_scores.csv")
681
+ write_rows_csv(single_ranked, self.out_dir / "tables" / "single_fidelity_adaptive_scores.csv")
682
+ write_rows_csv(final_ranked, self.out_dir / "tables" / "multifidelity_final_hits_ranked.csv")
683
+
684
+ full_best = full_rows[0] if full_rows else None
685
+ final_only_rows = [row for row in final_ranked if str(row.get("is_final_fidelity", "")).lower() in {"true", "1"}]
686
+ mf_best = final_only_rows[0] if final_only_rows else None
687
+ random_best = min(random_ranked, key=lambda row: _float(row.get("final_score", row.get("SCORE")), float("inf"))) if random_ranked else None
688
+ single_best = min(single_ranked, key=lambda row: _float(row.get("final_score", row.get("SCORE")), float("inf"))) if single_ranked else None
689
+ total_runs_spent = sum(int(_float(row.get("n_rdock_runs_total_spent"), 0.0)) for row in self.state_by_id.values())
690
+ metrics = {
691
+ "strategy": self.config.strategy,
692
+ "dataset_dir": str(self.dataset_dir),
693
+ "target_id": str(self.manifest.get("pdb_id", self.out_dir.name)).lower(),
694
+ "fidelity_levels": self.config.fidelity_levels,
695
+ "cost_budget_runs": self.config.cost_budget_runs,
696
+ "best_final_SCORE_found_by_multifidelity": _float(mf_best.get("final_score")) if mf_best else None,
697
+ "best_final_SCORE_found_by_random_at_same_cost": _float(random_best.get("final_score", random_best.get("SCORE"))) if random_best else None,
698
+ "best_SCORE_in_full_docking": _float(full_best.get("SCORE")) if full_best else None,
699
+ "best_final_SCORE_found_by_single_fidelity": _float(single_best.get("final_score", single_best.get("SCORE"))) if single_best else None,
700
+ "multifidelity_percentile_vs_full": _float(mf_best.get("full_percentile")) if mf_best else None,
701
+ "random_percentile_vs_full": _float(random_best.get("full_percentile")) if random_best else None,
702
+ "single_fidelity_percentile_vs_full": _float(single_best.get("full_percentile")) if single_best else None,
703
+ "top1_overlap_vs_full": _top_overlap(full_rows, final_ranked, 1),
704
+ "top5_overlap_vs_full": _top_overlap(full_rows, final_ranked, 5),
705
+ "top10_overlap_vs_full": _top_overlap(full_rows, final_ranked, 10),
706
+ "total_rdock_runs_spent": total_runs_spent,
707
+ "walltime_total_seconds": self.docking_time_total + self.training_time_total + self.overhead_time_total + full_metrics["full_docking_seconds"] + random_seconds + single_seconds,
708
+ "docking_time_seconds": self.docking_time_total,
709
+ "training_time_seconds": self.training_time_total,
710
+ "overhead_time_seconds": self.overhead_time_total,
711
+ "number_of_ligands_screened_at_each_fidelity": per_level_summary,
712
+ "number_promoted_between_levels": {
713
+ f"{current}->{next_level}": sum(1 for row in self.promotion_rows if row.get("promoted") and row.get("from_level") == current and row.get("to_level") == next_level)
714
+ for current, next_level in zip(self.config.fidelity_levels[:-1], self.config.fidelity_levels[1:])
715
+ },
716
+ "success_failure_rate_per_fidelity": per_level_summary,
717
+ "outlier_count_per_fidelity": {str(row["fidelity_level"]): row["outlier_count"] for row in per_level_summary},
718
+ "adaptive_gain_over_random": (
719
+ _float(random_best.get("full_percentile")) - _float(mf_best.get("full_percentile"))
720
+ if mf_best and random_best
721
+ else None
722
+ ),
723
+ "final_hits_count": len(final_only_rows),
724
+ "full_docking_success_count": len(full_rows),
725
+ "random_final_count": len(random_ranked),
726
+ "single_fidelity_final_count": len(single_ranked),
727
+ }
728
+ _write_json(self.out_dir / "metrics" / "adaptive_benchmark_metrics.json", metrics)
729
+ _write_json(self.out_dir / "metrics" / "validation_metrics.json", metrics)
730
+
731
+ plots = []
732
+ plots.extend(plot_score_outputs(self.out_dir / "tables" / "full_docking_scores.csv", self.out_dir / "plots", title_prefix="full docking"))
733
+ plots.extend(
734
+ plot_multifidelity_outputs(
735
+ self.out_dir / "tables" / "multifidelity_trace.csv",
736
+ self.out_dir / "tables" / "final_hits.csv",
737
+ self.out_dir / "tables" / "random_baseline_scores.csv",
738
+ self.out_dir / "tables" / "full_docking_scores.csv",
739
+ self.out_dir / "metrics" / "adaptive_benchmark_metrics.json",
740
+ self.out_dir / "plots",
741
+ )
742
+ )
743
+
744
+ report_lines = [
745
+ f"# benchmark-adaptive: {self.manifest.get('pdb_id', self.out_dir.name)}",
746
+ "",
747
+ "## Input",
748
+ f"- dataset_dir: `{self.dataset_dir}`",
749
+ f"- strategy: `{self.config.strategy}`",
750
+ f"- fidelity_levels: `{','.join(str(v) for v in self.config.fidelity_levels)}`",
751
+ f"- cost_budget_runs: `{self.config.cost_budget_runs}`",
752
+ f"- jobs: `{self.config.jobs}`",
753
+ f"- cpu_fraction: `{self.config.cpu_fraction}`",
754
+ "",
755
+ "## Metrics",
756
+ ]
757
+ for key in [
758
+ "best_final_SCORE_found_by_multifidelity",
759
+ "best_final_SCORE_found_by_random_at_same_cost",
760
+ "best_final_SCORE_found_by_single_fidelity",
761
+ "best_SCORE_in_full_docking",
762
+ "multifidelity_percentile_vs_full",
763
+ "random_percentile_vs_full",
764
+ "single_fidelity_percentile_vs_full",
765
+ "total_rdock_runs_spent",
766
+ "walltime_total_seconds",
767
+ "docking_time_seconds",
768
+ "training_time_seconds",
769
+ "adaptive_gain_over_random",
770
+ ]:
771
+ report_lines.append(f"- {key}: `{metrics.get(key)}`")
772
+ report_lines.extend(["", "## Plots"])
773
+ report_lines.extend([f"- `{path}`" for path in plots] or ["- No plots generated"])
774
+ report_lines.extend(["", "## Top Final Hits"])
775
+ for row in final_only_rows[:20]:
776
+ report_lines.append(
777
+ f"- `{row.get('ligand_id')}` final_score `{row.get('final_score')}` "
778
+ f"cluster `{row.get('cluster_id')}` runs_spent `{row.get('n_rdock_runs_total_spent')}` "
779
+ f"warning `{row.get('component_warning', '')}`"
780
+ )
781
+ (self.out_dir / "report.md").write_text("\n".join(report_lines) + "\n", encoding="utf-8")
782
+
783
+ manifest = {
784
+ "engine": "benchmark-adaptive",
785
+ "strategy": self.config.strategy,
786
+ "dataset_dir": str(self.dataset_dir),
787
+ "artifacts": {
788
+ "target_dir": str(self.out_dir / "target"),
789
+ "ligands_sdf": str(self.out_dir / "ligands" / "all_ligands.sdf"),
790
+ "full_docking_scores": str(self.out_dir / "tables" / "full_docking_scores.csv"),
791
+ "random_baseline_scores": str(self.out_dir / "tables" / "random_baseline_scores.csv"),
792
+ "single_fidelity_scores": str(self.out_dir / "tables" / "single_fidelity_adaptive_scores.csv"),
793
+ "multifidelity_trace": str(self.out_dir / "tables" / "multifidelity_trace.csv"),
794
+ "promotion_decisions": str(self.out_dir / "tables" / "promotion_decisions.csv"),
795
+ "final_hits": str(self.out_dir / "tables" / "final_hits.csv"),
796
+ "metrics_json": str(self.out_dir / "metrics" / "adaptive_benchmark_metrics.json"),
797
+ "report": str(self.out_dir / "report.md"),
798
+ },
799
+ "executables": {
800
+ "rbdock": probe_version(require_executable("rbdock")),
801
+ "rbcavity": probe_version(require_executable("rbcavity")),
802
+ "obabel": probe_version(require_executable("obabel")),
803
+ },
804
+ "metrics": metrics,
805
+ }
806
+ _write_json(self.out_dir / "manifest.json", manifest)
807
+ _write_yaml_like(
808
+ self.out_dir / "config.yaml",
809
+ {
810
+ "dataset_dir": str(self.dataset_dir),
811
+ "strategy": self.config.strategy,
812
+ "fidelity_levels": self.config.fidelity_levels,
813
+ "cost_budget_runs": self.config.cost_budget_runs,
814
+ "promotion_fraction": self.config.promotion_fraction,
815
+ "min_per_cluster": self.config.min_per_cluster,
816
+ "max_per_cluster": self.config.max_per_cluster,
817
+ "outlier_intra_z_threshold": self.config.outlier_intra_z_threshold,
818
+ "score_component_filter": self.config.score_component_filter,
819
+ "final_fidelity_only_hits": self.config.final_fidelity_only_hits,
820
+ "jobs": self.config.jobs,
821
+ "cpu_fraction": self.config.cpu_fraction,
822
+ "resume": self.config.resume,
823
+ },
824
+ )
825
+ return {"run_dir": str(self.out_dir), "metrics": metrics}
826
+
827
+
828
+ def build_arg_parser() -> argparse.ArgumentParser:
829
+ parser = argparse.ArgumentParser(description="Run adaptive rDock benchmark from a prepared dataset directory.")
830
+ parser.add_argument("--dataset-dir", required=True)
831
+ parser.add_argument("--strategy", default="multifidelity_adaptive_rdock", choices=["multifidelity_adaptive_rdock", "single_fidelity_adaptive_rdock"])
832
+ parser.add_argument("--fidelity-levels", default="5,10,15,30,50")
833
+ parser.add_argument("--cost-budget-runs", type=int, required=True)
834
+ parser.add_argument("--adaptive-budget-ligands", type=int)
835
+ parser.add_argument("--promotion-fraction", type=float, default=0.5)
836
+ parser.add_argument("--min-per-cluster", type=int, default=1)
837
+ parser.add_argument("--max-per-cluster", type=int, default=50)
838
+ parser.add_argument("--outlier-intra-z-threshold", type=float, default=3.0)
839
+ parser.add_argument("--score-component-filter", default="warn")
840
+ parser.add_argument("--final-fidelity-only-hits", default="true")
841
+ parser.add_argument("--resume", action="store_true")
842
+ parser.add_argument("--checkpoint-every", type=int, default=1)
843
+ parser.add_argument("--jobs", default="auto")
844
+ parser.add_argument("--cpu-fraction", type=float, default=0.85)
845
+ parser.add_argument("--out", required=True)
846
+ parser.add_argument("--dry-run", action="store_true")
847
+ parser.add_argument("--plan-only", action="store_true")
848
+ return parser
849
+
850
+
851
+ def run_from_args(args: argparse.Namespace) -> dict[str, Any]:
852
+ levels = _parse_levels(args.fidelity_levels)
853
+ dataset_summary = validate_dataset_dir(args.dataset_dir, check_rdock_tools=False)
854
+ plan = {
855
+ "dataset_dir": args.dataset_dir,
856
+ "strategy": args.strategy,
857
+ "fidelity_levels": levels,
858
+ "cost_budget_runs": int(args.cost_budget_runs),
859
+ "adaptive_budget_ligands": args.adaptive_budget_ligands,
860
+ "promotion_fraction": float(args.promotion_fraction),
861
+ "min_per_cluster": int(args.min_per_cluster),
862
+ "max_per_cluster": int(args.max_per_cluster),
863
+ "outlier_intra_z_threshold": float(args.outlier_intra_z_threshold),
864
+ "score_component_filter": args.score_component_filter,
865
+ "final_fidelity_only_hits": str(args.final_fidelity_only_hits).lower() in {"1", "true", "yes", "y"},
866
+ "jobs": args.jobs,
867
+ "cpu_fraction": float(args.cpu_fraction),
868
+ "dataset_summary": dataset_summary,
869
+ }
870
+ out_dir = Path(args.out)
871
+ out_dir.mkdir(parents=True, exist_ok=True)
872
+ if args.dry_run or args.plan_only:
873
+ _write_json(out_dir / "benchmark_adaptive_plan.json", plan)
874
+ return plan
875
+ config = MultiFidelityConfig(
876
+ strategy=args.strategy,
877
+ fidelity_levels=levels,
878
+ cost_budget_runs=int(args.cost_budget_runs),
879
+ adaptive_budget_ligands=args.adaptive_budget_ligands,
880
+ promotion_fraction=float(args.promotion_fraction),
881
+ min_per_cluster=int(args.min_per_cluster),
882
+ max_per_cluster=int(args.max_per_cluster),
883
+ outlier_intra_z_threshold=float(args.outlier_intra_z_threshold),
884
+ score_component_filter=str(args.score_component_filter),
885
+ final_fidelity_only_hits=str(args.final_fidelity_only_hits).lower() in {"1", "true", "yes", "y"},
886
+ checkpoint_every=int(args.checkpoint_every),
887
+ jobs=args.jobs,
888
+ cpu_fraction=float(args.cpu_fraction),
889
+ resume=bool(args.resume),
890
+ )
891
+ engine = RDockEngine(
892
+ RDockRunConfig(
893
+ n_runs=levels[-1],
894
+ jobs=args.jobs,
895
+ cpu_fraction=float(args.cpu_fraction),
896
+ timeout_seconds=3600,
897
+ )
898
+ )
899
+ runner = MultiFidelityAdaptiveRunner(args.dataset_dir, args.out, engine, config)
900
+ return runner.run_multifidelity()
docking_pipeline/config_io.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from .provenance import RDockPipelineError, require_file
8
+
9
+
10
+ def load_structured_file(path: str | Path) -> dict[str, Any]:
11
+ source = require_file(path, "structured config file")
12
+ text = source.read_text(encoding="utf-8")
13
+ try:
14
+ payload = json.loads(text)
15
+ except json.JSONDecodeError:
16
+ try:
17
+ import yaml
18
+ except Exception as exc:
19
+ raise RDockPipelineError(
20
+ f"Could not parse {source} as JSON and PyYAML is unavailable: {exc}"
21
+ ) from exc
22
+ payload = yaml.safe_load(text)
23
+ if not isinstance(payload, dict):
24
+ raise RDockPipelineError(f"Expected mapping at top level of {source}")
25
+ return payload
26
+
27
+
28
+ def dump_json_like(path: str | Path, payload: dict[str, Any]) -> Path:
29
+ target = Path(path)
30
+ target.parent.mkdir(parents=True, exist_ok=True)
31
+ target.write_text(json.dumps(payload, indent=2), encoding="utf-8")
32
+ return target
docking_pipeline/dataset.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import json
5
+ import math
6
+ import subprocess
7
+ import shutil
8
+ import urllib.request
9
+ from datetime import UTC, datetime
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from .config_io import dump_json_like, load_structured_file
14
+ from .provenance import RDockPipelineError, probe_version, require_executable, require_file
15
+ from .rdock import RDockEngine, RDockRunConfig, load_target_config
16
+ from .sdf import split_sdf_file
17
+
18
+
19
+ IGNORED_SOLVENT_RESNAMES = {
20
+ "HOH",
21
+ "WAT",
22
+ "DOD",
23
+ "SOL",
24
+ "EDO",
25
+ "GOL",
26
+ "PEG",
27
+ "PG4",
28
+ "PGE",
29
+ "MPD",
30
+ "EOH",
31
+ "IPA",
32
+ "DMS",
33
+ "ACT",
34
+ "ACY",
35
+ "FMT",
36
+ "TRS",
37
+ "MES",
38
+ "BME",
39
+ }
40
+ IGNORED_BUFFER_RESNAMES = {
41
+ "SO4",
42
+ "PO4",
43
+ "CL",
44
+ "BR",
45
+ "IOD",
46
+ "NO3",
47
+ "SCN",
48
+ "IMD",
49
+ "CIT",
50
+ "ACE",
51
+ }
52
+ METAL_ELEMENTS = {
53
+ "LI",
54
+ "NA",
55
+ "K",
56
+ "RB",
57
+ "CS",
58
+ "MG",
59
+ "CA",
60
+ "SR",
61
+ "BA",
62
+ "ZN",
63
+ "FE",
64
+ "CO",
65
+ "NI",
66
+ "CU",
67
+ "MN",
68
+ "CD",
69
+ "HG",
70
+ "AG",
71
+ "AU",
72
+ }
73
+
74
+
75
+ def count_sdf_records(path: str | Path) -> int:
76
+ return len(split_sdf_file(path))
77
+
78
+
79
+ def list_known_good_complexes(config_path: str | Path) -> list[dict[str, Any]]:
80
+ payload = load_structured_file(config_path)
81
+ complexes = payload.get("complexes")
82
+ if not isinstance(complexes, list):
83
+ raise RDockPipelineError(f"`complexes` list missing in {config_path}")
84
+ return [dict(item) for item in complexes]
85
+
86
+
87
+ def _parse_pdb_atom_line(line: str) -> dict[str, Any]:
88
+ record = line[:6].strip()
89
+ atom_name = line[12:16].strip()
90
+ resname = line[17:20].strip().upper()
91
+ chain = line[21:22].strip()
92
+ residue_id = line[22:26].strip()
93
+ try:
94
+ x = float(line[30:38].strip())
95
+ y = float(line[38:46].strip())
96
+ z = float(line[46:54].strip())
97
+ except ValueError:
98
+ x = y = z = math.nan
99
+ element = line[76:78].strip().upper() or "".join(char for char in atom_name if char.isalpha())[:2].upper()
100
+ return {
101
+ "record": record,
102
+ "atom_name": atom_name,
103
+ "resname": resname,
104
+ "chain": chain,
105
+ "residue_id": residue_id,
106
+ "x": x,
107
+ "y": y,
108
+ "z": z,
109
+ "element": element,
110
+ "line": line,
111
+ }
112
+
113
+
114
+ def _is_heavy_atom(element: str) -> bool:
115
+ return bool(element) and element != "H"
116
+
117
+
118
+ def _classify_hetero_group(resname: str, elements: set[str], heavy_atom_count: int) -> tuple[bool, str]:
119
+ if resname in IGNORED_SOLVENT_RESNAMES:
120
+ return True, "solvent"
121
+ if resname in IGNORED_BUFFER_RESNAMES:
122
+ return True, "buffer_or_salt"
123
+ if elements and elements.issubset(METAL_ELEMENTS):
124
+ return True, "ion_or_metal"
125
+ if heavy_atom_count <= 1:
126
+ return True, "tiny_fragment"
127
+ return False, ""
128
+
129
+
130
+ def list_hetero_ligands(pdb_like: str | Path, min_reference_ligand_atoms: int = 8) -> list[dict[str, Any]]:
131
+ source = require_file(pdb_like, "PDB/mmCIF structure")
132
+ groups: dict[tuple[str, str, str], dict[str, Any]] = {}
133
+ for line in source.read_text(encoding="utf-8", errors="ignore").splitlines():
134
+ if not line.startswith("HETATM"):
135
+ continue
136
+ atom = _parse_pdb_atom_line(line)
137
+ key = (atom["resname"], atom["chain"], atom["residue_id"])
138
+ group = groups.setdefault(
139
+ key,
140
+ {
141
+ "resname": atom["resname"],
142
+ "chain": atom["chain"],
143
+ "residue_id": atom["residue_id"],
144
+ "atom_count": 0,
145
+ "heavy_atom_count": 0,
146
+ "elements": set(),
147
+ },
148
+ )
149
+ group["atom_count"] += 1
150
+ if _is_heavy_atom(atom["element"]):
151
+ group["heavy_atom_count"] += 1
152
+ if atom["element"]:
153
+ group["elements"].add(atom["element"])
154
+ rows: list[dict[str, Any]] = []
155
+ for _, group in sorted(groups.items()):
156
+ ignored, reason = _classify_hetero_group(
157
+ str(group["resname"]),
158
+ set(group["elements"]),
159
+ int(group["heavy_atom_count"]),
160
+ )
161
+ rows.append(
162
+ {
163
+ "resname": str(group["resname"]),
164
+ "chain": str(group["chain"]),
165
+ "residue_id": str(group["residue_id"]),
166
+ "atom_count": int(group["atom_count"]),
167
+ "heavy_atom_count": int(group["heavy_atom_count"]),
168
+ "ignored": ignored,
169
+ "ignored_reason": reason,
170
+ "candidate_ligand": (not ignored) and int(group["heavy_atom_count"]) >= int(min_reference_ligand_atoms),
171
+ }
172
+ )
173
+ return rows
174
+
175
+
176
+ def auto_detect_reference_ligand(
177
+ pdb_like: str | Path,
178
+ receptor_chain: str,
179
+ min_reference_ligand_atoms: int = 8,
180
+ ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
181
+ source = require_file(pdb_like, "PDB/mmCIF structure")
182
+ hetero = list_hetero_ligands(source, min_reference_ligand_atoms=min_reference_ligand_atoms)
183
+ receptor_chains = {item.strip() for item in receptor_chain.split(",") if item.strip()}
184
+ receptor_atoms: list[tuple[float, float, float]] = []
185
+ ligand_atoms: dict[tuple[str, str, str], list[tuple[float, float, float]]] = {}
186
+ for line in source.read_text(encoding="utf-8", errors="ignore").splitlines():
187
+ if not line.startswith(("ATOM", "HETATM")):
188
+ continue
189
+ atom = _parse_pdb_atom_line(line)
190
+ if line.startswith("ATOM") and (not receptor_chains or atom["chain"] in receptor_chains):
191
+ if not math.isnan(atom["x"]):
192
+ receptor_atoms.append((atom["x"], atom["y"], atom["z"]))
193
+ elif line.startswith("HETATM"):
194
+ key = (atom["resname"], atom["chain"], atom["residue_id"])
195
+ ligand_atoms.setdefault(key, [])
196
+ if not math.isnan(atom["x"]):
197
+ ligand_atoms[key].append((atom["x"], atom["y"], atom["z"]))
198
+ if not receptor_atoms:
199
+ raise RDockPipelineError(f"No receptor atoms found in {source} for chain(s) {receptor_chain}")
200
+
201
+ def _min_distance(points: list[tuple[float, float, float]]) -> float:
202
+ best = math.inf
203
+ for lx, ly, lz in points:
204
+ for rx, ry, rz in receptor_atoms:
205
+ dist = math.dist((lx, ly, lz), (rx, ry, rz))
206
+ if dist < best:
207
+ best = dist
208
+ return best
209
+
210
+ candidates: list[dict[str, Any]] = []
211
+ for row in hetero:
212
+ key = (str(row["resname"]), str(row["chain"]), str(row["residue_id"]))
213
+ points = ligand_atoms.get(key, [])
214
+ if not points:
215
+ continue
216
+ min_dist = _min_distance(points)
217
+ enriched = dict(row)
218
+ enriched["min_distance_to_receptor"] = min_dist
219
+ enriched["contact_candidate"] = bool(row["candidate_ligand"]) and min_dist <= 6.0
220
+ candidates.append(enriched)
221
+ viable = [row for row in candidates if row["candidate_ligand"]]
222
+ if not viable:
223
+ raise RDockPipelineError(
224
+ f"No suitable reference ligand candidates found in {source}. "
225
+ f"Available hetero entries: {candidates[:20]}"
226
+ )
227
+ viable.sort(
228
+ key=lambda item: (
229
+ int(bool(item.get("contact_candidate"))),
230
+ int(item.get("heavy_atom_count", 0)),
231
+ int(item.get("atom_count", 0)),
232
+ -float(item.get("min_distance_to_receptor", math.inf)),
233
+ ),
234
+ reverse=True,
235
+ )
236
+ return viable[0], candidates
237
+
238
+
239
+ def resolve_known_good_defaults(
240
+ config_path: str | Path,
241
+ pdb_id: str,
242
+ receptor_chain: str | None,
243
+ ligand_resname: str | None,
244
+ ligand_chain: str | None,
245
+ ) -> dict[str, str]:
246
+ pdb_upper = pdb_id.upper().strip()
247
+ matches = [item for item in list_known_good_complexes(config_path) if str(item.get("pdb_id", "")).upper() == pdb_upper]
248
+ if not matches:
249
+ return {
250
+ "pdb_id": pdb_upper,
251
+ "receptor_chain": receptor_chain or "",
252
+ "reference_ligand_resname": ligand_resname or "",
253
+ "reference_ligand_chain": ligand_chain or "",
254
+ }
255
+ chosen = matches[0]
256
+ return {
257
+ "pdb_id": pdb_upper,
258
+ "receptor_chain": receptor_chain or str(chosen.get("receptor_chain", "")),
259
+ "reference_ligand_resname": ligand_resname or str(chosen.get("reference_ligand_resname", "")),
260
+ "reference_ligand_chain": ligand_chain or str(chosen.get("reference_ligand_chain", "")),
261
+ }
262
+
263
+
264
+ def download_pdb_structure(pdb_id: str, out_dir: str | Path, force: bool = False) -> Path:
265
+ target_dir = Path(out_dir)
266
+ target_dir.mkdir(parents=True, exist_ok=True)
267
+ pdb_id = pdb_id.upper().strip()
268
+ pdb_path = target_dir / f"{pdb_id.lower()}.pdb"
269
+ if pdb_path.exists() and pdb_path.stat().st_size > 0 and not force:
270
+ return pdb_path
271
+ url = f"https://files.rcsb.org/download/{pdb_id}.pdb"
272
+ try:
273
+ urllib.request.urlretrieve(url, pdb_path)
274
+ except Exception as exc:
275
+ curl = shutil.which("curl")
276
+ if curl:
277
+ proc = subprocess.run(
278
+ [curl, "-fsSL", url, "-o", str(pdb_path)],
279
+ check=False,
280
+ capture_output=True,
281
+ text=True,
282
+ )
283
+ if proc.returncode == 0 and pdb_path.exists() and pdb_path.stat().st_size > 0:
284
+ return require_file(pdb_path, f"downloaded PDB for {pdb_id}")
285
+ raise RDockPipelineError(
286
+ f"Failed to download PDB {pdb_id} from {url}. urllib error: {exc}. "
287
+ f"curl stderr: {proc.stderr.strip() or '<empty>'}. "
288
+ f"Check network access or provide a locally cached PDB in {target_dir}."
289
+ ) from exc
290
+ raise RDockPipelineError(
291
+ f"Failed to download PDB {pdb_id} from {url}: {exc}. "
292
+ "curl is not available for fallback; check network access or pre-stage the PDB file locally."
293
+ ) from exc
294
+ return require_file(pdb_path, f"downloaded PDB for {pdb_id}")
295
+
296
+
297
+ def extract_receptor_and_reference_ligand(
298
+ pdb_like: str | Path,
299
+ receptor_chain: str,
300
+ ligand_resname: str,
301
+ ligand_chain: str,
302
+ out_dir: str | Path,
303
+ min_reference_ligand_atoms: int = 8,
304
+ ) -> tuple[Path, Path, list[dict[str, str]]]:
305
+ source = require_file(pdb_like, "PDB/mmCIF structure")
306
+ out_root = Path(out_dir)
307
+ out_root.mkdir(parents=True, exist_ok=True)
308
+ receptor = out_root / "target_raw.pdb"
309
+ ligand_pdb = out_root / "reference_ligand_raw.pdb"
310
+
311
+ receptor_lines: list[str] = []
312
+ ligand_lines: list[str] = []
313
+ hetero_rows = list_hetero_ligands(source, min_reference_ligand_atoms=min_reference_ligand_atoms)
314
+ receptor_chains = {item.strip() for item in receptor_chain.split(",") if item.strip()}
315
+ wanted_resname = ligand_resname.upper().strip()
316
+ wanted_chain = ligand_chain.strip()
317
+ wanted_keys = {
318
+ (str(item["resname"]), str(item["chain"]), str(item["residue_id"]))
319
+ for item in hetero_rows
320
+ if str(item["resname"]) == wanted_resname and (not wanted_chain or str(item["chain"]) == wanted_chain)
321
+ }
322
+
323
+ for line in source.read_text(encoding="utf-8", errors="ignore").splitlines():
324
+ record = line[:6].strip()
325
+ atom = _parse_pdb_atom_line(line)
326
+ chain = str(atom["chain"])
327
+ resname = str(atom["resname"])
328
+ if record == "ATOM" and (not receptor_chains or chain in receptor_chains):
329
+ receptor_lines.append(line)
330
+ if record == "HETATM":
331
+ key = (resname, chain, str(atom["residue_id"]))
332
+ if key in wanted_keys:
333
+ ligand_lines.append(line)
334
+ if not receptor_lines:
335
+ raise RDockPipelineError(f"No receptor atoms found in {source} for chain(s) {receptor_chain}")
336
+ if not ligand_lines:
337
+ raise RDockPipelineError(
338
+ f"Reference ligand {wanted_resname} chain {wanted_chain or '*'} not found in {source}. "
339
+ f"Available hetero ligands: {hetero_rows[:20]}"
340
+ )
341
+
342
+ receptor.write_text("\n".join(receptor_lines + ["END", ""]), encoding="utf-8")
343
+ ligand_pdb.write_text("\n".join(ligand_lines + ["END", ""]), encoding="utf-8")
344
+ return receptor, ligand_pdb, hetero_rows
345
+
346
+
347
+ def validate_dataset_dir(dataset_dir: str | Path, check_rdock_tools: bool = False) -> dict[str, Any]:
348
+ root = Path(dataset_dir)
349
+ manifest_path = root / "dataset_manifest.json"
350
+ manifest = json.loads(require_file(manifest_path, "dataset manifest").read_text(encoding="utf-8"))
351
+ required = {
352
+ "target_mol2": root / "target" / "target.mol2",
353
+ "reference_ligand_sdf": root / "target" / "reference_ligand.sdf",
354
+ "all_ligands_sdf": root / "ligands" / "all_ligands.sdf",
355
+ "invalid_ligands_csv": root / "ligands" / "invalid_ligands.csv",
356
+ "preparation_report": root / "qc" / "preparation_report.md",
357
+ "target_config": root / "target" / "rdock_prm" / "target_config.yaml",
358
+ }
359
+ for label, path in required.items():
360
+ require_file(path, label)
361
+ ligand_count = count_sdf_records(required["all_ligands_sdf"])
362
+ expected_count = int(manifest.get("ligands_prepared", 0))
363
+ if expected_count and ligand_count != expected_count:
364
+ raise RDockPipelineError(
365
+ f"Ligand count mismatch for {root}: manifest says {expected_count}, SDF contains {ligand_count}"
366
+ )
367
+ ref_count = count_sdf_records(required["reference_ligand_sdf"])
368
+ if ref_count < 1:
369
+ raise RDockPipelineError(f"Reference ligand SDF is empty in {root}")
370
+ target_config = load_target_config(required["target_config"])
371
+ cavity = require_file(target_config.cavity_as, "rDock cavity .as file from dataset")
372
+ if cavity.stat().st_size <= 0:
373
+ raise RDockPipelineError(f"Invalid empty cavity file in dataset: {cavity}")
374
+ ligand_source = str(manifest.get("ligand_source", ""))
375
+ if ligand_source.startswith("pubchem"):
376
+ require_file(root / "logs" / "pubchem_diagnostics.json", "PubChem diagnostics log")
377
+ tools: dict[str, str] = {}
378
+ if check_rdock_tools:
379
+ tools = {
380
+ "rbdock": probe_version(require_executable("rbdock")),
381
+ "rbcavity": probe_version(require_executable("rbcavity")),
382
+ "obabel": probe_version(require_executable("obabel")),
383
+ }
384
+ return {
385
+ "dataset_dir": str(root),
386
+ "manifest": manifest,
387
+ "ligand_count": ligand_count,
388
+ "reference_records": ref_count,
389
+ "target_config": str(required["target_config"]),
390
+ "executables": tools,
391
+ }
392
+
393
+
394
+ def create_dataset_manifest(
395
+ dataset_dir: str | Path,
396
+ payload: dict[str, Any],
397
+ ) -> Path:
398
+ root = Path(dataset_dir)
399
+ payload = dict(payload)
400
+ payload["created_at"] = datetime.now(UTC).isoformat()
401
+ return dump_json_like(root / "dataset_manifest.json", payload)
402
+
403
+
404
+ def copy_prepared_target_bundle(target_config_dir: str | Path, dataset_target_dir: str | Path) -> dict[str, str]:
405
+ src = Path(target_config_dir)
406
+ dst = Path(dataset_target_dir)
407
+ dst.mkdir(parents=True, exist_ok=True)
408
+ copied: dict[str, str] = {}
409
+ for path in src.iterdir():
410
+ if path.is_file():
411
+ shutil.copy2(path, dst / path.name)
412
+ copied[path.name] = str(dst / path.name)
413
+ return copied
414
+
415
+
416
+ def prepare_dataset_target_with_rdock(
417
+ receptor_pdb: str | Path,
418
+ reference_ligand_sdf: str | Path,
419
+ out_dir: str | Path,
420
+ jobs: int | str = "auto",
421
+ cpu_fraction: float = 0.85,
422
+ ) -> dict[str, Any]:
423
+ engine = RDockEngine(RDockRunConfig(jobs=jobs, cpu_fraction=cpu_fraction))
424
+ target_config = engine.prepare_target(receptor_pdb, reference_ligand_sdf, out_dir)
425
+ return {
426
+ "target_config_yaml": str(Path(out_dir) / "target_config.yaml"),
427
+ "target_config": target_config.__dict__,
428
+ }
429
+
430
+
431
+ def read_ligand_metadata(path: str | Path) -> list[dict[str, str]]:
432
+ with require_file(path, "ligand metadata CSV").open("r", encoding="utf-8", newline="") as handle:
433
+ return list(csv.DictReader(handle))
docking_pipeline/metrics.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import json
5
+ import csv
6
+ from pathlib import Path
7
+
8
+
9
+ def roc_auc(scores: list[float], labels: list[int]) -> float:
10
+ pairs = [(float(s), int(y)) for s, y in zip(scores, labels)]
11
+ pos = [s for s, y in pairs if y == 1]
12
+ neg = [s for s, y in pairs if y == 0]
13
+ if not pos or not neg:
14
+ return float("nan")
15
+ wins = 0.0
16
+ for p in pos:
17
+ wins += sum(1.0 for n in neg if p < n)
18
+ wins += 0.5 * sum(1.0 for n in neg if p == n)
19
+ return float(wins / (len(pos) * len(neg)))
20
+
21
+
22
+ def enrichment_factor(scores: list[float], labels: list[int], fraction: float) -> float:
23
+ pairs = [(float(s), int(y)) for s, y in zip(scores, labels)]
24
+ n = len(pairs)
25
+ total_actives = sum(y for _, y in pairs)
26
+ if n == 0 or total_actives == 0:
27
+ return float("nan")
28
+ k = max(1, int(math.ceil(n * fraction)))
29
+ top = sorted(pairs, key=lambda item: item[0])[:k]
30
+ hit_rate_top = float(sum(y for _, y in top)) / float(k)
31
+ hit_rate_all = float(total_actives) / float(n)
32
+ return float(hit_rate_top / hit_rate_all) if hit_rate_all > 0 else float("nan")
33
+
34
+
35
+ def bedroc(scores: list[float], labels: list[int], alpha: float = 20.0) -> float:
36
+ pairs = sorted([(float(s), int(y)) for s, y in zip(scores, labels)], key=lambda item: item[0])
37
+ n = len(pairs)
38
+ n_act = sum(y for _, y in pairs)
39
+ if n == 0 or n_act == 0 or n_act == n:
40
+ return float("nan")
41
+ ranks = [idx + 1 for idx, (_, y) in enumerate(pairs) if y == 1]
42
+ denom = (1 - math.exp(-alpha)) / (math.exp(alpha / n) - 1)
43
+ rie = (n / n_act) * sum(math.exp(-alpha * rank / n) for rank in ranks) / denom
44
+ rie_min = (n / n_act) * sum(math.exp(-alpha * rank / n) for rank in range(n - n_act + 1, n + 1)) / denom
45
+ rie_max = (n / n_act) * sum(math.exp(-alpha * rank / n) for rank in range(1, n_act + 1)) / denom
46
+ return float((rie - rie_min) / (rie_max - rie_min))
47
+
48
+
49
+ def enrichment_rows(scores: list[float], labels: list[int]) -> list[dict[str, float]]:
50
+ rows = []
51
+ for frac in (0.01, 0.05, 0.10, 0.20):
52
+ rows.append({"fraction": frac, "enrichment_factor": enrichment_factor(scores, labels, frac)})
53
+ return rows
54
+
55
+
56
+ def validation_metrics_from_rows(rows: list[dict[str, object]], score_col: str = "SCORE", label_col: str = "label") -> dict[str, float]:
57
+ scores = [float(row[score_col]) for row in rows]
58
+ labels = [int(float(row.get(label_col, 0) or 0)) for row in rows]
59
+ return {
60
+ "roc_auc": roc_auc(scores, labels),
61
+ "ef1": enrichment_factor(scores, labels, 0.01),
62
+ "ef5": enrichment_factor(scores, labels, 0.05),
63
+ "ef10": enrichment_factor(scores, labels, 0.10),
64
+ "ef20": enrichment_factor(scores, labels, 0.20),
65
+ "bedroc20": bedroc(scores, labels, alpha=20.0),
66
+ }
67
+
68
+
69
+ def write_metrics(rows: list[dict[str, object]], metrics_json: str | Path, enrichment_csv: str | Path) -> dict[str, float]:
70
+ metrics = validation_metrics_from_rows(rows)
71
+ Path(metrics_json).parent.mkdir(parents=True, exist_ok=True)
72
+ Path(metrics_json).write_text(json.dumps(metrics, indent=2), encoding="utf-8")
73
+ scores = [float(row["SCORE"]) for row in rows]
74
+ labels = [int(float(row.get("label", 0) or 0)) for row in rows]
75
+ with Path(enrichment_csv).open("w", encoding="utf-8", newline="") as handle:
76
+ writer = csv.DictWriter(handle, fieldnames=["fraction", "enrichment_factor"])
77
+ writer.writeheader()
78
+ writer.writerows(enrichment_rows(scores, labels))
79
+ return metrics
80
+
81
+
82
+ validation_metrics_from_table = validation_metrics_from_rows
83
+ enrichment_table = enrichment_rows
docking_pipeline/provenance.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ from dataclasses import asdict, dataclass
9
+ from datetime import UTC, datetime
10
+ from pathlib import Path
11
+ from typing import Sequence
12
+
13
+
14
+ class RDockPipelineError(RuntimeError):
15
+ """Raised for actionable pipeline failures."""
16
+
17
+
18
+ def sha256_file(path: str | Path) -> str:
19
+ source = Path(path)
20
+ h = hashlib.sha256()
21
+ with source.open("rb") as handle:
22
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
23
+ h.update(chunk)
24
+ return h.hexdigest()
25
+
26
+
27
+ def require_file(path: str | Path, label: str) -> Path:
28
+ p = Path(path)
29
+ if not p.exists():
30
+ raise RDockPipelineError(f"Missing {label}: {p}")
31
+ if p.is_file() and p.stat().st_size == 0:
32
+ raise RDockPipelineError(f"Empty {label}: {p}")
33
+ return p
34
+
35
+
36
+ def require_executable(name: str) -> str:
37
+ resolved = shutil.which(name)
38
+ if not resolved:
39
+ raise RDockPipelineError(
40
+ f"Required executable `{name}` was not found on PATH. Install rDock/OpenBabel "
41
+ "and ensure RBT_ROOT/RBT_HOME/library paths are configured before running."
42
+ )
43
+ return resolved
44
+
45
+
46
+ def probe_version(executable: str) -> str:
47
+ for args in ([executable, "--version"], [executable, "-version"], [executable, "-h"]):
48
+ try:
49
+ proc = subprocess.run(args, check=False, capture_output=True, text=True, timeout=10)
50
+ except Exception:
51
+ continue
52
+ text = "\n".join([proc.stdout or "", proc.stderr or ""]).strip()
53
+ if text:
54
+ for line in text.splitlines():
55
+ probe = line.strip()
56
+ if probe and set(probe) != {"*"}:
57
+ return probe[:240]
58
+ return text.splitlines()[0][:240]
59
+ return "unavailable"
60
+
61
+
62
+ @dataclass
63
+ class CommandRecord:
64
+ stage: str
65
+ command: list[str]
66
+ cwd: str
67
+ start_time: str
68
+ end_time: str
69
+ exit_code: int
70
+ stdout_log: str
71
+ stderr_log: str
72
+
73
+ def to_dict(self) -> dict[str, object]:
74
+ return asdict(self)
75
+
76
+
77
+ class CommandRunner:
78
+ def __init__(self, command_log: str | Path) -> None:
79
+ self.command_log = Path(command_log)
80
+ self.command_log.parent.mkdir(parents=True, exist_ok=True)
81
+ self.records: list[CommandRecord] = []
82
+
83
+ def run(
84
+ self,
85
+ stage: str,
86
+ command: Sequence[str],
87
+ cwd: str | Path,
88
+ stdout_log: str | Path,
89
+ stderr_log: str | Path,
90
+ timeout: int | None = None,
91
+ env: dict[str, str] | None = None,
92
+ ) -> CommandRecord:
93
+ cwd_path = Path(cwd)
94
+ stdout_path = Path(stdout_log)
95
+ stderr_path = Path(stderr_log)
96
+ stdout_path.parent.mkdir(parents=True, exist_ok=True)
97
+ stderr_path.parent.mkdir(parents=True, exist_ok=True)
98
+ start = datetime.now(UTC).isoformat()
99
+ merged_env = os.environ.copy()
100
+ if env:
101
+ merged_env.update(env)
102
+ try:
103
+ proc = subprocess.run(
104
+ list(command),
105
+ cwd=str(cwd_path),
106
+ check=False,
107
+ capture_output=True,
108
+ text=True,
109
+ timeout=timeout,
110
+ env=merged_env,
111
+ )
112
+ stdout = proc.stdout or ""
113
+ stderr = proc.stderr or ""
114
+ rc = int(proc.returncode)
115
+ except subprocess.TimeoutExpired as exc:
116
+ stdout = exc.stdout if isinstance(exc.stdout, str) else ""
117
+ stderr = (exc.stderr if isinstance(exc.stderr, str) else "") + f"\nTIMEOUT after {timeout}s"
118
+ rc = 124
119
+ end = datetime.now(UTC).isoformat()
120
+ stdout_path.write_text(stdout, encoding="utf-8")
121
+ stderr_path.write_text(stderr, encoding="utf-8")
122
+ rec = CommandRecord(
123
+ stage=stage,
124
+ command=list(command),
125
+ cwd=str(cwd_path),
126
+ start_time=start,
127
+ end_time=end,
128
+ exit_code=rc,
129
+ stdout_log=str(stdout_path),
130
+ stderr_log=str(stderr_path),
131
+ )
132
+ self.records.append(rec)
133
+ with self.command_log.open("a", encoding="utf-8") as handle:
134
+ handle.write(json.dumps(rec.to_dict(), sort_keys=True) + "\n")
135
+ return rec
136
+
137
+
138
+ def fail_if_bad_command(record: CommandRecord, expected: str) -> None:
139
+ stdout = Path(record.stdout_log).read_text(encoding="utf-8", errors="ignore") if record.stdout_log else ""
140
+ stderr = Path(record.stderr_log).read_text(encoding="utf-8", errors="ignore") if record.stderr_log else ""
141
+ text = f"{stdout}\n{stderr}"
142
+ error_markers = (
143
+ "RBT_FILE_READ_ERROR",
144
+ "RBT_ERROR",
145
+ "BAD_RECEPTOR_FILE",
146
+ "Error opening",
147
+ "Segmentation fault",
148
+ "Fatal",
149
+ )
150
+ if record.exit_code == 0 and not any(marker.lower() in text.lower() for marker in error_markers):
151
+ return
152
+ raise RDockPipelineError(
153
+ f"{expected} failed with exit code {record.exit_code}. Command: {' '.join(record.command)}. "
154
+ f"See stdout log: {record.stdout_log}; stderr log: {record.stderr_log}. "
155
+ f"Last diagnostic: {text.strip()[-1200:]}"
156
+ )
docking_pipeline/rdock.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import os
6
+ import shutil
7
+ from concurrent.futures import ThreadPoolExecutor, as_completed
8
+ from dataclasses import asdict, dataclass, field
9
+ from datetime import UTC, datetime
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from .provenance import (
14
+ CommandRecord,
15
+ CommandRunner,
16
+ RDockPipelineError,
17
+ fail_if_bad_command,
18
+ probe_version,
19
+ require_executable,
20
+ require_file,
21
+ sha256_file,
22
+ )
23
+ from .sdf import best_per_ligand, parse_rdock_sdf_records, records_to_rows, split_sdf_file, write_rows_csv, write_sdf_blocks, write_sdf_records
24
+
25
+
26
+ @dataclass
27
+ class TargetConfig:
28
+ receptor: str
29
+ reference_ligand: str
30
+ target_dir: str
31
+ receptor_mol2: str
32
+ receptor_prm: str
33
+ cavity_as: str
34
+ pocket_center: list[float]
35
+ pocket_radius: float
36
+ diagnostics: dict[str, Any]
37
+
38
+
39
+ @dataclass
40
+ class RDockRunConfig:
41
+ n_runs: int = 50
42
+ jobs: int | str = "auto"
43
+ cpu_fraction: float = 0.85
44
+ timeout_seconds: int = 3600
45
+ rbdock_bin: str = "rbdock"
46
+ rbcavity_bin: str = "rbcavity"
47
+ obabel_bin: str = "obabel"
48
+ sdsort_bin: str = "sdsort"
49
+ sdfilter_bin: str = "sdfilter"
50
+ sdreport_bin: str = "sdreport"
51
+ sdrmsd_bin: str = "sdrmsd"
52
+ sdsplit_bin: str = "sdsplit"
53
+ dock_prm: str | None = None
54
+ rbt_root: str | None = None
55
+ require_reporting_tools: bool = False
56
+
57
+
58
+ @dataclass
59
+ class RunArtifacts:
60
+ run_dir: str
61
+ manifest: str
62
+ config_yaml: str
63
+ commands_log: str
64
+ all_poses_sdf: str
65
+ best_per_ligand_sdf: str
66
+ scores_long_csv: str
67
+ best_per_ligand_csv: str
68
+ report_md: str
69
+ command_records: list[dict[str, Any]] = field(default_factory=list)
70
+ best_ligand_poses_sdf: str | None = None
71
+
72
+
73
+ def _write_yaml_like(path: Path, payload: dict[str, Any]) -> None:
74
+ try:
75
+ import yaml
76
+
77
+ text = yaml.safe_dump(payload, sort_keys=False)
78
+ except Exception:
79
+ text = json.dumps(payload, indent=2)
80
+ path.write_text(text, encoding="utf-8")
81
+
82
+
83
+ def _coords_from_pdb(path: Path, include_hetatm: bool) -> np.ndarray:
84
+ coords: list[list[float]] = []
85
+ for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
86
+ if not line.startswith(("ATOM", "HETATM")):
87
+ continue
88
+ if line.startswith("HETATM") and not include_hetatm:
89
+ continue
90
+ try:
91
+ coords.append([float(line[30:38]), float(line[38:46]), float(line[46:54])])
92
+ except Exception:
93
+ continue
94
+ return coords # type: ignore[return-value]
95
+
96
+
97
+ def _coords_from_mol2(path: Path) -> np.ndarray:
98
+ coords: list[list[float]] = []
99
+ in_atoms = False
100
+ for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
101
+ if line.startswith("@<TRIPOS>ATOM"):
102
+ in_atoms = True
103
+ continue
104
+ if line.startswith("@<TRIPOS>") and in_atoms:
105
+ break
106
+ if not in_atoms:
107
+ continue
108
+ parts = line.split()
109
+ if len(parts) >= 5:
110
+ try:
111
+ coords.append([float(parts[2]), float(parts[3]), float(parts[4])])
112
+ except Exception:
113
+ continue
114
+ return coords # type: ignore[return-value]
115
+
116
+
117
+ def _coords_from_sdf(path: Path) -> np.ndarray:
118
+ first = path.read_text(encoding="utf-8", errors="ignore").split("$$$$", 1)[0]
119
+ lines = first.splitlines()
120
+ if len(lines) < 4:
121
+ return [] # type: ignore[return-value]
122
+ try:
123
+ atom_count = int(lines[3][0:3])
124
+ except Exception:
125
+ atom_count = 0
126
+ coords = []
127
+ for line in lines[4 : 4 + atom_count]:
128
+ try:
129
+ coords.append([float(line[0:10]), float(line[10:20]), float(line[20:30])])
130
+ except Exception:
131
+ parts = line.split()
132
+ if len(parts) >= 3:
133
+ try:
134
+ coords.append([float(parts[0]), float(parts[1]), float(parts[2])])
135
+ except Exception:
136
+ continue
137
+ return coords # type: ignore[return-value]
138
+
139
+
140
+ def _coords_for_structure(path: Path, receptor: bool) -> np.ndarray:
141
+ suffix = path.suffix.lower()
142
+ if suffix == ".mol2":
143
+ return _coords_from_mol2(path)
144
+ if suffix in {".sdf", ".sd"}:
145
+ return _coords_from_sdf(path)
146
+ if suffix in {".pdb", ".ent", ".cif", ".mmcif"}:
147
+ return _coords_from_pdb(path, include_hetatm=not receptor)
148
+ raise RDockPipelineError(f"Unsupported structure format for coordinate validation: {path}")
149
+
150
+
151
+ def _validate_receptor_ligand_geometry(receptor: Path, ligand: Path) -> tuple[list[float], dict[str, Any]]:
152
+ receptor_coords = _coords_for_structure(receptor, receptor=True)
153
+ ligand_coords = _coords_for_structure(ligand, receptor=False)
154
+ if not receptor_coords:
155
+ raise RDockPipelineError(f"Missing receptor atoms or coordinates in {receptor}")
156
+ if not ligand_coords:
157
+ raise RDockPipelineError(f"Missing ligand coordinates in reference ligand {ligand}")
158
+ n_lig = len(ligand_coords)
159
+ center = [sum(coord[i] for coord in ligand_coords) / n_lig for i in range(3)]
160
+
161
+ def dist(a: list[float], b: list[float]) -> float:
162
+ return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2) ** 0.5
163
+
164
+ all_dists = [dist(r, l) for r in receptor_coords for l in ligand_coords]
165
+ min_receptor_ligand_dist = min(all_dists)
166
+ centroid_to_receptor = min(dist(r, center) for r in receptor_coords)
167
+ severe_clashes = sum(1 for d in all_dists if d < 1.0)
168
+ clash_fraction = severe_clashes / float(max(1, len(ligand_coords)))
169
+ if centroid_to_receptor > 20.0:
170
+ raise RDockPipelineError(
171
+ f"Reference ligand centroid is {centroid_to_receptor:.2f} A from the nearest receptor atom; "
172
+ "check receptor/reference ligand pairing and coordinate frames."
173
+ )
174
+ if clash_fraction > 1.0:
175
+ raise RDockPipelineError(
176
+ f"Severe receptor-ligand clashes before docking ({severe_clashes} atom pairs < 1.0 A). "
177
+ "Check protonation, alternate locations, and coordinate consistency."
178
+ )
179
+ spread = max(dist(l, center) for l in ligand_coords)
180
+ return [float(center[0]), float(center[1]), float(center[2])], {
181
+ "receptor_atom_count": int(len(receptor_coords)),
182
+ "reference_ligand_atom_count": int(len(ligand_coords)),
183
+ "reference_ligand_centroid": [float(x) for x in center],
184
+ "reference_ligand_radius": spread,
185
+ "min_receptor_ligand_distance": min_receptor_ligand_dist,
186
+ "reference_centroid_to_nearest_receptor_atom": centroid_to_receptor,
187
+ "severe_clash_pairs_lt_1A": severe_clashes,
188
+ }
189
+
190
+
191
+ class RDockEngine:
192
+ def __init__(self, config: RDockRunConfig | None = None) -> None:
193
+ self.config = config or RDockRunConfig()
194
+
195
+ def _env(self) -> dict[str, str]:
196
+ env: dict[str, str] = {}
197
+ if self.config.rbt_root:
198
+ env["RBT_ROOT"] = self.config.rbt_root
199
+ elif os.environ.get("RBT_ROOT"):
200
+ env["RBT_ROOT"] = str(os.environ["RBT_ROOT"])
201
+ else:
202
+ for candidate in (Path("/opt/homebrew/opt/rdock/share"), Path("/usr/local/opt/rdock/share")):
203
+ if (candidate / "data" / "RbtElements.dat").exists():
204
+ env["RBT_ROOT"] = str(candidate)
205
+ break
206
+ if "RBT_ROOT" not in env:
207
+ cellar = Path("/opt/homebrew/Cellar/rdock")
208
+ if cellar.exists():
209
+ for candidate in sorted(cellar.glob("*/share"), reverse=True):
210
+ if (candidate / "data" / "RbtElements.dat").exists():
211
+ env["RBT_ROOT"] = str(candidate)
212
+ break
213
+ return env
214
+
215
+ def _dock_prm(self) -> Path:
216
+ if self.config.dock_prm:
217
+ return require_file(self.config.dock_prm, "rDock protocol dock.prm")
218
+ rbt_root = self.config.rbt_root or os.environ.get("RBT_ROOT")
219
+ candidates = []
220
+ if rbt_root:
221
+ candidates.append(Path(rbt_root) / "data" / "scripts" / "dock.prm")
222
+ candidates.append(Path(rbt_root) / "data" / "dock.prm")
223
+ candidates.extend(
224
+ [
225
+ Path("/opt/homebrew/opt/rdock/share/data/scripts/dock.prm"),
226
+ Path("/usr/local/opt/rdock/share/data/scripts/dock.prm"),
227
+ ]
228
+ )
229
+ cellar = Path("/opt/homebrew/Cellar/rdock")
230
+ if cellar.exists():
231
+ candidates.extend(sorted(cellar.glob("*/share/data/scripts/dock.prm"), reverse=True))
232
+ candidates.append(Path("dock.prm"))
233
+ for candidate in candidates:
234
+ if candidate.exists() and candidate.stat().st_size > 0:
235
+ return candidate.resolve()
236
+ raise RDockPipelineError(
237
+ "Could not locate rDock dock.prm. Pass --dock-prm or set RBT_ROOT so "
238
+ "$RBT_ROOT/data/scripts/dock.prm exists."
239
+ )
240
+
241
+ def check_required_tools(self, validation: bool = False) -> dict[str, str]:
242
+ needed = {
243
+ "rbdock": self.config.rbdock_bin,
244
+ "rbcavity": self.config.rbcavity_bin,
245
+ "obabel": self.config.obabel_bin,
246
+ }
247
+ if validation or self.config.require_reporting_tools:
248
+ needed.update(
249
+ {
250
+ "sdsort": self.config.sdsort_bin,
251
+ "sdfilter": self.config.sdfilter_bin,
252
+ "sdreport": self.config.sdreport_bin,
253
+ "sdrmsd": self.config.sdrmsd_bin,
254
+ }
255
+ )
256
+ return {key: require_executable(bin_name) for key, bin_name in needed.items()}
257
+
258
+ def prepare_target(self, receptor: str | Path, reference_ligand: str | Path, out_dir: str | Path) -> TargetConfig:
259
+ tools = self.check_required_tools(validation=False)
260
+ receptor_path = require_file(receptor, "receptor structure")
261
+ ref_path = require_file(reference_ligand, "reference ligand")
262
+ out = Path(out_dir)
263
+ out.mkdir(parents=True, exist_ok=True)
264
+ command_log = out / "commands.log"
265
+ runner = CommandRunner(command_log)
266
+
267
+ receptor_copy = out / receptor_path.name
268
+ reference_copy = out / ref_path.name
269
+ if receptor_path.resolve() != receptor_copy.resolve():
270
+ shutil.copy2(receptor_path, receptor_copy)
271
+ if ref_path.resolve() != reference_copy.resolve():
272
+ shutil.copy2(ref_path, reference_copy)
273
+
274
+ center, diagnostics = _validate_receptor_ligand_geometry(receptor_copy, reference_copy)
275
+ receptor_mol2 = out / "receptor.mol2"
276
+ if receptor_copy.suffix.lower() == ".mol2":
277
+ shutil.copy2(receptor_copy, receptor_mol2)
278
+ else:
279
+ rec = runner.run(
280
+ "prepare_receptor_obabel",
281
+ [tools["obabel"], str(receptor_copy.resolve()), "-O", str(receptor_mol2.resolve())],
282
+ cwd=out,
283
+ stdout_log=out / "prepare_receptor_obabel.stdout.log",
284
+ stderr_log=out / "prepare_receptor_obabel.stderr.log",
285
+ timeout=300,
286
+ env=self._env(),
287
+ )
288
+ fail_if_bad_command(rec, "OpenBabel receptor conversion")
289
+ require_file(receptor_mol2, "prepared receptor MOL2")
290
+
291
+ prm = out / "receptor.prm"
292
+ prm.write_text(
293
+ "\n".join(
294
+ [
295
+ "RBT_PARAMETER_FILE_V1.00",
296
+ "TITLE rdock_receptor_reference_ligand",
297
+ f"RECEPTOR_FILE {receptor_mol2.resolve()}",
298
+ "",
299
+ "SECTION MAPPER",
300
+ " SITE_MAPPER RbtLigandSiteMapper",
301
+ f" REF_MOL {reference_copy.resolve()}",
302
+ " RADIUS 6.0",
303
+ " SMALL_SPHERE 1.5",
304
+ "END_SECTION",
305
+ "",
306
+ "SECTION CAVITY",
307
+ " SCORING_FUNCTION RbtCavityGridSF",
308
+ "END_SECTION",
309
+ "",
310
+ ]
311
+ ),
312
+ encoding="utf-8",
313
+ )
314
+
315
+ rec = runner.run(
316
+ "rbcavity",
317
+ [tools["rbcavity"], "-r", prm.name, "-was"],
318
+ cwd=out,
319
+ stdout_log=out / "rbcavity.stdout.log",
320
+ stderr_log=out / "rbcavity.stderr.log",
321
+ timeout=self.config.timeout_seconds,
322
+ env=self._env(),
323
+ )
324
+ fail_if_bad_command(rec, "rbcavity cavity generation")
325
+ cavity = out / f"{prm.stem}.as"
326
+ require_file(cavity, "rDock cavity .as file")
327
+ if cavity.stat().st_size < 16:
328
+ raise RDockPipelineError(f"rbcavity produced an invalid tiny cavity file: {cavity}")
329
+
330
+ target_config = TargetConfig(
331
+ receptor=str(receptor_copy),
332
+ reference_ligand=str(reference_copy),
333
+ target_dir=str(out),
334
+ receptor_mol2=str(receptor_mol2),
335
+ receptor_prm=str(prm),
336
+ cavity_as=str(cavity),
337
+ pocket_center=center,
338
+ pocket_radius=float(max(6.0, diagnostics["reference_ligand_radius"] + 2.0)),
339
+ diagnostics=diagnostics,
340
+ )
341
+ _write_yaml_like(out / "target_config.yaml", asdict(target_config))
342
+ return target_config
343
+
344
+ def _resolve_jobs(self, requested: int | str | None = None) -> int:
345
+ value = self.config.jobs if requested is None else requested
346
+ if isinstance(value, str) and value.lower() == "auto":
347
+ cpus = os.cpu_count() or 1
348
+ reserve = 1 if cpus <= 4 else 2
349
+ return max(1, min(cpus - reserve, int(math.floor(cpus * self.config.cpu_fraction))))
350
+ return max(1, int(value))
351
+
352
+ def _split_input_sdf(self, ligands_sdf: Path, split_dir: Path, jobs: int) -> list[Path]:
353
+ blocks = split_sdf_file(ligands_sdf)
354
+ if jobs <= 1 or len(blocks) <= 1:
355
+ target = split_dir / "chunk_000.sdf"
356
+ write_sdf_blocks(blocks, target)
357
+ return [target]
358
+ chunks: list[list[str]] = [[] for _ in range(min(jobs, len(blocks)))]
359
+ for idx, block in enumerate(blocks):
360
+ chunks[idx % len(chunks)].append(block)
361
+ paths = []
362
+ for idx, chunk in enumerate(chunks):
363
+ path = split_dir / f"chunk_{idx:03d}.sdf"
364
+ write_sdf_blocks(chunk, path)
365
+ paths.append(path)
366
+ return paths
367
+
368
+ def dock_sdf(
369
+ self,
370
+ target_config: TargetConfig,
371
+ ligands_sdf: str | Path,
372
+ run_dir: str | Path,
373
+ n_runs: int | None = None,
374
+ jobs: int | str | None = None,
375
+ run_id: str | None = None,
376
+ validation_labels_csv: str | Path | None = None,
377
+ resume: bool = False,
378
+ ) -> RunArtifacts:
379
+ self.check_required_tools(validation=False)
380
+ ligands = require_file(ligands_sdf, "ligand SDF")
381
+ dock_prm = self._dock_prm()
382
+ run_root = Path(run_dir)
383
+ run_root.mkdir(parents=True, exist_ok=True)
384
+ for name in ("target", "ligands", "rdock", "poses", "tables", "metrics"):
385
+ (run_root / name).mkdir(parents=True, exist_ok=True)
386
+ commands_log = run_root / "commands.log"
387
+ runner = CommandRunner(commands_log)
388
+
389
+ target_dir = run_root / "target"
390
+ for src in (target_config.receptor, target_config.reference_ligand, target_config.receptor_mol2, target_config.receptor_prm, target_config.cavity_as):
391
+ p = Path(src)
392
+ if p.exists():
393
+ shutil.copy2(p, target_dir / p.name)
394
+ lig_copy = run_root / "ligands" / ligands.name
395
+ if ligands.resolve() != lig_copy.resolve():
396
+ shutil.copy2(ligands, lig_copy)
397
+ shutil.copy2(dock_prm, run_root / "rdock" / "dock.prm")
398
+
399
+ resolved_jobs = self._resolve_jobs(jobs)
400
+ actual_n_runs = int(n_runs if n_runs is not None else self.config.n_runs)
401
+ chunks = self._split_input_sdf(lig_copy, run_root / "rdock" / "chunks", resolved_jobs)
402
+ rbdock = require_executable(self.config.rbdock_bin)
403
+ prm = Path(target_config.receptor_prm).resolve()
404
+ out_files: dict[int, Path] = {}
405
+
406
+ def _run_chunk(idx: int, chunk: Path) -> tuple[int, CommandRecord, Path]:
407
+ out_prefix = run_root / "rdock" / f"chunk_{idx:03d}_out"
408
+ out_sd = out_prefix.with_suffix(".sd")
409
+ if resume and out_sd.exists() and out_sd.stat().st_size > 0:
410
+ rec = CommandRecord(
411
+ stage=f"rbdock_chunk_{idx:03d}_resume",
412
+ command=[rbdock, "-r", str(prm), "-p", str(dock_prm.resolve()), "-n", str(actual_n_runs), "-i", str(chunk.resolve()), "-o", str(out_prefix.resolve())],
413
+ cwd=str(run_root / "rdock"),
414
+ start_time=datetime.now(UTC).isoformat(),
415
+ end_time=datetime.now(UTC).isoformat(),
416
+ exit_code=0,
417
+ stdout_log=str(run_root / "rdock" / f"chunk_{idx:03d}.stdout.log"),
418
+ stderr_log=str(run_root / "rdock" / f"chunk_{idx:03d}.stderr.log"),
419
+ )
420
+ return idx, rec, out_sd
421
+ rec = runner.run(
422
+ f"rbdock_chunk_{idx:03d}",
423
+ [
424
+ rbdock,
425
+ "-r",
426
+ str(prm),
427
+ "-p",
428
+ str(dock_prm.resolve()),
429
+ "-n",
430
+ str(actual_n_runs),
431
+ "-i",
432
+ str(chunk.resolve()),
433
+ "-o",
434
+ str(out_prefix.resolve()),
435
+ ],
436
+ cwd=run_root / "rdock",
437
+ stdout_log=run_root / "rdock" / f"chunk_{idx:03d}.stdout.log",
438
+ stderr_log=run_root / "rdock" / f"chunk_{idx:03d}.stderr.log",
439
+ timeout=self.config.timeout_seconds,
440
+ env=self._env(),
441
+ )
442
+ return idx, rec, out_sd
443
+
444
+ with ThreadPoolExecutor(max_workers=min(resolved_jobs, len(chunks))) as pool:
445
+ futures = [pool.submit(_run_chunk, idx, chunk) for idx, chunk in enumerate(chunks)]
446
+ for fut in as_completed(futures):
447
+ idx, rec, out_sd = fut.result()
448
+ fail_if_bad_command(rec, f"rbdock chunk {idx}")
449
+ require_file(out_sd, f"rDock output SDF for chunk {idx}")
450
+ out_files[idx] = out_sd
451
+
452
+ all_blocks: list[str] = []
453
+ for idx in sorted(out_files):
454
+ all_blocks.extend(split_sdf_file(out_files[idx]))
455
+ all_poses = run_root / "poses" / "all_poses.sdf"
456
+ write_sdf_blocks(all_blocks, all_poses)
457
+ records = parse_rdock_sdf_records(all_poses, require_score=True)
458
+ best = best_per_ligand(records)
459
+ best_sdf = write_sdf_records(best, run_root / "poses" / "best_per_ligand.sdf")
460
+ best_ligand_poses_sdf: str | None = None
461
+ if best:
462
+ top_ligand_id = best[0].ligand_id
463
+ best_ligand_records = [rec for rec in records if rec.ligand_id == top_ligand_id]
464
+ best_ligand_path = run_root / "poses" / f"best_ligand_{actual_n_runs}.sdf"
465
+ write_sdf_records(best_ligand_records, best_ligand_path)
466
+ best_ligand_poses_sdf = str(best_ligand_path)
467
+ scores_long = write_rows_csv(records_to_rows(records), run_root / "tables" / "scores_long.csv")
468
+ best_csv = write_rows_csv(records_to_rows(best), run_root / "tables" / "best_per_ligand.csv")
469
+
470
+ labels_map: dict[str, int] = {}
471
+ if validation_labels_csv:
472
+ import pandas as pd
473
+
474
+ label_df = pd.read_csv(validation_labels_csv)
475
+ labels_map = dict(zip(label_df["ligand_id"].astype(str), label_df["label"].astype(int)))
476
+ best_rows = records_to_rows(best)
477
+ for row in best_rows:
478
+ row["label"] = labels_map.get(str(row["ligand_id"]), 0)
479
+ best_csv = write_rows_csv(best_rows, best_csv)
480
+
481
+ manifest_path = run_root / "manifest.json"
482
+ config_yaml = run_root / "config.yaml"
483
+ report_md = run_root / "report.md"
484
+ now = datetime.now(UTC).isoformat()
485
+ file_inputs = {
486
+ "ligands_sdf": str(lig_copy),
487
+ "dock_prm": str(run_root / "rdock" / "dock.prm"),
488
+ "receptor_prm": str(target_config.receptor_prm),
489
+ "cavity_as": str(target_config.cavity_as),
490
+ }
491
+ manifest = {
492
+ "run_id": run_id or run_root.name,
493
+ "created_at": now,
494
+ "engine": "real-rdock",
495
+ "n_runs": actual_n_runs,
496
+ "jobs": resolved_jobs,
497
+ "input_hashes": {k: sha256_file(v) for k, v in file_inputs.items() if Path(v).exists()},
498
+ "rdock_versions": {
499
+ "rbdock": probe_version(rbdock),
500
+ "rbcavity": probe_version(require_executable(self.config.rbcavity_bin)),
501
+ },
502
+ "target_config": asdict(target_config),
503
+ "commands": [r.to_dict() for r in runner.records],
504
+ "artifacts": {
505
+ "all_poses_sdf": str(all_poses),
506
+ "best_per_ligand_sdf": str(best_sdf),
507
+ "best_ligand_poses_sdf": best_ligand_poses_sdf,
508
+ "scores_long_csv": str(scores_long),
509
+ "best_per_ligand_csv": str(best_csv),
510
+ "commands_log": str(commands_log),
511
+ },
512
+ "pose_count": len(records),
513
+ "docked_ligand_count": len(best),
514
+ }
515
+ manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
516
+ _write_yaml_like(config_yaml, {"rdock": asdict(self.config), "run": {"n_runs": actual_n_runs, "jobs": resolved_jobs}})
517
+ report_md.write_text(
518
+ "\n".join(
519
+ [
520
+ "# rDock Run Report",
521
+ "",
522
+ f"- Engine: `real-rdock`",
523
+ f"- Run ID: `{manifest['run_id']}`",
524
+ f"- n_runs per ligand: `{actual_n_runs}`",
525
+ f"- local jobs: `{resolved_jobs}`",
526
+ f"- poses parsed: `{len(records)}`",
527
+ f"- docked ligands: `{len(best)}`",
528
+ f"- all poses: `{all_poses}`",
529
+ f"- best per ligand: `{best_sdf}`",
530
+ f"- best ligand all poses: `{best_ligand_poses_sdf or ''}`",
531
+ f"- command log: `{commands_log}`",
532
+ "",
533
+ "No surrogate or undocked ligand is reported as a real rDock hit; hit tables are generated only from parsed rDock SDF records with native SCORE fields.",
534
+ ]
535
+ ),
536
+ encoding="utf-8",
537
+ )
538
+ return RunArtifacts(
539
+ run_dir=str(run_root),
540
+ manifest=str(manifest_path),
541
+ config_yaml=str(config_yaml),
542
+ commands_log=str(commands_log),
543
+ all_poses_sdf=str(all_poses),
544
+ best_per_ligand_sdf=str(best_sdf),
545
+ scores_long_csv=str(scores_long),
546
+ best_per_ligand_csv=str(best_csv),
547
+ report_md=str(report_md),
548
+ command_records=[r.to_dict() for r in runner.records],
549
+ best_ligand_poses_sdf=best_ligand_poses_sdf,
550
+ )
551
+
552
+
553
+ def load_target_config(path: str | Path) -> TargetConfig:
554
+ source = require_file(path, "target config")
555
+ try:
556
+ import yaml
557
+
558
+ data = yaml.safe_load(source.read_text(encoding="utf-8"))
559
+ except Exception:
560
+ data = json.loads(source.read_text(encoding="utf-8"))
561
+ return TargetConfig(**data)
docking_pipeline/reports/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Report and plotting helpers for strict rDock runs."""
docking_pipeline/reports/plots.py ADDED
@@ -0,0 +1,644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import json
5
+ import math
6
+ import struct
7
+ import zlib
8
+ from pathlib import Path
9
+ from typing import Iterable
10
+
11
+
12
+ def _read_rows(path: str | Path) -> list[dict[str, str]]:
13
+ with Path(path).open("r", encoding="utf-8", newline="") as handle:
14
+ return list(csv.DictReader(handle))
15
+
16
+
17
+ def _floats(rows: Iterable[dict[str, object]], key: str) -> list[float]:
18
+ out: list[float] = []
19
+ for row in rows:
20
+ try:
21
+ out.append(float(row[key])) # type: ignore[index]
22
+ except Exception:
23
+ continue
24
+ return out
25
+
26
+
27
+ def _boolish(value: object) -> bool:
28
+ return str(value).strip().lower() in {"1", "true", "yes", "y"}
29
+
30
+
31
+ def _float_or_zero(value: object) -> float:
32
+ try:
33
+ return float(value)
34
+ except Exception:
35
+ return 0.0
36
+
37
+
38
+ def _plot_or_skip(plot_dir: Path, name: str, fn) -> str | None: # type: ignore[no-untyped-def]
39
+ try:
40
+ import matplotlib
41
+
42
+ matplotlib.use("Agg")
43
+ import matplotlib.pyplot as plt
44
+ except Exception as exc:
45
+ (plot_dir / "skipped_plots.json").write_text(
46
+ json.dumps({"reason": f"matplotlib unavailable: {exc}"}, indent=2),
47
+ encoding="utf-8",
48
+ )
49
+ return None
50
+ path = plot_dir / name
51
+ fig = fn(plt)
52
+ fig.tight_layout()
53
+ fig.savefig(path, dpi=160)
54
+ plt.close(fig)
55
+ return str(path)
56
+
57
+
58
+ def _write_png(path: Path, width: int, height: int, pixels: bytearray) -> str:
59
+ def chunk(tag: bytes, data: bytes) -> bytes:
60
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
61
+
62
+ raw = b"".join(b"\x00" + pixels[y * width * 3 : (y + 1) * width * 3] for y in range(height))
63
+ png = (
64
+ b"\x89PNG\r\n\x1a\n"
65
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
66
+ + chunk(b"IDAT", zlib.compress(raw, 9))
67
+ + chunk(b"IEND", b"")
68
+ )
69
+ path.write_bytes(png)
70
+ return str(path)
71
+
72
+
73
+ def _simple_plot(path: Path, values: list[float], kind: str = "hist") -> str:
74
+ width, height = 800, 480
75
+ pix = bytearray([255] * width * height * 3)
76
+
77
+ def setpx(x: int, y: int, color: tuple[int, int, int]) -> None:
78
+ if 0 <= x < width and 0 <= y < height:
79
+ i = (y * width + x) * 3
80
+ pix[i : i + 3] = bytes(color)
81
+
82
+ def line(x0: int, y0: int, x1: int, y1: int, color: tuple[int, int, int]) -> None:
83
+ dx, dy = abs(x1 - x0), -abs(y1 - y0)
84
+ sx = 1 if x0 < x1 else -1
85
+ sy = 1 if y0 < y1 else -1
86
+ err = dx + dy
87
+ while True:
88
+ setpx(x0, y0, color)
89
+ if x0 == x1 and y0 == y1:
90
+ break
91
+ e2 = 2 * err
92
+ if e2 >= dy:
93
+ err += dy
94
+ x0 += sx
95
+ if e2 <= dx:
96
+ err += dx
97
+ y0 += sy
98
+
99
+ def rect(x0: int, y0: int, x1: int, y1: int, color: tuple[int, int, int]) -> None:
100
+ for y in range(max(0, y0), min(height, y1)):
101
+ for x in range(max(0, x0), min(width, x1)):
102
+ setpx(x, y, color)
103
+
104
+ left, top, right, bottom = 70, 40, 760, 420
105
+ line(left, bottom, right, bottom, (20, 20, 20))
106
+ line(left, top, left, bottom, (20, 20, 20))
107
+ vals = [v for v in values if math.isfinite(v)]
108
+ if not vals:
109
+ return _write_png(path, width, height, pix)
110
+ if kind == "bar":
111
+ ordered = vals[:20]
112
+ mn = min(0.0, min(ordered))
113
+ mx = max(0.0, max(ordered))
114
+ span = mx - mn or 1.0
115
+ bw = max(2, int((right - left) / max(1, len(ordered))))
116
+ for i, v in enumerate(ordered):
117
+ x0 = left + i * bw + 2
118
+ x1 = left + (i + 1) * bw - 2
119
+ y = int(bottom - ((v - mn) / span) * (bottom - top))
120
+ y0, y1 = sorted([bottom, y])
121
+ rect(x0, y0, x1, y1, (75, 125, 170))
122
+ else:
123
+ bins = min(30, max(5, len(vals) // 3))
124
+ mn, mx = min(vals), max(vals)
125
+ span = mx - mn or 1.0
126
+ counts = [0] * bins
127
+ for v in vals:
128
+ idx = min(bins - 1, int(((v - mn) / span) * bins))
129
+ counts[idx] += 1
130
+ maxc = max(counts) or 1
131
+ bw = int((right - left) / bins)
132
+ for i, c in enumerate(counts):
133
+ x0 = left + i * bw + 1
134
+ x1 = left + (i + 1) * bw - 1
135
+ y0 = int(bottom - (c / maxc) * (bottom - top))
136
+ rect(x0, y0, x1, bottom, (75, 125, 170))
137
+ return _write_png(path, width, height, pix)
138
+
139
+
140
+ def plot_score_outputs(best_csv: str | Path, plot_dir: str | Path, title_prefix: str = "rDock") -> list[str]:
141
+ pdir = Path(plot_dir)
142
+ pdir.mkdir(parents=True, exist_ok=True)
143
+ rows = _read_rows(best_csv)
144
+ scores = _floats(rows, "SCORE")
145
+ paths: list[str] = []
146
+ if not scores:
147
+ return paths
148
+
149
+ def hist(plt): # type: ignore[no-untyped-def]
150
+ fig, ax = plt.subplots(figsize=(7, 4))
151
+ ax.hist(scores, bins=min(30, max(5, len(scores) // 5)), color="#3b6ea8", edgecolor="white")
152
+ ax.set_title(f"{title_prefix} SCORE distribution")
153
+ ax.set_xlabel("SCORE")
154
+ ax.set_ylabel("Count")
155
+ return fig
156
+
157
+ def topbar(plt): # type: ignore[no-untyped-def]
158
+ ordered = sorted(rows, key=lambda r: float(r.get("SCORE", "inf")))[:20]
159
+ labels = [str(r.get("ligand_id", "")) for r in ordered]
160
+ vals = [float(r.get("SCORE", "nan")) for r in ordered]
161
+ fig, ax = plt.subplots(figsize=(9, 4))
162
+ ax.bar(range(len(vals)), vals, color="#7a9d54")
163
+ ax.set_title(f"{title_prefix} top SCOREs")
164
+ ax.set_xlabel("Ligand rank")
165
+ ax.set_ylabel("SCORE")
166
+ ax.set_xticks(range(len(vals)))
167
+ ax.set_xticklabels(labels, rotation=60, ha="right", fontsize=8)
168
+ return fig
169
+
170
+ for name, fn in (("score_distribution.png", hist), ("top_scores.png", topbar)):
171
+ if path := _plot_or_skip(pdir, name, fn):
172
+ paths.append(path)
173
+ else:
174
+ paths.append(_simple_plot(pdir / name, scores if "distribution" in name else sorted(scores)[:20], "hist" if "distribution" in name else "bar"))
175
+ return paths
176
+
177
+
178
+ def plot_astex_outputs(summary_csv: str | Path, plot_dir: str | Path) -> list[str]:
179
+ pdir = Path(plot_dir)
180
+ pdir.mkdir(parents=True, exist_ok=True)
181
+ rows = _read_rows(summary_csv)
182
+ top1 = _floats(rows, "top1_rmsd")
183
+ best = _floats(rows, "best_of_n_rmsd")
184
+ scores = _floats(rows, "top1_SCORE")
185
+ paths: list[str] = []
186
+ if not top1 and not best:
187
+ return paths
188
+
189
+ def hist(plt): # type: ignore[no-untyped-def]
190
+ fig, ax = plt.subplots(figsize=(7, 4))
191
+ if top1:
192
+ ax.hist(top1, alpha=0.65, label="top1", bins=20)
193
+ if best:
194
+ ax.hist(best, alpha=0.65, label="best-of-n", bins=20)
195
+ ax.axvline(2.0, color="black", linestyle="--", linewidth=1)
196
+ ax.set_xlabel("RMSD (A)")
197
+ ax.set_ylabel("Systems")
198
+ ax.legend()
199
+ return fig
200
+
201
+ def scatter(plt): # type: ignore[no-untyped-def]
202
+ fig, ax = plt.subplots(figsize=(5, 5))
203
+ ax.scatter(top1[: len(best)], best[: len(top1)], color="#3b6ea8")
204
+ ax.axhline(2.0, color="black", linestyle="--", linewidth=1)
205
+ ax.axvline(2.0, color="black", linestyle="--", linewidth=1)
206
+ ax.set_xlabel("Top1 RMSD (A)")
207
+ ax.set_ylabel("Best-of-n RMSD (A)")
208
+ return fig
209
+
210
+ def success_bar(plt): # type: ignore[no-untyped-def]
211
+ top1_success = sum(1 for row in rows if _boolish(row.get("success_top1_rmsd_le_2A")))
212
+ best_success = sum(1 for row in rows if _boolish(row.get("success_best_rmsd_le_2A")))
213
+ total = max(1, len([r for r in rows if r.get("status") == "success"]))
214
+ fig, ax = plt.subplots(figsize=(5, 4))
215
+ ax.bar(["top1 <= 2A", "best <= 2A"], [top1_success / total, best_success / total], color=["#3b6ea8", "#7a9d54"])
216
+ ax.set_ylim(0, 1)
217
+ ax.set_ylabel("Successful fraction")
218
+ return fig
219
+
220
+ def score_vs_rmsd(plt): # type: ignore[no-untyped-def]
221
+ n = min(len(scores), len(top1))
222
+ fig, ax = plt.subplots(figsize=(6, 4))
223
+ ax.scatter(scores[:n], top1[:n], color="#7a4f9d")
224
+ ax.axhline(2.0, color="black", linestyle="--", linewidth=1)
225
+ ax.set_xlabel("Top pose SCORE")
226
+ ax.set_ylabel("Top1 RMSD (A)")
227
+ return fig
228
+
229
+ plot_specs = [("rmsd_distribution.png", hist), ("top1_vs_best_rmsd.png", scatter), ("success_rmsd_le_2A.png", success_bar)]
230
+ if scores and top1:
231
+ plot_specs.append(("score_vs_rmsd.png", score_vs_rmsd))
232
+ for name, fn in plot_specs:
233
+ if path := _plot_or_skip(pdir, name, fn):
234
+ paths.append(path)
235
+ else:
236
+ values = scores if name == "score_vs_rmsd.png" else (top1 or []) + (best or [])
237
+ paths.append(_simple_plot(pdir / name, values, "hist"))
238
+ return paths
239
+
240
+
241
+ def plot_dud_outputs(best_csv: str | Path, enrichment_csv: str | Path, plot_dir: str | Path) -> list[str]:
242
+ pdir = Path(plot_dir)
243
+ pdir.mkdir(parents=True, exist_ok=True)
244
+ rows = _read_rows(best_csv)
245
+ scores = _floats(rows, "SCORE")
246
+ labels = []
247
+ for row in rows:
248
+ try:
249
+ labels.append(int(float(row.get("label", 0))))
250
+ except Exception:
251
+ labels.append(0)
252
+ paths: list[str] = []
253
+ if not scores:
254
+ return paths
255
+
256
+ ordered = sorted(zip(scores, labels), key=lambda x: x[0])
257
+ total_actives = max(1, sum(labels))
258
+ x = [(i + 1) / len(ordered) for i in range(len(ordered))]
259
+ y = []
260
+ seen = 0
261
+ for _, label in ordered:
262
+ seen += int(label)
263
+ y.append(seen / total_actives)
264
+ total_decoys = max(1, len(labels) - sum(labels))
265
+ roc_x: list[float] = []
266
+ roc_y: list[float] = []
267
+ tp = 0
268
+ fp = 0
269
+ for _, label in ordered:
270
+ if int(label) == 1:
271
+ tp += 1
272
+ else:
273
+ fp += 1
274
+ roc_x.append(fp / total_decoys)
275
+ roc_y.append(tp / total_actives)
276
+ ef_rows = _read_rows(enrichment_csv) if Path(enrichment_csv).exists() else []
277
+
278
+ def cumulative(plt): # type: ignore[no-untyped-def]
279
+ fig, ax = plt.subplots(figsize=(7, 4))
280
+ ax.plot(x, y, color="#3b6ea8")
281
+ ax.set_xlabel("Ranked fraction")
282
+ ax.set_ylabel("Cumulative active recovery")
283
+ return fig
284
+
285
+ def score_by_label(plt): # type: ignore[no-untyped-def]
286
+ fig, ax = plt.subplots(figsize=(7, 4))
287
+ active = [s for s, l in zip(scores, labels) if l == 1]
288
+ decoy = [s for s, l in zip(scores, labels) if l == 0]
289
+ if active:
290
+ ax.hist(active, alpha=0.6, label="actives", bins=20)
291
+ if decoy:
292
+ ax.hist(decoy, alpha=0.6, label="decoys", bins=20)
293
+ ax.set_xlabel("SCORE")
294
+ ax.set_ylabel("Ligands")
295
+ ax.legend()
296
+ return fig
297
+
298
+ def roc_curve(plt): # type: ignore[no-untyped-def]
299
+ fig, ax = plt.subplots(figsize=(5, 5))
300
+ ax.plot([0, *roc_x], [0, *roc_y], color="#3b6ea8")
301
+ ax.plot([0, 1], [0, 1], color="gray", linestyle="--", linewidth=1)
302
+ ax.set_xlabel("False positive rate")
303
+ ax.set_ylabel("True positive rate")
304
+ return fig
305
+
306
+ def semilog_roc(plt): # type: ignore[no-untyped-def]
307
+ fig, ax = plt.subplots(figsize=(6, 4))
308
+ xs = [max(0.0005, v) for v in roc_x]
309
+ ax.plot(xs, roc_y, color="#3b6ea8")
310
+ ax.set_xscale("log")
311
+ ax.set_xlabel("False positive rate")
312
+ ax.set_ylabel("True positive rate")
313
+ return fig
314
+
315
+ def ef_bar(plt): # type: ignore[no-untyped-def]
316
+ fig, ax = plt.subplots(figsize=(6, 4))
317
+ labels_ef = [str(row.get("fraction", "")) for row in ef_rows]
318
+ vals = _floats(ef_rows, "enrichment_factor")
319
+ ax.bar(labels_ef, vals, color="#7a9d54")
320
+ ax.set_xlabel("Ranked fraction")
321
+ ax.set_ylabel("Enrichment factor")
322
+ return fig
323
+
324
+ plot_specs = [
325
+ ("roc_curve.png", roc_curve),
326
+ ("semilog_roc.png", semilog_roc),
327
+ ("enrichment_factors.png", ef_bar),
328
+ ("cumulative_actives.png", cumulative),
329
+ ("score_distribution_by_label.png", score_by_label),
330
+ ]
331
+ for name, fn in plot_specs:
332
+ if path := _plot_or_skip(pdir, name, fn):
333
+ paths.append(path)
334
+ else:
335
+ paths.append(_simple_plot(pdir / name, y if "cumulative" in name else scores, "bar" if "cumulative" in name else "hist"))
336
+ return paths
337
+
338
+
339
+ def plot_adaptive_benchmark_outputs(
340
+ full_csv: str | Path,
341
+ adaptive_csv: str | Path,
342
+ random_csv: str | Path,
343
+ metrics_json: str | Path,
344
+ plot_dir: str | Path,
345
+ ) -> list[str]:
346
+ pdir = Path(plot_dir)
347
+ pdir.mkdir(parents=True, exist_ok=True)
348
+ full_rows = _read_rows(full_csv)
349
+ adaptive_rows = _read_rows(adaptive_csv)
350
+ random_rows = _read_rows(random_csv)
351
+ metrics = json.loads(Path(metrics_json).read_text(encoding="utf-8")) if Path(metrics_json).exists() else {}
352
+ full_scores = _floats(full_rows, "SCORE")
353
+ adaptive_scores = _floats(adaptive_rows, "SCORE")
354
+ random_scores = _floats(random_rows, "SCORE")
355
+ paths: list[str] = []
356
+ if not full_scores:
357
+ return paths
358
+
359
+ def cumulative_best(rows: list[dict[str, str]]) -> list[float]:
360
+ vals = _floats(rows, "SCORE")
361
+ best: list[float] = []
362
+ current = float("inf")
363
+ for value in vals:
364
+ current = min(current, value)
365
+ best.append(current)
366
+ return best
367
+
368
+ def cumulative_plot(plt): # type: ignore[no-untyped-def]
369
+ fig, ax = plt.subplots(figsize=(7, 4))
370
+ full_curve = cumulative_best(full_rows)
371
+ adaptive_curve = cumulative_best(adaptive_rows)
372
+ random_curve = cumulative_best(random_rows)
373
+ if full_curve:
374
+ ax.plot(range(1, len(full_curve) + 1), full_curve, label="full")
375
+ if adaptive_curve:
376
+ ax.plot(range(1, len(adaptive_curve) + 1), adaptive_curve, label="adaptive")
377
+ if random_curve:
378
+ ax.plot(range(1, len(random_curve) + 1), random_curve, label="random")
379
+ ax.set_xlabel("Docked ligand count")
380
+ ax.set_ylabel("Best SCORE so far")
381
+ ax.legend()
382
+ return fig
383
+
384
+ def percentile_bar(plt): # type: ignore[no-untyped-def]
385
+ fig, ax = plt.subplots(figsize=(6, 4))
386
+ labels = ["adaptive", "random", "full"]
387
+ vals = [
388
+ float(metrics.get("adaptive_best_percentile_of_full", 0.0) or 0.0),
389
+ float(metrics.get("random_best_percentile_of_full", 0.0) or 0.0),
390
+ float(metrics.get("full_best_percentile_of_full", 100.0) or 100.0),
391
+ ]
392
+ ax.bar(labels, vals, color=["#3b6ea8", "#bf7f2f", "#7a9d54"])
393
+ ax.set_ylim(0, 100)
394
+ ax.set_ylabel("Percentile in full ranking")
395
+ return fig
396
+
397
+ def runtime_bar(plt): # type: ignore[no-untyped-def]
398
+ fig, ax = plt.subplots(figsize=(6, 4))
399
+ labels = ["full docking", "adaptive docking", "random docking", "adaptive model"]
400
+ vals = [
401
+ float(metrics.get("full_docking_seconds", 0.0) or 0.0),
402
+ float(metrics.get("adaptive_docking_seconds", 0.0) or 0.0),
403
+ float(metrics.get("random_docking_seconds", 0.0) or 0.0),
404
+ float(metrics.get("adaptive_model_seconds", 0.0) or 0.0),
405
+ ]
406
+ ax.bar(labels, vals, color=["#7a9d54", "#3b6ea8", "#bf7f2f", "#7a4f9d"])
407
+ ax.set_ylabel("Seconds")
408
+ ax.tick_params(axis="x", rotation=20)
409
+ return fig
410
+
411
+ def success_bar(plt): # type: ignore[no-untyped-def]
412
+ fig, ax = plt.subplots(figsize=(6, 4))
413
+ labels = ["full ok", "adaptive ok", "random ok", "failed"]
414
+ vals = [
415
+ float(metrics.get("full_success_count", 0.0) or 0.0),
416
+ float(metrics.get("adaptive_success_count", 0.0) or 0.0),
417
+ float(metrics.get("random_success_count", 0.0) or 0.0),
418
+ float(metrics.get("failed_docking_count", 0.0) or 0.0),
419
+ ]
420
+ ax.bar(labels, vals, color=["#7a9d54", "#3b6ea8", "#bf7f2f", "#b14d4d"])
421
+ ax.set_ylabel("Ligands")
422
+ ax.tick_params(axis="x", rotation=15)
423
+ return fig
424
+
425
+ def model_scatter(plt): # type: ignore[no-untyped-def]
426
+ fig, ax = plt.subplots(figsize=(6, 4))
427
+ xs = _floats(adaptive_rows, "model_score")
428
+ ys = _floats(adaptive_rows, "SCORE")
429
+ n = min(len(xs), len(ys))
430
+ ax.scatter(xs[:n], ys[:n], color="#3b6ea8")
431
+ ax.set_xlabel("Model score")
432
+ ax.set_ylabel("rDock SCORE")
433
+ return fig
434
+
435
+ plot_specs = [
436
+ ("cumulative_best_score.png", cumulative_plot),
437
+ ("adaptive_random_full_percentile.png", percentile_bar),
438
+ ("runtime_summary.png", runtime_bar),
439
+ ("success_failure_summary.png", success_bar),
440
+ ]
441
+ if _floats(adaptive_rows, "model_score"):
442
+ plot_specs.append(("model_vs_rdock_score.png", model_scatter))
443
+ for name, fn in plot_specs:
444
+ if path := _plot_or_skip(pdir, name, fn):
445
+ paths.append(path)
446
+ else:
447
+ fallback = full_scores
448
+ if name == "adaptive_random_full_percentile.png":
449
+ fallback = [
450
+ float(metrics.get("adaptive_best_percentile_of_full", 0.0) or 0.0),
451
+ float(metrics.get("random_best_percentile_of_full", 0.0) or 0.0),
452
+ float(metrics.get("full_best_percentile_of_full", 100.0) or 100.0),
453
+ ]
454
+ paths.append(_simple_plot(pdir / name, fallback, "bar" if "summary" in name or "percentile" in name else "hist"))
455
+ return paths
456
+
457
+
458
+ def plot_multifidelity_outputs(
459
+ trace_csv: str | Path,
460
+ final_hits_csv: str | Path,
461
+ random_csv: str | Path,
462
+ full_csv: str | Path,
463
+ metrics_json: str | Path,
464
+ plot_dir: str | Path,
465
+ ) -> list[str]:
466
+ pdir = Path(plot_dir)
467
+ pdir.mkdir(parents=True, exist_ok=True)
468
+ trace_rows = _read_rows(trace_csv) if Path(trace_csv).exists() else []
469
+ final_rows = _read_rows(final_hits_csv) if Path(final_hits_csv).exists() else []
470
+ random_rows = _read_rows(random_csv) if Path(random_csv).exists() else []
471
+ full_rows = _read_rows(full_csv) if Path(full_csv).exists() else []
472
+ metrics = json.loads(Path(metrics_json).read_text(encoding="utf-8")) if Path(metrics_json).exists() else {}
473
+ paths: list[str] = []
474
+ if not trace_rows:
475
+ return paths
476
+
477
+ def cumulative_best_vs_cost(rows: list[dict[str, str]], score_key: str = "current_best_score"): # type: ignore[no-untyped-def]
478
+ ordered = sorted(rows, key=lambda row: (_float_or_zero(row.get("n_rdock_runs_total_spent", 0.0)), _float_or_zero(row.get("selected_fidelity_runs", 0.0))))
479
+ xs: list[float] = []
480
+ ys: list[float] = []
481
+ current = float("inf")
482
+ for row in ordered:
483
+ score = _float_or_zero(row.get(score_key, row.get("SCORE", 0.0)))
484
+ if score == 0.0 and row.get(score_key, row.get("SCORE", "")) in ("", None):
485
+ continue
486
+ current = min(current, score)
487
+ xs.append(_float_or_zero(row.get("n_rdock_runs_total_spent", 0.0)))
488
+ ys.append(current)
489
+ return xs, ys
490
+
491
+ def best_vs_cost(plt): # type: ignore[no-untyped-def]
492
+ fig, ax = plt.subplots(figsize=(7, 4))
493
+ xs, ys = cumulative_best_vs_cost(trace_rows)
494
+ if xs and ys:
495
+ ax.plot(xs, ys, label="multifidelity")
496
+ random_vals = sorted(_floats(random_rows, "final_score") or _floats(random_rows, "SCORE"))
497
+ if random_vals:
498
+ ax.axhline(random_vals[0], color="#bf7f2f", linestyle="--", label="random best")
499
+ full_vals = sorted(_floats(full_rows, "SCORE"))
500
+ if full_vals:
501
+ ax.axhline(full_vals[0], color="#7a9d54", linestyle=":", label="full best")
502
+ ax.set_xlabel("Total rDock runs spent")
503
+ ax.set_ylabel("Best SCORE so far")
504
+ ax.legend()
505
+ return fig
506
+
507
+ def best_vs_walltime(plt): # type: ignore[no-untyped-def]
508
+ fig, ax = plt.subplots(figsize=(7, 4))
509
+ ordered = sorted(trace_rows, key=lambda row: _float_or_zero(row.get("timing_docking_seconds", 0.0)) + _float_or_zero(row.get("timing_training_seconds", 0.0)))
510
+ xs: list[float] = []
511
+ ys: list[float] = []
512
+ elapsed = 0.0
513
+ current = float("inf")
514
+ for row in ordered:
515
+ score = _float_or_zero(row.get("current_best_score", row.get("SCORE", 0.0)))
516
+ elapsed += _float_or_zero(row.get("timing_docking_seconds", 0.0)) + _float_or_zero(row.get("timing_training_seconds", 0.0))
517
+ current = min(current, score)
518
+ xs.append(elapsed)
519
+ ys.append(current)
520
+ if xs and ys:
521
+ ax.plot(xs, ys, color="#3b6ea8")
522
+ ax.set_xlabel("Walltime (s)")
523
+ ax.set_ylabel("Best SCORE so far")
524
+ return fig
525
+
526
+ def fidelity_counts(plt): # type: ignore[no-untyped-def]
527
+ counts: dict[str, int] = {}
528
+ for row in trace_rows:
529
+ level = str(row.get("selected_fidelity_runs", ""))
530
+ counts[level] = counts.get(level, 0) + 1
531
+ labels = sorted(counts, key=lambda x: int(x or 0))
532
+ vals = [counts[label] for label in labels]
533
+ fig, ax = plt.subplots(figsize=(6, 4))
534
+ ax.bar(labels, vals, color="#3b6ea8")
535
+ ax.set_xlabel("Fidelity runs")
536
+ ax.set_ylabel("Ligands screened")
537
+ return fig
538
+
539
+ def promotion_funnel(plt): # type: ignore[no-untyped-def]
540
+ counts: dict[str, int] = {}
541
+ for row in trace_rows:
542
+ level = str(row.get("selected_fidelity_runs", ""))
543
+ counts[level] = counts.get(level, 0) + 1
544
+ labels = sorted(counts, key=lambda x: int(x or 0))
545
+ vals = [counts[label] for label in labels]
546
+ fig, ax = plt.subplots(figsize=(6, 4))
547
+ ax.plot(range(len(vals)), vals, marker="o", color="#7a4f9d")
548
+ ax.set_xticks(range(len(vals)))
549
+ ax.set_xticklabels(labels)
550
+ ax.set_xlabel("Fidelity runs")
551
+ ax.set_ylabel("Ligands")
552
+ return fig
553
+
554
+ def percentile_bar(plt): # type: ignore[no-untyped-def]
555
+ labels = ["multifidelity", "random", "single", "full"]
556
+ vals = [
557
+ float(metrics.get("multifidelity_percentile_vs_full", 0.0) or 0.0),
558
+ float(metrics.get("random_percentile_vs_full", 0.0) or 0.0),
559
+ float(metrics.get("single_fidelity_percentile_vs_full", 0.0) or 0.0),
560
+ 100.0,
561
+ ]
562
+ fig, ax = plt.subplots(figsize=(6, 4))
563
+ ax.bar(labels, vals, color=["#3b6ea8", "#bf7f2f", "#7a4f9d", "#7a9d54"])
564
+ ax.set_ylim(0, 100)
565
+ ax.set_ylabel("Percentile in full ranking")
566
+ return fig
567
+
568
+ def score_by_level(plt): # type: ignore[no-untyped-def]
569
+ fig, ax = plt.subplots(figsize=(7, 4))
570
+ levels = sorted({str(row.get("selected_fidelity_runs", "")) for row in trace_rows}, key=lambda x: int(x or 0))
571
+ for level in levels:
572
+ vals = [_float_or_zero(row.get("SCORE", 0.0)) for row in trace_rows if str(row.get("selected_fidelity_runs", "")) == level and row.get("SCORE", "") not in ("", None)]
573
+ if vals:
574
+ ax.hist(vals, bins=min(25, max(5, len(vals) // 3)), alpha=0.45, label=level)
575
+ ax.set_xlabel("SCORE")
576
+ ax.set_ylabel("Records")
577
+ ax.legend(title="runs")
578
+ return fig
579
+
580
+ def intra_hist(plt): # type: ignore[no-untyped-def]
581
+ vals = [_float_or_zero(row.get("SCORE.INTRA", 0.0)) for row in trace_rows if row.get("SCORE.INTRA", "") not in ("", None)]
582
+ fig, ax = plt.subplots(figsize=(7, 4))
583
+ ax.hist(vals, bins=min(30, max(5, len(vals) // 3)), color="#bf7f2f")
584
+ ax.set_xlabel("SCORE.INTRA")
585
+ ax.set_ylabel("Records")
586
+ return fig
587
+
588
+ def score_vs_intra(plt): # type: ignore[no-untyped-def]
589
+ xs = [_float_or_zero(row.get("SCORE.INTRA", 0.0)) for row in trace_rows if row.get("SCORE", "") not in ("", None) and row.get("SCORE.INTRA", "") not in ("", None)]
590
+ ys = [_float_or_zero(row.get("SCORE", 0.0)) for row in trace_rows if row.get("SCORE", "") not in ("", None) and row.get("SCORE.INTRA", "") not in ("", None)]
591
+ fig, ax = plt.subplots(figsize=(6, 4))
592
+ if xs and ys:
593
+ ax.scatter(xs, ys, c=["#b14d4d" if _boolish(row.get("intra_outlier", "")) else "#3b6ea8" for row in trace_rows[: min(len(xs), len(trace_rows))]], alpha=0.7)
594
+ ax.set_xlabel("SCORE.INTRA")
595
+ ax.set_ylabel("SCORE")
596
+ return fig
597
+
598
+ def top_hits_bar(plt): # type: ignore[no-untyped-def]
599
+ ordered = sorted(
600
+ [row for row in final_rows if str(row.get("is_final_fidelity", "")).lower() in {"true", "1"}],
601
+ key=lambda row: _float_or_zero(row.get("final_score", row.get("current_best_score", 0.0))),
602
+ )[:20]
603
+ labels = [str(row.get("ligand_id", "")) for row in ordered]
604
+ vals = [_float_or_zero(row.get("final_score", row.get("current_best_score", 0.0))) for row in ordered]
605
+ fig, ax = plt.subplots(figsize=(9, 4))
606
+ ax.bar(range(len(vals)), vals, color="#7a9d54")
607
+ ax.set_xticks(range(len(vals)))
608
+ ax.set_xticklabels(labels, rotation=60, ha="right", fontsize=8)
609
+ ax.set_ylabel("Final SCORE")
610
+ return fig
611
+
612
+ def training_vs_docking(plt): # type: ignore[no-untyped-def]
613
+ fig, ax = plt.subplots(figsize=(6, 4))
614
+ ax.bar(
615
+ ["training", "docking", "overhead"],
616
+ [
617
+ float(metrics.get("training_time_seconds", 0.0) or 0.0),
618
+ float(metrics.get("docking_time_seconds", 0.0) or 0.0),
619
+ float(metrics.get("overhead_time_seconds", 0.0) or 0.0),
620
+ ],
621
+ color=["#7a4f9d", "#3b6ea8", "#bf7f2f"],
622
+ )
623
+ ax.set_ylabel("Seconds")
624
+ return fig
625
+
626
+ plot_specs = [
627
+ ("cumulative_best_final_score_vs_runs.png", best_vs_cost),
628
+ ("cumulative_best_score_vs_walltime.png", best_vs_walltime),
629
+ ("ligands_per_fidelity_level.png", fidelity_counts),
630
+ ("promotion_funnel.png", promotion_funnel),
631
+ ("adaptive_vs_random_vs_full_percentile.png", percentile_bar),
632
+ ("score_distribution_by_fidelity.png", score_by_level),
633
+ ("score_intra_distribution.png", intra_hist),
634
+ ("score_vs_score_intra.png", score_vs_intra),
635
+ ("top_final_hits.png", top_hits_bar),
636
+ ("training_vs_docking_time.png", training_vs_docking),
637
+ ]
638
+ for name, fn in plot_specs:
639
+ if path := _plot_or_skip(pdir, name, fn):
640
+ paths.append(path)
641
+ else:
642
+ vals = _floats(trace_rows, "SCORE")
643
+ paths.append(_simple_plot(pdir / name, vals, "bar" if "percentile" in name or "fidelity" in name or "top_" in name or "training" in name else "hist"))
644
+ return paths
docking_pipeline/sdf.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import math
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any, Iterable
9
+
10
+ from .provenance import RDockPipelineError, require_file
11
+
12
+ TAG_RE = re.compile(r"^>\s*<\s*([^>]+?)\s*>", flags=re.IGNORECASE)
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class SDFRecord:
17
+ block: str
18
+ index: int
19
+ ligand_id: str
20
+ score: float | None
21
+ tags: dict[str, str]
22
+ numeric_tags: dict[str, float]
23
+
24
+
25
+ def split_sdf_text(text: str) -> list[str]:
26
+ blocks: list[str] = []
27
+ for part in text.split("$$$$"):
28
+ body = part.strip()
29
+ if body:
30
+ blocks.append(body + "\n$$$$\n")
31
+ return blocks
32
+
33
+
34
+ def split_sdf_file(path: str | Path) -> list[str]:
35
+ source = require_file(path, "SDF file")
36
+ blocks = split_sdf_text(source.read_text(encoding="utf-8", errors="ignore"))
37
+ if not blocks:
38
+ raise RDockPipelineError(f"No SDF records found in {source}")
39
+ return blocks
40
+
41
+
42
+ def parse_tags(block: str) -> dict[str, str]:
43
+ lines = block.splitlines()
44
+ tags: dict[str, str] = {}
45
+ i = 0
46
+ while i < len(lines):
47
+ m = TAG_RE.match(lines[i].strip())
48
+ if not m:
49
+ i += 1
50
+ continue
51
+ key = m.group(1).strip()
52
+ values: list[str] = []
53
+ j = i + 1
54
+ while j < len(lines) and lines[j].strip() and lines[j].strip() != "$$$$" and not TAG_RE.match(lines[j].strip()):
55
+ values.append(lines[j].strip())
56
+ j += 1
57
+ tags[key] = "\n".join(values).strip()
58
+ i = j
59
+ return tags
60
+
61
+
62
+ def _safe_float(value: Any) -> float | None:
63
+ try:
64
+ out = float(str(value).strip())
65
+ except Exception:
66
+ return None
67
+ if not math.isfinite(out):
68
+ return None
69
+ return out
70
+
71
+
72
+ def _record_name(block: str, fallback: str) -> str:
73
+ first = block.splitlines()[0].strip() if block.splitlines() else ""
74
+ return first or fallback
75
+
76
+
77
+ def ligand_id_from_block(block: str, tags: dict[str, str], index: int) -> str:
78
+ for key in ("ligand_id", "LigandID", "LIGAND_ID", "ID", "Name", "_Name"):
79
+ value = tags.get(key)
80
+ if value:
81
+ return value.split()[0].strip()
82
+ return _record_name(block, f"ligand_{index:06d}").split()[0].strip()
83
+
84
+
85
+ def parse_rdock_sdf_records(path: str | Path, require_score: bool = True) -> list[SDFRecord]:
86
+ records: list[SDFRecord] = []
87
+ for idx, block in enumerate(split_sdf_file(path)):
88
+ tags = parse_tags(block)
89
+ numeric = {k: v for k, raw in tags.items() if (v := _safe_float(raw)) is not None}
90
+ score = numeric.get("SCORE")
91
+ if require_score and score is None:
92
+ raise RDockPipelineError(f"Missing required rDock SCORE field in SDF record {idx} of {path}")
93
+ records.append(
94
+ SDFRecord(
95
+ block=block,
96
+ index=idx,
97
+ ligand_id=ligand_id_from_block(block, tags, idx),
98
+ score=score,
99
+ tags=tags,
100
+ numeric_tags=numeric,
101
+ )
102
+ )
103
+ return records
104
+
105
+
106
+ def write_sdf_records(records: Iterable[SDFRecord], path: str | Path) -> Path:
107
+ target = Path(path)
108
+ target.parent.mkdir(parents=True, exist_ok=True)
109
+ target.write_text("".join(rec.block for rec in records), encoding="utf-8")
110
+ return target
111
+
112
+
113
+ def write_sdf_blocks(blocks: Iterable[str], path: str | Path) -> Path:
114
+ target = Path(path)
115
+ target.parent.mkdir(parents=True, exist_ok=True)
116
+ target.write_text("".join(blocks), encoding="utf-8")
117
+ return target
118
+
119
+
120
+ def best_per_ligand(records: Iterable[SDFRecord]) -> list[SDFRecord]:
121
+ best: dict[str, SDFRecord] = {}
122
+ for rec in records:
123
+ if rec.score is None:
124
+ raise RDockPipelineError(f"Cannot rank ligand {rec.ligand_id}: missing SCORE")
125
+ prev = best.get(rec.ligand_id)
126
+ if prev is None or float(rec.score) < float(prev.score):
127
+ best[rec.ligand_id] = rec
128
+ return sorted(best.values(), key=lambda r: (float(r.score), r.ligand_id, r.index))
129
+
130
+
131
+ def records_to_rows(records: Iterable[SDFRecord]) -> list[dict[str, object]]:
132
+ rows: list[dict[str, object]] = []
133
+ for rec in records:
134
+ row: dict[str, object] = {
135
+ "pose_index": rec.index,
136
+ "ligand_id": rec.ligand_id,
137
+ "SCORE": rec.score,
138
+ }
139
+ for key, value in sorted(rec.numeric_tags.items()):
140
+ row[key] = value
141
+ rows.append(row)
142
+ return rows
143
+
144
+
145
+ def write_rows_csv(rows: list[dict[str, object]], path: str | Path) -> Path:
146
+ target = Path(path)
147
+ target.parent.mkdir(parents=True, exist_ok=True)
148
+ fields: list[str] = []
149
+ for row in rows:
150
+ for key in row:
151
+ if key not in fields:
152
+ fields.append(key)
153
+ with target.open("w", encoding="utf-8", newline="") as handle:
154
+ writer = csv.DictWriter(handle, fieldnames=fields)
155
+ writer.writeheader()
156
+ writer.writerows(rows)
157
+ return target
docking_pipeline/validation.py ADDED
@@ -0,0 +1,708 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import gzip
5
+ import json
6
+ import os
7
+ import re
8
+ import shutil
9
+ import tarfile
10
+ import urllib.request
11
+ from concurrent.futures import ThreadPoolExecutor, as_completed
12
+ from dataclasses import asdict, dataclass
13
+ from pathlib import Path
14
+ from statistics import median
15
+ from typing import Iterable
16
+
17
+ from .metrics import enrichment_rows, validation_metrics_from_rows
18
+ from .provenance import CommandRecord, CommandRunner, RDockPipelineError, fail_if_bad_command, require_executable, require_file
19
+ from .reports.plots import plot_astex_outputs, plot_dud_outputs
20
+ from .sdf import best_per_ligand, parse_rdock_sdf_records, records_to_rows, split_sdf_file, write_rows_csv, write_sdf_blocks, write_sdf_records
21
+
22
+ VALIDATION_URL = "https://rdock.github.io/validation-sets/"
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class ValidationSystem:
27
+ system_id: str
28
+ path: str
29
+ receptor_prm: str
30
+ dock_prm: str
31
+ ligand_sdf: str = ""
32
+ ligprep_sdf: str = ""
33
+ crystal_sdf: str = ""
34
+
35
+
36
+ def resolve_jobs(jobs: int | str = "auto", cpu_fraction: float = 0.85) -> int:
37
+ if str(jobs).lower() == "auto":
38
+ cpus = os.cpu_count() or 1
39
+ reserve = 1 if cpus <= 4 else 2
40
+ return max(1, min(cpus - reserve, int(cpus * float(cpu_fraction))))
41
+ return max(1, int(jobs))
42
+
43
+
44
+ def _rdock_env() -> dict[str, str]:
45
+ root = os.environ.get("RBT_ROOT")
46
+ if root:
47
+ return {"RBT_ROOT": root}
48
+ for candidate in (Path("/opt/homebrew/opt/rdock/share"), Path("/usr/local/opt/rdock/share")):
49
+ if (candidate / "data" / "RbtElements.dat").exists():
50
+ return {"RBT_ROOT": str(candidate)}
51
+ cellar = Path("/opt/homebrew/Cellar/rdock")
52
+ if cellar.exists():
53
+ for candidate in sorted(cellar.glob("*/share"), reverse=True):
54
+ if (candidate / "data" / "RbtElements.dat").exists():
55
+ return {"RBT_ROOT": str(candidate)}
56
+ return {}
57
+
58
+
59
+ def _system_id_from_prm(path: Path) -> str:
60
+ name = path.stem
61
+ return re.sub(r"_?rdock$", "", name, flags=re.IGNORECASE)
62
+
63
+
64
+ def _find_first(candidates: Iterable[Path]) -> Path | None:
65
+ for p in candidates:
66
+ if p.exists() and p.is_file() and p.stat().st_size > 0:
67
+ return p
68
+ return None
69
+
70
+
71
+ def _find_dock_prm(system_dir: Path) -> Path | None:
72
+ candidates = [system_dir / "dock.prm"] + [parent / "dock.prm" for parent in list(system_dir.parents)[:3]]
73
+ rbt_root = os.environ.get("RBT_ROOT")
74
+ if rbt_root:
75
+ candidates.extend([Path(rbt_root) / "data" / "scripts" / "dock.prm", Path(rbt_root) / "data" / "dock.prm"])
76
+ candidates.extend(
77
+ [
78
+ Path("/opt/homebrew/share/rdock/data/scripts/dock.prm"),
79
+ Path("/opt/homebrew/opt/rdock/share/data/scripts/dock.prm"),
80
+ ]
81
+ )
82
+ candidates.extend(sorted(Path("/opt/homebrew/Cellar/rdock").glob("*/share/data/scripts/dock.prm")) if Path("/opt/homebrew/Cellar/rdock").exists() else [])
83
+ return _find_first(candidates)
84
+
85
+
86
+ def discover_validation_systems(data_dir: str | Path, set_name: str) -> list[ValidationSystem]:
87
+ root = Path(data_dir)
88
+ if not root.exists():
89
+ return []
90
+ systems: dict[str, ValidationSystem] = {}
91
+ for prm in sorted(root.rglob("*_rdock.prm")):
92
+ system_dir = prm.parent
93
+ system_id = _system_id_from_prm(prm)
94
+ dock_prm = _find_dock_prm(system_dir)
95
+ if dock_prm is None:
96
+ local = list(system_dir.rglob("dock.prm"))
97
+ dock_prm = local[0] if local else None
98
+ sdf_files = sorted(list(system_dir.glob("*.sd")) + list(system_dir.glob("*.sdf")))
99
+ gz_sdfs = sorted(list(system_dir.glob("*.sd.gz")) + list(system_dir.glob("*.sdf.gz")))
100
+ ligand_sdf = _find_first(
101
+ [
102
+ system_dir / f"{system_id}_ligand.sd",
103
+ system_dir / f"{system_id}_ligand.sdf",
104
+ system_dir / "ligand.sd",
105
+ system_dir / "ligand.sdf",
106
+ ]
107
+ + [p for p in sdf_files if "ligand" in p.name.lower() or "crystal" in p.name.lower()]
108
+ + sdf_files
109
+ )
110
+ ligprep_sdf = _find_first(
111
+ [
112
+ system_dir / f"{system_id}_ligprep.sdf",
113
+ system_dir / f"{system_id}_ligprep.sd",
114
+ ]
115
+ + [p for p in sdf_files if "ligprep" in p.name.lower()]
116
+ + [p for p in gz_sdfs if "ligprep" in p.name.lower()]
117
+ )
118
+ if set_name.lower() == "dud" and ligprep_sdf is None:
119
+ continue
120
+ systems[system_id] = ValidationSystem(
121
+ system_id=system_id,
122
+ path=str(system_dir),
123
+ receptor_prm=str(prm),
124
+ dock_prm=str(dock_prm or ""),
125
+ ligand_sdf=str(ligand_sdf or ""),
126
+ ligprep_sdf=str(ligprep_sdf or ""),
127
+ crystal_sdf=str(ligand_sdf or ""),
128
+ )
129
+ return [systems[k] for k in sorted(systems)]
130
+
131
+
132
+ def _actionable_missing_system(data_dir: Path, set_name: str, system: str | None) -> RDockPipelineError:
133
+ expected = data_dir / (system or "<system>")
134
+ return RDockPipelineError(
135
+ "Missing rDock validation data.\n"
136
+ f"Expected path or discoverable system files under: {expected}\n"
137
+ f"Validation set: {set_name}\n"
138
+ f"Official validation sets: {VALIDATION_URL}\n"
139
+ "Use one of:\n"
140
+ f" python -m docking_pipeline validate-rdock --set {set_name} --data-dir {data_dir} --list-systems\n"
141
+ f" python -m docking_pipeline validate-rdock --set {set_name} --system {system or '<id>'} --data-dir {data_dir} --out results/benchmarks/{set_name}_{system or '<id>'} --download-url <official_tar.gz> --download-if-missing\n"
142
+ "or manually download/extract the official rDock validation set and pass its extracted directory via --data-dir."
143
+ )
144
+
145
+
146
+ def download_validation_set(download_url: str, data_dir: str | Path, force: bool = False) -> Path:
147
+ target = Path(data_dir)
148
+ if target.exists() and any(target.iterdir()) and not force:
149
+ return target
150
+ target.mkdir(parents=True, exist_ok=True)
151
+ archive = target / Path(download_url).name
152
+ urllib.request.urlretrieve(download_url, archive)
153
+ with tarfile.open(archive, "r:*") as tar:
154
+ tar.extractall(target)
155
+ return target
156
+
157
+
158
+ def ensure_validation_data(data_dir: str | Path, set_name: str, download_url: str | None, download_if_missing: bool, force: bool = False) -> Path:
159
+ root = Path(data_dir)
160
+ if root.exists() and discover_validation_systems(root, set_name):
161
+ return root
162
+ if download_if_missing:
163
+ if not download_url:
164
+ raise RDockPipelineError(
165
+ f"--download-if-missing was set but --download-url was not provided. Official validation sets: {VALIDATION_URL}"
166
+ )
167
+ download_validation_set(download_url, root, force=force)
168
+ return root
169
+
170
+
171
+ def resolve_systems(
172
+ data_dir: str | Path,
173
+ set_name: str,
174
+ system: str | None = None,
175
+ system_list: str | Path | None = None,
176
+ max_systems: int | None = None,
177
+ ) -> list[ValidationSystem]:
178
+ root = Path(data_dir)
179
+ systems = discover_validation_systems(root, set_name)
180
+ if not systems:
181
+ raise _actionable_missing_system(root, set_name, system)
182
+ wanted: set[str] | None = None
183
+ if system:
184
+ wanted = {system}
185
+ if system_list:
186
+ ids = [line.strip() for line in Path(system_list).read_text(encoding="utf-8").splitlines() if line.strip()]
187
+ wanted = (wanted or set()) | set(ids)
188
+ if wanted is not None:
189
+ systems = [s for s in systems if s.system_id in wanted]
190
+ if not systems:
191
+ raise _actionable_missing_system(root, set_name, system or ",".join(sorted(wanted)))
192
+ if max_systems is not None:
193
+ systems = systems[: int(max_systems)]
194
+ return systems
195
+
196
+
197
+ def _copy_system(src: Path, out_dir: Path, force: bool) -> Path:
198
+ dst = out_dir / "rdock" / src.name
199
+ if dst.exists():
200
+ if not force:
201
+ return dst
202
+ shutil.rmtree(dst)
203
+ shutil.copytree(src, dst)
204
+ return dst
205
+
206
+
207
+ def _gunzip_if_needed(path: Path) -> Path:
208
+ if path.exists() and path.suffix != ".gz":
209
+ return path
210
+ if path.suffix == ".gz":
211
+ out = path.with_suffix("")
212
+ if not out.exists():
213
+ with gzip.open(path, "rb") as src, out.open("wb") as dst:
214
+ shutil.copyfileobj(src, dst)
215
+ return out
216
+ gz = path.with_suffix(path.suffix + ".gz")
217
+ if gz.exists():
218
+ return _gunzip_if_needed(gz)
219
+ return require_file(path, "ligand-prepped SDF")
220
+
221
+
222
+ def _run_rbdock_parallel(
223
+ runner: CommandRunner,
224
+ work: Path,
225
+ prm: Path,
226
+ dock_prm: Path,
227
+ ligand_sdf: Path,
228
+ out_prefix: str,
229
+ n_runs: int,
230
+ jobs: int,
231
+ ) -> tuple[Path, list[CommandRecord]]:
232
+ rbdock = require_executable("rbdock")
233
+ blocks = split_sdf_file(ligand_sdf)
234
+ chunk_dir = work / "chunks"
235
+ chunk_dir.mkdir(exist_ok=True)
236
+ chunk_count = min(max(1, jobs), len(blocks))
237
+ chunks: list[Path] = []
238
+ for idx in range(chunk_count):
239
+ chunk_blocks = blocks[idx::chunk_count]
240
+ chunk = chunk_dir / f"chunk_{idx:03d}.sdf"
241
+ write_sdf_blocks(chunk_blocks, chunk)
242
+ chunks.append(chunk)
243
+
244
+ def run_one(idx: int, chunk: Path) -> tuple[int, CommandRecord, Path]:
245
+ prefix = work / f"{out_prefix}_chunk_{idx:03d}"
246
+ rec = runner.run(
247
+ f"rbdock_chunk_{idx:03d}",
248
+ [rbdock, "-r", str(prm.name), "-p", str(dock_prm), "-n", str(int(n_runs)), "-i", str(chunk.relative_to(work)), "-o", str(prefix.name)],
249
+ work,
250
+ work / f"{out_prefix}_chunk_{idx:03d}.stdout.log",
251
+ work / f"{out_prefix}_chunk_{idx:03d}.stderr.log",
252
+ env=_rdock_env(),
253
+ )
254
+ return idx, rec, prefix.with_suffix(".sd")
255
+
256
+ outputs: dict[int, Path] = {}
257
+ records: list[CommandRecord] = []
258
+ with ThreadPoolExecutor(max_workers=chunk_count) as pool:
259
+ futures = [pool.submit(run_one, idx, chunk) for idx, chunk in enumerate(chunks)]
260
+ for fut in as_completed(futures):
261
+ idx, rec, out_sd = fut.result()
262
+ fail_if_bad_command(rec, f"rbdock chunk {idx}")
263
+ require_file(out_sd, f"rDock output chunk {idx}")
264
+ outputs[idx] = out_sd
265
+ records.append(rec)
266
+ merged = work / f"{out_prefix}.sd"
267
+ all_blocks: list[str] = []
268
+ for idx in sorted(outputs):
269
+ all_blocks.extend(split_sdf_file(outputs[idx]))
270
+ write_sdf_blocks(all_blocks, merged)
271
+ return merged, records
272
+
273
+
274
+ def _parse_rmsd_stdout(text: str) -> list[float]:
275
+ vals: list[float] = []
276
+ for token in re.findall(r"[-+]?(?:\d+\.\d+|\d+)", text):
277
+ try:
278
+ value = float(token)
279
+ except Exception:
280
+ continue
281
+ if 0.0 <= value < 100.0:
282
+ vals.append(value)
283
+ return vals
284
+
285
+
286
+ def _sdf_pose_coords(path: Path) -> list[list[list[float]]]:
287
+ poses: list[list[list[float]]] = []
288
+ for block in split_sdf_file(path):
289
+ lines = block.splitlines()
290
+ if len(lines) < 4:
291
+ continue
292
+ try:
293
+ atom_count = int(lines[3][0:3])
294
+ except Exception:
295
+ continue
296
+ coords: list[list[float]] = []
297
+ for line in lines[4 : 4 + atom_count]:
298
+ try:
299
+ coords.append([float(line[0:10]), float(line[10:20]), float(line[20:30])])
300
+ except Exception:
301
+ parts = line.split()
302
+ if len(parts) >= 3:
303
+ try:
304
+ coords.append([float(parts[0]), float(parts[1]), float(parts[2])])
305
+ except Exception:
306
+ continue
307
+ if coords:
308
+ poses.append(coords)
309
+ return poses
310
+
311
+
312
+ def _rmsd_same_order(a: list[list[float]], b: list[list[float]]) -> float:
313
+ n = min(len(a), len(b))
314
+ if n == 0:
315
+ return float("nan")
316
+ return (sum((a[i][0] - b[i][0]) ** 2 + (a[i][1] - b[i][1]) ** 2 + (a[i][2] - b[i][2]) ** 2 for i in range(n)) / n) ** 0.5
317
+
318
+
319
+ def _internal_rmsds(reference_sdf: Path, poses_sdf: Path) -> list[float]:
320
+ ref = _sdf_pose_coords(reference_sdf)
321
+ poses = _sdf_pose_coords(poses_sdf)
322
+ if not ref:
323
+ return []
324
+ return [_rmsd_same_order(ref[0], pose) for pose in poses]
325
+
326
+
327
+ def _write_csv(path: Path, rows: list[dict[str, object]]) -> None:
328
+ path.parent.mkdir(parents=True, exist_ok=True)
329
+ fields: list[str] = []
330
+ for row in rows:
331
+ for k in row:
332
+ if k not in fields:
333
+ fields.append(k)
334
+ with path.open("w", encoding="utf-8", newline="") as handle:
335
+ writer = csv.DictWriter(handle, fieldnames=fields)
336
+ writer.writeheader()
337
+ writer.writerows(rows)
338
+
339
+
340
+ def _empty_standard_outputs(root: Path) -> None:
341
+ for name in ("target", "ligands", "rdock", "poses", "tables", "metrics", "plots"):
342
+ (root / name).mkdir(parents=True, exist_ok=True)
343
+
344
+
345
+ def _copy_receptor_to_target(work: Path, system: ValidationSystem, root: Path) -> Path | None:
346
+ target_dir = root / "target"
347
+ target_dir.mkdir(parents=True, exist_ok=True)
348
+ prm_stem = Path(system.receptor_prm).stem
349
+ candidates = [
350
+ work / f"{prm_stem}.mol2",
351
+ work / f"{system.system_id}_rdock.mol2",
352
+ work / f"{system.system_id}.mol2",
353
+ ]
354
+ candidates.extend(sorted(work.glob("*.mol2")))
355
+ receptor = _find_first(candidates)
356
+ if receptor is None:
357
+ return None
358
+ dst = target_dir / receptor.name
359
+ shutil.copy2(receptor, dst)
360
+ return dst
361
+
362
+
363
+ def validate_astex_system(
364
+ system: ValidationSystem,
365
+ root: Path,
366
+ n_runs: int,
367
+ jobs: int,
368
+ force: bool = False,
369
+ ) -> dict[str, object]:
370
+ _empty_standard_outputs(root)
371
+ work = _copy_system(Path(system.path), root, force=force)
372
+ _copy_receptor_to_target(work, system, root)
373
+ runner = CommandRunner(root / "commands.log")
374
+ for exe in ("rbcavity", "rbdock", "sdsort", "sdrmsd"):
375
+ require_executable(exe)
376
+ prm = require_file(work / Path(system.receptor_prm).name, "ASTEX rDock receptor prm")
377
+ dock_prm = require_file(system.dock_prm, "ASTEX dock.prm")
378
+ ligand = require_file(work / Path(system.ligand_sdf).name, "ASTEX ligand SDF")
379
+ rec = runner.run("rbcavity", ["rbcavity", "-r", prm.name, "-was"], work, work / "rbcavity.stdout.log", work / "rbcavity.stderr.log", env=_rdock_env())
380
+ fail_if_bad_command(rec, "ASTEX rbcavity")
381
+ out_sd, _ = _run_rbdock_parallel(runner, work, prm, dock_prm, ligand, f"{system.system_id}_docking_out", n_runs, jobs)
382
+ rec = runner.run(
383
+ "sdsort",
384
+ ["/bin/sh", "-c", f"sdsort -n -f'SCORE' {out_sd.name} > {system.system_id}_docking_out_sorted.sd"],
385
+ work,
386
+ work / "sdsort.stdout.log",
387
+ work / "sdsort.stderr.log",
388
+ env=_rdock_env(),
389
+ )
390
+ fail_if_bad_command(rec, "ASTEX sdsort")
391
+ sorted_sd = require_file(work / f"{system.system_id}_docking_out_sorted.sd", "ASTEX sorted SDF")
392
+ rmsd_source = "sdrmsd"
393
+ rmsd_diagnostic = ""
394
+ rec = runner.run("sdrmsd", ["sdrmsd", ligand.name, sorted_sd.name], work, work / "sdrmsd.stdout.log", work / "sdrmsd.stderr.log", env=_rdock_env())
395
+ try:
396
+ fail_if_bad_command(rec, "ASTEX sdrmsd")
397
+ rmsds = _parse_rmsd_stdout(Path(rec.stdout_log).read_text(encoding="utf-8", errors="ignore"))
398
+ except RDockPipelineError as exc:
399
+ rmsd_source = "internal_same_atom_order_sdf_rmsd_after_sdrmsd_failure"
400
+ rmsd_diagnostic = str(exc)
401
+ rmsds = _internal_rmsds(ligand, sorted_sd)
402
+ top1 = rmsds[0] if rmsds else float("nan")
403
+ best = min(rmsds) if rmsds else float("nan")
404
+ shutil.copy2(out_sd, root / "poses" / "all_poses.sdf")
405
+ shutil.copy2(sorted_sd, root / "poses" / "best_per_ligand.sdf")
406
+ records = parse_rdock_sdf_records(out_sd)
407
+ sorted_records = parse_rdock_sdf_records(sorted_sd)
408
+ best_records = best_per_ligand(records)
409
+ write_rows_csv(records_to_rows(records), root / "tables" / "scores_long.csv")
410
+ write_rows_csv(records_to_rows(best_records), root / "tables" / "best_per_ligand.csv")
411
+ top1_score = sorted_records[0].numeric_tags.get("SCORE") if sorted_records else None
412
+ row = {
413
+ "system_id": system.system_id,
414
+ "top1_rmsd": top1,
415
+ "best_of_n_rmsd": best,
416
+ "top1_SCORE": top1_score,
417
+ "success_top1_rmsd_le_2A": bool(top1 <= 2.0),
418
+ "success_best_rmsd_le_2A": bool(best <= 2.0),
419
+ "n_poses": len(records),
420
+ "status": "success",
421
+ "rmsd_source": rmsd_source,
422
+ "rmsd_diagnostic": rmsd_diagnostic,
423
+ }
424
+ _write_csv(root / "tables" / "astex_system_summary.csv", [row])
425
+ metrics = {
426
+ **row,
427
+ "median_top1_rmsd": top1,
428
+ "median_best_rmsd": best,
429
+ "n_systems_total": 1,
430
+ "n_systems_successful": 1,
431
+ "n_systems_failed": 0,
432
+ "n_poses_total": len(records),
433
+ }
434
+ (root / "metrics" / "validation_metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8")
435
+ (root / "metrics" / "enrichment.csv").write_text("", encoding="utf-8")
436
+ plots = plot_astex_outputs(root / "tables" / "astex_system_summary.csv", root / "plots")
437
+ _write_validation_report(root, "ASTEX", [system], runner.records, metrics, plots)
438
+ return metrics
439
+
440
+
441
+ def _read_dud_labels(work: Path) -> dict[str, int]:
442
+ labels: dict[str, int] = {}
443
+ for name, value in (("ligands.txt", 1), ("actives.txt", 1), ("decoys.txt", 0)):
444
+ p = work / name
445
+ if not p.exists():
446
+ continue
447
+ for line in p.read_text(encoding="utf-8", errors="ignore").splitlines():
448
+ parts = line.strip().split()
449
+ if parts:
450
+ labels[parts[0]] = value
451
+ return labels
452
+
453
+
454
+ def validate_dud_system(system: ValidationSystem, root: Path, n_runs: int, jobs: int, force: bool = False) -> dict[str, object]:
455
+ _empty_standard_outputs(root)
456
+ work = _copy_system(Path(system.path), root, force=force)
457
+ _copy_receptor_to_target(work, system, root)
458
+ runner = CommandRunner(root / "commands.log")
459
+ for exe in ("rbcavity", "rbdock", "sdsort", "sdfilter", "sdreport"):
460
+ require_executable(exe)
461
+ prm = require_file(work / Path(system.receptor_prm).name, "DUD rDock receptor prm")
462
+ dock_prm = require_file(system.dock_prm, "DUD dock.prm")
463
+ ligprep = _gunzip_if_needed(work / Path(system.ligprep_sdf).name)
464
+ labels = _read_dud_labels(work)
465
+ if not labels:
466
+ raise RDockPipelineError(
467
+ "Missing DUD active/decoy label files for enrichment metrics.\n"
468
+ f"Expected `ligands.txt`/`actives.txt` and `decoys.txt` in: {work}\n"
469
+ "The official rDock ROC workflow requires these files to assign IsActive labels.\n"
470
+ "Add the label files for this DUD system, then rerun the same validate-rdock command."
471
+ )
472
+ rec = runner.run("rbcavity", ["rbcavity", "-r", prm.name, "-was"], work, work / "rbcavity.stdout.log", work / "rbcavity.stderr.log", env=_rdock_env())
473
+ fail_if_bad_command(rec, "DUD rbcavity")
474
+ out_sd, _ = _run_rbdock_parallel(runner, work, prm, dock_prm, ligprep, f"{system.system_id}_docking_out", n_runs, jobs)
475
+ records = parse_rdock_sdf_records(out_sd, require_score=True)
476
+ best_records = best_per_ligand(records)
477
+ best_sd = write_sdf_records(best_records, work / f"{system.system_id}_1poseperlig.sd")
478
+ rows = records_to_rows(best_records)
479
+ for row in rows:
480
+ row["label"] = labels.get(str(row["ligand_id"]), 0)
481
+ duplicate_count = len(records) - len({r.ligand_id for r in records})
482
+ metrics = validation_metrics_from_rows(rows)
483
+ metrics.update(
484
+ {
485
+ "active_count": sum(int(row.get("label", 0)) for row in rows),
486
+ "decoy_count": sum(1 - int(row.get("label", 0)) for row in rows),
487
+ "attempted_ligands": len(split_sdf_file(ligprep)),
488
+ "successful_ligands": len(rows),
489
+ "failed_ligands": max(0, len(split_sdf_file(ligprep)) - len(rows)),
490
+ "duplicate_ligand_ids": duplicate_count,
491
+ "missing_SCORE_count": 0,
492
+ }
493
+ )
494
+ shutil.copy2(out_sd, root / "poses" / "all_poses.sdf")
495
+ shutil.copy2(best_sd, root / "poses" / "best_per_ligand.sdf")
496
+ write_rows_csv(records_to_rows(records), root / "tables" / "scores_long.csv")
497
+ write_rows_csv(rows, root / "tables" / "best_per_ligand.csv")
498
+ _write_csv(root / "metrics" / "enrichment.csv", enrichment_rows([float(r["SCORE"]) for r in rows], [int(r["label"]) for r in rows]))
499
+ (root / "metrics" / "validation_metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8")
500
+ plots = plot_dud_outputs(root / "tables" / "best_per_ligand.csv", root / "metrics" / "enrichment.csv", root / "plots")
501
+ _write_validation_report(root, "DUD", [system], runner.records, metrics, plots)
502
+ return metrics
503
+
504
+
505
+ def plan_validation(
506
+ set_name: str,
507
+ data_dir: str | Path,
508
+ systems: list[ValidationSystem],
509
+ out_dir: str | Path,
510
+ n_runs: int,
511
+ jobs: int | str,
512
+ cpu_fraction: float,
513
+ ) -> dict[str, object]:
514
+ resolved_jobs = resolve_jobs(jobs, cpu_fraction)
515
+ return {
516
+ "set": set_name,
517
+ "data_dir": str(data_dir),
518
+ "out": str(out_dir),
519
+ "n_runs": int(n_runs),
520
+ "jobs": resolved_jobs,
521
+ "system_count": len(systems),
522
+ "systems": [asdict(s) for s in systems],
523
+ "commands": [
524
+ f"rbcavity -r <system>_rdock.prm -was",
525
+ f"rbdock -r <system>_rdock.prm -p dock.prm -n {int(n_runs)} -i <ligands>.sd -o <out>",
526
+ "sdsort/sdrmsd for ASTEX or best-pose/enrichment reporting for DUD",
527
+ ],
528
+ }
529
+
530
+
531
+ def validate_many(
532
+ set_name: str,
533
+ data_dir: str | Path,
534
+ out_dir: str | Path,
535
+ system: str | None = None,
536
+ system_list: str | Path | None = None,
537
+ max_systems: int | None = None,
538
+ n_runs: int = 100,
539
+ jobs: int | str = "auto",
540
+ cpu_fraction: float = 0.85,
541
+ download_url: str | None = None,
542
+ download_if_missing: bool = False,
543
+ force: bool = False,
544
+ dry_run: bool = False,
545
+ plan_only: bool = False,
546
+ ) -> dict[str, object]:
547
+ root_data = ensure_validation_data(data_dir, set_name, download_url, download_if_missing, force=force)
548
+ systems = resolve_systems(root_data, set_name, system, system_list, max_systems)
549
+ plan = plan_validation(set_name, root_data, systems, out_dir, n_runs, jobs, cpu_fraction)
550
+ out = Path(out_dir)
551
+ if dry_run or plan_only:
552
+ out.mkdir(parents=True, exist_ok=True)
553
+ (out / "validation_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8")
554
+ return {"dry_run": bool(dry_run), "plan": plan}
555
+ if out.exists() and force:
556
+ shutil.rmtree(out)
557
+ out.mkdir(parents=True, exist_ok=True)
558
+ resolved_jobs = int(plan["jobs"])
559
+ rows: list[dict[str, object]] = []
560
+ failures: list[dict[str, object]] = []
561
+ metrics_by_system: list[dict[str, object]] = []
562
+ per_system_jobs = resolved_jobs if len(systems) == 1 else 1
563
+ system_order = {s.system_id: idx for idx, s in enumerate(systems)}
564
+
565
+ def run_system(s: ValidationSystem) -> tuple[int, ValidationSystem, dict[str, object] | None, dict[str, object], Exception | None]:
566
+ run_root = out / s.system_id if len(systems) > 1 else out
567
+ try:
568
+ if set_name.lower() == "astex":
569
+ metrics = validate_astex_system(s, run_root, n_runs=n_runs, jobs=per_system_jobs, force=force)
570
+ row = {
571
+ "system_id": s.system_id,
572
+ "top1_rmsd": metrics.get("top1_rmsd"),
573
+ "best_of_n_rmsd": metrics.get("best_of_n_rmsd"),
574
+ "top1_SCORE": metrics.get("top1_SCORE"),
575
+ "success_top1_rmsd_le_2A": metrics.get("success_top1_rmsd_le_2A"),
576
+ "success_best_rmsd_le_2A": metrics.get("success_best_rmsd_le_2A"),
577
+ "n_poses": metrics.get("n_poses"),
578
+ "status": "success",
579
+ }
580
+ elif set_name.lower() == "dud":
581
+ metrics = validate_dud_system(s, run_root, n_runs=n_runs, jobs=per_system_jobs, force=force)
582
+ row = {"system_id": s.system_id, "status": "success", **metrics}
583
+ else:
584
+ raise RDockPipelineError(f"Unsupported validation set: {set_name}")
585
+ return system_order[s.system_id], s, metrics, row, None
586
+ except Exception as exc:
587
+ return system_order[s.system_id], s, None, {"system_id": s.system_id, "status": "failed", "error": str(exc)}, exc
588
+
589
+ max_system_workers = min(resolved_jobs, len(systems))
590
+ results: list[tuple[int, ValidationSystem, dict[str, object] | None, dict[str, object], Exception | None]] = []
591
+ if max_system_workers > 1:
592
+ with ThreadPoolExecutor(max_workers=max_system_workers) as pool:
593
+ futures = [pool.submit(run_system, s) for s in systems]
594
+ for fut in as_completed(futures):
595
+ results.append(fut.result())
596
+ else:
597
+ results = [run_system(s) for s in systems]
598
+
599
+ for _, s, metrics, row, exc in sorted(results, key=lambda item: item[0]):
600
+ rows.append(row)
601
+ if exc is not None:
602
+ failures.append({"system_id": s.system_id, "error": str(exc)})
603
+ continue
604
+ if metrics is not None:
605
+ metrics_by_system.append({"system_id": s.system_id, **metrics})
606
+
607
+ # Per-system outputs are written by each worker. The root directory stores
608
+ # aggregate summaries, plots, manifests, and reports.
609
+ _empty_standard_outputs(out)
610
+ _write_csv(out / "tables" / f"{set_name.lower()}_system_summary.csv", rows)
611
+ if set_name.lower() == "astex":
612
+ top1 = [float(r["top1_rmsd"]) for r in rows if r.get("status") == "success"]
613
+ best_vals = [float(r["best_of_n_rmsd"]) for r in rows if r.get("status") == "success"]
614
+ aggregate = {
615
+ "n_systems_total": len(systems),
616
+ "n_systems_successful": len(top1),
617
+ "n_systems_failed": len(failures),
618
+ "median_top1_rmsd": median(top1) if top1 else None,
619
+ "median_best_rmsd": median(best_vals) if best_vals else None,
620
+ "success_top1_rmsd_le_2A": sum(1 for x in top1 if x <= 2.0),
621
+ "success_best_rmsd_le_2A": sum(1 for x in best_vals if x <= 2.0),
622
+ "n_poses_total": sum(int(r.get("n_poses", 0) or 0) for r in rows),
623
+ "failures": failures,
624
+ }
625
+ plots = plot_astex_outputs(out / "tables" / f"{set_name.lower()}_system_summary.csv", out / "plots")
626
+ else:
627
+ aggregate = {
628
+ "n_systems_total": len(systems),
629
+ "n_systems_successful": len(metrics_by_system),
630
+ "n_systems_failed": len(failures),
631
+ "failures": failures,
632
+ }
633
+ plots = []
634
+ (out / "metrics" / "validation_metrics.json").write_text(json.dumps(aggregate, indent=2), encoding="utf-8")
635
+ _write_validation_report(out, set_name.upper(), systems, [], aggregate, plots)
636
+ return {"metrics": aggregate, "systems": rows}
637
+
638
+
639
+ def validate_astex(data_dir: str | Path, system: str, out_dir: str | Path, n_runs: int = 100, jobs: int | str = 1) -> dict[str, object]:
640
+ result = validate_many("astex", data_dir, out_dir, system=system, n_runs=n_runs, jobs=jobs)
641
+ return dict(result.get("metrics", {}))
642
+
643
+
644
+ def validate_dud(data_dir: str | Path, system: str, out_dir: str | Path, n_runs: int = 100, jobs: int | str = 1) -> dict[str, object]:
645
+ result = validate_many("dud", data_dir, out_dir, system=system, n_runs=n_runs, jobs=jobs)
646
+ return dict(result.get("metrics", {}))
647
+
648
+
649
+ def _write_validation_report(
650
+ root: Path,
651
+ set_name: str,
652
+ systems: list[ValidationSystem],
653
+ commands: list[CommandRecord],
654
+ metrics: dict[str, object],
655
+ plots: list[str],
656
+ ) -> None:
657
+ manifest = {
658
+ "validation_set": set_name,
659
+ "engine": "real-rdock-official-workflow",
660
+ "systems": [asdict(s) for s in systems],
661
+ "commands": [c.to_dict() for c in commands],
662
+ "metrics": metrics,
663
+ "plots": plots,
664
+ "artifacts": {
665
+ "report": str(root / "report.md"),
666
+ "manifest": str(root / "manifest.json"),
667
+ "config": str(root / "config.yaml"),
668
+ "commands": str(root / "commands.log"),
669
+ "tables": str(root / "tables"),
670
+ "metrics": str(root / "metrics"),
671
+ "plots": str(root / "plots"),
672
+ },
673
+ }
674
+ (root / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
675
+ (root / "config.yaml").write_text(f"validation_set: {set_name}\nsystems: {[s.system_id for s in systems]}\n", encoding="utf-8")
676
+ top_lines = []
677
+ for item in list(metrics.items())[:20]:
678
+ top_lines.append(f"- {item[0]}: `{item[1]}`")
679
+ plot_lines = [f"- `{p}`" for p in plots] or ["- No plots generated; see `plots/skipped_plots.json` if present."]
680
+ (root / "report.md").write_text(
681
+ "\n".join(
682
+ [
683
+ f"# {set_name} rDock Validation",
684
+ "",
685
+ "## Input Summary",
686
+ f"- Systems: `{', '.join(s.system_id for s in systems)}`",
687
+ f"- System count: `{len(systems)}`",
688
+ "",
689
+ "## Metrics",
690
+ *top_lines,
691
+ "",
692
+ "## Commands",
693
+ f"- Command log: `{root / 'commands.log'}`",
694
+ "- Per-system command logs are stored under each system run directory for multi-system runs.",
695
+ "",
696
+ "## Plots",
697
+ *plot_lines,
698
+ "",
699
+ "## Skipped Steps",
700
+ "- Browser bundle export was removed from the production pipeline.",
701
+ "- No mock docking or surrogate scores are used.",
702
+ "",
703
+ "## Diagnostics",
704
+ f"- Failures: `{json.dumps(metrics.get('failures', []))}`",
705
+ ]
706
+ ),
707
+ encoding="utf-8",
708
+ )
environment.yml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: portable-rdock-pipeline
2
+ channels:
3
+ - conda-forge
4
+ dependencies:
5
+ - python=3.11
6
+ - pip
7
+ - numpy
8
+ - pandas
9
+ - matplotlib
10
+ - pyyaml
11
+ - rdkit
12
+ - requests
libs/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Top-level package for modular docking pipeline libraries."""
libs/adaptive/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adaptive scheduling, clustering, and surrogate learning components."""
2
+
3
+ from .clustering import cluster_ligands_butina
4
+ from .epsilon_regret import EpsilonRegretConfig, EpsilonRegretController
5
+ from .hyperclustering import hypercluster_representatives
6
+ from .scheduler import AdaptiveScheduler
7
+ from .surrogate_model import SurrogateModel
8
+ from .thresholding import DynamicEarlyStopController, DynamicThresholdConfig
9
+
10
+ __all__ = [
11
+ "AdaptiveScheduler",
12
+ "DynamicEarlyStopController",
13
+ "DynamicThresholdConfig",
14
+ "EpsilonRegretConfig",
15
+ "EpsilonRegretController",
16
+ "SurrogateModel",
17
+ "cluster_ligands_butina",
18
+ "hypercluster_representatives",
19
+ ]
libs/adaptive/clustering.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, Iterable, List, Sequence
4
+
5
+ import numpy as np
6
+ from rdkit import DataStructs
7
+ from rdkit.Chem import rdchem
8
+ from rdkit.ML.Cluster import Butina
9
+
10
+
11
+ def _np_to_explicit_bitvect(fp: np.ndarray) -> DataStructs.ExplicitBitVect:
12
+ bitvect = DataStructs.ExplicitBitVect(fp.shape[0])
13
+ on_bits = np.where(fp > 0)[0]
14
+ for idx in on_bits:
15
+ bitvect.SetBit(int(idx))
16
+ return bitvect
17
+
18
+
19
+ def cluster_ligands_butina(
20
+ ligand_ids: Sequence[str],
21
+ fingerprints: Sequence[np.ndarray],
22
+ cutoff: float = 0.35,
23
+ ) -> Dict[str, int]:
24
+ """Cluster ligands with Butina on Tanimoto distance over Morgan fingerprints."""
25
+ if not ligand_ids:
26
+ return {}
27
+ if len(ligand_ids) != len(fingerprints):
28
+ raise ValueError("ligand_ids and fingerprints must have same length")
29
+
30
+ fp_bv = [_np_to_explicit_bitvect(np.asarray(fp, dtype=int)) for fp in fingerprints]
31
+
32
+ dists: List[float] = []
33
+ for i in range(1, len(fp_bv)):
34
+ sims = DataStructs.BulkTanimotoSimilarity(fp_bv[i], fp_bv[:i])
35
+ dists.extend([1.0 - x for x in sims])
36
+
37
+ clusters = Butina.ClusterData(dists, len(fp_bv), cutoff, isDistData=True)
38
+
39
+ mapping: Dict[str, int] = {}
40
+ for c_idx, cluster in enumerate(clusters):
41
+ for member in cluster:
42
+ mapping[ligand_ids[member]] = c_idx
43
+
44
+ # Ensure all ligands map to a cluster, even edge cases.
45
+ for idx, ligand_id in enumerate(ligand_ids):
46
+ mapping.setdefault(ligand_id, max(mapping.values(), default=-1) + idx + 1)
47
+ return mapping
libs/adaptive/diversity.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable
4
+
5
+ import numpy as np
6
+
7
+
8
+ def _tanimoto(fp_a: np.ndarray, fp_b: np.ndarray) -> float:
9
+ inter = float(np.sum((fp_a > 0) & (fp_b > 0)))
10
+ union = float(np.sum((fp_a > 0) | (fp_b > 0)))
11
+ if union == 0:
12
+ return 0.0
13
+ return inter / union
14
+
15
+
16
+ def selection_diversity(fingerprints: Iterable[np.ndarray]) -> float:
17
+ fps = list(fingerprints)
18
+ if len(fps) < 2:
19
+ return 0.0
20
+ distances = []
21
+ for i in range(len(fps)):
22
+ for j in range(i + 1, len(fps)):
23
+ distances.append(1.0 - _tanimoto(fps[i], fps[j]))
24
+ return float(np.mean(distances)) if distances else 0.0
libs/adaptive/epsilon_regret.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, Iterable, List, Sequence
5
+
6
+ import numpy as np
7
+
8
+
9
+ @dataclass
10
+ class EpsilonRegretConfig:
11
+ epsilon_quality: float = 0.10
12
+ acceptable_regret: float = 0.10
13
+ min_budget: int = 250
14
+ max_budget: int = 10000
15
+ min_model_weight: float = 0.25
16
+ patience_rounds: int = 6
17
+ min_improvement: float = 0.02
18
+ uncertainty_multiplier: float = 0.50
19
+ min_cluster_coverage: float = 0.20
20
+ min_hypercluster_coverage: float = 0.20
21
+
22
+
23
+ class EpsilonRegretController:
24
+ """
25
+ Budget-aware stop controller with epsilon-regret semantics.
26
+
27
+ Online intent:
28
+ stop when estimated remaining gain is small relative to current best score,
29
+ after minimum exploration and coverage constraints are satisfied.
30
+ """
31
+
32
+ def __init__(self, config: EpsilonRegretConfig | None = None) -> None:
33
+ self.config = config or EpsilonRegretConfig()
34
+ self.best_score = np.inf
35
+ self.stagnant_rounds = 0
36
+ self.history: List[Dict[str, float | int | bool | str]] = []
37
+
38
+ @staticmethod
39
+ def _mean_or_nan(values: Sequence[float]) -> float:
40
+ arr = np.asarray(values, dtype=float)
41
+ if arr.size == 0:
42
+ return float("nan")
43
+ return float(np.nanmean(arr))
44
+
45
+ @staticmethod
46
+ def _estimate_remaining_gain(
47
+ best_score: float,
48
+ expected_remaining_scores: Iterable[float],
49
+ uncertainty_scores: Iterable[float],
50
+ uncertainty_multiplier: float,
51
+ ) -> float:
52
+ pred = np.asarray(list(expected_remaining_scores), dtype=float)
53
+ unc = np.asarray(list(uncertainty_scores), dtype=float)
54
+ if pred.size == 0:
55
+ return float("inf")
56
+ if unc.size != pred.size:
57
+ unc = np.full(pred.shape[0], np.nanmean(unc) if unc.size else 1.0, dtype=float)
58
+ optimistic = pred - float(max(0.0, uncertainty_multiplier)) * np.abs(unc)
59
+ optimistic_best = float(np.nanmin(optimistic)) if np.isfinite(optimistic).any() else float(np.nanmin(pred))
60
+ if not np.isfinite(optimistic_best) or not np.isfinite(best_score):
61
+ return float("inf")
62
+ # lower score is better
63
+ return float(max(0.0, best_score - optimistic_best))
64
+
65
+ def update(
66
+ self,
67
+ *,
68
+ round_idx: int,
69
+ n_evaluated: int,
70
+ best_score_now: float,
71
+ recent_scores: Sequence[float],
72
+ model_weight: float,
73
+ cluster_coverage: float,
74
+ hypercluster_coverage: float,
75
+ expected_remaining_scores: Iterable[float],
76
+ uncertainty_scores: Iterable[float],
77
+ time_importance: float,
78
+ budget_cap: int,
79
+ ) -> Dict[str, float | int | bool | str]:
80
+ cfg = self.config
81
+ ti = float(max(0.0, min(1.0, float(time_importance))))
82
+
83
+ if np.isfinite(self.best_score):
84
+ improvement = float(self.best_score - best_score_now)
85
+ else:
86
+ improvement = float("inf")
87
+
88
+ if improvement > float(cfg.min_improvement):
89
+ self.stagnant_rounds = 0
90
+ else:
91
+ self.stagnant_rounds += 1
92
+ self.best_score = min(float(self.best_score), float(best_score_now))
93
+
94
+ epsilon_rel = float(max(cfg.epsilon_quality, cfg.acceptable_regret))
95
+ # Higher time importance permits slightly larger acceptable residual gain.
96
+ epsilon_rel *= float(1.0 + 0.5 * ti)
97
+ epsilon_abs = float(epsilon_rel * max(1.0, abs(float(self.best_score))))
98
+
99
+ remaining_gain = self._estimate_remaining_gain(
100
+ best_score=float(self.best_score),
101
+ expected_remaining_scores=expected_remaining_scores,
102
+ uncertainty_scores=uncertainty_scores,
103
+ uncertainty_multiplier=float(cfg.uncertainty_multiplier),
104
+ )
105
+ regret_ratio_proxy = float(remaining_gain / max(1.0, abs(float(self.best_score))))
106
+
107
+ budget_floor = int(max(1, cfg.min_budget))
108
+ budget_ceiling = int(min(cfg.max_budget, budget_cap))
109
+ budget_ready = int(n_evaluated) >= budget_floor
110
+ model_ready = float(model_weight) >= float(cfg.min_model_weight)
111
+ coverage_ready = bool(
112
+ float(cluster_coverage) >= float(cfg.min_cluster_coverage)
113
+ and float(hypercluster_coverage) >= float(cfg.min_hypercluster_coverage)
114
+ )
115
+ stagnation_ready = int(self.stagnant_rounds) >= int(cfg.patience_rounds)
116
+
117
+ hit_budget_ceiling = int(n_evaluated) >= int(budget_ceiling)
118
+ epsilon_ready = bool(np.isfinite(remaining_gain) and remaining_gain <= epsilon_abs)
119
+ stop = bool(hit_budget_ceiling or (budget_ready and model_ready and coverage_ready and stagnation_ready and epsilon_ready))
120
+
121
+ if hit_budget_ceiling:
122
+ reason = "max_budget_reached"
123
+ elif not budget_ready:
124
+ reason = "below_min_budget"
125
+ elif not model_ready:
126
+ reason = "model_not_ready"
127
+ elif not coverage_ready:
128
+ reason = "coverage_not_ready"
129
+ elif not stagnation_ready:
130
+ reason = "insufficient_stagnation_evidence"
131
+ elif not epsilon_ready:
132
+ reason = "remaining_gain_above_epsilon"
133
+ else:
134
+ reason = "epsilon_regret_stop"
135
+
136
+ rec = {
137
+ "round_idx": int(round_idx),
138
+ "n_evaluated": int(n_evaluated),
139
+ "best_score": float(self.best_score),
140
+ "recent_mean_score": self._mean_or_nan(recent_scores),
141
+ "model_weight": float(model_weight),
142
+ "cluster_coverage": float(cluster_coverage),
143
+ "hypercluster_coverage": float(hypercluster_coverage),
144
+ "stagnant_rounds": int(self.stagnant_rounds),
145
+ "epsilon_abs": float(epsilon_abs),
146
+ "estimated_remaining_gain": float(remaining_gain),
147
+ "regret_ratio_proxy": float(regret_ratio_proxy),
148
+ "budget_floor": int(budget_floor),
149
+ "budget_ceiling": int(budget_ceiling),
150
+ "budget_ready": bool(budget_ready),
151
+ "model_ready": bool(model_ready),
152
+ "coverage_ready": bool(coverage_ready),
153
+ "stagnation_ready": bool(stagnation_ready),
154
+ "epsilon_ready": bool(epsilon_ready),
155
+ "stop": bool(stop),
156
+ "reason": reason,
157
+ }
158
+ self.history.append(rec)
159
+ return rec
160
+
libs/adaptive/features.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, Iterable, List, Tuple
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from rdkit import Chem
9
+ from rdkit.Chem import AllChem, Descriptors, Lipinski, MolSurf, rdMolDescriptors
10
+ from rdkit.Chem.Scaffolds import MurckoScaffold
11
+ from rdkit.DataStructs import TanimotoSimilarity
12
+
13
+ try:
14
+ from rdkit.Chem import rdFreeSASA
15
+ except Exception: # pragma: no cover
16
+ rdFreeSASA = None # type: ignore[assignment]
17
+
18
+
19
+ @dataclass
20
+ class FeatureValue:
21
+ value: float | None
22
+ available: bool
23
+ source: str
24
+ feature_type: str
25
+
26
+
27
+ @dataclass
28
+ class FeatureBundle:
29
+ object_id: str
30
+ features: Dict[str, FeatureValue]
31
+
32
+ def to_records(self, channel: str, round_idx: int | None = None) -> List[dict]:
33
+ rows: List[dict] = []
34
+ for name, fv in sorted(self.features.items()):
35
+ rows.append(
36
+ {
37
+ "object_id": self.object_id,
38
+ "round": round_idx,
39
+ "channel": channel,
40
+ "feature_name": name,
41
+ "value": fv.value,
42
+ "available": bool(fv.available),
43
+ "source": fv.source,
44
+ "feature_type": fv.feature_type,
45
+ }
46
+ )
47
+ return rows
48
+
49
+
50
+ def _fv(value: float | None, available: bool, source: str, feature_type: str) -> FeatureValue:
51
+ return FeatureValue(value=value, available=available, source=source, feature_type=feature_type)
52
+
53
+
54
+ def _safe_float(value: float | int | None) -> float | None:
55
+ if value is None:
56
+ return None
57
+ try:
58
+ v = float(value)
59
+ except Exception:
60
+ return None
61
+ if not np.isfinite(v):
62
+ return None
63
+ return v
64
+
65
+
66
+ def _compute_ligand_sasa(mol: Chem.Mol) -> Tuple[float | None, bool]:
67
+ if rdFreeSASA is None:
68
+ return None, False
69
+ try:
70
+ if mol.GetNumConformers() == 0:
71
+ m = Chem.AddHs(Chem.Mol(mol))
72
+ status = AllChem.EmbedMolecule(m, AllChem.ETKDGv3())
73
+ if int(status) != 0:
74
+ return None, False
75
+ else:
76
+ m = Chem.Mol(mol)
77
+
78
+ if m.GetNumConformers() == 0:
79
+ return None, False
80
+
81
+ radii = rdFreeSASA.classifyAtoms(m)
82
+ sasa = rdFreeSASA.CalcSASA(m, radii)
83
+ return _safe_float(sasa), True
84
+ except Exception:
85
+ return None, False
86
+
87
+
88
+ def build_ligand_feature_bundle(
89
+ ligand_id: str,
90
+ smiles: str,
91
+ fingerprint: np.ndarray,
92
+ reference_mol: Chem.Mol | None = None,
93
+ compute_partial_charges: bool = True,
94
+ compute_sasa: bool = True,
95
+ ) -> FeatureBundle:
96
+ mol = Chem.MolFromSmiles(smiles)
97
+ if mol is None:
98
+ raise ValueError(f"Invalid SMILES for ligand {ligand_id}: {smiles}")
99
+
100
+ m_h = Chem.AddHs(Chem.Mol(mol))
101
+ if compute_partial_charges:
102
+ try:
103
+ AllChem.ComputeGasteigerCharges(m_h)
104
+ partial_charges = []
105
+ for atom in m_h.GetAtoms():
106
+ prop = atom.GetProp("_GasteigerCharge") if atom.HasProp("_GasteigerCharge") else "nan"
107
+ try:
108
+ q = float(prop)
109
+ except Exception:
110
+ continue
111
+ if np.isfinite(q):
112
+ partial_charges.append(q)
113
+ if partial_charges:
114
+ mean_abs_q = float(np.mean(np.abs(partial_charges)))
115
+ total_q = float(np.sum(partial_charges))
116
+ has_q = True
117
+ else:
118
+ mean_abs_q = None
119
+ total_q = None
120
+ has_q = False
121
+ except Exception:
122
+ mean_abs_q = None
123
+ total_q = None
124
+ has_q = False
125
+ else:
126
+ mean_abs_q = None
127
+ total_q = None
128
+ has_q = False
129
+
130
+ aromatic_rings = rdMolDescriptors.CalcNumAromaticRings(mol)
131
+ formal_charge = Chem.GetFormalCharge(mol)
132
+ heavy_atoms = mol.GetNumHeavyAtoms()
133
+ frac_csp3 = rdMolDescriptors.CalcFractionCSP3(mol)
134
+ bertz_ct = Descriptors.BertzCT(mol)
135
+ balaban_j = Descriptors.BalabanJ(mol)
136
+ topological_complexity = rdMolDescriptors.CalcChi0v(mol)
137
+
138
+ if compute_sasa:
139
+ ligand_sasa, has_sasa = _compute_ligand_sasa(m_h)
140
+ else:
141
+ ligand_sasa, has_sasa = None, False
142
+
143
+ reference_similarity = None
144
+ scaffold_match = None
145
+ chemical_distance = None
146
+ if reference_mol is not None:
147
+ fp_gen = AllChem.GetMorganGenerator(radius=2, fpSize=int(fingerprint.shape[0]))
148
+ ref_fp = fp_gen.GetFingerprint(reference_mol)
149
+ lig_fp = fp_gen.GetFingerprint(mol)
150
+ sim = TanimotoSimilarity(ref_fp, lig_fp)
151
+ reference_similarity = float(sim)
152
+ chemical_distance = float(1.0 - sim)
153
+
154
+ ref_scaffold = MurckoScaffold.MurckoScaffoldSmiles(mol=reference_mol)
155
+ lig_scaffold = MurckoScaffold.MurckoScaffoldSmiles(mol=mol)
156
+ scaffold_match = float(ref_scaffold == lig_scaffold)
157
+
158
+ features: Dict[str, FeatureValue] = {
159
+ "ligand_mw": _fv(_safe_float(Descriptors.MolWt(mol)), True, "rdkit", "exact"),
160
+ "ligand_logp": _fv(_safe_float(Descriptors.MolLogP(mol)), True, "rdkit", "exact"),
161
+ "ligand_tpsa": _fv(_safe_float(MolSurf.TPSA(mol)), True, "rdkit", "exact"),
162
+ "ligand_hbd": _fv(_safe_float(Lipinski.NumHDonors(mol)), True, "rdkit", "exact"),
163
+ "ligand_hba": _fv(_safe_float(Lipinski.NumHAcceptors(mol)), True, "rdkit", "exact"),
164
+ "ligand_rotatable_bonds": _fv(_safe_float(Lipinski.NumRotatableBonds(mol)), True, "rdkit", "exact"),
165
+ "ligand_aromatic_ring_count": _fv(_safe_float(aromatic_rings), True, "rdkit", "exact"),
166
+ "ligand_formal_charge": _fv(_safe_float(formal_charge), True, "rdkit", "exact"),
167
+ "ligand_partial_charge_abs_mean": _fv(mean_abs_q, has_q, "rdkit", "approximate"),
168
+ "ligand_partial_charge_total": _fv(total_q, has_q, "rdkit", "approximate"),
169
+ "ligand_topological_bertz": _fv(_safe_float(bertz_ct), True, "rdkit", "exact"),
170
+ "ligand_topological_balaban_j": _fv(_safe_float(balaban_j), True, "rdkit", "exact"),
171
+ "ligand_topological_chi0v": _fv(_safe_float(topological_complexity), True, "rdkit", "exact"),
172
+ "ligand_fraction_csp3": _fv(_safe_float(frac_csp3), True, "rdkit", "exact"),
173
+ "ligand_heavy_atom_count": _fv(_safe_float(heavy_atoms), True, "rdkit", "exact"),
174
+ "ligand_sasa": _fv(ligand_sasa, has_sasa, "geometric", "approximate"),
175
+ "similarity_to_reference": _fv(reference_similarity, reference_similarity is not None, "rdkit", "exact"),
176
+ "scaffold_match": _fv(scaffold_match, scaffold_match is not None, "rdkit", "exact"),
177
+ "chemical_distance_to_reference": _fv(chemical_distance, chemical_distance is not None, "rdkit", "exact"),
178
+ }
179
+
180
+ for i, bit in enumerate(fingerprint.astype(float).tolist()):
181
+ features[f"morgan_fp_{i:04d}"] = _fv(float(bit), True, "rdkit", "exact")
182
+
183
+ return FeatureBundle(object_id=ligand_id, features=features)
184
+
185
+
186
+ def build_protein_feature_bundle(target_id: str, sequence_features: Dict[str, float], structure_features: Dict[str, float]) -> FeatureBundle:
187
+ seq_len = float(sequence_features.get("seq_length", 1.0) or 1.0)
188
+ hydrophobic = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["A", "V", "I", "L", "M", "F", "W", "Y"])
189
+ charged = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["K", "R", "H", "D", "E"])
190
+ polar = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["S", "T", "N", "Q", "C"])
191
+
192
+ residue_count = float(structure_features.get("residue_count", 0.0))
193
+ mean_extent = float(structure_features.get("mean_spatial_extent", 0.0))
194
+ pocket_residues = float(structure_features.get("pocket_residue_count", 0.0))
195
+
196
+ approx_volume = float(max(0.0, mean_extent**3))
197
+ pocket_coverage = float(pocket_residues / max(residue_count, 1.0))
198
+
199
+ features = {
200
+ "pocket_hydrophobic_fraction": _fv(hydrophobic, True, "protein", "exact"),
201
+ "pocket_charged_fraction": _fv(charged, True, "protein", "exact"),
202
+ "pocket_polar_fraction": _fv(polar, True, "protein", "exact"),
203
+ "pocket_residue_count": _fv(residue_count, True, "protein", "exact"),
204
+ "pocket_volume_approx": _fv(approx_volume, True, "geometric", "approximate"),
205
+ "pocket_coverage_fraction": _fv(pocket_coverage, True, "geometric", "approximate"),
206
+ "pocket_sequence_length": _fv(seq_len, True, "protein", "exact"),
207
+ }
208
+ return FeatureBundle(object_id=target_id, features=features)
209
+
210
+
211
+ def build_complex_feature_bundle(
212
+ ligand_id: str,
213
+ docking_score: float,
214
+ interface_features: Dict[str, float],
215
+ ligand_bundle: FeatureBundle,
216
+ protein_bundle: FeatureBundle,
217
+ ) -> FeatureBundle:
218
+ lig = ligand_bundle.features
219
+ prot = protein_bundle.features
220
+
221
+ logp = lig.get("ligand_logp", _fv(None, False, "rdkit", "exact")).value or 0.0
222
+ tpsa = lig.get("ligand_tpsa", _fv(None, False, "rdkit", "exact")).value or 0.0
223
+ charge_mag = lig.get("ligand_partial_charge_abs_mean", _fv(None, False, "rdkit", "approximate")).value
224
+ heavy_atoms = lig.get("ligand_heavy_atom_count", _fv(None, False, "rdkit", "exact")).value or 1.0
225
+ pocket_volume = prot.get("pocket_volume_approx", _fv(None, False, "geometric", "approximate")).value or 1.0
226
+ pocket_hydrophobic = prot.get("pocket_hydrophobic_fraction", _fv(None, False, "protein", "exact")).value or 0.0
227
+
228
+ interface_contact_proxy = float(interface_features.get("interface_contact_proxy", max(0.0, -docking_score / 8.0)))
229
+ hbond_proxy = float(interface_features.get("hbond_proxy", max(0.0, tpsa / 100.0)))
230
+ shape_proxy = float(interface_features.get("shape_proxy", max(0.0, 1.0 / (1.0 + abs(docking_score)))))
231
+
232
+ contact_count = max(1.0, heavy_atoms * (0.3 + interface_contact_proxy))
233
+ polar_contacts = contact_count * min(1.0, tpsa / 120.0)
234
+ hydrophobic_contacts = contact_count * min(1.0, max(0.0, logp) / 6.0) * (0.5 + pocket_hydrophobic)
235
+ clash_count = max(0.0, docking_score - 9.0)
236
+ min_distance = max(1.5, 6.0 - interface_contact_proxy)
237
+ pocket_coverage = min(1.0, contact_count / max(10.0, pocket_volume / 20.0))
238
+ interaction_density = contact_count / max(1.0, pocket_volume)
239
+
240
+ ligand_sasa = lig.get("ligand_sasa", _fv(None, False, "geometric", "approximate")).value
241
+ protein_sasa = pocket_volume * 0.75
242
+ if ligand_sasa is not None:
243
+ complex_sasa = max(1.0, protein_sasa + ligand_sasa - 0.5 * contact_count)
244
+ buried_sasa = max(0.0, protein_sasa + ligand_sasa - complex_sasa)
245
+ burial_ratio = buried_sasa / max(ligand_sasa, 1e-6)
246
+ sasa_available = True
247
+ else:
248
+ complex_sasa = None
249
+ buried_sasa = None
250
+ burial_ratio = None
251
+ sasa_available = False
252
+
253
+ if charge_mag is not None:
254
+ electrostatic_proxy = -charge_mag * max(0.5, 5.0 - min_distance)
255
+ electro_available = True
256
+ else:
257
+ electrostatic_proxy = None
258
+ electro_available = False
259
+
260
+ contact_energy = -0.15 * contact_count
261
+ steric_penalty = 0.6 * clash_count
262
+ hydrophobic_proxy = -0.1 * hydrophobic_contacts
263
+ interaction_decomp = contact_energy + hydrophobic_proxy + (electrostatic_proxy or 0.0) + steric_penalty
264
+
265
+ features = {
266
+ "complex_contact_count": _fv(float(contact_count), True, "interaction", "proxy"),
267
+ "complex_hbond_proxy": _fv(float(hbond_proxy), True, "interaction", "proxy"),
268
+ "complex_polar_contact_count": _fv(float(polar_contacts), True, "interaction", "proxy"),
269
+ "complex_hydrophobic_contact_proxy": _fv(float(hydrophobic_contacts), True, "interaction", "proxy"),
270
+ "complex_clash_count": _fv(float(clash_count), True, "interaction", "proxy"),
271
+ "complex_min_distance": _fv(float(min_distance), True, "geometric", "approximate"),
272
+ "complex_pocket_coverage": _fv(float(pocket_coverage), True, "interaction", "proxy"),
273
+ "complex_interaction_density": _fv(float(interaction_density), True, "interaction", "proxy"),
274
+ "complex_ligand_sasa": _fv(_safe_float(ligand_sasa), ligand_sasa is not None, "geometric", "approximate"),
275
+ "complex_protein_sasa": _fv(_safe_float(protein_sasa), True, "geometric", "approximate"),
276
+ "complex_sasa": _fv(_safe_float(complex_sasa), sasa_available, "geometric", "approximate"),
277
+ "complex_buried_sasa": _fv(_safe_float(buried_sasa), sasa_available, "geometric", "approximate"),
278
+ "complex_shape_complementarity": _fv(float(shape_proxy), True, "geometric", "proxy"),
279
+ "complex_ligand_burial_ratio": _fv(_safe_float(burial_ratio), sasa_available, "geometric", "approximate"),
280
+ "energy_contact_proxy": _fv(float(contact_energy), True, "energy_proxy", "proxy"),
281
+ "energy_electrostatic_proxy": _fv(_safe_float(electrostatic_proxy), electro_available, "energy_proxy", "proxy"),
282
+ "energy_steric_clash_penalty": _fv(float(steric_penalty), True, "energy_proxy", "proxy"),
283
+ "energy_hydrophobic_proxy": _fv(float(hydrophobic_proxy), True, "energy_proxy", "proxy"),
284
+ "energy_interaction_decomposition": _fv(float(interaction_decomp), True, "energy_proxy", "proxy"),
285
+ }
286
+
287
+ return FeatureBundle(object_id=ligand_id, features=features)
288
+
289
+
290
+ def build_rdock_feature_bundle(
291
+ ligand_id: str,
292
+ parsed_row: Dict[str, float | int | str | bool | None],
293
+ ) -> FeatureBundle:
294
+ """Build a feature bundle from rDock-native and rDock-derived per-ligand outputs."""
295
+
296
+ def _as_feature(
297
+ key: str,
298
+ source: str,
299
+ ftype: str,
300
+ ) -> FeatureValue:
301
+ value = _safe_float(parsed_row.get(key)) # type: ignore[arg-type]
302
+ return _fv(value, value is not None, source, ftype if value is not None else "unavailable")
303
+
304
+ features: Dict[str, FeatureValue] = {
305
+ "rdock_total_score": _as_feature("rdock_total_score", "rdock_native", "exact"),
306
+ "rdock_pose_rank": _as_feature("rdock_pose_rank", "rdock_native", "exact"),
307
+ "n_generated_poses": _as_feature("n_generated_poses", "rdock_native", "exact"),
308
+ "best_pose_score": _as_feature("best_pose_score", "rdock_native", "exact"),
309
+ "mean_top3_pose_score": _as_feature("mean_top3_pose_score", "rdock_native", "exact"),
310
+ "mean_top5_pose_score": _as_feature("mean_top5_pose_score", "rdock_native", "exact"),
311
+ "std_top5_pose_score": _as_feature("std_top5_pose_score", "rdock_native", "exact"),
312
+ "pose_score_gap_1_2": _as_feature("pose_score_gap_1_2", "rdock_native", "exact"),
313
+ "rdock_restraint_term": _as_feature("rdock_restraint_term", "rdock_native", "exact"),
314
+ "rdock_internal_ligand_term": _as_feature("rdock_internal_ligand_term", "rdock_native", "exact"),
315
+ "rdock_polar_term": _as_feature("rdock_polar_term", "rdock_native", "exact"),
316
+ "rdock_vdw_term": _as_feature("rdock_vdw_term", "rdock_native", "exact"),
317
+ "top_pose_rmsd_consistency": _as_feature("top_pose_rmsd_consistency", "rdock_derived", "proxy"),
318
+ "contact_overlap_consistency": _as_feature("contact_overlap_consistency", "rdock_derived", "proxy"),
319
+ "hotspot_contact_frequency": _as_feature("hotspot_contact_frequency", "rdock_derived", "proxy"),
320
+ "subpocket_match_score": _as_feature("subpocket_match_score", "rdock_derived", "proxy"),
321
+ "replicate_mean_score": _as_feature("replicate_mean_score", "rdock_derived", "proxy"),
322
+ "replicate_score_variance": _as_feature("replicate_score_variance", "rdock_derived", "proxy"),
323
+ "replicate_consensus_score": _as_feature("replicate_consensus_score", "rdock_derived", "proxy"),
324
+ }
325
+ return FeatureBundle(object_id=ligand_id, features=features)
326
+
327
+
328
+ def merge_bundles(object_id: str, bundles: Iterable[FeatureBundle]) -> FeatureBundle:
329
+ merged: Dict[str, FeatureValue] = {}
330
+ for bundle in bundles:
331
+ merged.update(bundle.features)
332
+ return FeatureBundle(object_id=object_id, features=merged)
333
+
334
+
335
+ def bundles_to_wide_frames(
336
+ bundles: List[FeatureBundle],
337
+ ordered_feature_names: List[str] | None = None,
338
+ ) -> Tuple[pd.DataFrame, pd.DataFrame, List[str]]:
339
+ if not bundles:
340
+ return pd.DataFrame(), pd.DataFrame(), []
341
+
342
+ if ordered_feature_names is None:
343
+ feature_set = set()
344
+ for bundle in bundles:
345
+ feature_set.update(bundle.features.keys())
346
+ ordered_feature_names = sorted(feature_set)
347
+
348
+ value_rows = []
349
+ mask_rows = []
350
+ for bundle in bundles:
351
+ vrow = {"ligand_id": bundle.object_id}
352
+ mrow = {"ligand_id": bundle.object_id}
353
+ for name in ordered_feature_names:
354
+ fv = bundle.features.get(name)
355
+ if fv is None or not fv.available or fv.value is None:
356
+ vrow[name] = np.nan
357
+ mrow[f"mask_{name}"] = 0
358
+ else:
359
+ vrow[name] = float(fv.value)
360
+ mrow[f"mask_{name}"] = 1
361
+ value_rows.append(vrow)
362
+ mask_rows.append(mrow)
363
+
364
+ return pd.DataFrame(value_rows), pd.DataFrame(mask_rows), ordered_feature_names
365
+
366
+
367
+ def compute_feature_diagnostics(values_df: pd.DataFrame, masks_df: pd.DataFrame, target: pd.Series | None = None) -> pd.DataFrame:
368
+ if values_df.empty:
369
+ return pd.DataFrame(columns=["feature", "missing_frac", "mean", "std", "min", "max", "is_constant", "corr_to_target"])
370
+
371
+ numeric_cols = [c for c in values_df.columns if c != "ligand_id"]
372
+ rows = []
373
+ for col in numeric_cols:
374
+ vals = pd.to_numeric(values_df[col], errors="coerce")
375
+ mask_col = f"mask_{col}"
376
+ if mask_col in masks_df.columns:
377
+ missing_frac = 1.0 - float(pd.to_numeric(masks_df[mask_col], errors="coerce").mean())
378
+ else:
379
+ missing_frac = float(vals.isna().mean())
380
+
381
+ finite_vals = vals[np.isfinite(vals)]
382
+ is_constant = finite_vals.nunique(dropna=True) <= 1 if not finite_vals.empty else True
383
+
384
+ if target is not None and len(target) == len(vals):
385
+ target_num = pd.to_numeric(target, errors="coerce")
386
+ paired = pd.concat([vals, target_num], axis=1).dropna()
387
+ if paired.shape[0] >= 3 and paired.iloc[:, 0].nunique(dropna=True) > 1 and paired.iloc[:, 1].nunique(dropna=True) > 1:
388
+ corr = paired.iloc[:, 0].corr(paired.iloc[:, 1])
389
+ corr_val = float(corr) if corr is not None and np.isfinite(corr) else np.nan
390
+ else:
391
+ corr_val = np.nan
392
+ else:
393
+ corr_val = np.nan
394
+
395
+ rows.append(
396
+ {
397
+ "feature": col,
398
+ "missing_frac": float(missing_frac),
399
+ "mean": float(finite_vals.mean()) if not finite_vals.empty else np.nan,
400
+ "std": float(finite_vals.std()) if not finite_vals.empty else np.nan,
401
+ "min": float(finite_vals.min()) if not finite_vals.empty else np.nan,
402
+ "max": float(finite_vals.max()) if not finite_vals.empty else np.nan,
403
+ "is_constant": bool(is_constant),
404
+ "corr_to_target": corr_val,
405
+ }
406
+ )
407
+
408
+ return pd.DataFrame(rows).sort_values(["missing_frac", "feature"], ascending=[False, True]).reset_index(drop=True)
libs/adaptive/hyperclustering.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, Sequence
4
+
5
+ import numpy as np
6
+ from sklearn.cluster import AgglomerativeClustering
7
+
8
+
9
+ def hypercluster_representatives(
10
+ cluster_vectors: Dict[int, np.ndarray],
11
+ n_hyperclusters: int | None = None,
12
+ ) -> Dict[int, int]:
13
+ """Agglomerative clustering over cluster representative vectors."""
14
+ if not cluster_vectors:
15
+ return {}
16
+
17
+ cluster_ids = sorted(cluster_vectors)
18
+ x = np.vstack([cluster_vectors[cid] for cid in cluster_ids])
19
+
20
+ if len(cluster_ids) == 1:
21
+ return {cluster_ids[0]: 0}
22
+
23
+ n_clusters = n_hyperclusters or max(2, int(np.sqrt(len(cluster_ids))))
24
+ n_clusters = min(n_clusters, len(cluster_ids))
25
+
26
+ model = AgglomerativeClustering(n_clusters=n_clusters)
27
+ labels = model.fit_predict(x)
28
+ return {cluster_id: int(label) for cluster_id, label in zip(cluster_ids, labels)}
libs/adaptive/metrics.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, Iterable, Sequence
4
+
5
+ import numpy as np
6
+
7
+ from .diversity import selection_diversity
8
+
9
+
10
+ def clustering_metrics(cluster_map: Dict[str, int], hypercluster_map: Dict[int, int]) -> Dict[str, float]:
11
+ return {
12
+ "ligand_count": float(len(cluster_map)),
13
+ "cluster_count": float(len(set(cluster_map.values())) if cluster_map else 0),
14
+ "hypercluster_count": float(len(set(hypercluster_map.values())) if hypercluster_map else 0),
15
+ }
16
+
17
+
18
+ def score_metrics(scores: Sequence[float]) -> Dict[str, float]:
19
+ if not scores:
20
+ return {
21
+ "evaluated_ligand_count": 0.0,
22
+ "mean_score": 0.0,
23
+ "best_score": 0.0,
24
+ }
25
+ arr = np.asarray(scores, dtype=float)
26
+ return {
27
+ "evaluated_ligand_count": float(arr.size),
28
+ "mean_score": float(np.mean(arr)),
29
+ "best_score": float(np.min(arr)),
30
+ }
31
+
32
+
33
+ def enrichment_metrics(scores: Sequence[float], labels: Sequence[int] | None, topk: int = 10) -> Dict[str, float]:
34
+ if labels is None or not scores or len(labels) != len(scores):
35
+ return {"topk_hit_rate": 0.0, "enrichment_like": 0.0}
36
+
37
+ idx_sorted = np.argsort(np.asarray(scores, dtype=float))
38
+ labels_arr = np.asarray(labels, dtype=int)
39
+ k = min(topk, len(idx_sorted))
40
+ top_hits = int(np.sum(labels_arr[idx_sorted[:k]]))
41
+ baseline = float(np.mean(labels_arr)) if labels_arr.size else 0.0
42
+ hit_rate = top_hits / max(k, 1)
43
+ enrichment = (hit_rate / baseline) if baseline > 0 else 0.0
44
+ return {"topk_hit_rate": float(hit_rate), "enrichment_like": float(enrichment)}
45
+
46
+
47
+ def diversity_metric(selected_fingerprints: Iterable[np.ndarray]) -> Dict[str, float]:
48
+ return {"selection_diversity": selection_diversity(selected_fingerprints)}
libs/adaptive/policies.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass
7
+ class PrioritizationPolicy:
8
+ utility_weight: float = 0.55
9
+ uncertainty_weight: float = 0.2
10
+ diversity_weight: float = 0.15
11
+ cluster_bonus_weight: float = 0.1
12
+ conservative_deprioritize_quantile: float = 0.15
libs/adaptive/prioritization.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict
4
+
5
+ from .policies import PrioritizationPolicy
6
+
7
+
8
+ def compute_priority(
9
+ predicted_utility: float,
10
+ uncertainty: float,
11
+ diversity_gain: float,
12
+ cluster_bonus: float,
13
+ policy: PrioritizationPolicy,
14
+ ) -> float:
15
+ """Weighted priority function used by adaptive queueing."""
16
+ return (
17
+ policy.utility_weight * predicted_utility
18
+ + policy.uncertainty_weight * uncertainty
19
+ + policy.diversity_weight * diversity_gain
20
+ + policy.cluster_bonus_weight * cluster_bonus
21
+ )
22
+
23
+
24
+ def cluster_bonus(cluster_load: Dict[int, int], cluster_id: int) -> float:
25
+ load = cluster_load.get(cluster_id, 0)
26
+ return 1.0 / (1.0 + float(load))
libs/adaptive/queue_manager.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, Iterable, List
5
+
6
+ from .state import QueueItem
7
+
8
+ VALID_STATUSES = {"active", "deprioritized", "frozen", "completed"}
9
+
10
+
11
+ @dataclass
12
+ class QueueManager:
13
+ items: Dict[str, QueueItem]
14
+
15
+ @classmethod
16
+ def from_items(cls, items: Iterable[QueueItem]) -> "QueueManager":
17
+ return cls(items={item.ligand_id: item for item in items})
18
+
19
+ def set_status(self, ligand_id: str, status: str) -> None:
20
+ if status not in VALID_STATUSES:
21
+ raise ValueError(f"Invalid status: {status}")
22
+ self.items[ligand_id].status = status
23
+
24
+ def active_items(self) -> List[QueueItem]:
25
+ return [item for item in self.items.values() if item.status == "active"]
26
+
27
+ def completed_items(self) -> List[QueueItem]:
28
+ return [item for item in self.items.values() if item.status == "completed"]
29
+
30
+ def ordered_active(self) -> List[QueueItem]:
31
+ return sorted(self.active_items(), key=lambda item: item.priority, reverse=True)
libs/adaptive/scheduler.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ from typing import Dict, List
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ from .metrics import score_metrics
11
+ from .policies import PrioritizationPolicy
12
+ from .prioritization import cluster_bonus, compute_priority
13
+ from .queue_manager import QueueManager
14
+ from .state import QueueItem, SchedulerState
15
+ from .surrogate_model import SurrogateConfig, SurrogateModel
16
+ from .weight_schedule import WeightScheduleConfig, compute_model_weight
17
+
18
+
19
+ @dataclass
20
+ class SchedulerConfig:
21
+ batch_size: int = 8
22
+ init_coverage_fraction: float = 0.25
23
+ conservative_deprioritize: bool = True
24
+ state_path: str = "results/state.json"
25
+ weight_schedule: WeightScheduleConfig = field(default_factory=WeightScheduleConfig)
26
+
27
+
28
+ class AdaptiveScheduler:
29
+ """Adaptive batch scheduler with queue state and online masked surrogate updates."""
30
+
31
+ def __init__(
32
+ self,
33
+ config: SchedulerConfig | None = None,
34
+ policy: PrioritizationPolicy | None = None,
35
+ surrogate_config: SurrogateConfig | None = None,
36
+ ) -> None:
37
+ self.config = config or SchedulerConfig()
38
+ self.policy = policy or PrioritizationPolicy()
39
+ self.surrogate = SurrogateModel(surrogate_config)
40
+ self.state = SchedulerState()
41
+ self.queue_manager = QueueManager.from_items([])
42
+ self.last_model_weight: float = 0.0
43
+
44
+ def initialize(
45
+ self,
46
+ ligands_df: pd.DataFrame,
47
+ cluster_map: Dict[str, int],
48
+ hypercluster_for_cluster: Dict[int, int],
49
+ ) -> None:
50
+ items: List[QueueItem] = []
51
+ cluster_load: Dict[int, int] = {}
52
+
53
+ for row in ligands_df.itertuples(index=False):
54
+ ligand_id = str(row.ligand_id)
55
+ cluster_id = int(cluster_map.get(ligand_id, -1))
56
+ hypercluster_id = int(hypercluster_for_cluster.get(cluster_id, -1))
57
+ bonus = cluster_bonus(cluster_load, cluster_id)
58
+ priority = compute_priority(
59
+ predicted_utility=0.0,
60
+ uncertainty=1.0,
61
+ diversity_gain=bonus,
62
+ cluster_bonus=bonus,
63
+ policy=self.policy,
64
+ )
65
+ items.append(
66
+ QueueItem(
67
+ ligand_id=ligand_id,
68
+ status="active",
69
+ priority=float(priority),
70
+ cluster_id=cluster_id,
71
+ hypercluster_id=hypercluster_id,
72
+ )
73
+ )
74
+ cluster_load[cluster_id] = cluster_load.get(cluster_id, 0) + 1
75
+
76
+ self.state = SchedulerState(queue=items, batch_history=[], round_idx=0)
77
+ self.queue_manager = QueueManager.from_items(items)
78
+
79
+ def select_batch(self) -> List[str]:
80
+ active = self.queue_manager.ordered_active()
81
+ if not active:
82
+ # If conservative deprioritization exhausted active queue, reactivate
83
+ # deprioritized candidates to continue spending the docking budget.
84
+ deprioritized = sorted(
85
+ [item for item in self.queue_manager.items.values() if item.status == "deprioritized"],
86
+ key=lambda item: item.priority,
87
+ reverse=True,
88
+ )
89
+ if not deprioritized:
90
+ return []
91
+ for item in deprioritized:
92
+ item.status = "active"
93
+ active = deprioritized
94
+
95
+ coverage_count = max(1, int(self.config.batch_size * self.config.init_coverage_fraction))
96
+ by_hypercluster: Dict[int, List[QueueItem]] = {}
97
+ for item in active:
98
+ by_hypercluster.setdefault(item.hypercluster_id, []).append(item)
99
+
100
+ selected: List[str] = []
101
+ # Broad initial coverage.
102
+ for _h_id, items in sorted(by_hypercluster.items(), key=lambda x: len(x[1]), reverse=True):
103
+ if len(selected) >= coverage_count:
104
+ break
105
+ selected.append(items[0].ligand_id)
106
+
107
+ # Fill remaining slots by priority.
108
+ for item in active:
109
+ if len(selected) >= self.config.batch_size:
110
+ break
111
+ if item.ligand_id not in selected:
112
+ selected.append(item.ligand_id)
113
+
114
+ for ligand_id in selected:
115
+ self.queue_manager.items[ligand_id].times_selected += 1
116
+ return selected
117
+
118
+ @staticmethod
119
+ def _mean_or_default(values: list[float], default: float = 0.0) -> float:
120
+ if not values:
121
+ return float(default)
122
+ return float(np.mean(np.asarray(values, dtype=float)))
123
+
124
+ def update_from_batch(
125
+ self,
126
+ evaluated_df: pd.DataFrame,
127
+ feature_values_df: pd.DataFrame,
128
+ feature_masks_df: pd.DataFrame,
129
+ ) -> Dict[str, float]:
130
+ # Mark completed ligands and store latest score.
131
+ score_map = dict(zip(evaluated_df["ligand_id"].astype(str), evaluated_df["docking_score"].astype(float)))
132
+ for ligand_id, score in score_map.items():
133
+ if ligand_id in self.queue_manager.items:
134
+ item = self.queue_manager.items[ligand_id]
135
+ item.status = "completed"
136
+ item.last_score = float(score)
137
+
138
+ if feature_values_df.empty or feature_masks_df.empty:
139
+ raise ValueError("Feature tables cannot be empty in adaptive update")
140
+
141
+ if "ligand_id" not in feature_values_df.columns or "ligand_id" not in feature_masks_df.columns:
142
+ raise ValueError("Feature tables must include ligand_id column")
143
+
144
+ ligand_order = feature_values_df["ligand_id"].astype(str).tolist()
145
+ features = feature_values_df.drop(columns=["ligand_id"]).to_numpy(dtype=float)
146
+ masks = feature_masks_df.drop(columns=["ligand_id"]).to_numpy(dtype=float)
147
+ feature_names = feature_values_df.drop(columns=["ligand_id"]).columns.tolist()
148
+ mask_names = feature_masks_df.drop(columns=["ligand_id"]).columns.tolist()
149
+
150
+ target = np.full(len(ligand_order), np.nan, dtype=float)
151
+ for i, ligand_id in enumerate(ligand_order):
152
+ if ligand_id in self.queue_manager.items:
153
+ score = self.queue_manager.items[ligand_id].last_score
154
+ if score is not None:
155
+ target[i] = float(score)
156
+
157
+ fit_stats = self.surrogate.fit(
158
+ features=features,
159
+ masks=masks,
160
+ y=target,
161
+ feature_names=feature_names,
162
+ mask_names=mask_names,
163
+ )
164
+
165
+ n_train = int(fit_stats.get("n_train", 0.0))
166
+ instability_ratio = float(fit_stats.get("instability_ratio", 1.0))
167
+ model_weight = compute_model_weight(
168
+ n_samples=n_train,
169
+ instability_ratio=instability_ratio,
170
+ config=self.config.weight_schedule,
171
+ )
172
+ if self.surrogate.model is None:
173
+ model_weight = 0.0
174
+ self.last_model_weight = float(model_weight)
175
+
176
+ # Predict for active items.
177
+ active_items = self.queue_manager.active_items()
178
+ active_ids = [item.ligand_id for item in active_items]
179
+
180
+ completed_items = [item for item in self.queue_manager.items.values() if item.last_score is not None]
181
+ global_completed = [float(item.last_score) for item in completed_items if item.last_score is not None]
182
+ global_mean_score = self._mean_or_default(global_completed, default=0.0)
183
+
184
+ cluster_scores: Dict[int, list[float]] = {}
185
+ hyper_scores: Dict[int, list[float]] = {}
186
+ for item in completed_items:
187
+ assert item.last_score is not None
188
+ cluster_scores.setdefault(item.cluster_id, []).append(float(item.last_score))
189
+ hyper_scores.setdefault(item.hypercluster_id, []).append(float(item.last_score))
190
+
191
+ if active_ids:
192
+ id_to_idx = {lid: idx for idx, lid in enumerate(ligand_order)}
193
+ x_active = np.vstack([features[id_to_idx[lid]] for lid in active_ids])
194
+ m_active = np.vstack([masks[id_to_idx[lid]] for lid in active_ids])
195
+ bundle = self.surrogate.predict_bundle(x_active, m_active)
196
+
197
+ cluster_load: Dict[int, int] = {}
198
+ for item in active_items:
199
+ cluster_load[item.cluster_id] = cluster_load.get(item.cluster_id, 0) + 1
200
+
201
+ for i, ligand_id in enumerate(active_ids):
202
+ item = self.queue_manager.items[ligand_id]
203
+
204
+ cluster_mean = self._mean_or_default(cluster_scores.get(item.cluster_id, []), default=np.nan)
205
+ hyper_mean = self._mean_or_default(hyper_scores.get(item.hypercluster_id, []), default=np.nan)
206
+ observed_docking = (
207
+ cluster_mean
208
+ if np.isfinite(cluster_mean)
209
+ else hyper_mean
210
+ if np.isfinite(hyper_mean)
211
+ else global_mean_score
212
+ )
213
+
214
+ docking_component = -float(observed_docking)
215
+ model_component = -float(bundle["expected_score"][i])
216
+ blended_utility = (1.0 - model_weight) * docking_component + model_weight * model_component
217
+
218
+ bonus = cluster_bonus(cluster_load, item.cluster_id)
219
+ item.priority = compute_priority(
220
+ predicted_utility=float(blended_utility),
221
+ uncertainty=float(bundle["uncertainty"][i]),
222
+ diversity_gain=bonus,
223
+ cluster_bonus=bonus,
224
+ policy=self.policy,
225
+ )
226
+
227
+ if self.config.conservative_deprioritize:
228
+ priorities = np.asarray([self.queue_manager.items[lid].priority for lid in active_ids], dtype=float)
229
+ threshold = float(np.quantile(priorities, self.policy.conservative_deprioritize_quantile))
230
+ for lid in active_ids:
231
+ if self.queue_manager.items[lid].priority < threshold:
232
+ self.queue_manager.items[lid].status = "deprioritized"
233
+
234
+ self.state.round_idx += 1
235
+ sm = score_metrics(evaluated_df["docking_score"].astype(float).tolist())
236
+ batch_record: Dict[str, float | str] = {
237
+ "round_idx": self.state.round_idx,
238
+ "batch_size": int(evaluated_df.shape[0]),
239
+ "model_weight": float(model_weight),
240
+ "n_train": float(n_train),
241
+ "train_mae": float(fit_stats.get("train_mae", np.nan)),
242
+ "val_mae": float(fit_stats.get("val_mae", np.nan)),
243
+ "instability_ratio": float(instability_ratio),
244
+ "surrogate_backend": self.surrogate.backend,
245
+ **sm,
246
+ }
247
+ self.state.batch_history.append(batch_record)
248
+ return fit_stats
249
+
250
+ def save_state(self, output_path: str | Path | None = None) -> Path:
251
+ target = Path(output_path or self.config.state_path)
252
+ self.state.queue = list(self.queue_manager.items.values())
253
+ return self.state.save(target)
libs/adaptive/state.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import asdict, dataclass, field
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List
6
+
7
+ import json
8
+
9
+
10
+ @dataclass
11
+ class QueueItem:
12
+ ligand_id: str
13
+ status: str = "active"
14
+ priority: float = 0.0
15
+ hypercluster_id: int = -1
16
+ cluster_id: int = -1
17
+ times_selected: int = 0
18
+ last_score: float | None = None
19
+
20
+
21
+ @dataclass
22
+ class SchedulerState:
23
+ queue: List[QueueItem] = field(default_factory=list)
24
+ batch_history: List[Dict[str, Any]] = field(default_factory=list)
25
+ round_idx: int = 0
26
+
27
+ def to_dict(self) -> Dict[str, Any]:
28
+ return {
29
+ "queue": [asdict(item) for item in self.queue],
30
+ "batch_history": self.batch_history,
31
+ "round_idx": self.round_idx,
32
+ }
33
+
34
+ @classmethod
35
+ def from_dict(cls, payload: Dict[str, Any]) -> "SchedulerState":
36
+ queue = [QueueItem(**item) for item in payload.get("queue", [])]
37
+ return cls(queue=queue, batch_history=payload.get("batch_history", []), round_idx=int(payload.get("round_idx", 0)))
38
+
39
+ def save(self, path: str | Path) -> Path:
40
+ target = Path(path)
41
+ target.parent.mkdir(parents=True, exist_ok=True)
42
+ with target.open("w", encoding="utf-8") as handle:
43
+ json.dump(self.to_dict(), handle, indent=2)
44
+ return target
45
+
46
+ @classmethod
47
+ def load(cls, path: str | Path) -> "SchedulerState":
48
+ source = Path(path)
49
+ with source.open("r", encoding="utf-8") as handle:
50
+ return cls.from_dict(json.load(handle))
libs/adaptive/surrogate_model.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, List, Optional
5
+
6
+ import numpy as np
7
+ from sklearn.ensemble import RandomForestRegressor
8
+
9
+ try:
10
+ from xgboost import XGBRegressor
11
+ except Exception: # pragma: no cover
12
+ XGBRegressor = None # type: ignore[assignment]
13
+
14
+
15
+ @dataclass
16
+ class SurrogateConfig:
17
+ prefer_xgboost: bool = True
18
+ random_state: int = 42
19
+ n_estimators: int = 200
20
+ min_train_samples: int = 8
21
+ max_depth_small: int = 3
22
+ max_depth_large: int = 6
23
+
24
+
25
+ class SurrogateModel:
26
+ """Surrogate model with explicit missing-feature masking support."""
27
+
28
+ def __init__(self, config: Optional[SurrogateConfig] = None):
29
+ self.config = config or SurrogateConfig()
30
+ self.model = None
31
+ self.backend = "uninitialized"
32
+ self.feature_names: List[str] = []
33
+ self.mask_names: List[str] = []
34
+
35
+ self._median: np.ndarray | None = None
36
+ self._iqr: np.ndarray | None = None
37
+ self._train_x: np.ndarray | None = None
38
+ self._train_y: np.ndarray | None = None
39
+ self.last_fit_stats: Dict[str, float] = {}
40
+
41
+ def _build_model(self, n_samples: int):
42
+ max_depth = self.config.max_depth_small if n_samples < 50 else self.config.max_depth_large
43
+ if self.config.prefer_xgboost and XGBRegressor is not None:
44
+ self.backend = "xgboost"
45
+ return XGBRegressor(
46
+ n_estimators=self.config.n_estimators,
47
+ max_depth=max_depth,
48
+ learning_rate=0.05,
49
+ subsample=0.9,
50
+ colsample_bytree=0.9,
51
+ reg_alpha=0.1,
52
+ reg_lambda=1.0,
53
+ random_state=self.config.random_state,
54
+ )
55
+
56
+ self.backend = "random_forest"
57
+ return RandomForestRegressor(
58
+ n_estimators=max(100, self.config.n_estimators),
59
+ max_depth=max_depth,
60
+ random_state=self.config.random_state,
61
+ n_jobs=-1,
62
+ )
63
+
64
+ def _fit_normalizer(self, x: np.ndarray, m: np.ndarray) -> None:
65
+ med = []
66
+ iqr = []
67
+ for j in range(x.shape[1]):
68
+ vals = x[m[:, j] > 0.5, j]
69
+ if vals.size == 0:
70
+ med.append(0.0)
71
+ iqr.append(1.0)
72
+ continue
73
+ q1 = float(np.quantile(vals, 0.25))
74
+ q3 = float(np.quantile(vals, 0.75))
75
+ inter = max(1e-6, q3 - q1)
76
+ med.append(float(np.median(vals)))
77
+ iqr.append(inter)
78
+ self._median = np.asarray(med, dtype=float)
79
+ self._iqr = np.asarray(iqr, dtype=float)
80
+
81
+ def _transform(self, x: np.ndarray, m: np.ndarray, fit: bool = False) -> np.ndarray:
82
+ x = np.asarray(x, dtype=float)
83
+ m = np.asarray(m, dtype=float)
84
+ if fit or self._median is None or self._iqr is None:
85
+ self._fit_normalizer(x, m)
86
+ assert self._median is not None and self._iqr is not None
87
+
88
+ x_filled = np.where(np.isfinite(x), x, np.nan)
89
+ for j in range(x.shape[1]):
90
+ col = x_filled[:, j]
91
+ missing = ~np.isfinite(col)
92
+ col[missing] = self._median[j]
93
+ x_filled[:, j] = (col - self._median[j]) / self._iqr[j]
94
+
95
+ # Explicit missingness information: concatenate mask vector.
96
+ return np.concatenate([x_filled, m], axis=1)
97
+
98
+ def fit(
99
+ self,
100
+ features: np.ndarray,
101
+ masks: np.ndarray,
102
+ y: np.ndarray,
103
+ feature_names: List[str],
104
+ mask_names: List[str],
105
+ ) -> Dict[str, float]:
106
+ y = np.asarray(y, dtype=float)
107
+ valid = np.isfinite(y)
108
+ n_samples = int(np.sum(valid))
109
+
110
+ self.feature_names = list(feature_names)
111
+ self.mask_names = list(mask_names)
112
+
113
+ if n_samples < self.config.min_train_samples:
114
+ self.model = None
115
+ self.backend = "warmup"
116
+ self.last_fit_stats = {
117
+ "n_train": float(n_samples),
118
+ "train_mae": np.nan,
119
+ "val_mae": np.nan,
120
+ "instability_ratio": 1.0,
121
+ }
122
+ return self.last_fit_stats
123
+
124
+ x = np.asarray(features, dtype=float)[valid]
125
+ m = np.asarray(masks, dtype=float)[valid]
126
+ yv = y[valid]
127
+
128
+ x_trans = self._transform(x, m, fit=True)
129
+ self._train_x = x_trans
130
+ self._train_y = yv
131
+
132
+ self.model = self._build_model(n_samples=n_samples)
133
+ self.model.fit(x_trans, yv)
134
+
135
+ train_pred = self.model.predict(x_trans)
136
+ train_mae = float(np.mean(np.abs(train_pred - yv)))
137
+
138
+ # Simple rolling validation proxy.
139
+ if n_samples >= 12:
140
+ split = int(max(8, n_samples * 0.8))
141
+ x_tr, x_val = x_trans[:split], x_trans[split:]
142
+ y_tr, y_val = yv[:split], yv[split:]
143
+
144
+ val_model = self._build_model(n_samples=split)
145
+ val_model.fit(x_tr, y_tr)
146
+ val_pred = val_model.predict(x_val)
147
+ val_mae = float(np.mean(np.abs(val_pred - y_val))) if y_val.size else train_mae
148
+ else:
149
+ val_mae = train_mae
150
+
151
+ instability = float((val_mae + 1e-6) / (train_mae + 1e-6))
152
+ self.last_fit_stats = {
153
+ "n_train": float(n_samples),
154
+ "train_mae": train_mae,
155
+ "val_mae": val_mae,
156
+ "instability_ratio": instability,
157
+ }
158
+ return self.last_fit_stats
159
+
160
+ def _rf_uncertainty(self, x: np.ndarray) -> np.ndarray:
161
+ assert self.model is not None
162
+ if not hasattr(self.model, "estimators_"):
163
+ return np.full(x.shape[0], float(np.std(self._train_y)) if self._train_y is not None else 1.0)
164
+ preds = np.vstack([tree.predict(x) for tree in self.model.estimators_])
165
+ return np.std(preds, axis=0)
166
+
167
+ def predict_bundle(self, features: np.ndarray, masks: np.ndarray, topk_threshold: float | None = None) -> Dict[str, np.ndarray]:
168
+ n = features.shape[0]
169
+ if self.model is None:
170
+ return {
171
+ "expected_score": np.zeros(n, dtype=float),
172
+ "topk_probability": np.full(n, 0.5, dtype=float),
173
+ "uncertainty": np.full(n, 1.0, dtype=float),
174
+ }
175
+
176
+ x = self._transform(np.asarray(features, dtype=float), np.asarray(masks, dtype=float), fit=False)
177
+ expected = self.model.predict(x)
178
+
179
+ if self.backend == "random_forest":
180
+ uncertainty = self._rf_uncertainty(x)
181
+ else:
182
+ residual_scale = (
183
+ float(np.std(self._train_y - self.model.predict(self._train_x)))
184
+ if self._train_x is not None and self._train_y is not None
185
+ else 1.0
186
+ )
187
+ uncertainty = np.full(expected.shape[0], max(1e-3, residual_scale))
188
+
189
+ if topk_threshold is None:
190
+ topk_threshold = float(np.quantile(self._train_y, 0.8)) if self._train_y is not None else 0.0
191
+
192
+ z = (expected - topk_threshold) / (uncertainty + 1e-6)
193
+ topk_prob = 1.0 / (1.0 + np.exp(-z))
194
+ return {
195
+ "expected_score": expected.astype(float),
196
+ "topk_probability": topk_prob.astype(float),
197
+ "uncertainty": uncertainty.astype(float),
198
+ }
199
+
200
+ def feature_importance(self) -> Dict[str, float]:
201
+ if self.model is None or not hasattr(self.model, "feature_importances_"):
202
+ return {}
203
+
204
+ names = self.feature_names + self.mask_names
205
+ importances = np.asarray(self.model.feature_importances_, dtype=float)
206
+ if importances.size != len(names):
207
+ return {}
208
+ return {name: float(value) for name, value in zip(names, importances)}
libs/adaptive/thresholding.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, List, Sequence
5
+
6
+ import numpy as np
7
+
8
+
9
+ @dataclass
10
+ class DynamicThresholdConfig:
11
+ min_evaluated: int = 500
12
+ patience_rounds: int = 8
13
+ min_model_weight: float = 0.35
14
+ quantile: float = 0.15
15
+ uncertainty_weight: float = 0.20
16
+ min_improvement: float = 0.02
17
+ exploration_margin: float = 0.45
18
+ exploitation_margin: float = 0.10
19
+ reference_evaluations: int = 5000
20
+
21
+
22
+ class DynamicEarlyStopController:
23
+ """
24
+ Conservative early-stop controller for adaptive replay.
25
+
26
+ Lower scores are considered better.
27
+ """
28
+
29
+ def __init__(self, config: DynamicThresholdConfig | None = None) -> None:
30
+ self.config = config or DynamicThresholdConfig()
31
+ self.best_score = np.inf
32
+ self.stagnant_rounds = 0
33
+ self.history: List[Dict[str, float | int | bool | str]] = []
34
+
35
+ def update(
36
+ self,
37
+ *,
38
+ round_idx: int,
39
+ n_evaluated: int,
40
+ all_scores: Sequence[float],
41
+ recent_scores: Sequence[float],
42
+ model_weight: float,
43
+ mean_uncertainty: float,
44
+ ) -> Dict[str, float | int | bool | str]:
45
+ cfg = self.config
46
+ scores = np.asarray(all_scores, dtype=float)
47
+ recent = np.asarray(recent_scores, dtype=float)
48
+
49
+ if scores.size == 0:
50
+ rec = {
51
+ "round_idx": int(round_idx),
52
+ "n_evaluated": int(n_evaluated),
53
+ "dynamic_threshold": np.nan,
54
+ "score_quantile": np.nan,
55
+ "best_score": np.nan,
56
+ "recent_mean_score": np.nan,
57
+ "mean_uncertainty": float(mean_uncertainty),
58
+ "model_weight": float(model_weight),
59
+ "stagnant_rounds": int(self.stagnant_rounds),
60
+ "eligible_for_stop": False,
61
+ "stop": False,
62
+ "reason": "no_scores",
63
+ }
64
+ self.history.append(rec)
65
+ return rec
66
+
67
+ score_quantile = float(np.nanquantile(scores, cfg.quantile))
68
+ best = float(np.nanmin(scores))
69
+ recent_mean = float(np.nanmean(recent)) if recent.size else float(np.nan)
70
+ uncertainty = float(max(0.0, mean_uncertainty))
71
+
72
+ if np.isfinite(self.best_score):
73
+ improvement = float(self.best_score - best)
74
+ else:
75
+ improvement = np.inf
76
+
77
+ if improvement > cfg.min_improvement:
78
+ self.stagnant_rounds = 0
79
+ else:
80
+ self.stagnant_rounds += 1
81
+ self.best_score = min(self.best_score, best)
82
+
83
+ coverage = float(min(1.0, n_evaluated / max(1.0, float(cfg.reference_evaluations))))
84
+ margin = (1.0 - coverage) * cfg.exploration_margin + coverage * cfg.exploitation_margin
85
+ dynamic_threshold = float(score_quantile + margin + cfg.uncertainty_weight * uncertainty)
86
+
87
+ eligible = (
88
+ int(n_evaluated) >= int(cfg.min_evaluated)
89
+ and float(model_weight) >= float(cfg.min_model_weight)
90
+ )
91
+ plateau = self.stagnant_rounds >= int(cfg.patience_rounds)
92
+ poor_recent = bool(np.isfinite(recent_mean) and recent_mean >= dynamic_threshold)
93
+ should_stop = bool(eligible and plateau and poor_recent)
94
+
95
+ if not eligible:
96
+ reason = "not_eligible"
97
+ elif not plateau:
98
+ reason = "improving_or_not_stagnant"
99
+ elif not poor_recent:
100
+ reason = "recent_batch_still_competitive"
101
+ else:
102
+ reason = "stagnation_above_dynamic_threshold"
103
+
104
+ rec = {
105
+ "round_idx": int(round_idx),
106
+ "n_evaluated": int(n_evaluated),
107
+ "dynamic_threshold": dynamic_threshold,
108
+ "score_quantile": score_quantile,
109
+ "best_score": self.best_score,
110
+ "recent_mean_score": recent_mean,
111
+ "mean_uncertainty": uncertainty,
112
+ "model_weight": float(model_weight),
113
+ "stagnant_rounds": int(self.stagnant_rounds),
114
+ "eligible_for_stop": bool(eligible),
115
+ "stop": should_stop,
116
+ "reason": reason,
117
+ }
118
+ self.history.append(rec)
119
+ return rec
120
+
libs/adaptive/weight_schedule.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Sequence
5
+
6
+
7
+ @dataclass
8
+ class WeightScheduleConfig:
9
+ sample_knots: tuple[int, int, int, int] = (20, 50, 100, 200)
10
+ weight_knots: tuple[float, float, float, float] = (0.1, 0.3, 0.5, 0.8)
11
+ max_weight: float = 0.9
12
+ min_weight: float = 0.05
13
+ instability_threshold: float = 2.0
14
+ instability_decay: float = 0.25
15
+
16
+
17
+ def _interp(x: float, xs: Sequence[float], ys: Sequence[float]) -> float:
18
+ if x <= xs[0]:
19
+ return float(ys[0])
20
+ if x >= xs[-1]:
21
+ return float(ys[-1])
22
+
23
+ for i in range(1, len(xs)):
24
+ if x <= xs[i]:
25
+ x0, x1 = xs[i - 1], xs[i]
26
+ y0, y1 = ys[i - 1], ys[i]
27
+ t = (x - x0) / max(1e-9, (x1 - x0))
28
+ return float(y0 + t * (y1 - y0))
29
+ return float(ys[-1])
30
+
31
+
32
+ def compute_model_weight(
33
+ n_samples: int,
34
+ instability_ratio: float = 1.0,
35
+ config: WeightScheduleConfig | None = None,
36
+ ) -> float:
37
+ cfg = config or WeightScheduleConfig()
38
+
39
+ base = _interp(float(n_samples), cfg.sample_knots, cfg.weight_knots)
40
+ if n_samples > cfg.sample_knots[-1]:
41
+ extra = min(cfg.max_weight - base, 0.05 * (n_samples - cfg.sample_knots[-1]) / 100.0)
42
+ base += max(0.0, extra)
43
+
44
+ if instability_ratio > cfg.instability_threshold:
45
+ base *= max(0.1, 1.0 - cfg.instability_decay)
46
+
47
+ base = max(cfg.min_weight, min(cfg.max_weight, base))
48
+ return float(base)
libs/analysis/__init__.py ADDED
File without changes
libs/analysis/backend_diagnostic.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ from typing import Any, Iterable
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+
11
+ REQUIRED_REFERENCE_DIAG_COLUMNS = [
12
+ "dataset",
13
+ "target_name",
14
+ "reference_ligand_id",
15
+ "reference_ligand_score",
16
+ "reference_ligand_rank_percentile",
17
+ "adaptive_best_score",
18
+ "exhaustive_best_score",
19
+ ]
20
+
21
+ REQUIRED_BACKEND_COMPARISON_COLUMNS = [
22
+ "dataset",
23
+ "backend",
24
+ "analysis_scope",
25
+ "available",
26
+ "n_ligands",
27
+ "runtime_seconds",
28
+ "runtime_per_ligand",
29
+ "reference_ligand_score",
30
+ "reference_ligand_rank_percentile",
31
+ "best_score",
32
+ "score_gap_reference_vs_best",
33
+ "reference_pose_centroid_distance_A",
34
+ "reference_pose_in_expected_pocket",
35
+ ]
36
+
37
+ REQUIRED_POCKET_PREP_COLUMNS = [
38
+ "dataset",
39
+ "backend",
40
+ "pocket_variant",
41
+ "prep_variant",
42
+ "reference_ligand_score",
43
+ "reference_pose_centroid_distance_A",
44
+ "reference_pose_in_expected_pocket",
45
+ ]
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class ManualAgentsCheck:
50
+ exists: bool
51
+ path: str
52
+ manually_read: bool
53
+
54
+
55
+ def manual_agents_check(path: str | Path, manually_read: bool = True) -> ManualAgentsCheck:
56
+ p = Path(path).expanduser().resolve()
57
+ return ManualAgentsCheck(exists=p.exists(), path=str(p), manually_read=bool(manually_read and p.exists()))
58
+
59
+
60
+ def _safe_float(x: Any, default: float = np.nan) -> float:
61
+ try:
62
+ v = float(x)
63
+ return float(v) if np.isfinite(v) else float(default)
64
+ except Exception:
65
+ return float(default)
66
+
67
+
68
+ def compute_rank_percentile(df: pd.DataFrame, ligand_id: str, score_col: str, lower_is_better: bool = True) -> float:
69
+ if df.empty or score_col not in df.columns:
70
+ return np.nan
71
+ d = df[["ligand_id", score_col]].copy()
72
+ d["ligand_id"] = d["ligand_id"].astype(str)
73
+ d[score_col] = pd.to_numeric(d[score_col], errors="coerce")
74
+ d = d.dropna(subset=[score_col]).copy()
75
+ if d.empty:
76
+ return np.nan
77
+ d = d.sort_values(score_col, ascending=bool(lower_is_better)).reset_index(drop=True)
78
+ hit = d.index[d["ligand_id"] == str(ligand_id)]
79
+ if len(hit) == 0:
80
+ return np.nan
81
+ rank = int(hit[0]) + 1
82
+ return float(100.0 * rank / max(1, d.shape[0]))
83
+
84
+
85
+ def select_suspicious_datasets(reference_diag_df: pd.DataFrame, threshold_pct: float = 25.0, max_deep: int = 2) -> list[str]:
86
+ if reference_diag_df.empty:
87
+ return []
88
+ d = reference_diag_df.copy()
89
+ d["reference_ligand_rank_percentile"] = pd.to_numeric(d["reference_ligand_rank_percentile"], errors="coerce")
90
+ d = d.dropna(subset=["reference_ligand_rank_percentile"]).copy()
91
+ d = d[d["reference_ligand_rank_percentile"] >= float(threshold_pct)].copy()
92
+ if d.empty:
93
+ return []
94
+ d = d.sort_values("reference_ligand_rank_percentile", ascending=False)
95
+ return d["dataset"].astype(str).head(int(max(1, max_deep))).tolist()
96
+
97
+
98
+ def validate_required_columns(df: pd.DataFrame, required_columns: Iterable[str]) -> list[str]:
99
+ cols = set(df.columns)
100
+ missing = [c for c in required_columns if c not in cols]
101
+ return missing
102
+
103
+
104
+ def recommend_toolchain(
105
+ backend_comparison_df: pd.DataFrame,
106
+ pocket_prep_df: pd.DataFrame,
107
+ ) -> dict[str, Any]:
108
+ """
109
+ Choose practical recommendation from diagnostic evidence.
110
+
111
+ Policy:
112
+ - Prefer backend with best median reference rank percentile under "subset_default" scope.
113
+ - Penalize poor runtime-per-ligand if >2x best runtime.
114
+ - Use pocket/prep gain to detect whether core issue is mostly preparation/pocket.
115
+ """
116
+ out: dict[str, Any] = {
117
+ "recommended_main_backend": "rdock",
118
+ "recommended_rescoring": "gnina_or_haddock_shortlist_optional",
119
+ "keep_haddock": "optional_shortlist_only",
120
+ "main_failure_source": "mixed",
121
+ "evidence": [],
122
+ }
123
+
124
+ bdf = backend_comparison_df.copy()
125
+ if not bdf.empty:
126
+ bdf = bdf[bdf["analysis_scope"].astype(str) == "subset_default"].copy()
127
+ if not bdf.empty:
128
+ bdf["runtime_per_ligand"] = pd.to_numeric(bdf["runtime_per_ligand"], errors="coerce")
129
+ bdf["reference_ligand_rank_percentile"] = pd.to_numeric(bdf["reference_ligand_rank_percentile"], errors="coerce")
130
+ agg = (
131
+ bdf.groupby("backend", as_index=False)
132
+ .agg(
133
+ median_ref_rank_pct=("reference_ligand_rank_percentile", "median"),
134
+ median_runtime=("runtime_per_ligand", "median"),
135
+ available_ratio=("available", "mean"),
136
+ )
137
+ .sort_values(["median_ref_rank_pct", "median_runtime"], ascending=[True, True])
138
+ )
139
+ if not agg.empty:
140
+ best = agg.iloc[0]
141
+ best_runtime = max(1e-9, _safe_float(best["median_runtime"], 1.0))
142
+ candidate = str(best["backend"])
143
+ if _safe_float(best["available_ratio"], 0.0) < 0.5:
144
+ out["evidence"].append("best_rank_backend_not_reliably_available")
145
+ else:
146
+ out["recommended_main_backend"] = candidate
147
+
148
+ rd = agg[agg["backend"].astype(str).str.lower() == "rdock"]
149
+ if not rd.empty:
150
+ rd_runtime = max(1e-9, _safe_float(rd.iloc[0]["median_runtime"], best_runtime))
151
+ if best_runtime > 2.0 * rd_runtime and candidate != "rdock":
152
+ out["evidence"].append("candidate_backend_too_slow_vs_rdock")
153
+ out["recommended_main_backend"] = "rdock"
154
+
155
+ out["evidence"].append(f"rank_runtime_table={agg.to_dict(orient='records')}")
156
+
157
+ pdf = pocket_prep_df.copy()
158
+ if not pdf.empty:
159
+ pdf["reference_ligand_score"] = pd.to_numeric(pdf["reference_ligand_score"], errors="coerce")
160
+ deltas: list[float] = []
161
+ for (_, _), sub in pdf.groupby(["dataset", "backend"]):
162
+ default = sub[(sub["pocket_variant"] == "default") & (sub["prep_variant"] == "default")]
163
+ if default.empty:
164
+ continue
165
+ default_score = _safe_float(default.iloc[0]["reference_ligand_score"], np.nan)
166
+ best_score = _safe_float(sub["reference_ligand_score"].min(), np.nan)
167
+ if np.isfinite(default_score) and np.isfinite(best_score):
168
+ deltas.append(default_score - best_score)
169
+ mean_gain = float(np.mean(np.asarray(deltas, dtype=float))) if deltas else 0.0
170
+ if mean_gain > 1.0:
171
+ out["main_failure_source"] = "pocket_or_preparation"
172
+ elif mean_gain > 0.2:
173
+ out["main_failure_source"] = "mixed"
174
+ else:
175
+ out["main_failure_source"] = "backend_scoring_limitations"
176
+ out["evidence"].append(f"mean_reference_gain_from_pocket_prep={mean_gain:.3f}")
177
+
178
+ out["keep_haddock"] = "optional_shortlist_only"
179
+ return out
libs/analysis/ranking.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+
7
+ def resolve_reference_rank_percentile(
8
+ merged_df: pd.DataFrame,
9
+ reference_ligand_id: str,
10
+ *,
11
+ oracle_rank_col: str = "rank_percentile",
12
+ run_rank_col: str = "run_rank_percentile",
13
+ ) -> tuple[float, str]:
14
+ """
15
+ Resolve reference rank percentile with robust fallback.
16
+
17
+ Returns:
18
+ - rank percentile (float)
19
+ - source ("oracle", "run_fallback", "missing")
20
+ """
21
+ if merged_df.empty:
22
+ return float("nan"), "missing"
23
+
24
+ d = merged_df.copy()
25
+ if "ligand_id" not in d.columns:
26
+ return float("nan"), "missing"
27
+ d["ligand_id"] = d["ligand_id"].astype(str)
28
+ ref = d[d["ligand_id"] == str(reference_ligand_id)]
29
+ if ref.empty:
30
+ return float("nan"), "missing"
31
+
32
+ if oracle_rank_col in ref.columns:
33
+ oracle_val = pd.to_numeric(ref[oracle_rank_col], errors="coerce").iloc[0]
34
+ if np.isfinite(float(oracle_val)):
35
+ return float(oracle_val), "oracle"
36
+
37
+ if run_rank_col in d.columns:
38
+ run_val = pd.to_numeric(ref[run_rank_col], errors="coerce").iloc[0]
39
+ if np.isfinite(float(run_val)):
40
+ return float(run_val), "run_fallback"
41
+
42
+ return float("nan"), "missing"
43
+
libs/benchmark/__init__.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Benchmark utilities for large-scale and modality sanity-check runs."""
2
+
3
+ from .cleanup import CleanupItem, execute_results_cleanup, plan_results_cleanup
4
+ from .budget_efficiency import (
5
+ TimeImportanceControls,
6
+ clamp_time_importance,
7
+ controls_from_time_importance,
8
+ required_budget_metric_columns,
9
+ select_best_policy_budget,
10
+ summarize_diversity,
11
+ validate_budget_metric_schema,
12
+ )
13
+ from .disk_guard import (
14
+ DiskCleanupAction,
15
+ DiskSnapshot,
16
+ append_disk_snapshot,
17
+ requires_cleanup,
18
+ run_repository_local_cleanup,
19
+ snapshot_disk_state,
20
+ write_cleanup_actions,
21
+ write_disk_guard_report,
22
+ )
23
+ from .large_library import build_large_benchmark_library
24
+ from .ordering import cluster_naive_order
25
+ from .policy_repair import (
26
+ AdaptivePolicyVariant,
27
+ PolicyRuntimeState,
28
+ apply_stop_policy,
29
+ coverage_floor_reached,
30
+ coverage_fraction,
31
+ default_policy_variants,
32
+ effective_controls,
33
+ regret_stop_variant,
34
+ select_cluster_bootstrap_batch,
35
+ )
36
+ from .multifidelity import (
37
+ ExplorationControls,
38
+ StoppingControls,
39
+ UncertaintyControls,
40
+ controls_from_config,
41
+ enforce_control_limits,
42
+ simulate_multifidelity_policy,
43
+ )
44
+ from .overnight_stop import (
45
+ OBJECTIVES,
46
+ STOP_MODELS,
47
+ StopModelParams,
48
+ estimate_marginal_expected_gain,
49
+ estimate_probability_target_percentile,
50
+ is_trivial_objective_solution,
51
+ objective_value,
52
+ simulate_stop_model,
53
+ )
54
+ from .runtime import AUTO_MINUS_FOUR, ThreadAllocation, detect_system_threads, enforce_thread_fairness, resolve_threads_used
55
+ from .reuse import ReuseCheck, validate_reuse_inputs
56
+
57
+ __all__ = [
58
+ "AUTO_MINUS_FOUR",
59
+ "AdaptivePolicyVariant",
60
+ "CleanupItem",
61
+ "DiskCleanupAction",
62
+ "DiskSnapshot",
63
+ "PolicyRuntimeState",
64
+ "TimeImportanceControls",
65
+ "ThreadAllocation",
66
+ "ReuseCheck",
67
+ "apply_stop_policy",
68
+ "append_disk_snapshot",
69
+ "build_large_benchmark_library",
70
+ "clamp_time_importance",
71
+ "cluster_naive_order",
72
+ "coverage_floor_reached",
73
+ "coverage_fraction",
74
+ "controls_from_time_importance",
75
+ "default_policy_variants",
76
+ "detect_system_threads",
77
+ "effective_controls",
78
+ "estimate_marginal_expected_gain",
79
+ "estimate_probability_target_percentile",
80
+ "enforce_thread_fairness",
81
+ "execute_results_cleanup",
82
+ "is_trivial_objective_solution",
83
+ "objective_value",
84
+ "OBJECTIVES",
85
+ "STOP_MODELS",
86
+ "plan_results_cleanup",
87
+ "required_budget_metric_columns",
88
+ "regret_stop_variant",
89
+ "requires_cleanup",
90
+ "resolve_threads_used",
91
+ "run_repository_local_cleanup",
92
+ "simulate_multifidelity_policy",
93
+ "simulate_stop_model",
94
+ "StopModelParams",
95
+ "StoppingControls",
96
+ "ExplorationControls",
97
+ "UncertaintyControls",
98
+ "controls_from_config",
99
+ "enforce_control_limits",
100
+ "validate_reuse_inputs",
101
+ "select_best_policy_budget",
102
+ "select_cluster_bootstrap_batch",
103
+ "snapshot_disk_state",
104
+ "summarize_diversity",
105
+ "validate_budget_metric_schema",
106
+ "write_cleanup_actions",
107
+ "write_disk_guard_report",
108
+ ]
libs/benchmark/budget_efficiency.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Iterable, List
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+ from libs.adaptive.policies import PrioritizationPolicy
10
+
11
+
12
+ def clamp_time_importance(value: float) -> float:
13
+ return float(max(0.0, min(1.0, float(value))))
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class TimeImportanceControls:
18
+ utility_weight: float
19
+ uncertainty_weight: float
20
+ diversity_weight: float
21
+ cluster_bonus_weight: float
22
+ threshold_stop_shift: float
23
+ exploration_additive: float
24
+
25
+
26
+ def controls_from_time_importance(
27
+ base_policy: PrioritizationPolicy,
28
+ *,
29
+ exploration_boost: float,
30
+ time_importance: float,
31
+ ) -> TimeImportanceControls:
32
+ ti = clamp_time_importance(time_importance)
33
+ exp = float(max(0.0, exploration_boost))
34
+
35
+ adjusted_exp = float(max(0.0, exp + (1.0 - ti) * 0.22))
36
+ utility = max(0.15, float(base_policy.utility_weight) - 0.40 * adjusted_exp + 0.22 * ti)
37
+ uncertainty = max(0.05, float(base_policy.uncertainty_weight) + 0.22 * adjusted_exp - 0.10 * ti)
38
+ diversity = max(0.05, float(base_policy.diversity_weight) + 0.14 * adjusted_exp - 0.08 * ti)
39
+ cluster_bonus = float(base_policy.cluster_bonus_weight) + 0.04 * adjusted_exp
40
+ # Negative means easier stopping (more time-sensitive).
41
+ threshold_stop_shift = float(-0.20 * ti)
42
+ return TimeImportanceControls(
43
+ utility_weight=float(utility),
44
+ uncertainty_weight=float(uncertainty),
45
+ diversity_weight=float(diversity),
46
+ cluster_bonus_weight=float(cluster_bonus),
47
+ threshold_stop_shift=threshold_stop_shift,
48
+ exploration_additive=adjusted_exp,
49
+ )
50
+
51
+
52
+ def required_budget_metric_columns() -> List[str]:
53
+ return [
54
+ "dataset",
55
+ "strategy",
56
+ "strategy_group",
57
+ "budget",
58
+ "time_importance",
59
+ "top10_recovery_fraction",
60
+ "top50_recovery_fraction",
61
+ "top100_recovery_fraction",
62
+ "best_docking_score",
63
+ "best_final_score",
64
+ "dockings_performed",
65
+ "wall_time_seconds",
66
+ "quality_per_time",
67
+ "quality_per_docking",
68
+ "auc_best_score_so_far",
69
+ ]
70
+
71
+
72
+ def validate_budget_metric_schema(df: pd.DataFrame) -> List[str]:
73
+ missing = [c for c in required_budget_metric_columns() if c not in df.columns]
74
+ return missing
75
+
76
+
77
+ def select_best_policy_budget(metrics_df: pd.DataFrame) -> pd.Series:
78
+ if metrics_df.empty:
79
+ raise ValueError("metrics_df is empty")
80
+ missing = validate_budget_metric_schema(metrics_df)
81
+ if missing:
82
+ raise ValueError(f"metrics_df missing required columns: {missing}")
83
+
84
+ d = metrics_df.copy()
85
+ if "strategy_group" in d.columns:
86
+ d = d[d["strategy_group"].astype(str) == "adaptive"].copy()
87
+ if d.empty:
88
+ raise ValueError("No adaptive rows found for selection")
89
+
90
+ for c in ["top10_recovery_fraction", "top50_recovery_fraction", "top100_recovery_fraction", "quality_per_time", "quality_per_docking"]:
91
+ d[f"rank_{c}"] = pd.to_numeric(d[c], errors="coerce").rank(method="average", ascending=False)
92
+ d["rank_budget"] = pd.to_numeric(d["budget"], errors="coerce").rank(method="average", ascending=True)
93
+ d["rank_best_final"] = pd.to_numeric(d["best_final_score"], errors="coerce").rank(method="average", ascending=True)
94
+
95
+ d["selection_score"] = (
96
+ 0.24 * d["rank_top50_recovery_fraction"]
97
+ + 0.24 * d["rank_top100_recovery_fraction"]
98
+ + 0.20 * d["rank_top10_recovery_fraction"]
99
+ + 0.12 * d["rank_quality_per_docking"]
100
+ + 0.10 * d["rank_quality_per_time"]
101
+ + 0.06 * d["rank_best_final"]
102
+ + 0.04 * d["rank_budget"]
103
+ )
104
+ chosen = d.sort_values(["selection_score", "budget"], ascending=[True, True]).iloc[0]
105
+ return chosen
106
+
107
+
108
+ def summarize_diversity(df: pd.DataFrame, *, similarity_col: str = "reference_similarity", scaffold_col: str = "scaffold_core") -> pd.DataFrame:
109
+ vals = pd.to_numeric(df.get(similarity_col, pd.Series(dtype=float)), errors="coerce").dropna()
110
+ bins = np.linspace(0.0, 1.0, 11)
111
+ hist, edges = np.histogram(vals.to_numpy(dtype=float), bins=bins)
112
+ out = pd.DataFrame(
113
+ {
114
+ "bin_left": edges[:-1],
115
+ "bin_right": edges[1:],
116
+ "count": hist,
117
+ "fraction": hist / max(1, int(hist.sum())),
118
+ }
119
+ )
120
+ out["unique_scaffold_count"] = int(df.get(scaffold_col, pd.Series(dtype=str)).astype(str).replace({"": np.nan}).dropna().nunique())
121
+ out["total_ligands"] = int(df.shape[0])
122
+ return out
123
+
libs/benchmark/cleanup.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import shutil
4
+ from dataclasses import dataclass
5
+ from datetime import UTC, datetime
6
+ from pathlib import Path
7
+ from typing import Iterable, List
8
+
9
+
10
+ @dataclass
11
+ class CleanupItem:
12
+ path: Path
13
+ action: str
14
+ reason: str
15
+
16
+
17
+ def plan_results_cleanup(
18
+ results_dir: Path,
19
+ *,
20
+ keep_dirs: Iterable[str] = (
21
+ "large_benchmark",
22
+ "discovery_benchmark",
23
+ "ppi_benchmark",
24
+ "ppi_sanity_check",
25
+ "experimental_benchmark_single_library",
26
+ "smoke_test",
27
+ ),
28
+ ) -> List[CleanupItem]:
29
+ keep = {str(x).strip() for x in keep_dirs}
30
+ items: List[CleanupItem] = []
31
+ if not results_dir.exists():
32
+ return items
33
+
34
+ for child in sorted(results_dir.iterdir()):
35
+ if not child.is_dir():
36
+ continue
37
+ if child.name in keep or child.name == "archive":
38
+ continue
39
+ items.append(
40
+ CleanupItem(
41
+ path=child,
42
+ action="archive",
43
+ reason="obsolete_or_legacy_result_artifact",
44
+ )
45
+ )
46
+ return items
47
+
48
+
49
+ def execute_results_cleanup(results_dir: Path, plan: List[CleanupItem]) -> Path:
50
+ archive_root = results_dir / "archive" / datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
51
+ archive_root.mkdir(parents=True, exist_ok=True)
52
+ for item in plan:
53
+ if item.action != "archive" or not item.path.exists():
54
+ continue
55
+ target = archive_root / item.path.name
56
+ if target.exists():
57
+ shutil.rmtree(target)
58
+ shutil.move(str(item.path), str(target))
59
+ return archive_root
libs/benchmark/disk_guard.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import gzip
4
+ import os
5
+ import shutil
6
+ from dataclasses import dataclass, asdict
7
+ from datetime import UTC, datetime
8
+ from pathlib import Path
9
+ from typing import Dict, Iterable, List
10
+
11
+ import pandas as pd
12
+
13
+
14
+ @dataclass
15
+ class DiskSnapshot:
16
+ timestamp_utc: str
17
+ stage: str
18
+ note: str
19
+ free_gb: float
20
+ repo_size_gb: float
21
+ projected_output_gb: float
22
+ projected_free_after_gb: float
23
+
24
+
25
+ @dataclass
26
+ class DiskCleanupAction:
27
+ timestamp_utc: str
28
+ action: str
29
+ target: str
30
+ size_before_mb: float
31
+ size_after_mb: float
32
+ reclaimed_mb: float
33
+ status: str
34
+ reason: str
35
+
36
+
37
+ def _utc_now() -> str:
38
+ return datetime.now(UTC).isoformat()
39
+
40
+
41
+ def _is_within_repo(target: Path, repo_root: Path) -> bool:
42
+ try:
43
+ target.resolve().relative_to(repo_root.resolve())
44
+ return True
45
+ except Exception:
46
+ return False
47
+
48
+
49
+ def directory_size_bytes(path: Path) -> int:
50
+ total = 0
51
+ if not path.exists():
52
+ return total
53
+ for entry in path.rglob("*"):
54
+ if entry.is_file():
55
+ try:
56
+ total += entry.stat().st_size
57
+ except OSError:
58
+ continue
59
+ return total
60
+
61
+
62
+ def system_free_bytes(path: Path) -> int:
63
+ return int(shutil.disk_usage(path).free)
64
+
65
+
66
+ def snapshot_disk_state(repo_root: Path, stage: str, note: str, projected_output_gb: float = 0.0) -> DiskSnapshot:
67
+ free = system_free_bytes(repo_root)
68
+ repo_size = directory_size_bytes(repo_root)
69
+ projected_after = max(0.0, (free / (1024**3)) - float(projected_output_gb))
70
+ return DiskSnapshot(
71
+ timestamp_utc=_utc_now(),
72
+ stage=stage,
73
+ note=note,
74
+ free_gb=free / (1024**3),
75
+ repo_size_gb=repo_size / (1024**3),
76
+ projected_output_gb=float(projected_output_gb),
77
+ projected_free_after_gb=projected_after,
78
+ )
79
+
80
+
81
+ def append_disk_snapshot(csv_path: Path, snapshot: DiskSnapshot) -> None:
82
+ csv_path.parent.mkdir(parents=True, exist_ok=True)
83
+ row = pd.DataFrame([asdict(snapshot)])
84
+ if csv_path.exists():
85
+ old = pd.read_csv(csv_path)
86
+ out = pd.concat([old, row], ignore_index=True)
87
+ else:
88
+ out = row
89
+ out.to_csv(csv_path, index=False)
90
+
91
+
92
+ def requires_cleanup(snapshot: DiskSnapshot, *, min_free_gb: float = 8.0) -> bool:
93
+ return bool(snapshot.projected_free_after_gb < float(min_free_gb))
94
+
95
+
96
+ def _compress_file(path: Path) -> tuple[float, float]:
97
+ before = path.stat().st_size / (1024**2)
98
+ gz_path = path.with_suffix(path.suffix + ".gz")
99
+ with path.open("rb") as src, gzip.open(gz_path, "wb", compresslevel=6) as dst:
100
+ shutil.copyfileobj(src, dst)
101
+ path.unlink(missing_ok=True)
102
+ after = gz_path.stat().st_size / (1024**2)
103
+ return before, after
104
+
105
+
106
+ def _prune_batches(raw_root: Path, keep_first_n: int) -> tuple[float, float]:
107
+ before = directory_size_bytes(raw_root) / (1024**2)
108
+ batches = sorted([p for p in raw_root.iterdir() if p.is_dir()])
109
+ for batch in batches[keep_first_n:]:
110
+ shutil.rmtree(batch, ignore_errors=True)
111
+ after = directory_size_bytes(raw_root) / (1024**2)
112
+ return before, after
113
+
114
+
115
+ def run_repository_local_cleanup(
116
+ repo_root: Path,
117
+ *,
118
+ results_dir: Path,
119
+ keep_raw_batches: int = 6,
120
+ ) -> List[DiskCleanupAction]:
121
+ actions: List[DiskCleanupAction] = []
122
+
123
+ def record(action: str, target: Path, before: float, after: float, status: str, reason: str) -> None:
124
+ actions.append(
125
+ DiskCleanupAction(
126
+ timestamp_utc=_utc_now(),
127
+ action=action,
128
+ target=str(target),
129
+ size_before_mb=float(before),
130
+ size_after_mb=float(after),
131
+ reclaimed_mb=max(0.0, float(before - after)),
132
+ status=status,
133
+ reason=reason,
134
+ )
135
+ )
136
+
137
+ # 1) Remove replay caches after summary tables are present.
138
+ for replay in results_dir.glob("*/replay_cache"):
139
+ parent = replay.parent
140
+ if not _is_within_repo(replay, repo_root):
141
+ record("remove_dir", replay, 0.0, 0.0, "skipped", "outside_repo_guard")
142
+ continue
143
+ if not (parent / "summary.json").exists():
144
+ record("remove_dir", replay, 0.0, 0.0, "skipped", "missing_summary")
145
+ continue
146
+ before = directory_size_bytes(replay) / (1024**2)
147
+ shutil.rmtree(replay, ignore_errors=True)
148
+ after = directory_size_bytes(replay) / (1024**2) if replay.exists() else 0.0
149
+ record("remove_dir", replay, before, after, "ok", "replay_cache_not_required_for_final_reports")
150
+
151
+ # 2) Prune oversized raw output batches but keep representative subset.
152
+ for raw_root in list(results_dir.glob("*/raw_rdock_outputs")) + list(results_dir.glob("*/predock/raw_rdock_outputs")):
153
+ if not raw_root.exists() or not raw_root.is_dir():
154
+ continue
155
+ if not _is_within_repo(raw_root, repo_root):
156
+ record("prune_batches", raw_root, 0.0, 0.0, "skipped", "outside_repo_guard")
157
+ continue
158
+ before, after = _prune_batches(raw_root, keep_first_n=keep_raw_batches)
159
+ record("prune_batches", raw_root, before, after, "ok", "keep_representative_raw_batches_only")
160
+
161
+ # 3) Compress large logs.
162
+ for log_file in results_dir.rglob("*.log"):
163
+ if not log_file.exists() or not log_file.is_file():
164
+ continue
165
+ if not _is_within_repo(log_file, repo_root):
166
+ record("compress_log", log_file, 0.0, 0.0, "skipped", "outside_repo_guard")
167
+ continue
168
+ if log_file.stat().st_size < 2 * 1024 * 1024:
169
+ continue
170
+ before, after = _compress_file(log_file)
171
+ record("compress_log", log_file, before, after, "ok", "large_log_compression")
172
+
173
+ # 4) Remove stale duplicate work dirs if summaries exist.
174
+ for work_dir in results_dir.glob("*/work"):
175
+ parent = work_dir.parent
176
+ if not (parent / "summary.json").exists():
177
+ continue
178
+ if not _is_within_repo(work_dir, repo_root):
179
+ record("remove_work_dir", work_dir, 0.0, 0.0, "skipped", "outside_repo_guard")
180
+ continue
181
+ before = directory_size_bytes(work_dir) / (1024**2)
182
+ shutil.rmtree(work_dir, ignore_errors=True)
183
+ record("remove_work_dir", work_dir, before, 0.0, "ok", "parsed_outputs_already_persisted")
184
+
185
+ return actions
186
+
187
+
188
+ def write_cleanup_actions(path: Path, actions: Iterable[DiskCleanupAction]) -> None:
189
+ lines = ["# Disk Cleanup Actions", ""]
190
+ actions = list(actions)
191
+ if not actions:
192
+ lines.append("- No cleanup actions executed.")
193
+ else:
194
+ for a in actions:
195
+ lines.append(
196
+ f"- [{a.timestamp_utc}] action={a.action} target=`{a.target}` status={a.status} "
197
+ f"reclaimed_mb={a.reclaimed_mb:.2f} reason={a.reason}"
198
+ )
199
+ path.parent.mkdir(parents=True, exist_ok=True)
200
+ path.write_text("\n".join(lines), encoding="utf-8")
201
+
202
+
203
+ def write_disk_guard_report(
204
+ path: Path,
205
+ snapshots: Iterable[DiskSnapshot],
206
+ actions: Iterable[DiskCleanupAction],
207
+ *,
208
+ min_free_gb: float,
209
+ ) -> None:
210
+ snaps = list(snapshots)
211
+ acts = list(actions)
212
+ lines = [
213
+ "# Disk Guard Report",
214
+ "",
215
+ f"- Min free threshold (GB): `{min_free_gb}`",
216
+ f"- Snapshots captured: `{len(snaps)}`",
217
+ f"- Cleanup actions: `{len(acts)}`",
218
+ "",
219
+ "## Snapshot Timeline",
220
+ ]
221
+ for s in snaps:
222
+ lines.append(
223
+ f"- [{s.timestamp_utc}] stage={s.stage} free_gb={s.free_gb:.2f} repo_size_gb={s.repo_size_gb:.2f} "
224
+ f"projected_output_gb={s.projected_output_gb:.2f} projected_free_after_gb={s.projected_free_after_gb:.2f} note={s.note}"
225
+ )
226
+ lines.extend(["", "## Cleanup Summary"])
227
+ reclaimed = sum(a.reclaimed_mb for a in acts if a.status == "ok")
228
+ lines.append(f"- Total reclaimed MB: `{reclaimed:.2f}`")
229
+ outside_repo_violations = [a for a in acts if a.reason == "outside_repo_guard" and a.status == "ok"]
230
+ lines.append(f"- Outside-repo destructive actions: `{len(outside_repo_violations)}`")
231
+ path.parent.mkdir(parents=True, exist_ok=True)
232
+ path.write_text("\n".join(lines), encoding="utf-8")
233
+