{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "980a376b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:35.717260Z", "iopub.status.busy": "2025-03-25T07:16:35.717096Z", "iopub.status.idle": "2025-03-25T07:16:35.881830Z", "shell.execute_reply": "2025-03-25T07:16:35.881484Z" } }, "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 = \"GSE95425\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Chromophobe\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Chromophobe/GSE95425\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Chromophobe/GSE95425.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Chromophobe/gene_data/GSE95425.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE95425.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Chromophobe/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "9d80d14a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "c2f3241f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:35.883330Z", "iopub.status.busy": "2025-03-25T07:16:35.883189Z", "iopub.status.idle": "2025-03-25T07:16:35.972044Z", "shell.execute_reply": "2025-03-25T07:16:35.971727Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Cell-type specific gene programs of the normal human nephron define kidney cancer subtypes\"\n", "!Series_summary\t\"Comprehensive transcriptome studies of cancers often rely on corresponding normal tissue samples to serve as a transcriptional reference. In this study we performed in-depth analyses of normal kidney tissue transcriptomes from TCGA and demonstrate that the histological variability in cellularity, inherent in the kidney architecture, lead to considerable transcriptional differences between samples. This should be considered when comparing expression profiles of normal and cancerous kidney tissues. We exploited these differences to define renal cell-specific gene signatures and used these as framework to analyze renal cell carcinoma (RCC) ontogeny. Chromophobe RCCs express FOXI1-driven genes that define collecting duct intercalated cells whereas HNF-regulated genes, specific for proximal tubule cells, are an integral part of clear cell and papillary RCC transcriptomes. These networks may be used as framework for understanding the interplay between genomic changes in RCC subtypes and the lineage-defining regulatory machinery of their non-neoplastic counterparts.\"\n", "!Series_overall_design\t\"Samples from different parts of the kidneys were procured using core-sampling from approximately 10 mm thick sections obtained from nephrectomized patients in surgery for renal neoplasms. Sampling was performed in the part of the kidney that was farthest from the tumor. Sections were thereafter embedded and hematoxylin-eosin stained allowing for approximation of the respective site in kidney from which the sample was obtained. In all cases a histologically normal kidney histology was confirmed. In all, 53 samples from 5 different renal specimens were included in the analysis.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient id: R099', 'patient id: R116', 'patient id: R127', 'patient id: R134', 'patient id: R164'], 1: ['patient type: Normal kidney tissue'], 2: ['sampling depth: cortex', 'sampling depth: cortex/medulla', 'sampling depth: medulla']}\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": "335e153e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "83c10b41", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:35.973167Z", "iopub.status.busy": "2025-03-25T07:16:35.973059Z", "iopub.status.idle": "2025-03-25T07:16:35.977534Z", "shell.execute_reply": "2025-03-25T07:16:35.977243Z" } }, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# Gene Expression Availability\n", "# Based on the Series_summary, this study is about transcriptomes of normal kidney tissue,\n", "# which suggests gene expression data is available\n", "is_gene_available = True\n", "\n", "# Data Availability and Type Conversion\n", "# For trait (Kidney_Chromophobe), we can use the sampling depth as a proxy (row 2)\n", "# It seems the samples are from different depths of kidney tissue (cortex, cortex/medulla, medulla)\n", "trait_row = 2\n", "\n", "# No explicit age information is available\n", "age_row = None\n", "\n", "# No explicit gender information is available\n", "gender_row = None\n", "\n", "# Conversion functions\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert sampling depth information to a binary value:\n", " 1 for cortex (since we're studying kidney chromophobe which is related to cortex),\n", " 0 for medulla, and 0.5 for mixed cortex/medulla\n", " \"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if 'cortex' in value and 'medulla' in value:\n", " return 0.5 # Mixed\n", " elif 'cortex' in value:\n", " return 1 # Cortex\n", " elif 'medulla' in value:\n", " return 0 # Medulla\n", " else:\n", " return None\n", "\n", "# Since age and gender are not available, we don't need to define their conversion functions\n", "convert_age = None\n", "convert_gender = None\n", "\n", "# Save metadata\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", "# If trait data is available, extract clinical features\n", "if trait_row is not None:\n", " # Load the clinical data\n", " clinical_data_path = os.path.join(in_cohort_dir, 'clinical_data.csv')\n", " if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_csv(clinical_data_path)\n", " \n", " # Extract clinical features\n", " clinical_features = 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 dataframe\n", " preview = preview_df(clinical_features)\n", " print(\"Clinical features preview:\", 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 to CSV\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "555855d7", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "66c53c09", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:35.978551Z", "iopub.status.busy": "2025-03-25T07:16:35.978444Z", "iopub.status.idle": "2025-03-25T07:16:36.134260Z", "shell.execute_reply": "2025-03-25T07:16:36.133907Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n", "Successfully extracted gene data with 27367 rows\n", "First 20 gene IDs:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651209', 'ILMN_1651228',\n", " 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651236',\n", " 'ILMN_1651238', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259',\n", " 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278',\n", " 'ILMN_1651281', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286'],\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": "fff1bdd0", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "ba236eca", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:36.135545Z", "iopub.status.busy": "2025-03-25T07:16:36.135419Z", "iopub.status.idle": "2025-03-25T07:16:36.137440Z", "shell.execute_reply": "2025-03-25T07:16:36.137134Z" } }, "outputs": [], "source": [ "# Let's analyze the gene identifiers shown in the output\n", "# The identifiers starting with \"ILMN_\" indicate these are Illumina probe IDs,\n", "# not standard human gene symbols. Illumina is a microarray platform, and these\n", "# IDs need to be mapped to standard gene symbols.\n", "\n", "# Illumina probe IDs (like ILMN_1343291) need to be converted to gene symbols\n", "# for proper biological interpretation and cross-platform compatibility\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "f177f7e9", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "8abfcd72", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:36.138571Z", "iopub.status.busy": "2025-03-25T07:16:36.138462Z", "iopub.status.idle": "2025-03-25T07:16:39.794450Z", "shell.execute_reply": "2025-03-25T07:16:39.794078Z" } }, "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 1498611 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 47323 out of 1498611\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": "a2bde7b3", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "f81f00ce", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:39.796016Z", "iopub.status.busy": "2025-03-25T07:16:39.795777Z", "iopub.status.idle": "2025-03-25T07:16:40.517308Z", "shell.execute_reply": "2025-03-25T07:16:40.516912Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping from probe IDs to gene symbols...\n", "Created mapping with 44837 entries\n", "\n", "Sample of gene mapping (first 5 rows):\n", " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "\n", "Converting probe-level measurements to gene expression data...\n", "Converted to gene expression data with 17999 genes\n", "\n", "Preview of gene expression data (first 5 rows):\n", "{'GSM2510512': [872.3328899999999, 11.0, 22.0, 3095.599, 1837.8201], 'GSM2510513': [529.13506, 11.0, 22.0, 1993.715, 2131.865], 'GSM2510514': [55.676279, 11.0, 22.0, 183.4023, 2454.2156], 'GSM2510515': [52.654965000000004, 11.0, 22.0, 193.08295, 1946.8962], 'GSM2510516': [832.20962, 11.0, 22.0, 3110.6108, 2073.256], 'GSM2510517': [1360.64394, 11.0, 22.0, 1384.135, 2864.6042], 'GSM2510518': [1368.9527165, 11.0, 22.0, 1532.8215, 2951.128], 'GSM2510519': [1533.6409039999999, 11.0, 22.0, 1205.4614, 2807.1365], 'GSM2510520': [1562.745696, 11.0, 32.489699, 1283.1249, 3215.11], 'GSM2510521': [933.368998, 11.0, 23.894692, 873.89545, 3413.5544], 'GSM2510522': [51.395092000000005, 11.0, 22.0, 170.76437, 3335.5144], 'GSM2510523': [39.869029, 11.0, 24.117759, 121.04247, 3237.8586], 'GSM2510524': [935.773576, 11.0, 22.0, 1180.9115, 4329.2563], 'GSM2510525': [1527.8258429999998, 11.0, 22.0, 1339.8024, 3603.318], 'GSM2510526': [1371.70434, 11.0, 23.962249999999997, 1433.5597, 3470.304], 'GSM2510527': [42.690068, 11.0, 22.0, 93.94554, 5261.3115], 'GSM2510528': [1465.6894539999998, 11.0, 22.0, 1386.3071, 3136.0098], 'GSM2510529': [1311.75817, 11.0, 23.086296, 379.8976, 1184.7294], 'GSM2510530': [101.295492, 11.0, 22.0, 112.62307, 1955.1335], 'GSM2510531': [47.469662, 11.0, 27.1514, 87.183014, 1038.2617], 'GSM2510532': [35.690842, 11.0, 22.0, 88.86818, 1425.7654], 'GSM2510533': [2018.043818, 11.0, 22.814933, 2121.634, 1111.7844], 'GSM2510534': [101.663408, 11.0, 26.122869, 251.01561, 1937.2194], 'GSM2510535': [44.1849535, 12.845573, 27.5292515, 137.54932, 3470.304], 'GSM2510536': [2051.2570339999997, 11.0, 22.0, 1710.6075, 1148.4624], 'GSM2510537': [409.070391, 11.0, 25.483086, 765.54126, 1766.6683], 'GSM2510538': [43.668233, 11.0, 29.470469, 116.827324, 2349.7954], 'GSM2510539': [2045.155683, 11.0, 33.111835, 1647.8601, 1265.8164], 'GSM2510540': [1956.343963, 11.0, 22.0, 1812.7164, 1214.2676], 'GSM2510541': [2104.188781, 11.0, 22.0, 2936.9456, 1712.44], 'GSM2510542': [104.200416, 11.0, 24.436681, 301.06412, 2068.168], 'GSM2510543': [301.059822, 11.0, 22.0, 589.3337, 2367.6558], 'GSM2510544': [2169.367546, 11.0, 22.0, 2440.214, 1803.8013], 'GSM2510545': [1320.9640219999999, 11.0, 22.0, 2569.875, 1589.5535], 'GSM2510546': [474.98471900000004, 11.0, 23.422093, 578.22485, 2464.6843], 'GSM2510547': [567.8003150000001, 11.0, 22.0, 842.2657, 2335.4602], 'GSM2510548': [2156.020777, 11.0, 22.0, 2569.875, 1348.6691], 'GSM2510549': [1608.820542, 11.0, 22.0, 2607.201, 1946.8962], 'GSM2510550': [123.687578, 11.0, 22.0, 355.28568, 2019.0583], 'GSM2510551': [64.15707, 11.0, 22.048776, 159.59857, 1975.2699], 'GSM2510552': [2031.982165, 11.0, 22.0, 3161.3606, 1576.4044], 'GSM2510553': [562.449177, 11.0, 22.0, 1316.7535, 2623.531], 'GSM2510554': [2181.5946400000003, 11.0, 22.0, 2619.7034, 1845.374], 'GSM2510555': [37.126117, 11.0, 22.0, 188.29924, 2143.1885], 'GSM2510556': [72.53929, 11.0, 22.0, 214.37617, 2860.829], 'GSM2510557': [2058.9288850000003, 11.0, 22.0, 2631.5579, 1911.3302], 'GSM2510558': [2149.916889, 11.0, 22.0, 2768.2288, 1565.4874], 'GSM2510559': [748.7576670000001, 11.0, 29.200922, 1488.6082, 2565.6958], 'GSM2510560': [351.427136, 11.0, 23.455844, 993.36816, 2353.7473], 'GSM2510561': [1309.15126, 11.0, 26.795219, 2443.24, 2082.7336], 'GSM2510562': [1851.9362310000001, 11.0, 22.0, 2392.5454, 1199.6433], 'GSM2510563': [2129.819004, 11.0, 22.0, 2550.1956, 1508.5835], 'GSM2510564': [248.04747699999996, 11.0, 22.0, 626.13556, 2740.445]}\n", "\n", "Null values: 0.00% of the data\n", "\n", "Normalizing gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 17405 unique genes\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Saved gene expression data to ../../output/preprocess/Kidney_Chromophobe/gene_data/GSE95425.csv\n" ] } ], "source": [ "# 1. Identify mapping columns\n", "# From the output, we can see:\n", "# - The gene expression data uses 'ILMN_' IDs as identifiers (e.g., ILMN_1343291)\n", "# - The gene annotation data has an 'ID' column containing these same identifiers\n", "# - The 'Symbol' column in the annotation contains gene symbols\n", "\n", "# 2. Extract mapping between probe IDs and gene symbols\n", "print(\"Creating gene mapping from probe IDs to gene symbols...\")\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", "print(f\"Created mapping with {len(gene_mapping)} entries\")\n", "\n", "# Show a sample of the mapping\n", "print(\"\\nSample of gene mapping (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply the 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, gene_mapping)\n", "print(f\"Converted to gene expression data with {len(gene_data)} genes\")\n", "\n", "# Verify the result with a preview\n", "print(\"\\nPreview of gene expression data (first 5 rows):\")\n", "print(preview_df(gene_data.head()))\n", "\n", "# Check for data integrity\n", "non_null_count = gene_data.count().sum()\n", "total_elements = gene_data.size\n", "null_percentage = 100 - (non_null_count / total_elements * 100)\n", "print(f\"\\nNull values: {null_percentage:.2f}% of the data\")\n", "\n", "# Normalize gene symbols to standard format\n", "print(\"\\nNormalizing gene symbols...\")\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization: {len(gene_data)} unique genes\")\n", "\n", "# Save the processed 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\"\\nSaved gene expression data to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "c34556a2", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "ccb204a5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:40.518699Z", "iopub.status.busy": "2025-03-25T07:16:40.518578Z", "iopub.status.idle": "2025-03-25T07:16:48.520554Z", "shell.execute_reply": "2025-03-25T07:16:48.519952Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Extracting clinical features...\n", "Clinical data saved to ../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE95425.csv\n", "\n", "Linking clinical and genetic data...\n", "First few clinical sample columns: ['GSM2510512', 'GSM2510513', 'GSM2510514', 'GSM2510515', 'GSM2510516']\n", "First few genetic sample columns: ['GSM2510512', 'GSM2510513', 'GSM2510514', 'GSM2510515', 'GSM2510516']\n", "Linked data shape: (53, 17406)\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (53, 17406)\n", "\n", "Checking for bias in features...\n", "Quartiles for 'Kidney_Chromophobe':\n", " 25%: 0.0\n", " 50% (Median): 0.5\n", " 75%: 1.0\n", "Min: 0.0\n", "Max: 1.0\n", "The distribution of the feature 'Kidney_Chromophobe' 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_Chromophobe/GSE95425.csv\n" ] } ], "source": [ "# 1. Extract clinical features first since we didn't do this properly in Step 2\n", "print(\"\\nExtracting clinical features...\")\n", "try:\n", " # Get the trait row, which was identified in step 2\n", " trait_row = 2\n", " \n", " # Define convert_trait function as it was defined in step 2\n", " def convert_trait(value):\n", " \"\"\"\n", " Convert sampling depth information to a binary value:\n", " 1 for cortex (since we're studying kidney chromophobe which is related to cortex),\n", " 0 for medulla, and 0.5 for mixed cortex/medulla\n", " \"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if 'cortex' in value and 'medulla' in value:\n", " return 0.5 # Mixed\n", " elif 'cortex' in value:\n", " return 1 # Cortex\n", " elif 'medulla' in value:\n", " return 0 # Medulla\n", " else:\n", " return None\n", " \n", " # Extract clinical features\n", " 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=None,\n", " convert_age=None,\n", " gender_row=None,\n", " convert_gender=None\n", " )\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 clinical data\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error extracting clinical features: {e}\")\n", " is_trait_available = False\n", " clinical_df = None\n", "\n", "# 2. 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 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(gene_data.columns)[:5])\n", " \n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \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", " # 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(\"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", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 5. Final quality validation\n", "print(\"\\nPerforming final validation...\")\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() else pd.DataFrame(),\n", " note=\"Kidney tissue samples with different sampling depths (cortex/medulla) used to study kidney chromophobe\"\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 }