{ "cells": [ { "cell_type": "code", "execution_count": 2, "id": "f76b47d6", "metadata": {}, "outputs": [], "source": [ "import mdtraj as md\n", "import os\n", "import numpy as np\n", "from ipywidgets import widgets\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "import pandas as pd\n", "import itertools\n", "from tqdm import tqdm \n", "import ot\n", "import MDAnalysis" ] }, { "cell_type": "code", "execution_count": null, "id": "1219123d-f44f-4e08-9e71-4dc45cd81ced", "metadata": {}, "outputs": [], "source": [ "def multiframe_pdb_to_xtc(pdb_file, save_path, prot_name):\n", " \n", " u = MDAnalysis.core.universe.Universe(pdb_file)\n", " at = u.atoms\n", " \n", " os.chdir(save_path)\n", " \n", " # Write the trajectory in .xtc format\n", " at.write(\".\".join([prot_name,'xtc']), frames='all')\n", " # Write a frame of the trajectory in .pdb format for topology information\n", " at.write(\".\".join([prot_name,'pdb']))" ] }, { "cell_type": "code", "execution_count": 4, "id": "6f669fe3", "metadata": {}, "outputs": [], "source": [ "def get_cluster_files(ensemble_path, ensemble_name, labels_umap):\n", " \n", " # Initial parameters\n", " var_dict = {'multiframe' : 'n', 'check_folder' : True, 'do_xtc' : False, 'do_pdb' : False,\n", " 'ensemble_name' : ensemble_name, 'ensemble_path' : ensemble_path}\n", " \n", " var_dict['xtc_files'] = [file for file in os.listdir(ensemble_path) if file.endswith(\".xtc\")] \n", " var_dict['pdb_files'] = [file for file in os.listdir(ensemble_path) if file.endswith(\".pdb\") or file.endswith(\".prmtop\") or file.endswith(\".parm7\") or file.endswith(\".gro\")]\n", " var_dict['folders'] = [file for file in os.listdir(ensemble_path) if (os.path.isdir(\"/\".join([ensemble_path,file])) and not file.startswith('.') and not file.startswith(\"results\"))]\n", " \n", " # File processing\n", " \n", " if len(var_dict[\"xtc_files\"]) + len(var_dict[\"folders\"]) + len(var_dict[\"pdb_files\"]) == 0:\n", " sys.exit(\"\".join(['Folder for ', var_dict[\"ensemble_name\"], ' ensemble is empty...']))\n", " \n", " # .xtc file with a .pdb topology file\n", " \n", " if len(var_dict[\"xtc_files\"]) >= len(var_dict[\"pdb_files\"]) and len(var_dict[\"pdb_files\"]) == 1:\n", "\n", " print('\\nTaking as input:\\n')\n", " print(\"\".join([str(var_dict[\"xtc_files\"][0]),' : trajectory of ',var_dict[\"ensemble_name\"],',']))\n", " print(\"\".join([str(var_dict[\"pdb_files\"][0]),' : topology file of ',var_dict[\"ensemble_name\"],'.']))\n", " if len(var_dict[\"xtc_files\"]) > 1:\n", " print(\"\\nMore than one .xtc file were found. Taking the first as the trajectory file.\\n\")\n", " var_dict[\"do_xtc\"] = True\n", " var_dict[\"xtc_root_path\"] = var_dict[\"ensemble_path\"]\n", " var_dict['check_folder'] = False\n", " \n", " # multiframe .pdb files\n", " \n", " if var_dict['multiframe'] == 'y' or (len(var_dict[\"pdb_files\"]) >= 1 and len(var_dict[\"xtc_files\"]) == 0):\n", " \n", " print('\\nTaking as input:\\n') \n", " print(\"\".join([str(var_dict[\"pdb_files\"][0]),' : trajectory of ',var_dict[\"ensemble_name\"],'.']))\n", " if len(var_dict[\"pdb_files\"]) > 1:\n", " print(\"\\nMore than one multiframe .pdb file were found. Taking the first as the trajectory file.\\n\")\n", " print(\"\\nTaking the previously converted files.\\n\")\n", " var_dict[\"do_xtc\"] = True\n", " var_dict[\"xtc_root_path\"] = \"/\".join([var_dict[\"ensemble_path\"],'converted_files'])\n", " var_dict[\"xtc_files\"] = [file for file in os.listdir(var_dict[\"xtc_root_path\"]) if file.endswith(\".xtc\")]\n", " var_dict[\"pdb_files\"] = [file for file in os.listdir(var_dict[\"xtc_root_path\"]) if file.endswith(\".pdb\")]\n", " var_dict['check_folder'] = False\n", " \n", " # folder with .pdb files\n", " \n", " if len(var_dict[\"folders\"]) >= 1 and var_dict['check_folder'] == True:\n", " \n", " print('\\nTaking as input:\\n')\n", " print(\"\".join([var_dict[\"folders\"][0],' folder contains: trajectory of ',var_dict[\"ensemble_name\"],\".\"]))\n", " if len(var_dict[\"folders\"]) > 1:\n", " print(\"\\nMore than one .pdb folder were found. Taking the first as the trajectory folder.\\n\")\n", " var_dict[\"do_pdb\"] = True\n", " \n", " if not var_dict[\"do_pdb\"] and not var_dict[\"do_xtc\"]:\n", " sys.exit(\"\".join(['\\n Sorry, I did not understood the input. Please follow the guidelines described in the function documentation to create ',ensemble_name,' folder.\\n'])) \n", " \n", " print(\"\\n----------------------------------------------------------------------------------\\n\")\n", " print(\"\\nCreating cluster-specific files...\\n\")\n", " \n", " results_path = \"/\".join([os.path.abspath(ensemble_path),\"_\".join(['results',ensemble_name])])\n", " save_files = \"/\".join([results_path, \"cluster_files\"])\n", " if not os.path.exists(save_files):\n", " os.mkdir(save_files)\n", " \n", " if var_dict[\"do_xtc\"]:\n", " \n", " traj_file = md.load_xtc(\"/\".join([var_dict[\"xtc_root_path\"],var_dict[\"xtc_files\"][0]]), top = \"/\".join([var_dict[\"xtc_root_path\"],var_dict[\"pdb_files\"][0]]))\n", " \n", " # Save .xtc cluster files\n", " for k in tqdm(range(len(np.unique(labels_umap[labels_umap >= 0])))):\n", " traj_file[np.where(labels_umap == k)].save_xtc(\"/\".join([save_files, \"\".join([ensemble_name,'_',str(k),'.xtc'])]))\n", "\n", " if var_dict[\"do_pdb\"]:\n", " \n", " conf_list = os.listdir(\"/\".join([var_dict[\"ensemble_path\"],var_dict[\"folders\"][0]]))\n", "\n", " for k in tqdm(range(len(np.unique(labels_umap[labels_umap >= 0])))):\n", " clus_k_path = \"/\".join([save_files, \"_\".join(['clus',str(k)])])\n", " if not os.path.exists(clus_k_path):\n", " os.mkdir(clus_k_path)\n", " \n", " clus_k = np.where(labels_umap == k)[0]\n", " for j in range(len(clus_k)):\n", " traj = md.load_pdb(\"/\".join([\"/\".join([var_dict[\"ensemble_path\"],var_dict[\"folders\"][0]]),conf_list[clus_k[j]]]))\n", " traj.save_pdb(\"/\".join([clus_k_path, \"\".join([ensemble_name,'_',str(clus_k[j]),'.pdb'])]))\n", "\n", " print(\"\\nFiles saved.\\n\") " ] }, { "cell_type": "code", "execution_count": 1, "id": "ff9c4941", "metadata": {}, "outputs": [], "source": [ "def plot_2umap(embedding_2d, labels_umap, ensemble_name, results_path):\n", " \n", " classified = np.where(labels_umap >= 0)[0]\n", " \n", " output1 = widgets.Output()\n", " with output1:\n", " fig, ax = plt.subplots()\n", " ax.scatter(embedding_2d[~classified, 0],\n", " embedding_2d[~classified, 1],\n", " color=(0.5, 0.5, 0.5),\n", " s=0.5,\n", " alpha=0.5)\n", " scatter = ax.scatter(embedding_2d[classified, 0],\n", " embedding_2d[classified, 1],\n", " c=labels_umap[classified],\n", " s=0.5,\n", " alpha = 1,\n", " cmap='Spectral')\n", " plt.xlabel('UMAP coordinate 1')\n", " plt.ylabel('UMAP coordinate 2')\n", " plt.title(\"\".join(['UMAP 2-dimensional projection after contact clustering for ',ensemble_name,' ensemble']), fontsize = 8)\n", " plt.savefig(\"/\".join([results_path, \"\".join([\"clusters_2d\", ensemble_name, '.png'])]), dpi = 199)\n", " plt.show()\n", "\n", " output2 = widgets.Output()\n", " with output2:\n", " repartition = pd.Series(labels_umap).value_counts()\n", " repartition.index = [\"Unclassified\" if i == -1 else i for i in repartition.index]\n", " display(pd.DataFrame({\"Cluster\" : np.array(repartition.index), \"Occupancy (%)\" : 100*np.array(repartition.values)/len(labels_umap)}))\n", " two_columns = widgets.HBox([output1, output2])\n", " display(two_columns)" ] }, { "cell_type": "code", "execution_count": 4, "id": "00dfbe24", "metadata": {}, "outputs": [], "source": [ "def get_wmaps(wcont_data, labels_umap, ensemble_name, results_path, subsequence = None):\n", " \n", " maps_path = \"/\".join([results_path,\"wcont_maps\"]) # Path to save files\n", " if not os.path.exists(maps_path): # Create if doesn't exist\n", " os.mkdir(maps_path)\n", " \n", " L = int(0.5*(1+np.sqrt(1+8*wcont_data.shape[1]))) # Sequence length\n", " list_pos = np.asarray(list(itertools.combinations(range(1,L+1), 2))) # List of position pairs\n", " \n", " repartition = pd.Series(labels_umap).value_counts() # Clustering partition\n", " repartition.index = [\"Unclassified\" if i == -1 else i for i in repartition.index]\n", " repartition = repartition.drop(\"Unclassified\")\n", " cont_data = np.zeros([len(repartition),len(list_pos)+1])\n", " \n", " for cluster in tqdm(repartition.index): \n", " \n", " # Cluster-specific w-contact matrix\n", " prop_cluster = pd.Series(labels_umap).value_counts().sort_index()[cluster]/np.shape(wcont_data)[0]\n", " cont_matrix = pd.DataFrame(np.concatenate([list_pos,np.asarray([wcont_data.loc[labels_umap == cluster,].mean()]).T], axis = 1), columns=['pos1','pos2','cp'])\n", " cont_matrix.pos1 = cont_matrix.pos1.astype(int)\n", " cont_matrix.pos2 = cont_matrix.pos2.astype(int)\n", " cont_data[np.where(repartition.index == cluster)[0][0],:] = np.append(cont_matrix.cp.to_numpy(), prop_cluster)\n", " cont_matrix = cont_matrix.pivot(index='pos1',columns='pos2',values='cp')\n", "\n", " if subsequence is not None:\n", "\n", " list_pos = list_pos - 1\n", " cont_matrix.index = np.unique(subsequence[list_pos[:,0]]).astype(int)\n", " cont_matrix.columns = np.unique(subsequence[list_pos[:,1]]).astype(int)\n", " \n", " fig = plt.figure()\n", " res = sns.heatmap(cont_matrix.T, cmap='Reds',square=True, cbar_kws={\"shrink\": .5,'label':\"Contact weight average\"})\n", " plt.suptitle(\" \".join([ensemble_name,'contact-based clustering']), fontsize=10)\n", " plt.title(\"\".join(['Cluster #',str(cluster),' with ',str(round(100*prop_cluster,2)),'% of occupation']), fontsize = 8)\n", "\n", " plt.xlabel('Sequence position')\n", " plt.ylabel('Sequence position')\n", " plt.xticks(rotation=0)\n", " res.set_xticklabels(res.get_xmajorticklabels(), fontsize = 6)\n", " res.set_yticklabels(res.get_ymajorticklabels(), fontsize = 6)\n", " plt.savefig(\"/\".join([maps_path,\"\".join([ensemble_name,'_',str(cluster),'.png'])]), dpi=199) # Save figure in \n", "\n", " np.save(\"/\".join([results_path,\"\".join([ensemble_name,'_contdata'])]),cont_data)" ] }, { "cell_type": "code", "execution_count": 11, "id": "a4c98c97", "metadata": {}, "outputs": [], "source": [ "def representative_ensemble(size, ensemble_path, ensemble_name, labels_umap):\n", " \n", " # Initial parameters\n", " var_dict = {'multiframe' : 'n', 'check_folder' : True, 'do_xtc' : False, 'do_pdb' : False,\n", " 'ensemble_name' : ensemble_name, 'ensemble_path' : ensemble_path}\n", " \n", " var_dict['xtc_files'] = [file for file in os.listdir(ensemble_path) if file.endswith(\".xtc\")] \n", " var_dict['pdb_files'] = [file for file in os.listdir(ensemble_path) if file.endswith(\".pdb\") or file.endswith(\".prmtop\") or file.endswith(\".parm7\") or file.endswith(\".gro\")]\n", " var_dict['folders'] = [file for file in os.listdir(ensemble_path) if (os.path.isdir(\"/\".join([ensemble_path,file])) and not file.startswith('.') and not file.startswith(\"results\"))]\n", " \n", " # File processing\n", " \n", " if len(var_dict[\"xtc_files\"]) + len(var_dict[\"folders\"]) + len(var_dict[\"pdb_files\"]) == 0:\n", " sys.exit(\"\".join(['Folder for ', var_dict[\"ensemble_name\"], ' ensemble is empty...']))\n", " \n", " # .xtc file with a .pdb topology file\n", " \n", " if len(var_dict[\"xtc_files\"]) >= len(var_dict[\"pdb_files\"]) and len(var_dict[\"pdb_files\"]) == 1:\n", "\n", " print('\\nTaking as input:\\n')\n", " print(\"\".join([str(var_dict[\"xtc_files\"][0]),' : trajectory of ',var_dict[\"ensemble_name\"],',']))\n", " print(\"\".join([str(var_dict[\"pdb_files\"][0]),' : topology file of ',var_dict[\"ensemble_name\"],'.']))\n", " if len(var_dict[\"xtc_files\"]) > 1:\n", " print(\"\\nMore than one .xtc file were found. Taking the first as the trajectory file.\\n\")\n", " var_dict[\"do_xtc\"] = True\n", " var_dict[\"xtc_root_path\"] = var_dict[\"ensemble_path\"]\n", " var_dict['check_folder'] = False\n", " \n", " # multiframe .pdb files\n", " \n", " if var_dict['multiframe'] == 'y' or (len(var_dict[\"pdb_files\"]) >= 1 and len(var_dict[\"xtc_files\"]) == 0):\n", " \n", " print('\\nTaking as input:\\n') \n", " print(\"\".join([str(var_dict[\"pdb_files\"][0]),' : trajectory of ',var_dict[\"ensemble_name\"],'.']))\n", " if len(var_dict[\"pdb_files\"]) > 1:\n", " print(\"\\nMore than one multiframe .pdb file were found. Taking the first as the trajectory file.\\n\")\n", " print(\"\\nTaking the previously converted files.\\n\")\n", " var_dict[\"do_xtc\"] = True\n", " var_dict[\"xtc_root_path\"] = \"/\".join([var_dict[\"ensemble_path\"],'converted_files'])\n", " var_dict[\"xtc_files\"] = [file for file in os.listdir(var_dict[\"xtc_root_path\"]) if file.endswith(\".xtc\")]\n", " var_dict[\"pdb_files\"] = [file for file in os.listdir(var_dict[\"xtc_root_path\"]) if file.endswith(\".pdb\")]\n", " var_dict['check_folder'] = False\n", " \n", " # folder with .pdb files\n", " \n", " if len(var_dict[\"folders\"]) >= 1 and var_dict['check_folder'] == True:\n", " \n", " print('\\nTaking as input:\\n')\n", " print(\"\".join([var_dict[\"folders\"][0],' folder contains: trajectory of ',var_dict[\"ensemble_name\"],\".\"]))\n", " if len(var_dict[\"folders\"]) > 1:\n", " print(\"\\nMore than one .pdb folder were found. Taking the first as the trajectory folder.\\n\")\n", " var_dict[\"do_pdb\"] = True\n", " \n", " if not var_dict[\"do_pdb\"] and not var_dict[\"do_xtc\"]:\n", " sys.exit(\"\".join(['\\n Sorry, I did not understood the input. Please follow the guidelines described in the function documentation to create ',ensemble_name,' folder.\\n'])) \n", " \n", " print(\"\\n----------------------------------------------------------------------------------\\n\")\n", " print(\"\\nSampling representative family...\\n\")\n", " \n", " repartition = pd.Series(labels_umap).value_counts() # Clustering partition\n", " repartition.index = [\"Unclassified\" if i == -1 else i for i in repartition.index]\n", " repartition = repartition.drop(\"Unclassified\")\n", " probas = repartition.values/np.sum(repartition.values)\n", "\n", " selected_conf = np.zeros(size)\n", " for i in range(size):\n", "\n", " choose_cluster = np.random.choice(repartition.index, size = 1, p = probas)[0]\n", " selected_conf[i] = np.random.choice(np.where(labels_umap == choose_cluster)[0], size = 1)[0]\n", " \n", " selected_conf = np.ndarray.astype(selected_conf, int)\n", " results_path = \"/\".join([os.path.abspath(ensemble_path),\"_\".join(['results',ensemble_name])])\n", " save_files = \"/\".join([results_path, \"representative_family\"])\n", " if not os.path.exists(save_files):\n", " os.mkdir(save_files)\n", " \n", " if var_dict[\"do_xtc\"]:\n", " \n", " traj_file = md.load_xtc(\"/\".join([var_dict[\"xtc_root_path\"],var_dict[\"xtc_files\"][0]]), top = \"/\".join([var_dict[\"xtc_root_path\"],var_dict[\"pdb_files\"][0]]))\n", " \n", " # Save .xtc file\n", " traj_file[selected_conf].save_xtc(\"/\".join([save_files, \"\".join([ensemble_name,'_repfam.xtc'])]))\n", "\n", " if var_dict[\"do_pdb\"]:\n", " \n", " conf_list = os.listdir(\"/\".join([var_dict[\"ensemble_path\"],var_dict[\"folders\"][0]]))\n", " # Save pdb folder\n", " for j in selected_conf:\n", " traj = md.load_pdb(\"/\".join([\"/\".join([var_dict[\"ensemble_path\"],var_dict[\"folders\"][0]]),conf_list[j]]))\n", " traj.save_pdb(\"/\".join([save_files, \"\".join([ensemble_name,'_',conf_list[j],'.pdb'])]))\n", "\n", " print(\"\\nFiles saved.\\n\") " ] }, { "cell_type": "code", "execution_count": 17, "id": "7069e00f", "metadata": {}, "outputs": [], "source": [ "def cluster_descriptors(ensemble_path, ensemble_name, labels_umap):\n", " \n", " # Initial parameters\n", " var_dict = {'multiframe' : 'n', 'check_folder' : True, 'do_xtc' : False, 'do_pdb' : False,\n", " 'ensemble_name' : ensemble_name, 'ensemble_path' : ensemble_path}\n", " \n", " var_dict['xtc_files'] = [file for file in os.listdir(ensemble_path) if file.endswith(\".xtc\")] \n", " var_dict['pdb_files'] = [file for file in os.listdir(ensemble_path) if file.endswith(\".pdb\") or file.endswith(\".prmtop\") or file.endswith(\".parm7\") or file.endswith(\".gro\")]\n", " var_dict['folders'] = [file for file in os.listdir(ensemble_path) if (os.path.isdir(\"/\".join([ensemble_path,file])) and not file.startswith('.') and not file.startswith(\"results\"))]\n", " \n", " # File processing\n", " \n", " if len(var_dict[\"xtc_files\"]) + len(var_dict[\"folders\"]) + len(var_dict[\"pdb_files\"]) == 0:\n", " sys.exit(\"\".join(['Folder for ', var_dict[\"ensemble_name\"], ' ensemble is empty...']))\n", " \n", " # .xtc file with a .pdb topology file\n", " \n", " if len(var_dict[\"xtc_files\"]) >= len(var_dict[\"pdb_files\"]) and len(var_dict[\"pdb_files\"]) == 1:\n", "\n", " print('\\nTaking as input:\\n')\n", " print(\"\".join([str(var_dict[\"xtc_files\"][0]),' : trajectory of ',var_dict[\"ensemble_name\"],',']))\n", " print(\"\".join([str(var_dict[\"pdb_files\"][0]),' : topology file of ',var_dict[\"ensemble_name\"],'.']))\n", " if len(var_dict[\"xtc_files\"]) > 1:\n", " print(\"\\nMore than one .xtc file were found. Taking the first as the trajectory file.\\n\")\n", " var_dict[\"do_xtc\"] = True\n", " var_dict[\"xtc_root_path\"] = var_dict[\"ensemble_path\"]\n", " var_dict['check_folder'] = False\n", " \n", " # multiframe .pdb files\n", " \n", " if var_dict['multiframe'] == 'y' or (len(var_dict[\"pdb_files\"]) >= 1 and len(var_dict[\"xtc_files\"]) == 0):\n", " \n", " print('\\nTaking as input:\\n') \n", " print(\"\".join([str(var_dict[\"pdb_files\"][0]),' : trajectory of ',var_dict[\"ensemble_name\"],'.']))\n", " if len(var_dict[\"pdb_files\"]) > 1:\n", " print(\"\\nMore than one multiframe .pdb file were found. Taking the first as the trajectory file.\\n\")\n", " print(\"\\nTaking the previously converted files.\\n\")\n", " var_dict[\"do_xtc\"] = True\n", " var_dict[\"xtc_root_path\"] = \"/\".join([var_dict[\"ensemble_path\"],'converted_files'])\n", " var_dict[\"xtc_files\"] = [file for file in os.listdir(var_dict[\"xtc_root_path\"]) if file.endswith(\".xtc\")]\n", " var_dict[\"pdb_files\"] = [file for file in os.listdir(var_dict[\"xtc_root_path\"]) if file.endswith(\".pdb\")]\n", " var_dict['check_folder'] = False\n", " \n", " # folder with .pdb files\n", " \n", " if len(var_dict[\"folders\"]) >= 1 and var_dict['check_folder'] == True:\n", " \n", " print('\\nTaking as input:\\n')\n", " print(\"\".join([var_dict[\"folders\"][0],' folder contains: trajectory of ',var_dict[\"ensemble_name\"],\".\"]))\n", " if len(var_dict[\"folders\"]) > 1:\n", " print(\"\\nMore than one .pdb folder were found. Taking the first as the trajectory folder.\\n\")\n", " var_dict[\"do_pdb\"] = True\n", " \n", " if not var_dict[\"do_pdb\"] and not var_dict[\"do_xtc\"]:\n", " sys.exit(\"\".join(['\\n Sorry, I did not understood the input. Please follow the guidelines described in the function documentation to create ',ensemble_name,' folder.\\n'])) \n", " \n", " print(\"\\n----------------------------------------------------------------------------------\\n\")\n", " print(\"\\nComputing cluster-specific descriptors...\\n\")\n", " \n", " results_path = \"/\".join([os.path.abspath(ensemble_path),\"_\".join(['results',ensemble_name])])\n", " save_files = \"/\".join([results_path, \"cluster_descriptors\"])\n", " if not os.path.exists(save_files):\n", " os.mkdir(save_files)\n", " \n", " if var_dict[\"do_xtc\"]:\n", " \n", " traj_file = md.load_xtc(\"/\".join([var_dict[\"xtc_root_path\"],var_dict[\"xtc_files\"][0]]), top = \"/\".join([var_dict[\"xtc_root_path\"],var_dict[\"pdb_files\"][0]]))\n", " L = traj_file.n_residues\n", " Nconf = traj_file.n_frames\n", " \n", " dssp_types = ['H','B','E','G','I','T','S',' ']\n", " prop_dssp = np.zeros([len(dssp_types),L,len(labels_umap)-1])\n", " rg = np.zeros([len(labels_umap)-1])\n", " \n", " for k in range(len(np.unique(labels_umap[labels_umap >= 0]))):\n", " \n", " prop_dssp_k = np.zeros([len(dssp_types),L])\n", " dssp_k = md.compute_dssp(traj_file[np.where(labels_umap == k)], simplified = False)\n", " rg[k] = np.mean(md.compute_rg(traj_file[np.where(labels_umap == k)]))\n", " for dt in range(len(dssp_types)):\n", " prop_dssp_k[dt,:] = (dssp_k == dssp_types[dt]).sum(axis = 0)/len(np.where(labels_umap == k)[0])\n", " prop_dssp[:,:,k] = prop_dssp_k\n", "\n", " if var_dict[\"do_pdb\"]:\n", " \n", " conf_list = os.listdir(var_dict[\"folders\"][0])\n", " md_file = md.load_pdb(\"/\".join([var_dict[\"folders\"][0],conf_list[0]]))\n", " L = md_file.topology.n_residues\n", " Nconf = len(conf_list)\n", " \n", " dssp_types = ['H','B','E','G','I','T','S',' ']\n", " prop_dssp = np.zeros([len(dssp_types),L,len(labels_umap)-1])\n", " rg = np.zeros([len(labels_umap)-1])\n", " \n", " for k in range(len(np.unique(labels_umap[labels_umap >= 0]))):\n", " \n", " prop_dssp_k = np.zeros([len(dssp_types),L])\n", " clus_k = np.where(labels_umap == k)[0]\n", " dssp_k = np.zeros([len(clus_k),L]).astype(str)\n", " rg_k = np.zeros([len(clus_k)])\n", "\n", " for l in range(len(clus_k)):\n", " dssp_k[l,:] = md.compute_dssp(md.load_pdb(\"/\".join([pdb_folder,conf_list[clus_k[l]]])), simplified = False)[0].astype(str)\n", " rg_k[l] = md.compute_rg(md.load_pdb(\"/\".join([pdb_folder,conf_list[clus_k[l]]])))\n", " rg[k] = np.mean(rg_k)\n", " for dt in range(len(dssp_types)):\n", " prop_dssp_k[dt,:] = (dssp_k == dssp_types[dt]).sum(axis = 0)/len(np.where(labels_umap == k)[0])\n", " prop_dssp[:,:,k] = prop_dssp_k\n", " \n", " for cluster in tqdm(range(len(np.unique(labels_umap[labels_umap >= 0])))):\n", " \n", " prop_cluster = round(100*len(np.where(labels_umap == cluster)[0])/Nconf,2)\n", " fig = plt.figure(figsize=(10, 1.7))\n", " res = sns.heatmap(prop_dssp[:,:,cluster], cmap='Blues', square = True, cbar_kws={\"shrink\": .7,'label':\"Class prop.\"})\n", " xlabels = [item.get_text() for item in res.get_xmajorticklabels()]\n", " plt.xlabel('Sequence position')\n", " plt.ylabel('DSSP class')\n", " plt.title(\"\".join([ensemble_name, ' - cluster #',str(cluster),' (',str(prop_cluster),'% oc.). Average RG = ', str(round(10*rg[cluster],2)),r'$\\AA$.']), fontsize = 8)\n", " plt.yticks(rotation=0) \n", " res.set_xticklabels(np.asarray(xlabels).astype(int) + 1, fontsize = 7)\n", " res.set_yticklabels(['L' if x==' ' else x for x in dssp_types], fontsize = 7)\n", " plt.savefig(\"/\".join([save_files,\"\".join([ensemble_name,'_',str(cluster),'_DSSP.png'])]), dpi=199, bbox_inches='tight')\n", "\n", " \n", " print(\"\\nPlots saved.\\n\") " ] }, { "cell_type": "code", "execution_count": null, "id": "cc23916d-784e-4204-ab55-2ee8179cc317", "metadata": {}, "outputs": [], "source": [ "def compare_families(path_a, path_b, ensemble_name_a, ensemble_name_b):\n", " \n", " contmatrix_a = np.load('/'.join([path_a, \"_\".join([ensemble_name_a,'contdata.npy'])]))\n", " contmatrix_b = np.load('/'.join([path_b, \"_\".join([ensemble_name_b,'contdata.npy'])]))\n", "\n", " a = np.delete(contmatrix_a, -1, axis = 1)\n", " ma = contmatrix_a[:,-1]/np.sum(contmatrix_a[:,-1])\n", " b = np.delete(contmatrix_b, -1, axis = 1)\n", " mb = contmatrix_b[:,-1]/np.sum(contmatrix_b[:,-1])\n", " \n", " if np.shape(a)[1] != np.shape(b)[1]:\n", " quit('Both sequences must have the same number of residues.')\n", "\n", " M = ot.dist(a, b, metric = 'sqeuclidean') # Cost matrix\n", " clean = ot.utils.clean_zeros(ma, mb, M)\n", " w = np.sqrt(ot.emd2(clean[0], clean[1], clean[2])) # 2-Wasserstein distance\n", " return w" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.9" } }, "nbformat": 4, "nbformat_minor": 5 }