{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "89f0e421", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:36.610036Z", "iopub.status.busy": "2025-03-25T05:22:36.609800Z", "iopub.status.idle": "2025-03-25T05:22:36.775179Z", "shell.execute_reply": "2025-03-25T05:22:36.774727Z" } }, "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 = \"GSE226976\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Glioblastoma\"\n", "in_cohort_dir = \"../../input/GEO/Glioblastoma/GSE226976\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Glioblastoma/GSE226976.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Glioblastoma/gene_data/GSE226976.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Glioblastoma/clinical_data/GSE226976.csv\"\n", "json_path = \"../../output/preprocess/Glioblastoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "81bfc932", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "9e50a1f4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:36.776659Z", "iopub.status.busy": "2025-03-25T05:22:36.776514Z", "iopub.status.idle": "2025-03-25T05:22:36.805612Z", "shell.execute_reply": "2025-03-25T05:22:36.805171Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Combined oncolytic adenovirus DNX-2401 and anti-PD-checkpoint inhibitor pembrolizumab for recurrent glioblastoma\"\n", "!Series_summary\t\"Gene expression data for samples included in this trial of DNX2401 and pembrolizumab for recurrent glioma\"\n", "!Series_overall_design\t\"Observational cohort\"\n", "!Series_overall_design\t\"CAPTIVE investigators\"\n", "Sample Characteristics Dictionary:\n", "{0: ['sample type: recurrent glioma']}\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": "450d6b1c", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "5ac9fa46", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:36.806927Z", "iopub.status.busy": "2025-03-25T05:22:36.806817Z", "iopub.status.idle": "2025-03-25T05:22:36.833019Z", "shell.execute_reply": "2025-03-25T05:22:36.832696Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'GSM7089240': [1.0], 'GSM7089241': [1.0], 'GSM7089242': [1.0], 'GSM7089243': [1.0], 'GSM7089244': [1.0], 'GSM7089245': [1.0], 'GSM7089246': [1.0], 'GSM7089247': [1.0], 'GSM7089248': [1.0], 'GSM7089249': [1.0], 'GSM7089250': [1.0], 'GSM7089251': [1.0], 'GSM7089252': [1.0], 'GSM7089253': [1.0], 'GSM7089254': [1.0], 'GSM7089255': [1.0], 'GSM7089256': [1.0], 'GSM7089257': [1.0], 'GSM7089258': [1.0], 'GSM7089259': [1.0], 'GSM7089260': [1.0], 'GSM7089261': [1.0], 'GSM7089262': [1.0], 'GSM7089263': [1.0], 'GSM7089264': [1.0], 'GSM7089265': [1.0], 'GSM7089266': [1.0], 'GSM7089267': [1.0], 'GSM7089268': [1.0], 'GSM7089269': [1.0], 'GSM7089270': [1.0], 'GSM7089271': [1.0], 'GSM7089272': [1.0], 'GSM7089273': [1.0], 'GSM7089274': [1.0], 'GSM7089275': [1.0], 'GSM7089276': [1.0], 'GSM7089277': [1.0], 'GSM7089278': [1.0], 'GSM7089279': [1.0], 'GSM7089280': [1.0], 'GSM7089281': [1.0], 'GSM7089282': [1.0], 'GSM7089283': [1.0], 'GSM7089284': [1.0], 'GSM7089285': [1.0], 'GSM7089286': [1.0], 'GSM7089287': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Glioblastoma/clinical_data/GSE226976.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# Analysis based on the given information\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains \"Gene expression data for samples included in this trial\".\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# From the sample characteristics dictionary, we only have one key (0) with 'sample type: recurrent glioma'\n", "\n", "# 2.1 Data Availability\n", "# For trait (Glioblastoma):\n", "# The sample type is described as \"recurrent glioma\", which is related to but not exactly Glioblastoma\n", "# However, from the title, we know this is a study on \"recurrent glioblastoma\"\n", "trait_row = 0 # The key where we can infer the trait (glioblastoma) status\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 Functions\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert sample type to binary trait indicator for Glioblastoma.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " # From the title, we know this is about recurrent glioblastoma\n", " # The sample type mentions \"recurrent glioma\" which is likely referring to glioblastoma in this context\n", " if 'glioma' in value or 'glioblastoma' in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"Convert age value to float (not used in this dataset as age data is not available).\"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"Convert gender value to binary (not used in this dataset as gender data is not available).\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial filtering 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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " try:\n", " # Create directory for output if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Assuming clinical_data is already available from a previous step\n", " # We cannot proceed if it's not defined\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 extracted features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error extracting clinical features: {e}\")\n" ] }, { "cell_type": "markdown", "id": "ff44b330", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "b07db39f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:36.834302Z", "iopub.status.busy": "2025-03-25T05:22:36.834050Z", "iopub.status.idle": "2025-03-25T05:22:36.848565Z", "shell.execute_reply": "2025-03-25T05:22:36.848179Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 61\n", "Header line: \"ID_REF\"\t\"GSM7089240\"\t\"GSM7089241\"\t\"GSM7089242\"\t\"GSM7089243\"\t\"GSM7089244\"\t\"GSM7089245\"\t\"GSM7089246\"\t\"GSM7089247\"\t\"GSM7089248\"\t\"GSM7089249\"\t\"GSM7089250\"\t\"GSM7089251\"\t\"GSM7089252\"\t\"GSM7089253\"\t\"GSM7089254\"\t\"GSM7089255\"\t\"GSM7089256\"\t\"GSM7089257\"\t\"GSM7089258\"\t\"GSM7089259\"\t\"GSM7089260\"\t\"GSM7089261\"\t\"GSM7089262\"\t\"GSM7089263\"\t\"GSM7089264\"\t\"GSM7089265\"\t\"GSM7089266\"\t\"GSM7089267\"\t\"GSM7089268\"\t\"GSM7089269\"\t\"GSM7089270\"\t\"GSM7089271\"\t\"GSM7089272\"\t\"GSM7089273\"\t\"GSM7089274\"\t\"GSM7089275\"\t\"GSM7089276\"\t\"GSM7089277\"\t\"GSM7089278\"\t\"GSM7089279\"\t\"GSM7089280\"\t\"GSM7089281\"\t\"GSM7089282\"\t\"GSM7089283\"\t\"GSM7089284\"\t\"GSM7089285\"\t\"GSM7089286\"\t\"GSM7089287\"\n", "First data line: \"A2M\"\t19.9968671\t17.78207708\t19.24881111\t16.87933922\t19.11810162\t17.50234769\t18.81256357\t18.62195758\t18.58962005\t18.90626509\t16.81346241\t18.67700609\t16.98598829\t17.7329649\t19.13751049\t17.18096293\t18.43889199\t19.40324519\t19.17214276\t20.42669958\t18.92025434\t18.53633754\t20.33795161\t18.71954924\t16.96514146\t18.71277049\t17.89101063\t17.95152466\t18.34851415\t18.4338633\t19.30977132\t17.67758492\t16.35922707\t18.3582162\t20.98948775\t18.13616445\t17.7773347\t18.72633401\t18.41007769\t18.79477247\t17.91214586\t17.62986484\t16.65895059\t19.28841193\t17.34572035\t17.63160596\t18.80937881\t19.33760465\n", "Index(['A2M', 'ABCF1', 'ACVR1C', 'ADAM12', 'ADGRE1', 'ADM', 'ADORA2A', 'AKT1',\n", " 'ALDOA', 'ALDOC', 'ANGPT1', 'ANGPT2', 'ANGPTL4', 'ANLN', 'APC', 'APH1B',\n", " 'API5', 'APLNR', 'APOE', 'APOL6'],\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": "2e78e39e", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3cf005a5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:36.849762Z", "iopub.status.busy": "2025-03-25T05:22:36.849653Z", "iopub.status.idle": "2025-03-25T05:22:36.851705Z", "shell.execute_reply": "2025-03-25T05:22:36.851341Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the gene expression data\n", "# Looking at the sample index from the previous step:\n", "# Index(['A2M', 'ABCF1', 'ACVR1C', 'ADAM12', 'ADGRE1', 'ADM', 'ADORA2A', 'AKT1',\n", "# 'ALDOA', 'ALDOC', 'ANGPT1', 'ANGPT2', 'ANGPTL4', 'ANLN', 'APC', 'APH1B',\n", "# 'API5', 'APLNR', 'APOE', 'APOL6'],\n", "# dtype='object', name='ID')\n", "\n", "# These identifiers (A2M, ABCF1, etc.) are standard human gene symbols\n", "# A2M = Alpha-2-Macroglobulin\n", "# ABCF1 = ATP Binding Cassette Subfamily F Member 1\n", "# AKT1 = AKT Serine/Threonine Kinase 1\n", "# etc.\n", "\n", "# Therefore, no mapping is required\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "0548f0d6", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "4adf393b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:36.852915Z", "iopub.status.busy": "2025-03-25T05:22:36.852807Z", "iopub.status.idle": "2025-03-25T05:22:37.126484Z", "shell.execute_reply": "2025-03-25T05:22:37.125834Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original gene data shape: (770, 48)\n", "Sample gene symbols before normalization: ['A2M', 'ABCF1', 'ACVR1C', 'ADAM12', 'ADGRE1', 'ADM', 'ADORA2A', 'AKT1', 'ALDOA', 'ALDOC']\n", "Gene data shape after normalization: (762, 48)\n", "Sample gene symbols after normalization: ['A2M', 'ABCF1', 'ACVR1C', 'ADAM12', 'ADGRE1', 'ADM', 'ADORA2A', 'AKT1', 'ALDOA', 'ALDOC']\n", "Normalized gene data saved to ../../output/preprocess/Glioblastoma/gene_data/GSE226976.csv\n", "Clinical data shape: (1, 47)\n", "Clinical data preview:\n", " GSM7089241 GSM7089242 GSM7089243 GSM7089244 GSM7089245 \\\n", "GSM7089240 \n", "1.0 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM7089246 GSM7089247 GSM7089248 GSM7089249 GSM7089250 ... \\\n", "GSM7089240 ... \n", "1.0 1.0 1.0 1.0 1.0 1.0 ... \n", "\n", " GSM7089278 GSM7089279 GSM7089280 GSM7089281 GSM7089282 \\\n", "GSM7089240 \n", "1.0 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM7089283 GSM7089284 GSM7089285 GSM7089286 GSM7089287 \n", "GSM7089240 \n", "1.0 1.0 1.0 1.0 1.0 1.0 \n", "\n", "[1 rows x 47 columns]\n", "Linked data shape: (48, 763)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " 1.0 A2M ABCF1 ACVR1C ADAM12\n", "GSM7089241 1.0 17.782077 5.888663 10.816495 10.732307\n", "GSM7089242 1.0 19.248811 6.305956 8.825713 15.535675\n", "GSM7089243 1.0 16.879339 5.550797 10.624323 8.049131\n", "GSM7089244 1.0 19.118102 6.375912 10.128836 11.790075\n", "GSM7089245 1.0 17.502348 6.378189 10.444774 11.389109\n", "Identified trait column: 1.0\n", "\n", "Missing values before handling:\n", " Trait (1.0) missing: 1 out of 48\n", " Genes with >20% missing: 0\n", " Samples with >5% missing genes: 0\n", "Data shape after handling missing values: (47, 763)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Quartiles for '1.0':\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 '1.0' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data was determined to be unusable or empty and was not saved\n" ] } ], "source": [ "# 1. First process the gene expression data from the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data from the matrix file\n", "gene_data = get_genetic_data(matrix_file)\n", "print(f\"Original gene data shape: {gene_data.shape}\")\n", "print(f\"Sample gene symbols before normalization: {list(gene_data.index[:10])}\")\n", "\n", "# Normalize gene symbols using NCBI Gene database\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. Load clinical data\n", "try:\n", " clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(f\"Clinical data shape: {clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(clinical_df.head())\n", "except FileNotFoundError:\n", " print(f\"Error: Clinical data file not found at {out_clinical_data_file}\")\n", " # This is a critical error since we need clinical data to proceed\n", " raise\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. Identify the trait column by inspecting the linked data\n", "trait_col = clinical_df.index[0] # The trait column will match the index in clinical_df\n", "print(f\"Identified trait column: {trait_col}\")\n", "\n", "# Handle missing values\n", "print(\"\\nMissing values before handling:\")\n", "print(f\" Trait ({trait_col}) missing: {linked_data[trait_col].isna().sum()} out of {len(linked_data)}\")\n", "if 'Age' in linked_data.columns:\n", " print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n", "if 'Gender' in linked_data.columns:\n", " print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n", "\n", "gene_cols = [col for col in linked_data.columns if col not in [trait_col, 'Age', 'Gender']]\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_col)\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_col)\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.\"\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 }