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,56 @@
1
+ #!/usr/bin/env python3
2
+ """Check whether the installed ET-Flow runtime and default checkpoint are usable."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import os
8
+ import sys
9
+ import traceback
10
+ from pathlib import Path
11
+
12
+
13
+ def main():
14
+ parser = argparse.ArgumentParser(description="Validate ET-Flow package and checkpoint loading.")
15
+ parser.add_argument("--model", default="drugs-o3")
16
+ parser.add_argument("--device", default="cpu")
17
+ parser.add_argument("--cache", default=str(Path.home() / ".cache" / "etflow"))
18
+ args, _ = parser.parse_known_args()
19
+
20
+ cache_dir = Path(args.cache).expanduser()
21
+ cache_path = cache_dir / f"{args.model}.ckpt"
22
+ print(f"Python: {sys.executable}")
23
+ print(f"Model: {args.model}")
24
+ print(f"Expected checkpoint cache: {cache_path}")
25
+ if cache_path.exists():
26
+ print(f"Cached checkpoint size: {cache_path.stat().st_size} bytes")
27
+ else:
28
+ print("Cached checkpoint: not found")
29
+
30
+ try:
31
+ from etflow import BaseFlow
32
+
33
+ model = BaseFlow.from_default(model=args.model, device=args.device, cache=str(cache_dir))
34
+ print(f"ET-Flow load status: OK ({type(model).__name__})")
35
+ except EOFError:
36
+ print("ET-Flow load status: FAILED")
37
+ print("Reason: checkpoint file ended unexpectedly, which usually means the cached .ckpt is empty or incomplete.")
38
+ print("Suggested fix:")
39
+ print(f" rm -f {cache_path}")
40
+ print(f" {sys.executable} scripts/check_etflow_runtime.py --model {args.model} --device {args.device}")
41
+ raise
42
+ except FileNotFoundError:
43
+ print("ET-Flow load status: FAILED")
44
+ print("Reason: ET-Flow could not fetch or open the checkpoint. If network access is restricted, rerun this on the server or in a terminal with access to Zenodo.")
45
+ print("Suggested fix:")
46
+ print(f" rm -f {cache_path}")
47
+ print(f" {sys.executable} scripts/check_etflow_runtime.py --model {args.model} --device {args.device}")
48
+ raise
49
+ except Exception:
50
+ print("ET-Flow load status: FAILED")
51
+ traceback.print_exc()
52
+ raise
53
+
54
+
55
+ if __name__ == "__main__":
56
+ main()
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env python3
2
+ """Compare learned, shuffled, random, and train-fitted topology priors."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+ import sys
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ import torch
13
+ from scipy.stats import pearsonr, spearmanr
14
+ from torch_geometric.data import Batch
15
+
16
+ ROOT = Path(__file__).resolve().parents[1]
17
+ if str(ROOT) not in sys.path:
18
+ sys.path.insert(0, str(ROOT))
19
+ from dataset.sharded_drugdataset import ShardedDrugDataset
20
+ from infer_base_conformers import checkpoint_max_confs
21
+ from models.model0 import prob_low_dim_kernel
22
+ from train_torsional_denoiser import load_base_model
23
+
24
+
25
+ def parse_args():
26
+ p = argparse.ArgumentParser()
27
+ p.add_argument("--checkpoint", required=True)
28
+ p.add_argument("--sharded-root", required=True)
29
+ p.add_argument("--mapping", required=True)
30
+ p.add_argument("--max-molecules", type=int, default=50)
31
+ p.add_argument("--device", default="cuda")
32
+ p.add_argument("--seed", type=int, default=20260909)
33
+ p.add_argument("--output-dir", default="results/prior_validation_sources")
34
+ return p.parse_args()
35
+
36
+
37
+ def corr(fn, x, y):
38
+ if np.ptp(x) < 1e-12 or np.ptp(y) < 1e-12:
39
+ return np.nan
40
+ result = fn(x, y)
41
+ return float(getattr(result, "statistic", result[0]))
42
+
43
+
44
+ def metrics(pred, target):
45
+ delta = pred - target
46
+ count = max(1, int(np.ceil(0.1 * len(pred))))
47
+ ptop = set(np.argpartition(pred, -count)[-count:].tolist())
48
+ ttop = set(np.argpartition(target, -count)[-count:].tolist())
49
+ return {
50
+ "mae": float(np.abs(delta).mean()),
51
+ "rmse": float(np.sqrt((delta * delta).mean())),
52
+ "pearson": corr(pearsonr, pred, target),
53
+ "spearman": corr(spearmanr, pred, target),
54
+ "topk_overlap": float(len(ptop & ttop) / len(ptop | ttop)),
55
+ }
56
+
57
+
58
+ def distance_matrix(edge, n, device):
59
+ out = torch.full((n, n), n + 1, dtype=torch.long, device=device)
60
+ out.fill_diagonal_(0)
61
+ if edge is not None and edge.numel():
62
+ out[edge[0], edge[1]] = 1
63
+ for k in range(n):
64
+ out = torch.minimum(out, out[:, k:k + 1] + out[k:k + 1, :])
65
+ return out
66
+
67
+
68
+ @torch.inference_mode()
69
+ def evaluate(model, dataset, group, mapping, device, rng):
70
+ records = [dataset[i] for i in list(group)[:20]]
71
+ first = records[0]
72
+ batch = Batch.from_data_list([first]).to(device)
73
+ node = model.gnn(batch)
74
+ graph = model.pool(node, batch.batch)[0]
75
+ edge = model._get_local_edge_index(batch.edge_index, batch.batch == 0)
76
+ learned, _ = model._predict_P_global(node, edge)
77
+ teachers = []
78
+ for item in records:
79
+ cid = int(torch.as_tensor(item.conf_id).reshape(-1)[0].item())
80
+ a, b = model.predict_ab(graph, cid)
81
+ teachers.append(prob_low_dim_kernel(item.pos.to(device=device, dtype=node.dtype), a, b))
82
+ target = torch.stack(teachers).mean(0)
83
+ upper = torch.triu(torch.ones_like(target, dtype=torch.bool), diagonal=1)
84
+ learned_np = learned[upper].detach().cpu().numpy().astype(float)
85
+ target_np = target[upper].detach().cpu().numpy().astype(float)
86
+ random_np = rng.permutation(learned_np)
87
+ shuffled = learned_np.reshape(-1).copy()
88
+ shuffled = rng.permutation(shuffled)
89
+ dist = distance_matrix(edge, int(first.pos.size(0)), device)[upper].cpu().numpy()
90
+ topo_values = np.asarray(mapping["mean_q_by_bin"], dtype=float)
91
+ topo_np = topo_values[np.minimum(np.maximum(dist.astype(int), 1), 6) - 1]
92
+ result = []
93
+ for name, pred in (("learned", learned_np), ("random", random_np), ("shuffled", shuffled), ("topology", topo_np)):
94
+ result.append({"molecule_id": int(first.mol_id.item()), "n_rotatable_bonds": int(len({tuple(sorted((int(row[1]), int(row[2])))) for row in first.torsion_index.t().tolist()})) if first.torsion_index.numel() else 0, "source": name, **metrics(pred, target_np)})
95
+ return result
96
+
97
+
98
+ def main():
99
+ args = parse_args()
100
+ rng = np.random.default_rng(args.seed)
101
+ device = torch.device(args.device)
102
+ capacity = checkpoint_max_confs(args.checkpoint)
103
+ model = load_base_model(argparse.Namespace(checkpoint=args.checkpoint, max_confs=capacity), device)
104
+ dataset = ShardedDrugDataset(args.sharded_root, "test", cache_size=1)
105
+ groups = [g for block in dataset.molecule_groups_by_shard for g in block][:args.max_molecules]
106
+ mapping = json.loads(Path(args.mapping).read_text(encoding="utf-8"))
107
+ rows = []
108
+ for number, group in enumerate(groups, 1):
109
+ rows.extend(evaluate(model, dataset, group, mapping, device, rng))
110
+ if number == 1 or number % 10 == 0 or number == len(groups):
111
+ print(f"[{number}/{len(groups)}]", flush=True)
112
+ output = Path(args.output_dir)
113
+ output.mkdir(parents=True, exist_ok=True)
114
+ frame = pd.DataFrame(rows)
115
+ frame.to_csv(output / "prior_sources_per_molecule.csv", index=False)
116
+ summary = frame.groupby("source").agg({m: ["mean", "median"] for m in ("mae", "rmse", "pearson", "spearman", "topk_overlap")}).reset_index()
117
+ summary.to_csv(output / "prior_sources_summary.csv", index=False)
118
+ print(summary.to_string(index=False))
119
+
120
+
121
+ if __name__ == "__main__":
122
+ main()
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env python3
2
+ """Compose rendered binding-mode panels into a compact publication figure."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ from pathlib import Path
9
+
10
+ import yaml
11
+ from PIL import Image, ImageDraw, ImageFont
12
+
13
+
14
+ def parse_args() -> argparse.Namespace:
15
+ parser = argparse.ArgumentParser(description=__doc__)
16
+ parser.add_argument("--config", required=True)
17
+ parser.add_argument("--render-dir", default="outputs/binding_mode_figure")
18
+ parser.add_argument("--output", default="outputs/binding_modes")
19
+ return parser.parse_args()
20
+
21
+
22
+ def font(size: int) -> ImageFont.ImageFont:
23
+ for candidate in ("/System/Library/Fonts/Supplemental/Arial.ttf", "/Library/Fonts/Arial.ttf"):
24
+ if Path(candidate).exists():
25
+ return ImageFont.truetype(candidate, size=size)
26
+ return ImageFont.load_default()
27
+
28
+
29
+ def main() -> None:
30
+ args = parse_args()
31
+ config = yaml.safe_load(Path(args.config).read_text())
32
+ systems = [item for item in config.get("systems", []) if item.get("enabled", True)]
33
+ render_dir = Path(args.render_dir)
34
+ rows = []
35
+ for system in systems:
36
+ metadata = render_dir / system["name"] / "panels.json"
37
+ if metadata.exists():
38
+ rows.append((system, json.loads(metadata.read_text())))
39
+ if not rows:
40
+ raise SystemExit("No rendered panels found. Run render_binding_modes.py first.")
41
+ print(f"Composing systems: {[system['name'] for system, _ in rows]}")
42
+ first_image = Image.open(rows[0][1][0]["path"]).convert("RGB")
43
+ panel_w, panel_h = first_image.size
44
+ columns = max(len(panels) for _, panels in rows)
45
+ title = config.get("figure_title", "Representative MANIMOL binding-mode examples")
46
+ summary = config.get("figure_summary", "")
47
+ title_h = 0 if not title else 68
48
+ footer_h = 0 if not summary else 72
49
+ label_h, row_note_h, row_gap, margin = 80, 48, 28, 24
50
+ width = columns * panel_w + 2 * margin
51
+ height = len(rows) * (panel_h + label_h + row_note_h + row_gap) + title_h + footer_h + 2 * margin
52
+ figure = Image.new("RGB", (width, height), "white")
53
+ draw = ImageDraw.Draw(figure)
54
+ title_font, label_font, row_font, summary_font = font(58), font(42), font(44), font(36)
55
+ if title:
56
+ draw.text((margin, 12), title, fill="black", font=title_font)
57
+ y = title_h + margin
58
+ for row_index, (system, panels) in enumerate(rows):
59
+ for column, panel in enumerate(panels):
60
+ image = Image.open(panel["path"]).convert("RGB")
61
+ if image.size != (panel_w, panel_h):
62
+ image = image.resize((panel_w, panel_h), Image.Resampling.LANCZOS)
63
+ x = margin + column * panel_w
64
+ figure.paste(image, (x, y))
65
+ bbox = draw.multiline_textbbox((0, 0), panel["label"], font=label_font, spacing=3, align="center")
66
+ text_x = x + (panel_w - (bbox[2] - bbox[0])) // 2
67
+ draw.multiline_text((text_x, y + panel_h + 5), panel["label"], fill="black", font=label_font, spacing=3, align="center")
68
+ row_label = system.get("panel_label", f"({chr(ord('a') + row_index)})")
69
+ row_title = system.get("case_title", "")
70
+ if row_title:
71
+ row_label = f"{row_label} {row_title}"
72
+ bbox = draw.textbbox((0, 0), row_label, font=row_font)
73
+ draw.text(((width - (bbox[2] - bbox[0])) // 2, y + panel_h + label_h + 3), row_label, fill="black", font=row_font)
74
+ y += panel_h + label_h + row_note_h + row_gap
75
+ if summary:
76
+ bbox = draw.textbbox((0, 0), summary, font=summary_font)
77
+ draw.text(((width - (bbox[2] - bbox[0])) // 2, height - footer_h + 12), summary, fill=(55, 55, 55), font=summary_font)
78
+ output = Path(args.output)
79
+ output.parent.mkdir(parents=True, exist_ok=True)
80
+ figure.save(output.with_suffix(".png"), dpi=(300, 300))
81
+ figure.save(output.with_suffix(".pdf"), resolution=300.0)
82
+ print(f"Saved {output.with_suffix('.png')}")
83
+ print(f"Saved {output.with_suffix('.pdf')}")
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env python3
2
+ """Compose the HIF2A contact-pharmacophore supplementary figure."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+
11
+ os.environ.setdefault("MPLCONFIGDIR", str(Path("tmp/matplotlib").resolve()))
12
+
13
+ import matplotlib as mpl
14
+ import matplotlib.pyplot as plt
15
+ import numpy as np
16
+ import pandas as pd
17
+ from PIL import Image
18
+
19
+
20
+ COLORS = {
21
+ "etkdg": "#D98B45",
22
+ "manimol": "#8B63A4",
23
+ "reference": "#555555",
24
+ "protein": "#C9CED4",
25
+ "hbond": "#4B74C8",
26
+ "hydrophobic": "#D98B45",
27
+ "aromatic": "#8B63A4",
28
+ "electrostatic": "#43A6B6",
29
+ }
30
+
31
+ TYPE_PRIORITY = {"hbond": 0, "electrostatic": 1, "aromatic": 2, "hydrophobic": 3}
32
+
33
+
34
+ def trim_whitespace(image: Image.Image, threshold: int = 248, pad: int = 8) -> Image.Image:
35
+ rgb = image.convert("RGB")
36
+ arr = np.asarray(rgb)
37
+ mask = np.any(arr < threshold, axis=2)
38
+ if not mask.any():
39
+ return image
40
+ ys, xs = np.where(mask)
41
+ left = max(int(xs.min()) - pad, 0)
42
+ right = min(int(xs.max()) + pad, image.width - 1)
43
+ top = max(int(ys.min()) - pad, 0)
44
+ bottom = min(int(ys.max()) + pad, image.height - 1)
45
+ return image.crop((left, top, right + 1, bottom + 1))
46
+
47
+
48
+ def select_major_interactions(interactions: pd.DataFrame, max_edges: int = 5) -> pd.DataFrame:
49
+ pieces = []
50
+ for itype, quota in [("hbond", 2), ("aromatic", 1), ("hydrophobic", 2), ("electrostatic", 1)]:
51
+ pieces.append(interactions[interactions["interaction_type"].eq(itype)].sort_values("ref_distance").head(quota))
52
+ out = pd.concat(pieces, ignore_index=True)
53
+ out["_priority"] = out["interaction_type"].map(TYPE_PRIORITY).fillna(9)
54
+ if len(out) < max_edges:
55
+ used = set(out["interaction_id"]) if "interaction_id" in out else set()
56
+ fill = interactions[~interactions["interaction_id"].isin(used)].assign(_priority=interactions["interaction_type"].map(TYPE_PRIORITY).fillna(9))
57
+ out = pd.concat([out, fill.sort_values(["_priority", "ref_distance"]).head(max_edges - len(out))], ignore_index=True)
58
+ return out.sort_values(["_priority", "ref_distance"]).head(max_edges).reset_index(drop=True)
59
+
60
+
61
+ def select_semantic_interactions(interactions: pd.DataFrame) -> pd.DataFrame:
62
+ """Keep one true, representative contact for each pharmacophore class."""
63
+ selected = []
64
+ for interaction_type in ["hbond", "aromatic", "hydrophobic"]:
65
+ candidates = interactions[interactions["interaction_type"].eq(interaction_type)].sort_values("ref_distance")
66
+ if not candidates.empty:
67
+ selected.append(candidates.iloc[0])
68
+ if not selected:
69
+ return select_major_interactions(interactions, 3)
70
+ return pd.DataFrame(selected).reset_index(drop=True)
71
+
72
+
73
+ def draw_feature_icon(ax, family: str, x: float, y: float, label: str):
74
+ """Ligand pharmacophore glyphs: hexagon, sphere, or donor/acceptor triangle."""
75
+ if family == "aromatic":
76
+ patch = mpl.patches.RegularPolygon((x, y), numVertices=6, radius=0.055, orientation=np.pi / 6,
77
+ facecolor="#EEE5F3", edgecolor=COLORS["aromatic"], lw=0.85)
78
+ elif family == "hydrophobe":
79
+ patch = plt.Circle((x, y), 0.047, facecolor="#F8E5CE", edgecolor=COLORS["hydrophobic"], lw=0.85)
80
+ else:
81
+ color = "#B84A53" if family == "acceptor" else "#4B74C8"
82
+ patch = mpl.patches.RegularPolygon((x, y), numVertices=3, radius=0.058,
83
+ orientation=np.pi if family == "acceptor" else 0,
84
+ facecolor="#F6E8EA" if family == "acceptor" else "#E7EDF9",
85
+ edgecolor=color, lw=0.85)
86
+ ax.add_patch(patch)
87
+ ax.text(x, y, label, fontsize=5.5, ha="center", va="center", color="#333", zorder=4)
88
+
89
+
90
+ def draw_bipartite_graph(ax, interactions: pd.DataFrame):
91
+ ax.set_title("b Protein-contact-aware functional geometry", loc="left", fontsize=8.2, weight="semibold")
92
+ chosen = select_semantic_interactions(interactions)
93
+ family_label = {"acceptor": "HBA", "donor": "HBD", "hydrophobe": "HYD", "aromatic": "ARO", "positive": "+", "negative": "−"}
94
+ interaction_label = {"hbond": "H bond", "aromatic": "π–π", "hydrophobic": "Hydrophobic", "electrostatic": "Polar"}
95
+ xs = np.linspace(0.20, 0.80, len(chosen)) if len(chosen) else []
96
+
97
+ for x, (_, row) in zip(xs, chosen.iterrows()):
98
+ color = COLORS.get(str(row["interaction_type"]), "#777777")
99
+ # Protein residue -> interaction type -> ligand feature. The vertical
100
+ # arrangement makes it explicit that residues define the environment.
101
+ ax.add_patch(
102
+ mpl.patches.FancyBboxPatch(
103
+ (x - 0.075, 0.78), 0.15, 0.085, boxstyle="round,pad=0.008,rounding_size=0.018",
104
+ facecolor="#F0F2F4", edgecolor="#A7B0B8", lw=0.75,
105
+ )
106
+ )
107
+ ax.text(x, 0.822, str(row["protein_label"]), fontsize=6.4, ha="center", va="center", color="#42484E")
108
+ ax.plot([x, x], [0.775, 0.615], color="#B5BCC3", lw=0.65, zorder=1)
109
+ ax.text(x, 0.682, interaction_label.get(str(row["interaction_type"]), str(row["interaction_type"])),
110
+ fontsize=5.7, ha="center", va="center", color=color)
111
+ ax.plot([x, x], [0.648, 0.615], color=color, lw=1.0, zorder=2)
112
+ draw_feature_icon(ax, str(row["ligand_family"]), x, 0.52, family_label.get(str(row["ligand_family"]), "PH"))
113
+
114
+ ax.text(0.50, 0.945, "Protein residues", fontsize=6.3, ha="center", color="#555")
115
+ ax.text(0.50, 0.385, "Ligand pharmacophore features", fontsize=6.3, ha="center", color="#555")
116
+ # Compact legend in the upper right, retaining interaction-type semantics.
117
+ legend = [("H bond", "hbond"), ("π–π", "aromatic"), ("Hydrophobic", "hydrophobic")]
118
+ for i, (label, key) in enumerate(legend):
119
+ y = 0.975 - 0.06 * i
120
+ ax.plot([0.83, 0.88], [y, y], color=COLORS[key], lw=1.0)
121
+ ax.text(0.895, y, label, fontsize=5.1, va="center", color="#555")
122
+ ax.set_xlim(0.05, 0.98)
123
+ ax.set_ylim(0.30, 1.01)
124
+ ax.set_axis_off()
125
+
126
+
127
+ def draw_ensemble_metrics(ax, ensemble: pd.DataFrame):
128
+ ax.set_title("d Functional-geometry preservation metrics", loc="left", fontsize=8.5, weight="semibold")
129
+ max_k = int(ensemble["K"].max())
130
+ at_max = ensemble[ensemble["K"].eq(max_k)]
131
+ pairs = []
132
+ for ligand_id, group in at_max.groupby("ligand_id"):
133
+ if {"etkdg", "manimol"}.issubset(set(group["method"])):
134
+ pairs.append(ligand_id)
135
+
136
+ paired_metrics = [
137
+ ("ensemble_pharmacophore_coverage", f"EPC@{max_k} ↑", "score"),
138
+ ("functional_state_coverage", f"Functional-state coverage@{max_k} ↑", "score"),
139
+ ]
140
+ for i, (metric, label, unit) in enumerate(paired_metrics):
141
+ x0 = 0.035 if i == 0 else 0.690
142
+ iax = ax.inset_axes([x0, 0.18, 0.255, 0.58])
143
+ for ligand_id in pairs:
144
+ e = at_max[(at_max["ligand_id"].eq(ligand_id)) & (at_max["method"].eq("etkdg"))][metric].iloc[0]
145
+ m = at_max[(at_max["ligand_id"].eq(ligand_id)) & (at_max["method"].eq("manimol"))][metric].iloc[0]
146
+ iax.plot([0, 1], [e, m], color="#C8C8C8", lw=0.45, alpha=0.55, zorder=1)
147
+ for x, method in enumerate(["etkdg", "manimol"]):
148
+ vals = at_max[at_max["method"].eq(method)][metric].dropna().to_numpy(float)
149
+ iax.scatter(np.full(len(vals), x), vals, s=14, color=COLORS[method], alpha=0.70, edgecolor="white", linewidth=0.25, zorder=2)
150
+ iax.hlines(np.median(vals), x - 0.18, x + 0.18, color="#333333", lw=1.0, zorder=3)
151
+ iax.set_xlim(-0.35, 1.35)
152
+ iax.set_xticks([0, 1])
153
+ iax.set_xticklabels([])
154
+ iax.set_title(label, fontsize=7.0, pad=2)
155
+ iax.set_ylabel(unit if i == 0 else "", fontsize=6.2)
156
+ iax.set_ylim(0.0, 1.05)
157
+ iax.grid(axis="y", color="#ECECEC", linewidth=0.45)
158
+ iax.tick_params(axis="y", labelsize=6, width=0.55, length=2.5)
159
+ iax.spines["top"].set_visible(False)
160
+ iax.spines["right"].set_visible(False)
161
+ iax = ax.inset_axes([0.365, 0.18, 0.270, 0.58])
162
+ for method in ["etkdg", "manimol"]:
163
+ curve = (
164
+ ensemble[ensemble["method"].eq(method)]
165
+ .groupby("K", sort=True)["topk_functional_recovery"]
166
+ .mean()
167
+ )
168
+ iax.plot(curve.index, curve.values, marker="o", markersize=3.4, lw=1.25, color=COLORS[method], label=method.upper() if method == "etkdg" else "MANIMOL")
169
+ iax.set_title("Top-K functional recovery ↑", fontsize=7.0, pad=2)
170
+ iax.set_xlabel("K", fontsize=6.2, labelpad=1)
171
+ iax.set_ylabel("fraction", fontsize=6.2)
172
+ iax.set_ylim(0.0, 1.05)
173
+ iax.set_xticks(sorted(ensemble["K"].unique()))
174
+ iax.grid(axis="y", color="#ECECEC", linewidth=0.45)
175
+ iax.tick_params(axis="both", labelsize=6, width=0.55, length=2.5)
176
+ iax.spines["top"].set_visible(False)
177
+ iax.spines["right"].set_visible(False)
178
+ iax.legend(loc="lower right", fontsize=5.7, frameon=False, handlelength=1.2, borderpad=0.1)
179
+ ax.set_axis_off()
180
+
181
+
182
+ def main():
183
+ parser = argparse.ArgumentParser(description="Compose HIF2A contact pharmacophore supplementary figure.")
184
+ parser.add_argument("--reference_panel", default="", help="Optional fixed reference panel; defaults to the selected low-budget case.")
185
+ parser.add_argument("--pocket_comparison", default="", help="Optional fixed comparison panel; defaults to the selected low-budget case.")
186
+ parser.add_argument("--case_config", default="outputs/docking/hif2a_contact_pharmacophore/pymol/selected_lowbudget_functional_case.json")
187
+ parser.add_argument("--best_csv", default="outputs/docking/hif2a_contact_pharmacophore/hif2a_contact_pharmacophore_best_per_ligand.csv")
188
+ parser.add_argument("--ensemble_csv", default="outputs/docking/hif2a_contact_pharmacophore/hif2a_contact_pharmacophore_ensemble_per_ligand.csv")
189
+ parser.add_argument("--reference_interactions_csv", default="outputs/docking/hif2a_contact_pharmacophore/hif2a_reference_contact_pharmacophore.csv")
190
+ parser.add_argument("--ligand_id", default="", help="Optional fixed ligand; empty follows the selected-case configuration.")
191
+ parser.add_argument("--output_prefix", default="outputs/docking/hif2a_contact_pharmacophore/hif2a_contact_pharmacophore_suppfig")
192
+ args, _ = parser.parse_known_args()
193
+
194
+ mpl.rcParams.update(
195
+ {
196
+ "font.family": "sans-serif",
197
+ "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"],
198
+ "svg.fonttype": "none",
199
+ "pdf.fonttype": 42,
200
+ "font.size": 7,
201
+ }
202
+ )
203
+ best = pd.read_csv(args.best_csv)
204
+ ensemble = pd.read_csv(args.ensemble_csv)
205
+ ref = pd.read_csv(args.reference_interactions_csv)
206
+ case_config = json.loads(Path(args.case_config).read_text()) if Path(args.case_config).exists() else {}
207
+ ligand_id = args.ligand_id or case_config.get("ligand_id", "hif2a_lig019")
208
+ reference_panel = args.reference_panel or str((case_config.get("panels") or [""])[0])
209
+ pocket_comparison = args.pocket_comparison or str(case_config.get("comparison_panel", ""))
210
+ if not reference_panel or not Path(reference_panel).exists():
211
+ raise FileNotFoundError("Reference panel is required; run render_hif2a_contact_pharmacophore_pymol.py first.")
212
+ if not pocket_comparison or not Path(pocket_comparison).exists():
213
+ raise FileNotFoundError("Pocket comparison is required; run render_hif2a_contact_pharmacophore_pymol.py first.")
214
+ ref_lig = ref[ref["ligand_id"].eq(ligand_id)]
215
+
216
+ fig = plt.figure(figsize=(7.2, 5.20), dpi=300)
217
+ gs = fig.add_gridspec(3, 2, height_ratios=[0.92, 1.34, 0.59], hspace=0.075, wspace=0.075)
218
+
219
+ ax_a = fig.add_subplot(gs[0, 0])
220
+ ax_a.imshow(trim_whitespace(Image.open(reference_panel), threshold=252, pad=3))
221
+ ax_a.set_axis_off()
222
+ ax_a.set_title("a Reference contacts", loc="left", fontsize=8.2, weight="semibold")
223
+ ax_a.legend(
224
+ handles=[
225
+ mpl.lines.Line2D([0], [0], color=COLORS["hbond"], lw=1.1, label="H bond"),
226
+ mpl.lines.Line2D([0], [0], color=COLORS["aromatic"], lw=1.1, label="π–π"),
227
+ mpl.lines.Line2D([0], [0], color=COLORS["hydrophobic"], lw=1.1, label="Hydrophobic"),
228
+ ],
229
+ loc="lower right", frameon=False, fontsize=5.2, handlelength=1.2, borderpad=0.1, labelspacing=0.25,
230
+ )
231
+
232
+ ax_b = fig.add_subplot(gs[0, 1])
233
+ draw_bipartite_graph(ax_b, ref_lig)
234
+
235
+ ax_c = fig.add_subplot(gs[1, :])
236
+ ax_c.imshow(trim_whitespace(Image.open(pocket_comparison), threshold=252, pad=3))
237
+ ax_c.set_axis_off()
238
+ ax_c.set_title("c Pocket comparison", loc="left", fontsize=8.2, weight="semibold", pad=2)
239
+
240
+ ax_d = fig.add_subplot(gs[2, :])
241
+ draw_ensemble_metrics(ax_d, ensemble)
242
+
243
+ fig.subplots_adjust(left=0.012, right=0.994, top=0.980, bottom=0.025)
244
+ out = Path(args.output_prefix)
245
+ out.parent.mkdir(parents=True, exist_ok=True)
246
+ fig.savefig(out.with_suffix(".png"), bbox_inches="tight", dpi=600)
247
+ fig.savefig(out.with_suffix(".pdf"), bbox_inches="tight")
248
+ fig.savefig(out.with_suffix(".svg"), bbox_inches="tight")
249
+ print(f"Saved: {out.with_suffix('.png')}")
250
+ print(f"Saved: {out.with_suffix('.pdf')}")
251
+ print(f"Saved: {out.with_suffix('.svg')}")
252
+
253
+
254
+ if __name__ == "__main__":
255
+ main()