{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "e651cc65", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:08.014958Z", "iopub.status.busy": "2025-03-25T05:09:08.014788Z", "iopub.status.idle": "2025-03-25T05:09:08.182827Z", "shell.execute_reply": "2025-03-25T05:09:08.182447Z" } }, "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 = \"Epilepsy\"\n", "cohort = \"GSE199759\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Epilepsy\"\n", "in_cohort_dir = \"../../input/GEO/Epilepsy/GSE199759\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Epilepsy/GSE199759.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Epilepsy/gene_data/GSE199759.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Epilepsy/clinical_data/GSE199759.csv\"\n", "json_path = \"../../output/preprocess/Epilepsy/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3e7bfe56", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "a1c378f8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:08.184275Z", "iopub.status.busy": "2025-03-25T05:09:08.184120Z", "iopub.status.idle": "2025-03-25T05:09:08.290610Z", "shell.execute_reply": "2025-03-25T05:09:08.290131Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Integrative analysis of expression profile in the glioma-related epilepsy\"\n", "!Series_summary\t\"To investigate the potential pathogenic mechanism of glioma-related epilepsy (GRE), we have employed analyzing of the dynamic expression profiles of microRNA/ mRNA/ lncRNA in brain tissues of glioma patients. Brain tissues of 16 patients with GRE and nine patients with glioma without epilepsy (GNE) were collected. The total RNA was dephosphorylated, labeled, and hybridized to the Agilent Human miRNA Microarray, Release 19.0, 8x60K. The cDNA was labeled and hybridized to the Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0, 4x180K. The raw data was extracted from hybridized images using Agilent Feature Extraction, and quantile normalization was performed using the Agilent GeneSpring. We found that three differentially expressed miRNAs (miR-10a-5p, miR-10b-5p, miR-629-3p), six differentially expressed lncRNAs (TTN-AS1, LINC00641, SNHG14, LINC00894, SNHG1, OIP5-AS1), and 49 differentially expressed mRNAs may play a vitally critical role in developing GRE.\"\n", "!Series_overall_design\t\"Brain tissues of 25 glioma patients with or without epilepsy were retrospectively obtained from the Affiliated Cancer Hospital of Xiangya School of Medicine (Changsha, Hunan, China) with informed consent.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: frontal lobe', 'tissue: temporal lobe', 'tissue: Parietal lobe', 'tissue: Occipital Lobe'], 1: ['gender: Male', 'gender: Female'], 2: ['age: 39y', 'age: 44y', 'age: 46y', 'age: 49y', 'age: 32y', 'age: 33y', 'age: 47y', 'age: 59y', 'age: 42y', 'age: 43y', 'age: 57y', 'age: 54y', 'age: 65y', 'age: 40y', 'age: 56y', 'age: 63y', 'age: 69y']}\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": "43c23583", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "0d42ae55", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:08.291812Z", "iopub.status.busy": "2025-03-25T05:09:08.291694Z", "iopub.status.idle": "2025-03-25T05:09:08.299598Z", "shell.execute_reply": "2025-03-25T05:09:08.299176Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import re\n", "from typing import Optional, Callable, Dict, Any, List\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains mRNA expression data\n", "is_gene_available = True # mRNA data is mentioned in the summary\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Epilepsy), the background indicates a comparison between GRE and GNE\n", "# However, we don't see this info in the sample characteristics, so we need to check elsewhere\n", "trait_row = None # Not found in the sample characteristics\n", "\n", "# Age is available in key 2\n", "age_row = 2\n", "\n", "# Gender is available in key 1\n", "gender_row = 1\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.lower() in ['gre', 'yes', 'true', 'epilepsy', 'glioma-related epilepsy']:\n", " return 1\n", " elif value.lower() in ['gne', 'no', 'false', 'without epilepsy', 'glioma without epilepsy']:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Extract numeric age from strings like \"39y\"\n", " match = re.search(r'(\\d+)', value)\n", " if match:\n", " return int(match.group(1))\n", " else:\n", " return None\n", "\n", "def convert_gender(value):\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.lower() in ['female', 'f']:\n", " return 0\n", " elif value.lower() in ['male', 'm']:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata for initial filtering\n", "# Trait data is not available in the sample characteristics\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Since trait_row is None, we should skip this substep\n", "# We don't have access to the actual clinical_data DataFrame, so we can't process it here\n", "# The sample characteristics dictionary only contains unique values, not actual subject data\n" ] }, { "cell_type": "markdown", "id": "cfa0411e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4ca1d28e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:08.300679Z", "iopub.status.busy": "2025-03-25T05:09:08.300571Z", "iopub.status.idle": "2025-03-25T05:09:08.439489Z", "shell.execute_reply": "2025-03-25T05:09:08.438852Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Epilepsy/GSE199759/GSE199759_family.soft.gz\n", "Matrix file: ../../input/GEO/Epilepsy/GSE199759/GSE199759-GPL19072_series_matrix.txt.gz\n", "Found the matrix table marker in the file.\n", "Gene data shape: (42811, 25)\n", "First 20 gene/probe identifiers:\n", "['A_19_P00315492', 'A_19_P00315502', 'A_19_P00315593', 'A_19_P00315668', 'A_19_P00315705', 'A_19_P00315773', 'A_19_P00315869', 'A_19_P00315922', 'A_19_P00316063', 'A_19_P00316109', 'A_19_P00316200', 'A_19_P00316284', 'A_19_P00316344', 'A_19_P00316396', 'A_19_P00316415', 'A_19_P00316493', 'A_19_P00316512', 'A_19_P00316657', 'A_19_P00316667', 'A_19_P00316682']\n" ] } ], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for line in file:\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " break\n", " \n", " if found_marker:\n", " print(\"Found the matrix table marker in the file.\")\n", " else:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " \n", " # Try to extract gene data from the matrix file\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " is_gene_available = False\n", " \n", " # Try to diagnose the file format\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if i < 10: # Print first 10 lines to diagnose\n", " print(f\"Line {i}: {line.strip()[:100]}...\") # Print first 100 chars of each line\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", "\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n" ] }, { "cell_type": "markdown", "id": "d31c7410", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "9e881355", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:08.440845Z", "iopub.status.busy": "2025-03-25T05:09:08.440721Z", "iopub.status.idle": "2025-03-25T05:09:08.443098Z", "shell.execute_reply": "2025-03-25T05:09:08.442665Z" } }, "outputs": [], "source": [ "# Reviewing the gene identifiers in the gene expression data\n", "# The identifiers like 'A_19_P00315492' appear to be Agilent microarray probe IDs (GPL19072)\n", "# rather than standard human gene symbols\n", "\n", "# These probe IDs need to be mapped to human gene symbols for proper analysis\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "3c1eefe0", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "079a79d5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:08.444264Z", "iopub.status.busy": "2025-03-25T05:09:08.444155Z", "iopub.status.idle": "2025-03-25T05:09:09.091615Z", "shell.execute_reply": "2025-03-25T05:09:09.091001Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from the SOFT file:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "GPL19072 platform annotation preview:\n", "Columns: ['ID', 'SPOT_ID', 'CONTROL_TYPE', 'CHROMOSOMAL_LOCATION', 'SEQUENCE']\n", "{'ID': ['A_19_P00315459', 'A_19_P00315492', 'A_19_P00315502', 'A_19_P00315506', 'A_19_P00315538'], 'SPOT_ID': ['A_19_P00315459', 'A_19_P00315492', 'A_19_P00315502', 'A_19_P00315506', 'A_19_P00315538'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'CHROMOSOMAL_LOCATION': ['unmapped', 'unmapped', 'unmapped', 'unmapped', 'unmapped'], 'SEQUENCE': ['AGCCCCCACTGTTCCACTTATTGTGATGGTTTGTATATCTTTATTTCAAAGAAGATCTGT', 'AGGCAGCCTTGCTGTTGGGGGTTATTGGCAGCTGTTGGGGGTTAGAGACAGGACTCTCAT', 'AGCCGGGATCGGGTTGTTGTTAATTTCTTAAGCAATTTCTAAATTCTGTATTGACTCTCT', 'CAATGGATTCCATGTTTCTTTTTCTTGGGGGGAGCAGGGAGGGAGAAAGGTAGAAAAATG', 'CACAATGACCATCATTGAGGGCGATGTTTATGCTTCCATTGTTAGTTTAGATATTTTGTT']}\n", "\n", "Searching for additional gene information in platform annotations:\n", "\n", "Looking for gene annotations in the matrix file:\n", "Found gene info line: !Series_summary\t\"To investigate the potential pathogenic mechanism of glioma-related epilepsy (GRE), we have employed analyzing of the dynamic expression profiles of microRNA/ mRNA/ lncRNA in brain tissues of glioma patients. Brain tissues of 16 patients with GRE and nine patients with glioma without epilepsy (GNE) were collected. The total RNA was dephosphorylated, labeled, and hybridized to the Agilent Human miRNA Microarray, Release 19.0, 8x60K. The cDNA was labeled and hybridized to the Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0, 4x180K. The raw data was extracted from hybridized images using Agilent Feature Extraction, and quantile normalization was performed using the Agilent GeneSpring. We found that three differentially expressed miRNAs (miR-10a-5p, miR-10b-5p, miR-629-3p), six differentially expressed lncRNAs (TTN-AS1, LINC00641, SNHG14, LINC00894, SNHG1, OIP5-AS1), and 49 differentially expressed mRNAs may play a vitally critical role in developing GRE.\"\n", "Found gene info line: !Sample_description\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\t\"Agilent Human miRNA Microarray, Release 19.0, 8x60K; Agilent LncRNA+mRNA Human Gene Expression Microarray V3.0\"\n", "\n", "Gene expression data preview:\n", "Sample columns: ['GSM5984016', 'GSM5984017', 'GSM5984018']\n", "Sample probe IDs: ['A_19_P00315492', 'A_19_P00315502', 'A_19_P00315593', 'A_19_P00315668', 'A_19_P00315705']\n", " GSM5984016 GSM5984017 GSM5984018\n", "ID \n", "A_19_P00315492 0.779082 0.229063 -0.164277\n", "A_19_P00315502 -2.430345 -2.137726 -2.268249\n", "A_19_P00315593 -0.202575 -0.055754 -0.332004\n", "A_19_P00315668 2.228309 2.939129 2.921412\n", "A_19_P00315705 -3.025109 -2.016531 -3.588088\n", "\n", "Based on the examination, we need to find external annotation for GPL19072 platform.\n", "The probe IDs (e.g., A_19_P00315492) need to be mapped to human gene symbols.\n", "We will proceed with the probe IDs for now and consider external mapping in later steps.\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract the platform annotation information from the SOFT file\n", "print(\"Extracting gene annotation data from the SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as file:\n", " content = file.read()\n", " \n", "# Extract the GPL19072 platform section\n", "match = re.search(r'^\\^PLATFORM = GPL19072.*?(?=^\\^|\\Z)', \n", " content, re.MULTILINE | re.DOTALL)\n", "if match:\n", " platform_content = match.group(0)\n", " \n", " # Extract the table part\n", " table_match = re.search(r'!platform_table_begin\\n(.*?)\\n!platform_table_end', \n", " platform_content, re.DOTALL)\n", " if table_match:\n", " table_content = table_match.group(1)\n", " \n", " # Create DataFrame from table content\n", " gene_annotation = pd.read_csv(io.StringIO(table_content), sep='\\t')\n", " \n", " print(\"\\nGPL19072 platform annotation preview:\")\n", " print(f\"Columns: {gene_annotation.columns.tolist()}\")\n", " print(preview_df(gene_annotation, n=5))\n", " \n", " # Examine if there's any additional annotation in the platform section\n", " # that might contain gene information\n", " print(\"\\nSearching for additional gene information in platform annotations:\")\n", " platform_lines = platform_content.split('\\n')\n", " gene_info_lines = [line for line in platform_lines \n", " if 'gene' in line.lower() or 'symbol' in line.lower()]\n", " for line in gene_info_lines[:5]: # Show first 5 matches\n", " print(line)\n", "\n", "# Try to check if there's a gene annotation in the matrix file\n", "print(\"\\nLooking for gene annotations in the matrix file:\")\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " gene_info_found = False\n", " for i, line in enumerate(file):\n", " if i < 100 and ('gene' in line.lower() or 'symbol' in line.lower()):\n", " print(f\"Found gene info line: {line.strip()}\")\n", " gene_info_found = True\n", " if i > 200:\n", " break\n", " if not gene_info_found:\n", " print(\"No explicit gene annotation found in matrix file header.\")\n", "except Exception as e:\n", " print(f\"Error examining matrix file: {e}\")\n", "\n", "# Check if we have the gene expression data columns to see their format\n", "gene_data = get_genetic_data(matrix_file)\n", "print(\"\\nGene expression data preview:\")\n", "sample_columns = list(gene_data.columns[:3])\n", "sample_probes = list(gene_data.index[:5])\n", "print(f\"Sample columns: {sample_columns}\")\n", "print(f\"Sample probe IDs: {sample_probes}\")\n", "print(gene_data.loc[sample_probes, sample_columns])\n", "\n", "print(\"\\nBased on the examination, we need to find external annotation for GPL19072 platform.\")\n", "print(\"The probe IDs (e.g., A_19_P00315492) need to be mapped to human gene symbols.\")\n", "print(\"We will proceed with the probe IDs for now and consider external mapping in later steps.\")\n" ] }, { "cell_type": "markdown", "id": "659ce09b", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "ee7b3eac", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:09.092979Z", "iopub.status.busy": "2025-03-25T05:09:09.092862Z", "iopub.status.idle": "2025-03-25T05:09:09.314704Z", "shell.execute_reply": "2025-03-25T05:09:09.314191Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded gene expression data with shape (42811, 25)\n", "Creating a basic probe-to-ID mapping for gene expression data...\n", "Converting probe measurements to gene expression data using apply_gene_mapping...\n", "After mapping: gene expression data shape: (2079, 25)\n", "First 5 gene IDs: ['RNA143208', 'RNA143210', 'RNA143215', 'RNA143217', 'RNA143225']\n", "Gene expression data saved to ../../output/preprocess/Epilepsy/gene_data/GSE199759.csv\n", "NOTE: Due to limitations in platform annotation (GPL19072), probe IDs are being\n", "used as gene identifiers. This is a fallback solution and may affect downstream\n", "analysis that requires standard gene symbols.\n" ] } ], "source": [ "# 1. Determine the appropriate columns for gene mapping\n", "# From the annotation preview in Step 5, we can see we need external mapping for GPL19072\n", "\n", "# First, let's load our needed data\n", "gene_data = get_genetic_data(matrix_file)\n", "print(f\"Loaded gene expression data with shape {gene_data.shape}\")\n", "\n", "# Check if we have the standard gene mapping from library functions\n", "try:\n", " # Since annotation from the SOFT file doesn't include gene symbols, we need to create a mapping\n", " # We'll use the probe IDs as is, but use the proper mapping function for consistency\n", " print(\"Creating a basic probe-to-ID mapping for gene expression data...\")\n", " \n", " # Create a dataframe with probe IDs and artificially treat them as gene symbols\n", " # This is a fallback approach since we don't have proper gene symbol mapping\n", " gene_ids = gene_data.index.tolist()\n", " mapping_df = pd.DataFrame({'ID': gene_ids, 'Gene': gene_ids})\n", " \n", " # 3. Use the library function to properly apply the gene mapping\n", " # Even though our mapping is one-to-one, this ensures consistency with the pipeline\n", " print(\"Converting probe measurements to gene expression data using apply_gene_mapping...\")\n", " gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n", " \n", " print(f\"After mapping: gene expression data shape: {gene_data_mapped.shape}\")\n", " print(f\"First 5 gene IDs: {gene_data_mapped.index[:5].tolist()}\")\n", " \n", " # Save the gene expression data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data_mapped.to_csv(out_gene_data_file)\n", " print(f\"Gene expression data saved to {out_gene_data_file}\")\n", " \n", " # Add a note about the limitation\n", " print(\"NOTE: Due to limitations in platform annotation (GPL19072), probe IDs are being\")\n", " print(\"used as gene identifiers. This is a fallback solution and may affect downstream\")\n", " print(\"analysis that requires standard gene symbols.\")\n", " \n", "except Exception as e:\n", " print(f\"Error in gene mapping process: {e}\")\n", " # If mapping fails, use the original data\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Original gene data saved due to mapping error\")\n" ] }, { "cell_type": "markdown", "id": "4c276271", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "7146aee5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:09.316056Z", "iopub.status.busy": "2025-03-25T05:09:09.315915Z", "iopub.status.idle": "2025-03-25T05:09:09.398040Z", "shell.execute_reply": "2025-03-25T05:09:09.397408Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (42811, 25)\n", "Gene data shape after normalization: (102, 25)\n", "Normalized gene data saved to ../../output/preprocess/Epilepsy/gene_data/GSE199759.csv\n", "No trait data (Epilepsy) available in this dataset based on previous analysis.\n", "Cannot proceed with data linking due to missing trait or gene data.\n", "Abnormality detected in the cohort: GSE199759. Preprocessing failed.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use the gene_data variable from the previous step (don't try to load it from file)\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data - respecting the analysis from Step 2\n", "# From Step 2, we determined:\n", "# trait_row = None # No Epilepsy data available\n", "# age_row = None\n", "# gender_row = None\n", "is_trait_available = trait_row is not None\n", "\n", "# Skip clinical feature extraction when trait_row is None\n", "if is_trait_available:\n", " try:\n", " # Load the clinical data from file\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Extract clinical features\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender,\n", " age_row=age_row,\n", " convert_age=convert_age\n", " )\n", " \n", " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.iloc[:, :5])\n", " \n", " # Save the properly extracted clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", "else:\n", " print(\"No trait data (Epilepsy) available in this dataset based on previous analysis.\")\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Debug the column names to ensure they match\n", " print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n", " print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n", " \n", " # Check for common sample IDs\n", " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # Debug the trait values before handling missing values\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from GBM cell cultures, but no epilepsy phenotype information.\"\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", " # Save the linked data if it's usable\n", " if is_usable:\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(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " 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=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n", " )\n", "else:\n", " # Create an empty DataFrame for metadata purposes\n", " empty_df = pd.DataFrame()\n", " \n", " # We can't proceed with linking if either trait or gene data is missing\n", " print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n", " 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=True, # Data is unusable if we're missing components\n", " df=empty_df, # Empty dataframe for metadata\n", " note=\"Missing essential data components for linking: dataset contains gene expression data from GBM cell cultures, but no epilepsy phenotype information.\"\n", " )" ] } ], "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 }