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
manimol/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ """ConforMend utilities and the checkpoint-backed full inference runtime."""
2
+
3
+ from .legacy_imports import install_legacy_imports
4
+
5
+ install_legacy_imports()
6
+
7
+ from .priors import ensemble_pairwise_prior
8
+ from .runtime import ConforMend, ManiMol, run_full_inference
9
+ from .selection import density_centrality_select, pairwise_rmsd
10
+ from .torsion import circular_standard_deviation, wrap_angle
11
+ from .postprocess import fps_indices, mmff94s_window_fps, select_energy_window
12
+
13
+ # ``ManiMol`` remains a compatibility alias for existing checkpoints and
14
+ # downstream scripts released before the rename.
15
+
16
+ __all__ = [
17
+ "circular_standard_deviation",
18
+ "density_centrality_select",
19
+ "ensemble_pairwise_prior",
20
+ "ManiMol",
21
+ "ConforMend",
22
+ "pairwise_rmsd",
23
+ "fps_indices",
24
+ "select_energy_window",
25
+ "mmff94s_window_fps",
26
+ "run_full_inference",
27
+ "wrap_angle",
28
+ ]
29
+
30
+ __version__ = "0.2.8"
manimol/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ from .full_cli import main
2
+
3
+
4
+ if __name__ == "__main__":
5
+ main()
6
+
manimol/cli.py ADDED
@@ -0,0 +1,36 @@
1
+ """Command-line entry point for reference-free representative selection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+
10
+ from .selection import density_centrality_select
11
+
12
+
13
+ def main() -> None:
14
+ parser = argparse.ArgumentParser(
15
+ description="Select a compact, diverse conformer library from an .npy array."
16
+ )
17
+ parser.add_argument("input", type=Path, help=".npy file: (n_conformers, n_atoms, 3)")
18
+ parser.add_argument("-k", type=int, required=True, help="number of representatives")
19
+ parser.add_argument("-o", "--output", type=Path, required=True, help="output index .npy file")
20
+ parser.add_argument("--alpha", type=float, default=1.0)
21
+ parser.add_argument("--beta", type=float, default=0.45)
22
+ parser.add_argument("--duplicate-radius", type=float, default=0.04)
23
+ args = parser.parse_args()
24
+
25
+ conformers = np.load(args.input)
26
+ indices = density_centrality_select(
27
+ conformers,
28
+ args.k,
29
+ alpha=args.alpha,
30
+ beta=args.beta,
31
+ duplicate_radius=args.duplicate_radius,
32
+ )
33
+ args.output.parent.mkdir(parents=True, exist_ok=True)
34
+ np.save(args.output, indices)
35
+ print(f"selected {len(indices)} / {len(conformers)} conformers")
36
+ print(f"indices written to {args.output}")
manimol/full_cli.py ADDED
@@ -0,0 +1,41 @@
1
+ """Console entry point for the full checkpoint-backed ConforMend pipeline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+
8
+ def _ensure_default_oversampling(argv):
9
+ """Add the package default without overriding an explicit user value."""
10
+ argv = list(argv)
11
+ if not any(
12
+ item == "--oversample_factor" or item.startswith("--oversample_factor=")
13
+ for item in argv
14
+ ):
15
+ argv.extend(["--oversample_factor", "15"])
16
+ return argv
17
+
18
+
19
+ def main() -> None:
20
+ if "--help" in sys.argv[1:] or "-h" in sys.argv[1:]:
21
+ print(
22
+ "DualMapRef checkpoint-backed inference\n\n"
23
+ "Usage: dualmapref-infer --protocol mean_dispersion_denoising "
24
+ "--base_checkpoint PATH --data_root DIR "
25
+ "[--denoiser_checkpoint PATH | --pbasin_only] "
26
+ "[inference options]\n\n"
27
+ "Install dualmapref[full] to run the complete PyTorch/RDKit pipeline. "
28
+ "The underlying inference parser exposes additional options in that environment."
29
+ )
30
+ return
31
+ from .runtime import run_full_inference
32
+
33
+ # The benchmark implementation has its own complete argparse surface.
34
+ # Keep this wrapper transparent and append the package default only when
35
+ # the caller did not choose a budget explicitly.
36
+ argv = _ensure_default_oversampling(sys.argv[1:])
37
+ run_full_inference(argv)
38
+
39
+
40
+ if __name__ == "__main__":
41
+ main()
@@ -0,0 +1,43 @@
1
+ """Load historical module names after importing :mod:`manimol`.
2
+
3
+ Some older Python-serialized checkpoints contain module-qualified class names.
4
+ This adapter preserves those names without keeping numbered implementation files.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import importlib
9
+ import importlib.abc
10
+ import importlib.util
11
+ import sys
12
+
13
+ LEGACY_MODULES = {
14
+ "manimol_stage1": "train_graph_encoder",
15
+ "train2": "train_torsion_generator",
16
+ "train5": "train_torsional_denoiser",
17
+ "train7": "train_local_torsion_corrector",
18
+ "train8": "train_probability_basin",
19
+ "infer1": "infer_base_conformers",
20
+ "infer_torsion5": "infer_torsional_denoiser",
21
+ }
22
+
23
+ class _AliasLoader(importlib.abc.Loader):
24
+ def __init__(self, target: str):
25
+ self.target = target
26
+
27
+ def create_module(self, spec):
28
+ return importlib.import_module(self.target)
29
+
30
+ def exec_module(self, module):
31
+ pass
32
+
33
+ class _LegacyFinder(importlib.abc.MetaPathFinder):
34
+ def find_spec(self, fullname, path, target=None):
35
+ replacement = LEGACY_MODULES.get(fullname)
36
+ if replacement is None:
37
+ return None
38
+ return importlib.util.spec_from_loader(fullname, _AliasLoader(replacement))
39
+
40
+ def install_legacy_imports():
41
+ """Register old-to-new aliases for this process, without importing ML modules."""
42
+ if not any(isinstance(finder, _LegacyFinder) for finder in sys.meta_path):
43
+ sys.meta_path.insert(0, _LegacyFinder())
manimol/manifest.py ADDED
@@ -0,0 +1,56 @@
1
+ """Run-manifest helpers for reproducible public inference."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import platform
8
+ import sys
9
+ from datetime import datetime, timezone
10
+ from pathlib import Path
11
+ from typing import Any, Mapping
12
+
13
+
14
+ def sha256_file(path: str | Path, chunk_size: int = 1024 * 1024) -> str:
15
+ digest = hashlib.sha256()
16
+ with Path(path).open("rb") as handle:
17
+ for chunk in iter(lambda: handle.read(chunk_size), b""):
18
+ digest.update(chunk)
19
+ return digest.hexdigest()
20
+
21
+
22
+ def write_run_manifest(
23
+ output_dir: str | Path,
24
+ *,
25
+ protocol: str,
26
+ argv: list[str],
27
+ checkpoint: str,
28
+ data_root: str,
29
+ status: str = "started",
30
+ defaults: Mapping[str, Any] | None = None,
31
+ ) -> Path:
32
+ """Write a stable JSON manifest without serializing private data."""
33
+
34
+ destination = Path(output_dir).expanduser()
35
+ destination.mkdir(parents=True, exist_ok=True)
36
+ checkpoint_path = Path(checkpoint).expanduser()
37
+ payload = {
38
+ "schema_version": 1,
39
+ "status": status,
40
+ "protocol": protocol,
41
+ "argv": list(argv),
42
+ "defaults": dict(defaults or {}),
43
+ "checkpoint": {
44
+ "path": str(checkpoint_path),
45
+ "sha256": sha256_file(checkpoint_path),
46
+ },
47
+ "data_root": str(Path(data_root).expanduser()),
48
+ "runtime": {
49
+ "python": sys.version,
50
+ "platform": platform.platform(),
51
+ },
52
+ "timestamp_utc": datetime.now(timezone.utc).isoformat(),
53
+ }
54
+ path = destination / "manifest.json"
55
+ path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
56
+ return path
manimol/postprocess.py ADDED
@@ -0,0 +1,148 @@
1
+ """Deterministic fixed-budget post-processing for generated conformer pools.
2
+
3
+ The public protocol mirrors the paper's selected inference preparation:
4
+ MMFF94s optimization, a relative 5 kcal/mol energy window, farthest-point
5
+ selection (FPS), and a final MMFF94s optimization. Model checkpoints and
6
+ dataset records remain external to the package.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Sequence
12
+
13
+ import numpy as np
14
+
15
+
16
+ def _validate_coords(coords: np.ndarray) -> np.ndarray:
17
+ array = np.asarray(coords, dtype=float)
18
+ if array.ndim != 3 or array.shape[-1] != 3:
19
+ raise ValueError("coords must have shape (n_conformers, n_atoms, 3)")
20
+ if array.shape[0] == 0:
21
+ raise ValueError("coords must contain at least one conformer")
22
+ if not np.isfinite(array).all():
23
+ raise ValueError("coords must contain only finite values")
24
+ return array
25
+
26
+
27
+ def _centered_rmsd(left: np.ndarray, right: np.ndarray) -> float:
28
+ left_centered = left - left.mean(axis=0, keepdims=True)
29
+ right_centered = right - right.mean(axis=0, keepdims=True)
30
+ return float(np.sqrt(np.mean((left_centered - right_centered) ** 2)))
31
+
32
+
33
+ def fps_indices(coords: np.ndarray, target_count: int, *, start: int = 0) -> np.ndarray:
34
+ """Select a deterministic farthest-point subset using centered RMSD.
35
+
36
+ Parameters
37
+ ----------
38
+ coords:
39
+ Array with shape ``(n_conformers, n_atoms, 3)``.
40
+ target_count:
41
+ Number of conformers to retain. Values larger than the pool size are
42
+ clipped to the available pool.
43
+ start:
44
+ Initial conformer index; the default gives stable, order-independent
45
+ behavior for a fixed candidate pool.
46
+ """
47
+
48
+ array = _validate_coords(coords)
49
+ if int(target_count) <= 0:
50
+ raise ValueError("target_count must be positive")
51
+ count = min(int(target_count), array.shape[0])
52
+ start_index = int(start)
53
+ if not 0 <= start_index < array.shape[0]:
54
+ raise ValueError("start must index an available conformer")
55
+
56
+ centered = array - array.mean(axis=1, keepdims=True)
57
+ distances = np.sqrt(
58
+ np.mean((centered[:, None, :, :] - centered[None, :, :, :]) ** 2, axis=(2, 3))
59
+ )
60
+ selected = [start_index]
61
+ nearest = distances[start_index].copy()
62
+ nearest[start_index] = -np.inf
63
+ while len(selected) < count:
64
+ candidate = int(np.argmax(nearest))
65
+ selected.append(candidate)
66
+ nearest = np.minimum(nearest, distances[candidate])
67
+ nearest[selected] = -np.inf
68
+ return np.asarray(selected, dtype=np.int64)
69
+
70
+
71
+ def select_energy_window(energies: Sequence[float], window_kcal: float = 5.0) -> np.ndarray:
72
+ """Return indices within a relative energy window from the minimum."""
73
+
74
+ values = np.asarray(energies, dtype=float)
75
+ if values.ndim != 1 or values.size == 0:
76
+ raise ValueError("energies must be a non-empty one-dimensional array")
77
+ if window_kcal < 0:
78
+ raise ValueError("window_kcal must be non-negative")
79
+ finite = np.isfinite(values)
80
+ if not finite.any():
81
+ raise ValueError("energies contain no finite values")
82
+ minimum = float(values[finite].min())
83
+ return np.flatnonzero(finite & (values <= minimum + float(window_kcal)))
84
+
85
+
86
+ def mmff94s_window_fps(
87
+ conformers,
88
+ mol,
89
+ target_count: int,
90
+ *,
91
+ window_kcal: float = 5.0,
92
+ max_steps: int = 80,
93
+ final_mmff94s: bool = True,
94
+ ):
95
+ """Apply the selected fixed-budget MMFF94s/energy-window/FPS protocol.
96
+
97
+ ``conformers`` is a Torch tensor or an array with shape ``(N, A, 3)`` and
98
+ ``mol`` is an RDKit molecule containing matching atom coordinates. The
99
+ return value is a Torch tensor on CPU, matching the repository inference
100
+ artifact convention. Invalid MMFF candidates are excluded; if the
101
+ energy window contains fewer than the requested budget, the lowest finite
102
+ energy candidates refill the budget before FPS.
103
+ """
104
+
105
+ try:
106
+ import torch
107
+ import infer_base_conformers
108
+ except ImportError as exc: # pragma: no cover - exercised in full extra
109
+ raise ImportError(
110
+ "mmff94s_window_fps requires the 'manimol[full]' dependencies"
111
+ ) from exc
112
+
113
+ pool = conformers.detach().cpu() if hasattr(conformers, "detach") else torch.as_tensor(conformers)
114
+ if pool.ndim != 3 or pool.shape[-1] != 3 or pool.shape[0] == 0:
115
+ raise ValueError("conformers must have shape (n_conformers, n_atoms, 3)")
116
+ budget = min(int(target_count), int(pool.shape[0]))
117
+ if budget <= 0:
118
+ raise ValueError("target_count must be positive")
119
+
120
+ prepared, energies = [], []
121
+ for conformer in pool:
122
+ optimized, energy, valid = infer_base_conformers.optimize_with_mmff94s_and_energy(
123
+ conformer, mol, max_steps=int(max_steps)
124
+ )
125
+ prepared.append(optimized)
126
+ energies.append(float(energy) if valid else float("inf"))
127
+ prepared = torch.stack(prepared)
128
+ energies_np = np.asarray(energies, dtype=float)
129
+ window_idx = select_energy_window(energies_np, window_kcal=window_kcal)
130
+ if window_idx.size < budget:
131
+ finite_idx = np.flatnonzero(np.isfinite(energies_np))
132
+ refill = finite_idx[np.argsort(energies_np[finite_idx])[:budget]]
133
+ candidate_idx = np.asarray(refill, dtype=np.int64)
134
+ else:
135
+ candidate_idx = window_idx
136
+ chosen_idx = fps_indices(prepared[candidate_idx].numpy(), budget)
137
+ selected = prepared[candidate_idx[chosen_idx]]
138
+ if final_mmff94s:
139
+ selected = torch.stack(
140
+ [
141
+ infer_base_conformers.optimize_with_mmff94s_and_energy(conf, mol, max_steps=int(max_steps))[0]
142
+ for conf in selected
143
+ ]
144
+ )
145
+ return selected.cpu()
146
+
147
+
148
+ __all__ = ["fps_indices", "select_energy_window", "mmff94s_window_fps"]
manimol/priors.py ADDED
@@ -0,0 +1,60 @@
1
+ """Ensemble-level pairwise proximity and dispersion utilities.
2
+
3
+ These functions operate on already aligned Cartesian conformers. They do not
4
+ rank individual conformers and intentionally contain no model or dataset code.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+ from .selection import pairwise_rmsd
12
+
13
+
14
+ def ensemble_pairwise_prior(
15
+ conformers: np.ndarray,
16
+ *,
17
+ scale: float = 1.0,
18
+ ) -> tuple[np.ndarray, np.ndarray]:
19
+ """Return mean proximity and dispersion over an aligned conformer ensemble.
20
+
21
+ Parameters
22
+ ----------
23
+ conformers:
24
+ Array with shape ``(n_conformers, n_atoms, 3)``.
25
+ scale:
26
+ Positive length scale for the proximity kernel in the same units as
27
+ the coordinates, commonly Angstrom.
28
+
29
+ Returns
30
+ -------
31
+ mean, dispersion:
32
+ Two ``(n_atoms, n_atoms)`` arrays. Proximity is
33
+ ``exp(-RMSD_pair / scale)``; dispersion is its population variance
34
+ across the ensemble. Diagonal entries are zero.
35
+ """
36
+
37
+ data = _validate_conformers(conformers)
38
+ if scale <= 0:
39
+ raise ValueError("scale must be positive")
40
+ # Pairwise atom distances are measured across conformers, not between
41
+ # whole conformers: each atom pair receives an ensemble-level signal.
42
+ deltas = data[:, :, None, :] - data[:, None, :, :]
43
+ distances = np.sqrt(np.sum(deltas * deltas, axis=-1))
44
+ proximity = np.exp(-distances / float(scale))
45
+ mean = proximity.mean(axis=0)
46
+ dispersion = proximity.var(axis=0)
47
+ np.fill_diagonal(mean, 0.0)
48
+ np.fill_diagonal(dispersion, 0.0)
49
+ return mean, dispersion
50
+
51
+
52
+ def _validate_conformers(conformers: np.ndarray) -> np.ndarray:
53
+ data = np.asarray(conformers, dtype=float)
54
+ if data.ndim != 3 or data.shape[-1] != 3:
55
+ raise ValueError("conformers must have shape (n_conformers, n_atoms, 3)")
56
+ if data.shape[0] == 0 or data.shape[1] == 0:
57
+ raise ValueError("conformers must contain at least one conformer and atom")
58
+ if not np.isfinite(data).all():
59
+ raise ValueError("conformers must contain only finite coordinates")
60
+ return data
manimol/protocols.py ADDED
@@ -0,0 +1,119 @@
1
+ """Validated public inference protocols.
2
+
3
+ The research entry point has a large argparse surface. This module keeps the
4
+ small public preset in one place so the CLI and Python API cannot silently
5
+ drift apart.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ from pathlib import Path
12
+ from typing import Iterable, Mapping, Sequence
13
+
14
+
15
+ MEAN_DISPERSION_DENOISING = "mean_dispersion_denoising"
16
+ ROUTE2_PAPER = "route2_paper" # Legacy alias; kept for existing commands.
17
+
18
+
19
+ def mean_dispersion_denoising_defaults() -> dict[str, object]:
20
+ """Return the validated, reference-free route-2 inference defaults."""
21
+
22
+ return {
23
+ "max_confs": 0, # infer checkpoint embedding size unless explicitly overridden
24
+ "oversample_factor": 15.0,
25
+ "select_candidates": "stable_fps_088",
26
+ "stable_displacement_quantile": 0.88,
27
+ "precision2r_density_k": 20,
28
+ "precision2r_prefilter_quantile": 0.45,
29
+ "precision2r_density_weight": 1.0,
30
+ "precision2r_centrality_weight": 0.45,
31
+ "precision2r_duplicate_radius": 0.04,
32
+ "use_dispersion_proposal": True,
33
+ "deterministic_modes": True,
34
+ "use_mmff": True,
35
+ "mmff_steps": 200,
36
+ "use_torsion_refine": True,
37
+ "use_etkdg": True,
38
+ "etkdg_candidate_pool": True,
39
+ "output_dedup_radius": 0.0,
40
+ }
41
+
42
+
43
+ def route2_paper_defaults() -> dict[str, object]:
44
+ """Backward-compatible alias for historical callers."""
45
+ return mean_dispersion_denoising_defaults()
46
+
47
+
48
+ def validate_external_artifacts(
49
+ checkpoint: str,
50
+ data_root: str,
51
+ denoiser_checkpoint: str = "",
52
+ ) -> None:
53
+ """Fail early with actionable messages for external runtime artifacts."""
54
+
55
+ checkpoint_path = Path(checkpoint).expanduser()
56
+ data_path = Path(data_root).expanduser()
57
+ if not checkpoint_path.is_file():
58
+ raise FileNotFoundError(f"MANIMOL checkpoint does not exist: {checkpoint_path}")
59
+ if not data_path.is_dir():
60
+ raise FileNotFoundError(f"MANIMOL data_root does not exist or is not a directory: {data_path}")
61
+ if denoiser_checkpoint:
62
+ denoiser_path = Path(denoiser_checkpoint).expanduser()
63
+ if not denoiser_path.is_file():
64
+ raise FileNotFoundError(f"MANIMOL denoiser checkpoint does not exist: {denoiser_path}")
65
+
66
+
67
+ def _value_after(argv: Sequence[str], name: str, default: str = "") -> str:
68
+ for index, item in enumerate(argv):
69
+ if item == name and index + 1 < len(argv):
70
+ return str(argv[index + 1])
71
+ if item.startswith(name + "="):
72
+ return item.split("=", 1)[1]
73
+ return default
74
+
75
+
76
+ def _has_flag(argv: Sequence[str], name: str) -> bool:
77
+ return name in argv or any(item.startswith(name + "=") for item in argv)
78
+
79
+
80
+ def prepare_protocol_argv(argv: Iterable[str]) -> tuple[list[str], str, dict[str, object]]:
81
+ """Apply a public protocol while preserving explicit CLI overrides."""
82
+
83
+ raw = list(argv)
84
+ parser = argparse.ArgumentParser(add_help=False)
85
+ parser.add_argument("--protocol", default=MEAN_DISPERSION_DENOISING)
86
+ protocol_args, remaining = parser.parse_known_args(raw)
87
+ protocol = str(protocol_args.protocol)
88
+ if protocol not in (MEAN_DISPERSION_DENOISING, ROUTE2_PAPER):
89
+ raise ValueError(f"Unknown MANIMOL protocol: {protocol!r}; expected {MEAN_DISPERSION_DENOISING!r}")
90
+
91
+ defaults = mean_dispersion_denoising_defaults()
92
+ prepared = list(remaining)
93
+ for key, value in defaults.items():
94
+ flag = "--" + key
95
+ if _has_flag(prepared, flag):
96
+ continue
97
+ if isinstance(value, bool):
98
+ if value:
99
+ prepared.append(flag)
100
+ else:
101
+ prepared.extend([flag, str(value)])
102
+
103
+ checkpoint = _value_after(prepared, "--base_checkpoint")
104
+ data_root = _value_after(prepared, "--data_root")
105
+ denoiser = _value_after(prepared, "--denoiser_checkpoint")
106
+ if not checkpoint:
107
+ raise ValueError("mean_dispersion_denoising requires --base_checkpoint")
108
+ if not data_root:
109
+ raise ValueError("mean_dispersion_denoising requires --data_root")
110
+ validate_external_artifacts(checkpoint, data_root, denoiser)
111
+ # The underlying parser requires the same base model as --checkpoint.
112
+ if not _has_flag(prepared, "--checkpoint"):
113
+ prepared.extend(["--checkpoint", checkpoint])
114
+ if not denoiser and not _has_flag(prepared, "--pbasin_only"):
115
+ raise ValueError(
116
+ "mean_dispersion_denoising requires --denoiser_checkpoint, or explicitly pass --pbasin_only "
117
+ "for Stage-II-only inference"
118
+ )
119
+ return prepared, protocol, defaults