{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "960a986d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:45.117912Z", "iopub.status.busy": "2025-03-25T07:18:45.117799Z", "iopub.status.idle": "2025-03-25T07:18:45.279376Z", "shell.execute_reply": "2025-03-25T07:18:45.279022Z" } }, "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 = \"Kidney_Clear_Cell_Carcinoma\"\n", "cohort = \"GSE94321\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Clear_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Clear_Cell_Carcinoma/GSE94321\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/GSE94321.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE94321.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/GSE94321.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6ff76467", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0de09116", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:45.280843Z", "iopub.status.busy": "2025-03-25T07:18:45.280693Z", "iopub.status.idle": "2025-03-25T07:18:45.368659Z", "shell.execute_reply": "2025-03-25T07:18:45.368351Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Embryonic signature distinguishes pediatric and adult rhabdoid tumors from other SMARCB1-deficient cancers\"\n", "!Series_summary\t\"We used microarrays to compare gene expression profilings in various SMARCB1-deficient tumors.\"\n", "!Series_overall_design\t\"[human mRNA] 16 RT, 16 SD-NRT (8 Epithelioid Sarcomas, 3 Undifferentiated Chordomas and 5 Renal Medullary Carcinomas), 37 SMARCB1 deficient tumors.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: SMARCB1 deficient tumor', 'tissue: RT', 'tissue: RMC', 'tissue: ES', 'tissue: UC']}\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": "28ed164c", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "a5ee1242", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:45.369811Z", "iopub.status.busy": "2025-03-25T07:18:45.369698Z", "iopub.status.idle": "2025-03-25T07:18:45.378822Z", "shell.execute_reply": "2025-03-25T07:18:45.378518Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'tissue: SMARCB1 deficient tumor': [1.0], 'tissue: RT': [0.0], 'tissue: RMC': [1.0], 'tissue: ES': [0.0], 'tissue: UC': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/GSE94321.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# The sample characteristics dictionary was provided in the previous step\n", "sample_characteristics = {0: ['tissue: SMARCB1 deficient tumor', 'tissue: RT', 'tissue: RMC', 'tissue: ES', 'tissue: UC']}\n", "\n", "# Create a DataFrame from the sample characteristics dictionary\n", "clinical_data = pd.DataFrame()\n", "for row_idx, values in sample_characteristics.items():\n", " for value in values:\n", " clinical_data.loc[row_idx, value] = value\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series overall design mentioning \"human mRNA\", this dataset likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For trait (Kidney Clear Cell Carcinoma):\n", "# Looking at the sample characteristics, it appears to be RMC (Renal Medullary Carcinoma)\n", "# which is a type of kidney cancer, so row 0 contains relevant information\n", "trait_row = 0\n", "\n", "# Age and gender information are not available in the sample characteristics\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert trait value to binary (0: no cancer, 1: has cancer).\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # RMC (Renal Medullary Carcinoma) is a type of kidney cancer\n", " if 'RMC' in value:\n", " return 1\n", " # Clear Cell Carcinoma - we're looking for Kidney Clear Cell Carcinoma\n", " elif 'SMARCB1 deficient tumor' in value:\n", " return 1\n", " # RT (Rhabdoid Tumor) is not a kidney cancer\n", " elif 'RT' in value or 'ES' in value or 'UC' in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age value to float.\"\"\"\n", " # Age is not available\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender value to binary (0: female, 1: male).\"\"\"\n", " # Gender is not available\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available (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 is_trait_available:\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 selected clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the selected clinical features to a CSV file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "476c1c71", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "7a401dae", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:45.379905Z", "iopub.status.busy": "2025-03-25T07:18:45.379794Z", "iopub.status.idle": "2025-03-25T07:18:45.535076Z", "shell.execute_reply": "2025-03-25T07:18:45.534678Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n", "Successfully extracted gene data with 18989 rows\n", "First 20 gene IDs:\n", "Index(['100009676_at', '10000_at', '10001_at', '10002_at', '10003_at',\n", " '100048912_at', '100049716_at', '10004_at', '10005_at', '10006_at',\n", " '10007_at', '10008_at', '100093630_at', '10009_at', '1000_at',\n", " '100101467_at', '100101938_at', '10010_at', '100113407_at', '10011_at'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\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. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting gene data from matrix file:\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "11019180", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "060b912b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:45.536408Z", "iopub.status.busy": "2025-03-25T07:18:45.536285Z", "iopub.status.idle": "2025-03-25T07:18:45.538213Z", "shell.execute_reply": "2025-03-25T07:18:45.537921Z" } }, "outputs": [], "source": [ "# Analyze the gene identifiers format\n", "# The identifiers like '100009676_at', '10000_at', etc. appear to be probe IDs from a microarray\n", "# These are not standard human gene symbols (which would look like BRCA1, TP53, etc.)\n", "# The \"_at\" suffix is characteristic of Affymetrix probe IDs that need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "9dfcf202", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "b5bf6171", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:45.539311Z", "iopub.status.busy": "2025-03-25T07:18:45.539204Z", "iopub.status.idle": "2025-03-25T07:18:46.965337Z", "shell.execute_reply": "2025-03-25T07:18:46.964932Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation data with 1329299 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'ENTREZ_GENE_ID': ['1', '10', '100', '1000', '10000'], 'Description': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'ENTREZ_GENE_ID', 'Description', 'SPOT_ID']\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: nan\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "7f8e84fd", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "0436c495", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:46.967036Z", "iopub.status.busy": "2025-03-25T07:18:46.966902Z", "iopub.status.idle": "2025-03-25T07:18:48.957415Z", "shell.execute_reply": "2025-03-25T07:18:48.957014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Analyzing gene identifier and symbol columns...\n", "Comparing gene expression IDs with annotation IDs...\n", "Example ID from expression data: 100009676_at\n", "Number of matching probe IDs: 18989 out of 18989\n", "\n", "Sample rows from gene annotation:\n", " ID ENTREZ_GENE_ID Description \\\n", "0 1_at 1 alpha-1-B glycoprotein \n", "1 10_at 10 N-acetyltransferase 2 (arylamine N-acetyltrans... \n", "2 100_at 100 adenosine deaminase \n", "3 1000_at 1000 cadherin 2, type 1, N-cadherin (neuronal) \n", "4 10000_at 10000 v-akt murine thymoma viral oncogene homolog 3 ... \n", "\n", " SPOT_ID \n", "0 NaN \n", "1 NaN \n", "2 NaN \n", "3 NaN \n", "4 NaN \n", "\n", "Sample rows from gene expression data:\n", " GSM2473069 GSM2473070 GSM2473071 GSM2473072 GSM2473073 \\\n", "ID \n", "100009676_at 2.292232 2.421841 2.311515 2.312727 2.307486 \n", "10000_at 3.891792 4.184991 3.049052 4.313005 4.776864 \n", "10001_at 6.394557 8.168572 7.974895 7.708672 6.702601 \n", "\n", " GSM2473074 GSM2473075 GSM2473076 GSM2473077 GSM2473078 ... \\\n", "ID ... \n", "100009676_at 2.334719 2.305307 2.397930 2.323996 2.325830 ... \n", "10000_at 3.796574 3.505392 3.857803 5.502840 3.109216 ... \n", "10001_at 7.464943 6.625686 8.293250 6.611901 8.388462 ... \n", "\n", " GSM2473128 GSM2473129 GSM2473130 GSM2473131 GSM2473132 \\\n", "ID \n", "100009676_at 2.299306 2.314706 2.311947 2.311336 2.302005 \n", "10000_at 4.182249 3.083897 2.885094 2.850091 3.225609 \n", "10001_at 6.236331 7.064054 7.584998 6.886698 6.958695 \n", "\n", " GSM2473133 GSM2473134 GSM2473135 GSM2473136 GSM2473137 \n", "ID \n", "100009676_at 2.315264 2.362463 2.321335 2.283744 2.288802 \n", "10000_at 2.970452 4.395082 5.329623 5.258651 3.055347 \n", "10001_at 7.758514 7.202339 6.069835 7.429547 6.545031 \n", "\n", "[3 rows x 69 columns]\n", "\n", "Creating direct gene mapping dataframe...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Created direct mapping with 1329168 rows\n", "Preview of mapping:\n", " ID Gene\n", "0 1_at 1\n", "1 10_at 10\n", "2 100_at 100\n", "3 1000_at 1000\n", "4 10000_at 10000\n", "\n", "Checking if first 10 probe IDs from expression data exist in mapping:\n", "Probe ID 100009676_at: exists in mapping\n", "Probe ID 10000_at: exists in mapping\n", "Probe ID 10001_at: exists in mapping\n", "Probe ID 10002_at: exists in mapping\n", "Probe ID 10003_at: exists in mapping\n", "Probe ID 100048912_at: exists in mapping\n", "Probe ID 100049716_at: exists in mapping\n", "Probe ID 10004_at: exists in mapping\n", "Probe ID 10005_at: exists in mapping\n", "Probe ID 10006_at: exists in mapping\n", "\n", "Applying gene mapping with direct approach...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Created gene expression data with 0 genes\n", "\n", "Direct mapping failed. Trying approach with Description field...\n", "Created description-based mapping with 0 rows\n", "Preview of description mapping:\n", "Empty DataFrame\n", "Columns: [ID, Description, Gene]\n", "Index: []\n", "Created gene expression data with 0 genes\n", "\n", "Preview of gene expression data:\n", "{'Description': [], 'GSM2473069': [], 'GSM2473070': [], 'GSM2473071': [], 'GSM2473072': [], 'GSM2473073': [], 'GSM2473074': [], 'GSM2473075': [], 'GSM2473076': [], 'GSM2473077': [], 'GSM2473078': [], 'GSM2473079': [], 'GSM2473080': [], 'GSM2473081': [], 'GSM2473082': [], 'GSM2473083': [], 'GSM2473084': [], 'GSM2473085': [], 'GSM2473086': [], 'GSM2473087': [], 'GSM2473088': [], 'GSM2473089': [], 'GSM2473090': [], 'GSM2473091': [], 'GSM2473092': [], 'GSM2473093': [], 'GSM2473094': [], 'GSM2473095': [], 'GSM2473096': [], 'GSM2473097': [], 'GSM2473098': [], 'GSM2473099': [], 'GSM2473100': [], 'GSM2473101': [], 'GSM2473102': [], 'GSM2473103': [], 'GSM2473104': [], 'GSM2473105': [], 'GSM2473106': [], 'GSM2473107': [], 'GSM2473108': [], 'GSM2473109': [], 'GSM2473110': [], 'GSM2473111': [], 'GSM2473112': [], 'GSM2473113': [], 'GSM2473114': [], 'GSM2473115': [], 'GSM2473116': [], 'GSM2473117': [], 'GSM2473118': [], 'GSM2473119': [], 'GSM2473120': [], 'GSM2473121': [], 'GSM2473122': [], 'GSM2473123': [], 'GSM2473124': [], 'GSM2473125': [], 'GSM2473126': [], 'GSM2473127': [], 'GSM2473128': [], 'GSM2473129': [], 'GSM2473130': [], 'GSM2473131': [], 'GSM2473132': [], 'GSM2473133': [], 'GSM2473134': [], 'GSM2473135': [], 'GSM2473136': [], 'GSM2473137': []}\n", "Normalization skipped as gene data is empty\n", "Gene expression data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE94321.csv\n", "Final status - Gene expression data available: False\n" ] } ], "source": [ "# Gene Identifier Mapping\n", "\n", "# Analyze which columns correspond to gene identifiers and gene symbols\n", "print(\"Analyzing gene identifier and symbol columns...\")\n", "\n", "# Look at the gene expression index (probes)\n", "print(\"Comparing gene expression IDs with annotation IDs...\")\n", "expression_id_example = gene_data.index[0]\n", "print(f\"Example ID from expression data: {expression_id_example}\")\n", "\n", "# Check overlap between expression data and annotation data\n", "expression_ids = set(gene_data.index)\n", "annotation_ids = set(gene_annotation['ID'])\n", "common_ids = expression_ids & annotation_ids\n", "print(f\"Number of matching probe IDs: {len(common_ids)} out of {len(gene_data.index)}\")\n", "\n", "# Display a few rows from gene_annotation to understand its structure\n", "print(\"\\nSample rows from gene annotation:\")\n", "print(gene_annotation.head())\n", "\n", "# Display a few rows from gene_data to understand its structure\n", "print(\"\\nSample rows from gene expression data:\")\n", "print(gene_data.head(3))\n", "\n", "# Create a more direct and simplified mapping approach\n", "print(\"\\nCreating direct gene mapping dataframe...\")\n", "# Create a dataframe with just ID and gene identifiers (as Gene)\n", "direct_mapping = gene_annotation[['ID', 'ENTREZ_GENE_ID']].copy()\n", "direct_mapping = direct_mapping.rename(columns={'ENTREZ_GENE_ID': 'Gene'})\n", "direct_mapping = direct_mapping.dropna(subset=['Gene']) # Remove rows with missing gene identifiers\n", "direct_mapping['Gene'] = direct_mapping['Gene'].astype(str) # Ensure Gene column is string type\n", "\n", "# Make sure mapping IDs match expression IDs in format\n", "direct_mapping = direct_mapping[direct_mapping['ID'].isin(gene_data.index)]\n", "\n", "print(f\"Created direct mapping with {len(direct_mapping)} rows\")\n", "print(\"Preview of mapping:\")\n", "print(direct_mapping.head())\n", "\n", "# Debug: check that some probe IDs from expression data exist in our mapping\n", "first_10_probe_ids = list(gene_data.index[:10])\n", "print(f\"\\nChecking if first 10 probe IDs from expression data exist in mapping:\")\n", "for probe_id in first_10_probe_ids:\n", " exists = probe_id in direct_mapping['ID'].values\n", " print(f\"Probe ID {probe_id}: {'exists' if exists else 'does not exist'} in mapping\")\n", "\n", "# Apply mapping with the simpler approach\n", "print(\"\\nApplying gene mapping with direct approach...\")\n", "# Create a custom list for Gene column to ensure it's processed as a list\n", "direct_mapping['Gene'] = direct_mapping['Gene'].apply(lambda x: [x]) # Wrap each gene ID in a list\n", "\n", "# Apply the mapping\n", "gene_data = apply_gene_mapping(gene_data, direct_mapping)\n", "print(f\"Created gene expression data with {len(gene_data)} genes\")\n", "\n", "# If the direct mapping fails, try using the Description field\n", "if len(gene_data) == 0:\n", " print(\"\\nDirect mapping failed. Trying approach with Description field...\")\n", " # Extract gene symbols from Description column\n", " desc_mapping = gene_annotation[['ID', 'Description']].copy()\n", " desc_mapping = desc_mapping.dropna(subset=['Description'])\n", " \n", " # Extract the gene name from the beginning of the description\n", " def extract_first_gene_name(desc):\n", " if pd.isna(desc):\n", " return []\n", " # Take the first part of the description which often contains the gene name\n", " desc = str(desc).strip()\n", " parts = desc.split(',')[0].split('(')[0].strip()\n", " return [parts] # Return as a list for compatibility with apply_gene_mapping\n", " \n", " desc_mapping['Gene'] = desc_mapping['Description'].apply(extract_first_gene_name)\n", " desc_mapping = desc_mapping[desc_mapping['ID'].isin(gene_data.index)]\n", " \n", " print(f\"Created description-based mapping with {len(desc_mapping)} rows\")\n", " print(\"Preview of description mapping:\")\n", " print(desc_mapping.head())\n", " \n", " # Apply the description-based mapping\n", " gene_data = apply_gene_mapping(gene_data, desc_mapping)\n", " print(f\"Created gene expression data with {len(gene_data)} genes\")\n", "\n", "# Print preview of the gene expression data\n", "print(\"\\nPreview of gene expression data:\")\n", "print(preview_df(gene_data))\n", "\n", "# Normalize gene symbols\n", "if len(gene_data) > 0:\n", " gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: gene expression data with {len(gene_data)} genes\")\n", "else:\n", " print(\"Normalization skipped as gene data is empty\")\n", "\n", "# Save the gene expression data\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", "\n", "# Update the gene availability flag based on results\n", "is_gene_available = len(gene_data) > 0\n", "print(f\"Final status - Gene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "9424f3d0", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "6a8636bd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:48.958857Z", "iopub.status.busy": "2025-03-25T07:18:48.958739Z", "iopub.status.idle": "2025-03-25T07:18:48.966578Z", "shell.execute_reply": "2025-03-25T07:18:48.966278Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "Gene data is empty. Skipping normalization.\n", "Normalized gene expression data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE94321.csv\n", "\n", "Checking trait availability from previous analysis...\n", "Loaded clinical data with shape: (1, 5)\n", "\n", "Linking clinical and genetic data...\n", "Cannot link data: clinical or genetic data is missing.\n", "Reason: Gene expression data is empty (mapping failed).\n", "\n", "Performing final validation...\n", "Abnormality detected in the cohort: GSE94321. Preprocessing failed.\n", "Dataset not usable for Kidney_Clear_Cell_Carcinoma association studies. Data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "try:\n", " # Check if gene_data is empty before normalization\n", " if gene_data.empty:\n", " print(\"Gene data is empty. Skipping normalization.\")\n", " normalized_gene_data = gene_data\n", " else:\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {len(normalized_gene_data.index)} unique gene symbols\")\n", " \n", " # Save the normalized gene data (even if empty, to maintain consistent workflow)\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 expression data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene symbols: {e}\")\n", " normalized_gene_data = gene_data # Use original data if normalization fails\n", "\n", "# Use is_trait_available from previous steps, don't recheck trait_row\n", "print(\"\\nChecking trait availability from previous analysis...\")\n", "# Load the clinical data from the previously saved file\n", "try:\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " clinical_df = pd.DataFrame()\n", " is_trait_available = False\n", "\n", "# 2. Link clinical and genetic data if available\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if is_trait_available and not normalized_gene_data.empty:\n", " # Print sample IDs from both datasets for debugging\n", " print(\"First few clinical sample columns:\", list(clinical_df.columns)[:5])\n", " print(\"First few genetic sample columns:\", list(normalized_gene_data.columns)[:5])\n", " \n", " # 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", " \n", " # Check if we have at least one sample with trait value\n", " if trait in linked_data.columns:\n", " trait_count = linked_data[trait].count()\n", " print(f\"Number of samples with trait values: {trait_count}\")\n", " \n", " if trait_count > 0:\n", " # 3. Handle missing values systematically\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, data shape: {linked_data.shape}\")\n", " \n", " # Check if we still have samples after missing value handling\n", " if linked_data.shape[0] > 0:\n", " # 4. Determine whether the trait and demographic features are biased\n", " print(\"\\nChecking for bias in features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " else:\n", " print(\"Error: All samples were removed during missing value handling.\")\n", " is_biased = True\n", " else:\n", " print(\"No samples have valid trait values. Dataset cannot be used.\")\n", " is_biased = True\n", " else:\n", " print(f\"Trait column '{trait}' not found in linked data.\")\n", " is_biased = True\n", " else:\n", " print(\"Cannot link data: clinical or genetic data is missing.\")\n", " if not is_trait_available:\n", " print(\"Reason: Trait data is not available.\")\n", " if normalized_gene_data.empty:\n", " print(\"Reason: Gene expression data is empty (mapping failed).\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " \n", "except Exception as e:\n", " print(f\"Error in linking clinical and genetic data: {e}\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 5. Final quality validation\n", "print(\"\\nPerforming final validation...\")\n", "note = \"Dataset failed preprocessing: gene mapping in Step 6 produced empty data. \"\n", "note += \"The source data contains Affymetrix probe IDs but could not map to human gene symbols properly.\"\n", "\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=False, # Set to False since gene mapping failed\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data if 'linked_data' in locals() and not linked_data.empty else pd.DataFrame(),\n", " note=note\n", ")\n", "\n", "# 6. Save linked data if usable\n", "if is_usable and 'linked_data' in locals() and not linked_data.empty:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " \n", " # Save linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Dataset not usable for {trait} association studies. Data 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 }