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,185 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Audit PMS ensemble ordering versus candidate-pool coverage.
|
|
3
|
+
|
|
4
|
+
This is a read-only diagnostic over candidate_pharmacophore_match_scores.csv.
|
|
5
|
+
It does not change the PMS definition or regenerate conformers.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pandas as pd
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def parse_map(value: str) -> dict[str, float]:
|
|
19
|
+
try:
|
|
20
|
+
result = json.loads(value)
|
|
21
|
+
except (TypeError, json.JSONDecodeError):
|
|
22
|
+
return {}
|
|
23
|
+
return {str(key): float(val) for key, val in result.items()}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def score(rows: list[dict], selected: list[int]) -> tuple[float, float, float]:
|
|
27
|
+
feature_keys = sorted({key for row in rows for key in row["features"]})
|
|
28
|
+
pair_keys = sorted({key for row in rows for key in row["pairs"]})
|
|
29
|
+
feature = [max((rows[i]["features"].get(key, 0.0) for i in selected), default=0.0) for key in feature_keys]
|
|
30
|
+
pairs = [max((rows[i]["pairs"].get(key, 0.0) for i in selected), default=0.0) for key in pair_keys]
|
|
31
|
+
region = float(np.mean(feature)) if feature else np.nan
|
|
32
|
+
topology = float(np.mean(pairs)) if pairs else np.nan
|
|
33
|
+
return region, topology, float(0.5 * region + 0.5 * topology)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def greedy_oracle(rows: list[dict], k: int) -> list[int]:
|
|
37
|
+
selected: list[int] = []
|
|
38
|
+
remaining = set(range(len(rows)))
|
|
39
|
+
for _ in range(min(k, len(rows))):
|
|
40
|
+
best_idx = max(
|
|
41
|
+
remaining,
|
|
42
|
+
key=lambda idx: score(rows, selected + [idx])[2],
|
|
43
|
+
)
|
|
44
|
+
selected.append(best_idx)
|
|
45
|
+
remaining.remove(best_idx)
|
|
46
|
+
return selected
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def hybrid_select(rows: list[dict], k: int, quality_weight: float) -> list[int]:
|
|
50
|
+
"""Select candidates by quality plus normalized marginal coverage gain."""
|
|
51
|
+
selected: list[int] = []
|
|
52
|
+
remaining = set(range(len(rows)))
|
|
53
|
+
for _ in range(min(k, len(rows))):
|
|
54
|
+
current = score(rows, selected)[2] if selected else 0.0
|
|
55
|
+
gains = {idx: score(rows, selected + [idx])[2] - current for idx in remaining}
|
|
56
|
+
max_gain = max(gains.values(), default=1.0)
|
|
57
|
+
max_gain = max(max_gain, 1e-8)
|
|
58
|
+
best_idx = max(
|
|
59
|
+
remaining,
|
|
60
|
+
key=lambda idx: quality_weight * score(rows, [idx])[2]
|
|
61
|
+
+ (1.0 - quality_weight) * gains[idx] / max_gain,
|
|
62
|
+
)
|
|
63
|
+
selected.append(best_idx)
|
|
64
|
+
remaining.remove(best_idx)
|
|
65
|
+
return selected
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def main() -> None:
|
|
69
|
+
parser = argparse.ArgumentParser()
|
|
70
|
+
parser.add_argument("--input", default="outputs/docking/hif2a_pharmacophore_match_metric/candidate_pharmacophore_match_scores.csv")
|
|
71
|
+
parser.add_argument("--output_dir", default="outputs/docking/hif2a_pharmacophore_budget_diagnostic")
|
|
72
|
+
parser.add_argument("--budgets", default="1,5,10,20")
|
|
73
|
+
parser.add_argument("--random_repeats", type=int, default=100)
|
|
74
|
+
parser.add_argument("--seed", type=int, default=20260822)
|
|
75
|
+
parser.add_argument("--hybrid_lambdas", default="0.25,0.5,0.75")
|
|
76
|
+
args = parser.parse_args()
|
|
77
|
+
|
|
78
|
+
data = pd.read_csv(args.input)
|
|
79
|
+
budgets = [int(value) for value in args.budgets.split(",") if value.strip()]
|
|
80
|
+
hybrid_lambdas = [float(value) for value in args.hybrid_lambdas.split(",") if value.strip()]
|
|
81
|
+
output_dir = Path(args.output_dir)
|
|
82
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
rng = np.random.default_rng(args.seed)
|
|
84
|
+
summary_rows = []
|
|
85
|
+
detail_rows = []
|
|
86
|
+
selected_rows = []
|
|
87
|
+
rmsd_rows = []
|
|
88
|
+
|
|
89
|
+
for (method, ligand_id), group in data.groupby(["method", "ligand_id"], sort=True):
|
|
90
|
+
group = group.sort_values("candidate_index").reset_index(drop=True)
|
|
91
|
+
rows = [
|
|
92
|
+
{"features": parse_map(value), "pairs": parse_map(pair)}
|
|
93
|
+
for value, pair in zip(group["feature_scores_json"], group["pair_scores_json"])
|
|
94
|
+
]
|
|
95
|
+
for k in budgets:
|
|
96
|
+
original = score(rows, list(range(min(k, len(rows)))))
|
|
97
|
+
oracle_indices = greedy_oracle(rows, k)
|
|
98
|
+
oracle = score(rows, oracle_indices)
|
|
99
|
+
individual_indices = sorted(
|
|
100
|
+
range(len(rows)),
|
|
101
|
+
key=lambda idx: 0.5 * np.mean(list(rows[idx]["features"].values()))
|
|
102
|
+
+ 0.5 * np.mean(list(rows[idx]["pairs"].values())),
|
|
103
|
+
reverse=True,
|
|
104
|
+
)[: min(k, len(rows))]
|
|
105
|
+
individual = score(rows, individual_indices)
|
|
106
|
+
random_scores = [score(rows, rng.permutation(len(rows))[: min(k, len(rows))].tolist()) for _ in range(args.random_repeats)]
|
|
107
|
+
random_arr = np.asarray(random_scores, dtype=float)
|
|
108
|
+
values = {
|
|
109
|
+
"original": original[2],
|
|
110
|
+
"individual_pms_topk": individual[2],
|
|
111
|
+
"random_mean": float(random_arr[:, 2].mean()),
|
|
112
|
+
"random_std": float(random_arr[:, 2].std(ddof=1)),
|
|
113
|
+
"oracle": oracle[2],
|
|
114
|
+
}
|
|
115
|
+
for label, value in values.items():
|
|
116
|
+
summary_rows.append({"method": method, "K": k, "metric": label, "value": value})
|
|
117
|
+
selections = {
|
|
118
|
+
"original_order": list(range(min(k, len(rows)))),
|
|
119
|
+
"pms_topk": individual_indices,
|
|
120
|
+
"coverage_greedy": oracle_indices,
|
|
121
|
+
}
|
|
122
|
+
for quality_weight in hybrid_lambdas:
|
|
123
|
+
selections[f"hybrid_lambda_{quality_weight:g}"] = hybrid_select(rows, k, quality_weight)
|
|
124
|
+
for selector_name, indices in selections.items():
|
|
125
|
+
region, topology, pms = score(rows, indices)
|
|
126
|
+
summary_rows.extend([
|
|
127
|
+
{"method": method, "K": k, "metric": f"{selector_name}_region", "value": region},
|
|
128
|
+
{"method": method, "K": k, "metric": f"{selector_name}_topology", "value": topology},
|
|
129
|
+
{"method": method, "K": k, "metric": f"{selector_name}_pms", "value": pms},
|
|
130
|
+
])
|
|
131
|
+
for rank, idx in enumerate(indices):
|
|
132
|
+
selected_rows.append({
|
|
133
|
+
"method": method,
|
|
134
|
+
"ligand_id": ligand_id,
|
|
135
|
+
"K": k,
|
|
136
|
+
"selector": selector_name,
|
|
137
|
+
"rank": rank,
|
|
138
|
+
"candidate_index": int(group.iloc[idx]["candidate_index"]),
|
|
139
|
+
"candidate_file": group.iloc[idx]["candidate_file"],
|
|
140
|
+
})
|
|
141
|
+
rmsds = group.iloc[indices]["atom_rmsd"].astype(float).to_numpy()
|
|
142
|
+
hits = rmsds <= 0.75
|
|
143
|
+
rmsd_rows.append({
|
|
144
|
+
"method": method,
|
|
145
|
+
"ligand_id": ligand_id,
|
|
146
|
+
"K": k,
|
|
147
|
+
"selector": selector_name,
|
|
148
|
+
"cov_r": float(np.any(hits)),
|
|
149
|
+
"cov_p": float(np.mean(hits)),
|
|
150
|
+
"amr_r": float(np.min(rmsds)),
|
|
151
|
+
"amr_p": float(np.mean(rmsds)),
|
|
152
|
+
})
|
|
153
|
+
detail_rows.append({
|
|
154
|
+
"method": method,
|
|
155
|
+
"ligand_id": ligand_id,
|
|
156
|
+
"K": k,
|
|
157
|
+
"original_pms": original[2],
|
|
158
|
+
"original_region": original[0],
|
|
159
|
+
"original_topology": original[1],
|
|
160
|
+
"individual_pms_topk": individual[2],
|
|
161
|
+
"random_pms_mean": values["random_mean"],
|
|
162
|
+
"random_pms_std": values["random_std"],
|
|
163
|
+
"oracle_pms": oracle[2],
|
|
164
|
+
"oracle_indices": ";".join(map(str, oracle_indices)),
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
summary = pd.DataFrame(summary_rows)
|
|
168
|
+
detail = pd.DataFrame(detail_rows)
|
|
169
|
+
selected = pd.DataFrame(selected_rows)
|
|
170
|
+
rmsd = pd.DataFrame(rmsd_rows)
|
|
171
|
+
summary.to_csv(output_dir / "pharmacophore_budget_order_summary.csv", index=False)
|
|
172
|
+
detail.to_csv(output_dir / "pharmacophore_budget_order_per_ligand.csv", index=False)
|
|
173
|
+
selected.to_csv(output_dir / "pharmacophore_budget_selected_candidates.csv", index=False)
|
|
174
|
+
rmsd.to_csv(output_dir / "pharmacophore_budget_rmsd_per_ligand.csv", index=False)
|
|
175
|
+
rmsd_summary = rmsd.groupby(["method", "K", "selector"], as_index=False)[["cov_r", "cov_p", "amr_r", "amr_p"]].mean()
|
|
176
|
+
rmsd_summary.to_csv(output_dir / "pharmacophore_budget_rmsd_summary.csv", index=False)
|
|
177
|
+
config = vars(args)
|
|
178
|
+
(output_dir / "diagnostic_config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
|
|
179
|
+
print(summary.pivot_table(index=["method", "K"], columns="metric", values="value").reset_index().to_string(index=False))
|
|
180
|
+
print(rmsd_summary.to_string(index=False))
|
|
181
|
+
print(f"Saved outputs under {output_dir}")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
if __name__ == "__main__":
|
|
185
|
+
main()
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Diagnose whether probability controls produce distinct candidate rankings."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
from argparse import Namespace
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import torch
|
|
14
|
+
from tqdm import tqdm
|
|
15
|
+
|
|
16
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
17
|
+
|
|
18
|
+
import infer_base_conformers
|
|
19
|
+
from pgraph_controls import controlled_pglobal
|
|
20
|
+
from evaluate_route2_p_basin_budget import candidate_p_bce, farthest_point_basins
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def rank(values: torch.Tensor) -> torch.Tensor:
|
|
24
|
+
order = torch.argsort(values)
|
|
25
|
+
ranks = torch.empty_like(order, dtype=torch.float32)
|
|
26
|
+
ranks[order] = torch.arange(order.numel(), dtype=torch.float32)
|
|
27
|
+
return ranks
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def corr(a: torch.Tensor, b: torch.Tensor) -> float:
|
|
31
|
+
a = rank(a).double()
|
|
32
|
+
b = rank(b).double()
|
|
33
|
+
a = a - a.mean()
|
|
34
|
+
b = b - b.mean()
|
|
35
|
+
denom = torch.sqrt((a * a).sum() * (b * b).sum()).clamp_min(1e-12)
|
|
36
|
+
return float(((a * b).sum() / denom).item())
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def density_quality(pool, mol, heavy_mask, density_k):
|
|
40
|
+
dist = infer_base_conformers._pairwise_torsion_signature_distance(
|
|
41
|
+
pool, mol, fallback_metric="kabsch", heavy_mask=heavy_mask
|
|
42
|
+
)
|
|
43
|
+
n = int(dist.size(0))
|
|
44
|
+
eye = torch.eye(n, dtype=dist.dtype)
|
|
45
|
+
k = max(1, min(int(density_k), max(1, n - 1)))
|
|
46
|
+
sorted_dist = torch.sort(dist + eye * 1e6, dim=1).values
|
|
47
|
+
local_radius = sorted_dist[:, :k].mean(dim=1)
|
|
48
|
+
centrality = dist.mean(dim=1)
|
|
49
|
+
return infer_base_conformers._normalize_01(local_radius) + 0.45 * infer_base_conformers._normalize_01(centrality), dist
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def main():
|
|
53
|
+
parser = argparse.ArgumentParser()
|
|
54
|
+
parser.add_argument("--pool_pt", required=True)
|
|
55
|
+
parser.add_argument("--max_molecules", type=int, default=0)
|
|
56
|
+
parser.add_argument("--modes", type=int, default=3)
|
|
57
|
+
parser.add_argument("--budget_multiplier", type=float, default=2.0)
|
|
58
|
+
parser.add_argument("--controls", default="normal,shuffle,random")
|
|
59
|
+
parser.add_argument("--seed", type=int, default=20260825)
|
|
60
|
+
parser.add_argument("--density_k", type=int, default=20)
|
|
61
|
+
parser.add_argument("--output_prefix", required=True)
|
|
62
|
+
args = parser.parse_args()
|
|
63
|
+
|
|
64
|
+
payload = torch.load(args.pool_pt, map_location="cpu", weights_only=False)
|
|
65
|
+
records = list(payload["records"])
|
|
66
|
+
if args.max_molecules > 0:
|
|
67
|
+
records = records[: args.max_molecules]
|
|
68
|
+
controls = [x.strip() for x in args.controls.split(",") if x.strip()]
|
|
69
|
+
rows = []
|
|
70
|
+
for record in tqdm(records, desc="P ranking diagnostics", unit="molecule"):
|
|
71
|
+
pool = record["raw_pool"].float()
|
|
72
|
+
budget = min(int(pool.size(0)), max(1, int(round(
|
|
73
|
+
args.budget_multiplier * record["ref_confs"].size(0)
|
|
74
|
+
))))
|
|
75
|
+
density, distance = density_quality(
|
|
76
|
+
pool, record.get("mol"), record.get("heavy_mask"), args.density_k
|
|
77
|
+
)
|
|
78
|
+
assignment = farthest_point_basins(distance, args.modes)
|
|
79
|
+
learned = record.get("pglobal")
|
|
80
|
+
kernel = record.get("pgraph_kernel")
|
|
81
|
+
if learned is None or kernel is None:
|
|
82
|
+
continue
|
|
83
|
+
scores = {}
|
|
84
|
+
for control in controls:
|
|
85
|
+
control_args = Namespace(
|
|
86
|
+
pglobal_control=control, pglobal_seed=args.seed,
|
|
87
|
+
disable_stage1_pglobal=False,
|
|
88
|
+
)
|
|
89
|
+
target = controlled_pglobal(learned.float(), control_args, mol=record.get("mol"))
|
|
90
|
+
scores[control] = candidate_p_bce(pool, target, kernel, record.get("mol"))
|
|
91
|
+
row = {"mol_id": record["mol_id"], "pool_size": int(pool.size(0)), "budget": budget}
|
|
92
|
+
for control in controls:
|
|
93
|
+
row[f"p_vs_density_spearman_{control}"] = corr(scores[control], density)
|
|
94
|
+
top = torch.argsort(scores[control])[:budget]
|
|
95
|
+
row[f"top_budget_mean_bce_{control}"] = float(scores[control][top].mean())
|
|
96
|
+
row[f"top_budget_density_{control}"] = float(density[top].mean())
|
|
97
|
+
for i, first in enumerate(controls):
|
|
98
|
+
for second in controls[i + 1:]:
|
|
99
|
+
row[f"rank_corr_{first}_vs_{second}"] = corr(scores[first], scores[second])
|
|
100
|
+
left = set(torch.argsort(scores[first])[:budget].tolist())
|
|
101
|
+
right = set(torch.argsort(scores[second])[:budget].tolist())
|
|
102
|
+
row[f"top_budget_jaccard_{first}_vs_{second}"] = len(left & right) / max(1, len(left | right))
|
|
103
|
+
rows.append(row)
|
|
104
|
+
|
|
105
|
+
keys = sorted({key for row in rows for key in row})
|
|
106
|
+
prefix = Path(args.output_prefix)
|
|
107
|
+
prefix.parent.mkdir(parents=True, exist_ok=True)
|
|
108
|
+
import csv
|
|
109
|
+
with prefix.with_name(prefix.name + "_per_molecule.csv").open("w", newline="") as handle:
|
|
110
|
+
writer = csv.DictWriter(handle, fieldnames=keys)
|
|
111
|
+
writer.writeheader(); writer.writerows(rows)
|
|
112
|
+
summary = {"molecules": len(rows), "controls": controls}
|
|
113
|
+
for key in keys:
|
|
114
|
+
if key in {"mol_id", "pool_size", "budget"}:
|
|
115
|
+
continue
|
|
116
|
+
vals = [float(row[key]) for row in rows if key in row]
|
|
117
|
+
summary[key] = {"mean": float(np.mean(vals)), "std": float(np.std(vals))}
|
|
118
|
+
prefix.with_name(prefix.name + "_summary.json").write_text(json.dumps(summary, indent=2) + "\n")
|
|
119
|
+
print(json.dumps(summary, indent=2))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
if __name__ == "__main__":
|
|
123
|
+
main()
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Inventory local receptor, ligand, pose, CSV, and PyMOL-session candidates."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
ROOTS = (Path("data"), Path("outputs"))
|
|
12
|
+
PATTERN = re.compile(r"(receptor|protein|ligand|pose|dock|vina|pymol|\.pse$|\.pdb$|\.pdbqt$|\.sdf$|\.mol2$|\.csv$)", re.I)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main() -> None:
|
|
16
|
+
records = []
|
|
17
|
+
for root in ROOTS:
|
|
18
|
+
if not root.exists():
|
|
19
|
+
continue
|
|
20
|
+
for path in root.rglob("*"):
|
|
21
|
+
if path.is_file() and PATTERN.search(str(path)):
|
|
22
|
+
records.append(str(path))
|
|
23
|
+
out = Path("outputs/binding_mode_figure/discovery_report.json")
|
|
24
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
25
|
+
out.write_text(json.dumps({"candidates": sorted(records)}, indent=2) + "\n")
|
|
26
|
+
print(f"Saved {len(records)} candidates to {out}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
if __name__ == "__main__":
|
|
30
|
+
main()
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Evaluate optional functional-aware Stage-I probability teachers.
|
|
3
|
+
|
|
4
|
+
This diagnostic is intentionally protein-free. It compares predicted pairwise
|
|
5
|
+
probability maps with geometry and functional-aware ensemble teachers on the
|
|
6
|
+
same GEOM split, and exports a compact visual audit for one representative
|
|
7
|
+
molecule. It does not modify checkpoints or the main MANIMOL pipeline.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
from collections import OrderedDict
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
import matplotlib.pyplot as plt
|
|
18
|
+
import numpy as np
|
|
19
|
+
import pandas as pd
|
|
20
|
+
import torch
|
|
21
|
+
from torch_geometric.data import Batch
|
|
22
|
+
|
|
23
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
24
|
+
if str(ROOT) not in sys.path:
|
|
25
|
+
sys.path.insert(0, str(ROOT))
|
|
26
|
+
|
|
27
|
+
from dataset import QM9Dataset
|
|
28
|
+
from models.model0 import (
|
|
29
|
+
_functional_atom_masks,
|
|
30
|
+
cross_entropy_loss,
|
|
31
|
+
functional_aware_teacher_graph,
|
|
32
|
+
prob_low_dim_kernel,
|
|
33
|
+
)
|
|
34
|
+
from train_torsional_denoiser import load_base_model
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_checkpoints(value: str) -> OrderedDict[str, str]:
|
|
38
|
+
result: OrderedDict[str, str] = OrderedDict()
|
|
39
|
+
for item in value.split(","):
|
|
40
|
+
item = item.strip()
|
|
41
|
+
if not item:
|
|
42
|
+
continue
|
|
43
|
+
if "=" not in item:
|
|
44
|
+
raise ValueError("--checkpoints expects Label=/path/to/checkpoint pairs.")
|
|
45
|
+
label, path = item.split("=", 1)
|
|
46
|
+
result[label.strip()] = path.strip()
|
|
47
|
+
if not result:
|
|
48
|
+
raise ValueError("At least one checkpoint is required.")
|
|
49
|
+
return result
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def checkpoint_max_confs(path: str) -> int:
|
|
53
|
+
checkpoint = torch.load(path, map_location="cpu")
|
|
54
|
+
state = checkpoint.get("model_state_dict", checkpoint.get("state_dict", checkpoint)) if isinstance(checkpoint, dict) else checkpoint
|
|
55
|
+
for key, value in state.items():
|
|
56
|
+
if key.endswith("conf_embedding.weight"):
|
|
57
|
+
return int(value.shape[0])
|
|
58
|
+
raise KeyError(f"conf_embedding.weight is missing from checkpoint: {path}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def grouped_split(dataset, indices, max_molecules: int):
|
|
62
|
+
groups: OrderedDict[int, list] = OrderedDict()
|
|
63
|
+
for index in indices:
|
|
64
|
+
item = dataset[int(index)]
|
|
65
|
+
mol_id = int(torch.as_tensor(item.mol_id).view(-1)[0].item())
|
|
66
|
+
groups.setdefault(mol_id, []).append(item)
|
|
67
|
+
if max_molecules > 0 and len(groups) >= max_molecules:
|
|
68
|
+
continue
|
|
69
|
+
groups = OrderedDict((key, value) for key, value in groups.items())
|
|
70
|
+
if max_molecules > 0:
|
|
71
|
+
groups = OrderedDict(list(groups.items())[:max_molecules])
|
|
72
|
+
return groups
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def functional_pair_mask(mol, n_atoms: int, device):
|
|
76
|
+
masks = _functional_atom_masks(mol, n_atoms, device)
|
|
77
|
+
hbond = (masks["hbd"][:, None] & masks["hba"][None, :]) | (masks["hba"][:, None] & masks["hbd"][None, :])
|
|
78
|
+
aromatic = masks["aromatic"][:, None] & masks["aromatic"][None, :]
|
|
79
|
+
hydrophobic = masks["hydrophobic"][:, None] & masks["hydrophobic"][None, :]
|
|
80
|
+
mask = hbond | aromatic | hydrophobic
|
|
81
|
+
mask.fill_diagonal_(False)
|
|
82
|
+
return torch.triu(mask, diagonal=1)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@torch.no_grad()
|
|
86
|
+
def evaluate_one(model, conformers, device, kernel: str):
|
|
87
|
+
batch = Batch.from_data_list([conformers[0]]).to(device)
|
|
88
|
+
node_feat = model.gnn(batch)
|
|
89
|
+
graph_feat = model.pool(node_feat, batch.batch)
|
|
90
|
+
edge_i = model._get_local_edge_index(batch.edge_index, batch.batch == 0)
|
|
91
|
+
P, _ = model._predict_P_global(node_feat, edge_i)
|
|
92
|
+
P = P.detach()
|
|
93
|
+
q_geom_list, q_func_list = [], []
|
|
94
|
+
mol = conformers[0].rdmol
|
|
95
|
+
for conformer in conformers:
|
|
96
|
+
pos = conformer.pos.to(device=device, dtype=node_feat.dtype)
|
|
97
|
+
conf_id = int(torch.as_tensor(conformer.conf_id).view(-1)[0].item())
|
|
98
|
+
a, b = model.predict_ab(graph_feat[0], conf_id)
|
|
99
|
+
q_geom = prob_low_dim_kernel(pos, a, b, kernel=kernel)
|
|
100
|
+
q_geom_list.append(q_geom)
|
|
101
|
+
q_func_list.append(functional_aware_teacher_graph(q_geom, mol, model.args))
|
|
102
|
+
q_geom = torch.stack(q_geom_list).mean(dim=0)
|
|
103
|
+
q_func = torch.stack(q_func_list).mean(dim=0)
|
|
104
|
+
pair_mask = functional_pair_mask(mol, int(P.size(0)), device)
|
|
105
|
+
off_diag = torch.triu(torch.ones_like(P, dtype=torch.bool), diagonal=1)
|
|
106
|
+
other_mask = off_diag & ~pair_mask
|
|
107
|
+
functional_mean = P[pair_mask].mean() if pair_mask.any() else P.new_tensor(float("nan"))
|
|
108
|
+
other_mean = P[other_mask].mean() if other_mask.any() else P.new_tensor(float("nan"))
|
|
109
|
+
enrichment = functional_mean - other_mean if torch.isfinite(functional_mean) and torch.isfinite(other_mean) else P.new_tensor(float("nan"))
|
|
110
|
+
return {
|
|
111
|
+
"P": P.cpu(),
|
|
112
|
+
"Q_geom": q_geom.cpu(),
|
|
113
|
+
"Q_func": q_func.cpu(),
|
|
114
|
+
"bce_geometry": float(cross_entropy_loss(P, q_geom).item()),
|
|
115
|
+
"bce_functional": float(cross_entropy_loss(P, q_func).item()),
|
|
116
|
+
"functional_pair_probability": float(functional_mean.item()),
|
|
117
|
+
"other_pair_probability": float(other_mean.item()),
|
|
118
|
+
"functional_pair_enrichment": float(enrichment.item()),
|
|
119
|
+
"mol": mol,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def plot_audit(conformers, audit, output_prefix: Path, title: str):
|
|
124
|
+
fig, axes = plt.subplots(1, 4, figsize=(10.0, 2.65), dpi=300, gridspec_kw={"wspace": 0.34})
|
|
125
|
+
coords = np.stack([item.pos.detach().cpu().numpy() for item in conformers[: min(5, len(conformers))]])
|
|
126
|
+
for xyz in coords:
|
|
127
|
+
axes[0].plot(xyz[:, 0], xyz[:, 1], "o-", ms=2.8, lw=0.8, color="#8E6BBE", alpha=0.35)
|
|
128
|
+
axes[0].set_title("a Reference ensemble", loc="left", fontsize=8.4, weight="semibold")
|
|
129
|
+
axes[0].set_aspect("equal", adjustable="box")
|
|
130
|
+
axes[0].set_xticks([])
|
|
131
|
+
axes[0].set_yticks([])
|
|
132
|
+
for spine in axes[0].spines.values():
|
|
133
|
+
spine.set_visible(False)
|
|
134
|
+
|
|
135
|
+
maps = [("b $Q_{geom}$", audit["Q_geom"]), ("c $Q_{func}$", audit["Q_func"]), ("d $P_\\theta(G)$", audit["P"])]
|
|
136
|
+
for ax, (label, matrix) in zip(axes[1:], maps):
|
|
137
|
+
image = ax.imshow(matrix.numpy(), cmap="Purples", vmin=0.0, vmax=1.0, interpolation="nearest")
|
|
138
|
+
ax.set_title(label, loc="left", fontsize=8.4, weight="semibold")
|
|
139
|
+
ax.set_xticks([])
|
|
140
|
+
ax.set_yticks([])
|
|
141
|
+
for spine in ax.spines.values():
|
|
142
|
+
spine.set_color("#777777")
|
|
143
|
+
spine.set_linewidth(0.5)
|
|
144
|
+
cbar = fig.colorbar(image, ax=axes[1:], fraction=0.026, pad=0.02)
|
|
145
|
+
cbar.ax.tick_params(labelsize=6.3, width=0.5, length=2)
|
|
146
|
+
cbar.set_label("Pair probability", fontsize=6.8)
|
|
147
|
+
fig.suptitle(title, fontsize=9.0, y=1.01)
|
|
148
|
+
fig.savefig(output_prefix.with_suffix(".png"), bbox_inches="tight", pad_inches=0.03)
|
|
149
|
+
fig.savefig(output_prefix.with_suffix(".pdf"), bbox_inches="tight", pad_inches=0.03)
|
|
150
|
+
fig.savefig(output_prefix.with_suffix(".svg"), bbox_inches="tight", pad_inches=0.03)
|
|
151
|
+
plt.close(fig)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def main():
|
|
155
|
+
parser = argparse.ArgumentParser(description="Protein-free evaluation of functional-aware Stage-I teachers.")
|
|
156
|
+
parser.add_argument("--checkpoints", required=True, help="Comma-separated Label=/path pairs.")
|
|
157
|
+
parser.add_argument("--data_root", default="data")
|
|
158
|
+
parser.add_argument("--raw_prefix", default="geom_drugs")
|
|
159
|
+
parser.add_argument("--split", default="test", choices=["train", "val", "test"])
|
|
160
|
+
parser.add_argument("--max_confs", type=int, default=0,
|
|
161
|
+
help="Conformer cap; 0 reads the shared capacity from the supplied checkpoints.")
|
|
162
|
+
parser.add_argument("--max_molecules", type=int, default=50)
|
|
163
|
+
parser.add_argument("--device", default="auto")
|
|
164
|
+
parser.add_argument("--stage1_kernel", default="umap")
|
|
165
|
+
parser.add_argument("--output_prefix", default="outputs/functional_prior/stage1_teacher_alignment")
|
|
166
|
+
# The YAML runner appends common training flags (for example
|
|
167
|
+
# --fixed_dump_name) that are irrelevant to this standalone diagnostic.
|
|
168
|
+
args, _ = parser.parse_known_args()
|
|
169
|
+
|
|
170
|
+
device = torch.device("cuda" if args.device == "auto" and torch.cuda.is_available() else args.device if args.device != "auto" else "cpu")
|
|
171
|
+
checkpoints = parse_checkpoints(args.checkpoints)
|
|
172
|
+
capacities = {label: checkpoint_max_confs(path) for label, path in checkpoints.items()}
|
|
173
|
+
unique_capacities = set(capacities.values())
|
|
174
|
+
if int(args.max_confs) == 0:
|
|
175
|
+
if len(unique_capacities) != 1:
|
|
176
|
+
raise ValueError(
|
|
177
|
+
"Functional-prior comparison requires checkpoints trained with the same max_confs; "
|
|
178
|
+
f"received {capacities}."
|
|
179
|
+
)
|
|
180
|
+
args.max_confs = unique_capacities.pop()
|
|
181
|
+
print(f"Auto-resolved max_confs={args.max_confs} from checkpoints.")
|
|
182
|
+
elif any(capacity != int(args.max_confs) for capacity in capacities.values()):
|
|
183
|
+
raise ValueError(
|
|
184
|
+
f"--max_confs={args.max_confs} does not match checkpoint capacities: {capacities}."
|
|
185
|
+
)
|
|
186
|
+
dataset = QM9Dataset(name="Drugs", root=args.data_root, max_confs=args.max_confs, raw_prefix=args.raw_prefix)
|
|
187
|
+
split_indices = {"train": dataset.train_index, "val": dataset.valid_index, "test": dataset.test_index}[args.split]
|
|
188
|
+
groups = grouped_split(dataset, split_indices, args.max_molecules)
|
|
189
|
+
out_prefix = Path(args.output_prefix)
|
|
190
|
+
out_prefix.parent.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
|
|
192
|
+
rows = []
|
|
193
|
+
visual_candidate = None
|
|
194
|
+
for label, checkpoint in checkpoints.items():
|
|
195
|
+
loader_args = type("Args", (), {"checkpoint": checkpoint, "max_confs": args.max_confs})()
|
|
196
|
+
model = load_base_model(loader_args, device)
|
|
197
|
+
for mol_id, conformers in groups.items():
|
|
198
|
+
audit = evaluate_one(model, conformers, device, args.stage1_kernel)
|
|
199
|
+
smiles = str(getattr(conformers[0], "smiles", ""))
|
|
200
|
+
rows.append({
|
|
201
|
+
"variant": label,
|
|
202
|
+
"mol_id": mol_id,
|
|
203
|
+
"smiles": smiles,
|
|
204
|
+
"n_conformers": len(conformers),
|
|
205
|
+
"bce_geometry": audit["bce_geometry"],
|
|
206
|
+
"bce_functional": audit["bce_functional"],
|
|
207
|
+
"functional_pair_probability": audit["functional_pair_probability"],
|
|
208
|
+
"other_pair_probability": audit["other_pair_probability"],
|
|
209
|
+
"functional_pair_enrichment": audit["functional_pair_enrichment"],
|
|
210
|
+
})
|
|
211
|
+
if visual_candidate is None and np.isfinite(audit["functional_pair_enrichment"]):
|
|
212
|
+
visual_candidate = (label, conformers, audit)
|
|
213
|
+
|
|
214
|
+
per_molecule = pd.DataFrame(rows)
|
|
215
|
+
summary = per_molecule.groupby("variant", sort=False).mean(numeric_only=True).reset_index()
|
|
216
|
+
per_path = out_prefix.with_name(out_prefix.name + "_per_molecule.csv")
|
|
217
|
+
summary_path = out_prefix.with_name(out_prefix.name + "_summary.csv")
|
|
218
|
+
per_molecule.to_csv(per_path, index=False)
|
|
219
|
+
summary.to_csv(summary_path, index=False)
|
|
220
|
+
if visual_candidate is not None:
|
|
221
|
+
label, conformers, audit = visual_candidate
|
|
222
|
+
plot_audit(conformers, audit, out_prefix.with_name(out_prefix.name + "_heatmap"), f"Functional-aware probability prior: {label}")
|
|
223
|
+
print(f"Saved: {per_path}")
|
|
224
|
+
print(f"Saved: {summary_path}")
|
|
225
|
+
print(f"Evaluated {len(groups)} molecules on {device}.")
|
|
226
|
+
print(summary.to_string(index=False, float_format=lambda value: f"{value:.4f}"))
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
if __name__ == "__main__":
|
|
230
|
+
main()
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
"""COV/AMR evaluation for GeoManimol generated ensembles."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
|
|
12
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
13
|
+
|
|
14
|
+
from geomanimol.data import load_molecule_groups
|
|
15
|
+
from geomanimol.geometry import DynamicGeometryMemory
|
|
16
|
+
from geomanimol.model import GeoManimol
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def kabsch_rmsd(a: torch.Tensor, b: torch.Tensor) -> float:
|
|
20
|
+
a = a - a.mean(dim=0, keepdim=True)
|
|
21
|
+
b = b - b.mean(dim=0, keepdim=True)
|
|
22
|
+
cov = b.t() @ a
|
|
23
|
+
u, _, vh = torch.linalg.svd(cov)
|
|
24
|
+
correction = torch.eye(3, dtype=a.dtype)
|
|
25
|
+
correction[-1, -1] = torch.sign(torch.linalg.det(vh.t() @ u.t()))
|
|
26
|
+
rot = vh.t() @ correction @ u.t()
|
|
27
|
+
return float(torch.sqrt(((b @ rot - a) ** 2).sum(dim=-1).mean().clamp_min(1e-12)))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def distances(reference, generated):
|
|
31
|
+
return torch.tensor([[kabsch_rmsd(r, g) for g in generated] for r in reference])
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def main():
|
|
35
|
+
p = argparse.ArgumentParser()
|
|
36
|
+
p.add_argument("--test", default="data/geom_drugs_geomol_top20/geom_drugs_geomol_top20_debug_val.pt")
|
|
37
|
+
p.add_argument("--checkpoint", default="outputs/geomanimol/debug_p0_p1_checkpoint.pt")
|
|
38
|
+
p.add_argument("--molecules", type=int, default=2)
|
|
39
|
+
p.add_argument("--samples", type=int, default=8)
|
|
40
|
+
p.add_argument("--threshold", type=float, default=0.75)
|
|
41
|
+
p.add_argument("--steps", type=int, default=10)
|
|
42
|
+
args = p.parse_args()
|
|
43
|
+
|
|
44
|
+
molecules = load_molecule_groups(args.test, args.molecules)
|
|
45
|
+
checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
|
|
46
|
+
saved = checkpoint.get("args", {})
|
|
47
|
+
model = GeoManimol(saved.get("node_dim", 32), saved.get("n_basins", 3), saved.get("manifold_dim", 8), saved.get("diffusion_steps", 1000))
|
|
48
|
+
model.load_state_dict(checkpoint["model"])
|
|
49
|
+
model.eval()
|
|
50
|
+
|
|
51
|
+
recall_cov, precision_cov, recall_amr, precision_amr = [], [], [], []
|
|
52
|
+
for mol in molecules:
|
|
53
|
+
generated = model.generate(mol, args.samples, args.steps)
|
|
54
|
+
matrix = distances(mol["conformations"], generated)
|
|
55
|
+
recall_min = matrix.min(dim=1).values
|
|
56
|
+
precision_min = matrix.min(dim=0).values
|
|
57
|
+
recall_cov.append(float((recall_min <= args.threshold).float().mean()))
|
|
58
|
+
precision_cov.append(float((precision_min <= args.threshold).float().mean()))
|
|
59
|
+
recall_amr.append(float(recall_min.mean()))
|
|
60
|
+
precision_amr.append(float(precision_min.mean()))
|
|
61
|
+
|
|
62
|
+
print({
|
|
63
|
+
"molecules": len(molecules),
|
|
64
|
+
"samples": args.samples,
|
|
65
|
+
"threshold": args.threshold,
|
|
66
|
+
"COV-R": sum(recall_cov) / len(recall_cov),
|
|
67
|
+
"COV-P": sum(precision_cov) / len(precision_cov),
|
|
68
|
+
"AMR-R": sum(recall_amr) / len(recall_amr),
|
|
69
|
+
"AMR-P": sum(precision_amr) / len(precision_amr),
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
if __name__ == "__main__":
|
|
74
|
+
main()
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
"""Evaluate the parallel torsion flow-matching route."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
import argparse,sys,json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import torch
|
|
7
|
+
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
|
8
|
+
from geomanimol.data import load_molecule_groups
|
|
9
|
+
from geomanimol.residual import etkdg_scaffolds
|
|
10
|
+
from geomanimol.torsion_flow import TorsionFlowGeoManimol
|
|
11
|
+
from scripts.evaluate_geomanimol import distances
|
|
12
|
+
def main():
|
|
13
|
+
p=argparse.ArgumentParser(); p.add_argument('--test',default='data/geom_drugs_geomol_top20/geom_drugs_geomol_top20_debug_val.pt'); p.add_argument('--checkpoint',default='outputs/geomanimol/flow_debug_checkpoint.pt'); p.add_argument('--molecules',type=int,default=20); p.add_argument('--scaffolds',type=int,default=10); p.add_argument('--samples',type=int,default=20); p.add_argument('--steps',type=int,default=20); p.add_argument('--threshold',type=float,default=.75); p.add_argument('--condition-mode',choices=('full','no_z','shuffle_z'),default='full'); p.add_argument('--output',default=''); a=p.parse_args(); ms=load_molecule_groups(a.test,a.molecules); ck=torch.load(a.checkpoint,map_location='cpu',weights_only=False); c=ck['args']; model=TorsionFlowGeoManimol(c['node_dim'],c['n_basins'],c['manifold_dim'],c.get('assignment_weight',.5),c.get('basin_weight',.2)); model.load_state_dict(ck['model']); model.eval(); rr=[]; pp=[]; ar=[]; ap=[]
|
|
14
|
+
for m in ms:
|
|
15
|
+
gens=[]; ss=etkdg_scaffolds(m['mol'],a.scaffolds,30300+m['mol_id']*100)
|
|
16
|
+
for s in ss: gens.append(model.generate(m,s,max(1,a.samples//len(ss)),a.steps,a.condition_mode))
|
|
17
|
+
g=torch.cat(gens)[:a.samples]; d=distances(m['conformations'],g); r,q=d.min(1).values,d.min(0).values; rr.append(float((r<=a.threshold).float().mean())); pp.append(float((q<=a.threshold).float().mean())); ar.append(float(r.mean())); ap.append(float(q.mean()))
|
|
18
|
+
result={'molecules':len(ms),'scaffolds':a.scaffolds,'samples':a.samples,'steps':a.steps,'threshold':a.threshold,'condition_mode':a.condition_mode,'COV-R':sum(rr)/len(rr),'COV-P':sum(pp)/len(pp),'AMR-R':sum(ar)/len(ar),'AMR-P':sum(ap)/len(ap)}
|
|
19
|
+
print(result)
|
|
20
|
+
if a.output:
|
|
21
|
+
Path(a.output).parent.mkdir(parents=True,exist_ok=True)
|
|
22
|
+
Path(a.output).write_text(json.dumps(result,indent=2),encoding='utf-8')
|
|
23
|
+
if __name__=='__main__': main()
|