{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport glob\nimport random\n\nimport numpy as np\nimport pandas as pd\nimport pydicom\nimport matplotlib.pyplot as plt\nimport seaborn","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:24.095417Z","iopub.execute_input":"2021-08-02T07:14:24.095773Z","iopub.status.idle":"2021-08-02T07:14:24.101839Z","shell.execute_reply.started":"2021-08-02T07:14:24.095722Z","shell.execute_reply":"2021-08-02T07:14:24.100766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv(\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/train_labels.csv\")\ntrain_df","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:24.103337Z","iopub.execute_input":"2021-08-02T07:14:24.103806Z","iopub.status.idle":"2021-08-02T07:14:24.125907Z","shell.execute_reply.started":"2021-08-02T07:14:24.103769Z","shell.execute_reply":"2021-08-02T07:14:24.125227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"There are {len(train_df)} patients in the dataset.\")","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:24.128715Z","iopub.execute_input":"2021-08-02T07:14:24.128949Z","iopub.status.idle":"2021-08-02T07:14:24.136156Z","shell.execute_reply.started":"2021-08-02T07:14:24.128925Z","shell.execute_reply":"2021-08-02T07:14:24.135291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(5,5))\nseaborn.countplot(data=train_df, x=\"MGMT_value\")\nprint(train_df['MGMT_value'].value_counts())","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:24.138029Z","iopub.execute_input":"2021-08-02T07:14:24.138408Z","iopub.status.idle":"2021-08-02T07:14:24.247866Z","shell.execute_reply.started":"2021-08-02T07:14:24.138374Z","shell.execute_reply":"2021-08-02T07:14:24.246964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"frq, bins, fig = plt.hist(train_df[\"BraTS21ID\"])\nplt.ylabel(\"frequency\")\nplt.xlabel(\"BraTSID\")\nplt.grid()\nplt.show()\nprint(\"frequency array :\", frq)\nprint(\"range array :\", bins)","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:24.249209Z","iopub.execute_input":"2021-08-02T07:14:24.249537Z","iopub.status.idle":"2021-08-02T07:14:24.399437Z","shell.execute_reply.started":"2021-08-02T07:14:24.249502Z","shell.execute_reply":"2021-08-02T07:14:24.398694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"root_dir = \"../input/rsna-miccai-brain-tumor-radiogenomic-classification/train/\"\ntypes = [\"FLAIR\",\"T1w\",\"T1wCE\",\"T2w\"]\n_new = []\n\nfor index, num in enumerate(train_df[\"BraTS21ID\"]):\n    a = []\n    for i in range(len(types)):\n        _path = root_dir + str(num).zfill(5)\n        tpath = os.path.join(_path, types[i])\n        lists = os.listdir(tpath)\n        a.append(len(lists))\n    \n    _new.append([train_df[\"BraTS21ID\"].iloc[index],train_df[\"MGMT_value\"].iloc[index],a[0], a[1], a[2], a[3]])\n\nnew_df = pd.DataFrame(_new)\nnew_df.columns = [\"BraTS21Id\", \"MGMT_value\",\"FLAIR\", \"T1w\", \"T1wCE\", \"T2w\"]\n\nnew_df","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:24.400638Z","iopub.execute_input":"2021-08-02T07:14:24.400985Z","iopub.status.idle":"2021-08-02T07:14:25.179212Z","shell.execute_reply.started":"2021-08-02T07:14:24.400950Z","shell.execute_reply":"2021-08-02T07:14:25.178389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def dicom2array(path, fix_monochrome=True):\n    dicom = pydicom.read_file(path)\n    data = dicom.pixel_array\n    \n    # depending on value, image can be look inverted, so fix this\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n    \n    data = data - np.min(data)\n    data = data / np.max(data)    # 0~1\n    data = (data * 255).astype(np.uint8)    # 0~255\n    \n    return data","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:25.181883Z","iopub.execute_input":"2021-08-02T07:14:25.182154Z","iopub.status.idle":"2021-08-02T07:14:25.189621Z","shell.execute_reply.started":"2021-08-02T07:14:25.182125Z","shell.execute_reply":"2021-08-02T07:14:25.188890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def visualize_sample(\n    brats21id, \n    slice_i, \n    mgmt_value, \n    types=(\"FLAIR\", \"T1w\", \"T1wCE\", \"T2w\")\n):\n    plt.figure(figsize=(16, 5))\n    \n    patient_path = os.path.join(\n        \"../input/rsna-miccai-brain-tumor-radiogenomic-classification/train/\", \n        str(brats21id).zfill(5)\n    )\n    \n    for i, t in enumerate(types, 1):\n        t_paths = sorted(\n            glob.glob(os.path.join(patient_path, t, \"*\")),\n            key=lambda x: int(x[:-4].split(\"-\")[-1])\n        )\n        data = dicom2array(t_paths[int(len(t_paths) * slice_i)])\n        plt.subplot(1, 4, i)\n        plt.imshow(data, cmap=\"gray\")\n        plt.title(f\"{t}\", fontsize=16)\n        plt.axis(\"off\")\n        \n    plt.suptitle(f\"MGMT_value: {mgmt_value}\", fontsize=16)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:25.191455Z","iopub.execute_input":"2021-08-02T07:14:25.191792Z","iopub.status.idle":"2021-08-02T07:14:25.200456Z","shell.execute_reply.started":"2021-08-02T07:14:25.191756Z","shell.execute_reply":"2021-08-02T07:14:25.199459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in random.sample(range(train_df.shape[0]), 5):\n    _brats21id = train_df.iloc[i][\"BraTS21ID\"]\n    _mgmt_value = train_df.iloc[i][\"MGMT_value\"]\n    visualize_sample(brats21id=_brats21id, mgmt_value=_mgmt_value, slice_i=0.5)","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:25.202783Z","iopub.execute_input":"2021-08-02T07:14:25.203247Z","iopub.status.idle":"2021-08-02T07:14:26.768844Z","shell.execute_reply.started":"2021-08-02T07:14:25.203082Z","shell.execute_reply":"2021-08-02T07:14:26.768108Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in random.sample(range(train_df.shape[0]), 5):\n    _brats21id = train_df.iloc[i][\"BraTS21ID\"]\n    _mgmt_value = train_df.iloc[i][\"MGMT_value\"]\n    visualize_sample(brats21id=_brats21id, mgmt_value=_mgmt_value, slice_i=0.3)","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:26.770318Z","iopub.execute_input":"2021-08-02T07:14:26.770851Z","iopub.status.idle":"2021-08-02T07:14:28.229822Z","shell.execute_reply.started":"2021-08-02T07:14:26.770810Z","shell.execute_reply":"2021-08-02T07:14:28.229051Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import animation, rc\nrc('animation', html='jshtml')\n\n\ndef create_ani(ims):\n    fig = plt.figure(figsize=(6,6))\n    plt.axis('off')\n    im = plt.imshow(ims[0], cmap=\"gray\")\n    \n    def animate_func(i):\n        im.set_array(ims[i])\n        return [im]\n    \n    return animation.FuncAnimation(fig, animate_func, frames=len(ims), interval=1000//24)","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:28.231072Z","iopub.execute_input":"2021-08-02T07:14:28.231418Z","iopub.status.idle":"2021-08-02T07:14:28.237505Z","shell.execute_reply.started":"2021-08-02T07:14:28.231380Z","shell.execute_reply":"2021-08-02T07:14:28.236410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dicom_line(path):\n    t_paths = sorted(\n            glob.glob(os.path.join(path, \"*\")),\n            key=lambda x: int(x[:-4].split(\"-\")[-1])\n        )\n    \n    images = []\n    for filename in t_paths:\n        data = dicom2array(filename)\n        if data.max() == 0:\n            continue\n        images.append(data)\n    \n    return images","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:28.239149Z","iopub.execute_input":"2021-08-02T07:14:28.239718Z","iopub.status.idle":"2021-08-02T07:14:28.247920Z","shell.execute_reply.started":"2021-08-02T07:14:28.239678Z","shell.execute_reply":"2021-08-02T07:14:28.247160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images = load_dicom_line(\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/train/00002/FLAIR\")\ncreate_ani(images)","metadata":{"execution":{"iopub.status.busy":"2021-08-02T07:14:28.249044Z","iopub.execute_input":"2021-08-02T07:14:28.249564Z","iopub.status.idle":"2021-08-02T07:14:31.954157Z","shell.execute_reply.started":"2021-08-02T07:14:28.249526Z","shell.execute_reply":"2021-08-02T07:14:31.953202Z"},"trusted":true},"execution_count":null,"outputs":[]}]}