{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "b4179224", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:08.702628Z", "iopub.status.busy": "2025-03-25T07:17:08.702194Z", "iopub.status.idle": "2025-03-25T07:17:08.867930Z", "shell.execute_reply": "2025-03-25T07:17:08.867589Z" } }, "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 = \"GSE106757\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Clear_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Clear_Cell_Carcinoma/GSE106757\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/GSE106757.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE106757.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/GSE106757.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "bee84555", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "e4512000", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:08.869360Z", "iopub.status.busy": "2025-03-25T07:17:08.869222Z", "iopub.status.idle": "2025-03-25T07:17:08.939485Z", "shell.execute_reply": "2025-03-25T07:17:08.939190Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Analysis of monocyte subsets from pretreatment RCC patients compared to healthy donors.\"\n", "!Series_summary\t\"Peripheral blood monocytes are the starting material utilized in conventional dendritic cell (DC) vaccination for the treatment of a broad range of malignancies. While the use of cytokines and growth factors to polarize monocyte-derived DC to distinct phenotypes is well-established, little is known about the contributions of distinct human monocyte subsets to monocyte-derived DC function and patient responses to vaccination. To investigate the status of monocyte subsets in cancer patients and following culture into DC, we isolated classical (C-Mo), intermediate (I-Mo), and non-classical (NC-Mo) from the peripheral blood of renal cell carcinoma (RCC) patients prior to DC vaccination (NCT00085436) and from anonymous healthy donors. Patients treated with DC vaccination who were long term survivors (>100 months survival) had a unique monocyte signature with a two-fold higher percentage of NC-Mo in pretreatment peripheral blood compared to other RCC patients. RCC patient monocytes from each subset were transcriptionally distinct from healthy donor monocytes. Further transcriptional analysis determined that each monocyte subset was characterized by a discrete gene expression profile before and after DC maturation. Phenotypic analysis showed that DC derived from NC-Mo expressed higher levels of CD80, CD83, CD86, HLA-DR, and CD40 compared to DC originating from C-Mo and secreted increased amounts of IL-12p70 following CD40L stimulation. Collectively, these findings establish that DC derived from NC-Mo are potent antigen presenting cells and provide the foundation for future vaccination strategies that enrich NC-Mo prior to DC maturation.\"\n", "!Series_overall_design\t\"Blood monocyte subsets from 8 pretreatment RCC patients were compared to 4 healthy donor controls.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: healthy', 'disease state: renal cell carcinoma'], 1: ['monocyte subset: classical', 'monocyte subset: intermediate', 'monocyte subset: non-classical']}\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": "a77ef2d8", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "f5aad442", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:08.940617Z", "iopub.status.busy": "2025-03-25T07:17:08.940509Z", "iopub.status.idle": "2025-03-25T07:17:08.949268Z", "shell.execute_reply": "2025-03-25T07:17:08.948967Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'Sample_1': [0.0], 'Sample_2': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/GSE106757.csv\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Callable, Optional, Dict, Any, List, Union\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on background information, this dataset seems to contain transcriptional analysis data\n", "# comparing monocyte subsets from RCC patients and healthy donors.\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary:\n", "# Key 0 contains disease state (healthy or renal cell carcinoma) which represents our trait\n", "# Key 1 contains monocyte subset information which is not our focus\n", "trait_row = 0\n", "age_row = None # Age is not available in the sample characteristics\n", "gender_row = None # Gender is not available in the sample characteristics\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert the trait value to binary format.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert trait to binary (RCC = 1, healthy = 0)\n", " if 'renal cell carcinoma' in value.lower():\n", " return 1\n", " elif 'healthy' in value.lower():\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to numeric format.\"\"\"\n", " # This function is included for completeness, but not used since age data is not available\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary format (Female=0, Male=1).\"\"\"\n", " # This function is included for completeness, but not used since gender data is not available\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " value = value.lower()\n", " if 'female' in value or 'f' == value:\n", " return 0\n", " elif 'male' in value or 'm' == value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "# Initial validation 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", "if trait_row is not None:\n", " try:\n", " # Create a DataFrame from the sample characteristics dictionary\n", " # The sample characteristics are provided in the output of a previous step\n", " # We're creating a DataFrame with columns being the sample IDs and rows being the feature types\n", " sample_chars = {0: ['disease state: healthy', 'disease state: renal cell carcinoma'], \n", " 1: ['monocyte subset: classical', 'monocyte subset: intermediate', 'monocyte subset: non-classical']}\n", " \n", " # Convert the dictionary to a DataFrame format that geo_select_clinical_features can process\n", " # First, create sample IDs (assuming there are 2 samples based on the trait information)\n", " sample_ids = [f\"Sample_{i}\" for i in range(1, 3)] # Create 2 sample IDs\n", " \n", " # Initialize DataFrame with rows for each characteristic type and columns for each sample\n", " clinical_data = pd.DataFrame(index=sample_chars.keys(), columns=sample_ids)\n", " \n", " # Fill in sample values (for demonstration, assign values to make the trait information clear)\n", " clinical_data.loc[0, \"Sample_1\"] = \"disease state: healthy\"\n", " clinical_data.loc[0, \"Sample_2\"] = \"disease state: renal cell carcinoma\"\n", " \n", " # Assuming monocyte subset info is not our focus, we'll just assign one value to each sample\n", " clinical_data.loc[1, \"Sample_1\"] = \"monocyte subset: classical\"\n", " clinical_data.loc[1, \"Sample_2\"] = \"monocyte subset: classical\"\n", " \n", " # Extract clinical features\n", " selected_clinical = 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", " print(\"Preview of selected clinical features:\")\n", " preview = preview_df(selected_clinical)\n", " print(preview)\n", " \n", " # Save clinical data to file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical.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 processing clinical data: {str(e)}\")\n", "else:\n", " print(\"No trait data available, skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "0ec7357f", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "193e2bfd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:08.950395Z", "iopub.status.busy": "2025-03-25T07:17:08.950287Z", "iopub.status.idle": "2025-03-25T07:17:09.045438Z", "shell.execute_reply": "2025-03-25T07:17:09.045015Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Analysis of monocyte subsets from pretreatment RCC patients compared to healthy donors.\"\n", "Line 1: !Series_geo_accession\t\"GSE106757\"\n", "Line 2: !Series_status\t\"Public on Nov 15 2019\"\n", "Line 3: !Series_submission_date\t\"Nov 09 2017\"\n", "Line 4: !Series_last_update_date\t\"Nov 15 2019\"\n", "Line 5: !Series_summary\t\"Peripheral blood monocytes are the starting material utilized in conventional dendritic cell (DC) vaccination for the treatment of a broad range of malignancies. While the use of cytokines and growth factors to polarize monocyte-derived DC to distinct phenotypes is well-established, little is known about the contributions of distinct human monocyte subsets to monocyte-derived DC function and patient responses to vaccination. To investigate the status of monocyte subsets in cancer patients and following culture into DC, we isolated classical (C-Mo), intermediate (I-Mo), and non-classical (NC-Mo) from the peripheral blood of renal cell carcinoma (RCC) patients prior to DC vaccination (NCT00085436) and from anonymous healthy donors. Patients treated with DC vaccination who were long term survivors (>100 months survival) had a unique monocyte signature with a two-fold higher percentage of NC-Mo in pretreatment peripheral blood compared to other RCC patients. RCC patient monocytes from each subset were transcriptionally distinct from healthy donor monocytes. Further transcriptional analysis determined that each monocyte subset was characterized by a discrete gene expression profile before and after DC maturation. Phenotypic analysis showed that DC derived from NC-Mo expressed higher levels of CD80, CD83, CD86, HLA-DR, and CD40 compared to DC originating from C-Mo and secreted increased amounts of IL-12p70 following CD40L stimulation. Collectively, these findings establish that DC derived from NC-Mo are potent antigen presenting cells and provide the foundation for future vaccination strategies that enrich NC-Mo prior to DC maturation.\"\n", "Line 6: !Series_overall_design\t\"Blood monocyte subsets from 8 pretreatment RCC patients were compared to 4 healthy donor controls.\"\n", "Line 7: !Series_type\t\"Expression profiling by array\"\n", "Line 8: !Series_contributor\t\"Jason,,Muhitch\"\n", "Line 9: !Series_sample_id\t\"GSM2849909 GSM2849910 GSM2849911 GSM2849912 GSM2849913 GSM2849914 GSM2849915 GSM2849916 GSM2849917 GSM2849918 GSM2849919 GSM2849920 GSM2849921 GSM2849922 GSM2849923 GSM2849924 GSM2849925 GSM2849926 GSM2849927 GSM2849928 GSM2849929 GSM2849930 GSM2849931 GSM2849932 GSM2849933 GSM2849934 GSM2849935 GSM2849936 GSM2849937 GSM2849938 GSM2849939 GSM2849940 GSM2849941 GSM2849942 GSM2849943 GSM2849944 \"\n", "Found table marker at line 56\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM2849909\"\t\"GSM2849910\"\t\"GSM2849911\"\t\"GSM2849912\"\t\"GSM2849913\"\t\"GSM2849914\"\t\"GSM2849915\"\t\"GSM2849916\"\t\"GSM2849917\"\t\"GSM2849918\"\t\"GSM2849919\"\t\"GSM2849920\"\t\"GSM2849921\"\t\"GSM2849922\"\t\"GSM2849923\"\t\"GSM2849924\"\t\"GSM2849925\"\t\"GSM2849926\"\t\"GSM2849927\"\t\"GSM2849928\"\t\"GSM2849929\"\t\"GSM2849930\"\t\"GSM2849931\"\t\"GSM2849932\"\t\"GSM2849933\"\t\"GSM2849934\"\t\"GSM2849935\"\t\"GSM2849936\"\t\"GSM2849937\"\t\"GSM2849938\"\t\"GSM2849939\"\t\"GSM2849940\"\t\"GSM2849941\"\t\"GSM2849942\"\t\"GSM2849943\"\t\"GSM2849944\"\n", "\"7A5\"\t1.3\t-10.9\t0.2\t-2.2\t6\t-1.9\t0.8\t0\t-0.5\t2.4\t1.1\t1.7\t-0.5\t-0.6\t-3.8\t4.1\t-1.1\t3.3\t-0.5\t-0.2\t-3.4\t-5.2\t-6.4\t-1.6\t-3.4\t1.3\t2.4\t-4\t-2.4\t2\t0\t3.2\t-2.8\t-0.8\t-2.2\t-0.4\n", "\"A1BG\"\t3.3\t0.5\t4\t-1.8\t7\t4.4\t0.5\t4\t6.1\t0.6\t3.3\t6\t-4.9\t0.3\t4\t-0.5\t3.5\t-1.5\t3.7\t8.1\t-0.9\t0.7\t1.6\t7.1\t1\t11.2\t2.1\t3.3\t1.6\t2.5\t6.4\t-1.9\t2.4\t5.7\t7.9\t3.9\n", "\"A1CF\"\t1.5\t5.6\t-5.7\t1.3\t-0.2\t2.4\t4.7\t0.8\t-1.9\t6.6\t1.9\t-2.9\t-2.3\t1.8\t-3.7\t-1.3\t-1.1\t-1.7\t1.9\t0\t-0.5\t-0.9\t-2.5\t1.6\t-0.4\t3.6\t5.3\t0\t-3.4\t9.8\t1.3\t-2.6\t-0.9\t-2.6\t-2.1\t1\n", "\"A26C3\"\t-1.1\t-2.2\t-1.3\t-0.9\t2.2\t-0.3\t-2.3\t-2.5\t-5.1\t-1.8\t-4\t0.3\t4.3\t-3.4\t-4.2\t3.7\t-0.2\t-3.8\t4.7\t1.5\t1.5\t-3.6\t-1.2\t-3\t2.3\t1.8\t1.6\t-0.7\t0.3\t3.2\t2.9\t3.5\t-1.7\t0.5\t-3.2\t-2.9\n", "Total lines examined: 57\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 34678 rows\n", "First 20 gene IDs:\n", "Index(['7A5', 'A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1',\n", " 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AACSL', 'AADAC',\n", " 'AADACL1', 'AADACL2', 'AADACL3', 'AADACL4'],\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", "# Add diagnostic code to check file content and structure\n", "print(\"Examining matrix file structure...\")\n", "with gzip.open(matrix_file, 'rt') as file:\n", " table_marker_found = False\n", " lines_read = 0\n", " for i, line in enumerate(file):\n", " lines_read += 1\n", " if '!series_matrix_table_begin' in line:\n", " table_marker_found = True\n", " print(f\"Found table marker at line {i}\")\n", " # Read a few lines after the marker to check data structure\n", " next_lines = [next(file, \"\").strip() for _ in range(5)]\n", " print(\"First few lines after marker:\")\n", " for next_line in next_lines:\n", " print(next_line)\n", " break\n", " if i < 10: # Print first few lines to see file structure\n", " print(f\"Line {i}: {line.strip()}\")\n", " if i > 100: # Don't read the entire file\n", " break\n", " \n", " if not table_marker_found:\n", " print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n", " print(f\"Total lines examined: {lines_read}\")\n", "\n", "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n", "try:\n", " print(\"\\nAttempting to extract 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: {str(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", "\n", "# If data extraction failed, try an alternative approach using pandas directly\n", "if not is_gene_available:\n", " print(\"\\nTrying alternative approach to read gene expression data...\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Skip lines until we find the marker\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Try to read the data directly with pandas\n", " gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n", " \n", " if not gene_data.empty:\n", " print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", " else:\n", " print(\"Alternative extraction method also produced empty data\")\n", " except Exception as e:\n", " print(f\"Alternative extraction failed: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "3c2ef01e", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "ecb43ef7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:09.047021Z", "iopub.status.busy": "2025-03-25T07:17:09.046886Z", "iopub.status.idle": "2025-03-25T07:17:09.048847Z", "shell.execute_reply": "2025-03-25T07:17:09.048557Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers from the gene data\n", "# From the output, I can see gene identifiers like 'A1BG', 'A2M', 'AACS' which are\n", "# standard human gene symbols. These include:\n", "# - A1BG (Alpha-1-B Glycoprotein)\n", "# - A2M (Alpha-2-Macroglobulin)\n", "# - AACS (Acetoacetyl-CoA Synthetase)\n", "# \n", "# These are official HGNC gene symbols, not probe IDs or other identifiers that would\n", "# require mapping to gene symbols.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "ea396e6f", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "a2e623d0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:09.050218Z", "iopub.status.busy": "2025-03-25T07:17:09.050111Z", "iopub.status.idle": "2025-03-25T07:17:18.674974Z", "shell.execute_reply": "2025-03-25T07:17:18.674482Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 20741 unique gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE106757.csv\n", "\n", "Re-extracting clinical data with proper sample IDs...\n", "Re-extracted clinical data with shape: (2, 37)\n", "Found disease state information in row 0: ['disease state: healthy', 'disease state: renal cell carcinoma']\n", "Selected clinical data with shape: (1, 36)\n", "Updated clinical data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/GSE106757.csv\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (36, 20742)\n", "Number of samples with trait values: 36\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (36, 20742)\n", "\n", "Checking for bias in features...\n", "For the feature 'Kidney_Clear_Cell_Carcinoma', the least common label is '0.0' with 4 occurrences. This represents 11.11% of the dataset.\n", "The distribution of the feature 'Kidney_Clear_Cell_Carcinoma' in this dataset is fine.\n", "\n", "\n", "Performing final validation...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/GSE106757.csv\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", "# 2. Re-extract clinical data from matrix file to get proper sample IDs\n", "print(\"\\nRe-extracting clinical data with proper sample IDs...\")\n", "try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " print(f\"Re-extracted clinical data with shape: {clinical_data.shape}\")\n", " \n", " # Find the row with disease state information\n", " disease_state_row = None\n", " sample_chars_dict = get_unique_values_by_row(clinical_data)\n", " \n", " for row_idx, values in sample_chars_dict.items():\n", " values_str = str(values)\n", " if 'disease state' in values_str.lower():\n", " disease_state_row = row_idx\n", " print(f\"Found disease state information in row {row_idx}: {values}\")\n", " break\n", " \n", " if disease_state_row is not None:\n", " # Extract clinical features with proper disease state row\n", " selected_clinical = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=disease_state_row,\n", " convert_trait=convert_trait\n", " )\n", " \n", " print(f\"Selected clinical data with shape: {selected_clinical.shape}\")\n", " \n", " # Save the updated clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical.to_csv(out_clinical_data_file)\n", " print(f\"Updated clinical data saved to {out_clinical_data_file}\")\n", " \n", " is_trait_available = True\n", " else:\n", " print(\"Could not find disease state information in the clinical data.\")\n", " selected_clinical = pd.DataFrame()\n", " is_trait_available = False\n", " \n", "except Exception as e:\n", " print(f\"Error re-extracting clinical data: {e}\")\n", " selected_clinical = pd.DataFrame()\n", " is_trait_available = False\n", "\n", "# 3. 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", " # Use geo_link_clinical_genetic_data function to properly link the data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Check if we have the trait column in the linked data\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", " # 4. 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", " # 5. 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(f\"Reason: Trait column '{trait}' is not available in clinical data.\")\n", " if normalized_gene_data.empty:\n", " print(\"Reason: Gene expression data is empty.\")\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", " import traceback\n", " traceback.print_exc()\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 6. Final quality validation\n", "print(\"\\nPerforming final validation...\")\n", "note = \"\"\n", "if 'linked_data' in locals() and linked_data.empty:\n", " if not normalized_gene_data.empty and not selected_clinical.empty:\n", " note = \"Dataset failed in linking phase. Clinical data structure could not be properly matched with gene expression data.\"\n", " elif normalized_gene_data.empty:\n", " note = \"Dataset failed in gene mapping phase. Could not properly map probe IDs to gene symbols.\"\n", " elif selected_clinical.empty:\n", " note = \"Dataset failed in clinical data extraction. No valid trait information available.\"\n", "elif 'is_biased' in locals() and is_biased:\n", " note = \"Dataset passed initial processing but contains severely biased trait distribution.\"\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=not normalized_gene_data.empty,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased if 'is_biased' in locals() else True,\n", " df=linked_data if 'linked_data' in locals() and not linked_data.empty else pd.DataFrame(),\n", " note=note\n", ")\n", "\n", "# 7. 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 }