{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "eccc1cb0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:06.555470Z", "iopub.status.busy": "2025-03-25T07:16:06.555246Z", "iopub.status.idle": "2025-03-25T07:16:06.715246Z", "shell.execute_reply": "2025-03-25T07:16:06.714806Z" } }, "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 = \"GSE40912\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Chromophobe\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Chromophobe/GSE40912\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Chromophobe/GSE40912.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Chromophobe/gene_data/GSE40912.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE40912.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Chromophobe/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "405b5f3f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "b71bae91", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:06.716478Z", "iopub.status.busy": "2025-03-25T07:16:06.716341Z", "iopub.status.idle": "2025-03-25T07:16:06.736237Z", "shell.execute_reply": "2025-03-25T07:16:06.735847Z" } }, "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 survival)\"\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 16 human renal tumors from clear cell renal cell carcinoma (RCC) patients were evaluated in this study. We compared the expression profiles of tumor samples obtained from patients with clear cell RCC who died as a consequence of the disease versus those alive without disease (5-years follow-up) to evaluate a possible correlation of the lncRNAs with patient survival. 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: 1', 'patient identifier: 3', 'patient identifier: 5', 'patient identifier: 7', 'patient identifier: 9', 'patient identifier: 10', 'patient identifier: 11', 'patient identifier: 13', 'patient identifier: 15', 'patient identifier: 24', 'patient identifier: 26', 'patient identifier: 28', 'patient identifier: 29', 'patient identifier: 30', 'patient identifier: 32', 'patient identifier: 33'], 1: ['disease: clear cell renal cell carcinoma (RCC)'], 2: ['tissue: kidney tumor'], 3: ['gender: male', 'gender: female'], 4: ['age at surgery (yrs): 51', 'age at surgery (yrs): 78', 'age at surgery (yrs): 53', 'age at surgery (yrs): 41', 'age at surgery (yrs): 39', 'age at surgery (yrs): 34', 'age at surgery (yrs): 66', 'age at surgery (yrs): 75', 'age at surgery (yrs): 40', 'age at surgery (yrs): 63', 'age at surgery (yrs): 35'], 5: ['fuhrman grade: III', 'fuhrman grade: IV', 'fuhrman grade: II'], 6: ['tumor size (cm): 18', 'tumor size (cm): 6', 'tumor size (cm): 8', 'tumor size (cm): 11', 'tumor size (cm): 6.5', 'tumor size (cm): 7', 'tumor size (cm): 5', 'tumor size (cm): 10', 'tumor size (cm): 15', 'tumor size (cm): 20', 'tumor size (cm): 8.5', 'tumor size (cm): 13', 'tumor size (cm): 4'], 7: ['necrosis: yes', 'necrosis: no'], 8: ['capsule infiltration: yes', 'capsule infiltration: no'], 9: ['tnm classification (t): 3c', 'tnm classification (t): 2', 'tnm classification (t): 3a', 'tnm classification (t): 1b', 'tnm classification (t): 3', 'tnm classification (t): 3b', 'tnm classification (t): 1', 'tnm classification (t): 1a'], 10: ['tnm classification (n): no data available', 'tnm classification (n): 1', 'tnm classification (n): 0', 'tnm classification (n): 2'], 11: ['tnm classification (m): no data available', 'tnm classification (m): 1'], 12: ['organ metastasis at surgery: no data available', 'organ metastasis at surgery: endocava, bones', 'organ metastasis at surgery: liver', 'organ metastasis at surgery: lung', 'organ metastasis at surgery: peritoneum'], 13: ['organ metastasis after surgery: no data available', 'organ metastasis after surgery: liver, spleen', 'organ metastasis after surgery: bones', 'organ metastasis after surgery: brain, lung, bones'], 14: ['patient status: cancer-specific death', 'patient status: alive without cancer'], 15: ['follow-up (months): 0', 'follow-up (months): 21', 'follow-up (months): 6', 'follow-up (months): 66', 'follow-up (months): 60', 'follow-up (months): 8', 'follow-up (months): 16', 'follow-up (months): 62', 'follow-up (months): 54', 'follow-up (months): 56', 'follow-up (months): 17']}\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": "638211ec", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "ba001210", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:06.737213Z", "iopub.status.busy": "2025-03-25T07:16:06.737107Z", "iopub.status.idle": "2025-03-25T07:16:06.750621Z", "shell.execute_reply": "2025-03-25T07:16:06.750249Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Features Preview:\n", "{'GSM1000': [1.0, 51.0, 1.0], 'GSM1001': [0.0, 78.0, 0.0], 'GSM1002': [nan, 53.0, nan], 'GSM1003': [nan, 41.0, nan], 'GSM1004': [nan, 39.0, nan], 'GSM1005': [nan, 34.0, nan], 'GSM1006': [nan, 66.0, nan], 'GSM1007': [nan, 75.0, nan], 'GSM1008': [nan, 40.0, nan], 'GSM1009': [nan, 63.0, nan], 'GSM1010': [nan, 35.0, nan], 'GSM1011': [nan, nan, nan], 'GSM1012': [nan, nan, nan], 'GSM1013': [nan, nan, nan], 'GSM1014': [nan, nan, nan], 'GSM1015': [nan, nan, nan]}\n", "Saved clinical features to ../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE40912.csv\n" ] } ], "source": [ "# Step 1: Is gene expression data available?\n", "is_gene_available = True # Based on the background info, this dataset contains gene expression data (microarray)\n", "\n", "# Step 2: Clinical feature extraction\n", "\n", "# 2.1 Identify the row indices for trait, age, and gender\n", "trait_row = 14 # 'patient status' gives survival information related to Kidney cancer\n", "age_row = 4 # 'age at surgery (yrs)' gives age information\n", "gender_row = 3 # 'gender' gives gender information\n", "\n", "# 2.2 Define conversion functions for each variable\n", "\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert trait value to binary (1 for death from cancer, 0 for alive without cancer)\n", " \"\"\"\n", " if not isinstance(value, str) or \":\" not in value:\n", " return None\n", " status = value.split(\":\", 1)[1].strip().lower()\n", " if \"death\" in status:\n", " return 1\n", " elif \"alive\" in status:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age value to continuous numeric value\n", " \"\"\"\n", " if not isinstance(value, str) or \":\" not in value:\n", " return None\n", " try:\n", " age_str = value.split(\":\", 1)[1].strip()\n", " return float(age_str)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender value to binary (1 for male, 0 for female)\n", " \"\"\"\n", " if not isinstance(value, str) or \":\" not in value:\n", " return None\n", " gender = value.split(\":\", 1)[1].strip().lower()\n", " if \"male\" == gender:\n", " return 1\n", " elif \"female\" == gender:\n", " return 0\n", " else:\n", " return None\n", "\n", "# Step 3: Save metadata - initial filtering\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", "# Step 4: Clinical feature extraction (only if trait_row is not None)\n", "if trait_row is not None:\n", " # Sample characteristics data from previous step\n", " sample_chars = {0: ['patient identifier: 1', 'patient identifier: 3', 'patient identifier: 5', 'patient identifier: 7', 'patient identifier: 9', 'patient identifier: 10', 'patient identifier: 11', 'patient identifier: 13', 'patient identifier: 15', 'patient identifier: 24', 'patient identifier: 26', 'patient identifier: 28', 'patient identifier: 29', 'patient identifier: 30', 'patient identifier: 32', 'patient identifier: 33'], \n", " 1: ['disease: clear cell renal cell carcinoma (RCC)'], \n", " 2: ['tissue: kidney tumor'], \n", " 3: ['gender: male', 'gender: female'], \n", " 4: ['age at surgery (yrs): 51', 'age at surgery (yrs): 78', 'age at surgery (yrs): 53', 'age at surgery (yrs): 41', 'age at surgery (yrs): 39', 'age at surgery (yrs): 34', 'age at surgery (yrs): 66', 'age at surgery (yrs): 75', 'age at surgery (yrs): 40', 'age at surgery (yrs): 63', 'age at surgery (yrs): 35'], \n", " 5: ['fuhrman grade: III', 'fuhrman grade: IV', 'fuhrman grade: II'], \n", " 6: ['tumor size (cm): 18', 'tumor size (cm): 6', 'tumor size (cm): 8', 'tumor size (cm): 11', 'tumor size (cm): 6.5', 'tumor size (cm): 7', 'tumor size (cm): 5', 'tumor size (cm): 10', 'tumor size (cm): 15', 'tumor size (cm): 20', 'tumor size (cm): 8.5', 'tumor size (cm): 13', 'tumor size (cm): 4'], \n", " 7: ['necrosis: yes', 'necrosis: no'], \n", " 8: ['capsule infiltration: yes', 'capsule infiltration: no'], \n", " 9: ['tnm classification (t): 3c', 'tnm classification (t): 2', 'tnm classification (t): 3a', 'tnm classification (t): 1b', 'tnm classification (t): 3', 'tnm classification (t): 3b', 'tnm classification (t): 1', 'tnm classification (t): 1a'], \n", " 10: ['tnm classification (n): no data available', 'tnm classification (n): 1', 'tnm classification (n): 0', 'tnm classification (n): 2'], \n", " 11: ['tnm classification (m): no data available', 'tnm classification (m): 1'], \n", " 12: ['organ metastasis at surgery: no data available', 'organ metastasis at surgery: endocava, bones', 'organ metastasis at surgery: liver', 'organ metastasis at surgery: lung', 'organ metastasis at surgery: peritoneum'], \n", " 13: ['organ metastasis after surgery: no data available', 'organ metastasis after surgery: liver, spleen', 'organ metastasis after surgery: bones', 'organ metastasis after surgery: brain, lung, bones'], \n", " 14: ['patient status: cancer-specific death', 'patient status: alive without cancer'], \n", " 15: ['follow-up (months): 0', 'follow-up (months): 21', 'follow-up (months): 6', 'follow-up (months): 66', 'follow-up (months): 60', 'follow-up (months): 8', 'follow-up (months): 16', 'follow-up (months): 62', 'follow-up (months): 54', 'follow-up (months): 56', 'follow-up (months): 17']}\n", " \n", " # Create a properly structured DataFrame from the sample characteristics\n", " # We need to create a DataFrame where each row is a feature and each column is a sample\n", " max_samples = max(len(values) for values in sample_chars.values())\n", " sample_ids = [f'GSM{1000+i}' for i in range(max_samples)]\n", " \n", " # Initialize a DataFrame with the rows being the feature types\n", " clinical_data = pd.DataFrame(index=sample_chars.keys(), columns=sample_ids)\n", " \n", " # Fill in the data\n", " for row_idx, values in sample_chars.items():\n", " for col_idx, value in enumerate(values):\n", " if col_idx < max_samples:\n", " clinical_data.iloc[row_idx, col_idx] = value\n", " \n", " # Extract clinical features using the library function\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 selected clinical features\n", " clinical_preview = preview_df(clinical_features)\n", " print(\"Clinical Features Preview:\")\n", " print(clinical_preview)\n", " \n", " # Save the clinical features to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Saved clinical features to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "379cd901", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "5fc4f932", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:06.751779Z", "iopub.status.busy": "2025-03-25T07:16:06.751675Z", "iopub.status.idle": "2025-03-25T07:16:06.770506Z", "shell.execute_reply": "2025-03-25T07:16:06.770134Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n", "Successfully extracted gene data with 3205 rows\n", "First 20 gene IDs:\n", "Index(['1', '2', '3', '4', '5', '6', '7', '9', '10', '11', '13', '14', '15',\n", " '16', '17', '18', '19', '20', '21', '22'],\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": "2f54e0b4", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "833c54f8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:06.771679Z", "iopub.status.busy": "2025-03-25T07:16:06.771577Z", "iopub.status.idle": "2025-03-25T07:16:06.773483Z", "shell.execute_reply": "2025-03-25T07:16:06.773117Z" } }, "outputs": [], "source": [ "# The identifiers seen in the gene data are numeric IDs (1, 2, 3, etc.) which are not human gene symbols.\n", "# These appear to be Entrez Gene IDs or possibly probe IDs that need to be mapped to gene symbols.\n", "# As a domain expert, I can confirm these numeric identifiers require mapping to human gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "09a89da6", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "099718fe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:06.774639Z", "iopub.status.busy": "2025-03-25T07:16:06.774538Z", "iopub.status.idle": "2025-03-25T07:16:06.926888Z", "shell.execute_reply": "2025-03-25T07:16:06.926362Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n", "Successfully extracted gene annotation data with 107200 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: 105947 out of 107200\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": "f7f2f029", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "4b4a10dd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:06.928322Z", "iopub.status.busy": "2025-03-25T07:16:06.928214Z", "iopub.status.idle": "2025-03-25T07:16:07.001215Z", "shell.execute_reply": "2025-03-25T07:16:07.000811Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapping gene identifiers to gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Created gene mapping with 3169 entries\n", "Mapping preview (first 5 rows):\n", " ID Gene\n", "0 910 STON2\n", "1 4260 GNAQ\n", "2 1981 CEP78\n", "3 2381 GNAQ\n", "4 4288 HYDIN\n", "\n", "Converting probe measurements to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully mapped to 2608 genes\n", "First 10 mapped gene symbols:\n", "['A2ML1', 'AARSD1', 'AATF', 'ABCA2', 'ABCA3', 'ABCB1', 'ABCB10', 'ABCB6', 'ABCB7', 'ABCC10']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved gene expression data to ../../output/preprocess/Kidney_Chromophobe/gene_data/GSE40912.csv\n" ] } ], "source": [ "# 1. Identify the columns that contain gene identifiers and gene symbols in the annotation data\n", "print(\"Mapping gene identifiers to gene symbols...\")\n", "\n", "# Based on the preview, the 'ID' column in annotation contains the same numeric identifiers\n", "# that we saw in the gene expression data, and 'GENE_SYMBOL' contains the gene symbols\n", "id_column = 'ID'\n", "gene_symbol_column = 'GENE_SYMBOL'\n", "\n", "# 2. Get a gene mapping dataframe using the helper function\n", "gene_mapping = get_gene_mapping(gene_annotation, id_column, gene_symbol_column)\n", "print(f\"Created gene mapping with {len(gene_mapping)} entries\")\n", "print(\"Mapping preview (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression data\n", "print(\"\\nConverting probe measurements to gene expression data...\")\n", "try:\n", " gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", " print(f\"Successfully mapped to {len(gene_data.index)} genes\")\n", " print(\"First 10 mapped gene symbols:\")\n", " print(gene_data.index[:10].tolist())\n", " \n", " # Save the gene expression data to CSV\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\"Saved gene expression data to {out_gene_data_file}\")\n", " \n", "except Exception as e:\n", " print(f\"Error applying gene mapping: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "f61c3eb6", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "0ba4f320", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:16:07.002718Z", "iopub.status.busy": "2025-03-25T07:16:07.002606Z", "iopub.status.idle": "2025-03-25T07:16:07.137217Z", "shell.execute_reply": "2025-03-25T07:16:07.136672Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "After normalization: 2592 unique gene symbols\n", "Normalized gene expression data saved to ../../output/preprocess/Kidney_Chromophobe/gene_data/GSE40912.csv\n", "\n", "Loading clinical data...\n", "Loaded clinical data with shape: (3, 16)\n", "Clinical data preview:\n", "{'Kidney_Chromophobe': [1.0, 51.0, 1.0], 'GSM1001': [0.0, 78.0, 0.0], 'GSM1002': [nan, 53.0, nan], 'GSM1003': [nan, 41.0, nan], 'GSM1004': [nan, 39.0, nan], 'GSM1005': [nan, 34.0, nan], 'GSM1006': [nan, 66.0, nan], 'GSM1007': [nan, 75.0, nan], 'GSM1008': [nan, 40.0, nan], 'GSM1009': [nan, 63.0, nan], 'GSM1010': [nan, 35.0, nan], 'GSM1011': [nan, nan, nan], 'GSM1012': [nan, nan, nan], 'GSM1013': [nan, nan, nan], 'GSM1014': [nan, nan, nan], 'GSM1015': [nan, nan, nan]}\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (0, 2596)\n", "Trait column 'Kidney_Chromophobe' not found in linked data.\n", "\n", "Performing final validation...\n", "Abnormality detected in the cohort: GSE40912. 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", "# 2. Load the clinical data that was previously saved in Step 2\n", "print(\"\\nLoading clinical data...\")\n", "try:\n", " # Check if the clinical data file exists\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", " # Make sure the trait column is present\n", " if trait not in clinical_df.columns:\n", " # If we don't have the trait column, rename the first column (which should be the trait)\n", " clinical_df = clinical_df.rename(columns={clinical_df.columns[0]: trait})\n", " is_trait_available = True\n", " else:\n", " # If we don't have the file, use the clinical data from Step 2\n", " print(\"Clinical data file not found. Using the clinical features extracted in Step 2.\")\n", " # We know from Step 2 that trait_row=14, age_row=4, gender_row=3\n", " clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=14, # 'patient status' (survival info)\n", " convert_trait=convert_trait,\n", " age_row=4, # 'age at surgery'\n", " convert_age=convert_age,\n", " gender_row=3, # 'gender'\n", " convert_gender=convert_gender\n", " )\n", " is_trait_available = True\n", " \n", " print(\"Clinical data preview:\")\n", " print(preview_df(clinical_df))\n", " \n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " is_trait_available = False\n", " clinical_df = pd.DataFrame() # Empty DataFrame if clinical data is unavailable\n", "\n", "# 3. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if not clinical_df.empty and not normalized_gene_data.empty:\n", " # Convert clinical_df to have samples as rows if it doesn't already\n", " if clinical_df.shape[0] <= 5: # Small number of rows suggests features as rows\n", " clinical_df = clinical_df.T\n", " # Ensure the index is not the trait and covariates\n", " if clinical_df.index.name is None:\n", " clinical_df = clinical_df.reset_index()\n", " \n", " linked_data = pd.concat([clinical_df, normalized_gene_data.T], axis=1, join='inner')\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Check if we have at least one sample with trait value\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", " # 4. 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", " # 5. Determine whether the trait and demographic features are biased\n", " print(\"\\nChecking for bias in features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " else:\n", " print(\"No samples have valid trait values. Dataset cannot be used.\")\n", " is_biased = True\n", " else:\n", " print(f\"Trait column '{trait}' not found in linked data.\")\n", " is_biased = True\n", " else:\n", " print(\"Cannot link data: clinical or genetic data is missing\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " \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", "# 6. Final quality validation\n", "print(\"\\nPerforming final validation...\")\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased if 'is_biased' in locals() else True,\n", " df=linked_data if 'linked_data' in locals() and not linked_data.empty else pd.DataFrame(),\n", " note=\"Dataset contains clear cell RCC patient expression data with survival information.\"\n", ")\n", "\n", "# 7. Save linked data if usable\n", "if is_usable and 'linked_data' in locals() and not linked_data.empty:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " \n", " # Save linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Dataset not usable for {trait} association studies. Data not saved.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }