{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "740c60df", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:10.407912Z", "iopub.status.busy": "2025-03-25T07:16:10.407720Z", "iopub.status.idle": "2025-03-25T07:16:10.569885Z", "shell.execute_reply": "2025-03-25T07:16:10.569449Z" } }, "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_Chromophobe\"\n", "cohort = \"GSE42977\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Chromophobe\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Chromophobe/GSE42977\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Chromophobe/GSE42977.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Chromophobe/gene_data/GSE42977.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE42977.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Chromophobe/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "08d88196", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "a13387cb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:10.571217Z", "iopub.status.busy": "2025-03-25T07:16:10.571066Z", "iopub.status.idle": "2025-03-25T07:16:10.882328Z", "shell.execute_reply": "2025-03-25T07:16:10.881856Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Sequential Binary Gene-Ratio Tests Define a Novel Molecular Diagnostic Strategy for Malignant Pleural Mesothelioma\"\n", "!Series_summary\t\"The gene-expression ratio technique was used to design a molecular signature to diagnose MPM from among other potentially confounding diagnoses and differentiate the epithelioid from the sarcomatoid histological subtype of MPM.\"\n", "!Series_overall_design\t\"Microarray analysis was performed on 113 specimens including MPMs and a spectrum of tumors and benign tissues comprising the differential diagnosis of MPM. A sequential combination of binary gene-expression ratio tests was developed to discriminate MPM from other thoracic malignancies . This method was compared to other bioinformatic tools and this signature was validated in an independent set of 170 samples. Functional enrichment analysis was performed to identify differentially expressed probes.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: control', 'tissue: Spindle Cell Sarcoma', 'tissue: Sarcoma', 'tissue: Metastatic Melanoma', 'tissue: Pleomorphic Sarcoma', 'tissue: Renal Cell Carcinoma-Clear Cell', 'tissue: Synovial Sarcoma', 'tissue: Metastatic Thymoma', 'tissue: Metastatic Prostate Cancer', 'tissue: Stomach Cancer-Stromal Sarcoma', 'tissue: Non-Hodgkins Lymphoma', 'tissue: Hemangioendothelioma', 'tissue: Papillary Thyroid Carcinoma', 'tissue: Metastatic Thyroid Cancer', 'tissue: Lymphocytic Lymphoma', 'tissue: Thymoma', 'tissue: Melanoma-Malignant', 'tissue: Hemangiopericytoma', 'tissue: Thyroid Carcinoma', 'tissue: Monophasic Synovial Sarcoma', 'tissue: Metastatic Alveolar Soft Part Sarcoma', 'tissue: Metastatic Meningeal Hemangiopericytoma', 'tissue: Follicular Lymphoma', 'tissue: Rhabdomyosarcoma', 'tissue: Myofibrosarcoma', 'tissue: Renal Cell Carcinoma - Chromophobe', 'tissue: MPM Epithelioid', 'tissue: MPM Sarcomatoid', 'tissue: MPM Biphasic', 'tissue: Normal Lung']}\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": "d8c421bd", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9709c2a1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:10.883772Z", "iopub.status.busy": "2025-03-25T07:16:10.883654Z", "iopub.status.idle": "2025-03-25T07:16:10.914133Z", "shell.execute_reply": "2025-03-25T07:16:10.913733Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Features Preview:\n", "{0: [0.0], 1: [0.0], 2: [0.0], 3: [0.0], 4: [0.0], 5: [0.0], 6: [0.0], 7: [0.0], 8: [0.0], 9: [0.0], 10: [0.0], 11: [0.0], 12: [0.0], 13: [0.0], 14: [0.0], 15: [0.0], 16: [0.0], 17: [0.0], 18: [0.0], 19: [0.0], 20: [0.0], 21: [0.0], 22: [0.0], 23: [0.0], 24: [0.0], 25: [1.0], 26: [0.0], 27: [0.0], 28: [0.0], 29: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE42977.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "from typing import Dict, Any, Optional, Callable, List\n", "\n", "# 1. Assess gene expression data availability\n", "# This dataset appears to have gene expression data as it mentions microarray analysis\n", "# and gene-expression ratio tests in the background information\n", "is_gene_available = True\n", "\n", "# 2.1. Identify data availability and rows\n", "# Examining the sample characteristics dictionary\n", "sample_chars = {0: ['tissue: control', 'tissue: Spindle Cell Sarcoma', 'tissue: Sarcoma', 'tissue: Metastatic Melanoma', 'tissue: Pleomorphic Sarcoma', 'tissue: Renal Cell Carcinoma-Clear Cell', 'tissue: Synovial Sarcoma', 'tissue: Metastatic Thymoma', 'tissue: Metastatic Prostate Cancer', 'tissue: Stomach Cancer-Stromal Sarcoma', 'tissue: Non-Hodgkins Lymphoma', 'tissue: Hemangioendothelioma', 'tissue: Papillary Thyroid Carcinoma', 'tissue: Metastatic Thyroid Cancer', 'tissue: Lymphocytic Lymphoma', 'tissue: Thymoma', 'tissue: Melanoma-Malignant', 'tissue: Hemangiopericytoma', 'tissue: Thyroid Carcinoma', 'tissue: Monophasic Synovial Sarcoma', 'tissue: Metastatic Alveolar Soft Part Sarcoma', 'tissue: Metastatic Meningeal Hemangiopericytoma', 'tissue: Follicular Lymphoma', 'tissue: Rhabdomyosarcoma', 'tissue: Myofibrosarcoma', 'tissue: Renal Cell Carcinoma - Chromophobe', 'tissue: MPM Epithelioid', 'tissue: MPM Sarcomatoid', 'tissue: MPM Biphasic', 'tissue: Normal Lung']}\n", "\n", "# For Kidney_Chromophobe trait, we look for \"Renal Cell Carcinoma - Chromophobe\" in the tissue type\n", "trait_row = 0 # The row index containing tissue type information\n", "age_row = None # No age information available\n", "gender_row = None # No gender information available\n", "\n", "# 2.2. Define conversion functions\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert tissue type to binary: 1 for Kidney Chromophobe, 0 for others\n", " \"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " value_part = value.split(':', 1)[1].strip()\n", " \n", " # Check if the value indicates Kidney Chromophobe (RCC-Chromophobe)\n", " if 'Renal Cell Carcinoma - Chromophobe' in value_part:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"\n", " This is a placeholder function since age data is not available\n", " \"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"\n", " This is a placeholder function since gender data is not available\n", " \"\"\"\n", " return None\n", "\n", "# 3. Save metadata about the dataset\n", "is_trait_available = trait_row is not None\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. Extract clinical features if trait data is available\n", "if trait_row is not None:\n", " # Assuming clinical_data is a DataFrame with sample characteristics\n", " # We need to first create this DataFrame from the sample_chars dictionary\n", " clinical_data = pd.DataFrame()\n", " for row_idx, values in sample_chars.items():\n", " for col_idx, value in enumerate(values):\n", " clinical_data.loc[row_idx, col_idx] = value\n", " \n", " # Extract 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 extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical Features Preview:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data\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": "1e21ebc5", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "61afe3b3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:10.915550Z", "iopub.status.busy": "2025-03-25T07:16:10.915439Z", "iopub.status.idle": "2025-03-25T07:16:11.482295Z", "shell.execute_reply": "2025-03-25T07:16:11.481658Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene data with 46713 rows\n", "First 20 gene IDs:\n", "Index(['ILMN_10000', 'ILMN_100000', 'ILMN_100007', 'ILMN_100009', 'ILMN_10001',\n", " 'ILMN_100010', 'ILMN_10002', 'ILMN_100028', 'ILMN_100030',\n", " 'ILMN_100031', 'ILMN_100034', 'ILMN_100037', 'ILMN_10004', 'ILMN_10005',\n", " 'ILMN_100054', 'ILMN_100059', 'ILMN_10006', 'ILMN_100075',\n", " 'ILMN_100079', 'ILMN_100083'],\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": "16855802", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "0f958af1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:11.484192Z", "iopub.status.busy": "2025-03-25T07:16:11.483948Z", "iopub.status.idle": "2025-03-25T07:16:11.486221Z", "shell.execute_reply": "2025-03-25T07:16:11.485788Z" } }, "outputs": [], "source": [ "# Based on the gene IDs shown in the output, these are Illumina probe IDs (starting with \"ILMN_\") \n", "# and not standard human gene symbols. These probe IDs need to be mapped to human gene symbols \n", "# for proper analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "0d2aa9b2", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "ca3b559b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:11.488260Z", "iopub.status.busy": "2025-03-25T07:16:11.488150Z", "iopub.status.idle": "2025-03-25T07:16:18.197981Z", "shell.execute_reply": "2025-03-25T07:16:18.197312Z" } }, "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 5512256 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['ILMN_89282', 'ILMN_35826', 'ILMN_25544', 'ILMN_132331', 'ILMN_105017'], 'GB_ACC': ['BU678343', 'XM_497527.2', 'NM_018433.3', 'AW629334', 'AI818233'], 'Symbol': [nan, 'LOC441782', 'JMJD1A', nan, nan], 'SEQUENCE': ['CTCTCTAAAGGGACAACAGAGTGGACAGTCAAGGAACTCCACATATTCAT', 'GGGGTCAAGCCCAGGTGAAATGTGGATTGGAAAAGTGCTTCCCTTGCCCC', 'CCAGGCTGTAAAAGCAAAACCTCGTATCAGCTCTGGAACAATACCTGCAG', 'CCAGACAGGAAGCATCAAGCCCTTCAGGAAAGAATATGCGAGAGTGCTGC', 'TGTGCAGAAAGCTGATGGAAGGGAGAAAGAATGGAAGTGGGTCACACAGC'], 'Definition': ['UI-CF-EC0-abi-c-12-0-UI.s1 UI-CF-EC0 Homo sapiens cDNA clone UI-CF-EC0-abi-c-12-0-UI 3, mRNA sequence', 'PREDICTED: Homo sapiens similar to spectrin domain with coiled-coils 1 (LOC441782), mRNA.', 'Homo sapiens jumonji domain containing 1A (JMJD1A), mRNA.', 'hi56g05.x1 Soares_NFL_T_GBC_S1 Homo sapiens cDNA clone IMAGE:2976344 3, mRNA sequence', 'wk77d04.x1 NCI_CGAP_Pan1 Homo sapiens cDNA clone IMAGE:2421415 3, mRNA sequence'], 'Ontology': [nan, nan, nan, nan, nan], 'Synonym': [nan, nan, 'TSGA; JMJD1; KIAA0742; DKFZp686A24246; DKFZp686P07111', nan, nan]}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'GB_ACC', 'Symbol', 'SEQUENCE', 'Definition', 'Ontology', 'Synonym']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 5512256 out of 5512256\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": "e63e245c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "26090643", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:18.199889Z", "iopub.status.busy": "2025-03-25T07:16:18.199767Z", "iopub.status.idle": "2025-03-25T07:16:18.587882Z", "shell.execute_reply": "2025-03-25T07:16:18.587360Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping between probe IDs and gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Extracted mapping data with 28566 rows\n", "\n", "Mapping data preview:\n", " ID Gene\n", "1 ILMN_35826 LOC441782\n", "2 ILMN_25544 JMJD1A\n", "6 ILMN_10519 NCOA3\n", "8 ILMN_17234 LOC389834\n", "9 ILMN_19244 C17orf77\n", "\n", "Number of unique probe IDs in mapping: 28566\n", "Number of unique genes in mapping: 24998\n", "\n", "Converting probe-level measurements to gene expression data...\n", "Generated gene expression data with 18401 genes and 117 samples\n", "\n", "Gene expression data preview (first few genes):\n", " GSM1054230 GSM1054231 GSM1054232 GSM1054233 GSM1054234 \\\n", "Gene \n", "A1BG 0.903276 0.821580 0.865428 0.890772 0.986434 \n", "A2BP1 1.719921 8.432093 1.797852 6.514504 1.802560 \n", "A2M 27.154642 17.070914 34.490890 9.773921 31.282731 \n", "A2ML1 0.893226 0.963602 0.996714 1.108153 0.855068 \n", "A3GALT2 1.357179 1.423179 1.518340 1.352150 1.415984 \n", "\n", " GSM1054235 GSM1054236 GSM1054237 GSM1054238 GSM1054239 ... \\\n", "Gene ... \n", "A1BG 1.197420 0.886271 1.117455 1.003215 0.865700 ... \n", "A2BP1 1.728039 1.944330 1.763054 1.856389 1.854349 ... \n", "A2M 20.569610 65.495478 77.842674 30.995838 41.236381 ... \n", "A2ML1 1.076572 0.943271 1.017992 0.925794 0.964499 ... \n", "A3GALT2 1.592975 1.484345 1.446382 1.389944 1.314923 ... \n", "\n", " GSM1054337 GSM1054338 GSM1054339 GSM1054340 GSM1054341 \\\n", "Gene \n", "A1BG 0.855990 0.897686 0.884723 0.925664 1.061455 \n", "A2BP1 1.788184 1.782779 1.929292 1.930075 1.844573 \n", "A2M 35.781895 43.580901 32.651689 25.655624 28.996303 \n", "A2ML1 1.070994 1.050752 1.000574 1.029542 1.056357 \n", "A3GALT2 1.488361 1.419631 1.593990 1.414248 1.362292 \n", "\n", " GSM1054342 GSM1054343 GSM1054344 GSM1054345 GSM1054346 \n", "Gene \n", "A1BG 0.868972 0.961211 0.802412 0.964033 1.097807 \n", "A2BP1 1.753932 1.859075 1.523183 1.742777 1.799859 \n", "A2M 22.165116 21.972497 22.618258 22.302836 34.703123 \n", "A2ML1 1.102940 0.976782 1.146317 1.128793 0.950305 \n", "A3GALT2 1.279548 1.113990 1.113299 1.135271 1.320155 \n", "\n", "[5 rows x 117 columns]\n" ] } ], "source": [ "# 1. Determine which columns to use for mapping\n", "# The gene expression data uses Illumina probe IDs (e.g., \"ILMN_10000\")\n", "# From the gene annotation preview, we can see that:\n", "# - The 'ID' column contains the same Illumina probe IDs\n", "# - The 'Symbol' column contains the gene symbols we need for mapping\n", "\n", "# 2. Extract the mapping columns from the gene annotation dataframe\n", "print(\"Creating gene mapping between probe IDs and gene symbols...\")\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "print(f\"Extracted mapping data with {len(mapping_df)} rows\")\n", "\n", "# Preview the mapping data\n", "print(\"\\nMapping data preview:\")\n", "print(mapping_df.head())\n", "\n", "# Check how many unique probe IDs and genes we have\n", "print(f\"\\nNumber of unique probe IDs in mapping: {mapping_df['ID'].nunique()}\")\n", "print(f\"Number of unique genes in mapping: {mapping_df['Gene'].nunique()}\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression\n", "print(\"\\nConverting probe-level measurements to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Generated gene expression data with {len(gene_data)} genes and {gene_data.shape[1]} samples\")\n", "\n", "# Preview the gene expression data\n", "print(\"\\nGene expression data preview (first few genes):\")\n", "print(gene_data.head())\n" ] }, { "cell_type": "markdown", "id": "eece6fb8", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "729228a3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:18.589783Z", "iopub.status.busy": "2025-03-25T07:16:18.589657Z", "iopub.status.idle": "2025-03-25T07:16:22.210239Z", "shell.execute_reply": "2025-03-25T07:16:22.209615Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 17207 unique gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Kidney_Chromophobe/gene_data/GSE42977.csv\n", "\n", "Loading previously saved clinical data...\n", "Loaded clinical data with shape: (1, 30)\n", "Clinical data preview:\n", "{'0': [0.0], '1': [0.0], '2': [0.0], '3': [0.0], '4': [0.0], '5': [0.0], '6': [0.0], '7': [0.0], '8': [0.0], '9': [0.0], '10': [0.0], '11': [0.0], '12': [0.0], '13': [0.0], '14': [0.0], '15': [0.0], '16': [0.0], '17': [0.0], '18': [0.0], '19': [0.0], '20': [0.0], '21': [0.0], '22': [0.0], '23': [0.0], '24': [0.0], '25': [1.0], '26': [0.0], '27': [0.0], '28': [0.0], '29': [0.0]}\n", "\n", "Linking clinical and genetic data...\n", "Clinical data has 30 samples\n", "Genetic data has 117 samples\n", "Found 0 common samples between datasets\n", "Clinical sample format example: 0\n", "Genetic sample format example: GSM1054230\n", "No matching sample IDs found - formats appear to be different\n", "Linked data by sample position: shape (30, 17208)\n", "Number of samples with trait values: 30\n", "\n", "Customizing missing value handling...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After customized missing value handling, data shape: (30, 17208)\n", "\n", "Checking for bias in features...\n", "For the feature 'Kidney_Chromophobe', the least common label is '1.0' with 1 occurrences. This represents 3.33% of the dataset.\n", "The distribution of the feature 'Kidney_Chromophobe' in this dataset is severely biased.\n", "\n", "\n", "Performing final validation...\n", "Dataset not usable for Kidney_Chromophobe association studies. Data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "try:\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\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. Load the previously saved clinical data\n", "print(\"\\nLoading previously saved clinical data...\")\n", "try:\n", " if os.path.exists(out_clinical_data_file):\n", " clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(preview_df(clinical_df))\n", " is_trait_available = True\n", " else:\n", " print(\"Clinical data file not found, using data from previous step\")\n", " clinical_df = pd.DataFrame()\n", " is_trait_available = False\n", "except Exception as e:\n", " print(f\"Error loading clinical features: {e}\")\n", " is_trait_available = False\n", " clinical_df = None\n", "\n", "# 3. Link clinical and genetic data if available\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if clinical_df is not None and not normalized_gene_data.empty:\n", " # Analyze samples in both datasets\n", " clinical_samples = clinical_df.columns.tolist()\n", " genetic_samples = normalized_gene_data.columns.tolist()\n", " print(f\"Clinical data has {len(clinical_samples)} samples\")\n", " print(f\"Genetic data has {len(genetic_samples)} samples\")\n", " \n", " # Find common samples\n", " common_samples = [s for s in clinical_samples if s in genetic_samples]\n", " print(f\"Found {len(common_samples)} common samples between datasets\")\n", " \n", " if len(common_samples) == 0:\n", " # Sample ID formats might be different, but could match positions\n", " # Compare a few IDs to check format differences\n", " if len(clinical_samples) > 0 and len(genetic_samples) > 0:\n", " print(f\"Clinical sample format example: {clinical_samples[0]}\")\n", " print(f\"Genetic sample format example: {genetic_samples[0]}\")\n", " print(\"No matching sample IDs found - formats appear to be different\")\n", " \n", " # Use sample positions for linking if possible\n", " if len(clinical_samples) <= len(genetic_samples):\n", " # Rename genetic samples to match clinical format\n", " genetic_subset = normalized_gene_data.iloc[:, :len(clinical_samples)]\n", " genetic_subset.columns = clinical_samples\n", " \n", " # Now link with renamed samples\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, genetic_subset)\n", " print(f\"Linked data by sample position: shape {linked_data.shape}\")\n", " else:\n", " print(\"Cannot link data: clinical samples exceed genetic samples\")\n", " linked_data = pd.DataFrame()\n", " else:\n", " # Use common samples for linking\n", " clinical_subset = clinical_df[common_samples]\n", " genetic_subset = normalized_gene_data[common_samples]\n", " linked_data = geo_link_clinical_genetic_data(clinical_subset, genetic_subset)\n", " print(f\"Linked data with common samples: shape {linked_data.shape}\")\n", " \n", " # Check for trait column\n", " if linked_data.shape[0] > 0:\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", " # Customize missing value handling for this dataset\n", " print(\"\\nCustomizing missing value handling...\")\n", " \n", " # Simple approach: drop samples with missing trait values\n", " linked_data = linked_data.dropna(subset=[trait])\n", " \n", " # Ensure trait is correctly formatted as numeric\n", " linked_data[trait] = pd.to_numeric(linked_data[trait], errors='coerce')\n", " \n", " # For columns with majority missing values, drop them\n", " missing_pct = linked_data.isna().mean()\n", " keep_cols = [col for col in linked_data.columns if missing_pct[col] < 0.5]\n", " linked_data = linked_data[keep_cols]\n", " \n", " # Fill remaining missing values\n", " linked_data = linked_data.fillna(linked_data.mean())\n", " \n", " print(f\"After customized missing value handling, data shape: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] > 0:\n", " # Check for bias in features\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\"Error: Trait column '{trait}' not found in linked data\")\n", " print(f\"Available columns: {linked_data.columns.tolist()[:10]}...\")\n", " is_biased = True\n", " else:\n", " print(\"Linked data is empty. Dataset cannot be used.\")\n", " is_biased = True\n", " else:\n", " print(\"Cannot link data: clinical or genetic data is missing\")\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", "# 4. Final quality validation\n", "print(\"\\nPerforming final validation...\")\n", "try:\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\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=\"Dataset contains normalized gene expression data but has limitations in clinical annotations and sample matching\"\n", " )\n", "except Exception as e:\n", " print(f\"Error in final validation: {e}\")\n", " is_usable = False\n", "\n", "# 5. 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 }