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,413 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Render reproducible protein-ligand binding-mode panels with PyMOL.
|
|
3
|
+
|
|
4
|
+
Run with the PyMOL Python executable, for example:
|
|
5
|
+
pymol -cq scripts/render_binding_modes.py -- --config configs/binding_modes.yaml
|
|
6
|
+
|
|
7
|
+
The renderer accepts explicit pose files (the recommended, auditable mode), a
|
|
8
|
+
multi-state SDF/MOL2 file, or rows selected from a results CSV. It saves one
|
|
9
|
+
PNG per panel, a shared camera matrix for every system, and conservative polar
|
|
10
|
+
contact records. No interaction labels are inferred without a distance-based
|
|
11
|
+
polar-atom criterion.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import csv
|
|
18
|
+
import json
|
|
19
|
+
import math
|
|
20
|
+
import re
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any, Dict, Iterable, List, Sequence, Tuple
|
|
23
|
+
|
|
24
|
+
import yaml
|
|
25
|
+
from pymol import cmd
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
AA1 = {
|
|
29
|
+
"ALA": "A", "ARG": "R", "ASN": "N", "ASP": "D", "CYS": "C",
|
|
30
|
+
"GLN": "Q", "GLU": "E", "GLY": "G", "HIS": "H", "ILE": "I",
|
|
31
|
+
"LEU": "L", "LYS": "K", "MET": "M", "PHE": "F", "PRO": "P",
|
|
32
|
+
"SER": "S", "THR": "T", "TRP": "W", "TYR": "Y", "VAL": "V",
|
|
33
|
+
}
|
|
34
|
+
POLAR = {"N", "O", "S"}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_args() -> argparse.Namespace:
|
|
38
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
39
|
+
parser.add_argument("--config", required=True, help="YAML configuration")
|
|
40
|
+
parser.add_argument("--output-dir", default="outputs/binding_mode_figure")
|
|
41
|
+
parser.add_argument("--system", action="append", help="Render only a named system; repeatable")
|
|
42
|
+
return parser.parse_args()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def ensure_path(path: str | Path, field: str, system: str) -> Path:
|
|
46
|
+
resolved = Path(path)
|
|
47
|
+
if not resolved.exists():
|
|
48
|
+
raise FileNotFoundError(f"{system}: {field} does not exist: {resolved}")
|
|
49
|
+
return resolved
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def safe_name(value: str) -> str:
|
|
53
|
+
return re.sub(r"[^A-Za-z0-9_.-]+", "_", value)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def read_pose_rows(system: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
57
|
+
"""Resolve explicit poses first; otherwise select rows from an optional CSV."""
|
|
58
|
+
if system.get("pose_files"):
|
|
59
|
+
return [dict(row) for row in system["pose_files"]]
|
|
60
|
+
|
|
61
|
+
csv_path = system.get("results_csv")
|
|
62
|
+
if csv_path:
|
|
63
|
+
with Path(csv_path).open(newline="") as handle:
|
|
64
|
+
rows = list(csv.DictReader(handle))
|
|
65
|
+
metric = system.get("selection_metric", "vina_score")
|
|
66
|
+
top_n = int(system.get("select_top_n", len(rows)))
|
|
67
|
+
direction = system.get("selection_direction", "asc")
|
|
68
|
+
path_column = next((name for name in ("pose_path", "dock_sdf", "placed_sdf", "path") if rows and name in rows[0]), None)
|
|
69
|
+
id_column = system.get("pose_id_column", "pose_id")
|
|
70
|
+
if not path_column:
|
|
71
|
+
raise ValueError(f"{system['name']}: results_csv has no pose-path column")
|
|
72
|
+
requested = {str(value) for value in system.get("pose_ids", [])}
|
|
73
|
+
if requested:
|
|
74
|
+
rows = [row for row in rows if str(row.get(id_column, row.get("conf_id", ""))) in requested]
|
|
75
|
+
else:
|
|
76
|
+
def key(row: Dict[str, str]) -> float:
|
|
77
|
+
try:
|
|
78
|
+
return float(row.get(metric, "nan"))
|
|
79
|
+
except ValueError:
|
|
80
|
+
return math.inf
|
|
81
|
+
rows = sorted(rows, key=key, reverse=(direction == "desc"))[:top_n]
|
|
82
|
+
colors = system.get("ligand_colors", {})
|
|
83
|
+
return [
|
|
84
|
+
{
|
|
85
|
+
"id": row.get(id_column, row.get("conf_id", index + 1)),
|
|
86
|
+
"path": row[path_column],
|
|
87
|
+
"label": f"ID: {row.get(id_column, row.get('conf_id', index + 1))}",
|
|
88
|
+
"color": colors.get(str(row.get(id_column, row.get("conf_id", index + 1))), "orange"),
|
|
89
|
+
}
|
|
90
|
+
for index, row in enumerate(rows)
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
poses = system.get("poses")
|
|
94
|
+
if not poses:
|
|
95
|
+
raise ValueError(f"{system['name']}: specify pose_files, results_csv, or poses")
|
|
96
|
+
ids = system.get("pose_ids", [])
|
|
97
|
+
if not ids:
|
|
98
|
+
raise ValueError(f"{system['name']}: poses requires explicit pose_ids")
|
|
99
|
+
colors = system.get("ligand_colors", {})
|
|
100
|
+
return [
|
|
101
|
+
{"id": pose_id, "path": poses, "state": int(pose_id), "label": f"ID: {pose_id}",
|
|
102
|
+
"color": colors.get(str(pose_id), "orange")}
|
|
103
|
+
for pose_id in ids
|
|
104
|
+
]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def color_ligand(object_name: str, carbon_color: str) -> None:
|
|
108
|
+
cmd.color(carbon_color, f"{object_name} and elem C")
|
|
109
|
+
cmd.color("blue", f"{object_name} and elem N")
|
|
110
|
+
cmd.color("red", f"{object_name} and elem O")
|
|
111
|
+
cmd.color("yellow", f"{object_name} and elem S")
|
|
112
|
+
cmd.color("green", f"{object_name} and elem F")
|
|
113
|
+
cmd.color("tv_green", f"{object_name} and elem Cl")
|
|
114
|
+
cmd.color("firebrick", f"{object_name} and elem Br")
|
|
115
|
+
cmd.color("purple", f"{object_name} and elem I")
|
|
116
|
+
cmd.show("sticks", object_name)
|
|
117
|
+
cmd.set("stick_radius", 0.20, object_name)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def setup_scene(render: Dict[str, Any]) -> None:
|
|
121
|
+
cmd.reinitialize()
|
|
122
|
+
cmd.bg_color(render.get("background", "white"))
|
|
123
|
+
cmd.set("orthoscopic", 1)
|
|
124
|
+
cmd.set("ray_opaque_background", 1)
|
|
125
|
+
cmd.set("ray_shadows", 0)
|
|
126
|
+
cmd.set("depth_cue", 0)
|
|
127
|
+
cmd.set("antialias", 2)
|
|
128
|
+
cmd.set("ambient", 0.35)
|
|
129
|
+
cmd.set("direct", 0.75)
|
|
130
|
+
cmd.set("specular", 0.18)
|
|
131
|
+
cmd.set("shininess", 25)
|
|
132
|
+
cmd.set("valence", 0)
|
|
133
|
+
# `dash_labels` is not available in every open-source PyMOL build.
|
|
134
|
+
# Distance labels are suppressed by naming only the dashes themselves.
|
|
135
|
+
cmd.set("label_font_id", 7)
|
|
136
|
+
cmd.set("label_color", "marine")
|
|
137
|
+
cmd.set("label_size", int(render.get("label_size", 21)))
|
|
138
|
+
cmd.set_color("protein_cartoon", [0.74, 0.79, 0.94])
|
|
139
|
+
cmd.set_color("pocket_carbon", [0.30, 0.40, 0.80])
|
|
140
|
+
cmd.set_color("polar_contact", [0.56, 0.20, 0.20])
|
|
141
|
+
cmd.set_color("annotation_red", [0.86, 0.12, 0.12])
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def atom_records(selection: str) -> List[Dict[str, Any]]:
|
|
145
|
+
model = cmd.get_model(selection)
|
|
146
|
+
records: List[Dict[str, Any]] = []
|
|
147
|
+
for atom in model.atom:
|
|
148
|
+
if atom.symbol.upper() == "H":
|
|
149
|
+
continue
|
|
150
|
+
records.append({
|
|
151
|
+
"coord": atom.coord, "element": atom.symbol.upper(), "resn": atom.resn,
|
|
152
|
+
"resi": atom.resi, "chain": atom.chain, "name": atom.name,
|
|
153
|
+
})
|
|
154
|
+
return records
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def distance(a: Sequence[float], b: Sequence[float]) -> float:
|
|
158
|
+
return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def nearest_residues(receptor: str, ligand: str, cutoff: float, limit: int) -> List[Tuple[str, str, str, float]]:
|
|
162
|
+
ligand_atoms = atom_records(ligand)
|
|
163
|
+
residues: Dict[Tuple[str, str, str], float] = {}
|
|
164
|
+
for atom in atom_records(f"{receptor} and polymer.protein"):
|
|
165
|
+
key = (atom["chain"], atom["resn"], atom["resi"])
|
|
166
|
+
minimum = min(distance(atom["coord"], ligand_atom["coord"]) for ligand_atom in ligand_atoms)
|
|
167
|
+
if minimum <= cutoff:
|
|
168
|
+
residues[key] = min(residues.get(key, math.inf), minimum)
|
|
169
|
+
ranked = sorted(((chain, resn, resi, value) for (chain, resn, resi), value in residues.items()), key=lambda item: item[3])
|
|
170
|
+
return ranked[:limit]
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def residue_selection(receptor: str, residues: Iterable[Tuple[str, str, str, float]]) -> str:
|
|
174
|
+
selections = [f"({receptor} and chain {chain} and resi {resi})" for chain, _resn, resi, _distance in residues]
|
|
175
|
+
return " or ".join(selections) if selections else "none"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def parse_key_residue(value: str) -> Tuple[str | None, str, str]:
|
|
179
|
+
match = re.fullmatch(r"([A-Za-z]{3})([0-9]+[A-Za-z]?)", str(value).strip())
|
|
180
|
+
if not match:
|
|
181
|
+
raise ValueError(f"Unsupported residue label {value!r}; use e.g. ARG82")
|
|
182
|
+
return None, match.group(1).upper(), match.group(2)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def configured_residues(receptor: str, labels: Sequence[str]) -> List[Tuple[str, str, str, float]]:
|
|
186
|
+
found: List[Tuple[str, str, str, float]] = []
|
|
187
|
+
for value in labels:
|
|
188
|
+
_chain, resn, resi = parse_key_residue(value)
|
|
189
|
+
model = cmd.get_model(f"{receptor} and resn {resn} and resi {resi} and name CA")
|
|
190
|
+
if model.atom:
|
|
191
|
+
found.append((model.atom[0].chain, resn, resi, 0.0))
|
|
192
|
+
return found
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def add_labels(receptor: str, residues: Iterable[Tuple[str, str, str, float]]) -> None:
|
|
196
|
+
for index, (chain, resn, resi, _value) in enumerate(residues):
|
|
197
|
+
one_letter = AA1.get(resn.upper(), resn[:1].upper())
|
|
198
|
+
selection = f"{receptor} and chain {chain} and resi {resi} and name CA"
|
|
199
|
+
label_selection = f"label_{safe_name(chain)}_{safe_name(resi)}_{index}"
|
|
200
|
+
cmd.select(label_selection, selection)
|
|
201
|
+
if cmd.count_atoms(label_selection):
|
|
202
|
+
cmd.label(label_selection, repr(f"{one_letter}{resi}"))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def collect_polar_contacts(system: str, pose_id: str, receptor: str, ligand: str, cutoff: float, max_contacts: int) -> List[Dict[str, Any]]:
|
|
206
|
+
rows: List[Dict[str, Any]] = []
|
|
207
|
+
candidates: List[Tuple[float, Dict[str, Any], Dict[str, Any]]] = []
|
|
208
|
+
seen: set[Tuple[str, str, str]] = set()
|
|
209
|
+
ligand_atoms = [atom for atom in atom_records(ligand) if atom["element"] in POLAR]
|
|
210
|
+
protein_atoms = [atom for atom in atom_records(f"{receptor} and polymer.protein") if atom["element"] in POLAR]
|
|
211
|
+
for protein_atom in protein_atoms:
|
|
212
|
+
for ligand_atom in ligand_atoms:
|
|
213
|
+
value = distance(protein_atom["coord"], ligand_atom["coord"])
|
|
214
|
+
key = (protein_atom["chain"], protein_atom["resn"], protein_atom["resi"])
|
|
215
|
+
if value <= cutoff and key not in seen:
|
|
216
|
+
seen.add(key)
|
|
217
|
+
candidates.append((value, protein_atom, ligand_atom))
|
|
218
|
+
for index, (value, protein_atom, ligand_atom) in enumerate(sorted(candidates, key=lambda item: item[0])[:max_contacts]):
|
|
219
|
+
name = f"polar_{safe_name(system)}_{safe_name(str(pose_id))}_{index}"
|
|
220
|
+
cmd.distance(name,
|
|
221
|
+
f"{receptor} and chain {protein_atom['chain']} and resi {protein_atom['resi']} and name {protein_atom['name']}",
|
|
222
|
+
f"{ligand} and name {ligand_atom['name']}")
|
|
223
|
+
cmd.color("polar_contact", name)
|
|
224
|
+
cmd.set("dash_width", 2.0, name)
|
|
225
|
+
cmd.hide("labels", name)
|
|
226
|
+
rows.append({
|
|
227
|
+
"system": system, "pose_id": pose_id, "chain": protein_atom["chain"],
|
|
228
|
+
"residue": f"{AA1.get(protein_atom['resn'], protein_atom['resn'][:1])}{protein_atom['resi']}",
|
|
229
|
+
"protein_atom": protein_atom["name"], "ligand_atom": ligand_atom["name"],
|
|
230
|
+
"distance": round(value, 3), "interaction_type": "polar_contact",
|
|
231
|
+
})
|
|
232
|
+
return rows
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def highlight_local_deviations(reference: str, ligand: str, threshold: float) -> int:
|
|
236
|
+
"""Mark atoms with a genuine reference-frame displacement.
|
|
237
|
+
|
|
238
|
+
The pose and reference files use the same atom ordering. The markers are
|
|
239
|
+
deliberately limited to heavy atoms exceeding the configured displacement
|
|
240
|
+
threshold, so the figure identifies a local geometric residual without
|
|
241
|
+
claiming a specific interaction or energy contribution.
|
|
242
|
+
"""
|
|
243
|
+
reference_atoms = [atom for atom in cmd.get_model(reference).atom if atom.symbol.upper() != "H"]
|
|
244
|
+
ligand_atoms = [atom for atom in cmd.get_model(ligand).atom if atom.symbol.upper() != "H"]
|
|
245
|
+
if len(reference_atoms) != len(ligand_atoms) or not reference_atoms:
|
|
246
|
+
return 0
|
|
247
|
+
displaced_atoms = []
|
|
248
|
+
for reference_atom, ligand_atom in zip(reference_atoms, ligand_atoms):
|
|
249
|
+
displacement = distance(reference_atom.coord, ligand_atom.coord)
|
|
250
|
+
if displacement >= float(threshold):
|
|
251
|
+
displaced_atoms.append((displacement, ligand_atom))
|
|
252
|
+
if not displaced_atoms:
|
|
253
|
+
return 0
|
|
254
|
+
# Pseudoatoms are used rather than an atom-index selection because SDF
|
|
255
|
+
# atom indices are not retained consistently by every PyMOL import path.
|
|
256
|
+
# They provide a robust, visible red marker at each local residual.
|
|
257
|
+
marker = f"{ligand}_residual"
|
|
258
|
+
for _displacement, atom in sorted(displaced_atoms, key=lambda item: item[0], reverse=True)[:3]:
|
|
259
|
+
cmd.pseudoatom(marker, pos=atom.coord)
|
|
260
|
+
cmd.show("spheres", marker)
|
|
261
|
+
cmd.color("annotation_red", marker)
|
|
262
|
+
cmd.set("sphere_scale", 0.72, marker)
|
|
263
|
+
cmd.set("sphere_transparency", 0.30, marker)
|
|
264
|
+
return min(len(displaced_atoms), 3)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def load_pose(object_name: str, pose: Dict[str, Any]) -> None:
|
|
268
|
+
path = ensure_path(pose["path"], "pose", object_name)
|
|
269
|
+
cmd.load(str(path), object_name)
|
|
270
|
+
if pose.get("state"):
|
|
271
|
+
extracted = f"{object_name}_state"
|
|
272
|
+
cmd.create(extracted, f"{object_name} and state {int(pose['state'])}")
|
|
273
|
+
cmd.delete(object_name)
|
|
274
|
+
cmd.set_name(extracted, object_name)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def write_view(path: Path) -> None:
|
|
278
|
+
path.write_text(json.dumps([round(float(value), 8) for value in cmd.get_view()], indent=2) + "\n")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def read_view(path: Path) -> List[float]:
|
|
282
|
+
return [float(value) for value in json.loads(path.read_text())]
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def render_system(system: Dict[str, Any], render: Dict[str, Any], output_dir: Path) -> Tuple[List[Dict[str, Any]], List[Path]]:
|
|
286
|
+
name = system["name"]
|
|
287
|
+
receptor_path = ensure_path(system["receptor"], "receptor", name)
|
|
288
|
+
reference_path = ensure_path(system["reference_ligand"], "reference_ligand", name)
|
|
289
|
+
poses = read_pose_rows(system)
|
|
290
|
+
system_dir = output_dir / safe_name(name)
|
|
291
|
+
panels_dir = system_dir / "panels"
|
|
292
|
+
panels_dir.mkdir(parents=True, exist_ok=True)
|
|
293
|
+
view_path = system_dir / "camera_view.json"
|
|
294
|
+
setup_scene(render)
|
|
295
|
+
cmd.load(str(receptor_path), "receptor")
|
|
296
|
+
cmd.load(str(reference_path), "reference")
|
|
297
|
+
cmd.remove("solvent or hydro")
|
|
298
|
+
cmd.hide("everything")
|
|
299
|
+
cmd.show("cartoon", "receptor and polymer.protein")
|
|
300
|
+
cmd.color("protein_cartoon", "receptor and polymer.protein")
|
|
301
|
+
cmd.set("cartoon_transparency", float(render.get("protein_transparency", 0.75)), "receptor")
|
|
302
|
+
color_ligand("reference", system.get("ligand_colors", {}).get("reference", "yellow"))
|
|
303
|
+
|
|
304
|
+
configured = configured_residues("receptor", system.get("key_residues", []))
|
|
305
|
+
key_residues = configured or nearest_residues(
|
|
306
|
+
"receptor", "reference", float(render.get("pocket_cutoff", 4.5)), int(render.get("auto_label_count", 6))
|
|
307
|
+
)
|
|
308
|
+
pocket = residue_selection("receptor", key_residues)
|
|
309
|
+
cmd.show("sticks", f"({pocket}) and not backbone")
|
|
310
|
+
cmd.color("pocket_carbon", f"({pocket}) and elem C")
|
|
311
|
+
cmd.color("blue", f"({pocket}) and elem N")
|
|
312
|
+
cmd.color("red", f"({pocket}) and elem O")
|
|
313
|
+
cmd.color("yellow", f"({pocket}) and elem S")
|
|
314
|
+
cmd.set("stick_radius", 0.14, pocket)
|
|
315
|
+
add_labels("receptor", key_residues)
|
|
316
|
+
cmd.orient(f"({pocket}) or reference")
|
|
317
|
+
cmd.zoom(f"({pocket}) or reference", float(render.get("zoom_buffer", 3.5)))
|
|
318
|
+
cmd.turn("y", float(render.get("turn_y", 18)))
|
|
319
|
+
cmd.turn("x", float(render.get("turn_x", -8)))
|
|
320
|
+
write_view(view_path)
|
|
321
|
+
|
|
322
|
+
records: List[Dict[str, Any]] = []
|
|
323
|
+
panel_paths: List[Path] = []
|
|
324
|
+
panels: List[Dict[str, Any]] = [{"id": "reference", "label": "Reference", "object": "reference", "color": system.get("ligand_colors", {}).get("reference", "yellow")}]
|
|
325
|
+
for pose in poses:
|
|
326
|
+
pose_id = str(pose.get("id", len(panels)))
|
|
327
|
+
object_name = f"pose_{safe_name(pose_id)}"
|
|
328
|
+
load_pose(object_name, pose)
|
|
329
|
+
color_ligand(object_name, pose.get("color", system.get("ligand_colors", {}).get(pose_id, "orange")))
|
|
330
|
+
panels.append({"id": pose_id, "label": pose.get("label", f"ID: {pose_id}"), "object": object_name, "color": pose.get("color", "orange")})
|
|
331
|
+
|
|
332
|
+
for panel in panels:
|
|
333
|
+
for other in panels:
|
|
334
|
+
cmd.disable(other["object"])
|
|
335
|
+
if panel["id"] != "reference" and render.get("overlay_reference", True):
|
|
336
|
+
# A subdued reference overlay makes the structural comparison
|
|
337
|
+
# directly visible without implying an interaction not in the data.
|
|
338
|
+
cmd.enable("reference")
|
|
339
|
+
cmd.color("gray70", "reference and elem C")
|
|
340
|
+
cmd.color("red", "reference and elem O")
|
|
341
|
+
cmd.color("blue", "reference and elem N")
|
|
342
|
+
cmd.color("yellow", "reference and elem S")
|
|
343
|
+
cmd.set("stick_transparency", 0.45, "reference")
|
|
344
|
+
cmd.set("stick_radius", 0.14, "reference")
|
|
345
|
+
else:
|
|
346
|
+
color_ligand("reference", system.get("ligand_colors", {}).get("reference", "yellow"))
|
|
347
|
+
cmd.set("stick_transparency", 0.0, "reference")
|
|
348
|
+
cmd.set("stick_radius", 0.20, "reference")
|
|
349
|
+
cmd.enable(panel["object"])
|
|
350
|
+
cmd.set_view(read_view(view_path))
|
|
351
|
+
panel_contacts = collect_polar_contacts(
|
|
352
|
+
name, str(panel["id"]), "receptor", panel["object"], float(render.get("contact_cutoff", 3.6)),
|
|
353
|
+
int(render.get("max_contact_lines", 2)),
|
|
354
|
+
)
|
|
355
|
+
records.extend(panel_contacts)
|
|
356
|
+
if panel["id"] != "reference" and render.get("highlight_deviations", True):
|
|
357
|
+
count = highlight_local_deviations("reference", panel["object"], float(render.get("deviation_threshold", 0.45)))
|
|
358
|
+
print(f"{name} pose {panel['id']}: marked {count} locally displaced atoms")
|
|
359
|
+
if not render.get("show_contacts", False):
|
|
360
|
+
cmd.disable("polar_*")
|
|
361
|
+
png_path = panels_dir / f"{safe_name(str(panel['id']))}.png"
|
|
362
|
+
cmd.png(str(png_path), width=int(render.get("width", 1800)), height=int(render.get("height", 1000)),
|
|
363
|
+
dpi=int(render.get("dpi", 300)), ray=1 if render.get("ray_trace", True) else 0)
|
|
364
|
+
panel_paths.append(png_path)
|
|
365
|
+
cmd.delete("polar_*")
|
|
366
|
+
cmd.delete("*_residual")
|
|
367
|
+
cmd.save(str(system_dir / f"{safe_name(name)}.pse"))
|
|
368
|
+
(system_dir / "panels.json").write_text(json.dumps([
|
|
369
|
+
{"id": panel["id"], "label": panel["label"], "path": str(path)} for panel, path in zip(panels, panel_paths)
|
|
370
|
+
], indent=2) + "\n")
|
|
371
|
+
return records, panel_paths
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def main() -> None:
|
|
375
|
+
args = parse_args()
|
|
376
|
+
config_path = Path(args.config)
|
|
377
|
+
config = yaml.safe_load(config_path.read_text())
|
|
378
|
+
render = config.get("render", {})
|
|
379
|
+
output_dir = Path(args.output_dir)
|
|
380
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
381
|
+
requested = set(args.system or [])
|
|
382
|
+
records: List[Dict[str, Any]] = []
|
|
383
|
+
rendered: List[str] = []
|
|
384
|
+
skipped: List[Dict[str, str]] = []
|
|
385
|
+
for system in config.get("systems", []):
|
|
386
|
+
name = system.get("name", "unnamed")
|
|
387
|
+
if requested and name not in requested:
|
|
388
|
+
continue
|
|
389
|
+
if system.get("enabled", True) is False:
|
|
390
|
+
skipped.append({"system": name, "reason": "disabled in YAML"})
|
|
391
|
+
continue
|
|
392
|
+
try:
|
|
393
|
+
system_records, _ = render_system(system, render, output_dir)
|
|
394
|
+
records.extend(system_records)
|
|
395
|
+
rendered.append(name)
|
|
396
|
+
print(f"Rendered {name}")
|
|
397
|
+
except (FileNotFoundError, ValueError) as exc:
|
|
398
|
+
skipped.append({"system": name, "reason": str(exc)})
|
|
399
|
+
print(f"Skipped {name}: {exc}")
|
|
400
|
+
contact_path = output_dir / "contacts.csv"
|
|
401
|
+
fields = ["system", "pose_id", "chain", "residue", "protein_atom", "ligand_atom", "distance", "interaction_type"]
|
|
402
|
+
with contact_path.open("w", newline="") as handle:
|
|
403
|
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
|
404
|
+
writer.writeheader()
|
|
405
|
+
writer.writerows(records)
|
|
406
|
+
(output_dir / "render_report.json").write_text(json.dumps({"rendered": rendered, "skipped": skipped}, indent=2) + "\n")
|
|
407
|
+
if not rendered:
|
|
408
|
+
raise SystemExit("No systems were rendered; see render_report.json")
|
|
409
|
+
print(f"Saved contacts: {contact_path}")
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
if __name__ == "__main__":
|
|
413
|
+
main()
|