{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "211d7c9f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:33.699123Z", "iopub.status.busy": "2025-03-25T05:21:33.698870Z", "iopub.status.idle": "2025-03-25T05:21:33.867427Z", "shell.execute_reply": "2025-03-25T05:21:33.867024Z" } }, "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 = \"Glioblastoma\"\n", "cohort = \"GSE148949\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Glioblastoma\"\n", "in_cohort_dir = \"../../input/GEO/Glioblastoma/GSE148949\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Glioblastoma/GSE148949.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Glioblastoma/gene_data/GSE148949.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Glioblastoma/clinical_data/GSE148949.csv\"\n", "json_path = \"../../output/preprocess/Glioblastoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "28e2162d", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ade2f1f5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:33.868949Z", "iopub.status.busy": "2025-03-25T05:21:33.868791Z", "iopub.status.idle": "2025-03-25T05:21:34.000887Z", "shell.execute_reply": "2025-03-25T05:21:34.000469Z" } }, "outputs": [ { "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": [ "from tools.preprocess import *\n", "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. 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", "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# 4. 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" ] }, { "cell_type": "markdown", "id": "f1028912", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "1ba8e640", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:34.002245Z", "iopub.status.busy": "2025-03-25T05:21:34.002106Z", "iopub.status.idle": "2025-03-25T05:21:34.009145Z", "shell.execute_reply": "2025-03-25T05:21:34.008800Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of processed clinical data:\n", "{'sample_characteristics': [1.0]}\n", "Clinical data saved to: ../../output/preprocess/Glioblastoma/clinical_data/GSE148949.csv\n" ] } ], "source": [ "# Analyze the dataset and extract clinical features\n", "\n", "# 1. Determine Gene Expression Data Availability\n", "# Based on the background info, this dataset contains gene expression data from microarrays\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Looking at the sample characteristics dictionary\n", "# 2.1 Data Availability\n", "\n", "# For trait (Glioblastoma): \n", "# The data mentions \"5_Glioblastoma, brain\" in the tissue list\n", "trait_row = 0 # The information is in key 0\n", "\n", "# For age: No age information available\n", "age_row = None\n", "\n", "# For gender: No gender information available\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait information to binary\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract text after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if Glioblastoma is mentioned in the cell\n", " if \"Glioblastoma\" in value or \"glioblastoma\" in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age information (not available in this dataset)\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender information (not available in this dataset)\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata - Initial filtering\n", "# Trait data is available since trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info\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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # Prepare the clinical data DataFrame\n", " # Since we only have a dictionary with one key, we'll convert it to a DataFrame\n", " clinical_data = pd.DataFrame(\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", " index=['sample_characteristics']\n", " ).T\n", " \n", " # Extract clinical features using geo_select_clinical_features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the processed clinical data\n", " preview_result = preview_df(selected_clinical_df)\n", " print(\"Preview of processed clinical data:\")\n", " print(preview_result)\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "3b0f52b9", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "c5b7c352", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:34.010291Z", "iopub.status.busy": "2025-03-25T05:21:34.010171Z", "iopub.status.idle": "2025-03-25T05:21:34.234692Z", "shell.execute_reply": "2025-03-25T05:21:34.234285Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 76\n", "Header line: \"ID_REF\"\t\"GSM4486560\"\t\"GSM4486561\"\t\"GSM4486562\"\t\"GSM4486563\"\t\"GSM4486564\"\t\"GSM4486565\"\t\"GSM4486566\"\t\"GSM4486567\"\t\"GSM4486568\"\t\"GSM4486569\"\t\"GSM4486570\"\t\"GSM4486571\"\t\"GSM4486572\"\t\"GSM4486573\"\t\"GSM4486574\"\t\"GSM4486575\"\t\"GSM4486576\"\t\"GSM4486577\"\t\"GSM4486578\"\t\"GSM4486579\"\t\"GSM4486580\"\t\"GSM4486581\"\t\"GSM4486582\"\t\"GSM4486583\"\t\"GSM4486584\"\t\"GSM4486585\"\t\"GSM4486586\"\t\"GSM4486587\"\t\"GSM4486588\"\t\"GSM4486589\"\t\"GSM4486590\"\t\"GSM4486591\"\t\"GSM4486592\"\t\"GSM4486593\"\t\"GSM4486594\"\t\"GSM4486595\"\t\"GSM4486596\"\t\"GSM4486597\"\t\"GSM4486598\"\t\"GSM4486599\"\t\"GSM4486600\"\t\"GSM4486601\"\t\"GSM4486602\"\t\"GSM4486603\"\t\"GSM4486604\"\t\"GSM4486605\"\t\"GSM4486606\"\t\"GSM4486607\"\t\"GSM4486608\"\t\"GSM4486609\"\t\"GSM4486610\"\t\"GSM4486611\"\t\"GSM4486612\"\t\"GSM4486613\"\n", "First data line: \"1/2-SBSRNA4\"\t0.33017439\t0.201567061\t0.333105343\t0.328331502\t0.399451105\t0.091421952\t0.739362035\t1.227083303\t0.55493156\t0.670595195\t0.652113571\t0.661813238\t0.073208376\t0.156654784\t0.460903565\t0.696163629\t0.309558797\t0.691537309\t0.628111559\t0.776558001\t0.220756966\t0.70553541\t0.837562469\t0.693095409\t0.401351376\t-0.013755554\t-0.151698027\t0.029777109\t0.24945924\t0.171661886\t0.64370555\t0.466353074\t1.094163504\t0.830710899\t0.700539517\t0.19375483\t0.422320749\t0.410191345\t0.160999689\t0.365935083\t0.256065736\t0.12035847\t0.11864065\t0.88513491\t0.544258949\t0.210622307\t0.072464021\t0.135376959\t1.728631068\t0.017632886\t0.180763937\t0.201122391\t0.392012613\t0.90061429\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "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. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "2c4fc5f2", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "670ef264", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:34.236199Z", "iopub.status.busy": "2025-03-25T05:21:34.236066Z", "iopub.status.idle": "2025-03-25T05:21:34.238151Z", "shell.execute_reply": "2025-03-25T05:21:34.237817Z" } }, "outputs": [], "source": [ "# Review the gene identifiers provided in the data\n", "# The first few identifiers are:\n", "# '1/2-SBSRNA4', '41334', '41335', '41336', '41337', etc.\n", "\n", "# '1/2-SBSRNA4' appears to be a small non-coding RNA identifier\n", "# The numerical identifiers (41334, 41335, etc.) are likely probe IDs from a microarray platform\n", "# These are not standard human gene symbols (like BRCA1, TP53, etc.)\n", "\n", "# Therefore, these identifiers require mapping to standard gene symbols\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "9c8a57c9", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "324423db", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:34.239429Z", "iopub.status.busy": "2025-03-25T05:21:34.239315Z", "iopub.status.idle": "2025-03-25T05:21:34.265624Z", "shell.execute_reply": "2025-03-25T05:21:34.265258Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n", "Line 0: ^DATABASE = GeoMiame\n", "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n", "Line 2: !Database_institute = NCBI NLM NIH\n", "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n", "Line 4: !Database_email = geo@ncbi.nlm.nih.gov\n", "Line 5: ^SERIES = GSE148949\n", "Line 6: !Series_title = BKM120 Treated WHIMs_17 Model Cohort\n", "Line 7: !Series_geo_accession = GSE148949\n", "Line 8: !Series_status = Public on Dec 31 2020\n", "Line 9: !Series_submission_date = Apr 20 2020\n", "Line 10: !Series_last_update_date = Dec 26 2023\n", "Line 11: !Series_pubmed_id = 33371187\n", "Line 12: !Series_summary = 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", "Line 13: !Series_overall_design = 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", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_contributor = Jeremy,W,Hoog\n", "Line 16: !Series_sample_id = GSM4486560\n", "Line 17: !Series_sample_id = GSM4486561\n", "Line 18: !Series_sample_id = GSM4486562\n", "Line 19: !Series_sample_id = GSM4486563\n", "\n", "Gene annotation preview:\n", "{'ID': ['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M'], 'ORF': ['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M']}\n" ] } ], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "6105093f", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "70f00d99", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:34.267094Z", "iopub.status.busy": "2025-03-25T05:21:34.266968Z", "iopub.status.idle": "2025-03-25T05:21:40.014472Z", "shell.execute_reply": "2025-03-25T05:21:40.014077Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape: (29657, 54)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation data shape: (1631189, 2)\n", "\n", "Gene annotation column names:\n", "['ID', 'ORF']\n", "\n", "First few rows of gene annotation:\n", " ID ORF\n", "0 A1BG A1BG\n", "1 A1BG-AS1 A1BG-AS1\n", "2 A1CF A1CF\n", "3 A2LD1 A2LD1\n", "4 A2M A2M\n", "\n", "Gene mapping dataframe preview:\n", " ID Gene\n", "0 A1BG A1BG\n", "1 A1BG-AS1 A1BG-AS1\n", "2 A1CF A1CF\n", "3 A2LD1 A2LD1\n", "4 A2M A2M\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after mapping: (18460, 54)\n", "\n", "First few genes after mapping:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT',\n", " 'AAAS', 'AACS'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to: ../../output/preprocess/Glioblastoma/gene_data/GSE148949.csv\n" ] } ], "source": [ "# Let's first properly load both the gene expression data and gene annotation data\n", "# 1. Load gene expression data from the matrix file\n", "gene_expr_data = get_genetic_data(matrix_file)\n", "print(f\"Gene expression data shape: {gene_expr_data.shape}\")\n", "\n", "# 2. Load gene annotation data from the SOFT file\n", "# Based on the preview, it looks like the SOFT file already contains proper gene symbols in both ID and ORF columns\n", "gene_annotation = get_gene_annotation(soft_file)\n", "print(f\"Gene annotation data shape: {gene_annotation.shape}\")\n", "\n", "# 3. Check which columns in gene_annotation contain the identifiers and gene symbols\n", "# From the preview, 'ID' appears to contain gene symbols directly\n", "print(\"\\nGene annotation column names:\")\n", "print(gene_annotation.columns.tolist())\n", "print(\"\\nFirst few rows of gene annotation:\")\n", "print(gene_annotation.head())\n", "\n", "# 4. Create the mapping dataframe\n", "# Since both ID and ORF appear to contain gene symbols, and the gene expression data has the same type of ID,\n", "# we can directly map them\n", "mapping_df = gene_annotation[['ID', 'ORF']].copy()\n", "mapping_df.rename(columns={'ORF': 'Gene'}, inplace=True)\n", "print(\"\\nGene mapping dataframe preview:\")\n", "print(mapping_df.head())\n", "\n", "# 5. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_expr_data, mapping_df)\n", "print(f\"\\nGene expression data after mapping: {gene_data.shape}\")\n", "print(\"\\nFirst few genes after mapping:\")\n", "print(gene_data.index[:10])\n", "\n", "# 6. Save the gene expression data for future use\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to: {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "5f5b24ed", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "d4e2cc41", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:40.015972Z", "iopub.status.busy": "2025-03-25T05:21:40.015843Z", "iopub.status.idle": "2025-03-25T05:21:46.141831Z", "shell.execute_reply": "2025-03-25T05:21:46.141356Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (18221, 54)\n", "Sample gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Glioblastoma/gene_data/GSE148949.csv\n", "Clinical data shape: (1, 54)\n", "Clinical data preview:\n", " GSM4486560 GSM4486561 GSM4486562 GSM4486563 GSM4486564 \\\n", "Glioblastoma 1 1 1 1 1 \n", "\n", " GSM4486565 GSM4486566 GSM4486567 GSM4486568 GSM4486569 ... \\\n", "Glioblastoma 1 1 1 1 1 ... \n", "\n", " GSM4486604 GSM4486605 GSM4486606 GSM4486607 GSM4486608 \\\n", "Glioblastoma 1 1 1 1 1 \n", "\n", " GSM4486609 GSM4486610 GSM4486611 GSM4486612 GSM4486613 \n", "Glioblastoma 1 1 1 1 1 \n", "\n", "[1 rows x 54 columns]\n", "Clinical data saved to ../../output/preprocess/Glioblastoma/clinical_data/GSE148949.csv\n", "Linked data shape: (54, 18222)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Glioblastoma A1BG A1BG-AS1 A1CF A2M\n", "GSM4486560 1.0 -0.248285 0.249204 -2.264265 -1.232422\n", "GSM4486561 1.0 0.177796 -0.177283 -1.703735 -2.352890\n", "GSM4486562 1.0 0.157001 0.026934 -1.728858 -1.300777\n", "GSM4486563 1.0 0.836357 0.883187 -1.853719 -4.036328\n", "GSM4486564 1.0 1.411080 0.595802 -1.629565 -3.459284\n", "\n", "Missing values before handling:\n", " Trait (Glioblastoma) missing: 0 out of 54\n", " Genes with >20% missing: 0\n", " Samples with >5% missing genes: 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (54, 18222)\n", "Quartiles for 'Glioblastoma':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1.0\n", "Max: 1.0\n", "The distribution of the feature 'Glioblastoma' in this dataset is severely biased.\n", "\n", "Data was determined to be unusable or empty and was not saved\n" ] } ], "source": [ "# 1. Normalize gene symbols using data from previous step\n", "# We already have gene_data from the previous step\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "print(f\"Sample gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Generate clinical data\n", "# Based on previous output, we know we only have the trait information\n", "# All samples are glioblastoma as indicated by the tissue info in sample characteristics\n", "\n", "# First, let's create a proper clinical dataframe based on what we know\n", "# We need a dataframe with sample IDs as columns and trait as the only row\n", "clinical_df = pd.DataFrame(index=[trait], \n", " data={col: 1 for col in normalized_gene_data.columns})\n", "print(f\"Clinical data shape: {clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(clinical_df.head())\n", "\n", "# Save the clinical features\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", "if linked_data.shape[1] >= 5:\n", " print(linked_data.iloc[:5, :5])\n", "else:\n", " print(linked_data.head())\n", "\n", "# 4. Handle missing values\n", "print(\"\\nMissing values before handling:\")\n", "print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", "gene_cols = [col for col in linked_data.columns if col != trait]\n", "if gene_cols:\n", " print(f\" Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n", " print(f\" Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n", "\n", "cleaned_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", "\n", "# 5. Evaluate bias in trait and demographic features\n", "is_trait_biased = False\n", "if len(cleaned_data) > 0:\n", " trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", " is_trait_biased = trait_biased\n", "else:\n", " print(\"No data remains after handling missing values.\")\n", " is_trait_biased = True\n", "\n", "# 6. Final validation and save\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=len(normalized_gene_data) > 0, \n", " is_trait_available=True, \n", " is_biased=is_trait_biased, \n", " df=cleaned_data,\n", " note=f\"Dataset contains gene expression data for {trait} analysis. No demographic features available.\"\n", ")\n", "\n", "# 7. Save if usable\n", "if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data was determined to be unusable or empty and was not saved\")" ] } ], "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 }