{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "45874ab5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:22:46.689277Z", "iopub.status.busy": "2025-03-25T07:22:46.689099Z", "iopub.status.idle": "2025-03-25T07:22:46.853841Z", "shell.execute_reply": "2025-03-25T07:22:46.853529Z" } }, "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_Papillary_Cell_Carcinoma\"\n", "cohort = \"GSE95425\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma/GSE95425\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/GSE95425.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE95425.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE95425.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "d1648a5b", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "779b1e70", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:22:46.855277Z", "iopub.status.busy": "2025-03-25T07:22:46.855134Z", "iopub.status.idle": "2025-03-25T07:22:46.936243Z", "shell.execute_reply": "2025-03-25T07:22:46.935928Z" } }, "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": "c0e9a3af", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b791f55d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:22:46.937236Z", "iopub.status.busy": "2025-03-25T07:22:46.937132Z", "iopub.status.idle": "2025-03-25T07:22:46.957312Z", "shell.execute_reply": "2025-03-25T07:22:46.957013Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview:\n", "{'GSM2510512': [0.0], 'GSM2510513': [nan], 'GSM2510514': [1.0], 'GSM2510515': [1.0], 'GSM2510516': [0.0], 'GSM2510517': [0.0], 'GSM2510518': [0.0], 'GSM2510519': [0.0], 'GSM2510520': [0.0], 'GSM2510521': [1.0], 'GSM2510522': [1.0], 'GSM2510523': [1.0], 'GSM2510524': [0.0], 'GSM2510525': [0.0], 'GSM2510526': [0.0], 'GSM2510527': [1.0], 'GSM2510528': [0.0], 'GSM2510529': [0.0], 'GSM2510530': [1.0], 'GSM2510531': [1.0], 'GSM2510532': [1.0], 'GSM2510533': [0.0], 'GSM2510534': [1.0], 'GSM2510535': [1.0], 'GSM2510536': [nan], 'GSM2510537': [1.0], 'GSM2510538': [1.0], 'GSM2510539': [0.0], 'GSM2510540': [0.0], 'GSM2510541': [0.0], 'GSM2510542': [1.0], 'GSM2510543': [1.0], 'GSM2510544': [0.0], 'GSM2510545': [nan], 'GSM2510546': [1.0], 'GSM2510547': [1.0], 'GSM2510548': [0.0], 'GSM2510549': [nan], 'GSM2510550': [1.0], 'GSM2510551': [1.0], 'GSM2510552': [0.0], 'GSM2510553': [1.0], 'GSM2510554': [0.0], 'GSM2510555': [1.0], 'GSM2510556': [1.0], 'GSM2510557': [0.0], 'GSM2510558': [0.0], 'GSM2510559': [nan], 'GSM2510560': [1.0], 'GSM2510561': [nan], 'GSM2510562': [0.0], 'GSM2510563': [0.0], 'GSM2510564': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE95425.csv\n" ] } ], "source": [ "# 1. Check if gene expression data is available\n", "is_gene_available = True # As per background information, this seems to be a gene expression study of normal kidney tissue\n", "\n", "# 2. Analyze clinical data availability and create conversion functions\n", "trait_row = 2 # 'sampling depth' can be used to categorize tissue samples\n", "age_row = None # Age information is not available\n", "gender_row = None # Gender information is not available\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert sampling depth information to binary values (0 for cortex, 1 for medulla)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if \"cortex\" in value and \"medulla\" in value:\n", " # Mixed sample - we'll treat as None since it's neither purely cortex nor medulla\n", " return None\n", " elif \"cortex\" in value:\n", " return 0 # Cortex\n", " elif \"medulla\" in value:\n", " return 1 # Medulla\n", " \n", " return None\n", "\n", "# Define empty conversion functions for age and gender since they're not available\n", "def convert_age(value):\n", " return None\n", "\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. 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", "# 4. Extract clinical features\n", "if trait_row is not None:\n", " # Assuming clinical_data was previously loaded\n", " clinical_df = geo_select_clinical_features(\n", " clinical_data,\n", " trait=\"Sampling_Depth\",\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 and save the clinical data\n", " print(\"Clinical Data Preview:\")\n", " print(preview_df(clinical_df))\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 to CSV\n", " 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": "be867313", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "7248f0b5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:22:46.958359Z", "iopub.status.busy": "2025-03-25T07:22:46.958258Z", "iopub.status.idle": "2025-03-25T07:22:47.116056Z", "shell.execute_reply": "2025-03-25T07:22:47.115528Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Cell-type specific gene programs of the normal human nephron define kidney cancer subtypes\"\n", "Line 1: !Series_geo_accession\t\"GSE95425\"\n", "Line 2: !Series_status\t\"Public on Aug 07 2017\"\n", "Line 3: !Series_submission_date\t\"Feb 27 2017\"\n", "Line 4: !Series_last_update_date\t\"Sep 19 2019\"\n", "Line 5: !Series_pubmed_id\t\"28793269\"\n", "Line 6: !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", "Line 7: !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", "Line 8: !Series_type\t\"Expression profiling by array\"\n", "Line 9: !Series_contributor\t\"David,,Lindgren\"\n", "Found table marker at line 71\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM2510512\"\t\"GSM2510513\"\t\"GSM2510514\"\t\"GSM2510515\"\t\"GSM2510516\"\t\"GSM2510517\"\t\"GSM2510518\"\t\"GSM2510519\"\t\"GSM2510520\"\t\"GSM2510521\"\t\"GSM2510522\"\t\"GSM2510523\"\t\"GSM2510524\"\t\"GSM2510525\"\t\"GSM2510526\"\t\"GSM2510527\"\t\"GSM2510528\"\t\"GSM2510529\"\t\"GSM2510530\"\t\"GSM2510531\"\t\"GSM2510532\"\t\"GSM2510533\"\t\"GSM2510534\"\t\"GSM2510535\"\t\"GSM2510536\"\t\"GSM2510537\"\t\"GSM2510538\"\t\"GSM2510539\"\t\"GSM2510540\"\t\"GSM2510541\"\t\"GSM2510542\"\t\"GSM2510543\"\t\"GSM2510544\"\t\"GSM2510545\"\t\"GSM2510546\"\t\"GSM2510547\"\t\"GSM2510548\"\t\"GSM2510549\"\t\"GSM2510550\"\t\"GSM2510551\"\t\"GSM2510552\"\t\"GSM2510553\"\t\"GSM2510554\"\t\"GSM2510555\"\t\"GSM2510556\"\t\"GSM2510557\"\t\"GSM2510558\"\t\"GSM2510559\"\t\"GSM2510560\"\t\"GSM2510561\"\t\"GSM2510562\"\t\"GSM2510563\"\t\"GSM2510564\"\n", "\"ILMN_1343291\"\t21416.965\t20471.84\t19279.266\t18744.207\t17861.898\t21416.965\t19691.62\t20471.84\t21416.965\t19279.266\t18343.49\t19691.62\t19279.266\t21416.965\t20471.84\t20471.84\t20471.84\t21416.965\t20471.84\t21416.965\t17182.785\t20471.84\t19691.62\t19279.266\t21416.965\t21416.965\t18744.207\t21416.965\t19691.62\t18343.49\t19279.266\t21416.965\t21416.965\t20471.84\t20471.84\t21416.965\t20471.84\t20471.84\t18744.207\t21416.965\t16873.422\t20471.84\t19279.266\t20471.84\t20471.84\t17861.898\t19691.62\t20471.84\t21416.965\t20471.84\t19279.266\t21416.965\t19691.62\n", "\"ILMN_1343295\"\t3779.5352\t3140.8442\t3243.7913\t3779.5352\t3660.2346\t3418.5916\t3437.193\t3038.3975\t3603.318\t2849.2954\t4353.7695\t4306.432\t2940.9995\t3161.3606\t3166.3428\t3249.8838\t3282.3171\t4788.355\t4749.9214\t6540.1123\t4712.049\t5261.3115\t3969.004\t4047.6267\t4816.5137\t3638.591\t4260.182\t4712.049\t4576.618\t4871.3843\t5181.525\t4365.0625\t4293.5796\t4497.482\t4306.432\t5155.966\t5155.966\t4602.2446\t4260.182\t4523.802\t5141.7563\t4106.847\t4774.8633\t4510.4727\t4842.1987\t5214.601\t4561.756\t4147.222\t4306.432\t4544.675\t5097.576\t4655.5254\t4436.1733\n", "\"ILMN_1651209\"\t11\t17.59506\t17.46359\t13.653342\t13.470478\t13.911773\t21.390825\t23.141996\t13.721687\t18.991056\t20.741686\t33.902534\t15.122869\t12.086296\t12.251597\t15.106336\t17.837526\t24.611845\t21.883617\t19.915628\t11\t11\t27.681795\t30.378868\t21.609922\t19.864428\t18.694729\t11.648846\t19.482737\t18.941504\t21.609922\t28.704924\t20.853231\t16.421354\t22.244642\t23.989117\t17.820253\t21.91488\t18.167496\t26.119518\t16.467424\t21.64486\t11\t12.251597\t28.57014\t21.928904\t11\t14.141491\t17.98868\t11\t28.474491\t22.111835\t24.696728\n", "\"ILMN_1651228\"\t6571.3975\t7527.4707\t6209.078\t5902.29\t7317.747\t6512.0347\t7444.3438\t7686.499\t7483.67\t8299.52\t5967.5747\t5307.057\t7345.2505\t6597.637\t6076.3457\t8520.89\t8132.5337\t3483.4578\t3744.7996\t3161.3606\t3489.7334\t3418.5916\t4106.847\t3215.11\t3406.3845\t3534.03\t4057.6711\t3696.34\t4106.847\t3617.6086\t2966.9666\t3489.7334\t3061.8374\t3489.7334\t4200.6465\t4897.958\t2554.7805\t3259.611\t3696.34\t3061.8374\t3476.0662\t4612.691\t3858.6177\t3095.599\t4066.4678\t4008.344\t3960.4128\t3061.8374\t3910.748\t4270.761\t3202.552\t3842.1963\t4158.447\n", "Total lines examined: 72\n", "\n", "Attempting to extract 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", "# 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": "b9b22de6", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "af3ed153", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:22:47.117526Z", "iopub.status.busy": "2025-03-25T07:22:47.117412Z", "iopub.status.idle": "2025-03-25T07:22:47.119578Z", "shell.execute_reply": "2025-03-25T07:22:47.119194Z" } }, "outputs": [], "source": [ "# Analyzing the gene identifiers from the extracted data\n", "# These identifiers (ILMN_*) are Illumina BeadArray probe IDs, not standard gene symbols\n", "# They need to be mapped to human gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "a2da5c08", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "d218a7e0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:22:47.120983Z", "iopub.status.busy": "2025-03-25T07:22:47.120879Z", "iopub.status.idle": "2025-03-25T07:22:50.822938Z", "shell.execute_reply": "2025-03-25T07:22:50.822283Z" } }, "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": "b6b68cd4", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "582eae56", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:22:50.824834Z", "iopub.status.busy": "2025-03-25T07:22:50.824703Z", "iopub.status.idle": "2025-03-25T07:22:51.476838Z", "shell.execute_reply": "2025-03-25T07:22:51.476178Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping from probes to gene symbols...\n", "Created mapping with 44837 rows\n", "First few rows of mapping data:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Gene': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']}\n", "\n", "Converting probe-level measurements to gene expression data...\n", "Converted to gene expression data with 17999 genes\n", "First few gene symbols:\n", "['A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE95425.csv\n" ] } ], "source": [ "# 1. Identify the columns for mapping identifiers to gene symbols\n", "# From the gene annotation data, we can see:\n", "# - 'ID' column contains the ILMN_* identifiers (same as in gene expression data)\n", "# - 'Symbol' column contains gene symbols\n", "\n", "# 2. Create the gene mapping dataframe\n", "print(\"Creating gene mapping from probes to gene symbols...\")\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "print(f\"Created mapping with {len(mapping_df)} rows\")\n", "print(\"First few rows of mapping data:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply the gene mapping to convert probe-level expression to gene-level expression\n", "print(\"\\nConverting probe-level measurements to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Converted to gene expression data with {len(gene_data.index)} genes\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Save gene expression data to file\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" ] }, { "cell_type": "markdown", "id": "c9ef7a51", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "aa59a5ef", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:22:51.478844Z", "iopub.status.busy": "2025-03-25T07:22:51.478688Z", "iopub.status.idle": "2025-03-25T07:22:59.818365Z", "shell.execute_reply": "2025-03-25T07:22:59.817663Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "After normalization: 17405 unique gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE95425.csv\n", "\n", "Loading and preparing clinical data...\n", "Loaded clinical data with shape: (1, 53)\n", "Transposed clinical data to shape: (53, 1)\n", "Clinical data structure:\n", " Sampling_Depth\n", "GSM2510512 0.0\n", "GSM2510513 NaN\n", "GSM2510514 1.0\n", "GSM2510515 1.0\n", "GSM2510516 0.0\n", "\n", "Linking clinical and genetic data...\n", "Gene data has 53 samples\n", "Clinical data has 53 samples\n", "Common samples between datasets: 53\n", "Linked data shape: (53, 17406)\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (47, 17406)\n", "\n", "Checking for bias in features...\n", "For the feature 'Sampling_Depth', the least common label is '0.0' with 23 occurrences. This represents 48.94% of the dataset.\n", "The distribution of the feature 'Sampling_Depth' 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_Papillary_Cell_Carcinoma/GSE95425.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. Load and prepare the clinical data\n", "print(\"\\nLoading and preparing clinical data...\")\n", "try:\n", " # Load the clinical data from file\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " \n", " # The trait name used when extracting clinical features in Step 2 was \"Sampling_Depth\"\n", " trait_column_name = \"Sampling_Depth\"\n", " \n", " # Check if the data is in the expected format\n", " if clinical_df.shape[0] == 1:\n", " # Data is in format with one row and samples as columns\n", " # Transpose to have samples as rows\n", " clinical_df = clinical_df.T\n", " clinical_df.columns = [trait_column_name]\n", " print(f\"Transposed clinical data to shape: {clinical_df.shape}\")\n", " \n", " print(\"Clinical data structure:\")\n", " print(clinical_df.head())\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", "# 3. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if is_trait_available and not normalized_gene_data.empty:\n", " # Get sample IDs from both datasets\n", " gene_samples = normalized_gene_data.columns.tolist()\n", " clinical_samples = clinical_df.index.tolist()\n", " \n", " print(f\"Gene data has {len(gene_samples)} samples\")\n", " print(f\"Clinical data has {len(clinical_samples)} samples\")\n", " \n", " # Find common samples\n", " common_samples = set(gene_samples).intersection(set(clinical_samples))\n", " print(f\"Common samples between datasets: {len(common_samples)}\")\n", " \n", " if len(common_samples) > 0:\n", " # Prepare genetic data for merging (samples as rows)\n", " gene_data_T = normalized_gene_data.T\n", " \n", " # Merge clinical and genetic data using common samples\n", " linked_data = clinical_df.join(gene_data_T, how='inner')\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Ensure the trait column exists\n", " if trait_column_name in linked_data.columns:\n", " # 4. Handle missing values\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait_column_name)\n", " print(f\"After handling missing values, data shape: {linked_data.shape}\")\n", " \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_column_name)\n", " else:\n", " print(f\"Error: Trait column '{trait_column_name}' not found in linked data.\")\n", " is_biased = True\n", " else:\n", " print(\"Error: No common samples between clinical and gene data.\")\n", " linked_data = pd.DataFrame()\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", "except Exception as e:\n", " print(f\"Error in linking data: {e}\")\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", " note = \"Failed to link clinical and genetic data. No common samples or error in processing.\"\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 }