{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "31520d73", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:10:21.537573Z", "iopub.status.busy": "2025-03-25T05:10:21.537350Z", "iopub.status.idle": "2025-03-25T05:10:21.704439Z", "shell.execute_reply": "2025-03-25T05:10:21.704009Z" } }, "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 = \"GSE74571\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Epilepsy\"\n", "in_cohort_dir = \"../../input/GEO/Epilepsy/GSE74571\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Epilepsy/GSE74571.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Epilepsy/gene_data/GSE74571.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Epilepsy/clinical_data/GSE74571.csv\"\n", "json_path = \"../../output/preprocess/Epilepsy/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "5b8f82c6", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "65d3f681", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:10:21.705727Z", "iopub.status.busy": "2025-03-25T05:10:21.705584Z", "iopub.status.idle": "2025-03-25T05:10:21.882091Z", "shell.execute_reply": "2025-03-25T05:10:21.881687Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Serum Conditions Do Not Abolish The Tumorigenicity of Glioma Stem Cells\"\n", "!Series_summary\t\"The subset of GBM patient samples gives rise to adherent cultures even in sphere culture conditions. Most samples in this subset are tumorigenic and exhibit a hybrid expression profile when tested with the marker panel. Cultures from these samples have a predominantly mesenchymal character based on substrate adherence, morphology, differentiation potential and gene expression.\"\n", "!Series_overall_design\t\"Total RNA isolated from glioblastoma stem cells (GSC) cultured as spheres was compared to that from adherent GSCs cultured in sphere culture conditions that exhibited both GSC and mesenchymal properties.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell/tissue type: GBM cell culture in 10% serum; mixture of cells from adherent and sphere cultured', 'cell/tissue type: GBM cell culture in 1% serum; mixture of cells from adherent and sphere cultured', 'cell/tissue type: GBM adherent cell culture in 1% serum', 'cell/tissue type: GBM adherent cell culture in 10% serum', 'cell/tissue type: fresh GBM tissue', 'cell/tissue type: fresh Normal human brain tissue', 'cell/tissue type: Bone marrow mesenchymal stem cells', 'cell/tissue type: adult human brain cell culture in 1% serum', 'cell/tissue type: Adipose tissue mesenchymal stem cells', 'cell/tissue type: GBM sphere cultures'], 1: ['culture type: adherent in 10% FBS', 'culture type: adherent in 1% FBS+TGF-a', 'culture type: adherent 1% FBS+TGF-a', 'culture type: adherent 10% FBS', nan, 'culture type: bone marrow-MSC', 'culture type: control normal in 1% FBS+TGF-a', 'culture type: adipose tissue-MSC', 'culture type: Grown as spheres']}\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": "b2898a6e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "654be5e4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:10:21.883304Z", "iopub.status.busy": "2025-03-25T05:10:21.883192Z", "iopub.status.idle": "2025-03-25T05:10:21.889962Z", "shell.execute_reply": "2025-03-25T05:10:21.889603Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this appears to be gene expression data from GBM cells\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Looking at the sample characteristics dictionary\n", "# For trait (Epilepsy): This dataset is about GBM (glioblastoma), not epilepsy\n", "trait_row = None # No Epilepsy data available\n", "\n", "# For age: No age information in the sample characteristics\n", "age_row = None\n", "\n", "# For gender: No gender information in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " # Not needed since trait_row is None, but defining for completeness\n", " if pd.isna(value):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " # For epilepsy, we would return 1 for epilepsy patients and 0 for controls\n", " # But this dataset doesn't have epilepsy data\n", " return None\n", "\n", "def convert_age(value):\n", " # Not needed since age_row is None, but defining for completeness\n", " if pd.isna(value):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " # Not needed since gender_row is None, but defining for completeness\n", " if pd.isna(value):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'female' in value or 'f' == value:\n", " return 0\n", " elif 'male' in value or 'm' == value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial cohort info\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 skip this substep\n" ] }, { "cell_type": "markdown", "id": "d7e30f76", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "1b54b0d4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:10:21.891012Z", "iopub.status.busy": "2025-03-25T05:10:21.890900Z", "iopub.status.idle": "2025-03-25T05:10:22.167362Z", "shell.execute_reply": "2025-03-25T05:10:22.166813Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Epilepsy/GSE74571/GSE74571_family.soft.gz\n", "Matrix file: ../../input/GEO/Epilepsy/GSE74571/GSE74571_series_matrix.txt.gz\n", "Found the matrix table marker in the file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (47322, 36)\n", "First 20 gene/probe identifiers:\n", "['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262']\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": "751fb0e6", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "053510dc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:10:22.168920Z", "iopub.status.busy": "2025-03-25T05:10:22.168807Z", "iopub.status.idle": "2025-03-25T05:10:22.170846Z", "shell.execute_reply": "2025-03-25T05:10:22.170473Z" } }, "outputs": [], "source": [ "# The gene identifiers start with \"ILMN_\" which are Illumina probe IDs, not human gene symbols\n", "# These are microarray probe identifiers from Illumina platform that need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "ceb86706", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "57e8f6d5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:10:22.172201Z", "iopub.status.busy": "2025-03-25T05:10:22.172098Z", "iopub.status.idle": "2025-03-25T05:10:26.512376Z", "shell.execute_reply": "2025-03-25T05:10:26.511978Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n", "\n", "Complete sample of a few rows:\n", " ID Species Source Search_Key\n", "0 ILMN_1343048 NaN NaN NaN\n", "1 ILMN_1343049 NaN NaN NaN\n", "2 ILMN_1343050 NaN NaN NaN\n", "\n", "Checking for gene information in Symbol column:\n", "Sample Symbol values: ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']\n", "\n", "Sample of probe ID to gene symbol mappings:\n", " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "5 ILMN_1343061 phage_lambda_genome:mm2\n", "6 ILMN_1343062 phage_lambda_genome:mm2\n", "7 ILMN_1343063 phage_lambda_genome:mm2\n", "8 ILMN_1343064 phage_lambda_genome:mm2\n", "9 ILMN_1343291 EEF1A1\n", "\n", "Total number of probe-to-gene mappings: 44837\n", "Number of unique gene symbols: 31432\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", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Get a more complete view to understand the annotation structure\n", "print(\"\\nComplete sample of a few rows:\")\n", "print(gene_annotation.iloc[:3, :4].to_string()) # Show only first few columns for readability\n", "\n", "# Examine the Symbol column which contains gene information\n", "print(\"\\nChecking for gene information in Symbol column:\")\n", "if 'Symbol' in gene_annotation.columns:\n", " sample_symbols = gene_annotation['Symbol'].head(5).tolist()\n", " print(f\"Sample Symbol values: {sample_symbols}\")\n", " \n", " # Use the library function to create the mapping\n", " mapping_data = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", " \n", " # Print sample of the mapping to confirm\n", " print(\"\\nSample of probe ID to gene symbol mappings:\")\n", " print(mapping_data.head(10))\n", " \n", " # Check the size of the mapping data\n", " print(f\"\\nTotal number of probe-to-gene mappings: {len(mapping_data)}\")\n", " \n", " # Check how many unique gene symbols we have\n", " unique_genes = mapping_data['Gene'].nunique()\n", " print(f\"Number of unique gene symbols: {unique_genes}\")\n", "else:\n", " print(\"\\nError: Could not find 'Symbol' column in the annotation data\")\n" ] }, { "cell_type": "markdown", "id": "6523b622", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "b7e3405b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:10:26.513668Z", "iopub.status.busy": "2025-03-25T05:10:26.513554Z", "iopub.status.idle": "2025-03-25T05:10:31.248212Z", "shell.execute_reply": "2025-03-25T05:10:31.247679Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created mapping from 44837 probes to gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Extracted gene expression data with shape: (47322, 36)\n", "Converted to gene expression data with shape: (21463, 36)\n", "\n", "Preview of gene expression data:\n", " GSM1923163 GSM1923164 GSM1923165 GSM1923166 GSM1923167 GSM1923168 \\\n", "Gene \n", "A1BG 156.612642 158.683792 141.065065 166.539842 147.699142 148.292042 \n", "A1CF 199.563955 202.111744 204.275435 189.724489 197.069696 205.367373 \n", "A26C3 200.364543 187.318372 195.010751 199.535568 196.223365 207.529118 \n", "\n", " GSM1923169 GSM1923170 GSM1923171 GSM1923172 ... GSM1923189 \\\n", "Gene ... \n", "A1BG 140.293936 148.664011 142.755005 171.070572 ... 142.289219 \n", "A1CF 199.349222 195.814469 186.430527 199.087704 ... 205.696066 \n", "A26C3 201.087326 198.236513 195.836060 198.248079 ... 192.199217 \n", "\n", " GSM1923190 GSM1923191 GSM1923192 GSM1923193 GSM1923194 GSM1923195 \\\n", "Gene \n", "A1BG 148.592491 150.963319 151.790128 163.260151 141.078393 139.353620 \n", "A1CF 195.456171 185.191283 190.508907 194.998976 202.166058 192.298238 \n", "A26C3 187.475647 191.034708 196.974782 196.220411 202.108519 196.091496 \n", "\n", " GSM1923196 GSM1923197 GSM1923198 \n", "Gene \n", "A1BG 158.225050 153.791561 151.815746 \n", "A1CF 212.517849 191.096558 194.987968 \n", "A26C3 194.420515 198.483571 198.829891 \n", "\n", "[3 rows x 36 columns]\n" ] } ], "source": [ "# 1. Soft file and matrix file have already been identified in previous steps\n", "# Extract gene annotation data from SOFT file for mapping\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Get the gene mapping dataframe using the appropriate columns from gene annotation\n", "# ID column contains probe identifiers matching those in gene expression data\n", "# Symbol column contains the gene symbols\n", "mapping_data = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", "print(f\"Created mapping from {len(mapping_data)} probes to gene symbols\")\n", "\n", "# 3. Extract gene expression data from matrix file\n", "gene_expression_data = get_genetic_data(matrix_file)\n", "print(f\"Extracted gene expression data with shape: {gene_expression_data.shape}\")\n", "\n", "# Apply the gene mapping to convert probe-level to gene-level expression\n", "gene_data = apply_gene_mapping(gene_expression_data, mapping_data)\n", "print(f\"Converted to gene expression data with shape: {gene_data.shape}\")\n", "\n", "# Preview the resulting gene expression data\n", "print(\"\\nPreview of gene expression data:\")\n", "print(gene_data.head(3))\n" ] }, { "cell_type": "markdown", "id": "de9b3700", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "7847310b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:10:31.249801Z", "iopub.status.busy": "2025-03-25T05:10:31.249680Z", "iopub.status.idle": "2025-03-25T05:10:31.943367Z", "shell.execute_reply": "2025-03-25T05:10:31.942723Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (21463, 36)\n", "Gene data shape after normalization: (20259, 36)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Epilepsy/gene_data/GSE74571.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: GSE74571. 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 }