dualmapref 0.2.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- args_parse.py +593 -0
- candidate_corrector.py +161 -0
- candidate_scorer.py +359 -0
- conformend/__init__.py +36 -0
- conformend/refiner.py +25 -0
- dataset/__init__.py +1 -0
- dataset/drugdataset.py +644 -0
- dataset/manifold.py +237 -0
- dataset/sharded_drugdataset.py +124 -0
- dataset/smiles2graph.py +217 -0
- dualmapref/__init__.py +24 -0
- dualmapref/refiner.py +16 -0
- dualmapref-0.2.8.dist-info/LICENSE +21 -0
- dualmapref-0.2.8.dist-info/METADATA +167 -0
- dualmapref-0.2.8.dist-info/RECORD +186 -0
- dualmapref-0.2.8.dist-info/WHEEL +5 -0
- dualmapref-0.2.8.dist-info/entry_points.txt +10 -0
- dualmapref-0.2.8.dist-info/top_level.txt +29 -0
- exputils.py +289 -0
- infer.py +23 -0
- infer_base_conformers.py +5589 -0
- infer_mean_dispersion_torsion.py +1117 -0
- infer_torsion.py +752 -0
- infer_torsional_denoiser.py +1021 -0
- manimol/__init__.py +30 -0
- manimol/__main__.py +6 -0
- manimol/cli.py +36 -0
- manimol/full_cli.py +41 -0
- manimol/legacy_imports.py +43 -0
- manimol/manifest.py +56 -0
- manimol/postprocess.py +148 -0
- manimol/priors.py +60 -0
- manimol/protocols.py +119 -0
- manimol/refiner.py +645 -0
- manimol/runtime.py +194 -0
- manimol/selection.py +85 -0
- manimol/torsion.py +22 -0
- manimol/train_cli.py +14 -0
- mixture_flow/src/__init__.py +1 -0
- mixture_flow/src/_path.py +7 -0
- mixture_flow/src/infer28_mixture_torsion_flow.py +1093 -0
- mixture_flow/src/mixture_torsion_flow.py +291 -0
- mixture_flow/src/summarize_mixture_debug.py +80 -0
- mixture_flow/src/train28_mixture_torsion_flow.py +583 -0
- mixture_torsion_flow.py +7 -0
- models/ manifold_learning.py +86 -0
- models/__init__.py +8 -0
- models/dist.py +273 -0
- models/dist2coords.py +23 -0
- models/egnn.py +107 -0
- models/experimental_backbones.py +364 -0
- models/gnnconv.py +512 -0
- models/kernel_inversion.py +141 -0
- models/kernels.py +427 -0
- models/losses.py +154 -0
- models/mean_dispersion_bridge.py +119 -0
- models/mean_dispersion_torsion_context.py +155 -0
- models/model.py +73 -0
- models/model0.py +2375 -0
- models/vis.py +128 -0
- pgraph_controls.py +107 -0
- scripts/__init__.py +2 -0
- scripts/analyze_basin_alignment.py +63 -0
- scripts/analyze_hif2a_conformer_aggregation.py +267 -0
- scripts/analyze_hif2a_contact_pharmacophore.py +1111 -0
- scripts/analyze_hif2a_fixed_budget.py +202 -0
- scripts/analyze_hif2a_pharmacophore.py +405 -0
- scripts/analyze_hif2a_pharmacophore_match_metric.py +386 -0
- scripts/analyze_p_control_candidate_flow.py +154 -0
- scripts/analyze_scaffold_basin.py +83 -0
- scripts/audit_dispersion_proposals.py +208 -0
- scripts/audit_etflow_protocol.py +258 -0
- scripts/audit_external_overlap.py +150 -0
- scripts/audit_oldbest_fulltrainval_split.py +82 -0
- scripts/audit_pdbbind_contact_pharmacophores.py +146 -0
- scripts/audit_qm9_geomol_test_split.py +94 -0
- scripts/audit_stage1_stage2_cross.py +131 -0
- scripts/build_geom_drugs_lowref_diagnostic.py +84 -0
- scripts/build_qm9_backfill_manifest.py +99 -0
- scripts/check_etflow_runtime.py +56 -0
- scripts/compare_prior_sources.py +122 -0
- scripts/compose_binding_mode_figure.py +87 -0
- scripts/compose_hif2a_contact_pharmacophore_suppfig.py +255 -0
- scripts/compose_hif2a_functional_geometry_pipeline.py +266 -0
- scripts/compose_manimol_internal_architecture.py +291 -0
- scripts/diagnose_flow_basin_intervention.py +54 -0
- scripts/diagnose_hif2a_pharmacophore_budget.py +185 -0
- scripts/diagnose_route2_p_ranking.py +123 -0
- scripts/discover_binding_mode_inputs.py +30 -0
- scripts/evaluate_functional_prior_stage1.py +230 -0
- scripts/evaluate_geomanimol.py +74 -0
- scripts/evaluate_geomanimol_flow.py +23 -0
- scripts/evaluate_geomanimol_multiscaffold.py +46 -0
- scripts/evaluate_geomanimol_residual.py +45 -0
- scripts/evaluate_geomanimol_torsion.py +40 -0
- scripts/evaluate_hif2a_bioactive_enrichment.py +91 -0
- scripts/evaluate_hif2a_pms_suite.py +440 -0
- scripts/evaluate_pdbbind_contact_pms.py +155 -0
- scripts/evaluate_platinum_external.py +114 -0
- scripts/evaluate_platinum_pool.py +82 -0
- scripts/evaluate_route2_calibrated_p.py +104 -0
- scripts/evaluate_route2_library_components.py +596 -0
- scripts/evaluate_route2_p_basin_budget.py +288 -0
- scripts/evaluate_stage1_checkpoint_only.py +30 -0
- scripts/export_dispersion_bond_audit.py +136 -0
- scripts/export_top20_shards.py +207 -0
- scripts/external_validation_metrics.py +152 -0
- scripts/fit_topology_prior.py +117 -0
- scripts/frozen_dispersion_audit.py +281 -0
- scripts/geomanimol_debug.py +50 -0
- scripts/geomanimol_smoke.py +37 -0
- scripts/infer_etflow_matched.py +524 -0
- scripts/inspect_checkpoint.py +12 -0
- scripts/inspect_conformer_capacity.py +71 -0
- scripts/inspect_pool.py +12 -0
- scripts/make_figure3_selection_loss.py +474 -0
- scripts/make_figure3_selection_summary.py +275 -0
- scripts/make_geom_debug_subset.py +62 -0
- scripts/make_low_reference_test_subset.py +70 -0
- scripts/merge_stage1_into_stage2.py +82 -0
- scripts/place_hif2a_candidates_for_evaluation.py +66 -0
- scripts/plot_hif2a_low_budget_efficiency.py +100 -0
- scripts/plot_prior_validation.py +48 -0
- scripts/precompute_stage2_assignments.py +90 -0
- scripts/prepare_bace_activity.py +98 -0
- scripts/prepare_bace_etkdg_benchmark.py +90 -0
- scripts/prepare_figure5_4x4_cases.py +470 -0
- scripts/prepare_geom_drugs_geomol_top20.py +472 -0
- scripts/prepare_pdbbind_core_raw.py +90 -0
- scripts/prepare_platinum_raw.py +74 -0
- scripts/prepare_pubchem_etkdg.py +54 -0
- scripts/rebuild_hif2a_final_sdf_and_metrics.py +55 -0
- scripts/rebuild_hif2a_fixed_pool_sweep.py +175 -0
- scripts/rebuild_hif2a_strict.py +220 -0
- scripts/recompute_hif2a_bootstrap.py +63 -0
- scripts/reference_free_geometry.py +112 -0
- scripts/render_binding_modes.py +413 -0
- scripts/render_figure5_4x4.py +330 -0
- scripts/render_figure6_pharmacophore_pymol.py +162 -0
- scripts/render_hif2a_contact_pharmacophore_pymol.py +414 -0
- scripts/render_hif2a_figure11.py +397 -0
- scripts/run_bace_2d_baseline.py +73 -0
- scripts/run_drugs_validation_matrix.py +225 -0
- scripts/run_external_reference_free.py +53 -0
- scripts/run_manimol_finalk_sensitivity.py +106 -0
- scripts/run_manimol_oversampling_sensitivity.py +109 -0
- scripts/run_pdisp_matched_intervention.py +116 -0
- scripts/run_stage1_stage2_cross20.py +83 -0
- scripts/score_hif2a_candidates_with_pgraph.py +221 -0
- scripts/summarize_dispersion_intervention.py +88 -0
- scripts/test_mean_dispersion_bridge.py +50 -0
- scripts/train_dispersion_head_diagnostic.py +320 -0
- scripts/train_dispersion_head_streaming.py +519 -0
- scripts/train_geomanimol.py +100 -0
- scripts/train_geomanimol_flow.py +26 -0
- scripts/train_geomanimol_residual.py +70 -0
- scripts/train_geomanimol_torsion.py +50 -0
- scripts/train_quantile_representation_diagnostic.py +204 -0
- scripts/validate_mean_dispersion_prior.py +173 -0
- scripts/validate_packed_shard.py +41 -0
- scripts/validate_stage1_prior.py +221 -0
- scripts/validate_top20_shards.py +36 -0
- scripts/validation/__init__.py +1 -0
- scripts/validation/hif2a_downstream_baselines.py +105 -0
- scripts/validation/hif2a_pairwise_ranker.py +218 -0
- scripts/verify_binding_mode_figure.py +47 -0
- torsion_manifold.py +281 -0
- train.py +78 -0
- train_graph_encoder.py +206 -0
- train_local_torsion_corrector.py +511 -0
- train_mean_dispersion_torsion_prior.py +329 -0
- train_probability_basin.py +235 -0
- train_torsion_generator.py +1631 -0
- train_torsion_manifold_prior.py +258 -0
- train_torsional_denoiser.py +415 -0
- trainer.py +1038 -0
- utils/__init__.py +7 -0
- utils/checkpoint.py +40 -0
- utils/device.py +17 -0
- utils/helpers.py +98 -0
- utils/kabsch.py +29 -0
- utils/lookup_table.py +164 -0
- utils/metrics.py +50 -0
- utils/optuna.py +111 -0
- utils/save_mol.py +366 -0
- utils/util.py +36 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Paired fixed-budget analysis for HIF-2A conformer and docking results."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import csv
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from rdkit import Chem
|
|
13
|
+
from rdkit.Chem import Lipinski, rdMolAlign
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def read_csv(path):
|
|
17
|
+
with open(path, newline="") as handle:
|
|
18
|
+
return list(csv.DictReader(handle))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def first_mol(path):
|
|
22
|
+
mol = Chem.SDMolSupplier(str(path), removeHs=False)[0]
|
|
23
|
+
if mol is None:
|
|
24
|
+
raise ValueError(f"cannot read {path}")
|
|
25
|
+
return Chem.RemoveHs(mol)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def conformer_rmsds(path, reference):
|
|
29
|
+
values = []
|
|
30
|
+
for index, mol in enumerate(Chem.SDMolSupplier(str(path), removeHs=False)):
|
|
31
|
+
if mol is None:
|
|
32
|
+
continue
|
|
33
|
+
values.append((index, float(rdMolAlign.GetBestRMS(Chem.RemoveHs(mol), reference))))
|
|
34
|
+
return values
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def bootstrap_difference(pairs, rng, repeats):
|
|
38
|
+
array = np.asarray(pairs, dtype=float)
|
|
39
|
+
differences = []
|
|
40
|
+
for _ in range(repeats):
|
|
41
|
+
sample = array[rng.integers(0, len(array), len(array))]
|
|
42
|
+
differences.append(float(np.mean(sample[:, 0] - sample[:, 1])))
|
|
43
|
+
return float(np.mean(array[:, 0] - array[:, 1])), *np.quantile(differences, [0.025, 0.975]).tolist()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def main():
|
|
47
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
48
|
+
parser.add_argument("--manifest", required=True)
|
|
49
|
+
parser.add_argument("--docking_rows", required=True)
|
|
50
|
+
parser.add_argument("--budgets", default="1,5,10,20")
|
|
51
|
+
parser.add_argument("--thresholds", default="0.5,0.75,1.0,1.5,2.0")
|
|
52
|
+
parser.add_argument("--random_repeats", type=int, default=1000)
|
|
53
|
+
parser.add_argument("--bootstrap_repeats", type=int, default=10000)
|
|
54
|
+
parser.add_argument("--seed", type=int, default=20260908)
|
|
55
|
+
parser.add_argument("--out_dir", required=True)
|
|
56
|
+
args = parser.parse_args()
|
|
57
|
+
|
|
58
|
+
budgets = [int(value) for value in args.budgets.split(",")]
|
|
59
|
+
thresholds = [float(value) for value in args.thresholds.split(",")]
|
|
60
|
+
rng = np.random.default_rng(args.seed)
|
|
61
|
+
out_dir = Path(args.out_dir)
|
|
62
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
candidate_rows = []
|
|
64
|
+
ligand_rows = []
|
|
65
|
+
|
|
66
|
+
manifest = read_csv(args.manifest)
|
|
67
|
+
for item in manifest:
|
|
68
|
+
reference = first_mol(item["crystal_ligand_sdf"])
|
|
69
|
+
rotatable = int(Lipinski.NumRotatableBonds(reference))
|
|
70
|
+
heavy = int(reference.GetNumHeavyAtoms())
|
|
71
|
+
rings = int(reference.GetRingInfo().NumRings())
|
|
72
|
+
method_paths = {
|
|
73
|
+
"etkdg": item["etkdg_sdf"],
|
|
74
|
+
"manimol": item.get("manimol_stage2_sdf") or item.get("manimol_sdf"),
|
|
75
|
+
}
|
|
76
|
+
for method, path in method_paths.items():
|
|
77
|
+
scores = conformer_rmsds(path, reference)
|
|
78
|
+
for index, value in scores:
|
|
79
|
+
candidate_rows.append({
|
|
80
|
+
"complex_id": item["complex_id"], "method": method,
|
|
81
|
+
"candidate_index": index, "bioactive_rmsd": value,
|
|
82
|
+
"rotatable_bonds": rotatable, "heavy_atoms": heavy, "rings": rings,
|
|
83
|
+
})
|
|
84
|
+
ligand_rows.append({
|
|
85
|
+
"complex_id": item["complex_id"], "method": method,
|
|
86
|
+
"rotatable_bonds": rotatable, "heavy_atoms": heavy, "rings": rings,
|
|
87
|
+
"available": len(scores), "best_rmsd": min(value for _, value in scores),
|
|
88
|
+
**{f"hit_{threshold:g}": float(min(value for _, value in scores) < threshold)
|
|
89
|
+
for threshold in thresholds},
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
docking = read_csv(args.docking_rows)
|
|
93
|
+
docking_groups = {}
|
|
94
|
+
for row in docking:
|
|
95
|
+
if row.get("success", "1") not in {"1", "True", "true"}:
|
|
96
|
+
continue
|
|
97
|
+
docking_groups.setdefault((row["complex_id"], row["method"]), []).append(row)
|
|
98
|
+
|
|
99
|
+
docking_budget_rows = []
|
|
100
|
+
for (complex_id, method), rows in docking_groups.items():
|
|
101
|
+
ranked = sorted(rows, key=lambda row: float(row["vina_score"]))
|
|
102
|
+
for budget in budgets:
|
|
103
|
+
selected = ranked[: min(budget, len(ranked))]
|
|
104
|
+
rmsds = np.asarray([float(row["pose_rmsd"]) for row in selected])
|
|
105
|
+
docking_budget_rows.append({
|
|
106
|
+
"complex_id": complex_id, "method": method, "budget": budget,
|
|
107
|
+
"best_pose_rmsd": float(rmsds.min()),
|
|
108
|
+
"top_score_pose_rmsd": float(rmsds[0]),
|
|
109
|
+
"top_score": float(selected[0]["vina_score"]),
|
|
110
|
+
**{f"hit_{threshold:g}": float(np.any(rmsds < threshold)) for threshold in thresholds},
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
# Expected recovery from an unordered K-member conformer library.
|
|
114
|
+
random_budget_rows = []
|
|
115
|
+
by_ligand = {}
|
|
116
|
+
for row in candidate_rows:
|
|
117
|
+
by_ligand.setdefault((row["complex_id"], row["method"]), []).append(row["bioactive_rmsd"])
|
|
118
|
+
for (complex_id, method), values in by_ligand.items():
|
|
119
|
+
values = np.asarray(values, dtype=float)
|
|
120
|
+
for budget in budgets:
|
|
121
|
+
best = []
|
|
122
|
+
for _ in range(args.random_repeats):
|
|
123
|
+
chosen = rng.choice(len(values), size=min(budget, len(values)), replace=False)
|
|
124
|
+
best.append(float(values[chosen].min()))
|
|
125
|
+
best = np.asarray(best)
|
|
126
|
+
random_budget_rows.append({
|
|
127
|
+
"complex_id": complex_id, "method": method, "budget": budget,
|
|
128
|
+
"expected_best_rmsd": float(best.mean()),
|
|
129
|
+
**{f"expected_hit_{threshold:g}": float(np.mean(best < threshold)) for threshold in thresholds},
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
def summarize(rows, keys, group_keys):
|
|
133
|
+
output = []
|
|
134
|
+
groups = {}
|
|
135
|
+
for row in rows:
|
|
136
|
+
groups.setdefault(tuple(row[key] for key in group_keys), []).append(row)
|
|
137
|
+
for group, subset in groups.items():
|
|
138
|
+
result = dict(zip(group_keys, group))
|
|
139
|
+
result["n"] = len(subset)
|
|
140
|
+
for key in keys:
|
|
141
|
+
values = np.asarray([float(row[key]) for row in subset])
|
|
142
|
+
result[key + "_mean"] = float(values.mean())
|
|
143
|
+
result[key + "_median"] = float(np.median(values))
|
|
144
|
+
output.append(result)
|
|
145
|
+
return output
|
|
146
|
+
|
|
147
|
+
hit_keys = [f"hit_{threshold:g}" for threshold in thresholds]
|
|
148
|
+
library_summary = summarize(ligand_rows, ["best_rmsd", *hit_keys], ["method"])
|
|
149
|
+
docking_summary = summarize(
|
|
150
|
+
docking_budget_rows, ["best_pose_rmsd", "top_score_pose_rmsd", "top_score", *hit_keys],
|
|
151
|
+
["method", "budget"],
|
|
152
|
+
)
|
|
153
|
+
random_keys = ["expected_best_rmsd", *[f"expected_hit_{threshold:g}" for threshold in thresholds]]
|
|
154
|
+
random_summary = summarize(random_budget_rows, random_keys, ["method", "budget"])
|
|
155
|
+
|
|
156
|
+
# Use median rotatable-bond count to define an auditable flexible subset.
|
|
157
|
+
rotatable_values = sorted({int(row["rotatable_bonds"]) for row in ligand_rows})
|
|
158
|
+
cutoff = float(np.median(rotatable_values))
|
|
159
|
+
stratified = []
|
|
160
|
+
for row in ligand_rows:
|
|
161
|
+
copy = dict(row)
|
|
162
|
+
copy["flexibility"] = "high" if int(row["rotatable_bonds"]) >= cutoff else "low"
|
|
163
|
+
stratified.append(copy)
|
|
164
|
+
stratified_summary = summarize(stratified, ["best_rmsd", *hit_keys], ["flexibility", "method"])
|
|
165
|
+
|
|
166
|
+
paired = []
|
|
167
|
+
for metric in ["best_rmsd", *hit_keys]:
|
|
168
|
+
values = {}
|
|
169
|
+
for row in ligand_rows:
|
|
170
|
+
values.setdefault(row["complex_id"], {})[row["method"]] = float(row[metric])
|
|
171
|
+
pairs = [(item["manimol"], item["etkdg"]) for item in values.values()
|
|
172
|
+
if "manimol" in item and "etkdg" in item]
|
|
173
|
+
mean, low, high = bootstrap_difference(pairs, rng, args.bootstrap_repeats)
|
|
174
|
+
paired.append({"metric": metric, "difference_manimol_minus_etkdg": mean,
|
|
175
|
+
"ci95_low": low, "ci95_high": high, "n": len(pairs)})
|
|
176
|
+
|
|
177
|
+
def write(name, rows):
|
|
178
|
+
path = out_dir / name
|
|
179
|
+
with path.open("w", newline="") as handle:
|
|
180
|
+
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
|
|
181
|
+
writer.writeheader(); writer.writerows(rows)
|
|
182
|
+
|
|
183
|
+
write("candidate_rmsd.csv", candidate_rows)
|
|
184
|
+
write("library_per_ligand.csv", ligand_rows)
|
|
185
|
+
write("library_summary.csv", library_summary)
|
|
186
|
+
write("library_flexibility_summary.csv", stratified_summary)
|
|
187
|
+
write("paired_bootstrap.csv", paired)
|
|
188
|
+
write("random_budget_per_ligand.csv", random_budget_rows)
|
|
189
|
+
write("random_budget_summary.csv", random_summary)
|
|
190
|
+
write("vina_ranked_budget_per_ligand.csv", docking_budget_rows)
|
|
191
|
+
write("vina_ranked_budget_summary.csv", docking_summary)
|
|
192
|
+
(out_dir / "config.json").write_text(json.dumps({**vars(args), "flexibility_cutoff": cutoff}, indent=2) + "\n")
|
|
193
|
+
print("Library summary")
|
|
194
|
+
for row in library_summary: print(row)
|
|
195
|
+
print("Paired bootstrap (MANIMOL - ETKDG)")
|
|
196
|
+
for row in paired: print(row)
|
|
197
|
+
print("Flexibility cutoff", cutoff)
|
|
198
|
+
print(f"Saved results under {out_dir}")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
if __name__ == "__main__":
|
|
202
|
+
main()
|
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Functional-geometry pharmacophore analysis for the HIF2A conformer diagnostic.
|
|
3
|
+
|
|
4
|
+
This is not introduced as a new benchmark metric. It is a downstream
|
|
5
|
+
pharmacophore-preservation diagnostic: given receptor-frame placed ligand SDFs,
|
|
6
|
+
it compares generated conformers against crystallographic ligands using
|
|
7
|
+
feature-point geometry rather than atom-level RMSD alone.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import re
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Iterable
|
|
18
|
+
|
|
19
|
+
import matplotlib.pyplot as plt
|
|
20
|
+
import numpy as np
|
|
21
|
+
import pandas as pd
|
|
22
|
+
from rdkit import Chem, RDConfig
|
|
23
|
+
from rdkit.Chem import AllChem, ChemicalFeatures
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
FEATURE_FAMILIES = {
|
|
27
|
+
"Donor": "donor",
|
|
28
|
+
"Acceptor": "acceptor",
|
|
29
|
+
"Hydrophobe": "hydrophobe",
|
|
30
|
+
"LumpedHydrophobe": "hydrophobe",
|
|
31
|
+
"Aromatic": "aromatic",
|
|
32
|
+
"PosIonizable": "positive",
|
|
33
|
+
"NegIonizable": "negative",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def get_factory():
|
|
38
|
+
fdef = Path(RDConfig.RDDataDir) / "BaseFeatures.fdef"
|
|
39
|
+
return ChemicalFeatures.BuildFeatureFactory(str(fdef))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def read_first_mol(path: Path):
|
|
43
|
+
suppl = Chem.SDMolSupplier(str(path), removeHs=False, sanitize=False)
|
|
44
|
+
for mol in suppl:
|
|
45
|
+
if mol is None:
|
|
46
|
+
continue
|
|
47
|
+
try:
|
|
48
|
+
Chem.SanitizeMol(mol)
|
|
49
|
+
except Exception:
|
|
50
|
+
pass
|
|
51
|
+
if mol.GetNumConformers():
|
|
52
|
+
return mol
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def read_all_mols(path: Path):
|
|
57
|
+
suppl = Chem.SDMolSupplier(str(path), removeHs=False, sanitize=False)
|
|
58
|
+
out = []
|
|
59
|
+
for mol in suppl:
|
|
60
|
+
if mol is None or not mol.GetNumConformers():
|
|
61
|
+
continue
|
|
62
|
+
try:
|
|
63
|
+
Chem.SanitizeMol(mol)
|
|
64
|
+
except Exception:
|
|
65
|
+
pass
|
|
66
|
+
out.append(mol)
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def feature_points(mol, factory) -> list[dict]:
|
|
71
|
+
conf = mol.GetConformer()
|
|
72
|
+
points = []
|
|
73
|
+
for feat in factory.GetFeaturesForMol(mol):
|
|
74
|
+
family = FEATURE_FAMILIES.get(feat.GetFamily())
|
|
75
|
+
if family is None:
|
|
76
|
+
continue
|
|
77
|
+
atom_ids = tuple(int(i) for i in feat.GetAtomIds())
|
|
78
|
+
if not atom_ids:
|
|
79
|
+
continue
|
|
80
|
+
coords = []
|
|
81
|
+
for atom_id in atom_ids:
|
|
82
|
+
p = conf.GetAtomPosition(atom_id)
|
|
83
|
+
coords.append([p.x, p.y, p.z])
|
|
84
|
+
points.append(
|
|
85
|
+
{
|
|
86
|
+
"family": family,
|
|
87
|
+
"atom_ids": atom_ids,
|
|
88
|
+
"coord": np.asarray(coords, dtype=float).mean(axis=0),
|
|
89
|
+
}
|
|
90
|
+
)
|
|
91
|
+
return points
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def read_pdb_atom_coords(path: Path) -> np.ndarray:
|
|
95
|
+
coords = []
|
|
96
|
+
if not path.exists():
|
|
97
|
+
return np.zeros((0, 3), dtype=float)
|
|
98
|
+
for line in path.read_text(errors="ignore").splitlines():
|
|
99
|
+
if not (line.startswith("ATOM") or line.startswith("HETATM")):
|
|
100
|
+
continue
|
|
101
|
+
element = line[76:78].strip() if len(line) >= 78 else ""
|
|
102
|
+
atom_name = line[12:16].strip()
|
|
103
|
+
if element.upper() == "H" or atom_name.startswith("H"):
|
|
104
|
+
continue
|
|
105
|
+
try:
|
|
106
|
+
coords.append([float(line[30:38]), float(line[38:46]), float(line[46:54])])
|
|
107
|
+
except ValueError:
|
|
108
|
+
continue
|
|
109
|
+
return np.asarray(coords, dtype=float)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def filter_pocket_facing_features(feats: list[dict], receptor_coords: np.ndarray, cutoff: float) -> list[dict]:
|
|
113
|
+
if receptor_coords.size == 0:
|
|
114
|
+
return feats
|
|
115
|
+
kept = []
|
|
116
|
+
for feat in feats:
|
|
117
|
+
d = np.linalg.norm(receptor_coords - feat["coord"][None, :], axis=1)
|
|
118
|
+
if float(np.min(d)) <= cutoff:
|
|
119
|
+
kept.append(feat)
|
|
120
|
+
return kept
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def greedy_family_match(ref_feats: list[dict], gen_feats: list[dict]) -> list[tuple[int, int, float]]:
|
|
124
|
+
matches = []
|
|
125
|
+
used_gen = set()
|
|
126
|
+
for i, ref in enumerate(ref_feats):
|
|
127
|
+
best = None
|
|
128
|
+
for j, gen in enumerate(gen_feats):
|
|
129
|
+
if j in used_gen or gen["family"] != ref["family"]:
|
|
130
|
+
continue
|
|
131
|
+
dist = float(np.linalg.norm(ref["coord"] - gen["coord"]))
|
|
132
|
+
if best is None or dist < best[2]:
|
|
133
|
+
best = (i, j, dist)
|
|
134
|
+
if best is not None:
|
|
135
|
+
matches.append(best)
|
|
136
|
+
used_gen.add(best[1])
|
|
137
|
+
return matches
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def pharmacophore_scores(ref_feats: list[dict], gen_feats: list[dict], pair_delta: float, feature_cutoff: float) -> dict:
|
|
141
|
+
matches = greedy_family_match(ref_feats, gen_feats)
|
|
142
|
+
if not ref_feats:
|
|
143
|
+
return {
|
|
144
|
+
"n_ref_features": 0,
|
|
145
|
+
"n_gen_features": len(gen_feats),
|
|
146
|
+
"n_matched_features": 0,
|
|
147
|
+
"feature_recall": np.nan,
|
|
148
|
+
"feature_rmsd": np.nan,
|
|
149
|
+
"pair_topology_mae": np.nan,
|
|
150
|
+
"pair_coverage": np.nan,
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
n_ref = len(ref_feats)
|
|
154
|
+
n_match = len(matches)
|
|
155
|
+
feature_dists = np.asarray([m[2] for m in matches], dtype=float)
|
|
156
|
+
feature_recall = float((feature_dists <= feature_cutoff).sum() / n_ref) if n_match else 0.0
|
|
157
|
+
feature_rmsd = float(math.sqrt(np.mean(feature_dists**2))) if n_match else np.nan
|
|
158
|
+
|
|
159
|
+
ref_pair_dists = []
|
|
160
|
+
gen_pair_dists = []
|
|
161
|
+
for a in range(len(matches)):
|
|
162
|
+
for b in range(a + 1, len(matches)):
|
|
163
|
+
i1, j1, _ = matches[a]
|
|
164
|
+
i2, j2, _ = matches[b]
|
|
165
|
+
ref_pair_dists.append(float(np.linalg.norm(ref_feats[i1]["coord"] - ref_feats[i2]["coord"])))
|
|
166
|
+
gen_pair_dists.append(float(np.linalg.norm(gen_feats[j1]["coord"] - gen_feats[j2]["coord"])))
|
|
167
|
+
if ref_pair_dists:
|
|
168
|
+
ref_pair_dists = np.asarray(ref_pair_dists)
|
|
169
|
+
gen_pair_dists = np.asarray(gen_pair_dists)
|
|
170
|
+
errors = np.abs(ref_pair_dists - gen_pair_dists)
|
|
171
|
+
pair_mae = float(np.mean(errors))
|
|
172
|
+
pair_cov = float(np.mean(errors <= pair_delta))
|
|
173
|
+
else:
|
|
174
|
+
pair_mae = np.nan
|
|
175
|
+
pair_cov = np.nan
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
"n_ref_features": n_ref,
|
|
179
|
+
"n_gen_features": len(gen_feats),
|
|
180
|
+
"n_matched_features": n_match,
|
|
181
|
+
"feature_recall": feature_recall,
|
|
182
|
+
"feature_rmsd": feature_rmsd,
|
|
183
|
+
"pair_topology_mae": pair_mae,
|
|
184
|
+
"pair_coverage": pair_cov,
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def heavy_atom_best_rmsd(ref_mol, gen_mol) -> float:
|
|
189
|
+
try:
|
|
190
|
+
return float(AllChem.GetBestRMS(Chem.RemoveHs(ref_mol), Chem.RemoveHs(gen_mol)))
|
|
191
|
+
except Exception:
|
|
192
|
+
return np.nan
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def candidate_index(path: Path) -> int:
|
|
196
|
+
m = re.search(r"conf_(\d+)", path.name)
|
|
197
|
+
return int(m.group(1)) if m else -1
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def iter_candidate_files(root: Path, ligand_id: str, method: str, pose_kind: str) -> Iterable[Path]:
|
|
201
|
+
direct = root / ligand_id / method
|
|
202
|
+
if pose_kind == "local_only":
|
|
203
|
+
if direct.exists():
|
|
204
|
+
yield from sorted(direct.glob("conf_*_local_only.sdf"), key=candidate_index)
|
|
205
|
+
return
|
|
206
|
+
placed = root / ligand_id / method / "placed_sdf"
|
|
207
|
+
if placed.exists():
|
|
208
|
+
yield from sorted(placed.glob("conf_*_placed.sdf"), key=candidate_index)
|
|
209
|
+
return
|
|
210
|
+
if direct.exists():
|
|
211
|
+
yield from sorted(direct.glob("conf_*_local_only.sdf"), key=candidate_index)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def summarize_best(df: pd.DataFrame) -> pd.DataFrame:
|
|
215
|
+
rows = []
|
|
216
|
+
for (ligand_id, method), group in df.groupby(["ligand_id", "method"], sort=True):
|
|
217
|
+
group = group.copy()
|
|
218
|
+
valid = group.dropna(subset=["feature_rmsd"])
|
|
219
|
+
if valid.empty:
|
|
220
|
+
best = group.iloc[0]
|
|
221
|
+
else:
|
|
222
|
+
best = valid.sort_values(["feature_rmsd", "pair_topology_mae", "atom_rmsd"], na_position="last").iloc[0]
|
|
223
|
+
rows.append(best)
|
|
224
|
+
return pd.DataFrame(rows).reset_index(drop=True)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def plot_summary(best: pd.DataFrame, output_prefix: Path):
|
|
228
|
+
methods = ["etkdg", "manimol"]
|
|
229
|
+
labels = {"etkdg": "ETKDG", "manimol": "MANIMOL"}
|
|
230
|
+
colors = {"etkdg": "#D98B45", "manimol": "#2E5EAA"}
|
|
231
|
+
metrics = [
|
|
232
|
+
("feature_rmsd", "Pharmacophore RMSD (Å)", "lower"),
|
|
233
|
+
("pair_topology_mae", "Feature-distance MAE (Å)", "lower"),
|
|
234
|
+
("pair_coverage", "Topology coverage", "higher"),
|
|
235
|
+
]
|
|
236
|
+
|
|
237
|
+
fig, axes = plt.subplots(1, 3, figsize=(10.5, 3.0), dpi=300)
|
|
238
|
+
rng = np.random.default_rng(20260730)
|
|
239
|
+
for ax, (metric, ylabel, _) in zip(axes, metrics):
|
|
240
|
+
data = [best.loc[best["method"] == method, metric].dropna().to_numpy() for method in methods]
|
|
241
|
+
parts = ax.violinplot(data, positions=np.arange(len(methods)), widths=0.62, showmeans=False, showmedians=False, showextrema=False)
|
|
242
|
+
for body, method in zip(parts["bodies"], methods):
|
|
243
|
+
body.set_facecolor(colors[method])
|
|
244
|
+
body.set_edgecolor("none")
|
|
245
|
+
body.set_alpha(0.30)
|
|
246
|
+
bp = ax.boxplot(data, positions=np.arange(len(methods)), widths=0.28, patch_artist=True, showfliers=False)
|
|
247
|
+
for patch, method in zip(bp["boxes"], methods):
|
|
248
|
+
patch.set_facecolor("white")
|
|
249
|
+
patch.set_edgecolor(colors[method])
|
|
250
|
+
patch.set_linewidth(1.2)
|
|
251
|
+
for element in ["whiskers", "caps", "medians"]:
|
|
252
|
+
for line in bp[element]:
|
|
253
|
+
line.set_color("#4A4A4A")
|
|
254
|
+
line.set_linewidth(1.0)
|
|
255
|
+
for x, values, method in zip(np.arange(len(methods)), data, methods):
|
|
256
|
+
jitter = rng.normal(0, 0.035, size=len(values))
|
|
257
|
+
ax.scatter(np.full(len(values), x) + jitter, values, s=18, color=colors[method], alpha=0.55, linewidths=0)
|
|
258
|
+
ax.set_xticks(np.arange(len(methods)))
|
|
259
|
+
ax.set_xticklabels([labels[m] for m in methods])
|
|
260
|
+
ax.set_ylabel(ylabel)
|
|
261
|
+
ax.grid(axis="y", color="#E8E8E8", linewidth=0.7)
|
|
262
|
+
ax.spines["top"].set_visible(False)
|
|
263
|
+
ax.spines["right"].set_visible(False)
|
|
264
|
+
ax.spines["left"].set_color("#666666")
|
|
265
|
+
ax.spines["bottom"].set_color("#666666")
|
|
266
|
+
if metric == "pair_coverage":
|
|
267
|
+
ax.set_ylim(-0.03, 1.03)
|
|
268
|
+
fig.tight_layout(w_pad=1.5)
|
|
269
|
+
fig.savefig(output_prefix.with_suffix(".png"), bbox_inches="tight")
|
|
270
|
+
fig.savefig(output_prefix.with_suffix(".pdf"), bbox_inches="tight")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def write_tex(best: pd.DataFrame, output_tex: Path):
|
|
274
|
+
agg = best.groupby("method").agg(
|
|
275
|
+
n=("ligand_id", "count"),
|
|
276
|
+
feature_rmsd_mean=("feature_rmsd", "mean"),
|
|
277
|
+
feature_rmsd_median=("feature_rmsd", "median"),
|
|
278
|
+
pair_mae_mean=("pair_topology_mae", "mean"),
|
|
279
|
+
pair_cov_mean=("pair_coverage", "mean"),
|
|
280
|
+
feature_recall_mean=("feature_recall", "mean"),
|
|
281
|
+
atom_rmsd_mean=("atom_rmsd", "mean"),
|
|
282
|
+
)
|
|
283
|
+
order = ["etkdg", "manimol"]
|
|
284
|
+
lines = [
|
|
285
|
+
r"\begin{tabular}{lcccccc}",
|
|
286
|
+
r"\toprule",
|
|
287
|
+
r"Method & $n$ & Pharm. RMSD $\downarrow$ & Pair MAE $\downarrow$ & Pair coverage $\uparrow$ & Feature recall $\uparrow$ & Atom RMSD $\downarrow$ \\",
|
|
288
|
+
r"\midrule",
|
|
289
|
+
]
|
|
290
|
+
for method in order:
|
|
291
|
+
if method not in agg.index:
|
|
292
|
+
continue
|
|
293
|
+
row = agg.loc[method]
|
|
294
|
+
label = "ETKDG" if method == "etkdg" else r"\name"
|
|
295
|
+
lines.append(
|
|
296
|
+
f"{label} & {int(row['n'])} & {row['feature_rmsd_mean']:.3f} & "
|
|
297
|
+
f"{row['pair_mae_mean']:.3f} & {100*row['pair_cov_mean']:.1f} & "
|
|
298
|
+
f"{100*row['feature_recall_mean']:.1f} & {row['atom_rmsd_mean']:.3f} \\\\"
|
|
299
|
+
)
|
|
300
|
+
lines.extend([r"\bottomrule", r"\end{tabular}"])
|
|
301
|
+
output_tex.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def main():
|
|
305
|
+
parser = argparse.ArgumentParser(description="Analyze HIF2A ligand 3D pharmacophore preservation.")
|
|
306
|
+
parser.add_argument("--manifest", default="outputs/docking/hif2a_conformers/docking_manifest_manimol_xtb.csv")
|
|
307
|
+
parser.add_argument("--placed_root", default="outputs/docking/hif2a_preorganized_vina_score_only_xtb")
|
|
308
|
+
parser.add_argument("--pose_kind", choices=["placed", "local_only"], default="placed")
|
|
309
|
+
parser.add_argument("--output_dir", default="outputs/docking/hif2a_pharmacophore")
|
|
310
|
+
parser.add_argument("--pair_delta", type=float, default=1.5)
|
|
311
|
+
parser.add_argument("--feature_cutoff", type=float, default=2.0)
|
|
312
|
+
parser.add_argument("--pocket_facing_only", action="store_true")
|
|
313
|
+
parser.add_argument("--pocket_cutoff", type=float, default=4.5)
|
|
314
|
+
parser.add_argument("--max_ligands", type=int, default=0)
|
|
315
|
+
args, _ = parser.parse_known_args()
|
|
316
|
+
|
|
317
|
+
manifest = pd.read_csv(args.manifest)
|
|
318
|
+
if args.max_ligands and args.max_ligands > 0:
|
|
319
|
+
manifest = manifest.head(args.max_ligands)
|
|
320
|
+
placed_root = Path(args.placed_root)
|
|
321
|
+
out_dir = Path(args.output_dir)
|
|
322
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
323
|
+
factory = get_factory()
|
|
324
|
+
|
|
325
|
+
rows = []
|
|
326
|
+
feature_rows = []
|
|
327
|
+
for _, entry in manifest.iterrows():
|
|
328
|
+
ligand_id = entry["complex_id"]
|
|
329
|
+
ref_path = Path(entry.get("crystal_ligand_sdf", entry["ligand_sdf"]))
|
|
330
|
+
ref_mol = read_first_mol(ref_path)
|
|
331
|
+
if ref_mol is None:
|
|
332
|
+
continue
|
|
333
|
+
ref_feats = feature_points(ref_mol, factory)
|
|
334
|
+
if args.pocket_facing_only:
|
|
335
|
+
receptor_path = Path(entry.get("receptor_pdb", ""))
|
|
336
|
+
receptor_coords = read_pdb_atom_coords(receptor_path)
|
|
337
|
+
ref_feats = filter_pocket_facing_features(ref_feats, receptor_coords, args.pocket_cutoff)
|
|
338
|
+
family_counts = pd.Series([f["family"] for f in ref_feats]).value_counts().to_dict()
|
|
339
|
+
feature_rows.append({"ligand_id": ligand_id, "n_ref_features": len(ref_feats), **family_counts})
|
|
340
|
+
|
|
341
|
+
for method in ["etkdg", "manimol"]:
|
|
342
|
+
for cand_path in iter_candidate_files(placed_root, ligand_id, method, args.pose_kind):
|
|
343
|
+
mol = read_first_mol(cand_path)
|
|
344
|
+
if mol is None:
|
|
345
|
+
continue
|
|
346
|
+
gen_feats = feature_points(mol, factory)
|
|
347
|
+
scores = pharmacophore_scores(ref_feats, gen_feats, args.pair_delta, args.feature_cutoff)
|
|
348
|
+
rows.append(
|
|
349
|
+
{
|
|
350
|
+
"ligand_id": ligand_id,
|
|
351
|
+
"ligand_name": entry.get("ligand_name", ligand_id),
|
|
352
|
+
"method": method,
|
|
353
|
+
"candidate_file": str(cand_path),
|
|
354
|
+
"candidate_index": candidate_index(cand_path),
|
|
355
|
+
"atom_rmsd": heavy_atom_best_rmsd(ref_mol, mol),
|
|
356
|
+
**scores,
|
|
357
|
+
}
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
all_df = pd.DataFrame(rows)
|
|
361
|
+
if all_df.empty:
|
|
362
|
+
raise RuntimeError(f"No candidate SDFs found under {placed_root}")
|
|
363
|
+
best_df = summarize_best(all_df)
|
|
364
|
+
feature_df = pd.DataFrame(feature_rows).fillna(0)
|
|
365
|
+
|
|
366
|
+
all_csv = out_dir / "hif2a_pharmacophore_all_candidates.csv"
|
|
367
|
+
best_csv = out_dir / "hif2a_pharmacophore_best_per_ligand.csv"
|
|
368
|
+
feature_csv = out_dir / "hif2a_reference_feature_counts.csv"
|
|
369
|
+
all_df.to_csv(all_csv, index=False)
|
|
370
|
+
best_df.to_csv(best_csv, index=False)
|
|
371
|
+
feature_df.to_csv(feature_csv, index=False)
|
|
372
|
+
write_tex(best_df, out_dir / "hif2a_pharmacophore_summary.tex")
|
|
373
|
+
plot_summary(best_df, out_dir / "hif2a_pharmacophore_summary")
|
|
374
|
+
|
|
375
|
+
config = {
|
|
376
|
+
"manifest": args.manifest,
|
|
377
|
+
"placed_root": args.placed_root,
|
|
378
|
+
"pose_kind": args.pose_kind,
|
|
379
|
+
"pair_delta_A": args.pair_delta,
|
|
380
|
+
"feature_cutoff_A": args.feature_cutoff,
|
|
381
|
+
"pocket_facing_only": args.pocket_facing_only,
|
|
382
|
+
"pocket_cutoff_A": args.pocket_cutoff,
|
|
383
|
+
"families": sorted(set(FEATURE_FAMILIES.values())),
|
|
384
|
+
"selection_rule": "minimum pharmacophore feature RMSD per ligand and method",
|
|
385
|
+
}
|
|
386
|
+
(out_dir / "hif2a_pharmacophore_config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
|
|
387
|
+
|
|
388
|
+
print(f"Saved: {all_csv}")
|
|
389
|
+
print(f"Saved: {best_csv}")
|
|
390
|
+
print(f"Saved: {feature_csv}")
|
|
391
|
+
print(f"Saved: {out_dir / 'hif2a_pharmacophore_summary.tex'}")
|
|
392
|
+
print(f"Saved: {out_dir / 'hif2a_pharmacophore_summary.png'}")
|
|
393
|
+
print(f"Saved: {out_dir / 'hif2a_pharmacophore_summary.pdf'}")
|
|
394
|
+
for method, group in best_df.groupby("method"):
|
|
395
|
+
print(
|
|
396
|
+
f"{method}: n={len(group)} "
|
|
397
|
+
f"pharm_rmsd={group['feature_rmsd'].mean():.3f} "
|
|
398
|
+
f"pair_mae={group['pair_topology_mae'].mean():.3f} "
|
|
399
|
+
f"pair_cov={100*group['pair_coverage'].mean():.1f}% "
|
|
400
|
+
f"feature_recall={100*group['feature_recall'].mean():.1f}%"
|
|
401
|
+
)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
if __name__ == "__main__":
|
|
405
|
+
main()
|