{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":99552,"databundleVersionId":13851420,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport pydicom\n\nimport os\n\nfrom tqdm.notebook import tqdm\n\nsns.set_style(\"whitegrid\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-10-02T19:06:27.937549Z","iopub.execute_input":"2025-10-02T19:06:27.937779Z","iopub.status.idle":"2025-10-02T19:06:33.452234Z","shell.execute_reply.started":"2025-10-02T19:06:27.937758Z","shell.execute_reply":"2025-10-02T19:06:33.450978Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"BASE_PATH = '/kaggle/input/rsna-intracranial-aneurysm-detection/' # Make sure this path is correct\n\ntrain_df = pd.read_csv(os.path.join(BASE_PATH, 'train.csv'))\nlocalizers_df = pd.read_csv(os.path.join(BASE_PATH, 'train_localizers.csv'))\n\nprint(f\"Number of scans in train_df: {len(train_df)}\")\ntrain_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T19:06:33.454549Z","iopub.execute_input":"2025-10-02T19:06:33.455029Z","iopub.status.idle":"2025-10-02T19:06:33.546191Z","shell.execute_reply.started":"2025-10-02T19:06:33.454993Z","shell.execute_reply":"2025-10-02T19:06:33.545068Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(8, 5))\nax = sns.countplot(data=train_df, x='Aneurysm Present', palette='viridis')\n\ntotal = len(train_df)\nfor p in ax.patches:\n    percentage = f'{100 * p.get_height() / total:.1f}%'\n    x = p.get_x() + p.get_width() / 2\n    y = p.get_height()\n    ax.annotate(percentage, (x, y), ha='center', va='bottom')\n\nplt.title('Distribution of \"Aneurysm Present\" Target', fontsize=16)\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T19:07:16.641071Z","iopub.execute_input":"2025-10-02T19:07:16.641442Z","iopub.status.idle":"2025-10-02T19:07:16.966018Z","shell.execute_reply.started":"2025-10-02T19:07:16.641416Z","shell.execute_reply":"2025-10-02T19:07:16.964887Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fig, axes = plt.subplots(1, 2, figsize=(16, 6))\n\nsns.histplot(data=train_df, x='PatientAge', hue='Aneurysm Present', kde=True, ax=axes[0], palette='magma')\naxes[0].set_title('Age Distribution by Aneurysm Presence')\n\nsns.countplot(data=train_df, x='PatientSex', hue='Aneurysm Present', ax=axes[1], palette='plasma')\naxes[1].set_title('Sex Distribution by Aneurysm Presence')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T19:07:17.027736Z","iopub.execute_input":"2025-10-02T19:07:17.028168Z","iopub.status.idle":"2025-10-02T19:07:17.984793Z","shell.execute_reply.started":"2025-10-02T19:07:17.028131Z","shell.execute_reply":"2025-10-02T19:07:17.983036Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(10, 8))\nsns.countplot(data=localizers_df, y='location', order=localizers_df['location'].value_counts().index, palette='crest')\nplt.title('Frequency of Aneurysm Locations', fontsize=16)\nplt.xlabel('Count')\nplt.ylabel('Anatomical Location')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T19:07:17.986682Z","iopub.execute_input":"2025-10-02T19:07:17.987126Z","iopub.status.idle":"2025-10-02T19:07:18.36551Z","shell.execute_reply.started":"2025-10-02T19:07:17.98709Z","shell.execute_reply":"2025-10-02T19:07:18.364515Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"aneurysms_per_scan = localizers_df.groupby('SeriesInstanceUID').size().reset_index(name='aneurysm_count')\n\nplt.figure(figsize=(10, 5))\nsns.countplot(data=aneurysms_per_scan, x='aneurysm_count', palette='rocket')\nplt.title('Number of Aneurysms per Scan (for positive scans)', fontsize=16)\nplt.xlabel('Number of Aneurysms')\nplt.ylabel('Number of Scans')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T19:08:59.606363Z","iopub.execute_input":"2025-10-02T19:08:59.606685Z","iopub.status.idle":"2025-10-02T19:08:59.820407Z","shell.execute_reply.started":"2025-10-02T19:08:59.606663Z","shell.execute_reply":"2025-10-02T19:08:59.819342Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import ast \n\ndef view_aneurysm_in_scan(series_uid, localizers_df):\n    \"\"\"\n    Loads a 3D scan and displays the slice with the aneurysm highlighted.\n    Handles both list and dictionary coordinate formats.\n    \"\"\"\n    print(f\"Loading and visualizing scan: {series_uid}\")\n    \n    # Path to the series directory\n    series_path = os.path.join(BASE_PATH, 'series', series_uid)\n    \n    # Load all DICOM files for the series\n    dicom_files = [pydicom.dcmread(os.path.join(series_path, f)) for f in os.listdir(series_path)]\n    \n    # Sort the slices by their position along the Z-axis\n    dicom_files.sort(key=lambda x: float(x.ImagePositionPatient[2]))\n    \n    # Get the aneurysm info for this scan\n    aneurysm_info = localizers_df[localizers_df['SeriesInstanceUID'] == series_uid].iloc[0]\n    coords_str = aneurysm_info['coordinates']\n    \n    # Use ast.literal_eval to safely parse the string into a Python object (list or dict)\n    coords_obj = ast.literal_eval(coords_str)\n    \n    # Check if the parsed object is a dictionary or a list and extract coordinates\n    if isinstance(coords_obj, dict):\n        x_coord, y_coord = int(coords_obj['x']), int(coords_obj['y'])\n    elif isinstance(coords_obj, list):\n        x_coord, y_coord = int(coords_obj[0]), int(coords_obj[1])\n    else:\n        print(f\"Unknown coordinate format for series {series_uid}\")\n        return\n\n    # Find which slice the aneurysm is on using its SOPInstanceUID\n    sop_uid = aneurysm_info['SOPInstanceUID']\n    target_slice_index = -1\n    for i, s in enumerate(dicom_files):\n        if s.SOPInstanceUID == sop_uid:\n            target_slice_index = i\n            break\n            \n    if target_slice_index == -1:\n        print(\"Error: Could not find the specified slice in the series.\")\n        return\n\n    # Stack the pixel data into a 3D numpy array\n    volume = np.stack([d.pixel_array for d in dicom_files])\n    \n    # Display the target slice\n    plt.figure(figsize=(10, 10))\n    plt.imshow(volume[target_slice_index], cmap='bone')\n    \n    # Draw a circle to highlight the aneurysm\n    circle = plt.Circle((x_coord, y_coord), radius=20, color='red', fill=False, lw=2)\n    plt.gca().add_patch(circle)\n    \n    plt.title(f'Aneurysm in Scan {series_uid}\\nSlice: {target_slice_index}, Location: ({x_coord}, {y_coord})', fontsize=16)\n    plt.axis('off')\n    plt.show()\n\n# Now, when you run this, it should work correctly\npositive_series_uid = localizers_df['SeriesInstanceUID'].iloc[0]\nview_aneurysm_in_scan(positive_series_uid, localizers_df)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T19:09:03.597012Z","iopub.execute_input":"2025-10-02T19:09:03.597433Z","iopub.status.idle":"2025-10-02T19:09:09.851749Z","shell.execute_reply.started":"2025-10-02T19:09:03.597398Z","shell.execute_reply":"2025-10-02T19:09:09.850221Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}