{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "original-blade",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "<ipython-input-2-b4cd77b5885a>:3: FutureWarning: Passing a negative integer is deprecated in version 1.0 and will not be supported in future version. Instead, use None to not limit the column width.\n",
      "  pd.set_option('display.max_colwidth', -1)\n"
     ]
    }
   ],
   "source": [
    "import glob\n",
    "import pandas as pd\n",
    "pd.set_option('display.max_colwidth', -1)  \n",
    "import numpy as np\n",
    "from tqdm import tqdm\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib\n",
    "matplotlib.rcParams['animation.html'] = 'jshtml'\n",
    "import seaborn as sns\n",
    "\n",
    "import tensorflow as tf\n",
    "import tensorflow.keras as keras\n",
    "\n",
    "import pydicom"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "polish-lesson",
   "metadata": {},
   "outputs": [],
   "source": [
    "root_dir = 'E:/MyMasterthesis/Ref/Dataset/'\n",
    "df = pd.read_csv('E:/MyMasterthesis/Ref/Dataset/train_labels.csv')\n",
    "data=df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "handed-change",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "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>BraTS21ID</th>\n",
       "      <th>MGMT_value</th>\n",
       "      <th>BraTS21ID_full</th>\n",
       "      <th>flair</th>\n",
       "      <th>t1w</th>\n",
       "      <th>t1wce</th>\n",
       "      <th>t2w</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>00000</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00000/FLAIR/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00000/T1w/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00000/T1wCE/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00000/T2w/</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>00002</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00002/FLAIR/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00002/T1w/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00002/T1wCE/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00002/T2w/</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>00003</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00003/FLAIR/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00003/T1w/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00003/T1wCE/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00003/T2w/</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>00005</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00005/FLAIR/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00005/T1w/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00005/T1wCE/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00005/T2w/</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>6</td>\n",
       "      <td>1</td>\n",
       "      <td>00006</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00006/FLAIR/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00006/T1w/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00006/T1wCE/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/00006/T2w/</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",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>580</th>\n",
       "      <td>1005</td>\n",
       "      <td>1</td>\n",
       "      <td>01005</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01005/FLAIR/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01005/T1w/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01005/T1wCE/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01005/T2w/</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>581</th>\n",
       "      <td>1007</td>\n",
       "      <td>1</td>\n",
       "      <td>01007</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01007/FLAIR/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01007/T1w/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01007/T1wCE/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01007/T2w/</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>582</th>\n",
       "      <td>1008</td>\n",
       "      <td>1</td>\n",
       "      <td>01008</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01008/FLAIR/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01008/T1w/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01008/T1wCE/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01008/T2w/</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>583</th>\n",
       "      <td>1009</td>\n",
       "      <td>0</td>\n",
       "      <td>01009</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01009/FLAIR/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01009/T1w/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01009/T1wCE/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01009/T2w/</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>584</th>\n",
       "      <td>1010</td>\n",
       "      <td>0</td>\n",
       "      <td>01010</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01010/FLAIR/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01010/T1w/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01010/T1wCE/</td>\n",
       "      <td>E:/MyMasterthesis/Ref/Dataset/train/01010/T2w/</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>585 rows × 7 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     BraTS21ID  MGMT_value BraTS21ID_full  \\\n",
       "0    0          1           00000           \n",
       "1    2          1           00002           \n",
       "2    3          0           00003           \n",
       "3    5          1           00005           \n",
       "4    6          1           00006           \n",
       "..  ..         ..             ...           \n",
       "580  1005       1           01005           \n",
       "581  1007       1           01007           \n",
       "582  1008       1           01008           \n",
       "583  1009       0           01009           \n",
       "584  1010       0           01010           \n",
       "\n",
       "                                                flair  \\\n",
       "0    E:/MyMasterthesis/Ref/Dataset/train/00000/FLAIR/   \n",
       "1    E:/MyMasterthesis/Ref/Dataset/train/00002/FLAIR/   \n",
       "2    E:/MyMasterthesis/Ref/Dataset/train/00003/FLAIR/   \n",
       "3    E:/MyMasterthesis/Ref/Dataset/train/00005/FLAIR/   \n",
       "4    E:/MyMasterthesis/Ref/Dataset/train/00006/FLAIR/   \n",
       "..                                                ...   \n",
       "580  E:/MyMasterthesis/Ref/Dataset/train/01005/FLAIR/   \n",
       "581  E:/MyMasterthesis/Ref/Dataset/train/01007/FLAIR/   \n",
       "582  E:/MyMasterthesis/Ref/Dataset/train/01008/FLAIR/   \n",
       "583  E:/MyMasterthesis/Ref/Dataset/train/01009/FLAIR/   \n",
       "584  E:/MyMasterthesis/Ref/Dataset/train/01010/FLAIR/   \n",
       "\n",
       "                                                t1w  \\\n",
       "0    E:/MyMasterthesis/Ref/Dataset/train/00000/T1w/   \n",
       "1    E:/MyMasterthesis/Ref/Dataset/train/00002/T1w/   \n",
       "2    E:/MyMasterthesis/Ref/Dataset/train/00003/T1w/   \n",
       "3    E:/MyMasterthesis/Ref/Dataset/train/00005/T1w/   \n",
       "4    E:/MyMasterthesis/Ref/Dataset/train/00006/T1w/   \n",
       "..                                              ...   \n",
       "580  E:/MyMasterthesis/Ref/Dataset/train/01005/T1w/   \n",
       "581  E:/MyMasterthesis/Ref/Dataset/train/01007/T1w/   \n",
       "582  E:/MyMasterthesis/Ref/Dataset/train/01008/T1w/   \n",
       "583  E:/MyMasterthesis/Ref/Dataset/train/01009/T1w/   \n",
       "584  E:/MyMasterthesis/Ref/Dataset/train/01010/T1w/   \n",
       "\n",
       "                                                t1wce  \\\n",
       "0    E:/MyMasterthesis/Ref/Dataset/train/00000/T1wCE/   \n",
       "1    E:/MyMasterthesis/Ref/Dataset/train/00002/T1wCE/   \n",
       "2    E:/MyMasterthesis/Ref/Dataset/train/00003/T1wCE/   \n",
       "3    E:/MyMasterthesis/Ref/Dataset/train/00005/T1wCE/   \n",
       "4    E:/MyMasterthesis/Ref/Dataset/train/00006/T1wCE/   \n",
       "..                                                ...   \n",
       "580  E:/MyMasterthesis/Ref/Dataset/train/01005/T1wCE/   \n",
       "581  E:/MyMasterthesis/Ref/Dataset/train/01007/T1wCE/   \n",
       "582  E:/MyMasterthesis/Ref/Dataset/train/01008/T1wCE/   \n",
       "583  E:/MyMasterthesis/Ref/Dataset/train/01009/T1wCE/   \n",
       "584  E:/MyMasterthesis/Ref/Dataset/train/01010/T1wCE/   \n",
       "\n",
       "                                                t2w  \n",
       "0    E:/MyMasterthesis/Ref/Dataset/train/00000/T2w/  \n",
       "1    E:/MyMasterthesis/Ref/Dataset/train/00002/T2w/  \n",
       "2    E:/MyMasterthesis/Ref/Dataset/train/00003/T2w/  \n",
       "3    E:/MyMasterthesis/Ref/Dataset/train/00005/T2w/  \n",
       "4    E:/MyMasterthesis/Ref/Dataset/train/00006/T2w/  \n",
       "..                                              ...  \n",
       "580  E:/MyMasterthesis/Ref/Dataset/train/01005/T2w/  \n",
       "581  E:/MyMasterthesis/Ref/Dataset/train/01007/T2w/  \n",
       "582  E:/MyMasterthesis/Ref/Dataset/train/01008/T2w/  \n",
       "583  E:/MyMasterthesis/Ref/Dataset/train/01009/T2w/  \n",
       "584  E:/MyMasterthesis/Ref/Dataset/train/01010/T2w/  \n",
       "\n",
       "[585 rows x 7 columns]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def full_ids(data):\n",
    "    zeros = 5 - len(str(data))\n",
    "    if zeros > 0:\n",
    "        prefix = ''.join(['0' for i in range(zeros)])\n",
    "    \n",
    "    return prefix+str(data)\n",
    "        \n",
    "\n",
    "df['BraTS21ID_full'] = df['BraTS21ID'].apply(full_ids)\n",
    "\n",
    "# Add all the paths to the df for easy access\n",
    "df['flair'] = df['BraTS21ID_full'].apply(lambda file_id : root_dir+'train/'+file_id+'/FLAIR/')\n",
    "df['t1w'] = df['BraTS21ID_full'].apply(lambda file_id : root_dir+'train/'+file_id+'/T1w/')\n",
    "df['t1wce'] = df['BraTS21ID_full'].apply(lambda file_id : root_dir+'train/'+file_id+'/T1wCE/')\n",
    "df['t2w'] = df['BraTS21ID_full'].apply(lambda file_id : root_dir+'train/'+file_id+'/T2w/')\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "intellectual-morrison",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1    307\n",
      "0    278\n",
      "Name: MGMT_value, dtype: int64\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<AxesSubplot:xlabel='MGMT_value', ylabel='count'>"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 5968 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "print(df[\"MGMT_value\"].value_counts())\n",
    "sns.countplot(data=df, x='MGMT_value')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "heard-skiing",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 10044 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig= df[\"MGMT_value\"].value_counts().plot(kind=\"pie\", title=\"label distribution\", autopct=\"%.1f%%\")\n",
    "plt.savefig(root_dir+'MGMT_Pie')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "hazardous-ceramic",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Dataset.file_meta -------------------------------\n",
       "(0002, 0010) Transfer Syntax UID                 UI: Implicit VR Little Endian\n",
       "-------------------------------------------------\n",
       "(0008, 0005) Specific Character Set              CS: 'ISO_IR 100'\n",
       "(0008, 0008) Image Type                          CS: ['DERIVED', 'SECONDARY']\n",
       "(0008, 0016) SOP Class UID                       UI: MR Image Storage\n",
       "(0008, 0018) SOP Instance UID                    UI: 1.2.826.0.1.3680043.8.498.42955106407039211039170882102206590655\n",
       "(0008, 0050) Accession Number                    SH: '00000'\n",
       "(0008, 0060) Modality                            CS: 'MR'\n",
       "(0008, 103e) Series Description                  LO: 'T1w'\n",
       "(0010, 0010) Patient's Name                      PN: '00000'\n",
       "(0010, 0020) Patient ID                          LO: '00000'\n",
       "(0018, 0023) MR Acquisition Type                 CS: '2D'\n",
       "(0018, 0050) Slice Thickness                     DS: '5.0'\n",
       "(0018, 0081) Echo Time                           DS: None\n",
       "(0018, 0083) Number of Averages                  DS: '1.0'\n",
       "(0018, 0084) Imaging Frequency                   DS: '127.742365'\n",
       "(0018, 0085) Imaged Nucleus                      SH: '1H'\n",
       "(0018, 0086) Echo Number(s)                      IS: '1'\n",
       "(0018, 0087) Magnetic Field Strength             DS: '3.0'\n",
       "(0018, 0088) Spacing Between Slices              DS: '1.0'\n",
       "(0018, 0091) Echo Train Length                   IS: '1'\n",
       "(0018, 0093) Percent Sampling                    DS: '100.0'\n",
       "(0018, 0094) Percent Phase Field of View         DS: '80.0'\n",
       "(0018, 0095) Pixel Bandwidth                     DS: '122.07'\n",
       "(0018, 1094) Trigger Window                      IS: '0'\n",
       "(0018, 1100) Reconstruction Diameter             DS: '240.0'\n",
       "(0018, 1310) Acquisition Matrix                  US: [0, 320, 224, 0]\n",
       "(0018, 1312) In-plane Phase Encoding Direction   CS: 'ROW'\n",
       "(0018, 1314) Flip Angle                          DS: '73.0'\n",
       "(0018, 1316) SAR                                 DS: '1.74313'\n",
       "(0018, 5100) Patient Position                    CS: 'HFS'\n",
       "(0020, 000d) Study Instance UID                  UI: 1.2.826.0.1.3680043.8.498.21557373119637153130481842401167746353\n",
       "(0020, 000e) Series Instance UID                 UI: 1.2.826.0.1.3680043.8.498.10088481353579602776972549292627734001\n",
       "(0020, 0011) Series Number                       IS: '8'\n",
       "(0020, 0013) Instance Number                     IS: '24'\n",
       "(0020, 0032) Image Position (Patient)            DS: [-117.109, -142.138, 43.6237]\n",
       "(0020, 0037) Image Orientation (Patient)         DS: [1, -0, 0, -0, 1, 0]\n",
       "(0020, 0060) Laterality                          CS: ''\n",
       "(0020, 1040) Position Reference Indicator        LO: ''\n",
       "(0020, 1041) Slice Location                      DS: '43.62374878'\n",
       "(0020, 9057) In-Stack Position Number            UL: 24\n",
       "(0028, 0002) Samples per Pixel                   US: 1\n",
       "(0028, 0004) Photometric Interpretation          CS: 'MONOCHROME2'\n",
       "(0028, 0010) Rows                                US: 512\n",
       "(0028, 0011) Columns                             US: 512\n",
       "(0028, 0030) Pixel Spacing                       DS: [0.468800008296967, 0.468800008296967]\n",
       "(0028, 0100) Bits Allocated                      US: 16\n",
       "(0028, 0101) Bits Stored                         US: 16\n",
       "(0028, 0102) High Bit                            US: 15\n",
       "(0028, 0103) Pixel Representation                US: 1\n",
       "(0028, 1050) Window Center                       DS: '1843.0'\n",
       "(0028, 1051) Window Width                        DS: '3686.0'\n",
       "(0028, 1052) Rescale Intercept                   DS: '0.0'\n",
       "(0028, 1053) Rescale Slope                       DS: '1.0'\n",
       "(0028, 1054) Rescale Type                        LO: 'US'\n",
       "(7fe0, 0010) Pixel Data                          OW: Array of 524288 elements"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = pydicom.dcmread(root_dir+'/train/00000/T1w/Image-24.dcm')\n",
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "deluxe-notion",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.image.AxesImage at 0x884a2c8e20>"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 24448 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "def get_image(data):\n",
    "    '''\n",
    "    Returns the image data as a numpy array.\n",
    "    '''  \n",
    "    if np.max(data.pixel_array)==0:\n",
    "        img = data.pixel_array\n",
    "    else:\n",
    "        img = data.pixel_array/np.max(data.pixel_array)\n",
    "        img = (img * 255).astype(np.uint8)\n",
    "        \n",
    "    return img\n",
    "\n",
    "data = pydicom.dcmread(root_dir+'/train/00000/T1w/Image-24.dcm')\n",
    "img = get_image(data)\n",
    "plt.imshow(img, cmap='gray')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "established-poison",
   "metadata": {},
   "outputs": [],
   "source": [
    "def sorted_image_dirs(path: str):\n",
    "    '''\n",
    "    Sorts the list of image directories by image number in a path\n",
    "    '''\n",
    "    dirs = glob.glob(path+'*')\n",
    "    dirs.sort(key=lambda x: int(x.split('/')[-1].split('-')[-1].split('.')[0]))\n",
    "    \n",
    "    return dirs\n",
    "\n",
    "\n",
    "def get_all_images(path: str):\n",
    "    '''\n",
    "    Returns a list of (non blank) images from a given path (of shape [non_blank_image_count, 512, 512])\n",
    "    '''\n",
    "    image_dirs = sorted_image_dirs(path)\n",
    "    images = []\n",
    "    \n",
    "    for directory in image_dirs:\n",
    "        data = pydicom.dcmread(directory)\n",
    "        img = get_image(data)\n",
    "        \n",
    "        # Exclude the blank images\n",
    "        if np.max(img)!=0:\n",
    "            images.append(img)\n",
    "        else:\n",
    "            pass\n",
    "    \n",
    "    return images\n",
    "    \n",
    "def show_animation(images: list):\n",
    "    '''\n",
    "    Displays an animation from the list of images.\n",
    "    \n",
    "    set: matplotlib.rcParams['animation.html'] = 'jshtml'\n",
    "    \n",
    "    '''\n",
    "    fig = plt.figure(figsize=(6, 6))\n",
    "    plt.axis('off')\n",
    "    im = plt.imshow(images[0], cmap='gray')\n",
    "    \n",
    "    def animate_func(i):\n",
    "        im.set_array(images[i])\n",
    "        return [im]\n",
    "    \n",
    "    return matplotlib.animation.FuncAnimation(fig, animate_func, frames = len(images), interval = 20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "spread-report",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "No of images: 74\n",
      "MGMT:  0\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 1094784 characters]\n",
      "text/plain": [
       "<Figure size 2160x2160 with 74 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# A random patient - patient 10\n",
    "patient = 10\n",
    "\n",
    "flair_images = get_all_images(df['flair'][patient])\n",
    "print('No of images:', len(flair_images))\n",
    "print('MGMT: ', df['MGMT_value'][patient])\n",
    "\n",
    "fig = plt.figure(figsize=(30,30))\n",
    "\n",
    "c = 1\n",
    "for image in flair_images:\n",
    "    ax = fig.add_subplot(len(flair_images)//10+1, 10, c)\n",
    "    ax.imshow(image, cmap='gray')\n",
    "    c+=1\n",
    "    \n",
    "    plt.axis('off')\n",
    "    \n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "fatal-blend",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_image_plane(data):\n",
    "    '''\n",
    "    Returns the MRI's plane from the dicom data.\n",
    "    \n",
    "    '''\n",
    "    x1,y1,_,x2,y2,_ = [round(j) for j in data.ImageOrientationPatient]\n",
    "    cords = [x1,y1,x2,y2]\n",
    "\n",
    "    if cords == [1,0,0,0]:\n",
    "        return 'coronal'\n",
    "    if cords == [1,0,0,1]:\n",
    "        return 'axial'\n",
    "    if cords == [0,1,0,0]:\n",
    "        return 'sagittal'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "congressional-scene",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_middle_image(path: str, plane=False):\n",
    "    '''\n",
    "    Returns the middle image from the path\n",
    "    \n",
    "    if plane=True returns the plane\n",
    "    '''\n",
    "    image_dirs = sorted_image_dirs(path)\n",
    "\n",
    "    dicom = pydicom.dcmread(image_dirs[len(image_dirs)//2])\n",
    "    img = get_image(dicom)\n",
    "    plane = get_image_plane(dicom)\n",
    "    \n",
    "    if plane:\n",
    "        return img, plane\n",
    "    else:\n",
    "        return img"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "imposed-boundary",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 620244 characters]\n",
      "text/plain": [
       "<Figure size 2520x1440 with 20 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure(figsize=(35,20))\n",
    "\n",
    "seq_types = ['flair', 't1w', 't1wce', 't2w']\n",
    "\n",
    "for i in range(20):\n",
    "    \n",
    "    patient = np.random.randint(low=0, high=len(df))\n",
    "    seq_type = np.random.choice(seq_types)\n",
    "\n",
    "    # path for the randomly selected image and sequence type\n",
    "    seq_path = df[seq_type][patient]\n",
    "\n",
    "    # Get the middle image and plane from the path\n",
    "    img, plane = get_middle_image(seq_path, plane=True)\n",
    "    \n",
    "    patient_id, mgmt = df['BraTS21ID_full'][patient], df['MGMT_value'][patient]\n",
    "    \n",
    "    ax = fig.add_subplot(4,5,i+1)\n",
    "    ax.imshow(img, cmap='gray')\n",
    "    plt.title(f'ID: {patient_id}, MGMT_value: {mgmt}, Plane: {plane}, Seq_type: {seq_type}')\n",
    "    plt.axis('off')\n",
    "    plt.savefig(root_dir+'MGMT_Random')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "spatial-exception",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 235500 characters]\n",
      "text/plain": [
       "<Figure size 2520x1440 with 4 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure(figsize=(35,20))\n",
    "\n",
    "seq_types = ['flair', 't1w', 't1wce', 't2w']\n",
    "\n",
    "patient = 0  # The first patient\n",
    "\n",
    "for i in range(4):\n",
    "    \n",
    "    seq_type = seq_types[i]\n",
    "    seq_path = df[seq_type][patient]\n",
    "\n",
    "    # Get the middle image and plane from the path\n",
    "    img, plane = get_middle_image(seq_path, plane=True)\n",
    "    \n",
    "    patient_id, mgmt= df['BraTS21ID_full'][patient], df['MGMT_value'][patient]\n",
    "    \n",
    "    ax = fig.add_subplot(1,4,i+1)\n",
    "    ax.imshow(img, cmap='gray')\n",
    "    plt.title(f'ID: {patient_id}, MGMT_value: {mgmt},{seq_type}')\n",
    "    plt.axis('off')\n",
    "    plt.savefig(root_dir+'diffrentscans')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "swiss-charleston",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 226256 characters]\n",
      "text/plain": [
       "<Figure size 2520x1440 with 4 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure(figsize=(35,20))\n",
    "\n",
    "seq_types = ['flair', 't1w', 't1wce', 't2w']\n",
    "\n",
    "patient = 2  \n",
    "\n",
    "for i in range(4):\n",
    "    \n",
    "    seq_type = seq_types[i]\n",
    "    seq_path = df[seq_type][patient]\n",
    "\n",
    "    # Get the middle image and plane from the path\n",
    "    img, plane = get_middle_image(seq_path, plane=True)\n",
    "    \n",
    "    patient_id, mgmt= df['BraTS21ID_full'][patient], df['MGMT_value'][patient]\n",
    "    \n",
    "    ax = fig.add_subplot(1,4,i+1)\n",
    "    ax.imshow(img, cmap='gray')\n",
    "    plt.title(f'ID: {patient_id}, MGMT_value: {mgmt}, {seq_type}')\n",
    "    plt.axis('off')\n",
    "    plt.savefig(root_dir+'MGMT0')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "second-mortality",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 585/585 [19:01<00:00,  1.95s/it] \n"
     ]
    },
    {
     "data": {
      "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>BraTS21ID_full</th>\n",
       "      <th>flair_axis</th>\n",
       "      <th>t1w_axis</th>\n",
       "      <th>t1wce_axis</th>\n",
       "      <th>t2w_axis</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>00000</td>\n",
       "      <td>coronal</td>\n",
       "      <td>axial</td>\n",
       "      <td>coronal</td>\n",
       "      <td>sagittal</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>00002</td>\n",
       "      <td>sagittal</td>\n",
       "      <td>axial</td>\n",
       "      <td>coronal</td>\n",
       "      <td>sagittal</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>00003</td>\n",
       "      <td>sagittal</td>\n",
       "      <td>axial</td>\n",
       "      <td>coronal</td>\n",
       "      <td>sagittal</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>00005</td>\n",
       "      <td>coronal</td>\n",
       "      <td>axial</td>\n",
       "      <td>coronal</td>\n",
       "      <td>sagittal</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>00006</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>coronal</td>\n",
       "      <td>sagittal</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>580</th>\n",
       "      <td>01005</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>581</th>\n",
       "      <td>01007</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>582</th>\n",
       "      <td>01008</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>583</th>\n",
       "      <td>01009</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>584</th>\n",
       "      <td>01010</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "      <td>axial</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>585 rows × 5 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "    BraTS21ID_full flair_axis t1w_axis t1wce_axis  t2w_axis\n",
       "0    00000          coronal    axial    coronal    sagittal\n",
       "1    00002          sagittal   axial    coronal    sagittal\n",
       "2    00003          sagittal   axial    coronal    sagittal\n",
       "3    00005          coronal    axial    coronal    sagittal\n",
       "4    00006          axial      axial    coronal    sagittal\n",
       "..     ...            ...        ...        ...         ...\n",
       "580  01005          axial      axial    axial      axial   \n",
       "581  01007          axial      axial    axial      axial   \n",
       "582  01008          axial      axial    axial      axial   \n",
       "583  01009          axial      axial    axial      axial   \n",
       "584  01010          axial      axial    axial      axial   \n",
       "\n",
       "[585 rows x 5 columns]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "seq_types = ['flair', 't1w', 't1wce', 't2w']\n",
    "\n",
    "seq_axes = {'flair':[], 't1w':[], 't1wce':[], 't2w':[]}\n",
    "\n",
    "for index in tqdm(range(len(df))):\n",
    "    \n",
    "    for seq in seq_types:\n",
    "        \n",
    "        seq_path = df[seq][index]\n",
    "\n",
    "        # Get the middle image from the path\n",
    "        img, plane = get_middle_image(seq_path, plane=True)\n",
    "    \n",
    "        seq_axes[seq].append(plane)\n",
    "        \n",
    "# Add the axes to the dataframe\n",
    "df['flair_axis'] = seq_axes['flair']\n",
    "df['t1w_axis'] = seq_axes['t1w']\n",
    "df['t1wce_axis'] = seq_axes['t1wce']\n",
    "df['t2w_axis'] = seq_axes['t2w']\n",
    "\n",
    "# Print the axes with the respective patient ID\n",
    "df[['BraTS21ID_full', 'flair_axis', 't1w_axis', 't1wce_axis', 't2w_axis']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "varying-oxford",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 21928 characters]\n",
      "text/plain": [
       "<Figure size 2160x720 with 4 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 0 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = plt.subplots(1,4, figsize=(30,10))\n",
    "\n",
    "sns.countplot(x='flair_axis', data=df, ax=ax[0])\n",
    "sns.countplot(x='t1w_axis', data=df, ax=ax[1])\n",
    "sns.countplot(x='t1wce_axis', data=df, ax=ax[2])\n",
    "sns.countplot(x='t2w_axis', data=df, ax=ax[3])\n",
    "\n",
    "plt.show()\n",
    "plt.savefig(root_dir+'axis')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "quarterly-hawaii",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
