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
manimol/refiner.py
ADDED
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
"""Generator-agnostic access to the frozen ConforMend local Refiner.
|
|
2
|
+
|
|
3
|
+
This module reorganizes the validated strict-serial refinement code behind a
|
|
4
|
+
small public API. It deliberately preserves the checkpoint schema, network
|
|
5
|
+
architecture, bond context, one-pass torsional update, and conservative
|
|
6
|
+
acceptance policy used by the best strict-serial method. It does not sample
|
|
7
|
+
conformers and does not depend on the generator that produced the candidates.
|
|
8
|
+
|
|
9
|
+
The full optional dependencies are required::
|
|
10
|
+
|
|
11
|
+
from manimol.refiner import ConforMendRefiner
|
|
12
|
+
|
|
13
|
+
refiner = ConforMendRefiner.from_checkpoint("refiner.pth", device="cuda")
|
|
14
|
+
result = refiner.refine(...)
|
|
15
|
+
|
|
16
|
+
Rejected proposals and candidates without valid rotatable bonds are returned
|
|
17
|
+
unchanged, preserving exactly one output per input candidate.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, Optional, Union
|
|
25
|
+
|
|
26
|
+
import torch
|
|
27
|
+
from torch import nn
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _torsion_rows(
|
|
31
|
+
torsion_index: Optional[torch.Tensor],
|
|
32
|
+
) -> Optional[torch.Tensor]:
|
|
33
|
+
if torsion_index is None:
|
|
34
|
+
return None
|
|
35
|
+
rows = torch.as_tensor(torsion_index)
|
|
36
|
+
if rows.ndim != 2 or rows.numel() == 0:
|
|
37
|
+
return None
|
|
38
|
+
if rows.size(0) == 4:
|
|
39
|
+
rows = rows.t()
|
|
40
|
+
if rows.size(1) < 4:
|
|
41
|
+
return None
|
|
42
|
+
return rows[:, :4]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _torsion_sincos(coords: torch.Tensor, torsion_index: torch.Tensor) -> torch.Tensor:
|
|
46
|
+
if coords.ndim == 2:
|
|
47
|
+
coords = coords.unsqueeze(0)
|
|
48
|
+
rows = torsion_index.to(device=coords.device, dtype=torch.long)
|
|
49
|
+
p0, p1, p2, p3 = (coords[:, rows[:, i], :] for i in range(4))
|
|
50
|
+
b0 = -(p1 - p0)
|
|
51
|
+
b1 = p2 - p1
|
|
52
|
+
b2 = p3 - p2
|
|
53
|
+
b1 = b1 / torch.linalg.vector_norm(b1, dim=-1, keepdim=True).clamp_min(1e-8)
|
|
54
|
+
v = b0 - (b0 * b1).sum(dim=-1, keepdim=True) * b1
|
|
55
|
+
w = b2 - (b2 * b1).sum(dim=-1, keepdim=True) * b1
|
|
56
|
+
angle = torch.atan2(
|
|
57
|
+
(torch.cross(b1, v, dim=-1) * w).sum(dim=-1),
|
|
58
|
+
(v * w).sum(dim=-1),
|
|
59
|
+
)
|
|
60
|
+
return torch.stack((torch.sin(angle), torch.cos(angle)), dim=-1)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class InterpretableLocalRefiner(nn.Module):
|
|
64
|
+
"""The checkpoint-compatible candidate-conditioned torsional Refiner."""
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
node_dim: int,
|
|
69
|
+
graph_dim: int,
|
|
70
|
+
context_dim: int = 8,
|
|
71
|
+
hidden_dim: int = 128,
|
|
72
|
+
max_delta: float = 0.8,
|
|
73
|
+
min_trust: float = 0.05,
|
|
74
|
+
max_trust: float = 0.35,
|
|
75
|
+
):
|
|
76
|
+
super().__init__()
|
|
77
|
+
self.node_dim = int(node_dim)
|
|
78
|
+
self.graph_dim = int(graph_dim)
|
|
79
|
+
self.context_dim = int(context_dim)
|
|
80
|
+
self.hidden_dim = int(hidden_dim)
|
|
81
|
+
self.max_delta = float(max_delta)
|
|
82
|
+
self.min_trust = float(min_trust)
|
|
83
|
+
self.max_trust = float(max_trust)
|
|
84
|
+
input_dim = 4 * self.node_dim + self.graph_dim + 2 + self.context_dim + 1
|
|
85
|
+
self.net = nn.Sequential(
|
|
86
|
+
nn.Linear(input_dim, hidden_dim),
|
|
87
|
+
nn.SiLU(),
|
|
88
|
+
nn.Linear(hidden_dim, hidden_dim),
|
|
89
|
+
nn.SiLU(),
|
|
90
|
+
nn.Linear(hidden_dim, 3),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def forward(
|
|
94
|
+
self,
|
|
95
|
+
node_feat: torch.Tensor,
|
|
96
|
+
graph_feat: torch.Tensor,
|
|
97
|
+
coords: torch.Tensor,
|
|
98
|
+
torsion_index: torch.Tensor,
|
|
99
|
+
context: torch.Tensor,
|
|
100
|
+
valid_mask: torch.Tensor,
|
|
101
|
+
step_index: Union[int, torch.Tensor],
|
|
102
|
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
103
|
+
if coords.ndim == 2:
|
|
104
|
+
coords = coords.unsqueeze(0)
|
|
105
|
+
rows = torsion_index.to(device=node_feat.device, dtype=torch.long)
|
|
106
|
+
batch_size, torsion_count = coords.size(0), rows.size(0)
|
|
107
|
+
atom_context = node_feat[rows].reshape(torsion_count, -1)
|
|
108
|
+
atom_context = atom_context.unsqueeze(0).expand(batch_size, -1, -1)
|
|
109
|
+
graph_context = graph_feat.reshape(1, 1, -1).expand(
|
|
110
|
+
batch_size, torsion_count, -1
|
|
111
|
+
)
|
|
112
|
+
torsion_context = _torsion_sincos(coords, rows)
|
|
113
|
+
if context.ndim == 2:
|
|
114
|
+
context = context.unsqueeze(0).expand(batch_size, -1, -1)
|
|
115
|
+
context = context.to(device=coords.device, dtype=coords.dtype)
|
|
116
|
+
step_value = torch.as_tensor(
|
|
117
|
+
step_index, device=coords.device, dtype=coords.dtype
|
|
118
|
+
).reshape(1, 1, 1)
|
|
119
|
+
step_feature = step_value.expand(batch_size, torsion_count, 1)
|
|
120
|
+
features = torch.cat(
|
|
121
|
+
(atom_context, graph_context, torsion_context, context, step_feature),
|
|
122
|
+
dim=-1,
|
|
123
|
+
)
|
|
124
|
+
raw = self.net(features)
|
|
125
|
+
delta = torch.tanh(raw[..., 0]) * self.max_delta
|
|
126
|
+
gate = torch.sigmoid(raw[..., 1])
|
|
127
|
+
trust = self.min_trust + (self.max_trust - self.min_trust) * torch.sigmoid(
|
|
128
|
+
raw[..., 2]
|
|
129
|
+
)
|
|
130
|
+
valid = valid_mask.to(device=coords.device, dtype=torch.bool).view(1, -1)
|
|
131
|
+
delta = torch.where(valid, delta, torch.zeros_like(delta))
|
|
132
|
+
gate = torch.where(valid, gate, torch.zeros_like(gate))
|
|
133
|
+
trust = torch.where(valid, trust, torch.zeros_like(trust))
|
|
134
|
+
return delta, gate, trust
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def proximity_matrix(coords: torch.Tensor, a: float, b: float) -> torch.Tensor:
|
|
138
|
+
"""Convert Cartesian distances to the Stage-I proximity representation."""
|
|
139
|
+
if coords.ndim != 2 or coords.size(-1) != 3:
|
|
140
|
+
raise ValueError("coords must have shape [atoms, 3]")
|
|
141
|
+
distance = torch.cdist(coords, coords)
|
|
142
|
+
proximity = (1.0 + float(a) * distance.pow(2.0 * float(b))).reciprocal()
|
|
143
|
+
eye = torch.eye(coords.size(0), dtype=torch.bool, device=coords.device)
|
|
144
|
+
return proximity.masked_fill(eye, 0.0)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def stable_relational_energy(
|
|
148
|
+
coords: torch.Tensor,
|
|
149
|
+
mean_prior: torch.Tensor,
|
|
150
|
+
dispersion_prior: torch.Tensor,
|
|
151
|
+
pair_mask: torch.Tensor,
|
|
152
|
+
a: float,
|
|
153
|
+
b: float,
|
|
154
|
+
eps: float = 1e-3,
|
|
155
|
+
) -> torch.Tensor:
|
|
156
|
+
"""Return the validated robust dispersion-weighted relational mismatch."""
|
|
157
|
+
proximity = proximity_matrix(coords, a=a, b=b)
|
|
158
|
+
if proximity.shape != mean_prior.shape or proximity.shape != dispersion_prior.shape:
|
|
159
|
+
raise ValueError("priors and coordinate-derived proximity must have matching shapes")
|
|
160
|
+
mask = pair_mask.to(device=proximity.device, dtype=torch.bool).clone()
|
|
161
|
+
mask.fill_diagonal_(False)
|
|
162
|
+
if not bool(mask.any()):
|
|
163
|
+
return coords.sum() * 0.0
|
|
164
|
+
residual = proximity - mean_prior.to(
|
|
165
|
+
device=proximity.device, dtype=proximity.dtype
|
|
166
|
+
)
|
|
167
|
+
variance = dispersion_prior.to(
|
|
168
|
+
device=proximity.device, dtype=proximity.dtype
|
|
169
|
+
).clamp_min(0.0)
|
|
170
|
+
scaled_square = residual.square() / (variance + float(eps))
|
|
171
|
+
robust = torch.sqrt(1.0 + scaled_square) - 1.0
|
|
172
|
+
return robust[mask].mean()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _fragment_partition(
|
|
176
|
+
mol: Any,
|
|
177
|
+
left_atom: int,
|
|
178
|
+
right_atom: int,
|
|
179
|
+
atom_count: int,
|
|
180
|
+
edge_index: Optional[torch.Tensor] = None,
|
|
181
|
+
) -> tuple[list[int], list[int]]:
|
|
182
|
+
adjacency: list[list[int]] = [[] for _ in range(atom_count)]
|
|
183
|
+
if mol is not None:
|
|
184
|
+
edges = (
|
|
185
|
+
(int(bond.GetBeginAtomIdx()), int(bond.GetEndAtomIdx()))
|
|
186
|
+
for bond in mol.GetBonds()
|
|
187
|
+
)
|
|
188
|
+
elif edge_index is not None:
|
|
189
|
+
tensor = torch.as_tensor(edge_index).detach().cpu()
|
|
190
|
+
edges = zip(tensor[0].tolist(), tensor[1].tolist())
|
|
191
|
+
else:
|
|
192
|
+
edges = ()
|
|
193
|
+
for begin, end in edges:
|
|
194
|
+
begin, end = int(begin), int(end)
|
|
195
|
+
if 0 <= begin < atom_count and 0 <= end < atom_count:
|
|
196
|
+
if end not in adjacency[begin]:
|
|
197
|
+
adjacency[begin].append(end)
|
|
198
|
+
if begin not in adjacency[end]:
|
|
199
|
+
adjacency[end].append(begin)
|
|
200
|
+
left = {left_atom}
|
|
201
|
+
stack = [left_atom]
|
|
202
|
+
while stack:
|
|
203
|
+
atom = stack.pop()
|
|
204
|
+
for neighbor in adjacency[atom]:
|
|
205
|
+
if {atom, neighbor} == {left_atom, right_atom} or neighbor in left:
|
|
206
|
+
continue
|
|
207
|
+
left.add(neighbor)
|
|
208
|
+
stack.append(neighbor)
|
|
209
|
+
right = set(range(atom_count)) - left
|
|
210
|
+
return sorted(left), sorted(right)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def bond_cross_fragment_context(
|
|
214
|
+
coords: torch.Tensor,
|
|
215
|
+
mean_prior: torch.Tensor,
|
|
216
|
+
dispersion_prior: torch.Tensor,
|
|
217
|
+
torsion_index: torch.Tensor,
|
|
218
|
+
mol: Any,
|
|
219
|
+
max_torsions: int,
|
|
220
|
+
eps: float = 1e-3,
|
|
221
|
+
edge_index: Optional[torch.Tensor] = None,
|
|
222
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
223
|
+
"""Build the same eight bond-specific features as the best Refiner."""
|
|
224
|
+
if coords.ndim != 2:
|
|
225
|
+
raise ValueError("coords must have shape [atoms, 3]")
|
|
226
|
+
current_proximity = proximity_matrix(coords, a=1.6, b=0.8)
|
|
227
|
+
rows = _torsion_rows(torsion_index)
|
|
228
|
+
limit = int(max_torsions)
|
|
229
|
+
context = coords.new_zeros((limit, 8))
|
|
230
|
+
valid = torch.zeros(limit, dtype=torch.bool, device=coords.device)
|
|
231
|
+
if (mol is None and edge_index is None) or rows is None:
|
|
232
|
+
return context, valid
|
|
233
|
+
mol_atoms = int(mol.GetNumAtoms()) if mol is not None else coords.size(0)
|
|
234
|
+
atom_count = min(coords.size(0), mol_atoms, mean_prior.size(0))
|
|
235
|
+
for index, row in enumerate(rows[:limit]):
|
|
236
|
+
j, k = int(row[1]), int(row[2])
|
|
237
|
+
if min(j, k) < 0 or max(j, k) >= atom_count:
|
|
238
|
+
continue
|
|
239
|
+
left_atoms, right_atoms = _fragment_partition(
|
|
240
|
+
mol, j, k, atom_count, edge_index=edge_index
|
|
241
|
+
)
|
|
242
|
+
if not left_atoms or not right_atoms:
|
|
243
|
+
continue
|
|
244
|
+
left = torch.tensor(left_atoms, device=coords.device, dtype=torch.long)
|
|
245
|
+
right = torch.tensor(right_atoms, device=coords.device, dtype=torch.long)
|
|
246
|
+
mean = mean_prior.to(coords.device, coords.dtype)[left][:, right].reshape(-1)
|
|
247
|
+
dispersion = (
|
|
248
|
+
dispersion_prior.to(coords.device, coords.dtype)[left][:, right]
|
|
249
|
+
.reshape(-1)
|
|
250
|
+
.clamp_min(0.0)
|
|
251
|
+
)
|
|
252
|
+
current = current_proximity[left][:, right].reshape(-1)
|
|
253
|
+
standardized = (current - mean) / torch.sqrt(dispersion + float(eps))
|
|
254
|
+
stable_cut = torch.median(dispersion)
|
|
255
|
+
context[index] = torch.stack(
|
|
256
|
+
(
|
|
257
|
+
mean.mean(),
|
|
258
|
+
dispersion.mean(),
|
|
259
|
+
torch.quantile(mean, 0.90),
|
|
260
|
+
mean.max(),
|
|
261
|
+
current.mean(),
|
|
262
|
+
standardized.mean(),
|
|
263
|
+
standardized.abs().max(),
|
|
264
|
+
(dispersion <= stable_cut).to(coords.dtype).mean(),
|
|
265
|
+
)
|
|
266
|
+
)
|
|
267
|
+
valid[index] = True
|
|
268
|
+
return context, valid
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _torsion_rotate_mask(
|
|
272
|
+
atom_count: int,
|
|
273
|
+
edge_index: Optional[torch.Tensor],
|
|
274
|
+
fixed: int,
|
|
275
|
+
moving: int,
|
|
276
|
+
device: torch.device,
|
|
277
|
+
) -> torch.Tensor:
|
|
278
|
+
mask = torch.zeros(atom_count, dtype=torch.bool, device=device)
|
|
279
|
+
if edge_index is None or edge_index.numel() == 0:
|
|
280
|
+
if 0 <= moving < atom_count:
|
|
281
|
+
mask[moving] = True
|
|
282
|
+
return mask
|
|
283
|
+
source, destination = edge_index.detach().cpu()
|
|
284
|
+
adjacency: dict[int, list[int]] = {}
|
|
285
|
+
for begin, end in zip(source.tolist(), destination.tolist()):
|
|
286
|
+
begin, end = int(begin), int(end)
|
|
287
|
+
if not (0 <= begin < atom_count and 0 <= end < atom_count) or begin == end:
|
|
288
|
+
continue
|
|
289
|
+
if (begin == fixed and end == moving) or (begin == moving and end == fixed):
|
|
290
|
+
continue
|
|
291
|
+
adjacency.setdefault(begin, []).append(end)
|
|
292
|
+
stack = [int(moving)]
|
|
293
|
+
seen = {int(fixed)}
|
|
294
|
+
while stack:
|
|
295
|
+
atom = stack.pop()
|
|
296
|
+
if atom in seen or not (0 <= atom < atom_count):
|
|
297
|
+
continue
|
|
298
|
+
seen.add(atom)
|
|
299
|
+
mask[atom] = True
|
|
300
|
+
for neighbor in adjacency.get(atom, []):
|
|
301
|
+
if neighbor not in seen:
|
|
302
|
+
stack.append(neighbor)
|
|
303
|
+
return mask
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _rotate_points_around_axis(
|
|
307
|
+
points: torch.Tensor,
|
|
308
|
+
p0: torch.Tensor,
|
|
309
|
+
p1: torch.Tensor,
|
|
310
|
+
angle: torch.Tensor,
|
|
311
|
+
) -> torch.Tensor:
|
|
312
|
+
axis = p1 - p0
|
|
313
|
+
axis = axis / torch.norm(axis).clamp(min=1e-8)
|
|
314
|
+
relative = points - p0
|
|
315
|
+
cosine = torch.cos(angle)
|
|
316
|
+
sine = torch.sin(angle)
|
|
317
|
+
cross = torch.cross(axis.view(1, 3).expand_as(relative), relative, dim=-1)
|
|
318
|
+
dot = (relative * axis.view(1, 3)).sum(dim=-1, keepdim=True)
|
|
319
|
+
return (
|
|
320
|
+
p0
|
|
321
|
+
+ relative * cosine
|
|
322
|
+
+ cross * sine
|
|
323
|
+
+ axis.view(1, 3) * dot * (1.0 - cosine)
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def apply_torsion_residuals(
|
|
328
|
+
coords: torch.Tensor,
|
|
329
|
+
torsions: torch.Tensor,
|
|
330
|
+
deltas: torch.Tensor,
|
|
331
|
+
edge_index: Optional[torch.Tensor],
|
|
332
|
+
max_torsions: int = 64,
|
|
333
|
+
) -> torch.Tensor:
|
|
334
|
+
"""Apply the validated sequential rigid-side torsion rotations."""
|
|
335
|
+
rows = _torsion_rows(torsions)
|
|
336
|
+
if rows is None:
|
|
337
|
+
return coords
|
|
338
|
+
rows = rows[: min(int(max_torsions), rows.size(0), deltas.size(0))].to(
|
|
339
|
+
coords.device
|
|
340
|
+
).long()
|
|
341
|
+
valid = (rows >= 0).all(dim=1) & (rows < coords.size(0)).all(dim=1)
|
|
342
|
+
rows = rows[valid]
|
|
343
|
+
deltas = deltas[: valid.size(0)][valid]
|
|
344
|
+
if rows.numel() == 0:
|
|
345
|
+
return coords
|
|
346
|
+
output = coords
|
|
347
|
+
for index, row in enumerate(rows):
|
|
348
|
+
_, j, k, _ = [int(value) for value in row.detach().cpu().tolist()]
|
|
349
|
+
side = _torsion_rotate_mask(
|
|
350
|
+
output.size(0), edge_index, fixed=j, moving=k, device=output.device
|
|
351
|
+
)
|
|
352
|
+
if int(side.sum().item()) == 0:
|
|
353
|
+
continue
|
|
354
|
+
rotated = _rotate_points_around_axis(
|
|
355
|
+
output[side], output[j], output[k], deltas[index]
|
|
356
|
+
)
|
|
357
|
+
output = output.clone()
|
|
358
|
+
output[side] = rotated
|
|
359
|
+
return torch.nan_to_num(output, nan=0.0, posinf=0.0, neginf=0.0)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
@dataclass(frozen=True)
|
|
363
|
+
class AcceptanceConfig:
|
|
364
|
+
"""Published conservative acceptance defaults for one-pass refinement."""
|
|
365
|
+
|
|
366
|
+
gate_threshold: float = 0.5
|
|
367
|
+
energy_tolerance: float = 1e-6
|
|
368
|
+
max_atom_displacement: float = 0.5
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def accept_refinement(
|
|
372
|
+
seeds: torch.Tensor,
|
|
373
|
+
proposals: torch.Tensor,
|
|
374
|
+
before_energy: torch.Tensor,
|
|
375
|
+
after_energy: torch.Tensor,
|
|
376
|
+
gate: torch.Tensor,
|
|
377
|
+
config: AcceptanceConfig,
|
|
378
|
+
) -> tuple[torch.Tensor, tuple[str, ...]]:
|
|
379
|
+
"""Apply gate, displacement, and relational-energy checks in that order."""
|
|
380
|
+
if seeds.shape != proposals.shape or seeds.ndim != 3:
|
|
381
|
+
raise ValueError("seeds and proposals must have equal [batch, atoms, 3] shape")
|
|
382
|
+
accepted = torch.zeros(seeds.size(0), dtype=torch.bool, device=seeds.device)
|
|
383
|
+
reasons: list[str] = []
|
|
384
|
+
for index in range(seeds.size(0)):
|
|
385
|
+
if not bool(torch.isfinite(proposals[index]).all()):
|
|
386
|
+
reasons.append("nonfinite")
|
|
387
|
+
continue
|
|
388
|
+
if float(gate[index].mean().item()) < float(config.gate_threshold):
|
|
389
|
+
reasons.append("low_gate")
|
|
390
|
+
continue
|
|
391
|
+
displacement = torch.linalg.vector_norm(
|
|
392
|
+
proposals[index] - seeds[index], dim=-1
|
|
393
|
+
).max()
|
|
394
|
+
if float(displacement.item()) > float(config.max_atom_displacement):
|
|
395
|
+
reasons.append("geometry_displacement")
|
|
396
|
+
continue
|
|
397
|
+
if float(after_energy[index].item()) > float(
|
|
398
|
+
before_energy[index].item()
|
|
399
|
+
) + float(config.energy_tolerance):
|
|
400
|
+
reasons.append("relational_energy")
|
|
401
|
+
continue
|
|
402
|
+
accepted[index] = True
|
|
403
|
+
reasons.append("accepted")
|
|
404
|
+
return accepted, tuple(reasons)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _compose_one_output_per_seed(
|
|
408
|
+
seeds: torch.Tensor,
|
|
409
|
+
proposals: torch.Tensor,
|
|
410
|
+
accepted: torch.Tensor,
|
|
411
|
+
) -> torch.Tensor:
|
|
412
|
+
mask = accepted.to(device=seeds.device, dtype=torch.bool).view(-1, 1, 1)
|
|
413
|
+
return torch.where(mask, proposals, seeds)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
@dataclass(frozen=True)
|
|
417
|
+
class RefinementResult:
|
|
418
|
+
"""One-to-one refined pool and auditable acceptance diagnostics."""
|
|
419
|
+
|
|
420
|
+
conformers: torch.Tensor
|
|
421
|
+
accepted: torch.Tensor
|
|
422
|
+
reasons: tuple[str, ...]
|
|
423
|
+
gate_mean: torch.Tensor
|
|
424
|
+
max_displacement: torch.Tensor
|
|
425
|
+
energy_before: torch.Tensor
|
|
426
|
+
energy_after: torch.Tensor
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
class ConforMendRefiner:
|
|
430
|
+
"""Standalone one-pass Refiner for candidates from heterogeneous generators."""
|
|
431
|
+
|
|
432
|
+
def __init__(
|
|
433
|
+
self,
|
|
434
|
+
model: InterpretableLocalRefiner,
|
|
435
|
+
*,
|
|
436
|
+
device: Union[str, torch.device] = "cpu",
|
|
437
|
+
acceptance: Optional[AcceptanceConfig] = None,
|
|
438
|
+
):
|
|
439
|
+
self.device = torch.device(device)
|
|
440
|
+
self.model = model.to(self.device).eval()
|
|
441
|
+
self.acceptance = acceptance or AcceptanceConfig()
|
|
442
|
+
|
|
443
|
+
@classmethod
|
|
444
|
+
def from_checkpoint(
|
|
445
|
+
cls,
|
|
446
|
+
checkpoint: Union[str, Path],
|
|
447
|
+
*,
|
|
448
|
+
device: Union[str, torch.device] = "cpu",
|
|
449
|
+
acceptance: Optional[AcceptanceConfig] = None,
|
|
450
|
+
) -> "ConforMendRefiner":
|
|
451
|
+
"""Load the unchanged ``interpretable_local_refiner_v1`` checkpoint."""
|
|
452
|
+
try:
|
|
453
|
+
state = torch.load(checkpoint, map_location=device, weights_only=False)
|
|
454
|
+
except TypeError: # Torch versions before ``weights_only``.
|
|
455
|
+
state = torch.load(checkpoint, map_location=device)
|
|
456
|
+
required = {
|
|
457
|
+
"model_state_dict",
|
|
458
|
+
"node_dim",
|
|
459
|
+
"graph_dim",
|
|
460
|
+
"context_dim",
|
|
461
|
+
"hidden_dim",
|
|
462
|
+
}
|
|
463
|
+
missing = sorted(required.difference(state))
|
|
464
|
+
if missing:
|
|
465
|
+
raise ValueError(f"Refiner checkpoint is missing fields: {', '.join(missing)}")
|
|
466
|
+
model = InterpretableLocalRefiner(
|
|
467
|
+
node_dim=int(state["node_dim"]),
|
|
468
|
+
graph_dim=int(state["graph_dim"]),
|
|
469
|
+
context_dim=int(state["context_dim"]),
|
|
470
|
+
hidden_dim=int(state["hidden_dim"]),
|
|
471
|
+
)
|
|
472
|
+
model.load_state_dict(state["model_state_dict"], strict=True)
|
|
473
|
+
return cls(model, device=device, acceptance=acceptance)
|
|
474
|
+
|
|
475
|
+
@torch.no_grad()
|
|
476
|
+
def refine(
|
|
477
|
+
self,
|
|
478
|
+
*,
|
|
479
|
+
node_feat: torch.Tensor,
|
|
480
|
+
graph_feat: torch.Tensor,
|
|
481
|
+
conformers: torch.Tensor,
|
|
482
|
+
mean_prior: torch.Tensor,
|
|
483
|
+
dispersion_prior: torch.Tensor,
|
|
484
|
+
torsion_index: torch.Tensor,
|
|
485
|
+
edge_index: Optional[torch.Tensor],
|
|
486
|
+
kernel_a: float,
|
|
487
|
+
kernel_b: float,
|
|
488
|
+
mol: Any = None,
|
|
489
|
+
pair_mask: Optional[torch.Tensor] = None,
|
|
490
|
+
max_torsions: int = 64,
|
|
491
|
+
step_index: int = 0,
|
|
492
|
+
) -> RefinementResult:
|
|
493
|
+
"""Refine a candidate pool without using reference conformers.
|
|
494
|
+
|
|
495
|
+
``conformers`` has shape ``[candidates, atoms, 3]``. The graph
|
|
496
|
+
features and predicted pairwise priors are shared across candidates;
|
|
497
|
+
candidate-specific cross-bond discrepancies are recomputed for every
|
|
498
|
+
input conformation. ``kernel_a`` and ``kernel_b`` are explicit because
|
|
499
|
+
the validated strict-serial method obtains them from the frozen base
|
|
500
|
+
model; silent fixed defaults would change its relational-energy check.
|
|
501
|
+
"""
|
|
502
|
+
if conformers.ndim != 3 or conformers.size(-1) != 3:
|
|
503
|
+
raise ValueError("conformers must have shape [candidates, atoms, 3]")
|
|
504
|
+
if conformers.size(0) == 0:
|
|
505
|
+
raise ValueError("conformers must contain at least one candidate")
|
|
506
|
+
original_device = conformers.device
|
|
507
|
+
original_dtype = conformers.dtype
|
|
508
|
+
seeds = conformers.to(device=self.device)
|
|
509
|
+
dtype = next(self.model.parameters()).dtype
|
|
510
|
+
seeds = seeds.to(dtype=dtype)
|
|
511
|
+
node = node_feat.to(device=self.device, dtype=dtype)
|
|
512
|
+
graph = graph_feat.to(device=self.device, dtype=dtype).reshape(-1)
|
|
513
|
+
mean = mean_prior.to(device=self.device, dtype=dtype)
|
|
514
|
+
dispersion = dispersion_prior.to(device=self.device, dtype=dtype)
|
|
515
|
+
edges = None if edge_index is None else edge_index.to(self.device)
|
|
516
|
+
torsions = torch.as_tensor(torsion_index, device=self.device)
|
|
517
|
+
rows = _torsion_rows(torsions)
|
|
518
|
+
|
|
519
|
+
empty_float = torch.zeros(seeds.size(0), device=self.device, dtype=dtype)
|
|
520
|
+
if rows is None:
|
|
521
|
+
return RefinementResult(
|
|
522
|
+
conformers=conformers.clone(),
|
|
523
|
+
accepted=torch.zeros(seeds.size(0), dtype=torch.bool),
|
|
524
|
+
reasons=tuple("no_valid_torsions" for _ in range(seeds.size(0))),
|
|
525
|
+
gate_mean=empty_float.cpu(),
|
|
526
|
+
max_displacement=empty_float.cpu(),
|
|
527
|
+
energy_before=empty_float.cpu(),
|
|
528
|
+
energy_after=empty_float.cpu(),
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
rows = rows[: min(int(max_torsions), rows.size(0))].long()
|
|
532
|
+
valid_rows = (rows >= 0).all(dim=1) & (rows < node.size(0)).all(dim=1)
|
|
533
|
+
rows = rows[valid_rows]
|
|
534
|
+
if rows.numel() == 0:
|
|
535
|
+
return RefinementResult(
|
|
536
|
+
conformers=conformers.clone(),
|
|
537
|
+
accepted=torch.zeros(seeds.size(0), dtype=torch.bool),
|
|
538
|
+
reasons=tuple("no_valid_torsions" for _ in range(seeds.size(0))),
|
|
539
|
+
gate_mean=empty_float.cpu(),
|
|
540
|
+
max_displacement=empty_float.cpu(),
|
|
541
|
+
energy_before=empty_float.cpu(),
|
|
542
|
+
energy_after=empty_float.cpu(),
|
|
543
|
+
)
|
|
544
|
+
|
|
545
|
+
if pair_mask is None:
|
|
546
|
+
off_diagonal = ~torch.eye(node.size(0), dtype=torch.bool, device=self.device)
|
|
547
|
+
informative = dispersion[off_diagonal]
|
|
548
|
+
if informative.numel() == 0:
|
|
549
|
+
effective_mask = off_diagonal
|
|
550
|
+
else:
|
|
551
|
+
effective_mask = off_diagonal & (
|
|
552
|
+
dispersion <= torch.quantile(informative, 0.5)
|
|
553
|
+
)
|
|
554
|
+
else:
|
|
555
|
+
effective_mask = pair_mask.to(device=self.device, dtype=torch.bool)
|
|
556
|
+
|
|
557
|
+
proposals = []
|
|
558
|
+
gates = []
|
|
559
|
+
before_energies = []
|
|
560
|
+
after_energies = []
|
|
561
|
+
for seed in seeds:
|
|
562
|
+
context, valid = bond_cross_fragment_context(
|
|
563
|
+
seed,
|
|
564
|
+
mean,
|
|
565
|
+
dispersion,
|
|
566
|
+
torsions,
|
|
567
|
+
mol,
|
|
568
|
+
int(max_torsions),
|
|
569
|
+
edge_index=edges,
|
|
570
|
+
)
|
|
571
|
+
context = context[: valid_rows.numel()][valid_rows]
|
|
572
|
+
valid = valid[: valid_rows.numel()][valid_rows]
|
|
573
|
+
if not bool(valid.any()):
|
|
574
|
+
proposals.append(seed)
|
|
575
|
+
gates.append(torch.zeros(rows.size(0), device=self.device, dtype=dtype))
|
|
576
|
+
before = stable_relational_energy(
|
|
577
|
+
seed, mean, dispersion, effective_mask, kernel_a, kernel_b
|
|
578
|
+
)
|
|
579
|
+
before_energies.append(before)
|
|
580
|
+
after_energies.append(before)
|
|
581
|
+
continue
|
|
582
|
+
delta, gate, trust = self.model(
|
|
583
|
+
node,
|
|
584
|
+
graph,
|
|
585
|
+
seed,
|
|
586
|
+
rows,
|
|
587
|
+
context,
|
|
588
|
+
valid,
|
|
589
|
+
step_index=step_index,
|
|
590
|
+
)
|
|
591
|
+
applied = (gate * delta).clamp(min=-trust, max=trust)
|
|
592
|
+
proposal = apply_torsion_residuals(
|
|
593
|
+
seed,
|
|
594
|
+
rows,
|
|
595
|
+
applied[0],
|
|
596
|
+
edges,
|
|
597
|
+
max_torsions=rows.size(0),
|
|
598
|
+
)
|
|
599
|
+
before = stable_relational_energy(
|
|
600
|
+
seed, mean, dispersion, effective_mask, kernel_a, kernel_b
|
|
601
|
+
)
|
|
602
|
+
after = stable_relational_energy(
|
|
603
|
+
proposal, mean, dispersion, effective_mask, kernel_a, kernel_b
|
|
604
|
+
)
|
|
605
|
+
proposals.append(proposal)
|
|
606
|
+
gates.append(gate[0])
|
|
607
|
+
before_energies.append(before)
|
|
608
|
+
after_energies.append(after)
|
|
609
|
+
|
|
610
|
+
proposal_pool = torch.stack(proposals)
|
|
611
|
+
gate_pool = torch.stack(gates)
|
|
612
|
+
energy_before = torch.stack(before_energies)
|
|
613
|
+
energy_after = torch.stack(after_energies)
|
|
614
|
+
accepted, reasons = accept_refinement(
|
|
615
|
+
seeds,
|
|
616
|
+
proposal_pool,
|
|
617
|
+
energy_before,
|
|
618
|
+
energy_after,
|
|
619
|
+
gate_pool,
|
|
620
|
+
self.acceptance,
|
|
621
|
+
)
|
|
622
|
+
output = _compose_one_output_per_seed(seeds, proposal_pool, accepted)
|
|
623
|
+
displacement = torch.linalg.vector_norm(proposal_pool - seeds, dim=-1).amax(dim=1)
|
|
624
|
+
return RefinementResult(
|
|
625
|
+
conformers=output.to(device=original_device, dtype=original_dtype),
|
|
626
|
+
accepted=accepted.detach().cpu(),
|
|
627
|
+
reasons=reasons,
|
|
628
|
+
gate_mean=gate_pool.mean(dim=1).detach().cpu(),
|
|
629
|
+
max_displacement=displacement.detach().cpu(),
|
|
630
|
+
energy_before=energy_before.detach().cpu(),
|
|
631
|
+
energy_after=energy_after.detach().cpu(),
|
|
632
|
+
)
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
__all__ = [
|
|
636
|
+
"AcceptanceConfig",
|
|
637
|
+
"ConforMendRefiner",
|
|
638
|
+
"InterpretableLocalRefiner",
|
|
639
|
+
"RefinementResult",
|
|
640
|
+
"accept_refinement",
|
|
641
|
+
"apply_torsion_residuals",
|
|
642
|
+
"bond_cross_fragment_context",
|
|
643
|
+
"proximity_matrix",
|
|
644
|
+
"stable_relational_energy",
|
|
645
|
+
]
|