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.
- args_parse.py +593 -0
- candidate_corrector.py +161 -0
- candidate_scorer.py +359 -0
- conformend/__init__.py +36 -0
- conformend/refiner.py +25 -0
- dataset/__init__.py +1 -0
- dataset/drugdataset.py +644 -0
- dataset/manifold.py +237 -0
- dataset/sharded_drugdataset.py +124 -0
- dataset/smiles2graph.py +217 -0
- dualmapref/__init__.py +24 -0
- dualmapref/refiner.py +16 -0
- dualmapref-0.2.8.dist-info/LICENSE +21 -0
- dualmapref-0.2.8.dist-info/METADATA +167 -0
- dualmapref-0.2.8.dist-info/RECORD +186 -0
- dualmapref-0.2.8.dist-info/WHEEL +5 -0
- dualmapref-0.2.8.dist-info/entry_points.txt +10 -0
- dualmapref-0.2.8.dist-info/top_level.txt +29 -0
- exputils.py +289 -0
- infer.py +23 -0
- infer_base_conformers.py +5589 -0
- infer_mean_dispersion_torsion.py +1117 -0
- infer_torsion.py +752 -0
- infer_torsional_denoiser.py +1021 -0
- manimol/__init__.py +30 -0
- manimol/__main__.py +6 -0
- manimol/cli.py +36 -0
- manimol/full_cli.py +41 -0
- manimol/legacy_imports.py +43 -0
- manimol/manifest.py +56 -0
- manimol/postprocess.py +148 -0
- manimol/priors.py +60 -0
- manimol/protocols.py +119 -0
- manimol/refiner.py +645 -0
- manimol/runtime.py +194 -0
- manimol/selection.py +85 -0
- manimol/torsion.py +22 -0
- manimol/train_cli.py +14 -0
- mixture_flow/src/__init__.py +1 -0
- mixture_flow/src/_path.py +7 -0
- mixture_flow/src/infer28_mixture_torsion_flow.py +1093 -0
- mixture_flow/src/mixture_torsion_flow.py +291 -0
- mixture_flow/src/summarize_mixture_debug.py +80 -0
- mixture_flow/src/train28_mixture_torsion_flow.py +583 -0
- mixture_torsion_flow.py +7 -0
- models/ manifold_learning.py +86 -0
- models/__init__.py +8 -0
- models/dist.py +273 -0
- models/dist2coords.py +23 -0
- models/egnn.py +107 -0
- models/experimental_backbones.py +364 -0
- models/gnnconv.py +512 -0
- models/kernel_inversion.py +141 -0
- models/kernels.py +427 -0
- models/losses.py +154 -0
- models/mean_dispersion_bridge.py +119 -0
- models/mean_dispersion_torsion_context.py +155 -0
- models/model.py +73 -0
- models/model0.py +2375 -0
- models/vis.py +128 -0
- pgraph_controls.py +107 -0
- scripts/__init__.py +2 -0
- scripts/analyze_basin_alignment.py +63 -0
- scripts/analyze_hif2a_conformer_aggregation.py +267 -0
- scripts/analyze_hif2a_contact_pharmacophore.py +1111 -0
- scripts/analyze_hif2a_fixed_budget.py +202 -0
- scripts/analyze_hif2a_pharmacophore.py +405 -0
- scripts/analyze_hif2a_pharmacophore_match_metric.py +386 -0
- scripts/analyze_p_control_candidate_flow.py +154 -0
- scripts/analyze_scaffold_basin.py +83 -0
- scripts/audit_dispersion_proposals.py +208 -0
- scripts/audit_etflow_protocol.py +258 -0
- scripts/audit_external_overlap.py +150 -0
- scripts/audit_oldbest_fulltrainval_split.py +82 -0
- scripts/audit_pdbbind_contact_pharmacophores.py +146 -0
- scripts/audit_qm9_geomol_test_split.py +94 -0
- scripts/audit_stage1_stage2_cross.py +131 -0
- scripts/build_geom_drugs_lowref_diagnostic.py +84 -0
- scripts/build_qm9_backfill_manifest.py +99 -0
- scripts/check_etflow_runtime.py +56 -0
- scripts/compare_prior_sources.py +122 -0
- scripts/compose_binding_mode_figure.py +87 -0
- scripts/compose_hif2a_contact_pharmacophore_suppfig.py +255 -0
- scripts/compose_hif2a_functional_geometry_pipeline.py +266 -0
- scripts/compose_manimol_internal_architecture.py +291 -0
- scripts/diagnose_flow_basin_intervention.py +54 -0
- scripts/diagnose_hif2a_pharmacophore_budget.py +185 -0
- scripts/diagnose_route2_p_ranking.py +123 -0
- scripts/discover_binding_mode_inputs.py +30 -0
- scripts/evaluate_functional_prior_stage1.py +230 -0
- scripts/evaluate_geomanimol.py +74 -0
- scripts/evaluate_geomanimol_flow.py +23 -0
- scripts/evaluate_geomanimol_multiscaffold.py +46 -0
- scripts/evaluate_geomanimol_residual.py +45 -0
- scripts/evaluate_geomanimol_torsion.py +40 -0
- scripts/evaluate_hif2a_bioactive_enrichment.py +91 -0
- scripts/evaluate_hif2a_pms_suite.py +440 -0
- scripts/evaluate_pdbbind_contact_pms.py +155 -0
- scripts/evaluate_platinum_external.py +114 -0
- scripts/evaluate_platinum_pool.py +82 -0
- scripts/evaluate_route2_calibrated_p.py +104 -0
- scripts/evaluate_route2_library_components.py +596 -0
- scripts/evaluate_route2_p_basin_budget.py +288 -0
- scripts/evaluate_stage1_checkpoint_only.py +30 -0
- scripts/export_dispersion_bond_audit.py +136 -0
- scripts/export_top20_shards.py +207 -0
- scripts/external_validation_metrics.py +152 -0
- scripts/fit_topology_prior.py +117 -0
- scripts/frozen_dispersion_audit.py +281 -0
- scripts/geomanimol_debug.py +50 -0
- scripts/geomanimol_smoke.py +37 -0
- scripts/infer_etflow_matched.py +524 -0
- scripts/inspect_checkpoint.py +12 -0
- scripts/inspect_conformer_capacity.py +71 -0
- scripts/inspect_pool.py +12 -0
- scripts/make_figure3_selection_loss.py +474 -0
- scripts/make_figure3_selection_summary.py +275 -0
- scripts/make_geom_debug_subset.py +62 -0
- scripts/make_low_reference_test_subset.py +70 -0
- scripts/merge_stage1_into_stage2.py +82 -0
- scripts/place_hif2a_candidates_for_evaluation.py +66 -0
- scripts/plot_hif2a_low_budget_efficiency.py +100 -0
- scripts/plot_prior_validation.py +48 -0
- scripts/precompute_stage2_assignments.py +90 -0
- scripts/prepare_bace_activity.py +98 -0
- scripts/prepare_bace_etkdg_benchmark.py +90 -0
- scripts/prepare_figure5_4x4_cases.py +470 -0
- scripts/prepare_geom_drugs_geomol_top20.py +472 -0
- scripts/prepare_pdbbind_core_raw.py +90 -0
- scripts/prepare_platinum_raw.py +74 -0
- scripts/prepare_pubchem_etkdg.py +54 -0
- scripts/rebuild_hif2a_final_sdf_and_metrics.py +55 -0
- scripts/rebuild_hif2a_fixed_pool_sweep.py +175 -0
- scripts/rebuild_hif2a_strict.py +220 -0
- scripts/recompute_hif2a_bootstrap.py +63 -0
- scripts/reference_free_geometry.py +112 -0
- scripts/render_binding_modes.py +413 -0
- scripts/render_figure5_4x4.py +330 -0
- scripts/render_figure6_pharmacophore_pymol.py +162 -0
- scripts/render_hif2a_contact_pharmacophore_pymol.py +414 -0
- scripts/render_hif2a_figure11.py +397 -0
- scripts/run_bace_2d_baseline.py +73 -0
- scripts/run_drugs_validation_matrix.py +225 -0
- scripts/run_external_reference_free.py +53 -0
- scripts/run_manimol_finalk_sensitivity.py +106 -0
- scripts/run_manimol_oversampling_sensitivity.py +109 -0
- scripts/run_pdisp_matched_intervention.py +116 -0
- scripts/run_stage1_stage2_cross20.py +83 -0
- scripts/score_hif2a_candidates_with_pgraph.py +221 -0
- scripts/summarize_dispersion_intervention.py +88 -0
- scripts/test_mean_dispersion_bridge.py +50 -0
- scripts/train_dispersion_head_diagnostic.py +320 -0
- scripts/train_dispersion_head_streaming.py +519 -0
- scripts/train_geomanimol.py +100 -0
- scripts/train_geomanimol_flow.py +26 -0
- scripts/train_geomanimol_residual.py +70 -0
- scripts/train_geomanimol_torsion.py +50 -0
- scripts/train_quantile_representation_diagnostic.py +204 -0
- scripts/validate_mean_dispersion_prior.py +173 -0
- scripts/validate_packed_shard.py +41 -0
- scripts/validate_stage1_prior.py +221 -0
- scripts/validate_top20_shards.py +36 -0
- scripts/validation/__init__.py +1 -0
- scripts/validation/hif2a_downstream_baselines.py +105 -0
- scripts/validation/hif2a_pairwise_ranker.py +218 -0
- scripts/verify_binding_mode_figure.py +47 -0
- torsion_manifold.py +281 -0
- train.py +78 -0
- train_graph_encoder.py +206 -0
- train_local_torsion_corrector.py +511 -0
- train_mean_dispersion_torsion_prior.py +329 -0
- train_probability_basin.py +235 -0
- train_torsion_generator.py +1631 -0
- train_torsion_manifold_prior.py +258 -0
- train_torsional_denoiser.py +415 -0
- trainer.py +1038 -0
- utils/__init__.py +7 -0
- utils/checkpoint.py +40 -0
- utils/device.py +17 -0
- utils/helpers.py +98 -0
- utils/kabsch.py +29 -0
- utils/lookup_table.py +164 -0
- utils/metrics.py +50 -0
- utils/optuna.py +111 -0
- utils/save_mol.py +366 -0
- utils/util.py +36 -0
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Render a fixed HIF2A pocket pharmacophore case with PyMOL.
|
|
3
|
+
|
|
4
|
+
This script deliberately does not select a favorable ligand. The ligand id and
|
|
5
|
+
candidate files are read from the pharmacophore analysis outputs so the figure
|
|
6
|
+
is traceable to the quantitative table.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import math
|
|
14
|
+
import os
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import pandas as pd
|
|
18
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
19
|
+
import matplotlib as mpl
|
|
20
|
+
import matplotlib.pyplot as plt
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
COLORS = {
|
|
24
|
+
"reference": "manimol_ref_gray",
|
|
25
|
+
"etkdg": "manimol_etkdg_orange",
|
|
26
|
+
"manimol": "manimol_purple",
|
|
27
|
+
"protein": "manimol_protein_gray",
|
|
28
|
+
"pocket": "manimol_pocket_gray",
|
|
29
|
+
"hbond": "manimol_hbond_blue",
|
|
30
|
+
"hydrophobic": "manimol_hydrophobic_orange",
|
|
31
|
+
"aromatic": "manimol_aromatic_purple",
|
|
32
|
+
"electrostatic": "manimol_polar_cyan",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def read_coord(row, prefix: str) -> list[float]:
|
|
37
|
+
return [float(row[f"{prefix}_x"]), float(row[f"{prefix}_y"]), float(row[f"{prefix}_z"])]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def short_distance(value: float) -> str:
|
|
41
|
+
if value is None or (isinstance(value, float) and math.isnan(value)):
|
|
42
|
+
return ""
|
|
43
|
+
return f"{value:.1f} Å"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def major_interactions(df: pd.DataFrame, max_edges: int) -> pd.DataFrame:
|
|
47
|
+
priority = {"hbond": 0, "electrostatic": 1, "aromatic": 2, "hydrophobic": 3}
|
|
48
|
+
pieces = []
|
|
49
|
+
for itype, quota in [("hbond", 2), ("aromatic", 1), ("hydrophobic", 2), ("electrostatic", 1)]:
|
|
50
|
+
pieces.append(df[df["interaction_type"].eq(itype)].sort_values("ref_distance").head(quota))
|
|
51
|
+
out = pd.concat(pieces, ignore_index=True)
|
|
52
|
+
out["_priority"] = out["interaction_type"].map(priority).fillna(9)
|
|
53
|
+
if len(out) < max_edges:
|
|
54
|
+
used = set(out["interaction_id"]) if "interaction_id" in out else set()
|
|
55
|
+
fill = df[~df["interaction_id"].isin(used)].assign(_priority=df["interaction_type"].map(priority).fillna(9))
|
|
56
|
+
out = pd.concat([out, fill.sort_values(["_priority", "ref_distance"]).head(max_edges - len(out))], ignore_index=True)
|
|
57
|
+
return out.sort_values(["_priority", "ref_distance"]).head(max_edges).reset_index(drop=True)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def residue_selection(interactions: pd.DataFrame) -> str:
|
|
61
|
+
parts = []
|
|
62
|
+
for residue in interactions["protein_residue"].dropna().unique():
|
|
63
|
+
# Stored as HIS293:A, ASN341:A, HOH502:A, ...
|
|
64
|
+
if ":" in residue:
|
|
65
|
+
left, chain = residue.split(":", 1)
|
|
66
|
+
else:
|
|
67
|
+
left, chain = residue, ""
|
|
68
|
+
digits = "".join(ch for ch in left if ch.isdigit())
|
|
69
|
+
if not digits:
|
|
70
|
+
continue
|
|
71
|
+
if chain and chain != "_":
|
|
72
|
+
parts.append(f"(chain {chain} and resi {digits})")
|
|
73
|
+
else:
|
|
74
|
+
parts.append(f"(resi {digits})")
|
|
75
|
+
return " or ".join(parts) if parts else "none"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def launch_pymol():
|
|
79
|
+
import pymol
|
|
80
|
+
|
|
81
|
+
pymol.finish_launching(["pymol", "-cq"])
|
|
82
|
+
from pymol import cmd
|
|
83
|
+
|
|
84
|
+
return cmd
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def define_colors(cmd):
|
|
88
|
+
cmd.set_color("manimol_ref_gray", [0.36, 0.36, 0.36])
|
|
89
|
+
cmd.set_color("manimol_etkdg_orange", [0.85, 0.47, 0.20])
|
|
90
|
+
cmd.set_color("manimol_purple", [0.52, 0.34, 0.62])
|
|
91
|
+
cmd.set_color("manimol_protein_gray", [0.82, 0.84, 0.87])
|
|
92
|
+
cmd.set_color("manimol_pocket_gray", [0.62, 0.66, 0.70])
|
|
93
|
+
cmd.set_color("manimol_surface_gray", [0.86, 0.88, 0.90])
|
|
94
|
+
cmd.set_color("manimol_pocket_sticks", [0.54, 0.58, 0.63])
|
|
95
|
+
cmd.set_color("manimol_key_residues", [0.40, 0.44, 0.49])
|
|
96
|
+
cmd.set_color("manimol_hbond_blue", [0.29, 0.45, 0.78])
|
|
97
|
+
cmd.set_color("manimol_hydrophobic_orange", [0.85, 0.55, 0.27])
|
|
98
|
+
cmd.set_color("manimol_aromatic_purple", [0.55, 0.39, 0.67])
|
|
99
|
+
cmd.set_color("manimol_polar_cyan", [0.26, 0.65, 0.71])
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def setup_scene(cmd, receptor: Path, reference: Path, generated: Path | None, method: str,
|
|
103
|
+
interactions: pd.DataFrame, ligand_only: bool = False, master_view=None,
|
|
104
|
+
pocket_residue_output: Path | None = None):
|
|
105
|
+
cmd.reinitialize()
|
|
106
|
+
define_colors(cmd)
|
|
107
|
+
cmd.bg_color("white")
|
|
108
|
+
cmd.set("orthoscopic", 1)
|
|
109
|
+
cmd.set("ray_opaque_background", 0)
|
|
110
|
+
cmd.set("antialias", 2)
|
|
111
|
+
cmd.set("depth_cue", 0)
|
|
112
|
+
cmd.set("specular", 0.25)
|
|
113
|
+
cmd.set("ambient", 0.50)
|
|
114
|
+
cmd.set("stick_radius", 0.17)
|
|
115
|
+
cmd.load(str(receptor), "receptor")
|
|
116
|
+
# Keep the protein scaffold and the validated W502 contact water only;
|
|
117
|
+
# crystallographic salts/ligands and unrelated solvent otherwise clutter
|
|
118
|
+
# the pocket crop.
|
|
119
|
+
cmd.remove("receptor and not polymer.protein and not (resn HOH and resi 502)")
|
|
120
|
+
cmd.load(str(reference), "ref")
|
|
121
|
+
if generated is not None:
|
|
122
|
+
cmd.load(str(generated), method)
|
|
123
|
+
|
|
124
|
+
cmd.hide("everything")
|
|
125
|
+
cmd.select("ligands", "ref" if generated is None else f"ref or {method}")
|
|
126
|
+
if not ligand_only:
|
|
127
|
+
cmd.show("cartoon", "receptor")
|
|
128
|
+
cmd.color(COLORS["protein"], "receptor")
|
|
129
|
+
cmd.set("cartoon_transparency", 0.93, "receptor")
|
|
130
|
+
# Define the pocket once from the crystallographic ligand. The same
|
|
131
|
+
# residue set is reused for every rendered ligand conformation.
|
|
132
|
+
cmd.select("pocket_residues", "byres (receptor within 5.0 of ref)")
|
|
133
|
+
if pocket_residue_output is not None:
|
|
134
|
+
residue_rows = []
|
|
135
|
+
cmd.iterate("pocket_residues and name CA", "residue_rows.append((chain, resn, resi))",
|
|
136
|
+
space={"residue_rows": residue_rows})
|
|
137
|
+
residue_rows = sorted(set(residue_rows))
|
|
138
|
+
pocket_residue_output.parent.mkdir(parents=True, exist_ok=True)
|
|
139
|
+
pocket_residue_output.write_text(
|
|
140
|
+
"Crystal-defined HIF2A pocket residues (byres receptor within 5.0 Å of crystal ligand)\n"
|
|
141
|
+
+ "\n".join(f"{chain}:{resn}{resi}" for chain, resn, resi in residue_rows)
|
|
142
|
+
+ "\n",
|
|
143
|
+
encoding="utf-8",
|
|
144
|
+
)
|
|
145
|
+
cmd.select("pocket_surface", "pocket_residues")
|
|
146
|
+
# Keep the cavity readable through the fixed pocket-residue sticks and
|
|
147
|
+
# subdued receptor cartoon. Ray-traced mesh/surface rendering can
|
|
148
|
+
# create distracting internal shadows for this receptor crop.
|
|
149
|
+
cmd.hide("everything", "pocket_surface")
|
|
150
|
+
key_residues = residue_selection(interactions)
|
|
151
|
+
cmd.select("pocket_sticks", "pocket_residues")
|
|
152
|
+
# Keep non-key pocket residues in the faint cartoon context; only the
|
|
153
|
+
# interaction-supported residues receive explicit sticks.
|
|
154
|
+
cmd.hide("sticks", "pocket_sticks")
|
|
155
|
+
cmd.select("key_residues", f"receptor and ({key_residues})")
|
|
156
|
+
cmd.show("sticks", "key_residues")
|
|
157
|
+
cmd.color("manimol_key_residues", "key_residues and elem C")
|
|
158
|
+
cmd.set("stick_radius", 0.135, "key_residues")
|
|
159
|
+
else:
|
|
160
|
+
# Remove the receptor object entirely so the lower functional-geometry
|
|
161
|
+
# panels cannot inherit hidden cartoon/surface pixels from the pocket view.
|
|
162
|
+
cmd.delete("receptor")
|
|
163
|
+
|
|
164
|
+
cmd.show("sticks", "ref")
|
|
165
|
+
cmd.color(COLORS["reference"], "ref and elem C")
|
|
166
|
+
cmd.set("stick_radius", 0.19, "ref")
|
|
167
|
+
if generated is not None:
|
|
168
|
+
cmd.show("sticks", method)
|
|
169
|
+
cmd.color(COLORS[method], f"{method} and elem C")
|
|
170
|
+
cmd.set("stick_radius", 0.21, method)
|
|
171
|
+
|
|
172
|
+
if ligand_only:
|
|
173
|
+
element_target = "ref" if generated is None else f"ref or {method}"
|
|
174
|
+
else:
|
|
175
|
+
element_target = "ref or key_residues" if generated is None else f"ref or {method} or key_residues"
|
|
176
|
+
cmd.color("red", f"({element_target}) and elem O")
|
|
177
|
+
cmd.color("blue", f"({element_target}) and elem N")
|
|
178
|
+
cmd.color("yellow", f"({element_target}) and elem S")
|
|
179
|
+
cmd.color("green", f"({element_target}) and elem Cl")
|
|
180
|
+
cmd.color("cyan", f"({element_target}) and elem F")
|
|
181
|
+
if not ligand_only:
|
|
182
|
+
cmd.color("manimol_surface_gray", "pocket_surface")
|
|
183
|
+
|
|
184
|
+
if master_view is None:
|
|
185
|
+
cmd.zoom("ligands", buffer=1.05 if ligand_only else 1.55)
|
|
186
|
+
cmd.orient("ligands")
|
|
187
|
+
else:
|
|
188
|
+
cmd.set_view(master_view)
|
|
189
|
+
|
|
190
|
+
for i, (_, row) in enumerate(interactions.iterrows(), start=1):
|
|
191
|
+
prot_obj = f"prot_{i}"
|
|
192
|
+
lig_obj = f"feat_{i}"
|
|
193
|
+
residue_text = str(row.get("protein_residue", ""))
|
|
194
|
+
label_text = "W502" if "502" in residue_text else ""
|
|
195
|
+
cmd.pseudoatom(prot_obj, pos=read_coord(row, "protein"), label=label_text)
|
|
196
|
+
cmd.pseudoatom(lig_obj, pos=read_coord(row, "ligand"), label="")
|
|
197
|
+
dist_name = f"contact_{i}"
|
|
198
|
+
cmd.distance(dist_name, prot_obj, lig_obj)
|
|
199
|
+
color = COLORS.get(str(row["interaction_type"]), "gray45")
|
|
200
|
+
cmd.color(color, dist_name)
|
|
201
|
+
cmd.set("dash_radius", 0.045, dist_name)
|
|
202
|
+
cmd.set("dash_gap", 0.32, dist_name)
|
|
203
|
+
cmd.hide("labels", dist_name)
|
|
204
|
+
cmd.set("label_size", 22)
|
|
205
|
+
cmd.set("label_color", "gray25")
|
|
206
|
+
cmd.set("label_position", [1.0, 1.0, 0.0], prot_obj)
|
|
207
|
+
cmd.hide("spheres", prot_obj)
|
|
208
|
+
marker_color = {
|
|
209
|
+
"aromatic": COLORS["aromatic"],
|
|
210
|
+
"hydrophobe": COLORS["hydrophobic"],
|
|
211
|
+
"acceptor": "red",
|
|
212
|
+
"donor": COLORS["hbond"],
|
|
213
|
+
}.get(str(row["ligand_family"]), COLORS["electrostatic"])
|
|
214
|
+
cmd.show("spheres", lig_obj)
|
|
215
|
+
cmd.color(marker_color, lig_obj)
|
|
216
|
+
cmd.set("sphere_scale", 0.22, lig_obj)
|
|
217
|
+
cmd.set("sphere_transparency", 0.35, lig_obj)
|
|
218
|
+
# Keep the pocket annotation unambiguous: W502 is labeled once, while
|
|
219
|
+
# the distance is left to the caption rather than overlaid on atoms.
|
|
220
|
+
|
|
221
|
+
if not ligand_only:
|
|
222
|
+
cmd.label("key_residues and name CA", "")
|
|
223
|
+
cmd.set("label_size", 22)
|
|
224
|
+
cmd.set("label_color", "gray30")
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def render_panel(cmd, out_png: Path, width: int, height: int):
|
|
228
|
+
out_png.parent.mkdir(parents=True, exist_ok=True)
|
|
229
|
+
cmd.png(str(out_png), width=width, height=height, dpi=300, ray=1)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def font(size: int, bold: bool = False):
|
|
233
|
+
candidates = [
|
|
234
|
+
"/System/Library/Fonts/Helvetica.ttc",
|
|
235
|
+
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
|
236
|
+
"/Library/Fonts/Arial.ttf",
|
|
237
|
+
]
|
|
238
|
+
for path in candidates:
|
|
239
|
+
if Path(path).exists():
|
|
240
|
+
try:
|
|
241
|
+
return ImageFont.truetype(path, size=size, index=1 if bold and path.endswith(".ttc") else 0)
|
|
242
|
+
except Exception:
|
|
243
|
+
continue
|
|
244
|
+
return ImageFont.load_default()
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def compose_panels(panel_paths: list[Path], labels: list[str], metrics: list[str], output_prefix: Path):
|
|
248
|
+
mpl.rcParams.update(
|
|
249
|
+
{
|
|
250
|
+
"font.family": "sans-serif",
|
|
251
|
+
"font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"],
|
|
252
|
+
"svg.fonttype": "none",
|
|
253
|
+
"pdf.fonttype": 42,
|
|
254
|
+
"font.size": 7,
|
|
255
|
+
}
|
|
256
|
+
)
|
|
257
|
+
imgs = [Image.open(p).convert("RGBA") for p in panel_paths]
|
|
258
|
+
fig, axes = plt.subplots(1, len(imgs), figsize=(7.2, 2.75), dpi=300)
|
|
259
|
+
if len(imgs) == 1:
|
|
260
|
+
axes = [axes]
|
|
261
|
+
for ax, img, label, metric in zip(axes, imgs, labels, metrics):
|
|
262
|
+
ax.imshow(img)
|
|
263
|
+
ax.set_axis_off()
|
|
264
|
+
ax.set_title(label, loc="left", fontsize=8.0, weight="semibold", pad=2)
|
|
265
|
+
ax.text(0.02, -0.035, metric, transform=ax.transAxes, ha="left", va="top", fontsize=5.6, color="#555555")
|
|
266
|
+
fig.subplots_adjust(left=0.01, right=0.99, top=0.92, bottom=0.16, wspace=0.03)
|
|
267
|
+
output_prefix.parent.mkdir(parents=True, exist_ok=True)
|
|
268
|
+
fig.savefig(output_prefix.with_suffix(".png"), bbox_inches="tight", dpi=600)
|
|
269
|
+
fig.savefig(output_prefix.with_suffix(".pdf"), bbox_inches="tight")
|
|
270
|
+
fig.savefig(output_prefix.with_suffix(".svg"), bbox_inches="tight")
|
|
271
|
+
plt.close(fig)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def select_low_budget_case(ensemble: pd.DataFrame, budget: int) -> tuple[str, pd.DataFrame]:
|
|
275
|
+
"""Select a representative low-budget case by a predeclared cohort rule."""
|
|
276
|
+
subset = ensemble[ensemble["K"].eq(budget)]
|
|
277
|
+
pivot = subset.pivot(index="ligand_id", columns="method", values="functional_state_coverage")
|
|
278
|
+
required = {"etkdg", "manimol"}
|
|
279
|
+
if not required.issubset(set(pivot.columns)):
|
|
280
|
+
raise RuntimeError(f"Both ETKDG and MANIMOL are required for K={budget} case selection.")
|
|
281
|
+
ranked = pivot.dropna(subset=["etkdg", "manimol"]).reset_index().copy()
|
|
282
|
+
ranked["manimol_minus_etkdg"] = ranked["manimol"] - ranked["etkdg"]
|
|
283
|
+
ranked = ranked.sort_values(
|
|
284
|
+
["manimol_minus_etkdg", "manimol", "ligand_id"],
|
|
285
|
+
ascending=[False, False, True],
|
|
286
|
+
)
|
|
287
|
+
if ranked.empty:
|
|
288
|
+
raise RuntimeError(f"No complete ETKDG/MANIMOL comparison found for K={budget}.")
|
|
289
|
+
return str(ranked.iloc[0]["ligand_id"]), ranked
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def select_best_functional_candidate(all_candidates: pd.DataFrame, ligand_id: str, method: str, budget: int) -> pd.Series:
|
|
293
|
+
"""Use the same functional-ranking rule for both methods within the first K candidates."""
|
|
294
|
+
subset = all_candidates[
|
|
295
|
+
all_candidates["ligand_id"].eq(ligand_id) & all_candidates["method"].eq(method)
|
|
296
|
+
].sort_values("candidate_index").head(budget)
|
|
297
|
+
if subset.empty:
|
|
298
|
+
raise RuntimeError(f"No {method} candidate found for {ligand_id} within K={budget}.")
|
|
299
|
+
return subset.sort_values(
|
|
300
|
+
["interaction_preservation", "pharmacophore_topology_coverage", "functional_distance_mae", "atom_rmsd"],
|
|
301
|
+
ascending=[False, False, True, True],
|
|
302
|
+
na_position="last",
|
|
303
|
+
).iloc[0]
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def main():
|
|
307
|
+
parser = argparse.ArgumentParser(description="Render fixed HIF2A contact pharmacophore pocket panels with PyMOL.")
|
|
308
|
+
parser.add_argument("--manifest", default="outputs/docking/hif2a_conformers/docking_manifest_manimol_xtb.csv")
|
|
309
|
+
parser.add_argument("--all_candidates_csv", default="outputs/docking/hif2a_contact_pharmacophore/hif2a_contact_pharmacophore_all_candidates.csv")
|
|
310
|
+
parser.add_argument("--ensemble_csv", default="outputs/docking/hif2a_contact_pharmacophore/hif2a_contact_pharmacophore_ensemble_per_ligand.csv")
|
|
311
|
+
parser.add_argument("--reference_interactions_csv", default="outputs/docking/hif2a_contact_pharmacophore/hif2a_reference_contact_pharmacophore.csv")
|
|
312
|
+
parser.add_argument("--ligand_id", default="", help="Optional fixed ligand id. Empty uses the declared low-budget selection rule.")
|
|
313
|
+
parser.add_argument("--case_budget", type=int, default=5)
|
|
314
|
+
parser.add_argument("--output_dir", default="outputs/docking/hif2a_contact_pharmacophore/pymol")
|
|
315
|
+
parser.add_argument("--width", type=int, default=1400)
|
|
316
|
+
parser.add_argument("--height", type=int, default=950)
|
|
317
|
+
parser.add_argument("--max_interactions", type=int, default=3)
|
|
318
|
+
parser.add_argument("--etkdg_candidate", default="", help="Optional explicit ETKDG candidate SDF.")
|
|
319
|
+
parser.add_argument("--manimol_candidate", default="", help="Optional explicit MANIMOL candidate SDF.")
|
|
320
|
+
parser.add_argument("--ligand_only", action="store_true", help="Render ligand/contact geometry without receptor context.")
|
|
321
|
+
args, _ = parser.parse_known_args()
|
|
322
|
+
|
|
323
|
+
manifest = pd.read_csv(args.manifest)
|
|
324
|
+
all_candidates = pd.read_csv(args.all_candidates_csv)
|
|
325
|
+
ensemble = pd.read_csv(args.ensemble_csv)
|
|
326
|
+
interactions = pd.read_csv(args.reference_interactions_csv)
|
|
327
|
+
|
|
328
|
+
selection_ranked = None
|
|
329
|
+
ligand_id = args.ligand_id
|
|
330
|
+
if not ligand_id:
|
|
331
|
+
ligand_id, selection_ranked = select_low_budget_case(ensemble, args.case_budget)
|
|
332
|
+
|
|
333
|
+
row = manifest[manifest["complex_id"].eq(ligand_id)]
|
|
334
|
+
if row.empty:
|
|
335
|
+
raise RuntimeError(f"Ligand {ligand_id} was not found in {args.manifest}")
|
|
336
|
+
row = row.iloc[0]
|
|
337
|
+
receptor = Path(str(row["receptor_pdb"]))
|
|
338
|
+
reference = Path(str(row["crystal_ligand_sdf"]))
|
|
339
|
+
chosen_interactions = major_interactions(interactions[interactions["ligand_id"].eq(ligand_id)], args.max_interactions)
|
|
340
|
+
|
|
341
|
+
method_rows = {
|
|
342
|
+
method: select_best_functional_candidate(all_candidates, ligand_id, method, args.case_budget)
|
|
343
|
+
for method in ["etkdg", "manimol"]
|
|
344
|
+
}
|
|
345
|
+
explicit_candidates = {
|
|
346
|
+
"etkdg": args.etkdg_candidate,
|
|
347
|
+
"manimol": args.manimol_candidate,
|
|
348
|
+
}
|
|
349
|
+
for method, candidate in explicit_candidates.items():
|
|
350
|
+
if candidate:
|
|
351
|
+
candidate_path = Path(candidate).resolve()
|
|
352
|
+
if not candidate_path.exists():
|
|
353
|
+
raise FileNotFoundError(candidate_path)
|
|
354
|
+
method_rows[method] = method_rows[method].copy()
|
|
355
|
+
method_rows[method]["candidate_file"] = str(candidate_path)
|
|
356
|
+
cmd = launch_pymol()
|
|
357
|
+
out_dir = Path(args.output_dir)
|
|
358
|
+
panels = []
|
|
359
|
+
|
|
360
|
+
pocket_residue_output = out_dir / "figure6_pocket_residues.txt"
|
|
361
|
+
setup_scene(cmd, receptor, reference, None, "reference", chosen_interactions, args.ligand_only,
|
|
362
|
+
pocket_residue_output=pocket_residue_output)
|
|
363
|
+
master_view = cmd.get_view()
|
|
364
|
+
ref_png = out_dir / f"{ligand_id}_reference.png"
|
|
365
|
+
render_panel(cmd, ref_png, args.width, args.height)
|
|
366
|
+
panels.append(ref_png)
|
|
367
|
+
|
|
368
|
+
for method in ["etkdg", "manimol"]:
|
|
369
|
+
cand = Path(str(method_rows[method]["candidate_file"]))
|
|
370
|
+
setup_scene(cmd, receptor, reference, cand, method, chosen_interactions, args.ligand_only, master_view)
|
|
371
|
+
out_png = out_dir / f"{ligand_id}_{method}.png"
|
|
372
|
+
render_panel(cmd, out_png, args.width, args.height)
|
|
373
|
+
panels.append(out_png)
|
|
374
|
+
|
|
375
|
+
labels = ["Crystal reference", "ETKDG", "MANIMOL"]
|
|
376
|
+
metrics = ["Reference", "", ""]
|
|
377
|
+
for i, method in enumerate(["etkdg", "manimol"], start=1):
|
|
378
|
+
m = method_rows[method]
|
|
379
|
+
metrics[i] = f"IPS {m['interaction_preservation']:.2f} · MAE {m['functional_distance_mae']:.2f} Å · Cov {m['pharmacophore_topology_coverage']:.2f}"
|
|
380
|
+
comparison_prefix = out_dir / f"{ligand_id}_pocket_comparison"
|
|
381
|
+
compose_panels(panels, labels[: len(panels)], metrics[: len(panels)], comparison_prefix)
|
|
382
|
+
config = {
|
|
383
|
+
"ligand_id": ligand_id,
|
|
384
|
+
"receptor": str(receptor),
|
|
385
|
+
"reference_ligand": str(reference),
|
|
386
|
+
"panels": [str(p) for p in panels],
|
|
387
|
+
"interaction_ids": chosen_interactions["interaction_id"].tolist(),
|
|
388
|
+
"selection": (
|
|
389
|
+
f"K={args.case_budget} representative selected by the prespecified paired PMS comparison; "
|
|
390
|
+
"the explicit candidate paths are the best PMS-scoring members within the matched retained libraries"
|
|
391
|
+
if all(explicit_candidates.values()) else
|
|
392
|
+
f"K={args.case_budget} representative selected by maximum MANIMOL-minus-ETKDG functional-state coverage; "
|
|
393
|
+
"each displayed method candidate maximizes IPS, then topology coverage, then minimizes distance MAE within its first K candidates"
|
|
394
|
+
),
|
|
395
|
+
"case_budget": args.case_budget,
|
|
396
|
+
"candidate_indices": {method: int(row["candidate_index"]) for method, row in method_rows.items()},
|
|
397
|
+
"metrics": {method: {key: float(row[key]) for key in ["interaction_preservation", "functional_distance_mae", "pharmacophore_topology_coverage"]} for method, row in method_rows.items()},
|
|
398
|
+
"comparison_panel": str(comparison_prefix.with_suffix(".png")),
|
|
399
|
+
}
|
|
400
|
+
if selection_ranked is not None:
|
|
401
|
+
config["selection_ranking"] = selection_ranked.reset_index(drop=True).to_dict(orient="records")
|
|
402
|
+
config_path = out_dir / "selected_lowbudget_functional_case.json"
|
|
403
|
+
config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
|
|
404
|
+
cmd.quit()
|
|
405
|
+
|
|
406
|
+
print(f"Selected ligand: {ligand_id} (K={args.case_budget})")
|
|
407
|
+
print(f"Saved: {comparison_prefix.with_suffix('.png')}")
|
|
408
|
+
print(f"Saved: {comparison_prefix.with_suffix('.pdf')}")
|
|
409
|
+
print(f"Saved: {comparison_prefix.with_suffix('.svg')}")
|
|
410
|
+
print(f"Saved: {config_path}")
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
if __name__ == "__main__":
|
|
414
|
+
main()
|