{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "6af7e461", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:38.398920Z", "iopub.status.busy": "2025-03-25T07:56:38.398731Z", "iopub.status.idle": "2025-03-25T07:56:38.568023Z", "shell.execute_reply": "2025-03-25T07:56:38.567627Z" } }, "outputs": [], "source": [ "import sys\n", "import os\n", "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n", "\n", "# Path Configuration\n", "from tools.preprocess import *\n", "\n", "# Processing context\n", "trait = \"Melanoma\"\n", "cohort = \"GSE148949\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Melanoma\"\n", "in_cohort_dir = \"../../input/GEO/Melanoma/GSE148949\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Melanoma/GSE148949.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Melanoma/gene_data/GSE148949.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Melanoma/clinical_data/GSE148949.csv\"\n", "json_path = \"../../output/preprocess/Melanoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "997bea1c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "610f91ab", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:38.569778Z", "iopub.status.busy": "2025-03-25T07:56:38.569627Z", "iopub.status.idle": "2025-03-25T07:56:38.696659Z", "shell.execute_reply": "2025-03-25T07:56:38.696270Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE148949_family.soft.gz', 'GSE148949_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Melanoma/GSE148949/GSE148949_family.soft.gz\n", "Matrix file: ../../input/GEO/Melanoma/GSE148949/GSE148949_series_matrix.txt.gz\n", "Background Information:\n", "!Series_title\t\"BKM120 Treated WHIMs_17 Model Cohort\"\n", "!Series_summary\t\"Aberrant activation of PI3K pathway is frequently observed in triple negative breast cancer (TNBC). However single agent PI3K inhibitors have shown modest anti-tumor activity. To investigate biomarkers of response, we tested 17 TNBC PDX models with diverse genetic and proteomic background, with varying PI3K pathway signaling activities for their tumor growth response to the pan-PI3K inhibitor BKM120 as well as baseline and treatment induced proteomic changes as assessed by reverse phase protein array (RPPA). We demonstrated that PI3K inhibition induces varying degrees of tumor growth inhibition (TGI), with 5 models demonstrating over 80% TGI. BKM120 consistently reduced PI3K pathway activity as demonstrated by reduced pAKT following therapy. Several biomarkers showed significant association with resistance, including baseline levels of growth factor receptors (EGFR, pHER3 Y1197), PI3Kp85 regulatory subunit, anti-apoptotic protein BclXL, EMT (Vimentin, MMP9, IntegrinaV), NFKB pathway (IkappaB, RANKL), and intracellular signaling molecules including Caveolin, CBP, and KLF4, as well as treatment induced increase in the levels of phosphorylated forms of Aurora kinases. Sensitivity was associated with higher baseline levels of proapoptotic markers (Bak and Caspase 3) and higher number of markers being changed following BKM120 therapy. Interestingly, markers indicating PI3K pathway signaling activation at baseline were not significantly correlated to %TGI. These results provide important insights in biomarker development for PI3K inhibitors in TNBC.\"\n", "!Series_overall_design\t\"Molecular profiling was completed on 54 microarrays representing different passages and human counterparts for 17 triple negative breast cancer models using 2 channel (tumor:reference) whole human genome Agilent arrays.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Total RNA from 10 human cell lines: 1_Adenocarcinoma, mammary gland 2_Hepatoblastoma, liver 3_Adenocarcinoma, cervix 4_Embryonal carcinoma, testis 5_Glioblastoma, brain 6_Melanoma 7_Liposarcoma 8_Histiocytic Lymphoma; macrophage; histocyte 9_ Lymphoblastic leukemia, T lymphoblast 10_Plasmacytoma; myeloma; B lymphocyte. Also, mRNA spiked in from MCF7 and ME16C.']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # Read the matrix file to obtain background information and sample characteristics data\n", " background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", " clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # Explicitly print out all the background information and the sample characteristics dictionary\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "44db539a", "metadata": {}, "source": [ "### Step 2: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 3, "id": "a201e7c6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:38.698441Z", "iopub.status.busy": "2025-03-25T07:56:38.698322Z", "iopub.status.idle": "2025-03-25T07:56:38.810330Z", "shell.execute_reply": "2025-03-25T07:56:38.809994Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE148949_family.soft.gz', 'GSE148949_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Melanoma/GSE148949/GSE148949_family.soft.gz\n", "Matrix file: ../../input/GEO/Melanoma/GSE148949/GSE148949_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"BKM120 Treated WHIMs_17 Model Cohort\"\n", "!Series_summary\t\"Aberrant activation of PI3K pathway is frequently observed in triple negative breast cancer (TNBC). However single agent PI3K inhibitors have shown modest anti-tumor activity. To investigate biomarkers of response, we tested 17 TNBC PDX models with diverse genetic and proteomic background, with varying PI3K pathway signaling activities for their tumor growth response to the pan-PI3K inhibitor BKM120 as well as baseline and treatment induced proteomic changes as assessed by reverse phase protein array (RPPA). We demonstrated that PI3K inhibition induces varying degrees of tumor growth inhibition (TGI), with 5 models demonstrating over 80% TGI. BKM120 consistently reduced PI3K pathway activity as demonstrated by reduced pAKT following therapy. Several biomarkers showed significant association with resistance, including baseline levels of growth factor receptors (EGFR, pHER3 Y1197), PI3Kp85 regulatory subunit, anti-apoptotic protein BclXL, EMT (Vimentin, MMP9, IntegrinaV), NFKB pathway (IkappaB, RANKL), and intracellular signaling molecules including Caveolin, CBP, and KLF4, as well as treatment induced increase in the levels of phosphorylated forms of Aurora kinases. Sensitivity was associated with higher baseline levels of proapoptotic markers (Bak and Caspase 3) and higher number of markers being changed following BKM120 therapy. Interestingly, markers indicating PI3K pathway signaling activation at baseline were not significantly correlated to %TGI. These results provide important insights in biomarker development for PI3K inhibitors in TNBC.\"\n", "!Series_overall_design\t\"Molecular profiling was completed on 54 microarrays representing different passages and human counterparts for 17 triple negative breast cancer models using 2 channel (tumor:reference) whole human genome Agilent arrays.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Total RNA from 10 human cell lines: 1_Adenocarcinoma, mammary gland 2_Hepatoblastoma, liver 3_Adenocarcinoma, cervix 4_Embryonal carcinoma, testis 5_Glioblastoma, brain 6_Melanoma 7_Liposarcoma 8_Histiocytic Lymphoma; macrophage; histocyte 9_ Lymphoblastic leukemia, T lymphoblast 10_Plasmacytoma; myeloma; B lymphocyte. Also, mRNA spiked in from MCF7 and ME16C.']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # Read the matrix file to obtain background information and sample characteristics data\n", " background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", " clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # Explicitly print out all the background information and the sample characteristics dictionary\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "b137c665", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "75efbabe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:38.811783Z", "iopub.status.busy": "2025-03-25T07:56:38.811660Z", "iopub.status.idle": "2025-03-25T07:56:38.818836Z", "shell.execute_reply": "2025-03-25T07:56:38.818509Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import re\n", "import json\n", "from typing import Dict, Any, Callable, Optional, List\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series summary and overall design, this dataset appears to contain gene expression data\n", "# using Agilent microarrays for TNBC (triple negative breast cancer) models\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Looking at the Sample Characteristics Dictionary, we need to check for trait, age, and gender\n", "\n", "# For trait (Melanoma):\n", "# The sample characteristics at key 0 mention \"Melanoma\" as one of the tissue types in a mixture,\n", "# but it doesn't contain information about which samples are Melanoma and which aren't.\n", "# This appears to be a reference RNA mixture, not individual Melanoma samples.\n", "trait_row = None\n", "\n", "# For age and gender:\n", "# No information about age or gender is provided in the sample characteristics\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "# Since we don't have data for any of these variables, we'll create placeholder functions\n", "\n", "def convert_trait(value):\n", " # This function won't be used since trait_row is None\n", " if pd.isna(value) or value is None:\n", " return None\n", " value_str = str(value)\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " if \"melanoma\" in value_str.lower():\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " # This function won't be used since age_row is None\n", " if pd.isna(value) or value is None:\n", " return None\n", " value_str = str(value)\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " try:\n", " return float(value_str)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " # This function won't be used since gender_row is None\n", " if pd.isna(value) or value is None:\n", " return None\n", " value_str = str(value)\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " value_lower = value_str.lower()\n", " if \"female\" in value_lower or \"f\" == value_lower:\n", " return 0\n", " elif \"male\" in value_lower or \"m\" == value_lower:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial cohort information\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Skip this step as trait_row is None, indicating clinical data is not available for our purposes\n" ] }, { "cell_type": "markdown", "id": "1069154b", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 5, "id": "a1d0a4e3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:38.820196Z", "iopub.status.busy": "2025-03-25T07:56:38.820079Z", "iopub.status.idle": "2025-03-25T07:56:39.032949Z", "shell.execute_reply": "2025-03-25T07:56:39.032577Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "No subseries references found in the first 1000 lines of the SOFT file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 29657\n", "First 20 gene/probe identifiers:\n", "Index(['1/2-SBSRNA4', '41334', '41335', '41336', '41337', '41338', '41339',\n", " '41340', '41341', '41342', '41343', '41344', '41518', '41519', '41520',\n", " '41521', '41522', '41523', '41524', '41525'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "be7c0d3e", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 6, "id": "33193465", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:39.034672Z", "iopub.status.busy": "2025-03-25T07:56:39.034545Z", "iopub.status.idle": "2025-03-25T07:56:39.036573Z", "shell.execute_reply": "2025-03-25T07:56:39.036242Z" } }, "outputs": [], "source": [ "# These identifiers don't appear to be standard human gene symbols\n", "# The presence of numeric identifiers like '41334', '41335' etc. suggests\n", "# these may be probe or feature IDs rather than actual gene symbols\n", "# These would likely need to be mapped to standard gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "a70c22a8", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 7, "id": "985467a8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:39.038374Z", "iopub.status.busy": "2025-03-25T07:56:39.038133Z", "iopub.status.idle": "2025-03-25T07:56:40.905988Z", "shell.execute_reply": "2025-03-25T07:56:40.905615Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M'], 'ORF': ['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M']}\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "30dcdaee", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 8, "id": "eb35e6c3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:40.907882Z", "iopub.status.busy": "2025-03-25T07:56:40.907745Z", "iopub.status.idle": "2025-03-25T07:56:41.105246Z", "shell.execute_reply": "2025-03-25T07:56:41.104866Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data IDs (first 5): ['1/2-SBSRNA4', '41334', '41335', '41336', '41337']\n", "Gene annotation columns: ['ID', 'ORF']\n", "\n", "Searching for platform information in SOFT file...\n", "No platform information found in SOFT file\n", "Using gene annotation as mapping. Sample (first 5 rows):\n", "{'Gene': ['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M'], 'ID': ['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M']}\n", "\n", "Gene expression data after mapping:\n", "Number of genes: 18460\n", "Sample of gene IDs (first 10): ['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS']\n", "Sample of expression values (first 5 rows, first 3 columns):\n", " GSM4486560 GSM4486561 GSM4486562\n", "Gene \n", "A1BG -0.248285 0.177796 0.157001\n", "A1BG-AS1 0.249204 -0.177283 0.026934\n", "A1CF -2.264265 -1.703735 -1.728858\n", "A2LD1 1.198356 1.538781 1.500333\n", "A2M -1.232422 -2.352890 -1.300777\n" ] } ], "source": [ "# Examine both datasets to understand what we're mapping\n", "print(\"Gene expression data IDs (first 5):\", gene_data.index[:5].tolist())\n", "\n", "# Looking at annotation data columns\n", "print(\"Gene annotation columns:\", gene_annotation.columns.tolist())\n", "\n", "# It appears the annotation data format is unusual - ID column already contains gene symbols\n", "# Based on the gene annotation preview, the 'ID' column contains gene symbols like 'A1BG', 'A2M'\n", "# while the gene expression data has numeric IDs like '41334'\n", "# This suggests we need a different mapping method\n", "\n", "# Try to get the gene mapping from the soft file in a different way\n", "# Let's look for platform information in the SOFT file that might help with the mapping\n", "print(\"\\nSearching for platform information in SOFT file...\")\n", "\n", "with gzip.open(soft_file, 'rt') as f:\n", " platform_lines = []\n", " for i, line in enumerate(f):\n", " if '!Platform_table_begin' in line:\n", " # Found the platform table, read until end\n", " platform_lines.append(line.strip())\n", " for platform_line in f:\n", " platform_lines.append(platform_line.strip())\n", " if '!Platform_table_end' in platform_line:\n", " break\n", " break\n", " if i > 5000: # Limit search \n", " break\n", "\n", "# Check if we found platform information\n", "if platform_lines:\n", " print(f\"Found platform information - first 5 lines of {len(platform_lines)} total lines:\")\n", " for line in platform_lines[:5]:\n", " print(line)\n", " \n", " # Create a mapping dataframe from the platform information\n", " if len(platform_lines) > 2: # Ensure we have header and data\n", " platform_df = pd.read_csv(io.StringIO('\\n'.join(platform_lines[1:-1])), sep='\\t')\n", " print(\"\\nPlatform mapping dataframe columns:\", platform_df.columns.tolist())\n", " print(preview_df(platform_df))\n", " \n", " # Check if there are ID and GENE_SYMBOL or similar columns\n", " id_col = next((col for col in platform_df.columns if 'ID' in col.upper()), None)\n", " gene_col = next((col for col in platform_df.columns \n", " if 'GENE' in col.upper() or 'SYMBOL' in col.upper() or 'NAME' in col.upper()), None)\n", " \n", " if id_col and gene_col:\n", " print(f\"\\nUsing columns '{id_col}' and '{gene_col}' for mapping\")\n", " mapping_df = platform_df[[id_col, gene_col]].rename(columns={id_col: 'ID', gene_col: 'Gene'})\n", " mapping_df = mapping_df.dropna(subset=['Gene'])\n", " print(\"Mapping sample (first 5 rows):\")\n", " print(preview_df(mapping_df))\n", " else:\n", " print(\"\\nCould not identify appropriate ID and gene symbol columns\")\n", " # In this case, we need to create a mapping using the gene annotation data we have\n", " print(\"Creating mapping from available gene annotation data\")\n", " mapping_df = gene_annotation.rename(columns={'ID': 'Gene', 'ORF': 'ID'})\n", " print(\"Mapping sample (first 5 rows):\")\n", " print(preview_df(mapping_df))\n", "else:\n", " print(\"No platform information found in SOFT file\")\n", " # Use what we have in gene_annotation\n", " mapping_df = gene_annotation.rename(columns={'ID': 'Gene', 'ORF': 'ID'})\n", " print(\"Using gene annotation as mapping. Sample (first 5 rows):\")\n", " print(preview_df(mapping_df))\n", "\n", "# The unusual format of the gene_annotation suggests we're dealing with a special case\n", "# Let's adapt our approach based on what we found\n", "\n", "# Final mapping and gene data conversion\n", "try:\n", " # First ensure ID column is string type for proper matching\n", " if 'ID' in mapping_df.columns:\n", " mapping_df['ID'] = mapping_df['ID'].astype(str)\n", " \n", " # Apply the gene mapping to get gene expression data\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " \n", " # Print the result to verify\n", " print(\"\\nGene expression data after mapping:\")\n", " print(\"Number of genes:\", len(gene_data))\n", " print(\"Sample of gene IDs (first 10):\", gene_data.index[:10].tolist())\n", " print(\"Sample of expression values (first 5 rows, first 3 columns):\")\n", " print(gene_data.iloc[:5, :3])\n", "except Exception as e:\n", " print(f\"Error in gene mapping: {e}\")\n", " # If mapping fails, we'll need an alternative approach\n", " # For now, we'll create a basic identity mapping as a fallback\n", " print(\"Using fallback approach: treating original IDs as gene symbols\")\n", " gene_data = gene_data.copy() # Keep original data but acknowledge the limitation\n", " print(\"\\nGene expression data (without mapping):\")\n", " print(\"Number of probes:\", len(gene_data))\n", " print(\"Sample of probe IDs (first 10):\", gene_data.index[:10].tolist())\n" ] }, { "cell_type": "markdown", "id": "ecc33754", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 9, "id": "813c3b0c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:41.107104Z", "iopub.status.busy": "2025-03-25T07:56:41.106973Z", "iopub.status.idle": "2025-03-25T07:56:41.798606Z", "shell.execute_reply": "2025-03-25T07:56:41.798240Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Top 10 gene indices before normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Top 10 gene indices after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC']\n", "Shape of normalized gene data: (18221, 54)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene data to ../../output/preprocess/Melanoma/gene_data/GSE148949.csv\n", "No usable clinical/trait data available for this dataset\n", "Saved minimal clinical data to ../../output/preprocess/Melanoma/clinical_data/GSE148949.csv as no real trait data is available\n", "Abnormality detected in the cohort: GSE148949. Preprocessing failed.\n", "Final dataset usability: False\n", "Dataset processing completed\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(f\"Top 10 gene indices before normalization: {gene_data.index[:10].tolist()}\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Top 10 gene indices after normalization: {normalized_gene_data.index[:10].tolist()}\")\n", "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n", "\n", "# Create directory for gene data file if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "# Save the normalized gene data\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. At this point we must recognize that there isn't usable clinical data for this dataset\n", "# This is consistent with our prior analysis in step 3 where we found trait_row = None\n", "print(\"No usable clinical/trait data available for this dataset\")\n", "\n", "# Create a minimal DataFrame with the expected structure for the trait\n", "minimal_clinical_df = pd.DataFrame({trait: [0]}, index=[\"dummy_sample\"])\n", "\n", "# Save clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "minimal_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Saved minimal clinical data to {out_clinical_data_file} as no real trait data is available\")\n", "\n", "# 3. Since we don't have clinical data, we can't create a proper linked dataset\n", "# Instead, we'll validate that this dataset isn't usable for our analysis\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=False, # We confirmed no trait data is available\n", " is_biased=True, # Setting to True since dataset is unusable for melanoma analysis\n", " df=minimal_clinical_df, # Pass the minimal DataFrame with required structure\n", " note=\"Dataset contains gene expression data but no melanoma trait information. Background shows this is a TNBC study, not a melanoma-specific dataset.\"\n", ")\n", "\n", "print(f\"Final dataset usability: {is_usable}\")\n", "print(\"Dataset processing completed\")" ] } ], "metadata": { "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.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }