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
@@ -0,0 +1,275 @@
1
+ # Academic Figure Skill Asset Confirmation (verified against assets/figures/)
2
+ # (a) connected dot plot -> cross-type inherit -> param inherit
3
+ # (b) horizontal lollipop summary -> assets/figures/LineTrend -> param inherit
4
+ # (c) correlation marker -> assets/figures/Forest -> param inherit
5
+ # RULE: "native run" = load pre-rendered PNG via Image.open().ax.imshow().
6
+ # "param inherit" = drawing function below that copies Class A/B/C values.
7
+ # If a panel says "native run" and you write a drawing function, you broke the contract.
8
+
9
+ #!/usr/bin/env python3
10
+ """Render the aggregate-only GEOM-Drugs finite-budget diagnostic.
11
+
12
+ This figure deliberately displays only confirmed summary statistics. It does
13
+ not reconstruct or imply unavailable molecule-level distributions.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ from pathlib import Path
20
+
21
+ import matplotlib as mpl
22
+
23
+ mpl.use("Agg")
24
+ import matplotlib.pyplot as plt
25
+ import numpy as np
26
+
27
+
28
+ # Academic Figure Skill Typography Baseline — COPY VERBATIM, place at TOP of script
29
+ mpl.rcParams.update({
30
+ "font.family": "sans-serif",
31
+ "font.sans-serif": ["Arial", "Helvetica", "Liberation Sans"],
32
+ "font.size": 8,
33
+ "axes.titlesize": 8,
34
+ "axes.labelsize": 8,
35
+ "xtick.labelsize": 7,
36
+ "ytick.labelsize": 7,
37
+ "legend.fontsize": 8,
38
+ "figure.titlesize": 9,
39
+ "axes.spines.top": False,
40
+ "axes.spines.right": False,
41
+ "axes.linewidth": 0.6,
42
+ "xtick.direction": "out",
43
+ "ytick.direction": "out",
44
+ "xtick.major.width": 0.6,
45
+ "ytick.major.width": 0.6,
46
+ "legend.frameon": False,
47
+ })
48
+
49
+ # Academic Figure Skill Nature/Cell/Science Color Palette -- COPY VERBATIM
50
+ CATEGORICAL = ["#2166AC", "#B2182B", "#1B7837", "#F1A340", "#762A83", "#666666"]
51
+ CATEGORICAL_EXTENDED = [
52
+ "#2166AC", "#B2182B", "#1B7837", "#F1A340", "#762A83", "#666666",
53
+ "#4393C3", "#D6604D", "#5AAE61", "#B35806", "#9970AB", "#999999",
54
+ ]
55
+ DIVERGING = ["#2166AC", "#F7F7F7", "#B2182B"]
56
+ SEQUENTIAL = ["#F7FBFF", "#6BAED6", "#08306B"]
57
+ ACCENT_RED = "#B2182B"
58
+ GREY = "#999999"
59
+ BLACK = "#222222"
60
+
61
+ # Academic Figure Skill Export Baseline — COPY VERBATIM
62
+ mpl.rcParams.update({
63
+ "pdf.fonttype": 42, # TrueType font embedding
64
+ "svg.fonttype": "none", # editable text in SVG
65
+ "savefig.bbox": "tight", # trim whitespace
66
+ "savefig.dpi": 300,
67
+ })
68
+
69
+
70
+ def save_cns_figure(fig, filename):
71
+ """Standard Academic Figure Skill export: vector PDF + 300dpi PNG preview."""
72
+ fig.savefig(f"{filename}.pdf", bbox_inches="tight", dpi=300)
73
+ fig.savefig(f"{filename}.png", bbox_inches="tight", dpi=300)
74
+
75
+
76
+ POOL = 95.51
77
+ ORACLE = 91.96
78
+ CURRENT = 87.42
79
+ LOSS_MEDIAN = 6.17
80
+ LOSS_MEAN = 8.09
81
+ LOSS_P90 = 24.12
82
+ FLEX_RHO = 0.423
83
+ FLEX_P = 3.17e-18
84
+
85
+ COLORS = {
86
+ "pool": "#4C78A8",
87
+ "oracle": "#7B6DB0",
88
+ "current": "#E08B45",
89
+ "loss_light": "#E9AD82",
90
+ "loss": "#D97841",
91
+ "loss_dark": "#B95F32",
92
+ "flexibility": "#4F9D78",
93
+ "gray": "#6F6F6F",
94
+ "line": "#A0A0A0",
95
+ "light_gray": "#D8D8D8",
96
+ "very_light_gray": "#EEEEEE",
97
+ "text": "#2F2F2F",
98
+ "spine": "#A5A5A5",
99
+ }
100
+
101
+
102
+ def parse_args() -> argparse.Namespace:
103
+ parser = argparse.ArgumentParser(description=__doc__)
104
+ parser.add_argument(
105
+ "--output-dir",
106
+ default="NCS_ManiMol/FIG",
107
+ help="directory for PDF, SVG, and PNG outputs",
108
+ )
109
+ return parser.parse_args()
110
+
111
+
112
+ def validate_statistics() -> None:
113
+ checks = {
114
+ "mean selection loss": (POOL - CURRENT, LOSS_MEAN),
115
+ "pool-to-oracle gap": (POOL - ORACLE, 3.55),
116
+ "oracle headroom": (ORACLE - CURRENT, 4.54),
117
+ }
118
+ for name, (calculated, reported) in checks.items():
119
+ if not np.isclose(calculated, reported, atol=0.005):
120
+ raise ValueError(f"Inconsistent {name}: {calculated:.3f} vs {reported:.3f}")
121
+ if not (0.0 <= FLEX_RHO <= 1.0 and 0.0 < FLEX_P <= 1.0):
122
+ raise ValueError("Invalid flexibility-association statistics")
123
+
124
+
125
+ def style_axis(ax: plt.Axes, *, grid_axis: str | None = None) -> None:
126
+ for side in ("left", "bottom"):
127
+ ax.spines[side].set_color(COLORS["spine"])
128
+ ax.spines[side].set_linewidth(0.7)
129
+ ax.tick_params(color=COLORS["spine"], labelcolor=COLORS["text"], width=0.7, length=3)
130
+ ax.xaxis.label.set_color(COLORS["text"])
131
+ ax.yaxis.label.set_color(COLORS["text"])
132
+ if grid_axis:
133
+ ax.grid(axis=grid_axis, color=COLORS["very_light_gray"], linewidth=0.55, zorder=0)
134
+
135
+
136
+ def add_panel_heading(ax: plt.Axes, label: str, title: str) -> None:
137
+ ax.text(
138
+ 0.0,
139
+ 1.035,
140
+ label,
141
+ transform=ax.transAxes,
142
+ fontsize=11,
143
+ fontweight="bold",
144
+ color=COLORS["text"],
145
+ ha="left",
146
+ va="bottom",
147
+ clip_on=False,
148
+ )
149
+ ax.text(
150
+ 0.085,
151
+ 1.035,
152
+ title,
153
+ transform=ax.transAxes,
154
+ fontsize=9.3,
155
+ fontweight="bold",
156
+ color=COLORS["text"],
157
+ ha="left",
158
+ va="bottom",
159
+ clip_on=False,
160
+ )
161
+
162
+
163
+ def panel_a(ax: plt.Axes) -> None:
164
+ x = np.arange(3)
165
+ y = np.array([POOL, ORACLE, CURRENT])
166
+ stage_colors = [COLORS["pool"], COLORS["oracle"], COLORS["current"]]
167
+
168
+ ax.plot(x, y, color=COLORS["line"], linewidth=0.75, zorder=2)
169
+ ax.scatter(x, y, s=64, c=stage_colors, edgecolors="white", linewidths=0.7, zorder=3)
170
+ for xi, yi in zip(x, y):
171
+ ax.annotate(
172
+ f"{yi:.2f}%",
173
+ (xi, yi),
174
+ xytext=(0, 8),
175
+ textcoords="offset points",
176
+ ha="center",
177
+ va="bottom",
178
+ fontsize=9.0,
179
+ fontweight="semibold",
180
+ color=COLORS["text"],
181
+ )
182
+
183
+ ax.text(0.50, 94.35, "−3.55 pp", ha="center", va="bottom", fontsize=7.5,
184
+ color=COLORS["gray"])
185
+ ax.text(1.50, 90.30, "−4.54 pp", ha="center", va="bottom", fontsize=7.5,
186
+ color=COLORS["gray"])
187
+
188
+ ax.set_ylabel("COV-R (%)", fontsize=8.3, labelpad=4)
189
+ ax.set_xticks(x, ["Pool", "Oracle", "Current"])
190
+ ax.set_yticks([86, 90, 94, 98])
191
+ ax.set_ylim(85.0, 98.2)
192
+ ax.set_xlim(-0.25, 2.25)
193
+ style_axis(ax, grid_axis="y")
194
+ add_panel_heading(ax, "a", "Coverage through compression")
195
+
196
+
197
+ def panel_b(ax: plt.Axes) -> None:
198
+ labels = ["Median", "Mean", "90th pct."]
199
+ values = [LOSS_MEDIAN, LOSS_MEAN, LOSS_P90]
200
+ colors = [COLORS["loss"], COLORS["loss"], COLORS["loss"]]
201
+ y = np.array([2, 1, 0])
202
+
203
+ for yi, value, color in zip(y, values, colors):
204
+ ax.hlines(yi, 0, value, color=color, linewidth=2.0, alpha=0.75, zorder=2)
205
+ ax.scatter(value, yi, s=48, color=color, edgecolor="white", linewidth=0.65, zorder=3)
206
+ ax.annotate(
207
+ f"{value:.2f} pp",
208
+ (value, yi),
209
+ xytext=(6, 0),
210
+ textcoords="offset points",
211
+ ha="left",
212
+ va="center",
213
+ fontsize=7.3,
214
+ fontweight="semibold",
215
+ color=COLORS["text"],
216
+ )
217
+
218
+ ax.set_xlabel("Selection loss (pp)", fontsize=8.3, labelpad=4)
219
+ ax.set_yticks(y, labels)
220
+ ax.set_xlim(0, 28.5)
221
+ ax.set_ylim(-0.55, 2.55)
222
+ ax.set_xticks([0, 5, 10, 15, 20, 25])
223
+ style_axis(ax, grid_axis="x")
224
+ add_panel_heading(ax, "b", "Magnitude of selection loss")
225
+
226
+
227
+ def panel_c(ax: plt.Axes) -> None:
228
+ y = 0.5
229
+ ax.hlines(y, 0, FLEX_RHO, color=COLORS["flexibility"], linewidth=2.2, zorder=2)
230
+ ax.scatter(FLEX_RHO, y, s=70, color=COLORS["flexibility"], edgecolor="white",
231
+ linewidth=0.7, zorder=3)
232
+ ax.annotate("ρ = 0.423", (FLEX_RHO, y), xytext=(-3, 9), textcoords="offset points",
233
+ ha="right", va="bottom", fontsize=8.8, fontweight="semibold",
234
+ color=COLORS["text"])
235
+ ax.annotate(r"$p = 3.17 \times 10^{-18}$", (FLEX_RHO, y), xytext=(-3, -10),
236
+ textcoords="offset points", ha="right", va="top", fontsize=7.5,
237
+ color=COLORS["gray"])
238
+
239
+ ax.set_xlabel("Spearman ρ", fontsize=8.3, labelpad=4)
240
+ ax.set_yticks([y], ["Rotatable bonds\nvs. selection loss"])
241
+ ax.set_xlim(0, 0.5)
242
+ ax.set_ylim(0, 1)
243
+ ax.set_xticks([0.0, 0.2, 0.4, 0.5])
244
+ style_axis(ax, grid_axis="x")
245
+ ax.tick_params(axis="y", labelsize=7.0, pad=2)
246
+ add_panel_heading(ax, "c", "Flexibility association")
247
+
248
+
249
+ def render(output_dir: Path) -> None:
250
+ output_dir.mkdir(parents=True, exist_ok=True)
251
+ fig = plt.figure(figsize=(7.1, 2.40), facecolor="white")
252
+ gs = fig.add_gridspec(1, 3, width_ratios=[1.20, 0.95, 0.65], wspace=0.18)
253
+ axes = [fig.add_subplot(gs[0, index]) for index in range(3)]
254
+ panel_a(axes[0])
255
+ panel_b(axes[1])
256
+ panel_c(axes[2])
257
+ fig.subplots_adjust(left=0.075, right=0.985, bottom=0.19, top=0.855, wspace=0.18)
258
+
259
+ for stem in ("figure3_selection_summary", "figure3_selection_summary_minimal"):
260
+ base = output_dir / stem
261
+ fig.savefig(base.with_suffix(".pdf"), bbox_inches="tight", pad_inches=0.03)
262
+ fig.savefig(base.with_suffix(".svg"), bbox_inches="tight", pad_inches=0.03)
263
+ fig.savefig(base.with_suffix(".png"), dpi=600, bbox_inches="tight", pad_inches=0.03)
264
+ plt.close(fig)
265
+
266
+
267
+ def main() -> None:
268
+ args = parse_args()
269
+ validate_statistics()
270
+ render(Path(args.output_dir))
271
+ print(f"Wrote Figure 3 summary outputs to {args.output_dir}")
272
+
273
+
274
+ if __name__ == "__main__":
275
+ main()
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env python
2
+ """Create small molecule-complete debug subsets from processed GEOM raw lists."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from collections import OrderedDict
8
+ from pathlib import Path
9
+
10
+ import torch
11
+
12
+
13
+ def subset_file(src: Path, dst: Path, molecule_limit: int) -> dict:
14
+ rows = torch.load(src, map_location="cpu", weights_only=False)
15
+ groups = OrderedDict()
16
+ for row in rows:
17
+ mol = row.get("rdmol") if isinstance(row, dict) else None
18
+ smiles = row.get("smiles") if isinstance(row, dict) else None
19
+ if mol is None or smiles is None:
20
+ continue
21
+ key = (str(smiles), int(mol.GetNumAtoms()))
22
+ groups.setdefault(key, []).append(row)
23
+
24
+ selected_keys = list(groups)[:molecule_limit]
25
+ selected = [row for key in selected_keys for row in groups[key]]
26
+ dst.parent.mkdir(parents=True, exist_ok=True)
27
+ torch.save(selected, dst)
28
+ counts = [len(groups[key]) for key in selected_keys]
29
+ return {
30
+ "source": str(src),
31
+ "output": str(dst),
32
+ "molecules": len(selected_keys),
33
+ "conformers": len(selected),
34
+ "min_conformers": min(counts) if counts else 0,
35
+ "max_conformers": max(counts) if counts else 0,
36
+ }
37
+
38
+
39
+ def main() -> None:
40
+ p = argparse.ArgumentParser()
41
+ p.add_argument("--input-dir", type=Path, required=True)
42
+ p.add_argument("--output-dir", type=Path, required=True)
43
+ p.add_argument("--prefix", default="geom_drugs_geomol_top20")
44
+ p.add_argument("--train-molecules", type=int, default=1000)
45
+ p.add_argument("--val-molecules", type=int, default=200)
46
+ args = p.parse_args()
47
+
48
+ reports = []
49
+ for split, limit in (("train", args.train_molecules), ("val", args.val_molecules)):
50
+ reports.append(
51
+ subset_file(
52
+ args.input_dir / f"{args.prefix}_{split}.pt",
53
+ args.output_dir / f"{args.prefix}_debug_{split}.pt",
54
+ limit,
55
+ )
56
+ )
57
+ for report in reports:
58
+ print(report)
59
+
60
+
61
+ if __name__ == "__main__":
62
+ main()
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env python3
2
+ """Build a deterministic low-reference-count GEOM test subset for fast diagnostics."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ from collections import OrderedDict
9
+ from pathlib import Path
10
+
11
+ import torch
12
+
13
+
14
+ def main() -> None:
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument("--input", type=Path, required=True)
17
+ parser.add_argument("--output", type=Path, required=True)
18
+ parser.add_argument("--molecules", type=int, default=50)
19
+ parser.add_argument("--min-conformers", type=int, default=5)
20
+ parser.add_argument("--max-conformers", type=int, default=20)
21
+ args = parser.parse_args()
22
+
23
+ rows = torch.load(args.input, map_location="cpu", weights_only=False)
24
+ groups: OrderedDict[tuple[str, int], list] = OrderedDict()
25
+ for row in rows:
26
+ if not isinstance(row, dict):
27
+ continue
28
+ mol = row.get("rdmol")
29
+ smiles = row.get("smiles")
30
+ if mol is None or smiles is None:
31
+ continue
32
+ groups.setdefault((str(smiles), int(mol.GetNumAtoms())), []).append(row)
33
+
34
+ eligible = [
35
+ (key, values)
36
+ for key, values in groups.items()
37
+ if args.min_conformers <= len(values) <= args.max_conformers
38
+ ]
39
+ eligible.sort(key=lambda item: (len(item[1]), item[0][0], item[0][1]))
40
+ selected = eligible[: args.molecules]
41
+ if len(selected) != args.molecules:
42
+ raise RuntimeError(
43
+ f"Requested {args.molecules} molecules, but only {len(selected)} satisfy "
44
+ f"{args.min_conformers} <= R <= {args.max_conformers}."
45
+ )
46
+
47
+ output_rows = [row for _, values in selected for row in values]
48
+ args.output.parent.mkdir(parents=True, exist_ok=True)
49
+ torch.save(output_rows, args.output)
50
+
51
+ counts = [len(values) for _, values in selected]
52
+ manifest = {
53
+ "source": str(args.input),
54
+ "output": str(args.output),
55
+ "selection": "lowest reference-conformer count, then canonical key",
56
+ "molecules": len(selected),
57
+ "conformers": len(output_rows),
58
+ "min_conformers": min(counts),
59
+ "max_conformers": max(counts),
60
+ "mean_conformers": sum(counts) / len(counts),
61
+ "counts": counts,
62
+ "molecule_keys": [f"{key[0]}__{key[1]}" for key, _ in selected],
63
+ }
64
+ manifest_path = args.output.with_suffix(".manifest.json")
65
+ manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
66
+ print(json.dumps({key: value for key, value in manifest.items() if key not in {"counts", "molecule_keys"}}, indent=2))
67
+
68
+
69
+ if __name__ == "__main__":
70
+ main()
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env python3
2
+ """Merge a Route-2 Stage-I prior checkpoint into a Stage-II checkpoint.
3
+
4
+ The Stage-I checkpoint contains the shared graph encoder, mean head, and the
5
+ fixed-kernel/rank-calibrated dispersion head. The Stage-II checkpoint keeps
6
+ the torsion decoder and any other generation modules. Exact key matching is
7
+ used so that a missing or unexpected parameter cannot be silently ignored.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ from pathlib import Path
13
+
14
+ import torch
15
+
16
+
17
+ def unwrap_state(obj):
18
+ if isinstance(obj, dict) and "model_state_dict" in obj:
19
+ return obj["model_state_dict"], obj
20
+ if isinstance(obj, dict):
21
+ return obj, None
22
+ raise TypeError(f"Unsupported checkpoint object: {type(obj)!r}")
23
+
24
+
25
+ def main():
26
+ parser = argparse.ArgumentParser()
27
+ parser.add_argument("--stage1", required=True)
28
+ parser.add_argument("--stage2", required=True)
29
+ parser.add_argument("--output", required=True)
30
+ args = parser.parse_args()
31
+
32
+ stage1_obj = torch.load(args.stage1, map_location="cpu", weights_only=False)
33
+ stage2_obj = torch.load(args.stage2, map_location="cpu", weights_only=False)
34
+ stage1, _ = unwrap_state(stage1_obj)
35
+ stage2, stage2_container = unwrap_state(stage2_obj)
36
+
37
+ # These are the parameters that define the Stage-I prior. The dispersion
38
+ # head is deliberately included; without it the new audit cannot affect
39
+ # Stage-II proposal widths.
40
+ prefixes = (
41
+ "gnn.",
42
+ "global_edge_predictor.",
43
+ "dispersion_edge_predictor.",
44
+ "conf_embedding.",
45
+ "ab_head.",
46
+ "fusion_weight_head.",
47
+ )
48
+ replaceable = {k for k in stage1 if k.startswith(prefixes)}
49
+ missing = sorted(k for k in replaceable if k not in stage2)
50
+ if missing:
51
+ # A legacy Stage-II checkpoint can lack the optional dispersion head;
52
+ # it is safe to add it because the current model defines the module.
53
+ allowed_missing = [k for k in missing if k.startswith("dispersion_edge_predictor.")]
54
+ unexpected = sorted(set(missing) - set(allowed_missing))
55
+ if unexpected:
56
+ raise RuntimeError(f"Stage-II checkpoint is missing non-optional Stage-I keys: {unexpected[:12]}")
57
+
58
+ merged = dict(stage2)
59
+ for key in replaceable:
60
+ merged[key] = stage1[key]
61
+
62
+ if stage2_container is None:
63
+ output_obj = merged
64
+ else:
65
+ output_obj = dict(stage2_container)
66
+ output_obj["model_state_dict"] = merged
67
+ output_obj["stage1_source"] = str(Path(args.stage1))
68
+ output_obj["stage1_prior_merge"] = "graph+mean+dispersion heads from fixed-a,b rank-loss checkpoint"
69
+
70
+ output = Path(args.output)
71
+ output.parent.mkdir(parents=True, exist_ok=True)
72
+ torch.save(output_obj, output)
73
+
74
+ print(f"saved={output}")
75
+ print(f"stage1_keys_replaced={len(replaceable)}")
76
+ print(f"dispersion_keys={sum(k.startswith('dispersion_edge_predictor.') for k in replaceable)}")
77
+ print(f"merged_keys={len(merged)}")
78
+ print(f"torsion_keys_preserved={sum(k.startswith('torsion_') for k in merged)}")
79
+
80
+
81
+ if __name__ == "__main__":
82
+ main()
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env python3
2
+ """Rigidly place HIF-2A candidates in the crystal frame for post-hoc analysis."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from rdkit import Chem
12
+
13
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
14
+ sys.path.insert(0, str(PROJECT_ROOT))
15
+ sys.path.insert(0, str(PROJECT_ROOT / "docking"))
16
+ from docking.run_preorganized_vina_benchmark import align_probe_to_reference, write_one_sdf
17
+
18
+
19
+ def first_mol(path):
20
+ for mol in Chem.SDMolSupplier(str(path), removeHs=False):
21
+ if mol is not None:
22
+ return mol
23
+ raise ValueError(f"cannot read {path}")
24
+
25
+
26
+ def main():
27
+ parser = argparse.ArgumentParser(description=__doc__)
28
+ parser.add_argument("--manifest", required=True)
29
+ parser.add_argument("--out_dir", required=True)
30
+ parser.add_argument("--max_confs", type=int, default=20)
31
+ args = parser.parse_args()
32
+
33
+ out_dir = Path(args.out_dir)
34
+ rows = []
35
+ with open(args.manifest, newline="") as handle:
36
+ manifest = list(csv.DictReader(handle))
37
+ for item in manifest:
38
+ reference = first_mol(item["crystal_ligand_sdf"])
39
+ paths = {
40
+ "etkdg": item["etkdg_sdf"],
41
+ "manimol": item.get("manimol_stage2_sdf") or item.get("manimol_sdf"),
42
+ }
43
+ for method, path in paths.items():
44
+ supplier = Chem.SDMolSupplier(str(path), removeHs=False)
45
+ for index, mol in enumerate(supplier):
46
+ if index >= args.max_confs:
47
+ break
48
+ if mol is None:
49
+ continue
50
+ placed, rmsd = align_probe_to_reference(mol, reference, item["ligand_smiles"])
51
+ destination = out_dir / item["complex_id"] / method / "placed_sdf" / f"conf_{index:03d}_placed.sdf"
52
+ write_one_sdf(placed, destination)
53
+ rows.append({
54
+ "ligand_id": item["complex_id"], "method": method,
55
+ "candidate_index": index, "placed_sdf": str(destination),
56
+ "posthoc_rigid_fit_rmsd": rmsd,
57
+ })
58
+ out_dir.mkdir(parents=True, exist_ok=True)
59
+ with (out_dir / "placement_audit.csv").open("w", newline="") as handle:
60
+ writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
61
+ writer.writeheader(); writer.writerows(rows)
62
+ print(f"Placed {len(rows)} candidates under {out_dir}")
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()
@@ -0,0 +1,100 @@
1
+ #!/usr/bin/env python
2
+ """Plot equal-budget HIF2A functional-geometry recovery curves.
3
+
4
+ The plot reports only the aggregate values written by
5
+ ``analyze_hif2a_contact_pharmacophore.py``. It neither filters ligands nor
6
+ selects a preferred budget, so the full low-to-higher budget trajectory is
7
+ shown for both methods.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ from pathlib import Path
14
+
15
+ import matplotlib as mpl
16
+ import matplotlib.pyplot as plt
17
+ import pandas as pd
18
+
19
+
20
+ COLORS = {"etkdg": "#7F7F7F", "manimol": "#6A51A3"}
21
+ LABELS = {"etkdg": "ETKDG", "manimol": "MANIMOL"}
22
+ METRICS = [
23
+ ("ensemble_pharmacophore_coverage_mean", "Ensemble pharmacophore\ncoverage"),
24
+ ("functional_state_coverage_mean", "Functional-state\ncoverage"),
25
+ ("topk_functional_recovery_mean", "Top-K functional\nrecovery"),
26
+ ]
27
+
28
+
29
+ def style_axis(ax) -> None:
30
+ ax.spines["top"].set_visible(False)
31
+ ax.spines["right"].set_visible(False)
32
+ ax.spines["left"].set_color("#444444")
33
+ ax.spines["bottom"].set_color("#444444")
34
+ ax.spines["left"].set_linewidth(0.7)
35
+ ax.spines["bottom"].set_linewidth(0.7)
36
+ ax.grid(axis="y", color="#E6E6E6", linewidth=0.55)
37
+ ax.tick_params(labelsize=8.5, length=3, width=0.7, color="#444444")
38
+
39
+
40
+ def main() -> None:
41
+ parser = argparse.ArgumentParser()
42
+ parser.add_argument(
43
+ "--summary_csv",
44
+ default="outputs/docking/hif2a_low_budget_efficiency/hif2a_contact_pharmacophore_ensemble_summary_by_method.csv",
45
+ )
46
+ parser.add_argument("--output_prefix", default="NCS_ManiMol/FIG/hif2a_low_budget_efficiency")
47
+ args = parser.parse_args()
48
+
49
+ mpl.rcParams.update(
50
+ {
51
+ "font.family": "Arial",
52
+ "font.size": 9,
53
+ "svg.fonttype": "none",
54
+ "pdf.fonttype": 42,
55
+ "figure.facecolor": "white",
56
+ "axes.facecolor": "white",
57
+ "savefig.facecolor": "white",
58
+ }
59
+ )
60
+ summary = pd.read_csv(args.summary_csv)
61
+ methods = ["etkdg", "manimol"]
62
+ expected = {1, 5, 10, 20}
63
+ observed = set(summary["K"].astype(int))
64
+ if not expected.issubset(observed):
65
+ raise ValueError(f"Expected budgets {sorted(expected)}, found {sorted(observed)}")
66
+
67
+ fig, axes = plt.subplots(1, 3, figsize=(7.25, 2.35), dpi=600, sharey=True)
68
+ for panel, (ax, (metric, title)) in enumerate(zip(axes, METRICS)):
69
+ for method in methods:
70
+ subset = summary[summary["method"].eq(method)].sort_values("K")
71
+ ax.plot(
72
+ subset["K"],
73
+ 100.0 * subset[metric],
74
+ color=COLORS[method],
75
+ marker="o" if method == "etkdg" else "s",
76
+ markersize=4.0,
77
+ linewidth=1.65,
78
+ label=LABELS[method],
79
+ )
80
+ ax.set_title(f"{chr(97 + panel)} {title}", loc="left", fontsize=9.3, fontweight="semibold", pad=5)
81
+ ax.set_xlim(0.6, 20.6)
82
+ ax.set_xticks([1, 5, 10, 20])
83
+ ax.set_xlabel("Conformer budget (K)", fontsize=9)
84
+ ax.set_ylim(0, 102)
85
+ ax.set_yticks([0, 25, 50, 75, 100])
86
+ style_axis(ax)
87
+ axes[0].set_ylabel("Recovery (%)", fontsize=9)
88
+ axes[0].legend(loc="lower right", fontsize=7.6, frameon=False, handlelength=1.6, borderaxespad=0.2)
89
+ fig.subplots_adjust(left=0.078, right=0.993, bottom=0.22, top=0.86, wspace=0.25)
90
+
91
+ output_prefix = Path(args.output_prefix)
92
+ output_prefix.parent.mkdir(parents=True, exist_ok=True)
93
+ fig.savefig(output_prefix.with_suffix(".png"), dpi=600)
94
+ fig.savefig(output_prefix.with_suffix(".pdf"))
95
+ fig.savefig(output_prefix.with_suffix(".svg"))
96
+ plt.close(fig)
97
+
98
+
99
+ if __name__ == "__main__":
100
+ main()