Skip to content
Snippets Groups Projects
utils.ipynb 28.2 KiB
Newer Older
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
{
 "cells": [
  {
   "cell_type": "code",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
   "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",
    "import MDAnalysis\n",
    "import h5py"
   ]
  },
  {
   "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']))"
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6f669fe3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_cluster_files(ensemble_path, ensemble_name, labels_umap):\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "             \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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "\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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "            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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "            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(conf_list[clus_k[j]]),'.pdb'])]))\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "\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, pdf = False, dpi_png = 200):\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "    \n",
    "    classified = np.where(labels_umap >= 0)[0]\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "    \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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "                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",
    "        if pdf:\n",
    "            plt.savefig(\"/\".join([results_path, \"\".join([\"clusters_2d\", ensemble_name, '.pdf'])]))\n",
    "        else:\n",
    "            plt.savefig(\"/\".join([results_path, \"\".join([\"clusters_2d\", ensemble_name, '.png'])]), dpi = dpi_png)\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        plt.show()\n",
    "\n",
    "    output2 = widgets.Output()\n",
    "    with output2:\n",
    "        repartition = pd.Series(labels_umap).value_counts()\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "    two_columns = widgets.HBox([output1, output2])\n",
    "    display(two_columns)"
   ]
  },
  {
   "cell_type": "code",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
   "id": "00dfbe24",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_wmaps(labels_umap, ensemble_name, results_path, subsequence = None, marks = None, \n",
    "              pdf = False, dpi_png = 500, fontsize_title = 10, fontsize_axis = 5,\n",
    "              fontsize_suptitle = 12, shrink_cbar = .5, xticks_angle = 90):\n",
    "\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "    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",
    "    h5f = h5py.File(\"/\".join([results_path, \"_\".join([ensemble_name,'wcontmatrix.h5'])]),'r')\n",
    "    n, p = np.shape(h5f['data'])\n",
    "    \n",
    "    L = int(0.5*(1+np.sqrt(1+8*p))) # Sequence length\n",
    "    list_pos = np.asarray(list(itertools.combinations(range(1,L+1), 2))) # List of position pairs\n",
    "\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "    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",
    "        # Load cluster-specific data\n",
    "        cluster_data = h5f['data'][labels_umap == cluster,]\n",
    "   \n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        # Cluster-specific w-contact matrix\n",
    "        prop_cluster = pd.Series(labels_umap).value_counts().sort_index()[cluster]/n\n",
    "        cont_matrix = pd.DataFrame(np.concatenate([list_pos,np.asarray([cluster_data.mean(axis = 0)]).T], axis = 1), columns=['pos1','pos2','cp'])\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        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(rasterized=True)\n",
    "        res = sns.heatmap(cont_matrix.T, cmap='Reds',square=True,  cbar_kws={\"shrink\": shrink_cbar,'label':\"Contact weight average\"})\n",
    "        plt.suptitle(\" \".join([ensemble_name,'contact-based clustering']), fontsize = fontsize_suptitle)\n",
    "        plt.title(\"\".join(['Cluster #',str(cluster),' with ',str(round(100*prop_cluster,2)),'% of occupation']), fontsize = fontsize_title)\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "\n",
    "        plt.xlabel('Sequence position')\n",
    "        plt.ylabel('Sequence position')\n",
    "        plt.xticks(rotation = xticks_angle)\n",
    "        res.set_xticklabels(res.get_xmajorticklabels(), fontsize = fontsize_axis)\n",
    "        res.set_yticklabels(res.get_ymajorticklabels(), fontsize = fontsize_axis)\n",
    "        if marks is not None:\n",
    "            res.hlines(marks, *res.get_xlim())\n",
    "            res.vlines(marks, *res.get_ylim())\n",
    "        \n",
    "        if pdf:\n",
    "            plt.savefig(\"/\".join([maps_path,\"\".join([ensemble_name,'_',str(cluster),'.pdf'])])) # Save figure in pdf \n",
    "        else:\n",
    "            plt.savefig(\"/\".join([maps_path,\"\".join([ensemble_name,'_',str(cluster),'.png'])]), dpi = dpi_png) # Save figure in png\n",
    "            \n",
    "    np.save(\"/\".join([results_path,\"\".join([ensemble_name,'_contdata'])]),cont_data) # Save contact map values"
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a4c98c97",
   "metadata": {},
   "outputs": [],
   "source": [
    "def representative_ensemble(size, ensemble_path, ensemble_name, labels_umap):\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "             \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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "    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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "    \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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        # 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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "\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, subsequence = None,\n",
    "                       fig_width = 10, fig_height = 1.7, shrink_cbar = .7, yticks_angle = 0,\n",
    "                       fontsize_title = 8, fontsize_axis = 7, pdf = False, dpi_png = 200):\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "             \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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "    \n",
    "        for k in range(len(np.unique(labels_umap[labels_umap >= 0]))):\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        \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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "            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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "            prop_dssp[:,:,k] = prop_dssp_k\n",
    "\n",
    "    if var_dict[\"do_pdb\"]:\n",
    "        \n",
    "        pdb_folder = \"/\".join([var_dict[\"ensemble_path\"],var_dict[\"folders\"][0]])\n",
    "        conf_list = os.listdir(pdb_folder)\n",
    "        md_file = md.load_pdb(\"/\".join([pdb_folder,conf_list[0]]))\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        \n",
    "        for k in range(len(np.unique(labels_umap[labels_umap >= 0]))):\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "            \n",
    "            prop_dssp_k = np.zeros([len(dssp_types),L])\n",
    "            clus_k = np.where(labels_umap == k)[0]\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "            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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "            prop_dssp[:,:,k] = prop_dssp_k\n",
    "  \n",
    "    \n",
    "    if subsequence is None:\n",
    "    \n",
    "        subsequence = np.arange(L)\n",
    "    for cluster in tqdm(range(len(np.unique(labels_umap[labels_umap >= 0])))):\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        \n",
    "        prop_cluster = round(100*len(np.where(labels_umap == cluster)[0])/Nconf,2)\n",
    "        fig = plt.figure(figsize=(fig_width, fig_height))\n",
    "        res = sns.heatmap(prop_dssp[:,subsequence,cluster], cmap='Blues', square = True,  cbar_kws={\"shrink\": shrink_cbar,'label':\"Class prop.\"})\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "        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 = fontsize_title)\n",
    "        plt.yticks(rotation = yticks_angle) \n",
    "        res.set_xticklabels(np.asarray(xlabels).astype(int) + 1, fontsize = fontsize_axis)\n",
    "        res.set_yticklabels(['L' if x==' ' else x for x in dssp_types], fontsize = fontsize_axis)\n",
    "        if pdf:\n",
    "            plt.savefig(\"/\".join([save_files,\"\".join([ensemble_name,'_',str(cluster),'_DSSP.pdf'])]), bbox_inches='tight')\n",
    "        else:\n",
    "            plt.savefig(\"/\".join([save_files,\"\".join([ensemble_name,'_',str(cluster),'_DSSP.png'])]), dpi = dpi_png, bbox_inches='tight')\n",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
    "\n",
    "    print(\"\\nPlots saved.\\n\")    "
   ]
  }
 ],
 "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",
gonzalez-delgado javier's avatar
gonzalez-delgado javier committed
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}