{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "gpuType": "T4" }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": "# 🧬 DiffTopo — Protein Topology Generation & Design Pipeline\n\n**Paper:** *Leveraging protein representations to explore uncharted fold spaces with generative models*\n\n### Pipeline\n1. **DiffTopo** — DDPM diffusion generates coarse-grained (CG) protein topologies conditioned on SSE strings\n2. **Build Sketch** — CG topology → all-atom PDB scaffold via `build_sketch.py`\n3. **RFdiffusion** — full diffusion (loop design) + partial diffusion (backbone diversification)\n4. **ProteinMPNN + AlphaFold2** — sequence design & self-consistency validation\n\n### Before running\n**Runtime:** GPU required (T4 or better). Set via *Runtime → Change runtime type → GPU*\n\n**Upload to Google Drive** under `MyDrive/DiffTopo/`:\n```\nDiffTopo/\n ckpt/\n dimer.ckpt # dimer checkpoint (required)\n monomer.ckpt # monomer checkpoint (optional)\n filtcathgraphlist_simple.pt # CATH dataset (download: bit.ly/difftopo-data)\n cath_sse_patterns.tsv # SSE pattern library\n af2_params/ # AlphaFold2 params folder\n```\n" }, { "cell_type": "markdown", "metadata": {}, "source": "## 0. Mount Google Drive" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "from google.colab import drive\ndrive.mount('/content/drive')\nimport os, sys\n\n# ─── Edit these paths to match your Google Drive layout ───────────────────\nGDRIVE = '/content/drive/MyDrive/DiffTopo'\nCKPT_DIMER = f'{GDRIVE}/ckpt/dimer.ckpt'\nCKPT_MONOMER = f'{GDRIVE}/ckpt/monomer.ckpt'\nDATA_PT = f'{GDRIVE}/filtcathgraphlist_simple.pt'\nCATH_TSV = f'{GDRIVE}/cath_sse_patterns.tsv'\nAF2_PARAMS = f'{GDRIVE}/af2_params'\n# ──────────────────────────────────────────────────────────────────────────\n\nWORK = '/content/DiffTopo_colab'\nRF_DIR = '/content/RFdiffusion'\nCD_DIR = '/content/ColabDesign'\nOUTPUT = '/content/output'\nos.makedirs(OUTPUT, exist_ok=True)\n\nprint('Checking required files:')\nok = True\nfor path, name in [(CKPT_DIMER,'dimer.ckpt'), (DATA_PT,'filtcathgraphlist_simple.pt'),\n (CATH_TSV,'cath_sse_patterns.tsv'), (AF2_PARAMS,'af2_params')]:\n found = os.path.exists(path)\n ok = ok and found\n print(f' [{\"āœ“\" if found else \"āœ— MISSING\"}] {name}')\nif not ok:\n print('\\n⚠ Upload missing files to Google Drive before continuing.')\n" }, { "cell_type": "markdown", "metadata": {}, "source": "## 1. Install dependencies\n> ā± ~5 min on first run. Safe to re-run — skips already-installed tools." }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "import subprocess, torch\n\ndef sh(cmd, **kw):\n r = subprocess.run(cmd, shell=True, text=True, capture_output=True, **kw)\n if r.returncode != 0: print(r.stderr[-1500:])\n return r.returncode\n\n# ── PyTorch Geometric (match installed torch + CUDA) ──\nTV = torch.__version__.split('+')[0]\nCU = 'cu' + torch.version.cuda.replace('.','') if torch.cuda.is_available() else 'cpu'\nprint(f'PyTorch {TV} CUDA {CU} GPU={torch.cuda.is_available()}')\nsh(f'pip install -q torch-scatter torch-sparse torch-cluster '\n f'-f https://data.pyg.org/whl/torch-{TV}+{CU}.html')\nsh('pip install -q torch-geometric')\n\n# ── Other Python deps ──\nsh('pip install -q pytorch-lightning==2.3.0 biotite==0.35.0 '\n 'biopython transforms3d icecream pandas seaborn py3Dmol')\n\n# ── RFdiffusion ──\nif not os.path.isdir(RF_DIR):\n sh(f'git clone -q https://github.com/RosettaCommons/RFdiffusion {RF_DIR}')\n sh(f'pip install -q -e {RF_DIR}')\n sh('pip install -q opt_einsum e3nn pyrsistent')\n print('RFdiffusion installed.')\n\nRF_CKPT = f'{RF_DIR}/models/Base_ckpt.pt'\nif not os.path.exists(RF_CKPT):\n print('Downloading RFdiffusion Base weights (~1 GB)...')\n sh(f'wget -q -O {RF_CKPT} '\n 'http://files.ipd.uw.edu/pub/RFdiffusion/'\n '6f5902ac237024bdd0c176cb93063dc6/Base_ckpt.pt')\n print(' Done.')\n\n# ── ColabDesign ──\nif not os.path.isdir(CD_DIR):\n sh(f'git clone -q https://github.com/sokrypton/ColabDesign {CD_DIR}')\n sh(f'pip install -q -e {CD_DIR}')\n sh('pip install -q \"jax[cuda12_pip]\" '\n '-f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html')\n print('ColabDesign + JAX installed.')\n\n# ── DiffTopo code ──\nif not os.path.isdir(WORK):\n # Option A: clone from GitHub (if public)\n # sh(f'git clone -q https://github.com/YOUR_ORG/DiffTopo {WORK}')\n # Option B: copy from Drive\n sh(f'cp -r {GDRIVE}/DiffTopo_colab {WORK}')\n print(f'DiffTopo code ready at {WORK}')\nsys.path.insert(0, WORK)\nprint('All dependencies ready āœ“')\n" }, { "cell_type": "markdown", "metadata": {}, "source": "## 2. Parameters\n\n| `MODE` | Description | SSE pattern |\n|--------|-------------|-------------|\n| `allH` | Single-chain all-helix | 25 Ɨ H |\n| `allE` | Single-chain all-strand | 25 Ɨ E |\n| `custom` | Your SSE string | see `CUSTOM_SSE` |\n| `dimer_allH` | All-helix dimer (both chains) | 25H + 25H |\n| `dimer_allE` | All-strand dimer | 25E + 25E |\n" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ═══════════════════════════════════════════════════\n# āœļø EDIT THESE\n# ═══════════════════════════════════════════════════\nMODE = 'allH' # allH | allE | custom | dimer_allH | dimer_allE\nCUSTOM_SSE = 'HEHEEHEHEHHEHEEHEHEHEHEHEHHHHEH' # only used if MODE='custom'\nTARGET_COUNT = 5 # sketches to generate (use 50-500 for production)\n\nNUM_DESIGNS = 1 # RFdiffusion full-diffusion designs per sketch\nPARTIAL_T = 10 # partial diffusion steps\nPARTIAL_DESN = 3 # partial diffusion samples per backbone\n\nMPNN_SEQNUM = 8 # sequences per backbone (16-32 for production)\nMPNN_TEMP = 0.2 # MPNN sampling temperature\nAF2_RECYCLES = 3 # AlphaFold2 recycles\n# ═══════════════════════════════════════════════════\n\n_sse_map = {\n 'allH': ('H'*25, None),\n 'allE': ('E'*25, None),\n 'custom': (CUSTOM_SSE, None),\n 'dimer_allH': ('H'*25, 'H'*25),\n 'dimer_allE': ('E'*25, 'E'*25),\n}\nSSE_A, SSE_B = _sse_map[MODE]\nIS_DIMER = SSE_B is not None\nRUN_DIR = f'{OUTPUT}/{MODE}'\nSKETCH_DIR = f'{RUN_DIR}/sketches'\nos.makedirs(SKETCH_DIR, exist_ok=True)\n\nprint(f'Mode : {MODE}')\nprint(f'SSE A : {SSE_A}')\nprint(f'SSE B : {SSE_B}')\nprint(f'Is dimer : {IS_DIMER}')\nprint(f'Target : {TARGET_COUNT} sketches')\nprint(f'Output : {RUN_DIR}')\n" }, { "cell_type": "markdown", "metadata": {}, "source": "## 3. DiffTopo — generate CG topologies\n\nCalls `generate_large.py` (single chain) or `generate_pinder.py` (dimer).\nOutput: `large_topologies.npy` — shape `[N, 7]` with columns `[x,y,z, ss1,ss2, chain_id, batch]`." }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "import subprocess\n\nTOPO_NPY = f'{RUN_DIR}/large_topologies.npy'\nCKPT = CKPT_DIMER # always use dimer checkpoint (supports both modes)\n\nif IS_DIMER:\n script = f'{WORK}/generate_pinder.py'\n extra = [\n '--fixed_pattern_A', SSE_A,\n '--fixed_pattern_B', SSE_B,\n '--output_dir', RUN_DIR,\n '--min_aa_total', '200',\n '--max_aa_total', '1400',\n '--max_loop', '999.0',\n ]\n TOPO_NPY = f'{RUN_DIR}/dimer_topologies.npy'\nelse:\n script = f'{WORK}/generate_large.py'\n extra = [\n '--fixed_pattern', SSE_A,\n '--output_dir', RUN_DIR,\n '--min_aa', '80' if 'E' in SSE_A else '150',\n '--max_aa', '500' if 'E' in SSE_A else '700',\n '--max_loop', '30.0',\n '--max_rg_factor', '1.3',\n '--cath_patterns', CATH_TSV,\n ]\n\ncmd = [\n sys.executable, script,\n '--checkpoint', CKPT,\n '--data', DATA_PT,\n '--target_count', str(TARGET_COUNT),\n '--num_trials', str(TARGET_COUNT * 30),\n '--batch_size', '16',\n '--device', 'cuda',\n] + extra\n\nprint('Running:', ' '.join(cmd[:6]), '...')\nr = subprocess.run(cmd, text=True)\nif r.returncode != 0:\n print('Generation failed.')\nelse:\n import numpy as np\n topo = np.load(TOPO_NPY)\n n_structs = len(np.unique(topo[:, -1]))\n print(f'\\nāœ“ Saved {n_structs} topologies → {TOPO_NPY}')\n" }, { "cell_type": "markdown", "metadata": {}, "source": "### 3a. Visualise generated CG topologies" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "import numpy as np\nimport matplotlib.pyplot as plt\n\ntopo = np.load(TOPO_NPY)\nbatch_col = topo[:, -1]\nuids = np.unique(batch_col)\nn_show = min(6, len(uids))\n\nfig = plt.figure(figsize=(4 * n_show, 4))\nfor i, uid in enumerate(uids[:n_show]):\n ax = fig.add_subplot(1, n_show, i+1, projection='3d')\n pts = topo[batch_col == uid, :3]\n ss = topo[batch_col == uid, 3]\n c = ['red' if s > 0.5 else 'royalblue' for s in ss]\n ax.scatter(*pts.T, c=c, s=20)\n ax.plot(*pts.T, 'k-', alpha=0.15, lw=0.7)\n ax.set_axis_off()\n ax.set_title(f'Topo {i}', fontsize=9)\n\nfrom matplotlib.patches import Patch\nfig.legend(handles=[Patch(color='red',label='Helix'),\n Patch(color='royalblue',label='Strand')],\n loc='lower center', ncol=2, fontsize=9)\nplt.suptitle(f'DiffTopo CG topologies — {MODE}', fontsize=11)\nplt.tight_layout()\nplt.savefig(f'{RUN_DIR}/topologies.png', dpi=100, bbox_inches='tight')\nplt.show()\n" }, { "cell_type": "markdown", "metadata": {}, "source": "## 4. Build Sketch — CG → all-atom PDB\n\nCalls `build_sketch.py` to convert each CG topology into an all-atom PDB scaffold.\nOutput: `sketches/sketch{i}.pdb` and `sketches/new_sketch.npy` (contig info)." }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "cmd = [\n sys.executable, f'{WORK}/build_sketch.py',\n '--input', TOPO_NPY,\n '--output', SKETCH_DIR,\n '--dimer', str(IS_DIMER),\n '--downstream', 'False', # we run downstream manually below\n '--filt_rg', 'False',\n '--filt_longloop', 'False',\n]\nr = subprocess.run(cmd, text=True)\n\nimport glob\nsketch_pdbs = sorted(glob.glob(f'{SKETCH_DIR}/sketch*.pdb'))\nsketch_info = np.load(f'{SKETCH_DIR}/new_sketch.npy', allow_pickle=True)\nprint(f'\\nāœ“ Built {len(sketch_pdbs)} sketch PDBs')\nfor i, d in enumerate(sketch_info[:min(3, len(sketch_info))]):\n L = d['length']\n total = sum(L) if hasattr(L,'__iter__') else int(L)\n print(f' sketch{i}: total_residues={total} contig={d[\"contig\"][:70]}...')\n" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# Visualise first sketch\nimport py3Dmol\n\ndef show_pdb(path, width=450, height=400):\n view = py3Dmol.view(width=width, height=height)\n view.addModel(open(path).read(), 'pdb')\n view.setStyle({'cartoon': {'colorscheme': 'chainHetatm'}})\n view.zoomTo()\n return view\n\nif sketch_pdbs:\n print(f'Sketch 0: {sketch_pdbs[0]}')\n show_pdb(sketch_pdbs[0]).show()\n" }, { "cell_type": "markdown", "metadata": {}, "source": "## 5. RFdiffusion — backbone design\n\n**Step 1:** Full diffusion — designs loop regions, keeps SSE positions from sketch.\n**Step 2:** Partial diffusion (T=10) — diversifies backbones, generates `PARTIAL_DESN` samples." }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "RF_SCRIPT = f'{RF_DIR}/run_inference.py'\n\ndef run_rfdiffusion(idx):\n d = sketch_info[idx]\n L = d['length']\n total_L = sum(L) if hasattr(L,'__iter__') else int(L)\n contig = d['contig']\n skpdb = f'{SKETCH_DIR}/sketch{idx}.pdb'\n outd = f'{SKETCH_DIR}/new_sketch{idx}'\n os.makedirs(outd, exist_ok=True)\n\n # Step 1 — full diffusion\n print(f' [sketch{idx}] full diffusion (contig length={total_L})...')\n r = subprocess.run([\n sys.executable, RF_SCRIPT,\n f'inference.output_prefix={outd}/sketch_loop',\n f'inference.input_pdb={skpdb}',\n f'contigmap.contigs=[{contig}]',\n f'inference.num_designs={NUM_DESIGNS}',\n ], capture_output=True, text=True, cwd=SKETCH_DIR)\n if r.returncode != 0:\n print(f' āœ— Step1 failed: {r.stderr[-300:]}')\n return False\n\n # Step 2 — partial diffusion\n print(f' [sketch{idx}] partial diffusion (T={PARTIAL_T}, n={PARTIAL_DESN})...')\n r = subprocess.run([\n sys.executable, RF_SCRIPT,\n f'inference.output_prefix={outd}/partialdiff',\n f'inference.input_pdb={outd}/sketch_loop_0.pdb',\n f'contigmap.contigs=[{total_L}-{total_L}]',\n f'inference.num_designs={PARTIAL_DESN}',\n f'diffuser.partial_T={PARTIAL_T}',\n ], capture_output=True, text=True, cwd=outd)\n if r.returncode != 0:\n print(f' āœ— Step2 failed: {r.stderr[-300:]}')\n return False\n\n pdiffs = glob.glob(f'{outd}/partialdiff_*.pdb')\n print(f' [sketch{idx}] āœ“ {len(pdiffs)} backbones ready')\n return True\n\nprint(f'Running RFdiffusion for {len(sketch_pdbs)} sketches...')\nfor i in range(len(sketch_pdbs)):\n run_rfdiffusion(i)\n" }, { "cell_type": "markdown", "metadata": {}, "source": "## 6. ProteinMPNN + AlphaFold2\n\nFor each RFdiffusion backbone:\n1. **ProteinMPNN** designs `MPNN_SEQNUM` sequences at temperature `MPNN_TEMP`\n2. **AlphaFold2** predicts the structure of each sequence (`--no_template`)\n3. RMSD between AF2 prediction and RFdiffusion backbone is computed\n\n> Low RMSD (< 5 ƅ) + high pLDDT (> 0.7) = successful design" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "CD_SCRIPT = f'{WORK}/run_mpnn_af2.py'\n\n# Ensure JAX can find ptxas\nfor _d in ['/usr/local/cuda/bin',\n '/usr/local/lib/python3.10/dist-packages/jaxlib',\n '/usr/local/lib/python3.11/dist-packages/jaxlib']:\n if os.path.isdir(_d):\n os.environ['PATH'] = _d + ':' + os.environ.get('PATH','')\n\ndef run_mpnn_af2(sketch_idx, partial_idx):\n outd = f'{SKETCH_DIR}/new_sketch{sketch_idx}'\n pdb = f'{outd}/partialdiff_{partial_idx}.pdb'\n resdir = f'{outd}/partialdiff_{partial_idx}'\n csv = f'{resdir}/alphafold_results.csv'\n\n if not os.path.exists(pdb):\n return None\n if os.path.exists(csv): # already done\n import pandas as pd\n return pd.read_csv(csv)\n\n r = subprocess.run([\n sys.executable, CD_SCRIPT,\n '--colabdesign_path', CD_DIR,\n '--designpdb', pdb,\n '--no_template',\n '--outdir', resdir,\n '--seqnum', str(MPNN_SEQNUM),\n '--temp', str(MPNN_TEMP),\n '--af2_params', AF2_PARAMS,\n '--num_recycles', str(AF2_RECYCLES),\n ], capture_output=True, text=True)\n\n if r.returncode != 0:\n print(f' āœ— sketch{sketch_idx}/pd{partial_idx}: {r.stderr[-300:]}')\n return None\n\n import pandas as pd\n df = pd.read_csv(csv)\n best= df.nsmallest(1,'rmsd').iloc[0]\n print(f' sketch{sketch_idx}/pd{partial_idx}: '\n f'pLDDT={best.plddt:.3f} ptm={best.ptm:.3f} RMSD={best.rmsd:.2f} ƅ')\n return df\n\nprint(f'Running MPNN+AF2...')\nfor i in range(len(sketch_pdbs)):\n for j in range(PARTIAL_DESN):\n run_mpnn_af2(i, j)\n" }, { "cell_type": "markdown", "metadata": {}, "source": "## 7. Collect & visualise results" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "import pandas as pd, seaborn as sns\n\ncsvs = glob.glob(f'{SKETCH_DIR}/new_sketch*/partialdiff_*/alphafold_results.csv')\ndfs = []\nfor f in csvs:\n try:\n df = pd.read_csv(f)\n p = f.split('/')\n df['sketch'] = p[-3]\n df['partialdiff'] = p[-2]\n dfs.append(df)\n except: pass\n\nif not dfs:\n print('No results yet — check that MPNN+AF2 completed.')\nelse:\n all_df = pd.concat(dfs, ignore_index=True)\n n = len(all_df)\n print(f'Total designs : {n}')\n for thr in [5, 10]:\n c = (all_df.rmsd < thr).sum()\n print(f' RMSD < {thr} ƅ : {c} ({100*c/n:.1f}%)')\n for thr in [0.5, 0.7, 0.8]:\n c = (all_df.plddt >= thr).sum()\n print(f' pLDDT ≄ {thr} : {c} ({100*c/n:.1f}%)')\n\n print('\\nTop 10 by RMSD:')\n print(all_df.nsmallest(10,'rmsd')\n [['sketch','partialdiff','plddt','ptm','rmsd']].to_string(index=False))\n\n fig, axes = plt.subplots(1, 3, figsize=(13, 3.5))\n all_df['rmsd'].clip(0,30).hist(bins=30, ax=axes[0], color='steelblue', edgecolor='white')\n axes[0].axvline(5, color='red', ls='--', label='5 ƅ'); axes[0].legend()\n axes[0].set(xlabel='RMSD (ƅ)', title='RMSD distribution')\n\n all_df['plddt'].hist(bins=30, ax=axes[1], color='darkorange', edgecolor='white')\n axes[1].axvline(0.7, color='red', ls='--', label='0.7'); axes[1].legend()\n axes[1].set(xlabel='pLDDT', title='pLDDT distribution')\n\n axes[2].scatter(all_df['rmsd'].clip(0,30), all_df['plddt'],\n alpha=0.35, s=10, c='mediumpurple')\n axes[2].axvline(5, color='red', ls='--'); axes[2].axhline(0.7, color='orange', ls='--')\n axes[2].set(xlabel='RMSD (ƅ)', ylabel='pLDDT', title='RMSD vs pLDDT')\n\n plt.tight_layout()\n plt.savefig(f'{RUN_DIR}/results_summary.png', dpi=120, bbox_inches='tight')\n plt.show()\n" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# View best design in 3D\nif dfs:\n best = all_df.nsmallest(1, 'rmsd').iloc[0]\n pdbs = glob.glob(f'{SKETCH_DIR}/{best.sketch}/{best.partialdiff}/*.pdb')\n if pdbs:\n print(f'Best design: {best.sketch} / {best.partialdiff}')\n print(f' pLDDT = {best.plddt:.3f} ptm = {best.ptm:.3f} RMSD = {best.rmsd:.2f} ƅ')\n show_pdb(pdbs[0], width=520, height=450).show()\n" }, { "cell_type": "markdown", "metadata": {}, "source": "## 8. Save results to Google Drive" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "import shutil\n\nSAVE = f'{GDRIVE}/results/{MODE}'\nos.makedirs(f'{SAVE}/pdbs_rmsd_lt5', exist_ok=True)\n\nif dfs:\n # Full results CSV\n out_csv = f'{SAVE}/all_results.csv'\n all_df.sort_values('rmsd').drop(columns=['seq'], errors='ignore').to_csv(out_csv, index=False)\n print(f'Saved: {out_csv}')\n\n # RMSD<5 PDBs\n n_cp = 0\n for _, row in all_df[all_df.rmsd < 5].iterrows():\n for pdb in glob.glob(f'{SKETCH_DIR}/{row.sketch}/{row.partialdiff}/*.pdb'):\n dst = f'{SAVE}/pdbs_rmsd_lt5/{row.sketch}_{row.partialdiff}_{os.path.basename(pdb)}'\n shutil.copy2(pdb, dst)\n n_cp += 1\n print(f'Copied {n_cp} RMSD<5 PDB files')\n\n # Figures\n for fig in [f'{RUN_DIR}/topologies.png', f'{RUN_DIR}/results_summary.png']:\n if os.path.exists(fig):\n shutil.copy2(fig, f'{SAVE}/{os.path.basename(fig)}')\n\nprint('\\nāœ“ Done! Results saved to Google Drive.')\n" } ] }