Skip to content

Commit d0bd9ec

Browse files
committed
add colab notebook
1 parent ec47eb3 commit d0bd9ec

File tree

1 file changed

+1
-0
lines changed

1 file changed

+1
-0
lines changed

β€Žscripts/colab.ipynbβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"cells":[{"cell_type":"markdown","metadata":{"id":"dkAls9zOJRMk"},"source":["# Protein-Protein Osmotic Second Virial Coefficient Calculation\n","\n","This takes two input PDB structures and calculates the potential of mean force between them, averaging over the angular space using a regular grid. The\n","Calvados 3 parameters for the pair-wise interaction between coarse grained amino acids is used.\n","The calculation is done using the still experimental `virialize` tool, written\n","in Rust. It is part of the yet unreleased Rust version of Faunus. Use with care!\n","\n","_M. Lund, December 2024_"]},{"cell_type":"code","execution_count":1,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":20679,"status":"ok","timestamp":1735914854943,"user":{"displayName":"Mikael","userId":"14077353807121110739"},"user_tz":0},"id":"l2CAcBNEeUN8","outputId":"47b06405-bdae-4b92-e6ef-4698c8b20ee7"},"outputs":[{"name":"stdout","output_type":"stream","text":["\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.5/1.5 MB\u001b[0m \u001b[31m6.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m7.4/7.4 MB\u001b[0m \u001b[31m12.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m9.1/9.1 MB\u001b[0m \u001b[31m19.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.3/1.3 MB\u001b[0m \u001b[31m20.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h"]}],"source":["# @title\n","!pip install virialize mdtraj --quiet\n","import mdtraj as md\n","from google.colab import files\n","import matplotlib.pyplot as plt\n","import numpy as np\n","import os\n","import ipywidgets as widgets\n","from IPython.display import display\n","%matplotlib inline"]},{"cell_type":"code","execution_count":2,"metadata":{"executionInfo":{"elapsed":5,"status":"ok","timestamp":1735914854944,"user":{"displayName":"Mikael","userId":"14077353807121110739"},"user_tz":0},"id":"sun3tQui4_kd"},"outputs":[],"source":["# @title\n","def convert_pdb(pdb_file, output_xyz_file):\n"," ''' Convert PDB to coarse grained XYZ file; one bead per amino acid '''\n"," traj = md.load_pdb(pdb_file, frame=0)\n"," residues = []\n"," for res in traj.topology.residues:\n"," if not res.is_protein:\n"," continue\n"," cm = [0.0, 0.0, 0.0] # residue mass center\n"," mw = 0.0 # residue weight\n"," for a in res.atoms:\n"," cm = cm + a.element.mass * traj.xyz[0][a.index]\n"," mw = mw + a.element.mass\n"," cm = cm / mw * 10.0\n"," residues.append(dict(name=res.name, cm=cm))\n"," with open(output_xyz_file, \"w\") as f:\n"," f.write(f'{len(residues)}\\n')\n"," for i in residues:\n"," f.write(f\"{i['name']} {i['cm'][0]} {i['cm'][1]} {i['cm'][2]}\\n\")\n"," print(f\"Converted {pdb_file} -\u003e {output_xyz_file} with {len(residues)} residues.\")"]},{"cell_type":"markdown","metadata":{"id":"b2nGPN5prwxl"},"source":["## Generate Force Field\n","\n","The following creates the two files `calvados3.yaml` and `topology.taml` which sets up the force field. By default this provides a coarse grained representation of amino acids: one bead or interaction site per residue. You may customize to other representations if you wish."]},{"cell_type":"code","execution_count":3,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":5,"status":"ok","timestamp":1735914854944,"user":{"displayName":"Mikael","userId":"14077353807121110739"},"user_tz":0},"id":"H2wpwzbtlBVD","outputId":"1d660c2e-7b36-4fbc-ac45-75158d855077"},"outputs":[{"name":"stdout","output_type":"stream","text":["Writing calvados3.yaml\n"]}],"source":["# @title\n","%%writefile calvados3.yaml\n","comment: \"Calvados 3 coarse grained amino acid model. Charges fixed to generic, neutral pH\"\n","version: 0.1.0\n","atoms:\n"," - {charge: 1.0, hydrophobicity: !Lambda 0.7407902764839954, mass: 156.19, name: ARG, Οƒ: 6.56, Ξ΅: 0.8368}\n"," - {charge: -1.0, hydrophobicity: !Lambda 0.092587557536158, mass: 115.09, name: ASP, Οƒ: 5.58, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.3706962163690402, mass: 114.1, name: ASN, Οƒ: 5.68, Ξ΅: 0.8368}\n"," - {charge: -1.0, hydrophobicity: !Lambda 0.000249590539426, mass: 129.11, name: GLU, Οƒ: 5.92, Ξ΅: 0.8368}\n"," - {charge: 1.0, hydrophobicity: !Lambda 0.1380602542039267, mass: 128.17, name: LYS, Οƒ: 6.36, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.4087176216525476, mass: 137.14, name: HIS, Οƒ: 6.08, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.3143449791669133, mass: 128.13, name: GLN, Οƒ: 6.02, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.4473142572693176, mass: 87.08, name: SER, Οƒ: 5.18, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.5922529084601322, mass: 103.14, name: CYS, Οƒ: 5.48, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.7538308115197386, mass: 57.05, name: GLY, Οƒ: 4.5, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.2672387936544146, mass: 101.11, name: THR, Οƒ: 5.62, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.3377244362031627, mass: 71.07, name: ALA, Οƒ: 5.04, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.5170874160398543, mass: 131.2, name: MET, Οƒ: 6.18, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.950628687301107, mass: 163.18, name: TYR, Οƒ: 6.46, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.2936174211771383, mass: 99.13, name: VAL, Οƒ: 5.86, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 1.033450123574512, mass: 186.22, name: TRP, Οƒ: 6.78, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.5548615312993875, mass: 113.16, name: LEU, Οƒ: 6.18, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.5130398874425708, mass: 113.16, name: ILE, Οƒ: 6.18, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.3469777523519372, mass: 97.12, name: PRO, Οƒ: 5.56, Ξ΅: 0.8368}\n"," - {charge: 0.0, hydrophobicity: !Lambda 0.8906449355499866, mass: 147.18, name: PHE, Οƒ: 6.36, Ξ΅: 0.8368}"]},{"cell_type":"code","execution_count":4,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"collapsed":true,"executionInfo":{"elapsed":4,"status":"ok","timestamp":1735914854944,"user":{"displayName":"Mikael","userId":"14077353807121110739"},"user_tz":0},"id":"5xEt7ayslehB","outputId":"7bed2418-6045-4fe4-9e61-04a43bb41c5b"},"outputs":[{"name":"stdout","output_type":"stream","text":["Writing topology.yaml\n"]}],"source":["# @title\n","%%writefile topology.yaml\n","include: [calvados3.yaml]\n","system:\n"," energy:\n"," nonbonded:\n"," # Note that a Coulomb term is automatically added, so don't specify one here!\n"," default:\n"," - !AshbaughHatch {mixing: arithmetic, cutoff: 100.0}"]},{"cell_type":"markdown","metadata":{"id":"YbpG_WQoLrC-"},"source":["# Upload PDB files\n","\n","Here you must upload two PDB files with atomistic information about the globular proteins to be investigated. These will be coarse grained to an amino acid representation, matching the Calvados 3 model. Currently this is not very sophisticated -- see included Python function for details.\n","\n","_If you run into a stack-related error for larger PDB files, try switching to another browser. This is a known problem with CoLab._"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","colab":{"background_save":true,"base_uri":"https://localhost:8080/","height":35},"id":"5XdblQ_Gbusc"},"outputs":[{"data":{"text/html":["\n"," \u003cinput type=\"file\" id=\"files-c473cfd3-e450-488f-86d7-aa3e954ae6a5\" name=\"files[]\" multiple disabled\n"," style=\"border:none\" /\u003e\n"," \u003coutput id=\"result-c473cfd3-e450-488f-86d7-aa3e954ae6a5\"\u003e\n"," Upload widget is only available when the cell has been executed in the\n"," current browser session. Please rerun this cell to enable.\n"," \u003c/output\u003e\n"," \u003cscript\u003e// Copyright 2017 Google LLC\n","//\n","// Licensed under the Apache License, Version 2.0 (the \"License\");\n","// you may not use this file except in compliance with the License.\n","// You may obtain a copy of the License at\n","//\n","// http://www.apache.org/licenses/LICENSE-2.0\n","//\n","// Unless required by applicable law or agreed to in writing, software\n","// distributed under the License is distributed on an \"AS IS\" BASIS,\n","// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n","// See the License for the specific language governing permissions and\n","// limitations under the License.\n","\n","/**\n"," * @fileoverview Helpers for google.colab Python module.\n"," */\n","(function(scope) {\n","function span(text, styleAttributes = {}) {\n"," const element = document.createElement('span');\n"," element.textContent = text;\n"," for (const key of Object.keys(styleAttributes)) {\n"," element.style[key] = styleAttributes[key];\n"," }\n"," return element;\n","}\n","\n","// Max number of bytes which will be uploaded at a time.\n","const MAX_PAYLOAD_SIZE = 100 * 1024;\n","\n","function _uploadFiles(inputId, outputId) {\n"," const steps = uploadFilesStep(inputId, outputId);\n"," const outputElement = document.getElementById(outputId);\n"," // Cache steps on the outputElement to make it available for the next call\n"," // to uploadFilesContinue from Python.\n"," outputElement.steps = steps;\n","\n"," return _uploadFilesContinue(outputId);\n","}\n","\n","// This is roughly an async generator (not supported in the browser yet),\n","// where there are multiple asynchronous steps and the Python side is going\n","// to poll for completion of each step.\n","// This uses a Promise to block the python side on completion of each step,\n","// then passes the result of the previous step as the input to the next step.\n","function _uploadFilesContinue(outputId) {\n"," const outputElement = document.getElementById(outputId);\n"," const steps = outputElement.steps;\n","\n"," const next = steps.next(outputElement.lastPromiseValue);\n"," return Promise.resolve(next.value.promise).then((value) =\u003e {\n"," // Cache the last promise value to make it available to the next\n"," // step of the generator.\n"," outputElement.lastPromiseValue = value;\n"," return next.value.response;\n"," });\n","}\n","\n","/**\n"," * Generator function which is called between each async step of the upload\n"," * process.\n"," * @param {string} inputId Element ID of the input file picker element.\n"," * @param {string} outputId Element ID of the output display.\n"," * @return {!Iterable\u003c!Object\u003e} Iterable of next steps.\n"," */\n","function* uploadFilesStep(inputId, outputId) {\n"," const inputElement = document.getElementById(inputId);\n"," inputElement.disabled = false;\n","\n"," const outputElement = document.getElementById(outputId);\n"," outputElement.innerHTML = '';\n","\n"," const pickedPromise = new Promise((resolve) =\u003e {\n"," inputElement.addEventListener('change', (e) =\u003e {\n"," resolve(e.target.files);\n"," });\n"," });\n","\n"," const cancel = document.createElement('button');\n"," inputElement.parentElement.appendChild(cancel);\n"," cancel.textContent = 'Cancel upload';\n"," const cancelPromise = new Promise((resolve) =\u003e {\n"," cancel.onclick = () =\u003e {\n"," resolve(null);\n"," };\n"," });\n","\n"," // Wait for the user to pick the files.\n"," const files = yield {\n"," promise: Promise.race([pickedPromise, cancelPromise]),\n"," response: {\n"," action: 'starting',\n"," }\n"," };\n","\n"," cancel.remove();\n","\n"," // Disable the input element since further picks are not allowed.\n"," inputElement.disabled = true;\n","\n"," if (!files) {\n"," return {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n"," }\n","\n"," for (const file of files) {\n"," const li = document.createElement('li');\n"," li.append(span(file.name, {fontWeight: 'bold'}));\n"," li.append(span(\n"," `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n"," `last modified: ${\n"," file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n"," 'n/a'} - `));\n"," const percent = span('0% done');\n"," li.appendChild(percent);\n","\n"," outputElement.appendChild(li);\n","\n"," const fileDataPromise = new Promise((resolve) =\u003e {\n"," const reader = new FileReader();\n"," reader.onload = (e) =\u003e {\n"," resolve(e.target.result);\n"," };\n"," reader.readAsArrayBuffer(file);\n"," });\n"," // Wait for the data to be ready.\n"," let fileData = yield {\n"," promise: fileDataPromise,\n"," response: {\n"," action: 'continue',\n"," }\n"," };\n","\n"," // Use a chunked sending to avoid message size limits. See b/62115660.\n"," let position = 0;\n"," do {\n"," const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n"," const chunk = new Uint8Array(fileData, position, length);\n"," position += length;\n","\n"," const base64 = btoa(String.fromCharCode.apply(null, chunk));\n"," yield {\n"," response: {\n"," action: 'append',\n"," file: file.name,\n"," data: base64,\n"," },\n"," };\n","\n"," let percentDone = fileData.byteLength === 0 ?\n"," 100 :\n"," Math.round((position / fileData.byteLength) * 100);\n"," percent.textContent = `${percentDone}% done`;\n","\n"," } while (position \u003c fileData.byteLength);\n"," }\n","\n"," // All done.\n"," yield {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n","}\n","\n","scope.google = scope.google || {};\n","scope.google.colab = scope.google.colab || {};\n","scope.google.colab._files = {\n"," _uploadFiles,\n"," _uploadFilesContinue,\n","};\n","})(self);\n","\u003c/script\u003e "],"text/plain":["\u003cIPython.core.display.HTML object\u003e"]},"metadata":{},"output_type":"display_data"}],"source":["# @title\n","xyzfile1 = files.upload()\n","xyzfile2 = files.upload()\n","if len(xyzfile1.keys()) != 1 or len(xyzfile2.keys()) != 1:\n"," raise ValueError(\"Please upload two single PDB files.\")\n","\n","pdb_files = [xyzfile1.keys(), xyzfile2.keys()]\n","for ndx, pdbfile in enumerate(pdb_files):\n"," for fn in pdbfile:\n"," if not fn.endswith(\".pdb\"):\n"," raise ValueError(\"PDB files required\")\n"," convert_pdb(fn, f\"mol{ndx+1}.xyz\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"PyhqA6nUa7BP"},"outputs":[],"source":["# @title Input parameters { display-mode: \"form\" }\n","\n","# @markdown #### Ionic strength (mol/l):\n","ionic_strength = 0.1 # @param {type:\"number\"}\n","# @markdown #### Temperature (kelvin):\n","temperature = 298.15 # @param {\"type\":\"number\"}\n","# @markdown #### Angular resolution (radians):\n","angular_resolution = 1 # @param {\"type\":\"slider\",\"min\":0.1,\"max\":1.2,\"step\":0.1}\n","# @markdown #### Minimum mass-center separation (angstrom):\n","min_distance = 10 # @param {\"type\":\"number\"}\n","# @markdown #### Maximum mass-center separation (angstrom):\n","max_distance = 60 # @param {\"type\":\"number\"}\n","# @markdown #### Mass-center separation steps (angstrom):\n","distance_step = 2 # @param {\"type\":\"number\"}\n","\n","!virialize scan --icotable \\\n","--mol1 mol1.xyz --mol2 mol2.xyz \\\n","--top topology.yaml \\\n","--molarity {ionic_strength} \\\n","--resolution {angular_resolution} \\\n","--rmin {min_distance} --rmax {max_distance} --dr {distance_step} \\\n","--temperature {temperature} \\\n","--pmf pmf.dat\n","\n","r, w, u = np.loadtxt(\"pmf.dat\", unpack=True)\n","plt.plot(r, w, label=\"Free energy\", color=\"orange\", lw=4, alpha=0.7)\n","plt.plot(r, u, label=\"Mean energy\", color=\"red\", lw=4, alpha=0.7)\n","plt.legend(loc=0, frameon=False)\n","plt.xlabel('Mass center separation (angstrom)')\n","plt.ylabel('Energy (kT)')"]},{"cell_type":"markdown","metadata":{"id":"fqGsOhulOp5_"},"source":["# Experimental section using `ipywidget`\n","\n","This is incomplete and cannot be used."]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"EnhKMFgnGB4Q"},"outputs":[],"source":["# @title\n","resolution_slider = widgets.FloatSlider(\n"," value=1.0,\n"," min=0.1,\n"," max=1.2,\n"," step=0.1,\n"," description='Angular resolution:',\n"," disabled=False,\n"," continuous_update=False,\n"," orientation='horizontal',\n"," readout=True,\n"," readout_format='.1f',\n",")\n","\n","interval_slider = widgets.FloatRangeSlider(\n"," value=[25, 50],\n"," min=0,\n"," max=120.0,\n"," step=1.0,\n"," description='Distances (β„«)',\n"," disabled=False,\n"," continuous_update=False,\n"," orientation='horizontal',\n"," readout=True,\n"," readout_format='.1f',\n",")\n","pdb_upload1 = widgets.FileUpload(accept='.pdb', multiple=False)\n","pdb_upload2 = widgets.FileUpload(accept='.pdb', multiple=False)\n","\n","display(widgets.HBox([widgets.Label(value=\"1st PDB:\"), pdb_upload1]))\n","display(widgets.HBox([widgets.Label(value=\"2nd PDB:\"), pdb_upload2]))\n","display(interval_slider)\n","display(resolution_slider)\n","\n","button = widgets.Button(description=\"Run!\")\n","output = widgets.Output()\n","\n","def on_button_clicked(b):\n"," # Display the message within the output widget.\n"," with output:\n"," print(\"Button clicked.\")\n","\n","button.on_click(on_button_clicked)\n","display(button, output)"]}],"metadata":{"colab":{"authorship_tag":"ABX9TyNDhPhBENrhxCa8uXeWb7LE","name":"","provenance":[{"file_id":"1F0B6BiJKh_ABc4QXYS33L1_uwU1Asl9k","timestamp":1733143763779}],"version":""},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}

0 commit comments

Comments
Β (0)