{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "metadata": { "id": "FLoa2lUhX9gu" }, "source": [ "# **Biomolecular Emulator (BioEmu) in ColabFold**\n", "\n", "\n", "[BioEmu](https://github.com/microsoft/bioemu) is a framework for emulating biomolecular dynamics and integrating structural prediction tools to accelerate research in structural biology and protein engineering. This notebook uses BioEmu with ColabFold to generate the MSA and identify cluster conformations using Foldseek.\n", "\n", "\n", "\n", "For more details, please read the [BioEmu Preprint](https://www.biorxiv.org/content/10.1101/2024.12.05.626885v2).\n", "\n", "\n", "## To run\n", "Either run each cell sequentially, or click on `Runtime -> Run All` after choosing the desired sampling config" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "TWM2qzfEYMaL" }, "outputs": [], "source": [ "#@title Sample with following config\n", "#@markdown - `sequence`: Monomer sequence to sample\n", "sequence = \"MADQLTEEQIAEFKEAFSLFDKDGDGTITTKELGTVMRSLGQNPTEAELQDMINEVDADGNGTIDFPEFLTMMARKMKDTDSEEEIREAFRVFDKDGNGYISAAELRHVMTNLGEKLTDEEVDEMIREADIDGDGQVNYEEFVQMMTAK\" #@param {type:\"string\"}\n", "#@markdown - `num_samples`: Number of samples requested\n", "num_samples = 10 #@param {type:\"integer\"}\n", "#@markdown - `jobname`: Name assigned to this job\n", "jobname = \"calmodulin\" #@param {type:\"string\"}\n", "#@markdown - `filter_samples`: Whether to filter unphysical samples (e.g., those containing chain breaks) from the written samples\n", "filter_samples = True #@param {type:\"boolean\"}\n", "# #@param {type:\"boolean\"}\n", "#@markdown - `model_name`: v1.1 = Journal accepted version | v1.0 preprint version\n", "model_name = \"bioemu-v1.1\" #@param [\"bioemu-v1.0\", \"bioemu-v1.1\"]\n", "# ------------------------\n", "# Copied logic from ColabFold\n", "# ------------------------\n", "import os\n", "import re\n", "import hashlib\n", "\n", "def add_hash(x, seq):\n", " \"\"\"Append a short SHA-1 hash of seq to x.\"\"\"\n", " return x + \"_\" + hashlib.sha1(seq.encode()).hexdigest()[:5]\n", "\n", "def folder_is_free(folder):\n", " \"\"\"Return True if folder doesn't exist.\"\"\"\n", " return not os.path.exists(folder)\n", "\n", "jobname_clean = re.sub(r'\\W+', '', jobname)\n", "sequence = \"\".join(sequence.split())\n", "jobname = add_hash(jobname_clean, sequence)\n", "\n", "if not folder_is_free(jobname):\n", " n = 0\n", " while not folder_is_free(f\"{jobname}_{n}\"):\n", " n += 1\n", " jobname = f\"{jobname}_{n}\"\n", "\n", "output_dir = os.path.join(\"/content\", jobname)\n", "os.makedirs(output_dir, exist_ok=True)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "7bAv6hU6Nedi", "cellView": "form" }, "outputs": [], "source": [ "#@title Install dependencies\n", "import os\n", "import sys\n", "\n", "_is_bioemu_setup_file = '/content/.BIOEMU_SETUP'\n", "\n", "conda_prefix = '/usr/local/'\n", "miniconda_link = 'https://repo.anaconda.com/miniconda/Miniconda3-py312_25.5.1-1-Linux-x86_64.sh'\n", "miniconda_basename = os.path.basename(miniconda_link)\n", "os.makedirs(conda_prefix, exist_ok=True)\n", "\n", "if not os.path.exists(_is_bioemu_setup_file):\n", " os.system(f'wget {miniconda_link}')\n", " os.system(f'chmod +x {miniconda_basename}')\n", " os.system(f'./{miniconda_basename} -b -f -p {conda_prefix}')\n", " os.system(f'conda install -q -y --prefix {conda_prefix} python=3.12')\n", " os.system('uv pip install --prerelease if-necessary-or-explicit bioemu')\n", "\n", " os.system('conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main')\n", " os.system('conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r')\n", " os.system('conda install -c conda-forge openmm cuda-version=11 --yes')\n", "\n", " sys.path.append(os.path.join(conda_prefix, 'lib/python3.12/site-packages/'))\n", "\n", " os.environ['CONDA_PREFIX'] = conda_prefix\n", " os.environ['CONDA_PREFIX_1'] = os.path.join(conda_prefix, 'envs/myenv')\n", " os.environ['CONDA_DEFAULT_ENV'] = 'base'\n", " os.system(f\"touch {_is_bioemu_setup_file}\")\n", " os.system('wget https://mmseqs.com/foldseek/foldseek-linux-avx2.tar.gz; tar xvzf foldseek-linux-avx2.tar.gz')\n", " os.system('/usr/bin/python3 -m pip install uv')\n", " os.unlink(miniconda_basename)\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_TYvJwSLMpd7", "cellView": "form" }, "outputs": [], "source": [ "#@title Run BioEmu\n", "\n", "from bioemu.sample import main as sample\n", "output_dir = f'/content/{jobname}'\n", "sample(sequence=sequence, num_samples=num_samples, model_name=model_name, output_dir=output_dir, filter_samples=filter_samples)" ] }, { "cell_type": "markdown", "metadata": { "id": "-1n_y3ycRpl4" }, "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "collapsed": true, "id": "GbNRxHwgWzfF" }, "outputs": [], "source": [ "#@title Write samples and run `foldseek`\n", "#@markdown - `n_write_samples`: Number of samples to randomly select for clustering. Set to `-1` to select all available samples\n", "#@markdown - `tmscore_threshold`: TM-score threshold used for foldseek clustering\n", "#@markdown - `coverage_threshold`: Coverage threshold used for foldseek clustering\n", "#@markdown - `seq_id`: Sequence identity threshold used for foldseek clustering\n", "\n", "n_write_samples = -1 #@param {type:\"integer\"}\n", "tmscore_threshold = 0.6 #@param {type: \"number\"}\n", "coverage_threshold = 0.7 #@param {type: \"number\"}\n", "seq_id = 0.95 #@param {type: \"number\"}\n", "\n", "import numpy as np\n", "import mdtraj\n", "\n", "_py3dmol_installed_file = '/content/.py3dmol'\n", "if not os.path.exists(_py3dmol_installed_file):\n", " os.system('uv pip install py3Dmol')\n", " os.system(f\"touch {_py3dmol_installed_file}\")\n", "\n", "import py3Dmol\n", "pdb_sample_dir = os.path.join('/content', 'pdb_samples')\n", "os.makedirs(pdb_sample_dir, exist_ok=True)\n", "\n", "def write_some_samples(topology_file: str, trajectory_file: str, output_dir:str, n_samples: int) -> None:\n", " traj = mdtraj.load(trajectory_file, top=topology_file)\n", " assert traj.n_frames >= n_samples\n", " if n_samples == -1:\n", " sample_indices = np.arange(traj.n_frames)\n", " else:\n", " sample_indices = np.random.choice(np.arange(traj.n_frames), size=n_samples, replace=False)\n", " for idx in sample_indices:\n", " traj[idx].save_pdb(os.path.join(output_dir, f'sample_{idx}.pdb'))\n", "\n", "\n", "topology_file = os.path.join(output_dir, \"topology.pdb\")\n", "trajectory_file = os.path.join(output_dir, \"samples.xtc\")\n", "\n", "write_some_samples(topology_file=topology_file,\n", " trajectory_file=trajectory_file,\n", " output_dir=pdb_sample_dir,\n", " n_samples=n_write_samples)\n", "\n", "# Foldseek\n", "import os\n", "import subprocess\n", "import tempfile\n", "\n", "import pandas as pd\n", "\n", "def parse_foldseek_cluster_results(cluster_table_path: str) -> dict[int, list[str]]:\n", " \"\"\"\n", " Parses the result of foldseek clustering\n", "\n", " Args:\n", " cluster_table: path of the output cluster table from foldseek\n", "\n", " Returns:\n", " Dictionary mapping cluster indices to members\n", "\n", " \"\"\"\n", "\n", " cluster_table = pd.read_csv(cluster_table_path, sep=r\"\\s+\", header=None)\n", "\n", " cluster_idx_to_members = {}\n", "\n", " for index, group in enumerate(cluster_table.groupby(0)):\n", " cluster_idx_to_members[index] = sorted(list(group[1][1]))\n", "\n", " return cluster_idx_to_members\n", "\n", "\n", "def foldseek_cluster(\n", " input_dir: str,\n", " out_prefix: str | None = None,\n", " tmscore_threshold: float = 0.7,\n", " coverage_threshold: float = 0.9,\n", " seq_id: float = 0.7,\n", " coverage_mode: int = 1,\n", ") -> dict[int, set[str]]:\n", " \"\"\"\n", " Runs foldseek easy cluster\n", "\n", " Args:\n", " input_dir (str): input directory with .cif or .pdb files\n", " out_prefix (str | None): the prefix of the output files, if None a temporary directory will be used\n", " tmscore_threshold (float): the tm-score threshold used for clustering\n", " coverage_threshold (float): the coverage threshold used for clustering\n", " seq_id (float): the sequence identity threshold used for clustering\n", " coverage_mode (int): mode used by mmseqs/foldseek to compute coverage\n", "\n", " Returns:\n", " Dictionary mapping cluster indices to members\n", " \"\"\"\n", "\n", " with tempfile.TemporaryDirectory() as temp_dir:\n", "\n", " with tempfile.TemporaryDirectory() as temp_out_dir:\n", " if out_prefix is None:\n", " out_prefix = os.path.join(temp_out_dir, \"output\")\n", "\n", " res = subprocess.run(\n", " \"/content/foldseek/bin/foldseek easy-cluster \"\n", " + input_dir\n", " + \" \"\n", " + out_prefix\n", " + \" \"\n", " + temp_dir\n", " + \" -c \"\n", " + str(coverage_threshold)\n", " + \" --min-seq-id \"\n", " + str(seq_id)\n", " + \" --tmscore-threshold \"\n", " + str(tmscore_threshold)\n", " + \" --cov-mode \"\n", " + str(coverage_mode)\n", " + \" --single-step-clustering\",\n", " shell=True,\n", " )\n", " assert res.returncode == 0, \"Something went wrong with foldseek\"\n", "\n", " cluster_idx_to_members = parse_foldseek_cluster_results(out_prefix + \"_cluster.tsv\")\n", "\n", " return cluster_idx_to_members\n", "\n", "!chmod +x '/content/foldseek/bin/foldseek'\n", "\n", "# Get foldseek clusters\n", "clusters = foldseek_cluster(input_dir=pdb_sample_dir, tmscore_threshold=tmscore_threshold,\n", " coverage_threshold=coverage_threshold, seq_id=seq_id)\n", "n_clusters = len(clusters)\n", "print(f'{n_clusters} clusters detected')\n", "\n", "# Write foldseek clusters to output dir\n", "import json\n", "\n", "with open(os.path.join(output_dir, 'foldseek_clusters.json'), 'w') as json_handle:\n", " json.dump(clusters, json_handle)\n", "\n", "\n", "# Write XTC with one sample per cluster only\n", "cluster_trajs = []\n", "for _cluster_idx, samples in clusters.items():\n", " sample = list(samples)[0] # Choose first sample in cluster\n", " pdb_file = os.path.join(pdb_sample_dir, f\"{sample}.pdb\")\n", " traj = mdtraj.load_pdb(pdb_file)\n", " cluster_trajs.append(traj)\n", "joint_traj = mdtraj.join(cluster_trajs)\n", "cluster_topology_file = os.path.join(output_dir, \"clustered_topology.pdb\")\n", "cluster_trajectory_file = os.path.join(output_dir, \"clustered_samples.xtc\")\n", "joint_traj[0].save_pdb(cluster_topology_file)\n", "joint_traj.save_xtc(cluster_trajectory_file)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "fLWzZQYAcVzr" }, "outputs": [], "source": [ "#@title Display structure\n", "import os\n", "import ipywidgets as widgets\n", "import py3Dmol\n", "from IPython.display import display, clear_output\n", "\n", "# Create interactive widgets for cluster and sample selection.\n", "cluster_slider = widgets.IntSlider(\n", " value=0,\n", " min=0,\n", " max=n_clusters - 1,\n", " step=1,\n", " description='Cluster No:',\n", " continuous_update=False\n", ")\n", "sample_slider = widgets.IntSlider(\n", " value=0,\n", " min=0,\n", " max=0, # will update based on the selected cluster\n", " step=1,\n", " description='Sample Idx:',\n", " continuous_update=False\n", ")\n", "display(cluster_slider, sample_slider)\n", "\n", "# Function to visualize a PDB file using py3Dmol.\n", "def show_pdb(pdb_file: str, show_sidechains: bool = False, show_mainchains: bool = True):\n", " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js')\n", " try:\n", " with open(pdb_file, 'r') as f:\n", " pdb_content = f.read()\n", " except FileNotFoundError:\n", " print(f\"File not found: {pdb_file}\")\n", " return None\n", " view.addModel(pdb_content, 'pdb')\n", " view.setStyle({'cartoon': {'color': 'spectrum'}})\n", "\n", " if show_sidechains:\n", " BB = ['C', 'O', 'N']\n", " view.addStyle({'and': [{'resn': [\"GLY\", \"PRO\"], 'invert': True}, {'atom': BB, 'invert': True}]},\n", " {'stick': {'colorscheme': \"WhiteCarbon\", 'radius': 0.3}})\n", " view.addStyle({'and': [{'resn': \"GLY\"}, {'atom': 'CA'}]},\n", " {'sphere': {'colorscheme': \"WhiteCarbon\", 'radius': 0.3}})\n", " view.addStyle({'and': [{'resn': \"PRO\"}, {'atom': ['C', 'O'], 'invert': True}]},\n", " {'stick': {'colorscheme': \"WhiteCarbon\", 'radius': 0.3}})\n", " if show_mainchains:\n", " BB = ['C', 'O', 'N', 'CA']\n", " view.addStyle({'atom': BB}, {'stick': {'colorscheme': \"WhiteCarbon\", 'radius': 0.3}})\n", "\n", " view.zoomTo()\n", " return view\n", "\n", "# Helper to update the sample slider's maximum value based on the selected cluster.\n", "def update_sample_slider(cluster_no):\n", " available_samples = list(clusters[cluster_no])\n", " sample_slider.max = max(len(available_samples) - 1, 0)\n", " # Reset sample_slider's value if it's out of range.\n", " if sample_slider.value > sample_slider.max:\n", " sample_slider.value = 0\n", "\n", "# Main function to update the viewer whenever widget values change.\n", "def update_view(change=None):\n", " cluster_no = cluster_slider.value\n", " update_sample_slider(cluster_no)\n", " available_samples = list(clusters[cluster_no])\n", " sample_idx = sample_slider.value\n", "\n", " clear_output(wait=True)\n", " display(cluster_slider, sample_slider)\n", "\n", " if sample_idx >= len(available_samples):\n", " print(f\"Only {len(available_samples)} samples available in cluster {cluster_no}\")\n", " return\n", "\n", " chosen_sample = available_samples[sample_idx]\n", " pdb_path = os.path.join(\"pdb_samples\", f\"{chosen_sample}.pdb\")\n", "\n", " # Check if the file exists before attempting to open it.\n", " if not os.path.exists(pdb_path):\n", " print(f\"File not found: {pdb_path}\")\n", " return\n", "\n", " print(f\"Displaying sample {sample_idx} from cluster {cluster_no}\")\n", " view = show_pdb(pdb_path)\n", " if view:\n", " view.show()\n", "\n", "# Observe changes to the slider values.\n", "cluster_slider.observe(update_view, names='value')\n", "sample_slider.observe(update_view, names='value')\n", "\n", "# Trigger an initial update.\n", "update_view()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "O5EhJTP3tzcJ", "cellView": "form" }, "outputs": [], "source": [ "#@title (Optional) Reconstruct sidechains + Run MD relaxation\n", "#@markdown - `reconstruct_sidechains`: whether to reconstruct sidechains via `hpacker`\n", "#@markdown - `run_md`: check to run MD after sidechain reconstruction, otherwise only sidechain reconstruction is performed\n", "#@markdown - `md_protocol`: `LOCAL_MINIMIZATION`: fast but only resolves local problems ; `NVT_EQUIL`: slow but might resolve more severe issues\n", "#@markdown - `one_per_cluster`: Reconstruct sidechains / optionally run MD for only one sample within each foldseek cluster\n", "\n", "#@markdown **WARNING**: this step can be quite expensive depending on how many samples you have requested / sequence length. You may want to check the `one_per_cluster` option.\n", "\n", "\n", "reconstruct_sidechains = True #@param {type: \"boolean\"}\n", "run_md = True #@param {type:\"boolean\"}\n", "one_per_cluster = True #@param {type:\"boolean\"}\n", "md_protocol = \"LOCAL_MINIMIZATION\" #@param [\"LOCAL_MINIMIZATION\", \"NVT_EQUIL\"] {type:\"string\"}\n", "import bioemu.sidechain_relax\n", "bioemu.sidechain_relax.HPACKER_PYTHONBIN = os.path.join(conda_prefix, '/envs/hpacker/bin/python')\n", "\n", "from bioemu.sidechain_relax import main as sidechainrelax\n", "from bioemu.sidechain_relax import MDProtocol\n", "md_protocol = MDProtocol[md_protocol]\n", "os.environ['CONDA_PREFIX_1'] = conda_prefix\n", "\n", "if one_per_cluster:\n", " topology_file = cluster_topology_file\n", " trajectory_file = cluster_trajectory_file\n", "\n", "prefix = 'hpacker-openmm'\n", "if reconstruct_sidechains:\n", " relaxed_dir = os.path.join(output_dir, prefix)\n", " os.makedirs(relaxed_dir, exist_ok=True)\n", " sidechainrelax(pdb_path=topology_file, xtc_path=trajectory_file,\n", " outpath=relaxed_dir, prefix=prefix, md_protocol=md_protocol,\n", " md_equil=run_md)\n", " if run_md:\n", " os.system(f'touch {relaxed_dir}/.RELAXED')\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0 }