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,1093 @@
1
+ #!/usr/bin/env python3
2
+ """Infer conformers from mixture latent modes and torsion flow matching."""
3
+ from __future__ import annotations
4
+
5
+ from _path import ROOT # noqa: F401
6
+
7
+ import argparse
8
+ import csv
9
+ import math
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ import tempfile
14
+
15
+ import torch
16
+ from rdkit import RDLogger
17
+ from torch_geometric.loader import DataLoader
18
+ from tqdm import tqdm
19
+ from rdkit import Chem
20
+
21
+ import infer_base_conformers
22
+ from dataset import QM9Dataset
23
+ from infer_base_conformers import build_model_args, get_split_indices
24
+ from infer_torsion import generate_base_conformers
25
+ from mixture_torsion_flow import MixtureTorsionFlowModel, normalize_periodic
26
+ from models.model0 import GNNEncoder, _torsion_rows, apply_torsion_residuals, periodic_angle_delta, torsion_angles
27
+ from torsion_manifold import probability_graph_torsion_context, probability_graph_torsion_pair_bias
28
+
29
+ RDLogger.DisableLog("rdApp.*")
30
+
31
+
32
+ def parse_args():
33
+ p = argparse.ArgumentParser(description="Evaluate mixture-mode torsion flow")
34
+ p.add_argument("--fixed_dump_name", action="store_true")
35
+ p.add_argument("--data_root", default="data")
36
+ p.add_argument("--dataset", default="Drugs")
37
+ p.add_argument("--raw_prefix", default="geom_drugs")
38
+ p.add_argument("--base_checkpoint", required=True)
39
+ p.add_argument("--flow_checkpoint", required=True)
40
+ p.add_argument("--device", default="cpu")
41
+ p.add_argument("--split", default="test")
42
+ p.add_argument("--batch_size", type=int, default=1)
43
+ p.add_argument("--max_confs", type=int, default=5)
44
+ p.add_argument("--raw_reference_file", default=None)
45
+ p.add_argument("--ref_subset", choices=["full", "top_energy", "first"], default="full")
46
+ p.add_argument("--ref_top_k", type=int, default=0)
47
+ p.add_argument("--sample_multiplier", type=float, default=2.0)
48
+ p.add_argument(
49
+ "--max_output_confs",
50
+ type=int,
51
+ default=0,
52
+ help="Optional cap on final conformer count, e.g. min(2K,32). 0 disables the cap.",
53
+ )
54
+ p.add_argument(
55
+ "--oversample_factor",
56
+ type=float,
57
+ default=1.0,
58
+ help="Generate this many times the final 2R budget before reference-free selection.",
59
+ )
60
+ p.add_argument("--flow_steps", type=int, default=24)
61
+ p.add_argument("--base_method", default="etkdg")
62
+ p.add_argument("--mode_center_alpha", type=float, default=0.0)
63
+ p.add_argument("--endpoint_repair_steps", type=int, default=0)
64
+ p.add_argument("--endpoint_repair_step_scale", type=float, default=0.35)
65
+ p.add_argument("--endpoint_repair_max_norm", type=float, default=0.35)
66
+ p.add_argument(
67
+ "--p_control",
68
+ choices=["normal", "zero", "static", "shuffle"],
69
+ default="normal",
70
+ help=(
71
+ "Probability-graph control. normal uses learned mode-specific P_m; "
72
+ "static uses the global Stage-1 P for all modes; zero uses a neutral "
73
+ "constant graph; shuffle permutes P_m as a topology-breaking control."
74
+ ),
75
+ )
76
+ p.add_argument("--min_modes", type=int, default=4)
77
+ p.add_argument("--min_per_mode", type=int, default=1)
78
+ p.add_argument(
79
+ "--select_candidates",
80
+ choices=["none", "precision2r", "modecover", "mode_precision", "cluster_quality"],
81
+ default="none",
82
+ help="Reference-free final-set compression applied after mixture-flow candidate generation.",
83
+ )
84
+ p.add_argument("--metric_recall_pool", choices=["final", "generated"], default="final")
85
+ p.add_argument("--precision2r_density_k", type=int, default=20)
86
+ p.add_argument("--precision2r_prefilter_quantile", type=float, default=0.45)
87
+ p.add_argument("--precision2r_density_weight", type=float, default=1.0)
88
+ p.add_argument("--precision2r_centrality_weight", type=float, default=0.45)
89
+ p.add_argument("--precision2r_duplicate_radius", type=float, default=0.0)
90
+ p.add_argument(
91
+ "--output_dedup_radius",
92
+ type=float,
93
+ default=0.0,
94
+ help="Minimum torsion/RMSD-signature distance between selected final conformers. 0 disables.",
95
+ )
96
+ p.add_argument("--modecover_min_modes", type=int, default=4)
97
+ p.add_argument("--modecover_min_per_mode", type=int, default=1)
98
+ p.add_argument("--modecover_weight_power", type=float, default=0.65)
99
+ p.add_argument("--modecover_adherence_weight", type=float, default=0.75)
100
+ p.add_argument("--modecover_compact_fraction", type=float, default=0.70)
101
+ p.add_argument("--modeprecision_min_modes", type=int, default=6)
102
+ p.add_argument("--modeprecision_min_per_mode", type=int, default=1)
103
+ p.add_argument("--modeprecision_weight_power", type=float, default=0.40)
104
+ p.add_argument("--modeprecision_adherence_weight", type=float, default=1.75)
105
+ p.add_argument("--modeprecision_centrality_weight", type=float, default=0.65)
106
+ p.add_argument("--modeprecision_compact_fraction", type=float, default=0.88)
107
+ p.add_argument("--modeprecision_refill_compact_fraction", type=float, default=0.95)
108
+ p.add_argument("--cluster_quality_radius", type=float, default=0.35)
109
+ p.add_argument("--cluster_quality_min_cluster_size", type=int, default=1)
110
+ p.add_argument("--cluster_quality_adherence_weight", type=float, default=1.50)
111
+ p.add_argument("--cluster_quality_clash_weight", type=float, default=2.50)
112
+ p.add_argument("--cluster_quality_centrality_weight", type=float, default=0.85)
113
+ p.add_argument("--cluster_quality_diversity_fraction", type=float, default=0.20)
114
+ p.add_argument("--cluster_quality_clash_threshold", type=float, default=1.05)
115
+ p.add_argument("--post_denoiser_checkpoint", default="")
116
+ p.add_argument("--post_denoise_steps", type=int, default=0)
117
+ p.add_argument("--post_denoise_sigma", type=float, default=0.015)
118
+ p.add_argument("--post_denoise_step_scale", type=float, default=0.22)
119
+ p.add_argument("--torsion_mode_max", type=int, default=64)
120
+ p.add_argument("--xtb_relax", action="store_true", help="Relax final selected conformers with external xTB GFN2.")
121
+ p.add_argument("--xtb_command", default="xtb")
122
+ p.add_argument("--xtb_max_confs", type=int, default=0, help="Optional cap on relaxed final conformers; 0 relaxes all selected conformers.")
123
+ p.add_argument("--cov_thresholds", default="0.25,0.5,0.75,1.0,1.25,1.5,1.75,2.0")
124
+ p.add_argument("--limit_molecules", type=int, default=50)
125
+ p.add_argument("--output_dir", required=True)
126
+ p.add_argument("--per_molecule_csv", default="")
127
+ p.add_argument("--threshold_curve_csv", default="")
128
+ p.add_argument("--revisited_metrics_csv", default="")
129
+ p.add_argument("--seed", type=int, default=20260725)
130
+ return p.parse_args()
131
+
132
+
133
+ def load_base(path, device):
134
+ cli = argparse.Namespace(
135
+ max_confs=5,
136
+ num_modes=10,
137
+ use_mode_specific_p=False,
138
+ mode_p_delta_scale=1.0,
139
+ deterministic_modes=True,
140
+ use_torsion_residual=False,
141
+ torsion_residual_max=64,
142
+ torsion_residual_scale=1.0,
143
+ )
144
+ model = GNNEncoder(args=build_model_args(cli), config={"model": {"model_level": "graph"}}).to(device)
145
+ state = torch.load(path, map_location=device, weights_only=False)
146
+ model.load_state_dict(state.get("model_state_dict", state.get("state_dict", state)), strict=False)
147
+ model.eval()
148
+ return model
149
+
150
+
151
+ def load_flow(path, device):
152
+ checkpoint = torch.load(path, map_location=device, weights_only=False)
153
+ model = MixtureTorsionFlowModel(
154
+ graph_dim=int(checkpoint.get("graph_dim", 128)),
155
+ pair_dim=int(checkpoint.get("pair_dim", 515)),
156
+ components=int(checkpoint["components"]),
157
+ mode_dim=int(checkpoint["mode_dim"]),
158
+ max_torsions=int(checkpoint["max_torsions"]),
159
+ hidden_dim=int(checkpoint["hidden_dim"]),
160
+ flow_layers=int(checkpoint.get("flow_layers", 3)),
161
+ scaffold_conditioned=bool(checkpoint.get("scaffold_conditioned", False)),
162
+ ).to(device)
163
+ state = checkpoint["model_state_dict"]
164
+ current = model.state_dict()
165
+ compatible = {key: value for key, value in state.items() if key in current and tuple(value.shape) == tuple(current[key].shape)}
166
+ missing = sorted(set(current) - set(compatible))
167
+ skipped = sorted(set(state) - set(compatible))
168
+ model.load_state_dict(compatible, strict=False)
169
+ if missing or skipped:
170
+ print(
171
+ f"Loaded compatible mixture-flow weights from {path}; "
172
+ f"missing={len(missing)} skipped={len(skipped)}. "
173
+ "Retrain with the p-biased task for the full model."
174
+ )
175
+ model.eval()
176
+ return model
177
+
178
+
179
+ def load_optional_post_denoiser(path, device):
180
+ path = str(path or "").strip()
181
+ if not path:
182
+ return None
183
+ from infer_torsional_denoiser import load_denoiser
184
+
185
+ model = load_denoiser(path, device)
186
+ model.eval()
187
+ return model
188
+
189
+
190
+ def allocation_schedule(weights, count, min_modes=4, min_per_mode=1):
191
+ count = int(count)
192
+ if count <= 0:
193
+ return []
194
+ weights = weights.detach().float().cpu()
195
+ order = torch.argsort(weights, descending=True).tolist()
196
+ active = order[: min(len(order), max(1, min(int(min_modes), count)))]
197
+ slots = {int(m): 0 for m in range(len(order))}
198
+ used = 0
199
+ for mode in active:
200
+ give = min(int(min_per_mode), count - used)
201
+ slots[int(mode)] += give
202
+ used += give
203
+ if used >= count:
204
+ break
205
+ remaining = count - used
206
+ if remaining > 0:
207
+ probs = weights.clamp_min(1e-8)
208
+ probs = probs / probs.sum().clamp_min(1e-8)
209
+ raw = torch.floor(probs * remaining).long()
210
+ for mode, value in enumerate(raw.tolist()):
211
+ slots[int(mode)] += int(value)
212
+ used = sum(slots.values())
213
+ remainder = count - used
214
+ if remainder > 0:
215
+ frac = probs * remaining - raw.float()
216
+ for mode in torch.argsort(frac, descending=True).tolist()[:remainder]:
217
+ slots[int(mode)] += 1
218
+ schedule = []
219
+ for mode in order:
220
+ schedule.extend([int(mode)] * int(slots[int(mode)]))
221
+ return schedule[:count]
222
+
223
+
224
+ def budgeted_mode_slots(weights, target_count, min_modes=4, min_per_mode=1, weight_power=1.0):
225
+ """Allocate final output slots across learned conformer modes."""
226
+ target_count = int(target_count)
227
+ if target_count <= 0:
228
+ return {}
229
+ weights = weights.detach().float().cpu().clamp_min(1e-8)
230
+ weights = weights / weights.sum().clamp_min(1e-8)
231
+ if float(weight_power) != 1.0:
232
+ weights = weights.pow(float(weight_power)).clamp_min(1e-8)
233
+ weights = weights / weights.sum().clamp_min(1e-8)
234
+ order = torch.argsort(weights, descending=True).tolist()
235
+ active_count = min(len(order), max(1, min(int(min_modes), target_count)))
236
+ active = order[:active_count]
237
+ slots = {int(mode): 0 for mode in active}
238
+ used = 0
239
+ for mode in active:
240
+ give = min(int(min_per_mode), target_count - used)
241
+ slots[int(mode)] += give
242
+ used += give
243
+ if used >= target_count:
244
+ return slots
245
+ remaining = target_count - used
246
+ if remaining <= 0:
247
+ return slots
248
+ active_w = weights[active]
249
+ active_w = active_w / active_w.sum().clamp_min(1e-8)
250
+ raw = torch.floor(active_w * remaining).long()
251
+ for idx, mode in enumerate(active):
252
+ slots[int(mode)] += int(raw[idx].item())
253
+ used = sum(slots.values())
254
+ remainder = target_count - used
255
+ if remainder > 0:
256
+ frac = active_w * remaining - raw.float()
257
+ for idx in torch.argsort(frac, descending=True).tolist()[:remainder]:
258
+ slots[int(active[idx])] += 1
259
+ return slots
260
+
261
+
262
+ def neutral_probability_graph_like(p_base):
263
+ p = torch.full_like(p_base, 0.5)
264
+ if p.dim() == 2 and p.size(0) == p.size(1):
265
+ eye = torch.eye(p.size(0), dtype=torch.bool, device=p.device)
266
+ p = p.masked_fill(eye, 1e-6)
267
+ return p
268
+
269
+
270
+ def controlled_encoder_p(p_base, args):
271
+ """Control the probability graph seen by the mixture-mode encoder."""
272
+ if args.p_control == "zero":
273
+ return neutral_probability_graph_like(p_base)
274
+ if args.p_control == "shuffle":
275
+ generator = torch.Generator(device=p_base.device)
276
+ generator.manual_seed((args.seed + p_base.size(0) * 7919) % (2**31 - 1))
277
+ perm = torch.randperm(p_base.size(0), generator=generator, device=p_base.device)
278
+ return p_base[perm][:, perm]
279
+ return p_base
280
+
281
+
282
+ def controlled_p_mode(p_modes, p_base, mode, args):
283
+ if args.p_control == "normal":
284
+ return p_modes[mode]
285
+ if args.p_control == "zero":
286
+ return neutral_probability_graph_like(p_base)
287
+ if args.p_control == "static":
288
+ return p_base
289
+ generator = torch.Generator(device=p_base.device)
290
+ generator.manual_seed((args.seed + int(mode) * 1009 + p_base.size(0) * 37) % (2**31 - 1))
291
+ perm = torch.randperm(p_base.size(0), generator=generator, device=p_base.device)
292
+ return p_modes[mode][perm][:, perm]
293
+
294
+
295
+ @torch.no_grad()
296
+ def sample_for_graph(base, flow_model, post_denoiser, batch, graph_idx, count, args):
297
+ node = base.gnn(batch)
298
+ graph = base.pool(node, batch.batch)
299
+ mask = batch.batch == graph_idx
300
+ feat = node[mask]
301
+ if feat.size(0) <= 1 or not hasattr(batch, "rdmol"):
302
+ return None
303
+ mol = batch.rdmol[graph_idx]
304
+ edge = base._get_local_edge_index(batch.edge_index, mask)
305
+ torsion = base._get_local_torsion_index(getattr(batch, "torsion_index", None), mask)
306
+ rows = _torsion_rows(torsion)
307
+ if rows is None or rows.numel() == 0:
308
+ return None
309
+ rows = rows[: int(flow_model.max_torsions)].long()
310
+ rows = rows[(rows >= 0).all(dim=1) & (rows < feat.size(0)).all(dim=1)]
311
+ if rows.numel() == 0:
312
+ return None
313
+ p_base, pair = base._predict_P_global(feat, edge)
314
+ p_for_encoder = controlled_encoder_p(p_base, args)
315
+ logits, p_modes, mode_embed, mu = flow_model.encode(graph[graph_idx], pair.detach(), p_for_encoder.detach())
316
+ weights = torch.softmax(logits, dim=-1)
317
+ schedule = allocation_schedule(weights, count, min_modes=args.min_modes, min_per_mode=args.min_per_mode)
318
+ bases = generate_base_conformers(mol, max(1, len(schedule)), args.base_method)
319
+ if not bases:
320
+ return None
321
+ out, mode_ids, mode_adherence, steps = [], [], [], max(1, int(args.flow_steps))
322
+ for idx, mode in enumerate(schedule):
323
+ base_conf = bases[idx % len(bases)].to(device=feat.device, dtype=feat.dtype)
324
+ if base_conf.shape[0] != feat.size(0):
325
+ continue
326
+ base_angle = torsion_angles(base_conf, rows)
327
+ base_embed = torch.stack([base_angle.sin(), base_angle.cos()], dim=-1)
328
+ p_mode = controlled_p_mode(p_modes, p_base, int(mode), args)
329
+ p_context, _ = probability_graph_torsion_context(p_mode, mol, torsion, flow_model.max_torsions)
330
+ p_pair_bias, _ = probability_graph_torsion_pair_bias(p_mode, torsion, flow_model.max_torsions)
331
+ noise = normalize_periodic(torch.randn(rows.size(0), 2, device=feat.device, dtype=feat.dtype))
332
+ mode_mu = mu[int(mode)]
333
+ if bool(getattr(flow_model, "scaffold_conditioned", False)):
334
+ mode_angle = torch.atan2(mode_mu[: rows.size(0), 0], mode_mu[: rows.size(0), 1])
335
+ residual_angle = periodic_angle_delta(mode_angle, base_angle)
336
+ mode_mu = torch.stack([residual_angle.sin(), residual_angle.cos()], dim=-1)
337
+ alpha = min(1.0, max(0.0, float(getattr(args, "mode_center_alpha", 0.0))))
338
+ if alpha > 0.0:
339
+ mode_center = mode_mu[: rows.size(0)].to(device=feat.device, dtype=feat.dtype)
340
+ x = normalize_periodic(alpha * mode_center + (1.0 - alpha) * noise)
341
+ else:
342
+ x = noise
343
+ last_flow_norm = torch.zeros(rows.size(0), 1, device=feat.device, dtype=feat.dtype)
344
+ dt = 1.0 / steps
345
+ for step in range(steps):
346
+ time = (step + 0.5) / steps
347
+ v1 = flow_model.flow(
348
+ x,
349
+ time,
350
+ graph[graph_idx],
351
+ mode_embed[int(mode)],
352
+ mode_mu,
353
+ p_context[: rows.size(0)],
354
+ p_pair_bias[: rows.size(0), : rows.size(0)],
355
+ scaffold_torsion=base_embed,
356
+ )
357
+ mid = normalize_periodic(x + 0.5 * dt * v1)
358
+ v2 = flow_model.flow(
359
+ mid,
360
+ min(1.0, time + 0.5 * dt),
361
+ graph[graph_idx],
362
+ mode_embed[int(mode)],
363
+ mode_mu,
364
+ p_context[: rows.size(0)],
365
+ p_pair_bias[: rows.size(0), : rows.size(0)],
366
+ scaffold_torsion=base_embed,
367
+ )
368
+ x = normalize_periodic(x + dt * v2)
369
+ last_flow_norm = v2.detach().norm(dim=-1, keepdim=True)
370
+ repair_steps = max(0, int(getattr(args, "endpoint_repair_steps", 0)))
371
+ if repair_steps > 0 and hasattr(flow_model, "repair"):
372
+ repair_scale = float(getattr(args, "endpoint_repair_step_scale", 0.35))
373
+ repair_max = max(1e-6, float(getattr(args, "endpoint_repair_max_norm", 0.35)))
374
+ for _ in range(repair_steps):
375
+ delta_x = flow_model.repair(
376
+ x,
377
+ graph[graph_idx],
378
+ mode_embed[int(mode)],
379
+ mode_mu,
380
+ p_context[: rows.size(0)],
381
+ p_pair_bias[: rows.size(0), : rows.size(0)],
382
+ flow_norm=last_flow_norm,
383
+ scaffold_torsion=base_embed,
384
+ )
385
+ norm = delta_x.norm(dim=-1, keepdim=True).clamp_min(1e-8)
386
+ delta_x = delta_x * torch.clamp(repair_max / norm, max=1.0)
387
+ x = normalize_periodic(x + repair_scale * delta_x)
388
+ target = torch.atan2(x[:, 0], x[:, 1])
389
+ if bool(getattr(flow_model, "scaffold_conditioned", False)):
390
+ delta = target
391
+ else:
392
+ delta = periodic_angle_delta(target, base_angle)
393
+ adherence = (1.0 - (x * mode_mu[: rows.size(0)].to(dtype=x.dtype)).sum(dim=-1).clamp(-1.0, 1.0)).mean()
394
+ y = apply_torsion_residuals(base_conf, torsion, delta, edge, max_torsions=flow_model.max_torsions)
395
+ post_steps = max(0, int(getattr(args, "post_denoise_steps", 0)))
396
+ if post_denoiser is not None and post_steps > 0:
397
+ max_torsions = int(getattr(args, "torsion_mode_max", flow_model.max_torsions))
398
+ for _ in range(post_steps):
399
+ correction = post_denoiser(
400
+ node_feat=feat,
401
+ graph_feat=graph[graph_idx],
402
+ coords=y,
403
+ P=p_base,
404
+ torsion_index=torsion,
405
+ sigma=float(getattr(args, "post_denoise_sigma", 0.015)),
406
+ max_torsions=max_torsions,
407
+ )
408
+ y = apply_torsion_residuals(
409
+ y,
410
+ torsions=torsion,
411
+ deltas=correction * float(getattr(args, "post_denoise_step_scale", 0.22)),
412
+ edge_index=edge,
413
+ max_torsions=max_torsions,
414
+ )
415
+ out.append(y.detach().cpu())
416
+ mode_ids.append(int(mode))
417
+ mode_adherence.append(float(adherence.detach().cpu()))
418
+ if not out:
419
+ return None
420
+ return {
421
+ "confs": torch.stack(out, dim=0),
422
+ "mode_ids": torch.tensor(mode_ids, dtype=torch.long),
423
+ "mode_adherence": torch.tensor(mode_adherence, dtype=torch.float32),
424
+ "mode_weights": weights.detach().cpu(),
425
+ }
426
+
427
+
428
+ def select_precision_subset(pool, target_count, mol, heavy_mask, args):
429
+ return infer_base_conformers.select_precision2r_conformers(
430
+ pool,
431
+ target_count,
432
+ mol=mol,
433
+ heavy_mask=heavy_mask,
434
+ density_k=int(getattr(args, "precision2r_density_k", 20)),
435
+ prefilter_quantile=float(getattr(args, "precision2r_prefilter_quantile", 0.45)),
436
+ density_weight=float(getattr(args, "precision2r_density_weight", 1.0)),
437
+ centrality_weight=float(getattr(args, "precision2r_centrality_weight", 0.45)),
438
+ duplicate_radius=float(getattr(args, "precision2r_duplicate_radius", 0.0)),
439
+ )
440
+
441
+
442
+ def _normalize_01(values):
443
+ values = values.float()
444
+ if values.numel() == 0:
445
+ return values
446
+ lo = values.min()
447
+ hi = values.max()
448
+ return (values - lo) / (hi - lo).clamp_min(1e-8)
449
+
450
+
451
+ def select_compact_diverse_representatives(pool, target_count, mol, heavy_mask, args, adherence=None):
452
+ """Stage3 mode-local compactness/diversity selector.
453
+
454
+ This is the selector used by the standalone mixture torsion-flow method.
455
+ It does not use references and does not call the old global precision2r
456
+ routine. Within a learned mode, low local radius/centrality candidates are
457
+ treated as compact representatives; the second half is filled by farthest
458
+ coverage to avoid duplicates inside the same mode.
459
+ """
460
+ target_count = max(1, int(target_count))
461
+ if pool is None or pool.size(0) <= target_count:
462
+ return pool
463
+ dist = infer_base_conformers._pairwise_torsion_signature_distance(
464
+ pool,
465
+ mol,
466
+ fallback_metric="centered_rmsd",
467
+ heavy_mask=heavy_mask,
468
+ )
469
+ n = int(pool.size(0))
470
+ eye = torch.eye(n, dtype=dist.dtype, device=dist.device)
471
+ k = max(1, min(int(getattr(args, "precision2r_density_k", 20)), max(1, n - 1)))
472
+ sorted_dist = torch.sort(dist + eye * 1e6, dim=1).values
473
+ local_radius = sorted_dist[:, :k].mean(dim=1)
474
+ centrality = dist.mean(dim=1)
475
+ compact_score = _normalize_01(local_radius) + 0.45 * _normalize_01(centrality)
476
+ if adherence is not None and adherence.numel() == n:
477
+ compact_score = compact_score + float(getattr(args, "modecover_adherence_weight", 0.75)) * _normalize_01(adherence)
478
+ ranked = torch.argsort(compact_score).detach().cpu().tolist()
479
+
480
+ selected = []
481
+ min_dist = None
482
+ dedup_radius = max(0.0, float(getattr(args, "output_dedup_radius", 0.0)))
483
+ compact_fraction = min(1.0, max(0.0, float(getattr(args, "modecover_compact_fraction", 0.70))))
484
+ compact_quota = max(1, min(target_count, int(round(target_count * compact_fraction))))
485
+ for idx in ranked:
486
+ idx = int(idx)
487
+ if min_dist is not None and dedup_radius > 0.0 and float(min_dist[idx].item()) < dedup_radius:
488
+ continue
489
+ selected.append(idx)
490
+ min_dist = dist[idx].clone() if min_dist is None else torch.minimum(min_dist, dist[idx])
491
+ if len(selected) >= compact_quota:
492
+ break
493
+
494
+ while len(selected) < target_count:
495
+ if min_dist is None:
496
+ break
497
+ added = False
498
+ for idx in torch.argsort(min_dist, descending=True).detach().cpu().tolist():
499
+ idx = int(idx)
500
+ if idx not in selected:
501
+ if dedup_radius > 0.0 and float(min_dist[idx].item()) < dedup_radius:
502
+ continue
503
+ selected.append(idx)
504
+ min_dist = torch.minimum(min_dist, dist[idx])
505
+ added = True
506
+ break
507
+ if not added:
508
+ break
509
+
510
+ if len(selected) < target_count:
511
+ for idx in ranked:
512
+ idx = int(idx)
513
+ if idx not in selected:
514
+ if min_dist is not None and dedup_radius > 0.0 and float(min_dist[idx].item()) < dedup_radius:
515
+ continue
516
+ selected.append(idx)
517
+ if len(selected) >= target_count:
518
+ break
519
+ if len(selected) < target_count:
520
+ for idx in ranked:
521
+ idx = int(idx)
522
+ if idx not in selected:
523
+ selected.append(idx)
524
+ if len(selected) >= target_count:
525
+ break
526
+ return pool[torch.tensor(selected[:target_count], dtype=torch.long)]
527
+
528
+
529
+ def select_modecover_conformers(pool, mode_ids, mode_weights, mode_adherence, target_count, mol, heavy_mask, args):
530
+ target_count = max(1, int(target_count))
531
+ if pool.size(0) <= target_count:
532
+ return pool
533
+ slots = budgeted_mode_slots(
534
+ mode_weights,
535
+ target_count,
536
+ min_modes=int(getattr(args, "modecover_min_modes", 4)),
537
+ min_per_mode=int(getattr(args, "modecover_min_per_mode", 1)),
538
+ weight_power=float(getattr(args, "modecover_weight_power", 0.65)),
539
+ )
540
+ selected_chunks, selected_global = [], []
541
+ for mode, slot in slots.items():
542
+ if int(slot) <= 0:
543
+ continue
544
+ local_idx = torch.nonzero(mode_ids == int(mode), as_tuple=False).view(-1)
545
+ if local_idx.numel() == 0:
546
+ continue
547
+ local_pool = pool[local_idx]
548
+ local_adherence = mode_adherence[local_idx] if mode_adherence is not None else None
549
+ picked = select_compact_diverse_representatives(
550
+ local_pool,
551
+ min(int(slot), int(local_pool.size(0))),
552
+ mol,
553
+ heavy_mask,
554
+ args,
555
+ adherence=local_adherence,
556
+ )
557
+ selected_chunks.append(picked)
558
+ # Track selected by exact local tensor position only for rough refill avoidance.
559
+ selected_global.extend(local_idx[: min(int(slot), int(local_idx.numel()))].tolist())
560
+ selected = torch.cat(selected_chunks, dim=0) if selected_chunks else pool[:0]
561
+ if selected.size(0) >= target_count:
562
+ return selected[:target_count]
563
+ remaining = target_count - int(selected.size(0))
564
+ refill = select_compact_diverse_representatives(
565
+ pool,
566
+ target_count + remaining,
567
+ mol,
568
+ heavy_mask,
569
+ args,
570
+ adherence=mode_adherence,
571
+ )
572
+ if selected.size(0) == 0:
573
+ return refill[:target_count]
574
+ combined = torch.cat([selected, refill], dim=0)
575
+ return select_compact_diverse_representatives(combined, target_count, mol, heavy_mask, args)
576
+
577
+
578
+ def _mode_local_precision_scores(dist, local_idx, mode_adherence, args):
579
+ local_dist = dist[local_idx][:, local_idx]
580
+ n = int(local_idx.numel())
581
+ if n <= 1:
582
+ return torch.zeros(n, dtype=dist.dtype, device=dist.device)
583
+ eye = torch.eye(n, dtype=local_dist.dtype, device=local_dist.device)
584
+ k = max(1, min(int(getattr(args, "precision2r_density_k", 20)), n - 1))
585
+ sorted_dist = torch.sort(local_dist + eye * 1e6, dim=1).values
586
+ local_radius = sorted_dist[:, :k].mean(dim=1)
587
+ centrality = local_dist.mean(dim=1)
588
+ score = _normalize_01(local_radius)
589
+ score = score + float(getattr(args, "modeprecision_centrality_weight", 0.65)) * _normalize_01(centrality)
590
+ if mode_adherence is not None and mode_adherence.numel() > int(local_idx.max().item()):
591
+ score = score + float(getattr(args, "modeprecision_adherence_weight", 1.75)) * _normalize_01(mode_adherence[local_idx])
592
+ return score
593
+
594
+
595
+ def _append_with_dedup(selected, candidate, dist, dedup_radius):
596
+ candidate = int(candidate)
597
+ if candidate in selected:
598
+ return False
599
+ if selected and dedup_radius > 0.0:
600
+ current = torch.tensor(selected, dtype=torch.long, device=dist.device)
601
+ if float(dist[candidate, current].min().item()) < dedup_radius:
602
+ return False
603
+ selected.append(candidate)
604
+ return True
605
+
606
+
607
+ def _fill_compact_then_diverse(selected, local_idx, dist, local_score, quota, compact_fraction, dedup_radius):
608
+ quota = max(0, int(quota))
609
+ if quota <= 0 or local_idx.numel() == 0:
610
+ return
611
+ start_len = len(selected)
612
+ target_len = start_len + quota
613
+ ranked_local = torch.argsort(local_score).detach().cpu().tolist()
614
+ compact_quota = max(1, min(quota, int(round(quota * min(1.0, max(0.0, float(compact_fraction)))))))
615
+ compact_target_len = start_len + compact_quota
616
+ for li in ranked_local:
617
+ if len(selected) >= target_len:
618
+ return
619
+ _append_with_dedup(selected, int(local_idx[int(li)].item()), dist, dedup_radius)
620
+ if len(selected) >= compact_target_len:
621
+ break
622
+ while len(selected) < target_len:
623
+ if not selected:
624
+ for li in ranked_local:
625
+ if _append_with_dedup(selected, int(local_idx[int(li)].item()), dist, dedup_radius):
626
+ break
627
+ if not selected:
628
+ break
629
+ continue
630
+ chosen = torch.tensor(selected, dtype=torch.long, device=dist.device)
631
+ min_dist = dist[local_idx][:, chosen].min(dim=1).values
632
+ # Keep the diversity refill from drifting to extreme outliers by adding
633
+ # a small compactness penalty; this is intentionally more precision-
634
+ # biased than the older modecover selector.
635
+ refill_score = min_dist - 0.25 * _normalize_01(local_score)
636
+ added = False
637
+ for li in torch.argsort(refill_score, descending=True).detach().cpu().tolist():
638
+ if _append_with_dedup(selected, int(local_idx[int(li)].item()), dist, dedup_radius):
639
+ added = True
640
+ break
641
+ if not added:
642
+ break
643
+
644
+
645
+ def select_mode_precision_conformers(pool, mode_ids, mode_weights, mode_adherence, target_count, mol, heavy_mask, args):
646
+ """Mode-preserving precision selector.
647
+
648
+ This selector targets the current bottleneck: raw pools contain good
649
+ candidates, but final 2R sets include too many mode-edge outliers. It keeps
650
+ explicit mode quotas, then prefers medoid-like candidates inside each mode
651
+ before using a small farthest-point refill for coverage.
652
+ """
653
+ target_count = max(1, int(target_count))
654
+ if pool.size(0) <= target_count:
655
+ return pool
656
+ dist = infer_base_conformers._pairwise_torsion_signature_distance(
657
+ pool,
658
+ mol,
659
+ fallback_metric="centered_rmsd",
660
+ heavy_mask=heavy_mask,
661
+ )
662
+ slots = budgeted_mode_slots(
663
+ mode_weights,
664
+ target_count,
665
+ min_modes=int(getattr(args, "modeprecision_min_modes", 6)),
666
+ min_per_mode=int(getattr(args, "modeprecision_min_per_mode", 1)),
667
+ weight_power=float(getattr(args, "modeprecision_weight_power", 0.40)),
668
+ )
669
+ dedup_radius = max(0.0, float(getattr(args, "output_dedup_radius", 0.0)))
670
+ compact_fraction = float(getattr(args, "modeprecision_compact_fraction", 0.88))
671
+ selected = []
672
+ global_scores = torch.zeros(pool.size(0), dtype=dist.dtype, device=dist.device)
673
+
674
+ for mode, slot in slots.items():
675
+ if int(slot) <= 0:
676
+ continue
677
+ local_idx = torch.nonzero(mode_ids == int(mode), as_tuple=False).view(-1).to(dist.device)
678
+ if local_idx.numel() == 0:
679
+ continue
680
+ local_score = _mode_local_precision_scores(dist, local_idx, mode_adherence, args)
681
+ global_scores[local_idx] = local_score
682
+ before = len(selected)
683
+ mode_selected = []
684
+ _fill_compact_then_diverse(
685
+ mode_selected,
686
+ local_idx,
687
+ dist,
688
+ local_score,
689
+ min(int(slot), int(local_idx.numel())),
690
+ compact_fraction,
691
+ dedup_radius,
692
+ )
693
+ for idx in mode_selected:
694
+ if len(selected) - before >= int(slot):
695
+ break
696
+ _append_with_dedup(selected, idx, dist, dedup_radius)
697
+
698
+ if len(selected) < target_count:
699
+ all_idx = torch.arange(pool.size(0), device=dist.device)
700
+ missing_mask = global_scores == 0
701
+ if bool(missing_mask.any().item()):
702
+ # Assign scores for modes that were not part of the quota so the
703
+ # global refill can still use compactness instead of raw order.
704
+ for mode in torch.unique(mode_ids).detach().cpu().tolist():
705
+ local_idx = torch.nonzero(mode_ids == int(mode), as_tuple=False).view(-1).to(dist.device)
706
+ if local_idx.numel() > 0:
707
+ global_scores[local_idx] = _mode_local_precision_scores(dist, local_idx, mode_adherence, args)
708
+ refill_count = target_count - len(selected)
709
+ refill_fraction = float(getattr(args, "modeprecision_refill_compact_fraction", 0.95))
710
+ _fill_compact_then_diverse(
711
+ selected,
712
+ all_idx,
713
+ dist,
714
+ global_scores,
715
+ refill_count,
716
+ refill_fraction,
717
+ dedup_radius,
718
+ )
719
+ if len(selected) < target_count and refill_count > 0:
720
+ for idx in torch.argsort(global_scores).detach().cpu().tolist():
721
+ _append_with_dedup(selected, int(idx), dist, 0.0)
722
+ if len(selected) >= target_count:
723
+ break
724
+
725
+ selected = selected[:target_count]
726
+ return pool[torch.tensor(selected, dtype=torch.long)]
727
+
728
+
729
+ def _heavy_nonbonded_clash_scores(pool, mol, heavy_mask=None, threshold=1.05):
730
+ n_conf, n_atom = int(pool.size(0)), int(pool.size(1))
731
+ if n_conf == 0 or n_atom == 0:
732
+ return torch.zeros(n_conf)
733
+ device = pool.device
734
+ if heavy_mask is None:
735
+ heavy = torch.ones(n_atom, dtype=torch.bool, device=device)
736
+ else:
737
+ heavy = torch.as_tensor(heavy_mask, dtype=torch.bool, device=device)
738
+ if heavy.numel() != n_atom:
739
+ heavy = torch.ones(n_atom, dtype=torch.bool, device=device)
740
+ excluded = torch.eye(n_atom, dtype=torch.bool, device=device)
741
+ if mol is not None:
742
+ for bond in mol.GetBonds():
743
+ i = int(bond.GetBeginAtomIdx())
744
+ j = int(bond.GetEndAtomIdx())
745
+ if 0 <= i < n_atom and 0 <= j < n_atom:
746
+ excluded[i, j] = True
747
+ excluded[j, i] = True
748
+ valid_pair = heavy.view(-1, 1) & heavy.view(1, -1) & (~excluded)
749
+ valid_pair = torch.triu(valid_pair, diagonal=1)
750
+ total = int(valid_pair.sum().item())
751
+ if total <= 0:
752
+ return torch.zeros(n_conf, dtype=pool.dtype, device=device)
753
+ dist = torch.cdist(pool.float(), pool.float())
754
+ clashes = ((dist < float(threshold)) & valid_pair.view(1, n_atom, n_atom)).sum(dim=(1, 2)).to(dtype=pool.dtype)
755
+ return clashes / float(max(1, total))
756
+
757
+
758
+ def _greedy_cluster_indices(dist, radius):
759
+ remaining = set(range(int(dist.size(0))))
760
+ clusters = []
761
+ order = torch.argsort(dist.mean(dim=1)).detach().cpu().tolist()
762
+ for seed in order:
763
+ seed = int(seed)
764
+ if seed not in remaining:
765
+ continue
766
+ members = [idx for idx in list(remaining) if float(dist[seed, idx].item()) <= float(radius)]
767
+ if not members:
768
+ members = [seed]
769
+ clusters.append(members)
770
+ for idx in members:
771
+ remaining.discard(int(idx))
772
+ return clusters
773
+
774
+
775
+ def select_cluster_quality_conformers(pool, mode_ids, mode_weights, mode_adherence, target_count, mol, heavy_mask, args):
776
+ """Cluster candidates, then choose the best-scored representative per cluster.
777
+
778
+ This is a reference-free approximation to the GO-Flow-style filtering
779
+ protocol: reject obvious geometric transients, cluster the remaining
780
+ ensemble, and retain quality-scored representatives rather than random
781
+ cluster members.
782
+ """
783
+ target_count = max(1, int(target_count))
784
+ if pool.size(0) <= target_count:
785
+ return pool
786
+ dist = infer_base_conformers._pairwise_torsion_signature_distance(
787
+ pool,
788
+ mol,
789
+ fallback_metric="centered_rmsd",
790
+ heavy_mask=heavy_mask,
791
+ )
792
+ clash = _heavy_nonbonded_clash_scores(
793
+ pool,
794
+ mol,
795
+ heavy_mask=heavy_mask,
796
+ threshold=float(getattr(args, "cluster_quality_clash_threshold", 1.05)),
797
+ ).to(device=dist.device, dtype=dist.dtype)
798
+ centrality = dist.mean(dim=1)
799
+ adherence = mode_adherence.to(device=dist.device, dtype=dist.dtype) if mode_adherence is not None else torch.zeros_like(centrality)
800
+ score = (
801
+ float(getattr(args, "cluster_quality_centrality_weight", 0.85)) * _normalize_01(centrality)
802
+ + float(getattr(args, "cluster_quality_adherence_weight", 1.50)) * _normalize_01(adherence)
803
+ + float(getattr(args, "cluster_quality_clash_weight", 2.50)) * _normalize_01(clash)
804
+ )
805
+
806
+ clusters = _greedy_cluster_indices(dist, float(getattr(args, "cluster_quality_radius", 0.35)))
807
+ min_cluster_size = max(1, int(getattr(args, "cluster_quality_min_cluster_size", 1)))
808
+ representatives = []
809
+ for members in clusters:
810
+ if len(members) < min_cluster_size and len(clusters) > target_count:
811
+ continue
812
+ member_tensor = torch.tensor(members, dtype=torch.long, device=dist.device)
813
+ best_local = int(member_tensor[torch.argmin(score[member_tensor])].item())
814
+ representatives.append(best_local)
815
+ if not representatives:
816
+ representatives = torch.argsort(score).detach().cpu().tolist()
817
+
818
+ representatives = sorted(set(int(x) for x in representatives), key=lambda idx: float(score[idx].item()))
819
+ selected = []
820
+ quota_quality = max(1, min(target_count, int(round(target_count * (1.0 - float(getattr(args, "cluster_quality_diversity_fraction", 0.20)))))))
821
+ for idx in representatives:
822
+ selected.append(int(idx))
823
+ if len(selected) >= quota_quality:
824
+ break
825
+ while len(selected) < target_count:
826
+ if not selected:
827
+ break
828
+ chosen = torch.tensor(selected, dtype=torch.long, device=dist.device)
829
+ min_dist = dist[:, chosen].min(dim=1).values
830
+ refill_score = min_dist - 0.35 * _normalize_01(score)
831
+ added = False
832
+ for idx in torch.argsort(refill_score, descending=True).detach().cpu().tolist():
833
+ idx = int(idx)
834
+ if idx not in selected:
835
+ selected.append(idx)
836
+ added = True
837
+ break
838
+ if not added:
839
+ break
840
+ if len(selected) < target_count:
841
+ for idx in torch.argsort(score).detach().cpu().tolist():
842
+ idx = int(idx)
843
+ if idx not in selected:
844
+ selected.append(idx)
845
+ if len(selected) >= target_count:
846
+ break
847
+ return pool[torch.tensor(selected[:target_count], dtype=torch.long)]
848
+
849
+
850
+ def select_final_conformers(sample, target_count, mol, heavy_mask, args):
851
+ if sample is None:
852
+ return None
853
+ pool = sample["confs"] if isinstance(sample, dict) else sample
854
+ target_count = max(1, int(target_count))
855
+ mode = str(getattr(args, "select_candidates", "none"))
856
+ if mode == "none":
857
+ return pool[:target_count]
858
+ if mode == "modecover" and isinstance(sample, dict):
859
+ return select_modecover_conformers(
860
+ pool,
861
+ sample["mode_ids"],
862
+ sample["mode_weights"],
863
+ sample.get("mode_adherence"),
864
+ target_count,
865
+ mol,
866
+ heavy_mask,
867
+ args,
868
+ )
869
+ if mode == "mode_precision" and isinstance(sample, dict):
870
+ return select_mode_precision_conformers(
871
+ pool,
872
+ sample["mode_ids"],
873
+ sample["mode_weights"],
874
+ sample.get("mode_adherence"),
875
+ target_count,
876
+ mol,
877
+ heavy_mask,
878
+ args,
879
+ )
880
+ if mode == "cluster_quality" and isinstance(sample, dict):
881
+ return select_cluster_quality_conformers(
882
+ pool,
883
+ sample["mode_ids"],
884
+ sample["mode_weights"],
885
+ sample.get("mode_adherence"),
886
+ target_count,
887
+ mol,
888
+ heavy_mask,
889
+ args,
890
+ )
891
+ return select_precision_subset(pool, target_count, mol, heavy_mask, args)
892
+
893
+
894
+ def _write_xyz(path, coords, mol):
895
+ atoms = [atom.GetSymbol() for atom in mol.GetAtoms()]
896
+ xyz = coords.detach().cpu().float().numpy()
897
+ with open(path, "w") as handle:
898
+ handle.write(f"{len(atoms)}\n")
899
+ handle.write("mixture torsion-flow conformer\n")
900
+ for symbol, row in zip(atoms, xyz):
901
+ handle.write(f"{symbol} {row[0]:.10f} {row[1]:.10f} {row[2]:.10f}\n")
902
+
903
+
904
+ def _read_xyz_coords(path, dtype):
905
+ with open(path) as handle:
906
+ lines = handle.readlines()[2:]
907
+ coords = []
908
+ for line in lines:
909
+ parts = line.split()
910
+ if len(parts) >= 4:
911
+ coords.append([float(parts[1]), float(parts[2]), float(parts[3])])
912
+ return torch.tensor(coords, dtype=dtype)
913
+
914
+
915
+ def relax_with_gfn2_xtb(confs, mol, args):
916
+ """Run external xTB GFN2 geometry optimization on final conformers.
917
+
918
+ This is intentionally a final-evaluation option. It requires the ``xtb``
919
+ executable and should be reported as an xTB-relaxed protocol, not mixed
920
+ silently with the native model output.
921
+ """
922
+ if not bool(getattr(args, "xtb_relax", False)):
923
+ return confs
924
+ command = shutil.which(str(getattr(args, "xtb_command", "xtb")))
925
+ if command is None:
926
+ raise RuntimeError("xTB relaxation requested but xtb executable was not found on PATH.")
927
+ max_confs = int(getattr(args, "xtb_max_confs", 0))
928
+ limit = int(confs.size(0)) if max_confs <= 0 else min(int(max_confs), int(confs.size(0)))
929
+ relaxed = []
930
+ charge = Chem.GetFormalCharge(mol) if mol is not None else 0
931
+ for idx, conf in enumerate(confs):
932
+ if idx >= limit:
933
+ relaxed.append(conf.detach().cpu())
934
+ continue
935
+ with tempfile.TemporaryDirectory(prefix="manimol_xtb_") as tmp:
936
+ inp = os.path.join(tmp, "input.xyz")
937
+ _write_xyz(inp, conf, mol)
938
+ cmd = [command, inp, "--gfn", "2", "--opt", "tight", "--chrg", str(int(charge))]
939
+ result = subprocess.run(cmd, cwd=tmp, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
940
+ out = os.path.join(tmp, "xtbopt.xyz")
941
+ if result.returncode != 0 or not os.path.exists(out):
942
+ relaxed.append(conf.detach().cpu())
943
+ continue
944
+ coords = _read_xyz_coords(out, conf.dtype)
945
+ if coords.shape == conf.detach().cpu().shape:
946
+ relaxed.append(coords)
947
+ else:
948
+ relaxed.append(conf.detach().cpu())
949
+ return torch.stack(relaxed, dim=0)
950
+
951
+
952
+ def main():
953
+ args = parse_args()
954
+ torch.manual_seed(args.seed)
955
+ args.device = "cuda" if args.device == "auto" and torch.cuda.is_available() else args.device
956
+ device = torch.device(args.device)
957
+ os.makedirs(args.output_dir, exist_ok=True)
958
+ thresholds = [float(x) for x in args.cov_thresholds.split(",")]
959
+
960
+ data = QM9Dataset(name=args.dataset, root=args.data_root, max_confs=args.max_confs, raw_prefix=args.raw_prefix)
961
+ subset = data[get_split_indices(data, args.split)]
962
+ refs = infer_base_conformers.build_raw_reference_groups(infer_base_conformers.raw_reference_path(args, data), subset)
963
+ base = load_base(args.base_checkpoint, device)
964
+ flow_model = load_flow(args.flow_checkpoint, device)
965
+ post_denoiser = load_optional_post_denoiser(args.post_denoiser_checkpoint, device)
966
+
967
+ metrics = {
968
+ t: {
969
+ key: []
970
+ for key in [
971
+ "raw_covr",
972
+ "raw_amrr",
973
+ "final_covr",
974
+ "final_amrr",
975
+ "covp",
976
+ "amrp",
977
+ "oracle_covp",
978
+ "oracle_amrp",
979
+ ]
980
+ }
981
+ for t in thresholds
982
+ }
983
+ rows, chemistry, seen = [], [], set()
984
+ loader = DataLoader(subset, batch_size=args.batch_size, shuffle=False)
985
+ for batch in tqdm(loader, desc="Mixture torsion-flow evaluation"):
986
+ batch = batch.to(device)
987
+ for gi in range(batch.num_graphs):
988
+ key = infer_base_conformers.get_batch_mol_key(batch, gi)
989
+ if key in seen or key not in refs:
990
+ continue
991
+ reference = infer_base_conformers.subset_reference_group(refs[key], subset=args.ref_subset, top_k=args.ref_top_k)
992
+ target = torch.stack(reference["confs"]).float()
993
+ protocol_count = max(1, int(math.ceil(float(args.sample_multiplier) * target.size(0))))
994
+ final_count = protocol_count
995
+ if int(getattr(args, "max_output_confs", 0)) > 0:
996
+ final_count = min(final_count, int(getattr(args, "max_output_confs", 0)))
997
+ pool_count = max(final_count, int(math.ceil(protocol_count * max(1.0, float(args.oversample_factor)))))
998
+ sample = sample_for_graph(base, flow_model, post_denoiser, batch, gi, pool_count, args)
999
+ if sample is None:
1000
+ continue
1001
+ pool = sample["confs"] if isinstance(sample, dict) else sample
1002
+ pred = select_final_conformers(
1003
+ sample,
1004
+ final_count,
1005
+ batch.rdmol[gi] if hasattr(batch, "rdmol") else None,
1006
+ reference.get("heavy_mask"),
1007
+ args,
1008
+ )
1009
+ if pred is None or pred.numel() == 0:
1010
+ continue
1011
+ if bool(getattr(args, "xtb_relax", False)):
1012
+ pred = relax_with_gfn2_xtb(pred, batch.rdmol[gi], args)
1013
+ rmsd_final = infer_base_conformers.compute_rmsd_matrix(pred, target, heavy_mask=reference.get("heavy_mask"))
1014
+ rmsd_pool = infer_base_conformers.compute_rmsd_matrix(pool, target, heavy_mask=reference.get("heavy_mask"))
1015
+ pool_nearest = rmsd_pool.min(dim=1).values
1016
+ oracle_idx = torch.argsort(pool_nearest)[: int(pred.size(0))]
1017
+ oracle_nearest = pool_nearest[oracle_idx]
1018
+ seen.add(key)
1019
+ for threshold in thresholds:
1020
+ raw_covr, raw_amrr, _, _ = infer_base_conformers.evaluate_metrics_from_rmsd(rmsd_pool, threshold)
1021
+ final_covr, final_amrr, covp, amrp = infer_base_conformers.evaluate_metrics_from_rmsd(rmsd_final, threshold)
1022
+ oracle_covp = float((oracle_nearest <= float(threshold)).float().mean().item()) if oracle_nearest.numel() else 0.0
1023
+ oracle_amrp = float(oracle_nearest.mean().item()) if oracle_nearest.numel() else 0.0
1024
+ report_covr = raw_covr if str(getattr(args, "metric_recall_pool", "final")) == "generated" else final_covr
1025
+ report_amrr = raw_amrr if str(getattr(args, "metric_recall_pool", "final")) == "generated" else final_amrr
1026
+ metrics[threshold]["raw_covr"].append(raw_covr)
1027
+ metrics[threshold]["raw_amrr"].append(raw_amrr)
1028
+ metrics[threshold]["final_covr"].append(final_covr)
1029
+ metrics[threshold]["final_amrr"].append(final_amrr)
1030
+ metrics[threshold]["covp"].append(covp)
1031
+ metrics[threshold]["amrp"].append(amrp)
1032
+ metrics[threshold]["oracle_covp"].append(oracle_covp)
1033
+ metrics[threshold]["oracle_amrp"].append(oracle_amrp)
1034
+ rows.append({
1035
+ "molecule": str(key),
1036
+ "threshold": threshold,
1037
+ "cov_r": report_covr,
1038
+ "amr_r": report_amrr,
1039
+ "raw_pool_cov_r": raw_covr,
1040
+ "raw_pool_amr_r": raw_amrr,
1041
+ "final_cov_r": final_covr,
1042
+ "final_amr_r": final_amrr,
1043
+ "cov_p": covp,
1044
+ "amr_p": amrp,
1045
+ "oracle_pool_cov_p": oracle_covp,
1046
+ "oracle_pool_amr_p": oracle_amrp,
1047
+ "selector_oracle_cov_p_gap": oracle_covp - covp,
1048
+ "selector_oracle_amr_p_gap": amrp - oracle_amrp,
1049
+ "n_ref": int(target.size(0)),
1050
+ "n_pred": int(pred.size(0)),
1051
+ "n_pool": int(pool.size(0)),
1052
+ })
1053
+ if args.revisited_metrics_csv and hasattr(batch, "rdmol"):
1054
+ item = infer_base_conformers.compute_revisited_metrics_for_molecule(pred, target, rmsd_final, batch.rdmol[gi], heavy_mask=reference.get("heavy_mask"))
1055
+ if item:
1056
+ item["molecule"] = str(key)
1057
+ chemistry.append(item)
1058
+ if args.limit_molecules > 0 and len(seen) >= args.limit_molecules:
1059
+ break
1060
+ if args.limit_molecules > 0 and len(seen) >= args.limit_molecules:
1061
+ break
1062
+
1063
+ curve = []
1064
+ for threshold in thresholds:
1065
+ item = {"threshold": threshold}
1066
+ for title, key in [
1067
+ ("raw COV-R", "raw_covr"),
1068
+ ("raw AMR-R", "raw_amrr"),
1069
+ ("final COV-R", "final_covr"),
1070
+ ("final AMR-R", "final_amrr"),
1071
+ ("COV-P", "covp"),
1072
+ ("AMR-P", "amrp"),
1073
+ ("oracle COV-P", "oracle_covp"),
1074
+ ("oracle AMR-P", "oracle_amrp"),
1075
+ ]:
1076
+ item[title], item[f"{title} median"] = infer_base_conformers.mean_median(metrics[threshold][key])
1077
+ item["COV-R"] = item["raw COV-R"] if str(getattr(args, "metric_recall_pool", "final")) == "generated" else item["final COV-R"]
1078
+ item["AMR-R"] = item["raw AMR-R"] if str(getattr(args, "metric_recall_pool", "final")) == "generated" else item["final AMR-R"]
1079
+ curve.append(item)
1080
+ print("threshold={:.2f} COV-R={:.4f} AMR-R={:.4f} COV-P={:.4f} AMR-P={:.4f}".format(threshold, item["COV-R"], item["AMR-R"], item["COV-P"], item["AMR-P"]))
1081
+
1082
+ for path, output in [(args.per_molecule_csv, rows), (args.threshold_curve_csv, curve), (args.revisited_metrics_csv, chemistry)]:
1083
+ if path and output:
1084
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
1085
+ with open(path, "w", newline="") as handle:
1086
+ writer = csv.DictWriter(handle, fieldnames=list(output[0]))
1087
+ writer.writeheader()
1088
+ writer.writerows(output)
1089
+ print(f"Saved: {path}")
1090
+
1091
+
1092
+ if __name__ == "__main__":
1093
+ main()