dualmapref 0.2.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. args_parse.py +593 -0
  2. candidate_corrector.py +161 -0
  3. candidate_scorer.py +359 -0
  4. conformend/__init__.py +36 -0
  5. conformend/refiner.py +25 -0
  6. dataset/__init__.py +1 -0
  7. dataset/drugdataset.py +644 -0
  8. dataset/manifold.py +237 -0
  9. dataset/sharded_drugdataset.py +124 -0
  10. dataset/smiles2graph.py +217 -0
  11. dualmapref/__init__.py +24 -0
  12. dualmapref/refiner.py +16 -0
  13. dualmapref-0.2.8.dist-info/LICENSE +21 -0
  14. dualmapref-0.2.8.dist-info/METADATA +167 -0
  15. dualmapref-0.2.8.dist-info/RECORD +186 -0
  16. dualmapref-0.2.8.dist-info/WHEEL +5 -0
  17. dualmapref-0.2.8.dist-info/entry_points.txt +10 -0
  18. dualmapref-0.2.8.dist-info/top_level.txt +29 -0
  19. exputils.py +289 -0
  20. infer.py +23 -0
  21. infer_base_conformers.py +5589 -0
  22. infer_mean_dispersion_torsion.py +1117 -0
  23. infer_torsion.py +752 -0
  24. infer_torsional_denoiser.py +1021 -0
  25. manimol/__init__.py +30 -0
  26. manimol/__main__.py +6 -0
  27. manimol/cli.py +36 -0
  28. manimol/full_cli.py +41 -0
  29. manimol/legacy_imports.py +43 -0
  30. manimol/manifest.py +56 -0
  31. manimol/postprocess.py +148 -0
  32. manimol/priors.py +60 -0
  33. manimol/protocols.py +119 -0
  34. manimol/refiner.py +645 -0
  35. manimol/runtime.py +194 -0
  36. manimol/selection.py +85 -0
  37. manimol/torsion.py +22 -0
  38. manimol/train_cli.py +14 -0
  39. mixture_flow/src/__init__.py +1 -0
  40. mixture_flow/src/_path.py +7 -0
  41. mixture_flow/src/infer28_mixture_torsion_flow.py +1093 -0
  42. mixture_flow/src/mixture_torsion_flow.py +291 -0
  43. mixture_flow/src/summarize_mixture_debug.py +80 -0
  44. mixture_flow/src/train28_mixture_torsion_flow.py +583 -0
  45. mixture_torsion_flow.py +7 -0
  46. models/ manifold_learning.py +86 -0
  47. models/__init__.py +8 -0
  48. models/dist.py +273 -0
  49. models/dist2coords.py +23 -0
  50. models/egnn.py +107 -0
  51. models/experimental_backbones.py +364 -0
  52. models/gnnconv.py +512 -0
  53. models/kernel_inversion.py +141 -0
  54. models/kernels.py +427 -0
  55. models/losses.py +154 -0
  56. models/mean_dispersion_bridge.py +119 -0
  57. models/mean_dispersion_torsion_context.py +155 -0
  58. models/model.py +73 -0
  59. models/model0.py +2375 -0
  60. models/vis.py +128 -0
  61. pgraph_controls.py +107 -0
  62. scripts/__init__.py +2 -0
  63. scripts/analyze_basin_alignment.py +63 -0
  64. scripts/analyze_hif2a_conformer_aggregation.py +267 -0
  65. scripts/analyze_hif2a_contact_pharmacophore.py +1111 -0
  66. scripts/analyze_hif2a_fixed_budget.py +202 -0
  67. scripts/analyze_hif2a_pharmacophore.py +405 -0
  68. scripts/analyze_hif2a_pharmacophore_match_metric.py +386 -0
  69. scripts/analyze_p_control_candidate_flow.py +154 -0
  70. scripts/analyze_scaffold_basin.py +83 -0
  71. scripts/audit_dispersion_proposals.py +208 -0
  72. scripts/audit_etflow_protocol.py +258 -0
  73. scripts/audit_external_overlap.py +150 -0
  74. scripts/audit_oldbest_fulltrainval_split.py +82 -0
  75. scripts/audit_pdbbind_contact_pharmacophores.py +146 -0
  76. scripts/audit_qm9_geomol_test_split.py +94 -0
  77. scripts/audit_stage1_stage2_cross.py +131 -0
  78. scripts/build_geom_drugs_lowref_diagnostic.py +84 -0
  79. scripts/build_qm9_backfill_manifest.py +99 -0
  80. scripts/check_etflow_runtime.py +56 -0
  81. scripts/compare_prior_sources.py +122 -0
  82. scripts/compose_binding_mode_figure.py +87 -0
  83. scripts/compose_hif2a_contact_pharmacophore_suppfig.py +255 -0
  84. scripts/compose_hif2a_functional_geometry_pipeline.py +266 -0
  85. scripts/compose_manimol_internal_architecture.py +291 -0
  86. scripts/diagnose_flow_basin_intervention.py +54 -0
  87. scripts/diagnose_hif2a_pharmacophore_budget.py +185 -0
  88. scripts/diagnose_route2_p_ranking.py +123 -0
  89. scripts/discover_binding_mode_inputs.py +30 -0
  90. scripts/evaluate_functional_prior_stage1.py +230 -0
  91. scripts/evaluate_geomanimol.py +74 -0
  92. scripts/evaluate_geomanimol_flow.py +23 -0
  93. scripts/evaluate_geomanimol_multiscaffold.py +46 -0
  94. scripts/evaluate_geomanimol_residual.py +45 -0
  95. scripts/evaluate_geomanimol_torsion.py +40 -0
  96. scripts/evaluate_hif2a_bioactive_enrichment.py +91 -0
  97. scripts/evaluate_hif2a_pms_suite.py +440 -0
  98. scripts/evaluate_pdbbind_contact_pms.py +155 -0
  99. scripts/evaluate_platinum_external.py +114 -0
  100. scripts/evaluate_platinum_pool.py +82 -0
  101. scripts/evaluate_route2_calibrated_p.py +104 -0
  102. scripts/evaluate_route2_library_components.py +596 -0
  103. scripts/evaluate_route2_p_basin_budget.py +288 -0
  104. scripts/evaluate_stage1_checkpoint_only.py +30 -0
  105. scripts/export_dispersion_bond_audit.py +136 -0
  106. scripts/export_top20_shards.py +207 -0
  107. scripts/external_validation_metrics.py +152 -0
  108. scripts/fit_topology_prior.py +117 -0
  109. scripts/frozen_dispersion_audit.py +281 -0
  110. scripts/geomanimol_debug.py +50 -0
  111. scripts/geomanimol_smoke.py +37 -0
  112. scripts/infer_etflow_matched.py +524 -0
  113. scripts/inspect_checkpoint.py +12 -0
  114. scripts/inspect_conformer_capacity.py +71 -0
  115. scripts/inspect_pool.py +12 -0
  116. scripts/make_figure3_selection_loss.py +474 -0
  117. scripts/make_figure3_selection_summary.py +275 -0
  118. scripts/make_geom_debug_subset.py +62 -0
  119. scripts/make_low_reference_test_subset.py +70 -0
  120. scripts/merge_stage1_into_stage2.py +82 -0
  121. scripts/place_hif2a_candidates_for_evaluation.py +66 -0
  122. scripts/plot_hif2a_low_budget_efficiency.py +100 -0
  123. scripts/plot_prior_validation.py +48 -0
  124. scripts/precompute_stage2_assignments.py +90 -0
  125. scripts/prepare_bace_activity.py +98 -0
  126. scripts/prepare_bace_etkdg_benchmark.py +90 -0
  127. scripts/prepare_figure5_4x4_cases.py +470 -0
  128. scripts/prepare_geom_drugs_geomol_top20.py +472 -0
  129. scripts/prepare_pdbbind_core_raw.py +90 -0
  130. scripts/prepare_platinum_raw.py +74 -0
  131. scripts/prepare_pubchem_etkdg.py +54 -0
  132. scripts/rebuild_hif2a_final_sdf_and_metrics.py +55 -0
  133. scripts/rebuild_hif2a_fixed_pool_sweep.py +175 -0
  134. scripts/rebuild_hif2a_strict.py +220 -0
  135. scripts/recompute_hif2a_bootstrap.py +63 -0
  136. scripts/reference_free_geometry.py +112 -0
  137. scripts/render_binding_modes.py +413 -0
  138. scripts/render_figure5_4x4.py +330 -0
  139. scripts/render_figure6_pharmacophore_pymol.py +162 -0
  140. scripts/render_hif2a_contact_pharmacophore_pymol.py +414 -0
  141. scripts/render_hif2a_figure11.py +397 -0
  142. scripts/run_bace_2d_baseline.py +73 -0
  143. scripts/run_drugs_validation_matrix.py +225 -0
  144. scripts/run_external_reference_free.py +53 -0
  145. scripts/run_manimol_finalk_sensitivity.py +106 -0
  146. scripts/run_manimol_oversampling_sensitivity.py +109 -0
  147. scripts/run_pdisp_matched_intervention.py +116 -0
  148. scripts/run_stage1_stage2_cross20.py +83 -0
  149. scripts/score_hif2a_candidates_with_pgraph.py +221 -0
  150. scripts/summarize_dispersion_intervention.py +88 -0
  151. scripts/test_mean_dispersion_bridge.py +50 -0
  152. scripts/train_dispersion_head_diagnostic.py +320 -0
  153. scripts/train_dispersion_head_streaming.py +519 -0
  154. scripts/train_geomanimol.py +100 -0
  155. scripts/train_geomanimol_flow.py +26 -0
  156. scripts/train_geomanimol_residual.py +70 -0
  157. scripts/train_geomanimol_torsion.py +50 -0
  158. scripts/train_quantile_representation_diagnostic.py +204 -0
  159. scripts/validate_mean_dispersion_prior.py +173 -0
  160. scripts/validate_packed_shard.py +41 -0
  161. scripts/validate_stage1_prior.py +221 -0
  162. scripts/validate_top20_shards.py +36 -0
  163. scripts/validation/__init__.py +1 -0
  164. scripts/validation/hif2a_downstream_baselines.py +105 -0
  165. scripts/validation/hif2a_pairwise_ranker.py +218 -0
  166. scripts/verify_binding_mode_figure.py +47 -0
  167. torsion_manifold.py +281 -0
  168. train.py +78 -0
  169. train_graph_encoder.py +206 -0
  170. train_local_torsion_corrector.py +511 -0
  171. train_mean_dispersion_torsion_prior.py +329 -0
  172. train_probability_basin.py +235 -0
  173. train_torsion_generator.py +1631 -0
  174. train_torsion_manifold_prior.py +258 -0
  175. train_torsional_denoiser.py +415 -0
  176. trainer.py +1038 -0
  177. utils/__init__.py +7 -0
  178. utils/checkpoint.py +40 -0
  179. utils/device.py +17 -0
  180. utils/helpers.py +98 -0
  181. utils/kabsch.py +29 -0
  182. utils/lookup_table.py +164 -0
  183. utils/metrics.py +50 -0
  184. utils/optuna.py +111 -0
  185. utils/save_mol.py +366 -0
  186. utils/util.py +36 -0
candidate_corrector.py ADDED
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env python3
2
+ """Lightweight post-hoc torsion corrector.
3
+
4
+ The corrector is intentionally independent of the main Manimol checkpoint. It
5
+ learns small local torsion deltas from generated candidates to their nearest
6
+ train/valid reference conformers, then can be applied during inference without
7
+ using test references.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from typing import Optional
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+
18
+ from models.model0 import _torsion_rows, apply_torsion_residuals, periodic_angle_delta, torsion_angles
19
+
20
+
21
+ CORRECTOR_FEATURE_DIM = 16
22
+
23
+
24
+ class TorsionCandidateCorrector(nn.Module):
25
+ def __init__(
26
+ self,
27
+ feature_dim: int = CORRECTOR_FEATURE_DIM,
28
+ hidden_dim: int = 128,
29
+ max_delta: float = 0.45,
30
+ ):
31
+ super().__init__()
32
+ self.max_delta = float(max_delta)
33
+ self.net = nn.Sequential(
34
+ nn.Linear(int(feature_dim), int(hidden_dim)),
35
+ nn.SiLU(),
36
+ nn.Linear(int(hidden_dim), int(hidden_dim)),
37
+ nn.SiLU(),
38
+ nn.Linear(int(hidden_dim), 1),
39
+ )
40
+ self.register_buffer("feature_mean", torch.zeros(int(feature_dim)))
41
+ self.register_buffer("feature_std", torch.ones(int(feature_dim)))
42
+
43
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
44
+ x = (features - self.feature_mean.to(features.device)) / self.feature_std.to(features.device).clamp_min(1e-6)
45
+ return torch.tanh(self.net(x).view(-1)) * self.max_delta
46
+
47
+
48
+ def _safe_dist(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
49
+ return torch.norm(a - b).clamp(0.0, 20.0)
50
+
51
+
52
+ def torsion_corrector_features(
53
+ coords: torch.Tensor,
54
+ torsion_index: Optional[torch.Tensor],
55
+ max_torsions: int = 64,
56
+ ) -> torch.Tensor:
57
+ rows = _torsion_rows(torsion_index)
58
+ if rows is None:
59
+ return coords.new_zeros((0, CORRECTOR_FEATURE_DIM))
60
+ rows = rows[: min(int(max_torsions), rows.size(0))].to(coords.device).long()
61
+ valid = (rows >= 0).all(dim=1) & (rows < coords.size(0)).all(dim=1)
62
+ rows = rows[valid]
63
+ if rows.numel() == 0:
64
+ return coords.new_zeros((0, CORRECTOR_FEATURE_DIM))
65
+
66
+ coords = coords.float()
67
+ centered = coords - coords.mean(dim=0, keepdim=True)
68
+ radius = torch.sqrt((centered * centered).sum(dim=1).mean() + 1e-8)
69
+ angles = torsion_angles(coords, rows)
70
+ feats = []
71
+ denom = max(1.0, float(rows.size(0) - 1))
72
+ for idx, row in enumerate(rows):
73
+ i, j, k, l = [int(x) for x in row.detach().cpu().tolist()]
74
+ b = coords[k] - coords[j]
75
+ b_norm = torch.norm(b).clamp_min(1e-6)
76
+ left = coords[i] - coords[j]
77
+ right = coords[l] - coords[k]
78
+ cos_lr = torch.dot(left, right) / (torch.norm(left).clamp_min(1e-6) * torch.norm(right).clamp_min(1e-6))
79
+ local = torch.stack(
80
+ [
81
+ torch.sin(angles[idx]),
82
+ torch.cos(angles[idx]),
83
+ _safe_dist(coords[i], coords[j]),
84
+ _safe_dist(coords[j], coords[k]),
85
+ _safe_dist(coords[k], coords[l]),
86
+ _safe_dist(coords[i], coords[k]),
87
+ _safe_dist(coords[j], coords[l]),
88
+ _safe_dist(coords[i], coords[l]),
89
+ b_norm,
90
+ cos_lr.clamp(-1.0, 1.0),
91
+ torch.tensor(math.log1p(float(coords.size(0))), device=coords.device, dtype=coords.dtype),
92
+ radius.to(coords.device, coords.dtype),
93
+ torch.tensor(float(idx) / denom, device=coords.device, dtype=coords.dtype),
94
+ torch.tensor(float(i) / max(1.0, float(coords.size(0) - 1)), device=coords.device, dtype=coords.dtype),
95
+ torch.tensor(float(j) / max(1.0, float(coords.size(0) - 1)), device=coords.device, dtype=coords.dtype),
96
+ torch.tensor(float(k) / max(1.0, float(coords.size(0) - 1)), device=coords.device, dtype=coords.dtype),
97
+ ]
98
+ )
99
+ feats.append(local)
100
+ return torch.nan_to_num(torch.stack(feats, dim=0), nan=0.0, posinf=1e4, neginf=-1e4)
101
+
102
+
103
+ def torsion_corrector_targets(
104
+ coords: torch.Tensor,
105
+ target: torch.Tensor,
106
+ torsion_index: Optional[torch.Tensor],
107
+ max_torsions: int = 64,
108
+ ) -> torch.Tensor:
109
+ rows = _torsion_rows(torsion_index)
110
+ if rows is None:
111
+ return coords.new_zeros((0,))
112
+ rows = rows[: min(int(max_torsions), rows.size(0))].to(coords.device).long()
113
+ valid = (rows >= 0).all(dim=1) & (rows < coords.size(0)).all(dim=1)
114
+ rows = rows[valid]
115
+ if rows.numel() == 0 or target.shape != coords.shape:
116
+ return coords.new_zeros((0,))
117
+ current = torsion_angles(coords.float(), rows)
118
+ ref = torsion_angles(target.to(coords.device).float(), rows)
119
+ return periodic_angle_delta(ref, current)
120
+
121
+
122
+ @torch.no_grad()
123
+ def apply_candidate_corrector(
124
+ coords: torch.Tensor,
125
+ torsion_index: Optional[torch.Tensor],
126
+ edge_index: Optional[torch.Tensor],
127
+ corrector: Optional[TorsionCandidateCorrector],
128
+ max_torsions: int = 64,
129
+ steps: int = 1,
130
+ scale: float = 1.0,
131
+ ) -> torch.Tensor:
132
+ if corrector is None or int(steps) <= 0:
133
+ return coords
134
+ device = next(corrector.parameters()).device
135
+ out = coords.to(device).float()
136
+ torsion_index = torsion_index.to(device) if torsion_index is not None else None
137
+ edge_index = edge_index.to(device) if edge_index is not None else None
138
+ for _ in range(int(steps)):
139
+ feat = torsion_corrector_features(out, torsion_index, max_torsions=max_torsions)
140
+ if feat.numel() == 0:
141
+ break
142
+ delta = corrector(feat) * float(scale)
143
+ out = apply_torsion_residuals(
144
+ out,
145
+ torsions=torsion_index,
146
+ deltas=delta,
147
+ edge_index=edge_index,
148
+ max_torsions=int(max_torsions),
149
+ )
150
+ return out.detach().cpu()
151
+
152
+
153
+ def load_candidate_corrector(path: str, device: torch.device) -> TorsionCandidateCorrector:
154
+ ckpt = torch.load(path, map_location=device)
155
+ feature_dim = int(ckpt.get("feature_dim", CORRECTOR_FEATURE_DIM))
156
+ hidden_dim = int(ckpt.get("hidden_dim", 128))
157
+ max_delta = float(ckpt.get("max_delta", 0.45))
158
+ model = TorsionCandidateCorrector(feature_dim=feature_dim, hidden_dim=hidden_dim, max_delta=max_delta).to(device)
159
+ model.load_state_dict(ckpt["model_state_dict"], strict=True)
160
+ model.eval()
161
+ return model
candidate_scorer.py ADDED
@@ -0,0 +1,359 @@
1
+ #!/usr/bin/env python3
2
+ """Candidate conformer scoring utilities for learned reranking."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import math
7
+ from typing import Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from rdkit import Chem
12
+ from rdkit.Chem import AllChem
13
+
14
+
15
+ BASE_FEATURE_DIM = 18
16
+ POOL_FEATURE_DIM = 12
17
+ # Candidate quality alone is insufficient to test whether Stage-1 provides a
18
+ # useful geometric prior. These features summarize CE(P(G), Q(Y)) across the
19
+ # *generated* pool. They are reference-free at inference time.
20
+ P_ALIGNMENT_FEATURE_DIM = 6
21
+ FEATURE_DIM = BASE_FEATURE_DIM + POOL_FEATURE_DIM + P_ALIGNMENT_FEATURE_DIM
22
+ # State-contact features are intentionally optional. Existing 36-dimensional
23
+ # scorer checkpoints remain valid; a contact-aware reranker requests 44 dims.
24
+ CONTACT_STATE_FEATURE_DIM = 8
25
+ CONTACT_FEATURE_DIM = FEATURE_DIM + CONTACT_STATE_FEATURE_DIM
26
+
27
+
28
+ class CandidateScorer(nn.Module):
29
+ """Small MLP predicting candidate nearest-reference RMSD from geometry features."""
30
+
31
+ def __init__(self, feature_dim: int = FEATURE_DIM, hidden_dim: int = 64):
32
+ super().__init__()
33
+ self.net = nn.Sequential(
34
+ nn.Linear(feature_dim, hidden_dim),
35
+ nn.SiLU(),
36
+ nn.Linear(hidden_dim, hidden_dim),
37
+ nn.SiLU(),
38
+ nn.Linear(hidden_dim, 1),
39
+ )
40
+ self.register_buffer("feature_mean", torch.zeros(feature_dim))
41
+ self.register_buffer("feature_std", torch.ones(feature_dim))
42
+
43
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
44
+ x = (features - self.feature_mean.to(features.device)) / self.feature_std.to(features.device).clamp_min(1e-6)
45
+ return self.net(x).view(-1)
46
+
47
+
48
+ class CandidatePoolRanker(nn.Module):
49
+ """Pool-aware ranker where larger scores mean better candidates.
50
+
51
+ Unlike CandidateScorer, this model is trained with listwise/pairwise losses
52
+ inside each molecule's candidate pool. The absolute value of the output is
53
+ not an RMSD estimate; only the within-pool order is meaningful.
54
+ """
55
+
56
+ def __init__(self, feature_dim: int = FEATURE_DIM, hidden_dim: int = 128, dropout: float = 0.05):
57
+ super().__init__()
58
+ self.net = nn.Sequential(
59
+ nn.Linear(feature_dim, hidden_dim),
60
+ nn.LayerNorm(hidden_dim),
61
+ nn.SiLU(),
62
+ nn.Dropout(float(dropout)),
63
+ nn.Linear(hidden_dim, hidden_dim),
64
+ nn.LayerNorm(hidden_dim),
65
+ nn.SiLU(),
66
+ nn.Dropout(float(dropout)),
67
+ nn.Linear(hidden_dim, 1),
68
+ )
69
+ self.register_buffer("feature_mean", torch.zeros(feature_dim))
70
+ self.register_buffer("feature_std", torch.ones(feature_dim))
71
+
72
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
73
+ x = (features - self.feature_mean.to(features.device)) / self.feature_std.to(features.device).clamp_min(1e-6)
74
+ return self.net(x).view(-1)
75
+
76
+
77
+ def _heavy_mask_from_mol(mol: Optional[Chem.Mol], n_atoms: int) -> torch.Tensor:
78
+ if mol is None:
79
+ return torch.ones(n_atoms, dtype=torch.bool)
80
+ vals = []
81
+ for atom in mol.GetAtoms():
82
+ vals.append(atom.GetAtomicNum() > 1)
83
+ if len(vals) != n_atoms:
84
+ return torch.ones(n_atoms, dtype=torch.bool)
85
+ return torch.tensor(vals, dtype=torch.bool)
86
+
87
+
88
+ def _pair_stats(coords: torch.Tensor) -> torch.Tensor:
89
+ if coords.size(0) <= 1:
90
+ return coords.new_zeros(6)
91
+ dist = torch.cdist(coords.float(), coords.float(), p=2)
92
+ eye = torch.eye(dist.size(0), dtype=torch.bool, device=dist.device)
93
+ vals = dist[~eye]
94
+ if vals.numel() == 0:
95
+ return coords.new_zeros(6)
96
+ return torch.stack(
97
+ [
98
+ vals.min(),
99
+ vals.mean(),
100
+ vals.std(unbiased=False),
101
+ torch.quantile(vals, 0.10),
102
+ torch.quantile(vals, 0.50),
103
+ torch.quantile(vals, 0.90),
104
+ ]
105
+ )
106
+
107
+
108
+ def _bond_stats(coords: torch.Tensor, mol: Optional[Chem.Mol]) -> torch.Tensor:
109
+ if mol is None:
110
+ return coords.new_zeros(4)
111
+ vals = []
112
+ for bond in mol.GetBonds():
113
+ i = int(bond.GetBeginAtomIdx())
114
+ j = int(bond.GetEndAtomIdx())
115
+ if i < coords.size(0) and j < coords.size(0):
116
+ vals.append(torch.norm(coords[i].float() - coords[j].float()))
117
+ if not vals:
118
+ return coords.new_zeros(4)
119
+ x = torch.stack(vals)
120
+ return torch.stack([x.min(), x.mean(), x.std(unbiased=False), x.max()])
121
+
122
+
123
+ def _nonlocal_contact_stats(coords: torch.Tensor, mol: Optional[Chem.Mol]) -> torch.Tensor:
124
+ """Reference-free soft contact-state summary for one candidate conformer."""
125
+ n = int(coords.size(0))
126
+ if mol is None or mol.GetNumAtoms() != n or n < 4:
127
+ return torch.zeros(CONTACT_STATE_FEATURE_DIM, dtype=torch.float32)
128
+ pairs = []
129
+ for i in range(n):
130
+ for j in range(i + 1, n):
131
+ # Exclude bonds and angle-neighbours: retained pairs can report
132
+ # conformer-specific folding contacts rather than fixed topology.
133
+ if len(Chem.GetShortestPath(mol, i, j)) >= 4:
134
+ pairs.append((i, j))
135
+ if not pairs:
136
+ return torch.zeros(CONTACT_STATE_FEATURE_DIM, dtype=torch.float32)
137
+ index = torch.tensor(pairs, dtype=torch.long)
138
+ distance = torch.norm(coords[index[:, 0]] - coords[index[:, 1]], dim=-1)
139
+ contact = torch.sigmoid((4.5 - distance) / 0.35).clamp(1e-6, 1.0 - 1e-6)
140
+ entropy = -(contact * contact.log() + (1.0 - contact) * (1.0 - contact).log()).mean()
141
+ values = torch.stack([
142
+ contact.mean(),
143
+ contact.std(unbiased=False),
144
+ torch.quantile(contact, 0.10),
145
+ torch.quantile(contact, 0.50),
146
+ torch.quantile(contact, 0.90),
147
+ (contact > 0.10).float().mean(),
148
+ (contact > 0.50).float().mean(),
149
+ entropy,
150
+ ])
151
+ return torch.nan_to_num(values.float(), nan=0.0, posinf=1e4, neginf=-1e4)
152
+
153
+
154
+ def _mmff_energy(coords: torch.Tensor, mol: Optional[Chem.Mol]) -> float:
155
+ if mol is None:
156
+ return float("nan")
157
+ try:
158
+ mol_copy = Chem.Mol(mol)
159
+ mol_copy.RemoveAllConformers()
160
+ conf = Chem.Conformer(mol_copy.GetNumAtoms())
161
+ arr = coords.detach().cpu().float().numpy()
162
+ if arr.shape[0] != mol_copy.GetNumAtoms():
163
+ return float("nan")
164
+ for i, xyz in enumerate(arr):
165
+ conf.SetAtomPosition(i, (float(xyz[0]), float(xyz[1]), float(xyz[2])))
166
+ mol_copy.AddConformer(conf, assignId=True)
167
+ props = AllChem.MMFFGetMoleculeProperties(mol_copy, mmffVariant="MMFF94")
168
+ if props is None:
169
+ return float("nan")
170
+ ff = AllChem.MMFFGetMoleculeForceField(mol_copy, props, confId=0)
171
+ if ff is None:
172
+ return float("nan")
173
+ return float(ff.CalcEnergy())
174
+ except Exception:
175
+ return float("nan")
176
+
177
+
178
+ def candidate_features(
179
+ coords: torch.Tensor,
180
+ mol: Optional[Chem.Mol] = None,
181
+ heavy_mask: Optional[torch.Tensor] = None,
182
+ feature_dim: int = BASE_FEATURE_DIM,
183
+ ) -> torch.Tensor:
184
+ coords = coords.detach().cpu().float()
185
+ n_atoms = int(coords.size(0))
186
+ if heavy_mask is None:
187
+ heavy_mask = _heavy_mask_from_mol(mol, n_atoms)
188
+ heavy_mask = heavy_mask.cpu().bool()
189
+ heavy = coords[heavy_mask] if heavy_mask.numel() == n_atoms and int(heavy_mask.sum().item()) >= 2 else coords
190
+ centered = heavy - heavy.mean(dim=0, keepdim=True)
191
+ radius = torch.sqrt((centered * centered).sum(dim=1).mean() + 1e-8)
192
+ max_radius = torch.sqrt((centered * centered).sum(dim=1).max() + 1e-8)
193
+ pair = _pair_stats(heavy)
194
+ bond = _bond_stats(coords, mol)
195
+ energy = _mmff_energy(coords, mol)
196
+ if not math.isfinite(energy):
197
+ energy = 0.0
198
+ energy_t = torch.tensor([math.copysign(math.log1p(abs(float(energy))), float(energy))], dtype=torch.float32)
199
+ atom_t = torch.tensor(
200
+ [
201
+ float(n_atoms),
202
+ float(heavy.size(0)),
203
+ float(heavy.size(0)) / max(1.0, float(n_atoms)),
204
+ float(radius),
205
+ float(max_radius),
206
+ float(pair[0]), # repeated min distance helps clash sensitivity.
207
+ float((pair[0] < 1.1).item()),
208
+ ],
209
+ dtype=torch.float32,
210
+ )
211
+ feat = torch.cat([energy_t, atom_t, pair.float(), bond.float()], dim=0)
212
+ if feat.numel() != BASE_FEATURE_DIM:
213
+ raise RuntimeError(f"candidate base feature dim mismatch: {feat.numel()} != {BASE_FEATURE_DIM}")
214
+ feat = torch.nan_to_num(feat, nan=0.0, posinf=1e4, neginf=-1e4)
215
+ if int(feature_dim) <= BASE_FEATURE_DIM:
216
+ return feat[: int(feature_dim)]
217
+ pad = torch.zeros(int(feature_dim) - BASE_FEATURE_DIM, dtype=feat.dtype)
218
+ return torch.cat([feat, pad], dim=0)
219
+
220
+
221
+ def _centered_pairwise_rmsd(confs: torch.Tensor, heavy_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
222
+ if confs.size(0) <= 1:
223
+ return torch.zeros(confs.size(0), confs.size(0), dtype=torch.float32)
224
+ x = confs.detach().cpu().float()
225
+ if heavy_mask is not None and heavy_mask.numel() == x.size(1) and int(heavy_mask.sum().item()) >= 2:
226
+ x = x[:, heavy_mask.cpu().bool()]
227
+ x = x - x.mean(dim=1, keepdim=True)
228
+ diff = x[:, None, :, :] - x[None, :, :, :]
229
+ return torch.sqrt((diff * diff).sum(dim=-1).mean(dim=-1).clamp_min(1e-12))
230
+
231
+
232
+ def candidate_pool_features(
233
+ confs: torch.Tensor,
234
+ mol: Optional[Chem.Mol] = None,
235
+ heavy_mask: Optional[torch.Tensor] = None,
236
+ feature_dim: int = FEATURE_DIM,
237
+ p_alignment_scores: Optional[torch.Tensor] = None,
238
+ ) -> torch.Tensor:
239
+ """Build candidate features plus non-reference pool context.
240
+
241
+ The extra context is intentionally fair: it only uses the generated pool,
242
+ RDKit chemistry, and force-field energy. It does not use test references.
243
+ """
244
+ feature_dim = int(feature_dim)
245
+ if feature_dim <= BASE_FEATURE_DIM:
246
+ return torch.stack(
247
+ [candidate_features(conf, mol=mol, heavy_mask=heavy_mask, feature_dim=feature_dim) for conf in confs],
248
+ dim=0,
249
+ )
250
+
251
+ base = torch.stack(
252
+ [candidate_features(conf, mol=mol, heavy_mask=heavy_mask, feature_dim=BASE_FEATURE_DIM) for conf in confs],
253
+ dim=0,
254
+ )
255
+ n = int(confs.size(0))
256
+ if n <= 1:
257
+ context = torch.zeros(n, POOL_FEATURE_DIM, dtype=torch.float32)
258
+ p_context = torch.zeros(n, P_ALIGNMENT_FEATURE_DIM, dtype=torch.float32)
259
+ return torch.cat([base, context, p_context], dim=1)[:, :feature_dim]
260
+
261
+ dist = _centered_pairwise_rmsd(confs, heavy_mask=heavy_mask)
262
+ eye = torch.eye(n, dtype=torch.bool)
263
+ masked = dist.masked_fill(eye, float("inf"))
264
+ finite_masked = masked.masked_fill(~torch.isfinite(masked), 0.0)
265
+ k3 = min(3, max(1, n - 1))
266
+ k8 = min(8, max(1, n - 1))
267
+ sorted_dist = torch.sort(masked, dim=1).values
268
+ knn3 = sorted_dist[:, :k3].mean(dim=1)
269
+ knn8 = sorted_dist[:, :k8].mean(dim=1)
270
+ min_dist = sorted_dist[:, 0]
271
+ mean_dist = finite_masked.sum(dim=1) / max(1, n - 1)
272
+ max_dist = torch.where(torch.isfinite(masked), masked, torch.zeros_like(masked)).max(dim=1).values
273
+ med_dist = torch.quantile(torch.where(torch.isfinite(masked), masked, torch.zeros_like(masked)), 0.5, dim=1)
274
+
275
+ energies = base[:, 0].float()
276
+ energy_order = torch.argsort(torch.argsort(energies)).float() / max(1.0, float(n - 1))
277
+ energy_z = (energies - energies.mean()) / energies.std(unbiased=False).clamp_min(1e-4)
278
+
279
+ radii = base[:, 4].float()
280
+ radius_z = (radii - radii.mean()) / radii.std(unbiased=False).clamp_min(1e-4)
281
+ pair_mean = base[:, 10].float()
282
+ pair_mean_z = (pair_mean - pair_mean.mean()) / pair_mean.std(unbiased=False).clamp_min(1e-4)
283
+
284
+ pool_size = torch.full((n,), math.log1p(float(n)), dtype=torch.float32)
285
+ duplicate_flag = (min_dist < 0.08).float()
286
+ context = torch.stack(
287
+ [
288
+ energy_order,
289
+ energy_z,
290
+ knn3,
291
+ knn8,
292
+ min_dist,
293
+ mean_dist,
294
+ max_dist,
295
+ med_dist,
296
+ radius_z,
297
+ pair_mean_z,
298
+ duplicate_flag,
299
+ pool_size,
300
+ ],
301
+ dim=1,
302
+ )
303
+ context = torch.nan_to_num(context.float(), nan=0.0, posinf=1e4, neginf=-1e4)
304
+
305
+ # CE(P(G), Q(Y)) is only useful relative to candidates from the same
306
+ # molecule. Preserve the raw value for calibration, and add normalized
307
+ # rank/margin descriptors so the ranker can learn a molecule-local
308
+ # probability-likelihood decision instead of a global CE threshold.
309
+ p_context = torch.zeros(n, P_ALIGNMENT_FEATURE_DIM, dtype=torch.float32)
310
+ if p_alignment_scores is not None:
311
+ p = torch.as_tensor(p_alignment_scores, dtype=torch.float32).detach().cpu().view(-1)
312
+ if p.numel() == n:
313
+ finite = torch.isfinite(p)
314
+ if finite.any():
315
+ fill = p[finite].max() + 5.0
316
+ p = torch.where(finite, p, torch.full_like(p, fill))
317
+ p_mean = p.mean()
318
+ p_std = p.std(unbiased=False).clamp_min(1e-4)
319
+ p_z = (p - p_mean) / p_std
320
+ p_order = torch.argsort(torch.argsort(p)).float() / max(1.0, float(n - 1))
321
+ p_soft = torch.softmax(-p_z, dim=0)
322
+ p_best_gap = p - p.min()
323
+ p_context = torch.stack(
324
+ [p, p_z, p_order, p_soft, p_best_gap, -p_z],
325
+ dim=1,
326
+ )
327
+ p_context = torch.nan_to_num(p_context, nan=0.0, posinf=1e4, neginf=-1e4)
328
+ output = torch.cat([base, context, p_context], dim=1)
329
+ if feature_dim > FEATURE_DIM:
330
+ contact = torch.stack([_nonlocal_contact_stats(conf.detach().cpu().float(), mol) for conf in confs], dim=0)
331
+ # Candidate-local ranks make the state graph comparable across molecules.
332
+ contact_mean = contact[:, 0]
333
+ contact_z = (contact_mean - contact_mean.mean()) / contact_mean.std(unbiased=False).clamp_min(1e-4)
334
+ contact_rank = torch.argsort(torch.argsort(contact_mean)).float() / max(1.0, float(n - 1))
335
+ contact[:, 0] = contact_z
336
+ contact[:, 1] = contact_rank
337
+ output = torch.cat([output, contact], dim=1)
338
+ return output[:, :feature_dim]
339
+
340
+
341
+ def load_candidate_scorer(path: str, device: torch.device):
342
+ ckpt = torch.load(path, map_location=device)
343
+ feature_dim = int(ckpt.get("feature_dim", FEATURE_DIM))
344
+ hidden_dim = int(ckpt.get("hidden_dim", 64))
345
+ model = CandidateScorer(feature_dim=feature_dim, hidden_dim=hidden_dim).to(device)
346
+ model.load_state_dict(ckpt["model_state_dict"], strict=True)
347
+ model.eval()
348
+ return model
349
+
350
+
351
+ def load_candidate_ranker(path: str, device: torch.device):
352
+ ckpt = torch.load(path, map_location=device)
353
+ feature_dim = int(ckpt.get("feature_dim", FEATURE_DIM))
354
+ hidden_dim = int(ckpt.get("hidden_dim", 128))
355
+ dropout = float(ckpt.get("dropout", 0.0))
356
+ model = CandidatePoolRanker(feature_dim=feature_dim, hidden_dim=hidden_dim, dropout=dropout).to(device)
357
+ model.load_state_dict(ckpt["model_state_dict"], strict=True)
358
+ model.eval()
359
+ return model
conformend/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """Public ConforMend API.
2
+
3
+ The implementation package remains available as :mod:`manimol` so that
4
+ existing checkpoints and downstream scripts continue to load. New code can
5
+ use this project-branded facade without changing the numerical implementation.
6
+ """
7
+
8
+ from manimol import (
9
+ ConforMend,
10
+ ManiMol,
11
+ circular_standard_deviation,
12
+ density_centrality_select,
13
+ ensemble_pairwise_prior,
14
+ fps_indices,
15
+ mmff94s_window_fps,
16
+ pairwise_rmsd,
17
+ run_full_inference,
18
+ select_energy_window,
19
+ wrap_angle,
20
+ )
21
+
22
+ __all__ = [
23
+ "ConforMend",
24
+ "ManiMol",
25
+ "circular_standard_deviation",
26
+ "density_centrality_select",
27
+ "ensemble_pairwise_prior",
28
+ "fps_indices",
29
+ "mmff94s_window_fps",
30
+ "pairwise_rmsd",
31
+ "run_full_inference",
32
+ "select_energy_window",
33
+ "wrap_angle",
34
+ ]
35
+
36
+ __version__ = "0.2.8"
conformend/refiner.py ADDED
@@ -0,0 +1,25 @@
1
+ """Public ConforMend namespace for the standalone local Refiner."""
2
+
3
+ from manimol.refiner import (
4
+ AcceptanceConfig,
5
+ ConforMendRefiner,
6
+ InterpretableLocalRefiner,
7
+ RefinementResult,
8
+ accept_refinement,
9
+ apply_torsion_residuals,
10
+ bond_cross_fragment_context,
11
+ proximity_matrix,
12
+ stable_relational_energy,
13
+ )
14
+
15
+ __all__ = [
16
+ "AcceptanceConfig",
17
+ "ConforMendRefiner",
18
+ "InterpretableLocalRefiner",
19
+ "RefinementResult",
20
+ "accept_refinement",
21
+ "apply_torsion_residuals",
22
+ "bond_cross_fragment_context",
23
+ "proximity_matrix",
24
+ "stable_relational_energy",
25
+ ]
dataset/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .drugdataset import QM9Dataset