{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e_-WASDNTuIU"
},
"source": [
"**RFdiffusion** - conditional fold generation\n",
"---\n",
"\n",
"**NOTE** This notebook is in development, we are still working on adding all the options from the [manuscript](https://www.biorxiv.org/content/10.1101/2022.12.09.519842v2)\n",
"\n",
"**instructions**:\n",
"1. select mode\n",
"2. enter info, hit the ▶️ button\n",
" - **RFdiffusion** takes ~1min to setup, next time you run this cell it will take seconds!\n",
"\n",
"3. modify the blueprint\n",
" - use diagonal to define the SSEs (`H:helix E:sheet C:coil ?:undefined`)\n",
" - use off-diagonal to define interactions (`0:no_contact 1:contact ?:undefined`)\n",
" - use the textbox in the last column to define the length of each SSE\n",
" - define the buffer length (`buff_length`) between SSEs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"id": "wXhngsOCYexR"
},
"outputs": [],
"source": [
"#@title Generate blueprint for **RFdiffusion**\n",
"\n",
"name = \"test\"\n",
"blueprint_mode = \"manual\" #@param [\"manual\", \"automated\"]\n",
"run_mode = \"unconditional\"\n",
"\n",
"#@markdown ---\n",
"#@markdown **Manual** blueprint (define number of secondary structure `elements` (SSE))\n",
"elements = 5 #@param [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\", \"20\"] {type:\"raw\"}\n",
"#@markdown ---\n",
"#@markdown **Automated** blueprint (from input PDB)\n",
"pdb = \"6MRR\" #@param {type:\"string\"}\n",
"chain = \"A\" #@param {type:\"string\"}\n",
"trim_loops = True #@param {type:\"boolean\"}\n",
"if chain == \"\": chain = None\n",
"\n",
"import os, time, sys\n",
"\n",
"######################################################################\n",
"# SETUP RFDIFFUSION\n",
"######################################################################\n",
"if not os.path.isdir(\"RFdiffusion\"):\n",
" print(\"installing RFdiffusion...\")\n",
" # send param download into background\n",
" os.system(\"apt-get install aria2\")\n",
" os.system(\"(\\\n",
" aria2c -q -x 16 https://files.ipd.uw.edu/krypton/schedules.zip; \\\n",
" aria2c -q -x 16 http://files.ipd.uw.edu/pub/RFdiffusion/60f09a193fb5e5ccdc4980417708dbab/Complex_Fold_base_ckpt.pt; \\\n",
" )&\")\n",
"\n",
" # install RFdiffusion\n",
" os.system(\"git clone https://github.com/sokrypton/RFdiffusion.git\")\n",
" os.system(\"pip install jedi omegaconf hydra-core icecream pyrsistent pynvml decorator\")\n",
" os.system(\"pip install git+https://github.com/NVIDIA/dllogger#egg=dllogger\")\n",
" # 17Mar2024: adding --no-dependencies to avoid installing nvidia-cuda-* dependencies\n",
" # 25Aug2025: updating dgi install to work with latest pytorch\n",
" os.system(\"pip install --no-dependencies dgl -f https://data.dgl.ai/wheels/torch-2.4/cu124/repo.html\")\n",
" os.system(\"pip install --no-dependencies e3nn==0.5.5 opt_einsum_fx\")\n",
" os.system(\"cd RFdiffusion/env/SE3Transformer; pip install .\")\n",
"\n",
" # extras\n",
" os.system(\"pip -q install py3Dmol pydssp\")\n",
" os.system(\"wget -qnc https://raw.githubusercontent.com/sokrypton/ColabDesign/main/colabdesign/rf/blueprint.js\")\n",
" os.system(\"wget -qnc https://raw.githubusercontent.com/sokrypton/ColabDesign/main/colabdesign/rf/blueprint.css\")\n",
"\n",
"if not os.path.isdir(\"RFdiffusion/models\"):\n",
" print(\"downloading RFdiffusion params...\")\n",
" os.system(\"mkdir RFdiffusion/models\")\n",
" models = [\"Complex_Fold_base_ckpt.pt\"]\n",
" for m in models:\n",
" while os.path.isfile(f\"{m}.aria2\"):\n",
" time.sleep(5)\n",
" os.system(f\"mv {' '.join(models)} RFdiffusion/models\")\n",
" os.system(\"unzip schedules.zip; rm schedules.zip\")\n",
" print(\"----------------------------------\")\n",
"\n",
"if 'RFdiffusion' not in sys.path:\n",
" os.environ[\"DGLBACKEND\"] = \"pytorch\"\n",
" sys.path.append('RFdiffusion')\n",
"######################################################################\n",
"\n",
"from IPython.display import display\n",
"import ipywidgets as widgets\n",
"import torch\n",
"import random, string, re\n",
"import numpy as np\n",
"import subprocess\n",
"import matplotlib.pyplot as plt\n",
"import py3Dmol\n",
"from google.colab import files, output\n",
"\n",
"from string import ascii_uppercase, ascii_lowercase\n",
"alphabet_list = list(ascii_uppercase+ascii_lowercase)\n",
"\n",
"def get_pdb(pdb_code=None):\n",
" if pdb_code is None or pdb_code == \"\":\n",
" upload_dict = files.upload()\n",
" pdb_string = upload_dict[list(upload_dict.keys())[0]]\n",
" with open(\"tmp.pdb\",\"wb\") as out: out.write(pdb_string)\n",
" return \"tmp.pdb\"\n",
" elif os.path.isfile(pdb_code):\n",
" return pdb_code\n",
" elif len(pdb_code) == 4:\n",
" os.system(f\"wget -qnc https://files.rcsb.org/view/{pdb_code}.pdb\")\n",
" return f\"{pdb_code}.pdb\"\n",
" else:\n",
" os.system(f\"wget -qnc https://alphafold.ebi.ac.uk/files/AF-{pdb_code}-F1-model_v3.pdb\")\n",
" return f\"AF-{pdb_code}-F1-model_v3.pdb\"\n",
"\n",
"def pdb_to_string(pdb_file, chains=None, models=[1]):\n",
" '''read pdb file and return as string'''\n",
"\n",
" MODRES = {'MSE':'MET','MLY':'LYS','FME':'MET','HYP':'PRO',\n",
" 'TPO':'THR','CSO':'CYS','SEP':'SER','M3L':'LYS',\n",
" 'HSK':'HIS','SAC':'SER','PCA':'GLU','DAL':'ALA',\n",
" 'CME':'CYS','CSD':'CYS','OCS':'CYS','DPR':'PRO',\n",
" 'B3K':'LYS','ALY':'LYS','YCM':'CYS','MLZ':'LYS',\n",
" '4BF':'TYR','KCX':'LYS','B3E':'GLU','B3D':'ASP',\n",
" 'HZP':'PRO','CSX':'CYS','BAL':'ALA','HIC':'HIS',\n",
" 'DBZ':'ALA','DCY':'CYS','DVA':'VAL','NLE':'LEU',\n",
" 'SMC':'CYS','AGM':'ARG','B3A':'ALA','DAS':'ASP',\n",
" 'DLY':'LYS','DSN':'SER','DTH':'THR','GL3':'GLY',\n",
" 'HY3':'PRO','LLP':'LYS','MGN':'GLN','MHS':'HIS',\n",
" 'TRQ':'TRP','B3Y':'TYR','PHI':'PHE','PTR':'TYR',\n",
" 'TYS':'TYR','IAS':'ASP','GPL':'LYS','KYN':'TRP',\n",
" 'CSD':'CYS','SEC':'CYS'}\n",
" restype_1to3 = {'A': 'ALA','R': 'ARG','N': 'ASN',\n",
" 'D': 'ASP','C': 'CYS','Q': 'GLN',\n",
" 'E': 'GLU','G': 'GLY','H': 'HIS',\n",
" 'I': 'ILE','L': 'LEU','K': 'LYS',\n",
" 'M': 'MET','F': 'PHE','P': 'PRO',\n",
" 'S': 'SER','T': 'THR','W': 'TRP',\n",
" 'Y': 'TYR','V': 'VAL'}\n",
"\n",
" restype_3to1 = {v: k for k, v in restype_1to3.items()}\n",
"\n",
" if chains is not None:\n",
" if \",\" in chains: chains = chains.split(\",\")\n",
" if not isinstance(chains,list): chains = [chains]\n",
" if models is not None:\n",
" if not isinstance(models,list): models = [models]\n",
"\n",
" modres = {**MODRES}\n",
" lines = []\n",
" seen = []\n",
" model = 1\n",
" for line in open(pdb_file,\"rb\"):\n",
" line = line.decode(\"utf-8\",\"ignore\").rstrip()\n",
" if line[:5] == \"MODEL\":\n",
" model = int(line[5:])\n",
" if models is None or model in models:\n",
" if line[:6] == \"MODRES\":\n",
" k = line[12:15]\n",
" v = line[24:27]\n",
" if k not in modres and v in restype_3to1:\n",
" modres[k] = v\n",
" if line[:6] == \"HETATM\":\n",
" k = line[17:20]\n",
" if k in modres:\n",
" line = \"ATOM \"+line[6:17]+modres[k]+line[20:]\n",
" if line[:4] == \"ATOM\":\n",
" chain = line[21:22]\n",
" if chains is None or chain in chains:\n",
" atom = line[12:12+4].strip()\n",
" resi = line[17:17+3]\n",
" resn = line[22:22+5].strip()\n",
" if resn[-1].isalpha(): # alternative atom\n",
" resn = resn[:-1]\n",
" line = line[:26]+\" \"+line[27:]\n",
" key = f\"{model}_{chain}_{resn}_{resi}_{atom}\"\n",
" if key not in seen: # skip alternative placements\n",
" lines.append(line)\n",
" seen.append(key)\n",
" if line[:5] == \"MODEL\" or line[:3] == \"TER\" or line[:6] == \"ENDMDL\":\n",
" lines.append(line)\n",
" return \"\\n\".join(lines)\n",
"\n",
"def from_pdb(pdb_code=None, chains=None, trim_loops=False,\n",
" mask_contacts=False, return_pdb_str=False):\n",
"\n",
" import pydssp\n",
" def process(secondary_structure, contact_map):\n",
" secondary_structure = np.array(secondary_structure)\n",
" # Find the start and end indices of the continuous secondary structure elements\n",
" sse_start,sse_end = [],[]\n",
" for i, current_element in enumerate(secondary_structure):\n",
" if current_element in [\"H\", \"E\", \"C\"]:\n",
" if i == 0 or secondary_structure[i-1] != current_element:\n",
" sse_start.append(i)\n",
" if i == len(secondary_structure) - 1 or secondary_structure[i+1] != current_element:\n",
" sse_end.append(i)\n",
"\n",
" sse_types = secondary_structure[sse_start]\n",
" sse_lengths = np.array(sse_end) - np.array(sse_start) + 1\n",
" num_sse = len(sse_lengths)\n",
" reduced_contact_map = np.full((num_sse, num_sse), '0', dtype=object)\n",
" np.fill_diagonal(reduced_contact_map, sse_types)\n",
"\n",
" for i in range(num_sse):\n",
" for j in range(num_sse):\n",
" if i != j and sse_types[i] != \"C\" and sse_types[j] != \"C\":\n",
" interaction_mask = np.any(contact_map[sse_start[i]:sse_end[i]+1, sse_start[j]:sse_end[j]+1])\n",
" reduced_contact_map[i, j] = str(interaction_mask.astype(int))\n",
" if mask_contacts and reduced_contact_map[i, j] == \"1\":\n",
" reduced_contact_map[i, j] = \"?\"\n",
"\n",
"\n",
" return {\"txt\":sse_lengths, \"adj\":reduced_contact_map}\n",
"\n",
" def coord_2_cb(coord):\n",
" N,Ca,C = coord[:,0],coord[:,1],coord[:,2]\n",
" # recreate Cb given N,Ca,C\n",
" b = Ca - N\n",
" c = C - Ca\n",
" a = np.cross(b, c)\n",
" Cb = -0.57910144*a + 0.5689693*b - 0.5441217*c + Ca\n",
" return Cb\n",
" pdb_filename = get_pdb(pdb_code)\n",
" pdb_str = pdb_to_string(pdb_filename, chains=chains)\n",
" coord = pydssp.read_pdbtext(pdb_str)\n",
"\n",
" ss = pydssp.assign(coord)\n",
"\n",
" # filter single length sse\n",
" for i in range(len(ss)):\n",
" if ss[i] in [\"H\",\"E\"]:\n",
" if (i == (len(ss)-1) or ss[i] != ss[i+1]) and (i == 0 or ss[i] != ss[i-1]):\n",
" ss[i] = \"-\"\n",
"\n",
" if not trim_loops:\n",
" ss = [(\"C\" if s == \"-\" else s) for s in ss]\n",
" cb = coord_2_cb(coord)\n",
" con = np.sqrt(np.square(cb[:,None] - cb[None,:]).sum(-1)) < 6.0\n",
" out = process(ss, con)\n",
" if return_pdb_str:\n",
" out[\"pdb_str\"] = pdb_str\n",
" return out\n",
"\n",
"def get_adj_ss(adj, txt, buff=0, mask_contacts=False):\n",
" # select non-zero elements\n",
" idx = []\n",
" for i in range(len(adj)):\n",
" if txt[i] > 0:\n",
" idx.append(i)\n",
"\n",
" L = (len(idx) + 1) * buff + sum(txt)\n",
" full_adj = np.full((L,L),2)\n",
" full_sse = np.full((L,),3)\n",
" n = buff\n",
" for i in idx:\n",
" ss = {\"H\":0, \"E\":1, \"C\":2, \"?\":3}[adj[i][i]]\n",
" full_sse[n:n+txt[i]] = ss\n",
" m = buff\n",
" for j in idx:\n",
" k = str(adj[i][j])\n",
" if i == j:\n",
" val = {\"H\":0,\"E\":0,\"C\":0,\"?\":2}[k]\n",
" else:\n",
" if mask_contacts and k == \"1\": k = \"?\"\n",
" val = {\"0\":0,\"1\":1,\"?\":2}[k]\n",
" full_adj[n:n+txt[i],m:m+txt[j]] = val\n",
" m += txt[j] + buff\n",
" n += txt[i] + buff\n",
" return {\"adj\":full_adj,\"sse\":full_sse}\n",
"\n",
"class blueprint_gui:\n",
"\n",
" def _toggle_callback(self, row, col):\n",
" if row == col:\n",
" new_value = {\"H\":\"E\",\"E\":\"C\",\"C\":\"?\",\"?\":\"H\"}[self.adj[row][col]]\n",
" self.txt[row] = {\"H\": 19, \"E\": 5, \"C\": 3, \"?\": 0}[new_value]\n",
" self.adj[row][col] = new_value\n",
" for i in range(self.elements):\n",
" if i != row:\n",
" if new_value == \"?\":\n",
" self.adj[row][i] = self.adj[i][col] = \"?\"\n",
" elif self.adj[i][i] != \"?\" and new_value in [\"C\",\"H\"]:\n",
" self.adj[row][i] = self.adj[i][col] = '0'\n",
" else:\n",
" if self.adj[row][row] not in [\"C\",\"?\"] and self.adj[col][col] not in [\"C\",\"?\"]:\n",
" new_value = {\"0\":\"1\",\"1\":\"?\",\"?\":\"0\"}[self.adj[row][col]]\n",
" self.adj[row][col] = self.adj[col][row] = new_value\n",
"\n",
" def _text_callback(self, row, new_value):\n",
" self.txt[row] = int(new_value)\n",
"\n",
" def _update_callback(self, position, add):\n",
" if position < 0: position = self.elements\n",
" self.elements = self.elements + 1 if add else self.elements - 1\n",
" if self.elements < 0: self.elements = 0\n",
" adj = [['' for _ in range(self.elements)] for _ in range(self.elements)]\n",
" txt = ['' for _ in range(self.elements)]\n",
" for row in range(self.elements):\n",
" old_row = row if row < position else row - 1 if add else row + 1\n",
" if add and row == position:\n",
" txt[row] = 19\n",
" else:\n",
" txt[row] = self.txt[old_row]\n",
" for col in range(self.elements):\n",
" old_col = col if col < position else col - 1 if add else col + 1\n",
" if add and (row == position or col == position):\n",
" if row == col:\n",
" adj[row][col] = 'H'\n",
" else:\n",
" cell = self.adj[old_row][old_row] if col == position else self.adj[old_col][old_col]\n",
" adj[row][col] = cell if cell == \"?\" else '0'\n",
" else:\n",
" adj[row][col] = self.adj[old_row][old_col]\n",
" self.adj = adj\n",
" self.txt = txt\n",
"\n",
" def _create_html(self):\n",
" # HTML for initial grid\n",
" html_grid = f'