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,83 @@
1
+ #!/usr/bin/env python3
2
+ """Run a fixed 20-molecule, four-checkpoint diagnostic on one GPU."""
3
+
4
+ import json
5
+ import os
6
+ import subprocess
7
+ import time
8
+ from pathlib import Path
9
+
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ BASE = ROOT / "results/stage1_stage2_crosscheck_20260919/pilot20_lowref_x1"
13
+ SOURCE = ROOT / "results/pdisp_intervention_pilot_20260915/protocol_manifest.json"
14
+ OLD = "results/stage2_fixed_ab_rankloss_merged/best.pth"
15
+ NEW = "dump/0915-stage2_full_gated_sharded_ddp_20260915/stage2_full_gated_sharded_ddp_20260915/rank0/best.pth"
16
+ CHECKPOINTS = (
17
+ ("old_prior_old_decoder", OLD),
18
+ ("old_prior_new_decoder", "results/stage1_stage2_crosscheck_20260919/old_prior_new_decoder.pth"),
19
+ ("new_prior_old_decoder", "results/stage1_stage2_crosscheck_20260919/new_prior_old_decoder.pth"),
20
+ ("new_prior_new_decoder", NEW),
21
+ )
22
+
23
+
24
+ def command(label, checkpoint, output):
25
+ args = list(json.loads(SOURCE.read_text())["commands"]["normal"])
26
+ updates = {
27
+ "--base_checkpoint": checkpoint,
28
+ "--checkpoint": checkpoint,
29
+ "--pbasin_checkpoint": checkpoint,
30
+ "--test_process_limit": "20",
31
+ "--limit_molecules": "20",
32
+ "--oversample_factor": "1",
33
+ "--rdkit_rmsd_max_matches": "1000",
34
+ "--data_root": "/mnt/liyong/route2_diag20_lowref_data",
35
+ "--test_raw_filename": "geom_drugs_test_diagnostic20_lowref.pt",
36
+ "--method_name": label,
37
+ "--output_dir": str(output),
38
+ "--per_molecule_csv": str(output / "per_molecule.csv"),
39
+ "--revisited_metrics_csv": str(output / "chemistry.csv"),
40
+ "--threshold_curve_csv": str(output / "curve.csv"),
41
+ }
42
+ for key, value in updates.items():
43
+ args[args.index(key) + 1] = value
44
+ args.extend(("--save_raw_pool_pt", str(output / "raw_pool.pt")))
45
+ return args
46
+
47
+
48
+ def main():
49
+ os.chdir(ROOT)
50
+ BASE.mkdir(parents=True, exist_ok=True)
51
+ manifest = {
52
+ "source_manifest": str(SOURCE),
53
+ "cohort": "frozen low-reference-count GEOM-Drugs diagnostic20 manifest",
54
+ "cohort_manifest": str(ROOT / "results/stage1_stage2_crosscheck_20260919/diagnostic20_lowref_manifest.json"),
55
+ "candidate_budget": "2R, no oversampling",
56
+ "retained_budget": "2R",
57
+ "rmsd_backend": "rdkit_best",
58
+ "rdkit_max_matches": 1000,
59
+ "gpu": os.environ.get("CUDA_VISIBLE_DEVICES"),
60
+ "purpose": "diagnostic only, not manuscript benchmark",
61
+ "runs": {},
62
+ }
63
+ for label, checkpoint in CHECKPOINTS:
64
+ output = BASE / label
65
+ output.mkdir(parents=True, exist_ok=True)
66
+ args = command(label, checkpoint, output)
67
+ manifest["runs"][label] = args
68
+ (BASE / "protocol_manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
69
+ if all((output / filename).exists() for filename in ("curve.csv", "per_molecule.csv", "raw_pool.pt")):
70
+ print(f"SKIP completed {label}", flush=True)
71
+ continue
72
+ start = time.time()
73
+ print(f"RUN {label}", flush=True)
74
+ with (output / "run.log").open("w") as log:
75
+ result = subprocess.run(args, env=os.environ.copy(), stdout=log, stderr=subprocess.STDOUT)
76
+ print(f"DONE {label}: exit={result.returncode}, minutes={(time.time() - start) / 60:.1f}", flush=True)
77
+ if result.returncode:
78
+ raise SystemExit(result.returncode)
79
+ (BASE / "COMPLETE").write_text("Four matched checkpoint combinations completed.\n")
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
@@ -0,0 +1,221 @@
1
+ #!/usr/bin/env python3
2
+ """Attach fixed-pool Normal/Shuffled/Random P scores to HIF2A candidates."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+ from types import SimpleNamespace
9
+
10
+ import pandas as pd
11
+ import torch
12
+ from rdkit import Chem
13
+ from rdkit.Chem import AllChem
14
+ from torch_geometric.data import Batch, Data
15
+
16
+ import sys
17
+
18
+ ROOT = Path(__file__).resolve().parents[1]
19
+ sys.path.insert(0, str(ROOT))
20
+
21
+ import infer_base_conformers
22
+ import infer_torsional_denoiser
23
+ from dataset.drugdataset import build_torsion_index, enrich_edge_attr_with_bond_flags
24
+ from dataset.smiles2graph import smile2graph4GEOM
25
+ from pgraph_controls import controlled_pglobal
26
+ from scripts.analyze_hif2a_contact_pharmacophore import read_first_mol
27
+
28
+
29
+ def model_args(args: argparse.Namespace) -> SimpleNamespace:
30
+ return SimpleNamespace(
31
+ checkpoint=args.checkpoint,
32
+ base_checkpoint=args.checkpoint,
33
+ denoiser_checkpoint=args.denoiser_checkpoint,
34
+ post_denoiser_checkpoint="",
35
+ pbasin_checkpoint="",
36
+ disable_probability_guidance=True,
37
+ device=args.device,
38
+ max_confs=args.max_confs,
39
+ num_modes=args.num_modes,
40
+ deterministic_modes=True,
41
+ )
42
+
43
+
44
+ def load_first_mol(path: str):
45
+ supplier = Chem.SDMolSupplier(str(path), removeHs=False)
46
+ mol = next((value for value in supplier if value is not None), None)
47
+ if mol is None:
48
+ raise RuntimeError(f"Could not read ligand SDF: {path}")
49
+ return mol
50
+
51
+
52
+ def mol_to_data(mol, ligand_id: str) -> Data:
53
+ if mol.GetNumConformers() == 0:
54
+ params = AllChem.ETKDGv3()
55
+ params.randomSeed = 2026
56
+ if AllChem.EmbedMolecule(mol, params) != 0:
57
+ raise RuntimeError(f"RDKit embedding failed for {ligand_id}")
58
+ smiles = Chem.MolToSmiles(Chem.RemoveHs(Chem.Mol(mol)), isomericSmiles=True)
59
+ pos = torch.tensor(mol.GetConformer(0).GetPositions(), dtype=torch.float32)
60
+ x, edge_index, edge_attr, vdw_radii = smile2graph4GEOM({"rdmol": mol, "smiles": smiles})
61
+ edge_attr = enrich_edge_attr_with_bond_flags(mol, edge_index, edge_attr)
62
+ data = Data(
63
+ x=x.clone(),
64
+ edge_index=edge_index.clone(),
65
+ edge_attr=edge_attr.clone(),
66
+ torsion_index=build_torsion_index(mol).clone(),
67
+ pos=pos,
68
+ smiles=smiles,
69
+ mol_key=f"{smiles}__{mol.GetNumAtoms()}",
70
+ mol_id=torch.tensor(0, dtype=torch.long),
71
+ conf_id=torch.tensor(0, dtype=torch.long),
72
+ idx=torch.tensor(0, dtype=torch.long),
73
+ num_atoms=torch.tensor(mol.GetNumAtoms(), dtype=torch.long),
74
+ num_confs_of_mol=torch.tensor(1, dtype=torch.long),
75
+ rdmol=mol,
76
+ rdmol_embedded=mol,
77
+ vdw_radii=vdw_radii,
78
+ )
79
+ data.batch_num_nodes = data.num_nodes
80
+ return data
81
+
82
+
83
+ def build_model(args: SimpleNamespace):
84
+ exp_args = SimpleNamespace(**vars(args))
85
+ defaults = {
86
+ "denoise_polish_steps": 0,
87
+ "denoise_polish_sigma": 0.03,
88
+ "denoise_polish_step_scale": 0.35,
89
+ "denoise_precision_fraction": 0.0,
90
+ "denoise_precision_steps": 0,
91
+ "denoise_precision_sigma_max": 0.45,
92
+ "denoise_precision_sigma_min": 0.02,
93
+ "denoise_precision_step_scale": 0.65,
94
+ "denoise_precision_initial_noise": 0.45,
95
+ "final_snap_steps": 0,
96
+ "final_snap_sigma": 0.015,
97
+ "final_snap_step_scale": 0.18,
98
+ "final_snap_max_candidates": 0,
99
+ "final_snap_use_post_denoiser": False,
100
+ "final_snap_keep_original": True,
101
+ "manifold_use_mode_p": False,
102
+ "pbudget_adaptive": False,
103
+ "pbudget_min_fraction": 0.2,
104
+ "pbudget_max_fraction": 0.75,
105
+ "pbudget_confidence_scale": 2.0,
106
+ "pbasin_anchor_gate": False,
107
+ "pbasin_anchor_gate_keep_fraction": 0.75,
108
+ "pbasin_anchor_gate_threshold": 0.9,
109
+ "pbasin_anchor_gate_min_keep_fraction": 0.5,
110
+ "pbasin_anchor_gate_max_anchors": 8,
111
+ "disable_stage1_pglobal": False,
112
+ "pglobal_control": "normal",
113
+ "pglobal_noise_std": 0.0,
114
+ "pglobal_seed": 2026,
115
+ "stage1_kernel": "umap",
116
+ "base_checkpoint": args.base_checkpoint,
117
+ }
118
+ for key, value in defaults.items():
119
+ if not hasattr(exp_args, key):
120
+ setattr(exp_args, key, value)
121
+ cli_args = SimpleNamespace(
122
+ checkpoint=args.checkpoint,
123
+ max_confs=int(args.max_confs),
124
+ num_modes=args.num_modes,
125
+ deterministic_modes=args.deterministic_modes,
126
+ use_mode_specific_p=False,
127
+ mode_p_delta_scale=1.0,
128
+ use_torsion_residual=False,
129
+ torsion_residual_max=32,
130
+ torsion_residual_scale=1.0,
131
+ )
132
+ return infer_torsional_denoiser.patched_load_model_factory(exp_args)(args.checkpoint, args.device, cli_args)
133
+
134
+
135
+ def predict_graph(model, batch: Batch, mol, kernel: str) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
136
+ core = infer_base_conformers._unwrap_manifold_model(model)
137
+ device = next(core.parameters()).device
138
+ batch = batch.to(device)
139
+ with torch.no_grad():
140
+ node_feat = core.gnn(batch)
141
+ graph_feat = core.pool(node_feat, batch.batch)
142
+ mask = batch.batch == 0
143
+ local_feat = node_feat[mask]
144
+ edge_index = core._get_local_edge_index(edge_index=batch.edge_index, mask=mask)
145
+ learned, _ = core._predict_P_global(local_feat, edge_index)
146
+ a, b = core.predict_ab(graph_feat[0], conf_idx=0)
147
+ return learned.detach(), a.detach(), b.detach()
148
+
149
+
150
+ def candidate_score(coords: torch.Tensor, target: torch.Tensor, a: torch.Tensor, b: torch.Tensor, kernel: str) -> float:
151
+ q = infer_base_conformers.prob_low_dim_kernel(coords, a, b, kernel=kernel).clamp(1e-6, 1.0 - 1e-6)
152
+ return -float(infer_base_conformers.cross_entropy_loss(q, target.clamp(1e-6, 1.0 - 1e-6)).detach().cpu())
153
+
154
+
155
+ def main() -> None:
156
+ parser = argparse.ArgumentParser()
157
+ parser.add_argument("--candidate_csv", required=True)
158
+ parser.add_argument("--manifest", required=True)
159
+ parser.add_argument("--checkpoint", required=True)
160
+ parser.add_argument("--denoiser_checkpoint", required=True)
161
+ parser.add_argument("--output_csv", required=True)
162
+ parser.add_argument("--methods", default="manimol")
163
+ parser.add_argument("--device", default="cuda")
164
+ parser.add_argument("--max_confs", type=int, default=0)
165
+ parser.add_argument("--num_modes", type=int, default=10)
166
+ parser.add_argument("--kernel", default="umap")
167
+ parser.add_argument("--seed", type=int, default=20260825)
168
+ args = parser.parse_args()
169
+
170
+ if args.max_confs == 0:
171
+ args.max_confs = infer_base_conformers.checkpoint_max_confs(args.checkpoint)
172
+ data = pd.read_csv(args.candidate_csv)
173
+ manifest = pd.read_csv(args.manifest).set_index("complex_id")
174
+ enabled = {value.strip().lower() for value in args.methods.split(",") if value.strip()}
175
+ model = build_model(model_args(args))
176
+ device = next(infer_base_conformers._unwrap_manifold_model(model).parameters()).device
177
+ score_columns = ["normal_p_score", "shuffled_p_score", "random_p_score"]
178
+ for column in score_columns:
179
+ data[column] = float("nan")
180
+
181
+ for ligand_id, indices in data.groupby("ligand_id", sort=True).groups.items():
182
+ if ligand_id not in manifest.index:
183
+ continue
184
+ ligand_path = manifest.loc[ligand_id].get("ligand_sdf")
185
+ if not isinstance(ligand_path, str) or not Path(ligand_path).exists():
186
+ crystal = manifest.loc[ligand_id].get("crystal_ligand_sdf")
187
+ ligand_path = crystal if isinstance(crystal, str) else ligand_path
188
+ mol = load_first_mol(ligand_path)
189
+ batch = Batch.from_data_list([mol_to_data(mol, ligand_id)])
190
+ learned, a, b = predict_graph(model, batch, mol, args.kernel)
191
+ targets = {}
192
+ for control in ("normal", "shuffle", "random"):
193
+ control_args = SimpleNamespace(
194
+ pglobal_control=control,
195
+ pglobal_seed=args.seed,
196
+ disable_stage1_pglobal=False,
197
+ )
198
+ targets[control] = controlled_pglobal(learned, control_args, mol=mol).to(device)
199
+
200
+ for index in indices:
201
+ row = data.loc[index]
202
+ if str(row["method"]).lower() not in enabled:
203
+ continue
204
+ candidate = read_first_mol(Path(str(row["candidate_file"])))
205
+ if candidate is None or candidate.GetNumAtoms() != learned.size(0):
206
+ continue
207
+ coords = torch.tensor(candidate.GetConformer().GetPositions(), dtype=learned.dtype, device=device)
208
+ data.at[index, "normal_p_score"] = candidate_score(coords, targets["normal"], a, b, args.kernel)
209
+ data.at[index, "shuffled_p_score"] = candidate_score(coords, targets["shuffle"], a, b, args.kernel)
210
+ data.at[index, "random_p_score"] = candidate_score(coords, targets["random"], a, b, args.kernel)
211
+ print(f"scored {ligand_id}")
212
+
213
+ output = Path(args.output_csv)
214
+ output.parent.mkdir(parents=True, exist_ok=True)
215
+ data.to_csv(output, index=False)
216
+ print(data.groupby("method")[score_columns].count().to_string())
217
+ print(f"Saved {output}")
218
+
219
+
220
+ if __name__ == "__main__":
221
+ main()
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env python3
2
+ """Summarize matched P_disp interventions from auditable inference outputs."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import json
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ from scipy.stats import pearsonr, spearmanr
12
+
13
+
14
+ def mean_metric(rows, prefix):
15
+ vals = [float(row[prefix]) for row in rows if row.get(prefix, "") not in {"", "nan"}]
16
+ return float(np.mean(vals)) if vals else None
17
+
18
+
19
+ def width_summary(path):
20
+ try:
21
+ import torch
22
+ payload = torch.load(path, map_location="cpu", weights_only=False)
23
+ except Exception:
24
+ return {"n_width_records": 0, "width_spread_pearson": None, "width_spread_spearman": None}
25
+ widths, scores = [], []
26
+ for record in payload.get("records", []):
27
+ w = record.get("dispersion_torsion_widths")
28
+ s = record.get("dispersion_torsion_scores")
29
+ if w is None or s is None:
30
+ continue
31
+ w, s = np.asarray(w, dtype=float).reshape(-1), np.asarray(s, dtype=float).reshape(-1)
32
+ n = min(len(w), len(s))
33
+ mask = np.isfinite(w[:n]) & np.isfinite(s[:n])
34
+ widths.extend(w[:n][mask]); scores.extend(s[:n][mask])
35
+ if len(widths) < 3 or np.ptp(widths) == 0 or np.ptp(scores) == 0:
36
+ return {"n_width_records": len(widths), "width_spread_pearson": None, "width_spread_spearman": None}
37
+ return {"n_width_records": len(widths),
38
+ "width_spread_pearson": float(pearsonr(scores, widths).statistic),
39
+ "width_spread_spearman": float(spearmanr(scores, widths).statistic)}
40
+
41
+
42
+ def main():
43
+ p = argparse.ArgumentParser()
44
+ p.add_argument("--root", type=Path, required=True)
45
+ p.add_argument("--output", type=Path, default=None)
46
+ args = p.parse_args()
47
+ rows_by_mode = {}
48
+ for mode in ("normal", "constant", "shuffle", "random"):
49
+ path = args.root / f"{mode}_per_molecule.csv"
50
+ if not path.exists():
51
+ continue
52
+ with path.open() as handle:
53
+ rows_by_mode[mode] = list(csv.DictReader(handle))
54
+ if not rows_by_mode:
55
+ raise FileNotFoundError(f"No intervention CSVs found under {args.root}")
56
+ summary = {"root": str(args.root), "controls": {}, "paired_differences": []}
57
+ for mode, rows in rows_by_mode.items():
58
+ summary["controls"][mode] = {
59
+ "n_molecules": len(rows),
60
+ "cov_r_t0p75": mean_metric(rows, "cov_r_t0p75"),
61
+ "amr_r_t0p75": mean_metric(rows, "amr_r_t0p75"),
62
+ "cov_p_t0p75": mean_metric(rows, "cov_p_t0p75"),
63
+ "amr_p_t0p75": mean_metric(rows, "amr_p_t0p75"),
64
+ **width_summary(args.root / f"{mode}/raw_pool.pt"),
65
+ }
66
+ if "normal" in rows_by_mode:
67
+ base = {r["mol_id"]: r for r in rows_by_mode["normal"]}
68
+ for mode, rows in rows_by_mode.items():
69
+ if mode == "normal":
70
+ continue
71
+ for row in rows:
72
+ ref = base.get(row["mol_id"])
73
+ if ref is None:
74
+ continue
75
+ summary["paired_differences"].append({
76
+ "mol_id": row["mol_id"], "control": mode,
77
+ "delta_cov_r_t0p75": float(row["cov_r_t0p75"]) - float(ref["cov_r_t0p75"]),
78
+ "delta_amr_r_t0p75": float(row["amr_r_t0p75"]) - float(ref["amr_r_t0p75"]),
79
+ "delta_cov_p_t0p75": float(row["cov_p_t0p75"]) - float(ref["cov_p_t0p75"]),
80
+ "delta_amr_p_t0p75": float(row["amr_p_t0p75"]) - float(ref["amr_p_t0p75"]),
81
+ })
82
+ output = args.output or args.root / "dispersion_intervention_summary.json"
83
+ output.write_text(json.dumps(summary, indent=2))
84
+ print(json.dumps(summary, indent=2))
85
+
86
+
87
+ if __name__ == "__main__":
88
+ main()
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env python3
2
+ """Small deterministic tests for the isolated mean--dispersion bridge."""
3
+ from __future__ import annotations
4
+
5
+ import importlib.util
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import torch
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ if str(ROOT) not in sys.path:
13
+ sys.path.insert(0, str(ROOT))
14
+
15
+ _spec = importlib.util.spec_from_file_location(
16
+ "mean_dispersion_bridge", ROOT / "models/mean_dispersion_bridge.py"
17
+ )
18
+ _module = importlib.util.module_from_spec(_spec)
19
+ assert _spec.loader is not None
20
+ _spec.loader.exec_module(_module)
21
+ dispersion_to_width = _module.dispersion_to_width
22
+ torsion_context_statistics = _module.torsion_context_statistics
23
+
24
+
25
+ def main():
26
+ mean = torch.tensor([
27
+ [0.0, 0.9, 0.2, 0.8],
28
+ [0.9, 0.0, 0.7, 0.1],
29
+ [0.2, 0.7, 0.0, 0.6],
30
+ [0.8, 0.1, 0.6, 0.0],
31
+ ])
32
+ disp = torch.tensor([
33
+ [0.0, 0.01, 0.02, 0.03],
34
+ [0.01, 0.0, 0.04, 0.05],
35
+ [0.02, 0.04, 0.0, 0.06],
36
+ [0.03, 0.05, 0.06, 0.0],
37
+ ])
38
+ torsions = torch.tensor([[0, 1, 2, 3]])
39
+ labels = torch.tensor([0, 0, 1, 1])
40
+ mu, var = torsion_context_statistics(mean, disp, torsions, fragment_labels=labels)
41
+ width = dispersion_to_width(var)
42
+ assert mu.shape == var.shape == width.shape == (1,)
43
+ assert torch.allclose(mean, mean.t())
44
+ assert torch.all((width >= 0.10) & (width <= 0.75))
45
+ print({"torsion_mean": mu.tolist(), "torsion_dispersion": var.tolist(), "width": width.tolist()})
46
+ print("mean-dispersion bridge: PASS")
47
+
48
+
49
+ if __name__ == "__main__":
50
+ main()