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.
Files changed (186) hide show
  1. args_parse.py +593 -0
  2. candidate_corrector.py +161 -0
  3. candidate_scorer.py +359 -0
  4. conformend/__init__.py +36 -0
  5. conformend/refiner.py +25 -0
  6. dataset/__init__.py +1 -0
  7. dataset/drugdataset.py +644 -0
  8. dataset/manifold.py +237 -0
  9. dataset/sharded_drugdataset.py +124 -0
  10. dataset/smiles2graph.py +217 -0
  11. dualmapref/__init__.py +24 -0
  12. dualmapref/refiner.py +16 -0
  13. dualmapref-0.2.8.dist-info/LICENSE +21 -0
  14. dualmapref-0.2.8.dist-info/METADATA +167 -0
  15. dualmapref-0.2.8.dist-info/RECORD +186 -0
  16. dualmapref-0.2.8.dist-info/WHEEL +5 -0
  17. dualmapref-0.2.8.dist-info/entry_points.txt +10 -0
  18. dualmapref-0.2.8.dist-info/top_level.txt +29 -0
  19. exputils.py +289 -0
  20. infer.py +23 -0
  21. infer_base_conformers.py +5589 -0
  22. infer_mean_dispersion_torsion.py +1117 -0
  23. infer_torsion.py +752 -0
  24. infer_torsional_denoiser.py +1021 -0
  25. manimol/__init__.py +30 -0
  26. manimol/__main__.py +6 -0
  27. manimol/cli.py +36 -0
  28. manimol/full_cli.py +41 -0
  29. manimol/legacy_imports.py +43 -0
  30. manimol/manifest.py +56 -0
  31. manimol/postprocess.py +148 -0
  32. manimol/priors.py +60 -0
  33. manimol/protocols.py +119 -0
  34. manimol/refiner.py +645 -0
  35. manimol/runtime.py +194 -0
  36. manimol/selection.py +85 -0
  37. manimol/torsion.py +22 -0
  38. manimol/train_cli.py +14 -0
  39. mixture_flow/src/__init__.py +1 -0
  40. mixture_flow/src/_path.py +7 -0
  41. mixture_flow/src/infer28_mixture_torsion_flow.py +1093 -0
  42. mixture_flow/src/mixture_torsion_flow.py +291 -0
  43. mixture_flow/src/summarize_mixture_debug.py +80 -0
  44. mixture_flow/src/train28_mixture_torsion_flow.py +583 -0
  45. mixture_torsion_flow.py +7 -0
  46. models/ manifold_learning.py +86 -0
  47. models/__init__.py +8 -0
  48. models/dist.py +273 -0
  49. models/dist2coords.py +23 -0
  50. models/egnn.py +107 -0
  51. models/experimental_backbones.py +364 -0
  52. models/gnnconv.py +512 -0
  53. models/kernel_inversion.py +141 -0
  54. models/kernels.py +427 -0
  55. models/losses.py +154 -0
  56. models/mean_dispersion_bridge.py +119 -0
  57. models/mean_dispersion_torsion_context.py +155 -0
  58. models/model.py +73 -0
  59. models/model0.py +2375 -0
  60. models/vis.py +128 -0
  61. pgraph_controls.py +107 -0
  62. scripts/__init__.py +2 -0
  63. scripts/analyze_basin_alignment.py +63 -0
  64. scripts/analyze_hif2a_conformer_aggregation.py +267 -0
  65. scripts/analyze_hif2a_contact_pharmacophore.py +1111 -0
  66. scripts/analyze_hif2a_fixed_budget.py +202 -0
  67. scripts/analyze_hif2a_pharmacophore.py +405 -0
  68. scripts/analyze_hif2a_pharmacophore_match_metric.py +386 -0
  69. scripts/analyze_p_control_candidate_flow.py +154 -0
  70. scripts/analyze_scaffold_basin.py +83 -0
  71. scripts/audit_dispersion_proposals.py +208 -0
  72. scripts/audit_etflow_protocol.py +258 -0
  73. scripts/audit_external_overlap.py +150 -0
  74. scripts/audit_oldbest_fulltrainval_split.py +82 -0
  75. scripts/audit_pdbbind_contact_pharmacophores.py +146 -0
  76. scripts/audit_qm9_geomol_test_split.py +94 -0
  77. scripts/audit_stage1_stage2_cross.py +131 -0
  78. scripts/build_geom_drugs_lowref_diagnostic.py +84 -0
  79. scripts/build_qm9_backfill_manifest.py +99 -0
  80. scripts/check_etflow_runtime.py +56 -0
  81. scripts/compare_prior_sources.py +122 -0
  82. scripts/compose_binding_mode_figure.py +87 -0
  83. scripts/compose_hif2a_contact_pharmacophore_suppfig.py +255 -0
  84. scripts/compose_hif2a_functional_geometry_pipeline.py +266 -0
  85. scripts/compose_manimol_internal_architecture.py +291 -0
  86. scripts/diagnose_flow_basin_intervention.py +54 -0
  87. scripts/diagnose_hif2a_pharmacophore_budget.py +185 -0
  88. scripts/diagnose_route2_p_ranking.py +123 -0
  89. scripts/discover_binding_mode_inputs.py +30 -0
  90. scripts/evaluate_functional_prior_stage1.py +230 -0
  91. scripts/evaluate_geomanimol.py +74 -0
  92. scripts/evaluate_geomanimol_flow.py +23 -0
  93. scripts/evaluate_geomanimol_multiscaffold.py +46 -0
  94. scripts/evaluate_geomanimol_residual.py +45 -0
  95. scripts/evaluate_geomanimol_torsion.py +40 -0
  96. scripts/evaluate_hif2a_bioactive_enrichment.py +91 -0
  97. scripts/evaluate_hif2a_pms_suite.py +440 -0
  98. scripts/evaluate_pdbbind_contact_pms.py +155 -0
  99. scripts/evaluate_platinum_external.py +114 -0
  100. scripts/evaluate_platinum_pool.py +82 -0
  101. scripts/evaluate_route2_calibrated_p.py +104 -0
  102. scripts/evaluate_route2_library_components.py +596 -0
  103. scripts/evaluate_route2_p_basin_budget.py +288 -0
  104. scripts/evaluate_stage1_checkpoint_only.py +30 -0
  105. scripts/export_dispersion_bond_audit.py +136 -0
  106. scripts/export_top20_shards.py +207 -0
  107. scripts/external_validation_metrics.py +152 -0
  108. scripts/fit_topology_prior.py +117 -0
  109. scripts/frozen_dispersion_audit.py +281 -0
  110. scripts/geomanimol_debug.py +50 -0
  111. scripts/geomanimol_smoke.py +37 -0
  112. scripts/infer_etflow_matched.py +524 -0
  113. scripts/inspect_checkpoint.py +12 -0
  114. scripts/inspect_conformer_capacity.py +71 -0
  115. scripts/inspect_pool.py +12 -0
  116. scripts/make_figure3_selection_loss.py +474 -0
  117. scripts/make_figure3_selection_summary.py +275 -0
  118. scripts/make_geom_debug_subset.py +62 -0
  119. scripts/make_low_reference_test_subset.py +70 -0
  120. scripts/merge_stage1_into_stage2.py +82 -0
  121. scripts/place_hif2a_candidates_for_evaluation.py +66 -0
  122. scripts/plot_hif2a_low_budget_efficiency.py +100 -0
  123. scripts/plot_prior_validation.py +48 -0
  124. scripts/precompute_stage2_assignments.py +90 -0
  125. scripts/prepare_bace_activity.py +98 -0
  126. scripts/prepare_bace_etkdg_benchmark.py +90 -0
  127. scripts/prepare_figure5_4x4_cases.py +470 -0
  128. scripts/prepare_geom_drugs_geomol_top20.py +472 -0
  129. scripts/prepare_pdbbind_core_raw.py +90 -0
  130. scripts/prepare_platinum_raw.py +74 -0
  131. scripts/prepare_pubchem_etkdg.py +54 -0
  132. scripts/rebuild_hif2a_final_sdf_and_metrics.py +55 -0
  133. scripts/rebuild_hif2a_fixed_pool_sweep.py +175 -0
  134. scripts/rebuild_hif2a_strict.py +220 -0
  135. scripts/recompute_hif2a_bootstrap.py +63 -0
  136. scripts/reference_free_geometry.py +112 -0
  137. scripts/render_binding_modes.py +413 -0
  138. scripts/render_figure5_4x4.py +330 -0
  139. scripts/render_figure6_pharmacophore_pymol.py +162 -0
  140. scripts/render_hif2a_contact_pharmacophore_pymol.py +414 -0
  141. scripts/render_hif2a_figure11.py +397 -0
  142. scripts/run_bace_2d_baseline.py +73 -0
  143. scripts/run_drugs_validation_matrix.py +225 -0
  144. scripts/run_external_reference_free.py +53 -0
  145. scripts/run_manimol_finalk_sensitivity.py +106 -0
  146. scripts/run_manimol_oversampling_sensitivity.py +109 -0
  147. scripts/run_pdisp_matched_intervention.py +116 -0
  148. scripts/run_stage1_stage2_cross20.py +83 -0
  149. scripts/score_hif2a_candidates_with_pgraph.py +221 -0
  150. scripts/summarize_dispersion_intervention.py +88 -0
  151. scripts/test_mean_dispersion_bridge.py +50 -0
  152. scripts/train_dispersion_head_diagnostic.py +320 -0
  153. scripts/train_dispersion_head_streaming.py +519 -0
  154. scripts/train_geomanimol.py +100 -0
  155. scripts/train_geomanimol_flow.py +26 -0
  156. scripts/train_geomanimol_residual.py +70 -0
  157. scripts/train_geomanimol_torsion.py +50 -0
  158. scripts/train_quantile_representation_diagnostic.py +204 -0
  159. scripts/validate_mean_dispersion_prior.py +173 -0
  160. scripts/validate_packed_shard.py +41 -0
  161. scripts/validate_stage1_prior.py +221 -0
  162. scripts/validate_top20_shards.py +36 -0
  163. scripts/validation/__init__.py +1 -0
  164. scripts/validation/hif2a_downstream_baselines.py +105 -0
  165. scripts/validation/hif2a_pairwise_ranker.py +218 -0
  166. scripts/verify_binding_mode_figure.py +47 -0
  167. torsion_manifold.py +281 -0
  168. train.py +78 -0
  169. train_graph_encoder.py +206 -0
  170. train_local_torsion_corrector.py +511 -0
  171. train_mean_dispersion_torsion_prior.py +329 -0
  172. train_probability_basin.py +235 -0
  173. train_torsion_generator.py +1631 -0
  174. train_torsion_manifold_prior.py +258 -0
  175. train_torsional_denoiser.py +415 -0
  176. trainer.py +1038 -0
  177. utils/__init__.py +7 -0
  178. utils/checkpoint.py +40 -0
  179. utils/device.py +17 -0
  180. utils/helpers.py +98 -0
  181. utils/kabsch.py +29 -0
  182. utils/lookup_table.py +164 -0
  183. utils/metrics.py +50 -0
  184. utils/optuna.py +111 -0
  185. utils/save_mol.py +366 -0
  186. utils/util.py +36 -0
@@ -0,0 +1,386 @@
1
+ #!/usr/bin/env python3
2
+ """Binding-aware pharmacophore match metric for receptor-frame HIF2A conformers.
3
+
4
+ This diagnostic is intentionally separate from RMSD and from the existing
5
+ protein-contact distance metrics. It reports two complementary components:
6
+
7
+ 1. Pose-aware feature-region matching in the crystallographic receptor frame.
8
+ 2. Receptor-independent ligand pharmacophore topology matching.
9
+
10
+ The combined PMS is their unweighted mean. No ligand optimization is performed.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import itertools
17
+ import json
18
+ import math
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import pandas as pd
23
+
24
+ from analyze_hif2a_contact_pharmacophore import (
25
+ candidate_index,
26
+ extract_reference_interactions,
27
+ get_factory,
28
+ heavy_atom_best_rmsd,
29
+ iter_candidate_files,
30
+ ligand_features,
31
+ read_first_mol,
32
+ read_protein_atoms,
33
+ )
34
+
35
+
36
+ FEATURE_REGION_SIGMA_A = {
37
+ "donor": 0.75,
38
+ "acceptor": 0.75,
39
+ "aromatic": 1.00,
40
+ "hydrophobe": 1.50,
41
+ "positive": 1.00,
42
+ "negative": 1.00,
43
+ }
44
+
45
+
46
+ def feature_key(feature: dict) -> str:
47
+ atoms = "-".join(str(int(v)) for v in feature["atom_ids"])
48
+ return f"{feature['family']}:{atoms}"
49
+
50
+
51
+ def build_targets(ref_features: list[dict], ref_interactions: pd.DataFrame) -> list[dict]:
52
+ relevant = set(int(v) for v in ref_interactions["ligand_feature_id"].unique())
53
+ targets = []
54
+ for feature in ref_features:
55
+ if int(feature["feature_id"]) not in relevant:
56
+ continue
57
+ targets.append(
58
+ {
59
+ "key": feature_key(feature),
60
+ "family": str(feature["family"]),
61
+ "atom_ids": tuple(int(v) for v in feature["atom_ids"]),
62
+ "coord": np.asarray(feature["coord"], dtype=float),
63
+ "sigma": float(FEATURE_REGION_SIGMA_A.get(str(feature["family"]), 1.0)),
64
+ }
65
+ )
66
+ return targets
67
+
68
+
69
+ def match_feature(target: dict, generated: list[dict]) -> dict | None:
70
+ same_family = [f for f in generated if str(f["family"]) == target["family"]]
71
+ for feature in same_family:
72
+ if tuple(int(v) for v in feature["atom_ids"]) == target["atom_ids"]:
73
+ return feature
74
+ if not same_family:
75
+ return None
76
+ target_atoms = set(target["atom_ids"])
77
+
78
+ def overlap(feature: dict) -> tuple[float, int]:
79
+ atoms = set(int(v) for v in feature["atom_ids"])
80
+ union = target_atoms | atoms
81
+ jaccard = len(target_atoms & atoms) / len(union) if union else 0.0
82
+ return jaccard, -abs(len(atoms) - len(target_atoms))
83
+
84
+ best = max(same_family, key=overlap)
85
+ return best if overlap(best)[0] > 0.0 else None
86
+
87
+
88
+ def gaussian_score(error: float, scale: float) -> float:
89
+ return float(math.exp(-0.5 * (float(error) / max(float(scale), 1e-8)) ** 2))
90
+
91
+
92
+ def score_candidate(
93
+ targets: list[dict],
94
+ generated: list[dict],
95
+ topology_tolerance: float,
96
+ min_pair_distance: float,
97
+ ) -> dict:
98
+ matched: dict[str, np.ndarray] = {}
99
+ feature_scores: dict[str, float] = {}
100
+ feature_hits: dict[str, float] = {}
101
+ feature_errors: dict[str, float | None] = {}
102
+ for target in targets:
103
+ feature = match_feature(target, generated)
104
+ if feature is None:
105
+ feature_scores[target["key"]] = 0.0
106
+ feature_hits[target["key"]] = 0.0
107
+ feature_errors[target["key"]] = None
108
+ continue
109
+ coord = np.asarray(feature["coord"], dtype=float)
110
+ error = float(np.linalg.norm(coord - target["coord"]))
111
+ matched[target["key"]] = coord
112
+ feature_scores[target["key"]] = gaussian_score(error, target["sigma"])
113
+ feature_hits[target["key"]] = float(error <= target["sigma"])
114
+ feature_errors[target["key"]] = error
115
+
116
+ pair_scores: dict[str, float] = {}
117
+ pair_hits: dict[str, float] = {}
118
+ pair_errors: dict[str, float | None] = {}
119
+ for left, right in itertools.combinations(targets, 2):
120
+ ref_distance = float(np.linalg.norm(left["coord"] - right["coord"]))
121
+ if ref_distance < float(min_pair_distance):
122
+ continue
123
+ key = f"{left['key']}|{right['key']}"
124
+ if left["key"] not in matched or right["key"] not in matched:
125
+ pair_scores[key] = 0.0
126
+ pair_hits[key] = 0.0
127
+ pair_errors[key] = None
128
+ continue
129
+ generated_distance = float(np.linalg.norm(matched[left["key"]] - matched[right["key"]]))
130
+ error = abs(generated_distance - ref_distance)
131
+ pair_scores[key] = gaussian_score(error, topology_tolerance)
132
+ pair_hits[key] = float(error <= topology_tolerance)
133
+ pair_errors[key] = error
134
+
135
+ region_score = float(np.mean(list(feature_scores.values()))) if feature_scores else np.nan
136
+ region_coverage = float(np.mean(list(feature_hits.values()))) if feature_hits else np.nan
137
+ topology_score = float(np.mean(list(pair_scores.values()))) if pair_scores else np.nan
138
+ topology_coverage = float(np.mean(list(pair_hits.values()))) if pair_hits else np.nan
139
+ valid_components = [v for v in (region_score, topology_score) if np.isfinite(v)]
140
+ pms = float(np.mean(valid_components)) if valid_components else np.nan
141
+ return {
142
+ "n_target_features": len(targets),
143
+ "n_topology_constraints": len(pair_scores),
144
+ "pose_region_match_score": region_score,
145
+ "pose_region_coverage": region_coverage,
146
+ "intrinsic_topology_match_score": topology_score,
147
+ "intrinsic_topology_coverage": topology_coverage,
148
+ "pharmacophore_match_score": pms,
149
+ "feature_scores_json": json.dumps(feature_scores, sort_keys=True),
150
+ "feature_errors_json": json.dumps(feature_errors, sort_keys=True),
151
+ "pair_scores_json": json.dumps(pair_scores, sort_keys=True),
152
+ "pair_errors_json": json.dumps(pair_errors, sort_keys=True),
153
+ }
154
+
155
+
156
+ def summarize_best(candidate_df: pd.DataFrame) -> pd.DataFrame:
157
+ rows = []
158
+ for _, group in candidate_df.groupby(["ligand_id", "method"], sort=True):
159
+ rows.append(
160
+ group.sort_values(
161
+ ["pharmacophore_match_score", "pose_region_match_score", "intrinsic_topology_match_score", "atom_rmsd"],
162
+ ascending=[False, False, False, True],
163
+ na_position="last",
164
+ ).iloc[0]
165
+ )
166
+ return pd.DataFrame(rows).reset_index(drop=True)
167
+
168
+
169
+ def mean_max_json(rows: pd.Series) -> float:
170
+ decoded = [json.loads(value) for value in rows]
171
+ keys = sorted({key for item in decoded for key in item})
172
+ if not keys:
173
+ return np.nan
174
+ return float(np.mean([max(float(item.get(key, 0.0)) for item in decoded) for key in keys]))
175
+
176
+
177
+ def summarize_ensembles(candidate_df: pd.DataFrame, budgets: list[int], recovery_threshold: float) -> pd.DataFrame:
178
+ rows = []
179
+ for (ligand_id, method), group in candidate_df.groupby(["ligand_id", "method"], sort=True):
180
+ group = group.sort_values("candidate_index")
181
+ for budget in budgets:
182
+ selected = group.head(int(budget))
183
+ if selected.empty:
184
+ continue
185
+ region_union = mean_max_json(selected["feature_scores_json"])
186
+ topology_union = mean_max_json(selected["pair_scores_json"])
187
+ union_components = [v for v in (region_union, topology_union) if np.isfinite(v)]
188
+ ensemble_pms = float(np.mean(union_components)) if union_components else np.nan
189
+ best_pms = float(selected["pharmacophore_match_score"].max())
190
+ rows.append(
191
+ {
192
+ "ligand_id": ligand_id,
193
+ "method": method,
194
+ "K": int(budget),
195
+ "n_candidates_available": int(len(group)),
196
+ "n_candidates_used": int(len(selected)),
197
+ "ensemble_pose_region_match": region_union,
198
+ "ensemble_intrinsic_topology_match": topology_union,
199
+ "ensemble_pharmacophore_match_score": ensemble_pms,
200
+ "best_candidate_pharmacophore_match_score": best_pms,
201
+ "topk_pharmacophore_recovery": float(best_pms >= float(recovery_threshold)),
202
+ }
203
+ )
204
+ return pd.DataFrame(rows)
205
+
206
+
207
+ def aggregate(df: pd.DataFrame, keys: list[str], metrics: list[str]) -> pd.DataFrame:
208
+ named = {"n_ligands": ("ligand_id", "count")}
209
+ for metric in metrics:
210
+ named[f"{metric}_mean"] = (metric, "mean")
211
+ named[f"{metric}_median"] = (metric, "median")
212
+ return df.groupby(keys, sort=True).agg(**named).reset_index()
213
+
214
+
215
+ def correlation_summary(candidate_df: pd.DataFrame) -> pd.DataFrame:
216
+ rows = []
217
+ for method, group in candidate_df.groupby("method", sort=True):
218
+ valid = group[["atom_rmsd", "pharmacophore_match_score"]].dropna()
219
+ rows.append(
220
+ {
221
+ "method": method,
222
+ "n_candidates": int(len(valid)),
223
+ "spearman_pms_vs_atom_rmsd": float(valid.corr(method="spearman").iloc[0, 1]) if len(valid) > 2 else np.nan,
224
+ }
225
+ )
226
+ return pd.DataFrame(rows)
227
+
228
+
229
+ def disagreement_summary(candidate_df: pd.DataFrame, high_match_threshold: float = 0.8, high_rmsd_threshold: float = 1.5) -> pd.DataFrame:
230
+ rows = []
231
+ for method, group in candidate_df.groupby("method", sort=True):
232
+ within_ligand_correlations = []
233
+ same_best = 0
234
+ high_match_count = 0
235
+ high_match_high_rmsd_count = 0
236
+ n_ligands = 0
237
+ for _, ligand_group in group.groupby("ligand_id", sort=True):
238
+ valid = ligand_group[["atom_rmsd", "pharmacophore_match_score"]].dropna()
239
+ if len(valid) > 2:
240
+ within_ligand_correlations.append(float(valid.corr(method="spearman").iloc[0, 1]))
241
+ same_best += int(
242
+ ligand_group["pharmacophore_match_score"].idxmax()
243
+ == ligand_group["atom_rmsd"].idxmin()
244
+ )
245
+ high = ligand_group["pharmacophore_match_score"] >= float(high_match_threshold)
246
+ high_match_count += int(high.sum())
247
+ high_match_high_rmsd_count += int((high & (ligand_group["atom_rmsd"] > float(high_rmsd_threshold))).sum())
248
+ n_ligands += 1
249
+ rows.append(
250
+ {
251
+ "method": method,
252
+ "n_ligands": n_ligands,
253
+ "mean_within_ligand_spearman_pms_vs_rmsd": float(np.mean(within_ligand_correlations)),
254
+ "same_best_candidate_by_pms_and_rmsd": same_best,
255
+ "high_pms_candidates": high_match_count,
256
+ "high_pms_high_rmsd_candidates": high_match_high_rmsd_count,
257
+ "high_pms_high_rmsd_fraction": high_match_high_rmsd_count / max(1, high_match_count),
258
+ }
259
+ )
260
+ return pd.DataFrame(rows)
261
+
262
+
263
+ def main() -> None:
264
+ parser = argparse.ArgumentParser(description="HIF2A binding-aware pharmacophore match metric.")
265
+ parser.add_argument("--manifest", default="outputs/docking/hif2a_conformers/docking_manifest_manimol_xtb.csv")
266
+ parser.add_argument("--placed_root", default="outputs/docking/hif2a_preorganized_vina_score_only_xtb")
267
+ parser.add_argument("--output_dir", default="outputs/docking/hif2a_pharmacophore_match_metric")
268
+ parser.add_argument("--methods", default="etkdg,manimol")
269
+ parser.add_argument("--ensemble_budgets", default="1,5,10,20")
270
+ parser.add_argument("--topology_tolerance", type=float, default=1.5)
271
+ parser.add_argument("--min_pair_distance", type=float, default=1.0)
272
+ parser.add_argument("--recovery_threshold", type=float, default=0.8)
273
+ parser.add_argument("--max_ligands", type=int, default=0)
274
+ args, _ = parser.parse_known_args()
275
+
276
+ manifest = pd.read_csv(args.manifest)
277
+ if args.max_ligands > 0:
278
+ manifest = manifest.head(args.max_ligands)
279
+ methods = [value.strip().lower() for value in args.methods.split(",") if value.strip()]
280
+ budgets = sorted({int(value) for value in args.ensemble_budgets.split(",") if value.strip()})
281
+ output_dir = Path(args.output_dir)
282
+ output_dir.mkdir(parents=True, exist_ok=True)
283
+ factory = get_factory()
284
+ reference_rows = []
285
+ candidate_rows = []
286
+
287
+ for _, entry in manifest.iterrows():
288
+ ligand_id = str(entry["complex_id"])
289
+ ref_path = Path(str(entry.get("crystal_ligand_sdf", entry["ligand_sdf"])))
290
+ receptor_path = Path(str(entry["receptor_pdb"]))
291
+ ref_mol = read_first_mol(ref_path)
292
+ if ref_mol is None or not receptor_path.exists():
293
+ continue
294
+ ref_features = ligand_features(ref_mol, factory)
295
+ interactions = extract_reference_interactions(ligand_id, ref_features, read_protein_atoms(receptor_path))
296
+ if interactions.empty:
297
+ continue
298
+ targets = build_targets(ref_features, interactions)
299
+ for target in targets:
300
+ reference_rows.append(
301
+ {
302
+ "ligand_id": ligand_id,
303
+ "feature_key": target["key"],
304
+ "family": target["family"],
305
+ "atom_ids": ";".join(map(str, target["atom_ids"])),
306
+ "x": target["coord"][0],
307
+ "y": target["coord"][1],
308
+ "z": target["coord"][2],
309
+ "region_sigma_A": target["sigma"],
310
+ }
311
+ )
312
+ for method in methods:
313
+ for path in iter_candidate_files(Path(args.placed_root), ligand_id, method):
314
+ mol = read_first_mol(path)
315
+ if mol is None:
316
+ continue
317
+ scores = score_candidate(
318
+ targets,
319
+ ligand_features(mol, factory),
320
+ topology_tolerance=args.topology_tolerance,
321
+ min_pair_distance=args.min_pair_distance,
322
+ )
323
+ candidate_rows.append(
324
+ {
325
+ "ligand_id": ligand_id,
326
+ "method": method,
327
+ "candidate_index": candidate_index(path),
328
+ "candidate_file": str(path),
329
+ "atom_rmsd": heavy_atom_best_rmsd(ref_mol, mol),
330
+ **scores,
331
+ }
332
+ )
333
+
334
+ if not candidate_rows:
335
+ raise RuntimeError("No receptor-frame candidate conformers were found.")
336
+ reference_df = pd.DataFrame(reference_rows)
337
+ candidate_df = pd.DataFrame(candidate_rows)
338
+ best_df = summarize_best(candidate_df)
339
+ ensemble_df = summarize_ensembles(candidate_df, budgets, args.recovery_threshold)
340
+ best_summary = aggregate(
341
+ best_df,
342
+ ["method"],
343
+ ["pose_region_match_score", "intrinsic_topology_match_score", "pharmacophore_match_score", "atom_rmsd"],
344
+ )
345
+ ensemble_summary = aggregate(
346
+ ensemble_df,
347
+ ["method", "K"],
348
+ ["ensemble_pose_region_match", "ensemble_intrinsic_topology_match", "ensemble_pharmacophore_match_score", "best_candidate_pharmacophore_match_score", "topk_pharmacophore_recovery"],
349
+ )
350
+ correlation_df = correlation_summary(candidate_df)
351
+ disagreement_df = disagreement_summary(candidate_df)
352
+
353
+ reference_df.to_csv(output_dir / "reference_pharmacophore_features.csv", index=False)
354
+ candidate_df.to_csv(output_dir / "candidate_pharmacophore_match_scores.csv", index=False)
355
+ best_df.to_csv(output_dir / "best_pharmacophore_match_per_ligand.csv", index=False)
356
+ best_summary.to_csv(output_dir / "pharmacophore_match_summary_by_method.csv", index=False)
357
+ ensemble_df.to_csv(output_dir / "ensemble_pharmacophore_match_per_ligand.csv", index=False)
358
+ ensemble_summary.to_csv(output_dir / "ensemble_pharmacophore_match_summary.csv", index=False)
359
+ correlation_df.to_csv(output_dir / "pharmacophore_match_rmsd_correlation.csv", index=False)
360
+ disagreement_df.to_csv(output_dir / "pharmacophore_match_rmsd_disagreement.csv", index=False)
361
+ config = {
362
+ "metric_name": "Binding-aware Pharmacophore Match Score (PMS)",
363
+ "manifest": args.manifest,
364
+ "placed_root": args.placed_root,
365
+ "methods": methods,
366
+ "feature_region_sigma_A": FEATURE_REGION_SIGMA_A,
367
+ "topology_tolerance_A": args.topology_tolerance,
368
+ "minimum_reference_feature_pair_distance_A": args.min_pair_distance,
369
+ "combined_score": "0.5 * pose_region_match_score + 0.5 * intrinsic_topology_match_score",
370
+ "missing_feature_policy": "zero score",
371
+ "candidate_selection": "maximum PMS per ligand and method",
372
+ "ensemble_budgets": budgets,
373
+ "topk_recovery_threshold": args.recovery_threshold,
374
+ "additional_ligand_optimization": False,
375
+ }
376
+ (output_dir / "pharmacophore_match_metric_config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
377
+
378
+ print(best_summary.to_string(index=False))
379
+ print(ensemble_summary.to_string(index=False))
380
+ print(correlation_df.to_string(index=False))
381
+ print(disagreement_df.to_string(index=False))
382
+ print(f"Saved outputs under {output_dir}")
383
+
384
+
385
+ if __name__ == "__main__":
386
+ main()
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env python3
2
+ """Compare candidate pools produced by probability-graph controls.
3
+
4
+ The analysis is reference-free: it measures whether interventions on P change
5
+ the generated torsion distributions before any library selector is applied.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import csv
12
+ import json
13
+ import math
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import torch
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
21
+ import infer_base_conformers
22
+
23
+
24
+ def parse_args():
25
+ parser = argparse.ArgumentParser(description=__doc__)
26
+ parser.add_argument("--control", action="append", required=True, metavar="NAME=POOL_PT")
27
+ parser.add_argument("--normal", default="normal")
28
+ parser.add_argument("--max_molecules", type=int, default=0)
29
+ parser.add_argument("--bins", type=int, default=24)
30
+ parser.add_argument("--output_prefix", required=True)
31
+ return parser.parse_args()
32
+
33
+
34
+ def load_controls(items, limit):
35
+ result = {}
36
+ for item in items:
37
+ name, path = item.split("=", 1)
38
+ payload = torch.load(path, map_location="cpu", weights_only=False)
39
+ records = list(payload["records"])
40
+ if limit > 0:
41
+ records = records[:limit]
42
+ result[name] = {str(row["mol_id"]): row for row in records}
43
+ return result
44
+
45
+
46
+ def torsion_angles(pool, mol):
47
+ signature = infer_base_conformers.torsion_signature_matrix(pool.float(), mol)
48
+ if signature is None:
49
+ return None, None
50
+ width = signature.size(1) // 2
51
+ angles = torch.atan2(signature[:, :width], signature[:, width:])
52
+ return signature.float(), angles.float()
53
+
54
+
55
+ def js_divergence(first, second, bins):
56
+ values = []
57
+ edges = torch.linspace(-math.pi, math.pi, bins + 1)
58
+ for index in range(min(first.size(1), second.size(1))):
59
+ left = torch.histogram(first[:, index], bins=edges).hist.float() + 1e-8
60
+ right = torch.histogram(second[:, index], bins=edges).hist.float() + 1e-8
61
+ left /= left.sum()
62
+ right /= right.sum()
63
+ middle = 0.5 * (left + right)
64
+ value = 0.5 * torch.sum(left * torch.log(left / middle))
65
+ value += 0.5 * torch.sum(right * torch.log(right / middle))
66
+ values.append(float(value))
67
+ return float(np.mean(values)) if values else float("nan")
68
+
69
+
70
+ def pairwise_summary(signature):
71
+ if signature.size(0) < 2:
72
+ return 0.0
73
+ return float(torch.pdist(signature).mean())
74
+
75
+
76
+ def compare(normal_record, control_record, bins):
77
+ normal_pool = normal_record["raw_pool"].float()
78
+ control_pool = control_record["raw_pool"].float()
79
+ normal_sig, normal_angles = torsion_angles(normal_pool, normal_record.get("mol"))
80
+ control_sig, control_angles = torsion_angles(control_pool, control_record.get("mol"))
81
+ if normal_sig is None or control_sig is None or normal_sig.size(1) != control_sig.size(1):
82
+ return None
83
+
84
+ cross = torch.cdist(normal_sig, control_sig) / math.sqrt(normal_sig.size(1))
85
+ nearest = cross.min(dim=1).values
86
+ same_count = min(normal_sig.size(0), control_sig.size(0))
87
+ same_index = torch.sqrt(
88
+ ((normal_sig[:same_count] - control_sig[:same_count]) ** 2).mean(dim=1)
89
+ )
90
+ normal_p = normal_record.get("pglobal")
91
+ control_p = control_record.get("pglobal")
92
+ p_rmse = float("nan")
93
+ if torch.is_tensor(normal_p) and torch.is_tensor(control_p) and normal_p.shape == control_p.shape:
94
+ p_rmse = float(torch.sqrt(torch.mean((normal_p.float() - control_p.float()) ** 2)))
95
+ return {
96
+ "normal_pool_size": int(normal_pool.size(0)),
97
+ "control_pool_size": int(control_pool.size(0)),
98
+ "torsion_count": int(normal_angles.size(1)),
99
+ "p_map_rmse": p_rmse,
100
+ "same_index_torsion_distance": float(same_index.mean()),
101
+ "nearest_normal_to_control_mean": float(nearest.mean()),
102
+ "nearest_normal_to_control_median": float(nearest.median()),
103
+ "fraction_nearest_lt_0p01": float((nearest < 0.01).float().mean()),
104
+ "fraction_nearest_lt_0p05": float((nearest < 0.05).float().mean()),
105
+ "fraction_nearest_lt_0p10": float((nearest < 0.10).float().mean()),
106
+ "torsion_histogram_js": js_divergence(normal_angles, control_angles, bins),
107
+ "normal_within_pool_diversity": pairwise_summary(normal_sig),
108
+ "control_within_pool_diversity": pairwise_summary(control_sig),
109
+ }
110
+
111
+
112
+ def main():
113
+ args = parse_args()
114
+ controls = load_controls(args.control, args.max_molecules)
115
+ if args.normal not in controls:
116
+ raise ValueError(f"normal control {args.normal!r} was not supplied")
117
+ common = set.intersection(*(set(records) for records in controls.values()))
118
+ rows = []
119
+ for mol_id in sorted(common, key=lambda value: int(value)):
120
+ normal_record = controls[args.normal][mol_id]
121
+ for name, records in controls.items():
122
+ if name == args.normal:
123
+ continue
124
+ values = compare(normal_record, records[mol_id], args.bins)
125
+ if values is not None:
126
+ rows.append({"mol_id": mol_id, "control": name, **values})
127
+
128
+ prefix = Path(args.output_prefix)
129
+ prefix.parent.mkdir(parents=True, exist_ok=True)
130
+ csv_path = prefix.with_name(prefix.name + "_per_molecule.csv")
131
+ with csv_path.open("w", newline="") as handle:
132
+ writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
133
+ writer.writeheader()
134
+ writer.writerows(rows)
135
+
136
+ summary = {"normal": args.normal, "common_molecules": len(common), "comparisons": {}}
137
+ numeric = [key for key in rows[0] if key not in {"mol_id", "control"}]
138
+ for name in sorted(set(row["control"] for row in rows)):
139
+ subset = [row for row in rows if row["control"] == name]
140
+ summary["comparisons"][name] = {
141
+ key: {
142
+ "mean": float(np.nanmean([row[key] for row in subset])),
143
+ "median": float(np.nanmedian([row[key] for row in subset])),
144
+ }
145
+ for key in numeric
146
+ }
147
+ json_path = prefix.with_name(prefix.name + "_summary.json")
148
+ json_path.write_text(json.dumps(summary, indent=2) + "\n")
149
+ print(json.dumps(summary, indent=2))
150
+ print(f"Saved {csv_path} and {json_path}")
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env python
2
+ """Diagnose scaffold-to-basin correspondence without changing training."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import math
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ import torch
13
+ from rdkit import Chem
14
+
15
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
16
+ from geomanimol.data import load_molecule_groups
17
+ from geomanimol.geometry import DynamicGeometryMemory
18
+ from geomanimol.residual import etkdg_scaffolds
19
+ from geomanimol.torsion_residual import TorsionResidualGeoManimol, get_torsions, torsion_defs
20
+ from scripts.evaluate_geomanimol import kabsch_rmsd
21
+
22
+
23
+ def scaffold_torsions(mol, scaffold, defs):
24
+ work = Chem.Mol(mol)
25
+ work.RemoveAllConformers()
26
+ conf = Chem.Conformer(scaffold.shape[0])
27
+ for i, xyz in enumerate(scaffold.tolist()):
28
+ conf.SetAtomPosition(i, xyz)
29
+ work.AddConformer(conf)
30
+ return get_torsions(work, defs)
31
+
32
+
33
+ def main():
34
+ p = argparse.ArgumentParser()
35
+ p.add_argument("--test", default="data/geom_drugs_geomol_top20/geom_drugs_geomol_top20_debug_val.pt")
36
+ p.add_argument("--checkpoint", default="outputs/geomanimol/torsion_soft_assignment_debug_checkpoint.pt")
37
+ p.add_argument("--molecules", type=int, default=20)
38
+ p.add_argument("--scaffolds", type=int, default=10)
39
+ p.add_argument("--temperature", type=float, default=1.0)
40
+ p.add_argument("--output", default="outputs/geomanimol/scaffold_basin_diagnostic.json")
41
+ args = p.parse_args()
42
+ molecules = load_molecule_groups(args.test, args.molecules)
43
+ memory = DynamicGeometryMemory(n_modes=3, manifold_dim=8); memory.initialize(molecules)
44
+ ckpt = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
45
+ cfg = ckpt["args"]
46
+ model = TorsionResidualGeoManimol(cfg["node_dim"], cfg["n_basins"], cfg["manifold_dim"], cfg["diffusion_steps"])
47
+ model.load_state_dict(ckpt["model"]); model.eval()
48
+ rows, entropies, diversities = [], [], []
49
+ for mol in molecules:
50
+ entry = memory.get(mol["mol_id"]); labels = entry["labels"]
51
+ ss = etkdg_scaffolds(mol["mol"], args.scaffolds, 30300 + mol["mol_id"] * 100)
52
+ defs = torsion_defs(mol["mol"]); tors = []
53
+ for sid, scaffold in enumerate(ss):
54
+ basin_dist = []
55
+ for k in range(cfg["n_basins"]):
56
+ members = mol["conformations"][labels == k] if (labels == k).any() else mol["conformations"]
57
+ basin_dist.append(min(kabsch_rmsd(scaffold, ref) for ref in members))
58
+ p_true = torch.softmax(-torch.tensor(basin_dist) / args.temperature, dim=0)
59
+ q_pred = model.mode_weights(mol, scaffold).cpu()
60
+ entropy = float(-(q_pred * q_pred.clamp_min(1e-8).log()).sum())
61
+ rows.append({"mol_id": mol["mol_id"], "scaffold_id": sid,
62
+ "true_distances": basin_dist, "true_assignment": p_true.tolist(),
63
+ "predicted_assignment": q_pred.tolist(), "predicted_entropy": entropy})
64
+ entropies.append(entropy)
65
+ if defs:
66
+ tors.append(scaffold_torsions(mol["mol"], scaffold, defs))
67
+ if len(tors) > 1:
68
+ pair = []
69
+ for i in range(len(tors)):
70
+ for j in range(i):
71
+ pair.append(float(torch.atan2(torch.sin(tors[i] - tors[j]), torch.cos(tors[i] - tors[j])).abs().mean()))
72
+ diversities.append(sum(pair) / len(pair))
73
+ result = {"molecules": len(molecules), "scaffolds_per_molecule": args.scaffolds,
74
+ "mean_predicted_basin_entropy": sum(entropies) / max(1, len(entropies)),
75
+ "mean_scaffold_torsion_distance_rad": sum(diversities) / max(1, len(diversities)),
76
+ "rows": rows}
77
+ out = Path(args.output); out.parent.mkdir(parents=True, exist_ok=True); out.write_text(json.dumps(result, indent=2))
78
+ print(json.dumps({k: v for k, v in result.items() if k != "rows"}, indent=2))
79
+ print(f"Saved: {out}")
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()