diff --git a/README_SERVER.md b/README_SERVER.md new file mode 100644 index 0000000000000000000000000000000000000000..10406da20ad78adb6af60f29e2e57677acb2f097 --- /dev/null +++ b/README_SERVER.md @@ -0,0 +1,112 @@ +# Portable rDock Pipeline + +## List known-good PDB complexes +```bash +python scripts/prepare_pdb_ligand_dataset.py --list-known-good +``` + +## Inspect hetero ligands for a PDB +```bash +python scripts/prepare_pdb_ligand_dataset.py \ + --list-hetero \ + --pdb-id 1A52 +``` + +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. + +## Prepare a dataset for one PDB complex +```bash +python scripts/prepare_pdb_ligand_dataset.py \ + --pdb-id 4HG7 \ + --receptor-chain A \ + --reference-ligand-resname NUT \ + --reference-ligand-chain A \ + --n-ligands 1000 \ + --ligand-source smiles_file \ + --smiles-file data/examples/example_smiles_1000.smi \ + --out /data/datasets/rdock_4hg7_1000 \ + --force +``` + +## Auto-detect the reference ligand +```bash +python scripts/prepare_pdb_ligand_dataset.py \ + --pdb-id 1A52 \ + --receptor-chain A \ + --auto-reference-ligand \ + --n-ligands 1000 \ + --ligand-source smiles_file \ + --smiles-file data/examples/example_smiles_1000.smi \ + --out /data/datasets/rdock_1a52_1000 \ + --force +``` + +## Validate an existing dataset directory +```bash +python scripts/prepare_pdb_ligand_dataset.py \ + --validate-only \ + --out /data/datasets/rdock_4hg7_1000 +``` + +or + +```bash +python -m docking_pipeline validate-dataset \ + --dataset-dir /data/datasets/rdock_4hg7_1000 +``` + +## Prepare a real 1000-SMILES example file +```bash +python scripts/download_example_smiles.py \ + --n 1000 \ + --out data/examples/example_smiles_1000.smi +``` + +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. + +## Large libraries +For large libraries such as `50000` ligands, use a real SMILES file: + +```bash +python scripts/prepare_pdb_ligand_dataset.py \ + --pdb-id 1A52 \ + --receptor-chain A \ + --auto-reference-ligand \ + --n-ligands 50000 \ + --ligand-source smiles_file \ + --smiles-file /data/libraries/real_50k_library.smi \ + --out /data/datasets/rdock_1a52_50k \ + --force +``` + +`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`. + +## Run multi-fidelity docking +```bash +python -m docking_pipeline benchmark-adaptive \ + --dataset-dir /data/datasets/rdock_1a52_50k \ + --strategy multifidelity_adaptive_rdock \ + --fidelity-levels 5,10,15,30,50 \ + --cost-budget-runs 250000 \ + --jobs auto \ + --cpu-fraction 0.85 \ + --out /data/results/rdock_1a52_50k_mf \ + --resume +``` + +## Results layout +- `target/`, `ligands/`, `rdock/`, `poses/`, `tables/`, `metrics/`, `plots/`, `checkpoints/` +- `report.md`, `manifest.json`, `config.yaml`, `commands.log` + +## Resume +- Re-run the same `benchmark-adaptive` command with `--resume`. +- Checkpoints are written under `checkpoints/`. + +## Output interpretation +- `full_docking_scores.csv`: exhaustive final-fidelity docking reference. +- `random_baseline_scores.csv`: random baseline at matched cost budget. +- `single_fidelity_adaptive_scores.csv`: direct final-fidelity model-priority comparator. +- `multifidelity_trace.csv`: per-ligand trace across fidelity levels. +- `promotion_decisions.csv`: promotion and rejection reasons. +- `final_hits.csv`: hit table after multi-fidelity promotion logic. +- `adaptive_benchmark_metrics.json`: aggregate benchmark metrics and cost accounting. diff --git a/check_environment.sh b/check_environment.sh new file mode 100644 index 0000000000000000000000000000000000000000..049512ec55ce7276297d71fc639e1afb612d287d --- /dev/null +++ b/check_environment.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -euo pipefail + +echo "python: $(command -v python || true)" +echo "rbdock: $(command -v rbdock || true)" +echo "rbcavity: $(command -v rbcavity || true)" +echo "obabel: $(command -v obabel || true)" + +python - <<'PY' +import importlib +import importlib.util + +mods = ["yaml", "pandas", "matplotlib", "rdkit"] +for name in mods: + print(f"{name}: {'ok' if importlib.util.find_spec(name) else 'missing'}") +PY + +python -m docking_pipeline --help >/dev/null +python scripts/prepare_pdb_ligand_dataset.py --help >/dev/null + +echo "Environment check completed." diff --git a/configs/known_good_pdb_complexes.yaml b/configs/known_good_pdb_complexes.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c6d4395368499f9ba4b2bd000d3c966e71a30bff --- /dev/null +++ b/configs/known_good_pdb_complexes.yaml @@ -0,0 +1,137 @@ +{ + "complexes": [ + { + "pdb_id": "4HG7", + "target_name": "MDM2", + "receptor_chain": "A", + "reference_ligand_resname": "NUT", + "reference_ligand_chain": "A", + "available_hetero_ligands": [ + {"resname": "NUT", "chain": "A", "residue_id": "201", "atom_count": 40, "candidate_ligand": true} + ], + "checked_download": true, + "checked_parse": true, + "checked_reference_ligand": true, + "notes": "Local parser check confirmed NUT chain A as the reference ligand." + }, + { + "pdb_id": "4WKQ", + "target_name": "EGFR", + "receptor_chain": "A", + "reference_ligand_resname": "IRE", + "reference_ligand_chain": "A", + "available_hetero_ligands": [ + {"resname": "IRE", "chain": "A", "residue_id": "1101", "atom_count": 31, "candidate_ligand": true} + ], + "checked_download": true, + "checked_parse": true, + "checked_reference_ligand": true, + "notes": "Local parser check confirmed IRE chain A." + }, + { + "pdb_id": "1IEP", + "target_name": "ABL1", + "receptor_chain": "A", + "reference_ligand_resname": "STI", + "reference_ligand_chain": "A", + "available_hetero_ligands": [ + {"resname": "STI", "chain": "A", "residue_id": "201", "atom_count": 37, "candidate_ligand": true}, + {"resname": "STI", "chain": "B", "residue_id": "202", "atom_count": 37, "candidate_ligand": true} + ], + "checked_download": true, + "checked_parse": true, + "checked_reference_ligand": true, + "notes": "Use chain A unless the alternate biological assembly is explicitly desired." + }, + { + "pdb_id": "1A52", + "target_name": "Estrogen receptor alpha", + "receptor_chain": "A", + "reference_ligand_resname": "EST", + "reference_ligand_chain": "A", + "available_hetero_ligands": [ + {"resname": "EST", "chain": "A", "residue_id": "1", "atom_count": 20, "candidate_ligand": true}, + {"resname": "EST", "chain": "B", "residue_id": "2", "atom_count": 20, "candidate_ligand": true}, + {"resname": "AU", "chain": "A", "residue_id": "265", "atom_count": 3, "candidate_ligand": false}, + {"resname": "AU", "chain": "B", "residue_id": "266", "atom_count": 3, "candidate_ligand": false} + ], + "checked_download": true, + "checked_parse": true, + "checked_reference_ligand": true, + "notes": "Correct reference ligand is EST, not MK1. AU entries are ignored as ions/metals." + }, + { + "pdb_id": "1T46", + "target_name": "ABL1 alternative complex", + "receptor_chain": "A", + "reference_ligand_resname": "STI", + "reference_ligand_chain": "A", + "available_hetero_ligands": [ + {"resname": "STI", "chain": "A", "residue_id": "3", "atom_count": 37, "candidate_ligand": true} + ], + "checked_download": true, + "checked_parse": true, + "checked_reference_ligand": true, + "notes": "Single clear STI ligand in chain A." + }, + { + "pdb_id": "3PTB", + "target_name": "Trypsin", + "receptor_chain": "A", + "reference_ligand_resname": "BEN", + "reference_ligand_chain": "A", + "available_hetero_ligands": [ + {"resname": "BEN", "chain": "A", "residue_id": "1", "atom_count": 9, "candidate_ligand": true} + ], + "checked_download": true, + "checked_parse": true, + "checked_reference_ligand": true, + "notes": "Compact benchmark target with benzamidine." + }, + { + "pdb_id": "2HYY", + "target_name": "ABL1 tetrameric assembly", + "receptor_chain": "A", + "reference_ligand_resname": "STI", + "reference_ligand_chain": "A", + "available_hetero_ligands": [ + {"resname": "STI", "chain": "A", "residue_id": "600", "atom_count": 37, "candidate_ligand": true}, + {"resname": "STI", "chain": "B", "residue_id": "600", "atom_count": 37, "candidate_ligand": true}, + {"resname": "STI", "chain": "C", "residue_id": "600", "atom_count": 37, "candidate_ligand": true}, + {"resname": "STI", "chain": "D", "residue_id": "600", "atom_count": 37, "candidate_ligand": true} + ], + "checked_download": true, + "checked_parse": true, + "checked_reference_ligand": true, + "notes": "Tetrameric structure; chain A is the default receptor chain for the portable pipeline." + }, + { + "pdb_id": "1HSG", + "target_name": "HIV protease", + "receptor_chain": "A,B", + "reference_ligand_resname": "MK1", + "reference_ligand_chain": "B", + "available_hetero_ligands": [ + {"resname": "MK1", "chain": "B", "residue_id": "902", "atom_count": 45, "candidate_ligand": true} + ], + "checked_download": true, + "checked_parse": true, + "checked_reference_ligand": true, + "notes": "Validated locally as a multi-chain receptor target with one clear ligand." + }, + { + "pdb_id": "1HVR", + "target_name": "HIV reverse transcriptase", + "receptor_chain": "A", + "reference_ligand_resname": "XK2", + "reference_ligand_chain": "A", + "available_hetero_ligands": [ + {"resname": "XK2", "chain": "A", "residue_id": "263", "atom_count": 46, "candidate_ligand": true} + ], + "checked_download": true, + "checked_parse": true, + "checked_reference_ligand": true, + "notes": "Validated locally as a single-chain receptor with one clear organic ligand." + } + ] +} diff --git a/configs/multifidelity_defaults.yaml b/configs/multifidelity_defaults.yaml new file mode 100644 index 0000000000000000000000000000000000000000..909f130779d80c74eb5c5cc01fa2bea57dc556f0 --- /dev/null +++ b/configs/multifidelity_defaults.yaml @@ -0,0 +1,14 @@ +{ + "strategy": "multifidelity_adaptive_rdock", + "fidelity_levels": [5, 10, 15, 30, 50], + "cost_budget_runs": 12500, + "promotion_fraction": 0.5, + "min_per_cluster": 1, + "max_per_cluster": 50, + "outlier_intra_z_threshold": 3.0, + "score_component_filter": "warn", + "final_fidelity_only_hits": true, + "jobs": "auto", + "cpu_fraction": 0.85, + "checkpoint_every": 1 +} diff --git a/data/examples/example_pdb_dataset_config.yaml b/data/examples/example_pdb_dataset_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4debf7d2cc2b5e325d3653f3a1aefadcb2af5547 --- /dev/null +++ b/data/examples/example_pdb_dataset_config.yaml @@ -0,0 +1,9 @@ +{ + "pdb_id": "4HG7", + "receptor_chain": "A", + "reference_ligand_resname": "NUT", + "reference_ligand_chain": "A", + "n_ligands": 50, + "smiles_file": "data/examples/example_smiles.smi", + "ligand_source": "bundled_or_remote" +} diff --git a/data/examples/example_smiles.smi b/data/examples/example_smiles.smi new file mode 100644 index 0000000000000000000000000000000000000000..f4289dd039e04290d52814c00760ebb75489c803 --- /dev/null +++ b/data/examples/example_smiles.smi @@ -0,0 +1,50 @@ +CCO ethanol +CCN ethylamine +CCC propane +CCCO propanol +CCCC butane +CC(=O)O acetic_acid +CCOC ethoxyethane +c1ccccc1 benzene +Cc1ccccc1 toluene +Oc1ccccc1 phenol +Nc1ccccc1 aniline +CC(=O)N acetamide +CC(C)O isopropanol +CC(C)N isopropylamine +C1CCCCC1 cyclohexane +C1CCNCC1 piperidine +c1ccncc1 pyridine +c1ccoc1 furan +c1ccsc1 thiophene +CCS ethanethiol +COC dimethyl_ether +CCCl chloroethane +CCBr bromoethane +CC#N acetonitrile +CC(=O)OC methyl_acetate +CC(C)(C)O tert_butanol +CC(C)(C)N tert_butylamine +CC(C)C isobutane +CC(C)CO isobutanol +CC(C)C(=O)O isobutyric_acid +c1ccc(F)cc1 fluorobenzene +c1ccc(Cl)cc1 chlorobenzene +c1ccc(Br)cc1 bromobenzene +COc1ccccc1 anisole +CCOc1ccccc1 ethoxybenzene +CCc1ccccc1 ethylbenzene +CC(=O)c1ccccc1 acetophenone +O=C(O)c1ccccc1 benzoic_acid +NC(=O)c1ccccc1 benzamide +CCN(CC)CC triethylamine +CCOCCO diethylene_glycol +NCCO ethanolamine +OCCO ethylene_glycol +CC(C)COC isobutyl_methyl_ether +CC(C)CC isoamyl +CC(C)(C)C neopentane +CNC methylamine +CN(C)C trimethylamine +CC(C)=O acetone +CCOC(=O)C ethyl_acetate diff --git a/data/examples/example_smiles_1000.smi b/data/examples/example_smiles_1000.smi new file mode 100644 index 0000000000000000000000000000000000000000..0feb97a357a085dcb0eb80fe4ca9fbe3699de9e2 --- /dev/null +++ b/data/examples/example_smiles_1000.smi @@ -0,0 +1,1000 @@ +Cc1nc2ccccc2n1CC(C)(C)c1cc(C(F)(F)F)cc(C(F)(F)F)c1 ref_nutlin3a_prelim +Cc1nc2ccccc2n1CC(F)(F)F lb_00001 +Cc1nc2ccccc2n1Cc1cccc(C(F)(F)F)c1 lb_00002 +Cc1nc2ccccc2n1-c1cc(C(F)(F)F)cc(C(F)(F)F)c1 lb_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00164 +Cc1cc(C)cc(NC(=O)Cn2c(C(F)(F)F)nc3ccccc32)c1 lb_00165 +FC(F)(F)c1cccc(-c2nc3ccccc3n2-c2ccccc2)c1 lb_00166 +FC(F)(F)c1ccccc1Cn1c(-c2ccccc2C(F)(F)F)nc2ccccc21 lb_00167 +Cc1cccc(C)c1-n1c(-c2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00168 +CC(C)(C)c1ccc(-c2nc3ccccc3n2Cc2ccccc2)cc1 lb_00169 +Fc1cccc(Cn2c(C(F)(F)F)nc3ccccc32)c1 lb_00170 +CCCn1c(-c2ccc(F)c(F)c2)nc2ccccc21 lb_00171 +CCCn1c(-c2cccc(Br)c2)nc2ccccc21 lb_00172 +CC(C)=CCC/C(C)=C/Cn1c(C)nc2ccccc21 lb_00173 +Cn1c(Nc2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00174 +CCCn1c(-c2ccccc2)nc2ccccc21 lb_00175 +CN(C)CCn1c(NCc2cccc(C(F)(F)F)c2)nc2ccccc21 lb_00176 +Nc1nonc1-c1nc2ccccc2n1Cc1cccc(C(F)(F)F)c1 lb_00177 +FC(F)(F)c1ccc(Cn2c(CN3CCCC3)nc3ccccc32)cc1 lb_00178 +Cc1ccccc1N1CCN(c2nc3ccccc3n2CC(F)(F)F)CC1 lb_00179 +CC(C)(C)c1ccc(Cn2c(-c3ccc(F)cc3)nc3ccccc32)cc1 lb_00180 +CC(C)(C)c1ccc(Cn2c(-c3ccccc3F)nc3ccccc32)cc1 lb_00181 +CCCn1c(-c2cccc(C)c2)nc2cc(C(F)(F)F)ccc21 lb_00182 +CCCn1c(-c2ccccc2F)nc2ccccc21 lb_00183 +CCCn1c(-c2cccc(C)c2)nc2ccccc21 lb_00184 +Cc1ccc(Cn2c(C(C)(C)C)nc3ccccc32)cc1 lb_00185 +Fc1ccc(Cn2c(C(F)(F)F)nc3ccccc32)cc1 lb_00186 +CCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00187 +Fc1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(Cc2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00231 +CCn1c(-c2cccc(C)c2)nc2cc(C(F)(F)F)ccc21 lb_00232 +CCCn1c(-c2ccc(C)cc2)nc2cc(C(F)(F)F)ccc21 lb_00233 +CCc1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00234 +CCCn1c(-c2cccc(C(F)(F)F)c2)nc2cc3nc(-c4cccc(C(F)(F)F)c4)n(CCC)c3cc21 lb_00235 +CCCCn1c(-c2cccc(Br)c2)nc2ccccc21 lb_00236 +CCCCn1c(-c2ccccc2)nc2ccccc21 lb_00237 +CCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00238 +Cn1c(-c2ccccc2C(F)(F)F)nc2ccccc21 lb_00239 +CCn1c(C)nc2cc(-c3ccccc3)ccc21 lb_00240 +Cn1c(-c2cc(-c3nc4ccccc4n3C)cc(C(C)(C)C)c2)nc2ccccc21 lb_00241 +CCn1c(-c2ccccc2F)nc2ccccc21 lb_00242 +C=CCn1c(C(C)(C)C)nc2ccccc21 lb_00243 +Nc1nc2ccccc2n1-c1ccc(C(F)(F)F)cc1 lb_00244 +CC(F)(F)c1ccc(Cn2c(CN3CCCC3)nc3ccccc32)cc1 lb_00245 +Cc1cccc(-c2nc3cc(C(F)(F)F)ccc3n2Cc2ccccc2)c1 lb_00246 +Cc1nc2ccccc2n1Cc1ccc2c(c1)CCc1ccccc1N2 lb_00247 +Cn1c(/C=C/c2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00248 +Cc1ccccc1Cn1c(CC(C)(C)C)nc2ccccc21 lb_00249 +Cn1c(C=Cc2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00250 +Cn1c(C#Cc2ccc(C(F)(F)F)cc2)nc2ccccc21 lb_00251 +CCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00252 +CC(F)(F)c1ccc(-c2nc3ccccc3n2-c2ccccc2)cc1 lb_00253 +Cc1cccc(-c2nc3ccccc3n2CCc2cccc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ccc21 lb_00276 +CCCn1c(-c2ccc(N)c(F)c2)nc2ccccc21 lb_00277 +CCC(c1ccccc1)c1nc2ccccc2n1-c1ccc(C(F)(F)F)cc1 lb_00278 +CC(C)n1c(C(F)(F)F)nc2ccccc21 lb_00279 +CN(CCN(C)C(=O)NCc1cc(C(F)(F)F)cc(C(F)(F)F)c1)Cc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00280 +Cc1nc2ccccc2n1Cc1ccc(B2OC(C)(C)C(C)(C)O2)cc1 lb_00281 +Cn1c(CN2CCN(Cc3cccc(C(F)(F)F)c3)CC2)nc2ccccc21 lb_00282 +Cc1nc2ccccc2n1CC1CCN(Cc2ccc(F)cc2)CC1 lb_00283 +Cc1nc2ccccc2n1CC1CCN(Cc2ccccc2F)CC1 lb_00284 +CCCCCn1c(-c2ccccc2)nc2ccccc21 lb_00285 +CC(c1ccccc1)n1c(C(F)(F)F)nc2ccccc21 lb_00286 +CC(C)CCn1c(-c2ccccc2)nc2ccccc21 lb_00287 +CC(C)(C)Cc1nc2ccccc2n1Cc1ccccc1 lb_00288 +C[C@@H](c1ccccc1)n1c(C(F)(F)F)nc2ccccc21 lb_00289 +C[C@H](c1ccccc1)n1c(C(F)(F)F)nc2ccccc21 lb_00290 +COCCn1c(-c2ccccc2)nc2ccccc21 lb_00291 +CCn1c(N)nc2cc(C(F)(F)F)ccc21 lb_00292 +Cn1c(CN2CCC(c3cccc(C(F)(F)F)c3)CC2)nc2ccccc21 lb_00293 +Cc1nc2ccccc2n1CC1CCN(Cc2cc(F)ccc2F)CC1 lb_00294 +CCN(CC)CCCn1c(-c2ccccc2C)nc2cc(C(F)(F)F)ccc21 lb_00295 +O[B-](O)(O)CSc1nc2ccccc2n1Cc1ccc(C(F)(F)F)cc1C(F)(F)F lb_00296 +CCCCCn1c(-c2cccc(C)c2)nc2ccccc21 lb_00297 +Cc1cccc(-c2nc3ccccc3n2CCC(C)C)c1 lb_00298 +FC(F)(F)c1nc2ccccc2n1CCC1CCC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N)nc3cc(C(F)(F)F)ccc32)c1 lb_00323 +Cc1ccc(-c2nc3cc(C(F)(F)F)ccc3n2Cc2ccccc2)c(C)c1 lb_00324 +Cc1nc2ccccc2n1CCNCc1cccc(C#N)c1 lb_00325 +CN(C)CCn1c(Cn2nc3ccccc3n2)nc2cc(C(F)(F)F)ccc21 lb_00326 +Cn1c(-c2cccc(C(C)(C)C)c2)nc2ccccc21 lb_00327 +CC(C)(C)Cc1nc2ccccc2n1CCc1ccccc1 lb_00328 +CCCCCCCn1c(-c2ccccc2)nc2ccccc21 lb_00329 +CCCCCCn1c(-c2ccccc2)nc2ccccc21 lb_00330 +CCCCn1c(-c2ccc(C)cc2)nc2ccccc21 lb_00331 +CCCCCCCCCCCCn1c(-c2ccccc2)nc2ccccc21 lb_00332 +CCCCn1c(-c2ccccc2C)nc2ccccc21 lb_00333 +Cn1c(-c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00334 +C=CCn1c(CC(C)(C)C)nc2ccccc21 lb_00335 +CCCn1c(-c2ccc(N)cc2)nc2ccccc21 lb_00336 +CC1(CC(F)F)Cn2c(nc3ccccc32)-c2ccc(C(F)(F)F)cc21 lb_00337 +CCCCN(CCCC)CCCn1c(-c2ccccc2C)nc2cc(C(F)(F)F)ccc21 lb_00338 +CC(C)(C)c1ccc(Cn2c(Cc3ccccc3)nc3ccccc32)cc1 lb_00339 +FC(F)(F)c1ccc([C@H]2Cc3nc4ccccc4n3C2)cc1 lb_00340 +CN(C)c1ccc(-c2ccc(-c3nc4ccccc4n3CCF)cc2)cc1 lb_00341 +CC(C)(C)c1nc2ccccc2n1CC1CCC(F)CC1 lb_00342 +CCCCCCCCCCCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00343 +CCCCCCCCCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00344 +CCCCCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00345 +CCCCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00346 +CCCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00347 +CCCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00348 +CCCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00349 +CCCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00350 +CCCCCCn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00351 +CCCCCCCCCCCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00352 +CCCCCCCCCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00353 +CCCCCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00354 +CCCCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00355 +CCCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00356 +CCCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00357 +CCCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00358 +CCCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00359 +CCCCCCn1c(-c2ccccc2F)nc2ccccc21 lb_00360 +N#Cc1ccccc1Cn1c(C(F)(F)F)nc2ccccc21 lb_00361 +FC(F)(F)c1ccc2c(c1)nc(Cc1ccccc1)n2Cc1ccccc1 lb_00362 +CC(C)Cn1c(-c2cccc(Br)c2)nc2ccccc21 lb_00363 +CC(C)(C)c1ccc(CCn2c(N)nc3ccccc32)cc1F lb_00364 +CCCCn1c(Nc2ccccc2C(F)(F)F)nc2ccccc21 lb_00365 +CCCCn1c(-c2ccc(F)cc2)nc2cc(C(F)(F)F)ccc21 lb_00366 +N#Cc1ccc(F)c(Cn2c(C(F)(F)F)nc3ccccc32)c1 lb_00367 +CCCn1c(C(CC)c2ccccc2)nc2cc(C(F)(F)F)ccc21 lb_00368 +CCCn1c(-c2ccc(C)cc2C)nc2cc(C(F)(F)F)ccc21 lb_00369 +CC(C)Cn1c(Cc2ccccc2)nc2cc(C(F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ccccc2C(F)(F)F)nc2ccccc21 lb_00416 +CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1CC(C)C lb_00417 +CCC(C)c1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00418 +CCC(c1ccccc1)c1nc2cc(C(F)(F)F)ccc2n1Cc1ccccc1 lb_00419 +Cc1nc2ccccc2n1CCCCN1CC=C(c2ccc(F)cc2)CC1 lb_00420 +Cn1c(CCN2CCN(c3cccc(C(F)(F)F)c3)CC2)nc2ccccc21 lb_00421 +Cc1ccccc1CN1CCC(Cn2c(C(F)(F)F)nc3ccccc32)CC1 lb_00422 +Cc1ccc(CN2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)cc1 lb_00423 +CCCn1c(CC)nc2ccccc21 lb_00424 +Cn1c(C(F)(F)C(F)(F)F)nc2ccccc21 lb_00425 +Cn1c(CC(C)(C)C)nc2ccccc21 lb_00426 +FC(F)(F)c1nc2ccccc2n1-c1ccccc1 lb_00427 +Cc1ccc(C)c(CN2CCC(Cn3c(C(F)(F)F)nc4ccccc43)CC2)c1 lb_00428 +Cc1ccc(Cn2c(N)nc3ccccc32)cc1 lb_00429 +Cc1ccc(Cn2c(-c3ccc(C)cc3)nc3ccccc32)cc1 lb_00430 +CCn1c(-c2ccc(N)cc2)nc2ccccc21 lb_00431 +Cc1cccc(Cn2c(-c3ccccc3)nc3ccccc32)c1 lb_00432 +CCCn1c(-c2ccc(N(C)C)cc2)nc2ccccc21 lb_00433 +C=CCn1c(-c2cccc(C)c2)nc2ccccc21 lb_00434 +FC(F)(F)c1cccc(Cn2cnc3ccccc32)c1 lb_00435 +CCc1nc2ccccc2n1Cc1cccc(C)c1 lb_00436 +Cc1ccccc1-c1nc2cc(C(F)(F)F)ccc2n1C lb_00437 +Cc1cc(C)c(C)c(Cn2c(CO)nc3ccccc32)c1C lb_00438 +CCCCn1c(-c2ccc(Br)cc2)nc2ccccc21 lb_00439 +CCCCn1c(-c2ccc(N)cc2)nc2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2ccccc2)nc2ccccc21 lb_00530 +CCn1c(-c2ccc(N(C)C)cc2)nc2ccccc21 lb_00531 +C=CCn1c(-c2ccc(C)cc2)nc2ccccc21 lb_00532 +CCc1nc2ccccc2n1Cc1ccccc1F lb_00533 +CCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00534 +Fc1ccccc1Cn1c(-c2ccccc2)nc2ccccc21 lb_00535 +Fc1cccc(F)c1-c1nc2ccccc2n1Cc1ccccc1 lb_00536 +Fc1ccccc1Cn1c(-c2ccccc2F)nc2ccccc21 lb_00537 +Fc1ccc(-c2nc3ccccc3n2Cc2ccccc2)cc1 lb_00538 +CCn1c(-c2ccc(C(C)C)cc2)nc2ccccc21 lb_00539 +Cn1c(CC(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00540 +Cc1ccc(Cn2c(C(C)C)nc3ccccc32)cc1 lb_00541 +CC(C)=CCn1c(-c2ccccc2)nc2ccccc21 lb_00542 +Fc1ccc(Cn2c(-c3ccccc3)nc3ccccc32)cc1 lb_00543 +Fc1ccccc1-c1nc2ccccc2n1Cc1ccccc1 lb_00544 +Cc1ccc(Cn2c(CO)nc3ccccc32)cc1 lb_00545 +Cn1c(Nc2ccccc2C(F)(F)F)nc2ccccc21 lb_00546 +CSc1nc2ccccc2n1Cc1ccc(C)cc1 lb_00547 +Cc1ccccc1Cn1c(CO)nc2ccccc21 lb_00548 +Fc1ccc(Cn2c(-c3ccc(F)cc3F)nc3ccccc32)c(F)c1 lb_00549 +CC(C)(C)n1c(Cc2cccc(F)c2)nc2ccccc21 lb_00550 +CCC1CCC(n2c(C(F)(F)F)nc3ccccc32)CC1 lb_00551 +Cc1ccccc1Cc1nc2ccccc2n1Cc1ccccc1F lb_00552 +Fc1ccc(-c2nc3ccccc3n2CCCc2ccccc2)cc1 lb_00553 +Fc1ccccc1-c1nc2ccccc2n1CCCc1ccccc1 lb_00554 +CCC(C)Cn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00555 +CCC(C)Cn1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n1c(Nc2ccccc2C)nc2ccccc21 lb_00688 +CN1CCN(c2nc3ccccc3n2CCc2ccccc2)CC1 lb_00689 +COCc1nc2ccccc2n1Cc1ccccc1C lb_00690 +Cc1ccccc1Cn1c(C(C)O)nc2ccccc21 lb_00691 +Cn1cccc1-c1nc2ccccc2n1Cc1ccccc1 lb_00692 +CN(C)c1ccc(Cn2c(-c3ccc(N(C)C)cc3)nc3ccccc32)cc1 lb_00693 +CCn1c(CCc2ccccc2)nc2ccccc21.Cl lb_00694 +CCn1c(/C=C/c2ccccc2)nc2ccccc21 lb_00695 +CCCc1nc2ccccc2n1CCc1ccccc1 lb_00696 +CCc1nc2ccccc2n1CCc1ccccc1.Cl lb_00697 +CCCc1nc2ccccc2n1Cc1ccccc1 lb_00698 +CC(C)c1nc2ccccc2n1CCc1ccccc1 lb_00699 +Cn1c(-c2cccc(F)c2)nc2ccccc21 lb_00700 +CCCn1c(Cc2ccccc2)nc2ccccc21 lb_00701 +Nc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00702 +CCc1nc2ccccc2n1CCC(C)C lb_00703 +Nc1nc2ccccc2n1Cc1ccccc1F lb_00704 +CCn1c(NCc2ccccc2)nc2ccccc21 lb_00705 +CCC(C)Cn1c(C(C)C)nc2ccccc21 lb_00706 +Nc1nc2ccccc2n1Cc1ccccc1 lb_00707 +CC1(N2CCC(n3c(-c4cccc(C(F)(F)F)c4)nc4ccccc43)CC2)CCCCCCC1 lb_00708 +CN1CCN(c2cc(-c3ccc(C(F)(F)F)cc3)c(C#N)c3nc4ccccc4n23)CC1 lb_00709 +FC(F)(F)c1nc2ccccc2n1CC1CCN(c2ccc(C3CCCCC3)cc2)CC1 lb_00710 +CCc1nc2ccccc2n1C1N=CC(F)=CN1c1ccc(C(F)(F)F)cc1 lb_00711 +Cc1nc2cc(C(F)(F)F)ccc2n1C1CCN(Cc2ccc(C(C)(C)C)cc2)CC1.Cl lb_00712 +Fc1cccc(CN2CCC(Cn3c(C(F)(F)F)nc4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ccccc1)c1nc2cc(C(F)(F)F)ccc2n1C(C)C lb_00734 +CCn1c(CNCc2cccc(F)c2)nc2ccccc21 lb_00735 +CCc1nc2ccccc2n1Cc1ccc(F)cc1CN lb_00736 +CCc1nc2ccccc2n1Cc1cc(F)ccc1CN lb_00737 +CN(Cc1nc2cc(C(F)(F)F)ccc2n1C)c1ccccc1 lb_00738 +CC(C)Cn1c(-c2ccc(N(C)C)cc2)nc2ccccc21 lb_00739 +CC(C)Cc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00740 +CC(C)Cc1nc2ccccc2n1Cc1ccccc1F lb_00741 +FC(F)(F)c1cccc(-c2cccc(-n3cnc4ccccc43)c2)c1 lb_00742 +CCCCn1c(C(=S)c2ccccc2)nc2ccccc21 lb_00743 +Fc1cccc(F)c1-c1nc2ccccc2n1CC1C=CC=C1 lb_00744 +CCN(CC)c1nc2ccccc2n1Cc1ccc(F)cc1 lb_00745 +Cc1nc2ccccc2n1C(C)C(N)c1ccc(F)cc1 lb_00746 +CCn1c(C(N)c2ccc(F)cc2)nc2ccccc21 lb_00747 +CCn1c(C(N)c2ccccc2F)nc2ccccc21 lb_00748 +CCSc1nc2ccccc2n1Cc1ccccc1F lb_00749 +CC(O)c1nc2ccccc2n1Cc1ccc(F)cc1 lb_00750 +CN(C)c1ccc(-c2nc3ccccc3n2Cc2ccccc2)cc1 lb_00751 +C=C(C)Cn1c(-c2ccc(N)cc2)nc2ccccc21 lb_00752 +COCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00753 +CC(O)c1nc2ccccc2n1Cc1ccccc1F lb_00754 +CC(C)Cn1c(Cc2ccccc2)nc2ccccc21 lb_00755 +CC(C)Cc1nc2ccccc2n1Cc1ccccc1 lb_00756 +CC(C)c1ccc(Cn2c(Cl)nc3ccccc32)cc1 lb_00757 +Cc1cc2nc(C)n(Cc3ccc(F)cc3)c2cc1C lb_00758 +Cn1c(-c2ccc(F)cc2F)nc2ccccc21 lb_00759 +Fc1cccc(F)c1Cc1nc2ccccc2n1Cc1c(F)cccc1F lb_00760 +FC(F)=C(F)c1nc2ccccc2n1Cc1ccccc1 lb_00761 +CCCn1c(CCc2ccccc2)nc2ccccc21 lb_00762 +CC(O)c1nc2ccccc2n1Cc1ccccc1 lb_00763 +CC(=O)c1nc2ccccc2n1Cc1ccccc1 lb_00764 +C=CCn1c(CCC)nc2ccccc21 lb_00765 +COCc1nc2ccccc2n1Cc1ccccc1 lb_00766 +FC(F)(F)c1cc(-c2cn3ccccc3n2)cc(C(F)(F)F)c1 lb_00767 +CCCCCCCn1c(CCCCCC)nc2ccccc21 lb_00768 +c1ccc(Cc2nc3ccccc3n2Cc2ccccc2)cc1 lb_00769 +Cn1c(-c2ccc(F)cc2)nc2ccccc21 lb_00770 +Cn1c(-c2ccccc2F)nc2ccccc21 lb_00771 +Cn1c(-c2c(F)cccc2F)nc2ccccc21 lb_00772 +Cc1cccc(-c2nc3ccccc3n2C)c1 lb_00773 +ClCc1nc2ccccc2n1Cc1ccccc1 lb_00774 +Nc1nc2ccccc2n1CCc1ccccc1 lb_00775 +Cn1c(-c2ccccc2)nc2ccccc21 lb_00776 +Cc1nc2cc3ccccc3cc2n1C lb_00777 +CC1(N2CCC(n3c(-c4cccc(C(F)(F)F)c4)nc4ccccc43)CC2)CCCCCCC1.Cl.Cl lb_00778 +Cc1cccc(Cn2c([C@@H](N)CC(C)C)nc3cc(C(F)(F)F)ccc32)c1 lb_00779 +CCC[C@H](N)c1nc2cc(C(F)(F)F)ccc2n1Cc1cccc(C)c1 lb_00780 +Cn1cnc2ccccc21.Fc1cc(CN2CCC(F)(F)CC2)cc(C(F)(F)F)c1 lb_00781 +CN(C)CCCn1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00782 +CCN(CC)CCn1c(Cc2cccc3ccccc23)nc2cc(C(F)(F)F)ccc21 lb_00783 +CCCCN(CCCC)CCCn1c(-c2ccc(C)cc2C)nc2cc(C(F)(F)F)ccc21 lb_00784 +CCc1n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lb_00829 +Cc1ccc(Cn2c(CCCO)nc3ccccc32)cc1 lb_00830 +CCc1nc2ccccc2n1CCCCNc1ccccc1 lb_00831 +CCCn1c(NCc2ccccc2C)nc2ccccc21 lb_00832 +Cc1ccccc1Cn1c(CCCO)nc2ccccc21 lb_00833 +Fc1ccc(Cn2c(-c3ccccn3)nc3ccccc32)cc1 lb_00834 +CCCn1c(/C=C/c2ccccc2)nc2ccccc21 lb_00835 +CC(C)Cc1nc2ccccc2n1CCc1ccccc1 lb_00836 +CCCCc1nc2ccccc2n1Cc1ccccc1 lb_00837 +CCCCn1c(Cc2ccccc2)nc2ccccc21 lb_00838 +CC(C)(C)c1ccc(-n2c(C(F)(F)F)nc3ccc(C(C)(C)C)cc32)cc1 lb_00839 +Cn1c(-c2ccc(C(F)(F)F)cc2)nc2cc(F)c(F)cc21 lb_00840 +FCCn1c(C#Cc2ccccc2)nc2ccccc21 lb_00841 +Cc1ccc(-c2nc3cc(C(F)(F)F)ccc3n2C)cc1 lb_00842 +CC(C)n1c(C(C)(C)C)nc2cc(C(F)(F)F)ccc21 lb_00843 +CC(=O)c1nc2ccccc2n1CCc1ccccc1 lb_00844 +OCc1nc2ccccc2n1Cc1ccccc1F lb_00845 +C=CCn1c(C(CC)CC)nc2ccccc21 lb_00846 +COCc1nc2ccccc2n1CCc1ccccc1 lb_00847 +CCn1c(CN(C)c2ccccc2)nc2ccccc21 lb_00848 +OCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00849 +CC(C)(C)c1ccc2nc(-c3ccccc3)n(O)c2c1 lb_00850 +NCc1cccc(Cn2c(N)nc3ccccc32)c1 lb_00851 +CC(O)c1nc2ccccc2n1CCc1ccccc1 lb_00852 +NCc1nc2ccccc2n1Cc1ccc(F)cc1 lb_00853 +c1ccc(CCn2c(Cc3ccccc3)nc3ccccc32)cc1 lb_00854 +NCc1nc2ccccc2n1Cc1ccccc1 lb_00855 +Fc1cc(C(F)(F)F)ccc1CCCCN1CCn2c(nc3ccccc32)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2)c1 lb_00991 +Cn1c(-c2ccccc2-c2ccc(F)cc2)nc2ccccc21 lb_00992 +CC(C)n1c(-c2ccc(F)cc2)nc2ccccc21 lb_00993 +Cn1c(-c2ccccc2)nc2c(C(F)(F)F)cccc21 lb_00994 +Cc1ccccc1CCc1nc2ccccc2n1C lb_00995 +CC(C)n1c(-c2ccccc2F)nc2ccccc21 lb_00996 +CCn1c(-c2ccccc2)nc2cc(C)ccc21 lb_00997 +OCCn1c(Cc2ccccc2)nc2ccccc21 lb_00998 +Cn1c(-c2cccc(N)c2)nc2ccccc21 lb_00999 diff --git a/docking_pipeline/__init__.py b/docking_pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dc16ccaabae541cce71d4d6725b8a4399635dcf9 --- /dev/null +++ b/docking_pipeline/__init__.py @@ -0,0 +1,5 @@ +"""Strict rDock-first docking pipeline.""" + +__all__ = ["__version__"] + +__version__ = "0.1.0" diff --git a/docking_pipeline/__main__.py b/docking_pipeline/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..063166f602eee55cf61feeb488b40b668dcb6a9b --- /dev/null +++ b/docking_pipeline/__main__.py @@ -0,0 +1,197 @@ +from __future__ import annotations + +import argparse +import json +from pathlib import Path + + +def _engine_from_args(args: argparse.Namespace, validation: bool = False) -> RDockEngine: + from .rdock import RDockEngine, RDockRunConfig + + return RDockEngine( + RDockRunConfig( + n_runs=int(getattr(args, "n_runs", 100 if validation else 50)), + jobs=getattr(args, "jobs", "auto"), + cpu_fraction=float(getattr(args, "cpu_fraction", 0.85)), + dock_prm=getattr(args, "dock_prm", None), + rbt_root=getattr(args, "rbt_root", None), + require_reporting_tools=validation, + ) + ) + + +def main() -> int: + parser = argparse.ArgumentParser(prog="python -m docking_pipeline", description="Strict rDock-first docking pipeline") + sub = parser.add_subparsers(dest="cmd", required=True) + + p = sub.add_parser("prepare-target") + p.add_argument("--receptor", required=True) + p.add_argument("--ref-ligand", required=True) + p.add_argument("--out", required=True) + p.add_argument("--rbt-root") + p.add_argument("--dock-prm") + + p = sub.add_parser("dock-rdock") + p.add_argument("--target-config", required=True) + p.add_argument("--ligands", required=True) + p.add_argument("--out", required=True) + p.add_argument("--n-runs", type=int, default=50) + p.add_argument("--jobs", default="auto") + p.add_argument("--cpu-fraction", type=float, default=0.85) + p.add_argument("--dock-prm") + p.add_argument("--rbt-root") + p.add_argument("--dry-run", action="store_true") + p.add_argument("--plan-only", action="store_true") + + p = sub.add_parser("validate-rdock") + p.add_argument("--set", choices=["astex", "dud", "rna"], required=True) + p.add_argument("--system") + p.add_argument("--system-list") + p.add_argument("--max-systems", type=int) + p.add_argument("--list-systems", action="store_true") + p.add_argument("--data-dir", required=True) + p.add_argument("--out", default="results/rdock_validation") + p.add_argument("--n-runs", type=int, default=100) + p.add_argument("--jobs", default="auto") + p.add_argument("--cpu-fraction", type=float, default=0.85) + p.add_argument("--download-url") + p.add_argument("--download-if-missing", action="store_true") + p.add_argument("--keep-work", action="store_true") + p.add_argument("--force", action="store_true") + p.add_argument("--dry-run", action="store_true") + p.add_argument("--plan-only", action="store_true") + + p = sub.add_parser("run-adaptive") + p.add_argument("--target-config", required=True) + p.add_argument("--ligands", required=True, help="CSV with ligand_id,smiles and optional model_score") + p.add_argument("--out", required=True) + p.add_argument("--budget", type=int, required=True) + p.add_argument("--batch-size", type=int, default=16) + p.add_argument("--n-runs", type=int, default=50) + p.add_argument("--jobs", default="auto") + p.add_argument("--cpu-fraction", type=float, default=0.85) + p.add_argument("--dock-prm") + p.add_argument("--rbt-root") + p.add_argument("--dry-run", action="store_true") + p.add_argument("--plan-only", action="store_true") + + p = sub.add_parser("benchmark-adaptive") + p.add_argument("--dataset-dir", required=True) + p.add_argument("--strategy", default="multifidelity_adaptive_rdock") + p.add_argument("--fidelity-levels", default="5,10,15,30,50") + p.add_argument("--cost-budget-runs", type=int, required=True) + p.add_argument("--adaptive-budget-ligands", type=int) + p.add_argument("--promotion-fraction", type=float, default=0.5) + p.add_argument("--min-per-cluster", type=int, default=1) + p.add_argument("--max-per-cluster", type=int, default=50) + p.add_argument("--outlier-intra-z-threshold", type=float, default=3.0) + p.add_argument("--score-component-filter", default="warn") + p.add_argument("--final-fidelity-only-hits", default="true") + p.add_argument("--resume", action="store_true") + p.add_argument("--checkpoint-every", type=int, default=1) + p.add_argument("--jobs", default="auto") + p.add_argument("--cpu-fraction", type=float, default=0.85) + p.add_argument("--out", required=True) + p.add_argument("--dry-run", action="store_true") + p.add_argument("--plan-only", action="store_true") + + p = sub.add_parser("validate-dataset") + p.add_argument("--dataset-dir", required=True) + p.add_argument("--check-rdock-tools", action="store_true") + + args = parser.parse_args() + if args.cmd == "prepare-target": + engine = _engine_from_args(args) + target = engine.prepare_target(args.receptor, args.ref_ligand, args.out) + print(json.dumps({"target_config": str(Path(args.out) / "target_config.yaml"), "target": target.__dict__}, indent=2)) + elif args.cmd == "dock-rdock": + from .rdock import load_target_config + + engine = _engine_from_args(args) + if args.dry_run or args.plan_only: + plan = { + "target_config": args.target_config, + "ligands": args.ligands, + "out": args.out, + "n_runs": args.n_runs, + "jobs": args.jobs, + "cpu_fraction": args.cpu_fraction, + "commands": ["rbcavity was already run during prepare-target", "rbdock chunks will be launched by --jobs"], + } + Path(args.out).mkdir(parents=True, exist_ok=True) + (Path(args.out) / "dock_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8") + print(json.dumps(plan, indent=2)) + return 0 + artifacts = engine.dock_sdf(load_target_config(args.target_config), args.ligands, args.out, n_runs=args.n_runs, jobs=args.jobs) + print(json.dumps(artifacts.__dict__, indent=2)) + elif args.cmd == "validate-rdock": + from .validation import discover_validation_systems, ensure_validation_data, validate_many + + if args.set == "rna": + raise SystemExit("RNA rDock validation is not implemented yet; supported sets are astex and dud.") + data_root = ensure_validation_data(args.data_dir, args.set, args.download_url, args.download_if_missing, force=args.force) + if args.list_systems: + systems = discover_validation_systems(data_root, args.set) + print(json.dumps([s.__dict__ for s in systems], indent=2)) + return 0 + result = validate_many( + args.set, + data_root, + args.out, + system=args.system, + system_list=args.system_list, + max_systems=args.max_systems, + n_runs=args.n_runs, + jobs=args.jobs, + cpu_fraction=args.cpu_fraction, + download_url=args.download_url, + download_if_missing=args.download_if_missing, + force=args.force, + dry_run=args.dry_run, + plan_only=args.plan_only, + ) + print(json.dumps(result, indent=2)) + metrics = result.get("metrics", {}) if isinstance(result, dict) else {} + if metrics.get("failures"): + return 1 + elif args.cmd == "run-adaptive": + from .adaptive import run_adaptive + from .rdock import load_target_config + + engine = _engine_from_args(args) + if args.dry_run or args.plan_only: + plan = { + "target_config": args.target_config, + "ligands": args.ligands, + "out": args.out, + "budget": args.budget, + "batch_size": args.batch_size, + "n_runs": args.n_runs, + "jobs": args.jobs, + } + Path(args.out).mkdir(parents=True, exist_ok=True) + (Path(args.out) / "adaptive_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8") + print(json.dumps(plan, indent=2)) + return 0 + 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) + print(json.dumps({"run_dir": str(run_dir)}, indent=2)) + elif args.cmd == "benchmark-adaptive": + from .benchmark_adaptive import run_from_args + + print(json.dumps(run_from_args(args), indent=2)) + elif args.cmd == "validate-dataset": + from .dataset import validate_dataset_dir + + print(json.dumps(validate_dataset_dir(args.dataset_dir, check_rdock_tools=args.check_rdock_tools), indent=2)) + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception as exc: + from .provenance import RDockPipelineError + + if isinstance(exc, RDockPipelineError): + raise SystemExit(str(exc)) + raise diff --git a/docking_pipeline/__pycache__/__init__.cpython-313.pyc b/docking_pipeline/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43992b1987641dd76c1f55509134dfaf045e2ddb Binary files /dev/null and b/docking_pipeline/__pycache__/__init__.cpython-313.pyc differ diff --git a/docking_pipeline/__pycache__/config_io.cpython-313.pyc b/docking_pipeline/__pycache__/config_io.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a61e536c956f8c50f0351deab0d92a6d4b835e9 Binary files /dev/null and b/docking_pipeline/__pycache__/config_io.cpython-313.pyc differ diff --git a/docking_pipeline/__pycache__/dataset.cpython-313.pyc b/docking_pipeline/__pycache__/dataset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f77a79d508c48df9d9c28115e568627ec74cb266 Binary files /dev/null and b/docking_pipeline/__pycache__/dataset.cpython-313.pyc differ diff --git a/docking_pipeline/__pycache__/provenance.cpython-313.pyc b/docking_pipeline/__pycache__/provenance.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3a0068f9ebb1a5122e211b43e05a3778df94b91 Binary files /dev/null and b/docking_pipeline/__pycache__/provenance.cpython-313.pyc differ diff --git a/docking_pipeline/__pycache__/rdock.cpython-313.pyc b/docking_pipeline/__pycache__/rdock.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..158c1a0a31b44d99e936cc78635d2c72310c99c7 Binary files /dev/null and b/docking_pipeline/__pycache__/rdock.cpython-313.pyc differ diff --git a/docking_pipeline/__pycache__/sdf.cpython-313.pyc b/docking_pipeline/__pycache__/sdf.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95984e0251cfb8dafea248fc8f0fe03f0d4f5616 Binary files /dev/null and b/docking_pipeline/__pycache__/sdf.cpython-313.pyc differ diff --git a/docking_pipeline/adaptive.py b/docking_pipeline/adaptive.py new file mode 100644 index 0000000000000000000000000000000000000000..869f905117adc6b03efcb13ed0e0f8d9722bdec7 --- /dev/null +++ b/docking_pipeline/adaptive.py @@ -0,0 +1,177 @@ +from __future__ import annotations + +import json +import shutil +from dataclasses import dataclass +from pathlib import Path + +from .provenance import RDockPipelineError, require_file +from .rdock import RDockEngine, TargetConfig +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 + + +@dataclass +class ScheduledBatch: + batch_index: int + ligand_ids: list[str] + + +class RealDockingScheduler: + """Simple explicit scheduler: model ranks candidates, rDock produces ground truth.""" + + def __init__(self, ligands: object, budget: int, batch_size: int) -> None: + if hasattr(ligands, "to_dict"): + rows = ligands.to_dict(orient="records") # type: ignore[call-arg] + else: + rows = list(ligands) # type: ignore[arg-type] + if not rows or "ligand_id" not in rows[0] or "smiles" not in rows[0]: + raise RDockPipelineError("Adaptive ligand CSV must contain ligand_id and smiles columns") + self.rows: list[dict[str, object]] = [dict(r) for r in rows] + self.budget = int(budget) + self.batch_size = int(batch_size) + self.completed: set[str] = set() + for row in self.rows: + model_score = _float_or_zero(row.get("model_score", 0.0)) + row["model_score"] = model_score + row["adaptive_priority"] = -model_score + row["actually_docked"] = False + + def next_batch(self) -> ScheduledBatch | None: + remaining_budget = self.budget - len(self.completed) + if remaining_budget <= 0: + return None + active = [row for row in self.rows if str(row["ligand_id"]) not in self.completed] + if not active: + return None + active = sorted(active, key=lambda r: (-float(r["adaptive_priority"]), str(r["ligand_id"]))) + ids = [str(row["ligand_id"]) for row in active[: min(self.batch_size, remaining_budget)]] + return ScheduledBatch(batch_index=len(self.completed) // max(1, self.batch_size), ligand_ids=ids) + + def update(self, docked_scores: object) -> None: + if hasattr(docked_scores, "to_dict"): + score_rows = docked_scores.to_dict(orient="records") # type: ignore[call-arg] + else: + score_rows = list(docked_scores) # type: ignore[arg-type] + for ligand_id in [str(row["ligand_id"]) for row in score_rows]: + self.completed.add(ligand_id) + for row in self.rows: + if str(row["ligand_id"]) == ligand_id: + row["actually_docked"] = True + if not score_rows: + return + scores = sorted(_float_or_zero(row.get("SCORE", 0.0)) for row in score_rows) + median_score = scores[len(scores) // 2] + for row in self.rows: + if str(row["ligand_id"]) not in self.completed: + row["adaptive_priority"] = float(row["adaptive_priority"]) + (0.001 * -median_score) + + def to_dataframe(self): + import pandas as pd + + return pd.DataFrame(self.rows) + + +def _float_or_zero(value: object) -> float: + try: + return float(value) + except Exception: + return 0.0 + + +def _prepare_batch_sdf(ligands: pd.DataFrame, ligand_ids: list[str], out_sdf: Path) -> Path: + from libs.docking.prep import prepare_ligand_sdf + + tmp = out_sdf.parent / "prepared" + tmp.mkdir(parents=True, exist_ok=True) + blocks: list[str] = [] + by_id = ligands.set_index("ligand_id") + for ligand_id in ligand_ids: + smiles = str(by_id.loc[ligand_id, "smiles"]) + sdf = prepare_ligand_sdf(ligand_id, smiles, tmp / f"{ligand_id}.sdf") + blocks.extend(split_sdf_file(sdf)) + write_sdf_blocks(blocks, out_sdf) + return out_sdf + + +def run_adaptive( + target_config: TargetConfig, + ligands_csv: str | Path, + out_dir: str | Path, + budget: int, + batch_size: int, + engine: RDockEngine, + n_runs: int | None = None, +) -> Path: + import pandas as pd + + ligands = pd.read_csv(require_file(ligands_csv, "adaptive ligand CSV")) + scheduler = RealDockingScheduler(ligands, budget=budget, batch_size=batch_size) + root = Path(out_dir) + for name in ("target", "ligands", "rdock", "poses", "tables", "metrics"): + (root / name).mkdir(parents=True, exist_ok=True) + shutil.copy2(target_config.receptor, root / "target" / Path(target_config.receptor).name) + shutil.copy2(target_config.reference_ligand, root / "target" / Path(target_config.reference_ligand).name) + + batch_records = [] + all_blocks: list[str] = [] + while True: + batch = scheduler.next_batch() + if batch is None: + break + batch_dir = root / "rdock" / f"batch_{batch.batch_index:03d}" + batch_sdf = _prepare_batch_sdf(ligands, batch.ligand_ids, root / "ligands" / f"batch_{batch.batch_index:03d}.sdf") + 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}") + best_df = pd.read_csv(artifacts.best_per_ligand_csv) + scheduler.update(best_df) + all_blocks.extend(split_sdf_file(artifacts.all_poses_sdf)) + for ligand_id in batch.ligand_ids: + batch_records.append({"batch": batch.batch_index, "ligand_id": ligand_id}) + + all_poses = root / "poses" / "all_poses.sdf" + write_sdf_blocks(all_blocks, all_poses) + if all_blocks: + records = parse_rdock_sdf_records(all_poses) + best = best_per_ligand(records) + write_sdf_records(best, root / "poses" / "best_per_ligand.sdf") + score_rows = records_to_rows(records) + best_rows = records_to_rows(best) + else: + score_rows = [] + best_rows = [] + (root / "poses" / "best_per_ligand.sdf").write_text("", encoding="utf-8") + scheduler_df = scheduler.to_dataframe() + model_cols = scheduler_df[["ligand_id", "model_score", "adaptive_priority", "actually_docked"]] + if best_rows: + model_map = model_cols.set_index("ligand_id").to_dict(orient="index") + for row in best_rows: + row.update(model_map.get(str(row["ligand_id"]), {})) + write_rows_csv(score_rows, root / "tables" / "scores_long.csv") + write_rows_csv(best_rows, root / "tables" / "best_per_ligand.csv") + scheduler_df.to_csv(root / "tables" / "scheduler_all_ligands.csv", index=False) + pd.DataFrame(batch_records).to_csv(root / "tables" / "adaptive_batches.csv", index=False) + (root / "metrics" / "validation_metrics.json").write_text("{}", encoding="utf-8") + pd.DataFrame().to_csv(root / "metrics" / "enrichment.csv", index=False) + manifest = { + "engine": "real-rdock-adaptive", + "budget": int(budget), + "batch_size": int(batch_size), + "docked_ligand_count": int(scheduler_df["actually_docked"].sum()), + "undocked_ligands_are_hits": False, + "artifacts": { + "all_poses_sdf": str(all_poses), + "best_per_ligand_csv": str(root / "tables" / "best_per_ligand.csv"), + "scheduler_all_ligands_csv": str(root / "tables" / "scheduler_all_ligands.csv"), + }, + } + (root / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") + (root / "config.yaml").write_text(f"budget: {budget}\nbatch_size: {batch_size}\n", encoding="utf-8") + (root / "commands.log").write_text("", encoding="utf-8") + for batch_log in sorted((root / "rdock").glob("batch_*/commands.log")): + with (root / "commands.log").open("a", encoding="utf-8") as dst: + dst.write(batch_log.read_text(encoding="utf-8")) + (root / "report.md").write_text( + "# Adaptive rDock Run\n\n" + "Model scores only schedule ligands. `best_per_ligand.csv` is built exclusively from real rDock SDF records with SCORE fields.\n", + encoding="utf-8", + ) + return root diff --git a/docking_pipeline/benchmark_adaptive.py b/docking_pipeline/benchmark_adaptive.py new file mode 100644 index 0000000000000000000000000000000000000000..4fd86679f246106f006603fb763695851ebc4ab6 --- /dev/null +++ b/docking_pipeline/benchmark_adaptive.py @@ -0,0 +1,900 @@ +from __future__ import annotations + +import argparse +import csv +import json +import math +import random +import shutil +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from .dataset import read_ligand_metadata, validate_dataset_dir +from .provenance import RDockPipelineError, probe_version, require_executable, require_file +from .rdock import RDockEngine, RDockRunConfig, TargetConfig, load_target_config +from .reports.plots import plot_multifidelity_outputs, plot_score_outputs +from .sdf import ligand_id_from_block, parse_tags, split_sdf_file, write_rows_csv, write_sdf_blocks + + +def _read_rows(path: str | Path) -> list[dict[str, str]]: + with Path(path).open("r", encoding="utf-8", newline="") as handle: + return list(csv.DictReader(handle)) + + +def _write_json(path: str | Path, payload: dict[str, Any]) -> Path: + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps(payload, indent=2), encoding="utf-8") + return target + + +def _float(value: object, default: float = 0.0) -> float: + try: + text = str(value).strip() + if not text: + return default + return float(text) + except Exception: + return default + + +def _bool_text(value: bool) -> str: + return "true" if value else "false" + + +def _parse_levels(text: str) -> list[int]: + try: + levels = [int(part.strip()) for part in text.split(",") if part.strip()] + except Exception as exc: + raise RDockPipelineError(f"Invalid --fidelity-levels value {text!r}: {exc}") from exc + if not levels or sorted(levels) != levels or min(levels) <= 0: + raise RDockPipelineError(f"Invalid fidelity levels: {levels}") + return levels + + +def _write_yaml_like(path: Path, payload: dict[str, Any]) -> None: + try: + import yaml + + text = yaml.safe_dump(payload, sort_keys=False) + except Exception: + text = json.dumps(payload, indent=2) + path.write_text(text, encoding="utf-8") + + +def _count_sdf(path: Path) -> int: + return len(split_sdf_file(path)) + + +def _load_input_block_map(sdf_path: Path) -> dict[str, str]: + block_map: dict[str, str] = {} + for idx, block in enumerate(split_sdf_file(sdf_path)): + tags = parse_tags(block) + ligand_id = ligand_id_from_block(block, tags, idx) + block_map[ligand_id] = block + return block_map + + +def _write_selected_sdf(block_map: dict[str, str], ligand_ids: list[str], out_path: Path) -> Path: + missing = [ligand_id for ligand_id in ligand_ids if ligand_id not in block_map] + if missing: + raise RDockPipelineError(f"Missing {len(missing)} ligand IDs in prepared SDF: {missing[:10]}") + write_sdf_blocks([block_map[ligand_id] for ligand_id in ligand_ids], out_path) + return out_path + + +def _mean(values: list[float]) -> float: + return sum(values) / len(values) if values else 0.0 + + +def _stdev(values: list[float], center: float) -> float: + if not values: + return 1.0 + var = sum((value - center) ** 2 for value in values) / max(1, len(values)) + return math.sqrt(var) or 1.0 + + +def _augment_full_rows(rows: list[dict[str, str]]) -> list[dict[str, Any]]: + ordered = sorted(rows, key=lambda row: (_float(row.get("SCORE"), float("inf")), str(row.get("ligand_id", "")))) + total = max(1, len(ordered)) + enriched: list[dict[str, Any]] = [] + for idx, row in enumerate(ordered, start=1): + item: dict[str, Any] = dict(row) + item["full_rank"] = idx + item["full_percentile"] = 100.0 if total == 1 else 100.0 * (1.0 - ((idx - 1) / (total - 1))) + enriched.append(item) + return enriched + + +def _percentile_from_rank(rank: int, total: int) -> float: + if total <= 1: + return 100.0 + return 100.0 * (1.0 - ((rank - 1) / (total - 1))) + + +def _append_rank_metrics(rows: list[dict[str, Any]], full_rank_map: dict[str, int], total: int) -> list[dict[str, Any]]: + enriched: list[dict[str, Any]] = [] + for row in rows: + item = dict(row) + ligand_id = str(item["ligand_id"]) + rank = full_rank_map.get(ligand_id) + item["full_rank"] = rank if rank is not None else "" + item["full_percentile"] = _percentile_from_rank(rank, total) if rank is not None else "" + enriched.append(item) + return enriched + + +def _top_overlap(full_rows: list[dict[str, Any]], sample_rows: list[dict[str, Any]], n: int) -> int: + full_top = {str(row["ligand_id"]) for row in full_rows[:n]} + ranked = sorted(sample_rows, key=lambda row: _float(row.get("final_score", row.get("SCORE")), float("inf"))) + sample_top = {str(row["ligand_id"]) for row in ranked[:n] if str(row.get("is_final_fidelity", "")).lower() in {"true", "1"}} + return len(full_top & sample_top) + + +def _infer_cluster_id(row: dict[str, str], index: int) -> str: + for key in ("cluster_id", "scaffold_id", "series_id"): + value = str(row.get(key, "")).strip() + if value: + return value + smiles = str(row.get("smiles", "")).strip() + if smiles: + return smiles[:12] + return f"cluster_{index:05d}" + + +def _build_model_rows(rows: list[dict[str, str]]) -> list[dict[str, Any]]: + numeric_keys = [ + "reference_similarity", + "molecular_weight", + "xlogp", + "tpsa", + "hbd", + "hba", + "rotatable_bonds", + "heavy_atom_count", + ] + features: dict[str, list[float]] = {key: [] for key in numeric_keys} + parsed: list[dict[str, Any]] = [] + for idx, row in enumerate(rows): + item: dict[str, Any] = dict(row) + item["cluster_id"] = _infer_cluster_id(row, idx) + scaffold_match = str(row.get("scaffold_match", "")).strip().lower() in {"1", "true", "yes", "y"} + is_reference = str(row.get("is_reference", "")).strip().lower() in {"1", "true", "yes", "y"} + item["scaffold_match_num"] = 1.0 if scaffold_match else 0.0 + item["is_reference_num"] = 1.0 if is_reference else 0.0 + sim = _float(row.get("reference_similarity"), 0.0) + model_score = _float(row.get("model_score"), sim + 0.1 * item["scaffold_match_num"] + 0.05 * item["is_reference_num"]) + item["model_score"] = model_score + for key in numeric_keys: + value = _float(row.get(key), 0.0) + item[key] = value + features[key].append(value) + parsed.append(item) + means = {key: _mean(values) for key, values in features.items()} + stdevs = {key: _stdev(values, means[key]) for key, values in features.items()} + for item in parsed: + item["feature_vector"] = [ + (_float(item[key]) - means[key]) / stdevs[key] + for key in numeric_keys + ] + [float(item["scaffold_match_num"]), float(item["is_reference_num"])] + return parsed + + +def _distance(a: list[float], b: list[float]) -> float: + return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b))) + + +def _plan_level_counts(library_size: int, levels: list[int], budget_runs: int, promotion_fraction: float) -> list[int]: + if not 0.0 < promotion_fraction <= 1.0: + raise RDockPipelineError(f"promotion_fraction must be in (0, 1], got {promotion_fraction}") + if library_size <= 0: + return [0 for _ in levels] + best_counts = [0 for _ in levels] + for final_count in range(1, library_size + 1): + counts = [0 for _ in levels] + counts[-1] = final_count + for idx in range(len(levels) - 2, -1, -1): + counts[idx] = min(library_size, max(counts[idx + 1], int(math.ceil(counts[idx + 1] / promotion_fraction)))) + cost = sum(count * level for count, level in zip(counts, levels)) + if cost <= budget_runs: + best_counts = counts + else: + break + if not any(best_counts): + base = min(library_size, max(1, budget_runs // levels[0])) + best_counts[0] = base + for idx in range(1, len(levels)): + best_counts[idx] = 0 + return best_counts + + +def _select_diverse(rows: list[dict[str, Any]], target_count: int, min_per_cluster: int, max_per_cluster: int) -> list[dict[str, Any]]: + if target_count <= 0 or not rows: + return [] + cluster_counts: dict[str, int] = {} + selected: list[dict[str, Any]] = [] + cluster_buckets: dict[str, list[dict[str, Any]]] = {} + for row in rows: + cluster_buckets.setdefault(str(row["cluster_id"]), []).append(row) + for cluster_id in sorted(cluster_buckets): + bucket = cluster_buckets[cluster_id] + take = min(len(bucket), min_per_cluster, max_per_cluster, target_count - len(selected)) + selected.extend(bucket[:take]) + cluster_counts[cluster_id] = take + if len(selected) >= target_count: + return selected[:target_count] + for row in rows: + cluster_id = str(row["cluster_id"]) + current = cluster_counts.get(cluster_id, 0) + if current >= max_per_cluster: + continue + if any(str(existing["ligand_id"]) == str(row["ligand_id"]) for existing in selected): + continue + selected.append(row) + cluster_counts[cluster_id] = current + 1 + if len(selected) >= target_count: + break + return selected[:target_count] + + +@dataclass +class MultiFidelityConfig: + strategy: str + fidelity_levels: list[int] + cost_budget_runs: int + adaptive_budget_ligands: int | None + promotion_fraction: float + min_per_cluster: int + max_per_cluster: int + outlier_intra_z_threshold: float + score_component_filter: str + final_fidelity_only_hits: bool + checkpoint_every: int + jobs: int | str + cpu_fraction: float + resume: bool + + +class MultiFidelityAdaptiveRunner: + def __init__( + self, + dataset_dir: str | Path, + out_dir: str | Path, + engine: RDockEngine, + config: MultiFidelityConfig, + ) -> None: + self.dataset_dir = Path(dataset_dir) + self.out_dir = Path(out_dir) + self.engine = engine + self.config = config + self.dataset_validation = validate_dataset_dir(self.dataset_dir, check_rdock_tools=False) + self.manifest = self.dataset_validation["manifest"] + self.target_config = load_target_config(self.dataset_dir / "target" / "rdock_prm" / "target_config.yaml") + self.ligands_sdf = require_file(self.dataset_dir / "ligands" / "all_ligands.sdf", "dataset ligand library") + metadata_path = self.dataset_dir / "ligands" / "ligand_metadata.csv" + if metadata_path.exists(): + metadata_rows = read_ligand_metadata(metadata_path) + else: + metadata_rows = [{"ligand_id": ligand_id, "smiles": ""} for ligand_id in self._load_block_map()] + self.model_rows = _build_model_rows(metadata_rows) + self.model_by_id = {str(row["ligand_id"]): row for row in self.model_rows} + self.block_map = self._load_block_map() + self.final_level = self.config.fidelity_levels[-1] + self.trace_rows: list[dict[str, Any]] = [] + self.promotion_rows: list[dict[str, Any]] = [] + self.state_by_id: dict[str, dict[str, Any]] = {} + self.training_time_total = 0.0 + self.docking_time_total = 0.0 + self.overhead_time_total = 0.0 + self._init_state() + + def _load_block_map(self) -> dict[str, str]: + return _load_input_block_map(Path(self.ligands_sdf)) + + def _init_state(self) -> None: + for row in self.model_rows: + ligand_id = str(row["ligand_id"]) + self.state_by_id[ligand_id] = { + "ligand_id": ligand_id, + "cluster_id": str(row["cluster_id"]), + "model_score": float(row["model_score"]), + "surrogate_score": float(row["model_score"]), + "selected_fidelity_runs": 0, + "current_best_score": "", + "current_best_score_level": "", + "final_score": "", + "is_final_fidelity": False, + "n_rdock_runs_total_spent": 0, + "promoted_from_level": "", + "promoted_to_level": "", + "promotion_reason": "", + "batch_id": "", + "rdock_success": False, + "failed_reason": "", + "timing_docking_seconds": 0.0, + "timing_training_seconds": 0.0, + "intra_outlier": False, + "score_outlier": False, + "component_warning": "", + } + + def _write_checkpoint(self, name: str, payload: dict[str, Any]) -> None: + checkpoint_dir = self.out_dir / "checkpoints" + checkpoint_dir.mkdir(parents=True, exist_ok=True) + _write_json(checkpoint_dir / f"{name}.json", payload) + + def _prepare_output_layout(self) -> None: + for name in ("target", "ligands", "rdock", "poses", "tables", "metrics", "plots", "checkpoints"): + (self.out_dir / name).mkdir(parents=True, exist_ok=True) + target_dir = self.out_dir / "target" + shutil.copy2(require_file(self.dataset_dir / "target" / "target.mol2", "dataset target.mol2"), target_dir / "target.mol2") + shutil.copy2(require_file(self.dataset_dir / "target" / "reference_ligand.sdf", "dataset reference_ligand.sdf"), target_dir / "reference_ligand.sdf") + prm_dir = target_dir / "rdock_prm" + prm_dir.mkdir(parents=True, exist_ok=True) + for path in (self.dataset_dir / "target" / "rdock_prm").iterdir(): + if path.is_file(): + shutil.copy2(path, prm_dir / path.name) + shutil.copy2(self.ligands_sdf, self.out_dir / "ligands" / "all_ligands.sdf") + + def _run_full_docking(self) -> tuple[list[dict[str, Any]], dict[str, Any]]: + full_dir = self.out_dir / "full_docking" + full_dir.mkdir(parents=True, exist_ok=True) + start = time.time() + artifacts = self.engine.dock_sdf( + self.target_config, + self.ligands_sdf, + full_dir, + n_runs=self.final_level, + jobs=self.config.jobs, + run_id=f"{self.out_dir.name}_full", + resume=self.config.resume, + ) + elapsed = time.time() - start + rows = _augment_full_rows(_read_rows(artifacts.best_per_ligand_csv)) + write_rows_csv(rows, self.out_dir / "tables" / "full_docking_scores.csv") + metrics = { + "library_size": _count_sdf(Path(self.ligands_sdf)), + "successful_ligands": len(rows), + "failed_ligands": max(0, _count_sdf(Path(self.ligands_sdf)) - len(rows)), + "pose_count": _count_sdf(Path(artifacts.all_poses_sdf)), + "best_SCORE": _float(rows[0]["SCORE"]) if rows else None, + "full_docking_seconds": elapsed, + "n_runs": self.final_level, + "best_ligand_id": rows[0]["ligand_id"] if rows else None, + } + _write_json(self.out_dir / "metrics" / "rdock_metrics.json", metrics) + return rows, metrics + + def _run_single_fidelity_adaptive(self, count: int) -> tuple[list[dict[str, Any]], float]: + if count <= 0: + return [], 0.0 + ordered = sorted( + self.model_rows, + key=lambda row: (-float(row["model_score"]), str(row["cluster_id"]), str(row["ligand_id"])), + ) + selected = _select_diverse(ordered, count, self.config.min_per_cluster, self.config.max_per_cluster) + selected_ids = [str(row["ligand_id"]) for row in selected] + run_dir = self.out_dir / "single_fidelity_adaptive" + run_dir.mkdir(parents=True, exist_ok=True) + sdf_path = self.out_dir / "ligands" / "single_fidelity_adaptive.sdf" + _write_selected_sdf(self.block_map, selected_ids, sdf_path) + start = time.time() + self.engine.dock_sdf( + self.target_config, + sdf_path, + run_dir, + n_runs=self.final_level, + jobs=self.config.jobs, + run_id=f"{self.out_dir.name}_single", + resume=self.config.resume, + ) + elapsed = time.time() - start + rows = [dict(row) for row in _read_rows(run_dir / "tables" / "best_per_ligand.csv")] + for row in rows: + row["is_final_fidelity"] = True + row["final_score"] = row.get("SCORE", "") + write_rows_csv(rows, self.out_dir / "tables" / "single_fidelity_adaptive_scores.csv") + return rows, elapsed + + def _run_random_baseline(self, cost_budget_runs: int) -> tuple[list[dict[str, Any]], float]: + count = max(1, cost_budget_runs // self.final_level) + population = [str(row["ligand_id"]) for row in self.model_rows] + selected_ids = random.Random(42).sample(population, min(len(population), count)) + run_dir = self.out_dir / "random_baseline" + run_dir.mkdir(parents=True, exist_ok=True) + sdf_path = self.out_dir / "ligands" / "random_baseline.sdf" + _write_selected_sdf(self.block_map, selected_ids, sdf_path) + start = time.time() + self.engine.dock_sdf( + self.target_config, + sdf_path, + run_dir, + n_runs=self.final_level, + jobs=self.config.jobs, + run_id=f"{self.out_dir.name}_random", + resume=self.config.resume, + ) + elapsed = time.time() - start + rows = [dict(row) for row in _read_rows(run_dir / "tables" / "best_per_ligand.csv")] + for row in rows: + row["is_final_fidelity"] = True + row["final_score"] = row.get("SCORE", "") + row["n_rdock_runs_total_spent"] = self.final_level + write_rows_csv(rows, self.out_dir / "tables" / "random_baseline_scores.csv") + return rows, elapsed + + def _penalize_rows(self, rows: list[dict[str, Any]], level: int) -> list[dict[str, Any]]: + score_values = [_float(row.get("SCORE"), float("nan")) for row in rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}] + intra_values = [_float(row.get("SCORE.INTRA"), float("nan")) for row in rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}] + score_mean = _mean(score_values) + intra_mean = _mean(intra_values) + score_sd = _stdev(score_values, score_mean) + intra_sd = _stdev(intra_values, intra_mean) + output: list[dict[str, Any]] = [] + for row in rows: + item = dict(row) + score = _float(item.get("SCORE"), float("inf")) + intra = _float(item.get("SCORE.INTRA"), 0.0) + score_z = (score - score_mean) / score_sd if math.isfinite(score) else 0.0 + intra_z = (intra - intra_mean) / intra_sd if math.isfinite(intra) else 0.0 + dominant_intra = abs(intra) > max(10.0, abs(score) * 1.5) + intra_outlier = intra_z < (-abs(self.config.outlier_intra_z_threshold)) or dominant_intra + score_outlier = score_z < -4.0 + penalty = 0.0 + warnings: list[str] = [] + if intra_outlier: + penalty += min(25.0, abs(intra_z) * 2.0 if math.isfinite(intra_z) else 10.0) + warnings.append("intra_outlier") + if score_outlier: + penalty += 5.0 + warnings.append("score_outlier") + item["intra_outlier"] = intra_outlier + item["score_outlier"] = score_outlier + item["component_warning"] = ",".join(warnings) + item["ranking_score"] = score + penalty + item["selected_fidelity_runs"] = level + output.append(item) + return output + + def _promotion_priority(self, row: dict[str, Any]) -> float: + ranking_score = _float(row.get("ranking_score"), float("inf")) + model_score = _float(row.get("model_score"), 0.0) + surrogate_score = _float(row.get("surrogate_score"), 0.0) + return ranking_score - (0.5 * surrogate_score) - (0.25 * model_score) + + def _update_surrogate(self, observed_rows: list[dict[str, Any]]) -> float: + start = time.time() + observed = [(str(row["ligand_id"]), _float(row.get("ranking_score"), float("inf"))) for row in observed_rows] + if not observed: + return 0.0 + observed_ids = [ligand_id for ligand_id, _ in observed] + for row in self.model_rows: + ligand_id = str(row["ligand_id"]) + if ligand_id in observed_ids: + row["surrogate_score"] = -_float(next(item[1] for item in observed if item[0] == ligand_id)) + continue + neighbors: list[tuple[float, float]] = [] + for observed_id, ranking_score in observed: + ref = self.model_by_id[observed_id] + dist = _distance(row["feature_vector"], ref["feature_vector"]) + neighbors.append((dist, ranking_score)) + neighbors.sort(key=lambda item: item[0]) + top = neighbors[: min(16, len(neighbors))] + weights = [1.0 / (1.0 + dist) for dist, _ in top] + total_weight = sum(weights) or 1.0 + predicted = sum(weight * score for weight, (_, score) in zip(weights, top)) / total_weight + row["surrogate_score"] = -predicted + return time.time() - start + + def _record_level_rows(self, level: int, batch_id: int, rows: list[dict[str, Any]], level_seconds: float, training_seconds: float) -> None: + level_rows: list[dict[str, Any]] = [] + for row in rows: + ligand_id = str(row["ligand_id"]) + state = self.state_by_id[ligand_id] + raw_score = row.get("SCORE", "") + current_best = state["current_best_score"] + if current_best == "" or _float(raw_score, float("inf")) < _float(current_best, float("inf")): + state["current_best_score"] = raw_score + state["current_best_score_level"] = level + state["selected_fidelity_runs"] = level + state["surrogate_score"] = self.model_by_id[ligand_id].get("surrogate_score", state["surrogate_score"]) + state["n_rdock_runs_total_spent"] = int(state["n_rdock_runs_total_spent"]) + level + state["batch_id"] = batch_id + state["rdock_success"] = str(row.get("rdock_success", True)).lower() in {"true", "1"} + state["failed_reason"] = row.get("failed_reason", "") + state["timing_docking_seconds"] = _float(state["timing_docking_seconds"]) + level_seconds / max(1, len(rows)) + state["timing_training_seconds"] = _float(state["timing_training_seconds"]) + training_seconds / max(1, len(rows)) + state["intra_outlier"] = row.get("intra_outlier", False) + state["score_outlier"] = row.get("score_outlier", False) + state["component_warning"] = row.get("component_warning", "") + if level == self.final_level and state["rdock_success"]: + state["final_score"] = raw_score + state["is_final_fidelity"] = True + merged = dict(state) + merged.update({key: value for key, value in row.items() if key not in merged}) + self.trace_rows.append(merged) + level_rows.append(merged) + write_rows_csv(level_rows, self.out_dir / "tables" / f"fidelity_level_{level}_scores.csv") + + def _run_level(self, level: int, level_index: int, selected_ids: list[str]) -> list[dict[str, Any]]: + level_dir = self.out_dir / "rdock" / f"fidelity_{level:03d}" + selection_path = level_dir / "selection.json" + level_dir.mkdir(parents=True, exist_ok=True) + if not (self.config.resume and selection_path.exists()): + _write_json( + selection_path, + { + "level": level, + "level_index": level_index, + "ligand_ids": selected_ids, + }, + ) + sdf_path = self.out_dir / "ligands" / f"fidelity_{level:03d}.sdf" + if not (self.config.resume and sdf_path.exists() and _count_sdf(sdf_path) == len(selected_ids)): + _write_selected_sdf(self.block_map, selected_ids, sdf_path) + start = time.time() + self.engine.dock_sdf( + self.target_config, + sdf_path, + level_dir, + n_runs=level, + jobs=self.config.jobs, + run_id=f"{self.out_dir.name}_fidelity_{level:03d}", + resume=self.config.resume, + ) + level_seconds = time.time() - start + self.docking_time_total += level_seconds + best_rows = [] + success_rows = {str(row["ligand_id"]): dict(row) for row in _read_rows(level_dir / "tables" / "best_per_ligand.csv")} + for ligand_id in selected_ids: + row = success_rows.get(ligand_id, {"ligand_id": ligand_id, "rdock_success": False, "failed_reason": "missing_best_pose"}) + row.setdefault("model_score", self.model_by_id[ligand_id]["model_score"]) + row.setdefault("cluster_id", self.model_by_id[ligand_id]["cluster_id"]) + row.setdefault("surrogate_score", self.model_by_id[ligand_id].get("surrogate_score", self.model_by_id[ligand_id]["model_score"])) + row["rdock_success"] = bool(success_rows.get(ligand_id)) + best_rows.append(row) + penalized = self._penalize_rows(best_rows, level) + training_seconds = self._update_surrogate(penalized) + self.training_time_total += training_seconds + self._record_level_rows(level, level_index, penalized, level_seconds, training_seconds) + return penalized + + def _promotion_reason(self, row: dict[str, Any]) -> str: + reasons = [f"ranking_score={row.get('ranking_score')}", f"cluster={row.get('cluster_id')}"] + if row.get("component_warning"): + reasons.append(str(row["component_warning"])) + return ";".join(reasons) + + def _promote( + self, + rows: list[dict[str, Any]], + current_level: int, + next_level: int, + target_count: int, + ) -> list[str]: + successful = [row for row in rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}] + ordered = sorted( + successful, + key=lambda row: ( + self._promotion_priority(row), + -_float(row.get("model_score"), 0.0), + str(row.get("cluster_id", "")), + str(row.get("ligand_id", "")), + ), + ) + chosen_rows = _select_diverse(ordered, target_count, self.config.min_per_cluster, self.config.max_per_cluster) + promoted_ids = [str(row["ligand_id"]) for row in chosen_rows] + for row in ordered: + ligand_id = str(row["ligand_id"]) + decision = { + "ligand_id": ligand_id, + "cluster_id": row.get("cluster_id", ""), + "from_level": current_level, + "to_level": next_level if ligand_id in promoted_ids else "", + "promoted": ligand_id in promoted_ids, + "promotion_reason": self._promotion_reason(row) if ligand_id in promoted_ids else "not selected", + "ranking_score": row.get("ranking_score", ""), + "SCORE": row.get("SCORE", ""), + "SCORE.INTER": row.get("SCORE.INTER", ""), + "SCORE.INTRA": row.get("SCORE.INTRA", ""), + "component_warning": row.get("component_warning", ""), + } + self.promotion_rows.append(decision) + state = self.state_by_id[ligand_id] + if ligand_id in promoted_ids: + state["promoted_from_level"] = current_level + state["promoted_to_level"] = next_level + state["promotion_reason"] = decision["promotion_reason"] + return promoted_ids + + def _initial_selection(self, target_count: int) -> list[str]: + ordered = sorted( + self.model_rows, + key=lambda row: (-float(row["model_score"]), str(row["cluster_id"]), str(row["ligand_id"])), + ) + selected = _select_diverse(ordered, target_count, self.config.min_per_cluster, self.config.max_per_cluster) + return [str(row["ligand_id"]) for row in selected] + + def run_multifidelity(self) -> dict[str, Any]: + self._prepare_output_layout() + full_rows, full_metrics = self._run_full_docking() + single_count = max(1, self.config.cost_budget_runs // self.final_level) + single_rows, single_seconds = self._run_single_fidelity_adaptive(single_count) + random_rows, random_seconds = self._run_random_baseline(self.config.cost_budget_runs) + + level_counts = _plan_level_counts( + library_size=_count_sdf(Path(self.ligands_sdf)), + levels=self.config.fidelity_levels, + budget_runs=self.config.cost_budget_runs, + promotion_fraction=self.config.promotion_fraction, + ) + if self.config.adaptive_budget_ligands is not None and level_counts: + level_counts[0] = min(level_counts[0], int(self.config.adaptive_budget_ligands)) + selected_ids = self._initial_selection(level_counts[0] if level_counts else 0) + observed_rows: list[dict[str, Any]] = [] + per_level_summary: list[dict[str, Any]] = [] + for idx, level in enumerate(self.config.fidelity_levels): + if not selected_ids: + break + level_rows = self._run_level(level, idx, selected_ids) + observed_rows.extend(level_rows) + outlier_count = sum(1 for row in level_rows if str(row.get("intra_outlier", "")).lower() in {"true", "1"}) + successful_count = sum(1 for row in level_rows if str(row.get("rdock_success", "")).lower() in {"true", "1"}) + per_level_summary.append( + { + "fidelity_level": level, + "screened_ligands": len(selected_ids), + "successful_ligands": successful_count, + "failed_ligands": len(selected_ids) - successful_count, + "outlier_count": outlier_count, + } + ) + if idx + 1 < len(self.config.fidelity_levels): + selected_ids = self._promote(level_rows, level, self.config.fidelity_levels[idx + 1], level_counts[idx + 1]) + if idx % max(1, self.config.checkpoint_every) == 0: + self._write_checkpoint( + f"level_{level:03d}", + { + "level": level, + "selected_ids": selected_ids, + "summary": per_level_summary[-1], + }, + ) + else: + selected_ids = [] + + write_rows_csv(self.trace_rows, self.out_dir / "tables" / "multifidelity_trace.csv") + write_rows_csv(self.promotion_rows, self.out_dir / "tables" / "promotion_decisions.csv") + + 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"])] + final_rows = [row for row in final_rows if row.get("final_score", "") != "" or not self.config.final_fidelity_only_hits] + final_rows.sort(key=lambda row: (_float(row.get("final_score", row.get("current_best_score")), float("inf")), str(row.get("ligand_id", "")))) + write_rows_csv(final_rows, self.out_dir / "tables" / "final_hits.csv") + + full_rank_map = {str(row["ligand_id"]): int(row["full_rank"]) for row in full_rows} + random_ranked = _append_rank_metrics(random_rows, full_rank_map, len(full_rows)) + single_ranked = _append_rank_metrics(single_rows, full_rank_map, len(full_rows)) + final_ranked = _append_rank_metrics(final_rows, full_rank_map, len(full_rows)) + write_rows_csv(random_ranked, self.out_dir / "tables" / "random_baseline_scores.csv") + write_rows_csv(single_ranked, self.out_dir / "tables" / "single_fidelity_adaptive_scores.csv") + write_rows_csv(final_ranked, self.out_dir / "tables" / "multifidelity_final_hits_ranked.csv") + + full_best = full_rows[0] if full_rows else None + final_only_rows = [row for row in final_ranked if str(row.get("is_final_fidelity", "")).lower() in {"true", "1"}] + mf_best = final_only_rows[0] if final_only_rows else None + random_best = min(random_ranked, key=lambda row: _float(row.get("final_score", row.get("SCORE")), float("inf"))) if random_ranked else None + single_best = min(single_ranked, key=lambda row: _float(row.get("final_score", row.get("SCORE")), float("inf"))) if single_ranked else None + total_runs_spent = sum(int(_float(row.get("n_rdock_runs_total_spent"), 0.0)) for row in self.state_by_id.values()) + metrics = { + "strategy": self.config.strategy, + "dataset_dir": str(self.dataset_dir), + "target_id": str(self.manifest.get("pdb_id", self.out_dir.name)).lower(), + "fidelity_levels": self.config.fidelity_levels, + "cost_budget_runs": self.config.cost_budget_runs, + "best_final_SCORE_found_by_multifidelity": _float(mf_best.get("final_score")) if mf_best else None, + "best_final_SCORE_found_by_random_at_same_cost": _float(random_best.get("final_score", random_best.get("SCORE"))) if random_best else None, + "best_SCORE_in_full_docking": _float(full_best.get("SCORE")) if full_best else None, + "best_final_SCORE_found_by_single_fidelity": _float(single_best.get("final_score", single_best.get("SCORE"))) if single_best else None, + "multifidelity_percentile_vs_full": _float(mf_best.get("full_percentile")) if mf_best else None, + "random_percentile_vs_full": _float(random_best.get("full_percentile")) if random_best else None, + "single_fidelity_percentile_vs_full": _float(single_best.get("full_percentile")) if single_best else None, + "top1_overlap_vs_full": _top_overlap(full_rows, final_ranked, 1), + "top5_overlap_vs_full": _top_overlap(full_rows, final_ranked, 5), + "top10_overlap_vs_full": _top_overlap(full_rows, final_ranked, 10), + "total_rdock_runs_spent": total_runs_spent, + "walltime_total_seconds": self.docking_time_total + self.training_time_total + self.overhead_time_total + full_metrics["full_docking_seconds"] + random_seconds + single_seconds, + "docking_time_seconds": self.docking_time_total, + "training_time_seconds": self.training_time_total, + "overhead_time_seconds": self.overhead_time_total, + "number_of_ligands_screened_at_each_fidelity": per_level_summary, + "number_promoted_between_levels": { + 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) + for current, next_level in zip(self.config.fidelity_levels[:-1], self.config.fidelity_levels[1:]) + }, + "success_failure_rate_per_fidelity": per_level_summary, + "outlier_count_per_fidelity": {str(row["fidelity_level"]): row["outlier_count"] for row in per_level_summary}, + "adaptive_gain_over_random": ( + _float(random_best.get("full_percentile")) - _float(mf_best.get("full_percentile")) + if mf_best and random_best + else None + ), + "final_hits_count": len(final_only_rows), + "full_docking_success_count": len(full_rows), + "random_final_count": len(random_ranked), + "single_fidelity_final_count": len(single_ranked), + } + _write_json(self.out_dir / "metrics" / "adaptive_benchmark_metrics.json", metrics) + _write_json(self.out_dir / "metrics" / "validation_metrics.json", metrics) + + plots = [] + plots.extend(plot_score_outputs(self.out_dir / "tables" / "full_docking_scores.csv", self.out_dir / "plots", title_prefix="full docking")) + plots.extend( + plot_multifidelity_outputs( + self.out_dir / "tables" / "multifidelity_trace.csv", + self.out_dir / "tables" / "final_hits.csv", + self.out_dir / "tables" / "random_baseline_scores.csv", + self.out_dir / "tables" / "full_docking_scores.csv", + self.out_dir / "metrics" / "adaptive_benchmark_metrics.json", + self.out_dir / "plots", + ) + ) + + report_lines = [ + f"# benchmark-adaptive: {self.manifest.get('pdb_id', self.out_dir.name)}", + "", + "## Input", + f"- dataset_dir: `{self.dataset_dir}`", + f"- strategy: `{self.config.strategy}`", + f"- fidelity_levels: `{','.join(str(v) for v in self.config.fidelity_levels)}`", + f"- cost_budget_runs: `{self.config.cost_budget_runs}`", + f"- jobs: `{self.config.jobs}`", + f"- cpu_fraction: `{self.config.cpu_fraction}`", + "", + "## Metrics", + ] + for key in [ + "best_final_SCORE_found_by_multifidelity", + "best_final_SCORE_found_by_random_at_same_cost", + "best_final_SCORE_found_by_single_fidelity", + "best_SCORE_in_full_docking", + "multifidelity_percentile_vs_full", + "random_percentile_vs_full", + "single_fidelity_percentile_vs_full", + "total_rdock_runs_spent", + "walltime_total_seconds", + "docking_time_seconds", + "training_time_seconds", + "adaptive_gain_over_random", + ]: + report_lines.append(f"- {key}: `{metrics.get(key)}`") + report_lines.extend(["", "## Plots"]) + report_lines.extend([f"- `{path}`" for path in plots] or ["- No plots generated"]) + report_lines.extend(["", "## Top Final Hits"]) + for row in final_only_rows[:20]: + report_lines.append( + f"- `{row.get('ligand_id')}` final_score `{row.get('final_score')}` " + f"cluster `{row.get('cluster_id')}` runs_spent `{row.get('n_rdock_runs_total_spent')}` " + f"warning `{row.get('component_warning', '')}`" + ) + (self.out_dir / "report.md").write_text("\n".join(report_lines) + "\n", encoding="utf-8") + + manifest = { + "engine": "benchmark-adaptive", + "strategy": self.config.strategy, + "dataset_dir": str(self.dataset_dir), + "artifacts": { + "target_dir": str(self.out_dir / "target"), + "ligands_sdf": str(self.out_dir / "ligands" / "all_ligands.sdf"), + "full_docking_scores": str(self.out_dir / "tables" / "full_docking_scores.csv"), + "random_baseline_scores": str(self.out_dir / "tables" / "random_baseline_scores.csv"), + "single_fidelity_scores": str(self.out_dir / "tables" / "single_fidelity_adaptive_scores.csv"), + "multifidelity_trace": str(self.out_dir / "tables" / "multifidelity_trace.csv"), + "promotion_decisions": str(self.out_dir / "tables" / "promotion_decisions.csv"), + "final_hits": str(self.out_dir / "tables" / "final_hits.csv"), + "metrics_json": str(self.out_dir / "metrics" / "adaptive_benchmark_metrics.json"), + "report": str(self.out_dir / "report.md"), + }, + "executables": { + "rbdock": probe_version(require_executable("rbdock")), + "rbcavity": probe_version(require_executable("rbcavity")), + "obabel": probe_version(require_executable("obabel")), + }, + "metrics": metrics, + } + _write_json(self.out_dir / "manifest.json", manifest) + _write_yaml_like( + self.out_dir / "config.yaml", + { + "dataset_dir": str(self.dataset_dir), + "strategy": self.config.strategy, + "fidelity_levels": self.config.fidelity_levels, + "cost_budget_runs": self.config.cost_budget_runs, + "promotion_fraction": self.config.promotion_fraction, + "min_per_cluster": self.config.min_per_cluster, + "max_per_cluster": self.config.max_per_cluster, + "outlier_intra_z_threshold": self.config.outlier_intra_z_threshold, + "score_component_filter": self.config.score_component_filter, + "final_fidelity_only_hits": self.config.final_fidelity_only_hits, + "jobs": self.config.jobs, + "cpu_fraction": self.config.cpu_fraction, + "resume": self.config.resume, + }, + ) + return {"run_dir": str(self.out_dir), "metrics": metrics} + + +def build_arg_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="Run adaptive rDock benchmark from a prepared dataset directory.") + parser.add_argument("--dataset-dir", required=True) + parser.add_argument("--strategy", default="multifidelity_adaptive_rdock", choices=["multifidelity_adaptive_rdock", "single_fidelity_adaptive_rdock"]) + parser.add_argument("--fidelity-levels", default="5,10,15,30,50") + parser.add_argument("--cost-budget-runs", type=int, required=True) + parser.add_argument("--adaptive-budget-ligands", type=int) + parser.add_argument("--promotion-fraction", type=float, default=0.5) + parser.add_argument("--min-per-cluster", type=int, default=1) + parser.add_argument("--max-per-cluster", type=int, default=50) + parser.add_argument("--outlier-intra-z-threshold", type=float, default=3.0) + parser.add_argument("--score-component-filter", default="warn") + parser.add_argument("--final-fidelity-only-hits", default="true") + parser.add_argument("--resume", action="store_true") + parser.add_argument("--checkpoint-every", type=int, default=1) + parser.add_argument("--jobs", default="auto") + parser.add_argument("--cpu-fraction", type=float, default=0.85) + parser.add_argument("--out", required=True) + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--plan-only", action="store_true") + return parser + + +def run_from_args(args: argparse.Namespace) -> dict[str, Any]: + levels = _parse_levels(args.fidelity_levels) + dataset_summary = validate_dataset_dir(args.dataset_dir, check_rdock_tools=False) + plan = { + "dataset_dir": args.dataset_dir, + "strategy": args.strategy, + "fidelity_levels": levels, + "cost_budget_runs": int(args.cost_budget_runs), + "adaptive_budget_ligands": args.adaptive_budget_ligands, + "promotion_fraction": float(args.promotion_fraction), + "min_per_cluster": int(args.min_per_cluster), + "max_per_cluster": int(args.max_per_cluster), + "outlier_intra_z_threshold": float(args.outlier_intra_z_threshold), + "score_component_filter": args.score_component_filter, + "final_fidelity_only_hits": str(args.final_fidelity_only_hits).lower() in {"1", "true", "yes", "y"}, + "jobs": args.jobs, + "cpu_fraction": float(args.cpu_fraction), + "dataset_summary": dataset_summary, + } + out_dir = Path(args.out) + out_dir.mkdir(parents=True, exist_ok=True) + if args.dry_run or args.plan_only: + _write_json(out_dir / "benchmark_adaptive_plan.json", plan) + return plan + config = MultiFidelityConfig( + strategy=args.strategy, + fidelity_levels=levels, + cost_budget_runs=int(args.cost_budget_runs), + adaptive_budget_ligands=args.adaptive_budget_ligands, + promotion_fraction=float(args.promotion_fraction), + min_per_cluster=int(args.min_per_cluster), + max_per_cluster=int(args.max_per_cluster), + outlier_intra_z_threshold=float(args.outlier_intra_z_threshold), + score_component_filter=str(args.score_component_filter), + final_fidelity_only_hits=str(args.final_fidelity_only_hits).lower() in {"1", "true", "yes", "y"}, + checkpoint_every=int(args.checkpoint_every), + jobs=args.jobs, + cpu_fraction=float(args.cpu_fraction), + resume=bool(args.resume), + ) + engine = RDockEngine( + RDockRunConfig( + n_runs=levels[-1], + jobs=args.jobs, + cpu_fraction=float(args.cpu_fraction), + timeout_seconds=3600, + ) + ) + runner = MultiFidelityAdaptiveRunner(args.dataset_dir, args.out, engine, config) + return runner.run_multifidelity() diff --git a/docking_pipeline/config_io.py b/docking_pipeline/config_io.py new file mode 100644 index 0000000000000000000000000000000000000000..76d73c21bcd4cd7d1b0f342de2b6238f30cf327e --- /dev/null +++ b/docking_pipeline/config_io.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from .provenance import RDockPipelineError, require_file + + +def load_structured_file(path: str | Path) -> dict[str, Any]: + source = require_file(path, "structured config file") + text = source.read_text(encoding="utf-8") + try: + payload = json.loads(text) + except json.JSONDecodeError: + try: + import yaml + except Exception as exc: + raise RDockPipelineError( + f"Could not parse {source} as JSON and PyYAML is unavailable: {exc}" + ) from exc + payload = yaml.safe_load(text) + if not isinstance(payload, dict): + raise RDockPipelineError(f"Expected mapping at top level of {source}") + return payload + + +def dump_json_like(path: str | Path, payload: dict[str, Any]) -> Path: + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps(payload, indent=2), encoding="utf-8") + return target diff --git a/docking_pipeline/dataset.py b/docking_pipeline/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..4e0421a9a23bbe80819e7fcb5f1c147752ca43e8 --- /dev/null +++ b/docking_pipeline/dataset.py @@ -0,0 +1,433 @@ +from __future__ import annotations + +import csv +import json +import math +import subprocess +import shutil +import urllib.request +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from .config_io import dump_json_like, load_structured_file +from .provenance import RDockPipelineError, probe_version, require_executable, require_file +from .rdock import RDockEngine, RDockRunConfig, load_target_config +from .sdf import split_sdf_file + + +IGNORED_SOLVENT_RESNAMES = { + "HOH", + "WAT", + "DOD", + "SOL", + "EDO", + "GOL", + "PEG", + "PG4", + "PGE", + "MPD", + "EOH", + "IPA", + "DMS", + "ACT", + "ACY", + "FMT", + "TRS", + "MES", + "BME", +} +IGNORED_BUFFER_RESNAMES = { + "SO4", + "PO4", + "CL", + "BR", + "IOD", + "NO3", + "SCN", + "IMD", + "CIT", + "ACE", +} +METAL_ELEMENTS = { + "LI", + "NA", + "K", + "RB", + "CS", + "MG", + "CA", + "SR", + "BA", + "ZN", + "FE", + "CO", + "NI", + "CU", + "MN", + "CD", + "HG", + "AG", + "AU", +} + + +def count_sdf_records(path: str | Path) -> int: + return len(split_sdf_file(path)) + + +def list_known_good_complexes(config_path: str | Path) -> list[dict[str, Any]]: + payload = load_structured_file(config_path) + complexes = payload.get("complexes") + if not isinstance(complexes, list): + raise RDockPipelineError(f"`complexes` list missing in {config_path}") + return [dict(item) for item in complexes] + + +def _parse_pdb_atom_line(line: str) -> dict[str, Any]: + record = line[:6].strip() + atom_name = line[12:16].strip() + resname = line[17:20].strip().upper() + chain = line[21:22].strip() + residue_id = line[22:26].strip() + try: + x = float(line[30:38].strip()) + y = float(line[38:46].strip()) + z = float(line[46:54].strip()) + except ValueError: + x = y = z = math.nan + element = line[76:78].strip().upper() or "".join(char for char in atom_name if char.isalpha())[:2].upper() + return { + "record": record, + "atom_name": atom_name, + "resname": resname, + "chain": chain, + "residue_id": residue_id, + "x": x, + "y": y, + "z": z, + "element": element, + "line": line, + } + + +def _is_heavy_atom(element: str) -> bool: + return bool(element) and element != "H" + + +def _classify_hetero_group(resname: str, elements: set[str], heavy_atom_count: int) -> tuple[bool, str]: + if resname in IGNORED_SOLVENT_RESNAMES: + return True, "solvent" + if resname in IGNORED_BUFFER_RESNAMES: + return True, "buffer_or_salt" + if elements and elements.issubset(METAL_ELEMENTS): + return True, "ion_or_metal" + if heavy_atom_count <= 1: + return True, "tiny_fragment" + return False, "" + + +def list_hetero_ligands(pdb_like: str | Path, min_reference_ligand_atoms: int = 8) -> list[dict[str, Any]]: + source = require_file(pdb_like, "PDB/mmCIF structure") + groups: dict[tuple[str, str, str], dict[str, Any]] = {} + for line in source.read_text(encoding="utf-8", errors="ignore").splitlines(): + if not line.startswith("HETATM"): + continue + atom = _parse_pdb_atom_line(line) + key = (atom["resname"], atom["chain"], atom["residue_id"]) + group = groups.setdefault( + key, + { + "resname": atom["resname"], + "chain": atom["chain"], + "residue_id": atom["residue_id"], + "atom_count": 0, + "heavy_atom_count": 0, + "elements": set(), + }, + ) + group["atom_count"] += 1 + if _is_heavy_atom(atom["element"]): + group["heavy_atom_count"] += 1 + if atom["element"]: + group["elements"].add(atom["element"]) + rows: list[dict[str, Any]] = [] + for _, group in sorted(groups.items()): + ignored, reason = _classify_hetero_group( + str(group["resname"]), + set(group["elements"]), + int(group["heavy_atom_count"]), + ) + rows.append( + { + "resname": str(group["resname"]), + "chain": str(group["chain"]), + "residue_id": str(group["residue_id"]), + "atom_count": int(group["atom_count"]), + "heavy_atom_count": int(group["heavy_atom_count"]), + "ignored": ignored, + "ignored_reason": reason, + "candidate_ligand": (not ignored) and int(group["heavy_atom_count"]) >= int(min_reference_ligand_atoms), + } + ) + return rows + + +def auto_detect_reference_ligand( + pdb_like: str | Path, + receptor_chain: str, + min_reference_ligand_atoms: int = 8, +) -> tuple[dict[str, Any], list[dict[str, Any]]]: + source = require_file(pdb_like, "PDB/mmCIF structure") + hetero = list_hetero_ligands(source, min_reference_ligand_atoms=min_reference_ligand_atoms) + receptor_chains = {item.strip() for item in receptor_chain.split(",") if item.strip()} + receptor_atoms: list[tuple[float, float, float]] = [] + ligand_atoms: dict[tuple[str, str, str], list[tuple[float, float, float]]] = {} + for line in source.read_text(encoding="utf-8", errors="ignore").splitlines(): + if not line.startswith(("ATOM", "HETATM")): + continue + atom = _parse_pdb_atom_line(line) + if line.startswith("ATOM") and (not receptor_chains or atom["chain"] in receptor_chains): + if not math.isnan(atom["x"]): + receptor_atoms.append((atom["x"], atom["y"], atom["z"])) + elif line.startswith("HETATM"): + key = (atom["resname"], atom["chain"], atom["residue_id"]) + ligand_atoms.setdefault(key, []) + if not math.isnan(atom["x"]): + ligand_atoms[key].append((atom["x"], atom["y"], atom["z"])) + if not receptor_atoms: + raise RDockPipelineError(f"No receptor atoms found in {source} for chain(s) {receptor_chain}") + + def _min_distance(points: list[tuple[float, float, float]]) -> float: + best = math.inf + for lx, ly, lz in points: + for rx, ry, rz in receptor_atoms: + dist = math.dist((lx, ly, lz), (rx, ry, rz)) + if dist < best: + best = dist + return best + + candidates: list[dict[str, Any]] = [] + for row in hetero: + key = (str(row["resname"]), str(row["chain"]), str(row["residue_id"])) + points = ligand_atoms.get(key, []) + if not points: + continue + min_dist = _min_distance(points) + enriched = dict(row) + enriched["min_distance_to_receptor"] = min_dist + enriched["contact_candidate"] = bool(row["candidate_ligand"]) and min_dist <= 6.0 + candidates.append(enriched) + viable = [row for row in candidates if row["candidate_ligand"]] + if not viable: + raise RDockPipelineError( + f"No suitable reference ligand candidates found in {source}. " + f"Available hetero entries: {candidates[:20]}" + ) + viable.sort( + key=lambda item: ( + int(bool(item.get("contact_candidate"))), + int(item.get("heavy_atom_count", 0)), + int(item.get("atom_count", 0)), + -float(item.get("min_distance_to_receptor", math.inf)), + ), + reverse=True, + ) + return viable[0], candidates + + +def resolve_known_good_defaults( + config_path: str | Path, + pdb_id: str, + receptor_chain: str | None, + ligand_resname: str | None, + ligand_chain: str | None, +) -> dict[str, str]: + pdb_upper = pdb_id.upper().strip() + matches = [item for item in list_known_good_complexes(config_path) if str(item.get("pdb_id", "")).upper() == pdb_upper] + if not matches: + return { + "pdb_id": pdb_upper, + "receptor_chain": receptor_chain or "", + "reference_ligand_resname": ligand_resname or "", + "reference_ligand_chain": ligand_chain or "", + } + chosen = matches[0] + return { + "pdb_id": pdb_upper, + "receptor_chain": receptor_chain or str(chosen.get("receptor_chain", "")), + "reference_ligand_resname": ligand_resname or str(chosen.get("reference_ligand_resname", "")), + "reference_ligand_chain": ligand_chain or str(chosen.get("reference_ligand_chain", "")), + } + + +def download_pdb_structure(pdb_id: str, out_dir: str | Path, force: bool = False) -> Path: + target_dir = Path(out_dir) + target_dir.mkdir(parents=True, exist_ok=True) + pdb_id = pdb_id.upper().strip() + pdb_path = target_dir / f"{pdb_id.lower()}.pdb" + if pdb_path.exists() and pdb_path.stat().st_size > 0 and not force: + return pdb_path + url = f"https://files.rcsb.org/download/{pdb_id}.pdb" + try: + urllib.request.urlretrieve(url, pdb_path) + except Exception as exc: + curl = shutil.which("curl") + if curl: + proc = subprocess.run( + [curl, "-fsSL", url, "-o", str(pdb_path)], + check=False, + capture_output=True, + text=True, + ) + if proc.returncode == 0 and pdb_path.exists() and pdb_path.stat().st_size > 0: + return require_file(pdb_path, f"downloaded PDB for {pdb_id}") + raise RDockPipelineError( + f"Failed to download PDB {pdb_id} from {url}. urllib error: {exc}. " + f"curl stderr: {proc.stderr.strip() or ''}. " + f"Check network access or provide a locally cached PDB in {target_dir}." + ) from exc + raise RDockPipelineError( + f"Failed to download PDB {pdb_id} from {url}: {exc}. " + "curl is not available for fallback; check network access or pre-stage the PDB file locally." + ) from exc + return require_file(pdb_path, f"downloaded PDB for {pdb_id}") + + +def extract_receptor_and_reference_ligand( + pdb_like: str | Path, + receptor_chain: str, + ligand_resname: str, + ligand_chain: str, + out_dir: str | Path, + min_reference_ligand_atoms: int = 8, +) -> tuple[Path, Path, list[dict[str, str]]]: + source = require_file(pdb_like, "PDB/mmCIF structure") + out_root = Path(out_dir) + out_root.mkdir(parents=True, exist_ok=True) + receptor = out_root / "target_raw.pdb" + ligand_pdb = out_root / "reference_ligand_raw.pdb" + + receptor_lines: list[str] = [] + ligand_lines: list[str] = [] + hetero_rows = list_hetero_ligands(source, min_reference_ligand_atoms=min_reference_ligand_atoms) + receptor_chains = {item.strip() for item in receptor_chain.split(",") if item.strip()} + wanted_resname = ligand_resname.upper().strip() + wanted_chain = ligand_chain.strip() + wanted_keys = { + (str(item["resname"]), str(item["chain"]), str(item["residue_id"])) + for item in hetero_rows + if str(item["resname"]) == wanted_resname and (not wanted_chain or str(item["chain"]) == wanted_chain) + } + + for line in source.read_text(encoding="utf-8", errors="ignore").splitlines(): + record = line[:6].strip() + atom = _parse_pdb_atom_line(line) + chain = str(atom["chain"]) + resname = str(atom["resname"]) + if record == "ATOM" and (not receptor_chains or chain in receptor_chains): + receptor_lines.append(line) + if record == "HETATM": + key = (resname, chain, str(atom["residue_id"])) + if key in wanted_keys: + ligand_lines.append(line) + if not receptor_lines: + raise RDockPipelineError(f"No receptor atoms found in {source} for chain(s) {receptor_chain}") + if not ligand_lines: + raise RDockPipelineError( + f"Reference ligand {wanted_resname} chain {wanted_chain or '*'} not found in {source}. " + f"Available hetero ligands: {hetero_rows[:20]}" + ) + + receptor.write_text("\n".join(receptor_lines + ["END", ""]), encoding="utf-8") + ligand_pdb.write_text("\n".join(ligand_lines + ["END", ""]), encoding="utf-8") + return receptor, ligand_pdb, hetero_rows + + +def validate_dataset_dir(dataset_dir: str | Path, check_rdock_tools: bool = False) -> dict[str, Any]: + root = Path(dataset_dir) + manifest_path = root / "dataset_manifest.json" + manifest = json.loads(require_file(manifest_path, "dataset manifest").read_text(encoding="utf-8")) + required = { + "target_mol2": root / "target" / "target.mol2", + "reference_ligand_sdf": root / "target" / "reference_ligand.sdf", + "all_ligands_sdf": root / "ligands" / "all_ligands.sdf", + "invalid_ligands_csv": root / "ligands" / "invalid_ligands.csv", + "preparation_report": root / "qc" / "preparation_report.md", + "target_config": root / "target" / "rdock_prm" / "target_config.yaml", + } + for label, path in required.items(): + require_file(path, label) + ligand_count = count_sdf_records(required["all_ligands_sdf"]) + expected_count = int(manifest.get("ligands_prepared", 0)) + if expected_count and ligand_count != expected_count: + raise RDockPipelineError( + f"Ligand count mismatch for {root}: manifest says {expected_count}, SDF contains {ligand_count}" + ) + ref_count = count_sdf_records(required["reference_ligand_sdf"]) + if ref_count < 1: + raise RDockPipelineError(f"Reference ligand SDF is empty in {root}") + target_config = load_target_config(required["target_config"]) + cavity = require_file(target_config.cavity_as, "rDock cavity .as file from dataset") + if cavity.stat().st_size <= 0: + raise RDockPipelineError(f"Invalid empty cavity file in dataset: {cavity}") + ligand_source = str(manifest.get("ligand_source", "")) + if ligand_source.startswith("pubchem"): + require_file(root / "logs" / "pubchem_diagnostics.json", "PubChem diagnostics log") + tools: dict[str, str] = {} + if check_rdock_tools: + tools = { + "rbdock": probe_version(require_executable("rbdock")), + "rbcavity": probe_version(require_executable("rbcavity")), + "obabel": probe_version(require_executable("obabel")), + } + return { + "dataset_dir": str(root), + "manifest": manifest, + "ligand_count": ligand_count, + "reference_records": ref_count, + "target_config": str(required["target_config"]), + "executables": tools, + } + + +def create_dataset_manifest( + dataset_dir: str | Path, + payload: dict[str, Any], +) -> Path: + root = Path(dataset_dir) + payload = dict(payload) + payload["created_at"] = datetime.now(UTC).isoformat() + return dump_json_like(root / "dataset_manifest.json", payload) + + +def copy_prepared_target_bundle(target_config_dir: str | Path, dataset_target_dir: str | Path) -> dict[str, str]: + src = Path(target_config_dir) + dst = Path(dataset_target_dir) + dst.mkdir(parents=True, exist_ok=True) + copied: dict[str, str] = {} + for path in src.iterdir(): + if path.is_file(): + shutil.copy2(path, dst / path.name) + copied[path.name] = str(dst / path.name) + return copied + + +def prepare_dataset_target_with_rdock( + receptor_pdb: str | Path, + reference_ligand_sdf: str | Path, + out_dir: str | Path, + jobs: int | str = "auto", + cpu_fraction: float = 0.85, +) -> dict[str, Any]: + engine = RDockEngine(RDockRunConfig(jobs=jobs, cpu_fraction=cpu_fraction)) + target_config = engine.prepare_target(receptor_pdb, reference_ligand_sdf, out_dir) + return { + "target_config_yaml": str(Path(out_dir) / "target_config.yaml"), + "target_config": target_config.__dict__, + } + + +def read_ligand_metadata(path: str | Path) -> list[dict[str, str]]: + with require_file(path, "ligand metadata CSV").open("r", encoding="utf-8", newline="") as handle: + return list(csv.DictReader(handle)) diff --git a/docking_pipeline/metrics.py b/docking_pipeline/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..02cc056608881226bd8cdb33dd1e08fbc5f1ae57 --- /dev/null +++ b/docking_pipeline/metrics.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import math +import json +import csv +from pathlib import Path + + +def roc_auc(scores: list[float], labels: list[int]) -> float: + pairs = [(float(s), int(y)) for s, y in zip(scores, labels)] + pos = [s for s, y in pairs if y == 1] + neg = [s for s, y in pairs if y == 0] + if not pos or not neg: + return float("nan") + wins = 0.0 + for p in pos: + wins += sum(1.0 for n in neg if p < n) + wins += 0.5 * sum(1.0 for n in neg if p == n) + return float(wins / (len(pos) * len(neg))) + + +def enrichment_factor(scores: list[float], labels: list[int], fraction: float) -> float: + pairs = [(float(s), int(y)) for s, y in zip(scores, labels)] + n = len(pairs) + total_actives = sum(y for _, y in pairs) + if n == 0 or total_actives == 0: + return float("nan") + k = max(1, int(math.ceil(n * fraction))) + top = sorted(pairs, key=lambda item: item[0])[:k] + hit_rate_top = float(sum(y for _, y in top)) / float(k) + hit_rate_all = float(total_actives) / float(n) + return float(hit_rate_top / hit_rate_all) if hit_rate_all > 0 else float("nan") + + +def bedroc(scores: list[float], labels: list[int], alpha: float = 20.0) -> float: + pairs = sorted([(float(s), int(y)) for s, y in zip(scores, labels)], key=lambda item: item[0]) + n = len(pairs) + n_act = sum(y for _, y in pairs) + if n == 0 or n_act == 0 or n_act == n: + return float("nan") + ranks = [idx + 1 for idx, (_, y) in enumerate(pairs) if y == 1] + denom = (1 - math.exp(-alpha)) / (math.exp(alpha / n) - 1) + rie = (n / n_act) * sum(math.exp(-alpha * rank / n) for rank in ranks) / denom + rie_min = (n / n_act) * sum(math.exp(-alpha * rank / n) for rank in range(n - n_act + 1, n + 1)) / denom + rie_max = (n / n_act) * sum(math.exp(-alpha * rank / n) for rank in range(1, n_act + 1)) / denom + return float((rie - rie_min) / (rie_max - rie_min)) + + +def enrichment_rows(scores: list[float], labels: list[int]) -> list[dict[str, float]]: + rows = [] + for frac in (0.01, 0.05, 0.10, 0.20): + rows.append({"fraction": frac, "enrichment_factor": enrichment_factor(scores, labels, frac)}) + return rows + + +def validation_metrics_from_rows(rows: list[dict[str, object]], score_col: str = "SCORE", label_col: str = "label") -> dict[str, float]: + scores = [float(row[score_col]) for row in rows] + labels = [int(float(row.get(label_col, 0) or 0)) for row in rows] + return { + "roc_auc": roc_auc(scores, labels), + "ef1": enrichment_factor(scores, labels, 0.01), + "ef5": enrichment_factor(scores, labels, 0.05), + "ef10": enrichment_factor(scores, labels, 0.10), + "ef20": enrichment_factor(scores, labels, 0.20), + "bedroc20": bedroc(scores, labels, alpha=20.0), + } + + +def write_metrics(rows: list[dict[str, object]], metrics_json: str | Path, enrichment_csv: str | Path) -> dict[str, float]: + metrics = validation_metrics_from_rows(rows) + Path(metrics_json).parent.mkdir(parents=True, exist_ok=True) + Path(metrics_json).write_text(json.dumps(metrics, indent=2), encoding="utf-8") + scores = [float(row["SCORE"]) for row in rows] + labels = [int(float(row.get("label", 0) or 0)) for row in rows] + with Path(enrichment_csv).open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=["fraction", "enrichment_factor"]) + writer.writeheader() + writer.writerows(enrichment_rows(scores, labels)) + return metrics + + +validation_metrics_from_table = validation_metrics_from_rows +enrichment_table = enrichment_rows diff --git a/docking_pipeline/provenance.py b/docking_pipeline/provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..61b5a570fa9dcecd518c31d560532c0a923e7bca --- /dev/null +++ b/docking_pipeline/provenance.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import subprocess +from dataclasses import asdict, dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Sequence + + +class RDockPipelineError(RuntimeError): + """Raised for actionable pipeline failures.""" + + +def sha256_file(path: str | Path) -> str: + source = Path(path) + h = hashlib.sha256() + with source.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + h.update(chunk) + return h.hexdigest() + + +def require_file(path: str | Path, label: str) -> Path: + p = Path(path) + if not p.exists(): + raise RDockPipelineError(f"Missing {label}: {p}") + if p.is_file() and p.stat().st_size == 0: + raise RDockPipelineError(f"Empty {label}: {p}") + return p + + +def require_executable(name: str) -> str: + resolved = shutil.which(name) + if not resolved: + raise RDockPipelineError( + f"Required executable `{name}` was not found on PATH. Install rDock/OpenBabel " + "and ensure RBT_ROOT/RBT_HOME/library paths are configured before running." + ) + return resolved + + +def probe_version(executable: str) -> str: + for args in ([executable, "--version"], [executable, "-version"], [executable, "-h"]): + try: + proc = subprocess.run(args, check=False, capture_output=True, text=True, timeout=10) + except Exception: + continue + text = "\n".join([proc.stdout or "", proc.stderr or ""]).strip() + if text: + for line in text.splitlines(): + probe = line.strip() + if probe and set(probe) != {"*"}: + return probe[:240] + return text.splitlines()[0][:240] + return "unavailable" + + +@dataclass +class CommandRecord: + stage: str + command: list[str] + cwd: str + start_time: str + end_time: str + exit_code: int + stdout_log: str + stderr_log: str + + def to_dict(self) -> dict[str, object]: + return asdict(self) + + +class CommandRunner: + def __init__(self, command_log: str | Path) -> None: + self.command_log = Path(command_log) + self.command_log.parent.mkdir(parents=True, exist_ok=True) + self.records: list[CommandRecord] = [] + + def run( + self, + stage: str, + command: Sequence[str], + cwd: str | Path, + stdout_log: str | Path, + stderr_log: str | Path, + timeout: int | None = None, + env: dict[str, str] | None = None, + ) -> CommandRecord: + cwd_path = Path(cwd) + stdout_path = Path(stdout_log) + stderr_path = Path(stderr_log) + stdout_path.parent.mkdir(parents=True, exist_ok=True) + stderr_path.parent.mkdir(parents=True, exist_ok=True) + start = datetime.now(UTC).isoformat() + merged_env = os.environ.copy() + if env: + merged_env.update(env) + try: + proc = subprocess.run( + list(command), + cwd=str(cwd_path), + check=False, + capture_output=True, + text=True, + timeout=timeout, + env=merged_env, + ) + stdout = proc.stdout or "" + stderr = proc.stderr or "" + rc = int(proc.returncode) + except subprocess.TimeoutExpired as exc: + stdout = exc.stdout if isinstance(exc.stdout, str) else "" + stderr = (exc.stderr if isinstance(exc.stderr, str) else "") + f"\nTIMEOUT after {timeout}s" + rc = 124 + end = datetime.now(UTC).isoformat() + stdout_path.write_text(stdout, encoding="utf-8") + stderr_path.write_text(stderr, encoding="utf-8") + rec = CommandRecord( + stage=stage, + command=list(command), + cwd=str(cwd_path), + start_time=start, + end_time=end, + exit_code=rc, + stdout_log=str(stdout_path), + stderr_log=str(stderr_path), + ) + self.records.append(rec) + with self.command_log.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(rec.to_dict(), sort_keys=True) + "\n") + return rec + + +def fail_if_bad_command(record: CommandRecord, expected: str) -> None: + stdout = Path(record.stdout_log).read_text(encoding="utf-8", errors="ignore") if record.stdout_log else "" + stderr = Path(record.stderr_log).read_text(encoding="utf-8", errors="ignore") if record.stderr_log else "" + text = f"{stdout}\n{stderr}" + error_markers = ( + "RBT_FILE_READ_ERROR", + "RBT_ERROR", + "BAD_RECEPTOR_FILE", + "Error opening", + "Segmentation fault", + "Fatal", + ) + if record.exit_code == 0 and not any(marker.lower() in text.lower() for marker in error_markers): + return + raise RDockPipelineError( + f"{expected} failed with exit code {record.exit_code}. Command: {' '.join(record.command)}. " + f"See stdout log: {record.stdout_log}; stderr log: {record.stderr_log}. " + f"Last diagnostic: {text.strip()[-1200:]}" + ) diff --git a/docking_pipeline/rdock.py b/docking_pipeline/rdock.py new file mode 100644 index 0000000000000000000000000000000000000000..78e96198cc58b79146054398a459e9ff093e3879 --- /dev/null +++ b/docking_pipeline/rdock.py @@ -0,0 +1,561 @@ +from __future__ import annotations + +import json +import math +import os +import shutil +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import asdict, dataclass, field +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from .provenance import ( + CommandRecord, + CommandRunner, + RDockPipelineError, + fail_if_bad_command, + probe_version, + require_executable, + require_file, + sha256_file, +) +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 + + +@dataclass +class TargetConfig: + receptor: str + reference_ligand: str + target_dir: str + receptor_mol2: str + receptor_prm: str + cavity_as: str + pocket_center: list[float] + pocket_radius: float + diagnostics: dict[str, Any] + + +@dataclass +class RDockRunConfig: + n_runs: int = 50 + jobs: int | str = "auto" + cpu_fraction: float = 0.85 + timeout_seconds: int = 3600 + rbdock_bin: str = "rbdock" + rbcavity_bin: str = "rbcavity" + obabel_bin: str = "obabel" + sdsort_bin: str = "sdsort" + sdfilter_bin: str = "sdfilter" + sdreport_bin: str = "sdreport" + sdrmsd_bin: str = "sdrmsd" + sdsplit_bin: str = "sdsplit" + dock_prm: str | None = None + rbt_root: str | None = None + require_reporting_tools: bool = False + + +@dataclass +class RunArtifacts: + run_dir: str + manifest: str + config_yaml: str + commands_log: str + all_poses_sdf: str + best_per_ligand_sdf: str + scores_long_csv: str + best_per_ligand_csv: str + report_md: str + command_records: list[dict[str, Any]] = field(default_factory=list) + best_ligand_poses_sdf: str | None = None + + +def _write_yaml_like(path: Path, payload: dict[str, Any]) -> None: + try: + import yaml + + text = yaml.safe_dump(payload, sort_keys=False) + except Exception: + text = json.dumps(payload, indent=2) + path.write_text(text, encoding="utf-8") + + +def _coords_from_pdb(path: Path, include_hetatm: bool) -> np.ndarray: + coords: list[list[float]] = [] + for line in path.read_text(encoding="utf-8", errors="ignore").splitlines(): + if not line.startswith(("ATOM", "HETATM")): + continue + if line.startswith("HETATM") and not include_hetatm: + continue + try: + coords.append([float(line[30:38]), float(line[38:46]), float(line[46:54])]) + except Exception: + continue + return coords # type: ignore[return-value] + + +def _coords_from_mol2(path: Path) -> np.ndarray: + coords: list[list[float]] = [] + in_atoms = False + for line in path.read_text(encoding="utf-8", errors="ignore").splitlines(): + if line.startswith("@ATOM"): + in_atoms = True + continue + if line.startswith("@") and in_atoms: + break + if not in_atoms: + continue + parts = line.split() + if len(parts) >= 5: + try: + coords.append([float(parts[2]), float(parts[3]), float(parts[4])]) + except Exception: + continue + return coords # type: ignore[return-value] + + +def _coords_from_sdf(path: Path) -> np.ndarray: + first = path.read_text(encoding="utf-8", errors="ignore").split("$$$$", 1)[0] + lines = first.splitlines() + if len(lines) < 4: + return [] # type: ignore[return-value] + try: + atom_count = int(lines[3][0:3]) + except Exception: + atom_count = 0 + coords = [] + for line in lines[4 : 4 + atom_count]: + try: + coords.append([float(line[0:10]), float(line[10:20]), float(line[20:30])]) + except Exception: + parts = line.split() + if len(parts) >= 3: + try: + coords.append([float(parts[0]), float(parts[1]), float(parts[2])]) + except Exception: + continue + return coords # type: ignore[return-value] + + +def _coords_for_structure(path: Path, receptor: bool) -> np.ndarray: + suffix = path.suffix.lower() + if suffix == ".mol2": + return _coords_from_mol2(path) + if suffix in {".sdf", ".sd"}: + return _coords_from_sdf(path) + if suffix in {".pdb", ".ent", ".cif", ".mmcif"}: + return _coords_from_pdb(path, include_hetatm=not receptor) + raise RDockPipelineError(f"Unsupported structure format for coordinate validation: {path}") + + +def _validate_receptor_ligand_geometry(receptor: Path, ligand: Path) -> tuple[list[float], dict[str, Any]]: + receptor_coords = _coords_for_structure(receptor, receptor=True) + ligand_coords = _coords_for_structure(ligand, receptor=False) + if not receptor_coords: + raise RDockPipelineError(f"Missing receptor atoms or coordinates in {receptor}") + if not ligand_coords: + raise RDockPipelineError(f"Missing ligand coordinates in reference ligand {ligand}") + n_lig = len(ligand_coords) + center = [sum(coord[i] for coord in ligand_coords) / n_lig for i in range(3)] + + def dist(a: list[float], b: list[float]) -> float: + return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2) ** 0.5 + + all_dists = [dist(r, l) for r in receptor_coords for l in ligand_coords] + min_receptor_ligand_dist = min(all_dists) + centroid_to_receptor = min(dist(r, center) for r in receptor_coords) + severe_clashes = sum(1 for d in all_dists if d < 1.0) + clash_fraction = severe_clashes / float(max(1, len(ligand_coords))) + if centroid_to_receptor > 20.0: + raise RDockPipelineError( + f"Reference ligand centroid is {centroid_to_receptor:.2f} A from the nearest receptor atom; " + "check receptor/reference ligand pairing and coordinate frames." + ) + if clash_fraction > 1.0: + raise RDockPipelineError( + f"Severe receptor-ligand clashes before docking ({severe_clashes} atom pairs < 1.0 A). " + "Check protonation, alternate locations, and coordinate consistency." + ) + spread = max(dist(l, center) for l in ligand_coords) + return [float(center[0]), float(center[1]), float(center[2])], { + "receptor_atom_count": int(len(receptor_coords)), + "reference_ligand_atom_count": int(len(ligand_coords)), + "reference_ligand_centroid": [float(x) for x in center], + "reference_ligand_radius": spread, + "min_receptor_ligand_distance": min_receptor_ligand_dist, + "reference_centroid_to_nearest_receptor_atom": centroid_to_receptor, + "severe_clash_pairs_lt_1A": severe_clashes, + } + + +class RDockEngine: + def __init__(self, config: RDockRunConfig | None = None) -> None: + self.config = config or RDockRunConfig() + + def _env(self) -> dict[str, str]: + env: dict[str, str] = {} + if self.config.rbt_root: + env["RBT_ROOT"] = self.config.rbt_root + elif os.environ.get("RBT_ROOT"): + env["RBT_ROOT"] = str(os.environ["RBT_ROOT"]) + else: + for candidate in (Path("/opt/homebrew/opt/rdock/share"), Path("/usr/local/opt/rdock/share")): + if (candidate / "data" / "RbtElements.dat").exists(): + env["RBT_ROOT"] = str(candidate) + break + if "RBT_ROOT" not in env: + cellar = Path("/opt/homebrew/Cellar/rdock") + if cellar.exists(): + for candidate in sorted(cellar.glob("*/share"), reverse=True): + if (candidate / "data" / "RbtElements.dat").exists(): + env["RBT_ROOT"] = str(candidate) + break + return env + + def _dock_prm(self) -> Path: + if self.config.dock_prm: + return require_file(self.config.dock_prm, "rDock protocol dock.prm") + rbt_root = self.config.rbt_root or os.environ.get("RBT_ROOT") + candidates = [] + if rbt_root: + candidates.append(Path(rbt_root) / "data" / "scripts" / "dock.prm") + candidates.append(Path(rbt_root) / "data" / "dock.prm") + candidates.extend( + [ + Path("/opt/homebrew/opt/rdock/share/data/scripts/dock.prm"), + Path("/usr/local/opt/rdock/share/data/scripts/dock.prm"), + ] + ) + cellar = Path("/opt/homebrew/Cellar/rdock") + if cellar.exists(): + candidates.extend(sorted(cellar.glob("*/share/data/scripts/dock.prm"), reverse=True)) + candidates.append(Path("dock.prm")) + for candidate in candidates: + if candidate.exists() and candidate.stat().st_size > 0: + return candidate.resolve() + raise RDockPipelineError( + "Could not locate rDock dock.prm. Pass --dock-prm or set RBT_ROOT so " + "$RBT_ROOT/data/scripts/dock.prm exists." + ) + + def check_required_tools(self, validation: bool = False) -> dict[str, str]: + needed = { + "rbdock": self.config.rbdock_bin, + "rbcavity": self.config.rbcavity_bin, + "obabel": self.config.obabel_bin, + } + if validation or self.config.require_reporting_tools: + needed.update( + { + "sdsort": self.config.sdsort_bin, + "sdfilter": self.config.sdfilter_bin, + "sdreport": self.config.sdreport_bin, + "sdrmsd": self.config.sdrmsd_bin, + } + ) + return {key: require_executable(bin_name) for key, bin_name in needed.items()} + + def prepare_target(self, receptor: str | Path, reference_ligand: str | Path, out_dir: str | Path) -> TargetConfig: + tools = self.check_required_tools(validation=False) + receptor_path = require_file(receptor, "receptor structure") + ref_path = require_file(reference_ligand, "reference ligand") + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=True) + command_log = out / "commands.log" + runner = CommandRunner(command_log) + + receptor_copy = out / receptor_path.name + reference_copy = out / ref_path.name + if receptor_path.resolve() != receptor_copy.resolve(): + shutil.copy2(receptor_path, receptor_copy) + if ref_path.resolve() != reference_copy.resolve(): + shutil.copy2(ref_path, reference_copy) + + center, diagnostics = _validate_receptor_ligand_geometry(receptor_copy, reference_copy) + receptor_mol2 = out / "receptor.mol2" + if receptor_copy.suffix.lower() == ".mol2": + shutil.copy2(receptor_copy, receptor_mol2) + else: + rec = runner.run( + "prepare_receptor_obabel", + [tools["obabel"], str(receptor_copy.resolve()), "-O", str(receptor_mol2.resolve())], + cwd=out, + stdout_log=out / "prepare_receptor_obabel.stdout.log", + stderr_log=out / "prepare_receptor_obabel.stderr.log", + timeout=300, + env=self._env(), + ) + fail_if_bad_command(rec, "OpenBabel receptor conversion") + require_file(receptor_mol2, "prepared receptor MOL2") + + prm = out / "receptor.prm" + prm.write_text( + "\n".join( + [ + "RBT_PARAMETER_FILE_V1.00", + "TITLE rdock_receptor_reference_ligand", + f"RECEPTOR_FILE {receptor_mol2.resolve()}", + "", + "SECTION MAPPER", + " SITE_MAPPER RbtLigandSiteMapper", + f" REF_MOL {reference_copy.resolve()}", + " RADIUS 6.0", + " SMALL_SPHERE 1.5", + "END_SECTION", + "", + "SECTION CAVITY", + " SCORING_FUNCTION RbtCavityGridSF", + "END_SECTION", + "", + ] + ), + encoding="utf-8", + ) + + rec = runner.run( + "rbcavity", + [tools["rbcavity"], "-r", prm.name, "-was"], + cwd=out, + stdout_log=out / "rbcavity.stdout.log", + stderr_log=out / "rbcavity.stderr.log", + timeout=self.config.timeout_seconds, + env=self._env(), + ) + fail_if_bad_command(rec, "rbcavity cavity generation") + cavity = out / f"{prm.stem}.as" + require_file(cavity, "rDock cavity .as file") + if cavity.stat().st_size < 16: + raise RDockPipelineError(f"rbcavity produced an invalid tiny cavity file: {cavity}") + + target_config = TargetConfig( + receptor=str(receptor_copy), + reference_ligand=str(reference_copy), + target_dir=str(out), + receptor_mol2=str(receptor_mol2), + receptor_prm=str(prm), + cavity_as=str(cavity), + pocket_center=center, + pocket_radius=float(max(6.0, diagnostics["reference_ligand_radius"] + 2.0)), + diagnostics=diagnostics, + ) + _write_yaml_like(out / "target_config.yaml", asdict(target_config)) + return target_config + + def _resolve_jobs(self, requested: int | str | None = None) -> int: + value = self.config.jobs if requested is None else requested + if isinstance(value, str) and value.lower() == "auto": + cpus = os.cpu_count() or 1 + reserve = 1 if cpus <= 4 else 2 + return max(1, min(cpus - reserve, int(math.floor(cpus * self.config.cpu_fraction)))) + return max(1, int(value)) + + def _split_input_sdf(self, ligands_sdf: Path, split_dir: Path, jobs: int) -> list[Path]: + blocks = split_sdf_file(ligands_sdf) + if jobs <= 1 or len(blocks) <= 1: + target = split_dir / "chunk_000.sdf" + write_sdf_blocks(blocks, target) + return [target] + chunks: list[list[str]] = [[] for _ in range(min(jobs, len(blocks)))] + for idx, block in enumerate(blocks): + chunks[idx % len(chunks)].append(block) + paths = [] + for idx, chunk in enumerate(chunks): + path = split_dir / f"chunk_{idx:03d}.sdf" + write_sdf_blocks(chunk, path) + paths.append(path) + return paths + + def dock_sdf( + self, + target_config: TargetConfig, + ligands_sdf: str | Path, + run_dir: str | Path, + n_runs: int | None = None, + jobs: int | str | None = None, + run_id: str | None = None, + validation_labels_csv: str | Path | None = None, + resume: bool = False, + ) -> RunArtifacts: + self.check_required_tools(validation=False) + ligands = require_file(ligands_sdf, "ligand SDF") + dock_prm = self._dock_prm() + run_root = Path(run_dir) + run_root.mkdir(parents=True, exist_ok=True) + for name in ("target", "ligands", "rdock", "poses", "tables", "metrics"): + (run_root / name).mkdir(parents=True, exist_ok=True) + commands_log = run_root / "commands.log" + runner = CommandRunner(commands_log) + + target_dir = run_root / "target" + for src in (target_config.receptor, target_config.reference_ligand, target_config.receptor_mol2, target_config.receptor_prm, target_config.cavity_as): + p = Path(src) + if p.exists(): + shutil.copy2(p, target_dir / p.name) + lig_copy = run_root / "ligands" / ligands.name + if ligands.resolve() != lig_copy.resolve(): + shutil.copy2(ligands, lig_copy) + shutil.copy2(dock_prm, run_root / "rdock" / "dock.prm") + + resolved_jobs = self._resolve_jobs(jobs) + actual_n_runs = int(n_runs if n_runs is not None else self.config.n_runs) + chunks = self._split_input_sdf(lig_copy, run_root / "rdock" / "chunks", resolved_jobs) + rbdock = require_executable(self.config.rbdock_bin) + prm = Path(target_config.receptor_prm).resolve() + out_files: dict[int, Path] = {} + + def _run_chunk(idx: int, chunk: Path) -> tuple[int, CommandRecord, Path]: + out_prefix = run_root / "rdock" / f"chunk_{idx:03d}_out" + out_sd = out_prefix.with_suffix(".sd") + if resume and out_sd.exists() and out_sd.stat().st_size > 0: + rec = CommandRecord( + stage=f"rbdock_chunk_{idx:03d}_resume", + command=[rbdock, "-r", str(prm), "-p", str(dock_prm.resolve()), "-n", str(actual_n_runs), "-i", str(chunk.resolve()), "-o", str(out_prefix.resolve())], + cwd=str(run_root / "rdock"), + start_time=datetime.now(UTC).isoformat(), + end_time=datetime.now(UTC).isoformat(), + exit_code=0, + stdout_log=str(run_root / "rdock" / f"chunk_{idx:03d}.stdout.log"), + stderr_log=str(run_root / "rdock" / f"chunk_{idx:03d}.stderr.log"), + ) + return idx, rec, out_sd + rec = runner.run( + f"rbdock_chunk_{idx:03d}", + [ + rbdock, + "-r", + str(prm), + "-p", + str(dock_prm.resolve()), + "-n", + str(actual_n_runs), + "-i", + str(chunk.resolve()), + "-o", + str(out_prefix.resolve()), + ], + cwd=run_root / "rdock", + stdout_log=run_root / "rdock" / f"chunk_{idx:03d}.stdout.log", + stderr_log=run_root / "rdock" / f"chunk_{idx:03d}.stderr.log", + timeout=self.config.timeout_seconds, + env=self._env(), + ) + return idx, rec, out_sd + + with ThreadPoolExecutor(max_workers=min(resolved_jobs, len(chunks))) as pool: + futures = [pool.submit(_run_chunk, idx, chunk) for idx, chunk in enumerate(chunks)] + for fut in as_completed(futures): + idx, rec, out_sd = fut.result() + fail_if_bad_command(rec, f"rbdock chunk {idx}") + require_file(out_sd, f"rDock output SDF for chunk {idx}") + out_files[idx] = out_sd + + all_blocks: list[str] = [] + for idx in sorted(out_files): + all_blocks.extend(split_sdf_file(out_files[idx])) + all_poses = run_root / "poses" / "all_poses.sdf" + write_sdf_blocks(all_blocks, all_poses) + records = parse_rdock_sdf_records(all_poses, require_score=True) + best = best_per_ligand(records) + best_sdf = write_sdf_records(best, run_root / "poses" / "best_per_ligand.sdf") + best_ligand_poses_sdf: str | None = None + if best: + top_ligand_id = best[0].ligand_id + best_ligand_records = [rec for rec in records if rec.ligand_id == top_ligand_id] + best_ligand_path = run_root / "poses" / f"best_ligand_{actual_n_runs}.sdf" + write_sdf_records(best_ligand_records, best_ligand_path) + best_ligand_poses_sdf = str(best_ligand_path) + scores_long = write_rows_csv(records_to_rows(records), run_root / "tables" / "scores_long.csv") + best_csv = write_rows_csv(records_to_rows(best), run_root / "tables" / "best_per_ligand.csv") + + labels_map: dict[str, int] = {} + if validation_labels_csv: + import pandas as pd + + label_df = pd.read_csv(validation_labels_csv) + labels_map = dict(zip(label_df["ligand_id"].astype(str), label_df["label"].astype(int))) + best_rows = records_to_rows(best) + for row in best_rows: + row["label"] = labels_map.get(str(row["ligand_id"]), 0) + best_csv = write_rows_csv(best_rows, best_csv) + + manifest_path = run_root / "manifest.json" + config_yaml = run_root / "config.yaml" + report_md = run_root / "report.md" + now = datetime.now(UTC).isoformat() + file_inputs = { + "ligands_sdf": str(lig_copy), + "dock_prm": str(run_root / "rdock" / "dock.prm"), + "receptor_prm": str(target_config.receptor_prm), + "cavity_as": str(target_config.cavity_as), + } + manifest = { + "run_id": run_id or run_root.name, + "created_at": now, + "engine": "real-rdock", + "n_runs": actual_n_runs, + "jobs": resolved_jobs, + "input_hashes": {k: sha256_file(v) for k, v in file_inputs.items() if Path(v).exists()}, + "rdock_versions": { + "rbdock": probe_version(rbdock), + "rbcavity": probe_version(require_executable(self.config.rbcavity_bin)), + }, + "target_config": asdict(target_config), + "commands": [r.to_dict() for r in runner.records], + "artifacts": { + "all_poses_sdf": str(all_poses), + "best_per_ligand_sdf": str(best_sdf), + "best_ligand_poses_sdf": best_ligand_poses_sdf, + "scores_long_csv": str(scores_long), + "best_per_ligand_csv": str(best_csv), + "commands_log": str(commands_log), + }, + "pose_count": len(records), + "docked_ligand_count": len(best), + } + manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8") + _write_yaml_like(config_yaml, {"rdock": asdict(self.config), "run": {"n_runs": actual_n_runs, "jobs": resolved_jobs}}) + report_md.write_text( + "\n".join( + [ + "# rDock Run Report", + "", + f"- Engine: `real-rdock`", + f"- Run ID: `{manifest['run_id']}`", + f"- n_runs per ligand: `{actual_n_runs}`", + f"- local jobs: `{resolved_jobs}`", + f"- poses parsed: `{len(records)}`", + f"- docked ligands: `{len(best)}`", + f"- all poses: `{all_poses}`", + f"- best per ligand: `{best_sdf}`", + f"- best ligand all poses: `{best_ligand_poses_sdf or ''}`", + f"- command log: `{commands_log}`", + "", + "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.", + ] + ), + encoding="utf-8", + ) + return RunArtifacts( + run_dir=str(run_root), + manifest=str(manifest_path), + config_yaml=str(config_yaml), + commands_log=str(commands_log), + all_poses_sdf=str(all_poses), + best_per_ligand_sdf=str(best_sdf), + scores_long_csv=str(scores_long), + best_per_ligand_csv=str(best_csv), + report_md=str(report_md), + command_records=[r.to_dict() for r in runner.records], + best_ligand_poses_sdf=best_ligand_poses_sdf, + ) + + +def load_target_config(path: str | Path) -> TargetConfig: + source = require_file(path, "target config") + try: + import yaml + + data = yaml.safe_load(source.read_text(encoding="utf-8")) + except Exception: + data = json.loads(source.read_text(encoding="utf-8")) + return TargetConfig(**data) diff --git a/docking_pipeline/reports/__init__.py b/docking_pipeline/reports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0a12420fc474b776666cbfe84db2e2b9b328b0ab --- /dev/null +++ b/docking_pipeline/reports/__init__.py @@ -0,0 +1 @@ +"""Report and plotting helpers for strict rDock runs.""" diff --git a/docking_pipeline/reports/plots.py b/docking_pipeline/reports/plots.py new file mode 100644 index 0000000000000000000000000000000000000000..201d2b15532d46fd4da97c9870d2b0590d8010bd --- /dev/null +++ b/docking_pipeline/reports/plots.py @@ -0,0 +1,644 @@ +from __future__ import annotations + +import csv +import json +import math +import struct +import zlib +from pathlib import Path +from typing import Iterable + + +def _read_rows(path: str | Path) -> list[dict[str, str]]: + with Path(path).open("r", encoding="utf-8", newline="") as handle: + return list(csv.DictReader(handle)) + + +def _floats(rows: Iterable[dict[str, object]], key: str) -> list[float]: + out: list[float] = [] + for row in rows: + try: + out.append(float(row[key])) # type: ignore[index] + except Exception: + continue + return out + + +def _boolish(value: object) -> bool: + return str(value).strip().lower() in {"1", "true", "yes", "y"} + + +def _float_or_zero(value: object) -> float: + try: + return float(value) + except Exception: + return 0.0 + + +def _plot_or_skip(plot_dir: Path, name: str, fn) -> str | None: # type: ignore[no-untyped-def] + try: + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + except Exception as exc: + (plot_dir / "skipped_plots.json").write_text( + json.dumps({"reason": f"matplotlib unavailable: {exc}"}, indent=2), + encoding="utf-8", + ) + return None + path = plot_dir / name + fig = fn(plt) + fig.tight_layout() + fig.savefig(path, dpi=160) + plt.close(fig) + return str(path) + + +def _write_png(path: Path, width: int, height: int, pixels: bytearray) -> str: + def chunk(tag: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) + + raw = b"".join(b"\x00" + pixels[y * width * 3 : (y + 1) * width * 3] for y in range(height)) + png = ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw, 9)) + + chunk(b"IEND", b"") + ) + path.write_bytes(png) + return str(path) + + +def _simple_plot(path: Path, values: list[float], kind: str = "hist") -> str: + width, height = 800, 480 + pix = bytearray([255] * width * height * 3) + + def setpx(x: int, y: int, color: tuple[int, int, int]) -> None: + if 0 <= x < width and 0 <= y < height: + i = (y * width + x) * 3 + pix[i : i + 3] = bytes(color) + + def line(x0: int, y0: int, x1: int, y1: int, color: tuple[int, int, int]) -> None: + dx, dy = abs(x1 - x0), -abs(y1 - y0) + sx = 1 if x0 < x1 else -1 + sy = 1 if y0 < y1 else -1 + err = dx + dy + while True: + setpx(x0, y0, color) + if x0 == x1 and y0 == y1: + break + e2 = 2 * err + if e2 >= dy: + err += dy + x0 += sx + if e2 <= dx: + err += dx + y0 += sy + + def rect(x0: int, y0: int, x1: int, y1: int, color: tuple[int, int, int]) -> None: + for y in range(max(0, y0), min(height, y1)): + for x in range(max(0, x0), min(width, x1)): + setpx(x, y, color) + + left, top, right, bottom = 70, 40, 760, 420 + line(left, bottom, right, bottom, (20, 20, 20)) + line(left, top, left, bottom, (20, 20, 20)) + vals = [v for v in values if math.isfinite(v)] + if not vals: + return _write_png(path, width, height, pix) + if kind == "bar": + ordered = vals[:20] + mn = min(0.0, min(ordered)) + mx = max(0.0, max(ordered)) + span = mx - mn or 1.0 + bw = max(2, int((right - left) / max(1, len(ordered)))) + for i, v in enumerate(ordered): + x0 = left + i * bw + 2 + x1 = left + (i + 1) * bw - 2 + y = int(bottom - ((v - mn) / span) * (bottom - top)) + y0, y1 = sorted([bottom, y]) + rect(x0, y0, x1, y1, (75, 125, 170)) + else: + bins = min(30, max(5, len(vals) // 3)) + mn, mx = min(vals), max(vals) + span = mx - mn or 1.0 + counts = [0] * bins + for v in vals: + idx = min(bins - 1, int(((v - mn) / span) * bins)) + counts[idx] += 1 + maxc = max(counts) or 1 + bw = int((right - left) / bins) + for i, c in enumerate(counts): + x0 = left + i * bw + 1 + x1 = left + (i + 1) * bw - 1 + y0 = int(bottom - (c / maxc) * (bottom - top)) + rect(x0, y0, x1, bottom, (75, 125, 170)) + return _write_png(path, width, height, pix) + + +def plot_score_outputs(best_csv: str | Path, plot_dir: str | Path, title_prefix: str = "rDock") -> list[str]: + pdir = Path(plot_dir) + pdir.mkdir(parents=True, exist_ok=True) + rows = _read_rows(best_csv) + scores = _floats(rows, "SCORE") + paths: list[str] = [] + if not scores: + return paths + + def hist(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(7, 4)) + ax.hist(scores, bins=min(30, max(5, len(scores) // 5)), color="#3b6ea8", edgecolor="white") + ax.set_title(f"{title_prefix} SCORE distribution") + ax.set_xlabel("SCORE") + ax.set_ylabel("Count") + return fig + + def topbar(plt): # type: ignore[no-untyped-def] + ordered = sorted(rows, key=lambda r: float(r.get("SCORE", "inf")))[:20] + labels = [str(r.get("ligand_id", "")) for r in ordered] + vals = [float(r.get("SCORE", "nan")) for r in ordered] + fig, ax = plt.subplots(figsize=(9, 4)) + ax.bar(range(len(vals)), vals, color="#7a9d54") + ax.set_title(f"{title_prefix} top SCOREs") + ax.set_xlabel("Ligand rank") + ax.set_ylabel("SCORE") + ax.set_xticks(range(len(vals))) + ax.set_xticklabels(labels, rotation=60, ha="right", fontsize=8) + return fig + + for name, fn in (("score_distribution.png", hist), ("top_scores.png", topbar)): + if path := _plot_or_skip(pdir, name, fn): + paths.append(path) + else: + paths.append(_simple_plot(pdir / name, scores if "distribution" in name else sorted(scores)[:20], "hist" if "distribution" in name else "bar")) + return paths + + +def plot_astex_outputs(summary_csv: str | Path, plot_dir: str | Path) -> list[str]: + pdir = Path(plot_dir) + pdir.mkdir(parents=True, exist_ok=True) + rows = _read_rows(summary_csv) + top1 = _floats(rows, "top1_rmsd") + best = _floats(rows, "best_of_n_rmsd") + scores = _floats(rows, "top1_SCORE") + paths: list[str] = [] + if not top1 and not best: + return paths + + def hist(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(7, 4)) + if top1: + ax.hist(top1, alpha=0.65, label="top1", bins=20) + if best: + ax.hist(best, alpha=0.65, label="best-of-n", bins=20) + ax.axvline(2.0, color="black", linestyle="--", linewidth=1) + ax.set_xlabel("RMSD (A)") + ax.set_ylabel("Systems") + ax.legend() + return fig + + def scatter(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(5, 5)) + ax.scatter(top1[: len(best)], best[: len(top1)], color="#3b6ea8") + ax.axhline(2.0, color="black", linestyle="--", linewidth=1) + ax.axvline(2.0, color="black", linestyle="--", linewidth=1) + ax.set_xlabel("Top1 RMSD (A)") + ax.set_ylabel("Best-of-n RMSD (A)") + return fig + + def success_bar(plt): # type: ignore[no-untyped-def] + top1_success = sum(1 for row in rows if _boolish(row.get("success_top1_rmsd_le_2A"))) + best_success = sum(1 for row in rows if _boolish(row.get("success_best_rmsd_le_2A"))) + total = max(1, len([r for r in rows if r.get("status") == "success"])) + fig, ax = plt.subplots(figsize=(5, 4)) + ax.bar(["top1 <= 2A", "best <= 2A"], [top1_success / total, best_success / total], color=["#3b6ea8", "#7a9d54"]) + ax.set_ylim(0, 1) + ax.set_ylabel("Successful fraction") + return fig + + def score_vs_rmsd(plt): # type: ignore[no-untyped-def] + n = min(len(scores), len(top1)) + fig, ax = plt.subplots(figsize=(6, 4)) + ax.scatter(scores[:n], top1[:n], color="#7a4f9d") + ax.axhline(2.0, color="black", linestyle="--", linewidth=1) + ax.set_xlabel("Top pose SCORE") + ax.set_ylabel("Top1 RMSD (A)") + return fig + + plot_specs = [("rmsd_distribution.png", hist), ("top1_vs_best_rmsd.png", scatter), ("success_rmsd_le_2A.png", success_bar)] + if scores and top1: + plot_specs.append(("score_vs_rmsd.png", score_vs_rmsd)) + for name, fn in plot_specs: + if path := _plot_or_skip(pdir, name, fn): + paths.append(path) + else: + values = scores if name == "score_vs_rmsd.png" else (top1 or []) + (best or []) + paths.append(_simple_plot(pdir / name, values, "hist")) + return paths + + +def plot_dud_outputs(best_csv: str | Path, enrichment_csv: str | Path, plot_dir: str | Path) -> list[str]: + pdir = Path(plot_dir) + pdir.mkdir(parents=True, exist_ok=True) + rows = _read_rows(best_csv) + scores = _floats(rows, "SCORE") + labels = [] + for row in rows: + try: + labels.append(int(float(row.get("label", 0)))) + except Exception: + labels.append(0) + paths: list[str] = [] + if not scores: + return paths + + ordered = sorted(zip(scores, labels), key=lambda x: x[0]) + total_actives = max(1, sum(labels)) + x = [(i + 1) / len(ordered) for i in range(len(ordered))] + y = [] + seen = 0 + for _, label in ordered: + seen += int(label) + y.append(seen / total_actives) + total_decoys = max(1, len(labels) - sum(labels)) + roc_x: list[float] = [] + roc_y: list[float] = [] + tp = 0 + fp = 0 + for _, label in ordered: + if int(label) == 1: + tp += 1 + else: + fp += 1 + roc_x.append(fp / total_decoys) + roc_y.append(tp / total_actives) + ef_rows = _read_rows(enrichment_csv) if Path(enrichment_csv).exists() else [] + + def cumulative(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(7, 4)) + ax.plot(x, y, color="#3b6ea8") + ax.set_xlabel("Ranked fraction") + ax.set_ylabel("Cumulative active recovery") + return fig + + def score_by_label(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(7, 4)) + active = [s for s, l in zip(scores, labels) if l == 1] + decoy = [s for s, l in zip(scores, labels) if l == 0] + if active: + ax.hist(active, alpha=0.6, label="actives", bins=20) + if decoy: + ax.hist(decoy, alpha=0.6, label="decoys", bins=20) + ax.set_xlabel("SCORE") + ax.set_ylabel("Ligands") + ax.legend() + return fig + + def roc_curve(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(5, 5)) + ax.plot([0, *roc_x], [0, *roc_y], color="#3b6ea8") + ax.plot([0, 1], [0, 1], color="gray", linestyle="--", linewidth=1) + ax.set_xlabel("False positive rate") + ax.set_ylabel("True positive rate") + return fig + + def semilog_roc(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(6, 4)) + xs = [max(0.0005, v) for v in roc_x] + ax.plot(xs, roc_y, color="#3b6ea8") + ax.set_xscale("log") + ax.set_xlabel("False positive rate") + ax.set_ylabel("True positive rate") + return fig + + def ef_bar(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(6, 4)) + labels_ef = [str(row.get("fraction", "")) for row in ef_rows] + vals = _floats(ef_rows, "enrichment_factor") + ax.bar(labels_ef, vals, color="#7a9d54") + ax.set_xlabel("Ranked fraction") + ax.set_ylabel("Enrichment factor") + return fig + + plot_specs = [ + ("roc_curve.png", roc_curve), + ("semilog_roc.png", semilog_roc), + ("enrichment_factors.png", ef_bar), + ("cumulative_actives.png", cumulative), + ("score_distribution_by_label.png", score_by_label), + ] + for name, fn in plot_specs: + if path := _plot_or_skip(pdir, name, fn): + paths.append(path) + else: + paths.append(_simple_plot(pdir / name, y if "cumulative" in name else scores, "bar" if "cumulative" in name else "hist")) + return paths + + +def plot_adaptive_benchmark_outputs( + full_csv: str | Path, + adaptive_csv: str | Path, + random_csv: str | Path, + metrics_json: str | Path, + plot_dir: str | Path, +) -> list[str]: + pdir = Path(plot_dir) + pdir.mkdir(parents=True, exist_ok=True) + full_rows = _read_rows(full_csv) + adaptive_rows = _read_rows(adaptive_csv) + random_rows = _read_rows(random_csv) + metrics = json.loads(Path(metrics_json).read_text(encoding="utf-8")) if Path(metrics_json).exists() else {} + full_scores = _floats(full_rows, "SCORE") + adaptive_scores = _floats(adaptive_rows, "SCORE") + random_scores = _floats(random_rows, "SCORE") + paths: list[str] = [] + if not full_scores: + return paths + + def cumulative_best(rows: list[dict[str, str]]) -> list[float]: + vals = _floats(rows, "SCORE") + best: list[float] = [] + current = float("inf") + for value in vals: + current = min(current, value) + best.append(current) + return best + + def cumulative_plot(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(7, 4)) + full_curve = cumulative_best(full_rows) + adaptive_curve = cumulative_best(adaptive_rows) + random_curve = cumulative_best(random_rows) + if full_curve: + ax.plot(range(1, len(full_curve) + 1), full_curve, label="full") + if adaptive_curve: + ax.plot(range(1, len(adaptive_curve) + 1), adaptive_curve, label="adaptive") + if random_curve: + ax.plot(range(1, len(random_curve) + 1), random_curve, label="random") + ax.set_xlabel("Docked ligand count") + ax.set_ylabel("Best SCORE so far") + ax.legend() + return fig + + def percentile_bar(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(6, 4)) + labels = ["adaptive", "random", "full"] + vals = [ + float(metrics.get("adaptive_best_percentile_of_full", 0.0) or 0.0), + float(metrics.get("random_best_percentile_of_full", 0.0) or 0.0), + float(metrics.get("full_best_percentile_of_full", 100.0) or 100.0), + ] + ax.bar(labels, vals, color=["#3b6ea8", "#bf7f2f", "#7a9d54"]) + ax.set_ylim(0, 100) + ax.set_ylabel("Percentile in full ranking") + return fig + + def runtime_bar(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(6, 4)) + labels = ["full docking", "adaptive docking", "random docking", "adaptive model"] + vals = [ + float(metrics.get("full_docking_seconds", 0.0) or 0.0), + float(metrics.get("adaptive_docking_seconds", 0.0) or 0.0), + float(metrics.get("random_docking_seconds", 0.0) or 0.0), + float(metrics.get("adaptive_model_seconds", 0.0) or 0.0), + ] + ax.bar(labels, vals, color=["#7a9d54", "#3b6ea8", "#bf7f2f", "#7a4f9d"]) + ax.set_ylabel("Seconds") + ax.tick_params(axis="x", rotation=20) + return fig + + def success_bar(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(6, 4)) + labels = ["full ok", "adaptive ok", "random ok", "failed"] + vals = [ + float(metrics.get("full_success_count", 0.0) or 0.0), + float(metrics.get("adaptive_success_count", 0.0) or 0.0), + float(metrics.get("random_success_count", 0.0) or 0.0), + float(metrics.get("failed_docking_count", 0.0) or 0.0), + ] + ax.bar(labels, vals, color=["#7a9d54", "#3b6ea8", "#bf7f2f", "#b14d4d"]) + ax.set_ylabel("Ligands") + ax.tick_params(axis="x", rotation=15) + return fig + + def model_scatter(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(6, 4)) + xs = _floats(adaptive_rows, "model_score") + ys = _floats(adaptive_rows, "SCORE") + n = min(len(xs), len(ys)) + ax.scatter(xs[:n], ys[:n], color="#3b6ea8") + ax.set_xlabel("Model score") + ax.set_ylabel("rDock SCORE") + return fig + + plot_specs = [ + ("cumulative_best_score.png", cumulative_plot), + ("adaptive_random_full_percentile.png", percentile_bar), + ("runtime_summary.png", runtime_bar), + ("success_failure_summary.png", success_bar), + ] + if _floats(adaptive_rows, "model_score"): + plot_specs.append(("model_vs_rdock_score.png", model_scatter)) + for name, fn in plot_specs: + if path := _plot_or_skip(pdir, name, fn): + paths.append(path) + else: + fallback = full_scores + if name == "adaptive_random_full_percentile.png": + fallback = [ + float(metrics.get("adaptive_best_percentile_of_full", 0.0) or 0.0), + float(metrics.get("random_best_percentile_of_full", 0.0) or 0.0), + float(metrics.get("full_best_percentile_of_full", 100.0) or 100.0), + ] + paths.append(_simple_plot(pdir / name, fallback, "bar" if "summary" in name or "percentile" in name else "hist")) + return paths + + +def plot_multifidelity_outputs( + trace_csv: str | Path, + final_hits_csv: str | Path, + random_csv: str | Path, + full_csv: str | Path, + metrics_json: str | Path, + plot_dir: str | Path, +) -> list[str]: + pdir = Path(plot_dir) + pdir.mkdir(parents=True, exist_ok=True) + trace_rows = _read_rows(trace_csv) if Path(trace_csv).exists() else [] + final_rows = _read_rows(final_hits_csv) if Path(final_hits_csv).exists() else [] + random_rows = _read_rows(random_csv) if Path(random_csv).exists() else [] + full_rows = _read_rows(full_csv) if Path(full_csv).exists() else [] + metrics = json.loads(Path(metrics_json).read_text(encoding="utf-8")) if Path(metrics_json).exists() else {} + paths: list[str] = [] + if not trace_rows: + return paths + + def cumulative_best_vs_cost(rows: list[dict[str, str]], score_key: str = "current_best_score"): # type: ignore[no-untyped-def] + 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)))) + xs: list[float] = [] + ys: list[float] = [] + current = float("inf") + for row in ordered: + score = _float_or_zero(row.get(score_key, row.get("SCORE", 0.0))) + if score == 0.0 and row.get(score_key, row.get("SCORE", "")) in ("", None): + continue + current = min(current, score) + xs.append(_float_or_zero(row.get("n_rdock_runs_total_spent", 0.0))) + ys.append(current) + return xs, ys + + def best_vs_cost(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(7, 4)) + xs, ys = cumulative_best_vs_cost(trace_rows) + if xs and ys: + ax.plot(xs, ys, label="multifidelity") + random_vals = sorted(_floats(random_rows, "final_score") or _floats(random_rows, "SCORE")) + if random_vals: + ax.axhline(random_vals[0], color="#bf7f2f", linestyle="--", label="random best") + full_vals = sorted(_floats(full_rows, "SCORE")) + if full_vals: + ax.axhline(full_vals[0], color="#7a9d54", linestyle=":", label="full best") + ax.set_xlabel("Total rDock runs spent") + ax.set_ylabel("Best SCORE so far") + ax.legend() + return fig + + def best_vs_walltime(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(7, 4)) + 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))) + xs: list[float] = [] + ys: list[float] = [] + elapsed = 0.0 + current = float("inf") + for row in ordered: + score = _float_or_zero(row.get("current_best_score", row.get("SCORE", 0.0))) + elapsed += _float_or_zero(row.get("timing_docking_seconds", 0.0)) + _float_or_zero(row.get("timing_training_seconds", 0.0)) + current = min(current, score) + xs.append(elapsed) + ys.append(current) + if xs and ys: + ax.plot(xs, ys, color="#3b6ea8") + ax.set_xlabel("Walltime (s)") + ax.set_ylabel("Best SCORE so far") + return fig + + def fidelity_counts(plt): # type: ignore[no-untyped-def] + counts: dict[str, int] = {} + for row in trace_rows: + level = str(row.get("selected_fidelity_runs", "")) + counts[level] = counts.get(level, 0) + 1 + labels = sorted(counts, key=lambda x: int(x or 0)) + vals = [counts[label] for label in labels] + fig, ax = plt.subplots(figsize=(6, 4)) + ax.bar(labels, vals, color="#3b6ea8") + ax.set_xlabel("Fidelity runs") + ax.set_ylabel("Ligands screened") + return fig + + def promotion_funnel(plt): # type: ignore[no-untyped-def] + counts: dict[str, int] = {} + for row in trace_rows: + level = str(row.get("selected_fidelity_runs", "")) + counts[level] = counts.get(level, 0) + 1 + labels = sorted(counts, key=lambda x: int(x or 0)) + vals = [counts[label] for label in labels] + fig, ax = plt.subplots(figsize=(6, 4)) + ax.plot(range(len(vals)), vals, marker="o", color="#7a4f9d") + ax.set_xticks(range(len(vals))) + ax.set_xticklabels(labels) + ax.set_xlabel("Fidelity runs") + ax.set_ylabel("Ligands") + return fig + + def percentile_bar(plt): # type: ignore[no-untyped-def] + labels = ["multifidelity", "random", "single", "full"] + vals = [ + float(metrics.get("multifidelity_percentile_vs_full", 0.0) or 0.0), + float(metrics.get("random_percentile_vs_full", 0.0) or 0.0), + float(metrics.get("single_fidelity_percentile_vs_full", 0.0) or 0.0), + 100.0, + ] + fig, ax = plt.subplots(figsize=(6, 4)) + ax.bar(labels, vals, color=["#3b6ea8", "#bf7f2f", "#7a4f9d", "#7a9d54"]) + ax.set_ylim(0, 100) + ax.set_ylabel("Percentile in full ranking") + return fig + + def score_by_level(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(7, 4)) + levels = sorted({str(row.get("selected_fidelity_runs", "")) for row in trace_rows}, key=lambda x: int(x or 0)) + for level in levels: + 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)] + if vals: + ax.hist(vals, bins=min(25, max(5, len(vals) // 3)), alpha=0.45, label=level) + ax.set_xlabel("SCORE") + ax.set_ylabel("Records") + ax.legend(title="runs") + return fig + + def intra_hist(plt): # type: ignore[no-untyped-def] + vals = [_float_or_zero(row.get("SCORE.INTRA", 0.0)) for row in trace_rows if row.get("SCORE.INTRA", "") not in ("", None)] + fig, ax = plt.subplots(figsize=(7, 4)) + ax.hist(vals, bins=min(30, max(5, len(vals) // 3)), color="#bf7f2f") + ax.set_xlabel("SCORE.INTRA") + ax.set_ylabel("Records") + return fig + + def score_vs_intra(plt): # type: ignore[no-untyped-def] + 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)] + 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)] + fig, ax = plt.subplots(figsize=(6, 4)) + if xs and ys: + 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) + ax.set_xlabel("SCORE.INTRA") + ax.set_ylabel("SCORE") + return fig + + def top_hits_bar(plt): # type: ignore[no-untyped-def] + ordered = sorted( + [row for row in final_rows if str(row.get("is_final_fidelity", "")).lower() in {"true", "1"}], + key=lambda row: _float_or_zero(row.get("final_score", row.get("current_best_score", 0.0))), + )[:20] + labels = [str(row.get("ligand_id", "")) for row in ordered] + vals = [_float_or_zero(row.get("final_score", row.get("current_best_score", 0.0))) for row in ordered] + fig, ax = plt.subplots(figsize=(9, 4)) + ax.bar(range(len(vals)), vals, color="#7a9d54") + ax.set_xticks(range(len(vals))) + ax.set_xticklabels(labels, rotation=60, ha="right", fontsize=8) + ax.set_ylabel("Final SCORE") + return fig + + def training_vs_docking(plt): # type: ignore[no-untyped-def] + fig, ax = plt.subplots(figsize=(6, 4)) + ax.bar( + ["training", "docking", "overhead"], + [ + float(metrics.get("training_time_seconds", 0.0) or 0.0), + float(metrics.get("docking_time_seconds", 0.0) or 0.0), + float(metrics.get("overhead_time_seconds", 0.0) or 0.0), + ], + color=["#7a4f9d", "#3b6ea8", "#bf7f2f"], + ) + ax.set_ylabel("Seconds") + return fig + + plot_specs = [ + ("cumulative_best_final_score_vs_runs.png", best_vs_cost), + ("cumulative_best_score_vs_walltime.png", best_vs_walltime), + ("ligands_per_fidelity_level.png", fidelity_counts), + ("promotion_funnel.png", promotion_funnel), + ("adaptive_vs_random_vs_full_percentile.png", percentile_bar), + ("score_distribution_by_fidelity.png", score_by_level), + ("score_intra_distribution.png", intra_hist), + ("score_vs_score_intra.png", score_vs_intra), + ("top_final_hits.png", top_hits_bar), + ("training_vs_docking_time.png", training_vs_docking), + ] + for name, fn in plot_specs: + if path := _plot_or_skip(pdir, name, fn): + paths.append(path) + else: + vals = _floats(trace_rows, "SCORE") + 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")) + return paths diff --git a/docking_pipeline/sdf.py b/docking_pipeline/sdf.py new file mode 100644 index 0000000000000000000000000000000000000000..4f4fa19aee7ee1ef401e1ce62f4c9462ca4ecf11 --- /dev/null +++ b/docking_pipeline/sdf.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +import csv +import math +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Iterable + +from .provenance import RDockPipelineError, require_file + +TAG_RE = re.compile(r"^>\s*<\s*([^>]+?)\s*>", flags=re.IGNORECASE) + + +@dataclass(frozen=True) +class SDFRecord: + block: str + index: int + ligand_id: str + score: float | None + tags: dict[str, str] + numeric_tags: dict[str, float] + + +def split_sdf_text(text: str) -> list[str]: + blocks: list[str] = [] + for part in text.split("$$$$"): + body = part.strip() + if body: + blocks.append(body + "\n$$$$\n") + return blocks + + +def split_sdf_file(path: str | Path) -> list[str]: + source = require_file(path, "SDF file") + blocks = split_sdf_text(source.read_text(encoding="utf-8", errors="ignore")) + if not blocks: + raise RDockPipelineError(f"No SDF records found in {source}") + return blocks + + +def parse_tags(block: str) -> dict[str, str]: + lines = block.splitlines() + tags: dict[str, str] = {} + i = 0 + while i < len(lines): + m = TAG_RE.match(lines[i].strip()) + if not m: + i += 1 + continue + key = m.group(1).strip() + values: list[str] = [] + j = i + 1 + while j < len(lines) and lines[j].strip() and lines[j].strip() != "$$$$" and not TAG_RE.match(lines[j].strip()): + values.append(lines[j].strip()) + j += 1 + tags[key] = "\n".join(values).strip() + i = j + return tags + + +def _safe_float(value: Any) -> float | None: + try: + out = float(str(value).strip()) + except Exception: + return None + if not math.isfinite(out): + return None + return out + + +def _record_name(block: str, fallback: str) -> str: + first = block.splitlines()[0].strip() if block.splitlines() else "" + return first or fallback + + +def ligand_id_from_block(block: str, tags: dict[str, str], index: int) -> str: + for key in ("ligand_id", "LigandID", "LIGAND_ID", "ID", "Name", "_Name"): + value = tags.get(key) + if value: + return value.split()[0].strip() + return _record_name(block, f"ligand_{index:06d}").split()[0].strip() + + +def parse_rdock_sdf_records(path: str | Path, require_score: bool = True) -> list[SDFRecord]: + records: list[SDFRecord] = [] + for idx, block in enumerate(split_sdf_file(path)): + tags = parse_tags(block) + numeric = {k: v for k, raw in tags.items() if (v := _safe_float(raw)) is not None} + score = numeric.get("SCORE") + if require_score and score is None: + raise RDockPipelineError(f"Missing required rDock SCORE field in SDF record {idx} of {path}") + records.append( + SDFRecord( + block=block, + index=idx, + ligand_id=ligand_id_from_block(block, tags, idx), + score=score, + tags=tags, + numeric_tags=numeric, + ) + ) + return records + + +def write_sdf_records(records: Iterable[SDFRecord], path: str | Path) -> Path: + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("".join(rec.block for rec in records), encoding="utf-8") + return target + + +def write_sdf_blocks(blocks: Iterable[str], path: str | Path) -> Path: + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("".join(blocks), encoding="utf-8") + return target + + +def best_per_ligand(records: Iterable[SDFRecord]) -> list[SDFRecord]: + best: dict[str, SDFRecord] = {} + for rec in records: + if rec.score is None: + raise RDockPipelineError(f"Cannot rank ligand {rec.ligand_id}: missing SCORE") + prev = best.get(rec.ligand_id) + if prev is None or float(rec.score) < float(prev.score): + best[rec.ligand_id] = rec + return sorted(best.values(), key=lambda r: (float(r.score), r.ligand_id, r.index)) + + +def records_to_rows(records: Iterable[SDFRecord]) -> list[dict[str, object]]: + rows: list[dict[str, object]] = [] + for rec in records: + row: dict[str, object] = { + "pose_index": rec.index, + "ligand_id": rec.ligand_id, + "SCORE": rec.score, + } + for key, value in sorted(rec.numeric_tags.items()): + row[key] = value + rows.append(row) + return rows + + +def write_rows_csv(rows: list[dict[str, object]], path: str | Path) -> Path: + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + fields: list[str] = [] + for row in rows: + for key in row: + if key not in fields: + fields.append(key) + with target.open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + return target diff --git a/docking_pipeline/validation.py b/docking_pipeline/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..3207ff051a076fd19b5e617905f1c67d4700c41d --- /dev/null +++ b/docking_pipeline/validation.py @@ -0,0 +1,708 @@ +from __future__ import annotations + +import csv +import gzip +import json +import os +import re +import shutil +import tarfile +import urllib.request +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import asdict, dataclass +from pathlib import Path +from statistics import median +from typing import Iterable + +from .metrics import enrichment_rows, validation_metrics_from_rows +from .provenance import CommandRecord, CommandRunner, RDockPipelineError, fail_if_bad_command, require_executable, require_file +from .reports.plots import plot_astex_outputs, plot_dud_outputs +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 + +VALIDATION_URL = "https://rdock.github.io/validation-sets/" + + +@dataclass(frozen=True) +class ValidationSystem: + system_id: str + path: str + receptor_prm: str + dock_prm: str + ligand_sdf: str = "" + ligprep_sdf: str = "" + crystal_sdf: str = "" + + +def resolve_jobs(jobs: int | str = "auto", cpu_fraction: float = 0.85) -> int: + if str(jobs).lower() == "auto": + cpus = os.cpu_count() or 1 + reserve = 1 if cpus <= 4 else 2 + return max(1, min(cpus - reserve, int(cpus * float(cpu_fraction)))) + return max(1, int(jobs)) + + +def _rdock_env() -> dict[str, str]: + root = os.environ.get("RBT_ROOT") + if root: + return {"RBT_ROOT": root} + for candidate in (Path("/opt/homebrew/opt/rdock/share"), Path("/usr/local/opt/rdock/share")): + if (candidate / "data" / "RbtElements.dat").exists(): + return {"RBT_ROOT": str(candidate)} + cellar = Path("/opt/homebrew/Cellar/rdock") + if cellar.exists(): + for candidate in sorted(cellar.glob("*/share"), reverse=True): + if (candidate / "data" / "RbtElements.dat").exists(): + return {"RBT_ROOT": str(candidate)} + return {} + + +def _system_id_from_prm(path: Path) -> str: + name = path.stem + return re.sub(r"_?rdock$", "", name, flags=re.IGNORECASE) + + +def _find_first(candidates: Iterable[Path]) -> Path | None: + for p in candidates: + if p.exists() and p.is_file() and p.stat().st_size > 0: + return p + return None + + +def _find_dock_prm(system_dir: Path) -> Path | None: + candidates = [system_dir / "dock.prm"] + [parent / "dock.prm" for parent in list(system_dir.parents)[:3]] + rbt_root = os.environ.get("RBT_ROOT") + if rbt_root: + candidates.extend([Path(rbt_root) / "data" / "scripts" / "dock.prm", Path(rbt_root) / "data" / "dock.prm"]) + candidates.extend( + [ + Path("/opt/homebrew/share/rdock/data/scripts/dock.prm"), + Path("/opt/homebrew/opt/rdock/share/data/scripts/dock.prm"), + ] + ) + candidates.extend(sorted(Path("/opt/homebrew/Cellar/rdock").glob("*/share/data/scripts/dock.prm")) if Path("/opt/homebrew/Cellar/rdock").exists() else []) + return _find_first(candidates) + + +def discover_validation_systems(data_dir: str | Path, set_name: str) -> list[ValidationSystem]: + root = Path(data_dir) + if not root.exists(): + return [] + systems: dict[str, ValidationSystem] = {} + for prm in sorted(root.rglob("*_rdock.prm")): + system_dir = prm.parent + system_id = _system_id_from_prm(prm) + dock_prm = _find_dock_prm(system_dir) + if dock_prm is None: + local = list(system_dir.rglob("dock.prm")) + dock_prm = local[0] if local else None + sdf_files = sorted(list(system_dir.glob("*.sd")) + list(system_dir.glob("*.sdf"))) + gz_sdfs = sorted(list(system_dir.glob("*.sd.gz")) + list(system_dir.glob("*.sdf.gz"))) + ligand_sdf = _find_first( + [ + system_dir / f"{system_id}_ligand.sd", + system_dir / f"{system_id}_ligand.sdf", + system_dir / "ligand.sd", + system_dir / "ligand.sdf", + ] + + [p for p in sdf_files if "ligand" in p.name.lower() or "crystal" in p.name.lower()] + + sdf_files + ) + ligprep_sdf = _find_first( + [ + system_dir / f"{system_id}_ligprep.sdf", + system_dir / f"{system_id}_ligprep.sd", + ] + + [p for p in sdf_files if "ligprep" in p.name.lower()] + + [p for p in gz_sdfs if "ligprep" in p.name.lower()] + ) + if set_name.lower() == "dud" and ligprep_sdf is None: + continue + systems[system_id] = ValidationSystem( + system_id=system_id, + path=str(system_dir), + receptor_prm=str(prm), + dock_prm=str(dock_prm or ""), + ligand_sdf=str(ligand_sdf or ""), + ligprep_sdf=str(ligprep_sdf or ""), + crystal_sdf=str(ligand_sdf or ""), + ) + return [systems[k] for k in sorted(systems)] + + +def _actionable_missing_system(data_dir: Path, set_name: str, system: str | None) -> RDockPipelineError: + expected = data_dir / (system or "") + return RDockPipelineError( + "Missing rDock validation data.\n" + f"Expected path or discoverable system files under: {expected}\n" + f"Validation set: {set_name}\n" + f"Official validation sets: {VALIDATION_URL}\n" + "Use one of:\n" + f" python -m docking_pipeline validate-rdock --set {set_name} --data-dir {data_dir} --list-systems\n" + f" python -m docking_pipeline validate-rdock --set {set_name} --system {system or ''} --data-dir {data_dir} --out results/benchmarks/{set_name}_{system or ''} --download-url --download-if-missing\n" + "or manually download/extract the official rDock validation set and pass its extracted directory via --data-dir." + ) + + +def download_validation_set(download_url: str, data_dir: str | Path, force: bool = False) -> Path: + target = Path(data_dir) + if target.exists() and any(target.iterdir()) and not force: + return target + target.mkdir(parents=True, exist_ok=True) + archive = target / Path(download_url).name + urllib.request.urlretrieve(download_url, archive) + with tarfile.open(archive, "r:*") as tar: + tar.extractall(target) + return target + + +def ensure_validation_data(data_dir: str | Path, set_name: str, download_url: str | None, download_if_missing: bool, force: bool = False) -> Path: + root = Path(data_dir) + if root.exists() and discover_validation_systems(root, set_name): + return root + if download_if_missing: + if not download_url: + raise RDockPipelineError( + f"--download-if-missing was set but --download-url was not provided. Official validation sets: {VALIDATION_URL}" + ) + download_validation_set(download_url, root, force=force) + return root + + +def resolve_systems( + data_dir: str | Path, + set_name: str, + system: str | None = None, + system_list: str | Path | None = None, + max_systems: int | None = None, +) -> list[ValidationSystem]: + root = Path(data_dir) + systems = discover_validation_systems(root, set_name) + if not systems: + raise _actionable_missing_system(root, set_name, system) + wanted: set[str] | None = None + if system: + wanted = {system} + if system_list: + ids = [line.strip() for line in Path(system_list).read_text(encoding="utf-8").splitlines() if line.strip()] + wanted = (wanted or set()) | set(ids) + if wanted is not None: + systems = [s for s in systems if s.system_id in wanted] + if not systems: + raise _actionable_missing_system(root, set_name, system or ",".join(sorted(wanted))) + if max_systems is not None: + systems = systems[: int(max_systems)] + return systems + + +def _copy_system(src: Path, out_dir: Path, force: bool) -> Path: + dst = out_dir / "rdock" / src.name + if dst.exists(): + if not force: + return dst + shutil.rmtree(dst) + shutil.copytree(src, dst) + return dst + + +def _gunzip_if_needed(path: Path) -> Path: + if path.exists() and path.suffix != ".gz": + return path + if path.suffix == ".gz": + out = path.with_suffix("") + if not out.exists(): + with gzip.open(path, "rb") as src, out.open("wb") as dst: + shutil.copyfileobj(src, dst) + return out + gz = path.with_suffix(path.suffix + ".gz") + if gz.exists(): + return _gunzip_if_needed(gz) + return require_file(path, "ligand-prepped SDF") + + +def _run_rbdock_parallel( + runner: CommandRunner, + work: Path, + prm: Path, + dock_prm: Path, + ligand_sdf: Path, + out_prefix: str, + n_runs: int, + jobs: int, +) -> tuple[Path, list[CommandRecord]]: + rbdock = require_executable("rbdock") + blocks = split_sdf_file(ligand_sdf) + chunk_dir = work / "chunks" + chunk_dir.mkdir(exist_ok=True) + chunk_count = min(max(1, jobs), len(blocks)) + chunks: list[Path] = [] + for idx in range(chunk_count): + chunk_blocks = blocks[idx::chunk_count] + chunk = chunk_dir / f"chunk_{idx:03d}.sdf" + write_sdf_blocks(chunk_blocks, chunk) + chunks.append(chunk) + + def run_one(idx: int, chunk: Path) -> tuple[int, CommandRecord, Path]: + prefix = work / f"{out_prefix}_chunk_{idx:03d}" + rec = runner.run( + f"rbdock_chunk_{idx:03d}", + [rbdock, "-r", str(prm.name), "-p", str(dock_prm), "-n", str(int(n_runs)), "-i", str(chunk.relative_to(work)), "-o", str(prefix.name)], + work, + work / f"{out_prefix}_chunk_{idx:03d}.stdout.log", + work / f"{out_prefix}_chunk_{idx:03d}.stderr.log", + env=_rdock_env(), + ) + return idx, rec, prefix.with_suffix(".sd") + + outputs: dict[int, Path] = {} + records: list[CommandRecord] = [] + with ThreadPoolExecutor(max_workers=chunk_count) as pool: + futures = [pool.submit(run_one, idx, chunk) for idx, chunk in enumerate(chunks)] + for fut in as_completed(futures): + idx, rec, out_sd = fut.result() + fail_if_bad_command(rec, f"rbdock chunk {idx}") + require_file(out_sd, f"rDock output chunk {idx}") + outputs[idx] = out_sd + records.append(rec) + merged = work / f"{out_prefix}.sd" + all_blocks: list[str] = [] + for idx in sorted(outputs): + all_blocks.extend(split_sdf_file(outputs[idx])) + write_sdf_blocks(all_blocks, merged) + return merged, records + + +def _parse_rmsd_stdout(text: str) -> list[float]: + vals: list[float] = [] + for token in re.findall(r"[-+]?(?:\d+\.\d+|\d+)", text): + try: + value = float(token) + except Exception: + continue + if 0.0 <= value < 100.0: + vals.append(value) + return vals + + +def _sdf_pose_coords(path: Path) -> list[list[list[float]]]: + poses: list[list[list[float]]] = [] + for block in split_sdf_file(path): + lines = block.splitlines() + if len(lines) < 4: + continue + try: + atom_count = int(lines[3][0:3]) + except Exception: + continue + coords: list[list[float]] = [] + for line in lines[4 : 4 + atom_count]: + try: + coords.append([float(line[0:10]), float(line[10:20]), float(line[20:30])]) + except Exception: + parts = line.split() + if len(parts) >= 3: + try: + coords.append([float(parts[0]), float(parts[1]), float(parts[2])]) + except Exception: + continue + if coords: + poses.append(coords) + return poses + + +def _rmsd_same_order(a: list[list[float]], b: list[list[float]]) -> float: + n = min(len(a), len(b)) + if n == 0: + return float("nan") + 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 + + +def _internal_rmsds(reference_sdf: Path, poses_sdf: Path) -> list[float]: + ref = _sdf_pose_coords(reference_sdf) + poses = _sdf_pose_coords(poses_sdf) + if not ref: + return [] + return [_rmsd_same_order(ref[0], pose) for pose in poses] + + +def _write_csv(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + fields: list[str] = [] + for row in rows: + for k in row: + if k not in fields: + fields.append(k) + with path.open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + + +def _empty_standard_outputs(root: Path) -> None: + for name in ("target", "ligands", "rdock", "poses", "tables", "metrics", "plots"): + (root / name).mkdir(parents=True, exist_ok=True) + + +def _copy_receptor_to_target(work: Path, system: ValidationSystem, root: Path) -> Path | None: + target_dir = root / "target" + target_dir.mkdir(parents=True, exist_ok=True) + prm_stem = Path(system.receptor_prm).stem + candidates = [ + work / f"{prm_stem}.mol2", + work / f"{system.system_id}_rdock.mol2", + work / f"{system.system_id}.mol2", + ] + candidates.extend(sorted(work.glob("*.mol2"))) + receptor = _find_first(candidates) + if receptor is None: + return None + dst = target_dir / receptor.name + shutil.copy2(receptor, dst) + return dst + + +def validate_astex_system( + system: ValidationSystem, + root: Path, + n_runs: int, + jobs: int, + force: bool = False, +) -> dict[str, object]: + _empty_standard_outputs(root) + work = _copy_system(Path(system.path), root, force=force) + _copy_receptor_to_target(work, system, root) + runner = CommandRunner(root / "commands.log") + for exe in ("rbcavity", "rbdock", "sdsort", "sdrmsd"): + require_executable(exe) + prm = require_file(work / Path(system.receptor_prm).name, "ASTEX rDock receptor prm") + dock_prm = require_file(system.dock_prm, "ASTEX dock.prm") + ligand = require_file(work / Path(system.ligand_sdf).name, "ASTEX ligand SDF") + rec = runner.run("rbcavity", ["rbcavity", "-r", prm.name, "-was"], work, work / "rbcavity.stdout.log", work / "rbcavity.stderr.log", env=_rdock_env()) + fail_if_bad_command(rec, "ASTEX rbcavity") + out_sd, _ = _run_rbdock_parallel(runner, work, prm, dock_prm, ligand, f"{system.system_id}_docking_out", n_runs, jobs) + rec = runner.run( + "sdsort", + ["/bin/sh", "-c", f"sdsort -n -f'SCORE' {out_sd.name} > {system.system_id}_docking_out_sorted.sd"], + work, + work / "sdsort.stdout.log", + work / "sdsort.stderr.log", + env=_rdock_env(), + ) + fail_if_bad_command(rec, "ASTEX sdsort") + sorted_sd = require_file(work / f"{system.system_id}_docking_out_sorted.sd", "ASTEX sorted SDF") + rmsd_source = "sdrmsd" + rmsd_diagnostic = "" + rec = runner.run("sdrmsd", ["sdrmsd", ligand.name, sorted_sd.name], work, work / "sdrmsd.stdout.log", work / "sdrmsd.stderr.log", env=_rdock_env()) + try: + fail_if_bad_command(rec, "ASTEX sdrmsd") + rmsds = _parse_rmsd_stdout(Path(rec.stdout_log).read_text(encoding="utf-8", errors="ignore")) + except RDockPipelineError as exc: + rmsd_source = "internal_same_atom_order_sdf_rmsd_after_sdrmsd_failure" + rmsd_diagnostic = str(exc) + rmsds = _internal_rmsds(ligand, sorted_sd) + top1 = rmsds[0] if rmsds else float("nan") + best = min(rmsds) if rmsds else float("nan") + shutil.copy2(out_sd, root / "poses" / "all_poses.sdf") + shutil.copy2(sorted_sd, root / "poses" / "best_per_ligand.sdf") + records = parse_rdock_sdf_records(out_sd) + sorted_records = parse_rdock_sdf_records(sorted_sd) + best_records = best_per_ligand(records) + write_rows_csv(records_to_rows(records), root / "tables" / "scores_long.csv") + write_rows_csv(records_to_rows(best_records), root / "tables" / "best_per_ligand.csv") + top1_score = sorted_records[0].numeric_tags.get("SCORE") if sorted_records else None + row = { + "system_id": system.system_id, + "top1_rmsd": top1, + "best_of_n_rmsd": best, + "top1_SCORE": top1_score, + "success_top1_rmsd_le_2A": bool(top1 <= 2.0), + "success_best_rmsd_le_2A": bool(best <= 2.0), + "n_poses": len(records), + "status": "success", + "rmsd_source": rmsd_source, + "rmsd_diagnostic": rmsd_diagnostic, + } + _write_csv(root / "tables" / "astex_system_summary.csv", [row]) + metrics = { + **row, + "median_top1_rmsd": top1, + "median_best_rmsd": best, + "n_systems_total": 1, + "n_systems_successful": 1, + "n_systems_failed": 0, + "n_poses_total": len(records), + } + (root / "metrics" / "validation_metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8") + (root / "metrics" / "enrichment.csv").write_text("", encoding="utf-8") + plots = plot_astex_outputs(root / "tables" / "astex_system_summary.csv", root / "plots") + _write_validation_report(root, "ASTEX", [system], runner.records, metrics, plots) + return metrics + + +def _read_dud_labels(work: Path) -> dict[str, int]: + labels: dict[str, int] = {} + for name, value in (("ligands.txt", 1), ("actives.txt", 1), ("decoys.txt", 0)): + p = work / name + if not p.exists(): + continue + for line in p.read_text(encoding="utf-8", errors="ignore").splitlines(): + parts = line.strip().split() + if parts: + labels[parts[0]] = value + return labels + + +def validate_dud_system(system: ValidationSystem, root: Path, n_runs: int, jobs: int, force: bool = False) -> dict[str, object]: + _empty_standard_outputs(root) + work = _copy_system(Path(system.path), root, force=force) + _copy_receptor_to_target(work, system, root) + runner = CommandRunner(root / "commands.log") + for exe in ("rbcavity", "rbdock", "sdsort", "sdfilter", "sdreport"): + require_executable(exe) + prm = require_file(work / Path(system.receptor_prm).name, "DUD rDock receptor prm") + dock_prm = require_file(system.dock_prm, "DUD dock.prm") + ligprep = _gunzip_if_needed(work / Path(system.ligprep_sdf).name) + labels = _read_dud_labels(work) + if not labels: + raise RDockPipelineError( + "Missing DUD active/decoy label files for enrichment metrics.\n" + f"Expected `ligands.txt`/`actives.txt` and `decoys.txt` in: {work}\n" + "The official rDock ROC workflow requires these files to assign IsActive labels.\n" + "Add the label files for this DUD system, then rerun the same validate-rdock command." + ) + rec = runner.run("rbcavity", ["rbcavity", "-r", prm.name, "-was"], work, work / "rbcavity.stdout.log", work / "rbcavity.stderr.log", env=_rdock_env()) + fail_if_bad_command(rec, "DUD rbcavity") + out_sd, _ = _run_rbdock_parallel(runner, work, prm, dock_prm, ligprep, f"{system.system_id}_docking_out", n_runs, jobs) + records = parse_rdock_sdf_records(out_sd, require_score=True) + best_records = best_per_ligand(records) + best_sd = write_sdf_records(best_records, work / f"{system.system_id}_1poseperlig.sd") + rows = records_to_rows(best_records) + for row in rows: + row["label"] = labels.get(str(row["ligand_id"]), 0) + duplicate_count = len(records) - len({r.ligand_id for r in records}) + metrics = validation_metrics_from_rows(rows) + metrics.update( + { + "active_count": sum(int(row.get("label", 0)) for row in rows), + "decoy_count": sum(1 - int(row.get("label", 0)) for row in rows), + "attempted_ligands": len(split_sdf_file(ligprep)), + "successful_ligands": len(rows), + "failed_ligands": max(0, len(split_sdf_file(ligprep)) - len(rows)), + "duplicate_ligand_ids": duplicate_count, + "missing_SCORE_count": 0, + } + ) + shutil.copy2(out_sd, root / "poses" / "all_poses.sdf") + shutil.copy2(best_sd, root / "poses" / "best_per_ligand.sdf") + write_rows_csv(records_to_rows(records), root / "tables" / "scores_long.csv") + write_rows_csv(rows, root / "tables" / "best_per_ligand.csv") + _write_csv(root / "metrics" / "enrichment.csv", enrichment_rows([float(r["SCORE"]) for r in rows], [int(r["label"]) for r in rows])) + (root / "metrics" / "validation_metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8") + plots = plot_dud_outputs(root / "tables" / "best_per_ligand.csv", root / "metrics" / "enrichment.csv", root / "plots") + _write_validation_report(root, "DUD", [system], runner.records, metrics, plots) + return metrics + + +def plan_validation( + set_name: str, + data_dir: str | Path, + systems: list[ValidationSystem], + out_dir: str | Path, + n_runs: int, + jobs: int | str, + cpu_fraction: float, +) -> dict[str, object]: + resolved_jobs = resolve_jobs(jobs, cpu_fraction) + return { + "set": set_name, + "data_dir": str(data_dir), + "out": str(out_dir), + "n_runs": int(n_runs), + "jobs": resolved_jobs, + "system_count": len(systems), + "systems": [asdict(s) for s in systems], + "commands": [ + f"rbcavity -r _rdock.prm -was", + f"rbdock -r _rdock.prm -p dock.prm -n {int(n_runs)} -i .sd -o ", + "sdsort/sdrmsd for ASTEX or best-pose/enrichment reporting for DUD", + ], + } + + +def validate_many( + set_name: str, + data_dir: str | Path, + out_dir: str | Path, + system: str | None = None, + system_list: str | Path | None = None, + max_systems: int | None = None, + n_runs: int = 100, + jobs: int | str = "auto", + cpu_fraction: float = 0.85, + download_url: str | None = None, + download_if_missing: bool = False, + force: bool = False, + dry_run: bool = False, + plan_only: bool = False, +) -> dict[str, object]: + root_data = ensure_validation_data(data_dir, set_name, download_url, download_if_missing, force=force) + systems = resolve_systems(root_data, set_name, system, system_list, max_systems) + plan = plan_validation(set_name, root_data, systems, out_dir, n_runs, jobs, cpu_fraction) + out = Path(out_dir) + if dry_run or plan_only: + out.mkdir(parents=True, exist_ok=True) + (out / "validation_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8") + return {"dry_run": bool(dry_run), "plan": plan} + if out.exists() and force: + shutil.rmtree(out) + out.mkdir(parents=True, exist_ok=True) + resolved_jobs = int(plan["jobs"]) + rows: list[dict[str, object]] = [] + failures: list[dict[str, object]] = [] + metrics_by_system: list[dict[str, object]] = [] + per_system_jobs = resolved_jobs if len(systems) == 1 else 1 + system_order = {s.system_id: idx for idx, s in enumerate(systems)} + + def run_system(s: ValidationSystem) -> tuple[int, ValidationSystem, dict[str, object] | None, dict[str, object], Exception | None]: + run_root = out / s.system_id if len(systems) > 1 else out + try: + if set_name.lower() == "astex": + metrics = validate_astex_system(s, run_root, n_runs=n_runs, jobs=per_system_jobs, force=force) + row = { + "system_id": s.system_id, + "top1_rmsd": metrics.get("top1_rmsd"), + "best_of_n_rmsd": metrics.get("best_of_n_rmsd"), + "top1_SCORE": metrics.get("top1_SCORE"), + "success_top1_rmsd_le_2A": metrics.get("success_top1_rmsd_le_2A"), + "success_best_rmsd_le_2A": metrics.get("success_best_rmsd_le_2A"), + "n_poses": metrics.get("n_poses"), + "status": "success", + } + elif set_name.lower() == "dud": + metrics = validate_dud_system(s, run_root, n_runs=n_runs, jobs=per_system_jobs, force=force) + row = {"system_id": s.system_id, "status": "success", **metrics} + else: + raise RDockPipelineError(f"Unsupported validation set: {set_name}") + return system_order[s.system_id], s, metrics, row, None + except Exception as exc: + return system_order[s.system_id], s, None, {"system_id": s.system_id, "status": "failed", "error": str(exc)}, exc + + max_system_workers = min(resolved_jobs, len(systems)) + results: list[tuple[int, ValidationSystem, dict[str, object] | None, dict[str, object], Exception | None]] = [] + if max_system_workers > 1: + with ThreadPoolExecutor(max_workers=max_system_workers) as pool: + futures = [pool.submit(run_system, s) for s in systems] + for fut in as_completed(futures): + results.append(fut.result()) + else: + results = [run_system(s) for s in systems] + + for _, s, metrics, row, exc in sorted(results, key=lambda item: item[0]): + rows.append(row) + if exc is not None: + failures.append({"system_id": s.system_id, "error": str(exc)}) + continue + if metrics is not None: + metrics_by_system.append({"system_id": s.system_id, **metrics}) + + # Per-system outputs are written by each worker. The root directory stores + # aggregate summaries, plots, manifests, and reports. + _empty_standard_outputs(out) + _write_csv(out / "tables" / f"{set_name.lower()}_system_summary.csv", rows) + if set_name.lower() == "astex": + top1 = [float(r["top1_rmsd"]) for r in rows if r.get("status") == "success"] + best_vals = [float(r["best_of_n_rmsd"]) for r in rows if r.get("status") == "success"] + aggregate = { + "n_systems_total": len(systems), + "n_systems_successful": len(top1), + "n_systems_failed": len(failures), + "median_top1_rmsd": median(top1) if top1 else None, + "median_best_rmsd": median(best_vals) if best_vals else None, + "success_top1_rmsd_le_2A": sum(1 for x in top1 if x <= 2.0), + "success_best_rmsd_le_2A": sum(1 for x in best_vals if x <= 2.0), + "n_poses_total": sum(int(r.get("n_poses", 0) or 0) for r in rows), + "failures": failures, + } + plots = plot_astex_outputs(out / "tables" / f"{set_name.lower()}_system_summary.csv", out / "plots") + else: + aggregate = { + "n_systems_total": len(systems), + "n_systems_successful": len(metrics_by_system), + "n_systems_failed": len(failures), + "failures": failures, + } + plots = [] + (out / "metrics" / "validation_metrics.json").write_text(json.dumps(aggregate, indent=2), encoding="utf-8") + _write_validation_report(out, set_name.upper(), systems, [], aggregate, plots) + return {"metrics": aggregate, "systems": rows} + + +def validate_astex(data_dir: str | Path, system: str, out_dir: str | Path, n_runs: int = 100, jobs: int | str = 1) -> dict[str, object]: + result = validate_many("astex", data_dir, out_dir, system=system, n_runs=n_runs, jobs=jobs) + return dict(result.get("metrics", {})) + + +def validate_dud(data_dir: str | Path, system: str, out_dir: str | Path, n_runs: int = 100, jobs: int | str = 1) -> dict[str, object]: + result = validate_many("dud", data_dir, out_dir, system=system, n_runs=n_runs, jobs=jobs) + return dict(result.get("metrics", {})) + + +def _write_validation_report( + root: Path, + set_name: str, + systems: list[ValidationSystem], + commands: list[CommandRecord], + metrics: dict[str, object], + plots: list[str], +) -> None: + manifest = { + "validation_set": set_name, + "engine": "real-rdock-official-workflow", + "systems": [asdict(s) for s in systems], + "commands": [c.to_dict() for c in commands], + "metrics": metrics, + "plots": plots, + "artifacts": { + "report": str(root / "report.md"), + "manifest": str(root / "manifest.json"), + "config": str(root / "config.yaml"), + "commands": str(root / "commands.log"), + "tables": str(root / "tables"), + "metrics": str(root / "metrics"), + "plots": str(root / "plots"), + }, + } + (root / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") + (root / "config.yaml").write_text(f"validation_set: {set_name}\nsystems: {[s.system_id for s in systems]}\n", encoding="utf-8") + top_lines = [] + for item in list(metrics.items())[:20]: + top_lines.append(f"- {item[0]}: `{item[1]}`") + plot_lines = [f"- `{p}`" for p in plots] or ["- No plots generated; see `plots/skipped_plots.json` if present."] + (root / "report.md").write_text( + "\n".join( + [ + f"# {set_name} rDock Validation", + "", + "## Input Summary", + f"- Systems: `{', '.join(s.system_id for s in systems)}`", + f"- System count: `{len(systems)}`", + "", + "## Metrics", + *top_lines, + "", + "## Commands", + f"- Command log: `{root / 'commands.log'}`", + "- Per-system command logs are stored under each system run directory for multi-system runs.", + "", + "## Plots", + *plot_lines, + "", + "## Skipped Steps", + "- Browser bundle export was removed from the production pipeline.", + "- No mock docking or surrogate scores are used.", + "", + "## Diagnostics", + f"- Failures: `{json.dumps(metrics.get('failures', []))}`", + ] + ), + encoding="utf-8", + ) diff --git a/environment.yml b/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..1520a51e29a27c456dde9004f3697a74a8e4d6bf --- /dev/null +++ b/environment.yml @@ -0,0 +1,12 @@ +name: portable-rdock-pipeline +channels: + - conda-forge +dependencies: + - python=3.11 + - pip + - numpy + - pandas + - matplotlib + - pyyaml + - rdkit + - requests diff --git a/libs/__init__.py b/libs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e08503c93d89f68d3bdcd172c71824e103afd605 --- /dev/null +++ b/libs/__init__.py @@ -0,0 +1 @@ +"""Top-level package for modular docking pipeline libraries.""" diff --git a/libs/adaptive/__init__.py b/libs/adaptive/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab5e40de07ba26e632c0bbc98366ed0bdead055 --- /dev/null +++ b/libs/adaptive/__init__.py @@ -0,0 +1,19 @@ +"""Adaptive scheduling, clustering, and surrogate learning components.""" + +from .clustering import cluster_ligands_butina +from .epsilon_regret import EpsilonRegretConfig, EpsilonRegretController +from .hyperclustering import hypercluster_representatives +from .scheduler import AdaptiveScheduler +from .surrogate_model import SurrogateModel +from .thresholding import DynamicEarlyStopController, DynamicThresholdConfig + +__all__ = [ + "AdaptiveScheduler", + "DynamicEarlyStopController", + "DynamicThresholdConfig", + "EpsilonRegretConfig", + "EpsilonRegretController", + "SurrogateModel", + "cluster_ligands_butina", + "hypercluster_representatives", +] diff --git a/libs/adaptive/clustering.py b/libs/adaptive/clustering.py new file mode 100644 index 0000000000000000000000000000000000000000..84664af9735a474f25101c48e0afcec75f2a5f5f --- /dev/null +++ b/libs/adaptive/clustering.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import Dict, Iterable, List, Sequence + +import numpy as np +from rdkit import DataStructs +from rdkit.Chem import rdchem +from rdkit.ML.Cluster import Butina + + +def _np_to_explicit_bitvect(fp: np.ndarray) -> DataStructs.ExplicitBitVect: + bitvect = DataStructs.ExplicitBitVect(fp.shape[0]) + on_bits = np.where(fp > 0)[0] + for idx in on_bits: + bitvect.SetBit(int(idx)) + return bitvect + + +def cluster_ligands_butina( + ligand_ids: Sequence[str], + fingerprints: Sequence[np.ndarray], + cutoff: float = 0.35, +) -> Dict[str, int]: + """Cluster ligands with Butina on Tanimoto distance over Morgan fingerprints.""" + if not ligand_ids: + return {} + if len(ligand_ids) != len(fingerprints): + raise ValueError("ligand_ids and fingerprints must have same length") + + fp_bv = [_np_to_explicit_bitvect(np.asarray(fp, dtype=int)) for fp in fingerprints] + + dists: List[float] = [] + for i in range(1, len(fp_bv)): + sims = DataStructs.BulkTanimotoSimilarity(fp_bv[i], fp_bv[:i]) + dists.extend([1.0 - x for x in sims]) + + clusters = Butina.ClusterData(dists, len(fp_bv), cutoff, isDistData=True) + + mapping: Dict[str, int] = {} + for c_idx, cluster in enumerate(clusters): + for member in cluster: + mapping[ligand_ids[member]] = c_idx + + # Ensure all ligands map to a cluster, even edge cases. + for idx, ligand_id in enumerate(ligand_ids): + mapping.setdefault(ligand_id, max(mapping.values(), default=-1) + idx + 1) + return mapping diff --git a/libs/adaptive/diversity.py b/libs/adaptive/diversity.py new file mode 100644 index 0000000000000000000000000000000000000000..522d78431f29a111baa1376a05116c8579df2107 --- /dev/null +++ b/libs/adaptive/diversity.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing import Iterable + +import numpy as np + + +def _tanimoto(fp_a: np.ndarray, fp_b: np.ndarray) -> float: + inter = float(np.sum((fp_a > 0) & (fp_b > 0))) + union = float(np.sum((fp_a > 0) | (fp_b > 0))) + if union == 0: + return 0.0 + return inter / union + + +def selection_diversity(fingerprints: Iterable[np.ndarray]) -> float: + fps = list(fingerprints) + if len(fps) < 2: + return 0.0 + distances = [] + for i in range(len(fps)): + for j in range(i + 1, len(fps)): + distances.append(1.0 - _tanimoto(fps[i], fps[j])) + return float(np.mean(distances)) if distances else 0.0 diff --git a/libs/adaptive/epsilon_regret.py b/libs/adaptive/epsilon_regret.py new file mode 100644 index 0000000000000000000000000000000000000000..7104c0bd33f5e98f96a8464b1e23de6aa6a1f99e --- /dev/null +++ b/libs/adaptive/epsilon_regret.py @@ -0,0 +1,160 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, Iterable, List, Sequence + +import numpy as np + + +@dataclass +class EpsilonRegretConfig: + epsilon_quality: float = 0.10 + acceptable_regret: float = 0.10 + min_budget: int = 250 + max_budget: int = 10000 + min_model_weight: float = 0.25 + patience_rounds: int = 6 + min_improvement: float = 0.02 + uncertainty_multiplier: float = 0.50 + min_cluster_coverage: float = 0.20 + min_hypercluster_coverage: float = 0.20 + + +class EpsilonRegretController: + """ + Budget-aware stop controller with epsilon-regret semantics. + + Online intent: + stop when estimated remaining gain is small relative to current best score, + after minimum exploration and coverage constraints are satisfied. + """ + + def __init__(self, config: EpsilonRegretConfig | None = None) -> None: + self.config = config or EpsilonRegretConfig() + self.best_score = np.inf + self.stagnant_rounds = 0 + self.history: List[Dict[str, float | int | bool | str]] = [] + + @staticmethod + def _mean_or_nan(values: Sequence[float]) -> float: + arr = np.asarray(values, dtype=float) + if arr.size == 0: + return float("nan") + return float(np.nanmean(arr)) + + @staticmethod + def _estimate_remaining_gain( + best_score: float, + expected_remaining_scores: Iterable[float], + uncertainty_scores: Iterable[float], + uncertainty_multiplier: float, + ) -> float: + pred = np.asarray(list(expected_remaining_scores), dtype=float) + unc = np.asarray(list(uncertainty_scores), dtype=float) + if pred.size == 0: + return float("inf") + if unc.size != pred.size: + unc = np.full(pred.shape[0], np.nanmean(unc) if unc.size else 1.0, dtype=float) + optimistic = pred - float(max(0.0, uncertainty_multiplier)) * np.abs(unc) + optimistic_best = float(np.nanmin(optimistic)) if np.isfinite(optimistic).any() else float(np.nanmin(pred)) + if not np.isfinite(optimistic_best) or not np.isfinite(best_score): + return float("inf") + # lower score is better + return float(max(0.0, best_score - optimistic_best)) + + def update( + self, + *, + round_idx: int, + n_evaluated: int, + best_score_now: float, + recent_scores: Sequence[float], + model_weight: float, + cluster_coverage: float, + hypercluster_coverage: float, + expected_remaining_scores: Iterable[float], + uncertainty_scores: Iterable[float], + time_importance: float, + budget_cap: int, + ) -> Dict[str, float | int | bool | str]: + cfg = self.config + ti = float(max(0.0, min(1.0, float(time_importance)))) + + if np.isfinite(self.best_score): + improvement = float(self.best_score - best_score_now) + else: + improvement = float("inf") + + if improvement > float(cfg.min_improvement): + self.stagnant_rounds = 0 + else: + self.stagnant_rounds += 1 + self.best_score = min(float(self.best_score), float(best_score_now)) + + epsilon_rel = float(max(cfg.epsilon_quality, cfg.acceptable_regret)) + # Higher time importance permits slightly larger acceptable residual gain. + epsilon_rel *= float(1.0 + 0.5 * ti) + epsilon_abs = float(epsilon_rel * max(1.0, abs(float(self.best_score)))) + + remaining_gain = self._estimate_remaining_gain( + best_score=float(self.best_score), + expected_remaining_scores=expected_remaining_scores, + uncertainty_scores=uncertainty_scores, + uncertainty_multiplier=float(cfg.uncertainty_multiplier), + ) + regret_ratio_proxy = float(remaining_gain / max(1.0, abs(float(self.best_score)))) + + budget_floor = int(max(1, cfg.min_budget)) + budget_ceiling = int(min(cfg.max_budget, budget_cap)) + budget_ready = int(n_evaluated) >= budget_floor + model_ready = float(model_weight) >= float(cfg.min_model_weight) + coverage_ready = bool( + float(cluster_coverage) >= float(cfg.min_cluster_coverage) + and float(hypercluster_coverage) >= float(cfg.min_hypercluster_coverage) + ) + stagnation_ready = int(self.stagnant_rounds) >= int(cfg.patience_rounds) + + hit_budget_ceiling = int(n_evaluated) >= int(budget_ceiling) + epsilon_ready = bool(np.isfinite(remaining_gain) and remaining_gain <= epsilon_abs) + stop = bool(hit_budget_ceiling or (budget_ready and model_ready and coverage_ready and stagnation_ready and epsilon_ready)) + + if hit_budget_ceiling: + reason = "max_budget_reached" + elif not budget_ready: + reason = "below_min_budget" + elif not model_ready: + reason = "model_not_ready" + elif not coverage_ready: + reason = "coverage_not_ready" + elif not stagnation_ready: + reason = "insufficient_stagnation_evidence" + elif not epsilon_ready: + reason = "remaining_gain_above_epsilon" + else: + reason = "epsilon_regret_stop" + + rec = { + "round_idx": int(round_idx), + "n_evaluated": int(n_evaluated), + "best_score": float(self.best_score), + "recent_mean_score": self._mean_or_nan(recent_scores), + "model_weight": float(model_weight), + "cluster_coverage": float(cluster_coverage), + "hypercluster_coverage": float(hypercluster_coverage), + "stagnant_rounds": int(self.stagnant_rounds), + "epsilon_abs": float(epsilon_abs), + "estimated_remaining_gain": float(remaining_gain), + "regret_ratio_proxy": float(regret_ratio_proxy), + "budget_floor": int(budget_floor), + "budget_ceiling": int(budget_ceiling), + "budget_ready": bool(budget_ready), + "model_ready": bool(model_ready), + "coverage_ready": bool(coverage_ready), + "stagnation_ready": bool(stagnation_ready), + "epsilon_ready": bool(epsilon_ready), + "stop": bool(stop), + "reason": reason, + } + self.history.append(rec) + return rec + diff --git a/libs/adaptive/features.py b/libs/adaptive/features.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7496ff5ce96c1f1b91af94fc92ccd30480a257 --- /dev/null +++ b/libs/adaptive/features.py @@ -0,0 +1,408 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, Iterable, List, Tuple + +import numpy as np +import pandas as pd +from rdkit import Chem +from rdkit.Chem import AllChem, Descriptors, Lipinski, MolSurf, rdMolDescriptors +from rdkit.Chem.Scaffolds import MurckoScaffold +from rdkit.DataStructs import TanimotoSimilarity + +try: + from rdkit.Chem import rdFreeSASA +except Exception: # pragma: no cover + rdFreeSASA = None # type: ignore[assignment] + + +@dataclass +class FeatureValue: + value: float | None + available: bool + source: str + feature_type: str + + +@dataclass +class FeatureBundle: + object_id: str + features: Dict[str, FeatureValue] + + def to_records(self, channel: str, round_idx: int | None = None) -> List[dict]: + rows: List[dict] = [] + for name, fv in sorted(self.features.items()): + rows.append( + { + "object_id": self.object_id, + "round": round_idx, + "channel": channel, + "feature_name": name, + "value": fv.value, + "available": bool(fv.available), + "source": fv.source, + "feature_type": fv.feature_type, + } + ) + return rows + + +def _fv(value: float | None, available: bool, source: str, feature_type: str) -> FeatureValue: + return FeatureValue(value=value, available=available, source=source, feature_type=feature_type) + + +def _safe_float(value: float | int | None) -> float | None: + if value is None: + return None + try: + v = float(value) + except Exception: + return None + if not np.isfinite(v): + return None + return v + + +def _compute_ligand_sasa(mol: Chem.Mol) -> Tuple[float | None, bool]: + if rdFreeSASA is None: + return None, False + try: + if mol.GetNumConformers() == 0: + m = Chem.AddHs(Chem.Mol(mol)) + status = AllChem.EmbedMolecule(m, AllChem.ETKDGv3()) + if int(status) != 0: + return None, False + else: + m = Chem.Mol(mol) + + if m.GetNumConformers() == 0: + return None, False + + radii = rdFreeSASA.classifyAtoms(m) + sasa = rdFreeSASA.CalcSASA(m, radii) + return _safe_float(sasa), True + except Exception: + return None, False + + +def build_ligand_feature_bundle( + ligand_id: str, + smiles: str, + fingerprint: np.ndarray, + reference_mol: Chem.Mol | None = None, + compute_partial_charges: bool = True, + compute_sasa: bool = True, +) -> FeatureBundle: + mol = Chem.MolFromSmiles(smiles) + if mol is None: + raise ValueError(f"Invalid SMILES for ligand {ligand_id}: {smiles}") + + m_h = Chem.AddHs(Chem.Mol(mol)) + if compute_partial_charges: + try: + AllChem.ComputeGasteigerCharges(m_h) + partial_charges = [] + for atom in m_h.GetAtoms(): + prop = atom.GetProp("_GasteigerCharge") if atom.HasProp("_GasteigerCharge") else "nan" + try: + q = float(prop) + except Exception: + continue + if np.isfinite(q): + partial_charges.append(q) + if partial_charges: + mean_abs_q = float(np.mean(np.abs(partial_charges))) + total_q = float(np.sum(partial_charges)) + has_q = True + else: + mean_abs_q = None + total_q = None + has_q = False + except Exception: + mean_abs_q = None + total_q = None + has_q = False + else: + mean_abs_q = None + total_q = None + has_q = False + + aromatic_rings = rdMolDescriptors.CalcNumAromaticRings(mol) + formal_charge = Chem.GetFormalCharge(mol) + heavy_atoms = mol.GetNumHeavyAtoms() + frac_csp3 = rdMolDescriptors.CalcFractionCSP3(mol) + bertz_ct = Descriptors.BertzCT(mol) + balaban_j = Descriptors.BalabanJ(mol) + topological_complexity = rdMolDescriptors.CalcChi0v(mol) + + if compute_sasa: + ligand_sasa, has_sasa = _compute_ligand_sasa(m_h) + else: + ligand_sasa, has_sasa = None, False + + reference_similarity = None + scaffold_match = None + chemical_distance = None + if reference_mol is not None: + fp_gen = AllChem.GetMorganGenerator(radius=2, fpSize=int(fingerprint.shape[0])) + ref_fp = fp_gen.GetFingerprint(reference_mol) + lig_fp = fp_gen.GetFingerprint(mol) + sim = TanimotoSimilarity(ref_fp, lig_fp) + reference_similarity = float(sim) + chemical_distance = float(1.0 - sim) + + ref_scaffold = MurckoScaffold.MurckoScaffoldSmiles(mol=reference_mol) + lig_scaffold = MurckoScaffold.MurckoScaffoldSmiles(mol=mol) + scaffold_match = float(ref_scaffold == lig_scaffold) + + features: Dict[str, FeatureValue] = { + "ligand_mw": _fv(_safe_float(Descriptors.MolWt(mol)), True, "rdkit", "exact"), + "ligand_logp": _fv(_safe_float(Descriptors.MolLogP(mol)), True, "rdkit", "exact"), + "ligand_tpsa": _fv(_safe_float(MolSurf.TPSA(mol)), True, "rdkit", "exact"), + "ligand_hbd": _fv(_safe_float(Lipinski.NumHDonors(mol)), True, "rdkit", "exact"), + "ligand_hba": _fv(_safe_float(Lipinski.NumHAcceptors(mol)), True, "rdkit", "exact"), + "ligand_rotatable_bonds": _fv(_safe_float(Lipinski.NumRotatableBonds(mol)), True, "rdkit", "exact"), + "ligand_aromatic_ring_count": _fv(_safe_float(aromatic_rings), True, "rdkit", "exact"), + "ligand_formal_charge": _fv(_safe_float(formal_charge), True, "rdkit", "exact"), + "ligand_partial_charge_abs_mean": _fv(mean_abs_q, has_q, "rdkit", "approximate"), + "ligand_partial_charge_total": _fv(total_q, has_q, "rdkit", "approximate"), + "ligand_topological_bertz": _fv(_safe_float(bertz_ct), True, "rdkit", "exact"), + "ligand_topological_balaban_j": _fv(_safe_float(balaban_j), True, "rdkit", "exact"), + "ligand_topological_chi0v": _fv(_safe_float(topological_complexity), True, "rdkit", "exact"), + "ligand_fraction_csp3": _fv(_safe_float(frac_csp3), True, "rdkit", "exact"), + "ligand_heavy_atom_count": _fv(_safe_float(heavy_atoms), True, "rdkit", "exact"), + "ligand_sasa": _fv(ligand_sasa, has_sasa, "geometric", "approximate"), + "similarity_to_reference": _fv(reference_similarity, reference_similarity is not None, "rdkit", "exact"), + "scaffold_match": _fv(scaffold_match, scaffold_match is not None, "rdkit", "exact"), + "chemical_distance_to_reference": _fv(chemical_distance, chemical_distance is not None, "rdkit", "exact"), + } + + for i, bit in enumerate(fingerprint.astype(float).tolist()): + features[f"morgan_fp_{i:04d}"] = _fv(float(bit), True, "rdkit", "exact") + + return FeatureBundle(object_id=ligand_id, features=features) + + +def build_protein_feature_bundle(target_id: str, sequence_features: Dict[str, float], structure_features: Dict[str, float]) -> FeatureBundle: + seq_len = float(sequence_features.get("seq_length", 1.0) or 1.0) + hydrophobic = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["A", "V", "I", "L", "M", "F", "W", "Y"]) + charged = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["K", "R", "H", "D", "E"]) + polar = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["S", "T", "N", "Q", "C"]) + + residue_count = float(structure_features.get("residue_count", 0.0)) + mean_extent = float(structure_features.get("mean_spatial_extent", 0.0)) + pocket_residues = float(structure_features.get("pocket_residue_count", 0.0)) + + approx_volume = float(max(0.0, mean_extent**3)) + pocket_coverage = float(pocket_residues / max(residue_count, 1.0)) + + features = { + "pocket_hydrophobic_fraction": _fv(hydrophobic, True, "protein", "exact"), + "pocket_charged_fraction": _fv(charged, True, "protein", "exact"), + "pocket_polar_fraction": _fv(polar, True, "protein", "exact"), + "pocket_residue_count": _fv(residue_count, True, "protein", "exact"), + "pocket_volume_approx": _fv(approx_volume, True, "geometric", "approximate"), + "pocket_coverage_fraction": _fv(pocket_coverage, True, "geometric", "approximate"), + "pocket_sequence_length": _fv(seq_len, True, "protein", "exact"), + } + return FeatureBundle(object_id=target_id, features=features) + + +def build_complex_feature_bundle( + ligand_id: str, + docking_score: float, + interface_features: Dict[str, float], + ligand_bundle: FeatureBundle, + protein_bundle: FeatureBundle, +) -> FeatureBundle: + lig = ligand_bundle.features + prot = protein_bundle.features + + logp = lig.get("ligand_logp", _fv(None, False, "rdkit", "exact")).value or 0.0 + tpsa = lig.get("ligand_tpsa", _fv(None, False, "rdkit", "exact")).value or 0.0 + charge_mag = lig.get("ligand_partial_charge_abs_mean", _fv(None, False, "rdkit", "approximate")).value + heavy_atoms = lig.get("ligand_heavy_atom_count", _fv(None, False, "rdkit", "exact")).value or 1.0 + pocket_volume = prot.get("pocket_volume_approx", _fv(None, False, "geometric", "approximate")).value or 1.0 + pocket_hydrophobic = prot.get("pocket_hydrophobic_fraction", _fv(None, False, "protein", "exact")).value or 0.0 + + interface_contact_proxy = float(interface_features.get("interface_contact_proxy", max(0.0, -docking_score / 8.0))) + hbond_proxy = float(interface_features.get("hbond_proxy", max(0.0, tpsa / 100.0))) + shape_proxy = float(interface_features.get("shape_proxy", max(0.0, 1.0 / (1.0 + abs(docking_score))))) + + contact_count = max(1.0, heavy_atoms * (0.3 + interface_contact_proxy)) + polar_contacts = contact_count * min(1.0, tpsa / 120.0) + hydrophobic_contacts = contact_count * min(1.0, max(0.0, logp) / 6.0) * (0.5 + pocket_hydrophobic) + clash_count = max(0.0, docking_score - 9.0) + min_distance = max(1.5, 6.0 - interface_contact_proxy) + pocket_coverage = min(1.0, contact_count / max(10.0, pocket_volume / 20.0)) + interaction_density = contact_count / max(1.0, pocket_volume) + + ligand_sasa = lig.get("ligand_sasa", _fv(None, False, "geometric", "approximate")).value + protein_sasa = pocket_volume * 0.75 + if ligand_sasa is not None: + complex_sasa = max(1.0, protein_sasa + ligand_sasa - 0.5 * contact_count) + buried_sasa = max(0.0, protein_sasa + ligand_sasa - complex_sasa) + burial_ratio = buried_sasa / max(ligand_sasa, 1e-6) + sasa_available = True + else: + complex_sasa = None + buried_sasa = None + burial_ratio = None + sasa_available = False + + if charge_mag is not None: + electrostatic_proxy = -charge_mag * max(0.5, 5.0 - min_distance) + electro_available = True + else: + electrostatic_proxy = None + electro_available = False + + contact_energy = -0.15 * contact_count + steric_penalty = 0.6 * clash_count + hydrophobic_proxy = -0.1 * hydrophobic_contacts + interaction_decomp = contact_energy + hydrophobic_proxy + (electrostatic_proxy or 0.0) + steric_penalty + + features = { + "complex_contact_count": _fv(float(contact_count), True, "interaction", "proxy"), + "complex_hbond_proxy": _fv(float(hbond_proxy), True, "interaction", "proxy"), + "complex_polar_contact_count": _fv(float(polar_contacts), True, "interaction", "proxy"), + "complex_hydrophobic_contact_proxy": _fv(float(hydrophobic_contacts), True, "interaction", "proxy"), + "complex_clash_count": _fv(float(clash_count), True, "interaction", "proxy"), + "complex_min_distance": _fv(float(min_distance), True, "geometric", "approximate"), + "complex_pocket_coverage": _fv(float(pocket_coverage), True, "interaction", "proxy"), + "complex_interaction_density": _fv(float(interaction_density), True, "interaction", "proxy"), + "complex_ligand_sasa": _fv(_safe_float(ligand_sasa), ligand_sasa is not None, "geometric", "approximate"), + "complex_protein_sasa": _fv(_safe_float(protein_sasa), True, "geometric", "approximate"), + "complex_sasa": _fv(_safe_float(complex_sasa), sasa_available, "geometric", "approximate"), + "complex_buried_sasa": _fv(_safe_float(buried_sasa), sasa_available, "geometric", "approximate"), + "complex_shape_complementarity": _fv(float(shape_proxy), True, "geometric", "proxy"), + "complex_ligand_burial_ratio": _fv(_safe_float(burial_ratio), sasa_available, "geometric", "approximate"), + "energy_contact_proxy": _fv(float(contact_energy), True, "energy_proxy", "proxy"), + "energy_electrostatic_proxy": _fv(_safe_float(electrostatic_proxy), electro_available, "energy_proxy", "proxy"), + "energy_steric_clash_penalty": _fv(float(steric_penalty), True, "energy_proxy", "proxy"), + "energy_hydrophobic_proxy": _fv(float(hydrophobic_proxy), True, "energy_proxy", "proxy"), + "energy_interaction_decomposition": _fv(float(interaction_decomp), True, "energy_proxy", "proxy"), + } + + return FeatureBundle(object_id=ligand_id, features=features) + + +def build_rdock_feature_bundle( + ligand_id: str, + parsed_row: Dict[str, float | int | str | bool | None], +) -> FeatureBundle: + """Build a feature bundle from rDock-native and rDock-derived per-ligand outputs.""" + + def _as_feature( + key: str, + source: str, + ftype: str, + ) -> FeatureValue: + value = _safe_float(parsed_row.get(key)) # type: ignore[arg-type] + return _fv(value, value is not None, source, ftype if value is not None else "unavailable") + + features: Dict[str, FeatureValue] = { + "rdock_total_score": _as_feature("rdock_total_score", "rdock_native", "exact"), + "rdock_pose_rank": _as_feature("rdock_pose_rank", "rdock_native", "exact"), + "n_generated_poses": _as_feature("n_generated_poses", "rdock_native", "exact"), + "best_pose_score": _as_feature("best_pose_score", "rdock_native", "exact"), + "mean_top3_pose_score": _as_feature("mean_top3_pose_score", "rdock_native", "exact"), + "mean_top5_pose_score": _as_feature("mean_top5_pose_score", "rdock_native", "exact"), + "std_top5_pose_score": _as_feature("std_top5_pose_score", "rdock_native", "exact"), + "pose_score_gap_1_2": _as_feature("pose_score_gap_1_2", "rdock_native", "exact"), + "rdock_restraint_term": _as_feature("rdock_restraint_term", "rdock_native", "exact"), + "rdock_internal_ligand_term": _as_feature("rdock_internal_ligand_term", "rdock_native", "exact"), + "rdock_polar_term": _as_feature("rdock_polar_term", "rdock_native", "exact"), + "rdock_vdw_term": _as_feature("rdock_vdw_term", "rdock_native", "exact"), + "top_pose_rmsd_consistency": _as_feature("top_pose_rmsd_consistency", "rdock_derived", "proxy"), + "contact_overlap_consistency": _as_feature("contact_overlap_consistency", "rdock_derived", "proxy"), + "hotspot_contact_frequency": _as_feature("hotspot_contact_frequency", "rdock_derived", "proxy"), + "subpocket_match_score": _as_feature("subpocket_match_score", "rdock_derived", "proxy"), + "replicate_mean_score": _as_feature("replicate_mean_score", "rdock_derived", "proxy"), + "replicate_score_variance": _as_feature("replicate_score_variance", "rdock_derived", "proxy"), + "replicate_consensus_score": _as_feature("replicate_consensus_score", "rdock_derived", "proxy"), + } + return FeatureBundle(object_id=ligand_id, features=features) + + +def merge_bundles(object_id: str, bundles: Iterable[FeatureBundle]) -> FeatureBundle: + merged: Dict[str, FeatureValue] = {} + for bundle in bundles: + merged.update(bundle.features) + return FeatureBundle(object_id=object_id, features=merged) + + +def bundles_to_wide_frames( + bundles: List[FeatureBundle], + ordered_feature_names: List[str] | None = None, +) -> Tuple[pd.DataFrame, pd.DataFrame, List[str]]: + if not bundles: + return pd.DataFrame(), pd.DataFrame(), [] + + if ordered_feature_names is None: + feature_set = set() + for bundle in bundles: + feature_set.update(bundle.features.keys()) + ordered_feature_names = sorted(feature_set) + + value_rows = [] + mask_rows = [] + for bundle in bundles: + vrow = {"ligand_id": bundle.object_id} + mrow = {"ligand_id": bundle.object_id} + for name in ordered_feature_names: + fv = bundle.features.get(name) + if fv is None or not fv.available or fv.value is None: + vrow[name] = np.nan + mrow[f"mask_{name}"] = 0 + else: + vrow[name] = float(fv.value) + mrow[f"mask_{name}"] = 1 + value_rows.append(vrow) + mask_rows.append(mrow) + + return pd.DataFrame(value_rows), pd.DataFrame(mask_rows), ordered_feature_names + + +def compute_feature_diagnostics(values_df: pd.DataFrame, masks_df: pd.DataFrame, target: pd.Series | None = None) -> pd.DataFrame: + if values_df.empty: + return pd.DataFrame(columns=["feature", "missing_frac", "mean", "std", "min", "max", "is_constant", "corr_to_target"]) + + numeric_cols = [c for c in values_df.columns if c != "ligand_id"] + rows = [] + for col in numeric_cols: + vals = pd.to_numeric(values_df[col], errors="coerce") + mask_col = f"mask_{col}" + if mask_col in masks_df.columns: + missing_frac = 1.0 - float(pd.to_numeric(masks_df[mask_col], errors="coerce").mean()) + else: + missing_frac = float(vals.isna().mean()) + + finite_vals = vals[np.isfinite(vals)] + is_constant = finite_vals.nunique(dropna=True) <= 1 if not finite_vals.empty else True + + if target is not None and len(target) == len(vals): + target_num = pd.to_numeric(target, errors="coerce") + paired = pd.concat([vals, target_num], axis=1).dropna() + if paired.shape[0] >= 3 and paired.iloc[:, 0].nunique(dropna=True) > 1 and paired.iloc[:, 1].nunique(dropna=True) > 1: + corr = paired.iloc[:, 0].corr(paired.iloc[:, 1]) + corr_val = float(corr) if corr is not None and np.isfinite(corr) else np.nan + else: + corr_val = np.nan + else: + corr_val = np.nan + + rows.append( + { + "feature": col, + "missing_frac": float(missing_frac), + "mean": float(finite_vals.mean()) if not finite_vals.empty else np.nan, + "std": float(finite_vals.std()) if not finite_vals.empty else np.nan, + "min": float(finite_vals.min()) if not finite_vals.empty else np.nan, + "max": float(finite_vals.max()) if not finite_vals.empty else np.nan, + "is_constant": bool(is_constant), + "corr_to_target": corr_val, + } + ) + + return pd.DataFrame(rows).sort_values(["missing_frac", "feature"], ascending=[False, True]).reset_index(drop=True) diff --git a/libs/adaptive/hyperclustering.py b/libs/adaptive/hyperclustering.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1bb64fa188f23cb173a71c8fb84cfe3a7a63c7 --- /dev/null +++ b/libs/adaptive/hyperclustering.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from typing import Dict, Sequence + +import numpy as np +from sklearn.cluster import AgglomerativeClustering + + +def hypercluster_representatives( + cluster_vectors: Dict[int, np.ndarray], + n_hyperclusters: int | None = None, +) -> Dict[int, int]: + """Agglomerative clustering over cluster representative vectors.""" + if not cluster_vectors: + return {} + + cluster_ids = sorted(cluster_vectors) + x = np.vstack([cluster_vectors[cid] for cid in cluster_ids]) + + if len(cluster_ids) == 1: + return {cluster_ids[0]: 0} + + n_clusters = n_hyperclusters or max(2, int(np.sqrt(len(cluster_ids)))) + n_clusters = min(n_clusters, len(cluster_ids)) + + model = AgglomerativeClustering(n_clusters=n_clusters) + labels = model.fit_predict(x) + return {cluster_id: int(label) for cluster_id, label in zip(cluster_ids, labels)} diff --git a/libs/adaptive/metrics.py b/libs/adaptive/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..7b4ebf86dfffc840ba45fbcbdea7695b63dba424 --- /dev/null +++ b/libs/adaptive/metrics.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from typing import Dict, Iterable, Sequence + +import numpy as np + +from .diversity import selection_diversity + + +def clustering_metrics(cluster_map: Dict[str, int], hypercluster_map: Dict[int, int]) -> Dict[str, float]: + return { + "ligand_count": float(len(cluster_map)), + "cluster_count": float(len(set(cluster_map.values())) if cluster_map else 0), + "hypercluster_count": float(len(set(hypercluster_map.values())) if hypercluster_map else 0), + } + + +def score_metrics(scores: Sequence[float]) -> Dict[str, float]: + if not scores: + return { + "evaluated_ligand_count": 0.0, + "mean_score": 0.0, + "best_score": 0.0, + } + arr = np.asarray(scores, dtype=float) + return { + "evaluated_ligand_count": float(arr.size), + "mean_score": float(np.mean(arr)), + "best_score": float(np.min(arr)), + } + + +def enrichment_metrics(scores: Sequence[float], labels: Sequence[int] | None, topk: int = 10) -> Dict[str, float]: + if labels is None or not scores or len(labels) != len(scores): + return {"topk_hit_rate": 0.0, "enrichment_like": 0.0} + + idx_sorted = np.argsort(np.asarray(scores, dtype=float)) + labels_arr = np.asarray(labels, dtype=int) + k = min(topk, len(idx_sorted)) + top_hits = int(np.sum(labels_arr[idx_sorted[:k]])) + baseline = float(np.mean(labels_arr)) if labels_arr.size else 0.0 + hit_rate = top_hits / max(k, 1) + enrichment = (hit_rate / baseline) if baseline > 0 else 0.0 + return {"topk_hit_rate": float(hit_rate), "enrichment_like": float(enrichment)} + + +def diversity_metric(selected_fingerprints: Iterable[np.ndarray]) -> Dict[str, float]: + return {"selection_diversity": selection_diversity(selected_fingerprints)} diff --git a/libs/adaptive/policies.py b/libs/adaptive/policies.py new file mode 100644 index 0000000000000000000000000000000000000000..87086ebc6500a1598d93d6f8a36aba947c6001b7 --- /dev/null +++ b/libs/adaptive/policies.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass +class PrioritizationPolicy: + utility_weight: float = 0.55 + uncertainty_weight: float = 0.2 + diversity_weight: float = 0.15 + cluster_bonus_weight: float = 0.1 + conservative_deprioritize_quantile: float = 0.15 diff --git a/libs/adaptive/prioritization.py b/libs/adaptive/prioritization.py new file mode 100644 index 0000000000000000000000000000000000000000..8483f1cf8a4aff077a826edfa6f26cb8b10ac602 --- /dev/null +++ b/libs/adaptive/prioritization.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +from typing import Dict + +from .policies import PrioritizationPolicy + + +def compute_priority( + predicted_utility: float, + uncertainty: float, + diversity_gain: float, + cluster_bonus: float, + policy: PrioritizationPolicy, +) -> float: + """Weighted priority function used by adaptive queueing.""" + return ( + policy.utility_weight * predicted_utility + + policy.uncertainty_weight * uncertainty + + policy.diversity_weight * diversity_gain + + policy.cluster_bonus_weight * cluster_bonus + ) + + +def cluster_bonus(cluster_load: Dict[int, int], cluster_id: int) -> float: + load = cluster_load.get(cluster_id, 0) + return 1.0 / (1.0 + float(load)) diff --git a/libs/adaptive/queue_manager.py b/libs/adaptive/queue_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..722a0c1877c1a2345b90877a6e8d178364ec7eeb --- /dev/null +++ b/libs/adaptive/queue_manager.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, Iterable, List + +from .state import QueueItem + +VALID_STATUSES = {"active", "deprioritized", "frozen", "completed"} + + +@dataclass +class QueueManager: + items: Dict[str, QueueItem] + + @classmethod + def from_items(cls, items: Iterable[QueueItem]) -> "QueueManager": + return cls(items={item.ligand_id: item for item in items}) + + def set_status(self, ligand_id: str, status: str) -> None: + if status not in VALID_STATUSES: + raise ValueError(f"Invalid status: {status}") + self.items[ligand_id].status = status + + def active_items(self) -> List[QueueItem]: + return [item for item in self.items.values() if item.status == "active"] + + def completed_items(self) -> List[QueueItem]: + return [item for item in self.items.values() if item.status == "completed"] + + def ordered_active(self) -> List[QueueItem]: + return sorted(self.active_items(), key=lambda item: item.priority, reverse=True) diff --git a/libs/adaptive/scheduler.py b/libs/adaptive/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..38441c8aae33fecea9e0482d1fb9c0f6cded7718 --- /dev/null +++ b/libs/adaptive/scheduler.py @@ -0,0 +1,253 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List + +import numpy as np +import pandas as pd + +from .metrics import score_metrics +from .policies import PrioritizationPolicy +from .prioritization import cluster_bonus, compute_priority +from .queue_manager import QueueManager +from .state import QueueItem, SchedulerState +from .surrogate_model import SurrogateConfig, SurrogateModel +from .weight_schedule import WeightScheduleConfig, compute_model_weight + + +@dataclass +class SchedulerConfig: + batch_size: int = 8 + init_coverage_fraction: float = 0.25 + conservative_deprioritize: bool = True + state_path: str = "results/state.json" + weight_schedule: WeightScheduleConfig = field(default_factory=WeightScheduleConfig) + + +class AdaptiveScheduler: + """Adaptive batch scheduler with queue state and online masked surrogate updates.""" + + def __init__( + self, + config: SchedulerConfig | None = None, + policy: PrioritizationPolicy | None = None, + surrogate_config: SurrogateConfig | None = None, + ) -> None: + self.config = config or SchedulerConfig() + self.policy = policy or PrioritizationPolicy() + self.surrogate = SurrogateModel(surrogate_config) + self.state = SchedulerState() + self.queue_manager = QueueManager.from_items([]) + self.last_model_weight: float = 0.0 + + def initialize( + self, + ligands_df: pd.DataFrame, + cluster_map: Dict[str, int], + hypercluster_for_cluster: Dict[int, int], + ) -> None: + items: List[QueueItem] = [] + cluster_load: Dict[int, int] = {} + + for row in ligands_df.itertuples(index=False): + ligand_id = str(row.ligand_id) + cluster_id = int(cluster_map.get(ligand_id, -1)) + hypercluster_id = int(hypercluster_for_cluster.get(cluster_id, -1)) + bonus = cluster_bonus(cluster_load, cluster_id) + priority = compute_priority( + predicted_utility=0.0, + uncertainty=1.0, + diversity_gain=bonus, + cluster_bonus=bonus, + policy=self.policy, + ) + items.append( + QueueItem( + ligand_id=ligand_id, + status="active", + priority=float(priority), + cluster_id=cluster_id, + hypercluster_id=hypercluster_id, + ) + ) + cluster_load[cluster_id] = cluster_load.get(cluster_id, 0) + 1 + + self.state = SchedulerState(queue=items, batch_history=[], round_idx=0) + self.queue_manager = QueueManager.from_items(items) + + def select_batch(self) -> List[str]: + active = self.queue_manager.ordered_active() + if not active: + # If conservative deprioritization exhausted active queue, reactivate + # deprioritized candidates to continue spending the docking budget. + deprioritized = sorted( + [item for item in self.queue_manager.items.values() if item.status == "deprioritized"], + key=lambda item: item.priority, + reverse=True, + ) + if not deprioritized: + return [] + for item in deprioritized: + item.status = "active" + active = deprioritized + + coverage_count = max(1, int(self.config.batch_size * self.config.init_coverage_fraction)) + by_hypercluster: Dict[int, List[QueueItem]] = {} + for item in active: + by_hypercluster.setdefault(item.hypercluster_id, []).append(item) + + selected: List[str] = [] + # Broad initial coverage. + for _h_id, items in sorted(by_hypercluster.items(), key=lambda x: len(x[1]), reverse=True): + if len(selected) >= coverage_count: + break + selected.append(items[0].ligand_id) + + # Fill remaining slots by priority. + for item in active: + if len(selected) >= self.config.batch_size: + break + if item.ligand_id not in selected: + selected.append(item.ligand_id) + + for ligand_id in selected: + self.queue_manager.items[ligand_id].times_selected += 1 + return selected + + @staticmethod + def _mean_or_default(values: list[float], default: float = 0.0) -> float: + if not values: + return float(default) + return float(np.mean(np.asarray(values, dtype=float))) + + def update_from_batch( + self, + evaluated_df: pd.DataFrame, + feature_values_df: pd.DataFrame, + feature_masks_df: pd.DataFrame, + ) -> Dict[str, float]: + # Mark completed ligands and store latest score. + score_map = dict(zip(evaluated_df["ligand_id"].astype(str), evaluated_df["docking_score"].astype(float))) + for ligand_id, score in score_map.items(): + if ligand_id in self.queue_manager.items: + item = self.queue_manager.items[ligand_id] + item.status = "completed" + item.last_score = float(score) + + if feature_values_df.empty or feature_masks_df.empty: + raise ValueError("Feature tables cannot be empty in adaptive update") + + if "ligand_id" not in feature_values_df.columns or "ligand_id" not in feature_masks_df.columns: + raise ValueError("Feature tables must include ligand_id column") + + ligand_order = feature_values_df["ligand_id"].astype(str).tolist() + features = feature_values_df.drop(columns=["ligand_id"]).to_numpy(dtype=float) + masks = feature_masks_df.drop(columns=["ligand_id"]).to_numpy(dtype=float) + feature_names = feature_values_df.drop(columns=["ligand_id"]).columns.tolist() + mask_names = feature_masks_df.drop(columns=["ligand_id"]).columns.tolist() + + target = np.full(len(ligand_order), np.nan, dtype=float) + for i, ligand_id in enumerate(ligand_order): + if ligand_id in self.queue_manager.items: + score = self.queue_manager.items[ligand_id].last_score + if score is not None: + target[i] = float(score) + + fit_stats = self.surrogate.fit( + features=features, + masks=masks, + y=target, + feature_names=feature_names, + mask_names=mask_names, + ) + + n_train = int(fit_stats.get("n_train", 0.0)) + instability_ratio = float(fit_stats.get("instability_ratio", 1.0)) + model_weight = compute_model_weight( + n_samples=n_train, + instability_ratio=instability_ratio, + config=self.config.weight_schedule, + ) + if self.surrogate.model is None: + model_weight = 0.0 + self.last_model_weight = float(model_weight) + + # Predict for active items. + active_items = self.queue_manager.active_items() + active_ids = [item.ligand_id for item in active_items] + + completed_items = [item for item in self.queue_manager.items.values() if item.last_score is not None] + global_completed = [float(item.last_score) for item in completed_items if item.last_score is not None] + global_mean_score = self._mean_or_default(global_completed, default=0.0) + + cluster_scores: Dict[int, list[float]] = {} + hyper_scores: Dict[int, list[float]] = {} + for item in completed_items: + assert item.last_score is not None + cluster_scores.setdefault(item.cluster_id, []).append(float(item.last_score)) + hyper_scores.setdefault(item.hypercluster_id, []).append(float(item.last_score)) + + if active_ids: + id_to_idx = {lid: idx for idx, lid in enumerate(ligand_order)} + x_active = np.vstack([features[id_to_idx[lid]] for lid in active_ids]) + m_active = np.vstack([masks[id_to_idx[lid]] for lid in active_ids]) + bundle = self.surrogate.predict_bundle(x_active, m_active) + + cluster_load: Dict[int, int] = {} + for item in active_items: + cluster_load[item.cluster_id] = cluster_load.get(item.cluster_id, 0) + 1 + + for i, ligand_id in enumerate(active_ids): + item = self.queue_manager.items[ligand_id] + + cluster_mean = self._mean_or_default(cluster_scores.get(item.cluster_id, []), default=np.nan) + hyper_mean = self._mean_or_default(hyper_scores.get(item.hypercluster_id, []), default=np.nan) + observed_docking = ( + cluster_mean + if np.isfinite(cluster_mean) + else hyper_mean + if np.isfinite(hyper_mean) + else global_mean_score + ) + + docking_component = -float(observed_docking) + model_component = -float(bundle["expected_score"][i]) + blended_utility = (1.0 - model_weight) * docking_component + model_weight * model_component + + bonus = cluster_bonus(cluster_load, item.cluster_id) + item.priority = compute_priority( + predicted_utility=float(blended_utility), + uncertainty=float(bundle["uncertainty"][i]), + diversity_gain=bonus, + cluster_bonus=bonus, + policy=self.policy, + ) + + if self.config.conservative_deprioritize: + priorities = np.asarray([self.queue_manager.items[lid].priority for lid in active_ids], dtype=float) + threshold = float(np.quantile(priorities, self.policy.conservative_deprioritize_quantile)) + for lid in active_ids: + if self.queue_manager.items[lid].priority < threshold: + self.queue_manager.items[lid].status = "deprioritized" + + self.state.round_idx += 1 + sm = score_metrics(evaluated_df["docking_score"].astype(float).tolist()) + batch_record: Dict[str, float | str] = { + "round_idx": self.state.round_idx, + "batch_size": int(evaluated_df.shape[0]), + "model_weight": float(model_weight), + "n_train": float(n_train), + "train_mae": float(fit_stats.get("train_mae", np.nan)), + "val_mae": float(fit_stats.get("val_mae", np.nan)), + "instability_ratio": float(instability_ratio), + "surrogate_backend": self.surrogate.backend, + **sm, + } + self.state.batch_history.append(batch_record) + return fit_stats + + def save_state(self, output_path: str | Path | None = None) -> Path: + target = Path(output_path or self.config.state_path) + self.state.queue = list(self.queue_manager.items.values()) + return self.state.save(target) diff --git a/libs/adaptive/state.py b/libs/adaptive/state.py new file mode 100644 index 0000000000000000000000000000000000000000..965450a6b2397100f7781ed2cb86da4eb507d0ee --- /dev/null +++ b/libs/adaptive/state.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any, Dict, List + +import json + + +@dataclass +class QueueItem: + ligand_id: str + status: str = "active" + priority: float = 0.0 + hypercluster_id: int = -1 + cluster_id: int = -1 + times_selected: int = 0 + last_score: float | None = None + + +@dataclass +class SchedulerState: + queue: List[QueueItem] = field(default_factory=list) + batch_history: List[Dict[str, Any]] = field(default_factory=list) + round_idx: int = 0 + + def to_dict(self) -> Dict[str, Any]: + return { + "queue": [asdict(item) for item in self.queue], + "batch_history": self.batch_history, + "round_idx": self.round_idx, + } + + @classmethod + def from_dict(cls, payload: Dict[str, Any]) -> "SchedulerState": + queue = [QueueItem(**item) for item in payload.get("queue", [])] + return cls(queue=queue, batch_history=payload.get("batch_history", []), round_idx=int(payload.get("round_idx", 0))) + + def save(self, path: str | Path) -> Path: + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + with target.open("w", encoding="utf-8") as handle: + json.dump(self.to_dict(), handle, indent=2) + return target + + @classmethod + def load(cls, path: str | Path) -> "SchedulerState": + source = Path(path) + with source.open("r", encoding="utf-8") as handle: + return cls.from_dict(json.load(handle)) diff --git a/libs/adaptive/surrogate_model.py b/libs/adaptive/surrogate_model.py new file mode 100644 index 0000000000000000000000000000000000000000..50605e3d1615c21f26d5bb79e81824baf8ddf750 --- /dev/null +++ b/libs/adaptive/surrogate_model.py @@ -0,0 +1,208 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, List, Optional + +import numpy as np +from sklearn.ensemble import RandomForestRegressor + +try: + from xgboost import XGBRegressor +except Exception: # pragma: no cover + XGBRegressor = None # type: ignore[assignment] + + +@dataclass +class SurrogateConfig: + prefer_xgboost: bool = True + random_state: int = 42 + n_estimators: int = 200 + min_train_samples: int = 8 + max_depth_small: int = 3 + max_depth_large: int = 6 + + +class SurrogateModel: + """Surrogate model with explicit missing-feature masking support.""" + + def __init__(self, config: Optional[SurrogateConfig] = None): + self.config = config or SurrogateConfig() + self.model = None + self.backend = "uninitialized" + self.feature_names: List[str] = [] + self.mask_names: List[str] = [] + + self._median: np.ndarray | None = None + self._iqr: np.ndarray | None = None + self._train_x: np.ndarray | None = None + self._train_y: np.ndarray | None = None + self.last_fit_stats: Dict[str, float] = {} + + def _build_model(self, n_samples: int): + max_depth = self.config.max_depth_small if n_samples < 50 else self.config.max_depth_large + if self.config.prefer_xgboost and XGBRegressor is not None: + self.backend = "xgboost" + return XGBRegressor( + n_estimators=self.config.n_estimators, + max_depth=max_depth, + learning_rate=0.05, + subsample=0.9, + colsample_bytree=0.9, + reg_alpha=0.1, + reg_lambda=1.0, + random_state=self.config.random_state, + ) + + self.backend = "random_forest" + return RandomForestRegressor( + n_estimators=max(100, self.config.n_estimators), + max_depth=max_depth, + random_state=self.config.random_state, + n_jobs=-1, + ) + + def _fit_normalizer(self, x: np.ndarray, m: np.ndarray) -> None: + med = [] + iqr = [] + for j in range(x.shape[1]): + vals = x[m[:, j] > 0.5, j] + if vals.size == 0: + med.append(0.0) + iqr.append(1.0) + continue + q1 = float(np.quantile(vals, 0.25)) + q3 = float(np.quantile(vals, 0.75)) + inter = max(1e-6, q3 - q1) + med.append(float(np.median(vals))) + iqr.append(inter) + self._median = np.asarray(med, dtype=float) + self._iqr = np.asarray(iqr, dtype=float) + + def _transform(self, x: np.ndarray, m: np.ndarray, fit: bool = False) -> np.ndarray: + x = np.asarray(x, dtype=float) + m = np.asarray(m, dtype=float) + if fit or self._median is None or self._iqr is None: + self._fit_normalizer(x, m) + assert self._median is not None and self._iqr is not None + + x_filled = np.where(np.isfinite(x), x, np.nan) + for j in range(x.shape[1]): + col = x_filled[:, j] + missing = ~np.isfinite(col) + col[missing] = self._median[j] + x_filled[:, j] = (col - self._median[j]) / self._iqr[j] + + # Explicit missingness information: concatenate mask vector. + return np.concatenate([x_filled, m], axis=1) + + def fit( + self, + features: np.ndarray, + masks: np.ndarray, + y: np.ndarray, + feature_names: List[str], + mask_names: List[str], + ) -> Dict[str, float]: + y = np.asarray(y, dtype=float) + valid = np.isfinite(y) + n_samples = int(np.sum(valid)) + + self.feature_names = list(feature_names) + self.mask_names = list(mask_names) + + if n_samples < self.config.min_train_samples: + self.model = None + self.backend = "warmup" + self.last_fit_stats = { + "n_train": float(n_samples), + "train_mae": np.nan, + "val_mae": np.nan, + "instability_ratio": 1.0, + } + return self.last_fit_stats + + x = np.asarray(features, dtype=float)[valid] + m = np.asarray(masks, dtype=float)[valid] + yv = y[valid] + + x_trans = self._transform(x, m, fit=True) + self._train_x = x_trans + self._train_y = yv + + self.model = self._build_model(n_samples=n_samples) + self.model.fit(x_trans, yv) + + train_pred = self.model.predict(x_trans) + train_mae = float(np.mean(np.abs(train_pred - yv))) + + # Simple rolling validation proxy. + if n_samples >= 12: + split = int(max(8, n_samples * 0.8)) + x_tr, x_val = x_trans[:split], x_trans[split:] + y_tr, y_val = yv[:split], yv[split:] + + val_model = self._build_model(n_samples=split) + val_model.fit(x_tr, y_tr) + val_pred = val_model.predict(x_val) + val_mae = float(np.mean(np.abs(val_pred - y_val))) if y_val.size else train_mae + else: + val_mae = train_mae + + instability = float((val_mae + 1e-6) / (train_mae + 1e-6)) + self.last_fit_stats = { + "n_train": float(n_samples), + "train_mae": train_mae, + "val_mae": val_mae, + "instability_ratio": instability, + } + return self.last_fit_stats + + def _rf_uncertainty(self, x: np.ndarray) -> np.ndarray: + assert self.model is not None + if not hasattr(self.model, "estimators_"): + return np.full(x.shape[0], float(np.std(self._train_y)) if self._train_y is not None else 1.0) + preds = np.vstack([tree.predict(x) for tree in self.model.estimators_]) + return np.std(preds, axis=0) + + def predict_bundle(self, features: np.ndarray, masks: np.ndarray, topk_threshold: float | None = None) -> Dict[str, np.ndarray]: + n = features.shape[0] + if self.model is None: + return { + "expected_score": np.zeros(n, dtype=float), + "topk_probability": np.full(n, 0.5, dtype=float), + "uncertainty": np.full(n, 1.0, dtype=float), + } + + x = self._transform(np.asarray(features, dtype=float), np.asarray(masks, dtype=float), fit=False) + expected = self.model.predict(x) + + if self.backend == "random_forest": + uncertainty = self._rf_uncertainty(x) + else: + residual_scale = ( + float(np.std(self._train_y - self.model.predict(self._train_x))) + if self._train_x is not None and self._train_y is not None + else 1.0 + ) + uncertainty = np.full(expected.shape[0], max(1e-3, residual_scale)) + + if topk_threshold is None: + topk_threshold = float(np.quantile(self._train_y, 0.8)) if self._train_y is not None else 0.0 + + z = (expected - topk_threshold) / (uncertainty + 1e-6) + topk_prob = 1.0 / (1.0 + np.exp(-z)) + return { + "expected_score": expected.astype(float), + "topk_probability": topk_prob.astype(float), + "uncertainty": uncertainty.astype(float), + } + + def feature_importance(self) -> Dict[str, float]: + if self.model is None or not hasattr(self.model, "feature_importances_"): + return {} + + names = self.feature_names + self.mask_names + importances = np.asarray(self.model.feature_importances_, dtype=float) + if importances.size != len(names): + return {} + return {name: float(value) for name, value in zip(names, importances)} diff --git a/libs/adaptive/thresholding.py b/libs/adaptive/thresholding.py new file mode 100644 index 0000000000000000000000000000000000000000..81ad4e032a776fac42911d30a121145bc59acd4e --- /dev/null +++ b/libs/adaptive/thresholding.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, List, Sequence + +import numpy as np + + +@dataclass +class DynamicThresholdConfig: + min_evaluated: int = 500 + patience_rounds: int = 8 + min_model_weight: float = 0.35 + quantile: float = 0.15 + uncertainty_weight: float = 0.20 + min_improvement: float = 0.02 + exploration_margin: float = 0.45 + exploitation_margin: float = 0.10 + reference_evaluations: int = 5000 + + +class DynamicEarlyStopController: + """ + Conservative early-stop controller for adaptive replay. + + Lower scores are considered better. + """ + + def __init__(self, config: DynamicThresholdConfig | None = None) -> None: + self.config = config or DynamicThresholdConfig() + self.best_score = np.inf + self.stagnant_rounds = 0 + self.history: List[Dict[str, float | int | bool | str]] = [] + + def update( + self, + *, + round_idx: int, + n_evaluated: int, + all_scores: Sequence[float], + recent_scores: Sequence[float], + model_weight: float, + mean_uncertainty: float, + ) -> Dict[str, float | int | bool | str]: + cfg = self.config + scores = np.asarray(all_scores, dtype=float) + recent = np.asarray(recent_scores, dtype=float) + + if scores.size == 0: + rec = { + "round_idx": int(round_idx), + "n_evaluated": int(n_evaluated), + "dynamic_threshold": np.nan, + "score_quantile": np.nan, + "best_score": np.nan, + "recent_mean_score": np.nan, + "mean_uncertainty": float(mean_uncertainty), + "model_weight": float(model_weight), + "stagnant_rounds": int(self.stagnant_rounds), + "eligible_for_stop": False, + "stop": False, + "reason": "no_scores", + } + self.history.append(rec) + return rec + + score_quantile = float(np.nanquantile(scores, cfg.quantile)) + best = float(np.nanmin(scores)) + recent_mean = float(np.nanmean(recent)) if recent.size else float(np.nan) + uncertainty = float(max(0.0, mean_uncertainty)) + + if np.isfinite(self.best_score): + improvement = float(self.best_score - best) + else: + improvement = np.inf + + if improvement > cfg.min_improvement: + self.stagnant_rounds = 0 + else: + self.stagnant_rounds += 1 + self.best_score = min(self.best_score, best) + + coverage = float(min(1.0, n_evaluated / max(1.0, float(cfg.reference_evaluations)))) + margin = (1.0 - coverage) * cfg.exploration_margin + coverage * cfg.exploitation_margin + dynamic_threshold = float(score_quantile + margin + cfg.uncertainty_weight * uncertainty) + + eligible = ( + int(n_evaluated) >= int(cfg.min_evaluated) + and float(model_weight) >= float(cfg.min_model_weight) + ) + plateau = self.stagnant_rounds >= int(cfg.patience_rounds) + poor_recent = bool(np.isfinite(recent_mean) and recent_mean >= dynamic_threshold) + should_stop = bool(eligible and plateau and poor_recent) + + if not eligible: + reason = "not_eligible" + elif not plateau: + reason = "improving_or_not_stagnant" + elif not poor_recent: + reason = "recent_batch_still_competitive" + else: + reason = "stagnation_above_dynamic_threshold" + + rec = { + "round_idx": int(round_idx), + "n_evaluated": int(n_evaluated), + "dynamic_threshold": dynamic_threshold, + "score_quantile": score_quantile, + "best_score": self.best_score, + "recent_mean_score": recent_mean, + "mean_uncertainty": uncertainty, + "model_weight": float(model_weight), + "stagnant_rounds": int(self.stagnant_rounds), + "eligible_for_stop": bool(eligible), + "stop": should_stop, + "reason": reason, + } + self.history.append(rec) + return rec + diff --git a/libs/adaptive/weight_schedule.py b/libs/adaptive/weight_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..17278422b9a00acd8bcd387ecb970bdb0b50e65f --- /dev/null +++ b/libs/adaptive/weight_schedule.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Sequence + + +@dataclass +class WeightScheduleConfig: + sample_knots: tuple[int, int, int, int] = (20, 50, 100, 200) + weight_knots: tuple[float, float, float, float] = (0.1, 0.3, 0.5, 0.8) + max_weight: float = 0.9 + min_weight: float = 0.05 + instability_threshold: float = 2.0 + instability_decay: float = 0.25 + + +def _interp(x: float, xs: Sequence[float], ys: Sequence[float]) -> float: + if x <= xs[0]: + return float(ys[0]) + if x >= xs[-1]: + return float(ys[-1]) + + for i in range(1, len(xs)): + if x <= xs[i]: + x0, x1 = xs[i - 1], xs[i] + y0, y1 = ys[i - 1], ys[i] + t = (x - x0) / max(1e-9, (x1 - x0)) + return float(y0 + t * (y1 - y0)) + return float(ys[-1]) + + +def compute_model_weight( + n_samples: int, + instability_ratio: float = 1.0, + config: WeightScheduleConfig | None = None, +) -> float: + cfg = config or WeightScheduleConfig() + + base = _interp(float(n_samples), cfg.sample_knots, cfg.weight_knots) + if n_samples > cfg.sample_knots[-1]: + extra = min(cfg.max_weight - base, 0.05 * (n_samples - cfg.sample_knots[-1]) / 100.0) + base += max(0.0, extra) + + if instability_ratio > cfg.instability_threshold: + base *= max(0.1, 1.0 - cfg.instability_decay) + + base = max(cfg.min_weight, min(cfg.max_weight, base)) + return float(base) diff --git a/libs/analysis/__init__.py b/libs/analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/libs/analysis/backend_diagnostic.py b/libs/analysis/backend_diagnostic.py new file mode 100644 index 0000000000000000000000000000000000000000..03b9b030de40bb485252c6f266ecbfb8c8173ff0 --- /dev/null +++ b/libs/analysis/backend_diagnostic.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Iterable + +import numpy as np +import pandas as pd + + +REQUIRED_REFERENCE_DIAG_COLUMNS = [ + "dataset", + "target_name", + "reference_ligand_id", + "reference_ligand_score", + "reference_ligand_rank_percentile", + "adaptive_best_score", + "exhaustive_best_score", +] + +REQUIRED_BACKEND_COMPARISON_COLUMNS = [ + "dataset", + "backend", + "analysis_scope", + "available", + "n_ligands", + "runtime_seconds", + "runtime_per_ligand", + "reference_ligand_score", + "reference_ligand_rank_percentile", + "best_score", + "score_gap_reference_vs_best", + "reference_pose_centroid_distance_A", + "reference_pose_in_expected_pocket", +] + +REQUIRED_POCKET_PREP_COLUMNS = [ + "dataset", + "backend", + "pocket_variant", + "prep_variant", + "reference_ligand_score", + "reference_pose_centroid_distance_A", + "reference_pose_in_expected_pocket", +] + + +@dataclass(frozen=True) +class ManualAgentsCheck: + exists: bool + path: str + manually_read: bool + + +def manual_agents_check(path: str | Path, manually_read: bool = True) -> ManualAgentsCheck: + p = Path(path).expanduser().resolve() + return ManualAgentsCheck(exists=p.exists(), path=str(p), manually_read=bool(manually_read and p.exists())) + + +def _safe_float(x: Any, default: float = np.nan) -> float: + try: + v = float(x) + return float(v) if np.isfinite(v) else float(default) + except Exception: + return float(default) + + +def compute_rank_percentile(df: pd.DataFrame, ligand_id: str, score_col: str, lower_is_better: bool = True) -> float: + if df.empty or score_col not in df.columns: + return np.nan + d = df[["ligand_id", score_col]].copy() + d["ligand_id"] = d["ligand_id"].astype(str) + d[score_col] = pd.to_numeric(d[score_col], errors="coerce") + d = d.dropna(subset=[score_col]).copy() + if d.empty: + return np.nan + d = d.sort_values(score_col, ascending=bool(lower_is_better)).reset_index(drop=True) + hit = d.index[d["ligand_id"] == str(ligand_id)] + if len(hit) == 0: + return np.nan + rank = int(hit[0]) + 1 + return float(100.0 * rank / max(1, d.shape[0])) + + +def select_suspicious_datasets(reference_diag_df: pd.DataFrame, threshold_pct: float = 25.0, max_deep: int = 2) -> list[str]: + if reference_diag_df.empty: + return [] + d = reference_diag_df.copy() + d["reference_ligand_rank_percentile"] = pd.to_numeric(d["reference_ligand_rank_percentile"], errors="coerce") + d = d.dropna(subset=["reference_ligand_rank_percentile"]).copy() + d = d[d["reference_ligand_rank_percentile"] >= float(threshold_pct)].copy() + if d.empty: + return [] + d = d.sort_values("reference_ligand_rank_percentile", ascending=False) + return d["dataset"].astype(str).head(int(max(1, max_deep))).tolist() + + +def validate_required_columns(df: pd.DataFrame, required_columns: Iterable[str]) -> list[str]: + cols = set(df.columns) + missing = [c for c in required_columns if c not in cols] + return missing + + +def recommend_toolchain( + backend_comparison_df: pd.DataFrame, + pocket_prep_df: pd.DataFrame, +) -> dict[str, Any]: + """ + Choose practical recommendation from diagnostic evidence. + + Policy: + - Prefer backend with best median reference rank percentile under "subset_default" scope. + - Penalize poor runtime-per-ligand if >2x best runtime. + - Use pocket/prep gain to detect whether core issue is mostly preparation/pocket. + """ + out: dict[str, Any] = { + "recommended_main_backend": "rdock", + "recommended_rescoring": "gnina_or_haddock_shortlist_optional", + "keep_haddock": "optional_shortlist_only", + "main_failure_source": "mixed", + "evidence": [], + } + + bdf = backend_comparison_df.copy() + if not bdf.empty: + bdf = bdf[bdf["analysis_scope"].astype(str) == "subset_default"].copy() + if not bdf.empty: + bdf["runtime_per_ligand"] = pd.to_numeric(bdf["runtime_per_ligand"], errors="coerce") + bdf["reference_ligand_rank_percentile"] = pd.to_numeric(bdf["reference_ligand_rank_percentile"], errors="coerce") + agg = ( + bdf.groupby("backend", as_index=False) + .agg( + median_ref_rank_pct=("reference_ligand_rank_percentile", "median"), + median_runtime=("runtime_per_ligand", "median"), + available_ratio=("available", "mean"), + ) + .sort_values(["median_ref_rank_pct", "median_runtime"], ascending=[True, True]) + ) + if not agg.empty: + best = agg.iloc[0] + best_runtime = max(1e-9, _safe_float(best["median_runtime"], 1.0)) + candidate = str(best["backend"]) + if _safe_float(best["available_ratio"], 0.0) < 0.5: + out["evidence"].append("best_rank_backend_not_reliably_available") + else: + out["recommended_main_backend"] = candidate + + rd = agg[agg["backend"].astype(str).str.lower() == "rdock"] + if not rd.empty: + rd_runtime = max(1e-9, _safe_float(rd.iloc[0]["median_runtime"], best_runtime)) + if best_runtime > 2.0 * rd_runtime and candidate != "rdock": + out["evidence"].append("candidate_backend_too_slow_vs_rdock") + out["recommended_main_backend"] = "rdock" + + out["evidence"].append(f"rank_runtime_table={agg.to_dict(orient='records')}") + + pdf = pocket_prep_df.copy() + if not pdf.empty: + pdf["reference_ligand_score"] = pd.to_numeric(pdf["reference_ligand_score"], errors="coerce") + deltas: list[float] = [] + for (_, _), sub in pdf.groupby(["dataset", "backend"]): + default = sub[(sub["pocket_variant"] == "default") & (sub["prep_variant"] == "default")] + if default.empty: + continue + default_score = _safe_float(default.iloc[0]["reference_ligand_score"], np.nan) + best_score = _safe_float(sub["reference_ligand_score"].min(), np.nan) + if np.isfinite(default_score) and np.isfinite(best_score): + deltas.append(default_score - best_score) + mean_gain = float(np.mean(np.asarray(deltas, dtype=float))) if deltas else 0.0 + if mean_gain > 1.0: + out["main_failure_source"] = "pocket_or_preparation" + elif mean_gain > 0.2: + out["main_failure_source"] = "mixed" + else: + out["main_failure_source"] = "backend_scoring_limitations" + out["evidence"].append(f"mean_reference_gain_from_pocket_prep={mean_gain:.3f}") + + out["keep_haddock"] = "optional_shortlist_only" + return out diff --git a/libs/analysis/ranking.py b/libs/analysis/ranking.py new file mode 100644 index 0000000000000000000000000000000000000000..6826ef13c19344bd89497d958ac661ec28e9d096 --- /dev/null +++ b/libs/analysis/ranking.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import numpy as np +import pandas as pd + + +def resolve_reference_rank_percentile( + merged_df: pd.DataFrame, + reference_ligand_id: str, + *, + oracle_rank_col: str = "rank_percentile", + run_rank_col: str = "run_rank_percentile", +) -> tuple[float, str]: + """ + Resolve reference rank percentile with robust fallback. + + Returns: + - rank percentile (float) + - source ("oracle", "run_fallback", "missing") + """ + if merged_df.empty: + return float("nan"), "missing" + + d = merged_df.copy() + if "ligand_id" not in d.columns: + return float("nan"), "missing" + d["ligand_id"] = d["ligand_id"].astype(str) + ref = d[d["ligand_id"] == str(reference_ligand_id)] + if ref.empty: + return float("nan"), "missing" + + if oracle_rank_col in ref.columns: + oracle_val = pd.to_numeric(ref[oracle_rank_col], errors="coerce").iloc[0] + if np.isfinite(float(oracle_val)): + return float(oracle_val), "oracle" + + if run_rank_col in d.columns: + run_val = pd.to_numeric(ref[run_rank_col], errors="coerce").iloc[0] + if np.isfinite(float(run_val)): + return float(run_val), "run_fallback" + + return float("nan"), "missing" + diff --git a/libs/benchmark/__init__.py b/libs/benchmark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97d29b0a9adae4a2d778cc9f8b114fc4419fd41f --- /dev/null +++ b/libs/benchmark/__init__.py @@ -0,0 +1,108 @@ +"""Benchmark utilities for large-scale and modality sanity-check runs.""" + +from .cleanup import CleanupItem, execute_results_cleanup, plan_results_cleanup +from .budget_efficiency import ( + TimeImportanceControls, + clamp_time_importance, + controls_from_time_importance, + required_budget_metric_columns, + select_best_policy_budget, + summarize_diversity, + validate_budget_metric_schema, +) +from .disk_guard import ( + DiskCleanupAction, + DiskSnapshot, + append_disk_snapshot, + requires_cleanup, + run_repository_local_cleanup, + snapshot_disk_state, + write_cleanup_actions, + write_disk_guard_report, +) +from .large_library import build_large_benchmark_library +from .ordering import cluster_naive_order +from .policy_repair import ( + AdaptivePolicyVariant, + PolicyRuntimeState, + apply_stop_policy, + coverage_floor_reached, + coverage_fraction, + default_policy_variants, + effective_controls, + regret_stop_variant, + select_cluster_bootstrap_batch, +) +from .multifidelity import ( + ExplorationControls, + StoppingControls, + UncertaintyControls, + controls_from_config, + enforce_control_limits, + simulate_multifidelity_policy, +) +from .overnight_stop import ( + OBJECTIVES, + STOP_MODELS, + StopModelParams, + estimate_marginal_expected_gain, + estimate_probability_target_percentile, + is_trivial_objective_solution, + objective_value, + simulate_stop_model, +) +from .runtime import AUTO_MINUS_FOUR, ThreadAllocation, detect_system_threads, enforce_thread_fairness, resolve_threads_used +from .reuse import ReuseCheck, validate_reuse_inputs + +__all__ = [ + "AUTO_MINUS_FOUR", + "AdaptivePolicyVariant", + "CleanupItem", + "DiskCleanupAction", + "DiskSnapshot", + "PolicyRuntimeState", + "TimeImportanceControls", + "ThreadAllocation", + "ReuseCheck", + "apply_stop_policy", + "append_disk_snapshot", + "build_large_benchmark_library", + "clamp_time_importance", + "cluster_naive_order", + "coverage_floor_reached", + "coverage_fraction", + "controls_from_time_importance", + "default_policy_variants", + "detect_system_threads", + "effective_controls", + "estimate_marginal_expected_gain", + "estimate_probability_target_percentile", + "enforce_thread_fairness", + "execute_results_cleanup", + "is_trivial_objective_solution", + "objective_value", + "OBJECTIVES", + "STOP_MODELS", + "plan_results_cleanup", + "required_budget_metric_columns", + "regret_stop_variant", + "requires_cleanup", + "resolve_threads_used", + "run_repository_local_cleanup", + "simulate_multifidelity_policy", + "simulate_stop_model", + "StopModelParams", + "StoppingControls", + "ExplorationControls", + "UncertaintyControls", + "controls_from_config", + "enforce_control_limits", + "validate_reuse_inputs", + "select_best_policy_budget", + "select_cluster_bootstrap_batch", + "snapshot_disk_state", + "summarize_diversity", + "validate_budget_metric_schema", + "write_cleanup_actions", + "write_disk_guard_report", +] diff --git a/libs/benchmark/budget_efficiency.py b/libs/benchmark/budget_efficiency.py new file mode 100644 index 0000000000000000000000000000000000000000..85869b09b5555b7da440b48daaf98c366d324f1c --- /dev/null +++ b/libs/benchmark/budget_efficiency.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Iterable, List + +import numpy as np +import pandas as pd + +from libs.adaptive.policies import PrioritizationPolicy + + +def clamp_time_importance(value: float) -> float: + return float(max(0.0, min(1.0, float(value)))) + + +@dataclass(frozen=True) +class TimeImportanceControls: + utility_weight: float + uncertainty_weight: float + diversity_weight: float + cluster_bonus_weight: float + threshold_stop_shift: float + exploration_additive: float + + +def controls_from_time_importance( + base_policy: PrioritizationPolicy, + *, + exploration_boost: float, + time_importance: float, +) -> TimeImportanceControls: + ti = clamp_time_importance(time_importance) + exp = float(max(0.0, exploration_boost)) + + adjusted_exp = float(max(0.0, exp + (1.0 - ti) * 0.22)) + utility = max(0.15, float(base_policy.utility_weight) - 0.40 * adjusted_exp + 0.22 * ti) + uncertainty = max(0.05, float(base_policy.uncertainty_weight) + 0.22 * adjusted_exp - 0.10 * ti) + diversity = max(0.05, float(base_policy.diversity_weight) + 0.14 * adjusted_exp - 0.08 * ti) + cluster_bonus = float(base_policy.cluster_bonus_weight) + 0.04 * adjusted_exp + # Negative means easier stopping (more time-sensitive). + threshold_stop_shift = float(-0.20 * ti) + return TimeImportanceControls( + utility_weight=float(utility), + uncertainty_weight=float(uncertainty), + diversity_weight=float(diversity), + cluster_bonus_weight=float(cluster_bonus), + threshold_stop_shift=threshold_stop_shift, + exploration_additive=adjusted_exp, + ) + + +def required_budget_metric_columns() -> List[str]: + return [ + "dataset", + "strategy", + "strategy_group", + "budget", + "time_importance", + "top10_recovery_fraction", + "top50_recovery_fraction", + "top100_recovery_fraction", + "best_docking_score", + "best_final_score", + "dockings_performed", + "wall_time_seconds", + "quality_per_time", + "quality_per_docking", + "auc_best_score_so_far", + ] + + +def validate_budget_metric_schema(df: pd.DataFrame) -> List[str]: + missing = [c for c in required_budget_metric_columns() if c not in df.columns] + return missing + + +def select_best_policy_budget(metrics_df: pd.DataFrame) -> pd.Series: + if metrics_df.empty: + raise ValueError("metrics_df is empty") + missing = validate_budget_metric_schema(metrics_df) + if missing: + raise ValueError(f"metrics_df missing required columns: {missing}") + + d = metrics_df.copy() + if "strategy_group" in d.columns: + d = d[d["strategy_group"].astype(str) == "adaptive"].copy() + if d.empty: + raise ValueError("No adaptive rows found for selection") + + for c in ["top10_recovery_fraction", "top50_recovery_fraction", "top100_recovery_fraction", "quality_per_time", "quality_per_docking"]: + d[f"rank_{c}"] = pd.to_numeric(d[c], errors="coerce").rank(method="average", ascending=False) + d["rank_budget"] = pd.to_numeric(d["budget"], errors="coerce").rank(method="average", ascending=True) + d["rank_best_final"] = pd.to_numeric(d["best_final_score"], errors="coerce").rank(method="average", ascending=True) + + d["selection_score"] = ( + 0.24 * d["rank_top50_recovery_fraction"] + + 0.24 * d["rank_top100_recovery_fraction"] + + 0.20 * d["rank_top10_recovery_fraction"] + + 0.12 * d["rank_quality_per_docking"] + + 0.10 * d["rank_quality_per_time"] + + 0.06 * d["rank_best_final"] + + 0.04 * d["rank_budget"] + ) + chosen = d.sort_values(["selection_score", "budget"], ascending=[True, True]).iloc[0] + return chosen + + +def summarize_diversity(df: pd.DataFrame, *, similarity_col: str = "reference_similarity", scaffold_col: str = "scaffold_core") -> pd.DataFrame: + vals = pd.to_numeric(df.get(similarity_col, pd.Series(dtype=float)), errors="coerce").dropna() + bins = np.linspace(0.0, 1.0, 11) + hist, edges = np.histogram(vals.to_numpy(dtype=float), bins=bins) + out = pd.DataFrame( + { + "bin_left": edges[:-1], + "bin_right": edges[1:], + "count": hist, + "fraction": hist / max(1, int(hist.sum())), + } + ) + out["unique_scaffold_count"] = int(df.get(scaffold_col, pd.Series(dtype=str)).astype(str).replace({"": np.nan}).dropna().nunique()) + out["total_ligands"] = int(df.shape[0]) + return out + diff --git a/libs/benchmark/cleanup.py b/libs/benchmark/cleanup.py new file mode 100644 index 0000000000000000000000000000000000000000..fb5077371fb85279599755a5b1ae1e2d1b537989 --- /dev/null +++ b/libs/benchmark/cleanup.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import shutil +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Iterable, List + + +@dataclass +class CleanupItem: + path: Path + action: str + reason: str + + +def plan_results_cleanup( + results_dir: Path, + *, + keep_dirs: Iterable[str] = ( + "large_benchmark", + "discovery_benchmark", + "ppi_benchmark", + "ppi_sanity_check", + "experimental_benchmark_single_library", + "smoke_test", + ), +) -> List[CleanupItem]: + keep = {str(x).strip() for x in keep_dirs} + items: List[CleanupItem] = [] + if not results_dir.exists(): + return items + + for child in sorted(results_dir.iterdir()): + if not child.is_dir(): + continue + if child.name in keep or child.name == "archive": + continue + items.append( + CleanupItem( + path=child, + action="archive", + reason="obsolete_or_legacy_result_artifact", + ) + ) + return items + + +def execute_results_cleanup(results_dir: Path, plan: List[CleanupItem]) -> Path: + archive_root = results_dir / "archive" / datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + archive_root.mkdir(parents=True, exist_ok=True) + for item in plan: + if item.action != "archive" or not item.path.exists(): + continue + target = archive_root / item.path.name + if target.exists(): + shutil.rmtree(target) + shutil.move(str(item.path), str(target)) + return archive_root diff --git a/libs/benchmark/disk_guard.py b/libs/benchmark/disk_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..048c7c38cd86ebc9b2f711b1a6622b0369de9ed5 --- /dev/null +++ b/libs/benchmark/disk_guard.py @@ -0,0 +1,233 @@ +from __future__ import annotations + +import gzip +import os +import shutil +from dataclasses import dataclass, asdict +from datetime import UTC, datetime +from pathlib import Path +from typing import Dict, Iterable, List + +import pandas as pd + + +@dataclass +class DiskSnapshot: + timestamp_utc: str + stage: str + note: str + free_gb: float + repo_size_gb: float + projected_output_gb: float + projected_free_after_gb: float + + +@dataclass +class DiskCleanupAction: + timestamp_utc: str + action: str + target: str + size_before_mb: float + size_after_mb: float + reclaimed_mb: float + status: str + reason: str + + +def _utc_now() -> str: + return datetime.now(UTC).isoformat() + + +def _is_within_repo(target: Path, repo_root: Path) -> bool: + try: + target.resolve().relative_to(repo_root.resolve()) + return True + except Exception: + return False + + +def directory_size_bytes(path: Path) -> int: + total = 0 + if not path.exists(): + return total + for entry in path.rglob("*"): + if entry.is_file(): + try: + total += entry.stat().st_size + except OSError: + continue + return total + + +def system_free_bytes(path: Path) -> int: + return int(shutil.disk_usage(path).free) + + +def snapshot_disk_state(repo_root: Path, stage: str, note: str, projected_output_gb: float = 0.0) -> DiskSnapshot: + free = system_free_bytes(repo_root) + repo_size = directory_size_bytes(repo_root) + projected_after = max(0.0, (free / (1024**3)) - float(projected_output_gb)) + return DiskSnapshot( + timestamp_utc=_utc_now(), + stage=stage, + note=note, + free_gb=free / (1024**3), + repo_size_gb=repo_size / (1024**3), + projected_output_gb=float(projected_output_gb), + projected_free_after_gb=projected_after, + ) + + +def append_disk_snapshot(csv_path: Path, snapshot: DiskSnapshot) -> None: + csv_path.parent.mkdir(parents=True, exist_ok=True) + row = pd.DataFrame([asdict(snapshot)]) + if csv_path.exists(): + old = pd.read_csv(csv_path) + out = pd.concat([old, row], ignore_index=True) + else: + out = row + out.to_csv(csv_path, index=False) + + +def requires_cleanup(snapshot: DiskSnapshot, *, min_free_gb: float = 8.0) -> bool: + return bool(snapshot.projected_free_after_gb < float(min_free_gb)) + + +def _compress_file(path: Path) -> tuple[float, float]: + before = path.stat().st_size / (1024**2) + gz_path = path.with_suffix(path.suffix + ".gz") + with path.open("rb") as src, gzip.open(gz_path, "wb", compresslevel=6) as dst: + shutil.copyfileobj(src, dst) + path.unlink(missing_ok=True) + after = gz_path.stat().st_size / (1024**2) + return before, after + + +def _prune_batches(raw_root: Path, keep_first_n: int) -> tuple[float, float]: + before = directory_size_bytes(raw_root) / (1024**2) + batches = sorted([p for p in raw_root.iterdir() if p.is_dir()]) + for batch in batches[keep_first_n:]: + shutil.rmtree(batch, ignore_errors=True) + after = directory_size_bytes(raw_root) / (1024**2) + return before, after + + +def run_repository_local_cleanup( + repo_root: Path, + *, + results_dir: Path, + keep_raw_batches: int = 6, +) -> List[DiskCleanupAction]: + actions: List[DiskCleanupAction] = [] + + def record(action: str, target: Path, before: float, after: float, status: str, reason: str) -> None: + actions.append( + DiskCleanupAction( + timestamp_utc=_utc_now(), + action=action, + target=str(target), + size_before_mb=float(before), + size_after_mb=float(after), + reclaimed_mb=max(0.0, float(before - after)), + status=status, + reason=reason, + ) + ) + + # 1) Remove replay caches after summary tables are present. + for replay in results_dir.glob("*/replay_cache"): + parent = replay.parent + if not _is_within_repo(replay, repo_root): + record("remove_dir", replay, 0.0, 0.0, "skipped", "outside_repo_guard") + continue + if not (parent / "summary.json").exists(): + record("remove_dir", replay, 0.0, 0.0, "skipped", "missing_summary") + continue + before = directory_size_bytes(replay) / (1024**2) + shutil.rmtree(replay, ignore_errors=True) + after = directory_size_bytes(replay) / (1024**2) if replay.exists() else 0.0 + record("remove_dir", replay, before, after, "ok", "replay_cache_not_required_for_final_reports") + + # 2) Prune oversized raw output batches but keep representative subset. + for raw_root in list(results_dir.glob("*/raw_rdock_outputs")) + list(results_dir.glob("*/predock/raw_rdock_outputs")): + if not raw_root.exists() or not raw_root.is_dir(): + continue + if not _is_within_repo(raw_root, repo_root): + record("prune_batches", raw_root, 0.0, 0.0, "skipped", "outside_repo_guard") + continue + before, after = _prune_batches(raw_root, keep_first_n=keep_raw_batches) + record("prune_batches", raw_root, before, after, "ok", "keep_representative_raw_batches_only") + + # 3) Compress large logs. + for log_file in results_dir.rglob("*.log"): + if not log_file.exists() or not log_file.is_file(): + continue + if not _is_within_repo(log_file, repo_root): + record("compress_log", log_file, 0.0, 0.0, "skipped", "outside_repo_guard") + continue + if log_file.stat().st_size < 2 * 1024 * 1024: + continue + before, after = _compress_file(log_file) + record("compress_log", log_file, before, after, "ok", "large_log_compression") + + # 4) Remove stale duplicate work dirs if summaries exist. + for work_dir in results_dir.glob("*/work"): + parent = work_dir.parent + if not (parent / "summary.json").exists(): + continue + if not _is_within_repo(work_dir, repo_root): + record("remove_work_dir", work_dir, 0.0, 0.0, "skipped", "outside_repo_guard") + continue + before = directory_size_bytes(work_dir) / (1024**2) + shutil.rmtree(work_dir, ignore_errors=True) + record("remove_work_dir", work_dir, before, 0.0, "ok", "parsed_outputs_already_persisted") + + return actions + + +def write_cleanup_actions(path: Path, actions: Iterable[DiskCleanupAction]) -> None: + lines = ["# Disk Cleanup Actions", ""] + actions = list(actions) + if not actions: + lines.append("- No cleanup actions executed.") + else: + for a in actions: + lines.append( + f"- [{a.timestamp_utc}] action={a.action} target=`{a.target}` status={a.status} " + f"reclaimed_mb={a.reclaimed_mb:.2f} reason={a.reason}" + ) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("\n".join(lines), encoding="utf-8") + + +def write_disk_guard_report( + path: Path, + snapshots: Iterable[DiskSnapshot], + actions: Iterable[DiskCleanupAction], + *, + min_free_gb: float, +) -> None: + snaps = list(snapshots) + acts = list(actions) + lines = [ + "# Disk Guard Report", + "", + f"- Min free threshold (GB): `{min_free_gb}`", + f"- Snapshots captured: `{len(snaps)}`", + f"- Cleanup actions: `{len(acts)}`", + "", + "## Snapshot Timeline", + ] + for s in snaps: + lines.append( + f"- [{s.timestamp_utc}] stage={s.stage} free_gb={s.free_gb:.2f} repo_size_gb={s.repo_size_gb:.2f} " + f"projected_output_gb={s.projected_output_gb:.2f} projected_free_after_gb={s.projected_free_after_gb:.2f} note={s.note}" + ) + lines.extend(["", "## Cleanup Summary"]) + reclaimed = sum(a.reclaimed_mb for a in acts if a.status == "ok") + lines.append(f"- Total reclaimed MB: `{reclaimed:.2f}`") + outside_repo_violations = [a for a in acts if a.reason == "outside_repo_guard" and a.status == "ok"] + lines.append(f"- Outside-repo destructive actions: `{len(outside_repo_violations)}`") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("\n".join(lines), encoding="utf-8") + diff --git a/libs/benchmark/large_library.py b/libs/benchmark/large_library.py new file mode 100644 index 0000000000000000000000000000000000000000..390fc88ff8c5d64924ab5a65200cbb2075086835 --- /dev/null +++ b/libs/benchmark/large_library.py @@ -0,0 +1,601 @@ +from __future__ import annotations + +import json +import re +import subprocess +import urllib.parse +from pathlib import Path +from typing import Any, Dict, Iterable, List + +import numpy as np +import pandas as pd +import requests +from rdkit import Chem, DataStructs +from rdkit.Chem import AllChem +from rdkit.Chem.Scaffolds import MurckoScaffold + + +def _curl_get_text(url: str, timeout: int = 30) -> str: + cp = subprocess.run( + [ + "curl", + "-L", + "--silent", + "--show-error", + "--fail", + "--retry", + "2", + "--retry-delay", + "1", + "--max-time", + str(int(timeout)), + url, + ], + capture_output=True, + text=True, + check=False, + ) + if cp.returncode != 0: + raise RuntimeError(f"curl failed for {url}: {cp.stderr.strip()}") + return cp.stdout + + +def _http_json(url: str, timeout: int = 30) -> Dict[str, Any]: + # Prefer curl on this workstation because requests+TLS has been unstable. + try: + return json.loads(_curl_get_text(url, timeout=timeout)) + except Exception: + pass + r = requests.get(url, timeout=timeout) + r.raise_for_status() + return r.json() + + +def _http_text(url: str, timeout: int = 60) -> str: + try: + return _curl_get_text(url, timeout=timeout) + except Exception: + pass + r = requests.get(url, timeout=timeout) + r.raise_for_status() + return r.text + + +def _canonicalize_smiles(smiles: str) -> str | None: + mol = Chem.MolFromSmiles(str(smiles)) + if mol is None: + return None + return Chem.MolToSmiles(mol, canonical=True) + + +def _morgan_bv(smiles: str, nbits: int = 2048): + mol = Chem.MolFromSmiles(smiles) + if mol is None: + return None + return AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=nbits) + + +def _tanimoto(smiles_a: str, smiles_b: str) -> float: + fp_a = _morgan_bv(smiles_a) + fp_b = _morgan_bv(smiles_b) + if fp_a is None or fp_b is None: + return 0.0 + return float(DataStructs.TanimotoSimilarity(fp_a, fp_b)) + + +def _scaffold_smiles(smiles: str) -> str | None: + mol = Chem.MolFromSmiles(smiles) + if mol is None: + return None + try: + return MurckoScaffold.MurckoScaffoldSmiles(mol=mol) + except Exception: + return None + + +def _chemcomp_info(comp_id: str) -> Dict[str, Any]: + d = _http_json(f"https://data.rcsb.org/rest/v1/core/chemcomp/{comp_id}", timeout=30) + desc = d.get("rcsb_chem_comp_descriptor", {}) + smiles = desc.get("SMILES_stereo") or desc.get("SMILES") + return { + "comp_id": comp_id, + "name": d.get("chem_comp", {}).get("name"), + "formula_weight": d.get("chem_comp", {}).get("formula_weight"), + "smiles": smiles, + "inchi_key": desc.get("InChIKey"), + } + + +def _download_pdb(pdb_id: str, out_path: Path) -> Path: + out_path.parent.mkdir(parents=True, exist_ok=True) + url = f"https://files.rcsb.org/download/{pdb_id}.pdb" + out_path.write_text(_http_text(url, timeout=60), encoding="utf-8") + return out_path + + +def _pubchem_similarity_cids(smiles: str, threshold: int, max_records: int) -> list[int]: + enc = urllib.parse.quote(smiles, safe="") + url = ( + "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/" + f"{enc}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}" + ) + try: + d = _http_json(url, timeout=30) + cids = [int(x) for x in d.get("IdentifierList", {}).get("CID", [])] + if cids: + return cids + except Exception: + pass + + # CID-based fallback for molecules where SMILES endpoint is sparse. + cid_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/{enc}/cids/JSON" + try: + cands = [int(x) for x in _http_json(cid_url, timeout=20).get("IdentifierList", {}).get("CID", [])] + except Exception: + return [] + if not cands: + return [] + cid = cands[0] + sim_url = ( + "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/cid/" + f"{cid}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}" + ) + try: + return [int(x) for x in _http_json(sim_url, timeout=30).get("IdentifierList", {}).get("CID", [])] + except Exception: + return [] + + +def _pubchem_properties_for_cids(cids: Iterable[int]) -> pd.DataFrame: + cids = list(cids) + if not cids: + return pd.DataFrame( + columns=[ + "cid", + "smiles", + "molecular_formula", + "molecular_weight", + "xlogp", + "tpsa", + "hbd", + "hba", + "rotatable_bonds", + "heavy_atom_count", + ] + ) + + rows: list[dict[str, Any]] = [] + # 200 CIDs/request is a stable balance on PubChem for URL size and throughput. + chunk_size = 200 + for i in range(0, len(cids), chunk_size): + chunk = cids[i : i + chunk_size] + joined = ",".join(str(x) for x in chunk) + url = ( + "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/" + f"{joined}/property/SMILES,ConnectivitySMILES,MolecularFormula,MolecularWeight," + "XLogP,TPSA,HBondDonorCount,HBondAcceptorCount,RotatableBondCount,HeavyAtomCount/JSON" + ) + props = [] + for _attempt in range(3): + try: + props = _http_json(url, timeout=30).get("PropertyTable", {}).get("Properties", []) + except Exception: + props = [] + if props: + break + if not props: + continue + for p in props: + rows.append( + { + "cid": int(p.get("CID")), + "smiles": str(p.get("SMILES") or p.get("ConnectivitySMILES") or ""), + "molecular_formula": p.get("MolecularFormula"), + "molecular_weight": p.get("MolecularWeight"), + "xlogp": p.get("XLogP"), + "tpsa": p.get("TPSA"), + "hbd": p.get("HBondDonorCount"), + "hba": p.get("HBondAcceptorCount"), + "rotatable_bonds": p.get("RotatableBondCount"), + "heavy_atom_count": p.get("HeavyAtomCount"), + } + ) + return pd.DataFrame(rows) + + +def _fetch_chembl_smiles(target_chembl_id: str, max_rows: int) -> pd.DataFrame: + if int(max_rows) <= 0: + return pd.DataFrame( + columns=[ + "smiles", + "molecule_chembl_id", + "assay_chembl_id", + "standard_type", + "standard_units", + "standard_value", + "source_database", + ] + ) + rows: list[dict[str, Any]] = [] + limit = 1000 + offset = 0 + while len(rows) < max_rows: + url = ( + "https://www.ebi.ac.uk/chembl/api/data/activity.json" + f"?target_chembl_id={target_chembl_id}&limit={limit}&offset={offset}" + ) + try: + d = _http_json(url, timeout=30) + except Exception: + break + acts = d.get("activities", []) + if not acts: + break + for a in acts: + smi = _canonicalize_smiles(str(a.get("canonical_smiles") or "")) + if smi is None: + continue + rows.append( + { + "smiles": smi, + "molecule_chembl_id": a.get("molecule_chembl_id"), + "assay_chembl_id": a.get("assay_chembl_id"), + "standard_type": a.get("standard_type"), + "standard_units": a.get("standard_units"), + "standard_value": a.get("standard_value"), + "source_database": "ChEMBL", + } + ) + if len(rows) >= max_rows: + break + offset += limit + if d.get("page_meta", {}).get("next") is None: + break + return pd.DataFrame(rows) + + +def _generate_fallback_smiles(seed_smiles: str, needed: int) -> List[str]: + """Conservative, deterministic fallback if database retrieval is insufficient.""" + variants: List[str] = [] + candidates = [seed_smiles] + replacements = [ + ("Cl", "F"), + ("F", "Cl"), + ("OC", "OCC"), + ("CC", "CCC"), + ] + while candidates and len(variants) < needed: + smi = candidates.pop(0) + for a, b in replacements: + if a not in smi: + continue + cand = smi.replace(a, b, 1) + c = _canonicalize_smiles(cand) + if c is None: + continue + if c not in variants: + variants.append(c) + if len(variants) >= needed: + break + return variants + + +def build_large_benchmark_library(config: Dict[str, Any], root: Path, logger) -> Dict[str, Any]: + dataset_cfg = config["benchmark_dataset"] + target_cfg = config["target"] + ref_cfg = config["reference"] + + out_dir = root / dataset_cfg["output_dir"] + out_dir.mkdir(parents=True, exist_ok=True) + + reference_path = out_dir / "reference_ligands.csv" + raw_path = out_dir / "shared_library_raw.csv" + dedup_path = out_dir / "shared_library_dedup.csv" + shuffled_path = out_dir / "shared_library_shuffled.csv" + provenance_path = out_dir / "ligand_provenance.csv" + metadata_path = out_dir / "ligand_metadata.csv" + similarity_path = out_dir / "similarity_distribution.csv" + reuse_existing = bool(dataset_cfg.get("reuse_existing", True)) + + required = [reference_path, raw_path, dedup_path, shuffled_path, provenance_path, metadata_path] + docking_target_path = root / target_cfg["docking_target_path"] + if reuse_existing and all(p.exists() for p in required): + if not similarity_path.exists(): + dedup_existing = pd.read_csv(dedup_path) + _write_similarity_distribution(dedup_existing, similarity_path) + if not docking_target_path.exists(): + _download_pdb(str(ref_cfg["pdb_id"]), docking_target_path) + return { + "reference_df": pd.read_csv(reference_path), + "raw_df": pd.read_csv(raw_path), + "dedup_df": pd.read_csv(dedup_path), + "shuffled_df": pd.read_csv(shuffled_path), + "provenance_df": pd.read_csv(provenance_path), + "metadata_df": pd.read_csv(metadata_path), + "similarity_df": pd.read_csv(similarity_path), + "target_path": docking_target_path, + "out_dir": out_dir, + } + + ref_smiles_cfg = str(ref_cfg.get("reference_smiles") or dataset_cfg.get("reference_smiles") or "").strip() + ref_name_cfg = str(ref_cfg.get("reference_name") or dataset_cfg.get("reference_name") or "").strip() + ref_formula_weight_cfg = dataset_cfg.get("reference_formula_weight", np.nan) + ref_comp: Dict[str, Any] + if ref_smiles_cfg: + ref_smiles = _canonicalize_smiles(ref_smiles_cfg) + if ref_smiles is None: + raise RuntimeError("Invalid configured reference_smiles") + ref_comp = { + "comp_id": str(ref_cfg["ligand_comp_id"]), + "name": ref_name_cfg or str(ref_cfg["ligand_comp_id"]), + "formula_weight": ref_formula_weight_cfg, + "smiles": ref_smiles, + "inchi_key": "", + } + else: + ref_comp = _chemcomp_info(str(ref_cfg["ligand_comp_id"])) + ref_smiles = _canonicalize_smiles(str(ref_comp["smiles"] or "")) + if ref_smiles is None: + raise RuntimeError("Invalid reference SMILES from RCSB chemcomp endpoint") + + ref_df = pd.DataFrame( + [ + { + "reference_id": str(ref_cfg["reference_id"]), + "pdb_id": str(ref_cfg["pdb_id"]), + "ligand_comp_id": str(ref_cfg["ligand_comp_id"]), + "ligand_name": ref_comp["name"], + "reference_smiles": ref_smiles, + "source_structure": str(ref_cfg["pdb_id"]), + } + ] + ) + ref_df.to_csv(reference_path, index=False) + + _download_pdb(str(ref_cfg["pdb_id"]), docking_target_path) + + target_size = int(dataset_cfg.get("target_size", 7500)) + min_keep = float(dataset_cfg.get("min_similarity_keep", 0.25)) + max_records = int(dataset_cfg.get("pubchem_max_records", 50000)) + thresholds = [int(x) for x in dataset_cfg.get("pubchem_thresholds", [95, 90, 85, 80, 75, 70, 65, 60, 55, 50])] + + records: Dict[str, Dict[str, Any]] = {} + for thr in thresholds: + cids = _pubchem_similarity_cids(ref_smiles, threshold=thr, max_records=max_records) + # Keep API workload bounded to what is still needed for target size. + remaining = max(0, int(target_size) - len(records)) + if remaining <= 0: + break + # Query a modest over-sampling margin to compensate duplicates/canonicalization. + limit = min(len(cids), max(remaining + 600, 1200)) + cids = cids[:limit] + props = _pubchem_properties_for_cids(cids) + if props.empty: + continue + for row in props.itertuples(index=False): + c = _canonicalize_smiles(str(row.smiles)) + if c is None: + continue + sim = _tanimoto(ref_smiles, c) + if sim < min_keep: + continue + prev = records.get(c) + base = { + "ligand_id": "", + "smiles": c, + "source": "database", + "source_database": "PubChem", + "source_type": "retrieved", + "original_database_id": f"CID:{int(row.cid)}", + "reference_similarity": float(sim), + "scaffold_core": _scaffold_smiles(c), + "scaffold_match": int(_scaffold_smiles(c) == _scaffold_smiles(ref_smiles)), + "retrieval_threshold": int(thr), + "is_reference": False, + "parent_reference_ligand": str(ref_cfg["reference_id"]), + "molecular_formula": row.molecular_formula, + "molecular_weight": row.molecular_weight, + "xlogp": row.xlogp, + "tpsa": row.tpsa, + "hbd": row.hbd, + "hba": row.hba, + "rotatable_bonds": row.rotatable_bonds, + "heavy_atom_count": row.heavy_atom_count, + } + if prev is None or (float(base["reference_similarity"]) > float(prev["reference_similarity"])): + records[c] = base + logger.info("PubChem threshold=%s cumulative=%s", thr, len(records)) + if len(records) >= int(target_size * 1.2): + break + + # ChEMBL supplement if needed (still database-first). + if len(records) < target_size: + chembl_target = str(dataset_cfg.get("chembl_target_id", "CHEMBL5023")) + chembl_max = int(dataset_cfg.get("chembl_max_rows", 25000)) + cdf = _fetch_chembl_smiles(target_chembl_id=chembl_target, max_rows=chembl_max) + for row in cdf.itertuples(index=False): + c = _canonicalize_smiles(str(row.smiles)) + if c is None or c in records: + continue + sim = _tanimoto(ref_smiles, c) + if sim < min_keep: + continue + records[c] = { + "ligand_id": "", + "smiles": c, + "source": "database", + "source_database": "ChEMBL", + "source_type": "retrieved", + "original_database_id": str(row.molecule_chembl_id or ""), + "reference_similarity": float(sim), + "scaffold_core": _scaffold_smiles(c), + "scaffold_match": int(_scaffold_smiles(c) == _scaffold_smiles(ref_smiles)), + "retrieval_threshold": np.nan, + "is_reference": False, + "parent_reference_ligand": str(ref_cfg["reference_id"]), + "molecular_formula": np.nan, + "molecular_weight": np.nan, + "xlogp": np.nan, + "tpsa": np.nan, + "hbd": np.nan, + "hba": np.nan, + "rotatable_bonds": np.nan, + "heavy_atom_count": np.nan, + } + if len(records) >= int(target_size * 1.2): + break + logger.info("ChEMBL supplement cumulative=%s", len(records)) + + # Ensure reference is present. + records[ref_smiles] = { + "ligand_id": str(ref_cfg["reference_id"]), + "smiles": ref_smiles, + "source": "reference", + "source_database": "RCSB", + "source_type": "reference", + "original_database_id": str(ref_cfg["ligand_comp_id"]), + "reference_similarity": 1.0, + "scaffold_core": _scaffold_smiles(ref_smiles), + "scaffold_match": 1, + "retrieval_threshold": np.nan, + "is_reference": True, + "parent_reference_ligand": str(ref_cfg["reference_id"]), + "molecular_formula": np.nan, + "molecular_weight": ref_comp.get("formula_weight"), + "xlogp": np.nan, + "tpsa": np.nan, + "hbd": np.nan, + "hba": np.nan, + "rotatable_bonds": np.nan, + "heavy_atom_count": np.nan, + } + + raw_df = pd.DataFrame(records.values()) + raw_df = raw_df.sort_values(["is_reference", "reference_similarity"], ascending=[False, False]).reset_index(drop=True) + raw_df.to_csv(raw_path, index=False) + + dedup_df = raw_df.drop_duplicates(subset=["smiles"], keep="first").reset_index(drop=True) + + allow_generated = bool(dataset_cfg.get("allow_generated_fallback", True)) + if dedup_df.shape[0] < target_size and allow_generated: + need = int(target_size - dedup_df.shape[0]) + generated = _generate_fallback_smiles(seed_smiles=ref_smiles, needed=need * 2) + gen_rows = [] + for s in generated: + if s in set(dedup_df["smiles"].astype(str).tolist()): + continue + sim = _tanimoto(ref_smiles, s) + gen_rows.append( + { + "ligand_id": "", + "smiles": s, + "source": "generated", + "source_database": "generated", + "source_type": "generated", + "original_database_id": "", + "reference_similarity": float(sim), + "scaffold_core": _scaffold_smiles(s), + "scaffold_match": int(_scaffold_smiles(s) == _scaffold_smiles(ref_smiles)), + "retrieval_threshold": np.nan, + "is_reference": False, + "parent_reference_ligand": str(ref_cfg["reference_id"]), + "molecular_formula": np.nan, + "molecular_weight": np.nan, + "xlogp": np.nan, + "tpsa": np.nan, + "hbd": np.nan, + "hba": np.nan, + "rotatable_bonds": np.nan, + "heavy_atom_count": np.nan, + } + ) + if len(gen_rows) >= need: + break + if gen_rows: + dedup_df = pd.concat([dedup_df, pd.DataFrame(gen_rows)], axis=0, ignore_index=True) + + dedup_df = dedup_df.sort_values(["is_reference", "source_type", "reference_similarity"], ascending=[False, True, False]).reset_index( + drop=True + ) + if dedup_df.shape[0] > target_size: + refs = dedup_df[dedup_df["is_reference"].astype(bool)].copy() + non_refs = dedup_df[~dedup_df["is_reference"].astype(bool)].copy() + keep = max(0, target_size - refs.shape[0]) + dedup_df = pd.concat([refs, non_refs.head(keep)], axis=0, ignore_index=True) + + dedup_df = dedup_df.reset_index(drop=True) + for i in range(dedup_df.shape[0]): + if bool(dedup_df.loc[i, "is_reference"]): + dedup_df.loc[i, "ligand_id"] = str(ref_cfg["reference_id"]) + else: + dedup_df.loc[i, "ligand_id"] = f"lb_{i:05d}" + dedup_df.to_csv(dedup_path, index=False) + + shuffle_seed = int(dataset_cfg.get("shuffle_seed", 1337)) + shuffled_df = dedup_df.sample(frac=1.0, random_state=shuffle_seed).reset_index(drop=True) + shuffled_df["shuffle_seed"] = shuffle_seed + shuffled_df.to_csv(shuffled_path, index=False) + + provenance_df = dedup_df[ + [ + "ligand_id", + "smiles", + "source", + "source_database", + "source_type", + "original_database_id", + "is_reference", + "parent_reference_ligand", + "reference_similarity", + "scaffold_core", + "scaffold_match", + "retrieval_threshold", + ] + ].copy() + provenance_df.to_csv(provenance_path, index=False) + + metadata_df = dedup_df[ + [ + "ligand_id", + "smiles", + "molecular_formula", + "molecular_weight", + "xlogp", + "tpsa", + "hbd", + "hba", + "rotatable_bonds", + "heavy_atom_count", + ] + ].copy() + metadata_df.to_csv(metadata_path, index=False) + similarity_df = _write_similarity_distribution(dedup_df, similarity_path) + + return { + "reference_df": ref_df, + "raw_df": raw_df, + "dedup_df": dedup_df, + "shuffled_df": shuffled_df, + "provenance_df": provenance_df, + "metadata_df": metadata_df, + "similarity_df": similarity_df, + "target_path": docking_target_path, + "out_dir": out_dir, + "shuffle_seed": shuffle_seed, + } + + +def _write_similarity_distribution(df: pd.DataFrame, path: Path) -> pd.DataFrame: + vals = pd.to_numeric(df.get("reference_similarity", pd.Series(dtype=float)), errors="coerce").dropna() + bins = np.linspace(0.0, 1.0, 21) + hist, edges = np.histogram(vals.to_numpy(dtype=float), bins=bins) + out = pd.DataFrame( + { + "bin_left": edges[:-1], + "bin_right": edges[1:], + "count": hist, + "fraction": hist / max(1, int(hist.sum())), + } + ) + out.to_csv(path, index=False) + return out diff --git a/libs/benchmark/multifidelity.py b/libs/benchmark/multifidelity.py new file mode 100644 index 0000000000000000000000000000000000000000..7553f5985b3c594ff4f71b4f07293f124e61db5c --- /dev/null +++ b/libs/benchmark/multifidelity.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict, Iterable, List, Mapping, Sequence, Tuple + +import numpy as np +import pandas as pd + + +@dataclass(frozen=True) +class StoppingControls: + target_rank_percentile: float = 1.0 + peak_patience: int = 32 + min_improvement_delta: float = 0.02 + + +@dataclass(frozen=True) +class ExplorationControls: + stagnation_patience: int = 24 + diversity_boost_strength: float = 0.4 + dominant_window: int = 128 + + +@dataclass(frozen=True) +class UncertaintyControls: + uncertainty_low_threshold: float = 0.35 + uncertainty_patience: int = 32 + expected_gain_threshold: float = 0.03 + + +def enforce_control_limits(cfg: Mapping[str, Any]) -> None: + """Enforce compact control surface to prevent parameter explosion.""" + + groups = { + "stopping": set((cfg.get("stopping") or {}).keys()), + "exploration": set((cfg.get("exploration") or {}).keys()), + "uncertainty": set((cfg.get("uncertainty") or {}).keys()), + } + for name, keys in groups.items(): + if len(keys) > 3: + raise ValueError(f"{name} parameter count exceeds limit (3): {sorted(keys)}") + + +def controls_from_config(cfg: Mapping[str, Any]) -> tuple[StoppingControls, ExplorationControls, UncertaintyControls]: + stop_cfg = cfg.get("stopping") or {} + exp_cfg = cfg.get("exploration") or {} + unc_cfg = cfg.get("uncertainty") or {} + return ( + StoppingControls( + target_rank_percentile=float(stop_cfg.get("target_rank_percentile", 1.0)), + peak_patience=int(stop_cfg.get("peak_patience", 32)), + min_improvement_delta=float(stop_cfg.get("min_improvement_delta", 0.02)), + ), + ExplorationControls( + stagnation_patience=int(exp_cfg.get("stagnation_patience", 24)), + diversity_boost_strength=float(exp_cfg.get("diversity_boost_strength", 0.4)), + dominant_window=int(exp_cfg.get("dominant_window", 128)), + ), + UncertaintyControls( + uncertainty_low_threshold=float(unc_cfg.get("uncertainty_low_threshold", 0.35)), + uncertainty_patience=int(unc_cfg.get("uncertainty_patience", 32)), + expected_gain_threshold=float(unc_cfg.get("expected_gain_threshold", 0.03)), + ), + ) + + +def _safe_float(value: Any, default: float = np.nan) -> float: + try: + x = float(value) + return x if np.isfinite(x) else float(default) + except Exception: + return float(default) + + +def _best_rank_percentile(selected_ids: Sequence[str], truth_map: Mapping[str, Mapping[str, float]]) -> float: + values: List[float] = [] + for lid in selected_ids: + info = truth_map.get(str(lid)) + if info is None: + continue + values.append(float(info.get("rank_percentile", 100.0))) + if not values: + return 100.0 + return float(np.min(np.asarray(values, dtype=float))) + + +def _dominant_cluster_from_recent(selected_rows: Sequence[dict[str, Any]], window: int) -> int | None: + if not selected_rows: + return None + recent = selected_rows[-max(1, int(window)) :] + cnt: Dict[int, int] = {} + for row in recent: + cid = int(_safe_float(row.get("cluster_id", -1), default=-1)) + if cid < 0: + continue + cnt[cid] = cnt.get(cid, 0) + 1 + if not cnt: + return None + return int(max(cnt.items(), key=lambda kv: kv[1])[0]) + + +def _expected_gain_proxy(remaining: pd.DataFrame, incumbent_best: float) -> float: + pred = pd.to_numeric(remaining.get("predicted_score_prebatch", np.nan), errors="coerce").dropna() + if pred.empty: + return 0.0 + optimistic = float(np.quantile(pred.to_numpy(dtype=float), 0.05)) + # Lower score is better. + return float(max(0.0, incumbent_best - optimistic)) + + +def simulate_multifidelity_policy( + order_df: pd.DataFrame, + *, + truth_map: Mapping[str, Mapping[str, float]], + budget: int, + min_budget: int, + max_budget: int, + wall_time_per_dock: float, + max_wall_time_seconds: float | None, + stopping: StoppingControls, + exploration: ExplorationControls, + uncertainty: UncertaintyControls, +) -> tuple[pd.DataFrame, pd.DataFrame]: + """Run compact multifidelity policy simulation on a pre-ranked candidate order. + + Default mode exploits dominant cluster. Diversity fallback is enabled only under + dominant-cluster stagnation, then automatically disabled. + """ + + if order_df.empty: + return order_df.copy(), pd.DataFrame() + + cap = int(max(1, min(int(budget), int(max_budget), int(order_df.shape[0])))) + remaining = order_df.sort_values("step").head(cap).copy().reset_index(drop=True) + + selected_rows: List[dict[str, Any]] = [] + selected_ids: List[str] = [] + trace_rows: List[dict[str, Any]] = [] + + cluster_selected_counts: Dict[int, int] = {} + dominant_cluster: int | None = None + dominant_best_score = np.inf + dominant_stagnant_rounds = 0 + diversity_steps_left = 0 + + rank_history: List[float] = [] + uncertainty_history: List[float] = [] + + stop_reason = "budget_cap_reached" + for i in range(cap): + if remaining.empty: + stop_reason = "pool_exhausted" + break + + if diversity_steps_left > 0: + cluster_counts_now = { + int(_safe_float(c, -1)): int(v) for c, v in cluster_selected_counts.items() if int(c) >= 0 + } + min_seen = min(cluster_counts_now.values()) if cluster_counts_now else 0 + candidate_clusters = {cid for cid, v in cluster_counts_now.items() if v <= min_seen} + cand = remaining[remaining["cluster_id"].isin(candidate_clusters)].head(1) + if cand.empty: + cand = remaining.head(1) + selection_mode = "diversity_fallback" + diversity_steps_left -= 1 + else: + dominant_cluster = _dominant_cluster_from_recent(selected_rows, exploration.dominant_window) + if dominant_cluster is not None: + cand = remaining[remaining["cluster_id"] == dominant_cluster].head(1) + if cand.empty: + cand = remaining.head(1) + selection_mode = "dominant_unavailable" + else: + selection_mode = "dominant_exploit" + else: + cand = remaining.head(1) + selection_mode = "initial_explore" + + row = cand.iloc[0].to_dict() + remaining = remaining.drop(index=int(cand.index[0])).reset_index(drop=True) + + lid = str(row.get("ligand_id")) + cid = int(_safe_float(row.get("cluster_id", -1), -1)) + dscore = _safe_float(row.get("docking_score", np.nan), np.nan) + unc = _safe_float(row.get("predicted_uncertainty_prebatch", np.nan), np.nan) + + selected_rows.append(row) + selected_ids.append(lid) + cluster_selected_counts[cid] = int(cluster_selected_counts.get(cid, 0) + 1) + if np.isfinite(unc): + uncertainty_history.append(float(unc)) + + if dominant_cluster is not None and cid == dominant_cluster: + if np.isfinite(dscore) and (dscore < dominant_best_score - stopping.min_improvement_delta): + dominant_best_score = float(dscore) + dominant_stagnant_rounds = 0 + else: + dominant_stagnant_rounds += 1 + + best_rank_pct = _best_rank_percentile(selected_ids, truth_map) + rank_history.append(best_rank_pct) + + patience = max(2, int(stopping.peak_patience)) + if len(rank_history) >= patience: + slope = float(rank_history[-patience] - rank_history[-1]) + else: + slope = np.nan + + incumbent_best = float(np.nanmin(pd.to_numeric(pd.DataFrame(selected_rows)["docking_score"], errors="coerce").to_numpy(dtype=float))) + expected_gain = _expected_gain_proxy(remaining, incumbent_best) + + u_pat = max(2, int(uncertainty.uncertainty_patience)) + recent_unc = uncertainty_history[-u_pat:] if uncertainty_history else [] + mean_unc = float(np.mean(np.asarray(recent_unc, dtype=float))) if recent_unc else np.nan + + est_wall = float((i + 1) * wall_time_per_dock) + rank_target_hit = bool(best_rank_pct <= float(stopping.target_rank_percentile)) + slope_stagnation = bool(np.isfinite(slope) and abs(float(slope)) <= float(stopping.min_improvement_delta)) + uncertainty_low = bool(np.isfinite(mean_unc) and mean_unc <= float(uncertainty.uncertainty_low_threshold)) + gain_low = bool(float(expected_gain) <= float(uncertainty.expected_gain_threshold)) + dominant_plateau = bool(dominant_stagnant_rounds >= int(exploration.stagnation_patience)) + + allow_stop = bool((i + 1) >= int(min_budget)) + stop_now = False + + if allow_stop and rank_target_hit and slope_stagnation and gain_low and uncertainty_low: + stop_now = True + stop_reason = "early_peak_dynamic_stop" + elif max_wall_time_seconds is not None and np.isfinite(float(max_wall_time_seconds)) and est_wall >= float(max_wall_time_seconds): + stop_now = True + stop_reason = "max_wall_time_reached" + + # Diversity fallback is only activated on dominant-cluster stagnation. + fallback_triggered = False + if ( + not stop_now + and diversity_steps_left <= 0 + and dominant_plateau + and (i + 1) >= int(min_budget) + and not rank_target_hit + ): + diversity_steps_left = max(1, int(round(8.0 * float(exploration.diversity_boost_strength)))) + fallback_triggered = True + + trace_rows.append( + { + "step": int(i), + "ligand_id": lid, + "selection_mode": selection_mode, + "stop_reason": stop_reason if stop_now else "", + "best_rank_percentile": float(best_rank_pct), + "rank_improvement_slope": float(slope) if np.isfinite(slope) else np.nan, + "expected_gain_proxy": float(expected_gain), + "mean_uncertainty": float(mean_unc) if np.isfinite(mean_unc) else np.nan, + "rank_target_hit": bool(rank_target_hit), + "slope_stagnation": bool(slope_stagnation), + "uncertainty_low": bool(uncertainty_low), + "dominant_plateau": bool(dominant_plateau), + "fallback_triggered": bool(fallback_triggered), + "diversity_steps_left": int(diversity_steps_left), + "dominant_cluster": int(dominant_cluster) if dominant_cluster is not None else -1, + "dynamic_budget_cap": int(cap), + "estimated_wall_seconds": float(est_wall), + } + ) + + if stop_now: + break + + selected_df = pd.DataFrame(selected_rows).reset_index(drop=True) + if not selected_df.empty: + selected_df = selected_df.copy() + selected_df["step"] = np.arange(selected_df.shape[0], dtype=int) + trace_df = pd.DataFrame(trace_rows) + return selected_df, trace_df diff --git a/libs/benchmark/ordering.py b/libs/benchmark/ordering.py new file mode 100644 index 0000000000000000000000000000000000000000..bc940275f5765fafb717d8b60338f4cfb2f8ef5d --- /dev/null +++ b/libs/benchmark/ordering.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import random +from typing import Dict, Iterable, List + + +def cluster_naive_order( + ligand_ids: Iterable[str], + cluster_map: Dict[str, int], + seed: int, +) -> List[str]: + """ + Static cluster baseline ordering: + 1) one representative per cluster (cluster round-robin), + 2) then remaining members cluster-by-cluster. + """ + ids = [str(x) for x in ligand_ids] + by_cluster: Dict[int, List[str]] = {} + for lid in ids: + by_cluster.setdefault(int(cluster_map.get(lid, -1)), []).append(lid) + + rng = random.Random(int(seed)) + cluster_ids = sorted(by_cluster.keys()) + rng.shuffle(cluster_ids) + for cid in cluster_ids: + rng.shuffle(by_cluster[cid]) + + order: List[str] = [] + for cid in cluster_ids: + if by_cluster[cid]: + order.append(by_cluster[cid][0]) + + for cid in cluster_ids: + members = by_cluster[cid][1:] + order.extend(members) + + seen = set() + out: List[str] = [] + for lid in order: + if lid in seen: + continue + seen.add(lid) + out.append(lid) + return out + diff --git a/libs/benchmark/overnight_stop.py b/libs/benchmark/overnight_stop.py new file mode 100644 index 0000000000000000000000000000000000000000..476a55018cb50a46ff70986ee150175c1b31242f --- /dev/null +++ b/libs/benchmark/overnight_stop.py @@ -0,0 +1,298 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict, Mapping, Sequence + +import numpy as np +import pandas as pd + + +STOP_MODELS = ( + "percentile_target", + "regret_constrained", + "utility_maximizing", + "hybrid", +) + +OBJECTIVES = ( + "quality_per_time", + "quality_per_docking", + "rank_percentile_minimization", + "regret_constrained_utility", + "target_percentile_attainment", + "hybrid_objective", +) + + +@dataclass(frozen=True) +class StopModelParams: + target_percentile: float = 1.0 + probability_threshold: float = 0.80 + epsilon_quality: float = 0.10 + min_budget: int = 100 + max_budget: int = 10000 + gain_threshold: float = 0.03 + utility_lambda: float = 0.001 + utility_threshold: float = 0.0 + uncertainty_threshold: float = 0.35 + confirmation_window: int = 24 + min_improvement_delta: float = 0.02 + + +def _sigmoid(x: float) -> float: + z = float(np.clip(x, -50.0, 50.0)) + return float(1.0 / (1.0 + np.exp(-z))) + + +def _safe_float(v: Any, default: float = np.nan) -> float: + try: + x = float(v) + return x if np.isfinite(x) else float(default) + except Exception: + return float(default) + + +def _best_rank_percentile(selected_ids: Sequence[str], truth_map: Mapping[str, Mapping[str, float]]) -> float: + vals = [] + for lid in selected_ids: + info = truth_map.get(str(lid)) + if info is None: + continue + vals.append(_safe_float(info.get("rank_percentile"), 100.0)) + if not vals: + return 100.0 + return float(np.nanmin(np.asarray(vals, dtype=float))) + + +def estimate_marginal_expected_gain( + *, + remaining_df: pd.DataFrame, + incumbent_best_score: float, + uncertainty_weight: float = 0.5, +) -> float: + pred = pd.to_numeric(remaining_df.get("predicted_score_prebatch", np.nan), errors="coerce").dropna().to_numpy(dtype=float) + if pred.size == 0: + return 0.0 + unc = pd.to_numeric(remaining_df.get("predicted_uncertainty_prebatch", np.nan), errors="coerce").dropna().to_numpy(dtype=float) + if unc.size == 0: + unc = np.full(pred.shape[0], np.nanstd(pred) if pred.size > 1 else 1.0) + if unc.size != pred.size: + unc = np.full(pred.shape[0], np.nanmean(unc) if unc.size else 1.0) + optimistic = pred - float(max(0.0, uncertainty_weight)) * np.abs(unc) + optimistic_best = float(np.nanmin(optimistic)) if np.isfinite(optimistic).any() else float(np.nanmin(pred)) + if not np.isfinite(optimistic_best): + return 0.0 + return float(max(0.0, float(incumbent_best_score) - optimistic_best)) + + +def estimate_probability_target_percentile( + *, + best_rank_percentile: float, + target_percentile: float, + marginal_expected_gain: float, + mean_uncertainty: float, + improvement_slope: float, + params: StopModelParams, +) -> float: + p_rank = _sigmoid((float(target_percentile) - float(best_rank_percentile)) / max(0.25, float(target_percentile))) + p_gain = _sigmoid((float(params.gain_threshold) - float(marginal_expected_gain)) / max(1e-3, float(params.gain_threshold))) + p_unc = 0.5 if not np.isfinite(mean_uncertainty) else _sigmoid( + (float(params.uncertainty_threshold) - float(mean_uncertainty)) / max(1e-3, float(params.uncertainty_threshold)) + ) + p_slope = 0.5 if not np.isfinite(improvement_slope) else _sigmoid( + (float(params.min_improvement_delta) - abs(float(improvement_slope))) / max(1e-3, float(params.min_improvement_delta)) + ) + return float(np.clip(0.45 * p_rank + 0.25 * p_gain + 0.15 * p_unc + 0.15 * p_slope, 0.0, 1.0)) + + +def _rank_slope(rank_history: Sequence[float], window: int) -> float: + w = max(2, int(window)) + if len(rank_history) < w: + return float("nan") + a = float(rank_history[-w]) + b = float(rank_history[-1]) + return float((a - b) / max(1, w - 1)) + + +def _stop_condition( + model_name: str, + *, + params: StopModelParams, + n_evaluated: int, + max_budget: int, + estimated_probability_target_percentile: float, + marginal_expected_gain: float, + expected_quality_loss: float, + utility_value: float, + mean_uncertainty: float, + improvement_slope: float, +) -> tuple[bool, str]: + if int(n_evaluated) >= int(max_budget): + return True, "max_budget_reached" + if int(n_evaluated) < int(params.min_budget): + return False, "below_min_budget" + + if model_name == "percentile_target": + if ( + float(estimated_probability_target_percentile) >= float(params.probability_threshold) + and float(marginal_expected_gain) <= float(params.gain_threshold) + ): + return True, "percentile_target_stop" + return False, "continue_percentile_target" + + if model_name == "regret_constrained": + if ( + float(expected_quality_loss) <= float(params.epsilon_quality) + and float(marginal_expected_gain) <= float(params.gain_threshold) + ): + return True, "regret_constrained_stop" + return False, "continue_regret_constrained" + + if model_name == "utility_maximizing": + if float(utility_value) <= float(params.utility_threshold): + return True, "utility_maximizing_stop" + return False, "continue_utility_maximizing" + + if model_name == "hybrid": + hybrid_ready = ( + float(estimated_probability_target_percentile) >= float(params.probability_threshold) + and float(marginal_expected_gain) <= float(params.gain_threshold) + and (not np.isfinite(mean_uncertainty) or float(mean_uncertainty) <= float(params.uncertainty_threshold)) + and (not np.isfinite(improvement_slope) or abs(float(improvement_slope)) <= float(params.min_improvement_delta)) + ) + if hybrid_ready or ( + float(expected_quality_loss) <= float(params.epsilon_quality) and float(utility_value) <= float(params.utility_threshold) + ): + return True, "hybrid_stop" + return False, "continue_hybrid" + + raise ValueError(f"Unsupported stop model: {model_name}") + + +def simulate_stop_model( + order_df: pd.DataFrame, + *, + truth_map: Mapping[str, Mapping[str, float]], + model_name: str, + budget: int, + params: StopModelParams, + wall_time_per_dock: float, + uncertainty_weight: float = 0.5, +) -> tuple[pd.DataFrame, pd.DataFrame]: + if model_name not in STOP_MODELS: + raise ValueError(f"Unsupported stop model `{model_name}`") + if order_df.empty: + return order_df.copy(), pd.DataFrame() + + cap = int(max(1, min(int(budget), int(params.max_budget), int(order_df.shape[0])))) + ordered = order_df.sort_values("step").head(cap).copy().reset_index(drop=True) + + selected_rows: list[dict[str, Any]] = [] + selected_ids: list[str] = [] + rank_history: list[float] = [] + score_history: list[float] = [] + trace_rows: list[dict[str, Any]] = [] + + for i, row in ordered.iterrows(): + row_d = row.to_dict() + selected_rows.append(row_d) + lid = str(row_d.get("ligand_id")) + selected_ids.append(lid) + + dscore = _safe_float(row_d.get("docking_score"), np.nan) + if np.isfinite(dscore): + score_history.append(float(dscore)) + incumbent_best = float(np.nanmin(np.asarray(score_history, dtype=float))) if score_history else float("inf") + + best_pct = _best_rank_percentile(selected_ids, truth_map) + rank_history.append(best_pct) + slope = _rank_slope(rank_history, int(params.confirmation_window)) + + remaining = ordered.iloc[i + 1 :].copy() + marginal_gain = estimate_marginal_expected_gain( + remaining_df=remaining, + incumbent_best_score=incumbent_best, + uncertainty_weight=float(uncertainty_weight), + ) + recent_unc = pd.to_numeric(remaining.head(32).get("predicted_uncertainty_prebatch", np.nan), errors="coerce").dropna() + mean_unc = float(recent_unc.mean()) if not recent_unc.empty else float("nan") + p_target = estimate_probability_target_percentile( + best_rank_percentile=best_pct, + target_percentile=float(params.target_percentile), + marginal_expected_gain=marginal_gain, + mean_uncertainty=mean_unc, + improvement_slope=slope, + params=params, + ) + expected_quality_loss = float(marginal_gain / max(1.0, abs(incumbent_best))) if np.isfinite(incumbent_best) else float("inf") + utility_value = float(marginal_gain - float(params.utility_lambda) * max(1e-9, float(wall_time_per_dock))) + + stop, reason = _stop_condition( + model_name=model_name, + params=params, + n_evaluated=int(i + 1), + max_budget=min(cap, int(params.max_budget)), + estimated_probability_target_percentile=p_target, + marginal_expected_gain=marginal_gain, + expected_quality_loss=expected_quality_loss, + utility_value=utility_value, + mean_uncertainty=mean_unc, + improvement_slope=slope, + ) + trace_rows.append( + { + "step": int(i), + "ligand_id": lid, + "stop_model": model_name, + "best_rank_percentile": float(best_pct), + "improvement_slope": float(slope) if np.isfinite(slope) else np.nan, + "estimated_probability_target_percentile": float(p_target), + "marginal_expected_gain": float(marginal_gain), + "expected_quality_loss": float(expected_quality_loss), + "utility_value": float(utility_value), + "mean_uncertainty": float(mean_unc) if np.isfinite(mean_unc) else np.nan, + "stop": bool(stop), + "stop_reason": str(reason), + "estimated_wall_time_seconds": float((i + 1) * max(1e-9, float(wall_time_per_dock))), + } + ) + if stop: + break + + selected_df = pd.DataFrame(selected_rows) + if not selected_df.empty: + selected_df["step"] = np.arange(selected_df.shape[0], dtype=int) + return selected_df, pd.DataFrame(trace_rows) + + +def objective_value(row: Mapping[str, Any], objective: str, target_percentile: float = 1.0) -> float: + rank_pct = _safe_float(row.get("best_found_rank_percentile"), 100.0) + q_loss = _safe_float(row.get("quality_loss_vs_exhaustive_best"), 1.0) + red = _safe_float(row.get("docking_reduction_fraction"), 0.0) + qpt = _safe_float(row.get("quality_per_time"), 0.0) + qpd = _safe_float(row.get("quality_per_docking"), 0.0) + p_est = _safe_float(row.get("estimated_probability_target_percentile"), 0.0) + gain = _safe_float(row.get("marginal_expected_gain"), 0.0) + + if objective == "quality_per_time": + return float(qpt) + if objective == "quality_per_docking": + return float(qpd) + if objective == "rank_percentile_minimization": + return float(-rank_pct) + if objective == "regret_constrained_utility": + return float((1.0 - q_loss) + 0.5 * red - 0.2 * gain) + if objective == "target_percentile_attainment": + hit = 1.0 if float(rank_pct) <= float(target_percentile) else 0.0 + return float(2.0 * hit + 0.5 * red + p_est - 0.1 * gain) + if objective == "hybrid_objective": + return float(0.35 * qpt + 0.25 * qpd + 0.25 * (1.0 - q_loss) + 0.15 * p_est - 0.15 * (rank_pct / 100.0)) + raise ValueError(f"Unsupported objective `{objective}`") + + +def is_trivial_objective_solution(best_budget: int, budget_grid: Sequence[int]) -> bool: + if not budget_grid: + return False + low = min(int(x) for x in budget_grid) + return int(best_budget) <= int(low) + diff --git a/libs/benchmark/policy_repair.py b/libs/benchmark/policy_repair.py new file mode 100644 index 0000000000000000000000000000000000000000..3778fe2d4a29527b9a6b7792e40ee595245fdb70 --- /dev/null +++ b/libs/benchmark/policy_repair.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, Iterable, List, Tuple + +from libs.adaptive.scheduler import AdaptiveScheduler + + +@dataclass(frozen=True) +class AdaptivePolicyVariant: + name: str + stop_mode: str # hard | soft | none + cluster_bootstrap_rounds: int = 0 + min_cluster_coverage: float = 0.0 + min_hypercluster_coverage: float = 0.0 + soft_recovery_batches: int = 0 + soft_threshold_relax: float = 0.0 + soft_model_weight_cap: float = 1.0 + soft_exploration_boost: float = 0.0 + pre_floor_model_weight_cap: float = 1.0 + max_soft_recoveries: int = 1 + epsilon_quality: float = 0.10 + acceptable_regret: float = 0.10 + min_budget: int = 250 + max_budget: int = 10000 + regret_patience_rounds: int = 6 + regret_uncertainty_multiplier: float = 0.5 + regret_min_cluster_coverage: float = 0.20 + regret_min_hypercluster_coverage: float = 0.20 + + +@dataclass +class PolicyRuntimeState: + soft_recovery_remaining: int = 0 + soft_recoveries_used: int = 0 + + +def default_policy_variants() -> Dict[str, AdaptivePolicyVariant]: + return { + "adaptive_hard_stop": AdaptivePolicyVariant( + name="adaptive_hard_stop", + stop_mode="hard", + ), + "adaptive_soft_stop": AdaptivePolicyVariant( + name="adaptive_soft_stop", + stop_mode="soft", + soft_recovery_batches=16, + soft_threshold_relax=0.35, + soft_model_weight_cap=0.45, + soft_exploration_boost=0.25, + pre_floor_model_weight_cap=1.0, + max_soft_recoveries=1, + ), + "adaptive_no_stop": AdaptivePolicyVariant( + name="adaptive_no_stop", + stop_mode="none", + ), + "adaptive_cluster_bootstrap": AdaptivePolicyVariant( + name="adaptive_cluster_bootstrap", + stop_mode="hard", + cluster_bootstrap_rounds=24, + ), + "adaptive_soft_stop_cluster_floor": AdaptivePolicyVariant( + name="adaptive_soft_stop_cluster_floor", + stop_mode="soft", + cluster_bootstrap_rounds=20, + min_cluster_coverage=0.60, + min_hypercluster_coverage=0.55, + soft_recovery_batches=20, + soft_threshold_relax=0.40, + soft_model_weight_cap=0.40, + soft_exploration_boost=0.30, + pre_floor_model_weight_cap=0.35, + max_soft_recoveries=2, + ), + } + + +def regret_stop_variant( + *, + name: str = "adaptive_budgeted_regret_stop", + epsilon_quality: float = 0.10, + acceptable_regret: float = 0.10, + min_budget: int = 250, + max_budget: int = 10000, + regret_patience_rounds: int = 6, + regret_uncertainty_multiplier: float = 0.50, + regret_min_cluster_coverage: float = 0.20, + regret_min_hypercluster_coverage: float = 0.20, +) -> AdaptivePolicyVariant: + return AdaptivePolicyVariant( + name=name, + stop_mode="regret", + epsilon_quality=float(epsilon_quality), + acceptable_regret=float(acceptable_regret), + min_budget=int(min_budget), + max_budget=int(max_budget), + regret_patience_rounds=int(regret_patience_rounds), + regret_uncertainty_multiplier=float(regret_uncertainty_multiplier), + regret_min_cluster_coverage=float(regret_min_cluster_coverage), + regret_min_hypercluster_coverage=float(regret_min_hypercluster_coverage), + ) + + +def coverage_fraction(sampled: Iterable[int], total: int) -> float: + if total <= 0: + return 0.0 + return float(len(set(sampled)) / float(total)) + + +def coverage_floor_reached( + variant: AdaptivePolicyVariant, + *, + cluster_coverage: float, + hypercluster_coverage: float, +) -> bool: + return bool( + cluster_coverage >= float(variant.min_cluster_coverage) + and hypercluster_coverage >= float(variant.min_hypercluster_coverage) + ) + + +def select_cluster_bootstrap_batch( + scheduler: AdaptiveScheduler, + *, + sampled_clusters: set[int], + batch_size: int, +) -> List[str]: + active = scheduler.queue_manager.ordered_active() + if not active: + return [] + selected: List[str] = [] + # First pass: one candidate from unsampled clusters. + for item in active: + if item.cluster_id in sampled_clusters: + continue + if item.ligand_id in selected: + continue + selected.append(item.ligand_id) + if len(selected) >= batch_size: + break + # Fill remaining by priority order. + if len(selected) < batch_size: + for item in active: + if item.ligand_id in selected: + continue + selected.append(item.ligand_id) + if len(selected) >= batch_size: + break + for ligand_id in selected: + scheduler.queue_manager.items[ligand_id].times_selected += 1 + return selected + + +def effective_controls( + variant: AdaptivePolicyVariant, + state: PolicyRuntimeState, + *, + coverage_floor_active: bool, +) -> Tuple[float, float, float]: + # Returns (model_weight_cap, exploration_boost, threshold_relax). + model_cap = 1.0 + exploration_boost = 0.0 + threshold_relax = 0.0 + if coverage_floor_active: + model_cap = min(model_cap, float(variant.pre_floor_model_weight_cap)) + if state.soft_recovery_remaining > 0: + model_cap = min(model_cap, float(variant.soft_model_weight_cap)) + exploration_boost = max(exploration_boost, float(variant.soft_exploration_boost)) + threshold_relax = max(threshold_relax, float(variant.soft_threshold_relax)) + return float(model_cap), float(exploration_boost), float(threshold_relax) + + +def apply_stop_policy( + variant: AdaptivePolicyVariant, + state: PolicyRuntimeState, + *, + stop_signal: bool, + stop_reason: str, + coverage_floor_active: bool, +) -> Tuple[bool, str, PolicyRuntimeState]: + mode = str(variant.stop_mode).strip().lower() + # Coverage floor blocks stop decisions in floor-enforced variants. + if coverage_floor_active and stop_signal: + return False, "coverage_floor_blocked_stop", state + + if mode == "none": + return False, "no_stop_policy", state + + if mode == "hard": + return bool(stop_signal), (stop_reason if stop_signal else "continue"), state + + if mode == "regret": + return bool(stop_signal), (stop_reason if stop_signal else "continue"), state + + # soft mode + if state.soft_recovery_remaining > 0: + state.soft_recovery_remaining -= 1 + if state.soft_recovery_remaining <= 0 and stop_signal: + if state.soft_recoveries_used >= int(variant.max_soft_recoveries): + return True, "soft_recovery_exhausted", state + state.soft_recovery_remaining = int(variant.soft_recovery_batches) + state.soft_recoveries_used += 1 + return False, "soft_recovery_restarted", state + return False, "soft_recovery_active", state + + if not stop_signal: + return False, "continue", state + + if state.soft_recoveries_used >= int(variant.max_soft_recoveries): + return True, "soft_recovery_limit_reached", state + + state.soft_recovery_remaining = int(variant.soft_recovery_batches) + state.soft_recoveries_used += 1 + return False, "soft_recovery_started", state diff --git a/libs/benchmark/redocking_validation.py b/libs/benchmark/redocking_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b2ec444a40a30323288a983ccf12c43ea11799a0 --- /dev/null +++ b/libs/benchmark/redocking_validation.py @@ -0,0 +1,811 @@ +from __future__ import annotations + +import json +import math +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Iterable + +import numpy as np +import pandas as pd +from rdkit import Chem +from rdkit.Chem import AllChem, Descriptors, rdMolAlign, rdMolDescriptors +from rdkit.Chem.MolStandardize import rdMolStandardize +from scipy.optimize import linear_sum_assignment +from scipy.spatial.distance import cdist + +from libs.docking.backend_rdock import RDockBackend, RDockConfig +from libs.docking.backend_smina import SminaBackend, SminaConfig, parse_smina_score +from libs.docking.base import DockingError +from libs.docking.pocket import PocketSpec, resolve_pocket_spec, write_pocket_spec +from libs.docking.prep import prepare_ligand_sdf +from libs.utils.logging_utils import get_logger +from libs.utils.subprocess_utils import run_command + + +LOGGER = get_logger("redocking_validation") +ROOT_DIR = Path(__file__).resolve().parents[2] + + +@dataclass(frozen=True) +class RedockingTarget: + dataset: str + target_name: str + target_path: Path + reference_csv: Path + + +@dataclass(frozen=True) +class RedockingValidationConfig: + attempts: int = 60 + base_seed: int = 20260422 + backend: str = "rdock" + positive_score_threshold: float = 2.0 + rmsd_fail_threshold: float = 2.0 + near_top_rank_percentile_threshold: float = 20.0 + + +@dataclass(frozen=True) +class CrystalLigandExtraction: + pdb_block: str + residue_name: str + chain: str + resseq: str + atom_count: int + + + +def strict_targets_catalog() -> list[RedockingTarget]: + return [ + RedockingTarget( + dataset="strict_dataset_1", + target_name="EGFR", + target_path=ROOT_DIR / "data/targets/prelim_set_egfr_4wkq/egfr_4wkq.pdb", + reference_csv=ROOT_DIR / "data/ligands/prelim_set_egfr_4wkq/reference_ligands.csv", + ), + RedockingTarget( + dataset="strict_dataset_2", + target_name="ABL1", + target_path=ROOT_DIR / "data/targets/prelim_set_abl1_1iep/abl1_1iep.pdb", + reference_csv=ROOT_DIR / "data/ligands/prelim_set_abl1_1iep/reference_ligands.csv", + ), + RedockingTarget( + dataset="strict_dataset_3", + target_name="MDM2", + target_path=ROOT_DIR / "data/targets/prelim_set_mdm2_4hg7/mdm2_4hg7.pdb", + reference_csv=ROOT_DIR / "data/ligands/prelim_set_mdm2_4hg7/reference_ligands.csv", + ), + ] + + +def _read_reference(reference_csv: Path) -> dict[str, str]: + df = pd.read_csv(reference_csv) + if df.empty: + raise DockingError(f"Reference CSV is empty: {reference_csv}") + row = df.iloc[0] + return { + "reference_id": str(row.get("reference_id", "")).strip(), + "ligand_comp_id": str(row.get("ligand_comp_id", "")).strip(), + "reference_smiles": str(row.get("reference_smiles", "")).strip(), + "pdb_id": str(row.get("pdb_id", "")).strip(), + } + + +def _extract_reference_ligand_block(target_path: Path, ligand_comp_id: str) -> CrystalLigandExtraction: + lines = target_path.read_text(encoding="utf-8", errors="ignore").splitlines() + grouped: dict[tuple[str, str, str, str], list[str]] = {} + serials_by_group: dict[tuple[str, str, str, str], set[int]] = {} + ligand_filter = ligand_comp_id.strip().upper() + + for ln in lines: + if not ln.startswith("HETATM"): + continue + resn = ln[17:20].strip().upper() + if not resn or resn in {"HOH", "WAT", "DOD", "SO4"}: + continue + if ligand_filter and resn != ligand_filter: + continue + chain = ln[21:22].strip() + resseq = ln[22:26].strip() + ins = ln[26:27].strip() + key = (resn, chain, resseq, ins) + grouped.setdefault(key, []).append(ln) + try: + serial = int(ln[6:11].strip()) + except Exception: + continue + serials_by_group.setdefault(key, set()).add(serial) + + if not grouped: + raise DockingError( + f"Cannot extract crystallographic ligand `{ligand_comp_id}` from target `{target_path}`" + ) + + selected = max(grouped.keys(), key=lambda k: len(grouped[k])) + selected_serials = serials_by_group.get(selected, set()) + out_lines: list[str] = list(grouped[selected]) + + for ln in lines: + if not ln.startswith("CONECT"): + continue + cols = ln.split() + if len(cols) < 3: + continue + try: + src = int(cols[1]) + dst = [int(x) for x in cols[2:] if x.isdigit()] + except Exception: + continue + if src in selected_serials and any(x in selected_serials for x in dst): + out_lines.append(ln) + + out_lines.append("END") + pdb_block = "\n".join(out_lines) + "\n" + return CrystalLigandExtraction( + pdb_block=pdb_block, + residue_name=selected[0], + chain=selected[1], + resseq=selected[2], + atom_count=len(grouped[selected]), + ) + + +def _safe_mol_from_pdb_block(block: str) -> Chem.Mol: + mol = Chem.MolFromPDBBlock(block, removeHs=False, sanitize=False, proximityBonding=True) + if mol is None: + raise DockingError("Failed to parse crystal ligand PDB block with RDKit") + try: + Chem.SanitizeMol(mol) + except Exception: + pass + return mol + + +def _assign_template_bond_orders(crystal_mol: Chem.Mol, reference_smiles: str) -> Chem.Mol: + template = Chem.MolFromSmiles(reference_smiles) + if template is None: + return crystal_mol + try: + assigned = AllChem.AssignBondOrdersFromTemplate(Chem.RemoveHs(template), Chem.RemoveHs(crystal_mol)) + return assigned + except Exception: + return crystal_mol + + +def _convert_with_obabel(src: Path, dst: Path, extra_args: list[str] | None = None, timeout: int = 120) -> None: + extra = extra_args or [] + cmd = ["obabel", str(src), "-O", str(dst), *extra] + result = run_command(cmd, cwd=dst.parent, timeout=timeout) + if result.returncode != 0 or (not dst.exists()) or dst.stat().st_size == 0: + raise DockingError(f"obabel conversion failed: {' '.join(cmd)} | rc={result.returncode} | stderr={result.stderr.strip()}") + + +def _tripos_atom_types_summary(mol2_path: Path) -> dict[str, int]: + text = mol2_path.read_text(encoding="utf-8", errors="ignore").splitlines() + in_atoms = False + counts: dict[str, int] = {} + for ln in text: + if ln.startswith("@ATOM"): + in_atoms = True + continue + if ln.startswith("@") and in_atoms: + break + if not in_atoms: + continue + cols = ln.split() + if len(cols) < 6: + continue + atom_type = str(cols[5]).strip() + counts[atom_type] = counts.get(atom_type, 0) + 1 + return dict(sorted(counts.items(), key=lambda kv: kv[0])) + + +def _tautomer_identifier(mol: Chem.Mol) -> str: + try: + te = rdMolStandardize.TautomerEnumerator() + t = te.Canonicalize(Chem.Mol(mol)) + return Chem.MolToSmiles(t, canonical=True) + except Exception: + return "" + + +def _ligand_prep_audit(mol: Chem.Mol, mol2_path: Path) -> dict[str, Any]: + atom_count = int(mol.GetNumAtoms()) + h_count = int(sum(1 for a in mol.GetAtoms() if a.GetAtomicNum() == 1)) + aromatic_count = int(sum(1 for a in mol.GetAtoms() if a.GetIsAromatic())) + formal_charge = int(sum(a.GetFormalCharge() for a in mol.GetAtoms())) + rot_bonds = np.nan + canonical = "" + tautomer_id = "" + try: + no_h = Chem.RemoveHs(Chem.Mol(mol)) + rot_bonds = int(rdMolDescriptors.CalcNumRotatableBonds(no_h)) + canonical = Chem.MolToSmiles(no_h, canonical=True) + tautomer_id = _tautomer_identifier(no_h) + except Exception: + pass + protonation_id = f"q={formal_charge}|smiles={canonical}" + return { + "atom_count": atom_count, + "hydrogen_count": h_count, + "formal_charge": formal_charge, + "aromatic_atom_count": aromatic_count, + "rotatable_bond_count": rot_bonds, + "tautomer_identifier": tautomer_id, + "protonation_identifier": protonation_id, + "tripos_atom_types": _tripos_atom_types_summary(mol2_path), + } + + +def _kabsch(P: np.ndarray, Q: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + cp = P.mean(axis=0) + cq = Q.mean(axis=0) + P0 = P - cp + Q0 = Q - cq + C = P0.T @ Q0 + V, _S, Wt = np.linalg.svd(C) + d = np.linalg.det(V @ Wt) + D = np.eye(3) + D[2, 2] = np.sign(d) if d != 0 else 1.0 + R = V @ D @ Wt + t = cq - (cp @ R) + return R, t + + +def _coords_by_element(mol: Chem.Mol) -> dict[int, np.ndarray]: + if mol.GetNumConformers() == 0: + return {} + conf = mol.GetConformer() + groups: dict[int, list[list[float]]] = {} + for i, atom in enumerate(mol.GetAtoms()): + z = int(atom.GetAtomicNum()) + if z == 1: + continue + p = conf.GetAtomPosition(i) + groups.setdefault(z, []).append([p.x, p.y, p.z]) + return {z: np.asarray(v, dtype=float) for z, v in groups.items() if v} + + +def _rmsd_assignment_fallback(probe: Chem.Mol, ref: Chem.Mol, max_iter: int = 8) -> float: + p_groups = _coords_by_element(probe) + r_groups = _coords_by_element(ref) + if not p_groups or not r_groups: + return float("nan") + if set(p_groups.keys()) != set(r_groups.keys()): + return float("nan") + for z in p_groups: + if p_groups[z].shape[0] != r_groups[z].shape[0]: + return float("nan") + + z_order = sorted(p_groups.keys()) + R = np.eye(3) + t = np.zeros(3, dtype=float) + + P_match = None + Q_match = None + for _ in range(max_iter): + P_parts: list[np.ndarray] = [] + Q_parts: list[np.ndarray] = [] + for z in z_order: + Pz = p_groups[z] + Qz = r_groups[z] + Pzt = (Pz @ R) + t + D = cdist(Pzt, Qz) + ridx, cidx = linear_sum_assignment(D) + P_parts.append(Pz[ridx]) + Q_parts.append(Qz[cidx]) + P_match = np.vstack(P_parts) + Q_match = np.vstack(Q_parts) + R, t = _kabsch(P_match, Q_match) + + if P_match is None or Q_match is None: + return float("nan") + P_final = (P_match @ R) + t + diff = P_final - Q_match + return float(np.sqrt(np.mean(np.sum(diff * diff, axis=1)))) + + +def heavy_atom_rmsd(probe: Chem.Mol, ref: Chem.Mol) -> float: + try: + probe_h = Chem.RemoveHs(Chem.Mol(probe)) + ref_h = Chem.RemoveHs(Chem.Mol(ref)) + except Exception: + return float("nan") + + try: + if probe_h.GetNumAtoms() == ref_h.GetNumAtoms() and probe_h.GetNumConformers() > 0 and ref_h.GetNumConformers() > 0: + val = float(rdMolAlign.GetBestRMS(probe_h, ref_h)) + if np.isfinite(val): + return val + except Exception: + pass + + return _rmsd_assignment_fallback(probe_h, ref_h) + + +def _safe_remove_hs(mol: Chem.Mol) -> Chem.Mol | None: + try: + return Chem.RemoveHs(Chem.Mol(mol)) + except Exception: + return None + + +def _safe_smiles(mol: Chem.Mol | None) -> str: + if mol is None: + return "" + try: + return Chem.MolToSmiles(mol, canonical=True) + except Exception: + return "" + + +def _pose_entries_from_rdock_sdf(sd_path: Path) -> list[dict[str, Any]]: + entries: list[dict[str, Any]] = [] + suppl = Chem.SDMolSupplier(str(sd_path), removeHs=False, sanitize=False) + for idx, mol in enumerate(suppl): + if mol is None: + continue + score = float("nan") + for key in ["SCORE", "score", "SCORE.INTER"]: + if mol.HasProp(key): + try: + score = float(mol.GetProp(key)) + break + except Exception: + continue + if not np.isfinite(score): + continue + entries.append({"pose_idx": idx, "score": float(score), "mol": mol}) + entries.sort(key=lambda x: x["score"]) + return entries + + +def _score_only_smina( + smina_executable: str, + receptor_pdbqt: Path, + ligand_pdbqt: Path, + pocket: PocketSpec, + out_dir: Path, + seed: int, +) -> float: + out_dir.mkdir(parents=True, exist_ok=True) + cmd = [ + str(smina_executable), + "--receptor", + str(receptor_pdbqt), + "--ligand", + str(ligand_pdbqt), + "--center_x", + f"{pocket.center[0]:.4f}", + "--center_y", + f"{pocket.center[1]:.4f}", + "--center_z", + f"{pocket.center[2]:.4f}", + "--size_x", + f"{pocket.box_size[0]:.4f}", + "--size_y", + f"{pocket.box_size[1]:.4f}", + "--size_z", + f"{pocket.box_size[2]:.4f}", + "--score_only", + "--seed", + str(seed), + ] + result = run_command(cmd, cwd=out_dir, timeout=120) + (out_dir / "score_only.stdout.log").write_text(result.stdout, encoding="utf-8") + (out_dir / "score_only.stderr.log").write_text(result.stderr, encoding="utf-8") + score = parse_smina_score("\n".join([result.stdout or "", result.stderr or ""])) + if result.returncode != 0 or not np.isfinite(score): + raise DockingError( + f"smina --score_only failed: rc={result.returncode} score={score} stderr={result.stderr.strip()}" + ) + return float(score) + + +def _format_target_report(target_row: dict[str, Any], fail_reasons: list[str]) -> str: + verdict = "GO" if not fail_reasons else "NO-GO" + lines = [ + f"# Redocking Validation: {target_row['dataset']} ({target_row['target_name']})", + "", + f"- backend: `{target_row['backend']}`", + f"- attempts: `{target_row['attempts']}`", + f"- reference ligand: `{target_row['reference_ligand_id']}`", + f"- crystal ligand component: `{target_row['ligand_comp_id']}`", + f"- top-pose heavy-atom RMSD [A]: `{target_row['top_pose_rmsd_A']:.4f}`", + f"- best-of-run heavy-atom RMSD [A]: `{target_row['best_of_run_rmsd_A']:.4f}`", + f"- crystallographic in-place score: `{target_row['crystal_inplace_score']:.4f}`", + f"- in-place score source: `{target_row.get('crystal_inplace_score_source', '')}`", + f"- best docked score: `{target_row['best_docked_score']:.4f}`", + f"- reference rank (in-place score among attempts): `{target_row['reference_rank']}` / `{target_row['attempts'] + 1}`", + f"- reference rank percentile: `{target_row['reference_rank_percentile']:.3f}`", + "", + f"## Verdict: **{verdict}**", + "", + "## Fail Criteria", + "- top-pose RMSD > 2.0 A and best-of-run RMSD > 2.0 A", + "- crystallographic pose score strongly positive", + "- reference ligand not near top in own redocking test", + "", + "## Triggered Fail Reasons", + ] + if fail_reasons: + lines.extend([f"- {r}" for r in fail_reasons]) + else: + lines.append("- none") + lines.append("") + return "\n".join(lines) + + +def run_redocking_validation( + output_dir: str | Path = "results/redocking_validation", + *, + config: RedockingValidationConfig | None = None, + datasets: Iterable[RedockingTarget] | None = None, +) -> dict[str, Any]: + cfg = config or RedockingValidationConfig() + if int(cfg.attempts) < 50 or int(cfg.attempts) > 100: + raise DockingError(f"Redocking attempts must be in [50,100], got {cfg.attempts}") + + out_dir = Path(output_dir) + out_dir.mkdir(parents=True, exist_ok=True) + target_reports_dir = out_dir / "target_reports" + target_reports_dir.mkdir(parents=True, exist_ok=True) + + targets = list(datasets or strict_targets_catalog()) + if not targets: + raise DockingError("No targets defined for redocking validation") + + if cfg.backend != "rdock": + raise DockingError("Current strict redocking validation supports backend='rdock' only") + + per_attempt_rows: list[dict[str, Any]] = [] + per_target_rows: list[dict[str, Any]] = [] + prep_rows: list[dict[str, Any]] = [] + compare_rows: list[dict[str, Any]] = [] + + for t in targets: + target_root = out_dir / t.dataset + target_root.mkdir(parents=True, exist_ok=True) + + ref = _read_reference(t.reference_csv) + reference_id = str(ref["reference_id"]) + ligand_comp_id = str(ref["ligand_comp_id"]) + reference_smiles = str(ref["reference_smiles"]) + + extraction = _extract_reference_ligand_block(t.target_path, ligand_comp_id) + crystal_pdb = target_root / "crystal_ligand.pdb" + crystal_pdb.write_text(extraction.pdb_block, encoding="utf-8") + + crystal_sdf = target_root / "crystal_ligand.sdf" + crystal_mol2 = target_root / "crystal_ligand.mol2" + crystal_pdbqt = target_root / "crystal_ligand.pdbqt" + _convert_with_obabel(crystal_pdb, crystal_sdf) + _convert_with_obabel(crystal_pdb, crystal_mol2) + _convert_with_obabel(crystal_pdb, crystal_pdbqt) + + crystal_raw = Chem.SDMolSupplier(str(crystal_sdf), removeHs=False, sanitize=False) + crystal_mol = crystal_raw[0] if crystal_raw and len(crystal_raw) > 0 else None + if crystal_mol is None: + crystal_mol = _safe_mol_from_pdb_block(extraction.pdb_block) + crystal_mol = _assign_template_bond_orders(crystal_mol, reference_smiles) + + prepared_sdf = prepare_ligand_sdf(reference_id, reference_smiles, target_root / "prepared_reference.sdf") + prepared_mol2 = target_root / "prepared_reference.mol2" + prepared_pdbqt = target_root / "prepared_reference.pdbqt" + _convert_with_obabel(prepared_sdf, prepared_mol2) + _convert_with_obabel(prepared_sdf, prepared_pdbqt) + + prepared_suppl = Chem.SDMolSupplier(str(prepared_sdf), removeHs=False, sanitize=False) + prepared_mol = prepared_suppl[0] if prepared_suppl and len(prepared_suppl) > 0 else None + if prepared_mol is None: + raise DockingError(f"Cannot parse prepared reference SDF for {t.dataset}") + + crystal_audit = _ligand_prep_audit(Chem.Mol(crystal_mol), crystal_mol2) + prepared_audit = _ligand_prep_audit(Chem.Mol(prepared_mol), prepared_mol2) + + prep_rows.append( + { + "dataset": t.dataset, + "target_name": t.target_name, + "reference_ligand_id": reference_id, + "variant": "crystal", + **{k: (json.dumps(v) if isinstance(v, dict) else v) for k, v in crystal_audit.items()}, + } + ) + prep_rows.append( + { + "dataset": t.dataset, + "target_name": t.target_name, + "reference_ligand_id": reference_id, + "variant": "prepared", + **{k: (json.dumps(v) if isinstance(v, dict) else v) for k, v in prepared_audit.items()}, + } + ) + + crystal_heavy = _safe_remove_hs(crystal_mol) + prepared_heavy = _safe_remove_hs(prepared_mol) + compare_rows.append( + { + "dataset": t.dataset, + "target_name": t.target_name, + "reference_ligand_id": reference_id, + "crystal_atom_count": int(crystal_mol.GetNumAtoms()), + "prepared_atom_count": int(prepared_mol.GetNumAtoms()), + "crystal_heavy_atom_count": int(crystal_heavy.GetNumAtoms()) if crystal_heavy is not None else np.nan, + "prepared_heavy_atom_count": int(prepared_heavy.GetNumAtoms()) if prepared_heavy is not None else np.nan, + "crystal_formal_charge": int(sum(a.GetFormalCharge() for a in crystal_mol.GetAtoms())), + "prepared_formal_charge": int(sum(a.GetFormalCharge() for a in prepared_mol.GetAtoms())), + "crystal_canonical_smiles": _safe_smiles(crystal_heavy), + "prepared_canonical_smiles": _safe_smiles(prepared_heavy), + "heavy_atom_rmsd_crystal_vs_prepared_A": ( + heavy_atom_rmsd(prepared_heavy, crystal_heavy) + if (prepared_heavy is not None and crystal_heavy is not None) + else np.nan + ), + } + ) + + rdock_backend = RDockBackend( + RDockConfig( + n_runs=1, + command_timeout_seconds=240, + parallel_jobs=1, + command_log_path=str(target_root / "rdock_commands.log"), + pocket_mode="reference_complex_pocket", + pocket_reference_ligand_id=ligand_comp_id, + pocket_relaxation_margin=0.0, + ) + ) + cap = rdock_backend.check_capability() + if not cap.available: + raise DockingError(f"rDock not available for redocking validation: {cap.details}") + + rdock_target_ctx = rdock_backend.prepare_target(t.target_path, target_root / "rdock_target") + rdock_ligand = rdock_backend.prepare_ligand(reference_id, reference_smiles, target_root / "rdock_ligand") + + smina_backend = SminaBackend( + SminaConfig( + command_timeout_seconds=120, + exhaustiveness=8, + num_modes=1, + cpu=1, + parallel_jobs=1, + seed=cfg.base_seed, + pocket_mode="reference_complex_pocket", + pocket_reference_ligand_id=ligand_comp_id, + pocket_relaxation_margin=0.0, + ) + ) + smina_cap = smina_backend.check_capability() + if not smina_cap.available: + raise DockingError( + f"smina is required for crystallographic in-place score in redocking validation: {smina_cap.details}" + ) + smina_exe = str(smina_cap.details.get("smina", "") or "") + if not smina_exe: + raise DockingError("smina executable path missing in capability details") + smina_target_ctx = smina_backend.prepare_target(t.target_path, target_root / "smina_score_only_target") + pocket = PocketSpec.from_dict(json.loads(Path(smina_target_ctx["pocket_json"]).read_text(encoding="utf-8"))) + + crystal_inplace_score = _score_only_smina( + smina_executable=smina_exe, + receptor_pdbqt=Path(smina_target_ctx["receptor_pdbqt"]), + ligand_pdbqt=crystal_pdbqt, + pocket=pocket, + out_dir=target_root / "score_only", + seed=cfg.base_seed, + ) + + all_pose_rmsd: list[float] = [] + all_pose_scores: list[float] = [] + top_pose_scores: list[float] = [] + top_pose_rmsd_list: list[float] = [] + + for attempt_idx in range(int(cfg.attempts)): + rdock_backend.config.n_runs = 1 + rdock_backend.config.allow_partial_failures = False + rdock_backend.config.seed = int(cfg.base_seed + attempt_idx) + + attempt_dir = target_root / "attempts" / f"attempt_{attempt_idx:04d}" + attempt_dir.mkdir(parents=True, exist_ok=True) + results = rdock_backend.dock( + target_context=rdock_target_ctx, + ligand_files=[rdock_ligand], + work_dir=attempt_dir, + allow_mock=False, + require_real_backend=True, + ) + parsed = rdock_backend.parse_results(results) + if not parsed: + per_attempt_rows.append( + { + "dataset": t.dataset, + "target_name": t.target_name, + "backend": cfg.backend, + "attempt_idx": attempt_idx, + "reference_ligand_id": reference_id, + "success": False, + "best_docked_score": np.nan, + "top_pose_score": np.nan, + "top_pose_rmsd_A": np.nan, + "best_rmsd_in_attempt_A": np.nan, + "n_poses": 0, + "raw_output_file": "", + } + ) + continue + + row = parsed[0] + raw = Path(str(row.get("raw_output_file", ""))) + success = bool(row.get("success", False)) and raw.exists() + top_pose_score = float(row.get("docking_score", np.nan)) + best_docked_score = float(top_pose_score) + top_pose_rmsd = float("nan") + best_rmsd_attempt = float("nan") + n_poses = 0 + + if success and raw.exists(): + poses = _pose_entries_from_rdock_sdf(raw) + n_poses = int(len(poses)) + if poses: + top = poses[0] + top_pose_score = float(top["score"]) + top_pose_rmsd = heavy_atom_rmsd(top["mol"], crystal_mol) + best_docked_score = float(min(float(p["score"]) for p in poses)) + rmsd_values = [ + heavy_atom_rmsd(p["mol"], crystal_mol) + for p in poses + ] + rmsd_values = [float(x) for x in rmsd_values if np.isfinite(x)] + if rmsd_values: + best_rmsd_attempt = float(np.min(np.asarray(rmsd_values, dtype=float))) + all_pose_rmsd.extend(rmsd_values) + all_pose_scores.extend([float(p["score"]) for p in poses if np.isfinite(float(p["score"]))]) + + if np.isfinite(top_pose_score): + top_pose_scores.append(float(top_pose_score)) + if np.isfinite(top_pose_rmsd): + top_pose_rmsd_list.append(float(top_pose_rmsd)) + + per_attempt_rows.append( + { + "dataset": t.dataset, + "target_name": t.target_name, + "backend": cfg.backend, + "attempt_idx": attempt_idx, + "reference_ligand_id": reference_id, + "success": bool(success), + "best_docked_score": float(best_docked_score) if np.isfinite(best_docked_score) else np.nan, + "top_pose_score": float(top_pose_score) if np.isfinite(top_pose_score) else np.nan, + "top_pose_rmsd_A": float(top_pose_rmsd) if np.isfinite(top_pose_rmsd) else np.nan, + "best_rmsd_in_attempt_A": float(best_rmsd_attempt) if np.isfinite(best_rmsd_attempt) else np.nan, + "n_poses": int(n_poses), + "raw_output_file": str(raw), + } + ) + + attempts_df = pd.DataFrame([r for r in per_attempt_rows if r["dataset"] == t.dataset]) + valid_attempts = attempts_df.dropna(subset=["top_pose_score"]).copy() + if valid_attempts.empty: + raise DockingError(f"No successful redocking attempts for {t.dataset}") + + valid_attempts = valid_attempts.sort_values("top_pose_score", ascending=True).reset_index(drop=True) + top_pose_rmsd_global = float(valid_attempts["top_pose_rmsd_A"].iloc[0]) if not valid_attempts.empty else float("nan") + best_of_run_rmsd = float(pd.to_numeric(valid_attempts["best_rmsd_in_attempt_A"], errors="coerce").min()) + best_docked_score = float(pd.to_numeric(valid_attempts["best_docked_score"], errors="coerce").min()) + + attempt_scores = pd.to_numeric(valid_attempts["top_pose_score"], errors="coerce").dropna().to_numpy(dtype=float) + ref_rank = int(1 + int(np.sum(attempt_scores < float(crystal_inplace_score)))) + ref_rank_pct = float(100.0 * ref_rank / max(1, attempt_scores.shape[0] + 1)) + + fail_reasons: list[str] = [] + if np.isfinite(top_pose_rmsd_global) and np.isfinite(best_of_run_rmsd): + if top_pose_rmsd_global > cfg.rmsd_fail_threshold and best_of_run_rmsd > cfg.rmsd_fail_threshold: + fail_reasons.append( + f"RMSD failure: top_pose_rmsd={top_pose_rmsd_global:.3f}A and best_of_run_rmsd={best_of_run_rmsd:.3f}A exceed {cfg.rmsd_fail_threshold:.3f}A" + ) + else: + fail_reasons.append("RMSD failure: non-finite RMSD value") + + if not np.isfinite(crystal_inplace_score) or crystal_inplace_score > cfg.positive_score_threshold: + fail_reasons.append( + f"Crystallographic in-place score is strongly positive or invalid: {crystal_inplace_score}" + ) + + if (not np.isfinite(ref_rank_pct)) or ref_rank_pct > cfg.near_top_rank_percentile_threshold: + fail_reasons.append( + f"Reference ligand not near top: rank_percentile={ref_rank_pct:.3f} > {cfg.near_top_rank_percentile_threshold:.3f}" + ) + + target_row = { + "dataset": t.dataset, + "target_name": t.target_name, + "backend": cfg.backend, + "attempts": int(cfg.attempts), + "reference_ligand_id": reference_id, + "ligand_comp_id": ligand_comp_id, + "top_pose_rmsd_A": float(top_pose_rmsd_global), + "best_of_run_rmsd_A": float(best_of_run_rmsd), + "crystal_inplace_score": float(crystal_inplace_score), + "crystal_inplace_score_source": "smina_score_only", + "best_docked_score": float(best_docked_score), + "reference_rank": int(ref_rank), + "reference_rank_percentile": float(ref_rank_pct), + "success_attempt_count": int(valid_attempts.shape[0]), + "go": bool(len(fail_reasons) == 0), + "fail_reasons": " | ".join(fail_reasons), + } + per_target_rows.append(target_row) + + report_md = _format_target_report(target_row, fail_reasons) + (target_reports_dir / f"{t.dataset}.md").write_text(report_md, encoding="utf-8") + + per_attempt_df = pd.DataFrame(per_attempt_rows) + per_target_df = pd.DataFrame(per_target_rows) + prep_df = pd.DataFrame(prep_rows) + compare_df = pd.DataFrame(compare_rows) + + per_attempt_df.to_csv(out_dir / "per_attempt_poses.csv", index=False) + per_target_df.to_csv(out_dir / "per_target_metrics.csv", index=False) + prep_df.to_csv(out_dir / "preparation_audit.csv", index=False) + compare_df.to_csv(out_dir / "crystal_vs_prepared_comparison.csv", index=False) + + compare_md = [ + "# Crystal vs Prepared Ligand Comparison", + "", + "This report captures changes introduced by conversion/preparation.", + "", + ] + if compare_df.empty: + compare_md.append("- no rows") + else: + for r in compare_df.itertuples(index=False): + compare_md.extend( + [ + f"## {r.dataset} ({r.target_name})", + f"- reference_ligand_id: `{r.reference_ligand_id}`", + f"- crystal_atoms / prepared_atoms: `{r.crystal_atom_count}` / `{r.prepared_atom_count}`", + f"- crystal_heavy / prepared_heavy: `{r.crystal_heavy_atom_count}` / `{r.prepared_heavy_atom_count}`", + f"- crystal_charge / prepared_charge: `{r.crystal_formal_charge}` / `{r.prepared_formal_charge}`", + f"- heavy_atom_rmsd_crystal_vs_prepared_A: `{float(r.heavy_atom_rmsd_crystal_vs_prepared_A):.4f}`", + f"- crystal_canonical_smiles: `{r.crystal_canonical_smiles}`", + f"- prepared_canonical_smiles: `{r.prepared_canonical_smiles}`", + "", + ] + ) + (out_dir / "crystal_vs_prepared_report.md").write_text("\n".join(compare_md) + "\n", encoding="utf-8") + + all_go = bool((per_target_df["go"].astype(bool)).all()) if not per_target_df.empty else False + + summary = { + "run_name": "redocking_validation", + "backend": cfg.backend, + "attempts": int(cfg.attempts), + "datasets": per_target_df["dataset"].astype(str).tolist(), + "all_targets_go": all_go, + "n_targets": int(per_target_df.shape[0]), + "outputs": { + "per_attempt_poses_csv": str(out_dir / "per_attempt_poses.csv"), + "per_target_metrics_csv": str(out_dir / "per_target_metrics.csv"), + "preparation_audit_csv": str(out_dir / "preparation_audit.csv"), + "crystal_vs_prepared_comparison_csv": str(out_dir / "crystal_vs_prepared_comparison.csv"), + "crystal_vs_prepared_report_md": str(out_dir / "crystal_vs_prepared_report.md"), + "target_reports_dir": str(target_reports_dir), + }, + } + (out_dir / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") + + gate_lines = [ + "# Redocking Validation Gate", + "", + f"- all_targets_go: `{all_go}`", + f"- backend: `{cfg.backend}`", + f"- attempts: `{cfg.attempts}`", + "", + "## Per-target verdict", + ] + for r in per_target_rows: + gate_lines.append(f"- {r['dataset']}: {'GO' if r['go'] else 'NO-GO'}") + (out_dir / "self_audit_report.md").write_text("\n".join(gate_lines) + "\n", encoding="utf-8") + + return summary diff --git a/libs/benchmark/reuse.py b/libs/benchmark/reuse.py new file mode 100644 index 0000000000000000000000000000000000000000..47b44d937d0b37e3f7121255333a9d8d1234fdf7 --- /dev/null +++ b/libs/benchmark/reuse.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable, List + + +@dataclass(frozen=True) +class ReuseCheck: + ok: bool + missing: List[str] + note: str + + +def validate_reuse_inputs(required_paths: Iterable[Path]) -> ReuseCheck: + missing = [str(p) for p in required_paths if not Path(p).exists()] + if missing: + return ReuseCheck(ok=False, missing=missing, note="missing_required_reuse_inputs") + return ReuseCheck(ok=True, missing=[], note="reuse_inputs_available") + diff --git a/libs/benchmark/runtime.py b/libs/benchmark/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..434ed432531f222bd18380bc2154ca8b8b616cee --- /dev/null +++ b/libs/benchmark/runtime.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import os +from dataclasses import dataclass +from typing import Any, Dict + + +AUTO_MINUS_FOUR = "auto-minus-4" + + +@dataclass(frozen=True) +class ThreadAllocation: + policy: str + system_threads: int + reserve_threads: int + threads_used: int + + +def detect_system_threads() -> int: + return max(1, int(os.cpu_count() or 1)) + + +def resolve_threads_used( + configured_value: Any, + *, + reserve_threads: int = 4, + system_threads: int | None = None, +) -> ThreadAllocation: + total = max(1, int(system_threads or detect_system_threads())) + reserve = max(0, int(reserve_threads)) + + policy_raw = configured_value if configured_value is not None else AUTO_MINUS_FOUR + policy = str(policy_raw).strip().lower() + + if policy in {"", "auto", AUTO_MINUS_FOUR}: + used = max(1, total - reserve) + return ThreadAllocation( + policy=AUTO_MINUS_FOUR, + system_threads=total, + reserve_threads=reserve, + threads_used=used, + ) + + try: + used = max(1, int(policy_raw)) + except (TypeError, ValueError) as exc: + raise ValueError( + f"Invalid backend.parallel_jobs value `{configured_value}`. Use integer or `{AUTO_MINUS_FOUR}`." + ) from exc + + return ThreadAllocation( + policy="fixed", + system_threads=total, + reserve_threads=reserve, + threads_used=min(total, used), + ) + + +def enforce_thread_fairness(config: Dict[str, Any], *, reserve_threads: int = 4) -> ThreadAllocation: + backend = config.setdefault("backend", {}) + configured = backend.get("parallel_jobs", AUTO_MINUS_FOUR) + alloc = resolve_threads_used(configured, reserve_threads=reserve_threads) + + backend["parallel_jobs"] = int(alloc.threads_used) + backend["thread_policy"] = alloc.policy + + runtime = config.setdefault("runtime", {}) + runtime["system_threads"] = int(alloc.system_threads) + runtime["reserve_threads"] = int(alloc.reserve_threads) + runtime["threads_used"] = int(alloc.threads_used) + runtime["thread_policy"] = alloc.policy + runtime["thread_formula"] = "threads_used = max(1, system_threads - 4)" + return alloc + diff --git a/libs/docking/__init__.py b/libs/docking/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..048b964f2a8a1a3ab1f0415dcff89c66ab9cdfa9 --- /dev/null +++ b/libs/docking/__init__.py @@ -0,0 +1,28 @@ +"""Docking backend abstractions and backend adapters.""" + +from .backend_rdock import RDockBackend +from .backend_smina import SminaBackend +from .base import BackendCapability, DockingBackend, DockingError, DockingResult +from .comparison import build_backend_comparison_table, semantic_compatibility_notes, summarize_backend_table +from .pocket import ( + POCKET_MODE_REFERENCE, + POCKET_MODE_REFERENCE_RELAXED, + POCKET_MODE_USER_FIXED, + PocketSpec, +) + +__all__ = [ + "BackendCapability", + "DockingBackend", + "DockingError", + "DockingResult", + "RDockBackend", + "SminaBackend", + "PocketSpec", + "POCKET_MODE_USER_FIXED", + "POCKET_MODE_REFERENCE", + "POCKET_MODE_REFERENCE_RELAXED", + "build_backend_comparison_table", + "semantic_compatibility_notes", + "summarize_backend_table", +] diff --git a/libs/docking/backend_rdock.py b/libs/docking/backend_rdock.py new file mode 100644 index 0000000000000000000000000000000000000000..9b3221e69f019e633cd3bd13e412f54b882f7403 --- /dev/null +++ b/libs/docking/backend_rdock.py @@ -0,0 +1,534 @@ +from __future__ import annotations + +import json +import os +import shutil +import threading +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from subprocess import TimeoutExpired +from typing import Dict, Sequence + +import numpy as np + +from libs.utils.logging_utils import get_logger +from libs.utils.subprocess_utils import CommandResult, run_command + +from .base import BackendCapability, BackendUnavailableError, DockingBackend, DockingError, DockingResult +from .constraints import write_receptor_prm, write_receptor_prm_sphere +from .interface_features import extract_simple_interface_features +from .pocket import ( + POCKET_MODE_REFERENCE, + POCKET_MODE_REFERENCE_RELAXED, + POCKET_MODE_USER_FIXED, + PocketSpec, + centroid_from_sdf, + is_pose_in_pocket, + pose_distance_to_center, + resolve_pocket_spec, + write_pocket_spec, +) +from .pose_parsing import parse_rdock_sdf +from .prep import prepare_ligand_sdf + + +@dataclass +class RDockConfig: + rbdock_bin: str = "rbdock" + rbcavity_bin: str = "rbcavity" + sdtether_bin: str = "sdtether" + n_runs: int = 5 + seed: int | None = None + protocol_prm: str | None = None + rbt_root: str | None = None + command_log_path: str | None = None + mapper_radius: float = 6.0 + command_timeout_seconds: int = 180 + parallel_jobs: int = 1 + allow_partial_failures: bool = False + pocket_mode: str = POCKET_MODE_REFERENCE + pocket_center: tuple[float, float, float] | str | list[float] | None = None + pocket_box_size: tuple[float, float, float] | str | list[float] | None = None + pocket_radius: float | None = None + pocket_reference_ligand_id: str | None = None + pocket_relaxation_margin: float = 0.0 + allow_legacy_generated_pocket: bool = False + + +class RDockBackend(DockingBackend): + """rDock adapter with strict backend validation and explicit provenance.""" + + def __init__(self, config: RDockConfig | None = None) -> None: + self.config = config or RDockConfig() + self.logger = get_logger("rdock_backend") + self.default_rbt_root = Path("/opt/homebrew/opt/rdock/share") + self.command_history: list[dict[str, str | int]] = [] + self._log_lock = threading.Lock() + + def _ensure_runtime_env(self) -> None: + if self.config.rbt_root: + os.environ["RBT_ROOT"] = self.config.rbt_root + return + + if "RBT_ROOT" not in os.environ and self.default_rbt_root.exists(): + os.environ["RBT_ROOT"] = str(self.default_rbt_root) + + def _resolve_protocol_prm(self) -> Path: + if self.config.protocol_prm: + prm = Path(self.config.protocol_prm).expanduser().resolve() + if prm.exists(): + return prm + raise DockingError(f"Configured protocol file does not exist: {prm}") + + rbt_root = os.environ.get("RBT_ROOT") + if not rbt_root: + raise DockingError("RBT_ROOT is not set and protocol_prm is not configured") + + prm = Path(rbt_root) / "data" / "scripts" / "dock.prm" + if not prm.exists(): + raise DockingError(f"Default rDock protocol file not found: {prm}") + return prm + + def _append_command_log(self, payload: dict[str, str | int]) -> None: + with self._log_lock: + self.command_history.append(payload) + if self.config.command_log_path: + log_path = Path(self.config.command_log_path) + log_path.parent.mkdir(parents=True, exist_ok=True) + line = ( + f"[{payload['timestamp']}] stage={payload['stage']} rc={payload['returncode']} cwd={payload['cwd']}\n" + f" command: {payload['command']}\n" + f" stdout: {payload['stdout_log']}\n" + f" stderr: {payload['stderr_log']}\n" + ) + with log_path.open("a", encoding="utf-8") as handle: + handle.write(line) + + def _record_command( + self, + stage: str, + result: CommandResult, + cwd: Path, + stdout_log: Path, + stderr_log: Path, + ) -> None: + stdout_log.write_text(result.stdout, encoding="utf-8") + stderr_log.write_text(result.stderr, encoding="utf-8") + self._append_command_log( + { + "timestamp": datetime.now(UTC).isoformat(), + "stage": stage, + "command": " ".join(result.command), + "cwd": str(cwd), + "returncode": result.returncode, + "stdout_log": str(stdout_log), + "stderr_log": str(stderr_log), + } + ) + + @staticmethod + def _indicates_failure(result: CommandResult) -> bool: + if result.returncode != 0: + return True + + text = f"{result.stdout}\n{result.stderr}".lower() + known_error_markers = [ + "rbt_file_read_error", + "bad_receptor_file", + "cavity file", + "inappropriate molecular file type", + "fatal", + ] + return any(marker in text for marker in known_error_markers) + + def check_capability(self) -> BackendCapability: + bins = { + "rbdock": shutil.which(self.config.rbdock_bin), + "rbcavity": shutil.which(self.config.rbcavity_bin), + "sdtether": shutil.which(self.config.sdtether_bin), + "obabel": shutil.which("obabel"), + } + available = bins["rbdock"] is not None and bins["rbcavity"] is not None and bins["obabel"] is not None + return BackendCapability(backend_name="rdock", available=available, details=bins) + + def _resolve_target_pocket(self, target_path: Path, work_dir: Path) -> PocketSpec: + spec = resolve_pocket_spec( + target_path=target_path, + pocket_mode=self.config.pocket_mode, + pocket_center=self.config.pocket_center, + pocket_box_size=self.config.pocket_box_size, + pocket_radius=self.config.pocket_radius, + pocket_reference_ligand_id=self.config.pocket_reference_ligand_id, + pocket_relaxation_margin=self.config.pocket_relaxation_margin, + fallback_radius=self.config.mapper_radius, + ) + write_pocket_spec(work_dir / "pocket_spec.json", spec) + return spec + + def prepare_target(self, target_path: str | Path, work_dir: str | Path) -> Dict[str, Path]: + source = Path(target_path) + if not source.exists(): + raise DockingError(f"Target file does not exist: {source}") + + wd = Path(work_dir) + wd.mkdir(parents=True, exist_ok=True) + + prepared = wd / f"target_prepared{source.suffix.lower()}" + prepared.write_bytes(source.read_bytes()) + + receptor_mol2 = wd / "receptor.mol2" + suffix = source.suffix.lower() + if suffix == ".mol2": + receptor_mol2.write_bytes(source.read_bytes()) + else: + obabel = shutil.which("obabel") + if obabel is None: + raise DockingError("Open Babel executable `obabel` is required for receptor preparation") + + try: + result = run_command([obabel, str(prepared), "-O", str(receptor_mol2)], cwd=wd, timeout=120) + except TimeoutExpired as exc: + raise DockingError(f"obabel timed out while preparing receptor: {exc}") from exc + self._record_command( + stage="prepare_target_obabel", + result=result, + cwd=wd, + stdout_log=wd / "prepare_target_obabel.stdout.log", + stderr_log=wd / "prepare_target_obabel.stderr.log", + ) + if self._indicates_failure(result) or not receptor_mol2.exists() or receptor_mol2.stat().st_size == 0: + raise DockingError( + "Failed to produce receptor.mol2 from target structure. " + f"Return code: {result.returncode}, stderr: {result.stderr.strip()}" + ) + + pocket = self._resolve_target_pocket(source, wd) + self.logger.info( + "Resolved pocket mode=%s source=%s center=(%.3f, %.3f, %.3f) radius=%.3f", + pocket.mode, + pocket.source, + pocket.center[0], + pocket.center[1], + pocket.center[2], + pocket.radius, + ) + + return { + "target_prepared": prepared, + "receptor_mol2": receptor_mol2, + "target_work_dir": wd, + "pocket_spec_json": wd / "pocket_spec.json", + } + + def prepare_ligand(self, ligand_id: str, smiles: str, work_dir: str | Path) -> Path: + wd = Path(work_dir) + wd.mkdir(parents=True, exist_ok=True) + return prepare_ligand_sdf(ligand_id, smiles, wd / f"{ligand_id}.sdf") + + def build_site_or_constraints( + self, + target_context: Dict[str, Path], + reference_ligand: Path, + work_dir: str | Path, + ) -> Path: + receptor_mol2 = target_context.get("receptor_mol2") + if receptor_mol2 is None or not receptor_mol2.exists(): + raise DockingError("Missing receptor_mol2 in target context") + + wd = Path(work_dir) + wd.mkdir(parents=True, exist_ok=True) + + prm = wd / "receptor.prm" + pocket_json = target_context.get("pocket_spec_json") + if pocket_json and Path(pocket_json).exists(): + pocket = PocketSpec.from_dict(json.loads(Path(pocket_json).read_text(encoding="utf-8"))) + write_receptor_prm_sphere( + receptor_mol2=receptor_mol2, + center=pocket.center, + radius=pocket.radius, + out_path=prm, + ) + return prm + + if not self.config.allow_legacy_generated_pocket: + raise DockingError( + "Missing pocket_spec_json while strict fixed-pocket mode is active. " + "Provide user_fixed_pocket or reference_complex_pocket settings." + ) + + write_receptor_prm( + receptor_mol2=receptor_mol2, + reference_ligand_sdf=reference_ligand, + out_path=prm, + radius=self.config.mapper_radius, + ) + return prm + + @staticmethod + def _failed_real_result(ligand_id: str, message: str, command: Sequence[str] | None = None) -> DockingResult: + return DockingResult( + ligand_id=ligand_id, + docking_score=float("nan"), + pose_path=None, + backend_name="rdock", + backend_mode="real-rdock", + score_source="rdock_error", + raw_output_file="", + parsed_from="", + fallback_used=False, + success=False, + message=message, + command=" ".join(command) if command else "", + extra={}, + ) + + def dock( + self, + target_context: Dict[str, Path], + ligand_files: Sequence[Path], + work_dir: str | Path, + allow_mock: bool = False, + require_real_backend: bool = False, + ) -> list[DockingResult]: + self._ensure_runtime_env() + capability = self.check_capability() + wd = Path(work_dir) + wd.mkdir(parents=True, exist_ok=True) + + if allow_mock: + raise DockingError( + "Mock rDock fallback has been removed. Install/configure rDock and OpenBabel, " + "or call with allow_mock=False to receive the actionable real-backend error." + ) + + if not capability.available: + msg = f"rDock capability check failed: {capability.details}" + raise BackendUnavailableError(msg) + + if not ligand_files: + return [] + + pocket_spec: PocketSpec | None = None + pocket_json = target_context.get("pocket_spec_json") + if pocket_json is not None and Path(pocket_json).exists(): + pocket_spec = PocketSpec.from_dict(json.loads(Path(pocket_json).read_text(encoding="utf-8"))) + else: + target_prepared = target_context.get("target_prepared") + if target_prepared is not None and Path(target_prepared).exists(): + resolved = self._resolve_target_pocket(Path(target_prepared), Path(target_context.get("target_work_dir", wd))) + write_pocket_spec(Path(target_context.get("target_work_dir", wd)) / "pocket_spec.json", resolved) + target_context["pocket_spec_json"] = Path(target_context.get("target_work_dir", wd)) / "pocket_spec.json" + pocket_spec = resolved + + site_dir = Path(target_context.get("target_work_dir", wd)) + site_dir.mkdir(parents=True, exist_ok=True) + cached_prm = Path(target_context["site_prm"]) if "site_prm" in target_context else None + cached_cavity = Path(target_context["site_cavity"]) if "site_cavity" in target_context else None + if ( + cached_prm is not None + and cached_cavity is not None + and cached_prm.exists() + and cached_cavity.exists() + and cached_cavity.stat().st_size > 0 + ): + prm_file = cached_prm + cavity_file = cached_cavity + else: + prm_file = self.build_site_or_constraints(target_context, ligand_files[0], site_dir) + try: + cavity = run_command( + [self.config.rbcavity_bin, "-was", "-r", str(prm_file)], + cwd=site_dir, + timeout=self.config.command_timeout_seconds, + ) + except TimeoutExpired as exc: + raise DockingError(f"rbcavity timed out: {exc}") from exc + self._record_command( + stage="rbcavity", + result=cavity, + cwd=site_dir, + stdout_log=site_dir / "rbcavity.stdout.log", + stderr_log=site_dir / "rbcavity.stderr.log", + ) + + cavity_file = site_dir / f"{prm_file.stem}.as" + cavity_ok = cavity_file.exists() and cavity_file.stat().st_size > 0 + if self._indicates_failure(cavity) or not cavity_ok: + msg = ( + "rbcavity failed or did not produce cavity file. " + f"expected={cavity_file}, rc={cavity.returncode}, stderr={cavity.stderr.strip()}" + ) + raise DockingError(msg) + target_context["site_prm"] = prm_file + target_context["site_cavity"] = cavity_file + + # Keep batch-local cavity artifact for compatibility with existing validation/tests. + local_prm = wd / prm_file.name + if prm_file.exists() and prm_file != local_prm and not local_prm.exists(): + shutil.copy2(prm_file, local_prm) + local_cavity = wd / cavity_file.name + if cavity_file.exists() and cavity_file != local_cavity and not local_cavity.exists(): + shutil.copy2(cavity_file, local_cavity) + + protocol_prm = self._resolve_protocol_prm() + + def _dock_single(ligand_file: Path) -> DockingResult: + ligand_id = ligand_file.stem + out_prefix = wd / f"{ligand_id}_rdock" + cmd = [ + self.config.rbdock_bin, + "-i", + str(ligand_file), + "-o", + str(out_prefix), + "-r", + str(prm_file), + "-p", + str(protocol_prm), + "-n", + str(self.config.n_runs), + ] + if self.config.seed is not None: + cmd.extend(["-s", str(int(self.config.seed))]) + try: + proc = run_command(cmd, cwd=wd, timeout=self.config.command_timeout_seconds) + except TimeoutExpired as exc: + msg = f"rbdock timed out for {ligand_id}: {exc}" + if self.config.allow_partial_failures: + return self._failed_real_result(ligand_id, msg, cmd) + raise DockingError(msg) from exc + self._record_command( + stage=f"rbdock:{ligand_id}", + result=proc, + cwd=wd, + stdout_log=wd / f"{ligand_id}.rbdock.stdout.log", + stderr_log=wd / f"{ligand_id}.rbdock.stderr.log", + ) + + if self._indicates_failure(proc): + msg = f"rbdock failed for {ligand_id}: rc={proc.returncode}, stderr={proc.stderr.strip()}" + if self.config.allow_partial_failures: + return self._failed_real_result(ligand_id, msg, cmd) + raise DockingError(msg) + + pose_candidates = sorted(wd.glob(f"{ligand_id}_rdock*.sd")) + if not pose_candidates: + msg = f"rbdock produced no .sd output for {ligand_id} in {wd}" + if self.config.allow_partial_failures: + return self._failed_real_result(ligand_id, msg, cmd) + raise DockingError(msg) + + pose_file = pose_candidates[0] + try: + parsed = parse_rdock_sdf(pose_file) + except Exception as exc: + msg = f"Failed parsing rDock output for {ligand_id}: {exc}" + if self.config.allow_partial_failures: + return self._failed_real_result(ligand_id, msg, cmd) + raise DockingError(msg) from exc + + pose_centroid = centroid_from_sdf(pose_file) + pocket_distance = pose_distance_to_center(pose_centroid, pocket_spec) if pocket_spec is not None else float("nan") + pose_inside = is_pose_in_pocket(pose_centroid, pocket_spec) if pocket_spec is not None else False + + return DockingResult( + ligand_id=ligand_id, + docking_score=float(parsed["score"]), + pose_path=pose_file, + backend_name="rdock", + backend_mode="real-rdock", + score_source=f"rdock_tag:{parsed['score_tag']}", + raw_output_file=str(pose_file), + parsed_from=f"{pose_file}::{parsed['score_tag']}", + fallback_used=False, + success=True, + command=" ".join(cmd), + extra={ + "all_scores": parsed.get("all_scores", []), + "pose_count": parsed.get("pose_count"), + "rdock_native": parsed.get("native_features", {}), + "rdock_derived": parsed.get("derived_features", {}), + "rdock_feature_provenance": parsed.get("feature_provenance", []), + "pocket_spec": pocket_spec.to_dict() if pocket_spec is not None else {}, + "pose_centroid": pose_centroid.tolist() if pose_centroid.size == 3 and np.isfinite(pose_centroid).all() else [], + "pose_distance_to_pocket_center": pocket_distance, + "pose_in_fixed_pocket": pose_inside, + }, + ) + + results: list[DockingResult] = [] + jobs = max(1, int(self.config.parallel_jobs)) + if jobs <= 1 or len(ligand_files) <= 1: + for ligand_file in ligand_files: + results.append(_dock_single(ligand_file)) + else: + with ThreadPoolExecutor(max_workers=min(jobs, len(ligand_files))) as ex: + for res in ex.map(_dock_single, ligand_files): + results.append(res) + + return results + + def parse_results(self, results: Sequence[DockingResult]) -> list[dict[str, object]]: + parsed: list[dict[str, object]] = [] + nan = float("nan") + for result in results: + native = dict((result.extra or {}).get("rdock_native", {})) + derived = dict((result.extra or {}).get("rdock_derived", {})) + pocket = dict((result.extra or {}).get("pocket_spec", {})) + center = pocket.get("center", [nan, nan, nan]) + box = pocket.get("box_size", [nan, nan, nan]) + parsed.append( + { + "ligand_id": result.ligand_id, + "docking_score": float(result.docking_score), + "backend_name": result.backend_name, + "backend_mode": result.backend_mode, + "score_source": result.score_source, + "raw_output_file": result.raw_output_file, + "parsed_from": result.parsed_from, + "fallback_used": bool(result.fallback_used), + "success": bool(result.success), + "message": result.message, + "pose_path": str(result.pose_path) if result.pose_path else "", + "command": result.command, + "quantity_type": "docking_score", + "rdock_total_score": native.get("rdock_total_score", float(result.docking_score)), + "rdock_pose_rank": native.get("rdock_pose_rank", 1), + "n_generated_poses": native.get("n_generated_poses", (result.extra or {}).get("pose_count", 1)), + "best_pose_score": native.get("best_pose_score", float(result.docking_score)), + "mean_top3_pose_score": native.get("mean_top3_pose_score", float(result.docking_score)), + "mean_top5_pose_score": native.get("mean_top5_pose_score", float(result.docking_score)), + "std_top5_pose_score": native.get("std_top5_pose_score", nan), + "pose_score_gap_1_2": native.get("pose_score_gap_1_2", nan), + "rdock_restraint_term": native.get("rdock_restraint_term", nan), + "rdock_internal_ligand_term": native.get("rdock_internal_ligand_term", nan), + "rdock_polar_term": native.get("rdock_polar_term", nan), + "rdock_vdw_term": native.get("rdock_vdw_term", nan), + "top_pose_rmsd_consistency": derived.get("top_pose_rmsd_consistency", nan), + "contact_overlap_consistency": derived.get("contact_overlap_consistency", nan), + "hotspot_contact_frequency": derived.get("hotspot_contact_frequency", nan), + "subpocket_match_score": derived.get("subpocket_match_score", nan), + "replicate_mean_score": nan, + "replicate_score_variance": nan, + "replicate_consensus_score": nan, + "rdock_feature_provenance": json.dumps((result.extra or {}).get("rdock_feature_provenance", [])), + "pocket_mode": pocket.get("mode", ""), + "pocket_source": pocket.get("source", ""), + "pocket_center_x": float(center[0]) if isinstance(center, (list, tuple)) and len(center) == 3 else nan, + "pocket_center_y": float(center[1]) if isinstance(center, (list, tuple)) and len(center) == 3 else nan, + "pocket_center_z": float(center[2]) if isinstance(center, (list, tuple)) and len(center) == 3 else nan, + "pocket_radius": float(pocket.get("radius", nan)), + "pocket_box_size_x": float(box[0]) if isinstance(box, (list, tuple)) and len(box) == 3 else nan, + "pocket_box_size_y": float(box[1]) if isinstance(box, (list, tuple)) and len(box) == 3 else nan, + "pocket_box_size_z": float(box[2]) if isinstance(box, (list, tuple)) and len(box) == 3 else nan, + "pose_distance_to_pocket_center": float((result.extra or {}).get("pose_distance_to_pocket_center", nan)), + "pose_in_fixed_pocket": bool((result.extra or {}).get("pose_in_fixed_pocket", False)), + } + ) + return parsed + + def extract_interface_features(self, parsed_results: Sequence[dict[str, object]]) -> list[dict[str, float]]: + normalized = [{"docking_score": float(row.get("docking_score", 0.0))} for row in parsed_results] + return extract_simple_interface_features(normalized) diff --git a/libs/docking/backend_smina.py b/libs/docking/backend_smina.py new file mode 100644 index 0000000000000000000000000000000000000000..534f22e9f37775fe71a36a5b1766ba6779ef2008 --- /dev/null +++ b/libs/docking/backend_smina.py @@ -0,0 +1,342 @@ +from __future__ import annotations + +import math +import re +import shutil +import json +from dataclasses import dataclass +from pathlib import Path +from subprocess import TimeoutExpired +from typing import Any, Dict, Sequence + +import numpy as np +from concurrent.futures import ThreadPoolExecutor + +from libs.utils.subprocess_utils import run_command + +from .base import BackendCapability, DockingBackend, DockingError, DockingResult +from .pocket import ( + PocketSpec, + centroid_from_pdbqt, + is_pose_in_pocket, + pose_distance_to_center, + resolve_pocket_spec, + write_pocket_spec, +) +from .prep import prepare_ligand_sdf + +_FLOAT_RE = re.compile(r"[-+]?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?") + + +def _resolve_executable(name: str) -> str | None: + direct = shutil.which(name) + if direct: + return direct + candidates = [ + Path.home() / "miniconda3" / "envs" / "docking_diag" / "bin" / name, + Path.home() / "miniconda3" / "bin" / name, + ] + for c in candidates: + if c.exists(): + return str(c) + return None + + +def parse_smina_score(text: str) -> float: + """ + Parse smina score from combined output text. + + Supported patterns: + - `REMARK minimizedAffinity -7.6` + - `REMARK VINA RESULT: -7.6 ...` + - score table lines: `1 -7.6 ...` + """ + best = math.nan + for ln in text.splitlines(): + low = ln.lower() + if "minimizedaffinity" in low or "vina result" in low or low.startswith("affinity:"): + nums = _FLOAT_RE.findall(ln) + for tok in nums: + try: + val = float(tok) + except Exception: + continue + if math.isfinite(val): + if (not math.isfinite(best)) or val < best: + best = val + break + continue + stripped = ln.strip() + if not stripped or stripped.startswith("#"): + continue + cols = stripped.split() + if len(cols) >= 2 and cols[0].isdigit(): + try: + val = float(cols[1]) + except Exception: + continue + if math.isfinite(val): + if (not math.isfinite(best)) or val < best: + best = val + return float(best) if math.isfinite(best) else float("nan") + + +@dataclass +class SminaConfig: + smina_bin: str = "smina" + obabel_bin: str = "obabel" + command_timeout_seconds: int = 120 + exhaustiveness: int = 8 + num_modes: int = 5 + cpu: int = 1 + parallel_jobs: int = 1 + seed: int = 20260419 + pocket_mode: str = "reference_complex_pocket" + pocket_center: tuple[float, float, float] | str | list[float] | None = None + pocket_box_size: tuple[float, float, float] | str | list[float] | None = None + pocket_radius: float | None = None + pocket_reference_ligand_id: str | None = None + pocket_relaxation_margin: float = 0.0 + + +class SminaBackend(DockingBackend): + """ + Minimal smina backend used for fixed-pocket diagnostics. + + It intentionally keeps logic compact and explicit: + success is true only when command succeeds, output pose exists and score is finite. + """ + + def __init__(self, config: SminaConfig | None = None) -> None: + self.config = config or SminaConfig() + + def check_capability(self) -> BackendCapability: + bins = { + "smina": _resolve_executable(self.config.smina_bin), + "obabel": _resolve_executable(self.config.obabel_bin), + } + return BackendCapability( + backend_name="smina", + available=bool(bins["smina"] and bins["obabel"]), + details=bins, + ) + + def prepare_target(self, target_path: str | Path, work_dir: str | Path) -> Dict[str, Path]: + src = Path(target_path) + if not src.exists(): + raise DockingError(f"Missing target file: {src}") + wd = Path(work_dir) + wd.mkdir(parents=True, exist_ok=True) + + receptor_pdbqt = wd / "receptor.pdbqt" + obabel = _resolve_executable(self.config.obabel_bin) + if obabel is None: + raise DockingError("obabel is required for smina receptor preparation") + conv = run_command([obabel, str(src), "-O", str(receptor_pdbqt)], cwd=wd, timeout=self.config.command_timeout_seconds) + if conv.returncode != 0 or (not receptor_pdbqt.exists()) or receptor_pdbqt.stat().st_size == 0: + raise DockingError(f"Failed to prepare receptor.pdbqt for smina: rc={conv.returncode}") + + pocket = resolve_pocket_spec( + target_path=src, + pocket_mode=self.config.pocket_mode, + pocket_center=self.config.pocket_center, + pocket_box_size=self.config.pocket_box_size, + pocket_radius=self.config.pocket_radius, + pocket_reference_ligand_id=self.config.pocket_reference_ligand_id, + pocket_relaxation_margin=self.config.pocket_relaxation_margin, + fallback_radius=6.0, + ) + write_pocket_spec(wd / "pocket.json", pocket) + return { + "receptor_pdbqt": receptor_pdbqt, + "target_prepared": src, + "target_work_dir": wd, + "pocket_json": wd / "pocket.json", + } + + def prepare_ligand(self, ligand_id: str, smiles: str, work_dir: str | Path) -> Path: + wd = Path(work_dir) + wd.mkdir(parents=True, exist_ok=True) + sdf = prepare_ligand_sdf(ligand_id, smiles, wd / f"{ligand_id}.sdf") + out = wd / f"{ligand_id}.pdbqt" + obabel = _resolve_executable(self.config.obabel_bin) + if obabel is None: + raise DockingError("obabel is required for smina ligand preparation") + conv = run_command([obabel, str(sdf), "-O", str(out)], cwd=wd, timeout=self.config.command_timeout_seconds) + if conv.returncode != 0 or (not out.exists()) or out.stat().st_size == 0: + raise DockingError(f"Failed to prepare ligand pdbqt for smina `{ligand_id}`: rc={conv.returncode}") + return out + + def build_site_or_constraints(self, target_context: Dict[str, Path], reference_ligand: Path, work_dir: str | Path) -> Path: + _ = (target_context, reference_ligand, work_dir) + return Path() + + def dock( + self, + target_context: Dict[str, Path], + ligand_files: Sequence[Path], + work_dir: str | Path, + allow_mock: bool = False, + require_real_backend: bool = False, + ) -> list[DockingResult]: + _ = (allow_mock, require_real_backend) + cap = self.check_capability() + if not cap.available: + raise DockingError(f"smina backend unavailable: {cap.details}") + + wd = Path(work_dir) + wd.mkdir(parents=True, exist_ok=True) + receptor = target_context.get("receptor_pdbqt") + if receptor is None: + raise DockingError("Missing receptor_pdbqt in target context") + + pocket_json = target_context.get("pocket_json") + if pocket_json is not None and Path(pocket_json).exists(): + pocket = PocketSpec.from_dict(json.loads(Path(pocket_json).read_text(encoding="utf-8"))) + else: + pocket = resolve_pocket_spec( + target_path=target_context.get("target_prepared", receptor), + pocket_mode=self.config.pocket_mode, + pocket_center=self.config.pocket_center, + pocket_box_size=self.config.pocket_box_size, + pocket_radius=self.config.pocket_radius, + pocket_reference_ligand_id=self.config.pocket_reference_ligand_id, + pocket_relaxation_margin=self.config.pocket_relaxation_margin, + fallback_radius=6.0, + ) + results: list[DockingResult] = [] + smina = _resolve_executable(self.config.smina_bin) + if smina is None: + raise DockingError("smina executable not found") + + def _dock_single(lig: Path) -> DockingResult: + lid = lig.stem + out_pose = wd / f"{lid}_smina_out.pdbqt" + cmd = [ + smina, + "--receptor", + str(receptor), + "--ligand", + str(lig), + "--center_x", + f"{pocket.center[0]:.4f}", + "--center_y", + f"{pocket.center[1]:.4f}", + "--center_z", + f"{pocket.center[2]:.4f}", + "--size_x", + f"{pocket.box_size[0]:.4f}", + "--size_y", + f"{pocket.box_size[1]:.4f}", + "--size_z", + f"{pocket.box_size[2]:.4f}", + "--exhaustiveness", + str(self.config.exhaustiveness), + "--num_modes", + str(self.config.num_modes), + "--cpu", + str(self.config.cpu), + "--seed", + str(self.config.seed), + "--out", + str(out_pose), + ] + try: + res = run_command(cmd, cwd=wd, timeout=self.config.command_timeout_seconds) + except TimeoutExpired as exc: + return DockingResult( + ligand_id=lid, + docking_score=float("nan"), + pose_path=None, + backend_name="smina", + backend_mode="real-smina", + score_source="smina_timeout", + raw_output_file=str(out_pose), + parsed_from="timeout", + fallback_used=False, + success=False, + message=f"smina_timeout:{exc}", + command=" ".join(cmd), + extra={"pocket_spec": pocket.to_dict(), "pose_distance_to_pocket_center": float("nan"), "pose_in_fixed_pocket": False}, + ) + except Exception as exc: + return DockingResult( + ligand_id=lid, + docking_score=float("nan"), + pose_path=None, + backend_name="smina", + backend_mode="real-smina", + score_source="smina_error", + raw_output_file=str(out_pose), + parsed_from="exception", + fallback_used=False, + success=False, + message=f"smina_exception:{exc}", + command=" ".join(cmd), + extra={"pocket_spec": pocket.to_dict(), "pose_distance_to_pocket_center": float("nan"), "pose_in_fixed_pocket": False}, + ) + text = "\n".join([res.stdout or "", res.stderr or ""]) + if out_pose.exists(): + text = f"{text}\n{out_pose.read_text(encoding='utf-8', errors='ignore')}" + score = parse_smina_score(text) + centroid = centroid_from_pdbqt(out_pose) if out_pose.exists() else np.asarray([np.nan, np.nan, np.nan], dtype=float) + distance = pose_distance_to_center(centroid, pocket) + inside = is_pose_in_pocket(centroid, pocket) + success = bool(res.returncode == 0 and out_pose.exists() and np.isfinite(score)) + parsed_from = "stdout+stderr+pose::minimizedAffinity_or_vina_result_or_table" + return DockingResult( + ligand_id=lid, + docking_score=float(score) if np.isfinite(score) else float("nan"), + pose_path=out_pose if out_pose.exists() else None, + backend_name="smina", + backend_mode="real-smina", + score_source="smina_affinity", + raw_output_file=str(out_pose), + parsed_from=parsed_from, + fallback_used=False, + success=success, + message="" if success else f"smina_rc={res.returncode}", + command=" ".join(cmd), + extra={ + "pocket_spec": pocket.to_dict(), + "pose_distance_to_pocket_center": distance, + "pose_in_fixed_pocket": inside, + }, + ) + + jobs = max(1, int(self.config.parallel_jobs)) + if jobs <= 1 or len(ligand_files) <= 1: + for lig in ligand_files: + results.append(_dock_single(lig)) + else: + with ThreadPoolExecutor(max_workers=min(jobs, len(ligand_files))) as ex: + for res in ex.map(_dock_single, ligand_files): + results.append(res) + return results + + def parse_results(self, results: Sequence[DockingResult]) -> list[dict[str, Any]]: + rows: list[dict[str, Any]] = [] + for r in results: + rows.append( + { + "ligand_id": r.ligand_id, + "docking_score": float(r.docking_score), + "backend_name": r.backend_name, + "backend_mode": r.backend_mode, + "score_source": r.score_source, + "raw_output_file": r.raw_output_file, + "parsed_from": r.parsed_from, + "fallback_used": bool(r.fallback_used), + "success": bool(r.success), + "message": r.message, + "command": r.command, + "pose_distance_to_pocket_center": float((r.extra or {}).get("pose_distance_to_pocket_center", np.nan)), + "pose_in_fixed_pocket": bool((r.extra or {}).get("pose_in_fixed_pocket", False)), + "quantity_type": "docking_score", + } + ) + return rows + + def extract_interface_features(self, parsed_results: Sequence[dict[str, Any]]) -> list[dict[str, float]]: + _ = parsed_results + return [] diff --git a/libs/docking/base.py b/libs/docking/base.py new file mode 100644 index 0000000000000000000000000000000000000000..7266e96bd53d2da0db904e1e01cad599205be615 --- /dev/null +++ b/libs/docking/base.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Dict, Sequence + + +@dataclass +class BackendCapability: + backend_name: str + available: bool + details: Dict[str, Any] + + +@dataclass +class DockingResult: + ligand_id: str + docking_score: float + pose_path: Path | None + backend_name: str + backend_mode: str + score_source: str + raw_output_file: str + parsed_from: str + fallback_used: bool + success: bool + message: str = "" + command: str = "" + extra: Dict[str, Any] = field(default_factory=dict) + + +class DockingError(RuntimeError): + """Generic docking backend error.""" + + +class BackendUnavailableError(DockingError): + """Raised when requested backend capability is not available.""" + + +class DockingBackend(ABC): + """Common backend interface for all docking engines.""" + + @abstractmethod + def check_capability(self) -> BackendCapability: + pass + + @abstractmethod + def prepare_target(self, target_path: str | Path, work_dir: str | Path) -> Dict[str, Any]: + pass + + @abstractmethod + def prepare_ligand(self, ligand_id: str, smiles: str, work_dir: str | Path) -> Path: + pass + + @abstractmethod + def build_site_or_constraints( + self, + target_context: Dict[str, Any], + reference_ligand: Path, + work_dir: str | Path, + ) -> Path: + pass + + @abstractmethod + def dock( + self, + target_context: Dict[str, Any], + ligand_files: Sequence[Path], + work_dir: str | Path, + allow_mock: bool = False, + require_real_backend: bool = False, + ) -> list[DockingResult]: + pass + + @abstractmethod + def parse_results(self, results: Sequence[DockingResult]) -> list[dict[str, Any]]: + pass + + @abstractmethod + def extract_interface_features(self, parsed_results: Sequence[dict[str, Any]]) -> list[dict[str, float]]: + pass diff --git a/libs/docking/comparison.py b/libs/docking/comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..9e8cbf2a929d5f88c8412e6d2c51f5cc00b1bff2 --- /dev/null +++ b/libs/docking/comparison.py @@ -0,0 +1,135 @@ +from __future__ import annotations + +from typing import Dict + +import numpy as np +import pandas as pd + + +def backend_score_semantics(backend_name: str) -> str: + name = str(backend_name).strip().lower() + if name == "rdock": + return "rdock_docking_score_lower_better" + if name == "haddock": + return "haddock_emscoring_energy_proxy_lower_better" + return "unknown_score_semantics" + + +def build_backend_comparison_table(df: pd.DataFrame) -> pd.DataFrame: + """Build backend-comparison rows with explicit semantics and normalized scores.""" + if df.empty: + return pd.DataFrame( + columns=[ + "ligand_id", + "backend_name", + "backend_mode", + "raw_score", + "normalized_score", + "zscore_within_backend", + "score_semantics", + "direct_comparison_justified", + "provenance_path", + "parsed_from", + ] + ) + + work = df.copy() + if "docking_score" in work.columns and "raw_score" not in work.columns: + work["raw_score"] = pd.to_numeric(work["docking_score"], errors="coerce") + work["backend_name"] = work["backend_name"].astype(str) + work["backend_mode"] = work.get("backend_mode", "").astype(str) + work["score_semantics"] = work["backend_name"].map(backend_score_semantics) + work["provenance_path"] = work.get("raw_output_file", "").astype(str) + work["parsed_from"] = work.get("parsed_from", "").astype(str) + + norm = np.full(work.shape[0], np.nan, dtype=float) + z = np.full(work.shape[0], np.nan, dtype=float) + for backend, idx in work.groupby("backend_name").groups.items(): + vals = pd.to_numeric(work.loc[idx, "raw_score"], errors="coerce").to_numpy(dtype=float) + valid = np.isfinite(vals) + if valid.any(): + v = vals[valid] + ranks = pd.Series(v).rank(method="average", pct=True).to_numpy(dtype=float) + # lower score is better -> invert percentile for "higher is better normalized" + nv = 1.0 - ranks + mu = float(np.mean(v)) + sd = float(np.std(v)) + zv = (v - mu) / (sd if sd > 1e-9 else 1.0) + + # map back + norm_vals = np.full(vals.shape[0], np.nan, dtype=float) + z_vals = np.full(vals.shape[0], np.nan, dtype=float) + norm_vals[valid] = nv + z_vals[valid] = zv + norm[list(idx)] = norm_vals + z[list(idx)] = z_vals + + work["normalized_score"] = norm + work["zscore_within_backend"] = z + + unique_sem = set(work["score_semantics"].astype(str).tolist()) + direct = len(unique_sem) == 1 + work["direct_comparison_justified"] = bool(direct) + if not direct: + work["direct_comparison_justified"] = False + + cols = [ + "ligand_id", + "backend_name", + "backend_mode", + "raw_score", + "normalized_score", + "zscore_within_backend", + "score_semantics", + "direct_comparison_justified", + "provenance_path", + "parsed_from", + ] + for c in cols: + if c not in work.columns: + work[c] = np.nan + return work[cols].copy() + + +def summarize_backend_table(df: pd.DataFrame) -> pd.DataFrame: + if df.empty: + return pd.DataFrame( + columns=[ + "backend_name", + "score_semantics", + "n_scores", + "mean_raw_score", + "std_raw_score", + "mean_normalized_score", + "direct_comparison_justified", + ] + ) + rows = [] + for backend, sub in df.groupby("backend_name"): + rows.append( + { + "backend_name": str(backend), + "score_semantics": str(sub["score_semantics"].iloc[0]), + "n_scores": int(sub.shape[0]), + "mean_raw_score": float(pd.to_numeric(sub["raw_score"], errors="coerce").mean()), + "std_raw_score": float(pd.to_numeric(sub["raw_score"], errors="coerce").std()), + "mean_normalized_score": float(pd.to_numeric(sub["normalized_score"], errors="coerce").mean()), + "direct_comparison_justified": bool(sub["direct_comparison_justified"].all()), + } + ) + return pd.DataFrame(rows) + + +def semantic_compatibility_notes() -> Dict[str, str]: + return { + "rdock": "Pose generation + docking score; lower score is better.", + "haddock": ( + "HADDOCK emscoring on provided complexes/poses; energy proxy; " + "lower score is better; in this repository treated as rescoring semantics." + ), + "cross_backend": ( + "Direct raw-score comparison between rDock and HADDOCK is approximate; " + "prefer within-backend normalization / rank statistics." + ), + } + diff --git a/libs/docking/constraints.py b/libs/docking/constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..5f81089a55604c4f2cc3965b4f636ab1f6dcc7d7 --- /dev/null +++ b/libs/docking/constraints.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from pathlib import Path + + +def write_receptor_prm( + receptor_mol2: str | Path, + reference_ligand_sdf: str | Path, + out_path: str | Path, + radius: float = 6.0, +) -> Path: + """Write receptor parameter file required by rbcavity/rbdock.""" + receptor_path = Path(receptor_mol2).resolve() + reference_path = Path(reference_ligand_sdf).resolve() + + payload = ( + "RBT_PARAMETER_FILE_V1.00\n" + "TITLE rdock_receptor\n" + f"RECEPTOR_FILE {receptor_path}\n" + "\n" + "SECTION MAPPER\n" + " SITE_MAPPER RbtLigandSiteMapper\n" + f" REF_MOL {reference_path}\n" + f" RADIUS {radius:.1f}\n" + " SMALL_SPHERE 1.5\n" + "END_SECTION\n" + "\n" + "SECTION CAVITY\n" + " SCORING_FUNCTION RbtCavityGridSF\n" + "END_SECTION\n" + ) + + target = Path(out_path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(payload, encoding="utf-8") + return target + + +def write_receptor_prm_sphere( + receptor_mol2: str | Path, + center: tuple[float, float, float], + radius: float, + out_path: str | Path, +) -> Path: + """Write receptor prm using a fixed sphere mapper (stable pocket definition).""" + receptor_path = Path(receptor_mol2).resolve() + cx, cy, cz = float(center[0]), float(center[1]), float(center[2]) + rad = float(radius) + + payload = ( + "RBT_PARAMETER_FILE_V1.00\n" + "TITLE rdock_receptor_fixed_pocket\n" + f"RECEPTOR_FILE {receptor_path}\n" + "\n" + "SECTION MAPPER\n" + " SITE_MAPPER RbtSphereSiteMapper\n" + f" CENTER ({cx:.4f},{cy:.4f},{cz:.4f})\n" + f" RADIUS {rad:.3f}\n" + " SMALL_SPHERE 1.5\n" + " MIN_VOLUME 100\n" + " MAX_CAVITIES 1\n" + " VOL_INCR 0.0\n" + " GRIDSTEP 0.5\n" + "END_SECTION\n" + "\n" + "SECTION CAVITY\n" + " SCORING_FUNCTION RbtCavityGridSF\n" + "END_SECTION\n" + ) + + target = Path(out_path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(payload, encoding="utf-8") + return target diff --git a/libs/docking/interface_features.py b/libs/docking/interface_features.py new file mode 100644 index 0000000000000000000000000000000000000000..b810751980badb6a72831e28ef25012eb2968ee8 --- /dev/null +++ b/libs/docking/interface_features.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from typing import Dict, Sequence + + +def extract_simple_interface_features(parsed_results: Sequence[Dict[str, float | str]]) -> list[dict[str, float]]: + """Generate coarse interface-like descriptors from docking results.""" + features: list[dict[str, float]] = [] + for row in parsed_results: + score = float(row.get("docking_score", row.get("score", 0.0))) + features.append( + { + "interface_contact_proxy": max(0.0, -score / 10.0), + "hbond_proxy": max(0.0, -score / 20.0), + "shape_proxy": max(0.0, -score / 15.0), + } + ) + return features diff --git a/libs/docking/pocket.py b/libs/docking/pocket.py new file mode 100644 index 0000000000000000000000000000000000000000..209b702dcdb277ba2da23212923f8727a5d2c1b2 --- /dev/null +++ b/libs/docking/pocket.py @@ -0,0 +1,313 @@ +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np +from rdkit import Chem + +POCKET_MODE_USER_FIXED = "user_fixed_pocket" +POCKET_MODE_REFERENCE = "reference_complex_pocket" +POCKET_MODE_REFERENCE_RELAXED = "reference_complex_pocket_relaxed" +SUPPORTED_POCKET_MODES = { + POCKET_MODE_USER_FIXED, + POCKET_MODE_REFERENCE, + POCKET_MODE_REFERENCE_RELAXED, +} + + +@dataclass(frozen=True) +class PocketSpec: + mode: str + center: tuple[float, float, float] + radius: float + box_size: tuple[float, float, float] + reference_ligand_id: str | None = None + relaxation_margin: float = 0.0 + source: str = "unknown" + notes: str = "" + + def to_dict(self) -> dict[str, Any]: + return { + "mode": self.mode, + "center": list(self.center), + "radius": float(self.radius), + "box_size": list(self.box_size), + "reference_ligand_id": self.reference_ligand_id or "", + "relaxation_margin": float(self.relaxation_margin), + "source": self.source, + "notes": self.notes, + } + + @classmethod + def from_dict(cls, payload: dict[str, Any]) -> "PocketSpec": + center = _parse_vector3(payload.get("center"), field_name="center") + box = _parse_vector3(payload.get("box_size"), field_name="box_size") + return cls( + mode=str(payload.get("mode", POCKET_MODE_REFERENCE)), + center=center, + radius=float(payload.get("radius", 6.0)), + box_size=box, + reference_ligand_id=str(payload.get("reference_ligand_id", "")).strip() or None, + relaxation_margin=float(payload.get("relaxation_margin", 0.0)), + source=str(payload.get("source", "unknown")), + notes=str(payload.get("notes", "")), + ) + + +def _parse_vector3(value: Any, field_name: str) -> tuple[float, float, float]: + if value is None: + raise ValueError(f"{field_name} is required") + if isinstance(value, str): + text = value.replace(";", ",").replace(" ", "") + parts = [x for x in text.split(",") if x] + if len(parts) != 3: + raise ValueError(f"{field_name} must contain 3 values, got: {value}") + return (float(parts[0]), float(parts[1]), float(parts[2])) + + if isinstance(value, (tuple, list)) and len(value) == 3: + return (float(value[0]), float(value[1]), float(value[2])) + + raise ValueError(f"{field_name} must be a length-3 sequence") + + +def _derive_center_radius_box( + coords: np.ndarray, + relaxation_margin: float, + fallback_radius: float, +) -> tuple[tuple[float, float, float], float, tuple[float, float, float]]: + if coords.size == 0: + raise ValueError("cannot derive pocket from empty coordinates") + center = coords.mean(axis=0) + max_dist = float(np.linalg.norm(coords - center, axis=1).max()) if coords.shape[0] > 0 else 0.0 + radius = max(float(fallback_radius), max_dist + 2.0 + float(relaxation_margin)) + half_box = max(radius, 8.0) + box = (2.0 * half_box, 2.0 * half_box, 2.0 * half_box) + return (float(center[0]), float(center[1]), float(center[2])), float(radius), box + + +def _extract_receptor_atom_coords(target_path: str | Path) -> np.ndarray: + coords: list[list[float]] = [] + for ln in Path(target_path).read_text(encoding="utf-8", errors="ignore").splitlines(): + if not ln.startswith("ATOM"): + continue + try: + x = float(ln[30:38]) + y = float(ln[38:46]) + z = float(ln[46:54]) + except Exception: + continue + coords.append([x, y, z]) + return np.asarray(coords, dtype=float) + + +def extract_reference_ligand_coords( + target_path: str | Path, + pocket_reference_ligand_id: str | None, +) -> tuple[np.ndarray, dict[str, Any]]: + path = Path(target_path) + ligand_filter = (pocket_reference_ligand_id or "").strip().upper() + grouped: dict[tuple[str, str, str, str], list[list[float]]] = {} + residues: dict[tuple[str, str, str, str], str] = {} + for ln in path.read_text(encoding="utf-8", errors="ignore").splitlines(): + if not ln.startswith("HETATM"): + continue + resn = ln[17:20].strip().upper() + if not resn or resn in {"HOH", "WAT", "DOD", "SO4"}: + continue + if ligand_filter and resn != ligand_filter: + continue + try: + x = float(ln[30:38]) + y = float(ln[38:46]) + z = float(ln[46:54]) + except Exception: + continue + chain = ln[21:22].strip() + resseq = ln[22:26].strip() + ins = ln[26:27].strip() + key = (resn, chain, resseq, ins) + grouped.setdefault(key, []).append([x, y, z]) + residues[key] = resn + + if not grouped: + return np.asarray([], dtype=float), { + "selected_resname": "", + "selected_chain": "", + "selected_resseq": "", + "selected_atom_count": 0, + } + + selected = max(grouped, key=lambda k: len(grouped[k])) + coords = np.asarray(grouped[selected], dtype=float) + return coords, { + "selected_resname": residues[selected], + "selected_chain": selected[1], + "selected_resseq": selected[2], + "selected_atom_count": int(coords.shape[0]), + } + + +def resolve_pocket_spec( + *, + target_path: str | Path, + pocket_mode: str | None = None, + pocket_center: Any = None, + pocket_box_size: Any = None, + pocket_radius: float | None = None, + pocket_reference_ligand_id: str | None = None, + pocket_relaxation_margin: float = 0.0, + fallback_radius: float = 6.0, +) -> PocketSpec: + mode = str(pocket_mode or POCKET_MODE_REFERENCE).strip() + if mode not in SUPPORTED_POCKET_MODES: + raise ValueError(f"Unsupported pocket_mode `{mode}`. Supported: {sorted(SUPPORTED_POCKET_MODES)}") + + # Explicit center + shape always wins over inferred modes. + if pocket_center is not None and (pocket_radius is not None or pocket_box_size is not None): + center = _parse_vector3(pocket_center, field_name="pocket_center") + radius = float(pocket_radius) if pocket_radius is not None else float(max(_parse_vector3(pocket_box_size, "pocket_box_size")) / 2.0) + box = _parse_vector3(pocket_box_size, "pocket_box_size") if pocket_box_size is not None else (2.0 * radius, 2.0 * radius, 2.0 * radius) + return PocketSpec( + mode=POCKET_MODE_USER_FIXED, + center=center, + radius=float(radius), + box_size=box, + reference_ligand_id=str(pocket_reference_ligand_id or "").strip() or None, + relaxation_margin=0.0, + source="user_explicit_override", + notes="Explicit pocket center/size provided by user; inferred modes skipped.", + ) + + if mode == POCKET_MODE_USER_FIXED: + center = _parse_vector3(pocket_center, field_name="pocket_center") + if pocket_radius is None and pocket_box_size is None: + raise ValueError("user_fixed_pocket requires pocket_radius or pocket_box_size") + radius = float(pocket_radius) if pocket_radius is not None else float(max(_parse_vector3(pocket_box_size, "pocket_box_size")) / 2.0) + box = _parse_vector3(pocket_box_size, "pocket_box_size") if pocket_box_size is not None else (2.0 * radius, 2.0 * radius, 2.0 * radius) + return PocketSpec( + mode=POCKET_MODE_USER_FIXED, + center=center, + radius=float(radius), + box_size=box, + reference_ligand_id=str(pocket_reference_ligand_id or "").strip() or None, + relaxation_margin=0.0, + source="user_fixed_pocket", + notes="Fixed pocket from explicit user configuration.", + ) + + margin = float(pocket_relaxation_margin if mode == POCKET_MODE_REFERENCE_RELAXED else 0.0) + coords, meta = extract_reference_ligand_coords(target_path=target_path, pocket_reference_ligand_id=pocket_reference_ligand_id) + if coords.size > 0: + center, derived_radius, box = _derive_center_radius_box(coords, relaxation_margin=margin, fallback_radius=fallback_radius) + radius = float(pocket_radius) if pocket_radius is not None else float(derived_radius) + if pocket_box_size is not None: + box = _parse_vector3(pocket_box_size, "pocket_box_size") + return PocketSpec( + mode=mode, + center=center, + radius=float(radius), + box_size=box, + reference_ligand_id=meta.get("selected_resname") or (str(pocket_reference_ligand_id).strip() if pocket_reference_ligand_id else None), + relaxation_margin=float(margin), + source="reference_complex_ligand", + notes=( + "Fixed pocket from crystal ligand coordinates " + f"(resname={meta.get('selected_resname', '')}, atoms={meta.get('selected_atom_count', 0)})." + ), + ) + + receptor_coords = _extract_receptor_atom_coords(target_path) + if receptor_coords.size == 0: + raise ValueError("Cannot resolve fixed pocket: no reference ligand and no receptor atom coordinates found") + center = receptor_coords.mean(axis=0) + radius = float(pocket_radius) if pocket_radius is not None else float(fallback_radius) + box = _parse_vector3(pocket_box_size, "pocket_box_size") if pocket_box_size is not None else (2.0 * radius, 2.0 * radius, 2.0 * radius) + return PocketSpec( + mode=mode, + center=(float(center[0]), float(center[1]), float(center[2])), + radius=float(radius), + box_size=box, + reference_ligand_id=str(pocket_reference_ligand_id or "").strip() or None, + relaxation_margin=float(margin), + source="receptor_centroid_fallback", + notes="Reference ligand not found; deterministic receptor-centroid fixed pocket fallback used.", + ) + + +def write_pocket_spec(path: str | Path, spec: PocketSpec) -> Path: + p = Path(path) + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(json.dumps(spec.to_dict(), indent=2), encoding="utf-8") + return p + + +def load_pocket_spec(path: str | Path) -> PocketSpec: + payload = json.loads(Path(path).read_text(encoding="utf-8")) + return PocketSpec.from_dict(payload) + + +def centroid_from_sdf(path: str | Path) -> np.ndarray: + mols = Chem.SDMolSupplier(str(path), removeHs=False) + mol = mols[0] if mols and len(mols) > 0 else None + if mol is None or mol.GetNumConformers() == 0: + return np.asarray([np.nan, np.nan, np.nan], dtype=float) + conf = mol.GetConformer() + pts = [] + for i in range(mol.GetNumAtoms()): + p = conf.GetAtomPosition(i) + pts.append([p.x, p.y, p.z]) + if not pts: + return np.asarray([np.nan, np.nan, np.nan], dtype=float) + return np.asarray(pts, dtype=float).mean(axis=0) + + +def centroid_from_pdbqt(path: str | Path) -> np.ndarray: + pts: list[list[float]] = [] + text = Path(path).read_text(encoding="utf-8", errors="ignore") + has_models = "MODEL" in text + in_model = False + for ln in text.splitlines(): + if ln.startswith("MODEL"): + in_model = True + continue + if ln.startswith("ENDMDL"): + break + if has_models and (not in_model): + continue + if not ln.startswith(("ATOM", "HETATM")): + continue + try: + x = float(ln[30:38]) + y = float(ln[38:46]) + z = float(ln[46:54]) + except Exception: + continue + pts.append([x, y, z]) + if not pts: + return np.asarray([np.nan, np.nan, np.nan], dtype=float) + return np.asarray(pts, dtype=float).mean(axis=0) + + +def pose_distance_to_center(centroid: np.ndarray, spec: PocketSpec) -> float: + if centroid.size != 3 or not np.isfinite(centroid).all(): + return float("nan") + center = np.asarray(spec.center, dtype=float) + return float(np.linalg.norm(centroid - center)) + + +def is_pose_in_pocket(centroid: np.ndarray, spec: PocketSpec) -> bool: + if centroid.size != 3 or not np.isfinite(centroid).all(): + return False + center = np.asarray(spec.center, dtype=float) + box = np.asarray(spec.box_size, dtype=float) + if box.size == 3 and np.isfinite(box).all(): + inside_box = bool(np.all(np.abs(centroid - center) <= (box / 2.0))) + else: + inside_box = False + if inside_box: + return True + dist = float(np.linalg.norm(centroid - center)) + return bool(np.isfinite(dist) and dist <= float(spec.radius)) diff --git a/libs/docking/pose_parsing.py b/libs/docking/pose_parsing.py new file mode 100644 index 0000000000000000000000000000000000000000..f53ea3ba0ff400ae0aa91e4636c57a70e20921e8 --- /dev/null +++ b/libs/docking/pose_parsing.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +from pathlib import Path +from .rdock_features import parse_rdock_output + + +def parse_rdock_sdf(path: str | Path) -> dict[str, object]: + """Parse real rDock SDF output and extract native/derived score features.""" + source = Path(path) + return parse_rdock_output(source) diff --git a/libs/docking/prep.py b/libs/docking/prep.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd1da8c2011910bb471faa474d5b1bdbc979cb3 --- /dev/null +++ b/libs/docking/prep.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from pathlib import Path + +from rdkit import Chem +from rdkit.Chem import AllChem + + +def _embed_3d_with_retries(mol: Chem.Mol) -> bool: + """Try multiple RDKit embedding strategies to guarantee a 3D conformer.""" + attempts = [] + + p1 = AllChem.ETKDGv3() + p1.randomSeed = 42 + attempts.append(p1) + + p2 = AllChem.ETKDGv2() + p2.randomSeed = 42 + attempts.append(p2) + + p3 = AllChem.ETKDGv3() + p3.randomSeed = 42 + p3.useRandomCoords = True + attempts.append(p3) + + for params in attempts: + try: + mol.RemoveAllConformers() + status = AllChem.EmbedMolecule(mol, params) + if int(status) != 0: + continue + if mol.GetNumConformers() == 0: + continue + try: + AllChem.UFFOptimizeMolecule(mol, maxIters=300) + except Exception: + # Keep conformer if optimization fails. + pass + return bool(mol.GetConformer().Is3D()) + except Exception: + continue + return False + + +def prepare_ligand_sdf(ligand_id: str, smiles: str, out_path: str | Path) -> Path: + """Prepare ligand SDF with optional 3D coordinates for docking.""" + mol = Chem.MolFromSmiles(smiles) + if mol is None: + raise ValueError(f"Invalid SMILES for ligand {ligand_id}: {smiles}") + mol = Chem.AddHs(mol) + + has_3d = _embed_3d_with_retries(mol) + if not has_3d: + raise ValueError(f"Failed to generate 3D conformer for ligand {ligand_id}") + + mol.SetProp("_Name", ligand_id) + target = Path(out_path) + target.parent.mkdir(parents=True, exist_ok=True) + writer = Chem.SDWriter(str(target)) + writer.write(mol) + writer.close() + return target diff --git a/libs/docking/rdock_features.py b/libs/docking/rdock_features.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f855fb1a40ba2819bede2d32ccafb3f188d498 --- /dev/null +++ b/libs/docking/rdock_features.py @@ -0,0 +1,232 @@ +from __future__ import annotations + +import math +import re +from pathlib import Path +from typing import Any, Dict, List, Tuple + +import numpy as np +from rdkit import Chem +from rdkit.Chem import rdMolAlign + + +TAG_RE = re.compile(r"^>\s*<\s*([^>]+?)\s*>", flags=re.IGNORECASE) + + +def _safe_float(value: object) -> float | None: + try: + v = float(value) # type: ignore[arg-type] + except Exception: + return None + if not np.isfinite(v): + return None + return float(v) + + +def _split_sdf_blocks(text: str) -> List[str]: + blocks = [] + for part in text.split("$$$$"): + block = part.strip() + if block: + blocks.append(block + "\n$$$$\n") + return blocks + + +def _parse_block_tags(block: str) -> Dict[str, str]: + lines = block.splitlines() + tags: Dict[str, str] = {} + i = 0 + while i < len(lines): + m = TAG_RE.match(lines[i].strip()) + if not m: + i += 1 + continue + tag = m.group(1).strip() + value = "" + if i + 1 < len(lines): + value = lines[i + 1].strip() + tags[tag] = value + i += 2 + return tags + + +def _pose_molecules(blocks: List[str]) -> List[Chem.Mol | None]: + out: List[Chem.Mol | None] = [] + for b in blocks: + mol = None + try: + mol = Chem.MolFromMolBlock(b, sanitize=False, removeHs=False, strictParsing=False) + except Exception: + mol = None + out.append(mol) + return out + + +def _pose_rmsd_stats(poses: List[Dict[str, Any]], mols: List[Chem.Mol | None], top_k: int = 5) -> Dict[str, float | None]: + if not poses: + return {"top_pose_rmsd_consistency": None, "geometry_similarity_top5": None} + + top = sorted(poses, key=lambda x: x["score"])[: max(1, min(top_k, len(poses)))] + top_idx = [int(x["pose_idx"]) for x in top] + if not top_idx: + return {"top_pose_rmsd_consistency": None, "geometry_similarity_top5": None} + + ref_idx = int(top_idx[0]) + ref_mol = mols[ref_idx] if 0 <= ref_idx < len(mols) else None + if ref_mol is None: + return {"top_pose_rmsd_consistency": None, "geometry_similarity_top5": None} + + rmsds: List[float] = [] + for idx in top_idx[1:]: + if idx < 0 or idx >= len(mols): + continue + mol = mols[idx] + if mol is None: + continue + try: + if ref_mol.GetNumAtoms() != mol.GetNumAtoms(): + continue + rmsd = float(rdMolAlign.GetBestRMS(ref_mol, mol)) + if np.isfinite(rmsd): + rmsds.append(rmsd) + except Exception: + continue + + if not rmsds: + return {"top_pose_rmsd_consistency": None, "geometry_similarity_top5": None} + + mean_rmsd = float(np.mean(np.asarray(rmsds, dtype=float))) + geom_sim = float(1.0 / (1.0 + mean_rmsd)) + return {"top_pose_rmsd_consistency": mean_rmsd, "geometry_similarity_top5": geom_sim} + + +def parse_rdock_output(path: str | Path) -> Dict[str, Any]: + """ + Parse real rDock SDF output and compute native + derived multi-pose features. + + Native features are direct tags parsed from rDock output (`SCORE*`). + Derived features are computed from real generated poses and are explicitly marked as proxies where needed. + """ + source = Path(path) + if not source.exists(): + raise ValueError(f"rDock output file does not exist: {source}") + if source.stat().st_size == 0: + raise ValueError(f"rDock output file is empty: {source}") + + raw = source.read_text(encoding="utf-8", errors="ignore") + blocks = _split_sdf_blocks(raw) + if not blocks: + raise ValueError(f"No molecule blocks found in real rDock output: {source}") + + poses: List[Dict[str, Any]] = [] + for i, block in enumerate(blocks): + tags = _parse_block_tags(block) + score = _safe_float(tags.get("SCORE")) + if score is None: + continue + poses.append({"pose_idx": i, "pose_rank": int(tags.get("RI", i) or i) + 1, "score": score, "tags": tags}) + + if not poses: + raise ValueError(f"No SCORE fields found in real rDock output: {source}") + + poses = sorted(poses, key=lambda x: x["score"]) + scores = [float(p["score"]) for p in poses] + best = poses[0] + top3 = scores[:3] + top5 = scores[:5] + + native = { + "rdock_total_score": float(best["score"]), + "rdock_pose_rank": int(best.get("pose_rank", 1)), + "n_generated_poses": int(len(scores)), + "best_pose_score": float(best["score"]), + "mean_top3_pose_score": float(np.mean(top3)), + "mean_top5_pose_score": float(np.mean(top5)), + "std_top5_pose_score": float(np.std(np.asarray(top5, dtype=float), ddof=0)), + "pose_score_gap_1_2": float(scores[1] - scores[0]) if len(scores) > 1 else np.nan, + "rdock_restraint_term": _safe_float(best["tags"].get("SCORE.RESTR")), + "rdock_internal_ligand_term": _safe_float(best["tags"].get("SCORE.INTRA")), + "rdock_polar_term": _safe_float(best["tags"].get("SCORE.INTER.POLAR")), + "rdock_vdw_term": _safe_float(best["tags"].get("SCORE.INTER.VDW")), + "rdock_inter_term": _safe_float(best["tags"].get("SCORE.INTER")), + "rdock_intra_vdw_term": _safe_float(best["tags"].get("SCORE.INTRA.VDW")), + "rdock_intra_dih_term": _safe_float(best["tags"].get("SCORE.INTRA.DIHEDRAL")), + "rdock_norm_score": _safe_float(best["tags"].get("SCORE.norm")), + "rdock_heavy_atoms": _safe_float(best["tags"].get("SCORE.heavy")), + } + + mols = _pose_molecules(blocks) + rmsd_stats = _pose_rmsd_stats(poses=poses, mols=mols, top_k=5) + + std5 = native["std_top5_pose_score"] + if std5 is None or (isinstance(std5, float) and (not np.isfinite(std5))): + pose_stability = None + else: + pose_stability = float(math.exp(-float(std5))) + + inter_scores: List[float] = [] + for p in poses[:5]: + v = _safe_float(p["tags"].get("SCORE.INTER")) + if v is not None: + inter_scores.append(float(v)) + inter_std = float(np.std(np.asarray(inter_scores), ddof=0)) if inter_scores else np.nan + + # Explicitly proxy-derived (not directly reported by rDock tags). + derived = { + "n_valid_poses": int(len(scores)), + "top_pose_rmsd_consistency": rmsd_stats["top_pose_rmsd_consistency"], + "contact_overlap_consistency": (float(1.0 / (1.0 + inter_std)) if np.isfinite(inter_std) else np.nan), + "hotspot_contact_frequency": ( + float(np.mean([1.0 if (_safe_float(p["tags"].get("SCORE.INTER")) or 0.0) < 0.0 else 0.0 for p in poses[:5]])) + if poses + else np.nan + ), + "subpocket_match_score": pose_stability if pose_stability is not None else np.nan, + "consensus_contact_score": (float(-np.mean(np.asarray(inter_scores, dtype=float))) if inter_scores else np.nan), + "consensus_hotspot_coverage": ( + float(np.mean([1.0 if (_safe_float(p["tags"].get("SCORE.INTER.VDW")) or 0.0) < 0.0 else 0.0 for p in poses[:5]])) + if poses + else np.nan + ), + "pose_stability_proxy": pose_stability, + "geometry_similarity_top5": rmsd_stats["geometry_similarity_top5"], + } + + feature_provenance: List[Dict[str, Any]] = [] + for name, val in native.items(): + feature_provenance.append( + { + "feature_name": name, + "feature_source": "rdock_native", + "pose_source": "best_pose" if name.startswith("rdock_") else "top5", + "raw_output_file": str(source), + "parsed_from": f"{source}::SDF_TAG", + "feature_type": "exact" if val is not None and np.isfinite(float(val)) else "unavailable", + "available": bool(val is not None and np.isfinite(float(val))), + } + ) + for name, val in derived.items(): + feature_provenance.append( + { + "feature_name": name, + "feature_source": "rdock_derived", + "pose_source": "top5" if ("top" in name or "consensus" in name) else "best_pose", + "raw_output_file": str(source), + "parsed_from": f"{source}::derived", + "feature_type": "proxy" if val is not None and np.isfinite(float(val)) else "unavailable", + "available": bool(val is not None and np.isfinite(float(val))), + } + ) + + return { + "pose_path": str(source), + "score": float(native["best_pose_score"]), + "score_tag": "SCORE", + "all_scores": scores, + "pose_count": int(len(scores)), + "poses": poses, + "native_features": native, + "derived_features": derived, + "feature_provenance": feature_provenance, + } + diff --git a/libs/encoders/__init__.py b/libs/encoders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75d7c3015949077889c065d673c92e8bd4db0414 --- /dev/null +++ b/libs/encoders/__init__.py @@ -0,0 +1,14 @@ +"""Encoders for ligands and proteins.""" + +from .ligand_encoder import LigandEncoder +from .protein_encoder import ProteinEncoder +from .schemas import LigandEncoding, LigandGraph, ProteinEncoding, ProteinGraph + +__all__ = [ + "LigandEncoder", + "LigandEncoding", + "LigandGraph", + "ProteinEncoder", + "ProteinEncoding", + "ProteinGraph", +] diff --git a/libs/encoders/graph_builders.py b/libs/encoders/graph_builders.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee2b2e6f895370b01e3cd16dd476aac78ee1460 --- /dev/null +++ b/libs/encoders/graph_builders.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Dict, List, Sequence + +import numpy as np +from Bio.PDB.Polypeptide import protein_letters_3to1 + +from libs.utils.io_pdb import load_structure + +from .schemas import LigandGraph, ProteinGraph + + +def build_ligand_graph(mol) -> LigandGraph: + """Build atom-level graph from an RDKit Mol object.""" + atom_features: List[List[float]] = [] + for atom in mol.GetAtoms(): + atom_features.append( + [ + float(atom.GetAtomicNum()), + float(atom.GetTotalDegree()), + float(atom.GetFormalCharge()), + float(atom.GetIsAromatic()), + float(atom.GetMass()), + ] + ) + + edges: List[List[int]] = [] + edge_features: List[List[float]] = [] + for bond in mol.GetBonds(): + i = bond.GetBeginAtomIdx() + j = bond.GetEndAtomIdx() + btype = float(bond.GetBondTypeAsDouble()) + ring = float(bond.IsInRing()) + edges.extend([[i, j], [j, i]]) + edge_features.extend([[btype, ring], [btype, ring]]) + + if not edges: + edge_index = np.zeros((2, 0), dtype=int) + edge_attr = np.zeros((0, 2), dtype=float) + else: + edge_index = np.asarray(edges, dtype=int).T + edge_attr = np.asarray(edge_features, dtype=float) + + node = np.asarray(atom_features, dtype=float) if atom_features else np.zeros((0, 5), dtype=float) + return LigandGraph(node_features=node, edge_index=edge_index, edge_features=edge_attr) + + +def _residue_name_to_one_letter(resname: str) -> str: + return protein_letters_3to1.get(resname.upper(), "X") + + +def build_protein_graph(structure_path: str | Path, distance_threshold: float = 8.0, pocket_residues: Sequence[str] | None = None) -> ProteinGraph: + """Build residue-level graph with distance-threshold edges.""" + structure = load_structure(structure_path) + residues = [r for r in structure.get_residues() if r.id[0] == " "] + + coords = [] + node_features = [] + node_labels: List[str] = [] + pocket_set = set(pocket_residues or []) + + for residue in residues: + chain = residue.get_parent().id + idx = residue.id[1] + label = f"{chain}:{idx}" + ca = residue["CA"].coord if "CA" in residue else None + if ca is None: + atoms = [atom.coord for atom in residue.get_atoms()] + ca = np.mean(np.asarray(atoms, dtype=float), axis=0) if atoms else np.zeros(3, dtype=float) + + aa = _residue_name_to_one_letter(residue.resname) + aa_index = float(ord(aa) - ord("A")) if aa.isalpha() else -1.0 + node_features.append( + [ + float(idx), + aa_index, + float(label in pocket_set), + ] + ) + coords.append(np.asarray(ca, dtype=float)) + node_labels.append(label) + + if not coords: + return ProteinGraph(node_features=np.zeros((0, 3)), edge_index=np.zeros((2, 0), dtype=int), node_labels=[]) + + xyz = np.vstack(coords) + n = xyz.shape[0] + edges: List[List[int]] = [] + for i in range(n): + for j in range(i + 1, n): + dist = float(np.linalg.norm(xyz[i] - xyz[j])) + if dist <= distance_threshold: + edges.extend([[i, j], [j, i]]) + + edge_index = np.asarray(edges, dtype=int).T if edges else np.zeros((2, 0), dtype=int) + return ProteinGraph(node_features=np.asarray(node_features, dtype=float), edge_index=edge_index, node_labels=node_labels) + + +def protein_sequence_from_structure(structure_path: str | Path) -> str: + """Derive a rough sequence by concatenating residue symbols from the first model.""" + structure = load_structure(structure_path) + residues = [r for r in structure.get_residues() if r.id[0] == " "] + return "".join(_residue_name_to_one_letter(r.resname) for r in residues) diff --git a/libs/encoders/ligand_encoder.py b/libs/encoders/ligand_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..c2dc934189257a526c22aeee46e5b18f639d211c --- /dev/null +++ b/libs/encoders/ligand_encoder.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, Iterable, List, Optional + +import numpy as np +import pandas as pd +from rdkit import Chem +from rdkit.Chem import AllChem, Descriptors +from rdkit.Chem.rdFingerprintGenerator import GetMorganGenerator + +from .graph_builders import build_ligand_graph +from .schemas import LigandEncoding + + +@dataclass +class LigandEncoderConfig: + radius: int = 2 + n_bits: int = 1024 + generate_3d: bool = False + + +class LigandEncoder: + """Encode ligands from SMILES/SDF into vectors and graph objects.""" + + def __init__(self, config: Optional[LigandEncoderConfig] = None) -> None: + self.config = config or LigandEncoderConfig() + self._fp_gen = GetMorganGenerator(radius=self.config.radius, fpSize=self.config.n_bits) + + def _mol_from_smiles(self, smiles: str): + mol = Chem.MolFromSmiles(smiles) + if mol is None: + raise ValueError(f"Invalid SMILES: {smiles}") + mol = Chem.AddHs(mol) + if self.config.generate_3d: + params = AllChem.ETKDGv3() + params.randomSeed = 42 + status = AllChem.EmbedMolecule(mol, params) + if status == 0: + AllChem.UFFOptimizeMolecule(mol) + return mol + + def _fingerprint(self, mol) -> np.ndarray: + fp = self._fp_gen.GetFingerprint(mol) + return np.asarray(fp, dtype=float) + + def _descriptors(self, mol) -> Dict[str, float]: + return { + "mw": float(Descriptors.MolWt(mol)), + "logp": float(Descriptors.MolLogP(mol)), + "hbd": float(Descriptors.NumHDonors(mol)), + "hba": float(Descriptors.NumHAcceptors(mol)), + "tpsa": float(Descriptors.TPSA(mol)), + "rot_bonds": float(Descriptors.NumRotatableBonds(mol)), + "ring_count": float(Descriptors.RingCount(mol)), + } + + def encode_smiles(self, ligand_id: str, smiles: str) -> LigandEncoding: + mol = self._mol_from_smiles(smiles) + fp = self._fingerprint(mol) + desc = self._descriptors(mol) + graph = build_ligand_graph(mol) + desc_vec = np.asarray(list(desc.values()), dtype=float) + vector = np.concatenate([fp, desc_vec]) + prep = { + "canonical_smiles": Chem.MolToSmiles(Chem.RemoveHs(mol), canonical=True), + "formula": str(Descriptors.rdMolDescriptors.CalcMolFormula(mol)), + "mw": float(desc["mw"]), + } + return LigandEncoding( + ligand_id=ligand_id, + smiles=smiles, + fingerprint=fp, + descriptors=desc, + graph=graph, + vector=vector, + prep=prep, + ) + + def encode_table(self, ligands: pd.DataFrame) -> List[LigandEncoding]: + rows = [] + for row in ligands.itertuples(index=False): + rows.append(self.encode_smiles(str(row.ligand_id), str(row.smiles))) + return rows + + def encode_sdf(self, sdf_path: str | Path) -> List[LigandEncoding]: + suppl = Chem.SDMolSupplier(str(sdf_path), removeHs=False) + output: List[LigandEncoding] = [] + for idx, mol in enumerate(suppl): + if mol is None: + continue + mol_h = Chem.AddHs(Chem.RemoveHs(mol)) + lig_id = mol_h.GetProp("_Name") if mol_h.HasProp("_Name") else f"lig_{idx:04d}" + smiles = Chem.MolToSmiles(Chem.RemoveHs(mol_h), canonical=True) + fp = self._fingerprint(mol_h) + desc = self._descriptors(mol_h) + graph = build_ligand_graph(mol_h) + vector = np.concatenate([fp, np.asarray(list(desc.values()), dtype=float)]) + prep = { + "canonical_smiles": smiles, + "formula": str(Descriptors.rdMolDescriptors.CalcMolFormula(mol_h)), + "mw": float(desc["mw"]), + } + output.append( + LigandEncoding( + ligand_id=lig_id, + smiles=smiles, + fingerprint=fp, + descriptors=desc, + graph=graph, + vector=vector, + prep=prep, + ) + ) + return output diff --git a/libs/encoders/protein_encoder.py b/libs/encoders/protein_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..a67bdcb146827148c593eeca2ec915d4781c0e84 --- /dev/null +++ b/libs/encoders/protein_encoder.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Optional, Sequence + +import numpy as np + +from .graph_builders import build_protein_graph, protein_sequence_from_structure +from .schemas import ProteinEncoding +from .sequence_features import compute_sequence_features +from .structure_features import compute_structure_features + + +@dataclass +class ProteinEncoderConfig: + distance_threshold: float = 8.0 + + +class ProteinEncoder: + """Encode protein structures from PDB/mmCIF for scheduling/modeling.""" + + def __init__(self, config: Optional[ProteinEncoderConfig] = None): + self.config = config or ProteinEncoderConfig() + + def encode_structure( + self, + target_id: str, + structure_path: str | Path, + pocket_residues: Sequence[str] | None = None, + ) -> ProteinEncoding: + sequence = protein_sequence_from_structure(structure_path) + seq_features = compute_sequence_features(sequence) + struct_features = compute_structure_features(structure_path, pocket_residues=pocket_residues) + graph = build_protein_graph( + structure_path, + distance_threshold=self.config.distance_threshold, + pocket_residues=pocket_residues, + ) + combined = {**seq_features, **struct_features} + vector = np.asarray(list(combined.values()), dtype=float) + return ProteinEncoding( + target_id=target_id, + sequence=sequence, + sequence_features=seq_features, + structure_features=struct_features, + graph=graph, + vector=vector, + ) diff --git a/libs/encoders/schemas.py b/libs/encoders/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..6ab03aed185b7341bf5b3f47792a89393b191729 --- /dev/null +++ b/libs/encoders/schemas.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, List + +import numpy as np + + +@dataclass +class LigandGraph: + """Lightweight ligand graph representation for downstream modeling.""" + + node_features: np.ndarray + edge_index: np.ndarray + edge_features: np.ndarray + + +@dataclass +class LigandEncoding: + """Encoded ligand outputs used across clustering and docking prep.""" + + ligand_id: str + smiles: str + fingerprint: np.ndarray + descriptors: Dict[str, float] + graph: LigandGraph + vector: np.ndarray + prep: Dict[str, str | float | int] + + +@dataclass +class ProteinGraph: + """Residue-level protein graph representation.""" + + node_features: np.ndarray + edge_index: np.ndarray + node_labels: List[str] + + +@dataclass +class ProteinEncoding: + """Encoded protein outputs for scheduling and surrogate modeling.""" + + target_id: str + sequence: str + sequence_features: Dict[str, float] + structure_features: Dict[str, float] + graph: ProteinGraph + vector: np.ndarray diff --git a/libs/encoders/sequence_features.py b/libs/encoders/sequence_features.py new file mode 100644 index 0000000000000000000000000000000000000000..be1b08c005e472d5c192a877f23a53ac1fe27c0e --- /dev/null +++ b/libs/encoders/sequence_features.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from typing import Dict + + +AA_ALPHABET = "ACDEFGHIKLMNPQRSTVWY" + + +def compute_sequence_features(sequence: str) -> Dict[str, float]: + """Compute simple amino-acid composition and coarse biochemical summaries.""" + seq = sequence.strip().upper() + length = max(len(seq), 1) + + features: Dict[str, float] = {f"aa_frac_{aa}": seq.count(aa) / length for aa in AA_ALPHABET} + aromatic = set("FWY") + polar = set("STNQ") + charged = set("KRHDE") + + features.update( + { + "seq_length": float(len(seq)), + "frac_aromatic": sum(1 for aa in seq if aa in aromatic) / length, + "frac_polar": sum(1 for aa in seq if aa in polar) / length, + "frac_charged": sum(1 for aa in seq if aa in charged) / length, + } + ) + return features diff --git a/libs/encoders/structure_features.py b/libs/encoders/structure_features.py new file mode 100644 index 0000000000000000000000000000000000000000..133a456fc794cf54f96f7e0223d02eb86f74ed29 --- /dev/null +++ b/libs/encoders/structure_features.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Dict, Sequence + +import numpy as np + +from libs.utils.io_pdb import load_structure + + +def _residue_centroid(residue) -> np.ndarray | None: + coords = [atom.coord for atom in residue.get_atoms()] + if not coords: + return None + return np.mean(np.asarray(coords, dtype=float), axis=0) + + +def compute_structure_features(structure_path: str | Path, pocket_residues: Sequence[str] | None = None) -> Dict[str, float]: + """Compute structure-derived summary features from PDB/mmCIF.""" + structure = load_structure(structure_path) + residues = [r for r in structure.get_residues() if r.id[0] == " "] + atoms = list(structure.get_atoms()) + + centroids = [] + for residue in residues: + c = _residue_centroid(residue) + if c is not None: + centroids.append(c) + if centroids: + xyz = np.vstack(centroids) + extent = xyz.max(axis=0) - xyz.min(axis=0) + mean_extent = float(np.mean(extent)) + else: + mean_extent = 0.0 + + pocket_count = 0.0 + pocket_residue_set = set(pocket_residues or []) + if pocket_residue_set: + for residue in residues: + chain = residue.get_parent().id + idx = residue.id[1] + key = f"{chain}:{idx}" + if key in pocket_residue_set: + pocket_count += 1.0 + + return { + "residue_count": float(len(residues)), + "atom_count": float(len(atoms)), + "mean_spatial_extent": mean_extent, + "pocket_residue_count": pocket_count, + } diff --git a/libs/modalities/__init__.py b/libs/modalities/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9328b5030b6fe3c0da60eb31f585652261d2f16c --- /dev/null +++ b/libs/modalities/__init__.py @@ -0,0 +1,16 @@ +"""Modalities beyond small-molecule docking (for architecture-level sanity checks).""" + +from .peptide_like import ( + PeptideBenchmarkConfig, + build_peptide_like_dataset, + extract_chain_sequence, + run_peptide_like_proxy_benchmark, +) + +__all__ = [ + "PeptideBenchmarkConfig", + "build_peptide_like_dataset", + "extract_chain_sequence", + "run_peptide_like_proxy_benchmark", +] + diff --git a/libs/modalities/peptide_like.py b/libs/modalities/peptide_like.py new file mode 100644 index 0000000000000000000000000000000000000000..50c7cc9783da86ccfcbbdc99ac14f8b1ca695f68 --- /dev/null +++ b/libs/modalities/peptide_like.py @@ -0,0 +1,256 @@ +from __future__ import annotations + +import random +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, List, Sequence + +import numpy as np +import pandas as pd +import requests +from Bio.Align import substitution_matrices +from Bio.PDB.Polypeptide import protein_letters_3to1 + +from libs.encoders.protein_encoder import ProteinEncoder +from libs.utils.io_pdb import load_structure + +AA_ALPHABET = list("ACDEFGHIKLMNPQRSTVWY") +HYDROPHOBIC = set("AVILMFWY") +POSITIVE = set("KRH") +NEGATIVE = set("DE") + + +@dataclass +class PeptideBenchmarkConfig: + target_name: str + reference_pdb_id: str + receptor_chain_id: str + peptide_chain_id: str + n_variants: int + random_seed: int + min_length: int = 8 + max_length: int = 20 + + +def download_pdb(pdb_id: str, out_path: Path) -> Path: + out_path.parent.mkdir(parents=True, exist_ok=True) + url = f"https://files.rcsb.org/download/{pdb_id}.pdb" + resp = requests.get(url, timeout=60) + resp.raise_for_status() + out_path.write_text(resp.text, encoding="utf-8") + return out_path + + +def extract_chain_sequence(structure_path: str | Path, chain_id: str) -> str: + structure = load_structure(structure_path, structure_id="peptide_like") + model = next(structure.get_models()) + if chain_id not in model: + raise ValueError(f"Chain `{chain_id}` not found in structure `{structure_path}`") + + seq: List[str] = [] + for residue in model[chain_id].get_residues(): + if residue.id[0] != " ": + continue + seq.append(protein_letters_3to1.get(residue.resname.upper(), "X")) + out = "".join(seq).replace("X", "") + if not out: + raise ValueError(f"No peptide/protein residues extracted for chain `{chain_id}` in `{structure_path}`") + return out + + +def _seq_identity(a: str, b: str) -> float: + n = min(len(a), len(b)) + if n == 0: + return 0.0 + return float(sum(1 for i in range(n) if a[i] == b[i]) / n) + + +def _blosum62_mean(a: str, b: str) -> float: + matrix = substitution_matrices.load("BLOSUM62") + n = min(len(a), len(b)) + if n == 0: + return 0.0 + scores = [] + for i in range(n): + aa = a[i] + bb = b[i] + if (aa, bb) in matrix: + scores.append(float(matrix[(aa, bb)])) + elif (bb, aa) in matrix: + scores.append(float(matrix[(bb, aa)])) + if not scores: + return 0.0 + return float(np.mean(scores)) + + +def _frac(seq: str, residues: Sequence[str]) -> float: + if not seq: + return 0.0 + r = set(residues) + return float(sum(1 for x in seq if x in r) / len(seq)) + + +def _anchor_positions(reference: str) -> List[int]: + # For alpha-helical MDM2-like peptides anchors often include aromatic/hydrophobic residues. + ranked = sorted(range(len(reference)), key=lambda i: (reference[i] in {"F", "W", "L", "Y"}, i), reverse=True) + out = sorted(ranked[:3]) + return out + + +def _mutate_sequence(reference: str, rng: random.Random, anchor_pos: Sequence[int]) -> str: + seq = list(reference) + n_mut = 1 if rng.random() < 0.65 else 2 + for _ in range(n_mut): + i = rng.randrange(len(seq)) + if i in anchor_pos and rng.random() < 0.8: + continue + if seq[i] in HYDROPHOBIC: + candidates = [x for x in AA_ALPHABET if x in HYDROPHOBIC] + elif seq[i] in POSITIVE: + candidates = [x for x in AA_ALPHABET if x in POSITIVE] + elif seq[i] in NEGATIVE: + candidates = [x for x in AA_ALPHABET if x in NEGATIVE] + else: + candidates = AA_ALPHABET + seq[i] = rng.choice(candidates) + return "".join(seq) + + +def build_peptide_like_dataset(cfg: PeptideBenchmarkConfig, structure_path: Path) -> pd.DataFrame: + reference_seq = extract_chain_sequence(structure_path, cfg.peptide_chain_id) + if not (cfg.min_length <= len(reference_seq) <= cfg.max_length): + raise ValueError( + f"Reference peptide length {len(reference_seq)} is outside configured bounds " + f"[{cfg.min_length}, {cfg.max_length}]" + ) + + rng = random.Random(cfg.random_seed) + anchor_pos = _anchor_positions(reference_seq) + + rows: List[Dict[str, object]] = [ + { + "ligand_id": "pep_ref_000", + "sequence": reference_seq, + "is_reference": True, + "source": "experimental_reference", + "parent_reference_id": "pep_ref_000", + } + ] + seen = {reference_seq} + while len(rows) < max(2, int(cfg.n_variants)): + s = _mutate_sequence(reference_seq, rng, anchor_pos) + if s in seen: + continue + seen.add(s) + rows.append( + { + "ligand_id": f"pep_var_{len(rows)-1:03d}", + "sequence": s, + "is_reference": False, + "source": "generated_conservative_variant", + "parent_reference_id": "pep_ref_000", + } + ) + + df = pd.DataFrame(rows) + df["sequence_identity_to_ref"] = df["sequence"].map(lambda s: _seq_identity(str(s), reference_seq)) + df["blosum62_to_ref"] = df["sequence"].map(lambda s: _blosum62_mean(str(s), reference_seq)) + return df + + +def _peptide_features(sequence: str, reference_seq: str, anchor_pos: Sequence[int]) -> Dict[str, float]: + seq = str(sequence) + ref = str(reference_seq) + n = min(len(seq), len(ref)) + anchors = [i for i in anchor_pos if i < n] + anchor_match = float(np.mean([1.0 if seq[i] == ref[i] else 0.0 for i in anchors])) if anchors else 0.0 + hydrophobic_diff = abs(_frac(seq, list(HYDROPHOBIC)) - _frac(ref, list(HYDROPHOBIC))) + charge_diff = abs((_frac(seq, list(POSITIVE)) - _frac(seq, list(NEGATIVE))) - (_frac(ref, list(POSITIVE)) - _frac(ref, list(NEGATIVE)))) + len_penalty = abs(len(seq) - len(ref)) / max(1, len(ref)) + return { + "seq_identity": _seq_identity(seq, ref), + "blosum62_mean": _blosum62_mean(seq, ref), + "anchor_match": anchor_match, + "hydrophobic_fraction": _frac(seq, list(HYDROPHOBIC)), + "charged_fraction": _frac(seq, list(POSITIVE) + list(NEGATIVE)), + "hydrophobic_diff_to_ref": hydrophobic_diff, + "charge_diff_to_ref": charge_diff, + "length_penalty": len_penalty, + "aromatic_count": float(sum(1 for x in seq if x in {"F", "W", "Y"})), + } + + +def _proxy_affinity_score(features: Dict[str, float], target_extent: float) -> float: + # Lower is better (affinity-like proxy). + raw = ( + 2.0 * (1.0 - features["seq_identity"]) + + 1.4 * (1.0 - features["anchor_match"]) + + 1.0 * features["hydrophobic_diff_to_ref"] + + 0.7 * features["charge_diff_to_ref"] + + 0.8 * features["length_penalty"] + - 0.06 * features["blosum62_mean"] + ) + # mild target-structure scaling (keeps pipeline linked to structural context) + scale = 1.0 + min(0.2, max(0.0, target_extent / 200.0)) + return float(raw * scale) + + +def run_peptide_like_proxy_benchmark( + cfg: PeptideBenchmarkConfig, + structure_path: Path, +) -> Dict[str, pd.DataFrame]: + ligands_df = build_peptide_like_dataset(cfg, structure_path=structure_path) + ref_seq = str(ligands_df.loc[ligands_df["is_reference"].astype(bool), "sequence"].iloc[0]) + anchor_pos = _anchor_positions(ref_seq) + + protein_encoding = ProteinEncoder().encode_structure( + target_id=f"{cfg.target_name}_{cfg.reference_pdb_id}_{cfg.receptor_chain_id}", + structure_path=structure_path, + ) + target_extent = float(protein_encoding.structure_features.get("mean_spatial_extent", 0.0)) + + feature_rows: List[Dict[str, object]] = [] + rank_rows: List[Dict[str, object]] = [] + for row in ligands_df.itertuples(index=False): + feats = _peptide_features(str(row.sequence), reference_seq=ref_seq, anchor_pos=anchor_pos) + score = _proxy_affinity_score(feats, target_extent=target_extent) + feature_rows.append( + { + "ligand_id": str(row.ligand_id), + "sequence": str(row.sequence), + "is_reference": bool(row.is_reference), + **feats, + "target_mean_spatial_extent": target_extent, + } + ) + rank_rows.append( + { + "ligand_id": str(row.ligand_id), + "sequence": str(row.sequence), + "is_reference": bool(row.is_reference), + "source": str(row.source), + "parent_reference_id": str(row.parent_reference_id), + "sequence_identity_to_ref": float(row.sequence_identity_to_ref), + "blosum62_to_ref": float(row.blosum62_to_ref), + "backend_name": "peptide_proxy", + "backend_mode": "proxy-peptide-like", + "score_source": "sequence_structural_proxy_v1", + "quantity_type": "affinity_proxy", + "fallback_used": False, + "success": True, + "docking_score": float(score), + "final_score": float(score), + "message": "", + } + ) + + features_df = pd.DataFrame(feature_rows) + ranking = pd.DataFrame(rank_rows).sort_values("final_score", ascending=True).reset_index(drop=True) + ranking["rank"] = np.arange(1, ranking.shape[0] + 1) + return { + "ranking_df": ranking, + "features_df": features_df, + "ligands_df": ligands_df, + "protein_features": pd.DataFrame([protein_encoding.structure_features | protein_encoding.sequence_features]), + } + diff --git a/libs/utils/__init__.py b/libs/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..47b4516a459bb092c2c3cd0c2ed6277e31ef919f --- /dev/null +++ b/libs/utils/__init__.py @@ -0,0 +1,8 @@ +"""Utility helpers for IO, config, logging, subprocesses, and paths.""" + +from .cache import DiskCache +from .config import load_config +from .logging_utils import get_logger +from .paths import ProjectPaths + +__all__ = ["DiskCache", "ProjectPaths", "get_logger", "load_config"] diff --git a/libs/utils/cache.py b/libs/utils/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..adbcfa92fa23cadd3cd2b66f039b32d820b4510f --- /dev/null +++ b/libs/utils/cache.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any + + +@dataclass +class DiskCache: + """Simple JSON-on-disk cache for reproducible intermediate artifacts.""" + + cache_dir: Path + + def __post_init__(self) -> None: + self.cache_dir.mkdir(parents=True, exist_ok=True) + + def _path(self, key: str) -> Path: + safe_key = key.replace("/", "_") + return self.cache_dir / f"{safe_key}.json" + + def set(self, key: str, value: Any) -> Path: + target = self._path(key) + with target.open("w", encoding="utf-8") as handle: + json.dump(value, handle, indent=2) + return target + + def get(self, key: str) -> Any | None: + target = self._path(key) + if not target.exists(): + return None + with target.open("r", encoding="utf-8") as handle: + return json.load(handle) diff --git a/libs/utils/config.py b/libs/utils/config.py new file mode 100644 index 0000000000000000000000000000000000000000..44b7abd8affa24c30a699945ee409cd8fe44c6c3 --- /dev/null +++ b/libs/utils/config.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any, Dict + +import yaml + + +def load_config(path: str | Path) -> Dict[str, Any]: + """Load YAML config into a plain dictionary.""" + config_path = Path(path) + with config_path.open("r", encoding="utf-8") as handle: + data = yaml.safe_load(handle) or {} + if not isinstance(data, dict): + raise ValueError(f"Config at {config_path} must be a mapping") + return data diff --git a/libs/utils/conversions.py b/libs/utils/conversions.py new file mode 100644 index 0000000000000000000000000000000000000000..2a878b14f98ba2b1b5cedae0803f3fcc985d0083 --- /dev/null +++ b/libs/utils/conversions.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Optional + + +def pdb_to_pdbqt_placeholder(pdb_path: str | Path, out_path: str | Path) -> Path: + """Placeholder conversion hook. Copies source content for adapter-level wiring tests.""" + source = Path(pdb_path) + target = Path(out_path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(source.read_text(encoding="utf-8"), encoding="utf-8") + return target + + +def smiles_to_sdf_placeholder(smiles: str, ligand_id: str, out_path: str | Path) -> Path: + """Write minimal placeholder SDF-like file used when backend preprocessing is unavailable.""" + target = Path(out_path) + target.parent.mkdir(parents=True, exist_ok=True) + payload = f"{ligand_id}\n generated\n\n0 0 0 0 0 0 999 V2000\nM END\n> \n{smiles}\n\n$$$$\n" + target.write_text(payload, encoding="utf-8") + return target + + +def maybe_float(value: object, default: Optional[float] = None) -> Optional[float]: + try: + return float(value) # type: ignore[arg-type] + except (TypeError, ValueError): + return default diff --git a/libs/utils/io_fasta.py b/libs/utils/io_fasta.py new file mode 100644 index 0000000000000000000000000000000000000000..149571ee007f4cd346f43515973f668eba8dd177 --- /dev/null +++ b/libs/utils/io_fasta.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Dict + + +def read_fasta(path: str | Path) -> Dict[str, str]: + """Read FASTA entries into mapping of record id to sequence.""" + source = Path(path) + records: Dict[str, str] = {} + current_id = None + current_seq: list[str] = [] + + for line in source.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line: + continue + if line.startswith(">"): # FASTA header + if current_id is not None: + records[current_id] = "".join(current_seq) + current_id = line[1:].split()[0] + current_seq = [] + else: + current_seq.append(line) + + if current_id is not None: + records[current_id] = "".join(current_seq) + return records diff --git a/libs/utils/io_pdb.py b/libs/utils/io_pdb.py new file mode 100644 index 0000000000000000000000000000000000000000..a120480f636b9fd17bf030b697ef70e60e333ce9 --- /dev/null +++ b/libs/utils/io_pdb.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any, Dict + +from Bio.PDB import MMCIFParser, PDBParser + + +def load_structure(path: str | Path, structure_id: str = "target") -> Any: + """Load PDB or mmCIF structure object using Biopython.""" + source = Path(path) + suffix = source.suffix.lower() + if suffix in {".pdb", ".ent"}: + parser = PDBParser(QUIET=True) + return parser.get_structure(structure_id, str(source)) + if suffix in {".cif", ".mmcif"}: + parser = MMCIFParser(QUIET=True) + return parser.get_structure(structure_id, str(source)) + raise ValueError(f"Unsupported structure extension: {source}") + + +def summarize_structure(path: str | Path) -> Dict[str, int]: + structure = load_structure(path) + residues = [r for r in structure.get_residues() if r.id[0] == " "] + atoms = list(structure.get_atoms()) + chains = list(structure.get_chains()) + return {"residue_count": len(residues), "atom_count": len(atoms), "chain_count": len(chains)} diff --git a/libs/utils/io_smiles.py b/libs/utils/io_smiles.py new file mode 100644 index 0000000000000000000000000000000000000000..b9ec9a74484b8eea2ca936847e1d757824b9c857 --- /dev/null +++ b/libs/utils/io_smiles.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from pathlib import Path + +import pandas as pd + + +REQUIRED_COLUMNS = {"ligand_id", "smiles"} + + +def read_smiles_table(path: str | Path) -> pd.DataFrame: + """Read ligand table with required columns ligand_id and smiles.""" + source = Path(path) + if source.suffix.lower() in {".tsv", ".txt"}: + df = pd.read_csv(source, sep="\t") + else: + df = pd.read_csv(source) + missing = REQUIRED_COLUMNS - set(df.columns) + if missing: + raise ValueError(f"Missing required columns in {source}: {sorted(missing)}") + return df + + +def write_smiles_table(df: pd.DataFrame, path: str | Path) -> Path: + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + df.to_csv(target, index=False) + return target diff --git a/libs/utils/io_tables.py b/libs/utils/io_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..32bf915fe035cc1d5da63315e83d0a2d311e4e3c --- /dev/null +++ b/libs/utils/io_tables.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from pathlib import Path + +import pandas as pd + + +def read_table(path: str | Path) -> pd.DataFrame: + source = Path(path) + suffix = source.suffix.lower() + if suffix in {".csv", ".txt", ".tsv"}: + sep = "\t" if suffix in {".tsv", ".txt"} else "," + return pd.read_csv(source, sep=sep) + if suffix == ".parquet": + return pd.read_parquet(source) + raise ValueError(f"Unsupported table format: {source}") + + +def write_table(df: pd.DataFrame, path: str | Path) -> Path: + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + suffix = target.suffix.lower() + if suffix == ".csv": + df.to_csv(target, index=False) + elif suffix == ".parquet": + df.to_parquet(target, index=False) + else: + raise ValueError(f"Unsupported output table format: {target}") + return target diff --git a/libs/utils/logging_utils.py b/libs/utils/logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8274d792250266cb47e06faa673e1ed4f135e6f9 --- /dev/null +++ b/libs/utils/logging_utils.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +import logging +from pathlib import Path + + +def get_logger(name: str, log_file: Path | None = None, level: int = logging.INFO) -> logging.Logger: + """Create or retrieve a configured logger.""" + logger = logging.getLogger(name) + logger.setLevel(level) + + if not logger.handlers: + formatter = logging.Formatter("%(asctime)s | %(levelname)s | %(name)s | %(message)s") + + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + logger.addHandler(stream_handler) + + if log_file is not None: + log_file.parent.mkdir(parents=True, exist_ok=True) + file_handler = logging.FileHandler(log_file) + file_handler.setFormatter(formatter) + logger.addHandler(file_handler) + + return logger diff --git a/libs/utils/paths.py b/libs/utils/paths.py new file mode 100644 index 0000000000000000000000000000000000000000..172f44a3f7605cdec4182bcf0d35aec835b5ce97 --- /dev/null +++ b/libs/utils/paths.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + + +@dataclass +class ProjectPaths: + """Resolved project paths for data/results/config management.""" + + root: Path + + @property + def data_dir(self) -> Path: + return self.root / "data" + + @property + def results_dir(self) -> Path: + return self.root / "results" + + @property + def configs_dir(self) -> Path: + return self.root / "configs" + + def ensure(self) -> None: + for path in [ + self.data_dir / "raw", + self.data_dir / "processed", + self.data_dir / "targets", + self.data_dir / "ligands", + self.data_dir / "benchmarks", + self.results_dir / "smoke_test", + self.results_dir / "demo_run", + ]: + path.mkdir(parents=True, exist_ok=True) diff --git a/libs/utils/subprocess_utils.py b/libs/utils/subprocess_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1b0dbaae72cd5eb7e836cc2f08c38f50b3555668 --- /dev/null +++ b/libs/utils/subprocess_utils.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import subprocess +from dataclasses import dataclass +from pathlib import Path +from typing import Sequence + + +@dataclass +class CommandResult: + command: list[str] + returncode: int + stdout: str + stderr: str + + +class SubprocessError(RuntimeError): + """Raised on failed subprocess execution when strict mode is enabled.""" + + +def run_command( + command: Sequence[str], + cwd: Path | None = None, + timeout: int | None = None, + strict: bool = False, +) -> CommandResult: + """Run command via subprocess with robust, non-throwing default behavior.""" + proc = subprocess.run( + list(command), + cwd=str(cwd) if cwd else None, + timeout=timeout, + check=False, + capture_output=True, + text=True, + ) + result = CommandResult(command=list(command), returncode=proc.returncode, stdout=proc.stdout, stderr=proc.stderr) + if strict and result.returncode != 0: + raise SubprocessError( + f"Command failed ({result.returncode}): {' '.join(result.command)}\n{result.stderr.strip()}" + ) + return result diff --git a/scripts/build_portable_bundle.sh b/scripts/build_portable_bundle.sh new file mode 100644 index 0000000000000000000000000000000000000000..2b4cf95ae645012506031bb0984ed9d9e3db9fc2 --- /dev/null +++ b/scripts/build_portable_bundle.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +BUNDLE_DIR="${ROOT_DIR}/portable_rdock_pipeline" + +rm -rf "${BUNDLE_DIR}" +mkdir -p "${BUNDLE_DIR}/scripts" "${BUNDLE_DIR}/configs" "${BUNDLE_DIR}/data/examples" "${BUNDLE_DIR}/tests_minimal" + +cp -R "${ROOT_DIR}/docking_pipeline" "${BUNDLE_DIR}/docking_pipeline" +cp -R "${ROOT_DIR}/libs" "${BUNDLE_DIR}/libs" +cp "${ROOT_DIR}/scripts/prepare_pdb_ligand_dataset.py" "${BUNDLE_DIR}/scripts/prepare_pdb_ligand_dataset.py" +cp "${ROOT_DIR}/scripts/download_example_smiles.py" "${BUNDLE_DIR}/scripts/download_example_smiles.py" +cp "${ROOT_DIR}/scripts/build_portable_bundle.sh" "${BUNDLE_DIR}/scripts/build_portable_bundle.sh" +cp "${ROOT_DIR}/configs/multifidelity_defaults.yaml" "${BUNDLE_DIR}/configs/multifidelity_defaults.yaml" +cp "${ROOT_DIR}/configs/known_good_pdb_complexes.yaml" "${BUNDLE_DIR}/configs/known_good_pdb_complexes.yaml" +cp "${ROOT_DIR}/data/examples/example_smiles.smi" "${BUNDLE_DIR}/data/examples/example_smiles.smi" +cp "${ROOT_DIR}/data/examples/example_smiles_1000.smi" "${BUNDLE_DIR}/data/examples/example_smiles_1000.smi" +cp "${ROOT_DIR}/data/examples/example_pdb_dataset_config.yaml" "${BUNDLE_DIR}/data/examples/example_pdb_dataset_config.yaml" +cp "${ROOT_DIR}/environment.yml" "${BUNDLE_DIR}/environment.yml" +cp "${ROOT_DIR}/setup_server.sh" "${BUNDLE_DIR}/setup_server.sh" +cp "${ROOT_DIR}/check_environment.sh" "${BUNDLE_DIR}/check_environment.sh" +cp "${ROOT_DIR}/README_SERVER.md" "${BUNDLE_DIR}/README_SERVER.md" +cp -R "${ROOT_DIR}/tests_minimal/." "${BUNDLE_DIR}/tests_minimal/" + +find "${BUNDLE_DIR}" -name "__pycache__" -type d -prune -exec rm -rf {} + +find "${BUNDLE_DIR}" -name "*.pyc" -delete +find "${BUNDLE_DIR}" -name ".DS_Store" -delete + +echo "Built portable bundle at ${BUNDLE_DIR}" diff --git a/scripts/download_example_smiles.py b/scripts/download_example_smiles.py new file mode 100644 index 0000000000000000000000000000000000000000..f947cac817d7024ec4a1b2ed1e667ca626acb24a --- /dev/null +++ b/scripts/download_example_smiles.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import argparse +import csv +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_SOURCE_CSV = ROOT / "data" / "ligands" / "prelim_set_mdm2_4hg7" / "shared_library_dedup.csv" +DEFAULT_BUNDLED_SMI = ROOT / "data" / "examples" / "example_smiles_1000.smi" + + +def _write_rows(rows: list[tuple[str, str]], out: Path) -> Path: + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text("\n".join(f"{smiles} {ligand_id}" for smiles, ligand_id in rows) + "\n", encoding="utf-8") + return out + + +def _read_smi(path: Path, n: int) -> list[tuple[str, str]]: + rows: list[tuple[str, str]] = [] + for idx, line in enumerate(path.read_text(encoding="utf-8").splitlines()): + text = line.strip() + if not text or text.startswith("#"): + continue + parts = text.split() + smiles = parts[0] + ligand_id = parts[1] if len(parts) > 1 else f"lig_{idx:05d}" + rows.append((smiles, ligand_id)) + if len(rows) >= n: + break + return rows + + +def _read_csv_rows(path: Path, n: int) -> list[tuple[str, str]]: + rows: list[tuple[str, str]] = [] + with path.open("r", encoding="utf-8", newline="") as handle: + reader = csv.DictReader(handle) + for idx, item in enumerate(reader): + smiles = str(item.get("smiles", "")).strip() + ligand_id = str(item.get("ligand_id", "")).strip() or f"lig_{idx:05d}" + if not smiles: + continue + rows.append((smiles, ligand_id)) + if len(rows) >= n: + break + return rows + + +def main() -> int: + parser = argparse.ArgumentParser(description="Prepare a real 1000-SMILES example file from the public benchmark library in this repo.") + parser.add_argument("--n", type=int, default=1000) + parser.add_argument("--out", default=str(DEFAULT_BUNDLED_SMI)) + args = parser.parse_args() + + out = Path(args.out) + if DEFAULT_SOURCE_CSV.exists(): + rows = _read_csv_rows(DEFAULT_SOURCE_CSV, args.n) + if len(rows) < args.n: + raise SystemExit( + f"Requested {args.n} SMILES but {DEFAULT_SOURCE_CSV} yielded only {len(rows)} rows." + ) + _write_rows(rows, out) + print(out) + return 0 + + if DEFAULT_BUNDLED_SMI.exists(): + rows = _read_smi(DEFAULT_BUNDLED_SMI, args.n) + if len(rows) < args.n: + raise SystemExit( + f"Requested {args.n} SMILES but bundled file {DEFAULT_BUNDLED_SMI} contains only {len(rows)} rows." + ) + _write_rows(rows, out) + print(out) + return 0 + + raise SystemExit( + "No real example 1000-SMILES source is available. Expected either " + f"{DEFAULT_SOURCE_CSV} or {DEFAULT_BUNDLED_SMI}." + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/prepare_pdb_ligand_dataset.py b/scripts/prepare_pdb_ligand_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d2b9c5eef0ffd7d161c8ad482b3ce3363ea832 --- /dev/null +++ b/scripts/prepare_pdb_ligand_dataset.py @@ -0,0 +1,724 @@ +from __future__ import annotations + +import argparse +import csv +import json +import shutil +import sys +import time +import urllib.parse +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from docking_pipeline.dataset import ( + auto_detect_reference_ligand, + create_dataset_manifest, + download_pdb_structure, + extract_receptor_and_reference_ligand, + list_hetero_ligands, + list_known_good_complexes, + prepare_dataset_target_with_rdock, + resolve_known_good_defaults, + validate_dataset_dir, +) +from docking_pipeline.provenance import CommandRunner, RDockPipelineError, fail_if_bad_command, probe_version, require_executable, require_file + + +KNOWN_GOOD = ROOT / "configs" / "known_good_pdb_complexes.yaml" +DEFAULT_THRESHOLD_LADDER = [95, 90, 85, 80, 75, 70] +DEFAULT_BUNDLED_EXAMPLE = ROOT / "data" / "examples" / "example_smiles.smi" +DEFAULT_EXAMPLE_1000 = ROOT / "data" / "examples" / "example_smiles_1000.smi" + + +def _read_smiles(path: Path, n_ligands: int) -> list[tuple[str, str]]: + rows: list[tuple[str, str]] = [] + for idx, line in enumerate(path.read_text(encoding="utf-8").splitlines()): + text = line.strip() + if not text or text.startswith("#"): + continue + parts = text.replace(",", " ").split() + smiles = parts[0] + ligand_id = parts[1] if len(parts) > 1 else f"lig_{idx:05d}" + rows.append((smiles, ligand_id)) + if len(rows) >= n_ligands: + break + return rows + + +def _mkdir_or_fail(path: Path) -> None: + try: + path.mkdir(parents=True, exist_ok=True) + except PermissionError as exc: + suggestion = Path.home() / "datasets" / path.name + raise RDockPipelineError( + f"Cannot create output directory {path}: permission denied. " + f"Use a writable path such as {suggestion} or a relative path under your home/project directory." + ) from exc + + +def _http_json(url: str, timeout: int, retries: int = 3, pause_seconds: float = 1.0) -> dict[str, object]: + last_error: Exception | None = None + for attempt in range(1, retries + 1): + try: + with urllib.request.urlopen(url, timeout=timeout) as response: + payload = response.read().decode("utf-8") + return json.loads(payload) + except Exception as exc: # pragma: no cover - network-dependent + last_error = exc + if attempt < retries: + time.sleep(pause_seconds * attempt) + raise RDockPipelineError(f"HTTP JSON request failed after {retries} attempts for {url}: {last_error}") + + +def _write_smi(rows: list[tuple[str, str]], path: Path) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("\n".join(f"{smiles} {ligand_id}" for smiles, ligand_id in rows) + "\n", encoding="utf-8") + return path + + +def _obabel_convert(runner: CommandRunner, stage: str, input_path: Path, output_path: Path, extra_args: list[str], cwd: Path) -> Path: + obabel = require_executable("obabel") + rec = runner.run( + stage, + [obabel, str(input_path.resolve()), *extra_args, "-O", str(output_path.resolve())], + cwd, + cwd / "logs" / f"{stage}.stdout.log", + cwd / "logs" / f"{stage}.stderr.log", + ) + fail_if_bad_command(rec, f"OpenBabel {stage}") + return require_file(output_path, f"OpenBabel output {stage}") + + +def _reference_ligand_to_smiles(runner: CommandRunner, reference_sdf: Path, cwd: Path) -> str: + obabel = require_executable("obabel") + stdout_log = cwd / "logs" / "reference_ligand_to_smiles.stdout.log" + stderr_log = cwd / "logs" / "reference_ligand_to_smiles.stderr.log" + rec = runner.run( + "reference_ligand_to_smiles", + [obabel, str(reference_sdf.resolve()), "-osmi"], + cwd, + stdout_log, + stderr_log, + ) + fail_if_bad_command(rec, "OpenBabel reference ligand to SMILES") + text = stdout_log.read_text(encoding="utf-8", errors="ignore").strip() + if not text: + raise RDockPipelineError(f"OpenBabel did not produce SMILES for reference ligand {reference_sdf}") + first = text.splitlines()[0].strip() + parts = first.split() + if not parts: + raise RDockPipelineError(f"Could not parse OpenBabel SMILES output for {reference_sdf}: {first!r}") + return parts[0] + + +def _canonicalize_smiles_for_filter(smiles: str) -> str: + return smiles.strip() + + +def _looks_organic_smiles(smiles: str) -> bool: + text = _canonicalize_smiles_for_filter(smiles) + if not text or "." in text: + return False + return "C" in text or "c" in text + + +def _parse_threshold_ladder(text: str) -> list[int]: + try: + values = [int(part.strip()) for part in text.split(",") if part.strip()] + except Exception as exc: + raise RDockPipelineError(f"Invalid --pubchem-threshold-ladder value {text!r}: {exc}") from exc + if not values: + raise RDockPipelineError("Empty --pubchem-threshold-ladder") + return values + + +def _pubchem_similarity_cids(reference_smiles: str, threshold: int, max_records: int, timeout: int) -> list[int]: + encoded = urllib.parse.quote(reference_smiles, safe="") + url = ( + "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/" + f"smiles/{encoded}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}" + ) + payload = _http_json(url, timeout) + info = payload.get("IdentifierList", {}) if isinstance(payload, dict) else {} + cids = info.get("CID", []) if isinstance(info, dict) else [] + return [int(cid) for cid in cids] + + +def _pubchem_name_search_cids(query: str, max_records: int, timeout: int) -> list[int]: + encoded = urllib.parse.quote(query.strip(), safe="") + url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{encoded}/cids/JSON?MaxRecords={int(max_records)}" + payload = _http_json(url, timeout) + info = payload.get("IdentifierList", {}) if isinstance(payload, dict) else {} + cids = info.get("CID", []) if isinstance(info, dict) else [] + return [int(cid) for cid in cids] + + +def _pubchem_fetch_properties(cids: list[int], timeout: int) -> list[dict[str, object]]: + if not cids: + return [] + chunk_size = 200 + rows: list[dict[str, object]] = [] + for start in range(0, len(cids), chunk_size): + chunk = cids[start : start + chunk_size] + cid_text = ",".join(str(cid) for cid in chunk) + url = ( + "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/" + f"{cid_text}/property/CanonicalSMILES,IUPACName,MolecularFormula,MolecularWeight," + "XLogP,TPSA,HBondDonorCount,HBondAcceptorCount,RotatableBondCount,HeavyAtomCount/JSON" + ) + payload = _http_json(url, timeout) + table = payload.get("PropertyTable", {}) if isinstance(payload, dict) else {} + props = table.get("Properties", []) if isinstance(table, dict) else [] + for item in props: + if isinstance(item, dict): + rows.append(item) + return rows + + +def _pubchem_similarity_rows( + reference_smiles: str, + n_ligands: int, + threshold_ladder: list[int], + timeout: int, +) -> tuple[list[tuple[str, str]], list[dict[str, object]], list[dict[str, object]]]: + collected_smiles: dict[str, tuple[str, str]] = {} + metadata: list[dict[str, object]] = [] + diagnostics: list[dict[str, object]] = [] + for threshold in threshold_ladder: + needed = max(0, n_ligands - len(collected_smiles)) + if needed <= 0: + break + cids = _pubchem_similarity_cids(reference_smiles, threshold, max_records=max(needed * 4, needed), timeout=timeout) + props = _pubchem_fetch_properties(cids, timeout) + accepted = 0 + for item in props: + smiles = str(item.get("CanonicalSMILES", "")).strip() + cid = int(item.get("CID", 0) or 0) + if not smiles or cid <= 0 or not _looks_organic_smiles(smiles): + continue + ligand_id = f"pubchem_cid_{cid}" + if ligand_id in collected_smiles: + continue + collected_smiles[ligand_id] = (smiles, ligand_id) + metadata.append( + { + "ligand_id": ligand_id, + "smiles": smiles, + "source": "pubchem_similarity", + "pubchem_cid": cid, + "pubchem_threshold": threshold, + "iupac_name": item.get("IUPACName", ""), + "molecular_formula": item.get("MolecularFormula", ""), + "molecular_weight": item.get("MolecularWeight", ""), + "xlogp": item.get("XLogP", ""), + "tpsa": item.get("TPSA", ""), + "hbd": item.get("HBondDonorCount", ""), + "hba": item.get("HBondAcceptorCount", ""), + "rotatable_bonds": item.get("RotatableBondCount", ""), + "heavy_atom_count": item.get("HeavyAtomCount", ""), + } + ) + accepted += 1 + if len(collected_smiles) >= n_ligands: + break + diagnostics.append( + { + "threshold": threshold, + "returned_cids": len(cids), + "accepted_new_smiles": accepted, + "collected_total": len(collected_smiles), + } + ) + if len(collected_smiles) < n_ligands: + raise RDockPipelineError( + f"PubChem similarity search collected only {len(collected_smiles)} ligands for reference SMILES after thresholds " + f"{threshold_ladder}. Requested {n_ligands}. Lower the threshold ladder, request fewer ligands, or provide --smiles-file." + ) + rows = list(collected_smiles.values())[:n_ligands] + return rows, metadata[:n_ligands], diagnostics + + +def _pubchem_name_rows( + queries: list[str], + n_ligands: int, + timeout: int, +) -> tuple[list[tuple[str, str]], list[dict[str, object]], list[dict[str, object]]]: + collected_smiles: dict[str, tuple[str, str]] = {} + metadata: list[dict[str, object]] = [] + diagnostics: list[dict[str, object]] = [] + for query in [item.strip() for item in queries if item.strip()]: + needed = max(0, n_ligands - len(collected_smiles)) + if needed <= 0: + break + cids = _pubchem_name_search_cids(query, max_records=max(needed * 4, needed), timeout=timeout) + props = _pubchem_fetch_properties(cids, timeout) + accepted = 0 + for item in props: + smiles = str(item.get("CanonicalSMILES", "")).strip() + cid = int(item.get("CID", 0) or 0) + if not smiles or cid <= 0 or not _looks_organic_smiles(smiles): + continue + ligand_id = f"pubchem_cid_{cid}" + if ligand_id in collected_smiles: + continue + collected_smiles[ligand_id] = (smiles, ligand_id) + metadata.append( + { + "ligand_id": ligand_id, + "smiles": smiles, + "source": "pubchem_compound_search", + "pubchem_cid": cid, + "pubchem_query": query, + "iupac_name": item.get("IUPACName", ""), + "molecular_formula": item.get("MolecularFormula", ""), + "molecular_weight": item.get("MolecularWeight", ""), + "xlogp": item.get("XLogP", ""), + "tpsa": item.get("TPSA", ""), + "hbd": item.get("HBondDonorCount", ""), + "hba": item.get("HBondAcceptorCount", ""), + "rotatable_bonds": item.get("RotatableBondCount", ""), + "heavy_atom_count": item.get("HeavyAtomCount", ""), + } + ) + accepted += 1 + if len(collected_smiles) >= n_ligands: + break + diagnostics.append( + { + "query": query, + "returned_cids": len(cids), + "accepted_new_smiles": accepted, + "collected_total": len(collected_smiles), + } + ) + return list(collected_smiles.values())[:n_ligands], metadata[:n_ligands], diagnostics + + +def _known_good_entry(pdb_id: str) -> dict[str, object] | None: + for item in list_known_good_complexes(KNOWN_GOOD): + if str(item.get("pdb_id", "")).upper() == pdb_id.upper(): + return item + return None + + +def _pubchem_diagnostics_payload( + source_name: str, + reference_smiles: str, + threshold_ladder: list[int], + diagnostics: list[dict[str, object]], + errors: list[str], +) -> dict[str, object]: + return { + "source": source_name, + "reference_smiles": reference_smiles, + "thresholds_tried": threshold_ladder, + "endpoints_tried": [ + "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{smiles}/cids/JSON", + "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{query}/cids/JSON", + "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cids}/property/.../JSON", + ], + "diagnostics": diagnostics, + "errors": errors, + } + + +def _write_pubchem_diagnostics(out: Path, payload: dict[str, object]) -> Path: + target = out / "logs" / "pubchem_diagnostics.json" + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps(payload, indent=2), encoding="utf-8") + return target + + +def _resolve_smiles_source(args: argparse.Namespace) -> Path | None: + if args.smiles_file: + return Path(args.smiles_file) + if args.ligand_source == "bundled_example": + return DEFAULT_BUNDLED_EXAMPLE + return None + + +def _write_csv(path: Path, rows: list[dict[str, object]]) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + fields: list[str] = [] + for row in rows: + for key in row: + if key not in fields: + fields.append(key) + with path.open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + return path + + +def _list_known_good() -> int: + complexes = list_known_good_complexes(KNOWN_GOOD) + print(json.dumps(complexes, indent=2)) + return 0 + + +def _list_hetero_for_pdb(args: argparse.Namespace) -> int: + temp_root = Path(args.out) if args.out else ROOT / ".tmp_list_hetero" + _mkdir_or_fail(temp_root) + pdb_path = download_pdb_structure(str(args.pdb_id), temp_root / "raw", force=False) + payload = { + "pdb_id": str(args.pdb_id).upper(), + "hetero_ligands": list_hetero_ligands(pdb_path, min_reference_ligand_atoms=args.min_reference_ligand_atoms), + } + print(json.dumps(payload, indent=2)) + return 0 + + +def _validate_only(dataset_dir: Path) -> int: + print(json.dumps(validate_dataset_dir(dataset_dir, check_rdock_tools=False), indent=2)) + return 0 + + +def _plan(args: argparse.Namespace, resolved: dict[str, str], smiles_file: Path | None) -> dict[str, object]: + if smiles_file is None: + ligand_count = None + smiles_repr = "" + elif not smiles_file.exists(): + ligand_count = 0 + smiles_repr = str(smiles_file) + else: + ligand_count = len(_read_smiles(smiles_file, args.n_ligands)) + smiles_repr = str(smiles_file) + missing_tools = [tool for tool in ("obabel", "rbcavity", "rbdock") if shutil.which(tool) is None] + return { + "pdb_id": resolved["pdb_id"], + "receptor_chain": resolved["receptor_chain"], + "reference_ligand_resname": resolved["reference_ligand_resname"], + "reference_ligand_chain": resolved["reference_ligand_chain"], + "n_ligands_requested": args.n_ligands, + "ligand_source": args.ligand_source, + "auto_reference_ligand": bool(args.auto_reference_ligand), + "min_reference_ligand_atoms": int(args.min_reference_ligand_atoms), + "smiles_file": smiles_repr, + "detected_smiles_rows": ligand_count, + "out": str(args.out), + "missing_dependencies": missing_tools, + "commands": [ + "download PDB structure if absent", + "extract receptor chain and reference ligand from PDB", + "convert reference ligand and receptor with OpenBabel", + "resolve ligand source via smiles file or PubChem when --smiles-file is not provided", + "prepare target with rbcavity", + "convert SMILES to 3D SDF", + "write dataset_manifest.json and qc/preparation_report.md", + ], + } + + +def _reference_selection_error( + exc: RDockPipelineError, + pdb_id: str, + receptor_chain: str, + out: Path, +) -> RDockPipelineError: + known = _known_good_entry(pdb_id) + lines = [str(exc)] + if known: + lines.append( + "Known-good suggestion: " + f"--receptor-chain {known.get('receptor_chain')} " + f"--reference-ligand-resname {known.get('reference_ligand_resname')} " + f"--reference-ligand-chain {known.get('reference_ligand_chain')}" + ) + lines.append( + "Recommended correction: " + f"python scripts/prepare_pdb_ligand_dataset.py --pdb-id {pdb_id} --receptor-chain {receptor_chain} " + f"--auto-reference-ligand --n-ligands 1000 --ligand-source smiles_file " + f"--smiles-file data/examples/example_smiles_1000.smi --out {out} --force" + ) + lines.append( + "You can inspect candidate hetero ligands with: " + f"python scripts/prepare_pdb_ligand_dataset.py --list-hetero --pdb-id {pdb_id}" + ) + return RDockPipelineError("\n".join(lines)) + + +def _select_reference_ligand(args: argparse.Namespace, resolved: dict[str, str], pdb_path: Path) -> tuple[dict[str, str], list[dict[str, object]], dict[str, object] | None]: + if args.auto_reference_ligand or not resolved["reference_ligand_resname"]: + selected, candidates = auto_detect_reference_ligand( + pdb_path, + resolved["receptor_chain"], + min_reference_ligand_atoms=args.min_reference_ligand_atoms, + ) + resolved = dict(resolved) + resolved["reference_ligand_resname"] = str(selected["resname"]) + resolved["reference_ligand_chain"] = str(selected["chain"]) + return resolved, candidates, selected + return resolved, [], None + + +def _resolve_ligand_rows( + args: argparse.Namespace, + resolved: dict[str, str], + runner: CommandRunner, + reference_sdf: Path, + out: Path, +) -> tuple[list[tuple[str, str]], list[dict[str, object]], str, dict[str, object] | None, str]: + smiles_file = _resolve_smiles_source(args) + source = args.ligand_source + if args.smiles_file: + source = "smiles_file" + if source == "smiles_file" and smiles_file is None: + raise RDockPipelineError("`--ligand-source smiles_file` requires --smiles-file /path/to/library.smi.") + if source in {"pubchem_random_compounds", "zinc_file"}: + raise RDockPipelineError( + f"Ligand source `{source}` is not enabled in this portable bundle. " + "Use --ligand-source smiles_file --smiles-file /path/to/real_library.smi." + ) + if source == "bundled_example": + if args.n_ligands > 50: + raise RDockPipelineError( + f"`bundled_example` contains only 50 ligands. Requested {args.n_ligands}. " + f"Use --ligand-source smiles_file --smiles-file data/examples/example_smiles_1000.smi or a larger real library." + ) + if args.n_ligands > 5000 and source != "smiles_file": + raise RDockPipelineError( + f"Requested {args.n_ligands} ligands with source `{source}`. For libraries larger than 5000 ligands, " + "provide a real large library via --ligand-source smiles_file --smiles-file /path/to/library.smi." + ) + if smiles_file is not None: + rows = _read_smiles(smiles_file, args.n_ligands) + if len(rows) < args.n_ligands: + raise RDockPipelineError( + f"Requested {args.n_ligands} ligands but {smiles_file} contains only {len(rows)} usable rows. " + f"Provide a larger --smiles-file. Example: --smiles-file /data/libraries/real_50k_library.smi" + ) + metadata_rows = [{"ligand_id": ligand_id, "smiles": smiles, "source": "smiles_file"} for smiles, ligand_id in rows] + return rows, metadata_rows, "", None, source + + reference_smiles = _reference_ligand_to_smiles(runner, reference_sdf, out) + threshold_ladder = _parse_threshold_ladder(args.pubchem_threshold_ladder) + diagnostics_errors: list[str] = [] + combined_diagnostics: list[dict[str, object]] = [] + + if source in {"auto", "pubchem_similarity"}: + try: + rows, metadata_rows, diagnostics = _pubchem_similarity_rows( + reference_smiles, + args.n_ligands, + threshold_ladder, + timeout=args.pubchem_timeout, + ) + combined_diagnostics.extend(diagnostics) + payload = _pubchem_diagnostics_payload("pubchem_similarity", reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors) + return rows, metadata_rows, reference_smiles, payload, "pubchem_similarity" + except RDockPipelineError as exc: + diagnostics_errors.append(str(exc)) + + if source in {"auto", "pubchem_compound_search"}: + queries = [ + resolved["reference_ligand_resname"], + f"{resolved['pdb_id']} {resolved['reference_ligand_resname']}", + str((_known_good_entry(resolved["pdb_id"]) or {}).get("target_name", "")), + ] + rows, metadata_rows, diagnostics = _pubchem_name_rows(queries, args.n_ligands, timeout=args.pubchem_timeout) + combined_diagnostics.extend(diagnostics) + if len(rows) >= args.n_ligands: + payload = _pubchem_diagnostics_payload("pubchem_compound_search", reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors) + return rows, metadata_rows, reference_smiles, payload, "pubchem_compound_search" + diagnostics_errors.append( + f"PubChem compound search collected only {len(rows)} ligands for queries {queries}. Requested {args.n_ligands}." + ) + + payload = _pubchem_diagnostics_payload(source, reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors) + _write_pubchem_diagnostics(out, payload) + raise RDockPipelineError( + f"Could not collect {args.n_ligands} ligands from source `{source}` for {resolved['pdb_id']}. " + f"Diagnostics were written to {out / 'logs' / 'pubchem_diagnostics.json'}. " + "Use --ligand-source smiles_file --smiles-file /path/to/real_library.smi for a stable large-library workflow." + ) + + +def run(args: argparse.Namespace) -> int: + if args.list_known_good: + return _list_known_good() + if args.list_hetero: + return _list_hetero_for_pdb(args) + if args.validate_only: + return _validate_only(Path(args.out)) + + resolved = resolve_known_good_defaults( + KNOWN_GOOD, + args.pdb_id, + args.receptor_chain, + args.reference_ligand_resname, + args.reference_ligand_chain, + ) + if not resolved["receptor_chain"] or (not resolved["reference_ligand_resname"] and not args.auto_reference_ligand): + raise RDockPipelineError( + "Missing receptor chain or reference ligand resname. Provide them explicitly, use --auto-reference-ligand, or use a known-good PDB entry." + ) + smiles_file = _resolve_smiles_source(args) + plan = _plan(args, resolved, smiles_file) + plan["ligand_source"] = args.ligand_source + plan["pubchem_threshold_ladder"] = _parse_threshold_ladder(args.pubchem_threshold_ladder) + plan["uses_pubchem_similarity"] = smiles_file is None + out = Path(args.out) + _mkdir_or_fail(out) + if args.dry_run: + (out / "dataset_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8") + print(json.dumps(plan, indent=2)) + return 0 + + if out.exists() and args.force: + shutil.rmtree(out) + _mkdir_or_fail(out) + for name in ("raw", "target", "ligands", "logs", "qc"): + _mkdir_or_fail(out / name) + runner = CommandRunner(out / "logs" / "commands.log") + pdb_path = download_pdb_structure(resolved["pdb_id"], out / "raw", force=args.force) + resolved, auto_candidates, auto_selected = _select_reference_ligand(args, resolved, pdb_path) + (out / "raw" / "download_metadata.json").write_text( + json.dumps({"pdb_id": resolved["pdb_id"], "source": str(pdb_path), "status": "downloaded_or_reused"}, indent=2), + encoding="utf-8", + ) + try: + receptor_pdb, ligand_pdb, hetero = extract_receptor_and_reference_ligand( + pdb_path, + resolved["receptor_chain"], + resolved["reference_ligand_resname"], + resolved["reference_ligand_chain"], + out / "target", + min_reference_ligand_atoms=args.min_reference_ligand_atoms, + ) + except RDockPipelineError as exc: + raise _reference_selection_error(exc, resolved["pdb_id"], resolved["receptor_chain"], out) from exc + reference_raw_sdf = out / "target" / "reference_ligand_raw.sdf" + reference_sdf = out / "target" / "reference_ligand.sdf" + _obabel_convert(runner, "reference_ligand_raw_to_sdf", ligand_pdb, reference_raw_sdf, [], out) + shutil.copy2(reference_raw_sdf, reference_sdf) + rows, metadata_rows, reference_smiles, pubchem_payload, ligand_source_used = _resolve_ligand_rows(args, resolved, runner, reference_sdf, out) + if pubchem_payload is not None: + _write_pubchem_diagnostics(out, pubchem_payload) + + target_prm_dir = out / "target" / "rdock_prm" + prep = prepare_dataset_target_with_rdock(receptor_pdb, reference_sdf, target_prm_dir, jobs="auto", cpu_fraction=0.85) + target_mol2 = require_file(target_prm_dir / "receptor.mol2", "prepared receptor mol2") + shutil.copy2(target_mol2, out / "target" / "target.mol2") + + smi_path = _write_smi(rows, out / "ligands" / "all_ligands.smi") + ligands_sdf = _obabel_convert(runner, "smiles_to_all_ligands_sdf", smi_path, out / "ligands" / "all_ligands.sdf", ["--gen3d", "-h"], out) + _write_csv(out / "ligands" / "ligand_metadata.csv", metadata_rows) + _write_csv(out / "ligands" / "invalid_ligands.csv", []) + + manifest = { + "pdb_id": resolved["pdb_id"], + "receptor_chain": resolved["receptor_chain"], + "reference_ligand_resname": resolved["reference_ligand_resname"], + "reference_ligand_chain": resolved["reference_ligand_chain"], + "n_ligands_requested": args.n_ligands, + "ligands_prepared": len(rows), + "paths": { + "target_mol2": str(out / "target" / "target.mol2"), + "reference_ligand_sdf": str(reference_sdf), + "all_ligands_sdf": str(ligands_sdf), + "rdock_prm_dir": str(target_prm_dir), + "target_config_yaml": str(target_prm_dir / "target_config.yaml"), + }, + "versions": { + "obabel": probe_version(require_executable("obabel")), + "rbdock": probe_version(require_executable("rbdock")), + "rbcavity": probe_version(require_executable("rbcavity")), + }, + "ligand_source": ligand_source_used, + "reference_ligand_smiles": reference_smiles, + "pubchem_threshold_ladder": _parse_threshold_ladder(args.pubchem_threshold_ladder) if pubchem_payload is not None else [], + "pubchem_diagnostics": pubchem_payload or {}, + "rbcavity_status": "success", + "warnings": [], + "available_hetero_ligands": hetero[:50], + "auto_reference_ligand": bool(args.auto_reference_ligand), + "auto_reference_candidates": auto_candidates[:50], + "auto_reference_selected": auto_selected or {}, + "prepared_target": prep, + "copied_target_bundle": {path.name: str(path) for path in target_prm_dir.iterdir() if path.is_file()}, + } + create_dataset_manifest(out, manifest) + qc_report = [ + f"# Dataset Preparation Report: {resolved['pdb_id']}", + "", + f"- receptor_chain: `{resolved['receptor_chain']}`", + f"- reference_ligand: `{resolved['reference_ligand_resname']}` chain `{resolved['reference_ligand_chain']}`", + f"- ligands_prepared: `{len(rows)}`", + f"- ligand_source: `{ligand_source_used}`", + f"- reference_ligand_smiles: `{reference_smiles}`", + f"- target_mol2: `{out / 'target' / 'target.mol2'}`", + f"- reference_ligand_sdf: `{reference_sdf}`", + f"- all_ligands_sdf: `{ligands_sdf}`", + f"- target_config_yaml: `{target_prm_dir / 'target_config.yaml'}`", + ] + if auto_selected: + qc_report.extend( + [ + "", + "## Auto reference ligand selection", + f"- selected_resname: `{auto_selected.get('resname', '')}`", + f"- selected_chain: `{auto_selected.get('chain', '')}`", + f"- selected_residue_id: `{auto_selected.get('residue_id', '')}`", + f"- heavy_atom_count: `{auto_selected.get('heavy_atom_count', '')}`", + f"- min_distance_to_receptor: `{auto_selected.get('min_distance_to_receptor', '')}`", + ] + ) + (out / "qc" / "preparation_report.md").write_text("\n".join(qc_report) + "\n", encoding="utf-8") + print(json.dumps(validate_dataset_dir(out, check_rdock_tools=False), indent=2)) + return 0 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="Prepare a portable PDB + ligand dataset for rDock production runs.") + parser.add_argument("--pdb-id") + parser.add_argument("--receptor-chain") + parser.add_argument("--reference-ligand-resname") + parser.add_argument("--reference-ligand-chain") + parser.add_argument("--auto-reference-ligand", action="store_true") + parser.add_argument("--min-reference-ligand-atoms", type=int, default=8) + parser.add_argument("--n-ligands", type=int, default=1000) + parser.add_argument( + "--ligand-source", + default="auto", + choices=[ + "auto", + "smiles_file", + "pubchem_similarity", + "pubchem_compound_search", + "pubchem_random_compounds", + "zinc_file", + "bundled_example", + ], + ) + parser.add_argument("--source", dest="ligand_source") + parser.add_argument("--smiles-file") + parser.add_argument("--pubchem-threshold-ladder", default="95,90,85,80,75,70") + parser.add_argument("--pubchem-timeout", type=int, default=60) + parser.add_argument("--out") + parser.add_argument("--ph", type=float, default=7.4) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--force", action="store_true") + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--list-known-good", action="store_true") + parser.add_argument("--list-hetero", action="store_true") + parser.add_argument("--validate-only", action="store_true") + return parser + + +def main() -> int: + parser = build_parser() + args = parser.parse_args() + if not args.list_known_good and not args.validate_only and not args.list_hetero and not args.pdb_id: + parser.error("--pdb-id is required unless --list-known-good, --list-hetero, or --validate-only is used") + if not args.list_known_good and not args.list_hetero and not args.out: + parser.error("--out is required unless --list-known-good or --list-hetero is used") + return run(args) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/setup_server.sh b/setup_server.sh new file mode 100644 index 0000000000000000000000000000000000000000..c1ce570203285d6b90c6c26be9f3d7f3f2b5acca --- /dev/null +++ b/setup_server.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# === 1. Usuń stare środowisko === +conda deactivate +conda env remove -n portable-rdock-pipeline -y + +# === 2. Utwórz nowe środowisko (ważna wersja rdock) === +conda create -n portable-rdock-pipeline \ + -c conda-forge -c bioconda --strict-channel-priority \ + python=3.11 \ + numpy pandas scipy scikit-learn matplotlib pyyaml tqdm joblib pytest requests \ + rdkit openbabel \ + 'rdock=24.04.204_legacy' \ + -y + +# === 3. Aktywuj środowisko === +conda activate portable-rdock-pipeline + +# === 4. Sprawdź instalację === +which rbdock +which rbcavity +find "$CONDA_PREFIX" -name dock.prm + +# === 5. Ustaw RBT_ROOT === +DOCK_PRM=$(find "$CONDA_PREFIX" -name dock.prm | head -n 1) +RBT_ROOT_DIR=$(dirname $(dirname $(dirname "$DOCK_PRM"))) + +# === 6. Dodaj automatyczne ustawienie przy aktywacji === +mkdir -p "$CONDA_PREFIX/etc/conda/activate.d" + +cat > "$CONDA_PREFIX/etc/conda/activate.d/rdock.sh" < None: + config = Path(__file__).resolve().parents[1] / "configs" / "known_good_pdb_complexes.yaml" + complexes = list_known_good_complexes(config) + assert any(item["pdb_id"] == "4HG7" for item in complexes)