{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a9fe5fa7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:01.529294Z", "iopub.status.busy": "2025-03-25T07:19:01.529109Z", "iopub.status.idle": "2025-03-25T07:19:01.693076Z", "shell.execute_reply": "2025-03-25T07:19:01.692736Z" } }, "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 = \"GSE19949\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma/GSE19949\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/GSE19949.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE19949.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE19949.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "cd4ecfab", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "5da3121f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:01.694416Z", "iopub.status.busy": "2025-03-25T07:19:01.694288Z", "iopub.status.idle": "2025-03-25T07:19:01.951512Z", "shell.execute_reply": "2025-03-25T07:19:01.951180Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Integrative genome-wide expression profiling identifies three distinct molecular subgroups of renal cell carcinoma with different patient outcome\"\n", "!Series_summary\t\"Background: Renal cell carcinoma (RCC) is characterized by a number of diverse molecular aberrations that differ among individuals. Recent approaches to molecularly classify RCC were based on clinical, pathological as well as on single molecular parameters. As a consequence, gene expression patterns reflecting the sum of genetic aberrations in individual tumors may not have been recognized. In an attempt to uncover such molecular features in RCC, we used a novel, unbiased and integrative approach.\"\n", "!Series_summary\t\"Methods: We integrated gene expression data from 97 primary RCCs of different pathologic parameters, 15 RCC metastases as well as 34 cancer cell lines for two-way nonsupervised hierarchical clustering using gene groups suggested by the PANTHER Classification System. We depicted the genomic landscape of the resulted tumor groups by means of Single Nuclear Polymorphism (SNP) technology. Finally, the achieved results were immunohistochemically analyzed using a tissue microarray (TMA) composed of 254 RCC. Results: We found robust, genome wide expression signatures, which split RCC into three distinct molecular subgroups. These groups remained stable even if randomly selected gene sets were clustered. Notably, the pattern obtained from RCC cell lines was clearly distinguishable from that of primary tumors. SNP array analysis demonstrated differing frequencies of chromosomal copy number alterations among RCC subgroups. TMA analysis with group-specific markers showed a prognostic significance of the different groups. Conclusion: We propose the existence of characteristic and histologically independent genome-wide expression outputs in RCC with potential biological and clinical relevance.\"\n", "!Series_overall_design\t\"Expression profiling by array, combined data analysis with genomic profiling data. Genomic DNA from renal cell was hybridized to renal cell carcinoma samples and matched normal kidney tissue biopsies, using the Affymetrix GenomewideSNP_6 platform. CEL files were processed using R, Bioconductor and software from the aroma.affymetrix project. Visualized Copy number profiles are accessible through the Progenetix site (www.progenetix.net). CN,raw.csv and segments.csv: Probes are mapped by their position in genome build 36 / HG18. Probes are ordered according to their linear position on the Golden Path.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['grade: 2', 'grade: 1', 'grade: 3', 'grade: NA', 'cell line: UMRC2', 'cell line: SLR24', 'cell line: A-498', 'cell line: SK-RC52', 'cell line: 786O (vhl19)', 'cell line: UMRC6', 'cell line: ACHN', 'cell line: 786O (vhl30)', 'cell line: A-704', 'cell line: SLR 26', 'cell line: Caki-1', 'cell line: RCC4 (vhl)', 'cell line: 769-P', 'cell line: KC12', 'cell line: RCC4 (neo)', 'cell line: SK-RC29', 'cell line: SW156', 'cell line: SK-RC31', 'cell line: SLR22', 'cell line: SK-RC38', 'cell line: 786-O', 'cell line: SK-RC42', 'cell line: 786O', 'cell line: SLR25', 'cell line: SLR20', 'cell line: Caki-2'], 1: ['stage: 2', 'stage: 1', 'stage: 3', 'stage: NA', 'grade: NA'], 2: ['sample type: neoplasia', 'stage: NA'], 3: ['icd-o 3 code: 8310/3', 'icd-o 3 code: 8317/3', 'icd-o 3 code: 8312/3', 'icd-o 3 code: 8260/3', 'sample type: neoplasia'], 4: ['icd-o 3 diagnosis text: clear cell renal cell carcinoma', 'icd-o 3 diagnosis text: renal cell carcinoma, chromophobe', 'icd-o 3 diagnosis text: renal cell carcinoma', 'icd-o 3 diagnosis text: papillary renal cell carcinoma', 'icd-o 3 code: 8312/3', 'icd-o 3 code: 8140/3'], 5: ['organ site: kidney', 'organ site: kidney [metastasis of RCC to other site]', 'icd-o 3 diagnosis text: renal cell carcinoma', 'icd-o 3 diagnosis text: adenocarcinoma, NOS'], 6: ['gender: male', 'gender: NA', 'gender: female', 'organ site: kidney [cell line]', 'organ site: prostate [cell line]'], 7: ['tissue type: renal cell carcinoma [clear cell RCC]', 'tissue type: renal cell carcinoma [chromophobe RCC]', 'tissue type: renal cell carcinoma [mixed papillary and clear cell RCC]', 'tissue type: renal cell carcinoma [RCC metastasis]', 'tissue type: renal cell carcinoma [papillary RCC]', 'gender: NA', 'gender: male'], 8: ['cluster id: B', 'cluster id: A', 'cluster id: C', 'tissue type: renal cell carcinoma [cell line UMRC2]', 'tissue type: renal cell carcinoma [cell line SLR24]', 'tissue type: renal cell carcinoma [cell line A-498]', 'tissue type: renal cell carcinoma [cell line SK-RC52]', 'tissue type: renal cell carcinoma [cell line 786O (vhl19)]', 'tissue type: renal cell carcinoma [cell line UMRC6]', 'tissue type: renal cell carcinoma [cell line ACHN]', 'tissue type: renal cell carcinoma [cell line 786O (vhl30)]', 'tissue type: renal cell carcinoma [cell line A-704]', 'tissue type: renal cell carcinoma [cell line SLR 26]', 'tissue type: renal cell carcinoma [cell line Caki-1]', 'tissue type: renal cell carcinoma [cell line RCC4 (vhl)]', 'tissue type: renal cell carcinoma [cell line 769-P]', 'tissue type: renal cell carcinoma [cell line KC12]', 'tissue type: renal cell carcinoma [cell line RCC4 (neo)]', 'tissue type: renal cell carcinoma [cell line SK-RC29]', 'tissue type: renal cell carcinoma [cell line SW156]', 'tissue type: renal cell carcinoma [cell line SK-RC31]', 'tissue type: renal cell carcinoma [cell line SLR22]', 'tissue type: renal cell carcinoma [cell line SK-RC38]', 'tissue type: renal cell carcinoma [cell line 786-O]', 'tissue type: renal cell carcinoma [cell line SK-RC42]', 'tissue type: renal cell carcinoma [cell line 786O]', 'tissue type: renal cell carcinoma [cell line SLR25]', 'tissue type: renal cell carcinoma [cell line SLR20]', 'tissue type: renal cell carcinoma [cell line Caki-2]', 'tissue type: renal cell carcinoma [cell line SLR21]'], 9: [nan, 'cluster id: NA']}\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": "c3699719", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "c10f4106", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:01.952877Z", "iopub.status.busy": "2025-03-25T07:19:01.952776Z", "iopub.status.idle": "2025-03-25T07:19:01.958286Z", "shell.execute_reply": "2025-03-25T07:19:01.958007Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data file not found at ../../input/GEO/Kidney_Papillary_Cell_Carcinoma/GSE19949/sample_characteristic.csv\n", "Unable to extract clinical features\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Dict, Any, Optional\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains genome-wide expression profiling data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Looking at the sample characteristics dictionary:\n", "\n", "# For trait (Kidney Papillary Cell Carcinoma):\n", "# Key 4 contains 'icd-o 3 diagnosis text: papillary renal cell carcinoma'\n", "trait_row = 4\n", "\n", "# For age:\n", "# There's no information about age in the sample characteristics\n", "age_row = None\n", "\n", "# For gender:\n", "# Key 6 contains gender information\n", "gender_row = 6\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0: non-PRCC, 1: PRCC)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if it's papillary renal cell carcinoma\n", " if 'papillary renal cell carcinoma' in value.lower():\n", " return 1\n", " elif 'clear cell' in value.lower() or 'chromophobe' in value.lower() or 'renal cell carcinoma' in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"This function is included for completeness but won't be used since age data is not available\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0: female, 1: male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert gender\n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " else:\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", "\n", "# Conduct initial filtering and save metadata\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", "# Check if trait_row is not None before extracting clinical features\n", "if trait_row is not None:\n", " # First check for sample_characteristic.csv which is the typical format\n", " sample_char_path = os.path.join(in_cohort_dir, \"sample_characteristic.csv\")\n", " \n", " # Check if the file exists before trying to load it\n", " if os.path.exists(sample_char_path):\n", " clinical_data = pd.read_csv(sample_char_path, header=None)\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(\"Preview of selected clinical features:\")\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 selected clinical features\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " else:\n", " print(f\"Clinical data file not found at {sample_char_path}\")\n", " print(\"Unable to extract clinical features\")\n" ] }, { "cell_type": "markdown", "id": "a33e29ba", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "91cd090f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:01.959635Z", "iopub.status.busy": "2025-03-25T07:19:01.959532Z", "iopub.status.idle": "2025-03-25T07:19:02.456491Z", "shell.execute_reply": "2025-03-25T07:19:02.455797Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Integrative genome-wide expression profiling identifies three distinct molecular subgroups of renal cell carcinoma with different patient outcome\"\n", "Line 1: !Series_geo_accession\t\"GSE19949\"\n", "Line 2: !Series_status\t\"Public on Jul 24 2012\"\n", "Line 3: !Series_submission_date\t\"Jan 19 2010\"\n", "Line 4: !Series_last_update_date\t\"Nov 27 2018\"\n", "Line 5: !Series_pubmed_id\t\"22824167\"\n", "Line 6: !Series_summary\t\"Background: Renal cell carcinoma (RCC) is characterized by a number of diverse molecular aberrations that differ among individuals. Recent approaches to molecularly classify RCC were based on clinical, pathological as well as on single molecular parameters. As a consequence, gene expression patterns reflecting the sum of genetic aberrations in individual tumors may not have been recognized. In an attempt to uncover such molecular features in RCC, we used a novel, unbiased and integrative approach.\"\n", "Line 7: !Series_summary\t\"Methods: We integrated gene expression data from 97 primary RCCs of different pathologic parameters, 15 RCC metastases as well as 34 cancer cell lines for two-way nonsupervised hierarchical clustering using gene groups suggested by the PANTHER Classification System. We depicted the genomic landscape of the resulted tumor groups by means of Single Nuclear Polymorphism (SNP) technology. Finally, the achieved results were immunohistochemically analyzed using a tissue microarray (TMA) composed of 254 RCC. Results: We found robust, genome wide expression signatures, which split RCC into three distinct molecular subgroups. These groups remained stable even if randomly selected gene sets were clustered. Notably, the pattern obtained from RCC cell lines was clearly distinguishable from that of primary tumors. SNP array analysis demonstrated differing frequencies of chromosomal copy number alterations among RCC subgroups. TMA analysis with group-specific markers showed a prognostic significance of the different groups. Conclusion: We propose the existence of characteristic and histologically independent genome-wide expression outputs in RCC with potential biological and clinical relevance.\"\n", "Line 8: !Series_overall_design\t\"Expression profiling by array, combined data analysis with genomic profiling data. Genomic DNA from renal cell was hybridized to renal cell carcinoma samples and matched normal kidney tissue biopsies, using the Affymetrix GenomewideSNP_6 platform. CEL files were processed using R, Bioconductor and software from the aroma.affymetrix project. Visualized Copy number profiles are accessible through the Progenetix site (www.progenetix.net). CN,raw.csv and segments.csv: Probes are mapped by their position in genome build 36 / HG18. Probes are ordered according to their linear position on the Golden Path.\"\n", "Line 9: !Series_type\t\"Expression profiling by array\"\n", "Found table marker at line 73\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM498450\"\t\"GSM498451\"\t\"GSM498452\"\t\"GSM498453\"\t\"GSM498454\"\t\"GSM498455\"\t\"GSM498456\"\t\"GSM498457\"\t\"GSM498458\"\t\"GSM498459\"\t\"GSM498460\"\t\"GSM498461\"\t\"GSM498462\"\t\"GSM498463\"\t\"GSM498464\"\t\"GSM498465\"\t\"GSM498466\"\t\"GSM498467\"\t\"GSM498468\"\t\"GSM498469\"\t\"GSM498470\"\t\"GSM498471\"\t\"GSM498472\"\t\"GSM498473\"\t\"GSM498474\"\t\"GSM498475\"\t\"GSM498476\"\t\"GSM498477\"\t\"GSM498478\"\t\"GSM498479\"\t\"GSM498480\"\t\"GSM498481\"\t\"GSM498482\"\t\"GSM498483\"\t\"GSM498484\"\t\"GSM498485\"\t\"GSM498486\"\t\"GSM498487\"\t\"GSM498488\"\t\"GSM498489\"\t\"GSM498490\"\t\"GSM498491\"\t\"GSM498492\"\t\"GSM498493\"\t\"GSM498494\"\t\"GSM498495\"\t\"GSM498496\"\t\"GSM498497\"\t\"GSM498498\"\t\"GSM498499\"\t\"GSM498500\"\t\"GSM498501\"\t\"GSM498502\"\t\"GSM498503\"\t\"GSM498504\"\t\"GSM498505\"\t\"GSM498506\"\t\"GSM498507\"\t\"GSM498508\"\t\"GSM498509\"\t\"GSM498510\"\t\"GSM498511\"\t\"GSM498512\"\t\"GSM498513\"\t\"GSM498514\"\t\"GSM498515\"\t\"GSM498516\"\t\"GSM498517\"\t\"GSM498518\"\t\"GSM498519\"\t\"GSM498520\"\t\"GSM498521\"\t\"GSM498522\"\t\"GSM498523\"\t\"GSM498524\"\t\"GSM498525\"\t\"GSM498526\"\t\"GSM498527\"\t\"GSM498528\"\t\"GSM498529\"\t\"GSM498530\"\t\"GSM498531\"\t\"GSM498532\"\t\"GSM498533\"\t\"GSM498534\"\t\"GSM498535\"\t\"GSM498536\"\t\"GSM498537\"\t\"GSM498538\"\t\"GSM498539\"\t\"GSM498540\"\t\"GSM498541\"\t\"GSM498542\"\t\"GSM498543\"\t\"GSM498544\"\t\"GSM498545\"\t\"GSM498546\"\t\"GSM498547\"\t\"GSM498548\"\t\"GSM498549\"\t\"GSM498550\"\t\"GSM498551\"\t\"GSM498552\"\t\"GSM498553\"\t\"GSM498554\"\t\"GSM498555\"\t\"GSM498556\"\t\"GSM498557\"\t\"GSM498558\"\t\"GSM498559\"\t\"GSM498560\"\t\"GSM498561\"\t\"GSM498562\"\t\"GSM498563\"\t\"GSM498564\"\t\"GSM498565\"\t\"GSM498566\"\t\"GSM498567\"\t\"GSM498568\"\t\"GSM498569\"\t\"GSM498570\"\t\"GSM498571\"\t\"GSM498572\"\t\"GSM498573\"\t\"GSM498574\"\t\"GSM498575\"\t\"GSM498576\"\t\"GSM498577\"\t\"GSM498578\"\t\"GSM498579\"\t\"GSM498580\"\t\"GSM498581\"\t\"GSM498582\"\t\"GSM498583\"\t\"GSM498584\"\t\"GSM498585\"\t\"GSM498586\"\t\"GSM498587\"\t\"GSM498588\"\t\"GSM498589\"\t\"GSM498590\"\t\"GSM498591\"\t\"GSM498592\"\t\"GSM498593\"\t\"GSM498594\"\t\"GSM498595\"\t\"GSM498596\"\n", "\"1007_s_at\"\t9363.60418462085\t4194.95902613104\t2727.50640488363\t1717.63426178281\t2428.52906530827\t2694.45963569399\t2961.13005158717\t2815.91249830135\t723.590420760864\t3572.21857479917\t1037.61405499613\t2430.72303780078\t6776.9571506939\t4306.85307382639\t2117.6950172912\t4172.96561159324\t871.024582442378\t207.992757265729\t2637.40127689759\t3653.00229202608\t4413.14374119404\t6036.7982763515\t3728.12745771456\t3299.92169532781\t1439.75402823783\t3095.88768581220\t1344.79671169968\t4010.37073498000\t1811.50244253362\t3210.93336238669\t2487.20059532482\t7943.77933033858\t3371.52941060966\t2337.22329760890\t2406.65420188752\t2001.21142367282\t1439.05927100700\t2595.52528953098\t4195.46805645774\t4171.19850421993\t4239.27976042416\t4225.59551974716\t4290.17637903692\t3525.05779983578\t4678.718136546\t3143.82838486676\t2863.94819743941\t4111.85278179918\t2224.21050930464\t5042.79900334531\t3216.72504008449\t2848.71008239607\t1220.58648522282\t1961.43209600136\t7803.0275511373\t6759.49586759964\t3084.30271773166\t3918.49832527274\t3244.94222669034\t3818.97625780761\t2038.1103177893\t3986.59007608589\t2160.01780271755\t2912.29697769287\t3682.77282561534\t2639.48451786437\t1601.77970845856\t24272.974237642\t3042.28113093913\t3805.15521972730\t4923.3116066726\t5105.39935414652\t2412.75487885138\t2446.36044748224\t3395.86214642277\t2541.32717361075\t1971.31138031816\t3648.12708944067\t5130.64765648781\t1150.26396387229\t8654.35351788325\t7912.03994119476\t7329.14441089045\t9948.6841693768\t10528.0062415085\t6271.28785628752\t6960.49560055742\t6766.02941210763\t3403.24044710012\t1403.28625574612\t3152.46416857899\t6142.49412961611\t5559.39646465675\t9044.50016019673\t5338.9452756898\t10255.1834116567\t4897.31481738224\t3804.1986373202\t2616.18683712413\t2733.00665065223\t961.64429552583\t3769.09495732271\t2614.82330498827\t1541.14563468206\t2740.71790994689\t704.775244796116\t2565.57100636763\t4733.14075087958\t1296.20838553161\t1530.93871675093\t887.264553291437\t3052.22927214844\t2104.33853563520\t109.048758093145\t1623.10877782210\t1149.75273094572\t791.034775602832\t562.978123318453\t366.345043016839\t1538.24703605692\t591.771616178851\t3357.49775872671\t1458.95077545364\t759.02817465599\t888.158271168394\t286.717884080033\t431.051842729251\t1239.7824803925\t498.280595254611\t940.816030924208\t731.133944963385\t505.62316011371\t550.167227044481\t703.241286525199\t304.664050990756\t584.017364631684\t913.169459619407\t400.457177916941\t2459.25927593572\t1112.49619387503\t740.329503424653\t493.162527557167\t6595.68790301168\t2720.07219650997\t1285.53952176573\t1704.40253536217\t1246.81463005400\n", "\"1053_at\"\t116.079092788960\t95.4548470581752\t445.073889177146\t422.012792967524\t683.385336191611\t135.355620152327\t131.59146017613\t98.1078070870905\t608.178665075712\t186.862473229037\t243.823848084776\t504.626097977540\t257.587770441046\t593.330424373735\t319.924310798166\t453.945939961721\t482.93400183853\t597.529637865612\t100.120961639392\t169.649349359282\t49.143105314699\t37.8155578103092\t268.602018517608\t229.075284597973\t390.308580619877\t324.392996015853\t265.130631208927\t371.488559888125\t433.562128769261\t281.397308503142\t476.336578178499\t289.623038482813\t430.518718934527\t282.558867401599\t692.14959035885\t599.751932307674\t502.6115230518\t263.882625702122\t286.140221018044\t463.900958422545\t473.462804011865\t371.753570069939\t487.908620084502\t470.872855388711\t210.722953582941\t390.047330253882\t416.132888084352\t400.608419880542\t651.792333582287\t198.818770202056\t334.566411901807\t401.800161246783\t415.417914551215\t336.696418207205\t377.286757721523\t395.672339075122\t456.634464013812\t427.513948538011\t466.112042064185\t504.62128961187\t228.085839875995\t709.42520911925\t33.5037887227131\t321.727538435366\t477.599438412987\t364.024205760053\t394.745810682868\t155.258421753964\t289.588943245141\t370.439999047582\t208.595886414974\t425.400842498188\t241.620719326612\t305.424230644078\t405.206825998287\t356.532711977673\t479.85816124289\t62.5013263173845\t416.122055806775\t167.832661710095\t140.385150148794\t336.445353792252\t274.034769177303\t37.7152513470146\t51.2240396997142\t224.823786724002\t290.713123598456\t167.872612531186\t55.8619149972023\t672.057230270961\t91.0580649839029\t10.5015548752648\t434.346887739277\t472.738121325114\t540.17757635711\t639.804852712083\t364.881400750944\t505.846784978734\t439.558151102614\t435.621523844053\t260.073278163285\t406.150162745939\t437.467482763501\t340.321103749067\t303.894861371707\t232.978431620112\t280.806174022342\t178.847175860102\t577.167140745395\t286.298084941519\t404.548628016692\t412.745674419030\t344.007435303653\t1365.72974286773\t1176.43929287237\t1493.87068568267\t1339.80561483128\t1461.49002077772\t509.453946379488\t2073.48096089889\t1288.17616090840\t1179.54901099109\t1669.72737073793\t523.16362419908\t1195.16876862356\t1391.82460181212\t791.472759075961\t1142.25281522951\t1823.31001481762\t1231.01158212096\t1310.43109008506\t1385.85664763296\t795.61134696038\t1002.91340589385\t1217.49733759524\t1127.38029649968\t1674.66159168933\t628.120912489755\t1156.16895501797\t811.745573790697\t810.510677349831\t1114.15247304423\t594.27442558398\t631.374937429245\t480.162815504004\t169.581254771985\t597.710869787195\n", "\"117_at\"\t453.893506717795\t777.977446024971\t524.233998379886\t83.1421505128734\t218.145032071757\t179.058985771441\t300.053180354629\t711.456472763725\t209.813461363131\t513.806319458299\t397.748867167290\t173.843953284777\t366.754978911273\t93.5896038705524\t91.4572527247835\t143.000403034363\t160.828747762546\t442.937124362758\t94.6064813004538\t195.597800794205\t1088.04886803495\t194.380980942403\t713.412391758222\t693.466652717624\t84.9275799626988\t30.3674518182135\t512.093134567365\t91.9327141019804\t459.504861163363\t184.282480925607\t195.434354539686\t64.4002940181734\t87.7185987929099\t470.832383150621\t150.680437895508\t155.478738368526\t362.652961014929\t167.280611394361\t43.1846642603704\t300.140793357201\t92.17242352893\t230.085459394624\t136.015338449995\t532.706750132042\t218.274930059606\t464.478805537352\t148.286927546399\t353.081560879088\t44.9530921442649\t834.93509685818\t215.12364205495\t26.8821412713861\t675.17231717856\t244.377839763034\t627.132886367147\t602.145144425511\t949.528404261672\t1131.98955960539\t228.51474299424\t361.919734742984\t301.021378165501\t232.930196731915\t1184.06085648208\t206.70033906408\t75.269591291817\t124.520720795872\t30.5401589215451\t51.4101204719045\t416.229331271585\t73.3167634232421\t419.775799218027\t433.207938643734\t116.815897799167\t84.9479123297227\t169.137003023306\t172.180570875203\t169.119698780722\t594.954206782195\t111.994180685274\t686.031319244511\t814.740419780245\t609.39906686908\t144.342507214789\t63.0578713110121\t130.890632536540\t182.785879571717\t803.021672975915\t277.770912545876\t91.8892549647865\t48.9283098748903\t20.6626950763899\t110.86066779176\t194.287354581001\t443.599003601567\t80.207291975603\t115.673144678820\t367.280513882817\t11.6392334714327\t574.764703202853\t215.842395737349\t480.07289983222\t447.09143485752\t257.740559008932\t341.605994697226\t341.973083582764\t440.286860511808\t159.027222698665\t572.178879456544\t176.169728998124\t418.86611028639\t75.96600623478\t178.829165403190\t179.775600855603\t10.8683069931642\t28.3969112533399\t17.7158060542698\t32.2875297188586\t7.11623086527391\t13.3708264394851\t95.2028371362148\t38.0306109310472\t89.7712031346607\t19.2601442339819\t14.1788414396446\t57.7173393955876\t3.01220420528177\t70.9069848697735\t96.0689176506332\t8.81031207177996\t10.6114767585574\t53.2620916798946\t22.1929627469616\t14.7177743628567\t18.5170750062095\t10.8848995641928\t18.4681682372258\t11.1331146520681\t52.3644149984155\t15.50915549425\t6.74590919452236\t20.6766719760546\t8.54724632683232\t732.702756046629\t127.764141309525\t230.294214608272\t186.988889617035\t9.68091483918967\n", "\"121_at\"\t12182.4326018138\t11552.3574245133\t2285.46248785832\t1696.28298582277\t2769.57351732795\t21542.9439374064\t8938.55355363638\t5058.86599473038\t3164.89888861279\t3748.05481707333\t1130.75929079836\t2519.31817789792\t5601.71176966948\t2462.87913161604\t1392.21305716111\t4298.76402832006\t1323.72414585787\t6346.87668729036\t7607.6611301172\t9876.33824941226\t4567.29296289390\t6354.32154423263\t4893.9033660619\t4190.75300868449\t930.831877050133\t2868.5835385539\t681.728199509062\t3368.72447767157\t1327.86494635161\t2612.22257355102\t1650.67402213800\t3284.57048220717\t2532.7774269228\t1226.60984577699\t1049.32143758359\t1787.48287936602\t2023.50422970497\t2857.4841854348\t3276.80467917238\t6888.63542302939\t2076.98893673248\t2986.07656180944\t2162.910516754\t4689.55468347573\t5904.80694919734\t2807.74416459221\t1402.97210522764\t6389.30625283014\t4727.52354338899\t5174.27122020524\t2876.22350716083\t2368.80373452677\t1206.44633981603\t4281.0129601262\t12832.1340938912\t3901.47067481615\t2155.45572681168\t1669.14133116203\t2084.47531232099\t8223.2787332495\t3046.48396898964\t2430.41733828013\t3175.08533727414\t1884.24384077799\t2429.38880179479\t2850.56289698225\t2431.54197109571\t8360.42812673882\t3654.75512033656\t1796.96467355448\t7526.21112972015\t3005.97843939871\t1544.08864005717\t1398.70505422727\t2116.07446222052\t1730.35550544080\t1671.17572558105\t4602.17224032484\t4586.62738186235\t3443.75517887960\t23099.443118084\t12508.6672566191\t10000.7457115575\t43034.9072383435\t34747.2158624908\t14824.2659693192\t10103.1987746392\t10578.7047022798\t25036.3091497843\t3413.27765569064\t7365.8871723162\t45616.9302029789\t9759.33993176138\t8839.61500955813\t4439.12984690436\t7369.4062733587\t5049.14327452163\t9362.6073503622\t3686.63847127545\t2266.80411962723\t789.333693451408\t10307.4471010401\t6831.43162153925\t2040.95134925982\t5847.50241121621\t6092.47921479295\t8997.25506529221\t6816.43843146537\t4466.58630333266\t6086.93373643797\t5830.20692112069\t3314.69735664972\t1453.96777214901\t3867.74511515965\t3775.2114442578\t4027.44383020147\t237.250203416008\t3588.22101470318\t4122.81412368803\t3807.1148773266\t3969.27079237568\t2250.39049028610\t7588.59710355815\t2562.79643081089\t3359.42334453593\t4112.8600295477\t1487.81006616202\t2872.81238782705\t3292.24589377289\t8194.57725200752\t3183.51649120599\t4886.99592968833\t4451.600260118\t8278.40880340203\t4240.27761967563\t3472.52945899022\t2137.61798276618\t3142.69581986334\t5367.37388334374\t5406.82224114095\t4898.99816276462\t2289.67139533070\t509.63048585622\t365.152729578784\t377.367214084959\t232.187760003287\t6737.88047997728\n", "Total lines examined: 74\n", "\n", "Attempting to extract gene data from matrix file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene data with 22277 rows\n", "First 20 gene IDs:\n", "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n", " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n", " '1494_f_at', '1598_g_at', '160020_at', '1729_at', '1773_at', '177_at',\n", " '179_at', '1861_at'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 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": "2a9fbbdb", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "af5db2eb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:02.457975Z", "iopub.status.busy": "2025-03-25T07:19:02.457849Z", "iopub.status.idle": "2025-03-25T07:19:02.460321Z", "shell.execute_reply": "2025-03-25T07:19:02.459881Z" } }, "outputs": [], "source": [ "# Analyze gene identifiers based on their format\n", "# Looking at the first few identifiers: '1007_s_at', '1053_at', '117_at', '121_at', etc.\n", "# These appear to be Affymetrix probe IDs, not standard human gene symbols\n", "# Affymetrix IDs typically have formats like NNN_at, NNN_s_at, etc.\n", "# These will require mapping to standard gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "51ea19c4", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "7f1112fe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:02.461532Z", "iopub.status.busy": "2025-03-25T07:19:02.461422Z", "iopub.status.idle": "2025-03-25T07:19:12.817175Z", "shell.execute_reply": "2025-03-25T07:19:12.816493Z" } }, "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 5177938 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': [nan, nan, nan, nan, nan], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor family, member 1', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box gene 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001954 /// NM_013993 /// NM_013994', 'NM_002914 /// NM_181471', 'NM_002155 /// XM_001134322', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409'], 'Gene Ontology Biological Process': ['0006468 // protein amino acid phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation', '0006260 // DNA replication // inferred from electronic annotation', '0006457 // protein folding // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0006986 // response to unfolded protein // inferred from electronic annotation', '0001656 // metanephros development // inferred from electronic annotation /// 0006183 // GTP biosynthesis // inferred from electronic annotation /// 0006228 // UTP biosynthesis // inferred from electronic annotation /// 0006241 // CTP biosynthesis // inferred from electronic annotation /// 0006350 // transcription // inferred from electronic annotation /// 0009887 // organ morphogenesis // inferred from electronic annotation /// 0030154 // cell differentiation // inferred from electronic annotation /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from sequence or structural similarity /// 0006355 // regulation of transcription, DNA-dependent // inferred from electronic annotation /// 0007275 // development // inferred from electronic annotation /// 0009653 // morphogenesis // traceable author statement', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // traceable author statement /// 0050896 // response to stimulus // inferred from electronic annotation /// 0007601 // visual perception // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005615 // extracellular space // inferred from electronic annotation /// 0005887 // integral to plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation', '0005634 // nucleus // inferred from electronic annotation /// 0005663 // DNA replication factor C complex // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from electronic annotation', nan, '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005667 // transcription factor complex // inferred from electronic annotation', nan], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004674 // protein serine/threonine kinase activity // inferred from electronic annotation /// 0004713 // protein-tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0004872 // receptor activity // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // traceable author statement /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0003700 // transcription factor activity // traceable author statement /// 0004550 // nucleoside diphosphate kinase activity // inferred from electronic annotation /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from sequence or structural similarity /// 0005524 // ATP binding // inferred from electronic annotation /// 0016563 // transcriptional activator activity // inferred from sequence or structural similarity /// 0003677 // DNA binding // inferred from electronic annotation', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // traceable author statement']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'GB_ACC', 'SPOT_ID', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Target Description', 'Representative Public ID', 'Gene Title', 'Gene Symbol', 'ENTREZ_GENE_ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 5177876 out of 5177938\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: nan\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "06ffde8e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "e160c543", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:12.818651Z", "iopub.status.busy": "2025-03-25T07:19:12.818515Z", "iopub.status.idle": "2025-03-25T07:19:14.762809Z", "shell.execute_reply": "2025-03-25T07:19:14.762146Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created gene mapping with 21248 rows\n", "First few rows of mapping data:\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'Gene': ['DDR1', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A']}\n", "Converted gene expression data from probes to genes, resulting in 13046 genes\n", "First 20 gene symbols:\n", "Index(['A2BP1', 'A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAK1',\n", " 'AAMP', 'AANAT', 'AARS', 'AARSD1', 'AASDHPPT', 'AASS', 'AATF', 'AATK',\n", " 'ABAT', 'ABC1', 'ABCA1', 'ABCA11'],\n", " dtype='object', name='Gene')\n", "After normalizing gene symbols: 12700 unique genes\n", "First 20 normalized gene symbols:\n", "Index(['A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAK1', 'AAMDC',\n", " 'AAMP', 'AANAT', 'AAR2', 'AARS1', 'AARSD1', 'AASDHPPT', 'AASS', 'AATF',\n", " 'AATK', 'ABAT', 'ABCA1', 'ABCA11P'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE19949.csv\n" ] } ], "source": [ "# 1. Identify the relevant columns for gene mapping\n", "# From the preview, we can see that:\n", "# - 'ID' in gene_annotation contains the probe IDs (like '1007_s_at')\n", "# - 'Gene Symbol' contains the human gene symbols (like 'DDR1')\n", "\n", "# 2. Get gene mapping dataframe\n", "mapping_data = get_gene_mapping(gene_annotation, 'ID', 'Gene Symbol')\n", "print(f\"Created gene mapping with {len(mapping_data)} rows\")\n", "print(\"First few rows of mapping data:\")\n", "print(preview_df(mapping_data))\n", "\n", "# 3. Convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "print(f\"Converted gene expression data from probes to genes, resulting in {len(gene_data)} genes\")\n", "print(\"First 20 gene symbols:\")\n", "print(gene_data.index[:20])\n", "\n", "# Optionally normalize gene symbols to handle synonyms\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalizing gene symbols: {len(gene_data)} unique genes\")\n", "print(\"First 20 normalized gene symbols:\")\n", "print(gene_data.index[:20])\n", "\n", "# Save the gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "47dfec30", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "57c63009", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:14.764410Z", "iopub.status.busy": "2025-03-25T07:19:14.764281Z", "iopub.status.idle": "2025-03-25T07:19:23.735738Z", "shell.execute_reply": "2025-03-25T07:19:23.734666Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "Loaded gene data with 12700 genes and 147 samples\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 12700 genes\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE19949.csv\n", "\n", "Extracting clinical data from source...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Clinical data saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE19949.csv\n", "Clinical data shape: (2, 147)\n", "Trait information available: True\n", "\n", "Linking clinical and genetic data...\n", "Created linked data with 147 samples and 12702 features\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values: 113 samples and 12702 features\n", "\n", "Evaluating feature bias...\n", "For the feature 'Kidney_Papillary_Cell_Carcinoma', the least common label is '1.0' with 20 occurrences. This represents 17.70% of the dataset.\n", "The distribution of the feature 'Kidney_Papillary_Cell_Carcinoma' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 11 occurrences. This represents 9.73% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "Trait bias determination: False\n", "Final linked data shape: 113 samples and 12702 features\n", "\n", "Performing final validation...\n", "A new JSON file was created at: ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/cohort_info.json\n", "\n", "Dataset usability for Kidney_Papillary_Cell_Carcinoma association studies: True\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Final linked data saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/GSE19949.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "try:\n", " # Load gene data that was saved in step 6\n", " gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", " print(f\"Loaded gene data with {gene_data.shape[0]} genes and {gene_data.shape[1]} samples\")\n", " \n", " # Normalize gene symbols using NCBI Gene database - this was already done in Step 6\n", " # but we'll ensure it's properly normalized here\n", " gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {gene_data.shape[0]} genes\")\n", " \n", " # Save the normalized gene 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\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Extract clinical data directly from the matrix file since it wasn't processed in Step 2\n", "print(\"\\nExtracting clinical data from source...\")\n", "try:\n", " # Get the file paths again to make sure we have them\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Extract background information and clinical data\n", " background_info, clinical_data = get_background_and_clinical_data(\n", " matrix_file, \n", " prefixes_a=['!Series_title', '!Series_summary', '!Series_overall_design'],\n", " prefixes_b=['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", " )\n", " \n", " # Process clinical data using trait information from Step 2\n", " trait_row = 4 # Based on analysis in step 2\n", " gender_row = 6 # Based on analysis in step 2\n", " age_row = None # Based on analysis in step 2\n", " \n", " def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0: non-PRCC, 1: PRCC)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if it's papillary renal cell carcinoma\n", " if 'papillary renal cell carcinoma' in value.lower():\n", " return 1\n", " elif 'clear cell' in value.lower() or 'chromophobe' in value.lower() or 'renal cell carcinoma' in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", " def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0: female, 1: male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert gender\n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " else:\n", " return None\n", " \n", " def convert_age(value):\n", " \"\"\"This function is included for completeness but won't be used since age data is not available\"\"\"\n", " return None\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", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n", " \n", " # Check if we have valid trait information\n", " is_trait_available = trait_row is not None and not selected_clinical_df.empty\n", " print(f\"Trait information available: {is_trait_available}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", " selected_clinical_df = pd.DataFrame()\n", "\n", "# 3. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if is_trait_available and not selected_clinical_df.empty:\n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n", " print(f\"Created linked data with {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n", " else:\n", " print(\"Cannot link data: clinical data is not available\")\n", " linked_data = pd.DataFrame()\n", " is_trait_available = False\n", "except Exception as e:\n", " print(f\"Error linking clinical and genetic data: {e}\")\n", " is_trait_available = False\n", " linked_data = pd.DataFrame()\n", "\n", "# 4. Handle missing values in the linked data\n", "if is_trait_available and not linked_data.empty:\n", " print(\"\\nHandling missing values...\")\n", " try:\n", " # Rename the first column to the trait name for consistency\n", " if linked_data.columns[0] != trait:\n", " linked_data = linked_data.rename(columns={linked_data.columns[0]: trait})\n", " \n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values: {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n", " except Exception as e:\n", " print(f\"Error handling missing values: {e}\")\n", " \n", " # 5. Determine whether the trait and demographic features are biased\n", " print(\"\\nEvaluating feature bias...\")\n", " try:\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Trait bias determination: {is_biased}\")\n", " print(f\"Final linked data shape: {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n", " except Exception as e:\n", " print(f\"Error evaluating feature bias: {e}\")\n", " is_biased = True\n", "else:\n", " print(\"\\nSkipping missing value handling and bias evaluation as linked data is not available\")\n", " is_biased = True\n", "\n", "# 6. Validate and save cohort information\n", "print(\"\\nPerforming final validation...\")\n", "note = \"\"\n", "if not is_trait_available:\n", " note = \"Dataset does not contain required trait information\"\n", "elif is_biased:\n", " note = \"Dataset has severe bias in the 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=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if usable\n", "print(f\"\\nDataset usability for {trait} association studies: {is_usable}\")\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Final linked data saved to {out_data_file}\")\n", "else:\n", " if note:\n", " print(f\"Reason: {note}\")\n", " else:\n", " print(\"Dataset does not meet quality criteria for the specified trait\")" ] } ], "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 }