File size: 34,297 Bytes
d766458 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/sokrypton/ColabDesign/blob/main/rf/examples/diffusion_foldcond.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e_-WASDNTuIU"
},
"source": [
"**RFdiffusion** - conditional fold generation\n",
"---\n",
"\n",
"**<font color=\"red\">NOTE</font>** 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'<div class=\"pos\"></div>'\n",
" for row in range(self.elements): html_grid += f'<div class=\"pos\">{row}</div>'\n",
" html_grid += f'<div class=\"pos\"></div>'\n",
" for row in range(self.elements):\n",
" html_grid += f'<div class=\"pos\">{row}</div>'\n",
" for col in range(self.elements):\n",
" value = self.adj[row][col]\n",
" bgcolor = {\"H\":\"red\",\"E\":\"yellow\",\"C\":\"lime\",\"?\":\"lightgray\",\"0\":\"white\",\"1\":\"lightblue\"}[value]\n",
" if row != col and (self.adj[row][row] in [\"?\",\"C\"] or self.adj[col][col] in [\"?\",\"C\"]):\n",
" opacity = 0.1\n",
" else:\n",
" opacity = 1.0\n",
" html_grid += f'<div class=\"grid-item\" id=\"cell_{row}_{col}\" style=\"background-color:{bgcolor};opacity:{opacity}\">{value}</div>'\n",
" html_grid += f'<div><input class=\"text\" type=\"number\" id=\"cell_{row}\" min=\"0\" value=\"{self.txt[row]}\" onchange=\"textFieldChanged({row}, this)\"></div>'\n",
"\n",
" self.html_code = f\"\"\"\n",
" <style>\n",
" {self._CSS}\n",
" .grid-container {{\n",
" display: grid;\n",
" grid-template-columns: repeat({self.elements+2}, 30px);\n",
" gap: 2px;\n",
" }}\n",
" </style>\n",
" <script>{self._JS}</script>\n",
" <label>resize:</label>\n",
" <button id=\"add\" style=\"width:25px\" class=\"button\" onclick=\"updateGrid(true)\">+</button>\n",
" <button id=\"remove\" style=\"width:25px\" class=\"button\" onclick=\"updateGrid(false)\">-</button>\n",
" <input type=\"number\" id=\"position\" min=\"-1\" max=\"{self.elements}\" value=\"0\" class=\"text\">\n",
" <label>(indicate where to +/- an element)</label>\n",
" <div class=\"grid-container\">{html_grid}</div>\n",
" \"\"\"\n",
"\n",
"class RFdiff_gui(blueprint_gui):\n",
"\n",
" def __init__(self, elements=5, adj=None, txt=None, buff_length=5, name=\"test\"):\n",
" self.path = self.name = name\n",
" self.input = widgets.Output()\n",
" self.output = widgets.Output()\n",
" self.buff_length = buff_length\n",
"\n",
" small_button_style = widgets.Layout(width='30px', height='30px', border='2px solid black')\n",
" button_style = widgets.Layout(width='84px', height='35px', border='2px solid black')\n",
" self.buttons = {\n",
" \"buff_length\": widgets.BoundedIntText(description='buff_length', value=self.buff_length, min=0, max=20),\n",
" \"reset\": widgets.Button(description='reset', layout=button_style),\n",
" \"animate\": widgets.Button(description='animate', layout=button_style),\n",
" \"freeze\": widgets.Button(description='freeze', layout=button_style),\n",
" \"download\": widgets.Button(description='download', layout=button_style),\n",
" \"color\": widgets.Dropdown(\n",
" options=['SSE','pLDDT'],\n",
" value='SSE',\n",
" description='color',\n",
" disabled=False)\n",
" }\n",
" self.buttons[\"animate\"].on_click(self._plot_pdb)\n",
" self.buttons[\"freeze\"].on_click(self._plot_pdb)\n",
" self.buttons[\"download\"].on_click(self._download)\n",
" self.buttons[\"color\"].observe(self._plot_pdb)\n",
" self._plot = {\"mode\":\"freeze\",\"color\":\"SSE\"}\n",
"\n",
" # prep inputs\n",
" if adj is not None and txt is not None:\n",
" self.elements = len(adj)\n",
" self.adj, self.txt = adj,txt\n",
" else:\n",
" self.elements = elements\n",
" self.adj = [[\"H\" if row == col else \"0\" for col in range(self.elements)] for row in range(self.elements)]\n",
" self.txt = [19 for _ in range(self.elements)]\n",
"\n",
" output.register_callback(\"update_callback\", self._update_callback)\n",
" output.register_callback(\"toggle_callback\", self._toggle_callback)\n",
" output.register_callback(\"text_callback\", self._text_callback)\n",
" self._CSS = open(\"blueprint.css\",\"r\").read()\n",
" self._JS = open(\"blueprint.js\",\"r\").read()\n",
"\n",
" def _redraw(self):\n",
" with self.input:\n",
" self._create_html()\n",
" self.input.clear_output(wait=True)\n",
" display(\n",
" widgets.VBox([\n",
" widgets.HTML(self.html_code),\n",
" widgets.Label(\"Options\"),\n",
" self.buttons[\"buff_length\"],\n",
" ])\n",
" )\n",
"\n",
" def display_input(self):\n",
" self._redraw()\n",
" display(self.input)\n",
"\n",
" def display_output(self):\n",
" display(self.output)\n",
"\n",
" def _download(self, button):\n",
" os.system(f\"zip -r {self.path}.result.zip outputs/{self.path}* outputs/traj/{self.path}*\")\n",
" files.download(f\"{self.path}.result.zip\")\n",
"\n",
" def _plot_pdb(self, change):\n",
" update = False\n",
" if isinstance(change, widgets.Button):\n",
" self._plot[\"mode\"] = change.description\n",
" update = True\n",
" elif isinstance(change, dict) and change['name'] == 'value':\n",
" widget = change['owner']\n",
" if isinstance(widget, widgets.Dropdown):\n",
" self._plot[\"color\"] = change[\"new\"]\n",
" update = True\n",
" if update:\n",
" view = py3Dmol.view()\n",
" if self._plot[\"mode\"] == \"animate\":\n",
" pdb = f\"outputs/traj/{self.path}_0_pX0_traj.pdb\"\n",
" pdb_str = open(pdb,'r').read()\n",
" view.addModelsAsFrames(pdb_str,'pdb')\n",
" else:\n",
" pdb = f\"outputs/{self.path}_0.pdb\"\n",
" pdb_str = open(pdb,'r').read()\n",
" view.addModel(pdb_str,'pdb')\n",
" if self._plot[\"color\"] == \"SSE\":\n",
" view.setStyle({\"ss\":\"h\",\"chain\":\"A\"},{'cartoon': {'color':'red'}})\n",
" view.setStyle({\"ss\":\"c\",\"chain\":\"A\"},{'cartoon': {'color':'lime'}})\n",
" view.setStyle({\"ss\":\"s\",\"chain\":\"A\"},{'cartoon': {'color':'yellow'}})\n",
" if self.use_target:\n",
" view.setStyle({\"chain\":\"B\"},{'cartoon': {'color':'white'}})\n",
" else:\n",
" view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':0.5,'max':0.9}}})\n",
" view.zoomTo()\n",
" if self._plot[\"mode\"] == \"animate\":\n",
" view.animate({'loop': 'backAndForth'})\n",
" out = widgets.Output()\n",
" with out: view.show()\n",
" toggle = self.buttons[\"freeze\"] if self._plot[\"mode\"] == \"animate\" else self.buttons[\"animate\"]\n",
" with self.output:\n",
" self.output.clear_output(wait=True)\n",
" display(widgets.VBox([out, widgets.HBox([toggle, self.buttons[\"download\"], self.buttons[\"color\"]])]))\n",
"\n",
" def _make_path(self):\n",
" os.makedirs(f\"outputs/{self.path}\", exist_ok=True)\n",
" while os.path.exists(f\"outputs/{self.path}_0.pdb\"):\n",
" self.path = self.name + \"_\" + ''.join(random.choices(string.ascii_lowercase + string.digits, k=5))\n",
" os.makedirs(f\"outputs/{self.path}\", exist_ok=True)\n",
"\n",
" def _get_adj_ss(self, mask_contacts=False):\n",
" # get unique path\n",
" full = get_adj_ss(adj=self.adj,\n",
" txt=self.txt,\n",
" buff=self.buttons[\"buff_length\"].value,\n",
" mask_contacts=mask_contacts)\n",
" self._sse = full[\"sse\"]\n",
" self._adj = full[\"adj\"]\n",
"\n",
" # save results\n",
" loc = [f\"outputs/{self.path}/tmp_ss.pt\",\n",
" f\"outputs/{self.path}/tmp_adj.pt\"]\n",
" torch.save(torch.from_numpy(self._sse).float(),loc[0])\n",
" torch.save(torch.from_numpy(self._adj).float(),loc[1])\n",
"\n",
" def diffuse(self, iterations=50,\n",
" mask_loops=True,\n",
" mask_contacts=False,\n",
" extra_cmd=None):\n",
" self.use_target = use_target\n",
" self._redraw()\n",
" self._make_path()\n",
" self._get_adj_ss(mask_contacts=mask_contacts)\n",
" # run\n",
" with self.output:\n",
" self.output.clear_output()\n",
" cmd = [\"./RFdiffusion/run_inference.py\",\n",
" \"inference.num_designs=1\",\n",
" f\"inference.output_prefix=outputs/{self.path}\",\n",
" \"scaffoldguided.scaffoldguided=True\",\n",
" f\"scaffoldguided.scaffold_dir=outputs/{self.path}\",\n",
" f\"diffuser.T={iterations}\",\n",
" f\"scaffoldguided.mask_loops={mask_loops}\",\n",
" \"inference.dump_pdb=True\",\n",
" \"inference.dump_pdb_path=/dev/shm\"]\n",
"\n",
" if extra_cmd is not None:\n",
" cmd += extra_cmd\n",
"\n",
" self.cmd_str = \" \".join(cmd)\n",
" self._run(self.cmd_str, iterations)\n",
" self._plot_pdb(self.buttons[\"freeze\"])\n",
"\n",
" def _run(self, command, steps, num_designs=1):\n",
" def run_command_and_get_pid(command):\n",
" pid_file = '/dev/shm/pid'\n",
" os.system(f'nohup {command} & echo $! > {pid_file}')\n",
" with open(pid_file, 'r') as f:\n",
" pid = int(f.read().strip())\n",
" os.remove(pid_file)\n",
" return pid\n",
" def is_process_running(pid):\n",
" try:\n",
" os.kill(pid, 0)\n",
" except OSError:\n",
" return False\n",
" else:\n",
" return True\n",
"\n",
" run_output = widgets.Output()\n",
" progress = widgets.FloatProgress(min=0, max=1, description='running', bar_style='info')\n",
" display(widgets.VBox([progress, run_output]))\n",
"\n",
" # clear previous run\n",
" for n in range(steps):\n",
" if os.path.isfile(f\"/dev/shm/{n}.pdb\"):\n",
" os.remove(f\"/dev/shm/{n}.pdb\")\n",
"\n",
" pid = run_command_and_get_pid(command)\n",
" try:\n",
" fail = False\n",
" for _ in range(num_designs):\n",
" # for each step\n",
" for n in range(steps):\n",
" wait = True\n",
" while wait and not fail:\n",
" time.sleep(0.5)\n",
" # check if output generated\n",
" if os.path.isfile(f\"/dev/shm/{n}.pdb\"):\n",
" pdb_str = open(f\"/dev/shm/{n}.pdb\").read()\n",
" if pdb_str[-3:] == \"TER\":\n",
" wait = False\n",
" elif not is_process_running(pid):\n",
" fail = True\n",
" elif not is_process_running(pid):\n",
" fail = True\n",
"\n",
" if fail:\n",
" progress.bar_style = 'danger'\n",
" progress.description = \"failed\"\n",
" break\n",
" else:\n",
" progress.value = (n+1) / steps\n",
" with run_output:\n",
" run_output.clear_output(wait=True)\n",
" view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js')\n",
" view.addModel(pdb_str,'pdb')\n",
" view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':0.5,'max':0.9}}})\n",
" view.zoomTo()\n",
" view.show()\n",
" if os.path.exists(f\"/dev/shm/{n}.pdb\"):\n",
" os.remove(f\"/dev/shm/{n}.pdb\")\n",
"\n",
" if fail:\n",
" progress.bar_style = 'danger'\n",
" progress.description = \"failed\"\n",
" break\n",
"\n",
" while is_process_running(pid):\n",
" time.sleep(0.5)\n",
"\n",
" except KeyboardInterrupt:\n",
" os.kill(pid, signal.SIGTERM)\n",
" progress.bar_style = 'danger'\n",
" progress.description = \"stopped\"\n",
"\n",
"if blueprint_mode == \"automated\":\n",
" pdb_feats = from_pdb(pdb, chains=chain, trim_loops=trim_loops)\n",
" rfdiff = RFdiff_gui(**pdb_feats, name=name, buff_length=(5 if trim_loops else 0))\n",
"else:\n",
" rfdiff = RFdiff_gui(elements, name=name)\n",
"rfdiff.display_input()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"id": "C3OSGy_YRb9d"
},
"outputs": [],
"source": [
"%%time\n",
"#@title run **RFdiffusion**\n",
"iterations = 25 #@param [\"25\", \"50\", \"100\", \"200\"] {type:\"raw\"}\n",
"mask_loops = True #@param {type:\"boolean\"}\n",
"mask_contacts = False #@param {type:\"boolean\"}\n",
"#@markdown **Optional**: specify target info (for binder design)\n",
"use_target = False #@param {type:\"boolean\"}\n",
"target_pdb = \"\" #@param {type:\"string\"}\n",
"target_chain = \"A\" #@param {type:\"string\"}\n",
"target_hotspot = \"\" #@param {type:\"string\"}\n",
"\n",
"if use_target:\n",
" # prep target features\n",
" rfdiff._make_path()\n",
" path = f\"outputs/{rfdiff.path}/target\"\n",
" os.makedirs(path, exist_ok=True)\n",
" target = from_pdb(target_pdb, target_chain, return_pdb_str=True)\n",
" target_pdb = f\"{path}/input.pdb\"\n",
" with open(target_pdb,\"w\") as handle:\n",
" handle.write(target[\"pdb_str\"])\n",
" full = get_adj_ss(adj=target[\"adj\"], txt=target[\"txt\"])\n",
" torch.save(torch.from_numpy(full[\"sse\"]).float(),f\"{path}/ss.pt\")\n",
" torch.save(torch.from_numpy(full[\"adj\"]).float(),f\"{path}/adj.pt\")\n",
"\n",
" extra_cmd = [\"scaffoldguided.target_pdb=True\",\n",
" f\"scaffoldguided.target_path={path}/input.pdb\",\n",
" f\"scaffoldguided.target_ss={path}/ss.pt\",\n",
" f\"scaffoldguided.target_adj={path}/adj.pt\",\n",
" \"denoiser.noise_scale_ca=0\",\n",
" \"denoiser.noise_scale_frame=0\"]\n",
" if target_hotspot != \"\":\n",
" extra_cmd += [f\"'ppi.hotspot_res=[{target_hotspot}]'\"]\n",
"else:\n",
" extra_cmd = None\n",
"\n",
"if \"rfdiff\" in dir():\n",
" rfdiff.display_output()\n",
" rfdiff.diffuse(iterations,\n",
" mask_loops=mask_loops,\n",
" mask_contacts=mask_contacts,\n",
" extra_cmd=extra_cmd)\n",
"else:\n",
" print(\"Error, looks like you didn't run the cell above\")"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"provenance": [],
"include_colab_link": true
},
"gpuClass": "standard",
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
} |