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,397 @@
1
+ #!/usr/bin/env python3
2
+ """Render a clean two-panel HIF2A docking pose comparison for Figure 11.
3
+
4
+ The script uses existing receptor and pose coordinates only. It does not alter
5
+ the docking poses, ligand conformations, or any scientific result. The output is
6
+ a simplified paper figure with (a) pocket context and (b) a ligand overlay.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import csv
12
+ import json
13
+ import math
14
+ from pathlib import Path
15
+ from typing import Dict, Iterable, List, Sequence, Tuple
16
+
17
+ import pymol
18
+ from PIL import Image, ImageDraw, ImageFont
19
+
20
+
21
+ ROOT = Path(__file__).resolve().parents[1]
22
+ CASE = "hif2a_lig019"
23
+ LIGAND_NAME = "7b"
24
+ RECEPTOR = ROOT / "data/docking/fep-benchmark/hif2a/5tbm_prepared.pdb"
25
+ POSE_DIR = ROOT / "outputs/docking/hif2a_visualization/publication_pymol/pocket_case/hif2a_lig019"
26
+ CRYSTAL = POSE_DIR / "crystal_reference.pdb"
27
+ ETKDG = POSE_DIR / "etkdg_top_score.pdb"
28
+ MANIMOL = POSE_DIR / "manimol_top_score.pdb"
29
+ METRICS_CSV = ROOT / "outputs/docking/hif2a_visualization/hif2a_pose_overlay_cases.csv"
30
+ OUT_DIR = ROOT / "outputs/docking/hif2a_visualization/publication_pymol/figure11_clean"
31
+ FIG_DIR = ROOT / "NCS_ManiMol/FIG"
32
+
33
+ PANEL_W = 2200
34
+ PANEL_H = 1350
35
+ PREFERRED_RESIDUES = {"A277", "M289", "L296"}
36
+ AA1 = {
37
+ "ALA": "A", "ARG": "R", "ASN": "N", "ASP": "D", "CYS": "C",
38
+ "GLN": "Q", "GLU": "E", "GLY": "G", "HIS": "H", "ILE": "I",
39
+ "LEU": "L", "LYS": "K", "MET": "M", "PHE": "F", "PRO": "P",
40
+ "SER": "S", "THR": "T", "TRP": "W", "TYR": "Y", "VAL": "V",
41
+ }
42
+ POLAR = {"N", "O", "S"}
43
+
44
+
45
+ def read_metrics() -> Dict[str, float | str]:
46
+ with METRICS_CSV.open(newline="") as handle:
47
+ for row in csv.DictReader(handle):
48
+ if row["complex_id"] == CASE:
49
+ return {
50
+ "ligand": row["ligand_name"],
51
+ "manimol_score": float(row["manimol_top_score"]),
52
+ "manimol_rmsd": float(row["manimol_top_score_rmsd"]),
53
+ "etkdg_score": float(row["etkdg_top_score"]),
54
+ "etkdg_rmsd": float(row["etkdg_top_score_rmsd"]),
55
+ }
56
+ raise RuntimeError(f"No metrics found for {CASE} in {METRICS_CSV}")
57
+
58
+
59
+ def font(size: int):
60
+ for candidate in (
61
+ "/System/Library/Fonts/Supplemental/Arial.ttf",
62
+ "/Library/Fonts/Arial.ttf",
63
+ "/System/Library/Fonts/Supplemental/Helvetica.ttf",
64
+ ):
65
+ if Path(candidate).exists():
66
+ return ImageFont.truetype(candidate, size=size)
67
+ return ImageFont.load_default()
68
+
69
+
70
+ def launch_pymol():
71
+ pymol.pymol_argv = ["pymol", "-qc"]
72
+ pymol.finish_launching()
73
+ from pymol import cmd
74
+
75
+ return cmd
76
+
77
+
78
+ def setup(cmd) -> None:
79
+ cmd.reinitialize()
80
+ cmd.bg_color("white")
81
+ cmd.set("orthoscopic", 1)
82
+ cmd.set("ray_opaque_background", 1)
83
+ cmd.set("ray_shadows", 0)
84
+ cmd.set("depth_cue", 0)
85
+ cmd.set("antialias", 2)
86
+ cmd.set("ambient", 0.42)
87
+ cmd.set("direct", 0.70)
88
+ cmd.set("specular", 0.10)
89
+ cmd.set("shininess", 18)
90
+ cmd.set("valence", 0)
91
+ cmd.set("cartoon_transparency", 0.76)
92
+ cmd.set("surface_quality", 1)
93
+ cmd.set("transparency_mode", 2)
94
+ cmd.set("label_font_id", 7)
95
+ cmd.set("label_size", 23)
96
+ cmd.set_color("label_bluegray", [0.22, 0.34, 0.42])
97
+ cmd.set("label_color", "label_bluegray")
98
+ cmd.set_color("protein_cartoon_soft", [0.78, 0.82, 0.94])
99
+ cmd.set_color("pocket_surface_soft", [0.82, 0.84, 0.86])
100
+ cmd.set_color("pocket_carbon_soft", [0.58, 0.60, 0.63])
101
+ cmd.set_color("crystal_carbon", [0.24, 0.24, 0.24])
102
+ cmd.set_color("etkdg_carbon", [0.93, 0.45, 0.08])
103
+ cmd.set_color("manimol_carbon", [0.76, 0.05, 0.55])
104
+ cmd.set_color("polar_contact_red", [0.72, 0.12, 0.12])
105
+
106
+
107
+ def load_objects(cmd) -> None:
108
+ for path in (RECEPTOR, CRYSTAL, ETKDG, MANIMOL):
109
+ if not path.exists():
110
+ raise FileNotFoundError(path)
111
+ cmd.load(str(RECEPTOR), "rec")
112
+ cmd.load(str(CRYSTAL), "crystal")
113
+ cmd.load(str(ETKDG), "etkdg")
114
+ cmd.load(str(MANIMOL), "manimol")
115
+ cmd.remove("hydro")
116
+ cmd.hide("everything", "all")
117
+
118
+
119
+ def color_ligand(cmd, obj: str, carbon_color: str, radius: float = 0.24) -> None:
120
+ cmd.show("sticks", obj)
121
+ cmd.set("stick_radius", radius, obj)
122
+ cmd.color(carbon_color, f"{obj} and elem C")
123
+ cmd.color("blue", f"{obj} and elem N")
124
+ cmd.color("red", f"{obj} and elem O")
125
+ cmd.color("yelloworange", f"{obj} and elem S")
126
+ cmd.color("cyan", f"{obj} and elem F")
127
+ cmd.color("green", f"{obj} and elem Cl")
128
+ cmd.color("firebrick", f"{obj} and elem Br")
129
+ cmd.color("purple", f"{obj} and elem I")
130
+
131
+
132
+ def atom_records(cmd, selection: str) -> List[Dict[str, object]]:
133
+ records = []
134
+ for atom in cmd.get_model(selection).atom:
135
+ if atom.symbol.upper() == "H":
136
+ continue
137
+ records.append(
138
+ {
139
+ "coord": tuple(atom.coord),
140
+ "element": atom.symbol.upper(),
141
+ "resn": atom.resn,
142
+ "resi": atom.resi,
143
+ "chain": atom.chain,
144
+ "name": atom.name,
145
+ }
146
+ )
147
+ return records
148
+
149
+
150
+ def dist(a: Sequence[float], b: Sequence[float]) -> float:
151
+ return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))
152
+
153
+
154
+ def nearby_residues(cmd, cutoff: float = 4.0, limit: int = 3) -> List[Tuple[str, str, str, float]]:
155
+ lig_atoms = atom_records(cmd, "crystal or etkdg or manimol")
156
+ residues: Dict[Tuple[str, str, str], float] = {}
157
+ for atom in atom_records(cmd, "rec and polymer.protein"):
158
+ minimum = min(dist(atom["coord"], lig["coord"]) for lig in lig_atoms)
159
+ if minimum <= cutoff:
160
+ key = (str(atom["chain"]), str(atom["resn"]), str(atom["resi"]))
161
+ residues[key] = min(residues.get(key, 999.0), minimum)
162
+ ranked = sorted([(chain, resn, resi, value) for (chain, resn, resi), value in residues.items()], key=lambda row: row[3])
163
+ preferred = [row for row in ranked if f"{AA1.get(row[1].upper(), row[1][:1].upper())}{row[2]}" in PREFERRED_RESIDUES]
164
+ selected = preferred[:limit]
165
+ for row in ranked:
166
+ if row not in selected:
167
+ selected.append(row)
168
+ if len(selected) >= limit:
169
+ break
170
+ # Keep a compact chemically readable subset. Preferred residues are used
171
+ # only when they are genuinely near the ligand in the current structure.
172
+ return selected[:limit]
173
+
174
+
175
+ def residue_selection(residues: Iterable[Tuple[str, str, str, float]]) -> str:
176
+ terms = [f"(rec and chain {chain} and resi {resi})" for chain, _resn, resi, _value in residues]
177
+ return " or ".join(terms) if terms else "none"
178
+
179
+
180
+ def show_residues(cmd, residues: List[Tuple[str, str, str, float]], label: bool = True) -> None:
181
+ selection = residue_selection(residues)
182
+ if selection == "none":
183
+ return
184
+ cmd.show("sticks", selection)
185
+ cmd.set("stick_radius", 0.075, selection)
186
+ cmd.color("pocket_carbon_soft", f"({selection}) and elem C")
187
+ cmd.color("blue", f"({selection}) and elem N")
188
+ cmd.color("red", f"({selection}) and elem O")
189
+ cmd.color("yelloworange", f"({selection}) and elem S")
190
+ if label:
191
+ for idx, (chain, resn, resi, _value) in enumerate(residues):
192
+ one = AA1.get(resn.upper(), resn[:1].upper())
193
+ label_sel = f"label_res_{idx}"
194
+ cmd.select(label_sel, f"rec and chain {chain} and resi {resi} and name CA")
195
+ if cmd.count_atoms(label_sel):
196
+ cmd.label(label_sel, repr(f"{one}{resi}"))
197
+
198
+
199
+ def draw_contacts(cmd, residues: List[Tuple[str, str, str, float]], cutoff: float = 3.6, max_contacts: int = 2) -> List[Dict[str, object]]:
200
+ lig_atoms = [atom for atom in atom_records(cmd, "manimol") if atom["element"] in POLAR]
201
+ prot_atoms = [atom for atom in atom_records(cmd, f"({residue_selection(residues)})") if atom["element"] in POLAR]
202
+ candidates = []
203
+ seen_res = set()
204
+ for pa in prot_atoms:
205
+ for la in lig_atoms:
206
+ value = dist(pa["coord"], la["coord"])
207
+ key = (pa["chain"], pa["resn"], pa["resi"])
208
+ if value <= cutoff and key not in seen_res:
209
+ seen_res.add(key)
210
+ candidates.append((value, pa, la))
211
+ contacts = []
212
+ for i, (value, pa, la) in enumerate(sorted(candidates, key=lambda row: row[0])[:max_contacts]):
213
+ name = f"polar_contact_{i}"
214
+ cmd.distance(name, f"rec and chain {pa['chain']} and resi {pa['resi']} and name {pa['name']}", f"manimol and name {la['name']}")
215
+ cmd.color("polar_contact_red", name)
216
+ cmd.set("dash_width", 1.7, name)
217
+ cmd.set("dash_gap", 0.28, name)
218
+ cmd.set("label_color", "polar_contact_red", name)
219
+ cmd.set("label_size", 17, name)
220
+ res_label = f"{AA1.get(str(pa['resn']).upper(), str(pa['resn'])[0])}{pa['resi']}"
221
+ contacts.append(
222
+ {
223
+ "system": CASE,
224
+ "residue": res_label,
225
+ "protein_atom": pa["name"],
226
+ "ligand_atom": la["name"],
227
+ "distance_A": round(value, 2),
228
+ "interaction_type": "polar contact",
229
+ }
230
+ )
231
+ return contacts
232
+
233
+
234
+ def base_scene(cmd, residues: List[Tuple[str, str, str, float]], with_surface: bool) -> None:
235
+ cmd.hide("everything", "all")
236
+ if with_surface:
237
+ cmd.show("cartoon", "byres (rec within 7.0 of (crystal or etkdg or manimol))")
238
+ cmd.color("protein_cartoon_soft", "rec and polymer.protein")
239
+ cmd.set("cartoon_transparency", 0.88, "rec")
240
+ surface_sel = "byres (rec within 5.0 of (crystal or etkdg or manimol))"
241
+ cmd.create("pocket_surface", surface_sel)
242
+ cmd.show("surface", "pocket_surface")
243
+ cmd.color("pocket_surface_soft", "pocket_surface")
244
+ cmd.set("transparency", 0.88, "pocket_surface")
245
+ show_residues(cmd, residues, label=not with_surface)
246
+ color_ligand(cmd, "crystal", "crystal_carbon", 0.30)
247
+ color_ligand(cmd, "etkdg", "etkdg_carbon", 0.255)
248
+ color_ligand(cmd, "manimol", "manimol_carbon", 0.255)
249
+
250
+
251
+ def render_panel(cmd, path: Path, residues: List[Tuple[str, str, str, float]], with_surface: bool, contacts: bool) -> List[Dict[str, object]]:
252
+ if cmd.get_names("objects").count("pocket_surface"):
253
+ cmd.delete("pocket_surface")
254
+ base_scene(cmd, residues, with_surface=with_surface)
255
+ contact_rows: List[Dict[str, object]] = []
256
+ if contacts:
257
+ contact_rows = draw_contacts(cmd, residues)
258
+ cmd.orient("crystal or etkdg or manimol")
259
+ cmd.turn("x", -14)
260
+ cmd.turn("y", 32)
261
+ cmd.turn("z", -12)
262
+ cmd.zoom("crystal or etkdg or manimol", 4.2 if with_surface else 3.35)
263
+ cmd.clip("slab", 18 if with_surface else 12)
264
+ cmd.ray(PANEL_W, PANEL_H)
265
+ path.parent.mkdir(parents=True, exist_ok=True)
266
+ cmd.png(str(path), width=PANEL_W, height=PANEL_H, dpi=300, ray=0)
267
+ return contact_rows
268
+
269
+
270
+ def add_text_box(draw: ImageDraw.ImageDraw, xy: Tuple[int, int], lines: List[Tuple[str, Tuple[int, int, int]]], pad: int = 18, size: int = 42) -> None:
271
+ f = font(size)
272
+ line_h = int(size * 1.28)
273
+ width = max(draw.textbbox((0, 0), text, font=f)[2] for text, _color in lines) + 2 * pad
274
+ height = len(lines) * line_h + 2 * pad
275
+ x, y = xy
276
+ draw.rounded_rectangle((x, y, x + width, y + height), radius=16, fill=(255, 255, 255), outline=(210, 210, 210), width=2)
277
+ for i, (text, color) in enumerate(lines):
278
+ draw.text((x + pad, y + pad + i * line_h), text, fill=color, font=f)
279
+
280
+
281
+ def compose(context_png: Path, overlay_png: Path, metrics: Dict[str, float | str], contacts: List[Dict[str, object]]) -> Path:
282
+ context = Image.open(context_png).convert("RGB")
283
+ overlay = Image.open(overlay_png).convert("RGB")
284
+ # PyMOL leaves a broad blank lead-in on the overlay export. Crop only that
285
+ # empty edge before assembly so panels a and b read as one paired figure.
286
+ overlay_left_crop = 500
287
+ overlay = overlay.crop((overlay_left_crop, 0, overlay.width, overlay.height))
288
+ context_w, panel_h = context.size
289
+ overlay_w, _ = overlay.size
290
+ top = 112
291
+ # The scientific interpretation belongs in the manuscript text, not in a
292
+ # sentence rendered inside the figure. Keep only a compact bottom margin.
293
+ bottom = 24
294
+ # Keep the context and zoomed overlay visually paired.
295
+ gap = 12
296
+ margin = 34
297
+ width = context_w + overlay_w + gap + 2 * margin
298
+ height = panel_h + top + bottom + 2 * margin
299
+ fig = Image.new("RGB", (width, height), "white")
300
+ draw = ImageDraw.Draw(fig)
301
+ title_f = font(58)
302
+ panel_f = font(62)
303
+ small_f = font(34)
304
+ y0 = top
305
+ fig.paste(context, (margin, y0))
306
+ bx = margin + context_w + gap
307
+ fig.paste(overlay, (bx, y0))
308
+ draw.text((margin, 26), "a", fill=(0, 0, 0), font=panel_f)
309
+ draw.text((margin + 66, 36), "Pocket context", fill=(0, 0, 0), font=title_f)
310
+ draw.text((bx, 26), "b", fill=(0, 0, 0), font=panel_f)
311
+ draw.text((bx + 66, 36), "Zoomed pose overlay", fill=(0, 0, 0), font=title_f)
312
+
313
+ legend = [
314
+ ("Crystal/reference", (70, 70, 70)),
315
+ ("ETKDG", (225, 105, 25)),
316
+ ("MANIMOL", (180, 22, 135)),
317
+ ]
318
+ lx = bx + 52
319
+ ly = y0 + 42
320
+ add_text_box(draw, (lx, ly), legend, pad=18, size=44)
321
+
322
+ metric_f = font(46)
323
+ metric_x = bx + overlay_w - 1030
324
+ metric_y = y0 + 44
325
+ draw.text((metric_x, metric_y), f"HIF2A ligand {metrics.get('ligand', LIGAND_NAME)} ({CASE})", fill=(30, 30, 30), font=metric_f)
326
+ draw.text((metric_x, metric_y + 58), f"ETKDG: RMSD {metrics['etkdg_rmsd']:.2f} Å | Vina {metrics['etkdg_score']:.2f}", fill=(210, 90, 20), font=metric_f)
327
+ draw.text((metric_x, metric_y + 116), f"MANIMOL: RMSD {metrics['manimol_rmsd']:.2f} Å | Vina {metrics['manimol_score']:.2f}", fill=(170, 20, 125), font=metric_f)
328
+
329
+ # A single restrained annotation highlights the local endpoint where the
330
+ # overlaid conformers diverge most visibly in this view.
331
+ circle = (
332
+ bx + int(context_w * 0.25) - overlay_left_crop,
333
+ y0 + int(panel_h * 0.39),
334
+ bx + int(context_w * 0.49) - overlay_left_crop,
335
+ y0 + int(panel_h * 0.58),
336
+ )
337
+ draw.ellipse(circle, outline=(190, 30, 30), width=5)
338
+ draw.line((circle[2] - 8, circle[1] + 8, circle[2] + 150, circle[1] - 62), fill=(190, 30, 30), width=4)
339
+ draw.text((circle[2] + 165, circle[1] - 82), "Flexible substituent\n deviation", fill=(150, 30, 30), font=small_f, spacing=4)
340
+
341
+ if contacts:
342
+ contact_text = "; ".join(f"{row['residue']} {row['distance_A']:.2f} Å" for row in contacts[:2])
343
+ draw.text((bx + 48, y0 + panel_h - 48), f"Polar contact opportunity: {contact_text}", fill=(115, 30, 30), font=small_f)
344
+
345
+ out = OUT_DIR / "hif2a_pocket_pose_overlay_publication_clean.png"
346
+ out_pdf = OUT_DIR / "hif2a_pocket_pose_overlay_publication_clean.pdf"
347
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
348
+ fig.save(out, dpi=(300, 300))
349
+ fig.save(out_pdf, resolution=300.0)
350
+ return out
351
+
352
+
353
+ def main() -> None:
354
+ metrics = read_metrics()
355
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
356
+ cmd = launch_pymol()
357
+ setup(cmd)
358
+ load_objects(cmd)
359
+ residues = nearby_residues(cmd, cutoff=4.0, limit=3)
360
+ context_png = OUT_DIR / "panel_a_pocket_context.png"
361
+ overlay_png = OUT_DIR / "panel_b_pose_overlay.png"
362
+ _ = render_panel(cmd, context_png, residues, with_surface=True, contacts=False)
363
+ contacts = render_panel(cmd, overlay_png, residues, with_surface=False, contacts=True)
364
+ figure_png = compose(context_png, overlay_png, metrics, contacts)
365
+ (OUT_DIR / "contacts.csv").write_text(
366
+ "system,residue,protein_atom,ligand_atom,distance_A,interaction_type\n"
367
+ + "\n".join(
368
+ f"{row['system']},{row['residue']},{row['protein_atom']},{row['ligand_atom']},{row['distance_A']:.2f},{row['interaction_type']}"
369
+ for row in contacts
370
+ )
371
+ + ("\n" if contacts else "")
372
+ )
373
+ (OUT_DIR / "figure11_clean_metadata.json").write_text(
374
+ json.dumps(
375
+ {
376
+ "case": CASE,
377
+ "ligand_name": metrics.get("ligand", LIGAND_NAME),
378
+ "residues": [
379
+ {"label": f"{AA1.get(resn, resn[:1])}{resi}", "distance_A": round(value, 2)}
380
+ for _chain, resn, resi, value in residues
381
+ ],
382
+ "metrics": metrics,
383
+ "contacts": contacts,
384
+ },
385
+ indent=2,
386
+ )
387
+ )
388
+ target = FIG_DIR / "hif2a_pocket_pose_overlay_publication.png"
389
+ target.write_bytes(figure_png.read_bytes())
390
+ print(f"Saved {figure_png}")
391
+ print(f"Updated {target}")
392
+ print(f"Contacts: {OUT_DIR / 'contacts.csv'}")
393
+ cmd.quit()
394
+
395
+
396
+ if __name__ == "__main__":
397
+ main()
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env python3
2
+ """Leakage-resistant BACE 2D baseline for the downstream benchmark."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ from rdkit import Chem, RDLogger
13
+ from rdkit.Chem import AllChem
14
+ from sklearn.linear_model import LogisticRegression
15
+ from sklearn.metrics import average_precision_score, roc_auc_score
16
+ from sklearn.pipeline import make_pipeline
17
+ from sklearn.preprocessing import StandardScaler
18
+
19
+ RDLogger.DisableLog("rdApp.*")
20
+
21
+
22
+ def fp(smiles: str, n_bits: int) -> np.ndarray:
23
+ mol = Chem.MolFromSmiles(smiles)
24
+ if mol is None:
25
+ raise ValueError(f"Invalid SMILES: {smiles}")
26
+ bitvect = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=n_bits)
27
+ out = np.zeros((n_bits,), dtype=np.float32)
28
+ Chem.DataStructs.ConvertToNumpyArray(bitvect, out)
29
+ return out
30
+
31
+
32
+ def main() -> None:
33
+ p = argparse.ArgumentParser()
34
+ p.add_argument("--input", default="data/downstream_activity/bace/bace_activity_clean.csv")
35
+ p.add_argument("--output", default="outputs/downstream_activity/bace_2d_baseline.json")
36
+ p.add_argument("--bits", type=int, default=2048)
37
+ args = p.parse_args()
38
+
39
+ df = pd.read_csv(args.input)
40
+ if "scaffold_split" not in df or "activity_label" not in df:
41
+ raise ValueError("Run prepare_bace_activity.py first")
42
+ x = np.stack([fp(str(s), args.bits) for s in df["smiles"]])
43
+ y = df["activity_label"].astype(int).to_numpy()
44
+ train = df["scaffold_split"].eq("train").to_numpy()
45
+ test = df["scaffold_split"].eq("test").to_numpy()
46
+ if train.sum() == 0 or test.sum() == 0:
47
+ raise RuntimeError("Empty scaffold split")
48
+
49
+ model = make_pipeline(
50
+ StandardScaler(with_mean=False),
51
+ LogisticRegression(max_iter=1000, class_weight="balanced", random_state=20260826),
52
+ )
53
+ model.fit(x[train], y[train])
54
+ score = model.predict_proba(x[test])[:, 1]
55
+ result = {
56
+ "task": "BACE binary activity prediction",
57
+ "representation": "Morgan/ECFP radius=2, 2048 bits",
58
+ "split": "deterministic scaffold split",
59
+ "train_molecules": int(train.sum()),
60
+ "test_molecules": int(test.sum()),
61
+ "test_positive_fraction": float(y[test].mean()),
62
+ "AUROC": float(roc_auc_score(y[test], score)),
63
+ "AUPRC": float(average_precision_score(y[test], score)),
64
+ }
65
+ out = Path(args.output)
66
+ out.parent.mkdir(parents=True, exist_ok=True)
67
+ out.write_text(json.dumps(result, indent=2) + "\n")
68
+ print(json.dumps(result, indent=2))
69
+ print(f"Saved: {out}")
70
+
71
+
72
+ if __name__ == "__main__":
73
+ main()