dualmapref 0.2.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- args_parse.py +593 -0
- candidate_corrector.py +161 -0
- candidate_scorer.py +359 -0
- conformend/__init__.py +36 -0
- conformend/refiner.py +25 -0
- dataset/__init__.py +1 -0
- dataset/drugdataset.py +644 -0
- dataset/manifold.py +237 -0
- dataset/sharded_drugdataset.py +124 -0
- dataset/smiles2graph.py +217 -0
- dualmapref/__init__.py +24 -0
- dualmapref/refiner.py +16 -0
- dualmapref-0.2.8.dist-info/LICENSE +21 -0
- dualmapref-0.2.8.dist-info/METADATA +167 -0
- dualmapref-0.2.8.dist-info/RECORD +186 -0
- dualmapref-0.2.8.dist-info/WHEEL +5 -0
- dualmapref-0.2.8.dist-info/entry_points.txt +10 -0
- dualmapref-0.2.8.dist-info/top_level.txt +29 -0
- exputils.py +289 -0
- infer.py +23 -0
- infer_base_conformers.py +5589 -0
- infer_mean_dispersion_torsion.py +1117 -0
- infer_torsion.py +752 -0
- infer_torsional_denoiser.py +1021 -0
- manimol/__init__.py +30 -0
- manimol/__main__.py +6 -0
- manimol/cli.py +36 -0
- manimol/full_cli.py +41 -0
- manimol/legacy_imports.py +43 -0
- manimol/manifest.py +56 -0
- manimol/postprocess.py +148 -0
- manimol/priors.py +60 -0
- manimol/protocols.py +119 -0
- manimol/refiner.py +645 -0
- manimol/runtime.py +194 -0
- manimol/selection.py +85 -0
- manimol/torsion.py +22 -0
- manimol/train_cli.py +14 -0
- mixture_flow/src/__init__.py +1 -0
- mixture_flow/src/_path.py +7 -0
- mixture_flow/src/infer28_mixture_torsion_flow.py +1093 -0
- mixture_flow/src/mixture_torsion_flow.py +291 -0
- mixture_flow/src/summarize_mixture_debug.py +80 -0
- mixture_flow/src/train28_mixture_torsion_flow.py +583 -0
- mixture_torsion_flow.py +7 -0
- models/ manifold_learning.py +86 -0
- models/__init__.py +8 -0
- models/dist.py +273 -0
- models/dist2coords.py +23 -0
- models/egnn.py +107 -0
- models/experimental_backbones.py +364 -0
- models/gnnconv.py +512 -0
- models/kernel_inversion.py +141 -0
- models/kernels.py +427 -0
- models/losses.py +154 -0
- models/mean_dispersion_bridge.py +119 -0
- models/mean_dispersion_torsion_context.py +155 -0
- models/model.py +73 -0
- models/model0.py +2375 -0
- models/vis.py +128 -0
- pgraph_controls.py +107 -0
- scripts/__init__.py +2 -0
- scripts/analyze_basin_alignment.py +63 -0
- scripts/analyze_hif2a_conformer_aggregation.py +267 -0
- scripts/analyze_hif2a_contact_pharmacophore.py +1111 -0
- scripts/analyze_hif2a_fixed_budget.py +202 -0
- scripts/analyze_hif2a_pharmacophore.py +405 -0
- scripts/analyze_hif2a_pharmacophore_match_metric.py +386 -0
- scripts/analyze_p_control_candidate_flow.py +154 -0
- scripts/analyze_scaffold_basin.py +83 -0
- scripts/audit_dispersion_proposals.py +208 -0
- scripts/audit_etflow_protocol.py +258 -0
- scripts/audit_external_overlap.py +150 -0
- scripts/audit_oldbest_fulltrainval_split.py +82 -0
- scripts/audit_pdbbind_contact_pharmacophores.py +146 -0
- scripts/audit_qm9_geomol_test_split.py +94 -0
- scripts/audit_stage1_stage2_cross.py +131 -0
- scripts/build_geom_drugs_lowref_diagnostic.py +84 -0
- scripts/build_qm9_backfill_manifest.py +99 -0
- scripts/check_etflow_runtime.py +56 -0
- scripts/compare_prior_sources.py +122 -0
- scripts/compose_binding_mode_figure.py +87 -0
- scripts/compose_hif2a_contact_pharmacophore_suppfig.py +255 -0
- scripts/compose_hif2a_functional_geometry_pipeline.py +266 -0
- scripts/compose_manimol_internal_architecture.py +291 -0
- scripts/diagnose_flow_basin_intervention.py +54 -0
- scripts/diagnose_hif2a_pharmacophore_budget.py +185 -0
- scripts/diagnose_route2_p_ranking.py +123 -0
- scripts/discover_binding_mode_inputs.py +30 -0
- scripts/evaluate_functional_prior_stage1.py +230 -0
- scripts/evaluate_geomanimol.py +74 -0
- scripts/evaluate_geomanimol_flow.py +23 -0
- scripts/evaluate_geomanimol_multiscaffold.py +46 -0
- scripts/evaluate_geomanimol_residual.py +45 -0
- scripts/evaluate_geomanimol_torsion.py +40 -0
- scripts/evaluate_hif2a_bioactive_enrichment.py +91 -0
- scripts/evaluate_hif2a_pms_suite.py +440 -0
- scripts/evaluate_pdbbind_contact_pms.py +155 -0
- scripts/evaluate_platinum_external.py +114 -0
- scripts/evaluate_platinum_pool.py +82 -0
- scripts/evaluate_route2_calibrated_p.py +104 -0
- scripts/evaluate_route2_library_components.py +596 -0
- scripts/evaluate_route2_p_basin_budget.py +288 -0
- scripts/evaluate_stage1_checkpoint_only.py +30 -0
- scripts/export_dispersion_bond_audit.py +136 -0
- scripts/export_top20_shards.py +207 -0
- scripts/external_validation_metrics.py +152 -0
- scripts/fit_topology_prior.py +117 -0
- scripts/frozen_dispersion_audit.py +281 -0
- scripts/geomanimol_debug.py +50 -0
- scripts/geomanimol_smoke.py +37 -0
- scripts/infer_etflow_matched.py +524 -0
- scripts/inspect_checkpoint.py +12 -0
- scripts/inspect_conformer_capacity.py +71 -0
- scripts/inspect_pool.py +12 -0
- scripts/make_figure3_selection_loss.py +474 -0
- scripts/make_figure3_selection_summary.py +275 -0
- scripts/make_geom_debug_subset.py +62 -0
- scripts/make_low_reference_test_subset.py +70 -0
- scripts/merge_stage1_into_stage2.py +82 -0
- scripts/place_hif2a_candidates_for_evaluation.py +66 -0
- scripts/plot_hif2a_low_budget_efficiency.py +100 -0
- scripts/plot_prior_validation.py +48 -0
- scripts/precompute_stage2_assignments.py +90 -0
- scripts/prepare_bace_activity.py +98 -0
- scripts/prepare_bace_etkdg_benchmark.py +90 -0
- scripts/prepare_figure5_4x4_cases.py +470 -0
- scripts/prepare_geom_drugs_geomol_top20.py +472 -0
- scripts/prepare_pdbbind_core_raw.py +90 -0
- scripts/prepare_platinum_raw.py +74 -0
- scripts/prepare_pubchem_etkdg.py +54 -0
- scripts/rebuild_hif2a_final_sdf_and_metrics.py +55 -0
- scripts/rebuild_hif2a_fixed_pool_sweep.py +175 -0
- scripts/rebuild_hif2a_strict.py +220 -0
- scripts/recompute_hif2a_bootstrap.py +63 -0
- scripts/reference_free_geometry.py +112 -0
- scripts/render_binding_modes.py +413 -0
- scripts/render_figure5_4x4.py +330 -0
- scripts/render_figure6_pharmacophore_pymol.py +162 -0
- scripts/render_hif2a_contact_pharmacophore_pymol.py +414 -0
- scripts/render_hif2a_figure11.py +397 -0
- scripts/run_bace_2d_baseline.py +73 -0
- scripts/run_drugs_validation_matrix.py +225 -0
- scripts/run_external_reference_free.py +53 -0
- scripts/run_manimol_finalk_sensitivity.py +106 -0
- scripts/run_manimol_oversampling_sensitivity.py +109 -0
- scripts/run_pdisp_matched_intervention.py +116 -0
- scripts/run_stage1_stage2_cross20.py +83 -0
- scripts/score_hif2a_candidates_with_pgraph.py +221 -0
- scripts/summarize_dispersion_intervention.py +88 -0
- scripts/test_mean_dispersion_bridge.py +50 -0
- scripts/train_dispersion_head_diagnostic.py +320 -0
- scripts/train_dispersion_head_streaming.py +519 -0
- scripts/train_geomanimol.py +100 -0
- scripts/train_geomanimol_flow.py +26 -0
- scripts/train_geomanimol_residual.py +70 -0
- scripts/train_geomanimol_torsion.py +50 -0
- scripts/train_quantile_representation_diagnostic.py +204 -0
- scripts/validate_mean_dispersion_prior.py +173 -0
- scripts/validate_packed_shard.py +41 -0
- scripts/validate_stage1_prior.py +221 -0
- scripts/validate_top20_shards.py +36 -0
- scripts/validation/__init__.py +1 -0
- scripts/validation/hif2a_downstream_baselines.py +105 -0
- scripts/validation/hif2a_pairwise_ranker.py +218 -0
- scripts/verify_binding_mode_figure.py +47 -0
- torsion_manifold.py +281 -0
- train.py +78 -0
- train_graph_encoder.py +206 -0
- train_local_torsion_corrector.py +511 -0
- train_mean_dispersion_torsion_prior.py +329 -0
- train_probability_basin.py +235 -0
- train_torsion_generator.py +1631 -0
- train_torsion_manifold_prior.py +258 -0
- train_torsional_denoiser.py +415 -0
- trainer.py +1038 -0
- utils/__init__.py +7 -0
- utils/checkpoint.py +40 -0
- utils/device.py +17 -0
- utils/helpers.py +98 -0
- utils/kabsch.py +29 -0
- utils/lookup_table.py +164 -0
- utils/metrics.py +50 -0
- utils/optuna.py +111 -0
- utils/save_mol.py +366 -0
- utils/util.py +36 -0
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Factorized evaluation of candidate allocation, selection, and preparation.
|
|
3
|
+
|
|
4
|
+
The input is an inference-time raw-pool export. Every non-oracle selector is
|
|
5
|
+
reference-free; reference conformers are read only after the final set has been
|
|
6
|
+
constructed to compute COV/AMR. This keeps the three library-construction
|
|
7
|
+
stages auditable under one fixed 30R -> 2R protocol.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import csv
|
|
14
|
+
import json
|
|
15
|
+
import math
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import torch
|
|
21
|
+
from tqdm import tqdm
|
|
22
|
+
|
|
23
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
24
|
+
import infer_base_conformers
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def parse_args():
|
|
28
|
+
parser = argparse.ArgumentParser()
|
|
29
|
+
parser.add_argument("--fixed_dump_name", action="store_true")
|
|
30
|
+
parser.add_argument("--pool_pt", required=True)
|
|
31
|
+
parser.add_argument("--allocation_label", default="P-on")
|
|
32
|
+
parser.add_argument("--selectors", default="random,diverse,density,precision2r")
|
|
33
|
+
parser.add_argument("--preparations", default="raw,mmff94s,mmff94s_energy_cluster")
|
|
34
|
+
parser.add_argument("--threshold", type=float, default=0.75)
|
|
35
|
+
parser.add_argument("--budget_multiplier", type=float, default=2.0)
|
|
36
|
+
parser.add_argument("--max_molecules", type=int, default=0)
|
|
37
|
+
parser.add_argument(
|
|
38
|
+
"--candidate_pool_cap",
|
|
39
|
+
type=int,
|
|
40
|
+
default=0,
|
|
41
|
+
help="Deterministic diagnostic cap on candidates per molecule; zero keeps the complete pool.",
|
|
42
|
+
)
|
|
43
|
+
parser.add_argument(
|
|
44
|
+
"--reference_limit",
|
|
45
|
+
type=int,
|
|
46
|
+
default=0,
|
|
47
|
+
help="Diagnostic cap on reference conformers per molecule; zero keeps all references.",
|
|
48
|
+
)
|
|
49
|
+
parser.add_argument("--seed", type=int, default=20260820)
|
|
50
|
+
parser.add_argument("--rmsd_backend", choices=["kabsch", "kabsch_atom", "rdkit_best"], default="rdkit_best")
|
|
51
|
+
parser.add_argument(
|
|
52
|
+
"--selection_rmsd_backend",
|
|
53
|
+
choices=["kabsch", "kabsch_atom", "rdkit_best"],
|
|
54
|
+
default="kabsch",
|
|
55
|
+
help="Fast metric for internal clustering; final COV/AMR still uses --rmsd_backend.",
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument("--rdkit_max_matches", type=int, default=1000000)
|
|
58
|
+
parser.add_argument("--mmff_steps", type=int, default=200)
|
|
59
|
+
parser.add_argument("--energy_window", type=float, default=6.0)
|
|
60
|
+
parser.add_argument("--cluster_rmsd", type=float, default=0.5)
|
|
61
|
+
parser.add_argument("--preparation_pool_factor", type=float, default=3.0)
|
|
62
|
+
parser.add_argument("--preparation_pool_cap", type=int, default=256)
|
|
63
|
+
parser.add_argument(
|
|
64
|
+
"--raw_fraction",
|
|
65
|
+
type=float,
|
|
66
|
+
default=0.5,
|
|
67
|
+
help="Final-budget fraction reserved for unrelaxed coverage anchors in raw_mmff94s_quota.",
|
|
68
|
+
)
|
|
69
|
+
parser.add_argument(
|
|
70
|
+
"--mmff_guard_rmsd",
|
|
71
|
+
type=float,
|
|
72
|
+
default=0.25,
|
|
73
|
+
help="Keep the raw conformer when MMFF relaxation moves it farther than this RMSD.",
|
|
74
|
+
)
|
|
75
|
+
parser.add_argument("--output_prefix", required=True)
|
|
76
|
+
return parser.parse_args()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def random_select(pool, budget, generator):
|
|
80
|
+
order = torch.randperm(pool.size(0), generator=generator)
|
|
81
|
+
return pool[order[:budget]]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def incremental_fps_select(pool, budget, record):
|
|
85
|
+
"""Greedy farthest-point sampling without materializing an NxN RMSD matrix."""
|
|
86
|
+
budget = min(int(budget), int(pool.size(0)))
|
|
87
|
+
if budget <= 0:
|
|
88
|
+
return pool[:0]
|
|
89
|
+
|
|
90
|
+
heavy_mask = record.get("heavy_mask")
|
|
91
|
+
mol = record.get("mol")
|
|
92
|
+
# A deterministic first anchor keeps paired control runs reproducible.
|
|
93
|
+
selected = [0]
|
|
94
|
+
min_distance = infer_base_conformers.compute_rmsd_matrix(
|
|
95
|
+
pool, pool[:1], heavy_mask=heavy_mask, mol=mol, backend="kabsch"
|
|
96
|
+
).reshape(-1)
|
|
97
|
+
min_distance[0] = -1.0
|
|
98
|
+
while len(selected) < budget:
|
|
99
|
+
index = int(torch.argmax(min_distance).item())
|
|
100
|
+
selected.append(index)
|
|
101
|
+
distance = infer_base_conformers.compute_rmsd_matrix(
|
|
102
|
+
pool,
|
|
103
|
+
pool[index:index + 1],
|
|
104
|
+
heavy_mask=heavy_mask,
|
|
105
|
+
mol=mol,
|
|
106
|
+
backend="kabsch",
|
|
107
|
+
).reshape(-1)
|
|
108
|
+
min_distance = torch.minimum(min_distance, distance)
|
|
109
|
+
min_distance[torch.tensor(selected, dtype=torch.long)] = -1.0
|
|
110
|
+
return pool[torch.tensor(selected, dtype=torch.long)]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def reference_oracle_select(pool, budget, record):
|
|
114
|
+
"""Diagnostic upper bound: cover references first, then fill by precision."""
|
|
115
|
+
reference = record.get("_reference_confs")
|
|
116
|
+
if reference is None:
|
|
117
|
+
raise ValueError("reference_oracle requires record['_reference_confs']")
|
|
118
|
+
budget = min(int(budget), int(pool.size(0)))
|
|
119
|
+
rmsd = infer_base_conformers.compute_rmsd_matrix(
|
|
120
|
+
pool,
|
|
121
|
+
reference,
|
|
122
|
+
heavy_mask=record.get("heavy_mask"),
|
|
123
|
+
mol=record.get("mol"),
|
|
124
|
+
backend="kabsch",
|
|
125
|
+
)
|
|
126
|
+
chosen = []
|
|
127
|
+
# Preserve the best available candidate for every reference state.
|
|
128
|
+
for index in torch.argmin(rmsd, dim=0).tolist():
|
|
129
|
+
index = int(index)
|
|
130
|
+
if index not in chosen:
|
|
131
|
+
chosen.append(index)
|
|
132
|
+
if len(chosen) >= budget:
|
|
133
|
+
break
|
|
134
|
+
# Fill the remaining budget with candidates closest to any reference.
|
|
135
|
+
if len(chosen) < budget:
|
|
136
|
+
for index in torch.argsort(rmsd.min(dim=1).values).tolist():
|
|
137
|
+
index = int(index)
|
|
138
|
+
if index not in chosen:
|
|
139
|
+
chosen.append(index)
|
|
140
|
+
if len(chosen) >= budget:
|
|
141
|
+
break
|
|
142
|
+
return pool[torch.tensor(chosen[:budget], dtype=torch.long)]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def support_medoid_select(pool, budget, record, support_power=0.5, iterations=2):
|
|
146
|
+
"""Select supported mode centers instead of isolated farthest points.
|
|
147
|
+
|
|
148
|
+
Farthest-point sampling spends budget on geometric outliers, while a pure
|
|
149
|
+
density score collapses rare but reproducible modes. This selector seeds
|
|
150
|
+
centers by distance times local support, then replaces every seed by the
|
|
151
|
+
medoid of its assigned candidate neighborhood.
|
|
152
|
+
"""
|
|
153
|
+
budget = min(int(budget), int(pool.size(0)))
|
|
154
|
+
if budget <= 0:
|
|
155
|
+
return pool[:0]
|
|
156
|
+
if budget == pool.size(0):
|
|
157
|
+
return pool
|
|
158
|
+
|
|
159
|
+
# Use the same fast torsion-aware geometry used by the production
|
|
160
|
+
# precision selector. Pairwise Kabsch is quadratic in Python and makes
|
|
161
|
+
# large oversampled pools impractical; final metrics remain symmetry-aware.
|
|
162
|
+
distance = infer_base_conformers._pairwise_torsion_signature_distance(
|
|
163
|
+
pool,
|
|
164
|
+
record.get("mol"),
|
|
165
|
+
fallback_metric="centered_rmsd",
|
|
166
|
+
heavy_mask=record.get("heavy_mask"),
|
|
167
|
+
).float()
|
|
168
|
+
n = int(pool.size(0))
|
|
169
|
+
neighbor_k = min(max(3, int(round(math.sqrt(n)))), n - 1)
|
|
170
|
+
local_radius = torch.topk(distance, k=neighbor_k + 1, largest=False, dim=1).values[:, -1]
|
|
171
|
+
scale = torch.median(local_radius).clamp_min(1e-6)
|
|
172
|
+
support = torch.exp(-local_radius / scale).clamp_min(1e-6)
|
|
173
|
+
|
|
174
|
+
centers = [int(torch.argmax(support).item())]
|
|
175
|
+
min_distance = distance[centers[0]].clone()
|
|
176
|
+
while len(centers) < budget:
|
|
177
|
+
score = min_distance * support.pow(float(support_power))
|
|
178
|
+
score[torch.tensor(centers, dtype=torch.long)] = -1.0
|
|
179
|
+
index = int(torch.argmax(score).item())
|
|
180
|
+
centers.append(index)
|
|
181
|
+
min_distance = torch.minimum(min_distance, distance[index])
|
|
182
|
+
|
|
183
|
+
for _ in range(max(0, int(iterations))):
|
|
184
|
+
center_tensor = torch.tensor(centers, dtype=torch.long)
|
|
185
|
+
assignment = torch.argmin(distance[:, center_tensor], dim=1)
|
|
186
|
+
updated = []
|
|
187
|
+
used = set()
|
|
188
|
+
for cluster_id in range(len(centers)):
|
|
189
|
+
members = torch.nonzero(assignment == cluster_id, as_tuple=False).reshape(-1)
|
|
190
|
+
if members.numel() == 0:
|
|
191
|
+
candidate = centers[cluster_id]
|
|
192
|
+
else:
|
|
193
|
+
within = distance[members][:, members]
|
|
194
|
+
# Mild support preference breaks ties toward stable local modes.
|
|
195
|
+
cost = within.mean(dim=1) / support[members].pow(0.25)
|
|
196
|
+
candidate = int(members[int(torch.argmin(cost).item())].item())
|
|
197
|
+
if candidate in used:
|
|
198
|
+
remaining = [i for i in range(n) if i not in used]
|
|
199
|
+
candidate = max(remaining, key=lambda i: float(min(distance[i, j] for j in used)))
|
|
200
|
+
updated.append(candidate)
|
|
201
|
+
used.add(candidate)
|
|
202
|
+
if updated == centers:
|
|
203
|
+
break
|
|
204
|
+
centers = updated
|
|
205
|
+
return pool[torch.tensor(centers[:budget], dtype=torch.long)]
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def hybrid_core_mode_select(pool, budget, record, core_fraction):
|
|
209
|
+
"""Reserve high-confidence cores, then spend remaining budget on modes."""
|
|
210
|
+
budget = min(int(budget), int(pool.size(0)))
|
|
211
|
+
if budget <= 0:
|
|
212
|
+
return pool[:0]
|
|
213
|
+
core_count = max(1, min(budget, int(round(budget * float(core_fraction)))))
|
|
214
|
+
core = infer_base_conformers.select_precision2r_conformers(
|
|
215
|
+
pool,
|
|
216
|
+
core_count,
|
|
217
|
+
mol=record.get("mol"),
|
|
218
|
+
heavy_mask=record.get("heavy_mask"),
|
|
219
|
+
metric="centered_rmsd",
|
|
220
|
+
density_k=20,
|
|
221
|
+
prefilter_quantile=0.45,
|
|
222
|
+
density_weight=1.0,
|
|
223
|
+
centrality_weight=0.45,
|
|
224
|
+
duplicate_radius=0.04,
|
|
225
|
+
)
|
|
226
|
+
modes = support_medoid_select(pool, budget, record, support_power=1.0)
|
|
227
|
+
|
|
228
|
+
selected = []
|
|
229
|
+
seen = set()
|
|
230
|
+
for row in torch.cat([core, modes, pool], dim=0):
|
|
231
|
+
# Both component selectors return unchanged rows from the input pool.
|
|
232
|
+
diffs = (pool - row.unsqueeze(0)).abs().sum(dim=(1, 2))
|
|
233
|
+
index = int(torch.argmin(diffs).item())
|
|
234
|
+
if index not in seen:
|
|
235
|
+
selected.append(index)
|
|
236
|
+
seen.add(index)
|
|
237
|
+
if len(selected) >= budget:
|
|
238
|
+
break
|
|
239
|
+
return pool[torch.tensor(selected[:budget], dtype=torch.long)]
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def select(pool, budget, record, method, generator):
|
|
243
|
+
budget = min(int(budget), int(pool.size(0)))
|
|
244
|
+
heavy_mask = record.get("heavy_mask")
|
|
245
|
+
mol = record.get("mol")
|
|
246
|
+
if method == "all":
|
|
247
|
+
return pool[:budget]
|
|
248
|
+
if method == "random":
|
|
249
|
+
return random_select(pool, budget, generator)
|
|
250
|
+
if method == "fps":
|
|
251
|
+
return incremental_fps_select(pool, budget, record)
|
|
252
|
+
if method == "reference_oracle":
|
|
253
|
+
return reference_oracle_select(pool, budget, record)
|
|
254
|
+
if method == "support_medoid_025":
|
|
255
|
+
return support_medoid_select(pool, budget, record, support_power=0.25)
|
|
256
|
+
if method == "support_medoid_050":
|
|
257
|
+
return support_medoid_select(pool, budget, record, support_power=0.50)
|
|
258
|
+
if method == "support_medoid_100":
|
|
259
|
+
return support_medoid_select(pool, budget, record, support_power=1.00)
|
|
260
|
+
if method == "hybrid_core_025":
|
|
261
|
+
return hybrid_core_mode_select(pool, budget, record, core_fraction=0.25)
|
|
262
|
+
if method == "hybrid_core_050":
|
|
263
|
+
return hybrid_core_mode_select(pool, budget, record, core_fraction=0.50)
|
|
264
|
+
if method == "hybrid_core_075":
|
|
265
|
+
return hybrid_core_mode_select(pool, budget, record, core_fraction=0.75)
|
|
266
|
+
if method == "diverse":
|
|
267
|
+
return infer_base_conformers.select_diverse_conformers(pool, budget, heavy_mask=heavy_mask, metric="kabsch")
|
|
268
|
+
if method == "density":
|
|
269
|
+
return infer_base_conformers.select_precision2r_conformers(
|
|
270
|
+
pool, budget, mol=mol, heavy_mask=heavy_mask, metric="kabsch",
|
|
271
|
+
density_k=20, prefilter_quantile=1.0, density_weight=1.0,
|
|
272
|
+
centrality_weight=0.45, duplicate_radius=0.0,
|
|
273
|
+
)
|
|
274
|
+
if method == "precision2r":
|
|
275
|
+
return infer_base_conformers.select_precision2r_conformers(
|
|
276
|
+
pool, budget, mol=mol, heavy_mask=heavy_mask, metric="kabsch",
|
|
277
|
+
density_k=20, prefilter_quantile=0.45, density_weight=1.0,
|
|
278
|
+
centrality_weight=0.45, duplicate_radius=0.04,
|
|
279
|
+
)
|
|
280
|
+
if method in {"precision_tight_050", "precision_tight_100", "precision_tight_200"}:
|
|
281
|
+
tight_weight = {
|
|
282
|
+
"precision_tight_050": 0.50,
|
|
283
|
+
"precision_tight_100": 1.00,
|
|
284
|
+
"precision_tight_200": 2.00,
|
|
285
|
+
}[method]
|
|
286
|
+
return infer_base_conformers.select_precision2r_conformers(
|
|
287
|
+
pool, budget, mol=mol, heavy_mask=heavy_mask, metric="centered_rmsd",
|
|
288
|
+
density_k=20, prefilter_quantile=0.30, density_weight=1.0,
|
|
289
|
+
centrality_weight=0.65, duplicate_radius=0.02,
|
|
290
|
+
tight_k=5, tight_weight=tight_weight,
|
|
291
|
+
)
|
|
292
|
+
raise ValueError(f"Unknown selector: {method}")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def optimize_mmff(conformers, mol, steps):
|
|
296
|
+
optimized, energies, successes = [], [], 0
|
|
297
|
+
for conformer in conformers:
|
|
298
|
+
coords, energy, success = infer_base_conformers.optimize_with_mmff94s_and_energy(conformer, mol, max_steps=steps)
|
|
299
|
+
optimized.append(coords.cpu())
|
|
300
|
+
energies.append(float(energy))
|
|
301
|
+
successes += int(success)
|
|
302
|
+
return torch.stack(optimized), torch.tensor(energies, dtype=torch.float32), successes
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def align_to_anchor(moving, anchor, heavy_mask=None):
|
|
306
|
+
"""Rigidly align an optimized conformer before Cartesian interpolation."""
|
|
307
|
+
if heavy_mask is None:
|
|
308
|
+
mask = torch.ones(anchor.size(0), dtype=torch.bool)
|
|
309
|
+
else:
|
|
310
|
+
mask = torch.as_tensor(heavy_mask, dtype=torch.bool)
|
|
311
|
+
source = moving[mask].float()
|
|
312
|
+
target = anchor[mask].float()
|
|
313
|
+
source_center = source.mean(dim=0)
|
|
314
|
+
target_center = target.mean(dim=0)
|
|
315
|
+
covariance = (source - source_center).transpose(0, 1) @ (target - target_center)
|
|
316
|
+
u, _, vh = torch.linalg.svd(covariance)
|
|
317
|
+
rotation = u @ vh
|
|
318
|
+
if torch.det(rotation) < 0:
|
|
319
|
+
u = u.clone()
|
|
320
|
+
u[:, -1] *= -1
|
|
321
|
+
rotation = u @ vh
|
|
322
|
+
return (moving.float() - source_center) @ rotation + target_center
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def restrained_mmff(chosen, mol, heavy_mask, steps, fraction):
|
|
326
|
+
"""Take only a controlled fraction of the MMFF displacement."""
|
|
327
|
+
optimized, energies, successes = optimize_mmff(chosen, mol, steps)
|
|
328
|
+
blended = []
|
|
329
|
+
displacements = []
|
|
330
|
+
for anchor, relaxed in zip(chosen, optimized):
|
|
331
|
+
aligned = align_to_anchor(relaxed, anchor, heavy_mask)
|
|
332
|
+
delta = aligned - anchor.float()
|
|
333
|
+
blended.append(anchor.float() + float(fraction) * delta)
|
|
334
|
+
displacements.append(float(torch.linalg.vector_norm(delta, dim=-1).mean()))
|
|
335
|
+
return (
|
|
336
|
+
torch.stack(blended),
|
|
337
|
+
energies,
|
|
338
|
+
successes,
|
|
339
|
+
float(np.mean(displacements)) if displacements else 0.0,
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def cluster_energy_ordered(conformers, energies, record, budget, threshold, backend, max_matches):
|
|
344
|
+
finite = torch.isfinite(energies)
|
|
345
|
+
if finite.any():
|
|
346
|
+
minimum = energies[finite].min()
|
|
347
|
+
in_window = finite & (energies <= minimum + 1e-8)
|
|
348
|
+
order = torch.argsort(energies)
|
|
349
|
+
else:
|
|
350
|
+
in_window = torch.ones_like(finite)
|
|
351
|
+
order = torch.arange(conformers.size(0))
|
|
352
|
+
|
|
353
|
+
# The caller stores the requested energy-window mask on the record-local
|
|
354
|
+
# namespace to keep this helper independent of CLI globals.
|
|
355
|
+
window = float(record["_energy_window"])
|
|
356
|
+
if finite.any():
|
|
357
|
+
in_window = finite & (energies <= energies[finite].min() + window)
|
|
358
|
+
eligible = [int(i) for i in order.tolist() if bool(in_window[i])]
|
|
359
|
+
fallback = [int(i) for i in order.tolist() if i not in set(eligible)]
|
|
360
|
+
|
|
361
|
+
rmsd = infer_base_conformers.compute_rmsd_matrix(
|
|
362
|
+
conformers, conformers, heavy_mask=record.get("heavy_mask"), mol=record.get("mol"),
|
|
363
|
+
backend=backend, rdkit_max_matches=max_matches,
|
|
364
|
+
)
|
|
365
|
+
selected = []
|
|
366
|
+
for index in eligible:
|
|
367
|
+
if all(float(rmsd[index, kept]) > threshold for kept in selected):
|
|
368
|
+
selected.append(index)
|
|
369
|
+
if len(selected) >= budget:
|
|
370
|
+
break
|
|
371
|
+
# Exact 2R output is part of the protocol. Backfill first with additional
|
|
372
|
+
# in-window conformers, then with the lowest-energy excluded conformers.
|
|
373
|
+
for index in eligible + fallback:
|
|
374
|
+
if index not in selected:
|
|
375
|
+
selected.append(index)
|
|
376
|
+
if len(selected) >= budget:
|
|
377
|
+
break
|
|
378
|
+
return conformers[torch.tensor(selected[:budget], dtype=torch.long)], len(eligible), len(set(selected[:budget]))
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def prepare(pool, budget, record, selector, preparation, generator, args):
|
|
382
|
+
if preparation == "raw":
|
|
383
|
+
return select(pool, budget, record, selector, generator), {"mmff_success": 0, "energy_window_kept": 0}
|
|
384
|
+
if preparation == "mmff94s":
|
|
385
|
+
chosen = select(pool, budget, record, selector, generator)
|
|
386
|
+
optimized, _, successes = optimize_mmff(chosen, record.get("mol"), args.mmff_steps)
|
|
387
|
+
return optimized, {"mmff_success": successes, "energy_window_kept": len(optimized)}
|
|
388
|
+
if preparation in {"mmff94s_restrained_010", "mmff94s_restrained_025"}:
|
|
389
|
+
fraction = 0.10 if preparation.endswith("010") else 0.25
|
|
390
|
+
chosen = select(pool, budget, record, selector, generator)
|
|
391
|
+
optimized, _, successes, mean_displacement = restrained_mmff(
|
|
392
|
+
chosen,
|
|
393
|
+
record.get("mol"),
|
|
394
|
+
record.get("heavy_mask"),
|
|
395
|
+
args.mmff_steps,
|
|
396
|
+
fraction,
|
|
397
|
+
)
|
|
398
|
+
return optimized, {
|
|
399
|
+
"mmff_success": successes,
|
|
400
|
+
"energy_window_kept": len(optimized),
|
|
401
|
+
"mmff_fraction": fraction,
|
|
402
|
+
"mmff_full_mean_displacement": mean_displacement,
|
|
403
|
+
}
|
|
404
|
+
if preparation == "mmff94s_guarded":
|
|
405
|
+
chosen = select(pool, budget, record, selector, generator)
|
|
406
|
+
optimized, _, successes = optimize_mmff(chosen, record.get("mol"), args.mmff_steps)
|
|
407
|
+
paired_rmsd = infer_base_conformers.compute_rmsd_matrix(
|
|
408
|
+
chosen,
|
|
409
|
+
optimized,
|
|
410
|
+
heavy_mask=record.get("heavy_mask"),
|
|
411
|
+
mol=record.get("mol"),
|
|
412
|
+
backend=args.selection_rmsd_backend,
|
|
413
|
+
rdkit_max_matches=args.rdkit_max_matches,
|
|
414
|
+
).diagonal()
|
|
415
|
+
accept = paired_rmsd <= float(args.mmff_guard_rmsd)
|
|
416
|
+
final = chosen.clone()
|
|
417
|
+
final[accept] = optimized[accept]
|
|
418
|
+
return final, {
|
|
419
|
+
"mmff_success": successes,
|
|
420
|
+
"energy_window_kept": int(accept.sum()),
|
|
421
|
+
"mmff_guard_accepted": int(accept.sum()),
|
|
422
|
+
}
|
|
423
|
+
if preparation == "mmff94s_energy_cluster":
|
|
424
|
+
pre_count = max(budget, int(math.ceil(budget * args.preparation_pool_factor)))
|
|
425
|
+
if args.preparation_pool_cap > 0:
|
|
426
|
+
pre_count = min(pre_count, max(budget, args.preparation_pool_cap))
|
|
427
|
+
pre_pool = select(pool, pre_count, record, selector, generator)
|
|
428
|
+
optimized, energies, successes = optimize_mmff(pre_pool, record.get("mol"), args.mmff_steps)
|
|
429
|
+
local_record = dict(record)
|
|
430
|
+
local_record["_energy_window"] = args.energy_window
|
|
431
|
+
final, window_kept, _ = cluster_energy_ordered(
|
|
432
|
+
optimized, energies, local_record, budget, args.cluster_rmsd,
|
|
433
|
+
args.selection_rmsd_backend, args.rdkit_max_matches,
|
|
434
|
+
)
|
|
435
|
+
return final, {"mmff_success": successes, "energy_window_kept": window_kept}
|
|
436
|
+
if preparation == "raw_mmff94s_union":
|
|
437
|
+
# MMFF can improve local geometry while contracting an ensemble toward
|
|
438
|
+
# a few low-energy basins. Keep the corresponding unrelaxed candidates
|
|
439
|
+
# in the decision set so that final selection can retain recall anchors.
|
|
440
|
+
pre_count = max(budget, int(math.ceil(budget * args.preparation_pool_factor)))
|
|
441
|
+
if args.preparation_pool_cap > 0:
|
|
442
|
+
pre_count = min(pre_count, max(budget, args.preparation_pool_cap))
|
|
443
|
+
raw_pre_pool = select(pool, pre_count, record, selector, generator)
|
|
444
|
+
optimized, energies, successes = optimize_mmff(
|
|
445
|
+
raw_pre_pool, record.get("mol"), args.mmff_steps
|
|
446
|
+
)
|
|
447
|
+
finite = torch.isfinite(energies)
|
|
448
|
+
if finite.any():
|
|
449
|
+
in_window = finite & (energies <= energies[finite].min() + args.energy_window)
|
|
450
|
+
optimized_for_union = optimized[in_window]
|
|
451
|
+
else:
|
|
452
|
+
in_window = torch.ones_like(finite)
|
|
453
|
+
optimized_for_union = optimized
|
|
454
|
+
union = torch.cat([raw_pre_pool, optimized_for_union], dim=0)
|
|
455
|
+
final = select(union, budget, record, selector, generator)
|
|
456
|
+
return final, {
|
|
457
|
+
"mmff_success": successes,
|
|
458
|
+
"energy_window_kept": int(in_window.sum()),
|
|
459
|
+
}
|
|
460
|
+
if preparation == "raw_mmff94s_quota":
|
|
461
|
+
# MMFF improves local geometry but can contract several conformational
|
|
462
|
+
# neighborhoods into the same low-energy basin. Reserve an explicit
|
|
463
|
+
# part of the final budget for diverse unrelaxed anchors, and use the
|
|
464
|
+
# remaining budget for energy-filtered relaxed representatives.
|
|
465
|
+
raw_budget = int(round(float(args.raw_fraction) * budget))
|
|
466
|
+
raw_budget = min(budget, max(0, raw_budget))
|
|
467
|
+
relaxed_budget = budget - raw_budget
|
|
468
|
+
|
|
469
|
+
pre_count = max(budget, int(math.ceil(budget * args.preparation_pool_factor)))
|
|
470
|
+
if args.preparation_pool_cap > 0:
|
|
471
|
+
pre_count = min(pre_count, max(budget, args.preparation_pool_cap))
|
|
472
|
+
pre_pool = select(pool, pre_count, record, selector, generator)
|
|
473
|
+
|
|
474
|
+
raw_final = select(pre_pool, raw_budget, record, "diverse", generator) if raw_budget else pre_pool[:0]
|
|
475
|
+
optimized, energies, successes = optimize_mmff(pre_pool, record.get("mol"), args.mmff_steps)
|
|
476
|
+
finite = torch.isfinite(energies)
|
|
477
|
+
if finite.any():
|
|
478
|
+
relaxed_eligible = optimized[finite & (energies <= energies[finite].min() + args.energy_window)]
|
|
479
|
+
else:
|
|
480
|
+
relaxed_eligible = optimized
|
|
481
|
+
if relaxed_eligible.size(0) == 0:
|
|
482
|
+
relaxed_eligible = optimized
|
|
483
|
+
|
|
484
|
+
relaxed_final = (
|
|
485
|
+
select(relaxed_eligible, relaxed_budget, record, "precision2r", generator)
|
|
486
|
+
if relaxed_budget else relaxed_eligible[:0]
|
|
487
|
+
)
|
|
488
|
+
final = torch.cat([raw_final, relaxed_final], dim=0)
|
|
489
|
+
if final.size(0) < budget:
|
|
490
|
+
backfill = select(pre_pool, budget, record, "diverse", generator)
|
|
491
|
+
final = torch.cat([final, backfill], dim=0)[:budget]
|
|
492
|
+
return final, {
|
|
493
|
+
"mmff_success": successes,
|
|
494
|
+
"energy_window_kept": int(relaxed_eligible.size(0)),
|
|
495
|
+
"raw_budget": int(raw_final.size(0)),
|
|
496
|
+
"relaxed_budget": int(relaxed_final.size(0)),
|
|
497
|
+
}
|
|
498
|
+
raise ValueError(f"Unknown preparation: {preparation}")
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def metrics(pred, ref, record, threshold, backend, max_matches):
|
|
502
|
+
rmsd = infer_base_conformers.compute_rmsd_matrix(
|
|
503
|
+
pred, ref, heavy_mask=record.get("heavy_mask"), mol=record.get("mol"),
|
|
504
|
+
backend=backend, rdkit_max_matches=max_matches,
|
|
505
|
+
)
|
|
506
|
+
ref_min = rmsd.min(dim=0).values
|
|
507
|
+
pred_min = rmsd.min(dim=1).values
|
|
508
|
+
return {
|
|
509
|
+
"cov_r": float((ref_min < threshold).float().mean()),
|
|
510
|
+
"cov_p": float((pred_min < threshold).float().mean()),
|
|
511
|
+
"amr_r": float(ref_min.mean()),
|
|
512
|
+
"amr_p": float(pred_min.mean()),
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def write_csv(path, rows):
|
|
517
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
518
|
+
if not rows:
|
|
519
|
+
path.write_text("")
|
|
520
|
+
return
|
|
521
|
+
with path.open("w", newline="") as handle:
|
|
522
|
+
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
|
|
523
|
+
writer.writeheader()
|
|
524
|
+
writer.writerows(rows)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def main():
|
|
528
|
+
args = parse_args()
|
|
529
|
+
payload = torch.load(args.pool_pt, map_location="cpu", weights_only=False)
|
|
530
|
+
records = payload["records"]
|
|
531
|
+
if args.max_molecules > 0:
|
|
532
|
+
records = records[:args.max_molecules]
|
|
533
|
+
selectors = [x.strip() for x in args.selectors.split(",") if x.strip()]
|
|
534
|
+
preparations = [x.strip() for x in args.preparations.split(",") if x.strip()]
|
|
535
|
+
rows = []
|
|
536
|
+
for selector in selectors:
|
|
537
|
+
for preparation in preparations:
|
|
538
|
+
generator = torch.Generator().manual_seed(args.seed)
|
|
539
|
+
for record in tqdm(records, desc=f"{args.allocation_label}/{selector}/{preparation}", unit="molecule"):
|
|
540
|
+
pool = record["raw_pool"].float()
|
|
541
|
+
ref = record["ref_confs"].float()
|
|
542
|
+
if args.reference_limit > 0:
|
|
543
|
+
ref = ref[:args.reference_limit]
|
|
544
|
+
record = dict(record)
|
|
545
|
+
record["_reference_confs"] = ref
|
|
546
|
+
if args.candidate_pool_cap > 0 and pool.size(0) > args.candidate_pool_cap:
|
|
547
|
+
indices = torch.linspace(
|
|
548
|
+
0, pool.size(0) - 1, args.candidate_pool_cap
|
|
549
|
+
).round().long().unique()
|
|
550
|
+
pool = pool[indices]
|
|
551
|
+
budget = min(pool.size(0), int(math.ceil(args.budget_multiplier * ref.size(0))))
|
|
552
|
+
final, prep_stats = prepare(pool, budget, record, selector, preparation, generator, args)
|
|
553
|
+
row = {
|
|
554
|
+
"allocation": args.allocation_label,
|
|
555
|
+
"selector": selector,
|
|
556
|
+
"preparation": preparation,
|
|
557
|
+
"mol_id": record.get("mol_id"),
|
|
558
|
+
"smiles": record.get("smiles", ""),
|
|
559
|
+
"reference_count": int(ref.size(0)),
|
|
560
|
+
"candidate_count": int(pool.size(0)),
|
|
561
|
+
"final_count": int(final.size(0)),
|
|
562
|
+
"raw_budget": 0,
|
|
563
|
+
"relaxed_budget": 0,
|
|
564
|
+
**prep_stats,
|
|
565
|
+
**metrics(final, ref, record, args.threshold, args.rmsd_backend, args.rdkit_max_matches),
|
|
566
|
+
}
|
|
567
|
+
rows.append(row)
|
|
568
|
+
|
|
569
|
+
summary = []
|
|
570
|
+
for selector in selectors:
|
|
571
|
+
for preparation in preparations:
|
|
572
|
+
subset = [r for r in rows if r["selector"] == selector and r["preparation"] == preparation]
|
|
573
|
+
summary.append({
|
|
574
|
+
"allocation": args.allocation_label,
|
|
575
|
+
"selector": selector,
|
|
576
|
+
"preparation": preparation,
|
|
577
|
+
"molecules": len(subset),
|
|
578
|
+
**{
|
|
579
|
+
f"{key}_mean": float(np.mean([r[key] for r in subset]))
|
|
580
|
+
for key in ("cov_r", "cov_p", "amr_r", "amr_p")
|
|
581
|
+
},
|
|
582
|
+
**{
|
|
583
|
+
f"{key}_median": float(np.median([r[key] for r in subset]))
|
|
584
|
+
for key in ("cov_r", "cov_p", "amr_r", "amr_p")
|
|
585
|
+
},
|
|
586
|
+
})
|
|
587
|
+
prefix = Path(args.output_prefix)
|
|
588
|
+
write_csv(prefix.with_name(prefix.name + "_per_molecule.csv"), rows)
|
|
589
|
+
write_csv(prefix.with_name(prefix.name + "_summary.csv"), summary)
|
|
590
|
+
prefix.with_name(prefix.name + "_summary.json").write_text(json.dumps(summary, indent=2) + "\n")
|
|
591
|
+
for row in summary:
|
|
592
|
+
print(row)
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
if __name__ == "__main__":
|
|
596
|
+
main()
|