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
infer_torsion.py
ADDED
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Inference wrapper for train_torsion_generator.py torsion-space checkpoints.
|
|
3
|
+
|
|
4
|
+
It reuses infer_base_conformers.py's dataset/reference/metric machinery, but replaces the
|
|
5
|
+
model sampling function with:
|
|
6
|
+
|
|
7
|
+
ETKDG base scaffold -> Manimol torsion_mode_decoder -> optional FF/refine
|
|
8
|
+
|
|
9
|
+
Independent ETKDG conformers are not required as candidate-pool members. The
|
|
10
|
+
ETKDG coordinates here are initialization scaffolds for Manimol candidates.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import sys
|
|
16
|
+
from argparse import ArgumentParser
|
|
17
|
+
|
|
18
|
+
import torch
|
|
19
|
+
import torch.nn.functional as F
|
|
20
|
+
from rdkit import Chem
|
|
21
|
+
from rdkit.Chem import AllChem
|
|
22
|
+
|
|
23
|
+
import infer_base_conformers
|
|
24
|
+
from pgraph_controls import controlled_pglobal
|
|
25
|
+
from candidate_corrector import apply_candidate_corrector, load_candidate_corrector
|
|
26
|
+
from models.model0 import GNNEncoder, apply_torsion_residuals, cross_entropy_loss, prob_low_dim_kernel
|
|
27
|
+
from train_torsion_generator import TorsionModeDecoder
|
|
28
|
+
from models.mean_dispersion_torsion_context import (
|
|
29
|
+
controlled_dispersion_for_width,
|
|
30
|
+
dispersion_torsion_widths,
|
|
31
|
+
mean_dispersion_torsion_context,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TorsionModelEnsemble:
|
|
36
|
+
"""Small wrapper so infer_base_conformers.py can treat an ensemble like one model."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, models):
|
|
39
|
+
self.models = list(models)
|
|
40
|
+
|
|
41
|
+
def __iter__(self):
|
|
42
|
+
return iter(self.models)
|
|
43
|
+
|
|
44
|
+
def __len__(self):
|
|
45
|
+
return len(self.models)
|
|
46
|
+
|
|
47
|
+
def __getitem__(self, idx):
|
|
48
|
+
return self.models[idx]
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def num_modes(self):
|
|
52
|
+
if not self.models:
|
|
53
|
+
return 0
|
|
54
|
+
return getattr(self.models[0], "num_modes", 10)
|
|
55
|
+
|
|
56
|
+
@num_modes.setter
|
|
57
|
+
def num_modes(self, value):
|
|
58
|
+
for model in self.models:
|
|
59
|
+
model.num_modes = value
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def parse_torsion_infer_args():
|
|
63
|
+
parser = ArgumentParser(add_help=False)
|
|
64
|
+
parser.add_argument("--torsion_mode_max", type=int, default=64)
|
|
65
|
+
parser.add_argument("--torsion_delta_scale", type=float, default=3.141592653589793)
|
|
66
|
+
parser.add_argument("--iterative_torsion_steps", type=int, default=0)
|
|
67
|
+
parser.add_argument("--iterative_torsion_delta_scale", type=float, default=0.8)
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"--mode_condition_strategy",
|
|
70
|
+
type=str,
|
|
71
|
+
default="z",
|
|
72
|
+
choices=["z", "learned_prototype", "z_plus_prototype"],
|
|
73
|
+
help="Decoder mode condition used by train_torsion_generator.py checkpoints.",
|
|
74
|
+
)
|
|
75
|
+
parser.add_argument("--mode_prototype_dim", type=int, default=32)
|
|
76
|
+
parser.add_argument(
|
|
77
|
+
"--torsion_base_confs",
|
|
78
|
+
type=int,
|
|
79
|
+
default=0,
|
|
80
|
+
help="Fixed number of ETKDG base scaffolds per molecule; 0 follows model candidate count.",
|
|
81
|
+
)
|
|
82
|
+
parser.add_argument(
|
|
83
|
+
"--torsion_base_seed_offset",
|
|
84
|
+
type=int,
|
|
85
|
+
default=1701,
|
|
86
|
+
help="Reserved for future deterministic base sampling variants.",
|
|
87
|
+
)
|
|
88
|
+
parser.add_argument(
|
|
89
|
+
"--torsion_base_method",
|
|
90
|
+
type=str,
|
|
91
|
+
default="etkdg",
|
|
92
|
+
choices=["etkdg", "rdkit_dg", "random3d"],
|
|
93
|
+
help="Base scaffold initialization used before Manimol torsion decoding.",
|
|
94
|
+
)
|
|
95
|
+
parser.add_argument(
|
|
96
|
+
"--torsion_jitter_scale",
|
|
97
|
+
type=float,
|
|
98
|
+
default=0.0,
|
|
99
|
+
help="Small Gaussian noise added to predicted torsion residuals during inference.",
|
|
100
|
+
)
|
|
101
|
+
parser.add_argument("--use_dispersion_proposal", action="store_true")
|
|
102
|
+
parser.add_argument("--dispersion_width_scale", type=float, default=0.35)
|
|
103
|
+
parser.add_argument("--dispersion_width_min", type=float, default=0.5)
|
|
104
|
+
parser.add_argument("--dispersion_width_max", type=float, default=2.0)
|
|
105
|
+
parser.add_argument("--dispersion_control", type=str, default="normal", choices=["normal", "shuffle", "constant", "random"])
|
|
106
|
+
parser.add_argument("--dispersion_seed", type=int, default=20260913)
|
|
107
|
+
parser.add_argument(
|
|
108
|
+
"--candidate_corrector_path",
|
|
109
|
+
type=str,
|
|
110
|
+
default="",
|
|
111
|
+
help="Optional post-hoc torsion corrector checkpoint trained by train_candidate_corrector.py.",
|
|
112
|
+
)
|
|
113
|
+
parser.add_argument("--candidate_corrector_steps", type=int, default=1)
|
|
114
|
+
parser.add_argument("--candidate_corrector_scale", type=float, default=1.0)
|
|
115
|
+
parser.add_argument("--candidate_corrector_max_torsions", type=int, default=64)
|
|
116
|
+
parser.add_argument(
|
|
117
|
+
"--ensemble_checkpoints",
|
|
118
|
+
type=str,
|
|
119
|
+
default="",
|
|
120
|
+
help="Comma-separated train_torsion_generator.py checkpoints. Candidates from all models are merged before selection.",
|
|
121
|
+
)
|
|
122
|
+
parser.add_argument(
|
|
123
|
+
"--ensemble_iterative_torsion_delta_scales",
|
|
124
|
+
type=str,
|
|
125
|
+
default="",
|
|
126
|
+
help="Optional comma-separated iterative_torsion_delta_scale values matching --ensemble_checkpoints.",
|
|
127
|
+
)
|
|
128
|
+
parser.add_argument(
|
|
129
|
+
"--disable_stage1_pglobal",
|
|
130
|
+
action="store_true",
|
|
131
|
+
help="Ablation: feed zero P_global during torsion inference instead of the Stage-1 probability map.",
|
|
132
|
+
)
|
|
133
|
+
parser.add_argument(
|
|
134
|
+
"--pglobal_control",
|
|
135
|
+
type=str,
|
|
136
|
+
default="normal",
|
|
137
|
+
choices=["normal", "zero", "constant", "topology", "random", "shuffle", "noisy"],
|
|
138
|
+
)
|
|
139
|
+
parser.add_argument("--pglobal_noise_std", type=float, default=0.15)
|
|
140
|
+
parser.add_argument("--pglobal_seed", type=int, default=20260715)
|
|
141
|
+
parser.add_argument("--pglobal_topology_scale", type=float, default=1.5)
|
|
142
|
+
parser.add_argument(
|
|
143
|
+
"--stage1_kernel",
|
|
144
|
+
type=str,
|
|
145
|
+
default="umap",
|
|
146
|
+
choices=[
|
|
147
|
+
"umap",
|
|
148
|
+
"gaussian",
|
|
149
|
+
"laplacian",
|
|
150
|
+
"student",
|
|
151
|
+
"cauchy",
|
|
152
|
+
"rational_quadratic",
|
|
153
|
+
"inverse_multiquadric",
|
|
154
|
+
"matern32",
|
|
155
|
+
"matern52",
|
|
156
|
+
"triweight",
|
|
157
|
+
"logistic",
|
|
158
|
+
],
|
|
159
|
+
help="Probability-graph kernel used by Stage-I manifold projection ablations.",
|
|
160
|
+
)
|
|
161
|
+
parser.add_argument("--manifold_projection_steps", type=int, default=0)
|
|
162
|
+
parser.add_argument("--manifold_projection_lr", type=float, default=0.04)
|
|
163
|
+
parser.add_argument("--manifold_projection_anchor", type=float, default=0.02)
|
|
164
|
+
parser.add_argument("--manifold_use_mode_p", action="store_true")
|
|
165
|
+
parser.add_argument("--manifold_projection_pdist_weight", type=float, default=0.0)
|
|
166
|
+
parser.add_argument("--p_distance_topk", type=int, default=64)
|
|
167
|
+
parser.add_argument("--p_distance_min_topo", type=int, default=3)
|
|
168
|
+
exp_args, remaining = parser.parse_known_args()
|
|
169
|
+
return exp_args, remaining
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _coords_from_mol_conformers(mol):
|
|
173
|
+
coords = []
|
|
174
|
+
for conf in mol.GetConformers():
|
|
175
|
+
coords.append(torch.tensor(conf.GetPositions(), dtype=torch.float32))
|
|
176
|
+
return coords
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def generate_rdkit_dg_conformers(mol, num_confs=10, random_seed=42):
|
|
180
|
+
"""RDKit distance-geometry base scaffolds without ETKDG torsion preferences."""
|
|
181
|
+
try:
|
|
182
|
+
mol_copy = Chem.RWMol(mol)
|
|
183
|
+
params = AllChem.EmbedParameters()
|
|
184
|
+
params.randomSeed = int(random_seed)
|
|
185
|
+
params.numThreads = 1
|
|
186
|
+
params.useRandomCoords = False
|
|
187
|
+
params.useExpTorsionAnglePrefs = False
|
|
188
|
+
params.useBasicKnowledge = False
|
|
189
|
+
params.enforceChirality = True
|
|
190
|
+
AllChem.EmbedMultipleConfs(mol_copy, numConfs=int(num_confs), params=params)
|
|
191
|
+
return _coords_from_mol_conformers(mol_copy)
|
|
192
|
+
except Exception:
|
|
193
|
+
return []
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def generate_random3d_conformers(mol, num_confs=10, random_seed=42):
|
|
197
|
+
"""Random-coordinate DG base scaffolds; useful as a deliberately weaker init."""
|
|
198
|
+
try:
|
|
199
|
+
mol_copy = Chem.RWMol(mol)
|
|
200
|
+
params = AllChem.EmbedParameters()
|
|
201
|
+
params.randomSeed = int(random_seed)
|
|
202
|
+
params.numThreads = 1
|
|
203
|
+
params.useRandomCoords = True
|
|
204
|
+
params.useExpTorsionAnglePrefs = False
|
|
205
|
+
params.useBasicKnowledge = False
|
|
206
|
+
params.enforceChirality = True
|
|
207
|
+
AllChem.EmbedMultipleConfs(mol_copy, numConfs=int(num_confs), params=params)
|
|
208
|
+
return _coords_from_mol_conformers(mol_copy)
|
|
209
|
+
except Exception:
|
|
210
|
+
return []
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def generate_base_conformers(mol, num_confs, method, random_seed=42):
|
|
214
|
+
method = str(method).lower()
|
|
215
|
+
if method == "etkdg":
|
|
216
|
+
return infer_base_conformers.generate_etkdg_conformers(mol, num_confs=num_confs, random_seed=random_seed)
|
|
217
|
+
if method == "rdkit_dg":
|
|
218
|
+
return generate_rdkit_dg_conformers(mol, num_confs=num_confs, random_seed=random_seed)
|
|
219
|
+
if method == "random3d":
|
|
220
|
+
return generate_random3d_conformers(mol, num_confs=num_confs, random_seed=random_seed)
|
|
221
|
+
raise ValueError(f"Unknown torsion_base_method={method}")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def attach_torsion_decoder(model, args_cli, device, iterative_delta_scale=None, checkpoint_state=None):
|
|
225
|
+
mode_condition_strategy = str(getattr(args_cli, "mode_condition_strategy", "z")).lower()
|
|
226
|
+
prototype_dim = int(getattr(args_cli, "mode_prototype_dim", getattr(model.args, "mode_dim", 32)))
|
|
227
|
+
decoder_prototype_dim = prototype_dim if mode_condition_strategy in {"learned_prototype", "z_plus_prototype"} else 0
|
|
228
|
+
state = checkpoint_state or {}
|
|
229
|
+
context_keys = (
|
|
230
|
+
"torsion_mode_decoder.context_proj.weight",
|
|
231
|
+
"torsion_refine_decoder.context_proj.weight",
|
|
232
|
+
)
|
|
233
|
+
context_dims = [int(state[key].shape[1]) for key in context_keys if key in state]
|
|
234
|
+
if context_dims and (len(set(context_dims)) != 1 or context_dims[0] != 4):
|
|
235
|
+
raise ValueError(f"Unsupported torsion context dimensions in checkpoint: {context_dims}")
|
|
236
|
+
context_dim = context_dims[0] if context_dims else 0
|
|
237
|
+
model.torsion_mode_decoder = TorsionModeDecoder(
|
|
238
|
+
emb_dim=int(getattr(model.args, "emb_dim", 128)),
|
|
239
|
+
mode_dim=int(getattr(model.args, "mode_dim", 32)),
|
|
240
|
+
hidden_dim=int(getattr(model.args, "mlp_hidden", 128)),
|
|
241
|
+
max_delta=float(getattr(args_cli, "torsion_delta_scale", 3.141592653589793)),
|
|
242
|
+
prototype_dim=decoder_prototype_dim,
|
|
243
|
+
torsion_context_dim=context_dim,
|
|
244
|
+
).to(device)
|
|
245
|
+
if int(getattr(args_cli, "iterative_torsion_steps", 0)) > 0:
|
|
246
|
+
model.torsion_refine_decoder = TorsionModeDecoder(
|
|
247
|
+
emb_dim=int(getattr(model.args, "emb_dim", 128)),
|
|
248
|
+
mode_dim=int(getattr(model.args, "mode_dim", 32)),
|
|
249
|
+
hidden_dim=int(getattr(model.args, "mlp_hidden", 128)),
|
|
250
|
+
max_delta=float(
|
|
251
|
+
iterative_delta_scale
|
|
252
|
+
if iterative_delta_scale is not None
|
|
253
|
+
else getattr(args_cli, "iterative_torsion_delta_scale", 0.8)
|
|
254
|
+
),
|
|
255
|
+
prototype_dim=decoder_prototype_dim,
|
|
256
|
+
torsion_context_dim=context_dim,
|
|
257
|
+
).to(device)
|
|
258
|
+
if decoder_prototype_dim > 0:
|
|
259
|
+
model.mode_prototype_embedding = torch.nn.Embedding(
|
|
260
|
+
int(getattr(args_cli, "num_modes", getattr(model, "num_modes", 10))),
|
|
261
|
+
decoder_prototype_dim,
|
|
262
|
+
).to(device)
|
|
263
|
+
return model
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def mode_inputs(model, args, mode_idx, device, dtype):
|
|
267
|
+
z = model._make_z(
|
|
268
|
+
int(mode_idx),
|
|
269
|
+
device,
|
|
270
|
+
dtype,
|
|
271
|
+
deterministic=bool(getattr(args, "deterministic_modes", True)),
|
|
272
|
+
)
|
|
273
|
+
prototype = None
|
|
274
|
+
strategy = str(getattr(args, "mode_condition_strategy", "z")).lower()
|
|
275
|
+
if strategy in {"learned_prototype", "z_plus_prototype"} and hasattr(model, "mode_prototype_embedding"):
|
|
276
|
+
idx = torch.tensor(
|
|
277
|
+
int(mode_idx) % int(getattr(args, "num_modes", getattr(model, "num_modes", 10))),
|
|
278
|
+
device=device,
|
|
279
|
+
dtype=torch.long,
|
|
280
|
+
)
|
|
281
|
+
prototype = model.mode_prototype_embedding(idx).to(dtype=dtype)
|
|
282
|
+
if strategy == "learned_prototype":
|
|
283
|
+
z = torch.zeros_like(z)
|
|
284
|
+
return z, prototype
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def mode_probability(model, args, P_global, pair_feat, z):
|
|
288
|
+
if bool(getattr(args, "manifold_use_mode_p", False)) and hasattr(model, "mode_generator"):
|
|
289
|
+
try:
|
|
290
|
+
return model.mode_generator(P_global, pair_feat, z).clamp(1e-6, 1.0 - 1e-6)
|
|
291
|
+
except Exception:
|
|
292
|
+
return P_global
|
|
293
|
+
return P_global
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def topology_distance(edge_index, n, device):
|
|
297
|
+
dist = torch.full((n, n), 1e6, device=device)
|
|
298
|
+
idx = torch.arange(n, device=device)
|
|
299
|
+
dist[idx, idx] = 0.0
|
|
300
|
+
if edge_index is not None and edge_index.numel() > 0:
|
|
301
|
+
row, col = edge_index.to(device=device)
|
|
302
|
+
valid = (row >= 0) & (row < n) & (col >= 0) & (col < n)
|
|
303
|
+
row, col = row[valid], col[valid]
|
|
304
|
+
dist[row, col] = 1.0
|
|
305
|
+
dist[col, row] = 1.0
|
|
306
|
+
for k in range(n):
|
|
307
|
+
dist = torch.minimum(dist, dist[:, k:k + 1] + dist[k:k + 1, :])
|
|
308
|
+
return dist
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def inverse_umap_distance(model, args, P, graph_feat_i, mode_idx):
|
|
312
|
+
max_confs = max(1, int(getattr(model, "max_confs", getattr(args, "max_confs", 5))))
|
|
313
|
+
cidx = int(mode_idx) % max_confs
|
|
314
|
+
a, b = model.predict_ab(graph_feat_i, cidx)
|
|
315
|
+
a = a.detach().clamp(min=1e-4, max=1e4)
|
|
316
|
+
b = b.detach().clamp(min=1e-4, max=10.0)
|
|
317
|
+
p = P.detach().clamp(1e-4, 1.0 - 1e-4)
|
|
318
|
+
val = ((1.0 / p - 1.0) / a).clamp(min=0.0, max=1e6)
|
|
319
|
+
d = torch.pow(val + 1e-12, 1.0 / (2.0 * b))
|
|
320
|
+
return torch.nan_to_num(d, nan=0.0, posinf=20.0, neginf=0.0).clamp(0.0, 20.0)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def p_distance_bound_loss(model, args, coords, P_target, graph_feat_i, mode_idx, edge_index):
|
|
324
|
+
if coords.size(0) <= 2:
|
|
325
|
+
return coords.sum() * 0.0
|
|
326
|
+
n = coords.size(0)
|
|
327
|
+
topo = topology_distance(edge_index, n, coords.device)
|
|
328
|
+
min_topo = int(getattr(args, "p_distance_min_topo", 3))
|
|
329
|
+
eye = torch.eye(n, dtype=torch.bool, device=coords.device)
|
|
330
|
+
valid = (topo >= float(min_topo)) & (topo < 1e5) & (~eye)
|
|
331
|
+
upper = torch.triu(torch.ones(n, n, dtype=torch.bool, device=coords.device), diagonal=1)
|
|
332
|
+
valid = valid & upper
|
|
333
|
+
if int(valid.sum().item()) == 0:
|
|
334
|
+
return coords.sum() * 0.0
|
|
335
|
+
score = torch.where(valid, P_target.detach().clamp(0.0, 1.0), torch.zeros_like(P_target))
|
|
336
|
+
flat_score = score.reshape(-1)
|
|
337
|
+
topk = min(int(getattr(args, "p_distance_topk", 64)), int(valid.sum().item()))
|
|
338
|
+
if topk <= 0:
|
|
339
|
+
return coords.sum() * 0.0
|
|
340
|
+
idx = torch.topk(flat_score, k=topk, largest=True).indices
|
|
341
|
+
rows = idx // n
|
|
342
|
+
cols = idx % n
|
|
343
|
+
pred_d = torch.cdist(coords, coords)[rows, cols]
|
|
344
|
+
target_d = inverse_umap_distance(model, args, P_target, graph_feat_i, mode_idx)[rows, cols]
|
|
345
|
+
weights = P_target.detach()[rows, cols].clamp(0.05, 1.0)
|
|
346
|
+
loss = F.smooth_l1_loss(pred_d, target_d, reduction="none")
|
|
347
|
+
return (loss * weights).sum() / weights.sum().clamp(min=1e-6)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def manifold_project_coords(model, args, coords, P_target, graph_feat_i, mode_idx, edge_index):
|
|
351
|
+
steps = int(getattr(args, "manifold_projection_steps", 0))
|
|
352
|
+
if steps <= 0:
|
|
353
|
+
return coords
|
|
354
|
+
stage1_kernel = str(getattr(args, "stage1_kernel", "umap")).lower()
|
|
355
|
+
max_confs = max(1, int(getattr(model, "max_confs", getattr(args, "max_confs", 5))))
|
|
356
|
+
cidx = int(mode_idx) % max_confs
|
|
357
|
+
try:
|
|
358
|
+
a, b = model.predict_ab(graph_feat_i, cidx)
|
|
359
|
+
except Exception:
|
|
360
|
+
return coords
|
|
361
|
+
a = a.detach()
|
|
362
|
+
b = b.detach()
|
|
363
|
+
y0 = coords.detach()
|
|
364
|
+
y = coords
|
|
365
|
+
lr = float(getattr(args, "manifold_projection_lr", 0.04))
|
|
366
|
+
anchor = float(getattr(args, "manifold_projection_anchor", 0.02))
|
|
367
|
+
with torch.enable_grad():
|
|
368
|
+
for _ in range(steps):
|
|
369
|
+
y_req = y.detach().clone().requires_grad_(True)
|
|
370
|
+
Q = prob_low_dim_kernel(y_req, a, b, kernel=stage1_kernel).clamp(1e-6, 1.0 - 1e-6)
|
|
371
|
+
loss = cross_entropy_loss(Q, P_target.detach()).clamp(0.0, 10.0)
|
|
372
|
+
if anchor > 0:
|
|
373
|
+
loss = loss + float(anchor) * ((y_req - y0) ** 2).mean().clamp(0.0, 10.0)
|
|
374
|
+
pdist_weight = float(getattr(args, "manifold_projection_pdist_weight", 0.0))
|
|
375
|
+
if pdist_weight > 0:
|
|
376
|
+
loss = loss + pdist_weight * p_distance_bound_loss(
|
|
377
|
+
model,
|
|
378
|
+
args,
|
|
379
|
+
y_req,
|
|
380
|
+
P_target,
|
|
381
|
+
graph_feat_i,
|
|
382
|
+
mode_idx,
|
|
383
|
+
edge_index,
|
|
384
|
+
).clamp(0.0, 10.0)
|
|
385
|
+
grad = torch.autograd.grad(loss, y_req, allow_unused=True)[0]
|
|
386
|
+
if grad is None:
|
|
387
|
+
break
|
|
388
|
+
grad = torch.nan_to_num(grad, nan=0.0, posinf=0.0, neginf=0.0)
|
|
389
|
+
y = torch.nan_to_num(y_req - lr * grad, nan=0.0, posinf=0.0, neginf=0.0)
|
|
390
|
+
return y.detach()
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def patched_load_model_factory(exp_args):
|
|
394
|
+
original_build_model_args = infer_base_conformers.build_model_args
|
|
395
|
+
|
|
396
|
+
def _split_csv(value):
|
|
397
|
+
if value is None:
|
|
398
|
+
return []
|
|
399
|
+
return [item.strip() for item in str(value).split(",") if item.strip()]
|
|
400
|
+
|
|
401
|
+
def load_one_model(checkpoint_path, device, args_cli, iterative_delta_scale=None):
|
|
402
|
+
model_args = original_build_model_args(args_cli)
|
|
403
|
+
model_args.deterministic_modes = bool(getattr(args_cli, "deterministic_modes", True))
|
|
404
|
+
model = GNNEncoder(args=model_args, config={"model": {"model_level": "graph"}}).to(device)
|
|
405
|
+
ckpt = torch.load(checkpoint_path, map_location=device)
|
|
406
|
+
if isinstance(ckpt, dict) and "model_state_dict" in ckpt:
|
|
407
|
+
state = ckpt["model_state_dict"]
|
|
408
|
+
elif isinstance(ckpt, dict) and "state_dict" in ckpt:
|
|
409
|
+
state = ckpt["state_dict"]
|
|
410
|
+
else:
|
|
411
|
+
state = ckpt
|
|
412
|
+
attach_torsion_decoder(
|
|
413
|
+
model,
|
|
414
|
+
args_cli,
|
|
415
|
+
device,
|
|
416
|
+
iterative_delta_scale=iterative_delta_scale,
|
|
417
|
+
checkpoint_state=state,
|
|
418
|
+
)
|
|
419
|
+
missing, unexpected = model.load_state_dict(state, strict=False)
|
|
420
|
+
decoder_prefixes = ("torsion_mode_decoder.", "torsion_refine_decoder.")
|
|
421
|
+
decoder_mismatch = [key for key in (*missing, *unexpected) if key.startswith(decoder_prefixes)]
|
|
422
|
+
if decoder_mismatch:
|
|
423
|
+
raise RuntimeError(f"Torsion decoder checkpoint mismatch: {decoder_mismatch}")
|
|
424
|
+
if missing:
|
|
425
|
+
print(f"Missing keys ({len(missing)}): {missing[:5]}...")
|
|
426
|
+
if unexpected:
|
|
427
|
+
print(f"Unexpected keys ({len(unexpected)}): {unexpected[:5]}...")
|
|
428
|
+
model.eval()
|
|
429
|
+
corrector_path = str(getattr(args_cli, "candidate_corrector_path", "") or "").strip()
|
|
430
|
+
if corrector_path:
|
|
431
|
+
model.candidate_corrector = load_candidate_corrector(corrector_path, device)
|
|
432
|
+
print(f"Loaded candidate corrector: {corrector_path}")
|
|
433
|
+
if iterative_delta_scale is None:
|
|
434
|
+
print(f"Loaded torsion-space checkpoint: {checkpoint_path}")
|
|
435
|
+
else:
|
|
436
|
+
print(
|
|
437
|
+
f"Loaded torsion-space checkpoint: {checkpoint_path} "
|
|
438
|
+
f"(iterative_torsion_delta_scale={iterative_delta_scale})"
|
|
439
|
+
)
|
|
440
|
+
return model
|
|
441
|
+
|
|
442
|
+
def load_model(checkpoint_path, device, args_cli):
|
|
443
|
+
checkpoints = _split_csv(getattr(args_cli, "ensemble_checkpoints", ""))
|
|
444
|
+
if not checkpoints:
|
|
445
|
+
checkpoints = [checkpoint_path]
|
|
446
|
+
|
|
447
|
+
scale_items = _split_csv(getattr(args_cli, "ensemble_iterative_torsion_delta_scales", ""))
|
|
448
|
+
scales = []
|
|
449
|
+
for item in scale_items:
|
|
450
|
+
scales.append(float(item))
|
|
451
|
+
if scales and len(scales) != len(checkpoints):
|
|
452
|
+
raise ValueError(
|
|
453
|
+
"--ensemble_iterative_torsion_delta_scales must have the same length "
|
|
454
|
+
"as --ensemble_checkpoints."
|
|
455
|
+
)
|
|
456
|
+
|
|
457
|
+
models = []
|
|
458
|
+
for idx, ckpt_path in enumerate(checkpoints):
|
|
459
|
+
scale = scales[idx] if scales else None
|
|
460
|
+
models.append(load_one_model(ckpt_path, device, args_cli, iterative_delta_scale=scale))
|
|
461
|
+
|
|
462
|
+
if len(models) == 1:
|
|
463
|
+
return models[0]
|
|
464
|
+
print(f"Loaded torsion-space ensemble: {len(models)} checkpoints")
|
|
465
|
+
return TorsionModelEnsemble(models)
|
|
466
|
+
|
|
467
|
+
return load_model
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
@torch.no_grad()
|
|
471
|
+
def _sample_torsion_conformers_single(model, batch, graph_idx, args, model_count=None, etkdg_count=None):
|
|
472
|
+
node_feat = model.gnn(batch)
|
|
473
|
+
graph_feat = model.pool(node_feat, batch.batch)
|
|
474
|
+
mask = batch.batch == graph_idx
|
|
475
|
+
feat_i = node_feat[mask]
|
|
476
|
+
graph_feat_i = graph_feat[graph_idx]
|
|
477
|
+
if feat_i.size(0) <= 1:
|
|
478
|
+
return None
|
|
479
|
+
|
|
480
|
+
edge_index_i = model._get_local_edge_index(edge_index=batch.edge_index, mask=mask)
|
|
481
|
+
local_ei, local_ea = model._get_local_edge_attr(getattr(batch, "edge_attr", None), batch.edge_index, mask)
|
|
482
|
+
local_torsion_index = model._get_local_torsion_index(getattr(batch, "torsion_index", None), mask)
|
|
483
|
+
if local_torsion_index is None or local_torsion_index.numel() == 0:
|
|
484
|
+
return None
|
|
485
|
+
|
|
486
|
+
mol_ref = batch.rdmol[graph_idx] if hasattr(batch, "rdmol") else None
|
|
487
|
+
if mol_ref is None:
|
|
488
|
+
return None
|
|
489
|
+
P_global, P_disp, pair_feat = model._predict_mean_dispersion(feat_i, edge_index_i)
|
|
490
|
+
if bool(getattr(args, "use_dispersion_proposal", False)):
|
|
491
|
+
width_dispersion = controlled_dispersion_for_width(P_disp, args)
|
|
492
|
+
dispersion_widths, _, _ = dispersion_torsion_widths(
|
|
493
|
+
width_dispersion,
|
|
494
|
+
mol_ref,
|
|
495
|
+
local_torsion_index,
|
|
496
|
+
int(getattr(args, "torsion_mode_max", 64)),
|
|
497
|
+
scale=float(getattr(args, "dispersion_width_scale", 0.35)),
|
|
498
|
+
min_width=float(getattr(args, "dispersion_width_min", 0.5)),
|
|
499
|
+
max_width=float(getattr(args, "dispersion_width_max", 2.0)),
|
|
500
|
+
)
|
|
501
|
+
dispersion_widths = dispersion_widths.to(device=P_global.device, dtype=P_global.dtype)
|
|
502
|
+
else:
|
|
503
|
+
dispersion_widths = torch.ones(
|
|
504
|
+
int(getattr(args, "torsion_mode_max", 64)), device=P_global.device, dtype=P_global.dtype
|
|
505
|
+
)
|
|
506
|
+
P_global = controlled_pglobal(P_global, args, mol=mol_ref)
|
|
507
|
+
torsion_context = None
|
|
508
|
+
if getattr(model.torsion_mode_decoder, "context_dim", 0) > 0:
|
|
509
|
+
torsion_context, _ = mean_dispersion_torsion_context(
|
|
510
|
+
P_global,
|
|
511
|
+
P_disp,
|
|
512
|
+
mol_ref,
|
|
513
|
+
local_torsion_index,
|
|
514
|
+
int(getattr(args, "torsion_mode_max", 64)),
|
|
515
|
+
)
|
|
516
|
+
if str(getattr(args, "pglobal_control", "normal")) != "normal" or bool(getattr(args, "disable_stage1_pglobal", False)):
|
|
517
|
+
pair_feat = None
|
|
518
|
+
|
|
519
|
+
if model_count is None:
|
|
520
|
+
model_count = int(getattr(args, "num_modes", getattr(model, "num_modes", 10)))
|
|
521
|
+
normal_count = int(model_count)
|
|
522
|
+
mirror_count = 0
|
|
523
|
+
if normal_count > 0 and float(getattr(args, "mirror_ratio", 0.0)) > 0:
|
|
524
|
+
mirror_count = int(round(normal_count * float(args.mirror_ratio)))
|
|
525
|
+
mirror_count = max(0, min(normal_count, mirror_count))
|
|
526
|
+
normal_count = max(1, normal_count - mirror_count)
|
|
527
|
+
|
|
528
|
+
base_count = int(getattr(args, "torsion_base_confs", 0))
|
|
529
|
+
if base_count <= 0:
|
|
530
|
+
base_count = int(normal_count)
|
|
531
|
+
base_confs = generate_base_conformers(
|
|
532
|
+
mol_ref,
|
|
533
|
+
num_confs=max(1, base_count),
|
|
534
|
+
method=getattr(args, "torsion_base_method", "etkdg"),
|
|
535
|
+
)
|
|
536
|
+
if not base_confs:
|
|
537
|
+
return None
|
|
538
|
+
|
|
539
|
+
rotatable_bonds = infer_base_conformers.find_rotatable_bonds(mol_ref) if args.use_torsion_refine else None
|
|
540
|
+
model_confs = []
|
|
541
|
+
for k in range(int(normal_count)):
|
|
542
|
+
base = base_confs[k % len(base_confs)]
|
|
543
|
+
if base.shape[0] != feat_i.size(0):
|
|
544
|
+
continue
|
|
545
|
+
base = base.to(device=P_global.device, dtype=P_global.dtype)
|
|
546
|
+
mode_idx = int(k) % max(1, int(getattr(model, "num_modes", getattr(args, "num_modes", 10))))
|
|
547
|
+
z, prototype = mode_inputs(model, args, mode_idx, P_global.device, P_global.dtype)
|
|
548
|
+
P_mode = mode_probability(model, args, P_global, pair_feat, z)
|
|
549
|
+
delta = model.torsion_mode_decoder(
|
|
550
|
+
node_feat=feat_i,
|
|
551
|
+
graph_feat=graph_feat_i,
|
|
552
|
+
coords=base,
|
|
553
|
+
P=P_mode,
|
|
554
|
+
torsion_index=local_torsion_index,
|
|
555
|
+
z=z,
|
|
556
|
+
prototype=prototype,
|
|
557
|
+
max_torsions=int(getattr(args, "torsion_mode_max", 64)),
|
|
558
|
+
torsion_context=torsion_context,
|
|
559
|
+
)
|
|
560
|
+
jitter_scale = float(getattr(args, "torsion_jitter_scale", 0.0))
|
|
561
|
+
if jitter_scale > 0:
|
|
562
|
+
delta = delta + torch.randn_like(delta) * jitter_scale
|
|
563
|
+
delta = delta * dispersion_widths[: delta.size(0)]
|
|
564
|
+
yT = apply_torsion_residuals(
|
|
565
|
+
base,
|
|
566
|
+
torsions=local_torsion_index,
|
|
567
|
+
deltas=delta,
|
|
568
|
+
edge_index=local_ei,
|
|
569
|
+
max_torsions=int(getattr(args, "torsion_mode_max", 64)),
|
|
570
|
+
)
|
|
571
|
+
for _ in range(max(0, int(getattr(args, "iterative_torsion_steps", 0)))):
|
|
572
|
+
if not hasattr(model, "torsion_refine_decoder"):
|
|
573
|
+
break
|
|
574
|
+
step_delta = model.torsion_refine_decoder(
|
|
575
|
+
node_feat=feat_i,
|
|
576
|
+
graph_feat=graph_feat_i,
|
|
577
|
+
coords=yT,
|
|
578
|
+
P=P_mode,
|
|
579
|
+
torsion_index=local_torsion_index,
|
|
580
|
+
z=z,
|
|
581
|
+
prototype=prototype,
|
|
582
|
+
max_torsions=int(getattr(args, "torsion_mode_max", 64)),
|
|
583
|
+
torsion_context=torsion_context,
|
|
584
|
+
)
|
|
585
|
+
jitter_scale = float(getattr(args, "torsion_jitter_scale", 0.0))
|
|
586
|
+
if jitter_scale > 0:
|
|
587
|
+
step_delta = step_delta + torch.randn_like(step_delta) * (0.5 * jitter_scale)
|
|
588
|
+
step_delta = step_delta * dispersion_widths[: step_delta.size(0)]
|
|
589
|
+
yT = apply_torsion_residuals(
|
|
590
|
+
yT,
|
|
591
|
+
torsions=local_torsion_index,
|
|
592
|
+
deltas=step_delta,
|
|
593
|
+
edge_index=local_ei,
|
|
594
|
+
max_torsions=int(getattr(args, "torsion_mode_max", 64)),
|
|
595
|
+
)
|
|
596
|
+
|
|
597
|
+
if bool(getattr(args, "use_egnn_refine", False)):
|
|
598
|
+
try:
|
|
599
|
+
yT, _ = model.refiner(P=P_mode, node_feat=feat_i, y0=yT, edge_index=local_ei, edge_attr=local_ea)
|
|
600
|
+
except Exception:
|
|
601
|
+
pass
|
|
602
|
+
yT = manifold_project_coords(model, args, yT, P_mode, graph_feat_i, mode_idx, local_ei)
|
|
603
|
+
if args.use_mmff:
|
|
604
|
+
yT = infer_base_conformers.optimize_with_mmff(yT, mol_ref, max_steps=args.mmff_steps)
|
|
605
|
+
if args.use_torsion_refine and rotatable_bonds:
|
|
606
|
+
yT = infer_base_conformers.optimize_torsions_fast(yT, mol_ref, rotatable_bonds, max_trials=args.torsion_trials)
|
|
607
|
+
if hasattr(model, "candidate_corrector"):
|
|
608
|
+
yT = apply_candidate_corrector(
|
|
609
|
+
yT,
|
|
610
|
+
torsion_index=local_torsion_index,
|
|
611
|
+
edge_index=local_ei,
|
|
612
|
+
corrector=model.candidate_corrector,
|
|
613
|
+
max_torsions=int(getattr(args, "candidate_corrector_max_torsions", getattr(args, "torsion_mode_max", 64))),
|
|
614
|
+
steps=int(getattr(args, "candidate_corrector_steps", 1)),
|
|
615
|
+
scale=float(getattr(args, "candidate_corrector_scale", 1.0)),
|
|
616
|
+
).to(device=P_global.device, dtype=P_global.dtype)
|
|
617
|
+
model_confs.append(yT.detach().cpu())
|
|
618
|
+
|
|
619
|
+
if mirror_count > 0 and model_confs:
|
|
620
|
+
for idx in range(int(mirror_count)):
|
|
621
|
+
model_confs.append(infer_base_conformers.mirror_conformer(model_confs[idx % len(model_confs)], axis=args.mirror_axis))
|
|
622
|
+
|
|
623
|
+
# Optional independent ETKDG pool is kept for ablation, but recommended
|
|
624
|
+
# torsion tasks below turn it off.
|
|
625
|
+
actual_etkdg_count = 0
|
|
626
|
+
all_confs = list(model_confs)
|
|
627
|
+
if args.use_etkdg and args.etkdg_candidate_pool and mol_ref is not None and int(etkdg_count or 0) > 0:
|
|
628
|
+
etkdg_confs = infer_base_conformers.generate_etkdg_conformers(mol_ref, num_confs=int(etkdg_count))
|
|
629
|
+
for conf in etkdg_confs:
|
|
630
|
+
if conf.shape[0] == feat_i.size(0):
|
|
631
|
+
all_confs.append(conf)
|
|
632
|
+
actual_etkdg_count += 1
|
|
633
|
+
|
|
634
|
+
if not all_confs:
|
|
635
|
+
return None
|
|
636
|
+
return torch.stack(all_confs, dim=0), int(normal_count), int(mirror_count), int(actual_etkdg_count)
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
@torch.no_grad()
|
|
640
|
+
def sample_torsion_conformers(model, batch, graph_idx, args, model_count=None, etkdg_count=None):
|
|
641
|
+
if isinstance(model, TorsionModelEnsemble):
|
|
642
|
+
models = list(model.models)
|
|
643
|
+
elif isinstance(model, (list, tuple)):
|
|
644
|
+
models = list(model)
|
|
645
|
+
else:
|
|
646
|
+
return _sample_torsion_conformers_single(
|
|
647
|
+
model,
|
|
648
|
+
batch,
|
|
649
|
+
graph_idx,
|
|
650
|
+
args,
|
|
651
|
+
model_count=model_count,
|
|
652
|
+
etkdg_count=etkdg_count,
|
|
653
|
+
)
|
|
654
|
+
|
|
655
|
+
if not models:
|
|
656
|
+
return None
|
|
657
|
+
total_model_count = int(model_count if model_count is not None else getattr(args, "num_modes", 10))
|
|
658
|
+
total_model_count = max(0, total_model_count)
|
|
659
|
+
base = total_model_count // len(models)
|
|
660
|
+
remainder = total_model_count % len(models)
|
|
661
|
+
|
|
662
|
+
all_confs = []
|
|
663
|
+
total_normal = 0
|
|
664
|
+
total_mirror = 0
|
|
665
|
+
total_etkdg = 0
|
|
666
|
+
for idx, sub_model in enumerate(models):
|
|
667
|
+
sub_count = base + (1 if idx < remainder else 0)
|
|
668
|
+
sub_etkdg = int(etkdg_count or 0) if idx == 0 else 0
|
|
669
|
+
if sub_count <= 0 and sub_etkdg <= 0:
|
|
670
|
+
continue
|
|
671
|
+
result = _sample_torsion_conformers_single(
|
|
672
|
+
sub_model,
|
|
673
|
+
batch,
|
|
674
|
+
graph_idx,
|
|
675
|
+
args,
|
|
676
|
+
model_count=sub_count,
|
|
677
|
+
etkdg_count=sub_etkdg,
|
|
678
|
+
)
|
|
679
|
+
if result is None:
|
|
680
|
+
continue
|
|
681
|
+
confs, normal_count, mirror_count, actual_etkdg_count = result
|
|
682
|
+
all_confs.append(confs)
|
|
683
|
+
total_normal += int(normal_count)
|
|
684
|
+
total_mirror += int(mirror_count)
|
|
685
|
+
total_etkdg += int(actual_etkdg_count)
|
|
686
|
+
|
|
687
|
+
if not all_confs:
|
|
688
|
+
return None
|
|
689
|
+
return torch.cat(all_confs, dim=0), total_normal, total_mirror, total_etkdg
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def main():
|
|
693
|
+
exp_args, remaining = parse_torsion_infer_args()
|
|
694
|
+
original_argv = sys.argv
|
|
695
|
+
original_parse_args = infer_base_conformers.parse_args
|
|
696
|
+
|
|
697
|
+
def patched_parse_args():
|
|
698
|
+
try:
|
|
699
|
+
sys.argv = [original_argv[0]] + remaining
|
|
700
|
+
args = original_parse_args()
|
|
701
|
+
finally:
|
|
702
|
+
sys.argv = original_argv
|
|
703
|
+
args.torsion_mode_max = int(exp_args.torsion_mode_max)
|
|
704
|
+
args.torsion_delta_scale = float(exp_args.torsion_delta_scale)
|
|
705
|
+
args.iterative_torsion_steps = int(exp_args.iterative_torsion_steps)
|
|
706
|
+
args.iterative_torsion_delta_scale = float(exp_args.iterative_torsion_delta_scale)
|
|
707
|
+
args.mode_condition_strategy = str(exp_args.mode_condition_strategy)
|
|
708
|
+
args.mode_prototype_dim = int(exp_args.mode_prototype_dim)
|
|
709
|
+
args.torsion_base_confs = int(exp_args.torsion_base_confs)
|
|
710
|
+
args.torsion_base_seed_offset = int(exp_args.torsion_base_seed_offset)
|
|
711
|
+
args.torsion_base_method = str(exp_args.torsion_base_method)
|
|
712
|
+
args.torsion_jitter_scale = float(exp_args.torsion_jitter_scale)
|
|
713
|
+
args.use_dispersion_proposal = bool(exp_args.use_dispersion_proposal)
|
|
714
|
+
args.dispersion_width_scale = float(exp_args.dispersion_width_scale)
|
|
715
|
+
args.dispersion_width_min = float(exp_args.dispersion_width_min)
|
|
716
|
+
args.dispersion_width_max = float(exp_args.dispersion_width_max)
|
|
717
|
+
args.candidate_corrector_path = str(exp_args.candidate_corrector_path)
|
|
718
|
+
args.candidate_corrector_steps = int(exp_args.candidate_corrector_steps)
|
|
719
|
+
args.candidate_corrector_scale = float(exp_args.candidate_corrector_scale)
|
|
720
|
+
args.candidate_corrector_max_torsions = int(exp_args.candidate_corrector_max_torsions)
|
|
721
|
+
args.ensemble_checkpoints = str(exp_args.ensemble_checkpoints)
|
|
722
|
+
args.ensemble_iterative_torsion_delta_scales = str(exp_args.ensemble_iterative_torsion_delta_scales)
|
|
723
|
+
args.disable_stage1_pglobal = bool(exp_args.disable_stage1_pglobal)
|
|
724
|
+
args.pglobal_control = str(exp_args.pglobal_control)
|
|
725
|
+
args.pglobal_noise_std = float(exp_args.pglobal_noise_std)
|
|
726
|
+
args.pglobal_seed = int(exp_args.pglobal_seed)
|
|
727
|
+
args.pglobal_topology_scale = float(exp_args.pglobal_topology_scale)
|
|
728
|
+
args.stage1_kernel = str(exp_args.stage1_kernel)
|
|
729
|
+
args.manifold_projection_steps = int(exp_args.manifold_projection_steps)
|
|
730
|
+
args.manifold_projection_lr = float(exp_args.manifold_projection_lr)
|
|
731
|
+
args.manifold_projection_anchor = float(exp_args.manifold_projection_anchor)
|
|
732
|
+
args.manifold_use_mode_p = bool(exp_args.manifold_use_mode_p)
|
|
733
|
+
args.manifold_projection_pdist_weight = float(exp_args.manifold_projection_pdist_weight)
|
|
734
|
+
args.p_distance_topk = int(exp_args.p_distance_topk)
|
|
735
|
+
args.p_distance_min_topo = int(exp_args.p_distance_min_topo)
|
|
736
|
+
# Torsion-space checkpoints are meant to be evaluated as Manimol-only
|
|
737
|
+
# candidates by default. ETKDG is used as initialization inside
|
|
738
|
+
# sample_torsion_conformers, not as a candidate-pool member.
|
|
739
|
+
if "--etkdg_candidate_pool" not in remaining:
|
|
740
|
+
args.etkdg_candidate_pool = False
|
|
741
|
+
if "--etkdg_init_ratio" not in remaining:
|
|
742
|
+
args.etkdg_init_ratio = 1.0
|
|
743
|
+
return args
|
|
744
|
+
|
|
745
|
+
infer_base_conformers.parse_args = patched_parse_args
|
|
746
|
+
infer_base_conformers.load_model = patched_load_model_factory(exp_args)
|
|
747
|
+
infer_base_conformers.sample_conformers = sample_torsion_conformers
|
|
748
|
+
infer_base_conformers.main()
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
if __name__ == "__main__":
|
|
752
|
+
main()
|