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,155 @@
1
+ #!/usr/bin/env python3
2
+ """GPU-batched post-hoc PMS evaluation for PDBbind candidate pools."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import math
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ import torch
13
+
14
+
15
+ REGION_SIGMA = {"HBD": 0.75, "HBA": 0.75, "Aromatic": 1.0, "Hydrophobic": 1.5}
16
+ TOPOLOGY_TOLERANCE = 1.5
17
+ MIN_PAIR_DISTANCE = 1.0
18
+
19
+
20
+ def parse_args():
21
+ p = argparse.ArgumentParser()
22
+ p.add_argument("--pool", nargs="+", required=True)
23
+ p.add_argument("--audit", required=True)
24
+ p.add_argument("--raw-root", required=True)
25
+ p.add_argument("--out", required=True)
26
+ p.add_argument("--device", default="cuda")
27
+ p.add_argument("--budgets", default="1,5,10,20,50")
28
+ return p.parse_args()
29
+
30
+
31
+ def score_record(record, target, budgets, device):
32
+ features = target["features"]
33
+ if len(features) < 1:
34
+ return []
35
+ coords = torch.as_tensor(record["raw_pool"], dtype=torch.float32, device=device)
36
+ reference = torch.as_tensor(record["ref_confs"][0], dtype=torch.float32, device=device)
37
+ mask = record.get("heavy_mask")
38
+ if mask is None:
39
+ mask = torch.ones(reference.shape[0], dtype=torch.bool, device=device)
40
+ else:
41
+ mask = torch.as_tensor(mask, dtype=torch.bool, device=device).reshape(-1)
42
+ # Post-hoc receptor-frame alignment is required for S_region. The
43
+ # alignment uses the same atom order as the generated molecule and is
44
+ # carried out in a batched Kabsch operation on the selected device.
45
+ x = coords[:, mask, :]
46
+ y = reference[mask, :].expand(x.shape[0], -1, -1)
47
+ xc = x - x.mean(dim=1, keepdim=True)
48
+ yc = y - y.mean(dim=1, keepdim=True)
49
+ u, _, vh = torch.linalg.svd(xc.transpose(1, 2).matmul(yc))
50
+ rot = u.matmul(vh)
51
+ flip = torch.det(rot) < 0
52
+ if bool(flip.any()):
53
+ vh = vh.clone()
54
+ vh[flip, -1, :] *= -1.0
55
+ rot = u.matmul(vh)
56
+ coords = (coords - x.mean(dim=1, keepdim=True)).matmul(rot) + reference[mask, :].mean(dim=0)
57
+ feature_xyz = []
58
+ families = []
59
+ for feat in features:
60
+ ids = torch.tensor(feat["atom_ids"], dtype=torch.long, device=device)
61
+ feature_xyz.append(coords[:, ids, :].mean(dim=1))
62
+ families.append(feat["family"])
63
+ xyz = torch.stack(feature_xyz, dim=1)
64
+ ref = torch.tensor([feat["coord"] for feat in features], dtype=torch.float32, device=device)
65
+ sigma = torch.tensor([REGION_SIGMA.get(f, 1.0) for f in families], dtype=torch.float32, device=device)
66
+ region_err = torch.linalg.vector_norm(xyz - ref[None, :, :], dim=-1)
67
+ region_score = torch.exp(-0.5 * (region_err / sigma[None, :]) ** 2).mean(dim=1)
68
+ region_hit = (region_err <= sigma[None, :]).float().mean(dim=1)
69
+
70
+ pair_i, pair_j, pair_tol = [], [], []
71
+ for i in range(len(features)):
72
+ for j in range(i + 1, len(features)):
73
+ dist = float(torch.linalg.vector_norm(ref[i] - ref[j]).item())
74
+ if dist >= MIN_PAIR_DISTANCE:
75
+ pair_i.append(i); pair_j.append(j); pair_tol.append(TOPOLOGY_TOLERANCE)
76
+ if pair_i:
77
+ generated_dist = torch.linalg.vector_norm(xyz[:, pair_i, :] - xyz[:, pair_j, :], dim=-1)
78
+ reference_dist = torch.linalg.vector_norm(ref[pair_i] - ref[pair_j], dim=-1)
79
+ topology_err = torch.abs(generated_dist - reference_dist[None, :])
80
+ topology_score = torch.exp(-0.5 * (topology_err / TOPOLOGY_TOLERANCE) ** 2).mean(dim=1)
81
+ topology_hit = (topology_err <= TOPOLOGY_TOLERANCE).float().mean(dim=1)
82
+ else:
83
+ topology_score = torch.full_like(region_score, float("nan"))
84
+ topology_hit = torch.full_like(region_score, float("nan"))
85
+ pms = torch.nanmean(torch.stack([region_score, topology_score], dim=1), dim=1)
86
+ rows = []
87
+ for k in budgets:
88
+ n = min(int(k), int(pms.numel()))
89
+ top = int(torch.argmax(pms[:n]).item())
90
+ rows.append({
91
+ "pdbid": str(record.get("mol_id", record.get("mol_key", ""))),
92
+ "K": int(k),
93
+ "n_candidates": n,
94
+ "best_candidate_index": top,
95
+ "S_region": float(region_score[top].item()),
96
+ "S_topology": float(topology_score[top].item()),
97
+ "PMS": float(pms[top].item()),
98
+ "feature_recall": float(region_hit[top].item()),
99
+ "topology_recall": float(topology_hit[top].item()),
100
+ "n_features": len(features),
101
+ "n_pairs": len(pair_i),
102
+ })
103
+ return rows
104
+
105
+
106
+ def main():
107
+ args = parse_args()
108
+ budgets = [int(x) for x in args.budgets.split(",") if x.strip()]
109
+ audit = pd.read_csv(args.audit).set_index("pdbid")
110
+ raw_records = torch.load(Path(args.raw_root) / "pdbbind_test.pt", map_location="cpu", weights_only=False)
111
+ index_to_pdbid = {int(i): str(rec["pdbid"]) for i, rec in enumerate(raw_records)}
112
+ targets = {}
113
+ for pdbid, row in audit.iterrows():
114
+ features = json.loads(row["features_json"])
115
+ contacts = json.loads(row["contacts_json"])
116
+ contact_atoms = {int(a) for c in contacts for a in c.get("atom_ids", [])}
117
+ selected = [f for f in features if contact_atoms.intersection(int(a) for a in f["atom_ids"])]
118
+ if selected:
119
+ targets[str(pdbid)] = {"features": selected}
120
+ device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu")
121
+ all_rows = []
122
+ for pool_path in args.pool:
123
+ payload = torch.load(pool_path, map_location="cpu", weights_only=False)
124
+ records = payload["records"] if isinstance(payload, dict) and "records" in payload else payload
125
+ # The inference CLI stores the same checkpoint method label in both
126
+ # control pools; use the audited pool directory as the comparison
127
+ # label so MANIMOL and ETKDG remain distinct.
128
+ parent_name = Path(pool_path).parent.name.lower()
129
+ method = "ETKDG" if "etkdg" in parent_name else "MANIMOL"
130
+ for record in records:
131
+ pdbid = index_to_pdbid.get(int(record.get("mol_id", -1)), "")
132
+ target = targets.get(pdbid)
133
+ if target is None:
134
+ continue
135
+ for row in score_record(record, target, budgets, device):
136
+ row["method"] = method
137
+ all_rows.append(row)
138
+ frame = pd.DataFrame(all_rows)
139
+ out = Path(args.out)
140
+ out.parent.mkdir(parents=True, exist_ok=True)
141
+ frame.to_csv(out, index=False)
142
+ summary = frame.groupby(["method", "K"], as_index=False).agg(
143
+ n_complexes=("pdbid", "nunique"),
144
+ S_region_mean=("S_region", "mean"), S_region_median=("S_region", "median"),
145
+ S_topology_mean=("S_topology", "mean"), S_topology_median=("S_topology", "median"),
146
+ PMS_mean=("PMS", "mean"), PMS_median=("PMS", "median"),
147
+ feature_recall_mean=("feature_recall", "mean"), topology_recall_mean=("topology_recall", "mean"),
148
+ )
149
+ summary.to_csv(out.with_name(out.stem + "_summary.csv"), index=False)
150
+ print(summary.to_string(index=False))
151
+ print(json.dumps({"device": str(device), "audited_targets": len(targets), "rows": len(frame), "output": str(out)}, indent=2))
152
+
153
+
154
+ if __name__ == "__main__":
155
+ main()
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env python3
2
+ """Evaluate saved Platinum bound-pose candidate pools under frozen fixed-K endpoints."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ import torch
11
+
12
+ from external_validation_metrics import complete_expected_units, evaluate_bound_pose_library, threshold_label
13
+
14
+
15
+ def parse_csv_numbers(text, cast=float):
16
+ return [cast(value.strip()) for value in text.split(",") if value.strip()]
17
+
18
+
19
+ def parse_args():
20
+ parser = argparse.ArgumentParser()
21
+ parser.add_argument("--pool", required=True)
22
+ parser.add_argument("--out", required=True)
23
+ parser.add_argument("--method", required=True)
24
+ parser.add_argument("--seed", required=True, type=int)
25
+ parser.add_argument("--budgets", default="1,5,10,20,50")
26
+ parser.add_argument("--thresholds", default="0.5,1.0,1.5,2.0")
27
+ parser.add_argument("--max-matches", type=int, default=10000)
28
+ parser.add_argument("--expected-ids", help="Optional CSV or one-ID-per-line eligibility manifest")
29
+ return parser.parse_args()
30
+
31
+
32
+ def read_expected_ids(path):
33
+ frame = pd.read_csv(path)
34
+ for column in ("molecule_id", "source_id", "id"):
35
+ if column in frame.columns:
36
+ return frame[column].astype(str).tolist()
37
+ if frame.shape[1] == 1:
38
+ return frame.iloc[:, 0].astype(str).tolist()
39
+ raise ValueError("expected-ID manifest needs molecule_id, source_id, id, or one column")
40
+
41
+
42
+ def failed_rows(record, method, seed, budgets, thresholds, reason):
43
+ rows = []
44
+ for budget in budgets:
45
+ row = {
46
+ "method": method,
47
+ "seed": seed,
48
+ "molecule_id": record.get("mol_id", record.get("source_id", "")),
49
+ "molecule_key": record.get("mol_key", ""),
50
+ "K": budget,
51
+ "n_retained_available": 0,
52
+ "generation_success": 0,
53
+ "min_rmsd_A": np.nan,
54
+ "status": reason,
55
+ }
56
+ row.update({threshold_label(value): 0 for value in thresholds})
57
+ rows.append(row)
58
+ return rows
59
+
60
+
61
+ def main():
62
+ args = parse_args()
63
+ budgets = parse_csv_numbers(args.budgets, int)
64
+ thresholds = parse_csv_numbers(args.thresholds, float)
65
+ payload = torch.load(args.pool, map_location="cpu", weights_only=False)
66
+ records = payload["records"] if isinstance(payload, dict) else payload
67
+ rows = []
68
+ for record in records:
69
+ base = {
70
+ "method": args.method,
71
+ "seed": args.seed,
72
+ "molecule_id": record.get("mol_id", record.get("source_id", "")),
73
+ "molecule_key": record.get("mol_key", ""),
74
+ }
75
+ try:
76
+ candidates = record.get("selected_pool", record.get("raw_pool"))
77
+ references = record.get("ref_confs")
78
+ if candidates is None or references is None or len(references) != 1:
79
+ raise ValueError("missing candidate pool or non-singleton bound reference")
80
+ evaluated = evaluate_bound_pose_library(
81
+ record["mol"], candidates, references[0], budgets, thresholds, args.max_matches
82
+ )
83
+ for row in evaluated:
84
+ rows.append({**base, **row, "status": "ok"})
85
+ except Exception as exc:
86
+ rows.extend(failed_rows(record, args.method, args.seed, budgets, thresholds, type(exc).__name__))
87
+
88
+ if args.expected_ids:
89
+ rows = complete_expected_units(
90
+ rows,
91
+ read_expected_ids(args.expected_ids),
92
+ budgets,
93
+ thresholds,
94
+ defaults={"method": args.method, "seed": args.seed, "molecule_key": ""},
95
+ )
96
+ frame = pd.DataFrame(rows)
97
+ out = Path(args.out)
98
+ out.parent.mkdir(parents=True, exist_ok=True)
99
+ frame.to_csv(out, index=False)
100
+ summary_cols = [threshold_label(value) for value in thresholds]
101
+ summary = frame.groupby(["method", "K"], dropna=False).agg(
102
+ n_total=("molecule_id", "size"),
103
+ n_generated=("generation_success", "sum"),
104
+ generation_success_rate=("generation_success", "mean"),
105
+ mean_min_rmsd_A=("min_rmsd_A", "mean"),
106
+ median_min_rmsd_A=("min_rmsd_A", "median"),
107
+ **{column: (column, "mean") for column in summary_cols},
108
+ ).reset_index()
109
+ summary.to_csv(out.with_name(out.stem + "_summary.csv"), index=False)
110
+ print(summary.to_string(index=False))
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env python3
2
+ """Evaluate a saved Platinum candidate pool at fixed retained-library K."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ import torch
11
+ from rdkit import Chem
12
+ from rdkit.Chem import rdMolAlign
13
+ from rdkit.Geometry import Point3D
14
+
15
+
16
+ def with_coords(mol, coords):
17
+ out = Chem.Mol(mol)
18
+ out.RemoveAllConformers()
19
+ arr = torch.as_tensor(coords).detach().cpu().numpy()
20
+ conf = Chem.Conformer(int(arr.shape[0]))
21
+ for atom_idx, xyz in enumerate(arr):
22
+ conf.SetAtomPosition(atom_idx, Point3D(float(xyz[0]), float(xyz[1]), float(xyz[2])))
23
+ out.AddConformer(conf, assignId=True)
24
+ return out
25
+
26
+
27
+ def rmsd_matrix(pool, refs, mol, heavy_mask=None, max_matches=10000):
28
+ if heavy_mask is not None:
29
+ mask = torch.as_tensor(heavy_mask).bool().cpu().numpy()
30
+ pool = [torch.as_tensor(x)[mask] for x in pool]
31
+ refs = [torch.as_tensor(x)[mask] for x in refs]
32
+ mol = Chem.RemoveHs(Chem.Mol(mol), sanitize=False)
33
+ rows = []
34
+ for i, pred in enumerate(pool):
35
+ for j, ref in enumerate(refs):
36
+ try:
37
+ m1 = with_coords(mol, pred)
38
+ m2 = with_coords(mol, ref)
39
+ rows.append((i, j, float(rdMolAlign.GetBestRMS(m1, m2, maxMatches=max_matches))))
40
+ except Exception:
41
+ # Fallback preserves the audit rather than silently dropping a molecule.
42
+ a = c1 - c1.mean(0, keepdims=True)
43
+ b = c2 - c2.mean(0, keepdims=True)
44
+ h = a.T @ b
45
+ u, _, vt = np.linalg.svd(h)
46
+ d = np.eye(3)
47
+ d[2, 2] = np.sign(np.linalg.det(vt.T @ u.T))
48
+ aa = a @ (vt.T @ d @ u.T)
49
+ rows.append((i, j, float(np.sqrt(np.mean((aa - b) ** 2)))))
50
+ return np.asarray(rows, dtype=float)
51
+
52
+
53
+ def main():
54
+ p = argparse.ArgumentParser()
55
+ p.add_argument("--pool", required=True)
56
+ p.add_argument("--out", required=True)
57
+ p.add_argument("--method", required=True)
58
+ p.add_argument("--max-matches", type=int, default=10000)
59
+ args = p.parse_args()
60
+ payload = torch.load(args.pool, map_location="cpu", weights_only=False)
61
+ records = payload["records"] if isinstance(payload, dict) else payload
62
+ out_rows = []
63
+ for rec in records:
64
+ mat = rmsd_matrix(rec["raw_pool"], rec["ref_confs"], rec["mol"], rec.get("heavy_mask"), args.max_matches)
65
+ for k in (1, 5, 10, 20):
66
+ kk = min(k, int(rec["raw_pool"].shape[0]))
67
+ sub = mat[mat[:, 0] < kk]
68
+ ref_min = np.array([sub[sub[:, 1] == j, 2].min() for j in range(len(rec["ref_confs"]))])
69
+ pred_min = np.array([sub[sub[:, 0] == i, 2].min() for i in range(kk)])
70
+ out_rows.append({"method": args.method, "mol_id": rec["mol_id"], "mol_key": rec["mol_key"], "K": k,
71
+ "cov_r": float(np.mean(ref_min < 0.75)), "amr_r": float(np.mean(ref_min)),
72
+ "cov_p": float(np.mean(pred_min < 0.75)), "amr_p": float(np.mean(pred_min)),
73
+ "best_rmsd": float(ref_min.min())})
74
+ df = pd.DataFrame(out_rows)
75
+ out = Path(args.out)
76
+ out.parent.mkdir(parents=True, exist_ok=True)
77
+ df.to_csv(out, index=False)
78
+ print(df.groupby(["method", "K"])[["cov_r", "amr_r", "cov_p", "amr_p", "best_rmsd"]].mean().to_string())
79
+
80
+
81
+ if __name__ == "__main__":
82
+ main()
@@ -0,0 +1,104 @@
1
+ #!/usr/bin/env python3
2
+ """Calibrate the saved Stage-I P scale on held-out records and rerank a fixed pool."""
3
+ from __future__ import annotations
4
+ import argparse, csv, json, math, sys
5
+ from pathlib import Path
6
+ from types import SimpleNamespace
7
+ import numpy as np
8
+ import torch
9
+ from tqdm import tqdm
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ sys.path.insert(0, str(ROOT))
13
+ import infer_base_conformers
14
+ from pgraph_controls import controlled_pglobal
15
+ from evaluate_route2_p_basin_budget import (
16
+ nonlocal_pair_mask, farthest_point_basins, mode_weights, allocate,
17
+ local_p_density_selection, metrics,
18
+ )
19
+
20
+ def logit(x):
21
+ return torch.logit(x.clamp(1e-6, 1.0 - 1e-6))
22
+
23
+ def record_teacher(record):
24
+ a, b = record["pgraph_kernel"]
25
+ q = []
26
+ for conf in record["ref_confs"].float():
27
+ q.append(infer_base_conformers.prob_low_dim_kernel(conf, a, b, kernel="umap"))
28
+ return torch.stack(q).mean(0).clamp(1e-6, 1.0 - 1e-6)
29
+
30
+ def fit_calibration(records):
31
+ xs, ys = [], []
32
+ for record in records:
33
+ mask = nonlocal_pair_mask(record.get("mol"), int(record["pglobal"].size(0)))
34
+ xs.append(logit(record["pglobal"])[mask])
35
+ ys.append(logit(record_teacher(record))[mask])
36
+ x, y = torch.cat(xs), torch.cat(ys)
37
+ X = torch.stack([x, torch.ones_like(x)], dim=1)
38
+ coef = torch.linalg.lstsq(X, y).solution
39
+ scale = float(coef[0].clamp(0.05, 20.0))
40
+ bias = float(coef[1].clamp(-10.0, 10.0))
41
+ return scale, bias
42
+
43
+ def calibrate(p, scale, bias):
44
+ return torch.sigmoid(scale * logit(p) + bias).clamp(1e-6, 1.0 - 1e-6)
45
+
46
+ def main():
47
+ ap = argparse.ArgumentParser()
48
+ ap.add_argument("--pool_pt", required=True)
49
+ ap.add_argument("--calibration_records", type=int, default=10)
50
+ ap.add_argument("--max_molecules", type=int, default=50)
51
+ ap.add_argument("--budget_multiplier", type=float, default=2.0)
52
+ ap.add_argument("--modes", type=int, default=3)
53
+ ap.add_argument("--p_weight", type=float, default=0.5)
54
+ ap.add_argument("--candidate_p_weight", type=float, default=0.5)
55
+ ap.add_argument("--controls", default="normal,shuffle,random,zero")
56
+ ap.add_argument("--threshold", type=float, default=0.5)
57
+ ap.add_argument("--density_k", type=int, default=20)
58
+ ap.add_argument("--seed", type=int, default=20260825)
59
+ ap.add_argument("--output_prefix", required=True)
60
+ args = ap.parse_args()
61
+ records = list(torch.load(args.pool_pt, map_location="cpu", weights_only=False)["records"])
62
+ records = records[:args.max_molecules] if args.max_molecules > 0 else records
63
+ ncal = min(args.calibration_records, max(1, len(records) - 1))
64
+ scale, bias = fit_calibration(records[:ncal])
65
+ controls = [x.strip() for x in args.controls.split(",") if x.strip()]
66
+ rows = []
67
+ eval_records = records[ncal:]
68
+ for record in tqdm(eval_records, desc="calibrated fixed-pool evaluation", unit="molecule"):
69
+ pool = record["raw_pool"].float()
70
+ budget = min(pool.size(0), max(1, round(args.budget_multiplier * record["ref_confs"].size(0))))
71
+ dist = infer_base_conformers._pairwise_torsion_signature_distance(pool, record.get("mol"), fallback_metric="kabsch", heavy_mask=record.get("heavy_mask"))
72
+ assignment = farthest_point_basins(dist, args.modes)
73
+ modes = int(assignment.max().item()) + 1
74
+ learned = record["pglobal"].float()
75
+ for control in controls:
76
+ cargs = SimpleNamespace(pglobal_control=control, pglobal_seed=args.seed, disable_stage1_pglobal=False)
77
+ target = controlled_pglobal(learned, cargs, mol=record.get("mol"))
78
+ target = calibrate(target, scale, bias)
79
+ a, b = record["pgraph_kernel"]
80
+ relations = []
81
+ mask = nonlocal_pair_mask(record.get("mol"), int(pool.size(1)))
82
+ for conf in pool:
83
+ q = infer_base_conformers.prob_low_dim_kernel(conf, a, b, kernel="umap").clamp(1e-6, 1.0 - 1e-6)
84
+ relations.append(q[mask])
85
+ rel = torch.stack(relations)
86
+ t = target[mask].view(1, -1)
87
+ bce = -(t * rel.log() + (1.0 - t) * (1.0 - rel).log()).mean(1)
88
+ weights, available, _ = mode_weights(assignment, bce, modes, args.p_weight, 1.0)
89
+ quota = allocate(weights, available, budget)
90
+ final = local_p_density_selection(pool, assignment, quota, record, bce, args.density_k, args.candidate_p_weight)
91
+ rows.append({"mol_id": record["mol_id"], "control": control, "pool_size": int(pool.size(0),), "budget": int(budget), **metrics(final, record, SimpleNamespace(rmsd_backend="kabsch", rdkit_max_matches=1000000, threshold=args.threshold))})
92
+ prefix = Path(args.output_prefix); prefix.parent.mkdir(parents=True, exist_ok=True)
93
+ with prefix.with_name(prefix.name + "_per_molecule.csv").open("w", newline="") as f:
94
+ w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)
95
+ summary = []
96
+ for control in controls:
97
+ sub = [r for r in rows if r["control"] == control]
98
+ summary.append({"control": control, "molecules": len(sub), **{k: float(np.mean([r[k] for r in sub])) for k in ("cov_r","cov_p","amr_r","amr_p")}})
99
+ out = {"calibration_records": ncal, "evaluation_records": len(eval_records), "logit_scale": scale, "logit_bias": bias, "summary": summary}
100
+ prefix.with_name(prefix.name + "_summary.json").write_text(json.dumps(out, indent=2) + "\n")
101
+ print(json.dumps(out, indent=2))
102
+
103
+ if __name__ == "__main__":
104
+ main()