introvoyz041 commited on
Commit
007eda2
·
verified ·
1 Parent(s): 134adcb

Migrated from GitHub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/AlphaFold2.ipynb +643 -0
  2. data/AlphaFold3_of3.ipynb +664 -0
  3. data/BioEmu.ipynb +478 -0
  4. data/Boltz1.ipynb +337 -0
  5. data/Contributing.md +98 -0
  6. data/Dockerfile +56 -0
  7. data/ESMFold.ipynb +345 -0
  8. data/LICENSE +21 -0
  9. data/MsaServer/README.md +65 -0
  10. data/MsaServer/config.json +112 -0
  11. data/MsaServer/restart-systemd.sh +5 -0
  12. data/MsaServer/setup-and-start-local.sh +111 -0
  13. data/MsaServer/systemd-example-mmseqs-server.service +16 -0
  14. data/README.md +262 -0
  15. data/RoseTTAFold.ipynb +301 -0
  16. data/RoseTTAFold2.ipynb +489 -0
  17. data/batch/AlphaFold2_batch.ipynb +277 -0
  18. data/beta/AlphaFold2_advanced.ipynb +745 -0
  19. data/beta/AlphaFold2_advanced_beta.ipynb +43 -0
  20. data/beta/AlphaFold2_advanced_old.ipynb +1127 -0
  21. data/beta/AlphaFold2_complexes.ipynb +647 -0
  22. data/beta/AlphaFold_wJackhmmer.ipynb +793 -0
  23. data/beta/Alphafold_single.ipynb +270 -0
  24. data/beta/ESMFold.ipynb +474 -0
  25. data/beta/ESMFold_advanced.ipynb +584 -0
  26. data/beta/ESMFold_api.ipynb +156 -0
  27. data/beta/RoseTTAFold.ipynb +388 -0
  28. data/beta/RoseTTAFold__network__Refine_module.patch +106 -0
  29. data/beta/RoseTTAFold_install.sh +5 -0
  30. data/beta/RoseTTAFold_run.sh +26 -0
  31. data/beta/alphafold_output_at_each_recycle.ipynb +0 -0
  32. data/beta/colabfold.py +711 -0
  33. data/beta/colabfold_alphafold.py +821 -0
  34. data/beta/config.patch +10 -0
  35. data/beta/convert_256_to_384_rep.ipynb +102 -0
  36. data/beta/folding.patch +34 -0
  37. data/beta/mapping.patch +63 -0
  38. data/beta/model.patch +70 -0
  39. data/beta/modules.patch +80 -0
  40. data/beta/omegafold.ipynb +239 -0
  41. data/beta/omegafold_hacks.ipynb +287 -0
  42. data/beta/pairmsa.py +237 -0
  43. data/beta/protein.patch +126 -0
  44. data/beta/recycle_0.patch +37 -0
  45. data/beta/relax_amber.ipynb +207 -0
  46. data/colabfold/__init__.py +0 -0
  47. data/colabfold/alphafold/__init__.py +0 -0
  48. data/colabfold/alphafold/extra_ptm.py +435 -0
  49. data/colabfold/alphafold/models.py +200 -0
  50. data/colabfold/alphafold/msa.py +44 -0
data/AlphaFold2.ipynb ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "accelerator": "GPU",
6
+ "colab": {
7
+ "provenance": [],
8
+ "gpuType": "T4",
9
+ "include_colab_link": true
10
+ },
11
+ "kernelspec": {
12
+ "display_name": "Python 3",
13
+ "name": "python3"
14
+ },
15
+ "language_info": {
16
+ "codemirror_mode": {
17
+ "name": "ipython",
18
+ "version": 3
19
+ },
20
+ "file_extension": ".py",
21
+ "mimetype": "text/x-python",
22
+ "name": "python",
23
+ "nbconvert_exporter": "python",
24
+ "pygments_lexer": "ipython3",
25
+ "version": "3.8.10"
26
+ }
27
+ },
28
+ "cells": [
29
+ {
30
+ "cell_type": "markdown",
31
+ "metadata": {
32
+ "id": "view-in-github",
33
+ "colab_type": "text"
34
+ },
35
+ "source": [
36
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/AlphaFold2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "metadata": {
42
+ "id": "G4yBrceuFbf3"
43
+ },
44
+ "source": [
45
+ "<img src=\"https://raw.githubusercontent.com/sokrypton/ColabFold/main/.github/ColabFold_Marv_Logo_Small.png\" height=\"200\" align=\"right\" style=\"height:240px\">\n",
46
+ "\n",
47
+ "##ColabFold v1.6.1: AlphaFold2 using MMseqs2\n",
48
+ "\n",
49
+ "Easy to use protein structure and complex prediction using [AlphaFold2](https://www.nature.com/articles/s41586-021-03819-2) and [Alphafold2-multimer](https://www.biorxiv.org/content/10.1101/2021.10.04.463034v1). Sequence alignments/templates are generated through [MMseqs2](mmseqs.com) and [HHsearch](https://github.com/soedinglab/hh-suite). For more details, see <a href=\"#Instructions\">bottom</a> of the notebook, checkout the [ColabFold GitHub](https://github.com/sokrypton/ColabFold) and [Nature Protocols](https://www.nature.com/articles/s41596-024-01060-5).\n",
50
+ "\n",
51
+ "Old versions: [v1.4](https://colab.research.google.com/github/sokrypton/ColabFold/blob/v1.4.0/AlphaFold2.ipynb), [v1.5.1](https://colab.research.google.com/github/sokrypton/ColabFold/blob/v1.5.1/AlphaFold2.ipynb), [v1.5.2](https://colab.research.google.com/github/sokrypton/ColabFold/blob/v1.5.2/AlphaFold2.ipynb), [v1.5.3-patch](https://colab.research.google.com/github/sokrypton/ColabFold/blob/56c72044c7d51a311ca99b953a71e552fdc042e1/AlphaFold2.ipynb)\n",
52
+ "\n",
53
+ "[Mirdita M, Schütze K, Moriwaki Y, Heo L, Ovchinnikov S, Steinegger M. ColabFold: Making protein folding accessible to all.\n",
54
+ "*Nature Methods*, 2022](https://www.nature.com/articles/s41592-022-01488-1)"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {
60
+ "id": "kOblAo-xetgx",
61
+ "cellView": "form"
62
+ },
63
+ "source": [
64
+ "#@title Input protein sequence(s), then hit `Runtime` -> `Run all`\n",
65
+ "from google.colab import files\n",
66
+ "import os\n",
67
+ "import re\n",
68
+ "import hashlib\n",
69
+ "import random\n",
70
+ "\n",
71
+ "from sys import version_info\n",
72
+ "python_version = f\"{version_info.major}.{version_info.minor}\"\n",
73
+ "\n",
74
+ "def add_hash(x,y):\n",
75
+ " return x+\"_\"+hashlib.sha1(y.encode()).hexdigest()[:5]\n",
76
+ "\n",
77
+ "query_sequence = 'PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK' #@param {type:\"string\"}\n",
78
+ "#@markdown - Use `:` to specify inter-protein chainbreaks for **modeling complexes** (supports homo- and hetro-oligomers). For example **PI...SK:PI...SK** for a homodimer\n",
79
+ "jobname = 'test' #@param {type:\"string\"}\n",
80
+ "# number of models to use\n",
81
+ "num_relax = 0 #@param [0, 1, 5] {type:\"raw\"}\n",
82
+ "#@markdown - specify how many of the top ranked structures to relax using amber\n",
83
+ "template_mode = \"none\" #@param [\"none\", \"pdb100\",\"custom\"]\n",
84
+ "#@markdown - `none` = no template information is used. `pdb100` = detect templates in pdb100 (see [notes](#pdb100)). `custom` - upload and search own templates (PDB or mmCIF format, see [notes](#custom_templates))\n",
85
+ "\n",
86
+ "use_amber = num_relax > 0\n",
87
+ "\n",
88
+ "# remove whitespaces\n",
89
+ "query_sequence = \"\".join(query_sequence.split())\n",
90
+ "\n",
91
+ "basejobname = \"\".join(jobname.split())\n",
92
+ "basejobname = re.sub(r'\\W+', '', basejobname)\n",
93
+ "jobname = add_hash(basejobname, query_sequence)\n",
94
+ "\n",
95
+ "# check if directory with jobname exists\n",
96
+ "def check(folder):\n",
97
+ " if os.path.exists(folder):\n",
98
+ " return False\n",
99
+ " else:\n",
100
+ " return True\n",
101
+ "if not check(jobname):\n",
102
+ " n = 0\n",
103
+ " while not check(f\"{jobname}_{n}\"): n += 1\n",
104
+ " jobname = f\"{jobname}_{n}\"\n",
105
+ "\n",
106
+ "# make directory to save results\n",
107
+ "os.makedirs(jobname, exist_ok=True)\n",
108
+ "\n",
109
+ "# save queries\n",
110
+ "queries_path = os.path.join(jobname, f\"{jobname}.csv\")\n",
111
+ "with open(queries_path, \"w\") as text_file:\n",
112
+ " text_file.write(f\"id,sequence\\n{jobname},{query_sequence}\")\n",
113
+ "\n",
114
+ "if template_mode == \"pdb100\":\n",
115
+ " use_templates = True\n",
116
+ " custom_template_path = None\n",
117
+ "elif template_mode == \"custom\":\n",
118
+ " custom_template_path = os.path.join(jobname,f\"template\")\n",
119
+ " os.makedirs(custom_template_path, exist_ok=True)\n",
120
+ " uploaded = files.upload()\n",
121
+ " use_templates = True\n",
122
+ " for fn in uploaded.keys():\n",
123
+ " os.rename(fn,os.path.join(custom_template_path,fn))\n",
124
+ "else:\n",
125
+ " custom_template_path = None\n",
126
+ " use_templates = False\n",
127
+ "\n",
128
+ "print(\"jobname\",jobname)\n",
129
+ "print(\"sequence\",query_sequence)\n",
130
+ "print(\"length\",len(query_sequence.replace(\":\",\"\")))"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "source": [
138
+ "#@title Install dependencies\n",
139
+ "%%time\n",
140
+ "import os\n",
141
+ "USE_AMBER = use_amber\n",
142
+ "USE_TEMPLATES = use_templates\n",
143
+ "PYTHON_VERSION = python_version\n",
144
+ "\n",
145
+ "if not os.path.isfile(\"COLABFOLD_READY\"):\n",
146
+ " print(\"installing colabfold...\")\n",
147
+ " os.system(\"pip install -q --no-warn-conflicts 'colabfold[alphafold-minus-jax] @ git+https://github.com/sokrypton/ColabFold'\")\n",
148
+ " if os.environ.get('TPU_NAME', False) != False:\n",
149
+ " os.system(\"pip uninstall -y jax jaxlib\")\n",
150
+ " os.system(\"pip install --no-warn-conflicts --upgrade dm-haiku==0.0.10 'jax[cuda12_pip]'==0.3.25 -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html\")\n",
151
+ " os.system(\"ln -s /usr/local/lib/python3.*/dist-packages/colabfold colabfold\")\n",
152
+ " os.system(\"ln -s /usr/local/lib/python3.*/dist-packages/alphafold alphafold\")\n",
153
+ " # hack to fix TF crash\n",
154
+ " os.system(\"rm -f /usr/local/lib/python3.*/dist-packages/tensorflow/core/kernels/libtfkernel_sobol_op.so /usr/local/lib/python3.*/dist-packages/tensorflow/lite/python/*/*.so\")\n",
155
+ " os.system(\"touch COLABFOLD_READY\")\n",
156
+ "\n",
157
+ "if USE_AMBER or USE_TEMPLATES:\n",
158
+ " if not os.path.isfile(\"CONDA_READY\"):\n",
159
+ " print(\"installing conda...\")\n",
160
+ " os.system(\"wget -qnc https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-x86_64.sh\")\n",
161
+ " os.system(\"bash Miniforge3-Linux-x86_64.sh -bfp /usr/local\")\n",
162
+ " os.system(\"mamba config --set auto_update_conda false\")\n",
163
+ " os.system(\"touch CONDA_READY\")\n",
164
+ "\n",
165
+ "if USE_TEMPLATES and not os.path.isfile(\"HH_READY\") and USE_AMBER and not os.path.isfile(\"AMBER_READY\"):\n",
166
+ " print(\"installing hhsuite and amber...\")\n",
167
+ " os.system(f\"mamba install -y -c conda-forge -c bioconda kalign2=2.04 hhsuite=3.3.0 openmm=8.2.0 python='{PYTHON_VERSION}' pdbfixer\")\n",
168
+ " os.system(\"touch HH_READY\")\n",
169
+ " os.system(\"touch AMBER_READY\")\n",
170
+ "else:\n",
171
+ " if USE_TEMPLATES and not os.path.isfile(\"HH_READY\"):\n",
172
+ " print(\"installing hhsuite...\")\n",
173
+ " os.system(f\"mamba install -y -c conda-forge -c bioconda kalign2=2.04 hhsuite=3.3.0 python='{PYTHON_VERSION}'\")\n",
174
+ " os.system(\"touch HH_READY\")\n",
175
+ " if USE_AMBER and not os.path.isfile(\"AMBER_READY\"):\n",
176
+ " print(\"installing amber...\")\n",
177
+ " os.system(f\"mamba install -y -c conda-forge openmm=8.2.0 python='{PYTHON_VERSION}' pdbfixer\")\n",
178
+ " os.system(\"touch AMBER_READY\")"
179
+ ],
180
+ "metadata": {
181
+ "cellView": "form",
182
+ "id": "AzIKiDiCaHAn"
183
+ },
184
+ "execution_count": null,
185
+ "outputs": []
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "source": [
190
+ "#@markdown ### MSA options (custom MSA upload, single sequence, pairing mode)\n",
191
+ "msa_mode = \"mmseqs2_uniref_env\" #@param [\"mmseqs2_uniref_env\", \"mmseqs2_uniref\",\"single_sequence\",\"custom\"]\n",
192
+ "pair_mode = \"unpaired_paired\" #@param [\"unpaired_paired\",\"paired\",\"unpaired\"] {type:\"string\"}\n",
193
+ "#@markdown - \"unpaired_paired\" = pair sequences from same species + unpaired MSA, \"unpaired\" = seperate MSA for each chain, \"paired\" - only use paired sequences.\n",
194
+ "\n",
195
+ "# decide which a3m to use\n",
196
+ "if \"mmseqs2\" in msa_mode:\n",
197
+ " a3m_file = os.path.join(jobname,f\"{jobname}.a3m\")\n",
198
+ "\n",
199
+ "elif msa_mode == \"custom\":\n",
200
+ " a3m_file = os.path.join(jobname,f\"{jobname}.custom.a3m\")\n",
201
+ " if not os.path.isfile(a3m_file):\n",
202
+ " custom_msa_dict = files.upload()\n",
203
+ " custom_msa = list(custom_msa_dict.keys())[0]\n",
204
+ " header = 0\n",
205
+ " import fileinput\n",
206
+ " for line in fileinput.FileInput(custom_msa,inplace=1):\n",
207
+ " if line.startswith(\">\"):\n",
208
+ " header = header + 1\n",
209
+ " if not line.rstrip():\n",
210
+ " continue\n",
211
+ " if line.startswith(\">\") == False and header == 1:\n",
212
+ " query_sequence = line.rstrip()\n",
213
+ " print(line, end='')\n",
214
+ "\n",
215
+ " os.rename(custom_msa, a3m_file)\n",
216
+ " queries_path=a3m_file\n",
217
+ " print(f\"moving {custom_msa} to {a3m_file}\")\n",
218
+ "\n",
219
+ "else:\n",
220
+ " a3m_file = os.path.join(jobname,f\"{jobname}.single_sequence.a3m\")\n",
221
+ " with open(a3m_file, \"w\") as text_file:\n",
222
+ " text_file.write(\">1\\n%s\" % query_sequence)"
223
+ ],
224
+ "metadata": {
225
+ "cellView": "form",
226
+ "id": "C2_sh2uAonJH"
227
+ },
228
+ "execution_count": null,
229
+ "outputs": []
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "source": [
234
+ "#@markdown ### Advanced settings\n",
235
+ "model_type = \"auto\" #@param [\"auto\", \"alphafold2_ptm\", \"alphafold2_multimer_v1\", \"alphafold2_multimer_v2\", \"alphafold2_multimer_v3\", \"deepfold_v1\", \"alphafold2\"]\n",
236
+ "#@markdown - if `auto` selected, will use `alphafold2_ptm` for monomer prediction and `alphafold2_multimer_v3` for complex prediction.\n",
237
+ "#@markdown Any of the mode_types can be used (regardless if input is monomer or complex).\n",
238
+ "num_recycles = \"3\" #@param [\"auto\", \"0\", \"1\", \"3\", \"6\", \"12\", \"24\", \"48\"]\n",
239
+ "#@markdown - if `auto` selected, will use `num_recycles=20` if `model_type=alphafold2_multimer_v3`, else `num_recycles=3` .\n",
240
+ "recycle_early_stop_tolerance = \"auto\" #@param [\"auto\", \"0.0\", \"0.5\", \"1.0\"]\n",
241
+ "#@markdown - if `auto` selected, will use `tol=0.5` if `model_type=alphafold2_multimer_v3` else `tol=0.0`.\n",
242
+ "relax_max_iterations = 200 #@param [0, 200, 2000] {type:\"raw\"}\n",
243
+ "#@markdown - max amber relax iterations, `0` = unlimited (AlphaFold2 default, can take very long)\n",
244
+ "pairing_strategy = \"greedy\" #@param [\"greedy\", \"complete\"] {type:\"string\"}\n",
245
+ "#@markdown - `greedy` = pair any taxonomically matching subsets, `complete` = all sequences have to match in one line.\n",
246
+ "calc_extra_ptm = False #@param {type:\"boolean\"}\n",
247
+ "#@markdown - return pairwise chain iptm/actifptm\n",
248
+ "\n",
249
+ "#@markdown #### Sample settings\n",
250
+ "#@markdown - enable dropouts and increase number of seeds to sample predictions from uncertainty of the model.\n",
251
+ "#@markdown - decrease `max_msa` to increase uncertainity\n",
252
+ "max_msa = \"auto\" #@param [\"auto\", \"512:1024\", \"256:512\", \"64:128\", \"32:64\", \"16:32\"]\n",
253
+ "num_seeds = 1 #@param [1,2,4,8,16] {type:\"raw\"}\n",
254
+ "use_dropout = False #@param {type:\"boolean\"}\n",
255
+ "\n",
256
+ "num_recycles = None if num_recycles == \"auto\" else int(num_recycles)\n",
257
+ "recycle_early_stop_tolerance = None if recycle_early_stop_tolerance == \"auto\" else float(recycle_early_stop_tolerance)\n",
258
+ "if max_msa == \"auto\": max_msa = None\n",
259
+ "\n",
260
+ "#@markdown #### Save settings\n",
261
+ "save_all = False #@param {type:\"boolean\"}\n",
262
+ "save_recycles = False #@param {type:\"boolean\"}\n",
263
+ "save_to_google_drive = False #@param {type:\"boolean\"}\n",
264
+ "#@markdown - if the save_to_google_drive option was selected, the result zip will be uploaded to your Google Drive\n",
265
+ "dpi = 200 #@param {type:\"integer\"}\n",
266
+ "#@markdown - set dpi for image resolution\n",
267
+ "\n",
268
+ "if save_to_google_drive:\n",
269
+ " from pydrive2.drive import GoogleDrive\n",
270
+ " from pydrive2.auth import GoogleAuth\n",
271
+ " from google.colab import auth\n",
272
+ " from oauth2client.client import GoogleCredentials\n",
273
+ " auth.authenticate_user()\n",
274
+ " gauth = GoogleAuth()\n",
275
+ " gauth.credentials = GoogleCredentials.get_application_default()\n",
276
+ " drive = GoogleDrive(gauth)\n",
277
+ " print(\"You are logged into Google Drive and are good to go!\")\n",
278
+ "\n",
279
+ "#@markdown Don't forget to hit `Runtime` -> `Run all` after updating the form."
280
+ ],
281
+ "metadata": {
282
+ "cellView": "form",
283
+ "id": "ADDuaolKmjGW"
284
+ },
285
+ "execution_count": null,
286
+ "outputs": []
287
+ },
288
+ {
289
+ "cell_type": "code",
290
+ "source": [
291
+ "#@title Run Prediction\n",
292
+ "display_images = True #@param {type:\"boolean\"}\n",
293
+ "\n",
294
+ "import sys\n",
295
+ "import warnings\n",
296
+ "warnings.simplefilter(action='ignore', category=FutureWarning)\n",
297
+ "from Bio import BiopythonDeprecationWarning\n",
298
+ "warnings.simplefilter(action='ignore', category=BiopythonDeprecationWarning)\n",
299
+ "from pathlib import Path\n",
300
+ "from colabfold.download import download_alphafold_params, default_data_dir\n",
301
+ "from colabfold.utils import setup_logging\n",
302
+ "from colabfold.batch import get_queries, run, set_model_type\n",
303
+ "from colabfold.plot import plot_msa_v2\n",
304
+ "\n",
305
+ "import os\n",
306
+ "import numpy as np\n",
307
+ "try:\n",
308
+ " K80_chk = os.popen('nvidia-smi | grep \"Tesla K80\" | wc -l').read()\n",
309
+ "except:\n",
310
+ " K80_chk = \"0\"\n",
311
+ " pass\n",
312
+ "if \"1\" in K80_chk:\n",
313
+ " print(\"WARNING: found GPU Tesla K80: limited to total length < 1000\")\n",
314
+ " if \"TF_FORCE_UNIFIED_MEMORY\" in os.environ:\n",
315
+ " del os.environ[\"TF_FORCE_UNIFIED_MEMORY\"]\n",
316
+ " if \"XLA_PYTHON_CLIENT_MEM_FRACTION\" in os.environ:\n",
317
+ " del os.environ[\"XLA_PYTHON_CLIENT_MEM_FRACTION\"]\n",
318
+ "\n",
319
+ "from colabfold.colabfold import plot_protein\n",
320
+ "from pathlib import Path\n",
321
+ "import matplotlib.pyplot as plt\n",
322
+ "\n",
323
+ "# For some reason we need that to get pdbfixer to import\n",
324
+ "if use_amber and f\"/usr/local/lib/python{python_version}/site-packages/\" not in sys.path:\n",
325
+ " sys.path.insert(0, f\"/usr/local/lib/python{python_version}/site-packages/\")\n",
326
+ "\n",
327
+ "def input_features_callback(input_features):\n",
328
+ " if display_images:\n",
329
+ " plot_msa_v2(input_features)\n",
330
+ " plt.show()\n",
331
+ " plt.close()\n",
332
+ "\n",
333
+ "def prediction_callback(protein_obj, length,\n",
334
+ " prediction_result, input_features, mode):\n",
335
+ " model_name, relaxed = mode\n",
336
+ " if not relaxed:\n",
337
+ " if display_images:\n",
338
+ " fig = plot_protein(protein_obj, Ls=length, dpi=150)\n",
339
+ " plt.show()\n",
340
+ " plt.close()\n",
341
+ "\n",
342
+ "result_dir = jobname\n",
343
+ "log_filename = os.path.join(jobname,\"log.txt\")\n",
344
+ "setup_logging(Path(log_filename))\n",
345
+ "\n",
346
+ "queries, is_complex = get_queries(queries_path)\n",
347
+ "model_type = set_model_type(is_complex, model_type)\n",
348
+ "\n",
349
+ "if \"multimer\" in model_type and max_msa is not None:\n",
350
+ " use_cluster_profile = False\n",
351
+ "else:\n",
352
+ " use_cluster_profile = True\n",
353
+ "\n",
354
+ "download_alphafold_params(model_type, Path(\".\"))\n",
355
+ "results = run(\n",
356
+ " queries=queries,\n",
357
+ " result_dir=result_dir,\n",
358
+ " use_templates=use_templates,\n",
359
+ " custom_template_path=custom_template_path,\n",
360
+ " num_relax=num_relax,\n",
361
+ " msa_mode=msa_mode,\n",
362
+ " model_type=model_type,\n",
363
+ " num_models=5,\n",
364
+ " num_recycles=num_recycles,\n",
365
+ " relax_max_iterations=relax_max_iterations,\n",
366
+ " recycle_early_stop_tolerance=recycle_early_stop_tolerance,\n",
367
+ " num_seeds=num_seeds,\n",
368
+ " use_dropout=use_dropout,\n",
369
+ " model_order=[1,2,3,4,5],\n",
370
+ " is_complex=is_complex,\n",
371
+ " data_dir=Path(\".\"),\n",
372
+ " keep_existing_results=False,\n",
373
+ " rank_by=\"auto\",\n",
374
+ " pair_mode=pair_mode,\n",
375
+ " pairing_strategy=pairing_strategy,\n",
376
+ " stop_at_score=float(100),\n",
377
+ " prediction_callback=prediction_callback,\n",
378
+ " dpi=dpi,\n",
379
+ " zip_results=False,\n",
380
+ " save_all=save_all,\n",
381
+ " max_msa=max_msa,\n",
382
+ " use_cluster_profile=use_cluster_profile,\n",
383
+ " input_features_callback=input_features_callback,\n",
384
+ " save_recycles=save_recycles,\n",
385
+ " user_agent=\"colabfold/google-colab-main\",\n",
386
+ " calc_extra_ptm=calc_extra_ptm,\n",
387
+ ")\n",
388
+ "results_zip = f\"{jobname}.result.zip\"\n",
389
+ "os.system(f\"zip -r {results_zip} {jobname}\")"
390
+ ],
391
+ "metadata": {
392
+ "cellView": "form",
393
+ "id": "mbaIO9pWjaN0"
394
+ },
395
+ "execution_count": null,
396
+ "outputs": []
397
+ },
398
+ {
399
+ "cell_type": "code",
400
+ "metadata": {
401
+ "id": "KK7X9T44pWb7",
402
+ "cellView": "form"
403
+ },
404
+ "source": [
405
+ "#@title Display 3D structure {run: \"auto\"}\n",
406
+ "import py3Dmol\n",
407
+ "import glob\n",
408
+ "import matplotlib.pyplot as plt\n",
409
+ "from colabfold.colabfold import plot_plddt_legend\n",
410
+ "from colabfold.colabfold import pymol_color_list, alphabet_list\n",
411
+ "rank_num = 1 #@param [\"1\", \"2\", \"3\", \"4\", \"5\"] {type:\"raw\"}\n",
412
+ "color = \"lDDT\" #@param [\"chain\", \"lDDT\", \"rainbow\"]\n",
413
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
414
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
415
+ "\n",
416
+ "tag = results[\"rank\"][0][rank_num - 1]\n",
417
+ "jobname_prefix = \".custom\" if msa_mode == \"custom\" else \"\"\n",
418
+ "pdb_filename = f\"{jobname}/{jobname}{jobname_prefix}_unrelaxed_{tag}.pdb\"\n",
419
+ "pdb_file = glob.glob(pdb_filename)\n",
420
+ "\n",
421
+ "def show_pdb(rank_num=1, show_sidechains=False, show_mainchains=False, color=\"lDDT\"):\n",
422
+ " model_name = f\"rank_{rank_num}\"\n",
423
+ " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js',)\n",
424
+ " view.addModel(open(pdb_file[0],'r').read(),'pdb')\n",
425
+ "\n",
426
+ " if color == \"lDDT\":\n",
427
+ " view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':50,'max':90}}})\n",
428
+ " elif color == \"rainbow\":\n",
429
+ " view.setStyle({'cartoon': {'color':'spectrum'}})\n",
430
+ " elif color == \"chain\":\n",
431
+ " chains = len(queries[0][1]) + 1 if is_complex else 1\n",
432
+ " for n,chain,color in zip(range(chains),alphabet_list,pymol_color_list):\n",
433
+ " view.setStyle({'chain':chain},{'cartoon': {'color':color}})\n",
434
+ "\n",
435
+ " if show_sidechains:\n",
436
+ " BB = ['C','O','N']\n",
437
+ " view.addStyle({'and':[{'resn':[\"GLY\",\"PRO\"],'invert':True},{'atom':BB,'invert':True}]},\n",
438
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
439
+ " view.addStyle({'and':[{'resn':\"GLY\"},{'atom':'CA'}]},\n",
440
+ " {'sphere':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
441
+ " view.addStyle({'and':[{'resn':\"PRO\"},{'atom':['C','O'],'invert':True}]},\n",
442
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
443
+ " if show_mainchains:\n",
444
+ " BB = ['C','O','N','CA']\n",
445
+ " view.addStyle({'atom':BB},{'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
446
+ "\n",
447
+ " view.zoomTo()\n",
448
+ " return view\n",
449
+ "\n",
450
+ "show_pdb(rank_num, show_sidechains, show_mainchains, color).show()\n",
451
+ "if color == \"lDDT\":\n",
452
+ " plot_plddt_legend().show()"
453
+ ],
454
+ "execution_count": null,
455
+ "outputs": []
456
+ },
457
+ {
458
+ "cell_type": "code",
459
+ "metadata": {
460
+ "id": "11l8k--10q0C",
461
+ "cellView": "form"
462
+ },
463
+ "source": [
464
+ "#@title Plots {run: \"auto\"}\n",
465
+ "from IPython.display import display, HTML\n",
466
+ "import base64\n",
467
+ "from html import escape\n",
468
+ "\n",
469
+ "# see: https://stackoverflow.com/a/53688522\n",
470
+ "def image_to_data_url(filename):\n",
471
+ " ext = filename.split('.')[-1]\n",
472
+ " prefix = f'data:image/{ext};base64,'\n",
473
+ " with open(filename, 'rb') as f:\n",
474
+ " img = f.read()\n",
475
+ " return prefix + base64.b64encode(img).decode('utf-8')\n",
476
+ "\n",
477
+ "pae = \"\"\n",
478
+ "pae_file = os.path.join(jobname,f\"{jobname}{jobname_prefix}_pae.png\")\n",
479
+ "if os.path.isfile(pae_file):\n",
480
+ " pae = image_to_data_url(pae_file)\n",
481
+ "cov = image_to_data_url(os.path.join(jobname,f\"{jobname}{jobname_prefix}_coverage.png\"))\n",
482
+ "plddt = image_to_data_url(os.path.join(jobname,f\"{jobname}{jobname_prefix}_plddt.png\"))\n",
483
+ "display(HTML(f\"\"\"\n",
484
+ "<style>\n",
485
+ " img {{\n",
486
+ " float:left;\n",
487
+ " }}\n",
488
+ " .full {{\n",
489
+ " max-width:100%;\n",
490
+ " }}\n",
491
+ " .half {{\n",
492
+ " max-width:50%;\n",
493
+ " }}\n",
494
+ " @media (max-width:640px) {{\n",
495
+ " .half {{\n",
496
+ " max-width:100%;\n",
497
+ " }}\n",
498
+ " }}\n",
499
+ "</style>\n",
500
+ "<div style=\"max-width:90%; padding:2em;\">\n",
501
+ " <h1>Plots for {escape(jobname)}</h1>\n",
502
+ " { '<!--' if pae == '' else '' }<img src=\"{pae}\" class=\"full\" />{ '-->' if pae == '' else '' }\n",
503
+ " <img src=\"{cov}\" class=\"half\" />\n",
504
+ " <img src=\"{plddt}\" class=\"half\" />\n",
505
+ "</div>\n",
506
+ "\"\"\"))"
507
+ ],
508
+ "execution_count": null,
509
+ "outputs": []
510
+ },
511
+ {
512
+ "cell_type": "code",
513
+ "source": [
514
+ "#@title Package and download results\n",
515
+ "#@markdown If you are having issues downloading the result archive, try disabling your adblocker and run this cell again. If that fails click on the little folder icon to the left, navigate to file: `jobname.result.zip`, right-click and select \\\"Download\\\" (see [screenshot](https://pbs.twimg.com/media/E6wRW2lWUAEOuoe?format=jpg&name=small)).\n",
516
+ "\n",
517
+ "if msa_mode == \"custom\":\n",
518
+ " print(\"Don't forget to cite your custom MSA generation method.\")\n",
519
+ "\n",
520
+ "files.download(f\"{jobname}.result.zip\")\n",
521
+ "\n",
522
+ "if save_to_google_drive == True and drive:\n",
523
+ " uploaded = drive.CreateFile({'title': f\"{jobname}.result.zip\"})\n",
524
+ " uploaded.SetContentFile(f\"{jobname}.result.zip\")\n",
525
+ " uploaded.Upload()\n",
526
+ " print(f\"Uploaded {jobname}.result.zip to Google Drive with ID {uploaded.get('id')}\")"
527
+ ],
528
+ "metadata": {
529
+ "cellView": "form",
530
+ "id": "R_AH6JSXaeb2"
531
+ },
532
+ "execution_count": null,
533
+ "outputs": []
534
+ },
535
+ {
536
+ "cell_type": "markdown",
537
+ "metadata": {
538
+ "id": "UGUBLzB3C6WN",
539
+ "pycharm": {
540
+ "name": "#%% md\n"
541
+ }
542
+ },
543
+ "source": [
544
+ "# Instructions <a name=\"Instructions\"></a>\n",
545
+ "For detailed instructions, tips and tricks, see recently published paper at [Nature Protocols](https://www.nature.com/articles/s41596-024-01060-5)\n",
546
+ "\n",
547
+ "**Quick start**\n",
548
+ "1. Paste your protein sequence(s) in the input field.\n",
549
+ "2. Press \"Runtime\" -> \"Run all\".\n",
550
+ "3. The pipeline consists of 5 steps. The currently running step is indicated by a circle with a stop sign next to it.\n",
551
+ "\n",
552
+ "**Result zip file contents**\n",
553
+ "\n",
554
+ "1. PDB formatted structures sorted by avg. pLDDT and complexes are sorted by pTMscore. (unrelaxed and relaxed if `use_amber` is enabled).\n",
555
+ "2. Plots of the model quality.\n",
556
+ "3. Plots of the MSA coverage.\n",
557
+ "4. Parameter log file.\n",
558
+ "5. A3M formatted input MSA.\n",
559
+ "6. A `predicted_aligned_error_v1.json` using [AlphaFold-DB's format](https://alphafold.ebi.ac.uk/faq#faq-7) and a `scores.json` for each model which contains an array (list of lists) for PAE, a list with the average pLDDT and the pTMscore.\n",
560
+ "7. BibTeX file with citations for all used tools and databases.\n",
561
+ "\n",
562
+ "At the end of the job a download modal box will pop up with a `jobname.result.zip` file. Additionally, if the `save_to_google_drive` option was selected, the `jobname.result.zip` will be uploaded to your Google Drive.\n",
563
+ "\n",
564
+ "**MSA generation for complexes**\n",
565
+ "\n",
566
+ "For the complex prediction we use unpaired and paired MSAs. Unpaired MSA is generated the same way as for the protein structures prediction by searching the UniRef100 and environmental sequences three iterations each.\n",
567
+ "\n",
568
+ "The paired MSA is generated by searching the UniRef100 database and pairing the best hits sharing the same NCBI taxonomic identifier (=species or sub-species). We only pair sequences if all of the query sequences are present for the respective taxonomic identifier.\n",
569
+ "\n",
570
+ "**Using a custom MSA as input**\n",
571
+ "\n",
572
+ "To predict the structure with a custom MSA (A3M formatted): (1) Change the `msa_mode`: to \"custom\", (2) Wait for an upload box to appear at the end of the \"MSA options ...\" box. Upload your A3M. The first fasta entry of the A3M must be the query sequence without gaps.\n",
573
+ "\n",
574
+ "It is also possilbe to provide custom MSAs for complex predictions. Read more about the format [here](https://github.com/sokrypton/ColabFold/issues/76).\n",
575
+ "\n",
576
+ "As an alternative for MSA generation the [HHblits Toolkit server](https://toolkit.tuebingen.mpg.de/tools/hhblits) can be used. After submitting your query, click \"Query Template MSA\" -> \"Download Full A3M\". Download the A3M file and upload it in this notebook.\n",
577
+ "\n",
578
+ "**PDB100** <a name=\"pdb100\"></a>\n",
579
+ "\n",
580
+ "As of 23/06/08, we have transitioned from using the PDB70 to a 100% clustered PDB, the PDB100. The construction methodology of PDB100 differs from that of PDB70.\n",
581
+ "\n",
582
+ "The PDB70 was constructed by running each PDB70 representative sequence through [HHblits](https://github.com/soedinglab/hh-suite) against the [Uniclust30](https://uniclust.mmseqs.com/). On the other hand, the PDB100 is built by searching each PDB100 representative structure with [Foldseek](https://github.com/steineggerlab/foldseek) against the [AlphaFold Database](https://alphafold.ebi.ac.uk).\n",
583
+ "\n",
584
+ "To maintain compatibility with older Notebook versions and local installations, the generated files and API responses will continue to be named \"PDB70\", even though we're now using the PDB100.\n",
585
+ "\n",
586
+ "**Using custom templates** <a name=\"custom_templates\"></a>\n",
587
+ "\n",
588
+ "To predict the structure with a custom template (PDB or mmCIF formatted): (1) change the `template_mode` to \"custom\" in the execute cell and (2) wait for an upload box to appear at the end of the \"Input Protein\" box. Select and upload your templates (multiple choices are possible).\n",
589
+ "\n",
590
+ "* Templates must follow the four letter PDB naming with lower case letters.\n",
591
+ "\n",
592
+ "* Templates in mmCIF format must contain `_entity_poly_seq`. An error is thrown if this field is not present. The field `_pdbx_audit_revision_history.revision_date` is automatically generated if it is not present.\n",
593
+ "\n",
594
+ "* Templates in PDB format are automatically converted to the mmCIF format. `_entity_poly_seq` and `_pdbx_audit_revision_history.revision_date` are automatically generated.\n",
595
+ "\n",
596
+ "If you encounter problems, please report them to this [issue](https://github.com/sokrypton/ColabFold/issues/177).\n",
597
+ "\n",
598
+ "**Comparison to the full AlphaFold2 and AlphaFold2 Colab**\n",
599
+ "\n",
600
+ "This notebook replaces the homology detection and MSA pairing of AlphaFold2 with MMseqs2. For a comparison against the [AlphaFold2 Colab](https://colab.research.google.com/github/deepmind/alphafold/blob/main/notebooks/AlphaFold.ipynb) and the full [AlphaFold2](https://github.com/deepmind/alphafold) system read our [paper](https://www.nature.com/articles/s41592-022-01488-1).\n",
601
+ "\n",
602
+ "**Troubleshooting**\n",
603
+ "* Check that the runtime type is set to GPU at \"Runtime\" -> \"Change runtime type\".\n",
604
+ "* Try to restart the session \"Runtime\" -> \"Factory reset runtime\".\n",
605
+ "* Check your input sequence.\n",
606
+ "\n",
607
+ "**Known issues**\n",
608
+ "* Google Colab assigns different types of GPUs with varying amount of memory. Some might not have enough memory to predict the structure for a long sequence.\n",
609
+ "* Your browser can block the pop-up for downloading the result file. You can choose the `save_to_google_drive` option to upload to Google Drive instead or manually download the result file: Click on the little folder icon to the left, navigate to file: `jobname.result.zip`, right-click and select \\\"Download\\\" (see [screenshot](https://pbs.twimg.com/media/E6wRW2lWUAEOuoe?format=jpg&name=small)).\n",
610
+ "\n",
611
+ "**Limitations**\n",
612
+ "* Computing resources: Our MMseqs2 API can handle ~20-50k requests per day.\n",
613
+ "* MSAs: MMseqs2 is very precise and sensitive but might find less hits compared to HHblits/HMMer searched against BFD or MGnify.\n",
614
+ "* We recommend to additionally use the full [AlphaFold2 pipeline](https://github.com/deepmind/alphafold).\n",
615
+ "\n",
616
+ "**Description of the plots**\n",
617
+ "* **Number of sequences per position** - We want to see at least 30 sequences per position, for best performance, ideally 100 sequences.\n",
618
+ "* **Predicted lDDT per position** - model confidence (out of 100) at each position. The higher the better.\n",
619
+ "* **Predicted Alignment Error** - For homooligomers, this could be a useful metric to assess how confident the model is about the interface. The lower the better.\n",
620
+ "\n",
621
+ "**Bugs**\n",
622
+ "- If you encounter any bugs, please report the issue to https://github.com/sokrypton/ColabFold/issues\n",
623
+ "\n",
624
+ "**License**\n",
625
+ "\n",
626
+ "The source code of ColabFold is licensed under [MIT](https://raw.githubusercontent.com/sokrypton/ColabFold/main/LICENSE). Additionally, this notebook uses the AlphaFold2 source code and its parameters licensed under [Apache 2.0](https://raw.githubusercontent.com/deepmind/alphafold/main/LICENSE) and [CC BY 4.0](https://creativecommons.org/licenses/by-sa/4.0/) respectively. Read more about the AlphaFold license [here](https://github.com/deepmind/alphafold).\n",
627
+ "\n",
628
+ "**Acknowledgments**\n",
629
+ "- We thank the AlphaFold team for developing an excellent model and open sourcing the software.\n",
630
+ "\n",
631
+ "- [KOBIC](https://kobic.re.kr) and [Söding Lab](https://www.mpinat.mpg.de/soeding) for providing the computational resources for the MMseqs2 MSA server.\n",
632
+ "\n",
633
+ "- Richard Evans for helping to benchmark the ColabFold's Alphafold-multimer support.\n",
634
+ "\n",
635
+ "- [David Koes](https://github.com/dkoes) for his awesome [py3Dmol](https://3dmol.csb.pitt.edu/) plugin, without whom these notebooks would be quite boring!\n",
636
+ "\n",
637
+ "- Do-Yoon Kim for creating the ColabFold logo.\n",
638
+ "\n",
639
+ "- A colab by Sergey Ovchinnikov ([@sokrypton](https://twitter.com/sokrypton)), Milot Mirdita ([@milot_mirdita](https://twitter.com/milot_mirdita)) and Martin Steinegger ([@thesteinegger](https://twitter.com/thesteinegger)).\n"
640
+ ]
641
+ }
642
+ ]
643
+ }
data/AlphaFold3_of3.ipynb ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "view-in-github",
7
+ "colab_type": "text"
8
+ },
9
+ "source": [
10
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/AlphaFold3_of3.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "id": "header",
16
+ "metadata": {
17
+ "id": "header"
18
+ },
19
+ "source": [
20
+ "# AlphaFold 3 (OpenFold3 Preview 2 weights)\n",
21
+ "\n",
22
+ "Predict protein, RNA, DNA, and small-molecule structures using [AlphaFold 3](https://www.nature.com/articles/s41586-024-07487-w) with the freely available [OpenFold3](https://github.com/aqlaboratory/openfold) weights (Apache 2.0 — no commercial restrictions).\n",
23
+ "\n",
24
+ "MSA generation via the [ColabFold](https://github.com/sokrypton/ColabFold) MMseqs2 server — **no local databases required**.\n",
25
+ "\n",
26
+ "Just fill in the **Input sequence(s)** cell and run all. Proteins, nucleic acids and ligands all go in a single box; attention/XLA flags are chosen automatically for your runtime (T4, newer GPUs, or CPU).\n",
27
+ "\n",
28
+ "**Citations:**\n",
29
+ "- Abramson et al. (2024) AlphaFold 3. *Nature* [doi:10.1038/s41586-024-07487-w](https://doi.org/10.1038/s41586-024-07487-w)\n",
30
+ "- Mirdita et al. (2022) ColabFold. *Nature Methods* [doi:10.1038/s41592-022-01488-1](https://doi.org/10.1038/s41592-022-01488-1)\n",
31
+ "- The OpenFold3 Team (2025) [Github](https://github.com/aqlaboratory/openfold-3) - [doi:10.5281/zenodo.19001000](https://doi.org/10.5281/zenodo.19001000)\n",
32
+ "\n",
33
+ "**Credits:** AF3 code: Google DeepMind (Apache 2.0) · OF3 weights: AlQuraishi Lab (Apache 2.0)"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "execution_count": null,
39
+ "id": "install",
40
+ "metadata": {
41
+ "cellView": "form",
42
+ "id": "install"
43
+ },
44
+ "outputs": [],
45
+ "source": [
46
+ "#@title Install dependencies (~3 mins)\n",
47
+ "%%time\n",
48
+ "import os, time, glob\n",
49
+ "\n",
50
+ "weights_url = '' #@param {type:\"string\"}\n",
51
+ "#@markdown - **weights_url**: leave EMPTY to use the free, open **OpenFold3** weights. To use\n",
52
+ "#@markdown the official **AlphaFold 3** weights, paste the Google Cloud URL: `https://storage.googleapis.com/alphafold3/models/[???]/af3.bin.zst` from your DeepMind\n",
53
+ "#@markdown approval email (you'll be prompted to authenticate). Subject to the AF3 weights terms of use.\n",
54
+ "weights_url = weights_url.strip()\n",
55
+ "USE_NATIVE = bool(weights_url)\n",
56
+ "NATIVE_DIR = 'af3_native_weights'\n",
57
+ "\n",
58
+ "if not os.path.isfile('ALPHAFOLD3_READY'):\n",
59
+ " print('Installing packages...')\n",
60
+ " os.system(\"pip install -q 'jax[cuda12]==0.10.1' dm-haiku==0.0.16 rdkit==2025.9.4 \\\n",
61
+ " zstandard awscli tokamax==0.0.11 py3Dmol py2Dmol\")\n",
62
+ " os.system(\"pip install -q --no-deps 'https://github.com/sokrypton/alphafold3/releases/download/v3.1.0/alphafold3_open-3.1.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl'\")\n",
63
+ " base = 'https://raw.githubusercontent.com/sokrypton/alphafold3/refs/heads/main'\n",
64
+ " for script in ['run_alphafold', 'convert_of3_weights']:\n",
65
+ " os.system(f'wget -q -nc {base}/{script}.py')\n",
66
+ " os.system('touch ALPHAFOLD3_READY')\n",
67
+ " print('Packages installed.')\n",
68
+ "\n",
69
+ "# Patch tokamax so Ada/consumer GPUs (L4, A10, RTX 30/40; cc 8.6/8.9) fall back to XLA\n",
70
+ "# kernels. tokamax enables its Triton kernels for ALL cc>=8.0 GPUs, but those kernels\n",
71
+ "# need more shared memory than Ada cards have -> 'Shared memory size limit exceeded' at\n",
72
+ "# launch (which its trace-time fallback can't catch). Restrict Triton to true datacenter\n",
73
+ "# GPUs (A100 cc 8.0, H100 cc 9.0+); everything else uses XLA, exactly like the T4 path.\n",
74
+ "try:\n",
75
+ " import tokamax\n",
76
+ " _gu = os.path.join(os.path.dirname(tokamax.__file__), '_src', 'gpu_utils.py')\n",
77
+ " _s = open(_gu).read()\n",
78
+ " _old = 'return float(device.compute_capability) >= 8.0'\n",
79
+ " _new = ('cc = float(device.compute_capability)\\n'\n",
80
+ " ' return cc == 8.0 or cc >= 9.0 # datacenter only; Ada/L4 (8.6/8.9) lack shared memory')\n",
81
+ " if _old in _s:\n",
82
+ " open(_gu, 'w').write(_s.replace(_old, _new))\n",
83
+ " print('Patched tokamax: Triton restricted to datacenter GPUs (L4/Ada -> XLA).')\n",
84
+ "except Exception as _e:\n",
85
+ " print(f'(tokamax patch skipped: {_e})')\n",
86
+ "\n",
87
+ "# Weights: official AlphaFold 3 (if a URL was given) or OpenFold3 (default, free)\n",
88
+ "if USE_NATIVE:\n",
89
+ " if not os.path.isfile('NATIVE_WEIGHTS_DONE'):\n",
90
+ " print('Fetching official AlphaFold 3 weights (Google authentication required)...')\n",
91
+ " from google.colab import auth\n",
92
+ " auth.authenticate_user()\n",
93
+ " from google.cloud import storage\n",
94
+ " weights_path = weights_url.removeprefix('https://storage.googleapis.com/alphafold3/')\n",
95
+ " blob = storage.Client().bucket('alphafold3').get_blob(weights_path)\n",
96
+ " if blob is None:\n",
97
+ " raise FileNotFoundError(f'No weights found at {weights_url} - check the URL and that your account was granted access.')\n",
98
+ " af3_weights = blob.open('rb').read()\n",
99
+ " print(f'Loaded AlphaFold 3 weights ({len(af3_weights):,} bytes)')\n",
100
+ " os.makedirs(NATIVE_DIR, exist_ok=True)\n",
101
+ " for _f in glob.glob(f'{NATIVE_DIR}/*'): # keep exactly one model file in the dir\n",
102
+ " os.remove(_f)\n",
103
+ " _name = os.path.basename(weights_path)\n",
104
+ " if not (_name.endswith('.bin') or _name.endswith('.bin.zst')):\n",
105
+ " _name = 'af3.bin.zst' if af3_weights[:4] == b'\\x28\\xb5\\x2f\\xfd' else 'af3.bin' # zstd magic\n",
106
+ " with open(f'{NATIVE_DIR}/{_name}', 'wb') as _fh:\n",
107
+ " _fh.write(af3_weights)\n",
108
+ " open('NATIVE_WEIGHTS_DONE', 'w').close()\n",
109
+ " print(f'Saved native weights -> {NATIVE_DIR}/{_name}')\n",
110
+ "elif not os.path.isfile('WEIGHTS_DONE'):\n",
111
+ " print('Downloading OpenFold3 weights...')\n",
112
+ " os.system('(aws s3 cp s3://openfold/staging/of3-p2-155k.pt . --no-sign-request; touch WEIGHTS_DONE) &')\n",
113
+ "\n",
114
+ "# Build AF3 data files (background, independent of weights)\n",
115
+ "if not os.path.isfile('DATA_DONE'):\n",
116
+ " print('Building AF3 data files...')\n",
117
+ " os.system('(build_data; touch DATA_DONE) &')\n",
118
+ "\n",
119
+ "# Wait for background jobs (the OF3 download only matters for the OpenFold3 path)\n",
120
+ "for sentinel in (['DATA_DONE'] if USE_NATIVE else ['WEIGHTS_DONE', 'DATA_DONE']):\n",
121
+ " while not os.path.isfile(sentinel):\n",
122
+ " time.sleep(5)\n",
123
+ " print(f'{sentinel} ✓')\n",
124
+ "\n",
125
+ "if not USE_NATIVE and not os.path.isfile('af3_converted_weights/of3_ported_weights.bin.zst'):\n",
126
+ " print(\"converting openfold3 weights...\")\n",
127
+ " os.system(\"python convert_of3_weights.py --of3_checkpoint of3-p2-155k.pt --output_dir af3_converted_weights\")\n",
128
+ "\n",
129
+ "print('Setup complete! ' + ('Using official AlphaFold 3 weights.' if USE_NATIVE else 'Using OpenFold3 weights.'))"
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "execution_count": null,
135
+ "id": "input",
136
+ "metadata": {
137
+ "id": "input",
138
+ "cellView": "form"
139
+ },
140
+ "outputs": [],
141
+ "source": [
142
+ "#@title Input sequences\n",
143
+ "import re, os, json, hashlib\n",
144
+ "\n",
145
+ "#@markdown ### Molecules\n",
146
+ "#@markdown Separate multiple chains within a box using `:` (extra colons are fine: `A::::B` == `A:B`). Leave a box empty if unused; full details in the Instructions cell.\n",
147
+ "protein = 'PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK' #@param {type:\"string\"}\n",
148
+ "dna = '' #@param {type:\"string\"}\n",
149
+ "rna = '' #@param {type:\"string\"}\n",
150
+ "ligand_ccd = '' #@param {type:\"string\"}\n",
151
+ "ligand_smiles = '' #@param {type:\"string\"}\n",
152
+ "\n",
153
+ "#@markdown ### Run settings\n",
154
+ "jobname = 'test' #@param {type:\"string\"}\n",
155
+ "msa_mode = \"mmseqs2_server\" #@param [\"mmseqs2_server\", \"single_sequence\"]\n",
156
+ "seeds = '1' #@param {type:\"string\"}\n",
157
+ "on_existing = \"overwrite\" #@param [\"overwrite\", \"skip\"]\n",
158
+ "#@markdown - `msa_mode`: `single_sequence` skips the MSA (faster, lower accuracy).\n",
159
+ "#@markdown - `seeds`: comma-separated, e.g. `1,2,3`.\n",
160
+ "#@markdown - `on_existing`: `overwrite` replaces this job's previous results; `skip` keeps them.\n",
161
+ "\n",
162
+ "# Split a box into entries: collapse colon runs, drop whitespace, skip empties\n",
163
+ "def split_entries(s):\n",
164
+ " s = re.sub(r':+', ':', s).strip(':')\n",
165
+ " return [e for e in (''.join(tok.split()) for tok in s.split(':')) if e]\n",
166
+ "\n",
167
+ "prot_seqs = [e.upper() for e in split_entries(protein)]\n",
168
+ "dna_seqs = [e.upper() for e in split_entries(dna)]\n",
169
+ "rna_seqs = [e.upper() for e in split_entries(rna)]\n",
170
+ "ccd_codes = [e.upper() for e in split_entries(ligand_ccd)]\n",
171
+ "smiles_strs = split_entries(ligand_smiles) # case-sensitive: leave as typed\n",
172
+ "\n",
173
+ "# Build AF3 chain entities (IDs A, B, C, ... in canonical order)\n",
174
+ "CHAIN_IDS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')\n",
175
+ "chains, prot_groups, idx = [], {}, 0\n",
176
+ "\n",
177
+ "for seq in prot_seqs:\n",
178
+ " cid = CHAIN_IDS[idx]; idx += 1\n",
179
+ " if seq in prot_groups: # merge identical seqs -> homo-oligomer\n",
180
+ " ent = prot_groups[seq]\n",
181
+ " ids = ent['id'] if isinstance(ent['id'], list) else [ent['id']]\n",
182
+ " ent['id'] = ids + [cid]\n",
183
+ " else:\n",
184
+ " ent = {'id': cid, 'sequence': seq, 'templates': []}\n",
185
+ " if msa_mode == 'single_sequence':\n",
186
+ " ent.update({'unpairedMsa': f'>query\\n{seq}\\n', 'pairedMsa': ''})\n",
187
+ " prot_groups[seq] = ent\n",
188
+ " chains.append({'protein': ent})\n",
189
+ "\n",
190
+ "for seq in rna_seqs:\n",
191
+ " c = {'id': CHAIN_IDS[idx], 'sequence': seq}\n",
192
+ " if msa_mode == 'single_sequence':\n",
193
+ " c['unpairedMsa'] = f'>query\\n{seq}\\n'\n",
194
+ " chains.append({'rna': c}); idx += 1\n",
195
+ "\n",
196
+ "for seq in dna_seqs:\n",
197
+ " chains.append({'dna': {'id': CHAIN_IDS[idx], 'sequence': seq}}); idx += 1\n",
198
+ "\n",
199
+ "for code in ccd_codes:\n",
200
+ " chains.append({'ligand': {'id': CHAIN_IDS[idx], 'ccdCodes': [code]}}); idx += 1\n",
201
+ "\n",
202
+ "for smiles in smiles_strs:\n",
203
+ " chains.append({'ligand': {'id': CHAIN_IDS[idx], 'smiles': smiles}}); idx += 1\n",
204
+ "\n",
205
+ "if not chains:\n",
206
+ " raise ValueError('No valid input found - fill in at least one box.')\n",
207
+ "\n",
208
+ "# Seeds: pull out integers regardless of separators, dedupe, default to [1]\n",
209
+ "seed_list = []\n",
210
+ "for tok in re.findall(r'\\d+', seeds):\n",
211
+ " v = int(tok)\n",
212
+ " if v not in seed_list:\n",
213
+ " seed_list.append(v)\n",
214
+ "if not seed_list:\n",
215
+ " seed_list = [1]\n",
216
+ "\n",
217
+ "# Deterministic, lower-cased job name from inputs+seeds.\n",
218
+ "# Same input+seeds -> same folder (so re-runs reuse it instead of piling up).\n",
219
+ "# Lower-cased to match run_alphafold.py's sanitised_name() output directory.\n",
220
+ "def _flat(mol):\n",
221
+ " if 'sequence' in mol: return mol['sequence']\n",
222
+ " if 'ccdCodes' in mol: return ','.join(mol['ccdCodes'])\n",
223
+ " return mol.get('smiles', '?')\n",
224
+ "flat = ':'.join(_flat(list(c.values())[0]) for c in chains) + '|seeds=' + ','.join(map(str, seed_list))\n",
225
+ "basejob = (re.sub(r'\\W+', '', ''.join(jobname.split())) or 'job').lower()\n",
226
+ "jobname = basejob + '_' + hashlib.sha1(flat.encode()).hexdigest()[:5]\n",
227
+ "\n",
228
+ "# Input JSON goes to a temp dir; ALL results land in ONE folder: af3_output/<jobname>/\n",
229
+ "INPUT_DIR = '/tmp/af3_inputs'\n",
230
+ "OUTPUT_DIR = 'af3_output'\n",
231
+ "job_dir = f'{OUTPUT_DIR}/{jobname}'\n",
232
+ "\n",
233
+ "fold_input = {\n",
234
+ " 'name': jobname,\n",
235
+ " 'sequences': chains,\n",
236
+ " 'modelSeeds': seed_list,\n",
237
+ " 'dialect': 'alphafold3',\n",
238
+ " 'version': 1,\n",
239
+ "}\n",
240
+ "os.makedirs(INPUT_DIR, exist_ok=True)\n",
241
+ "json_path = f'{INPUT_DIR}/{jobname}.json'\n",
242
+ "with open(json_path, 'w') as f:\n",
243
+ " json.dump(fold_input, f, indent=2)\n",
244
+ "\n",
245
+ "print(f'Job \"{jobname}\" -> results will be written to {job_dir}/')\n",
246
+ "fold_input\n"
247
+ ]
248
+ },
249
+ {
250
+ "cell_type": "code",
251
+ "execution_count": null,
252
+ "id": "run",
253
+ "metadata": {
254
+ "id": "run",
255
+ "cellView": "form"
256
+ },
257
+ "outputs": [],
258
+ "source": [
259
+ "#@title Run AlphaFold 3\n",
260
+ "%%time\n",
261
+ "import os, shutil, subprocess, glob\n",
262
+ "\n",
263
+ "#@markdown Inference settings (defaults match AlphaFold 3 - increase only if needed):\n",
264
+ "num_recycles = 10 #@param {type:\"integer\"}\n",
265
+ "num_diffusion_samples = 5 #@param {type:\"integer\"}\n",
266
+ "#@markdown - `num_recycles`: refinement passes through the network (default 10). More can help large/hard targets, but is slower.\n",
267
+ "#@markdown - `num_diffusion_samples`: candidate structures generated per seed (default 5). Total models = seeds x samples.\n",
268
+ "\n",
269
+ "num_recycles = max(1, int(num_recycles))\n",
270
+ "num_diffusion_samples = max(1, int(num_diffusion_samples))\n",
271
+ "\n",
272
+ "os.makedirs(OUTPUT_DIR, exist_ok=True)\n",
273
+ "\n",
274
+ "# Re-run policy (one folder per job, no timestamped duplicates):\n",
275
+ "# overwrite -> wipe this job's folder and recompute\n",
276
+ "# skip -> if a finished result (.cif) is already there, don't recompute\n",
277
+ "have_results = os.path.isdir(job_dir) and any(f.endswith('.cif') for f in os.listdir(job_dir))\n",
278
+ "run_it = not (on_existing == 'skip' and have_results)\n",
279
+ "if run_it:\n",
280
+ " shutil.rmtree(job_dir, ignore_errors=True) # start clean so exactly one folder is produced\n",
281
+ "\n",
282
+ "# Pick attention impl + XLA flags from the actual device.\n",
283
+ "# Triton/cuDNN flash attention need Ampere (compute capability >= 8.0);\n",
284
+ "# 7.x GPUs (T4=7.5, V100=7.0) and CPU use the portable XLA path, and 7.x\n",
285
+ "# additionally needs the XLA flag that disables the custom-kernel fusion pass.\n",
286
+ "def detect_device():\n",
287
+ " try:\n",
288
+ " out = subprocess.run(\n",
289
+ " ['nvidia-smi', '--query-gpu=compute_cap', '--format=csv,noheader'],\n",
290
+ " capture_output=True, text=True, timeout=15)\n",
291
+ " caps = [float(x) for x in out.stdout.split() if x.strip()]\n",
292
+ " if caps:\n",
293
+ " return 'gpu', min(caps)\n",
294
+ " except Exception:\n",
295
+ " pass\n",
296
+ " return 'cpu', None\n",
297
+ "\n",
298
+ "device, cap = detect_device()\n",
299
+ "nojit = False\n",
300
+ "xla_flags = [] # extra XLA flags to export for this device (per AlphaFold 3's guidance)\n",
301
+ "\n",
302
+ "if device == 'cpu':\n",
303
+ " flash_impl = 'xla'\n",
304
+ " nojit = True\n",
305
+ " print('No GPU detected - running on CPU with XLA attention + --nojit (slow, but avoids the compile).')\n",
306
+ "elif cap < 8.0:\n",
307
+ " # T4 / V100 (cc 7.x): XLA attention; disable the custom-kernel fusion pass.\n",
308
+ " # (Triton GEMM is not supported on these cards, so it is not disabled here.)\n",
309
+ " flash_impl = 'xla'\n",
310
+ " xla_flags = ['--xla_disable_hlo_passes=custom-kernel-fusion-rewriter']\n",
311
+ " print(f'Pre-Ampere GPU (compute capability {cap}) - XLA attention + custom-kernel fusion disabled.')\n",
312
+ "elif 8.0 < cap < 9.0:\n",
313
+ " # L4 / Ada / consumer Ampere (cc 8.6 / 8.9): limited shared memory. XLA's Triton GEMM\n",
314
+ " # kernels exceed it ('Shared memory size limit exceeded'), so disable Triton GEMM\n",
315
+ " # (falls back to cuBLAS) and use XLA attention to also avoid the Triton attention kernel.\n",
316
+ " flash_impl = 'xla'\n",
317
+ " xla_flags = ['--xla_gpu_enable_triton_gemm=false']\n",
318
+ " print(f'Ada/consumer GPU (compute capability {cap}) - XLA attention + Triton GEMM disabled (shared-memory limit).')\n",
319
+ "else:\n",
320
+ " # A100 (cc 8.0) and H100 (cc 9.0+): ample shared memory. Triton flash attention,\n",
321
+ " # with Triton GEMM disabled per AlphaFold 3's recommended XLA_FLAGS.\n",
322
+ " flash_impl = 'triton'\n",
323
+ " xla_flags = ['--xla_gpu_enable_triton_gemm=false']\n",
324
+ " print(f'Datacenter GPU (compute capability {cap}) - Triton flash attention + Triton GEMM disabled.')\n",
325
+ "\n",
326
+ "# Export XLA flags so the child shell (and JAX inside it) inherit them.\n",
327
+ "cur = os.environ.get('XLA_FLAGS', '')\n",
328
+ "for f in xla_flags:\n",
329
+ " if f not in cur:\n",
330
+ " cur = (cur + ' ' + f).strip()\n",
331
+ "if cur:\n",
332
+ " os.environ['XLA_FLAGS'] = cur\n",
333
+ "\n",
334
+ "print('XLA_FLAGS =', os.environ.get('XLA_FLAGS', '(unset)'))\n",
335
+ "\n",
336
+ "# Weights: use the official AlphaFold 3 weights if they were fetched, else OpenFold3.\n",
337
+ "if os.path.isdir('af3_native_weights') and glob.glob('af3_native_weights/*.bin*'):\n",
338
+ " model_dir, use_of3 = 'af3_native_weights', False\n",
339
+ " print('Weights: official AlphaFold 3')\n",
340
+ "else:\n",
341
+ " model_dir, use_of3 = 'af3_converted_weights', True\n",
342
+ " print('Weights: OpenFold3')\n",
343
+ "\n",
344
+ "cmd = [\n",
345
+ " 'python', 'run_alphafold.py',\n",
346
+ " f'--json_path={json_path}',\n",
347
+ " f'--model_dir={model_dir}',\n",
348
+ " '--norun_data_pipeline',\n",
349
+ " f'--output_dir={OUTPUT_DIR}',\n",
350
+ " '--cache_dir=/tmp/af3_cache',\n",
351
+ " '--force_output_dir', # reuse af3_output/<jobname>/ instead of a timestamped copy\n",
352
+ " f'--flash_attention_implementation={flash_impl}',\n",
353
+ " f'--num_recycles={num_recycles}',\n",
354
+ " f'--num_diffusion_samples={num_diffusion_samples}',\n",
355
+ "]\n",
356
+ "if msa_mode == 'mmseqs2_server':\n",
357
+ " cmd.append('--use_msa_server')\n",
358
+ "if nojit:\n",
359
+ " cmd.append('--nojit')\n",
360
+ "if use_of3:\n",
361
+ " cmd.append('--of3_weights')\n",
362
+ "\n",
363
+ "cmd = ' '.join(cmd)\n",
364
+ "if run_it:\n",
365
+ " print(cmd)\n",
366
+ " !{cmd}\n",
367
+ " print(f'\\nDone -> {job_dir}/')\n",
368
+ "else:\n",
369
+ " print(f'Skipping: results already exist in {job_dir}/ (set on_existing=overwrite to recompute).')\n"
370
+ ]
371
+ },
372
+ {
373
+ "cell_type": "code",
374
+ "execution_count": null,
375
+ "id": "display3d",
376
+ "metadata": {
377
+ "cellView": "form",
378
+ "id": "display3d"
379
+ },
380
+ "outputs": [],
381
+ "source": [
382
+ "#@title Display structures + PAE (py2Dmol)\n",
383
+ "import csv, glob, os, json\n",
384
+ "import numpy as np\n",
385
+ "import py2Dmol\n",
386
+ "\n",
387
+ "load_as_frames = True #@param {type:\"boolean\"}\n",
388
+ "viewer_size = 400\n",
389
+ "#@markdown All predicted models load together, best first (**rank_1, rank_2, ...**), each with its own PAE.\n",
390
+ "#@markdown - `load_as_frames` **off** -> pick a model from the dropdown.\n",
391
+ "#@markdown - `load_as_frames` **on** -> models become frames you can play through (press play / drag the slider).\n",
392
+ "#@markdown - The interactive PAE matrix sits beside the structure; click or drag-box on it to highlight residues.\n",
393
+ "\n",
394
+ "# All models in rank order (best first): from the ranking CSV, fall back to globbing.\n",
395
+ "def collect_models():\n",
396
+ " ranking_csv = f'{job_dir}/{jobname}_ranking_scores.csv'\n",
397
+ " cifs = []\n",
398
+ " if os.path.exists(ranking_csv):\n",
399
+ " rows = []\n",
400
+ " with open(ranking_csv) as f:\n",
401
+ " for r in csv.DictReader(f):\n",
402
+ " rows.append((float(r['ranking_score']), int(r['seed']), int(r['sample'])))\n",
403
+ " for _, seed, sample in sorted(rows, reverse=True):\n",
404
+ " d = f'{job_dir}/seed-{seed}_sample-{sample}'\n",
405
+ " hit = sorted(glob.glob(f'{d}/*_model.cif')) or sorted(glob.glob(f'{d}/*.cif'))\n",
406
+ " if hit:\n",
407
+ " cifs.append(hit[0])\n",
408
+ " if not cifs:\n",
409
+ " cifs = (sorted(glob.glob(f'{job_dir}/**/*_model.cif', recursive=True))\n",
410
+ " or sorted(glob.glob(f'{job_dir}/**/*.cif', recursive=True)))\n",
411
+ " return cifs\n",
412
+ "\n",
413
+ "# Per-model PAE: confidences.json next to the CIF, else the top-level one.\n",
414
+ "def load_pae(cif):\n",
415
+ " d = os.path.dirname(cif)\n",
416
+ " cands = [p for p in glob.glob(f'{d}/*_confidences.json')\n",
417
+ " if 'summary' not in os.path.basename(p)]\n",
418
+ " if not cands:\n",
419
+ " top = f'{job_dir}/{jobname}_confidences.json'\n",
420
+ " cands = [top] if os.path.exists(top) else []\n",
421
+ " if cands:\n",
422
+ " pae = json.load(open(cands[0])).get('pae')\n",
423
+ " if pae is not None:\n",
424
+ " return np.asarray(pae, dtype=float)\n",
425
+ " return None\n",
426
+ "\n",
427
+ "cifs = collect_models()\n",
428
+ "if not cifs:\n",
429
+ " raise FileNotFoundError(f'No model CIFs found in {job_dir}/')\n",
430
+ "print(f'Loaded {len(cifs)} model(s) from {job_dir}/'\n",
431
+ " + (' (frames - press play)' if load_as_frames else ' (use the dropdown to switch)'))\n",
432
+ "\n",
433
+ "viewer = py2Dmol.view(size=(viewer_size, viewer_size),\n",
434
+ " pae=True, autoplay=load_as_frames)\n",
435
+ "for i, cif in enumerate(cifs, start=1):\n",
436
+ " pae = load_pae(cif)\n",
437
+ " if load_as_frames:\n",
438
+ " viewer.add_pdb(cif, name='models', paes=pae) # same name -> frames (play through)\n",
439
+ " else:\n",
440
+ " viewer.add_pdb(cif, name=f'rank_{i}', paes=pae) # distinct names -> dropdown of objects\n",
441
+ "viewer.show()\n"
442
+ ]
443
+ },
444
+ {
445
+ "cell_type": "code",
446
+ "execution_count": null,
447
+ "id": "plots",
448
+ "metadata": {
449
+ "id": "plots",
450
+ "cellView": "form"
451
+ },
452
+ "outputs": [],
453
+ "source": [
454
+ "#@title Quality metrics and plots\n",
455
+ "import json, os\n",
456
+ "import numpy as np\n",
457
+ "import matplotlib.pyplot as plt\n",
458
+ "\n",
459
+ "conf_path = f'{OUTPUT_DIR}/{jobname}/{jobname}_confidences.json'\n",
460
+ "summ_path = f'{OUTPUT_DIR}/{jobname}/{jobname}_summary_confidences.json'\n",
461
+ "\n",
462
+ "with open(conf_path) as f:\n",
463
+ " conf = json.load(f)\n",
464
+ "with open(summ_path) as f:\n",
465
+ " summ = json.load(f)\n",
466
+ "\n",
467
+ "plddts = np.array(conf.get('atom_plddts', conf.get('token_plddts', [])), dtype=float)\n",
468
+ "plddt_chain_ids = conf.get('atom_chain_ids', conf.get('token_chain_ids', [])) # pLDDT is per-ATOM\n",
469
+ "token_chain_ids = conf.get('token_chain_ids', []) # PAE is per-TOKEN\n",
470
+ "pae = np.array(conf.get('pae', []), dtype=float)\n",
471
+ "\n",
472
+ "# ── Summary (ipTM is None for single-chain jobs — guard before formatting) ─\n",
473
+ "def fmt(v):\n",
474
+ " return f'{v:.3f}' if isinstance(v, (int, float)) else 'n/a'\n",
475
+ "\n",
476
+ "mean_plddt = summ.get('mean_plddt')\n",
477
+ "if mean_plddt is None and plddts.size:\n",
478
+ " mean_plddt = float(np.mean(plddts))\n",
479
+ "iptm = summ.get('iptm')\n",
480
+ "\n",
481
+ "print('=' * 38)\n",
482
+ "print(f'Mean pLDDT : {fmt(mean_plddt)}')\n",
483
+ "print(f'pTM : {fmt(summ.get(\"ptm\"))}')\n",
484
+ "print(f'ipTM : {fmt(iptm)}' + (' (single chain — no interface)' if iptm is None else ''))\n",
485
+ "print(f'Ranking score : {fmt(summ.get(\"ranking_score\"))}')\n",
486
+ "print('=' * 38)\n",
487
+ "\n",
488
+ "# ── Plots ───────────────────────────────────────────────────\n",
489
+ "has_pae = pae.ndim == 2 and pae.size > 0\n",
490
+ "ncols = 2 if has_pae else 1\n",
491
+ "fig, axes = plt.subplots(1, ncols, figsize=(13 if has_pae else 6.5, 4))\n",
492
+ "axes = np.atleast_1d(axes)\n",
493
+ "\n",
494
+ "# pLDDT per residue — a line (coloured per chain when there is more than one)\n",
495
+ "ax = axes[0]\n",
496
+ "x = np.arange(len(plddts))\n",
497
+ "xmax = max(len(plddts) - 1, 1)\n",
498
+ "ax.set_xlim(0, xmax)\n",
499
+ "ax.set_ylim(0, 100)\n",
500
+ "\n",
501
+ "unique_chains = list(dict.fromkeys(plddt_chain_ids))\n",
502
+ "if len(unique_chains) > 1:\n",
503
+ " colors = plt.cm.tab10(np.linspace(0, 1, len(unique_chains)))\n",
504
+ " tcid = np.array(plddt_chain_ids)\n",
505
+ " for ch, col in zip(unique_chains, colors):\n",
506
+ " y = np.where(tcid == ch, plddts, np.nan) # NaN gaps keep chains as separate lines\n",
507
+ " ax.plot(x, y, lw=1.5, color=col, label=f'Chain {ch}')\n",
508
+ " for b in [i for i in range(1, len(plddt_chain_ids)) if plddt_chain_ids[i] != plddt_chain_ids[i-1]]:\n",
509
+ " ax.axvline(b - 0.5, color='grey', lw=0.6, alpha=0.5)\n",
510
+ " ax.legend(loc='lower right', fontsize=8)\n",
511
+ "else:\n",
512
+ " ax.plot(x, plddts, lw=1.5, color='#1f77b4')\n",
513
+ "\n",
514
+ "for y in (50, 70, 90):\n",
515
+ " ax.axhline(y, ls='--', lw=0.7, color='grey', alpha=0.5)\n",
516
+ " ax.text(xmax, y, f' {y}', va='center', ha='left', fontsize=7, color='grey')\n",
517
+ "ax.set_xlabel('Atom')\n",
518
+ "ax.set_ylabel('pLDDT')\n",
519
+ "ax.set_title('Predicted pLDDT per atom')\n",
520
+ "\n",
521
+ "# PAE matrix\n",
522
+ "if has_pae:\n",
523
+ " ax = axes[1]\n",
524
+ " im = ax.imshow(pae, cmap='bwr', vmin=0, vmax=30, interpolation='nearest')\n",
525
+ " plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label='PAE (Å)')\n",
526
+ " if token_chain_ids:\n",
527
+ " for b in [i for i in range(1, len(token_chain_ids)) if token_chain_ids[i] != token_chain_ids[i-1]]:\n",
528
+ " ax.axhline(b - 0.5, c='black', lw=0.8)\n",
529
+ " ax.axvline(b - 0.5, c='black', lw=0.8)\n",
530
+ " ax.set_xlabel('Scored residue')\n",
531
+ " ax.set_ylabel('Aligned residue')\n",
532
+ " ax.set_title('Predicted Aligned Error (PAE)')\n",
533
+ "\n",
534
+ "plt.tight_layout()\n",
535
+ "plt.show()\n"
536
+ ]
537
+ },
538
+ {
539
+ "cell_type": "code",
540
+ "execution_count": null,
541
+ "id": "download",
542
+ "metadata": {
543
+ "cellView": "form",
544
+ "id": "download"
545
+ },
546
+ "outputs": [],
547
+ "source": [
548
+ "#@title Download results\n",
549
+ "from google.colab import files\n",
550
+ "import os\n",
551
+ "\n",
552
+ "results_zip = f'{jobname}.result.zip'\n",
553
+ "os.system(f'zip -r {results_zip} {OUTPUT_DIR}/{jobname}')\n",
554
+ "files.download(results_zip)\n"
555
+ ]
556
+ },
557
+ {
558
+ "cell_type": "markdown",
559
+ "id": "instructions",
560
+ "metadata": {
561
+ "id": "instructions"
562
+ },
563
+ "source": [
564
+ "# Instructions <a name=\"Instructions\"></a>\n",
565
+ "\n",
566
+ "**Quick start**\n",
567
+ "1. Fill in the sequence(s) in the **Input sequence(s)** cell.\n",
568
+ "2. Press **Runtime → Run all**.\n",
569
+ "3. The install cell (first run only) downloads OpenFold3 weights and builds AF3 data files in the background — subsequent runs reuse them.\n",
570
+ "\n",
571
+ "---\n",
572
+ "\n",
573
+ "## Model weights\n",
574
+ "\n",
575
+ "By default the notebook uses the open **OpenFold3** weights (Apache-2.0, no restrictions). To run the **official AlphaFold 3** weights instead, paste the Google Cloud URL from your DeepMind approval email into the **weights_url** field of the install cell. You'll be prompted to authenticate with the Google account that was granted access; the weights are fetched into `af3_native_weights/` and used automatically (the run cell detects them and drops the `--of3_weights` flag). Leaving **weights_url** empty keeps the OpenFold3 path.\n",
576
+ "\n",
577
+ "Official AlphaFold 3 parameters are subject to the [AF3 weights terms of use](https://github.com/google-deepmind/alphafold3/blob/main/WEIGHTS_TERMS_OF_USE.md); run_alphafold prints a reminder of these terms when they are used.\n",
578
+ "\n",
579
+ "---\n",
580
+ "\n",
581
+ "## Sequence input\n",
582
+ "\n",
583
+ "Each molecule type has its own box. Within a box, separate multiple chains with `:`.\n",
584
+ "\n",
585
+ "| Box | What goes in it | Example |\n",
586
+ "|---|---|---|\n",
587
+ "| **protein** | amino-acid sequence(s) | `MKTAY...` or `SEQ1:SEQ2` |\n",
588
+ "| **dna** | DNA sequence(s) | `CGCGAATTCGCG` |\n",
589
+ "| **rna** | RNA sequence(s) | `GCGGAUUUA` |\n",
590
+ "| **ligand_ccd** | ligand(s) by PDB CCD code | `ATP:MG:HEM` |\n",
591
+ "| **ligand_smiles** | ligand(s) by SMILES | `CC(=O)Oc1ccccc1C(=O)O` |\n",
592
+ "\n",
593
+ "Chains are assigned IDs A, B, C, … following AlphaFold 3's canonical order (protein → RNA → DNA → ligand; CCD ligands before SMILES ligands). Mix freely across boxes to build a complex — e.g. a protein in **protein**, `AUGCAUGC` in **rna**, and `ATP` in **ligand_ccd**.\n",
594
+ "\n",
595
+ "- **Homo-oligomers**: identical protein sequences are merged automatically, so `SEQ:SEQ` = homodimer, `SEQ:SEQ:SEQ` = homotrimer.\n",
596
+ "- Protein / DNA / RNA sequences and CCD codes are upper-cased automatically; **SMILES are left exactly as typed** (case is meaningful in SMILES).\n",
597
+ "- Spaces and newlines inside an entry are ignored, and **extra colons are forgiven** — `SEQ1::::SEQ2` is the same as `SEQ1:SEQ2`. Leave a box empty if unused.\n",
598
+ "- *Note:* because `:` separates entries, an atom-mapped SMILES that itself contains a colon (e.g. `[C:1]`) isn't supported via the box — use a raw AF3 JSON for that edge case.\n",
599
+ "\n",
600
+ "## Seeds\n",
601
+ "\n",
602
+ "Enter one or more model seeds in the **seeds** box, comma-separated (e.g. `1,2,3`). Each seed is an independent prediction (more seeds = more sampling, more runtime). Non-numeric characters are ignored and duplicates are dropped, so `1, 1, foo, 7` becomes seeds `1` and `7`.\n",
603
+ "\n",
604
+ "## MSA modes\n",
605
+ "\n",
606
+ "- **`mmseqs2_server`** *(recommended)*: queries the public [ColabFold](https://colabfold.mmseqs.com/) MMseqs2 API. Covers UniRef30 + environmental sequences for proteins. RNA/DNA chains always run MSA-free (ColabFold is protein-only).\n",
607
+ "- **`single_sequence`**: no MSA, query sequence only. Faster but less accurate, especially for monomers with close homologs.\n",
608
+ "\n",
609
+ "## Output files (inside the downloaded zip)\n",
610
+ "\n",
611
+ "| File | Contents |\n",
612
+ "|---|---|\n",
613
+ "| `*.cif` | Best-ranked structure in mmCIF format. B-factor = pLDDT (0–100). |\n",
614
+ "| `*_confidences.json` | Per-residue pLDDT, PAE matrix, contact probs. |\n",
615
+ "| `*_summary_confidences.json` | Mean pLDDT, pTM, ipTM, ranking score. |\n",
616
+ "| `*_ranking_scores.csv` | Ranking scores for all seed × sample combinations. |\n",
617
+ "| `seed-N_sample-M/` | Individual prediction directories (one per seed/sample). |\n",
618
+ "| `TERMS_OF_USE.md` | Apache 2.0 notice (OpenFold3 weights have no commercial restrictions). |\n",
619
+ "\n",
620
+ "## Interpreting confidence scores\n",
621
+ "\n",
622
+ "- **pLDDT > 90**: very high confidence.\n",
623
+ "- **pLDDT 70–90**: confident, backbone generally reliable.\n",
624
+ "- **pLDDT 50–70**: low confidence, treat with caution.\n",
625
+ "- **pLDDT < 50**: very low, likely disordered or incorrect.\n",
626
+ "- **PAE**: lower values = confident relative positioning between residue pairs. Useful for assessing interface quality in complexes.\n",
627
+ "- **ipTM > 0.8**: strong evidence for a well-defined complex interface. **ipTM is `n/a` for single-chain jobs** (there is no interface to score).\n",
628
+ "\n",
629
+ "## Troubleshooting\n",
630
+ "\n",
631
+ "- **Check runtime type**: `Runtime → Change runtime type → GPU` (T4 is fine; A100/L4 are faster).\n",
632
+ "- **OOM error**: reduce sequence length or use a larger-memory GPU runtime.\n",
633
+ "- **MSA server timeout**: the public ColabFold server is rate-limited. Try again later or switch to `single_sequence` mode.\n",
634
+ "- **Download popup blocked**: disable your ad blocker.\n",
635
+ "- **Weight download slow**: the OF3 checkpoint is ~1.4 GB from AWS S3; the install cell waits automatically.\n",
636
+ "\n",
637
+ "## License\n",
638
+ "\n",
639
+ "AlphaFold 3 source code and OpenFold3 weights are both licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). Outputs generated with OpenFold3 weights are **not** subject to Google DeepMind's AlphaFold 3 Output Terms of Use and may be used freely, including commercially.\n",
640
+ "\n",
641
+ "## Bugs / feedback\n",
642
+ "\n",
643
+ "Report issues at https://github.com/sokrypton/alphafold3/issues"
644
+ ]
645
+ }
646
+ ],
647
+ "metadata": {
648
+ "accelerator": "GPU",
649
+ "colab": {
650
+ "gpuType": "T4",
651
+ "provenance": [],
652
+ "include_colab_link": true
653
+ },
654
+ "kernelspec": {
655
+ "display_name": "Python 3",
656
+ "name": "python3"
657
+ },
658
+ "language_info": {
659
+ "name": "python"
660
+ }
661
+ },
662
+ "nbformat": 4,
663
+ "nbformat_minor": 5
664
+ }
data/BioEmu.ipynb ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "view-in-github",
7
+ "colab_type": "text"
8
+ },
9
+ "source": [
10
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/BioEmu.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "metadata": {
16
+ "id": "FLoa2lUhX9gu"
17
+ },
18
+ "source": [
19
+ "# **Biomolecular Emulator (BioEmu) in ColabFold**\n",
20
+ "<img src=\"https://github.com/microsoft/bioemu/raw/main/assets/emu.png\" height=\"130\" align=\"right\" style=\"height:240px\">\n",
21
+ "\n",
22
+ "[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",
23
+ "\n",
24
+ "\n",
25
+ "\n",
26
+ "For more details, please read the [BioEmu Preprint](https://www.biorxiv.org/content/10.1101/2024.12.05.626885v2).\n",
27
+ "\n",
28
+ "\n",
29
+ "## To run\n",
30
+ "Either run each cell sequentially, or click on `Runtime -> Run All` after choosing the desired sampling config"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": null,
36
+ "metadata": {
37
+ "cellView": "form",
38
+ "id": "TWM2qzfEYMaL"
39
+ },
40
+ "outputs": [],
41
+ "source": [
42
+ "#@title Sample with following config\n",
43
+ "#@markdown - `sequence`: Monomer sequence to sample\n",
44
+ "sequence = \"MADQLTEEQIAEFKEAFSLFDKDGDGTITTKELGTVMRSLGQNPTEAELQDMINEVDADGNGTIDFPEFLTMMARKMKDTDSEEEIREAFRVFDKDGNGYISAAELRHVMTNLGEKLTDEEVDEMIREADIDGDGQVNYEEFVQMMTAK\" #@param {type:\"string\"}\n",
45
+ "#@markdown - `num_samples`: Number of samples requested\n",
46
+ "num_samples = 10 #@param {type:\"integer\"}\n",
47
+ "#@markdown - `jobname`: Name assigned to this job\n",
48
+ "jobname = \"calmodulin\" #@param {type:\"string\"}\n",
49
+ "#@markdown - `filter_samples`: Whether to filter unphysical samples (e.g., those containing chain breaks) from the written samples\n",
50
+ "filter_samples = True #@param {type:\"boolean\"}\n",
51
+ "# #@param {type:\"boolean\"}\n",
52
+ "#@markdown - `model_name`: v1.1 = Journal accepted version | v1.0 preprint version\n",
53
+ "model_name = \"bioemu-v1.1\" #@param [\"bioemu-v1.0\", \"bioemu-v1.1\"]\n",
54
+ "# ------------------------\n",
55
+ "# Copied logic from ColabFold\n",
56
+ "# ------------------------\n",
57
+ "import os\n",
58
+ "import re\n",
59
+ "import hashlib\n",
60
+ "\n",
61
+ "def add_hash(x, seq):\n",
62
+ " \"\"\"Append a short SHA-1 hash of seq to x.\"\"\"\n",
63
+ " return x + \"_\" + hashlib.sha1(seq.encode()).hexdigest()[:5]\n",
64
+ "\n",
65
+ "def folder_is_free(folder):\n",
66
+ " \"\"\"Return True if folder doesn't exist.\"\"\"\n",
67
+ " return not os.path.exists(folder)\n",
68
+ "\n",
69
+ "jobname_clean = re.sub(r'\\W+', '', jobname)\n",
70
+ "sequence = \"\".join(sequence.split())\n",
71
+ "jobname = add_hash(jobname_clean, sequence)\n",
72
+ "\n",
73
+ "if not folder_is_free(jobname):\n",
74
+ " n = 0\n",
75
+ " while not folder_is_free(f\"{jobname}_{n}\"):\n",
76
+ " n += 1\n",
77
+ " jobname = f\"{jobname}_{n}\"\n",
78
+ "\n",
79
+ "output_dir = os.path.join(\"/content\", jobname)\n",
80
+ "os.makedirs(output_dir, exist_ok=True)\n"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "execution_count": null,
86
+ "metadata": {
87
+ "id": "7bAv6hU6Nedi",
88
+ "cellView": "form"
89
+ },
90
+ "outputs": [],
91
+ "source": [
92
+ "#@title Install dependencies\n",
93
+ "import os\n",
94
+ "import sys\n",
95
+ "\n",
96
+ "_is_bioemu_setup_file = '/content/.BIOEMU_SETUP'\n",
97
+ "\n",
98
+ "conda_prefix = '/usr/local/'\n",
99
+ "miniconda_link = 'https://repo.anaconda.com/miniconda/Miniconda3-py312_25.5.1-1-Linux-x86_64.sh'\n",
100
+ "miniconda_basename = os.path.basename(miniconda_link)\n",
101
+ "os.makedirs(conda_prefix, exist_ok=True)\n",
102
+ "\n",
103
+ "if not os.path.exists(_is_bioemu_setup_file):\n",
104
+ " os.system(f'wget {miniconda_link}')\n",
105
+ " os.system(f'chmod +x {miniconda_basename}')\n",
106
+ " os.system(f'./{miniconda_basename} -b -f -p {conda_prefix}')\n",
107
+ " os.system(f'conda install -q -y --prefix {conda_prefix} python=3.12')\n",
108
+ " os.system('uv pip install --prerelease if-necessary-or-explicit bioemu')\n",
109
+ "\n",
110
+ " os.system('conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main')\n",
111
+ " os.system('conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r')\n",
112
+ " os.system('conda install -c conda-forge openmm cuda-version=11 --yes')\n",
113
+ "\n",
114
+ " sys.path.append(os.path.join(conda_prefix, 'lib/python3.12/site-packages/'))\n",
115
+ "\n",
116
+ " os.environ['CONDA_PREFIX'] = conda_prefix\n",
117
+ " os.environ['CONDA_PREFIX_1'] = os.path.join(conda_prefix, 'envs/myenv')\n",
118
+ " os.environ['CONDA_DEFAULT_ENV'] = 'base'\n",
119
+ " os.system(f\"touch {_is_bioemu_setup_file}\")\n",
120
+ " os.system('wget https://mmseqs.com/foldseek/foldseek-linux-avx2.tar.gz; tar xvzf foldseek-linux-avx2.tar.gz')\n",
121
+ " os.system('/usr/bin/python3 -m pip install uv')\n",
122
+ " os.unlink(miniconda_basename)\n",
123
+ "\n"
124
+ ]
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "execution_count": null,
129
+ "metadata": {
130
+ "id": "_TYvJwSLMpd7",
131
+ "cellView": "form"
132
+ },
133
+ "outputs": [],
134
+ "source": [
135
+ "#@title Run BioEmu\n",
136
+ "\n",
137
+ "from bioemu.sample import main as sample\n",
138
+ "output_dir = f'/content/{jobname}'\n",
139
+ "sample(sequence=sequence, num_samples=num_samples, model_name=model_name, output_dir=output_dir, filter_samples=filter_samples)"
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "markdown",
144
+ "metadata": {
145
+ "id": "-1n_y3ycRpl4"
146
+ },
147
+ "source": []
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "execution_count": null,
152
+ "metadata": {
153
+ "cellView": "form",
154
+ "collapsed": true,
155
+ "id": "GbNRxHwgWzfF"
156
+ },
157
+ "outputs": [],
158
+ "source": [
159
+ "#@title Write samples and run `foldseek`\n",
160
+ "#@markdown - `n_write_samples`: Number of samples to randomly select for clustering. Set to `-1` to select all available samples\n",
161
+ "#@markdown - `tmscore_threshold`: TM-score threshold used for foldseek clustering\n",
162
+ "#@markdown - `coverage_threshold`: Coverage threshold used for foldseek clustering\n",
163
+ "#@markdown - `seq_id`: Sequence identity threshold used for foldseek clustering\n",
164
+ "\n",
165
+ "n_write_samples = -1 #@param {type:\"integer\"}\n",
166
+ "tmscore_threshold = 0.6 #@param {type: \"number\"}\n",
167
+ "coverage_threshold = 0.7 #@param {type: \"number\"}\n",
168
+ "seq_id = 0.95 #@param {type: \"number\"}\n",
169
+ "\n",
170
+ "import numpy as np\n",
171
+ "import mdtraj\n",
172
+ "\n",
173
+ "_py3dmol_installed_file = '/content/.py3dmol'\n",
174
+ "if not os.path.exists(_py3dmol_installed_file):\n",
175
+ " os.system('uv pip install py3Dmol')\n",
176
+ " os.system(f\"touch {_py3dmol_installed_file}\")\n",
177
+ "\n",
178
+ "import py3Dmol\n",
179
+ "pdb_sample_dir = os.path.join('/content', 'pdb_samples')\n",
180
+ "os.makedirs(pdb_sample_dir, exist_ok=True)\n",
181
+ "\n",
182
+ "def write_some_samples(topology_file: str, trajectory_file: str, output_dir:str, n_samples: int) -> None:\n",
183
+ " traj = mdtraj.load(trajectory_file, top=topology_file)\n",
184
+ " assert traj.n_frames >= n_samples\n",
185
+ " if n_samples == -1:\n",
186
+ " sample_indices = np.arange(traj.n_frames)\n",
187
+ " else:\n",
188
+ " sample_indices = np.random.choice(np.arange(traj.n_frames), size=n_samples, replace=False)\n",
189
+ " for idx in sample_indices:\n",
190
+ " traj[idx].save_pdb(os.path.join(output_dir, f'sample_{idx}.pdb'))\n",
191
+ "\n",
192
+ "\n",
193
+ "topology_file = os.path.join(output_dir, \"topology.pdb\")\n",
194
+ "trajectory_file = os.path.join(output_dir, \"samples.xtc\")\n",
195
+ "\n",
196
+ "write_some_samples(topology_file=topology_file,\n",
197
+ " trajectory_file=trajectory_file,\n",
198
+ " output_dir=pdb_sample_dir,\n",
199
+ " n_samples=n_write_samples)\n",
200
+ "\n",
201
+ "# Foldseek\n",
202
+ "import os\n",
203
+ "import subprocess\n",
204
+ "import tempfile\n",
205
+ "\n",
206
+ "import pandas as pd\n",
207
+ "\n",
208
+ "def parse_foldseek_cluster_results(cluster_table_path: str) -> dict[int, list[str]]:\n",
209
+ " \"\"\"\n",
210
+ " Parses the result of foldseek clustering\n",
211
+ "\n",
212
+ " Args:\n",
213
+ " cluster_table: path of the output cluster table from foldseek\n",
214
+ "\n",
215
+ " Returns:\n",
216
+ " Dictionary mapping cluster indices to members\n",
217
+ "\n",
218
+ " \"\"\"\n",
219
+ "\n",
220
+ " cluster_table = pd.read_csv(cluster_table_path, sep=r\"\\s+\", header=None)\n",
221
+ "\n",
222
+ " cluster_idx_to_members = {}\n",
223
+ "\n",
224
+ " for index, group in enumerate(cluster_table.groupby(0)):\n",
225
+ " cluster_idx_to_members[index] = sorted(list(group[1][1]))\n",
226
+ "\n",
227
+ " return cluster_idx_to_members\n",
228
+ "\n",
229
+ "\n",
230
+ "def foldseek_cluster(\n",
231
+ " input_dir: str,\n",
232
+ " out_prefix: str | None = None,\n",
233
+ " tmscore_threshold: float = 0.7,\n",
234
+ " coverage_threshold: float = 0.9,\n",
235
+ " seq_id: float = 0.7,\n",
236
+ " coverage_mode: int = 1,\n",
237
+ ") -> dict[int, set[str]]:\n",
238
+ " \"\"\"\n",
239
+ " Runs foldseek easy cluster\n",
240
+ "\n",
241
+ " Args:\n",
242
+ " input_dir (str): input directory with .cif or .pdb files\n",
243
+ " out_prefix (str | None): the prefix of the output files, if None a temporary directory will be used\n",
244
+ " tmscore_threshold (float): the tm-score threshold used for clustering\n",
245
+ " coverage_threshold (float): the coverage threshold used for clustering\n",
246
+ " seq_id (float): the sequence identity threshold used for clustering\n",
247
+ " coverage_mode (int): mode used by mmseqs/foldseek to compute coverage\n",
248
+ "\n",
249
+ " Returns:\n",
250
+ " Dictionary mapping cluster indices to members\n",
251
+ " \"\"\"\n",
252
+ "\n",
253
+ " with tempfile.TemporaryDirectory() as temp_dir:\n",
254
+ "\n",
255
+ " with tempfile.TemporaryDirectory() as temp_out_dir:\n",
256
+ " if out_prefix is None:\n",
257
+ " out_prefix = os.path.join(temp_out_dir, \"output\")\n",
258
+ "\n",
259
+ " res = subprocess.run(\n",
260
+ " \"/content/foldseek/bin/foldseek easy-cluster \"\n",
261
+ " + input_dir\n",
262
+ " + \" \"\n",
263
+ " + out_prefix\n",
264
+ " + \" \"\n",
265
+ " + temp_dir\n",
266
+ " + \" -c \"\n",
267
+ " + str(coverage_threshold)\n",
268
+ " + \" --min-seq-id \"\n",
269
+ " + str(seq_id)\n",
270
+ " + \" --tmscore-threshold \"\n",
271
+ " + str(tmscore_threshold)\n",
272
+ " + \" --cov-mode \"\n",
273
+ " + str(coverage_mode)\n",
274
+ " + \" --single-step-clustering\",\n",
275
+ " shell=True,\n",
276
+ " )\n",
277
+ " assert res.returncode == 0, \"Something went wrong with foldseek\"\n",
278
+ "\n",
279
+ " cluster_idx_to_members = parse_foldseek_cluster_results(out_prefix + \"_cluster.tsv\")\n",
280
+ "\n",
281
+ " return cluster_idx_to_members\n",
282
+ "\n",
283
+ "!chmod +x '/content/foldseek/bin/foldseek'\n",
284
+ "\n",
285
+ "# Get foldseek clusters\n",
286
+ "clusters = foldseek_cluster(input_dir=pdb_sample_dir, tmscore_threshold=tmscore_threshold,\n",
287
+ " coverage_threshold=coverage_threshold, seq_id=seq_id)\n",
288
+ "n_clusters = len(clusters)\n",
289
+ "print(f'{n_clusters} clusters detected')\n",
290
+ "\n",
291
+ "# Write foldseek clusters to output dir\n",
292
+ "import json\n",
293
+ "\n",
294
+ "with open(os.path.join(output_dir, 'foldseek_clusters.json'), 'w') as json_handle:\n",
295
+ " json.dump(clusters, json_handle)\n",
296
+ "\n",
297
+ "\n",
298
+ "# Write XTC with one sample per cluster only\n",
299
+ "cluster_trajs = []\n",
300
+ "for _cluster_idx, samples in clusters.items():\n",
301
+ " sample = list(samples)[0] # Choose first sample in cluster\n",
302
+ " pdb_file = os.path.join(pdb_sample_dir, f\"{sample}.pdb\")\n",
303
+ " traj = mdtraj.load_pdb(pdb_file)\n",
304
+ " cluster_trajs.append(traj)\n",
305
+ "joint_traj = mdtraj.join(cluster_trajs)\n",
306
+ "cluster_topology_file = os.path.join(output_dir, \"clustered_topology.pdb\")\n",
307
+ "cluster_trajectory_file = os.path.join(output_dir, \"clustered_samples.xtc\")\n",
308
+ "joint_traj[0].save_pdb(cluster_topology_file)\n",
309
+ "joint_traj.save_xtc(cluster_trajectory_file)\n"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "code",
314
+ "execution_count": null,
315
+ "metadata": {
316
+ "cellView": "form",
317
+ "id": "fLWzZQYAcVzr"
318
+ },
319
+ "outputs": [],
320
+ "source": [
321
+ "#@title Display structure\n",
322
+ "import os\n",
323
+ "import ipywidgets as widgets\n",
324
+ "import py3Dmol\n",
325
+ "from IPython.display import display, clear_output\n",
326
+ "\n",
327
+ "# Create interactive widgets for cluster and sample selection.\n",
328
+ "cluster_slider = widgets.IntSlider(\n",
329
+ " value=0,\n",
330
+ " min=0,\n",
331
+ " max=n_clusters - 1,\n",
332
+ " step=1,\n",
333
+ " description='Cluster No:',\n",
334
+ " continuous_update=False\n",
335
+ ")\n",
336
+ "sample_slider = widgets.IntSlider(\n",
337
+ " value=0,\n",
338
+ " min=0,\n",
339
+ " max=0, # will update based on the selected cluster\n",
340
+ " step=1,\n",
341
+ " description='Sample Idx:',\n",
342
+ " continuous_update=False\n",
343
+ ")\n",
344
+ "display(cluster_slider, sample_slider)\n",
345
+ "\n",
346
+ "# Function to visualize a PDB file using py3Dmol.\n",
347
+ "def show_pdb(pdb_file: str, show_sidechains: bool = False, show_mainchains: bool = True):\n",
348
+ " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js')\n",
349
+ " try:\n",
350
+ " with open(pdb_file, 'r') as f:\n",
351
+ " pdb_content = f.read()\n",
352
+ " except FileNotFoundError:\n",
353
+ " print(f\"File not found: {pdb_file}\")\n",
354
+ " return None\n",
355
+ " view.addModel(pdb_content, 'pdb')\n",
356
+ " view.setStyle({'cartoon': {'color': 'spectrum'}})\n",
357
+ "\n",
358
+ " if show_sidechains:\n",
359
+ " BB = ['C', 'O', 'N']\n",
360
+ " view.addStyle({'and': [{'resn': [\"GLY\", \"PRO\"], 'invert': True}, {'atom': BB, 'invert': True}]},\n",
361
+ " {'stick': {'colorscheme': \"WhiteCarbon\", 'radius': 0.3}})\n",
362
+ " view.addStyle({'and': [{'resn': \"GLY\"}, {'atom': 'CA'}]},\n",
363
+ " {'sphere': {'colorscheme': \"WhiteCarbon\", 'radius': 0.3}})\n",
364
+ " view.addStyle({'and': [{'resn': \"PRO\"}, {'atom': ['C', 'O'], 'invert': True}]},\n",
365
+ " {'stick': {'colorscheme': \"WhiteCarbon\", 'radius': 0.3}})\n",
366
+ " if show_mainchains:\n",
367
+ " BB = ['C', 'O', 'N', 'CA']\n",
368
+ " view.addStyle({'atom': BB}, {'stick': {'colorscheme': \"WhiteCarbon\", 'radius': 0.3}})\n",
369
+ "\n",
370
+ " view.zoomTo()\n",
371
+ " return view\n",
372
+ "\n",
373
+ "# Helper to update the sample slider's maximum value based on the selected cluster.\n",
374
+ "def update_sample_slider(cluster_no):\n",
375
+ " available_samples = list(clusters[cluster_no])\n",
376
+ " sample_slider.max = max(len(available_samples) - 1, 0)\n",
377
+ " # Reset sample_slider's value if it's out of range.\n",
378
+ " if sample_slider.value > sample_slider.max:\n",
379
+ " sample_slider.value = 0\n",
380
+ "\n",
381
+ "# Main function to update the viewer whenever widget values change.\n",
382
+ "def update_view(change=None):\n",
383
+ " cluster_no = cluster_slider.value\n",
384
+ " update_sample_slider(cluster_no)\n",
385
+ " available_samples = list(clusters[cluster_no])\n",
386
+ " sample_idx = sample_slider.value\n",
387
+ "\n",
388
+ " clear_output(wait=True)\n",
389
+ " display(cluster_slider, sample_slider)\n",
390
+ "\n",
391
+ " if sample_idx >= len(available_samples):\n",
392
+ " print(f\"Only {len(available_samples)} samples available in cluster {cluster_no}\")\n",
393
+ " return\n",
394
+ "\n",
395
+ " chosen_sample = available_samples[sample_idx]\n",
396
+ " pdb_path = os.path.join(\"pdb_samples\", f\"{chosen_sample}.pdb\")\n",
397
+ "\n",
398
+ " # Check if the file exists before attempting to open it.\n",
399
+ " if not os.path.exists(pdb_path):\n",
400
+ " print(f\"File not found: {pdb_path}\")\n",
401
+ " return\n",
402
+ "\n",
403
+ " print(f\"Displaying sample {sample_idx} from cluster {cluster_no}\")\n",
404
+ " view = show_pdb(pdb_path)\n",
405
+ " if view:\n",
406
+ " view.show()\n",
407
+ "\n",
408
+ "# Observe changes to the slider values.\n",
409
+ "cluster_slider.observe(update_view, names='value')\n",
410
+ "sample_slider.observe(update_view, names='value')\n",
411
+ "\n",
412
+ "# Trigger an initial update.\n",
413
+ "update_view()\n"
414
+ ]
415
+ },
416
+ {
417
+ "cell_type": "code",
418
+ "execution_count": null,
419
+ "metadata": {
420
+ "id": "O5EhJTP3tzcJ",
421
+ "cellView": "form"
422
+ },
423
+ "outputs": [],
424
+ "source": [
425
+ "#@title (Optional) Reconstruct sidechains + Run MD relaxation\n",
426
+ "#@markdown - `reconstruct_sidechains`: whether to reconstruct sidechains via `hpacker`\n",
427
+ "#@markdown - `run_md`: check to run MD after sidechain reconstruction, otherwise only sidechain reconstruction is performed\n",
428
+ "#@markdown - `md_protocol`: `LOCAL_MINIMIZATION`: fast but only resolves local problems ; `NVT_EQUIL`: slow but might resolve more severe issues\n",
429
+ "#@markdown - `one_per_cluster`: Reconstruct sidechains / optionally run MD for only one sample within each foldseek cluster\n",
430
+ "\n",
431
+ "#@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",
432
+ "\n",
433
+ "\n",
434
+ "reconstruct_sidechains = True #@param {type: \"boolean\"}\n",
435
+ "run_md = True #@param {type:\"boolean\"}\n",
436
+ "one_per_cluster = True #@param {type:\"boolean\"}\n",
437
+ "md_protocol = \"LOCAL_MINIMIZATION\" #@param [\"LOCAL_MINIMIZATION\", \"NVT_EQUIL\"] {type:\"string\"}\n",
438
+ "import bioemu.sidechain_relax\n",
439
+ "bioemu.sidechain_relax.HPACKER_PYTHONBIN = os.path.join(conda_prefix, '/envs/hpacker/bin/python')\n",
440
+ "\n",
441
+ "from bioemu.sidechain_relax import main as sidechainrelax\n",
442
+ "from bioemu.sidechain_relax import MDProtocol\n",
443
+ "md_protocol = MDProtocol[md_protocol]\n",
444
+ "os.environ['CONDA_PREFIX_1'] = conda_prefix\n",
445
+ "\n",
446
+ "if one_per_cluster:\n",
447
+ " topology_file = cluster_topology_file\n",
448
+ " trajectory_file = cluster_trajectory_file\n",
449
+ "\n",
450
+ "prefix = 'hpacker-openmm'\n",
451
+ "if reconstruct_sidechains:\n",
452
+ " relaxed_dir = os.path.join(output_dir, prefix)\n",
453
+ " os.makedirs(relaxed_dir, exist_ok=True)\n",
454
+ " sidechainrelax(pdb_path=topology_file, xtc_path=trajectory_file,\n",
455
+ " outpath=relaxed_dir, prefix=prefix, md_protocol=md_protocol,\n",
456
+ " md_equil=run_md)\n",
457
+ " if run_md:\n",
458
+ " os.system(f'touch {relaxed_dir}/.RELAXED')\n"
459
+ ]
460
+ }
461
+ ],
462
+ "metadata": {
463
+ "accelerator": "GPU",
464
+ "colab": {
465
+ "gpuType": "T4",
466
+ "provenance": []
467
+ },
468
+ "kernelspec": {
469
+ "display_name": "Python 3",
470
+ "name": "python3"
471
+ },
472
+ "language_info": {
473
+ "name": "python"
474
+ }
475
+ },
476
+ "nbformat": 4,
477
+ "nbformat_minor": 0
478
+ }
data/Boltz1.ipynb ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "machine_shape": "hm",
8
+ "gpuType": "T4",
9
+ "include_colab_link": true
10
+ },
11
+ "kernelspec": {
12
+ "name": "python3",
13
+ "display_name": "Python 3"
14
+ },
15
+ "language_info": {
16
+ "name": "python"
17
+ },
18
+ "accelerator": "GPU"
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {
24
+ "id": "view-in-github",
25
+ "colab_type": "text"
26
+ },
27
+ "source": [
28
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/Boltz1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "source": [
34
+ "# This is a work-in-progress notebook for [Boltz](https://github.com/jwohlwend/boltz)\n",
35
+ "\n",
36
+ "⚠️ **Warning to Users:**\n",
37
+ "- **Alpha Version:** This notebook is currently under active development and is considered a beta version.\n",
38
+ "- **Usage at Your Own Risk:** Use this notebook at your own discretion and risk."
39
+ ],
40
+ "metadata": {
41
+ "id": "KNOrLaJFdiA-"
42
+ }
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "source": [
47
+ "#@title Input protein sequence(s), then hit `Runtime` -> `Run all`\n",
48
+ "from google.colab import files\n",
49
+ "import os\n",
50
+ "import re\n",
51
+ "import hashlib\n",
52
+ "import random\n",
53
+ "import requests\n",
54
+ "from string import ascii_uppercase\n",
55
+ "\n",
56
+ "# Function to add a hash to the jobname\n",
57
+ "def add_hash(x, y):\n",
58
+ " return x + \"_\" + hashlib.sha1(y.encode()).hexdigest()[:5]\n",
59
+ "\n",
60
+ "# User inputs\n",
61
+ "query_sequence = 'PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASKK' #@param {type:\"string\"}\n",
62
+ "#@markdown - Use `:` to specify inter-protein chainbreaks for **modeling complexes** (supports homo- and hetro-oligomers). For example **PI...SK:PI...SK** for a homodimer\n",
63
+ "ligand_input = 'N[C@@H](Cc1ccc(O)cc1)C(=O)O' #@param {type:\"string\"}\n",
64
+ "#@markdown - Use `:` to specify multiple ligands as smile strings\n",
65
+ "ligand_input_ccd = 'SAH' #@param {type:\"string\"}\n",
66
+ "#@markdown - Use `:` to specify multiple ligands as CCD codes (three-letter codes)\n",
67
+ "ligand_input_common_name = '' #@param {type:\"string\"}\n",
68
+ "#@markdown - Use `:` to specify multiple ligands with their common name (e.g. Aspirin; SMILES fetched from [PubChem](https://pubchem.ncbi.nlm.nih.gov) API)\n",
69
+ "dna_input = '' #@param {type:\"string\"}\n",
70
+ "#@markdown - Use `:` to specify multiple DNA sequences\n",
71
+ "jobname = 'test' #@param {type:\"string\"}\n",
72
+ "\n",
73
+ "# Clean up the query sequence and jobname\n",
74
+ "query_sequence = \"\".join(query_sequence.split())\n",
75
+ "ligand_input = \"\".join(ligand_input.split())\n",
76
+ "ligand_input_ccd = \"\".join(ligand_input_ccd.split())\n",
77
+ "ligand_input_common_name = \"\".join(ligand_input_common_name.split())\n",
78
+ "dna_input = \"\".join(dna_input.split())\n",
79
+ "basejobname = \"\".join(jobname.split())\n",
80
+ "basejobname = re.sub(r'\\W+', '', basejobname)\n",
81
+ "jobname = add_hash(basejobname, query_sequence)\n",
82
+ "\n",
83
+ "# Check if a directory with jobname exists\n",
84
+ "def check(folder):\n",
85
+ " return not os.path.exists(folder)\n",
86
+ "\n",
87
+ "if not check(jobname):\n",
88
+ " n = 0\n",
89
+ " while not check(f\"{jobname}_{n}\"):\n",
90
+ " n += 1\n",
91
+ " jobname = f\"{jobname}_{n}\"\n",
92
+ "\n",
93
+ "# Make directory to save results\n",
94
+ "os.makedirs(jobname, exist_ok=True)\n",
95
+ "\n",
96
+ "from string import ascii_uppercase\n",
97
+ "\n",
98
+ "# Split sequences on chain breaks\n",
99
+ "protein_sequences = query_sequence.strip().split(':') if query_sequence.strip() else []\n",
100
+ "ligand_sequences = ligand_input.strip().split(':') if ligand_input.strip() else []\n",
101
+ "ligand_sequences_ccd = ligand_input_ccd.strip().split(':') if ligand_input_ccd.strip() else []\n",
102
+ "ligand_sequences_common_name = ligand_input_common_name.strip().split(':') if ligand_input_common_name.strip() else []\n",
103
+ "dna_sequences = dna_input.strip().split(':') if dna_input.strip() else []\n",
104
+ "\n",
105
+ "def get_smiles(compound_name):\n",
106
+ " autocomplete_url = f\"https://pubchem.ncbi.nlm.nih.gov/rest/autocomplete/compound/{compound_name}/json?limit=1\"\n",
107
+ " autocomplete_response = requests.get(autocomplete_url)\n",
108
+ " if autocomplete_response.status_code != 200:\n",
109
+ " return None\n",
110
+ "\n",
111
+ " autocomplete_data = autocomplete_response.json()\n",
112
+ " if autocomplete_data.get(\"status\", {}).get(\"code\") != 0 or autocomplete_data.get(\"total\", 0) == 0:\n",
113
+ " return None\n",
114
+ "\n",
115
+ " suggested_compound = autocomplete_data.get(\"dictionary_terms\", {}).get(\"compound\", [])\n",
116
+ " if not suggested_compound:\n",
117
+ " return None\n",
118
+ " suggested_compound_name = suggested_compound[0]\n",
119
+ "\n",
120
+ " smiles_url = f\"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{suggested_compound_name}/property/CanonicalSMILES/JSON\"\n",
121
+ " smiles_response = requests.get(smiles_url)\n",
122
+ " if smiles_response.status_code != 200:\n",
123
+ " return None\n",
124
+ "\n",
125
+ " smiles_data = smiles_response.json()\n",
126
+ " properties = smiles_data.get(\"PropertyTable\", {}).get(\"Properties\", [])\n",
127
+ " if len(properties) == 0:\n",
128
+ " return None\n",
129
+ "\n",
130
+ " return properties[0].get(\"CanonicalSMILES\")\n",
131
+ "\n",
132
+ "smiles_cache = {}\n",
133
+ "for name in ligand_sequences_common_name:\n",
134
+ " if name not in smiles_cache:\n",
135
+ " smiles_cache[name] = get_smiles(name)\n",
136
+ " if smiles_cache[name] is not None:\n",
137
+ " print(f\"Mapped compound {name} to {smiles_cache[name]}\")\n",
138
+ "\n",
139
+ " if smiles_cache[name] is not None:\n",
140
+ " ligand_sequences.append(smiles_cache[name])\n",
141
+ "\n",
142
+ "# Initialize chain labels starting from 'A'\n",
143
+ "chain_labels = iter(ascii_uppercase)\n",
144
+ "\n",
145
+ "fasta_entries = []\n",
146
+ "csv_entries = []\n",
147
+ "chain_label_to_seq_id = {}\n",
148
+ "seq_to_seq_id = {}\n",
149
+ "seq_id_counter = 0 # Counter for unique sequences\n",
150
+ "\n",
151
+ "# Process protein sequences\n",
152
+ "for seq in protein_sequences:\n",
153
+ " seq = seq.strip()\n",
154
+ " if not seq:\n",
155
+ " continue # Skip empty sequences\n",
156
+ " chain_label = next(chain_labels)\n",
157
+ " # Check if sequence has been seen before\n",
158
+ " if seq in seq_to_seq_id:\n",
159
+ " seq_id = seq_to_seq_id[seq]\n",
160
+ " else:\n",
161
+ " seq_id = f\"{jobname}_{seq_id_counter}\"\n",
162
+ " seq_to_seq_id[seq] = seq_id\n",
163
+ " seq_id_counter += 1\n",
164
+ " # For CSV file (for ColabFold), add only unique sequences\n",
165
+ " csv_entries.append((seq_id, seq))\n",
166
+ " chain_label_to_seq_id[chain_label] = seq_id\n",
167
+ " # For FASTA file\n",
168
+ " msa_path = os.path.join(jobname, f\"{seq_id}.a3m\")\n",
169
+ " header = f\">{chain_label}|protein|{msa_path}\"\n",
170
+ " sequence = seq\n",
171
+ " fasta_entries.append((header, sequence))\n",
172
+ "\n",
173
+ "# Process ligand sequences (assumed to be SMILES strings)\n",
174
+ "for lig in ligand_sequences:\n",
175
+ " lig = lig.strip()\n",
176
+ " if not lig:\n",
177
+ " continue # Skip empty ligands\n",
178
+ " chain_label = next(chain_labels)\n",
179
+ " lig_type = 'smiles'\n",
180
+ " header = f\">{chain_label}|{lig_type}\"\n",
181
+ " sequence = lig\n",
182
+ " fasta_entries.append((header, sequence))\n",
183
+ "\n",
184
+ "# Process DNA sequences (NO MSA is generated)\n",
185
+ "for seq in dna_sequences:\n",
186
+ " seq = seq.strip()\n",
187
+ " if not seq:\n",
188
+ " continue # Skip empty sequences\n",
189
+ " chain_label = next(chain_labels)\n",
190
+ " lig_type = 'DNA'\n",
191
+ " header = f\">{chain_label}|{lig_type}\"\n",
192
+ " sequence = seq\n",
193
+ " fasta_entries.append((header, sequence))\n",
194
+ "\n",
195
+ "# Process ligand sequences (CCD codes)\n",
196
+ "for lig in ligand_sequences_ccd:\n",
197
+ " lig = lig.strip()\n",
198
+ " if not lig:\n",
199
+ " continue # Skip empty ligands\n",
200
+ " chain_label = next(chain_labels)\n",
201
+ " lig_type = 'ccd'\n",
202
+ " header = f\">{chain_label}|{lig_type}\"\n",
203
+ " sequence = lig.upper() # Ensure CCD codes are uppercase\n",
204
+ " fasta_entries.append((header, sequence))\n",
205
+ "\n",
206
+ "# Write the CSV file for ColabFold\n",
207
+ "queries_path = os.path.join(jobname, f\"{jobname}.csv\")\n",
208
+ "with open(queries_path, \"w\") as text_file:\n",
209
+ " text_file.write(\"id,sequence\\n\")\n",
210
+ " for seq_id, seq in csv_entries:\n",
211
+ " text_file.write(f\"{seq_id},{seq}\\n\")\n",
212
+ "\n",
213
+ "# Write the FASTA file\n",
214
+ "queries_fasta = os.path.join(jobname, f\"{jobname}.fasta\")\n",
215
+ "with open(queries_fasta, 'w') as f:\n",
216
+ " for header, sequence in fasta_entries:\n",
217
+ " f.write(f\"{header}\\n{sequence}\\n\")\n",
218
+ "\n",
219
+ "# Optionally, print the output for verification\n",
220
+ "#print(f\"Generated FASTA file '{queries_fasta}':\\n\")\n",
221
+ "#for header, sequence in fasta_entries:\n",
222
+ "# print(f\"{header}\\n{sequence}\\n\")\n"
223
+ ],
224
+ "metadata": {
225
+ "cellView": "form",
226
+ "id": "AcYvVeDESi2a"
227
+ },
228
+ "execution_count": null,
229
+ "outputs": []
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "execution_count": null,
234
+ "metadata": {
235
+ "cellView": "form",
236
+ "id": "4eXNO1JJHYrB"
237
+ },
238
+ "outputs": [],
239
+ "source": [
240
+ "#@title Install dependencies\n",
241
+ "%%time\n",
242
+ "import os\n",
243
+ "if not os.path.isfile(\"COLABFOLD_READY\"):\n",
244
+ " print(\"installing colabfold...\")\n",
245
+ " os.system(\"pip install -q --no-warn-conflicts 'colabfold[alphafold-minus-jax] @ git+https://github.com/sokrypton/ColabFold'\")\n",
246
+ " if os.environ.get('TPU_NAME', False) != False:\n",
247
+ " os.system(\"pip uninstall -y jax jaxlib\")\n",
248
+ " os.system(\"pip install --no-warn-conflicts --upgrade dm-haiku==0.0.10 'jax[cuda12_pip]'==0.3.25 -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html\")\n",
249
+ " os.system(\"ln -s /usr/local/lib/python3.*/dist-packages/colabfold colabfold\")\n",
250
+ " os.system(\"ln -s /usr/local/lib/python3.*/dist-packages/alphafold alphafold\")\n",
251
+ " # hack to fix TF crash\n",
252
+ " os.system(\"rm -f /usr/local/lib/python3.*/dist-packages/tensorflow/core/kernels/libtfkernel_sobol_op.so /usr/local/lib/python3.*/dist-packages/tensorflow/lite/python/*/*.so\")\n",
253
+ " os.system(\"touch COLABFOLD_READY\")\n",
254
+ "\n",
255
+ "if not os.path.isfile(\"BOLZ_READY\"):\n",
256
+ " os.system(\"apt-get install -y aria2\")\n",
257
+ " os.system(\"pip install -q --no-warn-conflicts boltz\")\n",
258
+ " os.system(\"mkdir weights\")\n",
259
+ " os.system(\"aria2c -d weights -x8 -s8 https://colabfold.steineggerlab.workers.dev/boltz1.ckpt\")\n",
260
+ " os.system(\"aria2c -d weights -x8 -s8 https://colabfold.steineggerlab.workers.dev/ccd.pkl\")\n",
261
+ " os.system(\"touch BOLZ_READY\")"
262
+ ]
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "source": [
267
+ "#@title Generate MSA with ColabFold\n",
268
+ "!colabfold_batch \"{queries_path}\" \"{jobname}\" --msa-only"
269
+ ],
270
+ "metadata": {
271
+ "cellView": "form",
272
+ "id": "4aFDR4IhRe6y"
273
+ },
274
+ "execution_count": null,
275
+ "outputs": []
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "source": [
280
+ "#@title Predict structure using boltz\n",
281
+ "!boltz predict --out_dir \"{jobname}\" \"{jobname}/{jobname}.fasta\" --cache weights"
282
+ ],
283
+ "metadata": {
284
+ "cellView": "form",
285
+ "id": "bgaBXxXtIAu9"
286
+ },
287
+ "execution_count": null,
288
+ "outputs": []
289
+ },
290
+ {
291
+ "cell_type": "code",
292
+ "source": [
293
+ "#@title Download results\n",
294
+ "# Import necessary modules\n",
295
+ "import os\n",
296
+ "import zipfile\n",
297
+ "from google.colab import files\n",
298
+ "import glob\n",
299
+ "\n",
300
+ "# Ensure 'jobname' variable is defined\n",
301
+ "# jobname = 'test_abcde' # Uncomment and set if not already defined\n",
302
+ "\n",
303
+ "# Name of the zip file\n",
304
+ "zip_filename = f\"results_{jobname}.zip\"\n",
305
+ "\n",
306
+ "# Create a zip file and add the specified files without preserving directory structure\n",
307
+ "with zipfile.ZipFile(zip_filename, 'w') as zipf:\n",
308
+ " coverage_png_files = glob.glob(os.path.join(jobname, '*_coverage.png'))\n",
309
+ " a3m_files = glob.glob(os.path.join(jobname, '*.a3m'))\n",
310
+ " for file in coverage_png_files + a3m_files:\n",
311
+ " arcname = os.path.basename(file) # Use only the file name\n",
312
+ " zipf.write(file, arcname=arcname)\n",
313
+ "\n",
314
+ " cif_files = glob.glob(os.path.join(jobname, f'boltz_results_{jobname}', 'predictions', jobname, '*.cif'))\n",
315
+ " for file in cif_files:\n",
316
+ " arcname = os.path.basename(file) # Use only the file name\n",
317
+ " zipf.write(file, arcname=arcname)\n",
318
+ "\n",
319
+ " hparams_file = os.path.join(jobname, f'boltz_results_{jobname}', 'lightning_logs', 'version_0', 'hparams.yaml')\n",
320
+ " if os.path.exists(hparams_file):\n",
321
+ " arcname = os.path.basename(hparams_file) # Use only the file name\n",
322
+ " zipf.write(hparams_file, arcname=arcname)\n",
323
+ " else:\n",
324
+ " print(f\"Warning: {hparams_file} not found.\")\n",
325
+ "\n",
326
+ "# Download the zip file\n",
327
+ "files.download(zip_filename)\n"
328
+ ],
329
+ "metadata": {
330
+ "cellView": "form",
331
+ "id": "jdSBSTOpaULF"
332
+ },
333
+ "execution_count": null,
334
+ "outputs": []
335
+ }
336
+ ]
337
+ }
data/Contributing.md ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to colabfold and our alphafold fork
2
+
3
+ Install poetry (once per machine). Please consult the [poetry docs](https://python-poetry.org/docs/), they are well written:
4
+
5
+ ```shell
6
+ curl -sSL https://install.python-poetry.org | python3 -
7
+ poetry config virtualenvs.in-project true
8
+ ```
9
+
10
+ Clone and install the dependencies:
11
+
12
+ ```shell
13
+ git clone https://github.com/sokrypton/ColabFold
14
+ cd ColabFold
15
+ poetry install -E alphafold
16
+ ```
17
+
18
+ Activate the environment (everytime you want to run some python or install something):
19
+
20
+ ```shell
21
+ source .venv/bin/activate
22
+ ```
23
+
24
+ Install jax; You need to repeat after every `poetry install`/`poetry lock`/`poetry update` unfortunately:
25
+
26
+ ```shell
27
+ pip install -q "jax[cuda]>=0.3.8,<0.4" -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html
28
+ ```
29
+
30
+ If you also want to modify our alphafold fork
31
+
32
+ ```shell
33
+ git clone https://github.com/steineggerlab/alphafold
34
+ pip install -e alphafold
35
+ ```
36
+
37
+ ## Edit a dependency
38
+
39
+ Edit the corresponding `pyproject.toml`, then run `poetry lock --no-update` in the directory of the `pyproject.toml`.
40
+
41
+ ## Edit colabfold
42
+
43
+ You can run the tests with
44
+
45
+ ```
46
+ pytest tests
47
+ ```
48
+
49
+ ## Edit alphafold
50
+
51
+ * switch to the alphafold folder
52
+ * Make edits to alphafold
53
+ * With the `pip install -e` install, you can directly test them in colabfold
54
+ * Set the last digit of `version=` in setup.py one higher, e.g. to `2.1.1234`
55
+ * git commit and push as usual
56
+ * `git tag v2.1.1234 -m v2.1.1234`, make sure it's the correct number (if you don't have permission, ask one of the team to push the tag)
57
+ * `git push --tags`
58
+ * In colabfold: update the number of `alphafold-colabfold = { version = "` in pyproject.toml, commit and push
59
+
60
+ # Colab dev setup
61
+
62
+ While it's generally easier to edit locally, you can also test and develop directly in google colab.
63
+
64
+ We clone to _directory to avoid python from importing from the directory.
65
+
66
+ ```
67
+ %%bash
68
+
69
+ pip install -U pip
70
+ git clone https://github.com/sokrypton/Colabfold _colabfold
71
+ pip install _colabfold
72
+ # Unholy Hack: Use the files from our cloned git repository instead of installed copy
73
+ site_packages=$(python -c 'import site; print(site.getsitepackages()[0])')
74
+ rm -r ${site_packages}/colabfold
75
+ ln -s $(pwd)/_colabfold/colabfold ${site_packages}/colabfold
76
+ ```
77
+
78
+ If you also need to patch alphafold:
79
+
80
+ ```
81
+ %%bash
82
+
83
+ pip uninstall -y alphafold
84
+ git clone https://github.com/sokrypton/alphafold _alphafold
85
+ pip install -e ./_alphafold
86
+ ```
87
+
88
+ After that, restart the runtime.
89
+
90
+ When you changed a file in the `colabfold` package, you need to reload the modules you were using with `importlib.reload()`, e.g.
91
+
92
+ ```python
93
+ import colabfold.batch
94
+ import importlib
95
+
96
+ importlib.reload(colabfold.batch)
97
+ ```
98
+
data/Dockerfile ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG MMSEQS_HASH=archive/8cc5ce367b5638c4306c2d7cfc652dd099a4643f
2
+ ARG downloader=${TARGETARCH}_downloader
3
+
4
+ FROM scratch AS amd64_downloader
5
+ ARG MMSEQS_HASH
6
+ WORKDIR /opt/build
7
+ ONBUILD ADD https://mmseqs.com/${MMSEQS_HASH}/mmseqs-linux-gpu.tar.gz .
8
+
9
+ FROM scratch AS arm64_downloader
10
+ ARG MMSEQS_HASH
11
+ WORKDIR /opt/build
12
+ ONBUILD ADD https://mmseqs.com/${MMSEQS_HASH}/mmseqs-linux-gpu-arm64.tar.gz .
13
+
14
+ FROM $downloader AS downloader
15
+
16
+ FROM debian:trixie-slim AS builder
17
+ WORKDIR /opt/build
18
+ COPY --from=downloader /opt/build/* .
19
+ RUN mkdir binaries; \
20
+ for i in *.tar.gz; do \
21
+ if [ -e ${i} ]; then \
22
+ tar -xzvf ${i}; \
23
+ mv -f -- */bin/* binaries/; \
24
+ fi; \
25
+ done; \
26
+ chmod -R +x binaries;
27
+
28
+ FROM debian:trixie-slim
29
+
30
+ VOLUME cache
31
+ ENV MPLBACKEND=Agg
32
+ ENV MPLCONFIGDIR=/cache
33
+ ENV XDG_CACHE_HOME=/cache
34
+ ENV CONDA_VERSION=25.9.1-0
35
+
36
+ RUN apt-get update; \
37
+ apt-get install -y wget git --no-install-suggests; \
38
+ rm -rf /var/lib/apt/lists/*;
39
+
40
+ SHELL ["/bin/bash", "--login", "-x", "-c"]
41
+ RUN wget -qnc https://github.com/conda-forge/miniforge/releases/download/${CONDA_VERSION}/Miniforge3-${CONDA_VERSION}-Linux-x86_64.sh; \
42
+ bash Miniforge3-${CONDA_VERSION}-Linux-x86_64.sh -bfp /usr/local; \
43
+ conda config --set auto_update_conda false; \
44
+ rm -f Miniforge3-${CONDA_VERSION}-Linux-x86_64.sh; \
45
+ conda install -y -c conda-forge -c bioconda kalign2=2.04 hhsuite=3.3.0; \
46
+ conda clean -afy; \
47
+ conda shell.bash hook;
48
+ COPY --from=builder /opt/build/binaries/* /usr/local/bin/
49
+
50
+ WORKDIR /app
51
+ COPY . /app
52
+ RUN pip install --no-cache-dir \
53
+ ".[alphafold,openmm]" \
54
+ "jax[cuda]<0.8" \
55
+ "openmm[cuda12]"; \
56
+ rm -rf /root/.cache/pip
data/ESMFold.ipynb ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "include_colab_link": true
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "language_info": {
14
+ "name": "python"
15
+ },
16
+ "accelerator": "GPU",
17
+ "gpuClass": "standard"
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {
23
+ "id": "view-in-github",
24
+ "colab_type": "text"
25
+ },
26
+ "source": [
27
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/ESMFold.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "markdown",
32
+ "source": [
33
+ "#**ESMFold**\n",
34
+ "for more details see: [Github](https://github.com/facebookresearch/esm/tree/main/esm), [Preprint](https://www.biorxiv.org/content/10.1101/2022.07.20.500902v1)\n",
35
+ "\n",
36
+ "#### **Tips and Instructions**\n",
37
+ "- click the little ▶ play icon to the left of each cell below.\n",
38
+ "- use \"/\" to specify chainbreaks, (eg. sequence=\"AAA/AAA\")\n",
39
+ "- for homo-oligomeric predictions, set copies > 1\n",
40
+ "- See [experimental notebook](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/ESMFold_advanced.ipynb) for more advanced options (like sampling).\n",
41
+ "\n",
42
+ "#### **Colab Limitations**\n",
43
+ "- For short monomeric proteins under the length 400, consider using [ESMFold API](https://esmatlas.com/resources?action=fold) (no need for GPU, super fast!)\n",
44
+ "- On Tesla T4 (typical free colab GPU), max total length ~ 900"
45
+ ],
46
+ "metadata": {
47
+ "id": "POQBeXf2Xoxo"
48
+ }
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "execution_count": null,
53
+ "metadata": {
54
+ "cellView": "form",
55
+ "id": "boFQEwsNQ4Qt"
56
+ },
57
+ "outputs": [],
58
+ "source": [
59
+ "%%time\n",
60
+ "#@title install\n",
61
+ "#@markdown install ESMFold, OpenFold and download Params (~2min 30s)\n",
62
+ "version = \"1\" # @param [\"0\", \"1\"]\n",
63
+ "model_name = \"esmfold_v0.model\" if version == \"0\" else \"esmfold.model\"\n",
64
+ "import os, time\n",
65
+ "if not os.path.isfile(model_name):\n",
66
+ " # download esmfold params\n",
67
+ " os.system(\"apt-get install aria2 -qq\")\n",
68
+ " os.system(f\"aria2c -q -x 16 https://colabfold.steineggerlab.workers.dev/esm/{model_name} &\")\n",
69
+ "\n",
70
+ " if not os.path.isfile(\"finished_install\"):\n",
71
+ " # install libs\n",
72
+ " print(\"installing libs...\")\n",
73
+ " os.system(\"pip install -q omegaconf pytorch_lightning biopython ml_collections einops py3Dmol modelcif\")\n",
74
+ " os.system(\"pip install -q git+https://github.com/NVIDIA/dllogger.git\")\n",
75
+ "\n",
76
+ " print(\"installing openfold...\")\n",
77
+ " # install openfold\n",
78
+ " os.system(f\"pip install -q git+https://github.com/sokrypton/openfold.git\")\n",
79
+ "\n",
80
+ " print(\"installing esmfold...\")\n",
81
+ " # install esmfold\n",
82
+ " os.system(f\"pip install -q git+https://github.com/sokrypton/esm.git\")\n",
83
+ " os.system(\"touch finished_install\")\n",
84
+ "\n",
85
+ " # wait for Params to finish downloading...\n",
86
+ " while not os.path.isfile(model_name):\n",
87
+ " time.sleep(5)\n",
88
+ " if os.path.isfile(f\"{model_name}.aria2\"):\n",
89
+ " print(\"downloading params...\")\n",
90
+ " while os.path.isfile(f\"{model_name}.aria2\"):\n",
91
+ " time.sleep(5)"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "source": [
97
+ "#@title ##run **ESMFold**\n",
98
+ "%%time\n",
99
+ "from string import ascii_uppercase, ascii_lowercase\n",
100
+ "import hashlib, re, os\n",
101
+ "import numpy as np\n",
102
+ "import torch\n",
103
+ "from jax.tree_util import tree_map\n",
104
+ "import matplotlib.pyplot as plt\n",
105
+ "from scipy.special import softmax\n",
106
+ "import gc\n",
107
+ "\n",
108
+ "def parse_output(output):\n",
109
+ " pae = (output[\"aligned_confidence_probs\"][0] * np.arange(64)).mean(-1) * 31\n",
110
+ " plddt = output[\"plddt\"][0,:,1]\n",
111
+ "\n",
112
+ " bins = np.append(0,np.linspace(2.3125,21.6875,63))\n",
113
+ " sm_contacts = softmax(output[\"distogram_logits\"],-1)[0]\n",
114
+ " sm_contacts = sm_contacts[...,bins<8].sum(-1)\n",
115
+ " xyz = output[\"positions\"][-1,0,:,1]\n",
116
+ " mask = output[\"atom37_atom_exists\"][0,:,1] == 1\n",
117
+ " o = {\"pae\":pae[mask,:][:,mask],\n",
118
+ " \"plddt\":plddt[mask],\n",
119
+ " \"sm_contacts\":sm_contacts[mask,:][:,mask],\n",
120
+ " \"xyz\":xyz[mask]}\n",
121
+ " return o\n",
122
+ "\n",
123
+ "def get_hash(x): return hashlib.sha1(x.encode()).hexdigest()\n",
124
+ "alphabet_list = list(ascii_uppercase+ascii_lowercase)\n",
125
+ "\n",
126
+ "jobname = \"test\" #@param {type:\"string\"}\n",
127
+ "jobname = re.sub(r'\\W+', '', jobname)[:50]\n",
128
+ "\n",
129
+ "sequence = \"GWSTELEKHREELKEFLKKEGITNVEIRIDNGRLEVRVEGGTERLKRFLEELRQKLEKKGYTVDIKIE\" #@param {type:\"string\"}\n",
130
+ "sequence = re.sub(\"[^A-Z:]\", \"\", sequence.replace(\"/\",\":\").upper())\n",
131
+ "sequence = re.sub(\":+\",\":\",sequence)\n",
132
+ "sequence = re.sub(\"^[:]+\",\"\",sequence)\n",
133
+ "sequence = re.sub(\"[:]+$\",\"\",sequence)\n",
134
+ "copies = 1 #@param {type:\"integer\"}\n",
135
+ "if copies == \"\" or copies <= 0: copies = 1\n",
136
+ "sequence = \":\".join([sequence] * copies)\n",
137
+ "num_recycles = 3 #@param [\"0\", \"1\", \"2\", \"3\", \"6\", \"12\", \"24\"] {type:\"raw\"}\n",
138
+ "chain_linker = 25\n",
139
+ "\n",
140
+ "ID = jobname+\"_\"+get_hash(sequence)[:5]\n",
141
+ "seqs = sequence.split(\":\")\n",
142
+ "lengths = [len(s) for s in seqs]\n",
143
+ "length = sum(lengths)\n",
144
+ "print(\"length\",length)\n",
145
+ "\n",
146
+ "u_seqs = list(set(seqs))\n",
147
+ "if len(seqs) == 1: mode = \"mono\"\n",
148
+ "elif len(u_seqs) == 1: mode = \"homo\"\n",
149
+ "else: mode = \"hetero\"\n",
150
+ "\n",
151
+ "if \"model\" not in dir() or model_name != model_name_:\n",
152
+ " if \"model\" in dir():\n",
153
+ " # delete old model from memory\n",
154
+ " del model\n",
155
+ " gc.collect()\n",
156
+ " if torch.cuda.is_available():\n",
157
+ " torch.cuda.empty_cache()\n",
158
+ "\n",
159
+ " model = torch.load(model_name, weights_only=False)\n",
160
+ " model.eval().cuda().requires_grad_(False)\n",
161
+ " model_name_ = model_name\n",
162
+ "\n",
163
+ "# optimized for Tesla T4\n",
164
+ "if length > 700:\n",
165
+ " model.set_chunk_size(64)\n",
166
+ "else:\n",
167
+ " model.set_chunk_size(128)\n",
168
+ "\n",
169
+ "torch.cuda.empty_cache()\n",
170
+ "output = model.infer(sequence,\n",
171
+ " num_recycles=num_recycles,\n",
172
+ " chain_linker=\"X\"*chain_linker,\n",
173
+ " residue_index_offset=512)\n",
174
+ "\n",
175
+ "pdb_str = model.output_to_pdb(output)[0]\n",
176
+ "output = tree_map(lambda x: x.cpu().numpy(), output)\n",
177
+ "ptm = output[\"ptm\"][0]\n",
178
+ "plddt = output[\"plddt\"][0,...,1].mean()\n",
179
+ "O = parse_output(output)\n",
180
+ "print(f'ptm: {ptm:.3f} plddt: {plddt:.3f}')\n",
181
+ "os.system(f\"mkdir -p {ID}\")\n",
182
+ "prefix = f\"{ID}/ptm{ptm:.3f}_r{num_recycles}_default\"\n",
183
+ "np.savetxt(f\"{prefix}.pae.txt\",O[\"pae\"],\"%.3f\")\n",
184
+ "with open(f\"{prefix}.pdb\",\"w\") as out:\n",
185
+ " out.write(pdb_str)"
186
+ ],
187
+ "metadata": {
188
+ "cellView": "form",
189
+ "id": "CcyNpAvhTX6q"
190
+ },
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "source": [
197
+ "#@title display (optional) {run: \"auto\"}\n",
198
+ "import py3Dmol\n",
199
+ "pymol_color_list = [\"#33ff33\",\"#00ffff\",\"#ff33cc\",\"#ffff00\",\"#ff9999\",\"#e5e5e5\",\"#7f7fff\",\"#ff7f00\",\n",
200
+ " \"#7fff7f\",\"#199999\",\"#ff007f\",\"#ffdd5e\",\"#8c3f99\",\"#b2b2b2\",\"#007fff\",\"#c4b200\",\n",
201
+ " \"#8cb266\",\"#00bfbf\",\"#b27f7f\",\"#fcd1a5\",\"#ff7f7f\",\"#ffbfdd\",\"#7fffff\",\"#ffff7f\",\n",
202
+ " \"#00ff7f\",\"#337fcc\",\"#d8337f\",\"#bfff3f\",\"#ff7fff\",\"#d8d8ff\",\"#3fffbf\",\"#b78c4c\",\n",
203
+ " \"#339933\",\"#66b2b2\",\"#ba8c84\",\"#84bf00\",\"#b24c66\",\"#7f7f7f\",\"#3f3fa5\",\"#a5512b\"]\n",
204
+ "\n",
205
+ "def show_pdb(pdb_str, show_sidechains=False, show_mainchains=False,\n",
206
+ " color=\"pLDDT\", chains=None, vmin=50, vmax=90,\n",
207
+ " size=(800,480), hbondCutoff=4.0,\n",
208
+ " Ls=None,\n",
209
+ " animate=False):\n",
210
+ "\n",
211
+ " if chains is None:\n",
212
+ " chains = 1 if Ls is None else len(Ls)\n",
213
+ " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js', width=size[0], height=size[1])\n",
214
+ " if animate:\n",
215
+ " view.addModelsAsFrames(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
216
+ " else:\n",
217
+ " view.addModel(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
218
+ " if color == \"pLDDT\":\n",
219
+ " view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':vmin,'max':vmax}}})\n",
220
+ " elif color == \"rainbow\":\n",
221
+ " view.setStyle({'cartoon': {'color':'spectrum'}})\n",
222
+ " elif color == \"chain\":\n",
223
+ " for n,chain,color in zip(range(chains),alphabet_list,pymol_color_list):\n",
224
+ " view.setStyle({'chain':chain},{'cartoon': {'color':color}})\n",
225
+ " if show_sidechains:\n",
226
+ " BB = ['C','O','N']\n",
227
+ " view.addStyle({'and':[{'resn':[\"GLY\",\"PRO\"],'invert':True},{'atom':BB,'invert':True}]},\n",
228
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
229
+ " view.addStyle({'and':[{'resn':\"GLY\"},{'atom':'CA'}]},\n",
230
+ " {'sphere':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
231
+ " view.addStyle({'and':[{'resn':\"PRO\"},{'atom':['C','O'],'invert':True}]},\n",
232
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
233
+ " if show_mainchains:\n",
234
+ " BB = ['C','O','N','CA']\n",
235
+ " view.addStyle({'atom':BB},{'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
236
+ " view.zoomTo()\n",
237
+ " if animate: view.animate()\n",
238
+ " return view\n",
239
+ "\n",
240
+ "color = \"confidence\" #@param [\"confidence\", \"rainbow\", \"chain\"]\n",
241
+ "if color == \"confidence\": color = \"pLDDT\"\n",
242
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
243
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
244
+ "show_pdb(pdb_str, color=color,\n",
245
+ " show_sidechains=show_sidechains,\n",
246
+ " show_mainchains=show_mainchains,\n",
247
+ " Ls=lengths).show()"
248
+ ],
249
+ "metadata": {
250
+ "cellView": "form",
251
+ "id": "JM5ciSmeTZKO"
252
+ },
253
+ "execution_count": null,
254
+ "outputs": []
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "source": [
259
+ "#@title plot confidence (optional)\n",
260
+ "\n",
261
+ "dpi = 100 #@param {type:\"integer\"}\n",
262
+ "\n",
263
+ "def plot_ticks(Ls):\n",
264
+ " Ln = sum(Ls)\n",
265
+ " L_prev = 0\n",
266
+ " for L_i in Ls[:-1]:\n",
267
+ " L = L_prev + L_i\n",
268
+ " L_prev += L_i\n",
269
+ " plt.plot([0,Ln],[L,L],color=\"black\")\n",
270
+ " plt.plot([L,L],[0,Ln],color=\"black\")\n",
271
+ " ticks = np.cumsum([0]+Ls)\n",
272
+ " ticks = (ticks[1:] + ticks[:-1])/2\n",
273
+ " plt.yticks(ticks,alphabet_list[:len(ticks)])\n",
274
+ "\n",
275
+ "def plot_confidence(O, Ls=None, dpi=100):\n",
276
+ " if \"lm_contacts\" in O:\n",
277
+ " plt.figure(figsize=(20,4), dpi=dpi)\n",
278
+ " plt.subplot(1,4,1)\n",
279
+ " else:\n",
280
+ " plt.figure(figsize=(15,4), dpi=dpi)\n",
281
+ " plt.subplot(1,3,1)\n",
282
+ "\n",
283
+ " plt.title('Predicted lDDT')\n",
284
+ " plt.plot(O[\"plddt\"])\n",
285
+ " if Ls is not None:\n",
286
+ " L_prev = 0\n",
287
+ " for L_i in Ls[:-1]:\n",
288
+ " L = L_prev + L_i\n",
289
+ " L_prev += L_i\n",
290
+ " plt.plot([L,L],[0,100],color=\"black\")\n",
291
+ " plt.xlim(0,O[\"plddt\"].shape[0])\n",
292
+ " plt.ylim(0,100)\n",
293
+ " plt.ylabel('plDDT')\n",
294
+ " plt.xlabel('position')\n",
295
+ " plt.subplot(1,4 if \"lm_contacts\" in O else 3,2)\n",
296
+ "\n",
297
+ " plt.title('Predicted Aligned Error')\n",
298
+ " Ln = O[\"pae\"].shape[0]\n",
299
+ " plt.imshow(O[\"pae\"],cmap=\"bwr\",vmin=0,vmax=30,extent=(0, Ln, Ln, 0))\n",
300
+ " if Ls is not None and len(Ls) > 1: plot_ticks(Ls)\n",
301
+ " plt.colorbar()\n",
302
+ " plt.xlabel('Scored residue')\n",
303
+ " plt.ylabel('Aligned residue')\n",
304
+ "\n",
305
+ " if \"lm_contacts\" in O:\n",
306
+ " plt.subplot(1,4,3)\n",
307
+ " plt.title(\"contacts from LM\")\n",
308
+ " plt.imshow(O[\"lm_contacts\"],cmap=\"Greys\",vmin=0,vmax=1,extent=(0, Ln, Ln, 0))\n",
309
+ " if Ls is not None and len(Ls) > 1: plot_ticks(Ls)\n",
310
+ " plt.subplot(1,4,4)\n",
311
+ " else:\n",
312
+ " plt.subplot(1,3,3)\n",
313
+ " plt.title(\"contacts from Structure Module\")\n",
314
+ " plt.imshow(O[\"sm_contacts\"],cmap=\"Greys\",vmin=0,vmax=1,extent=(0, Ln, Ln, 0))\n",
315
+ " if Ls is not None and len(Ls) > 1: plot_ticks(Ls)\n",
316
+ " return plt\n",
317
+ "\n",
318
+ "plot_confidence(O, Ls=lengths, dpi=dpi)\n",
319
+ "plt.savefig(f'{prefix}.png',bbox_inches='tight')\n",
320
+ "plt.show()"
321
+ ],
322
+ "metadata": {
323
+ "cellView": "form",
324
+ "id": "HGFBl0QYYQpR"
325
+ },
326
+ "execution_count": null,
327
+ "outputs": []
328
+ },
329
+ {
330
+ "cell_type": "code",
331
+ "source": [
332
+ "#@title download predictions\n",
333
+ "from google.colab import files\n",
334
+ "os.system(f\"zip {ID}.zip {ID}/*\")\n",
335
+ "files.download(f'{ID}.zip')"
336
+ ],
337
+ "metadata": {
338
+ "cellView": "form",
339
+ "id": "hkMp_ZwRYfAQ"
340
+ },
341
+ "execution_count": null,
342
+ "outputs": []
343
+ }
344
+ ]
345
+ }
data/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Sergey Ovchinnikov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/MsaServer/README.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Setting up your local ColabFold API server
2
+
3
+ Here you will find two examples of how to setup your own API server on a Linux (or macOS for testing) machine.
4
+
5
+ ## `setup-and-start-local.sh`
6
+
7
+ The `setup-and-start-local.sh` script will execute most of the steps to get a server running for you.
8
+ It will do the following steps:
9
+ * check that all required software is installed (`curl`, `aria2c`, `rsync`, `aws`)
10
+ * download pinned **MMseqs2** and **mmseqs-server** binaries for your platform (Linux x86\_64/arm64, macOS universal)
11
+ * download the databases (UniRef30 and ColabFoldDB, this might take some time)
12
+ * download the API server and compile its binary
13
+ * start the API server
14
+
15
+ The script can be called repeatedly to (re)start the server. It avoids unnecessary work and only re-downloads components when the pinned commit changed.
16
+
17
+ ### CPU/GPU and platform detection
18
+
19
+ * Uncomment the `export GPU=1` line to enable GPU mode (Linux only).
20
+ * The script adds the parameters `--paths.colabfold.gpu.gpu 1 --paths.colabfold.gpu.server 1`. See `config.json` for more details.
21
+
22
+ ### Choosing a PDB rsync mirror
23
+
24
+ At the top of the script you can set the PDB mirror to use (RCSB, PDBe or PDBj).
25
+ Uncomment the pair you want. The script exits if no mirror is selected.
26
+
27
+ ### Configuration
28
+
29
+ Edit `config.json` as needed. Common tweaks:
30
+
31
+ * `server.address` — change the bind address/port (we recommend putting `nginx` in front for gzip/SSL).
32
+ * `local.workers` — number of local job workers.
33
+ * Optional GPU block under `paths.colabfold.gpu` lets you pin device IDs per DB when you run multi-GPU.
34
+ * A `server.ratelimit` example is included and can be enabled.
35
+
36
+ ### Run
37
+
38
+ ```
39
+ ./setup-and-start-local.sh
40
+ ```
41
+
42
+ If `DEBUG_MINI_DB=1` is set, the server starts with templates disabled and a tiny DB for quick tests.
43
+
44
+ ## Setup a systemd service
45
+ To better manage the ColabFold API server, we recommend to setup a systemd service. It will automatically restart on failure and lets you use `journalctl`/`systemctl`.
46
+
47
+ 1. First run `setup-and-start-local.sh` once to get the folder structure and binaries.
48
+ 2. Adjust the `systemd-example-mmseqs-server.service` example and point it to your paths:
49
+ 3. Enable and start `./restart-systemd.sh`
50
+
51
+ ## Forcing databases to stay resident in system memory
52
+
53
+ The ColabFold MSA API server will only achieve response time of few seconds if the search database are held fully within system memory. We use vmtouch (https://github.com/hoytech/vmtouch) to keep the precomputed database index file within system memory. In CPU mode, this is the most expensive part of the MSA API server, as the two default databases (UniRef30+ColabFoldDB) require currently 768GB-1024GB RAM to stay resident in RAM and have enough RAM spare for worker processes.
54
+
55
+ After installing `vmtouch`, you can execute the following command to make sure that the search databases are not evicted from the system cache:
56
+
57
+ ```
58
+ cd databases
59
+ sudo vmtouch -f -w -t -l -d -m 1000G *.idx
60
+ ```
61
+
62
+ ## Using a custom API server
63
+
64
+ You can pass the server URL to `colabfold_batch` via `--host-url`.
65
+ In notebooks, add `host_url=https://yourserver.example.org` to the `run()` call in the *Run Prediction* cell.
data/MsaServer/config.json ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "app": "colabfold",
3
+ // should mmseqs und webserver output be printed
4
+ "verbose": true,
5
+ "server" : {
6
+ "address" : "127.0.0.1:8080",
7
+ // prefix for all API endpoints
8
+ "pathprefix" : "/api/",
9
+ // enables additional API endpoints for adding databases
10
+ // WARNING: No additional authentication provided. Enable only within trusted network/for trusted admins.
11
+ "dbmanagment": false,
12
+ /* enable HTTP Basic Auth (optional)
13
+ "auth": {
14
+ "username" : "",
15
+ "password" : "",
16
+ },
17
+ // enable rate-limiting (optional)
18
+ "ratelimit" : {
19
+ // this uses the token-bucket algorithm
20
+ // i.e. we start with a full bucket (with burst tokens) and refill it at a given rate
21
+ // each request consumes one token, if the bucket is empty the request is rejected
22
+ // the example below starts with 20 tokens and refills 0.0333 token per second (2 tokens per minute)
23
+ "rate" : 0.03333333333333,
24
+ "burst" : 20,
25
+ "ttl" : 1,
26
+ "reason" : "The foldseek server is a shared resource. Please be mindful about submitting many jobs.",
27
+ // CIDRs to allow without rate-limiting
28
+ "allowlist": [],
29
+ },
30
+ */
31
+ // should CORS headers be set to allow requests from anywhere
32
+ "cors" : true,
33
+ // should old jobs be checked on startup
34
+ "checkold" : true,
35
+ },
36
+ "worker": {
37
+ // should workers exit immediately after SIGINT/SIGTERM signal or gracefully wait for job completion
38
+ "gracefulexit": false,
39
+ // How many databases can be searched in parallel (uses additional CPUs)
40
+ "paralleldatabases": 1,
41
+ },
42
+ // paths to workfolders and mmseqs, special character ~ is resolved relative to the binary location
43
+ "paths" : {
44
+ // path to job results and scratch directory, has to be shared between server/workers
45
+ "results" : "~jobs",
46
+ // paths to colabfold templates
47
+ "colabfold" : {
48
+ // configure GPU support for colabfold
49
+ // GPU support for mmseqs and foldseek is configured in database .params files
50
+ /*
51
+ "gpu" : {
52
+ // enable/disable
53
+ "gpu": true,
54
+ // enable gpuserver, saves about 1.5s per request in overhead
55
+ "server": true,
56
+ // set cuda visible devices for all databases, can be empty/omitted
57
+ // "devices": "0,1,2",
58
+ // set/override devices per database for better VRAM managment
59
+ // "uniref_devices": "0",
60
+ // "pdb_devices": "1",
61
+ // "environmental_devices": "2",
62
+ },
63
+ */
64
+ // should stages be run in parallel, faster at the cost of more CPU
65
+ "parallelstages": false,
66
+ // paths for search databases
67
+ "uniref" : "~databases/uniref30_2302_db",
68
+ "pdb" : "~databases/pdb100_230517",
69
+ "environmental" : "~databases/colabfold_envdb_202108_db",
70
+ // not used in public MSA server
71
+ // "environmentalpair" : "~databases/spire_ctg10_2401_db",
72
+ // paths for templates
73
+ "pdb70" : "~databases/pdb100",
74
+ "pdbdivided" : "~databases/pdb/divided",
75
+ "pdbobsolete" : "~databases/pdb/obsolete",
76
+ },
77
+ // path to mmseqs binary
78
+ "mmseqs" : "mmseqs",
79
+ },
80
+ // connection details for redis database, not used in -local mode
81
+ "redis" : {
82
+ "network" : "tcp",
83
+ "address" : "localhost:6379",
84
+ "password" : "",
85
+ "index" : 0,
86
+ },
87
+ // options for local/single-binary server
88
+ "local" : {
89
+ "workers" : 1,
90
+ // should old jobs be checked on startup
91
+ "checkold" : true,
92
+ },
93
+ "mail" : {
94
+ "type" : "null",
95
+ "sender" : "mail@example.org",
96
+ "templates" : {
97
+ "success" : {
98
+ "subject" : "Done -- %s",
99
+ "body" : "Dear User,\nThe results of your submitted job are available now at https://search.mmseqs.com/queue/%s .\n"
100
+ },
101
+ "timeout" : {
102
+ "subject" : "Timeout -- %s",
103
+ "body" : "Dear User,\nYour submitted job timed out. More details are available at https://search.mmseqs.com/queue/%s .\nPlease adjust the job and submit it again.\n"
104
+ },
105
+ "error" : {
106
+ "subject" : "Error -- %s",
107
+ "body" : "Dear User,\nYour submitted job failed. More details are available at https://search.mmseqs.com/queue/%s .\nPlease submit your job later again.\n"
108
+ }
109
+ }
110
+ }
111
+ }
112
+
data/MsaServer/restart-systemd.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/bin/sh -e
2
+ sudo systemctl stop mmseqs-server
3
+ rm -rf -- jobs
4
+ mkdir -p jobs
5
+ sudo systemctl start mmseqs-server
data/MsaServer/setup-and-start-local.sh ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -e
3
+
4
+ # run this script from the MsaServer folder
5
+ SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
6
+ cd "${SCRIPT_DIR}"
7
+
8
+ # enable this if you want to start a GPU MSA server
9
+ #export GPU=1
10
+
11
+ # choose which pdb rsync server to use
12
+ #PDB_SERVER=rsync.wwpdb.org::ftp # RCSB PDB server name
13
+ #PDB_PORT=33444 # port RCSB PDB server is using
14
+ #
15
+ #PDB_SERVER=rsync.ebi.ac.uk::pub/databases/rcsb/pdb-remediated # PDBe server name
16
+ #PDB_PORT=873 # port PDBe server is using
17
+ #
18
+ #PDB_SERVER=pdb.protein.osaka-u.ac.jp::ftp # PDBj server name
19
+ #PDB_PORT=873 # port PDBj server is using
20
+ if [ -z "${PDB_SERVER}" ] || [ -z "${PDB_PORT}" ]; then
21
+ echo "PDB rsync server was not chosen, please edit this script to choose which PDB download server you want to use"
22
+ exit 1
23
+ fi
24
+
25
+ # set which commits to use
26
+ MMSEQS_COMMIT=${1:-05ae20cbc628d9911ad0aa421fba029cc457b76e}
27
+ BACKEND_COMMIT=${2:-01365aa4735539ba95b417f73fb5326c77410394}
28
+
29
+ # check if all dependencies are there
30
+ for i in curl aria2c rsync aws; do
31
+ if ! command -v "${i}" > /dev/null 2>&1; then
32
+ echo "${i} is not installed, please install it first"
33
+ exit 1
34
+ fi
35
+ done
36
+
37
+ ARCH=avx2
38
+ if [ -n "${GPU}" ]; then
39
+ ARCH=gpu
40
+ fi
41
+ ARCH_SERVER=x86_64;
42
+ case "$(uname -m)" in
43
+ aarch64|arm64)
44
+ ARCH=arm64
45
+ if [ -n "${GPU}" ]; then
46
+ ARCH=gpu-arm64
47
+ fi
48
+ ARCH_SERVER=arm64
49
+ ;;
50
+ esac
51
+
52
+ OS=linux
53
+ case "$(uname -s)" in
54
+ Darwin)
55
+ OS=osx
56
+ ARCH=universal
57
+ ARCH_SERVER=universal
58
+ unset GPU
59
+ ;;
60
+ esac
61
+
62
+ # check that the correct mmseqs commit is there
63
+ if [ -x ./mmseqs/bin/mmseqs ]; then
64
+ # download it again if its a different commit
65
+ if [ $(./mmseqs/bin/mmseqs version) != ${MMSEQS_COMMIT} ]; then
66
+ rm -rf -- mmseqs
67
+ curl -s -o- https://mmseqs.com/archive/${MMSEQS_COMMIT}/mmseqs-${OS}-${ARCH}.tar.gz | tar -xzf - mmseqs/bin/mmseqs
68
+ fi
69
+ else
70
+ curl -s -o- https://mmseqs.com/archive/${MMSEQS_COMMIT}/mmseqs-${OS}-${ARCH}.tar.gz | tar -xzf - mmseqs/bin/mmseqs
71
+ fi
72
+
73
+ # check that the correct mmseqs commit is there
74
+ if [ -x ./mmseqs-server/bin/mmseqs-server ]; then
75
+ # download it again if its a different commit
76
+ if [ $(./mmseqs-server/bin/mmseqs-server -version) != ${BACKEND_COMMIT} ]; then
77
+ rm -rf -- mmseqs-server
78
+ curl -s -o- https://mmseqs.com/archive/${BACKEND_COMMIT}/mmseqs-server-${OS}-${ARCH_SERVER}.tar.gz | tar -xzf - mmseqs-server/bin/mmseqs-server
79
+ fi
80
+ else
81
+ curl -s -o- https://mmseqs.com/archive/${BACKEND_COMMIT}/mmseqs-server-${OS}-${ARCH_SERVER}.tar.gz | tar -xzf - mmseqs-server/bin/mmseqs-server
82
+ fi
83
+
84
+
85
+ # mmseqs needs to be in PATH for the setup_databases script to work
86
+ PATH="${SCRIPT_DIR}/mmseqs/bin:$PATH"
87
+
88
+ # This downloads a tiny swissprot based database for testing only
89
+ #export DEBUG_MINI_DB=1
90
+ # don't re-download databases if they already exist as they are large
91
+ if [ ! -d databases ]; then
92
+ mkdir -p databases
93
+ if [ -n "${DEBUG_MINI_DB}" ]; then
94
+ touch databases/SKIP_TEMPLATES
95
+ fi
96
+ ../setup_databases.sh databases "${PDB_SERVER}" "${PDB_PORT}"
97
+ fi
98
+
99
+ # Extra GPU parameters
100
+ GPU_PARAMS=""
101
+ if [ -n "${GPU}" ]; then
102
+ GPU_PARAMS="--paths.colabfold.gpu.gpu 1 --paths.colabfold.gpu.server 1"
103
+ fi
104
+
105
+ # start the server in local mode
106
+ # meaning both workers and server run from the same process
107
+ if [ -n "${DEBUG_MINI_DB}" ]; then
108
+ ./mmseqs-server/bin/mmseqs-server -local -config config.json -paths.colabfold.pdb70 '' ${GPU_PARAMS}
109
+ else
110
+ ./mmseqs-server/bin/mmseqs-server -local -config config.json ${GPU_PARAMS}
111
+ fi
data/MsaServer/systemd-example-mmseqs-server.service ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [Unit]
2
+ Description=MMseqs2 Server
3
+ After=network.target
4
+
5
+ [Service]
6
+ User=user
7
+ Group=user
8
+ WorkingDirectory=/path-to-mmseqs-server-home
9
+ Environment="MMSEQS_NUM_THREADS=1"
10
+ ExecStart=/path-to-mmseqs-server-home/msa-server -local -config /path-to-mmseqs-server-home/config.json
11
+ Type=simple
12
+ Restart=on-failure
13
+ RestartSec=10s
14
+
15
+ [Install]
16
+ WantedBy=multi-user.target
data/README.md ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ColabFold - v1.6.1
2
+
3
+ For details of what was changed in v1.6.1, see [change log](https://github.com/sokrypton/ColabFold/wiki/v1.6.1)!
4
+
5
+ <p align="center"><img src="https://github.com/sokrypton/ColabFold/raw/main/.github/ColabFold_Marv_Logo.png" height="250"/></p>
6
+
7
+ ### Making Protein folding accessible to all via Google Colab!
8
+
9
+ | Notebooks | monomers | complexes | mmseqs2 | jackhmmer | templates |
10
+ | :----------------------------------------------------------------------------------------------------------------------------------------------- | -------- | --------- | ------- | --------- | --------- |
11
+ | [AlphaFold2_mmseqs2](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/AlphaFold2.ipynb) | Yes | Yes | Yes | No | Yes |
12
+ | [AlphaFold2_batch](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/batch/AlphaFold2_batch.ipynb) | Yes | Yes | Yes | No | Yes |
13
+ | [AlphaFold2](https://colab.research.google.com/github/deepmind/alphafold/blob/main/notebooks/AlphaFold.ipynb) (from Deepmind) | Yes | Yes | No | Yes | No |
14
+ | [relax_amber](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/relax_amber.ipynb) (relax input structure) | | | | | |
15
+ | [ESMFold](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/ESMFold.ipynb) | Yes | Maybe | No | No | No |
16
+ | |
17
+ | **BETA (in development) notebooks** | | | | | |
18
+ | [RoseTTAFold2](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/RoseTTAFold2.ipynb) | Yes | Yes | Yes | No | WIP |
19
+ | [Boltz](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/Boltz1.ipynb) | Yes | Yes | Yes | No | No |
20
+ | [BioEmu](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/BioEmu.ipynb) | Yes | No | Yes | No | No |
21
+ | [OmegaFold](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/omegafold.ipynb) | Yes | Maybe | No | No | No |
22
+ | [AlphaFold2_advanced_v2](https://colab.research.google.com/github/sokrypton/ColabDesign/blob/gamma/af/examples/predict.ipynb) (new experimental notebook) | Yes | Yes | Yes | No | Yes |
23
+
24
+ Check the wiki page [old retired notebooks](https://github.com/sokrypton/ColabFold/wiki/Old-retired-notebooks) for unsupported notebooks.
25
+
26
+ ### FAQ
27
+ - Where can I chat with other ColabFold users?
28
+ - See our [Discord](https://discord.gg/gna8maru7d) channel!
29
+ - Can I use the models for **Molecular Replacement**?
30
+ - Yes, but be **CAREFUL**, the bfactor column is populated with pLDDT confidence values (higher = better). Phenix.phaser expects a "real" bfactor, where (lower = better). See [post](https://twitter.com/cheshireminima/status/1423929241675120643) from Claudia Millán.
31
+ - What is the maximum length?
32
+ - Limits depends on free GPU provided by Google Colab `fingers-crossed`
33
+ - For GPUs with ~16G the max length is ~2000
34
+ - Is it okay to use the MMseqs2 MSA server on a local computer?
35
+ - You can access the server from a local computer if you queries are serial from a single IP. Please do not use multiple computers to query the server.
36
+ - Where can I download the databases used by ColabFold?
37
+ - The databases are available at [colabfold.mmseqs.com](https://colabfold.mmseqs.com)
38
+ - I want to render my own images of the predicted structures, how do I color by pLDDT?
39
+ - In pymol for AlphaFold structures: `spectrum b, red_yellow_green_cyan_blue, minimum=50, maximum=90`
40
+ - If you want to use AlphaFold Colours (credit: Konstantin Korotkov)
41
+ ```python
42
+ set_color n0, [0.051, 0.341, 0.827]
43
+ set_color n1, [0.416, 0.796, 0.945]
44
+ set_color n2, [0.996, 0.851, 0.212]
45
+ set_color n3, [0.992, 0.490, 0.302]
46
+ color n0, b < 100; color n1, b < 90
47
+ color n2, b < 70; color n3, b < 50
48
+ ```
49
+ - In pymol for RoseTTAFold structures: `spectrum b, red_yellow_green_cyan_blue, minimum=0.5, maximum=0.9`
50
+ - What is the difference between the AlphaFold2_advanced and AlphaFold2_mmseqs2 (_batch) notebook for complex prediction?
51
+ - We currently have two different ways to predict protein complexes: (1) using the AlphaFold2 model with residue index jump and (2) using the AlphaFold2-multimer model. AlphaFold2_advanced supports (1) and AlphaFold2_mmseqs2 (_batch) (2).
52
+ - What is the difference between localcolabfold and the pip installable colabfold_batch?
53
+ - [LocalColabFold](https://github.com/YoshitakaMo/localcolabfold) is an installer script designed to make ColabFold functionality available on local users' machines. It supports wide range of operating systems, such as Windows 10 or later (using Windows Subsystem for Linux 2), macOS, and Linux.
54
+ - Is there a way to amber-relax structures without having to rerun alphafold/colabfold from scratch?
55
+ - Yes, see this [notebook](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/relax_amber.ipynb).
56
+ - Where can I find the old notebooks that were previously developed and are now retired?
57
+ - You can find the list of retired notebooks in the [old retired notebooks](https://github.com/sokrypton/ColabFold/wiki/Old-retired-notebooks) wiki page.
58
+ - Where can I find the history of MSA Server Databases used in ColabFold?
59
+ - You can view the database version history on the [MSA Server Database History](https://github.com/sokrypton/ColabFold/wiki/MSA-Server-Database-History) wiki page.
60
+
61
+ ### Installation
62
+
63
+ For a one-step installer script that supports Linux, macOS, and Windows (WSL2), see [LocalColabFold](https://github.com/YoshitakaMo/localcolabfold).
64
+
65
+ Alternatively, ColabFold can be installed directly with `conda` and `pip`:
66
+
67
+ ```shell
68
+ conda create -n colabfold -c conda-forge -c bioconda python=3.13 kalign2=2.04 hhsuite=3.3.0 mmseqs2=18.8cc5c
69
+ conda activate colabfold
70
+ # With CUDA GPU support
71
+ pip install colabfold[alphafold,openmm] jax[cuda] openmm[cuda12]
72
+ # CPU only
73
+ pip install colabfold[alphafold,openmm]
74
+ # For colabfold_search only (no structure prediction)
75
+ pip install colabfold
76
+ ```
77
+
78
+ A Docker image is also available:
79
+
80
+ ```shell
81
+ docker pull ghcr.io/sokrypton/colabfold:1.6.1-cuda12
82
+ ```
83
+
84
+ See our [wiki](https://github.com/sokrypton/ColabFold/wiki/Running-ColabFold-in-Docker) for more details on running ColabFold in Docker.
85
+
86
+ ### Generating MSAs for small scale local structure/complex predictions using the MSA server
87
+
88
+ When you pass a FASTA or CSV file containing your sequences to `colabfold_batch` it will automatically query the public MSA server to generate MSAs. You might want to split this into two steps for better GPU resource utilization:
89
+
90
+ ```
91
+ # Query the MSA server and predict the structure on local GPU in one go:
92
+ colabfold_batch input_sequences.fasta out_dir
93
+
94
+ # Split querying MSA server and GPU predictions into two steps
95
+ colabfold_batch input_sequences.fasta out_dir --msa-only
96
+ colabfold_batch input_sequences.fasta out_dir
97
+ ```
98
+
99
+ ### Generating MSAs for large scale structure/complex predictions
100
+
101
+ First create a directory for the databases on a disk with sufficient storage (940GB (!)). Depending on where you are, this will take a couple of hours:
102
+
103
+ Note: [MMseqs2 Release 18](https://github.com/soedinglab/MMseqs2/releases/tag/18-8cc5c) is used to create the databases and perform sequece search in the ColabFold MSA server. Please use this version if you want to obtain the same MSAs as the server.
104
+
105
+ ```shell
106
+ MMSEQS_NO_INDEX=1 ./setup_databases.sh /path/to/db_folder
107
+ ```
108
+
109
+ If MMseqs2 is not installed in your `PATH`, add `--mmseqs <path to mmseqs>` to your `mmseqs` in `colabfold_search`:
110
+
111
+ ```shell
112
+ # This needs a lot of CPU
113
+ colabfold_search --mmseqs /path/to/bin/mmseqs input_sequences.fasta /path/to/db_folder msas
114
+ # This needs a GPU
115
+ colabfold_batch msas predictions
116
+ ```
117
+
118
+ This will create intermediate folder `msas` that contains all input multiple sequence alignments formated as a3m files and a `predictions` folder with all predicted pdb,json and png files.
119
+
120
+ The procedure above disables MMseqs2 preindexing of the various ColabFold databases by setting the `MMSEQS_NO_INDEX=1` environment variable before calling the database setup script. For most use-cases of `colabfold_search` precomputing the index is not required and might hurt search speed. The precomputed index is necessary for fast response times of the ColabFold server, where the whole database is permamently kept in memory. In any case the batch searches will require a machine with about 128GB RAM or, if the databases are to be kept permamently in RAM, with over 1TB RAM.
121
+
122
+ In some cases using precomputed database can still be useful. For the following cases, call the `setup_databases.sh` script without the `MMSEQS_NO_INDEX` environment variable:
123
+
124
+ (0) As mentioned above, if you want to set-up a server.
125
+
126
+ (1) If the precomputed index is stored on a very fast storage system (e.g., NVMe-SSDs) it might be faster to read the index from disk than computing in on the fly. In this case, the search should be performed on the same machine that called `setup_databases.sh` since the precomputed index is created to fit within the given main memory size. Additionaly, pass the `--db-load-mode 0` option to make sure the database is read once from the storage system before use.
127
+
128
+ (2) Fast single query searches require the full index (the `.idx` files) to be kept in memory. This can be done with e.g. by using [vmtouch](https://github.com/hoytech/vmtouch). Thus, this type of search requires a machine with at least 768GB to 1TB RAM for the ColabfoldDB. If the index is present in memory, use the `--db-load-mode 2` parameter in `colabfold_search` to avoid index loading overhead.
129
+
130
+ If no index was created (`MMSEQS_NO_INDEX=1` was set), then `--db-load-mode` does not do anything and can be ignored.
131
+
132
+ ### Saving MSAs in AlphaFold3-compatible JSON format
133
+ You can export MSAs into a json format compatible with AlphaFold3 input using the `--af3-json` option.
134
+
135
+ **With colabfold_search:**
136
+
137
+ If you are using the local database setup with colabfold_search, you can add the `--af3-json` option to save the MSAs as AlphaFold3 input json:
138
+ ```shell
139
+ colabfold_search --mmseqs /path/to/bin/mmseqs input_sequences.fasta /path/to/db_folder msas --af3-json
140
+ ```
141
+ This will create a json file in the `msas` folder, using the same name as the a3m file.
142
+
143
+ **With colabfold_batch:**
144
+
145
+ If you are using the MSA server via colabfold_batch, you can also use the `--af3-json` option. However, structure prediction will be skipped, and only the json file will be generated.
146
+ ```shell
147
+ colabfold_batch input_sequences.fasta out_dir --af3-json
148
+ ```
149
+
150
+ #### Including non-protein molecules in FASTA
151
+ AlphaFold3 supports non-protein components such as ligands and nucleic acids in input complexes. To include these in the generated json file, you can specify them directly in your FASTA input using the following format, `molecule type|sequence|(copies)`. As molecue types, dna, rna, ccd, smiles are allowed.
152
+
153
+ > :exclamation: **Substitute aromatic bonds in SMILES**
154
+ > If your SMILES string contains aromatic bonds (`:`), please replace them with semicolons (`;`) to avoid internal parsing issues.
155
+
156
+ - Examples
157
+ - For DNA: `dna|ATCG`
158
+ - For RNA: `rna|AUGC`
159
+ - For ligands:
160
+ - SMILES string: `smiles|C1=NC(=C2C(=N1)N(C=N2)[C@H]3[C@@H]([C@@H]([C@H](O3)COP(=O)(O)OP(=O)(O)OP(=O)(O)O)O)O)N`
161
+ - CCD code: `ccd|ATP`
162
+ - To specify multiple copies of a molecule, you can add a number after the sequence, e.g. `ccd|ATP|2` or `dna|ATCG|2`.
163
+
164
+ Here is an example of biological complex with 2 proteins and 2 ATP ligands:
165
+ ```
166
+ >Complex1|Prot1:Prot2:Lig
167
+ FIRSTPROTEIN:SECONDPROTEIN:ccd|ATP|2
168
+ >Complex2|Prot1:Prot2:Lig
169
+ FIRSTPROTEIN:SECONDPROTEIN:ccd|ATP:ccd|ATP
170
+ ```
171
+ As the `copies` is optional, the `Complex1` and `Complex2` will result in identical json input.
172
+
173
+ Note that MMseqs2-based MSAs are only generated for the protein sequences. RNA entries will not have unpaired MSAs in the json file. However, the field is marked as null so that AlphaFold3 can generate MSAs for them.
174
+
175
+ ### GPU-accelerated search with ⁠`colabfold_search` ⁠
176
+ ColabFold supports GPU-accelerated MSA searches through [MMseqs2-GPU](https://www.biorxiv.org/content/10.1101/2024.11.13.623350v1).
177
+
178
+ #### GPU database setup
179
+ To setup the GPU databases, you will need to run the ⁠`setup_databases.sh`⁠ command with ⁠`GPU=1`⁠ as an environment variable:
180
+
181
+ ```
182
+ GPU=1 ./setup_databases.sh /path/to/db_folder
183
+ ```
184
+
185
+ This will download and setup the GPU databases in the specified folder. Note that here we do not pass ⁠`MMSEQS_NO_INDEX=1`⁠ as an argument since the indices are useful in the GPU search since we will keep them in the GPU memory.
186
+
187
+ #### GPU search
188
+ By default, running `colabfold_search` with the `--gpu 1` option uses all available GPUs for its search.
189
+
190
+ ```
191
+ colabfold_search /path/to/bin/mmseqs input_sequences.fasta /path/to/db_folder msas --gpu 1
192
+ ```
193
+
194
+ To select specific GPUs, set the `CUDA_VISIBLE_DEVICES` environment variable:
195
+ ```
196
+ CUDA_VISIBLE_DEVICES=0,1 colabfold_search --mmseqs /path/to/bin/mmseqs input_sequences.fasta /path/to/db_folder msas --gpu 1
197
+ ```
198
+
199
+ #### Optional GPU server for enhanced performance:
200
+ For frequent searches or to achieve minimal latency, you can run a dedicated GPU server. This server holds databases permanently in GPU memory, largely eliminating search overhead:
201
+
202
+ Start the GPU server(s):
203
+ ```
204
+ mmseqs gpuserver /path/to/db_folder/colabfold_envdb_202108_db --max-seqs 10000 --db-load-mode 0 --prefilter-mode 1 &
205
+ PID1=$!
206
+ mmseqs gpuserver /path/to/db_folder/uniref30_2302_db --max-seqs 10000 --db-load-mode 0 --prefilter-mode 1 &
207
+ PID2=$!
208
+ ```
209
+
210
+ By default, the GPU server distributes the database evenly across all visible GPUs. You can limit GPU usage by setting the CUDA_VISIBLE_DEVICES environment variable (e.g., `CUDA_VISIBLE_DEVICES=0,1`).
211
+ Important: Ensure that the `CUDA_VISIBLE_DEVICES` environment variable is set consistently for both `gpuserver` and `colabfold_search`, otherwise `colabfold_search` will try wait for the `gpuserver` to appear until a set timeout (by default 5 minutes). If your database exceeds GPU memory capacity, the GPU server efficiently streams data between host and GPU memory using asynchronous CUDA streams.
212
+
213
+ Run searches using the GPU server:
214
+ ```
215
+ colabfold_search --mmseqs /path/to/bin/mmseqs input_sequences.fasta /path/to/db_folder msas \
216
+ --gpu 1 --gpu-server 1 --db-load-mode 2
217
+ ```
218
+ Here, `--db-load-mode 2` is **criical** for fast single query performance. The parameter can be omitted if large batches of queries are supplied to `colabfold_search`. This parameter decides whether a database should be fully copied into RAM in each MMseqs2 module invocation (`--db-load-mode 0`; default), or if MMseqs2 can asusme that the databases are already present in RAM (`--db-load-mode 2`). For ideal performance, the database should still be preloaded into RAM (e.g. with `vmtouch`; see above), before the first `colabfold_search` invocation.
219
+
220
+ To stop the server(s) when done:
221
+ ```
222
+ kill $PID1
223
+ kill $PID2
224
+ ```
225
+ For more details, see [GPU-accelerated search](https://github.com/soedinglab/MMseqs2/wiki#gpu-accelerated-search).
226
+
227
+ ### Tutorials & Presentations
228
+ - ColabFold Tutorial presented at the Boston Protein Design and Modeling Club. [[video]](https://www.youtube.com/watch?v=Rfw7thgGTwI) [[slides]](https://docs.google.com/presentation/d/1mnffk23ev2QMDzGZ5w1skXEadTe54l8-Uei6ACce8eI).
229
+
230
+ ### Projects based on ColabFold or helpers
231
+
232
+ - [Run ColabFold on your local computer](https://github.com/YoshitakaMo/localcolabfold) by Yoshitaka Moriwaki
233
+ - [ColabFold/AlphaFold2 for protein structure predictions for Discoba species](https://github.com/zephyris/discoba_alphafold) by Richard John Wheeler
234
+ - [Cloud-based molecular simulations for everyone](https://github.com/pablo-arantes/Making-it-rain) by Pablo R. Arantes, Marcelo D. Polêto, Conrado Pedebos and Rodrigo Ligabue-Braun
235
+ - [getmoonbear is a webserver to predict protein structures](https://www.getmoonbear.com/AlphaFold2) by Stephanie Zhang and Neil Deshmukh
236
+ - [ColabFold/AlphaFold2 IDR complex prediction](https://github.com/normandavey/AlphaFold2-IDR-complex-prediction) by Balint Meszaros
237
+ - [ColabFold/AlphaFold2 (Phenix version) for macromolecular structure determination](https://colab.research.google.com/github/phenix-project/Colabs/blob/main/alphafold2/AlphaFold2.ipynb) by Tom Terwilliger
238
+ - [AlphaPickle: making AlphaFold2/ColabFold outputs interpretable](https://colab.research.google.com/github/mattarnoldbio/alphapickle/blob/main/AlphaPickle.ipynb) by Matt Arnold
239
+
240
+ ### Acknowledgments
241
+ - We would like to thank the [RoseTTAFold](https://github.com/RosettaCommons/RoseTTAFold) and [AlphaFold](https://github.com/deepmind/alphafold) team for doing an excellent job open sourcing the software.
242
+ - Also credit to [David Koes](https://github.com/dkoes) for his awesome [py3Dmol](https://3dmol.csb.pitt.edu/) plugin, without whom these notebooks would be quite boring!
243
+ - A colab by Sergey Ovchinnikov (@sokrypton), Milot Mirdita (@milot_mirdita) and Martin Steinegger (@thesteinegger).
244
+
245
+ ### How do I reference this work?
246
+
247
+ - Mirdita M, Schütze K, Moriwaki Y, Heo L, Ovchinnikov S and Steinegger M. ColabFold: Making protein folding accessible to all. <br />
248
+ Nature Methods (2022) doi: [10.1038/s41592-022-01488-1](https://www.nature.com/articles/s41592-022-01488-1)
249
+ - For a step-by-step protocol on how to use ColabFold, please refer to: <br />
250
+ Kim G & Lee S et al. Easy and accurate protein structure prediction using ColabFold. <br />
251
+ Nature Protocols (2025) doi: [10.1038/s41596-024-01060-5](https://www.nature.com/articles/s41596-024-01060-5)
252
+ - If you’re using **AlphaFold**, please also cite: <br />
253
+ Jumper et al. "Highly accurate protein structure prediction with AlphaFold." <br />
254
+ Nature (2021) doi: [10.1038/s41586-021-03819-2](https://doi.org/10.1038/s41586-021-03819-2)
255
+ - If you’re using **AlphaFold-multimer**, please also cite: <br />
256
+ Evans et al. "Protein complex prediction with AlphaFold-Multimer." <br />
257
+ biorxiv (2021) doi: [10.1101/2021.10.04.463034v1](https://www.biorxiv.org/content/10.1101/2021.10.04.463034v1)
258
+ - If you are using **RoseTTAFold**, please also cite: <br />
259
+ Minkyung et al. "Accurate prediction of protein structures and interactions using a three-track neural network." <br />
260
+ Science (2021) doi: [10.1126/science.abj8754](https://doi.org/10.1126/science.abj8754)
261
+
262
+ [![DOI](https://zenodo.org/badge/doi/10.5281/zenodo.5123296.svg)](https://doi.org/10.5281/zenodo.5123296)
data/RoseTTAFold.ipynb ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "RoseTTAFold.ipynb",
7
+ "provenance": [],
8
+ "include_colab_link": true
9
+ },
10
+ "kernelspec": {
11
+ "display_name": "Python 3",
12
+ "name": "python3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ },
17
+ "accelerator": "GPU"
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {
23
+ "id": "view-in-github",
24
+ "colab_type": "text"
25
+ },
26
+ "source": [
27
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/RoseTTAFold.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "markdown",
32
+ "metadata": {
33
+ "id": "74RP4ByMFXHR"
34
+ },
35
+ "source": [
36
+ "# RoseTTAFold\n",
37
+ "**Limitations**\n",
38
+ "- This notebook disables a few aspects (templates, pytosetta) of the full rosettafold pipeline.\n",
39
+ "- For best resuls use the [full pipeline](https://github.com/RosettaCommons/RoseTTAFold) or [Robetta webserver](https://robetta.bakerlab.org/)!\n",
40
+ "- For a typical Google-Colab session, with a `16G-GPU`, the max total length is **700 residues**. Sometimes a `12G-GPU` is assigned, in which case the max length is lower.\n",
41
+ "- For version of RoseTTAFold that runs with pyRosetta [see here](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/RoseTTAFold.ipynb).\n",
42
+ "\n",
43
+ "For other related notebooks see [ColabFold](https://github.com/sokrypton/ColabFold)"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "metadata": {
49
+ "id": "8v06TAo9ZaGH",
50
+ "cellView": "form"
51
+ },
52
+ "source": [
53
+ "#@title ##Install and import libraries\n",
54
+ "#@markdown This step can take up to ~2 mins\n",
55
+ "\n",
56
+ "import os\n",
57
+ "import sys\n",
58
+ "from IPython.utils import io\n",
59
+ "from google.colab import files\n",
60
+ "\n",
61
+ "import torch\n",
62
+ "torch_v = torch.__version__\n",
63
+ "\n",
64
+ "\n",
65
+ "if not os.path.isdir(\"RoseTTAFold\"):\n",
66
+ " with io.capture_output() as captured:\n",
67
+ " # extra functionality\n",
68
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/colabfold.py\n",
69
+ "\n",
70
+ " # download model\n",
71
+ " %shell git clone https://github.com/RosettaCommons/RoseTTAFold.git\n",
72
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/RoseTTAFold__network__Refine_module.patch\n",
73
+ " %shell patch -u RoseTTAFold/network/Refine_module.py -i RoseTTAFold__network__Refine_module.patch\n",
74
+ "\n",
75
+ " # download model params\n",
76
+ " %shell wget -qnc https://files.ipd.uw.edu/pub/RoseTTAFold/weights.tar.gz\n",
77
+ " %shell tar -xf weights.tar.gz\n",
78
+ " %shell rm weights.tar.gz\n",
79
+ "\n",
80
+ " # download scwrl4 (for adding sidechains)\n",
81
+ " # http://dunbrack.fccc.edu/SCWRL3.php\n",
82
+ " # Thanks Roland Dunbrack!\n",
83
+ " %shell wget -qnc https://files.ipd.uw.edu/krypton/TrRosetta/scwrl4.zip\n",
84
+ " %shell unzip -qqo scwrl4.zip\n",
85
+ "\n",
86
+ " # install libraries\n",
87
+ " %shell pip install -q dgl-cu113 -f https://data.dgl.ai/wheels/repo.html\n",
88
+ " %shell pip install -q torch-scatter -f https://pytorch-geometric.com/whl/torch-{torch_v}.html\n",
89
+ " %shell pip install -q torch-sparse -f https://pytorch-geometric.com/whl/torch-{torch_v}.html\n",
90
+ " %shell pip install -q torch-geometric\n",
91
+ " %shell pip install -q py3Dmol\n",
92
+ "\n",
93
+ "with io.capture_output() as captured:\n",
94
+ " sys.path.append('/content/RoseTTAFold/network')\n",
95
+ " import predict_e2e\n",
96
+ " from parsers import parse_a3m\n",
97
+ " \n",
98
+ "import colabfold as cf\n",
99
+ "import py3Dmol\n",
100
+ "import subprocess\n",
101
+ "import numpy as np\n",
102
+ "import matplotlib.pyplot as plt\n",
103
+ "\n",
104
+ "def get_bfactor(pdb_filename):\n",
105
+ " bfac = []\n",
106
+ " for line in open(pdb_filename,\"r\"):\n",
107
+ " if line[:4] == \"ATOM\":\n",
108
+ " bfac.append(float(line[60:66]))\n",
109
+ " return np.array(bfac)\n",
110
+ "\n",
111
+ "def set_bfactor(pdb_filename, bfac):\n",
112
+ " I = open(pdb_filename,\"r\").readlines()\n",
113
+ " O = open(pdb_filename,\"w\")\n",
114
+ " for line in I:\n",
115
+ " if line[0:6] == \"ATOM \":\n",
116
+ " seq_id = int(line[22:26].strip()) - 1\n",
117
+ " O.write(f\"{line[:60]}{bfac[seq_id]:6.2f}{line[66:]}\")\n",
118
+ " O.close() \n",
119
+ "\n",
120
+ "def do_scwrl(inputs, outputs, exe=\"./scwrl4/Scwrl4\"):\n",
121
+ " subprocess.run([exe,\"-i\",inputs,\"-o\",outputs,\"-h\"],\n",
122
+ " stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n",
123
+ " bfact = get_bfactor(inputs)\n",
124
+ " set_bfactor(outputs, bfact)\n",
125
+ " return bfact"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {
133
+ "id": "YWe2OSU59iKD",
134
+ "cellView": "form"
135
+ },
136
+ "source": [
137
+ "#@markdown ##Input Sequence\n",
138
+ "sequence = \"PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK\" #@param {type:\"string\"}\n",
139
+ "sequence = sequence.translate(str.maketrans('', '', ' \\n\\t')).upper()\n",
140
+ "\n",
141
+ "jobname = \"test\" #@param {type:\"string\"}\n",
142
+ "jobname = jobname+\"_\"+cf.get_hash(sequence)[:5]"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {
150
+ "id": "_nTsyKtQxjO8",
151
+ "cellView": "form"
152
+ },
153
+ "source": [
154
+ "#@title Search against genetic databases\n",
155
+ "#@markdown ---\n",
156
+ "msa_method = \"mmseqs2\" #@param [\"mmseqs2\",\"single_sequence\",\"custom_a3m\"]\n",
157
+ "#@markdown - `mmseqs2` - FAST method from [ColabFold](https://github.com/sokrypton/ColabFold)\n",
158
+ "#@markdown - `single_sequence` - use single sequence input (not recommended, unless a *denovo* design and you dont expect to find any homologous sequences)\n",
159
+ "#@markdown - `custom_a3m` Upload custom MSA (a3m format)\n",
160
+ "\n",
161
+ "# tmp directory\n",
162
+ "prefix = cf.get_hash(sequence)\n",
163
+ "os.makedirs('tmp', exist_ok=True)\n",
164
+ "prefix = os.path.join('tmp',prefix)\n",
165
+ "\n",
166
+ "os.makedirs(jobname, exist_ok=True)\n",
167
+ "\n",
168
+ "\n",
169
+ "if msa_method == \"mmseqs2\":\n",
170
+ " a3m_lines = cf.run_mmseqs2(sequence, prefix, filter=True)\n",
171
+ " with open(f\"{jobname}/msa.a3m\",\"w\") as a3m:\n",
172
+ " a3m.write(a3m_lines)\n",
173
+ "\n",
174
+ "elif msa_method == \"single_sequence\":\n",
175
+ " with open(f\"{jobname}/msa.a3m\",\"w\") as a3m:\n",
176
+ " a3m.write(f\">{jobname}\\n{sequence}\\n\")\n",
177
+ "\n",
178
+ "elif msa_method == \"custom_a3m\":\n",
179
+ " print(\"upload custom a3m\")\n",
180
+ " msa_dict = files.upload()\n",
181
+ " lines = msa_dict[list(msa_dict.keys())[0]].decode().splitlines()\n",
182
+ " a3m_lines = []\n",
183
+ " for line in lines:\n",
184
+ " line = line.replace(\"\\x00\",\"\")\n",
185
+ " if len(line) > 0 and not line.startswith('#'):\n",
186
+ " a3m_lines.append(line)\n",
187
+ "\n",
188
+ " with open(f\"{jobname}/msa.a3m\",\"w\") as a3m:\n",
189
+ " a3m.write(\"\\n\".join(a3m_lines))\n",
190
+ "\n",
191
+ "msa_all = parse_a3m(f\"{jobname}/msa.a3m\")\n",
192
+ "msa_arr = np.unique(msa_all,axis=0)\n",
193
+ "total_msa_size = len(msa_arr)\n",
194
+ "if msa_method == \"mmseqs2\":\n",
195
+ " print(f'\\n{total_msa_size} Sequences Found in Total (after filtering)\\n')\n",
196
+ "else:\n",
197
+ " print(f'\\n{total_msa_size} Sequences Found in Total\\n')\n",
198
+ "\n",
199
+ "if total_msa_size > 1:\n",
200
+ " plt.figure(figsize=(8,5),dpi=100)\n",
201
+ " plt.title(\"Sequence coverage\")\n",
202
+ " seqid = (msa_all[0] == msa_arr).mean(-1)\n",
203
+ " seqid_sort = seqid.argsort()\n",
204
+ " non_gaps = (msa_arr != 20).astype(float)\n",
205
+ " non_gaps[non_gaps == 0] = np.nan\n",
206
+ " plt.imshow(non_gaps[seqid_sort]*seqid[seqid_sort,None],\n",
207
+ " interpolation='nearest', aspect='auto',\n",
208
+ " cmap=\"rainbow_r\", vmin=0, vmax=1, origin='lower',\n",
209
+ " extent=(0, msa_arr.shape[1], 0, msa_arr.shape[0]))\n",
210
+ " plt.plot((msa_arr != 20).sum(0), color='black')\n",
211
+ " plt.xlim(0,msa_arr.shape[1])\n",
212
+ " plt.ylim(0,msa_arr.shape[0])\n",
213
+ " plt.colorbar(label=\"Sequence identity to query\",)\n",
214
+ " plt.xlabel(\"Positions\")\n",
215
+ " plt.ylabel(\"Sequences\")\n",
216
+ " plt.savefig(f\"{jobname}/msa_coverage.png\", bbox_inches = 'tight')\n",
217
+ " plt.show()"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {
225
+ "id": "14-q4hv59ast",
226
+ "cellView": "form"
227
+ },
228
+ "source": [
229
+ "#@title ## Run RoseTTAFold for mainchain and Scrwl4 for sidechain prediction\n",
230
+ "\n",
231
+ "# load model\n",
232
+ "if \"rosettafold\" not in dir():\n",
233
+ " rosettafold = predict_e2e.Predictor(model_dir=\"weights\")\n",
234
+ "\n",
235
+ "# make prediction using model\n",
236
+ "rosettafold.predict(f\"{jobname}/msa.a3m\",f\"{jobname}/pred\")\n",
237
+ "\n",
238
+ "# pack sidechains using Scwrl4\n",
239
+ "plddt = do_scwrl(f\"{jobname}/pred.pdb\",f\"{jobname}/pred.scwrl.pdb\")\n",
240
+ "\n",
241
+ "print(f\"Predicted LDDT: {plddt.mean()}\")\n",
242
+ "\n",
243
+ "plt.figure(figsize=(8,5),dpi=100)\n",
244
+ "plt.plot(plddt)\n",
245
+ "plt.xlabel(\"positions\")\n",
246
+ "plt.ylabel(\"plddt\")\n",
247
+ "plt.ylim(0,1)\n",
248
+ "plt.savefig(f\"{jobname}/plddt.png\", bbox_inches = 'tight')\n",
249
+ "plt.show()\n"
250
+ ],
251
+ "execution_count": null,
252
+ "outputs": []
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "metadata": {
257
+ "id": "qPhmF8SZr1k8",
258
+ "cellView": "form"
259
+ },
260
+ "source": [
261
+ "#@title Display 3D structure {run: \"auto\"}\n",
262
+ "color = \"lDDT\" #@param [\"chain\", \"lDDT\", \"rainbow\"]\n",
263
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
264
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
265
+ "cf.show_pdb(f\"{jobname}/pred.scwrl.pdb\", show_sidechains, show_mainchains, color, chains=1, vmin=0.5, vmax=0.9).show()\n",
266
+ "\n",
267
+ "if color == \"lDDT\": cf.plot_plddt_legend().show() "
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": []
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {
275
+ "id": "j0RhMLHKHf8d",
276
+ "cellView": "form"
277
+ },
278
+ "source": [
279
+ "#@title Download prediction\n",
280
+ "\n",
281
+ "#@markdown Once this cell has been executed, a zip-archive with \n",
282
+ "#@markdown the obtained prediction will be automatically downloaded \n",
283
+ "#@markdown to your computer.\n",
284
+ "\n",
285
+ "# add settings file\n",
286
+ "settings_path = f\"{jobname}/settings.txt\"\n",
287
+ "with open(settings_path, \"w\") as text_file:\n",
288
+ " text_file.write(f\"method=RoseTTAFold\\n\")\n",
289
+ " text_file.write(f\"sequence={sequence}\\n\")\n",
290
+ " text_file.write(f\"msa_method={msa_method}\\n\")\n",
291
+ " text_file.write(f\"use_templates=False\\n\")\n",
292
+ "\n",
293
+ "# --- Download the predictions ---\n",
294
+ "!zip -q -r {jobname}.zip {jobname}\n",
295
+ "files.download(f'{jobname}.zip')"
296
+ ],
297
+ "execution_count": null,
298
+ "outputs": []
299
+ }
300
+ ]
301
+ }
data/RoseTTAFold2.ipynb ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4",
8
+ "include_colab_link": true
9
+ },
10
+ "kernelspec": {
11
+ "display_name": "Python 3",
12
+ "name": "python3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ },
17
+ "accelerator": "GPU",
18
+ "gpuClass": "standard"
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {
24
+ "id": "view-in-github",
25
+ "colab_type": "text"
26
+ },
27
+ "source": [
28
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/RoseTTAFold2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {
34
+ "id": "74RP4ByMFXHR"
35
+ },
36
+ "source": [
37
+ "#**RoseTTAFold2 (WIP)**\n",
38
+ "RoseTTAFold2 is a method for protein structure prediction.\n",
39
+ "\n",
40
+ "\n",
41
+ "#### **Tips and Instructions**\n",
42
+ "- click the little ▶ play icon to the left of each cell below.\n",
43
+ "- use \":\" to specify multimeric input, (eg. sequence=\"AAA:AAA\")\n",
44
+ "- See detailed instructions at the end.\n",
45
+ "\n",
46
+ "\n",
47
+ "**<font color=\"red\">NOTE:</font>** This notebook is in active development, we are still working on adding all the options (such as template inputs) from the [manuscript](https://www.biorxiv.org/content/10.1101/2023.05.24.542179v1). Use at your own risk!\n"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "source": [
53
+ "%%time\n",
54
+ "#@title setup **RoseTTAFold2** (~1m)\n",
55
+ "params = \"RF2_apr23\" # @param [\"RF2_apr23\",\"RF2_jan24\"]\n",
56
+ "\n",
57
+ "import os, time, sys\n",
58
+ "os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"max_split_size_mb:512\"\n",
59
+ "\n",
60
+ "if params == \"RF2_jan24\" and not os.path.isfile(f\"{params}.tgz\"):\n",
61
+ " # send param download into background\n",
62
+ " os.system(\"(apt-get install aria2; aria2c -q -x 16 https://files.ipd.uw.edu/dimaio/RF2_jan24.tgz) &\")\n",
63
+ "\n",
64
+ "if params == \"RF2_apr23\" and not os.path.isfile(f\"{params}.tgz\"):\n",
65
+ " # send param download into background\n",
66
+ " os.system(\"(apt-get install aria2; aria2c -q -x 16 https://files.ipd.uw.edu/dimaio/RF2_apr23.tgz) &\")\n",
67
+ "\n",
68
+ "if not os.path.isdir(\"RoseTTAFold2\"):\n",
69
+ " print(\"install RoseTTAFold2\")\n",
70
+ " os.system(\"git clone https://github.com/uw-ipd/RoseTTAFold2.git\")\n",
71
+ " os.system(\"pip install py3Dmol\")\n",
72
+ "\n",
73
+ " # 17Mar2024: adding --no-dependencies to avoid installing nvidia-cuda-* dependencies\n",
74
+ " # 25Aug2025: updating dgi install to work with latest pytorch\n",
75
+ " os.system(\"pip install --no-dependencies dgl -f https://data.dgl.ai/wheels/torch-2.4/cu124/repo.html\")\n",
76
+ " os.system(\"pip install --no-dependencies e3nn==0.5.5 opt_einsum_fx\")\n",
77
+ " os.system(\"cd RoseTTAFold2/SE3Transformer; pip install .\")\n",
78
+ "\n",
79
+ " os.system(\"wget https://raw.githubusercontent.com/sokrypton/ColabFold/main/colabfold/colabfold.py -O colabfold_utils.py\")\n",
80
+ "\n",
81
+ " #os.system(\"pip install dgl -f https://data.dgl.ai/wheels/cu121/repo.html\")\n",
82
+ " #os.system(\"cd RoseTTAFold2/SE3Transformer; pip -q install --no-cache-dir -r requirements.txt; pip -q install .\")\n",
83
+ " #os.system(\"wget https://raw.githubusercontent.com/sokrypton/ColabFold/beta/colabfold/mmseqs/api.py\")\n",
84
+ "\n",
85
+ " # install hhsuite\n",
86
+ " print(\"install hhsuite\")\n",
87
+ " os.makedirs(\"hhsuite\", exist_ok=True)\n",
88
+ " os.system(f\"curl -fsSL https://github.com/soedinglab/hh-suite/releases/download/v3.3.0/hhsuite-3.3.0-SSE2-Linux.tar.gz | tar xz -C hhsuite/\")\n",
89
+ "\n",
90
+ "if not os.path.isfile(f\"{params}.pt\"):\n",
91
+ " time.sleep(5)\n",
92
+ "\n",
93
+ "if os.path.isfile(f\"{params}.tgz.aria2\"):\n",
94
+ " print(\"downloading RoseTTAFold2 params\")\n",
95
+ " while os.path.isfile(f\"{params}.tgz.aria2\"):\n",
96
+ " time.sleep(5)\n",
97
+ "\n",
98
+ "if not os.path.isfile(f\"{params}.pt\"):\n",
99
+ " os.system(f\"tar -zxvf {params}.tgz\")\n",
100
+ " if params == \"RF2_apr23\":\n",
101
+ " os.system(f\"mv weights/{params}.pt .\")\n",
102
+ "\n",
103
+ "if not \"IMPORTED\" in dir():\n",
104
+ " if 'RoseTTAFold2/network' not in sys.path:\n",
105
+ " os.environ[\"DGLBACKEND\"] = \"pytorch\"\n",
106
+ " sys.path.append('RoseTTAFold2/network')\n",
107
+ " if \"hhsuite\" not in os.environ['PATH']:\n",
108
+ " os.environ['PATH'] += \":hhsuite/bin:hhsuite/scripts\"\n",
109
+ "\n",
110
+ " import matplotlib.pyplot as plt\n",
111
+ " from google.colab import files\n",
112
+ " import numpy as np\n",
113
+ " from parsers import parse_a3m\n",
114
+ " #from api import run_mmseqs2\n",
115
+ " from colabfold_utils import run_mmseqs2\n",
116
+ " import py3Dmol\n",
117
+ " import torch\n",
118
+ " from string import ascii_uppercase, ascii_lowercase\n",
119
+ " import hashlib, re, os\n",
120
+ " import random\n",
121
+ "\n",
122
+ " def get_hash(x): return hashlib.sha1(x.encode()).hexdigest()\n",
123
+ " alphabet_list = list(ascii_uppercase+ascii_lowercase)\n",
124
+ " from collections import OrderedDict, Counter\n",
125
+ "\n",
126
+ " IMPORTED = True\n",
127
+ "\n",
128
+ "if not \"pred\" in dir() or params_sele != params:\n",
129
+ " from predict import Predictor\n",
130
+ " print(\"compile RoseTTAFold2\")\n",
131
+ "\n",
132
+ " if (torch.cuda.is_available()):\n",
133
+ " pred = Predictor(f\"{params}.pt\", torch.device(\"cuda:0\"))\n",
134
+ " else:\n",
135
+ " print (\"WARNING: using CPU\")\n",
136
+ " pred = Predictor(f\"{params}.pt\", torch.device(\"cpu\"))\n",
137
+ " params_sele = params\n",
138
+ "\n",
139
+ "def get_unique_sequences(seq_list):\n",
140
+ " unique_seqs = list(OrderedDict.fromkeys(seq_list))\n",
141
+ " return unique_seqs\n",
142
+ "\n",
143
+ "def run_mmseqs2_wrapper(*args, **kwargs):\n",
144
+ " kwargs['user_agent'] = \"colabfold/rosettafold2\"\n",
145
+ " return run_mmseqs2(*args, **kwargs)\n",
146
+ "\n",
147
+ "def get_msa(seq, jobname, cov=50, id=90, max_msa=2048,\n",
148
+ " mode=\"unpaired_paired\"):\n",
149
+ "\n",
150
+ " assert mode in [\"unpaired\",\"paired\",\"unpaired_paired\"]\n",
151
+ " seqs = [seq] if isinstance(seq,str) else seq\n",
152
+ "\n",
153
+ " # collapse homooligomeric sequences\n",
154
+ " counts = Counter(seqs)\n",
155
+ " u_seqs = list(counts.keys())\n",
156
+ " u_nums = list(counts.values())\n",
157
+ "\n",
158
+ " # expand homooligomeric sequences\n",
159
+ " first_seq = \"/\".join(sum([[x]*n for x,n in zip(u_seqs,u_nums)],[]))\n",
160
+ " msa = [first_seq]\n",
161
+ "\n",
162
+ " path = os.path.join(jobname,\"msa\")\n",
163
+ " os.makedirs(path, exist_ok=True)\n",
164
+ " if mode in [\"paired\",\"unpaired_paired\"] and len(u_seqs) > 1:\n",
165
+ " print(\"getting paired MSA\")\n",
166
+ " out_paired = run_mmseqs2_wrapper(u_seqs, f\"{path}/\", use_pairing=True)\n",
167
+ " headers, sequences = [],[]\n",
168
+ " for a3m_lines in out_paired:\n",
169
+ " n = -1\n",
170
+ " for line in a3m_lines.split(\"\\n\"):\n",
171
+ " if len(line) > 0:\n",
172
+ " if line.startswith(\">\"):\n",
173
+ " n += 1\n",
174
+ " if len(headers) < (n + 1):\n",
175
+ " headers.append([])\n",
176
+ " sequences.append([])\n",
177
+ " headers[n].append(line)\n",
178
+ " else:\n",
179
+ " sequences[n].append(line)\n",
180
+ " # filter MSA\n",
181
+ " with open(f\"{path}/paired_in.a3m\",\"w\") as handle:\n",
182
+ " for n,sequence in enumerate(sequences):\n",
183
+ " handle.write(f\">n{n}\\n{''.join(sequence)}\\n\")\n",
184
+ " os.system(f\"hhfilter -i {path}/paired_in.a3m -id {id} -cov {cov} -o {path}/paired_out.a3m\")\n",
185
+ " with open(f\"{path}/paired_out.a3m\",\"r\") as handle:\n",
186
+ " for line in handle:\n",
187
+ " if line.startswith(\">\"):\n",
188
+ " n = int(line[2:])\n",
189
+ " xs = sequences[n]\n",
190
+ " # expand homooligomeric sequences\n",
191
+ " xs = ['/'.join([x]*num) for x,num in zip(xs,u_nums)]\n",
192
+ " msa.append('/'.join(xs))\n",
193
+ "\n",
194
+ " if len(msa) < max_msa and (mode in [\"unpaired\",\"unpaired_paired\"] or len(u_seqs) == 1):\n",
195
+ " print(\"getting unpaired MSA\")\n",
196
+ " out = run_mmseqs2_wrapper(u_seqs,f\"{path}/\")\n",
197
+ " Ls = [len(seq) for seq in u_seqs]\n",
198
+ " sub_idx = []\n",
199
+ " sub_msa = []\n",
200
+ " sub_msa_num = 0\n",
201
+ " for n,a3m_lines in enumerate(out):\n",
202
+ " sub_msa.append([])\n",
203
+ " with open(f\"{path}/in_{n}.a3m\",\"w\") as handle:\n",
204
+ " handle.write(a3m_lines)\n",
205
+ " # filter\n",
206
+ " os.system(f\"hhfilter -i {path}/in_{n}.a3m -id {id} -cov {cov} -o {path}/out_{n}.a3m\")\n",
207
+ " with open(f\"{path}/out_{n}.a3m\",\"r\") as handle:\n",
208
+ " for line in handle:\n",
209
+ " if not line.startswith(\">\"):\n",
210
+ " xs = ['-'*l for l in Ls]\n",
211
+ " xs[n] = line.rstrip()\n",
212
+ " # expand homooligomeric sequences\n",
213
+ " xs = ['/'.join([x]*num) for x,num in zip(xs,u_nums)]\n",
214
+ " sub_msa[-1].append('/'.join(xs))\n",
215
+ " sub_msa_num += 1\n",
216
+ " sub_idx.append(list(range(len(sub_msa[-1]))))\n",
217
+ "\n",
218
+ " while len(msa) < max_msa and sub_msa_num > 0:\n",
219
+ " for n in range(len(sub_idx)):\n",
220
+ " if len(sub_idx[n]) > 0:\n",
221
+ " msa.append(sub_msa[n][sub_idx[n].pop(0)])\n",
222
+ " sub_msa_num -= 1\n",
223
+ " if len(msa) == max_msa:\n",
224
+ " break\n",
225
+ "\n",
226
+ " with open(f\"{jobname}/msa.a3m\",\"w\") as handle:\n",
227
+ " for n,sequence in enumerate(msa):\n",
228
+ " handle.write(f\">n{n}\\n{sequence}\\n\")"
229
+ ],
230
+ "metadata": {
231
+ "id": "ymCHu14w17wF",
232
+ "cellView": "form"
233
+ },
234
+ "execution_count": null,
235
+ "outputs": []
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "source": [
240
+ "#@title ###run **RoseTTAFold2**\n",
241
+ "sequence = \"PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK\" #@param {type:\"string\"}\n",
242
+ "jobname = \"test\" #@param {type:\"string\"}\n",
243
+ "\n",
244
+ "#@markdown symmetry settings\n",
245
+ "sym = \"X\" #@param [\"X\",\"C\", \"D\", \"T\", \"I\", \"O\"]\n",
246
+ "order = 1 #@param [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"] {type:\"raw\"}\n",
247
+ "msa_concat_mode = \"diag\" #@param [\"diag\", \"repeat\", \"default\"]\n",
248
+ "\n",
249
+ "#@markdown msa settings\n",
250
+ "msa_method = \"mmseqs2\" #@param [\"mmseqs2\",\"single_sequence\",\"custom_a3m\"]\n",
251
+ "pair_mode = \"unpaired_paired\" #@param [\"unpaired_paired\",\"paired\",\"unpaired\"] {type:\"string\"}\n",
252
+ "collapse_identical = False #@param {type:\"boolean\"}\n",
253
+ "\n",
254
+ "#@markdown RoseTTAFold2 settings\n",
255
+ "num_recycles = 6 #@param [0, 1, 3, 6, 12, 24] {type:\"raw\"}\n",
256
+ "\n",
257
+ "#@markdown stochastic settings\n",
258
+ "use_mlm = False #@param {type:\"boolean\"}\n",
259
+ "use_dropout = False #@param {type:\"boolean\"}\n",
260
+ "max_msa = 256 #@param [16, 32, 64, 128, 256, 512] {type:\"raw\"}\n",
261
+ "random_seed = 0 #@param {type:\"integer\"}\n",
262
+ "num_models = 1 #@param [\"1\", \"5\", \"10\", \"15\", \"20\", \"25\"] {type:\"raw\"}\n",
263
+ "\n",
264
+ "# process\n",
265
+ "max_extra_msa = max_msa * 8\n",
266
+ "\n",
267
+ "sequence = re.sub(\"[^A-Z:]\", \"\", sequence.replace(\"/\",\":\").upper())\n",
268
+ "sequence = re.sub(\":+\",\":\",sequence)\n",
269
+ "sequence = re.sub(\"^[:]+\",\"\",sequence)\n",
270
+ "sequence = re.sub(\"[:]+$\",\"\",sequence)\n",
271
+ "\n",
272
+ "if sym in [\"X\",\"C\"]:\n",
273
+ " copies = order\n",
274
+ "elif sym in [\"D\"]:\n",
275
+ " copies = order * 2\n",
276
+ "else:\n",
277
+ " copies = {\"T\":12,\"O\":24,\"I\":60}[sym]\n",
278
+ " order = \"\"\n",
279
+ "symm = sym + str(order)\n",
280
+ "\n",
281
+ "sequences = sequence.replace(\":\",\"/\").split(\"/\")\n",
282
+ "if collapse_identical:\n",
283
+ " u_sequences = get_unique_sequences(sequences)\n",
284
+ "else:\n",
285
+ " u_sequences = sequences\n",
286
+ "sequences = sum([u_sequences] * copies,[])\n",
287
+ "lengths = [len(s) for s in sequences]\n",
288
+ "\n",
289
+ "# TODO\n",
290
+ "#subcrop = 1000 if sum(lengths) > 1400 else -1\n",
291
+ "\n",
292
+ "subcrop = -1\n",
293
+ "topk = 1536\n",
294
+ "\n",
295
+ "\n",
296
+ "sequence = \"/\".join(sequences)\n",
297
+ "jobname = jobname+\"_\"+symm+\"_\"+get_hash(sequence)[:5]\n",
298
+ "\n",
299
+ "print(f\"jobname: {jobname}\")\n",
300
+ "print(f\"lengths: {lengths}\")\n",
301
+ "\n",
302
+ "os.makedirs(jobname, exist_ok=True)\n",
303
+ "if msa_method == \"mmseqs2\":\n",
304
+ " get_msa(u_sequences, jobname, mode=pair_mode, max_msa=max_extra_msa)\n",
305
+ "\n",
306
+ "elif msa_method == \"single_sequence\":\n",
307
+ " u_sequence = \"/\".join(u_sequences)\n",
308
+ " with open(f\"{jobname}/msa.a3m\",\"w\") as a3m:\n",
309
+ " a3m.write(f\">{jobname}\\n{u_sequence}\\n\")\n",
310
+ "\n",
311
+ "elif msa_method == \"custom_a3m\":\n",
312
+ " print(\"upload custom a3m\")\n",
313
+ " msa_dict = files.upload()\n",
314
+ " lines = msa_dict[list(msa_dict.keys())[0]].decode().splitlines()\n",
315
+ " a3m_lines = []\n",
316
+ " for line in lines:\n",
317
+ " line = line.replace(\"\\x00\",\"\")\n",
318
+ " if len(line) > 0 and not line.startswith('#'):\n",
319
+ " a3m_lines.append(line)\n",
320
+ "\n",
321
+ " with open(f\"{jobname}/msa.a3m\",\"w\") as a3m:\n",
322
+ " a3m.write(\"\\n\".join(a3m_lines))\n",
323
+ "\n",
324
+ "best_plddt = None\n",
325
+ "best_seed = None\n",
326
+ "for seed in range(random_seed,random_seed+num_models):\n",
327
+ " torch.manual_seed(seed)\n",
328
+ " random.seed(seed)\n",
329
+ " np.random.seed(seed)\n",
330
+ " npz = f\"{jobname}/rf2_seed{seed}_00.npz\"\n",
331
+ " pred.predict(inputs=[f\"{jobname}/msa.a3m\"],\n",
332
+ " out_prefix=f\"{jobname}/rf2_seed{seed}\",\n",
333
+ " symm=symm,\n",
334
+ " ffdb=None, #TODO (templates),\n",
335
+ " n_recycles=num_recycles,\n",
336
+ " msa_mask=0.15 if use_mlm else 0.0,\n",
337
+ " msa_concat_mode=msa_concat_mode,\n",
338
+ " nseqs=max_msa,\n",
339
+ " nseqs_full=max_extra_msa,\n",
340
+ " subcrop=subcrop,\n",
341
+ " topk=topk,\n",
342
+ " is_training=use_dropout)\n",
343
+ " plddt = np.load(npz)[\"lddt\"].mean()\n",
344
+ " if best_plddt is None or plddt > best_plddt:\n",
345
+ " best_plddt = plddt\n",
346
+ " best_seed = seed"
347
+ ],
348
+ "metadata": {
349
+ "cellView": "form",
350
+ "id": "Eh48KV70rQ03"
351
+ },
352
+ "execution_count": null,
353
+ "outputs": []
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "source": [
358
+ "#@title Display 3D structure {run: \"auto\"}\n",
359
+ "color = \"plddt\" #@param [\"plddt\",\"chain\",\"rainbow\"]\n",
360
+ "import py3Dmol\n",
361
+ "import matplotlib\n",
362
+ "from string import ascii_uppercase,ascii_lowercase\n",
363
+ "alphabet_list = list(ascii_uppercase+ascii_lowercase)\n",
364
+ "pymol_color_list = [\"#33ff33\",\"#00ffff\",\"#ff33cc\",\"#ffff00\",\"#ff9999\",\"#e5e5e5\",\"#7f7fff\",\"#ff7f00\",\n",
365
+ " \"#7fff7f\",\"#199999\",\"#ff007f\",\"#ffdd5e\",\"#8c3f99\",\"#b2b2b2\",\"#007fff\",\"#c4b200\",\n",
366
+ " \"#8cb266\",\"#00bfbf\",\"#b27f7f\",\"#fcd1a5\",\"#ff7f7f\",\"#ffbfdd\",\"#7fffff\",\"#ffff7f\",\n",
367
+ " \"#00ff7f\",\"#337fcc\",\"#d8337f\",\"#bfff3f\",\"#ff7fff\",\"#d8d8ff\",\"#3fffbf\",\"#b78c4c\",\n",
368
+ " \"#339933\",\"#66b2b2\",\"#ba8c84\",\"#84bf00\",\"#b24c66\",\"#7f7f7f\",\"#3f3fa5\",\"#a5512b\"]\n",
369
+ "pymol_cmap = matplotlib.colors.ListedColormap(pymol_color_list)\n",
370
+ "\n",
371
+ "def plot_pdb(pdb, color=\"plddt\"):\n",
372
+ " hbondCutoff = 4.0\n",
373
+ " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js')\n",
374
+ " pdb_str = open(pdb,'r').read()\n",
375
+ " view.addModel(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
376
+ " if color == \"rainbow\":\n",
377
+ " view.setStyle({'cartoon': {'color':'spectrum'}})\n",
378
+ " elif color == \"chain\":\n",
379
+ " for n,chain,c in zip(range(len(lengths)),alphabet_list,pymol_color_list):\n",
380
+ " view.setStyle({'chain':chain},{'cartoon': {'color':c}})\n",
381
+ " else:\n",
382
+ " view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':50,'max':90}}})\n",
383
+ " view.zoomTo()\n",
384
+ " view.show()\n",
385
+ "\n",
386
+ "plot_pdb(f\"{jobname}/rf2_seed{best_seed}_00_pred.pdb\", color=color)\n",
387
+ "output = dict(np.load(f\"{jobname}/rf2_seed{best_seed}_00.npz\"))\n",
388
+ "plt.figure(figsize=(10,5))\n",
389
+ "plt.subplot(1,2,1)\n",
390
+ "plt.title(\"predicted LDDT\")\n",
391
+ "plt.plot(output[\"lddt\"])\n",
392
+ "plt.ylim(0,1.0)\n",
393
+ "plt.subplot(1,2,2)\n",
394
+ "plt.title(\"predicted alignment error\")\n",
395
+ "plt.imshow(output[\"pae\"],vmin=0,vmax=30,cmap=\"bwr\")\n",
396
+ "plt.show()"
397
+ ],
398
+ "metadata": {
399
+ "cellView": "form",
400
+ "id": "3m0H-yCIrpc4"
401
+ },
402
+ "execution_count": null,
403
+ "outputs": []
404
+ },
405
+ {
406
+ "cell_type": "code",
407
+ "source": [
408
+ "#@title Download prediction\n",
409
+ "\n",
410
+ "#@markdown Once this cell has been executed, a zip-archive with\n",
411
+ "#@markdown the obtained prediction will be automatically downloaded\n",
412
+ "#@markdown to your computer.\n",
413
+ "\n",
414
+ "# add settings file\n",
415
+ "settings_path = f\"{jobname}/settings.txt\"\n",
416
+ "with open(settings_path, \"w\") as text_file:\n",
417
+ " text_file.write(f\"method=RoseTTAFold2\\n\")\n",
418
+ " text_file.write(f\"params={params}\\n\")\n",
419
+ " text_file.write(f\"sequence={sequence}\\n\")\n",
420
+ " text_file.write(f\"sym={sym}\\n\")\n",
421
+ " text_file.write(f\"order={order}\\n\")\n",
422
+ " text_file.write(f\"msa_concat_mode={msa_concat_mode}\\n\")\n",
423
+ " text_file.write(f\"collapse_identical={collapse_identical}\")\n",
424
+ " text_file.write(f\"random_seed={random_seed}\\n\")\n",
425
+ " text_file.write(f\"msa_method={msa_method}\\n\")\n",
426
+ " text_file.write(f\"num_recycles={num_recycles}\\n\")\n",
427
+ " text_file.write(f\"use_mlm={use_mlm}\\n\")\n",
428
+ " text_file.write(f\"use_dropout={use_dropout}\\n\")\n",
429
+ " text_file.write(f\"num_models={num_models}\\n\")\n",
430
+ "\n",
431
+ "# --- Download the predictions ---\n",
432
+ "os.system(f\"zip -r {jobname}.zip {jobname}\")\n",
433
+ "files.download(f'{jobname}.zip')"
434
+ ],
435
+ "metadata": {
436
+ "cellView": "form",
437
+ "id": "M21J9hQTLVhz"
438
+ },
439
+ "execution_count": null,
440
+ "outputs": []
441
+ },
442
+ {
443
+ "cell_type": "markdown",
444
+ "source": [
445
+ "#**Instructions**\n",
446
+ "---\n",
447
+ "**symmetry settings**\n",
448
+ "\n",
449
+ "RoseTTAFold2 was finetuned with explicit symmetry information. If the symmetry is known, you can specify using `sym` and `order` options. Supported symmetries include: [C]yclic, [D]ihedral, [T]etrahedral, [I]cosahedral, [O]ctahedral and [X] for unknown.\n",
450
+ "- `order` define number of copies in X/C/D symmetries.\n",
451
+ "- `msa_concat_mode` defines how the msa is concatenated.\n",
452
+ "```bash\n",
453
+ "| repeat | diag | default |\n",
454
+ "| AAA | A-- | A-- |\n",
455
+ "| | -A- | -AA |\n",
456
+ "| | --A | |\n",
457
+ "```\n",
458
+ "\n",
459
+ "**msa settings**\n",
460
+ "- `msa_method`\n",
461
+ " - `mmseqs2` - FAST method from [ColabFold](https://github.com/sokrypton/ColabFold)\n",
462
+ " - `single_sequence` - use single sequence input (not recommended, unless a *denovo* design and you dont expect to find any homologous sequences)\n",
463
+ " - `custom_a3m` Upload custom MSA (a3m format)\n",
464
+ "- `pair_mode` For multimeric inputs, specify how to generate MSA.\n",
465
+ " - `unpaired` - generate seperate MSA for each protein.\n",
466
+ " - `unpaired_paired` - attempt to pair sequences from the same genome.\n",
467
+ " - `paired` - only use sequences that were sucessfully paired.\n",
468
+ "- `collapse_identical` - remove identical (homooligomeric) sequences from input `sequence`. (This could be useful if you plan to use the symmetry option above).\n",
469
+ "\n",
470
+ "**RoseTTAFold2 settings**\n",
471
+ "- `num_recycles` specify number of iterations to run for.\n",
472
+ "\n",
473
+ "**stochastic settings**\n",
474
+ "\n",
475
+ " The stochasticity can be reproduced using specified `random_seed`. Increasing `num_models` controls how many random seeds to try: `range(random_seed,random_seed+num_models)`. There are 3 ways to introduce randomness into the predictions:\n",
476
+ "- `use_mlm` - random 15% of positions are masked in the input MSA.\n",
477
+ "- `use_dropout` - dropout layers are endabled during inference.\n",
478
+ "- `max_msa` - if `max_msa * 8` is lower than number of sequences in the input MSA. The number of sequences are subsampled to the max number. Different subsamplings may also results in stochasticity.\n",
479
+ "\n",
480
+ "**I'm running out of memory, what do I do??**\n",
481
+ "- Try decrease `max_msa` to a smaller number.\n",
482
+ "- Get better GPU, on free Google colab max total length ~1600"
483
+ ],
484
+ "metadata": {
485
+ "id": "IuRWdTAgY-7l"
486
+ }
487
+ }
488
+ ]
489
+ }
data/batch/AlphaFold2_batch.ipynb ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "accelerator": "GPU",
6
+ "colab": {
7
+ "name": "AlphaFold2_batch.ipynb",
8
+ "provenance": [],
9
+ "runtime_attributes": {
10
+ "runtime_version": "2025.07"
11
+ }
12
+ },
13
+ "kernelspec": {
14
+ "name": "python3",
15
+ "language": "python",
16
+ "display_name": "Python 3 (ipykernel)"
17
+ },
18
+ "language_info": {
19
+ "name": "python"
20
+ }
21
+ },
22
+ "cells": [
23
+ {
24
+ "cell_type": "markdown",
25
+ "metadata": {
26
+ "id": "view-in-github",
27
+ "colab_type": "text"
28
+ },
29
+ "source": [
30
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/batch/AlphaFold2_batch.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "markdown",
35
+ "metadata": {
36
+ "id": "G4yBrceuFbf3"
37
+ },
38
+ "source": [
39
+ "#ColabFold v1.6.1: AlphaFold2 w/ MMseqs2 BATCH\n",
40
+ "\n",
41
+ "<img src=\"https://raw.githubusercontent.com/sokrypton/ColabFold/main/.github/ColabFold_Marv_Logo_Small.png\" height=\"256\" align=\"right\" style=\"height:256px\">\n",
42
+ "\n",
43
+ "Easy to use AlphaFold2 protein structure [(Jumper et al. 2021)](https://www.nature.com/articles/s41586-021-03819-2) and complex [(Evans et al. 2021)](https://www.biorxiv.org/content/10.1101/2021.10.04.463034v1) prediction using multiple sequence alignments generated through MMseqs2. For details, refer to our manuscript:\n",
44
+ "\n",
45
+ "[Mirdita M, Schütze K, Moriwaki Y, Heo L, Ovchinnikov S, Steinegger M. ColabFold: Making protein folding accessible to all.\n",
46
+ "*Nature Methods*, 2022](https://www.nature.com/articles/s41592-022-01488-1)\n",
47
+ "\n",
48
+ "**Usage**\n",
49
+ "\n",
50
+ "`input_dir` directory with only fasta files or MSAs stored in Google Drive. MSAs need to be A3M formatted and have an `.a3m` extention. For MSAs MMseqs2 will not be called.\n",
51
+ "\n",
52
+ "`result_dir` results will be written to the result directory in Google Drive\n",
53
+ "\n",
54
+ "Old versions: [v1.4](https://colab.research.google.com/github/sokrypton/ColabFold/blob/v1.4.0/batch/AlphaFold2_batch.ipynb), [v1.5.1](https://colab.research.google.com/github/sokrypton/ColabFold/blob/v1.5.1/batch/AlphaFold2_batch.ipynb), [v1.5.2](https://colab.research.google.com/github/sokrypton/ColabFold/blob/v1.5.2/batch/AlphaFold2_batch.ipynb), [v1.5.3-patch](https://colab.research.google.com/github/sokrypton/ColabFold/blob/56c72044c7d51a311ca99b953a71e552fdc042e1/batch/AlphaFold2_batch.ipynb)\n",
55
+ "\n",
56
+ "<strong>For more details, see <a href=\"#Instructions\">bottom</a> of the notebook and checkout the [ColabFold GitHub](https://github.com/sokrypton/ColabFold). </strong>\n",
57
+ "\n",
58
+ "-----------\n",
59
+ "\n",
60
+ "### News\n",
61
+ "- <b><font color='green'>2023/07/31: The ColabFold MSA server is back to normal. It was using older DB (UniRef30 2202/PDB70 220313) from 27th ~8:30 AM CEST to 31st ~11:10 AM CEST.</font></b>\n",
62
+ "- <b><font color='green'>2023/06/12: New databases! UniRef30 updated to 2023_02 and PDB to 230517. We now use PDB100 instead of PDB70 (see notes in the [main](https://colabfold.com) notebook).</font></b>\n",
63
+ "- <b><font color='green'>2023/06/12: We introduced a new default pairing strategy: Previously, for multimer predictions with more than 2 chains, we only pair if all sequences taxonomically match (\"complete\" pairing). The new default \"greedy\" strategy pairs any taxonomically matching subsets.</font></b>"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {
69
+ "id": "AwvIWN3HDyUJ",
70
+ "cellView": "form"
71
+ },
72
+ "source": [
73
+ "#@title Mount google drive\n",
74
+ "from google.colab import drive\n",
75
+ "drive.mount('/content/drive')\n",
76
+ "from sys import version_info\n",
77
+ "python_version = f\"{version_info.major}.{version_info.minor}\""
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {
85
+ "id": "kOblAo-xetgx",
86
+ "cellView": "form"
87
+ },
88
+ "source": [
89
+ "#@title Input protein sequence, then hit `Runtime` -> `Run all`\n",
90
+ "\n",
91
+ "input_dir = '/content/drive/MyDrive/input_fasta' #@param {type:\"string\"}\n",
92
+ "result_dir = '/content/drive/MyDrive/result' #@param {type:\"string\"}\n",
93
+ "\n",
94
+ "# number of models to use\n",
95
+ "#@markdown ---\n",
96
+ "#@markdown ### Advanced settings\n",
97
+ "msa_mode = \"MMseqs2 (UniRef+Environmental)\" #@param [\"MMseqs2 (UniRef+Environmental)\", \"MMseqs2 (UniRef only)\",\"single_sequence\",\"custom\"]\n",
98
+ "num_models = 5 #@param [1,2,3,4,5] {type:\"raw\"}\n",
99
+ "num_recycles = 3 #@param [1,3,6,12,24,48] {type:\"raw\"}\n",
100
+ "stop_at_score = 100 #@param {type:\"string\"}\n",
101
+ "#@markdown - early stop computing models once score > threshold (avg. plddt for \"structures\" and ptmscore for \"complexes\")\n",
102
+ "use_custom_msa = False\n",
103
+ "num_relax = 0 #@param [0, 1, 5] {type:\"raw\"}\n",
104
+ "use_amber = num_relax > 0\n",
105
+ "relax_max_iterations = 200 #@param [0,200,2000] {type:\"raw\"}\n",
106
+ "use_templates = False #@param {type:\"boolean\"}\n",
107
+ "do_not_overwrite_results = True #@param {type:\"boolean\"}\n",
108
+ "zip_results = False #@param {type:\"boolean\"}\n"
109
+ ],
110
+ "execution_count": null,
111
+ "outputs": []
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "metadata": {
116
+ "id": "iccGdbe_Pmt9",
117
+ "cellView": "form"
118
+ },
119
+ "source": [
120
+ "#@title Install dependencies\n",
121
+ "%%bash -s $use_amber $use_templates $python_version\n",
122
+ "\n",
123
+ "set -e\n",
124
+ "\n",
125
+ "USE_AMBER=$1\n",
126
+ "USE_TEMPLATES=$2\n",
127
+ "PYTHON_VERSION=$3\n",
128
+ "\n",
129
+ "if [ ! -f COLABFOLD_READY ]; then\n",
130
+ " # install dependencies\n",
131
+ " # We have to use \"--no-warn-conflicts\" because colab already has a lot preinstalled with requirements different to ours\n",
132
+ " pip install -q --no-warn-conflicts \"colabfold[alphafold-minus-jax] @ git+https://github.com/sokrypton/ColabFold\"\n",
133
+ " if [ -n \"${TPU_NAME}\" ]; then\n",
134
+ " pip install -q --no-warn-conflicts -U dm-haiku==0.0.10 jax==0.3.25\n",
135
+ " fi\n",
136
+ " ln -s /usr/local/lib/python3.*/dist-packages/colabfold colabfold\n",
137
+ " ln -s /usr/local/lib/python3.*/dist-packages/alphafold alphafold\n",
138
+ " # hack to fix TF crash\n",
139
+ " rm -f /usr/local/lib/python3.*/dist-packages/tensorflow/core/kernels/libtfkernel_sobol_op.so /usr/local/lib/python3.*/dist-packages/tensorflow/lite/python/*/*.so\n",
140
+ " touch COLABFOLD_READY\n",
141
+ "fi\n",
142
+ "\n",
143
+ "# Download params (~1min)\n",
144
+ "python -m colabfold.download\n",
145
+ "\n",
146
+ "# setup conda\n",
147
+ "if [ ${USE_AMBER} == \"True\" ] || [ ${USE_TEMPLATES} == \"True\" ]; then\n",
148
+ " if [ ! -f CONDA_READY ]; then\n",
149
+ " wget -qnc https://github.com/conda-forge/miniforge/releases/download/25.3.1-0/Miniforge3-25.3.1-0-Linux-x86_64.sh\n",
150
+ " bash Miniforge3-25.3.1-0-Linux-x86_64.sh -bfp /usr/local 2>&1 1>/dev/null\n",
151
+ " rm Miniforge3-25.3.1-0-Linux-x86_64.sh\n",
152
+ " conda config --set auto_update_conda false\n",
153
+ " touch CONDA_READY\n",
154
+ " fi\n",
155
+ "fi\n",
156
+ "# setup template search\n",
157
+ "if [ ${USE_TEMPLATES} == \"True\" ] && [ ! -f HH_READY ]; then\n",
158
+ " conda install -y -q -c conda-forge -c bioconda kalign2=2.04 hhsuite=3.3.0 python=\"${PYTHON_VERSION}\" 2>&1 1>/dev/null\n",
159
+ " touch HH_READY\n",
160
+ "fi\n",
161
+ "# setup openmm for amber refinement\n",
162
+ "if [ ${USE_AMBER} == \"True\" ] && [ ! -f AMBER_READY ]; then\n",
163
+ " conda install -y -q -c conda-forge openmm=8.2.0 python=\"${PYTHON_VERSION}\" pdbfixer 2>&1 1>/dev/null\n",
164
+ " touch AMBER_READY\n",
165
+ "fi"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {
173
+ "id": "hUYApPElB30u",
174
+ "cellView": "form"
175
+ },
176
+ "source": [
177
+ "#@title Run Prediction\n",
178
+ "\n",
179
+ "import sys\n",
180
+ "\n",
181
+ "from colabfold.batch import get_queries, run\n",
182
+ "from colabfold.download import default_data_dir\n",
183
+ "from colabfold.utils import setup_logging\n",
184
+ "from pathlib import Path\n",
185
+ "\n",
186
+ "# For some reason we need that to get pdbfixer to import\n",
187
+ "if use_amber and f\"/usr/local/lib/python{python_version}/site-packages/\" not in sys.path:\n",
188
+ " sys.path.insert(0, f\"/usr/local/lib/python{python_version}/site-packages/\")\n",
189
+ "\n",
190
+ "setup_logging(Path(result_dir).joinpath(\"log.txt\"))\n",
191
+ "\n",
192
+ "queries, is_complex = get_queries(input_dir)\n",
193
+ "run(\n",
194
+ " queries=queries,\n",
195
+ " result_dir=result_dir,\n",
196
+ " use_templates=use_templates,\n",
197
+ " num_relax=num_relax,\n",
198
+ " relax_max_iterations=relax_max_iterations,\n",
199
+ " msa_mode=msa_mode,\n",
200
+ " model_type=\"auto\",\n",
201
+ " num_models=num_models,\n",
202
+ " num_recycles=num_recycles,\n",
203
+ " model_order=[1, 2, 3, 4, 5],\n",
204
+ " is_complex=is_complex,\n",
205
+ " data_dir=default_data_dir,\n",
206
+ " keep_existing_results=do_not_overwrite_results,\n",
207
+ " rank_by=\"auto\",\n",
208
+ " pair_mode=\"unpaired+paired\",\n",
209
+ " stop_at_score=stop_at_score,\n",
210
+ " zip_results=zip_results,\n",
211
+ " user_agent=\"colabfold/google-colab-batch\",\n",
212
+ ")"
213
+ ],
214
+ "execution_count": null,
215
+ "outputs": []
216
+ },
217
+ {
218
+ "cell_type": "markdown",
219
+ "metadata": {
220
+ "id": "UGUBLzB3C6WN"
221
+ },
222
+ "source": [
223
+ "# Instructions <a name=\"Instructions\"></a>\n",
224
+ "**Quick start**\n",
225
+ "1. Upload your single fasta files to a folder in your Google Drive\n",
226
+ "2. Define path to the fold containing the fasta files (`input_dir`) define an outdir (`output_dir`)\n",
227
+ "3. Press \"Runtime\" -> \"Run all\".\n",
228
+ "\n",
229
+ "**Result zip file contents**\n",
230
+ "\n",
231
+ "At the end of the job a all results `jobname.result.zip` will be uploaded to your (`output_dir`) Google Drive. Each zip contains one protein.\n",
232
+ "\n",
233
+ "1. PDB formatted structures sorted by avg. pIDDT. (unrelaxed and relaxed if `use_amber` is enabled).\n",
234
+ "2. Plots of the model quality.\n",
235
+ "3. Plots of the MSA coverage.\n",
236
+ "4. Parameter log file.\n",
237
+ "5. A3M formatted input MSA.\n",
238
+ "6. BibTeX file with citations for all used tools and databases.\n",
239
+ "\n",
240
+ "\n",
241
+ "**Troubleshooting**\n",
242
+ "* Check that the runtime type is set to GPU at \"Runtime\" -> \"Change runtime type\".\n",
243
+ "* Try to restart the session \"Runtime\" -> \"Factory reset runtime\".\n",
244
+ "* Check your input sequence.\n",
245
+ "\n",
246
+ "**Known issues**\n",
247
+ "* Google Colab assigns different types of GPUs with varying amount of memory. Some might not have enough memory to predict the structure for a long sequence.\n",
248
+ "* Google Colab assigns different types of GPUs with varying amount of memory. Some might not have enough memory to predict the structure for a long sequence.\n",
249
+ "* Your browser can block the pop-up for downloading the result file. You can choose the `save_to_google_drive` option to upload to Google Drive instead or manually download the result file: Click on the little folder icon to the left, navigate to file: `jobname.result.zip`, right-click and select \\\"Download\\\" (see [screenshot](https://pbs.twimg.com/media/E6wRW2lWUAEOuoe?format=jpg&name=small)).\n",
250
+ "\n",
251
+ "**Limitations**\n",
252
+ "* Computing resources: Our MMseqs2 API can handle ~20-50k requests per day.\n",
253
+ "* MSAs: MMseqs2 is very precise and sensitive but might find less hits compared to HHblits/HMMer searched against BFD or Mgnify.\n",
254
+ "* We recommend to additionally use the full [AlphaFold2 pipeline](https://github.com/deepmind/alphafold).\n",
255
+ "\n",
256
+ "**Description of the plots**\n",
257
+ "* **Number of sequences per position** - We want to see at least 30 sequences per position, for best performance, ideally 100 sequences.\n",
258
+ "* **Predicted lDDT per position** - model confidence (out of 100) at each position. The higher the better.\n",
259
+ "* **Predicted Alignment Error** - For homooligomers, this could be a useful metric to assess how confident the model is about the interface. The lower the better.\n",
260
+ "\n",
261
+ "**Bugs**\n",
262
+ "- If you encounter any bugs, please report the issue to https://github.com/sokrypton/ColabFold/issues\n",
263
+ "\n",
264
+ "**License**\n",
265
+ "\n",
266
+ "The source code of ColabFold is licensed under [MIT](https://raw.githubusercontent.com/sokrypton/ColabFold/main/LICENSE). Additionally, this notebook uses AlphaFold2 source code and its parameters licensed under [Apache 2.0](https://raw.githubusercontent.com/deepmind/alphafold/main/LICENSE) and [CC BY 4.0](https://creativecommons.org/licenses/by-sa/4.0/) respectively. Read more about the AlphaFold license [here](https://github.com/deepmind/alphafold).\n",
267
+ "\n",
268
+ "**Acknowledgments**\n",
269
+ "- We thank the AlphaFold team for developing an excellent model and open sourcing the software.\n",
270
+ "\n",
271
+ "- Do-Yoon Kim for creating the ColabFold logo.\n",
272
+ "\n",
273
+ "- A colab by Sergey Ovchinnikov ([@sokrypton](https://twitter.com/sokrypton)), Milot Mirdita ([@milot_mirdita](https://twitter.com/milot_mirdita)) and Martin Steinegger ([@thesteinegger](https://twitter.com/thesteinegger)).\n"
274
+ ]
275
+ }
276
+ ]
277
+ }
data/beta/AlphaFold2_advanced.ipynb ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "AlphaFold2_advanced.ipynb",
7
+ "provenance": [],
8
+ "include_colab_link": true
9
+ },
10
+ "kernelspec": {
11
+ "display_name": "Python 3",
12
+ "name": "python3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ },
17
+ "accelerator": "GPU"
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {
23
+ "id": "view-in-github",
24
+ "colab_type": "text"
25
+ },
26
+ "source": [
27
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/beta/beta/AlphaFold2_advanced.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "markdown",
32
+ "metadata": {
33
+ "id": "pc5-mbsX9PZC"
34
+ },
35
+ "source": [
36
+ "# AlphaFold2_advanced\n",
37
+ "\n",
38
+ "This notebook modifies deepmind's [original notebook](https://colab.research.google.com/github/deepmind/alphafold/blob/main/notebooks/AlphaFold.ipynb) (**before AlphaFold-Multimer existed**) to add experimental support for modeling complexes (both homo and hetero-oligomers), option to run MMseqs2 instead of Jackhmmer for MSA generation and advanced functionality.\n",
39
+ "\n",
40
+ "See [ColabFold](https://github.com/sokrypton/ColabFold/) for other related notebooks\n",
41
+ "\n",
42
+ "[Mirdita M, Schütze K, Moriwaki Y, Heo L, Ovchinnikov S, Steinegger M. ColabFold: Making protein folding accessible to all.\n",
43
+ "*Nature Methods*, 2022](https://www.nature.com/articles/s41592-022-01488-1) \n",
44
+ "\n",
45
+ "**Limitations**\n",
46
+ "- This notebook does **NOT** use Templates.\n",
47
+ "- This notebook does **NOT** use AlphaFold-Multimer for complex (protein-protein) modeling.\n",
48
+ "- For a typical Google-Colab session, with a `16G-GPU`, the max total length is **1400 residues**. Sometimes a `12G-GPU` is assigned, in which the max length is ~1000 residues.\n",
49
+ "- Can I use the models for **Molecular Replacement**? Yes, but be CAREFUL, the bfactor column is populated with pLDDT confidence values (higher = better). Phenix.phaser expects a \"real\" bfactor, where (lower = better). See [post](https://twitter.com/cheshireminima/status/1423929241675120643) from Claudia Millán on how to process models."
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {
55
+ "id": "woIxeCPygt7K",
56
+ "cellView": "form"
57
+ },
58
+ "source": [
59
+ "#@title Install software\n",
60
+ "#@markdown Please execute this cell by pressing the _Play_ button \n",
61
+ "#@markdown on the left.\n",
62
+ "\n",
63
+ "# setup device\n",
64
+ "import warnings\n",
65
+ "warnings.simplefilter(action='ignore', category=FutureWarning)\n",
66
+ "\n",
67
+ "import os\n",
68
+ "import sys\n",
69
+ "import tensorflow as tf\n",
70
+ "import jax\n",
71
+ "\n",
72
+ "try:\n",
73
+ " # check if TPU is available\n",
74
+ " import jax.tools.colab_tpu\n",
75
+ " jax.tools.colab_tpu.setup_tpu()\n",
76
+ " print('Running on TPU')\n",
77
+ " DEVICE = \"tpu\"\n",
78
+ "except:\n",
79
+ " if jax.local_devices()[0].platform == 'cpu':\n",
80
+ " print(\"WARNING: no GPU detected, will be using CPU\")\n",
81
+ " DEVICE = \"cpu\"\n",
82
+ " else:\n",
83
+ " print('Running on GPU')\n",
84
+ " DEVICE = \"gpu\"\n",
85
+ " # disable GPU on tensorflow\n",
86
+ " tf.config.set_visible_devices([], 'GPU')\n",
87
+ "\n",
88
+ "from IPython.utils import io\n",
89
+ "import subprocess\n",
90
+ "import tqdm.notebook\n",
91
+ "\n",
92
+ "from sys import version_info \n",
93
+ "python_version = f\"{version_info.major}.{version_info.minor}\"\n",
94
+ "\n",
95
+ "install_jackhmmer = True\n",
96
+ "GIT_REPO = 'https://github.com/deepmind/alphafold'\n",
97
+ "SOURCE_URL = 'https://storage.googleapis.com/alphafold/alphafold_params_2021-07-14.tar'\n",
98
+ "PARAMS_DIR = './alphafold/data/params'\n",
99
+ "PARAMS_PATH = os.path.join(PARAMS_DIR, os.path.basename(SOURCE_URL))\n",
100
+ "TQDM_BAR_FORMAT = '{l_bar}{bar}| {n_fmt}/{total_fmt} [elapsed: {elapsed} remaining: {remaining}]'\n",
101
+ "TMP_DIR = \"tmp\"\n",
102
+ "os.makedirs(TMP_DIR, exist_ok=True)\n",
103
+ "\n",
104
+ "# if not already installed\n",
105
+ "total = 55\n",
106
+ "with tqdm.notebook.tqdm(total=total, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
107
+ " if not os.path.isdir(\"alphafold\"):\n",
108
+ " # download alphafold code\n",
109
+ " os.system(f\"git clone {GIT_REPO} alphafold; cd alphafold; git checkout 1d43aaff941c84dc56311076b58795797e49107b\")\n",
110
+ " os.system(f\"git clone https://github.com/sokrypton/ColabFold.git\")\n",
111
+ "\n",
112
+ " # apply patches\n",
113
+ " os.system(f\"patch -u alphafold/alphafold/model/model.py -i ColabFold/beta/model.patch\")\n",
114
+ " os.system(f\"patch -u alphafold/alphafold/model/mapping.py -i ColabFold/beta/mapping.patch\")\n",
115
+ " os.system(f\"patch -u alphafold/alphafold/model/modules.py -i ColabFold/beta/modules.patch\")\n",
116
+ " os.system(f\"patch -u alphafold/alphafold/model/folding.py -i ColabFold/beta/folding.patch\")\n",
117
+ " os.system(f\"patch -u alphafold/alphafold/model/config.py -i ColabFold/beta/config.patch\")\n",
118
+ " # apply multi-chain patch from Lim Heo @huhlim\n",
119
+ " os.system(f\"patch -u alphafold/alphafold/common/protein.py -i ColabFold/beta/protein.patch\")\n",
120
+ " pbar.update(4)\n",
121
+ "\n",
122
+ " os.system(f\"pip install biopython dm-haiku==0.0.9 ml-collections py3Dmol\")\n",
123
+ " pbar.update(6)\n",
124
+ "\n",
125
+ " # download model params (speedup from kaczmarj)\n",
126
+ " os.system(f\"mkdir --parents {PARAMS_DIR}\")\n",
127
+ " os.system(f\"curl -fsSL {SOURCE_URL} | tar x -C {PARAMS_DIR}\")\n",
128
+ " pbar.update(14+27)\n",
129
+ "\n",
130
+ " # install hhsuite\n",
131
+ " os.system(f\"curl -fsSL https://github.com/soedinglab/hh-suite/releases/download/v3.3.0/hhsuite-3.3.0-SSE2-Linux.tar.gz | tar xz -C {TMP_DIR}/\")\n",
132
+ "\n",
133
+ " # install jackhmmer\n",
134
+ " if install_jackhmmer:\n",
135
+ " os.system(f\"sudo apt install --quiet --yes hmmer\")\n",
136
+ " pbar.update(3)\n",
137
+ "\n",
138
+ " # create a ramdisk to store a database chunk to make Jackhmmer run fast.\n",
139
+ " os.system(f\"sudo mkdir -m 777 --parents /tmp/ramdisk\")\n",
140
+ " os.system(f\"sudo mount -t tmpfs -o size=9G ramdisk /tmp/ramdisk\")\n",
141
+ " pbar.update(1)\n",
142
+ "\n",
143
+ " else:\n",
144
+ " pbar.update(4)\n",
145
+ "\n",
146
+ " else:\n",
147
+ " pbar.update(55)\n",
148
+ "\n",
149
+ "########################################################################################\n",
150
+ "# --- Python imports ---\n",
151
+ "if 'alphafold' not in sys.path:\n",
152
+ " sys.path.append('alphafold')\n",
153
+ "if 'ColabFold/beta' not in sys.path:\n",
154
+ " sys.path.append('ColabFold/beta')\n",
155
+ "\n",
156
+ "if f\"{TMP_DIR}/bin\" not in os.environ['PATH']:\n",
157
+ " os.environ['PATH'] += f\":{TMP_DIR}/bin:{TMP_DIR}/scripts\"\n",
158
+ "\n",
159
+ "import colabfold as cf\n",
160
+ "import colabfold_alphafold as cf_af\n",
161
+ "\n",
162
+ "import json\n",
163
+ "import matplotlib.pyplot as plt\n",
164
+ "import numpy as np\n",
165
+ "\n",
166
+ "try:\n",
167
+ " from google.colab import files\n",
168
+ " IN_COLAB = True\n",
169
+ "except:\n",
170
+ " IN_COLAB = False"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {
178
+ "id": "rowN0bVYLe9n",
179
+ "cellView": "form"
180
+ },
181
+ "source": [
182
+ "#@title Enter the amino acid sequence to fold ⬇️\n",
183
+ "import re\n",
184
+ "\n",
185
+ "# define sequence\n",
186
+ "sequence = 'PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK' #@param {type:\"string\"}\n",
187
+ "jobname = \"test\" #@param {type:\"string\"}\n",
188
+ "homooligomer = \"1\" #@param {type:\"string\"}\n",
189
+ "\n",
190
+ "#@markdown - `sequence` Specify protein sequence to be modelled.\n",
191
+ "#@markdown - Use `/` to specify intra-protein chainbreaks (for trimming regions within protein).\n",
192
+ "#@markdown - Use `:` to specify inter-protein chainbreaks (for modeling protein-protein hetero-complexes).\n",
193
+ "#@markdown - For example, sequence `AC/DE:FGH` will be modelled as polypeptides: `AC`, `DE` and `FGH`. A seperate MSA will be generates for `ACDE` and `FGH`.\n",
194
+ "#@markdown If `pair_msa` is enabled, `ACDE`'s MSA will be paired with `FGH`'s MSA.\n",
195
+ "#@markdown - `homooligomer` Define number of copies in a homo-oligomeric assembly.\n",
196
+ "#@markdown - Use `:` to specify different homooligomeric state (copy numer) for each component of the complex. \n",
197
+ "#@markdown - For example, **sequence:**`ABC:DEF`, **homooligomer:** `2:1`, the first protein `ABC` will be modeled as a homodimer (2 copies) and second `DEF` a monomer (1 copy).\n",
198
+ "\n",
199
+ "I = cf_af.prep_inputs(sequence, jobname, homooligomer, clean=IN_COLAB)"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": []
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "metadata": {
207
+ "id": "ITcPnLkLuDDE",
208
+ "cellView": "form"
209
+ },
210
+ "source": [
211
+ "#@title Search against genetic databases\n",
212
+ "#@markdown Once this cell has been executed, you will see\n",
213
+ "#@markdown statistics about the multiple sequence alignment \n",
214
+ "#@markdown (MSA) that will be used by AlphaFold. In particular, \n",
215
+ "#@markdown you’ll see how well each residue is covered by similar \n",
216
+ "#@markdown sequences in the MSA.\n",
217
+ "#@markdown (Note that the search against databases and the actual prediction can take some time, from minutes to hours, depending on the length of the protein and what type of GPU you are allocated by Colab.)\n",
218
+ "\n",
219
+ "#@markdown ---\n",
220
+ "msa_method = \"mmseqs2\" #@param [\"mmseqs2\",\"jackhmmer\",\"single_sequence\",\"precomputed\"]\n",
221
+ "#@markdown - `mmseqs2` - FAST method from [ColabFold](https://github.com/sokrypton/ColabFold)\n",
222
+ "#@markdown - `jackhmmer` - default method from Deepmind (SLOW, but may find more/less sequences).\n",
223
+ "#@markdown - `single_sequence` - use single sequence input\n",
224
+ "#@markdown - `precomputed` If you have previously run this notebook and saved the results,\n",
225
+ "#@markdown you can skip this step by uploading \n",
226
+ "#@markdown the previously generated `prediction_?????/msa.pickle`\n",
227
+ "\n",
228
+ "\n",
229
+ "#@markdown ---\n",
230
+ "#@markdown **custom msa options**\n",
231
+ "add_custom_msa = False #@param {type:\"boolean\"}\n",
232
+ "msa_format = \"fas\" #@param [\"fas\",\"a2m\",\"a3m\",\"sto\",\"psi\",\"clu\"]\n",
233
+ "#@markdown - `add_custom_msa` - If enabled, you'll get an option to upload your custom MSA in the specified `msa_format`. Note: Your MSA will be supplemented with those from 'mmseqs2' or 'jackhmmer', unless `msa_method` is set to 'single_sequence'.\n",
234
+ "\n",
235
+ "#@markdown ---\n",
236
+ "#@markdown **pair msa options**\n",
237
+ "\n",
238
+ "#@markdown Experimental option for protein complexes. Pairing currently only supported for proteins in same operon (prokaryotic genomes).\n",
239
+ "pair_mode = \"unpaired\" #@param [\"unpaired\",\"unpaired+paired\",\"paired\"] {type:\"string\"}\n",
240
+ "#@markdown - `unpaired` - generate seperate MSA for each protein.\n",
241
+ "#@markdown - `unpaired+paired` - attempt to pair sequences from the same operon within the genome. \n",
242
+ "#@markdown - `paired` - only use sequences that were sucessfully paired.\n",
243
+ "\n",
244
+ "#@markdown Options to prefilter each MSA before pairing. (It might help if there are any paralogs in the complex.)\n",
245
+ "pair_cov = 50 #@param [0,25,50,75,90] {type:\"raw\"}\n",
246
+ "pair_qid = 20 #@param [0,15,20,30,40,50] {type:\"raw\"}\n",
247
+ "#@markdown - `pair_cov` prefilter each MSA to minimum coverage with query (%) before pairing.\n",
248
+ "#@markdown - `pair_qid` prefilter each MSA to minimum sequence identity with query (%) before pairing.\n",
249
+ "\n",
250
+ "# --- Search against genetic databases ---\n",
251
+ "\n",
252
+ "I = cf_af.prep_msa(I, msa_method, add_custom_msa, msa_format,\n",
253
+ " pair_mode, pair_cov, pair_qid, TMP_DIR=TMP_DIR)\n",
254
+ "mod_I = I\n",
255
+ "\n",
256
+ "if len(I[\"msas\"][0]) > 1:\n",
257
+ " plt = cf.plot_msas(I[\"msas\"], I[\"ori_sequence\"])\n",
258
+ " plt.savefig(os.path.join(I[\"output_dir\"],\"msa_coverage.png\"), bbox_inches = 'tight', dpi=200)\n",
259
+ " plt.show()"
260
+ ],
261
+ "execution_count": null,
262
+ "outputs": []
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "metadata": {
267
+ "id": "sYIjwa1VXeeW",
268
+ "cellView": "form"
269
+ },
270
+ "source": [
271
+ "#@title Filter options (optional)\n",
272
+ "trim = \"\" #@param {type:\"string\"}\n",
273
+ "trim_inverse = False #@param {type:\"boolean\"}\n",
274
+ "#@markdown - Use `trim` to specify regions to trim. For example: `trim:5-9,20` will remove positions 5,6,7,8,9 and 20. \n",
275
+ "#@markdown - For complexes, you can use `trim:A1-A3,B5-B7` to remove positions 1,2,3 in 1st protein and positions 5,6,7 in 2nd protein.\n",
276
+ "#@markdown - Note: This function is 1-indexed, meaning the first position is 1, not 0.\n",
277
+ "#@markdown - To specify regions to keep instead of trim, enable `trim_inverse`\n",
278
+ "cov = 0 #@param [0,25,50,75,90,95] {type:\"raw\"}\n",
279
+ "qid = 0 #@param [0,15,20,25,30,40,50] {type:\"raw\"}\n",
280
+ "#@markdown - `cov` minimum coverage with query (%)\n",
281
+ "#@markdown - `qid` minimum sequence identity with query (%)\n",
282
+ "\n",
283
+ "mod_I = cf_af.prep_filter(I, trim, trim_inverse, cov, qid)\n",
284
+ "\n",
285
+ "if I[\"msas\"] != mod_I[\"msas\"]:\n",
286
+ " plt.figure(figsize=(16,5),dpi=100)\n",
287
+ " plt.subplot(1,2,1)\n",
288
+ " plt.title(\"Sequence coverage (Before)\")\n",
289
+ " cf.plot_msas(I[\"msas\"], I[\"ori_sequence\"], return_plt=False)\n",
290
+ " plt.subplot(1,2,2)\n",
291
+ " plt.title(\"Sequence coverage (After)\")\n",
292
+ " cf.plot_msas(mod_I[\"msas\"], mod_I[\"ori_sequence\"], return_plt=False)\n",
293
+ " plt.savefig(os.path.join(I[\"output_dir\"],\"msa_coverage.filtered.png\"), bbox_inches = 'tight', dpi=200)\n",
294
+ " plt.show()"
295
+ ],
296
+ "execution_count": null,
297
+ "outputs": []
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "metadata": {
302
+ "id": "bQe3KeyTcv0n",
303
+ "cellView": "form"
304
+ },
305
+ "source": [
306
+ "#@title Run alphafold\n",
307
+ "num_relax = \"None\"\n",
308
+ "rank_by = \"pLDDT\" #@param [\"pLDDT\",\"pTMscore\"]\n",
309
+ "use_turbo = True #@param {type:\"boolean\"}\n",
310
+ "max_msa = \"512:1024\" #@param [\"512:1024\", \"256:512\", \"128:256\", \"64:128\", \"32:64\"]\n",
311
+ "max_msa_clusters, max_extra_msa = [int(x) for x in max_msa.split(\":\")]\n",
312
+ "\n",
313
+ "#@markdown - `rank_by` specify metric to use for ranking models (For protein-protein complexes, we recommend pTMscore)\n",
314
+ "#@markdown - `use_turbo` introduces a few modifications (compile once, swap params, adjust max_msa) to speedup and reduce memory requirements. Disable for default behavior.\n",
315
+ "#@markdown - `max_msa` defines: `max_msa_clusters:max_extra_msa` number of sequences to use. When adjusting after GPU crash, be sure to `Runtime` → `Restart runtime`. (Lowering will reduce GPU requirements, but may result in poor model quality. This option ignored if `use_turbo` is disabled)\n",
316
+ "show_images = True #@param {type:\"boolean\"}\n",
317
+ "#@markdown - `show_images` To make things more exciting we show images of the predicted structures as they are being generated. (WARNING: the order of images displayed does not reflect any ranking).\n",
318
+ "\n",
319
+ "#@markdown ---\n",
320
+ "#@markdown **sampling options**\n",
321
+ "\n",
322
+ "#@markdown There are two stochastic parts of the pipeline. Within the feature generation (choice of cluster centers) and within the model (dropout). \n",
323
+ "#@markdown To get structure diversity, you can iterate through a fixed number of random_seeds (using `num_samples`) and/or enable dropout (using `is_training`).\n",
324
+ "\n",
325
+ "num_models = 5 #@param [1,2,3,4,5] {type:\"raw\"}\n",
326
+ "use_ptm = True #@param {type:\"boolean\"}\n",
327
+ "num_ensemble = 1 #@param [1,2,4,8] {type:\"raw\"}\n",
328
+ "max_recycles = 3 #@param [0,1,3,6,12,24,48] {type:\"raw\"}\n",
329
+ "is_training = False #@param {type:\"boolean\"}\n",
330
+ "num_samples = 1 #@param [1,2,4,8,16,32] {type:\"raw\"}\n",
331
+ "#@markdown - `num_models` specify how many model params to try. (5 recommended)\n",
332
+ "#@markdown - `use_ptm` uses Deepmind's `ptm` finetuned model parameters to get PAE per structure. Disable to use the original model params. (Disabling may give alternative structures.)\n",
333
+ "#@markdown - `num_ensemble` the trunk of the network is run multiple times with different random choices for the MSA cluster centers. (`1`=`default`, `8`=`casp14 setting`)\n",
334
+ "#@markdown - `max_recycles` controls the maximum number of times the structure is fed back into the neural network for refinement. (3 recommended)\n",
335
+ "#@markdown - `is_training` enables the stochastic part of the model (dropout), when coupled with `num_samples` can be used to \"sample\" a diverse set of structures.\n",
336
+ "#@markdown - `num_samples` number of random_seeds to try.\n",
337
+ "subsample_msa = True #@param {type:\"boolean\"}\n",
338
+ "#@markdown - `subsample_msa` subsample large MSA to `3E7/length` sequences to avoid crashing the preprocessing protocol. (This option ignored if `use_turbo` is disabled.)\n",
339
+ "\n",
340
+ "if not use_ptm and rank_by == \"pTMscore\":\n",
341
+ " print(\"WARNING: models will be ranked by pLDDT, 'use_ptm' is needed to compute pTMscore\")\n",
342
+ " rank_by = \"pLDDT\"\n",
343
+ "\n",
344
+ "# prep input features\n",
345
+ "feature_dict = cf_af.prep_feats(mod_I, clean=IN_COLAB)\n",
346
+ "Ls_plot = feature_dict[\"Ls\"]\n",
347
+ "\n",
348
+ "# prep model options\n",
349
+ "opt = {\"N\":len(feature_dict[\"msa\"]),\n",
350
+ " \"L\":len(feature_dict[\"residue_index\"]),\n",
351
+ " \"use_ptm\":use_ptm,\n",
352
+ " \"use_turbo\":use_turbo,\n",
353
+ " \"max_recycles\":max_recycles,\n",
354
+ " \"tol\":0.0,\n",
355
+ " \"num_ensemble\":num_ensemble,\n",
356
+ " \"max_msa_clusters\":max_msa_clusters,\n",
357
+ " \"max_extra_msa\":max_extra_msa,\n",
358
+ " \"is_training\":is_training}\n",
359
+ "\n",
360
+ "if use_turbo:\n",
361
+ " if \"runner\" in dir():\n",
362
+ " # only recompile if options changed\n",
363
+ " runner = cf_af.prep_model_runner(opt, old_runner=runner)\n",
364
+ " else:\n",
365
+ " runner = cf_af.prep_model_runner(opt)\n",
366
+ "else:\n",
367
+ " runner = None\n",
368
+ "\n",
369
+ "###########################\n",
370
+ "# run alphafold\n",
371
+ "###########################\n",
372
+ "outs, model_rank = cf_af.run_alphafold(feature_dict, opt, runner, num_models, num_samples, subsample_msa,\n",
373
+ " rank_by=rank_by, show_images=show_images)\n"
374
+ ],
375
+ "execution_count": null,
376
+ "outputs": []
377
+ },
378
+ {
379
+ "cell_type": "code",
380
+ "metadata": {
381
+ "id": "PnMog4kHUztt",
382
+ "cellView": "form"
383
+ },
384
+ "source": [
385
+ "#@title Refine structures with Amber-Relax (optional)\n",
386
+ "#@markdown If side-chain bond geometry is important to you, enable Amber-Relax by specifying how many top ranked structures you want relaxed. By default, we disable Amber-Relax since it barely moves the main-chain (backbone) structure and can overall double the runtime.\n",
387
+ "num_relax = \"None\" #@param [\"None\", \"Top1\", \"Top5\", \"All\"] {type:\"string\"}\n",
388
+ "if num_relax == \"None\":\n",
389
+ " num_relax = 0\n",
390
+ "elif num_relax == \"Top1\":\n",
391
+ " num_relax = 1\n",
392
+ "elif num_relax == \"Top5\":\n",
393
+ " num_relax = 5\n",
394
+ "else:\n",
395
+ " num_relax = num_models * num_samples\n",
396
+ "\n",
397
+ "#@markdown - `num_relax` specify how many of the top ranked structures to relax\n",
398
+ "if num_relax > 0 and not os.path.isfile(\"stereo_chemical_props.txt\"):\n",
399
+ " try:\n",
400
+ " total = 45\n",
401
+ " with tqdm.notebook.tqdm(total=total, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
402
+ " pbar.set_description(f'INSTALL AMBER')\n",
403
+ " with io.capture_output() as captured:\n",
404
+ " # Install OpenMM and pdbfixer.\n",
405
+ " %shell rm -rf /opt/conda\n",
406
+ " %shell wget -q -P /tmp \\\n",
407
+ " https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \\\n",
408
+ " && bash /tmp/Miniconda3-latest-Linux-x86_64.sh -b -p /opt/conda \\\n",
409
+ " && rm /tmp/Miniconda3-latest-Linux-x86_64.sh\n",
410
+ " pbar.update(4)\n",
411
+ "\n",
412
+ " PATH=%env PATH\n",
413
+ " %env PATH=/opt/conda/bin:{PATH}\n",
414
+ " %shell conda install -qy conda==4.13.0 \\\n",
415
+ " && conda install -qy -c conda-forge \\\n",
416
+ " python={python_version} \\\n",
417
+ " openmm=7.5.1 \\\n",
418
+ " pdbfixer\n",
419
+ " pbar.update(40)\n",
420
+ "\n",
421
+ " %shell wget -q -P /content \\\n",
422
+ " https://git.scicore.unibas.ch/schwede/openstructure/-/raw/7102c63615b64735c4941278d92b554ec94415f8/modules/mol/alg/src/stereo_chemical_props.txt\n",
423
+ " pbar.update(1)\n",
424
+ " %shell mkdir -p /content/alphafold/common\n",
425
+ " %shell cp -f /content/stereo_chemical_props.txt /content/alphafold/common\n",
426
+ "\n",
427
+ " # Apply OpenMM patch.\n",
428
+ " %shell pushd /opt/conda/lib/python{python_version}/site-packages/ && \\\n",
429
+ " patch -p0 < /content/alphafold/docker/openmm.patch && \\\n",
430
+ " popd\n",
431
+ "\n",
432
+ " except subprocess.CalledProcessError:\n",
433
+ " print(captured)\n",
434
+ " raise\n",
435
+ "\n",
436
+ "if num_relax > 0:\n",
437
+ " if \"relax\" not in dir():\n",
438
+ " # add conda environment to path\n",
439
+ " sys.path.append(f\"/opt/conda/lib/python{python_version}/site-packages\")\n",
440
+ " if 'LC_ALL' in os.environ:\n",
441
+ " del os.environ['LC_ALL']\n",
442
+ " \n",
443
+ " # import libraries\n",
444
+ " from alphafold.relax import relax\n",
445
+ " from alphafold.relax import utils\n",
446
+ "\n",
447
+ " with tqdm.notebook.tqdm(total=num_relax, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
448
+ " pbar.set_description(f'AMBER relaxation')\n",
449
+ " for n,key in enumerate(model_rank):\n",
450
+ " if n < num_relax:\n",
451
+ " prefix = f\"rank_{n+1}_{key}\" \n",
452
+ " pred_output_path = os.path.join(I[\"output_dir\"],f'{prefix}_relaxed.pdb')\n",
453
+ " if not os.path.isfile(pred_output_path):\n",
454
+ " amber_relaxer = relax.AmberRelaxation(\n",
455
+ " max_iterations=0,\n",
456
+ " tolerance=2.39,\n",
457
+ " stiffness=10.0,\n",
458
+ " exclude_residues=[],\n",
459
+ " max_outer_iterations=20)\n",
460
+ " relaxed_pdb_lines, _, _ = amber_relaxer.process(prot=outs[key][\"unrelaxed_protein\"]) \n",
461
+ " with open(pred_output_path, 'w') as f:\n",
462
+ " f.write(relaxed_pdb_lines)\n",
463
+ " pbar.update(n=1)"
464
+ ],
465
+ "execution_count": null,
466
+ "outputs": []
467
+ },
468
+ {
469
+ "cell_type": "code",
470
+ "metadata": {
471
+ "id": "KAZj6CBZTkJM",
472
+ "cellView": "form"
473
+ },
474
+ "source": [
475
+ "#@title Display 3D structure (optional) {run: \"auto\"}\n",
476
+ "rank_num = 1 #@param [\"1\", \"2\", \"3\", \"4\", \"5\"] {type:\"raw\"}\n",
477
+ "color = \"lDDT\" #@param [\"chain\", \"lDDT\", \"rainbow\"]\n",
478
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
479
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
480
+ "\n",
481
+ "key = model_rank[rank_num-1]\n",
482
+ "prefix = f\"rank_{rank_num}_{key}\" \n",
483
+ "pred_output_path = os.path.join(I[\"output_dir\"],f'{prefix}_relaxed.pdb') \n",
484
+ "if not os.path.isfile(pred_output_path):\n",
485
+ " pred_output_path = os.path.join(I[\"output_dir\"],f'{prefix}_unrelaxed.pdb') \n",
486
+ "\n",
487
+ "cf.show_pdb(pred_output_path, show_sidechains, show_mainchains, color, Ls=Ls_plot).show()\n",
488
+ "if color == \"lDDT\": cf.plot_plddt_legend().show() \n",
489
+ "if use_ptm:\n",
490
+ " cf.plot_confidence(outs[key][\"plddt\"], outs[key][\"pae\"], Ls=Ls_plot).show()\n",
491
+ "else:\n",
492
+ " cf.plot_confidence(outs[key][\"plddt\"], Ls=Ls_plot).show()"
493
+ ],
494
+ "execution_count": null,
495
+ "outputs": []
496
+ },
497
+ {
498
+ "cell_type": "code",
499
+ "metadata": {
500
+ "id": "XzK2Wve12GCk",
501
+ "cellView": "form"
502
+ },
503
+ "source": [
504
+ "#@title Extra outputs (optional)\n",
505
+ "dpi = 100#@param {type:\"integer\"}\n",
506
+ "save_to_txt = True #@param {type:\"boolean\"}\n",
507
+ "save_pae_json = True #@param {type:\"boolean\"}\n",
508
+ "#@markdown - save data used to generate contact and distogram plots below to text file (pae values can be found in json file if `use_ptm` is enabled)\n",
509
+ "\n",
510
+ "if use_ptm:\n",
511
+ " print(\"predicted alignment error\")\n",
512
+ " cf.plot_paes([outs[k][\"pae\"] for k in model_rank], Ls=Ls_plot, dpi=dpi)\n",
513
+ " plt.savefig(os.path.join(I[\"output_dir\"],f'predicted_alignment_error.png'), bbox_inches = 'tight', dpi=np.maximum(200,dpi))\n",
514
+ " plt.show()\n",
515
+ "\n",
516
+ "print(\"predicted contacts\")\n",
517
+ "cf.plot_adjs([outs[k][\"adj\"] for k in model_rank], Ls=Ls_plot, dpi=dpi)\n",
518
+ "plt.savefig(os.path.join(I[\"output_dir\"],f'predicted_contacts.png'), bbox_inches = 'tight', dpi=np.maximum(200,dpi))\n",
519
+ "plt.show()\n",
520
+ "\n",
521
+ "print(\"predicted distogram\")\n",
522
+ "cf.plot_dists([outs[k][\"dists\"] for k in model_rank], Ls=Ls_plot, dpi=dpi)\n",
523
+ "plt.savefig(os.path.join(I[\"output_dir\"],f'predicted_distogram.png'), bbox_inches = 'tight', dpi=np.maximum(200,dpi))\n",
524
+ "plt.show()\n",
525
+ "\n",
526
+ "print(\"predicted LDDT\")\n",
527
+ "cf.plot_plddts([outs[k][\"plddt\"] for k in model_rank], Ls=Ls_plot, dpi=dpi)\n",
528
+ "plt.savefig(os.path.join(I[\"output_dir\"],f'predicted_LDDT.png'), bbox_inches = 'tight', dpi=np.maximum(200,dpi))\n",
529
+ "plt.show()\n",
530
+ "\n",
531
+ "def do_save_to_txt(filename, adj, dists, sequence):\n",
532
+ " adj = np.asarray(adj)\n",
533
+ " dists = np.asarray(dists)\n",
534
+ " L = len(adj)\n",
535
+ " with open(filename,\"w\") as out:\n",
536
+ " out.write(\"i\\tj\\taa_i\\taa_j\\tp(cbcb<8)\\tmaxdistbin\\n\")\n",
537
+ " for i in range(L):\n",
538
+ " for j in range(i+1,L):\n",
539
+ " if dists[i][j] < 21.68 or adj[i][j] >= 0.001:\n",
540
+ " line = f\"{i}\\t{j}\\t{sequence[i]}\\t{sequence[j]}\\t{adj[i][j]:.3f}\"\n",
541
+ " line += f\"\\t>{dists[i][j]:.2f}\" if dists[i][j] == 21.6875 else f\"\\t{dists[i][j]:.2f}\"\n",
542
+ " out.write(f\"{line}\\n\")\n",
543
+ "\n",
544
+ "for n,key in enumerate(model_rank):\n",
545
+ " if save_to_txt:\n",
546
+ " txt_filename = os.path.join(I[\"output_dir\"],f'rank_{n+1}_{key}.raw.txt')\n",
547
+ " do_save_to_txt(txt_filename,\n",
548
+ " outs[key][\"adj\"],\n",
549
+ " outs[key][\"dists\"],\n",
550
+ " mod_I[\"full_sequence\"])\n",
551
+ "\n",
552
+ " if use_ptm and save_pae_json:\n",
553
+ " pae = outs[key][\"pae\"]\n",
554
+ " max_pae = pae.max()\n",
555
+ " # Save pLDDT and predicted aligned error (if it exists)\n",
556
+ " pae_output_path = os.path.join(I[\"output_dir\"],f'rank_{n+1}_{key}_pae.json')\n",
557
+ " # Save predicted aligned error in the same format as the AF EMBL DB\n",
558
+ " rounded_errors = np.round(np.asarray(pae), decimals=1)\n",
559
+ " indices = np.indices((len(rounded_errors), len(rounded_errors))) + 1\n",
560
+ " indices_1 = indices[0].flatten().tolist()\n",
561
+ " indices_2 = indices[1].flatten().tolist()\n",
562
+ " pae_data = json.dumps([{\n",
563
+ " 'residue1': indices_1,\n",
564
+ " 'residue2': indices_2,\n",
565
+ " 'distance': rounded_errors.flatten().tolist(),\n",
566
+ " 'max_predicted_aligned_error': max_pae.item()\n",
567
+ " }],\n",
568
+ " indent=None,\n",
569
+ " separators=(',', ':'))\n",
570
+ " with open(pae_output_path, 'w') as f:\n",
571
+ " f.write(pae_data)"
572
+ ],
573
+ "execution_count": null,
574
+ "outputs": []
575
+ },
576
+ {
577
+ "cell_type": "code",
578
+ "metadata": {
579
+ "cellView": "form",
580
+ "id": "xkCcitL6qdNS"
581
+ },
582
+ "source": [
583
+ "#@title Animate outputs (optional)\n",
584
+ "dpi = 100#@param {type:\"integer\"}\n",
585
+ "use_pca = True #@param {type:\"boolean\"}\n",
586
+ "color_by_plddt = False #@param {type:\"boolean\"}\n",
587
+ "#@markdown - `use_pca` - use the first principle component to determine order of animation frames\n",
588
+ "\n",
589
+ "\n",
590
+ "import matplotlib\n",
591
+ "from matplotlib import animation\n",
592
+ "from IPython.display import HTML\n",
593
+ "from sklearn.decomposition import PCA\n",
594
+ "\n",
595
+ "def mk_animation(positions, labels, plddt, ref=0, Ls=None, line_w=2.0, dpi=100,color_by_plddt=False):\n",
596
+ "\n",
597
+ " def ca_align_to_last(positions, ref):\n",
598
+ " def align(P, Q):\n",
599
+ " if Ls is None or len(Ls) == 1:\n",
600
+ " P_,Q_ = P,Q\n",
601
+ " else:\n",
602
+ " # align relative to first chain\n",
603
+ " P_,Q_ = P[:Ls[0]],Q[:Ls[0]]\n",
604
+ " p = P_ - P_.mean(0,keepdims=True)\n",
605
+ " q = Q_ - Q_.mean(0,keepdims=True)\n",
606
+ " return ((P - P_.mean(0,keepdims=True)) @ cf.kabsch(p,q)) + Q_.mean(0,keepdims=True)\n",
607
+ " \n",
608
+ " pos = positions[ref,:,1,:] - positions[ref,:,1,:].mean(0,keepdims=True)\n",
609
+ " best_2D_view = pos @ cf.kabsch(pos,pos,return_v=True)\n",
610
+ "\n",
611
+ " new_positions = []\n",
612
+ " for i in range(len(positions)):\n",
613
+ " new_positions.append(align(positions[i,:,1,:],best_2D_view))\n",
614
+ " return np.asarray(new_positions)\n",
615
+ "\n",
616
+ " # align to reference \n",
617
+ " pos = ca_align_to_last(positions, ref)\n",
618
+ "\n",
619
+ " fig, (ax1) = plt.subplots(1)\n",
620
+ " fig.set_figwidth(5)\n",
621
+ " fig.set_figheight(5)\n",
622
+ " fig.set_dpi(dpi)\n",
623
+ "\n",
624
+ " xy_min = pos[...,:2].min() - 1\n",
625
+ " xy_max = pos[...,:2].max() + 1\n",
626
+ "\n",
627
+ " for ax in [ax1]:\n",
628
+ " ax.set_xlim(xy_min, xy_max)\n",
629
+ " ax.set_ylim(xy_min, xy_max)\n",
630
+ " ax.axis(False)\n",
631
+ "\n",
632
+ " ims=[]\n",
633
+ " for l,pos_,plddt_ in zip(labels,pos,plddt):\n",
634
+ " if color_by_plddt:\n",
635
+ " img = cf.plot_pseudo_3D(pos_, c=plddt_, cmin=50, cmax=90, line_w=line_w, ax=ax1) \n",
636
+ " elif Ls is None or len(Ls) == 1:\n",
637
+ " img = cf.plot_pseudo_3D(pos_, ax=ax1, line_w=line_w)\n",
638
+ " else:\n",
639
+ " c = np.concatenate([[n]*L for n,L in enumerate(Ls)])\n",
640
+ " img = cf.plot_pseudo_3D(pos_, c=c, cmap=cf.pymol_cmap, cmin=0, cmax=39, line_w=line_w, ax=ax1)\n",
641
+ " ims.append([cf.add_text(f\"{l}\", ax1),img])\n",
642
+ " \n",
643
+ " ani = animation.ArtistAnimation(fig, ims, blit=True, interval=120)\n",
644
+ " plt.close()\n",
645
+ " return ani.to_html5_video()\n",
646
+ "\n",
647
+ "labels = np.array([k for k in outs])\n",
648
+ "pos = np.array([outs[k][\"unrelaxed_protein\"].atom_positions for k in labels])\n",
649
+ "plddt = np.asarray([outs[k][\"plddt\"] for k in outs.keys()])\n",
650
+ "if use_pca:\n",
651
+ " pos_ca = pos[:,:,1,:]\n",
652
+ " if Ls_plot is not None and len(Ls_plot) > 1:\n",
653
+ " pos_ca = pos_ca[:,:Ls_plot[0]]\n",
654
+ " i,j = np.triu_indices(pos_ca.shape[1],k=1)\n",
655
+ " pos_ca_dm = np.sqrt(np.square(pos_ca[:,None,:,:] - pos_ca[:,:,None]).sum(-1))[:,i,j]\n",
656
+ " pc = PCA(1).fit_transform(pos_ca_dm)[:,0].argsort()\n",
657
+ " pos = pos[pc]\n",
658
+ " labels = labels[pc]\n",
659
+ " plddt = plddt[pc]\n",
660
+ "\n",
661
+ "HTML(mk_animation(pos, labels, plddt, Ls=Ls_plot, dpi=dpi, color_by_plddt=color_by_plddt))"
662
+ ],
663
+ "execution_count": null,
664
+ "outputs": []
665
+ },
666
+ {
667
+ "cell_type": "code",
668
+ "metadata": {
669
+ "id": "Riekgf0KQv_3",
670
+ "cellView": "form"
671
+ },
672
+ "source": [
673
+ "#@title Download prediction\n",
674
+ "\n",
675
+ "#@markdown Once this cell has been executed, a zip-archive with \n",
676
+ "#@markdown the obtained prediction will be automatically downloaded \n",
677
+ "#@markdown to your computer.\n",
678
+ "\n",
679
+ "# add settings file\n",
680
+ "settings_path = os.path.join(I[\"output_dir\"],\"settings.txt\")\n",
681
+ "with open(settings_path, \"w\") as text_file:\n",
682
+ " text_file.write(f\"notebook=https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/AlphaFold2_advanced_beta.ipynb\\n\")\n",
683
+ " text_file.write(f\"sequence={I['ori_sequence']}\\n\")\n",
684
+ " text_file.write(f\"msa_method={msa_method}\\n\")\n",
685
+ " if add_custom_msa:\n",
686
+ " text_file.write(f\"add_custom_msa={add_custom_msa} msa_format={msa_format}\\n\")\n",
687
+ " text_file.write(f\"homooligomer={I['homooligomer']}\\n\")\n",
688
+ "\n",
689
+ " text_file.write(f\"pair_mode={pair_mode}\\n\")\n",
690
+ " if pair_mode != \"unpaired\":\n",
691
+ " text_file.write(f\"pair_cov={pair_cov}\\n\")\n",
692
+ " text_file.write(f\"pair_qid={pair_qid}\\n\")\n",
693
+ " \n",
694
+ " if I[\"ori_sequence\"] != mod_I[\"ori_sequence\"]:\n",
695
+ " text_file.write(f\"mod_sequence={mod_I['ori_sequence']}\\n\")\n",
696
+ " text_file.write(f\"trim={trim}\\n\")\n",
697
+ " text_file.write(f\"trim_inverse={trim_inverse}\\n\")\n",
698
+ " \n",
699
+ " if \"cov\" in dir():\n",
700
+ " text_file.write(f\"cov={cov}\\n\")\n",
701
+ " text_file.write(f\"qid={qid}\\n\")\n",
702
+ " else:\n",
703
+ " text_file.write(f\"cov=0\\nqid=0\\n\")\n",
704
+ "\n",
705
+ " text_file.write(f\"max_msa={max_msa}\\n\")\n",
706
+ " text_file.write(f\"subsample_msa={subsample_msa}\\n\") \n",
707
+ " text_file.write(f\"num_relax={num_relax}\\n\")\n",
708
+ " text_file.write(f\"use_turbo={use_turbo}\\n\")\n",
709
+ " text_file.write(f\"use_ptm={use_ptm}\\n\")\n",
710
+ " text_file.write(f\"rank_by={rank_by}\\n\")\n",
711
+ " text_file.write(f\"num_models={num_models}\\n\")\n",
712
+ " text_file.write(f\"num_samples={num_samples}\\n\")\n",
713
+ " text_file.write(f\"num_ensemble={num_ensemble}\\n\")\n",
714
+ " text_file.write(f\"max_recycles={max_recycles}\\n\")\n",
715
+ " text_file.write(f\"is_training={is_training}\\n\")\n",
716
+ " text_file.write(f\"use_templates=False\\n\")\n",
717
+ " text_file.write(f\"-------------------------------------------------\\n\")\n",
718
+ "\n",
719
+ " for n,key in enumerate(model_rank):\n",
720
+ " line = f\"rank_{n+1}_{key} pLDDT:{outs[key]['pLDDT']:.2f}\" + f\" pTMscore:{outs[key]['pTMscore']:.4f}\" if use_ptm else \"\"\n",
721
+ " text_file.write(line+\"\\n\")\n",
722
+ "\n",
723
+ "# --- Download the predictions ---\n",
724
+ "os.system(f'zip -FSr {I[\"output_dir\"]}.zip {I[\"output_dir\"]}')\n",
725
+ "if IN_COLAB:\n",
726
+ " files.download(f'{I[\"output_dir\"]}.zip')\n",
727
+ "else:\n",
728
+ " print(\"this notebook appears to be running locally, to download click folder icon to the left, navigate to file, right click and download\")"
729
+ ],
730
+ "execution_count": null,
731
+ "outputs": []
732
+ },
733
+ {
734
+ "cell_type": "markdown",
735
+ "source": [
736
+ "# License\n",
737
+ "\n",
738
+ "The source code of ColabFold is licensed under [MIT](https://raw.githubusercontent.com/sokrypton/ColabFold/main/LICENSE). Read more about the AlphaFold license [here](https://github.com/deepmind/alphafold)."
739
+ ],
740
+ "metadata": {
741
+ "id": "0RoRCHFJZgmF"
742
+ }
743
+ }
744
+ ]
745
+ }
data/beta/AlphaFold2_advanced_beta.ipynb ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "AlphaFold2_advanced_beta.ipynb",
7
+ "provenance": [],
8
+ "collapsed_sections": [],
9
+ "include_colab_link": true
10
+ },
11
+ "kernelspec": {
12
+ "display_name": "Python 3",
13
+ "name": "python3"
14
+ },
15
+ "language_info": {
16
+ "name": "python"
17
+ },
18
+ "accelerator": "GPU"
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {
24
+ "id": "view-in-github",
25
+ "colab_type": "text"
26
+ },
27
+ "source": [
28
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/AlphaFold2_advanced_beta.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {
34
+ "id": "pc5-mbsX9PZC"
35
+ },
36
+ "source": [
37
+ "# AlphaFold2_advanced_beta\n",
38
+ "\n",
39
+ "<font color='red'>**WARNING** This is beta (or development) version of the advanced notebook. </font> The latest edits were merged into: https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/AlphaFold2_advanced.ipynb"
40
+ ]
41
+ }
42
+ ]
43
+ }
data/beta/AlphaFold2_advanced_old.ipynb ADDED
@@ -0,0 +1,1127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "AlphaFold2_advanced.ipynb",
7
+ "provenance": [],
8
+ "collapsed_sections": [],
9
+ "include_colab_link": true
10
+ },
11
+ "kernelspec": {
12
+ "display_name": "Python 3",
13
+ "name": "python3"
14
+ },
15
+ "language_info": {
16
+ "name": "python"
17
+ },
18
+ "accelerator": "GPU"
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {
24
+ "id": "view-in-github",
25
+ "colab_type": "text"
26
+ },
27
+ "source": [
28
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/AlphaFold2_advanced.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {
34
+ "id": "pc5-mbsX9PZC"
35
+ },
36
+ "source": [
37
+ "# AlphaFold2_advanced\n",
38
+ "\n",
39
+ "-----------------\n",
40
+ "- <b><font color='green'>21Aug2021: MMseqs2 API has finished upgrade, all should be ready to go! Report any errors.</font></b>\n",
41
+ "\n",
42
+ "-----------------\n",
43
+ "\n",
44
+ "This notebook modifies deepmind's [original notebook](https://colab.research.google.com/github/deepmind/alphafold/blob/main/notebooks/AlphaFold.ipynb) to add experimental support for modeling complexes (both homo and hetero-oligomers), option to run MMseqs2 instead of Jackhmmer for MSA generation and advanced functionality.\n",
45
+ "\n",
46
+ "See [ColabFold](https://github.com/sokrypton/ColabFold/) for other related notebooks\n",
47
+ "\n",
48
+ "**Limitations**\n",
49
+ "- This notebook does NOT use Templates.\n",
50
+ "- For a typical Google-Colab session, with a `16G-GPU`, the max total length is **1400 residues**. Sometimes a `12G-GPU` is assigned, in which the max length is ~1000 residues.\n",
51
+ "- Can I use the models for **Molecular Replacement**? Yes, but be CAREFUL, the bfactor column is populated with pLDDT confidence values (higher = better). Phenix.phaser expects a \"real\" bfactor, where (lower = better). See [post](https://twitter.com/cheshireminima/status/1423929241675120643) from Claudia Millán on how to process models."
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "metadata": {
57
+ "id": "woIxeCPygt7K",
58
+ "cellView": "form"
59
+ },
60
+ "source": [
61
+ "#@title Install software\n",
62
+ "#@markdown Please execute this cell by pressing the _Play_ button \n",
63
+ "#@markdown on the left.\n",
64
+ "\n",
65
+ "import os\n",
66
+ "import tensorflow as tf\n",
67
+ "tf.config.set_visible_devices([], 'GPU')\n",
68
+ "\n",
69
+ "import jax\n",
70
+ "if jax.local_devices()[0].platform == 'tpu':\n",
71
+ " raise RuntimeError('Colab TPU runtime not supported. Change it to GPU via Runtime -> Change Runtime Type -> Hardware accelerator -> GPU.')\n",
72
+ "elif jax.local_devices()[0].platform == 'cpu':\n",
73
+ " raise RuntimeError('Colab CPU runtime not supported. Change it to GPU via Runtime -> Change Runtime Type -> Hardware accelerator -> GPU.')\n",
74
+ "\n",
75
+ "from IPython.utils import io\n",
76
+ "import subprocess\n",
77
+ "import tqdm.notebook\n",
78
+ "\n",
79
+ "from sys import version_info \n",
80
+ "python_version = f\"{version_info.major}.{version_info.minor}\"\n",
81
+ "\n",
82
+ "GIT_REPO = 'https://github.com/deepmind/alphafold'\n",
83
+ "SOURCE_URL = 'https://storage.googleapis.com/alphafold/alphafold_params_2021-07-14.tar'\n",
84
+ "PARAMS_DIR = './alphafold/data/params'\n",
85
+ "PARAMS_PATH = os.path.join(PARAMS_DIR, os.path.basename(SOURCE_URL))\n",
86
+ "TQDM_BAR_FORMAT = '{l_bar}{bar}| {n_fmt}/{total_fmt} [elapsed: {elapsed} remaining: {remaining}]'\n",
87
+ "\n",
88
+ "# if not already installed\n",
89
+ "try:\n",
90
+ " total = 55\n",
91
+ " with tqdm.notebook.tqdm(total=total, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
92
+ " with io.capture_output() as captured:\n",
93
+ " if not os.path.isdir(\"alphafold\"):\n",
94
+ " %shell rm -rf alphafold\n",
95
+ " %shell git clone {GIT_REPO} alphafold\n",
96
+ " %shell (cd alphafold; git checkout 1d43aaff941c84dc56311076b58795797e49107b --quiet)\n",
97
+ "\n",
98
+ " # colabfold patches\n",
99
+ " %shell mkdir --parents tmp\n",
100
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/colabfold.py\n",
101
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/pairmsa.py\n",
102
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/protein.patch -P tmp/\n",
103
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/config.patch -P tmp/\n",
104
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/model.patch -P tmp/\n",
105
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/modules.patch -P tmp/\n",
106
+ "\n",
107
+ " # install hhsuite\n",
108
+ " %shell curl -fsSL https://github.com/soedinglab/hh-suite/releases/download/v3.3.0/hhsuite-3.3.0-SSE2-Linux.tar.gz | tar xz -C tmp/\n",
109
+ "\n",
110
+ " # Apply multi-chain patch from Lim Heo @huhlim\n",
111
+ " %shell patch -u alphafold/alphafold/common/protein.py -i tmp/protein.patch\n",
112
+ " \n",
113
+ " # Apply patch to dynamically control number of recycles (idea from Ryan Kibler)\n",
114
+ " %shell patch -u alphafold/alphafold/model/model.py -i tmp/model.patch\n",
115
+ " %shell patch -u alphafold/alphafold/model/modules.py -i tmp/modules.patch\n",
116
+ " %shell patch -u alphafold/alphafold/model/config.py -i tmp/config.patch\n",
117
+ " pbar.update(4)\n",
118
+ "\n",
119
+ " %shell pip3 install biopython dm-haiku ml-collections py3Dmol\n",
120
+ " %shell pip3 install --no-dependencies ./alphafold\n",
121
+ " pbar.update(6)\n",
122
+ "\n",
123
+ " # speedup from kaczmarj\n",
124
+ " %shell mkdir --parents \"{PARAMS_DIR}\"\n",
125
+ " %shell curl -fsSL \"{SOURCE_URL}\" | tar x -C \"{PARAMS_DIR}\"\n",
126
+ " pbar.update(14+27)\n",
127
+ "\n",
128
+ " #######################################################################\n",
129
+ " %shell sudo apt install --quiet --yes hmmer\n",
130
+ " pbar.update(3)\n",
131
+ "\n",
132
+ " # Create a ramdisk to store a database chunk to make Jackhmmer run fast.\n",
133
+ " %shell sudo mkdir -m 777 --parents /tmp/ramdisk\n",
134
+ " %shell sudo mount -t tmpfs -o size=9G ramdisk /tmp/ramdisk\n",
135
+ " pbar.update(1)\n",
136
+ " else:\n",
137
+ " pbar.update(55)\n",
138
+ "\n",
139
+ "except subprocess.CalledProcessError:\n",
140
+ " print(captured)\n",
141
+ " raise\n",
142
+ "\n",
143
+ "########################################################################################\n",
144
+ "# --- Python imports ---\n",
145
+ "import colabfold as cf\n",
146
+ "import pairmsa\n",
147
+ "import sys\n",
148
+ "import pickle\n",
149
+ "\n",
150
+ "if \"/content/tmp/bin\" not in os.environ['PATH']:\n",
151
+ " os.environ['PATH'] += \":/content/tmp/bin:/content/tmp/scripts\"\n",
152
+ "\n",
153
+ "from urllib import request\n",
154
+ "from concurrent import futures\n",
155
+ "from google.colab import files\n",
156
+ "import json\n",
157
+ "from matplotlib import gridspec\n",
158
+ "import matplotlib.pyplot as plt\n",
159
+ "import numpy as np\n",
160
+ "import py3Dmol\n",
161
+ "\n",
162
+ "from alphafold.model import model\n",
163
+ "from alphafold.model import config\n",
164
+ "from alphafold.model import data\n",
165
+ "\n",
166
+ "from alphafold.data import parsers\n",
167
+ "from alphafold.data import pipeline\n",
168
+ "from alphafold.data.tools import jackhmmer\n",
169
+ "\n",
170
+ "from alphafold.common import protein\n",
171
+ "\n",
172
+ "def run_jackhmmer(sequence, prefix):\n",
173
+ "\n",
174
+ " fasta_path = f\"{prefix}.fasta\"\n",
175
+ " with open(fasta_path, 'wt') as f:\n",
176
+ " f.write(f'>query\\n{sequence}')\n",
177
+ "\n",
178
+ " pickled_msa_path = f\"{prefix}.jackhmmer.pickle\"\n",
179
+ " if os.path.isfile(pickled_msa_path):\n",
180
+ " msas_dict = pickle.load(open(pickled_msa_path,\"rb\"))\n",
181
+ " msas, deletion_matrices, names = (msas_dict[k] for k in ['msas', 'deletion_matrices', 'names'])\n",
182
+ " full_msa = []\n",
183
+ " for msa in msas:\n",
184
+ " full_msa += msa\n",
185
+ " else:\n",
186
+ " # --- Find the closest source ---\n",
187
+ " test_url_pattern = 'https://storage.googleapis.com/alphafold-colab{:s}/latest/uniref90_2021_03.fasta.1'\n",
188
+ " ex = futures.ThreadPoolExecutor(3)\n",
189
+ " def fetch(source):\n",
190
+ " request.urlretrieve(test_url_pattern.format(source))\n",
191
+ " return source\n",
192
+ " fs = [ex.submit(fetch, source) for source in ['', '-europe', '-asia']]\n",
193
+ " source = None\n",
194
+ " for f in futures.as_completed(fs):\n",
195
+ " source = f.result()\n",
196
+ " ex.shutdown()\n",
197
+ " break\n",
198
+ "\n",
199
+ " jackhmmer_binary_path = '/usr/bin/jackhmmer'\n",
200
+ " dbs = []\n",
201
+ "\n",
202
+ " num_jackhmmer_chunks = {'uniref90': 59, 'smallbfd': 17, 'mgnify': 71}\n",
203
+ " total_jackhmmer_chunks = sum(num_jackhmmer_chunks.values())\n",
204
+ " with tqdm.notebook.tqdm(total=total_jackhmmer_chunks, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
205
+ " def jackhmmer_chunk_callback(i):\n",
206
+ " pbar.update(n=1)\n",
207
+ "\n",
208
+ " pbar.set_description('Searching uniref90')\n",
209
+ " jackhmmer_uniref90_runner = jackhmmer.Jackhmmer(\n",
210
+ " binary_path=jackhmmer_binary_path,\n",
211
+ " database_path=f'https://storage.googleapis.com/alphafold-colab{source}/latest/uniref90_2021_03.fasta',\n",
212
+ " get_tblout=True,\n",
213
+ " num_streamed_chunks=num_jackhmmer_chunks['uniref90'],\n",
214
+ " streaming_callback=jackhmmer_chunk_callback,\n",
215
+ " z_value=135301051)\n",
216
+ " dbs.append(('uniref90', jackhmmer_uniref90_runner.query(fasta_path)))\n",
217
+ "\n",
218
+ " pbar.set_description('Searching smallbfd')\n",
219
+ " jackhmmer_smallbfd_runner = jackhmmer.Jackhmmer(\n",
220
+ " binary_path=jackhmmer_binary_path,\n",
221
+ " database_path=f'https://storage.googleapis.com/alphafold-colab{source}/latest/bfd-first_non_consensus_sequences.fasta',\n",
222
+ " get_tblout=True,\n",
223
+ " num_streamed_chunks=num_jackhmmer_chunks['smallbfd'],\n",
224
+ " streaming_callback=jackhmmer_chunk_callback,\n",
225
+ " z_value=65984053)\n",
226
+ " dbs.append(('smallbfd', jackhmmer_smallbfd_runner.query(fasta_path)))\n",
227
+ "\n",
228
+ " pbar.set_description('Searching mgnify')\n",
229
+ " jackhmmer_mgnify_runner = jackhmmer.Jackhmmer(\n",
230
+ " binary_path=jackhmmer_binary_path,\n",
231
+ " database_path=f'https://storage.googleapis.com/alphafold-colab{source}/latest/mgy_clusters_2019_05.fasta',\n",
232
+ " get_tblout=True,\n",
233
+ " num_streamed_chunks=num_jackhmmer_chunks['mgnify'],\n",
234
+ " streaming_callback=jackhmmer_chunk_callback,\n",
235
+ " z_value=304820129)\n",
236
+ " dbs.append(('mgnify', jackhmmer_mgnify_runner.query(fasta_path)))\n",
237
+ "\n",
238
+ " # --- Extract the MSAs and visualize ---\n",
239
+ " # Extract the MSAs from the Stockholm files.\n",
240
+ " # NB: deduplication happens later in pipeline.make_msa_features.\n",
241
+ "\n",
242
+ " mgnify_max_hits = 501\n",
243
+ " msas = []\n",
244
+ " deletion_matrices = []\n",
245
+ " names = []\n",
246
+ " for db_name, db_results in dbs:\n",
247
+ " unsorted_results = []\n",
248
+ " for i, result in enumerate(db_results):\n",
249
+ " msa, deletion_matrix, target_names = parsers.parse_stockholm(result['sto'])\n",
250
+ " e_values_dict = parsers.parse_e_values_from_tblout(result['tbl'])\n",
251
+ " e_values = [e_values_dict[t.split('/')[0]] for t in target_names]\n",
252
+ " zipped_results = zip(msa, deletion_matrix, target_names, e_values)\n",
253
+ " if i != 0:\n",
254
+ " # Only take query from the first chunk\n",
255
+ " zipped_results = [x for x in zipped_results if x[2] != 'query']\n",
256
+ " unsorted_results.extend(zipped_results)\n",
257
+ " sorted_by_evalue = sorted(unsorted_results, key=lambda x: x[3])\n",
258
+ " db_msas, db_deletion_matrices, db_names, _ = zip(*sorted_by_evalue)\n",
259
+ " if db_msas:\n",
260
+ " if db_name == 'mgnify':\n",
261
+ " db_msas = db_msas[:mgnify_max_hits]\n",
262
+ " db_deletion_matrices = db_deletion_matrices[:mgnify_max_hits]\n",
263
+ " db_names = db_names[:mgnify_max_hits]\n",
264
+ " msas.append(db_msas)\n",
265
+ " deletion_matrices.append(db_deletion_matrices)\n",
266
+ " names.append(db_names)\n",
267
+ " msa_size = len(set(db_msas))\n",
268
+ " print(f'{msa_size} Sequences Found in {db_name}')\n",
269
+ "\n",
270
+ " pickle.dump({\"msas\":msas,\n",
271
+ " \"deletion_matrices\":deletion_matrices,\n",
272
+ " \"names\":names}, open(pickled_msa_path,\"wb\"))\n",
273
+ " return msas, deletion_matrices, names"
274
+ ],
275
+ "execution_count": null,
276
+ "outputs": []
277
+ },
278
+ {
279
+ "cell_type": "code",
280
+ "metadata": {
281
+ "id": "rowN0bVYLe9n",
282
+ "cellView": "form"
283
+ },
284
+ "source": [
285
+ "#@title Enter the amino acid sequence to fold ⬇️\n",
286
+ "import re\n",
287
+ "\n",
288
+ "# define sequence\n",
289
+ "sequence = 'PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK' #@param {type:\"string\"}\n",
290
+ "sequence = re.sub(\"[^A-Z:/]\", \"\", sequence.upper())\n",
291
+ "sequence = re.sub(\":+\",\":\",sequence)\n",
292
+ "sequence = re.sub(\"/+\",\"/\",sequence)\n",
293
+ "sequence = re.sub(\"^[:/]+\",\"\",sequence)\n",
294
+ "sequence = re.sub(\"[:/]+$\",\"\",sequence)\n",
295
+ "\n",
296
+ "jobname = \"test\" #@param {type:\"string\"}\n",
297
+ "jobname = re.sub(r'\\W+', '', jobname)\n",
298
+ "\n",
299
+ "# define number of copies\n",
300
+ "homooligomer = \"1\" #@param {type:\"string\"}\n",
301
+ "homooligomer = re.sub(\"[:/]+\",\":\",homooligomer)\n",
302
+ "homooligomer = re.sub(\"^[:/]+\",\"\",homooligomer)\n",
303
+ "homooligomer = re.sub(\"[:/]+$\",\"\",homooligomer)\n",
304
+ "\n",
305
+ "if len(homooligomer) == 0: homooligomer = \"1\"\n",
306
+ "homooligomer = re.sub(\"[^0-9:]\", \"\", homooligomer)\n",
307
+ "homooligomers = [int(h) for h in homooligomer.split(\":\")]\n",
308
+ "\n",
309
+ "#@markdown - `sequence` Specify protein sequence to be modelled.\n",
310
+ "#@markdown - Use `/` to specify intra-protein chainbreaks (for trimming regions within protein).\n",
311
+ "#@markdown - Use `:` to specify inter-protein chainbreaks (for modeling protein-protein hetero-complexes).\n",
312
+ "#@markdown - For example, sequence `AC/DE:FGH` will be modelled as polypeptides: `AC`, `DE` and `FGH`. A seperate MSA will be generates for `ACDE` and `FGH`.\n",
313
+ "#@markdown If `pair_msa` is enabled, `ACDE`'s MSA will be paired with `FGH`'s MSA.\n",
314
+ "#@markdown - `homooligomer` Define number of copies in a homo-oligomeric assembly.\n",
315
+ "#@markdown - Use `:` to specify different homooligomeric state (copy numer) for each component of the complex. \n",
316
+ "#@markdown - For example, **sequence:**`ABC:DEF`, **homooligomer:** `2:1`, the first protein `ABC` will be modeled as a homodimer (2 copies) and second `DEF` a monomer (1 copy).\n",
317
+ "\n",
318
+ "ori_sequence = sequence\n",
319
+ "sequence = sequence.replace(\"/\",\"\").replace(\":\",\"\")\n",
320
+ "seqs = ori_sequence.replace(\"/\",\"\").split(\":\")\n",
321
+ "\n",
322
+ "if len(seqs) != len(homooligomers):\n",
323
+ " if len(homooligomers) == 1:\n",
324
+ " homooligomers = [homooligomers[0]] * len(seqs)\n",
325
+ " homooligomer = \":\".join([str(h) for h in homooligomers])\n",
326
+ " else:\n",
327
+ " while len(seqs) > len(homooligomers):\n",
328
+ " homooligomers.append(1)\n",
329
+ " homooligomers = homooligomers[:len(seqs)]\n",
330
+ " homooligomer = \":\".join([str(h) for h in homooligomers])\n",
331
+ " print(\"WARNING: Mismatch between number of breaks ':' in 'sequence' and 'homooligomer' definition\")\n",
332
+ "\n",
333
+ "full_sequence = \"\".join([s*h for s,h in zip(seqs,homooligomers)])\n",
334
+ "\n",
335
+ "# prediction directory\n",
336
+ "output_dir = 'prediction_' + jobname + '_' + cf.get_hash(full_sequence)[:5]\n",
337
+ "os.makedirs(output_dir, exist_ok=True)\n",
338
+ "# delete existing files in working directory\n",
339
+ "for f in os.listdir(output_dir):\n",
340
+ " os.remove(os.path.join(output_dir, f))\n",
341
+ "\n",
342
+ "MIN_SEQUENCE_LENGTH = 16\n",
343
+ "MAX_SEQUENCE_LENGTH = 2500\n",
344
+ "\n",
345
+ "aatypes = set('ACDEFGHIKLMNPQRSTVWY') # 20 standard aatypes\n",
346
+ "if not set(full_sequence).issubset(aatypes):\n",
347
+ " raise Exception(f'Input sequence contains non-amino acid letters: {set(sequence) - aatypes}. AlphaFold only supports 20 standard amino acids as inputs.')\n",
348
+ "if len(full_sequence) < MIN_SEQUENCE_LENGTH:\n",
349
+ " raise Exception(f'Input sequence is too short: {len(full_sequence)} amino acids, while the minimum is {MIN_SEQUENCE_LENGTH}')\n",
350
+ "if len(full_sequence) > MAX_SEQUENCE_LENGTH:\n",
351
+ " raise Exception(f'Input sequence is too long: {len(full_sequence)} amino acids, while the maximum is {MAX_SEQUENCE_LENGTH}. Please use the full AlphaFold system for long sequences.')\n",
352
+ "\n",
353
+ "if len(full_sequence) > 1400:\n",
354
+ " print(f\"WARNING: For a typical Google-Colab-GPU (16G) session, the max total length is ~1400 residues. You are at {len(full_sequence)}! Run Alphafold may crash.\")\n",
355
+ "\n",
356
+ "print(f\"homooligomer: '{homooligomer}'\")\n",
357
+ "print(f\"total_length: '{len(full_sequence)}'\")\n",
358
+ "print(f\"working_directory: '{output_dir}'\")\n"
359
+ ],
360
+ "execution_count": null,
361
+ "outputs": []
362
+ },
363
+ {
364
+ "cell_type": "code",
365
+ "metadata": {
366
+ "id": "ITcPnLkLuDDE",
367
+ "cellView": "form"
368
+ },
369
+ "source": [
370
+ "#@title Search against genetic databases\n",
371
+ "#@markdown Once this cell has been executed, you will see\n",
372
+ "#@markdown statistics about the multiple sequence alignment \n",
373
+ "#@markdown (MSA) that will be used by AlphaFold. In particular, \n",
374
+ "#@markdown you’ll see how well each residue is covered by similar \n",
375
+ "#@markdown sequences in the MSA.\n",
376
+ "#@markdown (Note that the search against databases and the actual prediction can take some time, from minutes to hours, depending on the length of the protein and what type of GPU you are allocated by Colab.)\n",
377
+ "\n",
378
+ "#@markdown ---\n",
379
+ "msa_method = \"mmseqs2\" #@param [\"mmseqs2\",\"jackhmmer\",\"single_sequence\",\"precomputed\"]\n",
380
+ "#@markdown - `mmseqs2` - FAST method from [ColabFold](https://github.com/sokrypton/ColabFold)\n",
381
+ "#@markdown - `jackhmmer` - default method from Deepmind (SLOW, but may find more/less sequences).\n",
382
+ "#@markdown - `single_sequence` - use single sequence input\n",
383
+ "#@markdown - `precomputed` If you have previously run this notebook and saved the results,\n",
384
+ "#@markdown you can skip this step by uploading \n",
385
+ "#@markdown the previously generated `prediction_?????/msa.pickle`\n",
386
+ "\n",
387
+ "\n",
388
+ "#@markdown ---\n",
389
+ "#@markdown **custom msa options**\n",
390
+ "add_custom_msa = False #@param {type:\"boolean\"}\n",
391
+ "msa_format = \"fas\" #@param [\"fas\",\"a2m\",\"a3m\",\"sto\",\"psi\",\"clu\"]\n",
392
+ "#@markdown - `add_custom_msa` - If enabled, you'll get an option to upload your custom MSA in the specified `msa_format`. Note: Your MSA will be supplemented with those from 'mmseqs2' or 'jackhmmer', unless `msa_method` is set to 'single_sequence'.\n",
393
+ "\n",
394
+ "#@markdown ---\n",
395
+ "#@markdown **pair msa options**\n",
396
+ "\n",
397
+ "#@markdown Experimental option for protein complexes. Pairing currently only supported for proteins in same operon (prokaryotic genomes).\n",
398
+ "pair_mode = \"unpaired\" #@param [\"unpaired\",\"unpaired+paired\",\"paired\"] {type:\"string\"}\n",
399
+ "#@markdown - `unpaired` - generate seperate MSA for each protein.\n",
400
+ "#@markdown - `unpaired+paired` - attempt to pair sequences from the same operon within the genome. \n",
401
+ "#@markdown - `paired` - only use sequences that were sucessfully paired.\n",
402
+ "\n",
403
+ "#@markdown Options to prefilter each MSA before pairing. (It might help if there are any paralogs in the complex.)\n",
404
+ "pair_cov = 50 #@param [0,25,50,75,90] {type:\"raw\"}\n",
405
+ "pair_qid = 20 #@param [0,15,20,30,40,50] {type:\"raw\"}\n",
406
+ "#@markdown - `pair_cov` prefilter each MSA to minimum coverage with query (%) before pairing.\n",
407
+ "#@markdown - `pair_qid` prefilter each MSA to minimum sequence identity with query (%) before pairing.\n",
408
+ "\n",
409
+ "# --- Search against genetic databases ---\n",
410
+ "os.makedirs('tmp', exist_ok=True)\n",
411
+ "msas, deletion_matrices = [],[]\n",
412
+ "\n",
413
+ "if add_custom_msa:\n",
414
+ " print(f\"upload custom msa in '{msa_format}' format\")\n",
415
+ " msa_dict = files.upload()\n",
416
+ " lines = msa_dict[list(msa_dict.keys())[0]].decode()\n",
417
+ " \n",
418
+ " # convert to a3m\n",
419
+ " with open(f\"tmp/upload.{msa_format}\",\"w\") as tmp_upload:\n",
420
+ " tmp_upload.write(lines)\n",
421
+ " os.system(f\"reformat.pl {msa_format} a3m tmp/upload.{msa_format} tmp/upload.a3m\")\n",
422
+ " a3m_lines = open(\"tmp/upload.a3m\",\"r\").read()\n",
423
+ "\n",
424
+ " # parse\n",
425
+ " msa, mtx = parsers.parse_a3m(a3m_lines)\n",
426
+ " msas.append(msa)\n",
427
+ " deletion_matrices.append(mtx)\n",
428
+ "\n",
429
+ " if len(msas[0][0]) != len(sequence):\n",
430
+ " raise ValueError(\"ERROR: the length of msa does not match input sequence\")\n",
431
+ "\n",
432
+ "if msa_method == \"precomputed\":\n",
433
+ " print(\"upload precomputed pickled msa from previous run\")\n",
434
+ " pickled_msa_dict = files.upload()\n",
435
+ " msas_dict = pickle.loads(pickled_msa_dict[list(pickled_msa_dict.keys())[0]])\n",
436
+ " msas, deletion_matrices = (msas_dict[k] for k in ['msas', 'deletion_matrices'])\n",
437
+ "\n",
438
+ "elif msa_method == \"single_sequence\":\n",
439
+ " if len(msas) == 0:\n",
440
+ " msas.append([sequence])\n",
441
+ " deletion_matrices.append([[0]*len(sequence)])\n",
442
+ "\n",
443
+ "else:\n",
444
+ " seqs = ori_sequence.replace('/','').split(':')\n",
445
+ " _blank_seq = [\"-\" * len(seq) for seq in seqs]\n",
446
+ " _blank_mtx = [[0] * len(seq) for seq in seqs]\n",
447
+ " def _pad(ns,vals,mode):\n",
448
+ " if mode == \"seq\": _blank = _blank_seq.copy()\n",
449
+ " if mode == \"mtx\": _blank = _blank_mtx.copy()\n",
450
+ " if isinstance(ns, list):\n",
451
+ " for n,val in zip(ns,vals): _blank[n] = val\n",
452
+ " else: _blank[ns] = vals\n",
453
+ " if mode == \"seq\": return \"\".join(_blank)\n",
454
+ " if mode == \"mtx\": return sum(_blank,[])\n",
455
+ "\n",
456
+ " if len(seqs) == 1 or \"unpaired\" in pair_mode:\n",
457
+ " # gather msas\n",
458
+ " if msa_method == \"mmseqs2\":\n",
459
+ " prefix = cf.get_hash(\"\".join(seqs))\n",
460
+ " prefix = os.path.join('tmp',prefix)\n",
461
+ " print(f\"running mmseqs2\")\n",
462
+ " A3M_LINES = cf.run_mmseqs2(seqs, prefix, filter=True)\n",
463
+ "\n",
464
+ " for n, seq in enumerate(seqs):\n",
465
+ " # tmp directory\n",
466
+ " prefix = cf.get_hash(seq)\n",
467
+ " prefix = os.path.join('tmp',prefix)\n",
468
+ "\n",
469
+ " if msa_method == \"mmseqs2\":\n",
470
+ " # run mmseqs2\n",
471
+ " a3m_lines = A3M_LINES[n]\n",
472
+ " msa, mtx = parsers.parse_a3m(a3m_lines)\n",
473
+ " msas_, mtxs_ = [msa],[mtx]\n",
474
+ "\n",
475
+ " elif msa_method == \"jackhmmer\":\n",
476
+ " print(f\"running jackhmmer on seq_{n}\")\n",
477
+ " # run jackhmmer\n",
478
+ " msas_, mtxs_, names_ = ([sum(x,())] for x in run_jackhmmer(seq, prefix))\n",
479
+ " \n",
480
+ " # pad sequences\n",
481
+ " for msa_,mtx_ in zip(msas_,mtxs_):\n",
482
+ " msa,mtx = [sequence],[[0]*len(sequence)] \n",
483
+ " for s,m in zip(msa_,mtx_):\n",
484
+ " msa.append(_pad(n,s,\"seq\"))\n",
485
+ " mtx.append(_pad(n,m,\"mtx\"))\n",
486
+ "\n",
487
+ " msas.append(msa)\n",
488
+ " deletion_matrices.append(mtx)\n",
489
+ "\n",
490
+ " ####################################################################################\n",
491
+ " # PAIR_MSA\n",
492
+ " ####################################################################################\n",
493
+ " if len(seqs) > 1 and (pair_mode == \"paired\" or pair_mode == \"unpaired+paired\"):\n",
494
+ " print(\"attempting to pair some sequences...\")\n",
495
+ "\n",
496
+ " if msa_method == \"mmseqs2\":\n",
497
+ " prefix = cf.get_hash(\"\".join(seqs))\n",
498
+ " prefix = os.path.join('tmp',prefix)\n",
499
+ " print(f\"running mmseqs2_noenv_nofilter on all seqs\")\n",
500
+ " A3M_LINES = cf.run_mmseqs2(seqs, prefix, use_env=False, use_filter=False)\n",
501
+ "\n",
502
+ " _data = []\n",
503
+ " for a in range(len(seqs)):\n",
504
+ " print(f\"prepping seq_{a}\")\n",
505
+ " _seq = seqs[a]\n",
506
+ " _prefix = os.path.join('tmp',cf.get_hash(_seq))\n",
507
+ "\n",
508
+ " if msa_method == \"mmseqs2\":\n",
509
+ " a3m_lines = A3M_LINES[a]\n",
510
+ " _msa, _mtx, _lab = pairmsa.parse_a3m(a3m_lines,\n",
511
+ " filter_qid=pair_qid/100,\n",
512
+ " filter_cov=pair_cov/100)\n",
513
+ "\n",
514
+ " elif msa_method == \"jackhmmer\":\n",
515
+ " _msas, _mtxs, _names = run_jackhmmer(_seq, _prefix)\n",
516
+ " _msa, _mtx, _lab = pairmsa.get_uni_jackhmmer(_msas[0], _mtxs[0], _names[0],\n",
517
+ " filter_qid=pair_qid/100,\n",
518
+ " filter_cov=pair_cov/100)\n",
519
+ "\n",
520
+ " if len(_msa) > 1:\n",
521
+ " _data.append(pairmsa.hash_it(_msa, _lab, _mtx, call_uniprot=False))\n",
522
+ " else:\n",
523
+ " _data.append(None)\n",
524
+ " \n",
525
+ " Ln = len(seqs)\n",
526
+ " O = [[None for _ in seqs] for _ in seqs]\n",
527
+ " for a in range(Ln):\n",
528
+ " if _data[a] is not None:\n",
529
+ " for b in range(a+1,Ln):\n",
530
+ " if _data[b] is not None:\n",
531
+ " print(f\"attempting pairwise stitch for {a} {b}\") \n",
532
+ " O[a][b] = pairmsa._stitch(_data[a],_data[b])\n",
533
+ " _seq_a, _seq_b, _mtx_a, _mtx_b = (*O[a][b][\"seq\"],*O[a][b][\"mtx\"])\n",
534
+ "\n",
535
+ " ##############################################\n",
536
+ " # filter to remove redundant sequences\n",
537
+ " ##############################################\n",
538
+ " ok = []\n",
539
+ " with open(\"tmp/tmp.fas\",\"w\") as fas_file:\n",
540
+ " fas_file.writelines([f\">{n}\\n{a+b}\\n\" for n,(a,b) in enumerate(zip(_seq_a,_seq_b))])\n",
541
+ " os.system(\"hhfilter -maxseq 1000000 -i tmp/tmp.fas -o tmp/tmp.id90.fas -id 90\")\n",
542
+ " for line in open(\"tmp/tmp.id90.fas\",\"r\"):\n",
543
+ " if line.startswith(\">\"): ok.append(int(line[1:]))\n",
544
+ " ############################################## \n",
545
+ " print(f\"found {len(_seq_a)} pairs ({len(ok)} after filtering)\")\n",
546
+ "\n",
547
+ " if len(_seq_a) > 0:\n",
548
+ " msa,mtx = [sequence],[[0]*len(sequence)]\n",
549
+ " for s_a,s_b,m_a,m_b in zip(_seq_a, _seq_b, _mtx_a, _mtx_b):\n",
550
+ " msa.append(_pad([a,b],[s_a,s_b],\"seq\"))\n",
551
+ " mtx.append(_pad([a,b],[m_a,m_b],\"mtx\"))\n",
552
+ " msas.append(msa)\n",
553
+ " deletion_matrices.append(mtx)\n",
554
+ " \n",
555
+ " '''\n",
556
+ " # triwise stitching (WIP)\n",
557
+ " if Ln > 2:\n",
558
+ " for a in range(Ln):\n",
559
+ " for b in range(a+1,Ln):\n",
560
+ " for c in range(b+1,Ln):\n",
561
+ " if O[a][b] is not None and O[b][c] is not None:\n",
562
+ " print(f\"attempting triwise stitch for {a} {b} {c}\")\n",
563
+ " list_ab = O[a][b][\"lab\"][1]\n",
564
+ " list_bc = O[b][c][\"lab\"][0]\n",
565
+ " msa,mtx = [sequence],[[0]*len(sequence)]\n",
566
+ " for i,l_b in enumerate(list_ab):\n",
567
+ " if l_b in list_bc:\n",
568
+ " j = list_bc.index(l_b)\n",
569
+ " s_a = O[a][b][\"seq\"][0][i]\n",
570
+ " s_b = O[a][b][\"seq\"][1][i]\n",
571
+ " s_c = O[b][c][\"seq\"][1][j]\n",
572
+ "\n",
573
+ " m_a = O[a][b][\"mtx\"][0][i]\n",
574
+ " m_b = O[a][b][\"mtx\"][1][i]\n",
575
+ " m_c = O[b][c][\"mtx\"][1][j]\n",
576
+ "\n",
577
+ " msa.append(_pad([a,b,c],[s_a,s_b,s_c],\"seq\"))\n",
578
+ " mtx.append(_pad([a,b,c],[m_a,m_b,m_c],\"mtx\"))\n",
579
+ " if len(msa) > 1:\n",
580
+ " msas.append(msa)\n",
581
+ " deletion_matrices.append(mtx)\n",
582
+ " print(f\"found {len(msa)} triplets\") \n",
583
+ " '''\n",
584
+ "####################################################################################\n",
585
+ "####################################################################################\n",
586
+ "\n",
587
+ "# save MSA as pickle\n",
588
+ "pickle.dump({\"msas\":msas,\"deletion_matrices\":deletion_matrices},\n",
589
+ " open(os.path.join(output_dir,\"msa.pickle\"),\"wb\"))\n",
590
+ "\n",
591
+ "make_msa_plot = len(msas[0]) > 1\n",
592
+ "if make_msa_plot:\n",
593
+ " plt = cf.plot_msas(msas, ori_sequence)\n",
594
+ " plt.savefig(os.path.join(output_dir,\"msa_coverage.png\"), bbox_inches = 'tight', dpi=200)\n",
595
+ " plt.show()\n"
596
+ ],
597
+ "execution_count": null,
598
+ "outputs": []
599
+ },
600
+ {
601
+ "cell_type": "code",
602
+ "metadata": {
603
+ "id": "bQe3KeyTcv0n",
604
+ "cellView": "form"
605
+ },
606
+ "source": [
607
+ "#@title run alphafold\n",
608
+ "num_relax = \"None\"\n",
609
+ "rank_by = \"pLDDT\" #@param [\"pLDDT\",\"pTMscore\"]\n",
610
+ "use_turbo = True #@param {type:\"boolean\"}\n",
611
+ "max_msa = \"512:1024\" #@param [\"512:1024\", \"256:512\", \"128:256\", \"64:128\", \"32:64\"]\n",
612
+ "max_msa_clusters, max_extra_msa = [int(x) for x in max_msa.split(\":\")]\n",
613
+ "\n",
614
+ "\n",
615
+ "\n",
616
+ "#@markdown - `rank_by` specify metric to use for ranking models (For protein-protein complexes, we recommend pTMscore)\n",
617
+ "#@markdown - `use_turbo` introduces a few modifications (compile once, swap params, adjust max_msa) to speedup and reduce memory requirements. Disable for default behavior.\n",
618
+ "#@markdown - `max_msa` defines: `max_msa_clusters:max_extra_msa` number of sequences to use. When adjusting after GPU crash, be sure to `Runtime` → `Restart runtime`. (Lowering will reduce GPU requirements, but may result in poor model quality. This option ignored if `use_turbo` is disabled)\n",
619
+ "show_images = True #@param {type:\"boolean\"}\n",
620
+ "#@markdown - `show_images` To make things more exciting we show images of the predicted structures as they are being generated. (WARNING: the order of images displayed does not reflect any ranking).\n",
621
+ "#@markdown ---\n",
622
+ "#@markdown #### Sampling options\n",
623
+ "#@markdown There are two stochastic parts of the pipeline. Within the feature generation (choice of cluster centers) and within the model (dropout). \n",
624
+ "#@markdown To get structure diversity, you can iterate through a fixed number of random_seeds (using `num_samples`) and/or enable dropout (using `is_training`).\n",
625
+ "\n",
626
+ "num_models = 5 #@param [1,2,3,4,5] {type:\"raw\"}\n",
627
+ "use_ptm = True #@param {type:\"boolean\"}\n",
628
+ "num_ensemble = 1 #@param [1,8] {type:\"raw\"}\n",
629
+ "max_recycles = 3 #@param [1,3,6,12,24,48] {type:\"raw\"}\n",
630
+ "tol = 0 #@param [0,0.1,0.5,1] {type:\"raw\"}\n",
631
+ "is_training = False #@param {type:\"boolean\"}\n",
632
+ "num_samples = 1 #@param [1,2,4,8,16,32] {type:\"raw\"}\n",
633
+ "#@markdown - `num_models` specify how many model params to try. (5 recommended)\n",
634
+ "#@markdown - `use_ptm` uses Deepmind's `ptm` finetuned model parameters to get PAE per structure. Disable to use the original model params. (Disabling may give alternative structures.)\n",
635
+ "#@markdown - `num_ensemble` the trunk of the network is run multiple times with different random choices for the MSA cluster centers. (`1`=`default`, `8`=`casp14 setting`)\n",
636
+ "#@markdown - `max_recycles` controls the maximum number of times the structure is fed back into the neural network for refinement. (3 recommended)\n",
637
+ "#@markdown - `tol` tolerance for deciding when to stop (CA-RMS between recycles)\n",
638
+ "#@markdown - `is_training` enables the stochastic part of the model (dropout), when coupled with `num_samples` can be used to \"sample\" a diverse set of structures.\n",
639
+ "#@markdown - `num_samples` number of random_seeds to try.\n",
640
+ "subsample_msa = True #@param {type:\"boolean\"}\n",
641
+ "#@markdown - `subsample_msa` subsample large MSA to `3E7/length` sequences to avoid crashing the preprocessing protocol. (This option ignored if `use_turbo` is disabled.)\n",
642
+ "\n",
643
+ "save_pae_json = True \n",
644
+ "save_tmp_pdb = True\n",
645
+ "\n",
646
+ "\n",
647
+ "if use_ptm == False and rank_by == \"pTMscore\":\n",
648
+ " print(\"WARNING: models will be ranked by pLDDT, 'use_ptm' is needed to compute pTMscore\")\n",
649
+ " rank_by = \"pLDDT\"\n",
650
+ "\n",
651
+ "#############################\n",
652
+ "# delete old files\n",
653
+ "#############################\n",
654
+ "for f in os.listdir(output_dir):\n",
655
+ " if \"rank_\" in f:\n",
656
+ " os.remove(os.path.join(output_dir, f))\n",
657
+ "\n",
658
+ "#############################\n",
659
+ "# homooligomerize\n",
660
+ "#############################\n",
661
+ "lengths = [len(seq) for seq in seqs]\n",
662
+ "msas_mod, deletion_matrices_mod = cf.homooligomerize_heterooligomer(msas, deletion_matrices,\n",
663
+ " lengths, homooligomers)\n",
664
+ "#############################\n",
665
+ "# define input features\n",
666
+ "#############################\n",
667
+ "def _placeholder_template_feats(num_templates_, num_res_):\n",
668
+ " return {\n",
669
+ " 'template_aatype': np.zeros([num_templates_, num_res_, 22], np.float32),\n",
670
+ " 'template_all_atom_masks': np.zeros([num_templates_, num_res_, 37, 3], np.float32),\n",
671
+ " 'template_all_atom_positions': np.zeros([num_templates_, num_res_, 37], np.float32),\n",
672
+ " 'template_domain_names': np.zeros([num_templates_], np.float32),\n",
673
+ " 'template_sum_probs': np.zeros([num_templates_], np.float32),\n",
674
+ " }\n",
675
+ "\n",
676
+ "num_res = len(full_sequence)\n",
677
+ "feature_dict = {}\n",
678
+ "feature_dict.update(pipeline.make_sequence_features(full_sequence, 'test', num_res))\n",
679
+ "feature_dict.update(pipeline.make_msa_features(msas_mod, deletion_matrices=deletion_matrices_mod))\n",
680
+ "if not use_turbo:\n",
681
+ " feature_dict.update(_placeholder_template_feats(0, num_res))\n",
682
+ "\n",
683
+ "def do_subsample_msa(F, random_seed=0):\n",
684
+ " '''subsample msa to avoid running out of memory'''\n",
685
+ " N = len(F[\"msa\"])\n",
686
+ " L = len(F[\"residue_index\"])\n",
687
+ " N_ = int(3E7/L)\n",
688
+ " if N > N_:\n",
689
+ " print(f\"whhhaaa... too many sequences ({N}) subsampling to {N_}\")\n",
690
+ " np.random.seed(random_seed)\n",
691
+ " idx = np.append(0,np.random.permutation(np.arange(1,N)))[:N_]\n",
692
+ " F_ = {}\n",
693
+ " F_[\"msa\"] = F[\"msa\"][idx]\n",
694
+ " F_[\"deletion_matrix_int\"] = F[\"deletion_matrix_int\"][idx]\n",
695
+ " F_[\"num_alignments\"] = np.full_like(F[\"num_alignments\"],N_)\n",
696
+ " for k in ['aatype', 'between_segment_residues',\n",
697
+ " 'domain_name', 'residue_index',\n",
698
+ " 'seq_length', 'sequence']:\n",
699
+ " F_[k] = F[k]\n",
700
+ " return F_\n",
701
+ " else:\n",
702
+ " return F\n",
703
+ "\n",
704
+ "################################\n",
705
+ "# set chain breaks\n",
706
+ "################################\n",
707
+ "Ls = []\n",
708
+ "for seq,h in zip(ori_sequence.split(\":\"),homooligomers):\n",
709
+ " Ls += [len(s) for s in seq.split(\"/\")] * h\n",
710
+ "Ls_plot = sum([[len(seq)]*h for seq,h in zip(seqs,homooligomers)],[])\n",
711
+ "feature_dict['residue_index'] = cf.chain_break(feature_dict['residue_index'], Ls)\n",
712
+ "\n",
713
+ "###########################\n",
714
+ "# run alphafold\n",
715
+ "###########################\n",
716
+ "def parse_results(prediction_result, processed_feature_dict):\n",
717
+ " b_factors = prediction_result['plddt'][:,None] * prediction_result['structure_module']['final_atom_mask'] \n",
718
+ " dist_bins = jax.numpy.append(0,prediction_result[\"distogram\"][\"bin_edges\"])\n",
719
+ " dist_mtx = dist_bins[prediction_result[\"distogram\"][\"logits\"].argmax(-1)]\n",
720
+ " contact_mtx = jax.nn.softmax(prediction_result[\"distogram\"][\"logits\"])[:,:,dist_bins < 8].sum(-1)\n",
721
+ "\n",
722
+ " out = {\"unrelaxed_protein\": protein.from_prediction(processed_feature_dict, prediction_result, b_factors=b_factors),\n",
723
+ " \"plddt\": prediction_result['plddt'],\n",
724
+ " \"pLDDT\": prediction_result['plddt'].mean(),\n",
725
+ " \"dists\": dist_mtx,\n",
726
+ " \"adj\": contact_mtx}\n",
727
+ "\n",
728
+ " if \"ptm\" in prediction_result:\n",
729
+ " out.update({\"pae\": prediction_result['predicted_aligned_error'],\n",
730
+ " \"pTMscore\": prediction_result['ptm']})\n",
731
+ " return out\n",
732
+ "\n",
733
+ "model_names = ['model_1', 'model_2', 'model_3', 'model_4', 'model_5'][:num_models]\n",
734
+ "total = len(model_names) * num_samples\n",
735
+ "with tqdm.notebook.tqdm(total=total, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
736
+ " #######################################################################\n",
737
+ " # precompile model and recompile only if length changes\n",
738
+ " #######################################################################\n",
739
+ " if use_turbo:\n",
740
+ " name = \"model_5_ptm\" if use_ptm else \"model_5\"\n",
741
+ " N = len(feature_dict[\"msa\"])\n",
742
+ " L = len(feature_dict[\"residue_index\"])\n",
743
+ " compiled = (N, L, use_ptm, max_recycles, tol, num_ensemble, max_msa, is_training)\n",
744
+ " if \"COMPILED\" in dir():\n",
745
+ " if COMPILED != compiled: recompile = True\n",
746
+ " else: recompile = True\n",
747
+ " if recompile:\n",
748
+ " cf.clear_mem(\"gpu\")\n",
749
+ " cfg = config.model_config(name) \n",
750
+ "\n",
751
+ " # set size of msa (to reduce memory requirements)\n",
752
+ " msa_clusters = min(N, max_msa_clusters)\n",
753
+ " cfg.data.eval.max_msa_clusters = msa_clusters\n",
754
+ " cfg.data.common.max_extra_msa = max(min(N-msa_clusters,max_extra_msa),1)\n",
755
+ "\n",
756
+ " cfg.data.common.num_recycle = max_recycles\n",
757
+ " cfg.model.num_recycle = max_recycles\n",
758
+ " cfg.model.recycle_tol = tol\n",
759
+ " cfg.data.eval.num_ensemble = num_ensemble\n",
760
+ "\n",
761
+ " params = data.get_model_haiku_params(name,'./alphafold/data')\n",
762
+ " model_runner = model.RunModel(cfg, params, is_training=is_training)\n",
763
+ " COMPILED = compiled\n",
764
+ " recompile = False\n",
765
+ "\n",
766
+ " else:\n",
767
+ " cf.clear_mem(\"gpu\")\n",
768
+ " recompile = True\n",
769
+ "\n",
770
+ " # cleanup\n",
771
+ " if \"outs\" in dir(): del outs\n",
772
+ " outs = {}\n",
773
+ " cf.clear_mem(\"cpu\") \n",
774
+ "\n",
775
+ " #######################################################################\n",
776
+ " def report(key):\n",
777
+ " pbar.update(n=1)\n",
778
+ " o = outs[key]\n",
779
+ " line = f\"{key} recycles:{o['recycles']} tol:{o['tol']:.2f} pLDDT:{o['pLDDT']:.2f}\"\n",
780
+ " if use_ptm: line += f\" pTMscore:{o['pTMscore']:.2f}\"\n",
781
+ " print(line)\n",
782
+ " if show_images:\n",
783
+ " fig = cf.plot_protein(o['unrelaxed_protein'], Ls=Ls_plot, dpi=100)\n",
784
+ " plt.show()\n",
785
+ " if save_tmp_pdb:\n",
786
+ " tmp_pdb_path = os.path.join(output_dir,f'unranked_{key}_unrelaxed.pdb')\n",
787
+ " pdb_lines = protein.to_pdb(o['unrelaxed_protein'])\n",
788
+ " with open(tmp_pdb_path, 'w') as f: f.write(pdb_lines)\n",
789
+ "\n",
790
+ " if use_turbo:\n",
791
+ " # go through each random_seed\n",
792
+ " for seed in range(num_samples):\n",
793
+ " \n",
794
+ " # prep input features\n",
795
+ " if subsample_msa:\n",
796
+ " sampled_feats_dict = do_subsample_msa(feature_dict, random_seed=seed) \n",
797
+ " processed_feature_dict = model_runner.process_features(sampled_feats_dict, random_seed=seed)\n",
798
+ " else:\n",
799
+ " processed_feature_dict = model_runner.process_features(feature_dict, random_seed=seed)\n",
800
+ "\n",
801
+ " # go through each model\n",
802
+ " for num, model_name in enumerate(model_names):\n",
803
+ " name = model_name+\"_ptm\" if use_ptm else model_name\n",
804
+ " key = f\"{name}_seed_{seed}\"\n",
805
+ " pbar.set_description(f'Running {key}')\n",
806
+ "\n",
807
+ " # replace model parameters\n",
808
+ " params = data.get_model_haiku_params(name, './alphafold/data')\n",
809
+ " for k in model_runner.params.keys():\n",
810
+ " model_runner.params[k] = params[k]\n",
811
+ "\n",
812
+ " # predict\n",
813
+ " prediction_result, (r, t) = cf.to(model_runner.predict(processed_feature_dict, random_seed=seed),\"cpu\")\n",
814
+ "\n",
815
+ " # save results\n",
816
+ " outs[key] = parse_results(prediction_result, processed_feature_dict)\n",
817
+ " outs[key].update({\"recycles\":r, \"tol\":t})\n",
818
+ " report(key)\n",
819
+ "\n",
820
+ " del prediction_result, params\n",
821
+ " del sampled_feats_dict, processed_feature_dict\n",
822
+ "\n",
823
+ " else: \n",
824
+ " # go through each model\n",
825
+ " for num, model_name in enumerate(model_names):\n",
826
+ " name = model_name+\"_ptm\" if use_ptm else model_name\n",
827
+ " params = data.get_model_haiku_params(name, './alphafold/data') \n",
828
+ " cfg = config.model_config(name)\n",
829
+ " cfg.data.common.num_recycle = cfg.model.num_recycle = max_recycles\n",
830
+ " cfg.model.recycle_tol = tol\n",
831
+ " cfg.data.eval.num_ensemble = num_ensemble\n",
832
+ " model_runner = model.RunModel(cfg, params, is_training=is_training)\n",
833
+ "\n",
834
+ " # go through each random_seed\n",
835
+ " for seed in range(num_samples):\n",
836
+ " key = f\"{name}_seed_{seed}\"\n",
837
+ " pbar.set_description(f'Running {key}')\n",
838
+ " processed_feature_dict = model_runner.process_features(feature_dict, random_seed=seed)\n",
839
+ " prediction_result, (r, t) = cf.to(model_runner.predict(processed_feature_dict, random_seed=seed),\"cpu\")\n",
840
+ " outs[key] = parse_results(prediction_result, processed_feature_dict)\n",
841
+ " outs[key].update({\"recycles\":r, \"tol\":t})\n",
842
+ " report(key)\n",
843
+ "\n",
844
+ " # cleanup\n",
845
+ " del processed_feature_dict, prediction_result\n",
846
+ "\n",
847
+ " del params, model_runner, cfg\n",
848
+ " cf.clear_mem(\"gpu\")\n",
849
+ "\n",
850
+ " # delete old files\n",
851
+ " for f in os.listdir(output_dir):\n",
852
+ " if \"rank\" in f:\n",
853
+ " os.remove(os.path.join(output_dir, f))\n",
854
+ "\n",
855
+ " # Find the best model according to the mean pLDDT.\n",
856
+ " model_rank = list(outs.keys())\n",
857
+ " model_rank = [model_rank[i] for i in np.argsort([outs[x][rank_by] for x in model_rank])[::-1]]\n",
858
+ "\n",
859
+ " # Write out the prediction\n",
860
+ " for n,key in enumerate(model_rank):\n",
861
+ " prefix = f\"rank_{n+1}_{key}\" \n",
862
+ " pred_output_path = os.path.join(output_dir,f'{prefix}_unrelaxed.pdb')\n",
863
+ " fig = cf.plot_protein(outs[key][\"unrelaxed_protein\"], Ls=Ls_plot, dpi=200)\n",
864
+ " plt.savefig(os.path.join(output_dir,f'{prefix}.png'), bbox_inches = 'tight')\n",
865
+ " plt.close(fig)\n",
866
+ "\n",
867
+ " pdb_lines = protein.to_pdb(outs[key][\"unrelaxed_protein\"])\n",
868
+ " with open(pred_output_path, 'w') as f:\n",
869
+ " f.write(pdb_lines)\n",
870
+ " \n",
871
+ "############################################################\n",
872
+ "print(f\"model rank based on {rank_by}\")\n",
873
+ "for n,key in enumerate(model_rank):\n",
874
+ " print(f\"rank_{n+1}_{key} {rank_by}:{outs[key][rank_by]:.2f}\")"
875
+ ],
876
+ "execution_count": null,
877
+ "outputs": []
878
+ },
879
+ {
880
+ "cell_type": "code",
881
+ "metadata": {
882
+ "id": "PnMog4kHUztt",
883
+ "cellView": "form"
884
+ },
885
+ "source": [
886
+ "#@title Refine structures with Amber-Relax (Optional)\n",
887
+ "#@markdown If side-chain bond geometry is important to you, enable Amber-Relax by specifying how many top ranked structures you want relaxed. By default, we disable Amber-Relax since it barely moves the main-chain (backbone) structure and can overall double the runtime.\n",
888
+ "num_relax = \"None\" #@param [\"None\", \"Top1\", \"Top5\", \"All\"] {type:\"string\"}\n",
889
+ "if num_relax == \"None\":\n",
890
+ " num_relax = 0\n",
891
+ "elif num_relax == \"Top1\":\n",
892
+ " num_relax = 1\n",
893
+ "elif num_relax == \"Top5\":\n",
894
+ " num_relax = 5\n",
895
+ "else:\n",
896
+ " num_relax = len(model_names) * num_samples\n",
897
+ "\n",
898
+ "#@markdown - `num_relax` specify how many of the top ranked structures to relax\n",
899
+ "if num_relax > 0 and not os.path.isfile(\"stereo_chemical_props.txt\"):\n",
900
+ " try:\n",
901
+ " total = 45\n",
902
+ " with tqdm.notebook.tqdm(total=total, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
903
+ " pbar.set_description(f'INSTALL AMBER')\n",
904
+ " with io.capture_output() as captured:\n",
905
+ " # Install OpenMM and pdbfixer.\n",
906
+ " %shell rm -rf /opt/conda\n",
907
+ " %shell wget -q -P /tmp \\\n",
908
+ " https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \\\n",
909
+ " && bash /tmp/Miniconda3-latest-Linux-x86_64.sh -b -p /opt/conda \\\n",
910
+ " && rm /tmp/Miniconda3-latest-Linux-x86_64.sh\n",
911
+ " pbar.update(4)\n",
912
+ "\n",
913
+ " PATH=%env PATH\n",
914
+ " %env PATH=/opt/conda/bin:{PATH}\n",
915
+ " %shell conda update -qy conda \\\n",
916
+ " && conda install -qy -c conda-forge \\\n",
917
+ " python={python_version} \\\n",
918
+ " openmm=7.5.1 \\\n",
919
+ " pdbfixer\n",
920
+ " pbar.update(40)\n",
921
+ "\n",
922
+ " %shell wget -q -P /content \\\n",
923
+ " https://git.scicore.unibas.ch/schwede/openstructure/-/raw/7102c63615b64735c4941278d92b554ec94415f8/modules/mol/alg/src/stereo_chemical_props.txt\n",
924
+ " pbar.update(1)\n",
925
+ " %shell mkdir -p /content/alphafold/common\n",
926
+ " %shell cp -f /content/stereo_chemical_props.txt /content/alphafold/common\n",
927
+ "\n",
928
+ " # Apply OpenMM patch.\n",
929
+ " %shell pushd /opt/conda/lib/python{python_version}/site-packages/ && \\\n",
930
+ " patch -p0 < /content/alphafold/docker/openmm.patch && \\\n",
931
+ " popd\n",
932
+ "\n",
933
+ " except subprocess.CalledProcessError:\n",
934
+ " print(captured)\n",
935
+ " raise\n",
936
+ "\n",
937
+ "if num_relax > 0:\n",
938
+ " if \"relax\" not in dir():\n",
939
+ " # add conda environment to path\n",
940
+ " sys.path.append(f\"/opt/conda/lib/python{python_version}/site-packages\")\n",
941
+ " \n",
942
+ " # import libraries\n",
943
+ " from alphafold.relax import relax\n",
944
+ " from alphafold.relax import utils\n",
945
+ "\n",
946
+ " with tqdm.notebook.tqdm(total=num_relax, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
947
+ " pbar.set_description(f'AMBER relaxation')\n",
948
+ " for n,key in enumerate(model_rank):\n",
949
+ " if n < num_relax:\n",
950
+ " prefix = f\"rank_{n+1}_{key}\" \n",
951
+ " pred_output_path = os.path.join(output_dir,f'{prefix}_relaxed.pdb')\n",
952
+ " if not os.path.isfile(pred_output_path):\n",
953
+ " amber_relaxer = relax.AmberRelaxation(\n",
954
+ " max_iterations=0,\n",
955
+ " tolerance=2.39,\n",
956
+ " stiffness=10.0,\n",
957
+ " exclude_residues=[],\n",
958
+ " max_outer_iterations=20)\n",
959
+ " relaxed_pdb_lines, _, _ = amber_relaxer.process(prot=outs[key][\"unrelaxed_protein\"]) \n",
960
+ " with open(pred_output_path, 'w') as f:\n",
961
+ " f.write(relaxed_pdb_lines)\n",
962
+ " pbar.update(n=1)"
963
+ ],
964
+ "execution_count": null,
965
+ "outputs": []
966
+ },
967
+ {
968
+ "cell_type": "code",
969
+ "metadata": {
970
+ "id": "KAZj6CBZTkJM",
971
+ "cellView": "form"
972
+ },
973
+ "source": [
974
+ "#@title Display 3D structure {run: \"auto\"}\n",
975
+ "rank_num = 1 #@param [\"1\", \"2\", \"3\", \"4\", \"5\"] {type:\"raw\"}\n",
976
+ "color = \"lDDT\" #@param [\"chain\", \"lDDT\", \"rainbow\"]\n",
977
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
978
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
979
+ "\n",
980
+ "key = model_rank[rank_num-1]\n",
981
+ "prefix = f\"rank_{rank_num}_{key}\" \n",
982
+ "pred_output_path = os.path.join(output_dir,f'{prefix}_relaxed.pdb') \n",
983
+ "if not os.path.isfile(pred_output_path):\n",
984
+ " pred_output_path = os.path.join(output_dir,f'{prefix}_unrelaxed.pdb') \n",
985
+ "\n",
986
+ "cf.show_pdb(pred_output_path, show_sidechains, show_mainchains, color, Ls=Ls_plot).show()\n",
987
+ "if color == \"lDDT\": cf.plot_plddt_legend().show() \n",
988
+ "if use_ptm:\n",
989
+ " cf.plot_confidence(outs[key][\"plddt\"], outs[key][\"pae\"], Ls=Ls_plot).show()\n",
990
+ "else:\n",
991
+ " cf.plot_confidence(outs[key][\"plddt\"], Ls=Ls_plot).show()"
992
+ ],
993
+ "execution_count": null,
994
+ "outputs": []
995
+ },
996
+ {
997
+ "cell_type": "code",
998
+ "metadata": {
999
+ "id": "XzK2Wve12GCk",
1000
+ "cellView": "form"
1001
+ },
1002
+ "source": [
1003
+ "#@title Extra outputs\n",
1004
+ "dpi = 100#@param {type:\"integer\"}\n",
1005
+ "save_to_txt = True #@param {type:\"boolean\"}\n",
1006
+ "save_pae_json = True #@param {type:\"boolean\"}\n",
1007
+ "#@markdown - save data used to generate contact and distogram plots below to text file (pae values can be found in json file if `use_ptm` is enabled)\n",
1008
+ "\n",
1009
+ "if use_ptm:\n",
1010
+ " print(\"predicted alignment error\")\n",
1011
+ " cf.plot_paes([outs[k][\"pae\"] for k in model_rank], Ls=Ls_plot, dpi=dpi)\n",
1012
+ " plt.savefig(os.path.join(output_dir,f'predicted_alignment_error.png'), bbox_inches = 'tight', dpi=np.maximum(200,dpi))\n",
1013
+ " plt.show()\n",
1014
+ "\n",
1015
+ "print(\"predicted contacts\")\n",
1016
+ "cf.plot_adjs([outs[k][\"adj\"] for k in model_rank], Ls=Ls_plot, dpi=dpi)\n",
1017
+ "plt.savefig(os.path.join(output_dir,f'predicted_contacts.png'), bbox_inches = 'tight', dpi=np.maximum(200,dpi))\n",
1018
+ "plt.show()\n",
1019
+ "\n",
1020
+ "print(\"predicted distogram\")\n",
1021
+ "cf.plot_dists([outs[k][\"dists\"] for k in model_rank], Ls=Ls_plot, dpi=dpi)\n",
1022
+ "plt.savefig(os.path.join(output_dir,f'predicted_distogram.png'), bbox_inches = 'tight', dpi=np.maximum(200,dpi))\n",
1023
+ "plt.show()\n",
1024
+ "\n",
1025
+ "print(\"predicted LDDT\")\n",
1026
+ "cf.plot_plddts([outs[k][\"plddt\"] for k in model_rank], Ls=Ls_plot, dpi=dpi)\n",
1027
+ "plt.savefig(os.path.join(output_dir,f'predicted_LDDT.png'), bbox_inches = 'tight', dpi=np.maximum(200,dpi))\n",
1028
+ "plt.show()\n",
1029
+ "\n",
1030
+ "def do_save_to_txt(filename, adj, dists):\n",
1031
+ " adj = np.asarray(adj)\n",
1032
+ " dists = np.asarray(dists)\n",
1033
+ " L = len(adj)\n",
1034
+ " with open(filename,\"w\") as out:\n",
1035
+ " out.write(\"i\\tj\\taa_i\\taa_j\\tp(cbcb<8)\\tmaxdistbin\\n\")\n",
1036
+ " for i in range(L):\n",
1037
+ " for j in range(i+1,L):\n",
1038
+ " if dists[i][j] < 21.68 or adj[i][j] >= 0.001:\n",
1039
+ " line = f\"{i+1}\\t{j+1}\\t{full_sequence[i]}\\t{full_sequence[j]}\\t{adj[i][j]:.3f}\"\n",
1040
+ " line += f\"\\t>{dists[i][j]:.2f}\" if dists[i][j] == 21.6875 else f\"\\t{dists[i][j]:.2f}\"\n",
1041
+ " out.write(f\"{line}\\n\")\n",
1042
+ "\n",
1043
+ "for n,key in enumerate(model_rank):\n",
1044
+ " if save_to_txt:\n",
1045
+ " txt_filename = os.path.join(output_dir,f'rank_{n+1}_{key}.raw.txt')\n",
1046
+ " do_save_to_txt(txt_filename,adj=outs[key][\"adj\"],dists=outs[key][\"dists\"])\n",
1047
+ "\n",
1048
+ " if use_ptm and save_pae_json:\n",
1049
+ " pae = outs[key][\"pae\"]\n",
1050
+ " max_pae = pae.max()\n",
1051
+ " # Save pLDDT and predicted aligned error (if it exists)\n",
1052
+ " pae_output_path = os.path.join(output_dir,f'rank_{n+1}_{key}_pae.json')\n",
1053
+ " # Save predicted aligned error in the same format as the AF EMBL DB\n",
1054
+ " rounded_errors = np.round(np.asarray(pae), decimals=1)\n",
1055
+ " indices = np.indices((len(rounded_errors), len(rounded_errors))) + 1\n",
1056
+ " indices_1 = indices[0].flatten().tolist()\n",
1057
+ " indices_2 = indices[1].flatten().tolist()\n",
1058
+ " pae_data = json.dumps([{\n",
1059
+ " 'residue1': indices_1,\n",
1060
+ " 'residue2': indices_2,\n",
1061
+ " 'distance': rounded_errors.flatten().tolist(),\n",
1062
+ " 'max_predicted_aligned_error': max_pae.item()\n",
1063
+ " }],\n",
1064
+ " indent=None,\n",
1065
+ " separators=(',', ':'))\n",
1066
+ " with open(pae_output_path, 'w') as f:\n",
1067
+ " f.write(pae_data)"
1068
+ ],
1069
+ "execution_count": null,
1070
+ "outputs": []
1071
+ },
1072
+ {
1073
+ "cell_type": "code",
1074
+ "metadata": {
1075
+ "id": "Riekgf0KQv_3",
1076
+ "cellView": "form"
1077
+ },
1078
+ "source": [
1079
+ "#@title Download prediction\n",
1080
+ "\n",
1081
+ "#@markdown Once this cell has been executed, a zip-archive with \n",
1082
+ "#@markdown the obtained prediction will be automatically downloaded \n",
1083
+ "#@markdown to your computer.\n",
1084
+ "\n",
1085
+ "# add settings file\n",
1086
+ "settings_path = os.path.join(output_dir,\"settings.txt\")\n",
1087
+ "with open(settings_path, \"w\") as text_file:\n",
1088
+ " text_file.write(f\"notebook=https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/AlphaFold2_advanced.ipynb\\n\")\n",
1089
+ " text_file.write(f\"sequence={ori_sequence}\\n\")\n",
1090
+ " text_file.write(f\"msa_method={msa_method}\\n\")\n",
1091
+ " if add_custom_msa:\n",
1092
+ " text_file.write(f\"add_custom_msa={add_custom_msa} msa_format={msa_format}\\n\")\n",
1093
+ " text_file.write(f\"homooligomer={homooligomer}\\n\")\n",
1094
+ "\n",
1095
+ " text_file.write(f\"pair_mode={pair_mode}\\n\")\n",
1096
+ " if pair_mode != \"unpaired\":\n",
1097
+ " text_file.write(f\"pair_cov={pair_cov}\\n\")\n",
1098
+ " text_file.write(f\"pair_qid={pair_qid}\\n\")\n",
1099
+ "\n",
1100
+ " text_file.write(f\"max_msa={max_msa}\\n\")\n",
1101
+ " text_file.write(f\"subsample_msa={subsample_msa}\\n\") \n",
1102
+ " text_file.write(f\"num_relax={num_relax}\\n\")\n",
1103
+ " text_file.write(f\"use_turbo={use_turbo}\\n\")\n",
1104
+ " text_file.write(f\"use_ptm={use_ptm}\\n\")\n",
1105
+ " text_file.write(f\"rank_by={rank_by}\\n\")\n",
1106
+ " text_file.write(f\"num_models={num_models}\\n\")\n",
1107
+ " text_file.write(f\"num_samples={num_samples}\\n\")\n",
1108
+ " text_file.write(f\"num_ensemble={num_ensemble}\\n\")\n",
1109
+ " text_file.write(f\"max_recycles={max_recycles}\\n\")\n",
1110
+ " text_file.write(f\"tol={tol}\\n\")\n",
1111
+ " text_file.write(f\"is_training={is_training}\\n\")\n",
1112
+ " text_file.write(f\"use_templates=False\\n\")\n",
1113
+ " text_file.write(f\"-------------------------------------------------\\n\")\n",
1114
+ "\n",
1115
+ " for n,key in enumerate(model_rank):\n",
1116
+ " line = f\"rank_{n+1}_{key} pLDDT:{outs[key]['pLDDT']:.2f}\" + f\" pTMscore:{outs[key]['pTMscore']:.4f}\" if use_ptm else \"\"\n",
1117
+ " text_file.write(line+\"\\n\")\n",
1118
+ "\n",
1119
+ "# --- Download the predictions ---\n",
1120
+ "!zip -FSr {output_dir}.zip {output_dir}\n",
1121
+ "files.download(f'{output_dir}.zip')"
1122
+ ],
1123
+ "execution_count": null,
1124
+ "outputs": []
1125
+ }
1126
+ ]
1127
+ }
data/beta/AlphaFold2_complexes.ipynb ADDED
@@ -0,0 +1,647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "accelerator": "GPU",
6
+ "colab": {
7
+ "name": "AlphaFold2_complexes.ipynb",
8
+ "provenance": [],
9
+ "collapsed_sections": [],
10
+ "machine_shape": "hm",
11
+ "include_colab_link": true
12
+ },
13
+ "kernelspec": {
14
+ "display_name": "Python 3",
15
+ "name": "python3"
16
+ },
17
+ "language_info": {
18
+ "name": "python"
19
+ }
20
+ },
21
+ "cells": [
22
+ {
23
+ "cell_type": "markdown",
24
+ "metadata": {
25
+ "id": "view-in-github",
26
+ "colab_type": "text"
27
+ },
28
+ "source": [
29
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/AlphaFold2_complexes.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "metadata": {
35
+ "id": "G4yBrceuFbf3"
36
+ },
37
+ "source": [
38
+ "#AlphaFold2_complexes\n",
39
+ "\n",
40
+ "---------\n",
41
+ "**UPDATE** (Aug. 13, 2021)\n",
42
+ "\n",
43
+ "This notebook is being retired and no longer updated. The functionality for complex prediction (including going beyond dimers) has been integrated in our [new advanced notebook](https://github.com/sokrypton/ColabFold/blob/main/beta/AlphaFold2_advanced.ipynb).\n",
44
+ "\n",
45
+ "---------\n",
46
+ "\n",
47
+ "Credit to Minkyung Baek @minkbaek and Yoshitaka Moriwaki @Ag_smith for initially showing protein-complex prediction works in alphafold2.\n",
48
+ "- https://twitter.com/minkbaek/status/1417538291709071362\n",
49
+ "- https://twitter.com/Ag_smith/status/1417063635000598528\n",
50
+ "\n",
51
+ "- [script](https://github.com/RosettaCommons/RoseTTAFold/blob/main/example/complex_modeling/make_joint_MSA_bacterial.py) from rosettafold for paired alignment generation\n",
52
+ "\n",
53
+ "**Instructions**\n",
54
+ "- For *monomers* and *homo-oligomers*, see this [notebook](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/AlphaFold2.ipynb).\n",
55
+ "- For prokaryotic protein complexes (found in operons), we recommend using the `pair_msa` option.\n",
56
+ "\n",
57
+ "\n",
58
+ "**Limitations**\n",
59
+ "- This notebook does NOT use templates or amber relax at the end for refinement.\n",
60
+ "- For a typical Google-Colab-GPU (16G) session, the max total length is **1400 residues**.\n"
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "metadata": {
66
+ "id": "kOblAo-xetgx",
67
+ "cellView": "form"
68
+ },
69
+ "source": [
70
+ "#@title Input protein sequences\n",
71
+ "import os\n",
72
+ "os.environ['TF_FORCE_UNIFIED_MEMORY'] = '1'\n",
73
+ "os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION'] = '2.0'\n",
74
+ "\n",
75
+ "from google.colab import files\n",
76
+ "import os.path\n",
77
+ "import re\n",
78
+ "\n",
79
+ "import hashlib\n",
80
+ "def add_hash(x,y):\n",
81
+ " return x+\"_\"+hashlib.sha1(y.encode()).hexdigest()[:5]\n",
82
+ "\n",
83
+ "query_sequence_a = 'AVLKIIQGALDTRELLKAYQEEACAKNFGAFCVFVGIVRKEDNIQGLSFDIYEALLKTWFEKWHHKAKDLGVVLKMAHSLGDVLIGQSSFLCVSMGKNRKNALELYENFIEDFKHNAPIWKYDLIHNKRIYAKERSHPLKGSGLLA' #@param {type:\"string\"}\n",
84
+ "query_sequence_a = \"\".join(query_sequence_a.split())\n",
85
+ "query_sequence_a = re.sub(r'[^A-Z]','', query_sequence_a.upper())\n",
86
+ "\n",
87
+ "query_sequence_b = 'MMVEVRFFGPIKEENFFIKANDLKELRAILQEKEGLKEWLGVCAIALNDHLIDNLNTPLKDGDVISLLPPVCGG' #@param {type:\"string\"}\n",
88
+ "query_sequence_b = \"\".join(query_sequence_b.split())\n",
89
+ "query_sequence_b = re.sub(r'[^A-Z]','', query_sequence_b.upper())\n",
90
+ "\n",
91
+ "# Using trick from @onoda_hiroki\n",
92
+ "# https://twitter.com/onoda_hiroki/status/1420068104239910915\n",
93
+ "# \"U\" indicates an \"UNKNOWN\" residue and it will not be modeled\n",
94
+ "# But we need linker of at least length 32\n",
95
+ "query_sequence_a = re.sub(r'U+',\"U\"*32,query_sequence_a)\n",
96
+ "query_sequence_b = re.sub(r'U+',\"U\"*32,query_sequence_b)\n",
97
+ "\n",
98
+ "query_sequence = query_sequence_a + query_sequence_b\n",
99
+ "\n",
100
+ "if len(query_sequence) > 1400:\n",
101
+ " print(f\"WARNING: For a typical Google-Colab-GPU (16G) session, the max total length is 1400 residues. You are at {len(query_sequence)}!\")\n",
102
+ "\n",
103
+ "jobname = 'test' #@param {type:\"string\"}\n",
104
+ "jobname = \"\".join(jobname.split())\n",
105
+ "jobname = re.sub(r'\\W+', '', jobname)\n",
106
+ "jobname = add_hash(jobname, query_sequence)\n",
107
+ "\n",
108
+ "# number of models to use\n",
109
+ "#@markdown ---\n",
110
+ "#@markdown ### Advanced settings\n",
111
+ "num_models = 5 #@param [1,2,3,4,5] {type:\"raw\"}\n",
112
+ "msa_mode = \"MMseqs2\" #@param [\"MMseqs2\",\"single_sequence\"]\n",
113
+ "use_msa = True if msa_mode == \"MMseqs2\" else False\n",
114
+ "pair_msa = False #@param {type:\"boolean\"}\n",
115
+ "disable_mmseqs2_filter = pair_msa\n",
116
+ "\n",
117
+ "#@markdown ---\n",
118
+ "with open(f\"{jobname}.log\", \"w\") as text_file:\n",
119
+ " text_file.write(\"num_models=%s\\n\" % num_models)\n",
120
+ " text_file.write(\"use_msa=%s\\n\" % use_msa)\n",
121
+ " text_file.write(\"msa_mode=%s\\n\" % msa_mode)\n",
122
+ " text_file.write(\"pair_msa=%s\\n\" % pair_msa)\n",
123
+ " text_file.write(\"disable_mmseqs2_filter=%s\\n\" % disable_mmseqs2_filter)"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {
131
+ "id": "iccGdbe_Pmt9",
132
+ "cellView": "form"
133
+ },
134
+ "source": [
135
+ "#@title Install dependencies\n",
136
+ "%%bash -s $use_msa\n",
137
+ "USE_MSA=$1\n",
138
+ "if [ ! -f AF2_READY ]; then\n",
139
+ "\n",
140
+ " # install dependencies\n",
141
+ " pip -q install biopython\n",
142
+ " pip -q install dm-haiku\n",
143
+ " pip -q install ml-collections\n",
144
+ " pip -q install py3Dmol\n",
145
+ "\n",
146
+ " wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/colabfold.py\n",
147
+ "\n",
148
+ " # download model\n",
149
+ " if [ ! -d \"alphafold/\" ]; then\n",
150
+ " git clone https://github.com/deepmind/alphafold.git --quiet\n",
151
+ " mv alphafold alphafold_\n",
152
+ " mv alphafold_/alphafold .\n",
153
+ " # remove \"END\" from PDBs, otherwise biopython complains\n",
154
+ " sed -i \"s/pdb_lines.append('END')//\" /content/alphafold/common/protein.py\n",
155
+ " sed -i \"s/pdb_lines.append('ENDMDL')//\" /content/alphafold/common/protein.py\n",
156
+ " fi\n",
157
+ " # download model params (~1 min)\n",
158
+ " if [ ! -d \"params/\" ]; then\n",
159
+ " wget -qnc https://storage.googleapis.com/alphafold/alphafold_params_2021-07-14.tar\n",
160
+ " mkdir params\n",
161
+ " tar -xf alphafold_params_2021-07-14.tar -C params/\n",
162
+ " rm alphafold_params_2021-07-14.tar\n",
163
+ " fi\n",
164
+ " touch AF2_READY\n",
165
+ "fi"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {
173
+ "id": "JPWfhGssZdTb",
174
+ "cellView": "form"
175
+ },
176
+ "source": [
177
+ "#@title Import libraries\n",
178
+ "# setup the model\n",
179
+ "if \"IMPORTED\" not in dir():\n",
180
+ "\n",
181
+ " import time\n",
182
+ " import requests\n",
183
+ " import tarfile\n",
184
+ " import sys\n",
185
+ " import numpy as np\n",
186
+ " import pickle\n",
187
+ "\n",
188
+ " from string import ascii_uppercase\n",
189
+ " from alphafold.common import protein\n",
190
+ " from alphafold.data import pipeline\n",
191
+ " from alphafold.data import templates\n",
192
+ " from alphafold.model import data\n",
193
+ " from alphafold.model import config\n",
194
+ " from alphafold.model import model\n",
195
+ " from alphafold.data.tools import hhsearch\n",
196
+ "\n",
197
+ " import colabfold as cf\n",
198
+ "\n",
199
+ " # plotting libraries\n",
200
+ " import py3Dmol\n",
201
+ " import matplotlib.pyplot as plt\n",
202
+ " IMPORTED = True\n",
203
+ "\n",
204
+ "def set_bfactor(pdb_filename, bfac, idx_res, chains):\n",
205
+ " I = open(pdb_filename,\"r\").readlines()\n",
206
+ " O = open(pdb_filename,\"w\")\n",
207
+ " for line in I:\n",
208
+ " if line[0:6] == \"ATOM \":\n",
209
+ " seq_id = int(line[22:26].strip()) - 1\n",
210
+ " seq_id = np.where(idx_res == seq_id)[0][0]\n",
211
+ " O.write(f\"{line[:21]}{chains[seq_id]}{line[22:60]}{bfac[seq_id]:6.2f}{line[66:]}\")\n",
212
+ " O.close()\n",
213
+ "\n",
214
+ "def predict_structure(prefix, feature_dict, Ls, random_seed=0, num_models=5): \n",
215
+ " \"\"\"Predicts structure using AlphaFold for the given sequence.\"\"\"\n",
216
+ " # Minkyung's code\n",
217
+ " # add big enough number to residue index to indicate chain breaks\n",
218
+ " idx_res = feature_dict['residue_index']\n",
219
+ " L_prev = 0\n",
220
+ " # Ls: number of residues in each chain\n",
221
+ " for L_i in Ls[:-1]:\n",
222
+ " idx_res[L_prev+L_i:] += 200\n",
223
+ " L_prev += L_i \n",
224
+ " chains = list(\"\".join([ascii_uppercase[n]*L for n,L in enumerate(Ls)]))\n",
225
+ " feature_dict['residue_index'] = idx_res\n",
226
+ "\n",
227
+ " # Run the models.\n",
228
+ " plddts = []\n",
229
+ " paes = []\n",
230
+ " unrelaxed_pdb_lines = []\n",
231
+ " relaxed_pdb_lines = []\n",
232
+ "\n",
233
+ " model_names = [\"model_4\",\"model_1\",\"model_2\",\"model_3\",\"model_5\"][:num_models]\n",
234
+ " for n,model_name in enumerate(model_names):\n",
235
+ " model_config = config.model_config(model_name+\"_ptm\")\n",
236
+ " model_config.data.eval.num_ensemble = 1\n",
237
+ " model_params = data.get_model_haiku_params(model_name+\"_ptm\", data_dir=\".\")\n",
238
+ "\n",
239
+ " if model_name == \"model_4\":\n",
240
+ " model_runner = model.RunModel(model_config, model_params)\n",
241
+ " processed_feature_dict = model_runner.process_features(feature_dict,random_seed=0)\n",
242
+ " else:\n",
243
+ " # swap params\n",
244
+ " for k in model_runner.params.keys():\n",
245
+ " model_runner.params[k] = model_params[k]\n",
246
+ "\n",
247
+ " print(f\"running model_{n+1}\")\n",
248
+ " prediction_result = model_runner.predict(processed_feature_dict)\n",
249
+ "\n",
250
+ " # cleanup to save memory\n",
251
+ " if model_name == \"model_5\": del model_runner\n",
252
+ " del model_params\n",
253
+ " \n",
254
+ " unrelaxed_protein = protein.from_prediction(processed_feature_dict,prediction_result)\n",
255
+ " unrelaxed_pdb_lines.append(protein.to_pdb(unrelaxed_protein))\n",
256
+ " plddts.append(prediction_result['plddt'])\n",
257
+ " paes.append(prediction_result['predicted_aligned_error'])\n",
258
+ "\n",
259
+ " # Delete unused outputs to save memory.\n",
260
+ " del prediction_result\n",
261
+ "\n",
262
+ " # rerank models based on predicted lddt\n",
263
+ " lddt_rank = np.mean(plddts,-1).argsort()[::-1]\n",
264
+ " plddts_ranked = {}\n",
265
+ " paes_ranked = {}\n",
266
+ " print(\"model\\tplldt\\tpae_ab\")\n",
267
+ " L = Ls[0]\n",
268
+ " for n,r in enumerate(lddt_rank):\n",
269
+ " plddt = plddts[r].mean()\n",
270
+ " pae_ab = (paes[r][L:,:L].mean() + paes[r][:L,L:].mean()) / 2\n",
271
+ " print(f\"model_{n+1}\\t{plddt:.2f}\\t{pae_ab:.2f}\")\n",
272
+ " \n",
273
+ " unrelaxed_pdb_path = f'{prefix}_unrelaxed_model_{n+1}.pdb' \n",
274
+ " with open(unrelaxed_pdb_path, 'w') as f:\n",
275
+ " f.write(unrelaxed_pdb_lines[r])\n",
276
+ " set_bfactor(unrelaxed_pdb_path, plddts[r], idx_res, chains)\n",
277
+ "\n",
278
+ " plddts_ranked[f\"model_{n+1}\"] = plddts[r]\n",
279
+ " paes_ranked[f\"model_{n+1}\"] = paes[r]\n",
280
+ "\n",
281
+ " return plddts_ranked, paes_ranked\n",
282
+ "\n",
283
+ "# CODE FROM MINKYUNG/ROSETTAFOLD\n",
284
+ "def read_a3m(a3m_lines):\n",
285
+ " '''parse an a3m files as a dictionary {label->sequence}'''\n",
286
+ " seq = []\n",
287
+ " lab = []\n",
288
+ " is_first = True\n",
289
+ " for line in a3m_lines.splitlines():\n",
290
+ " if line[0] == '>':\n",
291
+ " label = line.rstrip().split()[0][1:]\n",
292
+ " is_incl = True\n",
293
+ " if is_first: # include first sequence (query)\n",
294
+ " is_first = False\n",
295
+ " lab.append(label)\n",
296
+ " continue\n",
297
+ " if \"UniRef\" in label:\n",
298
+ " code = label.split()[0].split('_')[-1]\n",
299
+ " if code.startswith(\"UPI\"): # UniParc identifier -- exclude\n",
300
+ " is_incl = False\n",
301
+ " continue\n",
302
+ " elif label.startswith(\"tr|\"):\n",
303
+ " code = label.split('|')[1]\n",
304
+ " else:\n",
305
+ " is_incl = False\n",
306
+ " continue\n",
307
+ " lab.append(code)\n",
308
+ " else:\n",
309
+ " if is_incl:\n",
310
+ " seq.append(line.rstrip())\n",
311
+ " else:\n",
312
+ " continue\n",
313
+ " return seq, lab\n",
314
+ "\n",
315
+ "# https://www.uniprot.org/help/accession_numbers\n",
316
+ "def uni2idx(ids):\n",
317
+ " '''convert uniprot ids into integers according to the structure\n",
318
+ " of uniprot accession numbers'''\n",
319
+ " ids2 = [i.split(\"-\")[0] for i in ids]\n",
320
+ " ids2 = [i+'AAA0' if len(i)==6 else i for i in ids2]\n",
321
+ " arr = np.array([list(s) for s in ids2], dtype='|S1').view(np.uint8)\n",
322
+ " for i in [1,5,9]:\n",
323
+ " arr[:,i] -= ord('0')\n",
324
+ " arr[arr>=ord('A')] -= ord('A')\n",
325
+ " arr[arr>=ord('0')] -= ord('0')-26\n",
326
+ " arr[:,0][arr[:,0]>ord('Q')-ord('A')] -= 3\n",
327
+ " arr = arr.astype(np.int64)\n",
328
+ " coef = np.array([23,10,26,36,36,10,26,36,36,1], dtype=np.int64)\n",
329
+ " coef = np.tile(coef[None,:],[len(ids),1])\n",
330
+ " c1 = [i for i,id_ in enumerate(ids) if id_[0] in 'OPQ' and len(id_)==6]\n",
331
+ " c2 = [i for i,id_ in enumerate(ids) if id_[0] not in 'OPQ' and len(id_)==6]\n",
332
+ " coef[c1] = np.array([3, 10,36,36,36,1,1,1,1,1])\n",
333
+ " coef[c2] = np.array([23,10,26,36,36,1,1,1,1,1])\n",
334
+ " for i in range(1,10):\n",
335
+ " coef[:,-i-1] *= coef[:,-i]\n",
336
+ " return np.sum(arr*coef,axis=-1)\n",
337
+ "\n",
338
+ "def run_mmseqs2(query_sequence, prefix, use_env=True, filter=False):\n",
339
+ " def submit(query_sequence, mode):\n",
340
+ " res = requests.post('https://a3m.mmseqs.com/ticket/msa', data={'q':f\">1\\n{query_sequence}\", 'mode': mode})\n",
341
+ " return res.json()\n",
342
+ " def status(ID):\n",
343
+ " res = requests.get(f'https://a3m.mmseqs.com/ticket/{ID}')\n",
344
+ " return res.json()\n",
345
+ " def download(ID, path):\n",
346
+ " res = requests.get(f'https://a3m.mmseqs.com/result/download/{ID}')\n",
347
+ " with open(path,\"wb\") as out: out.write(res.content)\n",
348
+ " \n",
349
+ " if filter:\n",
350
+ " mode = \"env\" if use_env else \"all\"\n",
351
+ " else:\n",
352
+ " mode = \"env-nofilter\" if use_env else \"nofilter\"\n",
353
+ " \n",
354
+ " path = f\"{prefix}_{mode}\"\n",
355
+ " if not os.path.isdir(path): os.mkdir(path)\n",
356
+ "\n",
357
+ " # call mmseqs2 api\n",
358
+ " tar_gz_file = f'{path}/out.tar.gz'\n",
359
+ " if not os.path.isfile(tar_gz_file):\n",
360
+ " out = submit(query_sequence, mode)\n",
361
+ " while out[\"status\"] in [\"RUNNING\",\"PENDING\"]:\n",
362
+ " time.sleep(1)\n",
363
+ " out = status(out[\"id\"]) \n",
364
+ " download(out[\"id\"], tar_gz_file)\n",
365
+ " \n",
366
+ " # parse a3m files\n",
367
+ " a3m_lines = []\n",
368
+ " a3m = f\"{prefix}_{mode}.a3m\"\n",
369
+ " if not os.path.isfile(a3m):\n",
370
+ " with tarfile.open(tar_gz_file) as tar_gz: tar_gz.extractall(path)\n",
371
+ " a3m_files = [f\"{path}/uniref.a3m\"]\n",
372
+ " if use_env: a3m_files.append(f\"{path}/bfd.mgnify30.metaeuk30.smag30.a3m\")\n",
373
+ " a3m_out = open(a3m,\"w\")\n",
374
+ " for a3m_file in a3m_files:\n",
375
+ " for line in open(a3m_file,\"r\"):\n",
376
+ " line = line.replace(\"\\x00\",\"\")\n",
377
+ " if len(line) > 0:\n",
378
+ " a3m_lines.append(line)\n",
379
+ " a3m_out.write(line)\n",
380
+ " else:\n",
381
+ " a3m_lines = open(a3m).readlines()\n",
382
+ " return \"\".join(a3m_lines), len(a3m_lines)"
383
+ ],
384
+ "execution_count": null,
385
+ "outputs": []
386
+ },
387
+ {
388
+ "cell_type": "code",
389
+ "metadata": {
390
+ "id": "A9tUpDaikPC8",
391
+ "cellView": "form"
392
+ },
393
+ "source": [
394
+ "#@title Call MMseqs2 to get MSA for each gene \n",
395
+ "\n",
396
+ "Ls = [len(query_sequence_a),len(query_sequence_b)]\n",
397
+ "msas = []\n",
398
+ "deletion_matrices = []\n",
399
+ "if use_msa:\n",
400
+ " os.makedirs('tmp', exist_ok=True)\n",
401
+ " prefix = hashlib.sha1(query_sequence.encode()).hexdigest()\n",
402
+ " prefix = os.path.join('tmp',prefix)\n",
403
+ " print(f\"running mmseqs2 (use_env={True} filter={True})\")\n",
404
+ " a3m_lines = cf.run_mmseqs2([query_sequence_a, query_sequence_b], prefix, use_env=True, filter=True)\n",
405
+ " if pair_msa:\n",
406
+ " a3m_lines.append([])\n",
407
+ "\n",
408
+ " print(f\"running mmseqs2 for pair_msa (use_env={False} filter={False})\")\n",
409
+ " a3m_lines_pair = cf.run_mmseqs2([query_sequence_a, query_sequence_b], prefix, use_env=False, filter=False)\n",
410
+ "\n",
411
+ " # CODE FROM MINKYUNG/ROSETTAFOLD\n",
412
+ " msa1, lab1 = read_a3m(a3m_lines_pair[0])\n",
413
+ " msa2, lab2 = read_a3m(a3m_lines_pair[1])\n",
414
+ " if len(lab1) > 1 and len(lab2) > 1:\n",
415
+ " # convert uniprot ids into integers\n",
416
+ " hash1 = uni2idx(lab1[1:])\n",
417
+ " hash2 = uni2idx(lab2[1:])\n",
418
+ "\n",
419
+ " # find pairs of uniprot ids which are separated by at most 10\n",
420
+ " idx1, idx2 = np.where(np.abs(hash1[:,None]-hash2[None,:]) < 10)\n",
421
+ " if idx1.shape[0] > 0:\n",
422
+ " a3m_lines[2] = ['>query\\n%s%s\\n'%(msa1[0],msa2[0])]\n",
423
+ " for i,j in zip(idx1,idx2):\n",
424
+ " a3m_lines[2].append(\">%s_%s\\n%s%s\\n\"%(lab1[i+1],lab2[j+1],msa1[i+1],msa2[j+1]))\n",
425
+ " \n",
426
+ " msa, deletion_matrix = pipeline.parsers.parse_a3m(\"\".join(a3m_lines[2]))\n",
427
+ " msas.append(msa)\n",
428
+ " deletion_matrices.append(deletion_matrix)\n",
429
+ " print(\"pairs found:\",len(msa))\n",
430
+ " \n",
431
+ " msa, deletion_matrix = pipeline.parsers.parse_a3m(a3m_lines[0])\n",
432
+ " msas.append([seq+\"-\"*Ls[1] for seq in msa])\n",
433
+ " deletion_matrices.append([mtx+[0]*Ls[1] for mtx in deletion_matrix])\n",
434
+ "\n",
435
+ " msa, deletion_matrix = pipeline.parsers.parse_a3m(a3m_lines[1])\n",
436
+ " msas.append([\"-\"*Ls[0]+seq for seq in msa])\n",
437
+ " deletion_matrices.append([[0]*Ls[0]+mtx for mtx in deletion_matrix])\n",
438
+ "\n",
439
+ "else:\n",
440
+ " msas.append([query_sequence])\n",
441
+ " deletion_matrices.append([[0]*len(query_sequence)])\n",
442
+ "\n",
443
+ "feature_dict = {\n",
444
+ " **pipeline.make_sequence_features(sequence=query_sequence,\n",
445
+ " description=\"none\",\n",
446
+ " num_res=len(query_sequence)),\n",
447
+ " **pipeline.make_msa_features(msas=msas, deletion_matrices=deletion_matrices),\n",
448
+ "}"
449
+ ],
450
+ "execution_count": null,
451
+ "outputs": []
452
+ },
453
+ {
454
+ "cell_type": "code",
455
+ "metadata": {
456
+ "cellView": "form",
457
+ "id": "6sgAOSxCLIfC"
458
+ },
459
+ "source": [
460
+ "#@title Plot Number of Sequences per Position\n",
461
+ "dpi = 100#@param {type:\"integer\"}\n",
462
+ "# confidence per position\n",
463
+ "plt.figure(dpi=dpi)\n",
464
+ "plt.plot((feature_dict[\"msa\"] != 21).sum(0))\n",
465
+ "plt.xlabel(\"positions\")\n",
466
+ "plt.ylabel(\"number of sequences\")\n",
467
+ "plt.savefig(jobname+\"_msa_coverage.png\")\n",
468
+ "plt.show()"
469
+ ],
470
+ "execution_count": null,
471
+ "outputs": []
472
+ },
473
+ {
474
+ "cell_type": "code",
475
+ "metadata": {
476
+ "id": "hUYApPElB30u",
477
+ "cellView": "form"
478
+ },
479
+ "source": [
480
+ "#@title Predict structure\n",
481
+ "plddts, paes = predict_structure(jobname, feature_dict, Ls=Ls, num_models=num_models)"
482
+ ],
483
+ "execution_count": null,
484
+ "outputs": []
485
+ },
486
+ {
487
+ "cell_type": "code",
488
+ "metadata": {
489
+ "id": "oCZxmXKKTAxt",
490
+ "cellView": "form"
491
+ },
492
+ "source": [
493
+ "#@title Plot Predicted Alignment Error\n",
494
+ "dpi = 100#@param {type:\"integer\"}\n",
495
+ "\n",
496
+ "# confidence per position\n",
497
+ "plt.figure(figsize=(3*num_models,2), dpi=dpi)\n",
498
+ "for n,(model_name,value) in enumerate(paes.items()):\n",
499
+ " plt.subplot(1,num_models,n+1)\n",
500
+ " plt.title(model_name)\n",
501
+ " plt.imshow(value,label=model_name,cmap=\"bwr\",vmin=0,vmax=30)\n",
502
+ " plt.colorbar()\n",
503
+ "plt.savefig(jobname+\"_PAE.png\")\n",
504
+ "plt.show()"
505
+ ],
506
+ "execution_count": null,
507
+ "outputs": []
508
+ },
509
+ {
510
+ "cell_type": "code",
511
+ "metadata": {
512
+ "id": "exKwNxDxF7IO",
513
+ "cellView": "form"
514
+ },
515
+ "source": [
516
+ "#@title Plot lDDT per residue\n",
517
+ "# confidence per position\n",
518
+ "dpi = 100#@param {type:\"integer\"}\n",
519
+ "plt.figure(dpi=dpi)\n",
520
+ "for model_name,value in plddts.items():\n",
521
+ " plt.plot(value,label=model_name)\n",
522
+ "plt.legend()\n",
523
+ "plt.ylim(0,100)\n",
524
+ "plt.ylabel(\"predicted lDDT\")\n",
525
+ "plt.xlabel(\"positions\")\n",
526
+ "plt.savefig(jobname+\"_lDDT.png\")\n",
527
+ "plt.show()"
528
+ ],
529
+ "execution_count": null,
530
+ "outputs": []
531
+ },
532
+ {
533
+ "cell_type": "code",
534
+ "metadata": {
535
+ "id": "g-rPnOXdjf18",
536
+ "cellView": "form"
537
+ },
538
+ "source": [
539
+ "#@title Display 3D structure {run: \"auto\"}\n",
540
+ "model_num = 1 #@param [\"1\", \"2\", \"3\", \"4\", \"5\"] {type:\"raw\"}\n",
541
+ "color = \"chain\" #@param [\"chain\", \"lDDT\", \"rainbow\"]\n",
542
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
543
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
544
+ "\n",
545
+ "def plot_plddt_legend():\n",
546
+ " thresh = ['plDDT:','Very low (<50)','Low (60)','OK (70)','Confident (80)','Very high (>90)']\n",
547
+ " plt.figure(figsize=(1,0.1),dpi=100)\n",
548
+ " ########################################\n",
549
+ " for c in [\"#FFFFFF\",\"#FF0000\",\"#FFFF00\",\"#00FF00\",\"#00FFFF\",\"#0000FF\"]:\n",
550
+ " plt.bar(0, 0, color=c)\n",
551
+ " plt.legend(thresh, frameon=False,\n",
552
+ " loc='center', ncol=6,\n",
553
+ " handletextpad=1,\n",
554
+ " columnspacing=1,\n",
555
+ " markerscale=0.5,)\n",
556
+ " plt.axis(False)\n",
557
+ " return plt\n",
558
+ "\n",
559
+ "def plot_confidence(model_num=1):\n",
560
+ " model_name = f\"model_{model_num}\"\n",
561
+ " plt.figure(figsize=(10,3),dpi=100)\n",
562
+ " \"\"\"Plots the legend for plDDT.\"\"\"\n",
563
+ " #########################################\n",
564
+ " plt.subplot(1,2,1); plt.title('Predicted lDDT')\n",
565
+ " plt.plot(plddts[model_name])\n",
566
+ " for x in [len(query_sequence_a)]:\n",
567
+ " plt.plot([x,x],[0,100],color=\"black\")\n",
568
+ "\n",
569
+ " plt.ylabel('plDDT')\n",
570
+ " plt.xlabel('position')\n",
571
+ " #########################################\n",
572
+ " plt.subplot(1,2,2);plt.title('Predicted Aligned Error')\n",
573
+ " plt.imshow(paes[model_name], cmap=\"bwr\",vmin=0,vmax=30)\n",
574
+ " plt.colorbar()\n",
575
+ " plt.xlabel('Scored residue')\n",
576
+ " plt.ylabel('Aligned residue')\n",
577
+ " #########################################\n",
578
+ " return plt\n",
579
+ "\n",
580
+ "def show_pdb(model_num=1, show_sidechains=False, show_mainchains=False, color=\"lDDT\"):\n",
581
+ " model_name = f\"model_{model_num}\"\n",
582
+ " pdb_filename = f\"{jobname}_unrelaxed_{model_name}.pdb\"\n",
583
+ "\n",
584
+ " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js',)\n",
585
+ " view.addModel(open(pdb_filename,'r').read(),'pdb')\n",
586
+ "\n",
587
+ " if color == \"lDDT\":\n",
588
+ " view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':50,'max':90}}})\n",
589
+ " elif color == \"rainbow\":\n",
590
+ " view.setStyle({'cartoon': {'color':'spectrum'}})\n",
591
+ " elif color == \"chain\":\n",
592
+ " for n,chain,color in zip(range(2),list(\"ABCDEFGH\"),\n",
593
+ " [\"lime\",\"cyan\",\"magenta\",\"yellow\",\"salmon\",\"white\",\"blue\",\"orange\"]):\n",
594
+ " view.setStyle({'chain':chain},{'cartoon': {'color':color}})\n",
595
+ " if show_sidechains:\n",
596
+ " BB = ['C','O','N']\n",
597
+ " view.addStyle({'and':[{'resn':[\"GLY\",\"PRO\"],'invert':True},{'atom':BB,'invert':True}]},\n",
598
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
599
+ " view.addStyle({'and':[{'resn':\"GLY\"},{'atom':'CA'}]},\n",
600
+ " {'sphere':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
601
+ " view.addStyle({'and':[{'resn':\"PRO\"},{'atom':['C','O'],'invert':True}]},\n",
602
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}}) \n",
603
+ " if show_mainchains:\n",
604
+ " BB = ['C','O','N','CA']\n",
605
+ " view.addStyle({'atom':BB},{'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
606
+ "\n",
607
+ " view.zoomTo()\n",
608
+ " return view\n",
609
+ "\n",
610
+ "show_pdb(model_num,show_sidechains, show_mainchains, color).show()\n",
611
+ "if color == \"lDDT\": plot_plddt_legend().show() \n",
612
+ "plot_confidence(model_num).show()"
613
+ ],
614
+ "execution_count": null,
615
+ "outputs": []
616
+ },
617
+ {
618
+ "cell_type": "code",
619
+ "metadata": {
620
+ "id": "33g5IIegij5R",
621
+ "cellView": "form"
622
+ },
623
+ "source": [
624
+ "#@title Package and download results\n",
625
+ "!zip -FSr $jobname\".result.zip\" $jobname\".log\" $jobname\"_msa_coverage.png\" $jobname\"_\"*\"relaxed_model_\"*\".pdb\" $jobname\"_lDDT.png\" $jobname\"_PAE.png\"\n",
626
+ "files.download(f\"{jobname}.result.zip\")"
627
+ ],
628
+ "execution_count": null,
629
+ "outputs": []
630
+ },
631
+ {
632
+ "cell_type": "markdown",
633
+ "metadata": {
634
+ "id": "vP1m6jI7BgMT"
635
+ },
636
+ "source": [
637
+ "# Instructions\n",
638
+ "- If you having issues downloading results, try disable adblocker and run the last cell again. If that fails click on the little folder icon to the left, navigate to file:`jobname.result.zip`, right-click and select \"download\".\n",
639
+ "\n",
640
+ "\n",
641
+ "# License\n",
642
+ "\n",
643
+ "The source code of ColabFold is licensed under [MIT](https://raw.githubusercontent.com/sokrypton/ColabFold/main/LICENSE). Additionally, this notebook uses AlphaFold2 source code and its parameters licensed under [Apache 2.0](https://raw.githubusercontent.com/deepmind/alphafold/main/LICENSE) and [CC BY 4.0](https://creativecommons.org/licenses/by-sa/4.0/) respectively. Read more about the AlphaFold license [here](https://github.com/deepmind/alphafold)."
644
+ ]
645
+ }
646
+ ]
647
+ }
data/beta/AlphaFold_wJackhmmer.ipynb ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "accelerator": "GPU",
6
+ "colab": {
7
+ "name": "AlphaFold_wJackhmmer.ipynb",
8
+ "provenance": [],
9
+ "collapsed_sections": [],
10
+ "include_colab_link": true
11
+ },
12
+ "kernelspec": {
13
+ "display_name": "Python 3",
14
+ "name": "python3"
15
+ },
16
+ "language_info": {
17
+ "name": "python"
18
+ }
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {
24
+ "id": "view-in-github",
25
+ "colab_type": "text"
26
+ },
27
+ "source": [
28
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/AlphaFold_wJackhmmer.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {
34
+ "id": "pc5-mbsX9PZC"
35
+ },
36
+ "source": [
37
+ "# AlphaFold2 w/ Jackhmmer (or MMseqs2)\n",
38
+ "\n",
39
+ "---------\n",
40
+ "**UPDATE** (Aug. 13, 2021)\n",
41
+ "\n",
42
+ "This notebook is being retired and no longer updated. The functionality to search using jackhmmer/mmseqs has been integrated in our [new advanced notebook](https://github.com/sokrypton/ColabFold/blob/main/beta/AlphaFold2_advanced.ipynb).\n",
43
+ "\n",
44
+ "---------\n",
45
+ "\n",
46
+ "This notebook modifies deepmind's [original notebook](https://colab.research.google.com/github/deepmind/alphafold/blob/main/notebooks/AlphaFold.ipynb) to add experimental homooligomer support and option to run MMseqs2 instead of Jackhmmer for MSA generation.\n",
47
+ "\n",
48
+ "See [ColabFold](https://github.com/sokrypton/ColabFold/) for other related notebooks\n",
49
+ "\n",
50
+ "**Limitations**\n",
51
+ "- This notebook does NOT use Templates.\n",
52
+ "- For a typical Google-Colab-GPU (16G) session, the max total length is **1400 residues**."
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "metadata": {
58
+ "id": "woIxeCPygt7K",
59
+ "cellView": "form"
60
+ },
61
+ "source": [
62
+ "#@title Install software\n",
63
+ "#@markdown Please execute this cell by pressing the _Play_ button \n",
64
+ "#@markdown on the left.\n",
65
+ "use_amber_relax = True #@param {type:\"boolean\"}\n",
66
+ "\n",
67
+ "import os\n",
68
+ "os.environ['TF_FORCE_UNIFIED_MEMORY'] = '1'\n",
69
+ "os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION'] = '2.0'\n",
70
+ "\n",
71
+ "from IPython.utils import io\n",
72
+ "import subprocess\n",
73
+ "import requests\n",
74
+ "import hashlib\n",
75
+ "import tarfile\n",
76
+ "import time\n",
77
+ "import tqdm.notebook\n",
78
+ "\n",
79
+ "from sys import version_info \n",
80
+ "python_version = f\"{version_info.major}.{version_info.minor}\"\n",
81
+ "\n",
82
+ "GIT_REPO = 'https://github.com/deepmind/alphafold'\n",
83
+ "SOURCE_URL = 'https://storage.googleapis.com/alphafold/alphafold_params_2021-07-14.tar'\n",
84
+ "PARAMS_DIR = './alphafold/data/params'\n",
85
+ "PARAMS_PATH = os.path.join(PARAMS_DIR, os.path.basename(SOURCE_URL))\n",
86
+ "TQDM_BAR_FORMAT = '{l_bar}{bar}| {n_fmt}/{total_fmt} [elapsed: {elapsed} remaining: {remaining}]'\n",
87
+ "\n",
88
+ "# if not already installed\n",
89
+ "if not os.path.isdir(\"alphafold\"):\n",
90
+ " try:\n",
91
+ " total = 100 if use_amber_relax else 55\n",
92
+ " with tqdm.notebook.tqdm(total=total, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
93
+ " with io.capture_output() as captured:\n",
94
+ " #######################################################################\n",
95
+ " %shell rm -rf alphafold\n",
96
+ " %shell git clone {GIT_REPO} alphafold\n",
97
+ "\n",
98
+ " # Apply multi-chain patch from Lim Heo @huhlim\n",
99
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/protein.patch\n",
100
+ " %shell (patch -u alphafold/alphafold/common/protein.py -i /content/protein.patch)\n",
101
+ "\n",
102
+ " pbar.update(4)\n",
103
+ " %shell pip3 install ./alphafold\n",
104
+ " pbar.update(5)\n",
105
+ " \n",
106
+ " %shell mkdir --parents \"{PARAMS_DIR}\"\n",
107
+ " %shell wget -O \"{PARAMS_PATH}\" \"{SOURCE_URL}\"\n",
108
+ " pbar.update(14)\n",
109
+ "\n",
110
+ " %shell tar --extract --verbose --file=\"{PARAMS_PATH}\" \\\n",
111
+ " --directory=\"{PARAMS_DIR}\" --preserve-permissions\n",
112
+ " %shell rm \"{PARAMS_PATH}\"\n",
113
+ " pbar.update(27)\n",
114
+ "\n",
115
+ " #######################################################################\n",
116
+ " %shell sudo apt install --quiet --yes hmmer\n",
117
+ " pbar.update(3)\n",
118
+ "\n",
119
+ " # Install py3dmol.\n",
120
+ " %shell pip install py3dmol\n",
121
+ " pbar.update(1)\n",
122
+ "\n",
123
+ " if use_amber_relax:\n",
124
+ " # Install OpenMM and pdbfixer.\n",
125
+ " %shell rm -rf /opt/conda\n",
126
+ " %shell wget -q -P /tmp \\\n",
127
+ " https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \\\n",
128
+ " && bash /tmp/Miniconda3-latest-Linux-x86_64.sh -b -p /opt/conda \\\n",
129
+ " && rm /tmp/Miniconda3-latest-Linux-x86_64.sh\n",
130
+ " pbar.update(4)\n",
131
+ "\n",
132
+ " PATH=%env PATH\n",
133
+ " %env PATH=/opt/conda/bin:{PATH}\n",
134
+ " %shell conda update -qy conda \\\n",
135
+ " && conda install -qy -c conda-forge \\\n",
136
+ " python={python_version} \\\n",
137
+ " openmm=7.5.1 \\\n",
138
+ " pdbfixer\n",
139
+ " pbar.update(40)\n",
140
+ "\n",
141
+ " %shell wget -q -P /content \\\n",
142
+ " https://git.scicore.unibas.ch/schwede/openstructure/-/raw/7102c63615b64735c4941278d92b554ec94415f8/modules/mol/alg/src/stereo_chemical_props.txt\n",
143
+ " pbar.update(1)\n",
144
+ " %shell mkdir -p /content/alphafold/common\n",
145
+ " %shell cp -f /content/stereo_chemical_props.txt /content/alphafold/common\n",
146
+ "\n",
147
+ " # Apply OpenMM patch.\n",
148
+ " %shell pushd /opt/conda/lib/python{python_version}/site-packages/ && \\\n",
149
+ " patch -p0 < /content/alphafold/docker/openmm.patch && \\\n",
150
+ " popd\n",
151
+ "\n",
152
+ " # Create a ramdisk to store a database chunk to make Jackhmmer run fast.\n",
153
+ " %shell sudo mkdir -m 777 --parents /tmp/ramdisk\n",
154
+ " %shell sudo mount -t tmpfs -o size=9G ramdisk /tmp/ramdisk\n",
155
+ " pbar.update(1)\n",
156
+ "\n",
157
+ " except subprocess.CalledProcessError:\n",
158
+ " print(captured)\n",
159
+ " raise\n",
160
+ "\n",
161
+ " ########################################################################################\n",
162
+ " ########################################################################################\n",
163
+ "\n",
164
+ "import jax\n",
165
+ "if jax.local_devices()[0].platform == 'tpu':\n",
166
+ " raise RuntimeError('Colab TPU runtime not supported. Change it to GPU via Runtime -> Change Runtime Type -> Hardware accelerator -> GPU.')\n",
167
+ "elif jax.local_devices()[0].platform == 'cpu':\n",
168
+ " raise RuntimeError('Colab CPU runtime not supported. Change it to GPU via Runtime -> Change Runtime Type -> Hardware accelerator -> GPU.')\n",
169
+ "\n",
170
+ "# --- Python imports ---\n",
171
+ "import sys\n",
172
+ "import pickle\n",
173
+ "if use_amber_relax:\n",
174
+ " sys.path.append(f\"/opt/conda/lib/python{python_version}/site-packages\")\n",
175
+ "\n",
176
+ "from urllib import request\n",
177
+ "from concurrent import futures\n",
178
+ "from google.colab import files\n",
179
+ "import json\n",
180
+ "from matplotlib import gridspec\n",
181
+ "import matplotlib.pyplot as plt\n",
182
+ "import numpy as np\n",
183
+ "import py3Dmol\n",
184
+ "\n",
185
+ "from alphafold.model import model\n",
186
+ "from alphafold.model import config\n",
187
+ "from alphafold.model import data\n",
188
+ "\n",
189
+ "from alphafold.data import parsers\n",
190
+ "from alphafold.data import pipeline\n",
191
+ "from alphafold.data.tools import jackhmmer\n",
192
+ "\n",
193
+ "from alphafold.common import protein\n",
194
+ "\n",
195
+ "if use_amber_relax:\n",
196
+ " from alphafold.relax import relax\n",
197
+ " from alphafold.relax import utils\n",
198
+ "\n",
199
+ "#######################################################################################\n",
200
+ "#######################################################################################\n",
201
+ "def run_mmseqs2(query_sequence, prefix, use_env=True, filter=False):\n",
202
+ " def submit(query_sequence, mode):\n",
203
+ " res = requests.post('https://a3m.mmseqs.com/ticket/msa', data={'q':f\">1\\n{query_sequence}\", 'mode': mode})\n",
204
+ " return res.json()\n",
205
+ " def status(ID):\n",
206
+ " res = requests.get(f'https://a3m.mmseqs.com/ticket/{ID}')\n",
207
+ " return res.json()\n",
208
+ " def download(ID, path):\n",
209
+ " res = requests.get(f'https://a3m.mmseqs.com/result/download/{ID}')\n",
210
+ " with open(path,\"wb\") as out: out.write(res.content)\n",
211
+ " \n",
212
+ " if filter:\n",
213
+ " mode = \"env\" if use_env else \"all\"\n",
214
+ " else:\n",
215
+ " mode = \"env-nofilter\" if use_env else \"nofilter\"\n",
216
+ " \n",
217
+ " path = f\"{prefix}_{mode}\"\n",
218
+ " if not os.path.isdir(path): os.mkdir(path)\n",
219
+ "\n",
220
+ " # call mmseqs2 api\n",
221
+ " tar_gz_file = f'{path}/out.tar.gz'\n",
222
+ " if not os.path.isfile(tar_gz_file):\n",
223
+ " out = submit(query_sequence, mode)\n",
224
+ " while out[\"status\"] in [\"RUNNING\",\"PENDING\"]:\n",
225
+ " time.sleep(1)\n",
226
+ " out = status(out[\"id\"]) \n",
227
+ " download(out[\"id\"], tar_gz_file)\n",
228
+ " \n",
229
+ " # parse a3m files\n",
230
+ " a3m_lines = []\n",
231
+ " a3m = f\"{prefix}_{mode}.a3m\"\n",
232
+ " if not os.path.isfile(a3m):\n",
233
+ " with tarfile.open(tar_gz_file) as tar_gz: tar_gz.extractall(path)\n",
234
+ " a3m_files = [f\"{path}/uniref.a3m\"]\n",
235
+ " if use_env: a3m_files.append(f\"{path}/bfd.mgnify30.metaeuk30.smag30.a3m\")\n",
236
+ " a3m_out = open(a3m,\"w\")\n",
237
+ " for a3m_file in a3m_files:\n",
238
+ " for line in open(a3m_file,\"r\"):\n",
239
+ " line = line.replace(\"\\x00\",\"\")\n",
240
+ " if len(line) > 0:\n",
241
+ " a3m_lines.append(line)\n",
242
+ " a3m_out.write(line)\n",
243
+ " else:\n",
244
+ " a3m_lines = open(a3m).readlines()\n",
245
+ " return \"\".join(a3m_lines)\n",
246
+ "\n",
247
+ "def run_jackhmmer(sequence, prefix):\n",
248
+ " pickled_msa_path = f\"{prefix}.jackhmmer.pickle\"\n",
249
+ " if os.path.isfile(pickled_msa_path):\n",
250
+ " msas_dict = pickle.load(open(pickled_msa_path,\"rb\"))\n",
251
+ " msas, deletion_matrices = (msas_dict[k] for k in ['msas', 'deletion_matrices'])\n",
252
+ " full_msa = []\n",
253
+ " for msa in msas:\n",
254
+ " full_msa += msa\n",
255
+ " else:\n",
256
+ " # --- Find the closest source ---\n",
257
+ " test_url_pattern = 'https://storage.googleapis.com/alphafold-colab{:s}/latest/uniref90_2021_03.fasta.1'\n",
258
+ " ex = futures.ThreadPoolExecutor(3)\n",
259
+ " def fetch(source):\n",
260
+ " request.urlretrieve(test_url_pattern.format(source))\n",
261
+ " return source\n",
262
+ " fs = [ex.submit(fetch, source) for source in ['', '-europe', '-asia']]\n",
263
+ " source = None\n",
264
+ " for f in futures.as_completed(fs):\n",
265
+ " source = f.result()\n",
266
+ " ex.shutdown()\n",
267
+ " break\n",
268
+ "\n",
269
+ " jackhmmer_binary_path = '/usr/bin/jackhmmer'\n",
270
+ " dbs = []\n",
271
+ "\n",
272
+ " num_jackhmmer_chunks = {'uniref90': 59, 'smallbfd': 17, 'mgnify': 71}\n",
273
+ " total_jackhmmer_chunks = sum(num_jackhmmer_chunks.values())\n",
274
+ " with tqdm.notebook.tqdm(total=total_jackhmmer_chunks, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
275
+ " def jackhmmer_chunk_callback(i):\n",
276
+ " pbar.update(n=1)\n",
277
+ "\n",
278
+ " pbar.set_description('Searching uniref90')\n",
279
+ " jackhmmer_uniref90_runner = jackhmmer.Jackhmmer(\n",
280
+ " binary_path=jackhmmer_binary_path,\n",
281
+ " database_path=f'https://storage.googleapis.com/alphafold-colab{source}/latest/uniref90_2021_03.fasta',\n",
282
+ " get_tblout=True,\n",
283
+ " num_streamed_chunks=num_jackhmmer_chunks['uniref90'],\n",
284
+ " streaming_callback=jackhmmer_chunk_callback,\n",
285
+ " z_value=135301051)\n",
286
+ " dbs.append(('uniref90', jackhmmer_uniref90_runner.query('target.fasta')))\n",
287
+ "\n",
288
+ " pbar.set_description('Searching smallbfd')\n",
289
+ " jackhmmer_smallbfd_runner = jackhmmer.Jackhmmer(\n",
290
+ " binary_path=jackhmmer_binary_path,\n",
291
+ " database_path=f'https://storage.googleapis.com/alphafold-colab{source}/latest/bfd-first_non_consensus_sequences.fasta',\n",
292
+ " get_tblout=True,\n",
293
+ " num_streamed_chunks=num_jackhmmer_chunks['smallbfd'],\n",
294
+ " streaming_callback=jackhmmer_chunk_callback,\n",
295
+ " z_value=65984053)\n",
296
+ " dbs.append(('smallbfd', jackhmmer_smallbfd_runner.query('target.fasta')))\n",
297
+ "\n",
298
+ " pbar.set_description('Searching mgnify')\n",
299
+ " jackhmmer_mgnify_runner = jackhmmer.Jackhmmer(\n",
300
+ " binary_path=jackhmmer_binary_path,\n",
301
+ " database_path=f'https://storage.googleapis.com/alphafold-colab{source}/latest/mgy_clusters_2019_05.fasta',\n",
302
+ " get_tblout=True,\n",
303
+ " num_streamed_chunks=num_jackhmmer_chunks['mgnify'],\n",
304
+ " streaming_callback=jackhmmer_chunk_callback,\n",
305
+ " z_value=304820129)\n",
306
+ " dbs.append(('mgnify', jackhmmer_mgnify_runner.query('target.fasta')))\n",
307
+ "\n",
308
+ " # --- Extract the MSAs and visualize ---\n",
309
+ " # Extract the MSAs from the Stockholm files.\n",
310
+ " # NB: deduplication happens later in pipeline.make_msa_features.\n",
311
+ "\n",
312
+ " mgnify_max_hits = 501\n",
313
+ " msas = []\n",
314
+ " deletion_matrices = []\n",
315
+ " for db_name, db_results in dbs:\n",
316
+ " unsorted_results = []\n",
317
+ " for i, result in enumerate(db_results):\n",
318
+ " msa, deletion_matrix, target_names = parsers.parse_stockholm(result['sto'])\n",
319
+ " e_values_dict = parsers.parse_e_values_from_tblout(result['tbl'])\n",
320
+ " e_values = [e_values_dict[t.split('/')[0]] for t in target_names]\n",
321
+ " zipped_results = zip(msa, deletion_matrix, target_names, e_values)\n",
322
+ " if i != 0:\n",
323
+ " # Only take query from the first chunk\n",
324
+ " zipped_results = [x for x in zipped_results if x[2] != 'query']\n",
325
+ " unsorted_results.extend(zipped_results)\n",
326
+ " sorted_by_evalue = sorted(unsorted_results, key=lambda x: x[3])\n",
327
+ " db_msas, db_deletion_matrices, _, _ = zip(*sorted_by_evalue)\n",
328
+ " if db_msas:\n",
329
+ " if db_name == 'mgnify':\n",
330
+ " db_msas = db_msas[:mgnify_max_hits]\n",
331
+ " db_deletion_matrices = db_deletion_matrices[:mgnify_max_hits]\n",
332
+ " msas.append(db_msas)\n",
333
+ " deletion_matrices.append(db_deletion_matrices)\n",
334
+ " msa_size = len(set(db_msas))\n",
335
+ " print(f'{msa_size} Sequences Found in {db_name}')\n",
336
+ "\n",
337
+ " pickle.dump({\"msas\":msas,\"deletion_matrices\":deletion_matrices},\n",
338
+ " open(pickled_msa_path,\"wb\"))\n",
339
+ " return msas, deletion_matrices"
340
+ ],
341
+ "execution_count": null,
342
+ "outputs": []
343
+ },
344
+ {
345
+ "cell_type": "markdown",
346
+ "metadata": {
347
+ "id": "W4JpOs6oA-QS"
348
+ },
349
+ "source": [
350
+ "## Making a prediction\n",
351
+ "\n",
352
+ "Please paste the sequence of your protein in the text box below, then run the remaining cells via _Runtime_ > _Run after_. You can also run the cells individually by pressing the _Play_ button on the left.\n",
353
+ "\n",
354
+ "Note that the search against databases and the actual prediction can take some time, from minutes to hours, depending on the length of the protein and what type of GPU you are allocated by Colab (see FAQ below)."
355
+ ]
356
+ },
357
+ {
358
+ "cell_type": "code",
359
+ "metadata": {
360
+ "id": "rowN0bVYLe9n",
361
+ "cellView": "form"
362
+ },
363
+ "source": [
364
+ "#@title Enter the amino acid sequence to fold ⬇️\n",
365
+ "sequence = 'PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK' #@param {type:\"string\"}\n",
366
+ "\n",
367
+ "MIN_SEQUENCE_LENGTH = 16\n",
368
+ "MAX_SEQUENCE_LENGTH = 2500\n",
369
+ "\n",
370
+ "# Remove all whitespaces, tabs and end lines; upper-case\n",
371
+ "sequence = sequence.translate(str.maketrans('', '', ' \\n\\t')).upper()\n",
372
+ "#@markdown ### Experimental options\n",
373
+ "homooligomer = 1 #@param [1,2,3,4,5,6,7,8] {type:\"raw\"}\n",
374
+ "\n",
375
+ "full_sequence = sequence * homooligomer\n",
376
+ "\n",
377
+ "aatypes = set('ACDEFGHIKLMNPQRSTVWY') # 20 standard aatypes\n",
378
+ "if not set(sequence).issubset(aatypes):\n",
379
+ " raise Exception(f'Input sequence contains non-amino acid letters: {set(sequence) - aatypes}. AlphaFold only supports 20 standard amino acids as inputs.')\n",
380
+ "if len(full_sequence) < MIN_SEQUENCE_LENGTH:\n",
381
+ " raise Exception(f'Input sequence is too short: {len(full_sequence)} amino acids, while the minimum is {MIN_SEQUENCE_LENGTH}')\n",
382
+ "if len(full_sequence) > MAX_SEQUENCE_LENGTH:\n",
383
+ " raise Exception(f'Input sequence is too long: {len(full_sequence)} amino acids, while the maximum is {MAX_SEQUENCE_LENGTH}. Please use the full AlphaFold system for long sequences.')\n",
384
+ "\n",
385
+ "if len(full_sequence) > 1400:\n",
386
+ " print(f\"WARNING: For a typical Google-Colab-GPU (16G) session, the max total length is 1400 residues. You are at {len(full_sequence)}!\")"
387
+ ],
388
+ "execution_count": null,
389
+ "outputs": []
390
+ },
391
+ {
392
+ "cell_type": "code",
393
+ "metadata": {
394
+ "id": "Zq5EC6ju-XPo",
395
+ "cellView": "form"
396
+ },
397
+ "source": [
398
+ "#@title Search against genetic databases\n",
399
+ "#@markdown Once this cell has been executed, you will see\n",
400
+ "#@markdown statistics about the multiple sequence alignment \n",
401
+ "#@markdown (MSA) that will be used by AlphaFold. In particular, \n",
402
+ "#@markdown you’ll see how well each residue is covered by similar \n",
403
+ "#@markdown sequences in the MSA.\n",
404
+ "\n",
405
+ "#@markdown ---\n",
406
+ "msa_method = \"jackhmmer\" #@param [\"jackhmmer\",\"mmseqs2\",\"single_sequence\",\"custom_a3m\",\"precomputed\"]\n",
407
+ "#@markdown - `jackhmmer` - default approach from Deepmind\n",
408
+ "#@markdown - `mmseqs2` - fast method from [ColabFold](https://github.com/sokrypton/ColabFold)\n",
409
+ "#@markdown - `single_sequence` - use single sequence input (not recommended, unless a *denovo* design and you dont expect to find any homologous sequences)\n",
410
+ "#@markdown - `custom_a3m` Upload custom MSA (a3m format)\n",
411
+ "#@markdown - `precomputed` If you have previously run this notebook and saved the results,\n",
412
+ "#@markdown you can skip this step by uploading \n",
413
+ "#@markdown the previously generated `prediction/msa.npz`\n",
414
+ "\n",
415
+ "# prediction directory\n",
416
+ "output_dir = 'prediction'\n",
417
+ "os.makedirs(output_dir, exist_ok=True)\n",
418
+ "\n",
419
+ "# tmp directory\n",
420
+ "prefix = hashlib.sha1(sequence.encode()).hexdigest()\n",
421
+ "os.makedirs('tmp', exist_ok=True)\n",
422
+ "prefix = os.path.join('tmp',prefix)\n",
423
+ "\n",
424
+ "# --- Search against genetic databases ---\n",
425
+ "with open('target.fasta', 'wt') as f:\n",
426
+ " f.write(f'>query\\n{sequence}')\n",
427
+ "\n",
428
+ "# Run the search against chunks of genetic databases (since the genetic\n",
429
+ "# databases don't fit in Colab ramdisk).\n",
430
+ "\n",
431
+ "if msa_method == \"precomputed\":\n",
432
+ " print(\"upload precomputed pickled msa from previous run\")\n",
433
+ " pickled_msa_dict = files.upload()\n",
434
+ " msas_dict = pickle.loads(pickled_msa_dict[list(pickled_msa_dict.keys())[0]])\n",
435
+ " msas, deletion_matrices = (msas_dict[k] for k in ['msas', 'deletion_matrices'])\n",
436
+ "\n",
437
+ "elif msa_method == \"mmseqs2\":\n",
438
+ " msa, deletion_matrix = parsers.parse_a3m(run_mmseqs2(sequence, prefix, filter=True))\n",
439
+ " msas,deletion_matrices = [msa],[deletion_matrix]\n",
440
+ "\n",
441
+ "elif msa_method == \"single_sequence\":\n",
442
+ " msas = [[sequence]]\n",
443
+ " deletion_matrices = [[[0]*len(sequence)]]\n",
444
+ "\n",
445
+ "elif msa_method == \"custom_a3m\":\n",
446
+ " print(\"upload custom a3m\")\n",
447
+ " msa_dict = files.upload()\n",
448
+ " lines = msa_dict[list(msa_dict.keys())[0]].decode().splitlines()\n",
449
+ " a3m_lines = []\n",
450
+ " for line in lines:\n",
451
+ " line = line.replace(\"\\x00\",\"\")\n",
452
+ " if len(line) > 0 and not line.startswith('#'):\n",
453
+ " a3m_lines.append(line)\n",
454
+ " msa, deletion_matrix = parsers.parse_a3m(\"\\n\".join(a3m_lines))\n",
455
+ " msas,deletion_matrices = [msa],[deletion_matrix]\n",
456
+ "\n",
457
+ " if len(msas[0][0]) != len(sequence):\n",
458
+ " print(\"ERROR: the length of msa does not match input sequence\")\n",
459
+ "\n",
460
+ "else:\n",
461
+ " # run jackhmmer\n",
462
+ " msas, deletion_matrices = run_jackhmmer(sequence, prefix)\n",
463
+ "\n",
464
+ "full_msa = []\n",
465
+ "for msa in msas: full_msa += msa\n",
466
+ "\n",
467
+ "# save MSA as pickle\n",
468
+ "pickle.dump({\"msas\":msas,\"deletion_matrices\":deletion_matrices},\n",
469
+ " open(\"prediction/msa.pickle\",\"wb\"))\n",
470
+ "\n",
471
+ "# deduplicate\n",
472
+ "deduped_full_msa = list(dict.fromkeys(full_msa))\n",
473
+ "total_msa_size = len(deduped_full_msa)\n",
474
+ "print(f'\\n{total_msa_size} Sequences Found in Total\\n')\n",
475
+ "\n",
476
+ "msa_arr = np.array([list(seq) for seq in deduped_full_msa])\n",
477
+ "num_alignments, num_res = msa_arr.shape\n",
478
+ "\n",
479
+ "plt.figure(figsize=(8,5),dpi=100)\n",
480
+ "plt.title(\"Sequence coverage\")\n",
481
+ "seqid = (np.array(list(sequence)) == msa_arr).mean(-1)\n",
482
+ "seqid_sort = seqid.argsort() #[::-1]\n",
483
+ "non_gaps = (msa_arr != \"-\").astype(float)\n",
484
+ "non_gaps[non_gaps == 0] = np.nan\n",
485
+ "plt.imshow(non_gaps[seqid_sort]*seqid[seqid_sort,None],\n",
486
+ " interpolation='nearest', aspect='auto',\n",
487
+ " cmap=\"rainbow_r\", vmin=0, vmax=1, origin='lower')\n",
488
+ "plt.plot((msa_arr != \"-\").sum(0), color='black')\n",
489
+ "plt.xlim(-0.5,msa_arr.shape[1]-0.5)\n",
490
+ "plt.ylim(-0.5,msa_arr.shape[0]-0.5)\n",
491
+ "plt.colorbar(label=\"Sequence identity to query\",)\n",
492
+ "plt.xlabel(\"Positions\")\n",
493
+ "plt.ylabel(\"Sequences\")\n",
494
+ "plt.show()"
495
+ ],
496
+ "execution_count": null,
497
+ "outputs": []
498
+ },
499
+ {
500
+ "cell_type": "code",
501
+ "metadata": {
502
+ "id": "DynHMYHTzXbO",
503
+ "cellView": "form"
504
+ },
505
+ "source": [
506
+ "#@title Run AlphaFold \n",
507
+ "\n",
508
+ "#@markdown ---\n",
509
+ "relax_all = False #@param {type:\"boolean\"}\n",
510
+ "turbo = False #@param {type:\"boolean\"}\n",
511
+ "#@markdown - `relax_all` If disabled, only top ranked model is amber-relaxed.\n",
512
+ "#@markdown - `turbo` mode compiles a single model then swaps out params to speedup calculation. Warning, this option is experimental, and not extensively tested.\n",
513
+ "\n",
514
+ "\n",
515
+ "# --- Run the model ---\n",
516
+ "from string import ascii_uppercase\n",
517
+ "\n",
518
+ "def _placeholder_template_feats(num_templates_, num_res_):\n",
519
+ " return {\n",
520
+ " 'template_aatype': np.zeros([num_templates_, num_res_, 22], np.float32),\n",
521
+ " 'template_all_atom_masks': np.zeros([num_templates_, num_res_, 37, 3], np.float32),\n",
522
+ " 'template_all_atom_positions': np.zeros([num_templates_, num_res_, 37], np.float32),\n",
523
+ " 'template_domain_names': np.zeros([num_templates_], np.float32),\n",
524
+ " 'template_sum_probs': np.zeros([num_templates_], np.float32),\n",
525
+ " }\n",
526
+ "\n",
527
+ "num_templates = 0\n",
528
+ "num_res = len(sequence)\n",
529
+ "\n",
530
+ "if homooligomer == 1:\n",
531
+ " msas_mod = msas\n",
532
+ " deletion_matrices_mod = deletion_matrices\n",
533
+ "else:\n",
534
+ " msas_mod = []\n",
535
+ " deletion_matrices_mod = []\n",
536
+ " for o in range(homooligomer):\n",
537
+ " L = num_res * o\n",
538
+ " R = num_res * (homooligomer-(o+1))\n",
539
+ " for msa,deletion_matrix in zip(msas,deletion_matrices):\n",
540
+ " msas_mod.append([\"-\"*L+seq+\"-\"*R for seq in msa])\n",
541
+ " deletion_matrices_mod.append([[0]*L+mtx+[0]*R for mtx in deletion_matrix])\n",
542
+ "\n",
543
+ "\n",
544
+ "feature_dict = {}\n",
545
+ "feature_dict.update(pipeline.make_sequence_features(sequence*homooligomer, 'test', num_res*homooligomer))\n",
546
+ "feature_dict.update(pipeline.make_msa_features(msas_mod, deletion_matrices=deletion_matrices_mod))\n",
547
+ "feature_dict.update(_placeholder_template_feats(num_templates, num_res*homooligomer))\n",
548
+ "\n",
549
+ "# Minkyung's code\n",
550
+ "# add big enough number to residue index to indicate chain breaks\n",
551
+ "idx_res = feature_dict['residue_index']\n",
552
+ "L_prev = 0\n",
553
+ "Ls = [num_res]*homooligomer\n",
554
+ "for L_i in Ls[:-1]:\n",
555
+ " idx_res[L_prev+L_i:] += 200\n",
556
+ " L_prev += L_i \n",
557
+ "feature_dict['residue_index'] = idx_res\n",
558
+ "\n",
559
+ "plddts = {}\n",
560
+ "pae_outputs = {}\n",
561
+ "unrelaxed_proteins = {}\n",
562
+ "\n",
563
+ "model_names = ['model_4', 'model_1', 'model_2', 'model_3', 'model_5']\n",
564
+ "\n",
565
+ "total = len(model_names)\n",
566
+ "if use_amber_relax:\n",
567
+ " if relax_all: total += total\n",
568
+ " else: total += 1\n",
569
+ "\n",
570
+ "with tqdm.notebook.tqdm(total=total, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
571
+ " for num,model_name in enumerate(model_names):\n",
572
+ " pbar.set_description(f'Running model_{num+1}')\n",
573
+ "\n",
574
+ " cfg = config.model_config(model_name+\"_ptm\")\n",
575
+ " params = data.get_model_haiku_params(model_name+\"_ptm\", './alphafold/data')\n",
576
+ " if turbo:\n",
577
+ " #####################################################\n",
578
+ " # load models or params\n",
579
+ " if model_name == \"model_4\":\n",
580
+ " # define model and process features\n",
581
+ " model_runner = model.RunModel(cfg, params)\n",
582
+ " processed_feature_dict = model_runner.process_features(feature_dict,random_seed=0)\n",
583
+ " else:\n",
584
+ " # swap params\n",
585
+ " for k in model_runner.params.keys():\n",
586
+ " model_runner.params[k] = params[k]\n",
587
+ " prediction_result = model_runner.predict(processed_feature_dict) \n",
588
+ " # cleanup to save memory\n",
589
+ " if model_name == \"model_5\": del model_runner\n",
590
+ " del params\n",
591
+ " #####################################################\n",
592
+ " else:\n",
593
+ " #####################################################\n",
594
+ " model_runner = model.RunModel(cfg, params)\n",
595
+ "\n",
596
+ " processed_feature_dict = model_runner.process_features(feature_dict,random_seed=0)\n",
597
+ " prediction_result = model_runner.predict(processed_feature_dict) \n",
598
+ "\n",
599
+ " # cleanup to save memory\n",
600
+ " del params\n",
601
+ " del model_runner\n",
602
+ " #####################################################\n",
603
+ "\n",
604
+ " mean_plddt = prediction_result['plddt'].mean()\n",
605
+ "\n",
606
+ " # Get the pLDDT confidence metrics.\n",
607
+ " pae_outputs[model_name] = (\n",
608
+ " prediction_result['predicted_aligned_error'],\n",
609
+ " prediction_result['max_predicted_aligned_error']\n",
610
+ " )\n",
611
+ " plddts[model_name] = prediction_result['plddt']\n",
612
+ "\n",
613
+ " # Set the b-factors to the per-residue plddt.\n",
614
+ " final_atom_mask = prediction_result['structure_module']['final_atom_mask']\n",
615
+ " b_factors = prediction_result['plddt'][:, None] * final_atom_mask\n",
616
+ " unrelaxed_protein = protein.from_prediction(processed_feature_dict,\n",
617
+ " prediction_result,\n",
618
+ " b_factors=b_factors)\n",
619
+ " unrelaxed_proteins[model_name] = unrelaxed_protein\n",
620
+ "\n",
621
+ " # Delete unused outputs to save memory.\n",
622
+ " del prediction_result\n",
623
+ " pbar.update(n=1)\n",
624
+ "\n",
625
+ " # Find the best model according to the mean pLDDT.\n",
626
+ " model_rank = list(plddts.keys())\n",
627
+ " model_rank = [model_rank[i] for i in np.argsort([plddts[x].mean() for x in model_rank])[::-1]]\n",
628
+ "\n",
629
+ " # Write out the prediction\n",
630
+ " pbar.set_description(f'AMBER relaxation')\n",
631
+ " for n,name in enumerate(model_rank):\n",
632
+ " pred_output_path = os.path.join(output_dir,f'model_{n+1}_unrelaxed.pdb')\n",
633
+ " unrelaxed_protein = unrelaxed_proteins[name]\n",
634
+ " pdb_lines = protein.to_pdb(unrelaxed_protein)\n",
635
+ " with open(pred_output_path, 'w') as f:\n",
636
+ " f.write(pdb_lines)\n",
637
+ " \n",
638
+ " if use_amber_relax:\n",
639
+ " if relax_all or n == 0:\n",
640
+ " amber_relaxer = relax.AmberRelaxation(\n",
641
+ " max_iterations=0,\n",
642
+ " tolerance=2.39,\n",
643
+ " stiffness=10.0,\n",
644
+ " exclude_residues=[],\n",
645
+ " max_outer_iterations=20)\n",
646
+ " relaxed_pdb_lines, _, _ = amber_relaxer.process(prot=unrelaxed_protein) \n",
647
+ " pred_output_path = os.path.join(output_dir,f'model_{n+1}_relaxed.pdb')\n",
648
+ " with open(pred_output_path, 'w') as f:\n",
649
+ " f.write(relaxed_pdb_lines)\n",
650
+ " pbar.update(n=1)\n",
651
+ " \n",
652
+ "############################################################\n",
653
+ "############################################################\n",
654
+ "\n",
655
+ "for n,rank in enumerate(model_rank):\n",
656
+ " print(f\"model_{n+1} {plddts[rank].mean()}\")\n",
657
+ " pae, max_pae = pae_outputs[rank]\n",
658
+ " # Save pLDDT and predicted aligned error (if it exists)\n",
659
+ " pae_output_path = os.path.join(output_dir,f'predicted_aligned_error_{n+1}.json')\n",
660
+ " if pae_outputs:\n",
661
+ " # Save predicted aligned error in the same format as the AF EMBL DB\n",
662
+ " rounded_errors = np.round(pae.astype(np.float64), decimals=1)\n",
663
+ " indices = np.indices((len(rounded_errors), len(rounded_errors))) + 1\n",
664
+ " indices_1 = indices[0].flatten().tolist()\n",
665
+ " indices_2 = indices[1].flatten().tolist()\n",
666
+ " pae_data = json.dumps([{\n",
667
+ " 'residue1': indices_1,\n",
668
+ " 'residue2': indices_2,\n",
669
+ " 'distance': rounded_errors.flatten().tolist(),\n",
670
+ " 'max_predicted_aligned_error': max_pae.item()\n",
671
+ " }],\n",
672
+ " indent=None,\n",
673
+ " separators=(',', ':'))\n",
674
+ " with open(pae_output_path, 'w') as f:\n",
675
+ " f.write(pae_data)"
676
+ ],
677
+ "execution_count": null,
678
+ "outputs": []
679
+ },
680
+ {
681
+ "cell_type": "code",
682
+ "metadata": {
683
+ "id": "KAZj6CBZTkJM",
684
+ "cellView": "form"
685
+ },
686
+ "source": [
687
+ "#@title Display 3D structure {run: \"auto\"}\n",
688
+ "model_num = 1 #@param [\"1\", \"2\", \"3\", \"4\", \"5\"] {type:\"raw\"}\n",
689
+ "color = \"lDDT\" #@param [\"chain\", \"lDDT\", \"rainbow\"]\n",
690
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
691
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
692
+ "\n",
693
+ "def plot_plddt_legend():\n",
694
+ " thresh = ['plDDT:','Very low (<50)','Low (60)','OK (70)','Confident (80)','Very high (>90)']\n",
695
+ " plt.figure(figsize=(1,0.1),dpi=100)\n",
696
+ " ########################################\n",
697
+ " for c in [\"#FFFFFF\",\"#FF0000\",\"#FFFF00\",\"#00FF00\",\"#00FFFF\",\"#0000FF\"]:\n",
698
+ " plt.bar(0, 0, color=c)\n",
699
+ " plt.legend(thresh, frameon=False,\n",
700
+ " loc='center', ncol=6,\n",
701
+ " handletextpad=1,\n",
702
+ " columnspacing=1,\n",
703
+ " markerscale=0.5,)\n",
704
+ " plt.axis(False)\n",
705
+ " return plt\n",
706
+ "\n",
707
+ "def plot_confidence(model_num=1):\n",
708
+ " plt.figure(figsize=(10,3),dpi=100)\n",
709
+ " \"\"\"Plots the legend for plDDT.\"\"\"\n",
710
+ " #########################################\n",
711
+ " plt.subplot(1,2,1); plt.title('Predicted lDDT')\n",
712
+ " plt.plot(plddts[model_rank[model_num-1]])\n",
713
+ " for n in range(homooligomer+1):\n",
714
+ " x = n*(len(sequence))\n",
715
+ " plt.plot([x,x],[0,100],color=\"black\")\n",
716
+ " plt.ylabel('plDDT')\n",
717
+ " plt.xlabel('position')\n",
718
+ " #########################################\n",
719
+ " plt.subplot(1,2,2);plt.title('Predicted Aligned Error')\n",
720
+ " pae, max_pae = pae_outputs[model_rank[model_num-1]]\n",
721
+ " plt.imshow(pae, cmap=\"bwr\",vmin=0,vmax=30)\n",
722
+ " plt.colorbar()\n",
723
+ " plt.xlabel('Scored residue')\n",
724
+ " plt.ylabel('Aligned residue')\n",
725
+ " #########################################\n",
726
+ " return plt\n",
727
+ "\n",
728
+ "def show_pdb(model_num=1, show_sidechains=False, show_mainchains=False, color=\"lDDT\"):\n",
729
+ " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js',)\n",
730
+ " pred_output_path = os.path.join(output_dir,f'model_{model_num}_unrelaxed.pdb')\n",
731
+ " view.addModel(open(pred_output_path,'r').read(),'pdb')\n",
732
+ " if color == \"lDDT\":\n",
733
+ " view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':50,'max':90}}})\n",
734
+ " elif color == \"rainbow\":\n",
735
+ " view.setStyle({'cartoon': {'color':'spectrum'}})\n",
736
+ " elif color == \"chain\":\n",
737
+ " for n,chain,color in zip(range(homooligomer),list(\"ABCDEFGH\"),\n",
738
+ " [\"lime\",\"cyan\",\"magenta\",\"yellow\",\"salmon\",\"white\",\"blue\",\"orange\"]):\n",
739
+ " view.setStyle({'chain':chain},{'cartoon': {'color':color}})\n",
740
+ " if show_sidechains:\n",
741
+ " BB = ['C','O','N']\n",
742
+ " view.addStyle({'and':[{'resn':[\"GLY\",\"PRO\"],'invert':True},{'atom':BB,'invert':True}]},\n",
743
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
744
+ " view.addStyle({'and':[{'resn':\"GLY\"},{'atom':'CA'}]},\n",
745
+ " {'sphere':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
746
+ " view.addStyle({'and':[{'resn':\"PRO\"},{'atom':['C','O'],'invert':True}]},\n",
747
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}}) \n",
748
+ " if show_mainchains:\n",
749
+ " BB = ['C','O','N','CA']\n",
750
+ " view.addStyle({'atom':BB},{'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
751
+ "\n",
752
+ " view.zoomTo()\n",
753
+ " return view\n",
754
+ "\n",
755
+ "show_pdb(model_num,show_sidechains, show_mainchains, color).show()\n",
756
+ "if color == \"lDDT\": plot_plddt_legend().show() \n",
757
+ "plot_confidence(model_num).show()"
758
+ ],
759
+ "execution_count": null,
760
+ "outputs": []
761
+ },
762
+ {
763
+ "cell_type": "code",
764
+ "metadata": {
765
+ "id": "Riekgf0KQv_3",
766
+ "cellView": "form"
767
+ },
768
+ "source": [
769
+ "#@title Download prediction\n",
770
+ "\n",
771
+ "#@markdown Once this cell has been executed, a zip-archive with \n",
772
+ "#@markdown the obtained prediction will be automatically downloaded \n",
773
+ "#@markdown to your computer.\n",
774
+ "\n",
775
+ "# add settings file\n",
776
+ "settings_path = os.path.join(output_dir,\"settings.txt\")\n",
777
+ "with open(settings_path, \"w\") as text_file:\n",
778
+ " text_file.write(f\"sequence={sequence}\\n\")\n",
779
+ " text_file.write(f\"msa_method={msa_method}\\n\")\n",
780
+ " text_file.write(f\"homooligomer={homooligomer}\\n\")\n",
781
+ " text_file.write(f\"use_amber_relax={use_amber_relax}\\n\")\n",
782
+ " text_file.write(f\"turbo={turbo}\\n\")\n",
783
+ " text_file.write(f\"use_templates=False\\n\")\n",
784
+ "\n",
785
+ "# --- Download the predictions ---\n",
786
+ "!zip -q -r {output_dir}.zip {output_dir}\n",
787
+ "files.download(f'{output_dir}.zip')"
788
+ ],
789
+ "execution_count": null,
790
+ "outputs": []
791
+ }
792
+ ]
793
+ }
data/beta/Alphafold_single.ipynb ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "Alphafold_single.ipynb",
7
+ "provenance": [],
8
+ "collapsed_sections": [],
9
+ "include_colab_link": true
10
+ },
11
+ "kernelspec": {
12
+ "display_name": "Python 3",
13
+ "name": "python3"
14
+ },
15
+ "language_info": {
16
+ "name": "python"
17
+ },
18
+ "accelerator": "GPU"
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {
24
+ "id": "view-in-github",
25
+ "colab_type": "text"
26
+ },
27
+ "source": [
28
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/Alphafold_single.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {
34
+ "id": "iVVz9evNDNOf"
35
+ },
36
+ "source": [
37
+ "#AlphaFold_single"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {
43
+ "id": "woIxeCPygt7K",
44
+ "cellView": "form"
45
+ },
46
+ "source": [
47
+ "#@title Install software\n",
48
+ "#@markdown Please execute this cell by pressing the _Play_ button \n",
49
+ "#@markdown on the left.\n",
50
+ "\n",
51
+ "# setup device\n",
52
+ "import os\n",
53
+ "import tensorflow as tf\n",
54
+ "import jax\n",
55
+ "\n",
56
+ "try:\n",
57
+ " # check if TPU is available\n",
58
+ " import jax.tools.colab_tpu\n",
59
+ " jax.tools.colab_tpu.setup_tpu()\n",
60
+ " print('Running on TPU')\n",
61
+ " DEVICE = \"tpu\"\n",
62
+ "except:\n",
63
+ " if jax.local_devices()[0].platform == 'cpu':\n",
64
+ " print(\"WARNING: no GPU detected, will be using CPU\")\n",
65
+ " DEVICE = \"cpu\"\n",
66
+ " else:\n",
67
+ " print('Running on GPU')\n",
68
+ " DEVICE = \"gpu\"\n",
69
+ " # disable GPU on tensorflow\n",
70
+ " tf.config.set_visible_devices([], 'GPU')\n",
71
+ "\n",
72
+ " \n",
73
+ "from IPython.utils import io\n",
74
+ "import subprocess\n",
75
+ "import tqdm.notebook\n",
76
+ "\n",
77
+ "GIT_REPO = 'https://github.com/deepmind/alphafold'\n",
78
+ "SOURCE_URL = 'https://storage.googleapis.com/alphafold/alphafold_params_2021-07-14.tar'\n",
79
+ "PARAMS_DIR = './alphafold/data/params'\n",
80
+ "PARAMS_PATH = os.path.join(PARAMS_DIR, os.path.basename(SOURCE_URL))\n",
81
+ "TQDM_BAR_FORMAT = '{l_bar}{bar}| {n_fmt}/{total_fmt} [elapsed: {elapsed} remaining: {remaining}]'\n",
82
+ "\n",
83
+ "# if not already installed\n",
84
+ "try:\n",
85
+ " with tqdm.notebook.tqdm(total=50, bar_format=TQDM_BAR_FORMAT) as pbar:\n",
86
+ " with io.capture_output() as captured:\n",
87
+ " if not os.path.isdir(\"alphafold\"):\n",
88
+ " %shell rm -rf alphafold\n",
89
+ " %shell git clone {GIT_REPO} alphafold\n",
90
+ " %shell (cd alphafold; git checkout 1e216f93f06aa04aa699562f504db1d02c3b704c --quiet)\n",
91
+ "\n",
92
+ " # colabfold patches\n",
93
+ " %shell mkdir --parents tmp\n",
94
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/colabfold.py\n",
95
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/pairmsa.py\n",
96
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/protein.patch -P tmp/\n",
97
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/config.patch -P tmp/\n",
98
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/model.patch -P tmp/\n",
99
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/modules.patch -P tmp/\n",
100
+ "\n",
101
+ " # Apply multi-chain patch from Lim Heo @huhlim\n",
102
+ " %shell patch -u alphafold/alphafold/common/protein.py -i tmp/protein.patch\n",
103
+ " \n",
104
+ " # Apply patch to dynamically control number of recycles (idea from Ryan Kibler)\n",
105
+ " %shell patch -u alphafold/alphafold/model/model.py -i tmp/model.patch\n",
106
+ " %shell patch -u alphafold/alphafold/model/modules.py -i tmp/modules.patch\n",
107
+ " %shell patch -u alphafold/alphafold/model/config.py -i tmp/config.patch\n",
108
+ " pbar.update(4)\n",
109
+ "\n",
110
+ " %shell pip3 install ./alphafold\n",
111
+ " pbar.update(4)\n",
112
+ " \n",
113
+ " # speedup from kaczmarj\n",
114
+ " %shell mkdir --parents \"{PARAMS_DIR}\"\n",
115
+ " %shell curl -fsSL \"{SOURCE_URL}\" | tar x -C \"{PARAMS_DIR}\"\n",
116
+ " pbar.update(14+27)\n",
117
+ "\n",
118
+ " # Install py3dmol.\n",
119
+ " %shell pip install py3dmol\n",
120
+ " pbar.update(1)\n",
121
+ " else:\n",
122
+ " pbar.update(50)\n",
123
+ "\n",
124
+ "except subprocess.CalledProcessError:\n",
125
+ " print(captured)\n",
126
+ " raise\n",
127
+ "\n",
128
+ "########################################################################################\n",
129
+ "# --- Python imports ---\n",
130
+ "import colabfold as cf\n",
131
+ "import sys\n",
132
+ "\n",
133
+ "from google.colab import files\n",
134
+ "import matplotlib.pyplot as plt\n",
135
+ "import numpy as np\n",
136
+ "import py3Dmol\n",
137
+ "\n",
138
+ "from alphafold.model import model\n",
139
+ "from alphafold.model import config\n",
140
+ "from alphafold.model import data\n",
141
+ "from alphafold.data import pipeline\n",
142
+ "from alphafold.common import protein\n",
143
+ "\n",
144
+ "from alphafold.model.tf import shape_placeholders\n",
145
+ "\n",
146
+ "def make_fixed_size(feat, shape_schema, num_res=100, msa_cluster_size=1, extra_msa_size=1, num_templates=0):\n",
147
+ " \"\"\"Guess at the MSA and sequence dimensions to make fixed size.\"\"\"\n",
148
+ " pad_size_map = {\n",
149
+ " shape_placeholders.NUM_RES: num_res,\n",
150
+ " shape_placeholders.NUM_MSA_SEQ: msa_cluster_size,\n",
151
+ " shape_placeholders.NUM_EXTRA_SEQ: extra_msa_size,\n",
152
+ " shape_placeholders.NUM_TEMPLATES: num_templates,\n",
153
+ " }\n",
154
+ " for k, v in feat.items():\n",
155
+ " # Don't transfer this to the accelerator.\n",
156
+ " if k == 'extra_cluster_assignment':\n",
157
+ " continue\n",
158
+ " shape = list(v.shape)\n",
159
+ " schema = shape_schema[k]\n",
160
+ " assert len(shape) == len(schema), (\n",
161
+ " f'Rank mismatch between shape and shape schema for {k}: '\n",
162
+ " f'{shape} vs {schema}')\n",
163
+ " pad_size = [pad_size_map.get(s2, None) or s1 for (s1, s2) in zip(shape, schema)]\n",
164
+ " padding = [(0, p - tf.shape(v)[i]) for i, p in enumerate(pad_size)]\n",
165
+ " if padding:\n",
166
+ " feat[k] = tf.pad(v, padding, name=f'pad_to_fixed_{k}')\n",
167
+ " feat[k].set_shape(pad_size)\n",
168
+ " return {k:np.asarray(v) for k,v in feat.items()}\n",
169
+ "\n",
170
+ "def parse_results(prediction_result, processed_feature_dict):\n",
171
+ " b_factors = prediction_result['plddt'][:,None] * prediction_result['structure_module']['final_atom_mask'] \n",
172
+ " dist_bins = jax.numpy.append(0,prediction_result[\"distogram\"][\"bin_edges\"])\n",
173
+ " dist_mtx = dist_bins[prediction_result[\"distogram\"][\"logits\"].argmax(-1)]\n",
174
+ " contact_mtx = jax.nn.softmax(prediction_result[\"distogram\"][\"logits\"])[:,:,dist_bins < 8].sum(-1)\n",
175
+ "\n",
176
+ " out = {\"unrelaxed_protein\": protein.from_prediction(processed_feature_dict, prediction_result, b_factors=b_factors),\n",
177
+ " \"plddt\": prediction_result['plddt'],\n",
178
+ " \"pLDDT\": prediction_result['plddt'].mean(),\n",
179
+ " \"dists\": dist_mtx,\n",
180
+ " \"adj\": contact_mtx}\n",
181
+ "\n",
182
+ " if \"ptm\" in prediction_result:\n",
183
+ " out.update({\"pae\": prediction_result['predicted_aligned_error'],\n",
184
+ " \"pTMscore\": prediction_result['ptm']})\n",
185
+ " return out\n",
186
+ "\n",
187
+ "if \"model_runner\" not in dir():\n",
188
+ " name = \"model_5_ptm\"\n",
189
+ " model_config = config.model_config(name)\n",
190
+ " model_config.data.eval.max_msa_clusters = 1\n",
191
+ " model_config.data.common.max_extra_msa = 1\n",
192
+ " model_config.model.num_recycle = 2\n",
193
+ " model_config.data.common.num_recycle = 2\n",
194
+ "\n",
195
+ " model_runner = model.RunModel(model_config, data.get_model_haiku_params(name,'./alphafold/data'))\n",
196
+ "\n",
197
+ " eval_cfg = model_runner.config.data.eval\n",
198
+ " crop_feats = {k:[None]+v for k,v in dict(eval_cfg.feat).items()} \n",
199
+ "\n",
200
+ " MAX_LEN = 100 "
201
+ ],
202
+ "execution_count": null,
203
+ "outputs": []
204
+ },
205
+ {
206
+ "cell_type": "code",
207
+ "metadata": {
208
+ "id": "rowN0bVYLe9n",
209
+ "cellView": "form"
210
+ },
211
+ "source": [
212
+ "#@title Enter the amino acid sequence to fold ⬇️\n",
213
+ "import re\n",
214
+ "\n",
215
+ "# define sequence\n",
216
+ "sequence = 'GGGGGGGGGGGGGGGGGGG' #@param {type:\"string\"}\n",
217
+ "sequence = re.sub(\"[^A-Z]\", \"\", sequence.upper())\n",
218
+ "\n",
219
+ "msas, deletion_matrices = [],[]\n",
220
+ "msas.append([sequence])\n",
221
+ "deletion_matrices.append([[0]*len(sequence)])\n",
222
+ "\n",
223
+ "num_res = len(sequence)\n",
224
+ "feature_dict = {**pipeline.make_sequence_features(sequence, 'test', num_res),\n",
225
+ " **pipeline.make_msa_features(msas, deletion_matrices=deletion_matrices)}\n",
226
+ "\n",
227
+ "if num_res > MAX_LEN:\n",
228
+ " MAX_LEN = num_res\n",
229
+ "\n",
230
+ "# process features\n",
231
+ "processed_feature_dict = model_runner.process_features(feature_dict, random_seed=0)\n",
232
+ "processed_feature_dict = make_fixed_size(processed_feature_dict, crop_feats, num_res=MAX_LEN)\n",
233
+ "\n",
234
+ "# predict\n",
235
+ "prediction_result, (r, t) = model_runner.predict(processed_feature_dict)\n",
236
+ "\n",
237
+ "# save results\n",
238
+ "outs = parse_results(prediction_result, processed_feature_dict)\n",
239
+ "outs.update({\"recycles\":r, \"tol\":t})\n",
240
+ "with open(\"out.pdb\", 'w') as f: f.write(protein.to_pdb(outs[\"unrelaxed_protein\"]))"
241
+ ],
242
+ "execution_count": null,
243
+ "outputs": []
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "metadata": {
248
+ "id": "KAZj6CBZTkJM",
249
+ "cellView": "form"
250
+ },
251
+ "source": [
252
+ "#@title Display 3D structure {run: \"auto\"}\n",
253
+ "color = \"chain\" #@param [\"chain\", \"lDDT\", \"rainbow\"]\n",
254
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
255
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
256
+ "\n",
257
+ "cf.show_pdb(\"out.pdb\", show_sidechains, show_mainchains, color,\n",
258
+ " color_HP=True, size=(800,480)).show()\n",
259
+ "if color == \"lDDT\":\n",
260
+ " cf.plot_plddt_legend().show() \n",
261
+ "if \"pae\" in outs:\n",
262
+ " cf.plot_confidence(outs[\"plddt\"][:num_res], outs[\"pae\"][:num_res,:][:,:num_res]).show()\n",
263
+ "else:\n",
264
+ " cf.plot_confidence(outs[\"plddt\"][:num_res]).show()"
265
+ ],
266
+ "execution_count": null,
267
+ "outputs": []
268
+ }
269
+ ]
270
+ }
data/beta/ESMFold.ipynb ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "view-in-github",
7
+ "colab_type": "text"
8
+ },
9
+ "source": [
10
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/ESMFold.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "metadata": {
16
+ "id": "AMwhSNWEzRCZ"
17
+ },
18
+ "source": [
19
+ "#**ESMFold**\n",
20
+ "for more details see: [Github](https://github.com/facebookresearch/esm/tree/main/esm), [Preprint](https://www.biorxiv.org/content/10.1101/2022.07.20.500902v1)\n",
21
+ "\n",
22
+ "#### **Tips and Instructions**\n",
23
+ "- click the little ▶ play icon to the left of each cell below.\n",
24
+ "\n",
25
+ "#### **Colab Limitations**\n",
26
+ "- On Tesla T4 (typical free colab GPU), max total length ~ 900\n",
27
+ "\n"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "execution_count": null,
33
+ "metadata": {
34
+ "id": "catNptjYwNM6",
35
+ "cellView": "form"
36
+ },
37
+ "outputs": [],
38
+ "source": [
39
+ "%%time\n",
40
+ "#@title install\n",
41
+ "#@markdown install ESMFold, OpenFold and download Params (~2min 30s)\n",
42
+ "import os,sys\n",
43
+ "from IPython.utils import io\n",
44
+ "import time\n",
45
+ "if not os.path.isfile(\"esmfold.model\"):\n",
46
+ " with io.capture_output() as captured:\n",
47
+ " # download esmfold params\n",
48
+ " os.system(\"apt-get install aria2 -qq\")\n",
49
+ " os.system(\"aria2c -q -x 16 https://files.ipd.uw.edu/pub/esmfold/esmfold.model &\")\n",
50
+ "\n",
51
+ " # install libs\n",
52
+ " os.system(\"pip install -q omegaconf pytorch_lightning biopython ml_collections einops py3Dmol\")\n",
53
+ " os.system(\"pip install -q git+https://github.com/NVIDIA/dllogger.git\")\n",
54
+ "\n",
55
+ " # install esmfold (will be replaced later with github)\n",
56
+ " os.system(\"wget -qnc https://files.ipd.uw.edu/pub/esmfold/esmfold_beta.zip; unzip -qqo esmfold_beta.zip\")\n",
57
+ "\n",
58
+ " # install openfold\n",
59
+ " commit = \"6908936b68ae89f67755240e2f588c09ec31d4c8\"\n",
60
+ " os.system(f\"pip install -q git+https://github.com/aqlaboratory/openfold.git@{commit}\")\n",
61
+ " \n",
62
+ " # wait for Params to finish downloading...\n",
63
+ " if not os.path.isfile(\"esmfold.model\"):\n",
64
+ " # backup source!\n",
65
+ " os.system(\"aria2c -q -x 16 https://colabfold.steineggerlab.workers.dev/esm/esmfold.model\")\n",
66
+ " else:\n",
67
+ " while os.path.isfile(\"esmfold.model.aria2\"):\n",
68
+ " time.sleep(5)"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": null,
74
+ "metadata": {
75
+ "id": "2rqTrvifh17B",
76
+ "cellView": "form"
77
+ },
78
+ "outputs": [],
79
+ "source": [
80
+ "#@title ##run **ESMFold**\n",
81
+ "%%time\n",
82
+ "from string import ascii_uppercase, ascii_lowercase\n",
83
+ "import hashlib, re, os\n",
84
+ "import numpy as np\n",
85
+ "from jax.tree_util import tree_map\n",
86
+ "import matplotlib.pyplot as plt\n",
87
+ "from scipy.special import softmax\n",
88
+ "\n",
89
+ "def parse_output(output):\n",
90
+ " pae = (output[\"aligned_confidence_probs\"][0] * np.arange(64)).mean(-1) * 31\n",
91
+ " plddt = output[\"plddt\"][0,:,1] * 100\n",
92
+ " \n",
93
+ " bins = np.append(0,np.linspace(2.3125,21.6875,63))\n",
94
+ " sm_contacts = softmax(output[\"distogram_logits\"],-1)[0]\n",
95
+ " sm_contacts = sm_contacts[...,bins<8].sum(-1)\n",
96
+ " xyz = output[\"positions\"][-1,0,:,1]\n",
97
+ " mask = output[\"atom37_atom_exists\"][0,:,1] == 1\n",
98
+ " o = {\"pae\":pae[mask,:][:,mask],\n",
99
+ " \"plddt\":plddt[mask],\n",
100
+ " \"sm_contacts\":sm_contacts[mask,:][:,mask],\n",
101
+ " \"xyz\":xyz[mask]}\n",
102
+ " if \"contacts\" in output[\"lm_output\"]:\n",
103
+ " lm_contacts = output[\"lm_output\"][\"contacts\"].astype(float)[0]\n",
104
+ " o[\"lm_contacts\"] = lm_contacts[mask,:][:,mask]\n",
105
+ " return o\n",
106
+ "\n",
107
+ "def get_hash(x): return hashlib.sha1(x.encode()).hexdigest()\n",
108
+ "alphabet_list = list(ascii_uppercase+ascii_lowercase)\n",
109
+ "\n",
110
+ "jobname = \"test\" #@param {type:\"string\"}\n",
111
+ "jobname = re.sub(r'\\W+', '', jobname)[:50]\n",
112
+ "\n",
113
+ "sequence = \"GWSTELEKHREELKEFLKKEGITNVEIRIDNGRLEVRVEGGTERLKRFLEELRQKLEKKGYTVDIKIE\" #@param {type:\"string\"}\n",
114
+ "sequence = re.sub(\"[^A-Z:]\", \"\", sequence.replace(\"/\",\":\").upper())\n",
115
+ "sequence = re.sub(\":+\",\":\",sequence)\n",
116
+ "sequence = re.sub(\"^[:]+\",\"\",sequence)\n",
117
+ "sequence = re.sub(\"[:]+$\",\"\",sequence)\n",
118
+ "\n",
119
+ "#@markdown ---\n",
120
+ "#@markdown ###**Advanced Options**\n",
121
+ "num_recycles = 3 #@param [\"0\", \"1\", \"2\", \"3\", \"6\", \"12\"] {type:\"raw\"}\n",
122
+ "get_LM_contacts = False #@param {type:\"boolean\"}\n",
123
+ "\n",
124
+ "#@markdown **multimer options (experimental)**\n",
125
+ "#@markdown - use \"/\" to specify chainbreaks, (eg. sequence=\"AAA/AAA\")\n",
126
+ "#@markdown - for homo-oligomeric predictions, set copies > 1\n",
127
+ "\n",
128
+ "copies = 1 #@param {type:\"integer\"}\n",
129
+ "chain_linker = 25 #@param {type:\"raw\"}\n",
130
+ "if copies == \"\" or copies <= 0: copies = 1\n",
131
+ "sequence = \":\".join([sequence] * copies)\n",
132
+ "\n",
133
+ "#@markdown **sampling options (experimental)**\n",
134
+ "#@markdown - Samples are generated via random masking (defined by `masking_rate`) \n",
135
+ "#@markdown of input sequence (stochastic_mode=\"LM\") and/or via dropout within structure module (stochastic_mode=\"SM\").\n",
136
+ "samples = None #@param [\"None\", \"1\", \"4\", \"8\", \"16\", \"32\", \"64\"] {type:\"raw\"}\n",
137
+ "masking_rate = 0.15 #@param {type:\"raw\"}\n",
138
+ "stochastic_mode = \"LM\" #@param [\"LM\", \"LM_SM\", \"SM\"]\n",
139
+ "\n",
140
+ "ID = jobname+\"_\"+get_hash(sequence)[:5]\n",
141
+ "seqs = sequence.split(\":\")\n",
142
+ "lengths = [len(s) for s in seqs]\n",
143
+ "length = sum(lengths)\n",
144
+ "print(\"length\",length)\n",
145
+ "\n",
146
+ "u_seqs = list(set(seqs))\n",
147
+ "if len(seqs) == 1: mode = \"mono\"\n",
148
+ "elif len(u_seqs) == 1: mode = \"homo\"\n",
149
+ "else: mode = \"hetero\"\n",
150
+ "\n",
151
+ "if \"model\" not in dir():\n",
152
+ " import torch\n",
153
+ " model = torch.load(\"esmfold.model\")\n",
154
+ " model.cuda().requires_grad_(False)\n",
155
+ "\n",
156
+ "# optimized for Tesla T4\n",
157
+ "if length > 700:\n",
158
+ " model.trunk.set_chunk_size(64)\n",
159
+ "else:\n",
160
+ " model.trunk.set_chunk_size(128)\n",
161
+ "\n",
162
+ "best_pdb_str = None\n",
163
+ "best_ptm = 0\n",
164
+ "best_output = None\n",
165
+ "traj = []\n",
166
+ "\n",
167
+ "num_samples = 1 if samples is None else samples\n",
168
+ "for seed in range(num_samples):\n",
169
+ " torch.cuda.empty_cache()\n",
170
+ " if samples is None:\n",
171
+ " seed = \"default\"\n",
172
+ " mask_rate = 0.0\n",
173
+ " model.train(False)\n",
174
+ " else:\n",
175
+ " torch.manual_seed(seed)\n",
176
+ " mask_rate = masking_rate if \"LM\" in stochastic_mode else 0.0\n",
177
+ " model.train(\"SM\" in stochastic_mode)\n",
178
+ "\n",
179
+ " output = model.infer(sequence,\n",
180
+ " num_recycles=num_recycles+1,\n",
181
+ " chain_linker=\"X\"*chain_linker,\n",
182
+ " residue_index_offset=512,\n",
183
+ " mask_rate=mask_rate,\n",
184
+ " return_contacts=get_LM_contacts)\n",
185
+ " \n",
186
+ " pdb_str = model.output_to_pdb(output)[0]\n",
187
+ " output = tree_map(lambda x: x.cpu().numpy(), output)\n",
188
+ " ptm = output[\"ptm\"]\n",
189
+ " plddt = output[\"plddt\"][...,1].mean()\n",
190
+ " traj.append(parse_output(output))\n",
191
+ " print(f'{seed} ptm: {ptm:.3f} plddt: {plddt:.3f}')\n",
192
+ " if ptm > best_ptm:\n",
193
+ " best_pdb_str = pdb_str\n",
194
+ " best_ptm = ptm\n",
195
+ " best_output = output\n",
196
+ " os.system(f\"mkdir -p {ID}\")\n",
197
+ " if samples is None:\n",
198
+ " pdb_filename = f\"{ID}/ptm{ptm:.3f}_r{num_recycles}_{seed}.pdb\"\n",
199
+ " else:\n",
200
+ " pdb_filename = f\"{ID}/ptm{ptm:.3f}_r{num_recycles}_seed{seed}_{stochastic_mode}_mr{masking_rate:.2f}.pdb\"\n",
201
+ "\n",
202
+ " with open(pdb_filename,\"w\") as out:\n",
203
+ " out.write(pdb_str)"
204
+ ]
205
+ },
206
+ {
207
+ "cell_type": "code",
208
+ "execution_count": null,
209
+ "metadata": {
210
+ "cellView": "form",
211
+ "id": "tg7eFMC-TYRX"
212
+ },
213
+ "outputs": [],
214
+ "source": [
215
+ "#@title display (optional) {run: \"auto\"}\n",
216
+ "#@markdown Note: If samples selected, the model with max pTM is displayed.\n",
217
+ "import py3Dmol\n",
218
+ "\n",
219
+ "\n",
220
+ "pymol_color_list = [\"#33ff33\",\"#00ffff\",\"#ff33cc\",\"#ffff00\",\"#ff9999\",\"#e5e5e5\",\"#7f7fff\",\"#ff7f00\",\n",
221
+ " \"#7fff7f\",\"#199999\",\"#ff007f\",\"#ffdd5e\",\"#8c3f99\",\"#b2b2b2\",\"#007fff\",\"#c4b200\",\n",
222
+ " \"#8cb266\",\"#00bfbf\",\"#b27f7f\",\"#fcd1a5\",\"#ff7f7f\",\"#ffbfdd\",\"#7fffff\",\"#ffff7f\",\n",
223
+ " \"#00ff7f\",\"#337fcc\",\"#d8337f\",\"#bfff3f\",\"#ff7fff\",\"#d8d8ff\",\"#3fffbf\",\"#b78c4c\",\n",
224
+ " \"#339933\",\"#66b2b2\",\"#ba8c84\",\"#84bf00\",\"#b24c66\",\"#7f7f7f\",\"#3f3fa5\",\"#a5512b\"]\n",
225
+ "\n",
226
+ "def show_pdb(pdb_str, show_sidechains=False, show_mainchains=False,\n",
227
+ " color=\"pLDDT\", chains=None, vmin=50, vmax=90,\n",
228
+ " size=(800,480), hbondCutoff=4.0,\n",
229
+ " Ls=None,\n",
230
+ " animate=False):\n",
231
+ " \n",
232
+ " if chains is None:\n",
233
+ " chains = 1 if Ls is None else len(Ls)\n",
234
+ " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js', width=size[0], height=size[1])\n",
235
+ " if animate:\n",
236
+ " view.addModelsAsFrames(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
237
+ " else:\n",
238
+ " view.addModel(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
239
+ " if color == \"pLDDT\":\n",
240
+ " view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':vmin,'max':vmax}}})\n",
241
+ " elif color == \"rainbow\":\n",
242
+ " view.setStyle({'cartoon': {'color':'spectrum'}})\n",
243
+ " elif color == \"chain\":\n",
244
+ " for n,chain,color in zip(range(chains),alphabet_list,pymol_color_list):\n",
245
+ " view.setStyle({'chain':chain},{'cartoon': {'color':color}})\n",
246
+ " if show_sidechains:\n",
247
+ " BB = ['C','O','N']\n",
248
+ " view.addStyle({'and':[{'resn':[\"GLY\",\"PRO\"],'invert':True},{'atom':BB,'invert':True}]},\n",
249
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
250
+ " view.addStyle({'and':[{'resn':\"GLY\"},{'atom':'CA'}]},\n",
251
+ " {'sphere':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
252
+ " view.addStyle({'and':[{'resn':\"PRO\"},{'atom':['C','O'],'invert':True}]},\n",
253
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}}) \n",
254
+ " if show_mainchains:\n",
255
+ " BB = ['C','O','N','CA']\n",
256
+ " view.addStyle({'atom':BB},{'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
257
+ " view.zoomTo()\n",
258
+ " if animate: view.animate()\n",
259
+ " return view\n",
260
+ "\n",
261
+ "color = \"confidence\" #@param [\"confidence\", \"rainbow\", \"chain\"]\n",
262
+ "if color == \"confidence\": color = \"pLDDT\"\n",
263
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
264
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
265
+ "show_pdb(best_pdb_str, color=color,\n",
266
+ " show_sidechains=show_sidechains,\n",
267
+ " show_mainchains=show_mainchains,\n",
268
+ " Ls=lengths).show()"
269
+ ]
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "execution_count": null,
274
+ "metadata": {
275
+ "cellView": "form",
276
+ "id": "hkiKtX43voI-"
277
+ },
278
+ "outputs": [],
279
+ "source": [
280
+ "#@title plot confidence (optional)\n",
281
+ "#@markdown Note: If samples selected, the model with max pTM is displayed.\n",
282
+ "\n",
283
+ "dpi = 100 #@param {type:\"integer\"}\n",
284
+ "\n",
285
+ "def plot_ticks(Ls):\n",
286
+ " Ln = sum(Ls)\n",
287
+ " L_prev = 0\n",
288
+ " for L_i in Ls[:-1]:\n",
289
+ " L = L_prev + L_i\n",
290
+ " L_prev += L_i\n",
291
+ " plt.plot([0,Ln],[L,L],color=\"black\")\n",
292
+ " plt.plot([L,L],[0,Ln],color=\"black\")\n",
293
+ " ticks = np.cumsum([0]+Ls)\n",
294
+ " ticks = (ticks[1:] + ticks[:-1])/2\n",
295
+ " plt.yticks(ticks,alphabet_list[:len(ticks)])\n",
296
+ "\n",
297
+ "def plot_confidence(output, Ls=None, dpi=100):\n",
298
+ " O = parse_output(output)\n",
299
+ " if \"lm_contacts\" in O:\n",
300
+ " plt.figure(figsize=(20,4), dpi=dpi)\n",
301
+ " plt.subplot(1,4,1)\n",
302
+ " else:\n",
303
+ " plt.figure(figsize=(15,4), dpi=dpi)\n",
304
+ " plt.subplot(1,3,1)\n",
305
+ "\n",
306
+ " plt.title('Predicted lDDT')\n",
307
+ " plt.plot(O[\"plddt\"])\n",
308
+ " if Ls is not None:\n",
309
+ " L_prev = 0\n",
310
+ " for L_i in Ls[:-1]:\n",
311
+ " L = L_prev + L_i\n",
312
+ " L_prev += L_i\n",
313
+ " plt.plot([L,L],[0,100],color=\"black\")\n",
314
+ " plt.xlim(0,O[\"plddt\"].shape[0])\n",
315
+ " plt.ylim(0,100)\n",
316
+ " plt.ylabel('plDDT')\n",
317
+ " plt.xlabel('position')\n",
318
+ " plt.subplot(1,4 if \"lm_contacts\" in O else 3,2)\n",
319
+ "\n",
320
+ " plt.title('Predicted Aligned Error')\n",
321
+ " Ln = O[\"pae\"].shape[0]\n",
322
+ " plt.imshow(O[\"pae\"],cmap=\"bwr\",vmin=0,vmax=30,extent=(0, Ln, Ln, 0))\n",
323
+ " if Ls is not None and len(Ls) > 1: plot_ticks(Ls)\n",
324
+ " plt.colorbar()\n",
325
+ " plt.xlabel('Scored residue')\n",
326
+ " plt.ylabel('Aligned residue')\n",
327
+ "\n",
328
+ " if \"lm_contacts\" in O:\n",
329
+ " plt.subplot(1,4,3)\n",
330
+ " plt.title(\"contacts from LM\")\n",
331
+ " plt.imshow(O[\"lm_contacts\"],cmap=\"Greys\",vmin=0,vmax=1,extent=(0, Ln, Ln, 0))\n",
332
+ " if Ls is not None and len(Ls) > 1: plot_ticks(Ls)\n",
333
+ " plt.subplot(1,4,4)\n",
334
+ " else:\n",
335
+ " plt.subplot(1,3,3)\n",
336
+ " plt.title(\"contacts from Structure Module\")\n",
337
+ " plt.imshow(O[\"sm_contacts\"],cmap=\"Greys\",vmin=0,vmax=1,extent=(0, Ln, Ln, 0))\n",
338
+ " if Ls is not None and len(Ls) > 1: plot_ticks(Ls)\n",
339
+ " return plt\n",
340
+ "\n",
341
+ "plot_confidence(best_output, Ls=lengths, dpi=dpi)\n",
342
+ "plt.show()"
343
+ ]
344
+ },
345
+ {
346
+ "cell_type": "code",
347
+ "source": [
348
+ "#@title download predictions\n",
349
+ "from google.colab import files\n",
350
+ "os.system(f\"zip {ID}.zip {ID}/*\")\n",
351
+ "files.download(f'{ID}.zip')"
352
+ ],
353
+ "metadata": {
354
+ "cellView": "form",
355
+ "id": "AVn1z6H9o7GT"
356
+ },
357
+ "execution_count": null,
358
+ "outputs": []
359
+ },
360
+ {
361
+ "cell_type": "code",
362
+ "source": [
363
+ "#@title animate outputs (optional)\n",
364
+ "#@markdown if more than one sample generated\n",
365
+ "import os\n",
366
+ "if not os.path.isdir(\"colabfold\"):\n",
367
+ " os.system(\"git clone https://github.com/sokrypton/ColabFold.git\")\n",
368
+ "import ColabFold.beta.colabfold as cf\n",
369
+ "\n",
370
+ "dpi = 100#@param {type:\"integer\"}\n",
371
+ "color_by_plddt = True #@param {type:\"boolean\"}\n",
372
+ "use_pca = True\n",
373
+ "cycle = True \n",
374
+ "\n",
375
+ "import matplotlib\n",
376
+ "from matplotlib import animation\n",
377
+ "from IPython.display import HTML\n",
378
+ "from sklearn.decomposition import PCA\n",
379
+ "\n",
380
+ "def mk_animation(xyz, labels, plddt, ref=0, Ls=None, line_w=2.0, dpi=100,color_by_plddt=False):\n",
381
+ "\n",
382
+ " def ca_align_to_last(positions, ref):\n",
383
+ " def align(P, Q):\n",
384
+ " if Ls is None or len(Ls) == 1:\n",
385
+ " P_,Q_ = P,Q\n",
386
+ " else:\n",
387
+ " # align relative to first chain\n",
388
+ " P_,Q_ = P[:Ls[0]],Q[:Ls[0]]\n",
389
+ " p = P_ - P_.mean(0,keepdims=True)\n",
390
+ " q = Q_ - Q_.mean(0,keepdims=True)\n",
391
+ " return ((P - P_.mean(0,keepdims=True)) @ cf.kabsch(p,q)) + Q_.mean(0,keepdims=True)\n",
392
+ " \n",
393
+ " pos = positions[ref] - positions[ref].mean(0,keepdims=True)\n",
394
+ " best_2D_view = pos @ cf.kabsch(pos,pos,return_v=True)\n",
395
+ "\n",
396
+ " new_positions = []\n",
397
+ " for i in range(len(positions)):\n",
398
+ " new_positions.append(align(positions[i],best_2D_view))\n",
399
+ " return np.asarray(new_positions)\n",
400
+ "\n",
401
+ " # align to reference \n",
402
+ " pos = ca_align_to_last(xyz, ref)\n",
403
+ "\n",
404
+ " fig, (ax1) = plt.subplots(1)\n",
405
+ " fig.set_figwidth(5)\n",
406
+ " fig.set_figheight(5)\n",
407
+ " fig.set_dpi(dpi)\n",
408
+ "\n",
409
+ " xy_min = pos[...,:2].min() - 1\n",
410
+ " xy_max = pos[...,:2].max() + 1\n",
411
+ "\n",
412
+ " for ax in [ax1]:\n",
413
+ " ax.set_xlim(xy_min, xy_max)\n",
414
+ " ax.set_ylim(xy_min, xy_max)\n",
415
+ " ax.axis(False)\n",
416
+ "\n",
417
+ " ims=[]\n",
418
+ " for l,pos_,plddt_ in zip(labels,pos,plddt):\n",
419
+ " if color_by_plddt:\n",
420
+ " img = cf.plot_pseudo_3D(pos_, c=plddt_, cmin=50, cmax=90, line_w=line_w, ax=ax1) \n",
421
+ " elif Ls is None or len(Ls) == 1:\n",
422
+ " img = cf.plot_pseudo_3D(pos_, ax=ax1, line_w=line_w)\n",
423
+ " else:\n",
424
+ " c = np.concatenate([[n]*L for n,L in enumerate(Ls)])\n",
425
+ " img = cf.plot_pseudo_3D(pos_, c=c, cmap=cf.pymol_cmap, cmin=0, cmax=39, line_w=line_w, ax=ax1)\n",
426
+ " ims.append([cf.add_text(f\"{l}\", ax1),img])\n",
427
+ " \n",
428
+ " ani = animation.ArtistAnimation(fig, ims, blit=True, interval=120)\n",
429
+ " plt.close()\n",
430
+ " return ani.to_html5_video()\n",
431
+ "\n",
432
+ "labels = np.array([f\"seed:{x}\" for x in range(len(traj))])\n",
433
+ "pos = np.array([x[\"xyz\"] for x in traj])\n",
434
+ "plddt = np.array([x[\"plddt\"] for x in traj])\n",
435
+ "if use_pca and pos.shape[0] > 1:\n",
436
+ " pos_ca = pos\n",
437
+ " if lengths is not None and len(lengths) > 1:\n",
438
+ " pos_ca = pos_ca[:,:lengths[0]]\n",
439
+ " i,j = np.triu_indices(pos_ca.shape[1],k=1)\n",
440
+ " pos_ca_dm = np.sqrt(np.square(pos_ca[:,None,:,:] - pos_ca[:,:,None]).sum(-1))[:,i,j]\n",
441
+ " pc = PCA(1).fit_transform(pos_ca_dm)[:,0].argsort()\n",
442
+ " if cycle:\n",
443
+ " pc = np.append(pc,pc[1:-1][::-1])\n",
444
+ " pos = pos[pc]\n",
445
+ " labels = labels[pc]\n",
446
+ " plddt = plddt[pc]\n",
447
+ "HTML(mk_animation(pos, labels, plddt, Ls=lengths, dpi=dpi, color_by_plddt=color_by_plddt))"
448
+ ],
449
+ "metadata": {
450
+ "cellView": "form",
451
+ "id": "NY8H_iM5WFUu"
452
+ },
453
+ "execution_count": null,
454
+ "outputs": []
455
+ }
456
+ ],
457
+ "metadata": {
458
+ "accelerator": "GPU",
459
+ "colab": {
460
+ "provenance": [],
461
+ "include_colab_link": true
462
+ },
463
+ "gpuClass": "standard",
464
+ "kernelspec": {
465
+ "display_name": "Python 3",
466
+ "name": "python3"
467
+ },
468
+ "language_info": {
469
+ "name": "python"
470
+ }
471
+ },
472
+ "nbformat": 4,
473
+ "nbformat_minor": 0
474
+ }
data/beta/ESMFold_advanced.ipynb ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "view-in-github",
7
+ "colab_type": "text"
8
+ },
9
+ "source": [
10
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/ESMFold_advanced.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "metadata": {
16
+ "id": "AMwhSNWEzRCZ"
17
+ },
18
+ "source": [
19
+ "#**ESMFold_advanced**\n",
20
+ "for more details see: [Github](https://github.com/facebookresearch/esm/tree/main/esm), [Preprint](https://www.biorxiv.org/content/10.1101/2022.07.20.500902v1)\n",
21
+ "\n",
22
+ "#### **Tips and Instructions**\n",
23
+ "- click the little ▶ play icon to the left of each cell below.\n",
24
+ "\n",
25
+ "#### **Colab Limitations**\n",
26
+ "- On Tesla T4 (typical free colab GPU), max total length ~ 900\n",
27
+ "\n"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "execution_count": null,
33
+ "metadata": {
34
+ "id": "catNptjYwNM6",
35
+ "cellView": "form"
36
+ },
37
+ "outputs": [],
38
+ "source": [
39
+ "%%time\n",
40
+ "#@title install\n",
41
+ "#@markdown install ESMFold, OpenFold and download Params (~2min 30s)\n",
42
+ "\n",
43
+ "import os, time\n",
44
+ "import torch\n",
45
+ "if not os.path.isfile(\"esmfold.model\"):\n",
46
+ " # download esmfold params\n",
47
+ " os.system(\"apt-get install aria2 -qq\")\n",
48
+ " os.system(\"aria2c -q -x 16 https://colabfold.steineggerlab.workers.dev/esm/esmfold.model &\")\n",
49
+ "\n",
50
+ " # install libs\n",
51
+ " print(\"installing libs...\")\n",
52
+ " os.system(\"pip install -q omegaconf pytorch_lightning biopython ml_collections einops py3Dmol modelcif\")\n",
53
+ " os.system(\"pip install -q git+https://github.com/NVIDIA/dllogger.git\")\n",
54
+ "\n",
55
+ " print(\"installing openfold...\")\n",
56
+ " # install openfold\n",
57
+ " os.system(f\"pip install -q git+https://github.com/sokrypton/openfold.git\")\n",
58
+ "\n",
59
+ " print(\"installing esmfold...\")\n",
60
+ " # install esmfold\n",
61
+ " os.system(f\"pip install -q git+https://github.com/sokrypton/esm.git@beta\")\n",
62
+ "\n",
63
+ " # wait for Params to finish downloading...\n",
64
+ " if not os.path.isfile(\"esmfold.model\"):\n",
65
+ " # backup source!\n",
66
+ " os.system(\"aria2c -q -x 16 https://files.ipd.uw.edu/pub/esmfold/esmfold.model\")\n",
67
+ " else:\n",
68
+ " while os.path.isfile(\"esmfold.model.aria2\"):\n",
69
+ " time.sleep(5)\n",
70
+ "\n",
71
+ "if \"model\" not in dir():\n",
72
+ " model_path = \"esmfold.model\"\n",
73
+ " model = torch.load(model_path, weights_only=False)\n",
74
+ " model.cuda().requires_grad_(False)\n",
75
+ "\n",
76
+ "import os\n",
77
+ "import re\n",
78
+ "import hashlib\n",
79
+ "import numpy as np\n",
80
+ "import torch\n",
81
+ "from string import ascii_uppercase, ascii_lowercase\n",
82
+ "from jax.tree_util import tree_map\n",
83
+ "from scipy.special import softmax\n",
84
+ "from typing import Optional\n",
85
+ "\n",
86
+ "def get_hash(x: str) -> str:\n",
87
+ " \"\"\"Generates a SHA1 hash for a given string.\"\"\"\n",
88
+ " return hashlib.sha1(x.encode()).hexdigest()\n",
89
+ "\n",
90
+ "def parse_output(output: dict) -> dict:\n",
91
+ " \"\"\"\n",
92
+ " Parses the raw model output dictionary to extract key metrics and structures.\n",
93
+ "\n",
94
+ " Args:\n",
95
+ " output: The raw dictionary from model.infer().\n",
96
+ "\n",
97
+ " Returns:\n",
98
+ " A dictionary containing pae, plddt, contacts, and xyz coordinates.\n",
99
+ " \"\"\"\n",
100
+ " pae = (output[\"aligned_confidence_probs\"][0] * np.arange(64)).mean(-1) * 31\n",
101
+ " plddt = output[\"plddt\"][0, :, 1]\n",
102
+ "\n",
103
+ " bins = np.append(0, np.linspace(2.3125, 21.6875, 63))\n",
104
+ " sm_contacts = softmax(output[\"distogram_logits\"], -1)[0]\n",
105
+ " sm_contacts = sm_contacts[..., bins < 8].sum(-1)\n",
106
+ " xyz = output[\"positions\"][-1, 0, :, 1]\n",
107
+ " mask = output[\"atom37_atom_exists\"][0, :, 1] == 1\n",
108
+ "\n",
109
+ " o = {\"pae\": pae[mask, :][:, mask],\n",
110
+ " \"plddt\": plddt[mask],\n",
111
+ " \"sm_contacts\": sm_contacts[mask, :][:, mask],\n",
112
+ " \"xyz\": xyz[mask]}\n",
113
+ "\n",
114
+ " if \"contacts\" in output[\"lm_output\"]:\n",
115
+ " lm_contacts = output[\"lm_output\"][\"contacts\"].astype(float)[0]\n",
116
+ " o[\"lm_contacts\"] = lm_contacts[mask, :][:, mask]\n",
117
+ "\n",
118
+ " return o\n",
119
+ "\n",
120
+ "# --- Main Prediction Function ---\n",
121
+ "\n",
122
+ "def predict_esmfold(\n",
123
+ " model: torch.nn.Module,\n",
124
+ " sequence: str,\n",
125
+ " jobname: str = \"test\",\n",
126
+ " num_recycles: int = 3,\n",
127
+ " get_LM_contacts: bool = False,\n",
128
+ " copies: int = 1,\n",
129
+ " chain_linker: int = 25,\n",
130
+ " samples: Optional[int] = None,\n",
131
+ " masking_rate: float = 0.15,\n",
132
+ " stochastic_mode: str = \"LM\",\n",
133
+ " save_dir: str = \".\",\n",
134
+ " verbose=False\n",
135
+ ") -> dict:\n",
136
+ " \"\"\"\n",
137
+ " Runs ESMFold prediction for a given sequence and parameters.\n",
138
+ "\n",
139
+ " Args:\n",
140
+ " model: The loaded ESMFold torch model.\n",
141
+ " sequence: The amino acid sequence (e.g., \"GWSTELEKH...\").\n",
142
+ " jobname: A name for the prediction job.\n",
143
+ " num_recycles: Number of recycling iterations (0, 1, 2, 3, 6, 12).\n",
144
+ " get_LM_contacts: Whether to return language model contacts.\n",
145
+ " copies: Number of copies for homo-oligomeric predictions.\n",
146
+ " chain_linker: Length of the 'X' linker for multimers.\n",
147
+ " samples: Number of stochastic samples (None, 1, 4, 8, 16, 32, 64).\n",
148
+ " masking_rate: Masking rate for stochastic LM sampling.\n",
149
+ " stochastic_mode: Type of stochastic sampling (\"LM\", \"LM_SM\", \"SM\").\n",
150
+ " save_dir: Directory to save PDB files and results.\n",
151
+ "\n",
152
+ " Returns:\n",
153
+ " A dictionary containing:\n",
154
+ " - \"best_output\": Raw output dictionary of the best model.\n",
155
+ " - \"best_pdb_str\": PDB string of the best model (highest ptm).\n",
156
+ " - \"best_ptm\": The ptm score of the best model.\n",
157
+ " - \"trajectory\": A list of parsed outputs for each sample.\n",
158
+ " - \"prediction_dir\": The specific directory where results were saved.\n",
159
+ " \"\"\"\n",
160
+ "\n",
161
+ " # --- Input Processing ---\n",
162
+ " jobname = re.sub(r'\\W+', '', jobname)[:50]\n",
163
+ "\n",
164
+ " # Clean sequence\n",
165
+ " sequence = re.sub(\"[^A-Z:]\", \"\", sequence.replace(\"/\", \":\").upper())\n",
166
+ " sequence = re.sub(\":+\", \":\", sequence)\n",
167
+ " sequence = re.sub(\"^[:]+\", \"\", sequence)\n",
168
+ " sequence = re.sub(\"[:]+$\", \"\", sequence)\n",
169
+ "\n",
170
+ " if copies <= 0:\n",
171
+ " copies = 1\n",
172
+ " sequence = \":\".join([sequence] * copies)\n",
173
+ "\n",
174
+ " seqs = sequence.split(\":\")\n",
175
+ " lengths = [len(s) for s in seqs]\n",
176
+ " length = sum(lengths)\n",
177
+ " if verbose:\n",
178
+ " print(f\"Running prediction for job '{jobname}' with length {length}\")\n",
179
+ "\n",
180
+ " ID = jobname + \"_\" + get_hash(sequence)[:5]\n",
181
+ " prediction_dir = os.path.join(save_dir, ID)\n",
182
+ " os.makedirs(prediction_dir, exist_ok=True)\n",
183
+ "\n",
184
+ " # --- Model Configuration ---\n",
185
+ " # Optimized for Tesla T4\n",
186
+ " if length > 700:\n",
187
+ " model.trunk.set_chunk_size(64)\n",
188
+ " else:\n",
189
+ " model.trunk.set_chunk_size(128)\n",
190
+ "\n",
191
+ " if not next(model.parameters()).is_cuda:\n",
192
+ " print(\"Warning: Model is not on CUDA. Moving to CUDA.\")\n",
193
+ " model.cuda()\n",
194
+ " model.requires_grad_(False)\n",
195
+ "\n",
196
+ " # --- Prediction Loop ---\n",
197
+ " best_pdb_str = None\n",
198
+ " best_ptm = 0\n",
199
+ " best_output = None\n",
200
+ " traj = []\n",
201
+ "\n",
202
+ " num_samples = 1 if samples is None else samples\n",
203
+ "\n",
204
+ " for seed in range(num_samples):\n",
205
+ " torch.cuda.empty_cache()\n",
206
+ "\n",
207
+ " current_seed_str = \"default\"\n",
208
+ " mask_rate = 0.0\n",
209
+ " model.train(False) # Set to eval mode by default\n",
210
+ "\n",
211
+ " if samples is not None:\n",
212
+ " torch.manual_seed(seed)\n",
213
+ " current_seed_str = f\"seed{seed}\"\n",
214
+ " mask_rate = masking_rate if \"LM\" in stochastic_mode else 0.0\n",
215
+ " model.train(\"SM\" in stochastic_mode) # Set to train mode for dropout\n",
216
+ "\n",
217
+ " if verbose:\n",
218
+ " print(f\"Running sample {seed + 1}/{num_samples} (seed: {current_seed_str})...\")\n",
219
+ "\n",
220
+ " output = model.infer(\n",
221
+ " sequence,\n",
222
+ " num_recycles=num_recycles,\n",
223
+ " chain_linker=\"X\" * chain_linker,\n",
224
+ " residue_index_offset=512,\n",
225
+ " mask_rate=mask_rate,\n",
226
+ " return_contacts=get_LM_contacts\n",
227
+ " )\n",
228
+ "\n",
229
+ " pdb_str = model.output_to_pdb(output)[0]\n",
230
+ " output = tree_map(lambda x: x.cpu().numpy(), output)\n",
231
+ " ptm = output[\"ptm\"][0]\n",
232
+ " plddt = output[\"plddt\"][0, :, 1].mean()\n",
233
+ " traj.append(parse_output(output))\n",
234
+ "\n",
235
+ " if verbose:\n",
236
+ " print(f'Sample {seed} ptm: {ptm:.3f} plddt: {plddt:.1f}')\n",
237
+ "\n",
238
+ " if ptm > best_ptm:\n",
239
+ " best_pdb_str = pdb_str\n",
240
+ " best_ptm = ptm\n",
241
+ " best_output = output\n",
242
+ "\n",
243
+ " # --- Save PDB File ---\n",
244
+ " if samples is None:\n",
245
+ " pdb_filename = f\"ptm{ptm:.3f}_r{num_recycles}_{current_seed_str}.pdb\"\n",
246
+ " else:\n",
247
+ " pdb_filename = (\n",
248
+ " f\"ptm{ptm:.3f}_r{num_recycles}_{current_seed_str}_\"\n",
249
+ " f\"{stochastic_mode}_m{masking_rate:.2f}.pdb\"\n",
250
+ " )\n",
251
+ "\n",
252
+ " pdb_path = os.path.join(prediction_dir, pdb_filename)\n",
253
+ " with open(pdb_path, \"w\") as f:\n",
254
+ " f.write(pdb_str)\n",
255
+ " if verbose:\n",
256
+ " print(f\"Saved PDB to {pdb_path}\")\n",
257
+ "\n",
258
+ " if verbose:\n",
259
+ " print(f\"Prediction complete. Best ptm: {best_ptm:.3f}\")\n",
260
+ "\n",
261
+ " return {\n",
262
+ " \"output\": best_output,\n",
263
+ " \"pdb_str\": best_pdb_str,\n",
264
+ " \"ptm\": best_ptm,\n",
265
+ " \"traj\": traj,\n",
266
+ " \"dir\": prediction_dir,\n",
267
+ " \"lengths\":lengths\n",
268
+ " }\n"
269
+ ]
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "source": [
274
+ "#@title ##run **ESMFold**\n",
275
+ "jobname = \"test\" #@param {type:\"string\"}\n",
276
+ "sequence = \"GWSTELEKHREELKEFLKKEGITNVEIRIDNGRLEVRVEGGTERLKRFLEELRQKLEKKGYTVDIKIE\" #@param {type:\"string\"}\n",
277
+ "\n",
278
+ "#@markdown ---\n",
279
+ "#@markdown ###**Advanced Options**\n",
280
+ "num_recycles = 3 #@param [\"0\", \"1\", \"2\", \"3\", \"6\", \"12\"] {type:\"raw\"}\n",
281
+ "get_LM_contacts = False #@param {type:\"boolean\"}\n",
282
+ "\n",
283
+ "#@markdown **multimer options (experimental)**\n",
284
+ "#@markdown - use \"/\" to specify chainbreaks, (eg. sequence=\"AAA/AAA\")\n",
285
+ "#@markdown - for homo-oligomeric predictions, set copies > 1\n",
286
+ "\n",
287
+ "copies = 1 #@param {type:\"integer\"}\n",
288
+ "chain_linker = 25 #@param {type:\"number\"}\n",
289
+ "\n",
290
+ "#@markdown **sampling options (experimental)**\n",
291
+ "#@markdown - Samples are generated via random masking (defined by `masking_rate`)\n",
292
+ "#@markdown of input sequence (stochastic_mode=\"LM\") and/or via dropout within structure module (stochastic_mode=\"SM\").\n",
293
+ "samples = None #@param [\"None\", \"1\", \"4\", \"8\", \"16\", \"32\", \"64\"] {type:\"raw\"}\n",
294
+ "masking_rate = 0.15 #@param {type:\"number\"}\n",
295
+ "stochastic_mode = \"LM\" #@param [\"LM\", \"LM_SM\", \"SM\"]\n",
296
+ "\n",
297
+ "o = predict_esmfold(\n",
298
+ " model=model,\n",
299
+ " sequence=sequence,\n",
300
+ " jobname=jobname,\n",
301
+ " num_recycles=num_recycles,\n",
302
+ " get_LM_contacts=get_LM_contacts,\n",
303
+ " copies=copies,\n",
304
+ " chain_linker=chain_linker,\n",
305
+ " samples=samples,\n",
306
+ " masking_rate=masking_rate,\n",
307
+ " stochastic_mode=stochastic_mode)"
308
+ ],
309
+ "metadata": {
310
+ "cellView": "form",
311
+ "id": "UJ8ufvGNZfeQ"
312
+ },
313
+ "execution_count": null,
314
+ "outputs": []
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "execution_count": null,
319
+ "metadata": {
320
+ "cellView": "form",
321
+ "id": "tg7eFMC-TYRX"
322
+ },
323
+ "outputs": [],
324
+ "source": [
325
+ "#@title display (optional) {run: \"auto\"}\n",
326
+ "#@markdown Note: If samples selected, the model with max pTM is displayed.\n",
327
+ "import py3Dmol\n",
328
+ "\n",
329
+ "\n",
330
+ "pymol_color_list = [\"#33ff33\",\"#00ffff\",\"#ff33cc\",\"#ffff00\",\"#ff9999\",\"#e5e5e5\",\"#7f7fff\",\"#ff7f00\",\n",
331
+ " \"#7fff7f\",\"#199999\",\"#ff007f\",\"#ffdd5e\",\"#8c3f99\",\"#b2b2b2\",\"#007fff\",\"#c4b200\",\n",
332
+ " \"#8cb266\",\"#00bfbf\",\"#b27f7f\",\"#fcd1a5\",\"#ff7f7f\",\"#ffbfdd\",\"#7fffff\",\"#ffff7f\",\n",
333
+ " \"#00ff7f\",\"#337fcc\",\"#d8337f\",\"#bfff3f\",\"#ff7fff\",\"#d8d8ff\",\"#3fffbf\",\"#b78c4c\",\n",
334
+ " \"#339933\",\"#66b2b2\",\"#ba8c84\",\"#84bf00\",\"#b24c66\",\"#7f7f7f\",\"#3f3fa5\",\"#a5512b\"]\n",
335
+ "\n",
336
+ "def show_pdb(pdb_str, show_sidechains=False, show_mainchains=False,\n",
337
+ " color=\"pLDDT\", chains=None, vmin=50, vmax=90,\n",
338
+ " size=(800,480), hbondCutoff=4.0,\n",
339
+ " Ls=None,\n",
340
+ " animate=False):\n",
341
+ "\n",
342
+ " if chains is None:\n",
343
+ " chains = 1 if Ls is None else len(Ls)\n",
344
+ " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js', width=size[0], height=size[1])\n",
345
+ " if animate:\n",
346
+ " view.addModelsAsFrames(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
347
+ " else:\n",
348
+ " view.addModel(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
349
+ " if color == \"pLDDT\":\n",
350
+ " view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':vmin,'max':vmax}}})\n",
351
+ " elif color == \"rainbow\":\n",
352
+ " view.setStyle({'cartoon': {'color':'spectrum'}})\n",
353
+ " elif color == \"chain\":\n",
354
+ " for n,chain,color in zip(range(chains),alphabet_list,pymol_color_list):\n",
355
+ " view.setStyle({'chain':chain},{'cartoon': {'color':color}})\n",
356
+ " if show_sidechains:\n",
357
+ " BB = ['C','O','N']\n",
358
+ " view.addStyle({'and':[{'resn':[\"GLY\",\"PRO\"],'invert':True},{'atom':BB,'invert':True}]},\n",
359
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
360
+ " view.addStyle({'and':[{'resn':\"GLY\"},{'atom':'CA'}]},\n",
361
+ " {'sphere':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
362
+ " view.addStyle({'and':[{'resn':\"PRO\"},{'atom':['C','O'],'invert':True}]},\n",
363
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
364
+ " if show_mainchains:\n",
365
+ " BB = ['C','O','N','CA']\n",
366
+ " view.addStyle({'atom':BB},{'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
367
+ " view.zoomTo()\n",
368
+ " if animate: view.animate()\n",
369
+ " return view\n",
370
+ "\n",
371
+ "color = \"confidence\" #@param [\"confidence\", \"rainbow\", \"chain\"]\n",
372
+ "if color == \"confidence\": color = \"pLDDT\"\n",
373
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
374
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
375
+ "show_pdb(o[\"pdb_str\"], color=color,\n",
376
+ " show_sidechains=show_sidechains,\n",
377
+ " show_mainchains=show_mainchains,\n",
378
+ " Ls=o[\"lengths\"]).show()"
379
+ ]
380
+ },
381
+ {
382
+ "cell_type": "code",
383
+ "execution_count": null,
384
+ "metadata": {
385
+ "cellView": "form",
386
+ "id": "hkiKtX43voI-"
387
+ },
388
+ "outputs": [],
389
+ "source": [
390
+ "#@title plot confidence (optional)\n",
391
+ "#@markdown Note: If samples selected, the model with max pTM is displayed.\n",
392
+ "dpi = 100 #@param {type:\"integer\"}\n",
393
+ "\n",
394
+ "import matplotlib.pyplot as plt\n",
395
+ "def plot_ticks(Ls):\n",
396
+ " Ln = sum(Ls)\n",
397
+ " L_prev = 0\n",
398
+ " for L_i in Ls[:-1]:\n",
399
+ " L = L_prev + L_i\n",
400
+ " L_prev += L_i\n",
401
+ " plt.plot([0,Ln],[L,L],color=\"black\")\n",
402
+ " plt.plot([L,L],[0,Ln],color=\"black\")\n",
403
+ " ticks = np.cumsum([0]+Ls)\n",
404
+ " ticks = (ticks[1:] + ticks[:-1])/2\n",
405
+ " plt.yticks(ticks,alphabet_list[:len(ticks)])\n",
406
+ "\n",
407
+ "def plot_confidence(output, Ls=None, dpi=100):\n",
408
+ " O = parse_output(output)\n",
409
+ " if \"lm_contacts\" in O:\n",
410
+ " plt.figure(figsize=(20,4), dpi=dpi)\n",
411
+ " plt.subplot(1,4,1)\n",
412
+ " else:\n",
413
+ " plt.figure(figsize=(15,4), dpi=dpi)\n",
414
+ " plt.subplot(1,3,1)\n",
415
+ "\n",
416
+ " plt.title('Predicted lDDT')\n",
417
+ " plt.plot(O[\"plddt\"])\n",
418
+ " if Ls is not None:\n",
419
+ " L_prev = 0\n",
420
+ " for L_i in Ls[:-1]:\n",
421
+ " L = L_prev + L_i\n",
422
+ " L_prev += L_i\n",
423
+ " plt.plot([L,L],[0,100],color=\"black\")\n",
424
+ " plt.xlim(0,O[\"plddt\"].shape[0])\n",
425
+ " plt.ylim(0,100)\n",
426
+ " plt.ylabel('plDDT')\n",
427
+ " plt.xlabel('position')\n",
428
+ " plt.subplot(1,4 if \"lm_contacts\" in O else 3,2)\n",
429
+ "\n",
430
+ " plt.title('Predicted Aligned Error')\n",
431
+ " Ln = O[\"pae\"].shape[0]\n",
432
+ " plt.imshow(O[\"pae\"],cmap=\"bwr\",vmin=0,vmax=30,extent=(0, Ln, Ln, 0))\n",
433
+ " if Ls is not None and len(Ls) > 1: plot_ticks(Ls)\n",
434
+ " plt.colorbar()\n",
435
+ " plt.xlabel('Scored residue')\n",
436
+ " plt.ylabel('Aligned residue')\n",
437
+ "\n",
438
+ " if \"lm_contacts\" in O:\n",
439
+ " plt.subplot(1,4,3)\n",
440
+ " plt.title(\"contacts from LM\")\n",
441
+ " plt.imshow(O[\"lm_contacts\"],cmap=\"Greys\",vmin=0,vmax=1,extent=(0, Ln, Ln, 0))\n",
442
+ " if Ls is not None and len(Ls) > 1: plot_ticks(Ls)\n",
443
+ " plt.subplot(1,4,4)\n",
444
+ " else:\n",
445
+ " plt.subplot(1,3,3)\n",
446
+ " plt.title(\"contacts from Structure Module\")\n",
447
+ " plt.imshow(O[\"sm_contacts\"],cmap=\"Greys\",vmin=0,vmax=1,extent=(0, Ln, Ln, 0))\n",
448
+ " if Ls is not None and len(Ls) > 1: plot_ticks(Ls)\n",
449
+ " return plt\n",
450
+ "\n",
451
+ "plot_confidence(o[\"output\"], Ls=o[\"lengths\"], dpi=dpi)\n",
452
+ "plt.show()"
453
+ ]
454
+ },
455
+ {
456
+ "cell_type": "code",
457
+ "source": [
458
+ "#@title download predictions\n",
459
+ "from google.colab import files\n",
460
+ "os.system(f\"zip {o['dir']}.zip {o['dir']}/*\")\n",
461
+ "files.download(f\"{o['dir']}.zip\")"
462
+ ],
463
+ "metadata": {
464
+ "cellView": "form",
465
+ "id": "AVn1z6H9o7GT"
466
+ },
467
+ "execution_count": null,
468
+ "outputs": []
469
+ },
470
+ {
471
+ "cell_type": "code",
472
+ "source": [
473
+ "#@title animate outputs (optional)\n",
474
+ "#@markdown if more than one sample generated\n",
475
+ "import os\n",
476
+ "if not os.path.isdir(\"colabfold\"):\n",
477
+ " os.system(\"git clone https://github.com/sokrypton/ColabFold.git\")\n",
478
+ "import ColabFold.beta.colabfold as cf\n",
479
+ "\n",
480
+ "dpi = 100#@param {type:\"integer\"}\n",
481
+ "color_by_plddt = True #@param {type:\"boolean\"}\n",
482
+ "use_pca = True\n",
483
+ "cycle = True\n",
484
+ "\n",
485
+ "import matplotlib\n",
486
+ "from matplotlib import animation\n",
487
+ "from IPython.display import HTML\n",
488
+ "from sklearn.decomposition import PCA\n",
489
+ "\n",
490
+ "def mk_animation(xyz, labels, plddt, ref=0, Ls=None, line_w=2.0, dpi=100,color_by_plddt=False):\n",
491
+ "\n",
492
+ " def ca_align_to_last(positions, ref):\n",
493
+ " def align(P, Q):\n",
494
+ " if Ls is None or len(Ls) == 1:\n",
495
+ " P_,Q_ = P,Q\n",
496
+ " else:\n",
497
+ " # align relative to first chain\n",
498
+ " P_,Q_ = P[:Ls[0]],Q[:Ls[0]]\n",
499
+ " p = P_ - P_.mean(0,keepdims=True)\n",
500
+ " q = Q_ - Q_.mean(0,keepdims=True)\n",
501
+ " return ((P - P_.mean(0,keepdims=True)) @ cf.kabsch(p,q)) + Q_.mean(0,keepdims=True)\n",
502
+ "\n",
503
+ " pos = positions[ref] - positions[ref].mean(0,keepdims=True)\n",
504
+ " best_2D_view = pos @ cf.kabsch(pos,pos,return_v=True)\n",
505
+ "\n",
506
+ " new_positions = []\n",
507
+ " for i in range(len(positions)):\n",
508
+ " new_positions.append(align(positions[i],best_2D_view))\n",
509
+ " return np.asarray(new_positions)\n",
510
+ "\n",
511
+ " # align to reference\n",
512
+ " pos = ca_align_to_last(xyz, ref)\n",
513
+ "\n",
514
+ " fig, (ax1) = plt.subplots(1)\n",
515
+ " fig.set_figwidth(5)\n",
516
+ " fig.set_figheight(5)\n",
517
+ " fig.set_dpi(dpi)\n",
518
+ "\n",
519
+ " xy_min = pos[...,:2].min() - 1\n",
520
+ " xy_max = pos[...,:2].max() + 1\n",
521
+ "\n",
522
+ " for ax in [ax1]:\n",
523
+ " ax.set_xlim(xy_min, xy_max)\n",
524
+ " ax.set_ylim(xy_min, xy_max)\n",
525
+ " ax.axis(False)\n",
526
+ "\n",
527
+ " ims=[]\n",
528
+ " for l,pos_,plddt_ in zip(labels,pos,plddt):\n",
529
+ " if color_by_plddt:\n",
530
+ " img = cf.plot_pseudo_3D(pos_, c=plddt_, cmin=50, cmax=90, line_w=line_w, ax=ax1)\n",
531
+ " elif Ls is None or len(Ls) == 1:\n",
532
+ " img = cf.plot_pseudo_3D(pos_, ax=ax1, line_w=line_w)\n",
533
+ " else:\n",
534
+ " c = np.concatenate([[n]*L for n,L in enumerate(Ls)])\n",
535
+ " img = cf.plot_pseudo_3D(pos_, c=c, cmap=cf.pymol_cmap, cmin=0, cmax=39, line_w=line_w, ax=ax1)\n",
536
+ " ims.append([cf.add_text(f\"{l}\", ax1),img])\n",
537
+ "\n",
538
+ " ani = animation.ArtistAnimation(fig, ims, blit=True, interval=120)\n",
539
+ " plt.close()\n",
540
+ " return ani.to_html5_video()\n",
541
+ "\n",
542
+ "labels = np.array([f\"seed:{x}\" for x in range(len(o[\"traj\"]))])\n",
543
+ "pos = np.array([x[\"xyz\"] for x in o[\"traj\"]])\n",
544
+ "plddt = np.array([x[\"plddt\"] for x in o[\"traj\"]])\n",
545
+ "if use_pca and pos.shape[0] > 1:\n",
546
+ " pos_ca = pos\n",
547
+ " if o[\"lengths\"] is not None and len(o[\"lengths\"]) > 1:\n",
548
+ " pos_ca = pos_ca[:,:o[\"lengths\"][0]]\n",
549
+ " i,j = np.triu_indices(pos_ca.shape[1],k=1)\n",
550
+ " pos_ca_dm = np.sqrt(np.square(pos_ca[:,None,:,:] - pos_ca[:,:,None]).sum(-1))[:,i,j]\n",
551
+ " pc = PCA(1).fit_transform(pos_ca_dm)[:,0].argsort()\n",
552
+ " if cycle:\n",
553
+ " pc = np.append(pc,pc[1:-1][::-1])\n",
554
+ " pos = pos[pc]\n",
555
+ " labels = labels[pc]\n",
556
+ " plddt = plddt[pc]\n",
557
+ "HTML(mk_animation(pos, labels, plddt, Ls=o[\"lengths\"], dpi=dpi, color_by_plddt=color_by_plddt))"
558
+ ],
559
+ "metadata": {
560
+ "cellView": "form",
561
+ "id": "NY8H_iM5WFUu"
562
+ },
563
+ "execution_count": null,
564
+ "outputs": []
565
+ }
566
+ ],
567
+ "metadata": {
568
+ "accelerator": "GPU",
569
+ "colab": {
570
+ "provenance": [],
571
+ "include_colab_link": true
572
+ },
573
+ "gpuClass": "standard",
574
+ "kernelspec": {
575
+ "display_name": "Python 3",
576
+ "name": "python3"
577
+ },
578
+ "language_info": {
579
+ "name": "python"
580
+ }
581
+ },
582
+ "nbformat": 4,
583
+ "nbformat_minor": 0
584
+ }
data/beta/ESMFold_api.ipynb ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "authorship_tag": "ABX9TyOTvNvYm0TYMGMVWT4fM7rz",
8
+ "include_colab_link": true
9
+ },
10
+ "kernelspec": {
11
+ "name": "python3",
12
+ "display_name": "Python 3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ }
17
+ },
18
+ "cells": [
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {
22
+ "id": "view-in-github",
23
+ "colab_type": "text"
24
+ },
25
+ "source": [
26
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/ESMFold_api.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "markdown",
31
+ "source": [
32
+ "#**ESMFold API**\n",
33
+ "for more details see: [Github](https://github.com/facebookresearch/esm/tree/main/esm), [Preprint](https://www.biorxiv.org/content/10.1101/2022.07.20.500902v1)\n",
34
+ "\n",
35
+ "#### **Tips and Instructions**\n",
36
+ "- click the little ▶ play icon to the left of each cell below.\n",
37
+ "\n",
38
+ "#### **Limitations**\n",
39
+ "- max total length=400\n",
40
+ "- for lengths > 400, try our [colab notebook](https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/ESMFold.ipynb)\n",
41
+ "---"
42
+ ],
43
+ "metadata": {
44
+ "id": "v2jU2RLyacXQ"
45
+ }
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": null,
50
+ "metadata": {
51
+ "cellView": "form",
52
+ "id": "M8p9x4xCXCrw"
53
+ },
54
+ "outputs": [],
55
+ "source": [
56
+ "#@title run **ESMFold**\n",
57
+ "import os, time, re, requests\n",
58
+ "if not os.path.isfile(\"colabfold.py\"):\n",
59
+ " os.system(\"pip -q install pyppeteer nest_asyncio\")\n",
60
+ " import asyncio\n",
61
+ " import nest_asyncio\n",
62
+ " from pyppeteer import launch\n",
63
+ " import base64\n",
64
+ "\n",
65
+ " # Apply nest_asyncio to enable nested event loops\n",
66
+ " nest_asyncio.apply()\n",
67
+ "\n",
68
+ " async def fetch_blob_content(page, blob_url):\n",
69
+ " blob_to_base64 = \"\"\"\n",
70
+ " async (blobUrl) => {\n",
71
+ " const blob = await fetch(blobUrl).then(r => r.blob());\n",
72
+ " return new Promise((resolve) => {\n",
73
+ " const reader = new FileReader();\n",
74
+ " reader.onloadend = () => resolve(reader.result);\n",
75
+ " reader.readAsDataURL(blob);\n",
76
+ " });\n",
77
+ " }\n",
78
+ " \"\"\"\n",
79
+ " base64_data = await page.evaluate(blob_to_base64, blob_url)\n",
80
+ " _, encoded = base64_data.split(',', 1)\n",
81
+ " return base64.b64decode(encoded)\n",
82
+ "\n",
83
+ " async def extract_pdb_file_download_link_and_content(url):\n",
84
+ " browser = await launch(headless=True, args=['--no-sandbox', '--disable-setuid-sandbox'])\n",
85
+ " page = await browser.newPage()\n",
86
+ " await page.goto(url, {'waitUntil': 'networkidle0'})\n",
87
+ " elements = await page.querySelectorAll('a.btn.bg-purple')\n",
88
+ " for element in elements:\n",
89
+ " href = await page.evaluate('(element) => element.getAttribute(\"href\")', element)\n",
90
+ " if 'blob:https://esmatlas.com/' in href:\n",
91
+ " content = await fetch_blob_content(page, href)\n",
92
+ " await browser.close()\n",
93
+ " return href, content\n",
94
+ " await browser.close()\n",
95
+ " return \"No PDB file link found.\", None\n",
96
+ "\n",
97
+ " def esmfold_api(sequence):\n",
98
+ " url = f'https://esmatlas.com/resources/fold/result?fasta_header=%3Eunnamed&sequence={sequence}'\n",
99
+ " result = asyncio.get_event_loop().run_until_complete(extract_pdb_file_download_link_and_content(url))\n",
100
+ " if result[1]:\n",
101
+ " pdb_str = result[1].decode('utf-8')\n",
102
+ " return pdb_str\n",
103
+ " else:\n",
104
+ " return \"Failed to retrieve PDB content.\"\n",
105
+ "\n",
106
+ " os.system(\"pip -q install py3Dmol\")\n",
107
+ " os.system(\"wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/colabfold.py\")\n",
108
+ " os.system(\"mkdir -p tmp\")\n",
109
+ "\n",
110
+ "import colabfold as cf\n",
111
+ "\n",
112
+ "\n",
113
+ "sequence = \"GWSTELEKHREELKEFLKKEGITNVEIRIDNGRLEVRVEGGTERLKRFLEELRQKLEKKGYTVDIKIE\" #@param {type:\"string\"}\n",
114
+ "sequence = re.sub(\"[^A-Z]\", \"\", sequence.upper())\n",
115
+ "#assert len(sequence) <= 400, \"error: max length supported is 400\"\n",
116
+ "hash = cf.get_hash(sequence)[:5]\n",
117
+ "pdb_filename = f\"tmp/prediction_{hash}.pdb\"\n",
118
+ "if not os.path.isfile(pdb_filename):\n",
119
+ " pdb_str = esmfold_api(sequence)\n",
120
+ " with open(pdb_filename,\"w\") as out:\n",
121
+ " out.write(pdb_str)\n",
122
+ "\n",
123
+ "color = \"confidence\" #@param [\"confidence\", \"rainbow\"]\n",
124
+ "if color == \"confidence\": color = \"lDDT\"\n",
125
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
126
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
127
+ "v = cf.show_pdb(pdb_filename,\n",
128
+ " show_sidechains,\n",
129
+ " show_mainchains, color,\n",
130
+ " color_HP=True,\n",
131
+ " size=(800,480),\n",
132
+ " vmin=0.5, vmax=0.9)\n",
133
+ "v.setHoverable({}, True,\n",
134
+ " '''function(atom,viewer,event,container){if(!atom.label){atom.label=viewer.addLabel(\" \"+atom.resn+\":\"+atom.resi,{position:atom,backgroundColor:'mintcream',fontColor:'black'});}}''',\n",
135
+ " '''function(atom,viewer){if(atom.label){viewer.removeLabel(atom.label);delete atom.label;}}''')\n",
136
+ "v.show()\n",
137
+ "if color == \"lDDT\":\n",
138
+ " cf.plot_plddt_legend().show()"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "source": [
144
+ "#@title download prediction\n",
145
+ "from google.colab import files\n",
146
+ "files.download(pdb_filename)"
147
+ ],
148
+ "metadata": {
149
+ "cellView": "form",
150
+ "id": "fcR0YV4IaRpU"
151
+ },
152
+ "execution_count": null,
153
+ "outputs": []
154
+ }
155
+ ]
156
+ }
data/beta/RoseTTAFold.ipynb ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "RoseTTAFold.ipynb",
7
+ "provenance": [],
8
+ "include_colab_link": true
9
+ },
10
+ "kernelspec": {
11
+ "display_name": "Python 3",
12
+ "name": "python3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ },
17
+ "accelerator": "GPU"
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {
23
+ "id": "view-in-github",
24
+ "colab_type": "text"
25
+ },
26
+ "source": [
27
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/RoseTTAFold.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "markdown",
32
+ "metadata": {
33
+ "id": "74RP4ByMFXHR"
34
+ },
35
+ "source": [
36
+ "# RoseTTAFold w/ PyRosetta\n",
37
+ "\n",
38
+ "**Limitations**\n",
39
+ "- This notebook disables a few aspects (templates) of the full rosettafold pipeline.\n",
40
+ "- For best resuls use the [full pipeline](https://github.com/RosettaCommons/RoseTTAFold) or [Robetta webserver](https://robetta.bakerlab.org/)!\n",
41
+ "- For a typical Google-Colab session, with a `16G-GPU`, the max total length is **700 residues**. Sometimes a `12G-GPU` is assigned, in which case the max length is lower.\n",
42
+ "\n",
43
+ "For other related notebooks see [ColabFold](https://github.com/sokrypton/ColabFold)"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "metadata": {
49
+ "id": "8v06TAo9ZaGH",
50
+ "cellView": "form"
51
+ },
52
+ "source": [
53
+ "#@title ##Install and import libraries\n",
54
+ "if \"PAPERMILL_INPUT_PATH\" not in dir():\n",
55
+ " #@markdown This step will take 2+ mins (6min PyRosetta, 2min RoseTTAFold)\n",
56
+ " use_pyrosetta = False #@param {type:\"boolean\"}\n",
57
+ " #@markdown - Use PyRosetta for structure prediction. To do so you'll need to get a [PyRosetta License](https://els2.comotion.uw.edu/product/pyrosetta) (free for academic use).\n",
58
+ " #@markdown Once you obtain license, enter the username and password below.\n",
59
+ " username = '' #@param {type:\"string\"}\n",
60
+ " username.strip().lower()\n",
61
+ " password = '' #@param {type:\"string\"}\n",
62
+ "\n",
63
+ "import os\n",
64
+ "import subprocess\n",
65
+ "import hashlib\n",
66
+ "\n",
67
+ "import sys\n",
68
+ "from IPython.utils import io\n",
69
+ "try:\n",
70
+ " from google.colab import files\n",
71
+ "except:\n",
72
+ " from IPython.core.magic import register_line_magic\n",
73
+ " @register_line_magic\n",
74
+ " def tensorflow_version(line):\n",
75
+ " pass\n",
76
+ " pass\n",
77
+ "\n",
78
+ "if use_pyrosetta:\n",
79
+ " # Thanks Matteo Ferla for password check\n",
80
+ " hashed_username = hashlib.sha256(username.encode()).hexdigest()\n",
81
+ " hashed_password = hashlib.sha256(password.encode()).hexdigest()\n",
82
+ " expected_hashed_username = 'cf6f296b8145262b22721e52e2edec13ce57af8c6fc990c8ae1a4aa3e50ae40e'\n",
83
+ " expected_hashed_password = '45066dd976d8bf0c05dc8dd4d58727945c3437e6eb361ba9870097968db7a0da'\n",
84
+ " msg = 'Error: username or password is incorrect.'\n",
85
+ " assert hashed_username == expected_hashed_username, msg\n",
86
+ " assert hashed_password == expected_hashed_password, msg\n",
87
+ "\n",
88
+ " dist = subprocess.check_output(['lsb_release', '-is']).strip()\n",
89
+ " if dist == \"Ubuntu\":\n",
90
+ " dist = \"ubuntu\"\n",
91
+ " else:\n",
92
+ " dist = \"linux\"\n",
93
+ " pyrosetta_path = f\"PyRosetta4.Release.python37.{dist}.release-306\"\n",
94
+ " if not os.path.isdir(pyrosetta_path):\n",
95
+ " print(\"installing pyRosetta - 6 mins\")\n",
96
+ " with io.capture_output() as captured:\n",
97
+ " !wget --show-progress --user {username} --password {password} https://graylab.jhu.edu/download/PyRosetta4/archive/release/PyRosetta4.Release.python37.{dist}/{pyrosetta_path}.tar.bz2 -O - | tar -xj\n",
98
+ " !pip install -e {pyrosetta_path}/setup/\n",
99
+ "\n",
100
+ "if not os.path.isdir(\"RoseTTAFold\"):\n",
101
+ " print(\"installing RoseTTAFold - 2 mins\")\n",
102
+ " with io.capture_output() as captured:\n",
103
+ " # extra functionality\n",
104
+ " !wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/colabfold.py\n",
105
+ "\n",
106
+ " # download model\n",
107
+ " !git clone https://github.com/RosettaCommons/RoseTTAFold.git\n",
108
+ " !wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/beta/RoseTTAFold__network__Refine_module.patch\n",
109
+ " !patch -u RoseTTAFold/network/Refine_module.py -i RoseTTAFold__network__Refine_module.patch\n",
110
+ "\n",
111
+ " # download model params\n",
112
+ " !wget -qnc https://files.ipd.uw.edu/pub/RoseTTAFold/weights.tar.gz\n",
113
+ " !tar -xf weights.tar.gz\n",
114
+ " !rm weights.tar.gz\n",
115
+ "\n",
116
+ " # download scwrl4 (for adding sidechains)\n",
117
+ " # http://dunbrack.fccc.edu/SCWRL3.php\n",
118
+ " # Thanks Roland Dunbrack!\n",
119
+ " !wget -qnc https://files.ipd.uw.edu/krypton/TrRosetta/scwrl4.zip\n",
120
+ " !unzip -qqo scwrl4.zip\n",
121
+ "\n",
122
+ " # install libraries\n",
123
+ " !pip install -q dgl-cu113 -f https://data.dgl.ai/wheels/repo.html\n",
124
+ " !pip install -q torch-scatter -f https://pytorch-geometric.com/whl/torch-1.11.0+cu113.html\n",
125
+ " !pip install -q torch-sparse -f https://pytorch-geometric.com/whl/torch-1.11.0+cu113.html\n",
126
+ " !pip install -q torch-geometric\n",
127
+ " !pip install -q py3Dmol\n",
128
+ "\n",
129
+ " !wget https://openstructure.org/static/lddt-linux.zip -O lddt.zip\n",
130
+ " !unzip -d ./RoseTTAFold/lddt -j lddt.zip\n",
131
+ "\n",
132
+ "with io.capture_output() as captured:\n",
133
+ " sys.path.append('./RoseTTAFold/network')\n",
134
+ " import predict_e2e, predict_pyRosetta\n",
135
+ " from parsers import parse_a3m\n",
136
+ " \n",
137
+ "import colabfold as cf\n",
138
+ "import py3Dmol\n",
139
+ "import numpy as np\n",
140
+ "import matplotlib.pyplot as plt\n",
141
+ "\n",
142
+ "def get_bfactor(pdb_filename):\n",
143
+ " bfac = []\n",
144
+ " for line in open(pdb_filename,\"r\"):\n",
145
+ " if line[:4] == \"ATOM\":\n",
146
+ " bfac.append(float(line[60:66]))\n",
147
+ " return np.array(bfac)\n",
148
+ "\n",
149
+ "def set_bfactor(pdb_filename, bfac):\n",
150
+ " I = open(pdb_filename,\"r\").readlines()\n",
151
+ " O = open(pdb_filename,\"w\")\n",
152
+ " for line in I:\n",
153
+ " if line[0:6] == \"ATOM \":\n",
154
+ " seq_id = int(line[22:26].strip()) - 1\n",
155
+ " O.write(f\"{line[:60]}{bfac[seq_id]:6.2f}{line[66:]}\")\n",
156
+ " O.close() \n",
157
+ "\n",
158
+ "def do_scwrl(inputs, outputs, exe=\"./scwrl4/Scwrl4\"):\n",
159
+ " subprocess.run([exe,\"-i\",inputs,\"-o\",outputs,\"-h\"],\n",
160
+ " stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n",
161
+ " bfact = get_bfactor(inputs)\n",
162
+ " set_bfactor(outputs, bfact)\n",
163
+ " return bfact"
164
+ ],
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "metadata": {
171
+ "id": "YWe2OSU59iKD",
172
+ "cellView": "form"
173
+ },
174
+ "source": [
175
+ "#@markdown ##Input Sequence\n",
176
+ "if \"PAPERMILL_INPUT_PATH\" not in dir():\n",
177
+ " sequence = \"PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK\" #@param {type:\"string\"}\n",
178
+ " jobname = \"test\" #@param {type:\"string\"}\n",
179
+ "\n",
180
+ "sequence = sequence.translate(str.maketrans('', '', ' \\n\\t')).upper()\n",
181
+ "jobname = jobname+\"_\"+cf.get_hash(sequence)[:5]"
182
+ ],
183
+ "execution_count": null,
184
+ "outputs": []
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "metadata": {
189
+ "id": "_nTsyKtQxjO8",
190
+ "cellView": "form"
191
+ },
192
+ "source": [
193
+ "#@title Search against genetic databases\n",
194
+ "if \"PAPERMILL_INPUT_PATH\" not in dir():\n",
195
+ " #@markdown ---\n",
196
+ " msa_method = \"mmseqs2\" #@param [\"mmseqs2\",\"single_sequence\",\"custom_a3m\"]\n",
197
+ " #@markdown - `mmseqs2` - FAST method from [ColabFold](https://github.com/sokrypton/ColabFold)\n",
198
+ " #@markdown - `single_sequence` - use single sequence input (not recommended, unless a *denovo* design and you dont expect to find any homologous sequences)\n",
199
+ " #@markdown - `custom_a3m` Upload custom MSA (a3m format)\n",
200
+ "\n",
201
+ "# tmp directory\n",
202
+ "prefix = cf.get_hash(sequence)\n",
203
+ "os.makedirs('tmp', exist_ok=True)\n",
204
+ "prefix = os.path.join('tmp',prefix)\n",
205
+ "\n",
206
+ "os.makedirs(jobname, exist_ok=True)\n",
207
+ "\n",
208
+ "\n",
209
+ "if msa_method == \"mmseqs2\":\n",
210
+ " if \"PAPERMILL_INPUT_PATH\" not in dir():\n",
211
+ " host_url=\"https://a3m.mmseqs.com\"\n",
212
+ " a3m_lines = cf.run_mmseqs2(sequence, prefix, filter=True, host_url=host_url)\n",
213
+ " with open(f\"{jobname}/msa.a3m\",\"w\") as a3m:\n",
214
+ " a3m.write(a3m_lines)\n",
215
+ "\n",
216
+ "elif msa_method == \"single_sequence\":\n",
217
+ " with open(f\"{jobname}/msa.a3m\",\"w\") as a3m:\n",
218
+ " a3m.write(f\">{jobname}\\n{sequence}\\n\")\n",
219
+ "\n",
220
+ "elif msa_method == \"custom_a3m\":\n",
221
+ " if \"PAPERMILL_INPUT_PATH\" not in dir():\n",
222
+ " print(\"upload custom a3m\")\n",
223
+ " msa_dict = files.upload()\n",
224
+ " lines = msa_dict[list(msa_dict.keys())[0]].decode().splitlines()\n",
225
+ " a3m_lines = []\n",
226
+ " for line in lines:\n",
227
+ " line = line.replace(\"\\x00\",\"\")\n",
228
+ " if len(line) > 0 and not line.startswith('#'):\n",
229
+ " a3m_lines.append(line)\n",
230
+ " with open(f\"{jobname}/msa.a3m\",\"w\") as a3m:\n",
231
+ " a3m.write(\"\\n\".join(a3m_lines))\n",
232
+ " else:\n",
233
+ " import shutil\n",
234
+ " shutil.copy(a3m_file, f\"{jobname}/msa.a3m\")\n",
235
+ "\n",
236
+ "msa_all = parse_a3m(f\"{jobname}/msa.a3m\")\n",
237
+ "msa_arr = np.unique(msa_all,axis=0)\n",
238
+ "total_msa_size = len(msa_arr)\n",
239
+ "if msa_method == \"mmseqs2\":\n",
240
+ " print(f'\\n{total_msa_size} Sequences Found in Total (after filtering)\\n')\n",
241
+ "else:\n",
242
+ " print(f'\\n{total_msa_size} Sequences Found in Total\\n')\n",
243
+ "\n",
244
+ "if total_msa_size > 1:\n",
245
+ " plt.figure(figsize=(8,5),dpi=100)\n",
246
+ " plt.title(\"Sequence coverage\")\n",
247
+ " seqid = (msa_all[0] == msa_arr).mean(-1)\n",
248
+ " seqid_sort = seqid.argsort()\n",
249
+ " non_gaps = (msa_arr != 20).astype(float)\n",
250
+ " non_gaps[non_gaps == 0] = np.nan\n",
251
+ " plt.imshow(non_gaps[seqid_sort]*seqid[seqid_sort,None],\n",
252
+ " interpolation='nearest', aspect='auto',\n",
253
+ " cmap=\"rainbow_r\", vmin=0, vmax=1, origin='lower',\n",
254
+ " extent=(0, msa_arr.shape[1], 0, msa_arr.shape[0]))\n",
255
+ " plt.plot((msa_arr != 20).sum(0), color='black')\n",
256
+ " plt.xlim(0,msa_arr.shape[1])\n",
257
+ " plt.ylim(0,msa_arr.shape[0])\n",
258
+ " plt.colorbar(label=\"Sequence identity to query\",)\n",
259
+ " plt.xlabel(\"Positions\")\n",
260
+ " plt.ylabel(\"Sequences\")\n",
261
+ " plt.savefig(f\"{jobname}/msa_coverage.png\", bbox_inches = 'tight')\n",
262
+ " plt.show()"
263
+ ],
264
+ "execution_count": null,
265
+ "outputs": []
266
+ },
267
+ {
268
+ "cell_type": "code",
269
+ "metadata": {
270
+ "id": "14-q4hv59ast",
271
+ "cellView": "form"
272
+ },
273
+ "source": [
274
+ "%tensorflow_version 1.x\n",
275
+ "#@title ## Run RoseTTAFold\n",
276
+ "# load model\n",
277
+ "if \"rosettafold\" not in dir():\n",
278
+ " if use_pyrosetta:\n",
279
+ " rosettafold = predict_pyRosetta.Predictor(model_dir=\"weights\")\n",
280
+ " else:\n",
281
+ " rosettafold = predict_e2e.Predictor(model_dir=\"weights\")\n",
282
+ "\n",
283
+ "# make prediction using model\n",
284
+ "if use_pyrosetta:\n",
285
+ " if not os.path.isfile(f\"{jobname}/pred.npz\"):\n",
286
+ " print(\"running RoseTTAFold\")\n",
287
+ " rosettafold.predict(f\"{jobname}/msa.a3m\",f\"{jobname}/pred\")\n",
288
+ "else:\n",
289
+ " if not os.path.isfile(f\"{jobname}/pred.pdb\"):\n",
290
+ " print(\"running RoseTTAFold\")\n",
291
+ " rosettafold.predict(f\"{jobname}/msa.a3m\",f\"{jobname}/pred\")\n",
292
+ "\n",
293
+ "if not os.path.isfile(f\"{jobname}/pred.fasta\"):\n",
294
+ " with open(f\"{jobname}/pred.fasta\",\"w\") as out:\n",
295
+ " out.write(f\">pred\\n{sequence}\\n\")\n",
296
+ "\n",
297
+ "if use_pyrosetta:\n",
298
+ " CPU = max(1, len(os.sched_getaffinity(0)))\n",
299
+ " pyrosetta_script = \"./RoseTTAFold/folding/RosettaTR.py\"\n",
300
+ " if not os.path.isfile(f\"{jobname}/model/model_1.crderr.pdb\"):\n",
301
+ " print(\"running PyRosetta\")\n",
302
+ " with open(f\"{jobname}/job_list\",\"w\") as job_list:\n",
303
+ " for m in [0,1,2]:\n",
304
+ " for p in [0.05,0.15,0.25,0.35,0.45]:\n",
305
+ " pdb_out = f\"{jobname}/model_{m}_{p}.pdb\"\n",
306
+ " opt = f\"--roll -r 3 -pd {p} -m {m} -sg 7,3\"\n",
307
+ " if not os.path.isfile(pdb_out):\n",
308
+ " job_list.write(f\"python -u {pyrosetta_script} {opt} {jobname}/pred.npz {jobname}/pred.fasta {pdb_out}\\n\")\n",
309
+ " os.system(f\"cat {jobname}/job_list | tr '\\\\n' '\\\\0' | xargs -0 -L 1 -P {CPU} -I % sh -c '%'\")\n",
310
+ " \n",
311
+ " print(\"ranking models using DAN\")\n",
312
+ " dan_script = \"./RoseTTAFold/DAN-msa/ErrorPredictorMSA.py\"\n",
313
+ " dan_pick_script = \"./RoseTTAFold/DAN-msa/pick_final_models.div.py\"\n",
314
+ " os.system(f\"python {dan_script} --roll -p {CPU} {jobname}/pred.npz {jobname} {jobname}\")\n",
315
+ " os.system(f\"python {dan_pick_script} {jobname} {jobname}/model {CPU}\")\n",
316
+ " \n",
317
+ " plddt = get_bfactor(f\"{jobname}/model/model_1.crderr.pdb\")\n",
318
+ " \n",
319
+ "else:\n",
320
+ " # pack sidechains using Scwrl4\n",
321
+ " plddt = do_scwrl(f\"{jobname}/pred.pdb\",f\"{jobname}/pred.scwrl.pdb\")\n",
322
+ "\n",
323
+ "print(f\"Predicted LDDT: {plddt.mean()}\")\n",
324
+ "plt.figure(figsize=(8,5),dpi=100)\n",
325
+ "plt.plot(plddt)\n",
326
+ "plt.xlabel(\"positions\")\n",
327
+ "plt.ylabel(\"plddt\")\n",
328
+ "plt.ylim(0,1)\n",
329
+ "plt.savefig(f\"{jobname}/plddt.png\", bbox_inches = 'tight')\n",
330
+ "plt.show()"
331
+ ],
332
+ "execution_count": null,
333
+ "outputs": []
334
+ },
335
+ {
336
+ "cell_type": "code",
337
+ "metadata": {
338
+ "id": "qPhmF8SZr1k8",
339
+ "cellView": "form"
340
+ },
341
+ "source": [
342
+ "#@title Display 3D structure {run: \"auto\"}\n",
343
+ "color = \"lDDT\" #@param [\"chain\", \"lDDT\", \"rainbow\"]\n",
344
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
345
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
346
+ "if use_pyrosetta:\n",
347
+ " cf.show_pdb(f\"{jobname}/model/model_1.crderr.pdb\", show_sidechains, show_mainchains, color, chains=1, vmin=0.5, vmax=0.9).show()\n",
348
+ "else:\n",
349
+ " cf.show_pdb(f\"{jobname}/pred.scwrl.pdb\", show_sidechains, show_mainchains, color, chains=1, vmin=0.5, vmax=0.9).show()\n",
350
+ "\n",
351
+ "if color == \"lDDT\": cf.plot_plddt_legend().show() "
352
+ ],
353
+ "execution_count": null,
354
+ "outputs": []
355
+ },
356
+ {
357
+ "cell_type": "code",
358
+ "metadata": {
359
+ "id": "j0RhMLHKHf8d",
360
+ "cellView": "form"
361
+ },
362
+ "source": [
363
+ "#@title Download prediction\n",
364
+ "\n",
365
+ "#@markdown Once this cell has been executed, a zip-archive with \n",
366
+ "#@markdown the obtained prediction will be automatically downloaded \n",
367
+ "#@markdown to your computer.\n",
368
+ "\n",
369
+ "# add settings file\n",
370
+ "settings_path = f\"{jobname}/settings.txt\"\n",
371
+ "with open(settings_path, \"w\") as text_file:\n",
372
+ " text_file.write(f\"method=RoseTTAFold\\n\")\n",
373
+ " text_file.write(f\"sequence={sequence}\\n\")\n",
374
+ " text_file.write(f\"msa_method={msa_method}\\n\")\n",
375
+ " text_file.write(f\"use_templates=False\\n\")\n",
376
+ "\n",
377
+ "# --- Download the predictions ---\n",
378
+ "!zip -q -r {jobname}.zip {jobname}\n",
379
+ "try:\n",
380
+ " files.download(f'{jobname}.zip')\n",
381
+ "except:\n",
382
+ " pass\n"
383
+ ],
384
+ "execution_count": null,
385
+ "outputs": []
386
+ }
387
+ ]
388
+ }
data/beta/RoseTTAFold__network__Refine_module.patch ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- Refine_module_old.py 2021-08-04 07:49:26.000000000 -0400
2
+ +++ Refine_module.py 2021-08-04 07:46:27.000000000 -0400
3
+ @@ -129,47 +129,61 @@
4
+ self.norm_state = LayerNorm(SE3_param['l0_out_features'])
5
+ self.pred_lddt = nn.Linear(SE3_param['l0_out_features'], 1)
6
+
7
+ - def forward(self, node, edge, seq1hot, idx, use_transf_checkpoint=False, eps=1e-4):
8
+ + def forward(self, node, edge, seq1hot, idx, use_transf_checkpoint=False, eps=1e-4,
9
+ + mirror_mode="serial"):
10
+ +
11
+ + def run(xyz, state, node, edge, idx, seq1hot):
12
+ + best_xyz = xyz
13
+ + best_lddt = torch.zeros((xyz.shape[0], xyz.shape[1], 1), device=xyz.device)
14
+ + prev_lddt = 0.0
15
+ + no_impr = 0
16
+ + no_impr_best = 0
17
+ + for i_iter in range(200):
18
+ + for i_m in range(self.n_module):
19
+ + if use_transf_checkpoint:
20
+ + xyz, state = checkpoint.checkpoint(create_custom_forward(self.refine_net[i_m], top_k=64), node.float(), edge.float(), xyz.detach().float(), state.float(), seq1hot, idx)
21
+ + else:
22
+ + xyz, state = self.refine_net[i_m](node.float(), edge.float(), xyz.detach().float(), state.float(), seq1hot, idx, top_k=64)
23
+ + #
24
+ + lddt = self.pred_lddt(self.norm_state(state))
25
+ + lddt = torch.clamp(lddt, 0.0, 1.0)[...,0]
26
+ + print (f"SE(3) iteration {i_iter} {lddt.mean(-1).cpu().numpy()}")
27
+ + if lddt.mean(-1).max() <= prev_lddt+eps:
28
+ + no_impr += 1
29
+ + else:
30
+ + no_impr = 0
31
+ + if lddt.mean(-1).max() <= best_lddt.mean(-1).max()+eps:
32
+ + no_impr_best += 1
33
+ + else:
34
+ + no_impr_best = 0
35
+ + if no_impr > 10 or no_impr_best > 20:
36
+ + break
37
+ + if lddt.mean(-1).max() > best_lddt.mean(-1).max():
38
+ + best_lddt = lddt
39
+ + best_xyz = xyz
40
+ + prev_lddt = lddt.mean(-1).max()
41
+ +
42
+ + return best_xyz, best_lddt
43
+ +
44
+ edge = self.proj_edge(edge)
45
+ -
46
+ xyz, state = self.regen_net(seq1hot, idx, node, edge)
47
+ -
48
+ - # DOUBLE IT w/ Mirror images
49
+ - xyz = torch.cat([xyz, xyz*torch.tensor([1,1,-1], dtype=xyz.dtype, device=xyz.device)])
50
+ - state = torch.cat([state, state])
51
+ - node = torch.cat([node, node])
52
+ - edge = torch.cat([edge, edge])
53
+ - idx = torch.cat([idx, idx])
54
+ - seq1hot = torch.cat([seq1hot, seq1hot])
55
+
56
+ - best_xyz = xyz
57
+ - best_lddt = torch.zeros((xyz.shape[0], xyz.shape[1], 1), device=xyz.device)
58
+ - prev_lddt = 0.0
59
+ - no_impr = 0
60
+ - no_impr_best = 0
61
+ - for i_iter in range(200):
62
+ - for i_m in range(self.n_module):
63
+ - if use_transf_checkpoint:
64
+ - xyz, state = checkpoint.checkpoint(create_custom_forward(self.refine_net[i_m], top_k=64), node.float(), edge.float(), xyz.detach().float(), state.float(), seq1hot, idx)
65
+ - else:
66
+ - xyz, state = self.refine_net[i_m](node.float(), edge.float(), xyz.detach().float(), state.float(), seq1hot, idx, top_k=64)
67
+ - #
68
+ - lddt = self.pred_lddt(self.norm_state(state))
69
+ - lddt = torch.clamp(lddt, 0.0, 1.0)[...,0]
70
+ - print (f"SE(3) iteration {i_iter} {lddt.mean(-1).cpu().numpy()}")
71
+ - if lddt.mean(-1).max() <= prev_lddt+eps:
72
+ - no_impr += 1
73
+ - else:
74
+ - no_impr = 0
75
+ - if lddt.mean(-1).max() <= best_lddt.mean(-1).max()+eps:
76
+ - no_impr_best += 1
77
+ - else:
78
+ - no_impr_best = 0
79
+ - if no_impr > 10 or no_impr_best > 20:
80
+ - break
81
+ - if lddt.mean(-1).max() > best_lddt.mean(-1).max():
82
+ - best_lddt = lddt
83
+ - best_xyz = xyz
84
+ - prev_lddt = lddt.mean(-1).max()
85
+ - pick = best_lddt.mean(-1).argmax()
86
+ - return best_xyz[pick][None], best_lddt[pick][None]
87
+ + # DOUBLE IT w/ Mirror images
88
+ + if mirror_mode == "parallel":
89
+ + xyz = torch.cat([xyz, xyz*torch.tensor([1,1,-1], dtype=xyz.dtype, device=xyz.device)])
90
+ + state = torch.cat([state, state])
91
+ + node = torch.cat([node, node])
92
+ + edge = torch.cat([edge, edge])
93
+ + idx = torch.cat([idx, idx])
94
+ + seq1hot = torch.cat([seq1hot, seq1hot])
95
+ + best_xyz, best_lddt = run(xyz, state, node, edge, idx, seq1hot)
96
+ + pick = best_lddt.mean(-1).argmax()
97
+ + return best_xyz[pick][None], best_lddt[pick][None]
98
+ + else:
99
+ + best_xyz_A, best_lddt_A = run(xyz, state, node, edge, idx, seq1hot)
100
+ + xyz = xyz * torch.tensor([1,1,-1], dtype=xyz.dtype, device=xyz.device)
101
+ + best_xyz_B, best_lddt_B = run(xyz, state, node, edge, idx, seq1hot)
102
+ + if best_lddt_B.mean() > best_lddt_A.mean():
103
+ + return best_xyz_B, best_lddt_B
104
+ + else:
105
+ + return best_xyz_A, best_lddt_A
106
+
data/beta/RoseTTAFold_install.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/bin/sh -e
2
+ conda create -n rosettafold -c conda-forge cudnn cudatoolkit==11.3.1 cudatoolkit-dev==11.3.1 python==3.7
3
+ conda activate rosettafold
4
+ pip install jupyter papermill matplotlib tensorflow-gpu==1.15
5
+ pip install torch==1.10.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html
data/beta/RoseTTAFold_run.sh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -e
3
+ SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
4
+ INPUT="$(readlink -f "$1")"
5
+ shift
6
+ OUTPUT="$(readlink -f "$2")"
7
+ shift
8
+ USERNAME="$3"
9
+ shift
10
+ PASSWORD="$4"
11
+ shift
12
+ unset CONDA_SHLVL
13
+ eval "$(conda shell.bash hook)"
14
+ conda activate rosettafold
15
+ mkdir -p ${OUTPUT}
16
+ HEADER="$(cat "$INPUT" | awk 'NR == 1 { print substr($1, 2); exit; }')"
17
+ SEQUENCE="$(cat "$INPUT" | awk 'NR == 2 { print $1; exit; }')"
18
+ if [ "${INPUT##*.}" = "a3m" ]; then
19
+ A3M_FILE="$INPUT"
20
+ MSA_METHOD=custom_a3m
21
+ else
22
+ A3M_FILE=""
23
+ MSA_METHOD=mmseqs2
24
+ fi
25
+ PYROSETTA=True
26
+ /usr/bin/time -v papermill "${SCRIPT_DIR}/RoseTTAFold.ipynb" "${OUTPUT}.ipynb" --inject-input-path -p use_pyrosetta "${PYROSETTA}" -p username "${USERNAME}" -p password "${PASSWORD}" -p jobname "$HEADER" -p sequence "$SEQUENCE" -p a3m_file "${A3M_FILE}" -p msa_method "${MSA_METHOD}" -p host_url "https://a3m.mmseqs.com" "$@" 2>&1 | tee "${OUTPUT}.log"
data/beta/alphafold_output_at_each_recycle.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
data/beta/colabfold.py ADDED
@@ -0,0 +1,711 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+
3
+ ############################################
4
+ # imports
5
+ ############################################
6
+ import jax
7
+ import requests
8
+ import hashlib
9
+ import tarfile
10
+ import time
11
+ import pickle
12
+ import os
13
+ import re
14
+
15
+ import random
16
+ import tqdm.notebook
17
+
18
+ import numpy as np
19
+ import matplotlib.pyplot as plt
20
+ import matplotlib
21
+ import matplotlib.patheffects
22
+ from matplotlib import collections as mcoll
23
+
24
+ try:
25
+ import py3Dmol
26
+ except:
27
+ pass
28
+
29
+ from string import ascii_uppercase,ascii_lowercase
30
+
31
+ pymol_color_list = ["#33ff33","#00ffff","#ff33cc","#ffff00","#ff9999","#e5e5e5","#7f7fff","#ff7f00",
32
+ "#7fff7f","#199999","#ff007f","#ffdd5e","#8c3f99","#b2b2b2","#007fff","#c4b200",
33
+ "#8cb266","#00bfbf","#b27f7f","#fcd1a5","#ff7f7f","#ffbfdd","#7fffff","#ffff7f",
34
+ "#00ff7f","#337fcc","#d8337f","#bfff3f","#ff7fff","#d8d8ff","#3fffbf","#b78c4c",
35
+ "#339933","#66b2b2","#ba8c84","#84bf00","#b24c66","#7f7f7f","#3f3fa5","#a5512b"]
36
+
37
+ pymol_cmap = matplotlib.colors.ListedColormap(pymol_color_list)
38
+ alphabet_list = list(ascii_uppercase+ascii_lowercase)
39
+
40
+ aatypes = set('ACDEFGHIKLMNPQRSTVWY')
41
+
42
+
43
+ ###########################################
44
+ # control gpu/cpu memory usage
45
+ ###########################################
46
+ def rm(x):
47
+ '''remove data from device'''
48
+ jax.tree_util.tree_map(lambda y: y.device_buffer.delete(), x)
49
+
50
+ def to(x,device="cpu"):
51
+ '''move data to device'''
52
+ d = jax.devices(device)[0]
53
+ return jax.tree_util.tree_map(lambda y:jax.device_put(y,d), x)
54
+
55
+ def clear_mem(device="gpu"):
56
+ '''remove all data from device'''
57
+ backend = jax.lib.xla_bridge.get_backend(device)
58
+ for buf in backend.live_buffers(): buf.delete()
59
+
60
+ ##########################################
61
+ # call mmseqs2
62
+ ##########################################
63
+
64
+ TQDM_BAR_FORMAT = '{l_bar}{bar}| {n_fmt}/{total_fmt} [elapsed: {elapsed} remaining: {remaining}]'
65
+
66
+ def run_mmseqs2(x, prefix, use_env=True, use_filter=True,
67
+ use_templates=False, filter=None, host_url="https://a3m.mmseqs.com"):
68
+
69
+ def submit(seqs, mode, N=101):
70
+ n,query = N,""
71
+ for seq in seqs:
72
+ query += f">{n}\n{seq}\n"
73
+ n += 1
74
+
75
+ while True:
76
+ try:
77
+ # https://requests.readthedocs.io/en/latest/user/advanced/#advanced
78
+ # "good practice to set connect timeouts to slightly larger than a multiple of 3"
79
+ res = requests.post(f'{host_url}/ticket/msa', data={'q':query,'mode': mode}, timeout=6.02)
80
+ except requests.exceptions.Timeout:
81
+ continue
82
+ break
83
+
84
+ try: out = res.json()
85
+ except ValueError: out = {"status":"UNKNOWN"}
86
+ return out
87
+
88
+ def status(ID):
89
+ while True:
90
+ try:
91
+ res = requests.get(f'{host_url}/ticket/{ID}', timeout=6.02)
92
+ except requests.exceptions.Timeout:
93
+ continue
94
+ break
95
+
96
+ try: out = res.json()
97
+ except ValueError: out = {"status":"UNKNOWN"}
98
+ return out
99
+
100
+ def download(ID, path):
101
+ while True:
102
+ try:
103
+ res = requests.get(f'{host_url}/result/download/{ID}', timeout=6.02)
104
+ except requests.exceptions.Timeout:
105
+ continue
106
+ break
107
+
108
+ with open(path,"wb") as out: out.write(res.content)
109
+
110
+ # process input x
111
+ seqs = [x] if isinstance(x, str) else x
112
+
113
+ # compatibility to old option
114
+ if filter is not None:
115
+ use_filter = filter
116
+
117
+ # setup mode
118
+ if use_filter:
119
+ mode = "env" if use_env else "all"
120
+ else:
121
+ mode = "env-nofilter" if use_env else "nofilter"
122
+
123
+ # define path
124
+ path = f"{prefix}_{mode}"
125
+ if not os.path.isdir(path): os.mkdir(path)
126
+
127
+ # call mmseqs2 api
128
+ tar_gz_file = f'{path}/out.tar.gz'
129
+ N,REDO = 101,True
130
+
131
+ # deduplicate and keep track of order
132
+ seqs_unique = sorted(list(set(seqs)))
133
+ Ms = [N+seqs_unique.index(seq) for seq in seqs]
134
+
135
+ # lets do it!
136
+ if not os.path.isfile(tar_gz_file):
137
+ TIME_ESTIMATE = 150 * len(seqs_unique)
138
+ with tqdm.notebook.tqdm(total=TIME_ESTIMATE, bar_format=TQDM_BAR_FORMAT) as pbar:
139
+ while REDO:
140
+ pbar.set_description("SUBMIT")
141
+
142
+ # Resubmit job until it goes through
143
+ out = submit(seqs_unique, mode, N)
144
+ while out["status"] in ["UNKNOWN","RATELIMIT"]:
145
+ # resubmit
146
+ time.sleep(5 + random.randint(0,5))
147
+ out = submit(seqs_unique, mode, N)
148
+
149
+ if out["status"] == "ERROR":
150
+ raise Exception(f'MMseqs2 API is giving errors. Please confirm your input is a valid protein sequence. If error persists, please try again an hour later.')
151
+
152
+ if out["status"] == "MAINTENANCE":
153
+ raise Exception(f'MMseqs2 API is undergoing maintenance. Please try again in a few minutes.')
154
+
155
+ # wait for job to finish
156
+ ID,TIME = out["id"],0
157
+ pbar.set_description(out["status"])
158
+ while out["status"] in ["UNKNOWN","RUNNING","PENDING"]:
159
+ t = 5 + random.randint(0,5)
160
+ time.sleep(t)
161
+ out = status(ID)
162
+ pbar.set_description(out["status"])
163
+ if out["status"] == "RUNNING":
164
+ TIME += t
165
+ pbar.update(n=t)
166
+ #if TIME > 900 and out["status"] != "COMPLETE":
167
+ # # something failed on the server side, need to resubmit
168
+ # N += 1
169
+ # break
170
+
171
+ if out["status"] == "COMPLETE":
172
+ if TIME < TIME_ESTIMATE:
173
+ pbar.update(n=(TIME_ESTIMATE-TIME))
174
+ REDO = False
175
+
176
+ # Download results
177
+ download(ID, tar_gz_file)
178
+
179
+ # prep list of a3m files
180
+ a3m_files = [f"{path}/uniref.a3m"]
181
+ if use_env: a3m_files.append(f"{path}/bfd.mgnify30.metaeuk30.smag30.a3m")
182
+
183
+ # extract a3m files
184
+ if not os.path.isfile(a3m_files[0]):
185
+ with tarfile.open(tar_gz_file) as tar_gz:
186
+ tar_gz.extractall(path)
187
+
188
+ # templates
189
+ if use_templates:
190
+ templates = {}
191
+ print("seq\tpdb\tcid\tevalue")
192
+ for line in open(f"{path}/pdb70.m8","r"):
193
+ p = line.rstrip().split()
194
+ M,pdb,qid,e_value = p[0],p[1],p[2],p[10]
195
+ M = int(M)
196
+ if M not in templates: templates[M] = []
197
+ templates[M].append(pdb)
198
+ if len(templates[M]) <= 20:
199
+ print(f"{int(M)-N}\t{pdb}\t{qid}\t{e_value}")
200
+
201
+ template_paths = {}
202
+ for k,TMPL in templates.items():
203
+ TMPL_PATH = f"{prefix}_{mode}/templates_{k}"
204
+ if not os.path.isdir(TMPL_PATH):
205
+ os.mkdir(TMPL_PATH)
206
+ TMPL_LINE = ",".join(TMPL[:20])
207
+ os.system(f"curl -s {host_url}/template/{TMPL_LINE} | tar xzf - -C {TMPL_PATH}/")
208
+ os.system(f"cp {TMPL_PATH}/pdb70_a3m.ffindex {TMPL_PATH}/pdb70_cs219.ffindex")
209
+ os.system(f"touch {TMPL_PATH}/pdb70_cs219.ffdata")
210
+ template_paths[k] = TMPL_PATH
211
+
212
+ # gather a3m lines
213
+ a3m_lines = {}
214
+ for a3m_file in a3m_files:
215
+ update_M,M = True,None
216
+ for line in open(a3m_file,"r"):
217
+ if len(line) > 0:
218
+ if "\x00" in line:
219
+ line = line.replace("\x00","")
220
+ update_M = True
221
+ if line.startswith(">") and update_M:
222
+ M = int(line[1:].rstrip())
223
+ update_M = False
224
+ if M not in a3m_lines: a3m_lines[M] = []
225
+ a3m_lines[M].append(line)
226
+
227
+ # return results
228
+ a3m_lines = ["".join(a3m_lines[n]) for n in Ms]
229
+
230
+ if use_templates:
231
+ template_paths_ = []
232
+ for n in Ms:
233
+ if n not in template_paths:
234
+ template_paths_.append(None)
235
+ print(f"{n-N}\tno_templates_found")
236
+ else:
237
+ template_paths_.append(template_paths[n])
238
+ template_paths = template_paths_
239
+
240
+ if isinstance(x, str):
241
+ return (a3m_lines[0], template_paths[0]) if use_templates else a3m_lines[0]
242
+ else:
243
+ return (a3m_lines, template_paths) if use_templates else a3m_lines
244
+
245
+
246
+ #########################################################################
247
+ # utils
248
+ #########################################################################
249
+ def get_hash(x):
250
+ return hashlib.sha1(x.encode()).hexdigest()
251
+
252
+ def homooligomerize(msas, deletion_matrices, homooligomer=1):
253
+ if homooligomer == 1:
254
+ return msas, deletion_matrices
255
+ else:
256
+ new_msas = []
257
+ new_mtxs = []
258
+ for o in range(homooligomer):
259
+ for msa,mtx in zip(msas, deletion_matrices):
260
+ num_res = len(msa[0])
261
+ L = num_res * o
262
+ R = num_res * (homooligomer-(o+1))
263
+ new_msas.append(["-"*L+s+"-"*R for s in msa])
264
+ new_mtxs.append([[0]*L+m+[0]*R for m in mtx])
265
+ return new_msas, new_mtxs
266
+
267
+ # keeping typo for cross-compatibility
268
+ def homooliomerize(msas, deletion_matrices, homooligomer=1):
269
+ return homooligomerize(msas, deletion_matrices, homooligomer=homooligomer)
270
+
271
+ def homooligomerize_heterooligomer(msas, deletion_matrices, lengths, homooligomers):
272
+ '''
273
+ ----- inputs -----
274
+ msas: list of msas
275
+ deletion_matrices: list of deletion matrices
276
+ lengths: list of lengths for each component in complex
277
+ homooligomers: list of number of homooligomeric copies for each component
278
+ ----- outputs -----
279
+ (msas, deletion_matrices)
280
+ '''
281
+ if max(homooligomers) == 1:
282
+ return msas, deletion_matrices
283
+
284
+ elif len(homooligomers) == 1:
285
+ return homooligomerize(msas, deletion_matrices, homooligomers[0])
286
+
287
+ else:
288
+ frag_ij = [[0,lengths[0]]]
289
+ for length in lengths[1:]:
290
+ j = frag_ij[-1][-1]
291
+ frag_ij.append([j,j+length])
292
+
293
+ # for every msa
294
+ mod_msas, mod_mtxs = [],[]
295
+ for msa, mtx in zip(msas, deletion_matrices):
296
+ mod_msa, mod_mtx = [],[]
297
+ # for every sequence
298
+ for n,(s,m) in enumerate(zip(msa,mtx)):
299
+ # split sequence
300
+ _s,_m,_ok = [],[],[]
301
+ for i,j in frag_ij:
302
+ _s.append(s[i:j]); _m.append(m[i:j])
303
+ _ok.append(max([o != "-" for o in _s[-1]]))
304
+
305
+ if n == 0:
306
+ # if first query sequence
307
+ mod_msa.append("".join([x*h for x,h in zip(_s,homooligomers)]))
308
+ mod_mtx.append(sum([x*h for x,h in zip(_m,homooligomers)],[]))
309
+
310
+ elif sum(_ok) == 1:
311
+ # elif one fragment: copy each fragment to every homooligomeric copy
312
+ a = _ok.index(True)
313
+ for h_a in range(homooligomers[a]):
314
+ _blank_seq = [["-"*l]*h for l,h in zip(lengths,homooligomers)]
315
+ _blank_mtx = [[[0]*l]*h for l,h in zip(lengths,homooligomers)]
316
+ _blank_seq[a][h_a] = _s[a]
317
+ _blank_mtx[a][h_a] = _m[a]
318
+ mod_msa.append("".join(["".join(x) for x in _blank_seq]))
319
+ mod_mtx.append(sum([sum(x,[]) for x in _blank_mtx],[]))
320
+ else:
321
+ # else: copy fragment pair to every homooligomeric copy pair
322
+ for a in range(len(lengths)-1):
323
+ if _ok[a]:
324
+ for b in range(a+1,len(lengths)):
325
+ if _ok[b]:
326
+ for h_a in range(homooligomers[a]):
327
+ for h_b in range(homooligomers[b]):
328
+ _blank_seq = [["-"*l]*h for l,h in zip(lengths,homooligomers)]
329
+ _blank_mtx = [[[0]*l]*h for l,h in zip(lengths,homooligomers)]
330
+ for c,h_c in zip([a,b],[h_a,h_b]):
331
+ _blank_seq[c][h_c] = _s[c]
332
+ _blank_mtx[c][h_c] = _m[c]
333
+ mod_msa.append("".join(["".join(x) for x in _blank_seq]))
334
+ mod_mtx.append(sum([sum(x,[]) for x in _blank_mtx],[]))
335
+ mod_msas.append(mod_msa)
336
+ mod_mtxs.append(mod_mtx)
337
+ return mod_msas, mod_mtxs
338
+
339
+ def chain_break(idx_res, Ls, length=200):
340
+ # Minkyung's code
341
+ # add big enough number to residue index to indicate chain breaks
342
+ L_prev = 0
343
+ for L_i in Ls[:-1]:
344
+ idx_res[L_prev+L_i:] += length
345
+ L_prev += L_i
346
+ return idx_res
347
+
348
+ ##################################################
349
+ # plotting
350
+ ##################################################
351
+
352
+ def plot_plddt_legend(dpi=100):
353
+ thresh = ['plDDT:','Very low (<50)','Low (60)','OK (70)','Confident (80)','Very high (>90)']
354
+ plt.figure(figsize=(1,0.1),dpi=dpi)
355
+ ########################################
356
+ for c in ["#FFFFFF","#FF0000","#FFFF00","#00FF00","#00FFFF","#0000FF"]:
357
+ plt.bar(0, 0, color=c)
358
+ plt.legend(thresh, frameon=False,
359
+ loc='center', ncol=6,
360
+ handletextpad=1,
361
+ columnspacing=1,
362
+ markerscale=0.5,)
363
+ plt.axis(False)
364
+ return plt
365
+
366
+ def plot_ticks(Ls):
367
+ Ln = sum(Ls)
368
+ L_prev = 0
369
+ for L_i in Ls[:-1]:
370
+ L = L_prev + L_i
371
+ L_prev += L_i
372
+ plt.plot([0,Ln],[L,L],color="black")
373
+ plt.plot([L,L],[0,Ln],color="black")
374
+ ticks = np.cumsum([0]+Ls)
375
+ ticks = (ticks[1:] + ticks[:-1])/2
376
+ plt.yticks(ticks,alphabet_list[:len(ticks)])
377
+
378
+ def plot_confidence(plddt, pae=None, Ls=None, dpi=100):
379
+ use_ptm = False if pae is None else True
380
+ if use_ptm:
381
+ plt.figure(figsize=(10,3), dpi=dpi)
382
+ plt.subplot(1,2,1);
383
+ else:
384
+ plt.figure(figsize=(5,3), dpi=dpi)
385
+ plt.title('Predicted lDDT')
386
+ plt.plot(plddt)
387
+ if Ls is not None:
388
+ L_prev = 0
389
+ for L_i in Ls[:-1]:
390
+ L = L_prev + L_i
391
+ L_prev += L_i
392
+ plt.plot([L,L],[0,100],color="black")
393
+ plt.ylim(0,100)
394
+ plt.ylabel('plDDT')
395
+ plt.xlabel('position')
396
+ if use_ptm:
397
+ plt.subplot(1,2,2);plt.title('Predicted Aligned Error')
398
+ Ln = pae.shape[0]
399
+ plt.imshow(pae,cmap="bwr",vmin=0,vmax=30,extent=(0, Ln, Ln, 0))
400
+ if Ls is not None and len(Ls) > 1: plot_ticks(Ls)
401
+ plt.colorbar()
402
+ plt.xlabel('Scored residue')
403
+ plt.ylabel('Aligned residue')
404
+ return plt
405
+
406
+ def plot_msas(msas, ori_seq=None, sort_by_seqid=True, deduplicate=True, dpi=100, return_plt=True):
407
+ '''
408
+ plot the msas
409
+ '''
410
+ if ori_seq is None: ori_seq = msas[0][0]
411
+ seqs = ori_seq.replace("/","").split(":")
412
+ seqs_dash = ori_seq.replace(":","").split("/")
413
+
414
+ Ln = np.cumsum(np.append(0,[len(seq) for seq in seqs]))
415
+ Ln_dash = np.cumsum(np.append(0,[len(seq) for seq in seqs_dash]))
416
+ Nn,lines = [],[]
417
+ for msa in msas:
418
+ msa_ = set(msa) if deduplicate else msa
419
+ if len(msa_) > 0:
420
+ Nn.append(len(msa_))
421
+ msa_ = np.asarray([list(seq) for seq in msa_])
422
+ gap_ = msa_ != "-"
423
+ qid_ = msa_ == np.array(list("".join(seqs)))
424
+ gapid = np.stack([gap_[:,Ln[i]:Ln[i+1]].max(-1) for i in range(len(seqs))],-1)
425
+ seqid = np.stack([qid_[:,Ln[i]:Ln[i+1]].mean(-1) for i in range(len(seqs))],-1).sum(-1) / (gapid.sum(-1) + 1e-8)
426
+ non_gaps = gap_.astype(float)
427
+ non_gaps[non_gaps == 0] = np.nan
428
+ if sort_by_seqid:
429
+ lines.append(non_gaps[seqid.argsort()]*seqid[seqid.argsort(),None])
430
+ else:
431
+ lines.append(non_gaps[::-1] * seqid[::-1,None])
432
+
433
+ Nn = np.cumsum(np.append(0,Nn))
434
+ lines = np.concatenate(lines,0)
435
+
436
+ if return_plt:
437
+ plt.figure(figsize=(8,5),dpi=dpi)
438
+ plt.title("Sequence coverage")
439
+ plt.imshow(lines,
440
+ interpolation='nearest', aspect='auto',
441
+ cmap="rainbow_r", vmin=0, vmax=1, origin='lower',
442
+ extent=(0, lines.shape[1], 0, lines.shape[0]))
443
+ for i in Ln[1:-1]:
444
+ plt.plot([i,i],[0,lines.shape[0]],color="black")
445
+ for i in Ln_dash[1:-1]:
446
+ plt.plot([i,i],[0,lines.shape[0]],"--",color="black")
447
+ for j in Nn[1:-1]:
448
+ plt.plot([0,lines.shape[1]],[j,j],color="black")
449
+
450
+ plt.plot((np.isnan(lines) == False).sum(0), color='black')
451
+ plt.xlim(0,lines.shape[1])
452
+ plt.ylim(0,lines.shape[0])
453
+ plt.colorbar(label="Sequence identity to query")
454
+ plt.xlabel("Positions")
455
+ plt.ylabel("Sequences")
456
+ if return_plt: return plt
457
+
458
+ def read_pdb_renum(pdb_filename, Ls=None):
459
+ if Ls is not None:
460
+ L_init = 0
461
+ new_chain = {}
462
+ for L,c in zip(Ls, alphabet_list):
463
+ new_chain.update({i:c for i in range(L_init,L_init+L)})
464
+ L_init += L
465
+
466
+ n,pdb_out = 1,[]
467
+ resnum_,chain_ = 1,"A"
468
+ for line in open(pdb_filename,"r"):
469
+ if line[:4] == "ATOM":
470
+ chain = line[21:22]
471
+ resnum = int(line[22:22+5])
472
+ if resnum != resnum_ or chain != chain_:
473
+ resnum_,chain_ = resnum,chain
474
+ n += 1
475
+ if Ls is None: pdb_out.append("%s%4i%s" % (line[:22],n,line[26:]))
476
+ else: pdb_out.append("%s%s%4i%s" % (line[:21],new_chain[n-1],n,line[26:]))
477
+ return "".join(pdb_out)
478
+
479
+ def show_pdb(pred_output_path, show_sidechains=False, show_mainchains=False,
480
+ color="lDDT", chains=None, Ls=None, vmin=50, vmax=90,
481
+ color_HP=False, size=(800,480), hbondCutoff=4.0):
482
+
483
+ if chains is None:
484
+ chains = 1 if Ls is None else len(Ls)
485
+
486
+ view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js', width=size[0], height=size[1])
487
+ view.addModel(read_pdb_renum(pred_output_path, Ls),'pdb',{'hbondCutoff':hbondCutoff})
488
+ if color == "lDDT":
489
+ view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':vmin,'max':vmax}}})
490
+ elif color == "rainbow":
491
+ view.setStyle({'cartoon': {'color':'spectrum'}})
492
+ elif color == "chain":
493
+ for n,chain,color in zip(range(chains),alphabet_list,pymol_color_list):
494
+ view.setStyle({'chain':chain},{'cartoon': {'color':color}})
495
+ if show_sidechains:
496
+ BB = ['C','O','N']
497
+ HP = ["ALA","GLY","VAL","ILE","LEU","PHE","MET","PRO","TRP","CYS","TYR"]
498
+ if color_HP:
499
+ view.addStyle({'and':[{'resn':HP},{'atom':BB,'invert':True}]},
500
+ {'stick':{'colorscheme':"yellowCarbon",'radius':0.3}})
501
+ view.addStyle({'and':[{'resn':HP,'invert':True},{'atom':BB,'invert':True}]},
502
+ {'stick':{'colorscheme':"whiteCarbon",'radius':0.3}})
503
+ view.addStyle({'and':[{'resn':"GLY"},{'atom':'CA'}]},
504
+ {'sphere':{'colorscheme':"yellowCarbon",'radius':0.3}})
505
+ view.addStyle({'and':[{'resn':"PRO"},{'atom':['C','O'],'invert':True}]},
506
+ {'stick':{'colorscheme':"yellowCarbon",'radius':0.3}})
507
+ else:
508
+ view.addStyle({'and':[{'resn':["GLY","PRO"],'invert':True},{'atom':BB,'invert':True}]},
509
+ {'stick':{'colorscheme':f"WhiteCarbon",'radius':0.3}})
510
+ view.addStyle({'and':[{'resn':"GLY"},{'atom':'CA'}]},
511
+ {'sphere':{'colorscheme':f"WhiteCarbon",'radius':0.3}})
512
+ view.addStyle({'and':[{'resn':"PRO"},{'atom':['C','O'],'invert':True}]},
513
+ {'stick':{'colorscheme':f"WhiteCarbon",'radius':0.3}})
514
+ if show_mainchains:
515
+ BB = ['C','O','N','CA']
516
+ view.addStyle({'atom':BB},{'stick':{'colorscheme':f"WhiteCarbon",'radius':0.3}})
517
+ view.zoomTo()
518
+ return view
519
+
520
+ def plot_plddts(plddts, Ls=None, dpi=100, fig=True):
521
+ if fig: plt.figure(figsize=(8,5),dpi=100)
522
+ plt.title("Predicted lDDT per position")
523
+ for n,plddt in enumerate(plddts):
524
+ plt.plot(plddt,label=f"rank_{n+1}")
525
+ if Ls is not None:
526
+ L_prev = 0
527
+ for L_i in Ls[:-1]:
528
+ L = L_prev + L_i
529
+ L_prev += L_i
530
+ plt.plot([L,L],[0,100],color="black")
531
+ plt.legend()
532
+ plt.ylim(0,100)
533
+ plt.ylabel("Predicted lDDT")
534
+ plt.xlabel("Positions")
535
+ return plt
536
+
537
+ def plot_paes(paes, Ls=None, dpi=100, fig=True):
538
+ num_models = len(paes)
539
+ if fig: plt.figure(figsize=(3*num_models,2), dpi=dpi)
540
+ for n,pae in enumerate(paes):
541
+ plt.subplot(1,num_models,n+1)
542
+ plt.title(f"rank_{n+1}")
543
+ Ln = pae.shape[0]
544
+ plt.imshow(pae,cmap="bwr",vmin=0,vmax=30,extent=(0, Ln, Ln, 0))
545
+ if Ls is not None and len(Ls) > 1: plot_ticks(Ls)
546
+ plt.colorbar()
547
+ return plt
548
+
549
+ def plot_adjs(adjs, Ls=None, dpi=100, fig=True):
550
+ num_models = len(adjs)
551
+ if fig: plt.figure(figsize=(3*num_models,2), dpi=dpi)
552
+ for n,adj in enumerate(adjs):
553
+ plt.subplot(1,num_models,n+1)
554
+ plt.title(f"rank_{n+1}")
555
+ Ln = adj.shape[0]
556
+ plt.imshow(adj,cmap="binary",vmin=0,vmax=1,extent=(0, Ln, Ln, 0))
557
+ if Ls is not None and len(Ls) > 1: plot_ticks(Ls)
558
+ plt.colorbar()
559
+ return plt
560
+
561
+ def plot_dists(dists, Ls=None, dpi=100, fig=True):
562
+ num_models = len(dists)
563
+ if fig: plt.figure(figsize=(3*num_models,2), dpi=dpi)
564
+ for n,dist in enumerate(dists):
565
+ plt.subplot(1,num_models,n+1)
566
+ plt.title(f"rank_{n+1}")
567
+ Ln = dist.shape[0]
568
+ plt.imshow(dist,extent=(0, Ln, Ln, 0))
569
+ if Ls is not None and len(Ls) > 1: plot_ticks(Ls)
570
+ plt.colorbar()
571
+ return plt
572
+
573
+ ##########################################################################
574
+ ##########################################################################
575
+
576
+ def kabsch(a, b, weights=None, return_v=False):
577
+ a = np.asarray(a)
578
+ b = np.asarray(b)
579
+ if weights is None: weights = np.ones(len(b))
580
+ else: weights = np.asarray(weights)
581
+ B = np.einsum('ji,jk->ik', weights[:, None] * a, b)
582
+ u, s, vh = np.linalg.svd(B)
583
+ if np.linalg.det(u @ vh) < 0: u[:, -1] = -u[:, -1]
584
+ if return_v: return u
585
+ else: return u @ vh
586
+
587
+ def plot_pseudo_3D(xyz, c=None, ax=None, chainbreak=5,
588
+ cmap="gist_rainbow", line_w=2.0,
589
+ cmin=None, cmax=None, zmin=None, zmax=None):
590
+
591
+ def rescale(a,amin=None,amax=None):
592
+ a = np.copy(a)
593
+ if amin is None: amin = a.min()
594
+ if amax is None: amax = a.max()
595
+ a[a < amin] = amin
596
+ a[a > amax] = amax
597
+ return (a - amin)/(amax - amin)
598
+
599
+ # make segments
600
+ xyz = np.asarray(xyz)
601
+ seg = np.concatenate([xyz[:-1,None,:],xyz[1:,None,:]],axis=-2)
602
+ seg_xy = seg[...,:2]
603
+ seg_z = seg[...,2].mean(-1)
604
+ ord = seg_z.argsort()
605
+
606
+ # set colors
607
+ if c is None: c = np.arange(len(seg))[::-1]
608
+ else: c = (c[1:] + c[:-1])/2
609
+ c = rescale(c,cmin,cmax)
610
+
611
+ if isinstance(cmap, str):
612
+ if cmap == "gist_rainbow": c *= 0.75
613
+ colors = matplotlib.cm.get_cmap(cmap)(c)
614
+ else:
615
+ colors = cmap(c)
616
+
617
+ if chainbreak is not None:
618
+ dist = np.linalg.norm(xyz[:-1] - xyz[1:], axis=-1)
619
+ colors[...,3] = (dist < chainbreak).astype(float)
620
+
621
+ # add shade/tint based on z-dimension
622
+ z = rescale(seg_z,zmin,zmax)[:,None]
623
+ tint, shade = z/3, (z+2)/3
624
+ colors[:,:3] = colors[:,:3] + (1 - colors[:,:3]) * tint
625
+ colors[:,:3] = colors[:,:3] * shade
626
+
627
+ set_lim = False
628
+ if ax is None:
629
+ fig, ax = plt.subplots()
630
+ fig.set_figwidth(5)
631
+ fig.set_figheight(5)
632
+ set_lim = True
633
+ else:
634
+ fig = ax.get_figure()
635
+ if ax.get_xlim() == (0,1):
636
+ set_lim = True
637
+
638
+ if set_lim:
639
+ xy_min = xyz[:,:2].min() - line_w
640
+ xy_max = xyz[:,:2].max() + line_w
641
+ ax.set_xlim(xy_min,xy_max)
642
+ ax.set_ylim(xy_min,xy_max)
643
+
644
+ ax.set_aspect('equal')
645
+
646
+ # determine linewidths
647
+ width = fig.bbox_inches.width * ax.get_position().width
648
+ linewidths = line_w * 72 * width / np.diff(ax.get_xlim())
649
+
650
+ lines = mcoll.LineCollection(seg_xy[ord], colors=colors[ord], linewidths=linewidths,
651
+ path_effects=[matplotlib.patheffects.Stroke(capstyle="round")])
652
+
653
+ return ax.add_collection(lines)
654
+
655
+ def add_text(text, ax):
656
+ return plt.text(0.5, 1.01, text, horizontalalignment='center',
657
+ verticalalignment='bottom', transform=ax.transAxes)
658
+
659
+ def plot_protein(protein=None, pos=None, plddt=None, Ls=None, dpi=100, best_view=True, line_w=2.0):
660
+
661
+ if protein is not None:
662
+ pos = np.asarray(protein.atom_positions[:,1,:])
663
+ plddt = np.asarray(protein.b_factors[:,0])
664
+
665
+ # get best view
666
+ if best_view:
667
+ if plddt is not None:
668
+ weights = plddt/100
669
+ pos = pos - (pos * weights[:,None]).sum(0,keepdims=True) / weights.sum()
670
+ pos = pos @ kabsch(pos, pos, weights, return_v=True)
671
+ else:
672
+ pos = pos - pos.mean(0,keepdims=True)
673
+ pos = pos @ kabsch(pos, pos, return_v=True)
674
+
675
+ if plddt is not None:
676
+ fig, (ax1, ax2) = plt.subplots(1,2)
677
+ fig.set_figwidth(6); fig.set_figheight(3)
678
+ ax = [ax1, ax2]
679
+ else:
680
+ fig, ax1 = plt.subplots(1,1)
681
+ fig.set_figwidth(3); fig.set_figheight(3)
682
+ ax = [ax1]
683
+
684
+ fig.set_dpi(dpi)
685
+ fig.subplots_adjust(top = 0.9, bottom = 0.1, right = 1, left = 0, hspace = 0, wspace = 0)
686
+
687
+ xy_min = pos[...,:2].min() - line_w
688
+ xy_max = pos[...,:2].max() + line_w
689
+ for a in ax:
690
+ a.set_xlim(xy_min, xy_max)
691
+ a.set_ylim(xy_min, xy_max)
692
+ a.axis(False)
693
+
694
+ if Ls is None or len(Ls) == 1:
695
+ # color N->C
696
+ c = np.arange(len(pos))[::-1]
697
+ plot_pseudo_3D(pos, line_w=line_w, ax=ax1)
698
+ add_text("colored by N→C", ax1)
699
+ else:
700
+ # color by chain
701
+ c = np.concatenate([[n]*L for n,L in enumerate(Ls)])
702
+ if len(Ls) > 40: plot_pseudo_3D(pos, c=c, line_w=line_w, ax=ax1)
703
+ else: plot_pseudo_3D(pos, c=c, cmap=pymol_cmap, cmin=0, cmax=39, line_w=line_w, ax=ax1)
704
+ add_text("colored by chain", ax1)
705
+
706
+ if plddt is not None:
707
+ # color by pLDDT
708
+ plot_pseudo_3D(pos, c=plddt, cmin=50, cmax=90, line_w=line_w, ax=ax2)
709
+ add_text("colored by pLDDT", ax2)
710
+
711
+ return fig
data/beta/colabfold_alphafold.py ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from urllib import request
4
+ from concurrent import futures
5
+ import pickle
6
+
7
+ import jax
8
+ from alphafold.data.tools import jackhmmer
9
+ from alphafold.data import parsers
10
+ from alphafold.data import pipeline
11
+ from alphafold.common import protein
12
+ from alphafold.model import config
13
+ from alphafold.model import model
14
+ from alphafold.model import data
15
+ from alphafold.model.tf import shape_placeholders
16
+
17
+ import tensorflow as tf
18
+
19
+ from string import ascii_uppercase
20
+
21
+ import numpy as np
22
+ import matplotlib.pyplot as plt
23
+
24
+ import re
25
+ import colabfold as cf
26
+ import pairmsa
27
+
28
+ try:
29
+ from google.colab import files
30
+ IN_COLAB = True
31
+ except:
32
+ IN_COLAB = False
33
+
34
+ import tqdm.notebook
35
+ TQDM_BAR_FORMAT = '{l_bar}{bar}| {n_fmt}/{total_fmt} [elapsed: {elapsed} remaining: {remaining}]'
36
+
37
+ #######################################################################################################################################
38
+ # prep_inputs
39
+ #######################################################################################################################################
40
+
41
+ def prep_inputs(sequence, jobname="test", homooligomer="1", output_dir=None, clean=False, verbose=True):
42
+ # process inputs
43
+ sequence = str(sequence)
44
+ sequence = re.sub("[^A-Z:/]", "", sequence.upper())
45
+ sequence = re.sub(":+",":",sequence)
46
+ sequence = re.sub("/+","/",sequence)
47
+ sequence = re.sub("^[:/]+","",sequence)
48
+ sequence = re.sub("[:/]+$","",sequence)
49
+ jobname = re.sub(r'\W+', '', jobname)
50
+ homooligomer = str(homooligomer)
51
+ homooligomer = re.sub("[:/]+",":",homooligomer)
52
+ homooligomer = re.sub("^[:/]+","",homooligomer)
53
+ homooligomer = re.sub("[:/]+$","",homooligomer)
54
+
55
+ if len(homooligomer) == 0: homooligomer = "1"
56
+ homooligomer = re.sub("[^0-9:]", "", homooligomer)
57
+
58
+ # define inputs
59
+ I = {"ori_sequence":sequence,
60
+ "sequence":sequence.replace("/","").replace(":",""),
61
+ "seqs":sequence.replace("/","").split(":"),
62
+ "homooligomer":homooligomer,
63
+ "homooligomers":[int(h) for h in homooligomer.split(":")],
64
+ "msas":[], "deletion_matrices":[]}
65
+
66
+ # adjust homooligomer option
67
+ if len(I["seqs"]) != len(I["homooligomers"]):
68
+ if len(I["homooligomers"]) == 1:
69
+ I["homooligomers"] = [I["homooligomers"][0]] * len(I["seqs"])
70
+ else:
71
+ if verbose:
72
+ print("WARNING: Mismatch between number of breaks ':' in 'sequence' and 'homooligomer' definition")
73
+ while len(I["seqs"]) > len(I["homooligomers"]):
74
+ I["homooligomers"].append(1)
75
+ I["homooligomers"] = I["homooligomers"][:len(I["seqs"])]
76
+ I["homooligomer"] = ":".join([str(h) for h in I["homooligomers"]])
77
+
78
+ # define full sequence being modelled
79
+ I["full_sequence"] = ''.join([s*h for s,h in zip(I["seqs"],I["homooligomers"])])
80
+ I["lengths"] = [len(seq) for seq in I["seqs"]]
81
+
82
+ # prediction directory
83
+ if output_dir is None:
84
+ I["output_dir"] = 'prediction_' + jobname + '_' + cf.get_hash(I["full_sequence"])[:5]
85
+ else:
86
+ I["output_dir"] = output_dir
87
+ os.makedirs(I["output_dir"], exist_ok=True)
88
+
89
+ # delete existing files in working directory
90
+ if clean:
91
+ for f in os.listdir(I["output_dir"]):
92
+ os.remove(os.path.join(I["output_dir"], f))
93
+
94
+ if verbose and len(I["full_sequence"]) > 1400:
95
+ print(f"WARNING: For a typical Google-Colab-GPU (16G) session, the max total length is ~1400 residues. You are at {len(I['full_sequence'])}!")
96
+ print(f"Run Alphafold may crash, unless you trim to the protein(s) to a short length. (See trim options below).")
97
+
98
+ if verbose:
99
+ print(f"homooligomer: {I['homooligomer']}")
100
+ print(f"total_length: {len(I['full_sequence'])}")
101
+ print(f"output_dir: {I['output_dir']}")
102
+
103
+ return I
104
+
105
+ #######################################################################################################################################
106
+ # prep_msa
107
+ #######################################################################################################################################
108
+
109
+ def run_jackhmmer(sequence, prefix, jackhmmer_binary_path='jackhmmer', verbose=True):
110
+
111
+ fasta_path = f"{prefix}.fasta"
112
+ with open(fasta_path, 'wt') as f:
113
+ f.write(f'>query\n{sequence}')
114
+
115
+ pickled_msa_path = f"{prefix}.jackhmmer.pickle"
116
+ if os.path.isfile(pickled_msa_path):
117
+ msas_dict = pickle.load(open(pickled_msa_path,"rb"))
118
+ msas, deletion_matrices, names = (msas_dict[k] for k in ['msas', 'deletion_matrices', 'names'])
119
+ full_msa = []
120
+ for msa in msas:
121
+ full_msa += msa
122
+ else:
123
+ # --- Find the closest source ---
124
+ test_url_pattern = 'https://storage.googleapis.com/alphafold-colab{:s}/latest/uniref90_2021_03.fasta.1'
125
+ ex = futures.ThreadPoolExecutor(3)
126
+ def fetch(source):
127
+ request.urlretrieve(test_url_pattern.format(source))
128
+ return source
129
+ fs = [ex.submit(fetch, source) for source in ['', '-europe', '-asia']]
130
+ source = None
131
+ for f in futures.as_completed(fs):
132
+ source = f.result()
133
+ ex.shutdown()
134
+ break
135
+
136
+ dbs = []
137
+
138
+ num_jackhmmer_chunks = {'uniref90': 59, 'smallbfd': 17, 'mgnify': 71}
139
+ total_jackhmmer_chunks = sum(num_jackhmmer_chunks.values())
140
+ disable_tqdm = not verbose
141
+ with tqdm.notebook.tqdm(total=total_jackhmmer_chunks, bar_format=TQDM_BAR_FORMAT, disable=disable_tqdm) as pbar:
142
+ def jackhmmer_chunk_callback(i):
143
+ pbar.update(n=1)
144
+
145
+ pbar.set_description('Searching uniref90')
146
+ jackhmmer_uniref90_runner = jackhmmer.Jackhmmer(
147
+ binary_path=jackhmmer_binary_path,
148
+ database_path=f'https://storage.googleapis.com/alphafold-colab{source}/latest/uniref90_2021_03.fasta',
149
+ get_tblout=True,
150
+ num_streamed_chunks=num_jackhmmer_chunks['uniref90'],
151
+ streaming_callback=jackhmmer_chunk_callback,
152
+ z_value=135301051)
153
+ dbs.append(('uniref90', jackhmmer_uniref90_runner.query(fasta_path)))
154
+
155
+ pbar.set_description('Searching smallbfd')
156
+ jackhmmer_smallbfd_runner = jackhmmer.Jackhmmer(
157
+ binary_path=jackhmmer_binary_path,
158
+ database_path=f'https://storage.googleapis.com/alphafold-colab{source}/latest/bfd-first_non_consensus_sequences.fasta',
159
+ get_tblout=True,
160
+ num_streamed_chunks=num_jackhmmer_chunks['smallbfd'],
161
+ streaming_callback=jackhmmer_chunk_callback,
162
+ z_value=65984053)
163
+ dbs.append(('smallbfd', jackhmmer_smallbfd_runner.query(fasta_path)))
164
+
165
+ pbar.set_description('Searching mgnify')
166
+ jackhmmer_mgnify_runner = jackhmmer.Jackhmmer(
167
+ binary_path=jackhmmer_binary_path,
168
+ database_path=f'https://storage.googleapis.com/alphafold-colab{source}/latest/mgy_clusters_2019_05.fasta',
169
+ get_tblout=True,
170
+ num_streamed_chunks=num_jackhmmer_chunks['mgnify'],
171
+ streaming_callback=jackhmmer_chunk_callback,
172
+ z_value=304820129)
173
+ dbs.append(('mgnify', jackhmmer_mgnify_runner.query(fasta_path)))
174
+
175
+ # --- Extract the MSAs and visualize ---
176
+ # Extract the MSAs from the Stockholm files.
177
+ # NB: deduplication happens later in pipeline.make_msa_features.
178
+
179
+ mgnify_max_hits = 501
180
+ msas = []
181
+ deletion_matrices = []
182
+ names = []
183
+ for db_name, db_results in dbs:
184
+ unsorted_results = []
185
+ for i, result in enumerate(db_results):
186
+ msa, deletion_matrix, target_names = parsers.parse_stockholm(result['sto'])
187
+ e_values_dict = parsers.parse_e_values_from_tblout(result['tbl'])
188
+ e_values = [e_values_dict[t.split('/')[0]] for t in target_names]
189
+ zipped_results = zip(msa, deletion_matrix, target_names, e_values)
190
+ if i != 0:
191
+ # Only take query from the first chunk
192
+ zipped_results = [x for x in zipped_results if x[2] != 'query']
193
+ unsorted_results.extend(zipped_results)
194
+ sorted_by_evalue = sorted(unsorted_results, key=lambda x: x[3])
195
+ db_msas, db_deletion_matrices, db_names, _ = zip(*sorted_by_evalue)
196
+ if db_msas:
197
+ if db_name == 'mgnify':
198
+ db_msas = db_msas[:mgnify_max_hits]
199
+ db_deletion_matrices = db_deletion_matrices[:mgnify_max_hits]
200
+ db_names = db_names[:mgnify_max_hits]
201
+ msas.append(db_msas)
202
+ deletion_matrices.append(db_deletion_matrices)
203
+ names.append(db_names)
204
+ msa_size = len(set(db_msas))
205
+ print(f'{msa_size} Sequences Found in {db_name}')
206
+
207
+ pickle.dump({"msas":msas,
208
+ "deletion_matrices":deletion_matrices,
209
+ "names":names}, open(pickled_msa_path,"wb"))
210
+ return msas, deletion_matrices, names
211
+
212
+ def prep_msa(I, msa_method="mmseqs2", add_custom_msa=False, msa_format="fas",
213
+ pair_mode="unpaired", pair_cov=50, pair_qid=20,
214
+ hhfilter_loc="hhfilter", reformat_loc="reformat.pl", TMP_DIR="tmp",
215
+ custom_msa=None, precomputed=None,
216
+ mmseqs_host_url="https://a3m.mmseqs.com",
217
+ verbose=True):
218
+
219
+ # make temp directory
220
+ os.makedirs(TMP_DIR, exist_ok=True)
221
+
222
+ # clear previous inputs
223
+ I["msas"] = []
224
+ I["deletion_matrices"] = []
225
+
226
+ if add_custom_msa:
227
+ if IN_COLAB:
228
+ print(f"upload custom msa in '{msa_format}' format")
229
+ msa_dict = files.upload()
230
+ lines = msa_dict[list(msa_dict.keys())[0]].decode()
231
+ input_file = os.path.join(I["output_dir"],f"upload.{msa_format}")
232
+ with open(input_file,"w") as tmp_upload:
233
+ tmp_upload.write(lines)
234
+ else:
235
+ input_file = custom_msa
236
+ if input_file is None or not os.path.isfile(input_file):
237
+ raise ValueError("ERROR: `custom_msa` undefined")
238
+ else:
239
+ # convert to a3m
240
+ output_file = os.path.join(I["output_dir"],f"upload.a3m")
241
+ os.system(f"{reformat_loc} {msa_format} a3m {input_file} {output_file}")
242
+
243
+ # parse
244
+ msa, mtx = parsers.parse_a3m(open(output_file,"r").read())
245
+ I["msas"].append(msa)
246
+ I["deletion_matrices"].append(mtx)
247
+ if len(I["msas"][0][0]) != len(I["sequence"]):
248
+ raise ValueError("ERROR: the length of msa does not match input sequence")
249
+
250
+ if msa_method == "precomputed":
251
+ if IN_COLAB:
252
+ print("upload precomputed pickled msa from previous run")
253
+ uploaded_dict = files.upload()
254
+ uploaded_filename = list(uploaded_dict.keys())[0]
255
+ I.update(pickle.loads(uploaded_dict[uploaded_filename]))
256
+ elif precomputed is None:
257
+ raise ValueError("ERROR: `precomputed` undefined")
258
+ else:
259
+ I.update(pickle.load(open(precomputed,"rb")))
260
+
261
+ elif msa_method == "single_sequence":
262
+ if len(I["msas"]) == 0:
263
+ I["msas"].append([I["sequence"]])
264
+ I["deletion_matrices"].append([[0]*len(I["sequence"])])
265
+
266
+ else:
267
+ _blank_seq = ["-" * L for L in I["lengths"]]
268
+ _blank_mtx = [[0] * L for L in I["lengths"]]
269
+ def _pad(ns,vals,mode):
270
+ if mode == "seq": _blank = _blank_seq.copy()
271
+ if mode == "mtx": _blank = _blank_mtx.copy()
272
+ if isinstance(ns, list):
273
+ for n,val in zip(ns,vals): _blank[n] = val
274
+ else: _blank[ns] = vals
275
+ if mode == "seq": return "".join(_blank)
276
+ if mode == "mtx": return sum(_blank,[])
277
+
278
+ if len(I["seqs"]) == 1 or "unpaired" in pair_mode:
279
+ # gather msas
280
+ if msa_method == "mmseqs2":
281
+ prefix = cf.get_hash(I["sequence"])
282
+ prefix = os.path.join(TMP_DIR,prefix)
283
+ print(f"running mmseqs2")
284
+ A3M_LINES = cf.run_mmseqs2(I["seqs"], prefix, use_filter=True, host_url=mmseqs_host_url)
285
+
286
+ for n, seq in enumerate(I["seqs"]):
287
+ # tmp directory
288
+ prefix = cf.get_hash(seq)
289
+ prefix = os.path.join(TMP_DIR,prefix)
290
+
291
+ if msa_method == "mmseqs2":
292
+ # run mmseqs2
293
+ a3m_lines = A3M_LINES[n]
294
+ msa, mtx = parsers.parse_a3m(a3m_lines)
295
+ msas_, mtxs_ = [msa],[mtx]
296
+
297
+ elif msa_method == "jackhmmer":
298
+ print(f"running jackhmmer on seq_{n}")
299
+ # run jackhmmer
300
+ msas_, mtxs_, names_ = ([sum(x,())] for x in run_jackhmmer(seq, prefix))
301
+
302
+ # pad sequences
303
+ for msa_,mtx_ in zip(msas_,mtxs_):
304
+ msa,mtx = [I["sequence"]],[[0]*len(I["sequence"])]
305
+ for s,m in zip(msa_,mtx_):
306
+ msa.append(_pad(n,s,"seq"))
307
+ mtx.append(_pad(n,m,"mtx"))
308
+
309
+ I["msas"].append(msa)
310
+ I["deletion_matrices"].append(mtx)
311
+
312
+ # PAIR_MSA
313
+ if len(I["seqs"]) > 1 and (pair_mode == "paired" or pair_mode == "unpaired+paired"):
314
+ print("attempting to pair some sequences...")
315
+
316
+ if msa_method == "mmseqs2":
317
+ prefix = cf.get_hash(I["sequence"])
318
+ prefix = os.path.join(TMP_DIR,prefix)
319
+ print(f"running mmseqs2_noenv_nofilter on all seqs")
320
+ A3M_LINES = cf.run_mmseqs2(I["seqs"], prefix, use_env=False, use_filter=False, host_url=mmseqs_host_url)
321
+
322
+ _data = []
323
+ for a in range(len(I["seqs"])):
324
+ print(f"prepping seq_{a}")
325
+ _seq = I["seqs"][a]
326
+ _prefix = os.path.join(TMP_DIR,cf.get_hash(_seq))
327
+
328
+ if msa_method == "mmseqs2":
329
+ a3m_lines = A3M_LINES[a]
330
+ _msa, _mtx, _lab = pairmsa.parse_a3m(a3m_lines,
331
+ filter_qid=pair_qid/100,
332
+ filter_cov=pair_cov/100)
333
+
334
+ elif msa_method == "jackhmmer":
335
+ _msas, _mtxs, _names = run_jackhmmer(_seq, _prefix)
336
+ _msa, _mtx, _lab = pairmsa.get_uni_jackhmmer(_msas[0], _mtxs[0], _names[0],
337
+ filter_qid=pair_qid/100,
338
+ filter_cov=pair_cov/100)
339
+
340
+ if len(_msa) > 1:
341
+ _data.append(pairmsa.hash_it(_msa, _lab, _mtx, call_uniprot=False))
342
+ else:
343
+ _data.append(None)
344
+
345
+ Ln = len(I["seqs"])
346
+ O = [[None for _ in I["seqs"]] for _ in I["seqs"]]
347
+ for a in range(Ln):
348
+ if _data[a] is not None:
349
+ for b in range(a+1,Ln):
350
+ if _data[b] is not None:
351
+ print(f"attempting pairwise stitch for {a} {b}")
352
+ O[a][b] = pairmsa._stitch(_data[a],_data[b])
353
+ _seq_a, _seq_b, _mtx_a, _mtx_b = (*O[a][b]["seq"],*O[a][b]["mtx"])
354
+
355
+ # filter to remove redundant sequences
356
+ ok = []
357
+ with open(f"{TMP_DIR}/tmp.fas","w") as fas_file:
358
+ fas_file.writelines([f">{n}\n{a+b}\n" for n,(a,b) in enumerate(zip(_seq_a,_seq_b))])
359
+ os.system(f"{hhfilter_loc} -maxseq 1000000 -i {TMP_DIR}/tmp.fas -o {TMP_DIR}/tmp.id90.fas -id 90")
360
+ for line in open(f"{TMP_DIR}/tmp.id90.fas","r"):
361
+ if line.startswith(">"): ok.append(int(line[1:]))
362
+
363
+ if verbose:
364
+ print(f"found {len(_seq_a)} pairs ({len(ok)} after filtering)")
365
+
366
+ if len(_seq_a) > 0:
367
+ msa,mtx = [I["sequence"]],[[0]*len(I["sequence"])]
368
+ for s_a,s_b,m_a,m_b in zip(_seq_a, _seq_b, _mtx_a, _mtx_b):
369
+ msa.append(_pad([a,b],[s_a,s_b],"seq"))
370
+ mtx.append(_pad([a,b],[m_a,m_b],"mtx"))
371
+ I["msas"].append(msa)
372
+ I["deletion_matrices"].append(mtx)
373
+
374
+ # save MSA as pickle
375
+ pickle.dump({"msas":I["msas"],"deletion_matrices":I["deletion_matrices"]},
376
+ open(os.path.join(I["output_dir"],"msa.pickle"),"wb"))
377
+ return I
378
+
379
+ #######################################################################################################################################
380
+ # prep_filter
381
+ #######################################################################################################################################
382
+
383
+ def trim_inputs(trim, msas, deletion_matrices, ori_seq=None, inverse=False):
384
+ '''
385
+ input: trim, msas, deletion_matrices, ori_seq
386
+ output: msas, deletion_matrices, ori_seq
387
+ '''
388
+ if ori_seq is None: ori_seq = msas[0][0]
389
+ seqs = ori_seq.replace("/","").split(":")
390
+ L_ini = 0
391
+ chain_idx = {}
392
+ idx_chain = []
393
+ for chain,seq in zip(ascii_uppercase,seqs):
394
+ L = len(seq)
395
+ chain_idx[chain] = dict(zip(range(L),range(L_ini,L_ini+L)))
396
+ idx_chain += [f"{chain}{i+1}" for i in range(L)]
397
+ L_ini += L
398
+ global_idx = dict(zip(range(L_ini),range(L_ini)))
399
+
400
+ mode = "keeping" if inverse else "trimming"
401
+ trim_set = []
402
+ for idx in trim.split(","):
403
+
404
+ i,j = idx.split("-") if "-" in idx else (idx,"")
405
+
406
+ # set index reference frame
407
+ trim_idx_i = trim_idx_j = global_idx
408
+ if i != "" and i[0] in ascii_uppercase:
409
+ trim_idx_i,i = chain_idx[i[0]], i[1:]
410
+ if j != "" and j[0] in ascii_uppercase:
411
+ trim_idx_j,j = chain_idx[j[0]], j[1:]
412
+
413
+ # set which positions to trim
414
+ if "-" in idx:
415
+ i = trim_idx_i[int(i)-1] if i != "" else trim_idx_i[0]
416
+ j = trim_idx_j[int(j)-1] if j != "" else trim_idx_j[len(trim_idx_j) - 1]
417
+ trim_set += list(range(i,j+1))
418
+ print(f"{mode} positions: {idx_chain[i]}-{idx_chain[j]}")
419
+ else:
420
+ i = trim_idx_i[int(i)-1]
421
+ trim_set.append(i)
422
+ print(f"{mode} position: {idx_chain[i]}")
423
+
424
+ # deduplicate list
425
+ trim_set = set(trim_set)
426
+ if inverse:
427
+ trim_set = set(range(L_ini)) ^ trim_set
428
+
429
+ trim_set = sorted(list(trim_set))
430
+
431
+ # trim MSA
432
+ mod_msas, mod_mtxs = [],[]
433
+ for msa, mtx in zip(msas, deletion_matrices):
434
+ mod_msa = np.delete([list(s) for s in msa], trim_set, 1)
435
+ ok = (mod_msa != "-").sum(-1) > 0
436
+ mod_msas.append(["".join(s) for s in mod_msa[ok]])
437
+ mod_mtx = np.asarray(mtx)[ok]
438
+ mod_mtxs.append(np.delete(mod_mtx, trim_set, 1).tolist())
439
+
440
+ # trim original sequence
441
+ mod_idx = []
442
+ mod_chain = []
443
+ mod_ori_seq = []
444
+ for n,a in enumerate(ori_seq.replace("/","").replace(":","")):
445
+ if n not in trim_set:
446
+ mod_ori_seq.append(a)
447
+ mod_idx.append(n)
448
+ mod_chain.append(idx_chain[n][0])
449
+ if len(mod_idx) > 1:
450
+ if mod_chain[-1] != mod_chain[-2]:
451
+ mod_ori_seq[-1] = ":"
452
+ mod_ori_seq.append(a)
453
+ elif (mod_idx[-1] - mod_idx[-2]) > 1:
454
+ mod_ori_seq[-1] = "/"
455
+ mod_ori_seq.append(a)
456
+
457
+ mod_ori_seq = "".join(mod_ori_seq)
458
+ chains = sorted([ascii_uppercase.index(a) for a in set(mod_chain)])
459
+ return {"msas":mod_msas, "deletion_matrices":mod_mtxs,
460
+ "ori_sequence":mod_ori_seq, "chains":chains}
461
+
462
+ def cov_qid_filter(msas, deletion_matrices, ori_seq=None, cov=0, qid=0):
463
+ if ori_seq is None: ori_seq = msas[0][0]
464
+ seqs = ori_seq.replace("/","").split(":")
465
+ ref_seq_ = np.array(list("".join(seqs)))
466
+
467
+ new_msas,new_mtxs = [],[]
468
+ L = np.asarray([len(seq) for seq in seqs])
469
+ Ln = np.cumsum(np.append(0,L))
470
+ for msa, mtx in zip(msas, deletion_matrices):
471
+ msa_ = np.asarray([list(seq) for seq in msa])
472
+
473
+ # coverage (non-gap characters)
474
+ cov_ = msa_ != "-"
475
+ # sequence identity to query
476
+ qid_ = msa_ == ref_seq_
477
+
478
+ # split by protein (for protein complexes)
479
+ cov__ = np.stack([cov_[:,Ln[i]:Ln[i+1]].sum(-1) for i in range(len(seqs))],-1)
480
+ qid__ = np.stack([qid_[:,Ln[i]:Ln[i+1]].sum(-1) for i in range(len(seqs))],-1)
481
+
482
+ not_empty__ = cov__ > 0
483
+ ok = []
484
+ for n in range(len(msa)):
485
+ m = not_empty__[n]
486
+ if m.sum() > 0:
487
+ q = qid__[n][m].sum() / cov__[n][m].sum()
488
+ c = cov__[n][m].sum() / L[m].sum()
489
+ if q > qid and c > cov:
490
+ ok.append(n)
491
+
492
+ new_msas.append([msa[n] for n in ok])
493
+ new_mtxs.append([mtx[n] for n in ok])
494
+ return {"msas":new_msas, "deletion_matrices":new_mtxs}
495
+
496
+ def prep_filter(I, trim="", trim_inverse=False, cov=0, qid=0, verbose=True):
497
+ trim = re.sub("[^0-9A-Z,-]", "", trim.upper())
498
+ trim = re.sub(",+",",",trim)
499
+ trim = re.sub("^[,]+","",trim)
500
+ trim = re.sub("[,]+$","",trim)
501
+ if trim != "" or cov > 0 or qid > 0:
502
+ mod_I = dict(I)
503
+
504
+ if trim != "":
505
+ mod_I.update(trim_inputs(trim, mod_I["msas"], mod_I["deletion_matrices"],
506
+ mod_I["ori_sequence"], inverse=trim_inverse))
507
+
508
+ mod_I["homooligomers"] = [mod_I["homooligomers"][c] for c in mod_I["chains"]]
509
+ mod_I["sequence"] = mod_I["ori_sequence"].replace("/","").replace(":","")
510
+ mod_I["seqs"] = mod_I["ori_sequence"].replace("/","").split(":")
511
+ mod_I["full_sequence"] = "".join([s*h for s,h in zip(mod_I["seqs"], mod_I["homooligomers"])])
512
+ new_length = len(mod_I["full_sequence"])
513
+ if verbose:
514
+ print(f"total_length: '{new_length}' after trimming")
515
+
516
+ if cov > 0 or qid > 0:
517
+ mod_I.update(cov_qid_filter(mod_I["msas"], mod_I["deletion_matrices"],
518
+ mod_I["ori_sequence"], cov=cov/100, qid=qid/100))
519
+ return mod_I
520
+ else:
521
+ return I
522
+
523
+ #######################################################################################################################################
524
+ # prep features
525
+ #######################################################################################################################################
526
+
527
+ def prep_feats(I, clean=False):
528
+ def _placeholder_template_feats(num_templates_, num_res_):
529
+ return {
530
+ 'template_aatype': np.zeros([num_templates_, num_res_, 22], np.float32),
531
+ 'template_all_atom_masks': np.zeros([num_templates_, num_res_, 37], np.float32),
532
+ 'template_all_atom_positions': np.zeros([num_templates_, num_res_, 37, 3], np.float32),
533
+ 'template_domain_names': np.zeros([num_templates_], np.float32),
534
+ 'template_sum_probs': np.zeros([num_templates_], np.float32),
535
+ }
536
+ # delete old files
537
+ if clean:
538
+ for f in os.listdir(I["output_dir"]):
539
+ if "rank_" in f: os.remove(os.path.join(I["output_dir"], f))
540
+
541
+ if len(I["msas"]) == 0:
542
+ print("WARNING: no MSA found, switching to 'single_sequence' mode")
543
+ I["msas"].append([I["sequence"]])
544
+ I["deletion_matrices"].append([[0]*len(I["sequence"])])
545
+
546
+ # homooligomerize
547
+ lengths = [len(seq) for seq in I["seqs"]]
548
+ msas_mod, deletion_matrices_mod = cf.homooligomerize_heterooligomer(I["msas"], I["deletion_matrices"],
549
+ lengths, I["homooligomers"])
550
+ # define input features
551
+ num_res = len(I["full_sequence"])
552
+ feature_dict = {}
553
+ feature_dict.update(pipeline.make_sequence_features(I["full_sequence"], 'test', num_res))
554
+ feature_dict.update(pipeline.make_msa_features(msas_mod, deletion_matrices=deletion_matrices_mod))
555
+ feature_dict.update(_placeholder_template_feats(0, num_res))
556
+
557
+ # set chainbreaks
558
+ Ls = []
559
+ for seq,h in zip(I["ori_sequence"].split(":"), I["homooligomers"]):
560
+ Ls += [len(s) for s in seq.split("/")] * h
561
+ Ls_plot = []
562
+ for seq,h in zip(I["seqs"], I["homooligomers"]):
563
+ Ls_plot += [len(seq)] * h
564
+
565
+ feature_dict['residue_index'] = cf.chain_break(feature_dict['residue_index'], Ls)
566
+ feature_dict['Ls'] = Ls_plot
567
+ feature_dict['output_dir'] = I["output_dir"]
568
+ return feature_dict
569
+
570
+ def make_fixed_size(feat, runner):
571
+ '''pad input features'''
572
+ opt = runner["opt"]
573
+ cfg = runner["model"].config
574
+ shape_schema = {k:[None]+v for k,v in dict(cfg.data.eval.feat).items()}
575
+ pad_size_map = {
576
+ shape_placeholders.NUM_RES: opt["L"],
577
+ shape_placeholders.NUM_MSA_SEQ: cfg.data.eval.max_msa_clusters,
578
+ shape_placeholders.NUM_EXTRA_SEQ: cfg.data.common.max_extra_msa,
579
+ shape_placeholders.NUM_TEMPLATES: 0,
580
+ }
581
+ for k, v in feat.items():
582
+ # Don't transfer this to the accelerator.
583
+ if k == 'extra_cluster_assignment':
584
+ continue
585
+ shape = list(v.shape)
586
+ schema = shape_schema[k]
587
+ assert len(shape) == len(schema), (
588
+ f'Rank mismatch between shape and shape schema for {k}: '
589
+ f'{shape} vs {schema}')
590
+ pad_size = [pad_size_map.get(s2, None) or s1 for (s1, s2) in zip(shape, schema)]
591
+ padding = [(0, p - tf.shape(v)[i]) for i, p in enumerate(pad_size)]
592
+ if padding:
593
+ feat[k] = tf.pad(v, padding, name=f'pad_to_fixed_{k}')
594
+ feat[k].set_shape(pad_size)
595
+ return {k:np.asarray(v) for k,v in feat.items()}
596
+
597
+ #######################################################################################################################################
598
+ # run alphafold
599
+ #######################################################################################################################################
600
+
601
+ def clear_mem(device=None):
602
+ '''remove all data from device'''
603
+ backend = jax.lib.xla_bridge.get_backend(device)
604
+ if hasattr(backend,'live_buffers'):
605
+ for buf in backend.live_buffers():
606
+ buf.delete()
607
+
608
+ OPT_DEFAULT = {"N":None, "L":None,
609
+ "use_ptm":True, "use_turbo":True,
610
+ "max_recycles":3, "tol":0, "num_ensemble":1,
611
+ "max_msa_clusters":512, "max_extra_msa":1024,
612
+ "is_training":False}
613
+
614
+ def prep_model_runner(opt=None, model_name="model_5", old_runner=None, params_loc='./alphafold/data'):
615
+
616
+ # setup the [opt]ions
617
+ if opt is None:
618
+ opt = OPT_DEFAULT.copy()
619
+ else:
620
+ for k in OPT_DEFAULT:
621
+ if k not in opt: opt[k] = OPT_DEFAULT[k]
622
+
623
+ # if old_runner not defined or [opt]ions changed, start new runner
624
+ if old_runner is None or old_runner["opt"] != opt:
625
+ clear_mem()
626
+ name = f"{model_name}_ptm" if opt["use_ptm"] else model_name
627
+ cfg = config.model_config(name)
628
+
629
+ if opt["use_turbo"]:
630
+ if opt["N"] is None:
631
+ cfg.data.eval.max_msa_clusters = opt["max_msa_clusters"]
632
+ cfg.data.common.max_extra_msa = opt["max_extra_msa"]
633
+ else:
634
+ msa_clusters = min(opt["N"], opt["max_msa_clusters"])
635
+ cfg.data.eval.max_msa_clusters = msa_clusters
636
+ cfg.data.common.max_extra_msa = max(min(opt["N"] - msa_clusters, opt["max_extra_msa"]),1)
637
+
638
+ cfg.data.common.num_recycle = opt["max_recycles"]
639
+ cfg.model.num_recycle = opt["max_recycles"]
640
+ cfg.model.recycle_tol = opt["tol"]
641
+ cfg.data.eval.num_ensemble = opt["num_ensemble"]
642
+
643
+ params = data.get_model_haiku_params(name, params_loc)
644
+ return {"model":model.RunModel(cfg, params, is_training=opt["is_training"]), "opt":opt}
645
+ else:
646
+ return old_runner
647
+
648
+ def run_alphafold(feature_dict, opt=None, runner=None, num_models=5, num_samples=1, subsample_msa=True,
649
+ pad_feats=False, rank_by="pLDDT", show_images=True, params_loc='./alphafold/data', verbose=True):
650
+
651
+ def do_subsample_msa(F, random_seed=0):
652
+ '''subsample msa to avoid running out of memory'''
653
+ N = len(F["msa"])
654
+ L = len(F["residue_index"])
655
+ N_ = int(3E7/L)
656
+ if N > N_:
657
+ if verbose:
658
+ print(f"whhhaaa... too many sequences ({N}) subsampling to {N_}")
659
+ np.random.seed(random_seed)
660
+ idx = np.append(0,np.random.permutation(np.arange(1,N)))[:N_]
661
+ F_ = {}
662
+ F_["msa"] = F["msa"][idx]
663
+ F_["deletion_matrix_int"] = F["deletion_matrix_int"][idx]
664
+ F_["num_alignments"] = np.full_like(F["num_alignments"],N_)
665
+ for k in F.keys():
666
+ if k not in F_: F_[k] = F[k]
667
+ return F_
668
+ else:
669
+ return F
670
+
671
+ def parse_results(prediction_result, processed_feature_dict, r, t, num_res):
672
+ '''parse results and convert to numpy arrays'''
673
+
674
+ to_np = lambda a: np.asarray(a)
675
+ def class_to_np(c):
676
+ class dict2obj():
677
+ def __init__(self, d):
678
+ for k,v in d.items(): setattr(self, k, to_np(v))
679
+ return dict2obj(c.__dict__)
680
+
681
+ dist_bins = jax.numpy.append(0,prediction_result["distogram"]["bin_edges"])
682
+ dist_logits = prediction_result["distogram"]["logits"][:num_res,:][:,:num_res]
683
+ dist_mtx = dist_bins[dist_logits.argmax(-1)]
684
+ contact_mtx = jax.nn.softmax(dist_logits)[:,:,dist_bins < 8].sum(-1)
685
+
686
+ b_factors = prediction_result['plddt'][:,None] * prediction_result['structure_module']['final_atom_mask']
687
+ p = protein.from_prediction(processed_feature_dict, prediction_result, b_factors=b_factors)
688
+ plddt = prediction_result['plddt'][:num_res]
689
+ out = {"unrelaxed_protein": class_to_np(p),
690
+ "plddt": to_np(plddt),
691
+ "pLDDT": to_np(plddt.mean()),
692
+ "dists": to_np(dist_mtx),
693
+ "adj": to_np(contact_mtx),
694
+ "recycles":to_np(r),
695
+ "tol":to_np(t)}
696
+ if "ptm" in prediction_result:
697
+ out["pae"] = to_np(prediction_result['predicted_aligned_error'][:num_res,:][:,:num_res])
698
+ out["pTMscore"] = to_np(prediction_result['ptm'])
699
+ return out
700
+
701
+ num_res = len(feature_dict["residue_index"])
702
+
703
+ # if [opt]ions not defined
704
+ if opt is None:
705
+ opt = OPT_DEFAULT.copy()
706
+ opt["N"] = len(feature_dict["msa"])
707
+ opt["L"] = num_res
708
+ else:
709
+ for k in OPT_DEFAULT.keys():
710
+ if k not in opt: opt[k] = OPT_DEFAULT[k]
711
+
712
+ model_names = ['model_1', 'model_2', 'model_3', 'model_4', 'model_5'][:num_models]
713
+ total = len(model_names) * num_samples
714
+ outs = {}
715
+
716
+ def do_report(key):
717
+ o = outs[key]
718
+ if verbose:
719
+ line = f"{key} recycles:{o['recycles']} tol:{o['tol']:.2f} pLDDT:{o['pLDDT']:.2f}"
720
+ if 'pTMscore' in o:
721
+ line += f" pTMscore:{o['pTMscore']:.2f}"
722
+ print(line)
723
+ if show_images:
724
+ fig = cf.plot_protein(o['unrelaxed_protein'], Ls=feature_dict["Ls"], dpi=100)
725
+ plt.show()
726
+ tmp_pdb_path = os.path.join(feature_dict["output_dir"],f'unranked_{key}_unrelaxed.pdb')
727
+ pdb_lines = protein.to_pdb(o['unrelaxed_protein'])
728
+ with open(tmp_pdb_path, 'w') as f: f.write(pdb_lines)
729
+
730
+ disable_tqdm = not verbose
731
+ with tqdm.notebook.tqdm(total=total, bar_format=TQDM_BAR_FORMAT, disable=disable_tqdm) as pbar:
732
+ if opt["use_turbo"]:
733
+ if runner is None:
734
+ runner = prep_model_runner(opt,params_loc=params_loc)
735
+
736
+ # go through each random_seed
737
+ for seed in range(num_samples):
738
+ # prep input features
739
+ feat = do_subsample_msa(feature_dict, random_seed=seed) if subsample_msa else feature_dict
740
+ processed_feature_dict = runner["model"].process_features(feat, random_seed=seed)
741
+ if pad_feats:
742
+ processed_feature_dict = make_fixed_size(processed_feature_dict, runner)
743
+
744
+ # go through each model
745
+ for num, model_name in enumerate(model_names):
746
+ name = model_name+"_ptm" if opt["use_ptm"] else model_name
747
+ key = f"{name}_seed_{seed}"
748
+ pbar.set_description(f'Running {key}')
749
+
750
+ # replace model parameters
751
+ params = data.get_model_haiku_params(name, params_loc)
752
+ for k in runner["model"].params.keys():
753
+ runner["model"].params[k] = params[k]
754
+
755
+ # predict
756
+ prediction_result, (r, t) = runner["model"].predict(processed_feature_dict, random_seed=seed)
757
+ outs[key] = parse_results(prediction_result, processed_feature_dict, r=r, t=t, num_res=num_res)
758
+
759
+ # cleanup
760
+ del prediction_result, params, r, t
761
+
762
+ # report
763
+ do_report(key)
764
+ pbar.update(n=1)
765
+
766
+ # cleanup
767
+ del processed_feature_dict
768
+ if subsample_msa: del feat
769
+
770
+ else:
771
+ # go through each model
772
+ for num, model_name in enumerate(model_names):
773
+ name = model_name+"_ptm" if opt["use_ptm"] else model_name
774
+ model_runner = prep_model_runner(opt, model_name=model_name, params_loc=params_loc)["model"]
775
+
776
+ # go through each random_seed
777
+ for seed in range(num_samples):
778
+ key = f"{name}_seed_{seed}"
779
+ pbar.set_description(f'Running {key}')
780
+ processed_feature_dict = model_runner.process_features(feature_dict, random_seed=seed)
781
+
782
+ # predict
783
+ prediction_result, (r, t) = model_runner.predict(processed_feature_dict, random_seed=seed)
784
+ outs[key] = parse_results(prediction_result, processed_feature_dict, r=r, t=t, num_res=num_res)
785
+
786
+ # cleanup
787
+ del processed_feature_dict, prediction_result, r, t
788
+
789
+ # report
790
+ do_report(key)
791
+ pbar.update(n=1)
792
+
793
+ # cleanup
794
+ del model_runner
795
+
796
+ # Find the best model according to the mean pLDDT.
797
+ model_rank = list(outs.keys())
798
+ model_rank = [model_rank[i] for i in np.argsort([outs[x][rank_by] for x in model_rank])[::-1]]
799
+
800
+ # Write out the prediction
801
+ for n,key in enumerate(model_rank):
802
+ prefix = f"rank_{n+1}_{key}"
803
+ pred_output_path = os.path.join(feature_dict["output_dir"],f'{prefix}_unrelaxed.pdb')
804
+ fig = cf.plot_protein(outs[key]["unrelaxed_protein"], Ls=feature_dict["Ls"], dpi=200)
805
+ plt.savefig(os.path.join(feature_dict["output_dir"],f'{prefix}.png'), bbox_inches = 'tight')
806
+ plt.close(fig)
807
+ pdb_lines = protein.to_pdb(outs[key]["unrelaxed_protein"])
808
+ with open(pred_output_path, 'w') as f:
809
+ f.write(pdb_lines)
810
+
811
+ tmp_pdb_path = os.path.join(feature_dict["output_dir"],f'unranked_{key}_unrelaxed.pdb')
812
+ if os.path.isfile(tmp_pdb_path):
813
+ os.remove(tmp_pdb_path)
814
+
815
+ ############################################################
816
+ if verbose:
817
+ print(f"model rank based on {rank_by}")
818
+ for n,key in enumerate(model_rank):
819
+ print(f"rank_{n+1}_{key} {rank_by}:{outs[key][rank_by]:.2f}")
820
+
821
+ return outs, model_rank
data/beta/config.patch ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ --- /usr/local/lib/python3.7/dist-packages/alphafold/model/config.py 2021-08-01 22:46:44.442240295 +0000
2
+ +++ config.py 2021-08-01 22:52:08.519886454 +0000
3
+ @@ -397,6 +397,7 @@
4
+ },
5
+ },
6
+ 'num_recycle': 3,
7
+ + 'recycle_tol': 0.0,
8
+ 'resample_msa_in_recycling': True
9
+ },
10
+ })
data/beta/convert_256_to_384_rep.ipynb ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "authorship_tag": "ABX9TyMxPLX4u9e10BdDErRiKV+Y",
8
+ "include_colab_link": true
9
+ },
10
+ "kernelspec": {
11
+ "name": "python3",
12
+ "display_name": "Python 3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ }
17
+ },
18
+ "cells": [
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {
22
+ "id": "view-in-github",
23
+ "colab_type": "text"
24
+ },
25
+ "source": [
26
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/convert_256_to_384_rep.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "execution_count": null,
32
+ "metadata": {
33
+ "id": "SW7PGft_TTOL"
34
+ },
35
+ "outputs": [],
36
+ "source": [
37
+ "import os\n",
38
+ "if not os.path.isdir(\"params\"):\n",
39
+ " print(\"downloading weights...\")\n",
40
+ " os.system(\"mkdir params\")\n",
41
+ " os.system(\"apt-get install aria2 -qq\")\n",
42
+ " os.system(\"aria2c -q -x 16 https://storage.googleapis.com/alphafold/alphafold_params_2022-12-06.tar\")\n",
43
+ " os.system(\"tar -xf alphafold_params_2022-12-06.tar -C params\")"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "source": [
49
+ "import numpy as np\n",
50
+ "import pickle\n",
51
+ "\n",
52
+ "\n",
53
+ "example = \"test_a5e17_all_rank_001_alphafold2_ptm_model_3_seed_000.pickle\"\n",
54
+ "with open(example,\"rb\") as handle:\n",
55
+ " data = pickle.load(handle)\n",
56
+ "\n",
57
+ "model_num = example.split(\"_\")[-3]\n",
58
+ "if \"multimer_v3\" in example:\n",
59
+ " model_type = \"_multimer_v3\"\n",
60
+ "elif \"ptm\" in example:\n",
61
+ " model_type = \"_ptm\"\n",
62
+ "else:\n",
63
+ " model_type = \"\"\n",
64
+ "print(model_type, model_num)\n",
65
+ "model_params = np.load(f\"params/params_model_{model_num}{model_type}.npz\")\n",
66
+ "w = model_params['alphafold/alphafold_iteration/evoformer/single_activations//weights']\n",
67
+ "b = model_params['alphafold/alphafold_iteration/evoformer/single_activations//bias']\n",
68
+ "single_rep_256 = data[\"representations\"][\"single\"]\n",
69
+ "single_rep_384 = data[\"representations\"][\"single\"] @ w + b\n",
70
+ "\n",
71
+ "print(single_rep_256.shape, single_rep_384.shape)"
72
+ ],
73
+ "metadata": {
74
+ "colab": {
75
+ "base_uri": "https://localhost:8080/"
76
+ },
77
+ "id": "KXV8XWuuT0pN",
78
+ "outputId": "02c3003e-e72c-4e70-cb8c-7625def016d6"
79
+ },
80
+ "execution_count": null,
81
+ "outputs": [
82
+ {
83
+ "output_type": "stream",
84
+ "name": "stdout",
85
+ "text": [
86
+ "ptm 3\n",
87
+ "(59, 256) (59, 384)\n"
88
+ ]
89
+ }
90
+ ]
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "source": [],
95
+ "metadata": {
96
+ "id": "HPEnv_C3td-D"
97
+ },
98
+ "execution_count": null,
99
+ "outputs": []
100
+ }
101
+ ]
102
+ }
data/beta/folding.patch ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- /content/alphafold_copy/alphafold/model/folding.py 2022-06-16 23:22:42.489230552 +0000
2
+ +++ /content/alphafold/alphafold/model/folding.py 2022-06-16 23:46:03.017505449 +0000
3
+ @@ -440,21 +440,17 @@
4
+ name='pair_layer_norm')(
5
+ representations['pair'])
6
+
7
+ - outputs = []
8
+ - safe_keys = safe_key.split(c.num_layer)
9
+ - for sub_key in safe_keys:
10
+ - activations, output = fold_iteration(
11
+ - activations,
12
+ - initial_act=initial_act,
13
+ - static_feat_2d=act_2d,
14
+ - safe_key=sub_key,
15
+ - sequence_mask=sequence_mask,
16
+ - update_affine=True,
17
+ - is_training=is_training,
18
+ - aatype=batch['aatype'])
19
+ - outputs.append(output)
20
+ + def fold_iter(act, key):
21
+ + return fold_iteration(act, initial_act=initial_act,
22
+ + static_feat_2d=act_2d,
23
+ + safe_key=prng.SafeKey(key),
24
+ + sequence_mask=sequence_mask,
25
+ + update_affine=True,
26
+ + is_training=is_training,
27
+ + aatype=batch['aatype'])
28
+ + keys = jax.random.split(safe_key.get(), c.num_layer)
29
+ + activations, output = hk.scan(fold_iter, activations, keys)
30
+
31
+ - output = jax.tree_map(lambda *x: jnp.stack(x), *outputs)
32
+ # Include the activations in the output dict for use by the LDDT-Head.
33
+ output['act'] = activations['act']
34
+
data/beta/mapping.patch ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- /content/alphafold_old/alphafold/model/mapping.py 2022-09-06 22:48:51.735105962 +0000
2
+ +++ /content/alphafold/alphafold/model/mapping.py 2022-09-06 22:55:15.646553551 +0000
3
+ @@ -46,11 +46,11 @@
4
+
5
+
6
+ def _expand_axes(axes, values, name='sharded_apply'):
7
+ - values_tree_def = jax.tree_flatten(values)[1]
8
+ + values_tree_def = jax.tree_util.tree_flatten(values)[1]
9
+ flat_axes = jax.api_util.flatten_axes(name, values_tree_def, axes)
10
+ # Replace None's with PROXY
11
+ flat_axes = [PROXY if x is None else x for x in flat_axes]
12
+ - return jax.tree_unflatten(values_tree_def, flat_axes)
13
+ + return jax.tree_util.tree_unflatten(values_tree_def, flat_axes)
14
+
15
+
16
+ def sharded_map(
17
+ @@ -120,8 +120,8 @@
18
+ # Expand in axes and Determine Loop range
19
+ in_axes_ = _expand_axes(in_axes, args)
20
+
21
+ - in_sizes = jax.tree_multimap(_maybe_get_size, args, in_axes_)
22
+ - flat_sizes = jax.tree_flatten(in_sizes)[0]
23
+ + in_sizes = jax.tree_map(_maybe_get_size, args, in_axes_)
24
+ + flat_sizes = jax.tree_util.tree_flatten(in_sizes)[0]
25
+ in_size = max(flat_sizes)
26
+ assert all(i in {in_size, -1} for i in flat_sizes)
27
+
28
+ @@ -132,7 +132,7 @@
29
+ last_shard_size = shard_size if last_shard_size == 0 else last_shard_size
30
+
31
+ def apply_fun_to_slice(slice_start, slice_size):
32
+ - input_slice = jax.tree_multimap(
33
+ + input_slice = jax.tree_map(
34
+ lambda array, axis: _maybe_slice(array, slice_start, slice_size, axis
35
+ ), args, in_axes_)
36
+ return fun(*input_slice)
37
+ @@ -153,7 +153,7 @@
38
+ shard_shape[axis] * num_extra_shards +
39
+ remainder_shape[axis],) + shard_shape[axis + 1:]
40
+
41
+ - out_shapes = jax.tree_multimap(make_output_shape, out_axes_, shard_shapes,
42
+ + out_shapes = jax.tree_map(make_output_shape, out_axes_, shard_shapes,
43
+ out_shapes)
44
+
45
+ # Calls dynamic Update slice with different argument order
46
+ @@ -165,7 +165,7 @@
47
+ slice_out = apply_fun_to_slice(slice_start, slice_size)
48
+ update_slice = partial(
49
+ dynamic_update_slice_in_dim, i=slice_start)
50
+ - return jax.tree_multimap(update_slice, outputs, slice_out, out_axes_)
51
+ + return jax.tree_map(update_slice, outputs, slice_out, out_axes_)
52
+
53
+ def scan_iteration(outputs, i):
54
+ new_outputs = compute_shard(outputs, i, shard_size)
55
+ @@ -176,7 +176,7 @@
56
+ def allocate_buffer(dtype, shape):
57
+ return jnp.zeros(shape, dtype=dtype)
58
+
59
+ - outputs = jax.tree_multimap(allocate_buffer, out_dtypes, out_shapes)
60
+ + outputs = jax.tree_map(allocate_buffer, out_dtypes, out_shapes)
61
+
62
+ if slice_starts.shape[0] > 0:
63
+ outputs, _ = hk.scan(scan_iteration, outputs, slice_starts)
data/beta/model.patch ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- /content/alphafold_copy/alphafold/model/model.py 2022-06-21 02:56:28.903256585 +0000
2
+ +++ /content/alphafold/alphafold/model/model.py 2022-06-21 03:08:21.392362049 +0000
3
+ @@ -50,7 +50,8 @@
4
+
5
+ def __init__(self,
6
+ config: ml_collections.ConfigDict,
7
+ - params: Optional[Mapping[str, Mapping[str, np.ndarray]]] = None):
8
+ + params: Optional[Mapping[str, Mapping[str, np.ndarray]]] = None,
9
+ + is_training = False):
10
+ self.config = config
11
+ self.params = params
12
+
13
+ @@ -58,7 +59,7 @@
14
+ model = modules.AlphaFold(self.config.model)
15
+ return model(
16
+ batch,
17
+ - is_training=False,
18
+ + is_training=is_training,
19
+ compute_loss=False,
20
+ ensemble_representations=True)
21
+
22
+ @@ -117,7 +118,7 @@
23
+ logging.info('Output shape was %s', shape)
24
+ return shape
25
+
26
+ - def predict(self, feat: features.FeatureDict) -> Mapping[str, Any]:
27
+ + def predict(self, feat: features.FeatureDict, random_seed=0) -> Mapping[str, Any]:
28
+ """Makes a prediction by inferencing the model on the provided features.
29
+
30
+ Args:
31
+ @@ -128,14 +129,28 @@
32
+ A dictionary of model outputs.
33
+ """
34
+ self.init_params(feat)
35
+ - logging.info('Running predict with shape(feat) = %s',
36
+ - tree.map_structure(lambda x: x.shape, feat))
37
+ - result = self.apply(self.params, jax.random.PRNGKey(0), feat)
38
+ - # This block is to ensure benchmark timings are accurate. Some blocking is
39
+ - # already happening when computing get_confidence_metrics, and this ensures
40
+ - # all outputs are blocked on.
41
+ - jax.tree_map(lambda x: x.block_until_ready(), result)
42
+ - result.update(get_confidence_metrics(result))
43
+ - logging.info('Output shape was %s',
44
+ - tree.map_structure(lambda x: x.shape, result))
45
+ - return result
46
+ + logging.info('Running predict with shape(feat) = %s', tree.map_structure(lambda x: x.shape, feat))
47
+ +
48
+ + aatype = feat["aatype"]
49
+ + num_iters = self.config.model.num_recycle + 1
50
+ + num_ensemble = self.config.data.eval.num_ensemble
51
+ + L = aatype.shape[1]
52
+ + result = {"prev":{'prev_msa_first_row': np.zeros([L,256]),
53
+ + 'prev_pair': np.zeros([L,L,128]),
54
+ + 'prev_pos': np.zeros([L,37,3])}}
55
+ +
56
+ + r = 0
57
+ + key = jax.random.PRNGKey(random_seed)
58
+ + while r < num_iters:
59
+ + s = r * num_ensemble
60
+ + e = (r+1) * num_ensemble
61
+ + sub_feat = jax.tree_map(lambda x:x[s:e], feat)
62
+ + sub_feat["prev"] = result["prev"]
63
+ + result, _ = self.apply(self.params, key, sub_feat)
64
+ + del sub_feat
65
+ + confidences = get_confidence_metrics(result)
66
+ + result.update(confidences)
67
+ + r += 1
68
+ +
69
+ + logging.info('Output shape was %s', tree.map_structure(lambda x: x.shape, result))
70
+ + return result, (r-1,0)
data/beta/modules.patch ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- /content/alphafold_copy/alphafold/model/modules.py 2022-06-16 23:22:42.489230552 +0000
2
+ +++ /content/alphafold/alphafold/model/modules.py 2022-06-16 23:33:50.394462860 +0000
3
+ @@ -322,7 +322,7 @@
4
+ recycle_idx,
5
+ compute_loss=compute_loss):
6
+ if self.config.resample_msa_in_recycling:
7
+ - num_ensemble = batch_size // (self.config.num_recycle + 1)
8
+ + num_ensemble = batch_size
9
+ def slice_recycle_idx(x):
10
+ start = recycle_idx * num_ensemble
11
+ size = num_ensemble
12
+ @@ -341,53 +341,16 @@
13
+ compute_loss=compute_loss,
14
+ ensemble_representations=ensemble_representations)
15
+
16
+ - if self.config.num_recycle:
17
+ - emb_config = self.config.embeddings_and_evoformer
18
+ - prev = {
19
+ - 'prev_pos': jnp.zeros(
20
+ - [num_residues, residue_constants.atom_type_num, 3]),
21
+ - 'prev_msa_first_row': jnp.zeros(
22
+ - [num_residues, emb_config.msa_channel]),
23
+ - 'prev_pair': jnp.zeros(
24
+ - [num_residues, num_residues, emb_config.pair_channel]),
25
+ - }
26
+ -
27
+ - if 'num_iter_recycling' in batch:
28
+ - # Training time: num_iter_recycling is in batch.
29
+ - # The value for each ensemble batch is the same, so arbitrarily taking
30
+ - # 0-th.
31
+ - num_iter = batch['num_iter_recycling'][0]
32
+ -
33
+ - # Add insurance that we will not run more
34
+ - # recyclings than the model is configured to run.
35
+ - num_iter = jnp.minimum(num_iter, self.config.num_recycle)
36
+ - else:
37
+ - # Eval mode or tests: use the maximum number of iterations.
38
+ - num_iter = self.config.num_recycle
39
+ -
40
+ - body = lambda x: (x[0] + 1, # pylint: disable=g-long-lambda
41
+ - get_prev(do_call(x[1], recycle_idx=x[0],
42
+ - compute_loss=False)))
43
+ - if hk.running_init():
44
+ - # When initializing the Haiku module, run one iteration of the
45
+ - # while_loop to initialize the Haiku modules used in `body`.
46
+ - _, prev = body((0, prev))
47
+ - else:
48
+ - _, prev = hk.while_loop(
49
+ - lambda x: x[0] < num_iter,
50
+ - body,
51
+ - (0, prev))
52
+ - else:
53
+ - prev = {}
54
+ - num_iter = 0
55
+ + emb_config = self.config.embeddings_and_evoformer
56
+ + ret = do_call(prev=batch.pop("prev"), recycle_idx=0)
57
+ + ret["prev"] = get_prev(ret)
58
+
59
+ - ret = do_call(prev=prev, recycle_idx=num_iter)
60
+ if compute_loss:
61
+ ret = ret[0], [ret[1]]
62
+
63
+ if not return_representations:
64
+ del (ret[0] if compute_loss else ret)['representations'] # pytype: disable=unsupported-operands
65
+ - return ret
66
+ + return ret, (None, None)
67
+
68
+
69
+ class TemplatePairStack(hk.Module):
70
+ @@ -1730,9 +1693,7 @@
71
+ True,
72
+ name='prev_msa_first_row_norm')(
73
+ batch['prev_msa_first_row'])
74
+ - msa_activations = jax.ops.index_add(msa_activations, 0,
75
+ - prev_msa_first_row)
76
+ -
77
+ + msa_activations = msa_activations.at[0].add(prev_msa_first_row)
78
+ if 'prev_pair' in batch:
79
+ pair_activations += hk.LayerNorm([-1],
80
+ True,
data/beta/omegafold.ipynb ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "omegafold.ipynb",
7
+ "provenance": [],
8
+ "include_colab_link": true
9
+ },
10
+ "kernelspec": {
11
+ "name": "python3",
12
+ "display_name": "Python 3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ },
17
+ "accelerator": "GPU",
18
+ "gpuClass": "standard"
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {
24
+ "id": "view-in-github",
25
+ "colab_type": "text"
26
+ },
27
+ "source": [
28
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/omegafold.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "source": [
34
+ "#**OmegaFold**\n",
35
+ "for more details see: [Github](https://github.com/HeliXonProtein/OmegaFold), [Preprint](https://www.biorxiv.org/content/10.1101/2022.07.21.500999v1)\n",
36
+ "\n",
37
+ "#### **Tips and Instructions**\n",
38
+ "- click the little ▶ play icon to the left of each cell below.\n",
39
+ "- use \"/\" to specify chainbreaks, (eg. sequence=\"AAA/AAA\")\n",
40
+ "- for homo-oligomeric predictions, set copies > 1\n"
41
+ ],
42
+ "metadata": {
43
+ "id": "qEgffIPOyEgk"
44
+ }
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "execution_count": null,
49
+ "metadata": {
50
+ "cellView": "form",
51
+ "id": "oVkGfduwiAkw"
52
+ },
53
+ "outputs": [],
54
+ "source": [
55
+ "#@markdown ##Install\n",
56
+ "import os,sys,re\n",
57
+ "from IPython.utils import io\n",
58
+ "if \"SETUP_DONE\" not in dir():\n",
59
+ " import torch\n",
60
+ " device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
61
+ " with io.capture_output() as captured:\n",
62
+ " if not os.path.isdir(\"OmegaFold\"):\n",
63
+ " %shell git clone --branch beta --quiet https://github.com/sokrypton/OmegaFold.git\n",
64
+ " # %shell cd OmegaFold; pip -q install -r requirements.txt\n",
65
+ " %shell pip -q install py3Dmol biopython==1.81\n",
66
+ " %shell apt-get install aria2 -qq > /dev/null\n",
67
+ " %shell aria2c -q -x 16 https://helixon.s3.amazonaws.com/release1.pt\n",
68
+ " %shell mkdir -p ~/.cache/omegafold_ckpt\n",
69
+ " %shell mv release1.pt ~/.cache/omegafold_ckpt/model.pt\n",
70
+ " SETUP_DONE = True"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "source": [
76
+ "#@markdown ##Run **OmegaFold**\n",
77
+ "from string import ascii_uppercase, ascii_lowercase\n",
78
+ "import hashlib\n",
79
+ "\n",
80
+ "def get_hash(x): return hashlib.sha1(x.encode()).hexdigest()\n",
81
+ "alphabet_list = list(ascii_uppercase+ascii_lowercase)\n",
82
+ "\n",
83
+ "jobname = \"test\" #@param {type:\"string\"}\n",
84
+ "jobname = re.sub(r'\\W+', '', jobname)[:50]\n",
85
+ "\n",
86
+ "sequence = \"PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK\" #@param {type:\"string\"}\n",
87
+ "sequence = re.sub(\"[^A-Z:]\", \"\", sequence.replace(\"/\",\":\").upper())\n",
88
+ "sequence = re.sub(\":+\",\":\",sequence)\n",
89
+ "sequence = re.sub(\"^[:]+\",\"\",sequence)\n",
90
+ "sequence = re.sub(\"[:]+$\",\"\",sequence)\n",
91
+ "\n",
92
+ "copies = 1 #@param {type:\"integer\"}\n",
93
+ "sequence = \":\".join([sequence] * copies)\n",
94
+ "#@markdown **Advanced Options**\n",
95
+ "num_cycle = 4 #@param [\"1\", \"2\", \"4\", \"8\", \"16\", \"32\"] {type:\"raw\"}\n",
96
+ "offset_rope = False #@param {type:\"boolean\"}\n",
97
+ "\n",
98
+ "ID = jobname+\"_\"+get_hash(sequence)[:5]\n",
99
+ "seqs = sequence.split(\":\")\n",
100
+ "lengths = [len(s) for s in seqs]\n",
101
+ "\n",
102
+ "def get_subbatch_size(L):\n",
103
+ " if L < 500: return 500\n",
104
+ " if L < 1000: return 200\n",
105
+ " return 150\n",
106
+ "subbatch_size = get_subbatch_size(sum(lengths))\n",
107
+ "\n",
108
+ "u_seqs = list(set(seqs))\n",
109
+ "\n",
110
+ "if len(seqs) == 1: mode = \"mono\"\n",
111
+ "elif len(u_seqs) == 1: mode = \"homo\"\n",
112
+ "else: mode = \"hetero\"\n",
113
+ "\n",
114
+ "with open(f\"{ID}.fasta\",\"w\") as out:\n",
115
+ " out.write(f\">{ID}\\n{sequence}\\n\")\n",
116
+ "\n",
117
+ "%shell python OmegaFold/main.py --offset_rope={offset_rope} --device={device} --subbatch_size={subbatch_size} --num_cycle={num_cycle} {ID}.fasta .\n",
118
+ "\n",
119
+ "def renum_pdb_str(pdb_str, Ls=None, renum=True, offset=1):\n",
120
+ " if Ls is not None:\n",
121
+ " L_init = 0\n",
122
+ " new_chain = {}\n",
123
+ " for L,c in zip(Ls, alphabet_list):\n",
124
+ " new_chain.update({i:c for i in range(L_init,L_init+L)})\n",
125
+ " L_init += L \n",
126
+ "\n",
127
+ " n,num,pdb_out = 0,offset,[]\n",
128
+ " resnum_ = None\n",
129
+ " chain_ = None\n",
130
+ " new_chain_ = new_chain[0]\n",
131
+ " for line in pdb_str.split(\"\\n\"):\n",
132
+ " if line[:4] == \"ATOM\":\n",
133
+ " chain = line[21:22]\n",
134
+ " resnum = int(line[22:22+5])\n",
135
+ " if resnum_ is None: resnum_ = resnum\n",
136
+ " if chain_ is None: chain_ = chain\n",
137
+ " if resnum != resnum_ or chain != chain_:\n",
138
+ " num += (resnum - resnum_) \n",
139
+ " n += 1\n",
140
+ " resnum_,chain_ = resnum,chain\n",
141
+ " if Ls is not None:\n",
142
+ " if new_chain[n] != new_chain_:\n",
143
+ " num = offset\n",
144
+ " new_chain_ = new_chain[n]\n",
145
+ " N = num if renum else resnum\n",
146
+ " if Ls is None: pdb_out.append(\"%s%4i%s\" % (line[:22],N,line[26:]))\n",
147
+ " else: pdb_out.append(\"%s%s%4i%s\" % (line[:21],new_chain[n],N,line[26:])) \n",
148
+ " return \"\\n\".join(pdb_out)\n",
149
+ "\n",
150
+ "pdb_str = renum_pdb_str(open(f\"{ID}.pdb\",'r').read(), Ls=lengths)\n",
151
+ "with open(f\"{ID}.pdb\",\"w\") as out:\n",
152
+ " out.write(pdb_str)"
153
+ ],
154
+ "metadata": {
155
+ "cellView": "form",
156
+ "id": "CFCwEAa2oZEN"
157
+ },
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "source": [
164
+ "#@markdown ##Display\n",
165
+ "import py3Dmol\n",
166
+ "\n",
167
+ "\n",
168
+ "pymol_color_list = [\"#33ff33\",\"#00ffff\",\"#ff33cc\",\"#ffff00\",\"#ff9999\",\"#e5e5e5\",\"#7f7fff\",\"#ff7f00\",\n",
169
+ " \"#7fff7f\",\"#199999\",\"#ff007f\",\"#ffdd5e\",\"#8c3f99\",\"#b2b2b2\",\"#007fff\",\"#c4b200\",\n",
170
+ " \"#8cb266\",\"#00bfbf\",\"#b27f7f\",\"#fcd1a5\",\"#ff7f7f\",\"#ffbfdd\",\"#7fffff\",\"#ffff7f\",\n",
171
+ " \"#00ff7f\",\"#337fcc\",\"#d8337f\",\"#bfff3f\",\"#ff7fff\",\"#d8d8ff\",\"#3fffbf\",\"#b78c4c\",\n",
172
+ " \"#339933\",\"#66b2b2\",\"#ba8c84\",\"#84bf00\",\"#b24c66\",\"#7f7f7f\",\"#3f3fa5\",\"#a5512b\"]\n",
173
+ "\n",
174
+ "def show_pdb(pdb_str, show_sidechains=False, show_mainchains=False,\n",
175
+ " color=\"pLDDT\", chains=None, vmin=50, vmax=90,\n",
176
+ " size=(800,480), hbondCutoff=4.0,\n",
177
+ " Ls=None,\n",
178
+ " animate=False):\n",
179
+ " \n",
180
+ " if chains is None:\n",
181
+ " chains = 1 if Ls is None else len(Ls)\n",
182
+ " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js', width=size[0], height=size[1])\n",
183
+ " if animate:\n",
184
+ " view.addModelsAsFrames(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
185
+ " else:\n",
186
+ " view.addModel(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
187
+ " if color == \"pLDDT\":\n",
188
+ " view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':vmin,'max':vmax}}})\n",
189
+ " elif color == \"rainbow\":\n",
190
+ " view.setStyle({'cartoon': {'color':'spectrum'}})\n",
191
+ " elif color == \"chain\":\n",
192
+ " for n,chain,color in zip(range(chains),alphabet_list,pymol_color_list):\n",
193
+ " view.setStyle({'chain':chain},{'cartoon': {'color':color}})\n",
194
+ " if show_sidechains:\n",
195
+ " BB = ['C','O','N']\n",
196
+ " HP = [\"ALA\",\"GLY\",\"VAL\",\"ILE\",\"LEU\",\"PHE\",\"MET\",\"PRO\",\"TRP\",\"CYS\",\"TYR\"]\n",
197
+ " view.addStyle({'and':[{'resn':[\"GLY\",\"PRO\"],'invert':True},{'atom':BB,'invert':True}]},\n",
198
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
199
+ " view.addStyle({'and':[{'resn':\"GLY\"},{'atom':'CA'}]},\n",
200
+ " {'sphere':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
201
+ " view.addStyle({'and':[{'resn':\"PRO\"},{'atom':['C','O'],'invert':True}]},\n",
202
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}}) \n",
203
+ " if show_mainchains:\n",
204
+ " BB = ['C','O','N','CA']\n",
205
+ " view.addStyle({'atom':BB},{'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
206
+ " view.zoomTo()\n",
207
+ " if animate: view.animate()\n",
208
+ " return view\n",
209
+ "\n",
210
+ "color = \"confidence\" #@param [\"confidence\", \"rainbow\", \"chain\"]\n",
211
+ "if color == \"confidence\": color = \"pLDDT\"\n",
212
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
213
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
214
+ "show_pdb(pdb_str, color=color, show_sidechains=show_sidechains, show_mainchains=show_mainchains,\n",
215
+ " Ls=lengths).show()"
216
+ ],
217
+ "metadata": {
218
+ "cellView": "form",
219
+ "id": "dHl9aS-HHFNQ"
220
+ },
221
+ "execution_count": null,
222
+ "outputs": []
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "source": [
227
+ "#@title Download prediction\n",
228
+ "from google.colab import files\n",
229
+ "files.download(f'{ID}.pdb')"
230
+ ],
231
+ "metadata": {
232
+ "cellView": "form",
233
+ "id": "12rxVAHSrmYQ"
234
+ },
235
+ "execution_count": null,
236
+ "outputs": []
237
+ }
238
+ ]
239
+ }
data/beta/omegafold_hacks.ipynb ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "omegafold_hacks.ipynb",
7
+ "provenance": [],
8
+ "include_colab_link": true
9
+ },
10
+ "kernelspec": {
11
+ "name": "python3",
12
+ "display_name": "Python 3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ },
17
+ "accelerator": "GPU",
18
+ "gpuClass": "standard"
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {
24
+ "id": "view-in-github",
25
+ "colab_type": "text"
26
+ },
27
+ "source": [
28
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/omegafold_hacks.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "source": [
34
+ "#**OmegaFold_hacks**\n",
35
+ "**WARNING** This is an experimental notebook that implements various hacks (unintended uses) of OmegaFold. It has not been optimized or benchmarked. Use at your own risk!\n",
36
+ "\n",
37
+ "For detail about the original model see: [Github](https://github.com/HeliXonProtein/OmegaFold), [Preprint](https://www.biorxiv.org/content/10.1101/2022.07.21.500999v1)\n",
38
+ "\n",
39
+ "\n",
40
+ "#### **Tips and Instructions**\n",
41
+ "- click the little ▶ play icon to the left of each cell below.\n",
42
+ "\n",
43
+ "#### **Experimental Options**\n",
44
+ "- use \"/\" to specify chainbreaks, (eg. sequence=\"AAA/AAA\")\n",
45
+ "- if confidence of prediction is low, try `use_real_msa` (currently only supported for monomeric and homo-oligomeric predictions)\n"
46
+ ],
47
+ "metadata": {
48
+ "id": "qEgffIPOyEgk"
49
+ }
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": null,
54
+ "metadata": {
55
+ "cellView": "form",
56
+ "id": "oVkGfduwiAkw"
57
+ },
58
+ "outputs": [],
59
+ "source": [
60
+ "#@markdown ##Install\n",
61
+ "import os,sys,re\n",
62
+ "from IPython.utils import io\n",
63
+ "if \"SETUP_DONE\" not in dir():\n",
64
+ " import torch\n",
65
+ " device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
66
+ " with io.capture_output() as captured:\n",
67
+ " if not os.path.isdir(\"OmegaFold\"):\n",
68
+ " %shell git clone --quiet https://github.com/sokrypton/OmegaFold.git\n",
69
+ " %shell cd OmegaFold; pip -q install -r requirements.txt\n",
70
+ " %shell pip -q install py3Dmol\n",
71
+ " %shell apt-get install aria2 -qq > /dev/null\n",
72
+ " %shell aria2c -q -x 16 https://helixon.s3.amazonaws.com/release1.pt\n",
73
+ " %shell mkdir -p ~/.cache/omegafold_ckpt\n",
74
+ " %shell mv release1.pt ~/.cache/omegafold_ckpt/model.pt\n",
75
+ " %shell wget -qnc https://github.com/soedinglab/hh-suite/releases/download/v3.3.0/hhsuite-3.3.0-SSE2-Linux.tar.gz\n",
76
+ " %shell tar xfz hhsuite-3.3.0-SSE2-Linux.tar.gz\n",
77
+ " %shell wget -qnc https://raw.githubusercontent.com/sokrypton/ColabFold/main/colabfold/colabfold.py\n",
78
+ " os.environ['PATH'] += \":/content/bin:/content/scripts\"\n",
79
+ " SETUP_DONE = True"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "source": [
85
+ "#@markdown ##Prep inputs\n",
86
+ "from string import ascii_uppercase, ascii_lowercase\n",
87
+ "import colabfold as cf\n",
88
+ "alphabet_list = list(ascii_uppercase+ascii_lowercase)\n",
89
+ "\n",
90
+ "sequence = \"PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK\" #@param {type:\"string\"}\n",
91
+ "jobname = \"test\" #@param {type:\"string\"}\n",
92
+ "\n",
93
+ "# filter inputs\n",
94
+ "sequence = re.sub(\"[^A-Z:/]\", \"\", sequence.upper())\n",
95
+ "sequence = re.sub(\":+\",\":\",sequence)\n",
96
+ "sequence = re.sub(\"/+\",\"/\",sequence)\n",
97
+ "sequence = re.sub(\"^[:/]+\",\"\",sequence)\n",
98
+ "sequence = re.sub(\"[:/]+$\",\"\",sequence)\n",
99
+ "jobname = re.sub(r'\\W+', '', jobname)[:50]\n",
100
+ "\n",
101
+ "num_msa = 16\n",
102
+ "use_real_msa = False #@param {type:\"boolean\"}\n",
103
+ "\n",
104
+ "sequence = re.sub(\"[^A-Z\\/\\:]\", \"\", sequence.upper()).replace(\"/\",\":\")\n",
105
+ "ID = jobname+\"_\"+cf.get_hash(sequence)[:5]\n",
106
+ "seqs = sequence.split(\":\")\n",
107
+ "lengths = [len(s) for s in seqs]\n",
108
+ "u_seqs = list(set(seqs))\n",
109
+ "\n",
110
+ "if len(seqs) == 1: mode = \"mono\"\n",
111
+ "elif len(u_seqs) == 1: mode = \"homo\"\n",
112
+ "else: mode = \"hetero\"\n",
113
+ "\n",
114
+ "if use_real_msa and mode == \"hetero\":\n",
115
+ " print(\"ERROR: the msa mode is currently not supported for hetero-multimers\")\n",
116
+ " use_real_msa = False\n",
117
+ "\n",
118
+ "if use_real_msa:\n",
119
+ " ID_ = cf.get_hash(seqs[0])[:5]\n",
120
+ " a3m_lines = cf.run_mmseqs2(seqs[0], ID_, filter=True)[0]\n",
121
+ " with open(f\"{ID}.a3m\",\"w\") as a3m:\n",
122
+ " a3m.write(a3m_lines)\n",
123
+ " \n",
124
+ " %shell hhfilter -v 0 -qid 30 -cov 75 -diff {num_msa} -i {ID}.a3m -o {ID}.fasta\n",
125
+ " \n",
126
+ " a3m_lines = open(f\"{ID}.fasta\",\"r\").readlines()\n",
127
+ " with open(f\"{ID}.fasta\",\"w\") as a3m:\n",
128
+ " n = 0\n",
129
+ " for a3m_line in a3m_lines:\n",
130
+ " if a3m_line.startswith(\">\"):\n",
131
+ " if n == 0:\n",
132
+ " a3m.write(f\">{ID}\\n\")\n",
133
+ " else:\n",
134
+ " a3m.write(a3m_line)\n",
135
+ " else:\n",
136
+ " a3m_line = \":\".join([a3m_line.rstrip()] * len(lengths))\n",
137
+ " a3m.write(f\"{a3m_line}\\n\")\n",
138
+ " n += 1\n",
139
+ " if n == num_msa: break\n",
140
+ " # add pseudo_msa\n",
141
+ " while n < num_msa:\n",
142
+ " a3m.write(f\">tmp\\n{sequence}\\n\")\n",
143
+ " n += 1\n",
144
+ "else:\n",
145
+ " with open(f\"{ID}.fasta\",\"w\") as out:\n",
146
+ " out.write(f\">{ID}\\n{sequence}\\n\")"
147
+ ],
148
+ "metadata": {
149
+ "cellView": "form",
150
+ "id": "CFCwEAa2oZEN"
151
+ },
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "source": [
158
+ "%%time \n",
159
+ "#@markdown ## Run OmegaFold\n",
160
+ "num_cycle = 4 #@param [\"1\", \"2\", \"4\", \"8\", \"16\", \"32\"] {type:\"raw\"}\n",
161
+ "\n",
162
+ "if use_real_msa:\n",
163
+ " %shell python ./OmegaFold/main.py --device={device} --num_cycle={num_cycle} --real_msa=1 {ID}.fasta .\n",
164
+ "else:\n",
165
+ " %shell python ./OmegaFold/main.py --device={device} --num_cycle={num_cycle} --num_pseudo_msa={num_msa-1} {ID}.fasta .\n",
166
+ "\n",
167
+ "def renum_pdb_str(pdb_str, Ls=None, renum=True, offset=1):\n",
168
+ " if Ls is not None:\n",
169
+ " L_init = 0\n",
170
+ " new_chain = {}\n",
171
+ " for L,c in zip(Ls, alphabet_list):\n",
172
+ " new_chain.update({i:c for i in range(L_init,L_init+L)})\n",
173
+ " L_init += L \n",
174
+ "\n",
175
+ " n,num,pdb_out = 0,offset,[]\n",
176
+ " resnum_ = None\n",
177
+ " chain_ = None\n",
178
+ " new_chain_ = new_chain[0]\n",
179
+ " for line in pdb_str.split(\"\\n\"):\n",
180
+ " if line[:4] == \"ATOM\":\n",
181
+ " chain = line[21:22]\n",
182
+ " resnum = int(line[22:22+5])\n",
183
+ " if resnum_ is None: resnum_ = resnum\n",
184
+ " if chain_ is None: chain_ = chain\n",
185
+ " if resnum != resnum_ or chain != chain_:\n",
186
+ " num += (resnum - resnum_) \n",
187
+ " n += 1\n",
188
+ " resnum_,chain_ = resnum,chain\n",
189
+ " if Ls is not None:\n",
190
+ " if new_chain[n] != new_chain_:\n",
191
+ " num = offset\n",
192
+ " new_chain_ = new_chain[n]\n",
193
+ " N = num if renum else resnum\n",
194
+ " if Ls is None: pdb_out.append(\"%s%4i%s\" % (line[:22],N,line[26:]))\n",
195
+ " else: pdb_out.append(\"%s%s%4i%s\" % (line[:21],new_chain[n],N,line[26:])) \n",
196
+ " return \"\\n\".join(pdb_out)\n",
197
+ "\n",
198
+ "pdb_str = renum_pdb_str(open(f\"{ID}.pdb\",'r').read(), Ls=lengths)\n",
199
+ "with open(f\"{ID}.pdb\",\"w\") as out:\n",
200
+ " out.write(pdb_str)"
201
+ ],
202
+ "metadata": {
203
+ "cellView": "form",
204
+ "id": "_tUY92JL28DS"
205
+ },
206
+ "execution_count": null,
207
+ "outputs": []
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "source": [
212
+ "#@markdown ##Display\n",
213
+ "import py3Dmol\n",
214
+ "\n",
215
+ "\n",
216
+ "pymol_color_list = [\"#33ff33\",\"#00ffff\",\"#ff33cc\",\"#ffff00\",\"#ff9999\",\"#e5e5e5\",\"#7f7fff\",\"#ff7f00\",\n",
217
+ " \"#7fff7f\",\"#199999\",\"#ff007f\",\"#ffdd5e\",\"#8c3f99\",\"#b2b2b2\",\"#007fff\",\"#c4b200\",\n",
218
+ " \"#8cb266\",\"#00bfbf\",\"#b27f7f\",\"#fcd1a5\",\"#ff7f7f\",\"#ffbfdd\",\"#7fffff\",\"#ffff7f\",\n",
219
+ " \"#00ff7f\",\"#337fcc\",\"#d8337f\",\"#bfff3f\",\"#ff7fff\",\"#d8d8ff\",\"#3fffbf\",\"#b78c4c\",\n",
220
+ " \"#339933\",\"#66b2b2\",\"#ba8c84\",\"#84bf00\",\"#b24c66\",\"#7f7f7f\",\"#3f3fa5\",\"#a5512b\"]\n",
221
+ "\n",
222
+ "def show_pdb(pdb_str, show_sidechains=False, show_mainchains=False,\n",
223
+ " color=\"pLDDT\", chains=None, vmin=50, vmax=90,\n",
224
+ " size=(800,480), hbondCutoff=4.0,\n",
225
+ " Ls=None,\n",
226
+ " animate=False):\n",
227
+ " \n",
228
+ " if chains is None:\n",
229
+ " chains = 1 if Ls is None else len(Ls)\n",
230
+ " view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js', width=size[0], height=size[1])\n",
231
+ " if animate:\n",
232
+ " view.addModelsAsFrames(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
233
+ " else:\n",
234
+ " view.addModel(pdb_str,'pdb',{'hbondCutoff':hbondCutoff})\n",
235
+ " if color == \"pLDDT\":\n",
236
+ " view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':vmin,'max':vmax}}})\n",
237
+ " elif color == \"rainbow\":\n",
238
+ " view.setStyle({'cartoon': {'color':'spectrum'}})\n",
239
+ " elif color == \"chain\":\n",
240
+ " for n,chain,color in zip(range(chains),alphabet_list,pymol_color_list):\n",
241
+ " view.setStyle({'chain':chain},{'cartoon': {'color':color}})\n",
242
+ " if show_sidechains:\n",
243
+ " BB = ['C','O','N']\n",
244
+ " HP = [\"ALA\",\"GLY\",\"VAL\",\"ILE\",\"LEU\",\"PHE\",\"MET\",\"PRO\",\"TRP\",\"CYS\",\"TYR\"]\n",
245
+ " view.addStyle({'and':[{'resn':[\"GLY\",\"PRO\"],'invert':True},{'atom':BB,'invert':True}]},\n",
246
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
247
+ " view.addStyle({'and':[{'resn':\"GLY\"},{'atom':'CA'}]},\n",
248
+ " {'sphere':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
249
+ " view.addStyle({'and':[{'resn':\"PRO\"},{'atom':['C','O'],'invert':True}]},\n",
250
+ " {'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}}) \n",
251
+ " if show_mainchains:\n",
252
+ " BB = ['C','O','N','CA']\n",
253
+ " view.addStyle({'atom':BB},{'stick':{'colorscheme':f\"WhiteCarbon\",'radius':0.3}})\n",
254
+ " view.zoomTo()\n",
255
+ " if animate: view.animate()\n",
256
+ " return view\n",
257
+ "\n",
258
+ "color = \"confidence\" #@param [\"confidence\", \"rainbow\", \"chain\"]\n",
259
+ "if color == \"confidence\": color = \"pLDDT\"\n",
260
+ "show_sidechains = False #@param {type:\"boolean\"}\n",
261
+ "show_mainchains = False #@param {type:\"boolean\"}\n",
262
+ "show_pdb(pdb_str, color=color, show_sidechains=show_sidechains, show_mainchains=show_mainchains,\n",
263
+ " Ls=lengths).show()"
264
+ ],
265
+ "metadata": {
266
+ "cellView": "form",
267
+ "id": "e6rpvs0Nqix5"
268
+ },
269
+ "execution_count": null,
270
+ "outputs": []
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "source": [
275
+ "#@title Download prediction\n",
276
+ "from google.colab import files\n",
277
+ "files.download(f'{ID}.pdb')"
278
+ ],
279
+ "metadata": {
280
+ "cellView": "form",
281
+ "id": "12rxVAHSrmYQ"
282
+ },
283
+ "execution_count": null,
284
+ "outputs": []
285
+ }
286
+ ]
287
+ }
data/beta/pairmsa.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from string import ascii_uppercase, ascii_lowercase
3
+ import urllib.parse
4
+ import urllib.request
5
+ import time
6
+
7
+ def parse_a3m(a3m_lines=None, a3m_file=None, filter_qid=0.15, filter_cov=0.5, N=100000):
8
+
9
+ def seqid(a, b):
10
+ return sum(c1 == c2 for c1, c2 in zip(a, b))
11
+
12
+ def nongaps(a):
13
+ return sum(c != "-" for c in a)
14
+
15
+ def chk(seq, ref_seq):
16
+ rL = len(ref_seq)
17
+ L = nongaps(seq)
18
+ return not (L > filter_cov*rL and seqid(seq, ref_seq) > filter_qid*L)
19
+
20
+ rm_lower = str.maketrans('','',ascii_lowercase)
21
+
22
+ # prep inputs
23
+ if a3m_lines is None: a3m_lines = open(a3m_file,"r")
24
+ else: a3m_lines = a3m_lines.splitlines()
25
+
26
+ # parse inputs
27
+ n,nams,seqs,mtx = 0,[],[],[]
28
+ def do_filter():
29
+ seq = seqs[-1].translate(rm_lower)
30
+ if "_UPI" in nams[-1] or chk(seq,ref_seq):
31
+ nams.pop()
32
+ seqs.pop()
33
+ else:
34
+ # deletion matrix
35
+ deletion_vec = []
36
+ deletion_count = 0
37
+ for j in seqs[-1]:
38
+ if j.islower():
39
+ deletion_count += 1
40
+ else:
41
+ deletion_vec.append(deletion_count)
42
+ deletion_count = 0
43
+ mtx.append(deletion_vec)
44
+ seqs[-1] = seq
45
+
46
+ for line in a3m_lines:
47
+ line = line.rstrip()
48
+ if line.startswith(">"):
49
+ if n == 1:
50
+ ref_seq = seqs[0].translate(rm_lower)
51
+ if n >= 1:
52
+ # filter previous entry
53
+ do_filter()
54
+ # start new sequence entry
55
+ nam = line.split()[0][1:]
56
+ if "_" not in nam: nam = f"X_{nam}"
57
+ nams.append(nam)
58
+ seqs.append("")
59
+ n += 1
60
+ else:
61
+ seqs[-1] += line
62
+
63
+ # filter last entry
64
+ do_filter()
65
+
66
+ if len(seqs) > N+1:
67
+ print(f"found too many sequences ({len(seqs)}), taking the top{N} (sorted by qid)")
68
+ sid = np.argsort([seqid(seq,ref_seq) for seq in seqs])[::-1][:N+1]
69
+ seqs = [seqs[i] for i in sid]
70
+ mtx = [mtx[i] for i in sid]
71
+ nams = [nams[i] for i in sid]
72
+ return seqs[1:],mtx[1:],nams[1:]
73
+
74
+ def get_uni_jackhmmer(msa, mtx, lab, filter_qid=0.15, filter_cov=0.5):
75
+ '''filter entries to uniprot'''
76
+ lab_,msa_,mtx_ = [],[],[]
77
+ ref_seq = np.array(list(msa[0]))
78
+ rL = len(ref_seq)
79
+ for l,s,x in zip(lab[1:],msa[1:],mtx[1:]):
80
+ if l.startswith("UniRef"):
81
+ l = l.split("/")[0]
82
+ if "_UPI" not in l:
83
+ tar_seq = np.array(list(s))
84
+ L = (tar_seq != "-").sum()
85
+ qid = (ref_seq == tar_seq).sum()
86
+ if L > filter_cov * rL and qid > filter_qid * L:
87
+ lab_.append(l)
88
+ msa_.append(s)
89
+ mtx_.append(x)
90
+ return msa_, mtx_, lab_
91
+
92
+ def uni_num(ids):
93
+ ########################################
94
+ pa = {a:0 for a in ascii_uppercase}
95
+ for a in ["O","P","Q"]: pa[a] = 1
96
+ ma = [[{} for k in range(6)],[{} for k in range(6)]]
97
+ for n,t in enumerate(range(10)):
98
+ for i in [0,1]:
99
+ for j in [0,4]: ma[i][j][str(t)] = n
100
+ for n,t in enumerate(list(ascii_uppercase)+list(range(10))):
101
+ for i in [0,1]:
102
+ for j in [1,2]: ma[i][j][str(t)] = n
103
+ ma[1][3][str(t)] = n
104
+ for n,t in enumerate(ascii_uppercase):
105
+ ma[0][3][str(t)] = n
106
+ for i in [0,1]: ma[i][5][str(t)] = n
107
+ ########################################
108
+ nums = []
109
+ for uni in ids:
110
+ p = pa[uni[0]]
111
+ tot, num = 1,0
112
+ if len(uni) == 10:
113
+ for n,u in enumerate(reversed(uni[-4:])):
114
+ num += ma[p][n][u] * tot
115
+ tot *= len(ma[p][n].keys())
116
+ for n,u in enumerate(reversed(uni[:6])):
117
+ num += ma[p][n][u] * tot
118
+ tot *= len(ma[p][n].keys())
119
+ nums.append(num)
120
+ return nums
121
+
122
+ def map_retrieve(ids, call_uniprot=False):
123
+
124
+ if call_uniprot:
125
+ mode = "NF100" if "UniRef100" in ids[0] else "NF90"
126
+ url = 'https://www.uniprot.org/uploadlists/'
127
+ out = []
128
+ for i in range(0,len(ids),5000):
129
+ params = {
130
+ 'from': mode,
131
+ 'to': 'ACC',
132
+ 'format': 'tab',
133
+ 'query': " ".join(ids[i:i+5000])
134
+ }
135
+ data = urllib.parse.urlencode(params)
136
+ data = data.encode('utf-8')
137
+ req = urllib.request.Request(url, data)
138
+ with urllib.request.urlopen(req) as f:
139
+ response = f.read()
140
+ out += [line.split() for line in response.decode('utf-8').splitlines()]
141
+ time.sleep(5)
142
+
143
+ # combine mapping
144
+ mapping = {}
145
+ for i,j in out:
146
+ if i != "From":
147
+ if i not in mapping:
148
+ mapping[i] = [j]
149
+ else:
150
+ mapping[i].append(j)
151
+ else:
152
+ mapping = {}
153
+
154
+ for i in ids:
155
+ if i not in mapping:
156
+ mapping[i] = [i.split("_")[1]]
157
+
158
+ return mapping
159
+
160
+ def hash_it(_seq, _lab, _mtx, call_uniprot=False):
161
+ if _seq is None or _lab is None:
162
+ _seq, _lab = parse_a3m(a3m_lines)
163
+
164
+ _lab_to_seq = {L:S for L,S in zip(_lab,_seq)}
165
+ _lab_to_mtx = {L:M for L,M in zip(_lab,_mtx)}
166
+
167
+ # call uniprot
168
+ _lab_to_uni = map_retrieve(_lab, call_uniprot=call_uniprot)
169
+
170
+ _uni_to_lab = {}
171
+ for L,U in _lab_to_uni.items():
172
+ for u in U: _uni_to_lab[u] = L
173
+
174
+ _uni,__lab = [],[]
175
+ for U,L in _uni_to_lab.items():
176
+ _uni.append(U)
177
+ __lab.append(L)
178
+
179
+ _hash = uni_num(_uni)
180
+ _uni_to_hash = {u:h for u,h in zip(_uni,_hash)}
181
+ _hash_to_lab = {h:l for h,l in zip(_hash,__lab)}
182
+
183
+ _lab_to_hash = {}
184
+ for L,U in _lab_to_uni.items():
185
+ _lab_to_hash[L] = []
186
+ for u in U: _lab_to_hash[L].append(_uni_to_hash[u])
187
+
188
+ return {"_lab_to_seq":_lab_to_seq,
189
+ "_lab_to_mtx":_lab_to_mtx,
190
+ "_lab_to_hash":_lab_to_hash,
191
+ "_hash_to_lab":_hash_to_lab}
192
+
193
+ import tqdm.notebook
194
+ TQDM_BAR_FORMAT = '{l_bar}{bar}| {n_fmt}/{total_fmt} [elapsed: {elapsed} remaining: {remaining}]'
195
+
196
+ # keeping old function for compatability
197
+ def stitch(_hash_a,_hash_b, stitch_min=1, stitch_max=20, filter_id=None):
198
+ o = _stitch(_hash_a, _hash_b, stitch_min, stitch_max)
199
+ return (*o["seq"],*o["mtx"])
200
+
201
+ def _stitch(_hash_a,_hash_b, stitch_min=1, stitch_max=20):
202
+ _seq, _mtx, _lab, _delta_gene = [[],[]],[[],[]],[[],[]],[]
203
+ TOTAL = len(_hash_a["_lab_to_hash"])
204
+ with tqdm.notebook.tqdm(total=TOTAL, bar_format=TQDM_BAR_FORMAT) as pbar:
205
+ pbar.set_description("STITCHING")
206
+ H_A = np.asarray(list(_hash_a["_hash_to_lab"].keys()))
207
+ H_B = np.asarray(list(_hash_b["_hash_to_lab"].keys()))
208
+
209
+ def hit(h,H):
210
+ h = np.asarray(h)
211
+ match = np.abs(h[:,None]-H[None,:]).min(0)
212
+ match_min = match.min()
213
+ if match_min >= stitch_min and match_min <= stitch_max:
214
+ return True,H[match.argmin()],match_min
215
+ else:
216
+ return False,None,None
217
+
218
+ for n,(l_a,h_a) in enumerate(_hash_a["_lab_to_hash"].items()):
219
+ chk_b, h_b, dg = hit(h_a,H_B)
220
+ if chk_b:
221
+ l_b = _hash_b["_hash_to_lab"][h_b]
222
+ h_b = _hash_b["_lab_to_hash"][l_b]
223
+ chk_c, h_c, _ = hit(h_b,H_A)
224
+ if chk_c and _hash_a["_hash_to_lab"][h_c] == l_a:
225
+ _seq[0].append(_hash_a["_lab_to_seq"][l_a])
226
+ _mtx[0].append(_hash_a["_lab_to_mtx"][l_a])
227
+ _lab[0].append(l_a)
228
+ _seq[1].append(_hash_b["_lab_to_seq"][l_b])
229
+ _mtx[1].append(_hash_b["_lab_to_mtx"][l_b])
230
+ _lab[1].append(l_b)
231
+ _delta_gene.append(dg)
232
+ pbar.update()
233
+
234
+ return {"seq":_seq,
235
+ "mtx":_mtx,
236
+ "lab":_lab,
237
+ "delta_gene":_delta_gene}
data/beta/protein.patch ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- /content/alphafold_ori/common/protein.py 2021-08-10 10:03:26.580274340 +0000
2
+ +++ /content/alphafold/alphafold/common/protein.py 2021-08-10 10:04:47.660884323 +0000
3
+ @@ -19,6 +19,9 @@
4
+ from alphafold.common import residue_constants
5
+ from Bio.PDB import PDBParser
6
+ import numpy as np
7
+ +from string import ascii_uppercase,ascii_lowercase
8
+ +
9
+ +CHAIN_IDs = ascii_uppercase+ascii_lowercase
10
+
11
+ FeatureDict = Mapping[str, np.ndarray]
12
+ ModelOutput = Mapping[str, Any] # Is a nested dict.
13
+ @@ -75,14 +78,15 @@
14
+
15
+ if chain_id is not None:
16
+ chain = model[chain_id]
17
+ + chains = [chain]
18
+ else:
19
+ chains = list(model.get_chains())
20
+ - if len(chains) != 1:
21
+ - raise ValueError(
22
+ - 'Only single chain PDBs are supported when chain_id not specified. '
23
+ - f'Found {len(chains)} chains.')
24
+ - else:
25
+ - chain = chains[0]
26
+ + # if len(chains) != 1:
27
+ + # raise ValueError(
28
+ + # 'Only single chain PDBs are supported when chain_id not specified. '
29
+ + # f'Found {len(chains)} chains.')
30
+ + # else:
31
+ + # chain = chains[0]
32
+
33
+ atom_positions = []
34
+ aatype = []
35
+ @@ -90,31 +94,35 @@
36
+ residue_index = []
37
+ b_factors = []
38
+
39
+ - for res in chain:
40
+ - if res.id[2] != ' ':
41
+ - raise ValueError(
42
+ - f'PDB contains an insertion code at chain {chain.id} and residue '
43
+ - f'index {res.id[1]}. These are not supported.')
44
+ - res_shortname = residue_constants.restype_3to1.get(res.resname, 'X')
45
+ - restype_idx = residue_constants.restype_order.get(
46
+ - res_shortname, residue_constants.restype_num)
47
+ - pos = np.zeros((residue_constants.atom_type_num, 3))
48
+ - mask = np.zeros((residue_constants.atom_type_num,))
49
+ - res_b_factors = np.zeros((residue_constants.atom_type_num,))
50
+ - for atom in res:
51
+ - if atom.name not in residue_constants.atom_types:
52
+ + PARAM_CHAIN_BREAK = 100
53
+ + residue_index_prev = 0
54
+ + for k,chain in enumerate(chains):
55
+ + for res in chain:
56
+ + if res.id[2] != ' ':
57
+ + raise ValueError(
58
+ + f'PDB contains an insertion code at chain {chain.id} and residue '
59
+ + f'index {res.id[1]}. These are not supported.')
60
+ + res_shortname = residue_constants.restype_3to1.get(res.resname, 'X')
61
+ + restype_idx = residue_constants.restype_order.get(
62
+ + res_shortname, residue_constants.restype_num)
63
+ + pos = np.zeros((residue_constants.atom_type_num, 3))
64
+ + mask = np.zeros((residue_constants.atom_type_num,))
65
+ + res_b_factors = np.zeros((residue_constants.atom_type_num,))
66
+ + for atom in res:
67
+ + if atom.name not in residue_constants.atom_types:
68
+ + continue
69
+ + pos[residue_constants.atom_order[atom.name]] = atom.coord
70
+ + mask[residue_constants.atom_order[atom.name]] = 1.
71
+ + res_b_factors[residue_constants.atom_order[atom.name]] = atom.bfactor
72
+ + if np.sum(mask) < 0.5:
73
+ + # If no known atom positions are reported for the residue then skip it.
74
+ continue
75
+ - pos[residue_constants.atom_order[atom.name]] = atom.coord
76
+ - mask[residue_constants.atom_order[atom.name]] = 1.
77
+ - res_b_factors[residue_constants.atom_order[atom.name]] = atom.bfactor
78
+ - if np.sum(mask) < 0.5:
79
+ - # If no known atom positions are reported for the residue then skip it.
80
+ - continue
81
+ - aatype.append(restype_idx)
82
+ - atom_positions.append(pos)
83
+ - atom_mask.append(mask)
84
+ - residue_index.append(res.id[1])
85
+ - b_factors.append(res_b_factors)
86
+ + aatype.append(restype_idx)
87
+ + atom_positions.append(pos)
88
+ + atom_mask.append(mask)
89
+ + residue_index.append(res.id[1] + residue_index_prev + PARAM_CHAIN_BREAK*k)
90
+ + b_factors.append(res_b_factors)
91
+ + residue_index_prev = residue_index[-1]
92
+
93
+ return Protein(
94
+ atom_positions=np.array(atom_positions),
95
+ @@ -150,10 +158,21 @@
96
+
97
+ pdb_lines.append('MODEL 1')
98
+ atom_index = 1
99
+ - chain_id = 'A'
100
+ + chain_index = -1
101
+ + residue_index_prev = residue_index[0]-100
102
+ # Add all atom sites.
103
+ for i in range(aatype.shape[0]):
104
+ + if residue_index[i] - residue_index_prev > 1: # chain break
105
+ + chain_index += 1
106
+ + res_num = 1
107
+ + if chain_index > 0:
108
+ + pdb_lines.append("TER")
109
+ + elif residue_index[i] != residue_index_prev:
110
+ + res_num += 1
111
+ + residue_index_prev = residue_index[i]
112
+ + chain_id = CHAIN_IDs[chain_index]
113
+ res_name_3 = res_1to3(aatype[i])
114
+ + #
115
+ for atom_name, pos, mask, b_factor in zip(
116
+ atom_types, atom_positions[i], atom_mask[i], b_factors[i]):
117
+ if mask < 0.5:
118
+ @@ -169,7 +188,7 @@
119
+ # PDB is a columnar format, every space matters here!
120
+ atom_line = (f'{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}'
121
+ f'{res_name_3:>3} {chain_id:>1}'
122
+ - f'{residue_index[i]:>4}{insertion_code:>1} '
123
+ + f'{res_num:>4}{insertion_code:>1} '
124
+ f'{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}'
125
+ f'{occupancy:>6.2f}{b_factor:>6.2f} '
126
+ f'{element:>2}{charge:>2}')
data/beta/recycle_0.patch ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- /usr/local/lib/python3.7/dist-packages/alphafold/model/modules.py 2022-03-23 04:02:56.871333044 +0000
2
+ +++ alphafold/alphafold/model/modules.py 2022-03-23 04:04:16.081234108 +0000
3
+ @@ -341,17 +341,16 @@
4
+ compute_loss=compute_loss,
5
+ ensemble_representations=ensemble_representations)
6
+
7
+ + emb_config = self.config.embeddings_and_evoformer
8
+ + prev = {
9
+ + 'prev_pos': jnp.zeros(
10
+ + [num_residues, residue_constants.atom_type_num, 3]),
11
+ + 'prev_msa_first_row': jnp.zeros(
12
+ + [num_residues, emb_config.msa_channel]),
13
+ + 'prev_pair': jnp.zeros(
14
+ + [num_residues, num_residues, emb_config.pair_channel]),
15
+ + }
16
+ if self.config.num_recycle:
17
+ - emb_config = self.config.embeddings_and_evoformer
18
+ - prev = {
19
+ - 'prev_pos': jnp.zeros(
20
+ - [num_residues, residue_constants.atom_type_num, 3]),
21
+ - 'prev_msa_first_row': jnp.zeros(
22
+ - [num_residues, emb_config.msa_channel]),
23
+ - 'prev_pair': jnp.zeros(
24
+ - [num_residues, num_residues, emb_config.pair_channel]),
25
+ - }
26
+ -
27
+ if 'num_iter_recycling' in batch:
28
+ # Training time: num_iter_recycling is in batch.
29
+ # The value for each ensemble batch is the same, so arbitrarily taking
30
+ @@ -378,7 +377,6 @@
31
+ body,
32
+ (0, prev))
33
+ else:
34
+ - prev = {}
35
+ num_iter = 0
36
+
37
+ ret = do_call(prev=prev, recycle_idx=num_iter)
data/beta/relax_amber.ipynb ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "runtime_attributes": {
8
+ "runtime_version": "2025.07"
9
+ }
10
+ },
11
+ "kernelspec": {
12
+ "name": "python3",
13
+ "display_name": "Python 3"
14
+ },
15
+ "language_info": {
16
+ "name": "python"
17
+ }
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {
23
+ "id": "view-in-github",
24
+ "colab_type": "text"
25
+ },
26
+ "source": [
27
+ "<a href=\"https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/beta/relax_amber.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "markdown",
32
+ "source": [
33
+ "\n",
34
+ "<img src=\"https://raw.githubusercontent.com/sokrypton/ColabFold/main/.github/ColabFold_Marv_Logo_Small.png\" height=\"200\" align=\"right\" style=\"height:240px\">\n",
35
+ "\n",
36
+ "# Relax your structure using OpenMM/Amber\n",
37
+ "\n",
38
+ "Easy to use protein structure relaxation using [AlphaFold2](https://www.nature.com/articles/s41586-021-03819-2) and [OpenMM](https://github.com/openmm/openmm).\n",
39
+ "\n",
40
+ "This notebooks is part of ColabFold. See [GitHub](https://github.com/sokrypton/ColabFold) for other notebooks.\n",
41
+ "\n",
42
+ "[Mirdita M, Schütze K, Moriwaki Y, Heo L, Ovchinnikov S, Steinegger M. ColabFold: Making protein folding accessible to all.\n",
43
+ "*Nature Methods*, 2022](https://www.nature.com/articles/s41592-022-01488-1)\n"
44
+ ],
45
+ "metadata": {
46
+ "id": "rvfNfOLaE4bW"
47
+ }
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "source": [
52
+ "%%time\n",
53
+ "#@title Setup AlphaFold2 and OpenMM\n",
54
+ "import sys, os\n",
55
+ "from sys import version_info\n",
56
+ "PYTHON_VERSION = f\"{version_info.major}.{version_info.minor}\"\n",
57
+ "\n",
58
+ "if not os.path.isfile(\"ALPHAFOLD_READY\"):\n",
59
+ " print(\"installing AlphaFold...\")\n",
60
+ " os.system(\"pip install alphafold-colabfold\")\n",
61
+ " os.system(\"ln -s /usr/local/lib/python3.*/dist-packages/alphafold alphafold\")\n",
62
+ " os.system(\"touch ALPHAFOLD_READY\")\n",
63
+ "\n",
64
+ "if not os.path.isfile(\"CONDA_READY\"):\n",
65
+ " print(\"installing conda...\")\n",
66
+ " os.system(\"wget -qnc https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-x86_64.sh\")\n",
67
+ " os.system(\"bash Miniforge3-Linux-x86_64.sh -bfp /usr/local\")\n",
68
+ " os.system(\"mamba config --set auto_update_conda false\")\n",
69
+ " os.system(\"touch CONDA_READY\")\n",
70
+ "\n",
71
+ "if not os.path.isfile(\"AMBER_READY\"):\n",
72
+ " print(\"installing amber...\")\n",
73
+ " os.system(f\"mamba install -y -q -c conda-forge openmm=8.2.0 python='{PYTHON_VERSION}' pdbfixer 2>&1 1>/dev/null\")\n",
74
+ " os.system(\"touch AMBER_READY\")\n",
75
+ "\n",
76
+ "PATH = f\"/usr/local/lib/python{PYTHON_VERSION}/site-packages/\"\n",
77
+ "if PATH not in sys.path:\n",
78
+ " sys.path.insert(0, PATH)\n",
79
+ "\n",
80
+ "import warnings\n",
81
+ "warnings.simplefilter(action='ignore', category=FutureWarning)\n",
82
+ "\n",
83
+ "from alphafold.relax import relax\n",
84
+ "from alphafold.relax import utils\n",
85
+ "from alphafold.common import protein, residue_constants\n",
86
+ "\n",
87
+ "MODRES = {'MSE':'MET','MLY':'LYS','FME':'MET','HYP':'PRO',\n",
88
+ " 'TPO':'THR','CSO':'CYS','SEP':'SER','M3L':'LYS',\n",
89
+ " 'HSK':'HIS','SAC':'SER','PCA':'GLU','DAL':'ALA',\n",
90
+ " 'CME':'CYS','CSD':'CYS','OCS':'CYS','DPR':'PRO',\n",
91
+ " 'B3K':'LYS','ALY':'LYS','YCM':'CYS','MLZ':'LYS',\n",
92
+ " '4BF':'TYR','KCX':'LYS','B3E':'GLU','B3D':'ASP',\n",
93
+ " 'HZP':'PRO','CSX':'CYS','BAL':'ALA','HIC':'HIS',\n",
94
+ " 'DBZ':'ALA','DCY':'CYS','DVA':'VAL','NLE':'LEU',\n",
95
+ " 'SMC':'CYS','AGM':'ARG','B3A':'ALA','DAS':'ASP',\n",
96
+ " 'DLY':'LYS','DSN':'SER','DTH':'THR','GL3':'GLY',\n",
97
+ " 'HY3':'PRO','LLP':'LYS','MGN':'GLN','MHS':'HIS',\n",
98
+ " 'TRQ':'TRP','B3Y':'TYR','PHI':'PHE','PTR':'TYR',\n",
99
+ " 'TYS':'TYR','IAS':'ASP','GPL':'LYS','KYN':'TRP',\n",
100
+ " 'CSD':'CYS','SEC':'CYS'}\n",
101
+ "\n",
102
+ "def pdb_to_string(pdb_file, chains=None, models=[1]):\n",
103
+ " '''read pdb file and return as string'''\n",
104
+ "\n",
105
+ " if chains is not None:\n",
106
+ " if \",\" in chains: chains = chains.split(\",\")\n",
107
+ " if not isinstance(chains,list): chains = [chains]\n",
108
+ " if models is not None:\n",
109
+ " if not isinstance(models,list): models = [models]\n",
110
+ "\n",
111
+ " modres = {**MODRES}\n",
112
+ " lines = []\n",
113
+ " seen = []\n",
114
+ " model = 1\n",
115
+ " for line in open(pdb_file,\"rb\"):\n",
116
+ " line = line.decode(\"utf-8\",\"ignore\").rstrip()\n",
117
+ " if line[:5] == \"MODEL\":\n",
118
+ " model = int(line[5:])\n",
119
+ " if models is None or model in models:\n",
120
+ " if line[:6] == \"MODRES\":\n",
121
+ " k = line[12:15]\n",
122
+ " v = line[24:27]\n",
123
+ " if k not in modres and v in residue_constants.restype_3to1:\n",
124
+ " modres[k] = v\n",
125
+ " if line[:6] == \"HETATM\":\n",
126
+ " k = line[17:20]\n",
127
+ " if k in modres:\n",
128
+ " line = \"ATOM \"+line[6:17]+modres[k]+line[20:]\n",
129
+ " if line[:4] == \"ATOM\":\n",
130
+ " chain = line[21:22]\n",
131
+ " if chains is None or chain in chains:\n",
132
+ " atom = line[12:12+4].strip()\n",
133
+ " resi = line[17:17+3]\n",
134
+ " resn = line[22:22+5].strip()\n",
135
+ " if resn[-1].isalpha(): # alternative atom\n",
136
+ " resn = resn[:-1]\n",
137
+ " line = line[:26]+\" \"+line[27:]\n",
138
+ " key = f\"{model}_{chain}_{resn}_{resi}_{atom}\"\n",
139
+ " if key not in seen: # skip alternative placements\n",
140
+ " lines.append(line)\n",
141
+ " seen.append(key)\n",
142
+ " if line[:5] == \"MODEL\" or line[:3] == \"TER\" or line[:6] == \"ENDMDL\":\n",
143
+ " lines.append(line)\n",
144
+ " return \"\\n\".join(lines)\n",
145
+ "\n",
146
+ "def relax_me(pdb_in, pdb_out, max_iterations, tolerance, stiffness, use_gpu):\n",
147
+ " pdb_str = pdb_to_string(pdb_in)\n",
148
+ " protein_obj = protein.from_pdb_string(pdb_str)\n",
149
+ " amber_relaxer = relax.AmberRelaxation(\n",
150
+ " max_iterations=max_iterations,\n",
151
+ " tolerance=tolerance,\n",
152
+ " stiffness=stiffness,\n",
153
+ " exclude_residues=[],\n",
154
+ " max_outer_iterations=3,\n",
155
+ " use_gpu=use_gpu\n",
156
+ " )\n",
157
+ " relaxed_pdb_lines, _, _ = amber_relaxer.process(prot=protein_obj)\n",
158
+ " with open(pdb_out, 'w') as f:\n",
159
+ " f.write(relaxed_pdb_lines)"
160
+ ],
161
+ "metadata": {
162
+ "cellView": "form",
163
+ "id": "1KKjet38pMys"
164
+ },
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "source": [
171
+ "#@title #Relax\n",
172
+ "#@markdown - Click the little ▶ play icon to the left to get an upload prompt.\n",
173
+ "#@markdown - After relax is done, `relaxed.pdb` will automatically download.\n",
174
+ "#@markdown - If download was blocked, click the little folder 📁 icon on the left, right-click `relaxed.pdb` and select Download!\n",
175
+ "#@markdown ----\n",
176
+ "#@markdown ## Parameters\n",
177
+ "max_iterations = 2000 #@param {type:\"slider\", min:0, max:5000, step:250}\n",
178
+ "#@markdown - Low values might never converge and crash and high values might also run for a long time. `0` = infinity is the AF2 default, however it might run for a long time.\n",
179
+ "tolerance = 2.39 # @param {type:\"number\"}\n",
180
+ "#@markdown - kcal/mol, the energy tolerance of L-BFGS.\n",
181
+ "stiffness = 10.0 # @param {type:\"number\"}\n",
182
+ "#@markdown - kcal/mol A^2, spring constant of heavy atom restraining potential.\n",
183
+ "#@markdown - **Note:** Descriptions and default values are taken AF2.\n",
184
+ "use_gpu = False # @param {type:\"boolean\"}\n",
185
+ "#@markdown - set \"Runtime->Change runtime type\" to a GPU in Google Colab if you activate this.\n",
186
+ "\n",
187
+ "from google.colab import files\n",
188
+ "pdb_dict = files.upload()\n",
189
+ "relax_me(\n",
190
+ " pdb_in=list(pdb_dict.keys())[0],\n",
191
+ " pdb_out=\"relaxed.pdb\",\n",
192
+ " max_iterations=max_iterations,\n",
193
+ " tolerance=tolerance,\n",
194
+ " stiffness=stiffness,\n",
195
+ " use_gpu=use_gpu\n",
196
+ ")\n",
197
+ "files.download(f'relaxed.pdb')"
198
+ ],
199
+ "metadata": {
200
+ "id": "rEekqQXQ-Pec",
201
+ "cellView": "form"
202
+ },
203
+ "execution_count": null,
204
+ "outputs": []
205
+ }
206
+ ]
207
+ }
data/colabfold/__init__.py ADDED
File without changes
data/colabfold/alphafold/__init__.py ADDED
File without changes
data/colabfold/alphafold/extra_ptm.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import string
3
+ from copy import deepcopy
4
+ import jax.numpy as jnp
5
+ import jax
6
+ import scipy
7
+ import pandas as pd
8
+
9
+ from alphafold.common import confidence
10
+
11
+ """ Functions to calculate interface metrics on actual interfaces"""
12
+ def get_dgram_bins(result):
13
+ """From colabdesign, calculate bin boundaries of distogram"""
14
+ dgram = result["distogram"]["logits"]
15
+ if dgram.shape[-1] == 64:
16
+ dgram_bins = jnp.append(0,jnp.linspace(2.3125,21.6875,63))
17
+ if dgram.shape[-1] == 39:
18
+ dgram_bins = jnp.linspace(3.25,50.75,39) + 1.25
19
+ return dgram_bins
20
+
21
+
22
+ def get_contact_map(result, dist=8.0):
23
+ """From colabdesign, get contact map from distogram"""
24
+ dist_logits = result["distogram"]["logits"]
25
+ dist_bins = get_dgram_bins(result)
26
+ return (jax.nn.softmax(dist_logits) * (dist_bins < dist)).sum(-1)
27
+
28
+
29
+ def get_chain_indices(asym_id, use_jnp=True):
30
+ """Returns a list of tuples indicating the start and end indices for each chain."""
31
+
32
+ chain_starts_ends = []
33
+ unique_chains = np.unique(asym_id) # chains are numbered 0, 1, 2, ...
34
+
35
+ for chain in unique_chains:
36
+ positions = np.where(asym_id == chain)[0]
37
+ chain_starts_ends.append((positions[0], positions[-1]))
38
+
39
+ return chain_starts_ends
40
+
41
+
42
+ def predicted_tm_score_modified(logits, breaks, residue_weights=None,
43
+ asym_id=None, pair_residue_weights=None, use_jnp=False, ):
44
+ """Computes predicted TM alignment or predicted interface TM alignment score.
45
+
46
+ Args:
47
+ logits: [num_res, num_res, num_bins] the logits output from
48
+ PredictedAlignedErrorHead.
49
+ breaks: [num_bins] the error bins.
50
+ residue_weights: [num_res] the per residue weights to use for the
51
+ expectation.
52
+ asym_id: [num_res] the asymmetric unit ID - the chain ID. Only needed for
53
+ ipTM calculation.
54
+ pair_residue_weights: [num_res, num_res] unnormalized weights for actifptm calculation
55
+
56
+ Returns:
57
+ ptm_score: The predicted TM alignment or the predicted iTM score.
58
+ """
59
+ if use_jnp:
60
+ _np, _softmax = jnp, jax.nn.softmax
61
+ else:
62
+ _np, _softmax = np, scipy.special.softmax
63
+
64
+ # residue_weights has to be in [0, 1], but can be floating-point, i.e. the
65
+ # exp. resolved head's probability.
66
+ if residue_weights is None:
67
+ residue_weights = _np.ones(logits.shape[0])
68
+ bin_centers = confidence._calculate_bin_centers(breaks, use_jnp=use_jnp)
69
+ num_res = residue_weights.shape[0]
70
+
71
+ # Clip num_res to avoid negative/undefined d0.
72
+ clipped_num_res = _np.maximum(num_res, 19)
73
+
74
+ # Compute d_0(num_res) as defined by TM-score, eqn. (5) in Yang & Skolnick
75
+ # "Scoring function for automated assessment of protein structure template
76
+ # quality", 2004: http://zhanglab.ccmb.med.umich.edu/papers/2004_3.pdf
77
+ d0 = 1.24 * (clipped_num_res - 15) ** (1. / 3) - 1.8
78
+
79
+ # Convert logits to probs.
80
+ probs = _softmax(logits, axis=-1)
81
+
82
+ # TM-Score term for every bin.
83
+ tm_per_bin = 1. / (1 + _np.square(bin_centers) / _np.square(d0))
84
+
85
+ # E_distances tm(distance).
86
+ predicted_tm_term = (probs * tm_per_bin).sum(-1)
87
+
88
+ if asym_id is None:
89
+ pair_mask = _np.full((num_res, num_res), True)
90
+ else:
91
+ pair_mask = asym_id[:, None] != asym_id[None, :]
92
+
93
+ predicted_tm_term *= pair_mask
94
+
95
+ # If pair_residue_weights is provided (e.g. for if_ptm with contact probabilities),
96
+ # it should not be overwritten
97
+ if pair_residue_weights is None:
98
+ pair_residue_weights = pair_mask * (residue_weights[None, :] * residue_weights[:, None])
99
+ normed_residue_mask = pair_residue_weights / (1e-8 + pair_residue_weights.sum(-1, keepdims=True))
100
+
101
+ per_alignment = (predicted_tm_term * normed_residue_mask).sum(-1)
102
+ residuewise_iptm = per_alignment * residue_weights
103
+
104
+ return residuewise_iptm
105
+
106
+
107
+ def get_ptm_modified(inputs, outputs, interface=False):
108
+ """ This function is the same as in the original AF2, just calls a modified TM-score calculation function."""
109
+
110
+ pae = {"residue_weights": inputs["seq_mask"], **outputs["predicted_aligned_error"]}
111
+
112
+ if interface:
113
+ if "asym_id" not in pae:
114
+ pae["asym_id"] = inputs["asym_id"]
115
+ else:
116
+ if "asym_id" in pae:
117
+ pae.pop("asym_id")
118
+
119
+ return predicted_tm_score_modified(**pae, use_jnp=True)
120
+
121
+
122
+ def get_actifptm_probs(result, asym_id, cmap, start_i, end_i, start_j, end_j):
123
+ """
124
+ This function calculates the interface PTM score for a given interface, taking into account the contact probabilities, not binary contacts.
125
+
126
+ Args:
127
+ af: AlphaFold object
128
+ cmap: Contact map
129
+ start_i, end_i: Start and end indices of the first chain
130
+ start_j, end_j: Start and end indices of the second chain
131
+
132
+ Returns:
133
+ actifptm: Interface pTM score
134
+ """
135
+
136
+ total_length = len(asym_id)
137
+ outputs = deepcopy(result)
138
+
139
+ # Create a new matrix, which contains only the contacts between the two chains
140
+ cmap_copy = np.zeros((total_length, total_length))
141
+ cmap_copy[start_i:end_i + 1, start_j:end_j + 1] = cmap[start_i:end_i + 1, start_j:end_j + 1]
142
+ cmap_copy[start_j:end_j + 1, start_i:end_i + 1] = cmap[start_j:end_j + 1, start_i:end_i + 1]
143
+
144
+ # this is for the full-length actifptm
145
+ if end_i == end_j == total_length - 1 and start_i == start_j == 0:
146
+ pair_mask = asym_id[:, None] != asym_id[None, :]
147
+ cmap_copy *= pair_mask
148
+
149
+ # Update seq_mask for these positions to True within inputs
150
+ seq_mask = np.full(total_length, 0, dtype=float)
151
+ seq_mask[np.concatenate((np.arange(start_i, end_i + 1),
152
+ np.arange(start_j, end_j + 1)))] = 1
153
+
154
+ # Call get_ptm with updated inputs and outputs
155
+ pae = {"residue_weights": seq_mask,
156
+ **outputs["predicted_aligned_error"],
157
+ "asym_id": asym_id}
158
+ residuewise_actifptm = predicted_tm_score_modified(**pae, use_jnp=True, pair_residue_weights=cmap_copy)
159
+
160
+ return residuewise_actifptm
161
+
162
+
163
+ def get_actifptm_contacts(result, asym_id, cmap, start_i, end_i, start_j, end_j):
164
+ """
165
+ This function calculates the interface PTM score for a given interface, taking into account binary contacts.
166
+ In case of no confident contacts, the interface PTM score is set to 0.
167
+
168
+ Args:
169
+ af: AlphaFold object
170
+ cmap: Contact map
171
+ start_i, end_i: Start and end indices of the first chain
172
+ start_j, end_j: Start and end indices of the second chain
173
+
174
+ Returns:
175
+ actifptm: Interface pTM score
176
+ """
177
+
178
+ # Prepare a dictionary to collect the inputs for calculation
179
+ inputs_actifptm = {}
180
+ contacts = np.where(cmap[start_i:end_i + 1, start_j:end_j + 1] >= 0.6)
181
+ total_length = len(asym_id)
182
+ outputs = deepcopy(result)
183
+
184
+ if contacts[0].size > 0: # If there are contacts
185
+ # Convert local chain positions back to global positions using JAX
186
+ global_i_positions = contacts[0] + start_i
187
+ global_j_positions = contacts[1] + start_j
188
+ global_positions = list(set(np.concatenate((global_i_positions, global_j_positions))))
189
+ global_positions = np.array(global_positions, dtype=int)
190
+ global_positions.sort()
191
+
192
+ # Initialize new input dictionary
193
+ inputs_actifptm['asym_id'] = asym_id
194
+ inputs_actifptm['seq_mask'] = np.full(total_length, 0, dtype=float)
195
+ inputs_actifptm['seq_mask'][global_positions] = 1
196
+
197
+ # Call get_ptm with updated inputs and outputs
198
+ residuewise_actifptm = get_ptm_modified(inputs_actifptm, outputs, interface=True)
199
+ else:
200
+ residuewise_actifptm = np.array([0.0])
201
+ inputs_actifptm['seq_mask'] = np.full(total_length, 0, dtype=float)
202
+
203
+ return residuewise_actifptm, inputs_actifptm['seq_mask']
204
+
205
+
206
+ def get_pairwise_iptm(result, asym_id, start_i, end_i, start_j, end_j):
207
+ """This will calculate ipTM as usual, just between given chains"""
208
+
209
+ input_pairwise_iptm = {}
210
+
211
+ # Prepare inputs
212
+ outputs = deepcopy(result)
213
+ input_pairwise_iptm['seq_mask'] = np.full(len(asym_id), 0, dtype=float)
214
+ input_pairwise_iptm['asym_id'] = asym_id
215
+ input_pairwise_iptm['seq_mask'][np.concatenate((np.arange(start_i, end_i + 1),
216
+ np.arange(start_j, end_j + 1)))] = 1
217
+
218
+ return get_ptm_modified(input_pairwise_iptm, outputs, interface=True)
219
+
220
+
221
+ def get_per_chain_ptm(result, cmap, start, end):
222
+ """
223
+ Calculates the chain PTM score for a specified interface region, using contact probabilities.
224
+
225
+ Args:
226
+ af: AlphaFold object
227
+ cmap: Contact map
228
+ start: Start index of the interface region
229
+ end: End index of the interface region
230
+
231
+ Returns:
232
+ cpTM: Chain pTM score
233
+ """
234
+ # Extract only the relevant subset of the contact map
235
+ cmap_subset = cmap[start:end + 1, start:end + 1]
236
+
237
+ # Extract only the relevant subset of the logits map
238
+ pae_copy = deepcopy(result)["predicted_aligned_error"]
239
+ pae_copy['logits'] = pae_copy['logits'][start:end + 1, start:end + 1, :]
240
+
241
+ # Prepare inputs for the modified predicted_tm_score function
242
+ pae_copy['residue_weights'] = np.ones(end - start + 1, dtype=float)
243
+ pae_copy.pop('asym_id', None)
244
+
245
+ # Calculate and return chain PTM score
246
+ cptm = round(float(predicted_tm_score_modified(**pae_copy, use_jnp=True).max()), 3)
247
+
248
+ return cptm
249
+
250
+
251
+ def get_chain_and_interface_metrics(result, asym_id, use_probs_extra=False, use_jnp=True):
252
+ """
253
+ This function iterates over all pairs of chains and calculates the interface and interchain PTM score for each pair.
254
+
255
+ Args:
256
+ result: The result from AlphaFold.
257
+ asym_id: Array indicating chain boundaries.
258
+ use_probs_extra: If True, calculate interface pTM score based on contact probabilities. Default is False.
259
+ use_jnp: If True, use JAX numpy. Default is True.
260
+ Returns:
261
+ a dictionary with the pairwise interface pTM-s, and the chain-wise pTM.
262
+ returns None for each, if there was an error finding the logits for the pae matrix
263
+ """
264
+ # this is to deal with the ptm models (af2 monomer)
265
+ if len(asym_id.shape) > 1:
266
+ asym_id = asym_id[0]
267
+
268
+ full_length = len(asym_id)
269
+ # Prepare dictionaries to collect results
270
+ output = {'pairwise_actifptm': {}, 'pairwise_iptm': {}, 'per_chain_ptm': {}}
271
+ #residuewise_output = {'residuewise_actifptm': {}, 'residuewise_iptm': {}}
272
+ chain_starts_ends = get_chain_indices(asym_id, use_jnp=use_jnp)
273
+ pair_residue_weights_no_probs = np.zeros((full_length, full_length), dtype=float)
274
+
275
+ # Generate chain labels (A, B, C, ...)
276
+ chain_labels = list(string.ascii_uppercase)
277
+
278
+ # Define interface with 8A between Cb-s
279
+ cmap = get_contact_map(result, 8)
280
+
281
+ # This is for compatibility between colabdesign and colabfold
282
+ results = {}
283
+ if isinstance(result['predicted_aligned_error'], (np.ndarray, list)):
284
+ if 'pae_matrix_with_logits' in result.keys():
285
+ results['predicted_aligned_error'] = deepcopy(result['pae_matrix_with_logits'])
286
+ else:
287
+ print('There was an error retrieving the predicted aligned error matrix.')
288
+ return {"pairwise_actifptm": None, "pairwise_iptm": None, "per_chain_ptm": None, 'actifptm': None}
289
+ else:
290
+ results['predicted_aligned_error'] = deepcopy(result['predicted_aligned_error'])
291
+
292
+ for i, (start_i, end_i) in enumerate(chain_starts_ends):
293
+ chain_label_i = chain_labels[i % len(chain_labels)] # Wrap around if more than 26 chains
294
+ for j, (start_j, end_j) in enumerate(chain_starts_ends):
295
+ chain_label_j = chain_labels[j % len(chain_labels)] # Wrap around if more than 26 chains
296
+ if i < j: # Avoid self-comparison and duplicate comparisons
297
+ key = f"{chain_label_i}-{chain_label_j}"
298
+ if not use_probs_extra:
299
+ residuewise_actifptm, seq_mask = get_actifptm_contacts(results, asym_id, cmap, start_i, end_i, start_j, end_j)
300
+ pair_residue_weights_no_probs += seq_mask[None, :] * seq_mask[:, None]
301
+ output['pairwise_actifptm'][key] = round(float(residuewise_actifptm.max()), 3)
302
+ #residuewise_output['residuewise_actifptm'][key] = residuewise_actifptm
303
+ else:
304
+ residuewise_actifptm = get_actifptm_probs(results, asym_id, cmap, start_i, end_i, start_j, end_j)
305
+ output['pairwise_actifptm'][key] = round(float(residuewise_actifptm.max()), 3)
306
+ #residuewise_output['residuewise_actifptm'][key] = residuewise_actifptm
307
+
308
+
309
+ # Also add regular i_ptm (interchain), pairwise
310
+ residuewise_iptm = get_pairwise_iptm(results, asym_id, start_i, end_i, start_j, end_j)
311
+ output['pairwise_iptm'][key] = round(float(residuewise_iptm.max()), 3)
312
+ #residuewise_output['residuewise_iptm'][key] = output['pairwise_iptm'][key]
313
+
314
+ # Also calculate pTM score for single chain
315
+ output['per_chain_ptm'][chain_label_i] = get_per_chain_ptm(results, cmap, start_i, end_i)
316
+
317
+ if not use_probs_extra:
318
+ # we need to recreate the full matrix from the previously calculated contacts
319
+ pair_mask = asym_id[:, None] != asym_id[None, :]
320
+ pair_residue_weights_no_probs *= pair_mask
321
+ pae = {"residue_weights": np.full(full_length, 1, dtype=float),
322
+ **results["predicted_aligned_error"],
323
+ "asym_id": asym_id}
324
+ output['actifptm'] = round(float(predicted_tm_score_modified(**pae, pair_residue_weights=pair_residue_weights_no_probs).max()), 3)
325
+ else:
326
+ output['actifptm'] = round(float(get_actifptm_probs(results, asym_id, cmap, 0, full_length - 1, 0, full_length - 1).max()), 3)
327
+
328
+ return output
329
+
330
+
331
+ def plot_matrix(actifptm_dict, iptm_dict, cptm_dict, prefix='rank', ax_in=None, fig_path=None):
332
+ """This function plots the metrics in a matrix. The diagonal will be chain-wise pTM-s,
333
+ the lower triangle displays actifptm and the upper triangle the ipTM (calculated in the original way)."""
334
+ from matplotlib import pyplot as plt
335
+ if not ax_in: # In case, we are not plotting multiple models next to each other
336
+ fig, ax = plt.subplots(1, 1, figsize=(5, 5), squeeze=False)
337
+
338
+ # get chain ids
339
+ letters = sorted(set([key.split('-')[0] for key in actifptm_dict.keys()] + [key.split('-')[1] for key in actifptm_dict.keys()]))
340
+
341
+ # initialize dataframe
342
+ data = pd.DataFrame(np.zeros((len(letters), len(letters))), index=letters, columns=letters)
343
+
344
+ # populate dataframe with ifptm and iptm values
345
+ for key, value in actifptm_dict.items():
346
+ i, j = key.split('-')
347
+ data.loc[j, i] = value
348
+ data.loc[i, j] = iptm_dict[f'{i}-{j}']
349
+
350
+ # add cptm values to the dataframe
351
+ for chain, value in cptm_dict.items():
352
+ if chain in data.index:
353
+ data.loc[chain, chain] = value
354
+
355
+ # create masks for lower, upper triangles, and diagonal
356
+ mask_upper = np.triu(np.ones(data.shape), k=1)
357
+ mask_lower = np.tril(np.ones(data.shape), k=-1)
358
+ mask_diagonal = np.eye(data.shape[0])
359
+
360
+ dyn_size_ch = max(- 1.5 * len(letters) + 18, 3) # resize the font with differently sized figures
361
+ # Plot lower triangle (actifpTM)
362
+ ax_in.imshow(np.ma.masked_where(mask_upper + mask_diagonal, data), cmap='Blues', vmax=1, vmin=0)
363
+
364
+ # Plot upper triangle (ipTM)
365
+ ax_in.imshow(np.ma.masked_where(mask_lower + mask_diagonal, data), cmap='Reds', vmax=1, vmin=0)
366
+
367
+ # Plot diagonal (cpTM)
368
+ diagonal_data = np.diag(np.diag(data))
369
+ im = ax_in.imshow(np.ma.masked_where(~mask_diagonal.astype(bool), diagonal_data), cmap='Greys', vmax=1, vmin=0)
370
+
371
+ # Add colorbar for cpTM (diagonal)
372
+ cbar = plt.colorbar(im, ax=ax_in, fraction=0.046, pad=0.04)
373
+ cbar.ax.tick_params(labelsize=dyn_size_ch) # Set fontsize for colorbar labels
374
+ cbar.outline.set_edgecolor('grey')
375
+ cbar.outline.set_linewidth(0.5)
376
+
377
+ # Add text annotations
378
+ for i in range(data.shape[0]):
379
+ for j in range(data.shape[1]):
380
+ value = data.iloc[i, j]
381
+ if not mask_upper[i, j] and not mask_diagonal[i, j]:
382
+ text_color = 'white' if value > 0.8 else 'black'
383
+ ax_in.text(j, i, f"{value:.2f}", ha='center', va='center', color=text_color, fontsize=dyn_size_ch*1.2)
384
+ elif not mask_lower[i, j] and not mask_diagonal[i, j]:
385
+ text_color = 'white' if value > 0.8 else 'black'
386
+ ax_in.text(j, i, f"{value:.2f}", ha='center', va='center', color=text_color, fontsize=dyn_size_ch*1.2)
387
+ elif mask_diagonal[i, j]:
388
+ text_color = 'white' if value > 0.5 else 'black'
389
+ ax_in.text(j, i, f"{value:.2f}", ha='center', va='center', color=text_color, fontsize=dyn_size_ch*1.2)
390
+
391
+ # Custom colored legend (ifpTM, cpTM, ipTM)
392
+ x_start = 0.35
393
+ x_offset = 0.125
394
+ dyn_size = 16
395
+ ax_in.text(0.1, 1.05, prefix, fontsize=dyn_size, fontweight='bold', color='black', ha='center', transform=ax_in.transAxes)
396
+ ax_in.text(x_start + x_offset - 0.06, 1.05, 'actifpTM', fontsize=dyn_size, fontweight='bold', color='darkblue', ha='center', transform=ax_in.transAxes)
397
+ ax_in.text(x_start + 2 * x_offset, 1.05, ' - ', fontsize=dyn_size, fontweight='bold', color='black', ha='center', transform=ax_in.transAxes)
398
+ ax_in.text(x_start + 3 * x_offset, 1.05, 'cpTM', fontsize=dyn_size, fontweight='bold', color='dimgrey', ha='center', transform=ax_in.transAxes)
399
+ ax_in.text(x_start + 4 * x_offset, 1.05, ' - ', fontsize=dyn_size, fontweight='bold', color='black', ha='center', transform=ax_in.transAxes)
400
+ ax_in.text(x_start + 5 * x_offset, 1.05, 'ipTM', fontsize=dyn_size, fontweight='bold', color='firebrick', ha='center', transform=ax_in.transAxes)
401
+
402
+ # Format labels
403
+ ax_in.set_yticks(np.arange(len(letters)))
404
+ ax_in.set_yticklabels(letters, rotation=0, fontsize=dyn_size_ch*1.5)
405
+ ax_in.set_xticks(np.arange(len(letters)))
406
+ ax_in.set_xticklabels(letters, fontsize=dyn_size_ch*1.5)
407
+
408
+ # If this was only one plot, display and save it.
409
+ # If multiple plots have been appended, this needs to be done from the calling function
410
+ if not ax_in:
411
+ plt.tight_layout()
412
+ plt.savefig(fig_path, dpi=200, bbox_inches='tight')
413
+
414
+ def plot_chain_pairwise_analysis(info, prefix='rank_', fig_path="chain_pairwise_ptm.png"):
415
+ from matplotlib import pyplot as plt
416
+ num_elements = len(info)
417
+ fig, axes = plt.subplots(1, num_elements, figsize=(num_elements * 5, 5), squeeze=False)
418
+
419
+ # We do this so that the same function can be used both for colabfold and colabdesign
420
+ for idx, ax in enumerate(axes[0]):
421
+ prefix_plot = prefix + str(idx+1)
422
+ if isinstance(info[idx], dict):
423
+ actifptm_dict = info[idx].get("pairwise_actifptm", {})
424
+ iptm_dict = info[idx].get("pairwise_iptm", {})
425
+ cptm_dict = info[idx].get("per_chain_ptm", {})
426
+ else:
427
+ actifptm_dict = info[idx][4]
428
+ iptm_dict = info[idx][3]
429
+ cptm_dict = info[idx][5]
430
+
431
+ plot_matrix(actifptm_dict, iptm_dict, cptm_dict, prefix=prefix_plot, ax_in=ax, fig_path=fig_path)
432
+
433
+ plt.tight_layout()
434
+ plt.savefig(fig_path, dpi=200, bbox_inches='tight')
435
+ plt.close(fig)
data/colabfold/alphafold/models.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from functools import wraps, partialmethod
3
+ from typing import Tuple, List, Optional
4
+ import haiku
5
+ from alphafold.model import model, config, data
6
+ from alphafold.model.modules import AlphaFold
7
+ from alphafold.model.modules_multimer import AlphaFold as AlphaFoldMultimer
8
+
9
+ def get_model_haiku_params(
10
+ data_dir: str,
11
+ model_type: str,
12
+ model_number: str,
13
+ use_fuse: bool = True,
14
+ to_jnp: bool = True,
15
+ ) -> haiku.Params:
16
+ """Get the Haiku parameters from a model type and number."""
17
+ import os
18
+ import numpy as np
19
+ from alphafold.model import utils
20
+ import jax.numpy as jnp
21
+
22
+ is_deepfold = False
23
+ if model_type == "alphafold2_multimer_v1":
24
+ file = f"params_model_{model_number}_multimer.npz"
25
+ elif model_type == "alphafold2_multimer_v2":
26
+ file = f"params_model_{model_number}_multimer_v2.npz"
27
+ elif model_type == "alphafold2_multimer_v3":
28
+ file = f"params_model_{model_number}_multimer_v3.npz"
29
+ elif model_type == "alphafold2_ptm":
30
+ file = f"params_model_{model_number}_ptm.npz"
31
+ elif model_type == "alphafold2":
32
+ file = f"params_model_{model_number}.npz"
33
+ elif model_type == "deepfold_v1":
34
+ file = f"deepfold_model_{model_number}.npz"
35
+ is_deepfold = True
36
+ else:
37
+ raise ValueError(f"Unknown model_type {model_type}")
38
+
39
+ path = os.path.join(data_dir, "params", file)
40
+ params = np.load(path, allow_pickle=False)
41
+ return utils.flat_params_to_haiku(params, fuse=use_fuse, to_jnp=to_jnp)
42
+
43
+
44
+ def model_to_config_name(model_type: str, model_number: str) -> str:
45
+ if model_type == "alphafold2_multimer_v1":
46
+ return f"model_{model_number}_multimer"
47
+ elif model_type == "alphafold2_multimer_v2":
48
+ return f"model_{model_number}_multimer_v2"
49
+ elif model_type == "alphafold2_multimer_v3":
50
+ return f"model_{model_number}_multimer_v3"
51
+ elif model_type == "alphafold2_ptm":
52
+ return f"model_{model_number}_ptm"
53
+ elif model_type == "alphafold2":
54
+ return f"model_{model_number}"
55
+ elif model_type == "deepfold_v1":
56
+ return f"model_{model_number}"
57
+ else:
58
+ raise ValueError(f"Unknown model_type {model_type}")
59
+
60
+
61
+ def load_models_and_params(
62
+ num_models: int,
63
+ use_templates: bool,
64
+ num_recycles: Optional[int] = None,
65
+ recycle_early_stop_tolerance: Optional[float] = None,
66
+ num_ensemble: int = 1,
67
+ model_order: Optional[List[int]] = None,
68
+ model_type: str = "",
69
+ data_dir: Path = Path("."),
70
+ stop_at_score: float = 100,
71
+ rank_by: str = "auto",
72
+ max_seq: Optional[int] = None,
73
+ max_extra_seq: Optional[int] = None,
74
+ use_cluster_profile: bool = True,
75
+ use_fuse: bool = True,
76
+ use_bfloat16: bool = True,
77
+ use_dropout: bool = False,
78
+ save_all: bool = False,
79
+ calc_extra_ptm: bool = False,
80
+ use_probs_extra: bool = True
81
+ ) -> List[Tuple[str, model.RunModel, haiku.Params]]:
82
+ """We use only two actual models and swap the parameters to avoid recompiling.
83
+
84
+ Note that models 1 and 2 have a different number of parameters compared to models 3, 4 and 5,
85
+ so we load model 1 and model 3.
86
+ """
87
+
88
+ # Use only two model and later swap params to avoid recompiling
89
+ model_runner_and_params: [Tuple[str, model.RunModel, haiku.Params]] = []
90
+
91
+ if model_order is None:
92
+ model_order = [1, 2, 3, 4, 5]
93
+ else:
94
+ model_order.sort()
95
+
96
+ model_build_order = [3, 4, 5, 1, 2]
97
+ if "multimer" in model_type:
98
+ models_need_compilation = [3]
99
+ else:
100
+ # only models 1,2 use templates
101
+ models_need_compilation = [1, 3] if use_templates else [3]
102
+
103
+ model_runner_and_params_build_order: [Tuple[str, model.RunModel, haiku.Params]] = []
104
+ model_runner = None
105
+ for model_number in model_build_order:
106
+ if model_number in models_need_compilation:
107
+ # get configurations
108
+ config_name = model_to_config_name(model_type, model_number)
109
+ model_config = config.model_config(config_name)
110
+ model_config.model.stop_at_score = float(stop_at_score)
111
+ model_config.model.rank_by = rank_by
112
+
113
+ # set dropouts
114
+ model_config.model.global_config.eval_dropout = use_dropout
115
+
116
+ # set bfloat options
117
+ model_config.model.global_config.bfloat16 = use_bfloat16
118
+
119
+ # set fuse options
120
+ model_config.model.embeddings_and_evoformer.evoformer.triangle_multiplication_incoming.fuse_projection_weights = use_fuse
121
+ model_config.model.embeddings_and_evoformer.evoformer.triangle_multiplication_outgoing.fuse_projection_weights = use_fuse
122
+ if "multimer" in config_name or model_number in [1,2]:
123
+ model_config.model.embeddings_and_evoformer.template.template_pair_stack.triangle_multiplication_incoming.fuse_projection_weights = use_fuse
124
+ model_config.model.embeddings_and_evoformer.template.template_pair_stack.triangle_multiplication_outgoing.fuse_projection_weights = use_fuse
125
+
126
+ # set number of sequences options
127
+ if max_seq is not None:
128
+ if "multimer" in config_name:
129
+ model_config.model.embeddings_and_evoformer.num_msa = max_seq
130
+ else:
131
+ model_config.data.eval.max_msa_clusters = max_seq
132
+
133
+ if max_extra_seq is not None:
134
+ if "multimer" in config_name:
135
+ model_config.model.embeddings_and_evoformer.num_extra_msa = max_extra_seq
136
+ else:
137
+ model_config.data.common.max_extra_msa = max_extra_seq
138
+
139
+ # disable some outputs if not being saved
140
+ if not save_all:
141
+ if not calc_extra_ptm:
142
+ model_config.model.heads.distogram.weight = 0.0
143
+ model_config.model.heads.masked_msa.weight = 0.0
144
+ model_config.model.heads.experimentally_resolved.weight = 0.0
145
+
146
+ # set number of recycles and ensembles
147
+ if "multimer" in config_name:
148
+ if num_recycles is not None:
149
+ model_config.model.num_recycle = num_recycles
150
+ model_config.model.embeddings_and_evoformer.use_cluster_profile = use_cluster_profile
151
+ model_config.model.num_ensemble_eval = num_ensemble
152
+ else:
153
+ if num_recycles is not None:
154
+ model_config.data.common.num_recycle = num_recycles
155
+ model_config.model.num_recycle = num_recycles
156
+ model_config.data.eval.num_ensemble = num_ensemble
157
+
158
+ if recycle_early_stop_tolerance is not None:
159
+ model_config.model.recycle_early_stop_tolerance = recycle_early_stop_tolerance
160
+
161
+ # get model runner
162
+ params = get_model_haiku_params(
163
+ model_type=model_type,
164
+ model_number=model_number,
165
+ data_dir=str(data_dir),
166
+ use_fuse=use_fuse
167
+ )
168
+
169
+ model_runner = model.RunModel(
170
+ model_config,
171
+ params,
172
+ extended_ptm_config={'calc_extended_ptm': calc_extra_ptm,
173
+ 'use_probs_extended': use_probs_extra}
174
+ )
175
+
176
+ params = get_model_haiku_params(
177
+ model_type=model_type,
178
+ model_number=model_number,
179
+ data_dir=str(data_dir),
180
+ use_fuse=use_fuse,
181
+ )
182
+ # keep only parameters of compiled model
183
+ params_subset = {}
184
+ for k in model_runner.params.keys():
185
+ params_subset[k] = params[k]
186
+
187
+ model_name = f"model_{model_number}"
188
+ model_runner_and_params_build_order.append(
189
+ (model_name, model_runner, params_subset)
190
+ )
191
+ # reorder model
192
+ for n, model_number in enumerate(model_order):
193
+ if n == num_models:
194
+ break
195
+ model_name = f"model_{model_number}"
196
+ for m in model_runner_and_params_build_order:
197
+ if model_name == m[0]:
198
+ model_runner_and_params.append(m)
199
+ break
200
+ return model_runner_and_params
data/colabfold/alphafold/msa.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Mapping, Any
2
+ import numpy as np
3
+
4
+ from alphafold.model.features import FeatureDict
5
+ from alphafold.model.tf import shape_placeholders
6
+
7
+ NUM_RES = shape_placeholders.NUM_RES
8
+ NUM_MSA_SEQ = shape_placeholders.NUM_MSA_SEQ
9
+ NUM_EXTRA_SEQ = shape_placeholders.NUM_EXTRA_SEQ
10
+ NUM_TEMPLATES = shape_placeholders.NUM_TEMPLATES
11
+
12
+ def make_fixed_size(
13
+ feat: Mapping[str, Any],
14
+ shape_schema,
15
+ msa_cluster_size: int,
16
+ extra_msa_size: int,
17
+ num_res: int,
18
+ num_templates: int = 0,
19
+ ) -> FeatureDict:
20
+ """Guess at the MSA and sequence dimensions to make fixed size."""
21
+ pad_size_map = {
22
+ NUM_RES: num_res,
23
+ NUM_MSA_SEQ: msa_cluster_size,
24
+ NUM_EXTRA_SEQ: extra_msa_size,
25
+ NUM_TEMPLATES: num_templates,
26
+ }
27
+ for k, v in feat.items():
28
+ # Don't transfer this to the accelerator.
29
+ if k == "extra_cluster_assignment":
30
+ continue
31
+ shape = list(v.shape)
32
+
33
+ schema = shape_schema[k]
34
+
35
+ assert len(shape) == len(schema), (
36
+ f"Rank mismatch between shape and shape schema for {k}: "
37
+ f"{shape} vs {schema}"
38
+ )
39
+ pad_size = [pad_size_map.get(s2, None) or s1 for (s1, s2) in zip(shape, schema)]
40
+ padding = [(0, p - v.shape[i]) for i, p in enumerate(pad_size)]
41
+
42
+ if padding:
43
+ feat[k] = np.pad(v, padding)
44
+ return feat