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
models/dist.py ADDED
@@ -0,0 +1,273 @@
1
+ import torch
2
+ import numpy as np
3
+ from collections import deque
4
+
5
+ from rdkit import Chem
6
+ from rdkit.Chem import AllChem, DataStructs
7
+ from rdkit.Chem.rdmolops import FindAtomEnvironmentOfRadiusN
8
+
9
+ from scipy.spatial.distance import cdist
10
+ from scipy.sparse import coo_matrix
11
+ from scipy.sparse.csgraph import shortest_path
12
+ import torch
13
+ import numpy as np
14
+ import networkx as nx
15
+ from scipy.spatial.distance import cdist
16
+ from rdkit import Chem
17
+
18
+
19
+
20
+
21
+ import numpy as np
22
+ from collections import deque
23
+ from rdkit import Chem
24
+ def hop_matrix_from_mol(mol: Chem.Mol, use_heavy_only=False, kmax=None):
25
+ # 用别名,避免被同名变量遮蔽
26
+ from collections import deque as _deque
27
+
28
+ if use_heavy_only:
29
+ idx_map = [i for i, a in enumerate(mol.GetAtoms()) if a.GetAtomicNum() > 1]
30
+ map_back = {h: i for i, h in enumerate(idx_map)}
31
+ nH = len(idx_map)
32
+ adj = [[] for _ in range(nH)]
33
+ for b in mol.GetBonds():
34
+ i, j = b.GetBeginAtomIdx(), b.GetEndAtomIdx()
35
+ if i in map_back and j in map_back:
36
+ u, v = map_back[i], map_back[j]
37
+ adj[u].append(v); adj[v].append(u)
38
+ INF = 10**9
39
+ Hh = np.full((nH, nH), INF, dtype=int)
40
+ for s in range(nH):
41
+ Hh[s, s] = 0
42
+ q = _deque([s])
43
+ while q:
44
+ u = q.popleft()
45
+ if kmax is not None and Hh[s, u] >= kmax:
46
+ continue
47
+ for v in adj[u]:
48
+ if Hh[s, v] == INF:
49
+ Hh[s, v] = Hh[s, u] + 1
50
+ q.append(v)
51
+ # 映射回全原子
52
+ n = mol.GetNumAtoms()
53
+ H = np.full((n, n), INF, dtype=int)
54
+ for a in range(n):
55
+ if a in map_back:
56
+ ua = map_back[a]
57
+ for b in range(n):
58
+ if b in map_back:
59
+ vb = map_back[b]
60
+ H[a, b] = Hh[ua, vb]
61
+ elif b == a:
62
+ H[a, b] = 0
63
+ else:
64
+ nbrs = [bb.GetOtherAtomIdx(a) for bb in mol.GetAtomWithIdx(a).GetBonds()]
65
+ r = next((x for x in nbrs if mol.GetAtomWithIdx(x).GetAtomicNum() > 1), None)
66
+ H[a, a] = 0
67
+ if r is not None and r in map_back:
68
+ ur = map_back[r]
69
+ for b in range(n):
70
+ if b in map_back:
71
+ vb = map_back[b]
72
+ H[a, b] = H[b, a] = min(H[a, b], Hh[ur, vb] + 1)
73
+ return H
74
+ else:
75
+ # 全原子图 BFS
76
+ n = mol.GetNumAtoms()
77
+ adj = [[] for _ in range(n)]
78
+ for b in mol.GetBonds():
79
+ i, j = b.GetBeginAtomIdx(), b.GetEndAtomIdx()
80
+ adj[i].append(j); adj[j].append(i)
81
+ INF = 10**9
82
+ H = np.full((n, n), INF, dtype=int)
83
+ for s in range(n):
84
+ H[s, s] = 0
85
+ q = _deque([s])
86
+ while q:
87
+ u = q.popleft()
88
+ if kmax is not None and H[s, u] >= kmax:
89
+ continue
90
+ for v in adj[u]:
91
+ if H[s, v] == INF:
92
+ H[s, v] = H[s, u] + 1
93
+ q.append(v)
94
+ return H
95
+
96
+
97
+
98
+ def _all_pairs_shortest_path_from_edges(edge_index_np, weights_np, N, directed=False):
99
+ """
100
+ 使用 scipy.sparse.csgraph.shortest_path 一次性计算所有对最短路。
101
+ edge_index_np: shape (2, E)
102
+ weights_np: shape (E,)
103
+ 返回 numpy (N,N) 矩阵,无法到达处为 np.inf
104
+ """
105
+ rows = edge_index_np[0]
106
+ cols = edge_index_np[1]
107
+ A = coo_matrix((weights_np, (rows, cols)), shape=(N, N))
108
+ if not directed:
109
+ A = A + A.T
110
+ D = shortest_path(csgraph=A, directed=directed, method='D', unweighted=False)
111
+ return D
112
+
113
+
114
+ def compute_AE_tanimoto_distance_np(mol, radius=2, nBits=2048):
115
+ """返回 numpy (N,N) 的 AE-based Tanimoto 距离矩阵(1 - similarity)。"""
116
+ mol_local = Chem.Mol(mol)
117
+ N = mol_local.GetNumAtoms()
118
+ atom_fps = []
119
+ for atom_idx in range(N):
120
+ env_ids = FindAtomEnvironmentOfRadiusN(mol_local, radius, atom_idx)
121
+ env_mol = Chem.PathToSubmol(mol_local, env_ids)
122
+ # --- 修复 RingInfo 未初始化问题 ---
123
+ Chem.GetSymmSSSR(env_mol)
124
+ fp = AllChem.GetMorganFingerprintAsBitVect(env_mol, radius, nBits=nBits)
125
+ atom_fps.append(fp)
126
+ sim = np.zeros((N, N), dtype=float)
127
+ for i in range(N):
128
+ sim[i, :] = DataStructs.BulkTanimotoSimilarity(atom_fps[i], atom_fps)
129
+ return (1.0 - sim).astype(np.float32)
130
+
131
+
132
+
133
+ def compute_embed3d_distance_np(mol, embed=True, optimize=True, maxIters=200):
134
+ """基于 RDKit conformer 计算欧氏距离,返回 numpy (N,N)。"""
135
+ if mol is None:
136
+ raise ValueError("Invalid mol")
137
+ mol_local = Chem.Mol(mol)
138
+ if mol_local.GetNumConformers() == 0 and embed:
139
+ AllChem.EmbedMolecule(mol_local, AllChem.ETKDG())
140
+ if optimize and mol_local.GetNumConformers() > 0:
141
+ AllChem.UFFOptimizeMolecule(mol_local, maxIters=maxIters)
142
+ conf = mol_local.GetConformer()
143
+ N = mol_local.GetNumAtoms()
144
+ coords = np.zeros((N, 3), dtype=float)
145
+ for i in range(N):
146
+ p = conf.GetAtomPosition(i)
147
+ coords[i, 0] = p.x
148
+ coords[i, 1] = p.y
149
+ coords[i, 2] = p.z
150
+ D = cdist(coords, coords, metric='euclidean')
151
+ return D.astype(np.float32)
152
+
153
+ def compute_augmented_graph_distance_np(mol, data, alpha=1.0, beta=1.0, large_value=1e6):
154
+ """
155
+ Robust version: accepts featurizer that returns either:
156
+ - torch_geometric.data.Data (has .x/.edge_index/.edge_attr), or
157
+ - dict-like with keys 'x','edge_index','edge_attr', or
158
+ - tuple/list (x, edge_index, edge_attr, ...)
159
+
160
+ Converts tensors -> numpy, computes D_feat (node feature euclid),
161
+ D_topo (hop-count shortest path using scipy.sparse.csgraph.shortest_path with weight=1),
162
+ D_edge (shortest path with weight = ||edge_attr||),
163
+ normalizes and returns dict of numpy arrays (float32):
164
+ {'D_aug','D_topo','D_edge','D_feat'}
165
+ """
166
+ # prepare a dict-like datapoint for featurizer that expects indexable mapping
167
+ # (smile2graph4GEOM expects something like datapoint['rdmol'] etc.)
168
+ meta = {'smiles': Chem.MolToSmiles(mol), 'rdmol': mol}
169
+
170
+
171
+
172
+ # --- extract x, edge_index, edge_attr robustly ---
173
+ # handle Data-like (has .x) or dict-like or tuple/list
174
+ if hasattr(data, 'x'):
175
+ x_t = data.x
176
+ edge_index_t = data.edge_index
177
+ edge_attr_t = data.edge_attr
178
+ elif isinstance(data, dict):
179
+ x_t = data.get('x', None)
180
+ edge_index_t = data.get('edge_index', None)
181
+ edge_attr_t = data.get('edge_attr', None)
182
+ elif isinstance(data, (tuple, list)):
183
+ # assume conventional ordering: (x, edge_index, edge_attr, ...)
184
+ # allow shorter tuples (e.g., return only x, edge_index, edge_attr)
185
+ if len(data) >= 3:
186
+ x_t, edge_index_t, edge_attr_t = data[0], data[1], data[2]
187
+ else:
188
+ raise ValueError("featurizer returned tuple/list with <3 elements")
189
+ else:
190
+ raise ValueError("Unsupported featurizer return type: %s" % type(data))
191
+
192
+ # convert node features to numpy
193
+ if torch.is_tensor(x_t):
194
+ node_features = x_t.detach().cpu().numpy()
195
+ else:
196
+ node_features = np.asarray(x_t)
197
+
198
+ # normalize shapes: edge_index -> numpy shape (2, E)
199
+ if torch.is_tensor(edge_index_t):
200
+ edge_index_np = edge_index_t.detach().cpu().numpy()
201
+ else:
202
+ edge_index_np = np.asarray(edge_index_t)
203
+
204
+ # If edge_index is shape (E,2), convert to (2,E)
205
+ if edge_index_np.ndim == 2 and edge_index_np.shape[0] == 2:
206
+ pass
207
+ elif edge_index_np.ndim == 2 and edge_index_np.shape[1] == 2:
208
+ edge_index_np = edge_index_np.T
209
+ else:
210
+ # try flattenable or raise
211
+ edge_index_np = np.asarray(edge_index_np)
212
+ if edge_index_np.ndim != 2 or min(edge_index_np.shape) != 2:
213
+ raise ValueError("edge_index has unsupported shape: %s" % (edge_index_np.shape,))
214
+
215
+ # edge_attr -> numpy (E, feat_dim) or (E,)
216
+ if torch.is_tensor(edge_attr_t):
217
+ edge_attr_np = edge_attr_t.detach().cpu().numpy()
218
+ else:
219
+ edge_attr_np = np.asarray(edge_attr_t)
220
+
221
+ # Ensure consistent E:
222
+ E = edge_index_np.shape[1]
223
+ if edge_attr_np is None:
224
+ # no edge attr: treat as zeros
225
+ edge_attr_np = np.zeros((E,), dtype=float)
226
+
227
+ # flatten edge_attr per-edge vector to compute norm
228
+ # if edge_attr_np.ndim == 1 -> already per-edge scalar weight
229
+ if edge_attr_np.ndim == 1:
230
+ w_feat = edge_attr_np.astype(float)
231
+ else:
232
+ w_feat = np.linalg.norm(edge_attr_np.reshape(edge_attr_np.shape[0], -1), axis=1)
233
+
234
+ N = node_features.shape[0]
235
+
236
+ # D_feat: node features pairwise euclidean
237
+ D_feat = cdist(node_features, node_features, metric='euclidean')
238
+
239
+ # D_topo: shortest paths on graph with unit weight
240
+ ones = np.ones(E, dtype=float)
241
+ D_topo = _all_pairs_shortest_path_from_edges(edge_index_np, ones, N, directed=False)
242
+
243
+ # D_edge: shortest paths with w_feat weights
244
+ D_edge = _all_pairs_shortest_path_from_edges(edge_index_np, w_feat, N, directed=False)
245
+
246
+ # safe normalization helper
247
+ def _safe_norm_np(M):
248
+ M = np.array(M, dtype=float)
249
+ M = np.nan_to_num(M, nan=large_value, posinf=large_value)
250
+ finite_mask = M < large_value
251
+ if np.any(finite_mask):
252
+ mmax = np.max(M[finite_mask])
253
+ if mmax <= 0:
254
+ return M
255
+ return M / (mmax + 1e-12)
256
+ else:
257
+ return M
258
+
259
+ D_topo_n = _safe_norm_np(D_topo)
260
+ D_feat_n = _safe_norm_np(D_feat)
261
+ D_edge_n = _safe_norm_np(D_edge)
262
+
263
+ D_aug = D_topo_n + alpha * D_feat_n + beta * D_edge_n
264
+ D_aug = np.nan_to_num(D_aug, nan=large_value, posinf=large_value)
265
+ maxval = D_aug.max() if D_aug.size > 0 else 1.0
266
+ D_aug = (D_aug / (maxval + 1e-12)).astype(np.float32)
267
+
268
+ return {
269
+ 'D_aug': D_aug,
270
+ 'D_topo': D_topo.astype(np.float32),
271
+ 'D_edge': D_edge.astype(np.float32),
272
+ 'D_feat': D_feat.astype(np.float32)
273
+ }
models/dist2coords.py ADDED
@@ -0,0 +1,23 @@
1
+ from sklearn.manifold import MDS
2
+ import numpy as np
3
+ import torch
4
+
5
+ def coords2dict_mds(dist_matrix, dim=3):
6
+ mds = MDS(n_components=dim, dissimilarity='precomputed', random_state=0)
7
+ coords = mds.fit_transform(dist_matrix)
8
+ return coords
9
+
10
+
11
+ def coords2dict_tch(dist_matrix, lr=1e-2, steps=1000):
12
+ N = dist_matrix.shape[0]
13
+ D = torch.tensor(dist_matrix, dtype=torch.float32)
14
+ X = torch.randn(N, 3, requires_grad=True)
15
+
16
+ optimizer = torch.optim.Adam([X], lr=lr)
17
+ for step in range(steps):
18
+ dist_pred = torch.cdist(X, X)
19
+ loss = ((dist_pred - D) ** 2).mean()
20
+ optimizer.zero_grad()
21
+ loss.backward()
22
+ optimizer.step()
23
+ return X.detach().numpy()
models/egnn.py ADDED
@@ -0,0 +1,107 @@
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ class EGNNLayer(nn.Module):
6
+ """单层等变图神经网络层"""
7
+ def __init__(self, feat_dim, edge_dim=1):
8
+ super().__init__()
9
+ self.feat_dim = feat_dim
10
+ self.edge_dim = edge_dim
11
+
12
+ # 消息 MLP:输入 [h_i, h_j, ||x_i - x_j||, e_ij]
13
+ self.message_mlp = nn.Sequential(
14
+ nn.Linear(2 * feat_dim + 1 + edge_dim, feat_dim),
15
+ nn.SiLU(),
16
+ nn.Linear(feat_dim, feat_dim),
17
+ )
18
+ # 坐标更新 MLP:输入 [h_i, h_j, ||x_i - x_j||, e_ij]
19
+ self.coord_mlp = nn.Sequential(
20
+ nn.Linear(2 * feat_dim + 1 + edge_dim, 1),
21
+ nn.Tanh(),
22
+ )
23
+ # 节点特征更新 MLP
24
+ self.node_mlp = nn.Sequential(
25
+ nn.Linear(feat_dim + feat_dim, feat_dim),
26
+ nn.SiLU(),
27
+ nn.Linear(feat_dim, feat_dim),
28
+ )
29
+
30
+ def forward(self, h, x, edge_index, edge_weight=None):
31
+ row, col = edge_index
32
+ diff = x[row] - x[col] # (E, 3)
33
+ dist = torch.norm(diff, dim=1, keepdim=True) # (E, 1)
34
+ dir = diff / (dist + 1e-8) # (E, 3)
35
+
36
+ # 边输入特征
37
+ edge_input = torch.cat([h[row], h[col], dist], dim=1)
38
+ if edge_weight is not None:
39
+ edge_weight = edge_weight.view(-1, 1)
40
+ edge_input = torch.cat([edge_input, edge_weight], dim=1)
41
+
42
+ # 坐标更新量
43
+ coord_update_val = self.coord_mlp(edge_input) # (E, 1)
44
+ coord_update = coord_update_val * dir # (E, 3)
45
+
46
+ # 聚合坐标更新(scatter_add)
47
+ N = h.shape[0]
48
+ coord_update_aggr = torch.zeros(N, 3, device=h.device)
49
+ coord_update_aggr = coord_update_aggr.scatter_add(
50
+ 0, col.unsqueeze(-1).expand(-1, 3), coord_update
51
+ )
52
+ coord_update_aggr = coord_update_aggr.scatter_add(
53
+ 0, row.unsqueeze(-1).expand(-1, 3), -coord_update
54
+ )
55
+ x_new = x + coord_update_aggr
56
+
57
+ # 消息传递
58
+ m = self.message_mlp(edge_input) # (E, feat_dim)
59
+ m_aggr = torch.zeros(N, self.feat_dim, device=h.device)
60
+ m_aggr = m_aggr.scatter_add(0, col.unsqueeze(-1).expand(-1, self.feat_dim), m)
61
+ m_aggr = m_aggr.scatter_add(0, row.unsqueeze(-1).expand(-1, self.feat_dim), m)
62
+
63
+ # 更新节点特征
64
+ h_new = self.node_mlp(torch.cat([h, m_aggr], dim=1))
65
+ return h_new, x_new
66
+
67
+
68
+ class EGNN(nn.Module):
69
+ """等变图神经网络,用于从概率图预测坐标"""
70
+ def __init__(self, node_dim=64, edge_dim=1, num_layers=4):
71
+ super().__init__()
72
+ self.node_dim = node_dim
73
+ # 初始节点特征(可学习)
74
+ self.node_embed = nn.Embedding(1, node_dim)
75
+ self.layers = nn.ModuleList([
76
+ EGNNLayer(node_dim, edge_dim=edge_dim) for _ in range(num_layers)
77
+ ])
78
+
79
+ def forward(self, P, edge_index, initial_coords=None):
80
+ """
81
+ P: (N, N) 概率图,作为边权重(全连接图)
82
+ edge_index: (2, E) 稀疏边索引,若为 None 则使用所有上三角边
83
+ initial_coords: (N, 3) 初始坐标,若为 None 则用随机噪声
84
+ """
85
+ N = P.shape[0]
86
+ device = P.device
87
+ if initial_coords is None:
88
+ x = torch.randn(N, 3, device=device) * 0.1
89
+ else:
90
+ x = initial_coords
91
+
92
+ # 节点初始特征(所有节点相同)
93
+ h = self.node_embed(torch.zeros(1, dtype=torch.long, device=device)) # (1, D)
94
+ h = h.expand(N, -1)
95
+
96
+ if edge_index is None:
97
+ rows, cols = torch.triu_indices(N, N, offset=1, device=device)
98
+ edge_index = torch.stack([rows, cols], dim=0)
99
+ edge_weight = P[rows, cols]
100
+ else:
101
+ rows, cols = edge_index[0], edge_index[1]
102
+ edge_weight = P[rows, cols]
103
+
104
+ for layer in self.layers:
105
+ h, x = layer(h, x, edge_index, edge_weight)
106
+
107
+ return x