{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "e204352f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:24.873936Z", "iopub.status.busy": "2025-03-25T07:19:24.873706Z", "iopub.status.idle": "2025-03-25T07:19:25.043214Z", "shell.execute_reply": "2025-03-25T07:19:25.042821Z" } }, "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 = \"GSE40911\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma/GSE40911\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/GSE40911.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE40911.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE40911.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "73fe3b8b", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "a3ab5fa6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:25.044725Z", "iopub.status.busy": "2025-03-25T07:19:25.044567Z", "iopub.status.idle": "2025-03-25T07:19:25.068263Z", "shell.execute_reply": "2025-03-25T07:19:25.067916Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Expression analysis and in silico characterization of intronic long noncoding RNAs in renal cell carcinoma: emerging functional associations (RCC malignancy)\"\n", "!Series_summary\t\"Intronic and intergenic long noncoding RNAs (lncRNAs) are emerging gene expression regulators. The molecular pathogenesis of renal cell carcinoma (RCC) is still poorly understood, and in particular, limited studies are available for intronic lncRNAs expressed in RCC. Microarray experiments were performed with two different custom-designed arrays enriched with probes for lncRNAs mapping to intronic genomic regions. Samples from 18 primary clear cell RCC tumors and 11 nontumor adjacent matched tissues were analyzed with 4k-probes microarrays. Oligoarrays with 44k-probes were used to interrogate 17 RCC samples (14 clear cell, 2 papillary, 1 chromophobe subtypes) split into four pools. Meta-analyses were performed by taking the genomic coordinates of the RCC-expressed lncRNAs, and cross-referencing them with microarray expression data from three additional human tissues (normal liver, prostate tumor and kidney nontumor samples), and with large-scale public data for epigenetic regulatory marks and for evolutionarily conserved sequences. A signature of 29 intronic lncRNAs differentially expressed between RCC and nontumor samples was obtained (false discovery rate (FDR) <5%). An additional signature of 26 intronic lncRNAs significantly correlated with the RCC five-year patient survival outcome was identified (FDR <5%, p-value ≤0.01). We identified 4303 intronic antisense lncRNAs expressed in RCC, of which 25% were cis correlated (r >|0.6|) with the expression of the mRNA in the same locus across three human tissues. Gene Ontology (GO) analysis of those loci pointed to ‘regulation of biological processes’ as the main enriched category. A module map analysis of all expressed protein-coding genes in RCC that had a significant (r ≥|0.8|) trans correlation with the 20% most abundant lncRNAs identified 35 relevant (p <0.05) GO sets. In addition, we determined that 60% of these lncRNAs are evolutionarily conserved. At the genomic loci containing the intronic RCC-expressed lncRNAs, a strong association (p <0.001) was found between their transcription start sites and genomic marks such as CpG islands and histones methylation and acetylation. Intronic antisense lncRNAs are widely expressed in RCC tumors. Some of them are significantly altered in RCC in comparison with nontumor samples. The majority of these lncRNAs is evolutionarily conserved and possibly modulated by epigenetic modifications. Our data suggest that these RCC lncRNAs may contribute to the complex network of regulatory RNAs playing a role in renal cell malignant transformation.\"\n", "!Series_overall_design\t\"A total of 22 human kidney tissue samples consisting of 11 primary renal tumors and 11 matched adjacent nontumor tissues from clear cell renal cell carcinmoa (RCC) patients were evaluated in this study. We compared the expression profiles of tumor and non-tumor samples obtained from patients with clear cell RCC to evaluate a possible correlation of the lncRNAs with renal malignancy. The set of clear cell RCC expression profiles was generated using a custom-designed cDNA microarray platform with 4,608 unique elements in replicate (9,216) enriched in gene fragments that map to intronic regions of known human genes (GPL3985).\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient identifier: 3', 'patient identifier: 5', 'patient identifier: 8', 'patient identifier: 9', 'patient identifier: 10', 'patient identifier: 11', 'patient identifier: 24', 'patient identifier: 26', 'patient identifier: 28', 'patient identifier: 30', 'patient identifier: 31'], 1: ['disease: clear cell renal cell carcinoma (RCC)'], 2: ['tissue: adjacent nontumor kidney tissue', 'tissue: primary kidney tumor'], 3: ['gender: female', 'gender: male'], 4: ['age at surgery (yrs): 78', 'age at surgery (yrs): 53', 'age at surgery (yrs): 71', 'age at surgery (yrs): 39', 'age at surgery (yrs): 34', 'age at surgery (yrs): 51', 'age at surgery (yrs): 75', 'age at surgery (yrs): 40', 'age at surgery (yrs): 50'], 5: ['patient status: cancer-specific death', 'patient status: dead from other causes', 'patient status: alive without cancer', 'patient status: alive with cancer', 'fuhrman grade: IV', 'fuhrman grade: III', 'fuhrman grade: II'], 6: [nan, 'tumor size (cm): 6', 'tumor size (cm): 8', 'tumor size (cm): 5', 'tumor size (cm): 6.5', 'tumor size (cm): 7', 'tumor size (cm): 15', 'tumor size (cm): 8.5'], 7: [nan, 'necrosis: yes', 'necrosis: no'], 8: [nan, 'capsule infiltration: yes', 'capsule infiltration: no'], 9: [nan, 'tnm classification (t): 3c', 'tnm classification (t): 2', 'tnm classification (t): 3a', 'tnm classification (t): 1b', 'tnm classification (t): 3b', 'tnm classification (t): 1'], 10: [nan, 'tnm classification (n): no data available', 'tnm classification (n): 1', 'tnm classification (n): 0', 'tnm classification (n): 2'], 11: [nan, 'tnm classification (m): 1', 'tnm classification (m): no data available'], 12: [nan, 'organ metastasis at surgery: endocava, bones', 'organ metastasis at surgery: liver', 'organ metastasis at surgery: no data available', 'organ metastasis at surgery: lung, adjacent tissues'], 13: [nan, 'organ metastasis after surgery: no data available', 'organ metastasis after surgery: liver, spleen', 'organ metastasis after surgery: brain, lung, bones'], 14: [nan, 'patient status: cancer-specific death', 'patient status: dead from other causes', 'patient status: alive without cancer', 'patient status: alive with cancer']}\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": "d27d58c5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9e42e4ec", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:25.069437Z", "iopub.status.busy": "2025-03-25T07:19:25.069319Z", "iopub.status.idle": "2025-03-25T07:19:25.080346Z", "shell.execute_reply": "2025-03-25T07:19:25.080015Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features preview:\n", "{0: [0.0, 78.0, 0.0], 1: [1.0, 53.0, 1.0], 2: [nan, 71.0, nan], 3: [nan, 39.0, nan], 4: [nan, 34.0, nan], 5: [nan, 51.0, nan], 6: [nan, 75.0, nan], 7: [nan, 40.0, nan], 8: [nan, 50.0, nan], 9: [nan, nan, nan], 10: [nan, nan, nan]}\n", "Clinical features saved to: ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE40911.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains expression data for long non-coding RNAs (lncRNAs)\n", "# in renal cell carcinoma. This is gene expression data, not miRNA or methylation data.\n", "import numpy as np\n", "import pandas as pd\n", "import os\n", "import json\n", "\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# For trait (renal cell carcinoma), we can use row 2 which has 'tissue: primary kidney tumor' and 'tissue: adjacent nontumor kidney tissue'\n", "trait_row = 2\n", "\n", "# For age, data is available in row 4\n", "age_row = 4\n", "\n", "# For gender, data is available in row 3\n", "gender_row = 3\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert tissue type to binary (1 for tumor, 0 for non-tumor)\"\"\"\n", " if pd.isnull(value):\n", " return None\n", " value = value.lower()\n", " if 'tumor' in value and 'non' not in value and 'adjacent' not in value:\n", " return 1 # Tumor\n", " elif ('nontumor' in value) or ('adjacent' in value):\n", " return 0 # Non-tumor\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous numeric value\"\"\"\n", " if pd.isnull(value):\n", " return None\n", " try:\n", " # Extract the number after \"age at surgery (yrs): \"\n", " age_str = value.split(':')[1].strip()\n", " return float(age_str)\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n", " if pd.isnull(value):\n", " return None\n", " value = value.lower()\n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# 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", "# If trait data is available, extract clinical features\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary provided in the previous step\n", " # The dictionary keys are row indices and values are lists of unique values\n", " sample_chars_dict = {\n", " 0: ['patient identifier: 3', 'patient identifier: 5', 'patient identifier: 8', 'patient identifier: 9', 'patient identifier: 10', 'patient identifier: 11', 'patient identifier: 24', 'patient identifier: 26', 'patient identifier: 28', 'patient identifier: 30', 'patient identifier: 31'],\n", " 1: ['disease: clear cell renal cell carcinoma (RCC)'],\n", " 2: ['tissue: adjacent nontumor kidney tissue', 'tissue: primary kidney tumor'],\n", " 3: ['gender: female', 'gender: male'],\n", " 4: ['age at surgery (yrs): 78', 'age at surgery (yrs): 53', 'age at surgery (yrs): 71', 'age at surgery (yrs): 39', 'age at surgery (yrs): 34', 'age at surgery (yrs): 51', 'age at surgery (yrs): 75', 'age at surgery (yrs): 40', 'age at surgery (yrs): 50'],\n", " 5: ['patient status: cancer-specific death', 'patient status: dead from other causes', 'patient status: alive without cancer', 'patient status: alive with cancer', 'fuhrman grade: IV', 'fuhrman grade: III', 'fuhrman grade: II'],\n", " 6: [np.nan, 'tumor size (cm): 6', 'tumor size (cm): 8', 'tumor size (cm): 5', 'tumor size (cm): 6.5', 'tumor size (cm): 7', 'tumor size (cm): 15', 'tumor size (cm): 8.5'],\n", " 7: [np.nan, 'necrosis: yes', 'necrosis: no'],\n", " 8: [np.nan, 'capsule infiltration: yes', 'capsule infiltration: no'],\n", " 9: [np.nan, 'tnm classification (t): 3c', 'tnm classification (t): 2', 'tnm classification (t): 3a', 'tnm classification (t): 1b', 'tnm classification (t): 3b', 'tnm classification (t): 1'],\n", " 10: [np.nan, 'tnm classification (n): no data available', 'tnm classification (n): 1', 'tnm classification (n): 0', 'tnm classification (n): 2'],\n", " 11: [np.nan, 'tnm classification (m): 1', 'tnm classification (m): no data available'],\n", " 12: [np.nan, 'organ metastasis at surgery: endocava, bones', 'organ metastasis at surgery: liver', 'organ metastasis at surgery: no data available', 'organ metastasis at surgery: lung, adjacent tissues'],\n", " 13: [np.nan, 'organ metastasis after surgery: no data available', 'organ metastasis after surgery: liver, spleen', 'organ metastasis after surgery: brain, lung, bones'],\n", " 14: [np.nan, 'patient status: cancer-specific death', 'patient status: dead from other causes', 'patient status: alive without cancer', 'patient status: alive with cancer']\n", " }\n", " \n", " # Convert the dictionary to a DataFrame\n", " clinical_data = pd.DataFrame.from_dict(sample_chars_dict, orient='index')\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 extracted clinical features\n", " print(\"Clinical features preview:\")\n", " print(preview_df(clinical_features))\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical features to a CSV file\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to: {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "8c9c165e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "59f74b0c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:25.081436Z", "iopub.status.busy": "2025-03-25T07:19:25.081321Z", "iopub.status.idle": "2025-03-25T07:19:25.107351Z", "shell.execute_reply": "2025-03-25T07:19:25.107015Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Expression analysis and in silico characterization of intronic long noncoding RNAs in renal cell carcinoma: emerging functional associations (RCC malignancy)\"\n", "Line 1: !Series_geo_accession\t\"GSE40911\"\n", "Line 2: !Series_status\t\"Public on Jan 21 2014\"\n", "Line 3: !Series_submission_date\t\"Sep 14 2012\"\n", "Line 4: !Series_last_update_date\t\"Jan 21 2014\"\n", "Line 5: !Series_pubmed_id\t\"24238219\"\n", "Line 6: !Series_summary\t\"Intronic and intergenic long noncoding RNAs (lncRNAs) are emerging gene expression regulators. The molecular pathogenesis of renal cell carcinoma (RCC) is still poorly understood, and in particular, limited studies are available for intronic lncRNAs expressed in RCC. Microarray experiments were performed with two different custom-designed arrays enriched with probes for lncRNAs mapping to intronic genomic regions. Samples from 18 primary clear cell RCC tumors and 11 nontumor adjacent matched tissues were analyzed with 4k-probes microarrays. Oligoarrays with 44k-probes were used to interrogate 17 RCC samples (14 clear cell, 2 papillary, 1 chromophobe subtypes) split into four pools. Meta-analyses were performed by taking the genomic coordinates of the RCC-expressed lncRNAs, and cross-referencing them with microarray expression data from three additional human tissues (normal liver, prostate tumor and kidney nontumor samples), and with large-scale public data for epigenetic regulatory marks and for evolutionarily conserved sequences. A signature of 29 intronic lncRNAs differentially expressed between RCC and nontumor samples was obtained (false discovery rate (FDR) <5%). An additional signature of 26 intronic lncRNAs significantly correlated with the RCC five-year patient survival outcome was identified (FDR <5%, p-value ≤0.01). We identified 4303 intronic antisense lncRNAs expressed in RCC, of which 25% were cis correlated (r >|0.6|) with the expression of the mRNA in the same locus across three human tissues. Gene Ontology (GO) analysis of those loci pointed to ‘regulation of biological processes’ as the main enriched category. A module map analysis of all expressed protein-coding genes in RCC that had a significant (r ≥|0.8|) trans correlation with the 20% most abundant lncRNAs identified 35 relevant (p <0.05) GO sets. In addition, we determined that 60% of these lncRNAs are evolutionarily conserved. At the genomic loci containing the intronic RCC-expressed lncRNAs, a strong association (p <0.001) was found between their transcription start sites and genomic marks such as CpG islands and histones methylation and acetylation. Intronic antisense lncRNAs are widely expressed in RCC tumors. Some of them are significantly altered in RCC in comparison with nontumor samples. The majority of these lncRNAs is evolutionarily conserved and possibly modulated by epigenetic modifications. Our data suggest that these RCC lncRNAs may contribute to the complex network of regulatory RNAs playing a role in renal cell malignant transformation.\"\n", "Line 7: !Series_overall_design\t\"A total of 22 human kidney tissue samples consisting of 11 primary renal tumors and 11 matched adjacent nontumor tissues from clear cell renal cell carcinmoa (RCC) patients were evaluated in this study. We compared the expression profiles of tumor and non-tumor samples obtained from patients with clear cell RCC to evaluate a possible correlation of the lncRNAs with renal malignancy. The set of clear cell RCC expression profiles was generated using a custom-designed cDNA microarray platform with 4,608 unique elements in replicate (9,216) enriched in gene fragments that map to intronic regions of known human genes (GPL3985).\"\n", "Line 8: !Series_type\t\"Non-coding RNA profiling by array\"\n", "Line 9: !Series_type\t\"Expression profiling by array\"\n", "Found table marker at line 81\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM1004655\"\t\"GSM1004656\"\t\"GSM1004657\"\t\"GSM1004658\"\t\"GSM1004659\"\t\"GSM1004660\"\t\"GSM1004661\"\t\"GSM1004662\"\t\"GSM1004663\"\t\"GSM1004664\"\t\"GSM1004665\"\t\"GSM1004666\"\t\"GSM1004667\"\t\"GSM1004668\"\t\"GSM1004669\"\t\"GSM1004670\"\t\"GSM1004671\"\t\"GSM1004672\"\t\"GSM1004673\"\t\"GSM1004674\"\t\"GSM1004675\"\t\"GSM1004676\"\t\"GSM1004677\"\t\"GSM1004678\"\t\"GSM1004679\"\t\"GSM1004680\"\t\"GSM1004681\"\t\"GSM1004682\"\t\"GSM1004683\"\t\"GSM1004684\"\t\"GSM1004685\"\t\"GSM1004686\"\t\"GSM1004687\"\t\"GSM1004688\"\t\"GSM1004689\"\t\"GSM1004690\"\t\"GSM1004691\"\t\"GSM1004692\"\t\"GSM1004693\"\t\"GSM1004694\"\t\"GSM1004695\"\t\"GSM1004696\"\t\"GSM1004697\"\t\"GSM1004698\"\n", "3\t1.437272727\t1.674227273\t5.305340909\t4.193954545\t1.227295455\t3.416227273\t3.718272727\t4.329772727\t2.180568182\t1.933909091\t3.399431818\t2.745636364\t0.493170455\t2.895636364\t5.641727273\t5.072\t2.914045455\t2.665613636\t4.520590909\t3.763863636\t1.114784091\t1.269386364\t1.644761364\t2.243136364\t10.09538636\t6.444636364\t3.452818182\t2.988477273\t2.970159091\t2.901965909\t1.916840909\t2.302204545\t3.091909091\t5.328590909\t2.263227273\t1.810613636\t5.394136364\t5.185056818\t2.817340909\t2.631954545\t1.718863636\t0.911318182\t1.290840909\t1.1845\n", "4\t2.049590909\t2.043772727\t4.909659091\t4.76975\t1.303795455\t2.549125\t5.019545455\t5.817340909\t2.5055\t2.462613636\t3.957761364\t3.516977273\t3.828909091\t3.663988636\t5.990022727\t6.076318182\t3.246022727\t2.836340909\t3.916181818\t3.690272727\t1.114784091\t1.830977273\t1.885590909\t2.281795455\t9.922113636\t7.537636364\t3.981659091\t4.833022727\t4.379863636\t4.322\t1.916840909\t2.846193182\t4.258579545\t4.729909091\t2.949727273\t2.252272727\t8.628886364\t9.6825\t3.649704545\t3.624045455\t0.911318182\t1.885590909\t3.894159091\t2.964522727\n", "6\t6.138931818\t5.641727273\t11.10872727\t10.53229545\t4.600113636\t9.868204545\t10.03477273\t12.37495455\t6.749909091\t6.394931818\t9.169454545\t7.843613636\t11.07529545\t8.795454545\t14.12315909\t13.2645\t7.5195\t7.382090909\t7.814090909\t7.634704545\t1.114784091\t4.560636364\t4.581363636\t4.872477273\t16.06803409\t12.68006818\t7.340625\t9.787522727\t9.197568182\t9.984795455\t6.827977273\t5.195102273\t7.750431818\t5.542954545\t9.937272727\t9.1175\t12.21047727\t14.78147727\t10.95207955\t10.515\t10.15025\t8.656409091\t5.062488636\t4.377954545\n", "7\t1.655090909\t1.115704545\t6.016772727\t6.079090909\t1.45925\t2.676704545\t1.828693182\t2.787204545\t2.109113636\t2.007931818\t2.941045455\t2.685670455\t2.895636364\t2.590840909\t4.788090909\t3.794659091\t2.346329545\t1.400022727\t4.489113636\t3.468318182\t1.114784091\t1.737386364\t1.895159091\t1.746431818\t8.351363636\t5.888681818\t2.646295455\t1.887272727\t1.677363636\t1.217397727\t1.916840909\t2.037568182\t3.757113636\t2.973090909\t2.164375\t1.674795455\t4.452431818\t5.394136364\t2.623704545\t2.234193182\t1.003590909\t1.744397727\t1.441340909\t1.398079545\n", "Total lines examined: 82\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 3055 rows\n", "First 20 gene IDs:\n", "Index(['3', '4', '6', '7', '9', '10', '15', '16', '17', '19', '20', '21', '22',\n", " '23', '26', '27', '31', '32', '33', '35'],\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": "e807208e", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "333922b2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:25.108429Z", "iopub.status.busy": "2025-03-25T07:19:25.108314Z", "iopub.status.idle": "2025-03-25T07:19:25.110207Z", "shell.execute_reply": "2025-03-25T07:19:25.109878Z" } }, "outputs": [], "source": [ "# Gene Identifier Review\n", "# Examining the gene IDs in the extracted data\n", "\n", "# Based on the data shown, these identifiers appear to be probe IDs or numeric identifiers\n", "# rather than standard human gene symbols.\n", "# Human gene symbols would typically be alphanumeric (like BRCA1, TP53, etc.)\n", "# The identifiers shown are simple numbers like '3', '4', '6', '7', etc.\n", "# These would need to be mapped to actual gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "e148c379", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "47f5cda8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:25.111270Z", "iopub.status.busy": "2025-03-25T07:19:25.111155Z", "iopub.status.idle": "2025-03-25T07:19:25.309471Z", "shell.execute_reply": "2025-03-25T07:19:25.309093Z" } }, "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 139072 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['910', '4260', '1981', '2381', '4288'], 'GB_ACC': ['BE833259', 'BE702227', 'BF364095', 'BE081005', 'AW880607'], 'SPOT_TYPE': ['Exonic', 'Exonic', 'Exonic', 'Exonic', 'Exonic'], 'GENE_ID': [85439.0, 2776.0, 84131.0, 2776.0, 54768.0], 'GENE_SYMBOL': ['STON2', 'GNAQ', 'CEP78', 'GNAQ', 'HYDIN'], 'GENE_ANNOTATION': ['stonin 2', 'Guanine nucleotide binding protein (G protein), q polypeptide', 'centrosomal protein 78kDa', 'Guanine nucleotide binding protein (G protein), q polypeptide', 'hydrocephalus inducing homolog 2 (mouse); hydrocephalus inducing homolog (mouse)'], 'CPC_CODING_POTENTIAL': ['noncoding', 'noncoding', 'noncoding', 'noncoding', '-'], 'SEQUENCE': ['CTGATCCGCTTAAGCTTAGTATGTTTGAGTGTGTAATTTTAGTTTCTTTTCTGGTTGTATTTGTGGTAGTCAGATGTGTTGGATTGATTCCAACTGGACAGAGTAAGGAATTCCAGCATCCTCTTCCTGCTTGCTCGTGTTACCCCACAGATCAAACCCTCAATTCTAGTTGGGGATGCTGTCTAGCCCCACACCATGACTGAAGCCTTAAGCACTGTTGCGCCTCCATGTGCTTTGGATCAGCAACCCCAGTGGTATTCTACCAGAGCATTGTGGGAAAGCAGATGTATAGTCAGGTCCCAACAGCAAATTGTTGGGTGTGAGAGTTCTAAAGTATAGGGGTGAGGGAAGAGAAGGATATGAACTCCT', 'CTCTTCCGAAAGATATATCTTGGTTAGAAACACAAAAAAATAAAACTAGTAATATTGTATGTTTATCTATCTCTACATATTTCCAGCATATGTAGCGTTAATAGATCTGTCCTGGTAACTGTGTCTTTGGGATTTCATTTTGGTTCCATCAAATTAGGAAAAGAAATGGCTTAGTTGTATATGATTAGCTAGAGATTTTTGGAGCCAGACACCTGCTGTTTAGTAGATAACTTAGTACAGACCCTAAACTTGTCATTTGTTTTTCTCACAGAATAGCCATTTCCTGCTGTCTTCCCAATGATCACTGCCCTTTCAATAACACTCTTGCCTCTAGAATCATATG', 'CCTTTGAAATGACTGGAGAATATTAAAATAAGAAATAATCATGCAGAGTTGGAAACCAGAAATCTGAACAGTGAAATTGTCTGGCAGGATAAGACGCAGATGCATTTAAGTACCAGTTCAATTAAAGGATGGAACAGCTAAGCCATTCCACTCATCTTCGTGAGCATCTGATTCTGGAGTTTGCGCACCGAGGCTAAGAAAGCAGCTATCTGAAGTGGGAGCGCTGACCCAAGAAATGCTGGGATCGGAGAATAAGGGAATTATCCAAAATGGCTCCGAAGAGGAACTGAAGTTAAGCTGCCCACATGATCTCTCTAACTATGATGACCTGCCACTTCCGTTTATAATCACCACATAAGTGCCTGTAATCATTTGTGTTCATTAAAAGTGAACCAGAATTCCCATTTGGATGAAAAAATAACACTTCCAACTTTAATCTTAGGCCCTCATTTATAAATATGGACAACCAAGAATCATCAAATTTGAAGAAAACCAGTAACATAAAAGGAGGCATGAAATTAAAATTAACCTGTTCAAGAAGATAGTTACTAGGAGAAACATGAAATTTTTAAATTAATGAATCAAAATCTTCAGCAATTCATAAAGATACTGTGTTCATAAAGAATAGGATGCCATGACAAAAATATTTCGAGTTTCCTGGAATTAAACATTTGA', 'CCGTAGCACTTCCTGTACTATACAAGAACAAGAACATAAAACACAGAAACCTTTCTTCAGCATACCAAGGCAAGCAGCCATTTCATGACTCACTTAACACATTGCAGTGTACCAGTTTACAGATGATTTTTCCCTTTTTGCGTGACATGGCAGACCCTGCCGCCAGAGAATTCCTTATTTGTAAATTGGAAGTTTCTACTATGCCTTACAGAGCTTAAATTCAGAAGTTTGTGCCTCATATCTGAAACAAAGGGAAATAACACACCCATTCAAAAGTAAATAAATCTCCTATAAGTTTTTGTTTTTAACATTTCCATATAAAGAGCTCTGTTGAATGTCATGAATAGACTGGAACATAACATTTTAAGAACCTGCATATGTTGTTTACTAGCAGATGACAACTACAAAAGGAATCTGAAGAACACGTAAAACTTGTATTTTTTGGCTTGCACGGGGATATCAACTACCAGGCCTTTTTCAAAAAGGTATTTCAGCTAAGGGGCCAATACACTTTTTGGTACTCCAGACTATCTTGATTGTCAAGGTGTCCGACCTGTATTTTTAAATTTTATACTGCCACATGATTGTA', 'GAGGGATTGGCCCCTGTGGGTCAAATCTCACTTCAAATATTTCCGTTTCACAATGAGGCAGATTCTTTACACGATCTAGCTCAGTACTGAATCCTGTCTCATGAAGGACACGCTTGTCTGCATGGAATGACACTGGAAAGTGACTGGTGTTGATGATCTTGATGATGTGGGTTCGGACTTCGCCAAGGATGATGTAGCCAAAGTCCAGGATGTACTCTGGTAGCTGGATTTTGGCCAGTTTGCGGCGACTCCGATGGCTGAAGCAGGGGTCATCCATAGGATCAGGGGTGGTTGTATTCTGATGTTCTAGGACATAGCTTTGGACTATAAGTCTTTCTACCTCCATCTGGAGATGAGCACTTACCTCAGCAGGCTCGTCTTCTGGCACTTCCTCAGTTATTACGTCAAAGTGATCGAGCATTTCACATTTGTTATACTCTTTGTCTGTGTTTTTCCTGGCTTGATTCAAGAACATTTCATACTTTTCATTTGCTGTGAGGTTCCTGGGGAGATCGAGGCAGATTTGG'], 'COORDINATES': ['chr14:81727450-81727801', 'chr9:80331795-80332137', 'chr9:80885760-80886427', 'chr9:80332512-80333071', 'chr1_gl000192_random:211847-219091'], 'CLONE ID': ['QV3-OT0065-150600-231-c01', 'QV0-NN1022-070700-294-f10', 'QV0-NN1022-120500-220-f07', 'QV1-BT0631-210300-120-f05', 'QV0-OT0031-100300-157-h12'], 'SPOT_ID': ['Exonic', 'Exonic', 'Exonic', 'Exonic', 'Exonic']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'GB_ACC', 'SPOT_TYPE', 'GENE_ID', 'GENE_SYMBOL', 'GENE_ANNOTATION', 'CPC_CODING_POTENTIAL', 'SEQUENCE', 'COORDINATES', 'CLONE ID', 'SPOT_ID']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 137819 out of 139072\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: Exonic\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": "b53f28c2", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "b99cd29b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:25.310922Z", "iopub.status.busy": "2025-03-25T07:19:25.310793Z", "iopub.status.idle": "2025-03-25T07:19:25.408470Z", "shell.execute_reply": "2025-03-25T07:19:25.408123Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Comparing gene IDs between datasets:\n", "First few IDs in gene expression data: ['3', '4', '6', '7', '9']\n", "First few IDs in gene annotation data: ['910', '4260', '1981', '2381', '4288']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Created gene mapping with 3169 rows\n", "Gene mapping preview:\n", "{'ID': ['910', '4260', '1981', '2381', '4288'], 'Gene': ['STON2', 'GNAQ', 'CEP78', 'GNAQ', 'HYDIN']}\n", "\n", "Converting probe-level measurements to gene expression data...\n", "Converted gene expression data has 2502 genes\n", "Gene data preview:\n", "{'GSM1004655': [11.611, 10.926954546000001, 5.866136364, 2.304568182, 3.128022727], 'GSM1004656': [12.39861364, 15.123068182, 6.7795, 2.531636364, 4.258579545], 'GSM1004657': [8.044136364, 9.524568182, 7.152886364, 4.169409091, 5.121579545], 'GSM1004658': [8.556590909, 9.290693181, 7.174977273, 3.884727273, 5.776840909], 'GSM1004659': [7.704806818, 16.374318182, 5.923522727, 0.992409091, 5.195102273], 'GSM1004660': [6.522909091, 9.687295455000001, 7.814090909, 2.001590909, 6.675045455], 'GSM1004661': [9.999795455, 10.968193182, 5.647227273, 2.02575, 5.629681818], 'GSM1004662': [9.7725, 12.251704546, 5.936204545, 4.709954545, 5.837704545], 'GSM1004663': [7.132090909, 9.254681818, 5.132613636, 2.187363636, 6.154090909], 'GSM1004664': [5.202318182, 9.108636364, 8.291772727, 2.650977273, 6.749909091], 'GSM1004665': [7.729409091, 11.017318182, 6.432477273, 2.658306818, 3.019965909], 'GSM1004666': [6.749909091, 9.934795455, 5.235159091, 4.222090909, 2.882488636], 'GSM1004667': [9.229159091, 8.232295454, 8.291772727, 2.534909091, 4.392636364], 'GSM1004668': [9.699704545, 10.358159091000001, 6.468090909, 3.8385, 4.145613636], 'GSM1004669': [7.898068182, 10.755727273, 2.946704545, 3.163329545, 1.896011364], 'GSM1004670': [7.305909091, 15.909022732, 4.333090909, 3.442909091, 2.423590909], 'GSM1004671': [11.17552273, 12.279795454, 7.206340909, 2.149045455, 5.279454545], 'GSM1004672': [11.36931818, 10.411022727, 5.377204545, 2.704318182, 4.781897727], 'GSM1004673': [6.710772727, 12.407284091000001, 7.865613636, 5.0345, 3.488556818], 'GSM1004674': [7.999045455, 14.665750000000001, 5.283454545, 3.0705, 2.289409091], 'GSM1004675': [6.756704545, 10.103159091, 5.647227273, 1.114784091, 1.78625], 'GSM1004676': [6.301863636, 10.231477273, 4.661909091, 2.160954545, 2.859659091], 'GSM1004677': [11.611, 11.460386364, 6.440431818, 0.912181818, 5.733977273], 'GSM1004678': [10.85413636, 12.134636363999999, 5.702545455, 2.234193182, 5.506409091], 'GSM1004679': [6.810522727, 9.054931818, 3.482795455, 6.671613636, 3.380340909], 'GSM1004680': [7.465022727, 10.094306818, 3.427090909, 5.208977273, 3.434204545], 'GSM1004681': [11.93831818, 12.231340909, 6.920977273, 1.309045455, 3.399431818], 'GSM1004682': [10.73384091, 11.851431818, 6.515409091, 3.503613636, 3.492954545], 'GSM1004683': [12.11627273, 15.047090909, 7.524295455, 5.547136364, 3.569806818], 'GSM1004684': [12.37495455, 16.76318182, 6.880375, 6.660886364, 4.829159091], 'GSM1004685': [9.169454545, 7.645613637, 6.037113636, 1.916840909, 8.851568182], 'GSM1004686': [5.752090909, 8.816909091, 6.260897727, 3.121272727, 10.73384091], 'GSM1004687': [7.957818182, 8.856874999999999, 7.904306818, 2.993954545, 3.976977273], 'GSM1004688': [6.022886364, 8.296022727, 8.421681818, 3.789227273, 4.533590909], 'GSM1004689': [8.696045455, 11.166045454999999, 6.651886364, 4.423670455, 1.439886364], 'GSM1004690': [7.371818182, 9.934681818000001, 6.834840909, 4.664215909, 2.184136364], 'GSM1004691': [8.591147727, 10.042613636, 5.958522727, 5.718386364, 1.479147727], 'GSM1004692': [8.100954545, 10.340318181999999, 6.061704545, 6.238136364, 1.606227273], 'GSM1004693': [11.28059091, 9.906738637, 6.756704545, 4.003159091, 4.489113636], 'GSM1004694': [11.14823864, 11.463659091, 6.643340909, 5.027863636, 4.833022727], 'GSM1004695': [11.10872727, 11.734454545, 8.088909091, 2.009568182, 5.506409091], 'GSM1004696': [9.756568182, 11.018136364, 6.793795455, 0.258431818, 3.971659091], 'GSM1004697': [8.489977273, 12.513181818, 6.476136364, 2.962681818, 3.641545455], 'GSM1004698': [5.909795455, 9.900090909, 7.770227273, 2.970159091, 3.018]}\n", "Gene expression data saved to: ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE40911.csv\n" ] } ], "source": [ "# 1. Examine which annotation column contains the probe IDs that match the gene expression data\n", "# Based on previous analysis, the gene expression data has numeric IDs like '3', '4', '6'\n", "# Looking at the annotation data, the 'ID' column seems to contain these identifiers\n", "\n", "# Check the first few IDs from both datasets to verify the match\n", "print(\"\\nComparing gene IDs between datasets:\")\n", "print(\"First few IDs in gene expression data:\", gene_data.index[:5].tolist())\n", "print(\"First few IDs in gene annotation data:\", gene_annotation['ID'][:5].tolist())\n", "\n", "# 2. Extract the gene mapping dataframe\n", "# We need to map probe IDs to gene symbols, where:\n", "# - ID column in gene_annotation matches the gene_data index\n", "# - GENE_SYMBOL column contains the gene symbols we want to map to\n", "prob_col = 'ID'\n", "gene_col = 'GENE_SYMBOL'\n", "\n", "# Create the mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"\\nCreated gene mapping with {len(gene_mapping)} rows\")\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n", "print(\"\\nConverting probe-level measurements to gene expression data...\")\n", "\n", "# Apply the mapping with the library function\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Converted gene expression data has {len(gene_data.index)} genes\")\n", "print(\"Gene data preview:\")\n", "print(preview_df(gene_data))\n", "\n", "# Save the gene expression data to a CSV 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": "5b9ae6cf", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "deb67018", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:19:25.409815Z", "iopub.status.busy": "2025-03-25T07:19:25.409695Z", "iopub.status.idle": "2025-03-25T07:19:25.578724Z", "shell.execute_reply": "2025-03-25T07:19:25.578360Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "Loaded gene data with 2502 genes and 44 samples\n", "After normalization: 2488 genes\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE40911.csv\n", "\n", "Linking clinical and genetic data...\n", "Loaded clinical data with shape: (3, 12)\n", "Clinical data columns: ['Unnamed: 0', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']\n", "Clinical data preview:\n", " Unnamed: 0 0 1 2 3 4 5 6 \\\n", "0 Kidney_Papillary_Cell_Carcinoma 0.0 1.0 NaN NaN NaN NaN NaN \n", "1 Age 78.0 53.0 71.0 39.0 34.0 51.0 75.0 \n", "2 Gender 0.0 1.0 NaN NaN NaN NaN NaN \n", "\n", " 7 8 9 10 \n", "0 NaN NaN NaN NaN \n", "1 40.0 50.0 NaN NaN \n", "2 NaN NaN NaN NaN \n", "Created linked data with 47 samples and 2500 features\n", "\n", "Handling missing values...\n", "After handling missing values: 3 samples and 3 features\n", "\n", "Evaluating feature bias...\n", "Error evaluating feature bias: unsupported operand type(s) for -: 'str' and 'str'\n", "\n", "Performing final validation...\n", "Abnormality detected in the cohort: GSE40911. Preprocessing failed.\n", "\n", "Dataset usability for Kidney_Papillary_Cell_Carcinoma association studies: False\n", "Reason: Dataset has severe bias in the trait distribution\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/media/techt/DATA/GenoAgent/tools/preprocess.py:455: FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n", " df[gene_cols] = df[gene_cols].fillna(df[gene_cols].mean())\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\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. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " # Load clinical data from step 2\n", " clinical_data = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data with shape: {clinical_data.shape}\")\n", " \n", " # Print clinical data columns and preview for debugging\n", " print(\"Clinical data columns:\", clinical_data.columns.tolist())\n", " print(\"Clinical data preview:\")\n", " print(clinical_data.head())\n", " \n", " # In clinical data from geo_select_clinical_features, the trait is the first column (index 0)\n", " # and rows are in columns format (with genes as rows in gene_data)\n", " # We need to transpose it for linking with gene data\n", " clinical_transpose = clinical_data.T\n", " \n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_transpose, gene_data)\n", " print(f\"Created linked data with {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n", " is_trait_available = True\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", "# 3. 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", " # 4. 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", "# 5. 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", "# 6. 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 }