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
exputils.py ADDED
@@ -0,0 +1,289 @@
1
+ import os
2
+ import re
3
+ import sys
4
+ import time
5
+ import json
6
+ import torch
7
+ import pickle
8
+ import random
9
+ import getpass
10
+ import logging
11
+ import argparse
12
+ import subprocess
13
+ import numpy as np
14
+ from datetime import timedelta, date, datetime
15
+ import py3Dmol
16
+ from rdkit import Chem
17
+ from rdkit.Chem import rdMolAlign as MA
18
+ from rdkit.Chem.rdmolops import RemoveHs
19
+
20
+
21
+ # ---------- 新增的数学/几何辅助函数 ----------
22
+ def kabsch_alignment(P, Q):
23
+ """
24
+ Kabsch 算法:计算最优旋转矩阵,使 P 对齐到 Q(最小化 RMSD)。
25
+ P, Q: 形状均为 (N, 3) 的 numpy 数组
26
+ 返回旋转后的 P 和 RMSD
27
+ """
28
+ centroid_P = np.mean(P, axis=0)
29
+ centroid_Q = np.mean(Q, axis=0)
30
+ P_centered = P - centroid_P
31
+ Q_centered = Q - centroid_Q
32
+ H = P_centered.T @ Q_centered
33
+ U, S, Vt = np.linalg.svd(H)
34
+ V = Vt.T
35
+ U = U.T
36
+ R_mat = V @ U.T
37
+ # 处理反射情况
38
+ if np.linalg.det(R_mat) < 0:
39
+ V[:, -1] *= -1
40
+ R_mat = V @ U.T
41
+ P_aligned = (P_centered @ R_mat) + centroid_Q
42
+ rmsd = np.sqrt(np.mean((P_aligned - Q) ** 2))
43
+ return P_aligned, rmsd
44
+
45
+
46
+ def mae_per_atom(P, Q):
47
+ """
48
+ 计算每个原子的平均绝对误差(MAE),shape (N,)
49
+ """
50
+ return np.mean(np.abs(P - Q), axis=1)
51
+
52
+
53
+ def get_kabsch_rmsd(P, Q):
54
+ """
55
+ 返回 Kabsch 对齐后的 RMSD
56
+ """
57
+ _, rmsd = kabsch_alignment(P, Q)
58
+ return rmsd
59
+
60
+
61
+ # ---------- 原有的 RDKit 相关函数 ----------
62
+ def get_best_rmsd(probe, ref):
63
+ probe = RemoveHs(probe)
64
+ ref = RemoveHs(ref)
65
+ rmsd = MA.GetBestRMS(probe, ref)
66
+ return rmsd
67
+
68
+
69
+ # ---------- 日志与实验初始化 ----------
70
+ class LogFormatter:
71
+ def __init__(self):
72
+ self.start_time = time.time()
73
+
74
+ def format(self, record):
75
+ elapsed_seconds = round(record.created - self.start_time)
76
+
77
+ prefix = "%s - %s - %s" % (
78
+ record.levelname,
79
+ time.strftime('%x %X'),
80
+ timedelta(seconds=elapsed_seconds)
81
+ )
82
+ message = record.getMessage()
83
+ message = message.replace('\n', '\n' + ' ' * (len(prefix) + 3))
84
+ return "%s - %s" % (prefix, message) if message else ''
85
+
86
+
87
+ def create_logger(filepath, rank):
88
+ """
89
+ Create a logger.
90
+ Use a different log file for each process.
91
+ """
92
+ # create log formatter
93
+ log_formatter = LogFormatter()
94
+
95
+ # create file handler and set level to debug
96
+ if filepath is not None:
97
+ if rank > 0:
98
+ filepath = '%s-%i' % (filepath, rank)
99
+ file_handler = logging.FileHandler(filepath, "a", encoding='utf-8')
100
+ file_handler.setLevel(logging.DEBUG)
101
+ file_handler.setFormatter(log_formatter)
102
+
103
+ # create console handler and set level to info
104
+ console_handler = logging.StreamHandler()
105
+ console_handler.setLevel(logging.INFO)
106
+ console_handler.setFormatter(log_formatter)
107
+
108
+ # create logger and set level to debug
109
+ logger = logging.getLogger()
110
+ logger.handlers = []
111
+ logger.setLevel(logging.DEBUG)
112
+ logger.propagate = False
113
+ if filepath is not None:
114
+ logger.addHandler(file_handler)
115
+ logger.addHandler(console_handler)
116
+
117
+ # reset logger elapsed time
118
+ def reset_time():
119
+ log_formatter.start_time = time.time()
120
+
121
+ logger.reset_time = reset_time
122
+
123
+ return logger
124
+
125
+
126
+ def initialize_exp(params):
127
+ """
128
+ Initialize the experiment:
129
+ - dump parameters
130
+ - create a logger
131
+ """
132
+ # dump parameters
133
+ exp_folder = get_dump_path(params)
134
+ json.dump(vars(params), open(os.path.join(exp_folder, 'params.pkl'), 'w'), indent=4)
135
+
136
+ # get running command
137
+ command = ["python", sys.argv[0]]
138
+ for x in sys.argv[1:]:
139
+ if x.startswith('--'):
140
+ assert '"' not in x and "'" not in x
141
+ command.append(x)
142
+ else:
143
+ assert "'" not in x
144
+ if re.match('^[a-zA-Z0-9_]+$', x):
145
+ command.append("%s" % x)
146
+ else:
147
+ command.append("'%s'" % x)
148
+ command = ' '.join(command)
149
+ params.command = command + ' --exp_id "%s"' % params.exp_id
150
+
151
+ # check experiment name
152
+ assert len(params.exp_name.strip()) > 0
153
+
154
+ # create a logger
155
+ logger = create_logger(os.path.join(exp_folder, 'train.log'), rank=getattr(params, 'global_rank', 0))
156
+ logger.info("============ Initialized logger ============")
157
+ logger.info("\n".join("%s: %s" % (k, str(v))
158
+ for k, v in sorted(dict(vars(params)).items())))
159
+
160
+ logger.info("The experiment will be stored in %s\n" % exp_folder)
161
+ logger.info("Running command: %s" % command)
162
+ return logger
163
+
164
+
165
+ def get_dump_path(params):
166
+ """
167
+ Create a directory to store the experiment.
168
+ """
169
+ assert len(params.exp_name) > 0
170
+ assert not params.dump_path in ('', None), \
171
+ 'Please choose your favorite destination for dump.'
172
+ dump_path = params.dump_path
173
+
174
+ # create the sweep path if it does not exist
175
+ if getattr(params, "fixed_dump_name", False):
176
+ sweep_path = os.path.join(dump_path, params.exp_name)
177
+ else:
178
+ when = date.today().strftime('%m%d-')
179
+ sweep_path = os.path.join(dump_path, when + params.exp_name)
180
+ if not os.path.exists(sweep_path):
181
+ subprocess.Popen("mkdir -p %s" % sweep_path, shell=True).wait()
182
+
183
+ # create an random ID for the job if it is not given in the parameters.
184
+ if params.exp_id == '':
185
+ exp_id = datetime.now().strftime('%H-%M-%S.%f')[:-3]
186
+ exp_id += ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 3))
187
+ params.exp_id = exp_id
188
+
189
+ # create the dump folder / update parameters
190
+ exp_folder = os.path.join(sweep_path, params.exp_id)
191
+ if not os.path.isdir(exp_folder):
192
+ subprocess.Popen("mkdir -p %s" % exp_folder, shell=True).wait()
193
+ return exp_folder
194
+
195
+
196
+ def describe_model(model, path, name='model'):
197
+ file_path = os.path.join(path, f'{name}.describe')
198
+ with open(file_path, 'w') as fout:
199
+ print(model, file=fout)
200
+
201
+
202
+ def set_seed(seed):
203
+ """
204
+ Freeze every seed for reproducibility.
205
+ torch.cuda.manual_seed_all is useful when using random generation on GPUs.
206
+ e.g. torch.cuda.FloatTensor(100).uniform_()
207
+ """
208
+ random.seed(seed)
209
+ np.random.seed(seed)
210
+ torch.manual_seed(seed)
211
+ torch.cuda.manual_seed(seed)
212
+ torch.cuda.manual_seed_all(seed)
213
+
214
+
215
+ def save_model(model, save_dir, epoch=None, model_name='model'):
216
+ model_to_save = model.module if hasattr(model, "module") else model
217
+ if epoch is None:
218
+ save_path = os.path.join(save_dir, f'{model_name}.pkl')
219
+ else:
220
+ save_path = os.path.join(save_dir, f'{model_name}-{epoch}.pkl')
221
+ os.makedirs(save_dir, exist_ok=True)
222
+ torch.save(model_to_save.state_dict(), save_path)
223
+
224
+
225
+ def load_model(path, map_location):
226
+ return torch.load(path, map_location=map_location)
227
+
228
+
229
+ def save_checkpoint(model, optimizer, epoch, best_test_score, filepath):
230
+ torch.save({
231
+ 'epoch': epoch,
232
+ 'model_state_dict': model.state_dict(),
233
+ 'optimizer_state_dict': optimizer.state_dict(),
234
+ 'best_test_score': best_test_score,
235
+ }, filepath)
236
+
237
+
238
+ def load_checkpoint(filepath, model, optimizer):
239
+ checkpoint = torch.load(filepath)
240
+ model.load_state_dict(checkpoint['model_state_dict'])
241
+ optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
242
+ return checkpoint['epoch'], checkpoint['best_test_score']
243
+
244
+
245
+ def visualize_mol(mol, size=(300, 300), surface=False, opacity=0.5):
246
+ """Draw molecule in 3D
247
+
248
+ Args:
249
+ ----
250
+ mol: rdMol, molecule to show
251
+ size: tuple(int, int), canvas size
252
+ style: str, type of drawing molecule
253
+ style can be 'line', 'stick', 'sphere', 'carton'
254
+ surface, bool, display SAS
255
+ opacity, float, opacity of surface, range 0.0-1.0
256
+ Return:
257
+ ----
258
+ viewer: py3Dmol.view, a class for constructing embedded 3Dmol.js views in ipython notebooks.
259
+ """
260
+ mblock = Chem.MolToMolBlock(mol)
261
+ viewer = py3Dmol.view(width=size[0], height=size[1])
262
+ viewer.addModel(mblock, 'mol')
263
+ viewer.setStyle({'stick': {}, 'sphere': {'radius': 0.35}})
264
+ if surface:
265
+ viewer.addSurface(py3Dmol.SAS, {'opacity': opacity})
266
+ viewer.zoomTo()
267
+ return viewer
268
+
269
+ def merge_args_from_paths(args, attr_name="paras_path"):
270
+ """
271
+ 如果 args 中存在 attr_name 指定的路径,则从该路径读取 JSON 文件,
272
+ 并将其中的键值对合并到 args 对象中(仅当 args 中原本没有该属性时)。
273
+ """
274
+ import os
275
+ if not hasattr(args, attr_name):
276
+ return args
277
+ path = getattr(args, attr_name, None)
278
+ if not path or not os.path.exists(path):
279
+ return args
280
+ try:
281
+ import json
282
+ with open(path, 'r') as f:
283
+ extra = json.load(f)
284
+ for k, v in extra.items():
285
+ if not hasattr(args, k):
286
+ setattr(args, k, v)
287
+ except Exception as e:
288
+ print(f"Warning: merge_args_from_paths failed: {e}")
289
+ return args
infer.py ADDED
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env python3
2
+ """MANIMOL best-performance inference entry point.
3
+
4
+ This public entry point runs the probability-basin + denoising + precision
5
+ refinement inference pipeline used for the current MANIMOL results. The
6
+ implementation remains in `infer_torsional_denoiser.py` for compatibility with older YAML
7
+ tasks.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import runpy
12
+ import sys
13
+ from pathlib import Path
14
+
15
+
16
+ ROOT = Path(__file__).resolve().parent
17
+ SCRIPT = ROOT / "infer_torsional_denoiser.py"
18
+
19
+ if not SCRIPT.exists():
20
+ raise SystemExit(f"MANIMOL inference implementation was not found: {SCRIPT}")
21
+
22
+ sys.argv = [str(SCRIPT)] + sys.argv[1:]
23
+ runpy.run_path(str(SCRIPT), run_name="__main__")