{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "7b02aee2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:15:27.839313Z", "iopub.status.busy": "2025-03-25T07:15:27.839217Z", "iopub.status.idle": "2025-03-25T07:15:27.997427Z", "shell.execute_reply": "2025-03-25T07:15:27.997098Z" } }, "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 = \"GSE19949\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Chromophobe\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Chromophobe/GSE19949\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Chromophobe/GSE19949.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Chromophobe/gene_data/GSE19949.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE19949.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Chromophobe/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "9955f0e6", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "84fef3c4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:15:27.998832Z", "iopub.status.busy": "2025-03-25T07:15:27.998691Z", "iopub.status.idle": "2025-03-25T07:15:28.261904Z", "shell.execute_reply": "2025-03-25T07:15:28.261568Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Integrative genome-wide expression profiling identifies three distinct molecular subgroups of renal cell carcinoma with different patient outcome\"\n", "!Series_summary\t\"Background: Renal cell carcinoma (RCC) is characterized by a number of diverse molecular aberrations that differ among individuals. Recent approaches to molecularly classify RCC were based on clinical, pathological as well as on single molecular parameters. As a consequence, gene expression patterns reflecting the sum of genetic aberrations in individual tumors may not have been recognized. In an attempt to uncover such molecular features in RCC, we used a novel, unbiased and integrative approach.\"\n", "!Series_summary\t\"Methods: We integrated gene expression data from 97 primary RCCs of different pathologic parameters, 15 RCC metastases as well as 34 cancer cell lines for two-way nonsupervised hierarchical clustering using gene groups suggested by the PANTHER Classification System. We depicted the genomic landscape of the resulted tumor groups by means of Single Nuclear Polymorphism (SNP) technology. Finally, the achieved results were immunohistochemically analyzed using a tissue microarray (TMA) composed of 254 RCC. Results: We found robust, genome wide expression signatures, which split RCC into three distinct molecular subgroups. These groups remained stable even if randomly selected gene sets were clustered. Notably, the pattern obtained from RCC cell lines was clearly distinguishable from that of primary tumors. SNP array analysis demonstrated differing frequencies of chromosomal copy number alterations among RCC subgroups. TMA analysis with group-specific markers showed a prognostic significance of the different groups. Conclusion: We propose the existence of characteristic and histologically independent genome-wide expression outputs in RCC with potential biological and clinical relevance.\"\n", "!Series_overall_design\t\"Expression profiling by array, combined data analysis with genomic profiling data. Genomic DNA from renal cell was hybridized to renal cell carcinoma samples and matched normal kidney tissue biopsies, using the Affymetrix GenomewideSNP_6 platform. CEL files were processed using R, Bioconductor and software from the aroma.affymetrix project. Visualized Copy number profiles are accessible through the Progenetix site (www.progenetix.net). CN,raw.csv and segments.csv: Probes are mapped by their position in genome build 36 / HG18. Probes are ordered according to their linear position on the Golden Path.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['grade: 2', 'grade: 1', 'grade: 3', 'grade: NA', 'cell line: UMRC2', 'cell line: SLR24', 'cell line: A-498', 'cell line: SK-RC52', 'cell line: 786O (vhl19)', 'cell line: UMRC6', 'cell line: ACHN', 'cell line: 786O (vhl30)', 'cell line: A-704', 'cell line: SLR 26', 'cell line: Caki-1', 'cell line: RCC4 (vhl)', 'cell line: 769-P', 'cell line: KC12', 'cell line: RCC4 (neo)', 'cell line: SK-RC29', 'cell line: SW156', 'cell line: SK-RC31', 'cell line: SLR22', 'cell line: SK-RC38', 'cell line: 786-O', 'cell line: SK-RC42', 'cell line: 786O', 'cell line: SLR25', 'cell line: SLR20', 'cell line: Caki-2'], 1: ['stage: 2', 'stage: 1', 'stage: 3', 'stage: NA', 'grade: NA'], 2: ['sample type: neoplasia', 'stage: NA'], 3: ['icd-o 3 code: 8310/3', 'icd-o 3 code: 8317/3', 'icd-o 3 code: 8312/3', 'icd-o 3 code: 8260/3', 'sample type: neoplasia'], 4: ['icd-o 3 diagnosis text: clear cell renal cell carcinoma', 'icd-o 3 diagnosis text: renal cell carcinoma, chromophobe', 'icd-o 3 diagnosis text: renal cell carcinoma', 'icd-o 3 diagnosis text: papillary renal cell carcinoma', 'icd-o 3 code: 8312/3', 'icd-o 3 code: 8140/3'], 5: ['organ site: kidney', 'organ site: kidney [metastasis of RCC to other site]', 'icd-o 3 diagnosis text: renal cell carcinoma', 'icd-o 3 diagnosis text: adenocarcinoma, NOS'], 6: ['gender: male', 'gender: NA', 'gender: female', 'organ site: kidney [cell line]', 'organ site: prostate [cell line]'], 7: ['tissue type: renal cell carcinoma [clear cell RCC]', 'tissue type: renal cell carcinoma [chromophobe RCC]', 'tissue type: renal cell carcinoma [mixed papillary and clear cell RCC]', 'tissue type: renal cell carcinoma [RCC metastasis]', 'tissue type: renal cell carcinoma [papillary RCC]', 'gender: NA', 'gender: male'], 8: ['cluster id: B', 'cluster id: A', 'cluster id: C', 'tissue type: renal cell carcinoma [cell line UMRC2]', 'tissue type: renal cell carcinoma [cell line SLR24]', 'tissue type: renal cell carcinoma [cell line A-498]', 'tissue type: renal cell carcinoma [cell line SK-RC52]', 'tissue type: renal cell carcinoma [cell line 786O (vhl19)]', 'tissue type: renal cell carcinoma [cell line UMRC6]', 'tissue type: renal cell carcinoma [cell line ACHN]', 'tissue type: renal cell carcinoma [cell line 786O (vhl30)]', 'tissue type: renal cell carcinoma [cell line A-704]', 'tissue type: renal cell carcinoma [cell line SLR 26]', 'tissue type: renal cell carcinoma [cell line Caki-1]', 'tissue type: renal cell carcinoma [cell line RCC4 (vhl)]', 'tissue type: renal cell carcinoma [cell line 769-P]', 'tissue type: renal cell carcinoma [cell line KC12]', 'tissue type: renal cell carcinoma [cell line RCC4 (neo)]', 'tissue type: renal cell carcinoma [cell line SK-RC29]', 'tissue type: renal cell carcinoma [cell line SW156]', 'tissue type: renal cell carcinoma [cell line SK-RC31]', 'tissue type: renal cell carcinoma [cell line SLR22]', 'tissue type: renal cell carcinoma [cell line SK-RC38]', 'tissue type: renal cell carcinoma [cell line 786-O]', 'tissue type: renal cell carcinoma [cell line SK-RC42]', 'tissue type: renal cell carcinoma [cell line 786O]', 'tissue type: renal cell carcinoma [cell line SLR25]', 'tissue type: renal cell carcinoma [cell line SLR20]', 'tissue type: renal cell carcinoma [cell line Caki-2]', 'tissue type: renal cell carcinoma [cell line SLR21]'], 9: [nan, 'cluster id: NA']}\n" ] } ], "source": [ "from tools.preprocess import *\n", "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Read the matrix file to obtain background information and sample characteristics data\n", "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n", "print(\"Background Information:\")\n", "print(background_info)\n", "print(\"Sample Characteristics Dictionary:\")\n", "print(sample_characteristics_dict)\n" ] }, { "cell_type": "markdown", "id": "013b91c8", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "2794648f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:15:28.263264Z", "iopub.status.busy": "2025-03-25T07:15:28.263153Z", "iopub.status.idle": "2025-03-25T07:15:28.282891Z", "shell.execute_reply": "2025-03-25T07:15:28.282607Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview:\n", "{}\n", "Clinical data saved to ../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE19949.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this is an \"Expression profiling by array\" study \n", "# that involves renal cell carcinoma samples. The text mentions using Affymetrix platform\n", "# for genomic profiling, which suggests gene expression data is available.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 For the trait (Kidney_Chromophobe):\n", "# Looking at row 4, we can see \"icd-o 3 diagnosis text: renal cell carcinoma, chromophobe\"\n", "# which corresponds to the Kidney_Chromophobe trait\n", "trait_row = 4\n", "\n", "# Define conversion function for trait\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if the value indicates chromophobe RCC\n", " if 'chromophobe' in value.lower():\n", " return 1 # Case: chromophobe RCC\n", " elif 'renal cell carcinoma' in value.lower() or 'rcc' in value.lower():\n", " return 0 # Case: other types of RCC\n", " else:\n", " return None # Unknown or irrelevant value\n", "\n", "# 2.2 For age:\n", "# After reviewing the sample characteristics, there is no indication of age data\n", "age_row = None\n", "\n", "def convert_age(value):\n", " # This function is defined but won't be used as age data is not available\n", " return None\n", "\n", "# 2.3 For gender:\n", "# Gender information is available in row 6\n", "gender_row = 6\n", "\n", "def convert_gender(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert gender to binary\n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " else:\n", " return None # Unknown or NA\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Check if trait data is available\n", "is_trait_available = trait_row is not None\n", "# Validate and save cohort information\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 - Only if trait_row is not None\n", "if trait_row is not None:\n", " # Assuming clinical_data is available from previous steps\n", " try:\n", " # Load clinical data from file\n", " clinical_data = pd.DataFrame()\n", " clinical_data_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('_clinical.txt')]\n", " if clinical_data_files:\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, clinical_data_files[0]), sep='\\t')\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical Data Preview:\")\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 to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error in clinical feature extraction: {e}\")\n", "else:\n", " print(\"Clinical data extraction skipped as trait_row is None\")\n" ] }, { "cell_type": "markdown", "id": "b52ae86f", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "9525682a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:15:28.284018Z", "iopub.status.busy": "2025-03-25T07:15:28.283915Z", "iopub.status.idle": "2025-03-25T07:15:28.760344Z", "shell.execute_reply": "2025-03-25T07:15:28.759975Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene data with 22277 rows\n", "First 20 gene IDs:\n", "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n", " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n", " '1494_f_at', '1598_g_at', '160020_at', '1729_at', '1773_at', '177_at',\n", " '179_at', '1861_at'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 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": "bea6973a", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "210cb713", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:15:28.761625Z", "iopub.status.busy": "2025-03-25T07:15:28.761509Z", "iopub.status.idle": "2025-03-25T07:15:28.763332Z", "shell.execute_reply": "2025-03-25T07:15:28.763062Z" } }, "outputs": [], "source": [ "# These IDs are from Affymetrix probe IDs (e.g., '1007_s_at'), not human gene symbols.\n", "# They need to be mapped to standard gene symbols for biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "8b9e2e20", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "a291cd91", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:15:28.764481Z", "iopub.status.busy": "2025-03-25T07:15:28.764383Z", "iopub.status.idle": "2025-03-25T07:15:39.487113Z", "shell.execute_reply": "2025-03-25T07:15:39.486734Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation data with 5177938 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': [nan, nan, nan, nan, nan], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor family, member 1', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box gene 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001954 /// NM_013993 /// NM_013994', 'NM_002914 /// NM_181471', 'NM_002155 /// XM_001134322', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409'], 'Gene Ontology Biological Process': ['0006468 // protein amino acid phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation', '0006260 // DNA replication // inferred from electronic annotation', '0006457 // protein folding // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0006986 // response to unfolded protein // inferred from electronic annotation', '0001656 // metanephros development // inferred from electronic annotation /// 0006183 // GTP biosynthesis // inferred from electronic annotation /// 0006228 // UTP biosynthesis // inferred from electronic annotation /// 0006241 // CTP biosynthesis // inferred from electronic annotation /// 0006350 // transcription // inferred from electronic annotation /// 0009887 // organ morphogenesis // inferred from electronic annotation /// 0030154 // cell differentiation // inferred from electronic annotation /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from sequence or structural similarity /// 0006355 // regulation of transcription, DNA-dependent // inferred from electronic annotation /// 0007275 // development // inferred from electronic annotation /// 0009653 // morphogenesis // traceable author statement', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // traceable author statement /// 0050896 // response to stimulus // inferred from electronic annotation /// 0007601 // visual perception // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005615 // extracellular space // inferred from electronic annotation /// 0005887 // integral to plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation', '0005634 // nucleus // inferred from electronic annotation /// 0005663 // DNA replication factor C complex // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from electronic annotation', nan, '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005667 // transcription factor complex // inferred from electronic annotation', nan], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004674 // protein serine/threonine kinase activity // inferred from electronic annotation /// 0004713 // protein-tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0004872 // receptor activity // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // traceable author statement /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0003700 // transcription factor activity // traceable author statement /// 0004550 // nucleoside diphosphate kinase activity // inferred from electronic annotation /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from sequence or structural similarity /// 0005524 // ATP binding // inferred from electronic annotation /// 0016563 // transcriptional activator activity // inferred from sequence or structural similarity /// 0003677 // DNA binding // inferred from electronic annotation', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // traceable author statement']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'GB_ACC', 'SPOT_ID', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Target Description', 'Representative Public ID', 'Gene Title', 'Gene Symbol', 'ENTREZ_GENE_ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 5177876 out of 5177938\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: nan\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "8a87123e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "2a3afbcd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:15:39.488691Z", "iopub.status.busy": "2025-03-25T07:15:39.488560Z", "iopub.status.idle": "2025-03-25T07:15:41.366821Z", "shell.execute_reply": "2025-03-25T07:15:41.366252Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping dataframe...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully created gene mapping with 21248 rows\n", "First few rows of mapping dataframe:\n", " ID Gene\n", "0 1007_s_at DDR1\n", "1 1053_at RFC2\n", "2 117_at HSPA6\n", "3 121_at PAX8\n", "4 1255_g_at GUCA1A\n", "\n", "Converting probe measurements to gene expression data...\n", "Successfully converted to gene expression data with 13046 genes\n", "First few gene symbols:\n", "Index(['A2BP1', 'A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAK1',\n", " 'AAMP', 'AANAT'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Kidney_Chromophobe/gene_data/GSE19949.csv\n", "\n", "Gene expression data available: True\n" ] } ], "source": [ "# 1. Identify the columns for gene identifiers and gene symbols in the annotation data\n", "# From the previewed data, we can see 'ID' column contains probe identifiers similar to the gene expression data indices\n", "# and 'Gene Symbol' column contains the corresponding gene symbols\n", "\n", "# 2. Create gene mapping dataframe\n", "print(\"Creating gene mapping dataframe...\")\n", "try:\n", " mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", " print(f\"Successfully created gene mapping with {len(mapping_df)} rows\")\n", " print(\"First few rows of mapping dataframe:\")\n", " print(mapping_df.head())\n", " \n", " # 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", " print(\"\\nConverting probe 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)} genes\")\n", " print(\"First few gene symbols:\")\n", " print(gene_data.index[:10])\n", " \n", " # Save the gene expression data to a 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", " \n", "except Exception as e:\n", " print(f\"Error in gene mapping process: {e}\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "f344ad6c", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "4c6bb9f2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:15:41.368752Z", "iopub.status.busy": "2025-03-25T07:15:41.368619Z", "iopub.status.idle": "2025-03-25T07:15:42.987553Z", "shell.execute_reply": "2025-03-25T07:15:42.987025Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "After normalization: 12700 unique gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Kidney_Chromophobe/gene_data/GSE19949.csv\n", "\n", "Extracting clinical features...\n", "Clinical data shape: (0, 0)\n", "Clinical data columns: []\n", "Clinical data index: []\n", "Clinical data extracted with shape: (2, 0)\n", "Clinical data preview:\n", "{'Kidney_Chromophobe': [], 'Gender': []}\n", "Clinical data saved to ../../output/preprocess/Kidney_Chromophobe/clinical_data/GSE19949.csv\n", "\n", "Linking clinical and genetic data...\n", "Cannot link data: clinical or genetic data is missing/empty\n", "\n", "Performing final validation...\n", "Abnormality detected in the cohort: GSE19949. Preprocessing failed.\n", "A new JSON file was created at: ../../output/preprocess/Kidney_Chromophobe/cohort_info.json\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. Extract clinical features\n", "print(\"\\nExtracting clinical features...\")\n", "try:\n", " # Examine clinical_data structure for debugging\n", " print(\"Clinical data shape:\", clinical_data.shape)\n", " print(\"Clinical data columns:\", clinical_data.columns[:5].tolist())\n", " print(\"Clinical data index:\", clinical_data.index[:5].tolist())\n", " \n", " # Looking at the sample characteristics dictionary from Step 1\n", " # Row 7 contains tissue type with chromophobe RCC information\n", " # Row 6 contains gender information\n", " \n", " trait_row = 7\n", " \n", " def convert_trait(value):\n", " \"\"\"Convert histology information to binary trait (Kidney_Chromophobe)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Check if the value mentions chromophobe kidney cancer\n", " if \"chromophobe\" in value.lower():\n", " return 1\n", " elif \"renal cell carcinoma\" in value.lower() or \"rcc\" in value.lower():\n", " return 0\n", " else:\n", " return None\n", " \n", " gender_row = 6\n", " \n", " def convert_gender(value):\n", " \"\"\"Convert gender information to binary (0=female, 1=male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " value = value.lower()\n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " else:\n", " return None\n", " \n", " # Age not available in this dataset\n", " age_row = None\n", " \n", " def convert_age(value):\n", " return None\n", " \n", " # Extract clinical features\n", " 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", " print(f\"Clinical data extracted with shape: {clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(preview_df(clinical_df.T))\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save clinical data\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " is_trait_available = clinical_df.shape[1] > 0 # Check if we have any samples\n", "except Exception as e:\n", " print(f\"Error extracting clinical features: {e}\")\n", " is_trait_available = False\n", " clinical_df = pd.DataFrame()\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 and clinical_df.shape[1] > 0:\n", " # Print sample IDs from both datasets for debugging\n", " print(\"First few clinical sample columns:\", list(clinical_df.columns)[:5])\n", " print(\"First few genetic sample columns:\", list(normalized_gene_data.columns)[:5])\n", " \n", " # Check if there are common sample IDs\n", " common_samples = set(clinical_df.columns).intersection(set(normalized_gene_data.columns))\n", " print(f\"Number of common samples: {len(common_samples)}\")\n", " \n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\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", " # Check if we still have samples\n", " if linked_data.shape[0] > 0:\n", " # 5. Determine whether 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 remain after handling missing values\")\n", " is_biased = True\n", " else:\n", " print(\"No samples have valid trait values\")\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/empty\")\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", "note = \"Dataset contains kidney tissue samples with chromophobe RCC information in row 7\"\n", "if 'is_biased' not in locals():\n", " is_biased = True\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 if 'linked_data' in locals() and not linked_data.empty else pd.DataFrame(),\n", " note=note\n", ")\n", "\n", "# 7. Save linked data if usable\n", "if is_usable and 'linked_data' in locals() and not linked_data.empty:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " \n", " # Save linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Dataset not usable for {trait} association studies. Data not saved.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }