{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Integrating scRNA-seq data with PPI networks to study cell type-specific expression patterns in Alzheimer\n",
    "\n",
    "This study aims to construct cell type-specific PPI networks, analyze differentially expressed genes (DEGs), and evaluate how gene expression patterns vary across cell types in Alzheimer."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-02-27T09:37:56.583250Z",
     "start_time": "2025-02-27T09:37:48.632535Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "source": [
    "import scanpy as sc\n",
    "import pandas as pd\n",
    "import networkx as nx\n",
    "import seaborn as sns\n",
    "from tqdm import tqdm\n",
    "import requests\n",
    "import matplotlib.pyplot as plt\n",
    "from statsmodels.stats.multitest import multipletests\n",
    "from pandas.plotting import table\n",
    "from scipy.stats import pearsonr\n",
    "import numpy as np\n",
    "from scipy.stats import norm\n",
    "from matplotlib.patches import Rectangle\n",
    "from adjustText import adjust_text\n",
    "from scipy.stats import zscore\n",
    "import random\n",
    "import glob\n",
    "import gseapy as gp\n",
    "import os\n",
    "import json\n",
    "\n",
    "import functions_proximity"
   ],
   "outputs": [],
   "execution_count": 599
  },
  {
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "cell_type": "markdown",
   "source": [
    "## 1.  Load data\n",
    "\n",
    "The original dataset includes cells from multiple conditions (Normal, Alzheimer's, FTD, PSP). For this analysis, we are only interested in comparing Normal vs Alzheimer's, so these two conditions are filtered out."
   ],
   "id": "48bc73ea77a550de"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-26T15:40:36.960387Z",
     "start_time": "2025-02-26T15:36:57.430520Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "cell_type": "code",
   "source": [
    "adata = sc.read_h5ad('CellXGene/cross-dementia/cross-dementia.h5ad')"
   ],
   "id": "553338b8b68f7a23",
   "outputs": [
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mKeyboardInterrupt\u001B[0m                         Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[2], line 1\u001B[0m\n\u001B[1;32m----> 1\u001B[0m adata \u001B[38;5;241m=\u001B[39m \u001B[43msc\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mread_h5ad\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;124;43m'\u001B[39;49m\u001B[38;5;124;43mCellXGene/cross-dementia/cross-dementia.h5ad\u001B[39;49m\u001B[38;5;124;43m'\u001B[39;49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\_io\\h5ad.py:258\u001B[0m, in \u001B[0;36mread_h5ad\u001B[1;34m(filename, backed, as_sparse, as_sparse_fmt, chunk_size)\u001B[0m\n\u001B[0;32m    255\u001B[0m         \u001B[38;5;28;01mreturn\u001B[39;00m read_dataframe(elem)\n\u001B[0;32m    256\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m func(elem)\n\u001B[1;32m--> 258\u001B[0m adata \u001B[38;5;241m=\u001B[39m \u001B[43mread_dispatched\u001B[49m\u001B[43m(\u001B[49m\u001B[43mf\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mcallback\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mcallback\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m    260\u001B[0m \u001B[38;5;66;03m# Backwards compat (should figure out which version)\u001B[39;00m\n\u001B[0;32m    261\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mraw.X\u001B[39m\u001B[38;5;124m\"\u001B[39m \u001B[38;5;129;01min\u001B[39;00m f:\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\experimental\\_dispatch_io.py:42\u001B[0m, in \u001B[0;36mread_dispatched\u001B[1;34m(elem, callback)\u001B[0m\n\u001B[0;32m     38\u001B[0m \u001B[38;5;28;01mfrom\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21;01manndata\u001B[39;00m\u001B[38;5;21;01m.\u001B[39;00m\u001B[38;5;21;01m_io\u001B[39;00m\u001B[38;5;21;01m.\u001B[39;00m\u001B[38;5;21;01mspecs\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;28;01mimport\u001B[39;00m _REGISTRY, Reader\n\u001B[0;32m     40\u001B[0m reader \u001B[38;5;241m=\u001B[39m Reader(_REGISTRY, callback\u001B[38;5;241m=\u001B[39mcallback)\n\u001B[1;32m---> 42\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[43mreader\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mread_elem\u001B[49m\u001B[43m(\u001B[49m\u001B[43melem\u001B[49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\_io\\utils.py:211\u001B[0m, in \u001B[0;36mreport_read_key_on_error.<locals>.func_wrapper\u001B[1;34m(*args, **kwargs)\u001B[0m\n\u001B[0;32m    209\u001B[0m     \u001B[38;5;28;01mraise\u001B[39;00m \u001B[38;5;167;01mValueError\u001B[39;00m(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mNo element found in args.\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[0;32m    210\u001B[0m \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[1;32m--> 211\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m func(\u001B[38;5;241m*\u001B[39margs, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs)\n\u001B[0;32m    212\u001B[0m \u001B[38;5;28;01mexcept\u001B[39;00m \u001B[38;5;167;01mException\u001B[39;00m \u001B[38;5;28;01mas\u001B[39;00m e:\n\u001B[0;32m    213\u001B[0m     path, key \u001B[38;5;241m=\u001B[39m _get_display_path(store)\u001B[38;5;241m.\u001B[39mrsplit(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m/\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;241m1\u001B[39m)\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\_io\\specs\\registry.py:275\u001B[0m, in \u001B[0;36mReader.read_elem\u001B[1;34m(self, elem, modifiers)\u001B[0m\n\u001B[0;32m    273\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mcallback \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[0;32m    274\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m read_func(elem)\n\u001B[1;32m--> 275\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcallback\u001B[49m\u001B[43m(\u001B[49m\u001B[43mread_func\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43melem\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mname\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43melem\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43miospec\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43miospec\u001B[49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\_io\\h5ad.py:239\u001B[0m, in \u001B[0;36mread_h5ad.<locals>.callback\u001B[1;34m(func, elem_name, elem, iospec)\u001B[0m\n\u001B[0;32m    236\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21mcallback\u001B[39m(func, elem_name: \u001B[38;5;28mstr\u001B[39m, elem, iospec):\n\u001B[0;32m    237\u001B[0m     \u001B[38;5;28;01mif\u001B[39;00m iospec\u001B[38;5;241m.\u001B[39mencoding_type \u001B[38;5;241m==\u001B[39m \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124manndata\u001B[39m\u001B[38;5;124m\"\u001B[39m \u001B[38;5;129;01mor\u001B[39;00m elem_name\u001B[38;5;241m.\u001B[39mendswith(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m/\u001B[39m\u001B[38;5;124m\"\u001B[39m):\n\u001B[0;32m    238\u001B[0m         \u001B[38;5;28;01mreturn\u001B[39;00m AnnData(\n\u001B[1;32m--> 239\u001B[0m             \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39m{\n\u001B[0;32m    240\u001B[0m                 \u001B[38;5;66;03m# This is covering up backwards compat in the anndata initializer\u001B[39;00m\n\u001B[0;32m    241\u001B[0m                 \u001B[38;5;66;03m# In most cases we should be able to call `func(elen[k])` instead\u001B[39;00m\n\u001B[0;32m    242\u001B[0m                 k: read_dispatched(elem[k], callback)\n\u001B[0;32m    243\u001B[0m                 \u001B[38;5;28;01mfor\u001B[39;00m k \u001B[38;5;129;01min\u001B[39;00m elem\u001B[38;5;241m.\u001B[39mkeys()\n\u001B[0;32m    244\u001B[0m                 \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m k\u001B[38;5;241m.\u001B[39mstartswith(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mraw.\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[0;32m    245\u001B[0m             }\n\u001B[0;32m    246\u001B[0m         )\n\u001B[0;32m    247\u001B[0m     \u001B[38;5;28;01melif\u001B[39;00m elem_name\u001B[38;5;241m.\u001B[39mstartswith(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m/raw.\u001B[39m\u001B[38;5;124m\"\u001B[39m):\n\u001B[0;32m    248\u001B[0m         \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\_io\\h5ad.py:242\u001B[0m, in \u001B[0;36m<dictcomp>\u001B[1;34m(.0)\u001B[0m\n\u001B[0;32m    236\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21mcallback\u001B[39m(func, elem_name: \u001B[38;5;28mstr\u001B[39m, elem, iospec):\n\u001B[0;32m    237\u001B[0m     \u001B[38;5;28;01mif\u001B[39;00m iospec\u001B[38;5;241m.\u001B[39mencoding_type \u001B[38;5;241m==\u001B[39m \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124manndata\u001B[39m\u001B[38;5;124m\"\u001B[39m \u001B[38;5;129;01mor\u001B[39;00m elem_name\u001B[38;5;241m.\u001B[39mendswith(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m/\u001B[39m\u001B[38;5;124m\"\u001B[39m):\n\u001B[0;32m    238\u001B[0m         \u001B[38;5;28;01mreturn\u001B[39;00m AnnData(\n\u001B[0;32m    239\u001B[0m             \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39m{\n\u001B[0;32m    240\u001B[0m                 \u001B[38;5;66;03m# This is covering up backwards compat in the anndata initializer\u001B[39;00m\n\u001B[0;32m    241\u001B[0m                 \u001B[38;5;66;03m# In most cases we should be able to call `func(elen[k])` instead\u001B[39;00m\n\u001B[1;32m--> 242\u001B[0m                 k: \u001B[43mread_dispatched\u001B[49m\u001B[43m(\u001B[49m\u001B[43melem\u001B[49m\u001B[43m[\u001B[49m\u001B[43mk\u001B[49m\u001B[43m]\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mcallback\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m    243\u001B[0m                 \u001B[38;5;28;01mfor\u001B[39;00m k \u001B[38;5;129;01min\u001B[39;00m elem\u001B[38;5;241m.\u001B[39mkeys()\n\u001B[0;32m    244\u001B[0m                 \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m k\u001B[38;5;241m.\u001B[39mstartswith(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mraw.\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[0;32m    245\u001B[0m             }\n\u001B[0;32m    246\u001B[0m         )\n\u001B[0;32m    247\u001B[0m     \u001B[38;5;28;01melif\u001B[39;00m elem_name\u001B[38;5;241m.\u001B[39mstartswith(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m/raw.\u001B[39m\u001B[38;5;124m\"\u001B[39m):\n\u001B[0;32m    248\u001B[0m         \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\experimental\\_dispatch_io.py:42\u001B[0m, in \u001B[0;36mread_dispatched\u001B[1;34m(elem, callback)\u001B[0m\n\u001B[0;32m     38\u001B[0m \u001B[38;5;28;01mfrom\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21;01manndata\u001B[39;00m\u001B[38;5;21;01m.\u001B[39;00m\u001B[38;5;21;01m_io\u001B[39;00m\u001B[38;5;21;01m.\u001B[39;00m\u001B[38;5;21;01mspecs\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;28;01mimport\u001B[39;00m _REGISTRY, Reader\n\u001B[0;32m     40\u001B[0m reader \u001B[38;5;241m=\u001B[39m Reader(_REGISTRY, callback\u001B[38;5;241m=\u001B[39mcallback)\n\u001B[1;32m---> 42\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[43mreader\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mread_elem\u001B[49m\u001B[43m(\u001B[49m\u001B[43melem\u001B[49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\_io\\utils.py:211\u001B[0m, in \u001B[0;36mreport_read_key_on_error.<locals>.func_wrapper\u001B[1;34m(*args, **kwargs)\u001B[0m\n\u001B[0;32m    209\u001B[0m     \u001B[38;5;28;01mraise\u001B[39;00m \u001B[38;5;167;01mValueError\u001B[39;00m(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mNo element found in args.\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[0;32m    210\u001B[0m \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[1;32m--> 211\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m func(\u001B[38;5;241m*\u001B[39margs, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs)\n\u001B[0;32m    212\u001B[0m \u001B[38;5;28;01mexcept\u001B[39;00m \u001B[38;5;167;01mException\u001B[39;00m \u001B[38;5;28;01mas\u001B[39;00m e:\n\u001B[0;32m    213\u001B[0m     path, key \u001B[38;5;241m=\u001B[39m _get_display_path(store)\u001B[38;5;241m.\u001B[39mrsplit(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m/\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;241m1\u001B[39m)\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\_io\\specs\\registry.py:275\u001B[0m, in \u001B[0;36mReader.read_elem\u001B[1;34m(self, elem, modifiers)\u001B[0m\n\u001B[0;32m    273\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mcallback \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[0;32m    274\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m read_func(elem)\n\u001B[1;32m--> 275\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcallback\u001B[49m\u001B[43m(\u001B[49m\u001B[43mread_func\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43melem\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mname\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43melem\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43miospec\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43miospec\u001B[49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\_io\\h5ad.py:256\u001B[0m, in \u001B[0;36mread_h5ad.<locals>.callback\u001B[1;34m(func, elem_name, elem, iospec)\u001B[0m\n\u001B[0;32m    253\u001B[0m \u001B[38;5;28;01melif\u001B[39;00m elem_name \u001B[38;5;129;01min\u001B[39;00m {\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m/obs\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m/var\u001B[39m\u001B[38;5;124m\"\u001B[39m}:\n\u001B[0;32m    254\u001B[0m     \u001B[38;5;66;03m# Backwards compat\u001B[39;00m\n\u001B[0;32m    255\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m read_dataframe(elem)\n\u001B[1;32m--> 256\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[43mfunc\u001B[49m\u001B[43m(\u001B[49m\u001B[43melem\u001B[49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\_io\\specs\\methods.py:724\u001B[0m, in \u001B[0;36mread_sparse\u001B[1;34m(elem, _reader)\u001B[0m\n\u001B[0;32m    719\u001B[0m \u001B[38;5;129m@_REGISTRY\u001B[39m\u001B[38;5;241m.\u001B[39mregister_read(H5Group, IOSpec(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcsc_matrix\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m0.1.0\u001B[39m\u001B[38;5;124m\"\u001B[39m))\n\u001B[0;32m    720\u001B[0m \u001B[38;5;129m@_REGISTRY\u001B[39m\u001B[38;5;241m.\u001B[39mregister_read(H5Group, IOSpec(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcsr_matrix\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m0.1.0\u001B[39m\u001B[38;5;124m\"\u001B[39m))\n\u001B[0;32m    721\u001B[0m \u001B[38;5;129m@_REGISTRY\u001B[39m\u001B[38;5;241m.\u001B[39mregister_read(ZarrGroup, IOSpec(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcsc_matrix\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m0.1.0\u001B[39m\u001B[38;5;124m\"\u001B[39m))\n\u001B[0;32m    722\u001B[0m \u001B[38;5;129m@_REGISTRY\u001B[39m\u001B[38;5;241m.\u001B[39mregister_read(ZarrGroup, IOSpec(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcsr_matrix\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m0.1.0\u001B[39m\u001B[38;5;124m\"\u001B[39m))\n\u001B[0;32m    723\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21mread_sparse\u001B[39m(elem: GroupStorageType, \u001B[38;5;241m*\u001B[39m, _reader: Reader) \u001B[38;5;241m-\u001B[39m\u001B[38;5;241m>\u001B[39m sparse\u001B[38;5;241m.\u001B[39mspmatrix:\n\u001B[1;32m--> 724\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[43msparse_dataset\u001B[49m\u001B[43m(\u001B[49m\u001B[43melem\u001B[49m\u001B[43m)\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mto_memory\u001B[49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\anndata\\_core\\sparse_dataset.py:575\u001B[0m, in \u001B[0;36mBaseCompressedSparseDataset.to_memory\u001B[1;34m(self)\u001B[0m\n\u001B[0;32m    573\u001B[0m format_class \u001B[38;5;241m=\u001B[39m get_memory_class(\u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mformat)\n\u001B[0;32m    574\u001B[0m mtx \u001B[38;5;241m=\u001B[39m format_class(\u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mshape, dtype\u001B[38;5;241m=\u001B[39m\u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mdtype)\n\u001B[1;32m--> 575\u001B[0m mtx\u001B[38;5;241m.\u001B[39mdata \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mgroup\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43mdata\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m]\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m]\u001B[49m\n\u001B[0;32m    576\u001B[0m mtx\u001B[38;5;241m.\u001B[39mindices \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mgroup[\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mindices\u001B[39m\u001B[38;5;124m\"\u001B[39m][\u001B[38;5;241m.\u001B[39m\u001B[38;5;241m.\u001B[39m\u001B[38;5;241m.\u001B[39m]\n\u001B[0;32m    577\u001B[0m mtx\u001B[38;5;241m.\u001B[39mindptr \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mindptr\n",
      "File \u001B[1;32mh5py\\\\_objects.pyx:54\u001B[0m, in \u001B[0;36mh5py._objects.with_phil.wrapper\u001B[1;34m()\u001B[0m\n",
      "File \u001B[1;32mh5py\\\\_objects.pyx:55\u001B[0m, in \u001B[0;36mh5py._objects.with_phil.wrapper\u001B[1;34m()\u001B[0m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\h5py\\_hl\\dataset.py:781\u001B[0m, in \u001B[0;36mDataset.__getitem__\u001B[1;34m(self, args, new_dtype)\u001B[0m\n\u001B[0;32m    779\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_fast_read_ok \u001B[38;5;129;01mand\u001B[39;00m (new_dtype \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m):\n\u001B[0;32m    780\u001B[0m     \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[1;32m--> 781\u001B[0m         \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m_fast_reader\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mread\u001B[49m\u001B[43m(\u001B[49m\u001B[43margs\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m    782\u001B[0m     \u001B[38;5;28;01mexcept\u001B[39;00m \u001B[38;5;167;01mTypeError\u001B[39;00m:\n\u001B[0;32m    783\u001B[0m         \u001B[38;5;28;01mpass\u001B[39;00m  \u001B[38;5;66;03m# Fall back to Python read pathway below\u001B[39;00m\n",
      "\u001B[1;31mKeyboardInterrupt\u001B[0m: "
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Filter by Normal y Alzheimer\n",
    "adata = adata[adata.obs['disease'].isin(['normal', 'Alzheimer disease'])]"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-27T09:36:49.970112Z",
     "start_time": "2025-02-27T09:36:49.662224Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "cell_type": "code",
   "source": [
    "print(\"\\n✅ Observations summary:\")\n",
    "print(f\"Total number of cells: {adata.n_obs}\")\n",
    "print(f\"Total number of cellular types: {adata.obs['cell_type'].nunique()}\")\n",
    "print(f\"Total number of unique tissues: {adata.obs['tissue'].nunique()}\")\n",
    "print(f\"Total number of states: {adata.obs['disease'].nunique()}\")\n",
    "\n",
    "print(\"\\n✅ Variables summary:\")\n",
    "print(f\"Total number of genes: {adata.n_vars}\")\n",
    "print(f\"Number of highly variable genes: {adata.var['vst.variable'].sum()}\")"
   ],
   "id": "69f8796db374964f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "✅ Observations summary:\n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'adata' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mNameError\u001B[0m                                 Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[1], line 2\u001B[0m\n\u001B[0;32m      1\u001B[0m \u001B[38;5;28mprint\u001B[39m(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;130;01m\\n\u001B[39;00m\u001B[38;5;124m✅ Observations summary:\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[1;32m----> 2\u001B[0m \u001B[38;5;28mprint\u001B[39m(\u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mTotal number of cells: \u001B[39m\u001B[38;5;132;01m{\u001B[39;00madata\u001B[38;5;241m.\u001B[39mn_obs\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m\"\u001B[39m)\n\u001B[0;32m      3\u001B[0m \u001B[38;5;28mprint\u001B[39m(\u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mTotal number of cellular types: \u001B[39m\u001B[38;5;132;01m{\u001B[39;00madata\u001B[38;5;241m.\u001B[39mobs[\u001B[38;5;124m'\u001B[39m\u001B[38;5;124mcell_type\u001B[39m\u001B[38;5;124m'\u001B[39m]\u001B[38;5;241m.\u001B[39mnunique()\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m\"\u001B[39m)\n\u001B[0;32m      4\u001B[0m \u001B[38;5;28mprint\u001B[39m(\u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mTotal number of unique tissues: \u001B[39m\u001B[38;5;132;01m{\u001B[39;00madata\u001B[38;5;241m.\u001B[39mobs[\u001B[38;5;124m'\u001B[39m\u001B[38;5;124mtissue\u001B[39m\u001B[38;5;124m'\u001B[39m]\u001B[38;5;241m.\u001B[39mnunique()\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m\"\u001B[39m)\n",
      "\u001B[1;31mNameError\u001B[0m: name 'adata' is not defined"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "cell_type": "markdown",
   "source": [
    "## 2. Data preprocessing\n",
    "\n",
    "### 2.1. Filter genes\n",
    "\n",
    "Filter genes expressed in a minimum of 10 cells and filter cells which do not express at least 200 genes. These genes are often technical noise or of little biological relevance in the context of interest."
   ],
   "id": "81bc28121d2f73c1"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-26T15:42:08.719989Z",
     "start_time": "2025-02-26T15:42:08.696187Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "cell_type": "code",
   "source": [
    "sc.pp.filter_cells(adata, min_genes=200)"
   ],
   "id": "e0b48324c0bf96e8",
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "print(f\"Total number of cells after filtering: {adata.n_obs}\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-26T15:42:18.243824Z",
     "start_time": "2025-02-26T15:42:12.759852Z"
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "cell_type": "code",
   "source": [
    "sc.pp.filter_genes(adata, min_cells=10)"
   ],
   "id": "20aa135fce5a6f68",
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "print(f\"Total number of genes after filtering: {adata.n_vars}\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 2.2. Normalization and log transformation\n",
    "\n",
    "**Normalization** is performed because the raw RNA-seq counts depend on the sequencing depth. Therefore, the sum of counts per cell is normalised to a constant value (10,000). This allows comparison between cells with different sequencing depths.\n",
    "\n",
    "In addition, **log-transformation (log1p)** is applied to stabilise the variance and reduce the impact of genes with extreme high abundance."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "sc.pp.normalize_total(adata, target_sum=1e4)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "sc.pp.log1p(adata)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [],
   "source": [
    "adata.write('CellXGene/cross-dementia/preprocessed_data.h5ad')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 2.3. Dataset division\n",
    "\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [],
   "source": [
    "adata = sc.read_h5ad('CellXGene/cross-dementia/preprocessed_data.h5ad')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cell_type\n",
      "oligodendrocyte                      76181\n",
      "glutamatergic neuron                 60845\n",
      "astrocyte                            32390\n",
      "inhibitory interneuron               18662\n",
      "oligodendrocyte precursor cell       14054\n",
      "microglial cell                      10818\n",
      "endothelial cell of vascular tree     3017\n",
      "pericyte                               925\n",
      "T cell                                 136\n",
      "Name: count, dtype: int64\n",
      "disease\n",
      "Alzheimer disease    118234\n",
      "normal                98794\n",
      "Name: count, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print(adata.obs['cell_type'].value_counts())\n",
    "print(adata.obs['disease'].value_counts())"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Procesing cell types: 100%|██████████| 9/9 [03:05<00:00, 20.61s/it]\n"
     ]
    }
   ],
   "source": [
    "cell_types = adata.obs['cell_type'].unique()\n",
    "\n",
    "# Create a dictionary to save the data for each cell type\n",
    "data_per_type = {}\n",
    "for type in tqdm(cell_types, desc=\"Procesing cell types\"):\n",
    "    data_per_type[type] = adata[adata.obs['cell_type'] == type].copy()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "data": {
      "text/plain": "{'astrocyte': AnnData object with n_obs × n_vars = 32390 × 28215\n     obs: 'organism_ontology_term_id', 'tissue_ontology_term_id', 'assay_ontology_term_id', 'disease_ontology_term_id', 'cell_type_ontology_term_id', 'self_reported_ethnicity_ontology_term_id', 'development_stage_ontology_term_id', 'sex_ontology_term_id', 'donor_id', 'suspension_type', 'ct_subcluster', 'library_id', 'tissue_type', 'is_primary_data', 'cell_type', 'assay', 'disease', 'organism', 'sex', 'tissue', 'self_reported_ethnicity', 'development_stage', 'observation_joinid', 'n_genes'\n     var: 'vst.mean', 'vst.variance', 'vst.variance.expected', 'vst.variance.standardized', 'vst.variable', 'feature_is_filtered', 'feature_name', 'feature_reference', 'feature_biotype', 'feature_length', 'feature_type', 'n_cells'\n     uns: 'citation', 'log1p', 'schema_reference', 'schema_version', 'title'\n     obsm: 'X_pca', 'X_tsne', 'X_umap',\n 'glutamatergic neuron': AnnData object with n_obs × n_vars = 60845 × 28215\n     obs: 'organism_ontology_term_id', 'tissue_ontology_term_id', 'assay_ontology_term_id', 'disease_ontology_term_id', 'cell_type_ontology_term_id', 'self_reported_ethnicity_ontology_term_id', 'development_stage_ontology_term_id', 'sex_ontology_term_id', 'donor_id', 'suspension_type', 'ct_subcluster', 'library_id', 'tissue_type', 'is_primary_data', 'cell_type', 'assay', 'disease', 'organism', 'sex', 'tissue', 'self_reported_ethnicity', 'development_stage', 'observation_joinid', 'n_genes'\n     var: 'vst.mean', 'vst.variance', 'vst.variance.expected', 'vst.variance.standardized', 'vst.variable', 'feature_is_filtered', 'feature_name', 'feature_reference', 'feature_biotype', 'feature_length', 'feature_type', 'n_cells'\n     uns: 'citation', 'log1p', 'schema_reference', 'schema_version', 'title'\n     obsm: 'X_pca', 'X_tsne', 'X_umap',\n 'oligodendrocyte precursor cell': AnnData object with n_obs × n_vars = 14054 × 28215\n     obs: 'organism_ontology_term_id', 'tissue_ontology_term_id', 'assay_ontology_term_id', 'disease_ontology_term_id', 'cell_type_ontology_term_id', 'self_reported_ethnicity_ontology_term_id', 'development_stage_ontology_term_id', 'sex_ontology_term_id', 'donor_id', 'suspension_type', 'ct_subcluster', 'library_id', 'tissue_type', 'is_primary_data', 'cell_type', 'assay', 'disease', 'organism', 'sex', 'tissue', 'self_reported_ethnicity', 'development_stage', 'observation_joinid', 'n_genes'\n     var: 'vst.mean', 'vst.variance', 'vst.variance.expected', 'vst.variance.standardized', 'vst.variable', 'feature_is_filtered', 'feature_name', 'feature_reference', 'feature_biotype', 'feature_length', 'feature_type', 'n_cells'\n     uns: 'citation', 'log1p', 'schema_reference', 'schema_version', 'title'\n     obsm: 'X_pca', 'X_tsne', 'X_umap',\n 'oligodendrocyte': AnnData object with n_obs × n_vars = 76181 × 28215\n     obs: 'organism_ontology_term_id', 'tissue_ontology_term_id', 'assay_ontology_term_id', 'disease_ontology_term_id', 'cell_type_ontology_term_id', 'self_reported_ethnicity_ontology_term_id', 'development_stage_ontology_term_id', 'sex_ontology_term_id', 'donor_id', 'suspension_type', 'ct_subcluster', 'library_id', 'tissue_type', 'is_primary_data', 'cell_type', 'assay', 'disease', 'organism', 'sex', 'tissue', 'self_reported_ethnicity', 'development_stage', 'observation_joinid', 'n_genes'\n     var: 'vst.mean', 'vst.variance', 'vst.variance.expected', 'vst.variance.standardized', 'vst.variable', 'feature_is_filtered', 'feature_name', 'feature_reference', 'feature_biotype', 'feature_length', 'feature_type', 'n_cells'\n     uns: 'citation', 'log1p', 'schema_reference', 'schema_version', 'title'\n     obsm: 'X_pca', 'X_tsne', 'X_umap',\n 'inhibitory interneuron': AnnData object with n_obs × n_vars = 18662 × 28215\n     obs: 'organism_ontology_term_id', 'tissue_ontology_term_id', 'assay_ontology_term_id', 'disease_ontology_term_id', 'cell_type_ontology_term_id', 'self_reported_ethnicity_ontology_term_id', 'development_stage_ontology_term_id', 'sex_ontology_term_id', 'donor_id', 'suspension_type', 'ct_subcluster', 'library_id', 'tissue_type', 'is_primary_data', 'cell_type', 'assay', 'disease', 'organism', 'sex', 'tissue', 'self_reported_ethnicity', 'development_stage', 'observation_joinid', 'n_genes'\n     var: 'vst.mean', 'vst.variance', 'vst.variance.expected', 'vst.variance.standardized', 'vst.variable', 'feature_is_filtered', 'feature_name', 'feature_reference', 'feature_biotype', 'feature_length', 'feature_type', 'n_cells'\n     uns: 'citation', 'log1p', 'schema_reference', 'schema_version', 'title'\n     obsm: 'X_pca', 'X_tsne', 'X_umap',\n 'microglial cell': AnnData object with n_obs × n_vars = 10818 × 28215\n     obs: 'organism_ontology_term_id', 'tissue_ontology_term_id', 'assay_ontology_term_id', 'disease_ontology_term_id', 'cell_type_ontology_term_id', 'self_reported_ethnicity_ontology_term_id', 'development_stage_ontology_term_id', 'sex_ontology_term_id', 'donor_id', 'suspension_type', 'ct_subcluster', 'library_id', 'tissue_type', 'is_primary_data', 'cell_type', 'assay', 'disease', 'organism', 'sex', 'tissue', 'self_reported_ethnicity', 'development_stage', 'observation_joinid', 'n_genes'\n     var: 'vst.mean', 'vst.variance', 'vst.variance.expected', 'vst.variance.standardized', 'vst.variable', 'feature_is_filtered', 'feature_name', 'feature_reference', 'feature_biotype', 'feature_length', 'feature_type', 'n_cells'\n     uns: 'citation', 'log1p', 'schema_reference', 'schema_version', 'title'\n     obsm: 'X_pca', 'X_tsne', 'X_umap',\n 'endothelial cell of vascular tree': AnnData object with n_obs × n_vars = 3017 × 28215\n     obs: 'organism_ontology_term_id', 'tissue_ontology_term_id', 'assay_ontology_term_id', 'disease_ontology_term_id', 'cell_type_ontology_term_id', 'self_reported_ethnicity_ontology_term_id', 'development_stage_ontology_term_id', 'sex_ontology_term_id', 'donor_id', 'suspension_type', 'ct_subcluster', 'library_id', 'tissue_type', 'is_primary_data', 'cell_type', 'assay', 'disease', 'organism', 'sex', 'tissue', 'self_reported_ethnicity', 'development_stage', 'observation_joinid', 'n_genes'\n     var: 'vst.mean', 'vst.variance', 'vst.variance.expected', 'vst.variance.standardized', 'vst.variable', 'feature_is_filtered', 'feature_name', 'feature_reference', 'feature_biotype', 'feature_length', 'feature_type', 'n_cells'\n     uns: 'citation', 'log1p', 'schema_reference', 'schema_version', 'title'\n     obsm: 'X_pca', 'X_tsne', 'X_umap',\n 'pericyte': AnnData object with n_obs × n_vars = 925 × 28215\n     obs: 'organism_ontology_term_id', 'tissue_ontology_term_id', 'assay_ontology_term_id', 'disease_ontology_term_id', 'cell_type_ontology_term_id', 'self_reported_ethnicity_ontology_term_id', 'development_stage_ontology_term_id', 'sex_ontology_term_id', 'donor_id', 'suspension_type', 'ct_subcluster', 'library_id', 'tissue_type', 'is_primary_data', 'cell_type', 'assay', 'disease', 'organism', 'sex', 'tissue', 'self_reported_ethnicity', 'development_stage', 'observation_joinid', 'n_genes'\n     var: 'vst.mean', 'vst.variance', 'vst.variance.expected', 'vst.variance.standardized', 'vst.variable', 'feature_is_filtered', 'feature_name', 'feature_reference', 'feature_biotype', 'feature_length', 'feature_type', 'n_cells'\n     uns: 'citation', 'log1p', 'schema_reference', 'schema_version', 'title'\n     obsm: 'X_pca', 'X_tsne', 'X_umap',\n 'T cell': AnnData object with n_obs × n_vars = 136 × 28215\n     obs: 'organism_ontology_term_id', 'tissue_ontology_term_id', 'assay_ontology_term_id', 'disease_ontology_term_id', 'cell_type_ontology_term_id', 'self_reported_ethnicity_ontology_term_id', 'development_stage_ontology_term_id', 'sex_ontology_term_id', 'donor_id', 'suspension_type', 'ct_subcluster', 'library_id', 'tissue_type', 'is_primary_data', 'cell_type', 'assay', 'disease', 'organism', 'sex', 'tissue', 'self_reported_ethnicity', 'development_stage', 'observation_joinid', 'n_genes'\n     var: 'vst.mean', 'vst.variance', 'vst.variance.expected', 'vst.variance.standardized', 'vst.variable', 'feature_is_filtered', 'feature_name', 'feature_reference', 'feature_biotype', 'feature_length', 'feature_type', 'n_cells'\n     uns: 'citation', 'log1p', 'schema_reference', 'schema_version', 'title'\n     obsm: 'X_pca', 'X_tsne', 'X_umap'}"
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data_per_type"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 3. Differential expression analysis\n",
    "\n",
    "Scanpy, when running sc.tl.rank_genes_groups(), automatically prioritises adata.raw if it exists. In this case, we saved the raw array in adata.raw to begin with (which is correct), but Scanpy is using that raw array instead of the normalised, log-transformed .X array.\n",
    "\n",
    "\n",
    "\n",
    "**sc.tl.rank_genes_groups te da los genes más diferencialmente expresados entre los grupos comparados. El signo de logfoldchanges indica si el gen está más expresado en el grupo de interés o en el grupo de referencia. Si comparas \"normal\" vs \"Alzheimer\", un gen sobreexpresado en normal tendrá un logFC positivo para \"normal\" y un logFC negativo para \"Alzheimer\". Lo mismo al revés. El set de genes DEGs es el mismo, solo cambia el signo según qué grupo tomes como referencia.**"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Analyzing cell types...:  11%|█         | 1/9 [02:11<17:30, 131.28s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3712 DEGs found for astrocyte for Alzheimer disease\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Analyzing cell types...:  22%|██▏       | 2/9 [08:22<31:45, 272.28s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5467 DEGs found for glutamatergic neuron for Alzheimer disease\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Analyzing cell types...:  33%|███▎      | 3/9 [09:01<16:35, 165.95s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2193 DEGs found for oligodendrocyte precursor cell for Alzheimer disease\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Analyzing cell types...:  44%|████▍     | 4/9 [16:45<23:37, 283.57s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4002 DEGs found for oligodendrocyte for Alzheimer disease\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Analyzing cell types...:  56%|█████▌    | 5/9 [17:48<13:36, 204.07s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4878 DEGs found for inhibitory interneuron for Alzheimer disease\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Analyzing cell types...:  67%|██████▋   | 6/9 [18:16<07:12, 144.03s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1722 DEGs found for microglial cell for Alzheimer disease\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Analyzing cell types...:  78%|███████▊  | 7/9 [18:23<03:18, 99.43s/it] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "389 DEGs found for endothelial cell of vascular tree for Alzheimer disease\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Analyzing cell types...:  89%|████████▉ | 8/9 [18:25<01:08, 68.44s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "113 DEGs found for pericyte for Alzheimer disease\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Analyzing cell types...: 100%|██████████| 9/9 [18:26<00:00, 122.90s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 DEGs found for T cell for Alzheimer disease\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "for type, adata_type in tqdm(data_per_type.items(), desc= 'Analyzing cell types...'):\n",
    "\n",
    "    adata_normal = adata_type[adata_type.obs['disease'] == 'normal'].copy()\n",
    "    adata_disease = adata_type[adata_type.obs['disease'] == 'Alzheimer disease'].copy()\n",
    "\n",
    "    # IMPORTANT: forge use of log normalize X data.\n",
    "    adata_type.raw = None\n",
    "\n",
    "    # Differential expression analysis with wilcoxon, using the normal expression as baseline\n",
    "    sc.tl.rank_genes_groups(adata_type, groupby='disease', method='wilcoxon', reference='normal')\n",
    "\n",
    "    # Extract results of DEGs for \"disease\"\" condition (compared to normal)\n",
    "    degs_disease = sc.get.rank_genes_groups_df(adata_type, group='Alzheimer disease')\n",
    "\n",
    "    # Filter by logFC y p-adj\n",
    "    degs_disease_filtered = degs_disease[\n",
    "        (degs_disease['logfoldchanges'].abs() >= 0.25) &\n",
    "        (degs_disease['pvals_adj'] <= 0.05)\n",
    "    ]\n",
    "\n",
    "    print(f'{len(degs_disease_filtered)} DEGs found for {type} for Alzheimer disease')\n",
    "\n",
    "    degs_disease_filtered.to_csv(f'CellXGene/cross-dementia/complete/data/degs_{type}_total.csv', index=False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 4. Individualized-PPI construction per cell type\n",
    "\n",
    "### 4.1. Gene-protein mapping\n",
    "\n",
    "In this case, scRNA-seq data uses ENSEMBL ID to identify genes, and our mapping file uses Entrez ID. First we perform a step in order to transform the identifiers using NCBI API.\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "outputs": [],
   "source": [
    "gen = pd.read_csv('CellXGene/gen.tsv', sep = '\\t')\n",
    "gen_pro = pd.read_csv('CellXGene/gen_pro.tsv', sep = '\\t')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "outputs": [],
   "source": [
    "def obtain_gene_symbol(ensembl_ids, type):\n",
    "    \"\"\"\n",
    "    Function that, given a list of ensembl ids, searches for the gene symbols in the ensembl api\n",
    "    \"\"\"\n",
    "    base_url = \"https://rest.ensembl.org/lookup/id/\"\n",
    "\n",
    "    gene_symbols = {}\n",
    "\n",
    "    for ensembl_id in tqdm(ensembl_ids, desc = f'Processing ensembl ids for cell type {type}...'):\n",
    "        url = f\"{base_url}{ensembl_id}?content-type=application/json\"\n",
    "        response = requests.get(url)\n",
    "\n",
    "        if response.status_code == 200:\n",
    "            data = response.json()\n",
    "            gene_symbol = data.get('display_name', None)\n",
    "            gene_symbols[ensembl_id] = gene_symbol\n",
    "        else:\n",
    "            print(f\"Error obtaining data for {ensembl_id}: {response.status_code}\")\n",
    "            gene_symbols[ensembl_id] = None\n",
    "\n",
    "    return gene_symbols"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 150,
   "outputs": [],
   "source": [
    "def map_gene_symbols_to_entrez(gene_symbols, gen_file):\n",
    "    \"\"\"\n",
    "    Function to map gene symbols to Entrez IDs. You would replace this with your preferred method/API call.\n",
    "    \"\"\"\n",
    "    symbol_to_entrez = dict(zip(gen_file['gene_symbol'], gen_file['gene_id']))\n",
    "\n",
    "    # Mapear los Gene Symbols a Entrez IDs\n",
    "    #entrez_ids = {ensembl_id: symbol_to_entrez.get(gene_symbol, None) for ensembl_id, gene_symbol in gene_symbols.items()}\n",
    "    entrez_ids = {}\n",
    "    for ensembl_id, gene_symbol in gene_symbols.items():\n",
    "        entrez_ids[ensembl_id] = (gene_symbol, symbol_to_entrez.get(gene_symbol, None))\n",
    "\n",
    "    return entrez_ids"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "outputs": [
    {
     "data": {
      "text/plain": "{'pericyte': AnnData object with n_obs × n_vars = 925 × 28215\n     obs: 'organism_ontology_term_id', 'tissue_ontology_term_id', 'assay_ontology_term_id', 'disease_ontology_term_id', 'cell_type_ontology_term_id', 'self_reported_ethnicity_ontology_term_id', 'development_stage_ontology_term_id', 'sex_ontology_term_id', 'donor_id', 'suspension_type', 'ct_subcluster', 'library_id', 'tissue_type', 'is_primary_data', 'cell_type', 'assay', 'disease', 'organism', 'sex', 'tissue', 'self_reported_ethnicity', 'development_stage', 'observation_joinid', 'n_genes'\n     var: 'vst.mean', 'vst.variance', 'vst.variance.expected', 'vst.variance.standardized', 'vst.variable', 'feature_is_filtered', 'feature_name', 'feature_reference', 'feature_biotype', 'feature_length', 'feature_type', 'n_cells'\n     uns: 'citation', 'log1p', 'schema_reference', 'schema_version', 'title'\n     obsm: 'X_pca', 'X_tsne', 'X_umap'}"
     },
     "execution_count": 151,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sample_type = 'pericyte'\n",
    "\n",
    "# Obtén el valor correspondiente a esa key\n",
    "data_for_sample_type = {sample_type: data_per_type[sample_type]}\n",
    "data_for_sample_type"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Mapping DEGs for pericyte...:   0%|          | 0/1 [00:00<?, ?it/s]\n",
      "Processing ensembl ids for cell type pericyte...:   0%|          | 0/113 [00:00<?, ?it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:   1%|          | 1/113 [00:02<03:46,  2.02s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:   2%|▏         | 2/113 [00:05<04:49,  2.60s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:   3%|▎         | 3/113 [00:06<03:25,  1.87s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:   4%|▎         | 4/113 [00:09<04:44,  2.61s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:   4%|▍         | 5/113 [00:10<03:09,  1.75s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:   5%|▌         | 6/113 [00:13<04:06,  2.30s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:   6%|▌         | 7/113 [00:13<03:04,  1.74s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:   7%|▋         | 8/113 [00:17<03:47,  2.17s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:   8%|▊         | 9/113 [00:17<02:44,  1.58s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:   9%|▉         | 10/113 [00:19<02:49,  1.65s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  10%|▉         | 11/113 [00:19<02:08,  1.26s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  11%|█         | 12/113 [00:23<03:16,  1.95s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  12%|█▏        | 13/113 [00:27<04:21,  2.62s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  12%|█▏        | 14/113 [00:31<05:13,  3.17s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  13%|█▎        | 15/113 [00:36<05:48,  3.56s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  14%|█▍        | 16/113 [00:36<04:08,  2.56s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  15%|█▌        | 17/113 [00:37<03:16,  2.05s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  16%|█▌        | 18/113 [00:37<02:23,  1.51s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  17%|█▋        | 19/113 [00:37<01:44,  1.11s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  18%|█▊        | 20/113 [00:38<01:32,  1.01it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  19%|█▊        | 21/113 [00:38<01:15,  1.21it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  19%|█▉        | 22/113 [00:39<00:59,  1.53it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  20%|██        | 23/113 [00:39<00:52,  1.72it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  21%|██        | 24/113 [00:39<00:43,  2.06it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  22%|██▏       | 25/113 [00:39<00:36,  2.43it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  23%|██▎       | 26/113 [00:40<00:37,  2.32it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  24%|██▍       | 27/113 [00:40<00:38,  2.26it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  25%|██▍       | 28/113 [00:41<00:42,  1.98it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  26%|██▌       | 29/113 [00:46<02:39,  1.90s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  27%|██▋       | 30/113 [00:54<05:11,  3.75s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  27%|██▋       | 31/113 [00:55<03:53,  2.84s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  28%|██▊       | 32/113 [00:55<02:50,  2.11s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  29%|██▉       | 33/113 [00:56<02:16,  1.70s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  30%|███       | 34/113 [00:56<01:41,  1.29s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  31%|███       | 35/113 [00:57<01:25,  1.10s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  32%|███▏      | 36/113 [00:57<01:06,  1.16it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  33%|███▎      | 37/113 [00:58<00:49,  1.53it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  34%|███▎      | 38/113 [00:58<00:45,  1.65it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  35%|███▍      | 39/113 [00:59<00:48,  1.53it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  35%|███▌      | 40/113 [00:59<00:38,  1.89it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  36%|███▋      | 41/113 [01:03<01:54,  1.59s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  37%|███▋      | 42/113 [01:03<01:23,  1.18s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  38%|███▊      | 43/113 [01:04<01:18,  1.12s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  39%|███▉      | 44/113 [01:05<01:04,  1.06it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  40%|███▉      | 45/113 [01:05<00:54,  1.24it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  41%|████      | 46/113 [01:07<01:17,  1.16s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  42%|████▏     | 47/113 [01:08<00:57,  1.15it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  42%|████▏     | 48/113 [01:13<02:17,  2.11s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  43%|████▎     | 49/113 [01:16<02:41,  2.52s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  44%|████▍     | 50/113 [01:18<02:30,  2.39s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  45%|████▌     | 51/113 [01:18<01:48,  1.74s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  46%|████▌     | 52/113 [01:24<03:00,  2.95s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  47%|████▋     | 53/113 [01:30<03:51,  3.86s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  48%|████▊     | 54/113 [01:40<05:28,  5.56s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  49%|████▊     | 55/113 [01:41<04:08,  4.29s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  50%|████▉     | 56/113 [01:42<03:01,  3.18s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  50%|█████     | 57/113 [01:43<02:32,  2.72s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  51%|█████▏    | 58/113 [01:45<02:15,  2.46s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  52%|█████▏    | 59/113 [01:49<02:44,  3.05s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  53%|█████▎    | 60/113 [01:51<02:12,  2.49s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  54%|█████▍    | 61/113 [01:51<01:39,  1.92s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  55%|█████▍    | 62/113 [01:52<01:15,  1.48s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  56%|█████▌    | 63/113 [01:53<01:11,  1.43s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  57%|█████▋    | 64/113 [01:53<00:52,  1.08s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  58%|█████▊    | 65/113 [01:53<00:39,  1.22it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  58%|█████▊    | 66/113 [01:58<01:29,  1.91s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  59%|█████▉    | 67/113 [01:58<01:09,  1.50s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  60%|██████    | 68/113 [01:59<00:51,  1.14s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  61%|██████    | 69/113 [01:59<00:37,  1.16it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  62%|██████▏   | 70/113 [01:59<00:29,  1.44it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  63%|██████▎   | 71/113 [02:00<00:27,  1.52it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  64%|██████▎   | 72/113 [02:01<00:30,  1.36it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  65%|██████▍   | 73/113 [02:06<01:21,  2.04s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  65%|██████▌   | 74/113 [02:12<02:05,  3.22s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  66%|██████▋   | 75/113 [02:12<01:30,  2.39s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  67%|██████▋   | 76/113 [02:12<01:04,  1.73s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  68%|██████▊   | 77/113 [02:13<00:47,  1.31s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  69%|██████▉   | 78/113 [02:13<00:34,  1.03it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  70%|██████▉   | 79/113 [02:14<00:35,  1.03s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  71%|███████   | 80/113 [02:14<00:25,  1.28it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  72%|███████▏  | 81/113 [02:15<00:20,  1.55it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  73%|███████▎  | 82/113 [02:15<00:19,  1.61it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  73%|███████▎  | 83/113 [02:15<00:15,  1.99it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  74%|███████▍  | 84/113 [02:16<00:13,  2.23it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  75%|███████▌  | 85/113 [02:16<00:13,  2.13it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  76%|███████▌  | 86/113 [02:17<00:10,  2.46it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  77%|███████▋  | 87/113 [02:17<00:08,  2.93it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  78%|███████▊  | 88/113 [02:17<00:10,  2.50it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  79%|███████▉  | 89/113 [02:18<00:08,  2.94it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  80%|███████▉  | 90/113 [02:25<00:53,  2.35s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  81%|████████  | 91/113 [02:27<00:55,  2.51s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  81%|████████▏ | 92/113 [02:34<01:17,  3.71s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  82%|████████▏ | 93/113 [02:37<01:12,  3.61s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  83%|████████▎ | 94/113 [02:38<00:50,  2.65s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  84%|████████▍ | 95/113 [02:38<00:34,  1.92s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  85%|████████▍ | 96/113 [02:38<00:23,  1.41s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  86%|████████▌ | 97/113 [02:50<01:14,  4.66s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  87%|████████▋ | 98/113 [02:51<00:50,  3.39s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  88%|████████▊ | 99/113 [02:51<00:34,  2.43s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  88%|████████▊ | 100/113 [02:51<00:22,  1.76s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  89%|████████▉ | 101/113 [02:52<00:15,  1.32s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  90%|█████████ | 102/113 [02:53<00:14,  1.29s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  91%|█████████ | 103/113 [02:57<00:21,  2.14s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  92%|█████████▏| 104/113 [02:57<00:14,  1.66s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  93%|█████████▎| 105/113 [02:58<00:10,  1.34s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  94%|█████████▍| 106/113 [02:58<00:06,  1.01it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  95%|█████████▍| 107/113 [02:59<00:04,  1.22it/s]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  96%|█████████▌| 108/113 [03:17<00:30,  6.14s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  96%|█████████▋| 109/113 [03:21<00:21,  5.31s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  97%|█████████▋| 110/113 [03:22<00:12,  4.05s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  98%|█████████▊| 111/113 [03:22<00:05,  2.98s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...:  99%|█████████▉| 112/113 [03:22<00:02,  2.15s/it]\u001B[A\n",
      "Processing ensembl ids for cell type pericyte...: 100%|██████████| 113/113 [03:23<00:00,  1.80s/it]\u001B[A\n",
      "Mapping DEGs for pericyte...: 100%|██████████| 1/1 [03:23<00:00, 203.10s/it]\n"
     ]
    }
   ],
   "source": [
    "#for type, adata_type in data_per_type.items():\n",
    "for type, adata_type in tqdm(data_for_sample_type.items(), desc=f'Mapping DEGs for {sample_type}...'):\n",
    "\n",
    "    # Load DEGs for the cellular type\n",
    "    degs_disease_filtered = pd.read_csv(f'CellXGene/cross-dementia/complete/data/degs_{type}_total.csv')\n",
    "\n",
    "    # Obtain ENSEMBL IDs from the DEGs\n",
    "    ensembl_ids_disease = degs_disease_filtered['names'].tolist()\n",
    "\n",
    "    # Map ENSEMBL -> Gene symbol\n",
    "    symbol_ids_disease = obtain_gene_symbol(ensembl_ids_disease, type)\n",
    "\n",
    "    # Map Gene symbol -> Entrez\n",
    "    gene_symbol_entrez = map_gene_symbols_to_entrez(symbol_ids_disease, gen)\n",
    "\n",
    "    # Map DEGs with respective Entrez IDs\n",
    "    #degs_disease_filtered['gene_id'] = degs_disease_filtered['names'].map(entrez_ids_disease)\n",
    "    degs_disease_filtered['gene_symbol'] = degs_disease_filtered['names'].map(lambda x: gene_symbol_entrez[x][0])\n",
    "    degs_disease_filtered['gene_id'] = degs_disease_filtered['names'].map(lambda x: gene_symbol_entrez[x][1])\n",
    "\n",
    "    # Reorder columns\n",
    "    column_order = ['gene_id', 'gene_symbol', 'names', 'logfoldchanges', 'pvals', 'pvals_adj', 'scores']\n",
    "    degs_disease_filtered = degs_disease_filtered[column_order]\n",
    "\n",
    "    degs_disease_filtered.to_csv(f'CellXGene/cross-dementia/complete/data/degs_{type}_mapped.csv', index=False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 162,
   "outputs": [],
   "source": [
    "def add_protein_id(file_path):\n",
    "    df = pd.read_csv(file_path)\n",
    "    df['protein_id'] = df['gene_id'].map(gene_to_protein)\n",
    "    column_order = ['protein_id', 'gene_id', 'gene_symbol', 'names', 'logfoldchanges', 'pvals', 'pvals_adj', 'scores']\n",
    "    df = df[column_order]\n",
    "    df.to_csv(file_path, index=False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 164,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "pericyte\n"
     ]
    }
   ],
   "source": [
    "gene_to_protein = dict(zip(gen_pro['gene_id'], gen_pro['protein_id']))\n",
    "# keys = ['astrocyte', 'glutamatergic neuron', 'oligodendrocyte precursor cell', 'oligodendrocyte', 'inhibitory interneuron', 'microglial cell']\n",
    "keys = ['pericyte']\n",
    "\n",
    "for type in keys:\n",
    "    print(type)\n",
    "    mapped_file_path = f'CellXGene/cross-dementia/complete/data/degs_{type}_mapped.csv'\n",
    "    add_protein_id(mapped_file_path)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 4.2. Cell type-specific PPI construction and integration of DEGs expression values\n",
    "\n",
    "\n",
    "**Las PPI específicas de tipo celular y condición (sana/enferma) van a ser iguales en estructura (mismos nodos y edges) porque usas el mismo set de DEGs, solo que cambia el contexto de up/down-regulation. Se está filtrando el interactoma general (pro_pro.tsv) para quedarte con las interacciones entre DEGs.**\n",
    "\n",
    "Si los mismos genes aparecen como DEGs en ambas condiciones (solo cambia el signo del logFC), el set de proteínas mapeadas será el mismo.\n",
    "Eso implica que la topología (estructura) de la red será igual entre sano y enfermo.\n",
    "\n",
    "Problema: No estás capturando cambios estructurales reales entre las redes de condiciones sanas y enfermas. Solo podrías distinguirlas después (en análisis como enrichment o modularidad) considerando el estado up/down de los nodos, pero no en la conectividad."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 221,
   "outputs": [],
   "source": [
    "gen_pro = pd.read_csv(\"CellXGene/gen_pro.tsv\", sep='\\t')\n",
    "pro_pro = pd.read_csv('CellXGene/pro_pro.tsv', sep = '\\t')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 222,
   "outputs": [],
   "source": [
    "sample_type = 'astrocyte'\n",
    "\n",
    "# Obtén el valor correspondiente a esa key\n",
    "data_for_sample_type = {sample_type: data_per_type[sample_type]}"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 225,
   "outputs": [],
   "source": [
    "def build_ppi_with_expression(cell_type, gen_pro, pro_pro):\n",
    "    \"\"\"\n",
    "    Construye la red PPI específica de un tipo celular, filtrada por DEGs,\n",
    "    e integra los valores de expresión diferencial directamente en los nodos.\n",
    "\n",
    "    Parámetros:\n",
    "    - cell_type: str, nombre del tipo celular.\n",
    "    - gen_pro: DataFrame, mapeo gene_id → protein_id.\n",
    "    - pro_pro: DataFrame, interacciones proteína-proteína.\n",
    "\n",
    "    Output:\n",
    "    - G: Grafo NetworkX con expresión diferencial integrada.\n",
    "    \"\"\"\n",
    "    # Cargar los DEGs para este tipo celular\n",
    "    degs = pd.read_csv(f\"CellXGene/cross-dementia/complete/data/degs_{cell_type}_mapped.csv\")\n",
    "\n",
    "    # Mapear genes DEGs a proteínas (usando Entrez IDs)\n",
    "    degs = degs.merge(gen_pro, on=\"gene_id\", how=\"left\")\n",
    "\n",
    "    # Lista de proteínas DEGs\n",
    "    proteins_degs_disease = degs[\"protein_id\"].dropna().unique()\n",
    "\n",
    "    # Filtrar la red PPI para solo conservar interacciones entre proteínas DEGs y eliminar self-interactions\n",
    "    ppi_filtered_disease = pro_pro[\n",
    "        (pro_pro[\"prA\"].isin(proteins_degs_disease)) &\n",
    "        (pro_pro[\"prB\"].isin(proteins_degs_disease)) &\n",
    "        (pro_pro[\"prA\"] != pro_pro[\"prB\"])\n",
    "    ]\n",
    "\n",
    "    # Construir la red PPI\n",
    "    G = nx.from_pandas_edgelist(ppi_filtered_disease, \"prA\", \"prB\")\n",
    "\n",
    "    # Agregar la expresión diferencial a los nodos de la red\n",
    "    for _, row in degs.iterrows():\n",
    "        if row[\"protein_id\"] in G:\n",
    "            G.nodes[row[\"protein_id\"]][\"gene_id\"] = row[\"gene_id\"]\n",
    "            G.nodes[row[\"protein_id\"]][\"gene_symbol\"] = row[\"gene_symbol\"]\n",
    "            G.nodes[row[\"protein_id\"]][\"logfoldchanges\"] = row[\"logfoldchanges\"]\n",
    "            G.nodes[row[\"protein_id\"]][\"pval\"] = row[\"pvals\"]\n",
    "            G.nodes[row[\"protein_id\"]][\"pval_adj\"] = row[\"pvals_adj\"]\n",
    "\n",
    "    # Guardar la red en un único archivo con expresión integrada\n",
    "    output_path = f\"CellXGene/cross-dementia/complete/graphs/{cell_type}_network.graphml\"\n",
    "    nx.write_graphml(G, output_path)\n",
    "\n",
    "    return G"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 226,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Building cell type-specific PPIs with expression values...: 100%|██████████| 9/9 [00:03<00:00,  2.44it/s]\n"
     ]
    }
   ],
   "source": [
    "cell_networks = {\n",
    "    cell: build_ppi_with_expression(cell, gen_pro, pro_pro)\n",
    "    for cell in tqdm(data_per_type.keys(), desc=\"Building cell type-specific PPIs with expression values...\")\n",
    "}"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 5. Integrated analysis of DEG overlap and presence in the alzheimer module by cell type\n",
    "\n",
    "### 5.1. Obtain Alzheimer disease module\n",
    "\n",
    "Calculate the disease module for Alzheimer's disease.\n",
    "\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [],
   "source": [
    "dis_gen = pd.read_csv('CellXGene/dis_gen.tsv', sep = '\\t')\n",
    "gen_pro = pd.read_csv('CellXGene/gen_pro.tsv', sep = '\\t')\n",
    "pro_pro = pd.read_csv('CellXGene/pro_pro.tsv', sep = '\\t')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [],
   "source": [
    "G_ppi = nx.from_pandas_edgelist(pro_pro, 'prA', 'prB')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [],
   "source": [
    "def get_disease_module(disease, dis_gen, gen_pro, pro_pro, PPI):\n",
    "\n",
    "    genes = functions_proximity.genes_dis(disease, dis_gen)\n",
    "    prots = functions_proximity.pro_gen_dict(genes, gen_pro)\n",
    "    prots_interactome = functions_proximity.gen_pro_PPI(prots, pro_pro)\n",
    "    SG = PPI.subgraph(prots_interactome)\n",
    "    lcc = functions_proximity.lcc(SG)\n",
    "\n",
    "    return lcc"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [],
   "source": [
    "lcc_alz = get_disease_module('C0002395', dis_gen, gen_pro, pro_pro, G_ppi)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "outputs": [
    {
     "data": {
      "text/plain": "{'P52209',\n 'O43189',\n 'Q9NZQ7',\n 'Q9NZV6',\n 'P51843',\n 'Q16795',\n 'Q9HCE0',\n 'P35638',\n 'P04406',\n 'O15427',\n 'P03891',\n 'Q9ULV8',\n 'P35232',\n 'P00813',\n 'Q9UIK4',\n 'P63244',\n 'O75689',\n 'O15105',\n 'P51688',\n 'Q9BXY0',\n 'Q9BYF1',\n 'Q53EL6',\n 'P24387',\n 'P42768',\n 'P15529',\n 'P60228',\n 'Q9UHC9',\n 'Q9P2Y5',\n 'P12004',\n 'Q6ZW49',\n 'Q4V9L6',\n 'P49716',\n 'P04179',\n 'Q9Y2A7',\n 'Q13200',\n 'Q9NV58',\n 'O94813',\n 'Q05086',\n 'P12314',\n 'Q8N5C8',\n 'P08311',\n 'O95452',\n 'P78556',\n 'O15379',\n 'P25942',\n 'P46937',\n 'P16520',\n 'P60983',\n 'P02794',\n 'Q5SNT2',\n 'Q9UBW5',\n 'O14578',\n 'Q13133',\n 'Q92847',\n 'Q9GZX9',\n 'P26599',\n 'O15121',\n 'Q9Y5N1',\n 'Q9UMD9',\n 'P20138',\n 'Q15027',\n 'Q9NTU7',\n 'O75716',\n 'O14595',\n 'Q9H6U6',\n 'P22033',\n 'O14734',\n 'Q8IXL6',\n 'P48147',\n 'P46734',\n 'P35354',\n 'Q14573',\n 'P24863',\n 'P05112',\n 'Q9UKI9',\n 'P04062',\n 'P04439',\n 'Q9Y3D2',\n 'P23945',\n 'Q9Y4C0',\n 'P38936',\n 'P10145',\n 'Q8IYK4',\n 'Q86TM6',\n 'Q9NXA8',\n 'Q9Y6H1',\n 'Q02246',\n 'Q9NZC7',\n 'P63220',\n 'Q9UNU6',\n 'Q9UJY1',\n 'Q9Y485',\n 'P15502',\n 'O94907',\n 'Q9C0B1',\n 'O00499',\n 'Q9H190',\n 'Q9NP56',\n 'P68400',\n 'O75914',\n 'P42356',\n 'P33681',\n 'P12644',\n 'Q96DT6',\n 'P01860',\n 'Q07820',\n 'P60484',\n 'Q8WXG6',\n 'O43184',\n 'P84103',\n 'Q16548',\n 'Q9BYT8',\n 'P03905',\n 'O00418',\n 'Q6IN85',\n 'P39880',\n 'Q8TDQ7',\n 'O60895',\n 'Q7Z698',\n 'P10071',\n 'P01008',\n 'Q8IVL1',\n 'O75475',\n 'Q9UQB3',\n 'Q9Y6C9',\n 'P36955',\n 'Q92575',\n 'Q86UG4',\n 'Q9ULV1',\n 'P11712',\n 'Q96EY1',\n 'Q99700',\n 'Q9Y2C9',\n 'O15287',\n 'P49281',\n 'P22307',\n 'P51587',\n 'Q13393',\n 'P19429',\n 'P68036',\n 'Q13488',\n 'O43474',\n 'P49768',\n 'Q92570',\n 'Q8NA29',\n 'Q5EBL2',\n 'Q13619',\n 'Q92731',\n 'Q92993',\n 'P00749',\n 'O14874',\n 'Q9UNQ0',\n 'P00747',\n 'Q15276',\n 'P19875',\n 'P54253',\n 'P03886',\n 'P08294',\n 'Q9UMY4',\n 'P19419',\n 'Q9P2B7',\n 'Q96I99',\n 'O60493',\n 'Q5TCY1',\n 'P49675',\n 'Q9BYI3',\n 'Q05655',\n 'Q9NR12',\n 'P19367',\n 'Q8WTV0',\n 'Q8WWX9',\n 'P55786',\n 'Q86VK4',\n 'O14773',\n 'Q13867',\n 'Q9UEE9',\n 'Q9H2A3',\n 'P41182',\n 'P29372',\n 'A6NDG6',\n 'Q12774',\n 'Q6IQ55',\n 'Q9NQ75',\n 'P42892',\n 'P21709',\n 'Q01130',\n 'Q8NF50',\n 'P08172',\n 'P01185',\n 'Q9HC10',\n 'P15498',\n 'Q9UIF7',\n 'P19652',\n 'Q8NDV7',\n 'P04141',\n 'Q96B96',\n 'P56159',\n 'O60814',\n 'P15391',\n 'P34810',\n 'Q92673',\n 'Q9Y5X9',\n 'Q6UWF3',\n 'O14746',\n 'Q9UIC8',\n 'P28222',\n 'Q08722',\n 'Q9UPY5',\n 'Q6XR72',\n 'Q96QV1',\n 'O00148',\n 'Q16775',\n 'O75473',\n 'Q92542',\n 'Q5VWX1',\n 'Q9Y520',\n 'P46089',\n 'Q13510',\n 'Q92915',\n 'P78504',\n 'Q96I59',\n 'Q15762',\n 'O15540',\n 'Q14190',\n 'P45983',\n 'P60953',\n 'O96020',\n 'Q96KG7',\n 'Q9NRW4',\n 'P55317',\n 'P31930',\n 'P27797',\n 'P62760',\n 'P49760',\n 'Q15818',\n 'Q30154',\n 'P14410',\n 'O14756',\n 'P11226',\n 'P04626',\n 'Q6H8Q1',\n 'Q9Y6X6',\n 'O43464',\n 'Q8N998',\n 'O14744',\n 'Q99720',\n 'Q99259',\n 'P15153',\n 'P04049',\n 'P05106',\n 'P0DMV8',\n 'P00750',\n 'O60229',\n 'P61086',\n 'Q4LDR2',\n 'P55008',\n 'O95988',\n 'P10321',\n 'O75923',\n 'P20648',\n 'O60290',\n 'P30536',\n 'O00116',\n 'P23141',\n 'Q9UJ68',\n 'P29474',\n 'Q8TF40',\n 'P11245',\n 'Q01362',\n 'P48730',\n 'P35610',\n 'Q15388',\n 'P09543',\n 'O00154',\n 'Q9NZ42',\n 'P20783',\n 'P54257',\n 'P98160',\n 'Q9P1Z0',\n 'Q9NQR4',\n 'P17480',\n 'Q8NBF2',\n 'P00797',\n 'Q14978',\n 'P27695',\n 'P20042',\n 'Q06413',\n 'Q13875',\n 'P49815',\n 'Q6DJT9',\n 'Q96A65',\n 'O15061',\n 'P29323',\n 'O94911',\n 'Q9BXL6',\n 'P04070',\n 'P35372',\n 'P30711',\n 'Q8NI51',\n 'P06748',\n 'Q99962',\n 'Q96LT7',\n 'P36222',\n 'Q8WYA1',\n 'Q16515',\n 'Q9UKV0',\n 'Q8N271',\n 'O00429',\n 'Q99497',\n 'P51790',\n 'Q8IZT6',\n 'Q92876',\n 'P01732',\n 'Q9NZI7',\n 'P29475',\n 'P06307',\n 'P0C7P0',\n 'P24394',\n 'Q8NFT8',\n 'O94906',\n 'P01160',\n 'P32780',\n 'P17252',\n 'P11229',\n 'P18440',\n 'P17752',\n 'O75173',\n 'O95140',\n 'P02652',\n 'P14316',\n 'P43351',\n 'P07550',\n 'Q9H492',\n 'Q9UBL9',\n 'P0CG48',\n 'P21333',\n 'P01034',\n 'P11831',\n 'Q8NDN9',\n 'Q9HB63',\n 'P55212',\n 'Q15369',\n 'P07711',\n 'P22897',\n 'P62380',\n 'P16284',\n 'P27986',\n 'Q13310',\n 'Q9NPH5',\n 'O94827',\n 'P35613',\n 'Q96L34',\n 'Q99726',\n 'P06493',\n 'Q86X60',\n 'P08133',\n 'Q9NRR4',\n 'Q8N6T7',\n 'Q9H3D4',\n 'P02786',\n 'P53985',\n 'Q9UPY6',\n 'Q9HBI1',\n 'P06276',\n 'Q9UKV5',\n 'Q7Z570',\n 'Q96BR1',\n 'P24386',\n 'O15151',\n 'P15559',\n 'Q9NNW7',\n 'P42338',\n 'P61313',\n 'P29597',\n 'P30086',\n 'P41221',\n 'Q9BU40',\n 'O14920',\n 'Q14192',\n 'O43822',\n 'Q13155',\n 'Q16625',\n 'P13569',\n 'Q9Y484',\n 'P32745',\n 'P20226',\n 'O75509',\n 'Q8N9N2',\n 'P60903',\n 'Q15526',\n 'P32320',\n 'Q9UHD2',\n 'Q5T4S7',\n 'P30307',\n 'P20366',\n 'Q9Y4P1',\n 'Q13501',\n 'Q99538',\n 'P48736',\n 'Q01113',\n 'P43403',\n 'P56704',\n 'O75717',\n 'O60784',\n 'P14317',\n 'P56945',\n 'Q08648',\n 'Q86UW7',\n 'P01911',\n 'Q14393',\n 'P62136',\n 'P55072',\n 'P23975',\n 'Q6P1J6',\n 'Q13901',\n 'P56937',\n 'P42345',\n 'O95600',\n 'P08833',\n 'Q6PI77',\n 'P08621',\n 'Q12840',\n 'P09237',\n 'Q13112',\n 'P14859',\n 'P54098',\n 'P14174',\n 'Q9Y5Y6',\n 'Q14694',\n 'Q13148',\n 'P39687',\n 'P52823',\n 'P02766',\n 'Q86TB3',\n 'Q03701',\n 'Q07890',\n 'Q14194',\n 'Q9Y6E2',\n 'Q8WWN8',\n 'P17735',\n 'P21589',\n 'Q5M775',\n 'P01562',\n 'P31327',\n 'P04114',\n 'Q6UWP8',\n 'Q14186',\n 'P15144',\n 'Q13153',\n 'P01138',\n 'Q2M2I8',\n 'P13497',\n 'O75569',\n 'Q6XE24',\n 'P17661',\n 'Q8NF91',\n 'P13501',\n 'Q6ZT89',\n 'Q5T5P2',\n 'Q14126',\n 'P24385',\n 'P13533',\n 'Q12778',\n 'Q8WV28',\n 'P34741',\n 'P01127',\n 'P49841',\n 'P15884',\n 'O00400',\n 'Q9NPF7',\n 'Q12923',\n 'Q7Z417',\n 'Q7L266',\n 'P21399',\n 'Q9UIQ6',\n 'P15169',\n 'Q9H3M7',\n 'Q03001',\n 'P43116',\n 'P05412',\n 'Q13492',\n 'P06681',\n 'Q9UGM6',\n 'P40967',\n 'P42771',\n 'P80075',\n 'P10747',\n 'P11047',\n 'O15068',\n 'P36507',\n 'Q13451',\n 'Q15672',\n 'P17535',\n 'P17275',\n 'O43148',\n 'P30047',\n 'Q05940',\n 'O60885',\n 'Q86U42',\n 'P03372',\n 'Q7RTN6',\n 'P35498',\n 'P27815',\n 'O43490',\n 'Q9UBB9',\n 'P23381',\n 'P02511',\n 'Q7RTS9',\n 'P27708',\n 'P17152',\n 'Q6PUV4',\n 'P36897',\n 'P04233',\n 'P50406',\n 'P52824',\n 'P09622',\n 'P41440',\n 'P54219',\n 'O15553',\n 'Q99828',\n 'P47712',\n 'P28300',\n 'Q9UEY8',\n 'Q9UNK0',\n 'P30519',\n 'P18031',\n 'P14550',\n 'Q16656',\n 'Q96RR4',\n 'P48775',\n 'P25490',\n 'P25440',\n 'Q9H0E2',\n 'P05231',\n 'Q5RKV6',\n 'Q9BXS4',\n 'Q92558',\n 'Q9ULD9',\n 'Q06481',\n 'Q03014',\n 'P07288',\n 'Q96C19',\n 'Q9H2J7',\n 'Q99541',\n 'Q9GZQ8',\n 'P05783',\n 'P61916',\n 'P30740',\n 'Q96M11',\n 'Q9HCJ6',\n 'Q16570',\n 'P32927',\n 'P08913',\n 'P02656',\n 'P07910',\n 'P63165',\n 'P02647',\n 'Q6ZN06',\n 'Q14114',\n 'P14324',\n 'Q53GG5',\n 'Q8NBB4',\n 'P78509',\n 'Q9UJ41',\n 'Q9UBP4',\n 'O43889',\n 'Q9NQ94',\n 'O75955',\n 'P04424',\n 'Q99697',\n 'Q96HJ5',\n 'O75973',\n 'O15244',\n 'P17302',\n 'O00501',\n 'Q8N726',\n 'Q9P0R6',\n 'Q8N165',\n 'P19235',\n 'P06702',\n 'Q9H6X2',\n 'P14373',\n 'Q9UL25',\n 'Q9H8M9',\n 'P00414',\n 'Q8TCG1',\n 'Q9NYA1',\n 'P15036',\n 'Q9BQE4',\n 'Q9UHE5',\n 'Q8TDV0',\n 'P11142',\n 'Q16828',\n 'Q9HDC9',\n 'Q9UKC9',\n 'P41970',\n 'Q92854',\n 'P08473',\n 'P02774',\n 'P17947',\n 'O43914',\n 'O00522',\n 'Q12857',\n 'O96005',\n 'P07585',\n 'Q9NQ66',\n 'Q9H4A6',\n 'Q93086',\n 'Q969K7',\n 'Q99933',\n 'Q9H0Q3',\n 'P05771',\n 'Q8N9Q2',\n 'P55210',\n 'P15289',\n 'P48735',\n 'O15258',\n 'P20749',\n 'P08235',\n 'P10997',\n 'P08582',\n 'P12036',\n 'Q96FF9',\n 'P23284',\n 'Q96TC7',\n 'Q04760',\n 'Q7Z4F1',\n 'Q9NYY3',\n 'O75369',\n 'Q01959',\n 'Q9Y3I1',\n 'Q96BY2',\n 'F8WCM5',\n 'Q8NBJ9',\n 'P21554',\n 'O95433',\n 'Q92736',\n 'Q53H47',\n 'P31371',\n 'Q6UWB1',\n 'Q7Z602',\n 'P36575',\n 'Q13131',\n 'P08236',\n 'P04053',\n 'Q8TD91',\n 'P08247',\n 'Q8TDS5',\n 'Q9Y2W7',\n 'P41567',\n 'P01344',\n 'P04921',\n 'Q16623',\n 'P08138',\n 'Q8NEA6',\n 'P52758',\n 'Q9Y6M4',\n 'P09341',\n 'P25325',\n 'Q9NQC3',\n 'P32004',\n 'Q9ULC6',\n 'O00712',\n 'Q19T08',\n 'P01019',\n 'O60669',\n 'Q8TEW0',\n 'Q15019',\n 'O43497',\n 'O96017',\n 'Q8WTS6',\n 'O00748',\n 'Q9H598',\n 'O60502',\n 'P45877',\n 'Q9Y2G9',\n 'Q12955',\n 'Q07866',\n 'O14990',\n 'Q9UL54',\n 'P17181',\n 'Q969V5',\n 'Q9Y570',\n 'Q9UQQ2',\n 'P35398',\n 'P47914',\n 'P51159',\n 'Q8WXH5',\n 'P34130',\n 'P13473',\n 'Q9BZA7',\n 'Q8IXS6',\n 'O43426',\n 'P35251',\n 'P40121',\n 'P10451',\n 'Q13480',\n 'O94856',\n 'P11021',\n 'O14966',\n 'Q01954',\n 'P09601',\n 'Q96L92',\n 'P15976',\n 'P10636',\n 'P26358',\n 'O94875',\n 'Q9NQB0',\n 'P50458',\n 'P48307',\n 'Q13564',\n 'P26378',\n 'P00533',\n 'O96018',\n 'Q16881',\n 'P10588',\n 'P15692',\n 'Q96IZ0',\n 'Q9NPH3',\n 'Q13087',\n 'Q9UBD9',\n 'Q9UMS4',\n 'P05164',\n 'P08246',\n 'Q13639',\n 'P21281',\n 'P09603',\n 'O43759',\n 'Q99623',\n 'Q16555',\n 'Q9BZS1',\n 'Q16875',\n 'P14902',\n 'P49238',\n 'Q9UI32',\n 'Q08431',\n 'P14618',\n 'P21980',\n 'P06744',\n 'O95631',\n 'P09486',\n 'Q9UBY5',\n 'P07108',\n 'P49767',\n 'P51665',\n 'Q00613',\n 'Q9UBP9',\n 'Q14990',\n 'O15357',\n 'Q9Y287',\n 'Q9UPN3',\n 'P52948',\n 'P25391',\n 'Q02161',\n 'Q9BS16',\n 'P01920',\n 'P14598',\n 'Q13057',\n 'Q96NE9',\n 'P01100',\n 'Q9NZH0',\n 'P31153',\n 'P51572',\n 'Q5SSJ5',\n 'Q16236',\n 'P20742',\n 'P11473',\n 'O95453',\n 'Q99569',\n 'Q08397',\n 'P08151',\n 'O95169',\n 'Q9H1I8',\n 'P16581',\n 'P05019',\n 'P56470',\n 'P46531',\n 'P10070',\n 'P00390',\n 'Q6IBW4',\n 'Q13137',\n 'P78330',\n 'Q2M3C7',\n 'P52757',\n 'P55957',\n 'Q9H4W6',\n 'Q5T124',\n 'P40313',\n 'P49459',\n 'P24821',\n 'Q92599',\n 'Q711Q0',\n 'P02788',\n 'Q9Y2J8',\n 'Q03164',\n 'P28562',\n 'Q9Y6B6',\n 'Q9BQT9',\n 'O14939',\n 'Q5T749',\n 'Q8IV63',\n 'P10082',\n 'O00206',\n 'O60504',\n 'P12081',\n 'P37231',\n 'Q8TD46',\n 'Q9HBM1',\n 'P13798',\n 'P11150',\n 'Q96RU7',\n 'Q12968',\n 'P43115',\n 'Q9UNN5',\n 'Q9UJY5',\n 'P48681',\n 'Q7LC44',\n 'Q9H4A9',\n 'P10599',\n 'O60906',\n 'Q01082',\n 'Q7Z6M3',\n 'P37023',\n 'Q06124',\n 'P28072',\n 'Q14511',\n 'P21246',\n 'P20333',\n 'O14867',\n 'P43004',\n 'P09493',\n 'Q9Y6A2',\n 'P00748',\n 'Q8WUG5',\n 'Q99816',\n 'P06730',\n 'Q9UID3',\n 'P35052',\n 'Q9Y5K2',\n 'Q9NQC7',\n 'P32238',\n 'Q9NRA0',\n 'O75056',\n 'Q5VV43',\n 'P62993',\n 'P19793',\n 'P16035',\n 'Q969R5',\n 'P16885',\n 'P55055',\n 'P52888',\n 'Q8IW41',\n 'Q14CX7',\n 'P32121',\n 'P13693',\n 'P41235',\n 'P01889',\n 'Q96FL8',\n 'Q9UHD9',\n 'P42858',\n 'Q92692',\n 'P04181',\n 'O00233',\n 'Q9H6S1',\n 'P19338',\n 'P06733',\n 'P16278',\n 'P43005',\n 'Q8WZ64',\n 'Q9NZT1',\n 'P10147',\n 'Q14574',\n 'Q5MCW4',\n 'P01282',\n 'Q7Z7J5',\n 'Q99490',\n 'P35222',\n 'P62987',\n 'Q9UQ07',\n 'P00736',\n 'Q9NUM4',\n 'P00918',\n 'Q06187',\n 'Q08554',\n 'P13726',\n 'O76083',\n 'Q16581',\n 'Q9BZ23',\n 'Q14247',\n 'Q8IXJ6',\n 'P61247',\n 'P08519',\n 'O94763',\n 'P35030',\n 'Q9GZY8',\n 'A5PKW4',\n 'P25705',\n 'P21728',\n 'P08174',\n 'P27361',\n 'Q9Y210',\n 'Q9HD89',\n 'Q14643',\n 'P80188',\n 'Q8WXD2',\n 'Q9H0M4',\n 'Q14814',\n 'Q8IWV7',\n 'Q9NPG2',\n 'Q9GZT4',\n 'Q9Y6B2',\n 'Q9Y223',\n 'Q8WXA9',\n 'P20810',\n 'P78423',\n 'O15534',\n 'O43451',\n 'Q15853',\n 'O14863',\n 'Q9Y3A2',\n 'Q9H324',\n 'Q9HDB5',\n 'Q9Y3T9',\n 'O00264',\n 'Q9Y3B3',\n 'Q494W8',\n 'P50222',\n 'Q12908',\n 'O15240',\n 'O95816',\n 'Q7Z7K6',\n 'O15547',\n 'O60861',\n 'Q8TCT8',\n 'O75607',\n 'O95297',\n 'O14672',\n 'P21757',\n 'Q9H3Z4',\n 'P53355',\n 'Q96FA3',\n 'O94880',\n 'P0DN86',\n 'Q9BZV2',\n 'Q5TCZ1',\n 'P00491',\n 'Q04206',\n 'P06400',\n 'Q9Y333',\n 'P78380',\n 'Q9Y4H2',\n 'Q9UPX8',\n 'P19438',\n 'Q9Y617',\n 'Q13326',\n 'Q99678',\n 'P08047',\n 'Q8WZ42',\n 'Q16611',\n 'P06241',\n 'P34932',\n 'Q8IVG9',\n 'P50895',\n 'P07093',\n 'Q9UHM6',\n 'Q9BU23',\n 'P40763',\n 'Q16595',\n 'Q13255',\n 'Q9Y6H5',\n 'Q13404',\n 'Q8WYA6',\n 'P50416',\n 'Q9NQX4',\n 'P41091',\n 'P49840',\n 'P17936',\n 'P34969',\n 'Q8WV60',\n 'P07947',\n 'Q13247',\n 'P49736',\n 'Q562R1',\n 'Q9HAJ7',\n 'P25025',\n 'O00519',\n 'P09936',\n 'Q9NQ88',\n 'Q9NWB1',\n 'Q8TEL6',\n 'Q12800',\n 'Q13765',\n 'P57723',\n 'Q68D20',\n 'P37198',\n 'P78417',\n 'Q6ZVD7',\n 'P56270',\n 'Q9NP64',\n 'Q9UQ90',\n ...}"
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lcc_alz"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.2. Alzheimer module proteins filtering\n",
    "\n",
    "Keep only those proteins which are present in the Alzheimer disease module for subsequent analysis.\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "for cell_type in tqdm(cell_types, desc='Processing cell types...'):\n",
    "\n",
    "    # Cargar red PPI específica para este tipo celular\n",
    "    G = nx.read_graphml(f'CellXGene/cross-dementia/complete/graphs/{cell_type}_network.graphml')\n",
    "    ppi_proteins = set(G.nodes())\n",
    "\n",
    "    # Proteínas del módulo de Alzheimer presentes en la PPI de este tipo celular\n",
    "    alz_in_ppi = lcc_alz.intersection(ppi_proteins)\n",
    "\n",
    "    G_alz = G.subgraph(alz_in_ppi).copy()\n",
    "    nx.write_graphml(G_alz, f'CellXGene/cross-dementia/filtered/graphs/{cell_type}_network.graphml')\n",
    "\n",
    "    # Archivo filtrado de mapped genes\n",
    "    df_complete = pd.read_csv(f'CellXGene/cross-dementia/complete/data/degs_{cell_type}_mapped.csv')\n",
    "\n",
    "    alz_data = [{\n",
    "        \"protein_id\": protein,\n",
    "        \"gene_id\": G.nodes[protein].get(\"gene_id\", \"NA\"),\n",
    "        \"gene_symbol\": G.nodes[protein].get(\"gene_symbol\", \"NA\")\n",
    "    } for protein in alz_in_ppi]\n",
    "\n",
    "    df_alz = pd.DataFrame(alz_data)\n",
    "\n",
    "    df_filtered = df_alz.merge(df_complete, on=[\"gene_id\"], how=\"left\")\n",
    "    df_filtered = df_filtered[df_filtered['protein_id'].isin(G_alz.nodes)]\n",
    "    df_filtered = df_filtered.drop(columns=[\"gene_symbol_x\"], errors='ignore')\n",
    "    df_filtered = df_filtered.rename(columns={\"gene_symbol_y\": \"gene_symbol\"})\n",
    "\n",
    "    df_filtered.to_csv(f'CellXGene/cross-dementia/filtered/data/degs_{cell_type}_mapped.csv', index=False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 359,
   "outputs": [
    {
     "data": {
      "text/plain": "2697"
     },
     "execution_count": 359,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(lcc_alz)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 6. Cell type-specific network and Alzheimer module overlap\n",
    "\n",
    "This analysis investigates the relationship between differentially expressed genes (DEGs) and the Alzheimer disease module (defined as the largest connected component of a protein-protein interaction network associated with Alzheimer’s disease) across different cell types.\n",
    "\n",
    "- Cell Type\n",
    "- Total DEGs: numero total de DEGs en el dataset original\n",
    "- DEGs mapped to protein: numero de los DEGs totales codificados a proteinas\n",
    "- Cell Type proteins in main LCC: numero de proteinas que vienen de DEGs del tipo celular específico que se encuentran en el modulo del Alzheimer\n",
    "- Cell Type LCC size: tamaño del modulo de la enfermedad de la subred especifica del tipo celular\n",
    "- LCC mean: media del tamaño de los 1,000 modulos aleatorios generados\n",
    "- LCC std: desviación estándar del tamaño de los 1,000 modulos aleatorios generados\n",
    "- Zscore: calculado a partir del valor real del tamaño del LCC del subtipo celular (Cell Type LCC size), con la media (LCC mean) y la desviación estándar (LCC std) de los 1,000 modulos aleatorios\n",
    "- p_value: calculado a partir de la conversión del zscore a partir de la distribución Z\n",
    "- adjusted_p_value: calculado aplicando la corrección de Benjamini-Hochberg (FDR Correction) al p-value\n",
    "\n",
    "**Take into account that:** if a DEG can be mapped to protein only means that there is a known protein identifier for that gene. For it to be in the PPI, it must also be in the interaction network of the specific cell type. If there are no known interactions for that protein in that context, even if it has been mapped, it will not appear in the PPI network. This is why is why the value of ‘degs_in_alzheimer_module’ is higher than that of ‘alzheimer_proteins_in_specific_ppi’. This value can be higher because it is considering all DEGs proteins that have been mapped to proteins, without the need for all of them to necessarily be present in the cell type and condition specific PPI."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 242,
   "outputs": [],
   "source": [
    "cell_types = ['astrocyte', 'microglial cell', 'oligodendrocyte', 'glutamatergic neuron', 'inhibitory interneuron', 'endothelial cell of vascular tree', 'oligodendrocyte precursor cell', 'pericyte']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 232,
   "outputs": [],
   "source": [
    "def calculate_lcc_for_cell_type(degs_cell_type, gen_pro, pro_pro, PPI):\n",
    "\n",
    "    # Generar la subred para el tipo celular con sus DEGs\n",
    "    prots = functions_proximity.pro_gen_dict(degs_cell_type, gen_pro)  # Proteínas correspondientes a los DEGs\n",
    "    prots_interactome = functions_proximity.gen_pro_PPI(prots, pro_pro)\n",
    "    SG = PPI.subgraph(prots_interactome)\n",
    "    lcc_cell_type = functions_proximity.lcc(SG)\n",
    "\n",
    "    return lcc_cell_type\n",
    "\n",
    "# =================================================================================\n",
    "\n",
    "def calculate_lcc_from_prots(prots, pro_pro, PPI):\n",
    "\n",
    "    prots_interactome = []\n",
    "    for prot in prots:\n",
    "        # Iterating over all proteins in the general prot:gen dictionary.\n",
    "        if prot in pro_pro[\"prA\"].tolist() or prot in pro_pro[\"prB\"].tolist():\n",
    "            # Selecting proteins that appear in the PPI network.\n",
    "            prots_interactome.append(prot)\n",
    "\n",
    "    SG = PPI.subgraph(prots_interactome)\n",
    "    lcc_cell_type = functions_proximity.lcc(SG)\n",
    "\n",
    "    return lcc_cell_type\n",
    "\n",
    "# =================================================================================\n",
    "\n",
    "def generate_log_bins(graph, num_bins):\n",
    "    \"\"\"\n",
    "    This function generates logarithmic bins to group nodes of a graph based on\n",
    "    the degree distribution of the nodes.\n",
    "    \"\"\"\n",
    "    degrees = [degree for _, degree in graph.degree()]\n",
    "    min_degree = max(min(degrees), 1)  # Para evitar log(0)\n",
    "    max_degree = max(degrees)\n",
    "\n",
    "    return np.logspace(np.log10(min_degree), np.log10(max_degree), num_bins)\n",
    "\n",
    "# =================================================================================\n",
    "\n",
    "def group_nodes_by_bins(graph, log_bins):\n",
    "    \"\"\"\n",
    "    This function groups nodes of a graph in logarithmic bins based on its degree.\n",
    "\n",
    "    Input:\n",
    "    1.graph\n",
    "    2. log_bins: logarithmic bins\n",
    "    \"\"\"\n",
    "    nodes_bins = {}\n",
    "    for node, degree in graph.degree():\n",
    "        bin_index = np.digitize(degree, log_bins) - 1  # Ajustar índice para Python (basado en 0)\n",
    "        nodes_bins.setdefault(bin_index, []).append(node)\n",
    "\n",
    "    return nodes_bins\n",
    "\n",
    "# =================================================================================\n",
    "\n",
    "def random_subset_generator(proteins, graph_ppi, num_iterations):\n",
    "\n",
    "        # Generation of logarithmic bins\n",
    "    num_bins = 10\n",
    "    bin_edges = generate_log_bins(graph_ppi, num_bins)\n",
    "\n",
    "    # Group nodes in logarithmic bins\n",
    "    group_nodes_bins = group_nodes_by_bins(graph_ppi, bin_edges)\n",
    "\n",
    "    results = []\n",
    "\n",
    "    for _ in range(num_iterations):  # For each iteration\n",
    "\n",
    "        iteration_results = [] # list to append proteins for each disease\n",
    "\n",
    "        for prot in proteins:\n",
    "\n",
    "            # degree of the node\n",
    "            degree_node = graph_ppi.degree(prot)\n",
    "\n",
    "            # bin of the node based on its degree\n",
    "            bin_index = np.digitize(degree_node, bin_edges) - 1\n",
    "\n",
    "            # nodes of the same bin\n",
    "            available_nodes = group_nodes_bins.get(bin_index, [])\n",
    "\n",
    "            if available_nodes:\n",
    "                random_node = np.random.choice(available_nodes) #choose randomly a node from available nodes\n",
    "                # if len(available_nodes) == 1 and random_node == prot:\n",
    "                #     pass\n",
    "                # else:\n",
    "                while random_node == prot:\n",
    "                    random_node = np.random.choice(available_nodes)\n",
    "\n",
    "                iteration_results.append(str(random_node))\n",
    "\n",
    "            else:\n",
    "                iteration_results.append(None)\n",
    "\n",
    "        # results.append(results)\n",
    "        if any(iteration_results):\n",
    "            results.append(iteration_results)\n",
    "\n",
    "    return results"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 243,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing cell types...:   0%|          | 0/8 [00:00<?, ?it/s]"
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 640x480 with 1 Axes>",
      "image/png": "[encoded data, 24704 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing cell types...:  12%|█▎        | 1/8 [18:01<2:06:12, 1081.80s/it]"
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 640x480 with 1 Axes>",
      "image/png": "[encoded data, 25816 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing cell types...:  25%|██▌       | 2/8 [23:59<1:05:34, 655.83s/it] "
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 640x480 with 1 Axes>",
      "image/png": "[encoded data, 26292 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing cell types...:  38%|███▊      | 3/8 [43:44<1:14:47, 897.45s/it]"
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 640x480 with 1 Axes>",
      "image/png": "[encoded data, 25400 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing cell types...:  50%|█████     | 4/8 [1:11:51<1:20:37, 1209.26s/it]"
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 640x480 with 1 Axes>",
      "image/png": "[encoded data, 25908 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing cell types...:  62%|██████▎   | 5/8 [1:37:00<1:05:52, 1317.36s/it]"
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 640x480 with 1 Axes>",
      "image/png": "[encoded data, 23600 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing cell types...:  75%|███████▌  | 6/8 [1:37:23<29:14, 877.04s/it]   "
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 640x480 with 1 Axes>",
      "image/png": "[encoded data, 25248 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing cell types...:  88%|████████▊ | 7/8 [1:41:58<11:20, 680.37s/it]"
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 640x480 with 1 Axes>",
      "image/png": "[encoded data, 22432 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing cell types...: 100%|██████████| 8/8 [1:42:04<00:00, 765.58s/it]\n"
     ]
    }
   ],
   "source": [
    "table = []\n",
    "\n",
    "for cell_type in tqdm(cell_types, desc=\"Processing cell types...\"):\n",
    "\n",
    "    # Solapamiento DEGs en módulo de Alzheimer: número de proteínas DEGs que están en el módulo de Alzheimer.\n",
    "    degs_cell_type = pd.read_csv(f'CellXGene/cross-dementia/complete/data/degs_{cell_type}_mapped.csv')\n",
    "    degs_total = degs_cell_type.dropna(subset=['gene_id'])['gene_id']\n",
    "    degs_protein = degs_cell_type.dropna(subset=['protein_id'])['protein_id']\n",
    "\n",
    "    G = nx.read_graphml(f'CellXGene/cross-dementia/complete/graphs/{cell_type}_network.graphml')\n",
    "    ppi_proteins = set(G.nodes())\n",
    "\n",
    "    # Proteínas del módulo de Alzheimer presentes en la PPI de este tipo celular\n",
    "    alz_in_ppi = lcc_alz.intersection(ppi_proteins)\n",
    "\n",
    "    # Calcular el LCC de la red de enfermedad para el tipo celular. Para ello utilizamos los DEGs que se encuentran en el LCC general de la enfermedad\n",
    "    degs_cell_type_filt = pd.read_csv(f'CellXGene/cross-dementia/filtered/data/degs_{cell_type}_mapped.csv')\n",
    "    lcc_cell_type = calculate_lcc_for_cell_type(degs_cell_type_filt['gene_id'], gen_pro, pro_pro, G_ppi)\n",
    "\n",
    "    # Generar 1,000 redes aleatorias\n",
    "    random_networks = random_subset_generator(lcc_cell_type, G_ppi, 1000)\n",
    "\n",
    "    # Calcular el tamaño del LCC para cada red aleatoria\n",
    "    random_lcc_sizes = [len(calculate_lcc_from_prots(network, pro_pro, G_ppi)) for network in random_networks]\n",
    "\n",
    "    # Calcular estadísticas de los módulos aleatorios\n",
    "    random_lcc_mean = np.mean(random_lcc_sizes)\n",
    "    random_lcc_std = np.std(random_lcc_sizes)\n",
    "\n",
    "    plt.hist(random_lcc_sizes, bins=30, alpha=0.7, color='blue', edgecolor='black')\n",
    "    plt.axvline(len(lcc_cell_type), color='red', linestyle='dashed', linewidth=2, label=\"LCC real\")\n",
    "    plt.axvline(random_lcc_mean, color='blue', linestyle='dashed', linewidth=2, label=\"Random LCC mean\")\n",
    "    plt.xlabel(\"LCC size\")\n",
    "    plt.ylabel(\"Frequency\")\n",
    "    plt.title(f\"LCC size distribution in random networks - {cell_type}\")\n",
    "    plt.legend(loc = 'best')\n",
    "    plt.tight_layout()\n",
    "    plt.savefig(f'CellXGene/cross-dementia/plots/significance/random_modules_{cell_type}.svg', format='svg', dpi=1200)\n",
    "    plt.show()\n",
    "\n",
    "    # Agregar la fila correspondiente\n",
    "    table.append([cell_type, len(degs_total), len(degs_protein), len(alz_in_ppi), len(lcc_cell_type), random_lcc_mean, random_lcc_std])\n",
    "\n",
    "# Crear el DataFrame de la tabla\n",
    "table_df = pd.DataFrame(table, columns=[\"Cell Type\", \"Total DEGs\", \"DEGs mapped to protein\", \"Cell Type proteins in main LCC\", \"Cell Type LCC size\", \"LCC mean\", \"LCC std\"])"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 252,
   "outputs": [
    {
     "data": {
      "text/plain": "                           Cell Type  Total DEGs  DEGs mapped to protein  \\\n0                          astrocyte        3176                    2878   \n1                    microglial cell        1585                    1501   \n2                    oligodendrocyte        3383                    3052   \n3               glutamatergic neuron        4436                    3963   \n4             inhibitory interneuron        4130                    3769   \n5  endothelial cell of vascular tree         379                     367   \n6     oligodendrocyte precursor cell        1963                    1832   \n7                           pericyte         111                     107   \n\n   Cell Type proteins in main LCC  Cell Type LCC size  LCC mean    LCC std  \\\n0                             532                 183    53.963  13.744804   \n1                             334                  62     7.218   3.662032   \n2                             554                 191    57.553  14.372585   \n3                             733                 277   120.873  12.425573   \n4                             673                 251    93.186  14.119752   \n5                              73                   4     1.115   0.328291   \n6                             320                  49     4.996   2.286916   \n7                              20                   1     1.000   0.000000   \n\n   p_value  adjusted_p_value    z_score  \n0      0.0               0.0   9.388057  \n1      0.0               0.0  14.959456  \n2      0.0               0.0   9.284830  \n3      0.0               0.0  12.564974  \n4      0.0               0.0  11.176825  \n5      0.0               0.0   8.787934  \n6      0.0               0.0  19.241635  \n7      1.0               1.0        NaN  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Cell Type</th>\n      <th>Total DEGs</th>\n      <th>DEGs mapped to protein</th>\n      <th>Cell Type proteins in main LCC</th>\n      <th>Cell Type LCC size</th>\n      <th>LCC mean</th>\n      <th>LCC std</th>\n      <th>p_value</th>\n      <th>adjusted_p_value</th>\n      <th>z_score</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>astrocyte</td>\n      <td>3176</td>\n      <td>2878</td>\n      <td>532</td>\n      <td>183</td>\n      <td>53.963</td>\n      <td>13.744804</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>9.388057</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>microglial cell</td>\n      <td>1585</td>\n      <td>1501</td>\n      <td>334</td>\n      <td>62</td>\n      <td>7.218</td>\n      <td>3.662032</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>14.959456</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>oligodendrocyte</td>\n      <td>3383</td>\n      <td>3052</td>\n      <td>554</td>\n      <td>191</td>\n      <td>57.553</td>\n      <td>14.372585</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>9.284830</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>glutamatergic neuron</td>\n      <td>4436</td>\n      <td>3963</td>\n      <td>733</td>\n      <td>277</td>\n      <td>120.873</td>\n      <td>12.425573</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>12.564974</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>inhibitory interneuron</td>\n      <td>4130</td>\n      <td>3769</td>\n      <td>673</td>\n      <td>251</td>\n      <td>93.186</td>\n      <td>14.119752</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>11.176825</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>endothelial cell of vascular tree</td>\n      <td>379</td>\n      <td>367</td>\n      <td>73</td>\n      <td>4</td>\n      <td>1.115</td>\n      <td>0.328291</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>8.787934</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>oligodendrocyte precursor cell</td>\n      <td>1963</td>\n      <td>1832</td>\n      <td>320</td>\n      <td>49</td>\n      <td>4.996</td>\n      <td>2.286916</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>19.241635</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>pericyte</td>\n      <td>111</td>\n      <td>107</td>\n      <td>20</td>\n      <td>1</td>\n      <td>1.000</td>\n      <td>0.000000</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 252,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "table_df['z_score'] = (table_df['Cell Type LCC size'] - table_df['LCC mean']) / table_df['LCC std']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 253,
   "outputs": [],
   "source": [
    "table_df.to_csv('CellXGene/cross-dementia/filtered/results/cell_type_summary.tsv', sep='\\t', index=False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### P-value and Adj P-value calculation"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 272,
   "outputs": [],
   "source": [
    "df = pd.read_csv('CellXGene/cross-dementia/filtered/results/cell_type_summary.tsv', sep='\\t')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 274,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\868517119.py:5: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df['p_value'] = pd.to_numeric(df['p_value'], errors='coerce')  # Convertir a float\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\868517119.py:6: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df['p_value'] = df['p_value'].replace(0, np.nextafter(0, 1))\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\868517119.py:7: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df['adj_p_value'] = multipletests(df['p_value'], method='fdr_bh')[1]\n"
     ]
    },
    {
     "data": {
      "text/plain": "                           Cell Type  Total DEGs  DEGs mapped to protein  \\\n0                          astrocyte        3176                    2878   \n1                    microglial cell        1585                    1501   \n2                    oligodendrocyte        3383                    3052   \n3               glutamatergic neuron        4436                    3963   \n4             inhibitory interneuron        4130                    3769   \n5  endothelial cell of vascular tree         379                     367   \n6     oligodendrocyte precursor cell        1963                    1832   \n7                           pericyte         111                     107   \n\n   Cell Type proteins in main LCC  Cell Type LCC size  LCC mean    LCC std  \\\n0                             532                 183    53.963  13.744804   \n1                             334                  62     7.218   3.662032   \n2                             554                 191    57.553  14.372585   \n3                             733                 277   120.873  12.425573   \n4                             673                 251    93.186  14.119752   \n5                              73                   4     1.115   0.328291   \n6                             320                  49     4.996   2.286916   \n7                              20                   1     1.000   0.000000   \n\n     z_score       p_value   adj_p_value  \n0   9.388057  6.111731e-21  8.556424e-21  \n1  14.959456  1.351270e-50  4.729446e-50  \n2   9.284830  1.619661e-20  1.889605e-20  \n3  12.564974  3.289849e-36  7.676313e-36  \n4  11.176825  5.295062e-29  9.266358e-29  \n5   8.787934  1.523350e-18  1.523350e-18  \n6  19.241635  1.658917e-82  1.161242e-81  \n7        NaN           NaN           NaN  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Cell Type</th>\n      <th>Total DEGs</th>\n      <th>DEGs mapped to protein</th>\n      <th>Cell Type proteins in main LCC</th>\n      <th>Cell Type LCC size</th>\n      <th>LCC mean</th>\n      <th>LCC std</th>\n      <th>z_score</th>\n      <th>p_value</th>\n      <th>adj_p_value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>astrocyte</td>\n      <td>3176</td>\n      <td>2878</td>\n      <td>532</td>\n      <td>183</td>\n      <td>53.963</td>\n      <td>13.744804</td>\n      <td>9.388057</td>\n      <td>6.111731e-21</td>\n      <td>8.556424e-21</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>microglial cell</td>\n      <td>1585</td>\n      <td>1501</td>\n      <td>334</td>\n      <td>62</td>\n      <td>7.218</td>\n      <td>3.662032</td>\n      <td>14.959456</td>\n      <td>1.351270e-50</td>\n      <td>4.729446e-50</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>oligodendrocyte</td>\n      <td>3383</td>\n      <td>3052</td>\n      <td>554</td>\n      <td>191</td>\n      <td>57.553</td>\n      <td>14.372585</td>\n      <td>9.284830</td>\n      <td>1.619661e-20</td>\n      <td>1.889605e-20</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>glutamatergic neuron</td>\n      <td>4436</td>\n      <td>3963</td>\n      <td>733</td>\n      <td>277</td>\n      <td>120.873</td>\n      <td>12.425573</td>\n      <td>12.564974</td>\n      <td>3.289849e-36</td>\n      <td>7.676313e-36</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>inhibitory interneuron</td>\n      <td>4130</td>\n      <td>3769</td>\n      <td>673</td>\n      <td>251</td>\n      <td>93.186</td>\n      <td>14.119752</td>\n      <td>11.176825</td>\n      <td>5.295062e-29</td>\n      <td>9.266358e-29</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>endothelial cell of vascular tree</td>\n      <td>379</td>\n      <td>367</td>\n      <td>73</td>\n      <td>4</td>\n      <td>1.115</td>\n      <td>0.328291</td>\n      <td>8.787934</td>\n      <td>1.523350e-18</td>\n      <td>1.523350e-18</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>oligodendrocyte precursor cell</td>\n      <td>1963</td>\n      <td>1832</td>\n      <td>320</td>\n      <td>49</td>\n      <td>4.996</td>\n      <td>2.286916</td>\n      <td>19.241635</td>\n      <td>1.658917e-82</td>\n      <td>1.161242e-81</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>pericyte</td>\n      <td>111</td>\n      <td>107</td>\n      <td>20</td>\n      <td>1</td>\n      <td>1.000</td>\n      <td>0.000000</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 274,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pericyte_row = df[df['Cell Type'] == 'pericyte'].copy()\n",
    "\n",
    "df['p_value'] = 2 * norm.sf(abs(df['z_score'])) # p value bilateral porque tengo en cuenta que los modulos aleatorios pueden ser de mayor o menos tamaño que el real\n",
    "df = df.dropna(subset=['p_value'])\n",
    "df['p_value'] = pd.to_numeric(df['p_value'], errors='coerce')  # Convertir a float\n",
    "df['p_value'] = df['p_value'].replace(0, np.nextafter(0, 1))\n",
    "df['adj_p_value'] = multipletests(df['p_value'], method='fdr_bh')[1]\n",
    "\n",
    "pericyte_row['adj_p_value'] = np.nan  # Mantener el valor como NaN\n",
    "df = pd.concat([df, pericyte_row], ignore_index=True)\n",
    "\n",
    "df"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 275,
   "outputs": [],
   "source": [
    "df.to_csv('CellXGene/cross-dementia/filtered/results/cell_type_summary_stats.tsv', sep='\\t', index=False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 6.2. Representation of common proteins with DEGs values"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "outputs": [],
   "source": [
    "def load_and_process(files):\n",
    "    df_list = []\n",
    "    for file in files:\n",
    "        df = pd.read_csv(file)\n",
    "        # Extraer el tipo celular del nombre del archivo (por ejemplo, \"degs_celltype_mapped.csv\")\n",
    "        cell_type = file.split('_')[1]  # Asumiendo que el tipo celular está en la segunda posición del nombre del archivo\n",
    "        df['cell_type'] = cell_type  # Agregar la columna 'cell_type' al DataFrame\n",
    "        df_list.append(df)\n",
    "    merged_df = pd.concat(df_list)\n",
    "    return merged_df"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "outputs": [],
   "source": [
    "complete_files = glob.glob(\"CellXGene/cross-dementia/complete/data/degs_*_mapped.csv\")\n",
    "filtered_files = glob.glob(\"CellXGene/cross-dementia/filtered/data/degs_*_mapped.csv\")\n",
    "\n",
    "# Cargar datos\n",
    "complete_data = load_and_process(complete_files)\n",
    "filtered_data = load_and_process(filtered_files)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "outputs": [
    {
     "data": {
      "text/plain": "      protein_id  logfoldchange_mean  std_logfoldchanges  num_cell_types  \\\n0     A0A087WUL8            0.485817            0.215743               4   \n1     A0A087WVF3           -3.359497                 NaN               1   \n2     A0A0U1RRE5            0.342878            0.111791               3   \n3     A0A0U1RRL7            0.288252                 NaN               1   \n4     A0A1B0GTU2            1.060499                 NaN               1   \n...          ...                 ...                 ...             ...   \n8387      Q9Y6X6           -0.007668            0.382404               2   \n8388      Q9Y6X8            0.516868            0.162532               4   \n8389      Q9Y6Y0            0.595799            0.244793               4   \n8390      Q9Y6Y8           -0.340800            0.078085               3   \n8391      Q9Y6Z7           -1.352683                 NaN               1   \n\n     gene_symbol  \n0         NBPF19  \n1        TBC1D3D  \n2           NBDY  \n3        MMP24OS  \n4         CTXND1  \n...          ...  \n8387       MYO16  \n8388        ZHX2  \n8389    IVNS1ABP  \n8390     SEC23IP  \n8391     COLEC10  \n\n[8392 rows x 5 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>protein_id</th>\n      <th>logfoldchange_mean</th>\n      <th>std_logfoldchanges</th>\n      <th>num_cell_types</th>\n      <th>gene_symbol</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>A0A087WUL8</td>\n      <td>0.485817</td>\n      <td>0.215743</td>\n      <td>4</td>\n      <td>NBPF19</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>A0A087WVF3</td>\n      <td>-3.359497</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>TBC1D3D</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>A0A0U1RRE5</td>\n      <td>0.342878</td>\n      <td>0.111791</td>\n      <td>3</td>\n      <td>NBDY</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>A0A0U1RRL7</td>\n      <td>0.288252</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>MMP24OS</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>A0A1B0GTU2</td>\n      <td>1.060499</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>CTXND1</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>8387</th>\n      <td>Q9Y6X6</td>\n      <td>-0.007668</td>\n      <td>0.382404</td>\n      <td>2</td>\n      <td>MYO16</td>\n    </tr>\n    <tr>\n      <th>8388</th>\n      <td>Q9Y6X8</td>\n      <td>0.516868</td>\n      <td>0.162532</td>\n      <td>4</td>\n      <td>ZHX2</td>\n    </tr>\n    <tr>\n      <th>8389</th>\n      <td>Q9Y6Y0</td>\n      <td>0.595799</td>\n      <td>0.244793</td>\n      <td>4</td>\n      <td>IVNS1ABP</td>\n    </tr>\n    <tr>\n      <th>8390</th>\n      <td>Q9Y6Y8</td>\n      <td>-0.340800</td>\n      <td>0.078085</td>\n      <td>3</td>\n      <td>SEC23IP</td>\n    </tr>\n    <tr>\n      <th>8391</th>\n      <td>Q9Y6Z7</td>\n      <td>-1.352683</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>COLEC10</td>\n    </tr>\n  </tbody>\n</table>\n<p>8392 rows × 5 columns</p>\n</div>"
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Calcular estadísticas por proteína\n",
    "aggregated = complete_data.groupby(\"protein_id\").agg(\n",
    "    logfoldchange_mean=(\"logfoldchanges\", \"mean\"),\n",
    "    std_logfoldchanges=(\"logfoldchanges\", \"std\"),\n",
    "    num_cell_types=(\"cell_type\", \"nunique\"),\n",
    "    gene_symbol=(\"gene_symbol\", \"first\")\n",
    ").reset_index()\n",
    "\n",
    "aggregated"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 1000x700 with 1 Axes>",
      "image/png": "[encoded data, 183940 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Identificar proteínas comunes\n",
    "common_proteins = set(complete_data[\"protein_id\"]) & set(filtered_data[\"protein_id\"])\n",
    "aggregated[\"common\"] = aggregated[\"protein_id\"].isin(common_proteins)\n",
    "\n",
    "sns.set_context(\"paper\")\n",
    "sns.set_style(\"whitegrid\")\n",
    "\n",
    "# Crear el scatter plot\n",
    "plt.figure(figsize=(10, 7))\n",
    "sns.scatterplot(data=aggregated, x='logfoldchange_mean', y='std_logfoldchanges',\n",
    "                size='num_cell_types', color='gray', alpha=0.7)\n",
    "\n",
    "# Resaltar proteínas comunes en azul\n",
    "sns.scatterplot(data=aggregated[aggregated[\"common\"]], x='logfoldchange_mean', y='std_logfoldchanges',\n",
    "                color='blue', s=20, edgecolor='black', label='Common Proteins')\n",
    "\n",
    "plt.axvline(x=1, linestyle='--', color='gray')   # Umbral de LFC > 1\n",
    "plt.axvline(x=-1, linestyle='--', color='gray')  # Umbral de LFC < -1\n",
    "plt.axhline(y=0.5, linestyle='--', color='gray') # Umbral de alta variabilidad\n",
    "\n",
    "plt.title('Proteins with high variability in differential expression between cell types present in Alzheimer disease module')\n",
    "plt.xlabel('Average LFC')\n",
    "plt.ylabel('LFC Standard deviation')\n",
    "plt.legend(title='Number of cell types', loc='upper left')\n",
    "plt.tight_layout()\n",
    "\n",
    "plt.savefig('CellXGene/cross-dementia/plots/volcano_all.svg', format = 'svg', dpi=1200)\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 6.3. Representation of each cell type differential expression values"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 226,
   "outputs": [],
   "source": [
    "cell_types = ['astrocyte', 'microglial cell', 'oligodendrocyte', 'glutamatergic neuron', 'inhibitory interneuron', 'endothelial cell of vascular tree', 'oligodendrocyte precursor cell', 'pericyte']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 350,
   "outputs": [
    {
     "data": {
      "text/plain": "count    2.000000e+01\nmean     1.649116e-02\nstd      1.941289e-02\nmin      5.375182e-20\n25%      1.339488e-04\n50%      7.495072e-03\n75%      3.880477e-02\nmax      4.917496e-02\nName: pvals_adj, dtype: float64"
     },
     "execution_count": 350,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['pvals_adj'].describe()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 528,
   "outputs": [
    {
     "data": {
      "text/plain": "{'P02745', 'P04792', 'P08571', 'P21917', 'P46095'}"
     },
     "execution_count": 528,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list = {'P21917', 'P46095', 'P02745', 'P04792', 'P08571'}\n",
    "list.intersection(lcc_alz)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 636,
   "outputs": [],
   "source": [
    "cell_types = ['glutamatergic neuron', 'inhibitory interneuron', 'oligodendrocyte', 'astrocyte', 'microglial cell', 'oligodendrocyte precursor cell', 'endothelial cell of vascular tree', 'pericyte']\n",
    "titles = ['Glutamatergic neuron', 'Inhibitory interneuron', 'Oligodendrocyte', 'Astrocyte', 'Microglial cell', 'OPC', 'Endothelial cell', 'Pericyte']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 615,
   "outputs": [
    {
     "data": {
      "text/plain": "        Id  gene_id gene_symbol            names  logfoldchanges  \\\n0   P07900   3320.0    HSP90AA1  ENSG00000080824        1.110109   \n1   O94875   8470.0      SORBS2  ENSG00000154556        0.827073   \n2   P60484   5728.0        PTEN  ENSG00000171862       -0.782102   \n3   Q15303   2066.0       ERBB4  ENSG00000178568        1.107987   \n4   P04792   3315.0       HSPB1  ENSG00000106211        1.884719   \n5   P08238   3326.0    HSP90AB1  ENSG00000096384        0.861556   \n6   P54253   6310.0       ATXN1  ENSG00000124788        0.712304   \n7   P09619   5159.0      PDGFRB  ENSG00000113721       -0.378450   \n8   Q92598  10808.0       HSPH1  ENSG00000120694        1.676103   \n9   O43524   2309.0       FOXO3  ENSG00000118689        0.854423   \n10  P61586    387.0        RHOA  ENSG00000067560        0.785520   \n11  P0DMV8   3304.0      HSPA1B  ENSG00000204388        1.975146   \n12  P17676   1051.0       CEBPB  ENSG00000172216        1.105564   \n13  P02511   1410.0       CRYAB  ENSG00000109846        1.525713   \n14  P13693   7178.0        TPT1  ENSG00000133112        0.802365   \n15  Q15185  10728.0      PTGES3  ENSG00000110958        0.866479   \n16  P08670   7431.0         VIM  ENSG00000026025        1.117781   \n17  Q7Z6G8  56899.0      ANKS1B  ENSG00000185046        0.978241   \n18  Q09666  79026.0       AHNAK  ENSG00000124942        0.989039   \n19  P49716   1052.0       CEBPD  ENSG00000221869        0.708934   \n\n           pvals     pvals_adj     scores  -log10(pvals_adj)   flag  \n0   2.761193e-13  1.112958e-09   7.305558           8.953521  False  \n1   1.624354e-06  1.580385e-03   4.795295           2.801237  False  \n2   9.017274e-12  2.826915e-08  -6.821376           7.548687  False  \n3   1.496004e-04  4.292680e-02   3.791732           1.367271  False  \n4   1.905079e-24  5.375182e-20  10.203879          19.269607   True  \n5   2.566908e-06  2.336300e-03   4.702742           2.631471  False  \n6   3.498667e-05  1.410213e-02   4.138314           1.850715  False  \n7   1.948204e-04  4.917496e-02  -3.725640           1.308256  False  \n8   1.338602e-05  7.097056e-03   4.353698           2.148922   True  \n9   1.617127e-05  7.893088e-03   4.312098           2.102753  False  \n10  1.640082e-04  4.407135e-02   3.768840           1.355844  False  \n11  1.293792e-07  1.738302e-04   5.279723           3.759875   True  \n12  9.147368e-06  5.491340e-03   4.436405           2.260322  False  \n13  8.710331e-10  1.755443e-06   6.131411           5.755613   True  \n14  1.618387e-04  4.390652e-02   3.772163           1.357471  False  \n15  3.143596e-05  1.285458e-02   4.162807           1.890942  False  \n16  8.111714e-09  1.430450e-05   5.766120           4.844527   True  \n17  2.711835e-05  1.159309e-02   4.196406           1.935801  False  \n18  1.952010e-04  4.917496e-02   3.725147           1.308256  False  \n19  1.193964e-04  3.743076e-02   3.847362           1.426771  False  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Id</th>\n      <th>gene_id</th>\n      <th>gene_symbol</th>\n      <th>names</th>\n      <th>logfoldchanges</th>\n      <th>pvals</th>\n      <th>pvals_adj</th>\n      <th>scores</th>\n      <th>-log10(pvals_adj)</th>\n      <th>flag</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>P07900</td>\n      <td>3320.0</td>\n      <td>HSP90AA1</td>\n      <td>ENSG00000080824</td>\n      <td>1.110109</td>\n      <td>2.761193e-13</td>\n      <td>1.112958e-09</td>\n      <td>7.305558</td>\n      <td>8.953521</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>O94875</td>\n      <td>8470.0</td>\n      <td>SORBS2</td>\n      <td>ENSG00000154556</td>\n      <td>0.827073</td>\n      <td>1.624354e-06</td>\n      <td>1.580385e-03</td>\n      <td>4.795295</td>\n      <td>2.801237</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>P60484</td>\n      <td>5728.0</td>\n      <td>PTEN</td>\n      <td>ENSG00000171862</td>\n      <td>-0.782102</td>\n      <td>9.017274e-12</td>\n      <td>2.826915e-08</td>\n      <td>-6.821376</td>\n      <td>7.548687</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Q15303</td>\n      <td>2066.0</td>\n      <td>ERBB4</td>\n      <td>ENSG00000178568</td>\n      <td>1.107987</td>\n      <td>1.496004e-04</td>\n      <td>4.292680e-02</td>\n      <td>3.791732</td>\n      <td>1.367271</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>P04792</td>\n      <td>3315.0</td>\n      <td>HSPB1</td>\n      <td>ENSG00000106211</td>\n      <td>1.884719</td>\n      <td>1.905079e-24</td>\n      <td>5.375182e-20</td>\n      <td>10.203879</td>\n      <td>19.269607</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>P08238</td>\n      <td>3326.0</td>\n      <td>HSP90AB1</td>\n      <td>ENSG00000096384</td>\n      <td>0.861556</td>\n      <td>2.566908e-06</td>\n      <td>2.336300e-03</td>\n      <td>4.702742</td>\n      <td>2.631471</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>P54253</td>\n      <td>6310.0</td>\n      <td>ATXN1</td>\n      <td>ENSG00000124788</td>\n      <td>0.712304</td>\n      <td>3.498667e-05</td>\n      <td>1.410213e-02</td>\n      <td>4.138314</td>\n      <td>1.850715</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>P09619</td>\n      <td>5159.0</td>\n      <td>PDGFRB</td>\n      <td>ENSG00000113721</td>\n      <td>-0.378450</td>\n      <td>1.948204e-04</td>\n      <td>4.917496e-02</td>\n      <td>-3.725640</td>\n      <td>1.308256</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Q92598</td>\n      <td>10808.0</td>\n      <td>HSPH1</td>\n      <td>ENSG00000120694</td>\n      <td>1.676103</td>\n      <td>1.338602e-05</td>\n      <td>7.097056e-03</td>\n      <td>4.353698</td>\n      <td>2.148922</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>O43524</td>\n      <td>2309.0</td>\n      <td>FOXO3</td>\n      <td>ENSG00000118689</td>\n      <td>0.854423</td>\n      <td>1.617127e-05</td>\n      <td>7.893088e-03</td>\n      <td>4.312098</td>\n      <td>2.102753</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>P61586</td>\n      <td>387.0</td>\n      <td>RHOA</td>\n      <td>ENSG00000067560</td>\n      <td>0.785520</td>\n      <td>1.640082e-04</td>\n      <td>4.407135e-02</td>\n      <td>3.768840</td>\n      <td>1.355844</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>P0DMV8</td>\n      <td>3304.0</td>\n      <td>HSPA1B</td>\n      <td>ENSG00000204388</td>\n      <td>1.975146</td>\n      <td>1.293792e-07</td>\n      <td>1.738302e-04</td>\n      <td>5.279723</td>\n      <td>3.759875</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>P17676</td>\n      <td>1051.0</td>\n      <td>CEBPB</td>\n      <td>ENSG00000172216</td>\n      <td>1.105564</td>\n      <td>9.147368e-06</td>\n      <td>5.491340e-03</td>\n      <td>4.436405</td>\n      <td>2.260322</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>P02511</td>\n      <td>1410.0</td>\n      <td>CRYAB</td>\n      <td>ENSG00000109846</td>\n      <td>1.525713</td>\n      <td>8.710331e-10</td>\n      <td>1.755443e-06</td>\n      <td>6.131411</td>\n      <td>5.755613</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>P13693</td>\n      <td>7178.0</td>\n      <td>TPT1</td>\n      <td>ENSG00000133112</td>\n      <td>0.802365</td>\n      <td>1.618387e-04</td>\n      <td>4.390652e-02</td>\n      <td>3.772163</td>\n      <td>1.357471</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>Q15185</td>\n      <td>10728.0</td>\n      <td>PTGES3</td>\n      <td>ENSG00000110958</td>\n      <td>0.866479</td>\n      <td>3.143596e-05</td>\n      <td>1.285458e-02</td>\n      <td>4.162807</td>\n      <td>1.890942</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>P08670</td>\n      <td>7431.0</td>\n      <td>VIM</td>\n      <td>ENSG00000026025</td>\n      <td>1.117781</td>\n      <td>8.111714e-09</td>\n      <td>1.430450e-05</td>\n      <td>5.766120</td>\n      <td>4.844527</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>Q7Z6G8</td>\n      <td>56899.0</td>\n      <td>ANKS1B</td>\n      <td>ENSG00000185046</td>\n      <td>0.978241</td>\n      <td>2.711835e-05</td>\n      <td>1.159309e-02</td>\n      <td>4.196406</td>\n      <td>1.935801</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>Q09666</td>\n      <td>79026.0</td>\n      <td>AHNAK</td>\n      <td>ENSG00000124942</td>\n      <td>0.989039</td>\n      <td>1.952010e-04</td>\n      <td>4.917496e-02</td>\n      <td>3.725147</td>\n      <td>1.308256</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>P49716</td>\n      <td>1052.0</td>\n      <td>CEBPD</td>\n      <td>ENSG00000221869</td>\n      <td>0.708934</td>\n      <td>1.193964e-04</td>\n      <td>3.743076e-02</td>\n      <td>3.847362</td>\n      <td>1.426771</td>\n      <td>False</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 615,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 685,
   "outputs": [
    {
     "data": {
      "text/plain": "{'CRYAB', 'HSPA1B', 'HSPB1', 'HSPH1', 'VIM'}"
     },
     "execution_count": 685,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "set(top_genes['gene_symbol'])"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 686,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Andrea\\Downloads\\single-cell\\lib\\site-packages\\pandas\\core\\arraylike.py:399: RuntimeWarning: divide by zero encountered in log10\n",
      "  result = getattr(ufunc, method)(*inputs, **kwargs)\n",
      "C:\\Users\\Andrea\\Downloads\\single-cell\\lib\\site-packages\\pandas\\core\\arraylike.py:399: RuntimeWarning: divide by zero encountered in log10\n",
      "  result = getattr(ufunc, method)(*inputs, **kwargs)\n",
      "C:\\Users\\Andrea\\Downloads\\single-cell\\lib\\site-packages\\pandas\\core\\arraylike.py:399: RuntimeWarning: divide by zero encountered in log10\n",
      "  result = getattr(ufunc, method)(*inputs, **kwargs)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "glutamatergic neuron : {'C1QA', 'HSPB1', 'GPR6', 'DRD4', 'CD14'}\n",
      "inhibitory interneuron : {'PENK', 'GPR6', 'CRYZ', 'ARAP3', 'DRD4'}\n",
      "oligodendrocyte : {'RELN', 'CXCR4', 'BIRC3', 'HSPA1B'}\n",
      "astrocyte : {'CRYAB', 'ANXA1', 'EGR1', 'EGF', 'S100A10'}\n",
      "microglial cell : {'BAG3', 'HSPA1B', 'HSPB1', 'DNAJB1'}\n",
      "oligodendrocyte precursor cell : {'FOS', 'IGFBP3', 'EGR1', 'SOCS3', 'VGF'}\n",
      "endothelial cell of vascular tree : {'HSPA1B', 'CACYBP', 'RBM3', 'HSPB1', 'HSPH1'}\n",
      "pericyte : {'HSPA1B', 'CRYAB', 'HSPB1', 'VIM', 'HSPH1'}\n"
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 2200x300 with 8 Axes>",
      "image/png": "[encoded data, 101356 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sns.set_context(\"paper\")\n",
    "sns.set_style(\"white\")\n",
    "\n",
    "fig, axes = plt.subplots(1, 8, figsize=(22,3))\n",
    "axes = axes.flatten()\n",
    "\n",
    "for i, cell_type in enumerate(cell_types):\n",
    "    file_path = f\"CellXGene/cross-dementia/filtered/data/degs_{cell_type}_mapped.csv\"  # Ajustar el nombre del archivo según el formato\n",
    "\n",
    "    try:\n",
    "        # Cargar los datos\n",
    "        df = pd.read_csv(file_path)\n",
    "\n",
    "        df[\"-log10(pvals_adj)\"] = -np.log10(df[\"pvals_adj\"])\n",
    "\n",
    "        # Obtener el menor pvals_adj no nulo y mayor a 0 para recalcular en caso de infinito\n",
    "        min_pvals_adj = df.loc[df[\"pvals_adj\"] > 0, \"pvals_adj\"].min() * 0.1\n",
    "\n",
    "        # Calcular los valores corregidos en caso de infinito\n",
    "        df.loc[np.isinf(df[\"-log10(pvals_adj)\"]), \"-log10(pvals_adj)\"] = -np.log10(min_pvals_adj)\n",
    "\n",
    "        top_genes = df.loc[df[\"logfoldchanges\"].abs().nlargest(5).index]\n",
    "\n",
    "        top_genes.loc[top_genes.index, \"color\"] = top_genes.loc[top_genes.index, \"logfoldchanges\"].apply(\n",
    "            lambda x: \"red\" if x > 0 else \"blue\"\n",
    "        )\n",
    "\n",
    "        print(cell_type, \":\", set(top_genes[\"gene_symbol\"]))\n",
    "\n",
    "        sns.scatterplot(data=df, y=\"-log10(pvals_adj)\", x=\"logfoldchanges\", color='grey', legend=False, ax=axes[i])\n",
    "\n",
    "        # sns.scatterplot(data=top_genes, y=\"-log10(pvals_adj)\", x=\"logfoldchanges\", hue='color', legend=False, ax=axes[i])\n",
    "        # texts = []\n",
    "        for _, row in top_genes.iterrows():\n",
    "            axes[i].scatter(row[\"logfoldchanges\"], row[\"-log10(pvals_adj)\"], color=row['color'])\n",
    "        #     axes[i].text(row[\"logfoldchanges\"] + 0.15, row[\"-log10(pvals_adj)\"] + 0.25, row[\"gene_symbol\"], fontsize=5, color=\"black\")\n",
    "        #\n",
    "        # adjust_text(texts, arrowprops=dict(arrowstyle=\"-\", color='k', lw=0.5))\n",
    "\n",
    "        axes[i].set_ylabel(\"-log10(pvals_adj)\")\n",
    "        axes[i].set_xlabel(\"log2 Fold Change\")\n",
    "        axes[i].set_title(f\"{titles[i]}\")\n",
    "\n",
    "    except FileNotFoundError:\n",
    "        axes[i].set_title(f\"No data for {cell_type}\")\n",
    "        axes[i].axis(\"off\")\n",
    "\n",
    "plt.tight_layout()\n",
    "sns.despine()\n",
    "# plt.savefig('CellXGene/cross-dementia/plots/volcano_per_type_notext.svg', format = 'svg', dpi=1200)\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 687,
   "outputs": [],
   "source": [
    "top_genes_info = {'glutamatergic neuron': ['C1QA', 'HSPB1', 'GPR6', 'DRD4', 'CD14'], 'inhibitory neuron': ['PENK', 'GPR6', 'CRYZ', 'ARAP3', 'DRD4'], 'oligodendrocyte': ['RELN', 'CXCR4', 'BIRC3', 'HSPA1B'], 'astrocyte': ['CRYAB', 'ANXA1', 'EGR1', 'EGF', 'S100A10'], 'microglial cell': ['BAG3', 'HSPA1B', 'HSPB1', 'DNAJB1'], 'oligodendrocyte precursor cell': ['FOS', 'IGFBP3', 'EGR1', 'SOCS3', 'VGF'], 'endothelial cell of vascular tree': ['HSPA1B', 'CACYBP', 'RBM3', 'HSPB1', 'HSPH1'], 'pericyte': ['HSPA1B', 'CRYAB', 'HSPB1', 'VIM', 'HSPH1']}"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 531,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         Id   gene_id gene_symbol            names  logfoldchanges  \\\n",
      "0    Q9Y276     617.0       BCS1L  ENSG00000074582        0.837833   \n",
      "1    P11169    6515.0      SLC2A3  ENSG00000059804        0.387271   \n",
      "2    Q12904    9255.0       AIMP1  ENSG00000164022        0.431453   \n",
      "3    Q8N165  149420.0      PDIK1L  ENSG00000175087        0.293635   \n",
      "4    P67809    4904.0        YBX1  ENSG00000065978        0.364904   \n",
      "..      ...       ...         ...              ...             ...   \n",
      "728  Q9NQ75   57091.0       CASS4  ENSG00000087589        0.861684   \n",
      "729  Q92520   10447.0       FAM3C  ENSG00000196937        0.350469   \n",
      "730  Q08117     166.0        TLE5  ENSG00000104964        0.452040   \n",
      "731  P35638    1649.0       DDIT3  ENSG00000175197        0.872030   \n",
      "732  O15121    8560.0       DEGS1  ENSG00000143753        0.813354   \n",
      "\n",
      "             pvals     pvals_adj     scores  -log10(pvals_adj)   flag  \n",
      "0     5.074668e-04  1.902495e-03   3.476784           2.720677  False  \n",
      "1     1.823817e-26  2.245157e-25  10.645815          24.648753  False  \n",
      "2     5.335923e-17  4.623866e-16   8.379045          15.334995  False  \n",
      "3     9.947450e-08  5.149859e-07   5.327681           6.288205  False  \n",
      "4     9.498815e-09  5.280967e-08   5.739443           7.277287  False  \n",
      "..             ...           ...        ...                ...    ...  \n",
      "728   9.660778e-04  3.508093e-03   3.300224           2.454929  False  \n",
      "729   3.170170e-50  7.355784e-49  14.902596          48.133371  False  \n",
      "730  3.025295e-101  1.574884e-99  21.361858          98.802751  False  \n",
      "731   1.631244e-10  1.013556e-09   6.392566           8.994152  False  \n",
      "732   7.507713e-32  1.091908e-30  11.744825          29.961814  False  \n",
      "\n",
      "[733 rows x 10 columns]\n",
      "         Id      gene_id    gene_symbol            names  logfoldchanges  \\\n",
      "0    P11169       6515.0         SLC2A3  ENSG00000059804        0.449376   \n",
      "1    Q9Y2M5      27252.0         KLHL20  ENSG00000076321        0.354700   \n",
      "2    Q12904       9255.0          AIMP1  ENSG00000164022        0.341772   \n",
      "3    O60290     643641.0         ZNF862  ENSG00000106479        0.270450   \n",
      "4    P35613        682.0            BSG  ENSG00000172270        0.289875   \n",
      "..      ...          ...            ...              ...             ...   \n",
      "668  Q9NQ75      57091.0          CASS4  ENSG00000087589        1.062502   \n",
      "669  Q9Y6H5       9627.0         SNCAIP  ENSG00000064692        0.450695   \n",
      "670  Q08117        166.0           TLE5  ENSG00000104964        0.396488   \n",
      "671  P49674  102800317.0  TPTEP2-CSNK1E  ENSG00000283900        0.279767   \n",
      "672  O15121       8560.0          DEGS1  ENSG00000143753        0.455657   \n",
      "\n",
      "            pvals     pvals_adj     scores  -log10(pvals_adj)   flag  \n",
      "0    4.627132e-13  5.370404e-12   7.235823          11.269993  False  \n",
      "1    6.490162e-20  1.268144e-18   9.135839          17.896832  False  \n",
      "2    1.088346e-06  6.891310e-06   4.874953           5.161698  False  \n",
      "3    5.461479e-11  5.306324e-10   6.557780           9.275206  False  \n",
      "4    1.656321e-19  3.138555e-18   9.033918          17.503270  False  \n",
      "..            ...           ...        ...                ...    ...  \n",
      "668  6.727973e-03  2.591179e-02   2.710017           1.586503  False  \n",
      "669  5.165977e-24  1.336004e-22  10.106573          21.874192  False  \n",
      "670  1.013671e-34  5.345932e-33  12.290903          32.271977  False  \n",
      "671  2.926702e-15  4.067827e-14   7.893992          13.390638  False  \n",
      "672  5.582224e-07  3.651807e-06   5.005137           5.437492  False  \n",
      "\n",
      "[673 rows x 10 columns]\n",
      "         Id      gene_id    gene_symbol            names  logfoldchanges  \\\n",
      "0    Q5JRX3      10531.0         PITRM1  ENSG00000107959       -0.416291   \n",
      "1    P35398       6095.0           RORA  ENSG00000069667       -0.393192   \n",
      "2    Q14517       2195.0           FAT1  ENSG00000083857        0.278725   \n",
      "3    O60290     643641.0         ZNF862  ENSG00000106479        0.332163   \n",
      "4    P11274        613.0            BCR  ENSG00000186716        0.266660   \n",
      "..      ...          ...            ...              ...             ...   \n",
      "549  Q9HB63      59277.0           NTN4  ENSG00000074527       -0.683986   \n",
      "550  P42262       2891.0          GRIA2  ENSG00000120251       -0.435862   \n",
      "551  P49674  102800317.0  TPTEP2-CSNK1E  ENSG00000283900        0.303965   \n",
      "552  P35638       1649.0          DDIT3  ENSG00000175197        0.385822   \n",
      "553  O15121       8560.0          DEGS1  ENSG00000143753        0.397353   \n",
      "\n",
      "             pvals      pvals_adj     scores  -log10(pvals_adj)   flag  \n",
      "0     5.756569e-11   5.997843e-10  -6.549926           9.222005  False  \n",
      "1     3.596141e-48   1.100489e-46 -14.583136          45.958414  False  \n",
      "2     4.717047e-03   2.333301e-02   2.825747           1.632029  False  \n",
      "3     7.991042e-16   1.060523e-14   8.054338          13.974480  False  \n",
      "4     7.822840e-04   4.393340e-03   3.358988           2.357205  False  \n",
      "..             ...            ...        ...                ...    ...  \n",
      "549   3.365789e-05   2.210047e-04  -4.147191           3.655598  False  \n",
      "550  1.183541e-138  9.968240e-137 -25.065489         136.001382  False  \n",
      "551   9.381694e-38   2.363433e-36  12.843278          35.626457  False  \n",
      "552   9.698318e-04   5.378106e-03   3.299135           2.269371  False  \n",
      "553   4.039385e-04   2.356191e-03   3.537497           2.627790  False  \n",
      "\n",
      "[554 rows x 10 columns]\n",
      "         Id      gene_id    gene_symbol            names  logfoldchanges  \\\n",
      "0    P04626       2064.0          ERBB2  ENSG00000141736       -0.287940   \n",
      "1    Q8TCT8      84888.0         SPPL2A  ENSG00000138600       -0.353458   \n",
      "2    Q14517       2195.0           FAT1  ENSG00000083857        0.343325   \n",
      "3    O60290     643641.0         ZNF862  ENSG00000106479        0.419059   \n",
      "4    P35613        682.0            BSG  ENSG00000172270       -0.386828   \n",
      "..      ...          ...            ...              ...             ...   \n",
      "527  P27338       4129.0           MAOB  ENSG00000069535       -0.307064   \n",
      "528  P42262       2891.0          GRIA2  ENSG00000120251       -0.532803   \n",
      "529  Q09666      79026.0          AHNAK  ENSG00000124942        0.630602   \n",
      "530  P49674  102800317.0  TPTEP2-CSNK1E  ENSG00000283900        0.435953   \n",
      "531  Q8IZY2      10347.0          ABCA7  ENSG00000064687        0.761207   \n",
      "\n",
      "            pvals     pvals_adj     scores  -log10(pvals_adj)   flag  \n",
      "0    1.601280e-06  1.567121e-05  -4.798163           4.804897  False  \n",
      "1    2.918588e-15  5.954299e-14  -7.894339          13.225169  False  \n",
      "2    6.414122e-11  9.798292e-10   6.533754           9.008850  False  \n",
      "3    1.014438e-15  2.139190e-14   8.025100          13.669751  False  \n",
      "4    1.092795e-31  4.685898e-30 -11.713048          29.329207  False  \n",
      "..            ...           ...        ...                ...    ...  \n",
      "527  5.072092e-20  1.348813e-18  -9.162474          17.870048  False  \n",
      "528  5.124494e-98  1.063144e-95 -21.011720          94.973408  False  \n",
      "529  1.198747e-64  1.316056e-62  16.977812          61.880726  False  \n",
      "530  1.172580e-25  4.015089e-24  10.471111          23.396305  False  \n",
      "531  1.035701e-04  7.951646e-04   3.882072           3.099543  False  \n",
      "\n",
      "[532 rows x 10 columns]\n",
      "         Id   gene_id gene_symbol            names  logfoldchanges  \\\n",
      "0    P11169    6515.0      SLC2A3  ENSG00000059804       -0.779546   \n",
      "1    O60290  643641.0      ZNF862  ENSG00000106479        0.615092   \n",
      "2    Q02156    5581.0       PRKCE  ENSG00000171132        0.317718   \n",
      "3    Q14393    2621.0        GAS6  ENSG00000183087       -0.490290   \n",
      "4    P04233     972.0        CD74  ENSG00000019582        0.365258   \n",
      "..      ...       ...         ...              ...             ...   \n",
      "329  P20339    5868.0       RAB5A  ENSG00000144566       -0.353601   \n",
      "330  P51790    1182.0       CLCN3  ENSG00000109572        0.440371   \n",
      "331  P13473    3920.0       LAMP2  ENSG00000005893        0.372019   \n",
      "332  Q9NQ75   57091.0       CASS4  ENSG00000087589       -0.592606   \n",
      "333  Q09666   79026.0       AHNAK  ENSG00000124942        1.404643   \n",
      "\n",
      "            pvals     pvals_adj    scores  -log10(pvals_adj)   flag  \n",
      "0    1.832361e-15  1.416440e-13 -7.952195          12.848802  False  \n",
      "1    1.569596e-05  3.727790e-04  4.318688           3.428549  False  \n",
      "2    3.456984e-08  1.255326e-06  5.516561           5.901244  False  \n",
      "3    5.320820e-11  2.666553e-09 -6.561671           8.574050  False  \n",
      "4    4.915439e-17  4.280528e-15  8.388701          14.368503  False  \n",
      "..            ...           ...       ...                ...    ...  \n",
      "329  5.662569e-04  9.777808e-03 -3.447282           2.009758  False  \n",
      "330  3.586279e-06  9.492201e-05  4.634023           4.022633  False  \n",
      "331  3.486081e-05  7.757080e-04  4.139142           3.110302  False  \n",
      "332  9.174418e-07  2.688019e-05 -4.908567           4.570568  False  \n",
      "333  7.769801e-05  1.613134e-03  3.951392           2.792330  False  \n",
      "\n",
      "[334 rows x 10 columns]\n",
      "         Id  gene_id gene_symbol            names  logfoldchanges  \\\n",
      "0    P24821   3371.0         TNC  ENSG00000041982       -1.644939   \n",
      "1    P13804   2108.0        ETFA  ENSG00000140374       -0.412017   \n",
      "2    P35568   3667.0        IRS1  ENSG00000169047        0.499488   \n",
      "3    Q8IXJ6  22933.0       SIRT2  ENSG00000068903        0.371526   \n",
      "4    Q9UHD2  29110.0        TBK1  ENSG00000183735       -0.446271   \n",
      "..      ...      ...         ...              ...             ...   \n",
      "315  P14735   3416.0         IDE  ENSG00000119912       -0.288636   \n",
      "316  P24385    595.0       CCND1  ENSG00000110092       -0.548290   \n",
      "317  Q92520  10447.0       FAM3C  ENSG00000196937       -0.293168   \n",
      "318  Q9Y570  51400.0       PPME1  ENSG00000214517       -0.307343   \n",
      "319  P49674   1454.0      CSNK1E  ENSG00000213923        0.537802   \n",
      "\n",
      "            pvals     pvals_adj    scores  -log10(pvals_adj)   flag  \n",
      "0    1.198126e-12  5.161087e-11 -7.105587          10.287259  False  \n",
      "1    2.253193e-05  3.919472e-04 -4.238200           3.406772  False  \n",
      "2    2.773655e-03  2.916463e-02  2.991770           1.535143  False  \n",
      "3    8.949580e-08  2.287250e-06  5.346855           5.640686  False  \n",
      "4    2.094059e-06  4.350800e-05 -4.744129           4.361431  False  \n",
      "..            ...           ...       ...                ...    ...  \n",
      "315  3.064300e-03  3.168165e-02 -2.961213           1.499192  False  \n",
      "316  1.989628e-04  2.842398e-03 -3.720330           2.546315  False  \n",
      "317  1.881041e-03  2.077711e-02 -3.108399           1.682415  False  \n",
      "318  5.603309e-04  7.147259e-03 -3.450123           2.145860  False  \n",
      "319  1.961435e-08  5.473974e-07  5.615369           6.261697  False  \n",
      "\n",
      "[320 rows x 10 columns]\n",
      "        Id  gene_id gene_symbol            names  logfoldchanges  \\\n",
      "0   Q8TEW0  56288.0       PARD3  ENSG00000148498        0.536861   \n",
      "1   P05362   3383.0       ICAM1  ENSG00000090339       -1.358272   \n",
      "2   P46934   4734.0       NEDD4  ENSG00000069869        0.635650   \n",
      "3   P01130   3949.0        LDLR  ENSG00000130164        0.673549   \n",
      "4   P07900   3320.0    HSP90AA1  ENSG00000080824        1.269916   \n",
      "..     ...      ...         ...              ...             ...   \n",
      "68  P04439   3105.0       HLA-A  ENSG00000206503       -0.385615   \n",
      "69  Q13627   1859.0      DYRK1A  ENSG00000157540        0.508074   \n",
      "70  Q9NX09  54541.0       DDIT4  ENSG00000168209        1.310385   \n",
      "71  P22694   5567.0      PRKACB  ENSG00000142875        0.540728   \n",
      "72  Q13464   6093.0       ROCK1  ENSG00000067900        0.449656   \n",
      "\n",
      "           pvals     pvals_adj     scores  -log10(pvals_adj)   flag  \n",
      "0   1.576170e-06  3.532825e-04   4.801328           3.451878  False  \n",
      "1   1.738858e-06  3.803247e-04  -4.781623           3.419845  False  \n",
      "2   8.374939e-07  2.054773e-04   4.926421           3.687236  False  \n",
      "3   3.863434e-04  3.113288e-02   3.549241           1.506781  False  \n",
      "4   2.942664e-42  2.767576e-38  13.622513          37.557900  False  \n",
      "..           ...           ...        ...                ...    ...  \n",
      "68  9.379684e-06  1.584717e-03  -4.431001           2.800048  False  \n",
      "69  4.812537e-06  8.648773e-04   4.572798           3.063045  False  \n",
      "70  7.300147e-12  5.281375e-09   6.851653           8.277253  False  \n",
      "71  4.519031e-05  5.448908e-03   4.079203           2.263691  False  \n",
      "72  2.866264e-04  2.458104e-02   3.627096           1.609400  False  \n",
      "\n",
      "[73 rows x 10 columns]\n",
      "        Id  gene_id gene_symbol            names  logfoldchanges  \\\n",
      "0   P07900   3320.0    HSP90AA1  ENSG00000080824        1.110109   \n",
      "1   O94875   8470.0      SORBS2  ENSG00000154556        0.827073   \n",
      "2   P60484   5728.0        PTEN  ENSG00000171862       -0.782102   \n",
      "3   Q15303   2066.0       ERBB4  ENSG00000178568        1.107987   \n",
      "4   P04792   3315.0       HSPB1  ENSG00000106211        1.884719   \n",
      "5   P08238   3326.0    HSP90AB1  ENSG00000096384        0.861556   \n",
      "6   P54253   6310.0       ATXN1  ENSG00000124788        0.712304   \n",
      "7   P09619   5159.0      PDGFRB  ENSG00000113721       -0.378450   \n",
      "8   Q92598  10808.0       HSPH1  ENSG00000120694        1.676103   \n",
      "9   O43524   2309.0       FOXO3  ENSG00000118689        0.854423   \n",
      "10  P61586    387.0        RHOA  ENSG00000067560        0.785520   \n",
      "11  P0DMV8   3304.0      HSPA1B  ENSG00000204388        1.975146   \n",
      "12  P17676   1051.0       CEBPB  ENSG00000172216        1.105564   \n",
      "13  P02511   1410.0       CRYAB  ENSG00000109846        1.525713   \n",
      "14  P13693   7178.0        TPT1  ENSG00000133112        0.802365   \n",
      "15  Q15185  10728.0      PTGES3  ENSG00000110958        0.866479   \n",
      "16  P08670   7431.0         VIM  ENSG00000026025        1.117781   \n",
      "17  Q7Z6G8  56899.0      ANKS1B  ENSG00000185046        0.978241   \n",
      "18  Q09666  79026.0       AHNAK  ENSG00000124942        0.989039   \n",
      "19  P49716   1052.0       CEBPD  ENSG00000221869        0.708934   \n",
      "\n",
      "           pvals     pvals_adj     scores  -log10(pvals_adj)   flag  \n",
      "0   2.761193e-13  1.112958e-09   7.305558           8.953521  False  \n",
      "1   1.624354e-06  1.580385e-03   4.795295           2.801237  False  \n",
      "2   9.017274e-12  2.826915e-08  -6.821376           7.548687  False  \n",
      "3   1.496004e-04  4.292680e-02   3.791732           1.367271  False  \n",
      "4   1.905079e-24  5.375182e-20  10.203879          19.269607   True  \n",
      "5   2.566908e-06  2.336300e-03   4.702742           2.631471  False  \n",
      "6   3.498667e-05  1.410213e-02   4.138314           1.850715  False  \n",
      "7   1.948204e-04  4.917496e-02  -3.725640           1.308256  False  \n",
      "8   1.338602e-05  7.097056e-03   4.353698           2.148922   True  \n",
      "9   1.617127e-05  7.893088e-03   4.312098           2.102753  False  \n",
      "10  1.640082e-04  4.407135e-02   3.768840           1.355844  False  \n",
      "11  1.293792e-07  1.738302e-04   5.279723           3.759875   True  \n",
      "12  9.147368e-06  5.491340e-03   4.436405           2.260322  False  \n",
      "13  8.710331e-10  1.755443e-06   6.131411           5.755613   True  \n",
      "14  1.618387e-04  4.390652e-02   3.772163           1.357471  False  \n",
      "15  3.143596e-05  1.285458e-02   4.162807           1.890942  False  \n",
      "16  8.111714e-09  1.430450e-05   5.766120           4.844527   True  \n",
      "17  2.711835e-05  1.159309e-02   4.196406           1.935801  False  \n",
      "18  1.952010e-04  4.917496e-02   3.725147           1.308256  False  \n",
      "19  1.193964e-04  3.743076e-02   3.847362           1.426771  False  \n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Andrea\\Downloads\\single-cell\\lib\\site-packages\\pandas\\core\\arraylike.py:399: RuntimeWarning: divide by zero encountered in log10\n",
      "  result = getattr(ufunc, method)(*inputs, **kwargs)\n",
      "C:\\Users\\Andrea\\Downloads\\single-cell\\lib\\site-packages\\pandas\\core\\arraylike.py:399: RuntimeWarning: divide by zero encountered in log10\n",
      "  result = getattr(ufunc, method)(*inputs, **kwargs)\n",
      "C:\\Users\\Andrea\\Downloads\\single-cell\\lib\\site-packages\\pandas\\core\\arraylike.py:399: RuntimeWarning: divide by zero encountered in log10\n",
      "  result = getattr(ufunc, method)(*inputs, **kwargs)\n"
     ]
    }
   ],
   "source": [
    "for i, cell_type in enumerate(cell_types):\n",
    "    file_path = f\"CellXGene/cross-dementia/filtered/graphs/gephi/degs_{cell_type}_mapped_gephi.csv\"  # Ajustar el nombre del archivo según el formato\n",
    "\n",
    "    try:\n",
    "        # Cargar los datos\n",
    "        df = pd.read_csv(file_path)\n",
    "\n",
    "        df[\"-log10(pvals_adj)\"] = -np.log10(df[\"pvals_adj\"])\n",
    "\n",
    "        top_genes = df.loc[df[\"logfoldchanges\"].abs().nlargest(5).index]\n",
    "\n",
    "        # Crear la columna \"flag\" con False por defecto\n",
    "        df[\"flag\"] = False\n",
    "\n",
    "        # Marcar los top 5 genes como True\n",
    "        df.loc[top_genes.index, \"flag\"] = True\n",
    "        print(df)\n",
    "        df.to_csv(f\"CellXGene/cross-dementia/filtered/graphs/gephi/degs_{cell_type}_mapped_gephi.csv\", index=False)\n",
    "        # print(f\"Archivo guardado: {output_file}\")\n",
    "\n",
    "    except FileNotFoundError:\n",
    "        print(f\"No data for {cell_type}\")\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 480,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Andrea\\Downloads\\single-cell\\lib\\site-packages\\pandas\\core\\arraylike.py:399: RuntimeWarning: divide by zero encountered in log10\n",
      "  result = getattr(ufunc, method)(*inputs, **kwargs)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    protein_id   gene_id gene_symbol            names  logfoldchanges  \\\n",
      "0       Q9Y276     617.0       BCS1L  ENSG00000074582        0.837833   \n",
      "1       P11169    6515.0      SLC2A3  ENSG00000059804        0.387271   \n",
      "2       Q12904    9255.0       AIMP1  ENSG00000164022        0.431453   \n",
      "3       Q8N165  149420.0      PDIK1L  ENSG00000175087        0.293635   \n",
      "4       P67809    4904.0        YBX1  ENSG00000065978        0.364904   \n",
      "..         ...       ...         ...              ...             ...   \n",
      "728     Q9NQ75   57091.0       CASS4  ENSG00000087589        0.861684   \n",
      "729     Q92520   10447.0       FAM3C  ENSG00000196937        0.350469   \n",
      "730     Q08117     166.0        TLE5  ENSG00000104964        0.452040   \n",
      "731     P35638    1649.0       DDIT3  ENSG00000175197        0.872030   \n",
      "732     O15121    8560.0       DEGS1  ENSG00000143753        0.813354   \n",
      "\n",
      "             pvals     pvals_adj     scores  -log10(pvals_adj) color  \n",
      "0     5.074668e-04  1.902495e-03   3.476784           2.720677  grey  \n",
      "1     1.823817e-26  2.245157e-25  10.645815          24.648753  grey  \n",
      "2     5.335923e-17  4.623866e-16   8.379045          15.334995  grey  \n",
      "3     9.947450e-08  5.149859e-07   5.327681           6.288205  grey  \n",
      "4     9.498815e-09  5.280967e-08   5.739443           7.277287  grey  \n",
      "..             ...           ...        ...                ...   ...  \n",
      "728   9.660778e-04  3.508093e-03   3.300224           2.454929  grey  \n",
      "729   3.170170e-50  7.355784e-49  14.902596          48.133371  grey  \n",
      "730  3.025295e-101  1.574884e-99  21.361858          98.802751  grey  \n",
      "731   1.631244e-10  1.013556e-09   6.392566           8.994152  grey  \n",
      "732   7.507713e-32  1.091908e-30  11.744825          29.961814  grey  \n",
      "\n",
      "[733 rows x 10 columns]\n"
     ]
    },
    {
     "ename": "AttributeError",
     "evalue": "PathCollection.set() got an unexpected keyword argument 'order'",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mAttributeError\u001B[0m                            Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[480], line 32\u001B[0m\n\u001B[0;32m     27\u001B[0m df\u001B[38;5;241m.\u001B[39mloc[top_genes\u001B[38;5;241m.\u001B[39mindex, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcolor\u001B[39m\u001B[38;5;124m\"\u001B[39m] \u001B[38;5;241m=\u001B[39m df\u001B[38;5;241m.\u001B[39mloc[top_genes\u001B[38;5;241m.\u001B[39mindex, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mlogfoldchanges\u001B[39m\u001B[38;5;124m\"\u001B[39m]\u001B[38;5;241m.\u001B[39mapply(\n\u001B[0;32m     28\u001B[0m     \u001B[38;5;28;01mlambda\u001B[39;00m x: \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mred\u001B[39m\u001B[38;5;124m\"\u001B[39m \u001B[38;5;28;01mif\u001B[39;00m x \u001B[38;5;241m>\u001B[39m \u001B[38;5;241m0\u001B[39m \u001B[38;5;28;01melse\u001B[39;00m \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mblue\u001B[39m\u001B[38;5;124m\"\u001B[39m\n\u001B[0;32m     29\u001B[0m )\n\u001B[0;32m     30\u001B[0m \u001B[38;5;28mprint\u001B[39m(df)\n\u001B[1;32m---> 32\u001B[0m \u001B[43msns\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mscatterplot\u001B[49m\u001B[43m(\u001B[49m\u001B[43mdata\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mdf\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43my\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43m-log10(pvals_adj)\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mx\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43mlogfoldchanges\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mlegend\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[38;5;28;43;01mFalse\u001B[39;49;00m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43max\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43maxes\u001B[49m\u001B[43m[\u001B[49m\u001B[43mi\u001B[49m\u001B[43m]\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43morder\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43morder\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m     34\u001B[0m \u001B[38;5;66;03m# for _, row in top_genes.iterrows():\u001B[39;00m\n\u001B[0;32m     35\u001B[0m \u001B[38;5;66;03m#     # axes[i].scatter(row[\"logfoldchanges\"], row[\"-log10(pvals_adj)\"])\u001B[39;00m\n\u001B[0;32m     36\u001B[0m \u001B[38;5;66;03m#     axes[i].text(row[\"logfoldchanges\"] + 0.05, row[\"-log10(pvals_adj)\"] + 0.1, row[\"gene_symbol\"], fontsize=5, color=\"black\")\u001B[39;00m\n\u001B[0;32m     37\u001B[0m \n\u001B[0;32m     38\u001B[0m \u001B[38;5;66;03m# Etiquetas y título\u001B[39;00m\n\u001B[0;32m     39\u001B[0m axes[i]\u001B[38;5;241m.\u001B[39mset_ylabel(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m-log10(pvals_adj)\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\seaborn\\relational.py:634\u001B[0m, in \u001B[0;36mscatterplot\u001B[1;34m(data, x, y, hue, size, style, palette, hue_order, hue_norm, sizes, size_order, size_norm, markers, style_order, legend, ax, **kwargs)\u001B[0m\n\u001B[0;32m    631\u001B[0m p\u001B[38;5;241m.\u001B[39m_attach(ax)\n\u001B[0;32m    633\u001B[0m color \u001B[38;5;241m=\u001B[39m kwargs\u001B[38;5;241m.\u001B[39mpop(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcolor\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;28;01mNone\u001B[39;00m)\n\u001B[1;32m--> 634\u001B[0m kwargs[\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcolor\u001B[39m\u001B[38;5;124m\"\u001B[39m] \u001B[38;5;241m=\u001B[39m \u001B[43m_default_color\u001B[49m\u001B[43m(\u001B[49m\u001B[43max\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mscatter\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mhue\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mcolor\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mkwargs\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m    636\u001B[0m p\u001B[38;5;241m.\u001B[39mplot(ax, kwargs)\n\u001B[0;32m    638\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m ax\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\seaborn\\utils.py:105\u001B[0m, in \u001B[0;36m_default_color\u001B[1;34m(method, hue, color, kws, saturation)\u001B[0m\n\u001B[0;32m     99\u001B[0m scout_size \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mmax\u001B[39m(\n\u001B[0;32m    100\u001B[0m     np\u001B[38;5;241m.\u001B[39matleast_1d(kws\u001B[38;5;241m.\u001B[39mget(key, []))\u001B[38;5;241m.\u001B[39mshape[\u001B[38;5;241m0\u001B[39m]\n\u001B[0;32m    101\u001B[0m     \u001B[38;5;28;01mfor\u001B[39;00m key \u001B[38;5;129;01min\u001B[39;00m [\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124ms\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mc\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mfc\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mfacecolor\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mfacecolors\u001B[39m\u001B[38;5;124m\"\u001B[39m]\n\u001B[0;32m    102\u001B[0m )\n\u001B[0;32m    103\u001B[0m scout_x \u001B[38;5;241m=\u001B[39m scout_y \u001B[38;5;241m=\u001B[39m np\u001B[38;5;241m.\u001B[39mfull(scout_size, np\u001B[38;5;241m.\u001B[39mnan)\n\u001B[1;32m--> 105\u001B[0m scout \u001B[38;5;241m=\u001B[39m method(scout_x, scout_y, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkws)\n\u001B[0;32m    106\u001B[0m facecolors \u001B[38;5;241m=\u001B[39m scout\u001B[38;5;241m.\u001B[39mget_facecolors()\n\u001B[0;32m    108\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28mlen\u001B[39m(facecolors):\n\u001B[0;32m    109\u001B[0m     \u001B[38;5;66;03m# Handle bug in matplotlib <= 3.2 (I think)\u001B[39;00m\n\u001B[0;32m    110\u001B[0m     \u001B[38;5;66;03m# This will limit the ability to use non color= kwargs to specify\u001B[39;00m\n\u001B[0;32m    111\u001B[0m     \u001B[38;5;66;03m# a color in versions of matplotlib with the bug, but trying to\u001B[39;00m\n\u001B[0;32m    112\u001B[0m     \u001B[38;5;66;03m# work out what the user wanted by re-implementing the broken logic\u001B[39;00m\n\u001B[0;32m    113\u001B[0m     \u001B[38;5;66;03m# of inspecting the kwargs is probably too brittle.\u001B[39;00m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\__init__.py:1476\u001B[0m, in \u001B[0;36m_preprocess_data.<locals>.inner\u001B[1;34m(ax, data, *args, **kwargs)\u001B[0m\n\u001B[0;32m   1473\u001B[0m \u001B[38;5;129m@functools\u001B[39m\u001B[38;5;241m.\u001B[39mwraps(func)\n\u001B[0;32m   1474\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21minner\u001B[39m(ax, \u001B[38;5;241m*\u001B[39margs, data\u001B[38;5;241m=\u001B[39m\u001B[38;5;28;01mNone\u001B[39;00m, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs):\n\u001B[0;32m   1475\u001B[0m     \u001B[38;5;28;01mif\u001B[39;00m data \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[1;32m-> 1476\u001B[0m         \u001B[38;5;28;01mreturn\u001B[39;00m func(\n\u001B[0;32m   1477\u001B[0m             ax,\n\u001B[0;32m   1478\u001B[0m             \u001B[38;5;241m*\u001B[39m\u001B[38;5;28mmap\u001B[39m(sanitize_sequence, args),\n\u001B[0;32m   1479\u001B[0m             \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39m{k: sanitize_sequence(v) \u001B[38;5;28;01mfor\u001B[39;00m k, v \u001B[38;5;129;01min\u001B[39;00m kwargs\u001B[38;5;241m.\u001B[39mitems()})\n\u001B[0;32m   1481\u001B[0m     bound \u001B[38;5;241m=\u001B[39m new_sig\u001B[38;5;241m.\u001B[39mbind(ax, \u001B[38;5;241m*\u001B[39margs, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs)\n\u001B[0;32m   1482\u001B[0m     auto_label \u001B[38;5;241m=\u001B[39m (bound\u001B[38;5;241m.\u001B[39marguments\u001B[38;5;241m.\u001B[39mget(label_namer)\n\u001B[0;32m   1483\u001B[0m                   \u001B[38;5;129;01mor\u001B[39;00m bound\u001B[38;5;241m.\u001B[39mkwargs\u001B[38;5;241m.\u001B[39mget(label_namer))\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\axes\\_axes.py:4901\u001B[0m, in \u001B[0;36mAxes.scatter\u001B[1;34m(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, **kwargs)\u001B[0m\n\u001B[0;32m   4897\u001B[0m         keys_str \u001B[38;5;241m=\u001B[39m \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m, \u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;241m.\u001B[39mjoin(\u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m'\u001B[39m\u001B[38;5;132;01m{\u001B[39;00mk\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m'\u001B[39m\u001B[38;5;124m\"\u001B[39m \u001B[38;5;28;01mfor\u001B[39;00m k \u001B[38;5;129;01min\u001B[39;00m extra_keys)\n\u001B[0;32m   4898\u001B[0m         _api\u001B[38;5;241m.\u001B[39mwarn_external(\n\u001B[0;32m   4899\u001B[0m             \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mNo data for colormapping provided via \u001B[39m\u001B[38;5;124m'\u001B[39m\u001B[38;5;124mc\u001B[39m\u001B[38;5;124m'\u001B[39m\u001B[38;5;124m. \u001B[39m\u001B[38;5;124m\"\u001B[39m\n\u001B[0;32m   4900\u001B[0m             \u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mParameters \u001B[39m\u001B[38;5;132;01m{\u001B[39;00mkeys_str\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m will be ignored\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[1;32m-> 4901\u001B[0m \u001B[43mcollection\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m_internal_update\u001B[49m\u001B[43m(\u001B[49m\u001B[43mkwargs\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m   4903\u001B[0m \u001B[38;5;66;03m# Classic mode only:\u001B[39;00m\n\u001B[0;32m   4904\u001B[0m \u001B[38;5;66;03m# ensure there are margins to allow for the\u001B[39;00m\n\u001B[0;32m   4905\u001B[0m \u001B[38;5;66;03m# finite size of the symbols.  In v2.x, margins\u001B[39;00m\n\u001B[0;32m   4906\u001B[0m \u001B[38;5;66;03m# are present by default, so we disable this\u001B[39;00m\n\u001B[0;32m   4907\u001B[0m \u001B[38;5;66;03m# scatter-specific override.\u001B[39;00m\n\u001B[0;32m   4908\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m mpl\u001B[38;5;241m.\u001B[39mrcParams[\u001B[38;5;124m'\u001B[39m\u001B[38;5;124m_internal.classic_mode\u001B[39m\u001B[38;5;124m'\u001B[39m]:\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\artist.py:1216\u001B[0m, in \u001B[0;36mArtist._internal_update\u001B[1;34m(self, kwargs)\u001B[0m\n\u001B[0;32m   1209\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21m_internal_update\u001B[39m(\u001B[38;5;28mself\u001B[39m, kwargs):\n\u001B[0;32m   1210\u001B[0m \u001B[38;5;250m    \u001B[39m\u001B[38;5;124;03m\"\"\"\u001B[39;00m\n\u001B[0;32m   1211\u001B[0m \u001B[38;5;124;03m    Update artist properties without prenormalizing them, but generating\u001B[39;00m\n\u001B[0;32m   1212\u001B[0m \u001B[38;5;124;03m    errors as if calling `set`.\u001B[39;00m\n\u001B[0;32m   1213\u001B[0m \n\u001B[0;32m   1214\u001B[0m \u001B[38;5;124;03m    The lack of prenormalization is to maintain backcompatibility.\u001B[39;00m\n\u001B[0;32m   1215\u001B[0m \u001B[38;5;124;03m    \"\"\"\u001B[39;00m\n\u001B[1;32m-> 1216\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m_update_props\u001B[49m\u001B[43m(\u001B[49m\n\u001B[0;32m   1217\u001B[0m \u001B[43m        \u001B[49m\u001B[43mkwargs\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;132;43;01m{cls.__name__}\u001B[39;49;00m\u001B[38;5;124;43m.set() got an unexpected keyword argument \u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\n\u001B[0;32m   1218\u001B[0m \u001B[43m        \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;132;43;01m{prop_name!r}\u001B[39;49;00m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\artist.py:1190\u001B[0m, in \u001B[0;36mArtist._update_props\u001B[1;34m(self, props, errfmt)\u001B[0m\n\u001B[0;32m   1188\u001B[0m             func \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mgetattr\u001B[39m(\u001B[38;5;28mself\u001B[39m, \u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mset_\u001B[39m\u001B[38;5;132;01m{\u001B[39;00mk\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;28;01mNone\u001B[39;00m)\n\u001B[0;32m   1189\u001B[0m             \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28mcallable\u001B[39m(func):\n\u001B[1;32m-> 1190\u001B[0m                 \u001B[38;5;28;01mraise\u001B[39;00m \u001B[38;5;167;01mAttributeError\u001B[39;00m(\n\u001B[0;32m   1191\u001B[0m                     errfmt\u001B[38;5;241m.\u001B[39mformat(\u001B[38;5;28mcls\u001B[39m\u001B[38;5;241m=\u001B[39m\u001B[38;5;28mtype\u001B[39m(\u001B[38;5;28mself\u001B[39m), prop_name\u001B[38;5;241m=\u001B[39mk))\n\u001B[0;32m   1192\u001B[0m             ret\u001B[38;5;241m.\u001B[39mappend(func(v))\n\u001B[0;32m   1193\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m ret:\n",
      "\u001B[1;31mAttributeError\u001B[0m: PathCollection.set() got an unexpected keyword argument 'order'"
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 2000x1000 with 8 Axes>",
      "image/png": "[encoded data, 21812 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sns.set_context(\"paper\")\n",
    "sns.set_style(\"white\")\n",
    "\n",
    "fig, axes = plt.subplots(2, 4, figsize=(20,10))\n",
    "# fig, axes = plt.subplots(2, 4, figsize=(12,6))\n",
    "axes = axes.flatten()\n",
    "\n",
    "order = ['glutamatergic neuron', 'inhibitory interneuron',\n",
    "         'oligodendrocyte', 'astrocyte', 'microglial cell',\n",
    "         'oligodendrocyte precursor cell', 'endothelial cell of vascular tree', 'pericyte']\n",
    "\n",
    "# Iterar sobre cada tipo celular y graficar su volcano plot\n",
    "for i, cell_type in enumerate(order):\n",
    "    file_path = f\"CellXGene/cross-dementia/filtered/data/degs_{cell_type}_mapped.csv\"  # Ajustar el nombre del archivo según el formato\n",
    "\n",
    "    try:\n",
    "        # Cargar los datos\n",
    "        df = pd.read_csv(file_path)\n",
    "\n",
    "        # Calcular el eje x: -log10(pvals_adj)\n",
    "        df[\"-log10(pvals_adj)\"] = -np.log10(df[\"pvals_adj\"])\n",
    "\n",
    "        df[\"color\"] = \"grey\"  # Color predeterminado para genes no significativos\n",
    "        top_genes = df.loc[df[\"logfoldchanges\"].abs().nlargest(5).index]\n",
    "\n",
    "        # Asignar el color según el signo de logfoldchanges\n",
    "        df.loc[top_genes.index, \"color\"] = df.loc[top_genes.index, \"logfoldchanges\"].apply(\n",
    "            lambda x: \"red\" if x > 0 else \"blue\"\n",
    "        )\n",
    "        print(df)\n",
    "\n",
    "        sns.scatterplot(data=df, y=\"-log10(pvals_adj)\", x=\"logfoldchanges\", legend=False, ax=axes[i])\n",
    "\n",
    "        # for _, row in top_genes.iterrows():\n",
    "        #     # axes[i].scatter(row[\"logfoldchanges\"], row[\"-log10(pvals_adj)\"])\n",
    "        #     axes[i].text(row[\"logfoldchanges\"] + 0.05, row[\"-log10(pvals_adj)\"] + 0.1, row[\"gene_symbol\"], fontsize=5, color=\"black\")\n",
    "\n",
    "        # Etiquetas y título\n",
    "        axes[i].set_ylabel(\"-log10(pvals_adj)\")\n",
    "        axes[i].set_xlabel(\"log2 Fold Change\")\n",
    "        axes[i].set_title(f\"{cell_type}\")\n",
    "        # axes[i].axhline(y=0, color='black', linestyle='--', linewidth=1)\n",
    "        # axes[i].grid(True, linestyle='--', alpha=0.7)\n",
    "    except FileNotFoundError:\n",
    "        axes[i].set_title(f\"No data for {cell_type}\")\n",
    "        axes[i].axis(\"off\")\n",
    "\n",
    "# Ajustar el diseño\n",
    "plt.tight_layout()\n",
    "sns.despine()\n",
    "# plt.savefig('CellXGene/cross-dementia/plots/volcano_per_type.svg', format = 'svg', dpi=1200)\n",
    "# plt.savefig('CellXGene/cross-dementia/plots/volcano_per_type.png', format = 'png', dpi=500)\n",
    "plt.show()\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 6.4. Representation of top 20 most up- and down-regulated differentially expressed genes"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 276,
   "outputs": [],
   "source": [
    "cell_types = ['astrocyte', 'microglial cell', 'oligodendrocyte', 'glutamatergic neuron', 'inhibitory interneuron', 'endothelial cell of vascular tree', 'oligodendrocyte precursor cell', 'pericyte']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "file_pattern = 'CellXGene/cross-dementia/filtered/data/degs_*_mapped.csv'\n",
    "files = glob.glob(file_pattern)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 281,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     protein_id gene_symbol  logfoldchanges  cell_type\n",
      "0        P04626       ERBB2       -0.287940  astrocyte\n",
      "1        Q8TCT8      SPPL2A       -0.353458  astrocyte\n",
      "2        Q14517        FAT1        0.343325  astrocyte\n",
      "3        O60290      ZNF862        0.419059  astrocyte\n",
      "4        P35613         BSG       -0.386828  astrocyte\n",
      "...         ...         ...             ...        ...\n",
      "3234     Q15185      PTGES3        0.866479   pericyte\n",
      "3235     P08670         VIM        1.117781   pericyte\n",
      "3236     Q7Z6G8      ANKS1B        0.978241   pericyte\n",
      "3237     Q09666       AHNAK        0.989039   pericyte\n",
      "3238     P49716       CEBPD        0.708934   pericyte\n",
      "\n",
      "[3239 rows x 4 columns]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\72016613.py:16: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df_filtered['cell_type'] = cell_type\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\72016613.py:16: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df_filtered['cell_type'] = cell_type\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\72016613.py:16: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df_filtered['cell_type'] = cell_type\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\72016613.py:16: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df_filtered['cell_type'] = cell_type\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\72016613.py:16: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df_filtered['cell_type'] = cell_type\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\72016613.py:16: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df_filtered['cell_type'] = cell_type\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\72016613.py:16: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df_filtered['cell_type'] = cell_type\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\72016613.py:16: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  df_filtered['cell_type'] = cell_type\n"
     ]
    }
   ],
   "source": [
    "dfs = []\n",
    "\n",
    "# Leer cada archivo y seleccionar las columnas relevantes\n",
    "for file in files:\n",
    "    df = pd.read_csv(file)\n",
    "\n",
    "    df_filtered = df[['protein_id', 'gene_symbol', 'logfoldchanges']]\n",
    "\n",
    "    cell_type = file.split('/')[-1].split('_')[1]\n",
    "    df_filtered['cell_type'] = cell_type\n",
    "    # Añadir el DataFrame a la lista\n",
    "    dfs.append(df_filtered)\n",
    "\n",
    "# Concatenar todos los DataFrames en uno solo\n",
    "lfc_df = pd.concat(dfs, ignore_index=True)\n",
    "print(lfc_df)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 436,
   "outputs": [],
   "source": [
    "top_high = lfc_df.nlargest(20, \"logfoldchanges\")[\"protein_id\"]\n",
    "top_low = lfc_df.nsmallest(20, \"logfoldchanges\")[\"protein_id\"]\n",
    "top_proteins = pd.concat([top_high, top_low])"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 437,
   "outputs": [],
   "source": [
    "lfc_filtered = lfc_df[lfc_df[\"protein_id\"].isin(top_proteins)]"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 286,
   "outputs": [],
   "source": [
    "heatmap_df = lfc_filtered.pivot(index=\"protein_id\", columns=\"cell_type\", values=\"logfoldchanges\")\n",
    "\n",
    "# Agregar anotación de gene_symbol en las filas\n",
    "gene_symbols = lfc_filtered.set_index(\"protein_id\")[\"gene_symbol\"].to_dict()\n",
    "heatmap_df.index = heatmap_df.index.map(lambda x: f\"{gene_symbols.get(x, x)} ({x})\")  # Formato: gene_symbol (protein_id)\n",
    "\n",
    "heatmap_df[\"max_lfc\"] = heatmap_df.max(axis=1)  # Calcular la media de logfoldchange por proteína\n",
    "heatmap_df = heatmap_df.sort_values(by=\"max_lfc\", ascending=False)  # Ordenar de mayor a menor\n",
    "heatmap_df = heatmap_df.drop(columns=[\"max_lfc\"])  # Eliminar la columna auxiliar"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 287,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 900x800 with 2 Axes>",
      "image/png": "[encoded data, 98500 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sns.set_context(\"paper\")\n",
    "sns.set_style(\"white\")\n",
    "\n",
    "# Crear heatmap\n",
    "plt.figure(figsize=(9, 8))\n",
    "sns.heatmap(heatmap_df, cmap=\"coolwarm\", center=0, linewidths=0.5, annot=False, linecolor='grey')\n",
    "plt.title(\"Top 20 proteins with highest and top 20 proteins with lowest LFC by cell type\")\n",
    "plt.xlabel(\"Cell type\")\n",
    "plt.ylabel(\"Gene Symbol (Protein ID)\")\n",
    "# plt.xticks(rotation=45, ha='right')\n",
    "plt.yticks(rotation=0)\n",
    "plt.tight_layout()\n",
    "# plt.savefig('CellXGene/cross-dementia/plots/heatmap_top20genes.svg', format = 'svg', dpi=1200)\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 6.5. Representation of differentially expressed genes expressed in all cell types"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "outputs": [],
   "source": [
    "gen_pro = pd.read_csv('CellXGene/gen_pro.tsv', sep='\\t')\n",
    "gen = pd.read_csv(\"CellXGene/gen.tsv\", sep=\"\\t\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "outputs": [
    {
     "data": {
      "text/plain": "{'astrocyte': <networkx.classes.graph.Graph at 0x2bbb14d2460>,\n 'microglial cell': <networkx.classes.graph.Graph at 0x2bba59f9190>,\n 'oligodendrocyte': <networkx.classes.graph.Graph at 0x2bba59f93a0>,\n 'glutamatergic neuron': <networkx.classes.graph.Graph at 0x2bba59f9550>,\n 'inhibitory interneuron': <networkx.classes.graph.Graph at 0x2bba59f95e0>,\n 'endothelial cell of vascular tree': <networkx.classes.graph.Graph at 0x2bba59f9340>,\n 'oligodendrocyte precursor cell': <networkx.classes.graph.Graph at 0x2bba59f9670>,\n 'pericyte': <networkx.classes.graph.Graph at 0x2bba59f91f0>}"
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cell_types = ['astrocyte', 'microglial cell', 'oligodendrocyte', 'glutamatergic neuron', 'inhibitory interneuron', 'endothelial cell of vascular tree', 'oligodendrocyte precursor cell', 'pericyte']\n",
    "\n",
    "cell_networks = {cell: nx.read_graphml(f\"CellXGene/cross-dementia/filtered/graphs/{cell}_network.graphml\") for cell in cell_types}\n",
    "cell_networks"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "outputs": [],
   "source": [
    "combined_degs = [\n",
    "    {\"protein_id\": node, \"gene_symbol\": G.nodes[node]['gene_symbol'], \"gene_id\": G.nodes[node]['gene_id'], \"cell_type\": cell_type, \"logfoldchanges\": G.nodes[node]['logfoldchanges']}\n",
    "    for cell_type, G in cell_networks.items()\n",
    "    for node in G.nodes()\n",
    "    if \"logfoldchanges\" in G.nodes[node]\n",
    "]"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "outputs": [
    {
     "data": {
      "text/plain": "     protein_id gene_symbol   gene_id  cell_type  logfoldchanges\n0        P04626       ERBB2    2064.0  astrocyte       -0.287940\n1        Q14517        FAT1    2195.0  astrocyte        0.343325\n2        Q8TCT8      SPPL2A   84888.0  astrocyte       -0.353458\n3        O60290      ZNF862  643641.0  astrocyte        0.419059\n4        P35613         BSG     682.0  astrocyte       -0.386828\n...         ...         ...       ...        ...             ...\n3234     P60484        PTEN    5728.0   pericyte       -0.782102\n3235     P17676       CEBPB    1051.0   pericyte        1.105564\n3236     P49716       CEBPD    1052.0   pericyte        0.708934\n3237     Q09666       AHNAK   79026.0   pericyte        0.989039\n3238     Q7Z6G8      ANKS1B   56899.0   pericyte        0.978241\n\n[3239 rows x 5 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>protein_id</th>\n      <th>gene_symbol</th>\n      <th>gene_id</th>\n      <th>cell_type</th>\n      <th>logfoldchanges</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>P04626</td>\n      <td>ERBB2</td>\n      <td>2064.0</td>\n      <td>astrocyte</td>\n      <td>-0.287940</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Q14517</td>\n      <td>FAT1</td>\n      <td>2195.0</td>\n      <td>astrocyte</td>\n      <td>0.343325</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Q8TCT8</td>\n      <td>SPPL2A</td>\n      <td>84888.0</td>\n      <td>astrocyte</td>\n      <td>-0.353458</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>O60290</td>\n      <td>ZNF862</td>\n      <td>643641.0</td>\n      <td>astrocyte</td>\n      <td>0.419059</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>P35613</td>\n      <td>BSG</td>\n      <td>682.0</td>\n      <td>astrocyte</td>\n      <td>-0.386828</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>3234</th>\n      <td>P60484</td>\n      <td>PTEN</td>\n      <td>5728.0</td>\n      <td>pericyte</td>\n      <td>-0.782102</td>\n    </tr>\n    <tr>\n      <th>3235</th>\n      <td>P17676</td>\n      <td>CEBPB</td>\n      <td>1051.0</td>\n      <td>pericyte</td>\n      <td>1.105564</td>\n    </tr>\n    <tr>\n      <th>3236</th>\n      <td>P49716</td>\n      <td>CEBPD</td>\n      <td>1052.0</td>\n      <td>pericyte</td>\n      <td>0.708934</td>\n    </tr>\n    <tr>\n      <th>3237</th>\n      <td>Q09666</td>\n      <td>AHNAK</td>\n      <td>79026.0</td>\n      <td>pericyte</td>\n      <td>0.989039</td>\n    </tr>\n    <tr>\n      <th>3238</th>\n      <td>Q7Z6G8</td>\n      <td>ANKS1B</td>\n      <td>56899.0</td>\n      <td>pericyte</td>\n      <td>0.978241</td>\n    </tr>\n  </tbody>\n</table>\n<p>3239 rows × 5 columns</p>\n</div>"
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.DataFrame(combined_degs)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "outputs": [
    {
     "data": {
      "text/plain": "     protein_id gene_symbol   gene_id  cell_type  logfoldchanges  \\\n0        P04626       ERBB2    2064.0  astrocyte       -0.287940   \n1        Q14517        FAT1    2195.0  astrocyte        0.343325   \n2        Q8TCT8      SPPL2A   84888.0  astrocyte       -0.353458   \n3        O60290      ZNF862  643641.0  astrocyte        0.419059   \n4        P35613         BSG     682.0  astrocyte       -0.386828   \n...         ...         ...       ...        ...             ...   \n3234     P60484        PTEN    5728.0   pericyte       -0.782102   \n3235     P17676       CEBPB    1051.0   pericyte        1.105564   \n3236     P49716       CEBPD    1052.0   pericyte        0.708934   \n3237     Q09666       AHNAK   79026.0   pericyte        0.989039   \n3238     Q7Z6G8      ANKS1B   56899.0   pericyte        0.978241   \n\n      num_cell_types  \n0                  1  \n1                  2  \n2                  1  \n3                  4  \n4                  3  \n...              ...  \n3234               2  \n3235               4  \n3236               5  \n3237               3  \n3238               4  \n\n[3239 rows x 6 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>protein_id</th>\n      <th>gene_symbol</th>\n      <th>gene_id</th>\n      <th>cell_type</th>\n      <th>logfoldchanges</th>\n      <th>num_cell_types</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>P04626</td>\n      <td>ERBB2</td>\n      <td>2064.0</td>\n      <td>astrocyte</td>\n      <td>-0.287940</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Q14517</td>\n      <td>FAT1</td>\n      <td>2195.0</td>\n      <td>astrocyte</td>\n      <td>0.343325</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Q8TCT8</td>\n      <td>SPPL2A</td>\n      <td>84888.0</td>\n      <td>astrocyte</td>\n      <td>-0.353458</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>O60290</td>\n      <td>ZNF862</td>\n      <td>643641.0</td>\n      <td>astrocyte</td>\n      <td>0.419059</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>P35613</td>\n      <td>BSG</td>\n      <td>682.0</td>\n      <td>astrocyte</td>\n      <td>-0.386828</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>3234</th>\n      <td>P60484</td>\n      <td>PTEN</td>\n      <td>5728.0</td>\n      <td>pericyte</td>\n      <td>-0.782102</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>3235</th>\n      <td>P17676</td>\n      <td>CEBPB</td>\n      <td>1051.0</td>\n      <td>pericyte</td>\n      <td>1.105564</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>3236</th>\n      <td>P49716</td>\n      <td>CEBPD</td>\n      <td>1052.0</td>\n      <td>pericyte</td>\n      <td>0.708934</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>3237</th>\n      <td>Q09666</td>\n      <td>AHNAK</td>\n      <td>79026.0</td>\n      <td>pericyte</td>\n      <td>0.989039</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>3238</th>\n      <td>Q7Z6G8</td>\n      <td>ANKS1B</td>\n      <td>56899.0</td>\n      <td>pericyte</td>\n      <td>0.978241</td>\n      <td>4</td>\n    </tr>\n  </tbody>\n</table>\n<p>3239 rows × 6 columns</p>\n</div>"
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "count_cells = df.groupby(\"protein_id\")[\"cell_type\"].nunique().reset_index()\n",
    "count_cells.columns = [\"protein_id\", \"num_cell_types\"]\n",
    "\n",
    "df2 = df.merge(count_cells, on=\"protein_id\")\n",
    "df2"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "outputs": [
    {
     "data": {
      "text/plain": "num_cell_types\n2    932\n3    690\n1    610\n4    500\n5    240\n6    114\n7    105\n8     48\nName: count, dtype: int64"
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df2['num_cell_types'].value_counts()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 600x600 with 2 Axes>",
      "image/png": "[encoded data, 44388 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Heatmap con valores de expresión agrupados por proteinas y anotación por el gen que codifica dicha proteína.\n",
    "\n",
    "df_filtered_proteins = df2[df2[\"num_cell_types\"] == 8]\n",
    "\n",
    "# Crear un diccionario de mapeo de protein_id a gene_symbol\n",
    "gene_symbol_mapping = df_filtered_proteins.set_index(\"protein_id\")[\"gene_symbol\"].drop_duplicates()\n",
    "\n",
    "# Crear la tabla pivote\n",
    "df_pivot = df_filtered_proteins.pivot_table(index=\"protein_id\", columns=\"cell_type\", values=\"logfoldchanges\")\n",
    "\n",
    "sns.set_context(\"paper\")\n",
    "sns.set_style(\"white\")\n",
    "\n",
    "# Crear la figura y el heatmap\n",
    "fig, ax = plt.subplots(figsize=(6,6))\n",
    "sns.heatmap(df_pivot, cmap=\"coolwarm\", linewidths=0.5, fmt=\".2f\", linecolor='grey', cbar=True, square=False, ax=ax)\n",
    "\n",
    "# Ajustar título y etiquetas\n",
    "title = \"LFC heatmap for proteins in the 90th percentile across cell types\"\n",
    "plt.title(title, fontsize=10)\n",
    "plt.xlabel(\"Cell type\", fontsize=8)\n",
    "plt.ylabel(\"Gene Symbol\", fontsize=8)\n",
    "plt.xticks(rotation=45, ha='right', fontsize=8)\n",
    "ax.set_yticklabels(gene_symbol_mapping.loc[df_pivot.index].values, rotation=0, fontsize=8)\n",
    "plt.tight_layout()\n",
    "\n",
    "# plt.savefig('CellXGene/cross-dementia/plots/commonproteins.svg', format = 'svg', dpi=1200)\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "#### Combination of 6.4 and 6.5 plots"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 445,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\1253390478.py:9: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  lfc_filtered[\"max_abs_LFC\"] = lfc_filtered[\"logfoldchanges\"].abs()\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\1253390478.py:10: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  lfc_filtered['cell_type'] = lfc_filtered[\"cell_type\"].replace(\"endothelial cell of vascular tree\", \"endothelial cell\")\n"
     ]
    },
    {
     "data": {
      "text/plain": "     protein_id gene_symbol  logfoldchanges        cell_type  max_abs_LFC\n14       P43490       NAMPT       -0.900505        astrocyte     0.900505\n22       P06703      S100A6        1.067540        astrocyte     1.067540\n50       Q2I0M5       RSPO4       -1.032063        astrocyte     1.032063\n118      O60603        TLR2       -1.532612        astrocyte     1.532612\n133      P17275        JUNB       -0.300338        astrocyte     0.300338\n...         ...         ...             ...              ...          ...\n3194     P04792       HSPB1        2.069515  oligodendrocyte     2.069515\n3223     P04792       HSPB1        1.884719         pericyte     1.884719\n3227     Q92598       HSPH1        1.676103         pericyte     1.676103\n3230     P0DMV8      HSPA1B        1.975146         pericyte     1.975146\n3232     P02511       CRYAB        1.525713         pericyte     1.525713\n\n[123 rows x 5 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>protein_id</th>\n      <th>gene_symbol</th>\n      <th>logfoldchanges</th>\n      <th>cell_type</th>\n      <th>max_abs_LFC</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>14</th>\n      <td>P43490</td>\n      <td>NAMPT</td>\n      <td>-0.900505</td>\n      <td>astrocyte</td>\n      <td>0.900505</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>P06703</td>\n      <td>S100A6</td>\n      <td>1.067540</td>\n      <td>astrocyte</td>\n      <td>1.067540</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>Q2I0M5</td>\n      <td>RSPO4</td>\n      <td>-1.032063</td>\n      <td>astrocyte</td>\n      <td>1.032063</td>\n    </tr>\n    <tr>\n      <th>118</th>\n      <td>O60603</td>\n      <td>TLR2</td>\n      <td>-1.532612</td>\n      <td>astrocyte</td>\n      <td>1.532612</td>\n    </tr>\n    <tr>\n      <th>133</th>\n      <td>P17275</td>\n      <td>JUNB</td>\n      <td>-0.300338</td>\n      <td>astrocyte</td>\n      <td>0.300338</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>3194</th>\n      <td>P04792</td>\n      <td>HSPB1</td>\n      <td>2.069515</td>\n      <td>oligodendrocyte</td>\n      <td>2.069515</td>\n    </tr>\n    <tr>\n      <th>3223</th>\n      <td>P04792</td>\n      <td>HSPB1</td>\n      <td>1.884719</td>\n      <td>pericyte</td>\n      <td>1.884719</td>\n    </tr>\n    <tr>\n      <th>3227</th>\n      <td>Q92598</td>\n      <td>HSPH1</td>\n      <td>1.676103</td>\n      <td>pericyte</td>\n      <td>1.676103</td>\n    </tr>\n    <tr>\n      <th>3230</th>\n      <td>P0DMV8</td>\n      <td>HSPA1B</td>\n      <td>1.975146</td>\n      <td>pericyte</td>\n      <td>1.975146</td>\n    </tr>\n    <tr>\n      <th>3232</th>\n      <td>P02511</td>\n      <td>CRYAB</td>\n      <td>1.525713</td>\n      <td>pericyte</td>\n      <td>1.525713</td>\n    </tr>\n  </tbody>\n</table>\n<p>123 rows × 5 columns</p>\n</div>"
     },
     "execution_count": 445,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "##  HEATMAP 1: Top 20 más ↑ y ↓ logfoldchange\n",
    "\n",
    "top_high = lfc_df.sort_values(by=\"logfoldchanges\", ascending=False)[\"protein_id\"].drop_duplicates().head(20)\n",
    "top_low = lfc_df.sort_values(by=\"logfoldchanges\", ascending=True)[\"protein_id\"].drop_duplicates().head(20)\n",
    "top_proteins = pd.concat([top_high, top_low])\n",
    "\n",
    "lfc_filtered = lfc_df[lfc_df[\"protein_id\"].isin(top_proteins)]\n",
    "\n",
    "lfc_filtered[\"max_abs_LFC\"] = lfc_filtered[\"logfoldchanges\"].abs()\n",
    "lfc_filtered['cell_type'] = lfc_filtered[\"cell_type\"].replace(\"endothelial cell of vascular tree\", \"endothelial cell\")\n",
    "lfc_filtered"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 448,
   "outputs": [
    {
     "data": {
      "text/plain": "     protein_id gene_symbol   gene_id  cell_type  logfoldchanges  \\\n0        P04626       ERBB2    2064.0  astrocyte       -0.287940   \n1        Q14517        FAT1    2195.0  astrocyte        0.343325   \n2        Q8TCT8      SPPL2A   84888.0  astrocyte       -0.353458   \n3        O60290      ZNF862  643641.0  astrocyte        0.419059   \n4        P35613         BSG     682.0  astrocyte       -0.386828   \n...         ...         ...       ...        ...             ...   \n3234     P60484        PTEN    5728.0   pericyte       -0.782102   \n3235     P17676       CEBPB    1051.0   pericyte        1.105564   \n3236     P49716       CEBPD    1052.0   pericyte        0.708934   \n3237     Q09666       AHNAK   79026.0   pericyte        0.989039   \n3238     Q7Z6G8      ANKS1B   56899.0   pericyte        0.978241   \n\n      num_cell_types  \n0                  1  \n1                  2  \n2                  1  \n3                  4  \n4                  3  \n...              ...  \n3234               2  \n3235               4  \n3236               5  \n3237               3  \n3238               4  \n\n[3239 rows x 6 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>protein_id</th>\n      <th>gene_symbol</th>\n      <th>gene_id</th>\n      <th>cell_type</th>\n      <th>logfoldchanges</th>\n      <th>num_cell_types</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>P04626</td>\n      <td>ERBB2</td>\n      <td>2064.0</td>\n      <td>astrocyte</td>\n      <td>-0.287940</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Q14517</td>\n      <td>FAT1</td>\n      <td>2195.0</td>\n      <td>astrocyte</td>\n      <td>0.343325</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Q8TCT8</td>\n      <td>SPPL2A</td>\n      <td>84888.0</td>\n      <td>astrocyte</td>\n      <td>-0.353458</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>O60290</td>\n      <td>ZNF862</td>\n      <td>643641.0</td>\n      <td>astrocyte</td>\n      <td>0.419059</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>P35613</td>\n      <td>BSG</td>\n      <td>682.0</td>\n      <td>astrocyte</td>\n      <td>-0.386828</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>3234</th>\n      <td>P60484</td>\n      <td>PTEN</td>\n      <td>5728.0</td>\n      <td>pericyte</td>\n      <td>-0.782102</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>3235</th>\n      <td>P17676</td>\n      <td>CEBPB</td>\n      <td>1051.0</td>\n      <td>pericyte</td>\n      <td>1.105564</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>3236</th>\n      <td>P49716</td>\n      <td>CEBPD</td>\n      <td>1052.0</td>\n      <td>pericyte</td>\n      <td>0.708934</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>3237</th>\n      <td>Q09666</td>\n      <td>AHNAK</td>\n      <td>79026.0</td>\n      <td>pericyte</td>\n      <td>0.989039</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>3238</th>\n      <td>Q7Z6G8</td>\n      <td>ANKS1B</td>\n      <td>56899.0</td>\n      <td>pericyte</td>\n      <td>0.978241</td>\n      <td>4</td>\n    </tr>\n  </tbody>\n</table>\n<p>3239 rows × 6 columns</p>\n</div>"
     },
     "execution_count": 448,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## HEATMAP 2: Proteínas con expresión en 8 tipos celulares\n",
    "\n",
    "cell_types = ['astrocyte', 'microglial cell', 'oligodendrocyte', 'glutamatergic neuron', 'inhibitory interneuron',\n",
    "              'endothelial cell of vascular tree', 'oligodendrocyte precursor cell', 'pericyte']\n",
    "\n",
    "cell_networks = {cell: nx.read_graphml(f\"CellXGene/cross-dementia/filtered/graphs/{cell}_network.graphml\") for cell in\n",
    "                 cell_types}\n",
    "cell_networks\n",
    "combined_degs = [\n",
    "    {\"protein_id\": node, \"gene_symbol\": G.nodes[node]['gene_symbol'], \"gene_id\": G.nodes[node]['gene_id'],\n",
    "     \"cell_type\": cell_type, \"logfoldchanges\": G.nodes[node]['logfoldchanges']}\n",
    "    for cell_type, G in cell_networks.items()\n",
    "    for node in G.nodes()\n",
    "    if \"logfoldchanges\" in G.nodes[node]\n",
    "]\n",
    "df = pd.DataFrame(combined_degs)\n",
    "\n",
    "count_cells = df.groupby(\"protein_id\")[\"cell_type\"].nunique().reset_index()\n",
    "count_cells.columns = [\"protein_id\", \"num_cell_types\"]\n",
    "\n",
    "df2 = df.merge(count_cells, on=\"protein_id\")\n",
    "df2['cell_type'] = df2[\"cell_type\"].replace(\"endothelial cell of vascular tree\", \"endothelial cell\")\n",
    "df2"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 671,
   "outputs": [],
   "source": [
    "titles = ['Glutamatergic neuron', 'Inhibitory interneuron', 'Oligodendrocyte', 'Astrocyte', 'Microglial cell', 'OPC', 'Endothelial cell', 'Pericyte']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 680,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 1400x1000 with 3 Axes>",
      "image/png": "[encoded data, 265076 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# 🔹\n",
    "# top_high = lfc_df.sort_values(by=\"logfoldchanges\", ascending=False)[\"protein_id\"].drop_duplicates().head(20)\n",
    "# top_low = lfc_df.sort_values(by=\"logfoldchanges\", ascending=True)[\"protein_id\"].drop_duplicates().head(20)\n",
    "#\n",
    "# top_proteins = pd.concat([top_high, top_low])\n",
    "#\n",
    "# lfc_filtered = lfc_df[lfc_df[\"protein_id\"].isin(top_proteins)].copy()\n",
    "\n",
    "# lfc_filtered = lfc_filtered[\"cell_type\"].replace(\"endothelial cell of vascular tree\", \"endothelial cell\")\n",
    "\n",
    "heatmap_df = lfc_filtered.pivot(index=\"protein_id\", columns=\"cell_type\", values=\"logfoldchanges\")\n",
    "\n",
    "# Agregar anotación de gene_symbol\n",
    "gene_symbols = lfc_filtered.set_index(\"protein_id\")[\"gene_symbol\"].to_dict()\n",
    "heatmap_df.index = [f\"{gene_symbols.get(x, x)} ({x})\" for x in heatmap_df.index]\n",
    "\n",
    "heatmap_df[\"max_lfc\"] = heatmap_df.max(axis=1)\n",
    "heatmap_df = heatmap_df.sort_values(by=\"max_lfc\", ascending=False).drop(columns=[\"max_lfc\"])\n",
    "\n",
    "# 🔹 Espacio en blanco entre los genes más up y down regulados\n",
    "half = len(heatmap_df) // 2\n",
    "gap = pd.DataFrame(np.nan, index=[\"\"], columns=heatmap_df.columns)  # Dos filas vacías como separador\n",
    "heatmap_df = pd.concat([heatmap_df.iloc[:half], gap, heatmap_df.iloc[half:]])\n",
    "\n",
    "# 🔹 HEATMAP 2: Proteínas con expresión en 8 tipos celulares\n",
    "df_filtered_proteins = df2[df2[\"num_cell_types\"] == 8]\n",
    "gene_symbol_mapping = df_filtered_proteins.set_index(\"protein_id\")[\"gene_symbol\"].drop_duplicates()\n",
    "df_pivot = df_filtered_proteins.pivot_table(index=\"protein_id\", columns=\"cell_type\", values=\"logfoldchanges\")\n",
    "\n",
    "# Agregar anotación de gene_symbol\n",
    "# df_pivot.index = [f\"{gene_symbol_mapping.get(x, x)} ({x})\" for x in df_pivot.index]\n",
    "# Agregar anotación de gene_symbol con salto de línea\n",
    "df_pivot.index = [f\"{gene_symbol_mapping.get(x, x)}\\n({x})\" for x in df_pivot.index]\n",
    "\n",
    "df_pivot[\"max_lfc\"] = df_pivot.max(axis=1)\n",
    "df_pivot = df_pivot.sort_values(by=\"max_lfc\", ascending=False).drop(columns=[\"max_lfc\"])\n",
    "\n",
    "# Definir el orden deseado de las columnas\n",
    "order = ['glutamatergic neuron', 'inhibitory interneuron',\n",
    "         'oligodendrocyte', 'astrocyte', 'microglial cell',\n",
    "         'oligodendrocyte precursor cell', 'endothelial cell', 'pericyte']\n",
    "\n",
    "# Reordenar las columnas de los DataFrame antes de graficar\n",
    "heatmap_df = heatmap_df[order]\n",
    "df_pivot = df_pivot[order]\n",
    "\n",
    "# 🔹 Definir escala de colores compartida\n",
    "vmin = min(heatmap_df.min().min(), df_pivot.min().min())\n",
    "vmax = max(heatmap_df.max().max(), df_pivot.max().max())\n",
    "\n",
    "# 🔹 Configurar estilo y figura con 2 subplots\n",
    "sns.set_context(\"paper\")\n",
    "sns.set_style(\"white\")\n",
    "\n",
    "fig, axes = plt.subplots(1, 2, figsize=(14, 10), gridspec_kw={'width_ratios': [1, 1]})\n",
    "\n",
    "# Heatmap 1: Top 20 ↑↓ logfoldchange\n",
    "sns.heatmap(\n",
    "    heatmap_df, cmap=\"coolwarm\", center=0, linewidths=0.5, linecolor=\"grey\",\n",
    "    vmin=vmin, vmax=vmax, annot=False, ax=axes[0], cbar=False\n",
    ")\n",
    "axes[0].add_patch(Rectangle((0, 20), 8, 1, fill=True, facecolor= 'white', edgecolor='gray', lw=1))\n",
    "axes[0].set_title(\"Proteins with highest and lowest LFC values by cell type\", fontsize=18)\n",
    "axes[0].set_xlabel(\"\")\n",
    "axes[0].set_ylabel(\"Gene Symbol (Protein Accession Number)\", fontsize=15)\n",
    "axes[0].set_xticklabels(titles, rotation=45, ha='right', fontsize=15)\n",
    "axes[0].set_yticklabels(axes[0].get_yticklabels(), fontsize=14)\n",
    "\n",
    "# Heatmap 2: High variability proteins\n",
    "sns.heatmap(\n",
    "    df_pivot, cmap=\"coolwarm\", linewidths=0.5, linecolor='grey',\n",
    "    vmin=vmin, vmax=vmax, annot=False, ax=axes[1]\n",
    ")\n",
    "axes[1].set_title(\"Differentially expressed genes in all cell types\", fontsize=18)\n",
    "axes[1].set_xlabel(\"\")\n",
    "axes[1].set_ylabel(\"\")  # Evita duplicar etiqueta\n",
    "axes[1].set_xticklabels(titles, rotation=45, ha='right', fontsize=15)\n",
    "axes[1].set_yticklabels(axes[1].get_yticklabels(), rotation = 0, fontsize=14)\n",
    "\n",
    "# Ajustar distribución y guardar\n",
    "plt.tight_layout()\n",
    "plt.savefig('CellXGene/cross-dementia/plots/combined_heatmaps.pdf', format='pdf', dpi=1200)\n",
    "# plt.savefig('CellXGene/cross-dementia/plots/combined_heatmaps_pdf.svg', format='svg', dpi=1200)\n",
    "plt.show()\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 8. Network metrics analysis\n",
    "\n",
    "Calculation of degrees, betweenness and closeness centralities and clustering coefficient for each of the cell type-specific DEGs inside the main interactome.\n",
    "\n",
    "Considering the entire PPI, I want to know how the cell type-specific DEGs are located within the interactome. For the DEGs in each cell type, I draw the metrics (from the subnetworks I only need the genes that are in them) and plot the distributions that follow these metrics, comparing them with the distribution that the Alzheimer's module follows.\n",
    "\n",
    "### 8.1. Alzheimer module calculation"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "dis_gen = pd.read_csv('CellXGene/dis_gen.tsv', sep='\\t')\n",
    "gen_pro = pd.read_csv('CellXGene/gen_pro.tsv', sep='\\t')\n",
    "pro_pro = pd.read_csv('CellXGene/pro_pro.tsv', sep='\\t')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "G_ppi = nx.from_pandas_edgelist(pro_pro, 'prA', 'prB')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "def get_disease_module(disease, dis_gen, gen_pro, pro_pro, PPI):\n",
    "    genes = functions_proximity.genes_dis(disease, dis_gen)\n",
    "    prots = functions_proximity.pro_gen_dict(genes, gen_pro)\n",
    "    prots_interactome = functions_proximity.gen_pro_PPI(prots, pro_pro)\n",
    "    SG = PPI.subgraph(prots_interactome)\n",
    "    lcc = functions_proximity.lcc(SG)\n",
    "\n",
    "    return lcc"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "lcc_alz = get_disease_module('C0002395', dis_gen, gen_pro, pro_pro, G_ppi)\n",
    "len(lcc_alz)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 8.2. Metrics calculation for all the nodes in the interactome"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 605,
   "outputs": [],
   "source": [
    "def calculate_metrics(graph):\n",
    "    \"\"\"\n",
    "    Calcula métricas de red a nivel de nodo. Devuelve un DataFrame con las métricas.\n",
    "    \"\"\"\n",
    "    # Betweenness centrality\n",
    "    betweenness = nx.betweenness_centrality(graph)\n",
    "\n",
    "    # Closeness centrality\n",
    "    closeness = nx.closeness_centrality(graph)\n",
    "\n",
    "    # Clustering coefficient\n",
    "    clustering = nx.clustering(graph)\n",
    "\n",
    "    # Identificar hubs (proteínas con mayor grado)\n",
    "    degree = dict(graph.degree())\n",
    "    degree_values = list(degree.values())\n",
    "    percentile_90 = np.percentile(degree_values, 90)\n",
    "    is_hub = {node: degree[node] >= percentile_90 for node in degree}\n",
    "\n",
    "    return betweenness, closeness, clustering, degree, is_hub"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Calculo de las metricas de red para cada una de las proteinas de la PPI\n",
    "betweenness, closeness, clustering, degree, is_hub = calculate_metrics(G_ppi)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Convert metrics of whole interactome to a dataframe\n",
    "df = pd.DataFrame({\n",
    "    'protein_id': list(degree.keys()),\n",
    "    'degree': list(degree.values()),\n",
    "    'betweenness_centrality': list(betweenness.values()),\n",
    "    'closeness_centrality': list(closeness.values()),\n",
    "    'is_hub': list(is_hub.values())\n",
    "})"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "df['is_in_LCC'] = df['protein_id'].isin(lcc_alz)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "df.to_csv('CellXGene/cross-dementia/filtered/results/G_ppi_analysis.csv', index = False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 8.3. Metrics calculation for the DEGs nodes for each cell type"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "cell_types = ['astrocyte', 'microglial cell', 'oligodendrocyte', 'glutamatergic neuron', 'inhibitory interneuron', 'endothelial cell of vascular tree', 'oligodendrocyte precursor cell', 'pericyte']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "results_list = []\n",
    "\n",
    "for cell_type in tqdm(cell_types, desc=\"Processing cell types...\"):\n",
    "\n",
    "    graph = nx.read_graphml(f'CellXGene/cross-dementia/filtered/graphs/{cell_type}_network.graphml')\n",
    "\n",
    "    ppi_proteins = set(graph.nodes())\n",
    "    print(ppi_proteins)\n",
    "\n",
    "    # Añadir las métricas al DataFrame\n",
    "    for protein in ppi_proteins:\n",
    "        protein_id = protein\n",
    "        gene_id = graph.nodes[protein].get(\"gene_id\", \"NA\")\n",
    "        gene_symbol = graph.nodes[protein].get(\"gene_symbol\", \"NA\")\n",
    "        logfoldchanges = graph.nodes[protein].get(\"logfoldchanges\", \"NA\")\n",
    "        pvals = graph.nodes[protein].get(\"pval\", \"NA\")\n",
    "        pvals_adj = graph.nodes[protein].get(\"pval_adj\", \"NA\")\n",
    "\n",
    "        # Obtener las métricas para la proteína\n",
    "        betweenness_val = betweenness.get(protein_id, None)\n",
    "        closeness_val = closeness.get(protein_id, None)\n",
    "        clustering_val = clustering.get(protein_id, None)\n",
    "        degree_val = degree.get(protein_id, None)\n",
    "        is_hub_val = is_hub.get(protein_id, False)\n",
    "\n",
    "        # Añadir la fila al DataFrame de resultados\n",
    "        result_row = {\n",
    "            \"protein_id\": protein_id,\n",
    "            \"gene_id\": gene_id,\n",
    "            \"gene_symbol\": gene_symbol,\n",
    "            \"cell_type\": cell_type,\n",
    "            \"logfoldchanges\": logfoldchanges,\n",
    "            \"pvals\": pvals,\n",
    "            \"pvals_adj\": pvals_adj,\n",
    "            \"degree\": degree_val,\n",
    "            \"betweenness_centrality\": betweenness_val,\n",
    "            \"closeness_centrality\": closeness_val,\n",
    "            \"clustering_coefficient\": clustering_val,\n",
    "            \"is_hub\": is_hub_val\n",
    "        }\n",
    "\n",
    "        results_list.append(result_row)\n",
    "\n",
    "results_df = pd.DataFrame(results_list)\n",
    "\n",
    "results_df.to_csv('CellXGene/cross-dementia/filtered/results/network_analysis.csv', index=False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 8.4. Analysis of the metrics distributions across cell types"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 386,
   "outputs": [],
   "source": [
    "cell_data = pd.read_csv('CellXGene/cross-dementia/filtered/results/network_analysis.csv')\n",
    "module_data = pd.read_csv('CellXGene/cross-dementia/filtered/results/G_ppi_analysis.csv')\n",
    "\n",
    "module_data_lcc = module_data[module_data['is_in_LCC'] == True]"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 575,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\602881201.py:1: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  module_data_lcc[\"dataset\"] = \"General module for AD\"\n"
     ]
    },
    {
     "data": {
      "text/plain": "      protein_id  degree  betweenness_centrality  closeness_centrality  \\\n0     A0A087WXM9       8                0.000003              0.305735   \n2         P05783      91                0.000429              0.367223   \n4         P08670     266                0.003726              0.398942   \n6         P53350     221                0.001902              0.381054   \n32        Q96CV9      92                0.000621              0.362136   \n...          ...     ...                     ...                   ...   \n3234      P17676      27                0.000056              0.346096   \n3235      P07900     237                0.001698              0.398471   \n3236      P13693     124                0.000313              0.374662   \n3237      P0DMV8      63                0.000533              0.359315   \n3238      P08238     553                0.013363              0.420794   \n\n      is_hub is_in_LCC                dataset  gene_id gene_symbol cell_type  \\\n0      False      True  General module for AD      NaN         NaN       NaN   \n2       True      True  General module for AD      NaN         NaN       NaN   \n4       True      True  General module for AD      NaN         NaN       NaN   \n6       True      True  General module for AD      NaN         NaN       NaN   \n32      True      True  General module for AD      NaN         NaN       NaN   \n...      ...       ...                    ...      ...         ...       ...   \n3234   False       NaN               pericyte   1051.0       CEBPB  pericyte   \n3235    True       NaN               pericyte   3320.0    HSP90AA1  pericyte   \n3236    True       NaN               pericyte   7178.0        TPT1  pericyte   \n3237   False       NaN               pericyte   3304.0      HSPA1B  pericyte   \n3238    True       NaN               pericyte   3326.0    HSP90AB1  pericyte   \n\n      logfoldchanges         pvals     pvals_adj  clustering_coefficient  \n0                NaN           NaN           NaN                     NaN  \n2                NaN           NaN           NaN                     NaN  \n4                NaN           NaN           NaN                     NaN  \n6                NaN           NaN           NaN                     NaN  \n32               NaN           NaN           NaN                     NaN  \n...              ...           ...           ...                     ...  \n3234        1.105564  9.147368e-06  5.491340e-03                0.150000  \n3235        1.110109  2.761193e-13  1.112958e-09                0.061975  \n3236        0.802365  1.618387e-04  4.390652e-02                0.056517  \n3237        1.975146  1.293792e-07  1.738302e-04                0.045059  \n3238        0.861556  2.566908e-06  2.336300e-03                0.020023  \n\n[5936 rows x 14 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>protein_id</th>\n      <th>degree</th>\n      <th>betweenness_centrality</th>\n      <th>closeness_centrality</th>\n      <th>is_hub</th>\n      <th>is_in_LCC</th>\n      <th>dataset</th>\n      <th>gene_id</th>\n      <th>gene_symbol</th>\n      <th>cell_type</th>\n      <th>logfoldchanges</th>\n      <th>pvals</th>\n      <th>pvals_adj</th>\n      <th>clustering_coefficient</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>A0A087WXM9</td>\n      <td>8</td>\n      <td>0.000003</td>\n      <td>0.305735</td>\n      <td>False</td>\n      <td>True</td>\n      <td>General module for AD</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>P05783</td>\n      <td>91</td>\n      <td>0.000429</td>\n      <td>0.367223</td>\n      <td>True</td>\n      <td>True</td>\n      <td>General module for AD</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>P08670</td>\n      <td>266</td>\n      <td>0.003726</td>\n      <td>0.398942</td>\n      <td>True</td>\n      <td>True</td>\n      <td>General module for AD</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>P53350</td>\n      <td>221</td>\n      <td>0.001902</td>\n      <td>0.381054</td>\n      <td>True</td>\n      <td>True</td>\n      <td>General module for AD</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>Q96CV9</td>\n      <td>92</td>\n      <td>0.000621</td>\n      <td>0.362136</td>\n      <td>True</td>\n      <td>True</td>\n      <td>General module for AD</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>3234</th>\n      <td>P17676</td>\n      <td>27</td>\n      <td>0.000056</td>\n      <td>0.346096</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>pericyte</td>\n      <td>1051.0</td>\n      <td>CEBPB</td>\n      <td>pericyte</td>\n      <td>1.105564</td>\n      <td>9.147368e-06</td>\n      <td>5.491340e-03</td>\n      <td>0.150000</td>\n    </tr>\n    <tr>\n      <th>3235</th>\n      <td>P07900</td>\n      <td>237</td>\n      <td>0.001698</td>\n      <td>0.398471</td>\n      <td>True</td>\n      <td>NaN</td>\n      <td>pericyte</td>\n      <td>3320.0</td>\n      <td>HSP90AA1</td>\n      <td>pericyte</td>\n      <td>1.110109</td>\n      <td>2.761193e-13</td>\n      <td>1.112958e-09</td>\n      <td>0.061975</td>\n    </tr>\n    <tr>\n      <th>3236</th>\n      <td>P13693</td>\n      <td>124</td>\n      <td>0.000313</td>\n      <td>0.374662</td>\n      <td>True</td>\n      <td>NaN</td>\n      <td>pericyte</td>\n      <td>7178.0</td>\n      <td>TPT1</td>\n      <td>pericyte</td>\n      <td>0.802365</td>\n      <td>1.618387e-04</td>\n      <td>4.390652e-02</td>\n      <td>0.056517</td>\n    </tr>\n    <tr>\n      <th>3237</th>\n      <td>P0DMV8</td>\n      <td>63</td>\n      <td>0.000533</td>\n      <td>0.359315</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>pericyte</td>\n      <td>3304.0</td>\n      <td>HSPA1B</td>\n      <td>pericyte</td>\n      <td>1.975146</td>\n      <td>1.293792e-07</td>\n      <td>1.738302e-04</td>\n      <td>0.045059</td>\n    </tr>\n    <tr>\n      <th>3238</th>\n      <td>P08238</td>\n      <td>553</td>\n      <td>0.013363</td>\n      <td>0.420794</td>\n      <td>True</td>\n      <td>NaN</td>\n      <td>pericyte</td>\n      <td>3326.0</td>\n      <td>HSP90AB1</td>\n      <td>pericyte</td>\n      <td>0.861556</td>\n      <td>2.566908e-06</td>\n      <td>2.336300e-03</td>\n      <td>0.020023</td>\n    </tr>\n  </tbody>\n</table>\n<p>5936 rows × 14 columns</p>\n</div>"
     },
     "execution_count": 575,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "module_data_lcc[\"dataset\"] = \"General module for AD\"\n",
    "cell_data[\"dataset\"] = cell_data[\"cell_type\"]\n",
    "\n",
    "# Reemplazar el nombre de \"endothelial cell of vascular tree\" por \"endothelial cell\"\n",
    "combined_data = pd.concat([module_data_lcc, cell_data])\n",
    "# combined_data[\"dataset\"] = combined_data[\"dataset\"].replace(\"endothelial cell of vascular tree\", \"Endothelial cell\")\n",
    "# combined_data[\"dataset\"] = combined_data[\"dataset\"].replace(\"oligodendrocyte precursor cell\", \"OPC\")\n",
    "# combined_data[\"dataset\"] = combined_data[\"dataset\"].replace(\"astrocyte\", \"Astrocyte\")\n",
    "combined_data"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 543,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 640x480 with 1 Axes>",
      "image/png": "[encoded data, 30468 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sns.boxplot(data=combined_data, x=\"dataset\", y=\"degree\")\n",
    "\n",
    "plt.yscale('log')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 655,
   "outputs": [],
   "source": [
    "titles = ['General module for AD', 'Glutamatergic neuron', 'Inhibitory interneuron', 'Oligodendrocyte', 'Astrocyte', 'Microglial cell', 'OPC', 'Endothelial cell', 'Pericyte']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 656,
   "outputs": [
    {
     "data": {
      "text/plain": "10"
     },
     "execution_count": 656,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "max(10, len(ordered_datasets) * 0.5)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 658,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\2142562447.py:2: FutureWarning: The default of observed=False is deprecated and will be changed to True in a future version of pandas. Pass observed=False to retain current behavior or observed=True to adopt the future default and silence this warning.\n",
      "  subset_sizes = combined_data.groupby(\"dataset\")[\"protein_id\"].nunique()\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\2142562447.py:18: FutureWarning: \n",
      "\n",
      "Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0. Assign the `x` variable to `hue` and set `legend=False` for the same effect.\n",
      "\n",
      "  sns.boxplot(data=combined_data, x=\"dataset\", y=\"degree\", ax=ax, palette=palette, order=ordered_datasets,dodge=False)\n",
      "C:\\Users\\Andrea\\AppData\\Local\\Temp\\ipykernel_21772\\2142562447.py:25: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.\n",
      "  ax.set_xticklabels([f\"{titles[i]}\\nn = {subset_sizes[dataset]}\" for i, dataset in enumerate(ordered_datasets)],\n"
     ]
    },
    {
     "data": {
      "text/plain": "<Figure size 900x500 with 1 Axes>",
      "image/png": "[encoded data, 79788 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Calcular el tamaño de cada subset\n",
    "subset_sizes = combined_data.groupby(\"dataset\")[\"protein_id\"].nunique()\n",
    "\n",
    "# Generar una paleta de colores\n",
    "ordered_datasets = subset_sizes.sort_values(ascending=False).index\n",
    "combined_data[\"dataset\"] = pd.Categorical(combined_data[\"dataset\"], categories=ordered_datasets, ordered=True)\n",
    "palette = {dataset: '#79C4FF' for dataset in ordered_datasets}\n",
    "\n",
    "# Asignar rojo al \"Module\"\n",
    "palette[\"General module for AD\"] = \"#D3D3D3\"\n",
    "\n",
    "# fig, ax = plt.subplots(figsize=(max(10, len(ordered_datasets) * 0.5), 5))\n",
    "fig, ax = plt.subplots(figsize=(9, 5))\n",
    "\n",
    "sns.set_context(\"paper\")\n",
    "sns.set_style(\"whitegrid\")\n",
    "\n",
    "sns.boxplot(data=combined_data, x=\"dataset\", y=\"degree\", ax=ax, palette=palette, order=ordered_datasets,dodge=False)\n",
    "\n",
    "ax.tick_params(axis='both', which='both', bottom=True, left=True)\n",
    "\n",
    "plt.title('Degree distribution for the Alzheimer disease module and each cell type', fontsize=16)\n",
    "plt.xlabel('')\n",
    "# ax.set_xticklabels(titles, fontsize=9)\n",
    "ax.set_xticklabels([f\"{titles[i]}\\nn = {subset_sizes[dataset]}\" for i, dataset in enumerate(ordered_datasets)],\n",
    "                   rotation=45, ha=\"center\", fontsize=12)\n",
    "\n",
    "# plt.xticks(rotation=45)\n",
    "plt.yticks(fontsize=12)\n",
    "plt.yscale('log')\n",
    "plt.ylabel('log(Degree)', fontsize=12)\n",
    "sns.despine()\n",
    "# Añadir leyenda y mostrar la gráfica\n",
    "plt.tight_layout()\n",
    "plt.savefig('CellXGene/cross-dementia/plots/degree_boxplot.pdf', format='pdf', dpi=1200)\n",
    "# plt.savefig('CellXGene/cross-dementia/plots/degree_boxplot.svg', format='svg', dpi=1200)\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 595,
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "Figure.set() got an unexpected keyword argument 'bottom'",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mAttributeError\u001B[0m                            Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[595], line 1\u001B[0m\n\u001B[1;32m----> 1\u001B[0m fig, ax \u001B[38;5;241m=\u001B[39m \u001B[43mplt\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43msubplots\u001B[49m\u001B[43m(\u001B[49m\u001B[43mfigsize\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43m(\u001B[49m\u001B[38;5;241;43m13\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;241;43m6\u001B[39;49m\u001B[43m)\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mbottom\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[38;5;241;43m0.25\u001B[39;49m\u001B[43m)\u001B[49m\n\u001B[0;32m      3\u001B[0m sns\u001B[38;5;241m.\u001B[39mset_context(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mpaper\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[0;32m      4\u001B[0m sns\u001B[38;5;241m.\u001B[39mset_style(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mwhitegrid\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\pyplot.py:1759\u001B[0m, in \u001B[0;36msubplots\u001B[1;34m(nrows, ncols, sharex, sharey, squeeze, width_ratios, height_ratios, subplot_kw, gridspec_kw, **fig_kw)\u001B[0m\n\u001B[0;32m   1604\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21msubplots\u001B[39m(\n\u001B[0;32m   1605\u001B[0m     nrows: \u001B[38;5;28mint\u001B[39m \u001B[38;5;241m=\u001B[39m \u001B[38;5;241m1\u001B[39m, ncols: \u001B[38;5;28mint\u001B[39m \u001B[38;5;241m=\u001B[39m \u001B[38;5;241m1\u001B[39m, \u001B[38;5;241m*\u001B[39m,\n\u001B[0;32m   1606\u001B[0m     sharex: \u001B[38;5;28mbool\u001B[39m \u001B[38;5;241m|\u001B[39m Literal[\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mnone\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mall\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mrow\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcol\u001B[39m\u001B[38;5;124m\"\u001B[39m] \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;01mFalse\u001B[39;00m,\n\u001B[1;32m   (...)\u001B[0m\n\u001B[0;32m   1613\u001B[0m     \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mfig_kw\n\u001B[0;32m   1614\u001B[0m ) \u001B[38;5;241m-\u001B[39m\u001B[38;5;241m>\u001B[39m \u001B[38;5;28mtuple\u001B[39m[Figure, Any]:\n\u001B[0;32m   1615\u001B[0m \u001B[38;5;250m    \u001B[39m\u001B[38;5;124;03m\"\"\"\u001B[39;00m\n\u001B[0;32m   1616\u001B[0m \u001B[38;5;124;03m    Create a figure and a set of subplots.\u001B[39;00m\n\u001B[0;32m   1617\u001B[0m \n\u001B[1;32m   (...)\u001B[0m\n\u001B[0;32m   1757\u001B[0m \n\u001B[0;32m   1758\u001B[0m \u001B[38;5;124;03m    \"\"\"\u001B[39;00m\n\u001B[1;32m-> 1759\u001B[0m     fig \u001B[38;5;241m=\u001B[39m figure(\u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mfig_kw)\n\u001B[0;32m   1760\u001B[0m     axs \u001B[38;5;241m=\u001B[39m fig\u001B[38;5;241m.\u001B[39msubplots(nrows\u001B[38;5;241m=\u001B[39mnrows, ncols\u001B[38;5;241m=\u001B[39mncols, sharex\u001B[38;5;241m=\u001B[39msharex, sharey\u001B[38;5;241m=\u001B[39msharey,\n\u001B[0;32m   1761\u001B[0m                        squeeze\u001B[38;5;241m=\u001B[39msqueeze, subplot_kw\u001B[38;5;241m=\u001B[39msubplot_kw,\n\u001B[0;32m   1762\u001B[0m                        gridspec_kw\u001B[38;5;241m=\u001B[39mgridspec_kw, height_ratios\u001B[38;5;241m=\u001B[39mheight_ratios,\n\u001B[0;32m   1763\u001B[0m                        width_ratios\u001B[38;5;241m=\u001B[39mwidth_ratios)\n\u001B[0;32m   1764\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m fig, axs\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\pyplot.py:1027\u001B[0m, in \u001B[0;36mfigure\u001B[1;34m(num, figsize, dpi, facecolor, edgecolor, frameon, FigureClass, clear, **kwargs)\u001B[0m\n\u001B[0;32m   1017\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mlen\u001B[39m(allnums) \u001B[38;5;241m==\u001B[39m max_open_warning \u001B[38;5;241m>\u001B[39m\u001B[38;5;241m=\u001B[39m \u001B[38;5;241m1\u001B[39m:\n\u001B[0;32m   1018\u001B[0m     _api\u001B[38;5;241m.\u001B[39mwarn_external(\n\u001B[0;32m   1019\u001B[0m         \u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mMore than \u001B[39m\u001B[38;5;132;01m{\u001B[39;00mmax_open_warning\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m figures have been opened. \u001B[39m\u001B[38;5;124m\"\u001B[39m\n\u001B[0;32m   1020\u001B[0m         \u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mFigures created through the pyplot interface \u001B[39m\u001B[38;5;124m\"\u001B[39m\n\u001B[1;32m   (...)\u001B[0m\n\u001B[0;32m   1024\u001B[0m         \u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mConsider using `matplotlib.pyplot.close()`.\u001B[39m\u001B[38;5;124m\"\u001B[39m,\n\u001B[0;32m   1025\u001B[0m         \u001B[38;5;167;01mRuntimeWarning\u001B[39;00m)\n\u001B[1;32m-> 1027\u001B[0m manager \u001B[38;5;241m=\u001B[39m new_figure_manager(\n\u001B[0;32m   1028\u001B[0m     num, figsize\u001B[38;5;241m=\u001B[39mfigsize, dpi\u001B[38;5;241m=\u001B[39mdpi,\n\u001B[0;32m   1029\u001B[0m     facecolor\u001B[38;5;241m=\u001B[39mfacecolor, edgecolor\u001B[38;5;241m=\u001B[39medgecolor, frameon\u001B[38;5;241m=\u001B[39mframeon,\n\u001B[0;32m   1030\u001B[0m     FigureClass\u001B[38;5;241m=\u001B[39mFigureClass, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs)\n\u001B[0;32m   1031\u001B[0m fig \u001B[38;5;241m=\u001B[39m manager\u001B[38;5;241m.\u001B[39mcanvas\u001B[38;5;241m.\u001B[39mfigure\n\u001B[0;32m   1032\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m fig_label:\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\pyplot.py:550\u001B[0m, in \u001B[0;36mnew_figure_manager\u001B[1;34m(*args, **kwargs)\u001B[0m\n\u001B[0;32m    548\u001B[0m \u001B[38;5;250m\u001B[39m\u001B[38;5;124;03m\"\"\"Create a new figure manager instance.\"\"\"\u001B[39;00m\n\u001B[0;32m    549\u001B[0m _warn_if_gui_out_of_main_thread()\n\u001B[1;32m--> 550\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m _get_backend_mod()\u001B[38;5;241m.\u001B[39mnew_figure_manager(\u001B[38;5;241m*\u001B[39margs, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs)\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib_inline\\backend_inline.py:27\u001B[0m, in \u001B[0;36mnew_figure_manager\u001B[1;34m(num, FigureClass, *args, **kwargs)\u001B[0m\n\u001B[0;32m     21\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21mnew_figure_manager\u001B[39m(num, \u001B[38;5;241m*\u001B[39margs, FigureClass\u001B[38;5;241m=\u001B[39mFigure, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs):\n\u001B[0;32m     22\u001B[0m \u001B[38;5;250m    \u001B[39m\u001B[38;5;124;03m\"\"\"\u001B[39;00m\n\u001B[0;32m     23\u001B[0m \u001B[38;5;124;03m    Return a new figure manager for a new figure instance.\u001B[39;00m\n\u001B[0;32m     24\u001B[0m \n\u001B[0;32m     25\u001B[0m \u001B[38;5;124;03m    This function is part of the API expected by Matplotlib backends.\u001B[39;00m\n\u001B[0;32m     26\u001B[0m \u001B[38;5;124;03m    \"\"\"\u001B[39;00m\n\u001B[1;32m---> 27\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m new_figure_manager_given_figure(num, FigureClass(\u001B[38;5;241m*\u001B[39margs, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs))\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\figure.py:2502\u001B[0m, in \u001B[0;36mFigure.__init__\u001B[1;34m(self, figsize, dpi, facecolor, edgecolor, linewidth, frameon, subplotpars, tight_layout, constrained_layout, layout, **kwargs)\u001B[0m\n\u001B[0;32m   2406\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21m__init__\u001B[39m(\u001B[38;5;28mself\u001B[39m,\n\u001B[0;32m   2407\u001B[0m              figsize\u001B[38;5;241m=\u001B[39m\u001B[38;5;28;01mNone\u001B[39;00m,\n\u001B[0;32m   2408\u001B[0m              dpi\u001B[38;5;241m=\u001B[39m\u001B[38;5;28;01mNone\u001B[39;00m,\n\u001B[1;32m   (...)\u001B[0m\n\u001B[0;32m   2418\u001B[0m              \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs\n\u001B[0;32m   2419\u001B[0m              ):\n\u001B[0;32m   2420\u001B[0m \u001B[38;5;250m    \u001B[39m\u001B[38;5;124;03m\"\"\"\u001B[39;00m\n\u001B[0;32m   2421\u001B[0m \u001B[38;5;124;03m    Parameters\u001B[39;00m\n\u001B[0;32m   2422\u001B[0m \u001B[38;5;124;03m    ----------\u001B[39;00m\n\u001B[1;32m   (...)\u001B[0m\n\u001B[0;32m   2500\u001B[0m \u001B[38;5;124;03m        %(Figure:kwdoc)s\u001B[39;00m\n\u001B[0;32m   2501\u001B[0m \u001B[38;5;124;03m    \"\"\"\u001B[39;00m\n\u001B[1;32m-> 2502\u001B[0m     \u001B[38;5;28msuper\u001B[39m()\u001B[38;5;241m.\u001B[39m\u001B[38;5;21m__init__\u001B[39m(\u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs)\n\u001B[0;32m   2503\u001B[0m     \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mfigure \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\n\u001B[0;32m   2504\u001B[0m     \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_layout_engine \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;01mNone\u001B[39;00m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\figure.py:154\u001B[0m, in \u001B[0;36mFigureBase.__init__\u001B[1;34m(self, **kwargs)\u001B[0m\n\u001B[0;32m    152\u001B[0m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mstale \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;01mTrue\u001B[39;00m\n\u001B[0;32m    153\u001B[0m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39msuppressComposite \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;01mNone\u001B[39;00m\n\u001B[1;32m--> 154\u001B[0m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mset(\u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs)\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\artist.py:147\u001B[0m, in \u001B[0;36mArtist.__init_subclass__.<locals>.<lambda>\u001B[1;34m(self, **kwargs)\u001B[0m\n\u001B[0;32m    139\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28mhasattr\u001B[39m(\u001B[38;5;28mcls\u001B[39m\u001B[38;5;241m.\u001B[39mset, \u001B[38;5;124m'\u001B[39m\u001B[38;5;124m_autogenerated_signature\u001B[39m\u001B[38;5;124m'\u001B[39m):\n\u001B[0;32m    140\u001B[0m     \u001B[38;5;66;03m# Don't overwrite cls.set if the subclass or one of its parents\u001B[39;00m\n\u001B[0;32m    141\u001B[0m     \u001B[38;5;66;03m# has defined a set method set itself.\u001B[39;00m\n\u001B[0;32m    142\u001B[0m     \u001B[38;5;66;03m# If there was no explicit definition, cls.set is inherited from\u001B[39;00m\n\u001B[0;32m    143\u001B[0m     \u001B[38;5;66;03m# the hierarchy of auto-generated set methods, which hold the\u001B[39;00m\n\u001B[0;32m    144\u001B[0m     \u001B[38;5;66;03m# flag _autogenerated_signature.\u001B[39;00m\n\u001B[0;32m    145\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m\n\u001B[1;32m--> 147\u001B[0m \u001B[38;5;28mcls\u001B[39m\u001B[38;5;241m.\u001B[39mset \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;01mlambda\u001B[39;00m \u001B[38;5;28mself\u001B[39m, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs: Artist\u001B[38;5;241m.\u001B[39mset(\u001B[38;5;28mself\u001B[39m, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs)\n\u001B[0;32m    148\u001B[0m \u001B[38;5;28mcls\u001B[39m\u001B[38;5;241m.\u001B[39mset\u001B[38;5;241m.\u001B[39m\u001B[38;5;18m__name__\u001B[39m \u001B[38;5;241m=\u001B[39m \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mset\u001B[39m\u001B[38;5;124m\"\u001B[39m\n\u001B[0;32m    149\u001B[0m \u001B[38;5;28mcls\u001B[39m\u001B[38;5;241m.\u001B[39mset\u001B[38;5;241m.\u001B[39m\u001B[38;5;18m__qualname__\u001B[39m \u001B[38;5;241m=\u001B[39m \u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;132;01m{\u001B[39;00m\u001B[38;5;28mcls\u001B[39m\u001B[38;5;241m.\u001B[39m\u001B[38;5;18m__qualname__\u001B[39m\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m.set\u001B[39m\u001B[38;5;124m\"\u001B[39m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\artist.py:1224\u001B[0m, in \u001B[0;36mArtist.set\u001B[1;34m(self, **kwargs)\u001B[0m\n\u001B[0;32m   1220\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21mset\u001B[39m(\u001B[38;5;28mself\u001B[39m, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs):\n\u001B[0;32m   1221\u001B[0m     \u001B[38;5;66;03m# docstring and signature are auto-generated via\u001B[39;00m\n\u001B[0;32m   1222\u001B[0m     \u001B[38;5;66;03m# Artist._update_set_signature_and_docstring() at the end of the\u001B[39;00m\n\u001B[0;32m   1223\u001B[0m     \u001B[38;5;66;03m# module.\u001B[39;00m\n\u001B[1;32m-> 1224\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m_internal_update\u001B[49m\u001B[43m(\u001B[49m\u001B[43mcbook\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mnormalize_kwargs\u001B[49m\u001B[43m(\u001B[49m\u001B[43mkwargs\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;28;43mself\u001B[39;49m\u001B[43m)\u001B[49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\artist.py:1216\u001B[0m, in \u001B[0;36mArtist._internal_update\u001B[1;34m(self, kwargs)\u001B[0m\n\u001B[0;32m   1209\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21m_internal_update\u001B[39m(\u001B[38;5;28mself\u001B[39m, kwargs):\n\u001B[0;32m   1210\u001B[0m \u001B[38;5;250m    \u001B[39m\u001B[38;5;124;03m\"\"\"\u001B[39;00m\n\u001B[0;32m   1211\u001B[0m \u001B[38;5;124;03m    Update artist properties without prenormalizing them, but generating\u001B[39;00m\n\u001B[0;32m   1212\u001B[0m \u001B[38;5;124;03m    errors as if calling `set`.\u001B[39;00m\n\u001B[0;32m   1213\u001B[0m \n\u001B[0;32m   1214\u001B[0m \u001B[38;5;124;03m    The lack of prenormalization is to maintain backcompatibility.\u001B[39;00m\n\u001B[0;32m   1215\u001B[0m \u001B[38;5;124;03m    \"\"\"\u001B[39;00m\n\u001B[1;32m-> 1216\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m_update_props\u001B[49m\u001B[43m(\u001B[49m\n\u001B[0;32m   1217\u001B[0m \u001B[43m        \u001B[49m\u001B[43mkwargs\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;132;43;01m{cls.__name__}\u001B[39;49;00m\u001B[38;5;124;43m.set() got an unexpected keyword argument \u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\n\u001B[0;32m   1218\u001B[0m \u001B[43m        \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;132;43;01m{prop_name!r}\u001B[39;49;00m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\Downloads\\single-cell\\lib\\site-packages\\matplotlib\\artist.py:1190\u001B[0m, in \u001B[0;36mArtist._update_props\u001B[1;34m(self, props, errfmt)\u001B[0m\n\u001B[0;32m   1188\u001B[0m             func \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mgetattr\u001B[39m(\u001B[38;5;28mself\u001B[39m, \u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mset_\u001B[39m\u001B[38;5;132;01m{\u001B[39;00mk\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;28;01mNone\u001B[39;00m)\n\u001B[0;32m   1189\u001B[0m             \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28mcallable\u001B[39m(func):\n\u001B[1;32m-> 1190\u001B[0m                 \u001B[38;5;28;01mraise\u001B[39;00m \u001B[38;5;167;01mAttributeError\u001B[39;00m(\n\u001B[0;32m   1191\u001B[0m                     errfmt\u001B[38;5;241m.\u001B[39mformat(\u001B[38;5;28mcls\u001B[39m\u001B[38;5;241m=\u001B[39m\u001B[38;5;28mtype\u001B[39m(\u001B[38;5;28mself\u001B[39m), prop_name\u001B[38;5;241m=\u001B[39mk))\n\u001B[0;32m   1192\u001B[0m             ret\u001B[38;5;241m.\u001B[39mappend(func(v))\n\u001B[0;32m   1193\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m ret:\n",
      "\u001B[1;31mAttributeError\u001B[0m: Figure.set() got an unexpected keyword argument 'bottom'"
     ]
    }
   ],
   "source": [
    "fig, ax = plt.subplots(figsize=(13, 6))\n",
    "\n",
    "sns.set_context(\"paper\")\n",
    "sns.set_style(\"whitegrid\")\n",
    "\n",
    "# Calcular el tamaño de cada subset\n",
    "subset_sizes = combined_data.groupby(\"dataset\")[\"protein_id\"].nunique()\n",
    "\n",
    "# Generar una paleta de colores\n",
    "unique_datasets = combined_data[\"dataset\"].unique()\n",
    "palette = {dataset: '#79C4FF' for dataset in unique_datasets}\n",
    "\n",
    "# Asignar rojo al \"Module\"\n",
    "palette[\"Alzheimer LCC\"] = \"grey\"\n",
    "sns.violinplot(data=combined_data, x=\"dataset\", y=np.log10(combined_data[\"degree\"]), ax=ax, palette=palette)\n",
    "\n",
    "# Añadir etiquetas con el tamaño de cada subset\n",
    "for i, dataset in enumerate(combined_data[\"dataset\"].unique()):\n",
    "    ax.text(i, ax.get_ylim()[0], f\"n = {subset_sizes.get(dataset, 0)}\", ha='center', va='bottom', fontsize=10, color='black')\n",
    "\n",
    "plt.title('Degree distribution for the Alzheimer disease module and each cell type')\n",
    "plt.ylabel('log(Degree)')\n",
    "plt.xlabel('Dataset / Cell type')\n",
    "\n",
    "# Añadir leyenda y mostrar la gráfica\n",
    "plt.tight_layout()\n",
    "# plt.legend(title='Cell Types', loc='upper right')\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 420,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 1300x600 with 1 Axes>",
      "image/png": "[encoded data, 52592 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = plt.subplots(figsize=(13, 6))\n",
    "\n",
    "sns.set_context(\"paper\")\n",
    "sns.set_style(\"whitegrid\")\n",
    "\n",
    "# Calcular el tamaño de cada subset\n",
    "subset_sizes = combined_data.groupby(\"dataset\")[\"protein_id\"].nunique()\n",
    "\n",
    "# Generar una paleta de colores\n",
    "unique_datasets = combined_data[\"dataset\"].unique()\n",
    "palette = {dataset: '#79C4FF' for dataset in unique_datasets}\n",
    "\n",
    "# Asignar rojo al \"Module\"\n",
    "palette[\"Alzheimer LCC\"] = \"grey\"\n",
    "sns.histplot(data=combined_data, x=np.log10(combined_data[\"degree\"]), hue = 'dataset', ax=ax, palette=palette)\n",
    "\n",
    "# Añadir etiquetas con el tamaño de cada subset\n",
    "# for i, dataset in enumerate(combined_data[\"dataset\"].unique()):\n",
    "#     ax.text(i, ax.get_ylim()[0], f\"n = {subset_sizes.get(dataset, 0)}\", ha='center', va='bottom', fontsize=10, color='black')\n",
    "\n",
    "plt.title('Degree distribution for the Alzheimer disease module and each cell type')\n",
    "plt.xlabel('log(Degree)')\n",
    "# plt.ylabel('log(Protein Count)')\n",
    "\n",
    "# Añadir leyenda y mostrar la gráfica\n",
    "plt.tight_layout()\n",
    "# plt.legend(title='Cell Types', loc='upper right')\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 367,
   "outputs": [],
   "source": [
    "plot_data = cell_data.groupby([\"degree\", \"cell_type\"]).count()[\"protein_id\"].reset_index()\n",
    "plot_data.rename(columns={\"protein_id\": \"protein_count\"}, inplace=True)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 455,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 800x600 with 1 Axes>",
      "image/png": "[encoded data, 163316 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "\n",
    "plt.figure(figsize=(8, 6))\n",
    "# sns.barplot(data=plot_data, x=\"degree\", y=\"protein_count\", hue=\"cell_type\", alpha=0.7)\n",
    "sns.lineplot(data=plot_data, x=\"degree\", y=\"protein_count\", hue=\"cell_type\")\n",
    "# sns.boxplot(data = plot_data, x = \"degree\", y = \"protein_count\", hue = \"cell_type\")\n",
    "# Configurar escala logarítmica en ambos ejes\n",
    "plt.xscale(\"log\")\n",
    "plt.yscale(\"log\")\n",
    "\n",
    "# Etiquetas\n",
    "plt.xlabel(\"log(Degree)\")\n",
    "plt.ylabel(\"log(Protein Count)\")\n",
    "plt.title(\"Distribution of Degree per Protein\")\n",
    "plt.legend(title=\"Cell Type\", bbox_to_anchor=(1.05, 1), loc=\"upper left\")\n",
    "\n",
    "# Mostrar el gráfico\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 301,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 1200x600 with 8 Axes>",
      "image/png": "[encoded data, 47348 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "g = sns.FacetGrid(cell_data, col=\"cell_type\", col_wrap=4, sharex=True, sharey=True)\n",
    "g.map(sns.histplot, \"degree\", bins=300)\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "#### Numeric analysis\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 659,
   "outputs": [],
   "source": [
    "cell_data = pd.read_csv('CellXGene/cross-dementia/filtered/results/network_analysis.csv')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 668,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                                         mean         std  median  min   max  \\\n",
      "cell_type                                                                      \n",
      "astrocyte                           57.486842   97.024051    29.0    1  1379   \n",
      "endothelial cell of vascular tree   98.767123  119.863872    55.0    2   553   \n",
      "glutamatergic neuron                61.219645   98.005476    30.0    1  1379   \n",
      "inhibitory interneuron              61.210996   99.727546    31.0    1  1381   \n",
      "microglial cell                     66.434132  129.637865    35.5    2  1381   \n",
      "oligodendrocyte                     56.301444   97.276815    29.0    2  1379   \n",
      "oligodendrocyte precursor cell      65.284375  105.131312    38.0    2  1379   \n",
      "pericyte                           132.300000  138.173080    74.0   15   553   \n",
      "\n",
      "                                   count  \n",
      "cell_type                                 \n",
      "astrocyte                            532  \n",
      "endothelial cell of vascular tree     73  \n",
      "glutamatergic neuron                 733  \n",
      "inhibitory interneuron               673  \n",
      "microglial cell                      334  \n",
      "oligodendrocyte                      554  \n",
      "oligodendrocyte precursor cell       320  \n",
      "pericyte                              20  \n"
     ]
    }
   ],
   "source": [
    "cols_of_interest = [\"degree\"]\n",
    "\n",
    "# Calcular estadísticas por 'cell_type'\n",
    "stats = cell_data.groupby(\"cell_type\")[\"degree\"].agg([\"mean\", \"std\", \"median\", \"min\", \"max\"])\n",
    "\n",
    "stats[\"count\"] = cell_data.groupby(\"cell_type\").size()\n",
    "\n",
    "# Mostrar resultados\n",
    "print(stats)\n",
    "\n",
    "# Si deseas guardar los resultados en un archivo CSV:\n",
    "stats.to_csv(\"CellXGene/cross-dementia/filtered/results/cell_type_statistics.csv\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 669,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mean        45.292918\n",
      "std         84.963373\n",
      "median      23.000000\n",
      "min          1.000000\n",
      "max       1901.000000\n",
      "count     2697.000000\n",
      "Name: degree, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "module_data = pd.read_csv('CellXGene/cross-dementia/filtered/results/G_ppi_analysis.csv')\n",
    "\n",
    "module_data_lcc = module_data[module_data['is_in_LCC'] == True]\n",
    "\n",
    "# Calcular estadísticas por 'cell_type'\n",
    "stats = module_data_lcc[\"degree\"].agg([\"mean\", \"std\", \"median\", \"min\", \"max\", \"count\"])\n",
    "\n",
    "# stats[\"count\"] = module_data_lcc.groupby(\"cell_type\").size()\n",
    "\n",
    "# Mostrar resultados\n",
    "print(stats)\n",
    "\n",
    "# Si deseas guardar los resultados en un archivo CSV:\n",
    "# stats.to_csv(\"CellXGene/cross-dementia/filtered/results/general_module_statistics.csv\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 704,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['C1QA', 'HSPB1', 'GPR6', 'DRD4', 'CD14', 'PENK', 'GPR6', 'CRYZ', 'ARAP3', 'DRD4', 'RELN', 'CXCR4', 'BIRC3', 'HSPA1B', 'CRYAB', 'ANXA1', 'EGR1', 'EGF', 'S100A10', 'BAG3', 'HSPA1B', 'HSPB1', 'DNAJB1', 'FOS', 'IGFBP3', 'EGR1', 'SOCS3', 'VGF', 'HSPA1B', 'CACYBP', 'RBM3', 'HSPB1', 'HSPH1', 'HSPA1B', 'CRYAB', 'HSPB1', 'VIM', 'HSPH1']\n"
     ]
    }
   ],
   "source": [
    "gene_info = []\n",
    "\n",
    "for type, gene in top_genes_info.items():\n",
    "    for g in gene:\n",
    "        gene_info.append(g)\n",
    "        # gene_info = gene_info.append(cell_data[cell_data['gene_symbol'] == g])\n",
    "\n",
    "\n",
    "# gene_info = pd.DataFrame(gene_info)\n",
    "print(gene_info)\n",
    "\n",
    "cell_data[cell_data['gene_symbol'].isin(gene_info)].to_csv('CellXGene/cross-dementia/filtered/results/top_gene_info.csv', index = False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 705,
   "outputs": [],
   "source": [
    "top_genes = pd.read_csv('CellXGene/cross-dementia/filtered/results/top_gene_info.csv')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 714,
   "outputs": [
    {
     "data": {
      "text/plain": "   protein_id  gene_id gene_symbol        cell_type  logfoldchanges  \\\n30     P78509   5649.0        RELN  oligodendrocyte        2.069801   \n\n            pvals      pvals_adj  degree  betweenness_centrality  \\\n30  4.778383e-177  5.414541e-175       2            1.279763e-08   \n\n    closeness_centrality  clustering_coefficient  is_hub  \n30              0.255853                     0.0   False  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>protein_id</th>\n      <th>gene_id</th>\n      <th>gene_symbol</th>\n      <th>cell_type</th>\n      <th>logfoldchanges</th>\n      <th>pvals</th>\n      <th>pvals_adj</th>\n      <th>degree</th>\n      <th>betweenness_centrality</th>\n      <th>closeness_centrality</th>\n      <th>clustering_coefficient</th>\n      <th>is_hub</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>30</th>\n      <td>P78509</td>\n      <td>5649.0</td>\n      <td>RELN</td>\n      <td>oligodendrocyte</td>\n      <td>2.069801</td>\n      <td>4.778383e-177</td>\n      <td>5.414541e-175</td>\n      <td>2</td>\n      <td>1.279763e-08</td>\n      <td>0.255853</td>\n      <td>0.0</td>\n      <td>False</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 714,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "top_genes[top_genes['gene_symbol'] == 'RELN']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 716,
   "outputs": [
    {
     "data": {
      "text/plain": "   protein_id  gene_id gene_symbol                          cell_type  \\\n72     P04792   3315.0       HSPB1  endothelial cell of vascular tree   \n73     P25685   3337.0      DNAJB1  endothelial cell of vascular tree   \n74     P02511   1410.0       CRYAB  endothelial cell of vascular tree   \n75     O95817   9531.0        BAG3  endothelial cell of vascular tree   \n76     Q92598  10808.0       HSPH1  endothelial cell of vascular tree   \n77     P98179   5935.0        RBM3  endothelial cell of vascular tree   \n78     P0DMV8   3304.0      HSPA1B  endothelial cell of vascular tree   \n79     Q9HB71  27101.0      CACYBP  endothelial cell of vascular tree   \n\n    logfoldchanges         pvals     pvals_adj  degree  \\\n72        2.352189  9.755175e-62  1.376211e-57     320   \n73        1.947837  8.083351e-14  8.447102e-11      51   \n74        1.457500  3.843713e-10  2.046233e-07      49   \n75        1.000120  5.294115e-05  6.187393e-03     118   \n76        2.194557  2.518458e-33  1.015118e-29      48   \n77       -1.982801  4.016365e-09  1.770652e-06      35   \n78        2.800699  9.817635e-38  6.925114e-34      63   \n79        2.015665  3.298393e-12  2.658976e-09     104   \n\n    betweenness_centrality  closeness_centrality  clustering_coefficient  \\\n72                0.005160              0.402288                0.021804   \n73                0.000148              0.366387                0.092549   \n74                0.000346              0.347922                0.035153   \n75                0.000841              0.369861                0.025786   \n76                0.000107              0.370486                0.117908   \n77                0.000041              0.348381                0.147899   \n78                0.000533              0.359315                0.045059   \n79                0.000331              0.363172                0.041636   \n\n    is_hub  \n72    True  \n73   False  \n74   False  \n75    True  \n76   False  \n77   False  \n78   False  \n79    True  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>protein_id</th>\n      <th>gene_id</th>\n      <th>gene_symbol</th>\n      <th>cell_type</th>\n      <th>logfoldchanges</th>\n      <th>pvals</th>\n      <th>pvals_adj</th>\n      <th>degree</th>\n      <th>betweenness_centrality</th>\n      <th>closeness_centrality</th>\n      <th>clustering_coefficient</th>\n      <th>is_hub</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>72</th>\n      <td>P04792</td>\n      <td>3315.0</td>\n      <td>HSPB1</td>\n      <td>endothelial cell of vascular tree</td>\n      <td>2.352189</td>\n      <td>9.755175e-62</td>\n      <td>1.376211e-57</td>\n      <td>320</td>\n      <td>0.005160</td>\n      <td>0.402288</td>\n      <td>0.021804</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>73</th>\n      <td>P25685</td>\n      <td>3337.0</td>\n      <td>DNAJB1</td>\n      <td>endothelial cell of vascular tree</td>\n      <td>1.947837</td>\n      <td>8.083351e-14</td>\n      <td>8.447102e-11</td>\n      <td>51</td>\n      <td>0.000148</td>\n      <td>0.366387</td>\n      <td>0.092549</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>74</th>\n      <td>P02511</td>\n      <td>1410.0</td>\n      <td>CRYAB</td>\n      <td>endothelial cell of vascular tree</td>\n      <td>1.457500</td>\n      <td>3.843713e-10</td>\n      <td>2.046233e-07</td>\n      <td>49</td>\n      <td>0.000346</td>\n      <td>0.347922</td>\n      <td>0.035153</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td>O95817</td>\n      <td>9531.0</td>\n      <td>BAG3</td>\n      <td>endothelial cell of vascular tree</td>\n      <td>1.000120</td>\n      <td>5.294115e-05</td>\n      <td>6.187393e-03</td>\n      <td>118</td>\n      <td>0.000841</td>\n      <td>0.369861</td>\n      <td>0.025786</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>76</th>\n      <td>Q92598</td>\n      <td>10808.0</td>\n      <td>HSPH1</td>\n      <td>endothelial cell of vascular tree</td>\n      <td>2.194557</td>\n      <td>2.518458e-33</td>\n      <td>1.015118e-29</td>\n      <td>48</td>\n      <td>0.000107</td>\n      <td>0.370486</td>\n      <td>0.117908</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>77</th>\n      <td>P98179</td>\n      <td>5935.0</td>\n      <td>RBM3</td>\n      <td>endothelial cell of vascular tree</td>\n      <td>-1.982801</td>\n      <td>4.016365e-09</td>\n      <td>1.770652e-06</td>\n      <td>35</td>\n      <td>0.000041</td>\n      <td>0.348381</td>\n      <td>0.147899</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>78</th>\n      <td>P0DMV8</td>\n      <td>3304.0</td>\n      <td>HSPA1B</td>\n      <td>endothelial cell of vascular tree</td>\n      <td>2.800699</td>\n      <td>9.817635e-38</td>\n      <td>6.925114e-34</td>\n      <td>63</td>\n      <td>0.000533</td>\n      <td>0.359315</td>\n      <td>0.045059</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>79</th>\n      <td>Q9HB71</td>\n      <td>27101.0</td>\n      <td>CACYBP</td>\n      <td>endothelial cell of vascular tree</td>\n      <td>2.015665</td>\n      <td>3.298393e-12</td>\n      <td>2.658976e-09</td>\n      <td>104</td>\n      <td>0.000331</td>\n      <td>0.363172</td>\n      <td>0.041636</td>\n      <td>True</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 716,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "top_genes[top_genes['cell_type'] == 'endothelial cell of vascular tree']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 710,
   "outputs": [
    {
     "data": {
      "text/plain": "   gene_symbol  degree\n30        RELN       2\n56        GPR6       2\n32         VGF       3\n58       ARAP3       4\n59        DRD4       5\n62        PENK       8\n5          EGF       9\n35        CRYZ      11\n25        C1QA      19\n81      IGFBP3      21\n49        CD14      24\n6         EGR1      25\n39      HSPA1B      31\n9         RBM3      35\n27       CXCR4      37\n42       BIRC3      41\n1      S100A10      43\n89       SOCS3      47\n0        HSPH1      48\n65       CRYAB      49\n46      DNAJB1      51\n11      HSPA1B      63\n51       ANXA1      80\n45      CACYBP     104\n75        BAG3     118\n80         FOS     140\n57         VIM     266\n26       HSPB1     320",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>gene_symbol</th>\n      <th>degree</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>30</th>\n      <td>RELN</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>GPR6</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>VGF</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td>ARAP3</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td>DRD4</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>62</th>\n      <td>PENK</td>\n      <td>8</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>EGF</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>CRYZ</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>C1QA</td>\n      <td>19</td>\n    </tr>\n    <tr>\n      <th>81</th>\n      <td>IGFBP3</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>CD14</td>\n      <td>24</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>EGR1</td>\n      <td>25</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>HSPA1B</td>\n      <td>31</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>RBM3</td>\n      <td>35</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>CXCR4</td>\n      <td>37</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>BIRC3</td>\n      <td>41</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>S100A10</td>\n      <td>43</td>\n    </tr>\n    <tr>\n      <th>89</th>\n      <td>SOCS3</td>\n      <td>47</td>\n    </tr>\n    <tr>\n      <th>0</th>\n      <td>HSPH1</td>\n      <td>48</td>\n    </tr>\n    <tr>\n      <th>65</th>\n      <td>CRYAB</td>\n      <td>49</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>DNAJB1</td>\n      <td>51</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>HSPA1B</td>\n      <td>63</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>ANXA1</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>CACYBP</td>\n      <td>104</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td>BAG3</td>\n      <td>118</td>\n    </tr>\n    <tr>\n      <th>80</th>\n      <td>FOS</td>\n      <td>140</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>VIM</td>\n      <td>266</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>HSPB1</td>\n      <td>320</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 710,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "top_genes.sort_values('degree')[['gene_symbol', 'degree']].drop_duplicates()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 8.5. Gephi file preparation\n",
    "\n",
    "Quiero tener un archivo con la red representada por aquellos genes que están en el LCC del Alzheimer y además en al menos un tipo celular."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 333,
   "outputs": [],
   "source": [
    "pro_pro = pd.read_csv(\"CellXGene/pro_pro.tsv\", sep='\\t')\n",
    "cell_types = ['astrocyte', 'microglial cell', 'oligodendrocyte', 'glutamatergic neuron', 'inhibitory interneuron',\n",
    "              'endothelial cell of vascular tree', 'oligodendrocyte precursor cell', 'pericyte']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 334,
   "outputs": [],
   "source": [
    "filtered_files = glob.glob(\"CellXGene/cross-dementia/filtered/data/degs_*_mapped.csv\")\n",
    "\n",
    "filtered_data = load_and_process(filtered_files)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 335,
   "outputs": [],
   "source": [
    "unique_proteins = filtered_data['protein_id'].unique()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 339,
   "outputs": [],
   "source": [
    "G = nx.Graph()\n",
    "\n",
    "G.add_nodes_from(unique_proteins)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 340,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Graph with 1519 nodes and 0 edges\n"
     ]
    }
   ],
   "source": [
    "print(G)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 341,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Graph with 1519 nodes and 8331 edges\n"
     ]
    }
   ],
   "source": [
    "for _, row in pro_pro.iterrows():\n",
    "    protein_A = row['prA']\n",
    "    protein_B = row['prB']\n",
    "\n",
    "    # Asegurarse de que las proteínas estén en la lista de interés\n",
    "    if protein_A in unique_proteins and protein_B in unique_proteins:\n",
    "        # Evitar self-interactions\n",
    "        if protein_A != protein_B:\n",
    "            G.add_edge(protein_A, protein_B)\n",
    "\n",
    "print(G)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 343,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Graph with 1519 nodes and 8331 edges\n"
     ]
    }
   ],
   "source": [
    "for _, row in filtered_data.iterrows():\n",
    "    protein_id = row['protein_id']\n",
    "\n",
    "    if protein_id in G.nodes:\n",
    "        G.nodes[protein_id]['gene_id'] = row['gene_id']\n",
    "        G.nodes[protein_id]['gene_symbol'] = row['gene_symbol']\n",
    "\n",
    "print(G)\n",
    "\n",
    "nx.write_graphml(G, \"CellXGene/cross-dementia/filtered/graphs/gephi/proteins_network.graphml\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 344,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Red para astrocyte exportada: Graph with 1519 nodes and 8331 edges\n",
      "Red para microglial cell exportada: Graph with 1519 nodes and 8331 edges\n",
      "Red para oligodendrocyte exportada: Graph with 1519 nodes and 8331 edges\n",
      "Red para glutamatergic neuron exportada: Graph with 1519 nodes and 8331 edges\n",
      "Red para inhibitory interneuron exportada: Graph with 1519 nodes and 8331 edges\n",
      "Red para endothelial cell of vascular tree exportada: Graph with 1519 nodes and 8331 edges\n",
      "Red para oligodendrocyte precursor cell exportada: Graph with 1519 nodes and 8331 edges\n",
      "Red para pericyte exportada: Graph with 1519 nodes and 8331 edges\n"
     ]
    }
   ],
   "source": [
    "## Anotaciones para cada tipo celular\n",
    "\n",
    "for cell_type in cell_types:\n",
    "    # Crear una copia de la red grande para trabajar con ella\n",
    "    G_cell_type = G.copy()\n",
    "\n",
    "    # Cargar el archivo de sobreexpresión para el tipo celular\n",
    "    degs_cell_type = pd.read_csv(f\"CellXGene/cross-dementia/filtered/data/degs_{cell_type}_mapped.csv\")\n",
    "\n",
    "    # Añadir los datos de sobreexpresión a los nodos correspondientes para este tipo celular\n",
    "    for _, row in degs_cell_type.iterrows():\n",
    "        protein_id = row['protein_id']\n",
    "        if protein_id in G_cell_type.nodes:\n",
    "            # Añadir atributos específicos para cada tipo celular\n",
    "            G_cell_type.nodes[protein_id]['logfoldchanges'] = row['logfoldchanges']\n",
    "            G_cell_type.nodes[protein_id]['pvals_'] = row['pvals']\n",
    "            G_cell_type.nodes[protein_id]['pvals_adj_'] = row['pvals_adj']\n",
    "            G_cell_type.nodes[protein_id]['scores_'] = row['scores']\n",
    "\n",
    "    # Guardar la red con los atributos específicos para este tipo celular\n",
    "    print(f\"Red para {cell_type} exportada: {G}\")\n",
    "    nx.write_graphml(G_cell_type, f\"CellXGene/cross-dementia/filtered/graphs/gephi/protein_network_{cell_type}.graphml\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# CONSIDERACIONES A LLEVAR A CABO EN LA ESTANCIA A RAIZ DE ESTE ANALISIS\n",
    "\n",
    "1. Trabajar con coexpresión diferencial (recomendado)\n",
    "En lugar de construir las redes solo con DEGs (listas de genes diferencialmente expresados), podrías construir redes de coexpresión génica por condición.\n",
    "\n",
    "- Calculas redes de coexpresión (Spearman o Pearson) para cada tipo celular, una en sano y otra en enfermo.\n",
    "- Filtras esas redes usando un umbral (por ejemplo, correlación > 0.7).\n",
    "- Mapeas esas redes a proteínas y filtrarlas usando el interactoma general, conservando solo edges entre genes que también interaccionan a nivel de proteínas.\n",
    "\n",
    "De esta manera, la estructura de la red sí va a cambiar entre sano y enfermo, porque la coexpresión (y sus patrones) realmente cambia con la enfermedad.\n",
    "\n",
    "2. Peso en las aristas basado en coexpresión o logFC\n",
    "Si quieres mantener el enfoque de PPI usando solo DEGs, puedes añadir pesos a las aristas que reflejen:\n",
    "\n",
    "- Correlación de expresión entre los genes conectados (si tienes datos de expresión para cada célula).\n",
    "- Media del logFC de los genes conectados (refleja qué tan diferencial es la interacción).Así, aunque las redes tengan la misma topología (mismo set de nodos y aristas), al menos el análisis estructural posterior (centralidad, modularidad, etc.) podría diferenciarse usando pesos.\n",
    "\n",
    "3. Redes basadas en \"differential interactomes\"\n",
    "Si tienes una red PPI general, puedes crear una red diferencial donde:\n",
    "\n",
    "- Un edge existe solo si hay evidencia de interacción alterada en la condición enferma. Por ejemplo, podrías integrar información de interacción diferencial (differential coexpression + PPI)."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}