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,1111 @@
1
+ #!/usr/bin/env python3
2
+ """Protein-contact-aware 3D pharmacophore preservation analysis for HIF2A.
3
+
4
+ The analysis is a downstream functional-geometry diagnostic. It extracts
5
+ protein-contact pharmacophore interactions from HIF2A crystal ligand poses and
6
+ tests whether generated receptor-frame conformers preserve the same interaction
7
+ distances without additional ligand optimization.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import math
15
+ import os
16
+ import re
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Iterable
20
+
21
+ os.environ.setdefault("MPLCONFIGDIR", str(Path("tmp/matplotlib").resolve()))
22
+
23
+ import matplotlib as mpl
24
+ import matplotlib.pyplot as plt
25
+ import numpy as np
26
+ import pandas as pd
27
+ from rdkit import Chem, RDConfig
28
+ from rdkit.Chem import AllChem, ChemicalFeatures
29
+
30
+
31
+ FEATURE_FAMILIES = {
32
+ "Donor": "donor",
33
+ "Acceptor": "acceptor",
34
+ "Hydrophobe": "hydrophobe",
35
+ "LumpedHydrophobe": "hydrophobe",
36
+ "Aromatic": "aromatic",
37
+ "PosIonizable": "positive",
38
+ "NegIonizable": "negative",
39
+ }
40
+
41
+ AROMATIC_RESIDUES = {
42
+ "PHE": {"CG", "CD1", "CD2", "CE1", "CE2", "CZ"},
43
+ "TYR": {"CG", "CD1", "CD2", "CE1", "CE2", "CZ"},
44
+ "TRP": {"CD2", "CE2", "CE3", "CZ2", "CZ3", "CH2"},
45
+ "HIS": {"CG", "ND1", "CD2", "CE1", "NE2"},
46
+ }
47
+
48
+ HYDROPHOBIC_RESIDUES = {
49
+ "ALA",
50
+ "VAL",
51
+ "LEU",
52
+ "ILE",
53
+ "MET",
54
+ "PHE",
55
+ "TYR",
56
+ "TRP",
57
+ "PRO",
58
+ "CYS",
59
+ }
60
+
61
+ TYPE_CUTOFF = {
62
+ "hbond": 3.5,
63
+ "hydrophobic": 4.5,
64
+ "aromatic": 5.5,
65
+ "electrostatic": 4.5,
66
+ }
67
+
68
+ # Ensemble recovery uses tolerances on deviations from the crystallographic
69
+ # feature--residue distance, rather than the looser contact-existence cutoffs.
70
+ # These values are deliberately type-specific because hydrogen-bond geometry is
71
+ # more constrained than aromatic and hydrophobic contacts.
72
+ ENSEMBLE_DISTANCE_TOLERANCE = {
73
+ "hbond": 0.5,
74
+ "electrostatic": 0.5,
75
+ "aromatic": 1.0,
76
+ "hydrophobic": 1.5,
77
+ }
78
+ MAJOR_INTERACTIONS_PER_LIGAND = 5
79
+ FUNCTIONAL_STATE_FRACTION = 0.80
80
+
81
+ TYPE_PRIORITY = {
82
+ "hbond": 0,
83
+ "electrostatic": 1,
84
+ "aromatic": 2,
85
+ "hydrophobic": 3,
86
+ }
87
+
88
+ COLORS = {
89
+ "reference": "#555555",
90
+ "etkdg": "#D98B45",
91
+ "etflow": "#3F8F7B",
92
+ "manimol": "#8E4BBE",
93
+ "manimol_geometry": "#8E4BBE",
94
+ "manimol_functional": "#635D9E",
95
+ "protein": "#9AA6B2",
96
+ "hbond": "#B23A48",
97
+ "hydrophobic": "#8C8C8C",
98
+ "aromatic": "#5C6BC0",
99
+ "electrostatic": "#AB6F2D",
100
+ }
101
+
102
+
103
+ METHOD_LABELS = {
104
+ "etkdg": "ETKDG",
105
+ "etflow": "ET-Flow",
106
+ "manimol": "MANIMOL",
107
+ "manimol_geometry": "MANIMOL (geometry)",
108
+ "manimol_functional": "MANIMOL (functional)",
109
+ }
110
+
111
+
112
+ def method_color(method: str) -> str:
113
+ return COLORS.get(method, "#6F7A86")
114
+
115
+
116
+ def method_label(method: str) -> str:
117
+ return METHOD_LABELS.get(method, method.replace("_", " ").title())
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class ProteinAtom:
122
+ coord: np.ndarray
123
+ element: str
124
+ atom_name: str
125
+ resname: str
126
+ chain: str
127
+ resseq: str
128
+
129
+ @property
130
+ def residue_id(self) -> str:
131
+ return f"{self.resname}{self.resseq}:{self.chain}".replace(" ", "")
132
+
133
+ @property
134
+ def short_label(self) -> str:
135
+ one = {
136
+ "ALA": "A",
137
+ "ARG": "R",
138
+ "ASN": "N",
139
+ "ASP": "D",
140
+ "CYS": "C",
141
+ "GLN": "Q",
142
+ "GLU": "E",
143
+ "GLY": "G",
144
+ "HIS": "H",
145
+ "ILE": "I",
146
+ "LEU": "L",
147
+ "LYS": "K",
148
+ "MET": "M",
149
+ "PHE": "F",
150
+ "PRO": "P",
151
+ "SER": "S",
152
+ "THR": "T",
153
+ "TRP": "W",
154
+ "TYR": "Y",
155
+ "VAL": "V",
156
+ "HOH": "W",
157
+ }.get(self.resname, self.resname[:1])
158
+ return f"{one}{self.resseq}".replace(" ", "")
159
+
160
+
161
+ def read_first_mol(path: Path):
162
+ suppl = Chem.SDMolSupplier(str(path), removeHs=False, sanitize=False)
163
+ for mol in suppl:
164
+ if mol is None or not mol.GetNumConformers():
165
+ continue
166
+ try:
167
+ Chem.SanitizeMol(mol)
168
+ except Exception:
169
+ pass
170
+ return mol
171
+ return None
172
+
173
+
174
+ def read_all_mols(path: Path):
175
+ suppl = Chem.SDMolSupplier(str(path), removeHs=False, sanitize=False)
176
+ out = []
177
+ for mol in suppl:
178
+ if mol is None or not mol.GetNumConformers():
179
+ continue
180
+ try:
181
+ Chem.SanitizeMol(mol)
182
+ except Exception:
183
+ pass
184
+ out.append(mol)
185
+ return out
186
+
187
+
188
+ def get_factory():
189
+ fdef = Path(RDConfig.RDDataDir) / "BaseFeatures.fdef"
190
+ return ChemicalFeatures.BuildFeatureFactory(str(fdef))
191
+
192
+
193
+ def ligand_features(mol, factory) -> list[dict]:
194
+ conf = mol.GetConformer()
195
+ feats = []
196
+ for raw in factory.GetFeaturesForMol(mol):
197
+ family = FEATURE_FAMILIES.get(raw.GetFamily())
198
+ if family is None:
199
+ continue
200
+ atom_ids = tuple(int(i) for i in raw.GetAtomIds())
201
+ coords = []
202
+ for atom_id in atom_ids:
203
+ p = conf.GetAtomPosition(atom_id)
204
+ coords.append([p.x, p.y, p.z])
205
+ if not coords:
206
+ continue
207
+ feats.append(
208
+ {
209
+ "feature_id": len(feats),
210
+ "family": family,
211
+ "atom_ids": atom_ids,
212
+ "coord": np.asarray(coords, dtype=float).mean(axis=0),
213
+ }
214
+ )
215
+ return feats
216
+
217
+
218
+ def read_protein_atoms(path: Path) -> list[ProteinAtom]:
219
+ atoms = []
220
+ for line in path.read_text(errors="ignore").splitlines():
221
+ if not (line.startswith("ATOM") or line.startswith("HETATM")):
222
+ continue
223
+ atom_name = line[12:16].strip()
224
+ element = (line[76:78].strip() or re.sub(r"[^A-Za-z]", "", atom_name)[:1]).upper()
225
+ if element == "H" or atom_name.startswith("H"):
226
+ continue
227
+ try:
228
+ coord = np.asarray(
229
+ [float(line[30:38]), float(line[38:46]), float(line[46:54])],
230
+ dtype=float,
231
+ )
232
+ except ValueError:
233
+ continue
234
+ atoms.append(
235
+ ProteinAtom(
236
+ coord=coord,
237
+ element=element,
238
+ atom_name=atom_name,
239
+ resname=line[17:20].strip().upper(),
240
+ chain=line[21:22].strip() or "_",
241
+ resseq=line[22:26].strip(),
242
+ )
243
+ )
244
+ return atoms
245
+
246
+
247
+ def protein_aromatic_centers(atoms: list[ProteinAtom]) -> list[dict]:
248
+ grouped: dict[str, list[ProteinAtom]] = {}
249
+ for atom in atoms:
250
+ names = AROMATIC_RESIDUES.get(atom.resname)
251
+ if names and atom.atom_name in names:
252
+ grouped.setdefault(atom.residue_id, []).append(atom)
253
+ centers = []
254
+ for residue_id, residue_atoms in grouped.items():
255
+ if len(residue_atoms) < 4:
256
+ continue
257
+ coords = np.vstack([a.coord for a in residue_atoms])
258
+ rep = residue_atoms[0]
259
+ centers.append(
260
+ {
261
+ "coord": coords.mean(axis=0),
262
+ "residue_id": residue_id,
263
+ "residue_label": rep.short_label,
264
+ "resname": rep.resname,
265
+ "feature": "aromatic",
266
+ "atom_name": "ring",
267
+ }
268
+ )
269
+ return centers
270
+
271
+
272
+ def min_dist(a: np.ndarray, b: np.ndarray) -> float:
273
+ return float(np.linalg.norm(a - b))
274
+
275
+
276
+ def add_interaction(
277
+ interactions: list[dict],
278
+ ligand_id: str,
279
+ feat: dict,
280
+ pcoord: np.ndarray,
281
+ residue_id: str,
282
+ residue_label: str,
283
+ interaction_type: str,
284
+ protein_feature: str,
285
+ atom_name: str,
286
+ ):
287
+ dist = min_dist(feat["coord"], pcoord)
288
+ cutoff = TYPE_CUTOFF[interaction_type]
289
+ if dist <= cutoff:
290
+ interactions.append(
291
+ {
292
+ "ligand_id": ligand_id,
293
+ "interaction_id": "",
294
+ "interaction_type": interaction_type,
295
+ "ligand_feature_id": feat["feature_id"],
296
+ "ligand_family": feat["family"],
297
+ "ligand_atom_ids": ";".join(map(str, feat["atom_ids"])),
298
+ "protein_feature": protein_feature,
299
+ "protein_residue": residue_id,
300
+ "protein_label": residue_label,
301
+ "protein_atom": atom_name,
302
+ "ref_distance": dist,
303
+ "cutoff": cutoff,
304
+ "ligand_x": feat["coord"][0],
305
+ "ligand_y": feat["coord"][1],
306
+ "ligand_z": feat["coord"][2],
307
+ "protein_x": pcoord[0],
308
+ "protein_y": pcoord[1],
309
+ "protein_z": pcoord[2],
310
+ }
311
+ )
312
+
313
+
314
+ def extract_reference_interactions(
315
+ ligand_id: str,
316
+ ref_feats: list[dict],
317
+ protein_atoms: list[ProteinAtom],
318
+ ) -> pd.DataFrame:
319
+ interactions: list[dict] = []
320
+ aromatic_centers = protein_aromatic_centers(protein_atoms)
321
+ for feat in ref_feats:
322
+ family = feat["family"]
323
+ if family == "donor":
324
+ for atom in protein_atoms:
325
+ if atom.element == "O":
326
+ add_interaction(interactions, ligand_id, feat, atom.coord, atom.residue_id, atom.short_label, "hbond", "acceptor", atom.atom_name)
327
+ elif family == "acceptor":
328
+ for atom in protein_atoms:
329
+ if atom.element in {"N", "O"}:
330
+ add_interaction(interactions, ligand_id, feat, atom.coord, atom.residue_id, atom.short_label, "hbond", "donor", atom.atom_name)
331
+ elif family == "hydrophobe":
332
+ for atom in protein_atoms:
333
+ if atom.element in {"C", "S"} and atom.resname in HYDROPHOBIC_RESIDUES:
334
+ add_interaction(interactions, ligand_id, feat, atom.coord, atom.residue_id, atom.short_label, "hydrophobic", "hydrophobic", atom.atom_name)
335
+ elif family == "aromatic":
336
+ for center in aromatic_centers:
337
+ add_interaction(interactions, ligand_id, feat, center["coord"], center["residue_id"], center["residue_label"], "aromatic", "aromatic", center["atom_name"])
338
+ elif family == "positive":
339
+ for atom in protein_atoms:
340
+ if atom.element == "O":
341
+ add_interaction(interactions, ligand_id, feat, atom.coord, atom.residue_id, atom.short_label, "electrostatic", "negative", atom.atom_name)
342
+ elif family == "negative":
343
+ for atom in protein_atoms:
344
+ if atom.element == "N":
345
+ add_interaction(interactions, ligand_id, feat, atom.coord, atom.residue_id, atom.short_label, "electrostatic", "positive", atom.atom_name)
346
+
347
+ if not interactions:
348
+ return pd.DataFrame()
349
+ df = pd.DataFrame(interactions)
350
+ # Keep the nearest contact for each functional feature/residue/type triplet.
351
+ df = (
352
+ df.sort_values(["interaction_type", "ligand_feature_id", "protein_residue", "ref_distance"])
353
+ .drop_duplicates(["interaction_type", "ligand_feature_id", "protein_residue"], keep="first")
354
+ .reset_index(drop=True)
355
+ )
356
+ df = df.sort_values(
357
+ by=["interaction_type", "ref_distance"],
358
+ key=lambda s: s.map(TYPE_PRIORITY) if s.name == "interaction_type" else s,
359
+ ).reset_index(drop=True)
360
+ df["interaction_id"] = [f"{ligand_id}_I{i:03d}" for i in range(len(df))]
361
+ return df
362
+
363
+
364
+ def parse_atom_ids(value: str | float) -> tuple[int, ...]:
365
+ if value is None or (isinstance(value, float) and math.isnan(value)):
366
+ return tuple()
367
+ return tuple(int(x) for x in str(value).split(";") if str(x).strip())
368
+
369
+
370
+ def match_generated_feature(ref_row: pd.Series, gen_feats: list[dict]) -> dict | None:
371
+ ref_family = ref_row["ligand_family"]
372
+ ref_atom_ids = parse_atom_ids(ref_row["ligand_atom_ids"])
373
+ same_family = [f for f in gen_feats if f["family"] == ref_family]
374
+ for feat in same_family:
375
+ if tuple(feat["atom_ids"]) == ref_atom_ids:
376
+ return feat
377
+ if not same_family:
378
+ return None
379
+ ref_coord = np.asarray([ref_row["ligand_x"], ref_row["ligand_y"], ref_row["ligand_z"]], dtype=float)
380
+ return min(same_family, key=lambda f: min_dist(f["coord"], ref_coord))
381
+
382
+
383
+ def score_candidate(ref_interactions: pd.DataFrame, gen_feats: list[dict], topology_tolerance: float) -> dict:
384
+ if ref_interactions.empty:
385
+ return {
386
+ "n_reference_interactions": 0,
387
+ "n_matched_interactions": 0,
388
+ "n_preserved_interactions": 0,
389
+ "interaction_preservation": np.nan,
390
+ "functional_distance_mae": np.nan,
391
+ "pharmacophore_topology_coverage": np.nan,
392
+ }
393
+ errors = []
394
+ preserved = 0
395
+ matched = 0
396
+ for _, row in ref_interactions.iterrows():
397
+ feat = match_generated_feature(row, gen_feats)
398
+ if feat is None:
399
+ continue
400
+ matched += 1
401
+ pcoord = np.asarray([row["protein_x"], row["protein_y"], row["protein_z"]], dtype=float)
402
+ dist = min_dist(feat["coord"], pcoord)
403
+ err = abs(dist - float(row["ref_distance"]))
404
+ errors.append(err)
405
+ if dist <= float(row["cutoff"]):
406
+ preserved += 1
407
+ n_ref = len(ref_interactions)
408
+ if not errors:
409
+ return {
410
+ "n_reference_interactions": n_ref,
411
+ "n_matched_interactions": matched,
412
+ "n_preserved_interactions": 0,
413
+ "interaction_preservation": 0.0,
414
+ "functional_distance_mae": np.nan,
415
+ "pharmacophore_topology_coverage": 0.0,
416
+ }
417
+ errors_arr = np.asarray(errors, dtype=float)
418
+ return {
419
+ "n_reference_interactions": n_ref,
420
+ "n_matched_interactions": matched,
421
+ "n_preserved_interactions": preserved,
422
+ "interaction_preservation": float(preserved / n_ref),
423
+ "functional_distance_mae": float(np.mean(errors_arr)),
424
+ "pharmacophore_topology_coverage": float(np.mean(errors_arr <= topology_tolerance)),
425
+ }
426
+
427
+
428
+ def interaction_distance_errors(ref_interactions: pd.DataFrame, gen_feats: list[dict]) -> dict[str, float | None]:
429
+ """Return one feature--residue distance deviation per reference constraint."""
430
+ errors: dict[str, float | None] = {}
431
+ for _, row in ref_interactions.iterrows():
432
+ feat = match_generated_feature(row, gen_feats)
433
+ if feat is None:
434
+ errors[str(row["interaction_id"])] = None
435
+ continue
436
+ pcoord = np.asarray([row["protein_x"], row["protein_y"], row["protein_z"]], dtype=float)
437
+ errors[str(row["interaction_id"])] = abs(min_dist(feat["coord"], pcoord) - float(row["ref_distance"]))
438
+ return errors
439
+
440
+
441
+ def major_reference_interactions(ref_interactions: pd.DataFrame, max_edges: int = MAJOR_INTERACTIONS_PER_LIGAND) -> pd.DataFrame:
442
+ """Use a small, traceable interaction set for functional-state recovery."""
443
+ if ref_interactions.empty:
444
+ return ref_interactions
445
+ work = ref_interactions.copy()
446
+ work["_priority"] = work["interaction_type"].map(TYPE_PRIORITY).fillna(9)
447
+ return work.sort_values(["_priority", "ref_distance"]).head(max_edges).reset_index(drop=True)
448
+
449
+
450
+ def is_preserved(error: float | None, interaction_type: str) -> bool:
451
+ return error is not None and float(error) <= ENSEMBLE_DISTANCE_TOLERANCE.get(str(interaction_type), 1.0)
452
+
453
+
454
+ def summarize_ensemble_recovery(all_df: pd.DataFrame, ref_interactions: pd.DataFrame, budgets: list[int]) -> pd.DataFrame:
455
+ """Aggregate functional recovery across equal-sized conformer ensembles.
456
+
457
+ EPC is a union over candidates: each crystallographic feature--residue
458
+ constraint is counted once if any candidate in the first K preserves it.
459
+ Functional-state coverage is the best single-candidate coverage of five
460
+ representative constraints; Top-K recovery reports the fraction of ligand
461
+ ensembles with a candidate recovering at least 80% of those constraints.
462
+ """
463
+ rows: list[dict] = []
464
+ for ligand_id, ref_group in ref_interactions.groupby("ligand_id", sort=True):
465
+ constraints = ref_group.set_index("interaction_id")
466
+ major = major_reference_interactions(ref_group).set_index("interaction_id")
467
+ for method, group in all_df[all_df["ligand_id"].eq(ligand_id)].groupby("method", sort=True):
468
+ group = group.sort_values("candidate_index")
469
+ for budget in budgets:
470
+ candidates = group.head(budget)
471
+ if candidates.empty:
472
+ continue
473
+ errors_by_candidate = [json.loads(value) for value in candidates["interaction_errors_json"]]
474
+
475
+ preserved_any = []
476
+ for interaction_id, constraint in constraints.iterrows():
477
+ preserved_any.append(
478
+ any(is_preserved(errors.get(str(interaction_id)), constraint["interaction_type"]) for errors in errors_by_candidate)
479
+ )
480
+ epc = float(np.mean(preserved_any)) if preserved_any else np.nan
481
+
482
+ candidate_major_coverages = []
483
+ candidate_maes = []
484
+ for errors in errors_by_candidate:
485
+ major_hits = [
486
+ is_preserved(errors.get(str(interaction_id)), constraint["interaction_type"])
487
+ for interaction_id, constraint in major.iterrows()
488
+ ]
489
+ candidate_major_coverages.append(float(np.mean(major_hits)) if major_hits else np.nan)
490
+ valid_errors = [float(v) for v in errors.values() if v is not None]
491
+ candidate_maes.append(float(np.mean(valid_errors)) if valid_errors else np.nan)
492
+
493
+ functional_state_coverage = float(np.nanmax(candidate_major_coverages)) if candidate_major_coverages else np.nan
494
+ ensemble_distance_min = float(np.nanmin(candidate_maes)) if candidate_maes else np.nan
495
+ ensemble_distance_mean = float(np.nanmean(candidate_maes)) if candidate_maes else np.nan
496
+ rows.append(
497
+ {
498
+ "ligand_id": ligand_id,
499
+ "method": method,
500
+ "K": int(budget),
501
+ "n_candidates_available": int(len(group)),
502
+ "n_candidates_used": int(len(candidates)),
503
+ "n_reference_interactions": int(len(constraints)),
504
+ "n_major_interactions": int(len(major)),
505
+ "ensemble_pharmacophore_coverage": epc,
506
+ "functional_state_coverage": functional_state_coverage,
507
+ "topk_functional_recovery": float(functional_state_coverage >= FUNCTIONAL_STATE_FRACTION),
508
+ "ensemble_functional_distance_min": ensemble_distance_min,
509
+ "ensemble_functional_distance_mean": ensemble_distance_mean,
510
+ }
511
+ )
512
+ return pd.DataFrame(rows)
513
+
514
+
515
+ def write_ensemble_summary(ensemble_df: pd.DataFrame, output_csv: Path) -> pd.DataFrame:
516
+ summary = (
517
+ ensemble_df.groupby(["method", "K"], sort=True)
518
+ .agg(
519
+ n_ligands=("ligand_id", "count"),
520
+ ensemble_pharmacophore_coverage_mean=("ensemble_pharmacophore_coverage", "mean"),
521
+ ensemble_pharmacophore_coverage_median=("ensemble_pharmacophore_coverage", "median"),
522
+ topk_functional_recovery_mean=("topk_functional_recovery", "mean"),
523
+ functional_state_coverage_mean=("functional_state_coverage", "mean"),
524
+ ensemble_functional_distance_min_mean=("ensemble_functional_distance_min", "mean"),
525
+ ensemble_functional_distance_mean_mean=("ensemble_functional_distance_mean", "mean"),
526
+ )
527
+ .reset_index()
528
+ )
529
+ summary.to_csv(output_csv, index=False)
530
+ return summary
531
+
532
+
533
+ def heavy_atom_best_rmsd(ref_mol, gen_mol) -> float:
534
+ try:
535
+ return float(AllChem.GetBestRMS(Chem.RemoveHs(ref_mol), Chem.RemoveHs(gen_mol)))
536
+ except Exception:
537
+ return np.nan
538
+
539
+
540
+ def candidate_index(path: Path) -> int:
541
+ m = re.search(r"conf_(\d+)", path.name)
542
+ return int(m.group(1)) if m else -1
543
+
544
+
545
+ def iter_candidate_files(root: Path, ligand_id: str, method: str) -> Iterable[Path]:
546
+ placed = root / ligand_id / method / "placed_sdf"
547
+ if placed.exists():
548
+ yield from sorted(placed.glob("conf_*_placed.sdf"), key=candidate_index)
549
+ local = root / ligand_id / method
550
+ if local.exists():
551
+ yield from sorted(local.glob("conf_*_local_only.sdf"), key=candidate_index)
552
+
553
+
554
+ def summarize_best(all_df: pd.DataFrame) -> pd.DataFrame:
555
+ rows = []
556
+ for (ligand_id, method), group in all_df.groupby(["ligand_id", "method"], sort=True):
557
+ group = group.copy()
558
+ best = (
559
+ group.sort_values(
560
+ [
561
+ "interaction_preservation",
562
+ "pharmacophore_topology_coverage",
563
+ "functional_distance_mae",
564
+ "atom_rmsd",
565
+ ],
566
+ ascending=[False, False, True, True],
567
+ na_position="last",
568
+ )
569
+ .iloc[0]
570
+ )
571
+ rows.append(best)
572
+ return pd.DataFrame(rows).reset_index(drop=True)
573
+
574
+
575
+ def safe_mean(x: pd.Series) -> float:
576
+ return float(pd.to_numeric(x, errors="coerce").mean())
577
+
578
+
579
+ def write_summary(best_df: pd.DataFrame, output_csv: Path):
580
+ summary = (
581
+ best_df.groupby("method")
582
+ .agg(
583
+ n=("ligand_id", "count"),
584
+ interaction_preservation_mean=("interaction_preservation", safe_mean),
585
+ interaction_preservation_median=("interaction_preservation", "median"),
586
+ functional_distance_mae_mean=("functional_distance_mae", safe_mean),
587
+ functional_distance_mae_median=("functional_distance_mae", "median"),
588
+ pharmacophore_topology_coverage_mean=("pharmacophore_topology_coverage", safe_mean),
589
+ pharmacophore_topology_coverage_median=("pharmacophore_topology_coverage", "median"),
590
+ atom_rmsd_mean=("atom_rmsd", safe_mean),
591
+ atom_rmsd_median=("atom_rmsd", "median"),
592
+ )
593
+ .reset_index()
594
+ )
595
+ summary.to_csv(output_csv, index=False)
596
+ return summary
597
+
598
+
599
+ def pca_project(points: np.ndarray) -> np.ndarray:
600
+ points = np.asarray(points, dtype=float)
601
+ if len(points) == 0:
602
+ return np.zeros((0, 2), dtype=float)
603
+ centered = points - points.mean(axis=0, keepdims=True)
604
+ if len(points) < 2:
605
+ return np.zeros((len(points), 2), dtype=float)
606
+ _, _, vt = np.linalg.svd(centered, full_matrices=False)
607
+ basis = vt[:2].T
608
+ if basis.shape[1] < 2:
609
+ basis = np.pad(basis, ((0, 0), (0, 2 - basis.shape[1])))
610
+ return centered @ basis
611
+
612
+
613
+ def select_major_interactions(interactions: pd.DataFrame, max_edges: int = 5) -> pd.DataFrame:
614
+ if interactions.empty:
615
+ return interactions
616
+ chosen = []
617
+ work = interactions.copy()
618
+ work["_priority"] = work["interaction_type"].map(TYPE_PRIORITY).fillna(9)
619
+ quotas = {"hbond": 2, "aromatic": 1, "hydrophobic": 2, "electrostatic": 1}
620
+ for itype, quota in quotas.items():
621
+ part = work[work["interaction_type"] == itype].sort_values("ref_distance").head(quota)
622
+ chosen.append(part)
623
+ out = pd.concat(chosen, ignore_index=True) if chosen else pd.DataFrame()
624
+ if len(out) < max_edges:
625
+ used = set(out["interaction_id"]) if not out.empty else set()
626
+ fill = work[~work["interaction_id"].isin(used)].sort_values(["_priority", "ref_distance"]).head(max_edges - len(out))
627
+ out = pd.concat([out, fill], ignore_index=True)
628
+ return out.sort_values(["_priority", "ref_distance"]).head(max_edges).reset_index(drop=True)
629
+
630
+
631
+ def mol_heavy_atom_coords(mol) -> tuple[list[int], np.ndarray]:
632
+ conf = mol.GetConformer()
633
+ atom_ids = [atom.GetIdx() for atom in mol.GetAtoms() if atom.GetAtomicNum() > 1]
634
+ coords = []
635
+ for atom_id in atom_ids:
636
+ p = conf.GetAtomPosition(atom_id)
637
+ coords.append([p.x, p.y, p.z])
638
+ return atom_ids, np.asarray(coords, dtype=float)
639
+
640
+
641
+ def projection_basis(points: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
642
+ points = np.asarray(points, dtype=float)
643
+ center = points.mean(axis=0, keepdims=True)
644
+ centered = points - center
645
+ if len(points) < 2:
646
+ return center, np.eye(3, 2)
647
+ _, _, vt = np.linalg.svd(centered, full_matrices=False)
648
+ basis = vt[:2].T
649
+ if basis.shape[1] < 2:
650
+ basis = np.pad(basis, ((0, 0), (0, 2 - basis.shape[1])))
651
+ return center, basis
652
+
653
+
654
+ def project_with_basis(coords: np.ndarray, center: np.ndarray, basis: np.ndarray) -> np.ndarray:
655
+ return (np.asarray(coords, dtype=float) - center) @ basis
656
+
657
+
658
+ def nearby_protein_atoms(protein_atoms: list[ProteinAtom], ligand_coords: np.ndarray, cutoff: float = 5.5) -> list[ProteinAtom]:
659
+ if len(ligand_coords) == 0:
660
+ return []
661
+ nearby = []
662
+ for atom in protein_atoms:
663
+ if float(np.min(np.linalg.norm(ligand_coords - atom.coord[None, :], axis=1))) <= cutoff:
664
+ nearby.append(atom)
665
+ return nearby
666
+
667
+
668
+ def draw_molecule_projection(ax, mol, center: np.ndarray, basis: np.ndarray, color: str, lw: float = 1.8, alpha: float = 1.0):
669
+ atom_ids, coords = mol_heavy_atom_coords(mol)
670
+ if len(atom_ids) == 0:
671
+ return np.zeros((0, 2), dtype=float)
672
+ id_to_pos = {atom_id: i for i, atom_id in enumerate(atom_ids)}
673
+ xy = project_with_basis(coords, center, basis)
674
+ for bond in mol.GetBonds():
675
+ a = bond.GetBeginAtomIdx()
676
+ b = bond.GetEndAtomIdx()
677
+ if a not in id_to_pos or b not in id_to_pos:
678
+ continue
679
+ p1 = xy[id_to_pos[a]]
680
+ p2 = xy[id_to_pos[b]]
681
+ ax.plot([p1[0], p2[0]], [p1[1], p2[1]], color=color, lw=lw, alpha=alpha, solid_capstyle="round", zorder=4)
682
+ ax.scatter(xy[:, 0], xy[:, 1], s=10 + lw * 6, color=color, edgecolor="white", linewidth=0.25, alpha=alpha, zorder=5)
683
+ return xy
684
+
685
+
686
+ def setup_pocket_projection(ref_mol, protein_atoms: list[ProteinAtom], interactions: pd.DataFrame):
687
+ _, ligand_coords = mol_heavy_atom_coords(ref_mol)
688
+ pocket_atoms = nearby_protein_atoms(protein_atoms, ligand_coords, cutoff=5.5)
689
+ pocket_coords = np.vstack([atom.coord for atom in pocket_atoms]) if pocket_atoms else np.zeros((0, 3), dtype=float)
690
+ interaction_coords = interactions[["ligand_x", "ligand_y", "ligand_z", "protein_x", "protein_y", "protein_z"]].to_numpy(float).reshape(-1, 3)
691
+ all_points = np.vstack([ligand_coords, pocket_coords, interaction_coords]) if len(pocket_coords) else np.vstack([ligand_coords, interaction_coords])
692
+ center, basis = projection_basis(all_points)
693
+ return center, basis, pocket_atoms
694
+
695
+
696
+ def draw_pocket_background(ax, pocket_atoms: list[ProteinAtom], center: np.ndarray, basis: np.ndarray, alpha: float = 0.45):
697
+ if not pocket_atoms:
698
+ return
699
+ coords = np.vstack([atom.coord for atom in pocket_atoms])
700
+ xy = project_with_basis(coords, center, basis)
701
+ ax.scatter(xy[:, 0], xy[:, 1], s=9, color="#C8CDD3", alpha=alpha, linewidths=0, zorder=1)
702
+ # A very light envelope gives a pocket cue without pretending to be a rendered surface.
703
+ if len(xy) > 3:
704
+ lo = xy.min(axis=0)
705
+ hi = xy.max(axis=0)
706
+ width, height = hi - lo
707
+ ellipse = mpl.patches.Ellipse(
708
+ xy=(lo + hi) / 2,
709
+ width=max(width * 1.10, 0.5),
710
+ height=max(height * 1.10, 0.5),
711
+ facecolor="#EEF0F3",
712
+ edgecolor="none",
713
+ alpha=0.32,
714
+ zorder=0,
715
+ )
716
+ ax.add_patch(ellipse)
717
+
718
+
719
+ def draw_contact_lines(ax, interactions: pd.DataFrame, center: np.ndarray, basis: np.ndarray, label_limit: int = 4):
720
+ if interactions.empty:
721
+ return
722
+ lig = interactions[["ligand_x", "ligand_y", "ligand_z"]].to_numpy(float)
723
+ prot = interactions[["protein_x", "protein_y", "protein_z"]].to_numpy(float)
724
+ lig2 = project_with_basis(lig, center, basis)
725
+ prot2 = project_with_basis(prot, center, basis)
726
+ for i, (_, row) in enumerate(interactions.iterrows()):
727
+ color = COLORS.get(row["interaction_type"], "#777777")
728
+ ax.plot([lig2[i, 0], prot2[i, 0]], [lig2[i, 1], prot2[i, 1]], color=color, lw=0.9, linestyle=(0, (2, 2)), alpha=0.85, zorder=3)
729
+ mid = (lig2[i] + prot2[i]) / 2
730
+ if i < label_limit:
731
+ ax.text(mid[0], mid[1], f"{row['ref_distance']:.1f} Å", fontsize=5.8, color="#444444", ha="center", va="center")
732
+ ax.text(prot2[i, 0] + 0.05, prot2[i, 1] + 0.05, row["protein_label"], fontsize=6.4, color="#536273", weight="semibold")
733
+ ax.scatter(prot2[:, 0], prot2[:, 1], s=28, color="#D4DAE0", edgecolor="#85909A", linewidth=0.35, zorder=2)
734
+
735
+
736
+ def draw_interaction_projection(
737
+ ax,
738
+ interactions: pd.DataFrame,
739
+ ref_mol,
740
+ protein_atoms: list[ProteinAtom],
741
+ title: str,
742
+ ligand_color: str,
743
+ max_edges: int = 5,
744
+ ):
745
+ if interactions.empty:
746
+ ax.text(0.5, 0.5, "No reference contacts", ha="center", va="center", transform=ax.transAxes)
747
+ ax.set_axis_off()
748
+ return
749
+ chosen = select_major_interactions(interactions, max_edges=max_edges)
750
+ center, basis, pocket_atoms = setup_pocket_projection(ref_mol, protein_atoms, chosen)
751
+ draw_pocket_background(ax, pocket_atoms, center, basis, alpha=0.42)
752
+ draw_molecule_projection(ax, ref_mol, center, basis, ligand_color, lw=2.0, alpha=0.96)
753
+ draw_contact_lines(ax, chosen, center, basis, label_limit=5)
754
+ ax.set_title(title, loc="left", fontsize=8.5, weight="semibold")
755
+ ax.set_axis_off()
756
+ ax.margins(0.12)
757
+
758
+
759
+ def draw_graph_abstraction(ax, interactions: pd.DataFrame):
760
+ ax.set_title("b Functional graph abstraction", loc="left", fontsize=8.5, weight="semibold")
761
+ if interactions.empty:
762
+ ax.set_axis_off()
763
+ return
764
+ chosen = interactions.copy()
765
+ chosen["_priority"] = chosen["interaction_type"].map(TYPE_PRIORITY).fillna(9)
766
+ chosen = chosen.sort_values(["_priority", "ref_distance"]).head(6)
767
+ theta_l = np.linspace(0.25 * np.pi, 1.75 * np.pi, len(chosen))
768
+ theta_p = np.linspace(-0.25 * np.pi, 1.25 * np.pi, len(chosen))
769
+ lig_xy = np.c_[0.35 + 0.18 * np.cos(theta_l), 0.50 + 0.32 * np.sin(theta_l)]
770
+ prot_xy = np.c_[0.72 + 0.16 * np.cos(theta_p), 0.50 + 0.32 * np.sin(theta_p)]
771
+ family_label = {"donor": "HBD", "acceptor": "HBA", "hydrophobe": "Hyd", "aromatic": "Aro", "positive": "+", "negative": "-"}
772
+ for i, (_, row) in enumerate(chosen.iterrows()):
773
+ itype = row["interaction_type"]
774
+ ax.plot([lig_xy[i, 0], prot_xy[i, 0]], [lig_xy[i, 1], prot_xy[i, 1]], color=COLORS.get(itype, "#777"), lw=0.9, alpha=0.75)
775
+ mid = (lig_xy[i] + prot_xy[i]) / 2
776
+ ax.text(mid[0], mid[1] + 0.015, f"{row['ref_distance']:.1f}", fontsize=6, color="#444", ha="center")
777
+ ax.scatter(lig_xy[:, 0], lig_xy[:, 1], s=170, color="#EFE7F6", edgecolor="#8E4BBE", lw=0.8, zorder=3)
778
+ ax.scatter(prot_xy[:, 0], prot_xy[:, 1], s=170, color="#EEF1F4", edgecolor="#7D8791", lw=0.8, zorder=3)
779
+ for i, (_, row) in enumerate(chosen.iterrows()):
780
+ ax.text(lig_xy[i, 0], lig_xy[i, 1], family_label.get(row["ligand_family"], row["ligand_family"][:3]), fontsize=6.5, ha="center", va="center")
781
+ ax.text(prot_xy[i, 0], prot_xy[i, 1], row["protein_label"], fontsize=6.5, ha="center", va="center")
782
+ ax.text(0.35, 0.08, "Ligand features", ha="center", fontsize=7, color="#555")
783
+ ax.text(0.72, 0.08, "Protein residues", ha="center", fontsize=7, color="#555")
784
+ ax.set_xlim(0.05, 0.95)
785
+ ax.set_ylim(0.02, 0.98)
786
+ ax.set_axis_off()
787
+
788
+
789
+ def transformed_generated_interactions(ref_interactions: pd.DataFrame, gen_feats: list[dict]) -> pd.DataFrame:
790
+ rows = []
791
+ for _, row in ref_interactions.iterrows():
792
+ feat = match_generated_feature(row, gen_feats)
793
+ if feat is None:
794
+ continue
795
+ new = row.copy()
796
+ new["ligand_x"], new["ligand_y"], new["ligand_z"] = feat["coord"]
797
+ pcoord = np.asarray([row["protein_x"], row["protein_y"], row["protein_z"]], dtype=float)
798
+ new["ref_distance"] = min_dist(feat["coord"], pcoord)
799
+ rows.append(new)
800
+ return pd.DataFrame(rows)
801
+
802
+
803
+ def draw_representative_comparison(ax, rep_data: dict):
804
+ ax.set_title("c Representative conformer comparison", loc="left", fontsize=8.5, weight="semibold")
805
+ sub = ax.inset_axes([0.01, 0.06, 0.98, 0.84])
806
+ sub.set_axis_off()
807
+ ref_interactions = rep_data["ref_interactions"]
808
+ all_points = np.vstack(
809
+ [
810
+ ref_interactions[["ligand_x", "ligand_y", "ligand_z"]].to_numpy(float),
811
+ ref_interactions[["protein_x", "protein_y", "protein_z"]].to_numpy(float),
812
+ ]
813
+ )
814
+ center = all_points.mean(axis=0, keepdims=True)
815
+ _, _, vt = np.linalg.svd(all_points - center, full_matrices=False)
816
+ basis = vt[:2].T
817
+
818
+ def project(inter_df: pd.DataFrame):
819
+ lig = inter_df[["ligand_x", "ligand_y", "ligand_z"]].to_numpy(float)
820
+ prot = inter_df[["protein_x", "protein_y", "protein_z"]].to_numpy(float)
821
+ return (lig - center) @ basis, (prot - center) @ basis
822
+
823
+ methods = [
824
+ ("Crystal", "reference", ref_interactions, None),
825
+ ("ETKDG", "etkdg", rep_data.get("etkdg_interactions"), rep_data.get("etkdg_score")),
826
+ ("MANIMOL", "manimol", rep_data.get("manimol_interactions"), rep_data.get("manimol_score")),
827
+ ]
828
+ for col, (label, method, inter_df, score) in enumerate(methods):
829
+ iax = sub.inset_axes([col / 3 + 0.02, 0.02, 0.29, 0.92])
830
+ iax.set_axis_off()
831
+ if inter_df is None or inter_df.empty:
832
+ continue
833
+ chosen = inter_df.copy()
834
+ chosen["_priority"] = chosen["interaction_type"].map(TYPE_PRIORITY).fillna(9)
835
+ chosen = chosen.sort_values(["_priority", "ref_distance"]).head(5)
836
+ lig2, prot2 = project(chosen)
837
+ for i, (_, row) in enumerate(chosen.iterrows()):
838
+ color = COLORS.get(row["interaction_type"], "#777")
839
+ iax.plot([lig2[i, 0], prot2[i, 0]], [lig2[i, 1], prot2[i, 1]], color=color, lw=0.8, linestyle=(0, (2, 2)), alpha=0.7)
840
+ iax.scatter(prot2[:, 0], prot2[:, 1], s=30, color="#D9DEE4", edgecolor="#8A939D", lw=0.4)
841
+ iax.scatter(lig2[:, 0], lig2[:, 1], s=54, color=COLORS[method], edgecolor="white", lw=0.55)
842
+ for i, (_, row) in enumerate(chosen.head(3).iterrows()):
843
+ iax.text(prot2[i, 0] + 0.05, prot2[i, 1] + 0.05, row["protein_label"], fontsize=5.7, color="#5C6875")
844
+ iax.set_title(label, fontsize=7.5, color=COLORS[method], pad=1.5)
845
+ if score is not None:
846
+ iax.text(
847
+ 0.5,
848
+ -0.02,
849
+ f"IPS {score['interaction_preservation']:.2f}\nMAE {score['functional_distance_mae']:.2f} Å\nCov {score['pharmacophore_topology_coverage']:.2f}",
850
+ transform=iax.transAxes,
851
+ ha="center",
852
+ va="top",
853
+ fontsize=5.8,
854
+ color="#333333",
855
+ )
856
+ iax.margins(0.18)
857
+ ax.text(0.02, 0.00, rep_data["ligand_id"], transform=ax.transAxes, fontsize=6.5, color="#444")
858
+ ax.set_axis_off()
859
+
860
+
861
+ def plot_summary_figure(
862
+ best_df: pd.DataFrame,
863
+ ref_interactions: pd.DataFrame,
864
+ all_df: pd.DataFrame,
865
+ output_prefix: Path,
866
+ representative_ligand: str,
867
+ ):
868
+ mpl.rcParams.update(
869
+ {
870
+ "font.family": "sans-serif",
871
+ "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"],
872
+ "svg.fonttype": "none",
873
+ "pdf.fonttype": 42,
874
+ "font.size": 7,
875
+ "axes.spines.top": False,
876
+ "axes.spines.right": False,
877
+ "axes.linewidth": 0.7,
878
+ }
879
+ )
880
+ present = set(best_df["method"])
881
+ ordered = ["etkdg", "etflow", "manimol", "manimol_geometry", "manimol_functional"]
882
+ methods = [m for m in ordered if m in present] + sorted(present - set(ordered))
883
+
884
+ rep_ligand = representative_ligand
885
+ if rep_ligand not in set(ref_interactions["ligand_id"]):
886
+ rep_ligand = str(ref_interactions.iloc[0]["ligand_id"])
887
+ rep_ref = ref_interactions[ref_interactions["ligand_id"] == rep_ligand]
888
+ ref_mol = read_first_mol(Path(str(rep_ref.iloc[0]["reference_ligand_sdf"])))
889
+ protein_atoms = read_protein_atoms(Path(str(rep_ref.iloc[0]["receptor_pdb"])))
890
+
891
+ rep_data = {"ligand_id": rep_ligand, "ref_interactions": rep_ref}
892
+ for method in ["etkdg", "manimol"]:
893
+ row = best_df[(best_df["ligand_id"] == rep_ligand) & (best_df["method"] == method)]
894
+ if row.empty:
895
+ continue
896
+ mol = read_first_mol(Path(row.iloc[0]["candidate_file"]))
897
+ if mol is None:
898
+ continue
899
+ factory = get_factory()
900
+ gen_feats = ligand_features(mol, factory)
901
+ rep_data[f"{method}_interactions"] = transformed_generated_interactions(rep_ref, gen_feats)
902
+ rep_data[f"{method}_score"] = row.iloc[0].to_dict()
903
+
904
+ fig = plt.figure(figsize=(7.2, 6.4), dpi=300)
905
+ gs = fig.add_gridspec(2, 2, height_ratios=[0.95, 1.05], width_ratios=[1.0, 1.15], hspace=0.28, wspace=0.25)
906
+ ax_a = fig.add_subplot(gs[0, 0])
907
+ ax_b = fig.add_subplot(gs[0, 1])
908
+ ax_c = fig.add_subplot(gs[1, 0])
909
+ ax_d = fig.add_subplot(gs[1, 1])
910
+
911
+ draw_interaction_projection(ax_a, rep_ref, ref_mol, protein_atoms, "a Reference interaction extraction", "#D7B84F", max_edges=5)
912
+ draw_graph_abstraction(ax_b, rep_ref)
913
+ draw_representative_comparison(ax_c, rep_data)
914
+
915
+ ax_d.set_title("d Functional-geometry preservation", loc="left", fontsize=8.5, weight="semibold")
916
+ ax_d.set_axis_off()
917
+ metrics = [
918
+ ("interaction_preservation", "IPS ↑", (0, 1.05)),
919
+ ("functional_distance_mae", "Distance MAE (Å) ↓", None),
920
+ ("pharmacophore_topology_coverage", "Topology cov. ↑", (0, 1.05)),
921
+ ]
922
+ rng = np.random.default_rng(20260731)
923
+ width = 0.22 if len(methods) == 3 else 0.28
924
+ offsets = np.linspace(-width, width, len(methods))
925
+ for xi, (metric, label, ylim) in enumerate(metrics):
926
+ iax = ax_d.inset_axes([0.01 + xi * 0.33, 0.14, 0.29, 0.74])
927
+ for mi, method in enumerate(methods):
928
+ vals = best_df.loc[best_df["method"] == method, metric].dropna().to_numpy(float)
929
+ if not len(vals):
930
+ continue
931
+ x = 0 + offsets[mi]
932
+ color = method_color(method)
933
+ iax.boxplot(
934
+ [vals],
935
+ positions=[x],
936
+ widths=width * 0.78,
937
+ patch_artist=True,
938
+ showfliers=False,
939
+ boxprops={"facecolor": "white", "edgecolor": color, "linewidth": 1.0},
940
+ medianprops={"color": "#333333", "linewidth": 1.0},
941
+ whiskerprops={"color": "#777777", "linewidth": 0.8},
942
+ capprops={"color": "#777777", "linewidth": 0.8},
943
+ )
944
+ jitter = rng.normal(0, width * 0.08, len(vals))
945
+ iax.scatter(np.full(len(vals), x) + jitter, vals, s=10, color=color, alpha=0.45, linewidths=0)
946
+ iax.set_xlim(-0.45, 0.45)
947
+ iax.set_xticks([])
948
+ iax.set_title(label, fontsize=7.2, pad=2)
949
+ if ylim is not None:
950
+ iax.set_ylim(*ylim)
951
+ iax.grid(axis="y", color="#E8E8E8", linewidth=0.55)
952
+ iax.tick_params(axis="y", labelsize=6.2, width=0.6, length=2.5)
953
+ iax.spines["left"].set_color("#666666")
954
+ iax.spines["bottom"].set_visible(False)
955
+ legend_handles = [
956
+ plt.Line2D([0], [0], marker="o", color="none", markerfacecolor=method_color(m), markeredgecolor="none", markersize=5, label=method_label(m))
957
+ for m in methods
958
+ ]
959
+ ax_d.legend(handles=legend_handles, loc="lower center", bbox_to_anchor=(0.5, -0.08), ncol=len(methods), frameon=False)
960
+
961
+ fig.text(
962
+ 0.02,
963
+ 0.015,
964
+ "Protein-contact pharmacophore analysis tests whether generated conformers preserve binding-relevant feature-residue distances.",
965
+ fontsize=7,
966
+ color="#333333",
967
+ )
968
+ fig.savefig(output_prefix.with_suffix(".png"), bbox_inches="tight", dpi=600)
969
+ fig.savefig(output_prefix.with_suffix(".pdf"), bbox_inches="tight")
970
+ fig.savefig(output_prefix.with_suffix(".svg"), bbox_inches="tight")
971
+
972
+
973
+ def main():
974
+ parser = argparse.ArgumentParser(description="Protein-contact-aware HIF2A pharmacophore preservation analysis.")
975
+ parser.add_argument("--manifest", default="outputs/docking/hif2a_conformers/docking_manifest_manimol_xtb.csv")
976
+ parser.add_argument("--placed_root", default="outputs/docking/hif2a_preorganized_vina_score_only_xtb")
977
+ parser.add_argument("--output_dir", default="outputs/docking/hif2a_contact_pharmacophore")
978
+ parser.add_argument("--methods", default="etkdg,etflow,manimol")
979
+ parser.add_argument("--topology_tolerance", type=float, default=1.5)
980
+ parser.add_argument("--ensemble_budgets", default="5,10,20", help="Comma-separated equal candidate budgets for ensemble analysis.")
981
+ parser.add_argument("--max_ligands", type=int, default=0)
982
+ parser.add_argument("--representative_ligand", default="hif2a_lig019")
983
+ args, _ = parser.parse_known_args()
984
+
985
+ manifest = pd.read_csv(args.manifest)
986
+ if args.max_ligands > 0:
987
+ manifest = manifest.head(args.max_ligands)
988
+ methods = [m.strip().lower() for m in args.methods.split(",") if m.strip()]
989
+ ensemble_budgets = sorted({int(v) for v in args.ensemble_budgets.split(",") if v.strip()})
990
+ if not ensemble_budgets or min(ensemble_budgets) < 1:
991
+ raise ValueError("--ensemble_budgets must contain positive integers.")
992
+ out_dir = Path(args.output_dir)
993
+ out_dir.mkdir(parents=True, exist_ok=True)
994
+ factory = get_factory()
995
+
996
+ reference_rows = []
997
+ candidate_rows = []
998
+ for _, entry in manifest.iterrows():
999
+ ligand_id = str(entry["complex_id"])
1000
+ ref_path = Path(str(entry.get("crystal_ligand_sdf", entry["ligand_sdf"])))
1001
+ receptor_path = Path(str(entry["receptor_pdb"]))
1002
+ ref_mol = read_first_mol(ref_path)
1003
+ if ref_mol is None or not receptor_path.exists():
1004
+ continue
1005
+ protein_atoms = read_protein_atoms(receptor_path)
1006
+ ref_feats = ligand_features(ref_mol, factory)
1007
+ ref_df = extract_reference_interactions(ligand_id, ref_feats, protein_atoms)
1008
+ if ref_df.empty:
1009
+ continue
1010
+ ref_df["ligand_name"] = entry.get("ligand_name", ligand_id)
1011
+ ref_df["ligand_smiles"] = entry.get("ligand_smiles", "")
1012
+ ref_df["reference_ligand_sdf"] = str(ref_path)
1013
+ ref_df["receptor_pdb"] = str(receptor_path)
1014
+ reference_rows.append(ref_df)
1015
+
1016
+ for method in methods:
1017
+ for cand_path in iter_candidate_files(Path(args.placed_root), ligand_id, method):
1018
+ mol = read_first_mol(cand_path)
1019
+ if mol is None:
1020
+ continue
1021
+ gen_feats = ligand_features(mol, factory)
1022
+ scores = score_candidate(ref_df, gen_feats, args.topology_tolerance)
1023
+ interaction_errors = interaction_distance_errors(ref_df, gen_feats)
1024
+ candidate_rows.append(
1025
+ {
1026
+ "ligand_id": ligand_id,
1027
+ "ligand_name": entry.get("ligand_name", ligand_id),
1028
+ "method": method,
1029
+ "candidate_index": candidate_index(cand_path),
1030
+ "candidate_file": str(cand_path),
1031
+ "atom_rmsd": heavy_atom_best_rmsd(ref_mol, mol),
1032
+ "interaction_errors_json": json.dumps(interaction_errors, sort_keys=True),
1033
+ **scores,
1034
+ }
1035
+ )
1036
+
1037
+ if not reference_rows:
1038
+ raise RuntimeError("No reference protein-contact pharmacophore interactions were extracted.")
1039
+ if not candidate_rows:
1040
+ raise RuntimeError(f"No candidate SDFs found under {args.placed_root}.")
1041
+
1042
+ ref_df = pd.concat(reference_rows, ignore_index=True)
1043
+ all_df = pd.DataFrame(candidate_rows)
1044
+ best_df = summarize_best(all_df)
1045
+ summary_df = write_summary(best_df, out_dir / "hif2a_contact_pharmacophore_summary_by_method.csv")
1046
+ ensemble_df = summarize_ensemble_recovery(all_df, ref_df, ensemble_budgets)
1047
+ ensemble_summary_df = write_ensemble_summary(
1048
+ ensemble_df,
1049
+ out_dir / "hif2a_contact_pharmacophore_ensemble_summary_by_method.csv",
1050
+ )
1051
+
1052
+ ref_csv = out_dir / "hif2a_reference_contact_pharmacophore.csv"
1053
+ all_csv = out_dir / "hif2a_contact_pharmacophore_all_candidates.csv"
1054
+ best_csv = out_dir / "hif2a_contact_pharmacophore_best_per_ligand.csv"
1055
+ ensemble_csv = out_dir / "hif2a_contact_pharmacophore_ensemble_per_ligand.csv"
1056
+ ref_df.to_csv(ref_csv, index=False)
1057
+ all_df.to_csv(all_csv, index=False)
1058
+ best_df.to_csv(best_csv, index=False)
1059
+ ensemble_df.to_csv(ensemble_csv, index=False)
1060
+
1061
+ plot_summary_figure(best_df, ref_df, all_df, out_dir / "hif2a_contact_pharmacophore_figure", args.representative_ligand)
1062
+
1063
+ config = {
1064
+ "manifest": args.manifest,
1065
+ "placed_root": args.placed_root,
1066
+ "methods_requested": methods,
1067
+ "methods_found": sorted(best_df["method"].unique().tolist()),
1068
+ "topology_tolerance_A": args.topology_tolerance,
1069
+ "ensemble_budgets": ensemble_budgets,
1070
+ "ensemble_interaction_distance_tolerances_A": ENSEMBLE_DISTANCE_TOLERANCE,
1071
+ "functional_state_definition": (
1072
+ f"best candidate among the first K preserves at least {FUNCTIONAL_STATE_FRACTION:.0%} "
1073
+ f"of the {MAJOR_INTERACTIONS_PER_LIGAND} highest-priority crystal-derived interactions"
1074
+ ),
1075
+ "interaction_cutoffs_A": TYPE_CUTOFF,
1076
+ "selection_rule": "best functional-geometry candidate per ligand and method: maximize IPS, then topology coverage, then minimize distance MAE",
1077
+ "additional_ligand_optimization": False,
1078
+ "representative_ligand": args.representative_ligand,
1079
+ "note": "ET-Flow is included only when receptor-frame placed ET-Flow SDF files are present under the placed root.",
1080
+ }
1081
+ (out_dir / "hif2a_contact_pharmacophore_config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
1082
+
1083
+ print(f"Saved: {ref_csv}")
1084
+ print(f"Saved: {all_csv}")
1085
+ print(f"Saved: {best_csv}")
1086
+ print(f"Saved: {ensemble_csv}")
1087
+ print(f"Saved: {out_dir / 'hif2a_contact_pharmacophore_summary_by_method.csv'}")
1088
+ print(f"Saved: {out_dir / 'hif2a_contact_pharmacophore_ensemble_summary_by_method.csv'}")
1089
+ print(f"Saved: {out_dir / 'hif2a_contact_pharmacophore_figure.png'}")
1090
+ print(f"Saved: {out_dir / 'hif2a_contact_pharmacophore_figure.pdf'}")
1091
+ print(f"Saved: {out_dir / 'hif2a_contact_pharmacophore_figure.svg'}")
1092
+ for _, row in summary_df.iterrows():
1093
+ print(
1094
+ f"{row['method']}: n={int(row['n'])} "
1095
+ f"IPS={row['interaction_preservation_mean']:.3f} "
1096
+ f"MAE={row['functional_distance_mae_mean']:.3f} "
1097
+ f"TopoCov={row['pharmacophore_topology_coverage_mean']:.3f} "
1098
+ f"AtomRMSD={row['atom_rmsd_mean']:.3f}"
1099
+ )
1100
+ for _, row in ensemble_summary_df.iterrows():
1101
+ print(
1102
+ f"{row['method']} K={int(row['K'])}: "
1103
+ f"EPC={row['ensemble_pharmacophore_coverage_mean']:.3f} "
1104
+ f"TopK={row['topk_functional_recovery_mean']:.3f} "
1105
+ f"StateCov={row['functional_state_coverage_mean']:.3f} "
1106
+ f"MinMAE={row['ensemble_functional_distance_min_mean']:.3f}"
1107
+ )
1108
+
1109
+
1110
+ if __name__ == "__main__":
1111
+ main()