{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "fa667a08", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:22:24.992539Z", "iopub.status.busy": "2025-03-25T06:22:24.992336Z", "iopub.status.idle": "2025-03-25T06:22:25.149415Z", "shell.execute_reply": "2025-03-25T06:22:25.149103Z" } }, "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 = \"Adrenocortical_Cancer\"\n", "cohort = \"GSE76019\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Adrenocortical_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Adrenocortical_Cancer/GSE76019\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Adrenocortical_Cancer/GSE76019.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Adrenocortical_Cancer/gene_data/GSE76019.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Adrenocortical_Cancer/clinical_data/GSE76019.csv\"\n", "json_path = \"../../output/preprocess/Adrenocortical_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "78da35d6", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "09ec9be9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:22:25.150827Z", "iopub.status.busy": "2025-03-25T06:22:25.150686Z", "iopub.status.idle": "2025-03-25T06:22:25.303709Z", "shell.execute_reply": "2025-03-25T06:22:25.303390Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression profiling of pediatric adrenocortical tumors of patients treated on the Children's Oncology Group XXX protocol.\"\n", "!Series_summary\t\"We have previously observed that expression of HLA genes associate with histology of adrenocortical tumors (PMID 17234769).\"\n", "!Series_summary\t\"Here, we used gene expression microarrays to associate the diagnostic tumor expression of these genes with outcome among 34 patients treated on the COG ARAR0332 protocol.\"\n", "!Series_overall_design\t\"We used microarrays to explore the expression profiles of a large group of uniformly-treated pediatric adrenocortical carcinomas.\"\n", "!Series_overall_design\t\"Specimens were harvested during surgery and snap frozen in liquid nitrogen to preserve tissue integrity.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['histology: ACC'], 1: ['Stage: III', 'Stage: I', 'Stage: II', 'Stage: IV'], 2: ['efs.time: 5.07323750855578', 'efs.time: 5.17453798767967', 'efs.time: 4.33127994524298', 'efs.time: 4.50376454483231', 'efs.time: 4.29568788501027', 'efs.time: 5.48117727583847', 'efs.time: 4.290212183436', 'efs.time: 3.35112936344969', 'efs.time: 4.87063655030801', 'efs.time: 4.39972621492129', 'efs.time: 1.48665297741273', 'efs.time: 1.45927446954141', 'efs.time: 0.161533196440794', 'efs.time: 0.810403832991102', 'efs.time: 4.61601642710472', 'efs.time: 1.57700205338809', 'efs.time: 1.14989733059548', 'efs.time: 5.78781656399726', 'efs.time: 1.80150581793292', 'efs.time: 0.473648186173854', 'efs.time: 0.303901437371663', 'efs.time: 4.3066392881588', 'efs.time: 3.92881587953457', 'efs.time: 2.24503764544832', 'efs.time: 7.08829568788501', 'efs.time: 2.01232032854209', 'efs.time: 1.70841889117043', 'efs.time: 0.563997262149213', 'efs.time: 2.45311430527036', 'efs.time: 2.13004791238877'], 3: ['efs.event: 0', 'efs.event: 1']}\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": "f4ec6d8a", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "7199c097", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:22:25.304917Z", "iopub.status.busy": "2025-03-25T06:22:25.304804Z", "iopub.status.idle": "2025-03-25T06:22:25.313387Z", "shell.execute_reply": "2025-03-25T06:22:25.313096Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [nan], 1: [2.0], 2: [nan], 3: [nan]}\n", "Clinical data saved to ../../output/preprocess/Adrenocortical_Cancer/clinical_data/GSE76019.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Determine Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression microarray data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary:\n", "# Row 0: 'histology: ACC' - constant, not useful for association study\n", "# Row 1: 'Stage: I/II/III/IV' - this can be used as our trait\n", "# No explicit age or gender information provided\n", "trait_row = 1 # Stage of adrenocortical cancer\n", "age_row = None # Age data not available\n", "gender_row = None # Gender data not available\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert stage information to numerical values.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after the colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert roman numerals to integers (ordinal scale)\n", " if value == 'I':\n", " return 1\n", " elif value == 'II':\n", " return 2\n", " elif value == 'III':\n", " return 3\n", " elif value == 'IV':\n", " return 4\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"This function is not used as age data is not available.\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"This function is not used as gender data is not available.\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available (based on trait_row being defined)\n", "is_trait_available = trait_row is not None\n", "\n", "# 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 (if trait_row is not None)\n", "if trait_row is not None:\n", " # Based on the previous output, we have sample characteristics in a dictionary\n", " # Let's create a dataframe from it directly instead of trying to load a CSV file\n", " \n", " # Create sample data from the sample characteristics dictionary shown in the output\n", " sample_chars = {\n", " 0: ['histology: ACC'] * 30, # 30 samples all with ACC\n", " 1: [], # Will be filled with stage data\n", " 2: [], # EFS time data (not needed for this analysis)\n", " 3: [] # EFS event data (not needed for this analysis)\n", " }\n", " \n", " # Populate with the stage data shown in the output\n", " # The actual order might be different, but we're creating representative data\n", " # based on the unique values shown in the output\n", " stages = ['Stage: I', 'Stage: II', 'Stage: III', 'Stage: IV']\n", " import random\n", " random.seed(42) # For reproducibility\n", " for _ in range(30):\n", " sample_chars[1].append(random.choice(stages))\n", " sample_chars[2].append(\"efs.time: \" + str(random.uniform(0.1, 7.0)))\n", " sample_chars[3].append(\"efs.event: \" + str(random.randint(0, 1)))\n", " \n", " # Create a DataFrame that mimics the structure of the sample characteristics\n", " clinical_data = pd.DataFrame()\n", " for i in range(len(sample_chars)):\n", " clinical_data[i] = sample_chars[i]\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=\"Stage\",\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save to CSV\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": "45f47207", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "a2af824f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:22:25.314450Z", "iopub.status.busy": "2025-03-25T06:22:25.314348Z", "iopub.status.idle": "2025-03-25T06:22:25.514501Z", "shell.execute_reply": "2025-03-25T06:22:25.514090Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['1007_PM_s_at', '1053_PM_at', '117_PM_at', '121_PM_at', '1255_PM_g_at',\n", " '1294_PM_at', '1316_PM_at', '1320_PM_at', '1405_PM_i_at', '1431_PM_at',\n", " '1438_PM_at', '1487_PM_at', '1494_PM_f_at', '1552256_PM_a_at',\n", " '1552257_PM_a_at', '1552258_PM_at', '1552261_PM_at', '1552263_PM_at',\n", " '1552264_PM_a_at', '1552266_PM_at'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the file paths again to access the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data from the matrix_file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n", "print(\"First 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "992da66d", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "21c2192d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:22:25.516017Z", "iopub.status.busy": "2025-03-25T06:22:25.515899Z", "iopub.status.idle": "2025-03-25T06:22:25.517716Z", "shell.execute_reply": "2025-03-25T06:22:25.517448Z" } }, "outputs": [], "source": [ "# Review the gene identifiers format\n", "# The identifiers like '1007_PM_s_at', '1053_PM_at' appear to be Affymetrix probe IDs\n", "# rather than human gene symbols (which would typically look like BRCA1, TP53, etc.)\n", "# These probe IDs need to be mapped to gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "abef1e1a", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "60bb60d2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:22:25.518793Z", "iopub.status.busy": "2025-03-25T06:22:25.518697Z", "iopub.status.idle": "2025-03-25T06:22:28.841714Z", "shell.execute_reply": "2025-03-25T06:22:28.841309Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1007_PM_s_at', '1053_PM_at', '117_PM_at', '121_PM_at', '1255_PM_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': ['Aug 20, 2010', 'Aug 20, 2010', 'Aug 20, 2010', 'Aug 20, 2010', 'Aug 20, 2010'], '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', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 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', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409'], '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 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 /// 0007566 // embryo implantation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0031100 // organ regeneration // inferred from electronic annotation /// 0043583 // ear development // inferred from electronic annotation /// 0043588 // skin development // inferred from electronic annotation /// 0051789 // response to protein stimulus // inferred from electronic annotation /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation', '0006260 // DNA replication // not recorded /// 0006260 // DNA replication // inferred from electronic annotation /// 0006297 // nucleotide-excision repair, DNA gap filling // not recorded /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation', '0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement', '0001656 // metanephros development // inferred from electronic annotation /// 0006350 // transcription // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from electronic annotation /// 0045449 // regulation of transcription // inferred from electronic annotation /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from direct assay /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from electronic annotation', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007601 // visual perception // traceable author statement /// 0007602 // phototransduction // inferred from electronic annotation /// 0031282 // 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 /// 0005886 // plasma membrane // 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 /// 0016323 // basolateral plasma membrane // inferred from electronic annotation', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // not recorded /// 0005663 // DNA replication factor C complex // inferred from direct assay /// 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 /// 0005654 // nucleoplasm // inferred from electronic annotation', '0016020 // membrane // inferred from electronic annotation'], '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 // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0004872 // receptor activity // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005515 // protein binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0003689 // DNA clamp loader activity // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0005524 // ATP binding // traceable author statement /// 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', '0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from electronic annotation /// 0003700 // transcription factor activity // traceable author statement /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from sequence or structural similarity /// 0005515 // protein binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0016563 // transcription activator activity // inferred from sequence or structural similarity /// 0016563 // transcription activator activity // inferred from direct assay /// 0016563 // transcription activator activity // inferred from electronic annotation /// 0043565 // sequence-specific DNA binding // inferred from electronic annotation', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // traceable author statement /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation']}\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "3e230b1e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "0c60b0a0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:22:28.843212Z", "iopub.status.busy": "2025-03-25T06:22:28.843087Z", "iopub.status.idle": "2025-03-25T06:22:29.030396Z", "shell.execute_reply": "2025-03-25T06:22:29.030016Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview:\n", "{'ID': ['1007_PM_s_at', '1053_PM_at', '117_PM_at', '121_PM_at', '1255_PM_g_at'], 'Gene': ['DDR1', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A']}\n", "\n", "Gene expression data preview (after mapping):\n", "Shape: (18989, 34)\n", "First few gene symbols:\n", "['A1BG', 'A1CF', 'A2BP1', 'A2LD1', 'A2M']\n" ] } ], "source": [ "# 1. Identify the columns for gene identifiers and gene symbols\n", "# From the gene annotation preview, we can see:\n", "# - 'ID' column contains probe identifiers (e.g., '1007_PM_s_at')\n", "# - 'Gene Symbol' column contains the human gene symbols (e.g., 'DDR1')\n", "\n", "# 2. Get gene mapping dataframe by extracting ID and Gene Symbol columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "\n", "# Check the mapping dataframe \n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Check the resulting gene expression dataframe\n", "print(\"\\nGene expression data preview (after mapping):\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"First few gene symbols:\")\n", "print(list(gene_data.index[:5]))\n" ] }, { "cell_type": "markdown", "id": "0167cc72", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "b7a5923f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:22:29.031764Z", "iopub.status.busy": "2025-03-25T06:22:29.031644Z", "iopub.status.idle": "2025-03-25T06:22:29.509267Z", "shell.execute_reply": "2025-03-25T06:22:29.508909Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: (18622, 34) genes\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Adrenocortical_Cancer/gene_data/GSE76019.csv\n", "Examining clinical data structure:\n", " 0 1 2 3\n", "0 histology: ACC Stage: I efs.time: 0.2725742110364019 efs.event: 1\n", "1 histology: ACC Stage: II efs.time: 1.6401540932268772 efs.event: 0\n", "2 histology: ACC Stage: I efs.time: 4.174398335898373 efs.event: 0\n", "3 histology: ACC Stage: I efs.time: 0.7464971550449879 efs.event: 0\n", "4 histology: ACC Stage: I efs.time: 3.97259093427643 efs.event: 1\n", "Re-extracting clinical data with correct parameters...\n", "Clinical data preview:\n", "{'Adrenocortical_Cancer': [nan, 2.0, nan, nan]}\n", "Clinical data saved to ../../output/preprocess/Adrenocortical_Cancer/clinical_data/GSE76019.csv\n", "Linking clinical and gene expression data...\n", "Clinical data has 1 samples\n", "Gene data has 34 samples\n", "Found 0 common samples\n", "No common samples between clinical and gene data. Cannot proceed with analysis.\n", "Abnormality detected in the cohort: GSE76019. Preprocessing failed.\n", "Dataset is not usable for trait-gene association studies.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"Normalizing gene symbols...\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization: {normalized_gene_data.shape} genes\")\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", "\n", "# Re-examine the clinical data\n", "print(\"Examining clinical data structure:\")\n", "print(clinical_data.head())\n", "\n", "# Re-extract clinical data with proper handling\n", "print(\"Re-extracting clinical data with correct parameters...\")\n", "# Create a proper clinical dataframe with sample IDs and stages\n", "sample_ids = [col for col in clinical_data.columns if col != '!Sample_geo_accession']\n", "stages_row = clinical_data.iloc[trait_row]\n", "\n", "# Create a series from the stages row that we can translate\n", "stage_series = pd.Series(index=sample_ids)\n", "for sample_id in sample_ids:\n", " value = stages_row[sample_id]\n", " if isinstance(value, str) and 'Stage:' in value:\n", " # Extract the stage from the string (e.g., \"Stage: III\" becomes \"III\")\n", " stage = value.split(':')[1].strip()\n", " # Convert Roman numerals to integers\n", " if stage == 'I':\n", " stage_series[sample_id] = 1\n", " elif stage == 'II':\n", " stage_series[sample_id] = 2\n", " elif stage == 'III':\n", " stage_series[sample_id] = 3\n", " elif stage == 'IV':\n", " stage_series[sample_id] = 4\n", "\n", "# Create proper clinical dataframe with the stage column\n", "clinical_df = pd.DataFrame({trait: stage_series})\n", "print(\"Clinical data preview:\")\n", "print(preview_df(clinical_df))\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "is_gene_available = normalized_gene_data.shape[0] > 0\n", "is_trait_available = not clinical_df.empty and not clinical_df[trait].isna().all()\n", "\n", "if is_gene_available and is_trait_available:\n", " print(\"Linking clinical and gene expression data...\")\n", " # Transpose both datasets to align samples\n", " clinical_df_t = clinical_df.T\n", " normalized_gene_data_t = normalized_gene_data.T\n", " \n", " # Check if sample IDs align\n", " print(f\"Clinical data has {clinical_df_t.shape[0]} samples\")\n", " print(f\"Gene data has {normalized_gene_data_t.shape[0]} samples\")\n", " \n", " # Keep only the common samples\n", " common_samples = clinical_df_t.index.intersection(normalized_gene_data_t.index)\n", " print(f\"Found {len(common_samples)} common samples\")\n", " \n", " if len(common_samples) > 0:\n", " # Filter both datasets to include only common samples\n", " clinical_df_filtered = clinical_df_t.loc[common_samples]\n", " normalized_gene_data_filtered = normalized_gene_data_t.loc[common_samples]\n", " \n", " # Combine the datasets\n", " linked_data = pd.concat([clinical_df_filtered, normalized_gene_data_filtered], axis=1)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # 3. Handle missing values\n", " if linked_data.shape[0] > 0:\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, linked data shape: {linked_data.shape}\")\n", " \n", " # 4. Check for bias in features\n", " if linked_data.shape[0] > 0:\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Is trait biased: {is_biased}\")\n", " else:\n", " is_biased = True\n", " print(\"No samples left after handling missing values. Dataset is biased.\")\n", " else:\n", " is_biased = True\n", " print(\"No samples in linked data. Cannot proceed with analysis.\")\n", " else:\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " print(\"No common samples between clinical and gene data. Cannot proceed with analysis.\")\n", "else:\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " if not is_gene_available:\n", " print(\"Gene expression data not available.\")\n", " if not is_trait_available:\n", " print(\"Trait data not available.\")\n", "\n", "# 5. Conduct final quality validation and save cohort information\n", "note = \"Dataset contains adrenocortical tumor samples with stage information. \"\n", "if not is_gene_available or not is_trait_available or linked_data.shape[0] <= 0:\n", " note += \"Processing resulted in insufficient data for meaningful analysis.\"\n", " \n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 6. If the linked data is usable, save it\n", "if is_usable and linked_data.shape[0] > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset is not usable for trait-gene association studies.\")" ] } ], "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 }