{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from scipy.sparse import csr_matrix, diags\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from time import time\n",
    "import csv\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "import sys\n",
    "sys.path += ['utils/']  \n",
    "\n",
    "from EDRep import *\n",
    "from node_embedding import *\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "directory = 'data_Gene2Vec/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running the optimization for k = 1\n",
      "Execution time: 6.237004280090332\n"
     ]
    }
   ],
   "source": [
    "# load the data\n",
    "EL = pd.read_csv(directory + 'train_text.txt', sep = ' ', names = [\"id1\", \"id2\"])\n",
    "\n",
    "# create the adjacency matrix\n",
    "dist_EL = pd.concat([EL.id1, EL.id2]).unique()\n",
    "n = len(dist_EL)\n",
    "EL_to_ID = {k: v for v, k in enumerate(dist_EL)}\n",
    "ID_to_EL = {v: k for v, k in enumerate(dist_EL)}\n",
    "A = csr_matrix((np.ones(len(EL)), (EL.id1.apply(lambda x: EL_to_ID[x]), EL.id2.apply(lambda x: EL_to_ID[x]))), shape = (n,n))\n",
    "A = (A + A.T).sign()\n",
    "\n",
    "dim = 200\n",
    "\n",
    "# run EDRep\n",
    "t0 = time()\n",
    "result = NodeEmbedding(A, dim = dim, n_epochs = 10, walk_length = 1, k = 1, verbose = True, η = 0.8, sym = True)\n",
    "print(f'Execution time: {time() - t0}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the files with labeled pairs\n",
    "files = pd.read_csv(directory + 'train_text.txt', header = None, sep = ' ', names = ['id1', 'id2'])\n",
    "files['label'] = pd.read_csv(directory + 'train_label.txt', header = None)[0].values\n",
    "files = files.dropna()\n",
    "\n",
    "# convert the embeddings to dataframes\n",
    "X_EDRep = pd.DataFrame(result.X)\n",
    "indeces = [ID_to_EL[x] for x in range(n)]\n",
    "X_EDRep['idx'] = indeces\n",
    "X_EDRep.set_index('idx', inplace = True)\n",
    "\n",
    "# load the G2V embedding\n",
    "X_G2V = pd.read_csv(directory + 'Gene2Vec_embeddings.txt', header = None, sep = ' ')\n",
    "X_G2V['idx'] = X_G2V[0].map(lambda x: x.split('\\t')[0])\n",
    "X_G2V[0] = X_G2V[0].map(lambda x: float(x.split('\\t')[1]))\n",
    "X_G2V = X_G2V.drop(columns =  200, axis = 0)\n",
    "X_G2V.set_index('idx', inplace = True)\n",
    "\n",
    "# add the predicted similarity column\n",
    "files['S_EDRep'] = files.apply(lambda x:X_EDRep.loc[x.id1]@X_EDRep.loc[x.id2], axis = 1)\n",
    "files['S_G2V'] = files.apply(lambda x: X_G2V.loc[x.id1]@X_G2V.loc[x.id2], axis = 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Score EDRep: 0.9504901588266585\n",
      "Score G2V: 0.8446310509917166\n"
     ]
    }
   ],
   "source": [
    "# run the logistic regression\n",
    "\n",
    "idx = np.random.binomial(1, 0.7, len(files)) == 1\n",
    "files_train = files[idx]\n",
    "files_test = files[~idx]\n",
    "\n",
    "X = files_train.S_EDRep.values.reshape(1,-1).T\n",
    "y = files_train.label\n",
    "\n",
    "clf = LogisticRegression(random_state=0).fit(X, y)\n",
    "\n",
    "X = files_test.S_EDRep.values.reshape(1,-1).T\n",
    "y = files_test.label\n",
    "clf.predict(X)\n",
    "print(f'Score EDRep: {clf.score(X, y)}')\n",
    "\n",
    "X = files_train.S_G2V.values.reshape(1,-1).T\n",
    "y = files_train.label\n",
    "\n",
    "clf = LogisticRegression(random_state=0).fit(X, y)\n",
    "\n",
    "X = files_test.S_G2V.values.reshape(1,-1).T\n",
    "y = files_test.label\n",
    "clf.predict(X)\n",
    "print(f'Score G2V: {clf.score(X, y)}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 40344 characters]",
      "text/plain": [
       "<Figure size 1200x500 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = plt.subplots(1, 2, figsize= (12, 5))\n",
    "\n",
    "ax[0].hist(files[files.label == 0].S_EDRep, density = True, color = 'limegreen', edgecolor = 'white', bins =25, label = 'non interacting')\n",
    "ax[0].hist(files[files.label == 1].S_EDRep, density = True, color = 'plum', edgecolor = 'white', bins = 25, label = 'interacting')\n",
    "ax[0].set_title('EDRep', fontsize = 30)\n",
    "ax[0].tick_params(axis='x', which='major', labelsize=20)\n",
    "ax[0].tick_params(axis='y', which='major', labelsize=0)\n",
    "ax[0].set_xlabel(r'$\\mathbf{x}_i^T\\mathbf{x}_j$', fontsize = 24)\n",
    "\n",
    "\n",
    "ax[1].hist(files[files.label == 0].S_G2V, density = True, color = 'limegreen', edgecolor = 'white', bins =25, label = 'class 1')\n",
    "ax[1].hist(files[files.label == 1].S_G2V, density = True, color = 'plum', edgecolor = 'white', bins = 25, label = 'class 2')\n",
    "ax[1].set_title('Gene2Vec', fontsize = 30)\n",
    "ax[1].tick_params(axis='x', which='major', labelsize=20)\n",
    "ax[1].tick_params(axis='y', which='major', labelsize=0)\n",
    "ax[1].set_xlabel(r'$\\mathbf{x}_i^T\\mathbf{x}_j$', fontsize = 24)\n",
    "\n",
    "ax[0].set_ylabel('PDF', fontsize = 28)\n",
    "ax[0].legend(fontsize=  20)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "EDRep",
   "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.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
