{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "e53eefff", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:54.230257Z", "iopub.status.busy": "2025-03-25T07:17:54.230075Z", "iopub.status.idle": "2025-03-25T07:17:54.396463Z", "shell.execute_reply": "2025-03-25T07:17:54.396112Z" } }, "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_Clear_Cell_Carcinoma\"\n", "cohort = \"GSE131027\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Clear_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Clear_Cell_Carcinoma/GSE131027\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/GSE131027.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE131027.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/GSE131027.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e0b90cb7", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ad24f28a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:54.397925Z", "iopub.status.busy": "2025-03-25T07:17:54.397772Z", "iopub.status.idle": "2025-03-25T07:17:54.711033Z", "shell.execute_reply": "2025-03-25T07:17:54.710716Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"High frequency of pathogenic germline variants in genes associated with homologous recombination repair in patients with advanced solid cancers\"\n", "!Series_summary\t\"We identified pathogenic and likely pathogenic variants in 17.8% of the patients within a wide range of cancer types. In particular, mesothelioma, ovarian cancer, cervical cancer, urothelial cancer, and cancer of unknown primary origin displayed high frequencies of pathogenic variants. In total, 22 BRCA1 and BRCA2 germline variant were identified in 12 different cancer types, of which 10 (45%) variants were not previously identified in these patients. Pathogenic germline variants were predominantly found in DNA repair pathways; approximately half of the variants were within genes involved in homologous recombination repair. Loss of heterozygosity and somatic second hits were identified in several of these genes, supporting possible causality for cancer development. A potential treatment target based on pathogenic germline variant could be suggested in 25 patients (4%).\"\n", "!Series_overall_design\t\"investigation of expression features related to Class 4 and 5 germline mutations in cancer patients\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: tumor biopsy'], 1: ['cancer: Breast cancer', 'cancer: Colorectal cancer', 'cancer: Bile duct cancer', 'cancer: Mesothelioma', 'cancer: Urothelial cancer', 'cancer: Pancreatic cancer', 'cancer: Melanoma', 'cancer: Hepatocellular carcinoma', 'cancer: Ovarian cancer', 'cancer: Cervical cancer', 'cancer: Head and Neck cancer', 'cancer: Sarcoma', 'cancer: Prostate cancer', 'cancer: Adenoid cystic carcinoma', 'cancer: NSCLC', 'cancer: Oesophageal cancer', 'cancer: Thymoma', 'cancer: Others', 'cancer: CUP', 'cancer: Renal cell carcinoma', 'cancer: Gastric cancer', 'cancer: Neuroendocrine cancer', 'cancer: vulvovaginal'], 2: ['mutated gene: ATR', 'mutated gene: FAN1', 'mutated gene: ERCC3', 'mutated gene: FANCD2', 'mutated gene: BAP1', 'mutated gene: DDB2', 'mutated gene: TP53', 'mutated gene: ATM', 'mutated gene: CHEK1', 'mutated gene: BRCA1', 'mutated gene: WRN', 'mutated gene: CHEK2', 'mutated gene: BRCA2', 'mutated gene: XPC', 'mutated gene: PALB2', 'mutated gene: ABRAXAS1', 'mutated gene: NBN', 'mutated gene: BLM', 'mutated gene: FAM111B', 'mutated gene: FANCA', 'mutated gene: MLH1', 'mutated gene: BRIP1', 'mutated gene: IPMK', 'mutated gene: RECQL', 'mutated gene: RAD50', 'mutated gene: FANCM', 'mutated gene: GALNT12', 'mutated gene: SMAD9', 'mutated gene: ERCC2', 'mutated gene: FANCC'], 3: ['predicted: HRDEXP: HRD', 'predicted: HRDEXP: NO_HRD'], 4: ['parp predicted: kmeans-2: PARP sensitive', 'parp predicted: kmeans-2: PARP insensitive']}\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": "6663b4ee", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b8d8d531", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:54.712420Z", "iopub.status.busy": "2025-03-25T07:17:54.712301Z", "iopub.status.idle": "2025-03-25T07:17:54.720821Z", "shell.execute_reply": "2025-03-25T07:17:54.720554Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{1: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/GSE131027.csv\n" ] } ], "source": [ "# Analyzing the dataset information\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series title and overall design mentioning \"expression features\",\n", "# this dataset likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# Looking for trait related to Kidney Clear Cell Carcinoma\n", "trait_row = 1 # The row with 'cancer' types includes 'Renal cell carcinoma' which is equivalent to Kidney Clear Cell Carcinoma\n", "age_row = None # No age information is available in the sample characteristics\n", "gender_row = None # No gender information is available in the sample characteristics\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(trait_value):\n", " \"\"\"Convert trait value to binary format (0 for non-KCCC, 1 for KCCC)\"\"\"\n", " if trait_value is None:\n", " return None\n", " # Extract the value after the colon\n", " if ':' in trait_value:\n", " trait_value = trait_value.split(':', 1)[1].strip()\n", " # Match 'Renal cell carcinoma' as a positive case for Kidney Clear Cell Carcinoma\n", " if 'Renal cell carcinoma' in trait_value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(age_value):\n", " \"\"\"Convert age value to continuous format\"\"\"\n", " # This function won't be used since age data is not available\n", " if age_value is None:\n", " return None\n", " if ':' in age_value:\n", " age_value = age_value.split(':', 1)[1].strip()\n", " try:\n", " return float(age_value)\n", " except:\n", " return None\n", "\n", "def convert_gender(gender_value):\n", " \"\"\"Convert gender value to binary format (0 for female, 1 for male)\"\"\"\n", " # This function won't be used since gender data is not available\n", " if gender_value is None:\n", " return None\n", " if ':' in gender_value:\n", " gender_value = gender_value.split(':', 1)[1].strip().lower()\n", " if gender_value in ['female', 'f']:\n", " return 0\n", " elif gender_value in ['male', 'm']:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering\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", "# Only proceed if trait data is available\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary\n", " # The sample characteristics dictionary is from the previous step output\n", " sample_char_dict = {0: ['tissue: tumor biopsy'], \n", " 1: ['cancer: Breast cancer', 'cancer: Colorectal cancer', 'cancer: Bile duct cancer', \n", " 'cancer: Mesothelioma', 'cancer: Urothelial cancer', 'cancer: Pancreatic cancer', \n", " 'cancer: Melanoma', 'cancer: Hepatocellular carcinoma', 'cancer: Ovarian cancer', \n", " 'cancer: Cervical cancer', 'cancer: Head and Neck cancer', 'cancer: Sarcoma', \n", " 'cancer: Prostate cancer', 'cancer: Adenoid cystic carcinoma', 'cancer: NSCLC', \n", " 'cancer: Oesophageal cancer', 'cancer: Thymoma', 'cancer: Others', 'cancer: CUP', \n", " 'cancer: Renal cell carcinoma', 'cancer: Gastric cancer', \n", " 'cancer: Neuroendocrine cancer', 'cancer: vulvovaginal'], \n", " 2: ['mutated gene: ATR', 'mutated gene: FAN1', 'mutated gene: ERCC3', 'mutated gene: FANCD2', \n", " 'mutated gene: BAP1', 'mutated gene: DDB2', 'mutated gene: TP53', 'mutated gene: ATM', \n", " 'mutated gene: CHEK1', 'mutated gene: BRCA1', 'mutated gene: WRN', 'mutated gene: CHEK2', \n", " 'mutated gene: BRCA2', 'mutated gene: XPC', 'mutated gene: PALB2', 'mutated gene: ABRAXAS1', \n", " 'mutated gene: NBN', 'mutated gene: BLM', 'mutated gene: FAM111B', 'mutated gene: FANCA', \n", " 'mutated gene: MLH1', 'mutated gene: BRIP1', 'mutated gene: IPMK', 'mutated gene: RECQL', \n", " 'mutated gene: RAD50', 'mutated gene: FANCM', 'mutated gene: GALNT12', 'mutated gene: SMAD9', \n", " 'mutated gene: ERCC2', 'mutated gene: FANCC'], \n", " 3: ['predicted: HRDEXP: HRD', 'predicted: HRDEXP: NO_HRD'], \n", " 4: ['parp predicted: kmeans-2: PARP sensitive', 'parp predicted: kmeans-2: PARP insensitive']}\n", " \n", " # Convert the dictionary to a pandas DataFrame format that geo_select_clinical_features can process\n", " # Create empty rows for each sample\n", " samples = []\n", " for cancer_type in sample_char_dict[trait_row]:\n", " sample = {}\n", " sample[trait_row] = cancer_type\n", " samples.append(sample)\n", " \n", " clinical_data = pd.DataFrame(samples)\n", " \n", " # Extract and process 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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Preview the processed dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the processed clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "2226a93e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "f5a5b947", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:54.721911Z", "iopub.status.busy": "2025-03-25T07:17:54.721805Z", "iopub.status.idle": "2025-03-25T07:17:55.255194Z", "shell.execute_reply": "2025-03-25T07:17:55.254826Z" } }, "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 54675 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', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',\n", " '1552263_at', '1552264_a_at', '1552266_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": "6412f261", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3c8a114a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:55.256562Z", "iopub.status.busy": "2025-03-25T07:17:55.256433Z", "iopub.status.idle": "2025-03-25T07:17:55.258405Z", "shell.execute_reply": "2025-03-25T07:17:55.258103Z" } }, "outputs": [], "source": [ "# The gene identifiers observed in the gene expression data (like '1007_s_at', '1053_at', etc.)\n", "# appear to be Affymetrix probe IDs from a microarray platform, not human gene symbols.\n", "# These identifiers need to be mapped to standard gene symbols for meaningful analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "25bd9b8f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "0801282b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:55.259647Z", "iopub.status.busy": "2025-03-25T07:17:55.259541Z", "iopub.status.idle": "2025-03-25T07:18:03.421614Z", "shell.execute_reply": "2025-03-25T07:18:03.421276Z" } }, "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 5084867 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': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], '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 tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // 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 // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\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: 5084805 out of 5084867\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": "26a27409", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "113bb4b5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:03.422959Z", "iopub.status.busy": "2025-03-25T07:18:03.422829Z", "iopub.status.idle": "2025-03-25T07:18:05.148048Z", "shell.execute_reply": "2025-03-25T07:18:05.147649Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using probe column: 'ID' and gene symbol column: 'Gene Symbol'\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene mapping dataframe created with 45782 rows\n", "First few rows of gene mapping:\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'Gene': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A']}\n", "\n", "Applying gene mapping to convert probe data to gene expression data...\n", "Gene expression data created with 21278 unique genes\n", "First few gene symbols and sample columns:\n", "{'GSM3759992': [4.390919088, 4.498580122, 7.712909389, 14.491903516, 6.186830839], 'GSM3759993': [9.637093765, 4.911001093, 17.768013934, 16.222561284999998, 4.286040695], 'GSM3759994': [5.370775767, 4.409248332, 8.704945831, 15.166473245, 5.067773944], 'GSM3759995': [7.376018685, 4.958839994, 14.905013256, 15.598187591999999, 5.807062391], 'GSM3759996': [9.74745451, 4.12673215, 16.923252481, 15.317524529, 3.963854128], 'GSM3759997': [7.568073556, 5.894117526, 7.351391774, 14.574576716, 3.236874339], 'GSM3759998': [12.62778479, 4.571267834, 21.82809339, 17.392582999, 4.999760334], 'GSM3759999': [12.22717927, 4.925716874, 20.830583609, 17.035321453, 5.26134909], 'GSM3760000': [7.0424374, 4.390274455, 17.073983362, 13.785204266000001, 3.467432166], 'GSM3760001': [5.118174974, 4.578438532, 8.206697550000001, 15.715598135, 4.919674419], 'GSM3760002': [11.6638925, 4.292203932, 21.88066249, 16.553031539, 5.647762881], 'GSM3760003': [8.753595304, 4.415164538, 18.97417678, 16.878419546, 4.062729613], 'GSM3760004': [6.753561783, 5.262373488, 9.007149555, 13.509853516, 3.391483538], 'GSM3760005': [7.372395801, 5.181837968, 7.278802399, 16.933670614, 6.082005165], 'GSM3760006': [4.678157288, 4.396660975, 17.257719003000002, 15.423354391, 4.082916483], 'GSM3760007': [5.50296512, 4.539191797, 8.247180844999999, 17.224151001, 5.455018603], 'GSM3760008': [7.612056724, 4.993062606, 11.55378582, 14.188758691, 3.78089867], 'GSM3760009': [4.757200894, 5.055575441, 7.394558438000001, 12.443661113000001, 3.164630026], 'GSM3760010': [9.840923351, 4.657771502, 17.408444777, 15.696909766, 4.011686377], 'GSM3760011': [11.6221084, 4.140940733, 19.803169658, 17.503901714999998, 4.051300989], 'GSM3760012': [5.343630121, 4.368135959, 8.059393061, 14.423819356, 3.491124072], 'GSM3760013': [10.90520832, 4.537205755, 17.934721304, 15.527480285000001, 4.629277475], 'GSM3760014': [6.520046737, 4.612519369, 12.612512722, 13.964957214000002, 4.749371842], 'GSM3760015': [6.063488614, 4.613452014, 7.967249346000001, 14.425833706999999, 4.444007951], 'GSM3760016': [4.776125676, 4.492444981, 8.380000146, 15.799214865, 4.374293335], 'GSM3760017': [5.198930136, 4.635564255, 14.122622596, 14.254736216000001, 4.409477318], 'GSM3760018': [4.944523261, 4.750620131, 13.981686813, 13.220598085999999, 3.627491698], 'GSM3760019': [6.440924299, 4.730007477, 7.764874793000001, 14.857515339, 5.964286145], 'GSM3760020': [7.559469283, 5.236666726, 6.8281696599999995, 15.835042604999998, 5.792742593], 'GSM3760021': [5.298998696, 4.473200437, 8.062953108999999, 15.287922627, 6.112863262], 'GSM3760022': [6.814713151, 4.884057988, 9.486789199, 14.439356905, 4.410392985], 'GSM3760023': [6.779944088, 4.695987718, 7.887927809, 15.279319023, 4.819054706], 'GSM3760024': [5.635778394, 4.69616513, 8.314896747999999, 15.118010428, 4.715675846], 'GSM3760025': [6.722314572, 4.994652493, 7.640643408, 14.714635448, 4.377692911], 'GSM3760026': [6.130858567, 5.232790107, 7.539897679, 14.412475553, 4.064515428], 'GSM3760027': [6.612860418, 4.789916385, 7.536000756, 15.948411010000001, 5.54127374], 'GSM3760028': [4.976853888, 4.557117841, 7.549768355, 16.504380481, 5.529147761], 'GSM3760029': [10.87365811, 4.427287583, 18.582049307, 15.575506151, 3.849106027], 'GSM3760030': [6.06517596, 4.26419316, 7.973723598, 14.608208863, 4.026820621], 'GSM3760031': [12.01693841, 4.81187304, 21.55539494, 16.684636003, 4.738793827], 'GSM3760032': [6.033680922, 4.589327396, 8.450025799, 14.304476338, 3.971825265], 'GSM3760033': [12.22210557, 4.963286055, 22.43753379, 17.516572132, 4.936868656], 'GSM3760034': [11.31216016, 4.562068184, 17.72674382, 15.492935246000002, 4.999827823], 'GSM3760035': [7.361448591, 4.916437089, 7.205318161999999, 15.026405977, 4.429600105], 'GSM3760036': [12.39704418, 4.800305174, 20.100568629, 16.909587482, 5.103344247], 'GSM3760037': [9.946932309, 4.71973062, 17.082584639, 14.856362933, 4.999326024], 'GSM3760038': [6.184998138, 4.888675652, 7.395957425, 14.359517307, 5.196275297], 'GSM3760039': [8.206726944, 5.124415651, 8.001030515, 15.012661494, 4.088909659], 'GSM3760040': [6.134298746, 4.891833228, 7.6642790970000005, 14.290372786999999, 4.126884502], 'GSM3760041': [11.97993583, 4.212034452, 21.446551545, 16.764575578, 4.92497363], 'GSM3760042': [11.33419912, 4.108014446, 19.121283617, 16.954032604, 5.583980471], 'GSM3760043': [12.10786449, 4.643435255, 21.459385941, 17.150206531, 6.370548075], 'GSM3760044': [10.16274058, 4.033453872, 15.451567338, 14.790556379, 4.238499435], 'GSM3760045': [4.925323985, 4.058804582, 7.830816329000001, 14.030913338, 4.050689443], 'GSM3760046': [9.917466636, 4.346318318, 17.252199694, 14.686365504, 4.374118532], 'GSM3760047': [6.359462704, 5.104049639, 7.522744846, 13.665420343000001, 6.359734814], 'GSM3760048': [9.642436559, 4.883397019, 15.891001754000001, 17.001422807, 5.757429201], 'GSM3760049': [6.322108617, 4.59049491, 10.434122015, 13.529462626, 3.739439145], 'GSM3760050': [5.896488646, 4.163935808, 15.32063857, 14.310919961, 4.660358243], 'GSM3760051': [8.690878181, 4.943526274, 7.399347858, 14.18839404, 4.325759531], 'GSM3760052': [6.719934755, 4.553404903, 8.344314308, 14.862578893, 4.076985925], 'GSM3760053': [6.753424009, 4.752051635, 7.489790494, 14.450500616, 4.270951624], 'GSM3760054': [6.481343265, 4.804195372, 8.401573825, 15.988619816, 4.75192262], 'GSM3760055': [9.039746902, 4.49380227, 12.779113128999999, 16.218840482, 5.821574074], 'GSM3760056': [11.97152054, 4.399796987, 20.589787632, 16.005875422, 4.624760532], 'GSM3760057': [9.614237684, 4.569721604, 15.391983751, 15.016042541, 4.43152731], 'GSM3760058': [11.69690458, 4.476563755, 21.069629925, 16.647703093, 4.54615484], 'GSM3760059': [9.979779858, 4.159365691, 16.144414801, 15.880153745000001, 4.554688021], 'GSM3760060': [7.449754311, 5.055796513, 7.632118716, 14.310842709000001, 4.5988394], 'GSM3760061': [7.315180614, 5.212372158, 8.103036536, 16.975554945, 5.693855614], 'GSM3760062': [7.919369772, 4.19565724, 15.307241173, 13.503286164999999, 3.015975679], 'GSM3760063': [10.62984721, 4.639352752, 17.295163107, 15.362220161, 4.182993556], 'GSM3760064': [5.292380846, 4.467554337, 7.6066483090000006, 15.268422785, 3.801050902], 'GSM3760065': [6.304828827, 4.182044319, 7.924505366, 15.262218320999999, 4.388536469], 'GSM3760066': [5.619002898, 4.570622508, 8.397898810000001, 13.046332794000001, 3.800689392], 'GSM3760067': [10.53332282, 4.173174845, 18.780033077, 15.617544327, 4.154647416], 'GSM3760068': [5.591603732, 4.533261003, 12.024590037, 15.377985898, 4.879588405], 'GSM3760069': [10.51823124, 4.254397467, 17.07976892, 15.539807542999998, 4.223450907], 'GSM3760070': [8.896639791, 4.503023106, 14.519950322, 15.364241165, 4.193270597], 'GSM3760071': [5.218892313, 4.662084014, 7.553470038, 14.202493314999998, 3.633668735], 'GSM3760072': [7.233475904, 4.897697478, 7.605860487999999, 16.799253163, 6.334570487], 'GSM3760073': [10.14648768, 4.610247553, 17.832109909, 16.219394241, 5.174279055], 'GSM3760074': [4.466207441, 4.479958298, 8.096754477, 15.257647146, 5.474941323], 'GSM3760075': [6.302002334, 4.533261003, 8.508394175, 15.290760104, 4.403670274], 'GSM3760076': [4.770781448, 4.303739861, 7.585602558, 14.182057384, 4.141436715], 'GSM3760077': [6.557400994, 4.149872717, 9.130103723, 13.469336613, 3.626900854], 'GSM3760078': [10.95756244, 4.59027901, 18.034938907, 15.873611819, 4.69939363], 'GSM3760079': [4.419245647, 4.394308466, 8.542182366, 15.869546633, 5.321576225], 'GSM3760080': [11.36776252, 4.395192478, 20.746133643, 16.443654531, 4.664824216], 'GSM3760081': [11.85847631, 4.476915924, 20.372914311, 16.54085, 4.925050241], 'GSM3760082': [7.161333705, 4.426793432, 13.245911376, 13.29739341, 3.684124296], 'GSM3760083': [5.668884317, 4.243666129, 14.530918103000001, 13.946795727000001, 3.294243749]}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE131027.csv\n" ] } ], "source": [ "# 1. Identify the columns for probe ID and gene symbol in the gene annotation data\n", "# Based on the preview, we need the 'ID' column for probe identifiers and 'Gene Symbol' for gene symbols\n", "probe_col = 'ID' # Column containing probe IDs matching gene expression data\n", "gene_symbol_col = 'Gene Symbol' # Column containing the gene symbols we want to map to\n", "\n", "print(f\"Using probe column: '{probe_col}' and gene symbol column: '{gene_symbol_col}'\")\n", "\n", "# 2. Create a mapping dataframe with the probe IDs and gene symbols\n", "try:\n", " # Use the helper function to extract the mapping from the annotation dataframe\n", " gene_mapping = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)\n", " \n", " # Preview the mapping dataframe\n", " print(f\"\\nGene mapping dataframe created with {len(gene_mapping)} rows\")\n", " print(\"First few rows of gene mapping:\")\n", " print(preview_df(gene_mapping))\n", " \n", " # 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", " # This handles probes mapping to multiple genes by dividing expression and summing by gene\n", " print(\"\\nApplying gene mapping to convert probe data to gene expression data...\")\n", " gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)\n", " \n", " # Preview the resulting gene expression data\n", " print(f\"Gene expression data created with {len(gene_data.index)} unique genes\")\n", " print(\"First few gene symbols and sample columns:\")\n", " print(preview_df(gene_data))\n", " \n", " # Save the gene expression data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Gene expression data saved to {out_gene_data_file}\")\n", "\n", "except Exception as e:\n", " print(f\"Error in gene mapping process: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "b62cf1a1", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "4523511a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:05.149433Z", "iopub.status.busy": "2025-03-25T07:18:05.149303Z", "iopub.status.idle": "2025-03-25T07:18:06.472534Z", "shell.execute_reply": "2025-03-25T07:18:06.472144Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "After normalization: 19845 unique gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE131027.csv\n", "\n", "Checking trait availability from previous analysis...\n", "Loaded clinical data with shape: (1, 1)\n", "Renamed column '1' to 'Kidney_Clear_Cell_Carcinoma'\n", "\n", "Linking clinical and genetic data...\n", "Clinical columns: ['Kidney_Clear_Cell_Carcinoma']\n", "First few genetic sample columns: ['GSM3759992', 'GSM3759993', 'GSM3759994', 'GSM3759995', 'GSM3759996']\n", "Transposed clinical data to shape: (1, 1)\n", "Linked data shape: (93, 19846)\n", "Number of samples with trait values: 1\n", "\n", "Handling missing values...\n", "After handling missing values, data shape: (0, 1)\n", "Error: All samples were removed during missing value handling.\n", "\n", "Performing final validation...\n", "Abnormality detected in the cohort: GSE131027. Preprocessing failed.\n", "Dataset not usable for Kidney_Clear_Cell_Carcinoma association studies. Data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "try:\n", " # Check if gene_data is empty before normalization\n", " if gene_data.empty:\n", " print(\"Gene data is empty. Skipping normalization.\")\n", " normalized_gene_data = gene_data\n", " else:\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 (even if empty, to maintain consistent workflow)\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", "# Use is_trait_available from previous steps, don't recheck trait_row\n", "print(\"\\nChecking trait availability from previous analysis...\")\n", "# Load the clinical data from the previously saved file\n", "try:\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " # Rename the column '1' to the trait name if it exists\n", " if '1' in clinical_df.columns:\n", " clinical_df = clinical_df.rename(columns={'1': trait})\n", " print(f\"Renamed column '1' to '{trait}'\")\n", " is_trait_available = trait in clinical_df.columns\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " clinical_df = pd.DataFrame()\n", " is_trait_available = False\n", "\n", "# 2. Link clinical and genetic data if available\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if is_trait_available and not normalized_gene_data.empty:\n", " # Print sample IDs from both datasets for debugging\n", " print(\"Clinical columns:\", list(clinical_df.columns))\n", " print(\"First few genetic sample columns:\", list(normalized_gene_data.columns)[:5])\n", " \n", " # Transpose clinical data so samples are rows\n", " if clinical_df.shape[0] == 1: # If it's currently 1 row with samples as columns\n", " clinical_df = clinical_df.T\n", " clinical_df.columns = [trait]\n", " print(f\"Transposed clinical data to shape: {clinical_df.shape}\")\n", " \n", " # Now link clinical and genetic data\n", " linked_data = pd.concat([clinical_df, normalized_gene_data.T], axis=1)\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", " # 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\"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", " if not is_trait_available:\n", " print(f\"Reason: Trait column '{trait}' is not available in clinical data.\")\n", " if normalized_gene_data.empty:\n", " print(\"Reason: Gene expression data is 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", "# 5. Final quality validation\n", "print(\"\\nPerforming final validation...\")\n", "note = \"\"\n", "if 'linked_data' in locals() and linked_data.empty:\n", " if not normalized_gene_data.empty and not clinical_df.empty:\n", " note = \"Dataset failed in linking phase. Clinical data structure could not be properly matched with gene expression data.\"\n", " elif normalized_gene_data.empty:\n", " note = \"Dataset failed in gene mapping phase. Could not properly map probe IDs to gene symbols.\"\n", " elif clinical_df.empty:\n", " note = \"Dataset failed in clinical data extraction. No valid trait information available.\"\n", "elif 'is_biased' in locals() and is_biased:\n", " note = \"Dataset passed initial processing but contains severely biased trait distribution.\"\n", "\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=not normalized_gene_data.empty, # Set based on actual gene data availability\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 }