diff --git a/.claude/skills/implement-rgi/SKILL.md b/.claude/skills/implement-rgi/SKILL.md index c0e10d2..b627586 100644 --- a/.claude/skills/implement-rgi/SKILL.md +++ b/.claude/skills/implement-rgi/SKILL.md @@ -4,8 +4,7 @@ description: >- Integrate Restraint-Guided Inference (RGI) into a diffusion-based structure predictor using rgi_toolkit. Use when adding or porting guided sampling, distance, group-angle, group-dihedral, ligand-conformer, VdW, RMSD, or custom - restraints to boltz, protenix, OpenDDE, chai-lab, openfold-3, esmfold2, AlphaFold3, or - a similar sampler. Implement only the framework adapter, sampling-loop hooks, + restraints to a structure predictor. Implement only the framework adapter, sampling-loop hooks, and restraints_config pass-through; do not duplicate energy, optimization, config, or selection logic in the tool. --- @@ -66,7 +65,7 @@ tools drift out of parity. If you find yourself writing a restraint dataclass, an energy term, or an atom-selection parser in the tool, stop and use the rgi_toolkit one instead. -## Implementation — 3 steps +## Implementation ### Step 1 — Install (the backend is inferred, not configured) @@ -89,7 +88,7 @@ mechanism when available. It is a deliberate placement choice, and both options identically at runtime because the rgi_toolkit adapter protocol is duck-typed (no base class, no registration): -- **In rgi_toolkit** (`rgi_toolkit//adapter.py`) — the convention all seven existing tools +- **In rgi_toolkit** (`rgi_toolkit//adapter.py`) — the convention all eleven existing integrations follow; centralizes parity-critical code in one repo (one place to review the `resid` convention / a protocol tweak). Needs the adapter to be framework-free (plain dict/array in), so any irreducibly framework-coupled step (CCD/SMILES mol resolution, atom-name @@ -168,7 +167,8 @@ reference for "how small this should be." ## Framework selection -- **PyTorch (eager loop)** — boltz, protenix, OpenDDE, chai-lab, openfold-3, esmfold2. The +- **PyTorch (eager loop)** — boltz, protenix, OpenDDE, chai-lab, openfold-3, esmfold2, + RF3, BioEmu2, and Mol-1. The adapter lives in `rgi_toolkit//adapter.py` (it receives a plain dict/array and imports no framework code — **except boltz**, whose feats arrive as native torch tensors so its adapter imports torch, read at batch 0). Call `minimize` each step. @@ -177,12 +177,21 @@ reference for "how small this should be." (openfold-3 → take geometry from the reference-conformer feature), or real coords but no bonds (chai → perceive connectivity), or an over-broad ligand flag (use the entity type, not biotite `hetero`). See pitfalls 10–12. -- **JAX (JIT / lax.scan)** — alphafold3. The framework-free adapter ALSO lives in +- **JAX (JIT / lax.scan)** — AlphaFold3 and IntelliFold v2. The framework-free adapter ALSO lives in rgi_toolkit (`rgi_toolkit/alphafold3/adapter.py`), like the torch tools; only a thin **in-tool shim** (`alphafold3_restr/.../restraints/adapter.py` `build_af3_adapter`) does the one alphafold3-coupled step — resolve each ligand's CCD/SMILES RDKit mol + read `fold_input` — then constructs the rgi_toolkit adapter from plain data. Build the spec outside the scan; inject the pure `get_minimizer()` closure inside. + IntelliFold follows the same split through `intellifold.rgi.build_restraints` + and `rgi_toolkit/intellifold/adapter.py`. + +These are eleven integrations; Boltz-1/Boltz-2 and Protenix v1/v2 share adapters. +ESMFold2's sampling hook lives in `esm_restr/esm/models/esmfold2/layers.py`. +`processor.py` builds the restraint state; `model.py` and `experimental.py` +forward it to the sampler in the same directory. +The integration no longer requires `transformers_restr` or copying hooks into +an installed `transformers` package. Details, code, and the non-obvious traps (torch `inference_mode`, jax line search collapsing atoms, coordinate reshape) are in diff --git a/.claude/skills/implement-rgi/references/adapter-protocol.md b/.claude/skills/implement-rgi/references/adapter-protocol.md index 2385e3e..6123142 100644 --- a/.claude/skills/implement-rgi/references/adapter-protocol.md +++ b/.claude/skills/implement-rgi/references/adapter-protocol.md @@ -45,16 +45,16 @@ spells out the trade-off and requires a structured question when the client supp one): in rgi_toolkit (the convention below) or in the tool's own codebase (rgi_toolkit left unedited, the tool owns the adapter and may import its framework freely — at the cost of having to track protocol drift). Both work — the protocol is duck-typed (no base class, -no registration). The existing seven all chose rgi_toolkit: +no registration). The existing eleven integrations all chose rgi_toolkit: -**All seven adapters live in `rgi_toolkit//adapter.py`** — the project keeps them +**All eleven adapters live in `rgi_toolkit//adapter.py`** — the project keeps them together so a cross-tool invariant (the `resid` convention, a protocol tweak) is reviewed in one place. They receive plain dict/array data and import no framework code, EXCEPT boltz, whose feats arrive as native torch tensors so its adapter imports torch (read at batch 0). - **PyTorch tool**: drop the adapter straight into `rgi_toolkit//adapter.py`. -- **JAX tool (AF3)**: the framework-free adapter ALSO lives in rgi_toolkit +- **JAX tools (AF3 and IntelliFold)**: the framework-free adapter ALSO lives in rgi_toolkit (`rgi_toolkit/alphafold3/adapter.py`). Only the irreducibly framework-coupled step — resolving each ligand's CCD/SMILES RDKit mol and reading `fold_input` — stays in a thin **in-tool shim** (`alphafold3_restr/.../restraints/adapter.py` @@ -63,6 +63,8 @@ torch (read at batch 0). mapping, atom-name decode, leaving-atom subset, `iter_atoms` / `iter_ligand_confs`) is the framework-free rgi_toolkit adapter. The split keeps the dependency direction clean (rgi_toolkit imports no alphafold3) while still centralizing the adapter logic. + IntelliFold uses `intellifold.rgi.build_restraints` for this shim and + `rgi_toolkit/intellifold/adapter.py` for its adapter. ## Worked example 1 — boltz (reads a feats dict, batch 0) @@ -143,7 +145,7 @@ is rgi_toolkit. ## Full source -The seven complete adapters are the ground truth: +The eleven adapters are the ground truth: - `RGI-toolkit/src/rgi_toolkit/boltz/adapter.py` — feats dict + exposed `ligand_mols` - `RGI-toolkit/src/rgi_toolkit/protenix/adapter.py` — biotite AtomArray (real bonds + coords) - `RGI-toolkit/src/rgi_toolkit/chai/adapter.py` — reference conformer; prefers the source SMILES (`_mol_from_smiles`, real bond orders), falling back to `build_ligand_mol(perceive_bonds=True)` when none is supplied @@ -151,6 +153,10 @@ The seven complete adapters are the ground truth: - `RGI-toolkit/src/rgi_toolkit/esmfold2/adapter.py` — one token/atom; intra-ligand bonds + orders from `token_bonds` / `ligand_bond_orders` (CCD or SMILES) - `RGI-toolkit/src/rgi_toolkit/alphafold3/adapter.py` — framework-free (JAX), fed by the in-tool shim `/src/alphafold3/model/restraints/adapter.py` (`build_af3_adapter` = CCD/SMILES mol resolution + `fold_input` read) - `RGI-toolkit/src/rgi_toolkit/opendde/adapter.py` — OpenDDE AtomArray metadata + pre-expansion token mapping + `ref_pos`; ligand identity from `mol_type` +- `RGI-toolkit/src/rgi_toolkit/rf3/adapter.py` — AtomArray metadata, final atom-to-token mapping, reference positions, and source ligand chemistry +- `RGI-toolkit/src/rgi_toolkit/bioemu2/adapter.py` — topology and reference coordinates supplied by the BioEmu2 shim +- `RGI-toolkit/src/rgi_toolkit/mol1/adapter.py` — shared Protenix chemistry with Mol-1's per-chain atom-to-token mapping +- `RGI-toolkit/src/rgi_toolkit/intellifold/adapter.py` — shared AF3 layout with CCD/SMILES molecules supplied by `intellifold.rgi.build_restraints` The chai and openfold3 adapters are worth reading specifically for the "tool exposes an incomplete ligand picture" cases (pitfalls 10–12). diff --git a/.claude/skills/implement-rgi/references/framework-notes.md b/.claude/skills/implement-rgi/references/framework-notes.md index 538275f..c925dba 100644 --- a/.claude/skills/implement-rgi/references/framework-notes.md +++ b/.claude/skills/implement-rgi/references/framework-notes.md @@ -1,6 +1,9 @@ # Framework notes -## PyTorch (eager loop) — boltz, protenix, OpenDDE, chai-lab, openfold-3, esmfold2 +## PyTorch (eager loop) + +Boltz, Protenix, OpenDDE, Chai-1, OpenFold-3, ESMFold2, RF3, BioEmu2, and Mol-1 +use the PyTorch path. - **autograd under `inference_mode`**: predict loops often run inside `torch.inference_mode()`, where autograd backward fails with "element does not @@ -17,13 +20,20 @@ (a per-step radius search). `mode` defaults to **`both`** (run them together); both now run on **torch AND jax**, so a JAX tool gets the full VdW too. -## JAX (JIT / `lax.scan`) — AlphaFold3 +ESMFold2's native implementation is under `esm_restr/esm/models/esmfold2/`: +`processor.py` builds the restraint state, `model.py` and `experimental.py` +forward it, and `layers.py` applies the sampling hook. The old `transformers_restr` model +implementation and installed-package copy workaround are no longer needed. + +## JAX (JIT / `lax.scan`) — AlphaFold3 and IntelliFold v2 - **adapter placement**: the framework-free adapter lives in rgi_toolkit (`rgi_toolkit/alphafold3/adapter.py`), like the torch tools; only a thin in-tool shim (`alphafold3_restr/.../restraints/adapter.py` `build_af3_adapter`) does the one alphafold3-coupled step — CCD/SMILES mol resolution + `fold_input` read — and feeds the rgi_toolkit adapter plain data. + IntelliFold uses the same arrangement through `intellifold.rgi.build_restraints` + and `rgi_toolkit/intellifold/adapter.py`. - **no Python callbacks in the scan**: build the spec outside the scan (numpy, at build time) and inject `get_minimizer()`'s pure closure inside. Never call the Python `minimize` per step in a compiled loop. diff --git a/.gitignore b/.gitignore index 5b6f3f1..45c52e0 100644 --- a/.gitignore +++ b/.gitignore @@ -216,3 +216,7 @@ __marimo__/ /examples/**/*.a3m /examples/**/*.aligned.pqt /examples/ligand-dissociation/msas/ + +# Generated predictor inputs after MSA and template preprocessing +/examples/**/*-update-msa.json +/examples/**/*-final-updated.json diff --git a/AGENTS.md b/AGENTS.md index 0a9514d..6feafa3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,15 +65,16 @@ run cancels an older run for the same branch or pull request. **rgi_toolkit** — Restraint-Guided Inference (RGI): inject distance + ligand conformer + RMSD restraints into a structure-prediction diffusion loop via gradient -optimization. Shared by **nine** integrations — boltz / protenix / chai-lab / openfold-3 / -esmfold2 / opendde / rf3 / bioemu2 (torch) and alphafold3 (jax), covering 11 model variants (boltz1+boltz2 and +optimization. Shared by **eleven** integrations — boltz / protenix / chai-lab / openfold-3 / +esmfold2 / opendde / rf3 / bioemu2 / mol1 (torch) and alphafold3 / intellifold (jax), +covering 13 model variants (boltz1+boltz2 and protenix v1+v2 each share one adapter). The end-to-end guide for integrating a new tool is the `implement-rgi` skill, shared from `.claude/skills/` to `.agents/skills/` (alongside `generate-rgi-config` for authoring a config, `sync-upstream`, `create-github-release`). Per-tool as-built integration write-ups live in `docs/.md` (one per tool); the shared config + selection-DSL surface is `docs/config.md`. `examples/` holds ready-to-run samples organized by restraint type and predictor: -distance, angle, RMSD, custom, and MDM2-p53 ligand dissociation for nine predictors, +distance, angle, RMSD, custom, and MDM2-p53 ligand dissociation for eleven predictors, each with a `run.sh`. Reuse those fixtures instead of authoring new ones. Design = **3 layers + autodiff + static shapes + GPU-complete optimization**: @@ -379,7 +380,7 @@ prior spec/optimizer up front so a reused instance is safe) → `minimize(coords, step, sigma)` → `finalize(coords, step)`. Always construct a fresh instance per structure (the old `get_instance()`/`reset()` singleton shim was removed). The backend is **inferred from invocation, NOT a config key**: `get_minimizer()` → -jax (only AF3 calls it); `minimize(coords)` → jax if `coords` is a jax array, else +jax (used by AF3 and IntelliFold); `minimize(coords)` → jax if `coords` is a jax array, else torch (numpy/torch coords both take the torch path). Resolution is lazy — `setup` leaves `self._backend = None` and builds the optimizer on the first `minimize`/`get_minimizer` (`_ensure_backend` raises if one instance is invoked under @@ -394,12 +395,12 @@ when `gpu:true`), NOT the backend, so `gpu:false` runs the torch optimizer on CP (moving GPU coords to CPU and back). There is no numpy optimizer (numpy is the energy reference only); a leftover `backend:` config key raises with a migration hint. torch/jax imported lazily. JAX tools inside `lax.scan` grab the pure minimizer via -`get_minimizer()` instead of calling `minimize` per step (so for AF3 the `gpu` flag is -inert — to run AF3 restraints on CPU, run the whole process on the JAX CPU platform). +`get_minimizer()` instead of calling `minimize` per step. The `gpu` flag is inert +for AF3 and IntelliFold; run the whole process on the JAX CPU platform to use CPU. #### Framework adapters -(`{boltz,protenix,chai,openfold3,esmfold2,opendde,rf3,bioemu2,alphafold3}/adapter.py` — +(`{boltz,protenix,chai,openfold3,esmfold2,opendde,rf3,bioemu2,mol1,alphafold3,intellifold}/adapter.py` — framework-free EXCEPT boltz, whose feats arrive as native torch tensors so its adapter imports torch (read at batch 0); the others import no framework. AF3's CCD/SMILES mol resolution lives in a thin in-tool shim @@ -408,10 +409,15 @@ data): implement `iter_atoms()` (→ `AtomRecord(chain, resid, index)` for distance selection) and optionally `num_atoms()`, `get_elements()`, `iter_ligand_confs()` (→ `LigandConf(mol, conf_coords, global_indices, stereo_mol=...)` for conformer + VdW; -`stereo_mol` is the optional source SMILES graph renumbered to coordinate order). The four tools whose -features arrive as a **biotite `AtomArray`** (protenix / openfold3 / opendde / rf3) share +`stereo_mol` is the optional source SMILES graph renumbered to coordinate order). The five tools whose +features arrive as a **biotite `AtomArray`** (protenix / openfold3 / opendde / rf3 / mol1) share `_biotite_adapter.py` (`biotite_get_elements` / `biotite_ligand_confs`) rather than each -re-deriving elements + ligand conformers — extend that module, not the four call sites. +re-deriving elements + ligand conformers — extend that module, not the call sites. + +Mol-1 reuses the Protenix adapter chemistry and derives per-chain residue ordinals +from its actual atom-to-token map. IntelliFold reuses the AF3 adapter and obtains +CCD/SMILES molecules from `intellifold.rgi.build_restraints`. Its JAX loop takes +the scan minimizer as a numeric pytree so targets remain dynamic across inputs. RF3 receives the final atom-to-token map, reference positions and reference-space IDs from the tool-side shim, which also normalizes AtomWorks entity types and resolves diff --git a/README.md b/README.md index 56dc969..f888126 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ The input file contains both the protein sequence and its `restraints_config`. The command fetches an MSA from the server and writes results under the selected output directory. -The bundled examples cover four protocols across seven predictors: +The bundled examples cover five categories across eleven predictor integrations: | Example | System | Restraint | | --- | --- | --- | @@ -73,10 +73,13 @@ The bundled examples cover four protocols across seven predictors: | [Angle](examples/angle/) | ADK | NMP–CORE–LID centroid angle of 72.85° | | [RMSD](examples/rmsd/) | QBP | RMSD targets of 2.65 Å to both open and closed references | | [Custom energy](examples/custom/dist-diff/) | DgoT | Difference between two domain distances of 0.8 Å | +| [Ligand dissociation](examples/ligand-dissociation/) | MDM2–p53 | Chain-centroid distance of 30 Å | +Each category includes a `run.sh` for Boltz-2, Protenix v2, AlphaFold3, OpenFold-3, +Chai-1, ESMFold2, OpenDDE, RF3, BioEmu2, Mol-1 and IntelliFold v2. RF3 examples +are included here, such as [the RF3 distance example](examples/distance/rf3/). See the [example guide](examples/README.md) for predictor-specific environments, -MSA inputs, reference structures and run commands. RF3 examples are maintained in -the [Foundry integration](https://github.com/cddlab/foundry_restr/tree/rgi-integration/examples/rgi). +MSA inputs, reference structures and run commands. ## Google Colab @@ -115,6 +118,8 @@ The backends below refer to the local predictor integrations. | **OpenDDE v1** | opendde | PyTorch | [OpenDDE](docs/opendde_restr.md) | | **RF3** | foundry | PyTorch | [RF3](docs/foundry_restr.md) | | **BioEmu2** | bioemu2 | PyTorch | [BioEmu2](docs/bioemu2_restr.md) | +| **Mol-1** | mol1 | PyTorch | [Mol-1](docs/mol1_restr.md) | +| **IntelliFold v2** | intellifold | JAX | [IntelliFold](docs/intellifold_restr.md) | Each guide covers installation, input configuration and the prediction command. The [documentation index](docs/README.md) also summarizes where each predictor diff --git a/docs/README.md b/docs/README.md index 64a85d3..84121d1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -20,6 +20,8 @@ Guides are available for the following predictor integrations. | OpenDDE v1 | PyTorch | `restraints_config` in each fold-input JSON object | [OpenDDE](opendde_restr.md) | | RF3 (Foundry) | PyTorch | `restraints_config` in each input JSON job | [RF3](foundry_restr.md) | | BioEmu2 | PyTorch | `restraints_config` in the system YAML or `System` | [BioEmu2](bioemu2_restr.md) | +| Mol-1 | PyTorch | `restraints_config` in each fold-input JSON object | [Mol-1](mol1_restr.md) | +| IntelliFold v2 | JAX | `restraints_config` in the fold-input JSON | [IntelliFold](intellifold_restr.md) | ## Recommended workflow @@ -37,7 +39,7 @@ Guides are available for the following predictor integrations. - Conformer terms require both `conformer_restraints_config` and a per-ligand opt-in. The opt-in location differs by tool. - The backend is inferred from the predictor. `gpu` selects the PyTorch device and is inert for - AlphaFold 3's JAX path. + AlphaFold 3 and IntelliFold's JAX paths. - Config validation checks schema and selection syntax. Runtime `built spec:` counts confirm which restraints were built; verify the selected atom identities separately against the input structure to check that the selections match the intended atoms. diff --git a/docs/intellifold_restr.md b/docs/intellifold_restr.md new file mode 100644 index 0000000..4fc419e --- /dev/null +++ b/docs/intellifold_restr.md @@ -0,0 +1,106 @@ +# IntelliFold v2 — Restraint-Guided Inference (RGI) + +[Documentation index](README.md) · [Configuration reference](config.md) + +This integration supports the current `intellifold predict` JAX path with +IntelliFold v2 weights and the vendored AlphaFold 3 engine. Its framework-free +adapter is `rgi_toolkit.intellifold.adapter.IntelliFoldAdapter`; it reuses the +shared AF3 atom layout and ligand mapping. The legacy PyTorch runner is outside +this integration. + +## Installation + +Install both the fork's vendored engine and its wrapper. A stock AlphaFold 3 +installation does not contain the RGI sampling hooks. + +```bash +git clone --branch rgi-integration https://github.com/cddlab/IntelliFold_restr.git +cd IntelliFold_restr +uv venv --python 3.12 +source .venv/bin/activate +uv pip install -e ./third_party/alphafold3 +uv run --active --no-project build_data +uv pip install -e . +``` + +The engine requires a C++ build toolchain. Build native components on a machine +compatible with the inference node. The wrapper depends on the toolkit's +`add_mol1_intellifold` branch until that branch is merged. For co-development, +run `uv pip install -e ../RGI-toolkit` after installing the wrapper. + +IntelliFold v2 weights download on first use into `--model-dir`; no AlphaFold 3 +weights are needed. Inputs use AF3 JSON with explicit chain IDs. Put +`restraints_config` beside `sequences` and `modelSeeds`. A ligand opt-in is: + +```json +{"ligand": {"id": "B", "smiles": "N[C@@H](CCC(N)=O)C(O)=O", "conformer_restraints": true}} +``` + +SMILES and single-CCD ligands support conformer restraints. Opting a multi-CCD +ligand into conformer restraints raises an error rather than silently skipping +it. The RGI configuration and per-chain flags survive input serialization and +the MSA/template pipeline. + +The pure JAX minimizer runs inside `hk.scan`. Numeric targets and other restraint +arrays are runtime arguments to the outer JIT, so compatible inputs can reuse +compiled programs. Each input and seed builds its own restraint state using that +seed's reference features. `gpu` does not move JAX restraints off the model's +device. Native `--steering` is optional; when enabled, steering runs first and +RGI runs second within each denoising step. + +## Configuration + +The shared [configuration reference](config.md) defines distance, angle, dihedral, +improper, chiral, plane, RMSD, base-pair and custom restraints. Each input keeps +its own `restraints_config`. Omitting it preserves native sampling. + +Conformer restraints additionally require `"conformer_restraints": true` on each +ligand or polymer entity to be restrained. Other restraints need no entity opt-in. +`resid` is the per-chain 1-based residue/token ordinal; ligand atoms and atomized +modified residues occupy separate tokens. `index` refers to the model coordinate +array, so it can include padding gaps. Qualify protein selections with `chain A`. + +The engine applies restraints after denoising and before the diffusion update, +using the pre-churn sigma. Each restraint can use either sigma windows or step +windows. There is no top-level `start_sigma`. + +## Examples + +The five runnable example types are distance, angle, RMSD, custom distance +difference, and MDM2-p53 dissociation. Their input files contain all settings +inline; reference structures for RMSD are downloaded by the runner. + +```bash +DB_DIR=databases bash examples/distance/intellifold/run.sh +DB_DIR=databases bash examples/angle/intellifold/run.sh +DB_DIR=databases bash examples/rmsd/intellifold/run.sh +DB_DIR=databases bash examples/custom/dist-diff/intellifold/run.sh +DB_DIR=databases bash examples/ligand-dissociation/intellifold/run.sh +``` + +Run from the toolkit checkout with the predictor installed as a sibling. Set +`DB_DIR` to the local AF3 sequence databases. `MODEL_DIR` optionally overrides +the model cache. All runners accept an optional input JSON path. + +For precomputed MSAs, give each protein `unpairedMsaPath`, `pairedMsa: ""`, and +`templates: []`, then set `RUN_DATA_PIPELINE=false`. A query-only input can use +`unpairedMsa: ""` instead of a path. This explicitly disables MSA search. + +```bash +RUN_DATA_PIPELINE=false bash examples/distance/intellifold/run.sh input_with_msa.json +``` + +Use a new `OUT_DIR` for a changed restraint configuration, because the native +batch runner can skip completed predictions. + +## Verification + +The [small-case verification report](mol1_intellifold_verification.md) records +bench-rgi inputs, measured distances, source-stereo checks, and tested revisions. + +Use `verbose: true` and check the `built spec:` counts before interpreting final +energies. A zero energy with zero registered restraints does not demonstrate +guidance. Measure the selected distance or other geometry in the written CIF, +check that all coordinates are finite, and compare conformer ON/OFF predictions +with the same seed. Test two inputs with different targets in one process to +check that settings do not leak between structures. diff --git a/docs/mol1_intellifold_verification.md b/docs/mol1_intellifold_verification.md new file mode 100644 index 0000000..b0b5972 --- /dev/null +++ b/docs/mol1_intellifold_verification.md @@ -0,0 +1,116 @@ +# Mol-1 and IntelliFold small-case verification + +Verified on 2026-11-07 with RGI-toolkit 0.5.0. These are functional integration +checks with one seed and one sample per condition, not an accuracy benchmark. + +## Tested revisions and environment + +| Component | Inference revision | +|---|---| +| RGI-toolkit | `c08766fdd668d95bbeed85e046d7ed3ea78dfeab` | +| Mol-1 | `d4b6de899d4102b2b5fd536f3581deafb0cb06b9` | +| IntelliFold v2 | `74f3132d8b588455ff5739852994ed7997d2ad32` | +| bench-rgi fixtures/configuration | `70dd0a722b1f450d553c5b83883a33942bc3bdd3` | + +IntelliFold subsequently received a serialization fix in `5eaae93`: identical +molecules with different conformer opt-ins remain distinct when writing JSON. +All 14 CPU tests pass on that revision. The fix does not change the sampler or +the single-ligand inputs measured below. + +Both predictors ran on an RTX 5090 with Python 3.12.13. Mol-1 used PyTorch +2.13.0/CUDA 13.0, cuEquivariance 0.10.0, RDKit 2026.9.1, and Pandas 2.3.3. +IntelliFold used JAX/jaxlib 0.9.1 and RDKit 2025.9.4. Each prediction used seed 0, +one diffusion sample, 200 diffusion steps, and one recycle. Both models consumed +the same source MSAs through their native featurizers. Template search was off. + +Mol-1's native Fast LayerNorm extension was built with a CUDA 13 toolchain. +`TORCH_NO_COMPILER_WRAPPER=1` bypassed a failing local sccache wrapper; inference +used the native CUDA extension. The RGI compiler was enabled during inference. + +## Distance guidance and per-input configuration + +The 226-residue QBP fixture comes from `bench-rgi/distance/fixtures/qbp.a3m`. +The distance uses all atoms in residues 4-83 plus 185-223 versus residues 89-179, +all in chain A. Both adapters selected 946 and 686 atoms, respectively, and +registered one distance restraint. CG used `max_iter: 100` and +`start_sigma: 100000000`. + +| Predictor | No restraint (A) | Target 25 A | Target 35 A | +|---|---:|---:|---:| +| Mol-1 | 24.900717 | 25.000793 | 34.997422 | +| IntelliFold v2 | 25.225381 | 25.002289 | 34.998089 | + +Distances were measured independently from the written CIF coordinates. +Each predictor processed the three different configurations in one process. +Both restrained targets were within 0.003 A, confirming that the second target +was not replaced by cached settings from the first input. + +For Mol-1, the precomputed unpaired MSA path was supplied and `pairedMsaPath` +was omitted. An empty string for that optional path triggers another MSA search. +For IntelliFold, `pairedMsa: ""`, `templates: []`, and `--norun_data_pipeline` +disabled searches. The ColabFold metadata comment was removed from the QBP A3M; +its aligned sequences were retained. + +## Ligand conformer guidance + +The ct209 case `1cz2__1__1.A__1.B` contains a 90-residue protein and a 24-heavy-atom +ligand. Its source MSA, SMILES, and SDF came from the pinned +`wasarou/plinder-cistrans-209` v1.0 data used by bench-rgi. ON and OFF used the +same input sequence, ligand, MSA, seed, and sampling settings. + +ON used bench-rgi's conformer settings: CG with 100 iterations, UFF target +relaxation, `start_sigma: 1.0`, and unit weights for bond, angle, chiral, +cis/trans, and VdW terms. The optional plane term was disabled. Each predictor +registered 24 bond, 29 angle, one chiral, and two cis/trans restraints, plus +ligand-background VdW interactions against 667 protein atoms. + +| Predictor | Source chirality matches OFF / ON | Source E/Z matches OFF / ON | Ligand ON/OFF aligned RMSD (A) | +|---|---|---|---:| +| Mol-1 | 0/1 -> 1/1 | 1/2 -> 2/2 | 3.868602 | +| IntelliFold v2 | 0/1 -> 1/1 | 1/2 -> 2/2 | 0.680232 | + +Stereo was assigned independently from the written ligand coordinates and +compared with the source SMILES. A mismatch includes an unassigned center. +The RMSD uses an explicit atom-name correspondence and ligand-only rigid +alignment; it measures conformational change, not docking accuracy. +The final weighted restraint objectives were approximately 0.00002 for Mol-1 +and 0.00022 for IntelliFold. These are toolkit objective values, not physical +energies. All coordinates in all ten output structures were finite. + +## Regression and installation checks + +- Toolkit: 1,800 eager CPU tests and 22 actual CPU compiler tests passed. +- Mol-1: 196 CPU tests passed, 14 skipped; 203 GPU tests passed, 7 skipped. + Both runs also passed 27 subtests. The six new RGI cases passed in both runs. +- IntelliFold: all 14 tests passed, including input round-trips, independent + opt-ins for identical molecules, pipeline preservation, pre-churn sigma, + native steering order, and finite coordinates with or without RGI. +- All ten new example configurations passed schema and selection-syntax + validation. All ten shell runners passed syntax checks. These checks do not + replace full predictions for the larger angle, RMSD, custom, or dissociation + examples. +- Toolkit lint, formatting, and lock consistency passed. Both installed + predictor environments passed dependency checks, and installation resolution + succeeded against the published toolkit branch. + +The Mol-1 fork constrains Pandas below 3 after its existing vectorization tests +exposed incompatible string/NaN behavior, and its CUDA extras include Ninja. +IntelliFold clamps diffusion noise variance to zero before taking its square +root, preventing negative roundoff at zero churn on CPU. + +## Artifact provenance + +Generated inputs, output CIFs, logs, environment checks, `manifest.json`, and +independent measurement scripts are kept under +`$BENCH_VERIFICATION_ROOT/mol1_intellifold`. The root is configured by bench-rgi; +these generated artifacts are outside the source repositories. + +| Artifact | SHA-256 | +|---|---| +| Original QBP A3M | `aebbfcd7c42af3e00f0e01b9f33fdd2f11e13bde8267602b986d7075a223d156` | +| Normalized QBP A3M | `188ed7137e01921f90e5fed691fe034978603473fc7d474954ed37779c3335f8` | +| Ligand-case A3M | `6610b711d244bf4b8eb0024a4fb4cc34cb72a1b48a8246731fc5dec1d7ece583` | +| Ligand-case source SDF | `e27b5648dc8c82a1186c3defa29f3a092491c691beacd0739f5cb2808da6a187` | +| Mol-1 base weights | `d5b83a86884aa6870565b1a249e8f13c232dfc6dfa311089ab0c7868212b6bd6` | +| IntelliFold v2 JAX weights | `16ae6c2002989a3eb3fae60714f2802fc336f6b1fdfb1a90a74a91745cdcdef2` | +| IntelliFold Fourier weights | `4453bf29ac0a0f921a67a15155d0dd61e3f7214ec124d6deb91ce935d6a93201` | diff --git a/docs/mol1_restr.md b/docs/mol1_restr.md new file mode 100644 index 0000000..392e60c --- /dev/null +++ b/docs/mol1_restr.md @@ -0,0 +1,96 @@ +# Mol-1 — Restraint-Guided Inference (RGI) + +[Documentation index](README.md) · [Configuration reference](config.md) + +Mol-1 uses the PyTorch optimizer. Its adapter lives in +`rgi_toolkit.mol1.adapter.Mol1Adapter` and reuses the shared Protenix-shaped +chemistry extraction while following Mol-1's actual atom-to-token map. + +## Installation + +Install the RGI fork and its engine dependency. This integration uses the +toolkit's `add_mol1_intellifold` branch until that branch is merged. + +```bash +git clone --branch rgi-integration https://github.com/cddlab/Mol-1_restr.git +cd Mol-1_restr +uv venv --python 3.12 +source .venv/bin/activate +uv pip install -e '.[cuda]' +export MOL_ROOT_DIR="${MOL_ROOT_DIR:-$PWD/data}" +bash scripts/database/download_mol_data.sh +mkdir -p "$MOL_ROOT_DIR/checkpoint" +curl -fL https://mol-1-release.oss-cn-shanghai.aliyuncs.com/checkpoint/mol-1-base.pt \ + -o "$MOL_ROOT_DIR/checkpoint/mol-1-base.pt" +``` + +Use `.[cuda12]` for a CUDA 12 driver, or `.[cpu]` for CPU inference. During +co-development, install the sibling toolkit with `uv pip install -e ../RGI-toolkit` +after installing the predictor. + +GPU inference builds Fast LayerNorm on first use. Install a C++ compiler and a +CUDA toolkit matching the PyTorch CUDA major version, and set `CUDA_HOME` when +the default toolkit differs. The CUDA extras install Ninja. On systems without +that build toolchain, set `LAYERNORM_TYPE=torch` to use the native PyTorch +LayerNorm implementation. The fork constrains Pandas below 3 because its +existing dataset transformations rely on the Pandas 2 string/NaN behavior. + +Mol-1 takes a JSON list of jobs. Put `restraints_config` beside each job's `name` +and `sequences`. A ligand opt-in belongs inside its `ligand` object: + +```json +{"ligand": {"ligand": "N[C@@H](CCC(N)=O)C(O)=O", "count": 1, "conformer_restraints": true}} +``` + +SMILES bond orders and source stereochemistry are preserved for conformer +restraints. The adapter takes targets from the reference conformer; the shared +engine performs the configured relaxation and stereo checks. + +## Configuration + +The shared [configuration reference](config.md) defines distance, angle, dihedral, +improper, chiral, plane, RMSD, base-pair and custom restraints. Each input keeps +its own `restraints_config`. Omitting it preserves native sampling. + +Conformer restraints additionally require `"conformer_restraints": true` on each +ligand or polymer entity to be restrained. Other restraints need no entity opt-in. +`resid` is the per-chain 1-based residue/token ordinal; ligand atoms and atomized +modified residues occupy separate tokens. `index` refers to the model coordinate +array, so it can include padding gaps. Qualify protein selections with `chain A`. + +The engine applies restraints after denoising and before the diffusion update, +using the pre-churn sigma. Each restraint can use either sigma windows or step +windows. There is no top-level `start_sigma`. + +## Examples + +The five runnable example types are distance, angle, RMSD, custom distance +difference, and MDM2-p53 dissociation. Their input files contain all settings +inline; reference structures for RMSD are downloaded by the runner. + +```bash +bash examples/distance/mol1/run.sh +bash examples/angle/mol1/run.sh +bash examples/rmsd/mol1/run.sh +bash examples/custom/dist-diff/mol1/run.sh +bash examples/ligand-dissociation/mol1/run.sh +``` + +Run from the toolkit checkout with the predictor installed as a sibling. +The runners use Mol-1's MSA server. To supply existing alignments, set +`unpairedMsaPath` on each protein-chain object and optionally `pairedMsaPath`. +Omit `pairedMsaPath` when no paired alignment is available: an empty string is +treated as a missing file and triggers a new MSA search. To run without +MSA search, invoke `mol pred` directly with `--use_msa false`. + +## Verification + +The [small-case verification report](mol1_intellifold_verification.md) records +bench-rgi inputs, measured distances, source-stereo checks, and tested revisions. + +Use `verbose: true` and check the `built spec:` counts before interpreting final +energies. A zero energy with zero registered restraints does not demonstrate +guidance. Measure the selected distance or other geometry in the written CIF, +check that all coordinates are finite, and compare conformer ON/OFF predictions +with the same seed. Test two inputs with different targets in one process to +check that settings do not leak between structures. diff --git a/examples/README.md b/examples/README.md index 29b38aa..6e77346 100644 --- a/examples/README.md +++ b/examples/README.md @@ -13,8 +13,8 @@ contains one setting per model. | `custom/dist-diff/` | DgoT, 419 residues | ΔD = D_in − D_out = 0.8 Å | | `ligand-dissociation/` | MDM2–p53 | Chain-centroid distance of 30.0 Å | -The nine predictors covered here are `boltz-2`, `protenix-v2`, `alphafold3`, -`openfold-3`, `chai`, `esmfold2`, `opendde`, `rf3`, and `bioemu2`. +The eleven predictors covered here are `boltz-2`, `protenix-v2`, `alphafold3`, +`openfold-3`, `chai`, `esmfold2`, `opendde`, `rf3`, `bioemu2`, `mol1`, and `intellifold`. ## Run @@ -73,10 +73,13 @@ For comparisons across predictors, use the same full ColabFold A3M for each protein. Reproducing a prediction also requires the same model checkpoint and seed. -Boltz-2, Protenix-v2, OpenFold3, Chai, and BioEmu2 use an MSA server. +Boltz-2, Protenix-v2, OpenFold3, Chai, BioEmu2, and Mol-1 use an MSA server. RF3 uses the supplied sequence; add `msa_paths` to its input to provide alignments. AlphaFold3 uses its -local data pipeline and requires `MODEL_DIR` and `DB_DIR`. ESMFold2 reads the full +local data pipeline and requires `MODEL_DIR` and `DB_DIR`. IntelliFold also uses +the local pipeline and requires `DB_DIR`; its v2 weights download automatically +into `MODEL_DIR`. Set `RUN_DATA_PIPELINE=false` for inputs carrying MSAs and +templates. ESMFold2 reads the full A3M from `MSA_A3M` for single-chain examples, or `MSA_A3M_A` and `MSA_A3M_B` for ligand dissociation. It checks each query against the example sequence and uses `msa_max_depth=1024` and `msa_column_mask_rate=0.1`, with 20 recurrent @@ -87,8 +90,9 @@ To reuse a precomputed MSA, provide it through the predictor's native input: | Predictor | Precomputed MSA input | |---|---| | Boltz-2 | Protein `msa` field; omit `--use_msa_server` | -| Protenix-v2 | Protein-chain `unpairedMsaPath` | +| Protenix-v2 / Mol-1 | Protein-chain `unpairedMsaPath` | | AlphaFold3 | Protein `unpairedMsaPath`, `pairedMsa: ""`, and `templates: []`; use `--run_data_pipeline=False` | +| IntelliFold v2 | The same AF3 fields; set `RUN_DATA_PIPELINE=false` in the example runner | | OpenFold3 | Chain `main_msa_file_paths`; use `--use-msa-server false` | | Chai | Aligned Parquet files through `--msa-directory`; omit `--use-msa-server` | | ESMFold2 | `MSA_A3M`, or `MSA_A3M_A` / `MSA_A3M_B` for ligand dissociation | diff --git a/examples/angle/intellifold/adk_72.85.json b/examples/angle/intellifold/adk_72.85.json new file mode 100644 index 0000000..e5e608b --- /dev/null +++ b/examples/angle/intellifold/adk_72.85.json @@ -0,0 +1,35 @@ +{ + "dialect": "alphafold3", + "version": 4, + "name": "adk_72.85", + "modelSeeds": [ + 0 + ], + "sequences": [ + { + "protein": { + "id": "A", + "sequence": "MRIILLGAPGAGKGTQAQFIMEKYGIPQISTGDMLRAAVKSGSELGKQAKDIMDAGKLVTDELVIALVKERIAQEDCRNGFLLDGFPRTIPQADAMKEAGINVDYVLEFDVPDELIVDRIVGRRVHAPSGRVYHVKFNPPKVEGKDDVTGEELTTRKDDQEETVRKRLVEYHQMTAPLIGYYSKEAEAGNTKYAKVDGTKPVAEVRADLEKILG", + "modifications": [], + "templates": [] + } + } + ], + "restraints_config": { + "verbose": true, + "gpu": true, + "max_iter": 100, + "method": "CG", + "angle_restraints_config": [ + { + "atom_selection1": "chain A and ((resid 30 to 59))", + "atom_selection2": "chain A and ((resid 1 to 29) or (resid 60 to 121) or (resid 160 to 214))", + "atom_selection3": "chain A and ((resid 122 to 159))", + "start_sigma": 99999999, + "harmonic": { + "target_angle": 72.85 + } + } + ] + } +} diff --git a/examples/angle/intellifold/run.sh b/examples/angle/intellifold/run.sh new file mode 100755 index 0000000..eeed6db --- /dev/null +++ b/examples/angle/intellifold/run.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +WS="$(cd "$HERE/../../../.." && pwd)" +cd "$HERE" +INPUT="${1:-adk_72.85.json}" +test -f "$INPUT" +STEM="$(basename "$INPUT" .json)" +OUT="${OUT_DIR:-out/$STEM}" +MODEL_DIR="${MODEL_DIR:-$WS/IntelliFold_restr/model_v2}" +PIPELINE_ARGS=(--norun_data_pipeline) +if [[ "${RUN_DATA_PIPELINE:-true}" == true ]]; then + DB_DIR="${DB_DIR:?set DB_DIR to your sequence-database directory}" + PIPELINE_ARGS=(--run_data_pipeline=true --db_dir="$DB_DIR") +fi +export JAX_COMPILATION_CACHE_DIR="${JAX_COMPILATION_CACHE_DIR:-${TMPDIR:-/tmp}/rgi-intellifold-jax}" +uv run --no-project --python "$WS/IntelliFold_restr/.venv/bin/python" intellifold predict \ + "$INPUT" --model-dir "$MODEL_DIR" --output-dir "$OUT" -- \ + --num_diffusion_samples=1 "${PIPELINE_ARGS[@]}" diff --git a/examples/angle/mol1/adk_72.85.json b/examples/angle/mol1/adk_72.85.json new file mode 100644 index 0000000..e5bd550 --- /dev/null +++ b/examples/angle/mol1/adk_72.85.json @@ -0,0 +1,30 @@ +[ + { + "name": "adk_72.85", + "sequences": [ + { + "proteinChain": { + "sequence": "MRIILLGAPGAGKGTQAQFIMEKYGIPQISTGDMLRAAVKSGSELGKQAKDIMDAGKLVTDELVIALVKERIAQEDCRNGFLLDGFPRTIPQADAMKEAGINVDYVLEFDVPDELIVDRIVGRRVHAPSGRVYHVKFNPPKVEGKDDVTGEELTTRKDDQEETVRKRLVEYHQMTAPLIGYYSKEAEAGNTKYAKVDGTKPVAEVRADLEKILG", + "count": 1 + } + } + ], + "restraints_config": { + "verbose": true, + "gpu": true, + "max_iter": 100, + "method": "CG", + "angle_restraints_config": [ + { + "atom_selection1": "chain A and ((resid 30 to 59))", + "atom_selection2": "chain A and ((resid 1 to 29) or (resid 60 to 121) or (resid 160 to 214))", + "atom_selection3": "chain A and ((resid 122 to 159))", + "start_sigma": 99999999, + "harmonic": { + "target_angle": 72.85 + } + } + ] + } + } +] diff --git a/examples/angle/mol1/run.sh b/examples/angle/mol1/run.sh new file mode 100755 index 0000000..9acf94a --- /dev/null +++ b/examples/angle/mol1/run.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +WS="$(cd "$HERE/../../../.." && pwd)" +cd "$HERE" +INPUT="${1:-adk_72.85.json}" +test -f "$INPUT" +STEM="$(basename "$INPUT" .json)" +OUT="${OUT_DIR:-out/$STEM}" +export MOL_ROOT_DIR="${MOL_ROOT_DIR:-$WS/Mol-1_restr/data}" +uv run --no-project --python "$WS/Mol-1_restr/.venv/bin/python" mol pred \ + -i "$INPUT" -o "$OUT" --use_msa true --use_template false --use_rna_msa false \ + --seeds 0 --step 200 --sample 1 diff --git a/examples/custom/dist-diff/intellifold/dgot_0.80.json b/examples/custom/dist-diff/intellifold/dgot_0.80.json new file mode 100644 index 0000000..e624634 --- /dev/null +++ b/examples/custom/dist-diff/intellifold/dgot_0.80.json @@ -0,0 +1,38 @@ +{ + "dialect": "alphafold3", + "version": 4, + "name": "dgot_0.80", + "modelSeeds": [ + 0 + ], + "sequences": [ + { + "protein": { + "id": "A", + "sequence": "RRRYLTLVMIFITVVICYVDRANLAVASAHIQEEFGITKAEMGYVFSAFAWLYTLCQIPGGWFLDRVGSRVTYFIAIFGWSVATLFQGFATGLMSLIGLRAITGIFEAPAFPTNNRMVTSWFPEHERASAVGFYTSGQFVGLAFLTPLLIWIQEMLSWHWVFIVTGGIGIIWSLIWFKVYQPPRLTKGISKAELDYIRDGGGLVDGDAPVKKEARQPLTAKDWKLVFHRKLIGVYLGQFAVASTLWFFLTWFPNYLTQEKGITALKAGFMTTVPFLAAFVGVLLSGWVADLLVRKGFSLGFARKTPIICGLLISTCIMGANYTNDPMMIMCLMALAFFGNGFASITWSLVSSLAPMRLIGLTGGVFNFAGGLGGITVPLVVGYLAQGYGFAPALVYISAVALIGALSYILLVGDVKRVG", + "modifications": [], + "templates": [] + } + } + ], + "restraints_config": { + "verbose": true, + "gpu": true, + "max_iter": 100, + "method": "CG", + "custom_restraints_config": [ + { + "name": "double_distres", + "energy": "((distance(A, B) - distance(C, D)) - 0.8)**2", + "selections": { + "A": "chain A and ((resid 1 to 17) or (resid 52 to 66) or (resid 69 to 78) or (resid 108 to 121) or (resid 125 to 139) or (resid 168 to 178))", + "B": "chain A and ((resid 229 to 241) or (resid 280 to 295) or (resid 298 to 311) or (resid 341 to 354) or (resid 358 to 371) or (resid 400 to 412))", + "C": "chain A and ((resid 18 to 34) or (resid 38 to 51) or (resid 79 to 87) or (resid 92 to 107) or (resid 140 to 155) or (resid 158 to 167))", + "D": "chain A and ((resid 242 to 250) or (resid 265 to 279) or (resid 312 to 323) or (resid 325 to 340) or (resid 372 to 386) or (resid 388 to 399))" + }, + "start_sigma": 99999999, + "weight": 1.0 + } + ] + } +} diff --git a/examples/custom/dist-diff/intellifold/run.sh b/examples/custom/dist-diff/intellifold/run.sh new file mode 100755 index 0000000..e57074c --- /dev/null +++ b/examples/custom/dist-diff/intellifold/run.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +WS="$(cd "$HERE/../../../../.." && pwd)" +cd "$HERE" +INPUT="${1:-dgot_0.80.json}" +test -f "$INPUT" +STEM="$(basename "$INPUT" .json)" +OUT="${OUT_DIR:-out/$STEM}" +MODEL_DIR="${MODEL_DIR:-$WS/IntelliFold_restr/model_v2}" +PIPELINE_ARGS=(--norun_data_pipeline) +if [[ "${RUN_DATA_PIPELINE:-true}" == true ]]; then + DB_DIR="${DB_DIR:?set DB_DIR to your sequence-database directory}" + PIPELINE_ARGS=(--run_data_pipeline=true --db_dir="$DB_DIR") +fi +export JAX_COMPILATION_CACHE_DIR="${JAX_COMPILATION_CACHE_DIR:-${TMPDIR:-/tmp}/rgi-intellifold-jax}" +uv run --no-project --python "$WS/IntelliFold_restr/.venv/bin/python" intellifold predict \ + "$INPUT" --model-dir "$MODEL_DIR" --output-dir "$OUT" -- \ + --num_diffusion_samples=1 "${PIPELINE_ARGS[@]}" diff --git a/examples/custom/dist-diff/mol1/dgot_0.80.json b/examples/custom/dist-diff/mol1/dgot_0.80.json new file mode 100644 index 0000000..d005d8a --- /dev/null +++ b/examples/custom/dist-diff/mol1/dgot_0.80.json @@ -0,0 +1,33 @@ +[ + { + "name": "dgot_0.80", + "sequences": [ + { + "proteinChain": { + "sequence": "RRRYLTLVMIFITVVICYVDRANLAVASAHIQEEFGITKAEMGYVFSAFAWLYTLCQIPGGWFLDRVGSRVTYFIAIFGWSVATLFQGFATGLMSLIGLRAITGIFEAPAFPTNNRMVTSWFPEHERASAVGFYTSGQFVGLAFLTPLLIWIQEMLSWHWVFIVTGGIGIIWSLIWFKVYQPPRLTKGISKAELDYIRDGGGLVDGDAPVKKEARQPLTAKDWKLVFHRKLIGVYLGQFAVASTLWFFLTWFPNYLTQEKGITALKAGFMTTVPFLAAFVGVLLSGWVADLLVRKGFSLGFARKTPIICGLLISTCIMGANYTNDPMMIMCLMALAFFGNGFASITWSLVSSLAPMRLIGLTGGVFNFAGGLGGITVPLVVGYLAQGYGFAPALVYISAVALIGALSYILLVGDVKRVG", + "count": 1 + } + } + ], + "restraints_config": { + "verbose": true, + "gpu": true, + "max_iter": 100, + "method": "CG", + "custom_restraints_config": [ + { + "name": "double_distres", + "energy": "((distance(A, B) - distance(C, D)) - 0.8)**2", + "selections": { + "A": "chain A and ((resid 1 to 17) or (resid 52 to 66) or (resid 69 to 78) or (resid 108 to 121) or (resid 125 to 139) or (resid 168 to 178))", + "B": "chain A and ((resid 229 to 241) or (resid 280 to 295) or (resid 298 to 311) or (resid 341 to 354) or (resid 358 to 371) or (resid 400 to 412))", + "C": "chain A and ((resid 18 to 34) or (resid 38 to 51) or (resid 79 to 87) or (resid 92 to 107) or (resid 140 to 155) or (resid 158 to 167))", + "D": "chain A and ((resid 242 to 250) or (resid 265 to 279) or (resid 312 to 323) or (resid 325 to 340) or (resid 372 to 386) or (resid 388 to 399))" + }, + "start_sigma": 99999999, + "weight": 1.0 + } + ] + } + } +] diff --git a/examples/custom/dist-diff/mol1/run.sh b/examples/custom/dist-diff/mol1/run.sh new file mode 100755 index 0000000..e3f6b8d --- /dev/null +++ b/examples/custom/dist-diff/mol1/run.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +WS="$(cd "$HERE/../../../../.." && pwd)" +cd "$HERE" +INPUT="${1:-dgot_0.80.json}" +test -f "$INPUT" +STEM="$(basename "$INPUT" .json)" +OUT="${OUT_DIR:-out/$STEM}" +export MOL_ROOT_DIR="${MOL_ROOT_DIR:-$WS/Mol-1_restr/data}" +uv run --no-project --python "$WS/Mol-1_restr/.venv/bin/python" mol pred \ + -i "$INPUT" -o "$OUT" --use_msa true --use_template false --use_rna_msa false \ + --seeds 0 --step 200 --sample 1 diff --git a/examples/distance/intellifold/qbp_25.00.json b/examples/distance/intellifold/qbp_25.00.json new file mode 100644 index 0000000..59b5f16 --- /dev/null +++ b/examples/distance/intellifold/qbp_25.00.json @@ -0,0 +1,34 @@ +{ + "dialect": "alphafold3", + "version": 4, + "name": "qbp_25.00", + "modelSeeds": [ + 0 + ], + "sequences": [ + { + "protein": { + "id": "A", + "sequence": "ADKKLVVATDTAFVPFEFKQGDKYVGFDVDLWAAIAKELKLDYELKPMDFSGIIPALQTKNVDLALAGITITDERKKAIDFSDGYYKSGLLVMVKANNNDVKSVKDLDGKVVAVKSGTGSVDYAKANIKTKDLRQFPNIDNAYMELGTNRADAVLHDTPNILYFIKTAGNGQFKAVGDSLEAQQYGIAFPKGSDELRDKVNGALKTLRENGTYNEIYKKWFGTEPK", + "modifications": [], + "templates": [] + } + } + ], + "restraints_config": { + "verbose": true, + "gpu": true, + "max_iter": 100, + "method": "CG", + "distance_restraints_config": [ + { + "atom_selection1": "chain A and ((resid 4 to 83) or (resid 185 to 223))", + "atom_selection2": "chain A and ((resid 89 to 179))", + "start_sigma": 99999999, + "harmonic": { + "target_distance": 25.0 + } + } + ] + } +} diff --git a/examples/distance/intellifold/run.sh b/examples/distance/intellifold/run.sh new file mode 100755 index 0000000..700a090 --- /dev/null +++ b/examples/distance/intellifold/run.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +WS="$(cd "$HERE/../../../.." && pwd)" +cd "$HERE" +INPUT="${1:-qbp_25.00.json}" +test -f "$INPUT" +STEM="$(basename "$INPUT" .json)" +OUT="${OUT_DIR:-out/$STEM}" +MODEL_DIR="${MODEL_DIR:-$WS/IntelliFold_restr/model_v2}" +PIPELINE_ARGS=(--norun_data_pipeline) +if [[ "${RUN_DATA_PIPELINE:-true}" == true ]]; then + DB_DIR="${DB_DIR:?set DB_DIR to your sequence-database directory}" + PIPELINE_ARGS=(--run_data_pipeline=true --db_dir="$DB_DIR") +fi +export JAX_COMPILATION_CACHE_DIR="${JAX_COMPILATION_CACHE_DIR:-${TMPDIR:-/tmp}/rgi-intellifold-jax}" +uv run --no-project --python "$WS/IntelliFold_restr/.venv/bin/python" intellifold predict \ + "$INPUT" --model-dir "$MODEL_DIR" --output-dir "$OUT" -- \ + --num_diffusion_samples=1 "${PIPELINE_ARGS[@]}" diff --git a/examples/distance/mol1/qbp_25.00.json b/examples/distance/mol1/qbp_25.00.json new file mode 100644 index 0000000..7ded97e --- /dev/null +++ b/examples/distance/mol1/qbp_25.00.json @@ -0,0 +1,29 @@ +[ + { + "name": "qbp_25.00", + "sequences": [ + { + "proteinChain": { + "sequence": "ADKKLVVATDTAFVPFEFKQGDKYVGFDVDLWAAIAKELKLDYELKPMDFSGIIPALQTKNVDLALAGITITDERKKAIDFSDGYYKSGLLVMVKANNNDVKSVKDLDGKVVAVKSGTGSVDYAKANIKTKDLRQFPNIDNAYMELGTNRADAVLHDTPNILYFIKTAGNGQFKAVGDSLEAQQYGIAFPKGSDELRDKVNGALKTLRENGTYNEIYKKWFGTEPK", + "count": 1 + } + } + ], + "restraints_config": { + "verbose": true, + "gpu": true, + "max_iter": 100, + "method": "CG", + "distance_restraints_config": [ + { + "atom_selection1": "chain A and ((resid 4 to 83) or (resid 185 to 223))", + "atom_selection2": "chain A and ((resid 89 to 179))", + "start_sigma": 99999999, + "harmonic": { + "target_distance": 25.0 + } + } + ] + } + } +] diff --git a/examples/distance/mol1/run.sh b/examples/distance/mol1/run.sh new file mode 100755 index 0000000..40b7d78 --- /dev/null +++ b/examples/distance/mol1/run.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +WS="$(cd "$HERE/../../../.." && pwd)" +cd "$HERE" +INPUT="${1:-qbp_25.00.json}" +test -f "$INPUT" +STEM="$(basename "$INPUT" .json)" +OUT="${OUT_DIR:-out/$STEM}" +export MOL_ROOT_DIR="${MOL_ROOT_DIR:-$WS/Mol-1_restr/data}" +uv run --no-project --python "$WS/Mol-1_restr/.venv/bin/python" mol pred \ + -i "$INPUT" -o "$OUT" --use_msa true --use_template false --use_rna_msa false \ + --seeds 0 --step 200 --sample 1 diff --git a/examples/ligand-dissociation/intellifold/mdm2_p53_30.00.json b/examples/ligand-dissociation/intellifold/mdm2_p53_30.00.json new file mode 100644 index 0000000..d6513ca --- /dev/null +++ b/examples/ligand-dissociation/intellifold/mdm2_p53_30.00.json @@ -0,0 +1,40 @@ +{ + "dialect": "alphafold3", + "version": 4, + "name": "mdm2_p53_30.00", + "modelSeeds": [ + 0 + ], + "sequences": [ + { + "protein": { + "id": "A", + "sequence": "NHISTSDQEKLVQPTPLLLSLLKSAGAQKETFTMKEVIYHLGQYIMAKQLYDEKQQHIVHCSNDPLGELFGVQEFSVKEPRRLYAMISRNLVSANVKESSEDIFGNV", + "templates": [] + } + }, + { + "protein": { + "id": "B", + "sequence": "PLSQETFSDLWKLLPEN", + "templates": [] + } + } + ], + "restraints_config": { + "verbose": true, + "max_iter": 1000, + "method": "CG", + "distance_restraints_config": [ + { + "atom_selection1": "chain A", + "atom_selection2": "chain B", + "harmonic": { + "target_distance": 30.0 + }, + "start_sigma": 99999999 + } + ], + "gpu": true + } +} diff --git a/examples/ligand-dissociation/intellifold/run.sh b/examples/ligand-dissociation/intellifold/run.sh new file mode 100755 index 0000000..0dc49d7 --- /dev/null +++ b/examples/ligand-dissociation/intellifold/run.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +WS="$(cd "$HERE/../../../.." && pwd)" +cd "$HERE" +INPUT="${1:-mdm2_p53_30.00.json}" +test -f "$INPUT" +STEM="$(basename "$INPUT" .json)" +OUT="${OUT_DIR:-out/$STEM}" +MODEL_DIR="${MODEL_DIR:-$WS/IntelliFold_restr/model_v2}" +PIPELINE_ARGS=(--norun_data_pipeline) +if [[ "${RUN_DATA_PIPELINE:-true}" == true ]]; then + DB_DIR="${DB_DIR:?set DB_DIR to your sequence-database directory}" + PIPELINE_ARGS=(--run_data_pipeline=true --db_dir="$DB_DIR") +fi +export JAX_COMPILATION_CACHE_DIR="${JAX_COMPILATION_CACHE_DIR:-${TMPDIR:-/tmp}/rgi-intellifold-jax}" +uv run --no-project --python "$WS/IntelliFold_restr/.venv/bin/python" intellifold predict \ + "$INPUT" --model-dir "$MODEL_DIR" --output-dir "$OUT" -- \ + --num_diffusion_samples=1 "${PIPELINE_ARGS[@]}" diff --git a/examples/ligand-dissociation/mol1/mdm2_p53_30.00.json b/examples/ligand-dissociation/mol1/mdm2_p53_30.00.json new file mode 100644 index 0000000..5256eda --- /dev/null +++ b/examples/ligand-dissociation/mol1/mdm2_p53_30.00.json @@ -0,0 +1,35 @@ +[ + { + "name": "mdm2_p53_30.00", + "sequences": [ + { + "proteinChain": { + "sequence": "NHISTSDQEKLVQPTPLLLSLLKSAGAQKETFTMKEVIYHLGQYIMAKQLYDEKQQHIVHCSNDPLGELFGVQEFSVKEPRRLYAMISRNLVSANVKESSEDIFGNV", + "count": 1 + } + }, + { + "proteinChain": { + "sequence": "PLSQETFSDLWKLLPEN", + "count": 1 + } + } + ], + "restraints_config": { + "verbose": true, + "max_iter": 1000, + "method": "CG", + "distance_restraints_config": [ + { + "atom_selection1": "chain A", + "atom_selection2": "chain B", + "harmonic": { + "target_distance": 30.0 + }, + "start_sigma": 99999999 + } + ], + "gpu": true + } + } +] diff --git a/examples/ligand-dissociation/mol1/run.sh b/examples/ligand-dissociation/mol1/run.sh new file mode 100755 index 0000000..a2852b5 --- /dev/null +++ b/examples/ligand-dissociation/mol1/run.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +WS="$(cd "$HERE/../../../.." && pwd)" +cd "$HERE" +INPUT="${1:-mdm2_p53_30.00.json}" +test -f "$INPUT" +STEM="$(basename "$INPUT" .json)" +OUT="${OUT_DIR:-out/$STEM}" +export MOL_ROOT_DIR="${MOL_ROOT_DIR:-$WS/Mol-1_restr/data}" +uv run --no-project --python "$WS/Mol-1_restr/.venv/bin/python" mol pred \ + -i "$INPUT" -o "$OUT" --use_msa true --use_template false --use_rna_msa false \ + --seeds 0 --step 200 --sample 1 diff --git a/examples/rmsd/intellifold/qbp_2.65.json b/examples/rmsd/intellifold/qbp_2.65.json new file mode 100644 index 0000000..bf14660 --- /dev/null +++ b/examples/rmsd/intellifold/qbp_2.65.json @@ -0,0 +1,52 @@ +{ + "dialect": "alphafold3", + "version": 4, + "name": "qbp_2.65", + "modelSeeds": [ + 0 + ], + "sequences": [ + { + "protein": { + "id": "A", + "sequence": "ADKKLVVATDTAFVPFEFKQGDKYVGFDVDLWAAIAKELKLDYELKPMDFSGIIPALQTKNVDLALAGITITDERKKAIDFSDGYYKSGLLVMVKANNNDVKSVKDLDGKVVAVKSGTGSVDYAKANIKTKDLRQFPNIDNAYMELGTNRADAVLHDTPNILYFIKTAGNGQFKAVGDSLEAQQYGIAFPKGSDELRDKVNGALKTLRENGTYNEIYKKWFGTEPK", + "modifications": [], + "templates": [] + } + } + ], + "restraints_config": { + "verbose": true, + "gpu": true, + "max_iter": 1000, + "method": "CG", + "rmsd_restraints_config": [ + { + "ref_cif": "1GGG.cif", + "atom_selection_ref_fit": "chain A and name CA and resid 1 to 220", + "atom_selection_target_fit": "chain A and name CA and resid 5 to 224", + "atom_selection_ref_calc": "chain A and name CA and resid 1 to 220", + "atom_selection_target_calc": "chain A and name CA and resid 5 to 224", + "pairing": "align", + "start_sigma": 99999999, + "stop_sigma": 1.5, + "harmonic": { + "target_rmsd": 2.65 + } + }, + { + "ref_cif": "1WDN.cif", + "atom_selection_ref_fit": "chain A and name CA and resid 2 to 221", + "atom_selection_target_fit": "chain A and name CA and resid 5 to 224", + "atom_selection_ref_calc": "chain A and name CA and resid 2 to 221", + "atom_selection_target_calc": "chain A and name CA and resid 5 to 224", + "pairing": "align", + "start_sigma": 99999999, + "stop_sigma": 1.5, + "harmonic": { + "target_rmsd": 2.65 + } + } + ] + } +} diff --git a/examples/rmsd/intellifold/run.sh b/examples/rmsd/intellifold/run.sh new file mode 100755 index 0000000..ce48888 --- /dev/null +++ b/examples/rmsd/intellifold/run.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +WS="$(cd "$HERE/../../../.." && pwd)" +cd "$HERE" +INPUT="${1:-qbp_2.65.json}" +test -f "$INPUT" +STEM="$(basename "$INPUT" .json)" +OUT="${OUT_DIR:-out/$STEM}" +for pdb in 1GGG 1WDN; do + test -f "$pdb.cif" || curl -fLsS "https://files.rcsb.org/download/$pdb.cif" -o "$pdb.cif" +done +MODEL_DIR="${MODEL_DIR:-$WS/IntelliFold_restr/model_v2}" +PIPELINE_ARGS=(--norun_data_pipeline) +if [[ "${RUN_DATA_PIPELINE:-true}" == true ]]; then + DB_DIR="${DB_DIR:?set DB_DIR to your sequence-database directory}" + PIPELINE_ARGS=(--run_data_pipeline=true --db_dir="$DB_DIR") +fi +export JAX_COMPILATION_CACHE_DIR="${JAX_COMPILATION_CACHE_DIR:-${TMPDIR:-/tmp}/rgi-intellifold-jax}" +uv run --no-project --python "$WS/IntelliFold_restr/.venv/bin/python" intellifold predict \ + "$INPUT" --model-dir "$MODEL_DIR" --output-dir "$OUT" -- \ + --num_diffusion_samples=1 "${PIPELINE_ARGS[@]}" diff --git a/examples/rmsd/mol1/qbp_2.65.json b/examples/rmsd/mol1/qbp_2.65.json new file mode 100644 index 0000000..e81a5c4 --- /dev/null +++ b/examples/rmsd/mol1/qbp_2.65.json @@ -0,0 +1,47 @@ +[ + { + "name": "qbp_2.65", + "sequences": [ + { + "proteinChain": { + "sequence": "ADKKLVVATDTAFVPFEFKQGDKYVGFDVDLWAAIAKELKLDYELKPMDFSGIIPALQTKNVDLALAGITITDERKKAIDFSDGYYKSGLLVMVKANNNDVKSVKDLDGKVVAVKSGTGSVDYAKANIKTKDLRQFPNIDNAYMELGTNRADAVLHDTPNILYFIKTAGNGQFKAVGDSLEAQQYGIAFPKGSDELRDKVNGALKTLRENGTYNEIYKKWFGTEPK", + "count": 1 + } + } + ], + "restraints_config": { + "verbose": true, + "gpu": true, + "max_iter": 1000, + "method": "CG", + "rmsd_restraints_config": [ + { + "ref_cif": "1GGG.cif", + "atom_selection_ref_fit": "chain A and name CA and resid 1 to 220", + "atom_selection_target_fit": "chain A and name CA and resid 5 to 224", + "atom_selection_ref_calc": "chain A and name CA and resid 1 to 220", + "atom_selection_target_calc": "chain A and name CA and resid 5 to 224", + "pairing": "align", + "start_sigma": 99999999, + "stop_sigma": 1.5, + "harmonic": { + "target_rmsd": 2.65 + } + }, + { + "ref_cif": "1WDN.cif", + "atom_selection_ref_fit": "chain A and name CA and resid 2 to 221", + "atom_selection_target_fit": "chain A and name CA and resid 5 to 224", + "atom_selection_ref_calc": "chain A and name CA and resid 2 to 221", + "atom_selection_target_calc": "chain A and name CA and resid 5 to 224", + "pairing": "align", + "start_sigma": 99999999, + "stop_sigma": 1.5, + "harmonic": { + "target_rmsd": 2.65 + } + } + ] + } + } +] diff --git a/examples/rmsd/mol1/run.sh b/examples/rmsd/mol1/run.sh new file mode 100755 index 0000000..5eee033 --- /dev/null +++ b/examples/rmsd/mol1/run.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +WS="$(cd "$HERE/../../../.." && pwd)" +cd "$HERE" +INPUT="${1:-qbp_2.65.json}" +test -f "$INPUT" +STEM="$(basename "$INPUT" .json)" +OUT="${OUT_DIR:-out/$STEM}" +for pdb in 1GGG 1WDN; do + test -f "$pdb.cif" || curl -fLsS "https://files.rcsb.org/download/$pdb.cif" -o "$pdb.cif" +done +export MOL_ROOT_DIR="${MOL_ROOT_DIR:-$WS/Mol-1_restr/data}" +uv run --no-project --python "$WS/Mol-1_restr/.venv/bin/python" mol pred \ + -i "$INPUT" -o "$OUT" --use_msa true --use_template false --use_rna_msa false \ + --seeds 0 --step 200 --sample 1 diff --git a/pyproject.toml b/pyproject.toml index acc0ee4..0cd59a6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "rgi-toolkit" -version = "0.4.7" +version = "0.5.0" description = "Restraint-Guided Inference toolkit for PyTorch/JAX-based structure prediction models" readme = "README.md" requires-python = ">=3.12" @@ -21,7 +21,7 @@ torch = [ "torch>=2.2", "cuda-bindings>=12.8,<14; sys_platform == 'linux'", ] -# JAX backend (alphafold3). Pure JAX CG by default; jaxopt for optional L-BFGS. +# JAX backend (AlphaFold 3 and IntelliFold). Pure JAX CG by default; jaxopt for optional L-BFGS. jax = [ "jax", "jaxlib", diff --git a/src/rgi_toolkit/intellifold/__init__.py b/src/rgi_toolkit/intellifold/__init__.py new file mode 100644 index 0000000..e8c153c --- /dev/null +++ b/src/rgi_toolkit/intellifold/__init__.py @@ -0,0 +1 @@ +"""IntelliFold JAX integration adapters.""" diff --git a/src/rgi_toolkit/intellifold/adapter.py b/src/rgi_toolkit/intellifold/adapter.py new file mode 100644 index 0000000..0e616a7 --- /dev/null +++ b/src/rgi_toolkit/intellifold/adapter.py @@ -0,0 +1,7 @@ +"""Framework-free adapter for IntelliFold's vendored AlphaFold 3 JAX engine.""" + +from rgi_toolkit.alphafold3.adapter import AF3RestraintAdapter + + +class IntelliFoldAdapter(AF3RestraintAdapter): + """Use the shared AF3 token layout, chain mapping and ligand chemistry.""" diff --git a/src/rgi_toolkit/mol1/__init__.py b/src/rgi_toolkit/mol1/__init__.py new file mode 100644 index 0000000..9ce9119 --- /dev/null +++ b/src/rgi_toolkit/mol1/__init__.py @@ -0,0 +1 @@ +"""Mol-1 integration adapters.""" diff --git a/src/rgi_toolkit/mol1/adapter.py b/src/rgi_toolkit/mol1/adapter.py new file mode 100644 index 0000000..6a6e439 --- /dev/null +++ b/src/rgi_toolkit/mol1/adapter.py @@ -0,0 +1,29 @@ +"""Framework-free adapter for Mol-1's Protenix-shaped inference features.""" + +from __future__ import annotations + +from dataclasses import replace +from typing import Iterator + +from rgi_toolkit.atom_context import AtomRecord +from rgi_toolkit.protenix.adapter import ProtenixAdapter + + +class Mol1Adapter(ProtenixAdapter): + """Reuse shared chemistry while numbering the model's actual tokens per chain.""" + + def __init__(self, input_feature_dict: dict) -> None: + super().__init__(input_feature_dict) + if self.atom_array is None: + raise ValueError("Mol-1 restraints require the inference atom_array") + if len(self.atom_array) > self.num_atoms(): + raise ValueError("Mol-1 atom_array exceeds the coordinate atom axis") + self._atom_to_token = self._feature_numpy("atom_to_token_idx") + + def iter_atoms(self) -> Iterator[AtomRecord]: + chain_tokens: dict[str, dict[int, int]] = {} + for atom in super().iter_atoms(): + token = int(self._atom_to_token[atom.index]) + seen = chain_tokens.setdefault(atom.chain, {}) + ordinal = seen.setdefault(token, len(seen) + 1) + yield replace(atom, resid=ordinal) diff --git a/tests/ci.txt b/tests/ci.txt index d37cba3..479b69f 100644 --- a/tests/ci.txt +++ b/tests/ci.txt @@ -1,3 +1,4 @@ +tests/test_mol1_intellifold_adapters.py tests/test_adapters_shared.py tests/test_bioemu2_adapter.py tests/test_align.py diff --git a/tests/test_mol1_intellifold_adapters.py b/tests/test_mol1_intellifold_adapters.py new file mode 100644 index 0000000..127cb32 --- /dev/null +++ b/tests/test_mol1_intellifold_adapters.py @@ -0,0 +1,126 @@ +"""New predictor adapters preserve atom layout, chemistry and chain ordinals.""" + +from __future__ import annotations + +import subprocess +import sys + +import numpy as np +import pytest +from rdkit import Chem +from rdkit.Chem import AllChem + +from rgi_toolkit.intellifold.adapter import IntelliFoldAdapter +from rgi_toolkit.mol1.adapter import Mol1Adapter + + +class AtomArray: + def __init__(self, **annotations): + self.__dict__.update(annotations) + self.bonds = None + + def __len__(self): + return len(self.element) + + def get_annotation_categories(self): + return list(self.__dict__) + + +def test_mol1_uses_model_tokens_and_preserves_padding(): + aa = AtomArray( + label_asym_id=np.array(["Z", "Z", "Z", "B", "B", "B"]), + res_id=np.array([42, 42, 42, 100, 100, 101]), + hetero=np.zeros(6, dtype=bool), + atom_name=np.array(["CA", "CB", "X", "P", "C1'", "P"]), + res_name=np.array(["ALA", "ALA", "MOD", "DA", "DA", "DT"]), + mol_type=np.array(["protein"] * 3 + ["dna"] * 3), + conformer_restraints=np.array([True] * 3 + [False] * 3), + element=np.array(["C", "C", "N", "P", "C", "P"]), + ) + ref = np.arange(24).reshape(8, 3) + adapter = Mol1Adapter( + { + "atom_array": aa, + "atom_to_token_idx": np.array([4, 4, 5, 6, 6, 7, 0, 0]), + "ref_pos": ref, + "ref_space_uid": np.arange(8), + } + ) + atoms = list(adapter.iter_atoms()) + assert [a.resid for a in atoms] == [1, 1, 2, 1, 1, 2] + assert [a.index for a in atoms] == list(range(6)) + assert [a.conformer_restraints for a in atoms] == [True] * 3 + [False] * 3 + assert atoms[4].name == "C1'" and atoms[4].mol_type == "dna" + assert adapter.num_atoms() == 8 + np.testing.assert_array_equal(adapter.get_elements(), [6, 6, 7, 15, 6, 15, 0, 0]) + np.testing.assert_array_equal(adapter.get_reference_positions(), ref) + np.testing.assert_array_equal(adapter.get_reference_space_uid(), np.arange(8)) + + +def test_mol1_rejects_missing_atom_metadata(): + with pytest.raises(ValueError, match="atom_array"): + Mol1Adapter({"atom_to_token_idx": np.arange(2)}) + + +def test_intellifold_flat_indices_source_stereo_and_opt_in(): + smol = Chem.AddHs(Chem.MolFromSmiles("F/C=C/Cl")) + assert AllChem.EmbedMolecule(smol, randomSeed=11) == 0 + smol = Chem.RemoveHs(smol) + coords = smol.GetConformer().GetPositions() + mask = np.zeros((6, 3), dtype=bool) + mask[:5, 0] = True + names = np.zeros((6, 3, 4), dtype=int) + for token, name in enumerate(["CA", "F1", "C1", "C2", "CL1"]): + names[token, 0, : len(name)] = [ord(c) - 32 for c in name] + ref = np.zeros((6, 3, 3)) + ref[1:5, 0] = coords + batch = { + "asym_id": np.array([1, 2, 2, 2, 2, 0]), + "ref_mask": mask, + "ref_pos": ref, + "ref_element": np.array( + [[6, 0, 0], [9, 0, 0], [6, 0, 0], [6, 0, 0], [17, 0, 0], [0, 0, 0]] + ), + "ref_atom_name_chars": names, + "is_protein": np.array([True, False, False, False, False, False]), + "is_dna": np.zeros(6, dtype=bool), + "is_rna": np.zeros(6, dtype=bool), + "aatype": np.zeros(6, dtype=int), + } + adapter = IntelliFoldAdapter( + batch, + {"P": 1, "L": 2}, + ("ALA",), + [("L", smol, True)], + conformer_restraints_by_asym={1: False, 2: True}, + ) + atoms = list(adapter.iter_atoms()) + assert [(a.chain, a.resid, a.index) for a in atoms] == [ + ("P", 1, 0), + ("L", 1, 3), + ("L", 2, 6), + ("L", 3, 9), + ("L", 4, 12), + ] + (conf,) = adapter.iter_ligand_confs() + np.testing.assert_array_equal(conf.global_indices, [3, 6, 9, 12]) + np.testing.assert_allclose(conf.conf_coords, coords) + assert conf.conformer_restraints + assert Chem.MolToSmiles(conf.stereo_mol) == "F/C=C/Cl" + assert adapter.num_atoms() == 18 + assert not list( + IntelliFoldAdapter(batch, {"P": 1, "L": 2}, ("ALA",), []).iter_ligand_confs() + ) + + +def test_new_adapters_import_without_predictors_or_backends(): + subprocess.run( + [ + sys.executable, + "-c", + "import sys; import rgi_toolkit.mol1.adapter; " + "import rgi_toolkit.intellifold.adapter; " + "assert not {'mol', 'intellifold', 'alphafold3', 'torch', 'jax'} & sys.modules.keys()", + ], + check=True, + ) diff --git a/uv.lock b/uv.lock index af2c49e..ac41195 100644 --- a/uv.lock +++ b/uv.lock @@ -791,7 +791,7 @@ wheels = [ [[package]] name = "rgi-toolkit" -version = "0.4.7" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "biopython" },