{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "3e4e5c47", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:05.027543Z", "iopub.status.busy": "2025-03-25T07:16:05.027432Z", "iopub.status.idle": "2025-03-25T07:16:05.189605Z", "shell.execute_reply": "2025-03-25T07:16:05.189155Z" } }, "outputs": [], "source": [ "import sys\n", "import os\n", "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n", "\n", "# Path Configuration\n", "from tools.preprocess import *\n", "\n", "# Processing context\n", "trait = \"Kidney_Chromophobe\"\n", "cohort = \"GSE40911\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Chromophobe\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Chromophobe/GSE40911\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Chromophobe/GSE40911.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Chromophobe/gene_data/GSE40911.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE40911.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Chromophobe/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "d3672b1a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "00283ae8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:05.190979Z", "iopub.status.busy": "2025-03-25T07:16:05.190836Z", "iopub.status.idle": "2025-03-25T07:16:05.222524Z", "shell.execute_reply": "2025-03-25T07:16:05.222124Z" } }, "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": "880a378b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "04517395", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:05.223985Z", "iopub.status.busy": "2025-03-25T07:16:05.223879Z", "iopub.status.idle": "2025-03-25T07:16:05.239323Z", "shell.execute_reply": "2025-03-25T07:16:05.238858Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical data:\n", "{0: [nan, 10.0, nan], 1: [nan, nan, nan], 2: [nan, nan, nan], 3: [nan, nan, nan], 4: [nan, 34.0, nan], 5: [nan, nan, nan], 6: [nan, 6.5, nan], 7: [nan, nan, nan], 8: [nan, nan, nan], 9: [nan, nan, nan], 10: [nan, 2.0, nan], 11: [nan, nan, nan], 12: [nan, nan, nan], 13: [nan, nan, nan], 14: [nan, nan, nan]}\n", "Clinical data saved to ../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE40911.csv\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on background information, this dataset contains gene expression data from microarray experiments\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Trait data (Kidney_Chromophobe)\n", "# Looking at the sample characteristics dict, we can see \"tissue: adjacent nontumor kidney tissue\" vs \"tissue: primary kidney tumor\" at index 2\n", "trait_row = 2 # Using the tissue field since we want to compare tumor vs non-tumor\n", "\n", "# Define conversion function for trait\n", "def convert_trait(value):\n", " if not isinstance(value, str):\n", " return None\n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " # Convert to binary: 1 for tumor (case), 0 for non-tumor (control)\n", " if 'tumor' in value.lower() and 'nontumor' not in value.lower() and 'non-tumor' not in value.lower():\n", " return 1\n", " elif 'nontumor' in value.lower() or 'non-tumor' in value.lower() or 'adjacent' in value.lower():\n", " return 0\n", " return None\n", "\n", "# 2.2 Age data\n", "age_row = 4 # Age at surgery is at index 4\n", "\n", "def convert_age(value):\n", " if not isinstance(value, str):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " try:\n", " # Extract numeric age value\n", " # The format seems to be \"age at surgery (yrs): XX\"\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "# 2.3 Gender data\n", "gender_row = 3 # Gender is at index 3\n", "\n", "def convert_gender(value):\n", " if not isinstance(value, str):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " # Convert to binary: 0 for female, 1 for male\n", " if 'female' in value.lower():\n", " return 0\n", " elif 'male' in value.lower():\n", " return 1\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", "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_row is not None:\n", " # Create clinical_data from the sample characteristics dictionary shown in the output\n", " # The dictionary format is {row_index: [values_for_each_sample]}\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", " # Create a properly structured DataFrame that can be used with geo_select_clinical_features\n", " clinical_data = pd.DataFrame()\n", " for i, values in sample_chars_dict.items():\n", " clinical_data[i] = pd.Series(values)\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 dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of clinical data:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "b251998f", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "41720ba0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:05.240727Z", "iopub.status.busy": "2025-03-25T07:16:05.240623Z", "iopub.status.idle": "2025-03-25T07:16:05.262973Z", "shell.execute_reply": "2025-03-25T07:16:05.262528Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting 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", "# 2. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting gene data from matrix file:\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "063aa5f3", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3d3e4ac2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:05.264372Z", "iopub.status.busy": "2025-03-25T07:16:05.264268Z", "iopub.status.idle": "2025-03-25T07:16:05.266387Z", "shell.execute_reply": "2025-03-25T07:16:05.265966Z" } }, "outputs": [], "source": [ "# Review gene identifiers in the gene expression data\n", "# The identifiers appear to be numeric values (e.g., '3', '4', '6', etc.)\n", "# These are not standard human gene symbols, which typically look like BRCA1, TP53, etc.\n", "# These numeric IDs likely need to be mapped to proper gene symbols\n", "\n", "# This is likely to be Entrez Gene IDs or some other numeric identifier system\n", "# Proper gene symbols are alphabetic (like BRCA1, TP53) not purely numeric\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "9bcf1f80", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "fb10f677", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:05.267754Z", "iopub.status.busy": "2025-03-25T07:16:05.267655Z", "iopub.status.idle": "2025-03-25T07:16:05.448649Z", "shell.execute_reply": "2025-03-25T07:16:05.448129Z" } }, "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": "d98785bd", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "f051144e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:05.450065Z", "iopub.status.busy": "2025-03-25T07:16:05.449948Z", "iopub.status.idle": "2025-03-25T07:16:05.540685Z", "shell.execute_reply": "2025-03-25T07:16:05.540261Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapping gene identifiers to gene symbols...\n", "Created gene mapping with 3169 entries\n", "\n", "Gene mapping preview (first few rows):\n", "{'ID': ['910', '4260', '1981', '2381', '4288'], 'Gene': ['STON2', 'GNAQ', 'CEP78', 'GNAQ', 'HYDIN']}\n", "\n", "Converting probe-level measurements to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully converted to gene expression data with 2502 genes\n", "\n", "Gene expression data preview (first few genes):\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_Chromophobe/gene_data/GSE40911.csv\n" ] } ], "source": [ "# 1. Identify the mapping columns\n", "# From the gene annotation preview, we need to map from 'ID' to 'GENE_SYMBOL'\n", "# The gene expression data also uses 'ID' as its index\n", "print(\"Mapping gene identifiers to gene symbols...\")\n", "\n", "# 2. Extract the mapping columns and create a mapping dataframe\n", "prob_col = 'ID' # Column with probe identifiers\n", "gene_col = 'GENE_SYMBOL' # Column with gene symbols\n", "\n", "# Create the mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Created gene mapping with {len(mapping_df)} entries\")\n", "\n", "# Preview the mapping dataframe\n", "print(\"\\nGene mapping preview (first few rows):\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene expression data\n", "print(\"\\nConverting probe-level measurements to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Successfully converted to gene expression data with {len(gene_data.index)} genes\")\n", "\n", "# Preview the gene expression data\n", "print(\"\\nGene expression data preview (first few genes):\")\n", "print(preview_df(gene_data))\n", "\n", "# Save the gene expression data to the output 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": "17f97c36", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f1ee082a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:05.541843Z", "iopub.status.busy": "2025-03-25T07:16:05.541722Z", "iopub.status.idle": "2025-03-25T07:16:05.685404Z", "shell.execute_reply": "2025-03-25T07:16:05.684863Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "After normalization: 2488 unique gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Kidney_Chromophobe/gene_data/GSE40911.csv\n", "\n", "Loading clinical data...\n", "Loaded clinical data with shape: (3, 15)\n", "Clinical data preview:\n", "{'0': [nan, 10.0, nan], '1': [nan, nan, nan], '2': [nan, nan, nan], '3': [nan, nan, nan], '4': [nan, 34.0, nan], '5': [nan, nan, nan], '6': [nan, 6.5, nan], '7': [nan, nan, nan], '8': [nan, nan, nan], '9': [nan, nan, nan], '10': [nan, 2.0, nan], '11': [nan, nan, nan], '12': [nan, nan, nan], '13': [nan, nan, nan], '14': [nan, nan, nan]}\n", "Note: This dataset (GSE40911) focuses on clear cell renal cell carcinoma, not chromophobe RCC.\n", "The background information states: 'disease: clear cell renal cell carcinoma (RCC)' in row 1\n", "\n", "Linking clinical and genetic data...\n", "Cannot link data: clinical data is missing, genetic data is missing, or trait is unavailable\n", "\n", "Performing final validation...\n", "Abnormality detected in the cohort: GSE40911. Preprocessing failed.\n", "Dataset not usable for Kidney_Chromophobe association studies. Data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "try:\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {len(normalized_gene_data.index)} unique gene symbols\")\n", " \n", " # Save the normalized gene data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene symbols: {e}\")\n", " normalized_gene_data = gene_data # Use original data if normalization fails\n", "\n", "# Load clinical data from Step 2 (from the location where we saved it)\n", "print(\"\\nLoading clinical data...\")\n", "try:\n", " if os.path.exists(out_clinical_data_file):\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(preview_df(clinical_df))\n", " \n", " # Transform the clinical data to have proper feature names\n", " clinical_df_transformed = pd.DataFrame()\n", " clinical_df_transformed[trait] = [0] * len(clinical_df.columns) # Initialize with default values\n", " clinical_df_transformed['Age'] = [None] * len(clinical_df.columns)\n", " clinical_df_transformed['Gender'] = [None] * len(clinical_df.columns)\n", " \n", " # Set the indices to be the column names from original clinical_df\n", " clinical_df_transformed.index = clinical_df.columns\n", " \n", " # Based on background information, this dataset doesn't contain chromophobe RCC information\n", " print(\"Note: This dataset (GSE40911) focuses on clear cell renal cell carcinoma, not chromophobe RCC.\")\n", " print(\"The background information states: 'disease: clear cell renal cell carcinoma (RCC)' in row 1\")\n", " is_trait_available = False\n", " else:\n", " print(\"Clinical data file does not exist.\")\n", " is_trait_available = False\n", " clinical_df_transformed = pd.DataFrame()\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " is_trait_available = False\n", " clinical_df_transformed = pd.DataFrame()\n", "\n", "# 2. Link clinical and genetic data if available\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if not clinical_df_transformed.empty and not normalized_gene_data.empty and is_trait_available:\n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df_transformed, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Check if we have any valid trait values\n", " if trait in linked_data.columns:\n", " trait_count = linked_data[trait].count()\n", " print(f\"Number of samples with trait values: {trait_count}\")\n", " \n", " if trait_count > 0:\n", " # 3. Handle missing values systematically\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, data shape: {linked_data.shape}\")\n", " \n", " # Check if we still have samples after missing value handling\n", " if linked_data.shape[0] > 0:\n", " # 4. Determine whether the trait and demographic features are biased\n", " print(\"\\nChecking for bias in features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " else:\n", " print(\"Error: All samples were removed during missing value handling.\")\n", " is_biased = True\n", " else:\n", " print(\"No samples have valid trait values. Dataset cannot be used.\")\n", " is_biased = True\n", " else:\n", " print(f\"The {trait} trait column is not present in the linked data.\")\n", " is_biased = True\n", " else:\n", " print(\"Cannot link data: clinical data is missing, genetic data is missing, or trait is unavailable\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " \n", "except Exception as e:\n", " print(f\"Error in linking clinical and genetic data: {e}\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 5. Final quality validation\n", "print(\"\\nPerforming final validation...\")\n", "# Based on the dataset context, this dataset doesn't contain chromophobe RCC information\n", "note = \"Dataset contains clear cell renal cell carcinoma samples, not chromophobe RCC as required by the trait.\"\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased if 'is_biased' in locals() else True,\n", " df=linked_data if 'linked_data' in locals() and not linked_data.empty else pd.DataFrame(),\n", " note=note\n", ")\n", "\n", "# 6. Save linked data if usable\n", "if is_usable and 'linked_data' in locals() and not linked_data.empty:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " \n", " # Save linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Dataset not usable for {trait} association studies. Data not saved.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }